[
  {
    "path": ".devcontainer/devcontainer.json",
    "content": "{\n    \"name\": \"Swift Nightly Main\",\n    \"dockerComposeFile\": \"docker-compose.yaml\",\n    \"service\": \"devcontainer\",\n    \"workspaceFolder\": \"${localWorkspaceFolder}\",\n    \"features\": {\n        \"ghcr.io/devcontainers/features/common-utils:2\": {\n            \"installZsh\": \"false\",\n            \"username\": \"root\",\n            \"upgradePackages\": \"false\"\n        },\n        \"ghcr.io/devcontainers/features/git:1\": {\n            \"version\": \"os-provided\",\n            \"ppa\": \"false\"\n        }\n    },\n    \"initializeCommand\": \".devcontainer/init.sh\",\n    \"postCreateCommand\": \"apt-get update && apt-get install -y curl sqlite3 libsqlite3-dev libncurses5-dev python3 build-essential\",\n    \"postStartCommand\": \"cd ${WORKSPACE_DIR}\",\n    \"customizations\": {\n        \"vscode\": {\n            \"settings\": {\n                \"lldb.library\": \"/usr/lib/liblldb.so\"\n            },\n            \"extensions\": [\n                \"swiftlang.swift-vscode\"\n            ]\n        }\n    },\n    // Use 'forwardPorts' to make a list of ports inside the container available locally.\n    // \"forwardPorts\": [],\n    \"remoteUser\": \"root\"\n}\n"
  },
  {
    "path": ".devcontainer/docker-compose.yaml",
    "content": "services:\n  devcontainer:\n    # Use your desired image or Dockerfile here\n    image: \"swiftlang/swift:nightly-main\"\n    env_file:\n      - .env\n    cap_add:\n      - SYS_PTRACE\n    security_opt:\n      - seccomp=unconfined\n    volumes:\n      # Mount the main git repo dir and the current worktree dir at the same absolute path as the host\n      - ${GIT_REPO}:${GIT_REPO}:rw\n      - ${WORKSPACE_DIR}:${WORKSPACE_DIR}:rw\n    command: sleep infinity\n"
  },
  {
    "path": ".devcontainer/init.sh",
    "content": "#!/bin/bash\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2022 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\n# Calculates absolute paths for the git repo root and current workspace\n\nSCRIPT_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\n\nGIT_COMMON_DIR=$(git rev-parse --git-common-dir)\ncase \"$GIT_COMMON_DIR\" in\n  /*) ;;\n  *) GIT_COMMON_DIR=\"$PWD/$GIT_COMMON_DIR\" ;;\nesac\n\nenv_file=\"${SCRIPT_DIR}/.env\"\n# Ensure the paths are absolute for Docker mounting\necho \"GIT_REPO=$(realpath \"$GIT_COMMON_DIR\")\" > \"${env_file}\"\necho \"WORKSPACE_DIR=$(realpath \"$PWD\")\" >> \"${env_file}\"\n"
  },
  {
    "path": ".dir-locals.el",
    "content": ";;; Directory Local Variables            -*- no-byte-compile: t -*-\n;;; For more information see (info \"(emacs) Directory Variables\")\n\n((nil . ((c-basic-offset . 4)))\n (swift-mode . ((swift-mode:basic-offset . 4))))\n"
  },
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\nindent_size = 4\nindent_style = space\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nxcode_trim_whitespace_on_empty_lines = true\n\n[*.{yml,yaml}]\nindent_size = 2\n"
  },
  {
    "path": ".github/CODEOWNERS",
    "content": "# This file is a list of the people responsible for ensuring that patches for a\n# particular part of Swift are reviewed, either by themselves or by someone else.\n# They are also the gatekeepers for their part of Swift, with the final word on\n# what goes in or not.\n#\n# The list is sorted by surname and formatted to allow easy grepping and\n# beautification by scripts.  The fields are: name (N), email (E), web-address\n# (W), PGP key ID and fingerprint (P), description (D), and snail-mail address\n# (S).\n\n# N: Tomer Doron\n# E: tomer@apple.com\n# D: Package Manager\n\n# N: Max Desiatov\n# E: m_desiatov@apple.com\n# D: Package Manager\n\n# N: Ben Barham\n# E: ben_barham@apple.com\n# D: Package Manager\n\n###\n\n# The following lines are used by GitHub to automatically recommend reviewers.\n\n* @jakepetroules @dschaefer2 @bripeticca @plemarquand @owenv @bkhouri @cmcgee1024 @daveyc123 @rconnell9 @daveinglis\n\nSources/Commands/PackageCommands/Migrate.swift @AnthonyLatsis @xedin @jakepetroules @dschaefer2 @bripeticca @plemarquand @owenv @bkhouri @cmcgee1024 @daveyc123 @rconnell9 @daveinglis\nSources/SwiftFixIt/* @AnthonyLatsis @xedin @jakepetroules @dschaefer2 @bripeticca @plemarquand @owenv @bkhouri @cmcgee1024 @daveyc123 @rconnell9 @daveinglis\nTests/SwiftFixItTests/* @AnthonyLatsis @xedin @jakepetroules @dschaefer2 @bripeticca @plemarquand @owenv @bkhouri @cmcgee1024 @daveyc123 @rconnell9 @daveinglis\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/BUG_REPORT.yml",
    "content": "name: Bug Report\ndescription: Something isn't working as expected\nlabels: [bug]\nbody:\n  - type: checkboxes\n    id: cat-preferences\n    attributes:\n      label: >-\n        Is it reproducible with SwiftPM command-line tools: `swift build`,\n        `swift test`, `swift package` etc?\n      description: >-\n        Issues related to closed-source software are not tracked by this\n        repository and will be closed. For Xcode and `xcodebuild`, please\n        file a feedback at https://feedbackassistant.apple.com instead.\"\n      options:\n        - label: >-\n            Confirmed reproduction steps with SwiftPM CLI. The description\n            text _must_ include reproduction steps with either of command-line\n            SwiftPM commands, `swift build`, `swift test`, `swift package` etc.\n          required: true\n  - type: textarea\n    attributes:\n      label: Description\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Expected behavior\n      description: What you expected to happen.\n    validations:\n      required: false\n  - type: textarea\n    attributes:\n      label: Actual behavior\n      description: What actually happened.\n    validations:\n      required: false\n  - type: textarea\n    attributes:\n      label: Steps to reproduce\n      placeholder: |\n        1. ...\n        2. ...\n    validations:\n      required: false\n  - type: input\n    attributes:\n      label: Swift Package Manager version/commit hash\n    validations:\n      required: false\n  - type: textarea\n    attributes:\n      label: Swift & OS version (output of `swift --version ; uname -a`)\n    validations:\n      required: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml",
    "content": "name: Feature Request\ndescription: A suggestion for a new feature\nlabels: [enhancement]\nbody:\n  - type: textarea\n    attributes:\n      label: Description\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Expected behavior\n      description: What you expected to happen.\n    validations:\n      required: false\n  - type: textarea\n    attributes:\n      label: Actual behavior\n      description: What actually happened.\n    validations:\n      required: false\n  - type: textarea\n    attributes:\n      label: Steps to reproduce\n      placeholder: |\n        1. ...\n        2. ...\n    validations:\n      required: false\n  - type: input\n    attributes:\n      label: Swift Package Manager version/commit hash\n    validations:\n      required: false\n  - type: textarea\n    attributes:\n      label: Swift & OS version (output of `swift --version && uname -a`)\n    validations:\n      required: false\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "_[One line description of your change]_\n\n### Motivation:\n\n_[Explain here the context, and why you're making that change. What is the problem you're trying to solve.]_\n\n### Modifications:\n\n_[Describe the modifications you've done.]_\n\n### Result:\n\n_[After your change, what will change.]_\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n"
  },
  {
    "path": ".github/scripts/prebuild.ps1",
    "content": "##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2025 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nparam (\n    [switch]$SkipAndroid,\n    [switch]$InstallCMake\n)\n\n# winget isn't easily made available in containers, so use chocolatey\nSet-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))\n\nif ($InstallCMake) {\n    choco install -y cmake --installargs 'ADD_CMAKE_TO_PATH=System' --apply-install-arguments-to-dependencies\n    choco install -y ninja\n\n    Import-Module $env:ChocolateyInstall\\helpers\\chocolateyProfile.psm1\n    refreshenv\n\n    # Let swiftc find the path to link.exe in the CMake smoke test\n    $env:Path += \";$(Split-Path -Path \"$(& \"${env:ProgramFiles(x86)}\\Microsoft Visual Studio\\Installer\\vswhere.exe\" \"-latest\" -products Microsoft.VisualStudio.Product.BuildTools -find VC\\Tools\\MSVC\\*\\bin\\HostX64\\x64\\link.exe)\" -Parent)\"\n}\n\nif (-not $SkipAndroid) {\n    choco install -y android-ndk\n\n    Import-Module $env:ChocolateyInstall\\helpers\\chocolateyProfile.psm1\n    refreshenv\n\n    # Work around a bug in the package causing the env var to be set incorrectly\n    $env:ANDROID_NDK_ROOT = $env:ANDROID_NDK_ROOT.replace('-windows.zip','')\n}\n"
  },
  {
    "path": ".github/scripts/prebuild.sh",
    "content": "#!/bin/bash\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2025 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nset -e\n\nif [[ $(uname) == Darwin ]] ; then\n    if [[ \"$INSTALL_CMAKE\" == \"1\" ]] ; then\n        mkdir -p \"$RUNNER_TOOL_CACHE\"\n        if ! command -v cmake >/dev/null 2>&1 ; then\n            curl -fsSLO https://github.com/Kitware/CMake/releases/download/v4.1.2/cmake-4.1.2-macos-universal.tar.gz\n            echo '3be85f5b999e327b1ac7d804cbc9acd767059e9f603c42ec2765f6ab68fbd367 cmake-4.1.2-macos-universal.tar.gz' > cmake-4.1.2-macos-universal.tar.gz.sha256\n            sha256sum -c cmake-4.1.2-macos-universal.tar.gz.sha256\n            tar -xf cmake-4.1.2-macos-universal.tar.gz\n            ln -s \"$PWD/cmake-4.1.2-macos-universal/CMake.app/Contents/bin/cmake\" \"$RUNNER_TOOL_CACHE/cmake\"\n        fi\n        if ! command -v ninja >/dev/null 2>&1 ; then\n            curl -fsSLO https://github.com/ninja-build/ninja/releases/download/v1.13.1/ninja-mac.zip\n            echo 'da7797794153629aca5570ef7c813342d0be214ba84632af886856e8f0063dd9 ninja-mac.zip' > ninja-mac.zip.sha256\n            sha256sum -c ninja-mac.zip.sha256\n            unzip ninja-mac.zip\n            rm -f ninja-mac.zip\n            mv ninja \"$RUNNER_TOOL_CACHE/ninja\"\n        fi\n    fi\nelif command -v apt-get >/dev/null 2>&1 ; then # bookworm, noble, jammy\n    export DEBIAN_FRONTEND=noninteractive\n\n    apt-get update -y\n\n    # Build dependencies\n    apt-get install -y libsqlite3-dev libncurses-dev\n\n    # Debug symbols\n    apt-get install -y libc6-dbg\n\n    if [[ \"$INSTALL_CMAKE\" == \"1\" ]] ; then\n        apt-get install -y cmake ninja-build\n    fi\n\n    # Android NDK\n    dpkg_architecture=\"$(dpkg --print-architecture)\"\n    if [[ \"$SKIP_ANDROID\" != \"1\" ]] && [[ \"$dpkg_architecture\" == amd64 ]] ; then\n        eval \"$(cat /etc/os-release)\"\n        case \"$VERSION_CODENAME\" in\n            bookworm|jammy)\n                : # Not available\n                ;;\n            noble)\n                apt-get install -y google-android-ndk-r26c-installer\n                ;;\n            *)\n                echo \"Unable to fetch Android NDK for unknown Linux distribution: $VERSION_CODENAME\" >&2\n                exit 1\n        esac\n    else\n        echo \"Skipping Android NDK installation on $dpkg_architecture\" >&2\n    fi\nelif command -v dnf >/dev/null 2>&1 ; then # rhel-ubi9\n    dnf update -y\n\n    # Build dependencies\n    dnf install -y sqlite-devel ncurses-devel\n\n    # Debug symbols\n    dnf debuginfo-install -y glibc\nelif command -v yum >/dev/null 2>&1 ; then # amazonlinux2\n    yum update -y\n\n    # Build dependencies\n    yum install -y sqlite-devel ncurses-devel\n\n    # Debug symbols\n    yum install -y yum-utils\n    debuginfo-install -y glibc\nfi\n"
  },
  {
    "path": ".github/workflows/automerge.yml",
    "content": "name: Create PR to merge main into release branch\n# In the first period after branching the release branch,\n# we typically want to include many changes from `main` in the release branch.\n# This workflow automatically creates a PR to merge the main into the release branch.\n# Later in the release cycle we should stop this practice to avoid landing risky changes by disabling this workflow.\n# To do so, disable the workflow as described in https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/disabling-and-enabling-a-workflow\npermissions:\n  contents: read\non:\n  workflow_dispatch:\njobs:\n  create_merge_pr:\n    name: Create PR to merge main into release branch\n    uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.8\n    with:\n      head_branch: main\n      base_branch: release/6.3\n    permissions:\n      contents: write\n      pull-requests: write\n    if: (github.event_name == 'schedule' && github.repository == 'swiftlang/swift-package-manager') || (github.event_name != 'schedule')  # Ensure that we don't run this on a schedule in a fork\n"
  },
  {
    "path": ".github/workflows/pull_request.yml",
    "content": "name: Pull request\n\npermissions:\n  contents: read\n\non:\n  pull_request:\n    types: [opened, reopened, synchronize]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\njobs:\n  build:\n    needs: [soundness]\n    strategy:\n      fail-fast: false\n      matrix:\n        executableTargetBuildSystem: [\"native\"]\n        buildSystem: [\"native\", \"swiftbuild\"]\n        linuxSwiftVersion: ['[\"nightly-main\", \"nightly-6.2\"]', '[\"nightly-main\"]']\n        exclude:\n          - buildSystem: \"swiftbuild\"\n            linuxSwiftVersion: '[\"nightly-main\", \"nightly-6.2\"]'\n          - buildSystem: \"native\"\n            linuxSwiftVersion: '[\"nightly-main\"]'\n    name: Build (${{ matrix.buildSystem }}) (exectable target built using ${{ matrix.executableTargetBuildSystem }})\n    uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.8\n    with:\n      linux_os_versions: '[\"amazonlinux2\", \"bookworm\", \"noble\", \"jammy\", \"rhel-ubi9\"]'\n      linux_swift_versions: ${{ matrix.linuxSwiftVersion }}\n      linux_pre_build_command: ./.github/scripts/prebuild.sh\n      linux_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem}}'\n      # linux_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem}} && swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-test --parallel --build-system ${{ matrix.buildSystem}}'\n      windows_build_timeout: 180\n      windows_swift_versions: '[\"nightly-main\"]'\n      windows_pre_build_command: 'Invoke-Program .\\.github\\scripts\\prebuild.ps1'\n      windows_build_command: 'Invoke-Program swift run -Xlinker /ignore:4217 --configuration release --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests -Xlinker /ignore:4217 --build-system ${{ matrix.buildSystem}}'\n      # windows_build_command: 'Invoke-Program swift run -Xlinker /ignore:4217 --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests -Xlinker /ignore:4217 --build-system ${{ matrix.buildSystem}}; Invoke-Program swift run --build-system ${{ matrix.executableTargetBuildSystem }} -Xlinker /ignore:4217 swift-test -Xlinker /ignore:4217 --parallel --build-system ${{ matrix.buildSystem}}'\n      enable_windows_checks: true\n      enable_ios_checks: false\n      enable_macos_checks: true\n      macos_exclude_xcode_versions: \"[{\\\"xcode_version\\\": \\\"16.3\\\"}, {\\\"xcode_version\\\": \\\"16.4\\\"}]\"\n      macos_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem}}'\n      # macos_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem}} && swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-test --parallel --build-system ${{ matrix.buildSystem}}'\n      ios_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem}}  --sdk \\\"$(xcrun --sdk iphoneos --show-sdk-path)\\\" --triple arm64-apple-ios'\n      # ios_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem}} --sdk \\\"$(xcrun --sdk iphoneos --show-sdk-path)\\\" --triple arm64-apple-ios && swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-test --parallel --build-system ${{ matrix.buildSystem }} --sdk \\\"$(xcrun --sdk iphoneos --show-sdk-path)\\\" --triple arm64-apple-ios'\n\n  build-using-swiftbuild:\n    strategy:\n      fail-fast: false\n      matrix:\n        executableTargetBuildSystem: [\"swiftbuild\"]\n        buildSystem: [\"swiftbuild\"]\n    name: Build (${{ matrix.buildSystem }}) (exectable target built using ${{ matrix.executableTargetBuildSystem }})\n    needs: [soundness]\n    uses: swiftlang/github-workflows/.github/workflows/swift_package_test.yml@0.0.8\n    with:\n      linux_os_versions: '[\"amazonlinux2\", \"bookworm\", \"noble\", \"jammy\", \"rhel-ubi9\"]'\n      linux_swift_versions: '[\"nightly-main\"]'\n      linux_pre_build_command: ./.github/scripts/prebuild.sh\n      linux_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem }}'\n      enable_windows_checks: false\n      windows_build_timeout: 180\n      windows_swift_versions: '[\"nightly-main\"]'\n      windows_pre_build_command: 'Invoke-Program .\\.github\\scripts\\prebuild.ps1'\n      windows_build_command: 'Invoke-Program swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem }}'\n      enable_ios_checks: false\n      enable_macos_checks: true\n      macos_exclude_xcode_versions: \"[{\\\"xcode_version\\\": \\\"16.3\\\"}, {\\\"xcode_version\\\": \\\"16.4\\\"}]\"\n      macos_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem }}'\n      ios_build_command: 'swift run --build-system ${{ matrix.executableTargetBuildSystem }} swift-build --build-tests --build-system ${{ matrix.buildSystem }} --sdk \\\"$(xcrun --sdk iphoneos --show-sdk-path)\\\" --triple arm64-apple-ios'\n\n  soundness:\n    name: Soundness\n    uses: swiftlang/github-workflows/.github/workflows/soundness.yml@0.0.8\n    with:\n      license_header_check_project_name: \"Swift\"\n      license_header_check_enabled: true\n      unacceptable_language_check_enabled: true\n      api_breakage_check_enabled: false\n      format_check_enabled: false\n      shell_check_enabled: false\n      docs_check_enabled: true\n      broken_symlink_check_enabled: true\n      python_lint_check_enabled: true\n      yamllint_check_enabled: true\n"
  },
  {
    "path": ".gitignore",
    "content": ".build\n.test\n.index-build\n.devcontainer/.env\nDerivedData\n/.previous-build\nxcuserdata\n.DS_Store\n*~\n\\#*\n.\\#*\n.*.sw[nop]\n*.xcscmblueprint\n/default.profraw\n*.xcodeproj\nUtilities/Docker/*.tar.gz\n.swiftpm\nPackage.resolved\n/build\n*.pyc\n.docc-build\n.vscode\n/stage/\nUtilities/InstalledSwiftPMConfiguration/config.json\nFixtures/BinaryLibraries/Static/Package1/Simple.artifactbundle/build\n"
  },
  {
    "path": ".license_header_template",
    "content": "@@===----------------------------------------------------------------------===@@\n@@\n@@ This source file is part of the Swift open source project\n@@\n@@ Copyright (c) YEARS Apple Inc. and the Swift project authors\n@@ Licensed under Apache License v2.0 with Runtime Library Exception\n@@\n@@ See http://swift.org/LICENSE.txt for license information\n@@ See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n@@\n@@===----------------------------------------------------------------------===@@\n"
  },
  {
    "path": ".licenseignore",
    "content": "**/*.mlmodel\n**/*.pbxproj\n**/*.png\n**/*.xcworkspacedata\n**/Package.swift\n.dir-locals.el\n.editorconfig\n.swift-version\n.swiftformat\n.pep8\n.mailmap\n.mailfilter\nCODEOWNERS\nPackage.swift\nFixtures/**/*.*\n**/*.pc\n**/*.cer\n**/*.zip\n**/*.tar\n**/*.tgz\n**/*.gz\n**/*.svg\n**/*.bat\n**/*.xctestplan\n**/processInputs/**\nUtilities/bootstrap\nUtilities/build-using-self\nUtilities/new-bootstrap\nUtilities/test-toolchain\n"
  },
  {
    "path": ".mailfilter",
    "content": "# This is a list of `shasum` hashed email addresses which are filtered from CONTRIBUTORS.txt, typically for privacy.\n# Lines can be generated by running `echo -n 'My Name <my@email>' | shasum | head -c 40`.\n\n03a39e53ca4764a094b9f6e548e8d1ce0d941d7b\n38268a29b340ecfb435c5e6c5827a596acb71cc6\n43b012c0b4e67962522a02e12d07cb5d5c5ba036\n886d1da6503c6de1d630beaf6acb667e4ce3e2a0\n"
  },
  {
    "path": ".mailmap",
    "content": "Alex Blewitt <alblue@apple.com> <alblue@apple.com>\nAlex Blewitt <alblue@apple.com> <alex.blewitt@gmail.com>\nAlex Hoppen <ahoppen@apple.com> <ahoppen@apple.com>\nAlex Hoppen <ahoppen@apple.com> <alex@ateamer.de>\nAnkit Aggarwal <ankit_aggarwal@apple.com> <ankit_aggarwal@apple.com>\nAnkit Aggarwal <ankit_aggarwal@apple.com> <ankit.spd@gmail.com>\nAnkit Aggarwal <ankit_aggarwal@apple.com> <ankit.spd@gmail.com>\nAnkit Aggarwal <ankit_aggarwal@apple.com> <ankit@Stardust.local>\nBen Chatelain <ben@octop.ad> <ben@octop.ad>\nBen Chatelain <ben@octop.ad> <phatblat@users.noreply.github.com>\nBen Cohen <ben_cohen@apple.com> <ben_cohen@apple.com>\nBen Cohen <ben_cohen@apple.com> <airspeedswift@users.noreply.github.com>\nBen Langmuir <blangmuir@apple.com> <blangmuir@apple.com>\nBen Langmuir <blangmuir@apple.com> <ben.langmuir@gmail.com>\nBenjamin Herzog <benjamin_herzog@apple.com> <benjamin_herzog@apple.com>\nBenjamin Herzog <benjamin_herzog@apple.com> <mail@benchr.de>\nBenjamin Scholtysik <bscholtysik@apple.com> <bscholtysik@apple.com>\nBenjamin Scholtysik (Reimold) <bscholtysik@apple.com> <bereimol@microsoft.com>\nBenjamin Scholtysik <bscholtysik@apple.com> <bereimol@microsoft.com>\nBoris Buegling <bbuegling@apple.com> <bbuegling@apple.com>\nBoris Buegling <bbuegling@apple.com> <boris@icculus.org>\nBraden Scothern <BradenScothern@gmail.com> <BradenScothern@gmail.com>\nBraden Scothern <BradenScothern@gmail.com> <bscothern@users.noreply.github.com>\nBrandon Titus <bjtitus@gmail.com> <bjtitus@gmail.com>\nBrandon Titus <bjtitus@gmail.com> <b@titus.io>\nBrian Croom <bcroom@apple.com> <bcroom@apple.com>\nBrian Croom <bcroom@apple.com> <brian.s.croom@gmail.com>\nBrian Gesiak <modocache@gmail.com> <modocache@gmail.com>\nBrian Gesiak <modocache@gmail.com> <bgesiak@fb.com>\nChris Lattner <clattner@apple.com> <clattner@apple.com>\nChris Lattner <clattner@apple.com> <lattner@users.noreply.github.com>\nDan Zheng <danielzheng@google.com> <danielzheng@google.com>\nDan Zheng <danielzheng@google.com> <zheng321@purdue.edu>\nDaniel Duan <danmarner@gmail.com> <danmarner@gmail.com>\nDaniel Duan <danmarner@gmail.com> <daniel@duan.ca>\nDaniel Duan <danmarner@gmail.com> <daniel@duan.org>\nDaniel Dunbar <daniel_dunbar@apple.com> <daniel_dunbar@apple.com>\nDaniel Dunbar <daniel_dunbar@apple.com> <daniel@zuster.org>\nDario Rexin <drexin@apple.com> <drexin@apple.com>\nDario Rexin <drexin@apple.com> <dario.rexin@me.com>\nDave Abrahams <dabrahams@apple.com> <dabrahams@apple.com>\nDave Abrahams <dabrahams@apple.com> <dave@Skree.local>\nDavid Hart <david@hartbit.com> <david@hartbit.com>\nDavid Hart <david@hartbit.com> <david@atipik.ch>\nHarlan Haskins <harlan@apple.com> <harlan@apple.com>\nHarlan Haskins <harlan@apple.com> <harlan@harlanhaskins.com>\nHelge Hess <me@helgehess.eu> <me@helgehess.eu>\nHonza Dvorsky <honza@apple.com> <honza@apple.com>\nHonza Dvorsky <honza@apple.com> <honza@swiftkey.com>\nHonza Dvorsky <honza@apple.com> <jan.dvorsky@yahoo.com>\nJ. Cheyo Jimenez <cheyo@masters3d.com> <cheyo@masters3d.com>\nJ. Cheyo Jimenez <cheyo@masters3d.com> <masters3d@users.noreply.github.com>\nJohannes Weiss <johannesweiss@apple.com> <johannesweiss@apple.com>\nJohannes Weiss <johannesweiss@apple.com> <github@tux4u.de>\nJohannes Weiss <johannesweiss@apple.com> <johannesweiss@apple.com>\nKilian Koeltzsch <kiliank@apple.com> <kiliank@apple.com>\nKilian Koeltzsch <kiliank@apple.com> <me@kilian.io>\nKyle Jessup <kyle@perfect.org> <kyle@perfect.org>\nKyle Jessup <kyle@perfect.org> <badthing@gmail.com>\nLev Walkin <lwalkin@apple.com> <lwalkin@apple.com>\nLev Walkin <lwalkin@apple.com> <vlm@lionet.info>\nMarcin Krzyzanowski <marcin@krzyzanowskim.com> <marcin@krzyzanowskim.com>\nMarcin Krzyzanowski <marcin@krzyzanowskim.com> <758033+krzyzanowskim@users.noreply.github.com>\nMarcin Krzyzanowski <marcin@krzyzanowskim.com> <marcin.krzyzanowski@gmail.com>\nMarcin Krzyzanowski <marcin@krzyzanowskim.com> <marcin@krzyzanowskim.com>\nMatthew Seaman <mattsdeveloper@gmail.com> <mattsdeveloper@gmail.com>\nMatthew Seaman <mattsdeveloper@gmail.com> <matthewseaman@users.noreply.github.com>\nMattt Thompson <mattt@me.com> <mattt@me.com>\nMattt Thompson <mattt@me.com> <mattt@github.com>\nMattt Thompson <mattt@me.com> <mattt.thompson@apple.com>\nMax Howell <max.howell@apple.com> <max.howell@apple.com>\nMax Howell <max.howell@apple.com> <mxcl@me.com>\nMax Liberman <max.y.liberman@gmail.com> <max.y.liberman@gmail.com>\nMax Liberman <max.y.liberman@gmail.com> <liberman@wetransfer.com>\nMax Moiseev <moiseev@apple.com> <moiseev@apple.com>\nMax Moiseev <moiseev@apple.com> <moiseev@users.noreply.github.com>\nMax Moiseev <moiseev@apple.com> <maxim.moiseev@gmail.com>\nMichael Ilseman <milseman@apple.com> <milseman@apple.com>\nMichael Ilseman <milseman@apple.com> <michael.ilseman@gmail.com>\nMishal Shah <mishal_shah@apple.com> <mishal_shah@apple.com>\nMishal Shah <mishal_shah@apple.com> <shahmishal@users.noreply.github.com>\nNikola Lajic <n.lajic@gmail.com> <n.lajic@gmail.com>\nNikola Lajic <n.lajic@gmail.com> <nikola.lajic@codecentric.de>\nOwen Voorhees <owen@squibner.com> <owen@squibner.com>\nOwen Voorhees <owen@squibner.com> <owenvoorhees@gmail.com>\nPavel Yaskevich <pyaskevich@apple.com> <pyaskevich@apple.com>\nPavel Yaskevich <pyaskevich@apple.com> <xedin@apache.org>\nSaleem Abdulrasool <compnerd@compnerd.org> <compnerd@compnerd.org>\nSaleem Abdulrasool <compnerd@compnerd.org> <abdulras@fb.com>\nSaleem Abdulrasool <compnerd@compnerd.org> <abdulras@google.com>\nSergio Campamá <scampama@apple.com> <scampama@apple.com>\nSergio Campamá <scampama@apple.com> <kaipi@copilot.money>\nSlava Pestov <spestov@apple.com> <spestov@apple.com>\nSlava Pestov <spestov@apple.com> <sviatoslav.pestov@gmail.com>\nThomas Roughton <t.roughton@me.com> <t.roughton@me.com>\nThomas Roughton <t.roughton@me.com> <troughton@users.noreply.github.com>\nTim Condon <0xTim@users.noreply.github.com> <0xTim@users.noreply.github.com>\nTim Condon <0xTim@users.noreply.github.com> <tg908@icloud.com>\nTim Gymnich <tgymnich@icloud.com> <tgymnich@icloud.com>\nTim Gymnich <tgymnich@icloud.com> <tg908@icloud.com>\nTom Doron <tomer@apple.com> <tomer@apple.com>\nValeriy Van <github@w7software.com> <valeriy.van@enote.com>\nValeriy Van <github@w7software.com> <github@w7software.com>\nfinagolfin <butta@fastem.com> <butta@fastem.com>\nfinagolfin <butta@fastem.com> <repo@butta.fastem.com>\n"
  },
  {
    "path": ".pep8",
    "content": "[flake8]\nfilename = *.py,bootstrap\nmax-line-length = 80\n"
  },
  {
    "path": ".swift-version",
    "content": "6.2.3"
  },
  {
    "path": ".swiftformat",
    "content": "## File options\n\n--swiftversion 5.9\n--exclude .build\n\n## Formatting options\n\n# Configure the placement of an extension's access control keyword.\n--extensionacl on-declarations\n\n# #if indenting\n--ifdef no-indent\n\n# Wrap lines that exceed the specified maximum width.\n--maxwidth 120\n\n# Reposition `let` or `var` bindings within pattern.\n--patternlet inline\n\n# Insert explicit `self` where applicable.\n--self insert\n\n# Mark unused function arguments with `_`.\n--stripunusedargs unnamed-only\n\n# Remove trailing space at end of a line.\n--trimwhitespace always\n\n# Wrap `@attributes` onto a separate line.\n--funcattributes prev-line\n--typeattributes prev-line\n\n# Use `Void` for type declarations and `()` for values.\n--voidtype void\n\n# Align wrapped function arguments or collection elements.\n--wraparguments before-first\n\n## Rules\n\n# Prefer `&&` over `,` comma in `if`, `guard` or `while` conditions.\n# Preserve `nil` default value (Optional `var`s are `nil` by default).\n--disable andOperator,redundantNilInit \n"
  },
  {
    "path": "Benchmarks/Benchmarks/PackageGraphBenchmarks/PackageGraphBenchmarks.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport Basics\nimport Benchmark\nimport Foundation\nimport PackageModel\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport func PackageGraph.loadModulesGraph\n\nimport Workspace\n\nlet benchmarks = {\n    let defaultMetrics: [BenchmarkMetric]\n    if let envVar = ProcessInfo.processInfo.environment[\"SWIFTPM_BENCHMARK_ALL_METRICS\"],\n    envVar.lowercased() == \"true\" || envVar == \"1\" {\n        defaultMetrics = .all\n    } else {\n        defaultMetrics = [\n            .mallocCountTotal,\n            .syscalls,\n        ]\n    }\n\n    let modulesGraphDepth: Int\n    if let envVar = ProcessInfo.processInfo.environment[\"SWIFTPM_BENCHMARK_MODULES_GRAPH_DEPTH\"],\n    let parsedValue = Int(envVar) {\n        modulesGraphDepth = parsedValue\n    } else {\n        modulesGraphDepth = 150\n    }\n\n    let modulesGraphWidth: Int\n    if let envVar = ProcessInfo.processInfo.environment[\"SWIFTPM_BENCHMARK_MODULES_GRAPH_WIDTH\"],\n    let parsedValue = Int(envVar) {\n        modulesGraphWidth = parsedValue\n    } else {\n        modulesGraphWidth = 150\n    }\n\n    let packagesGraphDepth: Int\n    if let envVar = ProcessInfo.processInfo.environment[\"SWIFTPM_BENCHMARK_PACKAGES_GRAPH_DEPTH\"],\n    let parsedValue = Int(envVar) {\n        packagesGraphDepth = parsedValue\n    } else {\n        packagesGraphDepth = 10\n    }\n\n    // Benchmarks computation of a resolved graph of modules for a package using `Workspace` as an entry point. It runs PubGrub to get\n    // resolved concrete versions of dependencies, assigning all modules and products to each other as corresponding dependencies\n    // with their build triples, but with the build plan not yet constructed. In this benchmark specifically we're loading `Package.swift`\n    // for SwiftPM itself.\n    Benchmark(\n        \"SwiftPMWorkspaceModulesGraph\",\n        configuration: .init(\n            metrics: defaultMetrics,\n            maxDuration: .seconds(10),\n            thresholds: [\n                .mallocCountTotal: .init(absolute: [.p90: 12000]),\n                .syscalls: .init(absolute: [.p90: 1600]),\n            ]\n        )\n    ) { benchmark in\n        let path = try AbsolutePath(validating: #file).parentDirectory.parentDirectory.parentDirectory\n        let workspace = try Workspace(fileSystem: localFileSystem, location: .init(forRootPackage: path, fileSystem: localFileSystem))\n\n        for _ in benchmark.scaledIterations {\n            try workspace.loadPackageGraph(rootPath: path, observabilityScope: ObservabilitySystem.NOOP)\n        }\n    }\n\n    // Benchmarks computation of a resolved graph of modules for a trivial synthesized package using `loadModulesGraph`\n    // as an entry point, which almost immediately delegates to `ModulesGraph.load` under the hood.\n    Benchmark(\n        \"SyntheticModulesGraph\",\n        configuration: .init(\n            metrics: defaultMetrics,\n            maxDuration: .seconds(10),\n            thresholds: [\n                .mallocCountTotal: .init(absolute: [.p90: 17000]),\n                .syscalls: .init(absolute: [.p90: 5]),\n            ]\n        )\n    ) { benchmark in\n        try syntheticModulesGraph(\n            benchmark,\n            modulesGraphDepth: modulesGraphDepth,\n            modulesGraphWidth: modulesGraphWidth\n        )\n    }\n\n    // Benchmarks computation of a resolved graph of modules for a synthesized package that includes macros,\n    // using `loadModulesGraph` as an entry point, which almost immediately delegates to `ModulesGraph.load` under\n    // the hood.\n    Benchmark(\n        \"SyntheticModulesGraphWithMacros\",\n        configuration: .init(\n            metrics: defaultMetrics,\n            maxDuration: .seconds(10),\n            thresholds: [\n                .mallocCountTotal: .init(absolute: [.p90: 8000]),\n                .syscalls: .init(absolute: [.p90: 5]),\n            ]\n        )\n    ) { benchmark in\n        try syntheticModulesGraph(\n            benchmark,\n            modulesGraphDepth: modulesGraphDepth,\n            modulesGraphWidth: modulesGraphWidth,\n            includeMacros: true\n        )\n    }\n}\n\nfunc syntheticModulesGraph(\n    _ benchmark: Benchmark,\n    modulesGraphDepth: Int,\n    modulesGraphWidth: Int,\n    includeMacros: Bool = false\n) throws {\n    // If macros are included, modules are split in three parts:\n    // 1. top-level modules\n    // 2. macros\n    // 3. dependencies of macros\n    let macrosDenominator = includeMacros ? 3 : 1\n    let libraryModules: [TargetDescription] = try (0..<(modulesGraphWidth / macrosDenominator)).map { i -> TargetDescription in\n        let dependencies = (0..<min(i, modulesGraphDepth / macrosDenominator)).flatMap { i -> [TargetDescription.Dependency] in\n            if includeMacros {\n                [.target(name: \"Module\\(i)\"), .target(name: \"Macros\\(i)\")]\n            } else {\n                [.target(name: \"Module\\(i)\")]\n            }\n        }\n        return try TargetDescription(name: \"Module\\(i)\", dependencies: dependencies)\n    }\n\n    let macrosModules: [TargetDescription]\n    let macrosDependenciesModules: [TargetDescription]\n    if includeMacros {\n        macrosModules = try (0..<modulesGraphWidth / macrosDenominator).map { i in\n            try TargetDescription(name: \"Macros\\(i)\", dependencies: (0..<min(i, modulesGraphDepth)).map {\n                .target(name: \"MacrosDependency\\($0)\")\n            })\n        }\n        macrosDependenciesModules = try (0..<modulesGraphWidth / macrosDenominator).map { i in\n            try TargetDescription(name: \"MacrosDependency\\(i)\")\n        }\n    } else {\n        macrosModules = []\n        macrosDependenciesModules = []\n    }\n\n    let modules = libraryModules + macrosModules + macrosDependenciesModules\n    let fileSystem = InMemoryFileSystem(\n        emptyFiles: modules.map {\n            \"/benchmark/Sources/\\($0.name)/empty.swift\"\n        }\n    )\n    let rootPackagePath = try AbsolutePath(validating: \"/benchmark\")\n\n    let manifest = Manifest(\n        displayName: \"benchmark\",\n        path: rootPackagePath,\n        packageKind: .root(rootPackagePath),\n        packageLocation: rootPackagePath.pathString,\n        defaultLocalization: nil,\n        platforms: [],\n        version: nil,\n        revision: nil,\n        toolsVersion: .v5_10,\n        pkgConfig: nil,\n        providers: nil,\n        cLanguageStandard: nil,\n        cxxLanguageStandard: nil,\n        swiftLanguageVersions: nil,\n        targets: modules\n    )\n\n    for _ in benchmark.scaledIterations {\n        try blackHole(\n            loadModulesGraph(fileSystem: fileSystem, manifests: [manifest], observabilityScope: ObservabilitySystem.NOOP)\n        )\n    }\n}\n"
  },
  {
    "path": "Benchmarks/Package.swift",
    "content": "// swift-tools-version: 5.7\n//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"SwiftPMBenchmarks\",\n    platforms: [\n        .macOS(\"14\"),\n    ],\n    dependencies: [\n        .package(path: \"../\"),\n        .package(url: \"https://github.com/ordo-one/package-benchmark.git\", from: \"1.13.0\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"PackageGraphBenchmarks\",\n            dependencies: [\n                .product(name: \"Benchmark\", package: \"package-benchmark\"),\n                .product(name: \"SwiftPMDataModel\", package: \"SwiftPM\"),\n            ],\n            path: \"Benchmarks/PackageGraphBenchmarks\",\n            plugins: [\n                .plugin(name: \"BenchmarkPlugin\", package: \"package-benchmark\"),\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Benchmarks/README.md",
    "content": "# SwiftPM Benchmarks\n\nBenchmarks currently use [ordo-one/package-benchmark](https://github.com/ordo-one/package-benchmark) library for\nbenchmarking.\n\n## How to Run\n\nTo run the benchmarks in their default configuration, run this command in the `Benchmarks` subdirectory of the SwiftPM\nrepository clone (the directory in which this `README.md` file is contained):\n\n```\nswift package benchmark\n```\n\nTo collect all benchmark metrics, set `SWIFTPM_BENCHMARK_ALL_METRICS` to a truthy value:\n\n```\nSWIFTPM_BENCHMARK_ALL_METRICS=true swift package benchmark\n```\n\n## Benchmark Thresholds\n\n`Benchmarks/Thresholds` subdirectory contains recorded allocation and syscall counts for macOS on Apple Silicon when\nbuilt with Swift 5.10. To record new thresholds, run the following command:\n\n```\nswift package --allow-writing-to-package-directory benchmark \\\n  --format metricP90AbsoluteThresholds \\\n  --path \"Thresholds/$([[ $(uname) == Darwin ]] && echo macos || echo linux)-$(uname -m)\"\n```\n\nTo verify that recorded thresholds do not exceeded given relative or absolute values (passed as `thresholds` arguments\nto each benchmark's configuration), run this command:\n\n```\nswift package benchmark baseline check --check-absolute-path Thresholds/\n```\n"
  },
  {
    "path": "Benchmarks/Thresholds/macos-arm64/PackageGraphBenchmarks.SwiftPMWorkspaceModulesGraph.p90.json",
    "content": "{\n  \"mallocCountTotal\" : 11255,\n  \"syscalls\" : 1497\n}"
  },
  {
    "path": "Benchmarks/Thresholds/macos-arm64/PackageGraphBenchmarks.SyntheticModulesGraph.p90.json",
    "content": "{\n  \"mallocCountTotal\" : 15679,\n  \"syscalls\" : 0\n}"
  },
  {
    "path": "Benchmarks/Thresholds/macos-arm64/PackageGraphBenchmarks.SyntheticModulesGraphWithMacros.p90.json",
    "content": "{\n  \"mallocCountTotal\" : 7743,\n  \"syscalls\" : 0\n}"
  },
  {
    "path": "Benchmarks/Thresholds/macosx-arm64/PackageGraphBenchmarks.SwiftPMWorkspaceModulesGraph.p90.json",
    "content": "{\n  \"mallocCountTotal\" : 10775,\n  \"syscalls\" : 1508\n}"
  },
  {
    "path": "Benchmarks/Thresholds/macosx-arm64/PackageGraphBenchmarks.SyntheticModulesGraph.p90.json",
    "content": "{\n  \"mallocCountTotal\" : 2427,\n  \"syscalls\" : 0\n}"
  },
  {
    "path": "BuildSupport/SwiftSyntax/CMakeLists.txt",
    "content": "include(FetchContent)\n\nfind_package(SwiftSyntax CONFIG GLOBAL)\nif(NOT SwiftSyntax_FOUND)\n  set(SWIFT_SYNTAX_INSTALL_TARGETS YES)\n  if(DEFINED SWIFTPM_PATH_TO_SWIFT_SYNTAX_SOURCE)\n    file(TO_CMAKE_PATH \"${SWIFTPM_PATH_TO_SWIFT_SYNTAX_SOURCE}\" swift_syntax_path)\n    FetchContent_Declare(SwiftSyntax\n      SOURCE_DIR \"${swift_syntax_path}\")\n  else()\n    FetchContent_Declare(SwiftSyntax\n      GIT_REPOSITORY https://github.com/swiftlang/swift-syntax\n      GIT_TAG main)\n  endif()\n  FetchContent_MakeAvailable(SwiftSyntax)\nendif()\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "Note: This is in reverse chronological order, so newer entries are added to the top.\n\nSwift Next\n-----------\n\nSwift 6.2\n---------\n\n* [#8314]\n\n  Starting from tools-version 6.2, `SwiftSetting` provides a `strictMemorySafety` setting to enable the strict memory safety checking introduced in [SE-0458].\n\n* [#8301]\n\n  Starting from tools-version 6.2, `SwiftSetting` provides a `defaultIsolation` setting to allow specifying default actor isolation for a target [SE-0466].\n\nSwift 6.0\n-----------\n\n* [#7813]\n\n  Starting from tools-version 6.0, `swiftLanguageMode` can be specified at the target level, allowing for gradual per-target migration to the Swift 6 language mode.\n  The `swiftLanguageVersions` setting has been deprecated and renamed to `swiftLanguageModes`.\n\n* [#7530]\n\n  Starting from tools-version 6.0 makes it possible for packages to depend on each other if such dependency doesn't form any target-level cycles.\n  For example, package `A` can depend on `B` and `B` on `A` unless targets in `B` depend on products of `A` that depend on some of the same\n  targets from `B` and vice versa.\n\n* [#7741]\n\n  Fixed an issue where repositories would be re-cloned each build rather than using the cache due to git validation errors.\n\n* [#7507] \n\n  `swift experimental-sdk` command is deprecated with `swift sdk` command replacing it. `--experimental-swift-sdk` and\n  `--experimental-swift-sdks-path` options on `swift build` are deprecated with replacements that don't have the\n  `experimental` prefix.\n\n* [#7722]\n\n  An additional `--checksum` option  is now required for `swift sdk install` subcommand with remote URLs as arguments. `--checksum` allows users of a Swift SDK to specify a checksum provided by the SDK publisher. A checksum can be produced by running `swift package compute-checksum` command (introduced in [SE-0272]) with the Swift SDK bundle archive as an argument.\n\n* [#7535]\n\n  The `swift sdk configuration` subcommand is deprecated with a replacement named `configure` that has options that exactly match\n  [SE-0387 proposal text].\n\n\n* [#7202]\n\n  Package manifests can now access information about the Git repository the given package is in via the context object's \n  `gitInformation` property. This allows to determine the current tag (if any), the current commit and whether or not there are uncommited changes.\n\n* [#7201]\n\n  `// swift-tools-version:` can now be specified on subsequent lines of `Package.swift`, for example when first few lines are required to contain a licensing comment header.\n\n* [#7118]\n\n  Macros cross-compiled by SwiftPM with Swift SDKs are now correctly built, loaded, and evaluated for the host triple.\n\n  Packages with modules that incorrectly imported macro modules directly instead of importing macro interface modules will no longer build\n  with `swift build`.\n\nSwift 5.10\n-----------\n\n* [#7010]\n\n  On macOS, `swift build` and `swift run` now produce binaries that allow backtraces in debug builds. Pass `SWIFT_BACKTRACE=enable=yes` environment variable to enable backtraces on such binaries when running them.\n\n* [#7101]\n\n   Binary artifacts are now cached along side repository checkouts so they do not need to be re-downloaded across projects.\n\nSwift 5.9\n-----------\n\n* [SE-0386]\n\n  SwiftPM packages can now use `package` as a new access modifier, allowing accessing symbols in another target / module within the same package without making it public.\n\n* [SE-0387]\n\n  New `swift experimental-sdk` experimental command is now available for managing Swift SDK bundles that follow the format described in [SE-0387]: \"Swift SDKs for Cross-Compilation\".\n\n* [SE-0391]\n\n  SwiftPM can now publish to a registry following the publishing spec as defined in [SE-0391]. SwiftPM also gains support for signed packages. Trust-on-first-use (TOFU) check which includes only fingerprints (e.g., checksums) previously has been extended to include signing identities, and it is enforced for source archives as well as package manifests.\n\n* [#5966]\n\n  Plugin compilation can be influenced by using `-Xbuild-tools-swiftc` arguments in the SwiftPM command line. This is similar to the existing mechanism for influencing the manifest compilation using `-Xmanifest` arguments. Manifest compilation will also be influenced by `-Xbuild-tools-swiftc`, but only if no other `-Xmanifest` arguments are provided. Using `-Xmanifest` will show a deprecation message. `-Xmanifest` will be removed in the future.\n\n* [#6060]\n\n  Support for building plugin dependencies for the host when cross-compiling.\n\n* [#6067]\n\n  Basic support for a new `.embedInCode` resource rule which allows embedding the contents of the resource into the executable code by generating a byte array, e.g.\n\n  ```\n  struct PackageResources {\n    static let best_txt: [UInt8] = [104,101,108,108,111,32,119,111,114,108,100,10]\n  }\n  ```\n\n* [#6111]\n\n  Package creation using `package init` now also supports the build tool plugin and command plugin types.\n\n* [#6114]\n\n  Added a new `allowNetworkConnections(scope:reason:)` for giving a command plugin permissions to access the network. Permissions can be scoped to Unix domain sockets in general or specifically for Docker, as well as local or remote IP connections which can be limited by port. For non-interactive use cases, there is also a `--allow-network-connections` commandline flag to allow network connections for a particular scope.\n\n* [#6144]\n\n  Remove the `system-module` and `manifest` templates and clean up the remaining `empty`, `library`, and `executable` templates so they include the minimum information needed to get started, with links to documentation in the generated library, executable, and test content.\n\n* [#6185], [#6200]\n\n  Add a new `CompilerPluginSupport` module which contains the definition for macro targets. Macro targets allow authoring and distribution of custom Swift macros such as [expression macros](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0382-expression-macros.md).\n\n* [#6276]\n\n  Add new build setting in the package manifest that enables Swift/C++ Interoperability for a given Swift target.\n\n  ```\n  .interoperabilityMode(.Cxx, version: \"swift-5.9\")\n  ```\n  \n* [#6294]\n\n  When a package contains a single target, sources may be distributed anywhere within the `./Sources` directory. If sources are placed in a subdirectory under `./Sources/<target>`, or there is more than one target, the existing expectation for sources apply.\n\n* [#6540]\n\n  Build tool plugins can be used with C-family targets\n\n* [#6663]\n\n  Add `visionOS` as a platform alongside `iOS` and other platforms\n  \n\nSwift 5.8\n-----------\n\n* [SE-0362] \n\n  SwiftPM targets can now specify the upcoming language features they require. `Package.swift` manifest syntax has been expanded with an API to include setting `enableUpcomingFeature` and `enableExperimentalFeature` flags at the target level, as specified by [SE-0362].\n  \n* [SE-0378]\n\n  SwiftPM now supports token authentication when interacting with a package registry. The `swift package-registry` command has two new subcommands `login` and `logout` as defined in SE-0378 for adding/removing registry credentials.  \n\n* [#5810]\n\n  SwiftPM now allows exposing an executable product that consists solely of a binary target that is backed by an artifact bundle. This allow vending binary executables as their own separate package, independently of the plugins that are using them.  \n\n* [#5819]\n\n  Improved handling of offline behavior when a cached version of a dependency exists on disk. SwiftPM will check for network availability status to determine if it should attempt to update a checked version of a dependency, and when offline will use the cached version without an update.\n\n* [#5874]\n\n  In packages using tools version 5.8 or later, Foundation is no longer implicitly imported into package manifests. If Foundation APIs are used, the module needs to be imported explicitly.\n  \n* [#5892]\n\n  Added new `--emit-extension-block-symbols` and `--omit-extension-block-symbols` via `swift package dump-symbol-graph`. `--emit-extension-block-symbols` dumps symbol graph files that are extension block symbol format. The default behavior does not change. The `--omit-extension-block-symbols` flag will be used to explicitly disable the feature once the default behavior has been changed to `--emit-extension-block-symbols` in the future.\n  \n* [#5949]\n  \n  New `--pkg-config-path` option on `build`, `test`, and `run` commands has been introduced as an alternative to passing `PKG_CONFIG_PATH` environment variable. It allows specifying alternative path to search for `.pc` files used by `pkg-config`. Use the option multiple times to specify more than one path.  \n\nSwift 5.7\n-----------\n\n* [SE-0292]\n\n  SwiftPM can now resolve dependencies from a server compliant with the package registry server API defined in SE-0292. \n  \n* [SE-0339]\n\n  Module aliases can now be defined in the package manifest to disambiguate between modules with the same name originating from different packages. \n\n* [#4119] \n \n  Add a `--disable-testable-imports` flag to `swift test` with which tests are built without the testability feature (`import @testable` disabled).\n\n* [#4131]\n\n  Update to manifest API to make it impossible to create an invalid build settings condition.\n\n* [#4135]\n\n  Enable linker dead stripping for all platforms. This can be disabled with `--disable-dead-strip`\n\n* [#4168]\n\n  Update to manifest API to make it impossible to create an invalid target dependency condition.\n\nSwift 5.6\n-----------\n* [SE-0303]\n\n  Package plugins of the type `buildTool` can now be declared in packages that specify a tools version of 5.6 or later, and can be invoked using the `swift build` command.\n  \n* [SE-0332]\n\n  Package plugins of the type `command` can now be declared in packages that specify a tools version of 5.6 or later, and can be invoked using the `swift package` subcommand.\n\n* [#3649]\n\n  Semantic version dependencies can now be resolved against Git tag names that contain only major and minor version identifiers.  A tag with the form `X.Y` will be treated as `X.Y.0`. This improves compatibility with existing repositories.\n\n* [#3486]\n\n  Both parsing and comparison of semantic versions now strictly follow the [Semantic Versioning 2.0.0 specification](https://semver.org). \n  \n  The parsing logic now treats the first \"-\" in a version string as the delimiter between the version core and the pre-release identifiers, _only_ if there is no preceding \"+\". Otherwise, it's treated as part of a build metadata identifier.\n  \n  The comparison logic now ignores build metadata identifiers, and treats 2 semantic versions as equal if and only if they're equal in their major, minor, patch versions and pre-release identifiers.\n\n* [#3641]\n\n  Soft deprecate `.package(name:, url:)` dependency syntax in favor of `.package(url:)`, given that an explicit `name` attribute is no longer needed for target dependencies lookup.\n\n* [#3641]\n\n  Adding a dependency requirement can now be done with the convenience initializer `.package(url: String, exact: Version)`.\n\n* [#3641]\n\n  Dependency requirement enum calling convention is deprecated in favour of labeled argument:    \n    * `.package(url: String, .branch(String))` -> `.package(url: String, branch: String)`\n    * `.package(url: String, .revision(String))` -> `.package(url: String, revision: String)`    \n    * `.package(url: String, .exact(Version))` -> `.package(url: String, exact: Version)` \n\n* [#3717]\n\n  Introduce a second version of `Package.resolved` file format which more accurately captures package identity.\n\n* [#3890]\n\n  To increase the security of packages, SwiftPM performs trust on first use (TOFU) validation. The fingerprint of a package is now being recorded when the package is first downloaded from a Git repository or package registry. Subsequent downloads must have fingerpints matching previous recorded values, otherwise it would result in build warnings or failures depending on settings.   \n\n* [#3670], [#3901], [#3942]\n\n  Location of configuration files (including mirror file) have changed to accomodate new features that require more robust configuration directories structure, such as SE-0292:  \n    * `<project>/.swiftpm/config` (mirrors file) was moved to `<project>/.swiftpm/configuration/mirrors.json`. SwiftPM 5.6 will automatically copy the file from the old location to the new one and emit a warning to prompt the user to delete the file from the old location.\n    * `~/.swiftpm/config/collections.json` (collections file) was moved to `~/.swiftpm/configuration/collections.json`. SwiftPM 5.6 will automatically copy the file from the old location to the new one and emit a warning to prompt the user to delete the file from the old location.\n\n\nSwift 5.5\n-----------\n* [#3410]\n\n  In a package that specifies a minimum tools version of 5.5, `@main` can now be used in a single-source file executable as long as the name of the source file isn't `main.swift`.  To work around special compiler semantics with single-file modules, SwiftPM now passes `-parse-as-library` when compiling an executable module that contains a single Swift source file whose name is not `main.swift`.\n\n* [#3310]\n\n  Adding a dependency requirement can now be done with the convenience initializer `.package(url: String, revision: String)`.\n\n* [#3292]\n\n  Adding a dependency requirement can now be done with the convenience initializer `.package(url: String, branch: String)`.\n\n* [#3280]\n\n  A more intuitive `.product(name:, package:)` target dependency syntax is now accepted, where `package` is the package identifier as defined by the package URL.\n\n* [#3316]\n\n  Test targets can now link against executable targets as if they were libraries, so that they can test any data structures or algorithms in them.  All the code in the executable except for the main entry point itself is available to the unit test.  Separate executables are still linked, and can be tested as a subprocess in the same way as before.  This feature is available to tests defined in packages that have a tools version of `5.5` or newer. \n\n\nSwift 5.4\n-----------\n* [#2937]\n  \n  * Improvements\n    \n    `Package` manifests can now have any combination of leading whitespace characters. This allows more flexibility in formatting the manifests.\n    \n    [SR-13566] The Swift tools version specification in each manifest file now accepts any combination of _horizontal_ whitespace characters surrounding `swift-tools-version`, if and only if the specified version ≥ `5.4`. For example, `//swift-tools-version:\t5.4` and `//\t\t swift-tools-version: 5.4` are valid.\n  \n    All [Unicode line terminators](https://www.unicode.org/reports/tr14/) are now recognized in `Package` manifests. This ensures correctness in parsing manifests that are edited and/or built on many non-Unix-like platforms that use ASCII or Unicode encodings. \n  \n  * API Removal\n  \n    `ToolsVersionLoader.Error.malformedToolsVersion(specifier: String, currentToolsVersion: ToolsVersion)` is replaced by `ToolsVersionLoader.Error.malformedToolsVersionSpecification(_ malformation: ToolsVersionSpecificationMalformation)`.\n    \n    `ToolsVersionLoader.split(_ bytes: ByteString) -> (versionSpecifier: String?, rest: [UInt8])` and `ToolsVersionLoader.regex` are together replaced by `ToolsVersionLoader.split(_ manifest: String) -> ManifestComponents`.\n  \n  * Source Breakages for Swift Packages\n    \n    The package manager now throws an error if a manifest file contains invalid UTF-8 byte sequences.\n    \n\nSwift 4.2\n---------\n\n* [SE-0209]\n\n  The `swiftLanguageVersions` property no longer takes its Swift language versions via\n  a freeform Integer array; instead it should be passed as a new `SwiftVersion` enum\n  array.\n\n* [SE-0208]\n\n  The `Package` manifest now accepts a new type of target, `systemLibrary`. This\n  deprecates \"system-module packages\" which are now to be included in the packages\n  that require system-installed dependencies.\n\n* [SE-0201]\n\n  Packages can now specify a dependency as `package(path: String)` to point to a\n  path on the local filesystem which hosts a package. This will enable interconnected\n  projects to be edited in parallel.\n\n* [#1604]\n\n  The `generate-xcodeproj` has a new `--watch` option to automatically regenerate the Xcode project\n  if changes are detected. This uses the\n  [`watchman`](https://facebook.github.io/watchman/docs/install.html) tool to detect filesystem\n  changes.\n\n* Scheme generation has been improved:\n  * One scheme containing all regular and test targets of the root package.\n  * One scheme per executable target containing the test targets whose dependencies\n    intersect with the dependencies of the exectuable target.\n\n* [SR-6978]\n  Packages which mix versions of the form `vX.X.X` with `Y.Y.Y` will now be parsed and\n  ordered numerically.\n\n* [#1489]\n  A simpler progress bar is now generated for \"dumb\" terminals.\n\n\nSwift 4.1\n---------\n\n* [#1485]\n  Support has been added to automatically generate the `LinuxMain` files for testing on\n  Linux systems. On a macOS system, run `swift test --generate-linuxmain`.\n\n* [SR-5918]\n  `Package` manifests that include multiple products with the same name will now throw an\n  error.\n\n\nSwift 4.0\n---------\n\n* The generated Xcode project creates a dummy target which provides\n  autocompletion for the manifest files. The name of the dummy target is in\n  format: `<PackageName>PackageDescription`.\n\n* `--specifier` option for `swift test` is now deprecated.\n  Use `--filter` instead which supports regex.\n\n\nSwift 3.0\n---------\n\n* [SE-0135]\n\n  The package manager now supports writing Swift 3.0 specific tags and\n  manifests, in order to support future evolution of the formats used in both\n  cases while still allowing the Swift 3.0 package manager to continue to\n  function.\n\n* [SE-0129]\n\n  Test modules now *must* be named with a `Tests` suffix (e.g.,\n  `Foo/Tests/BarTests/BarTests.swift`). This name also defines the name of the\n  Swift module, replacing the old `BarTestSuite` module name.\n\n* It is no longer necessary to run `swift build` before running `swift test` (it\n  will always regenerates the build manifest when necessary). In addition, it\n  now accepts (and requires) the same `-Xcc`, etc. options as are used with\n  `swift build`.\n\n* The `Package` initializer now requires the `name:` parameter.\n\n[SE-0129]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0129-package-manager-test-naming-conventions.md\n[SE-0135]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0135-package-manager-support-for-differentiating-packages-by-swift-version.md\n[SE-0201]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0201-package-manager-local-dependencies.md\n[SE-0208]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0208-package-manager-system-library-targets.md\n[SE-0209]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0209-package-manager-swift-lang-version-update.md\n[SE-0272]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0272-swiftpm-binary-dependencies.md\n[SE-0292]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0292-package-registry-service.md\n[SE-0303]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0303-swiftpm-extensible-build-tools.md\n[SE-0332]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0332-swiftpm-command-plugins.md\n[SE-0339]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0339-module-aliasing-for-disambiguation.md\n[SE-0362]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0362-piecemeal-future-features.md\n[SE-0378]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0378-package-registry-auth.md\n[SE-0386]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0386-package-access-modifier.md\n[SE-0387]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0387-cross-compilation-destinations.md\n[SE-0391]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md\n[SE-0387 proposal text]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0387-cross-compilation-destinations.md#swift-sdk-installation-and-configuration\n[SE-0458]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0458-strict-memory-safety.md\n[SR-5918]: https://bugs.swift.org/browse/SR-5918\n[SR-6978]: https://bugs.swift.org/browse/SR-6978\n[SR-13566]: https://bugs.swift.org/browse/SR-13566\n\n[#1485]: https://github.com/swiftlang/swift-package-manager/pull/1485\n[#1489]: https://github.com/swiftlang/swift-package-manager/pull/1489\n[#1604]: https://github.com/swiftlang/swift-package-manager/pull/1604\n[#2937]: https://github.com/swiftlang/swift-package-manager/pull/2937\n[#3280]: https://github.com/swiftlang/swift-package-manager/pull/3280\n[#3292]: https://github.com/swiftlang/swift-package-manager/pull/3292\n[#3310]: https://github.com/swiftlang/swift-package-manager/pull/3310\n[#3316]: https://github.com/swiftlang/swift-package-manager/pull/3316\n[#3410]: https://github.com/swiftlang/swift-package-manager/pull/3410\n[#3486]: https://github.com/swiftlang/swift-package-manager/pull/3486\n[#3641]: https://github.com/swiftlang/swift-package-manager/pull/3641\n[#3649]: https://github.com/swiftlang/swift-package-manager/pull/3649\n[#3670]: https://github.com/swiftlang/swift-package-manager/pull/3670\n[#3717]: https://github.com/swiftlang/swift-package-manager/pull/3717\n[#3890]: https://github.com/swiftlang/swift-package-manager/pull/3890\n[#3901]: https://github.com/swiftlang/swift-package-manager/pull/3901\n[#3942]: https://github.com/swiftlang/swift-package-manager/pull/3942\n[#4119]: https://github.com/swiftlang/swift-package-manager/pull/4119\n[#4131]: https://github.com/swiftlang/swift-package-manager/pull/4131\n[#4135]: https://github.com/swiftlang/swift-package-manager/pull/4135\n[#4168]: https://github.com/swiftlang/swift-package-manager/pull/4168\n[#5728]: https://github.com/swiftlang/swift-package-manager/pull/5728\n[#5810]: https://github.com/swiftlang/swift-package-manager/pull/5810\n[#5819]: https://github.com/swiftlang/swift-package-manager/pull/5819\n[#5874]: https://github.com/swiftlang/swift-package-manager/pull/5874\n[#5949]: https://github.com/swiftlang/swift-package-manager/pull/5949\n[#5892]: https://github.com/swiftlang/swift-package-manager/pull/5892\n[#5966]: https://github.com/swiftlang/swift-package-manager/pull/5966\n[#6060]: https://github.com/swiftlang/swift-package-manager/pull/6060\n[#6067]: https://github.com/swiftlang/swift-package-manager/pull/6067\n[#6111]: https://github.com/swiftlang/swift-package-manager/pull/6111\n[#6114]: https://github.com/swiftlang/swift-package-manager/pull/6114\n[#6144]: https://github.com/swiftlang/swift-package-manager/pull/6144\n[#6294]: https://github.com/swiftlang/swift-package-manager/pull/6294\n[#6185]: https://github.com/swiftlang/swift-package-manager/pull/6185\n[#6200]: https://github.com/swiftlang/swift-package-manager/pull/6200\n[#6276]: https://github.com/swiftlang/swift-package-manager/pull/6276\n[#6540]: https://github.com/swiftlang/swift-package-manager/pull/6540\n[#6663]: https://github.com/swiftlang/swift-package-manager/pull/6663\n[#7010]: https://github.com/swiftlang/swift-package-manager/pull/7010\n[#7101]: https://github.com/swiftlang/swift-package-manager/pull/7101\n[#7118]: https://github.com/swiftlang/swift-package-manager/pull/7118\n[#7201]: https://github.com/swiftlang/swift-package-manager/pull/7201\n[#7202]: https://github.com/swiftlang/swift-package-manager/pull/7202\n[#7507]: https://github.com/swiftlang/swift-package-manager/pull/7507\n[#7530]: https://github.com/swiftlang/swift-package-manager/pull/7530\n[#7535]: https://github.com/swiftlang/swift-package-manager/pull/7535\n[#7722]: https://github.com/swiftlang/swift-package-manager/pull/7722\n[#7741]: https://github.com/swiftlang/swift-package-manager/pull/7741\n[#7813]: https://github.com/swiftlang/swift-package-manager/pull/7813\n[#8301]: https://github.com/swiftlang/swift-package-manager/pull/8301\n[#8314]: https://github.com/swiftlang/swift-package-manager/pull/8314\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nif(POLICY CMP0091)\n  cmake_policy(SET CMP0091 NEW)\nendif()\n\ncmake_minimum_required(VERSION 3.24)\n\nlist(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)\n\nproject(SwiftPM LANGUAGES C Swift)\n\noption(BUILD_SHARED_LIBS \"Build shared libraries by default\" YES)\noption(FIND_PM_DEPS \"Search for all external Package Manager dependencies\" YES)\noption(SwiftPM_ENABLE_RUNTIME \"Build the runtime\" YES)\n\nset(CMAKE_Swift_LANGUAGE_VERSION 5)\nset(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)\nset(CMAKE_Swift_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY MultiThreadedDLL)\n\nset(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)\nset(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)\nset(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)\n\nset(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreadedDLL)\nset(CMAKE_POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS})\n\nif(FIND_PM_DEPS)\n  find_package(SwiftSystem CONFIG REQUIRED)\n  find_package(TSC CONFIG REQUIRED)\n\n  find_package(LLBuild CONFIG)\n  if(NOT LLBuild_FOUND)\n    find_package(LLBuild REQUIRED)\n  endif()\n\n  find_package(ArgumentParser CONFIG REQUIRED)\n  find_package(SwiftDriver CONFIG REQUIRED)\n  find_package(SwiftCollections CONFIG REQUIRED)\n  find_package(SwiftASN1 CONFIG REQUIRED)\n  find_package(SwiftCertificates CONFIG REQUIRED)\n  find_package(SwiftCrypto CONFIG REQUIRED)\n  find_package(SwiftToolsProtocols CONFIG REQUIRED)\n  find_package(SwiftBuild CONFIG REQUIRED)\nendif()\n\nfind_package(dispatch QUIET)\nfind_package(Foundation QUIET)\nfind_package(SQLite3 REQUIRED)\n\n# Enable `package` modifier for the whole package.\nadd_compile_options(\"$<$<COMPILE_LANGUAGE:Swift>:SHELL:-package-name swift_package_manager>\")\nif(CMAKE_SYSTEM_NAME STREQUAL FreeBSD)\n  link_directories(/usr/local/lib)\nendif()\n\nadd_subdirectory(BuildSupport/SwiftSyntax)\nadd_subdirectory(Sources)\nadd_subdirectory(cmake/modules)\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to Swift Package Manager\n\nThere are several types of contributions one can make. Bug fixes, documentation and enhancements that do not materially change the user facing semantics of Swift Package Manager should be submitted directly as PR.\n\nLarger changes that do materially change the semantics of Swift Package Manager (e.g. changes to the manifest format or behavior) are required to go through [Swift Evolution Process](https://github.com/swiftlang/swift-evolution/blob/main/process.md).\n\nTo see how previous evolution decisions for SwiftPM have been made and have some direction for the development of future features please check out the [Community Proposals](https://forums.swift.org/tag/packagemanager).\n\nFor more information about making contributions to the Swift project in general see [Swift Contribution Guide](https://swift.org/contributing/).\n\n## Reporting issues\n\nIssues are tracked using [SwiftPM GitHub Issue Tracker](https://github.com/swiftlang/swift-package-manager/issues).\n\nFill the following fields:\n\n* `Title`: A one line summary of the problem you're facing.\n* `Description`: The complete description of the problem. Be specific.\n* `Expected behavior`: How you expect SwiftPM to behave.\n* `Actual behavior` : What actually happens.\n* `Steps to reproduce`: Be specific, provide steps to reproduce the bug.\n* `Swift Package Manager version/commit hash` : With which version are you testing.\n* `Actual behavior` : What actually happens.\n* `Swift & OS version` : (output of `swift --version && uname -a`).\n\nPlease include a minimal example package which can reproduce the issue. The\nsample package can be attached with the report or you can include the URL of the\npackage hosted on places like GitHub.\nAlso, include the verbose logs by adding `--verbose` or `-v` after a subcommand.\nFor example:\n\n    $ swift build --verbose\n    $ swift package update --verbose\n\nIf the bug is with a generated Xcode project, include how the project was\ngenerated and the Xcode build log.\n\n## Setting up the development environment\n\nFirst, clone a copy of SwiftPM code from https://github.com/swiftlang/swift-package-manager.\n\nIf you are preparing to make a contribution you should fork the repository first and clone the fork which will make opening Pull Requests easier. See \"Creating Pull Requests\" section below.\n\nSwiftPM is typically built with a pre-existing version of SwiftPM present on the system, but there are multiple ways to setup your development environment:\n\n### Using Xcode (Easiest)\n\n1. Install Xcode from [https://developer.apple.com/xcode](https://developer.apple.com/xcode) (including betas!).\n2. Verify the expected version of Xcode was installed.\n3. Open SwiftPM's `Package.swift` manifest with Xcode.\n4. Use Xcode to inspect, edit, and build the code.\n5. Select the `SwiftPM-Package` scheme to run the tests from Xcode. Note that the `SwiftPM-Package`\nshould be built prior to running any other schemes. This is so the `PackageDescription` module can be\nbuilt and cached for use.\n\n### Using the Command Line\n\nIf you are using macOS and have Xcode installed, you can use Swift from the command line immediately.\n\nIf you are not using macOS or do not have Xcode installed, you need to download and install a toolchain.\n\n#### Installing a toolchain\n\n1. Download a toolchain from https://swift.org/download/\n2. Install it and verify the expected version of the toolchain was installed:\n\n**macOS**\n\n```bash\n$> export TOOLCHAINS=swift\n$> xcrun --find swift\n/Library/Developer/Toolchains/swift-latest.xctoolchain/usr/bin/swift\n$> swift package --version\nSwift Package Manager - Swift 5.3.0\n$> swift --version\nApple Swift version 5.3\n```\n\n**Linux**\n\n```bash\n$> export PATH=/path/to/swift-toolchain/usr/bin:\"${PATH}\"\n$> which swift\n/path/to/swift-toolchain/usr/bin/swift\n$> swift package --version\nSwift Package Manager - Swift 5.3.0\n$> swift --version\nApple Swift version 5.3\n```\n\nAlternatively, there are tools like [swiftly](https://github.com/swiftlang/swiftly) that can install and manage toolchains automatically. This repository has a file called `.swift-version` that will keep swiftly at the current recommended version of the toolchain for best results. The `swiftly install` command ensures that SwiftPM's in-use toolchain is installed on your system and ready for you to do your development work with the usual swift commands.\n\n```bash\nswiftly install\nswift build\nswift test\n```\n\n## Developing in the Linux devcontainer\n\nSwiftPM includes a devcontainer configuration that allows you to develop in a containerized environment with VS Code. This approach provides a consistent development environment with all necessary dependencies pre-installed, regardless of your host operating system.\n\n### Prerequisites\n\n1. Install [Visual Studio Code](https://code.visualstudio.com/)\n2. Install the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) for VS Code\n3. Install [Docker](https://www.docker.com/products/docker-desktop/) on your system\n\n### Opening the Project in a Container\n\n1. Clone the SwiftPM repository (if you haven't already)\n2. Open the SwiftPM folder in VS Code\n3. VS Code will detect the devcontainer configuration and prompt you to \"Reopen in Container\". Click this button to start building and opening the container\n   - Alternatively, you can press `F1`, type \"Dev Containers: Reopen in Container\", and press Enter\n4. Wait for the container to build and initialize (this may take a few minutes the first time)\n\n### What's Included in the Dev Container\n\nThe SwiftPM devcontainer is based on the `swiftlang/swift:nightly-main` Docker image and includes:\n\n- Swift nightly build from the main branch\n- Git\n- Common development utilities\n- VS Code Swift extension for syntax highlighting and language support\n- Debugging support with LLDB\n\n### Building and Testing in the Container\n\nOnce you've opened the project in VS Code, choose `> Dev Containers: Build and Reopen in Container` from the command pallete. Once the container finishes building it will open and you can develop as if you are on Linux using VS Code.\n\nAll the commands described in the \"Local Development\" section below will work in the container environment.\n\n## Local Development\n\nWith a Swift toolchain installed and the SwiftPM code cloned, you are ready to make changes and test them locally.\n\n### Building\n\n```bash\n$> swift build\n```\n\nA successful build will create a `.build/` directory with the following approximate structure:\n\n```\nartifacts\ncheckouts\ndebug\nrepositories\nx86_64-apple-macosx\n```\n\nBinary artifacts are located in `x86_64-apple-macosx/` when building on macOS,\nor the equivalent on other architectures and operating systems.\n\nThese binaries can be used to test the code modification. For example, to test the `swift package init` and `swift build` commands from the new SwiftPM artifacts in `.build/`:\n\n```bash\n$> cd /tmp && mkdir hello && cd hello\n$> /path/to/swiftpm/.build/x86_64-apple-macosx/debug/swift-package init\n$> /path/to/swiftpm/.build/x86_64-apple-macosx/debug/swift-build\n```\n\n### Testing\n\n```bash\n$> swift test\n```\n\nto run a single test:\n\n```bash\n$> swift test --filter PackageGraphTests.DependencyResolverTests/testBasics\n```\n\nOr another example, to run tests for the test targets BuildTests and WorkspaceTests, but skip some test cases:\n\n```bash\n$> swift test --filter BuildTests --skip BuildPlanTests --filter WorkspaceTests --skip InitTests\n```\n\nTo run the performance tests, enable them with an ENV variable:\n\n```bash\n$> export TSC_ENABLE_PERF_TESTS=1\n$> swift test -c release --filter PerformanceTests\n```\n\n### The bootstrap script\n\nThe bootstrap script is designed for building SwiftPM on systems that do not have Xcode or a toolchain installed.\nIt is used on bare systems to bootstrap the Swift toolchain (including SwiftPM), and as such not typically used outside the Swift team.\n\nThe bootstrap script requires having [CMake](https://cmake.org/) and [Ninja](https://ninja-build.org/) installed.\nPlease refer to the [_Get Started_ guide](https://github.com/apple/swift/blob/main/docs/HowToGuides/GettingStarted.md#installing-dependencies) on the Swift project repository for installation instructions.\n\nClone the following repositories beside the SwiftPM directory:\n\n1. [swift-argument-parser] and check out tag with the [latest version](https://github.com/apple/swift-argument-parser/tags).\n\n   For example, if the latest tag is 0.4.3:\n   ```sh\n   $> git clone https://github.com/apple/swift-argument-parser --branch 0.4.3\n   ```\n\n2. [swift-llbuild] as llbuild\n   ```sh\n   $> git clone https://github.com/apple/swift-llbuild llbuild\n   ```\n   > Note: Make sure the directory for llbuild is called \"llbuild\" and not \"swift-llbuild\".\n\n3. [swift-tools-support-core]\n   ```sh\n   $> git clone https://github.com/apple/swift-tools-support-core\n   ```\n\n4. [swift-driver]\n   ```sh\n   $> git clone https://github.com/apple/swift-driver\n   ```\n\n5. [swift-system] and check out tag with the [latest version](https://github.com/apple/swift-system/tags).\n\n    For example, if the latest tag is 1.0.0:\n    ```sh\n    $> git clone https://github.com/apple/swift-system --branch 1.0.0\n    ```\n\n6. [swift-collections] and check out tag with the [latest version](https://github.com/apple/swift-collections/tags).\n\n    For example, if the latest tag is 1.0.1:\n    ```sh\n    $> git clone https://github.com/apple/swift-collections --branch 1.0.1\n    ```\n\n7. [swift-crypto] and check out tag with the [latest version](https://github.com/apple/swift-crypto/tags).\n\n    For example, if the latest tag is 2.3.0:\n    ```sh\n    $> git clone https://github.com/apple/swift-crypto --branch 2.3.0\n    ```\n\n8. [swift-asn1]\n   ```sh\n   $> git clone https://github.com/apple/swift-asn1\n   ```\n\n9. [swift-certificates]\n   ```sh\n   $> git clone https://github.com/apple/swift-certificates\n   ```\n\n10. [swift-syntax]\n   ```sh\n   $> git clone https://github.com/swiftlang/swift-syntax\n   ```\n\n11. [swift-toolchain-sqlite]\n   ```sh\n   $> git clone https://github.com/swiftlang/swift-toolchain-sqlite\n   ```\n\n[swift-argument-parser]: https://github.com/apple/swift-argument-parser\n[swift-collections]: https://github.com/apple/swift-collections\n[swift-driver]: https://github.com/apple/swift-driver\n[swift-llbuild]: https://github.com/apple/swift-llbuild\n[swift-system]: https://github.com/apple/swift-system\n[swift-tools-support-core]: https://github.com/apple/swift-tools-support-core\n[swift-crypto]: https://github.com/apple/swift-crypto\n[swift-asn1]: https://github.com/apple/swift-asn1\n[swift-certificates]: https://github.com/apple/swift-certificates\n[swift-toolchain-sqlite]: https://github.com/swiftlang/swift-toolchain-sqlite\n[swift-syntax]: https://github.com/swiftlang/swift-syntax\n\n\n#### Building\n\n```bash\n$> Utilities/bootstrap build\n```\n\nSee \"Using the Command Line / Building\" section above for more information on how to test the new artifacts.\n\n#### Testing\n\n```bash\n$> Utilities/bootstrap test\n```\n\n## Working with Docker to build and test for Linux\n\nWhen developing on macOS and need to test on Linux, install\n[Docker](https://www.docker.com/products/docker-desktop) and\n[Docker compose](https://docs.docker.com/compose/install/) and\nuse the following docker compose commands:\n\nPrepare the underlying image with the selected Ubuntu and Swift versions:\n\n```bash\ndocker-compose \\\n  -f Utilities/docker/docker-compose.yaml \\\n  -f Utilities/docker/docker-compose.<os-version>.<swift-version>.yaml \\\n  build\n```\n\nStart an interactive shell session:\n\n```bash\ndocker-compose \\\n  -f Utilities/docker/docker-compose.yaml \\\n  -f Utilities/docker/docker-compose.<os-version>.<swift-version>.yaml \\\n  run --rm shell\n```\n\nBuild SwiftPM (using the pre-installed SwiftPM version).\n\n```bash\ndocker-compose \\\n  -f Utilities/docker/docker-compose.yaml \\\n  -f Utilities/docker/docker-compose.<os-version>.<swift-version>.yaml \\\n  run --rm build\n```\n\nTest SwiftPM (using the pre-installed SwiftPM version).\n\n```bash\ndocker-compose \\\n  -f Utilities/docker/docker-compose.yaml \\\n  -f Utilities/docker/docker-compose.<os-version>.<swift-version>.yaml \\\n  run --rm test\n```\n\nBuild SwiftPM using the bootstrap script:\n\n```bash\ndocker-compose \\\n  -f Utilities/docker/docker-compose.yaml \\\n  -f Utilities/docker/docker-compose.<os-version>.<swift-version>.yaml \\\n  run --rm bootstrap-build\n```\n\nTest SwiftPM using the bootstrap script:\n\n```bash\ndocker-compose \\\n  -f Utilities/docker/docker-compose.yaml \\\n  -f Utilities/docker/docker-compose.<os-version>.<swift-version>.yaml \\\n  run --rm bootstrap-test\n```\n\nNote there are several Linux and Swift versions options to choose from, e.g.:\n\n`docker-compose.1804.53.yaml` => Ubuntu 18.04, Swift 5.3\n\n`docker-compose.2004.54.yaml` => Ubuntu 20.04, Swift 5.4\n\n`docker-compose.2004.main.yaml` => Ubuntu 20.04, Swift nightly\n\n## Creating Pull Requests\n\n1. Fork: https://github.com/swiftlang/swift-package-manager\n2. Clone a working copy of your fork\n3. Create a new branch\n4. Make your code changes\n5. If a particular version of the Swift toolchain is needed then update the `.swift-version` file to that version (or use `swiftly use` to update it).\n6. Try to keep your changes (when possible) below 200 lines of code.\n7. We use [SwiftFormat](https://www.github.com/nicklockwood/SwiftFormat) to enforce code style. Please install and run SwiftFormat before submitting your PR, ideally isolating formatting changes only to code changed for the original goal of the PR. This will keep the PR diff smaller.\n8. Commit (include the Radar link or GitHub issue id in the commit message if possible and a description your changes). Try to have only 1 commit in your PR (but, of course, if you add changes that can be helpful to be kept aside from the previous commit, make a new commit for them).\n9. Push the commit / branch to your fork\n10. Make a PR from your fork / branch to `apple: main`\n11. While creating your PR, make sure to follow the PR Template providing information about the motivation and highlighting the changes.\n12. Reviewers are going to be automatically added to your PR\n13. Pull requests will be merged by the maintainers after it passes CI testing and receives approval from one or more reviewers. Merge timing may be impacted by release schedule considerations.\n\nBy submitting a pull request, you represent that you have the right to license\nyour contribution to Apple and the community, and agree by submitting the patch\nthat your contributions are licensed under the [Swift\nlicense](https://swift.org/LICENSE.txt).\n\nAfter a change is known not to cause regressions in the `main` branch, it may be considered for cherry-picking to the latest release branch depending on the release schedule. Cherry-picks require [a specific template to be followed](https://github.com/swiftlang/.github/blob/main/PULL_REQUEST_TEMPLATE/release.md) in PR description that consolidates information about the change necessary for inclusion in the release branch and provides risk evaluation for nominating the change.\n\n## Continuous Integration\n\nSwiftPM uses [swift-ci](https://ci.swift.org) infrastructure for its continuous integration testing. The bots can be triggered on pull-requests if you have commit access. Otherwise, ask one of the code owners to trigger them for you.\n\n\nThis is **required** before a pull-request can be merged.\n\n\nTo run just the self-hosted test suite (faster turnaround times so it can be used to get quick feedback) use:\n\n```\n@swift-ci please test self hosted\n```\n\nTo run the windows self-hosted suite, use:\n\n```\n@swift-ci please test self hosted windows\n```\n\nTo run the swift toolchain test suite including SwiftPM use:\n\n```\n@swift-ci please test\n```\n\nTo run the swift toolchain test suite against a specific platform use one of the following:\n\n```\n@swift-ci please test macos\n@swift-ci please test linux\n@swift-ci please test windows\n```\n\nTo run package compatibility test suite (validates we do not break 3rd party packages) use:\n\n```\n@swift-ci please test package compatibility\n```\n\n\n## Generating Documentation\n\nSwiftPM uses [DocC](https://github.com/apple/swift-docc) to generate some of its documentation (currently only the `PackageDescription` module). Documentation can be built using Xcode's GUI (Product → Build Documentation or `⌃⇧⌘D`) or manually:\n\n1. Build and dump the symbol graph metadata used to generate the documentation:\n\n```\nswift package dump-symbol-graph\n```\n\n2. Generate the documentation and start a local preview server to review your changes:\n\n```\nxcrun docc preview Sources/PackageDescription/PackageDescription.docc --additional-symbol-graph-dir .build/*/symbolgraph/\n```\n\nNote that this may generate documentation for multiple modules — the preview link for PackageDescription will typically be: http://localhost:8000/documentation/packagedescription\n\n## Advanced\n\n### Using Custom Swift Compilers\n\nSwiftPM needs the Swift compiler to parse `Package.swift` manifest files and to\ncompile Swift source files. You can use the `SWIFT_EXEC` and `SWIFT_EXEC_MANIFEST`\nenvironment variables to control which compiler to use for these operations.\n\n`SWIFT_EXEC_MANIFEST`: This variable controls which compiler to use for parsing\n`Package.swift` manifest files. The lookup order for the manifest compiler is:\n`SWIFT_EXEC_MANIFEST`, `swiftc` adjacent to the `swiftpm` binaries, then `SWIFT_EXEC`\n\n`SWIFT_EXEC`: This variable controls which compiler to use for compiling Swift\nsources. The lookup order for the sources' compiler is: `SWIFT_EXEC`, then `swiftc` adjacent\nto `swiftpm` binaries. This is also useful for Swift compiler developers when they\nwant to use a debug compiler with SwiftPM.\n\n```bash\n$> SWIFT_EXEC=/path/to/my/built/swiftc swift build\n```\n\n### Overriding the Path to the Runtime Libraries\n\nSwiftPM computes the path of its runtime libraries relative to where it is\ninstalled. This path can be overridden by setting the environment variable\n`SWIFTPM_CUSTOM_LIBS_DIR` to a directory containing the libraries, or a colon-separated list of\nabsolute search paths. SwiftPM will choose the first\npath which exists on disk. If none of the paths are present on disk, it will fall\nback to built-in computation.\n\n### Making changes in TSC targets\n\nSwiftPM uses [Tools Support Core](https://github.com/apple/swift-tools-support-core) (aka TSC) for many of its general purpose utilities. Changes in SwiftPM often require changes in TSC first. To coordinate changes, open a PR against TSC first, then a second one against SwiftPM pulling the correct TSC version.\n\n## Community and Support\n\nIf you want to connect with the Swift community you can:\n* Use Swift Forums: [https://forums.swift.org/c/development/SwiftPM](https://forums.swift.org/c/development/SwiftPM)\n* Contact the CODEOWNERS: https://github.com/swiftlang/swift-package-manager/blob/main/CODEOWNERS\n\n## Additional resources\n\n* `Swift.org` Contributing page\n[https://swift.org/contributing/](https://swift.org/contributing/)\n* License\n[https://swift.org/LICENSE.txt](https://swift.org/LICENSE.txt)\n* Code of Conduct\n[https://swift.org/community/#code-of-conduct](https://swift.org/community/#code-of-conduct)\n\n## Troubleshooting\n\n* If during `swift build` you encounter this error:\n```bash\n/../apple-repos/swift-package-manager/.build/checkouts/swift-driver/Sources/SwiftDriver/Explicit Module Builds/InterModuleDependencyGraph.swift:102:3: error: unknown attribute '_spi'\n  @_spi(Testing) public var isFramework: Bool\n  ^\n```\nMake sure you are using SwiftPM 5.3\n```bash\n$> swift package --version\nSwift Package Manager - Swift 5.3.0\n```\n* If during `swift build` you encounter this error:\n```bash\n/../swift-package-manager/Sources/PackageLoading/Target+PkgConfig.swift:84:36: error: type 'PkgConfigError' has no member 'prohibitedFlags'\n            error = PkgConfigError.prohibitedFlags(filtered.unallowed.joined(separator: \", \"))\n                    ~~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~\n```\nMake sure to update your TSC (Tools Support Core):\n```bash\n$> swift package update\n```\nAlternatively, if you are using Xcode, you can update to the latest version of all packages:\n**Xcode App** > *File* > *Swift Packages* > *Update to Latest Package Versions*\n"
  },
  {
    "path": "CONTRIBUTORS.txt",
    "content": "For the purpose of tracking copyright, this is the list of individuals and\norganizations who have contributed to Swift Package Manager.\n\nFor employees of an organization/company where the copyright of work done\nby employees of that company is held by the company itself, only the company\nneeds to be listed here.\n\n## COPYRIGHT HOLDERS\n\n- Apple Inc. (all contributors with '@apple.com')\n\n### Contributors\n\n- 3405691582 <dsk@google.com>\n- A Koufatzis <akoufa@gmail.com>\n- AG <acgarland@apple.com>\n- Aaron Crespo <aaroncrespo@users.noreply.github.com>\n- Abdulhakim Ajetunmobi <abdulrapidz@live.com>\n- Adam Cox <extreme.boredom@gmail.com>\n- Adam Thayer <user@biticus.net>\n- Adam Yanalunas <adamyanalunas@users.noreply.github.com>\n- Ahmad Yasser <42544598+ahmdyasser@users.noreply.github.com>\n- Alastair Houghton <ahoughton@apple.com>\n- Alejandro Alonso <alejandro_alonso@apple.com>\n- Aleksei Sapitskii <45671572+aleksproger@users.noreply.github.com>\n- Aleksey Mashanov <a.mashanov@corp.mail.ru>\n- Aleph Retamal <retamal.ph@gmail.com>\n- Alex Blewitt <alblue@apple.com>\n- Alex Hoppen <ahoppen@apple.com>\n- Alex Lorenz <arphaman@gmail.com>\n- Alex Migicovsky <migi@apple.com>\n- Alexander Sandberg <hi@alexandersandberg.com>\n- Alexey Ivashko <mcivashko@gmail.com>\n- Alexis Laferrière <alaf@apple.com>\n- Anders Bertelrud <anders@apple.com>\n- Andreas Koslowski <andreas@dock13.com>\n- Andrew Carter <acarter@flipboard.com>\n- Andrew Clark <acdlite@me.com>\n- Angelo Villegas <gelo.web@gmail.com>\n- Anh Pham <thuanhsone99@gmail.com>\n- Ankit Aggarwal <ankit_aggarwal@apple.com>\n- Anton <antonmes@users.noreply.github.com>\n- Anton Pogonets <apogonets@readdle.com>\n- Antonio Mayorga <amayorga95@outlook.com>\n- Argyrios Kyrtzidis <kyrtzidis@apple.com>\n- Ariel Elkin <1756909+arielelkin@users.noreply.github.com>\n- Aris Sarris <78614622+a-sarris@users.noreply.github.com>\n- Arjun Nayini <aanayini@gmail.com>\n- Arnold Schwaighofer <aschwaighofer@apple.com>\n- Artem Chikin <achikin@apple.com>\n- Artemiy Sobolev <avriy@me.com>\n- Arthur Ariel Sabintsev <arthur@sabintsev.com>\n- Atul Sowani <asowani@users.noreply.github.com>\n- Aura Lily Vulcano <millenomi@apple.com>\n- Austin <Austinpayne@users.noreply.github.com>\n- BJ Homer <bjhomer@gmail.com>\n- Bastian Rinsche <bastian.rinsche@gmail.com>\n- Ben Barham <b.n.barham@gmail.com>\n- Ben Chatelain <ben@octop.ad>\n- Ben Cohen <ben_cohen@apple.com>\n- Ben Kennedy <ben-github@zygoat.ca>\n- Ben Langmuir <blangmuir@apple.com>\n- Ben Rimmington <me@benrimmington.com>\n- Ben Waldie <benwaldie@apple.com>\n- BenedictSt <52418145+BenedictSt@users.noreply.github.com>\n- Benedikt Terhechte <terhechte@gmail.com>\n- Benjamin Herzog <benjamin_herzog@apple.com>\n- Benjamin Scholtysik <bscholtysik@apple.com>\n- Bhargav <bhargav.grlnk@gmail.com>\n- Bhargav Gurlanka <bhargav.grlnk@gmail.com>\n- Bob Flanagan <89808793+bflanagan-apple@users.noreply.github.com>\n- Bob Wilson <bob.wilson@apple.com>\n- Boris Bielik <h3sperian@gmail.com>\n- Boris Buegling <bbuegling@apple.com>\n- BossJue <240778488@qq.com>\n- Bouke Haarsma <bouke@haarsma.eu>\n- Braden Scothern <BradenScothern@gmail.com>\n- Brandon Titus <bjtitus@gmail.com>\n- Brent Royal-Gordon <brentdax@apple.com>\n- Brian Croom <bcroom@apple.com>\n- Brian Gesiak <modocache@gmail.com>\n- Brian Pratt <brian@8thlight.com>\n- Calvin Hill <mr_j.c.h@hotmail.com>\n- Chris Lattner <clattner@apple.com>\n- Chris Willmore <cwillmore@apple.com>\n- Chris Zielinski <chrisz@berkeley.edu>\n- Christian Rishøj <christian@rishoj.net>\n- Christopher Goulet <christophergoulet@outlook.com>\n- Clay Ellis <clayellis@me.com>\n- Colin Cornaby <colin.cornaby@mac.com>\n- Connor Wakamo <cwakamo@apple.com>\n- Conrad Kramer <conrad@kramerapps.com>\n- Cory Benfield <lukasa@apple.com>\n- Dadoum <24679280+Dadoum@users.noreply.github.com>\n- Damiaan Dufaux <damiaan@dpro.be>\n- Dan Liew <dliew@apple.com>\n- Dan Mendoza <footpad01@gmail.com>\n- Dan Zheng <danielzheng@google.com>\n- Daniel Duan <danmarner@gmail.com>\n- Daniel Dunbar <daniel_dunbar@apple.com>\n- Daniel Firsht <dfirsht@us.ibm.com>\n- Daniel Rodríguez Troitiño <drodriguez@users.noreply.github.com>\n- Danny Mösch <danny.moesch@icloud.com>\n- Dario Rexin <drexin@apple.com>\n- Dave Abrahams <dabrahams@apple.com>\n- Dave Weston <dave.weston@binocracy.com>\n- David Bryson <dmbryson@apple.com>\n- David Farler <dfarler@apple.com>\n- David Hart <david@hartbit.com>\n- David M. Bryson <dmbryson@apple.com>\n- David Nadoba <dnadoba@gmail.com>\n- David Ungar <dungar@apple.com>\n- Denis Morozov <dmorozkn@gmail.com>\n- Derik Ramirez <rderik@gmail.com>\n- Diggory Laycock <nospam@diggory.net>\n- Dima Hutsuliak <doberq@gmail.com>\n- Ding Ye <dingobye@gmail.com>\n- Dmitri Gribenko <gribozavr@gmail.com>\n- Dmitriy Borovikov <dmitry@borovikov.name>\n- Dmytro Mishchenko <narmdv5@gmail.com>\n- Doug Gregor <dgregor@apple.com>\n- Drew Crawford <drew@sealedabstract.com>\n- Ed Arenberg <arenberg@epage.com>\n- Edan Lichtenstein <edan@bricksimple.com>\n- Edward Huynh <edward@edwardhuynh.com>\n- Edward Valentini <edward@interlook.com>\n- Egor Zhdan <e_zhdan@apple.com>\n- Egor Zhdan <egor.zhdan@gmail.com>\n- Eli Geller <elitree@gmail.com>\n- Ellie Shin <ellie_shin@apple.com>\n- Eric Dudiak <dudiak@apple.com>\n- Eric Jensen <jensen39@gmail.com>\n- Eric Miotto <1094986+edymtt@users.noreply.github.com>\n- Erik Eckstein <eeckstein@apple.com>\n- Erwin Mazariegos <erwinmaza@gmail.com>\n- Etan1 <Etan1@users.noreply.github.com>\n- Euan Harris <euan+github@ardenwood.net>\n- Eugene Tulushev <eugene@tulushev.com>\n- Evan Wilde <etceterawilde@gmail.com>\n- Example Example <example@example.com>\n- Fabian Cañas <fcanas@gmail.com>\n- Federico Bucchi <b.federico@gmail.com>\n- Federico Zanetello <zntfdr@gmail.com>\n- Florian Friedrich <ffried@me.com>\n- Florian Reinhart <florian.reinhart@gmail.com>\n- Franz Busch <privat@franz-busch.de>\n- Gaushik M.R <gaushik126@gmail.com>\n- Gavin Eadie <gavin@umich.edu>\n- George <unknown>\n- George Barnett <gbarnett@apple.com>\n- Glenn 'devalias' Grant <glenn@ensquared.net>\n- Grzegorz Miłoś <gmilos@apple.com>\n- Guillermo Ignacio Enriquez Gutierrez <nacho4d@mac.com>\n- Gwen Mittertreiner <gwen.mittertreiner@gmail.com>\n- Harlan Haskins <harlan@apple.com>\n- Hayden McCabe <hayden@haydenmccabe.com>\n- Helge Hess <me@helgehess.eu>\n- Honza Dvorsky <honza@apple.com>\n- Husein Kareem <huseinkareem@gmail.com>\n- Ian Partridge <i.partridge@uk.ibm.com>\n- Ilya Kulakov <kulakov.ilya@gmail.com>\n- Ismael Vilas Boas <ismael.vb@gmail.com>\n- Itai Ferber <iferber@apple.com>\n- Iulian Onofrei <5748627+revolter@users.noreply.github.com>\n- IxhenHasaniQM <94111216+IxhenHasaniQM@users.noreply.github.com>\n- J. Cheyo Jimenez <cheyo@masters3d.com>\n- J.D. Healy <jdhealy@gmail.com>\n- JP Simard <jp@jpsim.com>\n- JPMartha <jpmartha.jp@gmail.com>\n- Jacob Bandes-Storch <jacob@bandes-stor.ch>\n- Jacopo Andrea Giola <jacopo@giola.org>\n- Jader Feijo <jader@gojimo.co.uk>\n- Jake Heiser <jake@quizlet.com>\n- Jake Petroules <jake.petroules@apple.com>\n- Jane Manchun Wong <wongmjane@users.noreply.github.com>\n- Jason Choi <jasonnoahchoi@gmail.com>\n- Jason R Tibbetts <708510+jrtibbetts@users.noreply.github.com>\n- Jason Wray <friedbunny@users.noreply.github.com>\n- Jeff Kelley <SlaunchaMan@gmail.com>\n- Jeff Lett <2142301+jeffctown@users.noreply.github.com>\n- Jeremiah Njoroge <jnjoroge@gmail.com>\n- Jeremy David Giesbrecht <jeremy.g@sasktel.net>\n- Jhonny Bill <jhonnybillm@gmail.com>\n- Jimmy Arts <arts.jimmy@gmail.com>\n- Jobins John <jobins666@gmail.com>\n- Joe Groff <jgroff@apple.com>\n- Joe Heck <heckj@mac.com>\n- Joe Smith <yasumoto7@gmail.com>\n- Joe Susnick <joesusnick@gmail.com>\n- Johannes Plunien <johannes@plunien.de>\n- Johannes Weiss <johannesweiss@apple.com>\n- John Holdsworth <github@johnholdsworth.com>\n- John McCall <rjmccall@apple.com>\n- Jonas Schwartz <jonas@josc.io>\n- Jonathan Grynspan <grynspan@me.com>\n- Jordan Rose <jordan_rose@apple.com>\n- Jose Marcelino <jmarcelino@users.noreply.github.com>\n- Joseph Heck <heckj@mac.com>\n- Josh Parnham <joshparnham@gmail.com>\n- Joshua Emmons <joshua@reverb.com>\n- Joshua Peek <josh@joshpeek.com>\n- Julian Grosshauser <julian@juliangrosshauser.com>\n- Justas Brazauskas <brazauskasjustas@gmail.com>\n- Justin Jia <justin.jia.developer@gmail.com>\n- Justin Oroz <Juice805@users.noreply.github.com>\n- Justus Kandzi <justus.kandzi@kitchenstories.de>\n- Kaan Dedeoglu <kaandedeoglu@me.com>\n- Karl <5254025+karwa@users.noreply.github.com>\n- Karoy Lorentey <klorentey@apple.com>\n- Kazumasa Wakamori <k.wakamori.shizuoka@gmail.com>\n- Keith Smiley <keithbsmiley@gmail.com>\n- Kenta Kubo <601636+kkk669@users.noreply.github.com>\n- Kilian Koeltzsch <kiliank@apple.com>\n- Kit Langton <kitlangton@gmail.com>\n- Kohki Miki <giginet.net@gmail.com>\n- Kostiantyn Koval <konstantin.koval1@gmail.com>\n- Kyle <43724855+Kyle-Ye@users.noreply.github.com>\n- Kyle <kyle201817146@gmail.com>\n- Kyle Jessup <kyle@perfect.org>\n- Kyle Rokita <kyle.rokita@gmail.com>\n- Lei Zhang <lzhang@ca.ibm.com>\n- Lev Walkin <lwalkin@apple.com>\n- Lily Vulcano <millenomi@apple.com>\n- Ling Wang <an00na@gmail.com>\n- Liu Liu <i@liuliu.me>\n- Lukas Stabe <lukas@stabe.de>\n- Luke Lau <luke_lau@icloud.com>\n- MIZUNO Hiroki <mzpppp@gmail.com>\n- Marcin Iwanicki <iwan@icode.pl>\n- Marcin Krzyzanowski <marcin@krzyzanowskim.com>\n- Marco Eidinger <eidingermarco@gmail.com>\n- Marin Todorov <marin@underplot.com>\n- Mark Brownsword <markbrownsword@gmail.com>\n- Mark Lacey <mark.lacey@apple.com>\n- Martin Waitz <tali@admingilde.org>\n- Matt Diephouse <matt@diephouse.com>\n- Matt Seaman <mseaman@apple.com>\n- Matthew Seaman <mattsdeveloper@gmail.com>\n- Matthias Bartelmeß <mba@fourplusone.de>\n- Mattt Thompson <mattt@me.com>\n- Max Desiatov <m_desiatov@apple.com>\n- Max Desiatov <max@desiatov.com>\n- Max Howell <max.howell@apple.com>\n- Max Liberman <max.y.liberman@gmail.com>\n- Max Moiseev <moiseev@apple.com>\n- Max Obermeier <themomax@icloud.com>\n- Michael Gottesman <mgottesman@apple.com>\n- Michael Henson <mikehenson@gmail.com>\n- Michael Ilseman <milseman@apple.com>\n- Michael McGuire <Michael.McGuire@gmail.com>\n- Michael Munday <mike.munday@ibm.com>\n- Michael Vendivel <mvendivel@us.ibm.com>\n- Miguel A. Perez Ojito <54909066+miggs597@users.noreply.github.com>\n- Miguel Salinas <mikeys@me.com>\n- Mike Ash <mikeash@apple.com>\n- Mike Ferris <mferris@apple.com>\n- Mishal Awadah <mawadah@apple.com>\n- Mishal Shah <mishal_shah@apple.com>\n- Morten Bjerg Gregersen <morten@mogee.dk>\n- Muhammed Yavuz Nuzumlali <manuyavuz@gmail.com>\n- Nate Cook <natecook@apple.com>\n- Nathan Hawes <nhawes@apple.com>\n- Nathan Lanza <nathan@lanza.io>\n- Natik Gadzhi <natik@respawn.io>\n- Neil Jones <futurejones@users.noreply.github.com>\n- Nicholas Maccharoli <nmaccharoli@gmail.com>\n- Nick Cooke <36927374+ncooke3@users.noreply.github.com>\n- Nikola Lajic <n.lajic@gmail.com>\n- Noah Gilmore <noah.w.gilmore@gmail.com>\n- NobodyNada <jkeller234@icloud.com>\n- Norio Nomura <norio.nomura@gmail.com>\n- Noé Froidevaux <noe@noefroidevaux.com>\n- Oliver Chick <orac@apple.com>\n- Oliver Epper <45991777+oliverepper@users.noreply.github.com>\n- Orta <orta.therox+github@gmail.com>\n- Ostap Taran <github@austinate.me>\n- Owen Voorhees <owen@squibner.com>\n- P W <patrick@subzero.eu>\n- Patrick Balestra <me@patrickbalestra.com>\n- Patrick Metcalfe <git@patrickmetcalfe.com>\n- Paul Nettle <nettlep@users.noreply.github.com>\n- Paulo Faria <paulo.faria.rl@gmail.com>\n- Pavel Yaskevich <pyaskevich@apple.com>\n- Pedro José Pereira Vieito <pvieito@gmail.com>\n- Peteous <erik.peterman@und.edu>\n- Peter Adams <pp_adams@apple.com>\n- Peter Matta <pet3r.matta@gmail.com>\n- Philippe Hausler <phausler@apple.com>\n- Prachi <prachi.pai@gmail.com>\n- Pritesh Nandgaonkar <pncooldude91@gmail.com>\n- Quinn McHenry <quinn@jqm.us>\n- Rahul Malik <rmalik@pinterest.com>\n- Randy Becker <81446220+randy-becker@users.noreply.github.com>\n- Rauhul Varma <rauhul@apple.com>\n- Renzo Crisóstomo <renzo.crisostomo@xing.com>\n- Rich Ellis <rich@richellis.net>\n- Rick Ballard <rballard@apple.com>\n- Rintaro Ishizaki <rishizaki@apple.com>\n- Ritwik Gupta <RitwikGupta@users.noreply.github.com>\n- Robert Widmann <devteam.codafi@gmail.com>\n- Romain Pouclet <code@romain-pouclet.com>\n- Roman Levenstein <rlevenstein@apple.com>\n- Ron Baker <ronbak@protonmail.com>\n- Ron Olson <tachoknight@gmail.com>\n- Runar <runhum@gmail.com>\n- Runar Hummelsund <runhum@users.noreply.github.com>\n- Ryan Lovelett <ryan@lovelett.me>\n- Ryan Wilson <wilsonryan@google.com>\n- Ryosuke Hayashi <hayashikun@hayashikun.com>\n- Saleem Abdulrasool <abdulras@thebrowser.company>\n- Saleem Abdulrasool <compnerd@compnerd.org>\n- Samuel Giddins <segiddins@segiddins.me>\n- Sebastian Grail <sgrail@gmail.com>\n- Sergio Campamá <scampama@apple.com>\n- Sheikh Bayazid <44797746+sheikhbayazid@users.noreply.github.com>\n- Slava Pestov <spestov@apple.com>\n- Stan Stadelman <sstadelman@gmail.com>\n- Stephen Brown <steveybrown@gmail.com>\n- Stephen Celis <stephen@stephencelis.com>\n- Steve Barron <sdbarron@users.noreply.github.com>\n- Steve Moser <contact@stevemoser.org>\n- Steven Sherry <steven.r.sherry@gmail.com>\n- Stuart Montgomery <smontgomery@apple.com>\n- Sven A. Schmidt <sas@finestructure.co>\n- Swiftfuchs <github@t-no.de>\n- TaborKelly <taborkelly+github@gmail.com>\n- Ted Kremenek <kremenek@apple.com>\n- Thi <t@thi.im>\n- Thiago Holanda <unnamedd@gmail.com>\n- Thomas Grapperon <35562418+tgrapperon@users.noreply.github.com>\n- Thomas Roughton <t.roughton@me.com>\n- Thomas Van Lenten <thomasvl@google.com>\n- Tiago Martinho <martinho@thoughtworks.com>\n- Tianyu Wang <i@cee.moe>\n- Tim Condon <0xTim@users.noreply.github.com>\n- Tim Gymnich <tgymnich@icloud.com>\n- Tobias Landsberg <TobiLandsberg@gmail.com>\n- Tokuriku <oeil.noir@gmail.com>\n- Tom Doron <tomer@apple.com>\n- Tomasz Bąk <me@tomaszbak.engineer>\n- Tomoya Kose <tomoya@mitsuse.jp>\n- Toni Suter <tonisuter@users.noreply.github.com>\n- Tony Arnold <tony@thecocoabots.com>\n- Tony Parker <anthony.parker@apple.com>\n- TornjV <tornjanski.veljko@gmail.com>\n- Trevör Anne Denise <trevor.annedenise@icloud.com>\n- Tyler Stromberg <tylers@mac.com>\n- Török Zsolt <torokzsolt91@gmail.com>\n- Vadim Eisenberg <vadime@il.ibm.com>\n- Vadim Smal <vvsmal@avito.ru>\n- Valeriy Van <valeriy.van@enote.com>\n- Vasilica Costescu <vasilica.costescu@gmail.com>\n- Vatsal Manot <vatsal.manot@yahoo.com>\n- Viktor Szilárd Simkó <aqviktor@gmail.com>\n- Vincent Esche <regexident@gmail.com>\n- Vivian Kong <vivkong@ca.ibm.com>\n- Vladislav Alekseev <beefon@users.noreply.github.com>\n- WFT <will.a.ft@gmail.com>\n- Wang Binbin <hellomsg_noreply@163.com>\n- William Dillon <william@housedillon.com>\n- William Entriken <github.com@phor.net>\n- Wojtek Czekalski <me@wczekalski.com>\n- Wowbagger & his liquid lunch <55120045+WowbaggersLiquidLunch@users.noreply.github.com>\n- Xavier Matos <matos.xav@gmail.com>\n- Xiaodi Wu <13952+xwu@users.noreply.github.com>\n- Xiaodi Wu <xiaodi.wu@gmail.com>\n- Xing He <17washabi@gmail.com>\n- YOCKOW <YOCKOW@users.noreply.github.com>\n- YOUNG MO SONG <77970826+mooyoung2309@users.noreply.github.com>\n- YR Chen <stevapple@icloud.com>\n- Yan Li <eyeplum@gmail.com>\n- Yannick Heinrich <yannick.heinrich@gmail.com>\n- Yim Lee <yim_lee@apple.com>\n- Yonas Kolb <yonaskolb@gmail.com>\n- Yoshimasa Niwa <niw@niw.at>\n- Yu Ao <YuAo@users.noreply.github.com>\n- Yu Su <ssuuyyuu@gmail.com>\n- YuAo <me@imyuao.com>\n- Yuta Koshizawa <koher@koherent.org>\n- Yuta Saito <kateinoigakukun@gmail.com>\n- Zsolt Kiraly <zkiraly@gmail.com>\n- adamnemecek <adamnemecek@gmail.com>\n- aemino <aeminodev@gmail.com>\n- akashhansda <99724223+akashhansda@users.noreply.github.com>\n- aniket sharma <aniket965.as@gmail.com>\n- badim <goloveychuk@mail.ru>\n- buttaface <butta@fastem.com>\n- dudiak <dudiak@mac.com>\n- eeckstein <eeckstein@apple.com>\n- elsh <ellie_shin@apple.com>\n- emlai <emil.laine@cs.helsinki.fi>\n- freak4pc <freak4pc@gmail.com>\n- futbalguy <kyle.rokita@gmail.com>\n- futurejones <futurejones@users.noreply.github.com>\n- gibachan <childhoodend.tk@gmail.com>\n- giginet <giginet.net@gmail.com>\n- givip <pataridzegivi@gmail.com>\n- goloveychuk <goloveychuk@users.noreply.github.com>\n- hotchemi <hot.chemistry21@gmail.com>\n- jhonnybillm <jhonnybillm@gmail.com>\n- jp_pancake <jpmartha@users.noreply.github.com>\n- k-kohey <kawagutsuchi@gmail.com>\n- linqingmo <mariopteris@foxmail.com>\n- naru <tus.naru@gmail.com>\n- nate-chandler <46721658+nate-chandler@users.noreply.github.com>\n- nathan spindel <nathans@gmail.com>\n- nonsensery <ajohnson@quickleft.com>\n- onevcat <onevcat@gmail.com>\n- pcbeard <pcbeard@mac.com>\n- prachipai <prachi.pai@gmail.com>\n- samding01 <samding@ca.ibm.com>\n- sarveshtamba <sarvesh.tamba@ibm.com>\n- seabaylea <baileyc@uk.ibm.com>\n- sora0077 <t.hayashi0077+github@gmail.com>\n- swift-ci <swift-ci@users.noreply.github.com>\n- swiftix <swiftix@users.noreply.github.com>\n- t_hayashi <t.hayashi0077+github@gmail.com>\n- thecb4 <cavelle@thecb4.io>\n- twobitunicorn <joseph.ruskiewicz@gmail.com>\n- uhooi <the_uhooi@yahoo.co.jp>\n- yonihemi <jonathan@hemi.dev>\n- Łukasz Mróz <lukasz.mroz@droidsonroids.pl>\n- Šimon Javora <s.javora@me.com>\n- ✪ vi4m Marcin Kliks <vi4m@users.noreply.github.com>\n- 冀卓疌 <55120045+WowbaggersLiquidLunch@users.noreply.github.com>\n\n\n**Updating this list**\n\nPlease do not edit this file manually. It is generated using `./Utilities/generate_contributors_list.sh`. If a name is misspelled or appearing multiple times: add an entry in `./.mailmap`\n"
  },
  {
    "path": "Documentation/Design/EvolutionIdeas.md",
    "content": "# Swift Package Manager Ideas\n\nThis is a list of some evolution ideas for the package manager. Once the details\nof an idea are fleshed out and there is a full proposal, it can be scheduled for\nthe Swift Evolution process. It is important to note that not every idea on this\nlist is guaranteed to become an official feature, and it all depends on where\nthe design discussion leads us. Also, this is not meant to be an exhaustive\nfeature list, if you have an idea for a feature that you think will be\na valuable addition to the package manager, feel free to start a discussion\nabout it.\n\nIf you're interested in participating in a particular evolution idea, please\nfamiliarize yourself with the existing discussion on that topic and start\nparticipating in the discussion thread of that idea. If a thread doesn't exist\nfor that idea, please start one with a [draft\nproposal](https://github.com/swiftlang/swift-evolution/blob/main/proposal-templates/0000-swiftpm-template.md)\nthat can be used as a starting point.\n\n**Important Note**: This list is not in any particular order. I plan to keep\nthis post updated, but please let me know if you see something out-of-date.\n\n## Mirror and Fork Support\n\nYou may want an easy way to mirror or fork specific packages in your package\ngraph. This could be useful if you want to make a private customization to\na package that you depend on, or even if you just want to override the origin\nrepository of your packages so that you can fetch from a private mirror and not\ndepend on the original repository always being there.\n\nThread: https://forums.swift.org/t/dependency-mirroring-and-forking/13902\nBug: [SR-679](https://bugs.swift.org/browse/SR-679)\n\n## Build Settings\n\nSome packages require specific language or linker flags that SwiftPM doesn’t\ncurrently support, and some packages may desire other configurable properties as\nwell. We want to have a real, robust \"build settings\" model for adding these\nkinds of properties, potentially including conditional settings and\nfine-grained control over what parts of the package use which property values.\n\nThread: N/A\nBug: [SR-3948](https://bugs.swift.org/browse/SR-3948)\n\n## Conditional Dependencies\n\nPackages may want to use dependencies that they only use while testing the\npackage. Such dependencies shouldn't take part in dependency resolution process\nwhen a package is being used as a dependency. This is also called test-only or\ndevelopment dependencies in other package managers. It is sometimes also\nrequired to declare platform-specific dependencies which should only be fetched\nwhen a package is being built for a certain platform. This is currently possible\nusing `#if os` checks, but it leads to two problems: 1) it forces\na non-declarative syntax in the manifest file, and 2) it causes issues in\nmaintaining the `Package.resolved` file as the dependency is added or removed\ndepending on the platform.\n\nThread: N/A\nBug: [SR-883](https://bugs.swift.org/browse/SR-883)\n\n## Resource Support\n\nThe Swift Package Manager needs a story for how packages should specify their\nresources to include with products.\n\nThread: N/A\nBug: [SR-2866](https://bugs.swift.org/browse/SR-2866)\n\n## Extensible Build Tools\n\nMany users want to incorporate a variety of build-time tools into their\npackages, whether to support a custom language or preprocessor, or to add their\nown documentation generator or linter. SwiftPM could add extensibility to\nsupport tools packages which could bring these steps to the build process. We\nexpect this behavior to greatly enhance our capacity for building complex\nsoftware packages.\n\nOne important thing for us to be careful about here is to make sure that all\nparts of the build process still clearly declare their inputs and outputs to\nSwiftPM, so that it can make sure that they behave correctly and perform well\nfor incremental and parallel builds.\n\nThread: https://forums.swift.org/t/package-manager-extensible-build-tools/10900\nBug: N/A\n\n## User-defined Template Support\n\nIt would be nice if users can hook into the init command to add custom templates\nthat they frequently use.\n\nThread: N/A\nBug: [SR-7837](https://bugs.swift.org/browse/SR-7837)\n\n## Documentation Generation Support\n\nWe can leverage SourceKit to extract documentation information from Swift\npackages that can be further transformed into a developer consumable format like\na static HTML website.\n\nThread: N/A\nBug: N/A\n\n## Tagging and Publishing Support\n\nToday you publish new versions of your package by tagging manually with Git, and\nyou use Git directly to view your published tags. SwiftPM could help automate\nthis process, performing any validation, housekeeping, or auxiliary tasks that\nmight make sense as part of a streamlined and safe publication workflow.\n\nThread: N/A\nBug: N/A\n\n## Install/Deploy Command\n\nWhen you’re deploying the product of your package, whether to a server or your\nlocal system, it could be helpful for SwiftPM to provide support for automating\nthat process. You may want to configure layout and library linkage aspects of\nyour products for your specific deployment environment, record version\ninformation about what your products were built from, and otherwise leverage the\ncontext that SwiftPM has about your packages for a seamless deployment\nexperience.\n\nThread: N/A\nBug: N/A\n\n## Performance Testing Support\n\nCurrently, SwiftPM has no support for running performance tests. We need to\nprovide a way to specify performance tests for a package and to run them from\nthe SwiftPM command-line tools.\n\n[Here](https://github.com/aciidb0mb3r/swift-evolution/blob/pref-proposal/proposals/xxxx-package-manager-performance-testing.md) is a very old draft proposal that I haven't gotten around to posting for discussion yet.\n\nThread: N/A\nBug: [SR-1354](https://bugs.swift.org/browse/SR-1354)\n\n## Support for External Testing Frameworks\n\nCurrently, SwiftPM only supports writing tests with help of the XCTest testing\nframework. The community should be able to use any testing framework of their\nchoice to test with SwiftPM. This feature will most likely depend on the proposed extensible\nbuild tools feature described [here](https://forums.swift.org/t/package-manager-extensible-build-tools/10900).\n\nThread: N/A\nBug: N/A\n\n## Package Index\n\nSwiftPM plans to have a real index for Swift packages some day. In addition to\ndefining a namespace for package names and providing easier package discovery,\nit could even support metrics for quality, such as automated test coverage\nstatistics, or ways to evaluate the trustworthiness of packages that you’re\nconsidering using. This will be a large project.\n\nThread: N/A\nBug: N/A\n\n## Multi-Package Repository Support\n\nCurrently the package manager requires that each package live at the root of\na Git repository. This means that you can't store multiple packages in the same\nrepository, or develop packages which locate each other in a filesystem-relative\nmanner without relying on Git. We need a proposal for how we would like to\nsupport this.\n\nThread: N/A\nBug: [SR-3951](https://bugs.swift.org/browse/SR-3951)\n\n## Cross-platform Sandboxing\n\nSandboxing is one way to help prevent `Package.swift` manifest evaluation and\nbuilds from escaping out into your system, either accidentally or deliberately.\nSwiftPM uses macOS's sandboxing technology already, but it would be great to\nbring this safety to other platforms.\n\nThread: N/A\nBug: N/A\n\n## Automatic Semantic Versioning\n\nAutomatically detecting what semantic version it looks like you should be\npublishing your changes with could be very helpful for package authors. SwiftPM\ncould do this by analyzing the source code's API to see what has changed and\nwhether the API is backwards-compatible, at least at compile time.\n\nThread: N/A\nBug: N/A\n\n## Machine-Editable Package.swift\n\nWe need an easy way to edit the Package.swift manifest from automated tools, for\ncases where you don't want users to have to update the Swift code directly. We\nthink that it's possible to provide an API to allow this, probably using\n[`SwiftSyntax`](https://github.com/swiftlang/swift-syntax).\n\nThread: N/A\nBug: N/A\n"
  },
  {
    "path": "Documentation/Design/README.md",
    "content": "# Swift Package Manager Design Docs\n\nSwift Package Manager design is done in open source, and governed by Swift Evolution process.\nAs such, you can find up-to-date Swift Package Manager design docs [in the Swift Evolution repository](https://github.com/swiftlang/swift-evolution/tree/main/proposals).\n\nThis directory contains documentation on the engineering design decisions and internals of the Swift Package Manager, outside the evolution process.\n"
  },
  {
    "path": "Documentation/Design/SwiftBasedManifestFormat.md",
    "content": "# Swift-based Manifest Format\n\n> **PLEASE NOTE** This document represents the initial proposal for Swift Package Manager, and is provided for historical purposes only. It does not represent the current state or future direction of the project. For current documentation, see the main Swift Package Manager [documentation](../README.md).\n\n## Purpose\n\nWe need to have some facility for describing additional package metadata, outside of the content in the sources files. This document describes a proposal for using a Swift-based format for this manifest data.\n\n\n## Motivation\n\nThe package manager strives to support a \"convention based\" project structure which is derived from the project files and source code. This approach allows users to primarily focus on authoring their actual software and expect that the tools will assemble it into a product by following sensible defaults.\n\nHowever, packages also have information which cannot naturally be inferred from the project structure. To that end, we need to support some kind of manifest which contains the additional project information.\n\nAt a high level, the primary purpose of this manifest is to:\n\n* Complement the convention based system.\n\n  The manifest complements the convention based system, by being the one definitive place to add any project metadata that would otherwise require the project to use a custom configuration. The goal is that 80%+ of projects should be able to use only a manifest and the convention based layout.\n\n  By allowing the manifest to extend and override a few key, carefully picked details of the convention based system, then we allow many more projects to use the system without needing to define complex conventions.\n\n* Provide package information in a standard format.\n\n  There are certain pieces of information which are important enough and common enough that we would like all projects to include, or any projects which do include them to do so in a standardized manner. For example, the license declaration of a project should follow a very standard definition.\n\n* Serve as an indicator of a package manager project.\n\n  Although it is simple, having the manifest exist with a known name at the root of a package serves as an indicator to developers and tools of the type of project and how they are expected to interact with it.\n\n* Provide support for programmatic analysis and editing of project structure.\n\n  The manifest should be machine readable and writeable format. We envision a variety of tools that may want to inspect the contents of packages (for example, to build information for an index) or make automatic edits to the project structure. For example, when introducing a new library dependency via adding an import statement, we would like it if a tool could, after a user prompt, automatically update the manifest to specify the new dependency.\n\n\n## Proposal\n\nWe propose to use the Swift language itself to write the manifest. An example of a proposed manifest for a small cross-platform project with several libraries might look something like this:\n\n```swift\n// This imports the API for declaring packages.\nimport PackageDescription\n\n// This declares the package.\nlet package = Package(\n    // The name of the package (defaults to source root directory name).\n    name: \"Foo\",\n\n    // The list of targets in the package.\n    targets: [\n        // Declares the main application.\n        Target(\n            name: \"Foo\",\n            // Declare the type of application.\n            type: .Tool,\n            // Declare that this target is a published product of the package\n            // (as opposed to an internal library or tool).\n            published: true),\n\n        // Add information on a support library \"CoreFoo\" (as found by the\n        // convention based system in CoreFoo/**/*.swift).\n        Target(\n            name: \"CoreFoo\",\n            depends: [\n                // The library always depends on the \"Utils\" target.\n                \"Utils\",\n\n                // This library depends on \"AccessibilityUtils\" on Linux.\n                .Conditional(name: \"AccessibilityUtils\", platforms: [.Linux])\n            ]),\n\n        // NOTE: There is a \"Utils\" target inferred by the convention based\n        // system, but we don't need to modify it at all because the defaults\n        // were fine.\n\n        // Declare that the \"AccessibilityUtils\" target is Linux-specific.\n        Target(name: \"AccessibilityUtils\", platforms: [.Linux])\n\t])\n```\n\n*NOTE: this example is for expository purposes, the exact APIs are subject to change.*\n\nBy writing the manifest in Swift, we ensure a consistent development experience across not only authoring their source code, but also their project metadata. This means developers will have a consistent environment with all of the development conveniences they expect: syntax coloring, code completion, API documentation, and formatting tools. This also ensures that new developers to Swift can focus on learning the language and its tools, not another custom package description format.\n\nThe package description itself is a declarative definition of information which *augments* the convention based system. The actual package definition that will be used for a project consists of the convention based package definition with the package description applied to override or customize default behaviors. For example, this target description:\n\n```swift\nTarget(name: \"AccessibilityUtils\", platforms: [.Linux])\n```\n\n*does not* add a new target. Rather, it modifies the existing target `AccessibilityUtils` to specify what platforms it is available for.\n\n\n## Customization\n\nWe intend for the declaration package definition to cover 80%+ of the use cases for modifying the convention based system. Nevertheless, there are some kinds of legitimate project structures which are difficult or cumbersome to encode in a purely declarative model. For example, designing a general purpose mechanism to cover all the ways in which users may wish to divide their source code is difficult.\n\nInstead, we allow users to interact with the `Package` object using its native Swift APIs. The package declaration in a file may be followed by additional code which configures the package using a natural, imperative, Swifty API. For example, this is an example of a project which uses a custom convention for selecting which files build with unchecked optimizations:\n\n```swift\nimport PackageDescription\n\nlet package = Package(name: \"FTW\")\n\n// MARK: Custom Configuration\n\n// Build all *_unchecked.swift files using \"-Ounchecked\" for Release mode.\nfor target in package.targets {\n    for source in target.sources {\n        if source.path.hasSuffix(\"_unchecked.swift\") {\n            source.customFlags += [.Conditional(\"-Ounchecked\", mode: .Release)\n        }\n    }\n}\n```\n\nIt is important to note that even when using this feature, package manifest still **must be** declarative. That is, the only output of a manifest is a complete description of the package, which is then operated on by the package manager and build tools. For example, a manifest **must not** attempt to do anything to directly interact with the build output. All such interactions must go through a documented, public API vended by the package manager libraries and surfaced via the package manager tools.\n\n\n## Editor Support\n\nThe package definition format being written in Swift is problematic for tools that wish to perform automatic updates to the file (for example, in response to a user action, or to bind to a user interface), or for situations where dealing with executable code is problematic.\n\nTo that end, the declarative package specification portion of the file is \"Swift\" in the same sense that \"JSON is Javascript\". The syntax itself is valid, executable, Swift but the tools that process it will only accept a restricted, declarative, subset of Swift which can be statically evaluated, and which can be unambiguously, automatically rewritten by editing tools. We do not intend to define a \"standard\" syntax for \"Swift Object Notation\", but we intend to accept a natural restriction of the language which only accepts literal expressions. We do intend to allow the restricted subset to take full advantage of Swift's rich type inference and literal convertible design to allow for a succinct, readable, and yet expressive syntax.\n\nThe customization section above will *not* be written in this syntax. Instead, the customization section will be clearly demarcated in the file. The leading file section up to the first '// MARK:' will be processed as part of the restricted declarative specification. All subsequent code **must be** honored by tools which only need to consume the output of the specification, and **should be** displayed by tools which present an editor view of the manifest, but **should not** be automatically modified. The semantics of the APIs will be specifically designed to accommodate the expected use case of editor support for the primary data with custom project-specific logic for special cases.\n\nAll tools which process the package manifest **must** validate that the declaration portion of the specification fits into the restricted language subset, to ensure a consistent user experience.\n\n\n## Implementation\n\nWe need to have efficient, programmatic access to the data from the manifest for use in the package manager and associated tools. Additionally, we may wish to use this data in contexts where the executable-code nature of the manifest format is problematic. On the other hand, we also want the file format to properly match the Swift language.\n\nTo satisfy these two goals, we intend to extract the package metadata from the manifest file by using the Swift parser **and** type checker to parse the leading package declaration portion of the file (not including any customizations made subsequent to the package definition). Once type checked, we will then validate the AST produced for the package description using custom logic which validates that the AST can (a) be parsed into validate model objects without needing to execute code, and (b) is written following the strict format such that it can be automatically modified by editing tools.\n\nTools that do not need to be as strict with the manifest format will be able to load it by using Swift directly to execute the file and then interact with the package definition API to extract the constructed model.\n\n\n## Discussion\n\nWe decided to use a Swift-based format for the manifest because we believe it gives developers the best experience for working with and describing their project. The primary alternative we considered was to use a declarative format encoded in a common data format like JSON. Although that would simplify implementation of the tooling around the manifest, it has the downside that users must then learn this additional language, and the development of high quality tools for that (documentation, syntax coloring, parsing diagnostics) isn't aligned with our goal of building great tools for Swift. In contrast, using the Swift language means that we can leverage all of the work on Swift to make those tools great.\n\nThe decision to use a restricted subset of Swift for the primary package definition is because we believe it is important that common tasks which require the manifest be able to be automated or surfaced via a user interface.\n\nWe decided to allow additional customization of the package via imperative code because we do not anticipate that the convention based system will be able to cover all possible uses cases. When users need to accommodate special cases, we want them to be able to do so using the most natural and expression medium, by writing Swift code. By explicitly designing in a customization system, we believe we will be able to deliver a higher quality set of core conventions -- there is an escape hatch for the special cases that allows us to focus on only delivering conventions (and core APIs) for the things that truly merit it.\n\nA common problem with systems that permit arbitrary customization (especially via a programmatic interface) is that they become difficult to maintain and evolve, since it is hard to predict how developers have taken advantage of the interface. We deal with this by requiring that the manifest only interact with the package and tools through a strict, well defined API. That is, even though we allow developers to write arbitrary code to construct their package, we do not allow arbitrary interactions with the build process. Viewed a different way, the output of *all* manifests **must be** able to be treated as a single declaration specification -- even if part of that specification was programmatically generated.\n"
  },
  {
    "path": "Documentation/PackageRegistry/PackageRegistryUsage.md",
    "content": "# Package Registry Usage\n\n## Table of Contents\n\n  * [Getting Started](#getting-started)\n    + [Configuring a registry](#configuring-a-registry)\n    + [Adding a registry package dependency](#adding-a-registry-package-dependency)\n    + [Registry authentication](#registry-authentication)\n  * [Dependency Resolution Using Registry](#dependency-resolution-using-registry)\n    + [Using registry for source control dependencies](#using-registry-for-source-control-dependencies)\n  * [Dependency Download From Registry](#dependency-download-from-registry)\n    + [Checksum TOFU](#checksum-tofu)\n    + [Validating signed packages](#validating-signed-packages)\n      - [Trusted vs. untrusted certificate](#trusted-vs-untrusted-certificate)\n      - [Certificate policies](#certificate-policies)\n      - [Publisher TOFU](#publisher-tofu)\n  * [Publishing to Registry](#publishing-to-registry)\n    + [Package release metadata](#package-release-metadata)\n    + [Package signing](#package-signing)\n      - [Signature formats](#signature-formats)\n      - [Signed contents](#signed-contents)\n        * [Source archive](#source-archive)\n        * [Package release metadata](#package-release-metadata-1)\n        * [Package manifest(s)](#package-manifest-s-)\n  * [SwiftPM Registry Configuration](#swiftpm-registry-configuration)\n    + [Registry-to-scope mappings](#registry-to-scope-mappings)\n      - [`swift package-registry set` subcommand](#-swift-package-registry-set--subcommand)\n    + [Security configuration](#security-configuration)\n\n## Getting Started\n\nSwiftPM supports downloading dependencies from any package registry that implements \n[SE-0292](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0292-package-registry-service.md)\nand the corresponding [service specification](Registry.md). \n\nIn a registry, packages are identified by [package identifier](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0292-package-registry-service.md#package-identity)\nin the form of `scope.package-name`.\n\n### Configuring a registry\n\nA registry can be configured in SwiftPM at two levels:\n - Project: the registry will be used for packages within the project. Settings are stored in `.swiftpm/configuration/registries.json`.\n - User: the registry will be used for all projects for the user. Settings are stored in `~/.swiftpm/configuration/registries.json`.\n\nOne could use the [`swift package-registry set` subcommand](#swift-package-registry-set-subcommand) \nto assign a registry URL:\n\n```bash\n$ swift package-registry set https://packages.example.com \n```\n\nThe above sets registry to `https://packages.example.com` at project level. Pass \nthe `--global` option to set registry at user level:\n\n```bash\n$ swift package-registry set --global https://packages.example.com \n```\n\nThe resulting `registries.json` would look something like:\n\n```json\n{\n  \"registries\" : {\n    \"[default]\" : {\n      \"url\": \"https://packages.example.com\"\n    }   \n  },\n  \"version\" : 1\n}\n```\n\nThe JSON key `[default]` means that the registry at `https://packages.example.com` is \n\"unscoped\" and will be applied when there is no registry association found for \na given scope. \n\nIn this example, `https://packages.example.com` will be applied to all scopes.\n\n### Adding a registry package dependency\n\nA registry package dependency is declared in `Package.swift` using the\npackage identifier. For example: \n\n```swift\ndependencies: [\n    .package(id: \"mona.LinkedList\", .upToNextMajor(from: \"1.0.0\")),\n],\n```\n\nSwiftPM will query the registry mapped to a package's scope to \nresolve and download the appropriate release version.  \n\n### Registry authentication\n\nIf a registry requires authentication, it can be set up by using the \n[`swift package-registry login` subcommand](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0378-package-registry-auth.md#new-login-subcommand)\nintroduced by SE-0378:\n\n```bash\n$ swift package-registry login\nOVERVIEW: Log in to a registry\n\nUSAGE: swift package-registry login [<url>] [--username <username>] [--password <password>] [--token <token>] [--no-confirm]\n\nARGUMENTS:\n  <url>                   The registry URL\n\nOPTIONS:\n  --username <username>   Username\n  --password <password>   Password\n  --token <token>         Access token\n  --no-confirm            Allow writing to netrc file without confirmation\n```\n\nCurrently, basic and token authentication are supported.\n\nProvide the credentials either by setting the corresponding options\n(i.e., one of username/password or access token) or when prompted:\n\n```bash\n$ swift package-registry login https://packages.example.com\n```\n\nSwiftPM will save the credentials to the operating system's credential store\n(e.g., Keychain in macOS) or netrc file (which by default is located at `~/.netrc`) \nand apply them automatically when making registry API requests.\n\n## Dependency Resolution Using Registry\n\nResolving a registry dependency involves these steps:\n1. Fetch a package's available versions by calling the [list package releases](Registry.md#41-list-package-releases) API.\n2. Compute the dependency graph by [fetching manifest(s) for a package release](Registry.md#43-fetch-manifest-for-a-package-release).\n3. Pinpoint the package version to use.\n\n### Using registry for source control dependencies \n\nHere is an example of a source control dependency:\n\n```swift\ndependencies: [\n    .package(url: \"https://github.com/mona/LinkedList\", .upToNextMajor(from: \"1.0.0\")),\n],\n```\n\nRegistry can be used for source control dependencies as well. This is \nparticularly useful when there is a \"mixed\" graph (i.e., a dependency \ngraph that has both source control and registry dependencies). SwiftPM\nconsiders packages with different origins to be different, so if a\npackage is referenced as both a registry (e.g., `mona.LinkedList`) and\nsource control (e.g., `https://github.com/mona/LinkedList`) dependency,\nthey are considered different even though they are the same package,\nand would result in symbol clashes.\n\nSwiftPM can deduplicate packages by performing a \n[lookup on the source control URL](Registry.md#endpoint-5)\n(e.g., `https://github.com/mona/LinkedList`) to see if it is associated with \nany package identifier (e.g., `mona.LinkedList`).\n\nOne can control if/how SwiftPM should use registry in conjunction with \nsource control dependencies by setting one of these flags:\n- `--disable-scm-to-registry-transformation` (default): SwiftPM will not transform source control dependency to registry dependency. Source control dependency will be downloaded from its corresponding URL, while registry dependency will be resolved and downloaded using the configured registry (if any).\n- `--use-registry-identity-for-scm`: SwiftPM will look up source control dependencies in the registry and use their registry identity whenever possible to help deduplicate packages across the two origins. In other words, suppose `mona.LinkedList` is the package identifier for `https://github.com/mona/LinkedList`, then SwiftPM will treat both references in the dependency graph as the same package. \n- `--replace-scm-with-registry`: SwiftPM will look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible. In other words, SwiftPM will attempt to download a source control dependency from the registry first, and fall back to cloning the source repository iff the dependency is not found in the registry.\n\n## Dependency Download From Registry\n\nAfter a registry dependency is resolved, SwiftPM can\n[download source archive](Registry.md#endpoint-4)\nof the computed package version from the registry.\n\n### Checksum TOFU \n\nSwiftPM performs checksum TOFU \n([trust-on-first-use](https://en.wikipedia.org/wiki/Trust_on_first_use)) \non the downloaded source archive. If the archive is downloaded\nfor the first time, SwiftPM \n[fetches metadata of the package release](Registry.md#endpoint-2)\nto obtain the expected checksum. Otherwise, SwiftPM\ncompares the checksum with that in local storage (`~/.swiftpm/security/fingerprints/`)\nsaved from previous download.\n\nIf checksum of the downloaded archive doesn't match the expected\nor previous value, SwiftPM will fail the build. This can be\ntuned down from error to warning by setting the build option \n`--resolver-fingerprint-checking` to `warn` (default is `strict`).\n\nChecksum TOFU is also done for manifests downloaded from registry. \n\n### Validating signed packages\n\n[SE-0391](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md#package-signing)\nadds package signing support to SwiftPM. SwiftPM determines if\na downloaded archive is signed by checking for presence of the\n`X-Swift-Package-Signature-Format` and `X-Swift-Package-Signature`\nheaders in the HTTP response.\n\nSwiftPM then performs a series of validations based on user's\n[security configuration](#security-configuration).\n- If the archive is unsigned, SwiftPM will error/prompt/warn/allow \nbased on the `signing.onUnsigned` configuration. \n- If the archive is signed, SwiftPM will validate the signature and\nthe signing certificate chain. (see the following sections for details)\n\n#### Trusted vs. untrusted certificate\n\nA certificate is trusted if it is chained to any root in SwiftPM's \ntrust store, which consists of:\n- SwiftPM's default trust store, if `signing.includeDefaultTrustedRootCertificates` is `true`.\n- Custom root(s) in the configured trusted roots directory at `signing.trustedRootCertificatesPath`. Certificates must be DER-encoded.\n\nOtherwise, a certificate is untrusted and handled according to the \n`signing.onUntrustedCertificate` configuration. If user opts to\ncontinue with the untrusted certificate, SwiftPM will proceed with\nthe archive as if it were an unsigned package.\n\n#### Certificate policies\n\nSwiftPM requires all certificates used for package signing to have \nthe \"code signing\" extended key usage extension. They must also \nsatisfy the core policies from \n[RFC 5280](https://www.rfc-editor.org/rfc/rfc5280), as implemented\nby [swift-certificates](https://github.com/apple/swift-certificates). \n\nUser can configure certificate expiry and revocation check \nthrough the `signing.validationChecks.certificateExpiration` \nand `signing.validationChecks.certificateRevocation` configuration,\nrespectively. Note that revocation check implicitly requires\nexpiry check.\n   \nAn invalid signing certificate would result in SwiftPM rejecting\nthe archive.\n\n#### Publisher TOFU\n\nSome certificates allow SwiftPM to extract additional information \nabout the signing identity. For packages signed with these certificates, \nSwiftPM will perform publisher TOFU to ensure the signer remains the \nsame across all versions of the package. \n\nThe `--resolver-signing-entity-checking` option controls whether publisher \nmismatch should result in a warning (`warn`) or error (`strict`). \nData used by publisher TOFU is saved to `~/.swiftpm/security/signing-entities/`.\n\n## Publishing to Registry\n\n[`swift package-registry publish`](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md#new-package-registry-publish-subcommand)\nis an all-in-one command for publishing a package release to registry:\n\n```bash\nOVERVIEW: Publish to a registry\n\nUSAGE: swift package-registry publish <package-id> <package-version> [--url <url>] [--scratch-directory <scratch-directory>] [--metadata-path <metadata-path>] [--signing-identity <signing-identity>] [--private-key-path <private-key-path>] [--cert-chain-paths <cert-chain-paths> ...] [--dry-run]\n\nARGUMENTS:\n  <package-id>            The package identifier.\n  <package-version>       The package release version being created.\n\nOPTIONS:\n  --url, --registry-url <url>\n                          The registry URL.\n  --scratch-directory <scratch-directory>\n                          The path of the directory where working file(s) will be written.\n  --metadata-path <metadata-path>\n                          The path to the package metadata JSON file if it is not 'package-metadata.json' in the package directory.\n  --signing-identity <signing-identity>\n                          The label of the signing identity to be retrieved from the system's identity store if supported.\n  --private-key-path <private-key-path>\n                          The path to the certificate's PKCS#8 private key (DER-encoded).\n  --cert-chain-paths <cert-chain-paths>\n                          Path(s) to the signing certificate (DER-encoded) and optionally the rest of the certificate chain. Certificates\n                          should be ordered with the leaf first and the root last.\n  --dry-run               Dry run only; prepare the archive and sign it but do not publish to the registry.\n```\n \nThe command creates source archive for the package release,\noptionally signs the package release, and \n[publishes the package release](Registry.md#endpoint-6)\nto the registry.\n\nIf authentication is required for package publication, \npackage author should [configure registry login](#registry-authentication)\nbefore running `publish`.\n\n### Package release metadata\n\nPackage author can specify a custom location of the package \nrelease metadata file by setting the `--metadata-path` option \nof the `publish` subcommand. Otherwise, by default SwiftPM \nlooks for a file named `package-metadata.json` in the \npackage directory.\n\nContents of the metadata file must conform to the \n[JSON schema](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md#package-release-metadata-standards)\ndefined in SE-0391. Also refer to registry documentation \nfor any additional requirements.\n \n### Package signing\n\nA registry may support or require signing. To sign a package\nrelease, package author will need to set either the `signing-identity`\n(for reading from operating system's identity store such as Keychain in macOS),\nor `private-key-path` and `cert-chain-paths` (for reading from files)\noptions of the `publish` subcommand such that SwiftPM can\nlocate the signing key and certificate.\n\nIf the certificate chain's root and intermediates are known by SwiftPM,\nthen package author would only need to provide the leaf signing\ncertificate in `cert-chain-paths`. \n\nOtherwise, the entire certificate chain should be provided as \n`cert-chain-paths` so that all of the certificates will be \nincluded in the signature and make it possible for SwiftPM \nto reconstruct the certificate chain for validation later. \nThis is applicable to `signing-identity` as well \n(i.e., `signing-identity` can be used in combination with \n`cert-chain-paths` to provide the entire certificate chain).\n\nIf the root of the signing certificate is not in SwiftPM's\ndefault trust store, package author is responsible for \ntelling package users to include the root certificate in their local \n[trust roots](#trusted-vs-untrusted-certificate) \ndirectory, or else [signature validation](#validating-signed-packages) \nmay fail upon download because the signing certificate is not trusted.\n\nRefer to registry documentation for its certificate policy.\n\n#### Signature formats\n\n| Signature Format | Specification |\n| ---------------- | ------------- |\n| `cms-1.0.0`      | [SE-391](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md#package-signature-format-cms-100) |\n\nSince there is only one supported signature format, all\nsignatures produced by SwiftPM are in `cms-1.0.0`.\n\n#### Signed contents\n\n##### Source archive\n\nThe signature is detached and sent as part of the HTTP request to the\npublish API. It is included in the source archive download response as\nHTTP headers, and is part of the package release metadata.\n\n##### Package release metadata\n\nThe signature is detached and sent as part of the HTTP request to the\npublish API. The current API specification does not include an endpoint\nfor fetching this metadata in its original form.\n\n##### Package manifest(s)\n\n`Package.swift` and version-specific manifests are individually signed.\nThe signature is embedded in the corresponding manifest file. The source\narchive is generated and signed **after** manifest signing. \n\n```swift\n// swift-tools-version: 5.7\n\nimport PackageDescription\nlet package = Package(\n    name: \"library\",\n    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n    targets: [ .target(name: \"library\") ]\n)\n\n// signature: cms-1.0.0;l1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\n```\n\nWhen a manifest is fetched from the registry, SwiftPM checks if the\ncontaining source archive is signed by fetching the package release \nmetadata. It is a failure if the source archive is signed but the \nmanifest is not. SwiftPM will extract and parse signature from \nthe manifest then validate it similar to what is done for \n[source archive signature](#validating-signed-packages).\n\nSwiftPM performs publisher TOFU to ensure it remains consistent\nfor the package. This implies the signer of manifests and source\narchive must be the same.\n\nTo reduce the amount of logging and thus noise, diagnostics related \nto manifest signature validation are set to DEBUG level. Only when \nuser chooses the `prompt` option for unsigned packages or packages \nsigned with an untrusted certificate would SwiftPM behave like \nsource archive validation.  \n\n## SwiftPM Registry Configuration\n\n### Registry-to-scope mappings\n\nWhen resolving or downloading registry packages, SwiftPM looks at the\nregistry-to-scope mappings in project and user-level configuration to\ndetermine which registry is assigned for a package's scope.\n\nFor example, given the following configuration files:\n\n```json\n// User-level configuration (~/.swiftpm/configuration/registries.json)\n{\n  \"registries\": {\n    \"[default]\": {\n      \"url\": \"https://global.example.com\"\n    },\n    \"foo\": {\n      \"url\": \"https://global.example.com\"\n    },\n  },\n  \"version\": 1\n}\n\n// Local configuration (.swiftpm/configuration/registries.json)\n{\n  \"registries\": {\n    \"foo\": {\n      \"url\": \"https://local.example.com\"\n    }\n  },\n  \"version\": 1\n}\n```\n\n- For package `foo.LinkedList`, the registry at `https://local.example.com` is used. (Local configuration has higher precedence than user-level configuration.)\n- For package `bar.LinkedList`, the registry at `https://global.example.com` is used. (No mapping for scope `bar` is found, so `[default]` is used.)\n\n#### `swift package-registry set` subcommand\n\n```bash\n$ swift package-registry set \nOVERVIEW: Set a custom registry\n\nUSAGE: swift package-registry set [--global] [--scope <scope>] <url>\n\nARGUMENTS:\n  <url>                   The registry URL\n\nOPTIONS:\n  --global                Apply settings to all projects for this user\n  --scope <scope>         Associate the registry with a given scope\n```\n\nThis subcommand is used to assign registry at project or user-level:\n\n```bash\n# project-level\n$ swift package-registry set https://packages.example.com \n\n# user-level\n$ swift package-registry set --global https://global.example.com \n```\n\nFor a specific scope:\n\n```bash\n# project-level\n$ swift package-registry set --scope foo https://local.example.com\n\n# user-level\n$ swift package-registry set --scope foo --global https://global.example.com  \n```\n\nTo remove a registry assignment, use the `swift package-registry unset` subcommand.\n  \n### Security configuration\n\nRegistry security configuration are specified in the user-level `registries.json`\n(`~/.swiftpm/configuration/registries.json`):\n\n```json\n{\n  \"security\": {\n    \"default\": {\n      \"signing\": {\n        \"onUnsigned\": \"prompt\", // One of: \"error\", \"prompt\", \"warn\", \"silentAllow\"\n        \"onUntrustedCertificate\": \"prompt\", // One of: \"error\", \"prompt\", \"warn\", \"silentAllow\"\n        \"trustedRootCertificatesPath\": \"~/.swiftpm/security/trusted-root-certs/\",\n        \"includeDefaultTrustedRootCertificates\": true,\n        \"validationChecks\": {\n          \"certificateExpiration\": \"disabled\", // One of: \"enabled\", \"disabled\"\n          \"certificateRevocation\": \"disabled\"  // One of: \"strict\", \"allowSoftFail\", \"disabled\"\n        }\n      }\n    },\n    \"registryOverrides\": {\n      // The example shows all configuration overridable at registry level\n      \"packages.example.com\": {\n        \"signing\": {\n          \"onUnsigned\": \"warn\",\n          \"onUntrustedCertificate\": \"warn\",\n          \"trustedRootCertificatesPath\": <STRING>,\n          \"includeDefaultTrustedRootCertificates\": <BOOL>,\n          \"validationChecks\": {\n            \"certificateExpiration\": \"enabled\",\n            \"certificateRevocation\": \"allowSoftFail\"\n          }\n        }\n      }\n    },\n    \"scopeOverrides\": {\n      // The example shows all configuration overridable at scope level\n      \"mona\": {\n        \"signing\": {\n          \"trustedRootCertificatesPath\": <STRING>,\n          \"includeDefaultTrustedRootCertificates\": <BOOL>\n        }\n      }\n    },\n    \"packageOverrides\": {\n      // The example shows all configuration overridable at package level\n      \"mona.LinkedList\": {\n        \"signing\": {\n          \"trustedRootCertificatesPath\": <STRING>,\n          \"includeDefaultTrustedRootCertificates\": <BOOL>\n        }\n      }\n    }\n  },\n  ...\n}\n```\n\nThere are multiple levels of overrides. Configuration for a \npackage is computed using values from the following \n(in descending precedence):\n1. `packageOverrides` (if any)\n1. `scopeOverrides` (if any)\n1. `registryOverrides` (if any)\n1. `default`\n\nThe `default` JSON object in the example above contains all \nconfigurable security options and their default value when \nthere is no override.\n\n- `signing.onUnsigned`: Indicates how SwiftPM will handle an unsigned package.\n\n  | Option        | Description                                               |\n  | ------------- | --------------------------------------------------------- |\n  | `error`       | SwiftPM will reject the package and fail the build. |\n  | `prompt`      | SwiftPM will prompt user to see if the unsigned package should be allowed. <ul><li>If no, SwiftPM will reject the package and fail the build.</li><li>If yes and the package has never been downloaded, its checksum will be stored for [checksum TOFU](#checksum-tofu). Otherwise, if the package has been downloaded before, its checksum must match the previous value or else SwiftPM will reject the package and fail the build.</li></ul> SwiftPM will record user's response to prevent repetitive prompting. |\n  | `warn`        | SwiftPM will not prompt user but will emit a warning before proceeding. |\n  | `silentAllow` | SwiftPM will allow the unsigned package without prompting user or emitting warning. |\n\n- `signing.onUntrustedCertificate`: Indicates how SwiftPM will handle a package signed with an [untrusted certificate](#trusted-vs-untrusted-certificate).\n\n  | Option        | Description                                               |\n  | ------------- | --------------------------------------------------------- |\n  | `error`       | SwiftPM will reject the package and fail the build. |\n  | `prompt`      | SwiftPM will prompt user to see if the package signed with an untrusted certificate should be allowed. <ul><li>If no, SwiftPM will reject the package and fail the build.</li><li>If yes, SwiftPM will proceed with the package as if it were an unsigned package.</li></ul> SwiftPM will record user's response to prevent repetitive prompting. |\n  | `warn`        | SwiftPM will not prompt user but will emit a warning before proceeding. |\n  | `silentAllow` | SwiftPM will allow the package signed with an untrusted certificate without prompting user or emitting warning. |\n\n- `signing.trustedRootCertificatesPath`: Absolute path to the directory containing custom trusted roots. SwiftPM will include these roots in its [trust store](#trusted-vs-untrusted-certificate), and certificates used for package signing must chain to roots found in this store. This configuration allows override at the package, scope, and registry levels.\n- `signing.includeDefaultTrustedRootCertificates`: Indicates if SwiftPM should include default trusted roots in its [trust store](#trusted-vs-untrusted-certificate). This configuration allows override at the package, scope, and registry levels.\n- `signing.validationChecks`: Validation check settings for the package signature.\n\n  | Validation               | Description                                               |\n  | ------------------------ | --------------------------------------------------------------- |\n  | `certificateExpiration`  | <ul><li>`enabled`: SwiftPM will check that the current timestamp when downloading falls within the signing certificate's validity period. If it doesn't, SwiftPM will reject the package and fail the build.</li><li>`disabled`: SwiftPM will not perform this check.</li></ul> |\n  | `certificateRevocation`  | With the exception of `disabled`, SwiftPM will check revocation status of the signing certificate. Currently, SwiftPM only supports revocation check done through [OCSP](https://www.rfc-editor.org/rfc/rfc6960).<ul><li>`strict`: Revocation check must complete successfully and the certificate must be in good status. SwiftPM will reject the package and fail the build if the revocation status is revoked or unknown (including revocation check not supported or failed).</li><li>`allowSoftFail`: SwiftPM will reject the package and fail the build iff the certificate has been revoked. SwiftPM will allow the certificate's revocation status to be unknown (including revocation check not supported or failed).</li><li>`disabled`: SwiftPM will not perform this check.</li></ul> |\n"
  },
  {
    "path": "Documentation/PackageRegistry/Registry.md",
    "content": "# Swift Package Registry Service Specification\n\n- [1. Notations](#1-notations)\n- [2. Definitions](#2-definitions)\n- [3. Conventions](#3-conventions)\n  - [3.1. Application layer protocols](#31-application-layer-protocols)\n  - [3.2. Authentication](#32-authentication)\n  - [3.3. Error handling](#33-error-handling)\n  - [3.4. Rate limiting](#34-rate-limiting)\n  - [3.5. API versioning](#35-api-versioning)\n  - [3.6. Package identification](#36-package-identification)\n    - [3.6.1 Package scope](#361-package-scope)\n    - [3.6.2. Package name](#362-package-name)\n- [4. Endpoints](#4-endpoints)\n  - [4.1. List package releases](#41-list-package-releases)\n  - [4.2. Fetch information about a package release](#42-fetch-information-about-a-package-release)\n    - [4.2.1. Package release resources](#421-package-release-resources)\n    - [4.2.2. Package release metadata standards](#422-package-release-metadata-standards)\n  - [4.3. Fetch manifest for a package release](#43-fetch-manifest-for-a-package-release)\n    - [4.3.1. swift-version query parameter](#431-swift-version-query-parameter)\n  - [4.4. Download source archive](#44-download-source-archive)\n    - [4.4.1. Integrity verification](#441-integrity-verification)\n    - [4.4.2. Download locations](#442-download-locations)\n    - [4.4.3. Signature validation](#443-signature-validation)\n  - [4.5. Lookup package identifiers registered for a URL](#45-lookup-package-identifiers-registered-for-a-url)\n    - [4.5.1 URL to package identifier mappings](#451-url-to-package-identifier-mappings)\n  - [4.6. Create a package release](#46-create-a-package-release)\n    - [4.6.1. Source archive](#461-source-archive)\n    - [4.6.2. Package release metadata](#462-package-release-metadata)\n    - [4.6.3. Synchronous and asynchronous publication](#463-synchronous-and-asynchronous-publication)\n      - [4.6.3.1. Synchronous publication](#4631-synchronous-publication)\n      - [4.6.3.2. Asynchronous publication](#4632-asynchronous-publication)\n- [5. Normative References](#5-normative-references)\n- [6. Informative References](#6-informative-references)\n- [Appendix A - OpenAPI Document](#appendix-a---openapi-document)\n- [Appendix B - Package Release Metadata JSON Schema](#appendix-b---package-release-metadata-json-schema)\n\n## 1. Notations\n\nThe following terminology and conventions are used in this document.\n\nThe key words \"MUST\", \"MUST NOT\", \"REQUIRED\", \"SHALL\", \"SHALL NOT\",\n\"SHOULD\", \"SHOULD NOT\", \"RECOMMENDED\", \"MAY\", and \"OPTIONAL\"\nin this document are to be interpreted as described in [RFC 2119].\n\nThis specification uses the Augmented Backus-Naur Form (ABNF) notation\nas described in [RFC 5234]\nand Unicode regular expression syntax\nas described in [Unicode Technical Standard #18][UAX18].\n\nAPI endpoints that accept parameters in their path\nare expressed by Uniform Resource Identifier (URI) templates,\nas described in [RFC 6570].\n\n## 2. Definitions\n\nThe following terms, as used in this document, have the meanings indicated.\n\n- _Package_:\n  A named collection of Swift source code\n  that is organized into one or more modules\n  according to a `Package.swift` manifest file.\n- _Scope_:\n  A logical grouping of related packages assigned by a package registry.\n- _Release_:\n  The state of a package after applying a particular set of changes\n  that is uniquely identified by an assigned version number.\n- _Version Number_:\n  An identifier for a package release\n  in accordance with the [Semantic Versioning Specification (SemVer)][SemVer].\n- _Precedence_:\n  The ordering of version numbers relative to each other\n  as defined by the [Semantic Versioning Specification (SemVer)][SemVer].\n\n## 3. Conventions\n\nThis document uses the following conventions\nin its description of client-server interactions.\n\n### 3.1. Application layer protocols\n\nA client and server MUST communicate over a secured connection\nusing Transport Layer Security (TLS) with the `https` URI scheme.\n\nThe use of HTTP 1.1 in examples is non-normative.\nA client and server MAY communicate according to this specification\nusing any version of the HTTP protocol.\n\n### 3.2. Authentication\n\nA server MAY require authentication\nfor client requests to access information about packages and package releases.\n\nA server SHOULD respond with a status code of `401` (Unauthorized)\nif a client sends a request to an endpoint that requires authentication\nwithout providing credentials.\nA server MAY respond with a status code of `404` (Not Found) or `403` (Forbidden)\nwhen a client provides valid credentials\nbut isn't authorized to access the requested resource.\n\nA server MAY use any authentication model of its choosing.\nHowever, the use of a scoped, revocable authorization framework\nlike [OAuth 2.0][RFC 6749] is RECOMMENDED.\n\n### 3.3. Error handling\n\nA server MUST communicate any errors to the client\nusing \"problem details\" objects,\nas described by [RFC 7807].\nFor example,\na client sends a request for a nonexistent release of a package\nand receives the following response:\n\n```http\nHTTP/1.1 404\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"release not found\"\n}\n```\n\n### 3.4. Rate limiting\n\nA server MAY limit the number of requests made by a client\nby responding with a status code of `429` (Too Many Requests).\n\n```http\nHTTP/1.1 429\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\nRetry-After: 60\n\n{\n   \"detail\": \"try again in 60 seconds\"\n}\n```\n\nA client SHOULD follow the guidance of any\n`Retry-After` header values provided in responses\nto prevent overwhelming a server with retry requests.\nIt is RECOMMENDED for clients to introduce random jitter in their retry logic\nto avoid a [thundering herd effect].\n\n### 3.5. API versioning\n\nPackage registry APIs are versioned.\n\nAPI version numbers are designated by decimal integers.\nThe accepted version of this proposal constitutes the initial version, `1`.\nSubsequent revisions SHOULD be numbered sequentially\n(`2`, `3`, and so on).\n\nAPI version numbers SHOULD follow\nSemantic Versioning conventions for major releases.\nNon-breaking changes, such as\nadding new endpoints,\nadding new optional parameters to existing endpoints,\nor adding new information to existing endpoints in a backward-compatible way,\nSHOULD NOT require a new version.\nBreaking changes, such as\nremoving or changing an existing endpoint\nin a backward-incompatible way,\nMUST correspond to a new version.\n\nA client SHOULD set the `Accept` header field\nto specify the API version of a request.\n\n```http\nGET /mona/LinkedList/list HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+json\n```\n\nValid `Accept` header field values are described by the following rules:\n\n```abnf\n    version     = \"1\"       ; The API version\n    mediatype   = \"json\" /  ; JSON (default media type)\n                  \"zip\"  /  ; Zip archives, used for package releases\n                  \"swift\"   ; Swift file, used for package manifest\n    accept      = \"application/vnd.swift.registry\" [\".v\" version] [\"+\" mediatype]\n```\n\nA server MUST set the `Content-Type` header field\nwith the corresponding content type of the response.\n\nA server MUST set the `Content-Version` header field\nwith the API version number of the response, unless\nexplicitly stated otherwise.\n\n```http\nHTTP/1.1 200 OK\nContent-Type: application/json\nContent-Version: 1\n```\n\nIf a client sends a request without an `Accept` header,\na server MAY either respond with a status code of `400 Bad Request` or\nprocess the request using an API version that it chooses,\nmaking sure to set the `Content-Type` and `Content-Version` headers accordingly.\n\nIf a client sends a request with an `Accept` header\nthat specifies an unknown or invalid API version,\na server SHOULD respond with a status code of `400` (Bad Request).\n\n```http\nHTTP/1.1 400 Bad Request\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"invalid API version\"\n}\n```\n\nIf a client sends a request with an `Accept` header\nthat specifies a valid but unsupported API version,\na server SHOULD respond with a status code of `415` (Unsupported Media Type).\n\n```http\nHTTP/1.1 415 Unsupported Media Type\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"unsupported API version\"\n}\n```\n\n### 3.6. Package identification\n\nA package may declare external packages as dependencies in its manifest.\nEach package dependency may specify a requirement\non which versions are allowed.\n\nAn external package dependency may itself have\none or more external package dependencies,\nknown as <dfn>transitive dependencies</dfn>.\nWhen multiple packages have dependencies in common,\nSwift Package Manager determines which version of that package should be used\n(if any exist that satisfy all specified requirements)\nin a process called <dfn>package resolution</dfn>.\n\nEach external package is uniquely identified\nby a scoped identifier in the form `scope.package-name`.\n\n#### 3.6.1 Package scope\n\nA *scope* provides a namespace for related packages within a package registry.\nA package scope consists of alphanumeric characters and hyphens.\nHyphens may not occur at the beginning or end,\nnor consecutively within a scope.\nThe maximum length of a package scope is 39 characters.\nA valid package scope matches the following regular expression pattern:\n\n```regexp\n\\A[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}\\z\n```\n\nPackage scopes are case-insensitive\n(for example, `mona` ≍ `MONA`).\n\n#### 3.6.2. Package name\n\nA package's *name* uniquely identifies a package in a scope.\nA package name consists of alphanumeric characters, underscores, and hyphens.\nHyphens and underscores may not occur at the beginning or end,\nnor consecutively within a name.\nThe maximum length of a package name is 100 characters.\nA valid package name matches the following regular expression pattern:\n\n```regexp\n\\A[a-zA-Z0-9](?:[a-zA-Z0-9]|[-_](?=[a-zA-Z0-9])){0,99}\\z\n```\n\nPackage names are case-insensitive\n(for example, `LinkedList` ≍ `LINKEDLIST`).\n\n## 4. Endpoints\n\nA server MUST respond to the following endpoints:\n\n| Link                 | Method | Path                                                      | Description                                       |\n| -------------------- | ------ | --------------------------------------------------------- | ------------------------------------------------- |\n| [\\[1\\]](#endpoint-1) | `GET`  | `/{scope}/{name}`                                         | List package releases                             |\n| [\\[2\\]](#endpoint-2) | `GET`  | `/{scope}/{name}/{version}`                               | Fetch metadata for a package release              |\n| [\\[3\\]](#endpoint-3) | `GET`  | `/{scope}/{name}/{version}/Package.swift{?swift-version}` | Fetch manifest for a package release              |\n| [\\[4\\]](#endpoint-4) | `GET`  | `/{scope}/{name}/{version}.zip`                           | Download source archive for a package release     |\n| [\\[5\\]](#endpoint-5) | `GET`  | `/identifiers{?url}`                                      | Lookup package identifiers registered for a URL   |\n| [\\[6\\]](#endpoint-6) | `PUT`  | `/{scope}/{name}/{version}`                               | Create a package release                          |\n\nA server SHOULD also respond to `HEAD` requests\nfor each of the specified endpoints.\n\nA client MAY send an `OPTIONS` request with an asterisk (`*`)\nto determine the permitted communication options for the server.\nA server MAY respond with a `Link` header containing\nan entry for the `service-doc` relation type\nwith a link to this document, and\nan entry for the `service-desc` relation type\nwith a link to the OpenAPI specification.\n\n* * *\n\n<a name=\"endpoint-1\"></a>\n\n### 4.1. List package releases\n\nA client MAY send a `GET` request\nfor a URI matching the expression `/{scope}/{name}`\nto retrieve a list of the available releases for a particular package.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+json`\nand MAY append the `.json` extension to the requested URI.\n\n```http\nGET /mona/LinkedList HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+json\n```\n\nIf a package is found at the requested location,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `application/json`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\nA server SHOULD respond with a JSON document\ncontaining the releases for the requested package.\n\n```http\nHTTP/1.1 200 OK\nContent-Type: application/json\nContent-Version: 1\nContent-Length: 508\nLink: <https://github.com/mona/LinkedList>; rel=\"canonical\",\n      <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n      <https://packages.example.com/mona/LinkedList/1.1.1>; rel=\"latest-version\",\n      <https://github.com/sponsors/mona>; rel=\"payment\"\n\n{\n    \"releases\": {\n        \"1.1.1\": {\n            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.1\"\n        },\n        \"1.1.0\": {\n            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.0\",\n            \"problem\": {\n                \"status\": 410,\n                \"title\": \"Gone\",\n                \"detail\": \"this release was removed from the registry\"\n            }\n        },\n        \"1.0.0\": {\n            \"url\": \"https://packages.example.com/mona/LinkedList/1.0.0\"\n        }\n    }\n}\n```\n\nThe response body MUST contain a JSON object\nnested at a top-level `releases` key,\nwhose keys are version numbers for releases and\nwhose values are objects containing the following fields:\n\n| Key       | Type   | Description                           | Requirement Level |\n| --------- | ------ | ------------------------------------- | ----------------- |\n| `url`     | String | The location of the release resource. | OPTIONAL          |\n| `problem` | Object | A [problem details][RFC 7807] object. | OPTIONAL          |\n\nA server MAY specify a URL for a release using the `url` key.\nA client SHOULD locate a release using the value of the `url` key, if one is provided.\nOtherwise, the client SHOULD locate a release\nby expanding the URI Template `/{scope}/{name}/{version}` on the originating host.\n\nA server SHOULD communicate the unavailability of a package release\nusing a [\"problem details\"][RFC 7807] object.\nA client SHOULD consider any releases with an associated `problem`\nto be unavailable for the purposes of package resolution.\n\nA server SHOULD respond with\na link to the highest precedence published release of the package if one exists,\nusing a `Link` header field with a `latest-version` relation.\n\nA server SHOULD list releases in order of precedence,\nstarting with the highest precedence version.\nHowever, a client SHOULD NOT assume\nany specific ordering of versions in a response.\n\nA server MAY include a `Link` entry\nwith the `canonical` relation type\nthat locates the source repository of the package.\n\nA server MAY include one or more `Link` entries\nwith the `alternate` relation type\nfor other source repository locations.\n\nA server MAY paginate results by responding with\na `Link` header field that includes any of the following relations:\n\n| Name    | Description                             |\n| ------- | --------------------------------------- |\n| `next`  | The immediate next page of results.     |\n| `last`  | The last page of results.               |\n| `first` | The first page of results.              |\n| `prev`  | The immediate previous page of results. |\n\nFor example,\nthe `Link` header field in a response for the third page of paginated results:\n\n```http\nLink: <https://packages.example.com/mona/HashMap/5.0.3>; rel=\"latest-version\",\n      <https://packages.example.com/mona/HashMap?page=1>; rel=\"first\",\n      <https://packages.example.com/mona/HashMap?page=2>; rel=\"previous\",\n      <https://packages.example.com/mona/HashMap?page=4>; rel=\"next\",\n      <https://packages.example.com/mona/HashMap?page=10>; rel=\"last\"\n```\n\nA server MAY respond with additional `Link` entries,\nsuch as one with a `payment` relation for sponsoring a package maintainer.\n\n<a name=\"endpoint-2\"></a>\n\n### 4.2. Fetch information about a package release\n\nA client MAY send a `GET` request\nfor a URI matching the expression `/{scope}/{name}/{version}`\nto retrieve information about a release.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+json`,\nand MAY append the `.json` extension to the requested URI.\n\n```http\nGET /mona/LinkedList/1.1.1 HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+json\n```\n\nIf a release is found at the requested location,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `application/json`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\n```http\nHTTP/1.1 200 OK\nContent-Version: 1\nContent-Type: application/json\nContent-Length: 720\nLink: <https://packages.example.com/mona/LinkedList/1.1.1>; rel=\"latest-version\",\n      <https://packages.example.com/mona/LinkedList/1.0.0>; rel=\"predecessor-version\"\n{\n  \"id\": \"mona.LinkedList\",\n  \"version\": \"1.1.1\",\n  \"resources\": [\n    {\n      \"name\": \"source-archive\",\n      \"type\": \"application/zip\",\n      \"checksum\": \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\",\n      \"signing\": {\n        \"signatureBase64Encoded\": \"l1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\",\n        \"signatureFormat\": \"cms-1.0.0\"\n      }\n    }\n  ],\n  \"metadata\": { ... },\n  \"publishedAt\": \"2023-02-16T04:00:00.000Z\"\n}\n```\n\nThe response body SHOULD contain a JSON object containing the following fields:\n\n| Key           | Type   | Description                               | Required |\n| ------------- | ------ | ----------------------------------------- | :------: |\n| `id`          | String | The namespaced package identifier.        | ✓ |\n| `version`     | String | The package release version number.       | ✓ |\n| `resources`   | Array  | The resources available for the release.  | ✓ |\n| `metadata`    | Object | Additional information about the release. | ✓ |\n| `publishedAt` | String | The [ISO 8601]-formatted datetime string of when the package release was published, as recorded by the registry. See related [`originalPublicationTime`](#appendix-b---package-release-metadata-json-schema) in `metadata`. | |\n\nA server SHOULD respond with a `Link` header containing the following entries:\n\n| Relation              | Description                                                                          |\n| --------------------- | ------------------------------------------------------------------------------------ |\n| `latest-version`      | The highest precedence published release of the package                              |\n| `successor-version`   | The next published release of the package ordered by precedence, if one exists       |\n| `predecessor-version` | The previously published release of the package ordered by precedence, if one exists |\n\nA link with the `latest-version` relation\nMAY correspond to the requested release.\n\n#### 4.2.1. Package release resources\n\nEach element in the `resources` array is a JSON object with the following keys:\n\n| Key        | Type    | Description                                                                |\n| ---------- | ------- | -------------------------------------------------------------------------- |\n| `name`     | String  | The name of the resource.                                                  |\n| `type`     | String  | The content type of the resource.                                          |\n| `checksum` | String  | A hexadecimal representation of the SHA256 digest for the resource.        |\n| `signing`  | Object  | Information about the signature. Required only if the resource is signed.  |\n\nThe `signing` JSON object contains these keys:\n\n| Key                      | Type    | Description                                       |\n| ------------------------ | ------- | ------------------------------------------------- |\n| `signatureBase64Encoded` | String  | The resource's signature, base64 encoded.         |\n| `signatureFormat`        | String  | The signature format. (e.g., `cms-1.0.0`)         |\n\nA resource object SHOULD have one of the following combinations of\n`name` and `type` values:\n\n| Name               | Content Type      | Description                        |\n| ------------------ | ----------------- | ---------------------------------- |\n| `source-archive`   | `application/zip` | An archive of package sources.     |\n\nA release MUST NOT have more than a single resource object\nwith a given combination of `name` and `type` values.\n\n#### 4.2.2. Package release metadata standards\n\n[Appendix B](#appendix-b---package-release-metadata-json-schema)\ndefines the JSON schema for package release metadata that\ngets submitted as part of the [\"create a package release\"](#endpoint-6)\nrequest. A server MAY allow and/or populate additional metadata by\nexpanding the schema. The `metadata` key in the\n[\"fetch information about a package release \"](#endpoint-2) API response\nwill hold the user-provided as well as the server populated metadata.\n\n<a name=\"endpoint-3\"></a>\n\n### 4.3. Fetch manifest for a package release\n\nA client MAY send a `GET` request for a URI matching the expression\n`/{scope}/{name}/{version}/Package.swift`\nto retrieve the package manifest for a release.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+swift`.\n\n```http\nGET /mona/LinkedList/1.1.1/Package.swift HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+swift\n```\n\nIf a release is found at the requested location,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `text/x-swift`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\n```http\nHTTP/1.1 200 OK\nCache-Control: public, immutable\nContent-Type: text/x-swift\nContent-Disposition: attachment; filename=\"Package.swift\"\nContent-Length: 361\nContent-Version: 1\nLink: <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4>; rel=\"alternate\"; filename=\"Package@swift-4.swift\"; swift-tools-version=\"4.0\",\n      <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4.2>; rel=\"alternate\"; filename=\"Package@swift-4.2.swift\"; swift-tools-version=\"4.2\"\n\n// swift-tools-version:5.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"LinkedList\",\n    products: [\n        .library(name: \"LinkedList\", targets: [\"LinkedList\"])\n    ],\n    targets: [\n        .target(name: \"LinkedList\"),\n        .testTarget(name: \"LinkedListTests\", dependencies: [\"LinkedList\"]),\n    ],\n    swiftLanguageVersions: [.v4, .v5]\n)\n```\n\nA server SHOULD respond with a `Content-Length` header\nset to the size of the manifest in bytes.\n\nA server SHOULD respond with a `Content-Disposition` header\nset to `attachment` with a `filename` parameter equal to\nthe name of the manifest file\n(for example, \"Package.swift\").\n\nA server MAY omit the `Content-Version` header\nsince the response content (i.e., the manifest) SHOULD NOT\nchange across different API versions.\n\nIt is RECOMMENDED for clients and servers to support\ncaching as described by [RFC 7234].\n\nA server MUST include a `Link` header field\nwith a value for each version-specific package manifest file\nin the release's source archive,\nwhose filename matches the following regular expression pattern:\n\n```regexp\n\\APackage@swift-(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?.swift\\z\n```\n\nEach link value SHOULD have the `alternate` relation type,\na `filename` attribute set to the version-specific package manifest filename\n(for example, `Package@swift-4.swift`), and\na `swift-tools-version` attribute set to the [Swift tools version]\nspecified by the package manifest file\n(for example, `4.0` for a manifest beginning with the comment\n`// swift-tools-version:4.0`).\n\n#### 4.3.1. swift-version query parameter\n\nA client MAY specify a `swift-version` query parameter\nto request a manifest for a particular version of Swift.\n\n```http\nGET /mona/LinkedList/1.1.1/Package.swift?swift-version=4.2 HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+swift\n```\n\nIf the package includes a file named\n`Package@swift-{swift-version}.swift`,\nthe server SHOULD respond with a status code of `200` (OK)\nand the content of that file in the response body.\n\n```http\nHTTP/1.1 200 OK\nCache-Control: public, immutable\nContent-Type: text/x-swift\nContent-Disposition: attachment; filename=\"Package@swift-4.2.swift\"\nContent-Length: 361\nContent-Version: 1\n\n// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"LinkedList\",\n    products: [\n        .library(name: \"LinkedList\", targets: [\"LinkedList\"])\n    ],\n    targets: [\n        .target(name: \"LinkedList\"),\n        .testTarget(name: \"LinkedListTests\", dependencies: [\"LinkedList\"]),\n    ],\n    swiftLanguageVersions: [.v3, .v4]\n)\n```\n\nOtherwise,\nthe server SHOULD respond with a status code of `303` (See Other)\nand redirect to the unqualified `Package.swift` resource.\n\n```http\nHTTP/1.1 303 See Other\nContent-Version: 1\nLocation: https://packages.example.com/mona/LinkedList/1.1.1/Package.swift\n```\n\n<a name=\"endpoint-4\"></a>\n\n### 4.4. Download source archive\n\nA client MAY send a `GET` request\nfor a URI matching the expression `/{scope}/{name}/{version}.zip`\nto retrieve a release's source archive.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+zip`\nand MUST append the `.zip` extension to the requested path.\n\n```http\nGET /mona/LinkedList/1.1.1.zip HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+zip\n```\n\nIf a release is found at the requested location,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `application/zip`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\n```http\nHTTP/1.1 200 OK\nAccept-Ranges: bytes\nCache-Control: public, immutable\nContent-Type: application/zip\nContent-Disposition: attachment; filename=\"LinkedList-1.1.1.zip\"\nContent-Length: 2048\nContent-Version: 1\nDigest: sha-256=oqxUzyX7wa0AKPA/CqS5aDO4O7BaFOUQiSuyfepNyBI=\nLink: <https://mirror-japanwest.example.com/mona-LinkedList-1.1.1.zip>; rel=duplicate; geo=jp; pri=10; type=\"application/zip\"\nX-Swift-Package-Signature-Format: cms-1.0.0\nX-Swift-Package-Signature: l1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\n```\n\nA server MUST respond with a `Content-Length` header\nset to the size of the archive in bytes.\nA client SHOULD terminate any requests whose response exceeds\nthe expected content length.\n\nA server MAY respond with a `Digest` header\ncontaining a cryptographic digest of the source archive.\n\nA server SHOULD respond with a `Content-Disposition` header\nset to `attachment` with a `filename` parameter equal to the name of the package\nfollowed by a hyphen (`-`), the version number, and file extension\n(for example, \"LinkedList-1.1.1.zip\").\n\nA server MAY omit the `Content-Version` header\nsince the response content (i.e., the source archive) SHOULD NOT\nchange across different API versions.\n\nIt is RECOMMENDED for clients and servers to support\nrange requests as described by [RFC 7233]\nand caching as described by [RFC 7234].\n\nIf a release is signed, a server MUST include\n`X-Swift-Package-Signature-Format` and `X-Swift-Package-Signature`\nheaders in the response.\n\n#### 4.4.1. Integrity verification\n\nA client MUST verify the integrity of a downloaded source archive using\nthe `checksum` value for the associated `source-archive` resource\nin the response to `GET /{scope}/{name}/{version}`,\nas described in [4.2.1](#421-package-release-resources).\n\nA client SHOULD also verify the integrity using any values\nprovided in the `Digest` header of the source archive response\n(for using the command\n`shasum -b -a 256 LinkedList-1.1.1.zip | cut -f1 | xxd -r -p | base64`).\n\n#### 4.4.2. Download locations\n\nA server MAY specify mirrors or multiple download locations\nusing `Link` header fields\nwith a `duplicate` relation,\nas described by [RFC 6249].\nA client MAY use this information\nto determine its preferred strategy for downloading.\n\nA server MAY respond with a status code of `303` (See Other)\nto redirect the client to download the source archive from another host.\nThe client MUST NOT follow redirects that downgrade to an insecure connection.\nThe client SHOULD limit the number of redirects to prevent a redirect loop.\n\nFor example,\na server redirects the client to download from\na content delivery network (CDN) using a signed URL:\n\n```http\nHTTP/1.1 303 See Other\nLocation: https://example.cdn.com/LinkedList-1.1.1.zip?key=XXXXXXXXXXXXXXXXX\n```\n\n```http\nGET /LinkedList-1.1.1.zip?key=XXXXXXXXXXXXXXXXX HTTP/1.1\nHost: example.cdn.com\nAccept: application/vnd.swift.registry.v1+zip\n```\n\n```http\nHTTP/1.1 200 OK\nAccept-Ranges: bytes\nCache-Control: public, immutable\nContent-Type: application/zip\nContent-Disposition: attachment; filename=\"LinkedList-1.1.1.zip\"\nContent-Length: 2048\nContent-Version: 1\nDigest: sha-256=a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\n```\n\n#### 4.4.3. Signature validation\n\nA client MUST validate the signature of a signed archive\naccording to the signature format and configuration. Signing\ninformation can alternatively be found in the associated\n`source-archive` resource in the response to `GET /{scope}/{name}/{version}`,\nas described in [4.2.1](#421-package-release-resources).\n\n<a name=\"endpoint-5\"></a>\n\n### 4.5. Lookup package identifiers registered for a URL\n\nA client MAY send a `GET` request\nfor a URI matching the expression `/identifiers?url={url}`\nto retrieve package identifiers associated with a particular URL.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+json`.\n\n```http\nGET /identifiers?url=https://github.com/mona/LinkedList HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1\n```\n\nA client MUST provide a URL for the `url` query parameter.\nWhen no `url` parameter is specified,\na server SHOULD respond with a status code of `400` (Bad Request).\n\nIf one or more package identifiers are associated with the specified URL,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `application/json`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\nA server SHOULD respond with a JSON document\ncontaining the package identifiers for the specified URL.\n\n```http\nHTTP/1.1 200 OK\nContent-Type: application/json\nContent-Version: 1\n\n{\n    \"identifiers\": [\n      \"mona.LinkedList\"\n    ]\n}\n```\n\nThe response body MUST contain an array of package identifier strings\nnested at a top-level `identifiers` key.\n\nIt is RECOMMENDED for clients and servers to support\ncaching as described by [RFC 7234].\n\n#### 4.5.1 URL to package identifier mappings\n\nAs part of the [package release metadata](#422-package-release-metadata-standards)\nJSON object, the `repositoryURLs` array can be used to specify\nURLs associated with a package identifier. This is one way\nthrough which a server can obtain URL to package identifier\nmappings for this API.\n\nA server MAY choose other mechanism(s) for package authors\nto specify these mappings.\n\nA server SHOULD validate the package author's ownership claim\non the corresponding repository.\n\n<a name=\"endpoint-6\"></a>\n\n### 4.6. Create a package release\n\nA client MAY send a `PUT` request\nfor a URI matching the expression\n`/{scope}/{name}/{version}`\nto publish a release of a package.\nA client MUST provide a body encoded as multipart form data\nwith the following sections:\n\n| Key                        | Content-Type               | Description                               | Requirement Level |\n| -------------------------- | -------------------------- | ----------------------------------------- | ----------------- |\n| `source-archive`           | `application/zip`          | The source archive of the package.        | REQUIRED          |\n| `source-archive-signature` | `application/octet-stream` | The signature of the source archive.      | OPTIONAL          |\n| `metadata`                 | `application/json`         | Additional information about the release. | OPTIONAL          |\n| `metadata-signature`       | `application/octet-stream` | The signature of the metadata.            | OPTIONAL          |\n\nA client MUST set a `Content-Type` header with the value\n`multipart/form-data`. `boundary` can be any string.\n\nA client MAY use any valid value (e.g., `binary`) for the\n`Content-Transfer-Encoding` header.\n\nA client SHOULD set the `Content-Length` header with\nthe total size of the body in bytes.\n\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+json`.\n\nA client MUST set a `X-Swift-Package-Signature-Format` header\nwith the signature format if the source archive is signed.\n\n```http\nPUT /mona/LinkedList/1.1.1 HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+json\nContent-Type: multipart/form-data;boundary=\"boundary\"\nContent-Length: 336\nExpect: 100-continue\nX-Swift-Package-Signature-Format: cms-1.0.0\n\n--boundary\nContent-Disposition: form-data; name=\"source-archive\"\nContent-Type: application/zip\nContent-Length: 32\nContent-Transfer-Encoding: base64\n\ngHUFBgAAAAAAAAAAAAAAAAAAAAAAAA==\n\n--boundary\nContent-Disposition: form-data; name=\"source-archive-signature\"\nContent-Type: application/octet-stream\nContent-Length: 88\nContent-Transfer-Encoding: base64\n\nl1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\n\n--boundary\nContent-Disposition: form-data; name=\"metadata\"\nContent-Type: application/json\nContent-Transfer-Encoding: quoted-printable\nContent-Length: 3\n\n{ \"repositoryURLs\": [] }\n\n--boundary\nContent-Disposition: form-data; name=\"metadata-signature\"\nContent-Type: application/octet-stream\nContent-Length: 88\nContent-Transfer-Encoding: base64\n\nM6TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\n\n```\n\nA server SHOULD require a client to perform authentication\nfor any requests to create a package release.\nUse of multi-factor authentication is RECOMMENDED.\n\nA client MAY publish releases in any order.\nFor example,\nif a package has existing `1.0.0` and `2.0.0` releases,\na client MAY publish a new `1.0.1` or `1.1.0` release.\n\nOnce a release has been published,\nany resources associated with that release,\nincluding its source archive,\nMUST NOT change.\n\nIf a release already exists for a package at the specified version,\nthe server SHOULD respond with a status code of `409` (Conflict).\n\n```http\nHTTP/1.1 409 Conflict\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"a release with version 1.0.0 already exists\"\n}\n```\n\nIt is RECOMMENDED that a server institute policies\nfor publishing new releases of a package\nafter a scope is transferred to a new owner.\nFor example,\nthe next release of an existing package is published with a new major version,\nor only after a period of 45 days after transfer.\n\nIf the client provides an `Expect` header,\na server SHOULD check that the request can succeed\nbefore responding with a status code of `100 (Continue)`.\nA server that doesn't support expectations\nSHOULD respond with a status code of `417 (Expectation Failed)`.\nIn response,\na client MAY remove the `Expect` header and retry the request.\n\n```http\nHTTP/1.1 417 (Expectation Failed)\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"expectations aren't supported\"\n}\n```\n\nSupport for this endpoint is OPTIONAL.\nA server SHOULD indicate that publishing isn't supported\nby responding with a status code of `405` (Method Not Allowed).\n\n```http\nHTTP/1.1 405 (Method Not Allowed)\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"publishing isn't supported\"\n}\n```\n\nA server MAY respond either synchronously or asynchronously.\nFor more information,\nsee [4.6.4](#464-synchronous-and-asynchronous-publication).\n\n#### 4.6.1. Source archive\n\nA client MUST include a multipart section named `source-archive`\ncontaining the source archive for a release.\nA client SHOULD set a `Content-Type` header with the value `application/zip`\nand a `Content-Length` header with the size of the Zip archive in bytes.\n\n```http\n--boundary\nContent-Disposition: form-data; name=\"source-archive\"\nContent-Type: application/zip\nContent-Length: 32\nContent-Transfer-Encoding: base64\n\ngHUFBgAAAAAAAAAAAAAAAAAAAAAAAA==\n```\n\nA client SHOULD use the `swift package archive-source` tool\nto create a source archive for the release.\n\nA server MAY analyze a package to\nassess its viability,\nperform security testing,\nor otherwise evaluate software quality.\nA server MAY refuse to publish a package release for any reason\nby responding with a status code of `422` (Unprocessable Entity).\n\n```http\nHTTP/1.1 422 Unprocessable Entity\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"package doesn't contain a valid manifest (Package.swift) file\"\n}\n```\n\nA server SHOULD use the `swift package compute-checksum` tool\nto compute the checksum that's provided in response to\na client's subsequent request to [download the source archive](#endpoint-4)\nfor the release.\n\n#### 4.6.2. Package release metadata\n\nA client MAY include a multipart section named `metadata`\ncontaining additional information about the release.\nA client SHOULD set a `Content-Type` header with the value `application/json`\nand a `Content-Length` header with the size of the JSON document in bytes.\nThe package release metadata MUST be based on the [JSON schema](#appendix-b---package-release-metadata-json-schema),\nas discussed in [4.2.2](#422-package-release-metadata-standards).\n\n```http\n--boundary\nContent-Disposition: form-data; name=\"metadata\"\nContent-Type: application/json\nContent-Length: 226\nContent-Transfer-Encoding: quoted-printable\n\n{\n  \"description\": \"One thing links to another.\",\n  \"repositoryURLs\": [\"https://github.com/mona/LinkedList\"],\n  \"licenseURL\": \"https://www.apache.org/licenses/LICENSE-2.0\",\n  \"author\": {\n      \"name\": \"Mona Lisa Octocat\"\n  }\n}\n\n```\n\nA server MAY allow and/or populate additional metadata for a release.\n\nA server MAY make any properties in the [JSON schema](#appendix-b---package-release-metadata-json-schema)\nand additional metadata it defines required.\n\nIf a client provides an invalid JSON document,\nthe server SHOULD respond with a status code of\n`422` (Unprocessable Entity) or `413` (Payload Too Large)\nand MAY communicate validation error details in the response body.\n\n```http\nHTTP/1.1 422 Unprocessable Entity\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"invalid JSON provided for release metadata\"\n}\n```\n\n#### 4.6.3. Synchronous and asynchronous publication\n\nA server MAY respond to a request to publish a new package release\neither synchronously or asynchronously.\n\nA client MAY indicate their preference for asynchronous processing\nwith a `Prefer` header field containing the token `respond-async`\nand an optional `wait` preference,\nas described by [RFC 7240].\n\n```http\nPUT /mona/LinkedList/1.1.1 HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1\nPrefer: respond-async, wait=300\n```\n\n##### 4.6.3.1. Synchronous publication\n\nIf processing is done synchronously,\nthe server MUST respond with a status code of `201` (Created)\nto indicate that the package release was published.\nThis response SHOULD also contain\na `Location` header with a URL to the new release.\n\n```http\nHTTP/1.1 201 Created\nContent-Version: 1\nLocation: https://packages.example.com/github.com/mona/LinkedList/1.1.1\n```\n\nA client MAY set a timeout to guarantee a timely response to each request.\n\n##### 4.6.3.2. Asynchronous publication\n\nIf processing is done asynchronously,\nthe server MUST respond with a status code of `202` (Accepted)\nto acknowledge that the request is being processed.\nThis response MUST contain a `Location` header\nwith a URL that the client can poll for progress updates\nand SHOULD contain a `Retry-After` header\nwith an estimate of when processing is expected to finish.\nA server MAY locate the status resource endpoint at a URI of its choosing.\nHowever,\nthe use of a non-sequential, randomly-generated identifier is RECOMMENDED.\n\n```http\nHTTP/1.1 202 Accepted\nContent-Version: 1\nLocation: https://packages.example.com/submissions/90D8CC77-A576-47AE-A531-D6402C4E33BC\nRetry-After: 120\n```\n\nA client MAY send a `GET` request\nto the location provided by the server in response to a publish request\nto see the current status of that process.\n\n```http\nGET /submissions/90D8CC77-A576-47AE-A531-D6402C4E33BC HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1\n```\n\nIf the asynchronous publish request is still processing,\nthe server SHOULD respond with a status code of `202` (Accepted) and\na `Retry-After` header with an estimate of when processing should finish.\nA server MAY include additional details in the response body.\n\n```http\nHTTP/1.1 202 Accepted\nContent-Version: 1\nContent-Type: application/json\nRetry-After: 120\n\n{\n  \"status\": \"Processing (2/3 steps complete)\",\n  \"steps\": {\n    {\"name\": \"Validate metadata\", \"status\": \"complete\"},\n    {\"name\": \"Verify package manifest\", \"status\": \"complete\"},\n    {\"name\": \"Scan for vulnerabilities\", \"status\": \"pending\"}\n  }\n}\n```\n\nIf the asynchronous publish request is finished processing successfully,\nthe server SHOULD respond with a status code of `301` (Moved Permanently)\nand a `Location` header with a URL to the package release.\n\n```http\nHTTP/1.1 301 Moved Permanently\nContent-Version: 1\nLocation: https://packages.example.com/mona/LinkedList/1.1.1\n```\n\nIf the asynchronous publish request failed,\nthe server SHOULD respond with an appropriate client error status code (`4xx`).\n\n```http\nHTTP/1.1 400 Bad Request\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\nLocation: https://packages.example.com/submissions/90D8CC77-A576-47AE-A531-D6402C4E33BC\n\n{\n   \"detail\": \"invalid package\"\n}\n```\n\nA client MAY send a `DELETE` request\nto the location provided by the server in response to a publish request\nto cancel that process.\n\nIf a request to publish a new package release were to fail,\na server MUST communicate that failure in the same way\nif sending an immediate response\nas it would if responding to a client polling for status.\n\nIf a client makes a request to publish a package release\nto a server that is asynchronously processing a request to publish that release,\nthe server MUST respond with a status code of `409` (Conflict)\n\n```http\nHTTP/1.1 409 Conflict\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\nLocation: https://packages.example.com/submissions/90D8CC77-A576-47AE-A531-D6402C4E33BC\n\n{\n   \"detail\": \"already processing a request to publish this package version\"\n}\n```\n\nIf a client makes a request to publish a package release\nto a server that finished processing a failed request to publish that release,\nthe server SHOULD try publishing that release again.\nA server MAY refuse to fulfill a subsequent request to publish a package release\nby responding with a status code of `409` (Conflict).\n\n## 5. Normative References\n\n* [RFC 2119]: Key words for use in RFCs to Indicate Requirement Levels\n* [RFC 3230]: Instance Digests in HTTP\n* [RFC 3986]: Uniform Resource Identifier (URI): Generic Syntax\n* [RFC 3987]: Internationalized Resource Identifiers (IRIs)\n* [RFC 5234]: Augmented BNF for Syntax Specifications: ABNF\n* [RFC 5843]: Additional Hash Algorithms for HTTP Instance Digests\n* [RFC 6249]: Metalink/HTTP: Mirrors and Hashes\n* [RFC 6570]: URI Template\n* [RFC 7159]: The JavaScript Object Notation (JSON) Data Interchange Format\n* [RFC 7230]: Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing\n* [RFC 7231]: Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content\n* [RFC 7233]: Hypertext Transfer Protocol (HTTP/1.1): Range Requests\n* [RFC 7234]: Hypertext Transfer Protocol (HTTP/1.1): Caching\n* [RFC 7240]: Prefer Header for HTTP\n* [RFC 7578]: Returning Values from Forms: multipart/form-data\n* [RFC 7807]: Problem Details for HTTP APIs\n* [RFC 8288]: Web Linking\n* [SemVer]: Semantic Versioning\n\n## 6. Informative References\n\n* [BCP 13] Media Type Specifications and Registration Procedures\n* [RFC 6749]: The OAuth 2.0 Authorization Framework\n* [RFC 8446]: The Transport Layer Security (TLS) Protocol Version 1.3\n* [RFC 8631]: Link Relation Types for Web Services\n* [JSON-LD]: A JSON-based Serialization for Linked Data\n* [Schema.org]: A shared vocabulary for structured data.\n* [OAS]: OpenAPI Specification\n\n## Appendix A - OpenAPI Document\n\nThe following [OpenAPI (v3) specification][OAS] is non-normative,\nand is provided for the convenience of\ndevelopers interested in building their own package registry.\n\nSee [registry.openapi.yaml](./registry.openapi.yaml).\n\n## Appendix B - Package Release Metadata JSON Schema\n\nThe `metadata` section of the [create package release request](#46-create-a-package-release)\nmust be a JSON object of type [`PackageRelease`](#packagerelease-type), as defined in the\nJSON schema below.\n\n<details>\n\n<summary>Expand to view <a href=\"https://json-schema.org/specification.html\">JSON schema</a></summary>\n\n```json\n{\n  \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n  \"$id\": \"https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/PackageRegistry/Registry.md\",\n  \"title\": \"Package Release Metadata\",\n  \"description\": \"Metadata of a package release.\",\n  \"type\": \"object\",\n  \"properties\": {\n    \"author\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"name\": {\n          \"type\": \"string\",\n          \"description\": \"Name of the author.\"\n        },\n        \"email\": {\n          \"type\": \"string\",\n          \"format\": \"email\",\n          \"description\": \"Email address of the author.\"\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"description\": \"A description of the author.\"\n        },\n        \"organization\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"name\": {\n              \"type\": \"string\",\n              \"description\": \"Name of the organization.\"\n            },\n            \"email\": {\n              \"type\": \"string\",\n              \"format\": \"email\",\n              \"description\": \"Email address of the organization.\"\n            },\n            \"description\": {\n              \"type\": \"string\",\n              \"description\": \"A description of the organization.\"\n            },\n            \"url\": {\n              \"type\": \"string\",\n              \"format\": \"uri\",\n              \"description\": \"URL of the organization.\"\n            },\n          },\n          \"required\": [\"name\"]\n        },\n        \"url\": {\n          \"type\": \"string\",\n          \"format\": \"uri\",\n          \"description\": \"URL of the author.\"\n        },\n      },\n      \"required\": [\"name\"]\n    },\n    \"description\": {\n      \"type\": \"string\",\n      \"description\": \"A description of the package release.\"\n    },\n    \"licenseURL\": {\n      \"type\": \"string\",\n      \"format\": \"uri\",\n      \"description\": \"URL of the package release's license document.\"\n    },\n    \"originalPublicationTime\": {\n      \"type\": \"string\",\n      \"format\": \"date-time\",\n      \"description\": \"Original publication time of the package release in ISO 8601 format.\"\n    },\n    \"readmeURL\": {\n      \"type\": \"string\",\n      \"format\": \"uri\",\n      \"description\": \"URL of the README specifically for the package release or broadly for the package.\"\n    },\n    \"repositoryURLs\": {\n      \"type\": \"array\",\n      \"description\": \"Code repository URL(s) of the package release.\",\n      \"items\": {\n        \"type\": \"string\",\n        \"description\": \"Code repository URL.\"\n      }\n    }\n  }\n}\n```\n\n</details>\n\n##### `PackageRelease` type\n\n| Property                  | Type                | Description                                      | Required |\n| ------------------------- | :-----------------: | ------------------------------------------------ | :------: |\n| `author`                  | [Author](#author-type) | Author of the package release. | |\n| `description`             | String | A description of the package release. | |\n| `licenseURL`              | String | URL of the package release's license document. | |\n| `originalPublicationTime` | String | Original publication time of the package release in [ISO 8601] format. This can be set if the package release was previously published elsewhere.<br>A registry should record the publication time independently and include it as `publishedAt` in the [package release metadata response](#42-fetch-information-about-a-package-release). <br>In case both `originalPublicationTime` and `publishedAt` are set, `originalPublicationTime` should be used. | |\n| `readmeURL`       | String | URL of the README specifically for the package release or broadly for the package. | |\n| `repositoryURLs`  | Array | Code repository URL(s) of the package. It is recommended to include all URL variations (e.g., SSH, HTTPS) for the same repository. This can be an empty array if the package does not have source control representation.<br/>Setting this property is one way through which a registry can obtain repository URL to package identifier mappings for the [\"lookup package identifiers registered for a URL\" API](Registry.md#45-lookup-package-identifiers-registered-for-a-url). A registry may choose other mechanism(s) for package authors to specify such mappings. | |\n\n##### `Author` type\n\n| Property          | Type                | Description                                      | Required |\n| ----------------- | :-----------------: | ------------------------------------------------ | :------: |\n| `name`            | String | Name of the author. | ✓ |\n| `email`           | String | Email address of the author. | |\n| `description`     | String | A description of the author. | |\n| `organization`    | [Organization](#organization-type) | Organization that the author belongs to. | |\n| `url`             | String | URL of the author. | |\n\n##### `Organization` type\n\n| Property          | Type                | Description                                      | Required |\n| ----------------- | :-----------------: | ------------------------------------------------ | :------: |\n| `name`            | String | Name of the organization. | ✓ |\n| `email`           | String | Email address of the organization. | |\n| `description`     | String | A description of the organization. | |\n| `url`             | String | URL of the organization. | |\n\n[UAX18]: https://unicode.org/reports/tr18/\n[BCP 13]: https://tools.ietf.org/html/rfc6838 \"Media Type Specifications and Registration Procedures\"\n[RFC 2119]: https://tools.ietf.org/html/rfc2119 \"Key words for use in RFCs to Indicate Requirement Levels\"\n[RFC 3230]: https://tools.ietf.org/html/rfc5843 \"Instance Digests in HTTP\"\n[RFC 3986]: https://tools.ietf.org/html/rfc3986 \"Uniform Resource Identifier (URI): Generic Syntax\"\n[RFC 3987]: https://tools.ietf.org/html/rfc3987 \"Internationalized Resource Identifiers (IRIs)\"\n[RFC 5234]: https://tools.ietf.org/html/rfc5234 \"Augmented BNF for Syntax Specifications: ABNF\"\n[RFC 5843]: https://tools.ietf.org/html/rfc5843 \"Additional Hash Algorithms for HTTP Instance Digests\"\n[RFC 6249]: https://tools.ietf.org/html/rfc6249 \"Metalink/HTTP: Mirrors and Hashes\"\n[RFC 6570]: https://tools.ietf.org/html/rfc6570 \"URI Template\"\n[RFC 6749]: https://tools.ietf.org/html/rfc6749 \"The OAuth 2.0 Authorization Framework\"\n[RFC 7159]: https://tools.ietf.org/html/rfc7159 \"The JavaScript Object Notation (JSON) Data Interchange Format\"\n[RFC 7230]: https://tools.ietf.org/html/rfc7230 \"Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing\"\n[RFC 7231]: https://tools.ietf.org/html/rfc7231 \"Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content\"\n[RFC 7233]: https://tools.ietf.org/html/rfc7233 \"Hypertext Transfer Protocol (HTTP/1.1): Range Requests\"\n[RFC 7234]: https://tools.ietf.org/html/rfc7234 \"Hypertext Transfer Protocol (HTTP/1.1): Caching\"\n[RFC 7240]: https://tools.ietf.org/html/rfc7240 \"Prefer Header for HTTP\"\n[RFC 7578]: https://tools.ietf.org/html/rfc7578 \"Returning Values from Forms: multipart/form-data\"\n[RFC 7807]: https://tools.ietf.org/html/rfc7807 \"Problem Details for HTTP APIs\"\n[RFC 8288]: https://tools.ietf.org/html/rfc8288 \"Web Linking\"\n[RFC 8446]: https://tools.ietf.org/html/rfc8446 \"The Transport Layer Security (TLS) Protocol Version 1.3\"\n[RFC 8631]: https://tools.ietf.org/html/rfc8631 \"Link Relation Types for Web Services\"\n[IANA Link Relations]: https://www.iana.org/assignments/link-relations/link-relations.xhtml\n[JSON-LD]: https://w3c.github.io/json-ld-syntax/ \"JSON-LD 1.1: A JSON-based Serialization for Linked Data\"\n[SemVer]: https://semver.org/ \"Semantic Versioning\"\n[Schema.org]: https://schema.org/\n[SoftwareSourceCode]: https://schema.org/SoftwareSourceCode\n[DUST]: https://doi.org/10.1145/1462148.1462151 \"Bar-Yossef, Ziv, et al. Do Not Crawl in the DUST: Different URLs with Similar Text. Association for Computing Machinery, 17 Jan. 2009. January 2009\"\n[OAS]: https://swagger.io/specification/ \"OpenAPI Specification\"\n[GitHub / Swift Package Management Service]: https://forums.swift.org/t/github-swift-package-management-service/30406\n[RubyGems]: https://rubygems.org \"RubyGems: The Ruby community’s gem hosting service\"\n[PyPI]: https://pypi.org \"PyPI: The Python Package Index\"\n[npm]: https://www.npmjs.com \"The npm Registry\"\n[crates.io]: https://crates.io \"crates.io: The Rust community’s crate registry\"\n[CocoaPods]: https://cocoapods.org \"A dependency manager for Swift and Objective-C Cocoa projects\"\n[thundering herd effect]: https://en.wikipedia.org/wiki/Thundering_herd_problem \"Thundering herd problem\"\n[offline cache]: https://yarnpkg.com/features/offline-cache \"Offline Cache | Yarn - Package Manager\"\n[XCFramework]: https://developer.apple.com/videos/play/wwdc2019/416/ \"WWDC 2019 Session 416: Binary Frameworks in Swift\"\n[SE-0272]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0272-swiftpm-binary-dependencies.md \"Package Manager Binary Dependencies\"\n[Swift tools version]: https://github.com/swiftlang/swift-package-manager/blob/9b9bed7eaf0f38eeccd0d8ca06ae08f6689d1c3f/Documentation/Usage.md#swift-tools-version-specification \"Swift Tools Version Specification\"\n[ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html \"ISO 8601 Date and Time Format\"\n"
  },
  {
    "path": "Documentation/PackageRegistry/registry.openapi.yaml",
    "content": "openapi: 3.0.3\ninfo:\n  title: Swift Package Registry API\n  description: API for managing Swift package releases and interacting with the package registry.\n  version: 1.0.0\ntags:\n  - name: Releases\n  - name: Packages\n  - name: Authentication\npaths:\n  '/{scope}/{name}':\n    parameters:\n      - $ref: '#/components/parameters/Scope'\n      - $ref: '#/components/parameters/PackageName'\n    get:\n      tags:\n        - Releases\n      summary: List package releases\n      operationId: listPackageReleases\n      responses:\n        '200':\n          description: Retrieve a list of all available releases for a given package\n          headers:\n            Link:\n              $ref: '#/components/headers/PackageLinks'\n            Content-Version:\n              $ref: '#/components/headers/ContentVersion'\n          content:\n            'application/json':\n              schema:\n                $ref: '#/components/schemas/Releases'\n        '400':\n          $ref: '#/components/responses/BadRequest'\n        '401':\n          $ref: '#/components/responses/Unauthorized'\n        '404':\n          $ref: '#/components/responses/NotFound'\n        '415':\n          $ref: '#/components/responses/UnsupportedMediaType'\n        '429':\n          $ref: '#/components/responses/TooManyRequests'\n  '/{scope}/{name}/{version}':\n    parameters:\n      - $ref: '#/components/parameters/Scope'\n      - $ref: '#/components/parameters/PackageName'\n      - $ref: '#/components/parameters/Version'\n    get:\n      tags:\n        - Releases\n      summary: Fetch metadata for a package release\n      operationId: fetchReleaseMetadata\n      responses:\n        '200':\n          description: Retrieve detailed metadata for a specific package release\n          headers:\n            Link:\n              $ref: '#/components/headers/PackageLinks'\n            Content-Version:\n              $ref: '#/components/headers/ContentVersion'\n          content:\n            'application/json':\n              schema:\n                $ref: '#/components/schemas/ReleaseMetadata'\n        '400':\n          $ref: '#/components/responses/BadRequest'\n        '401':\n          $ref: '#/components/responses/Unauthorized'\n        '404':\n          $ref: '#/components/responses/NotFound'\n        '415':\n          $ref: '#/components/responses/UnsupportedMediaType'\n        '429':\n          $ref: '#/components/responses/TooManyRequests'\n    put:\n      tags:\n        - Releases\n      summary: Create a package release\n      operationId: createPackageRelease\n      parameters:\n        - in: header\n          name: X-Swift-Package-Signature-Format\n          description: The signature format if the source archive is signed.\n          schema:\n            type: string\n            example: 'cms-1.0.0'\n        - in: header\n          name: Prefer\n          description: |-\n            Communicates the preference for sync vs async processing.\n\n            Use \"respond-async\" to get async processing, for example \"respond-async, wait=300\" to wait up to 300 seconds.\n\n            Omit this header to prefer sync processing.\n          schema:\n            type: string\n      requestBody:\n        description: A multipart payload.\n        required: true\n        content:\n          multipart/form-data:\n            schema:\n              type: object\n              properties:\n                source-archive:\n                  type: string\n                  format: binary\n                  description: The binary source archive of the package to be published\n                  example: 'Binary data for Linked List package release'\n                source-archive-signature:\n                  type: string\n                  format: binary\n                  description: The signature for the source archive.\n                metadata:\n                  $ref: '#/components/schemas/PackageMetadata'\n                metadata-signature:\n                  type: string\n                  format: base64\n                  description: The signature for the metadata.\n              required:\n                - source-archive\n            encoding:\n              source-archive:\n                contentType: application/zip\n              source-archive-signature:\n                contentType: application/octet-stream\n              metadata:\n                contentType: application/json\n              metadata-signature:\n                contentType: application/octet-stream\n      responses:\n        '201':\n          description: The package release has been successfully published\n          headers:\n            Content-Version:\n              $ref: '#/components/headers/ContentVersion'\n            Location:\n              description: The URL to the created release.\n              schema:\n                type: string\n                format: uri\n                example: 'https://packages.example.com/github.com/mona/LinkedList/1.1.1'\n          content:\n            'application/json':\n              schema:\n                $ref: '#/components/schemas/PublishResponse'\n        '202':\n          description: The request to publish the package has been accepted and is being processed\n          headers:\n            'Retry-After':\n              $ref: '#/components/headers/RetryAfter'\n            Location:\n              description: |-\n                The URL to poll for status of the publication process.\n\n                Poll that URL using a `GET` request, and if the response is 202, extract the Retry-After header to get a new estimate\n                of when the processing will be finished.\n\n                When the response is 301, the processing is finished and the Location header points to the new release.\n\n                If the response is 4xx, the processing failed and you can stop polling. The response contains the failure details.\n\n                Send `DELETE` to the URL to cancel the processing.\n              schema:\n                type: string\n                format: uri\n                description: URL to poll for status of the publication process\n        '400':\n          $ref: '#/components/responses/BadRequest'\n        '401':\n          $ref: '#/components/responses/Unauthorized'\n        '404':\n          $ref: '#/components/responses/NotFound'\n        '405':\n          description: Method not allowed - publishing is not supported on this server.\n          content:\n            application/problem+json:\n              schema:\n                $ref: '#/components/schemas/ProblemDetails'\n        '409':\n          description: Conflict - an existing release already exists, or the release is still processing.\n          headers:\n            Location:\n              description: The location of the release that's still processing, see the 202 response for details.\n              schema:\n                type: string\n                format: uri\n          content:\n            application/problem+json:\n              schema:\n                $ref: '#/components/schemas/ProblemDetails'\n        '413':\n          description: Content too large.\n          content:\n            application/problem+json:\n              schema:\n                $ref: '#/components/schemas/ProblemDetails'\n        '415':\n          $ref: '#/components/responses/UnsupportedMediaType'\n        '422':\n          description: Unprocessable entity - refused to publish the release.\n          content:\n            application/problem+json:\n              schema:\n                $ref: '#/components/schemas/ProblemDetails'\n        '429':\n          $ref: '#/components/responses/TooManyRequests'\n  '/{scope}/{name}/{version}/Package.swift':\n    parameters:\n      - $ref: '#/components/parameters/Scope'\n      - $ref: '#/components/parameters/PackageName'\n      - $ref: '#/components/parameters/Version'\n    get:\n      tags:\n        - Packages\n      summary: Fetch manifest for a package release\n      operationId: fetchManifestForPackageRelease\n      parameters:\n        - $ref: '#/components/parameters/SwiftVersion'\n      responses:\n        '200':\n          description: Retrieve the manifest file for the specified package release\n          headers:\n            Link:\n              required: true\n              schema:\n                type: string\n                description: |-\n                  One value for each version-specific package manifest file in the release's source archive,\n                  whose filename matches the following regular expression pattern:\n                  `\\APackage@swift-(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?.swift\\z`\n\n                  Each link value should have the alternate relation type, a filename attribute set to the version-specific package manifest filename\n                  (for example, Package@swift-4.swift), and a swift-tools-version attribute set to the Swift tools version specified by the package\n                  manifest file (for example, 4.0 for a manifest beginning with the comment // swift-tools-version:4.0).\n          content:\n            text/x-swift:\n              schema:\n                type: string\n        '303':\n          description: Redirect to the unqualified Package.swift resource.\n          headers:\n            Location:\n              required: true\n              schema:\n                type: string\n                format: uri\n                example: 'https://packages.example.com/mona/LinkedList/1.1.1/Package.swift'\n            Content-Version:\n              $ref: '#/components/headers/ContentVersion'\n        '400':\n          $ref: '#/components/responses/BadRequest'\n        '401':\n          $ref: '#/components/responses/Unauthorized'\n        '404':\n          $ref: '#/components/responses/NotFound'\n        '415':\n          $ref: '#/components/responses/UnsupportedMediaType'\n        '429':\n          $ref: '#/components/responses/TooManyRequests'\n  '/{scope}/{name}/{version}.zip':\n    parameters:\n      - $ref: '#/components/parameters/Scope'\n      - $ref: '#/components/parameters/PackageName'\n      - $ref: '#/components/parameters/Version'\n    get:\n      tags:\n        - Packages\n      summary: Download source archive for a package release\n      operationId: downloadSourceArchive\n      responses:\n        '200':\n          description: Download the source archive for the specified package release\n          headers:\n            Digest:\n              description: A digest containing a cryptographic digest of the source archive.\n              schema:\n                type: string\n                example: 'sha-256=oqxUzyX7wa0AKPA/CqS5aDO4O7BaFOUQiSuyfepNyBI='\n            Content-Disposition:\n              description: |-\n                A header set to attachment with a filename parameter equal to the name of the package followed by a hyphen (-),\n                the version number, and file extension (for example, \"LinkedList-1.1.1.zip\")\n              schema:\n                type: string\n                example: 'attachment; filename=\"LinkedList-1.1.1.zip\"'\n            X-Swift-Package-Signature-Format:\n              description: The format of the package signature, used for integrity verification\n              schema:\n                type: string\n                example: 'cms-1.0.0'\n            X-Swift-Package-Signature:\n              description: Signature of the downloaded package, used for integrity verification\n              schema:\n                type: string\n                format: base64\n                example: 'l1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw=='\n            Link:\n              description: A header containing mirrors or multiple download locations.\n              schema:\n                type: string\n                description: A Link header with a `duplicate` relation, as described by RFC 6249.\n                example: '<https://mirror-japanwest.example.com/mona-LinkedList-1.1.1.zip>; rel=duplicate; geo=jp; pri=10; type=\"application/zip\"'\n          content:\n            application/zip:\n              schema:\n                type: string\n                format: binary\n        '303':\n          description: See other - download from the URL in the Location header.\n          headers:\n            Location:\n              description: The location from which to download the resource.\n              required: true\n              schema:\n                type: string\n                example: 'https://example.cdn.com/LinkedList-1.1.1.zip?key=XXXXXXXXXXXXXXXXX'\n        '400':\n          $ref: '#/components/responses/BadRequest'\n        '401':\n          $ref: '#/components/responses/Unauthorized'\n        '404':\n          $ref: '#/components/responses/NotFound'\n        '415':\n          $ref: '#/components/responses/UnsupportedMediaType'\n        '429':\n          $ref: '#/components/responses/TooManyRequests'\n  '/identifiers':\n    parameters:\n      - $ref: '#/components/parameters/Url'\n    get:\n      tags:\n        - Packages\n      summary: Lookup package identifiers registered for a URL\n      operationId: lookupPackageIdentifiersByURL\n      responses:\n        '200':\n          description: Retrieve a list of package identifiers registered for a specific URL\n          headers:\n            Content-Version:\n              $ref: '#/components/headers/ContentVersion'\n          content:\n            'application/json':\n              schema:\n                $ref: '#/components/schemas/Identifiers'\n        '400':\n          $ref: '#/components/responses/BadRequest'\n        '401':\n          $ref: '#/components/responses/Unauthorized'\n        '415':\n          $ref: '#/components/responses/UnsupportedMediaType'\n        '429':\n          $ref: '#/components/responses/TooManyRequests'\n  '/login':\n    post:\n      tags:\n        - Authentication\n      summary: Log in to the package registry\n      operationId: loginToRegistry\n      description: |-\n        Log in using either basic or token authentication. Use the `Authorization` header to provide credentials.\n\n        Also use this endpoint to verify authentication credentials before saving them to the local secrets store.\n      responses:\n        '200':\n          description: User successfully logged in to the package registry\n        '401':\n          $ref: '#/components/responses/Unauthorized'\n        '429':\n          $ref: '#/components/responses/TooManyRequests'\n        '501':\n          description: Registry does not support authentication.\ncomponents:\n  parameters:\n    SwiftVersion:\n      name: swift-version\n      in: query\n      required: false\n      description: The Swift version for which to fetch the manifest\n      schema:\n        type: string\n        example: '4.2'\n    Scope:\n      name: scope\n      in: path\n      required: true\n      description: |-\n        The scope of the package (for example, the organization or user).\n        Package scopes are case-insensitive.\n      schema:\n        type: string\n        pattern: '[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}'\n        example: 'mona'\n    PackageName:\n      name: name\n      in: path\n      required: true\n      description: |-\n        The name of the package.\n        Package names are case-insensitive.\n      schema:\n        type: string\n        pattern: '[a-zA-Z0-9](?:[a-zA-Z0-9]|[-_](?=[a-zA-Z0-9])){0,99}'\n        example: 'LinkedList'\n    Version:\n      name: version\n      in: path\n      required: true\n      description: The semantic version of the package release.\n      schema:\n        type: string\n        example: '1.2.3'\n    Url:\n      name: url\n      in: query\n      required: true\n      description: The URL for which to look up registered package identifiers\n      schema:\n        type: string\n        example: 'https://example.com/mona/LinkedList'\n  responses:\n    Unauthorized:\n      description: Authentication failed due to invalid credentials provided\n      content:\n        application/problem+json:\n          schema:\n            $ref: '#/components/schemas/ProblemDetails'\n    BadRequest:\n      description: Bad Request - The request was invalid or cannot be otherwise served\n      content:\n        application/problem+json:\n          schema:\n            $ref: '#/components/schemas/ProblemDetails'\n    NotFound:\n      description: Not Found - The specified resource could not be found\n      content:\n        application/problem+json:\n          schema:\n            $ref: '#/components/schemas/ProblemDetails'\n    UnsupportedMediaType:\n      description: Unsupported Media Type - Accept header specifies a valid but unsupported API version.\n      content:\n        application/problem+json:\n          schema:\n            $ref: '#/components/schemas/ProblemDetails'\n    TooManyRequests:\n      description: Too Many Requests - Rate limit exceeded\n      headers:\n        'Retry-After':\n          $ref: '#/components/headers/RetryAfter'\n      content:\n        application/problem+json:\n          schema:\n            $ref: '#/components/schemas/ProblemDetails'\n  headers:\n    PackageLinks:\n      schema:\n        type: string\n        description: |-\n          A set of related links.\n\n          An example:\n          <https://github.com/mona/LinkedList>; rel=\"canonical\",\n          <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n          <https://packages.example.com/mona/LinkedList/1.1.1>; rel=\"latest-version\",\n          <https://github.com/sponsors/mona>; rel=\"payment\",\n          <https://packages.example.com/mona/LinkedList?page=1>; rel=\"first\",\n          <https://packages.example.com/mona/LinkedList?page=2>; rel=\"previous\",\n          <https://packages.example.com/mona/LinkedList?page=4>; rel=\"next\",\n          <https://packages.example.com/mona/LinkedList?page=10>; rel=\"last\"\n\n          Another example:\n          <https://packages.example.com/mona/LinkedList/1.1.1>; rel=\"latest-version\",\n          <https://packages.example.com/mona/LinkedList/1.0.0>; rel=\"predecessor-version\"\n\n          Also see:\n          - https://www.rfc-editor.org/rfc/rfc6596.html\n          - https://html.spec.whatwg.org/multipage/links.html#link-type-alternate\n          - https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/PackageRegistry/Registry.md#4-endpoints\n    RetryAfter:\n      schema:\n        type: string\n        description: |-\n          Retry-After header, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After.\n\n          Examples:\n            Retry-After: Wed, 21 Oct 2015 07:28:00 GMT\n            Retry-After: 120\n        example: '120'\n    ContentVersion:\n      description: The content version.\n      required: true\n      schema:\n        type: integer\n        enum:\n          - 1\n  schemas:\n    PackageOrganization:\n      type: object\n      properties:\n        description:\n          description: A description of the organization.\n          type: string\n        email:\n          description: Email address of the organization.\n          format: email\n          type: string\n        name:\n          description: Name of the organization.\n          type: string\n        url:\n          description: URL of the organization.\n          format: uri\n          type: string\n      required:\n        - name\n    PackageAuthor:\n      type: object\n      properties:\n        description:\n          description: A description of the author.\n          type: string\n        email:\n          description: Email address of the author.\n          format: email\n          type: string\n        name:\n          description: Name of the author.\n          type: string\n        organization:\n          $ref: '#/components/schemas/PackageOrganization'\n        url:\n          description: URL of the author.\n          format: uri\n          type: string\n      required:\n        - name\n    PackageMetadata:\n      type: object\n      description: Metadata of a package release.\n      properties:\n        author:\n          $ref: '#/components/schemas/PackageAuthor'\n        description:\n          type: string\n          description: A description of the package release.\n        licenseURL:\n          type: string\n          format: uri\n          description: URL of the package release's license document.\n        originalPublicationTime:\n          type: string\n          format: date-time\n          description: Original publication time of the package release in ISO 8601 format.\n        readmeURL:\n          type: string\n          format: uri\n          description: URL of the README specifically for the package release or broadly\n            for the package.\n        repositoryURLs:\n          type: array\n          items:\n            description: Code repository URL.\n            type: string\n            format: uri\n          description: Code repository URL(s) of the package release.\n    PublishResponse:\n      type: object\n      properties:\n        message:\n          type: string\n          example: 'Package release successfully published'\n        url:\n          type: string\n          format: uri\n          description: The URL of the newly published package release\n          example: 'https://packages.example.com/mona/LinkedList/1.1.0'\n    ProblemDetails:\n      type: object\n      description: A problem detail object conforming to RFC7807\n      properties:\n        type:\n          type: string\n          format: uri\n          description: |-\n            A URI reference that identifies the problem type.\n            This specification encourages that, when dereferenced,\n            it provides human-readable documentation for the problem type.\n          example: 'https://example.com/problem/invalid-request-parameters'\n        title:\n          type: string\n          description: |-\n            A short, human-readable summary of the problem type.\n            It should not change from occurrence to occurrence of the\n            problem, except for purposes of localization.\n          example: 'Invalid request parameters'\n        status:\n          type: integer\n          description: |-\n            The HTTP status code generated by the origin server for this occurrence of the problem.\n          example: 400\n        detail:\n          type: string\n          description: A human-readable explanation specific to this occurrence of the problem.\n          example: 'The \"name\" field is required.'\n        instance:\n          type: string\n          format: uri\n          description: A URI reference that identifies the specific occurrence of the problem.\n          example: '/requests/12345'\n      additionalProperties: true\n    ListedRelease:\n      type: object\n      properties:\n        url:\n          type: string\n          format: uri\n          example: 'https://packages.example.com/mona/LinkedList/1.1.0'\n        problem:\n          $ref: '#/components/schemas/ProblemDetails'\n    Releases:\n      type: object\n      properties:\n        releases:\n          type: object\n          additionalProperties:\n            $ref: '#/components/schemas/ListedRelease'\n      required:\n        - releases\n    ReleaseSignature:\n      type: object\n      properties:\n        signatureBase64Encoded:\n          type: string\n          format: base64\n          description: The resource's signature, base64 encoded.\n          example: 'dGVzdFNpZ25hdHVyZQ=='\n        signatureFormat:\n          type: string\n          description: The signature format.\n          example: 'cms-1.0.0'\n      required:\n        - signatureBase64Encoded\n        - signatureFormat\n    ReleaseResource:\n      type: object\n      properties:\n        name:\n          type: string\n          description: The name of the resource.\n          example: 'source-archive'\n        type:\n          type: string\n          description: The content type of the resource.\n          example: 'application/zip'\n        checksum:\n          type: string\n          description: A hexadecimal representation of the SHA256 digest for the resource.\n          example: 'efaa6545cd99dd1e124b5269ea0586994b6d97a0443021d2966e1df6dec9c4a1'\n        signing:\n          $ref: '#/components/schemas/ReleaseSignature'\n      required:\n        - name\n        - type\n        - checksum\n    ReleaseMetadata:\n      type: object\n      properties:\n        id:\n          $ref: '#/components/schemas/Identifier'\n        version:\n          type: string\n          description: The package release version number.\n          example: '1.2.3'\n        resources:\n          type: array\n          items:\n            $ref: '#/components/schemas/ReleaseResource'\n          description: The resources available for the release.\n        metadata:\n          $ref: '#/components/schemas/PackageMetadata'\n        publishedAt:\n          type: string\n          format: date-time\n          description: |-\n            The ISO 8601-formatted datetime string of when the package release was published, as recorded by the registry.\n            See related `originalPublicationTime` in metadata.\n      required:\n        - id\n        - version\n        - resources\n        - metadata\n    Identifier:\n      type: string\n      example: 'mona.LinkedList'\n    Identifiers:\n      type: object\n      properties:\n        identifiers:\n          type: array\n          items:\n            $ref: '#/components/schemas/Identifier'\n      required:\n        - identifiers\n"
  },
  {
    "path": "Documentation/README.md",
    "content": "# Swift Package Manager\n\nThe documentation previously included here has primarily been migrated into DocC format, and is available for viewing online at Swift.org [Package Manager Docs](https://docs.swift.org/swiftpm/documentation/packagemanagerdocs).\nThe sources for the documentation content are in the [Sources/PackageManagerDocs](Sources/PackageManagerDocs) directory.\n\nFor documentation on developing the Swift Package Manager itself, see the [contribution guide](CONTRIBUTING.md).\n\nThis directory continues to retain legacy [design notes](Design), [release notes](ReleaseNotes), details about\nthe [Package Registry API](PackageRegistry), and [libSwiftPM](libSwiftPM).\n"
  },
  {
    "path": "Documentation/ReleaseNotes/5.3.md",
    "content": "# SwiftPM 5.3 Release Notes\n\nSwiftPM brings several new features in version 5.3, all of which are opt-in based on the tools-version.\n\n### Conditional dependencies\n\nYou can now declare conditions for a Swift package’s target dependencies, such as limiting the dependencies by platform. This gives you more flexibility to describe complex target dependencies that support multiple platforms. (40237402)\n\n```swift\n// swift-tools-version:5.3\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"SamplePackage\",\n    dependencies: [\n        .package(url: \"https://github.com/pureswift/bluetooth\", .branch(\"main\")),\n        .package(url: \"https://github.com/pureswift/bluetoothlinux\", .branch(\"main\")),\n    ],\n    targets: [\n        .target(\n            name: \"SampleExecutable\",\n            dependencies: [\n                .product(name: \"Bluetooth\", condition: .when(platforms: [.macOS])),\n                .product(name: \"BluetoothLinux\", condition: .when(platforms: [.linux])),\n            ]\n        ),\n     ]\n)\n```\n\n### Resources\n\nSwift packages can now contain resources such as images, asset catalogs, storyboards, and other files. When Xcode builds an app that depends on a package, it adds the package’s code and resources to the app bundle for use at runtime. For more information see [Bundling Resources with a Swift Package](https://developer.apple.com/documentation/swift_packages/bundling_resources_with_a_swift_package). (54361843)\n\nAny resource in the package can now contain localized content. In addition to localized content in asset catalogs, Xcode supports separate localization files in .lproj folders. For more information see [Localizing Package Resources](https://developer.apple.com/documentation/swift_packages/localizing_package_resources). (56925255)\n\n**Important**: The addition of resource support also changed the inclusion behavior for non-source files in packages. Updating a package tools-version to 5.3, means one has to explicitly declare whether to exclude or process any file whose type is unknown to SwiftPM. This can be done at the file or directory level. \n\n### Binary dependencies\n\nSwift packages can now vend prebuilt libraries distributed as XCFrameworks, allowing dependencies on libraries that can’t be distributed as source code. When Xcode builds an app that uses such a package, it embeds the libraries into the app bundle. For more information see [Distributing Binary Frameworks as Swift Packages](https://developer.apple.com/documentation/swift_packages/distributing_binary_frameworks_as_swift_packages). (56592977)\n"
  },
  {
    "path": "Documentation/ReleaseNotes/5.4.md",
    "content": "# SwiftPM 5.4 Release Notes\n\nSwiftPM 5.4 includes several improvements, all of which are opt-in based on specifying a tools version of 5.4.\n\n\n### Executable targets\n\nSwift packages that specify a 5.4 tools version can now explicitly declare targets as executable, which allows the use of the `@main` keyword in package code.\n\nThis is done by declaring the target using `executableTarget()` in the package manifest, telling SwiftPM that the target should be considered to be executable regardless of whether it contains a file with a base name of `main`.\n\nThe compiler still applies its usual rules when compiling an executable module, so a single target cannot, for example, have a file named `main.swift` and another file that uses `@main`.\n\n### Automatic test discovery\n\nAutomatic test discovery is now the default on all platforms, removing the need in `LinuxMain.swift`, which has been deprecated. This file is still honored if it is present.\n\n### More flexible tools version formatting\n\n`Package` manifests can now have any combination of leading whitespace characters before the tools version comment. This allows more flexibility in formatting manifests.\n    \nSpecifically, the Swift tools version specification in each manifest file now accepts any combination of _horizontal_ whitespace characters surrounding `swift-tools-version`, if and only if the specified version ≥ `5.4`. For example, `//swift-tools-version:\t5.4` and `//\t\t swift-tools-version: 5.4` are valid.\n  \nAll [Unicode line terminators](https://www.unicode.org/reports/tr14/) are now recognised in `Package` manifests. This ensures correctness in parsing manifests that are edited and/or built on many non-Unix-like platforms that use ASCII or Unicode encodings. \n\n### Package dependency caching\n\nSwift Package Manager now caches package dependency repositories on a per-user basis, which reduces the amount of network traffic and increases performance of dependency resolution for subsequent uses of the same package.\n\nThe default location of the cache differs depending on the platform, but can be controlled using the new `--cache-path` option. SwiftPM also creates a symbolic link at `~/.swiftpm` referencing the default cache location.\n\nCompiled package manifests are also now cached on a per-user basis. This can be overridden using the new `--manifest-cache` option.\n"
  },
  {
    "path": "Documentation/ReleaseNotes/5.5.md",
    "content": "# SwiftPM 5.5 Release Notes\n\n### Package Collections\n\nYou can now use package collections to discover, manage, and publish curated lists of packages. Package collections are authored as static JSON documents and can be published to the web or distributed to local file systems. SwiftPM and Xcode locally share the same package collections, so either interface can manage your added collections.\n\nTo try the official Apple Swift Packages collection, run:\n\n```\nswift package-collection add https://developer.apple.com/swift/packages/collections/apple.json\n```\n\nThen, to see which packages are included in that collection and can now be imported in your code, run:\n\n```\nswift package-collection describe https://developer.apple.com/swift/packages/collections/apple.json\n```\n\nFor more information about usage and how to publish your own package collections, see the [Package Collections documentation](../PackageCollections.md).\n\n### Executable target testing\n\nTest targets can now link against executable targets as if they were libraries, so that they can test any data structures or algorithms in them. All the code in the executable except for the main entry point itself is available to the unit test. Separate executables are still linked, and can be tested as a subprocess in the same way as before. This feature is available to tests defined in packages that have a tools version of `5.5` or newer. (#3316)\n\n### Manifest API improvements\n\nTwo new dependency convenience initializers are now available (#3292, #3310):\n\n```\n.package(url: String, revision: String)\n.package(url: String, branch: String)\n```\n\nTarget-based dependency resolution has also been improved. A more intuitive `.product(name:, package:)` syntax is now accepted, where `package` is the package name as defined by the package URL. (#3280)\n\n### Other improvements\n\n`@main` can now be used in a single-source file executable as long as the name of the source file isn't `main.swift`. To work around special compiler semantics with single-file modules, SwiftPM now passes `-parse-as-library` when compiling an executable module that contains a single Swift source file whose name is not `main.swift`. This feature is available in packages that have a tools version of `5.5` or newer. (#3410)\n\nAn issue where resolution of packages with binary dependencies failed to extract the binary archive was fixed. (#3507)\n"
  },
  {
    "path": "Documentation/ReleaseNotes/5.6.md",
    "content": "# SwiftPM 5.6 Release Notes\n\n### Package Plugins\n\n[SE-0303](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0303-swiftpm-extensible-build-tools.md) Introduces the ability to define build tool plugins in SwiftPM, allowing custom tools to be automatically invoked during a build. Build tool plugins are focused on code generation during the build of a package, for such purposes as generating Swift source files from .proto files or from other inputs, in order to allow build tools to be incorporated into the build graph and to run automatically in a safe manner.\n\n[SE-0332](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0332-swiftpm-command-plugins.md) Extends SwiftPM plugin support first introduced with SE-0303 to allow the definition of custom command plugins — plugins that users can invoke directly from the SwiftPM CLI, or from an IDE that supports Swift Packages, in order to perform custom actions on their packages. A command plugin specifies the semantic intent of the command — this might be one of the predefined intents such “documentation generation” or “source code formatting”, or it might be a custom intent with a specialized verb that can be passed to the swift package command.\n\n### Manifest API Improvements\n\nSemantic version dependencies can now be resolved against Git tag names that contain only major and minor version identifiers. A tag with the form `X.Y` will be treated as `X.Y.0`. This improves compatibility with existing repositories.\n\nBoth parsing and comparison of semantic versions now strictly follow the Semantic Versioning 2.0.0 specification (https://semver.org/).\nThe parsing logic now treats the first \"-\" in a version string as the delimiter between the version core and the pre-release identifiers, only if there is no preceding \"+\". Otherwise, it's treated as part of a build metadata identifier.\nThe comparison logic now ignores build metadata identifiers, and treats 2 semantic versions as equal if and only if they're equal in their major, minor, patch versions and pre-release identifiers.\n\n`.package(name:, url:)` dependency syntax is deprecated in favor of `.package(url:)`, given that an explicit name attribute is no longer needed for target dependencies lookup.\n\nAdding a dependency requirement can now be done with the convenience initializer .package(url: String, exact: Version).\n\nDependency requirement enum calling convention is deprecated in favour of labeled argument:\n\n* `.package(url: String, .branch(String)) -> .package(url: String, branch: String)`\n* `.package(url: String, .revision(String)) -> .package(url: String, revision: String)`\n* `.package(url: String, .exact(Version)) -> .package(url: String, exact: Version)`\n\n### Other Improvements\n\nLocation of configuration files (including mirror file) have changed to accommodate new features that require more robust configuration directories structure, such as SE-0292:\n\n* `<project>/.swiftpm/config` (mirrors file) was moved to `<project>/.swiftpm/configuration/mirrors.json`. SwiftPM 5.6 will automatically copy the file from the old location to the new one and emit a warning to prompt the user to delete the file from the old location.\n* `~/.swiftpm/config/collections.json` (collections file) was moved to `~/.swiftpm/configuration/collections.json`. SwiftPM 5.6 will automatically copy the file from the old location to the new one and emit a warning to prompt the user to delete the file from the old location.\n\nTo increase the security of packages, SwiftPM performs trust on first use (TOFU) validation. The fingerprint of a package is now being recorded when the package is first downloaded from a Git repository or package registry. Subsequent downloads must have fingerprints matching previous recorded values, otherwise it would result in build warnings or failures depending on settings.\n\nIntroduce a second version of `Package.resolved` file format which more accurately captures package identity.\n"
  },
  {
    "path": "Documentation/ReleaseNotes/5.7.md",
    "content": "# SwiftPM 5.7 Release Notes\n\n### Package Plugins\n\n[SE-0303: Build tool plugins](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0303-swiftpm-extensible-build-tools.md) and [SE-0332: Command Plugins](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0332-swiftpm-command-plugins.md) which were first introduced in Swift 5.6 have been further refined, with support for generating resources and improved diagnostics. To learn more, refer to the [Getting Started with Plugins](../Plugins.md) guide.\n\n### Package Registry Support\n\nSwiftPM now supports package registry related capabilities introduced by [SE-0292](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0292-package-registry-service.md) and the corresponding [service specification](../Registry.md). With the exception of package publishing, SwiftPM can resolve and download dependencies from any compliant registry using the defined APIs.\n\nTo get started, users will need to specify their package registry by running the `swift package-registry set` subcommand or editing the `registries.json` configuration file. `swift package` tool's `--use-registry-identity-for-scm` and `--replace-scm-with-registry` options might also be of interest.\n  \n### Module Aliasing For Disambiguation\n\nModules with the same name from different packages can now be disambiguated by module aliasing [SE-0339](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0339-module-aliasing-for-disambiguation.md). When adding a product dependency for a target in a package manifest, use a new parameter `moduleAliases` to provide a new unique name for a conflicting module.\n\n\n* [#4119] \n \n  Add a `--disable-testable-imports` flag to `swift test` with which tests are built without the testability feature (`import @testable` disabled).\n\n"
  },
  {
    "path": "Documentation/ReleaseNotes/5.8.md",
    "content": "# SwiftPM 5.8 Release Notes\n\n## Package manifest changes\n\nSwiftPM targets can now specify the upcoming language features they require. `Package.swift` manifest syntax has been expanded with an API to include setting `enableUpcomingFeature` and `enableExperimentalFeature` flags at the target level, as specified by [SE-0362](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0362-piecemeal-future-features.md).\n  \nSwiftPM now allows exposing an executable product that consists solely of a binary target that is backed by an artifact bundle. This allows vending binary executables as their own separate package, independently of plugins that are using them.\n\nIn packages using tools version 5.8 or later, `Foundation` is no longer implicitly imported into package manifests. If `Foundation` APIs are used, the module needs to be imported explicitly.\n  \n## Package Registry Support\n\nSwiftPM now supports token authentication when interacting with a package registry. The `swift package-registry` command has two new subcommands `login` and `logout` as defined in [SE-0378](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0378-package-registry-auth.md) for adding/removing registry credentials.\n\n## Other improvements\n\nImproved handling of offline behavior when a compatible cached version of a dependency exists on disk in either the per-package or shared cache. SwiftPM will check for network availability status to determine if it should attempt to update a checked version of a dependency, and when offline will use the cached version without an update.  \n  \nNew `--pkg-config-path` option on `build`, `test`, and `run` commands has been introduced as an alternative to passing `PKG_CONFIG_PATH` environment variable. It allows specifying alternative path to search for `.pc` files used by `pkg-config`. Use the option multiple times to specify more than one path.\n\nAdded new `--emit-extension-block-symbols` and `--omit-extension-block-symbols` via `swift package dump-symbol-graph`. `--emit-extension-block-symbols` dumps symbol graph files that are extension block symbol format. The default behavior does not change. The `--omit-extension-block-symbols` flag will be used to explicitly disable the feature once the default behavior has been changed to `--emit-extension-block-symbols` in the future.\n"
  },
  {
    "path": "Documentation/ReleaseNotes/5.9.md",
    "content": "# SwiftPM 5.9 Release Notes\n\n## Cross compilation\n\nSwiftPM now supports cross compilation based on the Swift SDK bundle format. While the feature is still considered experimental, we invite users to try it out and provide feedback.\n\n## Package registry\n\nSwiftPM can now publish to a registry following the specification defined in SE-0391, as well as support signed packages, which may be required by a registry. Trust-on-first-use (TOFU) validation checks can now use signing identities in addition to fingerprints, and are enforced for source archives as well as package manifests.\n\n## Embedded resources\n\nBasic support for a new `.embedInCode` resource rule which allows embedding the contents of the resource into the executable code by generating a byte array\n\n```\nstruct PackageResources {\n  static let best_txt: [UInt8] = [104,101,108,108,111,32,119,111,114,108,100,10]\n}\n```\n\n## Other improvements\n\nThe `CompilerPluginSupport` module enables defining macro targets. Macro targets allow authoring and distributing custom Swift macros as APIs in a library.\n\nPackages can use the new `package` access modifier, allowing access of symbols in another target / module within the same package without making them public. SwiftPM automatically sets the new compiler configuration to ensure this feature works out-of-the-box for packages.\n  \nThe `allowNetworkConnections(scope:reason:)` setting gives a command plugin permissions to access the network. Permissions can be scoped to Unix domain sockets as well as local or remote IP connections, with an option to limit by port. For non-interactive use cases, the `--allow-network-connections` command-line flag allows network connections for a particular scope.\n\nWhen a package contains a single target, sources may be distributed anywhere within the `./Sources` directory. If sources are placed in a subdirectory under `./Sources/<target>`, or there is more than one target, the existing expectation for sources apply\n\nBuild tool plugins can be used with C-family targets\n"
  },
  {
    "path": "Documentation/ReleaseNotes/6.3.md",
    "content": "# SwiftPM 6.3 Release Notes\n\n## SwiftBuild: Preview of Next-Generation Build System\n\nSwiftBuild is being developed to replace the current native build system and brings several key improvements.  Packages that build successfully with the existing native (default) build system should build with SwiftBuild without requiring changes to your `Package.swift` or source code.\n\nFor more information, including known limitations and platform-specific issues, see the [SwiftBuild Preview documentation](https://github.com/swiftlang/swift-package-manager/blob/main/Sources/PackageManagerDocs/Documentation.docc/SwiftBuildPreview.md).\n\n\n### Trying SwiftBuild\n\nYou can preview the build system using the `--build-system` flag:\n\n```\n# Use SwiftBuild for building\nswift build --build-system swiftbuild\n\n# Use SwiftBuild for testing\nswift test --build-system swiftbuild\n\n# Use SwiftBuild for running executables\nswift run --build-system swiftbuild MyExecutable\n```\n\nThe native build system remains the default and continues to be fully supported. We encourage developers to try SwiftBuild and [provide feedback](https://github.com/swiftlang/swift-package-manager/issues) on their experience.\n\n## Improved Build Plugin Support for C Interoperability\n\nSwiftPM now properly supports generation of C source files from plugin tools into C module targets.\nIn addition, it supports generation of module maps, header files, and API notes.\n\nThis is an experimental feature. To enable it, add a tag to the swift tools version in the\npackage manifest (Package.swift) of the target that uses the generator plugin as follows:\n\n``` swift\n// swift-tools-version: 6.3;(experimentalCGen)\n```\n\nThere are some limitations to this experimental mode.\nThere can be only one generated module map for a given target.\nHeader files to which this module map refers must be in the same directory as the module map.\nThis is also true for any API notes files generated for modules in the module map.\n\nIf a module map is generated, you can not provide one in the public headers path for the target.\n\nTo assist in finding generated public header files, the build system adds the `include` directory from the plugin output directory\nto the include path for the module and all modules that transitively depend on it.\nThe name of this directory is currently fixed.\n\nThis functionality is available in **both** the native build system and SwiftBuild.\n\n## Improved Prebuilt Swift Syntax for Macros Support\n\nBetter support has been added to use prebuilts of the swift-syntax package in libraries that are only used by macros.\nThis allows for code sharing between macro targets.\n\nSwiftPM now detects when such a library may be used by non macro targets and disables use of prebuilts when this is detected.\nIt is disabled because mixing of swift-syntax prebuilts and swift-syntax built from source at link time has caused a number of issues.\n\n## Symbol Graph Generation: Control Over Inherited Documentation\n\nCommand plugins that generate symbol graphs can now control whether inherited documentation is included, providing better flexibility for different documentation styles.\n\n## Package Traits: Improved Discoverability\n\nA new `swift package show-traits` command makes it easier to discover the traits supported by a package.\n\n"
  },
  {
    "path": "Documentation/libSwiftPM.md",
    "content": "# libSwiftPM - SwiftPM as a Library\n\n**NOTE: The libSwiftPM API is currently _unstable_ and may change at any time.**\n\nSwiftPM has a library based architecture and the top-level library product is\ncalled `libSwiftPM`. Other packages can add SwiftPM as a package dependency and\ncreate powerful custom build tools on top of `libSwiftPM`.\n\nA subset of `libSwiftPM` that includes only the data model (without SwiftPM's\nbuild system) is available as `libSwiftPMDataModel`.  Any one client should\ndepend on one or the other, but not both.\n\nThe SwiftPM repository contains an [example](https://github.com/swiftlang/swift-package-manager/tree/main/Examples/package-info) that demonstrates the use of\n`libSwiftPM` in a Swift package. Use the following commands to run the example\npackage:\n\n```sh\n$ git clone https://github.com/swiftlang/swift-package-manager\n$ cd swift-package-manager/Examples/package-info\n$ swift run\n```\n"
  },
  {
    "path": "Examples/package-info/Package.swift",
    "content": "// swift-tools-version:5.7\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"package-info\",\n    platforms: [\n        .macOS(.v13),\n        .iOS(.v13)\n    ],\n    dependencies: [\n        // This just points to the SwiftPM at the root of this repository.\n        .package(name: \"swift-package-manager\", path: \"../../\"),\n        // You will want to depend on a stable semantic version instead:\n        // .package(url: \"https://github.com/swiftlang/swift-package-manager\", .exact(\"0.4.0\"))\n    ],\n    targets: [\n        .executableTarget(\n            name: \"package-info\",\n            dependencies: [\n                .product(name: \"SwiftPM\", package: \"swift-package-manager\")\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Examples/package-info/README.md",
    "content": "# package-info\n\nSample package built on top of libSwiftPM.\n"
  },
  {
    "path": "Examples/package-info/Sources/package-info/example.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Basics\nimport TSCBasic\nimport Workspace\n\n@main\n@available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)\nstruct Example {\n    static func main() async throws {\n        // PREREQUISITES\n        // ============\n\n        // We need a package to work with.\n        // This computes the path of this package root based on the file location\n        let packagePath = try Basics.AbsolutePath(validating: #file).parentDirectory.parentDirectory.parentDirectory\n\n        // LOADING\n        // =======\n\n        // There are several levels of information available.\n        // Each takes longer to load than the level above it, but provides more detail.\n\n        let observability = ObservabilitySystem({ print(\"\\($0): \\($1)\") }, outputStream: stdoutStream, logLevel: .debug)\n\n        let workspace = try Workspace(forRootPackage: packagePath)\n\n        let manifest = try await workspace.loadRootManifest(at: packagePath, observabilityScope: observability.topScope)\n\n        let package = try await workspace.loadRootPackage(at: packagePath, observabilityScope: observability.topScope)\n\n        let graph = try await workspace.loadPackageGraph(rootPath: packagePath, observabilityScope: observability.topScope)\n\n        // EXAMPLES\n        // ========\n\n        // Manifest\n        let products = manifest.products.map({ $0.name }).joined(separator: \", \")\n        print(\"Products:\", products)\n\n        let targets = manifest.targets.map({ $0.name }).joined(separator: \", \")\n        print(\"Targets:\", targets)\n\n        // Package\n        let executables = package.modules.filter({ $0.type == .executable }).map({ $0.name })\n        print(\"Executable targets:\", executables)\n\n        // PackageGraph\n        let numberOfFiles = graph.reachableModules.reduce(0, { $0 + $1.sources.paths.count })\n        print(\"Total number of source files (including dependencies):\", numberOfFiles)\n    }\n}\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package1\",\n    targets: [\n        .executableTarget(\n            name: \"Example\",\n            dependencies: [\n                \"Simple\",\n                \"Wrapper\"\n            ]\n        ),\n        .target(\n            name: \"Wrapper\",\n            dependencies: [\n                \"Simple\"\n            ]\n        ),\n        .binaryTarget(\n            name: \"Simple\",\n            path: \"Simple.artifactbundle\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Simple.artifactbundle/Makefile",
    "content": "SRC_FILES := $(wildcard *.c)\n\n# Define architectures and platforms\nARCHS := x86_64 arm64\nPLATFORMS := macos linux\n\n# Define output directories\nBUILD_DIR := build\nDIST_DIR := dist\n\n# Platform-specific settings\nMACOS_SDK := $(shell xcrun --sdk macosx --show-sdk-path 2>/dev/null || echo \"\")\nMACOS_MIN_VERSION := 10.15\n\n# Compiler flags\nCOMMON_FLAGS := -O2\n\n# Platform and architecture specific flags\nMACOS_X86_64_FLAGS := -target x86_64-apple-macos$(MACOS_MIN_VERSION) -isysroot $(MACOS_SDK)\nMACOS_ARM64_FLAGS := -target arm64-apple-macos$(MACOS_MIN_VERSION) -isysroot $(MACOS_SDK)\nLINUX_X86_64_FLAGS := -target x86_64-unknown-linux-gnu\nLINUX_ARM64_FLAGS := -target aarch64-unknown-linux-gnu\n\n.PHONY: all clean macos linux universal\n\nall: macos linux\n\n# Create necessary directories\n$(BUILD_DIR):\n\tmkdir -p $(BUILD_DIR)/macos/x86_64\n\tmkdir -p $(BUILD_DIR)/macos/arm64\n\tmkdir -p $(BUILD_DIR)/linux/x86_64\n\tmkdir -p $(BUILD_DIR)/linux/arm64\n\n$(DIST_DIR):\n\tmkdir -p $(DIST_DIR)/macos\n\tmkdir -p $(DIST_DIR)/linux\n\n# macOS x86_64 build\n$(BUILD_DIR)/macos/x86_64/%.o: %.c | $(BUILD_DIR)\n\tclang $(COMMON_FLAGS) $(MACOS_X86_64_FLAGS) -c -o $@ $<\n\n# macOS arm64 build\n$(BUILD_DIR)/macos/arm64/%.o: %.c | $(BUILD_DIR)\n\tclang $(COMMON_FLAGS) $(MACOS_ARM64_FLAGS) -c -o $@ $<\n\n# Linux x86_64 build\n$(BUILD_DIR)/linux/x86_64/%.o: %.c | $(BUILD_DIR)\n\tclang $(COMMON_FLAGS) $(LINUX_X86_64_FLAGS) -c -o $@ $<\n\n# Linux arm64 build\n$(BUILD_DIR)/linux/arm64/%.o: %.c | $(BUILD_DIR)\n\tclang $(COMMON_FLAGS) $(LINUX_ARM64_FLAGS) -c -o $@ $<\n\n# Define object files for each platform and architecture\nMACOS_X86_64_OBJ_FILES := $(patsubst %.c,$(BUILD_DIR)/macos/x86_64/%.o,$(SRC_FILES))\nMACOS_ARM64_OBJ_FILES := $(patsubst %.c,$(BUILD_DIR)/macos/arm64/%.o,$(SRC_FILES))\nLINUX_X86_64_OBJ_FILES := $(patsubst %.c,$(BUILD_DIR)/linux/x86_64/%.o,$(SRC_FILES))\nLINUX_ARM64_OBJ_FILES := $(patsubst %.c,$(BUILD_DIR)/linux/arm64/%.o,$(SRC_FILES))\n\n# Create individual architecture libraries\n$(DIST_DIR)/macos/libSimple_x86_64.a: $(MACOS_X86_64_OBJ_FILES) | $(DIST_DIR)\n\tllvm-ar rc $@ $^\n\n$(DIST_DIR)/macos/libSimple_arm64.a: $(MACOS_ARM64_OBJ_FILES) | $(DIST_DIR)\n\tllvm-ar rc $@ $^\n\n$(DIST_DIR)/linux/libSimple_x86_64.a: $(LINUX_X86_64_OBJ_FILES) | $(DIST_DIR)\n\tllvm-ar rc $@ $^\n\n$(DIST_DIR)/linux/libSimple_arm64.a: $(LINUX_ARM64_OBJ_FILES) | $(DIST_DIR)\n\tllvm-ar rc $@ $^\n\n# Create universal binary for macOS\n$(DIST_DIR)/macos/libSimple.a: $(DIST_DIR)/macos/libSimple_x86_64.a $(DIST_DIR)/macos/libSimple_arm64.a\n\tlipo -create -output $@ $^\n\n# For Linux, we'll provide separate libraries since lipo is macOS-specific\nlinux: $(DIST_DIR)/linux/libSimple_x86_64.a $(DIST_DIR)/linux/libSimple_arm64.a\n\t@echo \"Linux libraries built in $(DIST_DIR)/linux/\"\n\t@echo \"Note: For Linux, use the architecture-specific libraries as needed.\"\n\nmacos: $(DIST_DIR)/macos/libSimple.a\n\t@echo \"macOS universal library built at $(DIST_DIR)/macos/libSimple.a\"\n\nclean:\n\trm -rf $(BUILD_DIR) $(DIST_DIR)\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Simple.artifactbundle/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    products: [\n        .library(name: \"Simple\", type: .static, targets: [\"Simple\"]),\n    ],\n    targets: [\n        .target(\n            name: \"Simple\",\n            path: \".\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Simple.artifactbundle/build.sh",
    "content": "#!/bin/bash\n\n# currently only used for Windows\n\nrm -fr .build\nswift build --arch arm64 -c release\nswift build --arch x86_64 -c release\n\ncd dist\nrm -fr windows\nmkdir windows\ncd windows\ncp ../../.build/arm64-unknown-windows-msvc/release/libSimple.a Simple_arm64.lib\ncp ../../.build/x86_64-unknown-windows-msvc/release/libSimple.a Simple_x86_64.lib\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Simple.artifactbundle/include/simple.h",
    "content": "int foo(void);\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Simple.artifactbundle/include/simple.modulemap",
    "content": "module Simple {\n  header \"simple.h\"\n  export *\n}"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Simple.artifactbundle/info.json",
    "content": "{\n    \"schemaVersion\": \"1.0\",\n    \"artifacts\": {\n        \"simple\": {\n            \"type\": \"staticLibrary\",\n            \"version\": \"1.0.0\",\n            \"variants\": [\n                {\n                    \"path\": \"dist/macOS/libSimple.a\",\n                    \"supportedTriples\": [\"arm64-apple-macosx\", \"x86_64-apple-macosx\"],\n                    \"staticLibraryMetadata\": {\n                        \"headerPaths\": [\"include\"],\n                        \"moduleMapPath\": \"include/simple.modulemap\"\n                    }\n                },\n                {\n                    \"path\": \"dist/linux/libSimple_arm64.a\",\n                    \"supportedTriples\": [\"aarch64-unknown-linux-gnu\"],\n                    \"staticLibraryMetadata\": {\n                        \"headerPaths\": [\"include\"],\n                        \"moduleMapPath\": \"include/simple.modulemap\"\n                    }\n                },\n                {\n                    \"path\": \"dist/linux/libSimple_x86_64.a\",\n                    \"supportedTriples\": [\"x86_64-unknown-linux-gnu\"],\n                    \"staticLibraryMetadata\": {\n                        \"headerPaths\": [\"include\"],\n                        \"moduleMapPath\": \"include/simple.modulemap\"\n                    }\n                },\n                {\n                    \"path\": \"dist/windows/Simple_arm64.lib\",\n                    \"supportedTriples\": [\"aarch64-unknown-windows-msvc\"],\n                    \"staticLibraryMetadata\": {\n                        \"headerPaths\": [\"include\"],\n                        \"moduleMapPath\": \"include/simple.modulemap\"\n                    }\n                },\n                {\n                    \"path\": \"dist/windows/Simple_x86_64.lib\",\n                    \"supportedTriples\": [\"x86_64-unknown-windows-msvc\"],\n                    \"staticLibraryMetadata\": {\n                        \"headerPaths\": [\"include\"],\n                        \"moduleMapPath\": \"include/simple.modulemap\"\n                    }\n                },\n                             \n            ]\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Simple.artifactbundle/simple.c",
    "content": "int foo(void) { return 42; }\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Sources/Example/Example.swift",
    "content": "import Simple\nimport Wrapper\n\n@main\nstruct Example {\n    static func main() {\n        print(foo())\n        print(bar())\n    }\n}"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Sources/Wrapper/include/wrapper.h",
    "content": "int bar(void);\n"
  },
  {
    "path": "Fixtures/BinaryLibraries/Static/Package1/Sources/Wrapper/wrapper.c",
    "content": "#include \"simple.h\"\n\nint bar(void) { return foo(); }\n"
  },
  {
    "path": "Fixtures/BinaryTargets/Inputs/DynamicLibrary/DynamicLibrary.m",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2020 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\n#import \"DynamicLibrary.h\"\n\n@implementation DynamicLibrary\n@end\n"
  },
  {
    "path": "Fixtures/BinaryTargets/Inputs/DynamicLibrary/include/DynamicLibrary.h",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2020 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\n#import <Foundation/Foundation.h>\n\n@interface DynamicLibrary : NSObject\n@end\n"
  },
  {
    "path": "Fixtures/BinaryTargets/Inputs/StaticLibrary/StaticLibrary.m",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2020 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\n#import \"StaticLibrary.h\"\n\n@implementation StaticLibrary\n@end\n"
  },
  {
    "path": "Fixtures/BinaryTargets/Inputs/StaticLibrary/include/StaticLibrary.h",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2020 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\n#import <Foundation/Foundation.h>\n\n@interface StaticLibrary : NSObject\n@end\n"
  },
  {
    "path": "Fixtures/BinaryTargets/Inputs/SwiftFramework/SwiftFramework/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>$(DEVELOPMENT_LANGUAGE)</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleVersion</key>\n\t<string>$(CURRENT_PROJECT_VERSION)</string>\n\t<key>NSHumanReadableCopyright</key>\n\t<string>Copyright © 2020 David Hart. All rights reserved.</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "Fixtures/BinaryTargets/Inputs/SwiftFramework/SwiftFramework/SwiftFramework.h",
    "content": "//\n//  SwiftFramework.h\n//  SwiftFramework\n//\n//  Created by David Hart on 17.02.20.\n//  Copyright © 2020 David Hart. All rights reserved.\n//\n\n#import <Foundation/Foundation.h>\n\n//! Project version number for SwiftFramework.\nFOUNDATION_EXPORT double SwiftFrameworkVersionNumber;\n\n//! Project version string for SwiftFramework.\nFOUNDATION_EXPORT const unsigned char SwiftFrameworkVersionString[];\n\n// In this header, you should import all the public headers of your framework using statements like #import <SwiftFramework/PublicHeader.h>\n\n\n"
  },
  {
    "path": "Fixtures/BinaryTargets/Inputs/SwiftFramework/SwiftFramework/SwiftFramework.swift",
    "content": "//\n//  SwiftFramework.swift\n//  SwiftFramework\n//\n//  Created by David Hart on 17.02.20.\n//  Copyright © 2020 David Hart. All rights reserved.\n//\n\nimport Foundation\n\npublic struct SwiftFramework {\n    public init() {}\n}\n"
  },
  {
    "path": "Fixtures/BinaryTargets/TestBinary/Package.swift",
    "content": "// swift-tools-version:5.3\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestBinary\",\n    dependencies: [\n    ],\n    targets: [\n        .target(name: \"exe\", dependencies: [\"Library\"]),\n        .target(name: \"Library\", dependencies: [\"SwiftFramework\"]),\n        .target(name: \"cexe\", dependencies: [\"CLibrary\"]),\n        .target(name: \"CLibrary\", dependencies: [\"StaticLibrary\", \"DynamicLibrary\"]),\n        .binaryTarget(name: \"SwiftFramework\", path: \"SwiftFramework.xcframework\"),\n        .binaryTarget(name: \"StaticLibrary\", path: \"StaticLibrary.xcframework\"),\n        .binaryTarget(name: \"DynamicLibrary\", path: \"DynamicLibrary.xcframework\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/BinaryTargets/TestBinary/Sources/CLibrary/CLibrary.m",
    "content": "#import \"CLibrary.h\"\n\n@implementation CLibrary\n\n- (instancetype)init {\n    self = [super init];\n    _staticLibrary = [StaticLibrary new];\n    _dynamicLibrary = [DynamicLibrary new];\n    return self;\n}\n\n@end"
  },
  {
    "path": "Fixtures/BinaryTargets/TestBinary/Sources/CLibrary/include/CLibrary.h",
    "content": "#import <StaticLibrary.h>\n#import <DynamicLibrary.h>\n\n@interface CLibrary: NSObject\n\n@property (nonatomic, readonly) StaticLibrary* staticLibrary;\n@property (nonatomic, readonly) DynamicLibrary* dynamicLibrary;\n\n@end"
  },
  {
    "path": "Fixtures/BinaryTargets/TestBinary/Sources/Library/Library.swift",
    "content": "import SwiftFramework\n\npublic struct Library {\n    public let framework = SwiftFramework()\n\n    public init() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/BinaryTargets/TestBinary/Sources/cexe/main.m",
    "content": "#import <CLibrary.h>\n\nint main(int argc, const char* argv[]) {\n\tprintf(\"%s\", [CLibrary new].description.UTF8String);\n}\n"
  },
  {
    "path": "Fixtures/BinaryTargets/TestBinary/Sources/exe/main.swift",
    "content": "import SwiftFramework\nimport Library\n\nprint(SwiftFramework())\nprint(Library())\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CDynamicLookup/Foo.c",
    "content": "#include \"Foo.h\"\n\nint foo() {\n    bar();\n    int a = 5;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CDynamicLookup/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"CDynamicLookup\",\n    targets: [\n        .target(name: \"CDynamicLookup\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CDynamicLookup/include/Foo.h",
    "content": "void bar();\nint foo();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryNoIncludeDir/Cfactorial/Package.swift",
    "content": "// swift-tools-version:5.5\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Cfactorial\",\n    products: [\n        // Products define the executables and libraries a package produces, and make them visible to other packages.\n        .library(\n            name: \"Cfactorial\",\n            targets: [\"Cfactorial\"]),\n    ],\n    dependencies: [\n        // Dependencies declare other packages that this package depends on.\n        // .package(url: /* package url */, from: \"1.0.0\"),\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n        // Targets can depend on other targets in this package, and on products in packages this package depends on.\n        .target(\n            name: \"Cfactorial\",\n            dependencies: [],\n\t    path: \"Sources/factorial\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryNoIncludeDir/Cfactorial/Sources/factorial/factorial.c",
    "content": "//#include \"include/factorial.h\"\n#include \"factorial.h\"\nlong factorial(int n) {\n    if (n == 0 || n == 1) return 1;\n    return n * factorial(n-1);\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryNoIncludeDir/Cfactorial/Sources/factorial/factorial.h",
    "content": "#ifndef factorial_h\n#define factorial_h\n\n#include <stdio.h>\n\nlong factorial(int n);\n\n#endif /* factorial_h */\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryNoIncludeDir/Package.swift",
    "content": "// swift-tools-version:5.5\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Client\",\n    dependencies: [\n        // Dependencies declare other packages that this package depends on.\n        // .package(url: /* package url */, from: \"1.0.0\"),\n\t.package(path: \"Cfactorial\")\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n        // Targets can depend on other targets in this package, and on products in packages this package depends on.\n        .executableTarget(\n            name: \"Client\",\n            dependencies: [\"Cfactorial\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryNoIncludeDir/Sources/Client/main.swift",
    "content": "import Cfactorial\n\nprint(factorial(5))\nprint(\"Hello, world!\")\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryParentSearchPath/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\nxcuserdata/\nDerivedData/\n.swiftpm/config/registries.json\n.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata\n.netrc\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryParentSearchPath/Package.swift",
    "content": "// swift-tools-version: 5.5\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"CLibraryParentSearchPath\",\n    products: [\n        .library(\n            name: \"HeaderInclude\",\n            targets: [\"HeaderInclude\"]),\n    ],\n    targets: [\n        .target(\n            name: \"CHeaderInclude\",\n            cSettings: [\n                /*\n                 This package tests path normalization; incorrect path normalization on certain OSes (especially Windows) can lead to relative paths like these not being correctly passed to the C compiler.\n                 */\n                .headerSearchPath(\"../Constants\")\n            ]\n        ),\n        .target(\n            name: \"HeaderInclude\",\n            dependencies: [\n                \"CHeaderInclude\"\n            ]\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryParentSearchPath/Sources/CHeaderInclude/answers.c",
    "content": "\n#include \"answers.h\"\n#include \"Constants.h\"\n\nint getAnswer(void) {\n    return kTheAnswer;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryParentSearchPath/Sources/CHeaderInclude/include/answers.h",
    "content": "\n#ifndef answers_h\n#define answers_h\n\nextern int getAnswer(void);\n\n#endif /* answers_h */\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryParentSearchPath/Sources/Constants/Constants.h",
    "content": "\n#ifndef Constants_h\n#define Constants_h\n\nstatic const int kTheAnswer = 42;\n\n#endif /* Constants_h */\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryParentSearchPath/Sources/HeaderInclude/FinalForm.swift",
    "content": "\nimport CHeaderInclude\n\nenum Answer {\n    var value: Int { Int(getAnswer()) }\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibrarySources/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"CLibrarySources\",\n    targets: [\n        .target(name: \"CLibrarySources\", path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibrarySources/Sources/Foo.c",
    "content": "#include \"Foo.h\"\n\nint foo() {\n    int a = 5;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibrarySources/Sources/include/Foo.h",
    "content": "int foo();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibrarySources/Tests/CLibrarySourcesTests/foo.swift",
    "content": ""
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibrarySources/Tests/LinuxMain.swift",
    "content": ""
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryWithSpaces/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"CLibraryWithSpaces\",\n    targets: [\n        .target(name: \"Bar\", dependencies: [\"Foo\"]),\n        .target(name: \"Baz\", dependencies: [\"Foo\", \"Bar\"]),\n        .target(name: \"Foo\", dependencies: []),\n        .target(name: \"Bar with spaces\", dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryWithSpaces/Sources/Bar/Bar.c",
    "content": "#include \"Bar/Bar.h\"\n#include \"Foo/Foo.h\"\n\nint bar() {\n    int a = foo();\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryWithSpaces/Sources/Bar/include/Bar/Bar.h",
    "content": "int bar();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryWithSpaces/Sources/Bar with spaces/Bar.c",
    "content": "int bar() {\n    return 5;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryWithSpaces/Sources/Bar with spaces/include/Bar/Bar.h",
    "content": "int bar();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryWithSpaces/Sources/Baz/main.swift",
    "content": "import Foo\nimport Bar\n\nlet _ = foo()\nlet _ = bar()\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryWithSpaces/Sources/Foo/Foo.c",
    "content": "#include \"Foo/Foo.h\"\n\nint foo() {\n    int a = 5;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/CLibraryWithSpaces/Sources/Foo/include/Foo/Foo.h",
    "content": "int foo();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"ModuleMapGenerationCases\",\n    targets: [\n\t\t.target(\n            name: \"Baz\",\n            dependencies: [\"CustomModuleMap\", \"FlatInclude\", \"NonModuleDirectoryInclude\", \"UmbrellaHeader\", \"UmbrellaDirectoryInclude\", \"UmbrellaHeaderFlat\"]),\n        .target(\n            name: \"CustomModuleMap\",\n            dependencies: []),\n\t\t.target(\n            name: \"FlatInclude\",\n            dependencies: []),\n\t\t.target(\n            name: \"NoIncludeDir\",\n            dependencies: []),\n\t\t.target(\n            name: \"NonModuleDirectoryInclude\",\n            dependencies: []),\n\t\t.target(\n            name: \"UmbrellaDirectoryInclude\",\n            dependencies: []),\n\t\t.target(\n            name: \"UmbrellaHeader\",\n            dependencies: []),\n\t\t.target(\n            name: \"UmbrellaHeaderFlat\",\n            dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/Baz/main.swift",
    "content": "import CustomModuleMap\nimport UmbrellaDirectoryInclude\nimport FlatInclude\nimport UmbrellaHeader\nimport UmbrellaHeaderFlat\n\nlet _ = foo()\nlet _ = bar()\nlet _ = jaz()\nlet _ = umbrellaHeaderFlat()\nlet _ = qux()\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/CustomModuleMap/CustomModuleMap.c",
    "content": "#include \"CustomModuleMap.h\"\n\nint qux() {\n    int a = 6;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/CustomModuleMap/include/CustomModuleMap.h",
    "content": "int qux();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/CustomModuleMap/include/module.modulemap",
    "content": "module CustomModuleMap {\n    header \"CustomModuleMap.h\"\n\n    export *\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/FlatInclude/FlatInclude.c",
    "content": "#include \"FlatIncludeHeader.h\"\n\nint bar() {\n    int a = 6;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/FlatInclude/include/FlatIncludeHeader.h",
    "content": "int bar();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/NoIncludeDir/Jaz.c",
    "content": "\nint noDir() {\n    int a = 6;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/NonModuleDirectoryInclude/Maz.c",
    "content": "#include \"NonModuleDirectoryInclude/Maz.h\"\n\nint maz() {\n    int a = 6;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/NonModuleDirectoryInclude/include/NonModuleDirectoryInclude/Maz.h",
    "content": "int jaz();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/UmbrellaDirectoryInclude/Jaz.c",
    "content": "#include \"Paz.h\"\n\nint jaz() {\n    int a = 6;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/UmbrellaDirectoryInclude/include/Paz.h",
    "content": "int jaz();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/UmbrellaHeader/UmbrellaHeader.c",
    "content": "#include \"UmbrellaHeader/UmbrellaHeader.h\"\n\nint foo() {\n    int a = 5;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/UmbrellaHeader/include/UmbrellaHeader/UmbrellaHeader.h",
    "content": "int foo();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/UmbrellaHeaderFlat/UmbrellaHeader.c",
    "content": "#include \"UmbrellaHeaderFlat.h\"\n\nint umbrellaHeaderFlat() {\n    int a = 5;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ModuleMapGenerationCases/Sources/UmbrellaHeaderFlat/include/UmbrellaHeaderFlat.h",
    "content": "int umbrellaHeaderFlat();\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ObjCmacOSPackage/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"ObjCmacOSPackage\",\n    targets: [\n        .target(name: \"ObjCmacOSPackage\", path: \"Sources\"),\n        .testTarget(name: \"ObjCmacOSPackageTests\", dependencies: [\"ObjCmacOSPackage\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ObjCmacOSPackage/Sources/HelloWorldExample.m",
    "content": "#import <Foundation/Foundation.h>\n#import \"HelloWorldExample.h\"\n\n@implementation HelloWorld\n- (NSString *)hello:(NSString *)name {\n  if(!name) {\n    name = @\"World\";\n  }\n  return [NSString stringWithFormat:@\"Hello, %@!\", name];\n}\n@end\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ObjCmacOSPackage/Sources/include/HelloWorldExample.h",
    "content": "#import <Foundation/Foundation.h>\n\n@interface HelloWorld : NSObject\n\n- (NSString *)hello:(NSString *)name;\n\n@end\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/ObjCmacOSPackage/Tests/ObjCmacOSPackageTests/HelloWorldTest.m",
    "content": "#import <XCTest/XCTest.h>\n\n# import \"HelloWorldExample.h\"\n\n@interface HelloWorldTest : XCTestCase\n\n@end\n\n@implementation HelloWorldTest\n\n- (HelloWorld *)helloWorld {\n  return [[HelloWorld alloc] init];\n}\n\n- (void)testNoName {\n  NSString *input = nil;\n  NSString *expected = @\"Hello, World!\";\n  NSString *result = [[self helloWorld] hello:input];\n  XCTAssertEqualObjects(expected, result);\n}\n\n- (void)testSampleName {\n  NSString *input = @\"Alice\";\n  NSString *expected = @\"Hello, Alice!\";\n  NSString *result = [[self helloWorld] hello:input];\n  XCTAssertEqualObjects(expected, result);\n}\n  \n- (void)testOtherSampleName {\n  NSString *input = @\"Bob\";\n  NSString *expected = @\"Hello, Bob!\";\n  NSString *result = [[self helloWorld] hello:input];\n  XCTAssertEqualObjects(expected, result);\n}\n\n@end\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/SwiftCMixed/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"SwiftCMixed\",\n    targets: [\n        .target(name: \"SeaExec\", dependencies: [\"SeaLib\"]),\n        .target(name: \"CExec\", dependencies: [\"SeaLib\"]),\n        .target(name: \"SeaLib\", dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/SwiftCMixed/Sources/CExec/main.c",
    "content": "#include \"Foo.h\"\n#include<stdio.h>\n\nint main() {\n    printf(\"%d\", foo(5));\n    return 0;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/SwiftCMixed/Sources/SeaExec/main.swift",
    "content": "import SeaLib\n\nlet a = foo(5)\nprint(\"a = \\(a)\")\n\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/SwiftCMixed/Sources/SeaLib/Foo.c",
    "content": "int foo(int a) {\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/CFamilyTargets/SwiftCMixed/Sources/SeaLib/include/Foo.h",
    "content": "int foo(int a);\n"
  },
  {
    "path": "Fixtures/Collections/GitHub/contributors.json",
    "content": "[\n  {\n    \"login\": \"octocat\",\n    \"id\": 1,\n    \"node_id\": \"MDQ6VXNlcjE=\",\n    \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n    \"gravatar_id\": \"\",\n    \"url\": \"https://api.github.com/users/octocat\",\n    \"html_url\": \"https://github.com/octocat\",\n    \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n    \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n    \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n    \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n    \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n    \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n    \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n    \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n    \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n    \"type\": \"User\",\n    \"site_admin\": false,\n    \"contributions\": 32\n  }\n]\n"
  },
  {
    "path": "Fixtures/Collections/GitHub/languages.json",
    "content": "{\n  \"Swift\": 3836385,\n  \"Shell\": 96027,\n  \"C\": 87433,\n}\n"
  },
  {
    "path": "Fixtures/Collections/GitHub/license.json",
    "content": "{\n  \"name\": \"LICENSE\",\n  \"path\": \"LICENSE\",\n  \"sha\": \"401c59dcc4570b954dd6d345e76199e1f4e76266\",\n  \"size\": 1077,\n  \"url\": \"https://api.github.com/repos/benbalter/gman/contents/LICENSE?ref=main\",\n  \"html_url\": \"https://github.com/benbalter/gman/blob/main/LICENSE\",\n  \"git_url\": \"https://api.github.com/repos/benbalter/gman/git/blobs/401c59dcc4570b954dd6d345e76199e1f4e76266\",\n  \"download_url\": \"https://raw.githubusercontent.com/benbalter/gman/main/LICENSE?lab=true\",\n  \"type\": \"file\",\n  \"content\": \"VGhlIE1JVCBMaWNlbnNlIChNSVQpCgpDb3B5cmlnaHQgKGMpIDIwMTMgQmVu\\nIEJhbHRlcgoKUGVybWlzc2lvbiBpcyBoZXJlYnkgZ3JhbnRlZCwgZnJlZSBv\\nZiBjaGFyZ2UsIHRvIGFueSBwZXJzb24gb2J0YWluaW5nIGEgY29weSBvZgp0\\naGlzIHNvZnR3YXJlIGFuZCBhc3NvY2lhdGVkIGRvY3VtZW50YXRpb24gZmls\\nZXMgKHRoZSAiU29mdHdhcmUiKSwgdG8gZGVhbCBpbgp0aGUgU29mdHdhcmUg\\nd2l0aG91dCByZXN0cmljdGlvbiwgaW5jbHVkaW5nIHdpdGhvdXQgbGltaXRh\\ndGlvbiB0aGUgcmlnaHRzIHRvCnVzZSwgY29weSwgbW9kaWZ5LCBtZXJnZSwg\\ncHVibGlzaCwgZGlzdHJpYnV0ZSwgc3VibGljZW5zZSwgYW5kL29yIHNlbGwg\\nY29waWVzIG9mCnRoZSBTb2Z0d2FyZSwgYW5kIHRvIHBlcm1pdCBwZXJzb25z\\nIHRvIHdob20gdGhlIFNvZnR3YXJlIGlzIGZ1cm5pc2hlZCB0byBkbyBzbywK\\nc3ViamVjdCB0byB0aGUgZm9sbG93aW5nIGNvbmRpdGlvbnM6CgpUaGUgYWJv\\ndmUgY29weXJpZ2h0IG5vdGljZSBhbmQgdGhpcyBwZXJtaXNzaW9uIG5vdGlj\\nZSBzaGFsbCBiZSBpbmNsdWRlZCBpbiBhbGwKY29waWVzIG9yIHN1YnN0YW50\\naWFsIHBvcnRpb25zIG9mIHRoZSBTb2Z0d2FyZS4KClRIRSBTT0ZUV0FSRSBJ\\nUyBQUk9WSURFRCAiQVMgSVMiLCBXSVRIT1VUIFdBUlJBTlRZIE9GIEFOWSBL\\nSU5ELCBFWFBSRVNTIE9SCklNUExJRUQsIElOQ0xVRElORyBCVVQgTk9UIExJ\\nTUlURUQgVE8gVEhFIFdBUlJBTlRJRVMgT0YgTUVSQ0hBTlRBQklMSVRZLCBG\\nSVRORVNTCkZPUiBBIFBBUlRJQ1VMQVIgUFVSUE9TRSBBTkQgTk9OSU5GUklO\\nR0VNRU5ULiBJTiBOTyBFVkVOVCBTSEFMTCBUSEUgQVVUSE9SUyBPUgpDT1BZ\\nUklHSFQgSE9MREVSUyBCRSBMSUFCTEUgRk9SIEFOWSBDTEFJTSwgREFNQUdF\\nUyBPUiBPVEhFUiBMSUFCSUxJVFksIFdIRVRIRVIKSU4gQU4gQUNUSU9OIE9G\\nIENPTlRSQUNULCBUT1JUIE9SIE9USEVSV0lTRSwgQVJJU0lORyBGUk9NLCBP\\nVVQgT0YgT1IgSU4KQ09OTkVDVElPTiBXSVRIIFRIRSBTT0ZUV0FSRSBPUiBU\\nSEUgVVNFIE9SIE9USEVSIERFQUxJTkdTIElOIFRIRSBTT0ZUV0FSRS4K\\n\",\n  \"encoding\": \"base64\",\n  \"_links\": {\n    \"self\": \"https://api.github.com/repos/benbalter/gman/contents/LICENSE?ref=main\",\n    \"git\": \"https://api.github.com/repos/benbalter/gman/git/blobs/401c59dcc4570b954dd6d345e76199e1f4e76266\",\n    \"html\": \"https://github.com/benbalter/gman/blob/main/LICENSE\"\n  },\n  \"license\": {\n    \"key\": \"mit\",\n    \"name\": \"MIT License\",\n    \"spdx_id\": \"MIT\",\n    \"url\": \"https://api.github.com/licenses/mit\",\n    \"node_id\": \"MDc6TGljZW5zZW1pdA==\"\n  }\n}\n"
  },
  {
    "path": "Fixtures/Collections/GitHub/metadata.json",
    "content": "{\n  \"id\": 1296269,\n  \"node_id\": \"MDEwOlJlcG9zaXRvcnkxMjk2MjY5\",\n  \"name\": \"Hello-World\",\n  \"full_name\": \"octocat/Hello-World\",\n  \"owner\": {\n    \"login\": \"octocat\",\n    \"id\": 1,\n    \"node_id\": \"MDQ6VXNlcjE=\",\n    \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n    \"gravatar_id\": \"\",\n    \"url\": \"https://api.github.com/users/octocat\",\n    \"html_url\": \"https://github.com/octocat\",\n    \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n    \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n    \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n    \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n    \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n    \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n    \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n    \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n    \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n    \"type\": \"User\",\n    \"site_admin\": false\n  },\n  \"private\": false,\n  \"html_url\": \"https://github.com/octocat/Hello-World\",\n  \"description\": \"This your first repo!\",\n  \"fork\": false,\n  \"url\": \"https://api.github.com/repos/octocat/Hello-World\",\n  \"archive_url\": \"https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}\",\n  \"assignees_url\": \"https://api.github.com/repos/octocat/Hello-World/assignees{/user}\",\n  \"blobs_url\": \"https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}\",\n  \"branches_url\": \"https://api.github.com/repos/octocat/Hello-World/branches{/branch}\",\n  \"collaborators_url\": \"https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}\",\n  \"comments_url\": \"https://api.github.com/repos/octocat/Hello-World/comments{/number}\",\n  \"commits_url\": \"https://api.github.com/repos/octocat/Hello-World/commits{/sha}\",\n  \"compare_url\": \"https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}\",\n  \"contents_url\": \"https://api.github.com/repos/octocat/Hello-World/contents/{+path}\",\n  \"contributors_url\": \"https://api.github.com/repos/octocat/Hello-World/contributors\",\n  \"deployments_url\": \"https://api.github.com/repos/octocat/Hello-World/deployments\",\n  \"downloads_url\": \"https://api.github.com/repos/octocat/Hello-World/downloads\",\n  \"events_url\": \"https://api.github.com/repos/octocat/Hello-World/events\",\n  \"forks_url\": \"https://api.github.com/repos/octocat/Hello-World/forks\",\n  \"git_commits_url\": \"https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}\",\n  \"git_refs_url\": \"https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}\",\n  \"git_tags_url\": \"https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}\",\n  \"git_url\": \"git:github.com/octocat/Hello-World.git\",\n  \"issue_comment_url\": \"https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}\",\n  \"issue_events_url\": \"https://api.github.com/repos/octocat/Hello-World/issues/events{/number}\",\n  \"issues_url\": \"https://api.github.com/repos/octocat/Hello-World/issues{/number}\",\n  \"keys_url\": \"https://api.github.com/repos/octocat/Hello-World/keys{/key_id}\",\n  \"labels_url\": \"https://api.github.com/repos/octocat/Hello-World/labels{/name}\",\n  \"languages_url\": \"https://api.github.com/repos/octocat/Hello-World/languages\",\n  \"merges_url\": \"https://api.github.com/repos/octocat/Hello-World/merges\",\n  \"milestones_url\": \"https://api.github.com/repos/octocat/Hello-World/milestones{/number}\",\n  \"notifications_url\": \"https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}\",\n  \"pulls_url\": \"https://api.github.com/repos/octocat/Hello-World/pulls{/number}\",\n  \"releases_url\": \"https://api.github.com/repos/octocat/Hello-World/releases{/id}\",\n  \"ssh_url\": \"git@github.com:octocat/Hello-World.git\",\n  \"stargazers_url\": \"https://api.github.com/repos/octocat/Hello-World/stargazers\",\n  \"statuses_url\": \"https://api.github.com/repos/octocat/Hello-World/statuses/{sha}\",\n  \"subscribers_url\": \"https://api.github.com/repos/octocat/Hello-World/subscribers\",\n  \"subscription_url\": \"https://api.github.com/repos/octocat/Hello-World/subscription\",\n  \"tags_url\": \"https://api.github.com/repos/octocat/Hello-World/tags\",\n  \"teams_url\": \"https://api.github.com/repos/octocat/Hello-World/teams\",\n  \"trees_url\": \"https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}\",\n  \"clone_url\": \"https://github.com/octocat/Hello-World.git\",\n  \"mirror_url\": \"git:git.example.com/octocat/Hello-World\",\n  \"hooks_url\": \"https://api.github.com/repos/octocat/Hello-World/hooks\",\n  \"svn_url\": \"https://svn.github.com/octocat/Hello-World\",\n  \"homepage\": \"https://github.com\",\n  \"language\": null,\n  \"forks_count\": 9,\n  \"forks\": 9,\n  \"stargazers_count\": 80,\n  \"watchers_count\": 80,\n  \"watchers\": 80,\n  \"size\": 108,\n  \"default_branch\": \"main\",\n  \"open_issues_count\": 0,\n  \"open_issues\": 0,\n  \"is_template\": true,\n  \"topics\": [\n    \"octocat\",\n    \"atom\",\n    \"electron\",\n    \"api\"\n  ],\n  \"has_issues\": true,\n  \"has_projects\": true,\n  \"has_wiki\": true,\n  \"has_pages\": false,\n  \"has_downloads\": true,\n  \"archived\": false,\n  \"disabled\": false,\n  \"visibility\": \"public\",\n  \"pushed_at\": \"2011-01-26T19:06:43Z\",\n  \"created_at\": \"2011-01-26T19:01:12Z\",\n  \"updated_at\": \"2011-01-26T19:14:43Z\",\n  \"permissions\": {\n    \"pull\": true,\n    \"push\": false,\n    \"admin\": false\n  },\n  \"allow_rebase_merge\": true,\n  \"template_repository\": null,\n  \"temp_clone_token\": \"ABTLWHOULUVAXGTRYU7OC2876QJ2O\",\n  \"allow_squash_merge\": true,\n  \"delete_branch_on_merge\": true,\n  \"allow_merge_commit\": true,\n  \"subscribers_count\": 42,\n  \"network_count\": 0,\n  \"license\": {\n    \"key\": \"mit\",\n    \"name\": \"MIT License\",\n    \"spdx_id\": \"MIT\",\n    \"url\": \"https://api.github.com/licenses/mit\",\n    \"node_id\": \"MDc6TGljZW5zZW1pdA==\"\n  },\n  \"organization\": {\n    \"login\": \"octocat\",\n    \"id\": 1,\n    \"node_id\": \"MDQ6VXNlcjE=\",\n    \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n    \"gravatar_id\": \"\",\n    \"url\": \"https://api.github.com/users/octocat\",\n    \"html_url\": \"https://github.com/octocat\",\n    \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n    \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n    \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n    \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n    \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n    \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n    \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n    \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n    \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n    \"type\": \"Organization\",\n    \"site_admin\": false\n  },\n  \"parent\": {\n    \"id\": 1296269,\n    \"node_id\": \"MDEwOlJlcG9zaXRvcnkxMjk2MjY5\",\n    \"name\": \"Hello-World\",\n    \"full_name\": \"octocat/Hello-World\",\n    \"owner\": {\n      \"login\": \"octocat\",\n      \"id\": 1,\n      \"node_id\": \"MDQ6VXNlcjE=\",\n      \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n      \"gravatar_id\": \"\",\n      \"url\": \"https://api.github.com/users/octocat\",\n      \"html_url\": \"https://github.com/octocat\",\n      \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n      \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n      \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n      \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n      \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n      \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n      \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n      \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n      \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n      \"type\": \"User\",\n      \"site_admin\": false\n    },\n    \"private\": false,\n    \"html_url\": \"https://github.com/octocat/Hello-World\",\n    \"description\": \"This your first repo!\",\n    \"fork\": false,\n    \"url\": \"https://api.github.com/repos/octocat/Hello-World\",\n    \"archive_url\": \"https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}\",\n    \"assignees_url\": \"https://api.github.com/repos/octocat/Hello-World/assignees{/user}\",\n    \"blobs_url\": \"https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}\",\n    \"branches_url\": \"https://api.github.com/repos/octocat/Hello-World/branches{/branch}\",\n    \"collaborators_url\": \"https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}\",\n    \"comments_url\": \"https://api.github.com/repos/octocat/Hello-World/comments{/number}\",\n    \"commits_url\": \"https://api.github.com/repos/octocat/Hello-World/commits{/sha}\",\n    \"compare_url\": \"https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}\",\n    \"contents_url\": \"https://api.github.com/repos/octocat/Hello-World/contents/{+path}\",\n    \"contributors_url\": \"https://api.github.com/repos/octocat/Hello-World/contributors\",\n    \"deployments_url\": \"https://api.github.com/repos/octocat/Hello-World/deployments\",\n    \"downloads_url\": \"https://api.github.com/repos/octocat/Hello-World/downloads\",\n    \"events_url\": \"https://api.github.com/repos/octocat/Hello-World/events\",\n    \"forks_url\": \"https://api.github.com/repos/octocat/Hello-World/forks\",\n    \"git_commits_url\": \"https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}\",\n    \"git_refs_url\": \"https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}\",\n    \"git_tags_url\": \"https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}\",\n    \"git_url\": \"git:github.com/octocat/Hello-World.git\",\n    \"issue_comment_url\": \"https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}\",\n    \"issue_events_url\": \"https://api.github.com/repos/octocat/Hello-World/issues/events{/number}\",\n    \"issues_url\": \"https://api.github.com/repos/octocat/Hello-World/issues{/number}\",\n    \"keys_url\": \"https://api.github.com/repos/octocat/Hello-World/keys{/key_id}\",\n    \"labels_url\": \"https://api.github.com/repos/octocat/Hello-World/labels{/name}\",\n    \"languages_url\": \"https://api.github.com/repos/octocat/Hello-World/languages\",\n    \"merges_url\": \"https://api.github.com/repos/octocat/Hello-World/merges\",\n    \"milestones_url\": \"https://api.github.com/repos/octocat/Hello-World/milestones{/number}\",\n    \"notifications_url\": \"https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}\",\n    \"pulls_url\": \"https://api.github.com/repos/octocat/Hello-World/pulls{/number}\",\n    \"releases_url\": \"https://api.github.com/repos/octocat/Hello-World/releases{/id}\",\n    \"ssh_url\": \"git@github.com:octocat/Hello-World.git\",\n    \"stargazers_url\": \"https://api.github.com/repos/octocat/Hello-World/stargazers\",\n    \"statuses_url\": \"https://api.github.com/repos/octocat/Hello-World/statuses/{sha}\",\n    \"subscribers_url\": \"https://api.github.com/repos/octocat/Hello-World/subscribers\",\n    \"subscription_url\": \"https://api.github.com/repos/octocat/Hello-World/subscription\",\n    \"tags_url\": \"https://api.github.com/repos/octocat/Hello-World/tags\",\n    \"teams_url\": \"https://api.github.com/repos/octocat/Hello-World/teams\",\n    \"trees_url\": \"https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}\",\n    \"clone_url\": \"https://github.com/octocat/Hello-World.git\",\n    \"mirror_url\": \"git:git.example.com/octocat/Hello-World\",\n    \"hooks_url\": \"https://api.github.com/repos/octocat/Hello-World/hooks\",\n    \"svn_url\": \"https://svn.github.com/octocat/Hello-World\",\n    \"homepage\": \"https://github.com\",\n    \"language\": null,\n    \"forks_count\": 9,\n    \"stargazers_count\": 80,\n    \"watchers_count\": 80,\n    \"size\": 108,\n    \"default_branch\": \"main\",\n    \"open_issues_count\": 0,\n    \"is_template\": true,\n    \"topics\": [\n      \"octocat\",\n      \"atom\",\n      \"electron\",\n      \"api\"\n    ],\n    \"has_issues\": true,\n    \"has_projects\": true,\n    \"has_wiki\": true,\n    \"has_pages\": false,\n    \"has_downloads\": true,\n    \"archived\": false,\n    \"disabled\": false,\n    \"visibility\": \"public\",\n    \"pushed_at\": \"2011-01-26T19:06:43Z\",\n    \"created_at\": \"2011-01-26T19:01:12Z\",\n    \"updated_at\": \"2011-01-26T19:14:43Z\",\n    \"permissions\": {\n      \"admin\": false,\n      \"push\": false,\n      \"pull\": true\n    },\n    \"allow_rebase_merge\": true,\n    \"template_repository\": null,\n    \"temp_clone_token\": \"ABTLWHOULUVAXGTRYU7OC2876QJ2O\",\n    \"allow_squash_merge\": true,\n    \"delete_branch_on_merge\": true,\n    \"allow_merge_commit\": true,\n    \"subscribers_count\": 42,\n    \"network_count\": 0,\n    \"license\": {\n      \"key\": \"mit\",\n      \"name\": \"MIT License\",\n      \"url\": \"https://api.github.com/licenses/mit\",\n      \"spdx_id\": \"MIT\",\n      \"node_id\": \"MDc6TGljZW5zZW1pdA==\",\n      \"html_url\": \"https://api.github.com/licenses/mit\"\n    },\n    \"forks\": 1,\n    \"open_issues\": 1,\n    \"watchers\": 1\n  },\n  \"source\": {\n    \"id\": 1296269,\n    \"node_id\": \"MDEwOlJlcG9zaXRvcnkxMjk2MjY5\",\n    \"name\": \"Hello-World\",\n    \"full_name\": \"octocat/Hello-World\",\n    \"owner\": {\n      \"login\": \"octocat\",\n      \"id\": 1,\n      \"node_id\": \"MDQ6VXNlcjE=\",\n      \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n      \"gravatar_id\": \"\",\n      \"url\": \"https://api.github.com/users/octocat\",\n      \"html_url\": \"https://github.com/octocat\",\n      \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n      \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n      \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n      \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n      \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n      \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n      \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n      \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n      \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n      \"type\": \"User\",\n      \"site_admin\": false\n    },\n    \"private\": false,\n    \"html_url\": \"https://github.com/octocat/Hello-World\",\n    \"description\": \"This your first repo!\",\n    \"fork\": false,\n    \"url\": \"https://api.github.com/repos/octocat/Hello-World\",\n    \"archive_url\": \"https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}\",\n    \"assignees_url\": \"https://api.github.com/repos/octocat/Hello-World/assignees{/user}\",\n    \"blobs_url\": \"https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}\",\n    \"branches_url\": \"https://api.github.com/repos/octocat/Hello-World/branches{/branch}\",\n    \"collaborators_url\": \"https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}\",\n    \"comments_url\": \"https://api.github.com/repos/octocat/Hello-World/comments{/number}\",\n    \"commits_url\": \"https://api.github.com/repos/octocat/Hello-World/commits{/sha}\",\n    \"compare_url\": \"https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}\",\n    \"contents_url\": \"https://api.github.com/repos/octocat/Hello-World/contents/{+path}\",\n    \"contributors_url\": \"https://api.github.com/repos/octocat/Hello-World/contributors\",\n    \"deployments_url\": \"https://api.github.com/repos/octocat/Hello-World/deployments\",\n    \"downloads_url\": \"https://api.github.com/repos/octocat/Hello-World/downloads\",\n    \"events_url\": \"https://api.github.com/repos/octocat/Hello-World/events\",\n    \"forks_url\": \"https://api.github.com/repos/octocat/Hello-World/forks\",\n    \"git_commits_url\": \"https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}\",\n    \"git_refs_url\": \"https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}\",\n    \"git_tags_url\": \"https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}\",\n    \"git_url\": \"git:github.com/octocat/Hello-World.git\",\n    \"issue_comment_url\": \"https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}\",\n    \"issue_events_url\": \"https://api.github.com/repos/octocat/Hello-World/issues/events{/number}\",\n    \"issues_url\": \"https://api.github.com/repos/octocat/Hello-World/issues{/number}\",\n    \"keys_url\": \"https://api.github.com/repos/octocat/Hello-World/keys{/key_id}\",\n    \"labels_url\": \"https://api.github.com/repos/octocat/Hello-World/labels{/name}\",\n    \"languages_url\": \"https://api.github.com/repos/octocat/Hello-World/languages\",\n    \"merges_url\": \"https://api.github.com/repos/octocat/Hello-World/merges\",\n    \"milestones_url\": \"https://api.github.com/repos/octocat/Hello-World/milestones{/number}\",\n    \"notifications_url\": \"https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}\",\n    \"pulls_url\": \"https://api.github.com/repos/octocat/Hello-World/pulls{/number}\",\n    \"releases_url\": \"https://api.github.com/repos/octocat/Hello-World/releases{/id}\",\n    \"ssh_url\": \"git@github.com:octocat/Hello-World.git\",\n    \"stargazers_url\": \"https://api.github.com/repos/octocat/Hello-World/stargazers\",\n    \"statuses_url\": \"https://api.github.com/repos/octocat/Hello-World/statuses/{sha}\",\n    \"subscribers_url\": \"https://api.github.com/repos/octocat/Hello-World/subscribers\",\n    \"subscription_url\": \"https://api.github.com/repos/octocat/Hello-World/subscription\",\n    \"tags_url\": \"https://api.github.com/repos/octocat/Hello-World/tags\",\n    \"teams_url\": \"https://api.github.com/repos/octocat/Hello-World/teams\",\n    \"trees_url\": \"https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}\",\n    \"clone_url\": \"https://github.com/octocat/Hello-World.git\",\n    \"mirror_url\": \"git:git.example.com/octocat/Hello-World\",\n    \"hooks_url\": \"https://api.github.com/repos/octocat/Hello-World/hooks\",\n    \"svn_url\": \"https://svn.github.com/octocat/Hello-World\",\n    \"homepage\": \"https://github.com\",\n    \"language\": null,\n    \"forks_count\": 9,\n    \"stargazers_count\": 80,\n    \"watchers_count\": 80,\n    \"size\": 108,\n    \"default_branch\": \"main\",\n    \"open_issues_count\": 0,\n    \"is_template\": true,\n    \"topics\": [\n      \"octocat\",\n      \"atom\",\n      \"electron\",\n      \"api\"\n    ],\n    \"has_issues\": true,\n    \"has_projects\": true,\n    \"has_wiki\": true,\n    \"has_pages\": false,\n    \"has_downloads\": true,\n    \"archived\": false,\n    \"disabled\": false,\n    \"visibility\": \"public\",\n    \"pushed_at\": \"2011-01-26T19:06:43Z\",\n    \"created_at\": \"2011-01-26T19:01:12Z\",\n    \"updated_at\": \"2011-01-26T19:14:43Z\",\n    \"permissions\": {\n      \"admin\": false,\n      \"push\": false,\n      \"pull\": true\n    },\n    \"allow_rebase_merge\": true,\n    \"template_repository\": null,\n    \"temp_clone_token\": \"ABTLWHOULUVAXGTRYU7OC2876QJ2O\",\n    \"allow_squash_merge\": true,\n    \"delete_branch_on_merge\": true,\n    \"allow_merge_commit\": true,\n    \"subscribers_count\": 42,\n    \"network_count\": 0,\n    \"license\": {\n      \"key\": \"mit\",\n      \"name\": \"MIT License\",\n      \"url\": \"https://api.github.com/licenses/mit\",\n      \"spdx_id\": \"MIT\",\n      \"node_id\": \"MDc6TGljZW5zZW1pdA==\",\n      \"html_url\": \"https://api.github.com/licenses/mit\"\n    },\n    \"forks\": 1,\n    \"open_issues\": 1,\n    \"watchers\": 1\n  }\n}\n"
  },
  {
    "path": "Fixtures/Collections/GitHub/readme.json",
    "content": "{\n  \"type\": \"file\",\n  \"encoding\": \"base64\",\n  \"size\": 5362,\n  \"name\": \"README.md\",\n  \"path\": \"README.md\",\n  \"content\": \"encoded content ...\",\n  \"sha\": \"3d21ec53a331a6f037a91c368710b99387d012c1\",\n  \"url\": \"https://api.github.com/repos/octokit/octokit.rb/contents/README.md\",\n  \"git_url\": \"https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1\",\n  \"html_url\": \"https://github.com/octokit/octokit.rb/blob/main/README.md\",\n  \"download_url\": \"https://raw.githubusercontent.com/octokit/octokit.rb/main/README.md\",\n  \"_links\": {\n    \"git\": \"https://api.github.com/repos/octokit/octokit.rb/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1\",\n    \"self\": \"https://api.github.com/repos/octokit/octokit.rb/contents/README.md\",\n    \"html\": \"https://github.com/octokit/octokit.rb/blob/main/README.md\"\n  }\n}\n"
  },
  {
    "path": "Fixtures/Collections/GitHub/releases.json",
    "content": "[\n  {\n    \"url\": \"https://api.github.com/repos/octocat/Hello-World/releases/1\",\n    \"html_url\": \"https://github.com/octocat/Hello-World/releases/v1.0.0\",\n    \"assets_url\": \"https://api.github.com/repos/octocat/Hello-World/releases/1/assets\",\n    \"upload_url\": \"https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}\",\n    \"tarball_url\": \"https://api.github.com/repos/octocat/Hello-World/tarball/v1.0.0\",\n    \"zipball_url\": \"https://api.github.com/repos/octocat/Hello-World/zipball/v1.0.0\",\n    \"id\": 1,\n    \"node_id\": \"MDc6UmVsZWFzZTE=\",\n    \"tag_name\": \"v2.0.0\",\n    \"target_commitish\": \"main\",\n    \"name\": \"2.0.0\",\n    \"body\": \"Description of the release\",\n    \"draft\": false,\n    \"prerelease\": false,\n    \"created_at\": \"2013-02-27T19:35:32Z\",\n    \"published_at\": \"2013-02-27T19:35:32Z\",\n    \"author\": {\n      \"login\": \"octocat\",\n      \"id\": 1,\n      \"node_id\": \"MDQ6VXNlcjE=\",\n      \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n      \"gravatar_id\": \"\",\n      \"url\": \"https://api.github.com/users/octocat\",\n      \"html_url\": \"https://github.com/octocat\",\n      \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n      \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n      \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n      \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n      \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n      \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n      \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n      \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n      \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n      \"type\": \"User\",\n      \"site_admin\": false\n    },\n    \"assets\": [\n      {\n        \"url\": \"https://api.github.com/repos/octocat/Hello-World/releases/assets/1\",\n        \"browser_download_url\": \"https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip\",\n        \"id\": 1,\n        \"node_id\": \"MDEyOlJlbGVhc2VBc3NldDE=\",\n        \"name\": \"example.zip\",\n        \"label\": \"short description\",\n        \"state\": \"uploaded\",\n        \"content_type\": \"application/zip\",\n        \"size\": 1024,\n        \"download_count\": 42,\n        \"created_at\": \"2013-02-27T19:35:32Z\",\n        \"updated_at\": \"2013-02-27T19:35:32Z\",\n        \"uploader\": {\n          \"login\": \"octocat\",\n          \"id\": 1,\n          \"node_id\": \"MDQ6VXNlcjE=\",\n          \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n          \"gravatar_id\": \"\",\n          \"url\": \"https://api.github.com/users/octocat\",\n          \"html_url\": \"https://github.com/octocat\",\n          \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n          \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n          \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n          \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n          \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n          \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n          \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n          \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n          \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n          \"type\": \"User\",\n          \"site_admin\": false\n        }\n      }\n    ]\n  },\n  {\n    \"url\": \"https://api.github.com/repos/octocat/Hello-World/releases/1\",\n    \"html_url\": \"https://github.com/octocat/Hello-World/releases/v1.0.0\",\n    \"assets_url\": \"https://api.github.com/repos/octocat/Hello-World/releases/1/assets\",\n    \"upload_url\": \"https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}\",\n    \"tarball_url\": \"https://api.github.com/repos/octocat/Hello-World/tarball/v1.0.0\",\n    \"zipball_url\": \"https://api.github.com/repos/octocat/Hello-World/zipball/v1.0.0\",\n    \"id\": 1,\n    \"node_id\": \"MDc6UmVsZWFzZTE=\",\n    \"tag_name\": \"1.0.0\",\n    \"target_commitish\": \"main\",\n    \"name\": \"1.0.0\",\n    \"body\": \"Description of the release\",\n    \"draft\": false,\n    \"prerelease\": false,\n    \"created_at\": \"2013-02-27T19:35:32Z\",\n    \"published_at\": \"2013-02-27T19:35:32Z\",\n    \"author\": {\n      \"login\": \"octocat\",\n      \"id\": 1,\n      \"node_id\": \"MDQ6VXNlcjE=\",\n      \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n      \"gravatar_id\": \"\",\n      \"url\": \"https://api.github.com/users/octocat\",\n      \"html_url\": \"https://github.com/octocat\",\n      \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n      \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n      \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n      \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n      \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n      \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n      \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n      \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n      \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n      \"type\": \"User\",\n      \"site_admin\": false\n    },\n    \"assets\": [\n      {\n        \"url\": \"https://api.github.com/repos/octocat/Hello-World/releases/assets/1\",\n        \"browser_download_url\": \"https://github.com/octocat/Hello-World/releases/download/v1.0.0/example.zip\",\n        \"id\": 1,\n        \"node_id\": \"MDEyOlJlbGVhc2VBc3NldDE=\",\n        \"name\": \"example.zip\",\n        \"label\": \"short description\",\n        \"state\": \"uploaded\",\n        \"content_type\": \"application/zip\",\n        \"size\": 1024,\n        \"download_count\": 42,\n        \"created_at\": \"2013-02-27T19:35:32Z\",\n        \"updated_at\": \"2013-02-27T19:35:32Z\",\n        \"uploader\": {\n          \"login\": \"octocat\",\n          \"id\": 1,\n          \"node_id\": \"MDQ6VXNlcjE=\",\n          \"avatar_url\": \"https://github.com/images/error/octocat_happy.gif\",\n          \"gravatar_id\": \"\",\n          \"url\": \"https://api.github.com/users/octocat\",\n          \"html_url\": \"https://github.com/octocat\",\n          \"followers_url\": \"https://api.github.com/users/octocat/followers\",\n          \"following_url\": \"https://api.github.com/users/octocat/following{/other_user}\",\n          \"gists_url\": \"https://api.github.com/users/octocat/gists{/gist_id}\",\n          \"starred_url\": \"https://api.github.com/users/octocat/starred{/owner}{/repo}\",\n          \"subscriptions_url\": \"https://api.github.com/users/octocat/subscriptions\",\n          \"organizations_url\": \"https://api.github.com/users/octocat/orgs\",\n          \"repos_url\": \"https://api.github.com/users/octocat/repos\",\n          \"events_url\": \"https://api.github.com/users/octocat/events{/privacy}\",\n          \"received_events_url\": \"https://api.github.com/users/octocat/received_events\",\n          \"type\": \"User\",\n          \"site_admin\": false\n        }\n      }\n    ]\n  }\n]\n"
  },
  {
    "path": "Fixtures/Collections/JSON/good.json",
    "content": "{\n  \"name\": \"Sample Package Collection\",\n  \"overview\": \"This is a sample package collection listing made-up packages.\",\n  \"keywords\": [\"sample package collection\"],\n  \"formatVersion\": \"1.0\",\n  \"revision\": 3,\n  \"generatedAt\": \"2020-10-22T06:03:52Z\",\n  \"generatedBy\": {\n    \"name\": \"Jane Doe\"\n  },\n  \"packages\": [\n    {\n      \"url\": \"https://www.example.com/repos/RepoOne.git\",\n      \"identity\": \"repos.one\",\n      \"summary\": \"Package One\",\n      \"keywords\": [\"sample package\"],\n      \"readmeURL\": \"https://www.example.com/repos/RepoOne/README\",\n      \"license\": {\n        \"name\": \"Apache-2.0\",\n        \"url\": \"https://www.example.com/repos/RepoOne/LICENSE\"\n      },\n      \"versions\": [\n        {\n          \"version\": \"0.1.0\",\n          \"summary\": \"Fixed a few bugs\",\n          \"manifests\": {\n            \"5.1\": {\n              \"toolsVersion\": \"5.1\",\n              \"packageName\": \"PackageOne\",\n              \"targets\": [\n                {\n                  \"name\": \"Foo\",\n                  \"moduleName\": \"Foo\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Foo\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Foo\"]\n                }\n              ],\n              \"minimumPlatformVersions\": [\n                { \"name\": \"macOS\", \"version\": \"10.15\" }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.1\",\n          \"verifiedCompatibility\": [\n            {\n              \"platform\": { \"name\": \"macOS\" },\n              \"swiftVersion\": \"5.1\"\n            },\n            {\n              \"platform\": { \"name\": \"iOS\" },\n              \"swiftVersion\": \"5.1\"\n            },\n            {\n              \"platform\": { \"name\": \"Linux\" },\n              \"swiftVersion\": \"5.1\"\n            }\n          ],\n          \"license\": {\n            \"name\": \"Apache-2.0\",\n            \"url\": \"https://www.example.com/repos/RepoOne/LICENSE\"\n          },\n          \"author\": {\n            \"name\": \"J. Appleseed\"\n          },\n          \"signer\": {\n            \"type\": \"ADP\",\n            \"commonName\": \"J. Appleseed\",\n            \"organizationalUnitName\": \"A1\",\n            \"organizationName\": \"Appleseed Inc.\"\n          },\n          \"createdAt\": \"2020-10-21T09:25:36Z\"\n        }\n      ]\n    },\n    {\n      \"url\": \"https://www.example.com/repos/RepoTwo.git\",\n      \"summary\": \"Package Two\",\n      \"readmeURL\": \"https://www.example.com/repos/RepoTwo/README\",\n      \"versions\": [\n        {\n          \"version\": \"2.1.0\",\n          \"manifests\": {\n            \"5.2\": {\n              \"toolsVersion\": \"5.2\",\n              \"packageName\": \"PackageTwo\",\n              \"targets\": [\n                {\n                  \"name\": \"Bar\",\n                  \"moduleName\": \"Bar\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Bar\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Bar\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.2\"\n        },\n        {\n          \"version\": \"v1.8.3\",\n          \"manifests\": {\n            \"5.0\": {\n              \"toolsVersion\": \"5.0\",\n              \"packageName\": \"PackageTwo\",\n              \"targets\": [\n                {\n                  \"name\": \"Bar\",\n                  \"moduleName\": \"Bar\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Bar\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Bar\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.0\"\n        }\n      ]\n    }\n  ]\n}\n"
  },
  {
    "path": "Fixtures/Collections/JSON/good_signed.json",
    "content": "{\n  \"name\": \"Sample Package Collection\",\n  \"overview\": \"This is a sample package collection listing made-up packages.\",\n  \"keywords\": [\"sample package collection\"],\n  \"formatVersion\": \"1.0\",\n  \"revision\": 3,\n  \"generatedAt\": \"2020-10-22T06:03:52Z\",\n  \"generatedBy\": {\n    \"name\": \"Jane Doe\"\n  },\n  \"packages\": [\n    {\n      \"url\": \"https://www.example.com/repos/RepoOne.git\",\n      \"identity\": \"repos.one\",\n      \"summary\": \"Package One\",\n      \"keywords\": [\"sample package\"],\n      \"readmeURL\": \"https://www.example.com/repos/RepoOne/README\",\n      \"license\": {\n        \"name\": \"Apache-2.0\",\n        \"url\": \"https://www.example.com/repos/RepoOne/LICENSE\"\n      },\n      \"versions\": [\n        {\n          \"version\": \"0.1.0\",\n          \"summary\": \"Fixed a few bugs\",\n          \"manifests\": {\n            \"5.1\": {\n              \"toolsVersion\": \"5.1\",\n              \"packageName\": \"PackageOne\",\n              \"targets\": [\n                {\n                  \"name\": \"Foo\",\n                  \"moduleName\": \"Foo\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Foo\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Foo\"]\n                }\n              ],\n              \"minimumPlatformVersions\": [\n                { \"name\": \"macOS\", \"version\": \"10.15\" }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.1\",\n          \"verifiedCompatibility\": [\n            {\n              \"platform\": { \"name\": \"macOS\" },\n              \"swiftVersion\": \"5.1\"\n            },\n            {\n              \"platform\": { \"name\": \"iOS\" },\n              \"swiftVersion\": \"5.1\"\n            },\n            {\n              \"platform\": { \"name\": \"Linux\" },\n              \"swiftVersion\": \"5.1\"\n            }\n          ],\n          \"license\": {\n            \"name\": \"Apache-2.0\",\n            \"url\": \"https://www.example.com/repos/RepoOne/LICENSE\"\n          },\n          \"author\": {\n            \"name\": \"J. Appleseed\"\n          },\n          \"signer\": {\n            \"type\": \"ADP\",\n            \"commonName\": \"J. Appleseed\",\n            \"organizationalUnitName\": \"A1\",\n            \"organizationName\": \"Appleseed Inc.\"\n          },\n          \"createdAt\": \"2020-10-21T09:25:36Z\"\n        }\n      ]\n    },\n    {\n      \"url\": \"https://www.example.com/repos/RepoTwo.git\",\n      \"summary\": \"Package Two\",\n      \"readmeURL\": \"https://www.example.com/repos/RepoTwo/README\",\n      \"versions\": [\n        {\n          \"version\": \"2.1.0\",\n          \"manifests\": {\n            \"5.2\": {\n              \"toolsVersion\": \"5.2\",\n              \"packageName\": \"PackageTwo\",\n              \"targets\": [\n                {\n                  \"name\": \"Bar\",\n                  \"moduleName\": \"Bar\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Bar\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Bar\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.2\"\n        },\n        {\n          \"version\": \"v1.8.3\",\n          \"manifests\": {\n            \"5.0\": {\n              \"toolsVersion\": \"5.0\",\n              \"packageName\": \"PackageTwo\",\n              \"targets\": [\n                {\n                  \"name\": \"Bar\",\n                  \"moduleName\": \"Bar\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Bar\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Bar\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.0\"\n        }\n      ]\n    }\n  ],\n  \"signature\": {\n    \"signature\": \"<SIGNATURE>\",\n    \"certificate\": {\n      \"subject\": {\n        \"commonName\": \"Sample Subject\"\n      },\n      \"issuer\": {\n        \"commonName\": \"Sample Issuer\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "Fixtures/Collections/Signing/Test_ec_key.pem",
    "content": "-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIFyZDwhGj2Q6ZchEt6DIQSptRk9yKPo60JH5x4u3p4YmoAoGCCqGSM49\nAwEHoUQDQgAEHg58TCXScU6zXSYygCNW0tBZeYFRWf3XAjaDJUkeEFUvKxiIcP8S\nsLfb8P9mukwJsj2CwfatwneFIUQGJ4P+SQ==\n-----END EC PRIVATE KEY-----\n"
  },
  {
    "path": "Fixtures/Collections/Signing/Test_rsa_key.pem",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAk1a/7/deGbDnbe9K8/LzN7fkx4D0kzCHIBlCuSylKOJKiPQ5\nMHH13IXAKJYbudkufYdbACTo/4xjgvWLWI/C/ycbNfEGTPd0r6ahS9LRljgGaCVr\neK4Jqg4VHIuC5B2fTQ5Tuv4k16JhKXuD/hCZ1my96Xwt2HPniRu9cIJFxlAz/1Fj\nbotlL6EbUzzZ7msNLdXEm7QWUIuCN48z1FKk/uapAewzjq1r3X4+pWmEJSi+2tyS\n5K03bmH+SE63fBui6o4dzeCrOblGQxqyqnR0mHOKe5rHU8Y5LVmkam/wyiRGTrmT\nOywsDhRtTyI0EZEp194C7QdLxiksGnl0wt/ArQIDAQABAoIBAG/1AD4QwrFU6lZv\n+Y1rNANHuhEa3T2nJ1Ztu3TIBuwNH8P3iClWvxMFkyGEBqdu71O1caGnamEcxVTy\nziLKgsqtZZDUiAweEM2UGYZrOJUkF0I2BPcbj/5nWwVowVojZDQCSf+SNF6iZaBG\n2eJJrQvxb1Gm6ZNLZ0mZCZcfdnOcwOwubGYGjoJV7qXRhs4kCfZMmA7g8MkQ0FBu\n3fLmD2MMjWqJA2kgnYVf27BfoZrEJBfWSAQ5SKOeSnH7UqTF+L/HTrXJJnpjIY5i\nXr/+lJ7BiOHHouP8dwbggjCmkrcGwcwE7PULyhycty5DOnSpGT2ktElyeqivxPVl\nNqm3U+ECgYEAw8bsQrYrZoSGsmUBFQ29z+S402TJyTOF14PinkfEyF2Gmel0024A\n1pY7eTrmlHJMBooy4IgdkLjKnaFMd98H+jcOpfX7dXXE+cCLAs9CA3HCeP5hsOl/\nPduswEahqne58v/FcGDdc66Jf6bCb3sOcIku4vxKiInbbtv8hjvpCcUCgYEAwKlp\nKQZ072QP4cNil+ITZjlf5xhihHUudL6BLfiR3BxQhtDqk/23rbEB69yl5JkSoYA8\n4T86Gdhnfe6lKHmWbgBN54tcoaesH8yKfTFvZZfbhENfV0gxXXpxdvjM1/1peRVK\n0CJsDAEvyREKhD4nuWv50vqMBK+HjD9gYANNEckCgYBbCMKPernPn8wqY8EPEyax\n5r7yvSj/P8/6mL7lrqWYLbULGH1UWxBUt+LLylGxsTwcxmJF+cUVqHe+uGQgUTsa\nZEORdEILKkn/gEKjedBOXbV6IX83jju2fdFkTvOZmraCgeBDEyemRQB2tQowYF4k\nggWlUn8t4jyA3hYcLPt9qQKBgQCDIsyxX/O3/iPRR2yUdQ0/R04/vhlQj3JPhFvp\nLogZiixFl24TzV54m0Lzh/xi3M4Rn3fQ2XhynxnSXd2M7zW1Kf/c2r7ySW6fNloN\nXNi2Decc377Fah4vwmf40uCbI6HnCNcjVEq24Rflg/Pkj2n6i8RAFsm3ZsKcc4bl\n01liAQKBgBTPtA4M3/TpKDwuPedsmzumSe1Rmn4QSAd0ssrQ9XoPHYw2RkBSpCQg\n1HYM/lD21uBr66nAtqpByiNILTQm1LiitBSnC9jOjpoM+ECqMyYPwfU9AD7weYlX\nqjLG9mzvjAEa7bzjweN77Mox4LDf6rEiAcs9ObceElEwN8W1g+63\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "Fixtures/Coverage/Simple/Package.swift",
    "content": "// swift-tools-version: 6.2\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    products: [\n        // Products define the executables and libraries a package produces, making them visible to other packages.\n        .library(\n            name: \"Simple\",\n            targets: [\"Simple\"]\n        ),\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package, defining a module or a test suite.\n        // Targets can depend on other targets in this package and products from dependencies.\n        .target(\n            name: \"Simple\"\n        ),\n        .testTarget(\n            name: \"SimpleTests\",\n            dependencies: [\"Simple\"]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Coverage/Simple/Sources/Simple/Simple.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n\npublic func greet(name: String = \"world\") -> String {\n    return \"Hello, \\(name)!\"\n}\n\npublic func libA() -> String {\n    return \"libA\"\n}\n"
  },
  {
    "path": "Fixtures/Coverage/Simple/Tests/SimpleTests/SimpleTests.swift",
    "content": "import Testing\nimport XCTest\n@testable import Simple\n\n@Test(\n    arguments: [\n        \"Bob\",\n        \"Alice\",\n        \"\",\n    ]\n)\n func testGreet(\n    name: String\n ) async throws {\n    let actual = greet(name: name)\n\n    #expect(actual == \"Hello, \\(name)!\")\n}\n\nfinal class SimpleTests: XCTestCase {\n    func testExample() throws {\n        XCTAssertEqual(libA(), \"libA\", \"Actual is not as expected\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Branch/Bar/Package.swift",
    "content": "// swift-tools-version:5.5\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    products: [\n        // Products define the executables and libraries a package produces, and make them visible to other packages.\n        .library(\n            name: \"Bar\",\n            targets: [\"Bar\"]),\n    ],\n    dependencies: [\n        // Dependencies declare other packages that this package depends on.\n        // .package(url: /* package url */, from: \"1.0.0\"),\n\t.package(url: \"../Foo\", branch: \"main\")\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n        // Targets can depend on other targets in this package, and on products in packages this package depends on.\n        .target(\n            name: \"Bar\",\n            dependencies: [\"Foo\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Branch/Bar/Sources/Bar/Bar.swift",
    "content": "import Foo\n\nstruct Bar {\n    var text = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Branch/Foo/Package.swift",
    "content": "// swift-tools-version:5.5\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        // Products define the executables and libraries a package produces, and make them visible to other packages.\n        .library(\n            name: \"Foo\",\n            targets: [\"Foo\"]),\n    ],\n    dependencies: [\n        // Dependencies declare other packages that this package depends on.\n        // .package(url: /* package url */, from: \"1.0.0\"),\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n        // Targets can depend on other targets in this package, and on products in packages this package depends on.\n        .target(\n            name: \"Foo\",\n            dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Branch/Foo/Sources/Foo/Foo.swift",
    "content": "struct Foo {\n    var text = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/CUsingCDep/Bar/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    dependencies: [\n        .package(url: \"../Foo\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"SeaLover\", dependencies: [\"Foo\"]),\n        .target(name: \"SwiftExec\", dependencies: [\"Foo\"]),\n    ]\n)\n\n\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/CUsingCDep/Bar/Sources/SeaLover/Sea.c",
    "content": "#include <Foo/Foo.h>\n\nvoid cool() {\n    foo();\n}"
  },
  {
    "path": "Fixtures/DependencyResolution/External/CUsingCDep/Bar/Sources/SeaLover/include/Sea.h",
    "content": ""
  },
  {
    "path": "Fixtures/DependencyResolution/External/CUsingCDep/Bar/Sources/SwiftExec/main.swift",
    "content": "import Foo\n\nfoo()\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/CUsingCDep/Foo/Foo.c",
    "content": "void foo() {\n    \n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/CUsingCDep/Foo/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/CUsingCDep/Foo/include/Foo/Foo.h",
    "content": "void foo();\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/FisherYates/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"FisherYates\",\n    products: [\n        .library(name: \"FisherYates\", targets: [\"FisherYates\"]),\n    ],\n    targets: [\n        .target(name: \"FisherYates\", path: \"src\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/FisherYates/src/Fisher-Yates_Shuffle.swift",
    "content": "\npublic extension Collection {\n    func shuffle() -> [Iterator.Element] {\n        var array = Array(self)\n        array.shuffleInPlace()\n\n        return array\n    }\n}\n\npublic extension MutableCollection {\n    /// Shuffles the contents of this collection.\n    mutating func shuffleInPlace() {\n        let c = count\n        guard c > 1 else { return }\n        \n        for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {\n            var g = SystemRandomNumberGenerator()\n            let d = Int.random(in: 1...unshuffledCount, using: &g)\n            let i = index(firstUnshuffled, offsetBy: d)\n            swapAt(firstUnshuffled, i)\n        }\n    }\n}\n\n\npublic let shuffle = false\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/PlayingCard/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"PlayingCard\",\n    products: [\n        .library(name: \"PlayingCard\", targets: [\"PlayingCard\"]),\n    ],\n    targets: [\n        .target(name: \"PlayingCard\", path: \"src\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/PlayingCard/src/PlayingCard.swift",
    "content": "public struct PlayingCard: Equatable {\n    let rank: Rank\n    let suit: Suit\n\n    public init(rank: Rank, suit: Suit) {\n        self.rank = rank\n        self.suit = suit\n    }\n}\n\n// MARK: - Comparable\n\nextension PlayingCard: Comparable {}\n\npublic func <(lhs: PlayingCard, rhs: PlayingCard) -> Bool {\n    return lhs.suit < rhs.suit || (lhs.suit == rhs.suit && lhs.rank < rhs.rank)\n}\n\n// MARK: - CustomStringConvertible\n\nextension PlayingCard : CustomStringConvertible {\n    public var description: String {\n        return \"\\(suit)\\(rank)\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/PlayingCard/src/Rank.swift",
    "content": "public enum Rank : Int {\n    case Ace = 1\n    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten\n    case Jack, Queen, King\n}\n\n// MARK: - Comparable\n\nextension Rank : Comparable {}\n\npublic func <(lhs: Rank, rhs: Rank) -> Bool {\n    switch (lhs, rhs) {\n    case (_, _) where lhs == rhs:\n        return false\n    case (.Ace, _):\n        return false\n    default:\n        return lhs.rawValue < rhs.rawValue\n    }\n}\n\n// MARK: - CustomStringConvertible\n\nextension Rank : CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .Ace: return \"A\"\n        case .Jack: return \"J\"\n        case .Queen: return \"Q\"\n        case .King: return \"K\"\n        default:\n            return \"\\(rawValue)\"\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/PlayingCard/src/Suit.swift",
    "content": "public enum Suit: String {\n    case Spades, Hearts, Diamonds, Clubs\n}\n\n// MARK: - Comparable\n\nextension Suit: Comparable {}\n\npublic func <(lhs: Suit, rhs: Suit) -> Bool {\n    switch (lhs, rhs) {\n    case (_, _) where lhs == rhs:\n        return false\n    case (.Spades, _),\n    (.Hearts, .Diamonds), (.Hearts, .Clubs),\n    (.Diamonds, .Clubs):\n        return false\n    default:\n        return true\n    }\n}\n\n// MARK: - CustomStringConvertible\n\nextension Suit : CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .Spades: return \"♠︎\"\n        case .Hearts: return \"♡\"\n        case .Diamonds: return \"♢\"\n        case .Clubs: return \"♣︎\"\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/app/Package.swift",
    "content": "// swift-tools-version:5.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"Dealer\",\n    platforms: [\n        .macOS(.v10_12),\n        .iOS(.v10),\n        .tvOS(.v11),\n        .watchOS(.v5)\n    ],\n    dependencies: [\n        .package(url: \"../deck-of-playing-cards\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(\n            name: \"Dealer\",\n            dependencies: [\"DeckOfPlayingCards\"],\n            path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/app/main.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nimport FisherYates\nimport PlayingCard\nimport DeckOfPlayingCards\n\nlet numberOfCards = 10\n\nvar deck = Deck.standard52CardDeck()\n\nif FisherYates.shuffle {\n    deck.shuffle()\n}\n\nfor _ in 0..<numberOfCards {\n    guard let card = deck.deal() else {\n        print(\"No More Cards!\")\n        break\n    }\n\n    print(card)\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/deck-of-playing-cards/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"DeckOfPlayingCards\",\n    products: [\n        .library(name: \"DeckOfPlayingCards\", targets: [\"DeckOfPlayingCards\"]),\n    ],\n    dependencies: [\n        .package(url: \"../PlayingCard\", from: \"1.0.0\"),\n        .package(url: \"../FisherYates\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(\n            name: \"DeckOfPlayingCards\",\n            dependencies: [\"PlayingCard\", \"FisherYates\"],\n            path: \"src\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/deck-of-playing-cards/src/Deck.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nimport FisherYates\nimport PlayingCard\n\npublic struct Deck: Equatable {\n    fileprivate var cards: [PlayingCard]\n\n    public static func standard52CardDeck() -> Deck {\n        let suits: [Suit] = [.Spades, .Hearts, .Diamonds, .Clubs]\n        let ranks: [Rank] = [.Ace, .Two, .Three, .Four, .Five, .Six, .Seven, .Eight, .Nine, .Ten, .Jack, .Queen, .King]\n\n        var cards: [PlayingCard] = []\n        for suit in suits {\n            for rank in ranks {\n                cards.append(PlayingCard(rank: rank, suit: suit))\n            }\n        }\n\n        return Deck(cards)\n    }\n\n    public init(_ cards: [PlayingCard]) {\n        self.cards = cards\n    }\n\n    public mutating func shuffle() {\n        cards.shuffleInPlace()\n    }\n\n    public mutating func deal() -> PlayingCard? {\n        guard !cards.isEmpty else { return nil }\n\n        return cards.removeLast()\n    }\n}\n\n// MARK: - ExpressibleByArrayLiteral\n\nextension Deck : ExpressibleByArrayLiteral {\n    public init(arrayLiteral elements: PlayingCard...) {\n        self.init(elements)\n    }\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/deck-of-playing-cards-local/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"DeckOfPlayingCards\",\n    products: [\n        .library(name: \"DeckOfPlayingCards\", targets: [\"DeckOfPlayingCards\"]),\n    ],\n    dependencies: [\n        .package(path: \"../PlayingCard\"),\n        .package(path: \"../FisherYates\")\n    ],\n    targets: [\n        .target(\n            name: \"DeckOfPlayingCards\",\n            dependencies: [\"PlayingCard\", \"FisherYates\"],\n            path: \"src\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Complex/deck-of-playing-cards-local/src/Deck.swift",
    "content": ""
  },
  {
    "path": "Fixtures/DependencyResolution/External/Mirror/App/Package.swift",
    "content": "// swift-tools-version:5.3\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"App\",\n    dependencies: [\n        .package(url: \"../Foo\", .branch(\"main\")),\n        .package(url: \"../Bar\", .branch(\"main\")),\n    ],\n    targets: [\n        .target(name: \"App\", dependencies: [\n            .product(name: \"Foo\", package: \"Foo\"),\n            .product(name: \"Bar\", package: \"Bar\"),\n        ], path: \"./\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Mirror/App/main.swift",
    "content": "import Foo\nimport Bar\n\npublic func main() {\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Mirror/Bar/Bar.swift",
    "content": "public func hello() {\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Mirror/Bar/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    products: [\n        .library(name: \"Bar\", targets: [\"Bar\"]),\n    ],\n    targets: [\n        .target(name: \"Bar\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Mirror/BarMirror/Bar.swift",
    "content": "public func hello() {\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Mirror/BarMirror/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    products: [\n        .library(name: \"Bar\", targets: [\"Bar\"]),\n    ],\n    targets: [\n        .target(name: \"Bar\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Mirror/Foo/Foo.swift",
    "content": "public func hello() {\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Mirror/Foo/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/PackageLookupCaseInsensitive/dep/Package.swift",
    "content": "// swift-tools-version:5.0\n\nimport PackageDescription\n\nlet package = Package(\n  name: \"Dep\",\n  products: [\n    .library(name: \"Dep\", targets: [\"Dep\"]),\n  ],\n  targets: [\n    .target(name: \"Dep\", dependencies: []),\n  ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/PackageLookupCaseInsensitive/dep/Sources/Dep/dep.swift",
    "content": "public struct dep {\n    public private(set) var text = \"Hello, World!\"\n\n    public init() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/PackageLookupCaseInsensitive/pkg/Package.swift",
    "content": "// swift-tools-version:5.4\n\nimport PackageDescription\n\nlet package = Package(\n  name: \"pkg\",\n  products: [\n    .library(name: \"pkg\", targets: [\"pkg\"]),\n  ],\n  dependencies: [\n    .package(path: \"../dep\"),\n  ],\n  targets: [\n    .target(\n      name: \"pkg\",\n      dependencies: [.product(name: \"Dep\", package: \"Dep\")]),\n  ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/PackageLookupCaseInsensitive/pkg/Sources/pkg/pkg.swift",
    "content": "public struct pkg {\n    public private(set) var text = \"Hello, World!\"\n\n    public init() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Simple/Bar/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    dependencies: [\n        .package(url: \"../Foo\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"Bar\", dependencies: [\"Foo\"], path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Simple/Bar/main.swift",
    "content": "import Foo\n\nfoo()\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Simple/Foo/Foo.swift",
    "content": "public func foo() {\n\t{}()\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/Simple/Foo/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/XCFramework/Bar.xcframework/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n    <key>AvailableLibraries</key>\n    <array>\n        <dict>\n            <key>LibraryIdentifier</key>\n            <string>macos-x86_64</string>\n            <key>LibraryPath</key>\n            <string>Framework.framework</string>\n            <key>SupportedArchitectures</key>\n            <array>\n                <string>x86_64</string>\n            </array>\n            <key>SupportedPlatform</key>\n            <string>macos</string>\n        </dict>\n    </array>\n    <key>CFBundlePackageType</key>\n    <string>XFWK</string>\n    <key>XCFrameworkFormatVersion</key>\n    <string>1.0</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/XCFramework/Foo/Foo.swift",
    "content": "public func foo() {\n\t{}()\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/External/XCFramework/Package.swift",
    "content": "// swift-tools-version:5.3\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\", \"Bar\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./Foo\"),\n        .binaryTarget(name: \"Bar\", path: \"./Bar.xcframework\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Complex/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    targets: [\n        .target(name: \"Bar\", dependencies: [\"Baz\", \"Cat\"]),\n        .target(name: \"Baz\", dependencies: []),\n        .target(name: \"Cat\", dependencies: [\"Sound\"]),\n        .target(name: \"Foo\", dependencies: [\"Bar\"]),\n        .target(name: \"Sound\", dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Complex/Sources/Bar/Bar.swift",
    "content": "import Baz\nimport Cat\n\npublic class Bar {\n    public init()\n    {}\n\n    public let baz = Baz()\n    public let cat = Cat()\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Complex/Sources/Baz/Baz.swift",
    "content": "public class Baz {\n    public let value = \"Baz\"\n    public init()\n    {}\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Complex/Sources/Cat/Cat.swift",
    "content": "import Sound\n\npublic class Cat {\n    public let sound = Sound()\n    public init()\n    {}\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Complex/Sources/Foo/Foo.swift",
    "content": "import Bar\n\nfunc foo() -> String {\n    let bar = Bar()\n    return bar.cat.sound.description + \" \" + bar.baz.value\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Complex/Sources/Foo/main.swift",
    "content": "print(foo())\n\n// TODO copy this fixture and make one that should not compile due to the dependency not being specified\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Complex/Sources/Sound/Sound.swift",
    "content": "public class Sound: CustomStringConvertible {\n    public init()\n    {}\n\n    public var description: String {\n        return \"meiow\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/InternalExecutableAsDependency/Bar/Bar.swift",
    "content": "public struct Bar {\n    public init() {}\n    public let value = \"Bar\"\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/InternalExecutableAsDependency/Bar/main.swift",
    "content": ""
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/InternalExecutableAsDependency/Foo/Foo.swift",
    "content": "class Foo {\n    let value = \"Foo\"\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/InternalExecutableAsDependency/Foo/main.swift",
    "content": "import Bar\n\nprint(Foo().value)\nprint(Bar().value)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/InternalExecutableAsDependency/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    targets: [\n        .target(name: \"Foo\", dependencies: [\"Bar\"], path: \"Foo\"),\n        .target(name: \"Bar\", path: \"Bar\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Simple/Bar/Bar.swift",
    "content": "public struct Bar {\n    public init() {}\n    public let value = \"Bar\"\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Simple/Foo/Foo.swift",
    "content": "class Foo {\n    let value = \"Foo\"\n}\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Simple/Foo/main.swift",
    "content": "import Bar\n\nprint(Foo().value)\nprint(Bar().value)\n"
  },
  {
    "path": "Fixtures/DependencyResolution/Internal/Simple/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    targets: [\n        .target(name: \"Foo\", dependencies: [\"Bar\"], path: \"Foo\"),\n        .target(name: \"Bar\", path: \"Bar\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Macros/MacroPackage/Package.swift",
    "content": "// swift-tools-version: 999.0\nimport PackageDescription\nimport CompilerPluginSupport\n\nlet settings: [SwiftSetting] = [\n    .enableExperimentalFeature(\"Macros\"),\n    .unsafeFlags([\"-Xfrontend\", \"-dump-macro-expansions\"])\n]\n\nlet package = Package(\n\tname: \"MacroPackage\",\n\tplatforms: [\n\t\t.macOS(.v10_15),\n\t],\n\ttargets: [\n\t\t.macro(name: \"MacroImpl\"),\n\t\t.target(name: \"MacroDef\", dependencies: [\"MacroImpl\"], swiftSettings: settings),\n\t\t.executableTarget(name: \"MacroClient\", dependencies: [\"MacroDef\"], swiftSettings: settings),\n\t]\n)\n"
  },
  {
    "path": "Fixtures/Macros/MacroPackage/Sources/MacroClient/client.swift",
    "content": "import MacroDef\n\nstruct Font: ExpressibleByFontLiteral {\n  init(fontLiteralName: String, size: Int, weight: MacroDef.FontWeight) {\n  }\n}\n\nlet _: Font = #fontLiteral(name: \"Comic Sans\", size: 14, weight: .thin)\n"
  },
  {
    "path": "Fixtures/Macros/MacroPackage/Sources/MacroDef/definition.swift",
    "content": "\npublic enum FontWeight {\n  case thin\n  case normal\n  case medium\n  case semiBold\n  case bold\n}\n\npublic protocol ExpressibleByFontLiteral {\n  init(fontLiteralName: String, size: Int, weight: FontWeight)\n}\n\n/// Font literal similar to, e.g., #colorLiteral.\n@freestanding(expression) public macro fontLiteral<T>(name: String, size: Int, weight: FontWeight) -> T = #externalMacro(module: \"MacroImpl\", type: \"FontLiteralMacro\")\n  where T: ExpressibleByFontLiteral"
  },
  {
    "path": "Fixtures/Macros/MacroPackage/Sources/MacroImpl/macro.swift",
    "content": "import SwiftSyntax\nimport SwiftSyntaxBuilder\nimport SwiftSyntaxMacros\n\n/// Implementation of the `#fontLiteral` macro, which is similar in spirit\n/// to the built-in expressions `#colorLiteral`, `#imageLiteral`, etc., but in\n/// a small macro.\npublic struct FontLiteralMacro: ExpressionMacro {\n  public static func expansion(\n    of macro: some FreestandingMacroExpansionSyntax,\n    in context: some MacroExpansionContext\n  ) -> ExprSyntax {\n    let argList = replaceFirstLabel(\n      of: macro.argumentList,\n      with: \"fontLiteralName\"\n    )\n    let initSyntax: ExprSyntax = \".init(\\(argList))\"\n    if let leadingTrivia = macro.leadingTrivia {\n      return initSyntax.with(\\.leadingTrivia, leadingTrivia)\n    }\n    return initSyntax\n  }\n}\n\n/// Replace the label of the first element in the tuple with the given\n/// new label.\nprivate func replaceFirstLabel(\n  of tuple: TupleExprElementListSyntax,\n  with newLabel: String\n) -> TupleExprElementListSyntax {\n  guard let firstElement = tuple.first else {\n    return tuple\n  }\n\n  return tuple.replacing(\n    childAt: 0,\n    with: firstElement.with(\\.label, .identifier(newLabel))\n  )\n}\n"
  },
  {
    "path": "Fixtures/Macros/MinimalMacroPackage/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\nimport CompilerPluginSupport\n\nlet package = Package(\n    name: \"MinimalMacroPackage\",\n    platforms: [\n        .macOS(.v13),\n    ],\n    targets: [\n        .macro(name: \"MacroImpl\"),\n        .target(name: \"MacroDef\", dependencies: [\"MacroImpl\"]),\n        .executableTarget(name: \"MacroClient\", dependencies: [\"MacroDef\"]),\n    ],\n    swiftLanguageModes: [.v5]\n)\n"
  },
  {
    "path": "Fixtures/Macros/MinimalMacroPackage/Sources/MacroClient/main.swift",
    "content": "import MacroDef\n\nlet result = #stringify(42)\nprint(\"Macro result: \\(result)\")\n"
  },
  {
    "path": "Fixtures/Macros/MinimalMacroPackage/Sources/MacroDef/MacroDef.swift",
    "content": "@freestanding(expression)\npublic macro stringify<T>(_ value: T) -> String = #externalMacro(module: \"MacroImpl\", type: \"StringifyMacro\")\n"
  },
  {
    "path": "Fixtures/Macros/MinimalMacroPackage/Sources/MacroImpl/StringifyMacro.swift",
    "content": "import Foundation\n\n@main\nstruct MacroPlugin {\n    static func main() throws {\n        while true {\n            guard let headerData = try read(count: 8),\n                  headerData.count == 8 else {\n                break\n            }\n            let length = headerData.withUnsafeBytes { buffer in\n                buffer.load(as: UInt64.self)\n            }\n            let payloadLength = UInt64(littleEndian: length)\n\n            if payloadLength == 0 {\n                break\n            }\n\n            guard let payloadData = try read(count: Int(payloadLength)),\n                  payloadData.count == Int(payloadLength) else {\n                break\n            }\n\n            guard let json = try? JSONSerialization.jsonObject(with: payloadData) as? [String: Any] else {\n                continue\n            }\n\n            if json.keys.contains(\"getCapability\") {\n                let response: [String: Any] = [\n                    \"getCapabilityResult\": [\n                        \"capability\": [\n                            \"protocolVersion\": 2\n                        ]\n                    ]\n                ]\n                if let responseData = try? JSONSerialization.data(withJSONObject: response) {\n                    try writeMessage(responseData, to: FileHandle.standardOutput)\n                }\n            } else if json.keys.contains(\"expandFreestandingMacro\") {\n                let response: [String: Any] = [\n                    \"expandMacroResult\": [\n                        \"expandedSource\": \"\\\"expanded\\\"\",\n                        \"diagnostics\": []\n                    ]\n                ]\n                if let responseData = try? JSONSerialization.data(withJSONObject: response) {\n                    try writeMessage(responseData, to: FileHandle.standardOutput)\n                }\n            }\n        }\n    }\n}\n\nprivate func read(count: Int) throws -> Data? {\n    var accumulated = Data()\n    while accumulated.count < count {\n        let remaining = count - accumulated.count\n        guard let chunk = try FileHandle.standardInput.read(upToCount: remaining), !chunk.isEmpty else {\n            return accumulated.isEmpty ? nil : accumulated\n        }\n        accumulated.append(chunk)\n    }\n    return accumulated\n}\n\nprivate func writeMessage(_ data: Data, to handle: FileHandle) throws {\n    var length = UInt64(data.count).littleEndian\n    let headerData = withUnsafeBytes(of: &length) { buffer in\n        Data(buffer)\n    }\n    try handle.write(contentsOf: headerData)\n    try handle.write(contentsOf: data)\n}\n"
  },
  {
    "path": "Fixtures/Metal/SimpleLibrary/Package.swift",
    "content": "// swift-tools-version: 6.2\n// The swift-tools-version declares the minimum version of Swift required to build this package.\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyRenderer\",\n    products: [\n        .library(\n            name: \"MyRenderer\",\n            targets: [\"MyRenderer\"]),\n    ],\n    targets: [\n        .target(\n            name: \"MyRenderer\",\n            dependencies: [\"MySharedTypes\"]),\n\n        .target(name: \"MySharedTypes\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Metal/SimpleLibrary/Sources/MyRenderer/Renderer.swift",
    "content": "import MySharedTypes\n\n\nlet vertex = AAPLVertex(position: .init(250, -250), color: .init(1, 0, 0, 1))\n"
  },
  {
    "path": "Fixtures/Metal/SimpleLibrary/Sources/MyRenderer/Shaders.metal",
    "content": "// A relative path to SharedTypes.h.\n#import \"../MySharedTypes/include/SharedTypes.h\"\n\n#include <metal_stdlib>\nusing namespace metal;\n\nvertex float4 simpleVertexShader(const device AAPLVertex *vertices [[buffer(0)]],\n                                  uint vertexID [[vertex_id]]) {\n    AAPLVertex in = vertices[vertexID];\n    return float4(in.position.x, in.position.y, 0.0, 1.0);\n}\n\n"
  },
  {
    "path": "Fixtures/Metal/SimpleLibrary/Sources/MySharedTypes/include/SharedTypes.h",
    "content": "#ifndef SharedTypes_h\n#define SharedTypes_h\n\n\n#import <simd/simd.h>\n\n\ntypedef struct {\n    vector_float2 position;\n    vector_float4 color;\n} AAPLVertex;\n\n\n#endif /* SharedTypes_h */\n"
  },
  {
    "path": "Fixtures/Metal/SimpleLibrary/Tests/MyRendererTests/MyRendererTests.swift",
    "content": "import Testing\n@testable import MyRenderer\n\n@Test func example() async throws {\n    // Write your test here and use APIs like `#expect(...)` to check expected conditions.\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/-DSWIFT_PACKAGE/Package.swift",
    "content": "// swift-tools-version:4.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExtraCommandLineFlags\",\n    targets: [\n        .target(name: \"CLib\"),\n        .target(name: \"SwiftExec\", dependencies: [\"CLib\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/-DSWIFT_PACKAGE/Sources/CLib/foo.c",
    "content": "#include \"CLib.h\"\n\nvoid foo(void) { }\n"
  },
  {
    "path": "Fixtures/Miscellaneous/-DSWIFT_PACKAGE/Sources/CLib/include/CLib.h",
    "content": "// This is to check a -Xcc arg.\n#if !defined(EXTRA_C_DEFINE) || EXTRA_C_DEFINE != 2\n#error \"unexpected compiler flags\"\n#endif\n\nvoid foo(void);\n"
  },
  {
    "path": "Fixtures/Miscellaneous/-DSWIFT_PACKAGE/Sources/SwiftExec/main.swift",
    "content": "import CLib\n\n// This is expected to be set with -Xswiftc.\n#if !EXTRA_SWIFTC_DEFINE\ndoesNotCompile()\n#endif\n\nfoo()\n\nclass Bar {\n    var bar: Int = 0 \n    #if SWIFT_PACKAGE\n    #else\n    var bar: String = \"\"\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/Bar/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    products: [\n        .library(name: \"Baz\", targets: [\"Baz\"]),\n        .library(name: \"Qux\", targets: [\"Qux\"]),\n    ],\n    targets: [\n        .target(name: \"Baz\"),\n        .target(name: \"Qux\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/Bar/Sources/Baz/Baz.swift",
    "content": "public func bar() -> Int {\n    42\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/Bar/Sources/Qux/Qux.swift",
    "content": "public class Qux<T> { public let x = 1 }\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/BrokenPkg/Package.swift",
    "content": "// swift-tools-version: 5.7\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"BrokenPkg\",\n    products: [\n        .library(name: \"BrokenPkg\", targets: [\"BrokenPkg\", \"Swift2\"]),\n    ],\n    targets: [\n        .target(name: \"BrokenPkg\", publicHeadersPath: \"bestHeaders\", cSettings: [ .define(\"FLAG\"), ]),\n        .target(name: \"Swift2\", dependencies: [\"BrokenPkg\"], cSettings: [ .define(\"FLAG\"), ]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/BrokenPkg/Sources/BrokenPkg/bestHeaders/header.h",
    "content": "#ifndef FLAG\n#error \"fail\"\n#endif\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/BrokenPkg/Sources/BrokenPkg/code.m",
    "content": "#import \"header.h\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/BrokenPkg/Sources/Swift2/file.swift",
    "content": "import BrokenPkg\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CIncludePath/Package.swift",
    "content": "// swift-tools-version: 6.0\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Sample\",\n    products: [\n        .library(\n            name: \"Sample\",\n            targets: [\"Sample\"]\n        ),\n    ],\n    targets: [\n        .target(\n            name: \"CSample\",\n            sources: [\"./vendorsrc/src\"],\n            cSettings: [\n                .headerSearchPath(\"./vendorsrc/include\"),\n            ]\n        ),\n        .target(\n            name: \"Sample\",\n            dependencies: [\"CSample\"]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CIncludePath/Sources/CSample/include/CSample.h",
    "content": "\n#include \"config.h\"\n#include \"../vendorsrc/include/vendor.h\""
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CIncludePath/Sources/CSample/include/config.h",
    "content": "#define HAVE_VENDOR_CONFIG\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CIncludePath/Sources/CSample/vendorsrc/include/vendor.h",
    "content": "\n#include \"config.h\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CIncludePath/Sources/CSample/vendorsrc/src/vendor.c",
    "content": "#include \"vendor.h\"\n\nint vendor__func(int n)\n{\n  return 0;\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CIncludePath/Sources/Sample/Sample.swift",
    "content": "import CSample\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CTargetDep/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"CLibrarySources\",\n    products: [\n        .library(name: \"Lib\", targets: [\"Bar\"])\n    ],\n    targets: [\n        .target(name: \"Foo\"),\n        .target(name: \"Bar\", dependencies: [\"Foo\"])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CTargetDep/Sources/Bar/Bar.swift",
    "content": "import Foo\n\npublic func bar() -> Int {\n    foo()\n    return 42\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CTargetDep/Sources/Foo/Foo.c",
    "content": "#include \"Foo.h\"\n\nint foo() {\n    int a = 5;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/CTargetDep/Sources/Foo/include/Foo.h",
    "content": "int foo();\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/Foo/Foo.swift",
    "content": "public func foo() {\n\t{}()\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/Foo/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/NonAPILibraryTargets/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"NonAPILibraryTargets\",\n    products: [\n        .library(name: \"One\", targets: [\"Foo\"]),\n        .library(name: \"Two\", targets: [\"Bar\", \"Baz\"]),\n        .executable(name: \"Exec\", targets: [\"Exec\", \"Qux\"])\n    ],\n    targets: [\n        .target(name: \"Foo\"),\n        .target(name: \"Bar\", dependencies: [\"Baz\"]),\n        .target(name: \"Baz\"),\n        .target(name: \"Qux\"),\n        .target(name: \"Exec\", dependencies: [\"Qux\"])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/NonAPILibraryTargets/Sources/Bar/Bar.swift",
    "content": "import Baz\n\npublic func bar() -> Int {\n    42\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/NonAPILibraryTargets/Sources/Baz/Baz.swift",
    "content": "public enum Baz {\n    case a, c\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/NonAPILibraryTargets/Sources/Exec/main.swift",
    "content": "import Qux\n\nprint(\"Hello, world!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/NonAPILibraryTargets/Sources/Foo/Foo.swift",
    "content": "public struct Foo {\n    func doThing() {}\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/NonAPILibraryTargets/Sources/Qux/Qux.swift",
    "content": "public class Qux<T> { public let x = 1 }\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/WithPlugin/Package.swift",
    "content": "// swift-tools-version: 6.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"package-with-plugin\",\n    products: [.library(name: \"PackageLib\", targets: [\"TargetLib\"])],\n    targets: [\n        .target(name: \"TargetLib\"),\n        .executableTarget(name: \"BuildTool\", dependencies: [\"TargetLib\"]),\n        .plugin(\n            name: \"BuildPlugin\",\n            capability: .command(intent: .custom(verb: \"do-it-now\", description: \"\")),\n            dependencies: [\"BuildTool\"]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/WithPlugin/Plugins/BuildPlugin/BuildToolPlugin.swift",
    "content": "import Foundation\nimport PackagePlugin\n\n@main\nfinal class BuildToolPlugin: CommandPlugin {\n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        _ = try context.tool(named: \"BuildTool\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/WithPlugin/Sources/BuildTool/BuildTool.swift",
    "content": "import TargetLib\n\n@main\npublic struct BuildTool {\n    static func main() {\n        TargetLibStruct.do_it()\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/APIDiff/WithPlugin/Sources/TargetLib/TargetLib.swift",
    "content": "public enum TargetLibStruct {\n    public static func do_it() {\n        print(\"Hello!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/AtMainSupport/Package.swift",
    "content": "// swift-tools-version:5.5\nimport PackageDescription\n\nlet package = Package(\n    name: \"AtMainSupport\",\n    products: [\n        .executable(name: \"ClangExecSingleFile\", targets: [\"ClangExecSingleFile\"]),\n        .executable(name: \"SwiftExecSingleFile\", targets: [\"SwiftExecSingleFile\"]),\n        .executable(name: \"SwiftExecMultiFile\", targets: [\"SwiftExecMultiFile\"]),\n    ],\n    targets: [\n        .executableTarget(name: \"ClangExecSingleFile\",\n        linkerSettings: [\n                .linkedLibrary(\"swiftCore\", .when(platforms: [.windows])), // for swift_addNewDSOImage\n            ]),\n        .executableTarget(name: \"SwiftExecSingleFile\"),\n        .executableTarget(name: \"SwiftExecMultiFile\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/AtMainSupport/Sources/ClangExecSingleFile/NotMain.c",
    "content": "#include <stdio.h>\n\nint main() {\n    printf(\"Hello, C.\");\n  }\n"
  },
  {
    "path": "Fixtures/Miscellaneous/AtMainSupport/Sources/SwiftExecMultiFile/NotMain.swift",
    "content": "@main\nstruct MyProgram {\n    static func main() {\n        print(\"Hello, Swift.\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/AtMainSupport/Sources/SwiftExecMultiFile/OtherFile.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/AtMainSupport/Sources/SwiftExecSingleFile/NotMain.swift",
    "content": "@main\nstruct MyProgram {\n    static func main() {\n        print(\"Hello, Swift.\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_7/Package.swift",
    "content": "// swift-tools-version:5.7\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"CXX17WithFModules\",\n    targets: [\n        .target(\n            name: \"lodepng\",\n            path: \"lodepng\",\n            sources: [\"lodepng.cpp\"],\n            publicHeadersPath: \"include\"),\n        .target(name: \"CXX17WithFModules\", dependencies: [\"lodepng\"], path: \"./\", sources: [\"src/user_objects.cc\"], publicHeadersPath: \"include\"),\n    ],\n    cxxLanguageStandard: .cxx17\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_7/include/user_objects.h",
    "content": "// Copyright 2021 DeepMind Technologies Limited\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#ifndef MUJOCO_SRC_USER_USER_OBJECTS_H_\n#define MUJOCO_SRC_USER_USER_OBJECTS_H_\n\n#include <string>\n#include <vector>\n\n#include \"lodepng.h\"\n\n// forward declarations of all mjC/X classes\nclass mjCError;\nclass mjCAlternative;\nclass mjCBase;\nclass mjCBody;\nclass mjCJoint;\nclass mjCGeom;\nclass mjCSite;\nclass mjCCamera;\nclass mjCLight;\nclass mjCMesh;\nclass mjCSkin;\nclass mjCTexture;\nclass mjCMaterial;\nclass mjCPair;\nclass mjCBodyPair;\nclass mjCEquality;\nclass mjCTendon;\nclass mjCWrap;\nclass mjCActuator;\nclass mjCSensor;\nclass mjCNumeric;\nclass mjCText;\nclass mjCTuple;\nclass mjCDef;\nclass mjCMesh;                      // defined in user_mesh\nclass mjCModel;                     // defined in user_model\nclass mjXWriter;                    // defined in xml_native\nclass mjXURDF;                      // defined in xml_urdf\n\n\n//------------------------- helper classes and constants -------------------------------------------\n\n\n// builtin type for procedural textures\ntypedef enum _mjtBuiltin {\n  mjBUILTIN_NONE = 0,             // no builtin\n  mjBUILTIN_GRADIENT,             // circular gradient: rgb1->rgb2->rgb3\n  mjBUILTIN_CHECKER,              // checker pattern: rgb1, rgb2\n  mjBUILTIN_FLAT                  // 2d: rgb1; cube: rgb1-up, rgb2-side, rgb3-down\n} mjtBuiltin;\n\n\n// mark type for procedural textures\ntypedef enum _mjtMark {\n  mjMARK_NONE = 0,                // no mark\n  mjMARK_EDGE,                    // paint edges\n  mjMARK_CROSS,                   // paint cross\n  mjMARK_RANDOM                   // paint random dots\n} mjtMark;\n\n\n// error information\nclass mjCError {\n public:\n  mjCError(const mjCBase* obj = 0,\n           const char* msg = 0,\n           const char* str = 0,\n           int pos1 = 0,\n           int pos2 = 0);\n\n  char message[500];              // error message\n  bool warning;                   // is this a warning instead of error\n};\n\n\n// alternative specifications of frame orientation\nclass mjCAlternative {\n public:\n  mjCAlternative();                               // constructor\n  const char* Set(double* quat, double* inertia,  // set frame quat and diag. inertia\n                  bool degree,                    //  angle format: degree/radian\n                  const char* sequence);          //  euler sequence format: \"xyz\"\n\n  double axisangle[4];            // rotation axis and angle\n  double xyaxes[6];               // x and y axes\n  double zaxis[3];                // z axis (use minimal rotation)\n  double euler[3];                // euler rotations\n  double fullinertia[6];          // non-axis-aligned inertia matrix\n};\n\n\n\n//------------------------- class mjCBase ----------------------------------------------------------\n// Generic functionality for all derived classes\n\nclass mjCBase {\n  friend class mjCDef;\n\n public:\n  std::string name;               // object name\n  std::string classname;          // defaults class name\n  int id;                         // object id\n  int xmlpos[2];                  // row and column in xml file\n  mjCDef* def;                    // defaults class used to init this object\n\n protected:\n  mjCBase();                      // constructor\n  mjCModel* model;                // pointer to model that created object\n};\n\n\n\n//------------------------- class mjCBody -----------------------------------------------\n// Describes a rigid body\n\nclass mjCBody : public mjCBase {\n  friend class mjCJoint;\n  friend class mjCGeom;\n  friend class mjCSite;\n  friend class mjCCamera;\n  friend class mjCLight;\n  friend class mjCEquality;\n  friend class mjCPair;\n  friend class mjCModel;\n  friend class mjXReader;\n  friend class mjXWriter;\n  friend class mjXURDF;\n\n public:\n  // API for adding objects to body\n  mjCBody*    AddBody(mjCDef* = 0);\n  mjCJoint*   AddJoint(mjCDef* = 0, bool isfree = false);\n  mjCGeom*    AddGeom(mjCDef* = 0);\n  mjCSite*    AddSite(mjCDef* = 0);\n  mjCCamera*  AddCamera(mjCDef* = 0);\n  mjCLight*   AddLight(mjCDef* = 0);\n\n\n  // setup child local frame, take into account change\n  void MakeLocal(double* locpos, double* locquat, const double* pos, const double* quat);\n\n  // set explicit_inertial to true\n  void MakeInertialExplicit();\n\n  // variables set by user or 'Compile'\n  bool mocap;                     // is this a mocap body\n  double pos[3];                  // frame position\n  double quat[4];                 // frame orientation\n  double ipos[3];                 // inertial frame position\n  double iquat[4];                // inertial frame orientation\n  double mass;                    // mass\n  double inertia[3];              // diagonal inertia (in i-frame)\n  std::vector<double> userdata;   // user data\n  mjCAlternative alt;             // alternative orientation specification\n  mjCAlternative ialt;            // alternative for inertial frame\n\n  // variables computed by 'Compile' and 'AddXXX'\n private:\n  mjCBody(mjCModel*);                 // constructor\n  ~mjCBody();                         // destructor\n  void Compile(void);                 // compiler\n\n  void GeomFrame(void);               // get inertial info from geoms\n\n  double locpos[3];               // position relative to parent\n  double locquat[4];              // orientation relative to parent\n  double locipos[3];              // inertial position frame, rel. to local frame\n  double lociquat[4];             // inertial frame orientation\n  int parentid;                   // parent index in global array\n  int weldid;                     // top index of body we are welded to\n  int dofnum;                     // number of motion dofs for body\n  int mocapid;                    // mocap id, -1: not mocap\n  bool explicit_inertial;         // whether to save the body with an explicit inertial clause\n\n  int lastdof;                    // id of last dof (used by compiler)\n\n  // objects allocated by Add functions\n  std::vector<mjCBody*>    bodies;     // child bodies\n  std::vector<mjCGeom*>    geoms;      // geoms attached to this body\n  std::vector<mjCJoint*>   joints;     // joints allowing motion relative to parent\n  std::vector<mjCSite*>    sites;      // sites attached to this body\n  std::vector<mjCCamera*>  cameras;    // cameras attached to this body\n  std::vector<mjCLight*>   lights;     // lights attached to this body\n};\n\n#endif  // MUJOCO_SRC_USER_USER_OBJECTS_H_\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_7/lodepng/include/lodepng.h",
    "content": "/*\nLodePNG version 20220109\n\nCopyright (c) 2005-2022 Lode Vandevenne\n\nThis software is provided 'as-is', without any express or implied\nwarranty. In no event will the authors be held liable for any damages\narising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose,\nincluding commercial applications, and to alter it and redistribute it\nfreely, subject to the following restrictions:\n\n    1. The origin of this software must not be misrepresented; you must not\n    claim that you wrote the original software. If you use this software\n    in a product, an acknowledgment in the product documentation would be\n    appreciated but is not required.\n\n    2. Altered source versions must be plainly marked as such, and must not be\n    misrepresented as being the original software.\n\n    3. This notice may not be removed or altered from any source\n    distribution.\n*/\n\n#ifndef LODEPNG_H\n#define LODEPNG_H\n\n#include <string.h> /*for size_t*/\n\nextern const char* LODEPNG_VERSION_STRING;\n\n/*\nThe following #defines are used to create code sections. They can be disabled\nto disable code sections, which can give faster compile time and smaller binary.\nThe \"NO_COMPILE\" defines are designed to be used to pass as defines to the\ncompiler command to disable them without modifying this header, e.g.\n-DLODEPNG_NO_COMPILE_ZLIB for gcc.\nIn addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to\nallow implementing a custom lodepng_crc32.\n*/\n/*deflate & zlib. If disabled, you must specify alternative zlib functions in\nthe custom_zlib field of the compress and decompress settings*/\n#ifndef LODEPNG_NO_COMPILE_ZLIB\n#define LODEPNG_COMPILE_ZLIB\n#endif\n\n/*png encoder and png decoder*/\n#ifndef LODEPNG_NO_COMPILE_PNG\n#define LODEPNG_COMPILE_PNG\n#endif\n\n/*deflate&zlib decoder and png decoder*/\n#ifndef LODEPNG_NO_COMPILE_DECODER\n#define LODEPNG_COMPILE_DECODER\n#endif\n\n/*deflate&zlib encoder and png encoder*/\n#ifndef LODEPNG_NO_COMPILE_ENCODER\n#define LODEPNG_COMPILE_ENCODER\n#endif\n\n/*the optional built in harddisk file loading and saving functions*/\n#ifndef LODEPNG_NO_COMPILE_DISK\n#define LODEPNG_COMPILE_DISK\n#endif\n\n/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/\n#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS\n#define LODEPNG_COMPILE_ANCILLARY_CHUNKS\n#endif\n\n/*ability to convert error numerical codes to English text string*/\n#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT\n#define LODEPNG_COMPILE_ERROR_TEXT\n#endif\n\n/*Compile the default allocators (C's free, malloc and realloc). If you disable this,\nyou can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your\nsource files with custom allocators.*/\n#ifndef LODEPNG_NO_COMPILE_ALLOCATORS\n#define LODEPNG_COMPILE_ALLOCATORS\n#endif\n\n/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/\n#ifdef __cplusplus\n#ifndef LODEPNG_NO_COMPILE_CPP\n#define LODEPNG_COMPILE_CPP\n#endif\n#endif\n\n#ifdef LODEPNG_COMPILE_CPP\n#include <vector>\n#include <string>\n#endif /*LODEPNG_COMPILE_CPP*/\n\n#ifdef LODEPNG_COMPILE_PNG\n/*The PNG color types (also used for raw image).*/\ntypedef enum LodePNGColorType {\n  LCT_GREY = 0, /*grayscale: 1,2,4,8,16 bit*/\n  LCT_RGB = 2, /*RGB: 8,16 bit*/\n  LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/\n  LCT_GREY_ALPHA = 4, /*grayscale with alpha: 8,16 bit*/\n  LCT_RGBA = 6, /*RGB with alpha: 8,16 bit*/\n  /*LCT_MAX_OCTET_VALUE lets the compiler allow this enum to represent any invalid\n  byte value from 0 to 255 that could be present in an invalid PNG file header. Do\n  not use, compare with or set the name LCT_MAX_OCTET_VALUE, instead either use\n  the valid color type names above, or numeric values like 1 or 7 when checking for\n  particular disallowed color type byte values, or cast to integer to print it.*/\n  LCT_MAX_OCTET_VALUE = 255\n} LodePNGColorType;\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*\nConverts PNG data in memory to raw pixel data.\nout: Output parameter. Pointer to buffer that will contain the raw pixel data.\n     After decoding, its size is w * h * (bytes per pixel) bytes larger than\n     initially. Bytes per pixel depends on colortype and bitdepth.\n     Must be freed after usage with free(*out).\n     Note: for 16-bit per channel colors, uses big endian format like PNG does.\nw: Output parameter. Pointer to width of pixel data.\nh: Output parameter. Pointer to height of pixel data.\nin: Memory buffer with the PNG file.\ninsize: size of the in buffer.\ncolortype: the desired color type for the raw output image. See explanation on PNG color types.\nbitdepth: the desired bit depth for the raw output image. See explanation on PNG color types.\nReturn value: LodePNG error code (0 means no error).\n*/\nunsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h,\n                               const unsigned char* in, size_t insize,\n                               LodePNGColorType colortype, unsigned bitdepth);\n\n/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/\nunsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h,\n                          const unsigned char* in, size_t insize);\n\n/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/\nunsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h,\n                          const unsigned char* in, size_t insize);\n\n#ifdef LODEPNG_COMPILE_DISK\n/*\nLoad PNG from disk, from file with given name.\nSame as the other decode functions, but instead takes a filename as input.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.*/\nunsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h,\n                             const char* filename,\n                             LodePNGColorType colortype, unsigned bitdepth);\n\n/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.*/\nunsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h,\n                               const char* filename);\n\n/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.*/\nunsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h,\n                               const char* filename);\n#endif /*LODEPNG_COMPILE_DISK*/\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*\nConverts raw pixel data into a PNG image in memory. The colortype and bitdepth\n  of the output PNG image cannot be chosen, they are automatically determined\n  by the colortype, bitdepth and content of the input pixel data.\n  Note: for 16-bit per channel colors, needs big endian format like PNG does.\nout: Output parameter. Pointer to buffer that will contain the PNG image data.\n     Must be freed after usage with free(*out).\noutsize: Output parameter. Pointer to the size in bytes of the out buffer.\nimage: The raw pixel data to encode. The size of this buffer should be\n       w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth.\nw: width of the raw pixel data in pixels.\nh: height of the raw pixel data in pixels.\ncolortype: the color type of the raw input image. See explanation on PNG color types.\nbitdepth: the bit depth of the raw input image. See explanation on PNG color types.\nReturn value: LodePNG error code (0 means no error).\n*/\nunsigned lodepng_encode_memory(unsigned char** out, size_t* outsize,\n                               const unsigned char* image, unsigned w, unsigned h,\n                               LodePNGColorType colortype, unsigned bitdepth);\n\n/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/\nunsigned lodepng_encode32(unsigned char** out, size_t* outsize,\n                          const unsigned char* image, unsigned w, unsigned h);\n\n/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/\nunsigned lodepng_encode24(unsigned char** out, size_t* outsize,\n                          const unsigned char* image, unsigned w, unsigned h);\n\n#ifdef LODEPNG_COMPILE_DISK\n/*\nConverts raw pixel data into a PNG file on disk.\nSame as the other encode functions, but instead takes a filename as output.\n\nNOTE: This overwrites existing files without warning!\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory.*/\nunsigned lodepng_encode_file(const char* filename,\n                             const unsigned char* image, unsigned w, unsigned h,\n                             LodePNGColorType colortype, unsigned bitdepth);\n\n/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory.*/\nunsigned lodepng_encode32_file(const char* filename,\n                               const unsigned char* image, unsigned w, unsigned h);\n\n/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory.*/\nunsigned lodepng_encode24_file(const char* filename,\n                               const unsigned char* image, unsigned w, unsigned h);\n#endif /*LODEPNG_COMPILE_DISK*/\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n\n#ifdef LODEPNG_COMPILE_CPP\nnamespace lodepng {\n#ifdef LODEPNG_COMPILE_DECODER\n/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype\nis the format to output the pixels to. Default is RGBA 8-bit per channel.*/\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                const unsigned char* in, size_t insize,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                const std::vector<unsigned char>& in,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\n#ifdef LODEPNG_COMPILE_DISK\n/*\nConverts PNG file from disk to raw pixel data in memory.\nSame as the other decode functions, but instead takes a filename as input.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.\n*/\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                const std::string& filename,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\n#endif /* LODEPNG_COMPILE_DISK */\n#endif /* LODEPNG_COMPILE_DECODER */\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype\nis that of the raw input data. The output PNG color type will be auto chosen.*/\nunsigned encode(std::vector<unsigned char>& out,\n                const unsigned char* in, unsigned w, unsigned h,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\nunsigned encode(std::vector<unsigned char>& out,\n                const std::vector<unsigned char>& in, unsigned w, unsigned h,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\n#ifdef LODEPNG_COMPILE_DISK\n/*\nConverts 32-bit RGBA raw pixel data into a PNG file on disk.\nSame as the other encode functions, but instead takes a filename as output.\n\nNOTE: This overwrites existing files without warning!\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.\n*/\nunsigned encode(const std::string& filename,\n                const unsigned char* in, unsigned w, unsigned h,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\nunsigned encode(const std::string& filename,\n                const std::vector<unsigned char>& in, unsigned w, unsigned h,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\n#endif /* LODEPNG_COMPILE_DISK */\n#endif /* LODEPNG_COMPILE_ENCODER */\n} /* namespace lodepng */\n#endif /*LODEPNG_COMPILE_CPP*/\n#endif /*LODEPNG_COMPILE_PNG*/\n\n#ifdef LODEPNG_COMPILE_ERROR_TEXT\n/*Returns an English description of the numerical error code.*/\nconst char* lodepng_error_text(unsigned code);\n#endif /*LODEPNG_COMPILE_ERROR_TEXT*/\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*Settings for zlib decompression*/\ntypedef struct LodePNGDecompressSettings LodePNGDecompressSettings;\nstruct LodePNGDecompressSettings {\n  /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */\n  unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/\n  unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/\n\n  /*Maximum decompressed size, beyond this the decoder may (and is encouraged to) stop decoding,\n  return an error, output a data size > max_output_size and all the data up to that point. This is\n  not hard limit nor a guarantee, but can prevent excessive memory usage. This setting is\n  ignored by the PNG decoder, but is used by the deflate/zlib decoder and can be used by custom ones.\n  Set to 0 to impose no limit (the default).*/\n  size_t max_output_size;\n\n  /*use custom zlib decoder instead of built in one (default: null).\n  Should return 0 if success, any non-0 if error (numeric value not exposed).*/\n  unsigned (*custom_zlib)(unsigned char**, size_t*,\n                          const unsigned char*, size_t,\n                          const LodePNGDecompressSettings*);\n  /*use custom deflate decoder instead of built in one (default: null)\n  if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate).\n  Should return 0 if success, any non-0 if error (numeric value not exposed).*/\n  unsigned (*custom_inflate)(unsigned char**, size_t*,\n                             const unsigned char*, size_t,\n                             const LodePNGDecompressSettings*);\n\n  const void* custom_context; /*optional custom settings for custom functions*/\n};\n\nextern const LodePNGDecompressSettings lodepng_default_decompress_settings;\nvoid lodepng_decompress_settings_init(LodePNGDecompressSettings* settings);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*\nSettings for zlib compression. Tweaking these settings tweaks the balance\nbetween speed and compression ratio.\n*/\ntypedef struct LodePNGCompressSettings LodePNGCompressSettings;\nstruct LodePNGCompressSettings /*deflate = compress*/ {\n  /*LZ77 related settings*/\n  unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/\n  unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/\n  unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/\n  unsigned minmatch; /*minimum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/\n  unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/\n  unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/\n\n  /*use custom zlib encoder instead of built in one (default: null)*/\n  unsigned (*custom_zlib)(unsigned char**, size_t*,\n                          const unsigned char*, size_t,\n                          const LodePNGCompressSettings*);\n  /*use custom deflate encoder instead of built in one (default: null)\n  if custom_zlib is used, custom_deflate is ignored since only the built in\n  zlib function will call custom_deflate*/\n  unsigned (*custom_deflate)(unsigned char**, size_t*,\n                             const unsigned char*, size_t,\n                             const LodePNGCompressSettings*);\n\n  const void* custom_context; /*optional custom settings for custom functions*/\n};\n\nextern const LodePNGCompressSettings lodepng_default_compress_settings;\nvoid lodepng_compress_settings_init(LodePNGCompressSettings* settings);\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n#ifdef LODEPNG_COMPILE_PNG\n/*\nColor mode of an image. Contains all information required to decode the pixel\nbits to RGBA colors. This information is the same as used in the PNG file\nformat, and is used both for PNG and raw image data in LodePNG.\n*/\ntypedef struct LodePNGColorMode {\n  /*header (IHDR)*/\n  LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/\n  unsigned bitdepth;  /*bits per sample, see PNG standard or documentation further in this header file*/\n\n  /*\n  palette (PLTE and tRNS)\n\n  Dynamically allocated with the colors of the palette, including alpha.\n  This field may not be allocated directly, use lodepng_color_mode_init first,\n  then lodepng_palette_add per color to correctly initialize it (to ensure size\n  of exactly 1024 bytes).\n\n  The alpha channels must be set as well, set them to 255 for opaque images.\n\n  When decoding, by default you can ignore this palette, since LodePNG already\n  fills the palette colors in the pixels of the raw RGBA output.\n\n  The palette is only supported for color type 3.\n  */\n  unsigned char* palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/\n  size_t palettesize; /*palette size in number of colors (amount of used bytes is 4 * palettesize)*/\n\n  /*\n  transparent color key (tRNS)\n\n  This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit.\n  For grayscale PNGs, r, g and b will all 3 be set to the same.\n\n  When decoding, by default you can ignore this information, since LodePNG sets\n  pixels with this key to transparent already in the raw RGBA output.\n\n  The color key is only supported for color types 0 and 2.\n  */\n  unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/\n  unsigned key_r;       /*red/grayscale component of color key*/\n  unsigned key_g;       /*green component of color key*/\n  unsigned key_b;       /*blue component of color key*/\n} LodePNGColorMode;\n\n/*init, cleanup and copy functions to use with this struct*/\nvoid lodepng_color_mode_init(LodePNGColorMode* info);\nvoid lodepng_color_mode_cleanup(LodePNGColorMode* info);\n/*return value is error code (0 means no error)*/\nunsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source);\n/* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */\nLodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth);\n\nvoid lodepng_palette_clear(LodePNGColorMode* info);\n/*add 1 color to the palette*/\nunsigned lodepng_palette_add(LodePNGColorMode* info,\n                             unsigned char r, unsigned char g, unsigned char b, unsigned char a);\n\n/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/\nunsigned lodepng_get_bpp(const LodePNGColorMode* info);\n/*get the amount of color channels used, based on colortype in the struct.\nIf a palette is used, it counts as 1 channel.*/\nunsigned lodepng_get_channels(const LodePNGColorMode* info);\n/*is it a grayscale type? (only colortype 0 or 4)*/\nunsigned lodepng_is_greyscale_type(const LodePNGColorMode* info);\n/*has it got an alpha channel? (only colortype 2 or 6)*/\nunsigned lodepng_is_alpha_type(const LodePNGColorMode* info);\n/*has it got a palette? (only colortype 3)*/\nunsigned lodepng_is_palette_type(const LodePNGColorMode* info);\n/*only returns true if there is a palette and there is a value in the palette with alpha < 255.\nLoops through the palette to check this.*/\nunsigned lodepng_has_palette_alpha(const LodePNGColorMode* info);\n/*\nCheck if the given color info indicates the possibility of having non-opaque pixels in the PNG image.\nReturns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).\nReturns false if the image can only have opaque pixels.\nIn detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,\nor if \"key_defined\" is true.\n*/\nunsigned lodepng_can_have_alpha(const LodePNGColorMode* info);\n/*Returns the byte size of a raw image buffer with given width, height and color mode*/\nsize_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color);\n\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\n/*The information of a Time chunk in PNG.*/\ntypedef struct LodePNGTime {\n  unsigned year;    /*2 bytes used (0-65535)*/\n  unsigned month;   /*1-12*/\n  unsigned day;     /*1-31*/\n  unsigned hour;    /*0-23*/\n  unsigned minute;  /*0-59*/\n  unsigned second;  /*0-60 (to allow for leap seconds)*/\n} LodePNGTime;\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n\n/*Information about the PNG image, except pixels, width and height.*/\ntypedef struct LodePNGInfo {\n  /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/\n  unsigned compression_method;/*compression method of the original file. Always 0.*/\n  unsigned filter_method;     /*filter method of the original file*/\n  unsigned interlace_method;  /*interlace method of the original file: 0=none, 1=Adam7*/\n  LodePNGColorMode color;     /*color type and bits, palette and transparency of the PNG file*/\n\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\n  /*\n  Suggested background color chunk (bKGD)\n\n  This uses the same color mode and bit depth as the PNG (except no alpha channel),\n  with values truncated to the bit depth in the unsigned integer.\n\n  For grayscale and palette PNGs, the value is stored in background_r. The values\n  in background_g and background_b are then unused.\n\n  So when decoding, you may get these in a different color mode than the one you requested\n  for the raw pixels.\n\n  When encoding with auto_convert, you must use the color model defined in info_png.color for\n  these values. The encoder normally ignores info_png.color when auto_convert is on, but will\n  use it to interpret these values (and convert copies of them to its chosen color model).\n\n  When encoding, avoid setting this to an expensive color, such as a non-gray value\n  when the image is gray, or the compression will be worse since it will be forced to\n  write the PNG with a more expensive color mode (when auto_convert is on).\n\n  The decoder does not use this background color to edit the color of pixels. This is a\n  completely optional metadata feature.\n  */\n  unsigned background_defined; /*is a suggested background color given?*/\n  unsigned background_r;       /*red/gray/palette component of suggested background color*/\n  unsigned background_g;       /*green component of suggested background color*/\n  unsigned background_b;       /*blue component of suggested background color*/\n\n  /*\n  Non-international text chunks (tEXt and zTXt)\n\n  The char** arrays each contain num strings. The actual messages are in\n  text_strings, while text_keys are keywords that give a short description what\n  the actual text represents, e.g. Title, Author, Description, or anything else.\n\n  All the string fields below including strings, keys, names and language tags are null terminated.\n  The PNG specification uses null characters for the keys, names and tags, and forbids null\n  characters to appear in the main text which is why we can use null termination everywhere here.\n\n  A keyword is minimum 1 character and maximum 79 characters long (plus the\n  additional null terminator). It's discouraged to use a single line length\n  longer than 79 characters for texts.\n\n  Don't allocate these text buffers yourself. Use the init/cleanup functions\n  correctly and use lodepng_add_text and lodepng_clear_text.\n\n  Standard text chunk keywords and strings are encoded using Latin-1.\n  */\n  size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/\n  char** text_keys; /*the keyword of a text chunk (e.g. \"Comment\")*/\n  char** text_strings; /*the actual text*/\n\n  /*\n  International text chunks (iTXt)\n  Similar to the non-international text chunks, but with additional strings\n  \"langtags\" and \"transkeys\", and the following text encodings are used:\n  keys: Latin-1, langtags: ASCII, transkeys and strings: UTF-8.\n  keys must be 1-79 characters (plus the additional null terminator), the other\n  strings are any length.\n  */\n  size_t itext_num; /*the amount of international texts in this PNG*/\n  char** itext_keys; /*the English keyword of the text chunk (e.g. \"Comment\")*/\n  char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/\n  char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/\n  char** itext_strings; /*the actual international text - UTF-8 string*/\n\n  /*time chunk (tIME)*/\n  unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/\n  LodePNGTime time;\n\n  /*phys chunk (pHYs)*/\n  unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/\n  unsigned phys_x; /*pixels per unit in x direction*/\n  unsigned phys_y; /*pixels per unit in y direction*/\n  unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/\n\n  /*\n  Color profile related chunks: gAMA, cHRM, sRGB, iCPP\n\n  LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color\n  profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please\n  use these values with a color management library.\n\n  See the PNG, ICC and sRGB specifications for more information about the meaning of these values.\n  */\n\n  /* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */\n  unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */\n  unsigned gama_gamma;   /* Gamma exponent times 100000 */\n\n  /* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */\n  unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */\n  unsigned chrm_white_x; /* White Point x times 100000 */\n  unsigned chrm_white_y; /* White Point y times 100000 */\n  unsigned chrm_red_x;   /* Red x times 100000 */\n  unsigned chrm_red_y;   /* Red y times 100000 */\n  unsigned chrm_green_x; /* Green x times 100000 */\n  unsigned chrm_green_y; /* Green y times 100000 */\n  unsigned chrm_blue_x;  /* Blue x times 100000 */\n  unsigned chrm_blue_y;  /* Blue y times 100000 */\n\n  /*\n  sRGB chunk: optional. May not appear at the same time as iCCP.\n  If gAMA is also present gAMA must contain value 45455.\n  If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000.\n  */\n  unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */\n  unsigned srgb_intent;  /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */\n\n  /*\n  iCCP chunk: optional. May not appear at the same time as sRGB.\n\n  LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a\n  separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color\n  management and conversions.\n\n  For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC\n  profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and\n  enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile.\n\n  For encoding, the ICC profile is required by the PNG specification to be an \"RGB\" profile for non-gray\n  PNG color types and a \"GRAY\" profile for gray PNG color types. If you disable auto_convert, you must ensure\n  the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is\n  enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder\n  error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of the pixel\n  data if the pixels could be encoded as grayscale but the ICC profile is RGB.\n\n  To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so\n  make sure you compute it carefully to avoid the above problems.\n  */\n  unsigned iccp_defined;      /* Whether an iCCP chunk is present (0 = not present, 1 = present). */\n  char* iccp_name;            /* Null terminated string with profile name, 1-79 bytes */\n  /*\n  The ICC profile in iccp_profile_size bytes.\n  Don't allocate this buffer yourself. Use the init/cleanup functions\n  correctly and use lodepng_set_icc and lodepng_clear_icc.\n  */\n  unsigned char* iccp_profile;\n  unsigned iccp_profile_size; /* The size of iccp_profile in bytes */\n\n  /* End of color profile related chunks */\n\n\n  /*\n  unknown chunks: chunks not known by LodePNG, passed on byte for byte.\n\n  There are 3 buffers, one for each position in the PNG where unknown chunks can appear.\n  Each buffer contains all unknown chunks for that position consecutively.\n  The 3 positions are:\n  0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND.\n\n  For encoding, do not store critical chunks or known chunks that are enabled with a \"_defined\" flag\n  above in here, since the encoder will blindly follow this and could then encode an invalid PNG file\n  (such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use\n  this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST),\n  or any non-standard PNG chunk.\n\n  Do not allocate or traverse this data yourself. Use the chunk traversing functions declared\n  later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct.\n  */\n  unsigned char* unknown_chunks_data[3];\n  size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n} LodePNGInfo;\n\n/*init, cleanup and copy functions to use with this struct*/\nvoid lodepng_info_init(LodePNGInfo* info);\nvoid lodepng_info_cleanup(LodePNGInfo* info);\n/*return value is error code (0 means no error)*/\nunsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source);\n\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\nunsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/\nvoid lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/\n\nunsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,\n                           const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/\nvoid lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/\n\n/*replaces if exists*/\nunsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size);\nvoid lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n\n/*\nConverts raw buffer from one color type to another color type, based on\nLodePNGColorMode structs to describe the input and output color type.\nSee the reference manual at the end of this header file to see which color conversions are supported.\nreturn value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported)\nThe out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel\nof the output color type (lodepng_get_bpp).\nFor < 8 bpp images, there should not be padding bits at the end of scanlines.\nFor 16-bit per channel colors, uses big endian format like PNG does.\nReturn value is LodePNG error code\n*/\nunsigned lodepng_convert(unsigned char* out, const unsigned char* in,\n                         const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,\n                         unsigned w, unsigned h);\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*\nSettings for the decoder. This contains settings for the PNG and the Zlib\ndecoder, but not the Info settings from the Info structs.\n*/\ntypedef struct LodePNGDecoderSettings {\n  LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/\n\n  /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */\n  unsigned ignore_crc; /*ignore CRC checksums*/\n  unsigned ignore_critical; /*ignore unknown critical chunks*/\n  unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/\n  /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable\n     errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some\n     strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters\n     in string keys, etc... */\n\n  unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/\n\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\n  unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/\n\n  /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/\n  unsigned remember_unknown_chunks;\n\n  /* maximum size for decompressed text chunks. If a text chunk's text is larger than this, an error is returned,\n  unless reading text chunks is disabled or this limit is set higher or disabled. Set to 0 to allow any size.\n  By default it is a value that prevents unreasonably large strings from hogging memory. */\n  size_t max_text_size;\n\n  /* maximum size for compressed ICC chunks. If the ICC profile is larger than this, an error will be returned. Set to\n  0 to allow any size. By default this is a value that prevents ICC profiles that would be much larger than any\n  legitimate profile could be to hog memory. */\n  size_t max_icc_size;\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n} LodePNGDecoderSettings;\n\nvoid lodepng_decoder_settings_init(LodePNGDecoderSettings* settings);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/\ntypedef enum LodePNGFilterStrategy {\n  /*every filter at zero*/\n  LFS_ZERO = 0,\n  /*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/\n  LFS_ONE = 1,\n  LFS_TWO = 2,\n  LFS_THREE = 3,\n  LFS_FOUR = 4,\n  /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/\n  LFS_MINSUM,\n  /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending\n  on the image, this is better or worse than minsum.*/\n  LFS_ENTROPY,\n  /*\n  Brute-force-search PNG filters by compressing each filter for each scanline.\n  Experimental, very slow, and only rarely gives better compression than MINSUM.\n  */\n  LFS_BRUTE_FORCE,\n  /*use predefined_filters buffer: you specify the filter type for each scanline*/\n  LFS_PREDEFINED\n} LodePNGFilterStrategy;\n\n/*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...),\nwhich helps decide which color model to use for encoding.\nUsed internally by default if \"auto_convert\" is enabled. Public because it's useful for custom algorithms.*/\ntypedef struct LodePNGColorStats {\n  unsigned colored; /*not grayscale*/\n  unsigned key; /*image is not opaque and color key is possible instead of full alpha*/\n  unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/\n  unsigned short key_g;\n  unsigned short key_b;\n  unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/\n  unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/\n  unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/\n  unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/\n  size_t numpixels;\n\n  /*user settings for computing/using the stats*/\n  unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/\n  unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/\n} LodePNGColorStats;\n\nvoid lodepng_color_stats_init(LodePNGColorStats* stats);\n\n/*Get a LodePNGColorStats of the image. The stats must already have been inited.\nReturns error code (e.g. alloc fail) or 0 if ok.*/\nunsigned lodepng_compute_color_stats(LodePNGColorStats* stats,\n                                     const unsigned char* image, unsigned w, unsigned h,\n                                     const LodePNGColorMode* mode_in);\n\n/*Settings for the encoder.*/\ntypedef struct LodePNGEncoderSettings {\n  LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/\n\n  unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/\n\n  /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than\n  8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to\n  completely follow the official PNG heuristic, filter_palette_zero must be true and\n  filter_strategy must be LFS_MINSUM*/\n  unsigned filter_palette_zero;\n  /*Which filter strategy to use when not using zeroes due to filter_palette_zero.\n  Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/\n  LodePNGFilterStrategy filter_strategy;\n  /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with\n  the same length as the amount of scanlines in the image, and each value must <= 5. You\n  have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero\n  must be set to 0 to ensure this is also used on palette or low bitdepth images.*/\n  const unsigned char* predefined_filters;\n\n  /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette).\n  If colortype is 3, PLTE is _always_ created.*/\n  unsigned force_palette;\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\n  /*add LodePNG identifier and version as a text chunk, for debugging*/\n  unsigned add_id;\n  /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/\n  unsigned text_compression;\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n} LodePNGEncoderSettings;\n\nvoid lodepng_encoder_settings_init(LodePNGEncoderSettings* settings);\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n\n#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)\n/*The settings, state and information for extended encoding and decoding.*/\ntypedef struct LodePNGState {\n#ifdef LODEPNG_COMPILE_DECODER\n  LodePNGDecoderSettings decoder; /*the decoding settings*/\n#endif /*LODEPNG_COMPILE_DECODER*/\n#ifdef LODEPNG_COMPILE_ENCODER\n  LodePNGEncoderSettings encoder; /*the encoding settings*/\n#endif /*LODEPNG_COMPILE_ENCODER*/\n  LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/\n  LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/\n  unsigned error;\n} LodePNGState;\n\n/*init, cleanup and copy functions to use with this struct*/\nvoid lodepng_state_init(LodePNGState* state);\nvoid lodepng_state_cleanup(LodePNGState* state);\nvoid lodepng_state_copy(LodePNGState* dest, const LodePNGState* source);\n#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*\nSame as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and\ngetting much more information about the PNG image and color mode.\n*/\nunsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,\n                        LodePNGState* state,\n                        const unsigned char* in, size_t insize);\n\n/*\nRead the PNG header, but not the actual data. This returns only the information\nthat is in the IHDR chunk of the PNG, such as width, height and color type. The\ninformation is placed in the info_png field of the LodePNGState.\n*/\nunsigned lodepng_inspect(unsigned* w, unsigned* h,\n                         LodePNGState* state,\n                         const unsigned char* in, size_t insize);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n/*\nReads one metadata chunk (other than IHDR) of the PNG file and outputs what it\nread in the state. Returns error code on failure.\nUse lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const\nto find the desired chunk type, and if non null use lodepng_inspect_chunk (with\nchunk_pointer - start_of_file as pos).\nSupports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...).\nIgnores unsupported, unknown, non-metadata or IHDR chunks (without error).\nRequirements: &in[pos] must point to start of a chunk, must use regular\nlodepng_inspect first since format of most other chunks depends on IHDR, and if\nthere is a PLTE chunk, that one must be inspected before tRNS or bKGD.\n*/\nunsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,\n                               const unsigned char* in, size_t insize);\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/\nunsigned lodepng_encode(unsigned char** out, size_t* outsize,\n                        const unsigned char* image, unsigned w, unsigned h,\n                        LodePNGState* state);\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n/*\nThe lodepng_chunk functions are normally not needed, except to traverse the\nunknown chunks stored in the LodePNGInfo struct, or add new ones to it.\nIt also allows traversing the chunks of an encoded PNG file yourself.\n\nThe chunk pointer always points to the beginning of the chunk itself, that is\nthe first byte of the 4 length bytes.\n\nIn the PNG file format, chunks have the following format:\n-4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer)\n-4 bytes chunk type (ASCII a-z,A-Z only, see below)\n-length bytes of data (may be 0 bytes if length was 0)\n-4 bytes of CRC, computed on chunk name + data\n\nThe first chunk starts at the 8th byte of the PNG file, the entire rest of the file\nexists out of concatenated chunks with the above format.\n\nPNG standard chunk ASCII naming conventions:\n-First byte: uppercase = critical, lowercase = ancillary\n-Second byte: uppercase = public, lowercase = private\n-Third byte: must be uppercase\n-Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy\n*/\n\n/*\nGets the length of the data of the chunk. Total chunk length has 12 bytes more.\nThere must be at least 4 bytes to read from. If the result value is too large,\nit may be corrupt data.\n*/\nunsigned lodepng_chunk_length(const unsigned char* chunk);\n\n/*puts the 4-byte type in null terminated string*/\nvoid lodepng_chunk_type(char type[5], const unsigned char* chunk);\n\n/*check if the type is the given type*/\nunsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type);\n\n/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/\nunsigned char lodepng_chunk_ancillary(const unsigned char* chunk);\n\n/*0: public, 1: private (see PNG standard)*/\nunsigned char lodepng_chunk_private(const unsigned char* chunk);\n\n/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/\nunsigned char lodepng_chunk_safetocopy(const unsigned char* chunk);\n\n/*get pointer to the data of the chunk, where the input points to the header of the chunk*/\nunsigned char* lodepng_chunk_data(unsigned char* chunk);\nconst unsigned char* lodepng_chunk_data_const(const unsigned char* chunk);\n\n/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/\nunsigned lodepng_chunk_check_crc(const unsigned char* chunk);\n\n/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/\nvoid lodepng_chunk_generate_crc(unsigned char* chunk);\n\n/*\nIterate to next chunks, allows iterating through all chunks of the PNG file.\nInput must be at the beginning of a chunk (result of a previous lodepng_chunk_next call,\nor the 8th byte of a PNG file which always has the first chunk), or alternatively may\npoint to the first byte of the PNG file (which is not a chunk but the magic header, the\nfunction will then skip over it and return the first real chunk).\nWill output pointer to the start of the next chunk, or at or beyond end of the file if there\nis no more chunk after this or possibly if the chunk is corrupt.\nStart this process at the 8th byte of the PNG file.\nIn a non-corrupt PNG file, the last chunk should have name \"IEND\".\n*/\nunsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end);\nconst unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end);\n\n/*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/\nunsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]);\nconst unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]);\n\n/*\nAppends chunk to the data in out. The given chunk should already have its chunk header.\nThe out variable and outsize are updated to reflect the new reallocated buffer.\nReturns error code (0 if it went ok)\n*/\nunsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk);\n\n/*\nAppends new chunk to out. The chunk to append is given by giving its length, type\nand data separately. The type is a 4-letter string.\nThe out variable and outsize are updated to reflect the new reallocated buffer.\nReturns error code (0 if it went ok)\n*/\nunsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length,\n                              const char* type, const unsigned char* data);\n\n\n/*Calculate CRC32 of buffer*/\nunsigned lodepng_crc32(const unsigned char* buf, size_t len);\n#endif /*LODEPNG_COMPILE_PNG*/\n\n\n#ifdef LODEPNG_COMPILE_ZLIB\n/*\nThis zlib part can be used independently to zlib compress and decompress a\nbuffer. It cannot be used to create gzip files however, and it only supports the\npart of zlib that is required for PNG, it does not support dictionaries.\n*/\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/\nunsigned lodepng_inflate(unsigned char** out, size_t* outsize,\n                         const unsigned char* in, size_t insize,\n                         const LodePNGDecompressSettings* settings);\n\n/*\nDecompresses Zlib data. Reallocates the out buffer and appends the data. The\ndata must be according to the zlib specification.\nEither, *out must be NULL and *outsize must be 0, or, *out must be a valid\nbuffer and *outsize its size in bytes. out must be freed by user after usage.\n*/\nunsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize,\n                                 const unsigned char* in, size_t insize,\n                                 const LodePNGDecompressSettings* settings);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*\nCompresses data with Zlib. Reallocates the out buffer and appends the data.\nZlib adds a small header and trailer around the deflate data.\nThe data is output in the format of the zlib specification.\nEither, *out must be NULL and *outsize must be 0, or, *out must be a valid\nbuffer and *outsize its size in bytes. out must be freed by user after usage.\n*/\nunsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize,\n                               const unsigned char* in, size_t insize,\n                               const LodePNGCompressSettings* settings);\n\n/*\nFind length-limited Huffman code for given frequencies. This function is in the\npublic interface only for tests, it's used internally by lodepng_deflate.\n*/\nunsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,\n                                      size_t numcodes, unsigned maxbitlen);\n\n/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/\nunsigned lodepng_deflate(unsigned char** out, size_t* outsize,\n                         const unsigned char* in, size_t insize,\n                         const LodePNGCompressSettings* settings);\n\n#endif /*LODEPNG_COMPILE_ENCODER*/\n#endif /*LODEPNG_COMPILE_ZLIB*/\n\n#ifdef LODEPNG_COMPILE_DISK\n/*\nLoad a file from disk into buffer. The function allocates the out buffer, and\nafter usage you should free it.\nout: output parameter, contains pointer to loaded buffer.\noutsize: output parameter, size of the allocated out buffer\nfilename: the path to the file to load\nreturn value: error code (0 means ok)\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.\n*/\nunsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename);\n\n/*\nSave a file from buffer to disk. Warning, if it exists, this function overwrites\nthe file without warning!\nbuffer: the buffer to write\nbuffersize: size of the buffer to write\nfilename: the path to the file to save to\nreturn value: error code (0 means ok)\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory\n*/\nunsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename);\n#endif /*LODEPNG_COMPILE_DISK*/\n\n#ifdef LODEPNG_COMPILE_CPP\n/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */\nnamespace lodepng {\n#ifdef LODEPNG_COMPILE_PNG\nclass State : public LodePNGState {\n  public:\n    State();\n    State(const State& other);\n    ~State();\n    State& operator=(const State& other);\n};\n\n#ifdef LODEPNG_COMPILE_DECODER\n/* Same as other lodepng::decode, but using a State for more settings and information. */\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                State& state,\n                const unsigned char* in, size_t insize);\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                State& state,\n                const std::vector<unsigned char>& in);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/* Same as other lodepng::encode, but using a State for more settings and information. */\nunsigned encode(std::vector<unsigned char>& out,\n                const unsigned char* in, unsigned w, unsigned h,\n                State& state);\nunsigned encode(std::vector<unsigned char>& out,\n                const std::vector<unsigned char>& in, unsigned w, unsigned h,\n                State& state);\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n#ifdef LODEPNG_COMPILE_DISK\n/*\nLoad a file from disk into an std::vector.\nreturn value: error code (0 means ok)\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory\n*/\nunsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename);\n\n/*\nSave the binary data in an std::vector to a file on disk. The file is overwritten\nwithout warning.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory\n*/\nunsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename);\n#endif /* LODEPNG_COMPILE_DISK */\n#endif /* LODEPNG_COMPILE_PNG */\n\n#ifdef LODEPNG_COMPILE_ZLIB\n#ifdef LODEPNG_COMPILE_DECODER\n/* Zlib-decompress an unsigned char buffer */\nunsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,\n                    const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);\n\n/* Zlib-decompress an std::vector */\nunsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,\n                    const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);\n#endif /* LODEPNG_COMPILE_DECODER */\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/* Zlib-compress an unsigned char buffer */\nunsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,\n                  const LodePNGCompressSettings& settings = lodepng_default_compress_settings);\n\n/* Zlib-compress an std::vector */\nunsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,\n                  const LodePNGCompressSettings& settings = lodepng_default_compress_settings);\n#endif /* LODEPNG_COMPILE_ENCODER */\n#endif /* LODEPNG_COMPILE_ZLIB */\n} /* namespace lodepng */\n#endif /*LODEPNG_COMPILE_CPP*/\n\n/*\nTODO:\n[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often\n[.] check compatibility with various compilers  - done but needs to be redone for every newer version\n[X] converting color to 16-bit per channel types\n[X] support color profile chunk types (but never let them touch RGB values by default)\n[ ] support all public PNG chunk types (almost done except sBIT, sPLT and hIST)\n[ ] make sure encoder generates no chunks with size > (2^31)-1\n[ ] partial decoding (stream processing)\n[X] let the \"isFullyOpaque\" function check color keys and transparent palettes too\n[X] better name for the variables \"codes\", \"codesD\", \"codelengthcodes\", \"clcl\" and \"lldl\"\n[ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58)\n[ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ...\n[ ] error messages with line numbers (and version)\n[ ] errors in state instead of as return code?\n[ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk\n[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes\n[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ...\n[ ] allow user to give data (void*) to custom allocator\n[X] provide alternatives for C library functions not present on some platforms (memcpy, ...)\n*/\n\n#endif /*LODEPNG_H inclusion guard*/\n\n/*\nLodePNG Documentation\n---------------------\n\n0. table of contents\n--------------------\n\n  1. about\n   1.1. supported features\n   1.2. features not supported\n  2. C and C++ version\n  3. security\n  4. decoding\n  5. encoding\n  6. color conversions\n    6.1. PNG color types\n    6.2. color conversions\n    6.3. padding bits\n    6.4. A note about 16-bits per channel and endianness\n  7. error values\n  8. chunks and PNG editing\n  9. compiler support\n  10. examples\n   10.1. decoder C++ example\n   10.2. decoder C example\n  11. state settings reference\n  12. changes\n  13. contact information\n\n\n1. about\n--------\n\nPNG is a file format to store raster images losslessly with good compression,\nsupporting different color types and alpha channel.\n\nLodePNG is a PNG codec according to the Portable Network Graphics (PNG)\nSpecification (Second Edition) - W3C Recommendation 10 November 2003.\n\nThe specifications used are:\n\n*) Portable Network Graphics (PNG) Specification (Second Edition):\n     http://www.w3.org/TR/2003/REC-PNG-20031110\n*) RFC 1950 ZLIB Compressed Data Format version 3.3:\n     http://www.gzip.org/zlib/rfc-zlib.html\n*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3:\n     http://www.gzip.org/zlib/rfc-deflate.html\n\nThe most recent version of LodePNG can currently be found at\nhttp://lodev.org/lodepng/\n\nLodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds\nextra functionality.\n\nLodePNG exists out of two files:\n-lodepng.h: the header file for both C and C++\n-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage\n\nIf you want to start using LodePNG right away without reading this doc, get the\nexamples from the LodePNG website to see how to use it in code, or check the\nsmaller examples in chapter 13 here.\n\nLodePNG is simple but only supports the basic requirements. To achieve\nsimplicity, the following design choices were made: There are no dependencies\non any external library. There are functions to decode and encode a PNG with\na single function call, and extended versions of these functions taking a\nLodePNGState struct allowing to specify or get more information. By default\nthe colors of the raw image are always RGB or RGBA, no matter what color type\nthe PNG file uses. To read and write files, there are simple functions to\nconvert the files to/from buffers in memory.\n\nThis all makes LodePNG suitable for loading textures in games, demos and small\nprograms, ... It's less suitable for full fledged image editors, loading PNGs\nover network (it requires all the image data to be available before decoding can\nbegin), life-critical systems, ...\n\n1.1. supported features\n-----------------------\n\nThe following features are supported by the decoder:\n\n*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image,\n   or the same color type as the PNG\n*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image\n*) Adam7 interlace and deinterlace for any color type\n*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk\n*) support for alpha channels, including RGBA color model, translucent palettes and color keying\n*) zlib decompression (inflate)\n*) zlib compression (deflate)\n*) CRC32 and ADLER32 checksums\n*) colorimetric color profile conversions: currently experimentally available in lodepng_util.cpp only,\n   plus alternatively ability to pass on chroma/gamma/ICC profile information to other color management system.\n*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks.\n*) the following chunks are supported by both encoder and decoder:\n    IHDR: header information\n    PLTE: color palette\n    IDAT: pixel data\n    IEND: the final chunk\n    tRNS: transparency for palettized images\n    tEXt: textual information\n    zTXt: compressed textual information\n    iTXt: international textual information\n    bKGD: suggested background color\n    pHYs: physical dimensions\n    tIME: modification time\n    cHRM: RGB chromaticities\n    gAMA: RGB gamma correction\n    iCCP: ICC color profile\n    sRGB: rendering intent\n\n1.2. features not supported\n---------------------------\n\nThe following features are _not_ supported:\n\n*) some features needed to make a conformant PNG-Editor might be still missing.\n*) partial loading/stream processing. All data must be available and is processed in one call.\n*) The following public chunks are not (yet) supported but treated as unknown chunks by LodePNG:\n    sBIT\n    hIST\n    sPLT\n\n\n2. C and C++ version\n--------------------\n\nThe C version uses buffers allocated with alloc that you need to free()\nyourself. You need to use init and cleanup functions for each struct whenever\nusing a struct from the C version to avoid exploits and memory leaks.\n\nThe C++ version has extra functions with std::vectors in the interface and the\nlodepng::State class which is a LodePNGState with constructor and destructor.\n\nThese files work without modification for both C and C++ compilers because all\nthe additional C++ code is in \"#ifdef __cplusplus\" blocks that make C-compilers\nignore it, and the C code is made to compile both with strict ISO C90 and C++.\n\nTo use the C++ version, you need to rename the source file to lodepng.cpp\n(instead of lodepng.c), and compile it with a C++ compiler.\n\nTo use the C version, you need to rename the source file to lodepng.c (instead\nof lodepng.cpp), and compile it with a C compiler.\n\n\n3. Security\n-----------\n\nEven if carefully designed, it's always possible that LodePNG contains possible\nexploits. If you discover one, please let me know, and it will be fixed.\n\nWhen using LodePNG, care has to be taken with the C version of LodePNG, as well\nas the C-style structs when working with C++. The following conventions are used\nfor all C-style structs:\n\n-if a struct has a corresponding init function, always call the init function when making a new one\n-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks\n-if a struct has a corresponding copy function, use the copy function instead of \"=\".\n The destination must also be inited already.\n\n\n4. Decoding\n-----------\n\nDecoding converts a PNG compressed image to a raw pixel buffer.\n\nMost documentation on using the decoder is at its declarations in the header\nabove. For C, simple decoding can be done with functions such as\nlodepng_decode32, and more advanced decoding can be done with the struct\nLodePNGState and lodepng_decode. For C++, all decoding can be done with the\nvarious lodepng::decode functions, and lodepng::State can be used for advanced\nfeatures.\n\nWhen using the LodePNGState, it uses the following fields for decoding:\n*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here\n*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get\n*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use\n\nLodePNGInfo info_png\n--------------------\n\nAfter decoding, this contains extra information of the PNG image, except the actual\npixels, width and height because these are already gotten directly from the decoder\nfunctions.\n\nIt contains for example the original color type of the PNG image, text comments,\nsuggested background color, etc... More details about the LodePNGInfo struct are\nat its declaration documentation.\n\nLodePNGColorMode info_raw\n-------------------------\n\nWhen decoding, here you can specify which color type you want\nthe resulting raw image to be. If this is different from the colortype of the\nPNG, then the decoder will automatically convert the result. This conversion\nalways works, except if you want it to convert a color PNG to grayscale or to\na palette with missing colors.\n\nBy default, 32-bit color is used for the result.\n\nLodePNGDecoderSettings decoder\n------------------------------\n\nThe settings can be used to ignore the errors created by invalid CRC and Adler32\nchunks, and to disable the decoding of tEXt chunks.\n\nThere's also a setting color_convert, true by default. If false, no conversion\nis done, the resulting data will be as it was in the PNG (after decompression)\nand you'll have to puzzle the colors of the pixels together yourself using the\ncolor type information in the LodePNGInfo.\n\n\n5. Encoding\n-----------\n\nEncoding converts a raw pixel buffer to a PNG compressed image.\n\nMost documentation on using the encoder is at its declarations in the header\nabove. For C, simple encoding can be done with functions such as\nlodepng_encode32, and more advanced decoding can be done with the struct\nLodePNGState and lodepng_encode. For C++, all encoding can be done with the\nvarious lodepng::encode functions, and lodepng::State can be used for advanced\nfeatures.\n\nLike the decoder, the encoder can also give errors. However it gives less errors\nsince the encoder input is trusted, the decoder input (a PNG image that could\nbe forged by anyone) is not trusted.\n\nWhen using the LodePNGState, it uses the following fields for encoding:\n*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be.\n*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has\n*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use\n\nLodePNGInfo info_png\n--------------------\n\nWhen encoding, you use this the opposite way as when decoding: for encoding,\nyou fill in the values you want the PNG to have before encoding. By default it's\nnot needed to specify a color type for the PNG since it's automatically chosen,\nbut it's possible to choose it yourself given the right settings.\n\nThe encoder will not always exactly match the LodePNGInfo struct you give,\nit tries as close as possible. Some things are ignored by the encoder. The\nencoder uses, for example, the following settings from it when applicable:\ncolortype and bitdepth, text chunks, time chunk, the color key, the palette, the\nbackground color, the interlace method, unknown chunks, ...\n\nWhen encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk.\nIf the palette contains any colors for which the alpha channel is not 255 (so\nthere are translucent colors in the palette), it'll add a tRNS chunk.\n\nLodePNGColorMode info_raw\n-------------------------\n\nYou specify the color type of the raw image that you give to the input here,\nincluding a possible transparent color key and palette you happen to be using in\nyour raw image data.\n\nBy default, 32-bit color is assumed, meaning your input has to be in RGBA\nformat with 4 bytes (unsigned chars) per pixel.\n\nLodePNGEncoderSettings encoder\n------------------------------\n\nThe following settings are supported (some are in sub-structs):\n*) auto_convert: when this option is enabled, the encoder will\nautomatically choose the smallest possible color mode (including color key) that\ncan encode the colors of all pixels without information loss.\n*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree,\n   2 = dynamic huffman tree (best compression). Should be 2 for proper\n   compression.\n*) use_lz77: whether or not to use LZ77 for compressed block types. Should be\n   true for proper compression.\n*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value\n   2048 by default, but can be set to 32768 for better, but slow, compression.\n*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE\n   chunk if force_palette is true. This can used as suggested palette to convert\n   to by viewers that don't support more than 256 colors (if those still exist)\n*) add_id: add text chunk \"Encoder: LodePNG <version>\" to the image.\n*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks.\n  zTXt chunks use zlib compression on the text. This gives a smaller result on\n  large texts but a larger result on small texts (such as a single program name).\n  It's all tEXt or all zTXt though, there's no separate setting per text yet.\n\n\n6. color conversions\n--------------------\n\nAn important thing to note about LodePNG, is that the color type of the PNG, and\nthe color type of the raw image, are completely independent. By default, when\nyou decode a PNG, you get the result as a raw image in the color type you want,\nno matter whether the PNG was encoded with a palette, grayscale or RGBA color.\nAnd if you encode an image, by default LodePNG will automatically choose the PNG\ncolor type that gives good compression based on the values of colors and amount\nof colors in the image. It can be configured to let you control it instead as\nwell, though.\n\nTo be able to do this, LodePNG does conversions from one color mode to another.\nIt can convert from almost any color type to any other color type, except the\nfollowing conversions: RGB to grayscale is not supported, and converting to a\npalette when the palette doesn't have a required color is not supported. This is\nnot supported on purpose: this is information loss which requires a color\nreduction algorithm that is beyond the scope of a PNG encoder (yes, RGB to gray\nis easy, but there are multiple ways if you want to give some channels more\nweight).\n\nBy default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB\ncolor, no matter what color type the PNG has. And by default when encoding,\nLodePNG automatically picks the best color model for the output PNG, and expects\nthe input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control\nthe color format of the images yourself, you can skip this chapter.\n\n6.1. PNG color types\n--------------------\n\nA PNG image can have many color types, ranging from 1-bit color to 64-bit color,\nas well as palettized color modes. After the zlib decompression and unfiltering\nin the PNG image is done, the raw pixel data will have that color type and thus\na certain amount of bits per pixel. If you want the output raw image after\ndecoding to have another color type, a conversion is done by LodePNG.\n\nThe PNG specification gives the following color types:\n\n0: grayscale, bit depths 1, 2, 4, 8, 16\n2: RGB, bit depths 8 and 16\n3: palette, bit depths 1, 2, 4 and 8\n4: grayscale with alpha, bit depths 8 and 16\n6: RGBA, bit depths 8 and 16\n\nBit depth is the amount of bits per pixel per color channel. So the total amount\nof bits per pixel is: amount of channels * bitdepth.\n\n6.2. color conversions\n----------------------\n\nAs explained in the sections about the encoder and decoder, you can specify\ncolor types and bit depths in info_png and info_raw to change the default\nbehaviour.\n\nIf, when decoding, you want the raw image to be something else than the default,\nyou need to set the color type and bit depth you want in the LodePNGColorMode,\nor the parameters colortype and bitdepth of the simple decoding function.\n\nIf, when encoding, you use another color type than the default in the raw input\nimage, you need to specify its color type and bit depth in the LodePNGColorMode\nof the raw image, or use the parameters colortype and bitdepth of the simple\nencoding function.\n\nIf, when encoding, you don't want LodePNG to choose the output PNG color type\nbut control it yourself, you need to set auto_convert in the encoder settings\nto false, and specify the color type you want in the LodePNGInfo of the\nencoder (including palette: it can generate a palette if auto_convert is true,\notherwise not).\n\nIf the input and output color type differ (whether user chosen or auto chosen),\nLodePNG will do a color conversion, which follows the rules below, and may\nsometimes result in an error.\n\nTo avoid some confusion:\n-the decoder converts from PNG to raw image\n-the encoder converts from raw image to PNG\n-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image\n-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG\n-when encoding, the color type in LodePNGInfo is ignored if auto_convert\n is enabled, it is automatically generated instead\n-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original\n PNG image, but it can be ignored since the raw image has the color type you requested instead\n-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion\n between the color types is done if the color types are supported. If it is not\n supported, an error is returned. If the types are the same, no conversion is done.\n-even though some conversions aren't supported, LodePNG supports loading PNGs from any\n colortype and saving PNGs to any colortype, sometimes it just requires preparing\n the raw image correctly before encoding.\n-both encoder and decoder use the same color converter.\n\nThe function lodepng_convert does the color conversion. It is available in the\ninterface but normally isn't needed since the encoder and decoder already call\nit.\n\nNon supported color conversions:\n-color to grayscale when non-gray pixels are present: no error is thrown, but\nthe result will look ugly because only the red channel is taken (it assumes all\nthree channels are the same in this case so ignores green and blue). The reason\nno error is given is to allow converting from three-channel grayscale images to\none-channel even if there are numerical imprecisions.\n-anything to palette when the palette does not have an exact match for a from-color\nin it: in this case an error is thrown\n\nSupported color conversions:\n-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA\n-any gray or gray+alpha, to gray or gray+alpha\n-anything to a palette, as long as the palette has the requested colors in it\n-removing alpha channel\n-higher to smaller bitdepth, and vice versa\n\nIf you want no color conversion to be done (e.g. for speed or control):\n-In the encoder, you can make it save a PNG with any color type by giving the\nraw color mode and LodePNGInfo the same color mode, and setting auto_convert to\nfalse.\n-In the decoder, you can make it store the pixel data in the same color type\nas the PNG has, by setting the color_convert setting to false. Settings in\ninfo_raw are then ignored.\n\n6.3. padding bits\n-----------------\n\nIn the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines\nhave a bit amount that isn't a multiple of 8, then padding bits are used so that each\nscanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output.\nThe raw input image you give to the encoder, and the raw output image you get from the decoder\nwill NOT have these padding bits, e.g. in the case of a 1-bit image with a width\nof 7 pixels, the first pixel of the second scanline will the 8th bit of the first byte,\nnot the first bit of a new byte.\n\n6.4. A note about 16-bits per channel and endianness\n----------------------------------------------------\n\nLodePNG uses unsigned char arrays for 16-bit per channel colors too, just like\nfor any other color format. The 16-bit values are stored in big endian (most\nsignificant byte first) in these arrays. This is the opposite order of the\nlittle endian used by x86 CPU's.\n\nLodePNG always uses big endian because the PNG file format does so internally.\nConversions to other formats than PNG uses internally are not supported by\nLodePNG on purpose, there are myriads of formats, including endianness of 16-bit\ncolors, the order in which you store R, G, B and A, and so on. Supporting and\nconverting to/from all that is outside the scope of LodePNG.\n\nThis may mean that, depending on your use case, you may want to convert the big\nendian output of LodePNG to little endian with a for loop. This is certainly not\nalways needed, many applications and libraries support big endian 16-bit colors\nanyway, but it means you cannot simply cast the unsigned char* buffer to an\nunsigned short* buffer on x86 CPUs.\n\n\n7. error values\n---------------\n\nAll functions in LodePNG that return an error code, return 0 if everything went\nOK, or a non-zero code if there was an error.\n\nThe meaning of the LodePNG error values can be retrieved with the function\nlodepng_error_text: given the numerical error code, it returns a description\nof the error in English as a string.\n\nCheck the implementation of lodepng_error_text to see the meaning of each code.\n\nIt is not recommended to use the numerical values to programmatically make\ndifferent decisions based on error types as the numbers are not guaranteed to\nstay backwards compatible. They are for human consumption only. Programmatically\nonly 0 or non-0 matter.\n\n\n8. chunks and PNG editing\n-------------------------\n\nIf you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG\neditor that should follow the rules about handling of unknown chunks, or if your\nprogram is able to read other types of chunks than the ones handled by LodePNG,\nthen that's possible with the chunk functions of LodePNG.\n\nA PNG chunk has the following layout:\n\n4 bytes length\n4 bytes type name\nlength bytes data\n4 bytes CRC\n\n8.1. iterating through chunks\n-----------------------------\n\nIf you have a buffer containing the PNG image data, then the first chunk (the\nIHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the\nsignature of the PNG and are not part of a chunk. But if you start at byte 8\nthen you have a chunk, and can check the following things of it.\n\nNOTE: none of these functions check for memory buffer boundaries. To avoid\nexploits, always make sure the buffer contains all the data of the chunks.\nWhen using lodepng_chunk_next, make sure the returned value is within the\nallocated memory.\n\nunsigned lodepng_chunk_length(const unsigned char* chunk):\n\nGet the length of the chunk's data. The total chunk length is this length + 12.\n\nvoid lodepng_chunk_type(char type[5], const unsigned char* chunk):\nunsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type):\n\nGet the type of the chunk or compare if it's a certain type\n\nunsigned char lodepng_chunk_critical(const unsigned char* chunk):\nunsigned char lodepng_chunk_private(const unsigned char* chunk):\nunsigned char lodepng_chunk_safetocopy(const unsigned char* chunk):\n\nCheck if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are).\nCheck if the chunk is private (public chunks are part of the standard, private ones not).\nCheck if the chunk is safe to copy. If it's not, then, when modifying data in a critical\nchunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your\nprogram doesn't handle that type of unknown chunk.\n\nunsigned char* lodepng_chunk_data(unsigned char* chunk):\nconst unsigned char* lodepng_chunk_data_const(const unsigned char* chunk):\n\nGet a pointer to the start of the data of the chunk.\n\nunsigned lodepng_chunk_check_crc(const unsigned char* chunk):\nvoid lodepng_chunk_generate_crc(unsigned char* chunk):\n\nCheck if the crc is correct or generate a correct one.\n\nunsigned char* lodepng_chunk_next(unsigned char* chunk):\nconst unsigned char* lodepng_chunk_next_const(const unsigned char* chunk):\n\nIterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these\nfunctions do no boundary checking of the allocated data whatsoever, so make sure there is enough\ndata available in the buffer to be able to go to the next chunk.\n\nunsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk):\nunsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length,\n                              const char* type, const unsigned char* data):\n\nThese functions are used to create new chunks that are appended to the data in *out that has\nlength *outsize. The append function appends an existing chunk to the new data. The create\nfunction creates a new chunk with the given parameters and appends it. Type is the 4-letter\nname of the chunk.\n\n8.2. chunks in info_png\n-----------------------\n\nThe LodePNGInfo struct contains fields with the unknown chunk in it. It has 3\nbuffers (each with size) to contain 3 types of unknown chunks:\nthe ones that come before the PLTE chunk, the ones that come between the PLTE\nand the IDAT chunks, and the ones that come after the IDAT chunks.\nIt's necessary to make the distinction between these 3 cases because the PNG\nstandard forces to keep the ordering of unknown chunks compared to the critical\nchunks, but does not force any other ordering rules.\n\ninfo_png.unknown_chunks_data[0] is the chunks before PLTE\ninfo_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT\ninfo_png.unknown_chunks_data[2] is the chunks after IDAT\n\nThe chunks in these 3 buffers can be iterated through and read by using the same\nway described in the previous subchapter.\n\nWhen using the decoder to decode a PNG, you can make it store all unknown chunks\nif you set the option settings.remember_unknown_chunks to 1. By default, this\noption is off (0).\n\nThe encoder will always encode unknown chunks that are stored in the info_png.\nIf you need it to add a particular chunk that isn't known by LodePNG, you can\nuse lodepng_chunk_append or lodepng_chunk_create to the chunk data in\ninfo_png.unknown_chunks_data[x].\n\nChunks that are known by LodePNG should not be added in that way. E.g. to make\nLodePNG add a bKGD chunk, set background_defined to true and add the correct\nparameters there instead.\n\n\n9. compiler support\n-------------------\n\nNo libraries other than the current standard C library are needed to compile\nLodePNG. For the C++ version, only the standard C++ library is needed on top.\nAdd the files lodepng.c(pp) and lodepng.h to your project, include\nlodepng.h where needed, and your program can read/write PNG files.\n\nIt is compatible with C90 and up, and C++03 and up.\n\nIf performance is important, use optimization when compiling! For both the\nencoder and decoder, this makes a large difference.\n\nMake sure that LodePNG is compiled with the same compiler of the same version\nand with the same settings as the rest of the program, or the interfaces with\nstd::vectors and std::strings in C++ can be incompatible.\n\nCHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets.\n\n*) gcc and g++\n\nLodePNG is developed in gcc so this compiler is natively supported. It gives no\nwarnings with compiler options \"-Wall -Wextra -pedantic -ansi\", with gcc and g++\nversion 4.7.1 on Linux, 32-bit and 64-bit.\n\n*) Clang\n\nFully supported and warning-free.\n\n*) Mingw\n\nThe Mingw compiler (a port of gcc for Windows) should be fully supported by\nLodePNG.\n\n*) Visual Studio and Visual C++ Express Edition\n\nLodePNG should be warning-free with warning level W4. Two warnings were disabled\nwith pragmas though: warning 4244 about implicit conversions, and warning 4996\nwhere it wants to use a non-standard function fopen_s instead of the standard C\nfopen.\n\nVisual Studio may want \"stdafx.h\" files to be included in each source file and\ngive an error \"unexpected end of file while looking for precompiled header\".\nThis is not standard C++ and will not be added to the stock LodePNG. You can\ndisable it for lodepng.cpp only by right clicking it, Properties, C/C++,\nPrecompiled Headers, and set it to Not Using Precompiled Headers there.\n\nNOTE: Modern versions of VS should be fully supported, but old versions, e.g.\nVS6, are not guaranteed to work.\n\n*) Compilers on Macintosh\n\nLodePNG has been reported to work both with gcc and LLVM for Macintosh, both for\nC and C++.\n\n*) Other Compilers\n\nIf you encounter problems on any compilers, feel free to let me know and I may\ntry to fix it if the compiler is modern and standards compliant.\n\n\n10. examples\n------------\n\nThis decoder example shows the most basic usage of LodePNG. More complex\nexamples can be found on the LodePNG website.\n\nNOTE: these examples do not support wide-character filenames, you can use an\nexternal method to handle such files and encode or decode in-memory\n\n10.1. decoder C++ example\n-------------------------\n\n#include \"lodepng.h\"\n#include <iostream>\n\nint main(int argc, char *argv[]) {\n  const char* filename = argc > 1 ? argv[1] : \"test.png\";\n\n  //load and decode\n  std::vector<unsigned char> image;\n  unsigned width, height;\n  unsigned error = lodepng::decode(image, width, height, filename);\n\n  //if there's an error, display it\n  if(error) std::cout << \"decoder error \" << error << \": \" << lodepng_error_text(error) << std::endl;\n\n  //the pixels are now in the vector \"image\", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...\n}\n\n10.2. decoder C example\n-----------------------\n\n#include \"lodepng.h\"\n\nint main(int argc, char *argv[]) {\n  unsigned error;\n  unsigned char* image;\n  size_t width, height;\n  const char* filename = argc > 1 ? argv[1] : \"test.png\";\n\n  error = lodepng_decode32_file(&image, &width, &height, filename);\n\n  if(error) printf(\"decoder error %u: %s\\n\", error, lodepng_error_text(error));\n\n  / * use image here * /\n\n  free(image);\n  return 0;\n}\n\n11. state settings reference\n----------------------------\n\nA quick reference of some settings to set on the LodePNGState\n\nFor decoding:\n\nstate.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums\nstate.decoder.zlibsettings.custom_...: use custom inflate function\nstate.decoder.ignore_crc: ignore CRC checksums\nstate.decoder.ignore_critical: ignore unknown critical chunks\nstate.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors\nstate.decoder.color_convert: convert internal PNG color to chosen one\nstate.decoder.read_text_chunks: whether to read in text metadata chunks\nstate.decoder.remember_unknown_chunks: whether to read in unknown chunks\nstate.info_raw.colortype: desired color type for decoded image\nstate.info_raw.bitdepth: desired bit depth for decoded image\nstate.info_raw....: more color settings, see struct LodePNGColorMode\nstate.info_png....: no settings for decoder but output, see struct LodePNGInfo\n\nFor encoding:\n\nstate.encoder.zlibsettings.btype: disable compression by setting it to 0\nstate.encoder.zlibsettings.use_lz77: use LZ77 in compression\nstate.encoder.zlibsettings.windowsize: tweak LZ77 windowsize\nstate.encoder.zlibsettings.minmatch: tweak min LZ77 length to match\nstate.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching\nstate.encoder.zlibsettings.lazymatching: try one more LZ77 matching\nstate.encoder.zlibsettings.custom_...: use custom deflate function\nstate.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png\nstate.encoder.filter_palette_zero: PNG filter strategy for palette\nstate.encoder.filter_strategy: PNG filter strategy to encode with\nstate.encoder.force_palette: add palette even if not encoding to one\nstate.encoder.add_id: add LodePNG identifier and version as a text chunk\nstate.encoder.text_compression: use compressed text chunks for metadata\nstate.info_raw.colortype: color type of raw input image you provide\nstate.info_raw.bitdepth: bit depth of raw input image you provide\nstate.info_raw: more color settings, see struct LodePNGColorMode\nstate.info_png.color.colortype: desired color type if auto_convert is false\nstate.info_png.color.bitdepth: desired bit depth if auto_convert is false\nstate.info_png.color....: more color settings, see struct LodePNGColorMode\nstate.info_png....: more PNG related settings, see struct LodePNGInfo\n\n\n12. changes\n-----------\n\nThe version number of LodePNG is the date of the change given in the format\nyyyymmdd.\n\nSome changes aren't backwards compatible. Those are indicated with a (!)\nsymbol.\n\nNot all changes are listed here, the commit history in github lists more:\nhttps://github.com/lvandeve/lodepng\n\n*) 09 jan 2022: minor decoder speed improvements.\n*) 27 jun 2021: added warnings that file reading/writing functions don't support\n   wide-character filenames (support for this is not planned, opening files is\n   not the core part of PNG decoding/decoding and is platform dependent).\n*) 17 okt 2020: prevent decoding too large text/icc chunks by default.\n*) 06 mar 2020: simplified some of the dynamic memory allocations.\n*) 12 jan 2020: (!) added 'end' argument to lodepng_chunk_next to allow correct\n   overflow checks.\n*) 14 aug 2019: around 25% faster decoding thanks to huffman lookup tables.\n*) 15 jun 2019: (!) auto_choose_color API changed (for bugfix: don't use palette\n   if gray ICC profile) and non-ICC LodePNGColorProfile renamed to\n   LodePNGColorStats.\n*) 30 dec 2018: code style changes only: removed newlines before opening braces.\n*) 10 sep 2018: added way to inspect metadata chunks without full decoding.\n*) 19 aug 2018: (!) fixed color mode bKGD is encoded with and made it use\n   palette index in case of palette.\n*) 10 aug 2018: (!) added support for gAMA, cHRM, sRGB and iCCP chunks. This\n   change is backwards compatible unless you relied on unknown_chunks for those.\n*) 11 jun 2018: less restrictive check for pixel size integer overflow\n*) 14 jan 2018: allow optionally ignoring a few more recoverable errors\n*) 17 sep 2017: fix memory leak for some encoder input error cases\n*) 27 nov 2016: grey+alpha auto color model detection bugfix\n*) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort).\n*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within\n   the limits of pure C90).\n*) 08 dec 2015: Made load_file function return error if file can't be opened.\n*) 24 okt 2015: Bugfix with decoding to palette output.\n*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding.\n*) 24 aug 2014: Moved to github\n*) 23 aug 2014: Reduced needless memory usage of decoder.\n*) 28 jun 2014: Removed fix_png setting, always support palette OOB for\n    simplicity. Made ColorProfile public.\n*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization.\n*) 22 dec 2013: Power of two windowsize required for optimization.\n*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key.\n*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png).\n*) 11 mar 2013: (!) Bugfix with custom free. Changed from \"my\" to \"lodepng_\"\n    prefix for the custom allocators and made it possible with a new #define to\n    use custom ones in your project without needing to change lodepng's code.\n*) 28 jan 2013: Bugfix with color key.\n*) 27 okt 2012: Tweaks in text chunk keyword length error handling.\n*) 8 okt 2012: (!) Added new filter strategy (entropy) and new auto color mode.\n    (no palette). Better deflate tree encoding. New compression tweak settings.\n    Faster color conversions while decoding. Some internal cleanups.\n*) 23 sep 2012: Reduced warnings in Visual Studio a little bit.\n*) 1 sep 2012: (!) Removed #define's for giving custom (de)compression functions\n    and made it work with function pointers instead.\n*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc\n    and free functions and toggle #defines from compiler flags. Small fixes.\n*) 6 may 2012: (!) Made plugging in custom zlib/deflate functions more flexible.\n*) 22 apr 2012: (!) Made interface more consistent, renaming a lot. Removed\n    redundant C++ codec classes. Reduced amount of structs. Everything changed,\n    but it is cleaner now imho and functionality remains the same. Also fixed\n    several bugs and shrunk the implementation code. Made new samples.\n*) 6 nov 2011: (!) By default, the encoder now automatically chooses the best\n    PNG color model and bit depth, based on the amount and type of colors of the\n    raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color.\n*) 9 okt 2011: simpler hash chain implementation for the encoder.\n*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching.\n*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking.\n    A bug with the PNG filtertype heuristic was fixed, so that it chooses much\n    better ones (it's quite significant). A setting to do an experimental, slow,\n    brute force search for PNG filter types is added.\n*) 17 aug 2011: (!) changed some C zlib related function names.\n*) 16 aug 2011: made the code less wide (max 120 characters per line).\n*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors.\n*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled.\n*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman\n    to optimize long sequences of zeros.\n*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and\n    LodePNG_InfoColor_canHaveAlpha functions for convenience.\n*) 7 nov 2010: added LodePNG_error_text function to get error code description.\n*) 30 okt 2010: made decoding slightly faster\n*) 26 okt 2010: (!) changed some C function and struct names (more consistent).\n     Reorganized the documentation and the declaration order in the header.\n*) 08 aug 2010: only changed some comments and external samples.\n*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version.\n*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers.\n*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could\n    read by ignoring the problem but windows apps couldn't.\n*) 06 jun 2008: added more error checks for out of memory cases.\n*) 26 apr 2008: added a few more checks here and there to ensure more safety.\n*) 06 mar 2008: crash with encoding of strings fixed\n*) 02 feb 2008: support for international text chunks added (iTXt)\n*) 23 jan 2008: small cleanups, and #defines to divide code in sections\n*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor.\n*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder.\n*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added\n    Also various fixes, such as in the deflate and the padding bits code.\n*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved\n    filtering code of encoder.\n*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A\n    C++ wrapper around this provides an interface almost identical to before.\n    Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code\n    are together in these files but it works both for C and C++ compilers.\n*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks\n*) 30 aug 2007: bug fixed which makes this Borland C++ compatible\n*) 09 aug 2007: some VS2005 warnings removed again\n*) 21 jul 2007: deflate code placed in new namespace separate from zlib code\n*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images\n*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing\n    invalid std::vector element [0] fixed, and level 3 and 4 warnings removed\n*) 02 jun 2007: made the encoder add a tag with version by default\n*) 27 may 2007: zlib and png code separated (but still in the same file),\n    simple encoder/decoder functions added for more simple usage cases\n*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69),\n    moved some examples from here to lodepng_examples.cpp\n*) 12 may 2007: palette decoding bug fixed\n*) 24 apr 2007: changed the license from BSD to the zlib license\n*) 11 mar 2007: very simple addition: ability to encode bKGD chunks.\n*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding\n    palettized PNG images. Plus little interface change with palette and texts.\n*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes.\n    Fixed a bug where the end code of a block had length 0 in the Huffman tree.\n*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented\n    and supported by the encoder, resulting in smaller PNGs at the output.\n*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone.\n*) 24 jan 2007: gave encoder an error interface. Added color conversion from any\n    greyscale type to 8-bit greyscale with or without alpha.\n*) 21 jan 2007: (!) Totally changed the interface. It allows more color types\n    to convert to and is more uniform. See the manual for how it works now.\n*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days:\n    encode/decode custom tEXt chunks, separate classes for zlib & deflate, and\n    at last made the decoder give errors for incorrect Adler32 or Crc.\n*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel.\n*) 29 dec 2006: Added support for encoding images without alpha channel, and\n    cleaned out code as well as making certain parts faster.\n*) 28 dec 2006: Added \"Settings\" to the encoder.\n*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now.\n    Removed some code duplication in the decoder. Fixed little bug in an example.\n*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter.\n    Fixed a bug of the decoder with 16-bit per color.\n*) 15 okt 2006: Changed documentation structure\n*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the\n    given image buffer, however for now it's not compressed.\n*) 08 sep 2006: (!) Changed to interface with a Decoder class\n*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different\n    way. Renamed decodePNG to decodePNGGeneric.\n*) 29 jul 2006: (!) Changed the interface: image info is now returned as a\n    struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy.\n*) 28 jul 2006: Cleaned the code and added new error checks.\n    Corrected terminology \"deflate\" into \"inflate\".\n*) 23 jun 2006: Added SDL example in the documentation in the header, this\n    example allows easy debugging by displaying the PNG and its transparency.\n*) 22 jun 2006: (!) Changed way to obtain error value. Added\n    loadFile function for convenience. Made decodePNG32 faster.\n*) 21 jun 2006: (!) Changed type of info vector to unsigned.\n    Changed position of palette in info vector. Fixed an important bug that\n    happened on PNGs with an uncompressed block.\n*) 16 jun 2006: Internally changed unsigned into unsigned where\n    needed, and performed some optimizations.\n*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them\n    in LodePNG namespace. Changed the order of the parameters. Rewrote the\n    documentation in the header. Renamed files to lodepng.cpp and lodepng.h\n*) 22 apr 2006: Optimized and improved some code\n*) 07 sep 2005: (!) Changed to std::vector interface\n*) 12 aug 2005: Initial release (C++, decoder only)\n\n\n13. contact information\n-----------------------\n\nFeel free to contact me with suggestions, problems, comments, ... concerning\nLodePNG. If you encounter a PNG image that doesn't work properly with this\ndecoder, feel free to send it and I'll use it to find and fix the problem.\n\nMy email address is (puzzle the account and domain together with an @ symbol):\nDomain: gmail dot com.\nAccount: lode dot vandevenne.\n\n\nCopyright (c) 2005-2022 Lode Vandevenne\n*/\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_7/lodepng/lodepng.cpp",
    "content": "#include \"lodepng.h\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_7/src/user_objects.cc",
    "content": "#include \"user_objects.h\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_8/Package.swift",
    "content": "// swift-tools-version:5.8.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"CXX17WithFModules\",\n    targets: [\n        .target(\n            name: \"lodepng\",\n            path: \"lodepng\",\n            sources: [\"lodepng.cpp\"],\n            publicHeadersPath: \"include\"),\n        .target(name: \"CXX17WithFModules\", dependencies: [\"lodepng\"], path: \"./\", sources: [\"src/user_objects.cc\"], publicHeadersPath: \"include\"),\n    ],\n    cxxLanguageStandard: .cxx17\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_8/include/user_objects.h",
    "content": "// Copyright 2021 DeepMind Technologies Limited\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#ifndef MUJOCO_SRC_USER_USER_OBJECTS_H_\n#define MUJOCO_SRC_USER_USER_OBJECTS_H_\n\n#include <string>\n#include <vector>\n\n#include \"lodepng.h\"\n\n// forward declarations of all mjC/X classes\nclass mjCError;\nclass mjCAlternative;\nclass mjCBase;\nclass mjCBody;\nclass mjCJoint;\nclass mjCGeom;\nclass mjCSite;\nclass mjCCamera;\nclass mjCLight;\nclass mjCMesh;\nclass mjCSkin;\nclass mjCTexture;\nclass mjCMaterial;\nclass mjCPair;\nclass mjCBodyPair;\nclass mjCEquality;\nclass mjCTendon;\nclass mjCWrap;\nclass mjCActuator;\nclass mjCSensor;\nclass mjCNumeric;\nclass mjCText;\nclass mjCTuple;\nclass mjCDef;\nclass mjCMesh;                      // defined in user_mesh\nclass mjCModel;                     // defined in user_model\nclass mjXWriter;                    // defined in xml_native\nclass mjXURDF;                      // defined in xml_urdf\n\n\n//------------------------- helper classes and constants -------------------------------------------\n\n\n// builtin type for procedural textures\ntypedef enum _mjtBuiltin {\n  mjBUILTIN_NONE = 0,             // no builtin\n  mjBUILTIN_GRADIENT,             // circular gradient: rgb1->rgb2->rgb3\n  mjBUILTIN_CHECKER,              // checker pattern: rgb1, rgb2\n  mjBUILTIN_FLAT                  // 2d: rgb1; cube: rgb1-up, rgb2-side, rgb3-down\n} mjtBuiltin;\n\n\n// mark type for procedural textures\ntypedef enum _mjtMark {\n  mjMARK_NONE = 0,                // no mark\n  mjMARK_EDGE,                    // paint edges\n  mjMARK_CROSS,                   // paint cross\n  mjMARK_RANDOM                   // paint random dots\n} mjtMark;\n\n\n// error information\nclass mjCError {\n public:\n  mjCError(const mjCBase* obj = 0,\n           const char* msg = 0,\n           const char* str = 0,\n           int pos1 = 0,\n           int pos2 = 0);\n\n  char message[500];              // error message\n  bool warning;                   // is this a warning instead of error\n};\n\n\n// alternative specifications of frame orientation\nclass mjCAlternative {\n public:\n  mjCAlternative();                               // constructor\n  const char* Set(double* quat, double* inertia,  // set frame quat and diag. inertia\n                  bool degree,                    //  angle format: degree/radian\n                  const char* sequence);          //  euler sequence format: \"xyz\"\n\n  double axisangle[4];            // rotation axis and angle\n  double xyaxes[6];               // x and y axes\n  double zaxis[3];                // z axis (use minimal rotation)\n  double euler[3];                // euler rotations\n  double fullinertia[6];          // non-axis-aligned inertia matrix\n};\n\n\n\n//------------------------- class mjCBase ----------------------------------------------------------\n// Generic functionality for all derived classes\n\nclass mjCBase {\n  friend class mjCDef;\n\n public:\n  std::string name;               // object name\n  std::string classname;          // defaults class name\n  int id;                         // object id\n  int xmlpos[2];                  // row and column in xml file\n  mjCDef* def;                    // defaults class used to init this object\n\n protected:\n  mjCBase();                      // constructor\n  mjCModel* model;                // pointer to model that created object\n};\n\n\n\n//------------------------- class mjCBody -----------------------------------------------\n// Describes a rigid body\n\nclass mjCBody : public mjCBase {\n  friend class mjCJoint;\n  friend class mjCGeom;\n  friend class mjCSite;\n  friend class mjCCamera;\n  friend class mjCLight;\n  friend class mjCEquality;\n  friend class mjCPair;\n  friend class mjCModel;\n  friend class mjXReader;\n  friend class mjXWriter;\n  friend class mjXURDF;\n\n public:\n  // API for adding objects to body\n  mjCBody*    AddBody(mjCDef* = 0);\n  mjCJoint*   AddJoint(mjCDef* = 0, bool isfree = false);\n  mjCGeom*    AddGeom(mjCDef* = 0);\n  mjCSite*    AddSite(mjCDef* = 0);\n  mjCCamera*  AddCamera(mjCDef* = 0);\n  mjCLight*   AddLight(mjCDef* = 0);\n\n\n  // setup child local frame, take into account change\n  void MakeLocal(double* locpos, double* locquat, const double* pos, const double* quat);\n\n  // set explicit_inertial to true\n  void MakeInertialExplicit();\n\n  // variables set by user or 'Compile'\n  bool mocap;                     // is this a mocap body\n  double pos[3];                  // frame position\n  double quat[4];                 // frame orientation\n  double ipos[3];                 // inertial frame position\n  double iquat[4];                // inertial frame orientation\n  double mass;                    // mass\n  double inertia[3];              // diagonal inertia (in i-frame)\n  std::vector<double> userdata;   // user data\n  mjCAlternative alt;             // alternative orientation specification\n  mjCAlternative ialt;            // alternative for inertial frame\n\n  // variables computed by 'Compile' and 'AddXXX'\n private:\n  mjCBody(mjCModel*);                 // constructor\n  ~mjCBody();                         // destructor\n  void Compile(void);                 // compiler\n\n  void GeomFrame(void);               // get inertial info from geoms\n\n  double locpos[3];               // position relative to parent\n  double locquat[4];              // orientation relative to parent\n  double locipos[3];              // inertial position frame, rel. to local frame\n  double lociquat[4];             // inertial frame orientation\n  int parentid;                   // parent index in global array\n  int weldid;                     // top index of body we are welded to\n  int dofnum;                     // number of motion dofs for body\n  int mocapid;                    // mocap id, -1: not mocap\n  bool explicit_inertial;         // whether to save the body with an explicit inertial clause\n\n  int lastdof;                    // id of last dof (used by compiler)\n\n  // objects allocated by Add functions\n  std::vector<mjCBody*>    bodies;     // child bodies\n  std::vector<mjCGeom*>    geoms;      // geoms attached to this body\n  std::vector<mjCJoint*>   joints;     // joints allowing motion relative to parent\n  std::vector<mjCSite*>    sites;      // sites attached to this body\n  std::vector<mjCCamera*>  cameras;    // cameras attached to this body\n  std::vector<mjCLight*>   lights;     // lights attached to this body\n};\n\n#endif  // MUJOCO_SRC_USER_USER_OBJECTS_H_\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_8/lodepng/include/lodepng.h",
    "content": "/*\nLodePNG version 20220109\n\nCopyright (c) 2005-2022 Lode Vandevenne\n\nThis software is provided 'as-is', without any express or implied\nwarranty. In no event will the authors be held liable for any damages\narising from the use of this software.\n\nPermission is granted to anyone to use this software for any purpose,\nincluding commercial applications, and to alter it and redistribute it\nfreely, subject to the following restrictions:\n\n    1. The origin of this software must not be misrepresented; you must not\n    claim that you wrote the original software. If you use this software\n    in a product, an acknowledgment in the product documentation would be\n    appreciated but is not required.\n\n    2. Altered source versions must be plainly marked as such, and must not be\n    misrepresented as being the original software.\n\n    3. This notice may not be removed or altered from any source\n    distribution.\n*/\n\n#ifndef LODEPNG_H\n#define LODEPNG_H\n\n#include <string.h> /*for size_t*/\n\nextern const char* LODEPNG_VERSION_STRING;\n\n/*\nThe following #defines are used to create code sections. They can be disabled\nto disable code sections, which can give faster compile time and smaller binary.\nThe \"NO_COMPILE\" defines are designed to be used to pass as defines to the\ncompiler command to disable them without modifying this header, e.g.\n-DLODEPNG_NO_COMPILE_ZLIB for gcc.\nIn addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to\nallow implementing a custom lodepng_crc32.\n*/\n/*deflate & zlib. If disabled, you must specify alternative zlib functions in\nthe custom_zlib field of the compress and decompress settings*/\n#ifndef LODEPNG_NO_COMPILE_ZLIB\n#define LODEPNG_COMPILE_ZLIB\n#endif\n\n/*png encoder and png decoder*/\n#ifndef LODEPNG_NO_COMPILE_PNG\n#define LODEPNG_COMPILE_PNG\n#endif\n\n/*deflate&zlib decoder and png decoder*/\n#ifndef LODEPNG_NO_COMPILE_DECODER\n#define LODEPNG_COMPILE_DECODER\n#endif\n\n/*deflate&zlib encoder and png encoder*/\n#ifndef LODEPNG_NO_COMPILE_ENCODER\n#define LODEPNG_COMPILE_ENCODER\n#endif\n\n/*the optional built in harddisk file loading and saving functions*/\n#ifndef LODEPNG_NO_COMPILE_DISK\n#define LODEPNG_COMPILE_DISK\n#endif\n\n/*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/\n#ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS\n#define LODEPNG_COMPILE_ANCILLARY_CHUNKS\n#endif\n\n/*ability to convert error numerical codes to English text string*/\n#ifndef LODEPNG_NO_COMPILE_ERROR_TEXT\n#define LODEPNG_COMPILE_ERROR_TEXT\n#endif\n\n/*Compile the default allocators (C's free, malloc and realloc). If you disable this,\nyou can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your\nsource files with custom allocators.*/\n#ifndef LODEPNG_NO_COMPILE_ALLOCATORS\n#define LODEPNG_COMPILE_ALLOCATORS\n#endif\n\n/*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/\n#ifdef __cplusplus\n#ifndef LODEPNG_NO_COMPILE_CPP\n#define LODEPNG_COMPILE_CPP\n#endif\n#endif\n\n#ifdef LODEPNG_COMPILE_CPP\n#include <vector>\n#include <string>\n#endif /*LODEPNG_COMPILE_CPP*/\n\n#ifdef LODEPNG_COMPILE_PNG\n/*The PNG color types (also used for raw image).*/\ntypedef enum LodePNGColorType {\n  LCT_GREY = 0, /*grayscale: 1,2,4,8,16 bit*/\n  LCT_RGB = 2, /*RGB: 8,16 bit*/\n  LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/\n  LCT_GREY_ALPHA = 4, /*grayscale with alpha: 8,16 bit*/\n  LCT_RGBA = 6, /*RGB with alpha: 8,16 bit*/\n  /*LCT_MAX_OCTET_VALUE lets the compiler allow this enum to represent any invalid\n  byte value from 0 to 255 that could be present in an invalid PNG file header. Do\n  not use, compare with or set the name LCT_MAX_OCTET_VALUE, instead either use\n  the valid color type names above, or numeric values like 1 or 7 when checking for\n  particular disallowed color type byte values, or cast to integer to print it.*/\n  LCT_MAX_OCTET_VALUE = 255\n} LodePNGColorType;\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*\nConverts PNG data in memory to raw pixel data.\nout: Output parameter. Pointer to buffer that will contain the raw pixel data.\n     After decoding, its size is w * h * (bytes per pixel) bytes larger than\n     initially. Bytes per pixel depends on colortype and bitdepth.\n     Must be freed after usage with free(*out).\n     Note: for 16-bit per channel colors, uses big endian format like PNG does.\nw: Output parameter. Pointer to width of pixel data.\nh: Output parameter. Pointer to height of pixel data.\nin: Memory buffer with the PNG file.\ninsize: size of the in buffer.\ncolortype: the desired color type for the raw output image. See explanation on PNG color types.\nbitdepth: the desired bit depth for the raw output image. See explanation on PNG color types.\nReturn value: LodePNG error code (0 means no error).\n*/\nunsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h,\n                               const unsigned char* in, size_t insize,\n                               LodePNGColorType colortype, unsigned bitdepth);\n\n/*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/\nunsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h,\n                          const unsigned char* in, size_t insize);\n\n/*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/\nunsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h,\n                          const unsigned char* in, size_t insize);\n\n#ifdef LODEPNG_COMPILE_DISK\n/*\nLoad PNG from disk, from file with given name.\nSame as the other decode functions, but instead takes a filename as input.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.*/\nunsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h,\n                             const char* filename,\n                             LodePNGColorType colortype, unsigned bitdepth);\n\n/*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.*/\nunsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h,\n                               const char* filename);\n\n/*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.*/\nunsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h,\n                               const char* filename);\n#endif /*LODEPNG_COMPILE_DISK*/\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*\nConverts raw pixel data into a PNG image in memory. The colortype and bitdepth\n  of the output PNG image cannot be chosen, they are automatically determined\n  by the colortype, bitdepth and content of the input pixel data.\n  Note: for 16-bit per channel colors, needs big endian format like PNG does.\nout: Output parameter. Pointer to buffer that will contain the PNG image data.\n     Must be freed after usage with free(*out).\noutsize: Output parameter. Pointer to the size in bytes of the out buffer.\nimage: The raw pixel data to encode. The size of this buffer should be\n       w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth.\nw: width of the raw pixel data in pixels.\nh: height of the raw pixel data in pixels.\ncolortype: the color type of the raw input image. See explanation on PNG color types.\nbitdepth: the bit depth of the raw input image. See explanation on PNG color types.\nReturn value: LodePNG error code (0 means no error).\n*/\nunsigned lodepng_encode_memory(unsigned char** out, size_t* outsize,\n                               const unsigned char* image, unsigned w, unsigned h,\n                               LodePNGColorType colortype, unsigned bitdepth);\n\n/*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/\nunsigned lodepng_encode32(unsigned char** out, size_t* outsize,\n                          const unsigned char* image, unsigned w, unsigned h);\n\n/*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/\nunsigned lodepng_encode24(unsigned char** out, size_t* outsize,\n                          const unsigned char* image, unsigned w, unsigned h);\n\n#ifdef LODEPNG_COMPILE_DISK\n/*\nConverts raw pixel data into a PNG file on disk.\nSame as the other encode functions, but instead takes a filename as output.\n\nNOTE: This overwrites existing files without warning!\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory.*/\nunsigned lodepng_encode_file(const char* filename,\n                             const unsigned char* image, unsigned w, unsigned h,\n                             LodePNGColorType colortype, unsigned bitdepth);\n\n/*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory.*/\nunsigned lodepng_encode32_file(const char* filename,\n                               const unsigned char* image, unsigned w, unsigned h);\n\n/*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory.*/\nunsigned lodepng_encode24_file(const char* filename,\n                               const unsigned char* image, unsigned w, unsigned h);\n#endif /*LODEPNG_COMPILE_DISK*/\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n\n#ifdef LODEPNG_COMPILE_CPP\nnamespace lodepng {\n#ifdef LODEPNG_COMPILE_DECODER\n/*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype\nis the format to output the pixels to. Default is RGBA 8-bit per channel.*/\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                const unsigned char* in, size_t insize,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                const std::vector<unsigned char>& in,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\n#ifdef LODEPNG_COMPILE_DISK\n/*\nConverts PNG file from disk to raw pixel data in memory.\nSame as the other decode functions, but instead takes a filename as input.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.\n*/\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                const std::string& filename,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\n#endif /* LODEPNG_COMPILE_DISK */\n#endif /* LODEPNG_COMPILE_DECODER */\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*Same as lodepng_encode_memory, but encodes to an std::vector. colortype\nis that of the raw input data. The output PNG color type will be auto chosen.*/\nunsigned encode(std::vector<unsigned char>& out,\n                const unsigned char* in, unsigned w, unsigned h,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\nunsigned encode(std::vector<unsigned char>& out,\n                const std::vector<unsigned char>& in, unsigned w, unsigned h,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\n#ifdef LODEPNG_COMPILE_DISK\n/*\nConverts 32-bit RGBA raw pixel data into a PNG file on disk.\nSame as the other encode functions, but instead takes a filename as output.\n\nNOTE: This overwrites existing files without warning!\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.\n*/\nunsigned encode(const std::string& filename,\n                const unsigned char* in, unsigned w, unsigned h,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\nunsigned encode(const std::string& filename,\n                const std::vector<unsigned char>& in, unsigned w, unsigned h,\n                LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8);\n#endif /* LODEPNG_COMPILE_DISK */\n#endif /* LODEPNG_COMPILE_ENCODER */\n} /* namespace lodepng */\n#endif /*LODEPNG_COMPILE_CPP*/\n#endif /*LODEPNG_COMPILE_PNG*/\n\n#ifdef LODEPNG_COMPILE_ERROR_TEXT\n/*Returns an English description of the numerical error code.*/\nconst char* lodepng_error_text(unsigned code);\n#endif /*LODEPNG_COMPILE_ERROR_TEXT*/\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*Settings for zlib decompression*/\ntypedef struct LodePNGDecompressSettings LodePNGDecompressSettings;\nstruct LodePNGDecompressSettings {\n  /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */\n  unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/\n  unsigned ignore_nlen; /*ignore complement of len checksum in uncompressed blocks*/\n\n  /*Maximum decompressed size, beyond this the decoder may (and is encouraged to) stop decoding,\n  return an error, output a data size > max_output_size and all the data up to that point. This is\n  not hard limit nor a guarantee, but can prevent excessive memory usage. This setting is\n  ignored by the PNG decoder, but is used by the deflate/zlib decoder and can be used by custom ones.\n  Set to 0 to impose no limit (the default).*/\n  size_t max_output_size;\n\n  /*use custom zlib decoder instead of built in one (default: null).\n  Should return 0 if success, any non-0 if error (numeric value not exposed).*/\n  unsigned (*custom_zlib)(unsigned char**, size_t*,\n                          const unsigned char*, size_t,\n                          const LodePNGDecompressSettings*);\n  /*use custom deflate decoder instead of built in one (default: null)\n  if custom_zlib is not null, custom_inflate is ignored (the zlib format uses deflate).\n  Should return 0 if success, any non-0 if error (numeric value not exposed).*/\n  unsigned (*custom_inflate)(unsigned char**, size_t*,\n                             const unsigned char*, size_t,\n                             const LodePNGDecompressSettings*);\n\n  const void* custom_context; /*optional custom settings for custom functions*/\n};\n\nextern const LodePNGDecompressSettings lodepng_default_decompress_settings;\nvoid lodepng_decompress_settings_init(LodePNGDecompressSettings* settings);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*\nSettings for zlib compression. Tweaking these settings tweaks the balance\nbetween speed and compression ratio.\n*/\ntypedef struct LodePNGCompressSettings LodePNGCompressSettings;\nstruct LodePNGCompressSettings /*deflate = compress*/ {\n  /*LZ77 related settings*/\n  unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/\n  unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/\n  unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/\n  unsigned minmatch; /*minimum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/\n  unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/\n  unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/\n\n  /*use custom zlib encoder instead of built in one (default: null)*/\n  unsigned (*custom_zlib)(unsigned char**, size_t*,\n                          const unsigned char*, size_t,\n                          const LodePNGCompressSettings*);\n  /*use custom deflate encoder instead of built in one (default: null)\n  if custom_zlib is used, custom_deflate is ignored since only the built in\n  zlib function will call custom_deflate*/\n  unsigned (*custom_deflate)(unsigned char**, size_t*,\n                             const unsigned char*, size_t,\n                             const LodePNGCompressSettings*);\n\n  const void* custom_context; /*optional custom settings for custom functions*/\n};\n\nextern const LodePNGCompressSettings lodepng_default_compress_settings;\nvoid lodepng_compress_settings_init(LodePNGCompressSettings* settings);\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n#ifdef LODEPNG_COMPILE_PNG\n/*\nColor mode of an image. Contains all information required to decode the pixel\nbits to RGBA colors. This information is the same as used in the PNG file\nformat, and is used both for PNG and raw image data in LodePNG.\n*/\ntypedef struct LodePNGColorMode {\n  /*header (IHDR)*/\n  LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/\n  unsigned bitdepth;  /*bits per sample, see PNG standard or documentation further in this header file*/\n\n  /*\n  palette (PLTE and tRNS)\n\n  Dynamically allocated with the colors of the palette, including alpha.\n  This field may not be allocated directly, use lodepng_color_mode_init first,\n  then lodepng_palette_add per color to correctly initialize it (to ensure size\n  of exactly 1024 bytes).\n\n  The alpha channels must be set as well, set them to 255 for opaque images.\n\n  When decoding, by default you can ignore this palette, since LodePNG already\n  fills the palette colors in the pixels of the raw RGBA output.\n\n  The palette is only supported for color type 3.\n  */\n  unsigned char* palette; /*palette in RGBARGBA... order. Must be either 0, or when allocated must have 1024 bytes*/\n  size_t palettesize; /*palette size in number of colors (amount of used bytes is 4 * palettesize)*/\n\n  /*\n  transparent color key (tRNS)\n\n  This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit.\n  For grayscale PNGs, r, g and b will all 3 be set to the same.\n\n  When decoding, by default you can ignore this information, since LodePNG sets\n  pixels with this key to transparent already in the raw RGBA output.\n\n  The color key is only supported for color types 0 and 2.\n  */\n  unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/\n  unsigned key_r;       /*red/grayscale component of color key*/\n  unsigned key_g;       /*green component of color key*/\n  unsigned key_b;       /*blue component of color key*/\n} LodePNGColorMode;\n\n/*init, cleanup and copy functions to use with this struct*/\nvoid lodepng_color_mode_init(LodePNGColorMode* info);\nvoid lodepng_color_mode_cleanup(LodePNGColorMode* info);\n/*return value is error code (0 means no error)*/\nunsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source);\n/* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */\nLodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth);\n\nvoid lodepng_palette_clear(LodePNGColorMode* info);\n/*add 1 color to the palette*/\nunsigned lodepng_palette_add(LodePNGColorMode* info,\n                             unsigned char r, unsigned char g, unsigned char b, unsigned char a);\n\n/*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/\nunsigned lodepng_get_bpp(const LodePNGColorMode* info);\n/*get the amount of color channels used, based on colortype in the struct.\nIf a palette is used, it counts as 1 channel.*/\nunsigned lodepng_get_channels(const LodePNGColorMode* info);\n/*is it a grayscale type? (only colortype 0 or 4)*/\nunsigned lodepng_is_greyscale_type(const LodePNGColorMode* info);\n/*has it got an alpha channel? (only colortype 2 or 6)*/\nunsigned lodepng_is_alpha_type(const LodePNGColorMode* info);\n/*has it got a palette? (only colortype 3)*/\nunsigned lodepng_is_palette_type(const LodePNGColorMode* info);\n/*only returns true if there is a palette and there is a value in the palette with alpha < 255.\nLoops through the palette to check this.*/\nunsigned lodepng_has_palette_alpha(const LodePNGColorMode* info);\n/*\nCheck if the given color info indicates the possibility of having non-opaque pixels in the PNG image.\nReturns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels).\nReturns false if the image can only have opaque pixels.\nIn detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values,\nor if \"key_defined\" is true.\n*/\nunsigned lodepng_can_have_alpha(const LodePNGColorMode* info);\n/*Returns the byte size of a raw image buffer with given width, height and color mode*/\nsize_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color);\n\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\n/*The information of a Time chunk in PNG.*/\ntypedef struct LodePNGTime {\n  unsigned year;    /*2 bytes used (0-65535)*/\n  unsigned month;   /*1-12*/\n  unsigned day;     /*1-31*/\n  unsigned hour;    /*0-23*/\n  unsigned minute;  /*0-59*/\n  unsigned second;  /*0-60 (to allow for leap seconds)*/\n} LodePNGTime;\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n\n/*Information about the PNG image, except pixels, width and height.*/\ntypedef struct LodePNGInfo {\n  /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/\n  unsigned compression_method;/*compression method of the original file. Always 0.*/\n  unsigned filter_method;     /*filter method of the original file*/\n  unsigned interlace_method;  /*interlace method of the original file: 0=none, 1=Adam7*/\n  LodePNGColorMode color;     /*color type and bits, palette and transparency of the PNG file*/\n\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\n  /*\n  Suggested background color chunk (bKGD)\n\n  This uses the same color mode and bit depth as the PNG (except no alpha channel),\n  with values truncated to the bit depth in the unsigned integer.\n\n  For grayscale and palette PNGs, the value is stored in background_r. The values\n  in background_g and background_b are then unused.\n\n  So when decoding, you may get these in a different color mode than the one you requested\n  for the raw pixels.\n\n  When encoding with auto_convert, you must use the color model defined in info_png.color for\n  these values. The encoder normally ignores info_png.color when auto_convert is on, but will\n  use it to interpret these values (and convert copies of them to its chosen color model).\n\n  When encoding, avoid setting this to an expensive color, such as a non-gray value\n  when the image is gray, or the compression will be worse since it will be forced to\n  write the PNG with a more expensive color mode (when auto_convert is on).\n\n  The decoder does not use this background color to edit the color of pixels. This is a\n  completely optional metadata feature.\n  */\n  unsigned background_defined; /*is a suggested background color given?*/\n  unsigned background_r;       /*red/gray/palette component of suggested background color*/\n  unsigned background_g;       /*green component of suggested background color*/\n  unsigned background_b;       /*blue component of suggested background color*/\n\n  /*\n  Non-international text chunks (tEXt and zTXt)\n\n  The char** arrays each contain num strings. The actual messages are in\n  text_strings, while text_keys are keywords that give a short description what\n  the actual text represents, e.g. Title, Author, Description, or anything else.\n\n  All the string fields below including strings, keys, names and language tags are null terminated.\n  The PNG specification uses null characters for the keys, names and tags, and forbids null\n  characters to appear in the main text which is why we can use null termination everywhere here.\n\n  A keyword is minimum 1 character and maximum 79 characters long (plus the\n  additional null terminator). It's discouraged to use a single line length\n  longer than 79 characters for texts.\n\n  Don't allocate these text buffers yourself. Use the init/cleanup functions\n  correctly and use lodepng_add_text and lodepng_clear_text.\n\n  Standard text chunk keywords and strings are encoded using Latin-1.\n  */\n  size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/\n  char** text_keys; /*the keyword of a text chunk (e.g. \"Comment\")*/\n  char** text_strings; /*the actual text*/\n\n  /*\n  International text chunks (iTXt)\n  Similar to the non-international text chunks, but with additional strings\n  \"langtags\" and \"transkeys\", and the following text encodings are used:\n  keys: Latin-1, langtags: ASCII, transkeys and strings: UTF-8.\n  keys must be 1-79 characters (plus the additional null terminator), the other\n  strings are any length.\n  */\n  size_t itext_num; /*the amount of international texts in this PNG*/\n  char** itext_keys; /*the English keyword of the text chunk (e.g. \"Comment\")*/\n  char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/\n  char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/\n  char** itext_strings; /*the actual international text - UTF-8 string*/\n\n  /*time chunk (tIME)*/\n  unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/\n  LodePNGTime time;\n\n  /*phys chunk (pHYs)*/\n  unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/\n  unsigned phys_x; /*pixels per unit in x direction*/\n  unsigned phys_y; /*pixels per unit in y direction*/\n  unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/\n\n  /*\n  Color profile related chunks: gAMA, cHRM, sRGB, iCPP\n\n  LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color\n  profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please\n  use these values with a color management library.\n\n  See the PNG, ICC and sRGB specifications for more information about the meaning of these values.\n  */\n\n  /* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */\n  unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */\n  unsigned gama_gamma;   /* Gamma exponent times 100000 */\n\n  /* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */\n  unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */\n  unsigned chrm_white_x; /* White Point x times 100000 */\n  unsigned chrm_white_y; /* White Point y times 100000 */\n  unsigned chrm_red_x;   /* Red x times 100000 */\n  unsigned chrm_red_y;   /* Red y times 100000 */\n  unsigned chrm_green_x; /* Green x times 100000 */\n  unsigned chrm_green_y; /* Green y times 100000 */\n  unsigned chrm_blue_x;  /* Blue x times 100000 */\n  unsigned chrm_blue_y;  /* Blue y times 100000 */\n\n  /*\n  sRGB chunk: optional. May not appear at the same time as iCCP.\n  If gAMA is also present gAMA must contain value 45455.\n  If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000.\n  */\n  unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */\n  unsigned srgb_intent;  /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */\n\n  /*\n  iCCP chunk: optional. May not appear at the same time as sRGB.\n\n  LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a\n  separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color\n  management and conversions.\n\n  For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC\n  profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and\n  enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile.\n\n  For encoding, the ICC profile is required by the PNG specification to be an \"RGB\" profile for non-gray\n  PNG color types and a \"GRAY\" profile for gray PNG color types. If you disable auto_convert, you must ensure\n  the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is\n  enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder\n  error if the pixel data has non-gray pixels for a GRAY profile, or a silent less-optimal compression of the pixel\n  data if the pixels could be encoded as grayscale but the ICC profile is RGB.\n\n  To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so\n  make sure you compute it carefully to avoid the above problems.\n  */\n  unsigned iccp_defined;      /* Whether an iCCP chunk is present (0 = not present, 1 = present). */\n  char* iccp_name;            /* Null terminated string with profile name, 1-79 bytes */\n  /*\n  The ICC profile in iccp_profile_size bytes.\n  Don't allocate this buffer yourself. Use the init/cleanup functions\n  correctly and use lodepng_set_icc and lodepng_clear_icc.\n  */\n  unsigned char* iccp_profile;\n  unsigned iccp_profile_size; /* The size of iccp_profile in bytes */\n\n  /* End of color profile related chunks */\n\n\n  /*\n  unknown chunks: chunks not known by LodePNG, passed on byte for byte.\n\n  There are 3 buffers, one for each position in the PNG where unknown chunks can appear.\n  Each buffer contains all unknown chunks for that position consecutively.\n  The 3 positions are:\n  0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND.\n\n  For encoding, do not store critical chunks or known chunks that are enabled with a \"_defined\" flag\n  above in here, since the encoder will blindly follow this and could then encode an invalid PNG file\n  (such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use\n  this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST),\n  or any non-standard PNG chunk.\n\n  Do not allocate or traverse this data yourself. Use the chunk traversing functions declared\n  later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct.\n  */\n  unsigned char* unknown_chunks_data[3];\n  size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n} LodePNGInfo;\n\n/*init, cleanup and copy functions to use with this struct*/\nvoid lodepng_info_init(LodePNGInfo* info);\nvoid lodepng_info_cleanup(LodePNGInfo* info);\n/*return value is error code (0 means no error)*/\nunsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source);\n\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\nunsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/\nvoid lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/\n\nunsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag,\n                           const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/\nvoid lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/\n\n/*replaces if exists*/\nunsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size);\nvoid lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n\n/*\nConverts raw buffer from one color type to another color type, based on\nLodePNGColorMode structs to describe the input and output color type.\nSee the reference manual at the end of this header file to see which color conversions are supported.\nreturn value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported)\nThe out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel\nof the output color type (lodepng_get_bpp).\nFor < 8 bpp images, there should not be padding bits at the end of scanlines.\nFor 16-bit per channel colors, uses big endian format like PNG does.\nReturn value is LodePNG error code\n*/\nunsigned lodepng_convert(unsigned char* out, const unsigned char* in,\n                         const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in,\n                         unsigned w, unsigned h);\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*\nSettings for the decoder. This contains settings for the PNG and the Zlib\ndecoder, but not the Info settings from the Info structs.\n*/\ntypedef struct LodePNGDecoderSettings {\n  LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/\n\n  /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */\n  unsigned ignore_crc; /*ignore CRC checksums*/\n  unsigned ignore_critical; /*ignore unknown critical chunks*/\n  unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/\n  /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable\n     errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some\n     strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters\n     in string keys, etc... */\n\n  unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/\n\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\n  unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/\n\n  /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/\n  unsigned remember_unknown_chunks;\n\n  /* maximum size for decompressed text chunks. If a text chunk's text is larger than this, an error is returned,\n  unless reading text chunks is disabled or this limit is set higher or disabled. Set to 0 to allow any size.\n  By default it is a value that prevents unreasonably large strings from hogging memory. */\n  size_t max_text_size;\n\n  /* maximum size for compressed ICC chunks. If the ICC profile is larger than this, an error will be returned. Set to\n  0 to allow any size. By default this is a value that prevents ICC profiles that would be much larger than any\n  legitimate profile could be to hog memory. */\n  size_t max_icc_size;\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n} LodePNGDecoderSettings;\n\nvoid lodepng_decoder_settings_init(LodePNGDecoderSettings* settings);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/\ntypedef enum LodePNGFilterStrategy {\n  /*every filter at zero*/\n  LFS_ZERO = 0,\n  /*every filter at 1, 2, 3 or 4 (paeth), unlike LFS_ZERO not a good choice, but for testing*/\n  LFS_ONE = 1,\n  LFS_TWO = 2,\n  LFS_THREE = 3,\n  LFS_FOUR = 4,\n  /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/\n  LFS_MINSUM,\n  /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending\n  on the image, this is better or worse than minsum.*/\n  LFS_ENTROPY,\n  /*\n  Brute-force-search PNG filters by compressing each filter for each scanline.\n  Experimental, very slow, and only rarely gives better compression than MINSUM.\n  */\n  LFS_BRUTE_FORCE,\n  /*use predefined_filters buffer: you specify the filter type for each scanline*/\n  LFS_PREDEFINED\n} LodePNGFilterStrategy;\n\n/*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...),\nwhich helps decide which color model to use for encoding.\nUsed internally by default if \"auto_convert\" is enabled. Public because it's useful for custom algorithms.*/\ntypedef struct LodePNGColorStats {\n  unsigned colored; /*not grayscale*/\n  unsigned key; /*image is not opaque and color key is possible instead of full alpha*/\n  unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/\n  unsigned short key_g;\n  unsigned short key_b;\n  unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/\n  unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16 or allow_palette is disabled.*/\n  unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order, only valid when numcolors is valid*/\n  unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for grayscale only. 16 if 16-bit per channel required.*/\n  size_t numpixels;\n\n  /*user settings for computing/using the stats*/\n  unsigned allow_palette; /*default 1. if 0, disallow choosing palette colortype in auto_choose_color, and don't count numcolors*/\n  unsigned allow_greyscale; /*default 1. if 0, choose RGB or RGBA even if the image only has gray colors*/\n} LodePNGColorStats;\n\nvoid lodepng_color_stats_init(LodePNGColorStats* stats);\n\n/*Get a LodePNGColorStats of the image. The stats must already have been inited.\nReturns error code (e.g. alloc fail) or 0 if ok.*/\nunsigned lodepng_compute_color_stats(LodePNGColorStats* stats,\n                                     const unsigned char* image, unsigned w, unsigned h,\n                                     const LodePNGColorMode* mode_in);\n\n/*Settings for the encoder.*/\ntypedef struct LodePNGEncoderSettings {\n  LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/\n\n  unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/\n\n  /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than\n  8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to\n  completely follow the official PNG heuristic, filter_palette_zero must be true and\n  filter_strategy must be LFS_MINSUM*/\n  unsigned filter_palette_zero;\n  /*Which filter strategy to use when not using zeroes due to filter_palette_zero.\n  Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/\n  LodePNGFilterStrategy filter_strategy;\n  /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with\n  the same length as the amount of scanlines in the image, and each value must <= 5. You\n  have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero\n  must be set to 0 to ensure this is also used on palette or low bitdepth images.*/\n  const unsigned char* predefined_filters;\n\n  /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette).\n  If colortype is 3, PLTE is _always_ created.*/\n  unsigned force_palette;\n#ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS\n  /*add LodePNG identifier and version as a text chunk, for debugging*/\n  unsigned add_id;\n  /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/\n  unsigned text_compression;\n#endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/\n} LodePNGEncoderSettings;\n\nvoid lodepng_encoder_settings_init(LodePNGEncoderSettings* settings);\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n\n#if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER)\n/*The settings, state and information for extended encoding and decoding.*/\ntypedef struct LodePNGState {\n#ifdef LODEPNG_COMPILE_DECODER\n  LodePNGDecoderSettings decoder; /*the decoding settings*/\n#endif /*LODEPNG_COMPILE_DECODER*/\n#ifdef LODEPNG_COMPILE_ENCODER\n  LodePNGEncoderSettings encoder; /*the encoding settings*/\n#endif /*LODEPNG_COMPILE_ENCODER*/\n  LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/\n  LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/\n  unsigned error;\n} LodePNGState;\n\n/*init, cleanup and copy functions to use with this struct*/\nvoid lodepng_state_init(LodePNGState* state);\nvoid lodepng_state_cleanup(LodePNGState* state);\nvoid lodepng_state_copy(LodePNGState* dest, const LodePNGState* source);\n#endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*\nSame as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and\ngetting much more information about the PNG image and color mode.\n*/\nunsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h,\n                        LodePNGState* state,\n                        const unsigned char* in, size_t insize);\n\n/*\nRead the PNG header, but not the actual data. This returns only the information\nthat is in the IHDR chunk of the PNG, such as width, height and color type. The\ninformation is placed in the info_png field of the LodePNGState.\n*/\nunsigned lodepng_inspect(unsigned* w, unsigned* h,\n                         LodePNGState* state,\n                         const unsigned char* in, size_t insize);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n/*\nReads one metadata chunk (other than IHDR) of the PNG file and outputs what it\nread in the state. Returns error code on failure.\nUse lodepng_inspect first with a new state, then e.g. lodepng_chunk_find_const\nto find the desired chunk type, and if non null use lodepng_inspect_chunk (with\nchunk_pointer - start_of_file as pos).\nSupports most metadata chunks from the PNG standard (gAMA, bKGD, tEXt, ...).\nIgnores unsupported, unknown, non-metadata or IHDR chunks (without error).\nRequirements: &in[pos] must point to start of a chunk, must use regular\nlodepng_inspect first since format of most other chunks depends on IHDR, and if\nthere is a PLTE chunk, that one must be inspected before tRNS or bKGD.\n*/\nunsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos,\n                               const unsigned char* in, size_t insize);\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/\nunsigned lodepng_encode(unsigned char** out, size_t* outsize,\n                        const unsigned char* image, unsigned w, unsigned h,\n                        LodePNGState* state);\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n/*\nThe lodepng_chunk functions are normally not needed, except to traverse the\nunknown chunks stored in the LodePNGInfo struct, or add new ones to it.\nIt also allows traversing the chunks of an encoded PNG file yourself.\n\nThe chunk pointer always points to the beginning of the chunk itself, that is\nthe first byte of the 4 length bytes.\n\nIn the PNG file format, chunks have the following format:\n-4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer)\n-4 bytes chunk type (ASCII a-z,A-Z only, see below)\n-length bytes of data (may be 0 bytes if length was 0)\n-4 bytes of CRC, computed on chunk name + data\n\nThe first chunk starts at the 8th byte of the PNG file, the entire rest of the file\nexists out of concatenated chunks with the above format.\n\nPNG standard chunk ASCII naming conventions:\n-First byte: uppercase = critical, lowercase = ancillary\n-Second byte: uppercase = public, lowercase = private\n-Third byte: must be uppercase\n-Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy\n*/\n\n/*\nGets the length of the data of the chunk. Total chunk length has 12 bytes more.\nThere must be at least 4 bytes to read from. If the result value is too large,\nit may be corrupt data.\n*/\nunsigned lodepng_chunk_length(const unsigned char* chunk);\n\n/*puts the 4-byte type in null terminated string*/\nvoid lodepng_chunk_type(char type[5], const unsigned char* chunk);\n\n/*check if the type is the given type*/\nunsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type);\n\n/*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/\nunsigned char lodepng_chunk_ancillary(const unsigned char* chunk);\n\n/*0: public, 1: private (see PNG standard)*/\nunsigned char lodepng_chunk_private(const unsigned char* chunk);\n\n/*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/\nunsigned char lodepng_chunk_safetocopy(const unsigned char* chunk);\n\n/*get pointer to the data of the chunk, where the input points to the header of the chunk*/\nunsigned char* lodepng_chunk_data(unsigned char* chunk);\nconst unsigned char* lodepng_chunk_data_const(const unsigned char* chunk);\n\n/*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/\nunsigned lodepng_chunk_check_crc(const unsigned char* chunk);\n\n/*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/\nvoid lodepng_chunk_generate_crc(unsigned char* chunk);\n\n/*\nIterate to next chunks, allows iterating through all chunks of the PNG file.\nInput must be at the beginning of a chunk (result of a previous lodepng_chunk_next call,\nor the 8th byte of a PNG file which always has the first chunk), or alternatively may\npoint to the first byte of the PNG file (which is not a chunk but the magic header, the\nfunction will then skip over it and return the first real chunk).\nWill output pointer to the start of the next chunk, or at or beyond end of the file if there\nis no more chunk after this or possibly if the chunk is corrupt.\nStart this process at the 8th byte of the PNG file.\nIn a non-corrupt PNG file, the last chunk should have name \"IEND\".\n*/\nunsigned char* lodepng_chunk_next(unsigned char* chunk, unsigned char* end);\nconst unsigned char* lodepng_chunk_next_const(const unsigned char* chunk, const unsigned char* end);\n\n/*Finds the first chunk with the given type in the range [chunk, end), or returns NULL if not found.*/\nunsigned char* lodepng_chunk_find(unsigned char* chunk, unsigned char* end, const char type[5]);\nconst unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]);\n\n/*\nAppends chunk to the data in out. The given chunk should already have its chunk header.\nThe out variable and outsize are updated to reflect the new reallocated buffer.\nReturns error code (0 if it went ok)\n*/\nunsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk);\n\n/*\nAppends new chunk to out. The chunk to append is given by giving its length, type\nand data separately. The type is a 4-letter string.\nThe out variable and outsize are updated to reflect the new reallocated buffer.\nReturns error code (0 if it went ok)\n*/\nunsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length,\n                              const char* type, const unsigned char* data);\n\n\n/*Calculate CRC32 of buffer*/\nunsigned lodepng_crc32(const unsigned char* buf, size_t len);\n#endif /*LODEPNG_COMPILE_PNG*/\n\n\n#ifdef LODEPNG_COMPILE_ZLIB\n/*\nThis zlib part can be used independently to zlib compress and decompress a\nbuffer. It cannot be used to create gzip files however, and it only supports the\npart of zlib that is required for PNG, it does not support dictionaries.\n*/\n\n#ifdef LODEPNG_COMPILE_DECODER\n/*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/\nunsigned lodepng_inflate(unsigned char** out, size_t* outsize,\n                         const unsigned char* in, size_t insize,\n                         const LodePNGDecompressSettings* settings);\n\n/*\nDecompresses Zlib data. Reallocates the out buffer and appends the data. The\ndata must be according to the zlib specification.\nEither, *out must be NULL and *outsize must be 0, or, *out must be a valid\nbuffer and *outsize its size in bytes. out must be freed by user after usage.\n*/\nunsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize,\n                                 const unsigned char* in, size_t insize,\n                                 const LodePNGDecompressSettings* settings);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/*\nCompresses data with Zlib. Reallocates the out buffer and appends the data.\nZlib adds a small header and trailer around the deflate data.\nThe data is output in the format of the zlib specification.\nEither, *out must be NULL and *outsize must be 0, or, *out must be a valid\nbuffer and *outsize its size in bytes. out must be freed by user after usage.\n*/\nunsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize,\n                               const unsigned char* in, size_t insize,\n                               const LodePNGCompressSettings* settings);\n\n/*\nFind length-limited Huffman code for given frequencies. This function is in the\npublic interface only for tests, it's used internally by lodepng_deflate.\n*/\nunsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies,\n                                      size_t numcodes, unsigned maxbitlen);\n\n/*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/\nunsigned lodepng_deflate(unsigned char** out, size_t* outsize,\n                         const unsigned char* in, size_t insize,\n                         const LodePNGCompressSettings* settings);\n\n#endif /*LODEPNG_COMPILE_ENCODER*/\n#endif /*LODEPNG_COMPILE_ZLIB*/\n\n#ifdef LODEPNG_COMPILE_DISK\n/*\nLoad a file from disk into buffer. The function allocates the out buffer, and\nafter usage you should free it.\nout: output parameter, contains pointer to loaded buffer.\noutsize: output parameter, size of the allocated out buffer\nfilename: the path to the file to load\nreturn value: error code (0 means ok)\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory.\n*/\nunsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename);\n\n/*\nSave a file from buffer to disk. Warning, if it exists, this function overwrites\nthe file without warning!\nbuffer: the buffer to write\nbuffersize: size of the buffer to write\nfilename: the path to the file to save to\nreturn value: error code (0 means ok)\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory\n*/\nunsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename);\n#endif /*LODEPNG_COMPILE_DISK*/\n\n#ifdef LODEPNG_COMPILE_CPP\n/* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */\nnamespace lodepng {\n#ifdef LODEPNG_COMPILE_PNG\nclass State : public LodePNGState {\n  public:\n    State();\n    State(const State& other);\n    ~State();\n    State& operator=(const State& other);\n};\n\n#ifdef LODEPNG_COMPILE_DECODER\n/* Same as other lodepng::decode, but using a State for more settings and information. */\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                State& state,\n                const unsigned char* in, size_t insize);\nunsigned decode(std::vector<unsigned char>& out, unsigned& w, unsigned& h,\n                State& state,\n                const std::vector<unsigned char>& in);\n#endif /*LODEPNG_COMPILE_DECODER*/\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/* Same as other lodepng::encode, but using a State for more settings and information. */\nunsigned encode(std::vector<unsigned char>& out,\n                const unsigned char* in, unsigned w, unsigned h,\n                State& state);\nunsigned encode(std::vector<unsigned char>& out,\n                const std::vector<unsigned char>& in, unsigned w, unsigned h,\n                State& state);\n#endif /*LODEPNG_COMPILE_ENCODER*/\n\n#ifdef LODEPNG_COMPILE_DISK\n/*\nLoad a file from disk into an std::vector.\nreturn value: error code (0 means ok)\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and decode in-memory\n*/\nunsigned load_file(std::vector<unsigned char>& buffer, const std::string& filename);\n\n/*\nSave the binary data in an std::vector to a file on disk. The file is overwritten\nwithout warning.\n\nNOTE: Wide-character filenames are not supported, you can use an external method\nto handle such files and encode in-memory\n*/\nunsigned save_file(const std::vector<unsigned char>& buffer, const std::string& filename);\n#endif /* LODEPNG_COMPILE_DISK */\n#endif /* LODEPNG_COMPILE_PNG */\n\n#ifdef LODEPNG_COMPILE_ZLIB\n#ifdef LODEPNG_COMPILE_DECODER\n/* Zlib-decompress an unsigned char buffer */\nunsigned decompress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,\n                    const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);\n\n/* Zlib-decompress an std::vector */\nunsigned decompress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,\n                    const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings);\n#endif /* LODEPNG_COMPILE_DECODER */\n\n#ifdef LODEPNG_COMPILE_ENCODER\n/* Zlib-compress an unsigned char buffer */\nunsigned compress(std::vector<unsigned char>& out, const unsigned char* in, size_t insize,\n                  const LodePNGCompressSettings& settings = lodepng_default_compress_settings);\n\n/* Zlib-compress an std::vector */\nunsigned compress(std::vector<unsigned char>& out, const std::vector<unsigned char>& in,\n                  const LodePNGCompressSettings& settings = lodepng_default_compress_settings);\n#endif /* LODEPNG_COMPILE_ENCODER */\n#endif /* LODEPNG_COMPILE_ZLIB */\n} /* namespace lodepng */\n#endif /*LODEPNG_COMPILE_CPP*/\n\n/*\nTODO:\n[.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often\n[.] check compatibility with various compilers  - done but needs to be redone for every newer version\n[X] converting color to 16-bit per channel types\n[X] support color profile chunk types (but never let them touch RGB values by default)\n[ ] support all public PNG chunk types (almost done except sBIT, sPLT and hIST)\n[ ] make sure encoder generates no chunks with size > (2^31)-1\n[ ] partial decoding (stream processing)\n[X] let the \"isFullyOpaque\" function check color keys and transparent palettes too\n[X] better name for the variables \"codes\", \"codesD\", \"codelengthcodes\", \"clcl\" and \"lldl\"\n[ ] allow treating some errors like warnings, when image is recoverable (e.g. 69, 57, 58)\n[ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ...\n[ ] error messages with line numbers (and version)\n[ ] errors in state instead of as return code?\n[ ] new errors/warnings like suspiciously big decompressed ztxt or iccp chunk\n[ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes\n[ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ...\n[ ] allow user to give data (void*) to custom allocator\n[X] provide alternatives for C library functions not present on some platforms (memcpy, ...)\n*/\n\n#endif /*LODEPNG_H inclusion guard*/\n\n/*\nLodePNG Documentation\n---------------------\n\n0. table of contents\n--------------------\n\n  1. about\n   1.1. supported features\n   1.2. features not supported\n  2. C and C++ version\n  3. security\n  4. decoding\n  5. encoding\n  6. color conversions\n    6.1. PNG color types\n    6.2. color conversions\n    6.3. padding bits\n    6.4. A note about 16-bits per channel and endianness\n  7. error values\n  8. chunks and PNG editing\n  9. compiler support\n  10. examples\n   10.1. decoder C++ example\n   10.2. decoder C example\n  11. state settings reference\n  12. changes\n  13. contact information\n\n\n1. about\n--------\n\nPNG is a file format to store raster images losslessly with good compression,\nsupporting different color types and alpha channel.\n\nLodePNG is a PNG codec according to the Portable Network Graphics (PNG)\nSpecification (Second Edition) - W3C Recommendation 10 November 2003.\n\nThe specifications used are:\n\n*) Portable Network Graphics (PNG) Specification (Second Edition):\n     http://www.w3.org/TR/2003/REC-PNG-20031110\n*) RFC 1950 ZLIB Compressed Data Format version 3.3:\n     http://www.gzip.org/zlib/rfc-zlib.html\n*) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3:\n     http://www.gzip.org/zlib/rfc-deflate.html\n\nThe most recent version of LodePNG can currently be found at\nhttp://lodev.org/lodepng/\n\nLodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds\nextra functionality.\n\nLodePNG exists out of two files:\n-lodepng.h: the header file for both C and C++\n-lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage\n\nIf you want to start using LodePNG right away without reading this doc, get the\nexamples from the LodePNG website to see how to use it in code, or check the\nsmaller examples in chapter 13 here.\n\nLodePNG is simple but only supports the basic requirements. To achieve\nsimplicity, the following design choices were made: There are no dependencies\non any external library. There are functions to decode and encode a PNG with\na single function call, and extended versions of these functions taking a\nLodePNGState struct allowing to specify or get more information. By default\nthe colors of the raw image are always RGB or RGBA, no matter what color type\nthe PNG file uses. To read and write files, there are simple functions to\nconvert the files to/from buffers in memory.\n\nThis all makes LodePNG suitable for loading textures in games, demos and small\nprograms, ... It's less suitable for full fledged image editors, loading PNGs\nover network (it requires all the image data to be available before decoding can\nbegin), life-critical systems, ...\n\n1.1. supported features\n-----------------------\n\nThe following features are supported by the decoder:\n\n*) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image,\n   or the same color type as the PNG\n*) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image\n*) Adam7 interlace and deinterlace for any color type\n*) loading the image from harddisk or decoding it from a buffer from other sources than harddisk\n*) support for alpha channels, including RGBA color model, translucent palettes and color keying\n*) zlib decompression (inflate)\n*) zlib compression (deflate)\n*) CRC32 and ADLER32 checksums\n*) colorimetric color profile conversions: currently experimentally available in lodepng_util.cpp only,\n   plus alternatively ability to pass on chroma/gamma/ICC profile information to other color management system.\n*) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks.\n*) the following chunks are supported by both encoder and decoder:\n    IHDR: header information\n    PLTE: color palette\n    IDAT: pixel data\n    IEND: the final chunk\n    tRNS: transparency for palettized images\n    tEXt: textual information\n    zTXt: compressed textual information\n    iTXt: international textual information\n    bKGD: suggested background color\n    pHYs: physical dimensions\n    tIME: modification time\n    cHRM: RGB chromaticities\n    gAMA: RGB gamma correction\n    iCCP: ICC color profile\n    sRGB: rendering intent\n\n1.2. features not supported\n---------------------------\n\nThe following features are _not_ supported:\n\n*) some features needed to make a conformant PNG-Editor might be still missing.\n*) partial loading/stream processing. All data must be available and is processed in one call.\n*) The following public chunks are not (yet) supported but treated as unknown chunks by LodePNG:\n    sBIT\n    hIST\n    sPLT\n\n\n2. C and C++ version\n--------------------\n\nThe C version uses buffers allocated with alloc that you need to free()\nyourself. You need to use init and cleanup functions for each struct whenever\nusing a struct from the C version to avoid exploits and memory leaks.\n\nThe C++ version has extra functions with std::vectors in the interface and the\nlodepng::State class which is a LodePNGState with constructor and destructor.\n\nThese files work without modification for both C and C++ compilers because all\nthe additional C++ code is in \"#ifdef __cplusplus\" blocks that make C-compilers\nignore it, and the C code is made to compile both with strict ISO C90 and C++.\n\nTo use the C++ version, you need to rename the source file to lodepng.cpp\n(instead of lodepng.c), and compile it with a C++ compiler.\n\nTo use the C version, you need to rename the source file to lodepng.c (instead\nof lodepng.cpp), and compile it with a C compiler.\n\n\n3. Security\n-----------\n\nEven if carefully designed, it's always possible that LodePNG contains possible\nexploits. If you discover one, please let me know, and it will be fixed.\n\nWhen using LodePNG, care has to be taken with the C version of LodePNG, as well\nas the C-style structs when working with C++. The following conventions are used\nfor all C-style structs:\n\n-if a struct has a corresponding init function, always call the init function when making a new one\n-if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks\n-if a struct has a corresponding copy function, use the copy function instead of \"=\".\n The destination must also be inited already.\n\n\n4. Decoding\n-----------\n\nDecoding converts a PNG compressed image to a raw pixel buffer.\n\nMost documentation on using the decoder is at its declarations in the header\nabove. For C, simple decoding can be done with functions such as\nlodepng_decode32, and more advanced decoding can be done with the struct\nLodePNGState and lodepng_decode. For C++, all decoding can be done with the\nvarious lodepng::decode functions, and lodepng::State can be used for advanced\nfeatures.\n\nWhen using the LodePNGState, it uses the following fields for decoding:\n*) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here\n*) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get\n*) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use\n\nLodePNGInfo info_png\n--------------------\n\nAfter decoding, this contains extra information of the PNG image, except the actual\npixels, width and height because these are already gotten directly from the decoder\nfunctions.\n\nIt contains for example the original color type of the PNG image, text comments,\nsuggested background color, etc... More details about the LodePNGInfo struct are\nat its declaration documentation.\n\nLodePNGColorMode info_raw\n-------------------------\n\nWhen decoding, here you can specify which color type you want\nthe resulting raw image to be. If this is different from the colortype of the\nPNG, then the decoder will automatically convert the result. This conversion\nalways works, except if you want it to convert a color PNG to grayscale or to\na palette with missing colors.\n\nBy default, 32-bit color is used for the result.\n\nLodePNGDecoderSettings decoder\n------------------------------\n\nThe settings can be used to ignore the errors created by invalid CRC and Adler32\nchunks, and to disable the decoding of tEXt chunks.\n\nThere's also a setting color_convert, true by default. If false, no conversion\nis done, the resulting data will be as it was in the PNG (after decompression)\nand you'll have to puzzle the colors of the pixels together yourself using the\ncolor type information in the LodePNGInfo.\n\n\n5. Encoding\n-----------\n\nEncoding converts a raw pixel buffer to a PNG compressed image.\n\nMost documentation on using the encoder is at its declarations in the header\nabove. For C, simple encoding can be done with functions such as\nlodepng_encode32, and more advanced decoding can be done with the struct\nLodePNGState and lodepng_encode. For C++, all encoding can be done with the\nvarious lodepng::encode functions, and lodepng::State can be used for advanced\nfeatures.\n\nLike the decoder, the encoder can also give errors. However it gives less errors\nsince the encoder input is trusted, the decoder input (a PNG image that could\nbe forged by anyone) is not trusted.\n\nWhen using the LodePNGState, it uses the following fields for encoding:\n*) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be.\n*) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has\n*) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use\n\nLodePNGInfo info_png\n--------------------\n\nWhen encoding, you use this the opposite way as when decoding: for encoding,\nyou fill in the values you want the PNG to have before encoding. By default it's\nnot needed to specify a color type for the PNG since it's automatically chosen,\nbut it's possible to choose it yourself given the right settings.\n\nThe encoder will not always exactly match the LodePNGInfo struct you give,\nit tries as close as possible. Some things are ignored by the encoder. The\nencoder uses, for example, the following settings from it when applicable:\ncolortype and bitdepth, text chunks, time chunk, the color key, the palette, the\nbackground color, the interlace method, unknown chunks, ...\n\nWhen encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk.\nIf the palette contains any colors for which the alpha channel is not 255 (so\nthere are translucent colors in the palette), it'll add a tRNS chunk.\n\nLodePNGColorMode info_raw\n-------------------------\n\nYou specify the color type of the raw image that you give to the input here,\nincluding a possible transparent color key and palette you happen to be using in\nyour raw image data.\n\nBy default, 32-bit color is assumed, meaning your input has to be in RGBA\nformat with 4 bytes (unsigned chars) per pixel.\n\nLodePNGEncoderSettings encoder\n------------------------------\n\nThe following settings are supported (some are in sub-structs):\n*) auto_convert: when this option is enabled, the encoder will\nautomatically choose the smallest possible color mode (including color key) that\ncan encode the colors of all pixels without information loss.\n*) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree,\n   2 = dynamic huffman tree (best compression). Should be 2 for proper\n   compression.\n*) use_lz77: whether or not to use LZ77 for compressed block types. Should be\n   true for proper compression.\n*) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value\n   2048 by default, but can be set to 32768 for better, but slow, compression.\n*) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE\n   chunk if force_palette is true. This can used as suggested palette to convert\n   to by viewers that don't support more than 256 colors (if those still exist)\n*) add_id: add text chunk \"Encoder: LodePNG <version>\" to the image.\n*) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks.\n  zTXt chunks use zlib compression on the text. This gives a smaller result on\n  large texts but a larger result on small texts (such as a single program name).\n  It's all tEXt or all zTXt though, there's no separate setting per text yet.\n\n\n6. color conversions\n--------------------\n\nAn important thing to note about LodePNG, is that the color type of the PNG, and\nthe color type of the raw image, are completely independent. By default, when\nyou decode a PNG, you get the result as a raw image in the color type you want,\nno matter whether the PNG was encoded with a palette, grayscale or RGBA color.\nAnd if you encode an image, by default LodePNG will automatically choose the PNG\ncolor type that gives good compression based on the values of colors and amount\nof colors in the image. It can be configured to let you control it instead as\nwell, though.\n\nTo be able to do this, LodePNG does conversions from one color mode to another.\nIt can convert from almost any color type to any other color type, except the\nfollowing conversions: RGB to grayscale is not supported, and converting to a\npalette when the palette doesn't have a required color is not supported. This is\nnot supported on purpose: this is information loss which requires a color\nreduction algorithm that is beyond the scope of a PNG encoder (yes, RGB to gray\nis easy, but there are multiple ways if you want to give some channels more\nweight).\n\nBy default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB\ncolor, no matter what color type the PNG has. And by default when encoding,\nLodePNG automatically picks the best color model for the output PNG, and expects\nthe input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control\nthe color format of the images yourself, you can skip this chapter.\n\n6.1. PNG color types\n--------------------\n\nA PNG image can have many color types, ranging from 1-bit color to 64-bit color,\nas well as palettized color modes. After the zlib decompression and unfiltering\nin the PNG image is done, the raw pixel data will have that color type and thus\na certain amount of bits per pixel. If you want the output raw image after\ndecoding to have another color type, a conversion is done by LodePNG.\n\nThe PNG specification gives the following color types:\n\n0: grayscale, bit depths 1, 2, 4, 8, 16\n2: RGB, bit depths 8 and 16\n3: palette, bit depths 1, 2, 4 and 8\n4: grayscale with alpha, bit depths 8 and 16\n6: RGBA, bit depths 8 and 16\n\nBit depth is the amount of bits per pixel per color channel. So the total amount\nof bits per pixel is: amount of channels * bitdepth.\n\n6.2. color conversions\n----------------------\n\nAs explained in the sections about the encoder and decoder, you can specify\ncolor types and bit depths in info_png and info_raw to change the default\nbehaviour.\n\nIf, when decoding, you want the raw image to be something else than the default,\nyou need to set the color type and bit depth you want in the LodePNGColorMode,\nor the parameters colortype and bitdepth of the simple decoding function.\n\nIf, when encoding, you use another color type than the default in the raw input\nimage, you need to specify its color type and bit depth in the LodePNGColorMode\nof the raw image, or use the parameters colortype and bitdepth of the simple\nencoding function.\n\nIf, when encoding, you don't want LodePNG to choose the output PNG color type\nbut control it yourself, you need to set auto_convert in the encoder settings\nto false, and specify the color type you want in the LodePNGInfo of the\nencoder (including palette: it can generate a palette if auto_convert is true,\notherwise not).\n\nIf the input and output color type differ (whether user chosen or auto chosen),\nLodePNG will do a color conversion, which follows the rules below, and may\nsometimes result in an error.\n\nTo avoid some confusion:\n-the decoder converts from PNG to raw image\n-the encoder converts from raw image to PNG\n-the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image\n-the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG\n-when encoding, the color type in LodePNGInfo is ignored if auto_convert\n is enabled, it is automatically generated instead\n-when decoding, the color type in LodePNGInfo is set by the decoder to that of the original\n PNG image, but it can be ignored since the raw image has the color type you requested instead\n-if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion\n between the color types is done if the color types are supported. If it is not\n supported, an error is returned. If the types are the same, no conversion is done.\n-even though some conversions aren't supported, LodePNG supports loading PNGs from any\n colortype and saving PNGs to any colortype, sometimes it just requires preparing\n the raw image correctly before encoding.\n-both encoder and decoder use the same color converter.\n\nThe function lodepng_convert does the color conversion. It is available in the\ninterface but normally isn't needed since the encoder and decoder already call\nit.\n\nNon supported color conversions:\n-color to grayscale when non-gray pixels are present: no error is thrown, but\nthe result will look ugly because only the red channel is taken (it assumes all\nthree channels are the same in this case so ignores green and blue). The reason\nno error is given is to allow converting from three-channel grayscale images to\none-channel even if there are numerical imprecisions.\n-anything to palette when the palette does not have an exact match for a from-color\nin it: in this case an error is thrown\n\nSupported color conversions:\n-anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA\n-any gray or gray+alpha, to gray or gray+alpha\n-anything to a palette, as long as the palette has the requested colors in it\n-removing alpha channel\n-higher to smaller bitdepth, and vice versa\n\nIf you want no color conversion to be done (e.g. for speed or control):\n-In the encoder, you can make it save a PNG with any color type by giving the\nraw color mode and LodePNGInfo the same color mode, and setting auto_convert to\nfalse.\n-In the decoder, you can make it store the pixel data in the same color type\nas the PNG has, by setting the color_convert setting to false. Settings in\ninfo_raw are then ignored.\n\n6.3. padding bits\n-----------------\n\nIn the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines\nhave a bit amount that isn't a multiple of 8, then padding bits are used so that each\nscanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output.\nThe raw input image you give to the encoder, and the raw output image you get from the decoder\nwill NOT have these padding bits, e.g. in the case of a 1-bit image with a width\nof 7 pixels, the first pixel of the second scanline will the 8th bit of the first byte,\nnot the first bit of a new byte.\n\n6.4. A note about 16-bits per channel and endianness\n----------------------------------------------------\n\nLodePNG uses unsigned char arrays for 16-bit per channel colors too, just like\nfor any other color format. The 16-bit values are stored in big endian (most\nsignificant byte first) in these arrays. This is the opposite order of the\nlittle endian used by x86 CPU's.\n\nLodePNG always uses big endian because the PNG file format does so internally.\nConversions to other formats than PNG uses internally are not supported by\nLodePNG on purpose, there are myriads of formats, including endianness of 16-bit\ncolors, the order in which you store R, G, B and A, and so on. Supporting and\nconverting to/from all that is outside the scope of LodePNG.\n\nThis may mean that, depending on your use case, you may want to convert the big\nendian output of LodePNG to little endian with a for loop. This is certainly not\nalways needed, many applications and libraries support big endian 16-bit colors\nanyway, but it means you cannot simply cast the unsigned char* buffer to an\nunsigned short* buffer on x86 CPUs.\n\n\n7. error values\n---------------\n\nAll functions in LodePNG that return an error code, return 0 if everything went\nOK, or a non-zero code if there was an error.\n\nThe meaning of the LodePNG error values can be retrieved with the function\nlodepng_error_text: given the numerical error code, it returns a description\nof the error in English as a string.\n\nCheck the implementation of lodepng_error_text to see the meaning of each code.\n\nIt is not recommended to use the numerical values to programmatically make\ndifferent decisions based on error types as the numbers are not guaranteed to\nstay backwards compatible. They are for human consumption only. Programmatically\nonly 0 or non-0 matter.\n\n\n8. chunks and PNG editing\n-------------------------\n\nIf you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG\neditor that should follow the rules about handling of unknown chunks, or if your\nprogram is able to read other types of chunks than the ones handled by LodePNG,\nthen that's possible with the chunk functions of LodePNG.\n\nA PNG chunk has the following layout:\n\n4 bytes length\n4 bytes type name\nlength bytes data\n4 bytes CRC\n\n8.1. iterating through chunks\n-----------------------------\n\nIf you have a buffer containing the PNG image data, then the first chunk (the\nIHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the\nsignature of the PNG and are not part of a chunk. But if you start at byte 8\nthen you have a chunk, and can check the following things of it.\n\nNOTE: none of these functions check for memory buffer boundaries. To avoid\nexploits, always make sure the buffer contains all the data of the chunks.\nWhen using lodepng_chunk_next, make sure the returned value is within the\nallocated memory.\n\nunsigned lodepng_chunk_length(const unsigned char* chunk):\n\nGet the length of the chunk's data. The total chunk length is this length + 12.\n\nvoid lodepng_chunk_type(char type[5], const unsigned char* chunk):\nunsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type):\n\nGet the type of the chunk or compare if it's a certain type\n\nunsigned char lodepng_chunk_critical(const unsigned char* chunk):\nunsigned char lodepng_chunk_private(const unsigned char* chunk):\nunsigned char lodepng_chunk_safetocopy(const unsigned char* chunk):\n\nCheck if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are).\nCheck if the chunk is private (public chunks are part of the standard, private ones not).\nCheck if the chunk is safe to copy. If it's not, then, when modifying data in a critical\nchunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your\nprogram doesn't handle that type of unknown chunk.\n\nunsigned char* lodepng_chunk_data(unsigned char* chunk):\nconst unsigned char* lodepng_chunk_data_const(const unsigned char* chunk):\n\nGet a pointer to the start of the data of the chunk.\n\nunsigned lodepng_chunk_check_crc(const unsigned char* chunk):\nvoid lodepng_chunk_generate_crc(unsigned char* chunk):\n\nCheck if the crc is correct or generate a correct one.\n\nunsigned char* lodepng_chunk_next(unsigned char* chunk):\nconst unsigned char* lodepng_chunk_next_const(const unsigned char* chunk):\n\nIterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these\nfunctions do no boundary checking of the allocated data whatsoever, so make sure there is enough\ndata available in the buffer to be able to go to the next chunk.\n\nunsigned lodepng_chunk_append(unsigned char** out, size_t* outsize, const unsigned char* chunk):\nunsigned lodepng_chunk_create(unsigned char** out, size_t* outsize, unsigned length,\n                              const char* type, const unsigned char* data):\n\nThese functions are used to create new chunks that are appended to the data in *out that has\nlength *outsize. The append function appends an existing chunk to the new data. The create\nfunction creates a new chunk with the given parameters and appends it. Type is the 4-letter\nname of the chunk.\n\n8.2. chunks in info_png\n-----------------------\n\nThe LodePNGInfo struct contains fields with the unknown chunk in it. It has 3\nbuffers (each with size) to contain 3 types of unknown chunks:\nthe ones that come before the PLTE chunk, the ones that come between the PLTE\nand the IDAT chunks, and the ones that come after the IDAT chunks.\nIt's necessary to make the distinction between these 3 cases because the PNG\nstandard forces to keep the ordering of unknown chunks compared to the critical\nchunks, but does not force any other ordering rules.\n\ninfo_png.unknown_chunks_data[0] is the chunks before PLTE\ninfo_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT\ninfo_png.unknown_chunks_data[2] is the chunks after IDAT\n\nThe chunks in these 3 buffers can be iterated through and read by using the same\nway described in the previous subchapter.\n\nWhen using the decoder to decode a PNG, you can make it store all unknown chunks\nif you set the option settings.remember_unknown_chunks to 1. By default, this\noption is off (0).\n\nThe encoder will always encode unknown chunks that are stored in the info_png.\nIf you need it to add a particular chunk that isn't known by LodePNG, you can\nuse lodepng_chunk_append or lodepng_chunk_create to the chunk data in\ninfo_png.unknown_chunks_data[x].\n\nChunks that are known by LodePNG should not be added in that way. E.g. to make\nLodePNG add a bKGD chunk, set background_defined to true and add the correct\nparameters there instead.\n\n\n9. compiler support\n-------------------\n\nNo libraries other than the current standard C library are needed to compile\nLodePNG. For the C++ version, only the standard C++ library is needed on top.\nAdd the files lodepng.c(pp) and lodepng.h to your project, include\nlodepng.h where needed, and your program can read/write PNG files.\n\nIt is compatible with C90 and up, and C++03 and up.\n\nIf performance is important, use optimization when compiling! For both the\nencoder and decoder, this makes a large difference.\n\nMake sure that LodePNG is compiled with the same compiler of the same version\nand with the same settings as the rest of the program, or the interfaces with\nstd::vectors and std::strings in C++ can be incompatible.\n\nCHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets.\n\n*) gcc and g++\n\nLodePNG is developed in gcc so this compiler is natively supported. It gives no\nwarnings with compiler options \"-Wall -Wextra -pedantic -ansi\", with gcc and g++\nversion 4.7.1 on Linux, 32-bit and 64-bit.\n\n*) Clang\n\nFully supported and warning-free.\n\n*) Mingw\n\nThe Mingw compiler (a port of gcc for Windows) should be fully supported by\nLodePNG.\n\n*) Visual Studio and Visual C++ Express Edition\n\nLodePNG should be warning-free with warning level W4. Two warnings were disabled\nwith pragmas though: warning 4244 about implicit conversions, and warning 4996\nwhere it wants to use a non-standard function fopen_s instead of the standard C\nfopen.\n\nVisual Studio may want \"stdafx.h\" files to be included in each source file and\ngive an error \"unexpected end of file while looking for precompiled header\".\nThis is not standard C++ and will not be added to the stock LodePNG. You can\ndisable it for lodepng.cpp only by right clicking it, Properties, C/C++,\nPrecompiled Headers, and set it to Not Using Precompiled Headers there.\n\nNOTE: Modern versions of VS should be fully supported, but old versions, e.g.\nVS6, are not guaranteed to work.\n\n*) Compilers on Macintosh\n\nLodePNG has been reported to work both with gcc and LLVM for Macintosh, both for\nC and C++.\n\n*) Other Compilers\n\nIf you encounter problems on any compilers, feel free to let me know and I may\ntry to fix it if the compiler is modern and standards compliant.\n\n\n10. examples\n------------\n\nThis decoder example shows the most basic usage of LodePNG. More complex\nexamples can be found on the LodePNG website.\n\nNOTE: these examples do not support wide-character filenames, you can use an\nexternal method to handle such files and encode or decode in-memory\n\n10.1. decoder C++ example\n-------------------------\n\n#include \"lodepng.h\"\n#include <iostream>\n\nint main(int argc, char *argv[]) {\n  const char* filename = argc > 1 ? argv[1] : \"test.png\";\n\n  //load and decode\n  std::vector<unsigned char> image;\n  unsigned width, height;\n  unsigned error = lodepng::decode(image, width, height, filename);\n\n  //if there's an error, display it\n  if(error) std::cout << \"decoder error \" << error << \": \" << lodepng_error_text(error) << std::endl;\n\n  //the pixels are now in the vector \"image\", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ...\n}\n\n10.2. decoder C example\n-----------------------\n\n#include \"lodepng.h\"\n\nint main(int argc, char *argv[]) {\n  unsigned error;\n  unsigned char* image;\n  size_t width, height;\n  const char* filename = argc > 1 ? argv[1] : \"test.png\";\n\n  error = lodepng_decode32_file(&image, &width, &height, filename);\n\n  if(error) printf(\"decoder error %u: %s\\n\", error, lodepng_error_text(error));\n\n  / * use image here * /\n\n  free(image);\n  return 0;\n}\n\n11. state settings reference\n----------------------------\n\nA quick reference of some settings to set on the LodePNGState\n\nFor decoding:\n\nstate.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums\nstate.decoder.zlibsettings.custom_...: use custom inflate function\nstate.decoder.ignore_crc: ignore CRC checksums\nstate.decoder.ignore_critical: ignore unknown critical chunks\nstate.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors\nstate.decoder.color_convert: convert internal PNG color to chosen one\nstate.decoder.read_text_chunks: whether to read in text metadata chunks\nstate.decoder.remember_unknown_chunks: whether to read in unknown chunks\nstate.info_raw.colortype: desired color type for decoded image\nstate.info_raw.bitdepth: desired bit depth for decoded image\nstate.info_raw....: more color settings, see struct LodePNGColorMode\nstate.info_png....: no settings for decoder but output, see struct LodePNGInfo\n\nFor encoding:\n\nstate.encoder.zlibsettings.btype: disable compression by setting it to 0\nstate.encoder.zlibsettings.use_lz77: use LZ77 in compression\nstate.encoder.zlibsettings.windowsize: tweak LZ77 windowsize\nstate.encoder.zlibsettings.minmatch: tweak min LZ77 length to match\nstate.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching\nstate.encoder.zlibsettings.lazymatching: try one more LZ77 matching\nstate.encoder.zlibsettings.custom_...: use custom deflate function\nstate.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png\nstate.encoder.filter_palette_zero: PNG filter strategy for palette\nstate.encoder.filter_strategy: PNG filter strategy to encode with\nstate.encoder.force_palette: add palette even if not encoding to one\nstate.encoder.add_id: add LodePNG identifier and version as a text chunk\nstate.encoder.text_compression: use compressed text chunks for metadata\nstate.info_raw.colortype: color type of raw input image you provide\nstate.info_raw.bitdepth: bit depth of raw input image you provide\nstate.info_raw: more color settings, see struct LodePNGColorMode\nstate.info_png.color.colortype: desired color type if auto_convert is false\nstate.info_png.color.bitdepth: desired bit depth if auto_convert is false\nstate.info_png.color....: more color settings, see struct LodePNGColorMode\nstate.info_png....: more PNG related settings, see struct LodePNGInfo\n\n\n12. changes\n-----------\n\nThe version number of LodePNG is the date of the change given in the format\nyyyymmdd.\n\nSome changes aren't backwards compatible. Those are indicated with a (!)\nsymbol.\n\nNot all changes are listed here, the commit history in github lists more:\nhttps://github.com/lvandeve/lodepng\n\n*) 09 jan 2022: minor decoder speed improvements.\n*) 27 jun 2021: added warnings that file reading/writing functions don't support\n   wide-character filenames (support for this is not planned, opening files is\n   not the core part of PNG decoding/decoding and is platform dependent).\n*) 17 okt 2020: prevent decoding too large text/icc chunks by default.\n*) 06 mar 2020: simplified some of the dynamic memory allocations.\n*) 12 jan 2020: (!) added 'end' argument to lodepng_chunk_next to allow correct\n   overflow checks.\n*) 14 aug 2019: around 25% faster decoding thanks to huffman lookup tables.\n*) 15 jun 2019: (!) auto_choose_color API changed (for bugfix: don't use palette\n   if gray ICC profile) and non-ICC LodePNGColorProfile renamed to\n   LodePNGColorStats.\n*) 30 dec 2018: code style changes only: removed newlines before opening braces.\n*) 10 sep 2018: added way to inspect metadata chunks without full decoding.\n*) 19 aug 2018: (!) fixed color mode bKGD is encoded with and made it use\n   palette index in case of palette.\n*) 10 aug 2018: (!) added support for gAMA, cHRM, sRGB and iCCP chunks. This\n   change is backwards compatible unless you relied on unknown_chunks for those.\n*) 11 jun 2018: less restrictive check for pixel size integer overflow\n*) 14 jan 2018: allow optionally ignoring a few more recoverable errors\n*) 17 sep 2017: fix memory leak for some encoder input error cases\n*) 27 nov 2016: grey+alpha auto color model detection bugfix\n*) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort).\n*) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within\n   the limits of pure C90).\n*) 08 dec 2015: Made load_file function return error if file can't be opened.\n*) 24 okt 2015: Bugfix with decoding to palette output.\n*) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding.\n*) 24 aug 2014: Moved to github\n*) 23 aug 2014: Reduced needless memory usage of decoder.\n*) 28 jun 2014: Removed fix_png setting, always support palette OOB for\n    simplicity. Made ColorProfile public.\n*) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization.\n*) 22 dec 2013: Power of two windowsize required for optimization.\n*) 15 apr 2013: Fixed bug with LAC_ALPHA and color key.\n*) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png).\n*) 11 mar 2013: (!) Bugfix with custom free. Changed from \"my\" to \"lodepng_\"\n    prefix for the custom allocators and made it possible with a new #define to\n    use custom ones in your project without needing to change lodepng's code.\n*) 28 jan 2013: Bugfix with color key.\n*) 27 okt 2012: Tweaks in text chunk keyword length error handling.\n*) 8 okt 2012: (!) Added new filter strategy (entropy) and new auto color mode.\n    (no palette). Better deflate tree encoding. New compression tweak settings.\n    Faster color conversions while decoding. Some internal cleanups.\n*) 23 sep 2012: Reduced warnings in Visual Studio a little bit.\n*) 1 sep 2012: (!) Removed #define's for giving custom (de)compression functions\n    and made it work with function pointers instead.\n*) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc\n    and free functions and toggle #defines from compiler flags. Small fixes.\n*) 6 may 2012: (!) Made plugging in custom zlib/deflate functions more flexible.\n*) 22 apr 2012: (!) Made interface more consistent, renaming a lot. Removed\n    redundant C++ codec classes. Reduced amount of structs. Everything changed,\n    but it is cleaner now imho and functionality remains the same. Also fixed\n    several bugs and shrunk the implementation code. Made new samples.\n*) 6 nov 2011: (!) By default, the encoder now automatically chooses the best\n    PNG color model and bit depth, based on the amount and type of colors of the\n    raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color.\n*) 9 okt 2011: simpler hash chain implementation for the encoder.\n*) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching.\n*) 23 aug 2011: tweaked the zlib compression parameters after benchmarking.\n    A bug with the PNG filtertype heuristic was fixed, so that it chooses much\n    better ones (it's quite significant). A setting to do an experimental, slow,\n    brute force search for PNG filter types is added.\n*) 17 aug 2011: (!) changed some C zlib related function names.\n*) 16 aug 2011: made the code less wide (max 120 characters per line).\n*) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors.\n*) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled.\n*) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman\n    to optimize long sequences of zeros.\n*) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and\n    LodePNG_InfoColor_canHaveAlpha functions for convenience.\n*) 7 nov 2010: added LodePNG_error_text function to get error code description.\n*) 30 okt 2010: made decoding slightly faster\n*) 26 okt 2010: (!) changed some C function and struct names (more consistent).\n     Reorganized the documentation and the declaration order in the header.\n*) 08 aug 2010: only changed some comments and external samples.\n*) 05 jul 2010: fixed bug thanks to warnings in the new gcc version.\n*) 14 mar 2010: fixed bug where too much memory was allocated for char buffers.\n*) 02 sep 2008: fixed bug where it could create empty tree that linux apps could\n    read by ignoring the problem but windows apps couldn't.\n*) 06 jun 2008: added more error checks for out of memory cases.\n*) 26 apr 2008: added a few more checks here and there to ensure more safety.\n*) 06 mar 2008: crash with encoding of strings fixed\n*) 02 feb 2008: support for international text chunks added (iTXt)\n*) 23 jan 2008: small cleanups, and #defines to divide code in sections\n*) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor.\n*) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder.\n*) 17 jan 2008: ability to encode and decode compressed zTXt chunks added\n    Also various fixes, such as in the deflate and the padding bits code.\n*) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved\n    filtering code of encoder.\n*) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A\n    C++ wrapper around this provides an interface almost identical to before.\n    Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code\n    are together in these files but it works both for C and C++ compilers.\n*) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks\n*) 30 aug 2007: bug fixed which makes this Borland C++ compatible\n*) 09 aug 2007: some VS2005 warnings removed again\n*) 21 jul 2007: deflate code placed in new namespace separate from zlib code\n*) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images\n*) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing\n    invalid std::vector element [0] fixed, and level 3 and 4 warnings removed\n*) 02 jun 2007: made the encoder add a tag with version by default\n*) 27 may 2007: zlib and png code separated (but still in the same file),\n    simple encoder/decoder functions added for more simple usage cases\n*) 19 may 2007: minor fixes, some code cleaning, new error added (error 69),\n    moved some examples from here to lodepng_examples.cpp\n*) 12 may 2007: palette decoding bug fixed\n*) 24 apr 2007: changed the license from BSD to the zlib license\n*) 11 mar 2007: very simple addition: ability to encode bKGD chunks.\n*) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding\n    palettized PNG images. Plus little interface change with palette and texts.\n*) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes.\n    Fixed a bug where the end code of a block had length 0 in the Huffman tree.\n*) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented\n    and supported by the encoder, resulting in smaller PNGs at the output.\n*) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone.\n*) 24 jan 2007: gave encoder an error interface. Added color conversion from any\n    greyscale type to 8-bit greyscale with or without alpha.\n*) 21 jan 2007: (!) Totally changed the interface. It allows more color types\n    to convert to and is more uniform. See the manual for how it works now.\n*) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days:\n    encode/decode custom tEXt chunks, separate classes for zlib & deflate, and\n    at last made the decoder give errors for incorrect Adler32 or Crc.\n*) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel.\n*) 29 dec 2006: Added support for encoding images without alpha channel, and\n    cleaned out code as well as making certain parts faster.\n*) 28 dec 2006: Added \"Settings\" to the encoder.\n*) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now.\n    Removed some code duplication in the decoder. Fixed little bug in an example.\n*) 09 dec 2006: (!) Placed output parameters of public functions as first parameter.\n    Fixed a bug of the decoder with 16-bit per color.\n*) 15 okt 2006: Changed documentation structure\n*) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the\n    given image buffer, however for now it's not compressed.\n*) 08 sep 2006: (!) Changed to interface with a Decoder class\n*) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different\n    way. Renamed decodePNG to decodePNGGeneric.\n*) 29 jul 2006: (!) Changed the interface: image info is now returned as a\n    struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy.\n*) 28 jul 2006: Cleaned the code and added new error checks.\n    Corrected terminology \"deflate\" into \"inflate\".\n*) 23 jun 2006: Added SDL example in the documentation in the header, this\n    example allows easy debugging by displaying the PNG and its transparency.\n*) 22 jun 2006: (!) Changed way to obtain error value. Added\n    loadFile function for convenience. Made decodePNG32 faster.\n*) 21 jun 2006: (!) Changed type of info vector to unsigned.\n    Changed position of palette in info vector. Fixed an important bug that\n    happened on PNGs with an uncompressed block.\n*) 16 jun 2006: Internally changed unsigned into unsigned where\n    needed, and performed some optimizations.\n*) 07 jun 2006: (!) Renamed functions to decodePNG and placed them\n    in LodePNG namespace. Changed the order of the parameters. Rewrote the\n    documentation in the header. Renamed files to lodepng.cpp and lodepng.h\n*) 22 apr 2006: Optimized and improved some code\n*) 07 sep 2005: (!) Changed to std::vector interface\n*) 12 aug 2005: Initial release (C++, decoder only)\n\n\n13. contact information\n-----------------------\n\nFeel free to contact me with suggestions, problems, comments, ... concerning\nLodePNG. If you encounter a PNG image that doesn't work properly with this\ndecoder, feel free to send it and I'll use it to find and fix the problem.\n\nMy email address is (puzzle the account and domain together with an @ symbol):\nDomain: gmail dot com.\nAccount: lode dot vandevenne.\n\n\nCopyright (c) 2005-2022 Lode Vandevenne\n*/\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_8/lodepng/lodepng.cpp",
    "content": "#include \"lodepng.h\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CXX17CompilerCrash/v5_8/src/user_objects.cc",
    "content": "#include \"user_objects.h\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CaseCollision/Package.swift",
    "content": "// swift-tools-version:6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"CaseInsensitiveCollisions\",\n    products: [\n        .executable(name: \"foo\", targets: [\"footool\"]),\n    ],\n    targets: [\n        .executableTarget(name: \"footool\", dependencies: [\"Foo\"]),\n        .target(name: \"Foo\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CaseCollision/Sources/Foo/Foo.swift",
    "content": "public func greeting() -> String {\n    \"Hello, world!\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CaseCollision/Sources/footool/main.swift",
    "content": "import Foo\n\nprint(greeting())\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CheckTestLibraryEnvironmentVariable/Package.swift",
    "content": "// swift-tools-version: 5.10\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"CheckTestLibraryEnvironmentVariable\",\n    targets: [\n        .testTarget(name: \"CheckTestLibraryEnvironmentVariableTests\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CheckTestLibraryEnvironmentVariable/Tests/CheckTestLibraryEnvironmentVariableTests/CheckTestLibraryEnvironmentVariableTests.swift",
    "content": "import XCTest\n\nfinal class CheckTestLibraryEnvironmentVariableTests: XCTestCase {\n    func testEnvironmentVariables() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"Test is macOS specific\")\n        #endif\n\n        let testingEnabled = ProcessInfo.processInfo.environment[\"SWIFT_TESTING_ENABLED\"]\n        XCTAssertEqual(testingEnabled, \"0\")\n\n        if ProcessInfo.processInfo.environment[\"CONTAINS_SWIFT_TESTING\"] != nil {\n            let frameworkPath = try XCTUnwrap(ProcessInfo.processInfo.environment[\"DYLD_FRAMEWORK_PATH\"])\n            let libraryPath = try XCTUnwrap(ProcessInfo.processInfo.environment[\"DYLD_LIBRARY_PATH\"])\n            XCTAssertTrue(\n                frameworkPath.contains(\"testing\") || libraryPath.contains(\"testing\"),\n                \"Expected 'testing' in '\\(frameworkPath)' or '\\(libraryPath)'\"\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CompileFails/Foo.swift",
    "content": "class Foo {\n    var bar: Int = 0\n    \n    compile_failure\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/CompileFails/Package.swift",
    "content": "// swift-tools-version:4.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"CompileFails\",\n    targets: [\n        .target(name: \"CompileFails\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings/app/Package.swift",
    "content": "// swift-tools-version: 5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"app\",\n    products: [\n        .executable(name: \"app\", targets: [\"app\"])\n    ],\n    dependencies: [\n        .package(url: \"../dep1\", from: \"1.0.0\"),\n        .package(url: \"../dep2\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .executableTarget(\n          name: \"app\",\n          dependencies: [\n            .product(name: \"dep1\", package: \"dep1\"),\n            .product(name: \"dep2\", package: \"dep2\")\n          ],\n          path: \"./\"\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings/app/app.swift",
    "content": "import dep1\nimport dep2\n\n@main\nstruct App {\n  var deprecated: DeprecatedApp\n\n  public static func main() {\n    print(\"hello, world!\")\n  }\n}\n\n@available(*, deprecated)\nstruct DeprecatedApp {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings/dep1/Package.swift",
    "content": "// swift-tools-version: 5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"dep1\",\n    products: [\n        .library(name: \"dep1\", targets: [\"dep1\"])\n    ],\n    targets: [\n        .target(name: \"dep1\", path: \"./\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings/dep1/code.swift",
    "content": "struct Dep1 {\n  var deprecated: Deprecated1\n}\n\n@available(*, deprecated)\nstruct Deprecated1 {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings/dep2/Package.swift",
    "content": "// swift-tools-version: 5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"dep2\",\n    products: [\n        .library(name: \"dep2\", targets: [\"dep2\"])\n    ],\n    targets: [\n        .target(name: \"dep2\", path: \"./\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings/dep2/code.swift",
    "content": "struct Dep2 {\n  var deprecated: Deprecated2\n}\n\n@available(*, deprecated)\nstruct Deprecated2 {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings2/app/Package.swift",
    "content": "// swift-tools-version: 5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"app\",\n    products: [\n        .executable(name: \"app\", targets: [\"app\"])\n    ],\n    dependencies: [\n        .package(url: \"../dep1\", from: \"1.0.0\"),\n        .package(url: \"../dep2\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .executableTarget(\n          name: \"app\",\n          dependencies: [\n            .product(name: \"dep1\", package: \"dep1\"),\n            .product(name: \"dep2\", package: \"dep2\")\n          ],\n          path: \"./\"\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings2/app/app.swift",
    "content": "import dep1\nimport dep2\n\n@main\nstruct App {\n  public static func main() {\n    print(\"hello, world!\")\n  }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings2/dep1/Package.swift",
    "content": "// swift-tools-version: 5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"dep1\",\n    products: [\n        .library(name: \"dep1\", targets: [\"dep1\"])\n    ],\n    targets: [\n        .target(name: \"dep1\", path: \"./\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings2/dep1/code.swift",
    "content": "struct Dep1 {\n  var deprecated: Deprecated1\n}\n\n@available(*, deprecated)\nstruct Deprecated1 {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings2/dep2/Package.swift",
    "content": "// swift-tools-version: 5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"dep2\",\n    products: [\n        .library(name: \"dep2\", targets: [\"dep2\"])\n    ],\n    targets: [\n        .target(name: \"dep2\", path: \"./\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependenciesWarnings2/dep2/code.swift",
    "content": "struct Dep2 {\n  var deprecated: Deprecated2\n}\n\n@available(*, deprecated)\nstruct Deprecated2 {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/External/dep1/Foo.swift",
    "content": "public let foo = \"Hello\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/External/dep1/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"dep1\",\n    products: [\n        .library(name: \"dep1\", targets: [\"dep1\"]),\n    ],\n    targets: [\n        .target(name: \"dep1\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/External/dep2/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"dep2\",\n    products: [\n        .executable(name: \"dep2\", targets: [\"dep2\"]),\n    ],\n    dependencies: [\n        .package(url: \"../dep1\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"dep2\", dependencies:[ \"dep1\"], path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/External/dep2/main.swift",
    "content": "import dep1\n\nprint(foo)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/External/root/Bar.swift",
    "content": "let bar = 1\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/External/root/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"root\",\n    dependencies: [\n        .package(url: \"../dep2\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"root\", dependencies: [\"dep2\"], path: \"./\"),\n    ]\n)\n\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/Internal/Bar/Bar.swift",
    "content": "public let bar = \"Hello\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/Internal/Foo/main.swift",
    "content": "import Bar\n\nprint(bar)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DependencyEdges/Internal/Package.swift",
    "content": "// swift-tools-version:4.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExtraCommandLineFlags\",\n    targets: [\n        .target(name: \"Bar\", path: \"Bar\"),\n        .target(name: \"Foo\", dependencies: [\"Bar\"], path: \"Foo\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DifferentProductTargetName/Package.swift",
    "content": "// swift-tools-version:5.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .executable(name: \"Foo\", targets: [\"Bar\"]),\n    ],\n    targets: [\n        .target(name: \"Bar\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DifferentProductTargetName/main.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/DistantFutureDeploymentTarget/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"DistantFutureDeploymentTarget\",\n    targets: [\n        .target(name: \"DistantFutureDeploymentTarget\", path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DistantFutureDeploymentTarget/Sources/main.swift",
    "content": "/// This file exists to test the ability to override deployment targets via args passed to swiftc\n/// For this test to work, this file must have an API call which was introduced in a version\n/// higher than the default macOS deployment target that is checked in.\n@available(macOS 41.0, *)\nfunc foo() {}\n\nfoo()\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DoNotFilterLinkerDiagnostics/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"DoNotFilterLinkerDiagnostics\",\n    targets: [\n        .executableTarget(\n            name: \"DoNotFilterLinkerDiagnostics\",\n            linkerSettings: [\n                .unsafeFlags([\"-Lfoobar\"]),\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DoNotFilterLinkerDiagnostics/Sources/DoNotFilterLinkerDiagnostics/main.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n\nprint(\"Hello, world!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DumpPackage/PlayingCard/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"PlayingCard\",\n    products: [\n        .library(name: \"PlayingCard\", targets: [\"PlayingCard\"]),\n    ],\n    targets: [\n        .target(name: \"PlayingCard\", path: \"src\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DumpPackage/PlayingCard/src/PlayingCard.swift",
    "content": "public struct PlayingCard: Equatable {\n    let rank: Rank\n    let suit: Suit\n\n    public init(rank: Rank, suit: Suit) {\n        self.rank = rank\n        self.suit = suit\n    }\n}\n\n// MARK: - Comparable\n\nextension PlayingCard: Comparable {}\n\npublic func <(lhs: PlayingCard, rhs: PlayingCard) -> Bool {\n    return lhs.suit < rhs.suit || (lhs.suit == rhs.suit && lhs.rank < rhs.rank)\n}\n\n// MARK: - CustomStringConvertible\n\nextension PlayingCard : CustomStringConvertible {\n    public var description: String {\n        return \"\\(suit)\\(rank)\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DumpPackage/PlayingCard/src/Rank.swift",
    "content": "public enum Rank : Int {\n    case Ace = 1\n    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten\n    case Jack, Queen, King\n}\n\n// MARK: - Comparable\n\nextension Rank : Comparable {}\n\npublic func <(lhs: Rank, rhs: Rank) -> Bool {\n    switch (lhs, rhs) {\n    case (_, _) where lhs == rhs:\n        return false\n    case (.Ace, _):\n        return false\n    default:\n        return lhs.rawValue < rhs.rawValue\n    }\n}\n\n// MARK: - CustomStringConvertible\n\nextension Rank : CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .Ace: return \"A\"\n        case .Jack: return \"J\"\n        case .Queen: return \"Q\"\n        case .King: return \"K\"\n        default:\n            return \"\\(rawValue)\"\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DumpPackage/PlayingCard/src/Suit.swift",
    "content": "public enum Suit: String {\n    case Spades, Hearts, Diamonds, Clubs\n}\n\n// MARK: - Comparable\n\nextension Suit: Comparable {}\n\npublic func <(lhs: Suit, rhs: Suit) -> Bool {\n    switch (lhs, rhs) {\n    case (_, _) where lhs == rhs:\n        return false\n    case (.Spades, _),\n    (.Hearts, .Diamonds), (.Hearts, .Clubs),\n    (.Diamonds, .Clubs):\n        return false\n    default:\n        return true\n    }\n}\n\n// MARK: - CustomStringConvertible\n\nextension Suit : CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .Spades: return \"♠︎\"\n        case .Hearts: return \"♡\"\n        case .Diamonds: return \"♢\"\n        case .Clubs: return \"♣︎\"\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DumpPackage/app/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"Dealer\",\n    defaultLocalization: \"en\",\n    platforms: [\n        .macOS(.v10_13),\n        .iOS(.v12),\n        .tvOS(.v12),\n        .watchOS(.v5)\n    ],\n    dependencies: [\n        .package(path: \"../PlayingCard\"),\n    ],\n    targets: [\n        .target(\n            name: \"Dealer\",\n            dependencies: [\"PlayingCard\"],\n            path: \"./\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DumpPackage/app/main.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nimport PlayingCard\n\nlet hand: [PlayingCard] = [\n    .init(rank: .Ace, suit: .Hearts),\n    .init(rank: .King, suit: .Spades),\n]\n\nfor card in hand {\n    print(card)\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/exec/Package.swift",
    "content": "// swift-tools-version:6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"exec\",\n    dependencies: [\n        .package(path: \"../secondDyna\")\n    ],\n    targets: [\n        .executableTarget(\n            name: \"exec\",\n            dependencies: [\"secondDyna\"]),\n        .testTarget(\n            name: \"DynaTests\",\n            dependencies: [\"exec\"])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/exec/README.md",
    "content": "# exec\n\nA description of this package.\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/exec/Sources/exec/main.swift",
    "content": "import secondDyna\n\nprint(secondDyna.hello())\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/exec/Tests/DynaTests/Tests.swift",
    "content": "error\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/firstDyna/Package.swift",
    "content": "// swift-tools-version:5.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"firstDyna\",\n    products: [\n        .library(\n            name: \"firstDyna\",\n            type: .dynamic,\n            targets: [\"firstDyna\"])\n    ],\n    targets: [\n        .target(\n            name: \"firstDyna\",\n            dependencies: [\"Core\"]),\n        .target(\n            name: \"Core\",\n            dependencies: [])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/firstDyna/README.md",
    "content": "# firstDyna\n\nA description of this package.\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/firstDyna/Sources/Core/Core.c",
    "content": "#include<Core.h>\n\nchar* hello() {\n    return \"Hello\";\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/firstDyna/Sources/Core/include/Core.h",
    "content": "\nchar* hello();\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/firstDyna/Sources/firstDyna/firstDyna.swift",
    "content": "import Core\n\npublic func hello() -> String {\n    return String(cString: Core.hello())\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/secondDyna/Package.swift",
    "content": "// swift-tools-version:5.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"secondDyna\",\n    products: [\n        .library(\n            name: \"secondDyna\",\n            type: .dynamic,\n            targets: [\"secondDyna\"])\n    ],\n    dependencies: [\n        .package(path: \"../firstDyna\")\n    ],\n    targets: [\n        .target(\n            name: \"secondDyna\",\n            dependencies: [\"firstDyna\"])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/secondDyna/README.md",
    "content": "# secondDyna\n\nA description of this package.\n"
  },
  {
    "path": "Fixtures/Miscellaneous/DynamicProduct/secondDyna/Sources/secondDyna/secondDyna.swift",
    "content": "import firstDyna \n\npublic func hello() -> String {\n    return firstDyna.hello()\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EchoExecutable/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"EchoExecutable\",\n    products: [\n        .executable(name: \"secho\", targets: [\"secho\"])\n    ],\n    targets: [\n        .target(name: \"secho\", dependencies: []),\n        .testTarget(name: \"TestSuite\")\n    ])\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EchoExecutable/Sources/secho/main.swift",
    "content": "#if canImport(Glibc)\n\timport Glibc\n#elseif canImport(Musl)\n\timport Musl\n#elseif canImport(Android)\n\timport Android\n#elseif canImport(Darwin.C)\n\timport Darwin.C\n#elseif canImport(ucrt)\n\timport ucrt\n\tlet PATH_MAX = 260\n\ttypealias Int = Int32\n#endif\n\nlet cwd = getcwd(nil, Int(PATH_MAX))\ndefer { free(cwd) }\nlet workingDirectory = String(validatingUTF8: cwd!)!\nlet values = [workingDirectory] + Array(CommandLine.arguments.dropFirst())\nprint(values.map({ \"\\\"\\($0)\\\"\" }).joined(separator: \" \"))"
  },
  {
    "path": "Fixtures/Miscellaneous/EchoExecutable/Tests/TestSuite/Tests.swift",
    "content": "import XCTest\n\nfinal class TestCase: XCTestCase {\n    func testFoo() {\n        XCTAssertTrue(true)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EchoExecutable/echo.bat",
    "content": "echo sentinel\necho %*\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EchoExecutable/echo.sh",
    "content": "#!/bin/sh\n\necho sentinel\necho \"$@\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EchoExecutable/toolset.json",
    "content": "{\n  \"debugger\": { \"path\": \"echo.sh\" },\n  \"testRunner\": { \"path\": \"echo.sh\" },\n  \"schemaVersion\" : \"1.0\",\n  \"rootPath\" : \".\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EchoExecutable/toolset.win32.json",
    "content": "{\n  \"debugger\": { \"path\": \"echo.bat\" },\n  \"testRunner\": { \"path\": \"echo.bat\" },\n  \"schemaVersion\" : \"1.0\",\n  \"rootPath\" : \".\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Edit/App/Package.swift",
    "content": "// swift-tools-version:5.3\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"App\",\n    dependencies: [\n        .package(name: \"Foo\", url: \"../Foo\", .branch(\"main\")),\n        .package(name: \"Bar\", url: \"../Bar\", .branch(\"main\")),\n    ],\n    targets: [\n        .target(name: \"App\", dependencies: [\n            .product(name: \"Foo\", package: \"Foo\"),\n            .product(name: \"Bar\", package: \"Bar\"),\n        ], path: \"./src\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Edit/App/src/main.swift",
    "content": "import Foo\nimport Bar\n\npublic func main() {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Edit/Bar/Bar.swift",
    "content": "public func hello() {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Edit/Bar/Package.swift",
    "content": "// swift-tools-version:5.3\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    products: [\n        .library(name: \"Bar\", targets: [\"Bar\"]),\n    ],\n    targets: [\n        .target(name: \"Bar\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Edit/Foo/Foo.swift",
    "content": "public func hello() {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Edit/Foo/Package.swift",
    "content": "// swift-tools-version:5.3\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EmptyTestsPkg/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EmptyTestsPkg/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"EmptyTestsPkg\",\n    targets: [\n        .target(\n            name: \"EmptyTestsPkg\",\n            dependencies: []),\n        .testTarget(\n            name: \"EmptyTestsPkgTests\",\n            dependencies: [\"EmptyTestsPkg\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EmptyTestsPkg/Sources/EmptyTestsPkg/EmptyTestsPkg.swift",
    "content": "struct EmptyTests {\n\n    var text = \"Hello, World!\"\n    var bool = false\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/EmptyTestsPkg/Tests/EmptyTestsPkgTests/EmptyTestsTests.swift",
    "content": "import XCTest\n@testable import EmptyTestsPkg\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Errors/FatalErrorInSingleXCTest/TypeLibrary/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\nxcuserdata/\nDerivedData/\n.swiftpm/configuration/registries.json\n.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata\n.netrc\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Errors/FatalErrorInSingleXCTest/TypeLibrary/Package.swift",
    "content": "// swift-tools-version:5.9\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"TypeLibrary\",\n    products: [\n        // Products define the executables and libraries a package produces, making them visible to other packages.\n        .library(\n            name: \"TypeLibrary\",\n            targets: [\"TypeLibrary\"]),\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package, defining a module or a test suite.\n        // Targets can depend on other targets in this package and products from dependencies.\n        .target(\n            name: \"TypeLibrary\"),\n        .testTarget(\n            name: \"TypeLibraryTests\",\n            dependencies: [\"TypeLibrary\"]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Errors/FatalErrorInSingleXCTest/TypeLibrary/Sources/TypeLibrary/TypeLibrary.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Errors/FatalErrorInSingleXCTest/TypeLibrary/Tests/TypeLibraryTests/TypeLibraryTests.swift",
    "content": "func testExample() throws {\n    let x = 0\n    let y = 1 / x\n    print(y)\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/FooExec/FooExec.swift",
    "content": "import FooLib1\nimport FooLib2\n\npublic class FooExec {\n    public var foo: FooLib1\n    public var bar: FooLib2\n    \n    public init() {\n        foo = FooLib1()\n        bar = FooLib2() \n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/FooExec/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"FooExec\",\n    products: [\n        .executable(name: \"FooExec\", targets: [\"FooExec\"]),\n    ],\n    dependencies: [\n        .package(url: \"../FooLib1\", from: \"1.0.0\"),\n        .package(url: \"../FooLib2\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"FooExec\", dependencies: [\"FooLib1\", \"FooLib2\"], path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/FooExec/main.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/FooLib1/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"FooLib1\",\n    products: [\n        .library(name: \"FooLib1\", targets: [\"FooLib1\"]),\n        .executable(name: \"cli\", targets: [\"cli\"]),\n    ],\n    targets: [\n        .target(name: \"FooLib1\"),\n        .target(name: \"cli\", dependencies: [\"FooLib1\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/FooLib1/Sources/FooLib1/FooLib1.swift",
    "content": "public class FooLib1 {\n    public var foo: Int\n    \n    public init() {\n        foo = 0\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/FooLib1/Sources/cli/main.swift",
    "content": "import FooLib1\n\nprint(FooLib1())\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/FooLib2/FooLib2.swift",
    "content": "public class FooLib2 {\n    public var foo: Int\n    \n    public init() {\n        foo = 0\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/FooLib2/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"FooLib2\",\n    products: [\n        .library(name: \"FooLib2\", targets: [\"FooLib2\"]),\n    ],\n    targets: [\n        .target(name: \"FooLib2\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/app/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"28_exact_dependencies\",\n    dependencies: [\n        .package(url: \"../FooExec\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"28_exact_dependencies\", dependencies: [\"FooExec\"], path: \"./\"),\n    ]\n)\n\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExactDependencies/app/main.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/ExeTest/Package.swift",
    "content": "// swift-tools-version: 5.5\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExeTest\",\n    targets: [\n        .executableTarget(\n            name: \"Exe\",\n            dependencies: []\n        ),\n        .testTarget(\n            name: \"ExeTests\",\n            dependencies: [\"Exe\"]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExeTest/Sources/Exe/main.swift",
    "content": "public func GetGreeting() -> String {\n    return \"Hello\"\n}\n\nprint(\"\\(GetGreeting()), world!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExeTest/Tests/ExeTests/ExeTests.swift",
    "content": "import XCTest\nimport Exe\n\nfinal class ExeTestTests: XCTestCase {\n    \n    func testExample() throws {\n        // This is an example of a test case that tries to imports an executable target.\n        XCTAssertEqual(Exe.GetGreeting(), \"Hello\")\n    }\n\n    static var allTests = [\n        (\"testExample\", testExample),\n    ]\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExecutableTargetWithTwoProducts/Foo.swift",
    "content": "@main struct Entry {\n    static func main() {\n        // Ensure that Bar can be referenced as a member of the module named Foo,\n        // even though the executable target Foo may have been merged into the Exe1 or Exe2 products.\n        let x = Foo.Bar()\n    }\n}\n\nstruct Bar {}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ExecutableTargetWithTwoProducts/Package.swift",
    "content": "// swift-tools-version:6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .executable(name: \"Exe1\", targets: [\"Foo\"]),\n        .executable(name: \"Exe2\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .executableTarget(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/FlatPackage/MyExec.swift",
    "content": "@main\npublic struct MyExec {\n    public private(set) var text = \"Hello, World!\"\n\n    public static func main() {\n        print(MyExec().text)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/FlatPackage/MyTest.swift",
    "content": "import XCTest\n@testable import MyExec\n\nfinal class MyTest: XCTestCase {\n    func testExample() throws {\n        XCTAssertEqual(MyExec().text, \"Hello, World!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/FlatPackage/Package.swift",
    "content": "// swift-tools-version: 5.5\nimport PackageDescription\n\nlet execSrcFiles = [\"MyExec.swift\"]\nlet testSrcFiles = [\"MyTest.swift\"]\nlet variousFiles = [\"README.md\"]\n\nlet package = Package(\n    name: \"FlatPackage\",\n    dependencies: [\n    ],\n    targets: [\n        .executableTarget(\n            name: \"MyExec\",\n            dependencies: [],\n            path: \".\",\n            exclude: testSrcFiles + variousFiles,\n            sources: execSrcFiles\n        ),\n        .testTarget(\n            name: \"MyTest\",\n            dependencies: [\"MyExec\"],\n            path: \".\",\n            exclude: execSrcFiles + variousFiles,\n            sources: testSrcFiles\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/FlatPackage/README.md",
    "content": "# FlatPackage\n\nA description of this package.\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ImportOfMissingDependency/Package.swift",
    "content": "// swift-tools-version:5.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"VerificationTestPackage\",\n    products: [\n      .executable(name: \"BExec\", targets: [\"B\"]),\n    ],\n    dependencies: [\n\n    ],\n    targets: [\n        .target(\n            name: \"A\",\n            dependencies: []),\n        .target(\n            name: \"B\",\n            dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ImportOfMissingDependency/Sources/A/A.swift",
    "content": "import B\npublic func bar(x: Int) -> Int {\n    return 11 + foo(x: x)\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ImportOfMissingDependency/Sources/B/B.swift",
    "content": "public func foo(x: Int) -> Int {\n    return 11 + x\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ImportOfMissingDependency/Sources/B/main.swift",
    "content": "print(baz(x: 11))\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LTO/SwiftAndCTargets/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\nxcuserdata/\nDerivedData/\n.swiftpm/configuration/registries.json\n.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata\n.netrc\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LTO/SwiftAndCTargets/Package.swift",
    "content": "// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"SwiftAndCTargets\",\n    targets: [\n        .target(name: \"cLib\"),\n        .executableTarget(name: \"exe\", dependencies: [\"cLib\", \"swiftLib\"]),\n        .target(name: \"swiftLib\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LTO/SwiftAndCTargets/Sources/cLib/cLib.c",
    "content": "#include <stdio.h>\n\n#include \"include/cLib.h\"\n\nvoid cPrint(int value) {\n    printf(\"c value: %i\\n\", value);\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LTO/SwiftAndCTargets/Sources/cLib/include/cLib.h",
    "content": "#pragma once\n\nextern void cPrint(int);\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LTO/SwiftAndCTargets/Sources/exe/main.swift",
    "content": "import swiftLib\nimport cLib\n\ncPrint(1)\nswiftPrint(value: 2)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LTO/SwiftAndCTargets/Sources/swiftLib/swiftLib.swift",
    "content": "public func swiftPrint(value: Int) {\n  print(\"swift value: \\(value)\")\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LibraryEvolution/Package.swift",
    "content": "// swift-tools-version:5.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"LibraryEvolution\",\n    products: [\n    ],\n    targets: [\n        .target(name: \"A\", dependencies: [], swiftSettings: [.unsafeFlags([\"-enable-library-evolution\"])]),\n        .target(name: \"B\", dependencies: [\"A\"], swiftSettings: [.unsafeFlags([\"-enable-library-evolution\"])]),\n    ])\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LibraryEvolution/Sources/A/A.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/LibraryEvolution/Sources/B/B.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/LibraryEvolutionLinuxXCF/SwiftFramework/Package.swift",
    "content": "// swift-tools-version:6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"SwiftFramework\",\n    products: [\n        .library(name: \"SwiftFramework\", type: .dynamic, targets: [\"SwiftFramework\"]),\n    ],\n    targets: [\n        .target(\n            name: \"SwiftFramework\",\n            swiftSettings: [.unsafeFlags([\"-enable-library-evolution\"])]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LibraryEvolutionLinuxXCF/SwiftFramework/Sources/SwiftFramework/SwiftFramework.swift",
    "content": "public enum SwiftFrameworkWithEvolution\n{\n    case v1\n    case v2\n\n    public\n    static var latest:Self { .v2 }\n}"
  },
  {
    "path": "Fixtures/Miscellaneous/LibraryEvolutionLinuxXCF/TestBinary/Package.swift",
    "content": "// swift-tools-version:6.0\n\nimport PackageDescription\n\nlet package = Package(name: \"TestBinary\",\n    products: [\n        .executable(name: \"TestBinary\", targets: [\"TestBinary\"]),\n    ],\n    targets: [\n        .binaryTarget(name: \"SwiftFramework\", path: \"SwiftFramework.xcframework\"),\n        .executableTarget(name: \"TestBinary\",\n            dependencies: [\n                .target(name: \"SwiftFramework\"),\n            ]\n        ),\n    ]\n)"
  },
  {
    "path": "Fixtures/Miscellaneous/LibraryEvolutionLinuxXCF/TestBinary/Sources/TestBinary/Main.swift",
    "content": "import SwiftFramework\n\nprint(\"Latest Framework with LibraryEvolution version: \\(SwiftFrameworkWithEvolution.latest)\")"
  },
  {
    "path": "Fixtures/Miscellaneous/LocalPackageAsURL/Bar/Package.swift",
    "content": "// swift-tools-version:5.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    dependencies: [\n        .package(url: \"../Foo\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"Bar\", dependencies: [\"Foo\"], path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LocalPackageAsURL/Bar/main.swift",
    "content": "import Foo\n\nfoo()\nprint(\"here\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LocalPackageAsURL/Foo/Foo.swift",
    "content": "public func foo() {\n\t{}()\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/LocalPackageAsURL/Foo/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/MissingDependency/Bar/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    dependencies: [\n        .package(url: \"../NonExistentPackage\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"Bar\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/MissingDependency/Bar/main.swift",
    "content": "import Foo\n\nfoo()\n"
  },
  {
    "path": "Fixtures/Miscellaneous/MultipleExecutables/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"EchoExecutable\",\n    products: [\n        .executable(name: \"exec1\", targets: [\"exec1\"]),\n        .executable(name: \"exec2\", targets: [\"exec2\"]),\n        .library(name: \"lib1\", targets: [\"lib1\"]),\n    ],\n    targets: [\n        .target(name: \"exec1\"),\n        .target(name: \"exec2\"),\n        .target(name: \"lib1\"),\n    ]\n)"
  },
  {
    "path": "Fixtures/Miscellaneous/MultipleExecutables/Sources/exec1/main.swift",
    "content": "print(\"1\")"
  },
  {
    "path": "Fixtures/Miscellaneous/MultipleExecutables/Sources/exec2/main.swift",
    "content": "print(\"2\")"
  },
  {
    "path": "Fixtures/Miscellaneous/MultipleExecutables/Sources/lib1/lib.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/bar/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/bar/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"bar\",\n    products: [\n        .library(name: \"bar\", targets: [\"bar\"]),\n    ],\n    targets: [\n        .target(name: \"bar\", path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/bar/Sources/bar.swift",
    "content": "public let theValue = 5\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/baz/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/baz/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"baz\",\n    products: [\n        .library(name: \"baz\", targets: [\"baz\"]),\n    ],\n    targets: [\n        .target(name: \"baz\", path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/baz/Sources/baz.swift",
    "content": "struct baz {\n\n    var text = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/foo/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/foo/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"foo\",\n    dependencies: [\n        .package(url: \"../bar\", from: \"1.0.0\"),\n        .package(url: \"../baz\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(\n            name: \"foo\",\n            dependencies: [\"bar\", \"baz\"],\n            path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageEdit/foo/Sources/main.swift",
    "content": "import bar\nprint(bar.theValue)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/appPkg/Package.swift",
    "content": "// swift-tools-version:5.9\nimport PackageDescription\n\nlet package = Package(\n    name: \"appPkg\",\n    dependencies: [\n        .package(url: \"../fooPkg\", from: \"1.0.0\"),\n        .package(url: \"../barPkg\", from: \"1.0.0\")\n    ],\n    targets: [\n        .executableTarget(name: \"exe\", dependencies: [\"App\"]),\n        .target(name: \"App\",\n                dependencies: [\n                    .product(name: \"Foo\", package: \"fooPkg\"),\n                    .product(name: \"Bar\", package: \"barPkg\"),\n                ])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/appPkg/Sources/App/file.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/appPkg/Sources/exe/main.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/barPkg/Package.swift",
    "content": "// swift-tools-version:5.8\nimport PackageDescription\n\nlet package = Package(\n    name: \"barPkg\",\n    products: [\n        .library(name: \"Bar\", targets: [\"Bar\"]),\n    ],\n    targets: [\n        .target(name: \"Bar\", dependencies: [\"Baz\"]),\n        .target(name: \"Baz\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/barPkg/Sources/Bar/file.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/barPkg/Sources/Baz/file.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/fooPkg/Package.swift",
    "content": "// swift-tools-version:5.9\nimport PackageDescription\n\nlet package = Package(\n    name: \"fooPkg\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", dependencies: [\"Zoo\"]),\n        .target(name: \"Zoo\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/fooPkg/Sources/Foo/file.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/PackageNameFlag/fooPkg/Sources/Zoo/file.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithMalformedLibraryProduct/Package.swift",
    "content": "// swift-tools-version: 5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"PackageWithMalformedLibraryProduct\",\n    products: [\n        .library(\n            name: \"PackageWithMalformedLibraryProduct\",\n            targets: [\"PackageWithMalformedLibraryProduct\"]),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"PackageWithMalformedLibraryProduct\")\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithMalformedLibraryProduct/Sources/PackageWithMalformedLibraryProduct/main.swift",
    "content": "print(\"Hello World\")"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithNonc99NameModules/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"PackageWithNonc99NameModules\",\n    targets: [\n        .target(name: \"A-B\", dependencies: [\"B-C\"]),\n        .target(name: \"B-C\", dependencies: []),\n        .target(name: \"C D\", dependencies: []),\n    ]\n)\n\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithNonc99NameModules/Sources/A-B/ab.swift",
    "content": "import B_C\n\nfunc ab() {\n    bc()\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithNonc99NameModules/Sources/B-C/bc.swift",
    "content": "public func bc() {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithNonc99NameModules/Sources/C D/cd.swift",
    "content": "public func bc() {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithResource/Package.swift",
    "content": "// swift-tools-version:5.3\nimport PackageDescription\n\nlet package = Package(\n    name: \"AwesomeResources\",\n    targets: [\n        .target(name: \"AwesomeResources\", resources: [.copy(\"hello.txt\")]),\n        .testTarget(name: \"AwesomeResourcesTest\", dependencies: [\"AwesomeResources\"], resources: [.copy(\"world.txt\")])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithResource/Sources/AwesomeResources/AwesomeResource.swift",
    "content": "import Foundation\n\npublic struct AwesomeResource {\n    public init() {}\n    public let hello = try! String(contentsOf: Bundle.module.url(forResource: \"hello\", withExtension: \"txt\")!)\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithResource/Sources/AwesomeResources/hello.txt",
    "content": "hello"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithResource/Tests/AwesomeResourcesTest/MyTests.swift",
    "content": "import XCTest\nimport Foundation\nimport AwesomeResources\n\nfinal class MyTests: XCTestCase {\n    func testFoo() {\n        XCTAssertTrue(AwesomeResource().hello == \"hello\")\n    }\n    func testBar() {\n        let world = try! String(contentsOf: Bundle.module.url(forResource: \"world\", withExtension: \"txt\")!)\n        XCTAssertTrue(world == \"world\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PackageWithResource/Tests/AwesomeResourcesTest/world.txt",
    "content": "world"
  },
  {
    "path": "Fixtures/Miscellaneous/ParallelTestsPkg/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParallelTestsPkg/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"ParallelTestsPkg\",\n    targets: [\n        .target(\n            name: \"ParallelTestsPkg\",\n            dependencies: []),\n        .testTarget(\n            name: \"ParallelTestsPkgTests\",\n            dependencies: [\"ParallelTestsPkg\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParallelTestsPkg/Sources/ParallelTestsPkg/ParallelTestsPkg.swift",
    "content": "struct ParallelTests {\n\n    var text = \"Hello, World!\"\n    var bool = false\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParallelTestsPkg/Tests/ParallelTestsPkgTests/ParallelTestsFailureTests.swift",
    "content": "import XCTest\n@testable import ParallelTestsPkg\n\nclass ParallelTestsFailureTests: XCTestCase {\n\n    func testSureFailure() {\n        XCTFail(\"Giving up is the only sure way to fail.\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParallelTestsPkg/Tests/ParallelTestsPkgTests/ParallelTestsTests.swift",
    "content": "import XCTest\n@testable import ParallelTestsPkg\n\nclass ParallelTestsTests: XCTestCase {\n\n    func testExample1() {\n        XCTAssertEqual(ParallelTests().text, \"Hello, World!\")\n    }\n\n    func testExample2() {\n        XCTAssertEqual(ParallelTests().bool, false)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseAsLibrary/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ParseAsLibrary\",\n    products: [],\n    targets: [\n        .executableTarget(name: \"ExecutableTargetOneFileNamedMainMainAttr\"),\n        .executableTarget(name: \"ExecutableTargetOneFileNamedMainNoMainAttr\"),\n        .executableTarget(name: \"ExecutableTargetOneFileNotNamedMainMainAttr\"),\n        .executableTarget(name: \"ExecutableTargetOneFileNotNamedMainNoMainAttr\"),\n        .executableTarget(name: \"ExecutableTargetTwoFiles\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseAsLibrary/Sources/ExecutableTargetOneFileNamedMainMainAttr/main.swift",
    "content": "@main struct Entry {\n    static func main() {}\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseAsLibrary/Sources/ExecutableTargetOneFileNamedMainNoMainAttr/main.swift",
    "content": "print(42)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseAsLibrary/Sources/ExecutableTargetOneFileNotNamedMainMainAttr/othername.swift",
    "content": "@main struct Entry {\n    static func main() {}\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseAsLibrary/Sources/ExecutableTargetOneFileNotNamedMainNoMainAttr/othername.swift",
    "content": "print(42)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseAsLibrary/Sources/ExecutableTargetTwoFiles/one.swift",
    "content": "@main struct Entry {\n    static func main() {}\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseAsLibrary/Sources/ExecutableTargetTwoFiles/two.swift",
    "content": "func foo() {}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseableInterfaces/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"ParseableInterfaces\",\n    products: [\n    ],\n    targets: [\n        .target(name: \"A\", dependencies: []),\n        .target(name: \"B\", dependencies: [\"A\"]),\n    ])\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ParseableInterfaces/Sources/A/A.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/ParseableInterfaces/Sources/B/B.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/CSystemModule/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"CSystemModule\",\n    pkgConfig: \"libSystemModule\",\n    providers: [\n        .brew([\"SystemModule\"]),\n    ]\n)\n\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/CSystemModule/module.modulemap",
    "content": "module CSystemModule {\n    header \"shim.h\"\n    link \"SystemModule\"\n    export *\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/CSystemModule/shim.h",
    "content": "#include <SystemModule.h>\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/SystemModule/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"SystemModule\",\n    products: [\n        .library(name: \"SystemModule\", targets: [\"SystemModule\"]),\n    ],\n    targets: [\n        .target(name: \"SystemModule\", path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/SystemModule/Sources/SystemModule.c",
    "content": "int foo() {\n    int a = 5;\n    int b = a;\n    a = b;\n    return a;\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/SystemModule/Sources/include/SystemModule.h",
    "content": "int foo();\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/SystemModuleUser/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"SystemModuleUser\",\n    dependencies: [\n        .package(url: \"../CSystemModule\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"SystemModuleUser\", path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/SystemModuleUser/Sources/main.swift",
    "content": "import CSystemModule\n\nprint(\"\\(foo())\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/SystemModuleUserClang/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"SystemModuleUserClang\",\n    dependencies: [\n        .package(url: \"../CSystemModule\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"SystemModuleUserClang\", path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PkgConfig/SystemModuleUserClang/Sources/main.c",
    "content": "#include <SystemModule.h>\n#include <stdio.h>\n\nint main() {\n    printf(\"%d\", foo());\n    return 0;\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PluginGeneratedResources/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"PluginGeneratedResources\",\n    targets: [\n        .executableTarget(name: \"PluginGeneratedResources\", plugins: [\"Generator\"]),\n        .plugin(name: \"Generator\", capability: .buildTool()),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PluginGeneratedResources/Plugins/Generator/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n#if os(Android)\nlet touchExe = \"/system/bin/touch\"\nlet touchArgs: [String] = []\n#elseif os(Windows)\nlet touchExe = \"C:/Windows/System32/cmd.exe\"\nlet touchArgs = [\"/c\", \"copy\", \"NUL\"]\n#else\nlet touchExe = \"/usr/bin/touch\"\nlet touchArgs: [String] = []\n#endif\n\n@main\nstruct GeneratorPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n        return [\n            .prebuildCommand(\n                displayName: \"Generating empty file\",\n                executable: .init(fileURLWithPath: touchExe),\n                arguments: touchArgs + [String(cString: (context.pluginWorkDirectoryURL.appending(path: \"best.txt\") as NSURL).fileSystemRepresentation)],\n                outputFilesDirectory: context.pluginWorkDirectoryURL\n            )\n        ]\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/PluginGeneratedResources/Sources/PluginGeneratedResources/PluginGeneratedResources.swift",
    "content": "import Foundation\n\n@main\npublic struct PluginGeneratedResources {\n    public private(set) var text = \"Hello, World!\"\n\n    public static func main() {\n        let path = Bundle.module.path(forResource: \"best\", ofType: \"txt\")\n        let exists = FileManager.default.fileExists(atPath: path!)\n        assert(exists, \"generated file is missing\")\n        print(PluginGeneratedResources().text)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/AmbiguousCommands/Dependencies/A/Package.swift",
    "content": "// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"A\",\n    products: [\n        .plugin(\n            name: \"A\",\n            targets: [\"A\"]),\n    ],\n    targets: [\n        .plugin(\n            name: \"A\",\n            capability: .command(intent: .custom(\n                verb: \"A\",\n                description: \"prints hello\"\n            ))\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/AmbiguousCommands/Dependencies/A/Plugins/A.swift",
    "content": "import PackagePlugin\n\n@main\nstruct A: CommandPlugin {\n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        print(\"Hello A!\")\n    }\n}\n\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/AmbiguousCommands/Dependencies/B/Package.swift",
    "content": "// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"B\",\n    products: [\n        .plugin(\n            name: \"B\",\n            targets: [\"B\"]),\n    ],\n    targets: [\n        .plugin(\n            name: \"B\",\n            capability: .command(intent: .custom(\n                verb: \"A\",\n                description: \"prints hello\"\n            ))\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/AmbiguousCommands/Dependencies/B/Plugins/B.swift",
    "content": "import PackagePlugin\n\n@main\nstruct B: CommandPlugin {\n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        print(\"Hello B!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/AmbiguousCommands/Package.swift",
    "content": "// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"AmbiguousCommands\",\n    dependencies: [\n        .package(path: \"Dependencies/A\"),\n        .package(path: \"Dependencies/B\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"AmbiguousCommands\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/AmbiguousCommands/Sources/main.swift",
    "content": "print(\"Hello, world!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryTargetExePlugin/Dependency/MyBinaryTargetExeArtifactBundle.artifactbundle/info.json",
    "content": "{\n    \"schemaVersion\": \"1.0\",\n    \"artifacts\": {\n        \"mytool\": {\n            \"type\": \"executable\",\n            \"version\": \"1.2.3\",\n            \"variants\": [\n                {\n                    \"path\": \"mytool-macos/mytool\",\n                    \"supportedTriples\": [\"x86_64-apple-macosx\", \"arm64-apple-macosx\"]\n                },\n                {\n                    \"path\": \"mytool-linux/mytool\",\n                    \"supportedTriples\": [\"x86_64-unknown-linux-gnu\", \"aarch64-unknown-linux-gnu\"]\n                }\n            ]\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryTargetExePlugin/Dependency/MyBinaryTargetExeArtifactBundle.artifactbundle/mytool-linux/mytool",
    "content": "#!/bin/bash\n\nprint_usage() {\n    echo \"usage: ${0##*/} [--verbose] <in> <out>\"\n}\n\n# Parse arguments until we find '--' or an argument that isn't an option.\nuntil [ $# -eq 0 ]\ndo\n    case \"$1\" in\n        --verbose) verbose=1; shift;;\n        --) shift; break;;\n        -*) echo \"unknown option: ${1}\"; print_usage; exit 1; shift;;\n        *) break;;\n    esac\ndone\n\n# Print usage and leave if we don't have exactly two arguments.\nif [ $# -ne 2 ]; then\n    print_usage\n    exit 1\nfi\n\n# For our sample tool we just copy from one to the other.\nif [ $verbose != 0 ]; then\n    echo \"[${0##*/}-linux] '$1' '$2'\"\nfi\n\ncp \"$1\" \"$2\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryTargetExePlugin/Dependency/MyBinaryTargetExeArtifactBundle.artifactbundle/mytool-macos/mytool",
    "content": "#!/bin/bash\n\nprint_usage() {\n    echo \"usage: ${0##*/} [--verbose] <in> <out>\"\n}\n\n# Parse arguments until we find '--' or an argument that isn't an option.\nuntil [ $# -eq 0 ]\ndo\n    case \"$1\" in\n        --verbose) verbose=1; shift;;\n        --) shift; break;;\n        -*) echo \"unknown option: ${1}\"; print_usage; exit 1; shift;;\n        *) break;;\n    esac\ndone\n\n# Print usage and leave if we don't have exactly two arguments.\nif [ $# -ne 2 ]; then\n    print_usage\n    exit 1\nfi\n\n# For our sample tool we just copy from one to the other.\nif [ $verbose != 0 ]; then\n    echo \"[${0##*/}-macosx] '$1' '$2'\"\nfi\n\ncp \"$1\" \"$2\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryTargetExePlugin/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyBinaryTargetExePlugin\",\n\n    products: [\n        .executable(\n            name: \"MyPluginExe\",\n            targets: [\"MyPluginExe\"]\n        ),\n        .plugin(\n            name: \"MyPlugin\",\n            targets: [\"MyPlugin\"]\n        ),\n        .executable(\n            name: \"MyBinaryTargetExe\",\n            targets: [\"MyBinaryTargetExeArtifactBundle\"]\n        ),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"MyPluginExe\",\n            dependencies: [],\n            exclude: [],\n        ),\n\n        .plugin(\n            name: \"MyPlugin\",\n            capability: .buildTool(),\n            dependencies: [\"MyPluginExe\", \"MyBinaryTargetExeArtifactBundle\"]\n        ),\n        .binaryTarget(\n            name: \"MyBinaryTargetExeArtifactBundle\",\n            path: \"Dependency/MyBinaryTargetExeArtifactBundle.artifactbundle\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryTargetExePlugin/Plugins/MyPlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    \n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from MyPlugin!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryTargetExePlugin/Sources/MyPluginExe/main.swift",
    "content": "print(\"It's Me MyPluginExe\\n\")"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryToolProductPlugin/Dependency/Binaries/MyVendedSourceGenBuildTool.artifactbundle/info.json",
    "content": "{\n    \"schemaVersion\": \"1.0\",\n    \"artifacts\": {\n        \"mytool\": {\n            \"type\": \"executable\",\n            \"version\": \"1.2.3\",\n            \"variants\": [\n                {\n                    \"path\": \"mytool-macos/mytool\",\n                    \"supportedTriples\": [\"x86_64-apple-macosx\", \"arm64-apple-macosx\"]\n                },\n                {\n                    \"path\": \"mytool-linux/mytool\",\n                    \"supportedTriples\": [\"x86_64-unknown-linux-gnu\", \"aarch64-unknown-linux-gnu\"]\n                }\n            ]\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryToolProductPlugin/Dependency/Binaries/MyVendedSourceGenBuildTool.artifactbundle/mytool-linux/mytool",
    "content": "#!/bin/bash\n\nprint_usage() {\n    echo \"usage: ${0##*/} [--verbose] <in> <out>\"\n}\n\n# Parse arguments until we find '--' or an argument that isn't an option.\nuntil [ $# -eq 0 ]\ndo\n    case \"$1\" in\n        --verbose) verbose=1; shift;;\n        --) shift; break;;\n        -*) echo \"unknown option: ${1}\"; print_usage; exit 1; shift;;\n        *) break;;\n    esac\ndone\n\n# Print usage and leave if we don't have exactly two arguments.\nif [ $# -ne 2 ]; then\n    print_usage\n    exit 1\nfi\n\n# For our sample tool we just copy from one to the other.\nif [ $verbose != 0 ]; then\n    echo \"[${0##*/}-linux] '$1' '$2'\"\nfi\n\ncp \"$1\" \"$2\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryToolProductPlugin/Dependency/Binaries/MyVendedSourceGenBuildTool.artifactbundle/mytool-macos/mytool",
    "content": "#!/bin/bash\n\nprint_usage() {\n    echo \"usage: ${0##*/} [--verbose] <in> <out>\"\n}\n\n# Parse arguments until we find '--' or an argument that isn't an option.\nuntil [ $# -eq 0 ]\ndo\n    case \"$1\" in\n        --verbose) verbose=1; shift;;\n        --) shift; break;;\n        -*) echo \"unknown option: ${1}\"; print_usage; exit 1; shift;;\n        *) break;;\n    esac\ndone\n\n# Print usage and leave if we don't have exactly two arguments.\nif [ $# -ne 2 ]; then\n    print_usage\n    exit 1\nfi\n\n# For our sample tool we just copy from one to the other.\nif [ $verbose != 0 ]; then\n    echo \"[${0##*/}-macosx] '$1' '$2'\"\nfi\n\ncp \"$1\" \"$2\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryToolProductPlugin/Dependency/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyBinaryProduct\",\n    products: [\n        .executable(\n            name: \"MyVendedSourceGenBuildTool\",\n            targets: [\"MyVendedSourceGenBuildTool\"]\n        ),    \n    ],\n    targets: [\n        .binaryTarget(\n            name: \"MyVendedSourceGenBuildTool\",\n            path: \"Binaries/MyVendedSourceGenBuildTool.artifactbundle\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryToolProductPlugin/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyBinaryToolPlugin\",\n    dependencies: [\n        .package(path: \"Dependency\"),\n    ],\n    targets: [\n        // A local tool that uses a build tool plugin.\n        .executableTarget(\n            name: \"MyLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        ),\n        // The plugin that generates build tool commands to invoke MySourceGenBuildTool.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                .product(name: \"MyVendedSourceGenBuildTool\", package: \"Dependency\"),\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryToolProductPlugin/Plugins/MySourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Build Tool Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        let inputFiles = target.sourceFiles.filter({ $0.url.pathExtension == \"dat\" })\n        return try inputFiles.map {\n            let inputPath = $0.url\n            let outputName = inputPath.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName:\n                    \"Generating \\(outputName) from \\(inputPath.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"mytool\").url,\n                arguments: [\n                    \"--verbose\",\n                    inputPath.path,\n                    outputPath.path,\n                ],\n                inputFiles: [\n                    inputPath,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BinaryToolProductPlugin/Sources/MyLocalTool/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BuildToolPluginCompilationError/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\nlet package = Package(\n    name: \"MyPackage\",\n    targets: [\n        .target(\n            name: \"MyLibrary\",\n            plugins: [\n                \"MyPlugin\",\n            ]\n        ),\n        .plugin(\n            name: \"MyPlugin\",\n            capability: .buildTool()\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BuildToolPluginCompilationError/Plugins/MyPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n@main\nstruct MyBuildToolPlugin: BuildToolPlugin {\n    func createBuildCommands(\n        context: PluginContext,\n        target: Target\n    ) throws -> [Command] {\n        print(\"This is text from the plugin\")\n        throw \"This is an error from the plugin\"\n        return []\n    }\n\n}\nextension String : Error {}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/BuildToolPluginCompilationError/Sources/MyLibrary/library.swift",
    "content": "public func Foo() { }\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ClientOfPluginWithInternalExecutable/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"ClientOfPluginWithInternalExecutable\",\n    dependencies: [\n        .package(path: \"../PluginWithInternalExecutable\")\n    ],\n    targets: [\n        .executableTarget(\n            name: \"RootTarget\",\n            plugins: [\n                .plugin(name: \"PluginScriptProduct\", package: \"PluginWithInternalExecutable\")\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ClientOfPluginWithInternalExecutable/Sources/RootTarget/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginCompilationError/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\nlet package = Package(\n    name: \"MyPackage\",\n    products: [\n        .library(\n            name: \"MyLibrary\",\n            targets: [\"MyLibrary\"]\n        ),\n        .executable(\n            name: \"MyExecutable\",\n            targets: [\"MyExecutable\"]\n        ),\n    ],\n    targets: [\n        .target(\n            name: \"MyLibrary\"\n        ),\n        .executableTarget(\n            name: \"MyExecutable\",\n            dependencies: [\"MyLibrary\"]\n        ),\n        .plugin(\n            name: \"MyBuildToolPlugin\",\n            capability: .buildTool()\n        ),\n        .plugin(\n            name: \"MyCommandPlugin\",\n            capability: .command(\n                intent: .custom(verb: \"my-build-tester\", description: \"Help description\")\n            )\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginCompilationError/Plugins/MyBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\n@main struct MyBuildToolPlugin: BuildToolPlugin {\n    func createBuildCommands(\n        context: PluginContext,\n        target: Target\n    ) throws -> [Command] {\n        return []\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginCompilationError/Plugins/MyCommandPlugin/plugin.swift",
    "content": "import PackagePlugin\n@main struct MyCommandPlugin: CommandPlugin {\n    func performCommand(\n        context: PluginContext,\n        arguments: [String]\n    ) throws {\n        this is an error\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginCompilationError/Sources/MyExecutable/main.swift",
    "content": "import MyLibrary\nprint(\"\\\\(GetGreeting()), World!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginCompilationError/Sources/MyLibrary/library.swift",
    "content": "public func GetGreeting() -> String { return \"Hello\" }\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Package.swift",
    "content": "// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"CommandPluginDiagnostics\",\n    targets: [\n        .plugin(\n            name: \"diagnostics-stub\",\n            capability: .command(intent: .custom(\n                verb: \"print-diagnostics\",\n                description: \"Writes diagnostic messages for testing\"\n            ))\n        ),\n        .plugin(\n            name: \"targetbuild-stub\",\n            capability: .command(intent: .custom(\n                verb: \"build-target\",\n                description: \"Build a target for testing\"\n            ))\n        ),\n        .plugin(\n            name: \"plugin-dependencies-stub\",\n            capability: .command(intent: .custom(\n                verb: \"build-plugin-dependency\",\n                description: \"Build a plugin dependency for testing\"\n            )),\n            dependencies: [\n                .target(name: \"plugintool\")\n            ]\n        ),\n        .plugin(\n            name: \"check-testability\",\n            capability: .command(intent: .custom(\n                verb: \"check-testability\",\n                description: \"Check testability of a target\"\n            ))\n        ),\n        .executableTarget(\n            name: \"placeholder\"\n        ),\n        .executableTarget(\n            name: \"plugintool\"\n        ),\n        .target(\n            name: \"InternalModule\"\n        ),\n        .testTarget(\n            name: \"InternalModuleTests\",\n            dependencies: [\n                .target(name: \"InternalModule\")\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Plugins/check-testability/main.swift",
    "content": "import Foundation\nimport PackagePlugin\n\n@main\nstruct CheckTestability: CommandPlugin {\n    // This is a helper for testing target builds to ensure that they are testable.\n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        // Parse the arguments: <targetName> <config> <shouldTestable>\n        guard arguments.count == 3 else {\n            fatalError(\"Usage: <targetName> <config> <shouldTestable>\")\n        }\n        let rawSubsetName = arguments[0]\n        var subset: PackageManager.BuildSubset\n        switch rawSubsetName {\n        // Special subset names\n        case \"all-with-tests\":\n            subset = .all(includingTests: true)\n        // By default, treat the subset as a target name\n        default:\n            subset = .target(rawSubsetName)\n        }\n        guard let config = PackageManager.BuildConfiguration(rawValue: arguments[1]) else {\n            fatalError(\"Invalid configuration: \\(arguments[1])\")\n        }\n        let shouldTestable = arguments[2] == \"true\"\n\n        var parameters = PackageManager.BuildParameters()\n        parameters.configuration = config\n        parameters.logging = .verbose\n\n        // Perform the build\n        let result = try packageManager.build(subset, parameters: parameters)\n\n        // Check if the build was successful\n        guard result.succeeded else {\n            fatalError(\"Build failed: \\(result.logText)\")\n        }\n\n        // Check if the build log contains \"-enable-testing\" flag\n        let isTestable = result.logText.contains(\"-enable-testing\")\n        if isTestable != shouldTestable {\n            fatalError(\"Testability mismatch: expected \\(shouldTestable), but got \\(isTestable):\\n\\(result.logText)\")\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Plugins/diagnostics-stub/diagnostics_stub.swift",
    "content": "import Foundation\nimport PackagePlugin\n\n@main\nstruct diagnostics_stub: CommandPlugin {\n    // This is a helper for testing plugin diagnostics.  It sends different messages to SwiftPM depending on its arguments.\n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        // Build a target, possibly asking SwiftPM to echo the logs as they are produced.\n        if arguments.contains(\"build\") {\n            // If echoLogs is true, SwiftPM will print build logs to stderr as they are produced.\n            // SwiftPM does not add a prefix to these logs.\n            let result = try packageManager.build(\n                .product(\"placeholder\"),\n                parameters: .init(echoLogs: arguments.contains(\"echologs\"))\n            )\n\n            // To verify that logs are also returned correctly to the plugin,\n            // print the accumulated log buffer lines with a prefix to\n            // distinguish them from echoed logs.   These logs are normal output\n            // from the plugin and will be printed on stdout.\n            if arguments.contains(\"printlogs\") {\n                for line in result.logText.components(separatedBy: \"\\n\") {\n                    print(\"command plugin: packageManager.build logtext: \\(line)\")\n                }\n            }\n        }\n\n        // Anything a plugin writes to standard output appears on standard output.\n        // Printing to stderr will also go to standard output because SwiftPM combines\n        // stdout and stderr before launching the plugin.\n        if arguments.contains(\"print\") {\n           print(\"command plugin: print\")\n        }\n\n        // Diagnostics are collected by SwiftPM and printed to standard error, depending on the current log verbosity level.\n        if arguments.contains(\"progress\") {\n           Diagnostics.progress(\"command plugin: Diagnostics.progress\")     // prefixed with [plugin_name]\n        }\n\n        if arguments.contains(\"remark\") {\n           Diagnostics.remark(\"command plugin: Diagnostics.remark\")     // prefixed with 'info:' when printed\n        }\n\n        if arguments.contains(\"warning\") {\n           Diagnostics.warning(\"command plugin: Diagnostics.warning\")   // prefixed with 'warning:' when printed\n        }\n\n        if arguments.contains(\"error\") {\n           Diagnostics.error(\"command plugin: Diagnostics.error\")       // prefixed with 'error:' when printed\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Plugins/plugin-dependencies-stub/main.swift",
    "content": "import PackagePlugin\n\n@main\nstruct test: CommandPlugin {\n    // This plugin exists to test that the executable it requires is built correctly when cross-compiling\n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        print(\"Hello from dependencies-stub\")\n        let _ = try packageManager.build(\n            .product(\"placeholder\"),\n            parameters: .init(configuration: .debug, logging: .concise)\n        )\n    }\n}"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Plugins/targetbuild-stub/targetbuild_stub.swift",
    "content": "import Foundation\nimport PackagePlugin\n\n@main\nstruct targetbuild_stub: CommandPlugin {\n    // This is a helper for testing target builds performed on behalf of plugins.\n    // It sends asks SwiftPM to build a target with different options depending on its arguments.\n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        // Build a target\n        var parameters = PackageManager.BuildParameters()\n        if arguments.contains(\"build-debug\") {\n            parameters.configuration = .debug\n        } else if arguments.contains(\"build-release\") {\n            parameters.configuration = .release\n        } else if arguments.contains(\"build-inherit\") {\n            parameters.configuration = .inherit\n        }\n        // If no 'build-*' argument is present, the default (.debug) will be used.\n\n        let _ = try packageManager.build(\n            .product(\"placeholder\"),\n            parameters: parameters\n        )\n    }\n}"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Sources/InternalModule/InternalModule.swift",
    "content": "internal func internalFunction() {\n    print(\"Internal function\")\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Sources/placeholder/main.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n\nprint(\"Hello, world from executable target!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Sources/plugintool/main.swift",
    "content": "print(\"Hello from plugintool\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/CommandPluginTestStub/Tests/InternalModuleTests/InternalModuleTests.swift",
    "content": "@testable import InternalModule\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ContrivedTestPlugin/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"ContrivedTestPlugin\",\n    targets: [\n        // A local tool that uses a build tool plugin.\n        .executableTarget(\n            name: \"MyLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n                \"MyAmbiguouslyNamedCommandPlugin\",\n            ]\n        ),\n        // The plugin that generates build tool commands to invoke MySourceGenBuildTool.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MySourceGenBuildTool\",\n            ]\n        ),\n        // The command line tool that generates source files.\n        .executableTarget(\n            name: \"MySourceGenBuildTool\"\n        ),\n        // Plugin that emits commands with a generic name.\n        .plugin(\n            name: \"MyAmbiguouslyNamedCommandPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MySourceGenBuildTool\",\n            ]\n        ),\n        // Sample system library target for testing.\n        .systemLibrary(\n            name: \"libpcre\",\n            path: \"Sources/libpcre\",\n            pkgConfig: \"libpcre\",\n            providers: [\n                .apt([\"libpcre-dev\"])\n            ]\n        )\n    ],\n    swiftLanguageModes: [.v5]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ContrivedTestPlugin/Plugins/MyAmbiguouslyNamedCommandPlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        guard let target = target as? SourceModuleTarget else { return [] }\n        var commands: [Command] = []\n        for inputFile in target.sourceFiles.filter({ $0.url.pathExtension == \"dat\" }) {\n            let inputPath = inputFile.url\n            let outputName = \"Ambiguous_\" + inputPath.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            commands.append(.buildCommand(\n                displayName:\n                    \"This is a constant name\",\n                executable:\n                    try context.tool(named: \"MySourceGenBuildTool\").url,\n                arguments: [\n                    inputPath.path,\n                    outputPath.path,\n                ],\n                environment: [\n                    \"VARIABLE_NAME_PREFIX\": \"SECOND_PREFIX_\"\n                ],\n                inputFiles: [\n                    inputPath,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            ))\n        }\n        return commands\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ContrivedTestPlugin/Plugins/MySourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        guard let target = target as? SourceModuleTarget else { return [] }\n        let inputFiles = target.sourceFiles.filter({ $0.url.pathExtension == \"dat\" })\n        return try inputFiles.map {\n            let inputPath = $0.url\n            let outputName = inputPath.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName:\n                    \"Generating \\(outputName) from \\(inputPath.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"MySourceGenBuildTool\").url,\n                arguments: [\n                    inputPath.path,\n                    outputPath.path,\n                ],\n                environment: [\n                    \"VARIABLE_NAME_PREFIX\": \"PREFIX_\"\n                ],\n                inputFiles: [\n                    inputPath,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ContrivedTestPlugin/Sources/MyLocalTool/main.swift",
    "content": "print(\"Generated string Foo: '\\(PREFIX_foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ContrivedTestPlugin/Sources/MySourceGenBuildTool/main.swift",
    "content": "import Foundation\n\n// Sample source generator tool that emits a Swift variable declaration of a string containing the hex representation of the contents of a file as a quoted string.  The variable name is the base name of the input file, with the value from an environment value prepended.  The input file is the first argument and the output file is the second.\nif ProcessInfo.processInfo.arguments.count != 3 {\n    print(\"usage: MySourceGenBuildTool <input> <output>\")\n    exit(1)\n}\nlet inputFile = ProcessInfo.processInfo.arguments[1]\nlet outputFile = ProcessInfo.processInfo.arguments[2]\n\nlet variablePrefix = ProcessInfo.processInfo.environment[\"VARIABLE_NAME_PREFIX\"] ?? \"\"\nlet variableName = URL(fileURLWithPath: inputFile).deletingPathExtension().lastPathComponent\n\nlet inputData = FileManager.default.contents(atPath: inputFile) ?? Data()\nlet dataAsHex = inputData.map { String(format: \"%02hhx\", $0) }.joined()\nlet outputString = \"public var \\(variablePrefix)\\(variableName) = \\(dataAsHex.quotedForSourceCode)\\n\"\nlet outputData = outputString.data(using: .utf8)\nFileManager.default.createFile(atPath: outputFile, contents: outputData)\n\nextension String {\n    \n    public var quotedForSourceCode: String {\n        return \"\\\"\" + self\n            .replacingOccurrences(of: \"\\\\\", with: \"\\\\\\\\\")\n            .replacingOccurrences(of: \"\\\"\", with: \"\\\\\\\"\")\n            + \"\\\"\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ContrivedTestPlugin/Sources/libpcre/module.modulemap",
    "content": "module readline [system] {\n  header \"sdk_libpcre.h\"\n  link \"libpcre\"\n  export *\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/ContrivedTestPlugin/Sources/libpcre/sdk_libpcre.h",
    "content": "#include <libpcre/libpcre.h>\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/DependentPlugins/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"DependentPlugins\",\n    platforms: [ .macOS(.v13) ],\n    dependencies: [\n    ],\n    targets: [\n        .executableTarget(name: \"MyExecutable\"),\n        .executableTarget(name: \"MyExecutable2\"),\n\n        .plugin(\n            name: \"MyPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MyExecutable\"\n            ]\n        ),\n\n        .plugin(\n            name: \"MyPlugin2\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MyExecutable2\"\n            ]\n        ),\n\n        .executableTarget(\n            name: \"MyClient\",\n            plugins: [\n                \"MyPlugin\",\n                \"MyPlugin2\",\n            ]\n        ),\n    ],\n    swiftLanguageModes: [.v5]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/DependentPlugins/Plugins/MyPlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n        let outputFilePath = context.pluginWorkDirectoryURL.appendingPathComponent(\"MyGeneratedFile.swift\")\n        return [\n            .buildCommand(\n                displayName: \"Running MyExecutable\",\n                executable: try context.tool(named: \"MyExecutable\").url,\n                arguments: [\"--output-file-path\", outputFilePath.path],\n                outputFiles: [outputFilePath]\n            )\n        ]\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/DependentPlugins/Plugins/MyPlugin2/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n        guard let sourceTarget = target as? SourceModuleTarget else {\n            throw \"Target is not a source target, cannot get a file list\"\n        }\n        guard let inputFilePath = sourceTarget.pluginGeneratedSources.first(where: { $0.lastPathComponent == \"MyGeneratedFile.swift\" }) else {\n            throw \"Cannot find MyGeneratedFile.swift, files: \\(sourceTarget.pluginGeneratedSources), target: \\(target)\"\n        }\n        return [\n            .buildCommand(\n                displayName: \"Running MyExecutable2\",\n                executable: try context.tool(named: \"MyExecutable2\").url,\n                arguments: [\"--input-file-path\", inputFilePath.path],\n                inputFiles: [inputFilePath],\n            )\n        ]\n    }\n}\n\nextension String: Error, LocalizedError {\n    public var errorDescription: String? {\n        self\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/DependentPlugins/Sources/MyClient/client.swift",
    "content": "@main\nstruct Client {\n    static func main() throws {\n        print(MyGeneratedStruct.message)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/DependentPlugins/Sources/MyExecutable/tool.swift",
    "content": "import Foundation\n\n@main\nstruct Tool {\n    static func main() async throws {\n        print(\"warning: Whoops! Coming from the executable\", to: &StdErr.shared)\n        \n        let path = CommandLine.arguments[2]\n        print(\"Writing a file to \\(path)\")\n        \n        try #\"\"\"\n        public struct MyGeneratedStruct {\n            public static var message: String = \"You got struct'd\"\n        }\n        \"\"\"#.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8)\n    }\n}\n\nstruct StdErr: TextOutputStream {\n    static var shared: Self = .init()\n    mutating func write(_ string: String) {\n        string.withCString { ptr in\n            _ = fputs(ptr, stderr)\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/DependentPlugins/Sources/MyExecutable2/tool.swift",
    "content": "import Foundation\n\n@main\nstruct Tool {\n    static func main() async throws {\n        let path = CommandLine.arguments[2]\n        print(\"Printing file at \\(path)\")\n        print(try String(contentsOfFile: path))\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/IncorrectDependencies/Package.swift",
    "content": "// swift-tools-version:6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"111920845-sample\",\n    platforms: [\n        .macOS(.v10_15), // example uses swift concurrency which is only available in 10.15 or newer\n    ],\n    products: [\n        .executable(name: \"MyPluginExecutable\", targets: [\"MyPluginExecutable\"]),\n        .plugin(name: \"MyPlugin\", targets: [\"MyPlugin\"]),\n    ],\n    targets: [\n        .executableTarget(name: \"MyPluginExecutable\"),\n        .plugin(name: \"MyPlugin\", capability: .buildTool, dependencies: [\"MyPluginExecutable\"]),\n\n        .target(name: \"MyLibrary\", plugins: [\"MyPlugin\"]),\n        .executableTarget(name: \"MyExecutable\", dependencies: [\"MyLibrary\"]),\n        .testTarget(name: \"MyExecutableTests\", dependencies: [\"MyExecutable\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/IncorrectDependencies/Plugins/MyPlugin/MyPlugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n        return [.buildCommand(\n            displayName: \"Running MyPluginExecutable\",\n            executable: try context.tool(named: \"MyPluginExecutable\").url,\n            arguments: [],\n            environment: [:],\n            inputFiles: [],\n            outputFiles: []\n        )]\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/IncorrectDependencies/Sources/MyExecutable/MyExecutable.swift",
    "content": "import MyLibrary\n\n@main\nstruct MyExecutable {\n    static func main() async throws {\n        print(\"Hello from executable.\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/IncorrectDependencies/Sources/MyLibrary/Empty.swift",
    "content": "\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/IncorrectDependencies/Sources/MyPluginExecutable/MyPluginExecutable.swift",
    "content": "@main\nstruct MyExecutable {\n    static func main() async throws {\n        print(\"Hello from plugin executable.\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/IncorrectDependencies/Tests/MyExecutableTests/MyExecutableTests.swift",
    "content": "import XCTest\n@testable import MyExecutable\n\nfinal class MyExecutableTests: XCTestCase {\n    func test() throws {\n        XCTAssertTrue(true)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/InvalidUseOfInternalPluginExecutable/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"InvalidUseOfInternalPluginExecutable\",\n    dependencies: [\n        .package(path: \"../PluginWithInternalExecutable\")\n    ],\n    targets: [\n        .executableTarget(\n            name: \"RootTarget\",\n            dependencies: [\n                .product(name: \"PluginExecutable\", package: \"PluginWithInternalExecutable\")\n            ],\n            plugins: [\n                .plugin(name: \"PluginScriptProduct\", package: \"PluginWithInternalExecutable\")\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/InvalidUseOfInternalPluginExecutable/Sources/RootTarget/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/LibraryWithLocalBuildToolPluginUsingRemoteTool/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyLibrary\",\n    dependencies: [\n        .package(path: \"../MySourceGenPlugin\")\n    ],\n    targets: [\n        .plugin(\n            name: \"MyLocalSourceGenBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                .product(name: \"MySourceGenBuildTool\", package: \"MySourceGenPlugin\")\n            ]\n        ),\n        .target(\n            name: \"MyLibrary\",\n            plugins: [\n                \"MyLocalSourceGenBuildToolPlugin\",\n            ]\n        ),\n        .testTarget(\n            name: \"MyLibraryTests\",\n            dependencies: [\"MyLibrary\"]\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/LibraryWithLocalBuildToolPluginUsingRemoteTool/Plugins/MyLocalSourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Build Tool Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        return try target.sourceFiles.map{ $0.url }.compactMap { (url: URL) -> Command? in\n            guard url.pathExtension == \"dat\" else { return nil }\n            let outputName = url.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName:\n                    \"Generating \\(outputName) from \\(url.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"MySourceGenBuildTool\").url,\n                arguments: [\n                    url.path,\n                    outputPath.path,\n                ],\n                inputFiles: [\n                    url,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/LibraryWithLocalBuildToolPluginUsingRemoteTool/Sources/MyLibrary/library.swift",
    "content": "public func GetGeneratedString() -> String {\n    return \"Generated string: \\(generated)\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/LibraryWithLocalBuildToolPluginUsingRemoteTool/Tests/MyLibraryTests/test.swift",
    "content": "import XCTest\nimport MyLibrary\n\nfinal class MyLibraryTests: XCTestCase {\n    \n    func testLibrary() throws {\n        XCTAssertEqual(GetGeneratedString(), \"Generated string: 4920616d20466f6f210a\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MissingPlugin/Package.swift",
    "content": "// swift-tools-version: 5.7\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"MissingPlugin\",\n    targets: [\n        .target(name: \"MissingPlugin\", plugins: [\"NonExistingPlugin\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MissingPlugin/Sources/MissingPlugin/MissingPlugin.swift",
    "content": "public struct MissingPlugin {\n    public private(set) var text = \"Hello, World!\"\n\n    public init() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBinaryToolPlugin/Binaries/MyVendedSourceGenBuildTool.artifactbundle/info.json",
    "content": "{\n    \"schemaVersion\": \"1.0\",\n    \"artifacts\": {\n        \"mytool\": {\n            \"type\": \"executable\",\n            \"version\": \"1.2.3\",\n            \"variants\": [\n                {\n                    \"path\": \"mytool-macos/mytool\",\n                    \"supportedTriples\": [\"x86_64-apple-macosx\", \"arm64-apple-macosx\"]\n                },\n                {\n                    \"path\": \"mytool-linux/mytool\",\n                    \"supportedTriples\": [\"x86_64-unknown-linux-gnu\", \"aarch64-unknown-linux-gnu\"]\n                },\n                {\n                    \"path\": \"mytool-windows/mytool.bat\",\n                    \"supportedTriples\": [\"x86_64-unknown-windows-msvc\", \"aarch64-unknown-windows-msvc\"]\n                }\n            ]\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBinaryToolPlugin/Binaries/MyVendedSourceGenBuildTool.artifactbundle/mytool-linux/mytool",
    "content": "#!/bin/bash\n\nprint_usage() {\n    echo \"usage: ${0##*/} [--verbose] <in> <out>\"\n}\n\n# Parse arguments until we find '--' or an argument that isn't an option.\nuntil [ $# -eq 0 ]\ndo\n    case \"$1\" in\n        --verbose) verbose=1; shift;;\n        --) shift; break;;\n        -*) echo \"unknown option: ${1}\"; print_usage; exit 1; shift;;\n        *) break;;\n    esac\ndone\n\n# Print usage and leave if we don't have exactly two arguments.\nif [ $# -ne 2 ]; then\n    print_usage\n    exit 1\nfi\n\n# For our sample tool we just copy from one to the other.\nif [ $verbose != 0 ]; then\n    echo \"[${0##*/}-linux] '$1' '$2'\"\nfi\n\ncp \"$1\" \"$2\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBinaryToolPlugin/Binaries/MyVendedSourceGenBuildTool.artifactbundle/mytool-macos/mytool",
    "content": "#!/bin/bash\n\nprint_usage() {\n    echo \"usage: ${0##*/} [--verbose] <in> <out>\"\n}\n\n# Parse arguments until we find '--' or an argument that isn't an option.\nuntil [ $# -eq 0 ]\ndo\n    case \"$1\" in\n        --verbose) verbose=1; shift;;\n        --) shift; break;;\n        -*) echo \"unknown option: ${1}\"; print_usage; exit 1; shift;;\n        *) break;;\n    esac\ndone\n\n# Print usage and leave if we don't have exactly two arguments.\nif [ $# -ne 2 ]; then\n    print_usage\n    exit 1\nfi\n\n# For our sample tool we just copy from one to the other.\nif [ $verbose != 0 ]; then\n    echo \"[${0##*/}-macosx] '$1' '$2'\"\nfi\n\ncp \"$1\" \"$2\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBinaryToolPlugin/Binaries/MyVendedSourceGenBuildTool.artifactbundle/mytool-windows/mytool.bat",
    "content": "@echo off\n\nset verbose=false\nIF NOT \"%1\"==\"\" (\n    IF \"%1\"==\"--verbose\" (\n        SET verbose=true\n        SHIFT\n    )\n)\n\nset input=%1\nset output=%2\nshift\nshift\n\n\nif \"%verbose%\" == \"true\" (\n    echo \"[mytool-windows] '%input%' '%output%'\"\n)\n@echo on\necho f | xcopy.exe /f \"%input%\" \"%output%\""
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBinaryToolPlugin/Package.swift",
    "content": "// swift-tools-version: 6.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyBinaryToolPlugin\",\n    targets: [\n        // A local tool that uses a build tool plugin.\n        .executableTarget(\n            name: \"MyLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        ),\n        // The plugin that generates build tool commands to invoke MySourceGenBuildTool.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MyVendedSourceGenBuildTool\",\n            ]\n        ),\n        // The vended executable that generates source files.\n        .binaryTarget(\n            name: \"MyVendedSourceGenBuildTool\",\n            path: \"Binaries/MyVendedSourceGenBuildTool.artifactbundle\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBinaryToolPlugin/Plugins/MySourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Build Tool Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        let inputFiles = target.sourceFiles.filter({ $0.url.pathExtension == \"dat\" })\n        let workDir = context.pluginWorkDirectoryURL\n\n        return try inputFiles.map {\n            let inputFile = $0\n            let inputPath = $0.url\n            let outputName = inputPath.deletingPathExtension().appendingPathExtension(\"swift\")\n                .lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName:\n                    \"Generating \\(outputName) from \\(inputPath.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"mytool\").url,\n                arguments: [\n                    \"--verbose\",\n                    inputPath.path,\n                    outputPath.path,\n                ],\n                inputFiles: [\n                    inputPath\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        } + [\n            .prebuildCommand(\n                displayName:\n                    \"Generating files in \\(workDir.path)\",\n                executable:\n                    try context.tool(named: \"mytool\").url,\n                arguments: [\n                    \"--verbose\",\n                    target.directoryURL.appendingPathComponent(\"bar.in\").path,\n                    workDir.appendingPathComponent(\"bar.swift\").path,\n                ],\n                outputFilesDirectory: workDir\n            )\n        ]\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBinaryToolPlugin/Sources/MyLocalTool/bar.in",
    "content": "let bar = \"I am Bar!\"\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBinaryToolPlugin/Sources/MyLocalTool/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\nprint(\"Generated string Bar: '\\(bar)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBuildToolPluginDependencies/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyBuildToolPluginDependencies\",\n    targets: [\n        // A local tool that uses a build tool plugin.\n        .executableTarget(\n            name: \"MyLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        ),\n        // The plugin that generates build tool commands to invoke MySourceGenBuildTool.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MySourceGenBuildTool\",\n            ]\n        ),\n        // A command line tool that generates source files.\n        .executableTarget(\n            name: \"MySourceGenBuildTool\",\n            dependencies: [\n                \"MySourceGenBuildToolLib\",\n            ]\n        ),\n        // A library used by MySourceGenBuildTool (not the client).\n        .target(\n            name: \"MySourceGenBuildToolLib\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBuildToolPluginDependencies/Plugins/MySourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    // Create build commands that don't invoke the MySourceGenBuildTool source generator\n    // tool directly, but instead invoke a system tool that invokes it indirectly.  We\n    // want to test that we still end up with a dependency on not only that tool but also\n    // on the library it depends on, even without including an explicit dependency on it.\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Build Tool Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        let inputFiles = target.sourceFiles.filter({ $0.url.pathExtension == \"dat\" })\n        return try inputFiles.map {\n            let inputPath = $0.url\n            let outputName = inputPath.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName:\n                    \"Generating \\(outputName) from \\(inputPath.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"MySourceGenBuildTool\").url,\n                arguments: [\n                    inputPath.path,\n                    outputPath.path,\n                ],\n                inputFiles: [\n                    inputPath,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBuildToolPluginDependencies/Sources/MyLocalTool/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBuildToolPluginDependencies/Sources/MySourceGenBuildTool/main.swift",
    "content": "import Foundation\nimport MySourceGenBuildToolLib\n\n// Sample source generator tool that emits a Swift variable declaration of a string containing the hex representation of the contents of a file as a quoted string.  The variable name is the base name of the input file.  The input file is the first argument and the output file is the second.\nif ProcessInfo.processInfo.arguments.count != 3 {\n    print(\"usage: MySourceGenBuildTool <input> <output>\")\n    exit(1)\n}\nlet inputFile = ProcessInfo.processInfo.arguments[1]\nlet outputFile = ProcessInfo.processInfo.arguments[2]\n\nlet variableName = URL(fileURLWithPath: inputFile).deletingPathExtension().lastPathComponent\n\nlet inputData = FileManager.default.contents(atPath: inputFile) ?? Data()\nlet dataAsHex = inputData.map { String(format: \"%02hhx\", $0) }.joined()\nlet outputString = \"public let \\(variableName) = \\(dataAsHex.quotedForSourceCode)\\n\"\nlet outputData = outputString.data(using: .utf8)\nFileManager.default.createFile(atPath: outputFile, contents: outputData)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MyBuildToolPluginDependencies/Sources/MySourceGenBuildToolLib/library.swift",
    "content": "import Foundation\n\nextension String {\n    \n    public var quotedForSourceCode: String {\n        return \"\\\"\" + self\n            .replacingOccurrences(of: \"\\\\\", with: \"\\\\\\\\\")\n            .replacingOccurrences(of: \"\\\"\", with: \"\\\\\\\"\")\n            + \"\\\"\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenClient/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"MySourceGenClient\",\n    dependencies: [\n        .package(path: \"../MySourceGenPlugin\")\n    ],\n    targets: [\n        // A tool that uses a plugin.\n        .executableTarget(\n            name: \"MyTool\",\n            plugins: [\n                .plugin(name: \"MySourceGenBuildToolPlugin\", package: \"MySourceGenPlugin\")\n            ]\n        ),\n        // A unit test that uses the plugin.\n        .testTarget(\n            name: \"MyTests\",\n            plugins: [\n                .plugin(name: \"MySourceGenBuildToolPlugin\", package: \"MySourceGenPlugin\")\n            ]\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenClient/Sources/MyTool/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenClient/Tests/MyTests/MyTests.swift",
    "content": "import XCTest\nimport class Foundation.Bundle\n\nfinal class SwiftyProtobufTests: XCTestCase {\n    func testExample() throws {\n        // This is an example of a functional test case.\n        // Use XCTAssert and related functions to verify your tests produce the correct\n        // results.\n\n        // Some of the APIs that we use below are available in macOS 10.13 and above.\n        guard #available(macOS 10.13, *) else {\n            return\n        }\n\n        // Mac Catalyst won't have `Process`, but it is supported for executables.\n        #if !targetEnvironment(macCatalyst)\n\n        let fooBinary = productsDirectory.appendingPathComponent(\"MySourceGenTool\")\n\n        let process = Process()\n        process.executableURL = fooBinary\n\n        let pipe = Pipe()\n        process.standardOutput = pipe\n\n        try process.run()\n        process.waitUntilExit()\n\n        let data = pipe.fileHandleForReading.readDataToEndOfFile()\n        let output = String(data: data, encoding: .utf8)\n\n        XCTAssertEqual(output, \"Hello, world!\\n\")\n        #endif\n    }\n\n    /// Returns path to the built products directory.\n    var productsDirectory: URL {\n      #if os(macOS)\n        for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(\".xctest\") {\n            return bundle.bundleURL.deletingLastPathComponent()\n        }\n        fatalError(\"couldn't find the products directory\")\n      #else\n        return Bundle.main.bundleURL\n      #endif\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"MySourceGenPlugin\",\n    products: [\n        // The product that vends MySourceGenBuildToolPlugin to client packages.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            targets: [\"MySourceGenBuildToolPlugin\"]\n        ),\n        // The product that vends the MySourceGenBuildTool executable to client packages.\n        .executable(\n            name: \"MySourceGenBuildTool\",\n            targets: [\"MySourceGenBuildTool\"]\n        ),\n        // The product that vends MySourceGenPrebuildPlugin to client packages.\n        .plugin(\n            name: \"MySourceGenPrebuildPlugin\",\n            targets: [\"MySourceGenPrebuildPlugin\"]\n        ),\n    ],\n    targets: [\n        // A local tool that uses a build tool plugin.\n        .executableTarget(\n            name: \"MyLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        ),\n        // A local tool that uses a prebuild plugin.\n        .executableTarget(\n            name: \"MyOtherLocalTool\",\n            plugins: [\n                \"MySourceGenPrebuildPlugin\",\n            ]\n        ),\n        // The plugin that generates build tool commands to invoke MySourceGenBuildTool.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MySourceGenBuildTool\",\n            ]\n        ),\n        // The plugin that generates prebuild commands (currently to invoke a system tool).\n        .plugin(\n            name: \"MySourceGenPrebuildPlugin\",\n            capability: .buildTool()\n        ),\n        // The command line tool that generates source files.\n        .executableTarget(\n            name: \"MySourceGenBuildTool\",\n            dependencies: [\n                \"MySourceGenBuildToolLib\",\n            ]\n        ),\n        // A library used by MySourceGenBuildTool (not the client).\n        .target(\n            name: \"MySourceGenBuildToolLib\"\n        ),\n        // A runtime library that the client needs to link against.\n        .target(\n            name: \"MySourceGenRuntimeLib\"\n        ),\n        // Unit tests for the plugin.\n        .testTarget(\n            name: \"MySourceGenPluginTests\",\n            dependencies: [\n                \"MySourceGenRuntimeLib\",\n            ],\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n                \"MySourceGenPrebuildPlugin\",\n            ]\n        )\n    ],\n    swiftLanguageModes: [.v5]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Plugins/MySourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    #if USE_CREATE\n    let verb = \"Creating\"\n    #else\n    let verb = \"Generating\"\n    #endif\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Build Tool Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        return try target.sourceFiles.map { $0.url }.compactMap { (url: URL) -> Command? in\n            guard url.pathExtension == \"dat\" else { return nil }\n            let outputName = url.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName: \"\\(verb) \\(outputName) from \\(url.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"MySourceGenBuildTool\").url,\n                arguments: [\n                    url.path,\n                    outputPath.path\n                ],\n                inputFiles: [\n                    url,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Plugins/MySourceGenPrebuildPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n#if os(Android)\nlet touchExe = \"/system/bin/touch\"\nlet touchArgs: [String]  = []\n#elseif os(Windows)\nlet touchExe = \"C:/Windows/System32/cmd.exe\"\nlet touchArgs = [\"/c\", \"copy\", \"NUL\"]\n#else\nlet touchExe = \"/usr/bin/touch\"\nlet touchArgs: [String]  = []\n#endif\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Prebuild Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        let outputPaths: [URL] = target.sourceFiles.filter{ $0.url.pathExtension == \"dat\" }.map { file in\n            context.pluginWorkDirectoryURL.appendingPathComponent(file.url.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent)\n        }\n        var commands: [Command] = []\n        let paths = outputPaths.map{ $0.path }\n#if os(Windows)\n        let args = [\"/c\", \"FOR %F IN (\" + paths.joined(separator: \" \") + \") DO TYPE NUL > %F\"]\n#else\n        let args = paths\n#endif\n        if !outputPaths.isEmpty {\n            commands.append(.prebuildCommand(\n                displayName:\n                    \"Running prebuild command for target \\(target.name)\",\n                executable:\n                    .init(fileURLWithPath: touchExe),\n                arguments:\n                    args,\n                outputFilesDirectory:\n                    context.pluginWorkDirectoryURL\n            ))\n        }\n        return commands\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Sources/MyLocalTool/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Sources/MyOtherLocalTool/main.swift",
    "content": "// print(\"Generated string Bar: '\\(bar)'\")\n// print(\"Generated string Baz: '\\(baz)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Sources/MySourceGenBuildTool/main.swift",
    "content": "import Foundation\nimport MySourceGenBuildToolLib\n\n// Sample source generator tool that emits a Swift variable declaration of a string containing the hex representation of the contents of a file as a quoted string.  The variable name is the base name of the input file.  The input file is the first argument and the output file is the second.\nif ProcessInfo.processInfo.arguments.count != 3 {\n    print(\"usage: MySourceGenBuildTool <input> <output>\")\n    exit(1)\n}\nlet inputFile = ProcessInfo.processInfo.arguments[1]\nlet outputFile = ProcessInfo.processInfo.arguments[2]\n\nlet variableName = URL(fileURLWithPath: inputFile).deletingPathExtension().lastPathComponent\n\nlet inputData = FileManager.default.contents(atPath: inputFile) ?? Data()\nlet dataAsHex = inputData.map { String(format: \"%02hhx\", $0) }.joined()\nlet outputString = \"public let \\(variableName) = \\(dataAsHex.quotedForSourceCode)\\n\"\nlet outputData = outputString.data(using: .utf8)\nFileManager.default.createFile(atPath: outputFile, contents: outputData)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Sources/MySourceGenBuildToolLib/library.swift",
    "content": "import Foundation\n\nextension String {\n    \n    public var quotedForSourceCode: String {\n        return \"\\\"\" + self\n            .replacingOccurrences(of: \"\\\\\", with: \"\\\\\\\\\")\n            .replacingOccurrences(of: \"\\\"\", with: \"\\\\\\\"\")\n            + \"\\\"\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Sources/MySourceGenRuntimeLib/library.swift",
    "content": "public func GetLibraryName() -> String {\n    return \"MySourceGenRuntimeLib\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPlugin/Tests/MySourceGenPluginTests/MySourceGenPluginTests.swift",
    "content": "import XCTest\nimport class Foundation.Bundle\n\nfinal class SwiftyProtobufTests: XCTestCase {\n    func testExample() throws {\n        // This is an example of a functional test case.\n        // Use XCTAssert and related functions to verify your tests produce the correct\n        // results.\n\n        // Some of the APIs that we use below are available in macOS 10.13 and above.\n        guard #available(macOS 10.13, *) else {\n            return\n        }\n\n        // Mac Catalyst won't have `Process`, but it is supported for executables.\n        #if !targetEnvironment(macCatalyst)\n\n        let fooBinary = productsDirectory.appendingPathComponent(\"MySourceGenTool\")\n\n        let process = Process()\n        process.executableURL = fooBinary\n\n        let pipe = Pipe()\n        process.standardOutput = pipe\n\n        try process.run()\n        process.waitUntilExit()\n\n        let data = pipe.fileHandleForReading.readDataToEndOfFile()\n        let output = String(data: data, encoding: .utf8)\n\n        XCTAssertEqual(output, \"Hello, world!\\n\")\n        #endif\n    }\n\n    /// Returns path to the built products directory.\n    var productsDirectory: URL {\n      #if os(macOS)\n        for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(\".xctest\") {\n            return bundle.bundleURL.deletingLastPathComponent()\n        }\n        fatalError(\"couldn't find the products directory\")\n      #else\n        return Bundle.main.bundleURL\n      #endif\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"MySourceGenPluginNoPreBuildCommands\",\n    products: [\n        // The product that vends MySourceGenBuildToolPlugin to client packages.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            targets: [\"MySourceGenBuildToolPlugin\"]\n        ),\n        // The product that vends the MySourceGenBuildTool executable to client packages.\n        .executable(\n            name: \"MySourceGenBuildTool\",\n            targets: [\"MySourceGenBuildTool\"]\n        ),\n    ],\n    targets: [\n        // A local tool that uses a build tool plugin.\n        .executableTarget(\n            name: \"MyLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        ),\n        // A local tool that uses a prebuild plugin.\n        .executableTarget(\n            name: \"MyOtherLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        ),\n        // The plugin that generates build tool commands to invoke MySourceGenBuildTool.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MySourceGenBuildTool\",\n            ]\n        ),\n        // The command line tool that generates source files.\n        .executableTarget(\n            name: \"MySourceGenBuildTool\",\n            dependencies: [\n                \"MySourceGenBuildToolLib\",\n            ]\n        ),\n        // A library used by MySourceGenBuildTool (not the client).\n        .target(\n            name: \"MySourceGenBuildToolLib\"\n        ),\n        // A runtime library that the client needs to link against.\n        .target(\n            name: \"MySourceGenRuntimeLib\"\n        ),\n        // Unit tests for the plugin.\n        .testTarget(\n            name: \"MySourceGenPluginTests\",\n            dependencies: [\n                \"MySourceGenRuntimeLib\",\n            ],\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        )\n    ],\n    swiftLanguageModes: [.v5]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Plugins/MySourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    #if USE_CREATE\n    let verb = \"Creating\"\n    #else\n    let verb = \"Generating\"\n    #endif\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Build Tool Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        return try target.sourceFiles.map{ $0.url }.compactMap { (url: URL) -> Command? in\n            guard url.pathExtension == \"dat\" else { return nil }\n            let outputName = url.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName:\n                    \"\\(verb) \\(outputName) from \\(url.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"MySourceGenBuildTool\").url,\n                arguments: [\n                    url.path,\n                    outputPath.path,\n                ],\n                inputFiles: [\n                    url,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Sources/MyLocalTool/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Sources/MyOtherLocalTool/main.swift",
    "content": "// print(\"Generated string Bar: '\\(bar)'\")\n// print(\"Generated string Baz: '\\(baz)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Sources/MySourceGenBuildTool/main.swift",
    "content": "import Foundation\nimport MySourceGenBuildToolLib\n\n// Sample source generator tool that emits a Swift variable declaration of a string containing the hex representation of the contents of a file as a quoted string.  The variable name is the base name of the input file.  The input file is the first argument and the output file is the second.\nif ProcessInfo.processInfo.arguments.count != 3 {\n    print(\"usage: MySourceGenBuildTool <input> <output>\")\n    exit(1)\n}\nlet inputFile = ProcessInfo.processInfo.arguments[1]\nlet outputFile = ProcessInfo.processInfo.arguments[2]\n\nlet variableName = URL(fileURLWithPath: inputFile).deletingPathExtension().lastPathComponent\n\nlet inputData = FileManager.default.contents(atPath: inputFile) ?? Data()\nlet dataAsHex = inputData.map { String(format: \"%02hhx\", $0) }.joined()\nlet outputString = \"public var \\(variableName) = \\(dataAsHex.quotedForSourceCode)\\n\"\nlet outputData = outputString.data(using: .utf8)\nFileManager.default.createFile(atPath: outputFile, contents: outputData)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Sources/MySourceGenBuildToolLib/library.swift",
    "content": "import Foundation\n\nextension String {\n    \n    public var quotedForSourceCode: String {\n        return \"\\\"\" + self\n            .replacingOccurrences(of: \"\\\\\", with: \"\\\\\\\\\")\n            .replacingOccurrences(of: \"\\\"\", with: \"\\\\\\\"\")\n            + \"\\\"\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Sources/MySourceGenRuntimeLib/library.swift",
    "content": "public func GetLibraryName() -> String {\n    return \"MySourceGenRuntimeLib\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Tests/MySourceGenPluginNoPreBuildCommandsTests/MySourceGenPluginNoPreBuildCommandsTests.swift",
    "content": "import XCTest\nimport class Foundation.Bundle\n\n// for rdar://113256834\nfinal class SwiftyProtobufTests: XCTestCase {\n    func testMyLocalTool() throws {\n        // This is an example of a functional test case.\n        // Use XCTAssert and related functions to verify your tests produce the correct\n        // results.\n\n        // Some of the APIs that we use below are available in macOS 10.13 and above.\n        guard #available(macOS 10.13, *) else {\n            return\n        }\n\n        // Mac Catalyst won't have `Process`, but it is supported for executables.\n        #if !targetEnvironment(macCatalyst)\n\n        let fooBinary = productsDirectory.appendingPathComponent(\"MyLocalTool\")\n\n        let process = Process()\n        process.executableURL = fooBinary\n\n        let pipe = Pipe()\n        process.standardOutput = pipe\n\n        try process.run()\n        process.waitUntilExit()\n\n        let data = pipe.fileHandleForReading.readDataToEndOfFile()\n        let output = String(data: data, encoding: .utf8)\n        XCTAssertEqual(output, \"Generated string Foo: \\'4920616d20466f6f210a\\'\\n\")\n        #endif\n    }\n\n    func testMyOtherLocalTool() throws {\n        // This is an example of a functional test case.\n        // Use XCTAssert and related functions to verify your tests produce the correct\n        // results.\n\n        // Some of the APIs that we use below are available in macOS 10.13 and above.\n        guard #available(macOS 10.13, *) else {\n            return\n        }\n\n        // Mac Catalyst won't have `Process`, but it is supported for executables.\n        #if !targetEnvironment(macCatalyst)\n\n        let fooBinary = productsDirectory.appendingPathComponent(\"MyOtherLocalTool\")\n\n        let process = Process()\n        process.executableURL = fooBinary\n\n        let pipe = Pipe()\n        process.standardOutput = pipe\n\n        try process.run()\n        process.waitUntilExit()\n\n        let data = pipe.fileHandleForReading.readDataToEndOfFile()\n        let output = String(data: data, encoding: .utf8)\n        XCTAssertEqual(output, \"\")\n        #endif\n    }\n\n    /// Returns path to the built products directory.\n    var productsDirectory: URL {\n      #if os(macOS)\n        for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(\".xctest\") {\n            return bundle.bundleURL.deletingLastPathComponent()\n        }\n        fatalError(\"couldn't find the products directory\")\n      #else\n        return Bundle.main.bundleURL\n      #endif\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands/Tests/MySourceGenPluginNoPreBuildCommandsTests/lunch.txt",
    "content": "coffee\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"MySourceGenPlugin\",\n    products: [\n        // The product that vends MySourceGenBuildToolPlugin to client packages.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            targets: [\"MySourceGenBuildToolPlugin\"]\n        ),\n        // The product that vends the MySourceGenBuildTool executable to client packages.\n        .executable(\n            name: \"MySourceGenBuildTool\",\n            targets: [\"MySourceGenBuildTool\"]\n        ),\n        // The product that vends MySourceGenPrebuildPlugin to client packages.\n        .plugin(\n            name: \"MySourceGenPrebuildPlugin\",\n            targets: [\"MySourceGenPrebuildPlugin\"]\n        ),\n    ],\n    targets: [\n        // A local tool that uses a build tool plugin.\n        .executableTarget(\n            name: \"MyLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        ),\n        // A local tool that uses a prebuild plugin.\n        .executableTarget(\n            name: \"MyOtherLocalTool\",\n            plugins: [\n                \"MySourceGenPrebuildPlugin\",\n            ]\n        ),\n        // The plugin that generates build tool commands to invoke MySourceGenBuildTool.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MySourceGenBuildTool\",\n            ]\n        ),\n        // The plugin that generates prebuild commands (currently to invoke a system tool).\n        .plugin(\n            name: \"MySourceGenPrebuildPlugin\",\n            capability: .buildTool()\n        ),\n        // The command line tool that generates source files.\n        .executableTarget(\n            name: \"MySourceGenBuildTool\",\n            dependencies: [\n                \"MySourceGenBuildToolLib\",\n            ]\n        ),\n        // A library used by MySourceGenBuildTool (not the client).\n        .target(\n            name: \"MySourceGenBuildToolLib\"\n        ),\n        // A runtime library that the client needs to link against.\n        .target(\n            name: \"MySourceGenRuntimeLib\"\n        ),\n        // Unit tests for the plugin.\n        .testTarget(\n            name: \"MySourceGenPluginTests\",\n            dependencies: [\n                \"MySourceGenRuntimeLib\",\n            ],\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n                \"MySourceGenPrebuildPlugin\",\n            ]\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Plugins/MySourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    #if USE_CREATE\n    let verb = \"Creating\"\n    #else\n    let verb = \"Generating\"\n    #endif\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Build Tool Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        return try target.sourceFiles.map{ $0.url }.compactMap { (url: URL) -> Command? in\n            guard url.pathExtension == \"dat\" else { return nil }\n            let outputName = url.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName:\n                    \"\\(verb) \\(outputName) from \\(url.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"MySourceGenBuildTool\").url,\n                arguments: [\n                    url.path,\n                    outputPath.path\n                ],\n                inputFiles: [\n                    url,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Plugins/MySourceGenPrebuildPlugin/plugin.swift",
    "content": "import Foundation\nimport PackagePlugin\n\n#if os(Android)\nlet touchExe = \"/system/bin/touch\"\n#elseif os(Windows)\nlet touchExe = \"C:/Windows/System32/cmd.exe\"\n#else\nlet touchExe = \"/usr/bin/touch\"\n#endif\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the Prebuild Plugin!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        let outputPaths: [URL] = target.sourceFiles.filter{ $0.url.pathExtension == \"dat\" }.map { file in\n            context.pluginWorkDirectoryURL.appendingPathComponent(file.url.lastPathComponent + \".swift\")\n        }\n        let paths = outputPaths.map{ $0.path }\n#if os(Windows)\n        let args = [\"/c\", \"FOR %F IN (\" + paths.joined(separator: \" \") + \") DO TYPE NUL > %F\"]\n#else\n        let args = paths\n#endif\n        var commands: [Command] = []\n        if !outputPaths.isEmpty {\n            commands.append(.prebuildCommand(\n                displayName:\n                    \"Running prebuild command for target \\(target.name)\",\n                executable:\n                    .init(fileURLWithPath: touchExe),\n                arguments:\n                    args,\n                outputFilesDirectory:\n                    context.pluginWorkDirectoryURL\n            ))\n        }\n        return commands\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Sources/MyLocalTool/main.swift",
    "content": "print(\"Generated string Foo: '\\(foo)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Sources/MyOtherLocalTool/main.swift",
    "content": "// print(\"Generated string Bar: '\\(bar)'\")\n// print(\"Generated string Baz: '\\(baz)'\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Sources/MySourceGenBuildTool/main.swift",
    "content": "import Foundation\nimport MySourceGenBuildToolLib\n\n// Sample source generator tool that emits a Swift variable declaration of a string containing the hex representation of the contents of a file as a quoted string.  The variable name is the base name of the input file.  The input file is the first argument and the output file is the second.\nif ProcessInfo.processInfo.arguments.count != 3 {\n    print(\"usage: MySourceGenBuildTool <input> <output>\")\n    exit(1)\n}\nlet inputFile = ProcessInfo.processInfo.arguments[1]\nlet outputFile = ProcessInfo.processInfo.arguments[2]\n\nlet variableName = URL(fileURLWithPath: inputFile).deletingPathExtension().lastPathComponent\n\nlet inputData = FileManager.default.contents(atPath: inputFile) ?? Data()\nlet dataAsHex = inputData.map { String(format: \"%02hhx\", $0) }.joined()\nlet outputString = \"public let \\(variableName) = \\(dataAsHex.quotedForSourceCode)\\n\"\nlet outputData = outputString.data(using: .utf8)\nFileManager.default.createFile(atPath: outputFile, contents: outputData)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Sources/MySourceGenBuildToolLib/library.swift",
    "content": "import Foundation\n\nextension String {\n    \n    public var quotedForSourceCode: String {\n        return \"\\\"\" + self\n            .replacingOccurrences(of: \"\\\\\", with: \"\\\\\\\\\")\n            .replacingOccurrences(of: \"\\\"\", with: \"\\\\\\\"\")\n            + \"\\\"\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Sources/MySourceGenRuntimeLib/library.swift",
    "content": "public func GetLibraryName() -> String {\n    return \"MySourceGenRuntimeLib\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI/Tests/MySourceGenPluginTests/MySourceGenPluginTests.swift",
    "content": "import XCTest\nimport class Foundation.Bundle\n\nfinal class SwiftyProtobufTests: XCTestCase {\n    func testExample() throws {\n        // This is an example of a functional test case.\n        // Use XCTAssert and related functions to verify your tests produce the correct\n        // results.\n\n        // Some of the APIs that we use below are available in macOS 10.13 and above.\n        guard #available(macOS 10.13, *) else {\n            return\n        }\n\n        // Mac Catalyst won't have `Process`, but it is supported for executables.\n        #if !targetEnvironment(macCatalyst)\n\n        let fooBinary = productsDirectory.appendingPathComponent(\"MySourceGenTool\")\n\n        let process = Process()\n        process.executableURL = fooBinary\n\n        let pipe = Pipe()\n        process.standardOutput = pipe\n\n        try process.run()\n        process.waitUntilExit()\n\n        let data = pipe.fileHandleForReading.readDataToEndOfFile()\n        let output = String(data: data, encoding: .utf8)\n\n        XCTAssertEqual(output, \"Hello, world!\\n\")\n        #endif\n    }\n\n    /// Returns path to the built products directory.\n    var productsDirectory: URL {\n      #if os(macOS)\n        for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(\".xctest\") {\n            return bundle.bundleURL.deletingLastPathComponent()\n        }\n        fatalError(\"couldn't find the products directory\")\n      #else\n        return Bundle.main.bundleURL\n      #endif\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginCanBeReferencedByProductName/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"PluginCanBeReferencedByProductName\",\n    products: [\n        .plugin(name: \"MyPluginProduct\", targets: [\"MyPlugin\"]),\n    ],\n    targets: [\n        .target(name: \"PluginCanBeReferencedByProductName\", plugins: [\"MyPluginProduct\"]),\n        .executableTarget(name: \"Exec\"),\n        .plugin(name: \"MyPlugin\", capability: .buildTool(), dependencies: [\"Exec\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginCanBeReferencedByProductName/Plugins/MyPlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PackagePlugin.PluginContext, target: PackagePlugin.Target) async throws -> [PackagePlugin.Command] {\n        let output = context.pluginWorkDirectoryURL.appendingPathComponent(\"gen.swift\")\n        return [\n            .buildCommand(displayName: \"Generating code\",\n                          executable: try context.tool(named: \"Exec\").url,\n                          arguments: [output.path],\n                          outputFiles: [output])\n        ]\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginCanBeReferencedByProductName/Sources/Exec/main.swift",
    "content": "import Foundation\n\nlet output = ProcessInfo.processInfo.arguments[1]\ntry \"let stringConstant = \\\"Hello, World!\\\"\".write(to: URL(fileURLWithPath: output), atomically: true, encoding: .utf8)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginCanBeReferencedByProductName/Sources/PluginCanBeReferencedByProductName/PluginCanBeReferencedByProductName.swift",
    "content": "public struct PluginCanBeReferencedByProductName {\n    public private(set) var text = stringConstant\n\n    public init() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyLibrary/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyLibrary\",\n    dependencies: [\n        .package(path: \"../MyPlugin\")\n    ],\n    targets: [\n        .target(\n            name: \"MyLibrary\"\n        ),\n        .testTarget(\n            name: \"MyLibraryTests\",\n            dependencies: [\"MyLibrary\"]\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyLibrary/Sources/MyLibrary/library.swift",
    "content": "public func Foo() -> String {\n    return \"Foo\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyLibrary/Tests/MyLibraryTests/test.swift",
    "content": "import XCTest\nimport MyLibrary\n\nfinal class MyLibraryTests: XCTestCase {\n    \n    func testLibrary() throws {\n        XCTAssertEqual(Foo(), \"Foo\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyPlugin/Libraries/LocalToolHelperLibrary/library.swift",
    "content": "public func LocalToolHelperFunction() -> String {\n    return \"local\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyPlugin/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyPlugin\",\n    products: [\n        .plugin(\n            name: \"MyPlugin\",\n            targets: [\"MyPlugin\"]\n        ),\n    ],\n    dependencies: [\n        .package(path: \"../RemoteTool\"),\n    ],\n    targets: [\n        .plugin(\n            name: \"MyPlugin\",\n            capability: .command(\n                intent: .custom(\n                    verb: \"my-plugin\",\n                    description: \"Tester plugin\"\n                )\n            ),\n            dependencies: [\n                .product(name: \"RemoteTool\", package: \"RemoteTool\"),\n                \"LocalTool\",\n                \"ImpliedLocalTool\",\n            ]\n        ),\n        .executableTarget(\n            name: \"LocalTool\",\n            dependencies: [\"LocalToolHelperLibrary\"],\n            path: \"Tools/LocalTool\"\n        ),\n        .executableTarget(\n            name: \"ImpliedLocalTool\",\n            dependencies: [\"LocalToolHelperLibrary\"],\n            path: \"Tools/ImpliedLocalTool\"\n        ),\n        .target(\n            name: \"LocalToolHelperLibrary\",\n            path: \"Libraries/LocalToolHelperLibrary\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyPlugin/Plugins/MyPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: CommandPlugin {\n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        for name in [\"RemoteTool\", \"LocalTool\", \"ImpliedLocalTool\"] {\n            let tool = try context.tool(named: name)\n            print(\"tool path is \\(tool.path)\")\n            \n            do {\n                let process = Process()\n                process.executableURL = URL(fileURLWithPath: tool.path.string)\n                try process.run()\n            }\n            catch {\n                print(\"error: \\(error)\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyPlugin/Tools/ImpliedLocalTool/main.swift",
    "content": "import LocalToolHelperLibrary\n\nprint(\"A message from the implied \\(LocalToolHelperFunction()) tool.\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/MyPlugin/Tools/LocalTool/main.swift",
    "content": "import LocalToolHelperLibrary\n\nprint(\"A message from the \\(LocalToolHelperFunction()) tool.\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/RemoteTool/Libraries/RemoteToolHelperLibrary/library.swift",
    "content": "public func RemoteToolHelperLibraryFunction() -> String {\n    return \"remote\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/RemoteTool/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"RemoteTool\",\n    products: [\n        .executable(\n            name: \"RemoteTool\",\n            targets: [\"RemoteTool\"]\n        ),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"RemoteTool\",\n            dependencies: [\"RemoteToolHelperLibrary\"],\n            path: \"Tools/RemoteTool\"\n        ),\n        .target(\n            name: \"RemoteToolHelperLibrary\",\n            path: \"Libraries/RemoteToolHelperLibrary\"\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool/RemoteTool/Tools/RemoteTool/main.swift",
    "content": "import RemoteToolHelperLibrary\n\nprint(\"A message from the \\(RemoteToolHelperLibraryFunction()) tool.\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginWithInternalExecutable/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"PluginWithInternalExecutable\",\n    products: [\n        .plugin(\n            name: \"PluginScriptProduct\",\n            targets: [\"PluginScriptTarget\"]\n        ),\n    ],\n    targets: [\n        .plugin(\n            name: \"PluginScriptTarget\",\n            capability: .buildTool(),\n            dependencies: [\n                \"PluginExecutable\",\n            ]\n        ),\n        .executableTarget(\n            name: \"PluginExecutable\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginWithInternalExecutable/Plugins/PluginScriptTarget/Script.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct PluginScript: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        print(\"Hello from the plugin script!\")\n        guard let target = target as? SourceModuleTarget else { return [] }\n        return try target.sourceFiles.map{ $0.url }.compactMap { (url: URL) -> Command? in\n            guard url.pathExtension == \"dat\" else { return nil }\n            let outputName = url.deletingPathExtension().appendingPathExtension(\"swift\").lastPathComponent\n            let outputPath = context.pluginWorkDirectoryURL.appendingPathComponent(outputName)\n            return .buildCommand(\n                displayName:\n                    \"Generating \\(outputName) from \\(url.lastPathComponent)\",\n                executable:\n                    try context.tool(named: \"PluginExecutable\").url,\n                arguments: [\n                    url.path,\n                    outputPath.path,\n                ],\n                inputFiles: [\n                    url,\n                ],\n                outputFiles: [\n                    outputPath\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginWithInternalExecutable/Sources/PluginExecutable/Utilities.swift",
    "content": "import Foundation\n\nextension String {\n\n    var quotedForSourceCode: String {\n        return \"\\\"\" + self\n            .replacingOccurrences(of: \"\\\\\", with: \"\\\\\\\\\")\n            .replacingOccurrences(of: \"\\\"\", with: \"\\\\\\\"\")\n            + \"\\\"\"\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginWithInternalExecutable/Sources/PluginExecutable/main.swift",
    "content": "import Foundation\n\n// Sample source generator tool that emits a Swift variable declaration of a string containing the hex representation of the contents of a file as a quoted string.  The variable name is the base name of the input file.  The input file is the first argument and the output file is the second.\nif ProcessInfo.processInfo.arguments.count != 3 {\n    print(\"usage: MySourceGenBuildTool <input> <output>\")\n    exit(1)\n}\nlet inputFile = ProcessInfo.processInfo.arguments[1]\nlet outputFile = ProcessInfo.processInfo.arguments[2]\n\nlet variableName = URL(fileURLWithPath: inputFile).deletingPathExtension().lastPathComponent\n\nlet inputData = FileManager.default.contents(atPath: inputFile) ?? Data()\nlet dataAsHex = inputData.map { String(format: \"%02hhx\", $0) }.joined()\nlet outputString = \"public let \\(variableName) = \\(dataAsHex.quotedForSourceCode)\\n\"\nlet outputData = outputString.data(using: .utf8)\nFileManager.default.createFile(atPath: outputFile, contents: outputData)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Package.swift",
    "content": "// swift-tools-version: 5.9\nimport PackageDescription\n\nlet package = Package(\n    name: \"PluginsAndSnippets\",\n    products: [\n        .plugin(\n            name: \"PluginScriptProduct\",\n            targets: [\n                \"PluginScriptTarget\"\n            ],\n        ),\n        .library(\n            name: \"MyLib\",\n            targets: [\n                \"MyLib\",\n            ],\n        ),\n    ],\n    targets: [\n        .plugin(\n            name: \"PluginScriptTarget\",\n            capability: .command(\n                intent: .custom(\n                    verb: \"do-something\",\n                    description: \"Do something\",\n                ),\n            ),\n        ),\n        .target(name: \"MyLib\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Plugins/PluginScriptTarget/Script.swift",
    "content": "import PackagePlugin\n\n@main\nstruct PluginScript: CommandPlugin {\n    \n    func performCommand(context: PluginContext, arguments: [String]) async throws {\n        if !arguments.contains(\"--skip-dump\") {\n            dump(context)\n        }\n        if let target = try context.package.targets(named: [\"MySnippet\"]).first as? SourceModuleTarget {\n            print(\"type of snippet target: \\(target.kind)\")\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Snippets/ContainsMain.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n\n@main\nstruct foo {\n    static func main() {\n        print(\"hello, snippets. File: \\(#file)\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Snippets/ImportsProductTarget.swift",
    "content": "import MyLib\n\nlibraryCall()"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Snippets/MySnippet.swift",
    "content": "print(\"hello, snippets. File: \\(#file)\")"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Snippets/SubDirectory/main.swift",
    "content": "print(\"hello, snippets! File: \\(#file)\")"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Sources/MyLib/MyLib.swift",
    "content": "public func libraryCall() {\n    print(\"From library\")\n    print(\"hello, snippets. File: \\(#file)\")\n}"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PrebuildDependsExecutableTarget/Package.swift",
    "content": "// swift-tools-version: 6.3\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"PrebuildDependsExecutableTarget\",\n    platforms: [ .macOS(.v13) ],\n    dependencies: [\n    ],\n    targets: [\n        .executableTarget(name: \"MyExecutable\"),\n\n        .plugin(\n            name: \"MyPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                \"MyExecutable\"\n            ]\n        ),\n\n        .executableTarget(\n            name: \"MyClient\",\n            plugins: [\n                \"MyPlugin\",\n            ]\n        ),\n    ],\n    swiftLanguageModes: [.v5]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PrebuildDependsExecutableTarget/Plugins/MyPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n        let outputFilePath = context.pluginWorkDirectoryURL.appendingPathComponent(\"MyGeneratedFile.swift\")\n\n        // We are attempting to assemble a prebuild command that relies on an executable that hasn't\n        // been built yet. This should result in an error in prebuild.\n        let myExecutable = try context.tool(named: \"MyExecutable\")\n\n        return [\n            .prebuildCommand(\n                displayName: \"Prebuild that runs MyExecutable\",\n                executable: myExecutable.url,\n                arguments: [\"--output-file-path\", outputFilePath.path],\n                outputFilesDirectory: context.pluginWorkDirectoryURL\n            )\n        ]\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PrebuildDependsExecutableTarget/Sources/MyClient/client.swift",
    "content": "@main\nstruct Client {\n    static func main() throws {\n        print(MyGeneratedStruct.message)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/PrebuildDependsExecutableTarget/Sources/MyExecutable/tool.swift",
    "content": "import Foundation\n\n@main\nstruct Tool {\n    static func main() async throws {\n        print(\"warning: Whoops! Coming from the executable\", to: &StdErr.shared)\n        \n        let path = CommandLine.arguments[2]\n        print(\"Writing a file to \\(path)\")\n        \n        try #\"\"\"\n        public struct MyGeneratedStruct {\n            public static var message: String = \"You got struct'd\"\n        }\n        \"\"\"#.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8)\n    }\n}\n\nstruct StdErr: TextOutputStream {\n    static var shared: Self = .init()\n    mutating func write(_ string: String) {\n        string.withCString { ptr in\n            _ = fputs(ptr, stderr)\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SandboxTesterPlugin/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"SandboxTesterPlugin\",\n    targets: [\n        // A local tool that uses a build tool plugin.\n        .executableTarget(\n            name: \"MyLocalTool\",\n            plugins: [\n                \"MySourceGenBuildToolPlugin\",\n            ]\n        ),\n        // The plugin that tries to write outside the sandbox.\n        .plugin(\n            name: \"MySourceGenBuildToolPlugin\",\n            capability: .buildTool()\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SandboxTesterPlugin/Plugins/MySourceGenBuildToolPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    \n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        guard let target = target as? SourceModuleTarget else { return [] }\n \n        // Check that we can write to the output directory.\n        let allowedOutputPath = context.pluginWorkDirectory.string + \"/\" + UUID().uuidString\n        if mkdir(allowedOutputPath, 0o777) != 0 {\n             throw StringError(\"unexpectedly could not write to '\\(allowedOutputPath)': \\(String(utf8String: strerror(errno)))\")\n        }\n        rmdir(allowedOutputPath)\n\n        // Check that we cannot write to the user's home directory.\n        let disallowedOutputPath = NSHomeDirectory() + \"/\" + UUID().uuidString\n        if mkdir(disallowedOutputPath, 0o777) == 0 {\n             throw StringError(\"unexpectedly could write to '\\(disallowedOutputPath)'\")\n        }\n        \n        // Check that we can write to the temporary directory.\n        let allowedTemporaryPath = NSTemporaryDirectory() + \"/\" + UUID().uuidString\n        if mkdir(allowedTemporaryPath, 0o777) != 0 {\n             throw StringError(\"unexpectedly could not write to '\\(allowedTemporaryPath)': \\(String(utf8String: strerror(errno)))\")\n        }\n        rmdir(allowedTemporaryPath)\n\n        return []\n    }\n\n    struct StringError: Error, CustomStringConvertible {\n        var error: String\n        init(_ error: String) {\n            self.error = error\n        }\n        var description: String { error }\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SandboxTesterPlugin/Sources/MyLocalTool/main.swift",
    "content": "print(\"Hello plugin\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SandboxViolatingBuildToolPluginCommands/MyLibrary/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyLibrary\",\n    dependencies: [\n        .package(path: \"../MyPlugin\")\n    ],\n    targets: [\n        .target(\n            name: \"MyLibrary\",\n            plugins: [\n                .plugin(name: \"PackageScribblerPlugin\", package: \"MyPlugin\")\n            ])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SandboxViolatingBuildToolPluginCommands/MyLibrary/Sources/MyLibrary/library.swift",
    "content": "public func MyLibraryStruct() -> String {\n    return \"This is \\(foo)\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SandboxViolatingBuildToolPluginCommands/MyPlugin/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyPlugin\",\n    products: [\n        .plugin(\n            name: \"PackageScribblerPlugin\",\n            targets: [\"PackageScribblerPlugin\"]\n        ),\n    ],\n    targets: [\n        .plugin(\n            name: \"PackageScribblerPlugin\",\n            capability: .buildTool()\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SandboxViolatingBuildToolPluginCommands/MyPlugin/Plugins/PackageScribblerPlugin/plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n\n    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n        let outputDir = target.directory.appending(\"generated\")\n        try FileManager.default.createDirectory(atPath: outputDir.string, withIntermediateDirectories: true)\n        return [\n            .prebuildCommand(\n                displayName: \"Creating Foo.swift in the target directory…\",\n                executable: Path(\"/bin/bash\"),\n                arguments: [ \"-c\", \"echo 'let foo = \\\"\\(target.name)\\\"' > '\\(outputDir)/foo.swift'\" ],\n                outputFilesDirectory: outputDir)\n        ]\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SwiftFilePlugin/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"SwiftFilePluginFixture\",\n    products: [\n        .library(\n            name: \"SwiftFilePluginFixture\",\n            targets: [\"SwiftFilePluginFixture\"]\n        ),\n    ],\n    targets: [\n        .target(\n            name: \"SwiftFilePluginFixture\",\n            plugins: [\n                .plugin(name: \"MyCustomBuildTool\")\n            ]\n        ),\n        .plugin(\n            name: \"MyCustomBuildTool\",\n            capability: .buildTool()\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SwiftFilePlugin/Plugins/MyCustomBuildTool/SwiftToolsBuildPlugin.swift",
    "content": "import Foundation\nimport PackagePlugin\n\n@main\nstruct SwiftToolsBuildPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n        let formatExecutable = context.package.directoryURL.appending(components: \"SimpleSwiftScript.swift\")\n        return [.buildCommand(\n            displayName: \"Run a swift script\",\n            executable: formatExecutable,\n            arguments: [],\n            inputFiles: [formatExecutable],\n            outputFiles: []\n        )]\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SwiftFilePlugin/SimpleSwiftScript.swift",
    "content": "#!/usr/bin/env swift\n\nprint(\"Hello, Build Tool Plugin!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/SwiftFilePlugin/Sources/SwiftFilePluginFixture/SwiftFilePluginFixture.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/TransitivePluginOnlyDependency/Dependencies/Library/Package.swift",
    "content": "// swift-tools-version: 5.7\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Library\",\n    products: [\n        .library(name: \"Library\", targets: [\"Library\"]),\n    ],\n    dependencies: [\n        .package(path: \"../PluginOnly\")\n    ],\n    targets: [\n        .target(name: \"Library\", plugins: [.plugin(name: \"MyPlugin\", package: \"PluginOnly\")]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/TransitivePluginOnlyDependency/Dependencies/Library/Sources/Library/Library.swift",
    "content": "public struct Library {\n    public private(set) var text = \"Hello, World!\"\n\n    public init() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/TransitivePluginOnlyDependency/Dependencies/PluginOnly/Package.swift",
    "content": "// swift-tools-version: 5.7\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"PluginOnly\",\n    products: [\n        .plugin(name: \"MyPlugin\", targets: [\"MyPlugin\"]),\n    ],\n    targets: [\n        .plugin(name: \"MyPlugin\", capability: .buildTool()),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/TransitivePluginOnlyDependency/Dependencies/PluginOnly/Plugins/MyPlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PackagePlugin.PluginContext, target: PackagePlugin.Target) async throws -> [PackagePlugin.Command] {\n        return []\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/TransitivePluginOnlyDependency/Package.swift",
    "content": "// swift-tools-version: 5.7\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"TransitivePluginOnlyDependency\",\n    dependencies: [\n        .package(path: \"Dependencies/Library\"),\n    ],\n    targets: [\n        .target(name: \"TransitivePluginOnlyDependency\", dependencies: [\"Library\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Plugins/TransitivePluginOnlyDependency/Sources/TransitivePluginOnlyDependency/TransitivePluginOnlyDependency.swift",
    "content": "public struct TransitivePluginOnlyDependency {\n    public private(set) var text = \"Hello, World!\"\n\n    public init() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/RequiresOlderDeploymentTarget/Foo.swift",
    "content": "@available(macOS, obsoleted: 13.0)\nfunc foo() {\n\n}\n\nfunc bar() {\n    foo()\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/RequiresOlderDeploymentTarget/Package.swift",
    "content": "// swift-tools-version:6.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    platforms: [.macOS(.v12)],\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/RootPackageWithConditionals/Package.swift",
    "content": "// swift-tools-version: 5.7\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"client\",\n    products: [\n        .library(name: \"client\", targets: [\"client\"]),\n    ],\n    dependencies: [\n    ],\n    targets: [\n        .target(name: \"client\", dependencies: [\n        \t.target(name: \"linuxOnly\", condition: .when(platforms: [.linux]))\n        ]),\n        .target(name: \"linuxOnly\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/RootPackageWithConditionals/Sources/client/client.swift",
    "content": "public struct client {\n    public private(set) var text = \"Hello, World!\"\n\n    public init() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/RootPackageWithConditionals/Sources/linuxOnly/linuxOnly.swift",
    "content": "public struct linuxOnly {\n    public private(set) var text = \"Hello, World!\"\n\n    public init() {\n#if os(Linux)\nprint(\"bestOS\")\n#else\n#error(\"not linux\")\n#endif\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ShowExecutables/app/Package.swift",
    "content": "// swift-tools-version:5.10\nimport PackageDescription\n\nlet package = Package(\n    name: \"Dealer\",\n    products: [\n        .executable(\n            name: \"dealer\",\n            targets: [\"Dealer\"]\n        ),\n    ],\n    dependencies: [\n        .package(path: \"../deck-of-playing-cards\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"Dealer\",\n            path: \"./\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ShowExecutables/app/main.swift",
    "content": "print(\"I'm the dealer\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ShowExecutables/deck-of-playing-cards/Package.swift",
    "content": "// swift-tools-version:5.10\nimport PackageDescription\n\nlet package = Package(\n    name: \"deck-of-playing-cards\",\n    products: [\n        .executable(\n            name: \"deck\",\n            targets: [\"Deck\"]\n        ),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"Deck\",\n            path: \"./\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ShowExecutables/deck-of-playing-cards/main.swift",
    "content": "print(\"I'm a deck of cards\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ShowTraits/app/Package.swift",
    "content": "// swift-tools-version:6.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"Dealer\",\n    products: [\n        .executable(\n            name: \"dealer\",\n            targets: [\"Dealer\"]\n        ),\n    ],\n    traits: [\n        .trait(name: \"trait1\", description: \"this trait is the default in app\"),\n        .trait(name: \"trait2\", description: \"this trait is not the default in app\"),\n        .default(enabledTraits: [\"trait1\"]),\n    ],\n    dependencies: [\n        .package(path: \"../deck-of-playing-cards\", traits: [\"trait3\"]),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"Dealer\",\n            path: \"./\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ShowTraits/app/main.swift",
    "content": "print(\"I'm the dealer\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ShowTraits/deck-of-playing-cards/Package.swift",
    "content": "// swift-tools-version:6.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"deck-of-playing-cards\",\n    products: [\n        .executable(\n            name: \"deck\",\n            targets: [\"Deck\"]\n        ),\n    ],\n    traits: [\n        .trait(name: \"trait3\", description: \"This trait is in a different package and not default.\")\n    ],\n    targets: [\n        .executableTarget(\n            name: \"Deck\",\n            path: \"./\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/ShowTraits/deck-of-playing-cards/main.swift",
    "content": "print(\"I'm a deck of cards\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Simple/Foo.swift",
    "content": "public func foo() {\n\t{}()\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Simple/Package.swift",
    "content": "// swift-tools-version:5.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SkipTests/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SkipTests/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Example\",\n    targets: [\n        .target(\n            name: \"Example\",\n            dependencies: []),\n        .testTarget(\n            name: \"ExampleTests\",\n            dependencies: [\"Example\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SkipTests/Sources/Example/Example.swift",
    "content": "struct Example {\n    var text = \"Hello, World!\"\n    var bool = false\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SkipTests/Tests/ExampleTests/MoreTests.swift",
    "content": "import XCTest\n@testable import Example\n\nclass MoreTests: XCTestCase {\n    func testExample3() {\n      XCTAssertEqual(Example().text, \"Hello, World!\")\n    }\n\n    func testExample4() {\n        XCTAssertEqual(Example().bool, false)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SkipTests/Tests/ExampleTests/Tests.swift",
    "content": "import XCTest\n@testable import Example\n\nclass SomeTests: XCTestCase {\n    func testExample1() {\n        XCTAssertEqual(Example().text, \"Hello, World!\")\n    }\n\n    func testExample2() {\n        XCTAssertEqual(Example().bool, false)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Spaces Fixture/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Spaces Fixture\",\n    targets: [\n        .target(\n            name: \"Module Name 2\",\n            dependencies: [\"Module Name 1\"]),\n        .target(\n            name: \"Module Name 1\",\n            dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Spaces Fixture/Sources/Module Name 1/Foo.swift",
    "content": "public class Foo {\n    var bar: Int = 0\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Spaces Fixture/Sources/Module Name 2/main.swift",
    "content": "import Module_Name_1\n\npublic class Foo {\n    var bar: Int = 0\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftBuild/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestableExe\",\n    targets: [\n        .executableTarget(\n            name: \"Test\",\n            path: \".\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftBuild/main.swift",
    "content": "print(\"done\")"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftPMXCTestHelper/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftPMXCTestHelper/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"SwiftPMXCTestHelper\",\n    targets: [\n        .target(name: \"SwiftPMXCTestHelper\", path: \"Sources\"),\n        .testTarget(name: \"SwiftPMXCTestHelperTests\", dependencies: [\"SwiftPMXCTestHelper\"]),\n        .testTarget(name: \"ObjCTests\"),\n    ]\n)\n\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftPMXCTestHelper/Sources/SwiftPMXCTestHelper.swift",
    "content": "struct SwiftPMXCTestHelper {\n\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftPMXCTestHelper/Tests/ObjCTests/ObjCTests.m",
    "content": "@import XCTest;\n\n@interface ObjCTests: XCTestCase\n@end\n\n@implementation ObjCTests\n\n- (void)testThisThing {\n}\n\n- (void)test_example {\n}\n\n- (void)nonTest {\n}\n\n@end\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftPMXCTestHelper/Tests/SwiftPMXCTestHelperTests/SwiftPMXCTestHelperTests.swift",
    "content": "import XCTest\n@testable import SwiftPMXCTestHelper\n\nclass SwiftPMXCTestHelperTests1: XCTestCase {\n\n    func testExample1() {\n    }\n\n    func test_Example2() {\n    }\n\n    func testExample3(arg: String) {\n    }\n\n    func nontest() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftRun/Package.swift",
    "content": "// swift-tools-version: 5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestableExe\",\n    targets: [\n        .executableTarget(\n            name: \"Test\",\n            path: \".\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SwiftRun/main.swift",
    "content": "print(\"done\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SystemModules/CFake/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"CFake\"\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SystemModules/CFake/module.modulemap",
    "content": "module CFake [system] {\n    header \"/tmp/fake.h\"\n    link \"fake\"\n    export *\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SystemModules/TestExec/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestExec\",\n    dependencies: [\n        .package(url: \"../CFake\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"TestExec\", path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/SystemModules/TestExec/Sources/main.swift",
    "content": "import CFake\n\nprint(\"Hello, \\(GetFakeString())!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TIF/Package.swift",
    "content": "// swift-tools-version:5.3\nimport PackageDescription\n\nlet package = Package(\n    name: \"TIF\",\n    products: [\n        .library(name: \"TIF\", targets: [\"TIF\"])\n    ],\n    targets: [\n        .target(\n            name: \"TIF\",\n            resources: [\n                .copy(\"some.txt\")\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TIF/README.md",
    "content": "# TIF\n\nA description of this package.\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TIF/Sources/TIF/SomeAlert.swift",
    "content": "//\n//  SomeAlert.swift\n//  MyFwk\n//\n//  Created by ankit on 10/31/19.\n//  Copyright © 2019 Ankit. All rights reserved.\n//\n\nimport Cocoa\n\npublic class SomeAlert: NSViewController {\n    \n    @IBOutlet var label: NSTextField!\n    \n    override public func viewDidLoad() {\n        super.viewDidLoad()\n        let bundlePath = Bundle.main.path(forResource: \"TIF_TIF\", ofType: \"bundle\")!\n      let bundle = Bundle(path: bundlePath)!\n\n        let txt = bundle.path(forResource: \"some\", ofType: \"txt\")!\n        let c = FileManager.default.contents(atPath: txt)!\n\n        label.stringValue = String(data:c, encoding: .utf8)!\n        // Do view setup here.\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TIF/Sources/TIF/SomeAlert.xib",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<document type=\"com.apple.InterfaceBuilder3.Cocoa.XIB\" version=\"3.0\" toolsVersion=\"14850.00\" targetRuntime=\"MacOSX.Cocoa\" propertyAccessControl=\"none\" useAutolayout=\"YES\" customObjectInstantitationMethod=\"direct\">\n    <dependencies>\n        <plugIn identifier=\"com.apple.InterfaceBuilder.CocoaPlugin\" version=\"14850.00\"/>\n        <capability name=\"documents saved in the Xcode 8 format\" minToolsVersion=\"8.0\"/>\n    </dependencies>\n    <objects>\n        <customObject id=\"-2\" userLabel=\"File's Owner\" customClass=\"SomeAlert\" customModule=\"MyFwk\" customModuleProvider=\"target\">\n            <connections>\n                <outlet property=\"label\" destination=\"AaI-7f-Hna\" id=\"9Qf-KY-ZKZ\"/>\n                <outlet property=\"view\" destination=\"Hz6-mo-xeY\" id=\"0bl-1N-x8E\"/>\n            </connections>\n        </customObject>\n        <customObject id=\"-1\" userLabel=\"First Responder\" customClass=\"FirstResponder\"/>\n        <customObject id=\"-3\" userLabel=\"Application\" customClass=\"NSObject\"/>\n        <customView id=\"Hz6-mo-xeY\">\n            <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"800\" height=\"521\"/>\n            <autoresizingMask key=\"autoresizingMask\" flexibleMaxX=\"YES\" flexibleMinY=\"YES\"/>\n            <subviews>\n                <imageView horizontalHuggingPriority=\"251\" verticalHuggingPriority=\"251\" translatesAutoresizingMaskIntoConstraints=\"NO\" id=\"PbM-Nr-mVI\">\n                    <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"800\" height=\"521\"/>\n                    <imageCell key=\"cell\" refusesFirstResponder=\"YES\" alignment=\"left\" imageScaling=\"proportionallyDown\" image=\"this_is_fine\" id=\"oAz-HJ-kbb\"/>\n                </imageView>\n                <textField horizontalHuggingPriority=\"251\" verticalHuggingPriority=\"750\" translatesAutoresizingMaskIntoConstraints=\"NO\" id=\"AaI-7f-Hna\">\n                    <rect key=\"frame\" x=\"373\" y=\"10\" width=\"37\" height=\"16\"/>\n                    <textFieldCell key=\"cell\" lineBreakMode=\"clipping\" title=\"Label\" id=\"8Nf-Ba-Sor\">\n                        <font key=\"font\" metaFont=\"system\"/>\n                        <color key=\"textColor\" name=\"labelColor\" catalog=\"System\" colorSpace=\"catalog\"/>\n                        <color key=\"backgroundColor\" name=\"textBackgroundColor\" catalog=\"System\" colorSpace=\"catalog\"/>\n                    </textFieldCell>\n                </textField>\n            </subviews>\n            <constraints>\n                <constraint firstItem=\"PbM-Nr-mVI\" firstAttribute=\"centerY\" secondItem=\"Hz6-mo-xeY\" secondAttribute=\"centerY\" id=\"6qc-mk-w7c\"/>\n                <constraint firstItem=\"PbM-Nr-mVI\" firstAttribute=\"centerX\" secondItem=\"Hz6-mo-xeY\" secondAttribute=\"centerX\" id=\"7oF-4c-nPi\"/>\n                <constraint firstAttribute=\"trailing\" secondItem=\"PbM-Nr-mVI\" secondAttribute=\"trailing\" id=\"Ixf-fF-M1X\"/>\n                <constraint firstItem=\"AaI-7f-Hna\" firstAttribute=\"leading\" secondItem=\"Hz6-mo-xeY\" secondAttribute=\"leading\" constant=\"375\" id=\"cSk-iC-InE\"/>\n                <constraint firstItem=\"AaI-7f-Hna\" firstAttribute=\"top\" secondItem=\"Hz6-mo-xeY\" secondAttribute=\"top\" constant=\"495\" id=\"ikr-Qp-hYt\"/>\n                <constraint firstItem=\"PbM-Nr-mVI\" firstAttribute=\"top\" secondItem=\"Hz6-mo-xeY\" secondAttribute=\"top\" id=\"pbz-et-fp8\"/>\n                <constraint firstAttribute=\"bottom\" secondItem=\"AaI-7f-Hna\" secondAttribute=\"bottom\" constant=\"10\" id=\"pwH-7O-7xL\"/>\n                <constraint firstItem=\"PbM-Nr-mVI\" firstAttribute=\"leading\" secondItem=\"Hz6-mo-xeY\" secondAttribute=\"leading\" id=\"tzP-BG-gDa\"/>\n            </constraints>\n            <point key=\"canvasLocation\" x=\"139\" y=\"189.5\"/>\n        </customView>\n    </objects>\n    <resources>\n        <image name=\"this_is_fine\" width=\"800\" height=\"450\"/>\n    </resources>\n</document>\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TIF/Sources/TIF/SomeAssets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TIF/Sources/TIF/SomeAssets.xcassets/this_is_fine.imageset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"filename\" : \"this_is_fine.jpg\",\n      \"idiom\" : \"universal\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"universal\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"universal\",\n      \"scale\" : \"3x\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TIF/Sources/TIF/some.txt",
    "content": "This is being read from some.txt file in the bundle.\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetMismatch/Package.swift",
    "content": "// swift-tools-version:5.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Sample\",\n    products: [\n        .library(\n            name: \"Sample\",\n            targets: [\n                \"Sample\"\n            ]\n        ),\n    ],\n    targets: [\n        .target(\n            name: \"Sample\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetMismatch/Sources/Sample/main.swift",
    "content": ""
  },
  {
    "path": "Fixtures/Miscellaneous/TargetPackageAccess/libPkg/Package.swift",
    "content": "// swift-tools-version:5.9\nimport PackageDescription\n\nlet package = Package(\n    name: \"libPkg\",\n    products: [\n        .executable(name: \"ExampleApp\", targets: [\"ExampleApp\"]),\n        .library(name: \"MainLib\", targets: [\"MainLib\"]),\n    ],\n    targets: [\n        .executableTarget(name: \"ExampleApp\", dependencies: [\"MainLib\"], packageAccess: false),\n        .target(name: \"MainLib\", dependencies: [\"Core\"], packageAccess: true),\n        .target(name: \"Core\", dependencies: [\"DataManager\"]),\n        .target(name: \"DataManager\", dependencies: [\"DataModel\"]),\n        .target(name: \"DataModel\"),\n        .testTarget(name: \"MainLibTests\", dependencies: [\"MainLib\"]),\n        .testTarget(name: \"BlackBoxTests\", dependencies: [\"MainLib\"], packageAccess: false)\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetPackageAccess/libPkg/Sources/Core/Core.swift",
    "content": "import DataManager\n\npublic struct PublicCore {\n    public let publicVar: Int\n    public init(publicVar: Int) {\n        self.publicVar = publicVar\n    }\n    public func publicCoreFunc() {\n        managePublicFunc()\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetPackageAccess/libPkg/Sources/DataManager/File.swift",
    "content": "import DataModel\n\npublic func managePublicFunc() -> PublicData? {\n    return nil\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetPackageAccess/libPkg/Sources/DataModel/File.swift",
    "content": "public class PublicData {}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetPackageAccess/libPkg/Sources/ExampleApp/main.swift",
    "content": "import MainLib\n\npublicFunc()\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetPackageAccess/libPkg/Sources/MainLib/Lib.swift",
    "content": "import Core\n\npublic func publicFunc() -> Int {\n    print(\"public decl\")\n    return PublicCore(publicVar: 10).publicVar\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetPackageAccess/libPkg/Tests/BlackBoxTests/BlackBoxTests.swift",
    "content": "import MainLib\nimport XCTest\n\nclass BlackBoxTests: XCTestCase {\n    func testBlackBox() {\n        let x = publicFunc()\n        XCTAssertTrue(x > 0)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TargetPackageAccess/libPkg/Tests/MainLibTests/MainLibTests.swift",
    "content": "import MainLib\nimport XCTest\n\nclass TestMainLib: XCTestCase {\n    func testMainLib() {\n        let x = publicFunc()\n        XCTAssertTrue(x > 0)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Async/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Async\",\n    targets: [\n        .target(name: \"Async\"),\n        .testTarget(name: \"AsyncTests\", dependencies: [\"Async\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Async/Sources/Async/Async.swift",
    "content": "struct Async {\n\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Async/Tests/AsyncTests/SwiftTests.swift",
    "content": "import XCTest\n@testable import Async\n\n@available(macOS 12.0, *)\nclass AsyncTests: XCTestCase {\n\n    func testAsync() async {\n    }\n\n    func testAsyncThrows() async throws {\n    }\n\n    @MainActor func testMainActor() async {\n        XCTAssertTrue(Thread.isMainThread)\n    }\n\n    func testNotAsync() {\n        XCTAssertTrue(Thread.isMainThread)\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Deprecation/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    targets: [\n        .target(name: \"Simple\"),\n        .testTarget(name: \"SimpleTests\", dependencies: [\"Simple\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Deprecation/Sources/Simple/Simple.swift",
    "content": "struct Simple {\n    func hello() {}\n\n    @available(*, deprecated, message: \"use hello instead\")\n    func deprecatedHello() {}\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Deprecation/Tests/SimpleTests/SwiftTests.swift",
    "content": "import XCTest\n@testable import Simple\n\nclass SimpleTests: XCTestCase {\n    func testHello() {\n        Simple().hello()\n    }\n\n    @available(*, deprecated, message: \"testing deprecated API\")\n    func testDeprecatedHello() {\n        Simple().deprecatedHello()\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Extensions/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    targets: [\n        .target(name: \"Simple\"),\n        .testTarget(name: \"SimpleTests\", dependencies: [\"Simple\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Extensions/Sources/Simple/Simple.swift",
    "content": "struct Simple {\n\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Extensions/Tests/SimpleTests/SwiftTests1.swift",
    "content": "import XCTest\n@testable import Simple\n\nclass SimpleTests1: XCTestCase {\n    func testExample1() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Extensions/Tests/SimpleTests/SwiftTests2.swift",
    "content": "import XCTest\n@testable import Simple\n\nclass SimpleTests2: XCTestCase {\n    func testExample2() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Extensions/Tests/SimpleTests/SwiftTests3.swift",
    "content": "import XCTest\n@testable import Simple\n\nextension SimpleTests1 {\n    func testExample1_a() {\n    }\n}\n\nextension SimpleTests2 {\n    func testExample2_a() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Extensions/Tests/SimpleTests/SwiftTests4.swift",
    "content": "import XCTest\n@testable import Simple\n\nclass SimpleTests4: XCTestCase {\n    func testExample() {\n    }\n\n    func testExample1() {\n    }\n\n    func testExample2() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/IgnoresLinuxMain/Package.swift",
    "content": "// swift-tools-version:5.10\nimport PackageDescription\n\nlet package = Package(\n    name: \"IgnoresLinuxMain\",\n    targets: [\n        .testTarget(name: \"IgnoresLinuxMainTests\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/IgnoresLinuxMain/Tests/IgnoresLinuxMainTests/SomeTest.swift",
    "content": "import XCTest\n\nfinal class SomeTests: XCTestCase {\n    func testSomething() {}\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/IgnoresLinuxMain/Tests/LinuxMain.swift",
    "content": "fatalError(\"Should not use the contents of LinuxMain.swift\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/NoTests/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    targets: [\n        .target(name: \"Simple\"),\n        .testTarget(name: \"SimpleTests\", dependencies: [\"Simple\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/NoTests/Sources/Simple/Simple.swift",
    "content": "struct Simple {\n\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/NoTests/Tests/SimpleTests/SwiftTests.swift",
    "content": "\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Simple/Package.swift",
    "content": "// swift-tools-version:5.8\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    targets: [\n        .target(name: \"Simple\", plugins: [\"SimplePlugin\"]),\n        .testTarget(name: \"SimpleTests\", dependencies: [\"Simple\"]),\n        .plugin(name: \"SimplePlugin\", capability: .buildTool()),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Simple/Plugins/SimplePlugin/plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct Simple: BuildToolPlugin {\n    func createBuildCommands(context: PackagePlugin.PluginContext, target: PackagePlugin.Target) async throws -> [PackagePlugin.Command] {\n        return []\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Simple/Sources/Simple/Simple.swift",
    "content": "struct Simple {\n\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Simple/Tests/SimpleTests/SwiftTests.swift",
    "content": "import XCTest\n@testable import Simple\n\nclass SimpleTests: XCTestCase {\n\n    func testExample1() {\n    }\n\n    func test_Example2() {\n    }\n\n    func testThrowing() throws {\n    }\n\n    func testWithArgs(arg: String) {\n    }\n\n    func nontest() {\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Subclass/Package.swift",
    "content": "// swift-tools-version:5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"Subclass\",\n    targets: [\n        .target(name: \"Subclass\"),\n        .testTarget(name: \"Module1Tests\", dependencies: [\"Subclass\"]),\n        .testTarget(name: \"Module2Tests\", dependencies: [\"Subclass\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Subclass/Sources/Subclass/Subclass.swift",
    "content": "struct Subclass {\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Subclass/Tests/Module1Tests/Tests1.swift",
    "content": "import XCTest\n\nclass Tests1: XCTestCase {\n    func test11() {\n      print(\"->Module1::Tests1::test11\")\n    }\n\n    func test12() {\n      print(\"->Module1::Tests1::test12\")\n    }\n\n    func test13() {\n      print(\"->Module1::Tests1::test13\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Subclass/Tests/Module1Tests/Tests2.swift",
    "content": "import XCTest\n\nclass Tests3: Tests2 {\n    override func test11() {\n      print(\"->Module1::Tests3::test11\")\n    }\n\n    override func test21() {\n      print(\"->Module1::Tests3::test21\")\n    }\n\n    func test31() {\n      print(\"->Module1::Tests3::test31\")\n    }\n\n    func test32() {\n      print(\"->Module1::Tests3::test32\")\n    }\n\n    func test33() {\n      print(\"->Module1::Tests3::test33\")\n    }\n}\n\nclass Tests2: Tests1 {\n    func test21() {\n      print(\"->Module1::Tests2::test21\")\n    }\n\n    func test22() {\n      print(\"->Module1::Tests2::test22\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/Subclass/Tests/Module2Tests/Test1.swift",
    "content": "import XCTest\n\nclass Tests1: XCTestCase {\n    func test11() {\n      print(\"->Module2::Tests1::test11\")\n    }\n\n    func test12() {\n      print(\"->Module2::Tests1::test12\")\n    }\n\n    func test13() {\n      print(\"->Module2::Tests1::test13\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/SwiftTesting/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"SwiftTesting\",\n    targets: [\n        .testTarget(name: \"SwiftTestingTests\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/SwiftTesting/Sources/SwiftTesting/SwiftTesting.swift",
    "content": "\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/SwiftTesting/Tests/SwiftTestingTests/SwiftTestingTests.swift",
    "content": "import Testing\n@Test(\"SOME TEST FUNCTION\") func someTestFunction() {}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/hello world/Package.swift",
    "content": "// swift-tools-version:5.3\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"hello world\",\n    products: [\n        // Products define the executables and libraries a package produces, and make them visible to other packages.\n        .library(\n            name: \"hello world\",\n            targets: [\"hello world\"]),\n    ],\n    dependencies: [\n        // Dependencies declare other packages that this package depends on.\n        // .package(url: /* package url */, from: \"1.0.0\"),\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n        // Targets can depend on other targets in this package, and on products in packages this package depends on.\n        .target(\n            name: \"hello world\",\n            dependencies: []),\n        .testTarget(\n            name: \"hello world tests\",\n            dependencies: [\"hello world\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/hello world/Sources/hello world/hello world.swift",
    "content": "struct hello_world {\n    var text = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestDiscovery/hello world/Tests/hello world tests/hello world tests.swift",
    "content": "import XCTest\n@testable import hello_world\n\nfinal class hello_worldTests: XCTestCase {\n    func testExample() {\n        // This is an example of a functional test case.\n        // Use XCTAssert and related functions to verify your tests produce the correct\n        // results.\n        XCTAssertEqual(hello_world().text, \"Hello, World!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestMultipleFailureSwiftTesting/Package.swift",
    "content": "// swift-tools-version: 6.0\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestMultipleFailureSwiftTesting\",\n    targets: [\n        .testTarget(\n            name: \"TestMultipleFailureSwiftTestingTests\"\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestMultipleFailureSwiftTesting/Tests/TestMultipleFailureSwiftTestingTests/TestMultipleFailureSwiftTestingTests.swift",
    "content": "import Testing\n\n@Test func testFailure1() async throws {\n    #expect(Bool(false), \"ST Test failure 1\")\n}\n\n@Test func testFailure2() async throws {\n    #expect(Bool(false), \"ST Test failure 2\")\n}\n\n@Test func testFailure3() async throws {\n    #expect(Bool(false), \"ST Test failure 3\")\n}\n\n@Test func testFailure4() async throws {\n    #expect(Bool(false), \"ST Test failure 4\")\n}\n\n@Test func testFailure5() async throws {\n    #expect(Bool(false), \"ST Test failure 5\")\n}\n\n@Test func testFailure6() async throws {\n    #expect(Bool(false), \"ST Test failure 6\")\n}\n\n@Test func testFailure7() async throws {\n    #expect(Bool(false), \"ST Test failure 7\")\n}\n\n@Test func testFailure8() async throws {\n    #expect(Bool(false), \"ST Test failure 8\")\n}\n\n@Test func testFailure9() async throws {\n    #expect(Bool(false), \"ST Test failure 9\")\n}\n\n@Test func testFailure10() async throws {\n    #expect(Bool(false), \"ST Test failure 10\")\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestMultipleFailureXCTest/Package.swift",
    "content": "// swift-tools-version: 5.9\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestMultipleFailureXCTest\",\n    targets: [\n        .testTarget(\n            name: \"TestMultipleFailureXCTestTests\"\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestMultipleFailureXCTest/Tests/TestMultipleFailureXCTestTests/TestMultipleFailureXCTestTests.swift",
    "content": "import XCTest\n\nfinal class TestMultipleFailureXCTestTests: XCTestCase {\n    func testFailure1() throws {\n        XCTAssertFalse(true, \"Test failure 1\")\n    }\n\n    func testFailure2() throws {\n        XCTAssertFalse(true, \"Test failure 2\")\n    }\n\n    func testFailure3() throws {\n        XCTAssertFalse(true, \"Test failure 3\")\n    }\n\n    func testFailure4() throws {\n        XCTAssertFalse(true, \"Test failure 4\")\n    }\n\n    func testFailure5() throws {\n        XCTAssertFalse(true, \"Test failure 5\")\n    }\n\n    func testFailure6() throws {\n        XCTAssertFalse(true, \"Test failure 6\")\n    }\n\n    func testFailure7() throws {\n        XCTAssertFalse(true, \"Test failure 7\")\n    }\n\n    func testFailure8() throws {\n        XCTAssertFalse(true, \"Test failure 8\")\n    }\n\n    func testFailure9() throws {\n        XCTAssertFalse(true, \"Test failure 9\")\n    }\n\n    func testFailure10() throws {\n        XCTAssertFalse(true, \"Test failure 10\")\n    }\n\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestSingleFailureSwiftTesting/Package.swift",
    "content": "// swift-tools-version: 5.9\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestFailuresSwiftTesting\",\n    targets: [\n        .testTarget(\n            name: \"TestFailuresSwiftTestingTests\"\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestSingleFailureSwiftTesting/Tests/TestFailuresSwiftTestingTests/TestFailuresSwiftTestingTests.swift",
    "content": "import Testing\n\n@Test func example() async throws {\n    #expect(Bool(false), \"Purposely failing & validating XML espace \\\"'<>\")\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestSingleFailureXCTest/Package.swift",
    "content": "// swift-tools-version: 5.9\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestFailures\",\n    targets: [\n        .testTarget(\n            name: \"TestFailuresTests\"\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestSingleFailureXCTest/Tests/TestFailuresTests/TestFailuresTests.swift",
    "content": "import XCTest\n\nfinal class TestFailuresTests: XCTestCase {\n    func testExample() throws {\n        XCTAssertFalse(true, \"Purposely failing & validating XML espace \\\"'<>\")\n    }\n}\n\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableAsyncExe/Package.swift",
    "content": "// swift-tools-version: 5.5\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestableAsyncExe\",\n    platforms: [\n        .macOS(.v10_15),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"TestableAsyncExe1\"\n        ),\n        .executableTarget(\n            name: \"TestableAsyncExe2\"\n        ),\n        .executableTarget(\n            name: \"TestableAsyncExe3\"\n        ),\n        .executableTarget(\n            name: \"TestableAsyncExe4\"\n        ),\n        .testTarget(\n            name: \"TestableAsyncExeTests\",\n            dependencies: [\n                \"TestableAsyncExe1\",\n                \"TestableAsyncExe2\",\n                \"TestableAsyncExe3\",\n                \"TestableAsyncExe4\",\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableAsyncExe/Sources/TestableAsyncExe1/main.swift",
    "content": "public func GetAsyncGreeting1() async -> String {\n    return \"Hello, async world\"\n}\n\nawait print(\"\\(GetAsyncGreeting1())!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableAsyncExe/Sources/TestableAsyncExe2/main.swift",
    "content": "public func GetAsyncGreeting2() async -> String {\n    return \"Hello, async planet\"\n}\n\nawait print(\"\\(GetAsyncGreeting2())!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableAsyncExe/Sources/TestableAsyncExe3/NonMain.swift",
    "content": "@main\nstruct AsyncMain3 {\n  static func main() async {\n    print(await getGreeting3())\n  }\n\n  static func getGreeting3() async -> String {\n      return \"Hello, async galaxy\"\n  }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableAsyncExe/Sources/TestableAsyncExe4/NonMain.swift",
    "content": "@main\nstruct AsyncMain4 {\n  static func main() async {\n    print(await getGreeting4())\n  }\n\n  static func getGreeting4() async -> String {\n      return \"Hello, async universe\"\n  }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableAsyncExe/Tests/TestableAsyncExeTests/TestableAsyncExeTests.swift",
    "content": "import XCTest\n@testable import TestableAsyncExe1\n@testable import TestableAsyncExe2\n@testable import TestableAsyncExe3\n@testable import TestableAsyncExe4\n\nfinal class TestableAsyncExeTests: XCTestCase {\n    func testExample() async throws {\n        let greeting1 = await GetAsyncGreeting1()\n        print(greeting1)\n        XCTAssertEqual(greeting1, \"Hello, async world\")\n\n        let greeting2 = await GetAsyncGreeting2()\n        print(greeting2)\n        XCTAssertEqual(greeting2, \"Hello, async planet\")\n\n        let greeting3 = await AsyncMain3.getGreeting3()\n        print(greeting3)\n        XCTAssertEqual(greeting3, \"Hello, async galaxy\")\n\n        let greeting4 = await AsyncMain4.getGreeting4()\n        print(greeting4)\n        XCTAssertEqual(greeting4, \"Hello, async universe\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExe/Package.swift",
    "content": "// swift-tools-version: 5.5\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestableExe\",\n    targets: [\n        .executableTarget(\n            name: \"TestableExe1\",\n            linkerSettings: [\n                .linkedLibrary(\"swiftCore\", .when(platforms: [.windows])), // for swift_addNewDSOImage\n            ]\n        ),\n        .executableTarget(\n            name: \"TestableExe2\",\n            linkerSettings: [\n                .linkedLibrary(\"swiftCore\", .when(platforms: [.windows])), // for swift_addNewDSOImage\n            ]\n\n        ),\n        .executableTarget(\n            name: \"TestableExe3\",\n            linkerSettings: [\n                .linkedLibrary(\"swiftCore\", .when(platforms: [.windows])), // for swift_addNewDSOImage\n            ]\n        ),\n        .testTarget(\n            name: \"TestableExeTests\",\n            dependencies: [\n                \"TestableExe1\",\n                \"TestableExe2\",\n                \"TestableExe3\",\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExe/Sources/TestableExe1/main.swift",
    "content": "public func GetGreeting1() -> String {\n    return \"Hello, world\"\n}\n\nprint(\"\\(GetGreeting1())!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExe/Sources/TestableExe2/main.swift",
    "content": "public func GetGreeting2() -> String {\n    return \"Hello, planet\"\n}\n\nprint(\"\\(GetGreeting2())!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExe/Sources/TestableExe3/include/TestableExe3.h",
    "content": "const char * GetGreeting3();"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExe/Sources/TestableExe3/main.c",
    "content": "#include <stdio.h>\n#include \"include/TestableExe3.h\"\n\nconst char * GetGreeting3() {\n    return \"Hello, universe\";\n}\n\nint main() {\n    printf(\"%s!\\n\", GetGreeting3());\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExe/Tests/TestableExeTests/TestableExeTests.swift",
    "content": "import XCTest\n@testable import TestableExe1\n@testable import TestableExe2\n// import TestableExe3\nimport class Foundation.Bundle\n\nfinal class TestableExeTests: XCTestCase {\n\n  #if os(Windows)\n      let eol = \"\\r\\n\"\n#else\n      let eol = \"\\n\"\n#endif\n\n    func testExample() throws {\n        // This is an example of a functional test case.\n        // Use XCTAssert and related functions to verify your tests produce the correct\n        // results.\n\n        print(GetGreeting1())\n        XCTAssertEqual(GetGreeting1(), \"Hello, world\")\n        print(GetGreeting2())\n        XCTAssertEqual(GetGreeting2(), \"Hello, planet\")\n        // XCTAssertEqual(String(cString: GetGreeting3()), \"Hello, universe\")\n\n        // Some of the APIs that we use below are available in macOS 10.13 and above.\n        guard #available(macOS 10.13, *) else {\n            return\n        }\n\n        var execPath = productsDirectory.appendingPathComponent(\"TestableExe1\")\n        var process = Process()\n        process.executableURL = execPath\n        var pipe = Pipe()\n        process.standardOutput = pipe\n        try process.run()\n        process.waitUntilExit()\n        var data = pipe.fileHandleForReading.readDataToEndOfFile()\n        var output = String(data: data, encoding: .utf8)\n        XCTAssertEqual(output, \"Hello, world!\\(eol)\")\n\n        execPath = productsDirectory.appendingPathComponent(\"TestableExe2\")\n        process = Process()\n        process.executableURL = execPath\n        pipe = Pipe()\n        process.standardOutput = pipe\n        try process.run()\n        process.waitUntilExit()\n        data = pipe.fileHandleForReading.readDataToEndOfFile()\n        output = String(data: data, encoding: .utf8)\n        XCTAssertEqual(output, \"Hello, planet!\\(eol)\")\n\n        execPath = productsDirectory.appendingPathComponent(\"TestableExe3\")\n        process = Process()\n        process.executableURL = execPath\n        pipe = Pipe()\n        process.standardOutput = pipe\n        try process.run()\n        process.waitUntilExit()\n        data = pipe.fileHandleForReading.readDataToEndOfFile()\n        output = String(data: data, encoding: .utf8)\n        XCTAssertEqual(output, \"Hello, universe!\\(eol)\")\n    }\n\n    /// Returns path to the built products directory.\n    var productsDirectory: URL {\n      #if os(macOS)\n        for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(\".xctest\") {\n            return bundle.bundleURL.deletingLastPathComponent()\n        }\n        fatalError(\"couldn't find the products directory\")\n      #else\n        return Bundle.main.bundleURL\n      #endif\n    }\n\n    static var allTests = [\n        (\"testExample\", testExample),\n    ]\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExeWithDifferentProductName/Package.swift",
    "content": "// swift-tools-version: 5.5\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestableExe\",\n    products: [\n        .executable(name: \"testable-exe\", targets: [\"TestableExe\"])\n    ],\n    targets: [\n        .executableTarget(\n            name: \"TestableExe\"\n        ),\n        .testTarget(\n            name: \"TestableExeTests\",\n            dependencies: [\n                \"TestableExe\",\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExeWithDifferentProductName/Sources/TestableExe/main.swift",
    "content": "public func functionFromTestableExecutable() {\n    print(\"Hello, world\")\n}\n\nfunctionFromTestableExecutable()\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExeWithDifferentProductName/Tests/TestableExeTests/TestableExeTests.swift",
    "content": "import XCTest\n@testable import TestableExe\n\nfinal class TestableExeTests: XCTestCase {\n    func testExample() throws {\n        functionFromTestableExecutable()\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExeWithResources/Package.swift",
    "content": "// swift-tools-version: 6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"TestableExe\",\n    targets: [\n        .executableTarget(\n            name: \"TestableExe\",\n            resources: [.embedInCode(\"foo.txt\")]\n        ),\n        .testTarget(\n            name: \"TestableExeTests\",\n            dependencies: [\n                \"TestableExe\",\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExeWithResources/Sources/TestableExe/foo.txt",
    "content": "bar\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExeWithResources/Sources/TestableExe/main.swift",
    "content": "public func GetGreeting1() -> String {\n    return String(decoding: PackageResources.foo_txt, as: UTF8.self)\n}\n\nprint(\"\\(GetGreeting1())!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/TestableExeWithResources/Tests/TestableExeTests/TestableExeTests.swift",
    "content": "import XCTest\n@testable import TestableExe\n\nfinal class TestableExeTests: XCTestCase {\n    func testExample() throws {\n        XCTAssertEqual(GetGreeting1(), \"bar\\n\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Package.swift",
    "content": "// swift-tools-version:5.1\n\nimport PackageDescription\nimport Foundation\n\n/// This string demonstrates as many complications of Unicode as possible.\nlet complicatedString = \"πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\"\n// π U+03C0: A simple BMP scalar.\n//‎ שּׁ U+FB2C: Changes under both NFC and NFD.\n// µ U+00B5: Changes under NFKC and NFKD.\n// 𝄞 U+1D11E: Simple non‐BMP scalar.\n// 🇺🇳 U+1F1FA U+1F1F3: Multi‐scalar character.\n// 🇮🇱 U+1F1EE U+1F1F1: Second consecutive regional indicator. (Complicated grapheme breaking.)\n// x̱̱̱̱̱̄̄̄̄̄ U+0078 (U+0331 U+0304) × 5: Extremely long combining sequence. (Also reordrant under normalization.)\n\n// The following verifies that sources haven’t been normalized, which would reduce the test’s effectiveness.\nvar verify = \"\\u{03C0}\\u{0FB2C}\\u{00B5}\\u{1D11E}\\u{1F1FA}\\u{1F1F3}\\u{1F1EE}\\u{1F1F1}\\u{0078}\\u{0331}\\u{0304}\\u{0331}\\u{0304}\\u{0331}\\u{0304}\\u{0331}\\u{0304}\\u{0331}\\u{0304}\"\nassert(\n    complicatedString.unicodeScalars.elementsEqual(verify.unicodeScalars),\n    \"\\(complicatedString) ≠ \\(verify)\")\n\nlet package = Package(\n    name: complicatedString,\n    products: [\n        .library(\n            name: complicatedString,\n            targets: [complicatedString]),\n        .executable(name: complicatedString + \"‐tool\", targets: [complicatedString + \"‐tool\"])\n    ],\n    dependencies: [\n        .package(url: \"../UnicodeDependency‐\\(complicatedString)\", from: \"1.0.0\")\n    ],\n    targets: [\n        .target(\n            name: complicatedString,\n            dependencies: [.product(name: \"UnicodeDependency‐\\(complicatedString)\")]),\n        .target(\n            name: complicatedString + \"‐tool\",\n            dependencies: [.target(name: complicatedString)]),\n        .testTarget(\n            name: complicatedString + \"Tests\",\n            dependencies: [.target(name: complicatedString)]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/README.md",
    "content": "# Unicode\n\nThis fixture makes extensive use of exotic Unicode. While deliberately trying to break a as many common false assumptions as possible, *this is a valid package*, and clients are encouraged to test their functionality with it. A tool that successfully handles this package is unlikely to encounter problems with any real‐world package in any human language.\n\nThe neighbouring package `UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄` must be placed next this package and tagged with version 1.0.0. (This is necessary to use Unicode in dependency URLs in this package’s manifest.)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Sources/πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄/πשּׁµ𝄞🇺🇳x̱̱̱̱̱̄̄̄̄̄.swift",
    "content": "public struct πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄ {\n    public init() {}\n    public var πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄ = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Sources/πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄‐tool/main.swift",
    "content": "import π_µ_____x__________\n\nprint(πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄().πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Tests/LinuxMain.swift",
    "content": "import XCTest\n\nimport π_µ_____x__________Tests\n\nvar tests = [XCTestCaseEntry]()\ntests += π_µ_____x__________Tests.__allTests()\n\nXCTMain(tests)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Tests/πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄Tests/XCTestManifests.swift",
    "content": "#if !canImport(ObjectiveC)\nimport XCTest\n\nextension πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄Tests {\n    // DO NOT MODIFY: This is autogenerated, use:\n    //   `swift test --generate-linuxmain`\n    // to regenerate.\n    static let __allTests__πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄Tests = [\n        (\"testπשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\", testπשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄),\n    ]\n}\n\npublic func __allTests() -> [XCTestCaseEntry] {\n    return [\n        testCase(πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄Tests.__allTests__πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄Tests),\n    ]\n}\n#endif\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Tests/πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄Tests/πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄Tests.swift",
    "content": "import XCTest\n\n// TODO: - Can imports be made less ugly? (SR‐10839)\n//@testable import πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\n@testable import π_µ_____x__________\n// (These characters all work for identifiers. See below.)\n\nfinal class πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄Tests: XCTestCase {\n    \n    func testπשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄() {\n        XCTAssertEqual(πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄().πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄, \"Hello, World!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Utilities/SomeOtherPackage/Package.swift",
    "content": "// swift-tools-version:5.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"SomeOtherPackage\",\n    dependencies: [\n        .package(path: \"../../\"),\n    ],\n    targets: [\n        .target(\n            name: \"SomeOtherPackage\",\n            dependencies: [\"πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Utilities/SomeOtherPackage/README.md",
    "content": "# SomeOtherPackage\n\nThis nested utility package refers back to the main repository as a local dependency.\n\nIf client tools accidentally pick this package up as part of the main repository package, dependency resolution could become circular or otherwise problematic.\n\n(Prior to direct Xcode support for packages, this repository structure was a common way of hiding executable utilities from `generate-xcodeproj`, so that the main package would still be viable for iOS.)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/Unicode/Utilities/SomeOtherPackage/Sources/SomeOtherPackage/main.swift",
    "content": "print(\"Hello, world!\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄/Package.swift",
    "content": "// swift-tools-version:5.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\",\n    products: [\n        .library(\n            name: \"UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\",\n            targets: [\"UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\"]),\n    ],\n    targets: [\n        .target(\n            name: \"UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\",\n            dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄/README.md",
    "content": "# UnicodeDependency‐πשּׁµ𝄞🇺🇳x̱̱̱̱̱̄̄̄̄̄\n\nA description of this package.\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄/Sources/UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄/UnicodeDependency‐πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄.swift",
    "content": "struct UnicodeDependency_UnicodeDependency_πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄ {\n    var text = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnreachableTargets/A/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"A\",\n    products: [\n        .executable(name: \"aexec\", targets: [\"ATarget\"])\n    ],\n\tdependencies: [\n\t\t.package(url: \"../B\", from: \"1.0.0\"),\n\t\t.package(url: \"../C\", from: \"1.0.0\")\n\t],\n    targets: [\n        .target(name: \"ATarget\", dependencies: [\n\t\t\t.product(name: \"BLibrary\")\n\t\t])\n    ])\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnreachableTargets/A/Sources/ATarget/main.swift",
    "content": "import BTarget1\n\nBTarget1()\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnreachableTargets/B/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"B\",\n    products: [\n        .library(name: \"BLibrary\", targets: [\"BTarget1\"]),\n\t\t.executable(name: \"bexec\", targets: [\"BTarget2\"])\n    ],\n    targets: [\n        .target(name: \"BTarget1\", dependencies: []),\n\t\t.target(name: \"BTarget2\", dependencies: [])\n    ])\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnreachableTargets/B/Sources/BTarget1/BTarget1.swift",
    "content": "public struct BTarget1 {\n\tpublic init() {}\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnreachableTargets/B/Sources/BTarget2/main.swift",
    "content": "print(\"BTarget2\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnreachableTargets/C/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"C\",\n    products: [\n\t\t.executable(name: \"cexec\", targets: [\"CTarget\"])\n    ],\n    targets: [\n        .target(name: \"CTarget\", dependencies: [])\n    ])\n"
  },
  {
    "path": "Fixtures/Miscellaneous/UnreachableTargets/C/Sources/CTarget/main.swift",
    "content": "print(\"CTarget\")\n"
  },
  {
    "path": "Fixtures/Miscellaneous/VersionSpecificManifest/Foo.swift",
    "content": "public func foo() {\n\t{}()\n}\n"
  },
  {
    "path": "Fixtures/Miscellaneous/VersionSpecificManifest/Package.swift",
    "content": "// swift-tools-version:6.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/VersionSpecificManifest/Package@swift-5.0.swift",
    "content": "// swift-tools-version:5.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"Foo\", targets: [\"Foo\"]),\n    ],\n    targets: [\n        .target(name: \"Foo\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/WarningWithinFunction/Package.swift",
    "content": "// swift-tools-version: 5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"app\",\n    products: [\n        .executable(name: \"app\", targets: [\"app\"])\n    ],\n    targets: [\n        .executableTarget(\n          name: \"app\",\n          path: \"./\"\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Miscellaneous/WarningWithinFunction/app.swift",
    "content": "@main\nstruct App {\n  public static func main() {\n    var myvariable = 0\n  }\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps1/AppPkg/Package.swift",
    "content": "// swift-tools-version:5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"AppPkg\",\n    dependencies: [\n        .package(path: \"../UtilsPkg\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"App\",\n            dependencies: [\n                \"Utils\",\n                .product(name: \"Utils\",\n                         package: \"UtilsPkg\",\n                         moduleAliases: [\"Utils\": \"GameUtils\"])\n            ],\n            path: \"./Sources/App\"),\n        .target(\n                name: \"Utils\",\n                dependencies: [],\n                path: \"./Sources/Utils\"\n            )\n        ]\n    )\n        \n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps1/AppPkg/Sources/App/main.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nimport Utils\nimport GameUtils\n\nUtils.echoModule()\n\nlet level = LevelDetector.detect(for: \"TestUser\")\nprint(level)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps1/AppPkg/Sources/Utils/FileUtils.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\npublic func echoModule() {\n    print(\"Utils\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps1/UtilsPkg/Package.swift",
    "content": "// swift-tools-version:5.5\nimport PackageDescription\n\nlet package = Package(\n    name: \"UtilsPkg\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps1/UtilsPkg/Sources/Utils/FileUtils.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\npublic struct LevelDetector: Equatable {\n    public static func detect(for user: String) -> Int {\n        return user.count\n    }\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps2/Apkg/Package.swift",
    "content": "// swift-tools-version:5.7\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Apkg\",\n    products: [\n        .executable(name: \"AApp\", targets: [\"AApp\"]),\n        .library(name: \"Utils\", type: .dynamic, targets: [\"Utils\"]),\n    ],\n    targets: [\n        .executableTarget(name: \"AApp\", dependencies: [\"Utils\"]),\n        .target(name: \"Utils\", dependencies: [])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps2/Apkg/Sources/AApp/main.swift",
    "content": "import Utils\n\nutilsInA()\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps2/Apkg/Sources/Utils/File.swift",
    "content": "public func utilsInA() {\n    print(\"Utils in A\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps2/AppPkg/Package.swift",
    "content": "// swift-tools-version:5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"AppPkg\",\n    dependencies: [\n        .package(path: \"../Apkg\"),\n        .package(path: \"../Bpkg\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"App\",\n            dependencies: [\n                .product(name: \"Utils\",\n                         package: \"Apkg\",\n                         moduleAliases: [\"Utils\": \"AUtils\"]\n                        ),\n                .product(name: \"Utils\",\n                         package: \"Bpkg\",\n                         moduleAliases: [\"Utils\": \"BUtils\"]\n                        )\n            ]\n        ),\n    ]\n)\n\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps2/AppPkg/Sources/App/main.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nimport AUtils\nimport BUtils\n\nutilsInA()\nutilsInB()\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps2/Bpkg/Package.swift",
    "content": "// swift-tools-version:5.7\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bpkg\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: [])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/DirectDeps2/Bpkg/Sources/Utils/File.swift",
    "content": "public func utilsInB() {\n    print(\"Utils in B\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/APkg/Package.swift",
    "content": "// swift-tools-version:5.7\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"APkg\",\n    products: [\n        .library(name: \"A\", targets: [\"A\"]),\n    ],\n    dependencies: [\n        .package(path: \"../BPkg\"),\n        .package(path: \"../CPkg\"),\n    ],\n    targets: [\n        .target(name: \"A\",\n                dependencies: [\n                    .product(name: \"Utils\",\n                             package: \"BPkg\",\n                             moduleAliases: [\"Utils\": \"FooUtils\"]\n                            ),\n                    .product(name: \"Utils\",\n                             package: \"CPkg\",\n                             moduleAliases: [\"Utils\": \"CarUtils\"]\n                            ),\n                ]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/APkg/Sources/A/File.swift",
    "content": "import FooUtils\nimport CarUtils\n\npublic func funcInA() {\n    print(\"func in A\")\n    utilsInB()\n    utilsInC()\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/AppPkg/Package.swift",
    "content": "// swift-tools-version:5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"AppPkg\",\n    dependencies: [\n        .package(path: \"../APkg\"),\n        .package(path: \"../XPkg\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"App\",\n            dependencies: [\n                .product(name: \"A\",\n                         package: \"APkg\",\n                         moduleAliases: [\"FooUtils\": \"AFooUtils\"]\n                        ),\n                .product(name: \"X\",\n                         package: \"XPkg\",\n                         moduleAliases: [\"Utils\": \"XUtils\", \"FooUtils\": \"XFooUtils\"]\n                        )\n            ]),\n    ]\n)\n\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/AppPkg/Sources/App/main.swift",
    "content": "import A\nimport X\nimport AFooUtils\nimport CarUtils\nimport XFooUtils\nimport XUtils\n\nfuncInA()\nfuncInX()\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/BPkg/Package.swift",
    "content": "// swift-tools-version:5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"BPkg\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: [])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/BPkg/Sources/Utils/File.swift",
    "content": "public func utilsInB() {\n    print(\"utils in B\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/CPkg/Package.swift",
    "content": "// swift-tools-version:5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"CPkg\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: [])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/CPkg/Sources/Utils/File.swift",
    "content": "public func utilsInC() {\n    print(\"utils in C\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/XPkg/Package.swift",
    "content": "// swift-tools-version:5.7\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"XPkg\",\n    products: [\n        .library(name: \"X\", targets: [\"X\"]),\n    ],\n    dependencies: [\n        .package(path: \"../YPkg\"),\n    ],\n    targets: [\n        .target(name: \"X\",\n                dependencies: [\n                    \"Utils\",\n                    .product(name: \"Utils\",\n                             package: \"YPkg\",\n                             moduleAliases: [\"Utils\": \"FooUtils\"]\n                            ),\n                ]),\n        .target(name: \"Utils\", dependencies: [])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/XPkg/Sources/Utils/File.swift",
    "content": "public func utilsInX() {\n    print(\"utils in X\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/XPkg/Sources/X/File.swift",
    "content": "import Utils\nimport FooUtils\n\npublic func funcInX() {\n    print(\"func in X\")\n    utilsInX()\n    utilsInY()\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/YPkg/Package.swift",
    "content": "// swift-tools-version:5.6\nimport PackageDescription\n\nlet package = Package(\n    name: \"YPkg\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: [])\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps1/YPkg/Sources/Utils/File.swift",
    "content": "public func utilsInY() {\n    print(\"utils in Y\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/Apkg/Package.swift",
    "content": "// swift-tools-version:5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"Apkg\",\n    products: [\n        .library(name: \"A\", targets: [\"A\"]),\n    ],\n    dependencies: [\n        .package(path: \"../Bpkg\"),\n        .package(path: \"../Cpkg\"),\n    ],\n    targets: [\n        .target(name: \"A\",\n                dependencies: [\n                    .product(name: \"Utils\",\n                             package: \"Bpkg\",\n                             moduleAliases: [\"Utils\": \"BUtils\"]),\n                    .product(name: \"Utils\",\n                            package: \"Cpkg\",\n                            moduleAliases: [\"Utils\": \"CUtils\"]),\n                ]\n               ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/Apkg/Sources/A/File.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nimport BUtils\nimport CUtils\n\npublic func funcA() {\n    print(\"func A\")\n    BUtils.funcB()\n    CUtils.funcC()\n}\n\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/AppPkg/Package.swift",
    "content": "// swift-tools-version:5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"AppPkg\",\n    dependencies: [\n        .package(path: \"../Apkg\"),\n        .package(path: \"../Xpkg\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"App\",\n            dependencies: [\n                .product(name: \"A\",\n                         package: \"Apkg\"\n                        ),\n                .product(name: \"Utils\",\n                         package: \"Xpkg\",\n                         moduleAliases: [\"Utils\": \"XUtils\"]\n                        ),\n            ]),\n        ]\n)\n\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/AppPkg/Sources/App/main.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nimport A\nimport XUtils\n\nprint(\"START\")\n\nfuncA()\nfuncX()\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/Bpkg/Package.swift",
    "content": "// swift-tools-version:5.7\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bpkg\",\n    products: [\n        .library(name: \"Utils\", type: .static, targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\",\n                dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/Bpkg/Sources/Utils/File.swift",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\npublic func funcB() {\n    print(\"func B\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/Cpkg/Package.swift",
    "content": "// swift-tools-version: 5.5\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Cpkg\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/Cpkg/Sources/Utils/File.swift",
    "content": "public func funcC() {\n    print(\"func C\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/Xpkg/Package.swift",
    "content": "// swift-tools-version: 5.5\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Xpkg\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: []),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleAliasing/NestedDeps2/Xpkg/Sources/Utils/File.swift",
    "content": "public func funcX() {\n    print(\"func X\")\n}\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Direct/App/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"App\",\n    dependencies: [\n        .package(url: \"../CFoo\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"App\", path: \"./\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Direct/App/main.swift",
    "content": "import CFoo\n\nprint(foo())\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Direct/CFoo/C/foo.c",
    "content": "int foo() {\n    return 123;\n}\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Direct/CFoo/C/foo.h",
    "content": "int foo();\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Direct/CFoo/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"CFoo\"\n)\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Direct/CFoo/module.modulemap",
    "content": "module CFoo  {\n    header \"C/foo.h\"\n    link \"foo\"\n    export *\n}\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Transitive/packageA/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"packageA\",\n    dependencies: [\n        .package(url: \"../packageB\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"packageA\", dependencies: [\"packageB\"], path: \"Sources\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Transitive/packageA/Sources/main.swift",
    "content": "/**\n * Copyright IBM Corporation 2016\n * Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\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\nimport y\n\nlet myY = Y()\nprint(\"calling Y.bar()\")\nmyY.bar()\n\n/*\nimport x\n\nlet myX = X()\nprint(\"calling X.foo()\")\nmyX.foo()\n*/\n\t\t\t\t \n"
  },
  {
    "path": "Fixtures/ModuleMaps/Transitive/packageB/.gitignore",
    "content": ".build\nPackages\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Transitive/packageB/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"packageB\",\n    products: [\n        .library(name: \"packageB\", targets: [\"y\"]),\n    ],\n    dependencies: [\n        .package(url: \"../packageC\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"y\", dependencies: [\"packageC\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Transitive/packageB/Sources/y/y.swift",
    "content": "/**\n * Copyright IBM Corporation 2016\n * Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\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\nimport x\n\npublic class Y {\n    public init() {}\n    public func bar() {\n       print(\"Y.bar() called\")\n       let myX = X()\n       myX.foo()\n    }\n}\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Transitive/packageC/.gitignore",
    "content": ".build\nPackages\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Transitive/packageC/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"packageC\",\n    products: [\n        .library(name: \"packageC\", targets: [\"x\"]),\n    ],\n    dependencies: [\n        .package(url: \"../packageD\", from: \"1.0.0\"),\n    ],\n    targets: [\n        .target(name: \"x\", dependencies: [\"CFoo\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ModuleMaps/Transitive/packageC/Sources/x/x.swift",
    "content": "/**\n * Copyright IBM Corporation 2016\n * Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\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\nimport CFoo\n\npublic class X {\n    public init() {}\n    public func foo() {\n        print(\"X.foo() called\")\n        let jpegData = CFoo.foo()\n        print(jpegData)\n    }\n}\n"
  },
  {
    "path": "Fixtures/PIFBuilder/BasicExecutable/Package.swift",
    "content": "// swift-tools-version: 6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"BasicExecutable\",\n    targets: [\n        .executableTarget(\n            name: \"Executable\",\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PIFBuilder/BasicExecutable/Sources/BasicExecutable/BasicExecutable.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n\n@main\nstruct BasicExecutable {\n    static func main() {\n        print(\"Hello, world!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/PIFBuilder/CCPackage/Package.swift",
    "content": "// swift-tools-version: 6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"CCPackage\",\n    products: [\n        .library(name: \"CCTarget\", type: .static, targets: [\"CCTarget\"]),\n    ],\n    targets: [\n        .target(name: \"CCTarget\", ),\n        .executableTarget(name: \"executable\", dependencies: [\"CCTarget\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PIFBuilder/CCPackage/Sources/CCTarget/include/test.h",
    "content": "\n#include <string>"
  },
  {
    "path": "Fixtures/PIFBuilder/CCPackage/Sources/CCTarget/test.cc",
    "content": "\n#include <test.h>\n"
  },
  {
    "path": "Fixtures/PIFBuilder/CCPackage/Sources/executable/executable.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n\n@main\nstruct Executable {\n    static func main() {\n        print(\"Hello, world!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/PIFBuilder/ConditionalBuildSettings/Package.swift",
    "content": "// swift-tools-version: 6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ConditionalBuildSettings\",\n    products: [\n        .library(\n            name: \"ConditionalBuildSettings\",\n            type: .dynamic,\n            targets: [\"ConditionalBuildSettings\"]\n        ),\n    ],\n    targets: [\n        .target(\n            name: \"ConditionalBuildSettings\",\n            linkerSettings: [\n                .unsafeFlags([\"-Xlinker\", \"-interposable\"], .when(configuration: .debug)),\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PIFBuilder/ConditionalBuildSettings/Sources/ConditionalBuildSettings/ConditionalBuildSettings.swift",
    "content": "public func placeholder() {}\n"
  },
  {
    "path": "Fixtures/PIFBuilder/Library/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\nxcuserdata/\nDerivedData/\n.swiftpm/configuration/registries.json\n.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata\n.netrc\n"
  },
  {
    "path": "Fixtures/PIFBuilder/Library/Package.swift",
    "content": "// swift-tools-version: 6.2\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Library\",\n    products: [\n        // Products define the executables and libraries a package produces, making them visible to other packages.\n        .library(\n            name: \"LibraryAuto\",\n            targets: [\"Library\"]\n        ),\n        .library(\n            name: \"LibraryStatic\",\n            type: .static,\n            targets: [\"Library\"]\n        ),\n        .library(\n            name: \"LibraryDynamic\",\n            type: .dynamic,\n            targets: [\"Library\"]\n        ),\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package, defining a module or a test suite.\n        // Targets can depend on other targets in this package and products from dependencies.\n        .target(\n            name: \"Library\"\n        ),\n        .testTarget(\n            name: \"LibraryTests\",\n            dependencies: [\"Library\"]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PIFBuilder/Library/Sources/Library/Library.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n"
  },
  {
    "path": "Fixtures/PIFBuilder/Library/Tests/LibraryTests/LibraryTests.swift",
    "content": "import Testing\n@testable import Library\n\n@Test func example() async throws {\n    // Write your test here and use APIs like `#expect(...)` to check expected conditions.\n}\n"
  },
  {
    "path": "Fixtures/PIFBuilder/PackageWithSDKSpecialization/Package.swift",
    "content": "// swift-tools-version: 6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"PackageWithSDKSpecialization\",\n    platforms: [ .macOS(\"10.15.foo\") ],\n    products: [\n        .library(\n            name: \"PackageWithSDKSpecialization\",\n            targets: [\"PackageWithSDKSpecialization\"]),\n    ],\n    targets: [\n        .target(\n            name: \"PackageWithSDKSpecialization\",\n            dependencies: []\n        ),\n        .target(\n            name: \"Executable\",\n            dependencies: [\"PackageWithSDKSpecialization\"]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PIFBuilder/PackageWithSDKSpecialization/Sources/Executable/main.swift",
    "content": "print(\"Hello, world!\")\n"
  },
  {
    "path": "Fixtures/PIFBuilder/PackageWithSDKSpecialization/Sources/PackageWithSDKSpecialization/PackageWithSDKSpecialization.swift",
    "content": "struct PackageWithSDKSpecialization {\n    var text = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/PIFBuilder/Simple/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\nxcuserdata/\nDerivedData/\n.swiftpm/configuration/registries.json\n.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata\n.netrc\n"
  },
  {
    "path": "Fixtures/PIFBuilder/Simple/Package.swift",
    "content": "// swift-tools-version: 6.2\n// The swift-tools-version declares the minimum version of Swift required to build this package.\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Simple\",\n    products: [\n        // Products define the executables and libraries a package produces, making them visible to other packages.\n        .library(\n            name: \"Simple\",\n            targets: [\"Simple\"]\n        ),\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package, defining a module or a test suite.\n        // Targets can depend on other targets in this package and products from dependencies.\n        .target(\n            name: \"Simple\"\n        ),\n        .testTarget(\n            name: \"SimpleTests\",\n            dependencies: [\"Simple\"]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PIFBuilder/Simple/Sources/Simple/Simple.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n\npublic struct Person {\n    public let name: String\n\n    public init(name: String) {\n        self.name = name\n    }\n}\nextension Person: CustomStringConvertible {\n    public var description: String {\n        return name\n    }\n}\n\npublic func greet(person: Person? = nil) -> String {\n    let name = if let person {\n        person.name\n    } else {\n        \"World\"\n    }\n\n    return \"Hello, \\(name)!\"\n}\n"
  },
  {
    "path": "Fixtures/PIFBuilder/Simple/Tests/SimpleTests/SimpleTests.swift",
    "content": "import Testing\nimport XCTest\n\nimport Simple\n\n\nfinal public class XCTesting: XCTestCase {\n    func testGreetWithEmptyArgument() {\n        let actual = greet()\n        XCTAssertEqual(actual, \"Hello, World!\")\n    }\n\n    func testGreetWithNonEmptyArgument() {\n        let name = \"MyName\"\n        let person = Person(name: name)\n        let actual = greet(person: person)\n        XCTAssertEqual(actual, \"Hello, \\(name)!\")\n    }\n}\n\n@Suite\nstruct STTestTests {\n    @Test(\"STTest tests\")\n    func testGreetWithEmptyArgument() {\n        let actual = greet()\n        #expect(actual == \"Hello, World!\")\n    }\n\n    @Test(\"STTest tests\")\n    func testGreetWithNonEmptyArgument() {\n        let name = \"MyName\"\n        let person = Person(name: name)\n        let actual = greet(person: person)\n        #expect(actual == \"Hello, \\(name)!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/PIFBuilder/UnknownPlatforms/Package.swift",
    "content": "// swift-tools-version: 6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"UnknownPlatforms\",\n    targets: [\n        .executableTarget(\n            name: \"UnknownPlatforms\",\n            swiftSettings: [\n                .define(\"FOO\", .when(platforms: [.custom(\"DoesNotExist\")])),\n\t\t        .define(\"BAR\", .when(platforms: [.linux])),\n                .define(\"BAZ\", .when(platforms: [.macOS])),\n            ],\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PIFBuilder/UnknownPlatforms/Sources/UnknownPlatforms/UnknownPlatforms.swift",
    "content": "// The Swift Programming Language\n// https://docs.swift.org/swift-book\n\n@main\nstruct UnknownPlatforms {\n    static func main() {\n        print(\"Hello, world!\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/PartiallyUnusedDependency/Dep/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Dep\",\n    products: [\n        .library(\n            name: \"MyDynamicLibrary\",\n            type: .dynamic,\n            targets: [\"MyDynamicLibrary\"]\n        ),\n        .executable(\n            name: \"MySupportExecutable\",\n            targets: [\"MySupportExecutable\"]\n        )\n    ],\n    targets: [\n        .target(\n            name: \"MyDynamicLibrary\"\n        ),\n        .executableTarget(\n            name: \"MySupportExecutable\",\n            dependencies: [\"MyDynamicLibrary\"]\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PartiallyUnusedDependency/Dep/Sources/MyDynamicLibrary/Dep.swift",
    "content": "public func sayHello() {\n    print(\"hello!\")\n}\n"
  },
  {
    "path": "Fixtures/PartiallyUnusedDependency/Dep/Sources/MySupportExecutable/exe.swift",
    "content": "import MyDynamicLibrary\n\n@main struct Entry {\n    static func main() {\n        print(\"running support tool\")\n        sayHello()\n    }\n}\n"
  },
  {
    "path": "Fixtures/PartiallyUnusedDependency/Package.swift",
    "content": "// swift-tools-version: 6.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"PartiallyUnusedDependency\",\n    products: [\n        .executable(\n            name: \"MyExecutable\",\n            targets: [\"MyExecutable\"]\n        ),\n    ],\n    dependencies: [\n        .package(path: \"Dep\")\n    ],\n    targets: [\n        .executableTarget(\n            name: \"MyExecutable\",\n            dependencies: [.product(name: \"MyDynamicLibrary\", package: \"Dep\")]\n        ),\n        .plugin(\n            name: \"dump-artifacts-plugin\",\n            capability: .command(\n                intent: .custom(verb: \"dump-artifacts-plugin\", description: \"Dump Artifacts\"),\n                permissions: []\n            )\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/PartiallyUnusedDependency/Plugins/dump-artifacts-plugin.swift",
    "content": "import PackagePlugin\n\n@main\nstruct DumpArtifactsPlugin: CommandPlugin {\n    func performCommand(\n        context: PluginContext,\n        arguments: [String]\n    ) throws {\n        do {\n            var parameters = PackageManager.BuildParameters()\n            parameters.configuration = .debug\n            parameters.logging = .concise\n            let result = try packageManager.build(.all(includingTests: false), parameters: parameters)\n            print(\"succeeded: \\(result.succeeded)\")\n            for artifact in result.builtArtifacts {\n                print(\"artifact-path: \\(artifact.path.string)\")\n                print(\"artifact-kind: \\(artifact.kind)\")\n            }\n        }\n        catch {\n            print(\"error from the plugin host: \\\\(error)\")\n        }\n    }\n}\n"
  },
  {
    "path": "Fixtures/PartiallyUnusedDependency/Sources/MyExecutable/PartiallyUnusedDependency.swift",
    "content": "import MyDynamicLibrary\n\n@main struct Entry {\n    static func main() {\n        print(\"Hello, world!\")\n        sayHello()\n    }\n}\n"
  },
  {
    "path": "Fixtures/Resources/EmbedInCodeSimple/Package.swift",
    "content": "// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"EmbedInCodeSimple\",\n    targets: [\n        .executableTarget(name: \"EmbedInCodeSimple\", resources: [.embedInCode(\"best.txt\")]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Resources/EmbedInCodeSimple/Sources/EmbedInCodeSimple/best.txt",
    "content": "hello world\n"
  },
  {
    "path": "Fixtures/Resources/EmbedInCodeSimple/Sources/EmbedInCodeSimple/main.swift",
    "content": "import Foundation\n\nprint(\"\\(String(decoding: Data(PackageResources.best_txt), as: UTF8.self))\")\n"
  },
  {
    "path": "Fixtures/Resources/FoundationlessClient/AppPkg/Package.swift",
    "content": "// swift-tools-version:999.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"AppPkg\",\n    dependencies: [\n        .package(path: \"../UtilsPkg\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"App\",\n            dependencies: [\n                .product(name: \"Utils\", package: \"UtilsPkg\")\n            ],\n            path: \"./Sources/App\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Resources/FoundationlessClient/AppPkg/Sources/App/main.swift",
    "content": "import Utils\n// Note the lack of 'import Foundation'.\n// The purpose of this fixture is to test that the following line of code\n// expectedly *doesn't* compile:\nprint(FooUtils.foo.trimmingCharacters(in: .whitespaces))\n"
  },
  {
    "path": "Fixtures/Resources/FoundationlessClient/UtilsPkg/Package.swift",
    "content": "// swift-tools-version:999.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"UtilsPkg\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: [], resources: [\n            .copy(\"foo.txt\"),\n        ]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Resources/FoundationlessClient/UtilsPkg/Sources/Utils/FooUtils.swift",
    "content": "@frozen\npublic enum FooUtils { }\n\nextension FooUtils {\n  public static let foo: String = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/Resources/FoundationlessClient/UtilsPkg/Sources/Utils/foo.txt",
    "content": "foo\n"
  },
  {
    "path": "Fixtures/Resources/FoundationlessClient/UtilsWithFoundationPkg/Package.swift",
    "content": "// swift-tools-version:5.8\nimport PackageDescription\n\n// This package acts as a regression test for the FoundationlessPackages to\n// assert that Swift targets with resources are not affected by using\n// `@_implementationOnly import Foundation` in the generated resource accessor.\nlet package = Package(\n    name: \"UtilsWithFoundationPkg\",\n    targets: [\n        .target(\n            name: \"UtilsWithFoundationPkg\",\n            resources: [\n                .copy(\"foo.txt\"),\n            ]\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Resources/FoundationlessClient/UtilsWithFoundationPkg/Sources/UtilsWithFoundationPkg/FooUtils.swift",
    "content": "import Foundation\n\n@frozen\npublic enum FooUtils { }\n\nextension FooUtils {\n  public static let foo: String = \"Hello, World!\"\n}\n"
  },
  {
    "path": "Fixtures/Resources/FoundationlessClient/UtilsWithFoundationPkg/Sources/UtilsWithFoundationPkg/foo.txt",
    "content": "foo\n"
  },
  {
    "path": "Fixtures/Resources/Localized/Package.swift",
    "content": "// swift-tools-version:5.3\nimport PackageDescription\n\nlet package = Package(\n    name: \"Localized\",\n    defaultLocalization: \"es\",\n    targets: [\n        .target(name: \"exe\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Resources/Localized/Sources/exe/Resources/de.lproj/Localizable.strings",
    "content": "\"hello_world\" = \"Hallo Welt!\";\n"
  },
  {
    "path": "Fixtures/Resources/Localized/Sources/exe/Resources/es.lproj/Localizable.strings",
    "content": "\"hello_world\" = \"¡Hola Mundo!\";\n"
  },
  {
    "path": "Fixtures/Resources/Localized/Sources/exe/Resources/fr.lproj/Localizable.strings",
    "content": "\"hello_world\" = \"Bonjour le monde !\";\n"
  },
  {
    "path": "Fixtures/Resources/Localized/Sources/exe/main.swift",
    "content": "import Foundation\n\nfunc localizationBundle(forLanguage language: String) -> Bundle? {\n\tif let path = Bundle.module.path(forResource: language, ofType: \"lproj\") {\n\t\treturn Bundle(path: path)\n\t} else {\n\t\treturn nil\n\t}\n}\n\n// Spanish localization (based on defaultLocalization).\nprint(NSLocalizedString(\"hello_world\", bundle: .module, comment: \"\"))\n\n// German localization.\nif let germanBundle = localizationBundle(forLanguage: \"de\") {\n\tprint(NSLocalizedString(\"hello_world\", bundle: germanBundle, comment: \"\"))\n}\n\n// French localization.\nif let frenchBundle = localizationBundle(forLanguage: \"fr\") {\n\tprint(NSLocalizedString(\"hello_world\", bundle: frenchBundle, comment: \"\"))\n}\n"
  },
  {
    "path": "Fixtures/Resources/Moved/Package.swift",
    "content": "// swift-tools-version:5.3\nimport PackageDescription\n\nlet package = Package(\n    name: \"Resources\",\n    targets: [\n        .target(\n            name: \"SwiftyResource\",\n            resources: [\n                .copy(\"foo.txt\"),\n            ]\n        ),\n\n        .target(\n            name: \"SeaResource\",\n            resources: [\n                .copy(\"foo.txt\"),\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Resources/Moved/Sources/SeaResource/foo.txt",
    "content": "foo\n"
  },
  {
    "path": "Fixtures/Resources/Moved/Sources/SeaResource/main.m",
    "content": "#import <Foundation/Foundation.h>\n\nint main(int argc, const char * argv[]) {\n    @autoreleasepool {\n        NSBundle *bundle = SWIFTPM_MODULE_BUNDLE;\n        NSString *foo = [bundle pathForResource:@\"foo\" ofType:@\"txt\"];\n        NSData *data = [NSFileManager.defaultManager contentsAtPath:foo];\n        NSString *contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];\n        printf(\"%s\", contents.UTF8String);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Fixtures/Resources/Moved/Sources/SwiftyResource/foo.txt",
    "content": "foo\n"
  },
  {
    "path": "Fixtures/Resources/Moved/Sources/SwiftyResource/main.swift",
    "content": "import Foundation\n\nlet bundle = Bundle.module\n\nlet foo = bundle.path(forResource: \"foo\", ofType: \"txt\")!\nlet contents = FileManager.default.contents(atPath: foo)!\nprint(String(data: contents, encoding: .utf8)!, terminator: \"\")\n"
  },
  {
    "path": "Fixtures/Resources/ResourceRules/Package.swift",
    "content": "// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ResourceRules\",\n    targets: [\n        .executableTarget(name: \"ResourceRules\", resources: [\n\t\t.copy(\"CopiedAssets.xcassets\"),\n\t\t.process(\"ProcessedAssets.xcassets\")\n\t]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Resources/ResourceRules/Sources/ResourceRules/CopiedAssets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Fixtures/Resources/ResourceRules/Sources/ResourceRules/CopiedAssets.xcassets/pixel.imageset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"filename\" : \"pixel.png\",\n      \"idiom\" : \"universal\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"universal\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"universal\",\n      \"scale\" : \"3x\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Fixtures/Resources/ResourceRules/Sources/ResourceRules/ProcessedAssets.xcassets/Contents.json",
    "content": "{\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Fixtures/Resources/ResourceRules/Sources/ResourceRules/ProcessedAssets.xcassets/processedpixel.imageset/Contents.json",
    "content": "{\n  \"images\" : [\n    {\n      \"filename\" : \"processedpixel.png\",\n      \"idiom\" : \"universal\",\n      \"scale\" : \"1x\"\n    },\n    {\n      \"idiom\" : \"universal\",\n      \"scale\" : \"2x\"\n    },\n    {\n      \"idiom\" : \"universal\",\n      \"scale\" : \"3x\"\n    }\n  ],\n  \"info\" : {\n    \"author\" : \"xcode\",\n    \"version\" : 1\n  }\n}\n"
  },
  {
    "path": "Fixtures/Resources/ResourceRules/Sources/ResourceRules/main.swift",
    "content": "import Foundation\nimport AppKit\n\n@main\nstruct Entry {\n    public static func main() {\n        guard Bundle.module.url(forResource: \"CopiedAssets\", withExtension: \"xcassets\") != nil else {\n            print(\"Failed to lookup unprocessed asset catalog\")\n            return\n        }\n        guard Bundle.module.image(forResource: \"processedpixel\") != nil else {\n            print(\"Failed to lookup processed asset from catalog\")\n            return\n        }\n        print(\"succeeded\")\n    }\n}\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Package.swift",
    "content": "// swift-tools-version:5.3\nimport PackageDescription\n\nlet package = Package(\n    name: \"Resources\",\n    targets: [\n        .target(\n            name: \"SwiftyResource\",\n            resources: [\n                .copy(\"foo.txt\"),\n            ]\n        ),\n\n        .target(\n            name: \"SeaResource\",\n            resources: [\n                .copy(\"foo.txt\"),\n            ]\n        ),\n\n        .target(\n            name: \"ClangResource\",\n            resources: [\n                .copy(\"foo.txt\"),\n            ]\n        ),\n\n        .testTarget(\n            name: \"ClangResourceTests\",\n            dependencies: [\"ClangResource\"]\n        ),\n\n        .target(\n            name: \"CPPResource\",\n            resources: [\n                .copy(\"foo.txt\"),\n            ]\n        ),\n\n        .target(\n            name: \"MixedClangResource\",\n            resources: [\n                .copy(\"foo.txt\"),\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/CPPResource/foo.txt",
    "content": "foo\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/CPPResource/main.mm",
    "content": "#import <Foundation/Foundation.h>\n\nint main(int argc, const char * argv[]) {\n    @autoreleasepool {\n        NSBundle *bundle = SWIFTPM_MODULE_BUNDLE;\n        NSString *foo = [bundle pathForResource:@\"foo\" ofType:@\"txt\"];\n        NSData *data = [NSFileManager.defaultManager contentsAtPath:foo];\n        NSString *contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];\n        printf(\"%s\", contents.UTF8String);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/ClangResource/Package.m",
    "content": "#import <Foundation/Foundation.h>\n\n#import \"Package.h\"\n\n@implementation Package\n\n+ (NSBundle *)resourceBundle {\n    return SWIFTPM_MODULE_BUNDLE;\n}\n\n@end\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/ClangResource/foo.txt",
    "content": "\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/ClangResource/include/Package.h",
    "content": "#import <Foundation/Foundation.h>\n\n@interface Package : NSObject\n\n+ (NSBundle *)resourceBundle;\n\n@end\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/MixedClangResource/Foo.m",
    "content": "#import <Foundation/Foundation.h>\n\n#import \"Foo.h\"\n\n@implementation Foo\n@end\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/MixedClangResource/bar.c",
    "content": "#include \"bar.h\"\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/MixedClangResource/bar.h",
    "content": "#ifndef foo_h\n#define foo_h\n\n#include <stdio.h>\n\n#endif /* foo_h */\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/MixedClangResource/baz.S",
    "content": ""
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/MixedClangResource/foo.txt",
    "content": ""
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/MixedClangResource/include/Foo.h",
    "content": "#import <Foundation/Foundation.h>\n\n@interface Foo : NSObject\n@end\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/MixedClangResource/qux.cpp",
    "content": ""
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/SeaResource/foo.txt",
    "content": "foo\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/SeaResource/main.m",
    "content": "#import <Foundation/Foundation.h>\n\nint main(int argc, const char * argv[]) {\n    @autoreleasepool {\n        NSBundle *bundle = SWIFTPM_MODULE_BUNDLE;\n        NSString *foo = [bundle pathForResource:@\"foo\" ofType:@\"txt\"];\n        NSData *data = [NSFileManager.defaultManager contentsAtPath:foo];\n        NSString *contents = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];\n        printf(\"%s\", contents.UTF8String);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/SwiftyResource/foo.txt",
    "content": "foo\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Sources/SwiftyResource/main.swift",
    "content": "import Foundation\n\nlet bundle = Bundle.module\n\nlet foo = bundle.path(forResource: \"foo\", ofType: \"txt\")!\nlet contents = FileManager.default.contents(atPath: foo)!\nprint(String(data: contents, encoding: .utf8)!, terminator: \"\")\n"
  },
  {
    "path": "Fixtures/Resources/Simple/Tests/ClangResourceTests/ClangResourceTests.m",
    "content": "#import <XCTest/XCTest.h>\n\n@import ClangResource;\n\n@interface ClangResourceTests : XCTestCase\n@end\n\n@implementation ClangResourceTests\n\n- (void)testResourceBundleIsNonNil {\n    XCTAssertNotNil([Package resourceBundle]);\n}\n\n@end\n"
  },
  {
    "path": "Fixtures/Signing/Certificates/Test_ec_key.pem",
    "content": "-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIGfOkQcQq6oTC06KkGMVBAr2MiYFRaLo4/wKdNBpIjhnoAoGCCqGSM49\nAwEHoUQDQgAE6SjFVQRtU/+ywvxslaVsl+iZf65YgkQShuxsbAbNJBTVkEkMGyNL\n8nbaj6B4Jskjo1loNPLirNE7mKeTLYbrcw==\n-----END EC PRIVATE KEY-----\n"
  },
  {
    "path": "Fixtures/Signing/Certificates/Test_rsa_key.pem",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEA13XgJ9lIhR2LefNxQdo3tVrbXEZ3o4T8+MgteVJVohbPMypf\nyGgGlJJ/r7+hhL/klsPDyR4SAtgLZUGFVt3WzGMolGyV11VUTTFHMWZ10tcgrUmR\n5wg2n5E59FsJf3y3WTs5CpD2tM8igWyAUOyS/MWvhgnMtvBG8I4Mg9xyyWi/GW3g\nPLXfnyULW/v2Zg+yG9j+/Bbpx+AP8TCvWoiPyiLEZ/DKZK2kC+8mkwOtHYDMkBO5\n2nIrxopB42VUWYBfAzHm0M2XlEuc26PVojqno2ht5WU486uJXzWILvW3zFdlNDF/\nSLeqQy1mNLRt5/An6la7e3sjOcuI1W2Qe7dkrwIDAQABAoIBAES+eUx9iSPfr1az\nk5k9NLUKTh785MMpdUUzKT8iQ+w5dtaOWI0qk57ntxGuBKzERPzNbTRIAdsib1BZ\nPV/f297ObG4ezxgrQ4B1jo92b3Vb6jMf3AtolXUH8wPB4B/q/Nzdhm+WnQBHbmz4\n31/ye1tm/3+2tLhRpXCvAdM4jO8xhJlH+Pxg20fliAuiJ+ggSL56CyBR4kg80KtA\nomeGB1DOVFd23aDO/79Mii/2tf6EpmVFB/4zBkPHOH3zucwt8XUttwBeOcGdIbP+\nCiU9VdZmG0XOJfC3apAXf9YwU3WVbmbvUWSwt6iHGZD4AuKY2R0ECTZnYS8ThDhd\nZwPXzCECgYEA6xe9MpBCIVRK51Hb083mDg16UjRvPJA4T8w9xFg4UtAwe/u3CC67\n4fAOSe0P3NtsXhcQFby7PEJwoeo2Hn6hUifxVMsKWmHb+FCg+CG/oBSwRKCa5BwG\nWpJ0jEt6KHZf0u+b/N1aOjVi/9tMrsHXFV3s2Gm9LQqA8u8izshDqakCgYEA6p8t\nKVK2mA+JjvSGyR6WfpVZ1OIi6CEEUhRU3aNHRB2zPf6J3PQLjz+Ad50BCVHXQSy/\naG3LpR44eUu5Q9AmTwDr8eiC8AT6uyE19zJHbK//E40Bn6khQvtymwByjav/5ZB+\nZAhE7E31eCZO8bqufSlnMNTD0Z8oqB5YR8uDApcCgYAkPcGd5N089Bij9luUGD6p\n1ewQdiLbzEPSEWNIPG1aXtvKkTBTI5k1KGObg98ZJf5btuR05WZb0MY6P7feFZla\n5+ttLevHqSRW8F8QQWugCvBtc/DMz4EvPzqWUiBf0nfNNcDvR1RcetRrKux0WE+G\n7LbRWeOe6OqeCL1t8TN1GQKBgHPaH6m8/w689VbSpc+fu/5Lby0wcL4gt4p0IafD\nnUgkRkLBcn/ZPfABEkV+EGnysJCtMOK2/IzPDGHQo2251YDDWr576lPskYZfks86\nU4x2p0SXJwsYr6Tslp21LduI5/YKUG7Cqo3ovOIUQH0ailihXiP9m6fhqGjDeyIQ\neuOHAoGAfDpntw1HRuk812au430Stl5eaTsH+w1msLLKZOukr6qWc2xFeC3fYPWQ\nBBkyzM3p6Se9FsfHY6LMxrEkz9fSdeVOeHenyUCTMqhqrc6o9f79zIlocsMzVGsK\nXKcULjpf67Igyx12eh3rqAEKwm6PGhbv9pK5/NpuzsP1atArMRg=\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyMigration/Package.swift",
    "content": "// swift-tools-version:5.8\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExistentialAnyMigration\",\n    targets: [\n        .target(name: \"Diagnostics\", path: \"Sources\", exclude: [\"Fixed\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyMigration/Sources/Fixed/Test.swift",
    "content": "protocol P {\n}\nprotocol Q {\n}\n\nfunc test1(_: any P) {\n}\n\nfunc test2(_: (any P).Protocol) {\n}\n\nfunc test3() {\n    let _: [(any P)?] = []\n}\n\nfunc test4() {\n    var x = 42\n}\n\nfunc test5(_: any P & Q) {\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyMigration/Sources/Test.swift",
    "content": "protocol P {\n}\nprotocol Q {\n}\n\nfunc test1(_: P) {\n}\n\nfunc test2(_: P.Protocol) {\n}\n\nfunc test3() {\n    let _: [P?] = []\n}\n\nfunc test4() {\n    var x = 42\n}\n\nfunc test5(_: P & Q) {\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithCommonPluginDependencyMigration/Package.swift",
    "content": "// swift-tools-version:5.8\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExistentialAnyMigration\",\n    platforms: [\n        .macOS(.v10_15)\n    ],\n    targets: [\n        .target(name: \"Library\", dependencies: [\"CommonLibrary\"], plugins: [.plugin(name: \"Plugin\")]),\n        .plugin(name: \"Plugin\", capability: .buildTool, dependencies: [\"Tool\"]),\n        .executableTarget(name: \"Tool\", dependencies: [\"CommonLibrary\"]),\n        .target(name: \"CommonLibrary\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithCommonPluginDependencyMigration/Plugins/Plugin/Plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main struct Plugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        let tool = try context.tool(named: \"Tool\")\n        let output = context.pluginWorkDirectory.appending([\"generated.swift\"])\n        return [\n            .buildCommand(\n                displayName: \"Plugin\",\n                executable: tool.path,\n                arguments: [output],\n                inputFiles: [],\n                outputFiles: [output])\n        ]\n    }\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithCommonPluginDependencyMigration/Sources/CommonLibrary/Common.swift",
    "content": "public func common() {}\n\n\nprotocol P {}\n\nfunc needsMigration(_ p: P) {}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithCommonPluginDependencyMigration/Sources/Library/Test.swift",
    "content": "import CommonLibrary\n\nfunc bar() {\n    generatedFunction()\n    common()\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithCommonPluginDependencyMigration/Sources/Tool/tool.swift",
    "content": "import Foundation\nimport CommonLibrary\n\n@main struct Entry {\n    public static func main() async throws {\n        common()\n        let outputPath = CommandLine.arguments[1]\n        let contents = \"\"\"\n        func generatedFunction() {}\n        \"\"\"\n        FileManager.default.createFile(atPath: outputPath, contents: contents.data(using: .utf8))\n    }\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithPluginMigration/Package.swift",
    "content": "// swift-tools-version:5.8\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExistentialAnyMigration\",\n    platforms: [\n        .macOS(.v10_15)\n    ],\n    targets: [\n        .target(name: \"Library\", plugins: [.plugin(name: \"Plugin\")]),\n        .plugin(name: \"Plugin\", capability: .buildTool, dependencies: [\"Tool\"]),\n        .executableTarget(name: \"Tool\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithPluginMigration/Plugins/Plugin/Plugin.swift",
    "content": "import PackagePlugin\nimport Foundation\n\n@main struct Plugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n        let tool = try context.tool(named: \"Tool\")\n        let output = context.pluginWorkDirectory.appending([\"generated.swift\"])\n        return [\n            .buildCommand(\n                displayName: \"Plugin\",\n                executable: tool.path,\n                arguments: [output],\n                inputFiles: [],\n                outputFiles: [output])\n        ]\n    }\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithPluginMigration/Sources/Library/Test.swift",
    "content": "protocol P {\n}\n\nfunc test1(_: P) {\n}\n\nfunc test2(_: P.Protocol) {\n}\n\nfunc test3() {\n    let _: [P?] = []\n}\n\nfunc test4() {\n    var x = 42\n}\n\nfunc bar() {\n    generatedFunction()\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/ExistentialAnyWithPluginMigration/Sources/Tool/tool.swift",
    "content": "import Foundation\n\n@main struct Entry {\n    public static func main() async throws {\n        let outputPath = CommandLine.arguments[1]\n        let contents = \"\"\"\n        func generatedFunction() {}\n        func dontmodifyme(_: P) {}\n        \"\"\"\n        FileManager.default.createFile(atPath: outputPath, contents: contents.data(using: .utf8))\n    }\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/InferIsolatedConformancesMigration/Package.swift",
    "content": "// swift-tools-version:6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"InferIsolatedConformancesMigration\",\n    targets: [\n        .target(name: \"Diagnostics\", path: \"Sources\", exclude: [\"Fixed\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/InferIsolatedConformancesMigration/Sources/Fixed/Test.swift",
    "content": "@MainActor\nclass C: nonisolated Equatable {\n  let name = \"Hello\"\n\n  nonisolated static func ==(lhs: C, rhs: C) -> Bool {\n    lhs.name == rhs.name\n  }\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/InferIsolatedConformancesMigration/Sources/Fixed/Test2.swift",
    "content": "protocol P {}\nprotocol Q {}\n\n@MainActor\nstruct S: nonisolated P & Q {}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/InferIsolatedConformancesMigration/Sources/Test.swift",
    "content": "@MainActor\nclass C: Equatable {\n  let name = \"Hello\"\n\n  nonisolated static func ==(lhs: C, rhs: C) -> Bool {\n    lhs.name == rhs.name\n  }\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/InferIsolatedConformancesMigration/Sources/Test2.swift",
    "content": "protocol P {}\nprotocol Q {}\n\n@MainActor\nstruct S: P & Q {}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/StrictMemorySafetyMigration/Package.swift",
    "content": "// swift-tools-version:6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"StrictMemorySafetyMigration\",\n    targets: [\n        .target(name: \"Diagnostics\", path: \"Sources\", exclude: [\"Fixed\"]),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/StrictMemorySafetyMigration/Sources/Fixed/Test.swift",
    "content": "@unsafe func f() { }\n\nfunc g() {\n  unsafe f()\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/StrictMemorySafetyMigration/Sources/Test.swift",
    "content": "@unsafe func f() { }\n\nfunc g() {\n  f()\n}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/UpdateManifest/Package.swift",
    "content": "// swift-tools-version:5.8\n\nimport PackageDescription\n\nvar swiftSettings: [SwiftSetting] = []\n\nlet package = Package(\n    name: \"WithErrors\",\n    targets: [\n        .target(\n            name: \"CannotFindSettings\",\n            swiftSettings: swiftSettings\n        ),\n        .target(name: \"A\"),\n        .target(name: \"B\"),\n    ]\n)\n\npackage.targets.append(\n    .target(\n        name: \"CannotFindTarget\",\n        swiftSettings: swiftSettings\n    ),\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/UpdateManifest/Package.updated.targets-A-B.swift",
    "content": "// swift-tools-version:5.8\n\nimport PackageDescription\n\nvar swiftSettings: [SwiftSetting] = []\n\nlet package = Package(\n    name: \"WithErrors\",\n    targets: [\n        .target(\n            name: \"CannotFindSettings\",\n            swiftSettings: swiftSettings\n        ),\n        .target(name: \"A\",swiftSettings: [\n    .enableUpcomingFeature(\"ExistentialAny\"),\n    .enableUpcomingFeature(\"InferIsolatedConformances\"),]),\n        .target(name: \"B\",swiftSettings: [\n    .enableUpcomingFeature(\"ExistentialAny\"),\n    .enableUpcomingFeature(\"InferIsolatedConformances\"),]),\n    ]\n)\n\npackage.targets.append(\n    .target(\n        name: \"CannotFindTarget\",\n        swiftSettings: swiftSettings\n    ),\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/UpdateManifest/Package.updated.targets-A.swift",
    "content": "// swift-tools-version:5.8\n\nimport PackageDescription\n\nvar swiftSettings: [SwiftSetting] = []\n\nlet package = Package(\n    name: \"WithErrors\",\n    targets: [\n        .target(\n            name: \"CannotFindSettings\",\n            swiftSettings: swiftSettings\n        ),\n        .target(name: \"A\",swiftSettings: [\n    .enableUpcomingFeature(\"ExistentialAny\"),\n    .enableUpcomingFeature(\"InferIsolatedConformances\"),]),\n        .target(name: \"B\"),\n    ]\n)\n\npackage.targets.append(\n    .target(\n        name: \"CannotFindTarget\",\n        swiftSettings: swiftSettings\n    ),\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/UpdateManifest/Package.updated.targets-all.swift",
    "content": "// swift-tools-version:5.8\n\nimport PackageDescription\n\nvar swiftSettings: [SwiftSetting] = []\n\nlet package = Package(\n    name: \"WithErrors\",\n    targets: [\n        .target(\n            name: \"CannotFindSettings\",\n            swiftSettings: swiftSettings\n        ),\n        .target(name: \"A\",swiftSettings: [\n    .enableUpcomingFeature(\"ExistentialAny\"),\n    .enableUpcomingFeature(\"InferIsolatedConformances\"),]),\n        .target(name: \"B\",swiftSettings: [\n    .enableUpcomingFeature(\"ExistentialAny\"),\n    .enableUpcomingFeature(\"InferIsolatedConformances\"),]),\n    ]\n)\n\npackage.targets.append(\n    .target(\n        name: \"CannotFindTarget\",\n        swiftSettings: swiftSettings\n    ),\n)\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/UpdateManifest/Sources/A/File.swift",
    "content": "public func foo() {}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/UpdateManifest/Sources/B/File.swift",
    "content": "public func foo() {}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/UpdateManifest/Sources/CannotFindSettings/File.swift",
    "content": "public func foo() {}\n"
  },
  {
    "path": "Fixtures/SwiftMigrate/UpdateManifest/Sources/CannotFindTarget/File.swift",
    "content": "public func foo() {}\n"
  },
  {
    "path": "Fixtures/SwiftSDKs/Package.swift",
    "content": "// This empty file tells test fixture logic to copy this directory's content to the test case temp directory.\n"
  },
  {
    "path": "Fixtures/Traits/DisablingEmptyDefaultsExample/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"DisablingEmptyDefaultsExample\",\n    dependencies: [\n        .package(\n            path: \"../Package11\",\n            traits: []\n        ),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"DisablingEmptyDefaultsExample\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/DisablingEmptyDefaultsExample/Sources/DisablingEmptyDefaultsExample/Example.swift",
    "content": "@main\nstruct Example {\n    static func main() {\n\n    }\n}"
  },
  {
    "path": "Fixtures/Traits/Example/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"TraitsExample\",\n    traits: [\n        .default(\n            enabledTraits: [\n                \"Package1\",\n                \"Package2\",\n                \"Package3\",\n                \"Package4\",\n                \"BuildCondition1\",\n            ]\n        ),\n        \"Package1\",\n        \"Package2\",\n        \"Package3\",\n        \"Package4\",\n        \"Package5\",\n        \"Package7\",\n        \"Package9\",\n        \"Package10\",\n        \"BuildCondition1\",\n        \"BuildCondition2\",\n        \"BuildCondition3\",\n        \"ExtraTrait\",\n    ],\n    dependencies: [\n        .package(\n            path: \"../Package1\",\n            traits: [\"Package1Trait1\"]\n        ),\n        .package(\n            path: \"../Package2\",\n            traits: [\"Package2Trait1\"]\n        ),\n        .package(\n            path: \"../Package3\"\n        ),\n        .package(\n            path: \"../Package4\",\n            traits: []\n        ),\n        .package(\n            path: \"../Package5\",\n            traits: [\"Package5Trait1\"]\n        ),\n        .package(\n            path: \"../Package7\"\n        ),\n        .package(\n            path: \"../Package9\"\n        ),\n        .package(\n            path: \"../Package10\",\n            traits: [\"Package10Trait2\"]\n        ),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"Example\",\n            dependencies: [\n                .product(\n                    name: \"Package1Library1\",\n                    package: \"Package1\",\n                    condition: .when(traits: [\"Package1\"])\n                ),\n                .product(\n                    name: \"Package2Library1\",\n                    package: \"Package2\",\n                    condition: .when(traits: [\"Package2\"])\n                ),\n                .product(\n                    name: \"Package3Library1\",\n                    package: \"Package3\",\n                    condition: .when(traits: [\"Package3\"])\n                ),\n                .product(\n                    name: \"Package4Library1\",\n                    package: \"Package4\",\n                    condition: .when(traits: [\"Package4\"])\n                ),\n                .product(\n                    name: \"Package5Library1\",\n                    package: \"Package5\",\n                    condition: .when(traits: [\"Package5\"])\n                ),\n                .product(\n                    name: \"Package7Library1\",\n                    package: \"Package7\",\n                    condition: .when(traits: [\"Package7\"])\n                ),\n                .product(\n                    name: \"Package9Library1\",\n                    package: \"Package9\",\n                    condition: .when(traits: [\"Package9\"])\n                ),\n                .product(\n                    name: \"Package10Library1\",\n                    package: \"Package10\",\n                    condition: .when(traits: [\"Package10\"])\n                ),\n                .product(\n                    name: \"Package10Library2\",\n                    package: \"Package10\",\n                    condition: .when(traits: [\"Package10\", \"ExtraTrait\"])\n                )\n            ],\n            swiftSettings: [\n                .define(\"DEFINE1\", .when(traits: [\"BuildCondition1\"])),\n                .define(\"DEFINE2\", .when(traits: [\"BuildCondition2\"])),\n                .define(\"DEFINE3\", .when(traits: [\"BuildCondition3\"])),\n            ]\n        ),\n        .testTarget(\n            name: \"ExampleTests\",\n            dependencies: [\n                .product(\n                    name: \"Package1Library1\",\n                    package: \"Package1\",\n                    condition: .when(traits: [\"Package1\"])\n                ),\n                .product(\n                    name: \"Package2Library1\",\n                    package: \"Package2\",\n                    condition: .when(traits: [\"Package2\"])\n                ),\n                .product(\n                    name: \"Package3Library1\",\n                    package: \"Package3\",\n                    condition: .when(traits: [\"Package3\"])\n                ),\n                .product(\n                    name: \"Package4Library1\",\n                    package: \"Package4\",\n                    condition: .when(traits: [\"Package4\"])\n                ),\n                .product(\n                    name: \"Package5Library1\",\n                    package: \"Package5\",\n                    condition: .when(traits: [\"Package5\"])\n                ),\n                .product(\n                    name: \"Package7Library1\",\n                    package: \"Package7\",\n                    condition: .when(traits: [\"Package7\"])\n                ),\n                .product(\n                    name: \"Package9Library1\",\n                    package: \"Package9\",\n                    condition: .when(traits: [\"Package9\"])\n                ),\n                .product(\n                    name: \"Package10Library1\",\n                    package: \"Package10\",\n                    condition: .when(traits: [\"Package10\"])\n                ),\n            ],\n            swiftSettings: [\n                .define(\"DEFINE1\", .when(traits: [\"BuildCondition1\"])),\n                .define(\"DEFINE2\", .when(traits: [\"BuildCondition2\"])),\n                .define(\"DEFINE3\", .when(traits: [\"BuildCondition3\"])),\n            ]\n        )\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Example/Sources/Example/Example.swift",
    "content": "#if Package1\nimport Package1Library1\n#endif\n#if Package2\nimport Package2Library1\n#endif\n#if Package3\nimport Package3Library1\n#endif\n#if Package4\nimport Package4Library1\n#endif\n#if Package5\nimport Package5Library1\n#endif\n#if Package7\nimport Package7Library1\n#endif\n#if Package9\nimport Package9Library1\n#endif\n#if Package10\nimport Package10Library1\nimport Package10Library2\n#endif\n#if ExtraTrait\nimport Package10Library2\n#endif\n\n@main\nstruct Example {\n    static func main() {\n        #if Package1\n        Package1Library1.hello()\n        #endif\n        #if Package2\n        Package2Library1.hello()\n        #endif\n        #if Package3\n        Package3Library1.hello()\n        #endif\n        #if Package4\n        Package4Library1.hello()\n        #endif\n        #if Package5\n        Package5Library1.hello()\n        #endif\n        #if Package7\n        Package7Library1.hello()\n        #endif\n        #if Package9\n        Package9Library1.hello()\n        #endif\n        #if Package10\n        Package10Library1.hello()\n        Package10Library2.hello()\n        #endif\n        #if ExtraTrait\n        Package10Library2.hello()\n        #endif\n        #if DEFINE1\n        print(\"DEFINE1 enabled\")\n        #else\n        print(\"DEFINE1 disabled\")\n        #endif\n        #if DEFINE2\n        print(\"DEFINE2 enabled\")\n        #else\n        print(\"DEFINE2 disabled\")\n        #endif\n        #if DEFINE3\n        print(\"DEFINE3 enabled\")\n        #else\n        print(\"DEFINE3 disabled\")\n        #endif\n    }\n}\n"
  },
  {
    "path": "Fixtures/Traits/Example/Tests/ExampleTests/Tests.swift",
    "content": "#if Package1\nimport Package1Library1\n#endif\n#if Package2\nimport Package2Library1\n#endif\n#if Package3\nimport Package3Library1\n#endif\n#if Package4\nimport Package4Library1\n#endif\n#if Package5\nimport Package5Library1\n#endif\n#if Package7\nimport Package7Library1\n#endif\n#if Package9\nimport Package9Library1\n#endif\n#if Package10\nimport Package10Library1\n#endif\n\nimport XCTest\n\nfinal class Tests: XCTestCase {\n    func testTraits() {\n        #if Package1\n        Package1Library1.hello()\n        #endif\n        #if Package2\n        Package2Library1.hello()\n        #endif\n        #if Package3\n        Package3Library1.hello()\n        #endif\n        #if Package4\n        Package4Library1.hello()\n        #endif\n        #if Package5\n        Package5Library1.hello()\n        #endif\n        #if Package7\n        Package7Library1.hello()\n        #endif\n        #if Package9\n        Package9Library1.hello()\n        #endif\n        #if Package10\n        Package10Library1.hello()\n        #endif\n        #if DEFINE1\n        print(\"DEFINE1 enabled\")\n        #else\n        print(\"DEFINE1 disabled\")\n        #endif\n        #if DEFINE2\n        print(\"DEFINE2 enabled\")\n        #else\n        print(\"DEFINE2 disabled\")\n        #endif\n        #if DEFINE3\n        print(\"DEFINE3 enabled\")\n        #else\n        print(\"DEFINE3 disabled\")\n        #endif\n    }\n}"
  },
  {
    "path": "Fixtures/Traits/Package1/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package1\",\n    products: [\n        .library(\n            name: \"Package1Library1\",\n            targets: [\"Package1Library1\"]\n        ),\n    ],\n    traits: [\n        \"Package1Trait1\"\n    ],\n    targets: [\n        .target(\n            name: \"Package1Library1\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package1/Sources/Package1Library1/Library.swift",
    "content": "public func hello() {\n    #if Package1Trait1\n    print(\"Package1Library1 trait1 enabled\")\n    #else\n    print(\"Package1Library1 trait1 disabled\")\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Traits/Package10/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package10\",\n    products: [\n        .library(\n            name: \"Package10Library1\",\n            targets: [\"Package10Library1\"]\n        ),\n        .library(\n            name: \"Package10Library2\",\n            targets: [\"Package10Library2\"]\n        ),\n    ],\n    traits: [\n        \"Package10Trait1\",\n        \"Package10Trait2\"\n    ],\n    targets: [\n        .target(\n            name: \"Package10Library1\"\n        ),\n        .target(\n            name: \"Package10Library2\"\n        ),\n        .plugin(\n            name: \"SymbolGraphExtract\",\n            capability: .command(\n                intent: .custom(verb: \"extract\", description: \"\")\n            )\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package10/Plugins/SymbolGraphExtract/Plugin.swift",
    "content": "import PackagePlugin\n\n@main struct SymbolGraphExtractPlugin: CommandPlugin {\n    func performCommand(\n        context: PluginContext,\n        arguments: [String]\n    ) throws {\n        let result = try self.packageManager.getSymbolGraph(for: context.package.targets.first!, options: .init())\n        print(result.directoryPath)\n    }\n}"
  },
  {
    "path": "Fixtures/Traits/Package10/Sources/Package10Library1/Library.swift",
    "content": "public func hello() {\n    #if Package10Trait1\n    print(\"Package10Library1 trait1 enabled\")\n    #else\n    print(\"Package10Library1 trait1 disabled\")\n    #endif\n    #if Package10Trait2\n    print(\"Package10Library1 trait2 enabled\")\n    #else\n    print(\"Package10Library1 trait2 disabled\")\n    #endif\n}\n\n#if Package10Trait1\npublic struct TypeGatedByPackage10Trait1 {}\n#endif\n\n#if Package10Trait2\npublic struct TypeGatedByPackage10Trait2 {}\n#endif"
  },
  {
    "path": "Fixtures/Traits/Package10/Sources/Package10Library2/Library.swift",
    "content": "public func hello() {\n    print(\"Package10Library2 has been included.\")\n}"
  },
  {
    "path": "Fixtures/Traits/Package11/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package11\",\n    products: [\n        .library(\n            name: \"Package11Library1\",\n            targets: [\"Package11Library1\"]\n        ),\n    ],\n    targets: [\n        .target(\n            name: \"Package11Library1\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package11/Sources/Package11Library1/Library.swift",
    "content": "public func hello() {\n    print(\"Package11Library1\")\n}"
  },
  {
    "path": "Fixtures/Traits/Package2/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package2\",\n    products: [\n        .library(\n            name: \"Package2Library1\",\n            targets: [\"Package2Library1\"]\n        ),\n    ],\n    traits: [\n        Trait(name: \"Package2Trait1\", enabledTraits: [\"Package2Trait2\"]),\n        \"Package2Trait2\",\n    ],\n    targets: [\n        .target(\n            name: \"Package2Library1\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package2/Sources/Package2Library1/Library.swift",
    "content": "public func hello() {\n    #if Package2Trait2\n    print(\"Package2Library1 trait2 enabled\")\n    #else\n    print(\"Package2Library1 trait2 disabled\")\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Traits/Package3/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package3\",\n    products: [\n        .library(\n            name: \"Package3Library1\",\n            targets: [\"Package3Library1\"]\n        ),\n    ],\n    traits: [\n        .default(enabledTraits: [\"Package3Trait3\"]),\n        .trait(name: \"Package3Trait1\", enabledTraits: [\"Package3Trait2\"]),\n        .trait(name: \"Package3Trait2\", enabledTraits: [\"Package3Trait3\"]),\n        \"Package3Trait3\",\n    ],\n    targets: [\n        .target(\n            name: \"Package3Library1\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package3/Sources/Package3Library1/Library.swift",
    "content": "public func hello() {\n    #if Package3Trait3\n    print(\"Package3Library1 trait3 enabled\")\n    #else\n    print(\"Package3Library1 trait3 disabled\")\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Traits/Package4/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package4\",\n    products: [\n        .library(\n            name: \"Package4Library1\",\n            targets: [\"Package4Library1\"]\n        ),\n    ],\n    traits: [\n        .default(enabledTraits: [\"Package4Trait1\"]),\n        \"Package4Trait1\",\n    ],\n    targets: [\n        .target(\n            name: \"Package4Library1\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package4/Sources/Package4Library1/Library.swift",
    "content": "public func hello() {\n    #if Package4Trait1\n    print(\"Package4Library1 trait1 enabled\")\n    #else\n    print(\"Package4Library1 trait1 disabled\")\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Traits/Package5/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package5\",\n    products: [\n        .library(\n            name: \"Package5Library1\",\n            targets: [\"Package5Library1\"]\n        ),\n    ],\n    traits: [\n        \"Package5Trait1\"\n    ],\n    dependencies: [\n        .package(\n            path: \"../Package6\",\n            traits: [\n                Package.Dependency.Trait(name: \"Package6Trait1\", condition: .when(traits: [\"Package5Trait1\"]))\n            ]\n        )\n    ],\n    targets: [\n        .target(\n            name: \"Package5Library1\",\n            dependencies: [\n                .product(\n                    name: \"Package6Library1\",\n                    package: \"Package6\"\n                )\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package5/Sources/Package5Library1/Library.swift",
    "content": "#if Package5Trait1\nimport Package6Library1\n#endif\n\npublic func hello() {\n    #if Package5Trait1\n    print(\"Package5Library1 trait1 enabled\")\n    Package6Library1.hello()\n    #else\n    print(\"Package5Library1 trait1 disabled\")\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Traits/Package6/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package6\",\n    products: [\n        .library(\n            name: \"Package6Library1\",\n            targets: [\"Package6Library1\"]\n        ),\n    ],\n    traits: [\n        \"Package6Trait1\"\n    ],\n    targets: [\n        .target(\n            name: \"Package6Library1\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package6/Sources/Package6Library1/Library.swift",
    "content": "public func hello() {\n    #if Package6Trait1\n    print(\"Package6Library1 trait1 enabled\")\n    #else\n    print(\"Package6Library1 trait1 disabled\")\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Traits/Package7/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package7\",\n    products: [\n        .library(\n            name: \"Package7Library1\",\n            targets: [\"Package7Library1\"]\n        ),\n    ],\n    traits: [\n        \"Package7Trait1\"\n    ],\n    dependencies: [\n        .package(\n            path: \"../Package8\"\n        )\n    ],\n    targets: [\n        .target(\n            name: \"Package7Library1\",\n            dependencies: [\n                .product(\n                    name: \"Package8Library1\",\n                    package: \"Package8\",\n                    condition: .when(traits: [\"Package7Trait1\"])\n                )\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package7/Sources/Package7Library1/Library.swift",
    "content": "#if Package7Trait1\nimport Package8Library1\n#endif\n\npublic func hello() {\n    #if Package7Trait1\n    print(\"Package7Library1 trait1 enabled\")\n    Package8Library1.hello()\n    #else\n    print(\"Package7Library1 trait1 disabled\")\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Traits/Package8/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package8\",\n    products: [\n        .library(\n            name: \"Package8Library1\",\n            targets: [\"Package8Library1\"]\n        ),\n    ],\n    traits: [\n        \"Package8Trait1\"\n    ],\n    targets: [\n        .target(\n            name: \"Package8Library1\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package8/Sources/Package6Library1/Library.swift",
    "content": "public func hello() {\n    #if Package8Trait1\n    print(\"Package8Library1 trait1 enabled\")\n    #else\n    print(\"Package8Library1 trait1 disabled\")\n    #endif\n}\n"
  },
  {
    "path": "Fixtures/Traits/Package9/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Package9\",\n    products: [\n        .library(\n            name: \"Package9Library1\",\n            targets: [\"Package9Library1\"]\n        ),\n    ],\n    dependencies: [\n        .package(\n            path: \"../Package10\",\n            traits: [\"Package10Trait1\"]\n        )\n    ],\n    targets: [\n        .target(\n            name: \"Package9Library1\",\n            dependencies: [\n                .product(\n                    name: \"Package10Library1\",\n                    package: \"Package10\"\n                )\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/Package9/Sources/Package9Library1/Library.swift",
    "content": "import Package10Library1\n\npublic func hello() {\n    Package10Library1.hello()\n}\n"
  },
  {
    "path": "Fixtures/Traits/PackageConditionalDeps/Package.swift",
    "content": "// swift-tools-version: 6.1\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"PackageConditionalDeps\",\n    products: [\n        .library(\n            name: \"PackageConditionalDeps\",\n            targets: [\"PackageConditionalDeps\"]\n        ),\n    ],\n    traits: [\n        .default(enabledTraits: [\"EnablePackage1Dep\"]),\n        \"EnablePackage1Dep\",\n        \"EnablePackage2Dep\"\n    ],\n    dependencies: [\n        .package(path: \"../Package1\"),\n        .package(path: \"../Package2\"),\n    ],\n    targets: [\n        .target(\n            name: \"PackageConditionalDeps\",\n            dependencies: [ \n                .product(\n                    name: \"Package1Library1\",\n                    package: \"Package1\",\n                    condition: .when(traits: [\"EnablePackage1Dep\"])\n                ),\n                .product(\n                    name: \"Package2Library1\",\n                    package: \"Package2\",\n                    condition: .when(traits: [\"EnablePackage2Dep\"])\n                )\n            ]\n        ),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/Traits/PackageConditionalDeps/Sources/PackageConditionalDeps/PackageConditionalDeps.swift",
    "content": "public func nothingHappens() {\n    // Do nothing.\n}\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableMixed/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableMixed/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExecutableNew\",\n    targets: [\n        .target(name: \"ExecutableSwift\"),\n        .target(name: \"ExecutableC\"),\n        .target(name: \"ExecutableCxx\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableMixed/README.md",
    "content": "# ExecutableMixed\n\nA description of this package.\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableMixed/Sources/ExecutableC/c.c",
    "content": "int main() {\n  return 0;\n}\n\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableMixed/Sources/ExecutableCxx/cxx.cpp",
    "content": "int main() {\n  return 0;\n}\n\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableMixed/Sources/ExecutableSwift/main.swift",
    "content": "print(\"Hello, world!\")\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableNew/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableNew/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExecutableNew\",\n    targets: [\n        .target(name: \"ExecutableNew\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableNew/README.md",
    "content": "# ExecutableNew\n\nA description of this package.\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/ExecutableNew/Sources/ExecutableNew/main.swift",
    "content": "print(\"Hello, world!\")\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/Library/Package.swift",
    "content": "// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"Library\",\n    targets: [\n        .target(name: \"Library\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/ValidLayouts/SingleModule/Library/Sources/Library/Foo.swift",
    "content": "class Foo {\n    var bar: Int = 0\n}\n"
  },
  {
    "path": "Fixtures/XCBuild/ExecutableProducts/Bar/Package.swift",
    "content": "// swift-tools-version:4.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    products: [\n        .executable(name: \"bar\", targets: [\"bar\"]),\n        .executable(name: \"cbar\", targets: [\"cbar\"]),\n        .library(name: \"BarLib\", targets: [\"BarLib\"]),\n    ],\n    targets: [\n        .target(name: \"bar\", dependencies: [\"BarLib\"]),\n        .target(name: \"cbar\"),\n        .target(name: \"BarLib\"),\n    ],\n    swiftLanguageVersions: [.v4_2],\n    cLanguageStandard: .c11,\n    cxxLanguageStandard: .cxx14\n)\n"
  },
  {
    "path": "Fixtures/XCBuild/ExecutableProducts/Bar/Sources/BarLib/BarLib.swift",
    "content": "public struct BarInfo {\n    public static let name: String = \"bar\"\n}"
  },
  {
    "path": "Fixtures/XCBuild/ExecutableProducts/Bar/Sources/bar/main.swift",
    "content": "import BarLib\n\nfunc main() {\n    print(\"Hello from \\(BarInfo.name)\")\n}"
  },
  {
    "path": "Fixtures/XCBuild/ExecutableProducts/Bar/Sources/cbar/main.c",
    "content": "#include <stdio.h>\n\nint main(void) {\n    printf(\"Hello from cbar\");\n}\n"
  },
  {
    "path": "Fixtures/XCBuild/ExecutableProducts/Foo/Package.swift",
    "content": "// swift-tools-version:5.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    dependencies: [\n        .package(path: \"../Bar\")\n    ],\n    targets: [\n        .target(name: \"foo\", dependencies: [\n            \"FooLib\",\n            \"cfoo\",\n            .product(name: \"bar\", package: \"Bar\")\n        ]),\n        .target(name: \"cfoo\"),\n        .target(name: \"FooLib\", dependencies: [\n            .product(name: \"BarLib\", package: \"Bar\"),\n        ]),\n    ],\n    swiftLanguageVersions: [.v4_2, .v5]\n)\n"
  },
  {
    "path": "Fixtures/XCBuild/ExecutableProducts/Foo/Sources/FooLib/FooLib.swift",
    "content": "public struct FooInfo {\n    public static let name: String = \"bar\"\n}"
  },
  {
    "path": "Fixtures/XCBuild/ExecutableProducts/Foo/Sources/cfoo/main.c",
    "content": "#include <stdio.h>\n\nint main(void) {\n    printf(\"Hello from cfoo\");\n}\n"
  },
  {
    "path": "Fixtures/XCBuild/ExecutableProducts/Foo/Sources/foo/main.swift",
    "content": "import FooLib\nimport BarLib\n\nfunc main() {\n    print(\"Hello from \\(FooInfo.name)\")\n    print(\"Hello from \\(BarInfo.name)\")\n}"
  },
  {
    "path": "Fixtures/XCBuild/Libraries/Bar/Package.swift",
    "content": "// swift-tools-version:4.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    products: [\n        .library(name: \"BarLib\", type: .dynamic, targets: [\"BarLib\"]),\n    ],\n    targets: [\n        .target(name: \"BarLib\"),\n    ],\n    swiftLanguageVersions: [.v4_2],\n    cLanguageStandard: .c11,\n    cxxLanguageStandard: .cxx14\n)\n"
  },
  {
    "path": "Fixtures/XCBuild/Libraries/Bar/Sources/BarLib/BarLib.swift",
    "content": "import Foundation\n\n@objcMembers public class BarInfo: NSObject {\n    public static let name = \"Bar\"\n}"
  },
  {
    "path": "Fixtures/XCBuild/Libraries/Foo/Package.swift",
    "content": "// swift-tools-version:5.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    products: [\n        .library(name: \"FooLib\", type: .static, targets: [\"FooLib\"]),\n    ],\n    dependencies: [\n        .package(path: \"../Bar\")\n    ],\n    targets: [\n        .target(name: \"FooLib\", dependencies: [\"CFooLib\"]),\n        .target(name: \"CFooLib\", dependencies: [\n            .product(name: \"BarLib\", package: \"Bar\"),\n        ]),\n    ],\n    swiftLanguageVersions: [.v4_2, .v5]\n)\n"
  },
  {
    "path": "Fixtures/XCBuild/Libraries/Foo/Sources/CFooLib/CFooLib.m",
    "content": "@import Foundation;\n@import BarLib;\n#import \"CFooLib.h\"\n\n@implementation CFooInfo\n\n+ (NSString*)name {\n    return [NSString stringWithFormat:@\"CFoo %@\", [BarInfo name]];\n}\n\n@end\n"
  },
  {
    "path": "Fixtures/XCBuild/Libraries/Foo/Sources/CFooLib/include/CFooLib.h",
    "content": "@import Foundation;\n\n@interface CFooInfo: NSObject\n+ (nonnull NSString*)name;\n@end\n"
  },
  {
    "path": "Fixtures/XCBuild/Libraries/Foo/Sources/FooLib/FooLib.swift",
    "content": "import CFooLib\nimport BarLib\n\npublic struct FooInfo {\n    public static let name = \"Foo \\(BarInfo.name) \\(CFooInfo.name)\"\n}"
  },
  {
    "path": "Fixtures/XCBuild/SystemTargets/Foo/Package.swift",
    "content": "// swift-tools-version:4.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    targets: [\n        .target(name: \"foo\", dependencies: [\"SystemLib\"]),\n        .systemLibrary(name: \"SystemLib\", pkgConfig: \"libsys\"),\n    ]\n)\n"
  },
  {
    "path": "Fixtures/XCBuild/SystemTargets/Foo/Sources/SystemLib/module.modulemap",
    "content": "module SystemLib [system] {\n    header \"../../../Inputs/libsys.h\"\n    export *\n}\n"
  },
  {
    "path": "Fixtures/XCBuild/SystemTargets/Foo/Sources/foo/main.swift",
    "content": "import SystemLib\n\nprint(String(cString: GetSystemLibName()!))\n"
  },
  {
    "path": "Fixtures/XCBuild/SystemTargets/Inputs/libsys.c",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2020 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nconst char* GetSystemLibName() {\n\treturn \"SystemLibrary\";\n}\n"
  },
  {
    "path": "Fixtures/XCBuild/SystemTargets/Inputs/libsys.h",
    "content": "/*\n This source file is part of the Swift.org open source project\n\n Copyright (c) 2020 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n*/\n\nconst char* GetSystemLibName();\n"
  },
  {
    "path": "Fixtures/XCBuild/SystemTargets/Inputs/libsys.pc",
    "content": "Name: SystemLibrary\nURL: http://127.0.0.1/\nDescription: The one and only SystemLibrary\nVersion: 1.0.0\nCflags: -I${pcfiledir}\nLibs: -L${pcfiledir} -lsys\n"
  },
  {
    "path": "Fixtures/XCBuild/TestProducts/Bar/Package.swift",
    "content": "// swift-tools-version:4.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Bar\",\n    products: [\n        .library(name: \"BarLib\", targets: [\"BarLib\"]),\n    ],\n    targets: [\n        .target(name: \"BarLib\"),\n    ],\n    swiftLanguageVersions: [.v4_2],\n    cLanguageStandard: .c11,\n    cxxLanguageStandard: .cxx14\n)\n"
  },
  {
    "path": "Fixtures/XCBuild/TestProducts/Bar/Sources/BarLib/BarLib.m",
    "content": "#import \"BarLib.h\"\n\n@implementation BarInfo\n\n+ (NSString*)name {\n    return @\"Bar\";\n}\n\n@end"
  },
  {
    "path": "Fixtures/XCBuild/TestProducts/Bar/Sources/BarLib/include/BarLib.h",
    "content": "@import Foundation;\n\n@interface BarInfo: NSObject\n+ (nonnull NSString*)name;\n@end"
  },
  {
    "path": "Fixtures/XCBuild/TestProducts/Foo/Package.swift",
    "content": "// swift-tools-version:5.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Foo\",\n    dependencies: [\n        .package(path: \"../Bar\")\n    ],\n    targets: [\n        .target(name: \"FooLib\", dependencies: [\n            .product(name: \"BarLib\", package: \"Bar\"),\n        ]),\n        .testTarget(name: \"FooTests\", dependencies: [\"FooLib\"]),\n        .testTarget(name: \"CFooTests\", dependencies: [\"FooLib\"]),\n    ],\n    swiftLanguageVersions: [.v4_2, .v5]\n)\n"
  },
  {
    "path": "Fixtures/XCBuild/TestProducts/Foo/Sources/FooLib/FooLib.swift",
    "content": "import Foundation\n\n@objcMembers public class FooInfo: NSObject {\n    public static let name = \"Foo\"\n}"
  },
  {
    "path": "Fixtures/XCBuild/TestProducts/Foo/Tests/CFooTests/tests.m",
    "content": "@import XCTest;\n@import Foundation;\n@import FooLib;\n@import BarLib;\n\n@interface CFooTests: XCTestCase\n@end\n@implementation CFooTests\n\n- (void)testFoo {\n    XCTAssert([[FooInfo name] isEqualTo:@\"Foo\"]);\n}\n\n- (void)testBar {\n    XCTAssert([[BarInfo name] isEqualTo:@\"Bar\"]);\n}\n\n@end\n"
  },
  {
    "path": "Fixtures/XCBuild/TestProducts/Foo/Tests/FooTests/FooTests.swift",
    "content": "import XCTest\nimport FooLib\nimport BarLib\n\nfinal class FooTests: XCTestCase {\n    func testFoo() {\n        XCTAssertEqual(FooInfo.name, \"Foo\")\n    }\n\n    func testBar() {\n        XCTAssertEqual(BarInfo.name(), \"Bar\")\n    }\n}"
  },
  {
    "path": "LICENSE.txt",
    "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   \n   \n## Runtime Library Exception to the Apache 2.0 License: ##\n\n\n    As an exception, if you use this Software to compile your source code and\n    portions of this Software are embedded into the binary product as a result,\n    you may redistribute such product without providing attribution as would\n    otherwise be required by Sections 4(a), 4(b) and 4(d) of the License.\n"
  },
  {
    "path": "NOTICE.txt",
    "content": "\n                            The SwiftPM Project\n                            ====================\n\nPlease visit the SwiftPM web site for more information:\n\n  * https://github.com/swiftlang/swift-package-manager\n\nCopyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n\nThe Swift Project licenses this file to you under the Apache License,\nversion 2.0 (the \"License\"); you may not use this file except in compliance\nwith the License. You may obtain a copy of the License at:\n\n  https://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, WITHOUT\nWARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\nLicense for the specific language governing permissions and limitations\nunder the License.\n\nAlso, please refer to each LICENSE.txt file, which is located in\nthe 'license' directory of the distribution file, for the license terms of the\ncomponents that this product depends on.\n\n-------------------------------------------------------------------------------\n\nThe dependency resolver is influenced by Dart project (pub tool).\n\n  * LICENSE (BSD 3-Clause \"New\" or \"Revised\" License):\n    * https://github.com/dart-lang/pub/blob/master/LICENSE          // ignore-unacceptable-language\n  * HOMEPAGE:\n    * https://dart.dev\n    * https://github.com/dart-lang/pub\n\n---\n\nThis product contains a derivation of Vapor's JWTKit library, specifically `JWTParser.swift`, `JWTSerializer.swift` and `Base64URL.swift`.\n\n  * LICENSE (MIT License):\n    * https://www.apache.org/licenses/LICENSE-2.0\n  * HOMEPAGE:\n    * https://vapor.codes\n    * https://github.com/vapor/jwt-kit\n\n---\n\nThis product contains a derivation of OpenSSL's OCSP implementation, found under the `PackageCollectionsSigningLibc` module.\n\n  * LICENSE (Apache License 2.0):\n    * https://www.apache.org/licenses/LICENSE-2.0\n  * HOMEPAGE:\n    * https://github.com/openssl/openssl\n\n---\n\nThe observability system is influenced by SwiftLog project.\n\n  * LICENSE (Apache License 2.0):\n    * https://www.apache.org/licenses/LICENSE-2.0\n  * HOMEPAGE:\n    * https://github.com/apple/swift-log\n\n---\n\nThe observability system is influenced by SwiftMetrics project.\n\n  * LICENSE (Apache License 2.0):\n    * https://www.apache.org/licenses/LICENSE-2.0\n  * HOMEPAGE:\n    * https://github.com/apple/swift-metrics\n\n---\n\nThe observability system is influenced by SwiftDistributedTracing project.\n\n  * LICENSE (Apache License 2.0):\n    * https://www.apache.org/licenses/LICENSE-2.0\n  * HOMEPAGE:\n    * https://github.com/apple/swift-distributed-tracing-baggage\n\n---\n"
  },
  {
    "path": "Package.swift",
    "content": "// swift-tools-version:6.1\n\n//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.ProcessInfo\nimport PackageDescription\n\n// When building the toolchain on the CI for ELF platforms, remove the CI's\n// stdlib absolute runpath and add ELF's $ORIGIN relative paths before installing.\nlet swiftpmLinkSettings: [LinkerSetting]\nlet packageLibraryLinkSettings: [LinkerSetting]\nif let resourceDirPath = ProcessInfo.processInfo.environment[\"SWIFTCI_INSTALL_RPATH_OS\"] {\n    swiftpmLinkSettings = [.unsafeFlags([\n        \"-no-toolchain-stdlib-rpath\",\n        \"-Xlinker\", \"-rpath\",\n        \"-Xlinker\", \"$ORIGIN/../lib/swift/\\(resourceDirPath)\",\n    ])]\n    packageLibraryLinkSettings = [.unsafeFlags([\n        \"-no-toolchain-stdlib-rpath\",\n        \"-Xlinker\", \"-rpath\",\n        \"-Xlinker\", \"$ORIGIN/../../\\(resourceDirPath)\",\n    ])]\n} else {\n    swiftpmLinkSettings = []\n    packageLibraryLinkSettings = []\n}\n\n// Common experimental flags to be added to all targets.\nlet commonExperimentalFeatures: [SwiftSetting] = [\n    .enableExperimentalFeature(\"MemberImportVisibility\"),\n]\n\n// Certain targets fail to compile with MemberImportVisibility enabled on 6.0.3\n// but work with >=6.1. These targets opt in to using `swift6CompatibleExperimentalFeatures`.\n#if swift(>=6.1)\nlet swift6CompatibleExperimentalFeatures = commonExperimentalFeatures\n#else\nlet swift6CompatibleExperimentalFeatures: [SwiftSetting] = []\n#endif\n\n/** SwiftPMDataModel is the subset of SwiftPM product that includes just its data model.\n This allows some clients (such as IDEs) that use SwiftPM's data model but not its build system\n to not have to depend on SwiftDriver, SwiftLLBuild, etc. We should probably have better names here,\n though that could break some clients.\n */\nlet swiftPMDataModelProduct = (\n    name: \"SwiftPMDataModel\",\n    targets: [\n        \"PackageCollections\",\n        \"PackageCollectionsModel\",\n        \"PackageGraph\",\n        \"PackageLoading\",\n        \"PackageMetadata\",\n        \"PackageModel\",\n        \"SourceControl\",\n        \"Workspace\",\n    ]\n)\n\n/** The `libSwiftPM` set of interfaces to programmatically work with Swift\n packages.  `libSwiftPM` includes all of the SwiftPM code except the\n command line tools, while `libSwiftPMDataModel` includes only the data model.\n\n NOTE: This API is *unstable* and may change at any time.\n */\nlet swiftPMProduct = (\n    name: \"SwiftPM\",\n    targets: swiftPMDataModelProduct.targets + [\n        \"Build\",\n        \"LLBuildManifest\",\n        \"SourceKitLSPAPI\",\n        \"SPMLLBuild\",\n    ]\n)\n\n#if os(Windows)\nlet includeDynamicLibrary: Bool = false\nlet systemSQLitePkgConfig: String? = nil\n#else\nlet includeDynamicLibrary: Bool = true\nvar systemSQLitePkgConfig: String? = \"sqlite3\"\nif ProcessInfo.processInfo.environment[\"SWIFTCI_INSTALL_RPATH_OS\"] == \"android\" {\n    systemSQLitePkgConfig = nil\n}\n#endif\n\n/** An array of products which have two versions listed: one dynamically linked, the other with the\n automatic linking type with `-auto` suffix appended to product's name.\n */\nlet autoProducts = [swiftPMProduct, swiftPMDataModelProduct]\n\nlet shouldUseSwiftBuildFramework = (ProcessInfo.processInfo.environment[\"SWIFTPM_SWBUILD_FRAMEWORK\"] != nil)\n\nlet swiftDriverDeps: [Target.Dependency]\nlet swiftTSCBasicsDeps: [Target.Dependency]\nlet swiftToolsCoreSupportAutoDeps: [Target.Dependency]\nlet swiftTSCTestSupportDeps: [Target.Dependency]\nlet swiftToolsProtocolsDeps: [Target.Dependency]\n\nif shouldUseSwiftBuildFramework {\n    swiftDriverDeps = []\n    swiftTSCBasicsDeps = []\n    swiftToolsCoreSupportAutoDeps = []\n    swiftTSCTestSupportDeps = []\n    swiftToolsProtocolsDeps = []\n} else {\n    swiftDriverDeps = [\n        .product(name: \"SwiftDriver\", package: \"swift-driver\")\n    ]\n    swiftTSCBasicsDeps = [\n        .product(name: \"TSCBasic\", package: \"swift-tools-support-core\"),\n    ]\n    swiftToolsCoreSupportAutoDeps = [\n        .product(name: \"SwiftToolsSupport-auto\", package: \"swift-tools-support-core\")\n    ]\n    swiftTSCTestSupportDeps = [\n        .product(name: \"TSCTestSupport\", package: \"swift-tools-support-core\"),\n    ]\n    swiftToolsProtocolsDeps = [\n        .product(name: \"BuildServerProtocol\", package: \"swift-tools-protocols\", condition: .when(platforms: [.macOS, .linux, .windows, .android, .openbsd, .custom(\"freebsd\")])),\n        .product(name: \"LanguageServerProtocol\", package: \"swift-tools-protocols\", condition: .when(platforms: [.macOS, .linux, .windows, .android, .openbsd, .custom(\"freebsd\")])),\n        .product(name: \"LanguageServerProtocolTransport\", package: \"swift-tools-protocols\", condition: .when(platforms: [.macOS, .linux, .windows, .android, .openbsd, .custom(\"freebsd\")])),\n    ]\n}\nlet package = Package(\n    name: \"SwiftPM\",\n    platforms: [\n        .macOS(.v14),\n        .iOS(.v17),\n        .macCatalyst(.v17),\n    ],\n    products:\n    autoProducts.flatMap {\n        (includeDynamicLibrary ? [\n            .library(\n                name: $0.name,\n                type: .dynamic,\n                targets: $0.targets\n            ),\n        ] : [])\n        +\n        [\n            .library(\n                name: \"\\($0.name)-auto\",\n                targets: $0.targets\n            ),\n        ]\n    } + [\n        .library(\n            name: \"XCBuildSupport\",\n            targets: [\"XCBuildSupport\"]\n        ),\n        .library(\n            name: \"PackageDescription\",\n            type: .dynamic,\n            targets: [\"PackageDescription\", \"CompilerPluginSupport\"]\n        ),\n        .library(\n            name: \"AppleProductTypes\",\n            type: .dynamic,\n            targets: [\"AppleProductTypes\"]\n        ),\n\n        .library(\n            name: \"PackagePlugin\",\n            type: .dynamic,\n            targets: [\"PackagePlugin\"]\n        ),\n        .library(\n            name: \"PackageCollectionsModel\",\n            targets: [\"PackageCollectionsModel\"]\n        ),\n        .library(\n            name: \"SwiftPMPackageCollections\",\n            targets: [\n                \"PackageCollections\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageModel\",\n            ]\n        ),\n    ],\n    targets: [\n        // The `AppleProductTypes` target provides additional product types\n        // to `Package.swift` manifests. Here we build a debug version of the\n        // library; the bootstrap scripts build the deployable version.\n        .target(\n            name: \"AppleProductTypes\",\n            // Note: We use `-module-link-name` so clients link against the\n            // AppleProductTypes library when they import it without further\n            // messing with the manifest loader.\n            dependencies: [\"PackageDescription\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-package-description-version\", \"999.0\"]),\n                .unsafeFlags([\"-enable-library-evolution\"], .when(platforms: [.macOS])),\n                .unsafeFlags([\"-Xfrontend\", \"-module-link-name\", \"-Xfrontend\", \"AppleProductTypes\"])\n            ]),\n\n        .target(\n            name: \"SourceKitLSPAPI\",\n            dependencies: [\n                \"Basics\",\n                \"Build\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageModel\",\n                \"SPMBuildCore\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .enableExperimentalFeature(\"AccessLevelOnImport\"),\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        // MARK: SwiftPM specific support libraries\n\n        .systemLibrary(name: \"SPMSQLite3\", pkgConfig: systemSQLitePkgConfig),\n\n        .target(\n            name: \"_AsyncFileSystem\",\n            dependencies: [\n                .product(name: \"SystemPackage\", package: \"swift-system\"),\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .enableExperimentalFeature(\"StrictConcurrency\"),\n                .enableExperimentalFeature(\"AccessLevelOnImport\"),\n                .enableExperimentalFeature(\"InternalImportsByDefault\"),\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            name: \"Basics\",\n            dependencies: [\n                \"_AsyncFileSystem\",\n                .target(name: \"SPMSQLite3\", condition: .when(platforms: [.macOS, .iOS, .tvOS, .watchOS, .visionOS, .macCatalyst, .linux, .openbsd, .custom(\"freebsd\")])),\n                .product(name: \"SwiftToolchainCSQLite\", package: \"swift-toolchain-sqlite\", condition: .when(platforms: [.windows, .android])),\n                .product(name: \"DequeModule\", package: \"swift-collections\"),\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n                .product(name: \"SystemPackage\", package: \"swift-system\"),\n            ] + swiftToolsCoreSupportAutoDeps,\n            exclude: [\"CMakeLists.txt\", \"Vendor/README.md\"],\n            swiftSettings: swift6CompatibleExperimentalFeatures + [\n                .enableExperimentalFeature(\"StrictConcurrency\"),\n                .enableExperimentalFeature(\"AccessLevelOnImport\"),\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** The llbuild manifest model */\n            name: \"LLBuildManifest\",\n            dependencies: [\"Basics\"],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** Package registry support */\n            name: \"PackageRegistry\",\n            dependencies: [\n                \"Basics\",\n                \"PackageFingerprint\",\n                \"PackageLoading\",\n                \"PackageModel\",\n                \"PackageSigning\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** Source control operations */\n            name: \"SourceControl\",\n            dependencies: [\n                \"Basics\",\n                \"PackageModel\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** Shim for llbuild library */\n            name: \"SPMLLBuild\",\n            dependencies: [\"Basics\"],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** API for deserializing diagnostics and applying fix-its */\n            name: \"SwiftFixIt\",\n            dependencies: [\n                \"Basics\",\n            ] + swiftTSCBasicsDeps + swiftSyntaxDependencies(\n                [\"SwiftDiagnostics\", \"SwiftIDEUtils\", \"SwiftParser\", \"SwiftSyntax\"]\n            ),\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** API for inspecting symbols defined in binaries */\n            name: \"BinarySymbols\",\n            dependencies: [\n                \"Basics\",\n            ] + swiftTSCBasicsDeps,\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        // MARK: Project Model\n\n        .target(\n            /** Primitive Package model objects */\n            name: \"PackageModel\",\n            dependencies: [\"Basics\"],\n            exclude: [\"CMakeLists.txt\", \"README.md\"],\n            swiftSettings: swift6CompatibleExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** SBOM (Software Bill of Materials) model objects */\n            name: \"SBOMModel\",\n            dependencies: [\"Basics\", \"PackageCollections\", \"PackageGraph\", \"PackageModel\", \"SourceControl\", \"SwiftBuildSupport\"],\n            exclude: [\"CMakeLists.txt\", \"README.md\"],\n            resources: [\n                .copy(\"CycloneDX/Resources/cyclonedx-1.7.schema.json\"),\n                .copy(\"SPDX/Resources/spdx-3.0.1.schema.json\"),\n            ],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** Package model conventions and loading support */\n            name: \"PackageLoading\",\n            dependencies: [\n                \"Basics\",\n                \"PackageModel\",\n                \"SourceControl\",\n            ],\n            exclude: [\"CMakeLists.txt\", \"README.md\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        // MARK: Package Dependency Resolution\n\n        .target(\n            /** Data structures and support for complete package graphs */\n            name: \"PackageGraph\",\n            dependencies: [\n                \"Basics\",\n                \"PackageLoading\",\n                \"PackageModel\",\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n            ],\n            exclude: [\"CMakeLists.txt\", \"README.md\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        // MARK: Package Collections\n\n        .target(\n            /** Package collections models */\n            name: \"PackageCollectionsModel\",\n            dependencies: [],\n            exclude: [\n                \"Formats/v1.md\",\n                \"CMakeLists.txt\",\n            ],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** Data structures and support for package collections */\n            name: \"PackageCollections\",\n            dependencies: [\n                \"Basics\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageModel\",\n                \"SourceControl\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: swift6CompatibleExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            name: \"PackageCollectionsSigning\",\n            dependencies: [\n                .product(name: \"Crypto\", package: \"swift-crypto\"),\n                .product(name: \"X509\", package: \"swift-certificates\"),\n                \"Basics\",\n                \"PackageCollectionsModel\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            name: \"PackageFingerprint\",\n            dependencies: [\n                \"Basics\",\n                \"PackageModel\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            name: \"PackageSigning\",\n            dependencies: [\n                .product(name: \"Crypto\", package: \"swift-crypto\"),\n                .product(name: \"X509\", package: \"swift-certificates\"),\n                \"Basics\",\n                \"PackageModel\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        // MARK: Documentation\n\n        .target(\n            name: \"PackageManagerDocs\",\n            exclude: [\"README.md\"],\n        ),\n\n        // MARK: Package Manager Functionality\n\n        .target(\n            /** Builds Modules and Products */\n            name: \"SPMBuildCore\",\n            dependencies: [\n                \"Basics\",\n                \"PackageGraph\",\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n        .target(\n            /** Builds Modules and Products */\n            name: \"Build\",\n            dependencies: [\n                \"Basics\",\n                \"LLBuildManifest\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n                \"DriverSupport\",\n            ] + swiftDriverDeps,\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n        .target(\n            name: \"DriverSupport\",\n            dependencies: [\n                \"Basics\",\n                \"PackageModel\",\n            ] + swiftDriverDeps,\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n        .target(\n            /** Support for building using Xcode's build system */\n            name: \"XCBuildSupport\",\n            dependencies: [\n                \"SPMBuildCore\",\n                \"PackageGraph\",\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n        .target(\n            name: \"SwiftBuildSupport\",\n            dependencies: [\n                \"SPMBuildCore\",\n                \"PackageGraph\",\n            ],\n            exclude: [\"CMakeLists.txt\", \"README.md\"],\n            swiftSettings: commonExperimentalFeatures\n        ),\n        .target(\n            /** High level functionality */\n            name: \"Workspace\",\n            dependencies: [\n                \"Basics\",\n                \"PackageFingerprint\",\n                \"PackageGraph\",\n                \"PackageModel\",\n                \"PackageRegistry\",\n                \"PackageSigning\",\n                \"SourceControl\",\n                \"SPMBuildCore\",\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n        .target(\n            // ** High level interface for package discovery */\n            name: \"PackageMetadata\",\n            dependencies: [\n                \"Basics\",\n                \"PackageCollections\",\n                \"PackageModel\",\n                \"PackageRegistry\",\n                \"PackageSigning\",\n            ],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        // MARK: BSP\n        .target(\n            name: \"SwiftPMBuildServer\",\n            dependencies: [\n                \"Basics\",\n                \"Build\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageModel\",\n                \"SPMBuildCore\",\n                \"SourceControl\",\n                \"SourceKitLSPAPI\",\n                \"SwiftBuildSupport\",\n                \"Workspace\"\n            ] + swiftTSCBasicsDeps + swiftToolsProtocolsDeps,\n            exclude: [\n                \"CMakeLists.txt\",\n            ],\n        ),\n\n        // MARK: Commands\n\n        .target(\n            /** Minimal set of commands required for bootstrapping a new SwiftPM */\n            name: \"CoreCommands\",\n            dependencies: [\n                .product(name: \"ArgumentParser\", package: \"swift-argument-parser\"),\n                \"Basics\",\n                \"Build\",\n                \"PackageLoading\",\n                \"PackageModel\",\n                \"PackageGraph\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"SBOMModel\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** High-level commands */\n            name: \"Commands\",\n            dependencies: [\n                .product(name: \"ArgumentParser\", package: \"swift-argument-parser\"),\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n                .product(name: \"SystemPackage\", package: \"swift-system\"),\n                \"Basics\",\n                \"BinarySymbols\",\n                \"Build\",\n                \"CoreCommands\",\n                \"PackageGraph\",\n                \"SBOMModel\",\n                \"SourceControl\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"SwiftFixIt\",\n                \"SwiftPMBuildServer\",\n            ] + swiftSyntaxDependencies([\"SwiftIDEUtils\", \"SwiftRefactor\"]),\n            exclude: [\"CMakeLists.txt\", \"README.md\"],\n            swiftSettings: swift6CompatibleExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** Interacts with Swift SDKs used for cross-compilation */\n            name: \"SwiftSDKCommand\",\n            dependencies: [\n                .product(name: \"ArgumentParser\", package: \"swift-argument-parser\"),\n                \"Basics\",\n                \"CoreCommands\",\n                \"SPMBuildCore\",\n                \"PackageModel\",\n            ],\n            exclude: [\"CMakeLists.txt\", \"README.md\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** Interacts with package collections */\n            name: \"PackageCollectionsCommand\",\n            dependencies: [\n                .product(name: \"ArgumentParser\", package: \"swift-argument-parser\"),\n                \"Basics\",\n                \"Commands\",\n                \"CoreCommands\",\n                \"PackageCollections\",\n                \"PackageModel\",\n            ],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** Interact with package registry */\n            name: \"PackageRegistryCommand\",\n            dependencies: [\n                .product(name: \"ArgumentParser\", package: \"swift-argument-parser\"),\n                \"Basics\",\n                \"Commands\",\n                \"CoreCommands\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageModel\",\n                \"PackageRegistry\",\n                \"PackageSigning\",\n                \"SourceControl\",\n                \"SPMBuildCore\",\n                \"Workspace\",\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            name: \"QueryEngine\",\n            dependencies: [\n                \"_AsyncFileSystem\",\n                \"Basics\",\n                .product(name: \"Crypto\", package: \"swift-crypto\"),\n            ],\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: [\n                .enableExperimentalFeature(\"StrictConcurrency=complete\"),\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .executableTarget(\n            /** The main executable provided by SwiftPM */\n            name: \"swift-package\",\n            dependencies: [\"Basics\", \"Commands\"],\n            exclude: [\"CMakeLists.txt\"]\n        ),\n        .executableTarget(\n            /** Builds packages */\n            name: \"swift-build\",\n            dependencies: [\"Commands\"],\n            exclude: [\"CMakeLists.txt\"]\n        ),\n        .executableTarget(\n            /** Builds SwiftPM itself for bootstrapping (minimal version of `swift-build`) */\n            name: \"swift-bootstrap\",\n            dependencies: [\n                .product(name: \"ArgumentParser\", package: \"swift-argument-parser\"),\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n                \"Basics\",\n                \"Build\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageModel\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n            ],\n            exclude: [\"CMakeLists.txt\"]\n        ),\n        .executableTarget(\n            /** Interacts with Swift SDKs used for cross-compilation */\n            name: \"swift-sdk\",\n            dependencies: [\"Commands\", \"SwiftSDKCommand\"],\n            exclude: [\"CMakeLists.txt\"]\n        ),\n        .executableTarget(\n            /** Deprecated command superseded by `swift-sdk` */\n            name: \"swift-experimental-sdk\",\n            dependencies: [\"Commands\", \"SwiftSDKCommand\"],\n            exclude: [\"CMakeLists.txt\"]\n        ),\n        .executableTarget(\n            /** Runs package tests */\n            name: \"swift-test\",\n            dependencies: [\"Commands\"],\n            exclude: [\"CMakeLists.txt\"]\n        ),\n        .executableTarget(\n            /** Runs an executable product */\n            name: \"swift-run\",\n            dependencies: [\"Commands\"],\n            exclude: [\"CMakeLists.txt\"]\n        ),\n        .executableTarget(\n            /** Interacts with package collections */\n            name: \"swift-package-collection\",\n            dependencies: [\"Commands\", \"PackageCollectionsCommand\"]\n        ),\n        .executableTarget(\n            /** Multi-command entry point for SwiftPM. */\n            name: \"swift-package-manager\",\n            dependencies: [\n                \"Basics\",\n                \"Commands\",\n                \"SwiftSDKCommand\",\n                \"PackageCollectionsCommand\",\n                \"PackageRegistryCommand\",\n            ],\n            linkerSettings: swiftpmLinkSettings\n        ),\n        .executableTarget(\n            /** Interact with package registry */\n            name: \"swift-package-registry\",\n            dependencies: [\"Commands\", \"PackageRegistryCommand\"]\n        ),\n        .executableTarget(\n            /** Utility to produce the artifacts for prebuilts */\n            name: \"swift-build-prebuilts\",\n            dependencies: [\n                .product(name: \"ArgumentParser\", package: \"swift-argument-parser\"),\n                \"Basics\",\n                \"Workspace\",\n            ],\n            exclude: [\n                \"build.sh\"\n            ]\n        ),\n\n        // The `PackageDescription` target provides the API that is available\n        // to `Package.swift` manifests. Here we build a debug version of the\n        // library; the bootstrap scripts build the deployable version.\n        .target(\n            name: \"PackageDescription\",\n            path: \"Sources/Runtimes/PackageDescription\",\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .define(\"USE_IMPL_ONLY_IMPORTS\"),\n                .unsafeFlags([\"-package-description-version\", \"999.0\"]),\n                .unsafeFlags([\"-enable-library-evolution\"]),\n            ],\n            linkerSettings: packageLibraryLinkSettings\n        ),\n\n        // The `PackagePlugin` target provides the API that is available to\n        // plugin scripts. Here we build a debug version of the library; the\n        // bootstrap scripts build the deployable version.\n        .target(\n            name: \"PackagePlugin\",\n            path: \"Sources/Runtimes/PackagePlugin\",\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-package-description-version\", \"999.0\"]),\n                .unsafeFlags([\"-enable-library-evolution\"]),\n            ],\n            linkerSettings: packageLibraryLinkSettings\n        ),\n\n        // MARK: Support for Swift macros, should eventually move to a plugin-based solution\n\n        .target(\n            name: \"CompilerPluginSupport\",\n            dependencies: [\"PackageDescription\"],\n            path: \"Sources/Runtimes/CompilerPluginSupport\",\n            exclude: [\"CMakeLists.txt\"],\n            swiftSettings: commonExperimentalFeatures + [\n                .unsafeFlags([\"-package-description-version\", \"999.0\"]),\n                .unsafeFlags([\"-enable-library-evolution\"]),\n            ]\n        ),\n\n        // MARK: Additional Test Dependencies\n\n        .target(\n            /** SwiftPM internal build test suite support library */\n            name: \"_InternalBuildTestSupport\",\n            dependencies: [\n                \"Build\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"_InternalTestSupport\"\n            ],\n            swiftSettings: [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        .target(\n            /** SwiftPM internal test suite support library */\n            name: \"_InternalTestSupport\",\n            dependencies: [\n                \"Basics\",\n                \"DriverSupport\",\n                \"PackageFingerprint\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageRegistry\",\n                \"PackageSigning\",\n                \"SourceControl\",\n                .product(name: \"OrderedCollections\", package: \"swift-collections\"),\n                \"Workspace\",\n            ] + swiftTSCTestSupportDeps,\n            swiftSettings: [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n        .target(\n            /** SwiftPM internal test suite support library */\n            name: \"_IntegrationTestSupport\",\n            dependencies: [\n                \"_InternalTestSupport\",\n            ] + swiftTSCTestSupportDeps,\n        ),\n\n        .target(\n            /** Test for thread-sanitizer. */\n            name: \"tsan_utils\",\n            dependencies: [],\n            swiftSettings: [\n                .unsafeFlags([\"-static\"]),\n            ]\n        ),\n\n        // MARK: SwiftPM tests\n\n        .testTarget(\n            name: \"_AsyncFileSystemTests\",\n            dependencies: [\n                \"_AsyncFileSystem\",\n                \"_InternalTestSupport\",\n            ]\n        ),\n\n        .testTarget(\n            name: \"SourceKitLSPAPITests\",\n            dependencies: [\n                \"SourceKitLSPAPI\",\n                \"_InternalTestSupport\",\n            ]\n        ),\n\n        .testTarget(\n            name: \"BasicsTests\",\n            dependencies: [\n                \"Basics\",\n                \"_InternalTestSupport\",\n                \"tsan_utils\",\n            ],\n            exclude: [\n                \"Archiver/Inputs/archive.tar.gz\",\n                \"Archiver/Inputs/archive.zip\",\n                \"Archiver/Inputs/invalid_archive.tar.gz\",\n                \"Archiver/Inputs/invalid_archive.zip\",\n                \"processInputs/long-stdout-stderr\",\n                \"processInputs/long-stdout-stderr.bat\",\n                \"processInputs/exit4\",\n                \"processInputs/exit4.bat\",\n                \"processInputs/simple-stdout-stderr\",\n                \"processInputs/simple-stdout-stderr.bat\",\n                \"processInputs/deadlock-if-blocking-io\",\n                \"processInputs/deadlock-if-blocking-io.bat\",\n                \"processInputs/echo\",\n                \"processInputs/echo.bat\",\n                \"processInputs/in-to-out\",\n                \"processInputs/in-to-out.bat\",\n            ]\n        ),\n        .testTarget(\n            name: \"BuildTests\",\n            dependencies: [\"Build\", \"PackageModel\", \"Commands\", \"_InternalTestSupport\", \"_InternalBuildTestSupport\"]\n        ),\n        .testTarget(\n            name: \"LLBuildManifestTests\",\n            dependencies: [\"Basics\", \"LLBuildManifest\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"WorkspaceTests\",\n            dependencies: [\"Workspace\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"PackageDescriptionTests\",\n            dependencies: [\"PackageDescription\"]\n        ),\n        .testTarget(\n            name: \"SPMBuildCoreTests\",\n            dependencies: [\"SPMBuildCore\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"PackageLoadingTests\",\n            dependencies: [\"PackageLoading\", \"_InternalTestSupport\"],\n            exclude: [\"Inputs\", \"pkgconfigInputs\"]\n        ),\n        .testTarget(\n            name: \"PackageModelTests\",\n            dependencies: [\"PackageModel\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"PackageGraphTests\",\n            dependencies: [\"PackageGraph\", \"_InternalTestSupport\"],\n            swiftSettings: commonExperimentalFeatures\n        ),\n        .testTarget(\n            name: \"PackageGraphPerformanceTests\",\n            dependencies: [\"PackageGraph\", \"_InternalTestSupport\"],\n            exclude: [\n                \"Inputs/PerfectHTTPServer.json\",\n                \"Inputs/ZewoHTTPServer.json\",\n                \"Inputs/SourceKitten.json\",\n                \"Inputs/kitura.json\",\n            ]\n        ),\n        .testTarget(\n            name: \"PackageCollectionsModelTests\",\n            dependencies: [\"PackageCollectionsModel\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"PackageCollectionsSigningTests\",\n            dependencies: [\"PackageCollectionsSigning\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"PackageCollectionsTests\",\n            dependencies: [\"PackageCollections\", \"_InternalTestSupport\", \"tsan_utils\"]\n        ),\n        .testTarget(\n            name: \"PackageFingerprintTests\",\n            dependencies: [\"PackageFingerprint\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"PackagePluginAPITests\",\n            dependencies: [\"PackagePlugin\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"PackageRegistryTests\",\n            dependencies: [\"_InternalTestSupport\", \"PackageRegistry\"]\n        ),\n        .testTarget(\n            name: \"PackageSigningTests\",\n            dependencies: [\"_InternalTestSupport\", \"PackageSigning\"]\n        ),\n        .testTarget(\n            name: \"SBOMModelTests\",\n            dependencies: [\"SBOMModel\", \"_InternalTestSupport\"],\n            resources: [\n                .copy(\"testfiles\"),\n            ]\n        ),\n        .testTarget(\n            name: \"QueryEngineTests\",\n            dependencies: [\"QueryEngine\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"SourceControlTests\",\n            dependencies: [\"SourceControl\", \"_InternalTestSupport\"],\n            exclude: [\"Inputs/TestRepo.tgz\"]\n        ),\n        .testTarget(\n            name: \"SwiftFixItTests\",\n            dependencies: [\"SwiftFixIt\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"BinarySymbolsTests\",\n            dependencies: [\"BinarySymbols\", \"_InternalTestSupport\"]\n        ),\n        .testTarget(\n            name: \"XCBuildSupportTests\",\n            dependencies: [\"XCBuildSupport\", \"_InternalTestSupport\", \"_InternalBuildTestSupport\"],\n            exclude: [\"Inputs/Foo.pc\"]\n        ),\n        .testTarget(\n            name: \"FunctionalPerformanceTests\",\n            dependencies: [\n                \"swift-package-manager\",\n                \"_InternalTestSupport\",\n            ]\n        ),\n        .testTarget(\n            name: \"SwiftBuildSupportTests\",\n            dependencies: [\"SwiftBuildSupport\", \"_InternalTestSupport\", \"_InternalBuildTestSupport\"]\n        ),\n        .testTarget(\n            name: \"BuildMetalTests\",\n            dependencies: [\n                \"_InternalTestSupport\",\n                \"Basics\"\n            ]\n        ),\n        // Examples (These are built to ensure they stay up to date with the API.)\n        .executableTarget(\n            name: \"package-info\",\n            dependencies: [\"Workspace\"],\n            path: \"Examples/package-info/Sources/package-info\"\n        )\n    ],\n    swiftLanguageModes: [.v5]\n)\n\n#if canImport(Darwin)\npackage.targets.append(contentsOf: [\n    .executableTarget(\n        name: \"swiftpm-testing-helper\"\n    )\n])\n#endif\n\n// rdar://101868275 \"error: cannot find 'XCTAssertEqual' in scope\" can affect almost any functional test, so we flat out\n// disable them all until we know what is going on\nif ProcessInfo.processInfo.environment[\"SWIFTCI_DISABLE_SDK_DEPENDENT_TESTS\"] == nil {\n    package.targets.append(contentsOf: [\n        .testTarget(\n            name: \"FunctionalTests\",\n            dependencies: [\n                \"swift-package-manager\",\n                \"PackageModel\",\n                \"_InternalTestSupport\",\n            ]\n        ),\n        .executableTarget(\n            name: \"dummy-swiftc\",\n            dependencies: [\n                \"Basics\",\n            ]\n        ),\n        .testTarget(\n            name: \"_InternalTestSupportTests\",\n            dependencies: [\n                \"_InternalTestSupport\"\n            ]\n        ),\n        .testTarget(\n            name: \"IntegrationTests\",\n            dependencies: [\n                \"_IntegrationTestSupport\",\n                \"_InternalTestSupport\",\n            ] + swiftTSCTestSupportDeps + swiftToolsCoreSupportAutoDeps,\n        ),\n        .testTarget(\n            name: \"CommandsTests\",\n            dependencies: [\n                \"swift-package-manager\",\n                \"Basics\",\n                \"Build\",\n                \"Commands\",\n                \"PackageModel\",\n                \"PackageRegistryCommand\",\n                \"SourceControl\",\n                \"_InternalTestSupport\",\n                \"Workspace\",\n                \"dummy-swiftc\",\n            ]\n        ),\n        .testTarget(\n            name: \"SwiftPMBuildServerTests\",\n            dependencies: [\n                \"SwiftPMBuildServer\",\n                \"_InternalTestSupport\",\n            ] + swiftToolsProtocolsDeps\n        ),\n    ])\n}\n\n\nfunc swiftSyntaxDependencies(_ names: [String]) -> [Target.Dependency] {\n  /// Whether swift-syntax is being built as a single dynamic library instead of as a separate library per module.\n  ///\n  /// This means that the swift-syntax symbols don't need to be statically linked, which allows us to stay below the\n  /// maximum number of exported symbols on Windows, in turn allowing us to build sourcekit-lsp using SwiftPM on Windows\n  /// and run its tests.\n  let buildDynamicSwiftSyntaxLibrary = ProcessInfo.processInfo.environment[\"SWIFTSYNTAX_BUILD_DYNAMIC_LIBRARY\"] != nil\n  if buildDynamicSwiftSyntaxLibrary {\n    return [.product(name: \"_SwiftSyntaxDynamic\", package: \"swift-syntax\")]\n  } else {\n    return names.map { .product(name: $0, package: \"swift-syntax\") }\n  }\n}\n\n// Add package dependency on llbuild when not bootstrapping.\n//\n// When bootstrapping SwiftPM, we can't use llbuild as a package dependency it\n// will provided by whatever build system (SwiftCI, bootstrap script) is driving\n// the build process. So, we only add these dependencies if SwiftPM is being\n// built directly using SwiftPM. It is a bit unfortunate that we've add the\n// package dependency like this but there is no other good way of expressing\n// this right now.\n\n/// When not using local dependencies, the branch to use for llbuild and TSC repositories.\nlet relatedDependenciesBranch = \"main\"\n\nif ProcessInfo.processInfo.environment[\"SWIFTPM_LLBUILD_FWK\"] == nil {\n    if ProcessInfo.processInfo.environment[\"SWIFTCI_USE_LOCAL_DEPS\"] == nil {\n        package.dependencies += [\n            .package(url: \"https://github.com/swiftlang/swift-llbuild.git\", branch: relatedDependenciesBranch),\n        ]\n    } else {\n        // In Swift CI, use a local path to llbuild to interoperate with tools\n        // like `update-checkout`, which control the sources externally.\n        package.dependencies += [\n            .package(name: \"swift-llbuild\", path: \"../llbuild\"),\n        ]\n    }\n    package.targets.first(where: { $0.name == \"SPMLLBuild\" })!.dependencies += [\n        .product(name: \"llbuildSwift\", package: \"swift-llbuild\"),\n    ]\n}\n\nif ProcessInfo.processInfo.environment[\"SWIFTCI_USE_LOCAL_DEPS\"] == nil {\n    package.dependencies += [\n        // These need to match the versions in the swiftlang/swift repo,\n        // utils/update_checkout/update-checkout-config.json\n        // They are used to build the official swift toolchain.\n        .package(url: \"https://github.com/swiftlang/swift-syntax.git\", branch: relatedDependenciesBranch),\n        .package(url: \"https://github.com/apple/swift-argument-parser.git\", revision: \"1.6.1\"),\n        .package(url: \"https://github.com/apple/swift-crypto.git\", revision: \"3.12.5\"),\n        .package(url: \"https://github.com/apple/swift-system.git\", revision: \"1.5.0\"),\n        .package(url: \"https://github.com/apple/swift-collections.git\", revision: \"1.1.6\"),\n        .package(url: \"https://github.com/apple/swift-certificates.git\", revision: \"1.10.1\"),\n        .package(url: \"https://github.com/swiftlang/swift-toolchain-sqlite.git\", revision: \"1.0.7\"),\n        // Not in toolchain, used for use in previewing documentation\n        .package(url: \"https://github.com/swiftlang/swift-docc-plugin\", from: \"1.1.0\"),\n    ]\n    if !swiftDriverDeps.isEmpty {\n        package.dependencies += [\n            .package(url: \"https://github.com/swiftlang/swift-tools-support-core.git\", branch: relatedDependenciesBranch),\n            .package(url: \"https://github.com/swiftlang/swift-driver.git\", branch: relatedDependenciesBranch),\n        ]\n    }\n} else {\n    package.dependencies += [\n        .package(path: \"../swift-argument-parser\"),\n        .package(path: \"../swift-crypto\"),\n        .package(path: \"../swift-syntax\"),\n        .package(path: \"../swift-system\"),\n        .package(path: \"../swift-collections\"),\n        .package(path: \"../swift-certificates\"),\n        .package(path: \"../swift-toolchain-sqlite\"),\n    ]\n    if !swiftDriverDeps.isEmpty {\n        package.dependencies += [\n            .package(path: \"../swift-tools-support-core\"),\n            .package(path: \"../swift-driver\"),\n        ]\n    }\n\n}\n\n/// If ENABLE_APPLE_PRODUCT_TYPES is set in the environment, then also define ENABLE_APPLE_PRODUCT_TYPES in each of the regular targets and test targets.\nif ProcessInfo.processInfo.environment[\"ENABLE_APPLE_PRODUCT_TYPES\"] == \"1\" {\n    for target in package.targets.filter({ $0.type == .regular || $0.type == .test }) {\n        target.swiftSettings = (target.swiftSettings ?? []) + [ .define(\"ENABLE_APPLE_PRODUCT_TYPES\") ]\n    }\n}\n\nif !shouldUseSwiftBuildFramework {\n\n    let swiftbuildsupport: Target = package.targets.first(where: { [\"SwiftBuildSupport\", \"SwiftPMBuildServer\", \"SwiftPMBuildServerTests\"].contains($0.name) } )!\n    swiftbuildsupport.dependencies += [\n        .product(name: \"SwiftBuild\", package: \"swift-build\"),\n    ]\n\n    swiftbuildsupport.dependencies += [\n        // This is here to statically link the build service in the same executable as SwiftPM\n        .product(name: \"SWBBuildService\", package: \"swift-build\"),\n    ]\n\n    if ProcessInfo.processInfo.environment[\"SWIFTCI_USE_LOCAL_DEPS\"] == nil {\n        package.dependencies += [\n            .package(url: \"https://github.com/swiftlang/swift-build.git\", branch: relatedDependenciesBranch),\n            .package(url: \"https://github.com/swiftlang/swift-tools-protocols.git\", branch: relatedDependenciesBranch),\n        ]\n    } else {\n        package.dependencies += [\n            .package(path: \"../swift-build\"),\n            .package(path: \"../swift-tools-protocols\"),\n        ]\n    }\n}\n"
  },
  {
    "path": "README.md",
    "content": "# Swift Package Manager Project\n\nThe Swift Package Manager is a tool for managing distribution of source code, aimed at making it easy to share your code and reuse others’ code. The tool directly addresses the challenges of compiling and linking Swift packages, managing dependencies, versioning, and supporting flexible distribution and collaboration models.\n\nWe’ve designed the system to make it easy to share packages on services like GitHub, but packages are also great for private personal development, sharing code within a team, or at any other granularity.\n\nSwift Package Manager includes a build system that can build for macOS and Linux. Starting with Xcode 11, Xcode integrates with SwiftPM to provide support for including packages in iOS, macOS, watchOS, and tvOS applications.\n\nThe [SourceKit-LSP](https://github.com/swiftlang/sourcekit-lsp) project leverages libSwiftPM and provides [Language Server Protocol](https://langserver.org/) implementation for editors that support LSP.\n\n---\n\n## Table of Contents\n* [Getting Started](#getting-started)\n* [Documentation](#documentation)\n* [System Requirements](#system-requirements)\n* [Installation](#installation)\n* [Contributing](#contributing)\n* [Reporting issues](#reporting-issues)\n* [License](#license)\n\n---\n\n## Getting Started\n\nPlease use [this guide](https://www.swift.org/documentation/package-manager/) for learning package manager basics.\n\n---\n\n## Documentation\n\nFor Quick Help use the `swift package --help` command.\n\nFor documentation on using Swift Package Manager, creating packages, and more, see the [Package Manager Docs](https://docs.swift.org/swiftpm/documentation/packagemanagerdocs).\n\nFor documentation on developing the Swift Package Manager itself, see the [contribution guide](CONTRIBUTING.md).\n\nFor detailed documentation on the package manifest API, see [PackageDescription API](https://docs.swift.org/swiftpm/documentation/packagedescription).\n\nFor release notes with information about changes between versions, see the [release notes](Documentation/ReleaseNotes).\n\n---\n\n## System Requirements\n\nThe package manager’s system requirements are the same as [those for Swift](https://github.com/swiftlang/swift/blob/main/docs/HowToGuides/GettingStarted.md#system-requirements) with the caveat that the package manager requires Git at runtime as well as build-time.\n\n---\n\n## Installation\n\nThe package manager is available as part the Swift toolchains available on [Swift.org](https://swift.org/download/) including snapshots for the latest versions built from `main` branch. For installation instructions for downloaded snapshots, please see the [Getting Started](https://swift.org/getting-started/#installing-swift) section of [Swift.org](https://swift.org).\n\nThe Swift Package Manager is also included in Xcode 8.0 and all subsequent releases.\n\nYou can verify your installation by typing `swift package --version` in a terminal:\n\n```sh\n$ swift package --version\nApple Swift Package Manager - ...\n```\n\n## Contributing\n\nThere are several ways to contribute to Swift Package Manager. To learn about the policies, best practices that govern contributions to the Swift project and instructions for setting up the development environment please read the [Contributor Guide](CONTRIBUTING.md).  \n\nThe Swift package manager uses [llbuild](https://github.com/apple/swift-llbuild) as the underlying build system for compiling source files. It is also open source and part of the Swift project.\n\n---\n\n## Reporting issues\n\nIf you have any trouble with the package manager, help is available. We recommend:\n\n* The [Swift Forums](https://forums.swift.org/c/development/swiftpm/),\n* SwiftPM's [bug tracker](https://github.com/swiftlang/swift-package-manager/issues)\n\nWhen reporting an issue please follow the bug reporting guidelines, they can be found in [contribution guide](./CONTRIBUTING.md#reporting-issues).\n\nIf you’re not comfortable sharing your question with the list, contact details for the code owners can be found in [CODEOWNERS](CODEOWNERS); however, Swift Forums is usually the best place to go for help.\n\n---\n\n## License\n\nCopyright 2015 - 2025 Apple Inc. and the Swift project authors. Licensed under Apache License v2.0 with Runtime Library Exception.\n\nSee [https://swift.org/LICENSE.txt](https://swift.org/LICENSE.txt) for license information.\n\nSee [https://swift.org/CONTRIBUTORS.txt](https://swift.org/CONTRIBUTORS.txt) for Swift project authors.\n"
  },
  {
    "path": "Sources/AppleProductTypes/Product.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\n@_spi(PackageProductSettings) import PackageDescription\n\n#if ENABLE_APPLE_PRODUCT_TYPES\nextension Product {\n    /// Creates an iOS application package product.\n    ///\n    /// - Parameters:\n    ///     - name: The name of the application product.\n    ///     - targets: The targets to include in the application product; one and only one of them should be an executable target.\n    ///     - settings: The settings that define the core properties of the application.\n    public static func iOSApplication(\n        name: String,\n        targets: [String],\n        bundleIdentifier: String? = nil,\n        teamIdentifier: String? = nil,\n        displayVersion: String? = nil,\n        bundleVersion: String? = nil,\n        iconAssetName: String? = nil,\n        accentColorAssetName: String? = nil,\n        supportedDeviceFamilies: [ProductSetting.IOSAppInfo.DeviceFamily],\n        supportedInterfaceOrientations: [ProductSetting.IOSAppInfo.InterfaceOrientation],\n        capabilities: [ProductSetting.IOSAppInfo.Capability] = [],\n        additionalInfoPlistContentFilePath: String? = nil\n    ) -> Product {\n        return iOSApplication(\n            name: name,\n            targets: targets,\n            bundleIdentifier: bundleIdentifier,\n            teamIdentifier: teamIdentifier,\n            displayVersion: displayVersion,\n            bundleVersion: bundleVersion,\n            appIcon: iconAssetName.map({ .asset($0) }),\n            accentColor: accentColorAssetName.map({ .asset($0) }),\n            supportedDeviceFamilies: supportedDeviceFamilies,\n            supportedInterfaceOrientations: supportedInterfaceOrientations,\n            capabilities: capabilities,\n            additionalInfoPlistContentFilePath: additionalInfoPlistContentFilePath\n        )\n    }\n\n    /// Creates an iOS application package product.\n    ///\n    /// - Parameters:\n    ///     - name: The name of the application product.\n    ///     - targets: The targets to include in the application product; one and only one of them should be an executable target.\n    ///     - settings: The settings that define the core properties of the application.\n    @available(_PackageDescription, introduced: 5.6)\n    public static func iOSApplication(\n        name: String,\n        targets: [String],\n        bundleIdentifier: String? = nil,\n        teamIdentifier: String? = nil,\n        displayVersion: String? = nil,\n        bundleVersion: String? = nil,\n        appIcon: ProductSetting.IOSAppInfo.AppIcon? = nil,\n        accentColor: ProductSetting.IOSAppInfo.AccentColor? = nil,\n        supportedDeviceFamilies: [ProductSetting.IOSAppInfo.DeviceFamily],\n        supportedInterfaceOrientations: [ProductSetting.IOSAppInfo.InterfaceOrientation],\n        capabilities: [ProductSetting.IOSAppInfo.Capability] = [],\n        appCategory: ProductSetting.IOSAppInfo.AppCategory? = nil,\n        additionalInfoPlistContentFilePath: String? = nil\n    ) -> Product {\n        return .executable(name: name, targets: targets, settings: [\n            bundleIdentifier.map{ .bundleIdentifier($0) },\n            teamIdentifier.map{ .teamIdentifier($0) },\n            displayVersion.map{ .displayVersion($0) },\n            bundleVersion.map{ .bundleVersion($0) },\n            .iOSAppInfo(ProductSetting.IOSAppInfo(\n                appIcon: appIcon,\n                accentColor: accentColor,\n                supportedDeviceFamilies: supportedDeviceFamilies,\n                supportedInterfaceOrientations: supportedInterfaceOrientations,\n                capabilities: capabilities,\n                appCategory: appCategory,\n                additionalInfoPlistContentFilePath: additionalInfoPlistContentFilePath\n            ))\n        ].compactMap{ $0 })\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Basics/Archiver/Archiver.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport struct Foundation.URL\n\n/// The `Archiver` protocol abstracts away the different operations surrounding archives.\npublic protocol Archiver: Sendable {\n    /// A set of extensions the current archiver supports.\n    var supportedExtensions: Set<String> { get }\n\n    /// Asynchronously extracts the contents of an archive to a destination folder.\n    ///\n    /// - Parameters:\n    ///   - archivePath: The `AbsolutePath` to the archive to extract.\n    ///   - destinationPath: The `AbsolutePath` to the directory to extract to.\n    ///   - completion: The completion handler that will be called when the operation finishes to notify of its success.\n    @available(*, noasync, message: \"Use the async alternative\")\n    func extract(\n        from archivePath: AbsolutePath,\n        to destinationPath: AbsolutePath,\n        completion: @escaping @Sendable (Result<Void, Error>) -> Void\n    )\n\n    /// Asynchronously compress the contents of a directory to a destination archive.\n    ///\n    /// - Parameters:\n    ///   - directory: The `AbsolutePath` to the archive to extract.\n    ///   - destinationPath: The `AbsolutePath` to the directory to extract to.\n    func compress(\n        directory: AbsolutePath,\n        to destinationPath: AbsolutePath\n    ) async throws\n\n    /// Asynchronously validates if a file is an archive.\n    ///\n    /// - Parameters:\n    ///   - path: The `AbsolutePath` to the archive to validate.\n    ///   - completion: The completion handler that will be called when the operation finishes to notify of its success.\n    @available(*, noasync, message: \"Use the async alternative\")\n    func validate(\n        path: AbsolutePath,\n        completion: @escaping @Sendable (Result<Bool, Error>) -> Void\n    )\n}\n\nextension Archiver {\n    /// Asynchronously extracts the contents of an archive to a destination folder.\n    ///\n    /// - Parameters:\n    ///   - archivePath: The `AbsolutePath` to the archive to extract.\n    ///   - destinationPath: The `AbsolutePath` to the directory to extract to.\n    public func extract(\n        from archivePath: AbsolutePath,\n        to destinationPath: AbsolutePath\n    ) async throws {\n        try await withCheckedThrowingContinuation { continuation in\n            self.extract(from: archivePath, to: destinationPath, completion: { continuation.resume(with: $0) })\n        }\n    }\n\n    /// Asynchronously validates if a file is an archive.\n    ///\n    /// - Parameters:\n    ///   - path: The `AbsolutePath` to the archive to validate.\n    public func validate(\n        path: AbsolutePath\n    ) async throws -> Bool {\n        try await withCheckedThrowingContinuation { continuation in\n            self.validate(path: path, completion: { continuation.resume(with: $0) })\n        }\n    }\n\n    package func isFileSupported(_ lastPathComponent: String) -> Bool {\n        self.supportedExtensions.contains(where: { lastPathComponent.hasSuffix($0) })\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Archiver/TarArchiver.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Dispatch.DispatchQueue\nimport struct Dispatch.DispatchTime\nimport struct TSCBasic.FileSystemError\n\n/// An `Archiver` that handles Tar archives using the command-line `tar` tool.\npublic struct TarArchiver: Archiver {\n    public let supportedExtensions: Set<String> = [\"tar\", \"tar.gz\"]\n\n    /// The file-system implementation used for various file-system operations and checks.\n    private let fileSystem: FileSystem\n\n    /// Helper for cancelling in-flight requests\n    private let cancellator: Cancellator\n\n    /// The underlying command\n    internal let tarCommand: String\n\n    /// Creates a `TarArchiver`.\n    ///\n    /// - Parameters:\n    ///   - fileSystem: The file system to used by the `TarArchiver`.\n    ///   - cancellator: Cancellation handler\n    public init(fileSystem: FileSystem, cancellator: Cancellator? = .none) {\n        self.fileSystem = fileSystem\n        self.cancellator = cancellator ?? Cancellator(observabilityScope: .none)\n\n        #if os(Windows)\n        self.tarCommand = \"tar.exe\"\n        #else\n        self.tarCommand = \"tar\"\n        #endif\n    }\n\n    public func extract(\n        from archivePath: AbsolutePath,\n        to destinationPath: AbsolutePath,\n        completion: @escaping @Sendable (Result<Void, Error>) -> Void\n    ) {\n        do {\n            guard self.fileSystem.exists(archivePath) else {\n                throw FileSystemError(.noEntry, archivePath.underlying)\n            }\n\n            guard self.fileSystem.isDirectory(destinationPath) else {\n                throw FileSystemError(.notDirectory, destinationPath.underlying)\n            }\n\n            let process = AsyncProcess(\n                arguments: [self.tarCommand, \"zxf\", archivePath.pathString, \"-C\", destinationPath.pathString]\n            )\n\n            guard let registrationKey = self.cancellator.register(process) else {\n                throw CancellationError.failedToRegisterProcess(process)\n            }\n\n            DispatchQueue.sharedConcurrent.async {\n                defer { self.cancellator.deregister(registrationKey) }\n                completion(.init(catching: {\n                    try process.launch()\n                    let processResult = try process.waitUntilExit()\n                    guard processResult.exitStatus == .terminated(code: 0) else {\n                        throw try StringError(processResult.utf8stderrOutput())\n                    }\n                }))\n            }\n        } catch {\n            return completion(.failure(error))\n        }\n    }\n\n    public func compress(\n        directory: AbsolutePath,\n        to destinationPath: AbsolutePath\n    ) async throws {\n\n        guard self.fileSystem.isDirectory(directory) else {\n            throw FileSystemError(.notDirectory, directory.underlying)\n        }\n\n        let process = AsyncProcess(\n            arguments: [self.tarCommand, \"acf\", destinationPath.pathString, directory.basename],\n            environment: .current,\n            workingDirectory: directory.parentDirectory\n        )\n\n        guard let registrationKey = self.cancellator.register(process) else {\n            throw CancellationError.failedToRegisterProcess(process)\n        }\n\n        defer { self.cancellator.deregister(registrationKey) }\n\n        try process.launch()\n        let processResult = try await process.waitUntilExit()\n        guard processResult.exitStatus == .terminated(code: 0) else {\n            throw try StringError(processResult.utf8stderrOutput())\n        }\n    }\n\n    public func validate(path: AbsolutePath, completion: @escaping @Sendable (Result<Bool, Error>) -> Void) {\n        do {\n            guard self.fileSystem.exists(path) else {\n                throw FileSystemError(.noEntry, path.underlying)\n            }\n\n            let process = AsyncProcess(arguments: [self.tarCommand, \"tf\", path.pathString])\n            guard let registrationKey = self.cancellator.register(process) else {\n                throw CancellationError.failedToRegisterProcess(process)\n            }\n\n            DispatchQueue.sharedConcurrent.async {\n                defer { self.cancellator.deregister(registrationKey) }\n                completion(.init(catching: {\n                    try process.launch()\n                    let processResult = try process.waitUntilExit()\n                    return processResult.exitStatus == .terminated(code: 0)\n                }))\n            }\n        } catch {\n            return completion(.failure(error))\n        }\n    }\n\n    public func cancel(deadline: DispatchTime) throws {\n        try self.cancellator.cancel(deadline: deadline)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Archiver/UniversalArchiver.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// An `Archiver` that handles multiple formats by delegating to other existing archivers each dedicated to its own\n/// format.\npublic struct UniversalArchiver: Archiver {\n    public let supportedExtensions: Set<String>\n\n    /// Errors specific to the implementation of ``UniversalArchiver``.\n    enum Error: Swift.Error {\n        case unknownFormat([String], AbsolutePath)\n        case noFileNameExtension(AbsolutePath)\n\n        var description: String {\n            switch self {\n            case .unknownFormat(let ext, let path):\n                return \"unknown format with extension \\(ext.joined(separator: \".\")) at path `\\(path)`\"\n            case .noFileNameExtension(let path):\n                return \"file at path `\\(path)` has no extension to detect archival format from\"\n            }\n        }\n    }\n\n    /// A dictionary that maps file extension strings to archiver instances that supports these extensions.\n    private let formatMapping: [String: any Archiver]\n\n    public init(_ fileSystem: any FileSystem, _ cancellator: Cancellator? = nil) {\n        var formatMapping = [String: any Archiver]()\n        var supportedExtensions = Set<String>()\n\n        for archiver in [\n            ZipArchiver(fileSystem: fileSystem, cancellator: cancellator),\n            TarArchiver(fileSystem: fileSystem, cancellator: cancellator),\n        ] as [any Archiver] {\n            supportedExtensions.formUnion(archiver.supportedExtensions)\n            for ext in archiver.supportedExtensions {\n                formatMapping[ext] = archiver\n            }\n        }\n\n        self.formatMapping = formatMapping\n        self.supportedExtensions = supportedExtensions\n    }\n\n    private func archiver(for archivePath: AbsolutePath) throws -> any Archiver {\n        guard var extensions = archivePath.allExtensions, extensions.count > 0 else {\n            throw Error.noFileNameExtension(archivePath)\n        }\n\n        // None of the archivers support extensions with more than 2 extension components\n        if extensions.count > 2 {\n            extensions = extensions.suffix(2)\n        }\n\n        if let archiver = self.formatMapping[extensions.joined(separator: \".\")] {\n            return archiver\n        } else if let lastExtension = extensions.last, let archiver = self.formatMapping[lastExtension] {\n            return archiver\n        } else {\n            throw Error.unknownFormat(extensions, archivePath)\n        }\n    }\n\n    public func extract(\n        from archivePath: AbsolutePath,\n        to destinationPath: AbsolutePath,\n        completion: @escaping @Sendable (Result<Void, Swift.Error>) -> Void\n    ) {\n        do {\n            let archiver = try archiver(for: archivePath)\n            archiver.extract(from: archivePath, to: destinationPath, completion: completion)\n        } catch {\n            completion(.failure(error))\n        }\n    }\n\n    public func compress(\n        directory: AbsolutePath,\n        to destinationPath: AbsolutePath\n    ) async throws {\n        let archiver = try archiver(for: destinationPath)\n        try await archiver.compress(directory: directory, to: destinationPath)\n    }\n\n    public func validate(\n        path: AbsolutePath,\n        completion: @escaping @Sendable (Result<Bool, Swift.Error>) -> Void\n    ) {\n        do {\n            let archiver = try archiver(for: path)\n            archiver.validate(path: path, completion: completion)\n        } catch {\n            completion(.failure(error))\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Archiver/ZipArchiver.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Dispatch\nimport struct TSCBasic.FileSystemError\n\n#if os(Windows)\nimport WinSDK\n#endif\n\n/// An `Archiver` that handles ZIP archives using the command-line `zip` and `unzip` tools.\npublic struct ZipArchiver: Archiver, Cancellable {\n    public var supportedExtensions: Set<String> { [\"zip\"] }\n\n    /// The file-system implementation used for various file-system operations and checks.\n    private let fileSystem: FileSystem\n\n    /// Helper for cancelling in-flight requests\n    private let cancellator: Cancellator\n\n    /// Absolute path to the Windows tar in the system folder\n    #if os(Windows)\n        internal let windowsTar: String\n    #else\n        internal let unzip = \"unzip\"\n        internal let zip = \"zip\"\n    #endif\n\n    #if os(FreeBSD)\n        internal let tar = \"tar\"\n    #endif\n\n    /// Creates a `ZipArchiver`.\n    ///\n    /// - Parameters:\n    ///   - fileSystem: The file-system to be used by the `ZipArchiver`.\n    ///   - cancellator: Cancellation handler\n    public init(fileSystem: FileSystem, cancellator: Cancellator? = .none) {\n        self.fileSystem = fileSystem\n        self.cancellator = cancellator ?? Cancellator(observabilityScope: .none)\n\n        #if os(Windows)\n        var tarPath: PWSTR?\n        defer { CoTaskMemFree(tarPath) }\n        let hr = withUnsafePointer(to: FOLDERID_System) { id in\n            SHGetKnownFolderPath(id, DWORD(KF_FLAG_DEFAULT.rawValue), nil, &tarPath)\n        }\n        if hr == S_OK, let tarPath {\n            windowsTar = String(decodingCString: tarPath, as: UTF16.self) + \"\\\\tar.exe\"\n        } else {\n            windowsTar = \"tar.exe\"\n        }\n        #endif\n    }\n\n    public func extract(\n        from archivePath: AbsolutePath,\n        to destinationPath: AbsolutePath,\n        completion: @escaping @Sendable (Result<Void, Error>) -> Void\n    ) {\n        do {\n            guard self.fileSystem.exists(archivePath) else {\n                throw FileSystemError(.noEntry, archivePath.underlying)\n            }\n\n            guard self.fileSystem.isDirectory(destinationPath) else {\n                throw FileSystemError(.notDirectory, destinationPath.underlying)\n            }\n\n            #if os(Windows)\n            // FileManager lost the ability to detect tar.exe as executable.\n            // It's part of system32 anyway so use the absolute path.\n            let process = AsyncProcess(arguments: [windowsTar, \"xf\", archivePath.pathString, \"-C\", destinationPath.pathString])\n            #else\n                let process = AsyncProcess(arguments: [\n                    self.unzip, archivePath.pathString, \"-d\", destinationPath.pathString,\n                ])\n            #endif\n            guard let registrationKey = self.cancellator.register(process) else {\n                throw CancellationError.failedToRegisterProcess(process)\n            }\n\n            DispatchQueue.sharedConcurrent.async {\n                defer { self.cancellator.deregister(registrationKey) }\n                completion(.init(catching: {\n                    try process.launch()\n                    let processResult = try process.waitUntilExit()\n                    guard processResult.exitStatus == .terminated(code: 0) else {\n                        throw try StringError(processResult.utf8stderrOutput())\n                    }\n                }))\n            }\n        } catch {\n            return completion(.failure(error))\n        }\n    }\n\n    public func compress(\n        directory: AbsolutePath,\n        to destinationPath: AbsolutePath\n    ) async throws {\n        guard self.fileSystem.isDirectory(directory) else {\n            throw FileSystemError(.notDirectory, directory.underlying)\n        }\n\n        #if os(Windows)\n        let process = AsyncProcess(\n            // FIXME: are these the right arguments?\n            arguments: [windowsTar, \"-a\", \"-c\", \"-f\", destinationPath.pathString, directory.basename],\n            workingDirectory: directory.parentDirectory\n        )\n        #elseif os(FreeBSD)\n        // On FreeBSD, the unzip command is available in base but not the zip command.\n        // Therefore; we use libarchive(bsdtar) to produce the ZIP archive instead.\n        let process = AsyncProcess(\n                arguments: [\n                    self.tar, \"-c\", \"--format\", \"zip\", \"-f\", destinationPath.pathString,\n                    directory.basename,\n                ],\n          workingDirectory: directory.parentDirectory\n        )\n        #else\n        // This is to work around `swift package-registry publish` tool failing on\n        // Amazon Linux 2 due to it having an earlier Glibc version (rdar://116370323)\n        // and therefore posix_spawn_file_actions_addchdir_np is unavailable.\n        // Instead of passing `workingDirectory` param to TSC.Process, which will trigger\n        // SPM_posix_spawn_file_actions_addchdir_np_supported check, we shell out and\n        // do `cd` explicitly before `zip`.\n        let process = AsyncProcess(\n            arguments: [\n                \"/bin/sh\",\n                \"-c\",\n                    \"cd \\(directory.parentDirectory.underlying.pathString) && \\(self.zip) -ry \\(destinationPath.pathString) \\(directory.basename)\"\n            ]\n        )\n        #endif\n\n        guard let registrationKey = self.cancellator.register(process) else {\n            throw CancellationError.failedToRegisterProcess(process)\n        }\n\n        defer { self.cancellator.deregister(registrationKey) }\n\n        try process.launch()\n        let processResult = try await process.waitUntilExit()\n        guard processResult.exitStatus == .terminated(code: 0) else {\n            throw try StringError(processResult.utf8stderrOutput())\n        }\n    }\n\n    public func validate(path: AbsolutePath, completion: @escaping @Sendable (Result<Bool, Error>) -> Void) {\n        do {\n            guard self.fileSystem.exists(path) else {\n                throw FileSystemError(.noEntry, path.underlying)\n            }\n\n            #if os(Windows)\n            let process = AsyncProcess(arguments: [windowsTar, \"tf\", path.pathString])\n            #else\n                let process = AsyncProcess(arguments: [self.unzip, \"-t\", path.pathString])\n            #endif\n            guard let registrationKey = self.cancellator.register(process) else {\n                throw CancellationError.failedToRegisterProcess(process)\n            }\n\n            DispatchQueue.sharedConcurrent.async {\n                defer { self.cancellator.deregister(registrationKey) }\n                completion(.init(catching: {\n                    try process.launch()\n                    let processResult = try process.waitUntilExit()\n                    return processResult.exitStatus == .terminated(code: 0)\n                }))\n            }\n        } catch {\n            return completion(.failure(error))\n        }\n    }\n\n    public func cancel(deadline: DispatchTime) throws {\n        try self.cancellator.cancel(deadline: deadline)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/ArrayHelpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic func nextItem<T: Equatable>(in array: [T], after item: T) -> T? {\n    for (index, element) in array.enumerated() {\n        if element == item {\n            let nextIndex = index + 1\n            return nextIndex < array.count ? array[nextIndex] : nil\n        }\n    }\n    return nil  // Item not found or it's the last item\n}\n\n/// Determines if an array contains all elements of a subset array in any order.\n/// - Parameters:\n///   - array: The array to search within\n///   - subset: The subset array to check for\n///   - shouldBeContiguous: if `true`, the subset match must be contiguous sequenence\n/// - Returns: `true` if all elements in `subset` are present in `array`, `false` otherwise\npublic func contains<T: Equatable>(array: [T], subset: [T], shouldBeContiguous: Bool = true) -> Bool {\n    if shouldBeContiguous {\n        return containsContiguousSubset(array: array, subset: subset)\n    } else {\n        return containsNonContiguousSubset(array: array, subset: subset)\n    }\n}\n\n/// Determines if an array contains all elements of a subset array in any order.\n/// - Parameters:\n///   - array: The array to search within\n///   - subset: The subset array to check for\n/// - Returns: `true` if all elements in `subset` are present in `array`, `false` otherwise\ninternal func containsNonContiguousSubset<T: Equatable>(array: [T], subset: [T]) -> Bool {\n    for element in subset {\n        if !array.contains(element) {\n            return false\n        }\n    }\n    return true\n}\n\n/// Determines if an array contains a contiguous subsequence matching the subset array.\n/// - Parameters:\n///   - array: The array to search within\n///   - subset: The contiguous subset array to check for\n/// - Returns: `true` if `subset` appears as a contiguous subsequence in `array`, `false` otherwise\ninternal func containsContiguousSubset<T: Equatable>(array: [T], subset: [T]) -> Bool {\n    guard !subset.isEmpty else { return true }\n    guard subset.count <= array.count else { return false }\n\n    for startIndex in 0...(array.count - subset.count) {\n        var matches = true\n        for (offset, element) in subset.enumerated() {\n            if array[startIndex + offset] != element {\n                matches = false\n                break\n            }\n        }\n        if matches {\n            return true\n        }\n    }\n    return false\n}\n"
  },
  {
    "path": "Sources/Basics/AuthorizationProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TSCBasic\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport struct Foundation.URL\n#if canImport(Security)\nimport Security\n#endif\n\npublic protocol AuthorizationProvider: Sendable {\n    func authentication(for url: URL) -> (user: String, password: String)?\n}\n\npublic protocol AuthorizationWriter {\n    func addOrUpdate(\n        for url: URL,\n        user: String,\n        password: String,\n        persist: Bool\n    ) async throws\n\n    func remove(for url: URL) async throws\n}\n\npublic enum AuthorizationProviderError: Error {\n    case invalidURLHost\n    case notFound\n    case other(String)\n}\n\nextension AuthorizationProvider {\n    @Sendable\n    public func httpAuthorizationHeader(for url: URL) -> String? {\n        guard let (user, password) = self.authentication(for: url) else {\n            return nil\n        }\n        let authString = \"\\(user):\\(password)\"\n        let authData = Data(authString.utf8)\n        return \"Basic \\(authData.base64EncodedString())\"\n    }\n}\n\n// MARK: - netrc\n\npublic final class NetrcAuthorizationProvider: AuthorizationProvider, AuthorizationWriter {\n    // marked internal for testing\n    internal let path: AbsolutePath\n    private let fileSystem: FileSystem\n\n    private let cache = ThreadSafeKeyValueStore<String, (user: String, password: String)>()\n\n    public init(path: AbsolutePath, fileSystem: FileSystem) throws {\n        self.path = path\n        self.fileSystem = fileSystem\n        // validate file is okay at the time of initializing the provider\n        _ = try Self.load(fileSystem: fileSystem, path: path)\n    }\n\n    public func addOrUpdate(\n        for url: URL,\n        user: String,\n        password: String,\n        persist: Bool = true\n    ) async throws {\n        guard let machine = Self.machine(for: url) else {\n            throw AuthorizationProviderError.invalidURLHost\n        }\n\n        if !persist {\n            self.cache[machine] = (user, password)\n            return\n        }\n\n        // Same entry already exists, no need to add or update\n        let netrc = try? Self.load(fileSystem: self.fileSystem, path: self.path)\n        guard netrc?.machines\n            .first(where: { $0.name.lowercased() == machine && $0.login == user && $0.password == password }) == nil\n        else {\n            return\n        }\n\n        do {\n            // Append to end of file\n            try self.fileSystem.withLock(on: self.path, type: .exclusive) {\n                let contents = try? self.fileSystem.readFileContents(self.path).contents\n                try self.fileSystem.writeFileContents(self.path) { stream in\n                    // Write existing contents\n                    if let contents, !contents.isEmpty {\n                        stream.write(contents)\n                        stream.write(\"\\n\")\n                    }\n                    stream.write(\"machine \\(machine) login \\(user) password \\(password)\")\n                    stream.write(\"\\n\")\n                }\n            }\n        } catch {\n            throw AuthorizationProviderError\n                .other(\"Failed to update netrc file at \\(self.path): \\(error.interpolationDescription)\")\n        }\n    }\n\n    public func remove(for url: URL) async throws {\n        throw AuthorizationProviderError\n            .other(\"User must edit netrc file at \\(self.path) manually to remove entries\")\n    }\n\n    public func authentication(for url: URL) -> (user: String, password: String)? {\n        if let machine = Self.machine(for: url), let cached = self.cache[machine] {\n            return cached\n        }\n        return self.machine(for: url).map { (user: $0.login, password: $0.password) }\n    }\n\n    private func machine(for url: URL) -> Basics.Netrc.Machine? {\n        // Since updates are appended to the end of the file, we\n        // take the _last_ match to use the most recent entry.\n        if let machine = Self.machine(for: url),\n           let existing = self.machines.last(where: { $0.name.lowercased() == machine })\n        {\n            return existing\n        }\n\n        // No match found. Use the first default if any.\n        if let existing = self.machines.first(where: { $0.isDefault }) {\n            return existing\n        }\n\n        return .none\n    }\n\n    // marked internal for testing\n    internal var machines: [Basics.Netrc.Machine] {\n        // this ignores any errors reading the file\n        // initial validation is done at the time of initializing the provider\n        // and if the file becomes corrupt at runtime it will handle it gracefully\n        let netrc = try? Self.load(fileSystem: self.fileSystem, path: self.path)\n        return netrc?.machines ?? []\n    }\n\n    private static func load(fileSystem: FileSystem, path: AbsolutePath) throws -> Netrc? {\n        do {\n            return try NetrcParser.parse(fileSystem: fileSystem, path: path)\n        } catch NetrcError.fileNotFound, NetrcError.machineNotFound {\n            // These are recoverable errors.\n            return .none\n        }\n    }\n\n    private static func machine(for url: URL) -> String? {\n        guard let host = url.host?.lowercased() else {\n            return nil\n        }\n        return host.isEmpty ? nil : host\n    }\n}\n\n// MARK: - Keychain\n\n#if canImport(Security)\npublic final class KeychainAuthorizationProvider: AuthorizationProvider, AuthorizationWriter {\n    private let observabilityScope: ObservabilityScope\n\n    private let cache = ThreadSafeKeyValueStore<String, (user: String, password: String)>()\n\n    public init(observabilityScope: ObservabilityScope) {\n        self.observabilityScope = observabilityScope\n    }\n\n    public func addOrUpdate(\n        for url: URL,\n        user: String,\n        password: String,\n        persist: Bool = true\n    ) async throws {\n        guard let protocolHostPort = ProtocolHostPort(from: url) else {\n            throw AuthorizationProviderError.invalidURLHost\n        }\n\n        self.observabilityScope\n            .emit(debug: \"add/update credentials for '\\(protocolHostPort)' [\\(url.absoluteString)] in keychain\")\n\n        if !persist {\n            self.cache[protocolHostPort.description] = (user, password)\n            return\n        }\n\n        let passwordData = Data(password.utf8)\n\n        if !(try self.update(protocolHostPort: protocolHostPort, account: user, password: passwordData)) {\n            try self.create(protocolHostPort: protocolHostPort, account: user, password: passwordData)\n        }\n    }\n\n    public func remove(for url: URL) async throws {\n        guard let protocolHostPort = ProtocolHostPort(from: url) else {\n            throw AuthorizationProviderError.invalidURLHost\n        }\n\n        self.observabilityScope\n            .emit(debug: \"remove credentials for '\\(protocolHostPort)' [\\(url.absoluteString)] from keychain\")\n\n        try self.delete(protocolHostPort: protocolHostPort)\n    }\n\n    public func authentication(for url: URL) -> (user: String, password: String)? {\n        guard let protocolHostPort = ProtocolHostPort(from: url) else {\n            return nil\n        }\n\n        if let cached = self.cache[protocolHostPort.description] {\n            return cached\n        }\n\n        self.observabilityScope\n            .emit(debug: \"search credentials for '\\(protocolHostPort)' [\\(url.absoluteString)] in keychain\")\n\n        do {\n            guard let existingItems = try self.search(protocolHostPort: protocolHostPort) as? [[String: Any]] else {\n                throw AuthorizationProviderError\n                    .other(\"Failed to extract credentials for '\\(protocolHostPort)' from keychain\")\n            }\n\n            // Log warning if there is more than one result\n            if existingItems.count > 1 {\n                self.observabilityScope\n                    .emit(\n                        warning: \"multiple (\\(existingItems.count)) keychain entries found for '\\(protocolHostPort)' [\\(url.absoluteString)]\"\n                    )\n            }\n\n            // Sort by modification timestamp\n            let sortedItems = existingItems.sorted {\n                switch (\n                    $0[kSecAttrModificationDate as String] as? Date,\n                    $1[kSecAttrModificationDate as String] as? Date\n                ) {\n                case (nil, nil):\n                    return false\n                case (_, nil):\n                    return true\n                case (nil, _):\n                    return false\n                case (.some(let left), .some(let right)):\n                    return left < right\n                }\n            }\n\n            // Return most recently modified item\n            guard let mostRecent = sortedItems.last,\n                  let created = mostRecent[kSecAttrCreationDate as String] as? Date,\n                  // Get password for this specific item\n                  let existingItem = try self.get(\n                      protocolHostPort: protocolHostPort,\n                      created: created,\n                      modified: mostRecent[kSecAttrModificationDate as String] as? Date\n                  ) as? [String: Any],\n                  let passwordData = existingItem[kSecValueData as String] as? Data,\n                  let account = existingItem[kSecAttrAccount as String] as? String\n            else {\n                throw AuthorizationProviderError\n                    .other(\"Failed to extract credentials for '\\(protocolHostPort)' from keychain\")\n            }\n          \n            let password = String(decoding: passwordData, as: UTF8.self)\n\n            return (user: account, password: password)\n        } catch {\n            switch error {\n            case AuthorizationProviderError.notFound:\n                self.observabilityScope.emit(debug: \"no credentials found for '\\(protocolHostPort)' in keychain\")\n            case AuthorizationProviderError.other(let detail):\n                self.observabilityScope.emit(error: detail)\n            default:\n                self.observabilityScope.emit(\n                    error: \"failed to find credentials for '\\(protocolHostPort)' in keychain\",\n                    underlyingError: error\n                )\n            }\n            return nil\n        }\n    }\n\n    private func create(protocolHostPort: ProtocolHostPort, account: String, password: Data) throws {\n        var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,\n                                    kSecAttrProtocol as String: protocolHostPort.protocolCFString,\n                                    kSecAttrServer as String: protocolHostPort.server,\n                                    kSecAttrAccount as String: account,\n                                    kSecValueData as String: password]\n\n        if let port = protocolHostPort.port {\n            query[kSecAttrPort as String] = port\n        }\n\n        let status = SecItemAdd(query as CFDictionary, nil)\n        guard status == errSecSuccess else {\n            throw AuthorizationProviderError\n                .other(\"Failed to save credentials for '\\(protocolHostPort)' to keychain: status \\(status)\")\n        }\n    }\n\n    private func update(protocolHostPort: ProtocolHostPort, account: String, password: Data) throws -> Bool {\n        var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,\n                                    kSecAttrProtocol as String: protocolHostPort.protocolCFString,\n                                    kSecAttrServer as String: protocolHostPort.server]\n\n        if let port = protocolHostPort.port {\n            query[kSecAttrPort as String] = port\n        }\n\n        let attributes: [String: Any] = [kSecAttrAccount as String: account,\n                                         kSecValueData as String: password]\n\n        let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)\n        guard status != errSecItemNotFound else {\n            return false\n        }\n        guard status == errSecSuccess else {\n            throw AuthorizationProviderError\n                .other(\"Failed to update credentials for '\\(protocolHostPort)' in keychain: status \\(status)\")\n        }\n        return true\n    }\n\n    private func delete(protocolHostPort: ProtocolHostPort) throws {\n        var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,\n                                    kSecAttrProtocol as String: protocolHostPort.protocolCFString,\n                                    kSecAttrServer as String: protocolHostPort.server]\n\n        if let port = protocolHostPort.port {\n            query[kSecAttrPort as String] = port\n        }\n\n        let status = SecItemDelete(query as CFDictionary)\n        guard status == errSecSuccess else {\n            throw AuthorizationProviderError\n                .other(\"Failed to delete credentials for '\\(protocolHostPort)' from keychain: status \\(status)\")\n        }\n    }\n\n    private func search(protocolHostPort: ProtocolHostPort) throws -> CFTypeRef? {\n        var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,\n                                    kSecAttrProtocol as String: protocolHostPort.protocolCFString,\n                                    kSecAttrServer as String: protocolHostPort.server,\n                                    kSecMatchLimit as String: kSecMatchLimitAll, // returns all matches\n                                    kSecReturnAttributes as String: true]\n        // https://developer.apple.com/documentation/security/keychain_services/keychain_items/searching_for_keychain_items\n        // Can't combine `kSecMatchLimitAll` and `kSecReturnData` (which contains password)\n\n        if let port = protocolHostPort.port {\n            query[kSecAttrPort as String] = port\n        }\n\n        var items: CFTypeRef?\n        // Search keychain for server's username and password, if any.\n        let status = SecItemCopyMatching(query as CFDictionary, &items)\n        guard status != errSecItemNotFound else {\n            throw AuthorizationProviderError.notFound\n        }\n        guard status == errSecSuccess else {\n            throw AuthorizationProviderError\n                .other(\"Failed to find credentials for '\\(protocolHostPort)' in keychain: status \\(status)\")\n        }\n\n        return items\n    }\n\n    private func get(protocolHostPort: ProtocolHostPort, created: Date, modified: Date?) throws -> CFTypeRef? {\n        self.observabilityScope\n            .emit(debug: \"read credentials for '\\(protocolHostPort)', created at \\(created), in keychain\")\n\n        var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,\n                                    kSecAttrProtocol as String: protocolHostPort.protocolCFString,\n                                    kSecAttrServer as String: protocolHostPort.server,\n                                    kSecAttrCreationDate as String: created,\n                                    kSecMatchLimit as String: kSecMatchLimitOne, // limit to one match\n                                    kSecReturnAttributes as String: true,\n                                    kSecReturnData as String: true] // password\n\n        if let port = protocolHostPort.port {\n            query[kSecAttrPort as String] = port\n        }\n        if let modified {\n            query[kSecAttrModificationDate as String] = modified\n        }\n\n        var item: CFTypeRef?\n        // Search keychain for server's username and password, if any.\n        let status = SecItemCopyMatching(query as CFDictionary, &item)\n        guard status != errSecItemNotFound else {\n            throw AuthorizationProviderError.notFound\n        }\n        guard status == errSecSuccess else {\n            throw AuthorizationProviderError\n                .other(\"Failed to find credentials for '\\(protocolHostPort)' in keychain: status \\(status)\")\n        }\n\n        return item\n    }\n\n    struct ProtocolHostPort: Hashable, CustomStringConvertible {\n        let `protocol`: String?\n        let host: String\n        let port: Int?\n\n        var server: String {\n            self.host\n        }\n\n        var protocolCFString: CFString {\n            // See\n            // https://developer.apple.com/documentation/security/keychain_services/keychain_items/item_attribute_keys_and_values?language=swift\n            // for a list of possible values for the `kSecAttrProtocol` attribute.\n            switch self.protocol {\n            case \"https\":\n                return kSecAttrProtocolHTTPS\n            case \"http\":\n                return kSecAttrProtocolHTTP\n            default:\n                return kSecAttrProtocolHTTPS\n            }\n        }\n\n        init?(from url: URL) {\n            guard let host = url.host?.lowercased(), !host.isEmpty else {\n                return nil\n            }\n\n            self.protocol = url.scheme?.lowercased()\n            self.host = host\n            self.port = url.port\n        }\n\n        var description: String {\n            \"\\(self.protocol.map { \"\\($0)://\" } ?? \"\")\\(self.host)\\(self.port.map { \":\\($0)\" } ?? \"\")\"\n        }\n    }\n}\n#endif\n\n// MARK: - Composite\n\npublic struct CompositeAuthorizationProvider: AuthorizationProvider {\n    // marked internal for testing\n    internal let providers: [AuthorizationProvider]\n    private let observabilityScope: ObservabilityScope\n\n    public init(_ providers: AuthorizationProvider..., observabilityScope: ObservabilityScope) {\n        self.init(providers, observabilityScope: observabilityScope)\n    }\n\n    public init(_ providers: [AuthorizationProvider], observabilityScope: ObservabilityScope) {\n        self.providers = providers\n        self.observabilityScope = observabilityScope\n    }\n\n    public func authentication(for url: URL) -> (user: String, password: String)? {\n        for provider in self.providers {\n            if let authentication = provider.authentication(for: url) {\n                switch provider {\n                case let provider as NetrcAuthorizationProvider:\n                    self.observabilityScope.emit(info: \"credentials for \\(url) found in netrc file at \\(provider.path)\")\n                #if canImport(Security)\n                case is KeychainAuthorizationProvider:\n                    self.observabilityScope.emit(info: \"credentials for \\(url) found in keychain\")\n                #endif\n                default:\n                    self.observabilityScope.emit(info: \"credentials for \\(url) found in \\(provider)\")\n                }\n                return authentication\n            }\n        }\n        return nil\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(Basics\n  Archiver/Archiver.swift\n  Archiver/TarArchiver.swift\n  Archiver/ZipArchiver.swift\n  Archiver/UniversalArchiver.swift\n  AuthorizationProvider.swift\n  Cancellator.swift\n  Collections/ByteString+Extensions.swift\n  Collections/Dictionary+Extensions.swift\n  Collections/IdentifiableSet.swift\n  Collections/String+Extensions.swift\n  Concurrency/AsyncProcess.swift\n  Concurrency/ConcurrencyHelpers.swift\n  Concurrency/NSLock+Extensions.swift\n  Concurrency/SendableBox.swift\n  Concurrency/ThreadSafeArrayStore.swift\n  Concurrency/ThreadSafeBox.swift\n  Concurrency/ThreadSafeKeyValueStore.swift\n  Concurrency/ThrowingDefer.swift\n  Concurrency/TokenBucket.swift\n  DispatchTimeInterval+Extensions.swift\n  Environment/Environment.swift\n  Environment/EnvironmentKey.swift\n  Environment/EnvironmentShims.swift\n  Errors.swift\n  FileSystem/AbsolutePath.swift\n  FileSystem/CommonParentDirectory.swift\n  FileSystem/FileSystem+Extensions.swift\n  FileSystem/InMemoryFileSystem.swift\n  FileSystem/NativePathExtensions.swift\n  FileSystem/RelativePath.swift\n  FileSystem/TemporaryFile.swift\n  FileSystem/TSCAdapters.swift\n  FileSystem/VirtualFileSystem.swift\n  FileSystem/VFSOverlay.swift\n  Graph/AdjacencyMatrix.swift\n  Graph/DirectedGraph.swift\n  Graph/GraphAlgorithms.swift\n  Graph/UndirectedGraph.swift\n  SourceControlURL.swift\n  HTTPClient/HTTPClient.swift\n  HTTPClient/HTTPClientConfiguration.swift\n  HTTPClient/HTTPClientError.swift\n  HTTPClient/HTTPClientHeaders.swift\n  HTTPClient/HTTPClientRequest.swift\n  HTTPClient/HTTPClientResponse.swift\n  HTTPClient/HTTPMethod.swift\n  HTTPClient/LegacyHTTPClient.swift\n  HTTPClient/LegacyHTTPClientRequest.swift\n  HTTPClient/URLSessionHTTPClient.swift\n  ImportScanning.swift\n  JSON+Extensions.swift\n  JSONDecoder+Extensions.swift\n  Netrc.swift\n  Observability.swift\n  OSSignpost.swift\n  Process.swift\n  ProgressAnimation/NinjaProgressAnimation.swift\n  ProgressAnimation/PercentProgressAnimation.swift\n  ProgressAnimation/ProgressAnimationProtocol.swift\n  ProgressAnimation/SingleLinePercentProgressAnimation.swift\n  ProgressAnimation/ThrottledProgressAnimation.swift\n  SQLite.swift\n  Sandbox.swift\n  SendableTimeInterval.swift\n  Serialization/SerializedJSON.swift\n  SwiftVersion.swift\n  SQLiteBackedCache.swift\n  TestingLibrary.swift\n  Triple+Basics.swift\n  URL.swift\n  Version+Extensions.swift\n  WritableByteStream+Extensions.swift\n  Vendor/Triple.swift\n  Vendor/Triple+Platforms.swift)\ntarget_link_libraries(Basics PUBLIC\n  _AsyncFileSystem\n  SwiftCollections::OrderedCollections\n  TSCBasic\n  TSCUtility)\ntarget_link_libraries(Basics PRIVATE\n  SwiftCollections::DequeModule\n  SPMSQLite3\n  TSCclibc)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(Basics PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\ntarget_link_options(Basics PRIVATE\n    \"$<$<PLATFORM_ID:Darwin>:SHELL:-Xlinker -framework -Xlinker Security>\")\n\ninstall(TARGETS Basics\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS Basics)\n"
  },
  {
    "path": "Sources/Basics/Cancellator.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Dispatch\nimport Foundation\nimport class TSCBasic.Thread\n#if canImport(WinSDK)\nimport WinSDK\n#elseif canImport(Android)\nimport Android\n#endif\n\npublic typealias CancellationHandler = @Sendable (DispatchTime) async throws -> Void\n\npublic final class Cancellator: Cancellable, Sendable {\n    public typealias RegistrationKey = String\n\n    private let observabilityScope: ObservabilityScope?\n    private let registry = ThreadSafeKeyValueStore<String, (name: String, handler: CancellationHandler)>()\n    private let cancelling = ThreadSafeBox<Bool>(false)\n\n    private static let signalHandlerLock = NSLock()\n    private static var isSignalHandlerInstalled = false\n\n    public init(observabilityScope: ObservabilityScope?) {\n        self.observabilityScope = observabilityScope\n    }\n\n    #if os(Windows)\n    // unfortunately this is needed for C callback handlers used by Windows shutdown handler\n    static var shared: Cancellator?\n    #endif\n\n    /// Installs signal handlers to terminate sub-processes on cancellation.\n    public func installSignalHandlers() {\n        Self.signalHandlerLock.withLock {\n            precondition(!Self.isSignalHandlerInstalled)\n\n            #if os(Windows)\n            // Closures passed to `SetConsoleCtrlHandler` can't capture context, working around that with a global.\n            Self.shared = self\n\n            // set shutdown handler to terminate sub-processes, etc\n            _ = SetConsoleCtrlHandler({ _ in\n                // Terminate all processes on receiving an interrupt signal.\n                try? Cancellator.shared?.cancel(deadline: .now() + .seconds(30))\n\n                // Reset the handler.\n                _ = SetConsoleCtrlHandler(nil, false)\n\n                // Exit as if by signal()\n                TerminateProcess(GetCurrentProcess(), 3)\n\n                return true\n            }, true)\n            #else\n            // trap SIGINT to terminate sub-processes, etc\n            signal(SIGINT, SIG_IGN)\n            let interruptSignalSource = DispatchSource.makeSignalSource(signal: SIGINT)\n            interruptSignalSource.setEventHandler { [weak self] in\n                // cancel the trap?\n                interruptSignalSource.cancel()\n\n                // Terminate all processes on receiving an interrupt signal.\n                try? self?.cancel(deadline: .now() + .seconds(30))\n\n                // Install the default signal handler.\n                var action = sigaction()\n                #if canImport(Darwin) || os(OpenBSD) || os(FreeBSD)\n                action.__sigaction_u.__sa_handler = SIG_DFL\n                #elseif canImport(Musl)\n                action.__sa_handler.sa_handler = SIG_DFL\n                #elseif os(Android)\n                action.sa_handler = SIG_DFL\n                #else\n                action.__sigaction_handler = unsafeBitCast(\n                    SIG_DFL,\n                    to: sigaction.__Unnamed_union___sigaction_handler.self\n                )\n                #endif\n                sigaction(SIGINT, &action, nil)\n                kill(getpid(), SIGINT)              // ignore-unacceptable-language\n            }\n            interruptSignalSource.resume()\n            #endif\n\n            Self.isSignalHandlerInstalled = true\n        }\n    }\n\n    @discardableResult\n    public func register(name: String, handler: @escaping CancellationHandler) -> RegistrationKey? {\n        if self.cancelling.get() {\n            self.observabilityScope?.emit(debug: \"not registering '\\(name)' with terminator, termination in progress\")\n            return .none\n        }\n        let key = UUID().uuidString\n        self.observabilityScope?.emit(debug: \"registering '\\(name)' with terminator\")\n        self.registry[key] = (name: name, handler: handler)\n        return key\n    }\n\n    @discardableResult\n    public func register(name: String, handler: Cancellable) -> RegistrationKey? {\n        self.register(name: name, handler: handler.cancel(deadline:))\n    }\n\n    @discardableResult\n    public func register(name: String, handler: AsyncCancellable) -> RegistrationKey? {\n        self.register(name: name, handler: handler.cancel(deadline:))\n    }\n\n    @discardableResult\n    public func register(name: String, handler: @escaping @Sendable () throws -> Void) -> RegistrationKey? {\n        self.register(name: name, handler: { _ in try handler() })\n    }\n\n    package func register(_ process: AsyncProcess) -> RegistrationKey? {\n        self.register(name: \"\\(process.arguments.joined(separator: \" \"))\", handler: process.terminate)\n    }\n\n    #if !canImport(Darwin) || os(macOS)\n    public func register(_ process: Foundation.Process) -> RegistrationKey? {\n        self.register(name: \"\\(process.description)\", handler: process.terminate(timeout:))\n    }\n    #endif\n\n    public func deregister(_ key: RegistrationKey) {\n        self.registry[key] = nil\n    }\n\n    public func cancel(deadline: DispatchTime) throws {\n        self._cancel(deadline: deadline)\n    }\n\n    // marked internal for testing\n    @discardableResult\n    internal func _cancel(deadline: DispatchTime? = .none) -> Int {\n        self.cancelling.put(true)\n\n        self.observabilityScope?\n            .emit(info: \"starting cancellation cycle with \\(self.registry.count) cancellation handlers registered\")\n\n        let deadline = deadline ?? .now() + .seconds(30)\n        // deadline for individual handlers set slightly before overall deadline\n        let delta: DispatchTimeInterval = .nanoseconds(abs(deadline.distance(to: .now()).nanoseconds() ?? 0) / 5)\n        let handlersDeadline = deadline - delta\n\n        let cancellationHandlers = self.registry.get()\n        let cancelled = ThreadSafeArrayStore<String>()\n        let group = DispatchGroup()\n        for (_, (name, handler)) in cancellationHandlers {\n            group.enter()\n            Task {\n                defer { group.leave() }\n                do {\n                    self.observabilityScope?.emit(debug: \"cancelling '\\(name)'\")\n                    try await handler(handlersDeadline)\n                    cancelled.append(name)\n                } catch {\n                    self.observabilityScope?.emit(\n                        warning: \"failed cancelling '\\(name)'\",\n                        underlyingError: error\n                    )\n                }\n            }\n        }\n\n        if case .timedOut = group.wait(timeout: deadline) {\n            self.observabilityScope?\n                .emit(\n                    warning: \"timeout waiting for cancellation with \\(cancellationHandlers.count - cancelled.count) cancellation handlers remaining\"\n                )\n        } else {\n            self.observabilityScope?.emit(info: \"cancellation cycle completed successfully\")\n        }\n\n        self.cancelling.put(false)\n\n        return cancelled.count\n    }\n}\n\npublic protocol Cancellable {\n    func cancel(deadline: DispatchTime) throws -> Void\n}\n\npublic protocol AsyncCancellable {\n    func cancel(deadline: DispatchTime) async throws -> Void\n}\n\npublic struct CancellationError: Error, CustomStringConvertible {\n    public let description: String\n\n    public init() {\n        self.init(description: \"Operation cancelled\")\n    }\n\n    private init(description: String) {\n        self.description = description\n    }\n\n    static func failedToRegisterProcess(_ process: AsyncProcess) -> Self {\n        Self(\n            description: \"\"\"\n            failed to register a cancellation handler for this process invocation `\\(\n                process.arguments.joined(separator: \" \")\n            )`\n            \"\"\"\n        )\n    }\n}\n\nextension AsyncProcess {\n    fileprivate func terminate(timeout: DispatchTime) {\n        // send graceful shutdown signal\n        self.signal(SIGINT)\n\n        // start a thread to see if we need to terminate more forcibly\n        let forceKillSemaphore = DispatchSemaphore(value: 0)\n        let forceKillThread = TSCBasic.Thread {\n            if case .timedOut = forceKillSemaphore.wait(timeout: timeout) {\n                // send a force-kill signal         // ignore-unacceptable-language\n                #if os(Windows)\n                self.signal(SIGTERM)\n                #else\n                self.signal(SIGKILL)\n                #endif\n            }\n        }\n        forceKillThread.start()\n        _ = try? self.waitUntilExit()\n        forceKillSemaphore.signal() // let the force-kill thread know we do not need it any more    //ignore-unacceptable-language\n        // join the force-kill thread thread so we don't exit before everything terminates          //ignore-unacceptable-language\n        forceKillThread.join()\n    }\n}\n\n#if !canImport(Darwin) || os(macOS)\nextension Foundation.Process {\n    fileprivate func terminate(timeout: DispatchTime) {\n        guard self.isRunning else {\n            return\n        }\n\n        // send graceful shutdown signal (SIGINT)\n        self.interrupt()\n\n        // start a thread to see if we need to terminate more forcibly\n        let forceKillSemaphore = DispatchSemaphore(value: 0)\n        let forceKillThread = TSCBasic.Thread {\n            if case .timedOut = forceKillSemaphore.wait(timeout: timeout) {\n                guard self.isRunning else {\n                    return\n                }\n\n                // force kill (SIGTERM)         // ignore-unacceptable-language\n                self.terminate()\n            }\n        }\n        forceKillThread.start()\n        self.waitUntilExit()\n        forceKillSemaphore.signal() // let the force-kill thread know we do not need it any more    //ignore-unacceptable-language\n        // join the force-kill thread thread so we don't exit before everything terminates          //ignore-unacceptable-language\n        forceKillThread.join()\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Basics/Collections/ByteString+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.SHA256\n\nextension ByteString {\n    /// A lowercase, hexadecimal representation of the SHA256 hash\n    /// generated for the byte string's contents.\n    ///\n    /// This property uses the CryptoKit implementation of\n    /// Secure Hashing Algorithm 2 (SHA-2) hashing with a 256-bit digest, when available,\n    /// falling back on a native implementation in Swift provided by TSCBasic.\n    public var sha256Checksum: String {\n        SHA256().hash(self).hexadecimalRepresentation\n    }\n\n    public init(json: SerializedJSON) {\n        self.init(json.underlying.utf8)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Collections/Dictionary+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TSCBasic\n\nextension Dictionary {\n    @inlinable\n    @discardableResult\n    public mutating func memoize(key: Key, body: () throws -> Value) rethrows -> Value {\n        if let value = self[key] {\n            return value\n        }\n        let value = try body()\n        self[key] = value\n        return value\n    }\n}\n\nextension Dictionary {\n    public init<S>(throwingUniqueKeysWithValues keysAndValues: S) throws where S: Sequence, S.Element == (Key, Value) {\n        self.init()\n        for pair in keysAndValues {\n            guard !self.keys.contains(pair.0) else {\n                throw StringError(\"duplicate key found: '\\(pair.0)'\")\n            }\n            self[pair.0] = pair.1\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Collections/IdentifiableSet.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct OrderedCollections.OrderedDictionary\n\n/// Replacement for `Set` elements that can't be `Hashable`, but can be `Identifiable`.\npublic struct IdentifiableSet<Element: Identifiable>: Collection {\n    public init() {\n        self.storage = [:]\n    }\n\n    public init(_ sequence: some Sequence<Element>) {\n        self.storage = .init(pickLastWhenDuplicateFound: sequence)\n    }\n\n    fileprivate typealias Storage = OrderedDictionary<Element.ID, Element>\n\n    public struct Index: Comparable {\n        public static func < (lhs: IdentifiableSet<Element>.Index, rhs: IdentifiableSet<Element>.Index) -> Bool {\n            lhs.storageIndex < rhs.storageIndex\n        }\n\n        fileprivate let storageIndex: Storage.Index\n    }\n\n    private var storage: Storage\n\n    public var startIndex: Index {\n        Index(storageIndex: self.storage.elements.startIndex)\n    }\n\n    public var endIndex: Index {\n        Index(storageIndex: self.storage.elements.endIndex)\n    }\n\n    public var values: some Sequence<Element> {\n        self.storage.values\n    }\n\n    public subscript(position: Index) -> Element {\n        self.storage.elements[position.storageIndex].value\n    }\n\n    public subscript(id: Element.ID) -> Element? {\n        get {\n            self.storage[id]\n        }\n        set {\n            self.storage[id] = newValue\n        }\n    }\n\n    public func index(after i: Index) -> Index {\n        Index(storageIndex: self.storage.elements.index(after: i.storageIndex))\n    }\n\n    public mutating func insert(_ element: Element) {\n        self.storage[element.id] = element\n    }\n\n    public func union(_ otherSequence: some Sequence<Element>) -> Self {\n        var result = self\n        for element in otherSequence {\n            result.storage[element.id] = element\n        }\n        return result\n    }\n\n    public mutating func formUnion(_ otherSequence: some Sequence<Element>) {\n        for element in otherSequence {\n            self.storage[element.id] = element\n        }\n    }\n\n    public func intersection(_ otherSequence: some Sequence<Element>) -> Self {\n        let keysToRemove = Set(self.storage.keys).subtracting(otherSequence.map(\\.id))\n        var result = self\n        for key in keysToRemove {\n            result.storage.removeValue(forKey: key)\n        }\n        return result\n    }\n\n    public func subtracting(_ otherSequence: some Sequence<Element>) -> Self {\n        var result = self\n        for element in otherSequence {\n            result.storage.removeValue(forKey: element.id)\n        }\n        return result\n    }\n\n    public func contains(id: Element.ID) -> Bool {\n        self.storage.keys.contains(id)\n    }\n\n    public mutating func remove(id: Element.ID) -> Element? {\n        self.storage.removeValue(forKey: id)\n    }\n\n    public mutating func remove(_ member: Element) -> Element? {\n        self.storage.removeValue(forKey: member.id)\n    }\n}\n\nextension OrderedDictionary where Value: Identifiable, Key == Value.ID {\n    fileprivate init(pickLastWhenDuplicateFound sequence: some Sequence<Value>) {\n        self.init(sequence.map { ($0.id, $0) }, uniquingKeysWith: { $1 })\n    }\n}\n\nextension IdentifiableSet: Equatable {\n    public static func == (_ lhs: Self, _ rhs: Self) -> Bool {\n        lhs.storage.keys == rhs.storage.keys\n    }\n}\n\nextension IdentifiableSet: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        for key in self.storage.keys {\n            hasher.combine(key)\n        }\n    }\n}\n\nextension IdentifiableSet: ExpressibleByArrayLiteral {\n    public init(arrayLiteral elements: Element...) {\n        self.init(elements)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Collections/String+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCBasic.SHA256\n\nextension String {\n    /// generated for the byte string's contents.\n    ///\n    /// This property uses the CryptoKit implementation of\n    /// Secure Hashing Algorithm 2 (SHA-2) hashing with a 256-bit digest, when available,\n    /// falling back on a native implementation in Swift provided by TSCBasic.\n    public var sha256Checksum: String {\n        SHA256().hash(self).hexadecimalRepresentation\n    }\n\n    /// Drops the given suffix from the string, if present.\n    public func spm_dropPrefix(_ prefix: String) -> String {\n        if self.hasPrefix(prefix) {\n            return String(self.dropFirst(prefix.count))\n        }\n        return self\n    }\n\n    public var isValidIdentifier: Bool {\n        guard !isEmpty else { return false }\n        return allSatisfy { $0.isLetter || $0.isNumber || $0 == \"_\" }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Concurrency/AsyncProcess.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Dispatch\nimport Foundation\n\n#if os(Windows)\nimport TSCLibc\n#elseif canImport(Android)\nimport Android\n#endif\n\n#if !os(Windows) && !canImport(Darwin)\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly\nimport func TSCclibc.SPM_posix_spawn_file_actions_addchdir_np_supported\n\n@_implementationOnly\nimport func TSCclibc.SPM_posix_spawn_file_actions_addchdir_np\n#else\nprivate import func TSCclibc.SPM_posix_spawn_file_actions_addchdir_np_supported\nprivate import func TSCclibc.SPM_posix_spawn_file_actions_addchdir_np\n#endif // #if USE_IMPL_ONLY_IMPORTS\n#endif\n\nimport class TSCBasic.CStringArray\nimport class TSCBasic.LocalFileOutputByteStream\nimport enum TSCBasic.SystemError\nimport class TSCBasic.Thread\nimport protocol TSCBasic.WritableByteStream\n\n/// Process result data which is available after process termination.\npackage struct AsyncProcessResult: CustomStringConvertible, Sendable {\n    package enum Error: Swift.Error, Sendable {\n        /// The output is not a valid UTF8 sequence.\n        case illegalUTF8Sequence\n\n        /// The process had a non zero exit.\n        case nonZeroExit(AsyncProcessResult)\n\n        /// The process failed with a `SystemError` (this is used to still provide context on the process that was\n        /// launched).\n        case systemError(arguments: [String], underlyingError: Swift.Error)\n    }\n\n    package enum ExitStatus: Equatable, Sendable {\n        /// The process was terminated normally with a exit code.\n        case terminated(code: Int32)\n        #if os(Windows)\n        /// The process was terminated abnormally.\n        case abnormal(exception: UInt32)\n        #else\n        /// The process was terminated due to a signal.\n        case signalled(signal: Int32)\n        #endif\n    }\n\n    /// The arguments with which the process was launched.\n    package let arguments: [String]\n\n    /// The environment with which the process was launched.\n    package let environment: Environment\n\n    /// The exit status of the process.\n    package let exitStatus: ExitStatus\n\n    /// The output bytes of the process. Available only if the process was\n    /// asked to redirect its output and no stdout output closure was set.\n    package let output: Result<[UInt8], Swift.Error>\n\n    /// The output bytes of the process. Available only if the process was\n    /// asked to redirect its output and no stderr output closure was set.\n    package let stderrOutput: Result<[UInt8], Swift.Error>\n\n    /// Create an instance using a POSIX process exit status code and output result.\n    ///\n    /// See `waitpid(2)` for information on the exit status code.\n    package init(\n        arguments: [String],\n        environment: Environment,\n        exitStatusCode: Int32,\n        normal: Bool,\n        output: Result<[UInt8], Swift.Error>,\n        stderrOutput: Result<[UInt8], Swift.Error>\n    ) {\n        let exitStatus: ExitStatus\n        #if os(Windows)\n        if normal {\n            exitStatus = .terminated(code: exitStatusCode)\n        } else {\n            exitStatus = .abnormal(exception: UInt32(exitStatusCode))\n        }\n        #else\n        if WIFSIGNALED(exitStatusCode) {\n            exitStatus = .signalled(signal: WTERMSIG(exitStatusCode))\n        } else {\n            precondition(WIFEXITED(exitStatusCode), \"unexpected exit status \\(exitStatusCode)\")\n            exitStatus = .terminated(code: WEXITSTATUS(exitStatusCode))\n        }\n        #endif\n        self.init(\n            arguments: arguments,\n            environment: environment,\n            exitStatus: exitStatus,\n            output: output,\n            stderrOutput: stderrOutput\n        )\n    }\n\n    /// Create an instance using an exit status and output result.\n    package init(\n        arguments: [String],\n        environment: Environment,\n        exitStatus: ExitStatus,\n        output: Result<[UInt8], Swift.Error>,\n        stderrOutput: Result<[UInt8], Swift.Error>\n    ) {\n        self.arguments = arguments\n        self.environment = environment\n        self.output = output\n        self.stderrOutput = stderrOutput\n        self.exitStatus = exitStatus\n    }\n\n    /// Converts stdout output bytes to string, assuming they're UTF8.\n    package func utf8Output() throws -> String {\n        try String(decoding: output.get(), as: Unicode.UTF8.self)\n    }\n\n    /// Converts stderr output bytes to string, assuming they're UTF8.\n    package func utf8stderrOutput() throws -> String {\n        try String(decoding: stderrOutput.get(), as: Unicode.UTF8.self)\n    }\n\n    package var description: String {\n        \"\"\"\n        <AsyncProcessResult: exit: \\(exitStatus), output:\n         \\((try? utf8Output()) ?? \"\")\n        >\n        \"\"\"\n    }\n}\n\nextension AsyncProcess: @unchecked Sendable {}\n\nextension DispatchQueue {\n    // a shared concurrent queue for running concurrent asynchronous operations\n    static let processConcurrent = DispatchQueue(\n        label: \"swift.org.swift-tsc.process.concurrent\",\n        attributes: .concurrent\n    )\n}\n\n/// Process allows spawning new subprocesses and working with them.\n///\n/// Note: This class is thread safe.\npackage final class AsyncProcess {\n    /// Errors when attempting to invoke a process\n    package enum Error: Swift.Error, Sendable {\n        /// The program requested to be executed cannot be found on the existing search paths, or is not executable.\n        case missingExecutableProgram(program: String)\n\n        /// The current OS does not support the workingDirectory API.\n        case workingDirectoryNotSupported\n\n        /// The stdin could not be opened.\n        case stdinUnavailable\n    }\n\n    package typealias ReadableStream = AsyncStream<[UInt8]>\n\n    package enum OutputRedirection: Sendable {\n        /// Do not redirect the output\n        case none\n\n        /// Collect stdout and stderr output and provide it back via ``AsyncProcessResult`` object. If\n        /// `redirectStderr` is `true`, `stderr` be redirected to `stdout`.\n        case collect(redirectStderr: Bool)\n\n        /// Stream `stdout` and `stderr` via the corresponding closures. If `redirectStderr` is `true`, `stderr` will\n        /// be redirected to `stdout`.\n        case stream(stdout: OutputClosure, stderr: OutputClosure, redirectStderr: Bool)\n\n        /// Stream stdout and stderr as `AsyncSequence` provided as an argument to closures passed to\n        /// ``AsyncProcess/launch(stdoutStream:stderrStream:)``.\n        case asyncStream(\n            stdoutStream: ReadableStream,\n            stdoutContinuation: ReadableStream.Continuation,\n            stderrStream: ReadableStream,\n            stderrContinuation: ReadableStream.Continuation\n        )\n\n        /// Default collect OutputRedirection that defaults to not redirect stderr. Provided for API compatibility.\n        package static let collect: Self = .collect(redirectStderr: false)\n\n        /// Default stream OutputRedirection that defaults to not redirect stderr. Provided for API compatibility.\n        package static func stream(stdout: @escaping OutputClosure, stderr: @escaping OutputClosure) -> Self {\n            .stream(stdout: stdout, stderr: stderr, redirectStderr: false)\n        }\n\n        package var redirectsOutput: Bool {\n            switch self {\n            case .none:\n                false\n            case .collect, .stream, .asyncStream:\n                true\n            }\n        }\n\n        package var outputClosures: (stdoutClosure: OutputClosure, stderrClosure: OutputClosure)? {\n            switch self {\n            case let .stream(stdoutClosure, stderrClosure, _):\n                (stdoutClosure: stdoutClosure, stderrClosure: stderrClosure)\n\n            case let .asyncStream(_, stdoutContinuation, _, stderrContinuation):\n                (stdoutClosure: { stdoutContinuation.yield($0) }, stderrClosure: { stderrContinuation.yield($0) })\n\n            case .collect, .none:\n                nil\n            }\n        }\n\n        package var redirectStderr: Bool {\n            switch self {\n            case .collect(let redirectStderr):\n                redirectStderr\n            case .stream(_, _, let redirectStderr):\n                redirectStderr\n            default:\n                false\n            }\n        }\n    }\n\n    // process execution mutable state\n    private enum State {\n        case idle\n        case readingOutput(sync: DispatchGroup)\n        case outputReady(stdout: Result<[UInt8], Swift.Error>, stderr: Result<[UInt8], Swift.Error>)\n        case complete(AsyncProcessResult)\n        case failed(Swift.Error)\n    }\n\n    /// Typealias for process id type.\n    #if !os(Windows)\n    package typealias ProcessID = pid_t\n    #else\n    package typealias ProcessID = DWORD\n    #endif\n\n    /// Typealias for stdout/stderr output closure.\n    package typealias OutputClosure = @Sendable ([UInt8]) -> Void\n\n    /// Typealias for logging handling closure.\n    package typealias LoggingHandler = @Sendable (String) -> Void\n\n    /// Global logging handler storage.\n    private static let _loggingHandler = ThreadSafeBox<LoggingHandler?>()\n\n    /// Global logging handler. Use with care! preferably use instance level instead of setting one globally.\n    package static var loggingHandler: LoggingHandler? {\n        get {\n            return _loggingHandler.get() ?? nil\n        }\n        @available(\n            *,\n            deprecated,\n            message: \"use instance level `loggingHandler` passed via `init` instead of setting one globally.\"\n        )\n        set {\n            _loggingHandler.put(newValue)\n        }\n    }\n\n    package let loggingHandler: LoggingHandler?\n\n    /// The arguments to execute.\n    package let arguments: [String]\n\n    package let environment: Environment\n\n    /// The path to the directory under which to run the process.\n    package let workingDirectory: AbsolutePath?\n\n    /// The process id of the spawned process, available after the process is launched.\n    #if os(Windows)\n    private var _process: Foundation.Process?\n    package var processID: ProcessID {\n        DWORD(self._process?.processIdentifier ?? 0)\n    }\n    #else\n    package private(set) var processID = ProcessID()\n    #endif\n\n    // process execution mutable state\n    private var state: State = .idle\n    private let stateLock = NSLock()\n\n    private static let sharedCompletionQueue = DispatchQueue(label: \"org.swift.tools-support-core.process-completion\")\n    private var completionQueue = AsyncProcess.sharedCompletionQueue\n\n    // ideally we would use the state for this, but we need to access it while the waitForExit is locking state\n    private var _launched = false\n    private let launchedLock = NSLock()\n\n    package var launched: Bool {\n        self.launchedLock.withLock {\n            self._launched\n        }\n    }\n\n    /// How process redirects its output.\n    package let outputRedirection: OutputRedirection\n\n    /// Indicates if a new progress group is created for the child process.\n    private let startNewProcessGroup: Bool\n\n    /// Cache of validated executables.\n    ///\n    /// Key: Executable name or path.\n    /// Value: Path to the executable, if found.\n    private static let validatedExecutablesMap = ThreadSafeKeyValueStore<String, AbsolutePath?>()\n\n    /// Create a new process instance.\n    ///\n    /// - Parameters:\n    ///   - arguments: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - workingDirectory: The path to the directory under which to run the process.\n    ///   - outputRedirection: How process redirects its output. Default value is .collect.\n    ///   - startNewProcessGroup: If true, a new progress group is created for the child making it\n    ///     continue running even if the parent is killed or interrupted. Default value is true.    //ignore-unacceptable-language\n    ///   - loggingHandler: Handler for logging messages\n    ///\n    package init(\n        arguments: [String],\n        environment: Environment = .current,\n        workingDirectory: AbsolutePath,\n        outputRedirection: OutputRedirection = .collect,\n        startNewProcessGroup: Bool = true,\n        loggingHandler: LoggingHandler? = .none\n    ) {\n        self.arguments = arguments\n        self.environment = environment\n        self.workingDirectory = workingDirectory\n        self.outputRedirection = outputRedirection\n        self.startNewProcessGroup = startNewProcessGroup\n        self.loggingHandler = loggingHandler ?? AsyncProcess.loggingHandler\n    }\n\n    /// Create a new process instance.\n    ///\n    /// - Parameters:\n    ///   - arguments: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - outputRedirection: How process redirects its output. Default value is .collect.\n    ///   - verbose: If true, launch() will print the arguments of the subprocess before launching it.\n    ///   - startNewProcessGroup: If true, a new progress group is created for the child making it\n    ///     continue running even if the parent is killed or interrupted. Default value is true.    //ignore-unacceptable-language\n    ///   - loggingHandler: Handler for logging messages\n    package init(\n        arguments: [String],\n        environment: Environment = .current,\n        outputRedirection: OutputRedirection = .collect,\n        startNewProcessGroup: Bool = true,\n        loggingHandler: LoggingHandler? = .none,\n        workingDirectory: AbsolutePath? = nil\n    ) {\n        self.arguments = arguments\n        self.environment = environment\n        self.workingDirectory = workingDirectory\n        self.outputRedirection = outputRedirection\n        self.startNewProcessGroup = startNewProcessGroup\n        self.loggingHandler = loggingHandler ?? AsyncProcess.loggingHandler\n    }\n\n    package convenience init(\n        args: [String],\n        environment: Environment = .current,\n        outputRedirection: OutputRedirection = .collect,\n        loggingHandler: LoggingHandler? = .none\n    ) {\n        self.init(\n            arguments: args,\n            environment: environment,\n            outputRedirection: outputRedirection,\n            loggingHandler: loggingHandler\n        )\n    }\n\n    package convenience init(\n        args: String...,\n        environment: Environment = .current,\n        outputRedirection: OutputRedirection = .collect,\n        loggingHandler: LoggingHandler? = .none\n    ) {\n        self.init(\n            arguments: args,\n            environment: environment,\n            outputRedirection: outputRedirection,\n            loggingHandler: loggingHandler\n        )\n    }\n\n    /// Returns the path of the the given program if found in the search paths.\n    ///\n    /// The program can be executable name, relative path or absolute path.\n    package static func findExecutable(\n        _ program: String,\n        workingDirectory: AbsolutePath? = nil\n    ) -> AbsolutePath? {\n        if let abs = try? AbsolutePath(validating: program) {\n            return abs\n        }\n        let cwdOpt = workingDirectory ?? localFileSystem.currentWorkingDirectory\n        // The program might be a multi-component relative path.\n        if let rel = try? RelativePath(validating: program), rel.components.count > 1 {\n            if let cwd = cwdOpt {\n                let abs = AbsolutePath(cwd, rel)\n                if localFileSystem.isExecutableFile(abs) {\n                    return abs\n                }\n            }\n            return nil\n        }\n        // From here on out, the program is an executable name, i.e. it doesn't contain a \"/\"\n        let lookup: () -> AbsolutePath? = {\n            let envSearchPaths = getEnvSearchPaths(\n                pathString: Environment.current[.path],\n                currentWorkingDirectory: cwdOpt\n            )\n            let value = lookupExecutablePath(\n                filename: program,\n                currentWorkingDirectory: cwdOpt,\n                searchPaths: envSearchPaths\n            )\n            return value\n        }\n        // This should cover the most common cases, i.e. when the cache is most helpful.\n        if workingDirectory == localFileSystem.currentWorkingDirectory {\n            return AsyncProcess.validatedExecutablesMap.memoize(program, body: lookup)\n        } else {\n            return lookup()\n        }\n    }\n\n    /// Launch the subprocess. Returns a WritableByteStream object that can be used to communicate to the process's\n    /// stdin. If needed, the stream can be closed using the close() API. Otherwise, the stream will be closed\n    /// automatically.\n    @discardableResult\n    package func launch() throws -> any WritableByteStream {\n        precondition(\n            self.arguments.count > 0 && !self.arguments[0].isEmpty,\n            \"Need at least one argument to launch the process.\"\n        )\n\n        self.launchedLock.withLock {\n            precondition(!self._launched, \"It is not allowed to launch the same process object again.\")\n            self._launched = true\n        }\n\n        // Print the arguments if we are verbose.\n        if let loggingHandler = self.loggingHandler {\n            loggingHandler(self.arguments.map { $0.spm_shellEscaped() }.joined(separator: \" \"))\n        }\n\n        // Look for executable.\n        let executable = self.arguments[0]\n        guard let executablePath = AsyncProcess.findExecutable(executable, workingDirectory: workingDirectory) else {\n            throw AsyncProcess.Error.missingExecutableProgram(program: executable)\n        }\n\n        #if os(Windows)\n        let process = Foundation.Process()\n        self._process = process\n        process.arguments = Array(self.arguments.dropFirst()) // Avoid including the executable URL twice.\n        if let workingDirectory {\n            process.currentDirectoryURL = workingDirectory.asURL\n        }\n        process.executableURL = executablePath.asURL\n        process.environment = .init(self.environment)\n\n        let stdinPipe = Pipe()\n        process.standardInput = stdinPipe\n\n        let group = DispatchGroup()\n\n        var stdout: [UInt8] = []\n        let stdoutLock = NSLock()\n\n        var stderr: [UInt8] = []\n        let stderrLock = NSLock()\n\n        if self.outputRedirection.redirectsOutput {\n            let stdoutPipe = Pipe()\n            let stderrPipe = Pipe()\n\n            group.enter()\n            stdoutPipe.fileHandleForReading.readabilityHandler = { (fh: FileHandle) in\n                let data = (try? fh.read(upToCount: Int.max)) ?? Data()\n                if data.count == 0 {\n                    stdoutPipe.fileHandleForReading.readabilityHandler = nil\n                    group.leave()\n                } else {\n                    let contents = data.withUnsafeBytes { [UInt8]($0) }\n                    self.outputRedirection.outputClosures?.stdoutClosure(contents)\n                    stdoutLock.withLock {\n                        stdout += contents\n                    }\n                }\n            }\n\n            group.enter()\n            stderrPipe.fileHandleForReading.readabilityHandler = { (fh: FileHandle) in\n                let data = (try? fh.read(upToCount: Int.max)) ?? Data()\n                if data.count == 0 {\n                    stderrPipe.fileHandleForReading.readabilityHandler = nil\n                    group.leave()\n                } else {\n                    let contents = data.withUnsafeBytes { [UInt8]($0) }\n                    self.outputRedirection.outputClosures?.stderrClosure(contents)\n                    stderrLock.withLock {\n                        stderr += contents\n                    }\n                }\n            }\n\n            process.standardOutput = stdoutPipe\n            process.standardError = stderrPipe\n        }\n\n        // first set state then start reading threads\n        let sync = DispatchGroup()\n        sync.enter()\n        self.stateLock.withLock {\n            self.state = .readingOutput(sync: sync)\n        }\n\n        group.notify(queue: self.completionQueue) {\n            self.stateLock.withLock {\n                self.state = .outputReady(stdout: .success(stdout), stderr: .success(stderr))\n            }\n            sync.leave()\n        }\n\n        try process.run()\n        return stdinPipe.fileHandleForWriting\n        #elseif(!canImport(Darwin) || os(macOS))\n        // Initialize the spawn attributes.\n        #if os(Android)\n        var attributes: posix_spawnattr_t! = nil\n        #elseif canImport(Darwin) || os(OpenBSD) || os(FreeBSD)\n        var attributes: posix_spawnattr_t? = nil\n        #else\n        var attributes = posix_spawnattr_t()\n        #endif\n        posix_spawnattr_init(&attributes)\n        defer { posix_spawnattr_destroy(&attributes) }\n\n        // Unmask all signals.\n        var noSignals = sigset_t()\n        sigemptyset(&noSignals)\n        posix_spawnattr_setsigmask(&attributes, &noSignals)\n\n        // Reset all signals to default behavior.\n        #if canImport(Darwin)\n        var mostSignals = sigset_t()\n        sigfillset(&mostSignals)\n        sigdelset(&mostSignals, SIGKILL)\n        sigdelset(&mostSignals, SIGSTOP)\n        posix_spawnattr_setsigdefault(&attributes, &mostSignals)\n        #else\n        // On Linux, this can only be used to reset signals that are legal to\n        // modify, so we have to take care about the set we use.\n        var mostSignals = sigset_t()\n        sigemptyset(&mostSignals)\n        for i in 1 ..< SIGSYS {\n            if i == SIGKILL || i == SIGSTOP {\n                continue\n            }\n            sigaddset(&mostSignals, i)\n        }\n        posix_spawnattr_setsigdefault(&attributes, &mostSignals)\n        #endif\n\n        // Set the attribute flags.\n        var flags = POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF\n        if self.startNewProcessGroup {\n            // Establish a separate process group.\n            flags |= POSIX_SPAWN_SETPGROUP\n            posix_spawnattr_setpgroup(&attributes, 0)\n        }\n\n        posix_spawnattr_setflags(&attributes, Int16(flags))\n\n        // Setup the file actions.\n        #if os(Android)\n        var fileActions: posix_spawn_file_actions_t! = nil\n        #elseif canImport(Darwin) || os(Android) || os(OpenBSD) || os(FreeBSD)\n        var fileActions: posix_spawn_file_actions_t? = nil\n        #else\n        var fileActions = posix_spawn_file_actions_t()\n        #endif\n        posix_spawn_file_actions_init(&fileActions)\n        defer { posix_spawn_file_actions_destroy(&fileActions) }\n\n        if let workingDirectory = workingDirectory?.pathString {\n            #if canImport(Darwin)\n            posix_spawn_file_actions_addchdir_np(&fileActions, workingDirectory)\n            #else\n            guard SPM_posix_spawn_file_actions_addchdir_np_supported() else {\n                throw AsyncProcess.Error.workingDirectoryNotSupported\n            }\n\n            SPM_posix_spawn_file_actions_addchdir_np(&fileActions, workingDirectory)\n            #endif\n        }\n\n        var stdinPipe: [Int32] = [-1, -1]\n        try open(pipe: &stdinPipe)\n\n        guard let fp = fdopen(stdinPipe[1], \"wb\") else {\n            throw AsyncProcess.Error.stdinUnavailable\n        }\n        let stdinStream = try LocalFileOutputByteStream(filePointer: fp, closeOnDeinit: true)\n\n        // Dupe the read portion of the remote to 0.\n        posix_spawn_file_actions_adddup2(&fileActions, stdinPipe[0], 0)\n\n        // Close the other side's pipe since it was dupped to 0.\n        posix_spawn_file_actions_addclose(&fileActions, stdinPipe[0])\n        posix_spawn_file_actions_addclose(&fileActions, stdinPipe[1])\n\n        var outputPipe: [Int32] = [-1, -1]\n        var stderrPipe: [Int32] = [-1, -1]\n        if self.outputRedirection.redirectsOutput {\n            // Open the pipe.\n            try open(pipe: &outputPipe)\n\n            // Open the write end of the pipe.\n            posix_spawn_file_actions_adddup2(&fileActions, outputPipe[1], 1)\n\n            // Close the other ends of the pipe since they were dupped to 1.\n            posix_spawn_file_actions_addclose(&fileActions, outputPipe[0])\n            posix_spawn_file_actions_addclose(&fileActions, outputPipe[1])\n\n            if self.outputRedirection.redirectStderr {\n                // If merged was requested, send stderr to stdout.\n                posix_spawn_file_actions_adddup2(&fileActions, 1, 2)\n            } else {\n                // If no redirect was requested, open the pipe for stderr.\n                try open(pipe: &stderrPipe)\n                posix_spawn_file_actions_adddup2(&fileActions, stderrPipe[1], 2)\n\n                // Close the other ends of the pipe since they were dupped to 2.\n                posix_spawn_file_actions_addclose(&fileActions, stderrPipe[0])\n                posix_spawn_file_actions_addclose(&fileActions, stderrPipe[1])\n            }\n        } else {\n            posix_spawn_file_actions_adddup2(&fileActions, 1, 1)\n            posix_spawn_file_actions_adddup2(&fileActions, 2, 2)\n        }\n\n        var resolvedArgs = self.arguments\n        if workingDirectory != nil {\n            resolvedArgs[0] = executablePath.pathString\n        }\n        let argv = CStringArray(resolvedArgs)\n        let envValues = environment.map { \"\\($0.0)=\\($0.1)\" }\n        let env = CStringArray(envValues)\n        let rv = posix_spawnp(&self.processID, argv.cArray[0]!, &fileActions, &attributes, argv.cArray, env.cArray)\n\n        guard rv == 0 else {\n            throw SystemError.posix_spawn(rv, self.arguments)\n        }\n\n        do {\n            // Close the local read end of the input pipe.\n            try close(fd: stdinPipe[0])\n\n            let group = DispatchGroup()\n            if !self.outputRedirection.redirectsOutput {\n                // no stdout or stderr in this case\n                self.stateLock.withLock {\n                    self.state = .outputReady(stdout: .success([]), stderr: .success([]))\n                }\n            } else {\n                var pending: Result<[UInt8], Swift.Error>?\n                let pendingLock = NSLock()\n\n                let outputClosures = self.outputRedirection.outputClosures\n\n                // Close the local write end of the output pipe.\n                try close(fd: outputPipe[1])\n\n                // Create a thread and start reading the output on it.\n                group.enter()\n                let stdoutThread = Thread { [weak self] in\n                    if let readResult = self?.readOutput(\n                        onFD: outputPipe[0],\n                        outputClosure: outputClosures?.stdoutClosure\n                    ) {\n                        pendingLock.withLock {\n                            if let stderrResult = pending {\n                                self?.stateLock.withLock {\n                                    self?.state = .outputReady(stdout: readResult, stderr: stderrResult)\n                                }\n                            } else {\n                                pending = readResult\n                            }\n                        }\n                        group.leave()\n                    } else if let stderrResult = (pendingLock.withLock { pending }) {\n                        // TODO: this is more of an error\n                        self?.stateLock.withLock {\n                            self?.state = .outputReady(stdout: .success([]), stderr: stderrResult)\n                        }\n                        group.leave()\n                    }\n                }\n\n                // Only schedule a thread for stderr if no redirect was requested.\n                var stderrThread: Thread? = nil\n                if !self.outputRedirection.redirectStderr {\n                    // Close the local write end of the stderr pipe.\n                    try close(fd: stderrPipe[1])\n\n                    // Create a thread and start reading the stderr output on it.\n                    group.enter()\n                    stderrThread = Thread { [weak self] in\n                        if let readResult = self?.readOutput(\n                            onFD: stderrPipe[0],\n                            outputClosure: outputClosures?.stderrClosure\n                        ) {\n                            pendingLock.withLock {\n                                if let stdoutResult = pending {\n                                    self?.stateLock.withLock {\n                                        self?.state = .outputReady(stdout: stdoutResult, stderr: readResult)\n                                    }\n                                } else {\n                                    pending = readResult\n                                }\n                            }\n                            group.leave()\n                        } else if let stdoutResult = (pendingLock.withLock { pending }) {\n                            // TODO: this is more of an error\n                            self?.stateLock.withLock {\n                                self?.state = .outputReady(stdout: stdoutResult, stderr: .success([]))\n                            }\n                            group.leave()\n                        }\n                    }\n                } else {\n                    pendingLock.withLock {\n                        pending = .success([]) // no stderr in this case\n                    }\n                }\n\n                // first set state then start reading threads\n                self.stateLock.withLock {\n                    self.state = .readingOutput(sync: group)\n                }\n\n                stdoutThread.start()\n                stderrThread?.start()\n            }\n\n            return stdinStream\n        } catch {\n            throw AsyncProcessResult.Error.systemError(arguments: self.arguments, underlyingError: error)\n        }\n        #else\n        preconditionFailure(\"Process spawning is not available\")\n        #endif // POSIX implementation\n    }\n\n    /// Executes the process I/O state machine, returning the result when finished.\n    @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)\n    @discardableResult\n    package func waitUntilExit() async throws -> AsyncProcessResult {\n        try await withCheckedThrowingContinuation { continuation in\n            DispatchQueue.processConcurrent.async {\n                self.waitUntilExit({\n                    continuation.resume(with: $0)\n                })\n            }\n        }\n    }\n\n    /// Blocks the calling process until the subprocess finishes execution.\n    @available(*, noasync)\n    @discardableResult\n    package func waitUntilExit() throws -> AsyncProcessResult {\n        let group = DispatchGroup()\n        group.enter()\n        let resultBox = ThreadSafeBox<Result<AsyncProcessResult, Swift.Error>?>()\n        self.waitUntilExit { result in\n            resultBox.put(result)\n            group.leave()\n        }\n        group.wait()\n        return try resultBox.get().unsafelyUnwrapped.get()\n    }\n\n    /// Executes the process I/O state machine, calling completion block when finished.\n    private func waitUntilExit(_ completion: @Sendable @escaping (Result<AsyncProcessResult, Swift.Error>) -> Void) {\n        self.stateLock.lock()\n        switch self.state {\n        case .idle:\n            defer { self.stateLock.unlock() }\n            preconditionFailure(\"The process is not yet launched.\")\n        case .complete(let result):\n            self.stateLock.unlock()\n            completion(.success(result))\n        case .failed(let error):\n            self.stateLock.unlock()\n            completion(.failure(error))\n        case .readingOutput(let sync):\n            self.stateLock.unlock()\n            sync.notify(queue: self.completionQueue) {\n                self.waitUntilExit(completion)\n            }\n        case .outputReady(let stdoutResult, let stderrResult):\n            defer { self.stateLock.unlock() }\n            // Wait until process finishes execution.\n            #if os(Windows)\n            precondition(self._process != nil, \"The process is not yet launched.\")\n            let p = self._process!\n            p.waitUntilExit()\n            let exitStatusCode = p.terminationStatus\n            let normalExit = p.terminationReason == .exit\n            #else\n            var exitStatusCode: Int32 = 0\n            var result = waitpid(processID, &exitStatusCode, 0)\n            while result == -1 && errno == EINTR {\n                result = waitpid(self.processID, &exitStatusCode, 0)\n            }\n            if result == -1 {\n                self.state = .failed(SystemError.waitpid(errno))\n            }\n            let normalExit = !WIFSIGNALED(result)\n            #endif\n\n            // Construct the result.\n            let executionResult = AsyncProcessResult(\n                arguments: arguments,\n                environment: environment,\n                exitStatusCode: exitStatusCode,\n                normal: normalExit,\n                output: stdoutResult,\n                stderrOutput: stderrResult\n            )\n            self.state = .complete(executionResult)\n            self.completionQueue.async {\n                self.waitUntilExit(completion)\n            }\n        }\n    }\n\n    #if !os(Windows)\n    /// Reads the given fd and returns its result.\n    ///\n    /// Closes the fd before returning.\n    private func readOutput(onFD fd: Int32, outputClosure: OutputClosure?) -> Result<[UInt8], Swift.Error> {\n        // Read all of the data from the output pipe.\n        let N = 4096\n        var buf = [UInt8](repeating: 0, count: N + 1)\n\n        var out = [UInt8]()\n        var error: Swift.Error? = nil\n        loop: while true {\n            let n = read(fd, &buf, N)\n            switch n {\n            case -1:\n                if errno == EINTR {\n                    continue\n                } else {\n                    error = SystemError.read(errno)\n                    break loop\n                }\n            case 0:\n                // Close the read end of the output pipe.\n                // We should avoid closing the read end of the pipe in case\n                // -1 because the child process may still have content to be\n                // flushed into the write end of the pipe. If the read end of the\n                // pipe is closed, then a write will cause a SIGPIPE signal to\n                // be generated for the calling process.  If the calling process is\n                // ignoring this signal, then write fails with the error EPIPE.\n                close(fd)\n                break loop\n            default:\n                let data = buf[0 ..< n]\n                if let outputClosure {\n                    outputClosure(Array(data))\n                } else {\n                    out += data\n                }\n            }\n        }\n        // Construct the output result.\n        return error.map(Result.failure) ?? .success(out)\n    }\n    #endif\n\n    /// Send a signal to the process.\n    ///\n    /// Note: This will signal all processes in the process group.\n    package func signal(_ signal: Int32) {\n        #if os(Windows)\n        if signal == SIGINT {\n            self._process?.interrupt()\n        } else {\n            self._process?.terminate()\n        }\n        #else\n        assert(self.launched, \"The process is not yet launched.\")\n        kill(self.startNewProcessGroup ? -self.processID : self.processID, signal)      //ignore-unacceptable-language\n        #endif\n    }\n}\n\nextension AsyncProcess {\n    /// Execute a subprocess and returns the result when it finishes execution\n    ///\n    /// - Parameters:\n    ///   - arguments: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    package static func popen(\n        arguments: [String],\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) async throws -> AsyncProcessResult {\n        let process = AsyncProcess(\n            arguments: arguments,\n            environment: environment,\n            outputRedirection: .collect,\n            loggingHandler: loggingHandler\n        )\n        try process.launch()\n        return try await process.waitUntilExit()\n    }\n\n    /// Execute a subprocess and returns the result when it finishes execution\n    ///\n    /// - Parameters:\n    ///   - args: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    package static func popen(\n        args: String...,\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) async throws -> AsyncProcessResult {\n        try await self.popen(arguments: args, environment: environment, loggingHandler: loggingHandler)\n    }\n\n    package typealias DuplexStreamHandler =\n        @Sendable (_ stdinStream: WritableByteStream, _ stdoutStream: ReadableStream) async throws -> ()\n    package typealias ReadableStreamHandler =\n        @Sendable (_ stderrStream: ReadableStream) async throws -> ()\n\n    /// Launches a new `AsyncProcess` instances, allowing the caller to consume `stdout` and `stderr` output\n    /// with handlers that support structured concurrency.\n    /// - Parameters:\n    ///   - arguments: CLI command used to launch the process.\n    ///   - environment: environment variables passed to the launched process.\n    ///   - loggingHandler: handler used for logging,\n    ///   - stdoutHandler: asynchronous bidirectional handler closure that receives `stdin` and `stdout` streams as\n    ///   arguments.\n    ///   - stderrHandler: asynchronous unidirectional handler closure that receives `stderr` stream as an argument.\n    /// - Returns: ``AsyncProcessResult`` value as received from the underlying ``AsyncProcess/waitUntilExit()`` call\n    /// made on ``AsyncProcess`` instance.\n    package static func popen(\n        arguments: [String],\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none,\n        stdoutHandler: @escaping DuplexStreamHandler,\n        stderrHandler: ReadableStreamHandler? = nil\n    ) async throws -> AsyncProcessResult {\n        let (stdoutStream, stdoutContinuation) = ReadableStream.makeStream()\n        let (stderrStream, stderrContinuation) = ReadableStream.makeStream()\n\n        let process = AsyncProcess(\n            arguments: arguments,\n            environment: environment,\n            outputRedirection: .stream {\n                stdoutContinuation.yield($0)\n            } stderr: {\n                stderrContinuation.yield($0)\n            },\n            loggingHandler: loggingHandler\n        )\n\n        return try await withThrowingTaskGroup(of: Void.self) { group in\n            let stdinStream = try process.launch()\n\n            group.addTask {\n                try await stdoutHandler(stdinStream, stdoutStream)\n            }\n\n            if let stderrHandler {\n                group.addTask {\n                    try await stderrHandler(stderrStream)\n                }\n            }\n\n            defer {\n                stdoutContinuation.finish()\n                stderrContinuation.finish()\n            }\n\n            return try await process.waitUntilExit()\n        }\n    }\n\n    /// Execute a subprocess and get its (UTF-8) output if it has a non zero exit.\n    ///\n    /// - Parameters:\n    ///   - arguments: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    /// - Returns: The process output (stdout + stderr).\n    @discardableResult\n    package static func checkNonZeroExit(\n        arguments: [String],\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) async throws -> String {\n        let result = try await popen(\n            arguments: arguments,\n            environment: environment,\n            loggingHandler: loggingHandler\n        )\n        // Throw if there was a non zero termination.\n        guard result.exitStatus == .terminated(code: 0) else {\n            throw AsyncProcessResult.Error.nonZeroExit(result)\n        }\n        return try result.utf8Output()\n    }\n\n    /// Execute a subprocess and get its (UTF-8) output if it has a non zero exit.\n    ///\n    /// - Parameters:\n    ///   - args: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    /// - Returns: The process output (stdout + stderr).\n    @discardableResult\n    package static func checkNonZeroExit(\n        args: String...,\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) async throws -> String {\n        try await self.checkNonZeroExit(\n            arguments: args,\n            environment: environment,\n            loggingHandler: loggingHandler\n        )\n    }\n}\n\nextension AsyncProcess {\n    /// Execute a subprocess and calls completion block when it finishes execution\n    ///\n    /// - Parameters:\n    ///   - arguments: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    ///   - queue: Queue to use for callbacks\n    ///   - completion: A completion handler to return the process result\n    @available(*, noasync)\n    package static func popen(\n        arguments: [String],\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none,\n        queue: DispatchQueue? = nil,\n        completion: @Sendable @escaping (Result<AsyncProcessResult, Swift.Error>) -> Void\n    ) {\n        let completionQueue = queue ?? Self.sharedCompletionQueue\n\n        do {\n            let process = AsyncProcess(\n                arguments: arguments,\n                environment: environment,\n                outputRedirection: .collect,\n                loggingHandler: loggingHandler\n            )\n            process.completionQueue = completionQueue\n            try process.launch()\n            process.waitUntilExit(completion)\n        } catch {\n            completionQueue.async {\n                completion(.failure(error))\n            }\n        }\n    }\n\n    /// Execute a subprocess and block until it finishes execution\n    ///\n    /// - Parameters:\n    ///   - arguments: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    /// - Returns: The process result.\n    @available(*, noasync)\n    @discardableResult\n    package static func popen(\n        arguments: [String],\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none,\n        workingDirectory: AbsolutePath? = nil\n    ) throws -> AsyncProcessResult {\n        let process = AsyncProcess(\n            arguments: arguments,\n            environment: environment,\n            outputRedirection: .collect,\n            loggingHandler: loggingHandler,\n            workingDirectory: workingDirectory\n        )\n        try process.launch()\n        return try process.waitUntilExit()\n    }\n\n    /// Execute a subprocess and block until it finishes execution\n    ///\n    /// - Parameters:\n    ///   - args: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    /// - Returns: The process result.\n    @available(*, noasync)\n    @discardableResult\n    package static func popen(\n        args: String...,\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) throws -> AsyncProcessResult {\n        try AsyncProcess.popen(arguments: args, environment: environment, loggingHandler: loggingHandler)\n    }\n\n    /// Execute a subprocess and get its (UTF-8) output if it has a non zero exit.\n    ///\n    /// - Parameters:\n    ///   - arguments: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    /// - Returns: The process output (stdout + stderr).\n    @available(*, noasync)\n    @discardableResult\n    package static func checkNonZeroExit(\n        arguments: [String],\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) throws -> String {\n        let process = AsyncProcess(\n            arguments: arguments,\n            environment: environment,\n            outputRedirection: .collect,\n            loggingHandler: loggingHandler\n        )\n        try process.launch()\n        let result = try process.waitUntilExit()\n        // Throw if there was a non zero termination.\n        guard result.exitStatus == .terminated(code: 0) else {\n            throw AsyncProcessResult.Error.nonZeroExit(result)\n        }\n        return try result.utf8Output()\n    }\n\n    /// Execute a subprocess and get its (UTF-8) output if it has a non zero exit.\n    ///\n    /// - Parameters:\n    ///   - arguments: The arguments for the subprocess.\n    ///   - environment: The environment to pass to subprocess. By default the current process environment\n    ///     will be inherited.\n    ///   - loggingHandler: Handler for logging messages\n    /// - Returns: The process output (stdout + stderr).\n    @available(*, noasync)\n    @discardableResult\n    package static func checkNonZeroExit(\n        args: String...,\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) throws -> String {\n        try self.checkNonZeroExit(arguments: args, environment: environment, loggingHandler: loggingHandler)\n    }\n}\n\nextension AsyncProcess: Hashable {\n    package func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n\n    package static func == (lhs: AsyncProcess, rhs: AsyncProcess) -> Bool {\n        ObjectIdentifier(lhs) == ObjectIdentifier(rhs)\n    }\n}\n\n// MARK: - Private helpers\n\n#if !os(Windows)\n#if canImport(Darwin)\nprivate typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t?\n#else\nprivate typealias swiftpm_posix_spawn_file_actions_t = posix_spawn_file_actions_t\n#endif\n\nprivate func WIFEXITED(_ status: Int32) -> Bool {\n    _WSTATUS(status) == 0\n}\n\nprivate func _WSTATUS(_ status: Int32) -> Int32 {\n    status & 0x7F\n}\n\nprivate func WIFSIGNALED(_ status: Int32) -> Bool {\n    (_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7F)\n}\n\nprivate func WEXITSTATUS(_ status: Int32) -> Int32 {\n    (status >> 8) & 0xFF\n}\n\nprivate func WTERMSIG(_ status: Int32) -> Int32 {\n    status & 0x7F\n}\n\n/// Open the given pipe.\nprivate func open(pipe buffer: inout [Int32]) throws {\n    let rv = pipe(&buffer)\n    guard rv == 0 else {\n        throw SystemError.pipe(rv)\n    }\n}\n\n/// Close the given fd.\nprivate func close(fd: Int32) throws {\n    func innerClose(_ fd: inout Int32) throws {\n        let rv = close(fd)\n        guard rv == 0 else {\n            throw SystemError.close(rv)\n        }\n    }\n    var innerFd = fd\n    try innerClose(&innerFd)\n}\n\nextension AsyncProcess.Error: CustomStringConvertible {\n    package var description: String {\n        switch self {\n        case .missingExecutableProgram(let program):\n            \"could not find executable for '\\(program)'\"\n        case .workingDirectoryNotSupported:\n            \"workingDirectory is not supported in this platform\"\n        case .stdinUnavailable:\n            \"could not open stdin on this platform\"\n        }\n    }\n}\n\nextension AsyncProcess.Error: CustomNSError {\n    package var errorUserInfo: [String: Any] {\n        [NSLocalizedDescriptionKey: self.description]\n    }\n}\n\n#endif\n\nextension AsyncProcessResult.Error: CustomStringConvertible {\n    package var description: String {\n        switch self {\n        case .systemError(let arguments, let underlyingError):\n            return \"error while executing `\\(arguments.joined(separator: \" \"))`: \\(underlyingError)\"\n        case .illegalUTF8Sequence:\n            return \"illegal UTF8 sequence output\"\n        case .nonZeroExit(let result):\n            var str = \"\"\n            switch result.exitStatus {\n            case .terminated(let code):\n                str.append(contentsOf: \"terminated(\\(code)): \")\n            #if os(Windows)\n            case .abnormal(let exception):\n                str.append(contentsOf: \"abnormal(\\(exception)): \")\n            #else\n            case .signalled(let signal):\n                str.append(contentsOf: \"signalled(\\(signal)): \")\n            #endif\n            }\n\n            // Strip sandbox information from arguments to keep things pretty.\n            var args = result.arguments\n            // This seems a little fragile.\n            if args.first == \"sandbox-exec\", args.count > 3 {\n                args = args.suffix(from: 3).map { $0 }\n            }\n            str.append(contentsOf: args.map { $0.spm_shellEscaped() }.joined(separator: \" \"))\n\n            // Include the output, if present.\n            if let output = try? result.utf8Output() + result.utf8stderrOutput() {\n                // We indent the output to keep it visually separated from everything else.\n                let indentation = \"    \"\n                str.append(contentsOf: \" output:\\n\")\n                str.append(contentsOf: indentation)\n                str.append(contentsOf: output.split(whereSeparator: { $0.isNewline })\n                                             .joined(separator: \"\\n\\(indentation)\"))\n                if !output.hasSuffix(\"\\n\") {\n                    str.append(contentsOf: \"\\n\")\n                }\n            }\n\n            return str\n        }\n    }\n}\n\n#if os(Windows)\nextension FileHandle: WritableByteStream {\n    package var position: Int {\n        Int(offsetInFile)\n    }\n\n    package func write(_ byte: UInt8) {\n        self.write(Data([byte]))\n    }\n\n    package func write(_ bytes: some Collection<UInt8>) {\n        self.write(Data(bytes))\n    }\n\n    package func flush() {\n        synchronizeFile()\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Basics/Concurrency/ConcurrencyHelpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Dispatch\nimport class Foundation.NSLock\nimport class Foundation.ProcessInfo\nimport class Foundation.Thread\nimport struct Foundation.URL\nimport struct Foundation.UUID\nimport func TSCBasic.tsc_await\n\npublic enum Concurrency {\n    public static var maxOperations: Int {\n        Environment.current[\"SWIFTPM_MAX_CONCURRENT_OPERATIONS\"].flatMap(Int.init) ?? ProcessInfo.processInfo\n            .activeProcessorCount\n    }\n}\n\n@available(*, noasync, message: \"This method blocks the current thread indefinitely. Calling it from the concurrency pool can cause deadlocks\")\npublic func unsafe_await<T: Sendable>(_ body: @Sendable @escaping () async -> T) -> T {\n    let semaphore = DispatchSemaphore(value: 0)\n\n    let box = ThreadSafeBox<T?>()\n    Task {\n        let localValue: T = await body()\n        box.mutate { _ in localValue }\n        semaphore.signal()\n    }\n    semaphore.wait()\n    return box.get()!\n}\n\nextension Task where Failure == Never {\n    /// Runs `block` in a new thread and suspends until it finishes execution.\n    ///\n    /// - note: This function should be used sparingly, such as for long-running operations that may block and therefore should not be run on the Swift Concurrency thread pool. Do not use this for operations for which there may be many concurrent invocations as it could lead to thread explosion. It is meant to be a bridge to pre-existing blocking code which can't easily be converted to use Swift concurrency features.\n    public static func detachNewThread(name: String? = nil, _ block: @Sendable @escaping () -> Success) async -> Success {\n        return await withCheckedContinuation { continuation in\n            Thread.detachNewThread {\n                Thread.current.name = name\n                return continuation.resume(returning: block())\n            }\n        }\n    }\n}\n\nextension DispatchQueue {\n    // a shared concurrent queue for running concurrent asynchronous operations\n    public static let sharedConcurrent = DispatchQueue(\n        label: \"swift.org.swiftpm.shared.concurrent\",\n        attributes: .concurrent\n    )\n}\n\nextension DispatchQueue {\n    package func scheduleOnQueue<T>(work: @escaping @Sendable () throws -> T) async throws -> T {\n        try await withCheckedThrowingContinuation { continuation in\n            self.async {\n                do {\n                    continuation.resume(returning: try work())\n                } catch {\n                    continuation.resume(throwing: error)\n                }\n            }\n        }\n    }\n\n    package func asyncResult<T: Sendable>(_ callback: @escaping @Sendable (Result<T, Error>) -> Void, _ closure: @escaping @Sendable () async throws -> T) {\n        let completion: @Sendable (Result<T, Error>) -> Void = {\n            result in self.async {\n                callback(result)\n            }\n        }\n\n        Task {\n            do {\n                completion(.success(try await closure()))\n            } catch {\n                completion(.failure(error))\n            }\n        }\n    }\n}\n\n/// A queue for running async operations with a limit on the number of concurrent tasks.\npublic final class AsyncOperationQueue: @unchecked Sendable {\n\n    // This implementation is identical to the AsyncOperationQueue in swift-build.\n    // Any modifications made here should also be made there.\n    // https://github.com/swiftlang/swift-build/blob/main/Sources/SWBUtil/AsyncOperationQueue.swift#L13\n\n    fileprivate typealias ID = UUID\n    fileprivate typealias WaitingContinuation = CheckedContinuation<Void, any Error>\n\n    private let concurrentTasks: Int\n    private var waitingTasks: [WorkTask] = []\n    private let waitingTasksLock = NSLock()\n\n    fileprivate enum WorkTask {\n        case creating(ID)\n        case waiting(ID, WaitingContinuation)\n        case running(ID)\n        case cancelled(ID)\n\n        var id: ID {\n            switch self {\n            case .creating(let id), .waiting(let id, _), .running(let id), .cancelled(let id):\n                return id\n            }\n        }\n\n        var continuation: WaitingContinuation? {\n            guard case .waiting(_, let continuation) = self else {\n                return nil\n            }\n            return continuation\n        }\n    }\n\n    /// Creates an `AsyncOperationQueue` with a specified number of concurrent tasks.\n    /// - Parameter concurrentTasks: The maximum number of concurrent tasks that can be executed concurrently.\n    public init(concurrentTasks: Int) {\n        self.concurrentTasks = concurrentTasks\n    }\n\n    deinit {\n        waitingTasksLock.withLock {\n            if !waitingTasks.isEmpty {\n                preconditionFailure(\"Deallocated with waiting tasks\")\n            }\n        }\n    }\n\n    /// Executes an asynchronous operation, ensuring that the number of concurrent tasks\n    // does not exceed the specified limit.\n    /// - Parameter operation: The asynchronous operation to execute.\n    /// - Returns: The result of the operation.\n    /// - Throws: An error thrown by the operation, or a `CancellationError` if the operation is cancelled.\n    public func withOperation<ReturnValue>(\n        _ operation: () async throws -> sending ReturnValue\n    ) async throws -> ReturnValue {\n        let taskId = try await waitIfNeeded()\n        defer { signalCompletion(taskId) }\n        return try await operation()\n    }\n\n    private func waitIfNeeded() async throws -> ID {\n        let workTask = waitingTasksLock.withLock({\n            let shouldWait = waitingTasks.count >= concurrentTasks\n            let workTask = shouldWait ? WorkTask.creating(ID()) : .running(ID())\n            waitingTasks.append(workTask)\n            return workTask\n        })\n\n        // If we aren't creating a task that needs to wait, we're under the concurrency limit.\n        guard case .creating(let taskId) = workTask else {\n            return workTask.id\n        }\n\n        enum TaskAction {\n            case start(WaitingContinuation)\n            case cancel(WaitingContinuation)\n        }\n\n        try await withTaskCancellationHandler {\n            try await withCheckedThrowingContinuation { (continuation: WaitingContinuation) -> Void in\n                let action: TaskAction? = waitingTasksLock.withLock {\n                    guard let index = waitingTasks.firstIndex(where: { $0.id == taskId }) else {\n                        // The task may have been marked as cancelled already and then removed from\n                        // waitingTasks in `signalCompletion`.\n                        return .cancel(continuation)\n                    }\n\n                    switch waitingTasks[index] {\n                        case .cancelled:\n                            // If the task was cancelled in between creating the task cancellation handler and acquiring the lock,\n                            // we should resume the continuation with a `CancellationError`.\n                            waitingTasks.remove(at: index)\n                            return .cancel(continuation)\n                        case .creating, .running, .waiting:\n                            // A task may have completed since we initially checked if we should wait. Check again in this locked\n                            // section and if we can start it, remove it from the waiting tasks and start it immediately.\n                            if waitingTasks.count >= concurrentTasks {\n                                waitingTasks[index] = .waiting(taskId, continuation)\n                                return nil\n                            } else {\n                                waitingTasks.remove(at: index)\n                                return .start(continuation)\n                            }\n                    }\n                }\n\n                switch action {\n                    case .some(.cancel(let continuation)):\n                        continuation.resume(throwing: _Concurrency.CancellationError())\n                    case .some(.start(let continuation)):\n                        continuation.resume()\n                    case .none:\n                        return\n                }\n            }\n        } onCancel: {\n            let continuation: WaitingContinuation? = self.waitingTasksLock.withLock {\n                guard let taskIndex = self.waitingTasks.firstIndex(where: { $0.id == taskId }) else {\n                    return nil\n                }\n\n                switch self.waitingTasks[taskIndex] {\n                    case .waiting(_, let continuation):\n                        self.waitingTasks.remove(at: taskIndex)\n\n                        // If the parent task is cancelled then we need to manually handle resuming the\n                        // continuation for the waiting task with a `CancellationError`. Return the continuation\n                        // here so it can be resumed once the `waitingTasksLock` is released.\n                        return continuation\n                    case .creating, .running:\n                        // If the task was still being created, mark it as cancelled in `waitingTasks` so that\n                        // the handler for `withCheckedThrowingContinuation` can immediately cancel it.\n                        self.waitingTasks[taskIndex] = .cancelled(taskId)\n                        return nil\n                    case .cancelled:\n                        preconditionFailure(\"Attempting to cancel a task that was already cancelled\")\n                }\n            }\n\n            continuation?.resume(throwing: _Concurrency.CancellationError())\n        }\n        return workTask.id\n    }\n\n    private func signalCompletion(_ taskId: ID) {\n        let continuationToResume = waitingTasksLock.withLock { () -> WaitingContinuation? in\n            guard !waitingTasks.isEmpty else {\n                return nil\n            }\n\n            // Remove the completed task from the list to decrement the active task count.\n            if let taskIndex = self.waitingTasks.firstIndex(where: { $0.id == taskId }) {\n                waitingTasks.remove(at: taskIndex)\n            }\n\n            // We cannot remove elements from `waitingTasks` while iterating over it, so we make\n            // a pass to collect operations and then apply them after the loop.\n            func createTaskListOperations() -> (CollectionDifference<WorkTask>?, WaitingContinuation?) {\n                var changes: [CollectionDifference<WorkTask>.Change] = []\n                for (index, task) in waitingTasks.enumerated() {\n                    switch task {\n                    case .running:\n                        // Skip tasks that are already running, looking for the first one that is waiting or creating.\n                        continue\n                    case .creating:\n                        // If the next task is in the process of being created, let the\n                        // creation code in the `withCheckedThrowingContinuation` in `waitIfNeeded`\n                        // handle starting the task.\n                        break\n                    case .waiting:\n                        // Begin the next waiting task\n                        changes.append(.remove(offset: index, element: task, associatedWith: nil))\n                        return (CollectionDifference<WorkTask>(changes), task.continuation)\n                    case .cancelled:\n                        // If the next task is cancelled, continue removing cancelled\n                        // tasks until we find one that hasn't run yet, or we exaust the list of waiting tasks.\n                        changes.append(.remove(offset: index, element: task, associatedWith: nil))\n                        continue\n                    }\n                }\n                return (CollectionDifference<WorkTask>(changes), nil)\n            }\n\n            let (collectionOperations, continuation) = createTaskListOperations()\n            if let operations = collectionOperations {\n                guard let appliedDiff = waitingTasks.applying(operations) else {\n                    preconditionFailure(\"Failed to apply changes to waiting tasks\")\n                }\n                waitingTasks = appliedDiff\n            }\n\n            return continuation\n        }\n\n        continuationToResume?.resume()\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Concurrency/NSLock+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.NSLock\n\nextension NSLock {\n    /// Execute the given block while holding the lock.\n    @discardableResult public func withLock<T>(_ body: () throws -> T) rethrows -> T {\n        lock()\n        defer { unlock() }\n        return try body()\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Concurrency/SendableBox.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.Date\n\n/// A `Sendable` storage that allows access from concurrently running tasks in\n/// an `async` closure. This type serves as a replacement for `ThreadSafeBox`\n/// implemented with Swift Concurrency primitives.\npublic actor SendableBox<Value: Sendable> {\n    public init(_ value: Value) {\n        self.value = value\n    }\n\n    public var value: Value\n\n    public func set(_ value: Value) {\n        self.value = value\n    }\n}\n\nextension SendableBox where Value == Int {\n    func increment() {\n        self.value = value + 1\n    }\n\n    func decrement() {\n        self.value = value - 1\n    }\n}\n\nextension SendableBox where Value == Date {\n    func resetDate() {\n        value = Date()\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Concurrency/ThreadSafeArrayStore.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.NSLock\n\n/// Thread-safe array like structure\npublic final class ThreadSafeArrayStore<Value> {\n    private var underlying: [Value]\n    private let lock = NSLock()\n\n    public init(_ seed: [Value] = []) {\n        self.underlying = seed\n    }\n\n    public subscript(index: Int) -> Value? {\n        self.lock.withLock {\n            self.underlying[index]\n        }\n    }\n\n    public func get() -> [Value] {\n        self.lock.withLock {\n            self.underlying\n        }\n    }\n\n    @discardableResult\n    public func clear() -> [Value] {\n        self.lock.withLock {\n            let underlying = self.underlying\n            self.underlying.removeAll()\n            return underlying\n        }\n    }\n\n    @discardableResult\n    public func append(_ item: Value) -> Int {\n        self.lock.withLock {\n            self.underlying.append(item)\n            return self.underlying.count\n        }\n    }\n\n    @discardableResult\n    public func append(contentsOf items: [Value]) -> Int {\n        self.lock.withLock {\n            self.underlying.append(contentsOf: items)\n            return self.underlying.count\n        }\n    }\n\n    public var count: Int {\n        self.lock.withLock {\n            self.underlying.count\n        }\n    }\n\n    public var isEmpty: Bool {\n        self.lock.withLock {\n            self.underlying.isEmpty\n        }\n    }\n\n    public func map<NewValue>(_ transform: (Value) -> NewValue) -> [NewValue] {\n        self.lock.withLock {\n            self.underlying.map(transform)\n        }\n    }\n\n    public func compactMap<NewValue>(_ transform: (Value) throws -> NewValue?) rethrows -> [NewValue] {\n        try self.lock.withLock {\n            try self.underlying.compactMap(transform)\n        }\n    }\n}\n\nextension ThreadSafeArrayStore: @unchecked Sendable where Value: Sendable {}\n"
  },
  {
    "path": "Sources/Basics/Concurrency/ThreadSafeBox.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.NSLock\n\n/// Thread-safe value boxing structure that provides synchronized access to a wrapped value.\n@dynamicMemberLookup\npublic final class ThreadSafeBox<Value> {\n    private var underlying: Value\n    private let lock = NSLock()\n\n    /// Creates a new thread-safe box with the given initial value.\n    ///\n    /// - Parameter seed: The initial value to store in the box.\n    public init(_ seed: Value) {\n        self.underlying = seed\n    }\n\n    /// Atomically mutates the stored value by applying a transformation function.\n    ///\n    /// The transformation function receives the current value and returns a new value\n    /// to replace it. The entire operation is performed under a lock to ensure atomicity.\n    ///\n    /// - Parameter body: A closure that takes the current value and returns a new value.\n    /// - Throws: Any error thrown by the transformation function.\n    public func mutate(body: (Value) throws -> Value) rethrows {\n        try self.lock.withLock {\n            let value = try body(self.underlying)\n            self.underlying = value\n        }\n    }\n\n    /// Atomically mutates the stored value by applying an in-place transformation.\n    ///\n    /// The transformation function receives an inout reference to the current value,\n    /// allowing direct modification. The entire operation is performed under a lock\n    /// to ensure atomicity.\n    ///\n    /// - Parameter body: A closure that receives an inout reference to the current value.\n    /// - Throws: Any error thrown by the transformation function.\n    public func mutate(body: (inout Value) throws -> Void) rethrows {\n        try self.lock.withLock {\n            try body(&self.underlying)\n        }\n    }\n\n    /// Atomically retrieves the current value from the box.\n    ///\n    /// - Returns: A copy of the current value stored in the box.\n    public func get() -> Value {\n        self.lock.withLock {\n            self.underlying\n        }\n    }\n\n    /// Atomically replaces the current value with a new value.\n    ///\n    /// - Parameter newValue: The new value to store in the box.\n    public func put(_ newValue: Value) {\n        self.lock.withLock {\n            self.underlying = newValue\n        }\n    }\n\n    /// Provides thread-safe read-only access to properties of the wrapped value.\n    ///\n    /// This subscript allows you to access properties of the wrapped value using\n    /// dot notation while maintaining thread safety.\n    ///\n    /// - Parameter keyPath: A key path to a property of the wrapped value.\n    /// - Returns: The value of the specified property.\n    public subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> T {\n        self.lock.withLock {\n            self.underlying[keyPath: keyPath]\n        }\n    }\n\n    /// Provides thread-safe read-write access to properties of the wrapped value.\n    ///\n    /// - Parameter keyPath: A writable key path to a property of the wrapped value.\n    /// - Returns: The value of the specified property when getting.\n    public subscript<T>(dynamicMember keyPath: WritableKeyPath<Value, T>) -> T {\n        get {\n            self.lock.withLock {\n                self.underlying[keyPath: keyPath]\n            }\n        }\n        set {\n            self.lock.withLock {\n                self.underlying[keyPath: keyPath] = newValue\n            }\n        }\n    }\n}\n\n// Extension for optional values to support empty initialization\nextension ThreadSafeBox {\n    /// Creates a new thread-safe box initialized with nil for optional value types.\n    ///\n    /// This convenience initializer is only available when the wrapped value type is optional.\n    public convenience init<Wrapped>() where Value == Wrapped? {\n        self.init(nil)\n    }\n\n    /// Takes the stored optional value, setting it to nil.\n    /// - Returns: The previously stored value, or nil if none was present.\n    public func takeValue<Wrapped>() -> Value where Value == Wrapped? {\n        self.lock.withLock {\n            guard let value = self.underlying else { return nil }\n            self.underlying = nil\n            return value\n        }\n    }\n\n    /// Atomically sets the stored optional value to nil.\n    ///\n    /// This method is only available when the wrapped value type is optional.\n    public func clear<Wrapped>() where Value == Wrapped? {\n        self.lock.withLock {\n            self.underlying = nil\n        }\n    }\n\n    /// Atomically retrieves the stored value, returning a default if nil.\n    ///\n    /// This method is only available when the wrapped value type is optional.\n    ///\n    /// - Parameter defaultValue: The value to return if the stored value is nil.\n    /// - Returns: The stored value if not nil, otherwise the default value.\n    public func get<Wrapped>(default defaultValue: Wrapped) -> Wrapped where Value == Wrapped? {\n        self.lock.withLock {\n            self.underlying ?? defaultValue\n        }\n    }\n\n    /// Atomically computes and caches a value if not already present.\n    ///\n    /// If the box already contains a non-nil value, that value is returned immediately.\n    /// Otherwise, the provided closure is executed to compute the value, which is then\n    /// stored and returned. This method is only available when the wrapped value type is optional.\n    ///\n    /// - Parameter body: A closure that computes the value to store if none exists.\n    /// - Returns: The cached value or the newly computed value.\n    /// - Throws: Any error thrown by the computation closure.\n    @discardableResult\n    public func memoize<Wrapped>(body: () throws -> Wrapped) rethrows -> Wrapped where Value == Wrapped? {\n        try self.lock.withLock {\n            if let value = self.underlying {\n                return value\n            }\n            let value = try body()\n            self.underlying = value\n            return value\n        }\n    }\n\n    /// Atomically computes and caches an optional value if not already present.\n    ///\n    /// If the box already contains a non-nil value, that value is returned immediately.\n    /// Otherwise, the provided closure is executed to compute the value, which is then\n    /// stored and returned. This method is only available when the wrapped value type is optional.\n    ///\n    /// If the returned value is `nil` subsequent calls to `memoize` or `memoizeOptional` will\n    /// re-execute the closure.\n    ///\n    /// - Parameter body: A closure that computes the optional value to store if none exists.\n    /// - Returns: The cached value or the newly computed value (which may be nil).\n    /// - Throws: Any error thrown by the computation closure.\n    @discardableResult\n    public func memoizeOptional<Wrapped>(body: () throws -> Wrapped?) rethrows -> Wrapped? where Value == Wrapped? {\n        try self.lock.withLock {\n            if let value = self.underlying {\n                return value\n            }\n            let value = try body()\n            self.underlying = value\n            return value\n        }\n    }\n}\n\nextension ThreadSafeBox where Value == Int {\n    /// Atomically increments the stored integer value by 1.\n    ///\n    /// This method is only available when the wrapped value type is Int.\n    public func increment() {\n        self.lock.withLock {\n            self.underlying = self.underlying + 1\n        }\n    }\n\n    /// Atomically decrements the stored integer value by 1.\n    ///\n    /// This method is only available when the wrapped value type is Int.\n    public func decrement() {\n        self.lock.withLock {\n            self.underlying = self.underlying - 1\n        }\n    }\n}\n\nextension ThreadSafeBox where Value == String {\n    /// Atomically appends a string to the stored string value.\n    ///\n    /// This method is only available when the wrapped value type is String.\n    ///\n    /// - Parameter value: The string to append to the current stored value.\n    public func append(_ value: String) {\n        self.mutate { existingValue in\n            existingValue + value\n        }\n    }\n}\n\nextension ThreadSafeBox: @unchecked Sendable where Value: Sendable {}\n"
  },
  {
    "path": "Sources/Basics/Concurrency/ThreadSafeKeyValueStore.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\n\nimport class Foundation.NSLock\n\n/// Thread-safe dictionary with async memoization\npublic actor ThrowingAsyncKeyValueMemoizer<Key: Hashable & Sendable, Value: Sendable> {\n    var stored: [Key: Task<Value, Error>] = [:]\n\n    public init() {\n        self.stored = [:]\n    }\n\n    public func memoize(_ key: Key, body: @Sendable @escaping () async throws -> Value) async throws -> Value {\n        guard let existingTask = self.stored[key] else {\n            let newTask = Task {\n                try await body()\n            }\n            self.stored[key] = newTask\n            return try await newTask.value\n        }\n        return try await existingTask.value\n    }\n}\n\npublic actor AsyncKeyValueMemoizer<Key: Hashable & Sendable, Value: Sendable> {\n    var stored: [Key: Task<Value, Never>] = [:]\n\n    public init() {\n        self.stored = [:]\n    }\n\n    public func memoize(_ key: Key, body: @Sendable @escaping () async -> Value) async -> Value {\n        guard let existingTask = self.stored[key] else {\n            let newTask = Task {\n                await body()\n            }\n            self.stored[key] = newTask\n            return await newTask.value\n        }\n        return await existingTask.value\n    }\n}\n\npublic actor AsyncThrowingValueMemoizer<Value: Sendable> {\n    var stored: ValueStorage?\n\n    enum ValueStorage {\n    case inProgress([CheckedContinuation<Value, Error>])\n    case complete(Result<Value, Error>)\n    }\n\n    public init() {}\n\n    public func memoize(body: @Sendable () async throws -> Value) async throws -> Value {\n        guard let stored else {\n            self.stored = .inProgress([])\n            let result: Result<Value, Error>\n            do {\n                result = try await .success(body())\n            } catch {\n                result = .failure(error)\n            }\n            if case .inProgress(let array) = self.stored {\n                self.stored = .complete(result)\n                array.forEach { $0.resume(with: result)}\n            }\n            return try result.get()\n        }\n        switch stored {\n\n        case .inProgress(let existing):\n            return try await withCheckedThrowingContinuation {\n                self.stored = .inProgress(existing + [$0])\n            }\n        case .complete(let result):\n            return try result.get()\n        }\n    }\n}\n\n/// Thread-safe dictionary like structure.\npublic final class ThreadSafeKeyValueStore<Key, Value> where Key: Hashable {\n    private var underlying: [Key: Value]\n    private let lock = NSLock()\n\n    public init(_ seed: [Key: Value] = [:]) {\n        self.underlying = seed\n    }\n\n    public func get() -> [Key: Value] {\n        self.lock.withLock {\n            self.underlying\n        }\n    }\n\n    public subscript(key: Key) -> Value? {\n        get {\n            self.lock.withLock {\n                self.underlying[key]\n            }\n        } set {\n            self.lock.withLock {\n                self.underlying[key] = newValue\n            }\n        }\n    }\n\n    @discardableResult\n    public func memoize(_ key: Key, body: () throws -> Value) rethrows -> Value {\n        try self.lock.withLock {\n            try self.underlying.memoize(key: key, body: body)\n        }\n    }\n\n    @discardableResult\n    public func removeValue(forKey key: Key) -> Value? {\n        self.lock.withLock {\n            self.underlying.removeValue(forKey: key)\n        }\n    }\n\n    @discardableResult\n    public func clear() -> [Key: Value] {\n        self.lock.withLock {\n            let underlying = self.underlying\n            self.underlying.removeAll()\n            return underlying\n        }\n    }\n\n    public var count: Int {\n        self.lock.withLock {\n            self.underlying.count\n        }\n    }\n\n    public var isEmpty: Bool {\n        self.lock.withLock {\n            self.underlying.isEmpty\n        }\n    }\n\n    public func contains(_ key: Key) -> Bool {\n        self.lock.withLock {\n            self.underlying.keys.contains(key)\n        }\n    }\n\n    public func map<T>(_ transform: ((key: Key, value: Value)) throws -> T) rethrows -> [T] {\n        try self.lock.withLock {\n            try self.underlying.map(transform)\n        }\n    }\n\n    public func mapValues<T>(_ transform: (Value) throws -> T) rethrows -> [Key: T] {\n        try self.lock.withLock {\n            try self.underlying.mapValues(transform)\n        }\n    }\n}\n\nextension ThreadSafeKeyValueStore: @unchecked Sendable where Key: Sendable, Value: Sendable {}\n"
  },
  {
    "path": "Sources/Basics/Concurrency/ThrowingDefer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Runs a cleanup closure (`deferred`) after a given `work` closure,\n/// making sure `deferred` is run also when `work` throws an error.\n/// - Parameters:\n///   - work: The work that should be performed. Will always be executed.\n///   - deferred: The cleanup that needs to be done in any case.\n/// - Throws: Any error thrown by `deferred` or `work` (in that order).\n/// - Returns: The result of `work`.\n/// - Note: If `work` **and** `deferred` throw an error,\n///         the one thrown by `deferred` is thrown from this function.\n/// - SeeAlso: ``withAsyncThrowing(do:defer:)``\npublic func withThrowing<T>(\n    do work: () throws -> T,\n    defer deferred: () throws -> Void\n) throws -> T {\n    do {\n        let result = try work()\n        try deferred()\n        return result\n    } catch {\n        try deferred()\n        throw error\n    }\n}\n\n/// Runs an async cleanup closure (`deferred`) after a given async `work` closure,\n/// making sure `deferred` is run also when `work` throws an error.\n/// - Parameters:\n///   - work: The work that should be performed. Will always be executed.\n///   - deferred: The cleanup that needs to be done in any case.\n/// - Throws: Any error thrown by `deferred` or `work` (in that order).\n/// - Returns: The result of `work`.\n/// - Note: If `work` **and** `deferred` throw an error,\n///         the one thrown by `deferred` is thrown from this function.\n/// - SeeAlso: ``withThrowing(do:defer:)``\npublic func withAsyncThrowing<T: Sendable>(\n    do work: @Sendable () async throws -> T,\n    defer deferred: @Sendable () async throws -> Void\n) async throws -> T {\n    do {\n        let result = try await work()\n        try await deferred()\n        return result\n    } catch {\n        try await deferred()\n        throw error\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Concurrency/TokenBucket.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nprivate import DequeModule\n\n/// Type modeled after a \"token bucket\" pattern, which is similar to a semaphore, but is built with\n/// Swift Concurrency primitives.\npublic actor TokenBucket {\n    private var tokens: Int\n    private var waiters: Deque<CheckedContinuation<Void, Never>>\n\n    public init(tokens: Int) {\n        self.tokens = tokens\n        self.waiters = Deque()\n    }\n\n    /// Executes an `async` closure immediately when a token is available.\n    /// Only the same number of closures will be executed concurrently as the number\n    /// of `tokens` passed to ``TokenBucket/init(tokens:)``, all subsequent\n    /// invocations of `withToken` will suspend until a \"free\" token is available.\n    /// - Parameter body: The closure to invoke when a token is available.\n    /// - Returns: Resulting value returned by `body`.\n    public func withToken<ReturnType: Sendable>(\n        _ body: @Sendable () async throws -> ReturnType\n    ) async rethrows -> ReturnType {\n        await self.getToken()\n        defer {\n            self.returnToken()\n        }\n\n        return try await body()\n    }\n\n    private func getToken() async {\n        if self.tokens > 0 {\n            self.tokens -= 1\n            return\n        }\n\n        await withCheckedContinuation {\n            self.waiters.append($0)\n        }\n    }\n\n    private func returnToken() {\n        if let nextWaiter = self.waiters.popFirst() {\n            nextWaiter.resume()\n        } else {\n            self.tokens += 1\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/DispatchTimeInterval+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Dispatch\nimport struct Foundation.TimeInterval\n\nextension DispatchTimeInterval {\n    public func timeInterval() -> TimeInterval? {\n        switch self {\n        case .seconds(let value):\n            return Double(value)\n        case .milliseconds(let value):\n            return Double(value) / 1000\n        case .microseconds(let value):\n            return Double(value) / 1_000_000\n        case .nanoseconds(let value):\n            return Double(value) / 1_000_000_000\n        default:\n            return nil\n        }\n    }\n\n    public func nanoseconds() -> Int? {\n        switch self {\n        case .seconds(let value):\n            return value.multipliedReportingOverflow(by: 1_000_000_000).partialValue\n        case .milliseconds(let value):\n            return value.multipliedReportingOverflow(by: 1_000_000).partialValue\n        case .microseconds(let value):\n            return value.multipliedReportingOverflow(by: 1000).partialValue\n        case .nanoseconds(let value):\n            return value\n        default:\n            return nil\n        }\n    }\n\n    public func milliseconds() -> Int? {\n        switch self {\n        case .seconds(let value):\n            return value.multipliedReportingOverflow(by: 1000).partialValue\n        case .milliseconds(let value):\n            return value\n        case .microseconds(let value):\n            return Int(Double(value) / 1000)\n        case .nanoseconds(let value):\n            return Int(Double(value) / 1_000_000)\n        default:\n            return nil\n        }\n    }\n\n    public func seconds() -> Int? {\n        switch self {\n        case .seconds(let value):\n            return value\n        case .milliseconds(let value):\n            return Int(Double(value) / 1000)\n        case .microseconds(let value):\n            return Int(Double(value) / 1_000_000)\n        case .nanoseconds(let value):\n            return Int(Double(value) / 1_000_000_000)\n        default:\n            return nil\n        }\n    }\n\n    public var descriptionInSeconds: String {\n        switch self {\n        case .seconds(let value):\n            return \"\\(value)s\"\n        case .milliseconds(let value):\n            return String(format: \"%.2f\", Double(value) / Double(1000)) + \"s\"\n        case .microseconds(let value):\n            return String(format: \"%.2f\", Double(value) / Double(1_000_000)) + \"s\"\n        case .nanoseconds(let value):\n            return String(format: \"%.2f\", Double(value) / Double(1_000_000_000)) + \"s\"\n        case .never:\n            return \"n/a\"\n        #if canImport(Darwin)\n        @unknown default:\n            return \"n/a\"\n        #endif\n        }\n    }\n}\n\n// remove when available to all platforms\n#if os(Linux) || os(Windows) || os(Android) || os(OpenBSD) || os(FreeBSD)\nextension DispatchTime {\n    public func distance(to: DispatchTime) -> DispatchTimeInterval {\n        let final = to.uptimeNanoseconds\n        let point = self.uptimeNanoseconds\n        let duration = Int64(bitPattern: final.subtractingReportingOverflow(point).partialValue)\n        return .nanoseconds(duration >= Int.max ? Int.max : Int(duration))\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Basics/Environment/Environment.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if canImport(Glibc)\nimport Glibc\n#elseif canImport(Musl)\nimport Musl\n#elseif os(Windows)\nimport CRT\nimport WinSDK\n#elseif canImport(Android)\nimport Android\n#else\nimport Darwin.C\n#endif\n\n// FIXME: Use Synchronization.Mutex when available\nprivate final class Mutex<T>: @unchecked Sendable {\n    var lock: NSLock\n    var value: T\n\n    init(value: T) {\n        self.lock = .init()\n        self.value = value\n    }\n\n    func withLock<U>(_ body: (inout T) -> U) -> U {\n        self.lock.lock()\n        defer { self.lock.unlock() }\n        return body(&self.value)\n    }\n}\n\n// FIXME: This should come from Foundation\n// FIXME: package (public required by users)\npublic struct Environment {\n    var storage: [EnvironmentKey: String]\n}\n\n// MARK: - Accessors\n\nextension Environment {\n    package init() {\n        self.storage = .init()\n    }\n\n    package subscript(_ key: EnvironmentKey) -> String? {\n        _read { yield self.storage[key] }\n        _modify { yield &self.storage[key] }\n    }\n}\n\n// MARK: - Conversions between Dictionary<String, String>\n\nextension Environment {\n    @_spi(SwiftPMInternal)\n    public init(_ dictionary: [String: String]) {\n        self.storage = .init()\n        let sorted = dictionary.sorted { $0.key < $1.key }\n        for (key, value) in sorted {\n            self.storage[.init(key)] = value\n        }\n    }\n}\n\nextension [String: String] {\n    @_spi(SwiftPMInternal)\n    public init(_ environment: Environment) {\n        self.init()\n        let sorted = environment.sorted { $0.key < $1.key }\n        for (key, value) in sorted {\n            self[key.rawValue] = value\n        }\n    }\n}\n\n// MARK: - Path Modification\n\nextension Environment {\n    package mutating func prependPath(key: EnvironmentKey, value: String) {\n        guard !value.isEmpty else { return }\n        if let existing = self[key] {\n            self[key] = \"\\(value)\\(Self.pathEntryDelimiter)\\(existing)\"\n        } else {\n            self[key] = value\n        }\n    }\n\n    package mutating func appendPath(key: EnvironmentKey, value: String) {\n        guard !value.isEmpty else { return }\n        if let existing = self[key] {\n            self[key] = \"\\(existing)\\(Self.pathEntryDelimiter)\\(value)\"\n        } else {\n            self[key] = value\n        }\n    }\n\n    package static var pathEntryDelimiter: String {\n        #if os(Windows)\n        \";\"\n        #else\n        \":\"\n        #endif\n    }\n}\n\n// MARK: - Global Environment\n\nextension Environment {\n    fileprivate static let _cachedCurrent = Mutex<Self?>(value: nil)\n\n    /// Vends a copy of the current process's environment variables.\n    ///\n    /// Mutations to the current process's global environment are not reflected\n    /// in the returned value.\n    public static var current: Self {\n        Self._cachedCurrent.withLock { cachedValue in\n            if let cachedValue = cachedValue {\n                return cachedValue\n            } else {\n                let current = Self(ProcessInfo.processInfo.environment)\n                cachedValue = current\n                return current\n            }\n        }\n    }\n\n    /// Temporary override environment variables\n    ///\n    /// WARNING! This method is not thread-safe. POSIX environments are shared\n    /// between threads. This means that when this method is called simultaneously\n    /// from different threads, the environment will neither be setup nor restored\n    /// correctly.\n    package static func makeCustom<T>(\n        _ environment: Self,\n        body: () async throws -> T\n    ) async throws -> T {\n        let current = Self.current\n        let state = environment.storage.keys.map { ($0, current[$0]) }\n        let restore = {\n            for (key, value) in state {\n                try Self.set(key: key, value: value)\n            }\n        }\n        let returnValue: T\n        do {\n            for (key, value) in environment {\n                try Self.set(key: key, value: value)\n            }\n            returnValue = try await body()\n        } catch {\n            try? restore()\n            throw error\n        }\n        try restore()\n        return returnValue\n    }\n\n    /// Temporary override environment variables\n    ///\n    /// WARNING! This method is not thread-safe. POSIX environments are shared\n    /// between threads. This means that when this method is called simultaneously\n    /// from different threads, the environment will neither be setup nor restored\n    /// correctly.\n    package static func makeCustom<T>(\n        _ environment: Self,\n        body: () throws -> T\n    ) throws -> T {\n        let current = Self.current\n        let state = environment.storage.keys.map { ($0, current[$0]) }\n        let restore = {\n            for (key, value) in state {\n                try Self.set(key: key, value: value)\n            }\n        }\n        let returnValue: T\n        do {\n            for (key, value) in environment {\n                try Self.set(key: key, value: value)\n            }\n            returnValue = try body()\n        } catch {\n            try? restore()\n            throw error\n        }\n        try restore()\n        return returnValue\n    }\n\n    struct UpdateEnvironmentError: CustomStringConvertible, Error {\n        var function: StaticString\n        var code: Int32\n        var description: String { \"\\(self.function) returned \\(self.code)\" }\n    }\n\n    /// Modifies the process's global environment.\n    ///\n    /// > Important: This operation is _not_ concurrency safe.\n    package static func set(key: EnvironmentKey, value: String?) throws {\n        #if os(Windows)\n        func _SetEnvironmentVariableW(_ key: String, _ value: String?) -> Bool {\n            key.withCString(encodedAs: UTF16.self) { key in\n                if let value {\n                    value.withCString(encodedAs: UTF16.self) { value in\n                        SetEnvironmentVariableW(key, value)\n                    }\n                } else {\n                    SetEnvironmentVariableW(key, nil)\n                }\n            }\n        }\n        #endif\n\n        // Invalidate cached value after mutating the global environment.\n        // This is potentially overly safe because we may not need to invalidate\n        // the cache if the mutation fails. However this approach is easier to\n        // read and reason about.\n        defer { Self._cachedCurrent.withLock { $0 = nil } }\n        if let value = value {\n            #if os(Windows)\n            guard _SetEnvironmentVariableW(key.rawValue, value) else {\n                throw UpdateEnvironmentError(\n                    function: \"SetEnvironmentVariableW\",\n                    code: Int32(GetLastError())\n                )\n            }\n            guard _putenv(\"\\(key)=\\(value)\") == 0 else {\n                throw UpdateEnvironmentError(\n                    function: \"_putenv\",\n                    code: Int32(GetLastError())\n                )\n            }\n            #else\n            guard setenv(key.rawValue, value, 1) == 0 else {\n                throw UpdateEnvironmentError(\n                    function: \"setenv\",\n                    code: errno\n                )\n            }\n            #endif\n        } else {\n            #if os(Windows)\n            guard _SetEnvironmentVariableW(key.rawValue, nil) else {\n                throw UpdateEnvironmentError(\n                    function: \"SetEnvironmentVariableW\",\n                    code: Int32(GetLastError())\n                )\n            }\n            guard _putenv(\"\\(key)=\") == 0 else {\n                throw UpdateEnvironmentError(\n                    function: \"_putenv\",\n                    code: Int32(GetLastError())\n                )\n            }\n            #else\n            guard unsetenv(key.rawValue) == 0 else {\n                throw UpdateEnvironmentError(\n                    function: \"unsetenv\",\n                    code: errno\n                )\n            }\n            #endif\n        }\n    }\n}\n\n// MARK: - Cachable Keys\n\nextension Environment {\n    /// Returns a copy of `self` with known non-cacheable keys removed.\n    ///\n    /// - Issue: rdar://107029374\n    package var cachable: Environment {\n        var cachable = Environment()\n        for (key, value) in self {\n            if !EnvironmentKey.nonCachable.contains(key) {\n                cachable[key] = value\n            }\n        }\n        return cachable\n    }\n}\n\n// MARK: - Protocol Conformances\n\nextension Environment: Collection {\n    public struct Index: Comparable {\n        public static func < (lhs: Self, rhs: Self) -> Bool {\n            lhs.underlying < rhs.underlying\n        }\n\n        var underlying: Dictionary<EnvironmentKey, String>.Index\n    }\n\n    public typealias Element = (key: EnvironmentKey, value: String)\n\n    public var startIndex: Index {\n        Index(underlying: self.storage.startIndex)\n    }\n\n    public var endIndex: Index {\n        Index(underlying: self.storage.endIndex)\n    }\n\n    public subscript(index: Index) -> Element {\n        self.storage[index.underlying]\n    }\n\n    public func index(after index: Self.Index) -> Self.Index {\n        Index(underlying: self.storage.index(after: index.underlying))\n    }\n}\n\nextension Environment: CustomStringConvertible {\n    public var description: String {\n        let body = self\n            .sorted { $0.key < $1.key }\n            .map { \"\\\"\\($0.rawValue)=\\($1)\\\"\" }\n            .joined(separator: \", \")\n        return \"[\\(body)]\"\n    }\n}\n\nextension Environment: Encodable {\n    public func encode(to encoder: any Encoder) throws {\n        try self.storage.encode(to: encoder)\n    }\n}\n\nextension Environment: Equatable {}\n\nextension Environment: ExpressibleByDictionaryLiteral {\n    public typealias Key = EnvironmentKey\n    public typealias Value = String\n\n    public init(dictionaryLiteral elements: (Key, Value)...) {\n        self.storage = .init()\n        for (key, value) in elements {\n            self.storage[key] = value\n        }\n    }\n}\n\nextension Environment: Decodable {\n    public init(from decoder: any Decoder) throws {\n        self.storage = try .init(from: decoder)\n    }\n}\n\nextension Environment: Sendable {}\n"
  },
  {
    "path": "Sources/Basics/Environment/EnvironmentKey.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A key used to access values in an ``Environment``.\n///\n/// This type respects the compiled platform's case sensitivity requirements.\npublic struct EnvironmentKey {\n    public var rawValue: String\n\n    package init(_ rawValue: String) {\n        self.rawValue = rawValue\n    }\n}\n\nextension EnvironmentKey {\n    package static let path: Self = \"PATH\"\n\n    package static var libraryPath: Self {\n        #if os(Windows)\n        path\n        #elseif canImport(Darwin)\n        \"DYLD_LIBRARY_PATH\"\n        #else\n        \"LD_LIBRARY_PATH\"\n        #endif\n    }\n\n    /// A set of known keys which should not be included in cache keys.\n    package static let nonCachable: Set<Self> = [\n        \"TERM\",\n        \"TERM_PROGRAM\",\n        \"TERM_PROGRAM_VERSION\",\n        \"TERM_SESSION_ID\",\n        \"ITERM_PROFILE\",\n        \"ITERM_SESSION_ID\",\n        \"SECURITYSESSIONID\",\n        \"LaunchInstanceID\",\n        \"LC_TERMINAL\",\n        \"LC_TERMINAL_VERSION\",\n        \"CLICOLOR\",\n        \"LS_COLORS\",\n        \"VSCODE_IPC_HOOK_CLI\",\n        \"HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET\",\n        \"SSH_AUTH_SOCK\",\n    ]\n}\n\nextension EnvironmentKey: CodingKeyRepresentable {}\n\nextension EnvironmentKey: Comparable {\n    public static func < (lhs: Self, rhs: Self) -> Bool {\n        // Even on windows use a stable sort order.\n        lhs.rawValue < rhs.rawValue\n    }\n}\n\nextension EnvironmentKey: CustomStringConvertible {\n    public var description: String { self.rawValue }\n}\n\nextension EnvironmentKey: Encodable {\n    public func encode(to encoder: any Encoder) throws {\n        try self.rawValue.encode(to: encoder)\n    }\n}\n\nextension EnvironmentKey: Equatable {\n    public static func == (_ lhs: Self, _ rhs: Self) -> Bool {\n        #if os(Windows)\n        lhs.rawValue.lowercased() == rhs.rawValue.lowercased()\n        #else\n        lhs.rawValue == rhs.rawValue\n        #endif\n    }\n}\n\nextension EnvironmentKey: ExpressibleByStringLiteral {\n    public init(stringLiteral rawValue: String) {\n        self.init(rawValue)\n    }\n}\n\nextension EnvironmentKey: Decodable {\n    public init(from decoder: any Decoder) throws {\n        self.rawValue = try String(from: decoder)\n    }\n}\n\nextension EnvironmentKey: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        #if os(Windows)\n        self.rawValue.lowercased().hash(into: &hasher)\n        #else\n        self.rawValue.hash(into: &hasher)\n        #endif\n    }\n}\n\nextension EnvironmentKey: RawRepresentable {\n    public init?(rawValue: String) {\n        self.rawValue = rawValue\n    }\n}\n\nextension EnvironmentKey: Sendable {}\n"
  },
  {
    "path": "Sources/Basics/Environment/EnvironmentShims.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCBasic.ProcessEnvironmentBlock\n\nimport Dispatch\n\n// FIXME: remove ProcessEnvironmentBlockShims\n// only needed outside this module for Git\nextension Environment {\n    @_spi(ProcessEnvironmentBlockShim)\n    public init(_ processEnvironmentBlock: ProcessEnvironmentBlock) {\n        self.init()\n        for (key, value) in processEnvironmentBlock {\n            self[.init(key.value)] = value\n        }\n    }\n}\n\nextension ProcessEnvironmentBlock {\n    @_spi(ProcessEnvironmentBlockShim)\n    public init(_ environment: Environment) {\n        self.init()\n        for (key, value) in environment {\n            self[.init(key.rawValue)] = value\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Errors.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport protocol Foundation.LocalizedError\nimport class Foundation.NSError\nimport var Foundation.NSLocalizedDescriptionKey\nimport struct TSCBasic.StringError\n\npublic typealias StringError = TSCBasic.StringError\n\npublic struct InternalError: Error {\n    private let description: String\n    public init(_ description: String) {\n        assertionFailure(description)\n        self.description =\n            \"Internal error. Please file a bug at https://github.com/swiftlang/swift-package-manager/issues with this info. \\(description)\"\n    }\n}\n\n/// Wraps another error and provides additional context when printed.\n/// This is useful for user facing errors that need to provide a user friendly message\n/// explaning why an error might have occured, while still showing the detailed underlying error.\npublic struct ErrorWithContext<E: Error>: Error {\n    public let error: E\n    public let context: String\n    public init(_ error: E, _ context: String) {\n        self.error = error\n        self.context = context\n    }\n}\n\nextension ErrorWithContext: LocalizedError {\n    public var errorDescription: String? {\n        return (context.split(separator: \"\\n\") + [error.interpolationDescription])\n            .map { \"\\t\\($0)\" }\n            .joined(separator: \"\\n\")\n    }\n}\n\nextension Error {\n    public var interpolationDescription: String {\n        switch self {\n        // special case because `LocalizedError` conversion will hide the underlying error\n        case let _error as DecodingError:\n            return \"\\(_error)\"\n        case let _error as LocalizedError:\n            var description = _error.errorDescription ?? _error.localizedDescription\n            if let recoverySuggestion = _error.recoverySuggestion {\n                description += \". \\(recoverySuggestion)\"\n            }\n            return description\n        case let _error as NSError:\n            guard var description = _error.userInfo[NSLocalizedDescriptionKey] as? String else {\n                return \"\\(self)\"\n            }\n\n            if let localizedRecoverySuggestion = _error.localizedRecoverySuggestion {\n                description += \". \\(localizedRecoverySuggestion)\"\n            }\n            return description\n        default:\n            return \"\\(self)\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/AbsolutePath.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\nimport struct TSCBasic.AbsolutePath\n\n// public for transition\npublic typealias TSCAbsolutePath = TSCBasic.AbsolutePath\n\n/// Represents an absolute file system path, independently of what (or whether\n/// anything at all) exists at that path in the file system at any given time.\n/// An absolute path always starts with a `/` character, and holds a normalized\n/// string representation.  This normalization is strictly syntactic, and does\n/// not access the file system in any way.\n///\n/// The absolute path string is normalized by:\n/// - Collapsing `..` path components\n/// - Removing `.` path components\n/// - Removing any trailing path separator\n/// - Removing any redundant path separators\n///\n/// This string manipulation may change the meaning of a path if any of the\n/// path components are symbolic links on disk.  However, the file system is\n/// never accessed in any way when initializing an AbsolutePath.\n///\n/// Note that `~` (home directory resolution) is *not* done as part of path\n/// normalization, because it is normally the responsibility of the shell and\n/// not the program being invoked (e.g. when invoking `cd ~`, it is the shell\n/// that evaluates the tilde; the `cd` command receives an absolute path).\npublic struct AbsolutePath: Hashable, Sendable {\n    /// Root directory (whose string representation is just a path separator).\n    public static let root = Self(TSCAbsolutePath.root)\n\n    internal let underlying: TSCAbsolutePath\n\n    // public for transition\n    public init(_ underlying: TSCAbsolutePath) {\n        self.underlying = underlying\n    }\n\n    /// Initializes the AbsolutePath from `absStr`, which must be an absolute\n    /// path (i.e. it must begin with a path separator; this initializer does\n    /// not interpret leading `~` characters as home directory specifiers).\n    /// The input string will be normalized if needed, as described in the\n    /// documentation for AbsolutePath.\n    public init(validating pathString: String) throws {\n        self.underlying = try .init(validating: pathString)\n    }\n\n    /// Initializes an AbsolutePath from a string that may be either absolute\n    /// or relative; if relative, `basePath` is used as the anchor; if absolute,\n    /// it is used as is, and in this case `basePath` is ignored.\n    public init(validating pathString: String, relativeTo basePath: AbsolutePath) throws {\n        self.underlying = try .init(validating: pathString, relativeTo: basePath.underlying)\n    }\n\n    /// Initializes the AbsolutePath by concatenating a relative path to an\n    /// existing absolute path, and renormalizing if necessary.\n    public init(_ absolutePath: AbsolutePath, _ relativeTo: RelativePath) {\n        self.underlying = .init(absolutePath.underlying, relativeTo.underlying)\n    }\n\n    /// Convenience initializer that appends a string to a relative path.\n    public init(_ absolutePath: AbsolutePath, validating relativePathString: String) throws {\n        try self.init(absolutePath, RelativePath(validating: relativePathString))\n    }\n\n    /// Directory component.  An absolute path always has a non-empty directory\n    /// component (the directory component of the root path is the root itself).\n    public var dirname: String {\n        self.underlying.dirname\n    }\n\n    /// Last path component (including the suffix, if any).  it is never empty.\n    public var basename: String {\n        self.underlying.basename\n    }\n\n    /// Returns the basename without the extension.\n    public var basenameWithoutExt: String {\n        self.underlying.basenameWithoutExt\n    }\n\n    /// Suffix (including leading `.` character) if any.  Note that a basename\n    /// that starts with a `.` character is not considered a suffix, nor is a\n    /// trailing `.` character.\n    public var suffix: String? {\n        self.underlying.suffix\n    }\n\n    /// Extension of the give path's basename. This follow same rules as\n    /// suffix except that it doesn't include leading `.` character.\n    public var `extension`: String? {\n        self.underlying.extension\n    }\n\n    /// Absolute path of parent directory.  This always returns a path, because\n    /// every directory has a parent (the parent directory of the root directory\n    /// is considered to be the root directory itself).\n    public var parentDirectory: AbsolutePath {\n        Self(self.underlying.parentDirectory)\n    }\n\n    /// True if the path is the root directory.\n    public var isRoot: Bool {\n        self.underlying.isRoot\n    }\n\n    /// NOTE: We will most likely want to add other `appending()` methods, such\n    ///       as `appending(suffix:)`, and also perhaps `replacing()` methods,\n    ///       such as `replacing(suffix:)` or `replacing(basename:)` for some\n    ///       of the more common path operations.\n\n    /// NOTE: We may want to consider adding operators such as `+` for appending\n    ///       a path component.\n\n    /// NOTE: We will want to add a method to return the lowest common ancestor\n    ///       path.\n\n    /// Normalized string representation (the normalization rules are described\n    /// in the documentation of the initializer).  This string is never empty.\n    public var pathString: String {\n        self.underlying.pathString\n    }\n}\n\nextension AbsolutePath {\n    /// Returns an array of strings that make up the path components of the\n    /// absolute path.  This is the same sequence of strings as the basenames\n    /// of each successive path component, starting from the root.  Therefore\n    /// the first path component of an absolute path is always `/`.\n    public var components: [String] {\n        self.underlying.components\n    }\n\n    /// Returns the absolute path with the relative path applied.\n    public func appending(_ relativePath: RelativePath) -> AbsolutePath {\n        Self(self.underlying.appending(relativePath.underlying))\n    }\n\n    /// Returns the absolute path with an additional literal component appended.\n    ///\n    /// This method accepts pseudo-path like '.' or '..', but should not contain \"/\".\n    public func appending(component: String) -> AbsolutePath {\n        Self(self.underlying.appending(component: component))\n    }\n\n    /// Returns the absolute path with additional literal components appended.\n    ///\n    /// This method should only be used in cases where the input is guaranteed\n    /// to be a valid path component (i.e., it cannot be empty, contain a path\n    /// separator, or be a pseudo-path like '.' or '..').\n    public func appending(components: [String]) -> AbsolutePath {\n        Self(self.underlying.appending(components: components))\n    }\n\n    /// Returns the absolute path with additional literal components appended.\n    ///\n    /// This method should only be used in cases where the input is guaranteed\n    /// to be a valid path component (i.e., it cannot be empty, contain a path\n    /// separator, or be a pseudo-path like '.' or '..').\n    public func appending(components: String...) -> AbsolutePath {\n        Self(self.underlying.appending(components: components))\n    }\n\n    /// Returns the absolute path with additional literal components appended.\n    ///\n    /// This method should only be used in cases where the input is guaranteed\n    /// to be a valid path component (i.e., it cannot be empty, contain a path\n    /// separator, or be a pseudo-path like '.' or '..').\n    public func appending(_ component: String) -> AbsolutePath {\n        self.appending(component: component)\n    }\n\n    /// Returns the absolute path with additional literal components appended.\n    ///\n    /// This method should only be used in cases where the input is guaranteed\n    /// to be a valid path component (i.e., it cannot be empty, contain a path\n    /// separator, or be a pseudo-path like '.' or '..').\n    public func appending(_ components: String...) -> AbsolutePath {\n        self.appending(components: components)\n    }\n\n    /// Returns the absolute path with additional extension appended.\n    ///\n    public func appending(extension: String) -> AbsolutePath {\n        guard !self.isRoot else { return self }\n        let `extension` = `extension`.spm_dropPrefix(\".\")\n        return self.parentDirectory.appending(\"\\(basename).\\(`extension`)\")\n    }\n}\n\nextension AbsolutePath {\n    /// Returns a relative path that, when concatenated to `base`, yields the\n    /// callee path itself.  If `base` is not an ancestor of the callee, the\n    /// returned path will begin with one or more `..` path components.\n    ///\n    /// Because both paths are absolute, they always have a common ancestor\n    /// (the root path, if nothing else).  Therefore, any path can be made\n    /// relative to any other path by using a sufficient number of `..` path\n    /// components.\n    ///\n    /// This method is strictly syntactic and does not access the file system\n    /// in any way.  Therefore, it does not take symbolic links into account.\n    public func relative(to base: AbsolutePath) -> RelativePath {\n        RelativePath(self.underlying.relative(to: base.underlying))\n    }\n\n    /// Returns true if the path is an ancestor of the given path.\n    ///\n    /// This method is strictly syntactic and does not access the file system\n    /// in any way.\n    public func isAncestor(of descendant: AbsolutePath) -> Bool {\n        self.underlying.isAncestor(of: descendant.underlying)\n    }\n\n    /// Returns true if the path is an ancestor of or equal to the given path.\n    ///\n    /// This method is strictly syntactic and does not access the file system\n    /// in any way.\n    public func isAncestorOfOrEqual(to descendant: AbsolutePath) -> Bool {\n        self.underlying.isAncestorOfOrEqual(to: descendant.underlying)\n    }\n\n    /// Returns true if the path is a descendant of the given path.\n    ///\n    /// This method is strictly syntactic and does not access the file system\n    /// in any way.\n    public func isDescendant(of ancestor: AbsolutePath) -> Bool {\n        self.underlying.isDescendant(of: ancestor.underlying)\n    }\n\n    /// Returns true if the path is a descendant of or equal to the given path.\n    ///\n    /// This method is strictly syntactic and does not access the file system\n    /// in any way.\n    public func isDescendantOfOrEqual(to ancestor: AbsolutePath) -> Bool {\n        self.underlying.isDescendantOfOrEqual(to: ancestor.underlying)\n    }\n}\n\nextension AbsolutePath {\n    /// Unlike ``AbsolutePath//extension``, this property returns all characters after the first `.` character in a\n    /// filename. If no dot character is present in the filename or first dot is the last character, `nil` is returned.\n    public var allExtensions: [String]? {\n        guard let firstDot = self.basename.firstIndex(of: \".\") else {\n            return nil\n        }\n\n        var extensions = String(self.basename[firstDot ..< self.basename.endIndex])\n\n        guard extensions.count > 1 else {\n            return nil\n        }\n\n        extensions.removeFirst()\n\n        return extensions.split(separator: \".\").map(String.init)\n    }\n\n    /// Returns the basename dropping any possible  extension.\n    public var basenameWithoutAnyExtension: String {\n        var basename = self.basename\n        if let index = basename.firstIndex(of: \".\") {\n            basename.removeSubrange(index ..< basename.endIndex)\n        }\n        return String(basename)\n    }\n}\n\nextension AbsolutePath: Codable {\n    public func encode(to encoder: Encoder) throws {\n        try self.underlying.encode(to: encoder)\n    }\n\n    public init(from decoder: Decoder) throws {\n        try self = .init(TSCAbsolutePath(from: decoder))\n    }\n}\n\n// Make absolute paths Comparable.\nextension AbsolutePath: Comparable {\n    public static func < (lhs: AbsolutePath, rhs: AbsolutePath) -> Bool {\n        lhs.underlying < rhs.underlying\n    }\n}\n\n/// Make absolute paths CustomStringConvertible and CustomDebugStringConvertible.\nextension AbsolutePath: CustomStringConvertible, CustomDebugStringConvertible {\n    public var description: String {\n        self.underlying.description\n    }\n\n    public var debugDescription: String {\n        self.underlying.debugDescription\n    }\n}\n\nextension AbsolutePath {\n    public var asURL: Foundation.URL {\n        self.underlying.asURL\n    }\n}\n\nextension AbsolutePath {\n    /// Returns a path suitable for display to the user (if possible, it is made\n    /// to be relative to the current working directory).\n    public func prettyPath(cwd: AbsolutePath? = localFileSystem.currentWorkingDirectory) -> String {\n        self.underlying.prettyPath(cwd: cwd?.underlying)\n    }\n}\n\nextension AbsolutePath {\n    public var escapedPathString: String {\n        self.pathString.replacing(\"\\\\\", with: \"\\\\\\\\\")\n    }\n}\n\nextension TSCAbsolutePath {\n    public init(_ path: AbsolutePath) {\n        self = path.underlying\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/CommonParentDirectory.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2026 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Returns the common parent directory of the given absolute paths.\n///\n/// This function finds the deepest directory that is an ancestor of all the provided paths.\n/// If the paths have no common ancestor other than the root directory, it returns the root.\n/// If the array is empty, it returns the root directory.\n///\n/// - Parameter paths: An array of absolute paths to find the common parent for\n/// - Returns: The common parent directory as an AbsolutePath\n///\n/// Examples:\n/// - `[\"/a/b/c\", \"/a/b/d\"]` → `\"/a/b\"`\n/// - `[\"/usr/local/bin\", \"/usr/local/lib\"]` → `\"/usr/local\"`\n/// - `[\"/a/b\", \"/x/y\"]` → `\"/\"`\n/// - `[]` → `\"/\"`\npublic func getCommonParentDirectory(paths: [AbsolutePath]) throws-> AbsolutePath {\n    // Handle empty array case\n    guard !paths.isEmpty else {\n        return AbsolutePath.root\n    }\n\n    // Handle single path case\n    guard paths.count > 1 else {\n        return paths[0]\n    }\n\n    // Get the components of all paths\n    let allComponents = paths.map { $0.components }\n\n    // Find the minimum length to avoid index out of bounds\n    let minLength = allComponents.map { $0.count }.min() ?? 0\n\n    // Find the common prefix by comparing components at each position\n    var commonComponents: [String] = []\n\n    for index in 0..<minLength {\n        let component = allComponents[0][index]\n\n        // Check if this component is the same in all paths\n        let isCommon = allComponents.allSatisfy { $0[index] == component }\n\n        if isCommon {\n            commonComponents.append(component)\n        } else {\n            // Stop at the first different component\n            break\n        }\n    }\n\n    // Handle the case where there are no common components beyond root\n    guard !commonComponents.isEmpty else {\n        return AbsolutePath.root\n    }\n\n    // Build the result path from common components\n    if commonComponents.count == 1 && commonComponents[0] == \"/\" {\n        return AbsolutePath.root\n    }\n\n    // Join the common components back into a path string\n    let commonPath = commonComponents.joined(separator: \"/\")\n\n    // Handle the case where the first component is the root separator\n    if commonComponents[0] == \"/\" {\n        if commonComponents.count == 1 {\n            return AbsolutePath.root\n        }\n        // Skip the first \"/\" component since AbsolutePath constructor expects paths to start with \"/\"\n        let pathWithoutLeadingSlash = commonComponents.dropFirst().joined(separator: \"/\")\n        return try AbsolutePath(validating: \"/\" + pathWithoutLeadingSlash)\n    }\n\n    if !commonPath.starts(with: \"/\") {\n        return try AbsolutePath(validating: \"/\\(commonPath)\")\n    }\n    return try AbsolutePath(validating: commonPath)\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/FileSystem+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.Data\nimport class Foundation.FileManager\nimport struct Foundation.UUID\n\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.FileInfo\nimport class TSCBasic.FileLock\nimport enum TSCBasic.FileMode\nimport protocol TSCBasic.FileSystem\nimport enum TSCBasic.FileSystemAttribute\nimport var TSCBasic.localFileSystem\nimport protocol TSCBasic.WritableByteStream\n\npublic typealias FileSystem = TSCBasic.FileSystem\npublic let localFileSystem = TSCBasic.localFileSystem\n\n// MARK: - Custom path\n\nextension FileSystem {\n    /// Check whether the given path exists and is accessible.\n    public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {\n        self.exists(path.underlying, followSymlink: followSymlink)\n    }\n\n    /// exists override with default value.\n    public func exists(_ path: AbsolutePath) -> Bool {\n        self.exists(path.underlying)\n    }\n\n    /// Check whether the given path is accessible and a directory.\n    public func isDirectory(_ path: AbsolutePath) -> Bool {\n        self.isDirectory(path.underlying)\n    }\n\n    /// Check whether the given path is accessible and a file.\n    public func isFile(_ path: AbsolutePath) -> Bool {\n        self.isFile(path.underlying)\n    }\n\n    /// Check whether the given path is an accessible and executable file.\n    public func isExecutableFile(_ path: AbsolutePath) -> Bool {\n        self.isExecutableFile(path.underlying)\n    }\n\n    /// Check whether the given path is accessible and is a symbolic link.\n    public func isSymlink(_ path: AbsolutePath) -> Bool {\n        self.isSymlink(path.underlying)\n    }\n\n    /// Check whether the given path is accessible and readable.\n    public func isReadable(_ path: AbsolutePath) -> Bool {\n        self.isReadable(path.underlying)\n    }\n\n    /// Check whether the given path is accessible and writable.\n    public func isWritable(_ path: AbsolutePath) -> Bool {\n        self.isWritable(path.underlying)\n    }\n\n    /// Returns `true` if a given path has a quarantine attribute applied if when file system supports this attribute.\n    /// Returns `false` if such attribute is not applied or it isn't supported.\n    public func hasAttribute(_ name: FileSystemAttribute, _ path: AbsolutePath) -> Bool {\n        self.hasAttribute(name, path.underlying)\n    }\n\n    /// Get the contents of the given directory, in an undefined order.\n    public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {\n        try self.getDirectoryContents(path.underlying)\n    }\n\n    /// Get the current working directory (similar to `getcwd(3)`), which can be\n    /// different for different (virtualized) implementations of a FileSystem.\n    /// The current working directory can be empty if e.g. the directory became\n    /// unavailable while the current process was still working in it.\n    /// This follows the POSIX `getcwd(3)` semantics.\n    public var currentWorkingDirectory: AbsolutePath? {\n        self.currentWorkingDirectory.flatMap { AbsolutePath($0) }\n    }\n\n    /// Change the current working directory.\n    /// - Parameters:\n    ///   - path: The path to the directory to change the current working directory to.\n    public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {\n        try self.changeCurrentWorkingDirectory(to: path.underlying)\n    }\n\n    /// Get the home directory of current user\n    public var homeDirectory: AbsolutePath {\n        get throws {\n            try AbsolutePath(self.homeDirectory)\n        }\n    }\n\n    /// Get the caches directory of current user\n    public var cachesDirectory: AbsolutePath? {\n        self.cachesDirectory.flatMap { AbsolutePath($0) }\n    }\n\n    /// Get the temp directory\n    public var tempDirectory: AbsolutePath {\n        get throws {\n            try AbsolutePath(self.tempDirectory)\n        }\n    }\n\n    /// Create the given directory.\n    public func createDirectory(_ path: AbsolutePath) throws {\n        try self.createDirectory(path.underlying)\n    }\n\n    /// Create the given directory.\n    ///\n    /// - recursive: If true, create missing parent directories if possible.\n    public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {\n        try self.createDirectory(path.underlying, recursive: recursive)\n    }\n\n    /// Creates a symbolic link of the source path at the target path\n    /// - Parameters:\n    ///   - path: The path at which to create the link.\n    ///   - destination: The path to which the link points to.\n    ///   - relative: If `relative` is true, the symlink contents will be a relative path, otherwise it will be\n    /// absolute.\n    public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws {\n        try self.createSymbolicLink(path.underlying, pointingAt: destination.underlying, relative: relative)\n    }\n\n    /// Get the contents of a file.\n    ///\n    /// - Returns: The file contents as bytes, or nil if missing.\n    public func readFileContents(_ path: AbsolutePath) throws -> ByteString {\n        try self.readFileContents(path.underlying)\n    }\n\n    /// Write the contents of a file.\n    public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {\n        try self.writeFileContents(path.underlying, bytes: bytes)\n    }\n\n    /// Write the contents of a file.\n    public func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {\n        try self.writeFileContents(path.underlying, bytes: bytes, atomically: atomically)\n    }\n\n    /// Write to a file from a stream producer.\n    public func writeFileContents(_ path: AbsolutePath, body: (WritableByteStream) -> Void) throws {\n        try self.writeFileContents(path.underlying, body: body)\n    }\n\n    /// Recursively deletes the file system entity at `path`.\n    ///\n    /// If there is no file system entity at `path`, this function does nothing (in particular, this is not considered\n    /// to be an error).\n    public func removeFileTree(_ path: AbsolutePath) throws {\n        try self.removeFileTree(path.underlying)\n    }\n\n    /// Change file mode.\n    public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {\n        try self.chmod(mode, path: path.underlying, options: options)\n    }\n\n    // Change file mode.\n    public func chmod(_ mode: FileMode, path: AbsolutePath) throws {\n        try self.chmod(mode, path: path.underlying)\n    }\n\n    /// Returns the file info of the given path.\n    ///\n    /// The method throws if the underlying stat call fails.\n    public func getFileInfo(_ path: AbsolutePath) throws -> FileInfo {\n        try self.getFileInfo(path.underlying)\n    }\n\n    /// Copy a file or directory.\n    public func copy(from source: AbsolutePath, to destination: AbsolutePath) throws {\n        try self.copy(from: source.underlying, to: destination.underlying)\n    }\n\n    /// Move a file or directory.\n    public func move(from source: AbsolutePath, to destination: AbsolutePath) throws {\n        try self.move(from: source.underlying, to: destination.underlying)\n    }\n\n    /// Execute the given block while holding the lock.\n    public func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool = true, _ body: () throws -> T) throws -> T {\n        try self.withLock(on: path.underlying, type: type, blocking: blocking, body)\n    }\n\n    /// Execute the given block while holding the lock.\n    public func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool = true, _ body: () async throws -> T) async throws -> T {\n        return try await FileLock.withLock(fileToLock: path.underlying, type: type, blocking: blocking, body: body)\n    }\n\n    /// Returns any known item replacement directories for a given path. These may be used by platform-specific\n    /// libraries to handle atomic file system operations, such as deletion.\n    func itemReplacementDirectories(for path: AbsolutePath) throws -> [AbsolutePath] {\n        return try self.itemReplacementDirectories(for: path.underlying).compactMap { AbsolutePath($0) }\n    }\n}\n\n// MARK: - user level\n\nextension FileSystem {\n    /// SwiftPM directory under user's home directory (~/.swiftpm)\n    /// or under $XDG_CONFIG_HOME/swiftpm if the environmental variable is defined\n    public var dotSwiftPM: AbsolutePath {\n        get throws {\n            if let configurationDirectory = Environment.current[\"XDG_CONFIG_HOME\"] {\n                return try AbsolutePath(validating: configurationDirectory).appending(\"swiftpm\")\n            } else {\n                return try self.homeDirectory.appending(\".swiftpm\")\n            }\n        }\n    }\n\n    private var idiomaticSwiftPMDirectory: AbsolutePath? {\n        get throws {\n            try FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first\n                .flatMap { try AbsolutePath(validating: $0.path) }?.appending(\"org.swift.swiftpm\")\n        }\n    }\n}\n\n// MARK: - cache\n\nextension FileSystem {\n    private var idiomaticUserCacheDirectory: AbsolutePath? {\n        // in TSC: FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)\n        self.cachesDirectory\n    }\n\n    /// SwiftPM cache directory under user's caches directory (if exists)\n    public var swiftPMCacheDirectory: AbsolutePath {\n        get throws {\n            if let path = self.idiomaticUserCacheDirectory {\n                return path.appending(\"org.swift.swiftpm\")\n            } else {\n                return try self.dotSwiftPMCachesDirectory\n            }\n        }\n    }\n\n    private var dotSwiftPMCachesDirectory: AbsolutePath {\n        get throws {\n            try self.dotSwiftPM.appending(\"cache\")\n        }\n    }\n}\n\nextension FileSystem {\n    public func getOrCreateSwiftPMCacheDirectory() throws -> AbsolutePath {\n        let idiomaticCacheDirectory = try self.swiftPMCacheDirectory\n        // Create idiomatic if necessary\n        if !self.exists(idiomaticCacheDirectory) {\n            try self.createDirectory(idiomaticCacheDirectory, recursive: true)\n        }\n        // Create ~/.swiftpm if necessary\n        if !self.exists(try self.dotSwiftPM) {\n            try self.createDirectory(self.dotSwiftPM, recursive: true)\n        }\n        // Create ~/.swiftpm/cache symlink if necessary\n        // locking ~/.swiftpm to protect from concurrent access\n        try self.withLock(on: self.dotSwiftPM, type: .exclusive) {\n            if !self.exists(try self.dotSwiftPMCachesDirectory, followSymlink: false) {\n                try self.createSymbolicLink(\n                    dotSwiftPMCachesDirectory,\n                    pointingAt: idiomaticCacheDirectory,\n                    relative: false\n                )\n            }\n        }\n        return idiomaticCacheDirectory\n    }\n}\n\nextension FileSystem {\n    private var dotSwiftPMInstalledBinsDir: AbsolutePath {\n        get throws {\n            try self.dotSwiftPM.appending(\"bin\")\n        }\n    }\n\n    public func getOrCreateSwiftPMInstalledBinariesDirectory() throws -> AbsolutePath {\n        let idiomaticInstalledBinariesDirectory = try self.dotSwiftPMInstalledBinsDir\n        // Create idiomatic if necessary\n        if !self.exists(idiomaticInstalledBinariesDirectory) {\n            try self.createDirectory(idiomaticInstalledBinariesDirectory, recursive: true)\n        }\n        // Create ~/.swiftpm if necessary\n        if !self.exists(try self.dotSwiftPM) {\n            try self.createDirectory(self.dotSwiftPM, recursive: true)\n        }\n        // Create ~/.swiftpm/bin symlink if necessary\n        // locking ~/.swiftpm to protect from concurrent access\n        try self.withLock(on: self.dotSwiftPM, type: .exclusive) {\n            if !self.exists(try self.dotSwiftPMInstalledBinsDir, followSymlink: false) {\n                try self.createSymbolicLink(\n                    self.dotSwiftPMInstalledBinsDir,\n                    pointingAt: idiomaticInstalledBinariesDirectory,\n                    relative: false\n                )\n            }\n        }\n        return idiomaticInstalledBinariesDirectory\n    }\n}\n\n// MARK: - configuration\n\nextension FileSystem {\n    /// SwiftPM config directory under user's config directory (if exists)\n    public var swiftPMConfigurationDirectory: AbsolutePath {\n        get throws {\n            if let path = try self.idiomaticSwiftPMDirectory {\n                return path.appending(\"configuration\")\n            } else {\n                return try self.dotSwiftPMConfigurationDirectory\n            }\n        }\n    }\n\n    private var dotSwiftPMConfigurationDirectory: AbsolutePath {\n        get throws {\n            try self.dotSwiftPM.appending(\"configuration\")\n        }\n    }\n}\n\nextension FileSystem {\n    public func getOrCreateSwiftPMConfigurationDirectory(warningHandler: @escaping (String) -> Void) throws\n        -> AbsolutePath\n    {\n        let idiomaticConfigurationDirectory = try self.swiftPMConfigurationDirectory\n\n        // temporary 5.6, remove on next version: transition from previous configuration location\n        if !self.exists(idiomaticConfigurationDirectory) {\n            try self.createDirectory(idiomaticConfigurationDirectory, recursive: true)\n        }\n\n        let handleExistingFiles = { (configurationFiles: [AbsolutePath]) in\n            for file in configurationFiles {\n                let destination = idiomaticConfigurationDirectory.appending(component: file.basename)\n                if !self.exists(destination) {\n                    try self.copy(from: file, to: destination)\n                } else {\n                    // Only emit a warning if source and destination file differ in their contents.\n                    let srcContents = try? self.readFileContents(file)\n                    let dstContents = try? self.readFileContents(destination)\n                    if srcContents != dstContents {\n                        warningHandler(\n                            \"Usage of \\(file) has been deprecated. Please delete it and use the new \\(destination) instead.\"\n                        )\n                    }\n                }\n            }\n        }\n\n        // in the case where ~/.swiftpm/configuration is not the idiomatic location (eg on macOS where its\n        // /Users/<user>/Library/org.swift.swiftpm/configuration)\n        if try idiomaticConfigurationDirectory != self.dotSwiftPMConfigurationDirectory {\n            // copy the configuration files from old location (eg /Users/<user>/Library/org.swift.swiftpm) to new one\n            // (eg /Users/<user>/Library/org.swift.swiftpm/configuration)\n            // but leave them there for backwards compatibility (eg older xcode)\n            let oldConfigDirectory = idiomaticConfigurationDirectory.parentDirectory\n            if self.exists(oldConfigDirectory, followSymlink: false) && self.isDirectory(oldConfigDirectory) {\n                let configurationFiles = try self.getDirectoryContents(oldConfigDirectory)\n                    .map { oldConfigDirectory.appending(component: $0) }\n                    .filter {\n                        self.isFile($0) && !self.isSymlink($0) && $0\n                            .extension != \"lock\" && ((try? self.readFileContents($0)) ?? []).count > 0\n                    }\n                try handleExistingFiles(configurationFiles)\n            }\n            // in the case where ~/.swiftpm/configuration is the idiomatic location (eg on Linux)\n        } else {\n            // copy the configuration files from old location (~/.swiftpm/config) to new one (~/.swiftpm/configuration)\n            // but leave them there for backwards compatibility (eg older toolchain)\n            let oldConfigDirectory = try self.dotSwiftPM.appending(\"config\")\n            if self.exists(oldConfigDirectory, followSymlink: false) && self.isDirectory(oldConfigDirectory) {\n                let configurationFiles = try self.getDirectoryContents(oldConfigDirectory)\n                    .map { oldConfigDirectory.appending(component: $0) }\n                    .filter {\n                        self.isFile($0) && !self.isSymlink($0) && $0\n                            .extension != \"lock\" && ((try? self.readFileContents($0)) ?? []).count > 0\n                    }\n                try handleExistingFiles(configurationFiles)\n            }\n        }\n        // ~temporary 5.6 migration\n\n        // Create idiomatic if necessary\n        if !self.exists(idiomaticConfigurationDirectory) {\n            try self.createDirectory(idiomaticConfigurationDirectory, recursive: true)\n        }\n        // Create ~/.swiftpm if necessary\n        if !self.exists(try self.dotSwiftPM) {\n            try self.createDirectory(self.dotSwiftPM, recursive: true)\n        }\n        // Create ~/.swiftpm/configuration symlink if necessary\n        // locking ~/.swiftpm to protect from concurrent access\n        try self.withLock(on: self.dotSwiftPM, type: .exclusive) {\n            if !self.exists(try self.dotSwiftPMConfigurationDirectory, followSymlink: false) {\n                try self.createSymbolicLink(\n                    dotSwiftPMConfigurationDirectory,\n                    pointingAt: idiomaticConfigurationDirectory,\n                    relative: false\n                )\n            }\n        }\n\n        return idiomaticConfigurationDirectory\n    }\n}\n\n// MARK: - security\n\nextension FileSystem {\n    /// SwiftPM security directory under user's security directory (if exists)\n    public var swiftPMSecurityDirectory: AbsolutePath {\n        get throws {\n            if let path = try self.idiomaticSwiftPMDirectory {\n                return path.appending(\"security\")\n            } else {\n                return try self.dotSwiftPMSecurityDirectory\n            }\n        }\n    }\n\n    private var dotSwiftPMSecurityDirectory: AbsolutePath {\n        get throws {\n            try self.dotSwiftPM.appending(\"security\")\n        }\n    }\n}\n\nextension FileSystem {\n    public func getOrCreateSwiftPMSecurityDirectory() throws -> AbsolutePath {\n        let idiomaticSecurityDirectory = try self.swiftPMSecurityDirectory\n\n        // temporary 5.6, remove on next version: transition from ~/.swiftpm/security to idiomatic location + symbolic\n        // link\n        if try idiomaticSecurityDirectory != self.dotSwiftPMSecurityDirectory &&\n            self.exists(try self.dotSwiftPMSecurityDirectory) &&\n            self.isDirectory(try self.dotSwiftPMSecurityDirectory)\n        {\n            try self.removeFileTree(self.dotSwiftPMSecurityDirectory)\n        }\n        // ~temporary 5.6 migration\n\n        // Create idiomatic if necessary\n        if !self.exists(idiomaticSecurityDirectory) {\n            try self.createDirectory(idiomaticSecurityDirectory, recursive: true)\n        }\n        // Create ~/.swiftpm if necessary\n        if !self.exists(try self.dotSwiftPM) {\n            try self.createDirectory(self.dotSwiftPM, recursive: true)\n        }\n        // Create ~/.swiftpm/security symlink if necessary\n        // locking ~/.swiftpm to protect from concurrent access\n        try self.withLock(on: self.dotSwiftPM, type: .exclusive) {\n            if !self.exists(try self.dotSwiftPMSecurityDirectory, followSymlink: false) {\n                try self.createSymbolicLink(\n                    dotSwiftPMSecurityDirectory,\n                    pointingAt: idiomaticSecurityDirectory,\n                    relative: false\n                )\n            }\n        }\n        return idiomaticSecurityDirectory\n    }\n}\n\n// MARK: - Swift SDKs\n\nprivate let swiftSDKsDirectoryName = \"swift-sdks\"\n\nextension FileSystem {\n    /// Path to Swift SDKs directory (if exists)\n    public var swiftSDKsDirectory: AbsolutePath {\n        get throws {\n            if let path = try idiomaticSwiftPMDirectory {\n                return path.appending(component: swiftSDKsDirectoryName)\n            } else {\n                return try dotSwiftPMSwiftSDKsDirectory\n            }\n        }\n    }\n\n    private var dotSwiftPMSwiftSDKsDirectory: AbsolutePath {\n        get throws {\n            try dotSwiftPM.appending(component: swiftSDKsDirectoryName)\n        }\n    }\n\n    public func getSharedSwiftSDKsDirectory(explicitDirectory: AbsolutePath?) throws -> AbsolutePath {\n        if let explicitDirectory {\n            // Create the explicit SDKs path if necessary\n            if !exists(explicitDirectory) {\n                try createDirectory(explicitDirectory, recursive: true)\n            }\n            return explicitDirectory\n        } else {\n            return try swiftSDKsDirectory\n        }\n    }\n\n    public func getOrCreateSwiftPMSwiftSDKsDirectory() throws -> AbsolutePath {\n        let idiomaticSwiftSDKDirectory = try swiftSDKsDirectory\n\n        // Create idiomatic if necessary\n        if !exists(idiomaticSwiftSDKDirectory) {\n            try createDirectory(idiomaticSwiftSDKDirectory, recursive: true)\n        }\n        // Create ~/.swiftpm if necessary\n        if !exists(try dotSwiftPM) {\n            try createDirectory(dotSwiftPM, recursive: true)\n        }\n        // Create ~/.swiftpm/swift-sdks symlink if necessary\n        // locking ~/.swiftpm to protect from concurrent access\n        try withLock(on: dotSwiftPM, type: .exclusive) {\n            if !exists(try dotSwiftPMSwiftSDKsDirectory, followSymlink: false) {\n                try createSymbolicLink(\n                    dotSwiftPMSwiftSDKsDirectory,\n                    pointingAt: idiomaticSwiftSDKDirectory,\n                    relative: false\n                )\n            }\n        }\n        return idiomaticSwiftSDKDirectory\n    }\n}\n\n// MARK: - Utilities\n\nextension FileSystem {\n    @_disfavoredOverload\n    public func readFileContents(_ path: AbsolutePath) throws -> Data {\n        try Data(self.readFileContents(path).contents)\n    }\n\n    @_disfavoredOverload\n    public func readFileContents(_ path: AbsolutePath) throws -> String {\n        try String(decoding: self.readFileContents(path), as: UTF8.self)\n    }\n\n    public func writeFileContents(_ path: AbsolutePath, data: Data) throws {\n        try self._writeFileContents(path, bytes: .init(data))\n    }\n\n    public func writeFileContents(_ path: AbsolutePath, string: String) throws {\n        try self._writeFileContents(path, bytes: .init(encodingAsUTF8: string))\n    }\n\n    private func _writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {\n        // using the \"body\" variant since it creates the directory first\n        // we should probably fix TSC to be consistent about this behavior\n        try self.writeFileContents(path, body: { $0.send(bytes) })\n    }\n}\n\nextension FileSystem {\n    /// Write bytes to the path if the given contents are different.\n    public func writeIfChanged(path: AbsolutePath, string: String) throws {\n        try writeIfChanged(path: path, bytes: .init(encodingAsUTF8: string))\n    }\n\n    public func writeIfChanged(path: AbsolutePath, data: Data) throws {\n        try writeIfChanged(path: path, bytes: .init(data))\n    }\n\n    /// Write bytes to the path if the given contents are different.\n    public func writeIfChanged(path: AbsolutePath, bytes: ByteString) throws {\n        try createDirectory(path.parentDirectory, recursive: true)\n\n        // Return if the contents are same.\n        if isFile(path), try readFileContents(path) == bytes {\n            return\n        }\n\n        try writeFileContents(path, bytes: bytes)\n    }\n}\n\nextension FileSystem {\n    public func forceCreateDirectory(at path: AbsolutePath) throws {\n        try self.createDirectory(path.parentDirectory, recursive: true)\n        if self.exists(path) {\n            try self.removeFileTree(path)\n        }\n        try self.createDirectory(path, recursive: true)\n    }\n}\n\nextension FileSystem {\n    public func stripFirstLevel(of path: AbsolutePath) throws {\n        let topLevelDirectories = try self.getDirectoryContents(path)\n            .map { path.appending(component: $0) }\n            .filter { self.isDirectory($0) }\n\n        guard topLevelDirectories.count == 1, let rootDirectory = topLevelDirectories.first else {\n            throw StringError(\"stripFirstLevel requires single top level directory\")\n        }\n\n        let tempDirectory = path.parentDirectory.appending(component: UUID().uuidString)\n        try self.move(from: rootDirectory, to: tempDirectory)\n\n        let rootContents = try self.getDirectoryContents(tempDirectory)\n        for entry in rootContents {\n            try self.move(from: tempDirectory.appending(component: entry), to: path.appending(component: entry))\n        }\n\n        try self.removeFileTree(tempDirectory)\n    }\n}\n\n// MARK: - Locking\n\nextension FileLock {\n    public static func prepareLock(\n        fileToLock: AbsolutePath,\n        at lockFilesDirectory: AbsolutePath? = nil\n    ) throws -> FileLock {\n        return try Self.prepareLock(fileToLock: fileToLock.underlying, at: lockFilesDirectory?.underlying)\n    }\n}\n\n/// Convenience initializers for testing purposes.\nextension InMemoryFileSystem {\n    /// Create a new file system with the given files, provided as a map from\n    /// file path to contents.\n    public convenience init(files: [String: ByteString]) {\n        self.init()\n\n        for (path, contents) in files {\n            let path = try! AbsolutePath(validating: path)\n            try! createDirectory(path.parentDirectory, recursive: true)\n            try! writeFileContents(path, bytes: contents)\n        }\n    }\n\n    /// Create a new file system with an empty file at each provided path.\n    public convenience init(emptyFiles files: String...) {\n        self.init(emptyFiles: files)\n    }\n\n    /// Create a new file system with an empty file at each provided path.\n    public convenience init(emptyFiles files: [String]) {\n        self.init()\n        self.createEmptyFiles(at: .root, files: files)\n    }\n}\n\nextension FileSystem {\n    public func createEmptyFiles(at root: AbsolutePath, files: String...) {\n        self.createEmptyFiles(at: root, files: files)\n    }\n\n    public func createEmptyFiles(at root: AbsolutePath, files: [String]) {\n        do {\n            try createDirectory(root, recursive: true)\n            for path in files {\n                let path = try AbsolutePath(validating: String(path.dropFirst()), relativeTo: root)\n                try createDirectory(path.parentDirectory, recursive: true)\n                try writeFileContents(path, bytes: \"\")\n            }\n        } catch {\n            fatalError(\"Failed to create empty files: \\(error)\")\n        }\n    }\n}\n\nextension FileSystem {\n    /// Do a deep enumeration, passing each file to block\n    public func enumerate(directory: AbsolutePath, block: (AbsolutePath) throws -> ()) throws {\n        for file in try getDirectoryContents(directory) {\n            let path = directory.appending(file)\n            if isDirectory(path) {\n                try enumerate(directory: path, block: block)\n            } else {\n                try block(path)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/InMemoryFileSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.NSLock\nimport class Dispatch.DispatchQueue\nimport struct TSCBasic.AbsolutePath\nimport struct TSCBasic.ByteString\nimport class TSCBasic.FileLock\nimport enum TSCBasic.FileMode\nimport struct TSCBasic.FileSystemError\n\n/// Concrete FileSystem implementation which simulates an empty disk.\npublic final class InMemoryFileSystem: FileSystem {\n    /// Private internal representation of a file system node.\n    /// Not thread-safe.\n    private class Node {\n        /// The actual node data.\n        let contents: NodeContents\n\n        /// Whether the node has executable bit enabled.\n        var isExecutable: Bool\n\n        init(_ contents: NodeContents, isExecutable: Bool = false) {\n            self.contents = contents\n            self.isExecutable = isExecutable\n        }\n\n        /// Creates deep copy of the object.\n        func copy() -> Node {\n            return Node(contents.copy())\n        }\n    }\n\n    /// Private internal representation the contents of a file system node.\n    /// Not thread-safe.\n    private enum NodeContents {\n        case file(ByteString)\n        case directory(DirectoryContents)\n        case symlink(String)\n\n        /// Creates deep copy of the object.\n        func copy() -> NodeContents {\n            switch self {\n            case .file(let bytes):\n                return .file(bytes)\n            case .directory(let contents):\n                return .directory(contents.copy())\n            case .symlink(let path):\n                return .symlink(path)\n            }\n        }\n    }\n\n    /// Private internal representation the contents of a directory.\n    /// Not thread-safe.\n    private final class DirectoryContents {\n        var entries: [String: Node]\n\n        init(entries: [String: Node] = [:]) {\n            self.entries = entries\n        }\n\n        /// Creates deep copy of the object.\n        func copy() -> DirectoryContents {\n            let contents = DirectoryContents()\n            for (key, node) in entries {\n                contents.entries[key] = node.copy()\n            }\n            return contents\n        }\n    }\n\n    /// The root node of the filesystem.\n    private var root: Node\n\n    /// Protects `root` and everything underneath it.\n    /// FIXME: Using a single lock for this is a performance problem, but in\n    /// reality, the only practical use for InMemoryFileSystem is for unit\n    /// tests.\n    private let lock = NSLock()\n    /// A map that keeps weak references to all locked files.\n    private var lockFiles = Dictionary<TSCBasic.AbsolutePath, WeakReference<DispatchQueue>>()\n    /// Used to access lockFiles in a thread safe manner.\n    private let lockFilesLock = NSLock()\n\n    /// Exclusive file system lock vended to clients through `withLock()`.\n    /// Used to ensure that DispatchQueues are released when they are no longer in use.\n    private struct WeakReference<Value: AnyObject> {\n        weak var reference: Value?\n\n        init(_ value: Value?) {\n            self.reference = value\n        }\n    }\n\n    public init() {\n        root = Node(.directory(DirectoryContents()))\n    }\n\n    /// Creates deep copy of the object.\n    public func copy() -> InMemoryFileSystem {\n        return lock.withLock {\n            let fs = InMemoryFileSystem()\n            fs.root = root.copy()\n            return fs\n        }\n    }\n\n    /// Private function to look up the node corresponding to a path.\n    /// Not thread-safe.\n    private func getNode(_ path: TSCBasic.AbsolutePath, followSymlink: Bool = true) throws -> Node? {\n        func getNodeInternal(_ path: TSCBasic.AbsolutePath) throws -> Node? {\n            // If this is the root node, return it.\n            if path.isRoot {\n                return root\n            }\n\n            // Otherwise, get the parent node.\n            guard let parent = try getNodeInternal(path.parentDirectory) else {\n                return nil\n            }\n\n            // If we didn't find a directory, this is an error.\n            guard case .directory(let contents) = parent.contents else {\n                throw FileSystemError(.notDirectory, path.parentDirectory)\n            }\n\n            // Return the directory entry.\n            let node = contents.entries[path.basename]\n\n            switch node?.contents {\n            case .directory, .file:\n                return node\n            case .symlink(let destination):\n                let destination = try TSCBasic.AbsolutePath(validating: destination, relativeTo: path.parentDirectory)\n                return followSymlink ? try getNodeInternal(destination) : node\n            case .none:\n                return nil\n            }\n        }\n\n        // Get the node that corresponds to the path.\n        return try getNodeInternal(path)\n    }\n\n    // MARK: FileSystem Implementation\n\n    public func exists(_ path: TSCBasic.AbsolutePath, followSymlink: Bool) -> Bool {\n        return lock.withLock {\n            do {\n                switch try getNode(path, followSymlink: followSymlink)?.contents {\n                case .file, .directory, .symlink: return true\n                case .none: return false\n                }\n            } catch {\n                return false\n            }\n        }\n    }\n\n    public func isDirectory(_ path: TSCBasic.AbsolutePath) -> Bool {\n        return lock.withLock {\n            do {\n                if case .directory? = try getNode(path)?.contents {\n                    return true\n                }\n                return false\n            } catch {\n                return false\n            }\n        }\n    }\n\n    public func isFile(_ path: TSCBasic.AbsolutePath) -> Bool {\n        return lock.withLock {\n            do {\n                if case .file? = try getNode(path)?.contents {\n                    return true\n                }\n                return false\n            } catch {\n                return false\n            }\n        }\n    }\n\n    public func isSymlink(_ path: TSCBasic.AbsolutePath) -> Bool {\n        return lock.withLock {\n            do {\n                if case .symlink? = try getNode(path, followSymlink: false)?.contents {\n                    return true\n                }\n                return false\n            } catch {\n                return false\n            }\n        }\n    }\n\n    public func isReadable(_ path: TSCBasic.AbsolutePath) -> Bool {\n        self.exists(path)\n    }\n\n    public func isWritable(_ path: TSCBasic.AbsolutePath) -> Bool {\n        self.exists(path)\n    }\n\n    public func isExecutableFile(_ path: TSCBasic.AbsolutePath) -> Bool {\n        (try? self.getNode(path)?.isExecutable) ?? false\n    }\n\n    public func updatePermissions(_ path: AbsolutePath, isExecutable: Bool) throws {\n        try lock.withLock {\n            guard let node = try self.getNode(path.underlying, followSymlink: true) else {\n                throw FileSystemError(.noEntry, path)\n            }\n            node.isExecutable = isExecutable\n        }\n    }\n\n    /// Virtualized current working directory.\n    private var _currentWorkingDirectory: TSCBasic.AbsolutePath = try! .init(validating: \"/\")\n\n    public var currentWorkingDirectory: TSCBasic.AbsolutePath? {\n        return _currentWorkingDirectory\n    }\n\n    public func changeCurrentWorkingDirectory(to path: TSCBasic.AbsolutePath) throws {\n        return try lock.withLock {\n            // Verify the path exists and is a directory\n            guard let node = try getNode(path) else {\n                throw FileSystemError(.noEntry, path)\n            }\n\n            guard case .directory = node.contents else {\n                throw FileSystemError(.notDirectory, path)\n            }\n            _currentWorkingDirectory = path\n        }\n    }\n\n    public var homeDirectory: TSCBasic.AbsolutePath {\n        get throws {\n            // FIXME: Maybe we should allow setting this when creating the fs.\n            return try .init(validating: \"/home/user\")\n        }\n    }\n\n    public var cachesDirectory: TSCBasic.AbsolutePath? {\n        return try? self.homeDirectory.appending(component: \"caches\")\n    }\n\n    public var tempDirectory: TSCBasic.AbsolutePath {\n        get throws {\n            return try .init(validating: \"/tmp\")\n        }\n    }\n\n    public func getDirectoryContents(_ path: TSCBasic.AbsolutePath) throws -> [String] {\n        return try lock.withLock {\n            guard let node = try getNode(path) else {\n                throw FileSystemError(.noEntry, path)\n            }\n            guard case .directory(let contents) = node.contents else {\n                throw FileSystemError(.notDirectory, path)\n            }\n\n            // FIXME: Perhaps we should change the protocol to allow lazy behavior.\n            return [String](contents.entries.keys)\n        }\n    }\n\n    /// Not thread-safe.\n    private func _createDirectory(_ path: TSCBasic.AbsolutePath, recursive: Bool) throws {\n        // Ignore if client passes root.\n        guard !path.isRoot else {\n            return\n        }\n        // Get the parent directory node.\n        let parentPath = path.parentDirectory\n        guard let parent = try getNode(parentPath) else {\n            // If the parent doesn't exist, and we are recursive, then attempt\n            // to create the parent and retry.\n            if recursive && path != parentPath {\n                // Attempt to create the parent.\n                try _createDirectory(parentPath, recursive: true)\n\n                // Re-attempt creation, non-recursively.\n                return try _createDirectory(path, recursive: false)\n            } else {\n                // Otherwise, we failed.\n                throw FileSystemError(.noEntry, parentPath)\n            }\n        }\n\n        // Check that the parent is a directory.\n        guard case .directory(let contents) = parent.contents else {\n            // The parent isn't a directory, this is an error.\n            throw FileSystemError(.notDirectory, parentPath)\n        }\n\n        // Check if the node already exists.\n        if let node = contents.entries[path.basename] {\n            // Verify it is a directory.\n            guard case .directory = node.contents else {\n                // The path itself isn't a directory, this is an error.\n                throw FileSystemError(.notDirectory, path)\n            }\n\n            // We are done.\n            return\n        }\n\n        // Otherwise, the node does not exist, create it.\n        contents.entries[path.basename] = Node(.directory(DirectoryContents()))\n    }\n\n    public func createDirectory(_ path: TSCBasic.AbsolutePath, recursive: Bool) throws {\n        return try lock.withLock {\n            try _createDirectory(path, recursive: recursive)\n        }\n    }\n\n    public func createSymbolicLink(\n        _ path: TSCBasic.AbsolutePath,\n        pointingAt destination: TSCBasic.AbsolutePath,\n        relative: Bool\n    ) throws {\n        return try lock.withLock {\n            // Create directory to destination parent.\n            guard let destinationParent = try getNode(path.parentDirectory) else {\n                throw FileSystemError(.noEntry, path.parentDirectory)\n            }\n\n            // Check that the parent is a directory.\n            guard case .directory(let contents) = destinationParent.contents else {\n                throw FileSystemError(.notDirectory, path.parentDirectory)\n            }\n\n            guard contents.entries[path.basename] == nil else {\n                throw FileSystemError(.alreadyExistsAtDestination, path)\n            }\n\n            let destination = relative ? destination.relative(to: path.parentDirectory).pathString : destination.pathString\n\n            contents.entries[path.basename] = Node(.symlink(destination))\n        }\n    }\n\n    public func readFileContents(_ path: TSCBasic.AbsolutePath) throws -> ByteString {\n        return try lock.withLock {\n            // Get the node.\n            guard let node = try getNode(path) else {\n                throw FileSystemError(.noEntry, path)\n            }\n\n            // Check that the node is a file.\n            guard case .file(let contents) = node.contents else {\n                // The path is a directory, this is an error.\n                throw FileSystemError(.isDirectory, path)\n            }\n\n            // Return the file contents.\n            return contents\n        }\n    }\n\n    public func writeFileContents(_ path: TSCBasic.AbsolutePath, bytes: ByteString) throws {\n        return try lock.withLock {\n            // It is an error if this is the root node.\n            let parentPath = path.parentDirectory\n            guard path != parentPath else {\n                throw FileSystemError(.isDirectory, path)\n            }\n\n            // Get the parent node.\n            guard let parent = try getNode(parentPath) else {\n                throw FileSystemError(.noEntry, parentPath)\n            }\n\n            // Check that the parent is a directory.\n            guard case .directory(let contents) = parent.contents else {\n                // The parent isn't a directory, this is an error.\n                throw FileSystemError(.notDirectory, parentPath)\n            }\n\n            // Check if the node exists.\n            if let node = contents.entries[path.basename] {\n                // Verify it is a file.\n                guard case .file = node.contents else {\n                    // The path is a directory, this is an error.\n                    throw FileSystemError(.isDirectory, path)\n                }\n            }\n\n            // Write the file.\n            contents.entries[path.basename] = Node(.file(bytes))\n        }\n    }\n\n    public func writeFileContents(_ path: TSCBasic.AbsolutePath, bytes: ByteString, atomically: Bool) throws {\n        // In memory file system's writeFileContents is already atomic, so ignore the parameter here\n        // and just call the base implementation.\n        try writeFileContents(path, bytes: bytes)\n    }\n\n    public func removeFileTree(_ path: TSCBasic.AbsolutePath) throws {\n        return lock.withLock {\n            // Ignore root and get the parent node's content if its a directory.\n            guard !path.isRoot,\n                  let parent = try? getNode(path.parentDirectory),\n                  case .directory(let contents) = parent.contents else {\n                      return\n                  }\n            // Set it to nil to release the contents.\n            contents.entries[path.basename] = nil\n        }\n    }\n\n    public func chmod(_ mode: FileMode, path: TSCBasic.AbsolutePath, options: Set<FileMode.Option>) throws {\n        // FIXME: We don't have these semantics in InMemoryFileSystem.\n    }\n\n    /// Private implementation of core copying function.\n    /// Not thread-safe.\n    private func _copy(from sourcePath: TSCBasic.AbsolutePath, to destinationPath: TSCBasic.AbsolutePath) throws {\n        // Get the source node.\n        guard let source = try getNode(sourcePath) else {\n            throw FileSystemError(.noEntry, sourcePath)\n        }\n\n        // Create directory to destination parent.\n        guard let destinationParent = try getNode(destinationPath.parentDirectory) else {\n            throw FileSystemError(.noEntry, destinationPath.parentDirectory)\n        }\n\n        // Check that the parent is a directory.\n        guard case .directory(let contents) = destinationParent.contents else {\n            throw FileSystemError(.notDirectory, destinationPath.parentDirectory)\n        }\n\n        guard contents.entries[destinationPath.basename] == nil else {\n            throw FileSystemError(.alreadyExistsAtDestination, destinationPath)\n        }\n\n        contents.entries[destinationPath.basename] = source\n    }\n\n    public func copy(from sourcePath: TSCBasic.AbsolutePath, to destinationPath: TSCBasic.AbsolutePath) throws {\n        return try lock.withLock {\n            try _copy(from: sourcePath, to: destinationPath)\n        }\n    }\n\n    public func move(from sourcePath: TSCBasic.AbsolutePath, to destinationPath: TSCBasic.AbsolutePath) throws {\n        return try lock.withLock {\n            // Get the source parent node.\n            guard let sourceParent = try getNode(sourcePath.parentDirectory) else {\n                throw FileSystemError(.noEntry, sourcePath.parentDirectory)\n            }\n\n            // Check that the parent is a directory.\n            guard case .directory(let contents) = sourceParent.contents else {\n                throw FileSystemError(.notDirectory, sourcePath.parentDirectory)\n            }\n\n            try _copy(from: sourcePath, to: destinationPath)\n\n            contents.entries[sourcePath.basename] = nil\n        }\n    }\n\n    public func withLock<T>(\n        on path: TSCBasic.AbsolutePath,\n        type: FileLock.LockType = .exclusive,\n        _ body: () throws -> T\n    ) throws -> T {\n        let resolvedPath: TSCBasic.AbsolutePath = try lock.withLock {\n            if case let .symlink(destination) = try getNode(path)?.contents {\n                return try .init(validating: destination, relativeTo: path.parentDirectory)\n            } else {\n                return path\n            }\n        }\n\n        let fileQueue: DispatchQueue = lockFilesLock.withLock {\n            if let queueReference = lockFiles[resolvedPath], let queue = queueReference.reference {\n                return queue\n            } else {\n                let queue = DispatchQueue(label: \"org.swift.swiftpm.in-memory-file-system.file-queue\", attributes: .concurrent)\n                lockFiles[resolvedPath] = WeakReference(queue)\n                return queue\n            }\n        }\n\n        return try fileQueue.sync(flags: type == .exclusive ? .barrier : .init() , execute: body)\n    }\n\n    public func withLock<T>(on path: TSCBasic.AbsolutePath, type: FileLock.LockType, blocking: Bool, _ body: () throws -> T) throws -> T {\n        try self.withLock(on: path, type: type, body)\n    }\n}\n\n// Internal state of `InMemoryFileSystem` is protected with a lock in all of its `public` methods.\nextension InMemoryFileSystem: @unchecked Sendable {}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/NativePathExtensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport struct TSCBasic.AbsolutePath\n\nextension AbsolutePath {\n    /// Returns the File System Representation of the `AbsolutePath`'s\n    /// `pathString` property converted into a `URL`.\n    public func _nativePathString(escaped: Bool) -> String {\n        return URL(fileURLWithPath: self.pathString).withUnsafeFileSystemRepresentation {\n            let repr = String(cString: $0!)\n            if escaped {\n                return repr.replacing(\"\\\\\", with: \"\\\\\\\\\")\n            }\n            return repr\n        }\n    }\n}\n\nextension DefaultStringInterpolation {\n    public mutating func appendInterpolation(_ value: AbsolutePath) {\n        self.appendInterpolation(value._nativePathString(escaped: false))\n    }\n}\n\nextension SerializedJSON.StringInterpolation {\n    public mutating func appendInterpolation(_ value: AbsolutePath) {\n        self.appendInterpolation(value._nativePathString(escaped: false))\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/RelativePath.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCBasic.RelativePath\n\n// public for transition\npublic typealias TSCRelativePath = TSCBasic.RelativePath\n\n/// Represents a relative file system path.  A relative path never starts with\n/// a `/` character, and holds a normalized string representation.  As with\n/// AbsolutePath, the normalization is strictly syntactic, and does not access\n/// the file system in any way.\n///\n/// The relative path string is normalized by:\n/// - Collapsing `..` path components that aren't at the beginning\n/// - Removing extraneous `.` path components\n/// - Removing any trailing path separator\n/// - Removing any redundant path separators\n/// - Replacing a completely empty path with a `.`\n///\n/// This string manipulation may change the meaning of a path if any of the\n/// path components are symbolic links on disk.  However, the file system is\n/// never accessed in any way when initializing a RelativePath.\npublic struct RelativePath: Hashable, Sendable {\n    let underlying: TSCBasic.RelativePath\n\n    // public for transition\n    public init(_ underlying: TSCBasic.RelativePath) {\n        self.underlying = underlying\n    }\n\n    /// Convenience initializer that verifies that the path is relative.\n    public init(validating pathString: String) throws {\n        self.underlying = try .init(validating: pathString)\n    }\n\n    /// Directory component.  For a relative path without any path separators,\n    /// this is the `.` string instead of the empty string.\n    public var dirname: String {\n        self.underlying.dirname\n    }\n\n    /// Last path component (including the suffix, if any).  It is never empty.\n    public var basename: String {\n        self.underlying.basename\n    }\n\n    /// Returns the basename without the extension.\n    public var basenameWithoutExt: String {\n        self.underlying.basenameWithoutExt\n    }\n\n    /// Suffix (including leading `.` character) if any.  Note that a basename\n    /// that starts with a `.` character is not considered a suffix, nor is a\n    /// trailing `.` character.\n    public var suffix: String? {\n        self.underlying.suffix\n    }\n\n    /// Extension of the give path's basename. This follow same rules as\n    /// suffix except that it doesn't include leading `.` character.\n    public var `extension`: String? {\n        self.underlying.extension\n    }\n\n    /// Normalized string representation (the normalization rules are described\n    /// in the documentation of the initializer).  This string is never empty.\n    public var pathString: String {\n        self.underlying.pathString\n    }\n}\n\nextension RelativePath {\n    /// Returns an array of strings that make up the path components of the\n    /// relative path.  This is the same sequence of strings as the basenames\n    /// of each successive path component.  Therefore the returned array of\n    /// path components is never empty; even an empty path has a single path\n    /// component: the `.` string.\n    public var components: [String] {\n        self.underlying.components\n    }\n\n    /// Returns the relative path with the given relative path applied.\n    public func appending(_ subpath: RelativePath) -> RelativePath {\n        Self(self.underlying.appending(subpath.underlying))\n    }\n\n    /// Returns the relative path with an additional literal component appended.\n    ///\n    /// This method accepts pseudo-path like '.' or '..', but should not contain \"/\".\n    public func appending(component: String) -> RelativePath {\n        Self(self.underlying.appending(component: component))\n    }\n\n    /// Returns the relative path with additional literal components appended.\n    ///\n    /// This method should only be used in cases where the input is guaranteed\n    /// to be a valid path component (i.e., it cannot be empty, contain a path\n    /// separator, or be a pseudo-path like '.' or '..').\n    public func appending(components: [String]) -> RelativePath {\n        Self(self.underlying.appending(components: components))\n    }\n\n    /// Returns the relative path with additional literal components appended.\n    ///\n    /// This method should only be used in cases where the input is guaranteed\n    /// to be a valid path component (i.e., it cannot be empty, contain a path\n    /// separator, or be a pseudo-path like '.' or '..').\n    public func appending(components: String...) -> RelativePath {\n        Self(self.underlying.appending(components: components))\n    }\n\n    /// Returns the relative path with additional literal components appended.\n    ///\n    /// This method should only be used in cases where the input is guaranteed\n    /// to be a valid path component (i.e., it cannot be empty, contain a path\n    /// separator, or be a pseudo-path like '.' or '..').\n    public func appending(_ component: String) -> RelativePath {\n        self.appending(component: component)\n    }\n\n    /// Returns the relative path with additional literal components appended.\n    ///\n    /// This method should only be used in cases where the input is guaranteed\n    /// to be a valid path component (i.e., it cannot be empty, contain a path\n    /// separator, or be a pseudo-path like '.' or '..').\n    public func appending(_ components: String...) -> RelativePath {\n        self.appending(components: components)\n    }\n}\n\nextension RelativePath: Codable {\n    public func encode(to encoder: Encoder) throws {\n        try self.underlying.encode(to: encoder)\n    }\n\n    public init(from decoder: Decoder) throws {\n        self = try .init(TSCBasic.RelativePath(from: decoder))\n    }\n}\n\n/// Make relative paths CustomStringConvertible and CustomDebugStringConvertible.\nextension RelativePath: CustomStringConvertible {\n    public var description: String {\n        self.underlying.description\n    }\n\n    public var debugDescription: String {\n        self.underlying.debugDescription\n    }\n}\n\nextension TSCRelativePath {\n    public init(_ path: RelativePath) {\n        self = path.underlying\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/TSCAdapters.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport func TSCBasic.getEnvSearchPaths\nimport func TSCBasic.lookupExecutablePath\nimport func TSCBasic.makeDirectories\nimport func TSCBasic.resolveSymlinks\nimport func TSCBasic.walk\nimport func TSCBasic.withTemporaryDirectory\n\nimport struct TSCBasic.FileSystemError\nimport class TSCBasic.LocalFileOutputByteStream\nimport enum TSCBasic.ProcessEnv\nimport class TSCBasic.RecursibleDirectoryContentsGenerator\n\npublic func resolveSymlinks(_ path: AbsolutePath) throws -> AbsolutePath {\n    try AbsolutePath(TSCBasic.resolveSymlinks(path.underlying))\n}\n\npublic func withTemporaryDirectory<Result>(\n    dir: AbsolutePath? = nil, prefix: String = \"TemporaryDirectory\",\n    _ body: (AbsolutePath, @escaping (AbsolutePath) -> Void) throws -> Result\n) throws -> Result {\n    try TSCBasic.withTemporaryDirectory(dir: dir?.underlying, prefix: prefix) { path, callback in\n        let callback2 = { (path: AbsolutePath) in\n            callback(path.underlying)\n        }\n        return try body(AbsolutePath(path), callback2)\n    }\n}\n\npublic func withTemporaryDirectory<Result>(\n    dir: AbsolutePath? = nil, prefix: String = \"TemporaryDirectory\",\n    _ body: (AbsolutePath, @escaping (AbsolutePath) async -> Void) async throws -> Result\n) async throws -> Result {\n    try await TSCBasic.withTemporaryDirectory(dir: dir?.underlying, prefix: prefix) { path, callback in\n        let callback2: (AbsolutePath) async -> Void = { (path: AbsolutePath) in\n            await callback(path.underlying)\n        }\n        return try await body(AbsolutePath(path), callback2)\n    }\n}\n\npublic func withTemporaryDirectory<Result>(\n    dir: AbsolutePath? = nil, prefix: String = \"TemporaryDirectory\", removeTreeOnDeinit: Bool = false,\n    _ body: (AbsolutePath) throws -> Result\n) throws -> Result {\n    try TSCBasic.withTemporaryDirectory(dir: dir?.underlying, prefix: prefix, removeTreeOnDeinit: removeTreeOnDeinit) {\n        try body(AbsolutePath($0))\n    }\n}\n\npublic func withTemporaryDirectory<Result>(\n    dir: AbsolutePath? = nil, prefix: String = \"TemporaryDirectory\", removeTreeOnDeinit: Bool = false,\n    _ body: (AbsolutePath) async throws -> Result\n) async throws -> Result {\n    try await TSCBasic.withTemporaryDirectory(\n        dir: dir?.underlying,\n        prefix: prefix,\n        removeTreeOnDeinit: removeTreeOnDeinit\n    ) {\n        try await body(AbsolutePath($0))\n    }\n}\n\n/// Lookup an executable path from an environment variable value, current working\n/// directory or search paths. Only return a value that is both found and executable.\n///\n/// This method searches in the following order:\n/// * If env value is a valid absolute path, return it.\n/// * If env value is relative path, first try to locate it in current working directory.\n/// * Otherwise, in provided search paths.\n///\n/// - Parameters:\n///   - filename: The name of the file to find.\n///   - currentWorkingDirectory: The current working directory to look in.\n///   - searchPaths: The additional search paths to look in if not found in cwd.\n/// - Returns: Valid path to executable if present, otherwise nil.\npublic func lookupExecutablePath(\n    filename: String?,\n    currentWorkingDirectory: AbsolutePath? = localFileSystem.currentWorkingDirectory,\n    searchPaths: [AbsolutePath] = []\n) -> AbsolutePath? {\n    TSCBasic.lookupExecutablePath(\n        filename: filename,\n        currentWorkingDirectory: currentWorkingDirectory?.underlying,\n        searchPaths: searchPaths.map(\\.underlying)\n    ).flatMap { AbsolutePath($0) }\n}\n\n/// Create a list of AbsolutePath search paths from a string, such as the PATH environment variable.\n///\n/// - Parameters:\n///   - pathString: The path string to parse.\n///   - currentWorkingDirectory: The current working directory, the relative paths will be converted to absolute paths\n///     based on this path.\n/// - Returns: List of search paths.\npublic func getEnvSearchPaths(\n    pathString: String?,\n    currentWorkingDirectory: AbsolutePath?\n) -> [AbsolutePath] {\n    TSCBasic.getEnvSearchPaths(\n        pathString: pathString,\n        currentWorkingDirectory: currentWorkingDirectory?.underlying\n    ).map { AbsolutePath($0) }\n}\n\npublic func walk(\n    _ path: AbsolutePath,\n    fileSystem: FileSystem = localFileSystem,\n    recursively: Bool = true\n) throws -> WalkResult {\n    let result = try TSCBasic.walk(\n        path.underlying,\n        fileSystem: fileSystem,\n        recursively: recursively\n    )\n    return WalkResult(result)\n}\n\npublic class WalkResult: IteratorProtocol, Sequence {\n    private let underlying: TSCBasic.RecursibleDirectoryContentsGenerator\n\n    init(_ underlying: TSCBasic.RecursibleDirectoryContentsGenerator) {\n        self.underlying = underlying\n    }\n\n    public func next() -> AbsolutePath? {\n        self.underlying.next().flatMap { AbsolutePath($0) }\n    }\n}\n\npublic func makeDirectories(_ path: AbsolutePath) throws {\n    try TSCBasic.makeDirectories(path.underlying)\n}\n\nextension TSCBasic.LocalFileOutputByteStream {\n    public convenience init(_ path: AbsolutePath, closeOnDeinit: Bool = true, buffered: Bool = true) throws {\n        try self.init(path.underlying, closeOnDeinit: closeOnDeinit, buffered: buffered)\n    }\n}\n\nextension TSCBasic.ProcessEnv {\n    public static func chdir(_ path: AbsolutePath) throws {\n        try self.chdir(path.underlying)\n    }\n}\n\nextension TSCBasic.FileSystemError {\n    @_disfavoredOverload\n    public init(_ kind: Kind, _ path: AbsolutePath? = nil) {\n        self.init(kind, path?.underlying)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/TemporaryFile.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Foundation\nimport enum TSCBasic.TempFileError\n\n/// Creates a temporary directory and evaluates a closure with the directory path as an argument.\n/// The temporary directory will live on disk while the closure is evaluated and will be deleted when\n/// the cleanup closure is called. This allows the temporary directory to have an arbitrary lifetime.\n///\n/// - Parameters:\n///     - fileSystem: `FileSystem` which is used to construct temporary directory.\n///     - dir: If specified the temporary directory will be created in this directory otherwise environment\n///            variables TMPDIR, TEMP and TMP will be checked for a value (in that order). If none of the env\n///            variables are set, dir will be set to `/tmp/`.\n///     - prefix: The prefix to the temporary file name.\n///     - body: A closure to execute that receives the absolute path of the directory as an argument.\n///           If `body` has a return value, that value is also used as the\n///           return value for the `withTemporaryDirectory` function.\n///           The cleanup block should be called when the temporary directory is no longer needed.\n///\n/// - Throws: An error when creating directory and rethrows all errors from `body`.\npublic func withTemporaryDirectory<Result>(\n    fileSystem: FileSystem = localFileSystem,\n    dir: AbsolutePath? = nil,\n    prefix: String = \"TemporaryDirectory\",\n    _ body: @escaping @Sendable (AbsolutePath, @escaping (AbsolutePath) -> Void) async throws -> Result\n) throws -> Task<Result, Error> {\n    let temporaryDirectory = try createTemporaryDirectory(fileSystem: fileSystem, dir: dir, prefix: prefix)\n\n    let task: Task<Result, Error> = Task {\n        try await withTaskCancellationHandler {\n            try await body(temporaryDirectory) { path in\n                try? fileSystem.removeFileTree(path)\n            }\n        } onCancel: {\n            try? fileSystem.removeFileTree(temporaryDirectory)\n        }\n    }\n\n    return task\n}\n\n/// Creates a temporary directory and evaluates a closure with the directory path as an argument.\n/// The temporary directory will live on disk while the closure is evaluated and will be deleted afterwards.\n///\n/// - Parameters:\n///     - fileSystem: `FileSystem` which is used to construct temporary directory.\n///     - dir: If specified the temporary directory will be created in this directory otherwise environment\n///            variables TMPDIR, TEMP and TMP will be checked for a value (in that order). If none of the env\n///            variables are set, dir will be set to `/tmp/`.\n///     - prefix: The prefix to the temporary file name.\n///     - removeTreeOnDeinit: If enabled try to delete the whole directory tree otherwise remove only if its empty.\n///     - body: A closure to execute that receives the absolute path of the directory as an argument.\n///             If `body` has a return value, that value is also used as the\n///             return value for the `withTemporaryDirectory` function.\n///\n/// - Throws: An error when creating directory and rethrows all errors from `body`.\n@discardableResult\npublic func withTemporaryDirectory<Result>(\n    fileSystem: FileSystem = localFileSystem,\n    dir: AbsolutePath? = nil,\n    prefix: String = \"TemporaryDirectory\",\n    removeTreeOnDeinit: Bool = false,\n    _ body: @escaping @Sendable (AbsolutePath) async throws -> Result\n) throws -> Task<Result, Error> {\n    try withTemporaryDirectory(fileSystem: fileSystem, dir: dir, prefix: prefix) { path, cleanup in\n        defer { if removeTreeOnDeinit { cleanup(path) } }\n        return try await body(path)\n    }\n}\n\nprivate func createTemporaryDirectory(\n    fileSystem: FileSystem,\n    dir: AbsolutePath?,\n    prefix: String\n) throws -> AbsolutePath {\n    // This random generation is needed so that\n    // it is more or less equal to generation using `mkdtemp` function\n    let letters = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n\n    let randomSuffix = String((0 ..< 6).map { _ in letters.randomElement()! })\n\n    let tempDirectory = try dir ?? fileSystem.tempDirectory\n    guard fileSystem.isDirectory(tempDirectory) else {\n        throw TempFileError.couldNotFindTmpDir(tempDirectory.pathString)\n    }\n\n    // Construct path to the temporary directory.\n    let templatePath = try AbsolutePath(validating: prefix + \".\\(randomSuffix)\", relativeTo: tempDirectory)\n\n    try fileSystem.createDirectory(templatePath, recursive: true)\n    return templatePath\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/VFSOverlay.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.JSONEncoder\n\npublic struct VFSOverlay: Encodable {\n    public struct File: Encodable {\n        enum CodingKeys: String, CodingKey {\n            case externalContents = \"external-contents\"\n            case name\n            case type\n        }\n\n        private let externalContents: String\n        private let name: String\n        private let type = \"file\"\n\n        public init(name: String, externalContents: String) {\n            self.name = name\n            self.externalContents = externalContents\n        }\n    }\n\n    enum CodingKeys: String, CodingKey {\n        case roots\n        case useExternalNames = \"use-external-names\"\n        case version\n    }\n\n    private let roots: [File]\n    private let useExternalNames = false\n    private let version = 0\n\n    public init(roots: [File]) {\n        self.roots = roots\n    }\n\n    public func write(to path: AbsolutePath, fileSystem: FileSystem) throws {\n        // VFS overlay files are YAML, but ours is simple enough that it works when being written using `JSONEncoder`.\n        try JSONEncoder.makeWithDefaults(prettified: false).encode(path: path, fileSystem: fileSystem, self)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/FileSystem/VirtualFileSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.FileInfo\nimport enum TSCBasic.FileMode\n\nprivate enum DirectoryNode: Codable {\n    case directory(name: String, isSymlink: Bool, children: [DirectoryNode])\n    case file(name: String, isExecutable: Bool, isSymlink: Bool, contents: Data?)\n    case root(children: [DirectoryNode])\n\n    var children: [DirectoryNode] {\n        switch self {\n        case .directory(_, _, let children): return children\n        case .file: return []\n        case .root(let children): return children\n        }\n    }\n\n    var name: String {\n        switch self {\n        case .directory(let name, _, _): return name\n        case .file(let name, _, _, _): return name\n        case .root: return AbsolutePath.root.pathString\n        }\n    }\n\n    var fileAttributeType: FileAttributeType {\n        switch self {\n        case .directory: return .typeDirectory\n        case .file(_, _, let isSymlink, _): return isSymlink ? .typeSymbolicLink : .typeRegular\n        case .root: return .typeDirectory\n        }\n    }\n\n    var isDirectory: Bool {\n        switch self {\n        case .directory: return true\n        case .file: return false\n        case .root: return true\n        }\n    }\n\n    var isFile: Bool {\n        switch self {\n        case .directory: return false\n        case .file: return true\n        case .root: return false\n        }\n    }\n\n    var isRoot: Bool {\n        switch self {\n        case .directory: return false\n        case .file: return false\n        case .root: return true\n        }\n    }\n\n    var isSymlink: Bool {\n        switch self {\n        case .directory(_, let isSymlink, _): return isSymlink\n        case .file(_, _, let isSymlink, _): return isSymlink\n        case .root: return false\n        }\n    }\n}\n\nprivate enum Errors: Swift.Error, LocalizedError {\n    case noSuchFileOrDirectory(path: AbsolutePath)\n    case notAFile(path: AbsolutePath)\n    case readOnlyFileSystem\n    case unhandledDirectoryNode(path: AbsolutePath)\n\n    public var errorDescription: String? {\n        switch self {\n        case .noSuchFileOrDirectory(let path): return \"no such file or directory: \\(path.pathString)\"\n        case .notAFile(let path): return \"not a file: \\(path.pathString)\"\n        case .readOnlyFileSystem: return \"read-only filesystem\"\n        case .unhandledDirectoryNode(let path): return \"unhandled directory node: \\(path.pathString)\"\n        }\n    }\n}\n\nextension FileSystem {\n    fileprivate func getDirectoryNodes(\n        _ path: AbsolutePath,\n        includeContents: [AbsolutePath]\n    ) throws -> [DirectoryNode] {\n        try getDirectoryContents(path).compactMap {\n            let current = path.appending(component: $0)\n            let isSymlink = isSymlink(current)\n\n            if isFile(current) {\n                let contents: Data?\n                if includeContents.contains(current) {\n                    contents = try readFileContents(current)\n                } else {\n                    contents = nil\n                }\n                return .file(\n                    name: $0,\n                    isExecutable: isExecutableFile(current),\n                    isSymlink: isSymlink,\n                    contents: contents\n                )\n            } else if isDirectory(current) {\n                if $0.hasPrefix(\".\") { return nil } // we ignore hidden files\n                return .directory(\n                    name: $0,\n                    isSymlink: isSymlink,\n                    children: try getDirectoryNodes(current, includeContents: includeContents)\n                )\n            } else {\n                throw Errors.unhandledDirectoryNode(path: current)\n            }\n        }\n    }\n}\n\n/// A JSON-backed, read-only virtual file system.\npublic class VirtualFileSystem: FileSystem {\n    private let root: DirectoryNode\n\n    public init(path: TSCAbsolutePath, fs: FileSystem) throws {\n        self.root = try JSONDecoder.makeWithDefaults()\n            .decode(path: AbsolutePath(path), fileSystem: fs, as: DirectoryNode.self)\n        assert(self.root.isRoot, \"VFS needs to have a root node\")\n    }\n\n    /// Write information about the directory tree at `directoryPath` into a JSON file at `vfsPath`. This can later be used to construct a `VirtualFileSystem` object.\n    public static func serializeDirectoryTree(\n        _ directoryPath: AbsolutePath,\n        into vfsPath: AbsolutePath,\n        fs: FileSystem,\n        includeContents: [AbsolutePath]\n    ) throws {\n        let data = try JSONEncoder.makeWithDefaults().encode(\n            DirectoryNode.root(\n                children: fs.getDirectoryNodes(\n                    directoryPath,\n                    includeContents: includeContents\n                )\n            )\n        )\n        try data.write(to: URL(fileURLWithPath: vfsPath.pathString))\n    }\n\n    private func findNode(_ path: TSCAbsolutePath, followSymlink: Bool) -> DirectoryNode? {\n        var current: DirectoryNode? = self.root\n        for component in path.components {\n            if component == AbsolutePath.root.pathString { continue }\n            guard followSymlink, current?.isSymlink == false else { return nil }\n            current = current?.children.first(where: { $0.name == component })\n        }\n        return current\n    }\n\n    public func exists(_ path: TSCAbsolutePath, followSymlink: Bool) -> Bool {\n        findNode(path, followSymlink: followSymlink) != nil\n    }\n\n    public func isDirectory(_ path: TSCAbsolutePath) -> Bool {\n        findNode(path, followSymlink: true)?.isDirectory == true\n    }\n\n    public func isFile(_ path: TSCAbsolutePath) -> Bool {\n        findNode(path, followSymlink: true)?.isFile == true\n    }\n\n    public func isExecutableFile(_ path: TSCAbsolutePath) -> Bool {\n        guard let node = findNode(path, followSymlink: true) else { return false }\n        if case .file(_, let isExecutable, _, _) = node {\n            return isExecutable\n        } else {\n            return false\n        }\n    }\n\n    public func isSymlink(_ path: TSCAbsolutePath) -> Bool {\n        findNode(path, followSymlink: true)?.isSymlink == true\n    }\n\n    public func isReadable(_ path: TSCAbsolutePath) -> Bool {\n        self.exists(path)\n    }\n\n    public func isWritable(_: TSCAbsolutePath) -> Bool {\n        false\n    }\n\n    public func getDirectoryContents(_ path: TSCAbsolutePath) throws -> [String] {\n        guard let node = findNode(path, followSymlink: true)\n        else { throw Errors.noSuchFileOrDirectory(path: AbsolutePath(path)) }\n        return node.children.map(\\.name)\n    }\n\n    public let currentWorkingDirectory: TSCAbsolutePath? = nil\n\n    public func changeCurrentWorkingDirectory(to path: TSCAbsolutePath) throws {\n        throw Errors.readOnlyFileSystem\n    }\n\n    public var homeDirectory = TSCAbsolutePath.root\n\n    public var cachesDirectory: TSCAbsolutePath? = nil\n\n    public var tempDirectory = TSCAbsolutePath.root\n\n    public func createSymbolicLink(\n        _ path: TSCAbsolutePath,\n        pointingAt destination: TSCAbsolutePath,\n        relative: Bool\n    ) throws {\n        throw Errors.readOnlyFileSystem\n    }\n\n    public func removeFileTree(_: TSCAbsolutePath) throws {\n        throw Errors.readOnlyFileSystem\n    }\n\n    public func copy(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws {\n        throw Errors.readOnlyFileSystem\n    }\n\n    public func move(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws {\n        throw Errors.readOnlyFileSystem\n    }\n\n    public func createDirectory(_ path: TSCAbsolutePath, recursive: Bool) throws {\n        throw Errors.readOnlyFileSystem\n    }\n\n    public func readFileContents(_ path: TSCAbsolutePath) throws -> ByteString {\n        guard let node = findNode(path, followSymlink: true)\n        else { throw Errors.noSuchFileOrDirectory(path: AbsolutePath(path)) }\n        switch node {\n        case .directory: throw Errors.notAFile(path: AbsolutePath(path))\n        case .file(_, _, _, let contents):\n            if let contents {\n                return ByteString(contents)\n            } else {\n                return \"\"\n            }\n        case .root: throw Errors.notAFile(path: AbsolutePath(path))\n        }\n    }\n\n    public func writeFileContents(_ path: TSCAbsolutePath, bytes: ByteString) throws {\n        throw Errors.readOnlyFileSystem\n    }\n\n    public func chmod(_ mode: FileMode, path: TSCAbsolutePath, options: Set<FileMode.Option>) throws {\n        throw Errors.readOnlyFileSystem\n    }\n\n    public func getFileInfo(_ path: TSCAbsolutePath) throws -> FileInfo {\n        guard let node = findNode(path, followSymlink: true)\n        else { throw Errors.noSuchFileOrDirectory(path: AbsolutePath(path)) }\n\n        let attrs: [FileAttributeKey: Any] = [\n            .systemNumber: NSNumber(value: UInt64(0)),\n            .systemFileNumber: UInt64(0),\n            .posixPermissions: NSNumber(value: Int16(0)),\n            .type: node.fileAttributeType,\n            .size: UInt64(0),\n            .modificationDate: Date(),\n        ]\n        return FileInfo(attrs)\n    }\n}\n\n// `VirtualFileSystem` is read-only, so it can be marked as `Sendable`.\nextension VirtualFileSystem: @unchecked Sendable {}\n"
  },
  {
    "path": "Sources/Basics/Graph/AdjacencyMatrix.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A matrix storing bits of `true`/`false` state for a given combination of row and column indices. Used as\n/// a square matrix indicating edges in graphs, where rows and columns are indices in a storage of graph's nodes.\n///\n/// For example, in a graph that contains 3 nodes `matrix[row: 1, column: 2]` evaluating to `true` means an edge\n/// between nodes with indices `1` and `2` exists. `matrix[row: 1, column: 2]` evaluating to `false` means that no\n/// edge exists.\n///\n/// See https://en.wikipedia.org/wiki/Adjacency_matrix for more details.\nstruct AdjacencyMatrix {\n    let columns: Int\n    let rows: Int\n    private var bytes: [UInt8]\n\n    /// Allocates a new bit matrix with a given size.\n    /// - Parameters:\n    ///   - rows: Number of rows in the matrix.\n    ///   - columns: Number of columns in the matrix.\n    init(rows: Int, columns: Int) {\n        self.columns = columns\n        self.rows = rows\n        \n        let (quotient, remainder) = (rows * columns).quotientAndRemainder(dividingBy: 8)\n        self.bytes = .init(repeating: 0, count: quotient + (remainder > 0 ? 1 : 0))\n    }\n\n    var bitCount: Int {\n        bytes.count * 8\n    }\n\n    private func calculateOffsets(row: Int, column: Int) -> (byteOffset: Int, bitOffsetInByte: Int) {\n        let totalBitOffset = row * columns + column\n        return (byteOffset: totalBitOffset / 8, bitOffsetInByte: totalBitOffset % 8)\n    }\n\n    subscript(row: Int, column: Int) -> Bool {\n        get {\n            let (byteOffset, bitOffsetInByte) = calculateOffsets(row: row, column: column)\n\n            let result = (self.bytes[byteOffset] >> bitOffsetInByte) & 1\n            return result == 1\n        }\n\n        set {\n            let (byteOffset, bitOffsetInByte) = calculateOffsets(row: row, column: column)\n\n            self.bytes[byteOffset] |= 1 << bitOffsetInByte\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Graph/DirectedGraph.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nprivate import DequeModule\n\n/// Directed graph that stores edges in [adjacency lists](https://en.wikipedia.org/wiki/Adjacency_list).\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\npublic struct DirectedGraph<Node> {\n    public init(nodes: [Node]) {\n        self.nodes = nodes\n        self.edges = .init(repeating: [], count: nodes.count)\n    }\n\n    public private(set) var nodes: [Node]\n    private var edges: [[Int]]\n\n    public mutating func addEdge(source: Int, destination: Int) {\n        self.edges[source].append(destination)\n    }\n    \n    /// Checks whether a path via previously created edges between two given nodes exists.\n    /// - Parameters:\n    ///   - source: `Index` of a node to start traversing edges from.\n    ///   - destination: `Index` of a node to which a path could exist via edges from `source`.\n    /// - Returns: `true` if a path from `source` to `destination` exists, `false` otherwise.\n    @_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\n    public func areNodesConnected(source: Int, destination: Int) -> Bool {\n        var todo = Deque<Int>([source])\n        var done = Set<Int>()\n\n        while !todo.isEmpty {\n            let nodeIndex = todo.removeFirst()\n\n            for reachableIndex in self.edges[nodeIndex] {\n                if reachableIndex == destination {\n                    return true\n                } else if !done.contains(reachableIndex) {\n                    todo.append(reachableIndex)\n                }\n            }\n\n            done.insert(nodeIndex)\n        }\n\n        return false\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Graph/GraphAlgorithms.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct OrderedCollections.OrderedSet\n\n/// Implements a pre-order depth-first search.\n///\n/// The cycles are handled by skipping cycle points but it should be possible to\n/// to extend this in the future to provide a callback for every cycle.\n///\n/// - Parameters:\n///   - nodes: The list of input nodes to sort.\n///   - successors: A closure for fetching the successors of a particular node.\n///   - onUnique: A callback to indicate the the given node is being processed for the first time.\n///   - onDuplicate: A callback to indicate that the node was already processed at least once.\n///\n/// - Complexity: O(v + e) where (v, e) are the number of vertices and edges\n/// reachable from the input nodes via the relation.\npublic func depthFirstSearch<T: Hashable>(\n    _ nodes: [T],\n    successors: (T) throws -> [T],\n    onUnique: (T) throws -> Void,\n    onDuplicate: (T, T) -> Void\n) rethrows {\n    var stack = OrderedSet<T>()\n    var visited = Set<T>()\n\n    for node in nodes {\n        precondition(stack.isEmpty)\n        stack.append(node)\n\n        while !stack.isEmpty {\n            let curr = stack.removeLast()\n\n            let visitResult = visited.insert(curr)\n            if visitResult.inserted {\n                try onUnique(curr)\n            } else {\n                onDuplicate(visitResult.memberAfterInsert, curr)\n                continue\n            }\n\n            for succ in try successors(curr) {\n                stack.append(succ)\n            }\n        }\n    }\n}\n\npublic func depthFirstSearch<T: Hashable>(\n    _ nodes: [T],\n    successors: (T) async throws -> [T],\n    onUnique: (T) async throws -> Void,\n    onDuplicate: (T, T) async -> Void\n) async rethrows {\n    var stack = OrderedSet<T>()\n    var visited = Set<T>()\n\n    for node in nodes {\n        precondition(stack.isEmpty)\n        stack.append(node)\n\n        while !stack.isEmpty {\n            let curr = stack.removeLast()\n\n            let visitResult = visited.insert(curr)\n            if visitResult.inserted {\n                try await onUnique(curr)\n            } else {\n                await onDuplicate(visitResult.memberAfterInsert, curr)\n                continue\n            }\n\n            for succ in try await successors(curr) {\n                stack.append(succ)\n            }\n        }\n    }\n}\n\nprivate struct TraversalNode<T: Hashable>: Hashable {\n    let parent: T?\n    let curr: T\n}\n\n/// Implements a pre-order depth-first search that traverses the whole graph and\n/// doesn't distinguish between unique and duplicate nodes. The method expects\n/// the graph to be acyclic but doesn't check that.\n///\n/// - Parameters:\n///   - nodes: The list of input nodes to sort.\n///   - successors: A closure for fetching the successors of a particular node.\n///   - onNext: A callback to indicate the node currently being processed\n///             including its parent (if any) and its depth.\n///\n/// - Complexity: O(v + e) where (v, e) are the number of vertices and edges\n/// reachable from the input nodes via the relation.\npublic func depthFirstSearch<T: Hashable>(\n    _ nodes: [T],\n    successors: (T) throws -> [T],\n    onNext: (T, _ parent: T?) throws -> Void\n) rethrows {\n    var stack = OrderedSet<TraversalNode<T>>()\n\n    for node in nodes {\n        precondition(stack.isEmpty)\n        stack.append(TraversalNode(parent: nil, curr: node))\n\n        while !stack.isEmpty {\n            let node = stack.removeLast()\n\n            try onNext(node.curr, node.parent)\n\n            for succ in try successors(node.curr) {\n                stack.append(\n                    TraversalNode(\n                        parent: node.curr,\n                        curr: succ\n                    )\n                )\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Graph/UndirectedGraph.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nprivate import DequeModule\n\n/// Undirected graph that stores edges in an [adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix).\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\npublic struct UndirectedGraph<Node> {\n    public init(nodes: [Node]) {\n        self.nodes = nodes\n        self.edges = .init(rows: nodes.count, columns: nodes.count)\n    }\n\n    private var nodes: [Node]\n    private var edges: AdjacencyMatrix\n\n    public mutating func addEdge(source: Int, destination: Int) {\n        // Adjacency matrix is symmetrical for undirected graphs.\n        self.edges[source, destination] = true\n        self.edges[destination, source] = true\n    }\n\n    /// Checks whether a connection via previously created edges between two given nodes exists.\n    /// - Parameters:\n    ///   - source: `Index` of a node to start traversing edges from.\n    ///   - destination: `Index` of a node to which a connection could exist via edges from `source`.\n    /// - Returns: `true` if a path from `source` to `destination` exists, `false` otherwise.\n    public func areNodesConnected(source: Int, destination: Int) -> Bool {\n        var todo = Deque<Int>([source])\n        var done = Set<Int>()\n\n        while !todo.isEmpty {\n            let nodeIndex = todo.removeFirst()\n\n            for reachableIndex in self.edges.nodesAdjacentTo(nodeIndex) {\n                if reachableIndex == destination {\n                    return true\n                } else if !done.contains(reachableIndex) {\n                    todo.append(reachableIndex)\n                }\n            }\n\n            done.insert(nodeIndex)\n        }\n\n        return false\n    }\n}\n\nprivate extension AdjacencyMatrix {\n    func nodesAdjacentTo(_ nodeIndex: Int) -> [Int] {\n        var result = [Int]()\n\n        for i in 0..<self.rows where self[i, nodeIndex] {\n            result.append(i)\n        }\n\n        return result\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/HTTPClient.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Foundation\n\n/// `async`-friendly wrapper for HTTP clients. It allows a specific client implementation (either Foundation or\n/// NIO-based) to be hidden from users of the wrapper.\npublic actor HTTPClient {\n    public typealias Configuration = HTTPClientConfiguration\n    public typealias Request = HTTPClientRequest\n    public typealias Response = HTTPClientResponse\n    public typealias ProgressHandler = @Sendable (_ bytesReceived: Int64, _ totalBytes: Int64?) throws -> Void\n    public typealias Implementation = @Sendable (Request, ProgressHandler?) async throws -> Response\n\n    /// Record of errors that occurred when querying a host applied in a circuit-breaking strategy.\n    private struct HostErrors {\n        var numberOfErrors: Int\n        var lastError: Date\n    }\n\n    /// Configuration used by ``HTTPClient`` when handling requests.\n    private let configuration: HTTPClientConfiguration\n\n    /// Underlying implementation of ``HTTPClient``.\n    private let implementation: Implementation\n\n    /// An `async`-friendly semaphore to handle limits on the number of concurrent requests.\n    private let tokenBucket: TokenBucket\n\n    /// Array of `HostErrors` values, which is used for applying a circuit-breaking strategy.\n    private var hostsErrors = [String: HostErrors]()\n\n    /// Tracks all active network request tasks.\n    private var activeTasks: Set<Task<HTTPClient.Response, Error>> = []\n\n    public init(configuration: HTTPClientConfiguration = .init(), implementation: Implementation? = nil) {\n        self.configuration = configuration\n        self.implementation = implementation ?? URLSessionHTTPClient().execute\n        self.tokenBucket = TokenBucket(tokens: configuration.maxConcurrentRequests ?? Concurrency.maxOperations)\n    }\n\n    /// Execute an HTTP request asynchronously\n    ///\n    /// - Parameters:\n    ///   - request: The ``HTTPClientRequest`` to perform.\n    ///   - observabilityScope: the observability scope to emit diagnostics on.\n    ///   - progress: A closure to handle response download progress.\n    /// - Returns: A response value returned by underlying ``HTTPClient.Implementation``.\n    public func execute(\n        _ request: Request,\n        observabilityScope: ObservabilityScope? = nil,\n        progress: ProgressHandler? = nil\n    ) async throws -> Response {\n        // merge configuration\n        var request = request\n        if request.options.retryStrategy == nil {\n            request.options.retryStrategy = self.configuration.retryStrategy\n        }\n        if request.options.circuitBreakerStrategy == nil {\n            request.options.circuitBreakerStrategy = self.configuration.circuitBreakerStrategy\n        }\n        if request.options.timeout == nil {\n            request.options.timeout = self.configuration.requestTimeout\n        }\n        if request.options.authorizationProvider == nil {\n            request.options.authorizationProvider = self.configuration.authorizationProvider\n        }\n        // add additional headers\n        if let additionalHeaders = self.configuration.requestHeaders {\n            additionalHeaders.forEach {\n                request.headers.add($0)\n            }\n        }\n        if request.options.addUserAgent, !request.headers.contains(\"User-Agent\") {\n            request.headers.add(name: \"User-Agent\", value: \"SwiftPackageManager/\\(SwiftVersion.current.displayString)\")\n        }\n\n        if let authorization = request.options.authorizationProvider?(request.url),\n           !authorization.isEmpty,\n           !request.headers.contains(\"Authorization\")\n        {\n            request.headers.add(name: \"Authorization\", value: authorization)\n        }\n\n        return try await self.executeWithStrategies(request: request, requestNumber: 0, observabilityScope, progress)\n    }\n\n    /// Cancel all in flight network reqeusts.\n    public func cancel(deadline: DispatchTime) async {\n        for task in activeTasks {\n            task.cancel()\n        }\n\n        // Wait for tasks to complete or timeout\n        while !activeTasks.isEmpty && (deadline.distance(to: .now()).nanoseconds() ?? 0) > 0 {\n            await Task.yield()\n        }\n\n        // Clear out the active task list regardless of whether they completed or not\n        activeTasks.removeAll()\n    }\n\n    private func executeWithStrategies(\n        request: Request,\n        requestNumber: Int,\n        _ observabilityScope: ObservabilityScope?,\n        _ progress: ProgressHandler?\n    ) async throws -> Response {\n        // apply circuit breaker if necessary\n        if self.shouldCircuitBreak(request: request) {\n            observabilityScope?.emit(warning: \"Circuit breaker triggered for \\(request.url)\")\n            throw HTTPClientError.circuitBreakerTriggered\n        }\n\n        let task = Task {\n            let response = try await self.tokenBucket.withToken {\n                try Task.checkCancellation()\n\n                return try await self.implementation(request) { received, expected in\n                    if let max = request.options.maximumResponseSizeInBytes {\n                        guard received < max else {\n                            // It's a responsibility of the underlying client implementation to cancel the request\n                            // when this closure throws an error\n                            throw HTTPClientError.responseTooLarge(received)\n                        }\n                    }\n\n                    try progress?(received, expected)\n                }\n            }\n\n            self.recordErrorIfNecessary(response: response, request: request)\n\n            // handle retry strategy\n            if let retryDelay = self.calculateRetry(\n                response: response,\n                request: request,\n                requestNumber: requestNumber\n            ), let retryDelayInNanoseconds = retryDelay.nanoseconds() {\n                try Task.checkCancellation()\n\n                observabilityScope?.emit(warning: \"\\(request.url) failed, retrying in \\(retryDelay)\")\n                try await Task.sleep(nanoseconds: UInt64(retryDelayInNanoseconds))\n\n                return try await self.executeWithStrategies(\n                    request: request,\n                    requestNumber: requestNumber + 1,\n                    observabilityScope,\n                    progress\n                )\n            }\n            // check for valid response codes\n            if let validResponseCodes = request.options.validResponseCodes,\n            !validResponseCodes.contains(response.statusCode)\n            {\n                throw HTTPClientError.badResponseStatusCode(response.statusCode)\n            } else {\n                return response\n            }\n        }\n\n        activeTasks.insert(task)\n        defer { activeTasks.remove(task) }\n\n        return try await task.value\n    }\n\n    private func calculateRetry(response: Response, request: Request, requestNumber: Int) -> SendableTimeInterval? {\n        guard let strategy = request.options.retryStrategy, response.statusCode >= 500 else {\n            return nil\n        }\n\n        switch strategy {\n        case .exponentialBackoff(let maxAttempts, let delay):\n            guard requestNumber < maxAttempts - 1 else {\n                return nil\n            }\n            let exponential = Int(min(pow(2.0, Double(requestNumber)), Double(Int.max)))\n            let delayMilli = exponential.multipliedReportingOverflow(by: delay.milliseconds() ?? 0).partialValue\n            let jitterMilli = Int.random(in: 1 ... 10)\n            return .milliseconds(delayMilli + jitterMilli)\n        }\n    }\n\n    private func recordErrorIfNecessary(response: Response, request: Request) {\n        guard let strategy = request.options.circuitBreakerStrategy, response.statusCode >= 500 else {\n            return\n        }\n\n        switch strategy {\n        case .hostErrors:\n            guard let host = request.url.host else {\n                return\n            }\n            // Avoid copy-on-write: remove entry from dictionary before mutating\n            let hostErrors: HostErrors\n            if var errors = self.hostsErrors.removeValue(forKey: host) {\n                errors.numberOfErrors += 1\n                errors.lastError = Date()\n                hostErrors = errors\n            } else {\n                hostErrors = HostErrors(numberOfErrors: 1, lastError: Date())\n            }\n            self.hostsErrors[host] = hostErrors\n        }\n    }\n\n    private func shouldCircuitBreak(request: Request) -> Bool {\n        guard let strategy = request.options.circuitBreakerStrategy else {\n            return false\n        }\n\n        switch strategy {\n        case .hostErrors(let maxErrors, let age):\n            if let host = request.url.host, let errors = self.hostsErrors[host] {\n                if errors.numberOfErrors >= maxErrors, let age = age.timeInterval() {\n                    return Date().timeIntervalSince(errors.lastError) <= age\n                } else if errors.numberOfErrors >= maxErrors {\n                    // reset aged errors\n                    self.hostsErrors[host] = nil\n                }\n            }\n            return false\n        }\n    }\n}\n\nextension HTTPClient {\n    public func head(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init()\n    ) async throws -> Response {\n        try await self.execute(\n            Request(method: .head, url: url, headers: headers, body: nil, options: options)\n        )\n    }\n\n    public func get(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init()\n    ) async throws -> Response {\n        try await self.execute(\n            Request(method: .get, url: url, headers: headers, body: nil, options: options)\n        )\n    }\n\n    public func put(\n        _ url: URL,\n        body: Data?,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init()\n    ) async throws -> Response {\n        try await self.execute(\n            Request(method: .put, url: url, headers: headers, body: body, options: options)\n        )\n    }\n\n    public func post(\n        _ url: URL,\n        body: Data?,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init()\n    ) async throws -> Response {\n        try await self.execute(\n            Request(method: .post, url: url, headers: headers, body: body, options: options)\n        )\n    }\n\n    public func delete(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init()\n    ) async throws -> Response {\n        try await self.execute(\n            Request(method: .delete, url: url, headers: headers, body: nil, options: options)\n        )\n    }\n\n    public func download(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init(),\n        progressHandler: ProgressHandler? = nil,\n        fileSystem: FileSystem,\n        destination: AbsolutePath,\n        observabilityScope: ObservabilityScope? = .none\n    ) async throws -> Response {\n        try await self.execute(\n            Request(\n                kind: .download(fileSystem: fileSystem, destination: destination),\n                url: url,\n                headers: headers,\n                body: nil,\n                options: options\n            ),\n            observabilityScope: observabilityScope,\n            progress: progressHandler\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/HTTPClientConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct HTTPClientConfiguration: Sendable {\n    // FIXME: this should be unified with ``AuthorizationProvider`` protocol or renamed to avoid unintended shadowing.\n    public typealias AuthorizationProvider = @Sendable (URL)\n        -> String?\n\n    public init(\n        requestHeaders: HTTPClientHeaders? = nil,\n        requestTimeout: SendableTimeInterval? = nil,\n        authorizationProvider: AuthorizationProvider? = nil,\n        retryStrategy: HTTPClientRetryStrategy? = nil,\n        circuitBreakerStrategy: HTTPClientCircuitBreakerStrategy? = nil,\n        maxConcurrentRequests: Int? = nil\n    ) {\n        self.requestHeaders = requestHeaders\n        self.requestTimeout = requestTimeout\n        self.authorizationProvider = authorizationProvider\n        self.retryStrategy = retryStrategy\n        self.circuitBreakerStrategy = circuitBreakerStrategy\n        self.maxConcurrentRequests = maxConcurrentRequests\n    }\n\n    public var requestHeaders: HTTPClientHeaders?\n    // FIXME: replace with `Duration` when that's available for back-deployment or minimum macOS is bumped to 13.0+\n    public var requestTimeout: SendableTimeInterval?\n    public var authorizationProvider: AuthorizationProvider?\n    public var retryStrategy: HTTPClientRetryStrategy?\n    public var circuitBreakerStrategy: HTTPClientCircuitBreakerStrategy?\n    public var maxConcurrentRequests: Int?\n}\n\npublic enum HTTPClientRetryStrategy: Sendable {\n    case exponentialBackoff(maxAttempts: Int, baseDelay: SendableTimeInterval)\n}\n\npublic enum HTTPClientCircuitBreakerStrategy: Sendable {\n    case hostErrors(maxErrors: Int, age: SendableTimeInterval)\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/HTTPClientError.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic enum HTTPClientError: Error, Equatable {\n    case invalidResponse\n    case badResponseStatusCode(Int)\n    case circuitBreakerTriggered\n    case responseTooLarge(Int64)\n    case downloadError(String)\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/HTTPClientHeaders.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct HTTPClientHeaders: Sendable {\n    private var items: [Item]\n    private var headers: [String: [String]]\n\n    public init(_ items: [Item] = []) {\n        self.items = items\n        self.headers = items.reduce([String: [String]]()) { partial, item in\n            var map = partial\n            // Avoid copy-on-write: remove entry from dictionary before mutating\n            var values = map.removeValue(forKey: item.name.lowercased()) ?? []\n            values.append(item.value)\n            map[item.name.lowercased()] = values\n            return map\n        }\n    }\n\n    public func contains(_ name: String) -> Bool {\n        self.headers[name.lowercased()] != nil\n    }\n\n    public var count: Int {\n        self.headers.count\n    }\n\n    public mutating func add(name: String, value: String) {\n        self.add(Item(name: name, value: value))\n    }\n\n    public mutating func add(_ item: Item) {\n        self.add([item])\n    }\n\n    public mutating func add(_ items: [Item]) {\n        for item in items {\n            if self.items.contains(item) {\n                continue\n            }\n            // Avoid copy-on-write: remove entry from dictionary before mutating\n            var values = self.headers.removeValue(forKey: item.name.lowercased()) ?? []\n            values.append(item.value)\n            self.headers[item.name.lowercased()] = values\n            self.items.append(item)\n        }\n    }\n\n    public mutating func merge(_ other: HTTPClientHeaders) {\n        self.add(other.items)\n    }\n\n    public func get(_ name: String) -> [String] {\n        self.headers[name.lowercased()] ?? []\n    }\n\n    public struct Item: Equatable, Sendable {\n        let name: String\n        let value: String\n\n        public init(name: String, value: String) {\n            self.name = name\n            self.value = value\n        }\n    }\n}\n\nextension HTTPClientHeaders: Sequence {\n    public func makeIterator() -> IndexingIterator<[Item]> {\n        self.items.makeIterator()\n    }\n}\n\nextension HTTPClientHeaders: Equatable {\n    public static func == (lhs: HTTPClientHeaders, rhs: HTTPClientHeaders) -> Bool {\n        lhs.headers == rhs.headers\n    }\n}\n\nextension HTTPClientHeaders: ExpressibleByDictionaryLiteral {\n    public init(dictionaryLiteral elements: (String, String)...) {\n        self.init(elements.map(Item.init))\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/HTTPClientRequest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct HTTPClientRequest: Sendable {\n    public let kind: Kind\n    public let url: URL\n    public var headers: HTTPClientHeaders\n    public var body: Data?\n    public var options: Options\n\n    public init(\n        kind: Kind,\n        url: URL,\n        headers: HTTPClientHeaders = .init(),\n        body: Data? = nil,\n        options: Options = .init()\n    ) {\n        self.kind = kind\n        self.url = url\n        self.headers = headers\n        self.body = body\n        self.options = options\n    }\n\n    // generic request\n    public init(\n        method: HTTPMethod = .get,\n        url: URL,\n        headers: HTTPClientHeaders = .init(),\n        body: Data? = nil,\n        options: Options = .init()\n    ) {\n        self.init(kind: .generic(method), url: url, headers: headers, body: body, options: options)\n    }\n\n    // download request\n    public static func download(\n        url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Options = .init(),\n        fileSystem: FileSystem,\n        destination: AbsolutePath\n    ) -> Self {\n        self.init(\n            kind: .download(fileSystem: fileSystem, destination: destination),\n            url: url,\n            headers: headers,\n            body: nil,\n            options: options\n        )\n    }\n\n    public var method: HTTPMethod {\n        switch self.kind {\n        case .generic(let method):\n            return method\n        case .download:\n            return .get\n        }\n    }\n\n    public enum Kind: Sendable {\n        case generic(HTTPMethod)\n        case download(fileSystem: FileSystem, destination: AbsolutePath)\n    }\n\n    public struct Options: Sendable {\n        public var addUserAgent: Bool\n        public var validResponseCodes: [Int]?\n        public var timeout: SendableTimeInterval?\n        public var maximumResponseSizeInBytes: Int64?\n        public var authorizationProvider: HTTPClientConfiguration.AuthorizationProvider?\n        public var retryStrategy: HTTPClientRetryStrategy?\n        public var circuitBreakerStrategy: HTTPClientCircuitBreakerStrategy?\n\n        public init() {\n            self.addUserAgent = true\n            self.validResponseCodes = .none\n            self.timeout = .none\n            self.maximumResponseSizeInBytes = .none\n            self.authorizationProvider = .none\n            self.retryStrategy = .none\n            self.circuitBreakerStrategy = .none\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/HTTPClientResponse.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct HTTPClientResponse: Sendable {\n    public let statusCode: Int\n    public let statusText: String?\n    public let headers: HTTPClientHeaders\n    public let body: Data?\n\n    public init(\n        statusCode: Int,\n        statusText: String? = nil,\n        headers: HTTPClientHeaders = .init(),\n        body: Data? = nil\n    ) {\n        self.statusCode = statusCode\n        self.statusText = statusText\n        self.headers = headers\n        self.body = body\n    }\n\n    public func decodeBody<T: Decodable>(_ type: T.Type, using decoder: JSONDecoder = .init()) throws -> T? {\n        try self.body.flatMap { try decoder.decode(type, from: $0) }\n    }\n}\n\nextension HTTPClientResponse {\n    public static func okay(body: String? = nil) -> HTTPClientResponse {\n        .okay(body: body.map { Data($0.utf8) })\n    }\n\n    public static func okay(body: Data?) -> HTTPClientResponse {\n        HTTPClientResponse(statusCode: 200, body: body)\n    }\n\n    public static func notFound(reason: String? = nil) -> HTTPClientResponse {\n        HTTPClientResponse(statusCode: 404, body: Data((reason ?? \"Not Found\").utf8))\n    }\n\n    public static func serverError(reason: String? = nil) -> HTTPClientResponse {\n        HTTPClientResponse(statusCode: 500, body: Data((reason ?? \"Internal Server Error\").utf8))\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/HTTPMethod.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic enum HTTPMethod: Sendable {\n    case head\n    case get\n    case post\n    case put\n    case delete\n\n    var string: String {\n        switch self {\n        case .head:\n            return \"HEAD\"\n        case .get:\n            return \"GET\"\n        case .post:\n            return \"POST\"\n        case .put:\n            return \"PUT\"\n        case .delete:\n            return \"DELETE\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/LegacyHTTPClient.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Dispatch\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.NSLock\nimport class Foundation.OperationQueue\nimport func Foundation.pow\nimport struct Foundation.URL\nimport struct Foundation.UUID\n\n// MARK: - LegacyHTTPClient\n\npublic final class LegacyHTTPClient: Cancellable {\n    public typealias Configuration = LegacyHTTPClientConfiguration\n    public typealias Request = LegacyHTTPClientRequest\n    public typealias Response = HTTPClientResponse\n    public typealias Handler = (Request, ProgressHandler?, @escaping @Sendable (Result<Response, Error>) -> Void) -> Void\n    public typealias ProgressHandler = @Sendable (_ bytesReceived: Int64, _ totalBytes: Int64?) throws -> Void\n    public typealias CompletionHandler = @Sendable (Result<HTTPClientResponse, Error>) -> Void\n\n    public var configuration: LegacyHTTPClientConfiguration\n    private let underlying: Handler\n\n    /// DispatchSemaphore to restrict concurrent operations on manager.\n    private let concurrencySemaphore: DispatchSemaphore\n    /// OperationQueue to park pending requests\n    private let requestsQueue: OperationQueue\n\n    private struct OutstandingRequest {\n        let url: URL\n        let completion: CompletionHandler\n        let progress: ProgressHandler?\n        let queue: DispatchQueue\n    }\n\n    // tracks outstanding requests for cancellation\n    private var outstandingRequests = ThreadSafeKeyValueStore<UUID, OutstandingRequest>()\n\n    // static to share across instances of the http client\n    private static let hostsErrorsLock = NSLock()\n    private static var hostsErrors = [String: [Date]]()\n\n    public init(configuration: LegacyHTTPClientConfiguration = .init(), handler: Handler? = nil) {\n        self.configuration = configuration\n        // FIXME: inject platform specific implementation here\n        self.underlying = handler ?? URLSessionHTTPClient().execute\n\n        // this queue and semaphore is used to limit the amount of concurrent http requests taking place\n        // the default max number of request chosen to match Concurrency.maxOperations which is the number of active\n        // CPUs\n        let maxConcurrentRequests = configuration.maxConcurrentRequests ?? Concurrency.maxOperations\n        self.requestsQueue = OperationQueue()\n        self.requestsQueue.name = \"org.swift.swiftpm.http-client\"\n        self.requestsQueue.maxConcurrentOperationCount = maxConcurrentRequests\n        self.concurrencySemaphore = DispatchSemaphore(value: maxConcurrentRequests)\n    }\n\n    /// Execute an HTTP request asynchronously\n    ///\n    /// - Parameters:\n    ///   - request: The `HTTPClientRequest` to perform.\n    ///   - observabilityScope: the observability scope to emit diagnostics on\n    ///   - progress: A progress handler to handle progress for example for downloads\n    ///   - completion: A completion handler to be notified of the completion of the request.\n    public func execute(\n        _ request: Request,\n        observabilityScope: ObservabilityScope? = nil,\n        progress: ProgressHandler? = nil,\n        completion: @escaping CompletionHandler\n    ) {\n        // merge configuration\n        var request = request\n        if request.options.callbackQueue == nil {\n            request.options.callbackQueue = self.configuration.callbackQueue\n        }\n        if request.options.retryStrategy == nil {\n            request.options.retryStrategy = self.configuration.retryStrategy\n        }\n        if request.options.circuitBreakerStrategy == nil {\n            request.options.circuitBreakerStrategy = self.configuration.circuitBreakerStrategy\n        }\n        if request.options.timeout == nil {\n            request.options.timeout = self.configuration.requestTimeout\n        }\n        if request.options.authorizationProvider == nil {\n            request.options.authorizationProvider = self.configuration.authorizationProvider\n        }\n        // add additional headers\n        if let additionalHeaders = self.configuration.requestHeaders {\n            additionalHeaders.forEach {\n                request.headers.add($0)\n            }\n        }\n        if request.options.addUserAgent, !request.headers.contains(\"User-Agent\") {\n            request.headers.add(name: \"User-Agent\", value: \"SwiftPackageManager/\\(SwiftVersion.current.displayString)\")\n        }\n\n        if let authorization = request.options.authorizationProvider?(request.url),\n           !authorization.isEmpty,\n           !request.headers.contains(\"Authorization\")\n        {\n            request.headers.add(name: \"Authorization\", value: authorization)\n        }\n        // execute\n        guard let callbackQueue = request.options.callbackQueue else {\n            return completion(.failure(InternalError(\"unknown callback queue\")))\n        }\n        self._execute(\n            request: request,\n            requestNumber: 0,\n            observabilityScope: observabilityScope,\n            progress: progress.map { handler in\n                { @Sendable received, expected in\n                    // call back on the requested queue\n                    callbackQueue.async {\n                        do {\n                            try handler(received, expected)\n                        } catch {\n                            completion(.failure(error))\n                        }\n                    }\n                }\n            },\n            completion: { result in\n                // call back on the requested queue\n                callbackQueue.async {\n                    completion(result)\n                }\n            }\n        )\n    }\n\n    /// Cancel any outstanding requests\n    public func cancel(deadline: DispatchTime) throws {\n        let outstanding = self.outstandingRequests.clear()\n        for value in outstanding.values {\n            value.queue.async {\n                value.completion(.failure(CancellationError()))\n            }\n        }\n    }\n\n    private func _execute(\n        request: Request,\n        requestNumber: Int,\n        observabilityScope: ObservabilityScope?,\n        progress: ProgressHandler?,\n        completion: @escaping CompletionHandler\n    ) {\n        // records outstanding requests for cancellation purposes\n        guard let callbackQueue = request.options.callbackQueue else {\n            return completion(.failure(InternalError(\"unknown callback queue\")))\n        }\n        let requestKey = UUID()\n        self.outstandingRequests[requestKey] =\n            .init(url: request.url, completion: completion, progress: progress, queue: callbackQueue)\n\n        // wrap completion handler with concurrency control cleanup\n        let originalCompletion = completion\n        let completion: CompletionHandler = { result in\n            // free concurrency control semaphore\n            self.concurrencySemaphore.signal()\n            // cancellation support\n            // if the callback is no longer on the pending lists it has been canceled already\n            // read + remove from outstanding requests atomically\n            if let outstandingRequest = self.outstandingRequests.removeValue(forKey: requestKey) {\n                // call back on the request queue\n                outstandingRequest.queue.async { outstandingRequest.completion(result) }\n            }\n        }\n\n        // we must not block the calling thread (for concurrency control) so nesting this in a queue\n        self.requestsQueue.addOperation {\n            // park the request thread based on the max concurrency allowed\n            self.concurrencySemaphore.wait()\n\n            // apply circuit breaker if necessary\n            if self.shouldCircuitBreak(request: request) {\n                observabilityScope?.emit(warning: \"Circuit breaker triggered for \\(request.url)\")\n                return completion(.failure(HTTPClientError.circuitBreakerTriggered))\n            }\n\n            // call underlying handler\n            self.underlying(\n                request,\n                { received, expected in\n                    if let max = request.options.maximumResponseSizeInBytes {\n                        guard received < max else {\n                            // It's a responsibility of the underlying client implementation to cancel the request\n                            // when this closure throws an error\n                            throw HTTPClientError.responseTooLarge(received)\n                        }\n                    }\n                    try progress?(received, expected)\n                },\n                { result in\n                    // handle result\n                    switch result {\n                    case .failure(let error):\n                        completion(.failure(error))\n                    case .success(let response):\n                        // record host errors for circuit breaker\n                        self.recordErrorIfNecessary(response: response, request: request)\n                        // handle retry strategy\n                        if let retryDelay = self.shouldRetry(\n                            response: response,\n                            request: request,\n                            requestNumber: requestNumber\n                        ) {\n                            observabilityScope?.emit(warning: \"\\(request.url) failed, retrying in \\(retryDelay)\")\n                            // free concurrency control semaphore and outstanding request,\n                            // since we re-submitting the request with the original completion handler\n                            // using the wrapped completion handler may lead to starving the max concurrent requests\n                            self.concurrencySemaphore.signal()\n                            self.outstandingRequests[requestKey] = nil\n                            // TODO: dedicated retry queue?\n                            return self.configuration.callbackQueue.asyncAfter(deadline: .now() + retryDelay) {\n                                self._execute(\n                                    request: request,\n                                    requestNumber: requestNumber + 1,\n                                    observabilityScope: observabilityScope,\n                                    progress: progress,\n                                    completion: originalCompletion\n                                )\n                            }\n                        }\n                        // check for valid response codes\n                        if let validResponseCodes = request.options.validResponseCodes,\n                           !validResponseCodes.contains(response.statusCode)\n                        {\n                            return completion(.failure(HTTPClientError.badResponseStatusCode(response.statusCode)))\n                        }\n                        completion(.success(response))\n                    }\n                }\n            )\n        }\n    }\n\n    private func shouldRetry(response: Response, request: Request, requestNumber: Int) -> DispatchTimeInterval? {\n        guard let strategy = request.options.retryStrategy, response.statusCode >= 500 else {\n            return .none\n        }\n\n        switch strategy {\n        case .exponentialBackoff(let maxAttempts, let delay):\n            guard requestNumber < maxAttempts - 1 else {\n                return .none\n            }\n            let exponential = Int(min(pow(2.0, Double(requestNumber)), Double(Int.max)))\n            let delayMilli = exponential.multipliedReportingOverflow(by: delay.milliseconds() ?? 0).partialValue\n            let jitterMilli = Int.random(in: 1 ... 10)\n            return .milliseconds(delayMilli + jitterMilli)\n        }\n    }\n\n    private func recordErrorIfNecessary(response: Response, request: Request) {\n        guard let strategy = request.options.circuitBreakerStrategy, response.statusCode >= 500 else {\n            return\n        }\n\n        switch strategy {\n        case .hostErrors:\n            guard let host = request.url.host else {\n                return\n            }\n            Self.hostsErrorsLock.withLock {\n                // Avoid copy-on-write: remove entry from dictionary before mutating\n                var errors = Self.hostsErrors.removeValue(forKey: host) ?? []\n                errors.append(Date())\n                Self.hostsErrors[host] = errors\n            }\n        }\n    }\n\n    private func shouldCircuitBreak(request: Request) -> Bool {\n        guard let strategy = request.options.circuitBreakerStrategy else {\n            return false\n        }\n\n        switch strategy {\n        case .hostErrors(let maxErrors, let age):\n            if let host = request.url.host, let errors = (Self.hostsErrorsLock.withLock { Self.hostsErrors[host] }) {\n                if errors.count >= maxErrors, let lastError = errors.last, let age = age.timeInterval() {\n                    return Date().timeIntervalSince(lastError) <= age\n                } else if errors.count >= maxErrors {\n                    // reset aged errors\n                    Self.hostsErrorsLock.withLock {\n                        Self.hostsErrors[host] = nil\n                    }\n                }\n            }\n            return false\n        }\n    }\n}\n\nextension LegacyHTTPClient {\n    public func head(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init(),\n        observabilityScope: ObservabilityScope? = .none\n    ) async throws -> Response {\n        try await withCheckedThrowingContinuation { continuation in\n            self.head(url, headers: headers, options: options, completion: { continuation.resume(with: $0) })\n        }\n    }\n    @available(*, noasync, message: \"Use the async alternative\")\n    public func head(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init(),\n        observabilityScope: ObservabilityScope? = .none,\n        completion: @Sendable @escaping (Result<Response, Error>) -> Void\n    ) {\n        self.execute(\n            Request(method: .head, url: url, headers: headers, body: nil, options: options),\n            observabilityScope: observabilityScope,\n            completion: completion\n        )\n    }\n\n    public func get(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init(),\n        observabilityScope: ObservabilityScope? = .none\n    ) async throws -> Response {\n        try await withCheckedThrowingContinuation { continuation in\n            self.get(url, headers: headers, options: options, completion: { continuation.resume(with: $0) })\n        }\n    }\n    @available(*, noasync, message: \"Use the async alternative\")\n    public func get(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init(),\n        observabilityScope: ObservabilityScope? = .none,\n        completion: @Sendable @escaping (Result<Response, Error>) -> Void\n    ) {\n        self.execute(\n            Request(method: .get, url: url, headers: headers, body: nil, options: options),\n            observabilityScope: observabilityScope,\n            completion: completion\n        )\n    }\n\n    public func put(\n        _ url: URL,\n        body: Data?,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init(),\n        observabilityScope: ObservabilityScope? = .none,\n        completion: @Sendable @escaping (Result<Response, Error>) -> Void\n    ) {\n        self.execute(\n            Request(method: .put, url: url, headers: headers, body: body, options: options),\n            observabilityScope: observabilityScope,\n            completion: completion\n        )\n    }\n\n    public func post(\n        _ url: URL,\n        body: Data?,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init(),\n        observabilityScope: ObservabilityScope? = .none,\n        completion: @Sendable @escaping (Result<Response, Error>) -> Void\n    ) {\n        self.execute(\n            Request(method: .post, url: url, headers: headers, body: body, options: options),\n            observabilityScope: observabilityScope,\n            completion: completion\n        )\n    }\n\n    public func delete(\n        _ url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Request.Options = .init(),\n        observabilityScope: ObservabilityScope? = .none,\n        completion: @Sendable @escaping (Result<Response, Error>) -> Void\n    ) {\n        self.execute(\n            Request(method: .delete, url: url, headers: headers, body: nil, options: options),\n            observabilityScope: observabilityScope,\n            completion: completion\n        )\n    }\n}\n\n// MARK: - LegacyHTTPClientConfiguration\n\npublic struct LegacyHTTPClientConfiguration {\n    public typealias AuthorizationProvider = @Sendable (URL) -> String?\n\n    public var requestHeaders: HTTPClientHeaders?\n    public var requestTimeout: DispatchTimeInterval?\n    public var authorizationProvider: AuthorizationProvider?\n    public var retryStrategy: HTTPClientRetryStrategy?\n    public var circuitBreakerStrategy: HTTPClientCircuitBreakerStrategy?\n    public var maxConcurrentRequests: Int?\n    public var callbackQueue: DispatchQueue\n\n    public init() {\n        self.requestHeaders = .none\n        self.requestTimeout = .none\n        self.authorizationProvider = .none\n        self.retryStrategy = .none\n        self.circuitBreakerStrategy = .none\n        self.maxConcurrentRequests = .none\n        self.callbackQueue = .sharedConcurrent\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/LegacyHTTPClientRequest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct LegacyHTTPClientRequest: Sendable {\n    public let kind: Kind\n    public let url: URL\n    public var headers: HTTPClientHeaders\n    public var body: Data?\n    public var options: Options\n\n    public init(\n        kind: Kind,\n        url: URL,\n        headers: HTTPClientHeaders = .init(),\n        body: Data? = nil,\n        options: Options = .init()\n    ) {\n        self.kind = kind\n        self.url = url\n        self.headers = headers\n        self.body = body\n        self.options = options\n    }\n\n    // generic request\n    public init(\n        method: HTTPMethod = .get,\n        url: URL,\n        headers: HTTPClientHeaders = .init(),\n        body: Data? = nil,\n        options: Options = .init()\n    ) {\n        self.init(kind: .generic(method), url: url, headers: headers, body: body, options: options)\n    }\n\n    // download request\n    public static func download(\n        url: URL,\n        headers: HTTPClientHeaders = .init(),\n        options: Options = .init(),\n        fileSystem: FileSystem,\n        destination: AbsolutePath\n    ) -> Self {\n        self.init(\n            kind: .download(fileSystem: fileSystem, destination: destination),\n            url: url,\n            headers: headers,\n            body: nil,\n            options: options\n        )\n    }\n\n    public var method: HTTPMethod {\n        switch self.kind {\n        case .generic(let method):\n            return method\n        case .download:\n            return .get\n        }\n    }\n\n    public typealias FileMoveCompletion = @Sendable (Error?)\n        -> Void\n\n    public enum Kind: Sendable {\n        case generic(HTTPMethod)\n        case download(fileSystem: FileSystem, destination: AbsolutePath)\n    }\n\n    public struct Options: Sendable {\n        public init(\n            addUserAgent: Bool = true,\n            validResponseCodes: [Int]? = nil,\n            timeout: DispatchTimeInterval? = nil,\n            maximumResponseSizeInBytes: Int64? = nil,\n            authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider? = nil,\n            retryStrategy: HTTPClientRetryStrategy? = nil,\n            circuitBreakerStrategy: HTTPClientCircuitBreakerStrategy? = nil,\n            callbackQueue: DispatchQueue? = nil\n        ) {\n            self.addUserAgent = addUserAgent\n            self.validResponseCodes = validResponseCodes\n            self.timeout = timeout\n            self.maximumResponseSizeInBytes = maximumResponseSizeInBytes\n            self.authorizationProvider = authorizationProvider\n            self.retryStrategy = retryStrategy\n            self.circuitBreakerStrategy = circuitBreakerStrategy\n            self.callbackQueue = callbackQueue\n        }\n\n        public var addUserAgent: Bool\n        public var validResponseCodes: [Int]?\n        public var timeout: DispatchTimeInterval?\n        public var maximumResponseSizeInBytes: Int64?\n        public var authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?\n        public var retryStrategy: HTTPClientRetryStrategy?\n        public var circuitBreakerStrategy: HTTPClientCircuitBreakerStrategy?\n        public var callbackQueue: DispatchQueue?\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/HTTPClient/URLSessionHTTPClient.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Foundation\nimport struct TSCUtility.Versioning\n#if canImport(FoundationNetworking)\n// FIXME: this brings OpenSSL dependency on Linux and needs to be replaced with `swift-server/async-http-client` package\nimport FoundationNetworking\n#endif\n\nfinal class URLSessionHTTPClient: Sendable {\n    private let dataSession: URLSession\n    private let downloadSession: URLSession\n    private let dataTaskManager: DataTaskManager\n    private let downloadTaskManager: DownloadTaskManager\n\n    init(configuration: URLSessionConfiguration = .default) {\n        let dataDelegateQueue = OperationQueue()\n        dataDelegateQueue.name = \"org.swift.swiftpm.urlsession-http-client-data-delegate\"\n        dataDelegateQueue.maxConcurrentOperationCount = 1\n        self.dataTaskManager = DataTaskManager()\n        self.dataSession = URLSession(\n            configuration: configuration,\n            delegate: self.dataTaskManager,\n            delegateQueue: dataDelegateQueue\n        )\n\n        let downloadDelegateQueue = OperationQueue()\n        downloadDelegateQueue.name = \"org.swift.swiftpm.urlsession-http-client-download-delegate\"\n        downloadDelegateQueue.maxConcurrentOperationCount = 1\n        self.downloadTaskManager = DownloadTaskManager()\n        self.downloadSession = URLSession(\n            configuration: configuration,\n            delegate: self.downloadTaskManager,\n            delegateQueue: downloadDelegateQueue\n        )\n    }\n\n    deinit {\n        dataSession.finishTasksAndInvalidate()\n        downloadSession.finishTasksAndInvalidate()\n    }\n\n    @Sendable\n    func execute(\n        _ request: HTTPClient.Request,\n        progress: HTTPClient.ProgressHandler? = nil\n    ) async throws -> LegacyHTTPClient.Response {\n        try await withCheckedThrowingContinuation { continuation in\n            let urlRequest = URLRequest(request)\n            let task: URLSessionTask\n            switch request.kind {\n            case .generic:\n                let dataTask = self.dataSession.dataTask(with: urlRequest)\n                self.dataTaskManager.register(\n                    task: dataTask,\n                    urlRequest: urlRequest,\n                    authorizationProvider: request.options.authorizationProvider,\n                    progress: progress,\n                    completion: { continuation.resume(with: $0) }\n                )\n                task = dataTask\n            case .download(_, let destination):\n                let downloadTask = self.downloadSession.downloadTask(with: urlRequest)\n                self.downloadTaskManager.register(\n                    task: downloadTask,\n                    urlRequest: urlRequest,\n                    authorizationProvider: request.options.authorizationProvider,\n                    // FIXME: always using synchronous filesystem, because `URLSessionDownloadDelegate`\n                    // needs temporary files to moved out of temporary locations synchronously in delegate callbacks.\n                    fileSystem: localFileSystem,\n                    destination: destination,\n                    progress: progress,\n                    completion: { continuation.resume(with: $0) }\n                )\n                task = downloadTask\n            }\n            task.resume()\n        }\n    }\n\n    @Sendable\n    public func execute(\n        _ request: LegacyHTTPClient.Request,\n        progress: LegacyHTTPClient.ProgressHandler?,\n        completion: @escaping LegacyHTTPClient.CompletionHandler\n    ) {\n        let urlRequest = URLRequest(request)\n        let task: URLSessionTask\n        switch request.kind {\n        case .generic:\n            let dataTask = self.dataSession.dataTask(with: urlRequest)\n            self.dataTaskManager.register(\n                task: dataTask,\n                urlRequest: urlRequest,\n                authorizationProvider: request.options.authorizationProvider,\n                progress: progress,\n                completion: completion\n            )\n            task = dataTask\n        case .download(let fileSystem, let destination):\n            let downloadTask = self.downloadSession.downloadTask(with: urlRequest)\n            self.downloadTaskManager.register(\n                task: downloadTask,\n                urlRequest: urlRequest,\n                authorizationProvider: request.options.authorizationProvider,\n                fileSystem: fileSystem,\n                destination: destination,\n                progress: progress,\n                completion: completion\n            )\n            task = downloadTask\n        }\n        task.resume()\n    }\n}\n\nprivate final class DataTaskManager: NSObject, URLSessionDataDelegate {\n    private let tasks = ThreadSafeKeyValueStore<Int, DataTask>()\n\n    func register(\n        task: URLSessionDataTask,\n        urlRequest: URLRequest,\n        authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?,\n        progress: LegacyHTTPClient.ProgressHandler?,\n        completion: @escaping LegacyHTTPClient.CompletionHandler\n    ) {\n        self.tasks[task.taskIdentifier] = DataTask(\n            task: task,\n            progressHandler: progress,\n            dataTaskManager: self,\n            completionHandler: completion,\n            authorizationProvider: authorizationProvider\n        )\n    }\n\n    public func urlSession(\n        _ session: URLSession,\n        dataTask: URLSessionDataTask,\n        didReceive response: URLResponse,\n        completionHandler: @escaping (URLSession.ResponseDisposition) -> Void\n    ) {\n        guard var task = self.tasks[dataTask.taskIdentifier] else {\n            return completionHandler(.cancel)\n        }\n        task.response = response as? HTTPURLResponse\n        task.expectedContentLength = response.expectedContentLength\n        self.tasks[dataTask.taskIdentifier] = task\n\n        do {\n            try task.progressHandler?(0, response.expectedContentLength)\n            completionHandler(.allow)\n        } catch {\n            completionHandler(.cancel)\n        }\n    }\n\n    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {\n        guard var task = self.tasks[dataTask.taskIdentifier] else {\n            return\n        }\n        if task.buffer != nil {\n            task.buffer?.append(data)\n        } else {\n            task.buffer = data\n        }\n        self.tasks[dataTask.taskIdentifier] = task\n\n        do {\n            // safe since created in the line above\n            try task.progressHandler?(Int64(task.buffer?.count ?? 0), task.expectedContentLength)\n        } catch {\n            task.task.cancel()\n        }\n    }\n\n    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {\n        guard let task = self.tasks.removeValue(forKey: task.taskIdentifier) else {\n            return\n        }\n        if let error {\n            task.completionHandler(.failure(error))\n        } else if let response = task.response {\n            task.completionHandler(.success(response.response(body: task.buffer)))\n        } else {\n            task.completionHandler(.failure(HTTPClientError.invalidResponse))\n        }\n    }\n\n    public func urlSession(\n        _ session: URLSession,\n        task: URLSessionTask,\n        willPerformHTTPRedirection response: HTTPURLResponse,\n        newRequest request: URLRequest,\n        completionHandler: @escaping (URLRequest?) -> Void\n    ) {\n        // Don't remove task from dictionary because we want to resume it later\n        guard let task = self.tasks[task.taskIdentifier] else {\n            return\n        }\n\n        var request = request\n        // Set `Authorization` header for the redirected request\n        if let redirectURL = request.url, let authorization = task.authorizationProvider?(redirectURL),\n           request.value(forHTTPHeaderField: \"Authorization\") == nil\n        {\n            request.addValue(authorization, forHTTPHeaderField: \"Authorization\")\n        }\n\n        completionHandler(request)\n    }\n\n    struct DataTask: Sendable {\n        let task: URLSessionDataTask\n        let completionHandler: LegacyHTTPClient.CompletionHandler\n        /// A strong reference to keep the `DataTaskManager` alive so it can handle the callbacks from the\n        /// `URLSession`.\n        ///\n        /// See comment on `WeakDataTaskManager`.\n        let dataTaskManager: DataTaskManager\n        let progressHandler: LegacyHTTPClient.ProgressHandler?\n        let authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?\n\n        var response: HTTPURLResponse?\n        var expectedContentLength: Int64?\n        var buffer: Data?\n\n        init(\n            task: URLSessionDataTask,\n            progressHandler: LegacyHTTPClient.ProgressHandler?,\n            dataTaskManager: DataTaskManager,\n            completionHandler: @escaping LegacyHTTPClient.CompletionHandler,\n            authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?\n        ) {\n            self.task = task\n            self.progressHandler = progressHandler\n            self.dataTaskManager = dataTaskManager\n            self.completionHandler = completionHandler\n            self.authorizationProvider = authorizationProvider\n        }\n    }\n}\n\nprivate final class DownloadTaskManager: NSObject, URLSessionDownloadDelegate {\n    private let tasks = ThreadSafeKeyValueStore<Int, DownloadTask>()\n\n    func register(\n        task: URLSessionDownloadTask,\n        urlRequest: URLRequest,\n        authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?,\n        fileSystem: FileSystem,\n        destination: AbsolutePath,\n        progress: LegacyHTTPClient.ProgressHandler?,\n        completion: @escaping LegacyHTTPClient.CompletionHandler\n    ) {\n        self.tasks[task.taskIdentifier] = DownloadTask(\n            task: task,\n            fileSystem: fileSystem,\n            destination: destination,\n            downloadTaskManager: self,\n            progressHandler: progress,\n            completionHandler: completion,\n            authorizationProvider: authorizationProvider\n        )\n    }\n\n    func urlSession(\n        _ session: URLSession,\n        downloadTask: URLSessionDownloadTask,\n        didWriteData bytesWritten: Int64,\n        totalBytesWritten: Int64,\n        totalBytesExpectedToWrite: Int64\n    ) {\n        guard let task = self.tasks[downloadTask.taskIdentifier] else {\n            return\n        }\n\n        let totalBytesToDownload = totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown ?\n            totalBytesExpectedToWrite : nil\n\n        do {\n            try task.progressHandler?(totalBytesWritten, totalBytesToDownload)\n        } catch {\n            task.task.cancel()\n        }\n    }\n\n    func urlSession(\n        _ session: URLSession,\n        downloadTask: URLSessionDownloadTask,\n        didFinishDownloadingTo location: URL\n    ) {\n        guard var task = self.tasks[downloadTask.taskIdentifier] else {\n            return\n        }\n\n        do {\n            let path = try AbsolutePath(validating: location.path)\n\n            // Only proceed to move the file if status code is within 200-299 range.\n            if let response = downloadTask.response as? HTTPURLResponse,\n               response.statusCode < 200 || response.statusCode >= 300 {\n                throw HTTPClientError.badResponseStatusCode(response.statusCode)\n            }\n\n            // Always using synchronous `localFileSystem` here since `URLSession` requires temporary `location`\n            // to be moved from synchronously. Otherwise the file will be immediately cleaned up after returning\n            // from this delegate method.\n            try task.fileSystem.move(from: path, to: task.destination)\n        } catch {\n            task.moveFileError = error\n            self.tasks[downloadTask.taskIdentifier] = task\n        }\n    }\n\n    public func urlSession(\n        _ session: URLSession,\n        task downloadTask: URLSessionTask,\n        didCompleteWithError error: Error?\n    ) {\n        guard let task = self.tasks.removeValue(forKey: downloadTask.taskIdentifier) else {\n            return\n        }\n\n        do {\n            if let error {\n                throw HTTPClientError.downloadError(error.interpolationDescription)\n            } else if let error = task.moveFileError {\n                throw error\n            } else if let response = downloadTask.response as? HTTPURLResponse {\n                task.completionHandler(.success(response.response(body: nil)))\n            } else {\n                throw HTTPClientError.invalidResponse\n            }\n        } catch {\n            task.completionHandler(.failure(error))\n        }\n    }\n\n    public func urlSession(\n        _ session: URLSession,\n        task: URLSessionTask,\n        willPerformHTTPRedirection response: HTTPURLResponse,\n        newRequest request: URLRequest,\n        completionHandler: @escaping (URLRequest?) -> Void\n    ) {\n        guard let task = self.tasks[task.taskIdentifier] else {\n            return\n        }\n\n        // Add new authorization header for a redirect if there is one, otherwise remove\n        var redirectRequest = request\n        if let redirectURL = request.url, let authorization = task.authorizationProvider?(redirectURL) {\n            redirectRequest.setValue(authorization, forHTTPHeaderField: \"Authorization\")\n        } else {\n            redirectRequest.setValue(nil, forHTTPHeaderField: \"Authorization\")\n        }\n\n        completionHandler(redirectRequest)\n    }\n\n    struct DownloadTask: Sendable {\n        let task: URLSessionDownloadTask\n        let fileSystem: FileSystem\n        let destination: AbsolutePath\n        let progressHandler: LegacyHTTPClient.ProgressHandler?\n        let completionHandler: LegacyHTTPClient.CompletionHandler\n        let authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?\n\n        var moveFileError: Error?\n\n        init(\n            task: URLSessionDownloadTask,\n            fileSystem: FileSystem,\n            destination: AbsolutePath,\n            downloadTaskManager: DownloadTaskManager,\n            progressHandler: LegacyHTTPClient.ProgressHandler?,\n            completionHandler: @escaping LegacyHTTPClient.CompletionHandler,\n            authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?\n        ) {\n            self.task = task\n            self.fileSystem = fileSystem\n            self.destination = destination\n            self.progressHandler = progressHandler\n            self.completionHandler = completionHandler\n            self.authorizationProvider = authorizationProvider\n        }\n    }\n}\n\nextension URLRequest {\n    init(_ request: LegacyHTTPClient.Request) {\n        self.init(url: request.url)\n        self.httpMethod = request.method.string\n        request.headers.forEach { header in\n            self.addValue(header.value, forHTTPHeaderField: header.name)\n        }\n        self.httpBody = request.body\n        if let interval = request.options.timeout?.timeInterval() {\n            self.timeoutInterval = interval\n        }\n    }\n\n    init(_ request: HTTPClient.Request) {\n        self.init(url: request.url)\n        self.httpMethod = request.method.string\n        request.headers.forEach { header in\n            self.addValue(header.value, forHTTPHeaderField: header.name)\n        }\n        self.httpBody = request.body\n        if let interval = request.options.timeout?.timeInterval() {\n            self.timeoutInterval = interval\n        }\n    }\n}\n\nextension HTTPURLResponse {\n    fileprivate func response(body: Data?) -> HTTPClientResponse {\n        let headers = HTTPClientHeaders(self.allHeaderFields.map { header in\n            .init(name: \"\\(header.key)\", value: \"\\(header.value)\")\n        })\n        return HTTPClientResponse(\n            statusCode: self.statusCode,\n            statusText: Self.localizedString(forStatusCode: self.statusCode),\n            headers: headers,\n            body: body\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/ImportScanning.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Dispatch\n\nimport class Foundation.JSONDecoder\n\nprivate let defaultImports = [\"Swift\", \"SwiftOnoneSupport\", \"_Concurrency\",\n                              \"_StringProcessing\", \"_SwiftConcurrencyShims\"]\n\nprivate struct Imports: Decodable {\n    let imports: [String]\n}\n\npackage protocol ImportScanner {\n    func scanImports(_ filePathToScan: AbsolutePath) async throws -> [String]\n}\n\npublic struct SwiftcImportScanner: ImportScanner {\n    private let swiftCompilerEnvironment: Environment\n    private let swiftCompilerFlags: [String]\n    private let swiftCompilerPath: AbsolutePath\n\n    package init(\n        swiftCompilerEnvironment: Environment,\n        swiftCompilerFlags: [String],\n        swiftCompilerPath: AbsolutePath\n    ) {\n        self.swiftCompilerEnvironment = swiftCompilerEnvironment\n        self.swiftCompilerFlags = swiftCompilerFlags\n        self.swiftCompilerPath = swiftCompilerPath\n    }\n\n    public func scanImports(_ filePathToScan: AbsolutePath) async throws -> [String] {\n        let cmd = [swiftCompilerPath.pathString,\n                   filePathToScan.pathString,\n                   \"-scan-dependencies\", \"-Xfrontend\", \"-import-prescan\"] + self.swiftCompilerFlags\n\n        let result = try await AsyncProcess.popen(arguments: cmd, environment: self.swiftCompilerEnvironment)\n\n        let stdout = try result.utf8Output()\n        return try JSONDecoder.makeWithDefaults().decode(Imports.self, from: stdout).imports\n            .filter { !defaultImports.contains($0) }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/JSON+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.Data\nimport class Foundation.DateFormatter\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\nextension JSONDecoder {\n    public static func makeWithDefaults(dateDecodingStrategy: DateDecodingStrategy = .iso8601) -> JSONDecoder {\n        let decoder = JSONDecoder()\n        decoder.dateDecodingStrategy = dateDecodingStrategy\n        return decoder\n    }\n}\n\nextension JSONEncoder {\n    public static func makeWithDefaults(\n        prettified: Bool = true,\n        dateEncodingStrategy: DateEncodingStrategy = .iso8601\n    ) -> JSONEncoder {\n        Self.makeWithDefaults(\n            sortKeys: prettified,\n            prettyPrint: prettified,\n            escapeSlashes: !prettified,\n            dateEncodingStrategy: dateEncodingStrategy\n        )\n    }\n\n    public static func makeWithDefaults(\n        sortKeys: Bool,\n        prettyPrint: Bool,\n        escapeSlashes: Bool,\n        dateEncodingStrategy: DateEncodingStrategy = .iso8601\n    ) -> JSONEncoder {\n        let encoder = JSONEncoder()\n        var outputFormatting: JSONEncoder.OutputFormatting = []\n\n        if sortKeys {\n            outputFormatting.insert(.sortedKeys)\n        }\n        if prettyPrint {\n            outputFormatting.insert(.prettyPrinted)\n        }\n        if !escapeSlashes {\n            outputFormatting.insert(.withoutEscapingSlashes)\n        }\n\n        encoder.outputFormatting = outputFormatting\n        encoder.dateEncodingStrategy = dateEncodingStrategy\n        return encoder\n    }\n}\n\nextension JSONDecoder {\n    public func decode<T: Decodable>(path: AbsolutePath, fileSystem: FileSystem, as kind: T.Type) throws -> T {\n        let data: Data = try fileSystem.readFileContents(path)\n        return try self.decode(kind, from: data)\n    }\n}\n\nextension JSONEncoder {\n    public func encode<T: Encodable>(path: AbsolutePath, fileSystem: FileSystem, _ value: T) throws {\n        let data = try self.encode(value)\n        try fileSystem.writeFileContents(path, data: data)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/JSONDecoder+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension JSONDecoder {\n    public func decode<T>(_ type: T.Type, from string: String) throws -> T where T: Decodable {\n        let data = Data(string.utf8)\n        return try self.decode(type, from: data)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Netrc.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Representation of Netrc configuration\npublic struct Netrc: Sendable {\n    /// Representation of `machine` connection settings & `default` connection settings.\n    /// If `default` connection settings present, they will be last element.\n    public let machines: [Machine]\n\n    fileprivate init(machines: [Machine]) {\n        self.machines = machines\n    }\n\n    /// Returns auth information\n    ///\n    /// - Parameters:\n    ///   - url: The url to retrieve authorization information for.\n    public func authorization(for url: URL) -> Authorization? {\n        guard let index = machines.firstIndex(where: { $0.name == url.host }) ?? machines\n            .firstIndex(where: { $0.isDefault })\n        else {\n            return .none\n        }\n        let machine = self.machines[index]\n        return Authorization(login: machine.login, password: machine.password)\n    }\n\n    /// Representation of connection settings\n    public struct Machine: Equatable, Sendable {\n        public let name: String\n        public let login: String\n        public let password: String\n\n        public var isDefault: Bool {\n            self.name == \"default\"\n        }\n\n        public init(name: String, login: String, password: String) {\n            self.name = name\n            self.login = login\n            self.password = password\n        }\n\n        init?(for match: NSTextCheckingResult, string: String, variant: String = \"\") {\n            guard let name = RegexUtil.Token.machine.capture(in: match, string: string) ?? RegexUtil.Token.default\n                .capture(in: match, string: string),\n                let login = RegexUtil.Token.login.capture(prefix: variant, in: match, string: string),\n                let password = RegexUtil.Token.password.capture(prefix: variant, in: match, string: string)\n            else {\n                return nil\n            }\n            self = Machine(name: name, login: login, password: password)\n        }\n    }\n\n    /// Representation of authorization information\n    public struct Authorization: Equatable {\n        public let login: String\n        public let password: String\n\n        public init(login: String, password: String) {\n            self.login = login\n            self.password = password\n        }\n    }\n}\n\npublic struct NetrcParser {\n    /// Parses a netrc file at the give location\n    ///\n    /// - Parameters:\n    ///   - fileSystem: The file system to use.\n    ///   - path: The file to parse\n    public static func parse(fileSystem: FileSystem, path: AbsolutePath) throws -> Netrc {\n        guard fileSystem.exists(path) else {\n            throw NetrcError.fileNotFound(path)\n        }\n        guard fileSystem.isReadable(path) else {\n            throw NetrcError.unreadableFile(path)\n        }\n        let content: String = try fileSystem.readFileContents(path)\n        return try Self.parse(content)\n    }\n\n    /// Parses stringified netrc content\n    ///\n    /// - Parameters:\n    ///   - content: The content to parse\n    public static func parse(_ content: String) throws -> Netrc {\n        let content = self.trimComments(from: content)\n        let regex = try! NSRegularExpression(pattern: RegexUtil.netrcPattern, options: [])\n        let matches = regex.matches(\n            in: content,\n            options: [],\n            range: NSRange(content.startIndex ..< content.endIndex, in: content)\n        )\n\n        let machines: [Netrc.Machine] = matches.compactMap {\n            Netrc.Machine(for: $0, string: content, variant: \"lp\") ?? Netrc\n                .Machine(for: $0, string: content, variant: \"pl\")\n        }\n\n        if let defIndex = machines.firstIndex(where: { $0.isDefault }) {\n            guard defIndex == machines.index(before: machines.endIndex) else {\n                throw NetrcError.invalidDefaultMachinePosition\n            }\n        }\n        guard machines.count > 0 else {\n            throw NetrcError.machineNotFound\n        }\n        return Netrc(machines: machines)\n    }\n\n    /// Utility method to trim comments from netrc content\n    /// - Parameter text: String text of netrc file\n    /// - Returns: String text of netrc file *sans* comments\n    private static func trimComments(from text: String) -> String {\n        let regex = try! NSRegularExpression(pattern: RegexUtil.comments, options: .anchorsMatchLines)\n        let nsString = text as NSString\n        let range = NSRange(location: 0, length: nsString.length)\n        let matches = regex.matches(in: text, range: range)\n        var trimmedCommentsText = text\n        matches.forEach {\n            let matchedString = nsString.substring(with: $0.range)\n            if !matchedString.starts(with: \"\\\"\") {\n                trimmedCommentsText = trimmedCommentsText\n                    .replacing(matchedString, with: \"\")\n            }\n        }\n        return trimmedCommentsText\n    }\n}\n\npublic enum NetrcError: Error, Equatable {\n    case fileNotFound(AbsolutePath)\n    case unreadableFile(AbsolutePath)\n    case machineNotFound\n    case invalidDefaultMachinePosition\n}\n\nprivate enum RegexUtil {\n    fileprivate enum Token: String, CaseIterable {\n        case machine, login, password, account, macdef, `default`\n\n        func capture(prefix: String = \"\", in match: NSTextCheckingResult, string: String) -> String? {\n            if let quotedRange = Range(match.range(withName: prefix + rawValue + quotedIdentifier), in: string) {\n                return String(string[quotedRange])\n            } else if let range = Range(match.range(withName: prefix + rawValue), in: string) {\n                return String(string[range])\n            } else {\n                return nil\n            }\n        }\n    }\n\n    private static let quotedIdentifier = \"quoted\"\n    static let comments: String = \"(\\\"[^\\\"]*\\\"|\\\\s#.*$)\"\n    static let `default`: String = #\"(?:\\s*(?<default>default))\"#\n    static let accountOptional: String = #\"(?:\\s*account\\s+\\S++)?\"#\n    static let loginPassword: String =\n        #\"\\#(namedTrailingCapture(\"login\", prefix: \"lp\"))\\#(accountOptional)\\#(namedTrailingCapture(\"password\", prefix: \"lp\"))\"#\n    static let passwordLogin: String =\n        #\"\\#(namedTrailingCapture(\"password\", prefix: \"pl\"))\\#(accountOptional)\\#(namedTrailingCapture(\"login\", prefix: \"pl\"))\"#\n    static let netrcPattern =\n        #\"(?:(?:(\\#(namedTrailingCapture(\"machine\"))|\\#(namedMatch(\"default\"))))(?:\\#(loginPassword)|\\#(passwordLogin)))\"#\n\n    static func namedMatch(_ string: String) -> String {\n        #\"(?:\\s*(?<\\#(string)>\\#(string)))\"#\n    }\n\n    static func namedTrailingCapture(_ string: String, prefix: String = \"\") -> String {\n        #\"\\s*\\#(string)\\s+(?:\"(?<\\#(prefix + string + quotedIdentifier)>[^\"]*)\"|(?<\\#(prefix + string)>\\S+))\"#\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/OSSignpost.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if canImport(os)\nimport os\n\nextension os.OSLog {\n    @usableFromInline\n    static let swiftpm = os.OSLog(subsystem: \"org.swift.swiftpm\", category: \"default\")\n}\n#endif\n\n/// Emits a signpost.\n@inlinable package func os_signpost(\n    _ type: SignpostType,\n    name: StaticString,\n    signpostID: SignpostID = .exclusive\n) {\n    #if canImport(os) && DEBUG\n    if #available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *) {\n        os.os_signpost(\n            type.underlying,\n            log: .swiftpm,\n            name: name,\n            signpostID: signpostID.underlying\n        )\n    }\n    #endif\n}\n\n@usableFromInline\npackage enum SignpostType {\n    case begin\n    case end\n    case event\n\n    #if canImport(os)\n    @available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *)\n    @usableFromInline\n    var underlying: os.OSSignpostType {\n        switch self {\n        case .begin:\n            return os.OSSignpostType.begin\n        case .end:\n            return os.OSSignpostType.end\n        case .event:\n            return os.OSSignpostType.event\n        }\n    }\n    #endif\n}\n\n@usableFromInline\npackage enum SignpostID {\n    case exclusive\n\n    #if canImport(os)\n    @available(macOS 10.14, iOS 12, tvOS 12, watchOS 5, *)\n    @usableFromInline\n    var underlying: os.OSSignpostID {\n        switch self {\n        case .exclusive:\n            return os.OSSignpostID.exclusive\n        }\n    }\n    #endif\n}\n\n\npackage enum SignpostName {\n    public static let updatingDependencies: StaticString = \"updating\"\n    public static let resolvingDependencies: StaticString = \"resolving\"\n    public static let pubgrub: StaticString = \"pubgrub\"\n    public static let loadingGraph: StaticString = \"loading graph\"\n}\n"
  },
  {
    "path": "Sources/Basics/Observability.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Dispatch\nimport Foundation\n\nimport protocol TSCBasic.WritableByteStream\nimport struct TSCBasic.Diagnostic\nimport protocol TSCBasic.DiagnosticData\nimport protocol TSCBasic.DiagnosticLocation\nimport class TSCBasic.TerminalController\nimport class TSCBasic.UnknownLocation\nimport protocol TSCUtility.DiagnosticDataConvertible\nimport enum TSCUtility.Diagnostics\n\n// this could become a struct when we remove the \"errorsReported\" pattern\n\n// designed after https://github.com/apple/swift-log\n// designed after https://github.com/apple/swift-metrics\n// designed after https://github.com/apple/swift-distributed-tracing-baggage\npublic class ObservabilitySystem {\n    public let topScope: ObservabilityScope\n\n    /// Create an ObservabilitySystem with a handler provider providing handler such as a collector.\n    public init(_ handlerProvider: ObservabilityHandlerProvider) {\n        self.topScope = .init(\n            description: \"top scope\",\n            parent: .none,\n            metadata: .none,\n            diagnosticsHandler: handlerProvider.diagnosticsHandler\n        )\n    }\n\n    /// Create an ObservabilitySystem with a single diagnostics handler.\n    public convenience init(\n        _ handler: @escaping @Sendable (ObservabilityScope, Diagnostic) -> Void,\n        outputStream: (any WritableByteStream)? = nil,\n        logLevel: Diagnostic.Severity = .error,\n    ) {\n        self.init(\n            SingleDiagnosticsHandler(\n                handler,\n                outputStream: outputStream,\n                logLevel: logLevel\n            )\n        )\n    }\n\n    private struct SingleDiagnosticsHandler: ObservabilityHandlerProvider, DiagnosticsHandler {\n        var diagnosticsHandler: DiagnosticsHandler { self }\n\n        let underlying: @Sendable (ObservabilityScope, Diagnostic) -> Void\n        let outputStream: (any WritableByteStream)?\n        let logLevel: Diagnostic.Severity\n\n        init(\n            _ underlying: @escaping @Sendable (ObservabilityScope, Diagnostic) -> Void,\n            outputStream: (any WritableByteStream)?,\n            logLevel: Diagnostic.Severity = .error\n        ) {\n            self.underlying = underlying\n            self.outputStream = outputStream\n            self.logLevel = logLevel\n        }\n\n        func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic) {\n            self.underlying(scope, diagnostic)\n        }\n\n        func print(_ output: String, condition: OutputCondition) {\n            switch condition {\n            case .always:\n                outputStream?.write(output)\n            case .onlyWhenVerbose:\n                guard self.logLevel.isVerbose else { return }\n                outputStream?.write(output)\n            }\n        }\n    }\n\n    public static var NOOP: ObservabilityScope {\n        ObservabilitySystem({ _, _ in }, outputStream: nil, logLevel: .debug).topScope\n    }\n}\n\npublic protocol ObservabilityHandlerProvider {\n    var diagnosticsHandler: DiagnosticsHandler { get }\n}\n\n// MARK: - ObservabilityScope\n\npublic final class ObservabilityScope: DiagnosticsEmitterProtocol, Sendable, CustomStringConvertible {\n    public let description: String\n    private let parent: ObservabilityScope?\n    private let metadata: ObservabilityMetadata?\n\n    private let diagnosticsHandler: DiagnosticsHandlerWrapper\n\n    fileprivate init(\n        description: String,\n        parent: ObservabilityScope?,\n        metadata: ObservabilityMetadata?,\n        diagnosticsHandler: DiagnosticsHandler\n    ) {\n        self.description = description\n        self.parent = parent\n        self.metadata = metadata\n        self.diagnosticsHandler = DiagnosticsHandlerWrapper(diagnosticsHandler)\n    }\n\n    public func makeChildScope(description: String, metadata: ObservabilityMetadata? = .none) -> Self {\n        let mergedMetadata = ObservabilityMetadata.mergeLeft(self.metadata, metadata)\n        return .init(\n            description: description,\n            parent: self,\n            metadata: mergedMetadata,\n            diagnosticsHandler: self.diagnosticsHandler\n        )\n    }\n\n    public func makeChildScope(description: String, metadataProvider: () -> ObservabilityMetadata) -> Self {\n        self.makeChildScope(description: description, metadata: metadataProvider())\n    }\n\n    // diagnostics\n\n    public func makeDiagnosticsEmitter(metadata: ObservabilityMetadata? = .none) -> DiagnosticsEmitter {\n        let mergedMetadata = ObservabilityMetadata.mergeLeft(self.metadata, metadata)\n        return .init(scope: self, metadata: mergedMetadata)\n    }\n\n    public func makeDiagnosticsEmitter(metadataProvider: () -> ObservabilityMetadata) -> DiagnosticsEmitter {\n        self.makeDiagnosticsEmitter(metadata: metadataProvider())\n    }\n\n    // FIXME: we want to remove this functionality and move to more conventional error handling\n    // @available(*, deprecated, message: \"this pattern is deprecated, transition to error handling instead\")\n    public var errorsReported: Bool {\n        self.diagnosticsHandler.errorsReported\n    }\n\n    // FIXME: we want to remove this functionality and move to more conventional error handling\n    // @available(*, deprecated, message: \"this pattern is deprecated, transition to error handling instead\")\n    public var errorsReportedInAnyScope: Bool {\n        if self.errorsReported {\n            return true\n        }\n        return parent?.errorsReportedInAnyScope ?? false\n    }\n\n    public func print(_ output: String, condition: OutputCondition) {\n        self.diagnosticsHandler.print(output, condition: condition)\n    }\n\n    // DiagnosticsEmitterProtocol\n    public func emit(_ diagnostic: Diagnostic) {\n        var diagnostic = diagnostic\n        diagnostic.metadata = ObservabilityMetadata.mergeLeft(self.metadata, diagnostic.metadata)\n        self.diagnosticsHandler.handleDiagnostic(scope: self, diagnostic: diagnostic)\n    }\n\n    private struct DiagnosticsHandlerWrapper: DiagnosticsHandler {\n        private let underlying: DiagnosticsHandler\n        private var _errorsReported = ThreadSafeBox<Bool>(false)\n\n        init(_ underlying: DiagnosticsHandler) {\n            self.underlying = underlying\n        }\n\n        public func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic) {\n            if diagnostic.severity == .error {\n                self._errorsReported.put(true)\n            }\n            self.underlying.handleDiagnostic(scope: scope, diagnostic: diagnostic)\n        }\n\n        public func print(_ output: String, condition: OutputCondition) {\n            self.underlying.print(output, condition: condition)\n        }\n\n        var errorsReported: Bool {\n            self._errorsReported.get()\n        }\n    }\n}\n\n// MARK: - OutputCondition\n\n/// Enum describing the condition in which some textual output should be emitted.\npublic enum OutputCondition {\n    case onlyWhenVerbose\n    case always\n}\n\n// MARK: - Diagnostics\n\npublic protocol DiagnosticsHandler: Sendable {\n    func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic)\n\n    func print(_ output: String, condition: OutputCondition)\n}\n\n/// Helper protocol to share default behavior.\npublic protocol DiagnosticsEmitterProtocol {\n    func emit(_ diagnostic: Diagnostic)\n}\n\nextension DiagnosticsEmitterProtocol {\n    public func emit(_ diagnostics: [Diagnostic]) {\n        for diagnostic in diagnostics {\n            self.emit(diagnostic)\n        }\n    }\n\n    public func emit(severity: Diagnostic.Severity, message: String, metadata: ObservabilityMetadata? = .none) {\n        self.emit(.init(severity: severity, message: message, metadata: metadata))\n    }\n\n    public func emit(error message: String, metadata: ObservabilityMetadata? = .none, underlyingError: Error? = .none) {\n        let message = makeMessage(from: message, underlyingError: underlyingError)\n        self.emit(.init(severity: .error, message: message, metadata: metadata))\n    }\n\n    public func emit(\n        error message: CustomStringConvertible,\n        metadata: ObservabilityMetadata? = .none,\n        underlyingError: Error? = .none\n    ) {\n        self.emit(error: message.description, metadata: metadata, underlyingError: underlyingError)\n    }\n\n    public func emit(_ error: Error, metadata: ObservabilityMetadata? = .none) {\n        self.emit(.error(error, metadata: metadata))\n    }\n\n    public func emit(\n        warning message: String,\n        metadata: ObservabilityMetadata? = .none,\n        underlyingError: Error? = .none\n    ) {\n        let message = makeMessage(from: message, underlyingError: underlyingError)\n        self.emit(severity: .warning, message: message, metadata: metadata)\n    }\n\n    public func emit(\n        warning message: CustomStringConvertible,\n        metadata: ObservabilityMetadata? = .none,\n        underlyingError: Error? = .none\n    ) {\n        self.emit(warning: message.description, metadata: metadata, underlyingError: underlyingError)\n    }\n\n    public func emit(info message: String, metadata: ObservabilityMetadata? = .none, underlyingError: Error? = .none) {\n        let message = makeMessage(from: message, underlyingError: underlyingError)\n        self.emit(severity: .info, message: message, metadata: metadata)\n    }\n\n    public func emit(\n        info message: CustomStringConvertible,\n        metadata: ObservabilityMetadata? = .none,\n        underlyingError: Error? = .none\n    ) {\n        self.emit(info: message.description, metadata: metadata, underlyingError: underlyingError)\n    }\n\n    public func emit(debug message: String, metadata: ObservabilityMetadata? = .none, underlyingError: Error? = .none) {\n        let message = makeMessage(from: message, underlyingError: underlyingError)\n        self.emit(severity: .debug, message: message, metadata: metadata)\n    }\n\n    public func emit(\n        debug message: CustomStringConvertible,\n        metadata: ObservabilityMetadata? = .none,\n        underlyingError: Error? = .none\n    ) {\n        self.emit(debug: message.description, metadata: metadata, underlyingError: underlyingError)\n    }\n\n    /// trap a throwing closure, emitting diagnostics on error and returning the value returned by the closure\n    public func trap<T>(_ closure: () throws -> T) -> T? {\n        do {\n            return try closure()\n        } catch Diagnostics.fatalError {\n            // FIXME: (diagnostics) deprecate this with Diagnostics.fatalError\n            return nil\n        } catch {\n            self.emit(error)\n            return nil\n        }\n    }\n\n    public func trap<T>(_ closure: () async throws -> T) async -> T? {\n        do {\n            return try await closure()\n        } catch Diagnostics.fatalError {\n            // FIXME: (diagnostics) deprecate this with Diagnostics.fatalError\n            return nil\n        } catch {\n            self.emit(error)\n            return nil\n        }\n    }\n\n    /// trap a throwing closure, emitting diagnostics on error and returning boolean representing success\n    @discardableResult\n    public func trap(_ closure: () throws -> Void) -> Bool {\n        do {\n            try closure()\n            return true\n        } catch Diagnostics.fatalError {\n            // FIXME: (diagnostics) deprecate this with Diagnostics.fatalError\n            return false\n        } catch {\n            self.emit(error)\n            return false\n        }\n    }\n\n    @discardableResult\n    public func trap(_ closure: () async throws -> Void) async -> Bool {\n        do {\n            try await closure()\n            return true\n        } catch Diagnostics.fatalError {\n            // FIXME: (diagnostics) deprecate this with Diagnostics.fatalError\n            return false\n        } catch {\n            self.emit(error)\n            return false\n        }\n    }\n\n    /// If `underlyingError` is not `nil`, its human-readable description is interpolated with `message`,\n    /// otherwise `message` itself is returned.\n    private func makeMessage(from message: String, underlyingError: Error?) -> String {\n        if let underlyingError {\n            return \"\\(message): \\(underlyingError.interpolationDescription)\"\n        } else {\n            return message\n        }\n    }\n}\n\n// TODO: consider using @autoclosure to delay potentially expensive evaluation of data when some diagnostics may be filtered out\npublic struct DiagnosticsEmitter: DiagnosticsEmitterProtocol {\n    private let scope: ObservabilityScope\n    private let metadata: ObservabilityMetadata?\n\n    fileprivate init(scope: ObservabilityScope, metadata: ObservabilityMetadata?) {\n        self.scope = scope\n        self.metadata = metadata\n    }\n\n    public func emit(_ diagnostic: Diagnostic) {\n        var diagnostic = diagnostic\n        diagnostic.metadata = ObservabilityMetadata.mergeLeft(self.metadata, diagnostic.metadata)\n        self.scope.emit(diagnostic)\n    }\n}\n\npublic struct Diagnostic: Sendable, CustomStringConvertible {\n    public let severity: Severity\n    public let message: String\n    public internal(set) var metadata: ObservabilityMetadata?\n\n    public init(severity: Severity, message: String, metadata: ObservabilityMetadata?) {\n        self.severity = severity\n        self.message = message\n        self.metadata = metadata\n    }\n\n    public var description: String {\n        \"[\\(self.severity)]: \\(self.message)\"\n    }\n\n    public static func error(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {\n        Self(severity: .error, message: message, metadata: metadata)\n    }\n\n    public static func error(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {\n        Self(severity: .error, message: message.description, metadata: metadata)\n    }\n\n    public static func error(_ error: Error, metadata: ObservabilityMetadata? = .none) -> Self {\n        var metadata = metadata ?? ObservabilityMetadata()\n\n        if metadata.underlyingError == nil {\n            metadata.underlyingError = .init(error)\n        }\n\n        let message: String\n        // FIXME: this brings in the TSC API still\n        // FIXME: string interpolation seems brittle\n        if let diagnosticData = error as? DiagnosticData {\n            message = \"\\(diagnosticData)\"\n        } else if let convertible = error as? DiagnosticDataConvertible {\n            message = \"\\(convertible.diagnosticData)\"\n        } else {\n            message = error.interpolationDescription\n        }\n\n        return Self(severity: .error, message: message, metadata: metadata)\n    }\n\n    public static func warning(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {\n        Self(severity: .warning, message: message, metadata: metadata)\n    }\n\n    public static func warning(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {\n        Self(severity: .warning, message: message.description, metadata: metadata)\n    }\n\n    public static func info(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {\n        Self(severity: .info, message: message, metadata: metadata)\n    }\n\n    public static func info(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {\n        Self(severity: .info, message: message.description, metadata: metadata)\n    }\n\n    public static func debug(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {\n        Self(severity: .debug, message: message, metadata: metadata)\n    }\n\n    public static func debug(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {\n        Self(severity: .debug, message: message.description, metadata: metadata)\n    }\n\n    public enum Severity: Comparable, Sendable {\n        case error\n        case warning\n        case info\n        case debug\n\n        var naturalIntegralValue: Int {\n            switch self {\n            case .debug:\n                return 0\n            case .info:\n                return 1\n            case .warning:\n                return 2\n            case .error:\n                return 3\n            }\n        }\n\n        public static func < (lhs: Self, rhs: Self) -> Bool {\n            lhs.naturalIntegralValue < rhs.naturalIntegralValue\n        }\n\n        /// A string that represents the log label associated with the severity level.\n        /// This property provides a descriptive prefix for log messages, indicating the type of message based on its\n        /// severity.\n        public var logLabel: String {\n            switch self {\n            case .debug:\n                return \"debug: \"\n            case .info:\n                return \"info: \"\n            case .warning:\n                return \"warning: \"\n            case .error:\n                return \"error: \"\n            }\n        }\n\n        public var color: TerminalController.Color {\n            switch self {\n            case .debug:\n                return .white\n            case .info:\n                return .white\n            case .error:\n                return .red\n            case .warning:\n                return .yellow\n            }\n        }\n\n        public var isBold: Bool {\n            return true\n        }\n\n        public var isVerbose: Bool {\n            self <= .info\n        }\n\n        public var isQuiet: Bool {\n            self >= .error\n        }\n    }\n}\n\n// MARK: - ObservabilityMetadata\n\n/// Provides type-safe access to the ObservabilityMetadata's values.\n/// This API should ONLY be used inside of accessor implementations.\n///\n/// End users should use \"accessors\" the key's author MUST define rather than using this subscript, following this\n/// pattern:\n///\n///     extension ObservabilityMetadata {\n///       var testID: String? {\n///         get {\n///           self[TestIDKey.self]\n///         }\n///         set {\n///           self[TestIDKey.self] = newValue\n///         }\n///       }\n///     }\n///\n///     enum TestIDKey: ObservabilityMetadataKey {\n///         typealias Value = String\n///     }\n///\n/// This is in order to enforce a consistent style across projects and also allow for fine grained control over\n/// who may set and who may get such property. Just access control to the Key type itself lacks such fidelity.\n///\n/// Note that specific baggage and context types MAY (and usually do), offer also a way to set baggage values,\n/// however in the most general case it is not required, as some frameworks may only be able to offer reading.\n\n// FIXME: we currently require that Value conforms to CustomStringConvertible which sucks\n// ideally Value would conform to Equatable but that has generic requirement\n// luckily, this is about to change so we can clean this up soon\npublic struct ObservabilityMetadata: Sendable, CustomDebugStringConvertible {\n    public typealias Key = ObservabilityMetadataKey\n\n    private var _storage = [AnyKey: Sendable]()\n\n    public init() {}\n\n    public subscript<Key: ObservabilityMetadataKey>(_ key: Key.Type) -> Key.Value? {\n        get {\n            guard let value = self._storage[AnyKey(key)] else { return nil }\n            // safe to force-cast as this subscript is the only way to set a value.\n            return (value as! Key.Value)\n        }\n        set {\n            self._storage[AnyKey(key)] = newValue\n        }\n    }\n\n    /// The number of items in the baggage.\n    public var count: Int {\n        self._storage.count\n    }\n\n    /// A Boolean value that indicates whether the baggage is empty.\n    public var isEmpty: Bool {\n        self._storage.isEmpty\n    }\n\n    /// Iterate through all items in this `ObservabilityMetadata` by invoking the given closure for each item.\n    ///\n    /// The order of those invocations is NOT guaranteed and should not be relied on.\n    ///\n    /// - Parameter body: The closure to be invoked for each item stored in this `ObservabilityMetadata`,\n    /// passing the type-erased key and the associated value.\n    public func forEach(_ body: (AnyKey, Sendable) throws -> Void) rethrows {\n        try self._storage.forEach { key, value in\n            try body(key, value)\n        }\n    }\n\n    public func merging(_ other: ObservabilityMetadata) -> ObservabilityMetadata {\n        var merged = ObservabilityMetadata()\n        self.forEach { key, value in\n            merged._storage[key] = value\n        }\n        other.forEach { key, value in\n            merged._storage[key] = value\n        }\n        return merged\n    }\n\n    public var debugDescription: String {\n        var items = [String]()\n        self._storage.forEach { key, value in\n            items.append(\"\\(key.keyType.self): \\(String(describing: value))\")\n        }\n        return items.joined(separator: \", \")\n    }\n\n    // FIXME: this currently requires that Value conforms to CustomStringConvertible which sucks\n    // ideally Value would conform to Equatable but that has generic requirement\n    // luckily, this is about to change so we can clean this up soon\n    /*\n     public static func == (lhs: ObservabilityMetadata, rhs: ObservabilityMetadata) -> Bool {\n         if lhs.count != rhs.count {\n             return false\n         }\n\n         var equals = true\n         lhs.forEach { (key, value) in\n             if rhs._storage[key]?.description != value.description {\n                 equals = false\n                 return\n             }\n         }\n\n         return equals\n     }*/\n\n    fileprivate static func mergeLeft(\n        _ lhs: ObservabilityMetadata?,\n        _ rhs: ObservabilityMetadata?\n    ) -> ObservabilityMetadata? {\n        switch (lhs, rhs) {\n        case (.none, .none):\n            return .none\n        case (.some(let left), .some(let right)):\n            return left.merging(right)\n        case (.some(let left), .none):\n            return left\n        case (.none, .some(let right)):\n            return right\n        }\n    }\n\n    /// A type-erased `ObservabilityMetadataKey` used when iterating through the `ObservabilityMetadata` using its\n    /// `forEach` method.\n    public struct AnyKey: Sendable {\n        /// The key's type represented erased to an `Any.Type`.\n        public let keyType: Any.Type\n\n        init<Key: ObservabilityMetadataKey>(_ keyType: Key.Type) {\n            self.keyType = keyType\n        }\n    }\n}\n\npublic protocol ObservabilityMetadataKey {\n    /// The type of value uniquely identified by this key.\n    associatedtype Value: Sendable\n}\n\nextension ObservabilityMetadata.AnyKey: Hashable {\n    public static func == (lhs: Self, rhs: Self) -> Bool {\n        ObjectIdentifier(lhs.keyType) == ObjectIdentifier(rhs.keyType)\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self.keyType))\n    }\n}\n\nextension ObservabilityMetadata {\n    public var underlyingError: Error? {\n        get {\n            self[UnderlyingErrorKey.self]\n        }\n        set {\n            self[UnderlyingErrorKey.self] = newValue\n        }\n    }\n\n    private enum UnderlyingErrorKey: Key {\n        typealias Value = Error\n    }\n\n    public struct UnderlyingError: CustomStringConvertible {\n        let underlying: Error\n\n        public init(_ underlying: Error) {\n            self.underlying = underlying\n        }\n\n        public var description: String {\n            String(describing: self.underlying)\n        }\n    }\n}\n\n// MARK: - Compatibility with TSC Diagnostics APIs\n\n@available(*, deprecated, message: \"temporary for transition TSCBasic.Diagnostic -> SwiftDriver.Diagnostic\")\nextension ObservabilityScope {\n    public func makeDiagnosticsHandler() -> (TSCBasic.Diagnostic) -> Void {\n        { Diagnostic($0).map { self.diagnosticsHandler.handleDiagnostic(scope: self, diagnostic: $0) } }\n    }\n}\n\n@available(*, deprecated, message: \"temporary for transition TSCBasic.Diagnostic -> SwiftDriver.Diagnostic\")\nextension Diagnostic {\n    init?(_ diagnostic: TSCBasic.Diagnostic) {\n        var metadata = ObservabilityMetadata()\n        if !(diagnostic.location is UnknownLocation) {\n            metadata.legacyDiagnosticLocation = .init(diagnostic.location)\n        }\n        metadata.legacyDiagnosticData = .init(diagnostic.data)\n\n        switch diagnostic.behavior {\n        case .error:\n            self = .error(diagnostic.message.text, metadata: metadata)\n        case .warning:\n            self = .warning(diagnostic.message.text, metadata: metadata)\n        case .note:\n            self = .info(diagnostic.message.text, metadata: metadata)\n        case .remark:\n            self = .info(diagnostic.message.text, metadata: metadata)\n        case .ignored:\n            return nil\n        }\n    }\n}\n\n@available(*, deprecated, message: \"temporary for transition TSCBasic.Diagnostic -> SwiftDriver.Diagnostic\")\nextension ObservabilityMetadata {\n    public var legacyDiagnosticLocation: DiagnosticLocationWrapper? {\n        get {\n            self[LegacyLocationKey.self]\n        }\n        set {\n            self[LegacyLocationKey.self] = newValue\n        }\n    }\n\n    private enum LegacyLocationKey: Key, Sendable {\n        typealias Value = DiagnosticLocationWrapper\n    }\n\n    public struct DiagnosticLocationWrapper: Sendable, CustomStringConvertible {\n        let underlying: DiagnosticLocation\n\n        public init(_ underlying: DiagnosticLocation) {\n            self.underlying = underlying\n        }\n\n        public var description: String {\n            self.underlying.description\n        }\n    }\n}\n\n@available(*, deprecated, message: \"temporary for transition TSCBasic.Diagnostic -> SwiftDriver.Diagnostic\")\nextension ObservabilityMetadata {\n    var legacyDiagnosticData: DiagnosticDataWrapper? {\n        get {\n            self[LegacyDataKey.self]\n        }\n        set {\n            self[LegacyDataKey.self] = newValue\n        }\n    }\n\n    private enum LegacyDataKey: Key, Sendable {\n        typealias Value = DiagnosticDataWrapper\n    }\n\n    struct DiagnosticDataWrapper: Sendable, CustomStringConvertible {\n        let underlying: DiagnosticData\n\n        public init(_ underlying: DiagnosticData) {\n            self.underlying = underlying\n        }\n\n        public var description: String {\n            self.underlying.description\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Process.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic import Foundation\n\npublic enum OperatingSystem: Hashable, Sendable {\n    case macOS\n    case windows\n    case linux\n    case android\n    case freebsd\n    case openbsd\n    case unknown\n}\n\n\nextension ProcessInfo {\n    public static var hostOperatingSystem: OperatingSystem {\n        #if os(macOS)\n        .macOS\n        #elseif os(Linux)\n        .linux\n        #elseif os(Windows)\n        .windows\n        #elseif os(FreeBSD)\n        .freebsd\n        #elseif os(OpenBSD)\n        .openbsd\n        #elseif os(Android)\n        .android\n        #else\n        .unknown\n        #endif\n    }\n\n    #if os(Windows)\n    public static let EOL = \"\\r\\n\"\n    #else\n    public static let EOL = \"\\n\"\n    #endif\n\n    #if os(Windows)\n    public static let exeSuffix = \".exe\"\n    #else\n    public static let exeSuffix = \"\"\n    #endif\n\n    #if os(Windows)\n    public static let batSuffix = \".bat\"\n    #else\n    public static let batSuffix = \"\"\n    #endif\n}\n"
  },
  {
    "path": "Sources/Basics/ProgressAnimation/NinjaProgressAnimation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class TSCBasic.TerminalController\nimport protocol TSCBasic.WritableByteStream\n\nextension ProgressAnimation {\n    /// A ninja-like progress animation that adapts to the provided output stream.\n    @_spi(SwiftPMInternal)\n    public static func ninja(\n        stream: WritableByteStream,\n        verbose: Bool,\n        normalizeStep: Bool = true\n    ) -> any ProgressAnimationProtocol {\n        Self.dynamic(\n            stream: stream,\n            verbose: verbose,\n            ttyTerminalAnimationFactory: { RedrawingNinjaProgressAnimation(terminal: $0, normalizeStep: normalizeStep) },\n            dumbTerminalAnimationFactory: { SingleLinePercentProgressAnimation(stream: stream, header: nil) },\n            defaultAnimationFactory: { MultiLineNinjaProgressAnimation(stream: stream, normalizeStep: normalizeStep) }\n        )\n    }\n}\n\n/// A redrawing ninja-like progress animation.\nfinal class RedrawingNinjaProgressAnimation: ProgressAnimationProtocol {\n    private let terminal: TerminalController\n    private var hasDisplayedProgress = false\n    private let normalizeStep: Bool\n\n    init(terminal: TerminalController, normalizeStep: Bool) {\n        self.terminal = terminal\n        self.normalizeStep = normalizeStep\n    }\n\n    func update(step: Int, total: Int, text: String) {\n        assert(step <= total)\n\n        terminal.clearLine()\n        var progressText = \"\"\n        if step < 0 && normalizeStep || step >= 0 {\n            let normalizedStep = max(0, step)\n            progressText = \"[\\(normalizedStep)/\\(total)] \\(text)\"\n        } else {\n            progressText = \"\\(text)\"\n        }\n        let width = terminal.width\n        if progressText.utf8.count > width {\n            let suffix = \"…\"\n            terminal.write(String(progressText.prefix(width - suffix.utf8.count)))\n            terminal.write(suffix)\n        } else {\n            terminal.write(progressText)\n        }\n\n        hasDisplayedProgress = true\n    }\n\n    func complete(success: Bool) {\n        if hasDisplayedProgress {\n            terminal.endLine()\n        }\n    }\n\n    func clear() {\n        terminal.clearLine()\n    }\n}\n\n/// A multi-line ninja-like progress animation.\nfinal class MultiLineNinjaProgressAnimation: ProgressAnimationProtocol {\n    private struct Info: Equatable {\n        let step: Int\n        let total: Int\n        let text: String\n    }\n\n    private let stream: WritableByteStream\n    private var lastDisplayedText: String? = nil\n    private let normalizeStep: Bool\n\n    init(stream: WritableByteStream, normalizeStep: Bool) {\n        self.stream = stream\n        self.normalizeStep = normalizeStep\n    }\n\n    func update(step: Int, total: Int, text: String) {\n        assert(step <= total)\n\n        guard text != lastDisplayedText else { return }\n\n        if (step < 0 && normalizeStep) || step >= 0 {\n            let normalizedStep = max(0, step)\n            stream.send(\"[\\(normalizedStep)/\\(total)] \")\n        }\n\n        stream.send(text)\n        stream.send(\"\\n\")\n        stream.flush()\n        lastDisplayedText = text\n    }\n\n    func complete(success: Bool) {\n    }\n\n    func clear() {\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/ProgressAnimation/PercentProgressAnimation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class TSCBasic.TerminalController\nimport protocol TSCBasic.WritableByteStream\n\nextension ProgressAnimation {\n    /// A percent-based progress animation that adapts to the provided output stream.\n    @_spi(SwiftPMInternal)\n    public static func percent(\n        stream: WritableByteStream,\n        verbose: Bool,\n        header: String,\n        isColorized: Bool\n    ) -> any ProgressAnimationProtocol {\n        Self.dynamic(\n            stream: stream,\n            verbose: verbose,\n            ttyTerminalAnimationFactory: { RedrawingPercentProgressAnimation(\n                terminal: $0,\n                header: header,\n                isColorized: isColorized\n            ) },\n            dumbTerminalAnimationFactory: { SingleLinePercentProgressAnimation(stream: stream, header: header) },\n            defaultAnimationFactory: { MultiLinePercentProgressAnimation(stream: stream, header: header) }\n        )\n    }\n}\n\n/// A redrawing lit-like progress animation.\nfinal class RedrawingPercentProgressAnimation: ProgressAnimationProtocol {\n    private let terminal: TerminalController\n    private let header: String\n    private let isColorized: Bool\n    private var hasDisplayedHeader = false\n\n    init(terminal: TerminalController, header: String, isColorized: Bool) {\n        self.terminal = terminal\n        self.header = header\n        self.isColorized = isColorized\n    }\n\n    /// Creates repeating string for count times.\n    /// If count is negative, returns empty string.\n    private func repeating(string: String, count: Int) -> String {\n        return String(repeating: string, count: max(count, 0))\n    }\n\n    func colorizeText(color: TerminalController.Color = .noColor) -> TerminalController.Color {\n        if self.isColorized {\n            return color\n        }\n        return .noColor\n    }\n\n    func update(step: Int, total: Int, text: String) {\n        assert(step <= total)\n        let isBold = self.isColorized\n\n        let width = terminal.width\n\n        if !hasDisplayedHeader {\n            let spaceCount = width / 2 - header.utf8.count / 2\n            terminal.write(repeating(string: \" \", count: spaceCount))\n            terminal.write(header, inColor: colorizeText(color: .cyan), bold: isBold)\n            terminal.endLine()\n            hasDisplayedHeader = true\n        } else {\n            terminal.moveCursor(up: 1)\n        }\n\n        terminal.clearLine()\n        let percentage = step * 100 / total\n        let paddedPercentage = percentage < 10 ? \" \\(percentage)\" : \"\\(percentage)\"\n        let prefix = \"\\(paddedPercentage)% \" + terminal\n            .wrap(\"[\", inColor: colorizeText(color: .green), bold: isBold)\n        terminal.write(prefix)\n\n        let barWidth = width - prefix.utf8.count\n        let n = Int(Double(barWidth) * Double(percentage) / 100.0)\n\n        terminal.write(\n            repeating(string: \"=\", count: n) + repeating(string: \"-\", count: barWidth - n),\n            inColor: colorizeText(color: .green)\n        )\n        terminal.write(\"]\", inColor: colorizeText(color: .green), bold: isBold)\n        terminal.endLine()\n\n        terminal.clearLine()\n        if text.utf8.count > width {\n            let prefix = \"…\"\n            terminal.write(prefix)\n            terminal.write(String(text.suffix(width - prefix.utf8.count)))\n        } else {\n            terminal.write(text)\n        }\n    }\n\n    func complete(success: Bool) {\n        terminal.endLine()\n        terminal.endLine()\n    }\n\n    func clear() {\n        terminal.clearLine()\n        terminal.moveCursor(up: 1)\n        terminal.clearLine()\n    }\n}\n\n/// A multi-line percent-based progress animation.\nfinal class MultiLinePercentProgressAnimation: ProgressAnimationProtocol {\n    private struct Info: Equatable {\n        let percentage: Int\n        let text: String\n    }\n\n    private let stream: WritableByteStream\n    private let header: String\n    private var hasDisplayedHeader = false\n    private var lastDisplayedText: String? = nil\n\n    init(stream: WritableByteStream, header: String) {\n        self.stream = stream\n        self.header = header\n    }\n\n    func update(step: Int, total: Int, text: String) {\n        assert(step <= total)\n\n        if !hasDisplayedHeader, !header.isEmpty {\n            stream.send(header)\n            stream.send(\"\\n\")\n            stream.flush()\n            hasDisplayedHeader = true\n        }\n\n        let percentage = step * 100 / total\n        stream.send(\"\\(percentage)%: \").send(text)\n        stream.send(\"\\n\")\n        stream.flush()\n        lastDisplayedText = text\n    }\n\n    func complete(success: Bool) {}\n\n    func clear() {}\n}\n"
  },
  {
    "path": "Sources/Basics/ProgressAnimation/ProgressAnimationProtocol.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class TSCBasic.TerminalController\nimport class TSCBasic.LocalFileOutputByteStream\nimport protocol TSCBasic.WritableByteStream\nimport protocol TSCUtility.ProgressAnimationProtocol\n\n@_spi(SwiftPMInternal)\npublic typealias ProgressAnimationProtocol = TSCUtility.ProgressAnimationProtocol\n\n/// Namespace to nest public progress animations under.\n@_spi(SwiftPMInternal)\npublic enum ProgressAnimation {\n    /// Dynamically create a progress animation based on the current stream\n    /// capabilities and desired verbosity.\n    ///\n    /// - Parameters:\n    ///   - stream: A stream to write animations into.\n    ///   - verbose: The verbosity level of other output in the system.\n    ///   - ttyTerminalAnimationFactory: A progress animation to use when the\n    ///     output stream is connected to a terminal with support for special\n    ///     escape sequences.\n    ///   - dumbTerminalAnimationFactory: A progress animation to use when the\n    ///     output stream is connected to a terminal without support for special\n    ///     escape sequences for clearing lines or controlling cursor positions.\n    ///   - defaultAnimationFactory: A progress animation to use when the\n    ///     desired output is verbose or the output stream verbose or is not\n    ///     connected to a terminal, e.g. a pipe or file.\n    /// - Returns: A progress animation instance matching the stream\n    ///   capabilities and desired verbosity.\n    static func dynamic(\n        stream: WritableByteStream,\n        verbose: Bool,\n        ttyTerminalAnimationFactory: (TerminalController) -> any ProgressAnimationProtocol,\n        dumbTerminalAnimationFactory: () -> any ProgressAnimationProtocol,\n        defaultAnimationFactory: () -> any ProgressAnimationProtocol\n    ) -> any ProgressAnimationProtocol {\n        if let terminal = TerminalController(stream: stream), !verbose {\n            return ttyTerminalAnimationFactory(terminal)\n        } else if let fileStream = stream as? LocalFileOutputByteStream,\n                  TerminalController.terminalType(fileStream) == .dumb\n        {\n            return dumbTerminalAnimationFactory()\n        } else {\n            return defaultAnimationFactory()\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/Basics/ProgressAnimation/SingleLinePercentProgressAnimation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class TSCBasic.TerminalController\nimport protocol TSCBasic.WritableByteStream\n\n/// A single line percent-based progress animation.\nfinal class SingleLinePercentProgressAnimation: ProgressAnimationProtocol {\n    private let stream: WritableByteStream\n    private let header: String?\n    private var displayedPercentages: Set<Int> = []\n    private var hasDisplayedHeader = false\n\n    init(stream: WritableByteStream, header: String?) {\n        self.stream = stream\n        self.header = header\n    }\n\n    func update(step: Int, total: Int, text: String) {\n        if let header = header, !hasDisplayedHeader {\n            stream.send(header)\n            stream.send(\"\\n\")\n            stream.flush()\n            hasDisplayedHeader = true\n        }\n\n        let percentage = step * 100 / total\n        let roundedPercentage = Int(Double(percentage / 10).rounded(.down)) * 10\n        if percentage != 100, !displayedPercentages.contains(roundedPercentage) {\n            stream.send(String(roundedPercentage)).send(\".. \")\n            displayedPercentages.insert(roundedPercentage)\n        }\n\n        stream.flush()\n    }\n\n    func complete(success: Bool) {\n        if success {\n            stream.send(\"OK\")\n            stream.flush()\n        }\n    }\n\n    func clear() {\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/ProgressAnimation/ThrottledProgressAnimation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport TSCUtility\n\n/// A progress animation wrapper that throttles updates to a given interval.\nfinal class ThrottledProgressAnimation: ProgressAnimationProtocol {\n    private let animation: ProgressAnimationProtocol\n    private let shouldUpdate: () -> Bool\n    private var pendingUpdate: (Int, Int, String)?\n\n    init<C: Clock>(\n      _ animation: ProgressAnimationProtocol,\n      now: @escaping () -> C.Instant, interval: C.Duration, clock: C.Type = C.self\n    ) {\n        self.animation = animation\n        var lastUpdate: C.Instant?\n        self.shouldUpdate = {\n            let now = now()\n            if let lastUpdate = lastUpdate, now < lastUpdate.advanced(by: interval) {\n                return false\n            }\n            // If we're over the interval or it's the first update, should update.\n            lastUpdate = now\n            return true\n        }\n    }\n\n    func update(step: Int, total: Int, text: String) {\n        guard shouldUpdate() else {\n            pendingUpdate = (step, total, text)\n            return\n        }\n        pendingUpdate = nil\n        animation.update(step: step, total: total, text: text)\n    }\n\n    func complete(success: Bool) {\n        if let (step, total, text) = pendingUpdate {\n            animation.update(step: step, total: total, text: text)\n        }\n        animation.complete(success: success)\n    }\n\n    func clear() {\n        animation.clear()\n    }\n}\n\n@_spi(SwiftPMInternal)\nextension ProgressAnimationProtocol {\n    @_spi(SwiftPMInternal)\n    public func throttled<C: Clock>(\n        now: @escaping () -> C.Instant,\n        interval: C.Duration,\n        clock: C.Type = C.self\n    ) -> some ProgressAnimationProtocol {\n        ThrottledProgressAnimation(self, now: now, interval: interval, clock: clock)\n    }\n\n    @_spi(SwiftPMInternal)\n    public func throttled<C: Clock>(\n        clock: C,\n        interval: C.Duration\n    ) -> some ProgressAnimationProtocol {\n        self.throttled(now: { clock.now }, interval: interval, clock: C.self)\n    }\n\n    @_spi(SwiftPMInternal)\n    public func throttled(\n        interval: ContinuousClock.Duration\n    )  -> some ProgressAnimationProtocol  {\n        self.throttled(clock: ContinuousClock(), interval: interval)\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/SQLite.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TSCBasic\nimport Foundation\n\n#if SWIFT_PACKAGE && (os(Windows) || os(Android))\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftToolchainCSQLite\n#else\nimport SwiftToolchainCSQLite\n#endif\n#else\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SPMSQLite3\n#else\nimport SPMSQLite3\n#endif\n#endif\n\n/// A minimal SQLite wrapper.\npackage final class SQLite {\n    /// The location of the database.\n    package let location: Location\n\n    /// The configuration for the database.\n    package let configuration: Configuration\n\n    /// Pointer to the database.\n    let db: OpaquePointer\n\n    /// Create or open the database at the given path.\n    ///\n    /// The database is opened in serialized mode.\n    package init(location: Location, configuration: Configuration = Configuration()) throws {\n        self.location = location\n        self.configuration = configuration\n\n        var handle: OpaquePointer?\n        try Self.checkError(\n            {\n                sqlite3_open_v2(\n                    location.pathString,\n                    &handle,\n                    SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX,\n                    nil\n                )\n            },\n            description: \"Unable to open database at \\(self.location)\"\n        )\n\n        guard let db = handle else {\n            throw StringError(\"Unable to open database at \\(self.location)\")\n        }\n        self.db = db\n        try Self.checkError({ sqlite3_extended_result_codes(db, 1) }, description: \"Unable to configure database\")\n        try Self.checkError(\n            { sqlite3_busy_timeout(db, self.configuration.busyTimeoutMilliseconds) },\n            description: \"Unable to configure database busy timeout\"\n        )\n        if let maxPageCount = self.configuration.maxPageCount {\n            try self.exec(query: \"PRAGMA max_page_count=\\(maxPageCount);\")\n        }\n    }\n\n    @available(*, deprecated, message: \"use init(location:configuration) instead\")\n    package convenience init(dbPath: AbsolutePath) throws {\n        try self.init(location: .path(dbPath))\n    }\n\n    /// Prepare the given query.\n    package func prepare(query: String) throws -> PreparedStatement {\n        try PreparedStatement(db: self.db, query: query)\n    }\n\n    /// Directly execute the given query.\n    ///\n    /// Note: Use withCString for string arguments.\n    package func exec(query queryString: String, args: [CVarArg] = [], _ callback: SQLiteExecCallback? = nil) throws {\n        let query = withVaList(args) { ptr in\n            sqlite3_vmprintf(queryString, ptr)\n        }\n\n        let wcb = callback.map { CallbackWrapper($0) }\n        let callbackCtx = wcb.map { Unmanaged.passUnretained($0).toOpaque() }\n\n        var err: UnsafeMutablePointer<Int8>?\n        try Self.checkError { sqlite3_exec(db, query, sqlite_callback, callbackCtx, &err) }\n\n        sqlite3_free(query)\n\n        if let err {\n            let errorString = String(cString: err)\n            sqlite3_free(err)\n            throw StringError(errorString)\n        }\n    }\n\n    package func close() throws {\n        try Self.checkError { sqlite3_close(db) }\n    }\n\n    package typealias SQLiteExecCallback = ([Column]) -> Void\n\n    package struct Configuration {\n        package var busyTimeoutMilliseconds: Int32\n        package var maxSizeInBytes: Int?\n\n        // https://www.sqlite.org/pgszchng2016.html\n        private let defaultPageSizeInBytes = 1024\n\n        package init() {\n            self.busyTimeoutMilliseconds = 5000\n            self.maxSizeInBytes = .none\n        }\n\n        // FIXME: deprecated 12/2020, remove once clients migrated over\n        @available(*, deprecated, message: \"use busyTimeout instead\")\n        package var busyTimeoutSeconds: Int32 {\n            get {\n                self._busyTimeoutSeconds\n            } set {\n                self._busyTimeoutSeconds = newValue\n            }\n        }\n\n        // so tests dont warn\n        internal var _busyTimeoutSeconds: Int32 {\n            get {\n                Int32(truncatingIfNeeded: Int(Double(self.busyTimeoutMilliseconds) / 1000))\n            } set {\n                self.busyTimeoutMilliseconds = newValue * 1000\n            }\n        }\n\n        package var maxSizeInMegabytes: Int? {\n            get {\n                self.maxSizeInBytes.map { $0 / (1024 * 1024) }\n            }\n            set {\n                self.maxSizeInBytes = newValue.map { $0 * 1024 * 1024 }\n            }\n        }\n\n        package var maxPageCount: Int? {\n            self.maxSizeInBytes.map { $0 / self.defaultPageSizeInBytes }\n        }\n    }\n\n    package enum Location: Sendable {\n        case path(AbsolutePath)\n        case memory\n        case temporary\n\n        var pathString: String {\n            switch self {\n            case .path(let path):\n                return path.pathString\n            case .memory:\n                return \":memory:\"\n            case .temporary:\n                return \"\"\n            }\n        }\n    }\n\n    /// Represents an sqlite value.\n    package enum SQLiteValue {\n        case null\n        case string(String)\n        case int(Int)\n        case blob(Data)\n    }\n\n    /// Represents a row returned by called step() on a prepared statement.\n    package struct Row {\n        /// The pointer to the prepared statement.\n        let stmt: OpaquePointer\n\n        /// Get integer at the given column index.\n        package func int(at index: Int32) -> Int {\n            Int(sqlite3_column_int64(self.stmt, index))\n        }\n\n        /// Get blob data at the given column index.\n        package func blob(at index: Int32) -> Data {\n            let bytes = sqlite3_column_blob(stmt, index)!\n            let count = sqlite3_column_bytes(stmt, index)\n            return Data(bytes: bytes, count: Int(count))\n        }\n\n        /// Get string at the given column index.\n        package func string(at index: Int32) -> String {\n            String(cString: sqlite3_column_text(self.stmt, index))\n        }\n    }\n\n    package struct Column {\n        package var name: String\n        package var value: String\n    }\n\n    /// Represents a prepared statement.\n    package struct PreparedStatement {\n        typealias sqlite3_destructor_type = @convention(c) (UnsafeMutableRawPointer?) -> Void\n        static let SQLITE_STATIC = unsafeBitCast(0, to: sqlite3_destructor_type.self)\n        static let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)\n\n        /// The pointer to the prepared statement.\n        let stmt: OpaquePointer\n\n        package init(db: OpaquePointer, query: String) throws {\n            var stmt: OpaquePointer?\n            try SQLite.checkError { sqlite3_prepare_v2(db, query, -1, &stmt, nil) }\n            self.stmt = stmt!\n        }\n\n        /// Evaluate the prepared statement.\n        @discardableResult\n        package func step() throws -> Row? {\n            let result = sqlite3_step(stmt)\n\n            switch result {\n            case SQLITE_DONE:\n                return nil\n            case SQLITE_ROW:\n                return Row(stmt: self.stmt)\n            default:\n                throw StringError(String(cString: sqlite3_errstr(result)))\n            }\n        }\n\n        /// Bind the given arguments to the statement.\n        package func bind(_ arguments: [SQLiteValue]) throws {\n            for (idx, argument) in arguments.enumerated() {\n                let idx = Int32(idx) + 1\n                switch argument {\n                case .null:\n                    try checkError { sqlite3_bind_null(stmt, idx) }\n                case .int(let int):\n                    try checkError { sqlite3_bind_int64(stmt, idx, Int64(int)) }\n                case .string(let str):\n                    try checkError { sqlite3_bind_text(stmt, idx, str, -1, Self.SQLITE_TRANSIENT) }\n                case .blob(let blob):\n                    try checkError {\n                        blob.withUnsafeBytes { ptr in\n                            sqlite3_bind_blob(\n                                stmt,\n                                idx,\n                                ptr.baseAddress,\n                                Int32(blob.count),\n                                Self.SQLITE_TRANSIENT\n                            )\n                        }\n                    }\n                }\n            }\n        }\n\n        /// Reset the prepared statement.\n        package func reset() throws {\n            try SQLite.checkError { sqlite3_reset(stmt) }\n        }\n\n        /// Clear bindings from the prepared statement.\n        package func clearBindings() throws {\n            try SQLite.checkError { sqlite3_clear_bindings(stmt) }\n        }\n\n        /// Finalize the statement and free up resources.\n        package func finalize() throws {\n            try SQLite.checkError { sqlite3_finalize(stmt) }\n        }\n    }\n\n    fileprivate class CallbackWrapper {\n        var callback: SQLiteExecCallback\n        init(_ callback: @escaping SQLiteExecCallback) {\n            self.callback = callback\n        }\n    }\n\n    private static func checkError(_ fn: () -> Int32, description prefix: String? = .none) throws {\n        let result = fn()\n        if result != SQLITE_OK {\n            var description = String(cString: sqlite3_errstr(result))\n            switch description.lowercased() {\n            case \"database or disk is full\":\n                throw Errors.databaseFull\n            default:\n                if let prefix {\n                    description = \"\\(prefix): \\(description)\"\n                }\n                throw StringError(description)\n            }\n        }\n    }\n\n    package enum Errors: Error {\n        case databaseFull\n    }\n}\n\n// Explicitly mark this class as non-Sendable\n@available(*, unavailable)\nextension SQLite: Sendable {}\n\nprivate func sqlite_callback(\n    _ ctx: UnsafeMutableRawPointer?,\n    _ numColumns: Int32,\n    _ columns: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?,\n    _ columnNames: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>?\n) -> Int32 {\n    guard let ctx else { return 0 }\n    guard let columnNames, let columns else { return 0 }\n    let numColumns = Int(numColumns)\n    var result: [SQLite.Column] = []\n\n    for idx in 0 ..< numColumns {\n        var name = \"\"\n        if let ptr = columnNames.advanced(by: idx).pointee {\n            name = String(cString: ptr)\n        }\n        var value = \"\"\n        if let ptr = columns.advanced(by: idx).pointee {\n            value = String(cString: ptr)\n        }\n        result.append(SQLite.Column(name: name, value: value))\n    }\n\n    let wcb = Unmanaged<SQLite.CallbackWrapper>.fromOpaque(ctx).takeUnretainedValue()\n    wcb.callback(result)\n\n    return 0\n}\n"
  },
  {
    "path": "Sources/Basics/SQLiteBackedCache.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport protocol TSCBasic.Closable\nimport var TSCBasic.localFileSystem\n\n/// SQLite backed persistent cache.\npackage final class SQLiteBackedCache<Value: Codable>: Closable {\n    package typealias Key = String\n\n    package let tableName: String\n    package let fileSystem: FileSystem\n    package let location: SQLite.Location\n    package let configuration: SQLiteBackedCacheConfiguration\n\n    private var state = State.idle\n    private let stateLock = NSLock()\n\n    private let jsonEncoder: JSONEncoder\n    private let jsonDecoder: JSONDecoder\n\n    /// Creates a SQLite-backed cache.\n    ///\n    /// - Parameters:\n    ///   - tableName: The SQLite table name. Must follow SQLite naming rules (e.g., no spaces).\n    ///   - location: SQLite.Location\n    ///   - configuration: Optional. Configuration for the cache.\n    package init(tableName: String, location: SQLite.Location, configuration: SQLiteBackedCacheConfiguration = .init()) {\n        self.tableName = tableName\n        self.location = location\n        switch self.location {\n        case .path, .temporary:\n            self.fileSystem = localFileSystem\n        case .memory:\n            self.fileSystem = InMemoryFileSystem()\n        }\n        self.configuration = configuration\n        self.jsonEncoder = JSONEncoder.makeWithDefaults()\n        self.jsonDecoder = JSONDecoder.makeWithDefaults()\n    }\n\n    /// Creates a SQLite-backed cache.\n    ///\n    /// - Parameters:\n    ///   - tableName: The SQLite table name. Must follow SQLite naming rules (e.g., no spaces).\n    ///   - path: The path of the SQLite database.\n    ///   - configuration: Optional. Configuration for the cache.\n    package convenience init(\n        tableName: String,\n        path: AbsolutePath,\n        configuration: SQLiteBackedCacheConfiguration = .init()\n    ) {\n        self.init(tableName: tableName, location: .path(path), configuration: configuration)\n    }\n\n    deinit {\n        try? self.withStateLock {\n            if case .connected(let db) = self.state {\n                // TODO: we could wrap the failure here with diagnostics if it was available\n                assertionFailure(\"db should be closed\")\n                try db.close()\n            }\n        }\n    }\n\n    package func close() throws {\n        try self.withStateLock {\n            if case .connected(let db) = self.state {\n                try db.close()\n            }\n            self.state = .disconnected\n        }\n    }\n\n    private func put(\n        rawKey key: SQLite.SQLiteValue,\n        value: Value,\n        replace: Bool = false,\n        observabilityScope: ObservabilityScope? = nil\n    ) throws {\n        do {\n            let query = \"INSERT OR \\(replace ? \"REPLACE\" : \"IGNORE\") INTO \\(self.tableName) VALUES (?, ?);\"\n            try self.executeStatement(query) { statement in\n                let data = try self.jsonEncoder.encode(value)\n                let bindings: [SQLite.SQLiteValue] = [\n                    key,\n                    .blob(data),\n                ]\n                try statement.bind(bindings)\n                try statement.step()\n            }\n        } catch (let error as SQLite.Errors) where error == .databaseFull {\n            if !self.configuration.truncateWhenFull {\n                throw error\n            }\n            observabilityScope?\n                .emit(\n                    warning: \"\"\"\n                    truncating \\(self.tableName) cache database since it reached max size of \\(\n                        self.configuration.maxSizeInBytes ?? 0\n                    ) bytes\n                    \"\"\"\n                )\n            try self.executeStatement(\"DELETE FROM \\(self.tableName);\") { statement in\n                try statement.step()\n            }\n            try self.put(rawKey: key, value: value, replace: replace, observabilityScope: observabilityScope)\n        } catch {\n            throw error\n        }\n    }\n\n    package func put(\n        blobKey key: some Sequence<UInt8>,\n        value: Value,\n        replace: Bool = false,\n        observabilityScope: ObservabilityScope? = nil\n    ) throws {\n        try self.put(rawKey: .blob(Data(key)), value: value, observabilityScope: observabilityScope)\n    }\n\n    package func put(\n        key: Key,\n        value: Value,\n        replace: Bool = false,\n        observabilityScope: ObservabilityScope? = nil\n    ) throws {\n        try self.put(rawKey: .string(key), value: value, replace: replace, observabilityScope: observabilityScope)\n    }\n\n    package func get(key: Key) throws -> Value? {\n        let query = \"SELECT value FROM \\(self.tableName) WHERE key = ? LIMIT 1;\"\n        return try self.executeStatement(query) { statement -> Value? in\n            try statement.bind([.string(key)])\n            let data = try statement.step()?.blob(at: 0)\n            return try data.flatMap {\n                try self.jsonDecoder.decode(Value.self, from: $0)\n            }\n        }\n    }\n\n    package func get(blobKey key: some Sequence<UInt8>) throws -> Value? {\n        let query = \"SELECT value FROM \\(self.tableName) WHERE key = ? LIMIT 1;\"\n        return try self.executeStatement(query) { statement -> Value? in\n            try statement.bind([.blob(Data(key))])\n            let data = try statement.step()?.blob(at: 0)\n            return try data.flatMap {\n                try self.jsonDecoder.decode(Value.self, from: $0)\n            }\n        }\n    }\n\n    package func remove(key: Key) throws {\n        let query = \"DELETE FROM \\(self.tableName) WHERE key = ?;\"\n        try self.executeStatement(query) { statement in\n            try statement.bind([.string(key)])\n            try statement.step()\n        }\n    }\n\n    @discardableResult\n    private func executeStatement<T>(_ query: String, _ body: (SQLite.PreparedStatement) throws -> T) throws -> T {\n        try self.withDB { db in\n            let result: Result<T, Error>\n            let statement = try db.prepare(query: query)\n            do {\n                result = try .success(body(statement))\n            } catch {\n                result = .failure(error)\n            }\n            try statement.finalize()\n            switch result {\n            case .failure(let error):\n                throw error\n            case .success(let value):\n                return value\n            }\n        }\n    }\n\n    private func withDB<T>(_ body: (SQLite) throws -> T) throws -> T {\n        let createDB = { () throws -> SQLite in\n            let db = try SQLite(location: self.location, configuration: self.configuration.underlying)\n            try self.createSchemaIfNecessary(db: db)\n            return db\n        }\n\n        return try self.withStateLock { () -> T in\n            let db: SQLite\n            switch (self.location, self.state) {\n            case (.path(let path), .connected(let database)):\n                if self.fileSystem.exists(path) {\n                    db = database\n                } else {\n                    try database.close()\n                    try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)\n                    db = try createDB()\n                }\n            case (.path(let path), _):\n                if !self.fileSystem.exists(path) {\n                    try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)\n                }\n                db = try createDB()\n            case (_, .connected(let database)):\n                db = database\n            case (_, _):\n                db = try createDB()\n            }\n            self.state = .connected(db)\n            return try body(db)\n        }\n    }\n\n    private func createSchemaIfNecessary(db: SQLite) throws {\n        let table = \"\"\"\n            CREATE TABLE IF NOT EXISTS \\(self.tableName) (\n                key STRING PRIMARY KEY NOT NULL,\n                value BLOB NOT NULL\n            );\n        \"\"\"\n\n        try db.exec(query: table)\n        try db.exec(query: \"PRAGMA journal_mode=WAL;\")\n    }\n\n    private func withStateLock<T>(_ body: () throws -> T) throws -> T {\n        switch self.location {\n        case .path(let path):\n            if !self.fileSystem.exists(path.parentDirectory) {\n                try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)\n            }\n            return try self.fileSystem.withLock(on: path, type: .exclusive, body)\n        case .memory, .temporary:\n            return try self.stateLock.withLock(body)\n        }\n    }\n\n    private enum State {\n        case idle\n        case connected(SQLite)\n        case disconnected\n    }\n}\n\npackage struct SQLiteBackedCacheConfiguration {\n    package var truncateWhenFull: Bool\n\n    fileprivate var underlying: SQLite.Configuration\n\n    package init() {\n        self.underlying = .init()\n        self.truncateWhenFull = true\n        self.maxSizeInMegabytes = 100\n        // see https://www.sqlite.org/c3ref/busy_timeout.html\n        self.busyTimeoutMilliseconds = 1000\n    }\n\n    package var maxSizeInMegabytes: Int? {\n        get {\n            self.underlying.maxSizeInMegabytes\n        }\n        set {\n            self.underlying.maxSizeInMegabytes = newValue\n        }\n    }\n\n    package var maxSizeInBytes: Int? {\n        get {\n            self.underlying.maxSizeInBytes\n        }\n        set {\n            self.underlying.maxSizeInBytes = newValue\n        }\n    }\n\n    package var busyTimeoutMilliseconds: Int32 {\n        get {\n            self.underlying.busyTimeoutMilliseconds\n        }\n        set {\n            self.underlying.busyTimeoutMilliseconds = newValue\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/Sandbox.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport func TSCBasic.determineTempDirectory\n\npublic enum SandboxNetworkPermission: Equatable {\n    case none\n    case local(ports: [Int])\n    case all(ports: [Int])\n    case docker\n    case unixDomainSocket\n\n    fileprivate var domain: String? {\n        switch self {\n        case .none, .docker, .unixDomainSocket: return nil\n        case .local: return \"local\"\n        case .all: return \"*\"\n        }\n    }\n\n    fileprivate var ports: [Int] {\n        switch self {\n        case .all(let ports): return ports\n        case .local(let ports): return ports\n        case .none, .docker, .unixDomainSocket: return []\n        }\n    }\n}\n\npublic enum Sandbox {\n    /// Applies a sandbox invocation to the given command line (if the platform supports it),\n    /// and returns the modified command line. On platforms that don't support sandboxing, the\n    /// command line is returned unmodified.\n    ///\n    /// - Parameters:\n    ///   - command: The command line to sandbox (including executable as first argument)\n    ///   - fileSystem: The file system instance to use.\n    ///   - strictness: The basic strictness level of the sandbox.\n    ///   - writableDirectories: Paths under which writing should be allowed, even if they would otherwise be read-only based on the strictness or paths in `readOnlyDirectories`.\n    ///   - readOnlyDirectories: Paths under which writing should be denied, even if they would have otherwise been allowed by the rules implied by the strictness level.\n    public static func apply(\n        command: [String],\n        fileSystem: FileSystem,\n        strictness: Strictness = .default,\n        writableDirectories: [AbsolutePath] = [],\n        readOnlyDirectories: [AbsolutePath] = [],\n        allowNetworkConnections: [SandboxNetworkPermission] = []\n    ) throws -> [String] {\n        #if os(macOS)\n        let profile = try macOSSandboxProfile(\n            fileSystem: fileSystem,\n            strictness: strictness,\n            writableDirectories: writableDirectories,\n            readOnlyDirectories: readOnlyDirectories,\n            allowNetworkConnections: allowNetworkConnections\n        )\n        return [\"/usr/bin/sandbox-exec\", \"-p\", profile] + command\n        #else\n        // rdar://40235432, rdar://75636874 tracks implementing sandboxes for other platforms.\n        return command\n        #endif\n    }\n\n    /// Basic strictness level of a sandbox applied to a command line.\n    public enum Strictness: Equatable {\n        /// Blocks network access and all file system modifications.\n        case `default`\n        /// More lenient restrictions than the default, for compatibility with SwiftPM manifests using a tools version older than 5.3.\n        case manifest_pre_53 // backwards compatibility for manifests\n        /// Like `default`, but also makes temporary-files directories (such as `/tmp`) on the platform writable.\n        case writableTemporaryDirectory\n    }\n}\n\n// MARK: - macOS\n\n#if os(macOS)\nfileprivate let threadSafeDarwinCacheDirectories: [AbsolutePath] = {\n    func GetConfStr(_ name: CInt) -> AbsolutePath? {\n        let length: Int = confstr(name, nil, 0)\n\n        let buffer: UnsafeMutableBufferPointer<CChar> = .allocate(capacity: length)\n        defer { buffer.deallocate() }\n\n        guard confstr(name, buffer.baseAddress, length) == length else { return nil }\n\n        let value = String(cString: buffer.baseAddress!)\n        guard value.hasSuffix(\"/\") else { return nil }\n\n        return try? resolveSymlinks(AbsolutePath(validating: value))\n    }\n\n    var directories: [AbsolutePath] = []\n    try? directories.append(AbsolutePath(validating: \"/private/var/tmp\"))\n    (try? TSCBasic.determineTempDirectory()).map { directories.append(AbsolutePath($0)) }\n    GetConfStr(_CS_DARWIN_USER_TEMP_DIR).map { directories.append($0) }\n    GetConfStr(_CS_DARWIN_USER_CACHE_DIR).map { directories.append($0) }\n    return directories\n}()\n\nfileprivate func macOSSandboxProfile(\n    fileSystem: FileSystem,\n    strictness: Sandbox.Strictness,\n    writableDirectories: [AbsolutePath],\n    readOnlyDirectories: [AbsolutePath],\n    allowNetworkConnections: [SandboxNetworkPermission]\n) throws -> String {\n    var contents = \"(version 1)\\n\"\n\n    // Deny everything by default.\n    contents += \"(deny default)\\n\"\n\n    // Import the system sandbox profile.\n    contents += \"(import \\\"system.sb\\\")\\n\"\n\n    // Allow reading all files; ideally we'd only allow the package directory and any dependencies,\n    // but all kinds of system locations need to be accessible.\n    contents += \"(allow file-read*)\\n\"\n\n    // This is needed to launch any processes.\n    contents += \"(allow process*)\\n\"\n    \n    // This is needed to use the UniformTypeIdentifiers API.\n    contents += \"(allow mach-lookup (global-name \\\"com.apple.lsd.mapdb\\\"))\\n\"\n\n    // For downloadable Metal toolchain lookups.\n    contents += \"(allow mach-lookup (global-name \\\"com.apple.mobileassetd.v2\\\"))\\n\"\n\n    if allowNetworkConnections.filter({ $0 != .none }).isEmpty == false {\n        // this is used by the system for caching purposes and will lead to log spew if not allowed\n        contents += \"(allow file-write* (regex \\\"/Users/*/Library/Caches/*/Cache.db*\\\"))\"\n\n        // this allows the specific network connections, as well as resolving DNS\n        contents += \"\"\"\n        (system-network)\n        (allow network-outbound\n            (literal \"/private/var/run/mDNSResponder\")\n        \"\"\"\n\n        allowNetworkConnections.forEach {\n            if let domain = $0.domain {\n                $0.ports.forEach { port in\n                    contents += \"(remote ip \\\"\\(domain):\\(port)\\\")\"\n                }\n\n                // empty list of ports means all are permitted\n                if $0.ports.isEmpty {\n                    contents += \"(remote ip \\\"\\(domain):*\\\")\"\n                }\n            }\n\n            switch $0 {\n            case .docker:\n                // specifically allow Docker by basename of the socket\n                contents += \"(remote unix-socket (regex \\\"*/docker.sock\\\"))\"\n            case .unixDomainSocket:\n                // this allows unix domain sockets\n                contents += \"(remote unix-socket)\"\n            default:\n                break\n            }\n        }\n\n        contents += \"\\n)\\n\"\n    }\n\n    // The following accesses are only needed when interpreting the manifest (versus running a compiled version).\n    if strictness == .manifest_pre_53 {\n        // This is required by the Swift compiler.\n        contents += \"(allow sysctl*)\\n\"\n    }\n\n    // Allow writing only to certain directories.\n    var writableDirectoriesExpression: [String] = []\n\n    // The following accesses are only needed when interpreting the manifest (versus running a compiled version).\n    if strictness == .manifest_pre_53 {\n        writableDirectoriesExpression += threadSafeDarwinCacheDirectories.map {\n            ##\"(regex #\"^\\##($0.pathString)/org\\.llvm\\.clang.*\")\"##\n        }\n    }\n    // Optionally allow writing to temporary directories (a lot of use of Foundation requires this).\n    else if strictness == .writableTemporaryDirectory {\n        var stableCacheDirectories: [AbsolutePath] = []\n        // Add `subpath` expressions for the regular, Foundation and clang module cache temporary directories.\n        for tmpDir in ([\"/tmp\"] + threadSafeDarwinCacheDirectories.map(\\.pathString)) {\n            let resolved = try resolveSymlinks(AbsolutePath(validating: tmpDir))\n            if !stableCacheDirectories.contains(where: { $0.isAncestorOfOrEqual(to: resolved) }) {\n                stableCacheDirectories.append(resolved)\n                writableDirectoriesExpression += [\n                    \"(subpath \\(resolved.quotedAsSubpathForSandboxProfile))\",\n                ]\n            }\n        }\n    }\n\n    // Emit rules for paths under which writing is allowed. Some of these expressions may be regular expressions and others literal subpaths.\n    if writableDirectoriesExpression.count > 0 {\n        contents += \"(allow file-write*\\n\"\n        for expression in writableDirectoriesExpression {\n            contents += \"    \\(expression)\\n\"\n        }\n        contents += \")\\n\"\n    }\n\n    // Emit rules for paths under which writing should be disallowed, even if they would be covered by a previous rule to allow writing to them. A classic case is a package which is located under the temporary directory, which should be read-only even though the temporary directory as a whole is writable.\n    if readOnlyDirectories.count > 0 {\n        contents += \"(deny file-write*\\n\"\n        for path in readOnlyDirectories {\n            contents += \"    (subpath \\(try resolveSymlinks(path).quotedAsSubpathForSandboxProfile))\\n\"\n        }\n        contents += \")\\n\"\n    }\n\n    // Emit rules for paths under which writing is allowed, even if they are descendants directories that are otherwise read-only.\n    if writableDirectories.count > 0 {\n        contents += \"(allow file-write*\\n\"\n        var stableItemReplacementDirectories: [AbsolutePath] = []\n        for path in writableDirectories {\n            contents += \"    (subpath \\(try resolveSymlinks(path).quotedAsSubpathForSandboxProfile))\\n\"\n            \n            // `itemReplacementDirectories` may return a combination of stable directory paths, and subdirectories which are unique on every call. Avoid including unnecessary subdirectories in the Sandbox profile which may lead to nondeterminism in its construction.\n            if let itemReplacementDirectories = try? fileSystem.itemReplacementDirectories(for: path).sorted(by: { $0.pathString.count < $1.pathString.count }) {\n                for directory in itemReplacementDirectories {\n                    let resolved = try resolveSymlinks(directory)\n                    if !stableItemReplacementDirectories.contains(where: { $0.isAncestorOfOrEqual(to: resolved) }) {\n                        stableItemReplacementDirectories.append(resolved)\n                        contents += \"    (subpath \\(resolved.quotedAsSubpathForSandboxProfile))\\n\"\n                    }\n                }\n            }\n        }\n        contents += \")\\n\"\n    }\n\n    return contents\n}\n\nextension AbsolutePath {\n    /// Private computed property that returns a version of the path as a string quoted for use as a subpath in a .sb sandbox profile.\n    fileprivate var quotedAsSubpathForSandboxProfile: String {\n        \"\\\"\" + self.pathString\n            .replacing(\"\\\\\", with: \"\\\\\\\\\")\n            .replacing(\"\\\"\", with: \"\\\\\\\"\")\n            + \"\\\"\"\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Basics/SendableTimeInterval.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport enum Dispatch.DispatchTimeInterval\n\n/// This typealias hides `DispatchTimeInterval` as an implementation detail until we can use `Swift.Duration`, as the\n/// latter requires macOS 13.\npublic typealias SendableTimeInterval = DispatchTimeInterval\n"
  },
  {
    "path": "Sources/Basics/Serialization/SerializedJSON.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Wrapper type representing serialized escaped JSON strings providing helpers\n/// for escaped string interpolations for common types such as `AbsolutePath`.\npublic struct SerializedJSON {\n    let underlying: String\n}\n\nextension SerializedJSON: ExpressibleByStringLiteral {\n    public init(stringLiteral: String) {\n        self.underlying = stringLiteral\n    }\n}\n\nextension SerializedJSON: ExpressibleByStringInterpolation {\n    public init(stringInterpolation: StringInterpolation) {\n        self.init(underlying: stringInterpolation.value)\n    }\n\n    public struct StringInterpolation: StringInterpolationProtocol {\n        fileprivate var value: String = \"\"\n\n        private func escape(_ string: String) -> String {\n            string.replacing(#\"\\\"#, with: #\"\\\\\"#)\n        }\n\n        public init(literalCapacity: Int, interpolationCount: Int) {\n            self.value.reserveCapacity(literalCapacity)\n        }\n\n        public mutating func appendLiteral(_ literal: String) {\n            self.value.append(self.escape(literal))\n        }\n\n        public mutating func appendInterpolation(_ value: some CustomStringConvertible) {\n            self.value.append(self.escape(value.description))\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/SourceControlURL.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic struct SourceControlURL: Codable, Equatable, Hashable, Sendable {\n    private let urlString: String\n\n    public init(stringLiteral: String) {\n        self.urlString = stringLiteral\n    }\n\n    public init(_ urlString: String) {\n        self.urlString = urlString\n    }\n\n    public init(_ url: URL) {\n        self.urlString = url.absoluteString\n    }\n\n    public var absoluteString: String {\n        return self.urlString\n    }\n\n    public var lastPathComponent: String {\n        return (self.urlString as NSString).lastPathComponent\n    }\n\n    public var url: URL? {\n        return URL(string: self.urlString)\n    }\n}\n\nextension SourceControlURL: CustomStringConvertible {\n    public var description: String {\n        return self.urlString\n    }\n}\n\nextension SourceControlURL: ExpressibleByStringInterpolation {\n}\n\nextension SourceControlURL: ExpressibleByStringLiteral {\n}\n"
  },
  {
    "path": "Sources/Basics/SwiftVersion.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import TSCclibc\n#else\nprivate import TSCclibc\n#endif\n\npublic struct SwiftVersion: Sendable {\n    /// The version number.\n    public var version: (major: Int, minor: Int, patch: Int)\n\n    /// Whether or not this is a development version.\n    public var isDevelopment: Bool\n\n    /// Build information, as an unstructured string.\n    public var buildIdentifier: String?\n\n    /// The major component of the version number.\n    public var major: Int { self.version.major }\n    /// The minor component of the version number.\n    public var minor: Int { self.version.minor }\n    /// The patch component of the version number.\n    public var patch: Int { self.version.patch }\n\n    /// The version as a readable string.\n    public var displayString: String {\n        var result = \"\\(major).\\(minor).\\(patch)\"\n        if self.isDevelopment {\n            result += \"-dev\"\n        }\n        if let buildIdentifier {\n            result += \" (\" + buildIdentifier + \")\"\n        }\n        return result\n    }\n\n    /// The complete product version display string (including the name).\n    public var completeDisplayString: String {\n        var vendorPrefix = String(cString: SPM_VendorNameString())\n        if !vendorPrefix.isEmpty {\n            vendorPrefix += \" \"\n        }\n        return vendorPrefix + \"Swift Package Manager - Swift \" + self.displayString\n    }\n}\n\nextension SwiftVersion {\n    /// The current version of the package manager.\n    public static let current = SwiftVersion(\n        version: (6, 4, 0),\n        isDevelopment: true,\n        buildIdentifier: getBuildIdentifier()\n    )\n}\n\nprivate func getBuildIdentifier() -> String? {\n    let buildIdentifier = String(cString: SPM_BuildIdentifierString())\n    return buildIdentifier.isEmpty ? nil : buildIdentifier\n}\n"
  },
  {
    "path": "Sources/Basics/TestingLibrary.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The testing libraries supported by the package manager.\npublic enum TestingLibrary: Sendable, CustomStringConvertible {\n  /// The XCTest library.\n  ///\n  /// This case represents both the open-source swift-corelibs-xctest\n  /// package and Apple's XCTest framework that ships with Xcode.\n  case xctest\n\n  /// The swift-testing library.\n  case swiftTesting\n\n  public var description: String {\n    switch self {\n    case .xctest:\n      \"XCTest\"\n    case .swiftTesting:\n      \"Swift Testing\"\n    }\n  }\n}\n\n"
  },
  {
    "path": "Sources/Basics/Triple+Basics.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TSCUtility\nimport enum TSCBasic.JSON\n\nextension Triple {\n    public init(_ description: String) throws {\n        self.init(description, normalizing: false)\n    }\n}\n\nextension Triple {\n    public static let macOS = try! Self(\"x86_64-apple-macosx\")\n}\n\nextension Triple {\n    public var isWasm: Bool {\n        [.wasm32, .wasm64].contains(self.arch)\n    }\n\n    public func isApple() -> Bool {\n        vendor == .apple\n    }\n\n    public func isAndroid() -> Bool {\n        os == .linux && environment == .android\n    }\n\n    public func isDarwin() -> Bool {\n        switch (vendor, os) {\n        case (.apple, .noneOS):\n            return false\n        case (.apple, _), (_, .macosx), (_, .darwin):\n            return true\n        default:\n            return false\n        }\n    }\n\n    public func isLinux() -> Bool {\n        os == .linux\n    }\n\n    public func isWindows() -> Bool {\n        os == .win32\n    }\n\n    public func isWASI() -> Bool {\n        os == .wasi\n    }\n\n    public func isOpenBSD() -> Bool {\n        os == .openbsd\n    }\n\n    public func isFreeBSD() -> Bool {\n        os == .freebsd\n    }\n\n    /// Returns the triple string for the given platform version.\n    ///\n    /// This is currently meant for Apple platforms only.\n    public func tripleString(forPlatformVersion version: String) -> String {\n        precondition(isDarwin())\n        return \"\"\"\n            \\(self.archName)-\\\n            \\(self.vendorName)-\\\n            \\(self.osNameUnversioned)\\(version)\\\n            \\(self.environmentName.isEmpty ? \"\" : \"-\\(self.environmentName)\")\n            \"\"\"\n    }\n\n    public var tripleString: String {\n        self.triple\n    }\n\n    /// Determine the versioned host triple using the Swift compiler.\n    public static func getVersionedHostTriple(usingSwiftCompiler swiftCompiler: AbsolutePath) throws -> Triple {\n        try Self.getHostTriple(usingSwiftCompiler: swiftCompiler).versionedTriple\n    }\n\n    /// Determine the unversioned host triple using the Swift compiler.\n    public static func getUnversionedHostTriple(usingSwiftCompiler swiftCompiler: AbsolutePath) throws -> Triple {\n        try Self.getHostTriple(usingSwiftCompiler: swiftCompiler).unversionedTriple\n    }\n\n    public static func getHostTriple(usingSwiftCompiler swiftCompiler: AbsolutePath) throws -> (versionedTriple: Triple, unversionedTriple: Triple) {\n        // Call the compiler to get the target info JSON.\n        let compilerOutput: String\n        do {\n            let result = try AsyncProcess.popen(args: swiftCompiler.pathString, \"-print-target-info\")\n            compilerOutput = try result.utf8Output().spm_chomp()\n        } catch {\n            throw InternalError(\"Failed to get target info (\\(error.interpolationDescription))\")\n        }\n        // Parse the compiler's JSON output.\n        let parsedTargetInfo: JSON\n        do {\n            parsedTargetInfo = try JSON(string: compilerOutput)\n        } catch {\n            throw InternalError(\n                \"Failed to parse target info (\\(error.interpolationDescription)).\\nRaw compiler output: \\(compilerOutput)\"\n            )\n        }\n        // Get the triple string from the parsed JSON.\n        let versionedTripleString: String\n        let unversionedTripleString: String\n        do {\n            versionedTripleString = try parsedTargetInfo.get(\"target\").get(\"triple\")\n            unversionedTripleString = try parsedTargetInfo.get(\"target\").get(\"unversionedTriple\")\n        } catch {\n            throw InternalError(\n                \"Target info does not contain a triple string (\\(error.interpolationDescription)).\\nTarget info: \\(parsedTargetInfo)\"\n            )\n        }\n\n        // Parse the triple string.\n        do {\n            return try (Triple(versionedTripleString), Triple(unversionedTripleString))\n        } catch {\n            throw InternalError(\n                \"Failed to parse triple string (\\(error.interpolationDescription)).\\nVersioned triple string: \\(versionedTripleString), unversioned triple string \\(unversionedTripleString)\"\n            )\n        }\n    }\n}\n\nextension Triple {\n    /// The file prefix for dynamic libraries\n    public var dynamicLibraryPrefix: String {\n        switch os {\n        case .win32:\n            return \"\"\n        default:\n            return \"lib\"\n        }\n    }\n\n    /// The file extension for dynamic libraries (eg. `.dll`, `.so`, or `.dylib`)\n    public var dynamicLibraryExtension: String {\n        guard let os = self.os else {\n            fatalError(\"Cannot create dynamic libraries for unknown os.\")\n        }\n\n        switch os {\n        case _ where isDarwin():\n            return \".dylib\"\n        case .linux, .openbsd, .freebsd:\n            return \".so\"\n        case .win32:\n            return \".dll\"\n        case .wasi:\n            return \".wasm\"\n        default:\n          break\n        }\n\n        guard let objectFormat = self.objectFormat else {\n            fatalError(\"Cannot create dynamic libraries for unknown object format.\")\n        }\n\n        switch objectFormat {\n        case .coff:\n            return \".coff\"\n        case .elf:\n            return \".elf\"\n        case .macho:\n            return \".macho\"\n        case .wasm:\n            return \".wasm\"\n        case .xcoff:\n            return \".xcoff\"\n        }\n    }\n\n    public var executableExtension: String {\n        guard !self.isWasm else {\n            return \".wasm\"\n        }\n\n        guard let os = self.os else {\n            return \"\"\n        }\n\n        switch os {\n        case _ where isDarwin():\n            return \"\"\n        case .linux, .openbsd, .freebsd:\n            return \"\"\n        case .win32:\n            return \".exe\"\n        case .noneOS:\n            return \"\"\n        default:\n            return \"\"\n        }\n    }\n\n    /// The file extension for static libraries.\n    public var staticLibraryExtension: String {\n        \".a\"\n    }\n\n    /// The file extension for Foundation-style bundle.\n    public var nsbundleExtension: String {\n        switch os {\n        case _ where isDarwin():\n            return \".bundle\"\n        default:\n            return \".resources\"\n        }\n    }\n\n    /// Returns `true` if code compiled for `triple` can run on `self` value of ``Triple``.\n    public func isRuntimeCompatible(with triple: Triple) -> Bool {\n        guard self != triple else {\n            return true\n        }\n\n        if\n            self.arch == triple.arch &&\n            self.vendor == triple.vendor &&\n            self.os == triple.os &&\n            self.environment == triple.environment\n        {\n            return self.osVersion >= triple.osVersion\n        } else {\n            return false\n        }\n    }\n}\n\nextension Triple: CustomStringConvertible {\n    public var description: String { tripleString }\n}\n\nextension Triple: Equatable {\n    public static func ==(lhs: Triple, rhs: Triple) -> Bool {\n      lhs.arch == rhs.arch\n        && lhs.vendor == rhs.vendor\n        && lhs.os == rhs.os\n        && lhs.environment == rhs.environment\n        && lhs.osVersion == rhs.osVersion\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/URL.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\n\nextension URL {\n    /// Returns the path of the file URL.\n    ///\n    /// This should always be used whenever the file path equivalent of a URL is needed. DO NOT use ``path`` or ``path(percentEncoded:)``, as these deal in terms of the path portion of the URL representation per RFC8089, which on Windows would include a leading slash.\n    ///\n    /// - throws: ``FileURLError`` if the URL does not represent a file or its path is otherwise not representable.\n    public var filePath: AbsolutePath {\n        get throws {\n            guard isFileURL else {\n                throw FileURLError.notRepresentable(self)\n            }\n            return try withUnsafeFileSystemRepresentation { cString in\n                guard let cString else {\n                    throw FileURLError.notRepresentable(self)\n                }\n                return try AbsolutePath(validating: String(cString: cString))\n            }\n        }\n    }\n}\n\nfileprivate enum FileURLError: Error {\n    case notRepresentable(URL)\n}\n"
  },
  {
    "path": "Sources/Basics/Vendor/README.md",
    "content": "#  README\n\nThe Triple.swift and Triple+Platform.swift files in this directory have been\nvendored from SwiftDriver. The purpose of this approach is to avoid\nintroducing a dependency on Driver in the \"data model\" section of SwiftPM,\nwhich could currently lead to complications with the Xcode integration.\n\nIn the long term, our goal is to consolidate this code into a shared\nimplementation that can be utilized by both SwiftPM and SwiftDriver through a\npackage. However, until we reach that point, it is important to keep the files\nin this directory up to date by incorporating any relevant additions from the\noriginal copies.\n"
  },
  {
    "path": "Sources/Basics/Vendor/Triple+Platforms.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n//\n// Warning: This file has been copied with minimal modifications from\n// swift-driver to avoid a direct dependency. See Vendor/README.md for details.\n//\n// Changes:\n// - Replaced usage of `\\(_:or:)` string interpolation.\n// - Replaced usage of `self.isDarwin` with `self.os?.isDarwin ?? false`.\n//\n//===----------------------------------------------------------------------===//\n\n/// Represents any of the \"Apple\" platforms handled by `DarwinToolchain`.\n/// This boils down a lot of complicated logic about different variants and\n/// environments into a straightforward, tightly-modeled type that can be\n/// switched over.\n///\n/// `DarwinPlatform` does not contain version information, but\n/// `Triple.version(for:)` retrieves a version based on the\n/// corresponding `DarwinPlatform`.\npublic enum DarwinPlatform: Hashable {\n  /// macOS, corresponding to the `macosx`, `macos`, and `darwin` OS names.\n  case macOS\n\n  /// iOS, corresponding to the `ios` and `iphoneos` OS names. This does not\n  /// match tvOS.\n  case iOS(Environment)\n\n  /// tvOS, corresponding to the `tvos` OS name.\n  case tvOS(EnvironmentWithoutCatalyst)\n\n  /// watchOS, corresponding to the `watchos` OS name.\n  case watchOS(EnvironmentWithoutCatalyst)\n\n  /// The most general form of environment information attached to a\n  /// `DarwinPlatform`.\n  ///\n  /// The environment is a variant of the platform like `device` or `simulator`.\n  /// Not all platforms support all values of environment. This type is a superset of\n  /// all the environments available on any case.\n  public enum Environment: Hashable {\n    case device\n    case simulator\n    case catalyst\n\n    var withoutCatalyst: EnvironmentWithoutCatalyst? {\n      switch self {\n      case .device:\n        return .device\n      case .simulator:\n        return .simulator\n      case .catalyst:\n        return nil\n      }\n    }\n  }\n\n  public enum EnvironmentWithoutCatalyst: Hashable {\n    case device\n    case simulator\n  }\n\n  /// Returns the same platform, but with the environment replaced by\n  /// `environment`. Returns `nil` if `environment` is not valid\n  /// for `self`.\n  func with(_ environment: Environment) -> DarwinPlatform? {\n    switch self {\n    case .macOS:\n      guard environment == .device else { return nil }\n      return .macOS\n    case .iOS:\n      return .iOS(environment)\n    case .tvOS:\n      guard let withoutCatalyst = environment.withoutCatalyst else { return nil }\n      return .tvOS(withoutCatalyst)\n    case .watchOS:\n    guard let withoutCatalyst = environment.withoutCatalyst else { return nil }\n      return .watchOS(withoutCatalyst)\n    }\n  }\n\n  public var platformDisplayName: String {\n    switch self {\n    case .macOS:\n      return \"macOS\"\n    case .iOS(.device):\n      return \"iOS\"\n    case .iOS(.simulator):\n      return \"iOS Simulator\"\n    case .iOS(.catalyst):\n      return \"Mac Catalyst\"\n    case .tvOS(.device):\n      return \"tvOS\"\n    case .tvOS(.simulator):\n      return \"tvOS Simulator\"\n    case .watchOS(.device):\n      return \"watchOS\"\n    case .watchOS(.simulator):\n      return \"watchOS Simulator\"\n    }\n  }\n\n  /// The platform name, i.e. the name clang uses to identify this platform in its\n  /// resource directory.\n  public var platformName: String {\n    switch self {\n    case .macOS:\n      return \"macosx\"\n    case .iOS(.device):\n      return \"iphoneos\"\n    case .iOS(.simulator):\n      return \"iphonesimulator\"\n    case .iOS(.catalyst):\n      return \"maccatalyst\"\n    case .tvOS(.device):\n      return \"appletvos\"\n    case .tvOS(.simulator):\n      return \"appletvsimulator\"\n    case .watchOS(.device):\n      return \"watchos\"\n    case .watchOS(.simulator):\n      return \"watchsimulator\"\n    }\n  }\n\n  /// The name the linker uses to identify this platform.\n  public var linkerPlatformName: String {\n    switch self {\n    case .macOS:\n      return \"macos\"\n    case .iOS(.device):\n      return \"ios\"\n    case .iOS(.simulator):\n      return \"ios-simulator\"\n    case .iOS(.catalyst):\n      return \"mac-catalyst\"\n    case .tvOS(.device):\n      return \"tvos\"\n    case .tvOS(.simulator):\n      return \"tvos-simulator\"\n    case .watchOS(.device):\n      return \"watchos\"\n    case .watchOS(.simulator):\n      return \"watchos-simulator\"\n    }\n  }\n\n\n  /// The name used to identify this platform in compiler_rt file names.\n  public var libraryNameSuffix: String {\n    switch self {\n    case .macOS:\n      return \"osx\"\n    case .iOS(.device):\n      return \"ios\"\n    case .iOS(.simulator):\n      return \"iossim\"\n    case .iOS(.catalyst):\n      return \"osx\"\n    case .tvOS(.device):\n      return \"tvos\"\n    case .tvOS(.simulator):\n      return \"tvossim\"\n    case .watchOS(.device):\n      return \"watchos\"\n    case .watchOS(.simulator):\n      return \"watchossim\"\n    }\n  }\n}\n\nextension Triple {\n  /// If this is a Darwin device platform, should it be inferred to be a device simulator?\n  public var _isSimulatorEnvironment: Bool {\n    return environment == .simulator\n  }\n\n  /// Returns the OS version equivalent for the given platform, converting and\n  /// defaulting various representations.\n  ///\n  /// - Parameter compatibilityPlatform: Overrides the platform to be fetched.\n  ///   For compatibility reasons, you sometimes have to e.g. pass an argument with a macOS\n  ///   version number even when you're building watchOS code. This parameter specifies the\n  ///   platform you need a version number for; the method will then return an arbitrary but\n  ///   suitable version number for `compatibilityPlatform`.\n  ///\n  /// - Precondition: `self` must be able to provide a version for `compatibilityPlatform`.\n  ///   Not all combinations are valid; in particular, you cannot fetch a watchOS version\n  ///   from an iOS/tvOS triple or vice versa.\n  public func version(for compatibilityPlatform: DarwinPlatform? = nil)\n    -> Triple.Version\n  {\n    switch compatibilityPlatform ?? darwinPlatform! {\n    case .macOS:\n      return _macOSVersion ?? osVersion\n    case .iOS, .tvOS:\n      return _iOSVersion\n    case .watchOS:\n      return _watchOSVersion\n    }\n  }\n\n  /// Returns the `DarwinPlatform` for this triple, or `nil` if it is a non-Darwin\n  /// platform.\n  ///\n  /// - SeeAlso: DarwinPlatform\n  public var darwinPlatform: DarwinPlatform? {\n    func makeEnvironment() -> DarwinPlatform.EnvironmentWithoutCatalyst {\n      _isSimulatorEnvironment ? .simulator : .device\n    }\n    switch os {\n    case .darwin, .macosx:\n      return .macOS\n    case .ios:\n      if isMacCatalyst {\n        return .iOS(.catalyst)\n      } else if _isSimulatorEnvironment {\n        return .iOS(.simulator)\n      } else {\n        return .iOS(.device)\n      }\n    case .watchos:\n      return .watchOS(makeEnvironment())\n    case .tvos:\n      return .tvOS(makeEnvironment())\n    default:\n      return nil\n    }\n  }\n\n  // The Darwin platform version used for linking.\n  public var darwinLinkerPlatformVersion: Version {\n    precondition(self.os?.isDarwin ?? false)\n    switch darwinPlatform! {\n    case .macOS:\n      // The integrated driver falls back to `osVersion` for invalid macOS\n      // versions, this decision might be worth revisiting.\n      let macVersion = _macOSVersion ?? osVersion\n      // The first deployment of arm64 for macOS is version 11\n      if macVersion.major < 11 && arch == .aarch64 {\n        return Version(11, 0, 0)\n      }\n\n      return macVersion\n    case .iOS(.catalyst):\n      // Mac Catalyst on arm was introduced with an iOS deployment target of\n      // 14.0; the linker doesn't want to see a deployment target before that.\n      if _iOSVersion.major < 14 && arch == .aarch64 {\n        return Version(14, 0, 0)\n      }\n\n      // Mac Catalyst was introduced with an iOS deployment target of 13.1;\n      // the linker doesn't want to see a deployment target before that.\n      if _iOSVersion.major < 13 {\n        return Version(13, 1, 0)\n      }\n\n      return _iOSVersion\n    case .iOS(.device), .iOS(.simulator), .tvOS(_):\n      // The first deployment of arm64 simulators is iOS/tvOS 14.0;\n      // the linker doesn't want to see a deployment target before that.\n      if _isSimulatorEnvironment && _iOSVersion.major < 14 && arch == .aarch64 {\n        return Version(14, 0, 0)\n      }\n\n      return _iOSVersion\n    case .watchOS(_):\n      // The first deployment of arm64 simulators is watchOS 7;\n      // the linker doesn't want to see a deployment target before that.\n      if _isSimulatorEnvironment && osVersion.major < 7 && arch == .aarch64 {\n        return Version(7, 0, 0)\n      }\n\n      return osVersion\n    }\n  }\n\n  /// The platform name, i.e. the name clang uses to identify this target in its\n  /// resource directory.\n  ///\n  /// - Parameter conflatingDarwin: If true, all Darwin platforms will be\n  ///   identified as just `darwin` instead of by individual platform names.\n  ///   Defaults to `false`.\n  public func platformName(conflatingDarwin: Bool = false) -> String? {\n    switch os {\n    case nil:\n      fatalError(\"unknown OS\")\n    case .darwin, .macosx, .ios, .tvos, .watchos:\n      guard let darwinPlatform = darwinPlatform else {\n        fatalError(\"unsupported darwin platform kind?\")\n      }\n      return conflatingDarwin ? \"darwin\" : darwinPlatform.platformName\n\n    case .linux:\n      return environment == .android ? \"android\" : \"linux\"\n    case .freebsd:\n      return \"freebsd\"\n    case .openbsd:\n      return \"openbsd\"\n    case .win32:\n      switch environment {\n      case .cygnus:\n        return \"cygwin\"\n      case .gnu:\n        return \"mingw\"\n      case .msvc, .itanium:\n        return \"windows\"\n      default:\n        if let environment = environment {\n          fatalError(\"unsupported Windows environment: \\(environment)\")\n        } else {\n          fatalError(\"unsupported Windows environment: nil\")\n        }\n      }\n    case .ps4:\n      return \"ps4\"\n    case .haiku:\n      return \"haiku\"\n    case .wasi:\n      return \"wasi\"\n    case .noneOS:\n      return nil\n\n    // Explicitly spell out the remaining cases to force a compile error when\n    // Triple updates\n    case .ananas, .cloudABI, .dragonFly, .fuchsia, .kfreebsd, .lv2, .netbsd,\n         .solaris, .minix, .rtems, .nacl, .cnk, .aix, .cuda, .nvcl, .amdhsa,\n         .elfiamcu, .mesa3d, .contiki, .amdpal, .hermitcore, .hurd, .emscripten:\n      return nil\n    }\n  }\n}\n\nextension Triple {\n  /// Represents the availability of a feature that is supported on some platforms\n  /// and versions, but not all. For Darwin versions, the version numbers provided\n  /// should be the version where the feature was added or the change was\n  /// introduced, because all version checks are in the form of\n  /// `tripleVersion >= featureVersion`.\n  ///\n  /// - SeeAlso: `Triple.supports(_:)`\npublic struct FeatureAvailability: Sendable {\n\n    public enum Availability: Sendable {\n      case unavailable\n      case available(since: Version)\n      case availableInAllVersions\n    }\n\n    public let macOS: Availability\n    public let iOS: Availability\n    public let tvOS: Availability\n    public let watchOS: Availability\n\n    // TODO: We should have linux, windows, etc.\n    public let nonDarwin: Bool\n\n    /// Describes the availability of a feature that is supported on multiple platforms,\n    /// but is tied to a particular version.\n    public init(\n      macOS: Availability,\n      iOS: Availability,\n      tvOS: Availability,\n      watchOS: Availability,\n      nonDarwin: Bool = false\n    ) {\n      self.macOS = macOS\n      self.iOS = iOS\n      self.tvOS = tvOS\n      self.watchOS = watchOS\n      self.nonDarwin = nonDarwin\n    }\n\n    /// Returns the version when the feature was introduced on the specified Darwin\n    /// platform, or `.unavailable` if the feature has not been introduced there.\n    public subscript(darwinPlatform: DarwinPlatform) -> Availability {\n      switch darwinPlatform {\n      case .macOS:\n        return macOS\n      case .iOS:\n        return iOS\n      case .tvOS:\n        return tvOS\n      case .watchOS:\n        return watchOS\n      }\n    }\n  }\n\n  /// Checks whether the triple supports the specified feature, i.e., the feature\n  /// has been introduced by the OS and version indicated by the triple.\n  public func supports(_ feature: FeatureAvailability) -> Bool {\n    guard let darwinPlatform = darwinPlatform else {\n      return feature.nonDarwin\n    }\n\n    switch feature[darwinPlatform] {\n    case .unavailable:\n      return false\n    case .available(let introducedVersion):\n      return version(for: darwinPlatform) >= introducedVersion\n    case .availableInAllVersions:\n      return true\n    }\n  }\n}\n\nextension Triple.FeatureAvailability {\n  /// Linking `libarclite` is unnecessary for triples supporting this feature.\n  ///\n  /// This impacts the `-link-objc-runtime` flag in Swift, which is akin to the\n  /// `-fobjc-link-runtime` build setting in clang. When set, these flags\n  /// automatically link libobjc, and any compatibility libraries that don't\n  /// ship with the OS. The versions here are the first OSes that support\n  /// ARC natively in their respective copies of the Objective-C runtime,\n  /// and therefore do not require additional support libraries.\n  static let nativeARC = Self(\n    macOS: .available(since: Triple.Version(10, 11, 0)),\n    iOS: .available(since: Triple.Version(9, 0, 0)),\n    tvOS: .available(since: Triple.Version(9, 0, 0)),\n    watchOS: .availableInAllVersions\n  )\n  // When updating the versions listed here, please record the most recent\n  // feature being depended on and when it was introduced:\n  //\n  // - Make assigning 'nil' to an NSMutableDictionary subscript delete the\n  //   entry, like it does for Swift.Dictionary, rather than trap.\n}\n"
  },
  {
    "path": "Sources/Basics/Vendor/Triple.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n//\n// Warning: This file has been copied with minimal modifications from\n// swift-driver to avoid a direct dependency. See Vendor/README.md for details.\n//\n// Changes:\n// - Replaced usage of `\\(_:or:)` string interpolation.\n// - Replaced usage of `self.isDarwin` with `self.os?.isDarwin ?? false`.\n//\n//===----------------------------------------------------------------------===//\n\n/// Helper for working with target triples.\n///\n/// Target triples are strings in the canonical form:\n///   ARCHITECTURE-VENDOR-OPERATING_SYSTEM\n/// or\n///   ARCHITECTURE-VENDOR-OPERATING_SYSTEM-ENVIRONMENT\n///\n/// This type is used for clients which want to support arbitrary\n/// configuration names, but also want to implement certain special\n/// behavior for particular configurations. This class isolates the mapping\n/// from the components of the configuration name to well known IDs.\n///\n/// At its core the Triple class is designed to be a wrapper for a triple\n/// string; the constructor does not change or normalize the triple string.\n/// Clients that need to handle the non-canonical triples that users often\n/// specify should use the normalize method.\n///\n/// See autoconf/config.guess for a glimpse into what target triples\n/// look like in practice.\n///\n/// This is a port of https://github.com/apple/swift-llvm/blob/stable/include/llvm/ADT/Triple.h\n@dynamicMemberLookup\npublic struct Triple: Sendable {\n  /// `Triple` proxies predicates from `Triple.OS`, returning `false` for an unknown OS.\n  public subscript(dynamicMember predicate: KeyPath<OS, Bool>) -> Bool {\n    os?[keyPath: predicate] ?? false\n  }\n\n  /// The original triple string.\n  public let triple: String\n\n  /// The parsed arch.\n  public let arch: Arch?\n\n  /// The parsed subarchitecture.\n  public let subArch: SubArch?\n\n  /// The parsed vendor.\n  public let vendor: Vendor?\n\n  /// The parsed OS.\n  public let os: OS?\n\n  /// The parsed Environment type.\n  public let environment: Environment?\n\n  /// The object format type.\n  public let objectFormat: ObjectFormat?\n\n  /// Represents a version that may be present in the target triple.\n    public struct Version: Equatable, Comparable, CustomStringConvertible, Sendable {\n    public static let zero = Version(0, 0, 0)\n\n    public var major: Int\n    public var minor: Int\n    public var micro: Int\n\n    public init<S: StringProtocol>(parse string: S) {\n      let components = string.split(separator: \".\", maxSplits: 3).map{ Int($0) ?? 0 }\n      self.major = components.count > 0 ? components[0] : 0\n      self.minor = components.count > 1 ? components[1] : 0\n      self.micro = components.count > 2 ? components[2] : 0\n    }\n\n    public init(_ major: Int, _ minor: Int, _ micro: Int) {\n      self.major = major\n      self.minor = minor\n      self.micro = micro\n    }\n\n    public static func <(lhs: Version, rhs: Version) -> Bool {\n      return (lhs.major, lhs.minor, lhs.micro) < (rhs.major, rhs.minor, rhs.micro)\n    }\n\n    public var description: String {\n      return \"\\(major).\\(minor).\\(micro)\"\n    }\n  }\n\n  public init(_ string: String, normalizing: Bool = false) {\n    var parser = TripleParser(string, allowMore: normalizing)\n\n    // First, see if each component parses at its expected position.\n    var parsedArch = parser.match(ArchInfo.self, at: 0)\n    var parsedVendor = parser.match(Vendor.self, at: 1)\n    var parsedOS = parser.match(OS.self, at: 2)\n    var parsedEnv = parser.match(EnvInfo.self, at: 3)\n\n    if normalizing {\n      // Next, try to fill in each unmatched field from the rejected components.\n      parser.rematch(&parsedArch, at: 0)\n      parser.rematch(&parsedVendor, at: 1)\n      parser.rematch(&parsedOS, at: 2)\n      parser.rematch(&parsedEnv, at: 3)\n\n      let isCygwin = parser.componentsIndicateCygwin\n      let isMinGW32 = parser.componentsIndicateMinGW32\n\n      if\n      let parsedEnv = parsedEnv,\n      parsedEnv.value.environment == .android,\n      parsedEnv.substring.hasPrefix(\"androideabi\") {\n        let androidVersion = parsedEnv.substring.dropFirst(\"androideabi\".count)\n\n        parser.components[3] = \"android\\(androidVersion)\"\n      }\n\n      // SUSE uses \"gnueabi\" to mean \"gnueabihf\"\n      if parsedVendor?.value == .suse && parsedEnv?.value.environment == .gnueabi {\n        parser.components[3] = \"gnueabihf\"\n      }\n\n      if parsedOS?.value == .win32 {\n        parser.components.resize(toCount: 4, paddingWith: \"\")\n        parser.components[2] = \"windows\"\n        if parsedEnv?.value.environment == nil {\n          if let objectFormat = parsedEnv?.value.objectFormat, objectFormat != .coff {\n            parser.components[3] = Substring(objectFormat.name)\n          } else {\n            parser.components[3] = \"msvc\"\n          }\n        }\n      } else if isMinGW32 {\n        parser.components.resize(toCount: 4, paddingWith: \"\")\n        parser.components[2] = \"windows\"\n        parser.components[3] = \"gnu\"\n      } else if isCygwin {\n        parser.components.resize(toCount: 4, paddingWith: \"\")\n        parser.components[2] = \"windows\"\n        parser.components[3] = \"cygnus\"\n      }\n\n      if isMinGW32 || isCygwin || (parsedOS?.value == .win32 && parsedEnv?.value.environment != nil) {\n        if let objectFormat = parsedEnv?.value.objectFormat, objectFormat != .coff {\n          parser.components.resize(toCount: 5, paddingWith: \"\")\n          parser.components[4] = Substring(objectFormat.name)\n        }\n      }\n\n      // Now that we've parsed everything, we construct a normalized form of the\n      // triple string.\n      triple = parser.components.map({ $0.isEmpty ? \"unknown\" : $0 }).joined(separator: \"-\")\n    }\n    else {\n      triple = string\n    }\n\n    // Unpack the parsed data into the fields. If no environment info was found,\n    // attempt to infer it from other fields.\n    self.arch = parsedArch?.value.arch\n    self.subArch = parsedArch?.value.subArch\n    self.vendor = parsedVendor?.value\n    self.os = parsedOS?.value\n\n    if let parsedEnv = parsedEnv {\n      self.environment = parsedEnv.value.environment\n      self.objectFormat = parsedEnv.value.objectFormat\n        ?? ObjectFormat.infer(arch: parsedArch?.value.arch,\n                              os: parsedOS?.value)\n    }\n    else {\n      self.environment = Environment.infer(archName: parsedArch?.substring)\n      self.objectFormat = ObjectFormat.infer(arch: parsedArch?.value.arch,\n                                             os: parsedOS?.value)\n    }\n  }\n}\n\nextension Triple: Codable {\n  public init(from decoder: Decoder) throws {\n    self.init(try decoder.singleValueContainer().decode(String.self), normalizing: false)\n  }\n\n  public func encode(to encoder: Encoder) throws {\n    var container = encoder.singleValueContainer()\n    try container.encode(triple)\n  }\n}\n\n// MARK: - Triple component parsing\n\nfileprivate protocol TripleComponent {\n  static func parse(_ component: Substring) -> Self?\n\n  static func valueIsValid(_ value: Substring) -> Bool\n}\n\nextension TripleComponent {\n  static func valueIsValid(_ value: Substring) -> Bool {\n    parse(value) != nil\n  }\n}\n\nfileprivate struct ParsedComponent<Value: TripleComponent> {\n  let value: Value\n  let substring: Substring\n\n  /// Attempts to parse `component` with `parser`, placing it in `rejects` if\n  /// it does not succeed.\n  ///\n  /// - Returns: `nil` if `type` cannot parse `component`; otherwise, an\n  ///   instance containing the component and its parsed value.\n  init?(_ component: Substring, as type: Value.Type) {\n    guard let value = type.parse(component) else {\n      return nil\n    }\n\n    self.value = value\n    self.substring = component\n  }\n}\n\n/// Holds the list of components in this string, as well as whether or not we\n/// have matched them.\n///\n/// In normalizing mode, the triple is parsed in two steps:\n///\n/// 1. Try to match each component against the type of component expected in\n///    that position. (`TripleParser.match(_:at:)`.)\n/// 2. For each type of component we have not yet matched, try each component\n///    we have not yet found a match for, moving the match (if found) to the\n///    correct location. (`TripleParser.rematch(_:at:)`.)\n///\n/// In non-normalizing mode, we simply skip the second step.\nfileprivate struct TripleParser {\n  var components: [Substring]\n  var isMatched: Set<Int> = []\n\n  var componentsIndicateCygwin: Bool {\n    components.count > 2 ? components[2].hasPrefix(\"cygwin\") : false\n  }\n\n  var componentsIndicateMinGW32: Bool {\n    components.count > 2 ? components[2].hasPrefix(\"mingw\") : false\n  }\n\n  init(_ string: String, allowMore: Bool) {\n    components = string.split(\n      separator: \"-\", maxSplits: allowMore ? Int.max : 3,\n      omittingEmptySubsequences: false\n    )\n  }\n\n  /// Attempt to parse the component at position `i` as a `Value`, marking it as\n  /// matched if successful.\n  mutating func match<Value: TripleComponent>(_: Value.Type, at i: Int)\n    -> ParsedComponent<Value>?\n  {\n    guard\n      i < components.endIndex,\n      let parsed = ParsedComponent(components[i], as: Value.self)\n    else {\n      return nil\n    }\n\n    precondition(!isMatched.contains(i))\n    isMatched.insert(i)\n\n    return parsed\n  }\n\n  /// If `value` has not been filled in, attempt to parse all unmatched\n  /// components with it, correcting the components list if a match is found.\n  mutating func rematch<Value: TripleComponent>(\n    _ value: inout ParsedComponent<Value>?, at correctIndex: Int\n  ) {\n    guard value == nil else { return }\n\n    precondition(!isMatched.contains(correctIndex),\n                 \"Lost the parsed component somehow?\")\n\n    for i in unmatchedIndices {\n      guard Value.valueIsValid(components[i]) else {\n        continue\n      }\n\n      value = ParsedComponent(components[i], as: Value.self)\n      shiftComponent(at: i, to: correctIndex)\n      isMatched.insert(correctIndex)\n\n      return\n    }\n  }\n\n  /// Returns `component.indices` with matched elements lazily filtered out.\n  private var unmatchedIndices: LazyFilterSequence<Range<Int>> {\n    components.indices.lazy.filter { [isMatched] in\n      !isMatched.contains($0)\n    }\n  }\n\n  /// Rearrange `components` so that the element at `actualIndex` now appears\n  /// at `correctIndex`, without moving any components that have already\n  /// matched.\n  ///\n  /// The exact transformations performed by this function are difficult to\n  /// describe concisely, but they work well in practice for the ways people\n  /// tend to permute triples. Essentially:\n  ///\n  /// * If a component appears later than it ought to, it is moved to the right\n  ///   location and other unmatched components are shifted later.\n  /// * If a component appears earlier than it ought to, empty components are\n  ///   either found later in the list and moved before it, or created from\n  ///   whole cloth and inserted before it.\n  /// * If no movement is necessary, this is a no-op.\n  ///\n  /// - Parameter actualIndex: The index that the component is currently at.\n  /// - Parameter correctIndex: The index that the component ought to be at.\n  ///\n  /// - Precondition: Neither `correctIndex` nor `actualIndex` are matched.\n  private mutating func shiftComponent(\n    at actualIndex: Int,\n    to correctIndex: Int\n  ) {\n    // Don't mark actualIndex as matched until after you've called this method.\n    precondition(!isMatched.contains(actualIndex),\n                 \"actualIndex was already matched to something else?\")\n    precondition(!isMatched.contains(correctIndex),\n                 \"correctIndex already had something match it?\")\n\n    if correctIndex < actualIndex {\n      // Repeatedly swap `actualIndex` with its leftward neighbor, skipping\n      // matched components, until it finds its way to `correctIndex`.\n\n      // Compute all of the indices that we'll shift, not including any that\n      // have matched, and then build a reversed list of adjacent pairs. (That\n      // is, if the filter returns `[1,2,4]`, the resulting list will be\n      // `[(4,2),(2,1)]`.)\n      let swaps = unmatchedIndices[correctIndex...actualIndex]\n          .zippedPairs().reversed()\n\n      // Swap each pair. This has the effect of moving `actualIndex` to\n      // `correctIndex` and shifting each unmatched element between them to\n      // take up the space. Swapping instead of assigning ought to avoid retain\n      // count traffic.\n      for (earlier, later) in swaps {\n        components.swapAt(earlier, later)\n      }\n    }\n\n    // The rest of this method is concerned with shifting components rightward.\n    // If we don't need to do that, we're done.\n    guard correctIndex > actualIndex else { return }\n\n    // We will essentially insert one empty component in front of `actualIndex`,\n    // then recurse to shift `actualIndex + 1` if necessary. However, we want to\n    // avoid shifting matched components and eat empty components, so this is\n    // all a bit more complicated than just that.\n\n    // Create a new empty component. We call it `removed` because for most\n    // of this variable's lifetime, `removed` is a component that has been\n    // removed from the list.\n    var removed: Substring = \"\"\n\n    // This loop has the effect of inserting the empty component and\n    // shifting other unmatched components rightward until we either remove\n    // an empty unmatched component, or remove the last element of the list.\n    for i in unmatchedIndices[actualIndex...] {\n      swap(&removed, &components[i])\n\n      // If the element we removed is empty, consume it rather than reinserting\n      // it later in the list.\n      if removed.isEmpty { break }\n    }\n\n    // If we shifted a non-empty component off the end, add it back in.\n    if !removed.isEmpty {\n      components.append(removed)\n    }\n\n    // Find the next unmatched index after `actualIndex`; that's where we moved\n    // the element at `actualIndex` to.\n    let nextIndex = unmatchedIndices[(actualIndex + 1)..<correctIndex].first ??\n        correctIndex\n\n    // Recurse to move or create another empty component if necessary.\n    shiftComponent(at: nextIndex, to: correctIndex)\n  }\n}\n\nextension Collection {\n  fileprivate func zippedPairs() -> Zip2Sequence<SubSequence, SubSequence> {\n    zip(dropLast(), dropFirst())\n  }\n}\n\n// MARK: - Parse Arch\n\nextension Triple {\n  fileprivate struct ArchInfo: TripleComponent {\n    var arch: Triple.Arch\n    var subArch: Triple.SubArch?\n\n    fileprivate static func parse(_ component: Substring) -> ArchInfo? {\n      // This code assumes that all architectures with a subarch also have an arch.\n      // This is slightly different from llvm::Triple, whose\n      // startswith/endswith-based logic might occasionally recognize a subarch\n      // without an arch, e.g. \"xxkalimba5\" would have an unknown arch and a\n      // kalimbav5 subarch. I'm pretty sure that's undesired behavior from LLVM.\n\n      guard let arch = Triple.Arch.parse(component) else { return nil }\n      return ArchInfo(arch: arch, subArch: Triple.SubArch.parse(component))\n    }\n  }\n\npublic enum Arch: String, CaseIterable, Decodable, Sendable {\n    /// ARM (little endian): arm, armv.*, xscale\n    case arm\n    // ARM (big endian): armeb\n    case armeb\n    /// AArch64 (little endian): aarch64\n    case aarch64\n    /// AArch64e (little endian): aarch64e\n    case aarch64e\n    /// AArch64 (big endian): aarch64_be\n    case aarch64_be\n    // AArch64 (little endian) ILP32: aarch64_32\n    case aarch64_32\n    /// ARC: Synopsis ARC\n    case arc\n    /// AVR: Atmel AVR microcontroller\n    case avr\n    /// eBPF or extended BPF or 64-bit BPF (little endian)\n    case bpfel\n    /// eBPF or extended BPF or 64-bit BPF (big endian)\n    case bpfeb\n    /// Hexagon: hexagon\n    case hexagon\n    /// MIPS: mips, mipsallegrex, mipsr6\n    case mips\n    /// MIPSEL: mipsel, mipsallegrexe, mipsr6el\n    case mipsel\n    // MIPS64: mips64, mips64r6, mipsn32, mipsn32r6\n    case mips64\n    // MIPS64EL: mips64el, mips64r6el, mipsn32el, mipsn32r6el\n    case mips64el\n    // MSP430: msp430\n    case msp430\n    // PPC: powerpc\n    case ppc\n    // PPC64: powerpc64, ppu\n    case ppc64\n    // PPC64LE: powerpc64le\n    case ppc64le\n    // R600: AMD GPUs HD2XXX - HD6XXX\n    case r600\n    // AMDGCN: AMD GCN GPUs\n    case amdgcn\n    // RISC-V (32-bit): riscv32\n    case riscv32\n    // RISC-V (64-bit): riscv64\n    case riscv64\n    // Sparc: sparc\n    case sparc\n    // Sparcv9: Sparcv9\n    case sparcv9\n    // Sparc: (endianness = little). NB: 'Sparcle' is a CPU variant\n    case sparcel\n    // SystemZ: s390x\n    case systemz\n    // TCE (http://tce.cs.tut.fi/): tce\n    case tce\n    // TCE little endian (http://tce.cs.tut.fi/): tcele\n    case tcele\n    // Thumb (little endian): thumb, thumbv.*\n    case thumb\n    // Thumb (big endian): thumbeb\n    case thumbeb\n    // X86: i[3-9]86\n    case x86 = \"i386\"\n    // X86-64: amd64, x86_64\n    case x86_64\n    // XCore: xcore\n    case xcore\n    // NVPTX: 32-bit\n    case nvptx\n    // NVPTX: 64-bit\n    case nvptx64\n    // le32: generic little-endian 32-bit CPU (PNaCl)\n    case le32\n    // le64: generic little-endian 64-bit CPU (PNaCl)\n    case le64\n    // AMDIL\n    case amdil\n    // AMDIL with 64-bit pointers\n    case amdil64\n    // AMD HSAIL\n    case hsail\n    // AMD HSAIL with 64-bit pointers\n    case hsail64\n    // SPIR: standard portable IR for OpenCL 32-bit version\n    case spir\n    // SPIR: standard portable IR for OpenCL 64-bit version\n    case spir64\n    // Kalimba: generic kalimba\n    case kalimba\n    // SHAVE: Movidius vector VLIW processors\n    case shave\n    // Lanai: Lanai 32-bit\n    case lanai\n    // WebAssembly with 32-bit pointers\n    case wasm32\n    // WebAssembly with 64-bit pointers\n    case wasm64\n    // 32-bit RenderScript\n    case renderscript32\n    // 64-bit RenderScript\n    case renderscript64\n\n    static func parse(_ archName: Substring) -> Triple.Arch? {\n      switch archName {\n      case \"i386\", \"i486\", \"i586\", \"i686\":\n        return .x86\n      case \"i786\", \"i886\", \"i986\":\n        return .x86\n      case \"amd64\", \"x86_64\", \"x86_64h\":\n        return .x86_64\n      case \"powerpc\", \"ppc\", \"ppc32\":\n        return .ppc\n      case \"powerpc64\", \"ppu\", \"ppc64\":\n        return .ppc64\n      case \"powerpc64le\", \"ppc64le\":\n        return .ppc64le\n      case \"xscale\":\n        return .arm\n      case \"xscaleeb\":\n        return .armeb\n      case \"aarch64\":\n        return .aarch64\n      case \"aarch64_be\":\n        return .aarch64_be\n      case \"aarch64_32\":\n        return .aarch64_32\n      case \"arc\":\n        return .arc\n      case \"arm64\":\n        return .aarch64\n      case \"arm64e\":\n        return .aarch64e\n      case \"arm64_32\":\n        return .aarch64_32\n      case \"arm\":\n        return .arm\n      case \"armeb\":\n        return .armeb\n      case \"thumb\":\n        return .thumb\n      case \"thumbeb\":\n        return .thumbeb\n      case \"avr\":\n        return .avr\n      case \"msp430\":\n        return .msp430\n      case \"mips\", \"mipseb\", \"mipsallegrex\", \"mipsisa32r6\", \"mipsr6\":\n        return .mips\n      case \"mipsel\", \"mipsallegrexel\", \"mipsisa32r6el\", \"mipsr6el\":\n        return .mipsel\n      case \"mips64\", \"mips64eb\", \"mipsn32\", \"mipsisa64r6\", \"mips64r6\", \"mipsn32r6\":\n        return .mips64\n      case \"mips64el\", \"mipsn32el\", \"mipsisa64r6el\", \"mips64r6el\", \"mipsn32r6el\":\n        return .mips64el\n      case \"r600\":\n        return .r600\n      case \"amdgcn\":\n        return .amdgcn\n      case \"riscv32\":\n        return .riscv32\n      case \"riscv64\":\n        return .riscv64\n      case \"hexagon\":\n        return .hexagon\n      case \"s390x\", \"systemz\":\n        return .systemz\n      case \"sparc\":\n        return .sparc\n      case \"sparcel\":\n        return .sparcel\n      case \"sparcv9\", \"sparc64\":\n        return .sparcv9\n      case \"tce\":\n        return .tce\n      case \"tcele\":\n        return .tcele\n      case \"xcore\":\n        return .xcore\n      case \"nvptx\":\n        return .nvptx\n      case \"nvptx64\":\n        return .nvptx64\n      case \"le32\":\n        return .le32\n      case \"le64\":\n        return .le64\n      case \"amdil\":\n        return .amdil\n      case \"amdil64\":\n        return .amdil64\n      case \"hsail\":\n        return .hsail\n      case \"hsail64\":\n        return .hsail64\n      case \"spir\":\n        return .spir\n      case \"spir64\":\n        return .spir64\n      case _ where archName.hasPrefix(\"kalimba\"):\n        return .kalimba\n      case \"lanai\":\n        return .lanai\n      case \"shave\":\n        return .shave\n      case \"wasm32\":\n        return .wasm32\n      case \"wasm64\":\n        return .wasm64\n      case \"renderscript32\":\n        return .renderscript32\n      case \"renderscript64\":\n        return .renderscript64\n\n      case _ where archName.hasPrefix(\"arm\") || archName.hasPrefix(\"thumb\") || archName.hasPrefix(\"aarch64\"):\n        return parseARMArch(archName)\n\n      case _ where archName.hasPrefix(\"bpf\"):\n        return parseBPFArch(archName)\n\n      default:\n        return nil\n      }\n    }\n\n    enum Endianness {\n      case big, little\n\n      // Based on LLVM's ARM::parseArchEndian\n      init?<S: StringProtocol>(armArchName archName: S) {\n        if archName.starts(with: \"armeb\") || archName.starts(with: \"thumbeb\") || archName.starts(with: \"aarch64_be\") {\n          self = .big\n        } else if archName.starts(with: \"arm\") || archName.starts(with: \"thumb\") {\n          self = archName.hasSuffix(\"eb\") ? .big : .little\n        } else if archName.starts(with: \"aarch64\") || archName.starts(with: \"aarch64_32\") {\n          self = .little\n        } else {\n          return nil\n        }\n      }\n    }\n\n    enum ARMISA {\n      case aarch64, thumb, arm\n\n      // Based on LLVM's ARM::parseArchISA\n      init?<S: StringProtocol>(archName: S) {\n        if archName.starts(with: \"aarch64\") || archName.starts(with: \"arm64\") {\n          self = .aarch64\n        } else if archName.starts(with: \"thumb\") {\n          self = .thumb\n        } else if archName.starts(with: \"arm\") {\n          self = .arm\n        } else {\n          return nil\n        }\n      }\n    }\n\n    // Parse ARM architectures not handled by `parse`. On its own, this is not\n    // enough to correctly parse an ARM architecture.\n    private static func parseARMArch<S: StringProtocol>(_ archName: S) -> Triple.Arch? {\n\n      let ISA = ARMISA(archName: archName)\n      let endianness = Endianness(armArchName: archName)\n\n      let arch: Triple.Arch?\n      switch (endianness, ISA) {\n      case (.little, .arm):\n        arch = .arm\n      case (.little, .thumb):\n        arch = .thumb\n      case (.little, .aarch64):\n        arch = .aarch64\n      case (.big, .arm):\n        arch = .armeb\n      case (.big, .thumb):\n        arch = .thumbeb\n      case (.big, .aarch64):\n        arch = .aarch64_be\n      case (nil, _), (_, nil):\n        arch = nil\n      }\n\n      let cannonicalArchName = cannonicalARMArchName(from: archName)\n\n      if cannonicalArchName.isEmpty {\n        return nil\n      }\n\n      // Thumb only exists in v4+\n      if ISA == .thumb && (cannonicalArchName.hasPrefix(\"v2\") || cannonicalArchName.hasPrefix(\"v3\")) {\n          return nil\n      }\n\n      // Thumb only for v6m\n      if case .arm(let subArch) = Triple.SubArch.parse(archName), subArch.profile == .m && subArch.version == 6 {\n        if endianness == .big {\n          return .thumbeb\n        } else {\n          return .thumb\n        }\n      }\n\n      return arch\n    }\n\n    // Based on LLVM's ARM::getCanonicalArchName\n    //\n    // MArch is expected to be of the form (arm|thumb)?(eb)?(v.+)?(eb)?, but\n    // (iwmmxt|xscale)(eb)? is also permitted. If the former, return\n    // \"v.+\", if the latter, return unmodified string, minus 'eb'.\n    // If invalid, return empty string.\n    fileprivate static func cannonicalARMArchName<S: StringProtocol>(from arch: S) -> String {\n      var name = Substring(arch)\n\n      func dropPrefix(_ prefix: String) {\n        if name.hasPrefix(prefix) {\n          name = name.dropFirst(prefix.count)\n        }\n      }\n\n      let possiblePrefixes = [\"arm64_32\", \"arm64\", \"aarch64_32\", \"arm\", \"thumb\", \"aarch64\"]\n\n      if let prefix = possiblePrefixes.first(where: name.hasPrefix) {\n        dropPrefix(prefix)\n\n        if prefix == \"aarch64\" {\n          // AArch64 uses \"_be\", not \"eb\" suffix.\n          if name.contains(\"eb\") {\n            return \"\"\n          }\n\n          dropPrefix(\"_be\")\n        }\n      }\n\n      // Ex. \"armebv7\", move past the \"eb\".\n      if name != arch {\n        dropPrefix(\"eb\")\n      }\n      // Or, if it ends with eb (\"armv7eb\"), chop it off.\n      else if name.hasSuffix(\"eb\") {\n        name = name.dropLast(2)\n      }\n\n      // Reached the end - arch is valid.\n      if name.isEmpty {\n        return String(arch)\n      }\n\n      // Only match non-marketing names\n      if name != arch {\n        // Must start with 'vN'.\n        if name.count >= 2 && (name.first != \"v\" || !name.dropFirst().first!.isNumber) {\n          return \"\"\n        }\n\n        // Can't have an extra 'eb'.\n        if name.hasPrefix(\"eb\") {\n          return \"\"\n        }\n      }\n\n      // Arch will either be a 'v' name (v7a) or a marketing name (xscale).\n      return String(name)\n    }\n\n    private static func parseBPFArch<S: StringProtocol>(_ archName: S) -> Triple.Arch? {\n\n      let isLittleEndianHost = 1.littleEndian == 1\n\n      switch archName {\n      case \"bpf\":\n        return isLittleEndianHost ? .bpfel : .bpfeb\n      case \"bpf_be\", \"bpfeb\":\n        return .bpfeb\n      case \"bpf_le\", \"bpfel\":\n        return .bpfel\n      default:\n        return nil\n      }\n    }\n\n    /// Whether or not this architecture has 64-bit pointers\n    public var is64Bit: Bool { pointerBitWidth == 64 }\n\n    /// Whether or not this architecture has 32-bit pointers\n    public var is32Bit: Bool { pointerBitWidth == 32 }\n\n    /// Whether or not this architecture has 16-bit pointers\n    public var is16Bit: Bool { pointerBitWidth == 16 }\n\n    /// The width in bits of pointers on this architecture.\n    var pointerBitWidth: Int {\n      switch self {\n      case .avr, .msp430:\n        return 16\n\n      case .arc, .arm, .armeb, .hexagon, .le32, .mips, .mipsel, .nvptx,\n           .ppc, .r600, .riscv32, .sparc, .sparcel, .tce, .tcele, .thumb,\n           .thumbeb, .x86, .xcore, .amdil, .hsail, .spir, .kalimba,.lanai,\n           .shave, .wasm32, .renderscript32, .aarch64_32:\n        return 32\n\n      case .aarch64, .aarch64e, .aarch64_be, .amdgcn, .bpfel, .bpfeb, .le64, .mips64,\n           .mips64el, .nvptx64, .ppc64, .ppc64le, .riscv64, .sparcv9, .systemz,\n           .x86_64, .amdil64, .hsail64, .spir64,  .wasm64, .renderscript64:\n        return 64\n      }\n    }\n  }\n}\n\n// MARK: - Parse SubArch\n\nextension Triple {\n    public enum SubArch: Hashable, Sendable {\n\n    public enum ARM: Sendable {\n\n      public enum Profile {\n        case a, r, m\n      }\n\n      case v2\n      case v2a\n      case v3\n      case v3m\n      case v4\n      case v4t\n      case v5\n      case v5e\n      case v6\n      case v6k\n      case v6kz\n      case v6m\n      case v6t2\n      case v7\n      case v7em\n      case v7k\n      case v7m\n      case v7r\n      case v7s\n      case v7ve\n      case v8\n      case v8_1a\n      case v8_1m_mainline\n      case v8_2a\n      case v8_3a\n      case v8_4a\n      case v8_5a\n      case v8m_baseline\n      case v8m_mainline\n      case v8r\n\n      var profile: Triple.SubArch.ARM.Profile? {\n        switch self {\n        case .v6m, .v7m, .v7em, .v8m_mainline, .v8m_baseline, .v8_1m_mainline:\n          return .m\n        case .v7r, .v8r:\n          return .r\n        case .v7, .v7ve, .v7k, .v8, .v8_1a, .v8_2a, .v8_3a, .v8_4a, .v8_5a:\n          return .a\n        case .v2, .v2a, .v3, .v3m, .v4, .v4t, .v5, .v5e, .v6, .v6k, .v6kz, .v6t2, .v7s:\n          return nil\n        }\n      }\n\n      var version: Int {\n        switch self {\n        case .v2, .v2a:\n          return 2\n        case .v3, .v3m:\n          return 3\n        case .v4, .v4t:\n          return 4\n        case .v5, .v5e:\n          return 5\n        case .v6, .v6k, .v6kz, .v6m, .v6t2:\n          return 6\n        case .v7, .v7em, .v7k, .v7m, .v7r, .v7s, .v7ve:\n          return 7\n        case .v8, .v8_1a, .v8_1m_mainline, .v8_2a, .v8_3a, .v8_4a, .v8_5a, .v8m_baseline, .v8m_mainline, .v8r:\n          return 8\n        }\n      }\n    }\n\n    public enum Kalimba: Sendable {\n      case v3\n      case v4\n      case v5\n    }\n\n    public enum MIPS: Sendable {\n      case r6\n    }\n\n    case arm(ARM)\n    case kalimba(Kalimba)\n    case mips(MIPS)\n\n    fileprivate static func parse<S: StringProtocol>(_ component: S) -> Triple.SubArch? {\n\n      if component.hasPrefix(\"mips\") && (component.hasSuffix(\"r6el\") || component.hasSuffix(\"r6\")) {\n        return .mips(.r6)\n      }\n\n      let armSubArch = Triple.Arch.cannonicalARMArchName(from: component)\n\n      if armSubArch.isEmpty {\n        switch component {\n        case _ where component.hasSuffix(\"kalimba3\"):\n          return .kalimba(.v3)\n        case _ where component.hasSuffix(\"kalimba4\"):\n          return .kalimba(.v4)\n        case _ where component.hasSuffix(\"kalimba5\"):\n          return .kalimba(.v5)\n        default:\n          return nil\n        }\n      }\n\n      switch armSubArch {\n      case \"v2\":\n        return .arm(.v2)\n      case \"v2a\":\n        return .arm(.v2a)\n      case \"v3\":\n        return .arm(.v3)\n      case \"v3m\":\n        return .arm(.v3m)\n      case \"v4\":\n        return .arm(.v4)\n      case \"v4t\":\n        return .arm(.v4t)\n      case \"v5t\":\n        return .arm(.v5)\n      case \"v5te\", \"v5tej\", \"xscale\":\n        return .arm(.v5e)\n      case \"v6\":\n        return .arm(.v6)\n      case \"v6k\":\n        return .arm(.v6k)\n      case \"v6kz\":\n        return .arm(.v6kz)\n      case \"v6m\", \"v6-m\":\n        return .arm(.v6m)\n      case \"v6t2\":\n        return .arm(.v6t2)\n      case \"v7a\", \"v7-a\":\n        return .arm(.v7)\n      case \"v7k\":\n        return .arm(.v7k)\n      case \"v7m\", \"v7-m\":\n        return .arm(.v7m)\n      case \"v7em\", \"v7e-m\":\n        return .arm(.v7em)\n      case \"v7r\", \"v7-r\":\n        return .arm(.v7r)\n      case \"v7s\":\n        return .arm(.v7s)\n      case \"v7ve\":\n        return .arm(.v7ve)\n      case \"v8-a\":\n        return .arm(.v8)\n      case \"v8-m.main\":\n        return .arm(.v8m_mainline)\n      case \"v8-m.base\":\n        return .arm(.v8m_baseline)\n      case \"v8-r\":\n        return .arm(.v8r)\n      case \"v8.1-m.main\":\n        return .arm(.v8_1m_mainline)\n      case \"v8.1-a\":\n        return .arm(.v8_1a)\n      case \"v8.2-a\":\n        return .arm(.v8_2a)\n      case \"v8.3-a\":\n        return .arm(.v8_3a)\n      case \"v8.4-a\":\n        return .arm(.v8_4a)\n      case \"v8.5-a\":\n        return .arm(.v8_5a)\n      default:\n        return nil\n      }\n    }\n  }\n}\n\n// MARK: - Parse Vendor\n\nextension Triple {\n    public enum Vendor: String, CaseIterable, TripleComponent, Sendable {\n    case apple\n    case pc\n    case scei\n    case bgp\n    case bgq\n    case freescale = \"fsl\"\n    case ibm\n    case imaginationTechnologies = \"img\"\n    case mipsTechnologies = \"mti\"\n    case nvidia\n    case csr\n    case myriad\n    case amd\n    case mesa\n    case suse\n    case openEmbedded = \"oe\"\n\n    fileprivate static func parse(_ component: Substring) -> Triple.Vendor? {\n      switch component {\n      case \"apple\":\n        return .apple\n      case \"pc\":\n        return .pc\n      case \"scei\":\n        return .scei\n      case \"bgp\":\n        return .bgp\n      case \"bgq\":\n        return .bgq\n      case \"fsl\":\n        return .freescale\n      case \"ibm\":\n        return .ibm\n      case \"img\":\n        return .imaginationTechnologies\n      case \"mti\":\n        return .mipsTechnologies\n      case \"nvidia\":\n        return .nvidia\n      case \"csr\":\n        return .csr\n      case \"myriad\":\n        return .myriad\n      case \"amd\":\n        return .amd\n      case \"mesa\":\n        return .mesa\n      case \"suse\":\n        return .suse\n      case \"oe\":\n        return .openEmbedded\n      default:\n        return nil\n      }\n    }\n  }\n}\n\n// MARK: - Parse OS\n\nextension Triple {\n  public enum OS: String, CaseIterable, TripleComponent, Sendable {\n    case ananas\n    case cloudABI = \"cloudabi\"\n    case darwin\n    case dragonFly = \"dragonfly\"\n    case freebsd = \"freebsd\"\n    case fuchsia\n    case ios\n    case kfreebsd\n    case linux\n    case lv2\n    case macosx\n    case netbsd\n    case openbsd\n    case solaris\n    case win32\n    case haiku\n    case minix\n    case rtems\n    case nacl\n    case cnk\n    case aix\n    case cuda\n    case nvcl\n    case amdhsa\n    case ps4\n    case elfiamcu\n    case tvos\n    case watchos\n    case mesa3d\n    case contiki\n    case amdpal\n    case hermitcore\n    case hurd\n    case wasi\n    case emscripten\n    case noneOS // 'OS' suffix purely to avoid name clash with Optional.none\n\n    var name: String {\n      return rawValue\n    }\n\n    fileprivate static func parse(_ os: Substring) -> Triple.OS? {\n      switch os {\n      case _ where os.hasPrefix(\"ananas\"):\n        return .ananas\n      case _ where os.hasPrefix(\"cloudabi\"):\n        return .cloudABI\n      case _ where os.hasPrefix(\"darwin\"):\n        return .darwin\n      case _ where os.hasPrefix(\"dragonfly\"):\n        return .dragonFly\n      case _ where os.hasPrefix(\"freebsd\"):\n        return .freebsd\n      case _ where os.hasPrefix(\"fuchsia\"):\n        return .fuchsia\n      case _ where os.hasPrefix(\"ios\"):\n        return .ios\n      case _ where os.hasPrefix(\"kfreebsd\"):\n        return .kfreebsd\n      case _ where os.hasPrefix(\"linux\"):\n        return .linux\n      case _ where os.hasPrefix(\"lv2\"):\n        return .lv2\n      case _ where os.hasPrefix(\"macos\"):\n        return .macosx\n      case _ where os.hasPrefix(\"netbsd\"):\n        return .netbsd\n      case _ where os.hasPrefix(\"openbsd\"):\n        return .openbsd\n      case _ where os.hasPrefix(\"solaris\"):\n        return .solaris\n      case _ where os.hasPrefix(\"win32\"):\n        return .win32\n      case _ where os.hasPrefix(\"windows\"):\n        return .win32\n      case _ where os.hasPrefix(\"haiku\"):\n        return .haiku\n      case _ where os.hasPrefix(\"minix\"):\n        return .minix\n      case _ where os.hasPrefix(\"rtems\"):\n        return .rtems\n      case _ where os.hasPrefix(\"nacl\"):\n        return .nacl\n      case _ where os.hasPrefix(\"cnk\"):\n        return .cnk\n      case _ where os.hasPrefix(\"aix\"):\n        return .aix\n      case _ where os.hasPrefix(\"cuda\"):\n        return .cuda\n      case _ where os.hasPrefix(\"nvcl\"):\n        return .nvcl\n      case _ where os.hasPrefix(\"amdhsa\"):\n        return .amdhsa\n      case _ where os.hasPrefix(\"ps4\"):\n        return .ps4\n      case _ where os.hasPrefix(\"elfiamcu\"):\n        return .elfiamcu\n      case _ where os.hasPrefix(\"tvos\"):\n        return .tvos\n      case _ where os.hasPrefix(\"watchos\"):\n        return .watchos\n      case _ where os.hasPrefix(\"mesa3d\"):\n        return .mesa3d\n      case _ where os.hasPrefix(\"contiki\"):\n        return .contiki\n      case _ where os.hasPrefix(\"amdpal\"):\n        return .amdpal\n      case _ where os.hasPrefix(\"hermit\"):\n        return .hermitcore\n      case _ where os.hasPrefix(\"hurd\"):\n        return .hurd\n      case _ where os.hasPrefix(\"wasi\"):\n        return .wasi\n      case _ where os.hasPrefix(\"emscripten\"):\n        return .emscripten\n      case _ where os.hasPrefix(\"none\"):\n        return .noneOS\n      default:\n        return nil\n      }\n    }\n\n    fileprivate static func valueIsValid(_ value: Substring) -> Bool {\n      parse(value) != nil || value.hasPrefix(\"cygwin\") || value.hasPrefix(\"mingw\")\n    }\n  }\n}\n\n// MARK: - Parse Environment\n\nextension Triple {\n  fileprivate enum EnvInfo: TripleComponent {\n    case environmentOnly(Triple.Environment)\n    case objectFormatOnly(Triple.ObjectFormat)\n    case both(\n      environment: Triple.Environment,\n      objectFormat: Triple.ObjectFormat\n    )\n\n    var environment: Triple.Environment? {\n      switch self {\n      case .environmentOnly(let env), .both(let env, _):\n        return env\n      case .objectFormatOnly:\n        return nil\n      }\n    }\n    var objectFormat: Triple.ObjectFormat? {\n      switch self {\n      case .objectFormatOnly(let obj), .both(_, let obj):\n        return obj\n      case .environmentOnly:\n        return nil\n      }\n    }\n\n    fileprivate static func parse(_ component: Substring) -> EnvInfo? {\n      switch (\n        Triple.Environment.parse(component),\n        Triple.ObjectFormat.parse(component)\n      ) {\n      case (nil, nil):\n        return nil\n      case (nil, let obj?):\n        return .objectFormatOnly(obj)\n      case (let env?, nil):\n        return .environmentOnly(env)\n      case (let env?, let obj?):\n        return .both(environment: env, objectFormat: obj)\n      }\n    }\n  }\n\n  public enum Environment: String, CaseIterable, Equatable, Sendable {\n    case eabihf\n    case eabi\n    case elfv1\n    case elfv2\n    case gnuabin32\n    case gnuabi64\n    case gnueabihf\n    case gnueabi\n    case gnux32\n    case code16\n    case gnu\n    case android\n    case musleabihf\n    case musleabi\n    case musl\n    case msvc\n    case itanium\n    case cygnus\n    case coreclr\n    case simulator\n    case macabi\n\n    fileprivate static func parse(_ env: Substring) -> Triple.Environment? {\n      switch env {\n      case _ where env.hasPrefix(\"eabihf\"):\n        return .eabihf\n      case _ where env.hasPrefix(\"eabi\"):\n        return .eabi\n      case _ where env.hasPrefix(\"elfv1\"):\n        return .elfv1\n      case _ where env.hasPrefix(\"elfv2\"):\n        return .elfv2\n      case _ where env.hasPrefix(\"gnuabin32\"):\n        return .gnuabin32\n      case _ where env.hasPrefix(\"gnuabi64\"):\n        return .gnuabi64\n      case _ where env.hasPrefix(\"gnueabihf\"):\n        return .gnueabihf\n      case _ where env.hasPrefix(\"gnueabi\"):\n        return .gnueabi\n      case _ where env.hasPrefix(\"gnux32\"):\n        return .gnux32\n      case _ where env.hasPrefix(\"code16\"):\n        return .code16\n      case _ where env.hasPrefix(\"gnu\"):\n        return .gnu\n      case _ where env.hasPrefix(\"android\"):\n        return .android\n      case _ where env.hasPrefix(\"musleabihf\"):\n        return .musleabihf\n      case _ where env.hasPrefix(\"musleabi\"):\n        return .musleabi\n      case _ where env.hasPrefix(\"musl\"):\n        return .musl\n      case _ where env.hasPrefix(\"msvc\"):\n        return .msvc\n      case _ where env.hasPrefix(\"itanium\"):\n        return .itanium\n      case _ where env.hasPrefix(\"cygnus\"):\n        return .cygnus\n      case _ where env.hasPrefix(\"coreclr\"):\n        return .coreclr\n      case _ where env.hasPrefix(\"simulator\"):\n        return .simulator\n      case _ where env.hasPrefix(\"macabi\"):\n        return .macabi\n      default:\n        return nil\n      }\n    }\n\n    fileprivate static func infer(archName: Substring?) -> Triple.Environment? {\n      guard let firstComponent = archName else { return nil }\n\n      switch firstComponent {\n      case _ where firstComponent.hasPrefix(\"mipsn32\"):\n        return .gnuabin32\n      case _ where firstComponent.hasPrefix(\"mips64\"):\n        return .gnuabi64\n      case _ where firstComponent.hasPrefix(\"mipsisa64\"):\n        return .gnuabi64\n      case _ where firstComponent.hasPrefix(\"mipsisa32\"):\n        return .gnu\n      case \"mips\", \"mipsel\", \"mipsr6\", \"mipsr6el\":\n        return .gnu\n      default:\n        return nil\n      }\n    }\n  }\n}\n\n// MARK: - Parse Object Format\n\nextension Triple {\n  public enum ObjectFormat: Sendable {\n    case coff\n    case elf\n    case macho\n    case wasm\n    case xcoff\n\n    fileprivate static func parse(_ env: Substring) -> Triple.ObjectFormat? {\n      switch env {\n      // \"xcoff\" must come before \"coff\" because of the order-dependendent pattern matching.\n      case _ where env.hasSuffix(\"xcoff\"):\n        return .xcoff\n      case _ where env.hasSuffix(\"coff\"):\n        return .coff\n      case _ where env.hasSuffix(\"elf\"):\n        return .elf\n      case _ where env.hasSuffix(\"macho\"):\n        return .macho\n      case _ where env.hasSuffix(\"wasm\"):\n        return .wasm\n      default:\n        return nil\n      }\n    }\n\n    fileprivate static func infer(arch: Triple.Arch?, os: Triple.OS?) -> Triple.ObjectFormat {\n      switch arch {\n        case nil, .aarch64, .aarch64e, .aarch64_32, .arm, .thumb, .x86, .x86_64:\n          if os?.isDarwin ?? false {\n            return .macho\n          } else if os?.isWindows ?? false {\n            return .coff\n          }\n          return .elf\n\n        case .aarch64_be: fallthrough\n        case .arc: fallthrough\n        case .amdgcn: fallthrough\n        case .amdil: fallthrough\n        case .amdil64: fallthrough\n        case .armeb: fallthrough\n        case .avr: fallthrough\n        case .bpfeb: fallthrough\n        case .bpfel: fallthrough\n        case .hexagon: fallthrough\n        case .lanai: fallthrough\n        case .hsail: fallthrough\n        case .hsail64: fallthrough\n        case .kalimba: fallthrough\n        case .le32: fallthrough\n        case .le64: fallthrough\n        case .mips: fallthrough\n        case .mips64: fallthrough\n        case .mips64el: fallthrough\n        case .mipsel: fallthrough\n        case .msp430: fallthrough\n        case .nvptx: fallthrough\n        case .nvptx64: fallthrough\n        case .ppc64le: fallthrough\n        case .r600: fallthrough\n        case .renderscript32: fallthrough\n        case .renderscript64: fallthrough\n        case .riscv32: fallthrough\n        case .riscv64: fallthrough\n        case .shave: fallthrough\n        case .sparc: fallthrough\n        case .sparcel: fallthrough\n        case .sparcv9: fallthrough\n        case .spir: fallthrough\n        case .spir64: fallthrough\n        case .systemz: fallthrough\n        case .tce: fallthrough\n        case .tcele: fallthrough\n        case .thumbeb: fallthrough\n        case .xcore:\n          return .elf\n\n        case .ppc, .ppc64:\n          if os?.isDarwin ?? false {\n            return .macho\n          } else if os == .aix {\n            return .xcoff\n          }\n          return .elf\n\n        case .wasm32, .wasm64:\n          return .wasm\n      }\n    }\n\n    var name: String {\n      switch self {\n        case .coff:   return \"coff\"\n        case .elf:    return \"elf\"\n        case .macho:  return \"macho\"\n        case .wasm:   return \"wasm\"\n        case .xcoff:  return \"xcoff\"\n      }\n    }\n  }\n}\n\n// MARK: - OS tests\n\nextension Triple.OS {\n\n  public var isWindows: Bool {\n    self == .win32\n  }\n\n  public var isAIX: Bool {\n    self == .aix\n  }\n\n  /// isMacOSX - Is this a Mac OS X triple. For legacy reasons, we support both\n  /// \"darwin\" and \"osx\" as OS X triples.\n  public var isMacOSX: Bool {\n    self == .darwin || self == .macosx\n  }\n\n  /// Is this an iOS triple.\n  /// Note: This identifies tvOS as a variant of iOS. If that ever\n  /// changes, i.e., if the two operating systems diverge or their version\n  /// numbers get out of sync, that will need to be changed.\n  /// watchOS has completely different version numbers so it is not included.\n  public var isiOS: Bool {\n    self == .ios || isTvOS\n  }\n\n  /// Is this an Apple tvOS triple.\n  public var isTvOS: Bool {\n    self == .tvos\n  }\n\n  /// Is this an Apple watchOS triple.\n  public var isWatchOS: Bool {\n    self == .watchos\n  }\n\n  /// isOSDarwin - Is this a \"Darwin\" OS (OS X, iOS, or watchOS).\n  public var isDarwin: Bool {\n    isMacOSX || isiOS || isWatchOS\n  }\n}\n\n// MARK: - Versions\n\nextension Triple {\n  fileprivate func component(at i: Int) -> String {\n    let components = triple.split(separator: \"-\", maxSplits: 3,\n                                  omittingEmptySubsequences: false)\n    guard i < components.endIndex else { return \"\" }\n    return String(components[i])\n  }\n\n  public var archName: String { component(at: 0) }\n  public var vendorName: String { component(at: 1) }\n\n  /// Returns the name of the OS from the triple string.\n  public var osName: String { component(at: 2) }\n\n  public var environmentName: String { component(at: 3) }\n\n  /// Parse the version number from the OS name component of the triple, if present.\n  ///\n  /// For example, \"fooos1.2.3\" would return (1, 2, 3). If an entry is not defined, it will\n  /// be returned as 0.\n  ///\n  /// This does not do any normalization of the version; for instance, a\n  /// `darwin` OS version number is not adjusted to match the equivalent\n  /// `macosx` version number. It's usually better to use `version(for:)`\n  /// to get Darwin versions.\n  public var osVersion: Version {\n    var osName = self.osName[...]\n\n    // Assume that the OS portion of the triple starts with the canonical name.\n    if let os = os {\n      if osName.hasPrefix(os.name) {\n        osName = osName.dropFirst(os.name.count)\n      } else if os == .macosx, osName.hasPrefix(\"macos\") {\n        osName = osName.dropFirst(5)\n      }\n    }\n\n    return Version(parse: osName)\n  }\n\n  public var osNameUnversioned: String {\n    var canonicalOsName = self.osName[...]\n\n    // Assume that the OS portion of the triple starts with the canonical name.\n    if let os = os {\n      if canonicalOsName.hasPrefix(os.name) {\n        canonicalOsName = osName.prefix(os.name.count)\n      } else if os == .macosx, osName.hasPrefix(\"macos\") {\n        canonicalOsName = osName.prefix(5)\n      }\n    }\n    return String(canonicalOsName)\n  }\n}\n\n// MARK: - Darwin Versions\n\nextension Triple {\n  /// Parse the version number as with getOSVersion and then\n  /// translate generic \"darwin\" versions to the corresponding OS X versions.\n  /// This may also be called with IOS triples but the OS X version number is\n  /// just set to a constant 10.4.0 in that case.\n  ///\n  /// Returns true if successful.\n  ///\n  /// This accessor is semi-private; it's typically better to use `version(for:)` or\n  /// `Triple.FeatureAvailability`.\n  public var _macOSVersion: Version? {\n    var version = osVersion\n\n    switch os {\n    case .darwin:\n      // Default to darwin8, i.e., MacOSX 10.4.\n      if version.major == 0 {\n        version.major = 8\n      }\n\n      // Darwin version numbers are skewed from OS X versions.\n      if version.major < 4 {\n        return nil\n      }\n\n      if version.major <= 19 {\n        version.micro = 0\n        version.minor = version.major - 4\n        version.major = 10\n      } else {\n        version.micro = 0\n        version.minor = 0\n        // darwin20+ corresponds to macOS 11+.\n        version.major = version.major - 9\n      }\n\n    case .macosx:\n      // Default to 10.4.\n      if version.major == 0 {\n        version.major = 10\n        version.minor = 4\n      }\n\n      if version.major < 10 {\n        return nil\n      }\n\n    case .ios, .tvos, .watchos:\n       // Ignore the version from the triple.  This is only handled because the\n       // the clang driver combines OS X and IOS support into a common Darwin\n       // toolchain that wants to know the OS X version number even when targeting\n       // IOS.\n      version = Version(10, 4, 0)\n\n    default:\n      fatalError(\"unexpected OS for Darwin triple\")\n    }\n    return version\n  }\n\n  /// Parse the version number as with getOSVersion.  This should\n  /// only be called with IOS or generic triples.\n  ///\n  /// This accessor is semi-private; it's typically better to use `version(for:)` or\n  /// `Triple.FeatureAvailability`.\n  public var _iOSVersion: Version {\n    switch os {\n    case .darwin, .macosx:\n      // Ignore the version from the triple.  This is only handled because the\n      // the clang driver combines OS X and iOS support into a common Darwin\n      // toolchain that wants to know the iOS version number even when targeting\n      // OS X.\n      return Version(5, 0, 0)\n    case .ios, .tvos:\n      var version = self.osVersion\n      // Default to 5.0 (or 7.0 for arm64).\n      if version.major == 0 {\n        version.major = arch == .aarch64 ? 7 : 5\n      }\n      return version\n    case .watchos:\n      fatalError(\"conflicting triple info\")\n    default:\n      fatalError(\"unexpected OS for Darwin triple\")\n    }\n  }\n\n  /// Parse the version number as with getOSVersion. This should only be\n  /// called with WatchOS or generic triples.\n  ///\n  /// This accessor is semi-private; it's typically better to use `version(for:)` or\n  /// `Triple.FeatureAvailability`.\n  public var _watchOSVersion: Version {\n    switch os {\n    case .darwin, .macosx:\n      // Ignore the version from the triple.  This is only handled because the\n      // the clang driver combines OS X and iOS support into a common Darwin\n      // toolchain that wants to know the iOS version number even when targeting\n      // OS X.\n      return Version(2, 0, 0)\n    case .watchos:\n      var version = self.osVersion\n      if version.major == 0 {\n        version.major = 2\n      }\n      return version\n    case .ios:\n      fatalError(\"conflicting triple info\")\n    default:\n      fatalError(\"unexpected OS for Darwin triple\")\n    }\n  }\n}\n\n// MARK: - Catalyst\n\nextension Triple {\n  @_spi(Testing) public var isMacCatalyst: Bool {\n    return self.isiOS && !self.isTvOS && environment == .macabi\n  }\n\n  func isValidForZipperingWithTriple(_ variant: Triple) -> Bool {\n    guard archName == variant.archName,\n      arch == variant.arch,\n      subArch == variant.subArch,\n      vendor == variant.vendor else {\n        return false\n    }\n\n    // Allow a macOS target and an iOS-macabi target variant\n    // This is typically the case when zippering a library originally\n    // developed for macOS.\n    if self.isMacOSX && variant.isMacCatalyst {\n      return true\n    }\n\n    // Allow an iOS-macabi target and a macOS target variant. This would\n    // be the case when zippering a library originally developed for\n    // iOS.\n    if variant.isMacOSX && isMacCatalyst {\n      return true\n    }\n\n    return false\n  }\n}\n\nfileprivate extension Array {\n\n  mutating func resize(toCount desiredCount: Int, paddingWith element: Element) {\n\n    if desiredCount > count {\n      append(contentsOf: repeatElement(element, count: desiredCount - count))\n    } else if desiredCount < count {\n      removeLast(count - desiredCount)\n    }\n  }\n}\n"
  },
  {
    "path": "Sources/Basics/Version+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCUtility.Version\n\nextension Version {\n    /// Try a version from a git tag.\n    ///\n    /// - Parameter tag: A version string possibly prepended with \"v\".\n    public init?(tag: String) {\n        if tag.first == \"v\" {\n            try? self.init(versionString: String(tag.dropFirst()), usesLenientParsing: true)\n        } else {\n            try? self.init(versionString: tag, usesLenientParsing: true)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Basics/WritableByteStream+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class TSCBasic.LocalFileOutputByteStream\nimport class TSCBasic.TerminalController\nimport class TSCBasic.ThreadSafeOutputByteStream\nimport protocol TSCBasic.WritableByteStream\n\nextension WritableByteStream {\n    /// Returns true if an only if the output byte stream is attached to a TTY.\n    public var isTTY: Bool {\n        let stream: WritableByteStream\n        if let threadSafeStream = self as? ThreadSafeOutputByteStream {\n            stream = threadSafeStream.stream\n        } else {\n            stream = self\n        }\n        guard let fileStream = stream as? LocalFileOutputByteStream else {\n            return false\n        }\n        return TerminalController.isTTY(fileStream)\n    }\n}\n"
  },
  {
    "path": "Sources/BinarySymbols/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(BinarySymbols STATIC\n  ClangHostDefaultObjectsDetector.swift\n  LLVMObjdumpSymbolProvider.swift\n  ReferencedSymbols.swift\n  SymbolProvider.swift)\ntarget_link_libraries(BinarySymbols PUBLIC\n  Basics)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(BinarySymbols PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n"
  },
  {
    "path": "Sources/BinarySymbols/ClangHostDefaultObjectsDetector.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\nimport protocol TSCBasic.WritableByteStream\n\npackage func detectDefaultObjects(\n    clang: AbsolutePath, fileSystem: any FileSystem, hostTriple: Triple,\n    observabilityScope: ObservabilityScope\n) async throws -> [AbsolutePath] {\n    let clangProcess = AsyncProcess(args: clang.pathString, \"-###\", \"-x\", \"c\", \"-\")\n    let stdinStream = try clangProcess.launch()\n    stdinStream.write(\n        #\"\"\"\n        #include <stdio.h>\n        int main(int argc, char *argv[]) {\n            printf(\"Hello world!\\n\")\n            return 0;\n        }\n        \"\"\"#\n    )\n    stdinStream.flush()\n    try stdinStream.close()\n    let clangResult = try await clangProcess.waitUntilExit()\n    guard case .terminated(let status) = clangResult.exitStatus,\n        status == 0\n    else {\n        throw StringError(\"Couldn't run clang on sample hello world program\")\n    }\n    let commandsStrings = try clangResult.utf8stderrOutput().split(whereSeparator: \\.isNewline)\n\n    let commands = commandsStrings.map { $0.split(whereSeparator: \\.isWhitespace) }\n    guard let linkerCommand = commands.last(where: { $0.first?.contains(\"ld\") == true }) else {\n        throw StringError(\"Couldn't find default link command\")\n    }\n\n    // TODO: This logic doesn't support Darwin and Windows based, c.f. https://github.com/swiftlang/swift-package-manager/issues/8753\n    let libraryExtensions = [hostTriple.staticLibraryExtension, hostTriple.dynamicLibraryExtension]\n    var objects: Set<AbsolutePath> = []\n    var searchPaths: [AbsolutePath] = []\n\n    var linkerArguments = linkerCommand.dropFirst().map {\n        $0.replacingOccurrences(of: \"\\\"\", with: \"\")\n    }\n\n    if hostTriple.isLinux() {\n        // Some platform still separate those out...\n        linkerArguments.append(contentsOf: [\"-lm\", \"-lpthread\", \"-ldl\"])\n    }\n\n    func handleArgument(_ argument: String) throws {\n        if argument.hasPrefix(\"-L\") {\n            searchPaths.append(try AbsolutePath(validating: String(argument.dropFirst(2))))\n        } else if argument.hasPrefix(\"-l\") && !argument.hasSuffix(\"lto_library\") {\n            let libraryName = argument.dropFirst(2)\n            let potentialLibraries = searchPaths.flatMap { path in\n                return libraryExtensions.map { ext in\n                    path.appending(\"\\(hostTriple.dynamicLibraryPrefix)\\(libraryName)\\(ext)\")\n                }\n            }\n\n            guard let library = potentialLibraries.first(where: { fileSystem.isFile($0) }) else {\n                observabilityScope.emit(warning: \"Could not find library: \\(libraryName)\")\n                return\n            }\n\n            // Try and detect if this a GNU ld linker script.\n            if let fileContents = try fileSystem.readFileContents(library).validDescription {\n                let lines = fileContents.split(whereSeparator: \\.isNewline)\n                guard lines.contains(where: { $0.contains(\"GNU ld script\") }) else {\n                    objects.insert(library)\n                    return\n                }\n\n                // If it is try and parse GROUP/INPUT commands as documented in https://sourceware.org/binutils/docs/ld/File-Commands.html\n                // Empirically it seems like GROUP is the only used such directive for libraries of interest.\n                // Empirically it looks like packaging linker scripts use spaces around parenthesis which greatly simplifies parsing.\n                let inputs = lines.filter { $0.hasPrefix(\"GROUP\") || $0.hasPrefix(\"INPUT\") }\n                let words = inputs.flatMap { $0.split(whereSeparator: \\.isWhitespace) }\n                let newArguments = words.filter {\n                    ![\"GROUP\", \"AS_NEEDED\", \"INPUT\"].contains($0) && $0 != \"(\" && $0 != \")\"\n                }.map(String.init)\n\n                for arg in newArguments {\n                    if arg.hasPrefix(\"-l\") {\n                        try handleArgument(arg)\n                    } else {\n                        // First try and locate the file relative to the linker script.\n                        let siblingPath = try AbsolutePath(\n                            validating: arg,\n                            relativeTo: try AbsolutePath(validating: library.dirname))\n                        if fileSystem.isFile(siblingPath) {\n                            try handleArgument(siblingPath.pathString)\n                        } else {\n                            // If this fails the file needs to be resolved relative to the search paths.\n                            guard\n                                let library = searchPaths.map({ $0.appending(arg) }).first(where: {\n                                    fileSystem.isFile($0)\n                                })\n                            else {\n                                observabilityScope.emit(\n                                    warning:\n                                        \"Malformed linker script at \\(library): found no library named \\(arg)\"\n                                )\n                                continue\n                            }\n                            try handleArgument(library.pathString)\n                        }\n                    }\n                }\n\n            } else {\n                objects.insert(library)\n            }\n\n        } else if try argument.hasSuffix(\".o\")\n            && fileSystem.isFile(AbsolutePath(validating: argument))\n        {\n            objects.insert(try AbsolutePath(validating: argument))\n        } else if let dotIndex = argument.firstIndex(of: \".\"),\n            libraryExtensions.first(where: { argument[dotIndex...].contains($0) }) != nil\n        {\n            objects.insert(try AbsolutePath(validating: argument))\n        }\n    }\n\n    for argument in linkerArguments {\n        try handleArgument(argument)\n    }\n\n    return objects.compactMap { $0 }\n}\n"
  },
  {
    "path": "Sources/BinarySymbols/LLVMObjdumpSymbolProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport RegexBuilder\n\npackage struct LLVMObjdumpSymbolProvider: SymbolProvider {\n    private let objdumpPath: AbsolutePath\n\n    package init(objdumpPath: AbsolutePath) {\n        self.objdumpPath = objdumpPath\n    }\n\n    package func symbols(for binary: AbsolutePath, symbols: inout ReferencedSymbols, recordUndefined: Bool = true) async throws {\n        let objdumpProcess = AsyncProcess(args: objdumpPath.pathString, \"-t\", \"-T\", binary.pathString)\n        try objdumpProcess.launch()\n        let result = try await objdumpProcess.waitUntilExit()\n        guard case .terminated(let status) = result.exitStatus,\n            status == 0 else {\n            throw InternalError(\"Unable to run llvm-objdump\")\n        }\n\n        try parse(output: try result.utf8Output(), symbols: &symbols, recordUndefined: recordUndefined)\n    }\n\n    package func parse(output: String, symbols: inout ReferencedSymbols, recordUndefined: Bool = true) throws {\n        let visibility = Reference<Substring>()\n        let weakLinkage = Reference<Substring>()\n        let section = Reference<Substring>()\n        let name = Reference<Substring>()\n        let symbolLineRegex = Regex {\n            Anchor.startOfLine\n            Repeat(CharacterClass.hexDigit, count: 16) // The address of the symbol\n            CharacterClass.whitespace\n            Capture(as: visibility) {\n                ChoiceOf {\n                    \"l\"\n                    \"g\"\n                    \"u\"\n                    \"!\"\n                    \" \"\n                }\n            }\n            Capture(as: weakLinkage) { // Whether the symbol is weak or strong\n                ChoiceOf {\n                    \"w\"\n                    \" \"\n                }\n            }\n            ChoiceOf {\n                \"C\"\n                \" \"\n            }\n            ChoiceOf {\n                \"W\"\n                \" \"\n            }\n            ChoiceOf {\n                \"I\"\n                \"i\"\n                \" \"\n            }\n            ChoiceOf {\n                \"D\"\n                \"d\"\n                \" \"\n            }\n            ChoiceOf {\n                \"F\"\n                \"f\"\n                \"O\"\n                \" \"\n            }\n            OneOrMore{\n                .whitespace\n            }\n            Capture(as: section) { // The section the symbol appears in\n                ZeroOrMore {\n                    .whitespace.inverted\n                }\n            }\n            ZeroOrMore {\n                .anyNonNewline\n            }\n            CharacterClass.whitespace\n            Capture(as: name) { // The name of symbol\n                OneOrMore {\n                    .whitespace.inverted\n                }\n            }\n            Anchor.endOfLine\n        }\n        for line in output.split(whereSeparator: \\.isNewline) {\n            guard let match = try symbolLineRegex.wholeMatch(in: line) else {\n                // This isn't a symbol definition line\n                continue\n            }\n\n            switch match[section] {\n            case \"*UND*\":\n                guard recordUndefined else {\n                    continue\n                }\n                // Weak symbols are optional\n                if match[weakLinkage] != \"w\" {\n                    symbols.addUndefined(String(match[name]))\n                }\n            default:\n                symbols.addDefined(String(match[name]))\n            }\n        }\n    }\n\n    private func name(line: Substring) -> Substring? {\n        guard let lastspace = line.lastIndex(where: \\.isWhitespace) else { return nil }\n        return line[line.index(after: lastspace)...]\n    }\n\n    private func section(line: Substring) throws -> Substring {\n        guard line.count > 25 else {\n            throw InternalError(\"Unable to run llvm-objdump\")\n        }\n        let sectionStart = line.index(line.startIndex, offsetBy: 25)\n        guard let sectionEnd = line[sectionStart...].firstIndex(where: \\.isWhitespace) else {\n            throw InternalError(\"Unable to run llvm-objdump\")\n        }\n        return line[sectionStart..<sectionEnd]\n    }\n}\n\n"
  },
  {
    "path": "Sources/BinarySymbols/ReferencedSymbols.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npackage struct ReferencedSymbols {\n    package private(set) var defined: Set<String>\n    package private(set) var undefined: Set<String>\n\n    package init() {\n        // Some symbols are defined by linker directly by convention and need to be assumed defined.\n        // The list below was pulled from\n        // https://github.com/llvm/llvm-project/blob/177e38286cd61a7b5a968636e1f147f128dd25a2/lld/ELF/Config.h#L632\n        self.defined = [\n            \"__bss_start\",\n            \"_etext\",\n            \"etext\",\n            \"_edata\",\n            \"edata\",\n            \"_end\",\n            \"end\",\n            \"_GLOBAL_OFFSET_TABLE_\",\n            \"_gp\",\n            \"_gp_disp\",\n            \"__gnu_local_gp\",\n            \"__global_pointer$\",\n            \"__rela_iplt_start\",\n            \"__rela_iplt_end\",\n            \"_TLS_MODULE_BASE\",\n        ]\n        self.undefined = []\n    }\n\n    mutating func addUndefined(_ name: String) {\n        guard !self.defined.contains(name) else {\n            return\n        }\n        self.undefined.insert(name)\n    }\n\n    mutating func addDefined(_ name: String) {\n        self.defined.insert(name)\n        self.undefined.remove(name)\n    }\n}\n"
  },
  {
    "path": "Sources/BinarySymbols/SymbolProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\npackage protocol SymbolProvider {\n    func symbols(for: AbsolutePath, symbols: inout ReferencedSymbols, recordUndefined: Bool) async throws\n}\n\nextension SymbolProvider {\n    package func symbols(for binary: AbsolutePath, symbols: inout ReferencedSymbols) async throws {\n        try await self.symbols(for: binary, symbols: &symbols, recordUndefined: true)\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildDescription/ClangModuleBuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport struct PackageGraph.ModulesGraph\nimport struct PackageGraph.ResolvedModule\nimport struct SPMBuildCore.BuildParameters\nimport struct SPMBuildCore.BuildToolPluginInvocationResult\nimport struct SPMBuildCore.CommandPluginResult\nimport enum SPMBuildCore.WarningControlFlags\n\n@available(*, deprecated, renamed: \"ClangModuleBuildDescription\")\npublic typealias ClangTargetBuildDescription = ClangModuleBuildDescription\n\n/// Build description for a Clang target i.e. C language family module.\npublic final class ClangModuleBuildDescription {\n    /// The package this target belongs to.\n    public let package: ResolvedPackage\n\n    /// The target described by this target.\n    public let target: ResolvedModule\n\n    /// The underlying clang target.\n    public let clangTarget: ClangModule\n\n    /// The tools version of the package that declared the target.  This can\n    /// can be used to conditionalize semantically significant changes in how\n    /// a target is built.\n    public let toolsVersion: ToolsVersion\n\n    /// The build parameters.\n    let buildParameters: BuildParameters\n\n    /// The destination for while this module is built.\n    public var destination: BuildParameters.Destination {\n        self.buildParameters.destination\n    }\n\n    /// The build environment.\n    var buildEnvironment: BuildEnvironment {\n        buildParameters.buildEnvironment\n    }\n\n    /// The list of all resource files in the target, including the derived ones.\n    public var resources: [Resource] {\n        self.target.underlying.resources + self.pluginDerivedResources\n    }\n\n    /// The list of files in the target that were marked as ignored.\n    public var ignored: [AbsolutePath] {\n        self.target.underlying.ignored\n    }\n\n    /// The list of other kinds of files in the target.\n    public var others: [AbsolutePath] {\n        self.target.underlying.others\n    }\n\n    /// Path to the bundle generated for this module (if any).\n    var bundlePath: AbsolutePath? {\n        guard !self.resources.isEmpty else {\n            return .none\n        }\n\n        if let bundleName = target.underlying.potentialBundleName {\n            return self.buildParameters.bundlePath(named: bundleName)\n        } else {\n            return .none\n        }\n    }\n\n    /// The modulemap file for this target, if any.\n    public private(set) var moduleMap: AbsolutePath?\n\n    /// Path to the temporary directory for this target.\n    var tempsPath: AbsolutePath\n\n    /// The directory containing derived sources of this target.\n    ///\n    /// These are the source files generated during the build.\n    private var derivedSources: Sources\n\n    /// These are the source files derived from plugins.\n    private var pluginDerivedSources: Sources\n\n    /// These are the resource files derived from plugins.\n    private var pluginDerivedResources: [Resource]\n\n    /// Generated headers, modulemaps, and api notes for this module\n    public let pluginDerivedModuleMap: AbsolutePath?\n    public let pluginDerivedAPINotes: [AbsolutePath]\n    public var pluginDerivedInterfaceFiles: [AbsolutePath] {\n        [pluginDerivedModuleMap].compactMap(\\.self) + pluginDerivedAPINotes\n    }\n\n    /// Public header paths from plugins\n    public private(set) var pluginDerivedPublicHeaderPaths: [AbsolutePath]\n\n    /// Path to the resource accessor header file, if generated.\n    public private(set) var resourceAccessorHeaderFile: AbsolutePath?\n\n    /// Path to the resource Info.plist file, if generated.\n    public private(set) var resourceBundleInfoPlistPath: AbsolutePath?\n\n    /// The objects in this target.\n    public var objects: [AbsolutePath] {\n        get throws {\n            try compilePaths().map(\\.object)\n        }\n    }\n\n    /// Paths to the binary libraries the target depends on.\n    var libraryBinaryPaths: Set<AbsolutePath> = []\n\n    /// Path to Windows DLLs that ship with binary libraries that need to be copied\n    /// over to the build output directory so executables that use them can find them.\n    var windowsDLLBinaryPaths: Set<AbsolutePath> = []\n\n    /// Any addition flags to be added. These flags are expected to be computed during build planning.\n    var additionalFlags: [String] = []\n\n    /// The filesystem to operate on.\n    private let fileSystem: FileSystem\n\n    /// If this target is a test target.\n    public var isTestTarget: Bool {\n        target.type == .test\n    }\n\n    /// The results of applying any build tool plugins to this target.\n    public let buildToolPluginInvocationResults: [BuildToolPluginInvocationResult]\n\n    /// Create a new target description with target and build parameters.\n    init(\n        package: ResolvedPackage,\n        target: ResolvedModule,\n        toolsVersion: ToolsVersion,\n        additionalFileRules: [FileRuleDescription] = [],\n        buildParameters: BuildParameters,\n        buildToolPluginInvocationResults: [BuildToolPluginInvocationResult] = [],\n        prebuildCommandResults: [CommandPluginResult] = [],\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        guard let clangTarget = target.underlying as? ClangModule else {\n            throw InternalError(\"underlying target type mismatch \\(target)\")\n        }\n\n        self.package = package\n        self.clangTarget = clangTarget\n        self.fileSystem = fileSystem\n        self.target = target\n        self.toolsVersion = toolsVersion\n        self.buildParameters = buildParameters\n        self.tempsPath = target.tempsPath(buildParameters)\n        self.derivedSources = Sources(paths: [], root: tempsPath.appending(\"DerivedSources\"))\n\n        // We did not use to apply package plugins to C-family targets in prior tools-versions, this preserves the behavior.\n        if toolsVersion >= .v5_9 {\n            self.buildToolPluginInvocationResults = buildToolPluginInvocationResults\n\n            let pluginGeneratedFiles = ModulesGraph.computePluginGeneratedFiles(\n                target: target,\n                toolsVersion: toolsVersion,\n                additionalFileRules: additionalFileRules,\n                buildParameters: buildParameters,\n                buildToolPluginInvocationResults: buildToolPluginInvocationResults,\n                prebuildCommandResults: prebuildCommandResults,\n                observabilityScope: observabilityScope\n            )\n\n            self.pluginDerivedSources = Sources(\n                paths: pluginGeneratedFiles.sources.map(\\.self),\n                root: buildParameters.dataPath\n            )\n            self.pluginDerivedResources = pluginGeneratedFiles.resources.values.map(\\.self)\n            self.pluginDerivedPublicHeaderPaths = pluginGeneratedFiles.publicHeaderPaths.map(\\.self)\n            self.pluginDerivedAPINotes = pluginGeneratedFiles.apiNotes\n\n            if pluginGeneratedFiles.moduleMaps.count > 1 {\n                observabilityScope.emit(warning: \"Only one module map generated by plugins is supported at this time: \\(clangTarget.name)\")\n                self.pluginDerivedModuleMap = nil\n            } else if let moduleMap = pluginGeneratedFiles.moduleMaps.first {\n                self.pluginDerivedModuleMap = moduleMap\n            } else {\n                self.pluginDerivedModuleMap = nil\n            }\n        } else {\n            self.buildToolPluginInvocationResults = []\n            self.pluginDerivedSources = Sources(paths: [], root: buildParameters.dataPath)\n            self.pluginDerivedResources = []\n            self.pluginDerivedModuleMap = nil\n            self.pluginDerivedAPINotes = []\n            self.pluginDerivedPublicHeaderPaths = []\n        }\n\n        // Try computing modulemap path for a C library.  This also creates the file in the file system, if needed.\n        if target.type == .library {\n            // If there's a custom module map, use it as given.\n            if case .custom(let path) = clangTarget.moduleMapType {\n                self.moduleMap = path\n            }\n            else if let pluginDerivedModuleMap {\n                self.moduleMap = pluginDerivedModuleMap\n            }\n            // If a generated module map is needed, generate one now in our temporary directory.\n            else if let generatedModuleMapType = clangTarget.moduleMapType.generatedModuleMapType {\n                let path = tempsPath.appending(component: moduleMapFilename)\n                let moduleMapGenerator = ModuleMapGenerator(\n                    targetName: clangTarget.name,\n                    moduleName: clangTarget.c99name,\n                    publicHeadersDir: clangTarget.includeDir,\n                    fileSystem: fileSystem\n                )\n                try moduleMapGenerator.generateModuleMap(type: generatedModuleMapType, at: path)\n                self.moduleMap = path\n            }\n            // Otherwise there is no module map, and we leave `moduleMap` unset.\n        }\n\n        // Do nothing if we're not generating a bundle.\n        if bundlePath != nil {\n            try self.generateResourceAccessor()\n\n            let infoPlistPath = tempsPath.appending(\"Info.plist\")\n            if try generateResourceInfoPlist(fileSystem: fileSystem, target: target, path: infoPlistPath) {\n                resourceBundleInfoPlistPath = infoPlistPath\n            }\n        }\n    }\n\n    /// An array of tuples containing filename, source, object and dependency path for each of the source in this target.\n    public func compilePaths()\n        throws -> [(filename: RelativePath, source: AbsolutePath, object: AbsolutePath, deps: AbsolutePath)]\n    {\n        let sources = [\n            target.sources.root: target.sources.relativePaths,\n            derivedSources.root: derivedSources.relativePaths,\n            pluginDerivedSources.root: pluginDerivedSources.relativePaths\n        ]\n\n        return try sources.flatMap { root, relativePaths in\n            try relativePaths.map { source in\n                let path = root.appending(source)\n                let object = try AbsolutePath(validating: \"\\(source.pathString).o\", relativeTo: tempsPath)\n                let deps = try AbsolutePath(validating: \"\\(source.pathString).d\", relativeTo: tempsPath)\n                return (source, path, object, deps)\n            }\n        }\n    }\n\n    /// Determines the arguments needed to run `swift-symbolgraph-extract` for\n    /// this module.\n    package func symbolGraphExtractArguments() throws -> [String] {\n        var args = [String]()\n\n        args += [\"-module-name\", self.target.c99name]\n        args += try self.buildParameters.tripleArgs(for: self.target)\n        args += [\"-module-cache-path\", try self.buildParameters.moduleCache.pathString]\n\n        if self.clangTarget.isCXX {\n            args += [\"-cxx-interoperability-mode=default\"]\n        }\n        if let cxxLanguageStandard = self.clangTarget.cxxLanguageStandard {\n            args += [\"-Xcc\", \"-std=\\(cxxLanguageStandard)\"]\n        }\n        args += [\"-I\", self.clangTarget.includeDir.pathString]\n        for path in pluginDerivedPublicHeaderPaths {\n            args += [\"-I\", path.pathString]\n        }\n        args += self.additionalFlags.asSwiftcCCompilerFlags()\n        // Unconditionally use clang modules with swift tools.\n        args += try self.clangModuleArguments().asSwiftcCCompilerFlags()\n        args += try self.currentModuleMapFileArguments().asSwiftcCCompilerFlags()\n        return args\n    }\n\n    /// Builds up basic compilation arguments for a source file in this target; these arguments may be different for C++\n    /// vs non-C++.\n    /// NOTE: The parameter to specify whether to get C++ semantics is currently optional, but this is only for revlock\n    /// avoidance with clients. Callers should always specify what they want based either the user's indication or on a\n    /// default value (possibly based on the filename suffix).\n    public func basicArguments(\n        isCXX isCXXOverride: Bool? = .none,\n        isC: Bool = false,\n        isAsm: Bool = false\n    ) throws -> [String] {\n        // For now fall back on the hold semantics if the C++ nature isn't specified. This is temporary until clients\n        // have been updated.\n        let isCXX = isCXXOverride ?? clangTarget.isCXX\n\n        var args = [String]()\n        // Only enable ARC on macOS.\n        if self.buildParameters.triple.isDarwin() {\n            args += [\"-fobjc-arc\"]\n        }\n        args += try self.buildParameters.tripleArgs(for: target)\n\n        args += optimizationArguments\n        args += activeCompilationConditions\n        args += [\"-fblocks\"]\n\n        // Enable index store, if appropriate.\n        if let supported = try? ClangSupport.supportsFeature(\n            name: \"index-unit-output-path\",\n            toolchain: self.buildParameters.toolchain\n        ), supported {\n            args += self.buildParameters.indexStoreArguments(for: target)\n        }\n\n        // Enable Clang module flags, if appropriate.\n        let triple = self.buildParameters.triple\n        // Swift is able to use modules on non-Darwin platforms because it injects its own module maps\n        // via vfs. However, nothing does that for C based compilation, and so non-Darwin platforms can't\n        // support clang modules.\n        // Note that if modules get enabled for other platforms later, they can't be used with C++ until\n        // https://github.com/llvm/llvm-project/issues/55980 (crash on C++17 and later) is fixed.\n        // clang modules aren't fully supported in C++ mode in the current Darwin SDKs.\n        let enableModules = triple.isDarwin() && !isCXX\n        if enableModules {\n            args += try self.clangModuleArguments()\n        }\n\n        // Only add the build path to the framework search path if there are binary frameworks to link against.\n        if !libraryBinaryPaths.isEmpty {\n            args += [\"-F\", buildParameters.buildPath.pathString]\n        }\n\n        args += [\"-I\", clangTarget.includeDir.pathString]\n        for path in pluginDerivedPublicHeaderPaths {\n            args += [\"-I\", path.pathString]\n        }\n\n        args += additionalFlags\n\n        args += buildParameters.sanitizers.compileCFlags()\n\n        // Add arguments from declared build settings.\n        args += try self.buildSettingsFlags()\n\n        // Include the path to the resource header unless the arguments are\n        // being evaluated for a C file. A C file cannot depend on the resource\n        // accessor header due to it exporting a Foundation type (`NSBundle`).\n        if let resourceAccessorHeaderFile, !isC && !isAsm {\n            args += [\"-include\", resourceAccessorHeaderFile.pathString]\n        }\n\n        args += self.buildParameters.toolchain.extraFlags.cCompilerFlags.rawFlags\n        // User arguments (from -Xcc) should follow generated arguments to allow user overrides\n        args += self.buildParameters.flags.cCompilerFlags.rawFlags\n\n        // Add extra C++ flags if this target contains C++ files.\n        if isCXX {\n            args += self.buildParameters.toolchain.extraFlags.cxxCompilerFlags.rawFlags\n            // User arguments (from -Xcxx) should follow generated arguments to allow user overrides\n            args += self.buildParameters.flags.cxxCompilerFlags.rawFlags\n        }\n\n        // Enable the correct lto mode if requested.\n        switch self.buildParameters.linkingParameters.linkTimeOptimizationMode {\n        case nil:\n            break\n        case .full:\n            args += [\"-flto=full\"]\n        case .thin:\n            args += [\"-flto=thin\"]\n        }\n\n        // rdar://117578677\n        // Pass -fno-omit-frame-pointer to support backtraces\n        // this can be removed once the backtracer uses DWARF instead of frame pointers\n        if let omitFramePointers = self.buildParameters.debuggingParameters.omitFramePointers {\n            if omitFramePointers {\n                args += [\"-fomit-frame-pointer\"]\n            } else {\n                args += [\"-fno-omit-frame-pointer\"]\n            }\n        }\n\n        // Pass default include paths from the toolchain.\n        for includeSearchPath in self.buildParameters.toolchain.includeSearchPaths {\n            args += [\"-I\", includeSearchPath.pathString]\n        }\n\n        // FIXME: Remove this once it becomes possible to express this dependency in a package manifest.\n        //\n        // On Linux/Android swift-corelibs-foundation depends on dispatch library which is\n        // currently shipped with the Swift toolchain.\n        if (triple.isLinux() || triple.isAndroid()) && self.package.id == .plain(\"swift-corelibs-foundation\") {\n            let swiftCompilerPath = self.buildParameters.toolchain.swiftCompilerPath\n            let toolchainResourcesPath = swiftCompilerPath.parentDirectory\n                                                          .parentDirectory\n                                                          .appending(components: [\"lib\", \"swift\"])\n            args += [\"-I\", toolchainResourcesPath.pathString]\n        }\n\n        // suppress warnings if the package is remote\n        if self.package.isRemote {\n            // `-w` (suppress warnings) and the other warning control flags are mutually exclusive\n            args = WarningControlFlags.filterClangWarningControlFlags(args)\n            args += [\"-w\"]\n        }\n\n        return args\n    }\n\n    public func emitCommandLine(for filePath: AbsolutePath) throws -> [String] {\n        let standards = [\n            (clangTarget.cxxLanguageStandard, SupportedLanguageExtension.cppExtensions),\n            (clangTarget.cLanguageStandard, SupportedLanguageExtension.cExtensions),\n        ]\n\n        guard let path = try self.compilePaths().first(where: { $0.source == filePath }) else {\n            throw BuildDescriptionError.requestedFileNotPartOfTarget(\n                targetName: self.target.name,\n                requestedFilePath: filePath\n            )\n        }\n\n        let isCXX = path.source.extension.map { SupportedLanguageExtension.cppExtensions.contains($0) } ?? false\n        let isC = path.source.extension.map { $0 == SupportedLanguageExtension.c.rawValue } ?? false\n        let isAsm = path.source.extension.map { SupportedLanguageExtension.assemblyExtensions.contains($0) } ?? false\n\n        var args = try basicArguments(isCXX: isCXX, isC: isC, isAsm: isAsm)\n\n        args += [\"-MD\", \"-MT\", \"dependencies\", \"-MF\", path.deps.pathString]\n\n        // Add language standard flag if needed.\n        if let ext = path.source.extension {\n            for (standard, validExtensions) in standards {\n                if let standard, validExtensions.contains(ext) {\n                    args += [\"-std=\\(standard)\"]\n                }\n            }\n        }\n\n        args += [\"-c\", path.source.pathString, \"-o\", path.object.pathString]\n\n        let clangCompiler = try buildParameters.toolchain.getClangCompiler().pathString\n        args.insert(clangCompiler, at: 0)\n        return args\n    }\n\n    /// Returns the build flags from the declared build settings.\n    private func buildSettingsFlags() throws -> [String] {\n        let scope = buildParameters.createScope(for: target)\n        var flags: [String] = []\n\n        // C defines.\n        let cDefines = scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS)\n        flags += cDefines.map { \"-D\" + $0 }\n\n        // Header search paths.\n        let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)\n        flags += try headerSearchPaths.map {\n            \"-I\\(try AbsolutePath(validating: $0, relativeTo: target.sources.root).pathString)\"\n        }\n\n        // Other C flags.\n        flags += scope.evaluate(.OTHER_CFLAGS)\n\n        // Other CXX flags.\n        flags += scope.evaluate(.OTHER_CPLUSPLUSFLAGS)\n\n        return flags\n    }\n\n    /// Optimization arguments according to the build configuration.\n    private var optimizationArguments: [String] {\n        switch buildParameters.configuration {\n        case .debug:\n            return [\"-O0\"]\n        case .release:\n            return [\"-O2\"]\n        }\n    }\n\n    /// A list of compilation conditions to enable for conditional compilation expressions.\n    private var activeCompilationConditions: [String] {\n        var compilationConditions = [\"-DSWIFT_PACKAGE=1\"]\n\n        switch buildParameters.configuration {\n        case .debug:\n            compilationConditions += [\"-DDEBUG=1\"]\n        case .release:\n            break\n        }\n\n        return compilationConditions\n    }\n\n    /// Enable Clang module flags.\n    private func clangModuleArguments() throws -> [String] {\n        let cachePath = try self.buildParameters.moduleCache.pathString\n        return [\n            \"-fmodules\",\n            \"-fmodule-name=\\(self.target.c99name)\",\n            \"-fmodules-cache-path=\\(cachePath)\",\n        ]\n    }\n    \n    private func currentModuleMapFileArguments() throws -> [String] {\n        // Pass the path to the current module's module map if present.\n        if let moduleMap = self.moduleMap {\n            return [\"-fmodule-map-file=\\(moduleMap.pathString)\"]\n        }\n        return []\n    }\n\n    /// Generate the resource bundle accessor, if appropriate.\n    private func generateResourceAccessor() throws {\n        // Only generate access when we have a bundle and ObjC files.\n        guard let bundlePath, clangTarget.sources.containsObjcFiles else { return }\n\n        // Compute the basename of the bundle.\n        let bundleBasename = bundlePath.basename\n\n        let implContent =\n            \"\"\"\n            #import <Foundation/Foundation.h>\n\n            NSBundle* \\(target.c99name)_SWIFTPM_MODULE_BUNDLE() {\n                NSURL *bundleURL = [[[NSBundle mainBundle] bundleURL] URLByAppendingPathComponent:@\"\\(bundleBasename)\"];\n\n                NSBundle *preferredBundle = [NSBundle bundleWithURL:bundleURL];\n                if (preferredBundle == nil) {\n                  return [NSBundle bundleWithPath:@\"\\(bundlePath.pathString)\"];\n                }\n\n                return preferredBundle;\n            }\n            \"\"\"\n\n        let implFileSubpath = try RelativePath(validating: \"resource_bundle_accessor.m\")\n\n        // Add the file to the derived sources.\n        derivedSources.relativePaths.append(implFileSubpath)\n\n        // Write this file out.\n        // FIXME: We should generate this file during the actual build.\n        try fileSystem.writeIfChanged(\n            path: derivedSources.root.appending(implFileSubpath),\n            string: implContent\n        )\n\n        let headerContent =\n            \"\"\"\n            #if __OBJC__\n            #import <Foundation/Foundation.h>\n\n            #if __cplusplus\n            extern \"C\" {\n            #endif\n\n            NSBundle* \\(target.c99name)_SWIFTPM_MODULE_BUNDLE(void);\n\n            #define SWIFTPM_MODULE_BUNDLE \\(target.c99name)_SWIFTPM_MODULE_BUNDLE()\n\n            #if __cplusplus\n            }\n            #endif\n            #endif\n            \"\"\"\n\n        let headerFile = derivedSources.root.appending(\"resource_bundle_accessor.h\")\n        self.resourceAccessorHeaderFile = headerFile\n\n        try fileSystem.writeIfChanged(\n            path: headerFile,\n            string: headerContent\n        )\n    }\n}\n\nextension ClangModuleBuildDescription {\n    package func dependencies(\n        using plan: BuildPlan\n    ) -> [ModuleBuildDescription.Dependency] {\n        ModuleBuildDescription.clang(self).dependencies(using: plan)\n    }\n\n    package func recursiveDependencies(\n        using plan: BuildPlan\n    ) -> [ModuleBuildDescription.Dependency] {\n        ModuleBuildDescription.clang(self).recursiveDependencies(using: plan)\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildDescription/ModuleBuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedPackage\nimport struct PackageGraph.ResolvedProduct\nimport struct PackageModel.Resource\nimport struct PackageModel.ToolsVersion\nimport struct SPMBuildCore.BuildToolPluginInvocationResult\nimport struct SPMBuildCore.BuildParameters\nimport protocol SPMBuildCore.ModuleBuildDescription\n\npublic enum BuildDescriptionError: Swift.Error {\n    case requestedFileNotPartOfTarget(targetName: String, requestedFilePath: AbsolutePath)\n}\n\n@available(*, deprecated, renamed: \"ModuleBuildDescription\")\npublic typealias TargetBuildDescription = ModuleBuildDescription\n\n/// A module build description which can either be for a Swift or Clang module.\npublic enum ModuleBuildDescription: SPMBuildCore.ModuleBuildDescription {\n    /// Swift target description.\n    case swift(SwiftModuleBuildDescription)\n\n    /// Clang target description.\n    case clang(ClangModuleBuildDescription)\n\n    /// The objects in this target.\n    var objects: [AbsolutePath] {\n        get throws {\n            switch self {\n            case .swift(let module):\n                return try module.objects\n            case .clang(let module):\n                return try module.objects\n            }\n        }\n    }\n\n    /// The resources in this target.\n    var resources: [Resource] {\n        switch self {\n        case .swift(let buildDescription):\n            return buildDescription.resources\n        case .clang(let buildDescription):\n            return buildDescription.resources\n        }\n    }\n\n    /// Path to the bundle generated for this module (if any).\n    var bundlePath: AbsolutePath? {\n        switch self {\n        case .swift(let buildDescription):\n            return buildDescription.bundlePath\n        case .clang(let buildDescription):\n            return buildDescription.bundlePath\n        }\n    }\n\n    public var module: ResolvedModule {\n        switch self {\n        case .swift(let buildDescription):\n            return buildDescription.target\n        case .clang(let buildDescription):\n            return buildDescription.target\n        }\n    }\n\n    public var package: ResolvedPackage {\n        switch self {\n        case .swift(let description):\n            description.package\n        case .clang(let description):\n            description.package\n        }\n    }\n\n    /// Paths to the binary libraries the target depends on.\n    var libraryBinaryPaths: Set<AbsolutePath> {\n        switch self {\n        case .swift(let target):\n            return target.libraryBinaryPaths\n        case .clang(let target):\n            return target.libraryBinaryPaths\n        }\n    }\n\n    var windowsDLLBinaryPaths: Set<AbsolutePath> {\n        switch self {\n        case .swift(let target):\n            return target.windowsDLLBinaryPaths\n        case .clang(let target):\n            return target.windowsDLLBinaryPaths\n        }\n    }\n\n    var resourceBundleInfoPlistPath: AbsolutePath? {\n        switch self {\n        case .swift(let buildDescription):\n            return buildDescription.resourceBundleInfoPlistPath\n        case .clang(let buildDescription):\n            return buildDescription.resourceBundleInfoPlistPath\n        }\n    }\n\n    var buildToolPluginInvocationResults: [BuildToolPluginInvocationResult] {\n        switch self {\n        case .swift(let buildDescription):\n            return buildDescription.buildToolPluginInvocationResults\n        case .clang(let buildDescription):\n            return buildDescription.buildToolPluginInvocationResults\n        }\n    }\n\n    public var buildParameters: BuildParameters {\n        switch self {\n        case .swift(let buildDescription):\n            return buildDescription.buildParameters\n        case .clang(let buildDescription):\n            return buildDescription.buildParameters\n        }\n    }\n\n    var destination: BuildParameters.Destination {\n        switch self {\n        case .swift(let buildDescription):\n            buildDescription.destination\n        case .clang(let buildDescription):\n            buildDescription.destination\n        }\n    }\n\n    var toolsVersion: ToolsVersion {\n        switch self {\n        case .swift(let buildDescription):\n            return buildDescription.toolsVersion\n        case .clang(let buildDescription):\n            return buildDescription.toolsVersion\n        }\n    }\n\n    public var diagnosticFiles: [AbsolutePath] {\n        switch self {\n        case .swift(let buildDescription):\n            buildDescription.diagnosticFiles\n        case .clang(_):\n            []\n        }\n    }\n    /// Determines the arguments needed to run `swift-symbolgraph-extract` for\n    /// this module.\n    public func symbolGraphExtractArguments() throws -> [String] {\n        switch self {\n        case .swift(let buildDescription): try buildDescription.symbolGraphExtractArguments()\n        case .clang(let buildDescription): try buildDescription.symbolGraphExtractArguments()\n        }\n    }\n}\n\nextension ModuleBuildDescription: Identifiable {\n    public struct ID: Hashable {\n        let moduleID: ResolvedModule.ID\n        let destination: BuildParameters.Destination\n    }\n\n    public var id: ID {\n        ID(moduleID: self.module.id, destination: self.destination)\n    }\n}\n\nextension ModuleBuildDescription {\n    package enum Dependency {\n        /// Not all of the modules and products have build descriptions\n        case product(ResolvedProduct, ProductBuildDescription?)\n        case module(ResolvedModule, ModuleBuildDescription?)\n    }\n\n    package func dependencies(using plan: BuildPlan) -> [Dependency] {\n        self.module\n            .dependencies(satisfying: self.buildParameters.buildEnvironment)\n            .map {\n                switch $0 {\n                case .product(let product, _):\n                    let productDescription = plan.description(for: product, context: self.destination)\n                    return .product(product, productDescription)\n                case .module(let module, _):\n                    let moduleDescription = plan.description(for: module, context: self.destination)\n                    return .module(module, moduleDescription)\n                }\n            }\n    }\n\n    package func recursiveDependencies(using plan: BuildPlan) -> [Dependency] {\n        var dependencies: [Dependency] = []\n        plan.traverseDependencies(of: self) { product, _, description in\n            dependencies.append(.product(product, description))\n        } onModule: { module, _, description in\n            dependencies.append(.module(module, description))\n        }\n        return dependencies\n    }\n\n    package func recursiveLinkDependencies(using plan: BuildPlan) -> [Dependency] {\n        var dependencies: [Dependency] = []\n        plan.traverseLinkDependencies(of: self) { product, _, description in\n            dependencies.append(.product(product, description))\n        } onModule: { module, _, description in\n            dependencies.append(.module(module, description))\n        }\n        return dependencies\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildDescription/PluginBuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageGraph\nimport PackageModel\n\nimport struct Basics.InternalError\nimport protocol Basics.FileSystem\n\n/// Description for a plugin module. This is treated a bit differently from the\n/// regular kinds of modules, and is not included in the LLBuild description.\n/// But because the modules graph and build plan are not loaded for incremental\n/// builds, this information is included in the BuildDescription, and the plugin\n/// modules are compiled directly.\npublic final class PluginBuildDescription: Codable {\n    /// The identity of the package in which the plugin is defined.\n    public let package: PackageIdentity\n\n    /// The name of the plugin module in that package (this is also the name of\n    /// the plugin).\n    public let moduleName: String\n\n    /// The language-level module name.\n    public let moduleC99Name: String\n\n    /// The names of any plugin products in that package that vend the plugin\n    /// to other packages.\n    public let productNames: [String]\n\n    /// The tools version of the package that declared the module. This affects\n    /// the API that is available in the PackagePlugin module.\n    public let toolsVersion: ToolsVersion\n\n    /// Swift source files that comprise the plugin.\n    public let sources: Sources\n\n    /// Initialize a new plugin module description. The module is expected to be\n    /// a `PluginTarget`.\n    init(\n        module: ResolvedModule,\n        products: [ResolvedProduct],\n        package: ResolvedPackage,\n        toolsVersion: ToolsVersion,\n        testDiscoveryTarget: Bool = false,\n        fileSystem: FileSystem\n    ) throws {\n        guard module.underlying is PluginModule else {\n            throw InternalError(\"underlying target type mismatch \\(module)\")\n        }\n\n        self.package = package.identity\n        self.moduleName = module.name\n        self.moduleC99Name = module.c99name\n        self.productNames = products.map(\\.name)\n        self.toolsVersion = toolsVersion\n        self.sources = module.sources\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildDescription/ProductBuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageGraph\n\n@_spi(SwiftPMInternal)\nimport PackageModel\n\nimport OrderedCollections\nimport SPMBuildCore\nimport TSCUtility\n\nimport struct TSCBasic.SortedArray\n\n/// The build description for a product.\npublic final class ProductBuildDescription: SPMBuildCore.ProductBuildDescription {\n    /// The reference to the product.\n    public let package: ResolvedPackage\n\n    /// The reference to the product.\n    public let product: ResolvedProduct\n\n    /// The tools version of the package that declared the product.  This can\n    /// can be used to conditionalize semantically significant changes in how\n    /// a target is built.\n    public let toolsVersion: ToolsVersion\n\n    /// The build parameters.\n    public let buildParameters: BuildParameters\n\n    /// The destination for while this product is built.\n    public var destination: BuildParameters.Destination {\n        self.buildParameters.destination\n    }\n\n    /// All object files to link into this product.\n    ///\n    // Computed during build planning.\n    public internal(set) var objects = SortedArray<AbsolutePath>()\n\n    /// The dynamic libraries this product needs to link with.\n    // Computed during build planning.\n    var dylibs: [ProductBuildDescription] = []\n\n    /// Any additional flags to be added. These flags are expected to be computed during build planning.\n    var additionalFlags: [String] = []\n\n    /// The list of targets that are going to be linked statically in this product.\n    var staticTargets: [ResolvedModule] = []\n\n    /// The list of Swift modules that should be passed to the linker. This is required for debugging to work.\n    var swiftASTs: SortedArray<AbsolutePath> = .init()\n\n    /// Paths to the binary libraries the product depends on.\n    var libraryBinaryPaths: Set<AbsolutePath> = []\n\n    /// Paths to tools shipped in binary dependencies\n    var availableTools: [String: AbsolutePath] = [:]\n\n    /// Path to the temporary directory for this product.\n    var tempsPath: AbsolutePath {\n        let suffix = buildParameters.suffix\n        return self.buildParameters.buildPath.appending(component: \"\\(self.product.name)\\(suffix).product\")\n    }\n\n    /// Path to the link filelist file.\n    var linkFileListPath: AbsolutePath {\n        self.tempsPath.appending(\"Objects.LinkFileList\")\n    }\n\n    /// File system reference.\n    private let fileSystem: FileSystem\n\n    /// ObservabilityScope with which to emit diagnostics\n    private let observabilityScope: ObservabilityScope\n\n    /// Create a build description for a product.\n    init(\n        package: ResolvedPackage,\n        product: ResolvedProduct,\n        toolsVersion: ToolsVersion,\n        buildParameters: BuildParameters,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        guard product.type != .library(.automatic) else {\n            throw InternalError(\"Automatic type libraries should not be described.\")\n        }\n\n        self.package = package\n        self.product = product\n        self.toolsVersion = toolsVersion\n        self.buildParameters = buildParameters\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n    }\n\n    /// Strips the arguments which should *never* be passed to Swift compiler\n    /// when we're linking the product.\n    ///\n    /// We might want to get rid of this method once Swift driver can strip the\n    /// flags itself, <rdar://problem/31215562>.\n    private func stripInvalidArguments(_ args: [String]) -> [String] {\n        let invalidArguments: Set<String> = [\"-wmo\", \"-whole-module-optimization\"]\n        return args.filter { !invalidArguments.contains($0) }\n    }\n\n    private var deadStripArguments: [String] {\n        if !self.buildParameters.linkingParameters.linkerDeadStrip {\n            return []\n        }\n\n        let triple = self.buildParameters.triple\n        switch self.buildParameters.configuration {\n        case .debug:\n            return []\n        case .release:\n            if triple.isApple() {\n                return [\"-Xlinker\", \"-dead_strip\"]\n            } else if triple.isWindows() {\n                return [\"-Xlinker\", \"/OPT:REF\"]\n            } else {\n                return [\"-Xlinker\", \"--gc-sections\"]\n            }\n        }\n    }\n\n    /// The arguments to the librarian to create a static library.\n    public func archiveArguments() throws -> [String] {\n        let librarian = self.buildParameters.toolchain.librarianPath.pathString\n        let triple = self.buildParameters.triple\n        if triple.isWindows(), librarian.hasSuffix(\"link\") || librarian.hasSuffix(\"link.exe\") {\n            return try [librarian, \"/LIB\", \"/OUT:\\(binaryPath.pathString)\", \"@\\(self.linkFileListPath.pathString)\"]\n        }\n        if triple.isApple(), librarian.hasSuffix(\"libtool\") {\n            return try [librarian, \"-static\", \"-o\", binaryPath.pathString, \"@\\(self.linkFileListPath.pathString)\"]\n        }\n        return try [librarian, \"crs\", binaryPath.pathString, \"@\\(self.linkFileListPath.pathString)\"]\n    }\n\n    /// The arguments to link and create this product.\n    public func linkArguments() throws -> [String] {\n        var args = [buildParameters.toolchain.swiftCompilerPath.pathString]\n        args += self.buildParameters.sanitizers.linkSwiftFlags()\n        args += self.additionalFlags\n\n        // pass `-v` during verbose builds.\n        if self.buildParameters.outputParameters.isVerbose {\n            args += [\"-v\"]\n        }\n\n        // Only add the build path to the framework search path if there are binary frameworks to link against.\n        if !self.libraryBinaryPaths.isEmpty {\n            args += [\"-F\", self.buildParameters.buildPath.pathString]\n        }\n\n        args += [\"-L\", self.buildParameters.buildPath.pathString]\n        args += try [\"-o\", binaryPath.pathString]\n        args += [\"-module-name\", self.product.name.spm_mangledToC99ExtendedIdentifier()]\n        args += self.dylibs.map { \"-l\" + $0.product.name + $0.buildParameters.suffix }\n\n        // Add arguments needed for code coverage if it is enabled.\n        if self.buildParameters.testingParameters.enableCodeCoverage {\n            args += [\"-profile-coverage-mapping\", \"-profile-generate\"]\n        }\n\n        let containsSwiftTargets = self.product.containsSwiftModules\n\n        let derivedProductType: ProductType\n        switch self.product.type {\n        case .macro:\n            #if BUILD_MACROS_AS_DYLIBS\n            derivedProductType = .library(.dynamic)\n            #else\n            derivedProductType = .executable\n            #endif\n        default:\n            derivedProductType = self.product.type\n        }\n\n        var isLinkingStaticStdlib = false\n        let triple = self.buildParameters.triple\n\n        // radar://112671586 supress unnecessary warnings\n        if triple.isMacOSX {\n            args += [\"-Xlinker\", \"-no_warn_duplicate_libraries\"]\n        }\n        // We may also need to turn off locally defined symbol imported on Windows\n        // args += [\"-Xlinker\", \"/ignore:4217\"]\n\n        switch derivedProductType {\n        case .macro:\n            throw InternalError(\"macro not supported\") // should never be reached\n        case .library(.automatic):\n            throw InternalError(\"automatic library not supported\")\n        case .library(.static):\n            // No arguments for static libraries.\n            return []\n        case .test:\n            // Test products are bundle when using Objective-C, executable when using test entry point.\n            switch self.buildParameters.testProductStyle {\n            case .loadableBundle:\n                args += [\"-Xlinker\", \"-bundle\"]\n            case .entryPointExecutable:\n                args += [\"-emit-executable\"]\n            }\n            args += self.deadStripArguments\n        case .library(.dynamic):\n            args += [\"-emit-library\"]\n            if triple.isDarwin() {\n                let relativePath = try \"@rpath/\\(buildParameters.binaryRelativePath(for: self.product).pathString)\"\n                args += [\"-Xlinker\", \"-install_name\", \"-Xlinker\", relativePath]\n            }\n            args += self.deadStripArguments\n        case .executable, .snippet:\n            // Link the Swift stdlib statically, if requested.\n            // TODO: unify this logic with SwiftTargetBuildDescription.stdlibArguments\n            if self.buildParameters.linkingParameters.shouldLinkStaticSwiftStdlib {\n                if triple.isDarwin() {\n                    self.observabilityScope.emit(.swiftBackDeployError)\n                } else if triple.isSupportingStaticStdlib {\n                    args += [\"-static-stdlib\"]\n                    isLinkingStaticStdlib = true\n                }\n            }\n            args += [\"-emit-executable\"]\n            args += self.deadStripArguments\n\n            // If we're linking an executable whose main module is implemented in Swift,\n            // we rename the `_<modulename>_main` entry point symbol to `_main` again.\n            // This is because executable modules implemented in Swift are compiled with\n            // a main symbol named that way to allow tests to link against it without\n            // conflicts. If we're using a linker that doesn't support symbol renaming,\n            // we will instead have generated a source file containing the redirect.\n            // Support for linking tests against executables is conditional on the tools\n            // version of the package that defines the executable product.\n            let executableTarget = try product.executableModule\n            if let target = executableTarget.underlying as? SwiftModule, \n                self.toolsVersion >= .v5_5,\n                self.buildParameters.driverParameters.canRenameEntrypointFunctionName,\n                target.supportsTestableExecutablesFeature\n            {\n                if let flags = buildParameters.linkerFlagsForRenamingMainFunction(of: executableTarget) {\n                    args += flags\n                }\n            }\n        case .plugin:\n            throw InternalError(\"unexpectedly asked to generate linker arguments for a plugin product\")\n        }\n\n        if let resourcesPath = self.buildParameters.toolchain.swiftResourcesPath(isStatic: isLinkingStaticStdlib) {\n            args += [\"-resource-dir\", \"\\(resourcesPath)\"]\n        }\n\n        // clang resources are always in lib/swift/\n        if let dynamicResourcesPath = self.buildParameters.toolchain.swiftResourcesPath {\n            let clangResourcesPath = dynamicResourcesPath.appending(\"clang\")\n            args += [\"-Xclang-linker\", \"-resource-dir\", \"-Xclang-linker\", \"\\(clangResourcesPath)\"]\n        }\n\n        // Set rpath such that dynamic libraries are looked up\n        // adjacent to the product, unless overridden.\n        if triple.os != .noneOS, !self.buildParameters.linkingParameters.shouldDisableLocalRpath {\n            switch triple.objectFormat {\n            case .elf:\n                args += [\"-Xlinker\", \"-rpath=$ORIGIN\"]\n            case .macho:\n                let rpath = self.product.type == .test ? \"@loader_path/../../../\" : \"@loader_path\"\n                args += [\"-Xlinker\", \"-rpath\", \"-Xlinker\", rpath]\n            default:\n                break\n            }\n        }\n        args += [\"@\\(self.linkFileListPath.pathString)\"]\n\n        if containsSwiftTargets {\n            // Pass experimental features to link jobs in addition to compile jobs. Preserve ordering while eliminating\n            // duplicates with `OrderedSet`.\n            var experimentalFeatures = OrderedSet<String>()\n            var strictMemorySafety = false\n            for target in self.product.modules {\n                let swiftSettings = target.underlying.buildSettingsDescription.filter { $0.tool == .swift }\n              for kind in swiftSettings.map(\\.kind) {\n                if case let .enableExperimentalFeature(feature) = kind {\n                    experimentalFeatures.append(feature)\n                } else if kind == .strictMemorySafety {\n                    strictMemorySafety = true\n                }\n              }\n            }\n\n            for feature in experimentalFeatures {\n                args += [\"-enable-experimental-feature\", feature]\n            }\n\n            if strictMemorySafety {\n                args.append(\"-strict-memory-safety\")\n            }\n\n            // Embed the swift stdlib library path inside tests and executables on Darwin.\n            let useStdlibRpath: Bool\n            switch self.product.type {\n            case .library(let type):\n                useStdlibRpath = type == .dynamic\n            case .test, .executable, .snippet, .macro:\n                useStdlibRpath = true\n            case .plugin:\n                throw InternalError(\"unexpectedly asked to generate linker arguments for a plugin product\")\n            }\n\n            if useStdlibRpath, triple.isMacOSX {\n                let macOSSupportedPlatform = self.package.getSupportedPlatform(for: .macOS, usingXCTest: product.isLinkingXCTest)\n\n                if macOSSupportedPlatform.version.major < 12 {\n                    // When deploying to macOS prior to macOS 12, add an rpath to the\n                    // back-deployed concurrency libraries.\n                    let backDeployedStdlib = try buildParameters.toolchain.macosSwiftStdlib\n                        .parentDirectory\n                        .parentDirectory\n                        .appending(\"swift-5.5\")\n                        .appending(\"macosx\")\n                    args += [\"-Xlinker\", \"-rpath\", \"-Xlinker\", backDeployedStdlib.pathString]\n                }\n\n                if macOSSupportedPlatform.version.major < 26 {\n                    // When deploying to macOS prior to macOS 26, add an rpath to the\n                    // back-deployed Span library.\n                    let backDeployedStdlib = try buildParameters.toolchain.macosSwiftStdlib\n                        .parentDirectory\n                        .parentDirectory\n                        .appending(\"swift-6.2\")\n                        .appending(\"macosx\")\n                    args += [\"-Xlinker\", \"-rpath\", \"-Xlinker\", backDeployedStdlib.pathString]\n                }\n\n                // If either back deployment library is used, the driver is responsible for injecting\n                // a /usr/lib/swift -rpath at the front to ensure OS content is preferred when\n                // available.\n            }\n        } else {\n            // Don't link runtime compatibility patch libraries if there are no\n            // Swift sources in the target.\n            args += [\"-runtime-compatibility-version\", \"none\"]\n        }\n\n        // Add the target triple from the first target in the product.\n        //\n        // We can just use the first target of the product because the deployment target\n        // setting is the package-level right now. We might need to figure out a better\n        // answer for libraries if/when we support specifying deployment target at the\n        // target-level.\n        args += try self.buildParameters.tripleArgs(for: self.product.modules[self.product.modules.startIndex])\n\n        // Add arguments from declared build settings.\n        args += self.buildSettingsFlags\n\n        // Add AST paths to make the product debuggable. This array is only populated when we're\n        // building for Darwin in debug configuration.\n        args += self.swiftASTs.flatMap { [\"-Xlinker\", \"-add_ast_path\", \"-Xlinker\", $0.pathString] }\n\n        args += self.buildParameters.toolchain.extraFlags.swiftCompilerFlags.rawFlags\n        // User arguments (from -Xswiftc) should follow generated arguments to allow user overrides\n        args += self.buildParameters.flags.swiftCompilerFlags.rawFlags\n\n        args += self.buildParameters.toolchain.extraFlags.linkerFlags.rawFlags.asSwiftcLinkerFlags()\n        // User arguments (from -Xlinker) should follow generated arguments to allow user overrides\n        args += self.buildParameters.flags.linkerFlags.rawFlags.asSwiftcLinkerFlags()\n\n        // Enable the correct lto mode if requested.\n        switch self.buildParameters.linkingParameters.linkTimeOptimizationMode {\n        case nil:\n            break\n        case .full:\n            args += [\"-lto=llvm-full\"]\n        case .thin:\n            args += [\"-lto=llvm-thin\"]\n        }\n\n        // Pass default library paths from the toolchain.\n        for librarySearchPath in self.buildParameters.toolchain.librarySearchPaths {\n            args += [\"-L\", librarySearchPath.pathString]\n        }\n\n        // Library search path for the toolchain's copy of SwiftSyntax.\n        #if BUILD_MACROS_AS_DYLIBS\n        if product.type == .macro {\n            args += try [\"-L\", defaultBuildParameters.toolchain.hostLibDir.pathString]\n        }\n        #endif\n\n        return self.stripInvalidArguments(args)\n    }\n\n    /// Returns the build flags from the declared build settings.\n    private var buildSettingsFlags: [String] {\n        var flags: [String] = []\n\n        // Linked libraries.\n        let libraries = OrderedSet(self.staticTargets.reduce([]) {\n            $0 + self.buildParameters.createScope(for: $1).evaluate(.LINK_LIBRARIES)\n        })\n        flags += libraries.map { \"-l\" + $0 }\n\n        // Linked frameworks.\n        if self.buildParameters.triple.supportsFrameworks {\n            let frameworks = OrderedSet(self.staticTargets.reduce([]) {\n                $0 + self.buildParameters.createScope(for: $1).evaluate(.LINK_FRAMEWORKS)\n            })\n            flags += frameworks.flatMap { [\"-framework\", $0] }\n        }\n\n        // Prebuilt libraries.\n        let prebuiltLibPaths = OrderedSet(self.staticTargets.reduce([]) {\n            $0 + self.buildParameters.createScope(for: $1).evaluate(.PREBUILT_LIBRARY_PATHS)\n        })\n        let prebuiltLibraries = OrderedSet(self.staticTargets.reduce([]) {\n            $0 + self.buildParameters.createScope(for: $1).evaluate(.PREBUILT_LIBRARIES)\n        })\n        flags += prebuiltLibPaths.flatMap({ [\"-L\", $0] }) + prebuiltLibraries.map({ \"-l\" + $0 })\n\n        // Other linker flags.\n        for target in self.staticTargets {\n            let scope = self.buildParameters.createScope(for: target)\n            flags += scope.evaluate(.OTHER_LDFLAGS)\n        }\n\n        return flags\n    }\n\n    func codeSigningArguments(plistPath: AbsolutePath, binaryPath: AbsolutePath) -> [String] {\n        [\"codesign\", \"--force\", \"--sign\", \"-\", \"--entitlements\", plistPath.pathString, binaryPath.pathString]\n    }\n}\n\nextension ProductBuildDescription: Identifiable {\n    public struct ID: Hashable {\n        let productID: ResolvedProduct.ID\n        let destination: BuildParameters.Destination\n    }\n\n    public var id: ID {\n        ID(productID: self.product.id, destination: self.destination)\n    }\n}\n\nextension SortedArray where Element == AbsolutePath {\n    public static func +=<S: Sequence>(lhs: inout SortedArray, rhs: S) where S.Iterator.Element == AbsolutePath {\n        lhs.insert(contentsOf: rhs)\n    }\n}\n\nextension Basics.Triple {\n    var supportsFrameworks: Bool {\n        return self.isDarwin()\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildDescription/ResolvedModule+BuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport struct PackageGraph.ResolvedModule\n\nimport SPMBuildCore\n\nextension ResolvedModule {\n    func tempsPath(_ buildParameters: BuildParameters) -> AbsolutePath {\n        let suffix = buildParameters.suffix\n        return buildParameters.buildPath.appending(component: \"\\(self.c99name)\\(suffix).build\")\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildDescription/SwiftModuleBuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport TSCUtility\n\n@_spi(SwiftPMInternal)\nimport PackageModel\n\n@_spi(SwiftPMInternal)\nimport SPMBuildCore\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import DriverSupport\n#else\nimport DriverSupport\n#endif\n\nimport struct TSCBasic.ByteString\n\n@available(*, deprecated, renamed: \"SwiftModuleBuildDescription\")\npublic typealias SwiftTargetBuildDescription = SwiftModuleBuildDescription\n\n/// Build description for a Swift module.\npublic final class SwiftModuleBuildDescription {\n    /// The package this target belongs to.\n    public let package: ResolvedPackage\n\n    /// The target described by this target.\n    public let target: ResolvedModule\n\n    private let swiftTarget: SwiftModule\n\n    /// The tools version of the package that declared the target.  This can\n    /// can be used to conditionalize semantically significant changes in how\n    /// a target is built.\n    public let toolsVersion: ToolsVersion\n\n    /// The build parameters for this target.\n    let buildParameters: BuildParameters\n\n    /// The destination for while this module is built.\n    public var destination: BuildParameters.Destination {\n        self.buildParameters.destination\n    }\n\n    /// The build parameters for the macro dependencies of this target.\n    let macroBuildParameters: BuildParameters\n\n    /// Path to the temporary directory for this target.\n    let tempsPath: AbsolutePath\n\n    /// The directory containing derived sources of this target.\n    ///\n    /// These are the source files generated during the build.\n    private var derivedSources: Sources\n\n    /// These are the source files derived from plugins.\n    private var pluginDerivedSources: Sources\n\n    /// These are the resource files derived from plugins.\n    private var pluginDerivedResources: [Resource]\n\n    /// Path to the bundle generated for this module (if any).\n    var bundlePath: AbsolutePath? {\n        if let bundleName = target.underlying.potentialBundleName, needsResourceBundle {\n            let suffix = self.buildParameters.suffix\n            return self.buildParameters.bundlePath(named: bundleName + suffix)\n        } else {\n            return nil\n        }\n    }\n\n    private var needsResourceBundle: Bool {\n        return resources.filter { $0.rule != .embedInCode }.isEmpty == false\n    }\n\n    var resourceFilesToEmbed: [AbsolutePath] {\n        return resources.filter { $0.rule == .embedInCode }.map { $0.path }\n    }\n\n    /// The path to Swift source file embedding resource contents if needed.\n    private(set) var resourcesEmbeddingSource: AbsolutePath?\n\n    /// The list of all source files in the target, including the derived ones.\n    public var sources: [AbsolutePath] {\n        self.target.sources.paths + self.derivedSources.paths + self.pluginDerivedSources.paths\n    }\n\n    public var sourcesFileListPath: AbsolutePath {\n        self.tempsPath.appending(component: \"sources\")\n    }\n\n    /// The list of all resource files in the target, including the derived ones.\n    public var resources: [Resource] {\n        self.target.underlying.resources + self.pluginDerivedResources\n    }\n\n    /// The list of files in the target that were marked as ignored.\n    public var ignored: [AbsolutePath] {\n        self.target.underlying.ignored\n    }\n\n    /// The list of other kinds of files in the target.\n    public var others: [AbsolutePath] {\n        self.target.underlying.others\n    }\n\n    /// The objects in this target, containing either machine code or bitcode\n    /// depending on the build parameters used.\n    public var objects: [AbsolutePath] {\n        get throws {\n            let relativeSources = self.target.sources.relativePaths\n                + self.derivedSources.relativePaths\n                + self.pluginDerivedSources.relativePaths\n            let ltoEnabled = self.buildParameters.linkingParameters.linkTimeOptimizationMode != nil\n            let objectFileExtension = ltoEnabled ? \"bc\" : \"o\"\n            return try relativeSources.map {\n                try AbsolutePath(\n                    validating: \"\\($0.basename).\\(objectFileExtension)\",\n                    relativeTo: self.tempsPath)\n            }\n        }\n    }\n\n    var modulesPath: AbsolutePath {\n        let suffix = self.buildParameters.suffix\n        return self.buildParameters.buildPath.appending(component: \"Modules\\(suffix)\")\n    }\n\n    /// The path to the swiftmodule file after compilation.\n    public var moduleOutputPath: AbsolutePath { // note: needs to be public because of sourcekit-lsp\n        // If we're an executable and we're not allowing test targets to link against us, we hide the module.\n        let triple = buildParameters.triple\n        let allowLinkingAgainstExecutables = [.coff, .macho, .elf].contains(triple.objectFormat) && self.toolsVersion >= .v5_5\n        let dirPath = (target.type == .executable && !allowLinkingAgainstExecutables) ? self.tempsPath : self.modulesPath\n        return dirPath.appending(component: \"\\(self.target.c99name).swiftmodule\")\n    }\n\n    /// The path to the wrapped swift module which is created using the modulewrap tool. This is required\n    /// for supporting debugging on non-Darwin platforms (On Darwin, we just pass the swiftmodule to the linker\n    /// using the `-add_ast_path` flag).\n    var wrappedModuleOutputPath: AbsolutePath {\n        self.tempsPath.appending(component: self.target.c99name + \".swiftmodule.o\")\n    }\n\n    /// The path to the swiftinterface file after compilation.\n    var parseableModuleInterfaceOutputPath: AbsolutePath {\n        self.modulesPath.appending(component: self.target.c99name + \".swiftinterface\")\n    }\n\n    /// Path to the resource Info.plist file, if generated.\n    public private(set) var resourceBundleInfoPlistPath: AbsolutePath?\n\n    /// Paths to the binary libraries the target depends on.\n    var libraryBinaryPaths: Set<AbsolutePath> = []\n\n    /// Path to Windows DLLs that ship with binary libraries that need to be copied\n    /// over to the build output directory so executables that use them can find them.\n    var windowsDLLBinaryPaths: Set<AbsolutePath> = []\n\n    /// Any addition flags to be added. These flags are expected to be computed during build planning.\n    var additionalFlags: [String] = []\n\n    /// Describes the purpose of a test target, including any special roles such as containing a list of discovered\n    /// tests or serving as the manifest target which contains the main entry point.\n    public enum TestTargetRole {\n        /// An ordinary test target, defined explicitly in a package, containing test code.\n        case `default`\n\n        /// A test target which was synthesized automatically, containing a list of discovered tests\n        /// from `plain` test targets.\n        case discovery\n\n        /// A test target which was either synthesized automatically and contains an entry point file configured to run\n        /// all discovered tests, or contains a custom entry point file. In the latter case, the custom entry point file\n        /// may have been discovered in the package automatically (e.g. `XCTMain.swift`) or may have been provided\n        /// explicitly via a CLI flag.\n        case entryPoint(isSynthesized: Bool)\n    }\n\n    public let testTargetRole: TestTargetRole?\n\n    /// If this target is a test target.\n    public var isTestTarget: Bool {\n        self.testTargetRole != nil\n    }\n\n    /// True if this module needs to be parsed as a library based on the target type and the configuration\n    /// of the source code\n    var needsToBeParsedAsLibrary: Bool {\n        if buildParameters.sanitizers.sanitizers.contains(.fuzzer) {\n            return true\n        }\n\n        switch self.target.type {\n        case .library, .test:\n            return true\n        case .executable, .snippet, .macro:\n            // This deactivates heuristics in the Swift compiler that treats single-file modules and source files\n            // named \"main.swift\" specially w.r.t. whether they can have an entry point.\n            //\n            // See https://bugs.swift.org/browse/SR-14488 for discussion about improvements so that SwiftPM can\n            // convey the intent to build an executable module to the compiler regardless of the number of files\n            // in the module or their names.\n            if self.toolsVersion < .v5_5 || self.sources.count != 1 {\n                return false\n            }\n            // looking into the file content to see if it is using the @main annotation which requires parse-as-library\n            return (try? containsAtMain(fileSystem: self.fileSystem, path: self.sources[0])) ?? false\n        default:\n            return false\n        }\n    }\n\n    /// The filesystem to operate on.\n    let fileSystem: FileSystem\n\n    /// The modulemap file for this target, if any.\n    private(set) var moduleMap: AbsolutePath?\n\n    /// The results of applying any build tool plugins to this target.\n    public let buildToolPluginInvocationResults: [BuildToolPluginInvocationResult]\n\n    /// The results of running any prebuild commands for this target.\n    public let prebuildCommandResults: [CommandPluginResult]\n\n    public var requiredMacros: [ResolvedModule] {\n        get throws {\n            try self.target.recursiveModuleDependencies().filter {\n                $0.type == .macro\n            }\n        }\n    }\n\n    /// ObservabilityScope with which to emit diagnostics\n    private let observabilityScope: ObservabilityScope\n\n    /// Whether or not to generate code for test observation.\n    private let shouldGenerateTestObservation: Bool\n\n    /// Whether to disable sandboxing (e.g. for macros).\n    private let shouldDisableSandbox: Bool\n\n    /// Whether to add -static on Windows to reduce symbol exports\n    public var isWindowsStatic: Bool\n\n    /// Create a new target description with target and build parameters.\n    init(\n        package: ResolvedPackage,\n        target: ResolvedModule,\n        toolsVersion: ToolsVersion,\n        additionalFileRules: [FileRuleDescription] = [],\n        buildParameters: BuildParameters,\n        macroBuildParameters: BuildParameters,\n        buildToolPluginInvocationResults: [BuildToolPluginInvocationResult] = [],\n        prebuildCommandResults: [CommandPluginResult] = [],\n        testTargetRole: TestTargetRole? = nil,\n        shouldGenerateTestObservation: Bool = false,\n        shouldDisableSandbox: Bool,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        guard let swiftTarget = target.underlying as? SwiftModule else {\n            throw InternalError(\"underlying target type mismatch \\(target)\")\n        }\n\n        self.swiftTarget = swiftTarget\n        self.package = package\n        self.target = target\n        self.toolsVersion = toolsVersion\n        self.buildParameters = buildParameters\n        self.macroBuildParameters = macroBuildParameters\n\n        // Unless mentioned explicitly, use the target type to determine if this is a test target.\n        if let testTargetRole {\n            self.testTargetRole = testTargetRole\n        } else if target.type == .test {\n            self.testTargetRole = .default\n        } else {\n            self.testTargetRole = nil\n        }\n\n        self.tempsPath = target.tempsPath(self.buildParameters)\n        self.derivedSources = Sources(paths: [], root: self.tempsPath.appending(\"DerivedSources\"))\n        self.buildToolPluginInvocationResults = buildToolPluginInvocationResults\n        self.prebuildCommandResults = prebuildCommandResults\n        self.shouldGenerateTestObservation = shouldGenerateTestObservation\n        self.shouldDisableSandbox = shouldDisableSandbox\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n\n        let pluginGeneratedFiles = ModulesGraph.computePluginGeneratedFiles(\n            target: target,\n            toolsVersion: toolsVersion,\n            additionalFileRules: additionalFileRules,\n            buildParameters: self.buildParameters,\n            buildToolPluginInvocationResults: buildToolPluginInvocationResults,\n            prebuildCommandResults: prebuildCommandResults,\n            observabilityScope: observabilityScope\n        )\n        self.pluginDerivedSources = Sources(\n            paths: pluginGeneratedFiles.sources.map(\\.self),\n            root: buildParameters.dataPath\n        )\n        self.pluginDerivedResources = pluginGeneratedFiles.resources.values.map(\\.self)\n\n        let nonSwiftSources = pluginDerivedSources.relativePaths.filter({ $0.extension != \"swift\" })\n        if !nonSwiftSources.isEmpty {\n            for source in nonSwiftSources {\n                let absPath = pluginDerivedSources.root.appending(source)\n                observabilityScope.emit(warning: \"Only Swift is supported for generated plugin source files: \\(absPath)\")\n            }\n            self.pluginDerivedSources.relativePaths = self.pluginDerivedSources.relativePaths.filter({ $0.extension == \"swift\" })\n        }\n\n        for absPath in pluginGeneratedFiles.headers {\n            observabilityScope.emit(warning: \"Module maps generated by plugins are not supported in Swift modules: \\(absPath)\")\n        }\n        for absPath in pluginGeneratedFiles.moduleMaps {\n            observabilityScope.emit(warning: \"API Notes generated by plugins are not supported in Swift modules: \\(absPath)\")\n        }\n        for absPath in pluginGeneratedFiles.apiNotes {\n            observabilityScope.emit(warning: \"API Notes generated by plugins are not supported in Swift modules: \\(absPath)\")\n        }\n\n        // default to -static on Windows\n        self.isWindowsStatic = buildParameters.triple.isWindows()\n\n        if self.shouldEmitObjCCompatibilityHeader {\n            self.moduleMap = try self.generateModuleMap()\n        }\n\n        // Do nothing if we're not generating a bundle.\n        if self.bundlePath != nil {\n            try self.generateResourceAccessor()\n\n            let infoPlistPath = self.tempsPath.appending(\"Info.plist\")\n            if try generateResourceInfoPlist(fileSystem: self.fileSystem, target: target, path: infoPlistPath) {\n                self.resourceBundleInfoPlistPath = infoPlistPath\n            }\n        }\n\n        if !resourceFilesToEmbed.isEmpty {\n            resourcesEmbeddingSource = try addResourceEmbeddingSource()\n        }\n\n        try self.generateTestObservation()\n    }\n\n    private func generateTestObservation() throws {\n        guard target.type == .test else {\n            return\n        }\n\n        let subpath = try RelativePath(validating: \"test_observation.swift\")\n        let path = self.derivedSources.root.appending(subpath)\n\n        guard shouldGenerateTestObservation else {\n            _ = try? fileSystem.removeFileTree(path)\n            return\n        }\n\n        guard\n            self.buildParameters.triple.isDarwin() &&\n            self.buildParameters.testingParameters.experimentalTestOutput\n        else {\n            return\n        }\n\n        let content = generateTestObservationCode(buildParameters: self.buildParameters)\n\n        // FIXME: We should generate this file during the actual build.\n        self.derivedSources.relativePaths.append(subpath)\n        try self.fileSystem.writeIfChanged(path: path, string: content)\n    }\n\n    private func addResourceEmbeddingSource() throws -> AbsolutePath {\n        let subpath = try RelativePath(validating: \"embedded_resources.swift\")\n        self.derivedSources.relativePaths.append(subpath)\n        return self.derivedSources.root.appending(subpath)\n    }\n\n    /// Generate the resource bundle accessor, if appropriate.\n    private func generateResourceAccessor() throws {\n        // Do nothing if we're not generating a bundle.\n        guard let bundlePath else { return }\n\n        let mainPathSubstitution: String\n        if self.buildParameters.triple.isWASI() {\n            // We prefer compile-time evaluation of the bundle path here for WASI. There's no benefit in evaluating this\n            // at runtime, especially as `Bundle` support in WASI Foundation is partial. We expect all resource paths to\n            // evaluate to `/\\(resourceBundleName)/\\(resourcePath)`, which allows us to pass this path to JS APIs like\n            // `fetch` directly, or to `<img src=` HTML attributes. The resources are loaded from the server, and we\n            // can't hardcode the host part in the URL. Making URLs relative by starting them with\n            // `/\\(resourceBundleName)` makes it work in the browser.\n            let mainPath = try AbsolutePath(validating: Bundle.main.bundlePath)\n                .appending(component: bundlePath.basename).pathString\n            mainPathSubstitution = #\"\"\\#(mainPath.asSwiftStringLiteralConstant)\"\"#\n        } else {\n            mainPathSubstitution =\n                #\"Bundle.main.bundleURL.appendingPathComponent(\"\\#(bundlePath.basename.asSwiftStringLiteralConstant)\").path\"#\n        }\n\n        let content =\n            \"\"\"\n            import Foundation\n\n            extension Foundation.Bundle {\n                static let module: Bundle = {\n                    let mainPath = \\(mainPathSubstitution)\n                    let buildPath = \"\\(bundlePath.pathString.asSwiftStringLiteralConstant)\"\n\n                    let preferredBundle = Bundle(path: mainPath)\n\n                    guard let bundle = preferredBundle ?? Bundle(path: buildPath) else {\n                        // Users can write a function called fatalError themselves, we should be resilient against that.\n                        Swift.fatalError(\"could not load resource bundle: from \\\\(mainPath) or \\\\(buildPath)\")\n                    }\n\n                    return bundle\n                }()\n            }\n            \"\"\"\n\n        let subpath = try RelativePath(validating: \"resource_bundle_accessor.swift\")\n\n        // Add the file to the derived sources.\n        self.derivedSources.relativePaths.append(subpath)\n\n        // Write this file out.\n        // FIXME: We should generate this file during the actual build.\n        let path = self.derivedSources.root.appending(subpath)\n        try self.fileSystem.writeIfChanged(path: path, string: content)\n    }\n\n    private func macroArguments() throws -> [String] {\n        var args = [String]()\n\n        #if BUILD_MACROS_AS_DYLIBS\n        try self.requiredMacros.forEach { macro in\n            args += [\n                \"-Xfrontend\", \"-load-plugin-library\",\n                \"-Xfrontend\", macroBuildParameters.macroBinaryPath(macro).pathString\n            ]\n        }\n        #else\n        let macroModules = try self.requiredMacros\n        try macroModules.forEach { macro in\n            let executablePath = try macroBuildParameters.macroBinaryPath(macro).pathString\n            args += [\"-Xfrontend\", \"-load-plugin-executable\", \"-Xfrontend\", \"\\(executablePath)#\\(macro.c99name)\"]\n        }\n        #endif\n\n        if self.shouldDisableSandbox {\n            let toolchainSupportsDisablingSandbox = DriverSupport.checkSupportedFrontendFlags(\n                flags: [\"-disable-sandbox\"],\n                toolchain: self.buildParameters.toolchain,\n                fileSystem: fileSystem\n            )\n            if toolchainSupportsDisablingSandbox {\n                args += [\"-disable-sandbox\"]\n            } else {\n                // If there's at least one macro being used, we warn about our inability to disable sandboxing.\n                if !macroModules.isEmpty {\n                    observabilityScope.emit(warning: \"cannot disable sandboxing for Swift compilation because the selected toolchain does not support it\")\n                }\n            }\n        }\n\n        return args\n    }\n\n    /// The arguments needed to compile this target.\n    public func compileArguments() throws -> [String] {\n        var args = [String]()\n        args += try self.buildParameters.tripleArgs(for: self.target)\n\n        // pass `-v` during verbose builds.\n        if self.buildParameters.outputParameters.isVerbose {\n            args += [\"-v\"]\n        }\n\n        if self.useWholeModuleOptimization {\n            args.append(\"-whole-module-optimization\")\n            args.append(\"-num-threads\")\n            args.append(String(ProcessInfo.processInfo.activeProcessorCount))\n        } else {\n            args.append(\"-incremental\")\n            args.append(\"-enable-batch-mode\")\n        }\n\n        args += [\"-serialize-diagnostics\"]\n\n        args += self.buildParameters.indexStoreArguments(for: self.target)\n        args += self.optimizationArguments\n        args += self.testingArguments\n\n        if self.buildParameters.driverParameters.emitOptimizationRecord {\n            args += [\"-save-optimization-record\"]\n            args += [\"-g\"]\n        }\n\n        args += [\"-j\\(self.buildParameters.workers)\"]\n        args += self.activeCompilationConditions\n        args += self.additionalFlags\n        args += try self.moduleCacheArgs\n        args += self.stdlibArguments\n        args += self.buildParameters.sanitizers.compileSwiftFlags()\n        args += [\"-parseable-output\"]\n\n        // If we're compiling the main module of an executable other than the one that\n        // implements a test suite, and if the package tools version indicates that we\n        // should, we rename the `_main` entry point to `_<modulename>_main`.\n        //\n        // This will allow tests to link against the module without any conflicts. And\n        // when we link the executable, we will ask the linker to rename the entry point\n        // symbol to just `_main` again (or if the linker doesn't support it, we'll\n        // generate a source containing a redirect).\n        if (self.target.underlying as? SwiftModule)?.supportsTestableExecutablesFeature == true\n            && !self.isTestTarget && self.toolsVersion >= .v5_5\n        {\n            // We only do this if the linker supports it, as indicated by whether we\n            // can construct the linker flags. In the future we will use a generated\n            // code stub for the cases in which the linker doesn't support it, so that\n            // we can rename the symbol unconditionally.\n            // No `-` for these flags because the set of Strings in driver.supportedFrontendFlags do\n            // not have a leading `-`\n            if self.buildParameters.driverParameters.canRenameEntrypointFunctionName,\n               self.buildParameters.linkerFlagsForRenamingMainFunction(of: self.target) != nil\n            {\n                args += [\"-Xfrontend\", \"-entry-point-function-name\", \"-Xfrontend\", \"\\(self.target.c99name)_main\"]\n            }\n        }\n\n        // If the target needs to be parsed without any special semantics involving \"main.swift\", do so now.\n        if self.needsToBeParsedAsLibrary {\n            args += [\"-parse-as-library\"]\n        }\n\n        // Add -static to reduce symbol export count\n        if self.isWindowsStatic {\n            args += [\"-static\"]\n        }\n\n        // Only add the build path to the framework search path if there are binary frameworks to link against.\n        if !self.libraryBinaryPaths.isEmpty {\n            args += [\"-F\", self.buildParameters.buildPath.pathString]\n        }\n\n        // Emit the ObjC compatibility header if enabled.\n        if self.shouldEmitObjCCompatibilityHeader {\n            args += [\"-emit-objc-header\", \"-emit-objc-header-path\", self.objCompatibilityHeaderPath.pathString]\n        }\n\n        // Add arguments needed for code coverage if it is enabled.\n        if self.buildParameters.testingParameters.enableCodeCoverage {\n            args += [\"-profile-coverage-mapping\", \"-profile-generate\"]\n        }\n\n        // Add arguments to colorize output if stdout is tty\n        if self.buildParameters.outputParameters.isColorized {\n            args += [\"-color-diagnostics\"]\n        }\n\n        args += try self.cxxInteroperabilityModeArguments(\n            propagateFromCurrentModuleOtherSwiftFlags: false)\n\n        // Add arguments from declared build settings.\n        args += try self.buildSettingsFlags()\n\n        // Add the output for the `.swiftinterface`, if requested or if library evolution has been enabled some other\n        // way.\n        if self.buildParameters.driverParameters.enableParseableModuleInterfaces || args.contains(\"-enable-library-evolution\") {\n            args += [\"-emit-module-interface-path\", self.parseableModuleInterfaceOutputPath.pathString]\n        }\n\n        switch self.buildParameters.prepareForIndexing {\n        case .off:\n            break\n        case .on:\n            args += [\"-Xfrontend\", \"-experimental-lazy-typecheck\",]\n            if !args.contains(\"-enable-testing\") {\n                // enable-testing needs the non-exportable-decls\n                args += [\"-Xfrontend\", \"-experimental-skip-non-exportable-decls\"]\n            }\n            fallthrough\n        case .noLazy:\n            args += [\n                \"-Xfrontend\", \"-experimental-skip-all-function-bodies\",\n                \"-Xfrontend\", \"-experimental-allow-module-with-compiler-errors\",\n                \"-Xfrontend\", \"-empty-abi-descriptor\"\n            ]\n        }\n\n        args += self.buildParameters.toolchain.extraFlags.swiftCompilerFlags.rawFlags\n        // User arguments (from -Xswiftc) should follow generated arguments to allow user overrides\n        args += self.buildParameters.flags.swiftCompilerFlags.rawFlags\n\n        args += self.buildParameters.toolchain.extraFlags.cCompilerFlags.rawFlags.asSwiftcCCompilerFlags()\n        // User arguments (from -Xcc) should follow generated arguments to allow user overrides\n        args += self.buildParameters.flags.cCompilerFlags.rawFlags.asSwiftcCCompilerFlags()\n\n        // TODO: Pass -Xcxx flags to swiftc (#6491)\n        // Uncomment when downstream support arrives.\n        // args += self.buildParameters.toolchain.extraFlags.cxxCompilerFlags.rawFlags.asSwiftcCXXCompilerFlags()\n        // // User arguments (from -Xcxx) should follow generated arguments to allow user overrides\n        // args += self.buildParameters.flags.cxxCompilerFlags.rawFlags.asSwiftcCXXCompilerFlags()\n\n        // Enable the correct LTO mode if requested.\n        switch self.buildParameters.linkingParameters.linkTimeOptimizationMode {\n        case nil:\n            break\n        case .full:\n            args += [\"-lto=llvm-full\"]\n        case .thin:\n            args += [\"-lto=llvm-thin\"]\n        }\n\n        // Pass default include paths from the toolchain.\n        for includeSearchPath in self.buildParameters.toolchain.includeSearchPaths {\n            args += [\"-I\", includeSearchPath.pathString]\n        }\n\n        // suppress warnings if the package is remote\n        if self.package.isRemote {\n            args = try WarningControlFlags.filterSwiftWarningControlFlags(args)\n            args += [\"-suppress-warnings\"]\n        }\n\n        // Pass `-user-module-version` for versioned packages that aren't pre-releases.\n        if\n          let version = package.manifest.version,\n          version.prereleaseIdentifiers.isEmpty &&\n          version.buildMetadataIdentifiers.isEmpty &&\n          toolsVersion >= .v6_0\n        {\n            args += [\"-user-module-version\", version.description]\n        }\n\n        args += self.package.packageNameArgument(\n            target: self.target,\n            isPackageNameSupported: self.buildParameters.driverParameters.isPackageAccessModifierSupported\n        )\n        args += try self.macroArguments()\n\n        // rdar://117578677\n        // Pass -fno-omit-frame-pointer to support backtraces\n        // this can be removed once the backtracer uses DWARF instead of frame pointers\n        if let omitFramePointers = self.buildParameters.debuggingParameters.omitFramePointers {\n            if omitFramePointers {\n                args += [\"-Xcc\", \"-fomit-frame-pointer\"]\n            } else {\n                args += [\"-Xcc\", \"-fno-omit-frame-pointer\"]\n            }\n        }\n\n        return args\n    }\n\n    /// Determines the arguments needed to run `swift-symbolgraph-extract` for\n    /// this module.\n    package func symbolGraphExtractArguments() throws -> [String] {\n        var args = [String]()\n\n        args += [\"-module-name\", self.target.c99name]\n        args += try self.buildParameters.tripleArgs(for: self.target)\n        args += [\"-module-cache-path\", try self.buildParameters.moduleCache.pathString]\n\n        args += try self.cxxInteroperabilityModeArguments(\n            propagateFromCurrentModuleOtherSwiftFlags: true)\n\n        args += self.buildParameters.toolchain.extraFlags.swiftCompilerFlags.rawFlags\n\n        // Include search paths determined during planning\n        args += self.additionalFlags\n        // FIXME: only pass paths to the actual dependencies of the module\n        // Include search paths for swift module dependencies.\n        args += [\"-I\", self.modulesPath.pathString]\n\n        // FIXME: Only include valid args\n        // This condition should instead only include args which are known to be\n        // compatible instead of filtering out specific unknown args.\n        //\n        // swift-symbolgraph-extract does not support parsing `-use-ld=lld` and\n        // will silently error failing the operation.\n        args = args.filter { !$0.starts(with: \"-use-ld=\") }\n        return args\n    }\n\n    // FIXME: this function should operation on a strongly typed buildSetting\n    // Move logic from PackageBuilder here.\n    /// Determines the arguments needed for cxx interop for this module.\n    func cxxInteroperabilityModeArguments(\n        // FIXME: Remove argument\n        // This argument is added as a stop gap to support generating arguments\n        // for tools which currently don't leverage \"OTHER_SWIFT_FLAGS\". In the\n        // fullness of time this function should operate on a strongly typed\n        // \"interopMode\" property of SwiftTargetBuildDescription instead of\n        // digging through \"OTHER_SWIFT_FLAGS\" manually.\n        propagateFromCurrentModuleOtherSwiftFlags: Bool\n    ) throws -> [String] {\n        func cxxInteroperabilityModeAndStandard(\n            for module: ResolvedModule\n        ) -> [String]? {\n            let scope = self.buildParameters.createScope(for: module)\n            let flags = scope.evaluate(.OTHER_SWIFT_FLAGS)\n            let mode = flags.first { $0.hasPrefix(\"-cxx-interoperability-mode=\") }\n            guard let mode else { return nil }\n            // FIXME: Use a stored self.cxxLanguageStandard property\n            // It definitely should _never_ reach back into the manifest\n            if let cxxStandard = self.package.manifest.cxxLanguageStandard {\n                return [mode, \"-Xcc\", \"-std=\\(cxxStandard)\"]\n            } else {\n                return [mode]\n            }\n        }\n\n        if propagateFromCurrentModuleOtherSwiftFlags {\n            // Look for cxx interop mode in the current module, if set exit early,\n            // the flag is already present.\n            if let args = cxxInteroperabilityModeAndStandard(for: self.target) {\n                return args\n            }\n        }\n\n        // Implicitly propagate cxx interop flags for generated test targets.\n        // If the current module doesn't have cxx interop mode set, search\n        // through the module's dependencies looking for the a module that\n        // enables cxx interop and copy it's flag.\n        switch self.testTargetRole {\n        case .discovery, .entryPoint:\n            for module in try self.target.recursiveModuleDependencies() {\n                if let args = cxxInteroperabilityModeAndStandard(for: module) {\n                    return args\n                }\n            }\n        default: break\n        }\n        return []\n    }\n\n    /// - Parameters:\n    ///   - scanInvocation: When `true`, omit the side-effect producing arguments such as emitting a module or\n    ///     supplementary outputs.\n    ///   - writeOutputFileMap: When `false`, we assume that an output file map for this command line already exists at\n    ///     the expected location on disk. This is intended for SourceKit-LSP to get build settings for a file without\n    ///     writing out an output file map as a side effect. We expect that preparation of the module has already\n    ///     created the output file map.\n    public func emitCommandLine(scanInvocation: Bool = false, writeOutputFileMap: Bool = true) throws -> [String] {\n        var result: [String] = []\n        result.append(self.buildParameters.toolchain.swiftCompilerPath.pathString)\n\n        result.append(\"-module-name\")\n        result.append(self.target.c99name)\n        result.append(\n            contentsOf: self.package.packageNameArgument(\n                target: self.target,\n                isPackageNameSupported: self.buildParameters.driverParameters.isPackageAccessModifierSupported\n            )\n        )\n        if !scanInvocation {\n            result.append(\"-emit-dependencies\")\n\n            // FIXME: Do we always have a module?\n            result.append(\"-emit-module\")\n            result.append(\"-emit-module-path\")\n            result.append(self.moduleOutputPath.pathString)\n\n            result.append(\"-output-file-map\")\n            let outputFileMapPath = self.tempsPath.appending(\"output-file-map.json\")\n            if writeOutputFileMap {\n                // FIXME: Eliminate side effect.\n                try self.writeOutputFileMap(to: outputFileMapPath)\n            }\n            result.append(outputFileMapPath.pathString)\n        }\n\n        result.append(\"-c\")\n        result.append(contentsOf: self.sources.map(\\.pathString))\n\n        result.append(\"-I\")\n        result.append(self.modulesPath.pathString)\n\n        result += try self.compileArguments()\n        return result\n    }\n\n    /// Returns true if ObjC compatibility header should be emitted.\n    private var shouldEmitObjCCompatibilityHeader: Bool {\n        self.target.type == .library\n    }\n\n    func writeOutputFileMap(to path: AbsolutePath) throws {\n        let primateDepsPath = self.tempsPath.appending(\"primary.swiftdeps\")\n\n        var content =\n            #\"\"\"\n            {\n              \"\": {\n\n            \"\"\"#\n\n        if self.useWholeModuleOptimization {\n            let moduleName = self.target.c99name\n            content +=\n                #\"\"\"\n                    \"dependencies\": \"\\#(\n                    self.tempsPath.appending(component: moduleName + \".d\")._nativePathString(escaped: true)\n                )\",\n\n                \"\"\"#\n\n            // FIXME: Need to record this deps file for processing it later.\n            content +=\n                #\"\"\"\n                    \"object\": \"\\#(\n                    self.tempsPath.appending(component: moduleName + \".o\")._nativePathString(escaped: true)\n                )\",\n\n                \"\"\"#\n\n            if self.buildParameters.driverParameters.emitSILFiles {\n                let silPath = try self.silOutputPath()\n                content +=\n                    #\"\"\"\n                        \"sil\": \"\\#(silPath._nativePathString(escaped: true))\",\n\n                    \"\"\"#\n            }\n\n            if !self.useParallelWMO {\n                if self.buildParameters.driverParameters.emitIRFiles {\n                    let irPath = try self.irOutputPath()\n                    content +=\n                        #\"\"\"\n                            \"llvm-ir\": \"\\#(irPath._nativePathString(escaped: true))\",\n\n                        \"\"\"#\n                }\n\n                if self.buildParameters.driverParameters.emitOptimizationRecord {\n                    content +=\n                        #\"\"\"\n                            \"yaml-opt-record\": \"\\#(try self.optimizationRecordOutputPath()._nativePathString(escaped: true))\",\n\n                        \"\"\"#\n                }\n            }\n        }\n        content +=\n            #\"\"\"\n                \"swift-dependencies\": \"\\#(primateDepsPath._nativePathString(escaped: true))\"\n              },\n\n            \"\"\"#\n\n\n        // Write out the entries for each source file.\n        let sources = self.sources\n        let objects = try self.objects\n        let ltoEnabled = self.buildParameters.linkingParameters.linkTimeOptimizationMode != nil\n        let objectKey = ltoEnabled ? \"llvm-bc\" : \"object\"\n\n        for idx in 0..<sources.count {\n            let source = sources[idx]\n            let object = objects[idx]\n\n            let sourceFileName = source.basenameWithoutExt\n            let partialModulePath = self.tempsPath.appending(component: sourceFileName + \"~partial.swiftmodule\")\n            let swiftDepsPath = self.tempsPath.appending(component: sourceFileName + \".swiftdeps\")\n            let diagnosticsPath = self.diagnosticFile(sourceFile: source)\n\n            content +=\n                #\"\"\"\n                  \"\\#(source._nativePathString(escaped: true))\": {\n\n                \"\"\"#\n\n            if !self.useWholeModuleOptimization {\n                let depsPath = self.tempsPath.appending(component: sourceFileName + \".d\")\n                content +=\n                    #\"\"\"\n                        \"dependencies\": \"\\#(depsPath._nativePathString(escaped: true))\",\n\n                    \"\"\"#\n                // FIXME: Need to record this deps file for processing it later.\n            }\n\n            content +=\n                #\"\"\"\n                    \"\\#(objectKey)\": \"\\#(object._nativePathString(escaped: true))\",\n                    \"swiftmodule\": \"\\#(partialModulePath._nativePathString(escaped: true))\",\n                    \"swift-dependencies\": \"\\#(swiftDepsPath._nativePathString(escaped: true))\",\n                    \"diagnostics\": \"\\#(diagnosticsPath._nativePathString(escaped: true))\"\n                \"\"\"#\n\n            if self.buildParameters.driverParameters.emitSILFiles && !self.useWholeModuleOptimization {\n                let silPath = try self.silOutputPath(for: source)\n                content +=\n                    #\"\"\"\n                    ,\n                        \"sil\": \"\\#(silPath._nativePathString(escaped: true))\"\n                    \"\"\"#\n            }\n\n            if self.buildParameters.driverParameters.emitIRFiles {\n                let irPath = try self.irOutputPath(for: source)\n                content +=\n                    #\"\"\"\n                    ,\n                        \"llvm-ir\": \"\\#(irPath._nativePathString(escaped: true))\"\n                    \"\"\"#\n            }\n\n            if self.buildParameters.driverParameters.emitOptimizationRecord {\n                content +=\n                    #\"\"\"\n                    ,\n                        \"yaml-opt-record\": \"\\#(try self.optimizationRecordOutputPath(for: source)._nativePathString(escaped: true))\"\n                    \"\"\"#\n            }\n\n            content +=\n                #\"\"\"\n                  }\\#((idx + 1) < sources.count ? \",\" : \"\")\n\n                \"\"\"#\n        }\n\n        content += \"}\\n\"\n\n        if let silOutputDir = self.buildParameters.driverParameters.silOutputDirectory {\n            do {\n                try fileSystem.createDirectory(silOutputDir, recursive: true)\n                observabilityScope.emit(info: \"Writing SIL files to: \\(silOutputDir)\")\n            } catch {\n                throw StringError(\"Failed to create SIL output directory at \\(silOutputDir): \\(error)\")\n            }\n        } else if self.buildParameters.driverParameters.emitSILFiles {\n            observabilityScope.emit(info: \"Writing SIL files to: \\(self.tempsPath)\")\n        }\n\n        if let irOutputDir = self.buildParameters.driverParameters.irOutputDirectory {\n            do {\n                try fileSystem.createDirectory(irOutputDir, recursive: true)\n                observabilityScope.emit(info: \"Writing LLVM IR files to: \\(irOutputDir)\")\n            } catch {\n                throw StringError(\"Failed to create LLVM IR output directory at \\(irOutputDir): \\(error)\")\n            }\n        } else if self.buildParameters.driverParameters.emitIRFiles {\n            observabilityScope.emit(info: \"Writing LLVM IR files to: \\(self.tempsPath)\")\n        }\n\n        if let optRecordDir = self.buildParameters.driverParameters.optimizationRecordDirectory {\n            do {\n                try fileSystem.createDirectory(optRecordDir, recursive: true)\n                observabilityScope.emit(info: \"Writing optimization records to: \\(optRecordDir)\")\n            } catch {\n                throw StringError(\"Failed to create optimization record output directory at \\(optRecordDir): \\(error)\")\n            }\n        } else if self.buildParameters.driverParameters.emitOptimizationRecord {\n            observabilityScope.emit(info: \"Writing optimization records to: \\(self.tempsPath)\")\n        }\n\n        try fileSystem.createDirectory(path.parentDirectory, recursive: true)\n        try self.fileSystem.writeFileContents(path, bytes: .init(encodingAsUTF8: content), atomically: true)\n    }\n\n    /// Returns the path for SIL output file.\n    /// In WMO mode, returns the path for the whole module's SIL output.\n    /// In non-WMO mode, returns the path for the given source file's SIL output.\n    private func silOutputPath(for source: AbsolutePath? = nil) throws -> AbsolutePath {\n        let outputDir = self.buildParameters.driverParameters.silOutputDirectory ?? self.tempsPath\n        let baseName: String\n        if self.useWholeModuleOptimization {\n            baseName = self.target.c99name\n        } else {\n            guard let source = source else {\n                throw InternalError(\"Source file required for SIL output path in non-WMO mode\")\n            }\n            baseName = source.basenameWithoutExt\n        }\n        return outputDir.appending(component: baseName + \".sil\")\n    }\n\n    private func irOutputPath(for source: AbsolutePath? = nil) throws -> AbsolutePath {\n        let outputDir = self.buildParameters.driverParameters.irOutputDirectory ?? self.tempsPath\n        let baseName: String\n        if let source {\n            baseName = source.basenameWithoutExt\n        } else if self.useWholeModuleOptimization {\n            baseName = self.target.c99name\n        } else {\n            throw InternalError(\"Source file required for IR output path in non-WMO mode\")\n        }\n        return outputDir.appending(component: baseName + \".ll\")\n    }\n\n    private func optimizationRecordOutputPath(for source: AbsolutePath? = nil) throws -> AbsolutePath {\n        let outputDir = self.buildParameters.driverParameters.optimizationRecordDirectory ?? self.tempsPath\n        let baseName: String\n        if let source {\n            baseName = source.basenameWithoutExt\n        } else if self.useWholeModuleOptimization {\n            baseName = self.target.c99name\n        } else {\n            throw InternalError(\"Source file required for optimization record path in non-WMO mode\")\n        }\n        return outputDir.appending(component: baseName + \".opt.yaml\")\n    }\n\n    /// Directory for the the compatibility header and module map generated for this target.\n    /// The whole directory should be usable as a header search path.\n    private var compatibilityHeaderDirectory: AbsolutePath {\n        tempsPath.appending(\"include\")\n    }\n\n    /// Generates the module map for the Swift target and returns its path.\n    private func generateModuleMap() throws -> AbsolutePath {\n        let path = self.compatibilityHeaderDirectory.appending(component: moduleMapFilename)\n\n        let bytes = ByteString(\n            #\"\"\"\n            module \\#(self.target.c99name) {\n                header \"\\#(self.objCompatibilityHeaderPath.pathString)\"\n            }\n\n            \"\"\"#.utf8\n        )\n\n        // Return early if the contents are identical.\n        if self.fileSystem.isFile(path), try self.fileSystem.readFileContents(path) == bytes {\n            return path\n        }\n\n        try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)\n        try self.fileSystem.writeFileContents(path, bytes: bytes)\n\n        return path\n    }\n\n    /// Returns the path to the ObjC compatibility header for this Swift target.\n    var objCompatibilityHeaderPath: AbsolutePath {\n        self.compatibilityHeaderDirectory.appending(\"\\(self.target.name)-Swift.h\")\n    }\n\n    /// Returns the build flags from the declared build settings.\n    private func buildSettingsFlags() throws -> [String] {\n        let scope = self.buildParameters.createScope(for: self.target)\n        var flags: [String] = []\n\n        // A custom swift version.\n        flags += scope.evaluate(.SWIFT_VERSION).flatMap { [\"-swift-version\", $0] }\n\n        // Swift defines.\n        let swiftDefines = scope.evaluate(.SWIFT_ACTIVE_COMPILATION_CONDITIONS)\n        flags += swiftDefines.map { \"-D\" + $0 }\n\n        // Other Swift flags.\n        flags += scope.evaluate(.OTHER_SWIFT_FLAGS)\n\n        // Add C flags by prefixing them with -Xcc.\n        //\n        // C defines.\n        let cDefines = scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS)\n        flags += cDefines.flatMap { [\"-Xcc\", \"-D\" + $0] }\n\n        // Header search paths.\n        let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)\n        flags += try headerSearchPaths.flatMap { path in\n            [\"-Xcc\", \"-I\\(try AbsolutePath(validating: path, relativeTo: target.sources.root).pathString)\"]\n        }\n\n        // Other C flags.\n        flags += scope.evaluate(.OTHER_CFLAGS).flatMap { [\"-Xcc\", $0] }\n\n        // Prebuilt include paths\n        flags += scope.evaluate(.PREBUILT_INCLUDE_PATHS).flatMap { [\"-I\", $0] }\n\n        // Include path for the toolchain's copy of SwiftSyntax.\n        #if BUILD_MACROS_AS_DYLIBS\n        if module.type == .macro {\n            flags += try [\"-I\", self.defaultBuildParameters.toolchain.hostLibDir.pathString]\n        }\n        #endif\n\n        return flags\n    }\n\n    /// A list of compilation conditions to enable for conditional compilation expressions.\n    private var activeCompilationConditions: [String] {\n        var compilationConditions = [\"-DSWIFT_PACKAGE\"]\n\n        switch self.buildParameters.configuration {\n        case .debug:\n            compilationConditions += [\"-DDEBUG\"]\n        case .release:\n            break\n        }\n\n        if bundlePath != nil {\n            compilationConditions += [\"-DSWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\"]\n        } else {\n            compilationConditions += [\"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n        }\n\n        return compilationConditions\n    }\n\n    /// Optimization arguments according to the build configuration.\n    private var optimizationArguments: [String] {\n        switch self.buildParameters.configuration {\n        case .debug:\n            return [\"-Onone\"]\n        case .release:\n            return [\"-O\"]\n        }\n    }\n\n    /// Testing arguments according to the build configuration.\n    private var testingArguments: [String] {\n        if self.isTestTarget {\n            // test targets must be built with -enable-testing\n            // since its required for test discovery (the non objective-c reflection kind)\n            var result = [\"-enable-testing\"]\n\n            // Test targets need to enable cross-import overlays because Swift\n            // Testing cannot directly link to most other modules and needs to\n            // provide API that works with e.g. Foundation. (Developers can\n            // override this flag by passing -disable-cross-import-overlays.)\n            result += [\"-Xfrontend\", \"-enable-cross-import-overlays\"]\n\n            return result\n        } else if self.buildParameters.enableTestability {\n            return [\"-enable-testing\"]\n        } else {\n            return []\n        }\n    }\n\n    /// Module cache arguments.\n    private var moduleCacheArgs: [String] {\n        get throws {\n            [\"-module-cache-path\", try self.buildParameters.moduleCache.pathString]\n        }\n    }\n\n    private var stdlibArguments: [String] {\n        var arguments: [String] = []\n\n        let isLinkingStaticStdlib = self.buildParameters.linkingParameters.shouldLinkStaticSwiftStdlib\n            && self.buildParameters.triple.isSupportingStaticStdlib\n        if isLinkingStaticStdlib {\n            arguments += [\"-static-stdlib\"]\n        }\n\n        if let resourcesPath = self.buildParameters.toolchain.swiftResourcesPath(isStatic: isLinkingStaticStdlib) {\n            arguments += [\"-resource-dir\", \"\\(resourcesPath)\"]\n        }\n\n        return arguments\n    }\n\n    package var isEmbeddedSwift: Bool {\n        // If the target explicitly declares that it should build with Embedded\n        // Swift, then true.\n        let buildSettings = self.target.underlying.buildSettingsDescription\n        let swiftSettings = buildSettings.swiftSettings.map(\\.kind)\n        for case .enableExperimentalFeature(\"Embedded\") in swiftSettings {\n            return true\n        }\n\n        // Otherwise dig through flags looking for -enable-experimental-feature\n        // Embedded. This is needed to handle Embedded being set via:\n        // - unsafeFlags\n        // - swift build cli flags\n        // - toolset flags\n        let queryFlags = [\"-enable-experimental-feature\", \"Embedded\"]\n\n        let toolchainFlags = self.buildParameters.toolchain.extraFlags.swiftCompilerFlags\n        if toolchainFlags.rawFlags.contains(queryFlags) { return true }\n\n        let generalFlags = self.buildParameters.flags.swiftCompilerFlags\n        if generalFlags.rawFlags.contains(queryFlags) { return true }\n\n        return false\n    }\n\n    /// Whether to build Swift code with whole module optimization (WMO)\n    /// enabled.\n    package var useWholeModuleOptimization: Bool {\n        if self.isEmbeddedSwift { return true }\n\n        switch self.buildParameters.configuration {\n        case .debug:\n            return false\n        case .release:\n            return true\n        }\n    }\n\n    /// Whether the Swift driver will use multi-threaded WMO.\n    /// With only one source file, the driver treats it as single-threaded.\n    var useParallelWMO: Bool {\n        ProcessInfo.processInfo.activeProcessorCount > 1 && self.sources.count > 1\n    }\n}\n\nextension SwiftModuleBuildDescription {\n    package func dependencies(\n        using plan: BuildPlan\n    ) -> [ModuleBuildDescription.Dependency] {\n        ModuleBuildDescription.swift(self).dependencies(using: plan)\n    }\n\n    package func recursiveLinkDependencies(\n        using plan: BuildPlan\n    ) -> [ModuleBuildDescription.Dependency] {\n        ModuleBuildDescription.swift(self).recursiveLinkDependencies(using: plan)\n    }\n\n    package func recursiveDependencies(\n        using plan: BuildPlan\n    ) -> [ModuleBuildDescription.Dependency] {\n        ModuleBuildDescription.swift(self).recursiveDependencies(using: plan)\n    }\n}\n\nextension SwiftModuleBuildDescription {\n    package var diagnosticFiles: [AbsolutePath] {\n        // WMO builds have a single frontend invocation and produce a single\n        // diagnostic file named after the module.\n        if self.useWholeModuleOptimization {\n            return [\n                self.diagnosticFile(name: self.target.name)\n            ]\n        }\n\n        return self.sources.map(self.diagnosticFile(sourceFile:))\n    }\n\n    private func diagnosticFile(name: String) -> AbsolutePath {\n        self.tempsPath.appending(component: \"\\(name).dia\")\n    }\n\n    private func diagnosticFile(sourceFile: AbsolutePath) -> AbsolutePath {\n        self.diagnosticFile(name: sourceFile.basenameWithoutExt)\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildManifest/LLBuildManifestBuilder+Clang.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct LLBuildManifest.Node\nimport struct Basics.AbsolutePath\nimport struct Basics.InternalError\nimport class Basics.ObservabilityScope\nimport struct PackageGraph.ResolvedModule\nimport PackageModel\nimport SPMBuildCore\n\nextension LLBuildManifestBuilder {\n    /// Create a llbuild target for a Clang target description.\n    func createClangCompileCommand(\n        _ target: ClangModuleBuildDescription\n    ) throws {\n        var inputs: [Node] = []\n\n        // Add resources node as the input to the target. This isn't great because we\n        // don't need to block building of a module until its resources are assembled but\n        // we don't currently have a good way to express that resources should be built\n        // whenever a module is being built.\n        if let resourcesNode = try self.createResourcesBundle(for: .clang(target)) {\n            inputs.append(resourcesNode)\n        }\n\n        func addStaticTargetInputs(_ description: ModuleBuildDescription?) {\n            if case .swift(let desc) = description, desc.target.type == .library {\n                inputs.append(file: desc.moduleOutputPath)\n            }\n        }\n\n        for dependency in target.dependencies(using: self.plan) {\n            switch dependency {\n            case .module(_, let description):\n                addStaticTargetInputs(description)\n\n            case .product(let product, let productDescription):\n                switch product.type {\n                case .executable, .snippet, .library(.dynamic), .macro:\n                    guard let productDescription else {\n                        throw InternalError(\"No build description for product: \\(product)\")\n                    }\n                    // Establish a dependency on binary of the product.\n                    try inputs.append(file: productDescription.binaryPath)\n\n                case .library(.automatic), .library(.static), .plugin:\n                    for module in product.modules {\n                        let dependencyDescription = self.plan.description(\n                            for: module,\n                            context: product.type == .plugin ? .host : target.destination\n                        )\n                        addStaticTargetInputs(dependencyDescription)\n                    }\n                case .test:\n                    break\n                }\n            }\n        }\n\n        for binaryPath in target.libraryBinaryPaths {\n            let path = target.buildParameters.destinationPath(forBinaryAt: binaryPath)\n            if self.fileSystem.isDirectory(binaryPath) {\n                inputs.append(directory: path)\n            } else {\n                inputs.append(file: path)\n            }\n        }\n\n        var objectFileNodes: [Node] = []\n\n        for path in try target.compilePaths() {\n            let args = try target.emitCommandLine(for: path.source)\n\n            let objectFileNode: Node = .file(path.object)\n            objectFileNodes.append(objectFileNode)\n\n            self.manifest.addClangCmd(\n                name: path.object.pathString,\n                description: \"Compiling \\(target.target.name) \\(path.filename)\",\n                inputs: inputs + [.file(path.source)],\n                outputs: [objectFileNode],\n                arguments: args,\n                dependencies: path.deps.pathString\n            )\n        }\n\n        let additionalInputs = try addBuildToolPlugins(.clang(target))\n\n        // Create a phony node to represent the entire target.\n        let targetName = target.llbuildTargetName\n        let output: Node = .virtual(targetName)\n\n        self.manifest.addNode(output, toTarget: targetName)\n        self.manifest.addPhonyCmd(\n            name: output.name,\n            inputs: objectFileNodes + additionalInputs,\n            outputs: [output]\n        )\n\n        if self.plan.graph.isInRootPackages(target.target, satisfying: target.buildParameters.buildEnvironment) {\n            if !target.isTestTarget {\n                self.addNode(output, toTarget: .main)\n            }\n            self.addNode(output, toTarget: .test)\n        }\n    }\n\n    /// Create a llbuild target for a Clang target preparation\n    func createClangPrepareCommand(\n        _ target: ClangModuleBuildDescription\n    ) throws {\n        // Create the node for the target so you can --target it.\n        // It is a no-op for index preparation.\n        let targetName = target.llbuildTargetName\n        let output: Node = .virtual(targetName)\n        self.manifest.addNode(output, toTarget: targetName)\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildManifest/LLBuildManifestBuilder+Product.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageModel\n\nimport struct Basics.AbsolutePath\nimport struct Basics.InternalError\nimport struct LLBuildManifest.Node\nimport struct SPMBuildCore.BuildParameters\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedProduct\n\nextension LLBuildManifestBuilder {\n    func createProductCommand(_ buildProduct: ProductBuildDescription) throws {\n        let cmdName = try buildProduct.commandName\n\n        // Add dependency on Info.plist generation on Darwin platforms.\n        let testInputs: [AbsolutePath]\n        if buildProduct.product.type == .test\n            && buildProduct.buildParameters.triple.isDarwin()\n            && buildProduct.buildParameters.testingParameters.experimentalTestOutput {\n            let testBundleInfoPlistPath = try buildProduct.binaryPath.parentDirectory.parentDirectory.appending(component: \"Info.plist\")\n            testInputs = [testBundleInfoPlistPath]\n\n            self.manifest.addWriteInfoPlistCommand(\n                principalClass: \"\\(buildProduct.product.modules[buildProduct.product.modules.startIndex].c99name).SwiftPMXCTestObserver\",\n                outputPath: testBundleInfoPlistPath\n            )\n        } else {\n            testInputs = []\n        }\n\n        // Create a phony node to represent the entire target.\n        let targetName = try buildProduct.llbuildTargetName\n        let output: Node = .virtual(targetName)\n\n        let finalProductNode: Node\n        switch buildProduct.product.type {\n        case .library(.static):\n            finalProductNode = try .file(buildProduct.binaryPath)\n            try self.manifest.addShellCmd(\n                name: cmdName,\n                description: \"Archiving \\(buildProduct.binaryPath.prettyPath())\",\n                inputs: (buildProduct.objects + [buildProduct.linkFileListPath]).map(Node.file),\n                outputs: [finalProductNode],\n                arguments: try buildProduct.archiveArguments()\n            )\n\n        default:\n            let inputs = try buildProduct.objects\n                + buildProduct.dylibs.map { try $0.binaryPath }\n                + [buildProduct.linkFileListPath]\n                + testInputs\n\n            let shouldCodeSign: Bool\n            let linkedBinaryNode: Node\n            let linkedBinaryPath = try buildProduct.binaryPath\n            if case .executable = buildProduct.product.type,\n               buildProduct.buildParameters.triple.isMacOSX,\n               buildProduct.buildParameters.debuggingParameters.shouldEnableDebuggingEntitlement {\n                shouldCodeSign = true\n                linkedBinaryNode = try .file(buildProduct.binaryPath, isMutated: true)\n            } else {\n                shouldCodeSign = false\n                linkedBinaryNode = try .file(buildProduct.binaryPath)\n            }\n\n            try self.manifest.addShellCmd(\n                name: cmdName,\n                description: \"Linking \\(buildProduct.binaryPath.prettyPath())\",\n                inputs: inputs.map(Node.file),\n                outputs: [linkedBinaryNode],\n                arguments: try buildProduct.linkArguments()\n            )\n\n            if shouldCodeSign {\n                let basename = try buildProduct.binaryPath.basename\n                let plistPath = try buildProduct.binaryPath.parentDirectory\n                    .appending(component: \"\\(basename)-entitlement.plist\")\n                self.manifest.addEntitlementPlistCommand(\n                    entitlement: \"com.apple.security.get-task-allow\",\n                    outputPath: plistPath\n                )\n\n                let cmdName = try buildProduct.commandName\n                let codeSigningOutput = Node.virtual(targetName + \"-CodeSigning\")\n                try self.manifest.addShellCmd(\n                    name: \"\\(cmdName)-entitlements\",\n                    description: \"Applying debug entitlements to \\(buildProduct.binaryPath.prettyPath())\",\n                    inputs: [linkedBinaryNode, .file(plistPath)],\n                    outputs: [codeSigningOutput],\n                    arguments: buildProduct.codeSigningArguments(plistPath: plistPath, binaryPath: linkedBinaryPath)\n                )\n                finalProductNode = codeSigningOutput\n            } else {\n                finalProductNode = linkedBinaryNode\n            }\n        }\n\n        self.manifest.addNode(output, toTarget: targetName)\n        self.manifest.addPhonyCmd(\n            name: output.name,\n            inputs: [finalProductNode],\n            outputs: [output]\n        )\n\n        if self.plan.graph.reachableProducts.contains(id: buildProduct.product.id) {\n            if buildProduct.product.type != .test {\n                self.addNode(output, toTarget: .main)\n            }\n            self.addNode(output, toTarget: .test)\n        }\n\n        self.manifest.addWriteLinkFileListCommand(\n            objects: Array(buildProduct.objects),\n            linkFileListPath: buildProduct.linkFileListPath\n        )\n    }\n}\n\nextension ProductBuildDescription {\n    package var llbuildTargetName: String {\n        get throws {\n            try self.product.getLLBuildTargetName(buildParameters: self.buildParameters)\n        }\n    }\n\n    package var commandName: String {\n        get throws {\n            try \"C.\\(self.llbuildTargetName)\\(self.buildParameters.suffix)\"\n        }\n    }\n}\n\nfileprivate func llbuildNameWithoutExtension(\n    for product: String,\n    buildParameters: BuildParameters\n) -> String {\n    \"\\(product)-\\(buildParameters.triple.tripleString)-\\(buildParameters.buildConfig)\\(buildParameters.suffix)\"\n}\n\nfileprivate func executableName(\n    for product: String,\n    buildParameters: BuildParameters\n) -> String {\n    \"\\(llbuildNameWithoutExtension(for: product, buildParameters: buildParameters)).exe\"\n}\n\nfileprivate func dynamicLibraryName(\n    for product: String,\n    buildParameters: BuildParameters\n) -> String {\n    \"\\(llbuildNameWithoutExtension(for: product, buildParameters: buildParameters)).dylib\"\n}\n\nfileprivate func staticLibraryName(\n    for product: String,\n    buildParameters: BuildParameters\n) -> String {\n    \"\\(llbuildNameWithoutExtension(for: product, buildParameters: buildParameters)).a\"\n}\n\nfileprivate func testName(\n    for testProduct: String,\n    buildParameters: BuildParameters\n) -> String {\n    \"\\(llbuildNameWithoutExtension(for: testProduct, buildParameters: buildParameters)).test\"\n}\n\nfunc getLLBuildTargetName(\n    macro: ResolvedModule,\n    buildParameters: BuildParameters\n) -> String {\n    assert(macro.type == .macro)\n    #if BUILD_MACROS_AS_DYLIBS\n    return dynamicLibraryName(for: macro.name, buildParameters: buildParameters)\n    #else\n    return executableName(for: macro.name, buildParameters: buildParameters)\n    #endif\n}\n\nextension ResolvedProduct {\n    public func getLLBuildTargetName(buildParameters: BuildParameters) throws -> String {\n        switch type {\n        case .library(.dynamic):\n            return dynamicLibraryName(for: self.name, buildParameters: buildParameters)\n        case .test:\n            return testName(for: self.name, buildParameters: buildParameters)\n        case .library(.static):\n            return staticLibraryName(for: self.name, buildParameters: buildParameters)\n        case .library(.automatic):\n            throw InternalError(\"automatic library not supported\")\n        case .executable, .snippet:\n            return executableName(for: self.name, buildParameters: buildParameters)\n        case .macro:\n            guard let macroModule = self.modules.first else {\n                throw InternalError(\"macro product \\(self.name) has no targets\")\n            }\n            return Build.getLLBuildTargetName(macro: macroModule, buildParameters: buildParameters)\n        case .plugin:\n            throw InternalError(\"unexpectedly asked for the llbuild target name of a plugin product\")\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildManifest/LLBuildManifestBuilder+Resources.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct LLBuildManifest.Node\nimport struct Basics.RelativePath\n\nimport PackageModel\n\nextension LLBuildManifestBuilder {\n    /// Adds command for creating the resources bundle of the given target.\n    ///\n    /// Returns the virtual node that will build the entire bundle.\n    func createResourcesBundle(\n        for target: ModuleBuildDescription\n    ) throws -> Node? {\n        guard let bundlePath = target.bundlePath else { return nil }\n\n        var outputs: [Node] = []\n\n        let infoPlistDestination = try RelativePath(validating: \"Info.plist\")\n\n        // Create a copy command for each resource file.\n        for resource in target.resources {\n            switch resource.rule {\n            case .copy, .process:\n                let destination = try bundlePath.appending(resource.destination)\n                let (_, output) = addCopyCommand(from: resource.path, to: destination)\n                outputs.append(output)\n            case .embedInCode:\n                break\n            }\n        }\n\n        // Create a copy command for the Info.plist if a resource with the same name doesn't exist yet.\n        if let infoPlistPath = target.resourceBundleInfoPlistPath {\n            let destination = bundlePath.appending(infoPlistDestination)\n            let (_, output) = addCopyCommand(from: infoPlistPath, to: destination)\n            outputs.append(output)\n        }\n\n        let cmdName = target.llbuildResourcesCmdName\n        self.manifest.addPhonyCmd(name: cmdName, inputs: outputs, outputs: [.virtual(cmdName)])\n\n        return .virtual(cmdName)\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildManifest/LLBuildManifestBuilder+Swift.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.InternalError\nimport struct Basics.AbsolutePath\nimport struct Basics.RelativePath\nimport struct Basics.TSCAbsolutePath\nimport struct LLBuildManifest.Node\nimport struct LLBuildManifest.LLBuildManifest\nimport struct SPMBuildCore.BuildParameters\nimport struct PackageGraph.ResolvedModule\nimport protocol TSCBasic.FileSystem\nimport func TSCBasic.topologicalSort\nimport struct Basics.Environment\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import class DriverSupport.SPMSwiftDriverExecutor\n@_implementationOnly import Foundation\n@_implementationOnly import SwiftDriver\n@_implementationOnly import TSCUtility\n#else\nimport class DriverSupport.SPMSwiftDriverExecutor\nimport Foundation\nimport SwiftDriver\nimport TSCUtility\n#endif\n\nimport PackageModel\n\nextension LLBuildManifestBuilder {\n    /// Create a llbuild target for a Swift module description.\n    func createSwiftCompileCommand(\n        _ target: SwiftModuleBuildDescription\n    ) throws {\n        // Inputs.\n        let inputs = try self.computeSwiftCompileCmdInputs(target)\n\n        // Outputs.\n        let objectNodes = target.buildParameters.prepareForIndexing == .off ? try target.objects.map(Node.file) : []\n        let moduleNode = Node.file(target.moduleOutputPath)\n        let cmdOutputs = objectNodes + [moduleNode]\n\n        if target.buildParameters.driverParameters.useIntegratedSwiftDriver {\n            try self.addSwiftCmdsViaIntegratedDriver(\n                target,\n                inputs: inputs,\n                moduleNode: moduleNode\n            )\n        } else {\n            try self.addCmdWithBuiltinSwiftTool(target, inputs: inputs, cmdOutputs: cmdOutputs)\n        }\n\n        self.addTargetCmd(target, cmdOutputs: cmdOutputs)\n        try self.addModuleWrapCmd(target)\n    }\n\n    private func addSwiftCmdsViaIntegratedDriver(\n        _ target: SwiftModuleBuildDescription,\n        inputs: [Node],\n        moduleNode: Node\n    ) throws {\n        // Use the integrated Swift driver to compute the set of frontend\n        // jobs needed to build this Swift module.\n        var commandLine = try target.emitCommandLine()\n        commandLine.append(\"-driver-use-frontend-path\")\n        commandLine.append(target.buildParameters.toolchain.swiftCompilerPath.pathString)\n        // FIXME: At some point SwiftPM should provide its own executor for\n        // running jobs/launching processes during planning\n        let resolver = try ArgsResolver(fileSystem: target.fileSystem)\n        let executor = SPMSwiftDriverExecutor(\n            resolver: resolver,\n            fileSystem: target.fileSystem,\n            env: Environment.current\n        )\n        var driver = try Driver(\n            args: commandLine,\n            diagnosticsOutput: .handler(self.observabilityScope.makeDiagnosticsHandler()),\n            fileSystem: self.fileSystem,\n            executor: executor,\n            compilerIntegratedTooling: false\n        )\n        try driver.checkLDPathOption(commandLine: commandLine)\n\n        let jobs = try driver.planBuild()\n        try self.addSwiftDriverJobs(\n            for: target,\n            jobs: jobs,\n            inputs: inputs,\n            resolver: resolver,\n            isMainModule: { driver.isExplicitMainModuleJob(job: $0) }\n        )\n    }\n\n    private func addSwiftDriverJobs(\n        for targetDescription: SwiftModuleBuildDescription,\n        jobs: [Job],\n        inputs: [Node],\n        resolver: ArgsResolver,\n        isMainModule: (Job) -> Bool,\n    ) throws {\n        // Add build jobs to the manifest\n        for job in jobs {\n            let tool = try resolver.resolve(.path(job.tool))\n            let commandLine = try job.commandLine.map { try resolver.resolve($0) }\n            let arguments = [tool] + commandLine\n\n            let jobInputs = try job.inputs.map { try $0.resolveToNode(fileSystem: self.fileSystem) }\n            let jobOutputs = try job.outputs.map { try $0.resolveToNode(fileSystem: self.fileSystem) }\n\n            // Add module dependencies as inputs to the main module build command.\n            //\n            // Jobs for a module's intermediate build artifacts, such as PCMs or\n            // modules built from a .swiftinterface, do not have a\n            // dependency on cross-module build products. If multiple targets share\n            // common intermediate dependency modules, such dependencies can lead\n            // to cycles in the resulting manifest.\n            var manifestNodeInputs: [Node] = []\n            if !isMainModule(job) {\n                manifestNodeInputs = jobInputs\n            } else {\n                manifestNodeInputs = (inputs + jobInputs).uniqued()\n            }\n\n            guard let firstJobOutput = jobOutputs.first else {\n                throw InternalError(\"unknown first JobOutput\")\n            }\n\n            let moduleName = targetDescription.target.c99name\n            let packageName = targetDescription.package.identity.description.spm_mangledToC99ExtendedIdentifier()\n            let description = job.description\n            if job.kind.isSwiftFrontend {\n                self.manifest.addSwiftFrontendCmd(\n                    name: firstJobOutput.name,\n                    moduleName: moduleName,\n                    packageName: packageName,\n                    description: description,\n                    inputs: manifestNodeInputs,\n                    outputs: jobOutputs,\n                    arguments: arguments\n                )\n            } else {\n                self.manifest.addShellCmd(\n                    name: firstJobOutput.name,\n                    description: description,\n                    inputs: manifestNodeInputs,\n                    outputs: jobOutputs,\n                    arguments: arguments\n                )\n            }\n        }\n    }\n\n    private func addCmdWithBuiltinSwiftTool(\n        _ target: SwiftModuleBuildDescription,\n        inputs: [Node],\n        cmdOutputs: [Node]\n    ) throws {\n        let isLibrary = target.target.type == .library || target.target.type == .test\n        let cmdName = target.getCommandName()\n\n        self.manifest.addWriteSourcesFileListCommand(sources: target.sources, sourcesFileListPath: target.sourcesFileListPath)\n        let outputFileMapPath = target.tempsPath.appending(\"output-file-map.json\")\n        // FIXME: Eliminate side effect.\n        try target.writeOutputFileMap(to: outputFileMapPath)\n        self.manifest.addSwiftCmd(\n            name: cmdName,\n            inputs: inputs + [Node.file(target.sourcesFileListPath)],\n            outputs: cmdOutputs,\n            executable: target.buildParameters.toolchain.swiftCompilerPath,\n            moduleName: target.target.c99name,\n            moduleAliases: target.target.moduleAliases,\n            moduleOutputPath: target.moduleOutputPath,\n            importPath: target.modulesPath,\n            tempsPath: target.tempsPath,\n            objects: try target.objects,\n            otherArguments: try target.compileArguments(),\n            sources: target.sources,\n            fileList: target.sourcesFileListPath,\n            isLibrary: isLibrary,\n            wholeModuleOptimization: target.useWholeModuleOptimization,\n            outputFileMapPath: outputFileMapPath,\n            prepareForIndexing: target.buildParameters.prepareForIndexing != .off\n        )\n    }\n\n    private func computeSwiftCompileCmdInputs(\n        _ target: SwiftModuleBuildDescription\n    ) throws -> [Node] {\n        var inputs = target.sources.map(Node.file)\n\n        let swiftVersionFilePath = addSwiftGetVersionCommand(buildParameters: target.buildParameters)\n        inputs.append(.file(swiftVersionFilePath))\n\n        // Add resources node as the input to the module. This isn't great because we\n        // don't need to block building of a module until its resources are assembled but\n        // we don't currently have a good way to express that resources should be built\n        // whenever a module is being built.\n        if let resourcesNode = try createResourcesBundle(for: .swift(target)) {\n            inputs.append(resourcesNode)\n        }\n\n        if let resourcesEmbeddingSource = target.resourcesEmbeddingSource {\n            let resourceFilesToEmbed = target.resourceFilesToEmbed\n            self.manifest.addWriteEmbeddedResourcesCommand(resources: resourceFilesToEmbed, outputPath: resourcesEmbeddingSource)\n        }\n\n        let prepareForIndexing = target.buildParameters.prepareForIndexing\n\n        func addStaticTargetInputs(_ module: ResolvedModule, _ description: ModuleBuildDescription?) throws {\n            // Ignore C Modules.\n            if module.underlying is SystemLibraryModule { return }\n            // Ignore Binary Modules.\n            if module.underlying is BinaryModule { return }\n            // Ignore Plugin Modules.\n            if module.underlying is PluginModule { return }\n\n            if target.target.platformConstraint == .all && module.platformConstraint == .host {\n                // Skip module that is host only.\n                // This only happens when the target isn't actually referenced by the root package.\n                return\n            }\n\n            guard let description else {\n                throw InternalError(\"No build description for module: \\(module)\")\n            }\n\n            // Depend on the binary for executable targets.\n            if module.type == .executable && prepareForIndexing == .off {\n                // FIXME: Optimize. Build plan could build a mapping between executable modules\n                // and their products to speed up search here, which is inefficient if the plan\n                // contains a lot of products.\n                if let productDescription = try plan.productMap.values.first(where: {\n                    try $0.product.type == .executable &&\n                        $0.product.executableModule.id == module.id &&\n                        $0.destination == description.destination\n                }) {\n                    try inputs.append(file: productDescription.binaryPath)\n                }\n                return\n            }\n\n            switch description {\n            case .swift(let swiftDescription):\n                inputs.append(file: swiftDescription.moduleOutputPath)\n            case .clang(let clangDescription):\n                if prepareForIndexing != .off {\n                    // In preparation, we're only building swiftmodules\n                    // propagate the dependency to the header files in this target\n                    for header in clangDescription.clangTarget.headers {\n                        inputs.append(file: header)\n                    }\n                } else {\n                    for object in try clangDescription.objects {\n                        inputs.append(file: object)\n                    }\n                    // Make sure these files get generated\n                    for interface in clangDescription.pluginDerivedInterfaceFiles {\n                        inputs.append(file: interface)\n                    }\n                }\n            }\n        }\n\n        for dependency in target.dependencies(using: self.plan) {\n            switch dependency {\n            case .module(let module, let description):\n                try addStaticTargetInputs(module, description)\n\n            case .product(let product, let productDescription):\n                switch product.type {\n                case .executable, .snippet, .library(.dynamic), .macro:\n                    guard let productDescription else {\n                        throw InternalError(\"No description for product: \\(product)\")\n                    }\n                    // Establish a dependency on binary of the product.\n                    try inputs.append(file: productDescription.binaryPath)\n\n                // For automatic and static libraries, and plugins, add their targets as static input.\n                case .library(.automatic), .library(.static), .plugin:\n                    for module in product.modules {\n                        let description = self.plan.description(\n                            for: module,\n                            context: product.type == .plugin ? .host : target.destination\n                        )\n                        try addStaticTargetInputs(module, description)\n                    }\n\n                case .test:\n                    break\n                }\n            }\n        }\n\n        for binaryPath in target.libraryBinaryPaths {\n            let path = target.buildParameters.destinationPath(forBinaryAt: binaryPath)\n            if self.fileSystem.isDirectory(binaryPath) {\n                inputs.append(directory: path)\n            } else {\n                inputs.append(file: path)\n            }\n        }\n\n        // Make sure the windows DLLs get copied over\n        for binaryPath in target.windowsDLLBinaryPaths {\n            let path = target.buildParameters.destinationPath(forBinaryAt: binaryPath)\n            if self.fileSystem.isDirectory(binaryPath) {\n                inputs.append(directory: path)\n            } else {\n                inputs.append(file: path)\n            }\n        }\n\n\n        let additionalInputs = try self.addBuildToolPlugins(.swift(target))\n\n        // Depend on any required macro's output.\n        try target.requiredMacros.forEach { macro in\n            inputs.append(.virtual(getLLBuildTargetName(\n                macro: macro,\n                buildParameters: target.macroBuildParameters\n            )))\n        }\n\n        return inputs + additionalInputs\n    }\n\n    /// Adds a top-level phony command that builds the entire module.\n    private func addTargetCmd(_ target: SwiftModuleBuildDescription, cmdOutputs: [Node]) {\n        // Create a phony node to represent the entire module.\n        let targetName = target.getLLBuildTargetName()\n        let targetOutput: Node = .virtual(targetName)\n\n        self.manifest.addNode(targetOutput, toTarget: targetName)\n        self.manifest.addPhonyCmd(\n            name: targetOutput.name,\n            inputs: cmdOutputs,\n            outputs: [targetOutput]\n        )\n        if self.plan.graph.isInRootPackages(target.target, satisfying: target.buildParameters.buildEnvironment) {\n            if !target.isTestTarget {\n                self.addNode(targetOutput, toTarget: .main)\n            }\n            self.addNode(targetOutput, toTarget: .test)\n        }\n    }\n\n    private func addModuleWrapCmd(_ target: SwiftModuleBuildDescription) throws {\n        // Add commands to perform the module wrapping Swift modules when debugging strategy is `modulewrap`.\n        guard target.buildParameters.debuggingStrategy == .modulewrap else { return }\n        var moduleWrapArgs = [\n            target.buildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-modulewrap\", target.moduleOutputPath.pathString,\n            \"-o\", target.wrappedModuleOutputPath.pathString,\n        ]\n        moduleWrapArgs += try target.buildParameters.tripleArgs(for: target.target)\n        self.manifest.addShellCmd(\n            name: target.wrappedModuleOutputPath.pathString,\n            description: \"Wrapping AST for \\(target.target.name) for debugging\",\n            inputs: [.file(target.moduleOutputPath)],\n            outputs: [.file(target.wrappedModuleOutputPath)],\n            arguments: moduleWrapArgs\n        )\n    }\n\n    private func addSwiftGetVersionCommand(buildParameters: BuildParameters) -> AbsolutePath {\n        let swiftCompilerPath = buildParameters.toolchain.swiftCompilerPath\n\n        // If we are already tracking this compiler, we can re-use the existing command by just returning the tracking file.\n        if let swiftVersionFilePath = swiftGetVersionFiles[swiftCompilerPath] {\n            return swiftVersionFilePath\n        }\n\n        // Otherwise, come up with a path for the new file and generate a command to populate it.\n        let swiftCompilerPathHash = String(swiftCompilerPath.pathString.hash, radix: 16, uppercase: true)\n        let swiftVersionFilePath = buildParameters.buildPath.appending(component: \"swift-version-\\(swiftCompilerPathHash).txt\")\n        self.manifest.addSwiftGetVersionCommand(swiftCompilerPath: swiftCompilerPath, swiftVersionFilePath: swiftVersionFilePath)\n        swiftGetVersionFiles[swiftCompilerPath] = swiftVersionFilePath\n        return swiftVersionFilePath\n    }\n}\n\nextension TypedVirtualPath {\n    /// Resolve a typed virtual path provided by the Swift driver to\n    /// a node in the build graph.\n    fileprivate func resolveToNode(fileSystem: some FileSystem) throws -> Node {\n        if let absolutePath = (file.absolutePath.flatMap { AbsolutePath($0) }) {\n            return Node.file(absolutePath)\n        } else if let relativePath = (file.relativePath.flatMap { RelativePath($0) }) {\n            guard let workingDirectory: AbsolutePath = fileSystem.currentWorkingDirectory else {\n                throw InternalError(\"unknown working directory\")\n            }\n            return Node.file(workingDirectory.appending(relativePath))\n        } else if let temporaryFileName = file.temporaryFileName {\n            return Node.virtual(temporaryFileName.pathString)\n        } else {\n            throw InternalError(\"Cannot resolve VirtualPath: \\(file)\")\n        }\n    }\n}\n\nextension Driver {\n    func checkLDPathOption(commandLine: [String]) throws {\n        // `-ld-path` option is only available in recent versions of the compiler: rdar://117049947\n        if let option = commandLine.first(where: { $0.hasPrefix(\"-ld-path\") }),\n           !self.supportedFrontendFeatures.contains(\"ld-path-driver-option\") {\n            throw LLBuildManifestBuilder.Error.ldPathDriverOptionUnavailable(option: option)\n        }\n    }\n}\n\nextension SwiftModuleBuildDescription {\n    public func getCommandName() -> String {\n        \"C.\" + self.getLLBuildTargetName()\n    }\n\n    public func getLLBuildTargetName() -> String {\n        self.target.getLLBuildTargetName(buildParameters: self.buildParameters)\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildManifest/LLBuildManifestBuilder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport LLBuildManifest\nimport PackageGraph\nimport PackageModel\nimport SPMBuildCore\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftDriver\n#else\nimport SwiftDriver\n#endif\n\nimport struct TSCBasic.ByteString\nimport func TSCBasic.topologicalSort\n\n/// High-level interface to ``LLBuildManifest`` and ``LLBuildManifestWriter``.\npublic class LLBuildManifestBuilder {\n    enum Error: Swift.Error {\n        case ldPathDriverOptionUnavailable(option: String)\n\n        var description: String {\n            switch self {\n            case .ldPathDriverOptionUnavailable(let option):\n                return \"Unable to pass \\(option), currently used version of `swiftc` doesn't support it.\"\n            }\n        }\n    }\n\n    public enum TargetKind {\n        case main\n        case test\n\n        public var targetName: String {\n            switch self {\n            case .main: return \"main\"\n            case .test: return \"test\"\n            }\n        }\n    }\n\n    /// The build plan to work on.\n    public let plan: BuildPlan\n\n    /// Whether to sandbox commands from build tool plugins.\n    public let disableSandboxForPluginCommands: Bool\n\n    /// File system reference.\n    let fileSystem: any FileSystem\n\n    /// ObservabilityScope with which to emit diagnostics\n    public let observabilityScope: ObservabilityScope\n\n    public internal(set) var manifest: LLBuildManifest = .init()\n\n    /// Mapping from Swift compiler path to Swift get version files.\n    var swiftGetVersionFiles = [AbsolutePath: AbsolutePath]()\n\n    /// Create a new builder with a build plan.\n    public init(\n        _ plan: BuildPlan,\n        disableSandboxForPluginCommands: Bool = false,\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.plan = plan\n        self.disableSandboxForPluginCommands = disableSandboxForPluginCommands\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n    }\n\n    // MARK: - Generate Build Manifest\n\n    /// Generate build manifest at the given path.\n    @discardableResult\n    public func generateManifest(at path: AbsolutePath) throws -> LLBuildManifest {\n        self.swiftGetVersionFiles.removeAll()\n\n        self.manifest.createTarget(TargetKind.main.targetName)\n        self.manifest.createTarget(TargetKind.test.targetName)\n        self.manifest.defaultTarget = TargetKind.main.targetName\n\n        addPackageStructureCommand()\n        addBinaryDependencyCommands()\n        // Create commands for all target descriptions in the plan.\n        for description in self.plan.targetMap {\n            switch description {\n            case .swift(let desc):\n                try self.createSwiftCompileCommand(desc)\n            case .clang(let desc):\n                if desc.buildParameters.prepareForIndexing == .off {\n                    try self.createClangCompileCommand(desc)\n                } else {\n                    // Hook up the clang module target when preparing\n                    try self.createClangPrepareCommand(desc)\n                }\n            }\n        }\n\n        // Skip test discovery if preparing for indexing\n        if self.plan.destinationBuildParameters.prepareForIndexing == .off {\n            try self.addTestDiscoveryGenerationCommand()\n            try self.addTestEntryPointGenerationCommand()\n        }\n\n        // Create command for all products in the plan.\n        for description in self.plan.productMap {\n            if description.buildParameters.prepareForIndexing == .off {\n                try self.createProductCommand(description)\n            }\n        }\n\n        try LLBuildManifestWriter.write(self.manifest, at: path, fileSystem: self.fileSystem)\n        return self.manifest\n    }\n\n    func addNode(_ node: Node, toTarget targetKind: TargetKind) {\n        self.manifest.addNode(node, toTarget: targetKind.targetName)\n    }\n}\n\n// MARK: - Package Structure\n\nextension LLBuildManifestBuilder {\n    private func addPackageStructureCommand() {\n        let inputs = self.plan.inputs.map {\n            switch $0 {\n            case .directoryStructure(let path): return Node.directoryStructure(path)\n            case .file(let path): return Node.file(path)\n            }\n        }\n\n        let name = \"PackageStructure\"\n        let output: Node = .virtual(name)\n\n        self.manifest.addPkgStructureCmd(\n            name: name,\n            inputs: inputs,\n            outputs: [output]\n        )\n        self.manifest.addNode(output, toTarget: name)\n    }\n}\n\n// MARK: - Binary Dependencies\n\nextension LLBuildManifestBuilder {\n    // Creates commands for copying all binary artifacts depended on in the plan.\n    private func addBinaryDependencyCommands() {\n        // Make sure we don't have multiple copy commands for each destination by mapping each destination to\n        // its source binary.\n        var destinations = [AbsolutePath: AbsolutePath]()\n        for target in self.plan.targetMap.values {\n            // skip if target is preparing for indexing\n            guard target.buildParameters.prepareForIndexing == .off else { continue }\n\n            for binaryPath in target.libraryBinaryPaths {\n                destinations[target.buildParameters.destinationPath(forBinaryAt: binaryPath)] = binaryPath\n            }\n            for binaryPath in target.windowsDLLBinaryPaths {\n                destinations[target.buildParameters.destinationPath(forBinaryAt: binaryPath)] = binaryPath\n            }\n        }\n        for (destination, source) in destinations {\n            self.addCopyCommand(from: source, to: destination)\n        }\n    }\n}\n\n// MARK: - Compilation\n\nextension LLBuildManifestBuilder {\n    func addBuildToolPlugins(_ target: ModuleBuildDescription) throws -> [Node] {\n        // For any build command that doesn't declare any outputs, we need to create a phony output to ensure they will still be run by the build system.\n        var phonyOutputs = [Node]()\n        // If we have multiple commands with no output files and no display name, this serves as a way to disambiguate the virtual nodes being created.\n        var pluginNumber = 1\n\n        // Add any regular build commands created by plugins for the target.\n        for result in target.buildToolPluginInvocationResults {\n            // Only go through the regular build commands — prebuild commands are handled separately.\n            for command in result.buildCommands {\n                // Create a shell command to invoke the executable. We include the path of the executable as a\n                // dependency, and make sure the name is unique.\n                let execPath = command.configuration.executable\n                let uniquedName = ([execPath.pathString] + command.configuration.arguments).joined(separator: \"|\")\n                let displayName = command.configuration.displayName ?? execPath.basename\n                var commandLine = [execPath.pathString] + command.configuration.arguments\n                if !self.disableSandboxForPluginCommands {\n                    commandLine = try Sandbox.apply(\n                        command: commandLine,\n                        fileSystem: self.fileSystem,\n                        strictness: .writableTemporaryDirectory,\n                        writableDirectories: [result.pluginOutputDirectory]\n                    )\n                }\n                let additionalOutputs: [Node]\n                if command.outputFiles.isEmpty {\n                    if target.toolsVersion >= .v6_0 {\n                        additionalOutputs = [.virtual(\"\\(target.module.c99name)-\\(command.configuration.displayName ?? \"\\(pluginNumber)\")\")]\n                        phonyOutputs += additionalOutputs\n                    } else {\n                        additionalOutputs = []\n                        observabilityScope.emit(warning: \"Build tool command '\\(displayName)' (applied to target '\\(target.module.name)') does not declare any output files and therefore will not run. You may want to consider updating the given package to tools-version 6.0 (or higher) which would run such a build tool command even without declared outputs.\")\n                    }\n                    pluginNumber += 1\n                } else {\n                    additionalOutputs = []\n                }\n                self.manifest.addShellCmd(\n                    name: displayName + \"-\" + ByteString(encodingAsUTF8: uniquedName).sha256Checksum,\n                    description: displayName,\n                    inputs: command.inputFiles.map { .file($0) },\n                    outputs: command.outputFiles.map { .file($0) } + additionalOutputs,\n                    arguments: commandLine,\n                    environment: command.configuration.environment,\n                    workingDirectory: command.configuration.workingDirectory?.pathString\n                )\n            }\n        }\n\n        return phonyOutputs\n    }\n}\n\n// MARK: - Test File Generation\n\nextension LLBuildManifestBuilder {\n    private func addTestDiscoveryGenerationCommand() throws {\n        for testDiscoveryTarget in self.plan.targets.compactMap(\\.testDiscoveryTargetBuildDescription) {\n            let testTargets = testDiscoveryTarget.target.dependencies\n                .compactMap(\\.module).compactMap { self.plan.description(for: $0, context: testDiscoveryTarget.destination) }\n            let objectFiles = try testTargets.flatMap { try $0.objects }.sorted().map(Node.file)\n            let outputs = testDiscoveryTarget.target.sources.paths\n\n            guard let mainOutput = (outputs.first { $0.basename == TestDiscoveryTool.mainFileName }) else {\n                throw InternalError(\"main output (\\(TestDiscoveryTool.mainFileName)) not found\")\n            }\n            let cmdName = mainOutput.pathString\n            self.manifest.addTestDiscoveryCmd(\n                name: cmdName,\n                inputs: objectFiles,\n                outputs: outputs.map(Node.file)\n            )\n        }\n    }\n\n    private func addTestEntryPointGenerationCommand() throws {\n        for module in self.plan.targets {\n            guard case .swift(let swiftModule) = module,\n                  case .entryPoint(let isSynthesized) = swiftModule.testTargetRole,\n                  isSynthesized else { continue }\n\n            let testEntryPointTarget = swiftModule\n\n            // Get the Swift target build descriptions of all discovery modules this synthesized entry point target\n            // depends on.\n            let discoveredTargetDependencyBuildDescriptions = module.dependencies(using: self.plan)\n                .compactMap {\n                    if case .module(_, let description) = $0 {\n                        return description\n                    }\n                    return nil\n                }\n                .compactMap(\\.testDiscoveryTargetBuildDescription)\n\n            // The module outputs of the discovery modules this synthesized entry point target depends on are\n            // considered the inputs to the entry point command.\n            let inputs = discoveredTargetDependencyBuildDescriptions.map(\\.moduleOutputPath)\n\n            let outputs = testEntryPointTarget.target.sources.paths\n\n            let mainFileName = TestEntryPointTool.mainFileName\n            guard let mainOutput = (outputs.first { $0.basename == mainFileName }) else {\n                throw InternalError(\"main output (\\(mainFileName)) not found\")\n            }\n            let cmdName = mainOutput.pathString\n            self.manifest.addTestEntryPointCmd(\n                name: cmdName,\n                inputs: inputs.map(Node.file),\n                outputs: outputs.map(Node.file)\n            )\n        }\n    }\n}\n\nextension ModuleBuildDescription {\n    /// If receiver represents a Swift target build description whose test target role is Discovery,\n    /// then this returns that Swift target build description, else returns nil.\n    fileprivate var testDiscoveryTargetBuildDescription: SwiftModuleBuildDescription? {\n        guard case .swift(let targetBuildDescription) = self,\n              case .discovery = targetBuildDescription.testTargetRole else { return nil }\n        return targetBuildDescription\n    }\n}\n\nextension ModuleBuildDescription {\n    package var llbuildResourcesCmdName: String {\n        \"\\(self.module.name)-\\(self.buildParameters.triple.tripleString)-\\(self.buildParameters.buildConfig)\\(self.buildParameters.suffix).module-resources\"\n    }\n}\n\nextension ClangModuleBuildDescription {\n    package var llbuildTargetName: String {\n        self.target.getLLBuildTargetName(buildParameters: self.buildParameters)\n    }\n}\n\nextension ResolvedModule {\n    public func getLLBuildTargetName(buildParameters: BuildParameters) -> String {\n        \"\\(self.name)-\\(buildParameters.triple.tripleString)-\\(buildParameters.buildConfig)\\(buildParameters.suffix).module\"\n    }\n}\n\n// MARK: - Helper\n\nextension LLBuildManifestBuilder {\n    @discardableResult\n    func addCopyCommand(\n        from source: AbsolutePath,\n        to destination: AbsolutePath\n    ) -> (inputNode: Node, outputNode: Node) {\n        let isDirectory = self.fileSystem.isDirectory(source)\n        let nodeType = isDirectory ? Node.directory : Node.file\n        let inputNode = nodeType(source)\n        let outputNode = nodeType(destination)\n        self.manifest.addCopyCmd(name: destination.pathString, inputs: [inputNode], outputs: [outputNode])\n        return (inputNode, outputNode)\n    }\n}\n\nextension BuildParameters {\n    func destinationPath(forBinaryAt path: AbsolutePath) -> AbsolutePath {\n        self.buildPath.appending(component: path.basename)\n    }\n\n    var buildConfig: String { self.configuration.dirname }\n}\n\nextension Sequence where Element: Hashable {\n    /// Unique the elements in a sequence.\n    func uniqued() -> [Element] {\n        var seen: Set<Element> = []\n        return filter { seen.insert($0).inserted }\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildOperation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\n@_spi(SwiftPMInternal)\nimport Basics\nimport Foundation\nimport LLBuildManifest\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SPMBuildCore\nimport SPMLLBuild\n\nimport class Basics.AsyncProcess\nimport class TSCBasic.DiagnosticsEngine\nimport protocol TSCBasic.OutputByteStream\nimport struct TSCBasic.RegEx\n\nimport enum TSCUtility.Diagnostics\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import DriverSupport\n@_implementationOnly import SwiftDriver\n#else\nimport DriverSupport\nimport SwiftDriver\n#endif\n\npackage struct LLBuildSystemConfiguration {\n    fileprivate let toolsBuildParameters: BuildParameters\n    fileprivate let destinationBuildParameters: BuildParameters\n\n    let scratchDirectory: AbsolutePath\n\n    let traitConfiguration: TraitConfiguration?\n\n    fileprivate(set) var manifestPath: AbsolutePath\n    fileprivate(set) var databasePath: AbsolutePath\n    fileprivate(set) var buildDescriptionPath: AbsolutePath\n\n    let fileSystem: any Basics.FileSystem\n\n    let logLevel: Basics.Diagnostic.Severity\n    let outputStream: OutputByteStream\n\n    let observabilityScope: ObservabilityScope\n\n    init(\n        toolsBuildParameters: BuildParameters,\n        destinationBuildParameters: BuildParameters,\n        scratchDirectory: AbsolutePath,\n        traitConfiguration: TraitConfiguration?,\n        manifestPath: AbsolutePath? = nil,\n        databasePath: AbsolutePath? = nil,\n        buildDescriptionPath: AbsolutePath? = nil,\n        fileSystem: any Basics.FileSystem,\n        logLevel: Basics.Diagnostic.Severity,\n        outputStream: OutputByteStream,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.toolsBuildParameters = toolsBuildParameters\n        self.destinationBuildParameters = destinationBuildParameters\n        self.scratchDirectory = scratchDirectory\n        self.traitConfiguration = traitConfiguration\n        self.manifestPath = manifestPath ?? destinationBuildParameters.llbuildManifest\n        self.databasePath = databasePath ?? scratchDirectory.appending(\"build.db\")\n        self.buildDescriptionPath = buildDescriptionPath ?? destinationBuildParameters.buildDescriptionPath\n        self.fileSystem = fileSystem\n        self.logLevel = logLevel\n        self.outputStream = outputStream\n        self.observabilityScope = observabilityScope\n    }\n\n    func buildParameters(for destination: BuildParameters.Destination) -> BuildParameters {\n        switch destination {\n        case .host: self.toolsBuildParameters\n        case .target: self.destinationBuildParameters\n        }\n    }\n\n    func buildEnvironment(for destination: BuildParameters.Destination) -> BuildEnvironment {\n        switch destination {\n        case .host: self.toolsBuildParameters.buildEnvironment\n        case .target: self.destinationBuildParameters.buildEnvironment\n        }\n    }\n\n    func shouldSkipBuilding(for destination: BuildParameters.Destination) -> Bool {\n        switch destination {\n        case .host: self.toolsBuildParameters.shouldSkipBuilding\n        case .target: self.destinationBuildParameters.shouldSkipBuilding\n        }\n    }\n\n    func toolchain(for description: BuildParameters.Destination) -> any PackageModel.Toolchain {\n        switch description {\n        case .host: self.toolsBuildParameters.toolchain\n        case .target: self.destinationBuildParameters.toolchain\n        }\n    }\n\n    func buildPath(for description: BuildParameters.Destination) -> AbsolutePath {\n        switch description {\n        case .host: self.toolsBuildParameters.buildPath\n        case .target: self.destinationBuildParameters.buildPath\n        }\n    }\n\n    func dataPath(for description: BuildParameters.Destination) -> AbsolutePath {\n        switch description {\n        case .host: self.toolsBuildParameters.dataPath\n        case .target: self.destinationBuildParameters.dataPath\n        }\n    }\n\n    func buildDescriptionPath(for description: BuildParameters.Destination) -> AbsolutePath {\n        switch description {\n        case .host: self.toolsBuildParameters.buildDescriptionPath\n        case .target: self.destinationBuildParameters.buildDescriptionPath\n        }\n    }\n\n    func configuration(for destination: BuildParameters.Destination) -> BuildConfiguration {\n        switch destination {\n        case .host: self.toolsBuildParameters.configuration\n        case .target: self.destinationBuildParameters.configuration\n        }\n    }\n}\n\npublic final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildSystem, BuildErrorAdviceProvider {\n    /// The delegate used by the build system.\n    public weak var delegate: SPMBuildCore.BuildSystemDelegate?\n\n    private let config: LLBuildSystemConfiguration\n\n    /// The closure for loading the package graph.\n    let packageGraphLoader: () async throws -> ModulesGraph\n\n    /// the plugin configuration for build plugins\n    let pluginConfiguration: PluginConfiguration?\n\n    /// The llbuild build system reference previously created\n    /// via `createBuildSystem` call.\n    private var current: (buildSystem: SPMLLBuild.BuildSystem, tracker: LLBuildProgressTracker)?\n\n    /// If build manifest caching should be enabled.\n    public let cacheBuildManifest: Bool\n\n    /// The build plan that was computed, if any.\n    public private(set) var _buildPlan: BuildPlan?\n\n    public var buildPlan: SPMBuildCore.BuildPlan {\n        get throws {\n            if let buildPlan = _buildPlan {\n                return buildPlan\n            } else {\n                throw StringError(\"did not compute a build plan yet\")\n            }\n        }\n    }\n\n    /// The build description resulting from planing.\n    private let buildDescription = AsyncThrowingValueMemoizer<BuildDescription>()\n\n    /// The loaded package graph.\n    private let packageGraph = AsyncThrowingValueMemoizer<ModulesGraph>()\n\n    /// File system to operate on.\n    private var fileSystem: Basics.FileSystem {\n        config.fileSystem\n    }\n\n    /// ObservabilityScope with which to emit diagnostics.\n    private var observabilityScope: ObservabilityScope {\n        config.observabilityScope\n    }\n\n    public var builtTestProducts: [BuiltTestProduct] {\n        get async {\n            (try? await getBuildDescription())?.builtTestProducts ?? []\n        }\n    }\n\n    /// File rules to determine resource handling behavior.\n    private let additionalFileRules: [FileRuleDescription]\n\n    /// Alternative path to search for pkg-config `.pc` files.\n    private let pkgConfigDirectories: [AbsolutePath]\n\n    public var hasIntegratedAPIDigesterSupport: Bool { false }\n\n    public convenience init(\n        productsBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n        cacheBuildManifest: Bool,\n        packageGraphLoader: @escaping () throws -> ModulesGraph,\n        pluginConfiguration: PluginConfiguration? = .none,\n        scratchDirectory: AbsolutePath,\n        additionalFileRules: [FileRuleDescription],\n        pkgConfigDirectories: [AbsolutePath],\n        outputStream: OutputByteStream,\n        logLevel: Basics.Diagnostic.Severity,\n        fileSystem: Basics.FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.init(\n            productsBuildParameters: productsBuildParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            cacheBuildManifest: cacheBuildManifest,\n            packageGraphLoader: packageGraphLoader,\n            pluginConfiguration: pluginConfiguration,\n            scratchDirectory: scratchDirectory,\n            traitConfiguration: nil,\n            additionalFileRules: additionalFileRules,\n            pkgConfigDirectories: pkgConfigDirectories,\n            outputStream: outputStream,\n            logLevel: logLevel,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            delegate: nil\n        )\n    }\n\n    package init(\n        productsBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n        cacheBuildManifest: Bool,\n        packageGraphLoader: @escaping () async throws -> ModulesGraph,\n        pluginConfiguration: PluginConfiguration? = .none,\n        scratchDirectory: AbsolutePath,\n        traitConfiguration: TraitConfiguration?,\n        additionalFileRules: [FileRuleDescription],\n        pkgConfigDirectories: [AbsolutePath],\n        outputStream: OutputByteStream,\n        logLevel: Basics.Diagnostic.Severity,\n        fileSystem: Basics.FileSystem,\n        observabilityScope: ObservabilityScope,\n        delegate: SPMBuildCore.BuildSystemDelegate?\n    ) {\n        /// Checks if stdout stream is tty.\n        var productsBuildParameters = productsBuildParameters\n        if productsBuildParameters.outputParameters.isColorized {\n            productsBuildParameters.outputParameters.isColorized = outputStream.isTTY\n        }\n        var toolsBuildParameters = toolsBuildParameters\n        if toolsBuildParameters.outputParameters.isColorized {\n            toolsBuildParameters.outputParameters.isColorized = outputStream.isTTY\n        }\n        self.config = LLBuildSystemConfiguration(\n            toolsBuildParameters: toolsBuildParameters,\n            destinationBuildParameters: productsBuildParameters,\n            scratchDirectory: scratchDirectory,\n            traitConfiguration: traitConfiguration,\n            fileSystem: fileSystem,\n            logLevel: logLevel,\n            outputStream: outputStream,\n            observabilityScope: observabilityScope.makeChildScope(description: \"Build Operation\")\n        )\n\n        self.cacheBuildManifest = cacheBuildManifest\n        self.packageGraphLoader = packageGraphLoader\n        self.additionalFileRules = additionalFileRules\n        self.pluginConfiguration = pluginConfiguration\n        self.pkgConfigDirectories = pkgConfigDirectories\n        self.delegate = delegate\n    }\n\n    public func getPackageGraph() async throws -> ModulesGraph {\n        try await self.packageGraph.memoize {\n            try await self.packageGraphLoader()\n        }\n    }\n\n    /// Compute and return the latest build description.\n    ///\n    /// This will try skip build planning if build manifest caching is enabled\n    /// and the package structure hasn't changed.\n    public func getBuildDescription(subset: BuildSubset? = nil) async throws -> BuildDescription {\n        return try await self.buildDescription.memoize {\n            if self.cacheBuildManifest {\n                do {\n                    // if buildPackageStructure returns a valid description we use that, otherwise we perform full planning\n                    if try await self.buildPackageStructure() {\n                        // confirm the step above created the build description as expected\n                        // we trust it to update the build description when needed\n                        let buildDescriptionPath = self.config.buildDescriptionPath(for: .target)\n                        guard self.fileSystem.exists(buildDescriptionPath) else {\n                            throw InternalError(\"could not find build descriptor at \\(buildDescriptionPath)\")\n                        }\n                        // return the build description that's on disk.\n                        let buildDescription = try BuildDescription.load(fileSystem: self.fileSystem, path: buildDescriptionPath)\n\n                        // We need to check that the build has same traits enabled for the cached build operation\n                        // match otherwise we have to re-plan.\n                        if buildDescription.traitConfiguration == self.config.traitConfiguration {\n                            return buildDescription\n                        }\n                    }\n                } catch {\n                    // since caching is an optimization, warn about failing to load the cached version\n                    self.observabilityScope.emit(\n                        warning: \"failed to load the cached build description\",\n                        underlyingError: error\n                    )\n                }\n            }\n            // We need to perform actual planning if we reach here.\n            return try await self.generateDescription(subset: subset).description\n        }\n    }\n\n    public func getBuildManifest() async throws -> LLBuildManifest {\n        try await self.generateDescription().manifest\n    }\n\n    /// Cancel the active build operation.\n    public func cancel(deadline: DispatchTime) throws {\n        current?.buildSystem.cancel()\n    }\n\n    // Emit a warning if a target imports another target in this build\n    // without specifying it as a dependency in the manifest\n    private func verifyTargetImports(in description: BuildDescription) throws {\n        let checkingMode = description.explicitTargetDependencyImportCheckingMode\n        guard checkingMode != .none else {\n            return\n        }\n        // Ensure the compiler supports the import-scan operation\n        guard DriverSupport.checkSupportedFrontendFlags(\n            flags: [\"import-prescan\"],\n            toolchain: self.config.toolchain(for: .target),\n            fileSystem: localFileSystem\n        ) else {\n            return\n        }\n\n        for (target, commandLine) in description.swiftTargetScanArgs {\n            do {\n                guard let dependencies = description.targetDependencyMap[target] else {\n                    // Skip target if no dependency information is present\n                    continue\n                }\n                let targetDependenciesSet = Set(dependencies)\n                guard !description.generatedSourceTargetSet.contains(target),\n                      targetDependenciesSet.intersection(description.generatedSourceTargetSet).isEmpty else {\n                    // Skip targets which contain, or depend-on-targets, with generated source-code.\n                    // Such as test discovery targets and targets with plugins.\n                    continue\n                }\n                let resolver = try ArgsResolver(fileSystem: localFileSystem)\n                let executor = SPMSwiftDriverExecutor(resolver: resolver,\n                                                      fileSystem: localFileSystem,\n                                                      env: Environment.current)\n\n                let consumeDiagnostics: DiagnosticsEngine = DiagnosticsEngine(handlers: [])\n                var driver = try Driver(args: commandLine,\n                                        diagnosticsOutput: .engine(consumeDiagnostics),\n                                        fileSystem: localFileSystem,\n                                        executor: executor)\n                guard !consumeDiagnostics.hasErrors else {\n                    // If we could not init the driver with this command, something went wrong,\n                    // proceed without checking this target.\n                    continue\n                }\n                let imports = try driver.performImportPrescan().imports\n                let nonDependencyTargetsSet =\n                    Set(description.targetDependencyMap.keys.filter { !targetDependenciesSet.contains($0) })\n                let importedTargetsMissingDependency = Set(imports).intersection(nonDependencyTargetsSet)\n                if let missedDependency = importedTargetsMissingDependency.first {\n                    switch checkingMode {\n                        case .error:\n                            self.observabilityScope.emit(error: \"Target \\(target) imports another target (\\(missedDependency)) in the package without declaring it a dependency.\")\n                        case .warn:\n                            self.observabilityScope.emit(warning: \"Target \\(target) imports another target (\\(missedDependency)) in the package without declaring it a dependency.\")\n                        case .none:\n                            fatalError(\"Explicit import checking is disabled.\")\n                    }\n                }\n            } catch {\n                // The above verification is a best-effort attempt to warn the user about a potential manifest\n                // error. If something went wrong during the import-prescan, proceed silently.\n                return\n            }\n        }\n    }\n\n    /// Perform a build using the given build description and subset.\n    public func build(subset: BuildSubset, buildOutputs: [BuildOutput]) async throws -> BuildResult {\n        var result = BuildResult(\n            serializedDiagnosticPathsByTargetName: .failure(StringError(\"Building was skipped\")),\n            replArguments: nil,\n            dependencyGraph: nil\n        )\n\n        guard !self.config.shouldSkipBuilding(for: .target) else {\n            return result\n        }\n\n        let buildStartTime = DispatchTime.now()\n\n        // Get the build description (either a cached one or newly created).\n\n        // Get the build description\n        let buildDescription = try await self.getBuildDescription(subset: subset)\n\n        // Verify dependency imports on the described targets\n        try verifyTargetImports(in: buildDescription)\n\n        // Create the build system.\n        let (buildSystem, progressTracker) = try self.createBuildSystem(\n            buildDescription: buildDescription,\n            config: self.config\n        )\n        self.current = (buildSystem, progressTracker)\n\n        // If any plugins are part of the build set, compile them now to surface\n        // any errors up-front. Returns true if we should proceed with the build\n        // or false if not. It will already have thrown any appropriate error.\n        guard try await self.compilePlugins(in: subset) else {\n            result.serializedDiagnosticPathsByTargetName = .failure(StringError(\"Plugin compilation failed\"))\n            return result\n        }\n\n        let configuration = self.config.configuration(for: .target)\n        // delegate is only available after createBuildSystem is called\n        progressTracker.buildStart(configuration: configuration)\n\n        // Perform the build.\n        let llbuildTarget = try await computeLLBuildTargetName(for: subset)\n        let success = buildSystem.build(target: llbuildTarget)\n\n        let duration = buildStartTime.distance(to: .now())\n\n        let subsetDescriptor: String?\n        switch subset {\n        case .product(let productName, _):\n            subsetDescriptor = \"product '\\(productName)'\"\n        case .target(let targetName, _):\n            subsetDescriptor = \"target: '\\(targetName)'\"\n        case .allExcludingTests, .allIncludingTests:\n            subsetDescriptor = nil\n        }\n\n        progressTracker.buildComplete(\n            success: success,\n            duration: duration,\n            subsetDescriptor: subsetDescriptor\n        )\n        guard success else { throw Diagnostics.fatalError }\n\n        let buildResultBuildPlan = buildOutputs.contains(.buildPlan) ? try buildPlan : nil\n        let buildResultReplArgs = buildOutputs.contains(.replArguments) ? try buildPlan.createREPLArguments() : nil\n\n        let artifacts: [(String, PluginInvocationBuildResult.BuiltArtifact)]?\n        if buildOutputs.contains(.builtArtifacts) {\n            let builtProducts = try buildPlan.buildProducts\n            artifacts = try builtProducts.compactMap {\n                switch $0.product.type {\n                case .library(let kind):\n                    let artifactKind: PluginInvocationBuildResult.BuiltArtifact.Kind\n                    switch kind {\n                        case .dynamic: artifactKind = .dynamicLibrary\n                        case .static, .automatic: artifactKind = .staticLibrary\n                    }\n                    return try ($0.product.name, .init(\n                        path: $0.binaryPath.pathString,\n                        kind: artifactKind)\n                    )\n                case .executable:\n                    return try ($0.product.name, .init(path: $0.binaryPath.pathString, kind: .executable))\n                default:\n                    return nil\n                }\n            }\n        } else {\n            artifacts = nil\n        }\n\n        result = BuildResult(\n            serializedDiagnosticPathsByTargetName: result.serializedDiagnosticPathsByTargetName,\n            symbolGraph: result.symbolGraph,\n            buildPlan: buildResultBuildPlan,\n            replArguments: buildResultReplArgs,\n            builtArtifacts: artifacts,\n            dependencyGraph: nil  // Not supported in native build system\n        )\n        var serializedDiagnosticPaths: [String: [AbsolutePath]] = [:]\n        do {\n            for module in try buildPlan.buildModules {\n                serializedDiagnosticPaths[module.module.name, default: []].append(contentsOf: module.diagnosticFiles)\n            }\n            result.serializedDiagnosticPathsByTargetName = .success(serializedDiagnosticPaths)\n        } catch {\n            result.serializedDiagnosticPathsByTargetName = .failure(error)\n        }\n\n        // Create backwards-compatibility symlink to old build path.\n        let oldBuildPath = self.config.dataPath(for: .target).parentDirectory.appending(\n            component: configuration.dirname\n        )\n        if self.fileSystem.exists(oldBuildPath) {\n            do { try self.fileSystem.removeFileTree(oldBuildPath) }\n            catch {\n                self.observabilityScope.emit(\n                    warning: \"unable to delete \\(oldBuildPath), skip creating symbolic link\",\n                    underlyingError: error\n                )\n\n                return result\n            }\n        }\n\n        do {\n            try self.fileSystem.createSymbolicLink(\n                oldBuildPath,\n                pointingAt: self.config.buildPath(for: .target),\n                relative: true\n            )\n        } catch {\n            self.observabilityScope.emit(\n                warning: \"unable to create symbolic link at \\(oldBuildPath)\",\n                underlyingError: error\n            )\n        }\n\n        return result\n    }\n\n    /// Compiles any plugins specified or implied by the build subset, returning\n    /// true if the build should proceed. Throws an error in case of failure. A\n    /// reason why the build might not proceed even on success is if only plugins\n    /// should be compiled.\n    func compilePlugins(in subset: BuildSubset) async throws -> Bool {\n        // Figure out what, if any, plugin descriptions to compile, and whether\n        // to continue building after that based on the subset.\n        let allPlugins = try await getBuildDescription().pluginDescriptions\n        let pluginsToCompile: [PluginBuildDescription]\n        let continueBuilding: Bool\n        switch subset {\n        case .allExcludingTests, .allIncludingTests:\n            pluginsToCompile = allPlugins\n            continueBuilding = true\n        case .product(let productName, _):\n            pluginsToCompile = allPlugins.filter{ $0.productNames.contains(productName) }\n            continueBuilding = pluginsToCompile.isEmpty\n        case .target(let targetName, _):\n            pluginsToCompile = allPlugins.filter{ $0.moduleName == targetName }\n            continueBuilding = pluginsToCompile.isEmpty\n        }\n\n        // Compile any plugins we ended up with. If any of them fails, it will\n        // throw.\n        for plugin in pluginsToCompile {\n            try await compilePlugin(plugin)\n        }\n\n        // If we get this far they all succeeded. Return whether to continue the\n        // build, based on the subset.\n        return continueBuilding\n    }\n\n    // Compiles a single plugin, emitting its output and throwing an error if it\n    // fails.\n    func compilePlugin(_ plugin: PluginBuildDescription) async throws {\n        guard let pluginConfiguration else {\n            throw InternalError(\"unknown plugin script runner\")\n        }\n        // Compile the plugin, getting back a PluginCompilationResult.\n        final class Delegate: PluginScriptCompilerDelegate {\n            let preparationStepName: String\n            let progressTracker: LLBuildProgressTracker?\n            init(preparationStepName: String, progressTracker: LLBuildProgressTracker?) {\n                self.preparationStepName = preparationStepName\n                self.progressTracker = progressTracker\n            }\n\n            func willCompilePlugin(commandLine: [String], environment: [String: String]) {\n                self.progressTracker?.preparationStepStarted(preparationStepName)\n            }\n\n            func didCompilePlugin(result: PluginCompilationResult) {\n                self.progressTracker?.preparationStepHadOutput(\n                    preparationStepName,\n                    output: result.commandLine.joined(separator: \" \"),\n                    verboseOnly: true\n                )\n                if !result.compilerOutput.isEmpty {\n                    self.progressTracker?.preparationStepHadOutput(\n                        preparationStepName,\n                        output: result.compilerOutput,\n                        verboseOnly: false\n                    )\n                }\n                self.progressTracker?.preparationStepFinished(preparationStepName, result: (result.succeeded ? .succeeded : .failed))\n            }\n\n            func skippedCompilingPlugin(cachedResult: PluginCompilationResult) {\n                // Historically we have emitted log info about cached plugins that are used. We should reconsider whether this is the right thing to do.\n                self.progressTracker?.preparationStepStarted(preparationStepName)\n                if !cachedResult.compilerOutput.isEmpty {\n                    self.progressTracker?.preparationStepHadOutput(\n                        preparationStepName,\n                        output: cachedResult.compilerOutput,\n                        verboseOnly: false\n                    )\n                }\n                self.progressTracker?.preparationStepFinished(preparationStepName, result: (cachedResult.succeeded ? .succeeded : .failed))\n            }\n        }\n        let delegate = Delegate(\n            preparationStepName: \"Compiling plugin \\(plugin.moduleName)\",\n            progressTracker: self.current?.tracker\n        )\n        let result = try await pluginConfiguration.scriptRunner.compilePluginScript(\n            sourceFiles: plugin.sources.paths,\n            pluginName: plugin.moduleName,\n            toolsVersion: plugin.toolsVersion,\n            workers: config.toolsBuildParameters.workers,\n            observabilityScope: self.observabilityScope,\n            callbackQueue: DispatchQueue.sharedConcurrent,\n            delegate: delegate\n        )\n\n        // Throw an error on failure; we will already have emitted the compiler's output in this case.\n        if !result.succeeded {\n            throw Diagnostics.fatalError\n        }\n    }\n\n    /// Compute the llbuild target name using the given subset.\n    func computeLLBuildTargetName(for subset: BuildSubset) async throws -> String {\n        func inferTestDestination(\n            testModule: ResolvedModule,\n            graph: ModulesGraph\n        ) throws -> BuildParameters.Destination {\n            for product in graph.allProducts where product.type == .test {\n                if product.modules.contains(where: { $0.id == testModule.id }) {\n                    return product.hasDirectMacroDependencies ? .host : .target\n                }\n            }\n\n            throw InternalError(\"Could not find a product for test module: \\(testModule)\")\n        }\n\n        switch subset {\n        case .allExcludingTests:\n            return LLBuildManifestBuilder.TargetKind.main.targetName\n        case .allIncludingTests:\n            return LLBuildManifestBuilder.TargetKind.test.targetName\n        case .product(let productName, let destination):\n            // FIXME: This is super unfortunate that we might need to load the package graph.\n            let graph = try await getPackageGraph()\n\n            let product = graph.product(for: productName)\n\n            guard let product else {\n                observabilityScope.emit(error: \"no product named '\\(productName)'\")\n                throw Diagnostics.fatalError\n            }\n\n            let buildParameters = if let destination {\n                config.buildParameters(for: destination)\n            } else if product.type == .macro || product.type == .plugin {\n                config.buildParameters(for: .host)\n            } else if product.type == .test {\n                config.buildParameters(for: product.hasDirectMacroDependencies ? .host : .target)\n            } else {\n                config.buildParameters(for: .target)\n            }\n\n            // If the product is automatic, we build the main target because automatic products\n            // do not produce a binary right now.\n            if product.type == .library(.automatic) {\n                observabilityScope.emit(\n                    warning:\n                        \"'--product' cannot be used with the automatic product '\\(productName)'; building the default target instead\"\n                )\n                return LLBuildManifestBuilder.TargetKind.main.targetName\n            }\n            return try product.getLLBuildTargetName(buildParameters: buildParameters)\n        case .target(let targetName, let destination):\n            // FIXME: This is super unfortunate that we might need to load the package graph.\n            let graph = try await getPackageGraph()\n\n            let module = graph.module(for: targetName)\n\n            guard let module else {\n                observabilityScope.emit(error: \"no target named '\\(targetName)'\")\n                throw Diagnostics.fatalError\n            }\n\n            let buildParameters = if let destination {\n                config.buildParameters(for: destination)\n            } else if module.type == .macro || module.type == .plugin {\n                config.buildParameters(for: .host)\n            } else if module.type == .test {\n                try config.buildParameters(for: inferTestDestination(testModule: module, graph: graph))\n            } else {\n                config.buildParameters(for: .target)\n            }\n\n            return module.getLLBuildTargetName(buildParameters: buildParameters)\n        }\n    }\n\n    package func generatePlan() async throws -> BuildPlan {\n        let graph = try await getPackageGraph()\n\n        let pluginTools: [ResolvedModule.ID: [String: PluginTool]]\n        // FIXME: This is unfortunate but we need to build plugin tools upfront at the moment because\n        // llbuild doesn't support dynamic dependency detection. In order to construct a manifest\n        // we need to build and invoke all of the build-tool plugins and capture their outputs in\n        // `BuildPlan`.\n        if let pluginConfiguration: PluginConfiguration, !self.config.shouldSkipBuilding(for: .target) {\n            let pluginsPerModule = graph.pluginsPerModule(\n                satisfying: self.config.buildEnvironment(for: .host)\n            )\n\n            pluginTools = try await buildPluginTools(\n                graph: graph,\n                pluginsPerModule: pluginsPerModule,\n                hostTriple: try pluginConfiguration.scriptRunner.hostTriple\n            )\n        } else {\n            pluginTools = [:]\n        }\n\n        // Create the build plan based on the modules graph and any information from plugins.\n        return try await BuildPlan(\n            destinationBuildParameters: self.config.buildParameters(for: .target),\n            toolsBuildParameters: self.config.buildParameters(for: .host),\n            graph: graph,\n            pluginConfiguration: self.pluginConfiguration,\n            pluginTools: pluginTools,\n            additionalFileRules: additionalFileRules,\n            pkgConfigDirectories: pkgConfigDirectories,\n            disableSandbox: self.pluginConfiguration?.disableSandbox ?? false,\n            fileSystem: self.fileSystem,\n            observabilityScope: self.observabilityScope\n        )\n    }\n\n    /// Create the build plan and return the build description.\n    private func generateDescription(subset: BuildSubset? = nil) async throws -> (description: BuildDescription, manifest: LLBuildManifest) {\n        let plan = try await generatePlan()\n        self._buildPlan = plan\n\n        // Emit warnings about any unhandled files in authored packages. We do this after applying build tool plugins, once we know what files they handled.\n        // rdar://113256834 This fix works for the plugins that do not have PreBuildCommands.\n        let targetsToConsider: [ResolvedModule]\n        if let subset = subset, let recursiveDependencies = try\n            subset.recursiveDependencies(for: plan.graph, observabilityScope: observabilityScope) {\n            targetsToConsider = recursiveDependencies\n        } else {\n            targetsToConsider = Array(plan.graph.reachableModules)\n        }\n\n        for module in targetsToConsider {\n            // Subtract out any that were inputs to any commands generated by plugins.\n            if let pluginResults = plan.buildToolPluginInvocationResults[module.id] {\n                diagnoseUnhandledFiles(\n                    modulesGraph: plan.graph,\n                    module: module,\n                    buildToolPluginInvocationResults: pluginResults\n                )\n            }\n        }\n\n        let (buildDescription, buildManifest) = try BuildDescription.create(\n            from: plan,\n            using: self.config,\n            disableSandboxForPluginCommands: self.pluginConfiguration?.disableSandbox ?? false\n        )\n\n        // Finally create the llbuild manifest from the plan.\n        return (buildDescription, buildManifest)\n    }\n\n    /// Emit warnings about any files that aren't specifically declared as resources\n    /// or excluded from the build of the given module.\n    private func diagnoseUnhandledFiles(\n        modulesGraph: ModulesGraph,\n        module: ResolvedModule,\n        buildToolPluginInvocationResults: [BuildToolPluginInvocationResult]\n    ) {\n        guard let package = modulesGraph.package(for: module),\n              package.manifest.toolsVersion >= .v5_3\n        else {\n            return\n        }\n\n        // Get the set of unhandled files in targets.\n        var unhandledFiles = Set(module.underlying.others)\n        if unhandledFiles.isEmpty {\n            return\n        }\n\n        // Subtract out any that were inputs to any commands generated by plugins.\n        let handledFiles = buildToolPluginInvocationResults.flatMap { $0.buildCommands.flatMap(\\.inputFiles) }\n        unhandledFiles.subtract(handledFiles)\n\n        if unhandledFiles.isEmpty {\n            return\n        }\n\n        // Emit a diagnostic if any remain. This is kept the same as the previous message for now, but this could be\n        // improved.\n        let diagnosticsEmitter = self.observabilityScope.makeDiagnosticsEmitter {\n            var metadata = ObservabilityMetadata()\n            metadata.packageIdentity = package.identity\n            metadata.packageKind = package.manifest.packageKind\n            metadata.moduleName = module.name\n            return metadata\n        }\n        var warning =\n            \"found \\(unhandledFiles.count) file(s) which are unhandled; explicitly declare them as resources or exclude from the target\\n\"\n        for file in unhandledFiles {\n            warning += \"    \" + file.pathString + \"\\n\"\n        }\n        diagnosticsEmitter.emit(warning: warning)\n    }\n\n    /// Build the package structure target.\n    private func buildPackageStructure() async throws -> Bool {\n        let (buildSystem, tracker) = try self.createBuildSystem(\n            buildDescription: .none,\n            config: self.config\n        )\n        self.current = (buildSystem, tracker)\n\n        // We use Task.detachNewThread here because buildSystem.build() is a blocking\n        // operation. Running this on the Swift Concurrency thread pool can block a worker thread\n        // potentially causing thread pool starvation and deadlocks. By running it on a dedicated\n        // thread, we keep the Swift Concurrency pool available for other async work.\n        let buildSuccess = await _Concurrency.Task.detachNewThread(name: \"buildPackageStructure\") {\n            // Build the package structure target which will re-generate the llbuild manifest, if necessary.\n            buildSystem.build(target: \"PackageStructure\")\n        }\n\n        // If progress has been printed this will add a newline to separate it from what could be\n        // the output of the command. For instance `swift test --skip-build` may print progress for\n        // the Planning Build stage, followed immediately by a list of tests. Without this finialize()\n        // call the first entry in the list appear on the same line as the Planning Build progress.\n        tracker.finalize(success: true)\n\n        return buildSuccess\n    }\n\n    /// Create the build system using the given build description.\n    ///\n    /// The build description should only be omitted when creating the build system for\n    /// building the package structure target.\n    private func createBuildSystem(\n        buildDescription: BuildDescription?,\n        config: LLBuildSystemConfiguration\n    ) throws -> (buildSystem: SPMLLBuild.BuildSystem, tracker: LLBuildProgressTracker) {\n        // Figure out which progress bar we have to use during the build.\n        let progressAnimation = ProgressAnimation.ninja(\n            stream: config.outputStream,\n            verbose: config.logLevel.isVerbose\n        )\n        let buildExecutionContext = BuildExecutionContext(\n            productsBuildParameters: config.destinationBuildParameters,\n            toolsBuildParameters: config.toolsBuildParameters,\n            buildDescription: buildDescription,\n            fileSystem: config.fileSystem,\n            observabilityScope: config.observabilityScope,\n            packageStructureDelegate: self,\n            buildErrorAdviceProvider: self\n        )\n\n        // Create the build delegate.\n        let progressTracker = LLBuildProgressTracker(\n            buildSystem: self,\n            buildExecutionContext: buildExecutionContext,\n            outputStream: config.outputStream,\n            progressAnimation: progressAnimation,\n            logLevel: config.logLevel,\n            observabilityScope: config.observabilityScope,\n            delegate: self.delegate\n        )\n\n        let llbuildSystem = SPMLLBuild.BuildSystem(\n            buildFile: config.manifestPath.pathString,\n            databaseFile: config.databasePath.pathString,\n            delegate: progressTracker,\n            schedulerLanes: config.destinationBuildParameters.workers\n        )\n\n        return (buildSystem: llbuildSystem, tracker: progressTracker)\n    }\n\n    public func provideBuildErrorAdvice(for target: String, command: String, message: String) -> String? {\n        // Find the target for which the error was emitted.  If we don't find it, we can't give any advice.\n        guard let _ = self._buildPlan?.targets.first(where: { $0.module.name == target }) else { return nil }\n\n        // Check for cases involving modules that cannot be found.\n        if let importedModule = try? RegEx(pattern: \"no such module '(.+)'\").matchGroups(in: message).first?.first {\n            // A target is importing a module that can't be found.  We take a look at the build plan and see if can offer any advice.\n\n            // Look for a target with the same module name as the one that's being imported.\n            if let importedTarget = self._buildPlan?.targets.first(where: { $0.module.c99name == importedModule }) {\n                // For the moment we just check for executables that other targets try to import.\n                if importedTarget.module.type == .executable {\n                    return \"module '\\(importedModule)' is the main module of an executable, and cannot be imported by tests and other targets\"\n                }\n                if importedTarget.module.type == .macro {\n                    return \"module '\\(importedModule)' is a macro, and cannot be imported by tests and other targets\"\n                }\n\n                // Here we can add more checks in the future.\n            }\n        }\n        return nil\n    }\n\n    public func packageStructureChanged() async -> Bool {\n        do {\n            _ = try await self.generateDescription()\n        }\n        catch Diagnostics.fatalError {\n            return false\n        }\n        catch {\n            self.observabilityScope.emit(error)\n            return false\n        }\n        return true\n    }\n\n    public func generatePIF(preserveStructure: Bool) async throws -> String {\n        throw StringError(\"PIF generation is not applicable to the native build system.\")\n    }\n}\n\npublic struct PluginConfiguration {\n    /// Entity responsible for compiling and running plugin scripts.\n    let scriptRunner: PluginScriptRunner\n\n    /// Directory where plugin intermediate files are stored.\n    let workDirectory: AbsolutePath\n\n    /// Whether to sandbox commands from build tool plugins.\n    let disableSandbox: Bool\n\n    public init(\n        scriptRunner: PluginScriptRunner,\n        workDirectory: AbsolutePath,\n        disableSandbox: Bool\n    ) {\n        self.scriptRunner = scriptRunner\n        self.workDirectory = workDirectory\n        self.disableSandbox = disableSandbox\n    }\n}\n\nextension BuildOperation {\n    private func buildPluginTools(\n        graph: ModulesGraph,\n        pluginsPerModule: [ResolvedModule.ID: [ResolvedModule]],\n        hostTriple: Basics.Triple\n    ) async throws -> [ResolvedModule.ID: [String: PluginTool]] {\n        var accessibleToolsPerPlugin: [ResolvedModule.ID: [String: PluginTool]] = [:]\n\n        var config = self.config\n\n        config.manifestPath = config.dataPath(for: .host).appending(\n            components: \"..\", \"plugin-tools.yaml\"\n        )\n\n        // FIXME: It should be possible to share database between plugin tools\n        // and regular builds. To make that happen we need to refactor\n        // `buildPackageStructure` to recognize the split.\n        config.databasePath = config.scratchDirectory.appending(\"plugin-tools.db\")\n\n        config.buildDescriptionPath = config.buildPath(for: .host).appending(\n            component: \"plugin-tools-description.json\"\n        )\n\n        let buildPlan = try await BuildPlan(\n            destinationBuildParameters: config.destinationBuildParameters,\n            toolsBuildParameters: config.toolsBuildParameters,\n            graph: graph,\n            pluginConfiguration: nil,\n            additionalFileRules: [],\n            fileSystem: config.fileSystem,\n            observabilityScope: config.observabilityScope\n        )\n\n        let (buildDescription, _) = try BuildDescription.create(\n            from: buildPlan,\n            using: config,\n            disableSandboxForPluginCommands: false\n        )\n\n        let (buildSystem, _) = try self.createBuildSystem(\n            buildDescription: buildDescription,\n            config: config\n        )\n\n        func buildToolBuilder(_ name: String, _ path: RelativePath) async throws -> AbsolutePath? {\n            let llbuildTarget = try await self.computeLLBuildTargetName(for: .product(name, for: .host))\n            let success = buildSystem.build(target: llbuildTarget)\n\n            if !success {\n                return nil\n            }\n\n            return try buildPlan.buildProducts.first {\n                $0.product.name == name && $0.buildParameters.destination == .host\n            }?.binaryPath\n        }\n\n        for (_, plugins) in pluginsPerModule {\n            for plugin in plugins where accessibleToolsPerPlugin[plugin.id] == nil {\n                // Determine the tools to which this plugin has access, and create a name-to-path mapping from tool\n                // names to the corresponding paths. Built tools are assumed to be in the build tools directory.\n                let accessibleTools = try await plugin.preparePluginTools(\n                    fileSystem: config.fileSystem,\n                    environment: config.buildEnvironment(for: .host),\n                    for: hostTriple\n                ) { name, path in\n                    if let result = try await buildToolBuilder(name, path) {\n                        return result\n                    } else {\n                        return config.buildPath(for: .host).appending(path)\n                    }\n                }\n\n                accessibleToolsPerPlugin[plugin.id] = accessibleTools\n            }\n        }\n\n        return accessibleToolsPerPlugin\n    }\n}\n\nextension BuildDescription {\n    static func create(\n        from plan: BuildPlan,\n        using config: LLBuildSystemConfiguration,\n        disableSandboxForPluginCommands: Bool\n    ) throws -> (BuildDescription, LLBuildManifest) {\n        let fileSystem = config.fileSystem\n\n        // Generate the llbuild manifest.\n        let llbuild = LLBuildManifestBuilder(\n            plan,\n            disableSandboxForPluginCommands: disableSandboxForPluginCommands,\n            fileSystem: fileSystem,\n            observabilityScope: config.observabilityScope\n        )\n        let buildManifest = try llbuild.generateManifest(at: config.manifestPath)\n\n        let swiftCommands = llbuild.manifest.getCmdToolMap(kind: SwiftCompilerTool.self)\n        let swiftFrontendCommands = llbuild.manifest.getCmdToolMap(kind: SwiftFrontendTool.self)\n        let testDiscoveryCommands = llbuild.manifest.getCmdToolMap(kind: TestDiscoveryTool.self)\n        let testEntryPointCommands = llbuild.manifest.getCmdToolMap(kind: TestEntryPointTool.self)\n        let copyCommands = llbuild.manifest.getCmdToolMap(kind: CopyTool.self)\n        let writeCommands = llbuild.manifest.getCmdToolMap(kind: WriteAuxiliaryFile.self)\n\n        // Create the build description.\n        let buildDescription = try BuildDescription(\n            plan: plan,\n            swiftCommands: swiftCommands,\n            swiftFrontendCommands: swiftFrontendCommands,\n            testDiscoveryCommands: testDiscoveryCommands,\n            testEntryPointCommands: testEntryPointCommands,\n            copyCommands: copyCommands,\n            writeCommands: writeCommands,\n            pluginDescriptions: plan.pluginDescriptions,\n            traitConfiguration: config.traitConfiguration\n        )\n        try fileSystem.createDirectory(\n            config.buildDescriptionPath.parentDirectory,\n            recursive: true\n        )\n        try buildDescription.write(\n            fileSystem: fileSystem,\n            path: config.buildDescriptionPath\n        )\n        return (buildDescription, buildManifest)\n    }\n}\n\nextension BuildSubset {\n    func recursiveDependencies(for graph: ModulesGraph, observabilityScope: ObservabilityScope) throws -> [ResolvedModule]? {\n        switch self {\n        case .allIncludingTests:\n            return Array(graph.reachableModules)\n        case .allExcludingTests:\n            return graph.reachableModules.filter { $0.type != .test }\n        case .product(let productName, _):\n            guard let product = graph.product(for: productName) else {\n                observabilityScope.emit(error: \"no product named '\\(productName)'\")\n                return nil\n            }\n            return try product.recursiveModuleDependencies()\n        case .target(let targetName, _):\n            guard let target = graph.module(for: targetName) else {\n                observabilityScope.emit(error: \"no target named '\\(targetName)'\")\n                return nil\n            }\n            return try target.recursiveModuleDependencies()\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildPlan/BuildPlan+Clang.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageGraph\nimport PackageLoading\nimport SPMBuildCore\n\nimport class PackageModel.BinaryModule\nimport class PackageModel.ClangModule\nimport class PackageModel.SwiftModule\nimport class PackageModel.SystemLibraryModule\n\nextension BuildPlan {\n    /// Plan a Clang target.\n    func plan(clangTarget: ClangModuleBuildDescription) throws {\n        let dependencies = clangTarget.recursiveDependencies(using: self)\n\n        for case .module(let dependency, let description) in dependencies {\n            switch dependency.underlying {\n            case is SwiftModule:\n                if case let .swift(dependencyTargetDescription)? = description {\n                    if let moduleMap = dependencyTargetDescription.moduleMap {\n                        // C languages clients should either import the module or include the compatibility header next to it.\n                        clangTarget.additionalFlags += [\"-I\", moduleMap.dirname]\n                    }\n                }\n\n            case let target as ClangModule where target.type == .library:\n                // Setup search paths for C dependencies:\n                clangTarget.additionalFlags += [\"-I\", target.includeDir.pathString]\n\n                if case let .clang(dependencyTargetDescription)? = description {\n                    // Add in public generated header paths\n                    clangTarget.additionalFlags += dependencyTargetDescription.pluginDerivedPublicHeaderPaths.flatMap { [\"-I\", $0.pathString] }\n                    // Add the modulemap of the dependency if it has one.\n                    if let moduleMap = dependencyTargetDescription.moduleMap {\n                        clangTarget.additionalFlags += [\"-fmodule-map-file=\\(moduleMap.pathString)\"]\n                    }\n                }\n            case let target as SystemLibraryModule:\n                clangTarget.additionalFlags += [\"-fmodule-map-file=\\(target.moduleMapPath.pathString)\"]\n                clangTarget.additionalFlags += try pkgConfig(for: target).cFlags\n            case let target as BinaryModule:\n                switch target.kind {\n                case .unknown:\n                    break\n                case .artifactsArchive:\n                    let libraries = try self.parseLibraryArtifactsArchive(for: target, triple: clangTarget.buildParameters.triple)\n                    for library in libraries {\n                        library.headersPaths.forEach {\n                            clangTarget.additionalFlags += [\"-I\", $0.pathString]\n                        }\n                        if let moduleMapPath = library.moduleMapPath {\n                            clangTarget.additionalFlags += [\"-fmodule-map-file=\\(moduleMapPath)\"]\n                        }\n\n                        clangTarget.libraryBinaryPaths.insert(library.libraryPath)\n                    }\n                case .xcframework:\n                    let libraries = try self.parseXCFramework(\n                        for: target,\n                        triple: clangTarget.buildParameters.triple,\n                        enableXCFrameworksOnLinux: clangTarget.buildParameters.enableXCFrameworksOnLinux\n                    )\n                    for library in libraries {\n                        library.headersPaths.forEach {\n                            clangTarget.additionalFlags += [\"-I\", $0.pathString]\n                        }\n                        clangTarget.libraryBinaryPaths.insert(library.libraryPath)\n                    }\n                }\n\n            default: continue\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildPlan/BuildPlan+Product.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport func Basics.depthFirstSearch\nimport struct Basics.InternalError\nimport struct Basics.Triple\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedProduct\nimport class PackageModel.BinaryModule\nimport class PackageModel.ClangModule\n\n@_spi(SwiftPMInternal)\nimport class PackageModel.Module\n\nimport class PackageModel.SwiftModule\nimport class PackageModel.SystemLibraryModule\nimport struct SPMBuildCore.BuildParameters\nimport struct SPMBuildCore.ExecutableInfo\nimport struct SPMBuildCore.LibraryInfo\nimport struct SPMBuildCore.WindowsDLLInfo\nimport func TSCBasic.topologicalSort\n\nextension BuildPlan {\n    /// Plan a product.\n    func plan(buildProduct: ProductBuildDescription) throws {\n        // Compute the product's dependency.\n        let dependencies = try computeDependencies(of: buildProduct)\n\n        var isEmbeddedSwift = false\n        for module in dependencies.staticTargets {\n            guard case .swift(let module) = module else { continue }\n            isEmbeddedSwift = isEmbeddedSwift || module.isEmbeddedSwift\n        }\n\n        // Add flags for system targets.\n        for systemModule in dependencies.systemModules {\n            guard case let target as SystemLibraryModule = systemModule.underlying else {\n                throw InternalError(\"This should not be possible.\")\n            }\n            // Add pkgConfig libs arguments.\n            buildProduct.additionalFlags += try pkgConfig(for: target).libs\n        }\n\n        // Add flags for binary dependencies.\n        for binaryPath in dependencies.libraryBinaryPaths {\n            if binaryPath.extension == \"framework\" {\n                buildProduct.additionalFlags += [\"-framework\", binaryPath.basenameWithoutExt]\n            } else if binaryPath.basename.starts(with: \"lib\") {\n                buildProduct.additionalFlags += [\"-l\\(binaryPath.basenameWithoutExt.dropFirst(3))\"]\n            } else if binaryPath.extension == \"lib\" {\n                // Static libraries on Windows\n                buildProduct.additionalFlags += [\"-l\\(binaryPath.basenameWithoutExt)\"]\n            } else {\n                self.observabilityScope.emit(error: \"unexpected binary name at \\(binaryPath). Static libraries should be prefixed with lib\")\n            }\n        }\n\n        // Don't link libc++ or libstd++ when building for Embedded Swift.\n        // Users can still link it manually for embedded platforms when needed,\n        // by providing `-Xlinker -lc++` options via CLI or `Package.swift`.\n        if !isEmbeddedSwift {\n            // Link C++ if needed.\n            // Note: This will come from build settings in future.\n            for description in dependencies.staticTargets {\n                if case let target as ClangModule = description.module.underlying, target.isCXX {\n                    let triple = buildProduct.buildParameters.triple\n                    if triple.isDarwin() || triple.isFreeBSD() {\n                        buildProduct.additionalFlags += [\"-lc++\"]\n                    } else if triple.isWindows() {\n                        // Don't link any C++ library.\n                    } else {\n                        buildProduct.additionalFlags += [\"-lstdc++\"]\n                    }\n                    break\n                }\n            }\n        }\n\n        for description in dependencies.staticTargets {\n            switch description.module.underlying {\n            case is SwiftModule:\n                // Swift targets are guaranteed to have a corresponding Swift description.\n                guard case .swift(let description) = description else {\n                    throw InternalError(\"Expected a Swift module: \\(description.module)\")\n                }\n\n                // Based on the debugging strategy, we either need to pass swiftmodule paths to the\n                // product or link in the wrapped module object. This is required for properly debugging\n                // Swift products. Debugging strategy is computed based on the current platform we're\n                // building for and is nil for the release configuration.\n                switch buildProduct.buildParameters.debuggingStrategy {\n                case .swiftAST:\n                    buildProduct.swiftASTs.insert(description.moduleOutputPath)\n                case .modulewrap:\n                    buildProduct.objects += [description.wrappedModuleOutputPath]\n                case nil:\n                    break\n                }\n            default: break\n            }\n        }\n\n        buildProduct.staticTargets = dependencies.staticTargets.map(\\.module)\n        buildProduct.dylibs = dependencies.dylibs\n        buildProduct.objects += try dependencies.staticTargets.flatMap { try $0.objects }\n        buildProduct.libraryBinaryPaths = dependencies.libraryBinaryPaths\n        buildProduct.availableTools = dependencies.availableTools\n    }\n\n    /// Computes the dependencies of a product.\n    private func computeDependencies(\n        of productDescription: ProductBuildDescription\n    ) throws -> (\n        dylibs: [ProductBuildDescription],\n        staticTargets: [ModuleBuildDescription],\n        systemModules: [ResolvedModule],\n        libraryBinaryPaths: Set<AbsolutePath>,\n        availableTools: [String: AbsolutePath]\n    ) {\n        let product = productDescription.product\n        /* Prior to tools-version 5.9, we used to erroneously recursively traverse executable/plugin dependencies and statically include their\n         targets. For compatibility reasons, we preserve that behavior for older tools-versions. */\n        let shouldExcludePlugins = productDescription.package.manifest.toolsVersion >= .v5_9\n\n        // For test targets, we need to consider the first level of transitive dependencies since the first level is\n        // always test targets.\n        let topLevelDependencies: [PackageModel.Module] = if product.type == .test {\n            product.modules.flatMap(\\.underlying.dependencies).compactMap {\n                switch $0 {\n                case .product:\n                    nil\n                case .module(let target, _):\n                    target\n                }\n            }\n        } else {\n            []\n        }\n\n        // get the dynamic libraries for explicitly linking rdar://108561857\n        func recursiveDynamicLibraries(for description: ProductBuildDescription) throws -> [ProductBuildDescription] {\n            let dylibs = try computeDependencies(of: description).dylibs\n            return try dylibs + dylibs.flatMap { try recursiveDynamicLibraries(for: $0) }\n        }\n\n        // Sort the product targets in topological order.\n        var allDependencies: [ModuleBuildDescription.Dependency] = []\n\n        do {\n            func successors(\n                for product: ResolvedProduct,\n                destination: BuildParameters.Destination\n            ) throws -> [TraversalNode] {\n                let productDependencies: [TraversalNode] = product.modules.map {\n                    .init(module: $0, context: destination)\n                }\n\n                switch product.type {\n                case .library(.automatic), .library(.static):\n                    return productDependencies\n                case .plugin:\n                    return shouldExcludePlugins ? [] : productDependencies\n                case .library(.dynamic):\n                    guard let description = self.description(for: product, context: destination) else {\n                        throw InternalError(\"Could not find a description for product: \\(product)\")\n                    }\n                    return try recursiveDynamicLibraries(for: description).map { TraversalNode(\n                        product: $0.product,\n                        context: $0.destination\n                    ) }\n                case .test, .executable, .snippet, .macro:\n                    return []\n                }\n            }\n\n            func successors(\n                for module: ResolvedModule,\n                destination: BuildParameters.Destination\n            ) -> [TraversalNode] {\n                let isTopLevel = topLevelDependencies.contains(module.underlying) || product.modules\n                    .contains(id: module.id)\n                let topLevelIsMacro = isTopLevel && product.type == .macro\n                let topLevelIsPlugin = isTopLevel && product.type == .plugin\n                let topLevelIsTest = isTopLevel && product.type == .test\n\n                if !topLevelIsMacro && !topLevelIsTest && module.type == .macro {\n                    return []\n                }\n                if shouldExcludePlugins, !topLevelIsPlugin && !topLevelIsTest && module.type == .plugin {\n                    return []\n                }\n                return module.dependencies(satisfying: productDescription.buildParameters.buildEnvironment)\n                    .map {\n                        switch $0 {\n                        case .product(let product, _):\n                            .init(product: product, context: destination)\n                        case .module(let module, _):\n                            .init(module: module, context: destination)\n                        }\n                    }\n            }\n\n            let directDependencies = product.modules\n                .map { TraversalNode(module: $0, context: productDescription.destination) }\n\n            var uniqueNodes = Set<TraversalNode>(directDependencies)\n\n            try depthFirstSearch(directDependencies) {\n                let result: [TraversalNode] = switch $0 {\n                case .product(let product, let destination):\n                    try successors(for: product, destination: destination)\n                case .module(let module, let destination):\n                    successors(for: module, destination: destination)\n                case .package:\n                    []\n                }\n\n                return result.filter { uniqueNodes.insert($0).inserted }\n            } onNext: { node, _ in\n                switch node {\n                case .package: break\n                case .product(let product, let destination):\n                    allDependencies.append(.product(product, self.description(for: product, context: destination)))\n                case .module(let module, let destination):\n                    allDependencies.append(.module(module, self.description(for: module, context: destination)))\n                }\n            }\n        }\n\n        // Create empty arrays to collect our results.\n        var linkLibraries = [ProductBuildDescription]()\n        var staticTargets = [ModuleBuildDescription]()\n        var systemModules = [ResolvedModule]()\n        var libraryBinaryPaths: Set<AbsolutePath> = []\n        var availableTools = [String: AbsolutePath]()\n\n        for dependency in allDependencies {\n            switch dependency {\n            case .module(let module, let description):\n                switch module.type {\n                // Executable target have historically only been included if they are directly in the product's\n                // target list.  Otherwise they have always been just build-time dependencies.\n                // In tool version .v5_5 or greater, we also include executable modules implemented in Swift in\n                // any test products... this is to allow testing of executables.  Note that they are also still\n                // built as separate products that the test can invoke as subprocesses.\n                case .executable, .snippet, .macro:\n                    if product.modules.contains(id: module.id) {\n                        guard let description else {\n                            throw InternalError(\"Could not find a description for module: \\(module)\")\n                        }\n                        staticTargets.append(description)\n                    } else if product.type == .test && (module.underlying as? SwiftModule)?\n                        .supportsTestableExecutablesFeature == true\n                    {\n                        // Only \"top-level\" targets should really be considered here, not transitive ones.\n                        let isTopLevel = topLevelDependencies.contains(module.underlying) || product.modules\n                            .contains(id: module.id)\n                        if let toolsVersion = graph.package(for: product)?.manifest.toolsVersion, toolsVersion >= .v5_5,\n                           isTopLevel\n                        {\n                            guard let description else {\n                                throw InternalError(\"Could not find a description for module: \\(module)\")\n                            }\n                            staticTargets.append(description)\n                        }\n                    }\n                // Test targets should be included only if they are directly in the product's target list.\n                case .test:\n                    if product.modules.contains(id: module.id) {\n                        guard let description else {\n                            throw InternalError(\"Could not find a description for module: \\(module)\")\n                        }\n                        staticTargets.append(description)\n                    }\n                // Library targets should always be included for the same build triple.\n                case .library:\n                    guard let description else {\n                        throw InternalError(\"Could not find a description for module: \\(module)\")\n                    }\n                    if description.destination == productDescription.destination {\n                        staticTargets.append(description)\n                    }\n                // Add system target to system targets array.\n                case .systemModule:\n                    systemModules.append(module)\n                // Add binary to binary paths set.\n                case .binary:\n                    guard let binaryTarget = module.underlying as? BinaryModule else {\n                        throw InternalError(\"invalid binary target '\\(module.name)'\")\n                    }\n                    switch binaryTarget.kind {\n                    case .xcframework:\n                        let libraries = try self.parseXCFramework(\n                            for: binaryTarget,\n                            triple: productDescription.buildParameters.triple,\n                            enableXCFrameworksOnLinux: productDescription.buildParameters.enableXCFrameworksOnLinux\n                        )\n                        for library in libraries {\n                            libraryBinaryPaths.insert(library.libraryPath)\n                        }\n                    case .artifactsArchive:\n                        let tools = try self.parseExecutableArtifactsArchive(\n                            for: binaryTarget, triple: productDescription.buildParameters.triple\n                        )\n                        for tool in tools {\n                            availableTools[tool.name] = tool.executablePath\n                        }\n                        \n                        let libraries = try self.parseLibraryArtifactsArchive(\n                            for: binaryTarget,\n                            triple: productDescription.buildParameters.triple\n                        )\n                        for library in libraries {\n                            libraryBinaryPaths.insert(library.libraryPath)\n                        }\n                    case .unknown:\n                        throw InternalError(\"unknown binary target '\\(module.name)' type\")\n                    }\n                case .plugin:\n                    continue\n                }\n\n            case .product(let product, let description):\n                // Add the dynamic products to array of libraries to link.\n                if product.type == .library(.dynamic) {\n                    guard let description else {\n                        throw InternalError(\"Dynamic library product should have description: \\(product)\")\n                    }\n                    linkLibraries.append(description)\n                }\n            }\n        }\n\n        // Add derived test targets, if necessary\n        if product.type == .test, let derivedTestTargets = derivedTestTargetsMap[product.id] {\n            staticTargets.append(contentsOf: derivedTestTargets.compactMap {\n                self.description(for: $0, context: productDescription.destination)\n            })\n        }\n\n        return (linkLibraries, staticTargets, systemModules, libraryBinaryPaths, availableTools)\n    }\n\n    /// Extracts the artifacts  from an artifactsArchive\n    func parseExecutableArtifactsArchive(for module: BinaryModule, triple: Triple) throws -> [ExecutableInfo] {\n        try self.externalExecutablesCache.memoize(key: module) {\n            let execInfos = try module.parseExecutableArtifactArchives(for: triple, fileSystem: self.fileSystem)\n            return execInfos.filter { !$0.supportedTriples.isEmpty }\n        }\n    }\n\n    func parseWindowsDLLArtifactsArchive(for module: BinaryModule, triple: Triple) throws -> [WindowsDLLInfo] {\n        try self.externalWindowsDLLCache.memoize(key: module) {\n            let dllInfos = try module.parseWindowsDLLArtifactArchives(for: triple, fileSystem: self.fileSystem)\n            return dllInfos.filter { !$0.supportedTriples.isEmpty }\n        }\n    }\n\n    func parseLibraryArtifactsArchive(for module: BinaryModule, triple: Triple) throws -> [LibraryInfo] {\n        try self.externalLibrariesCache.memoize(key: module) {\n            try module.parseLibraryArtifactArchives(for: triple, fileSystem: self.fileSystem)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildPlan/BuildPlan+Swift.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.InternalError\n\nimport class PackageModel.BinaryModule\nimport class PackageModel.ClangModule\nimport class PackageModel.SwiftModule\nimport class PackageModel.SystemLibraryModule\n\nimport PackageGraph\nimport PackageLoading\nimport SPMBuildCore\n\nextension BuildPlan {\n    func plan(swiftTarget: SwiftModuleBuildDescription) throws {\n        // We need to iterate recursive dependencies because Swift compiler needs to see all the targets a target\n        // builds against\n        var prebuiltPaths = Set<String>()\n        for case .module(let dependency, let description) in swiftTarget.recursiveLinkDependencies(using: self) {\n            switch dependency.underlying {\n            case let underlyingTarget as ClangModule where underlyingTarget.type == .library:\n                guard case let .clang(target)? = description else {\n                    throw InternalError(\"unexpected clang target \\(underlyingTarget)\")\n                }\n                // Add the path to modulemap of the dependency. Currently we require that all Clang targets have a\n                // modulemap but we may want to remove that requirement since it is valid for a target to exist without\n                // one. However, in that case it will not be importable in Swift targets. We may want to emit a warning\n                // in that case from here.\n                guard let moduleMap = target.moduleMap else { break }\n                swiftTarget.additionalFlags += [\n                    \"-Xcc\", \"-fmodule-map-file=\\(moduleMap.pathString)\",\n                    \"-Xcc\", \"-I\", \"-Xcc\", target.clangTarget.includeDir.pathString,\n                ]\n                swiftTarget.additionalFlags += target.pluginDerivedPublicHeaderPaths.flatMap {\n                    [\"-Xcc\", \"-I\", \"-Xcc\", $0.pathString]\n                }\n            case let target as SwiftModule:\n                // Copy include paths over if needed\n                let targetPaths = Set(swiftTarget.target.underlying.buildSettings.assignments[.PREBUILT_INCLUDE_PATHS]?.flatMap(\\.values) ?? [])\n                if let assignment = target.buildSettings.assignments[.PREBUILT_INCLUDE_PATHS] {\n                    for path in assignment.flatMap(\\.values) {\n                        if !prebuiltPaths.contains(path), !targetPaths.contains(path) {\n                            swiftTarget.additionalFlags += [\"-I\", path]\n                        }\n                        // Dedup the path\n                        prebuiltPaths.insert(path)\n                    }\n                }\n            case let target as SystemLibraryModule:\n                swiftTarget.additionalFlags += [\"-Xcc\", \"-fmodule-map-file=\\(target.moduleMapPath.pathString)\"]\n                swiftTarget.additionalFlags += try pkgConfig(for: target).cFlags\n            case let target as BinaryModule:\n                switch target.kind {\n                case .unknown:\n                    break\n                case .artifactsArchive:\n                    let libraries = try self.parseLibraryArtifactsArchive(for: target, triple: swiftTarget.buildParameters.triple)\n                    for library in libraries {\n                        library.headersPaths.forEach {\n                            swiftTarget.additionalFlags += [\"-I\", $0.pathString, \"-Xcc\", \"-I\", \"-Xcc\", $0.pathString]\n                        }\n                        if let moduleMapPath = library.moduleMapPath {\n                            // We need to pass the module map if there is one. If there is none Swift cannot import it but\n                            // this might still be valid\n                            swiftTarget.additionalFlags += [\"-Xcc\", \"-fmodule-map-file=\\(moduleMapPath)\"]\n                        }\n\n                        swiftTarget.libraryBinaryPaths.insert(library.libraryPath)\n                    }\n\n                    // Record usages of Windows DLLs\n                    for dll in try parseWindowsDLLArtifactsArchive(for: target, triple: swiftTarget.buildParameters.triple) {\n                        swiftTarget.windowsDLLBinaryPaths.insert(dll.dllPath)\n                    }\n                case .xcframework:\n                    let libraries = try self.parseXCFramework(\n                        for: target,\n                        triple: swiftTarget.buildParameters.triple,\n                        enableXCFrameworksOnLinux: swiftTarget.buildParameters.enableXCFrameworksOnLinux\n                    )\n                    for library in libraries {\n                        library.headersPaths.forEach {\n                            swiftTarget.additionalFlags += [\"-I\", $0.pathString, \"-Xcc\", \"-I\", \"-Xcc\", $0.pathString]\n                        }\n                        swiftTarget.libraryBinaryPaths.insert(library.libraryPath)\n                    }\n                }\n            default:\n                break\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildPlan/BuildPlan+Test.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Basics.ObservabilityScope\nimport struct Basics.InternalError\nimport struct Basics.AbsolutePath\nimport struct LLBuildManifest.TestDiscoveryTool\nimport struct LLBuildManifest.TestEntryPointTool\nimport struct PackageGraph.ModulesGraph\n\n@_spi(SwiftPMInternal)\nimport struct PackageGraph.ResolvedPackage\n\n@_spi(SwiftPMInternal)\nimport struct PackageGraph.ResolvedProduct\n\n@_spi(SwiftPMInternal)\nimport struct PackageGraph.ResolvedModule\n\nimport struct PackageModel.Sources\nimport enum PackageModel.BuildSettings\nimport class PackageModel.SwiftModule\nimport class PackageModel.Module\nimport struct SPMBuildCore.BuildParameters\nimport protocol TSCBasic.FileSystem\n\nextension BuildPlan {\n    static func makeDerivedTestTargets(\n        testProducts: [ProductBuildDescription],\n        destinationBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n        shouldDisableSandbox: Bool,\n        _ fileSystem: FileSystem,\n        _ observabilityScope: ObservabilityScope\n    ) throws -> [(product: ResolvedProduct, discoveryTargetBuildDescription: SwiftModuleBuildDescription?, entryPointTargetBuildDescription: SwiftModuleBuildDescription)] {\n        var explicitlyEnabledDiscovery = false\n        var explicitlySpecifiedPath: AbsolutePath?\n        if case let .entryPointExecutable(caseExplicitlyEnabledDiscovery, caseExplicitlySpecifiedPath) = destinationBuildParameters.testProductStyle {\n            explicitlyEnabledDiscovery = caseExplicitlyEnabledDiscovery\n            explicitlySpecifiedPath = caseExplicitlySpecifiedPath\n        }\n        let isEntryPointPathSpecifiedExplicitly = explicitlySpecifiedPath != nil\n\n        var isDiscoveryEnabledRedundantly = explicitlyEnabledDiscovery && !isEntryPointPathSpecifiedExplicitly\n        var result: [(ResolvedProduct, SwiftModuleBuildDescription?, SwiftModuleBuildDescription)] = []\n        for testBuildDescription in testProducts {\n            let testProduct = testBuildDescription.product\n            let package = testBuildDescription.package\n\n            isDiscoveryEnabledRedundantly = isDiscoveryEnabledRedundantly && nil == testProduct.testEntryPointModule\n            // If a non-explicitly specified test entry point file exists, prefer that over test discovery.\n            // This is designed as an escape hatch when test discovery is not appropriate and for backwards\n            // compatibility for projects that have existing test entry point files (e.g. XCTMain.swift, LinuxMain.swift).\n            let toolsVersion = package.manifest.toolsVersion\n\n            // If `testProduct.testEntryPointTarget` is non-nil, it may either represent an `XCTMain.swift` (formerly `LinuxMain.swift`) file\n            // if such a file is located in the package, or it may represent a test entry point file at a path specified by the option\n            // `--experimental-test-entry-point-path <file>`. The latter is useful because it still performs test discovery and places the discovered\n            // tests into a separate target/module named \"<PackageName>PackageDiscoveredTests\". Then, that entry point file may import that module and\n            // obtain that list to pass it to the `XCTMain(...)` function and avoid needing to maintain a list of tests itself.\n            if testProduct.testEntryPointModule != nil && explicitlyEnabledDiscovery && !isEntryPointPathSpecifiedExplicitly {\n                let testEntryPointName = testProduct.underlying.testEntryPointPath?.basename ?? SwiftModule.defaultTestEntryPointName\n                observabilityScope.emit(warning: \"'--enable-test-discovery' was specified so the '\\(testEntryPointName)' entry point file for '\\(testProduct.name)' will be ignored and an entry point will be generated automatically. To use test discovery with a custom entry point file, pass '--experimental-test-entry-point-path <file>'.\")\n            } else if testProduct.testEntryPointModule == nil, let testEntryPointPath = explicitlySpecifiedPath, !fileSystem.exists(testEntryPointPath) {\n                observabilityScope.emit(error: \"'--experimental-test-entry-point-path' was specified but the file '\\(testEntryPointPath)' could not be found.\")\n            }\n\n            /// Generates test discovery modules, which contain derived sources listing the discovered tests.\n            func generateDiscoveryTargets() throws -> (target: SwiftModule, resolved: ResolvedModule, buildDescription: SwiftModuleBuildDescription) {\n                let discoveryTargetName = \"\\(package.manifest.displayName)PackageDiscoveredTests\"\n                let discoveryDerivedDir = destinationBuildParameters.buildPath.appending(components: \"\\(discoveryTargetName).derived\")\n                let discoveryMainFile = discoveryDerivedDir.appending(component: TestDiscoveryTool.mainFileName)\n\n                var discoveryPaths: [AbsolutePath] = []\n                var discoveryBuildSettings: BuildSettings.AssignmentTable = .init()\n                discoveryPaths.append(discoveryMainFile)\n                for testTarget in testProduct.modules {\n                    let path = discoveryDerivedDir.appending(components: testTarget.name + \".swift\")\n                    discoveryPaths.append(path)\n                    // Add in the include path from the test targets to ensure this module builds\n                    if let flags = testTarget.underlying.buildSettings.assignments[.OTHER_SWIFT_FLAGS] {\n                        for assignment in flags {\n                            let values = assignment.values.filter({ $0.hasPrefix(\"-I\") })\n                            if !values.isEmpty {\n                                discoveryBuildSettings.add(.init(values: values, conditions: []), for: .OTHER_SWIFT_FLAGS)\n                            }\n                        }\n                    }\n                }\n\n                let discoveryTarget = SwiftModule(\n                    name: discoveryTargetName,\n                    dependencies: testProduct.underlying.modules.map { .module($0, conditions: []) },\n                    packageAccess: true, // test target is allowed access to package decls by default\n                    testDiscoverySrc: Sources(paths: discoveryPaths, root: discoveryDerivedDir),\n                    buildSettings: discoveryBuildSettings,\n                    implicit: true\n                )\n                let discoveryResolvedModule = ResolvedModule(\n                    packageIdentity: testProduct.packageIdentity,\n                    underlying: discoveryTarget,\n                    dependencies: testProduct.modules.map { .module($0, conditions: []) },\n                    defaultLocalization: testProduct.defaultLocalization,\n                    supportedPlatforms: testProduct.supportedPlatforms,\n                    platformConstraint: .all,\n                    platformVersionProvider: testProduct.platformVersionProvider\n                )\n\n                let discoveryTargetBuildDescription = try SwiftModuleBuildDescription(\n                    package: package,\n                    target: discoveryResolvedModule,\n                    toolsVersion: toolsVersion,\n                    buildParameters: testBuildDescription.buildParameters,\n                    macroBuildParameters: toolsBuildParameters,\n                    testTargetRole: .discovery,\n                    shouldDisableSandbox: shouldDisableSandbox,\n                    fileSystem: fileSystem,\n                    observabilityScope: observabilityScope\n                )\n\n                return (discoveryTarget, discoveryResolvedModule, discoveryTargetBuildDescription)\n            }\n\n            /// Generates a synthesized test entry point target, consisting of a single \"main\" file which calls the test entry\n            /// point API and leverages the test discovery target to reference which tests to run.\n            func generateSynthesizedEntryPointTarget(\n                swiftTargetDependencies: [Module.Dependency],\n                resolvedTargetDependencies: [ResolvedModule.Dependency]\n            ) throws -> SwiftModuleBuildDescription {\n                let entryPointDerivedDir = destinationBuildParameters.buildPath.appending(components: \"\\(testProduct.name).derived\")\n                let entryPointMainFileName = TestEntryPointTool.mainFileName\n                let entryPointMainFile = entryPointDerivedDir.appending(component: entryPointMainFileName)\n                let entryPointSources = Sources(paths: [entryPointMainFile], root: entryPointDerivedDir)\n\n                var entryPointBuildSettings: BuildSettings.AssignmentTable = .init()\n                for testTarget in testProduct.modules {\n                    // Add in the include path from the test targets to ensure this module builds\n                    if let flags = testTarget.underlying.buildSettings.assignments[.OTHER_SWIFT_FLAGS] {\n                        for assignment in flags {\n                            let values = assignment.values.filter({ $0.hasPrefix(\"-I\") })\n                            if !values.isEmpty {\n                                entryPointBuildSettings.add(.init(values: values, conditions: []), for: .OTHER_SWIFT_FLAGS)\n                            }\n                        }\n                    }\n                }\n\n                let entryPointTarget = SwiftModule(\n                    name: testProduct.name,\n                    type: .library,\n                    dependencies: testProduct.underlying.modules.map { .module($0, conditions: []) } + swiftTargetDependencies,\n                    packageAccess: true, // test target is allowed access to package decls\n                    testEntryPointSources: entryPointSources,\n                    buildSettings: entryPointBuildSettings\n                )\n\n                let entryPointResolvedTarget = ResolvedModule(\n                    packageIdentity: testProduct.packageIdentity,\n                    underlying: entryPointTarget,\n                    dependencies: testProduct.modules.map { .module($0, conditions: []) } + resolvedTargetDependencies,\n                    defaultLocalization: testProduct.defaultLocalization,\n                    supportedPlatforms: testProduct.supportedPlatforms,\n                    platformConstraint: .all,\n                    platformVersionProvider: testProduct.platformVersionProvider\n                )\n\n                return try SwiftModuleBuildDescription(\n                    package: package,\n                    target: entryPointResolvedTarget,\n                    toolsVersion: toolsVersion,\n                    buildParameters: testBuildDescription.buildParameters,\n                    macroBuildParameters: toolsBuildParameters,\n                    testTargetRole: .entryPoint(isSynthesized: true),\n                    shouldDisableSandbox: shouldDisableSandbox,\n                    fileSystem: fileSystem,\n                    observabilityScope: observabilityScope\n                )\n            }\n\n            let discoveryTargets: (target: SwiftModule, resolved: ResolvedModule, buildDescription: SwiftModuleBuildDescription)?\n            let swiftTargetDependencies: [Module.Dependency]\n            let resolvedTargetDependencies: [ResolvedModule.Dependency]\n\n            if destinationBuildParameters.triple.isDarwin() {\n                discoveryTargets = nil\n                swiftTargetDependencies = []\n                resolvedTargetDependencies = []\n            } else {\n                discoveryTargets = try generateDiscoveryTargets()\n                swiftTargetDependencies = [.module(discoveryTargets!.target, conditions: [])]\n                resolvedTargetDependencies = [.module(discoveryTargets!.resolved, conditions: [])]\n            }\n\n            if !destinationBuildParameters.triple.isDarwin(), let entryPointResolvedTarget = testProduct.testEntryPointModule {\n                if isEntryPointPathSpecifiedExplicitly || explicitlyEnabledDiscovery {\n                    if isEntryPointPathSpecifiedExplicitly {\n                        // Allow using the explicitly-specified test entry point target, but still perform test discovery and thus declare a dependency on the discovery modules.\n                        let entryPointTarget = SwiftModule(\n                            name: entryPointResolvedTarget.underlying.name,\n                            dependencies: entryPointResolvedTarget.underlying.dependencies + swiftTargetDependencies,\n                            packageAccess: entryPointResolvedTarget.packageAccess,\n                            testEntryPointSources: entryPointResolvedTarget.underlying.sources\n                        )\n                        let entryPointResolvedTarget = ResolvedModule(\n                            packageIdentity: testProduct.packageIdentity,\n                            underlying: entryPointTarget,\n                            dependencies: entryPointResolvedTarget.dependencies + resolvedTargetDependencies,\n                            defaultLocalization: testProduct.defaultLocalization,\n                            supportedPlatforms: testProduct.supportedPlatforms,\n                            platformConstraint: .all,\n                            platformVersionProvider: testProduct.platformVersionProvider\n                        )\n                        let entryPointTargetBuildDescription = try SwiftModuleBuildDescription(\n                            package: package,\n                            target: entryPointResolvedTarget,\n                            toolsVersion: toolsVersion,\n                            buildParameters: destinationBuildParameters,\n                            macroBuildParameters: toolsBuildParameters,\n                            testTargetRole: .entryPoint(isSynthesized: false),\n                            shouldDisableSandbox: shouldDisableSandbox,\n                            fileSystem: fileSystem,\n                            observabilityScope: observabilityScope\n                        )\n\n                        result.append((testProduct, discoveryTargets?.buildDescription, entryPointTargetBuildDescription))\n                    } else {\n                        // Ignore test entry point and synthesize one, declaring a dependency on the test discovery targets created above.\n                        let entryPointTargetBuildDescription = try generateSynthesizedEntryPointTarget(\n                            swiftTargetDependencies: swiftTargetDependencies,\n                            resolvedTargetDependencies: resolvedTargetDependencies\n                        )\n                        result.append((testProduct, discoveryTargets?.buildDescription, entryPointTargetBuildDescription))\n                    }\n                } else {\n                    // Use the test entry point as-is, without performing test discovery.\n                    let entryPointTargetBuildDescription = try SwiftModuleBuildDescription(\n                        package: package,\n                        target: entryPointResolvedTarget,\n                        toolsVersion: toolsVersion,\n                        buildParameters: destinationBuildParameters,\n                        macroBuildParameters: toolsBuildParameters,\n                        testTargetRole: .entryPoint(isSynthesized: false),\n                        shouldDisableSandbox: shouldDisableSandbox,\n                        fileSystem: fileSystem,\n                        observabilityScope: observabilityScope\n                    )\n                    result.append((testProduct, nil, entryPointTargetBuildDescription))\n                }\n            } else {\n                // Synthesize a test entry point target, declaring a dependency on the test discovery targets.\n                let entryPointTargetBuildDescription = try generateSynthesizedEntryPointTarget(\n                    swiftTargetDependencies: swiftTargetDependencies,\n                    resolvedTargetDependencies: resolvedTargetDependencies\n                )\n                result.append((testProduct, discoveryTargets?.buildDescription, entryPointTargetBuildDescription))\n            }\n        }\n\n        if isDiscoveryEnabledRedundantly {\n            observabilityScope.emit(warning: \"'--enable-test-discovery' option is deprecated; tests are automatically discovered on all platforms\")\n        }\n\n        return result\n    }\n}\n\nprivate extension PackageModel.SwiftModule {\n    /// Initialize a SwiftTarget representing a test entry point.\n    convenience init(\n        name: String,\n        type: PackageModel.Module.Kind? = nil,\n        dependencies: [PackageModel.Module.Dependency],\n        packageAccess: Bool,\n        testEntryPointSources sources: Sources,\n        buildSettings: BuildSettings.AssignmentTable = .init()\n    ) {\n        self.init(\n            name: name,\n            type: type ?? .executable,\n            path: .root,\n            sources: sources,\n            dependencies: dependencies,\n            packageAccess: packageAccess,\n            buildSettings: buildSettings,\n            usesUnsafeFlags: false,\n            implicit: true\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/Build/BuildPlan/BuildPlan.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Basics\nimport Foundation\nimport LLBuildManifest\nimport OrderedCollections\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SPMBuildCore\nimport TSCBasic\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftDriver\n#else\nimport SwiftDriver\n#endif\n\nimport enum TSCUtility.Diagnostics\nimport var TSCUtility.verbosity\n\nextension String {\n    var asSwiftStringLiteralConstant: String {\n        unicodeScalars.reduce(\"\") { $0 + $1.escaped(asASCII: false) }\n    }\n}\n\nextension BuildParameters {\n    /// Returns the directory to be used for module cache.\n    public var moduleCache: Basics.AbsolutePath {\n        get throws {\n            // FIXME: We use this hack to let swiftpm's functional test use shared\n            // cache so it doesn't become painfully slow.\n            if let path = Environment.current[\"SWIFTPM_TESTS_MODULECACHE\"] {\n                return try AbsolutePath(validating: path)\n            }\n            return buildPath.appending(\"ModuleCache\")\n        }\n    }\n\n    /// Returns the compiler arguments for the index store, if enabled.\n    func indexStoreArguments(for target: ResolvedModule) -> [String] {\n        let addIndexStoreArguments: Bool\n        switch indexStoreMode {\n        case .on:\n            addIndexStoreArguments = true\n        case .off:\n            addIndexStoreArguments = false\n        case .auto:\n            if configuration == .debug {\n                addIndexStoreArguments = true\n            } else if target.type == .test {\n                // Test discovery requires an index store for the test target to discover the tests\n                addIndexStoreArguments = true\n            } else {\n                addIndexStoreArguments = false\n            }\n        }\n\n        if addIndexStoreArguments {\n            return [\"-index-store-path\", indexStore.pathString]\n        }\n        return []\n    }\n\n    /// Computes the target triple arguments for a given resolved target.\n    public func tripleArgs(for target: ResolvedModule) throws -> [String] {\n        // confusingly enough this is the triple argument, not the target argument\n        var args = [\"-target\"]\n\n        // Compute the triple string for Darwin platform using the platform version.\n        if self.triple.isDarwin() {\n            let platform = self.buildEnvironment.platform\n            let supportedPlatform = target.getSupportedPlatform(for: platform, usingXCTest: target.type == .test)\n            args += [self.triple.tripleString(forPlatformVersion: supportedPlatform.version.versionString)]\n        } else {\n            args += [self.triple.tripleString]\n        }\n        return args\n    }\n\n    /// Computes the linker flags to use in order to rename a module-named main function to 'main' for the target\n    /// platform, or nil if the linker doesn't support it for the platform.\n    func linkerFlagsForRenamingMainFunction(of target: ResolvedModule) -> [String]? {\n        let args: [String]\n        switch self.triple.objectFormat {\n        case .macho:\n            args = [\"-alias\", \"_\\(target.c99name)_main\", \"_main\"]\n        case .elf:\n            args = [\"--defsym\", \"main=\\(target.c99name)_main\"]\n        case .coff:\n            // If the user is specifying a custom entry point name that isn't \"main\", assume they may be setting WinMain or wWinMain\n            // and don't do any modifications ourselves. In that case the linker will infer the WINDOWS subsystem and call WinMainCRTStartup,\n            // which will then call the custom entry point. And WinMain/wWinMain != main, so this still won't run into duplicate symbol\n            // issues when called from a test target, which always uses main.\n            if let customEntryPointFunctionName = findCustomEntryPointFunctionName(of: target), customEntryPointFunctionName != \"main\" {\n                return nil\n            }\n            args = [\"/ALTERNATENAME:main=\\(target.c99name)_main\", \"/SUBSYSTEM:CONSOLE\"]\n        default:\n            return nil\n        }\n        return args.asSwiftcLinkerFlags()\n    }\n\n    private func findCustomEntryPointFunctionName(of target: ResolvedModule) -> String? {\n        let flags = createScope(for: target).evaluate(.OTHER_SWIFT_FLAGS)\n        var it = flags.makeIterator()\n        while let value = it.next() {\n            if value == \"-Xfrontend\" && it.next() == \"-entry-point-function-name\" && it.next() == \"-Xfrontend\" {\n                return it.next()\n            }\n        }\n        return nil\n    }\n\n    /// Returns the scoped view of build settings for a given target.\n    func createScope(for target: ResolvedModule) -> BuildSettings.Scope {\n        BuildSettings.Scope(target.underlying.buildSettings, environment: buildEnvironment)\n    }\n}\n\n/// A build plan for a package graph.\npublic class BuildPlan: SPMBuildCore.BuildPlan {\n    /// Return value of `inputs()`\n    package enum Input {\n        /// Any file in this directory affects the build plan\n        case directoryStructure(Basics.AbsolutePath)\n        /// The file at the given path affects the build plan\n        case file(Basics.AbsolutePath)\n    }\n\n    public enum Error: Swift.Error, CustomStringConvertible, Equatable {\n        /// There is no buildable target in the graph.\n        case noBuildableTarget\n\n        public var description: String {\n            switch self {\n            case .noBuildableTarget:\n                return \"\"\"\n                The package does not contain a buildable target.\n                Add at least one `.target` or `.executableTarget` to your `Package.swift`.\n                \"\"\"\n            }\n        }\n    }\n\n    /// Build parameters used for products.\n    public let destinationBuildParameters: BuildParameters\n\n    /// Build parameters used for tools.\n    public let toolsBuildParameters: BuildParameters\n\n    /// The package graph.\n    public let graph: ModulesGraph\n\n    /// The target build description map.\n    public let targetMap: IdentifiableSet<ModuleBuildDescription>\n\n    /// The product build description map.\n    public let productMap: IdentifiableSet<ProductBuildDescription>\n\n    /// The plugin descriptions. Plugins are represented in the package graph\n    /// as targets, but they are not directly included in the build graph.\n    public let pluginDescriptions: [PluginBuildDescription]\n\n    /// The build targets.\n    public var targets: AnySequence<ModuleBuildDescription> {\n        AnySequence(self.targetMap.values)\n    }\n\n    /// The products in this plan.\n    public var buildProducts: AnySequence<SPMBuildCore.ProductBuildDescription> {\n        AnySequence(self.productMap.values.map { $0 as SPMBuildCore.ProductBuildDescription })\n    }\n\n    public var buildModules: AnySequence<SPMBuildCore.ModuleBuildDescription> {\n        AnySequence(self.targetMap.values.map { $0 as SPMBuildCore.ModuleBuildDescription })\n    }\n\n    /// The results of invoking any build tool plugins used by targets in this build.\n    public let buildToolPluginInvocationResults: [ResolvedModule.ID: [BuildToolPluginInvocationResult]]\n\n    /// The results of running any prebuild commands for the targets in this build.  This includes any derived\n    /// source files as well as directories to which any changes should cause us to reevaluate the build plan.\n    public let prebuildCommandResults: [ResolvedModule.ID: [CommandPluginResult]]\n\n    @_spi(SwiftPMInternal)\n    public private(set) var derivedTestTargetsMap: [ResolvedProduct.ID: [ResolvedModule]] = [:]\n\n    /// Cache for pkgConfig flags.\n    private var pkgConfigCache = [SystemLibraryModule: (cFlags: [String], libs: [String])]()\n\n    /// Cache for library information.\n    var externalLibrariesCache = [BinaryModule: [LibraryInfo]]()\n\n    /// Cache for tools information.\n    var externalExecutablesCache = [BinaryModule: [ExecutableInfo]]()\n\n    /// Cache for Windows DLL information.\n    var externalWindowsDLLCache = [BinaryModule: [WindowsDLLInfo]]()\n\n    /// Whether to disable sandboxing (e.g. for macros).\n    private let shouldDisableSandbox: Bool\n\n    /// The filesystem to operate on.\n    let fileSystem: any FileSystem\n\n    /// ObservabilityScope with which to emit diagnostics\n    let observabilityScope: ObservabilityScope\n\n    @available(*, deprecated, renamed: \"init(destinationBuildParameters:toolsBuildParameters:graph:fileSystem:observabilityScope:)\")\n    public convenience init(\n        productsBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n        graph: ModulesGraph,\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        try await self.init(\n            destinationBuildParameters: productsBuildParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            graph: graph,\n            pluginConfiguration: nil,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Create a build plan with a package graph and explicitly distinct build parameters for destination platform and\n    /// tools platform.\n    public init(\n        destinationBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n        graph: ModulesGraph,\n        pluginConfiguration: PluginConfiguration? = nil,\n        pluginTools: [ResolvedModule.ID: [String: PluginTool]] = [:],\n        additionalFileRules: [FileRuleDescription] = [],\n        pkgConfigDirectories: [Basics.AbsolutePath] = [],\n        disableSandbox: Bool = false,\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        self.destinationBuildParameters = destinationBuildParameters\n        self.toolsBuildParameters = toolsBuildParameters\n        self.graph = graph\n        self.shouldDisableSandbox = disableSandbox\n        self.fileSystem = fileSystem\n\n        var buildToolPluginInvocationResults: [ResolvedModule.ID: [BuildToolPluginInvocationResult]] = [:]\n        var prebuildCommandResults: [ResolvedModule.ID: [CommandPluginResult]] = [:]\n\n        // Create product description for each product we have in the package graph that is eligible.\n        var productMap = IdentifiableSet<ProductBuildDescription>()\n        // Create build target description for each target which we need to plan.\n        // Plugin targets are noted, since they need to be compiled, but they do\n        // not get directly incorporated into the build description that will be\n        // given to LLBuild.\n        var targetMap = IdentifiableSet<ModuleBuildDescription>()\n        var pluginDescriptions = [PluginBuildDescription]()\n        var shouldGenerateTestObservation = true\n\n        let planningObservabilityScope = observabilityScope.makeChildScope(description: \"Planning\")\n        try await Self.computeDestinations(\n            graph: graph,\n            onProduct: { product, destination in\n                if !product.shouldCreateProductDescription {\n                    return\n                }\n\n                guard let package = graph.package(for: product) else {\n                    throw InternalError(\"Package not found for product: \\(product.name)\")\n                }\n\n                try productMap.insert(ProductBuildDescription(\n                    package: package,\n                    product: product,\n                    toolsVersion: package.manifest.toolsVersion,\n                    buildParameters: destination == .host ? toolsBuildParameters : destinationBuildParameters,\n                    fileSystem: fileSystem,\n                    observabilityScope: planningObservabilityScope\n                ))\n            },\n            onModule: { module, destination in\n                guard let package = graph.package(for: module) else {\n                    throw InternalError(\"Package not found for module: \\(module.name)\")\n                }\n\n                let buildParameters = destination == .host ? toolsBuildParameters : destinationBuildParameters\n\n                // Validate the product dependencies of this target.\n                for dependency in module.dependencies {\n                    guard dependency.satisfies(buildParameters.buildEnvironment) else {\n                        continue\n                    }\n\n                    switch dependency {\n                    case .module: break\n                    case .product(let product, _):\n                        if buildParameters.triple.isDarwin() {\n                            try BuildPlan.validateDeploymentVersionOfProductDependency(\n                                product: product,\n                                forTarget: module,\n                                buildEnvironment: buildParameters.buildEnvironment,\n                                observabilityScope: planningObservabilityScope\n                                                        .makeChildScope(description: \"Validate Deployment of Dependency\")\n                            )\n                        }\n                    }\n                }\n\n                if let pluginConfiguration, !buildParameters.shouldSkipBuilding {\n                    let pluginInvocationResults = try await Self.invokeBuildToolPlugins(\n                        for: module,\n                        destination: destination,\n                        configuration: pluginConfiguration,\n                        buildParameters: toolsBuildParameters,\n                        modulesGraph: graph,\n                        tools: pluginTools,\n                        additionalFileRules: additionalFileRules,\n                        pkgConfigDirectories: pkgConfigDirectories,\n                        fileSystem: fileSystem,\n                        observabilityScope: planningObservabilityScope,\n                        surfaceDiagnostics: true\n                    )\n\n                    if pluginInvocationResults.contains(where: { !$0.succeeded }) {\n                        throw StringError(\"build planning stopped due to build-tool plugin failures\")\n                    }\n\n                    buildToolPluginInvocationResults[module.id] = pluginInvocationResults\n                    prebuildCommandResults[module.id] = try Self.runPluginCommands(\n                        using: pluginConfiguration,\n                        for: pluginInvocationResults,\n                        fileSystem: fileSystem,\n                        observabilityScope: planningObservabilityScope\n                    )\n                }\n\n                switch module.underlying {\n                case is SwiftModule:\n                    var generateTestObservation = false\n                    if module.type == .test && shouldGenerateTestObservation {\n                        generateTestObservation = true\n                        shouldGenerateTestObservation = false // Only generate the code once.\n                    }\n\n                    try targetMap.insert(.swift(\n                        SwiftModuleBuildDescription(\n                            package: package,\n                            target: module,\n                            toolsVersion: package.manifest.toolsVersion,\n                            additionalFileRules: additionalFileRules,\n                            buildParameters: buildParameters,\n                            macroBuildParameters: toolsBuildParameters,\n                            buildToolPluginInvocationResults: buildToolPluginInvocationResults[module.id] ?? [],\n                            prebuildCommandResults: prebuildCommandResults[module.id] ?? [],\n                            shouldGenerateTestObservation: generateTestObservation,\n                            shouldDisableSandbox: disableSandbox,\n                            fileSystem: fileSystem,\n                            observabilityScope: planningObservabilityScope\n                        )\n                    ))\n                case is ClangModule:\n                    try targetMap.insert(.clang(\n                        ClangModuleBuildDescription(\n                            package: package,\n                            target: module,\n                            toolsVersion: package.manifest.toolsVersion,\n                            additionalFileRules: additionalFileRules,\n                            buildParameters: buildParameters,\n                            buildToolPluginInvocationResults: buildToolPluginInvocationResults[module.id] ?? [],\n                            prebuildCommandResults: prebuildCommandResults[module.id] ?? [],\n                            fileSystem: fileSystem,\n                            observabilityScope: planningObservabilityScope\n                        )\n                    ))\n                case is PluginModule:\n                    try module.dependencies.compactMap {\n                        switch $0 {\n                        case .module(let moduleDependency, _):\n                            if moduleDependency.type == .executable {\n                                return graph.product(for: moduleDependency.name)\n                            }\n                            return nil\n                        default:\n                            return nil\n                        }\n                    }.forEach {\n                        try productMap.insert(ProductBuildDescription(\n                            package: package,\n                            product: $0,\n                            toolsVersion: package.manifest.toolsVersion,\n                            buildParameters: toolsBuildParameters,\n                            fileSystem: fileSystem,\n                            observabilityScope: planningObservabilityScope\n                        ))\n                    }\n\n                    try pluginDescriptions.append(PluginBuildDescription(\n                        module: module,\n                        products: package.products.filter { $0.modules.contains(id: module.id) },\n                        package: package,\n                        toolsVersion: package.manifest.toolsVersion,\n                        fileSystem: fileSystem\n                    ))\n                case is SystemLibraryModule, is BinaryModule:\n                    break\n                default:\n                    throw InternalError(\"unhandled \\(module.underlying)\")\n                }\n            }\n        )\n\n        /// Ensure we have at least one buildable target.\n        guard !targetMap.isEmpty else {\n            throw Error.noBuildableTarget\n        }\n\n        // Abort now if we have any diagnostics at this point.\n        guard !planningObservabilityScope.errorsReported else {\n            throw Diagnostics.fatalError\n        }\n\n        self.observabilityScope = observabilityScope.makeChildScope(description: \"Build Plan\")\n\n        // Plan the derived test targets, if necessary.\n        let derivedTestTargets = try Self.makeDerivedTestTargets(\n            testProducts: productMap.filter {\n                $0.product.type == .test\n            },\n            destinationBuildParameters: destinationBuildParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            shouldDisableSandbox: self.shouldDisableSandbox,\n            self.fileSystem,\n            self.observabilityScope\n        )\n        for item in derivedTestTargets {\n            var derivedTestTargets = [item.entryPointTargetBuildDescription.target]\n\n            targetMap.insert(.swift(\n                item.entryPointTargetBuildDescription\n            ))\n\n            if let discoveryTargetBuildDescription = item.discoveryTargetBuildDescription {\n                targetMap.insert(.swift(discoveryTargetBuildDescription))\n                derivedTestTargets.append(discoveryTargetBuildDescription.target)\n            }\n\n            self.derivedTestTargetsMap[item.product.id] = derivedTestTargets\n        }\n\n        self.buildToolPluginInvocationResults = buildToolPluginInvocationResults\n        self.prebuildCommandResults = prebuildCommandResults\n\n        self.productMap = productMap\n        self.targetMap = targetMap\n        self.pluginDescriptions = pluginDescriptions\n\n        // Finally plan these targets.\n        try self.plan()\n    }\n\n    static func validateDeploymentVersionOfProductDependency(\n        product: ResolvedProduct,\n        forTarget target: ResolvedModule,\n        buildEnvironment: BuildEnvironment,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        // Supported platforms are defined at the package (e.g., build environment) level.\n        // This will need to become a bit complicated once we have target-level or product-level platform support.\n        let productPlatform = product.getSupportedPlatform(\n            for: buildEnvironment.platform,\n            usingXCTest: product.isLinkingXCTest\n        )\n        let targetPlatform = target.getSupportedPlatform(\n            for: buildEnvironment.platform,\n            usingXCTest: target.type == .test\n        )\n\n        // Check if the version requirement is satisfied.\n        //\n        // If the product's platform version is greater than ours, then it is incompatible.\n        if productPlatform.version > targetPlatform.version {\n            observabilityScope.emit(.productRequiresHigherPlatformVersion(\n                target: target,\n                targetPlatform: targetPlatform,\n                product: product.name,\n                productPlatform: productPlatform\n            ))\n        }\n    }\n\n    /// Plan the targets and products.\n    private func plan() throws {\n        // Plan targets.\n        for buildTarget in self.targets {\n            switch buildTarget {\n            case .swift(let target):\n                try self.plan(swiftTarget: target)\n            case .clang(let target):\n                try self.plan(clangTarget: target)\n            }\n        }\n\n        // Plan products.\n        for buildProduct in self.buildProducts {\n            try self.plan(buildProduct: buildProduct as! ProductBuildDescription)\n        }\n        // FIXME: We need to find out if any product has a target on which it depends\n        // both static and dynamically and then issue a suitable diagnostic or auto\n        // handle that situation.\n\n        // Ensure modules in Windows DLLs export their symbols\n        for product in productMap.values where product.product.type == .library(.dynamic) && product.buildParameters.triple.isWindows() {\n            for target in product.product.modules {\n                let targetId: ModuleBuildDescription.ID = .init(moduleID: target.id, destination: product.buildParameters.destination)\n                if case let .swift(buildDescription) = targetMap[targetId] {\n                    buildDescription.isWindowsStatic = false\n                }\n            }\n        }\n    }\n\n    public func createAPIToolCommonArgs(includeLibrarySearchPaths: Bool) throws -> [String] {\n        // API tool runs on products, hence using `self.productsBuildParameters`, not `self.toolsBuildParameters`\n        var arguments: [String] = []\n\n        // swift-symbolgraph-extract does not support parsing `-use-ld=lld` and\n        // will silently error failing the operation.  Filter out this flag\n        // similar to how we filter out the library search path unless\n        // explicitly requested.\n        var extraSwiftCFlags = self.destinationBuildParameters.toolchain.extraFlags.swiftCompilerFlags\n            .filter { !$0.value.starts(with: \"-use-ld=\") }\n        if !includeLibrarySearchPaths {\n            for index in extraSwiftCFlags.indices.dropLast().reversed() {\n                if extraSwiftCFlags[index].value == \"-L\" {\n                    // Remove the flag\n                    extraSwiftCFlags.remove(at: index)\n                    // Remove the argument\n                    extraSwiftCFlags.remove(at: index)\n                }\n            }\n        }\n        arguments += extraSwiftCFlags.rawFlags\n\n        // Add search paths to the directories containing module maps and Swift modules.\n        for target in self.targets {\n            switch target {\n            case .swift(let targetDescription):\n                if target.destination == .target {\n                    // Include in the analysis surface target destination. That way auxiliary\n                    // modules from building a build tool (destination == .host) won't conflict\n                    // with the modules intended to analyze.\n                    arguments += [\"-I\", targetDescription.moduleOutputPath.parentDirectory.pathString]\n                }\n            case .clang(let targetDescription):\n                if let includeDir = targetDescription.moduleMap?.parentDirectory {\n                    arguments += [\"-I\", includeDir.pathString]\n                }\n                arguments += [\"-I\", targetDescription.clangTarget.includeDir.pathString]\n            }\n        }\n\n        // Add search paths from the system library targets.\n        for target in self.graph.reachableModules {\n            if let systemLib = target.underlying as? SystemLibraryModule {\n                try arguments.append(contentsOf: self.pkgConfig(for: systemLib).cFlags)\n                // Add the path to the module map.\n                arguments += [\"-I\", systemLib.moduleMapPath.parentDirectory.pathString]\n            }\n        }\n\n        return arguments\n    }\n\n    /// Creates arguments required to launch the Swift REPL that will allow\n    /// importing the modules in the package graph.\n    public func createREPLArguments() throws -> CLIArguments {\n        let buildPath = self.toolsBuildParameters.buildPath.pathString\n        var arguments = [\"repl\", \"-I\" + buildPath, \"-L\" + buildPath]\n\n        // Link the special REPL product that contains all of the library targets.\n        let replProductName = try self.graph.getReplProductName()\n        arguments.append(\"-l\" + replProductName)\n\n        // The graph should have the REPL product.\n        assert(self.graph.product(for: replProductName) != nil)\n\n        // Add the search path to the directory containing the modulemap file.\n        for target in self.targets {\n            switch target {\n            case .swift: break\n            case .clang(let targetDescription):\n                if let includeDir = targetDescription.moduleMap?.parentDirectory {\n                    arguments += [\"-I\\(includeDir.pathString)\"]\n                }\n            }\n        }\n\n        // Add search paths from the system library targets.\n        for target in self.graph.reachableModules {\n            if let systemLib = target.underlying as? SystemLibraryModule {\n                arguments += try self.pkgConfig(for: systemLib).cFlags\n            }\n        }\n\n        return arguments\n    }\n\n    /// Get pkgConfig arguments for a system library target.\n    func pkgConfig(for target: SystemLibraryModule) throws -> (cFlags: [String], libs: [String]) {\n        // If we already have these flags, we're done.\n        if let flags = pkgConfigCache[target] {\n            return flags\n        } else {\n            self.pkgConfigCache[target] = ([], [])\n        }\n        let results = try pkgConfigArgs(\n            for: target,\n            pkgConfigDirectories: self.destinationBuildParameters.pkgConfigDirectories,\n            sdkRootPath: self.destinationBuildParameters.toolchain.sdkRootPath,\n            fileSystem: self.fileSystem,\n            observabilityScope: self.observabilityScope\n        )\n        var ret: [(cFlags: [String], libs: [String])] = []\n        for result in results {\n            ret.append((result.cFlags, result.libs))\n        }\n\n        // Build cache\n        var cflagsCache: OrderedCollections.OrderedSet<String> = []\n        var libsCache: [String] = []\n        for tuple in ret {\n            for cFlag in tuple.cFlags {\n                cflagsCache.append(cFlag)\n            }\n\n            libsCache.append(contentsOf: tuple.libs)\n        }\n\n        let result = ([String](cflagsCache), libsCache)\n        self.pkgConfigCache[target] = result\n        return result\n    }\n\n    /// Extracts the library information from an XCFramework.\n    func parseXCFramework(for binaryTarget: BinaryModule, triple: Basics.Triple, enableXCFrameworksOnLinux: Bool) throws -> [LibraryInfo] {\n        try self.externalLibrariesCache.memoize(key: binaryTarget) {\n            if !enableXCFrameworksOnLinux && triple.os == .linux {\n                return []\n            }\n            return try binaryTarget.parseXCFrameworks(for: triple, fileSystem: self.fileSystem)\n        }\n    }\n\n    /// Returns the files and directories that affect the build process of this build plan.\n    package var inputs: [Input] {\n        var inputs: [Input] = []\n        for package in self.graph.rootPackages {\n            inputs += package.modules\n                .map(\\.sources.root)\n                .sorted()\n                .map { .directoryStructure($0) }\n\n            // Add the output paths of any prebuilds that were run, so that we redo the plan if they change.\n            var derivedSourceDirPaths: [Basics.AbsolutePath] = []\n            for result in self.prebuildCommandResults.values.flatMap({ $0 }) {\n                derivedSourceDirPaths.append(contentsOf: result.outputDirectories)\n            }\n            inputs.append(contentsOf: derivedSourceDirPaths.sorted().map { .directoryStructure($0) })\n\n            // FIXME: Need to handle version-specific manifests.\n            inputs.append(.file(package.manifest.path))\n\n            // FIXME: This won't be the location of Package.resolved for multiroot packages.\n            inputs.append(.file(package.path.appending(\"Package.resolved\")))\n\n            // FIXME: Add config file as an input\n\n        }\n        return inputs\n    }\n\n    public func description(\n        for product: ResolvedProduct,\n        context: BuildParameters.Destination\n    ) -> ProductBuildDescription? {\n        let destination: BuildParameters.Destination = switch product.type {\n        case .macro, .plugin:\n            .host\n        default:\n            context\n        }\n\n        return self.productMap[.init(productID: product.id, destination: destination)]\n    }\n\n    public func description(\n        for module: ResolvedModule,\n        context: BuildParameters.Destination\n    ) -> ModuleBuildDescription? {\n        let destination: BuildParameters.Destination = switch module.type {\n        case .macro, .plugin:\n            .host\n        default:\n            context\n        }\n\n        return self.targetMap[.init(moduleID: module.id, destination: destination)]\n    }\n}\n\nextension BuildPlan {\n    /// Applies plugins to the given module as needed. Each plugin is passed an input context that provides\n    /// information about the module to which it is being applied (along with some information about that\n    /// module's dependency closure). The plugin is expected to generate an output in the form of commands\n    /// that will later be run before or during the build, and can also emit debug output and diagnostics.\n    ///\n    /// Each result returned by this function includes an ordered list of commands to run before the build\n    /// of the module, and another list of the commands to incorporate into the build graph so they run\n    /// at the appropriate times during the build.\n    ///\n    /// Any warnings and errors related to running the plugin will be emitted to `diagnostics` when\n    /// `surfaceDiagnostics` parameter is set to `true`.\n    ///\n    /// Note that warnings emitted by the the plugin itself will be returned in the `BuildToolPluginInvocationResult`\n    /// structures for later showing to the user, and not added directly to the diagnostics engine.\n    static func invokeBuildToolPlugins(\n        for module: ResolvedModule,\n        destination: BuildParameters.Destination,\n        configuration: PluginConfiguration,\n        buildParameters: BuildParameters,\n        modulesGraph: ModulesGraph,\n        tools: [ResolvedModule.ID: [String: PluginTool]],\n        additionalFileRules: [FileRuleDescription],\n        pkgConfigDirectories: [Basics.AbsolutePath],\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope,\n        surfaceDiagnostics: Bool = false\n    ) async throws -> [BuildToolPluginInvocationResult] {\n        let outputDir = configuration.workDirectory.appending(\"outputs\")\n\n        /// Determine the package that contains the target.\n        guard let package = modulesGraph.package(for: module) else {\n            throw InternalError(\"could not determine package for module \\(self)\")\n        }\n\n        // Apply each build tool plugin used by the target in order,\n        // creating a list of results (one for each plugin usage).\n        var buildToolPluginResults: [BuildToolPluginInvocationResult] = []\n        for plugin in module.pluginDependencies(satisfying: buildParameters.buildEnvironment) {\n            let pluginModule = plugin.underlying as! PluginModule\n\n            // Determine the tools to which this plugin has access, and create a name-to-path mapping from tool\n            // names to the corresponding paths. Built tools are assumed to be in the build tools directory.\n            guard let accessibleTools = tools[plugin.id] else {\n                throw InternalError(\"No tools found for plugin \\(plugin.name)\")\n            }\n\n            // Assign a plugin working directory based on the package, target, and plugin.\n            let pluginOutputDir = outputDir.appending(\n                components: [\n                    package.identity.description,\n                    module.name,\n                    destination == .host ? \"tools\" : \"destination\",\n                    plugin.name,\n                ]\n            )\n\n            // Determine the set of directories under which plugins are allowed to write.\n            // We always include just the output directory, and for now there is no possibility\n            // of opting into others.\n            let writableDirectories = [outputDir]\n\n            // Determine a set of further directories under which plugins are never allowed\n            // to write, even if they are covered by other rules (such as being able to write\n            // to the temporary directory).\n            let readOnlyDirectories = [package.path]\n\n            // In tools version 6.0 and newer, we vend the list of files generated by previous plugins.\n            let pluginDerivedSources: Sources\n            let pluginDerivedResources: [Resource]\n            if package.manifest.toolsVersion >= .v6_0 {\n                // Set up dummy observability because we don't want to emit diagnostics for this before the actual\n                // build.\n                let observability = ObservabilitySystem { _, _ in }\n                // Compute the generated files based on all results we have computed so far.\n                let pluginGeneratedFiles = ModulesGraph.computePluginGeneratedFiles(\n                    target: module,\n                    toolsVersion: package.manifest.toolsVersion,\n                    additionalFileRules: additionalFileRules,\n                    buildParameters: buildParameters,\n                    buildToolPluginInvocationResults: buildToolPluginResults,\n                    prebuildCommandResults: [],\n                    observabilityScope: observability.topScope\n                )\n                pluginDerivedSources = Sources(\n                    paths: pluginGeneratedFiles.sources.map(\\.self),\n                    root: buildParameters.dataPath\n                )\n                pluginDerivedResources = pluginGeneratedFiles.resources.values.map(\\.self)\n            } else {\n                pluginDerivedSources = .init(paths: [], root: package.path)\n                pluginDerivedResources = []\n            }\n\n            let result = try await pluginModule.invoke(\n                module: plugin,\n                action: .createBuildToolCommands(\n                    package: package,\n                    target: module,\n                    pluginGeneratedSources: pluginDerivedSources.paths,\n                    pluginGeneratedResources: pluginDerivedResources.map(\\.path)\n                ),\n                buildEnvironment: buildParameters.buildEnvironment,\n                workers: buildParameters.workers,\n                scriptRunner: configuration.scriptRunner,\n                workingDirectory: package.path,\n                outputDirectory: pluginOutputDir,\n                toolSearchDirectories: [buildParameters.toolchain.swiftCompilerPath.parentDirectory],\n                accessibleTools: accessibleTools,\n                writableDirectories: writableDirectories,\n                readOnlyDirectories: readOnlyDirectories,\n                allowNetworkConnections: [],\n                pkgConfigDirectories: pkgConfigDirectories,\n                sdkRootPath: buildParameters.toolchain.sdkRootPath,\n                fileSystem: fileSystem,\n                modulesGraph: modulesGraph,\n                observabilityScope: observabilityScope\n            )\n\n\n            if surfaceDiagnostics {\n                let diagnosticsEmitter = observabilityScope.makeDiagnosticsEmitter {\n                    var metadata = ObservabilityMetadata()\n                    metadata.moduleName = module.name\n                    metadata.pluginName = result.plugin.name\n                    return metadata\n                }\n\n                for line in result.textOutput.split(whereSeparator: { $0.isNewline }) {\n                    diagnosticsEmitter.emit(info: line)\n                }\n\n                for diag in result.diagnostics {\n                    diagnosticsEmitter.emit(diag)\n                }\n            }\n\n            // Add a BuildToolPluginInvocationResult to the mapping.\n            buildToolPluginResults.append(result)\n        }\n\n        return buildToolPluginResults\n    }\n\n    /// Runs any commands associated with the given list of plugin invocation results,\n    /// in order, and returns the results of running those prebuild commands.\n    fileprivate static func runPluginCommands(\n        using pluginConfiguration: PluginConfiguration,\n        for pluginResults: [BuildToolPluginInvocationResult],\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws -> [CommandPluginResult] {\n        // Run through all the commands from all the plugin usages in the target.\n        try pluginResults.map { pluginResult in\n            // As we go we will collect a list of prebuild output directories whose contents should be input to the\n            // build, and a list of the files in those directories after running the commands.\n            var derivedFiles: [Basics.AbsolutePath] = []\n            var prebuildOutputDirs: [Basics.AbsolutePath] = []\n            for command in pluginResult.prebuildCommands {\n                observabilityScope\n                    .emit(\n                        info: \"Running \" +\n                            (command.configuration.displayName ?? command.configuration.executable.basename)\n                    )\n\n                // Run the command configuration as a subshell. This doesn't return until it is done.\n                // TODO: We need to also use any working directory, but that support isn't yet available on all platforms at a lower level.\n                var commandLine = [command.configuration.executable.pathString] + command.configuration.arguments\n                if !pluginConfiguration.disableSandbox {\n                    commandLine = try Sandbox.apply(\n                        command: commandLine,\n                        fileSystem: fileSystem,\n                        strictness: .writableTemporaryDirectory,\n                        writableDirectories: [pluginResult.pluginOutputDirectory]\n                    )\n                }\n                let processResult = try AsyncProcess.popen(\n                    arguments: commandLine,\n                    environment: command.configuration.environment\n                )\n                let output = try processResult.utf8Output() + processResult.utf8stderrOutput()\n                if processResult.exitStatus != .terminated(code: 0) {\n                    throw StringError(\"failed: \\(command)\\n\\n\\(output)\")\n                }\n\n                // Add any files found in the output directory declared for the prebuild command after the command ends.\n                let outputFilesDir = command.outputFilesDirectory\n                if let swiftFiles = try? fileSystem.getDirectoryContents(outputFilesDir).sorted() {\n                    derivedFiles.append(contentsOf: swiftFiles.map { outputFilesDir.appending(component: $0) })\n                }\n\n                // Add the output directory to the list of directories whose structure should affect the build plan.\n                prebuildOutputDirs.append(outputFilesDir)\n            }\n\n            // Add the results of running any prebuild commands for this invocation.\n            return CommandPluginResult(derivedFiles: derivedFiles, outputDirectories: prebuildOutputDirs)\n        }\n    }\n}\n\nextension BuildPlan {\n    fileprivate typealias Destination = BuildParameters.Destination\n\n    enum TraversalNode: Hashable {\n        case package(ResolvedPackage)\n        case product(ResolvedProduct, BuildParameters.Destination)\n        case module(ResolvedModule, BuildParameters.Destination)\n\n        var destination: BuildParameters.Destination {\n            switch self {\n            case .package:\n                .target\n            case .product(_, let destination):\n                destination\n            case .module(_, let destination):\n                destination\n            }\n        }\n\n        init(\n            product: ResolvedProduct,\n            context destination: BuildParameters.Destination\n        ) {\n            switch product.type {\n            case .macro, .plugin:\n                self = .product(product, .host)\n            case .test:\n                self = .product(product, product.hasDirectMacroDependencies ? .host : destination)\n            default:\n                self = .product(product, product.platformConstraint == .host ? .host : destination)\n            }\n        }\n\n        init(\n            module: ResolvedModule,\n            context destination: BuildParameters.Destination\n        ) {\n            switch module.type {\n            case .macro, .plugin:\n                // Macros and plugins are ways built for host\n                self = .module(module, .host)\n            case .test:\n                self = .module(module, module.hasDirectMacroDependencies ? .host : destination)\n            default:\n                // By default assume the destination of the context.\n                // This means that i.e. test products that reference macros\n                // would force all of their successors to be `host`.\n                // Also if the module has a platform constraint of `host`, use that.\n                self = .module(module, module.platformConstraint == .host ? .host : destination)\n            }\n        }\n    }\n\n    /// Traverse the modules graph and find a destination for every product and module.\n    /// All non-macro/plugin products and modules have `target` destination with one\n    /// notable exception - test products/modules with direct macro dependency.\n    fileprivate static func computeDestinations(\n        graph: ModulesGraph,\n        onProduct: (ResolvedProduct, Destination) throws -> Void,\n        onModule: (ResolvedModule, Destination) async throws -> Void\n    ) async rethrows {\n        func successors(for package: ResolvedPackage) -> [TraversalNode] {\n            var successors: [TraversalNode] = []\n            for product in package.products {\n                if case .test = product.underlying.type,\n                   !graph.rootPackages.contains(id: package.id)\n                {\n                    continue\n                }\n\n                successors.append(.init(product: product, context: .target))\n            }\n\n            for module in package.modules {\n                // Tests are discovered through an aggregate product which also\n                // informs their destination.\n                if case .test = module.underlying.type {\n                    continue\n                }\n\n                successors.append(.init(module: module, context: .target))\n            }\n\n            return successors\n        }\n\n        func successors(\n            for product: ResolvedProduct,\n            destination: Destination\n        ) -> [TraversalNode] {\n            guard destination == .host || product.underlying.type == .test else {\n                return []\n            }\n\n            return product.modules.map { module in\n                TraversalNode(module: module, context: destination)\n            }\n        }\n\n        func successors(\n            for module: ResolvedModule,\n            destination: Destination\n        ) -> [TraversalNode] {\n            guard destination == .host else {\n                return []\n            }\n\n            return module.dependencies.reduce(into: [TraversalNode]()) { partial, dependency in\n                switch dependency {\n                case .product(let product, conditions: _):\n                    partial.append(.init(product: product, context: destination))\n                case .module(let module, _):\n                    partial.append(.init(module: module, context: destination))\n                }\n            }\n        }\n\n        try await depthFirstSearch(graph.packages.map { TraversalNode.package($0) }) { node in\n            switch node {\n            case .package(let package):\n                successors(for: package)\n            case .product(let product, let destination):\n                successors(for: product, destination: destination)\n            case .module(let module, let destination):\n                successors(for: module, destination: destination)\n            }\n        } onUnique: {\n            switch $0 {\n            case .package:\n                break\n            case .product(let product, let destination):\n                try onProduct(product, destination)\n\n            case .module(let module, let destination):\n                try await onModule(module, destination)\n            }\n        } onDuplicate: { _, _ in\n            // No de-duplication is necessary we only want unique nodes.\n        }\n    }\n\n    /// Traverses the modules graph, computes destination of every module reference and\n    /// provides the data to the caller by means of `onModule` callback. The products\n    /// are completely transparent to this method and are represented by their module dependencies.\n    package func traverseModules(\n        _ onModule: (\n            (ResolvedModule, BuildParameters.Destination),\n            _ parent: (ResolvedModule, BuildParameters.Destination)?\n        ) -> Void\n    ) {\n        var visited = Set<TraversalNode>()\n\n        func successors(for package: ResolvedPackage) -> [TraversalNode] {\n            guard visited.insert(.package(package)).inserted else {\n                return []\n            }\n\n            var successors: [TraversalNode] = []\n            for product in package.products {\n                if case .test = product.underlying.type,\n                   !graph.rootPackages.contains(id: package.id)\n                {\n                    continue\n                }\n\n                successors.append(.init(product: product, context: .target))\n            }\n\n            for module in package.modules {\n                // Tests are discovered through an aggregate product which also\n                // informs their destination.\n                if case .test = module.type {\n                    continue\n                }\n                successors.append(.init(module: module, context: .target))\n            }\n\n            return successors\n        }\n\n        func successors(\n            for product: ResolvedProduct,\n            destination: Destination\n        ) -> [TraversalNode] {\n            guard destination == .host || product.underlying.type == .test else {\n                return []\n            }\n\n            return product.modules.map { module in\n                TraversalNode(module: module, context: destination)\n            }\n        }\n\n        func successors(\n            for module: ResolvedModule,\n            destination: Destination\n        ) -> [TraversalNode] {\n            guard visited.insert(.module(module, destination)).inserted else {\n                return []\n            }\n            return module.dependencies.reduce(into: [TraversalNode]()) { partial, dependency in\n                switch dependency {\n                case .product(let product, conditions: _):\n                    let parent = TraversalNode(product: product, context: destination)\n                    for module in product.modules {\n                        partial.append(.init(module: module, context: parent.destination))\n                    }\n                case .module(let module, _):\n                    partial.append(.init(module: module, context: destination))\n                }\n            }\n        }\n\n        depthFirstSearch(self.graph.packages.map { TraversalNode.package($0) }) {\n            switch $0 {\n            case .package(let package):\n                successors(for: package)\n            case .module(let module, let destination):\n                successors(for: module, destination: destination)\n            case .product(let product, let destination):\n                successors(for: product, destination: destination)\n            }\n        } onNext: { current, parent in\n            let parentModule: (ResolvedModule, BuildParameters.Destination)? = switch parent {\n            case .package, .product, nil:\n                nil\n            case .module(let module, let destination):\n                (module, destination)\n            }\n\n            switch current {\n            case .package, .product:\n                break\n\n            case .module(let module, let destination):\n                onModule((module, destination), parentModule)\n            }\n        }\n    }\n\n    package func traverseDependencies(\n        of description: ModuleBuildDescription,\n        onProduct: (ResolvedProduct, BuildParameters.Destination, ProductBuildDescription?) -> Void,\n        onModule: (ResolvedModule, BuildParameters.Destination, ModuleBuildDescription?) -> Void\n    ) {\n        var visited = Set<TraversalNode>()\n        func successors(\n            for product: ResolvedProduct,\n            destination: Destination\n        ) -> [TraversalNode] {\n            product.modules.map { module in\n                TraversalNode(module: module, context: destination)\n            }.filter {\n                visited.insert($0).inserted\n            }\n        }\n\n        func successors(\n            for module: ResolvedModule,\n            destination: Destination\n        ) -> [TraversalNode] {\n            module\n                .dependencies(satisfying: description.buildParameters.buildEnvironment)\n                .reduce(into: [TraversalNode]()) { partial, dependency in\n                    switch dependency {\n                    case .product(let product, _):\n                        partial.append(.init(product: product, context: destination))\n                    case .module(let module, _):\n                        partial.append(.init(module: module, context: destination))\n                    }\n                }.filter {\n                    visited.insert($0).inserted\n                }\n        }\n\n        depthFirstSearch(successors(for: description.module, destination: description.destination)) {\n            switch $0 {\n            case .module(let module, let destination):\n                successors(for: module, destination: destination)\n            case .product(let product, let destination):\n                successors(for: product, destination: destination)\n            case .package:\n                []\n            }\n        } onNext: { module, _ in\n            switch module {\n            case .package:\n                break\n\n            case .product(let product, let destination):\n                onProduct(product, destination, self.description(for: product, context: destination))\n\n            case .module(let module, let destination):\n                onModule(module, destination, self.description(for: module, context: destination))\n            }\n        }\n    }\n\n    // Only follow link time dependencies, i.e. skip dependencies on macros and plugins\n    // except for testTargets that depend on macros.\n    package func traverseLinkDependencies(\n        of description: ModuleBuildDescription,\n        onProduct: (ResolvedProduct, BuildParameters.Destination, ProductBuildDescription?) -> Void,\n        onModule: (ResolvedModule, BuildParameters.Destination, ModuleBuildDescription?) -> Void\n    ) {\n        var visited = Set<TraversalNode>()\n        func successors(\n            for product: ResolvedProduct,\n            destination: Destination\n        ) -> [TraversalNode] {\n            product.modules.map { module in\n                TraversalNode(module: module, context: destination)\n            }.filter {\n                visited.insert($0).inserted\n            }\n        }\n\n        func successors(\n            for parentModule: ResolvedModule,\n            destination: Destination\n        ) -> [TraversalNode] {\n            parentModule\n                .dependencies(satisfying: description.buildParameters.buildEnvironment)\n                .reduce(into: [TraversalNode]()) { partial, dependency in\n                    switch dependency {\n                    case .product(let product, _):\n                        guard product.type != .plugin else {\n                            return\n                        }\n                        \n                        guard product.type != .macro || parentModule.type == .test else {\n                            return\n                        }\n\n                        partial.append(.init(product: product, context: destination))\n                    case .module(let childModule, _):\n                        guard childModule.type != .plugin else {\n                            return\n                        }\n                        \n                        guard childModule.type != .macro || parentModule.type == .test else {\n                            return\n                        }\n\n                        partial.append(.init(module: childModule, context: destination))\n                    }\n                }.filter {\n                    visited.insert($0).inserted\n                }\n        }\n\n        depthFirstSearch(successors(for: description.module, destination: description.destination)) {\n            switch $0 {\n            case .module(let module, let destination):\n                successors(for: module, destination: destination)\n            case .product(let product, let destination):\n                successors(for: product, destination: destination)\n            case .package:\n                []\n            }\n        } onNext: { module, _ in\n            switch module {\n            case .package:\n                break\n\n            case .product(let product, let destination):\n                onProduct(product, destination, self.description(for: product, context: destination))\n\n            case .module(let module, let destination):\n                onModule(module, destination, self.description(for: module, context: destination))\n            }\n        }\n    }\n}\n\nextension Basics.Diagnostic {\n    static var swiftBackDeployError: Self {\n        .warning(\n            \"\"\"\n            Swift compiler no longer supports statically linking the Swift libraries. They're included in the OS by \\\n            default starting with macOS Mojave 10.14.4 beta 3. For macOS Mojave 10.14.3 and earlier, there's an \\\n            optional Swift library package that can be downloaded from \\\"More Downloads\\\" for Apple Developers at \\\n            https://developer.apple.com/download/more/\n            \"\"\"\n        )\n    }\n\n    static func productRequiresHigherPlatformVersion(\n        target: ResolvedModule,\n        targetPlatform: SupportedPlatform,\n        product: String,\n        productPlatform: SupportedPlatform\n    ) -> Self {\n        .error(\"\"\"\n        the \\(target.type.rawValue) '\\(target.name)' requires \\\n        \\(targetPlatform.platform.name) \\(targetPlatform.version.versionString), \\\n        but depends on the product '\\(product)' which requires \\\n        \\(productPlatform.platform.name) \\(productPlatform.version.versionString); \\\n        consider changing the \\(target.type.rawValue) '\\(target.name)' to require \\\n        \\(productPlatform.platform.name) \\(productPlatform.version.versionString) or later, \\\n        or the product '\\(product)' to require \\\n        \\(targetPlatform.platform.name) \\(targetPlatform.version.versionString) or earlier.\n        \"\"\")\n    }\n\n    static func binaryTargetsNotSupported() -> Self {\n        .error(\"binary targets are not supported on this platform\")\n    }\n}\n\nextension BuildParameters {\n    /// Returns a named bundle's path inside the build directory.\n    func bundlePath(named name: String) -> Basics.AbsolutePath {\n        self.buildPath.appending(component: name + self.triple.nsbundleExtension)\n    }\n}\n\n/// Generate the resource bundle Info.plist.\nfunc generateResourceInfoPlist(\n    fileSystem: FileSystem,\n    target: ResolvedModule,\n    path: Basics.AbsolutePath\n) throws -> Bool {\n    guard let defaultLocalization = target.defaultLocalization else {\n        return false\n    }\n\n    try fileSystem.writeIfChanged(\n        path: path,\n        string: \"\"\"\n        <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n        <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n        <plist version=\"1.0\">\n        <dict>\n            <key>CFBundleDevelopmentRegion</key>\n            <string>\\(defaultLocalization)</string>\n        </dict>\n        </plist>\n        \"\"\"\n    )\n    return true\n}\n\nextension Basics.Triple {\n    var isSupportingStaticStdlib: Bool {\n        isLinux() || arch == .wasm32\n    }\n}\n\nextension ResolvedPackage {\n    var isRemote: Bool {\n        self.underlying.manifest.packageKind.isRemote\n    }\n}\n\nextension ResolvedProduct {\n    private var isAutomaticLibrary: Bool {\n        self.type == .library(.automatic)\n    }\n\n    private var isBinaryOnly: Bool {\n        self.modules.filter { !($0.underlying is BinaryModule) }.isEmpty\n    }\n\n    private var isPlugin: Bool {\n        self.type == .plugin\n    }\n\n    // We shouldn't create product descriptions for automatic libraries, plugins or products which consist solely of\n    // binary targets, because they don't produce any output.\n    fileprivate var shouldCreateProductDescription: Bool {\n        !self.isAutomaticLibrary && !self.isBinaryOnly && !self.isPlugin\n    }\n}\n"
  },
  {
    "path": "Sources/Build/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(Build\n  BuildDescription/ClangModuleBuildDescription.swift\n  BuildDescription/PluginBuildDescription.swift\n  BuildDescription/ProductBuildDescription.swift\n  BuildDescription/ResolvedModule+BuildDescription.swift\n  BuildDescription/SwiftModuleBuildDescription.swift\n  BuildDescription/ModuleBuildDescription.swift\n  BuildManifest/LLBuildManifestBuilder.swift\n  BuildManifest/LLBuildManifestBuilder+Clang.swift\n  BuildManifest/LLBuildManifestBuilder+Product.swift\n  BuildManifest/LLBuildManifestBuilder+Resources.swift\n  BuildManifest/LLBuildManifestBuilder+Swift.swift\n  BuildOperation.swift\n  BuildPlan/BuildPlan.swift\n  BuildPlan/BuildPlan+Clang.swift\n  BuildPlan/BuildPlan+Product.swift\n  BuildPlan/BuildPlan+Swift.swift\n  BuildPlan/BuildPlan+Test.swift\n  ClangSupport.swift\n  LLBuildCommands.swift\n  LLBuildDescription.swift\n  LLBuildProgressTracker.swift\n  SwiftCompilerOutputParser.swift\n  TestObservation.swift)\ntarget_link_libraries(Build PUBLIC\n  TSCBasic\n  Basics\n  SwiftCollections::OrderedCollections\n  PackageGraph\n  SPMBuildCore)\ntarget_link_libraries(Build PRIVATE\n  DriverSupport\n  LLBuildManifest\n  SPMLLBuild\n  SwiftDriver)\ntarget_link_libraries(Build INTERFACE\n  llbuildSwift)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(Build PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS Build\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS Build)\n"
  },
  {
    "path": "Sources/Build/ClangSupport.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\n\npublic enum ClangSupport {\n    private struct Feature: Decodable {\n        let name: String\n        let value: [String]?\n    }\n\n    private struct Features: Decodable {\n        let features: [Feature]\n    }\n\n    private static var cachedFeatures = ThreadSafeBox<Features?>()\n\n    public static func supportsFeature(name: String, toolchain: PackageModel.Toolchain) throws -> Bool {\n        let features = try cachedFeatures.memoize {\n            let clangPath = try toolchain.getClangCompiler()\n            let featuresPath = clangPath.parentDirectory.parentDirectory.appending(components: [\"share\", \"clang\", \"features.json\"])\n            return try JSONDecoder.makeWithDefaults().decode(\n                path: featuresPath,\n                fileSystem: localFileSystem,\n                as: Features.self\n            )\n        }\n        return features.features.first(where: { $0.name == name }) != nil\n    }\n}\n"
  },
  {
    "path": "Sources/Build/LLBuildCommands.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport LLBuildManifest\nimport SPMBuildCore\nimport SPMLLBuild\nimport PackageModel\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftDriver\n@_implementationOnly import SwiftOptions\n#else\nimport SwiftDriver\nimport SwiftOptions\n#endif\n\nimport class TSCBasic.LocalFileOutputByteStream\n\nimport class TSCUtility.IndexStore\n\nclass CustomLLBuildCommand: SPMLLBuild.ExternalCommand {\n    let context: BuildExecutionContext\n\n    required init(_ context: BuildExecutionContext) {\n        self.context = context\n    }\n\n    func getSignature(_: SPMLLBuild.Command) -> [UInt8] {\n        []\n    }\n\n    func execute(\n        _: SPMLLBuild.Command,\n        _: SPMLLBuild.BuildSystemCommandInterface\n    ) -> Bool {\n        fatalError(\"subclass responsibility\")\n    }\n}\n\nprivate protocol TestBuildCommand {}\n\nextension IndexStore.TestCaseClass.TestMethod {\n    fileprivate var allTestsEntry: String {\n        let baseName = name.hasSuffix(\"()\") ? String(name.dropLast(2)) : name\n\n        return \"(\\\"\\(baseName)\\\", \\(isAsync ? \"asyncTest(\\(baseName))\" : baseName))\"\n    }\n}\n\nextension TestEntryPointTool {\n    public static var mainFileName: String {\n        \"runner.swift\"\n    }\n}\n\nfinal class TestDiscoveryCommand: CustomLLBuildCommand, TestBuildCommand {\n    private func write(\n        tests: [IndexStore.TestCaseClass],\n        forModule module: String,\n        fileSystem: Basics.FileSystem,\n        path: AbsolutePath\n    ) throws {\n        let testsByClassNames = Dictionary(grouping: tests, by: { $0.name }).sorted(by: { $0.key < $1.key })\n\n        var content = \"import XCTest\\n\"\n        content += \"@testable import \\(module)\\n\"\n\n        for iterator in testsByClassNames {\n            // 'className' provides uniqueness for derived class.\n            let className = iterator.key\n            let testMethods = iterator.value.flatMap(\\.testMethods)\n            content +=\n                #\"\"\"\n\n                fileprivate extension \\#(className) {\n                    @available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")\n                    static nonisolated(unsafe) let __allTests__\\#(className) = [\n                        \\#(testMethods.map(\\.allTestsEntry).joined(separator: \",\\n        \"))\n                    ]\n                }\n\n                \"\"\"#\n        }\n\n        content +=\n            #\"\"\"\n            @available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")\n            func __\\#(module)__allTests() -> [XCTestCaseEntry] {\n                return [\n                    \\#(\n                        testsByClassNames.map { \"testCase(\\($0.key).__allTests__\\($0.key))\" }\n                            .joined(separator: \",\\n        \")\n                    )\n                ]\n            }\n            \"\"\"#\n\n        try fileSystem.writeFileContents(path, string: content)\n    }\n\n    private func execute(fileSystem: Basics.FileSystem, tool: TestDiscoveryTool) throws {\n        let outputs = tool.outputs.compactMap { try? AbsolutePath(validating: $0.name) }\n\n        if case .loadableBundle = context.productsBuildParameters.testProductStyle {\n            // When building an XCTest bundle, test discovery is handled by the\n            // test harness process (i.e. this is the Darwin path.)\n            for file in outputs {\n                try fileSystem.writeIfChanged(path: file, string: \"\")\n            }\n            return\n        }\n\n        let index = self.context.productsBuildParameters.indexStore\n        let api = try self.context.indexStoreAPI.get()\n        let store = try IndexStore.open(store: TSCAbsolutePath(index), api: api)\n\n        // FIXME: We can speed this up by having one llbuild command per object file.\n        let tests = try store\n            .listTests(in: tool.inputs.map { try TSCAbsolutePath(AbsolutePath(validating: $0.name)) })\n\n        let testsByModule = Dictionary(grouping: tests, by: { $0.module.spm_mangledToC99ExtendedIdentifier() })\n\n        // Find the main file path.\n        guard let mainFile = outputs.first(where: { path in\n            path.basename == TestDiscoveryTool.mainFileName\n        }) else {\n            throw InternalError(\"main output (\\(TestDiscoveryTool.mainFileName)) not found\")\n        }\n\n        // Write one file for each test module.\n        //\n        // We could write everything in one file but that can easily run into type conflicts due\n        // in complex packages with large number of test modules.\n        for file in outputs where file != mainFile {\n            // FIXME: This is relying on implementation detail of the output but passing the\n            // the context all the way through is not worth it right now.\n            let module = file.basenameWithoutExt.spm_mangledToC99ExtendedIdentifier()\n\n            guard let tests = testsByModule[module] else {\n                // This module has no tests so just write an empty file for it.\n                try fileSystem.writeFileContents(file, bytes: \"\")\n                continue\n            }\n            try write(\n                tests: tests,\n                forModule: module,\n                fileSystem: fileSystem,\n                path: file\n            )\n        }\n\n        let testsKeyword = tests.isEmpty ? \"let\" : \"var\"\n\n        // Write the main file.\n        let stream = try LocalFileOutputByteStream(mainFile)\n\n        stream.send(\n            #\"\"\"\n            import XCTest\n\n            @available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")\n            public func __allDiscoveredTests() -> [XCTestCaseEntry] {\n                \\#(testsKeyword) tests = [XCTestCaseEntry]()\n\n                \\#(testsByModule.keys.map { \"tests += __\\($0)__allTests()\" }.joined(separator: \"\\n    \"))\n\n                return tests\n            }\n            \"\"\"#\n        )\n\n        stream.flush()\n    }\n\n    override func execute(\n        _ command: SPMLLBuild.Command,\n        _: SPMLLBuild.BuildSystemCommandInterface\n    ) -> Bool {\n        do {\n            // This tool will never run without the build description.\n            guard let buildDescription = self.context.buildDescription else {\n                throw InternalError(\"unknown build description\")\n            }\n            guard let tool = buildDescription.testDiscoveryCommands[command.name] else {\n                throw InternalError(\"command \\(command.name) not registered\")\n            }\n            try self.execute(fileSystem: self.context.fileSystem, tool: tool)\n            return true\n        } catch {\n            self.context.observabilityScope.emit(error)\n            return false\n        }\n    }\n}\n\nfinal class TestEntryPointCommand: CustomLLBuildCommand, TestBuildCommand {\n    private func execute(fileSystem: Basics.FileSystem, tool: TestEntryPointTool) throws {\n        let outputs = tool.outputs.compactMap { try? AbsolutePath(validating: $0.name) }\n\n        // Find the main output file\n        let mainFileName = TestEntryPointTool.mainFileName\n        guard let mainFile = outputs.first(where: { path in\n            path.basename == mainFileName\n        }) else {\n            throw InternalError(\"main file output (\\(mainFileName)) not found\")\n        }\n\n        // Write the main file.\n        let stream = try LocalFileOutputByteStream(mainFile)\n\n        // Find the inputs, which are the names of the test discovery module(s)\n        let inputs = tool.inputs.compactMap { try? AbsolutePath(validating: $0.name) }\n        let discoveryModuleNames = inputs.map(\\.basenameWithoutExt)\n\n        let testObservabilitySetup: String\n        let buildParameters = self.context.productsBuildParameters\n        if buildParameters.testingParameters.experimentalTestOutput && buildParameters.triple.supportsTestSummary {\n            testObservabilitySetup = \"_ = SwiftPMXCTestObserver()\\n\"\n        } else {\n            testObservabilitySetup = \"\"\n        }\n\n        let isXCTMainAvailable: String = switch buildParameters.testProductStyle {\n        case .entryPointExecutable:\n            \"canImport(XCTest)\"\n        case .loadableBundle:\n            \"false\"\n        }\n\n        /// On WASI, we can't block the main thread, so XCTestMain is defined as async.\n        let awaitXCTMainKeyword = if buildParameters.triple.isWASI() {\n            \"await\"\n        } else {\n            \"\"\n        }\n\n        var needsAsyncMainWorkaround = false\n        if buildParameters.triple.isLinux() {\n            // FIXME: work around crash on Amazon Linux 2 when main function is async (rdar://128303921)\n            needsAsyncMainWorkaround = true\n        }\n\n        stream.send(\n            #\"\"\"\n            #if canImport(Testing)\n            import Testing\n            #endif\n\n            #if \\#(isXCTMainAvailable)\n            \\#(generateTestObservationCode(buildParameters: buildParameters))\n\n            import XCTest\n            \\#(discoveryModuleNames.map { \"import \\($0)\" }.joined(separator: \"\\n\"))\n            #endif\n\n            @main\n            @available(macOS 10.15, iOS 11, watchOS 4, tvOS 11, *)\n            @available(*, deprecated, message: \"Not actually deprecated. Marked as deprecated to allow inclusion of deprecated tests (which test deprecated functionality) without warnings\")\n            struct Runner {\n                private static func testingLibrary() -> String {\n                    var iterator = CommandLine.arguments.makeIterator()\n                    while let argument = iterator.next() {\n                        if argument == \"--testing-library\", let libraryName = iterator.next() {\n                            return libraryName.lowercased()\n                        }\n                    }\n\n                    // Fallback if not specified: run XCTest (legacy behavior)\n                    return \"xctest\"\n                }\n\n                #if \\#(needsAsyncMainWorkaround)\n                @_silgen_name(\"$ss13_runAsyncMainyyyyYaKcF\")\n                private static func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> ())\n                #endif\n\n                static func main() \\#(needsAsyncMainWorkaround ? \"\" : \"async\") {\n                    let testingLibrary = Self.testingLibrary()\n                    #if canImport(Testing)\n                    if testingLibrary == \"swift-testing\" {\n                        #if \\#(needsAsyncMainWorkaround)\n                        _runAsyncMain {\n                            await Testing.__swiftPMEntryPoint() as Never\n                        }\n                        #else\n                        await Testing.__swiftPMEntryPoint() as Never\n                        #endif\n                    }\n                    #endif\n                    #if \\#(isXCTMainAvailable)\n                    if testingLibrary == \"xctest\" {\n                        \\#(testObservabilitySetup)\n                        \\#(awaitXCTMainKeyword) XCTMain(__allDiscoveredTests()) as Never\n                    }\n                    #endif\n                }\n            }\n            \"\"\"#\n        )\n\n        stream.flush()\n    }\n\n    override func execute(\n        _ command: SPMLLBuild.Command,\n        _: SPMLLBuild.BuildSystemCommandInterface\n    ) -> Bool {\n        do {\n            // This tool will never run without the build description.\n            guard let buildDescription = self.context.buildDescription else {\n                throw InternalError(\"unknown build description\")\n            }\n            guard let tool = buildDescription.testEntryPointCommands[command.name] else {\n                throw InternalError(\"command \\(command.name) not registered\")\n            }\n            try self.execute(fileSystem: self.context.fileSystem, tool: tool)\n            return true\n        } catch {\n            self.context.observabilityScope.emit(error)\n            return false\n        }\n    }\n}\n\nfinal class WriteAuxiliaryFileCommand: CustomLLBuildCommand {\n    override func getSignature(_ command: SPMLLBuild.Command) -> [UInt8] {\n        guard let buildDescription = self.context.buildDescription else {\n            self.context.observabilityScope.emit(error: \"unknown build description\")\n            return []\n        }\n        guard let tool = buildDescription.writeCommands[command.name] else {\n            self.context.observabilityScope.emit(error: \"command \\(command.name) not registered\")\n            return []\n        }\n\n        do {\n            let encoder = JSONEncoder.makeWithDefaults()\n            var hash = Data()\n            hash += try encoder.encode(tool.inputs)\n            hash += try encoder.encode(tool.outputs)\n            return [UInt8](hash)\n        } catch {\n            self.context.observabilityScope.emit(error: \"getSignature() failed: \\(error.interpolationDescription)\")\n            return []\n        }\n    }\n\n    override func execute(\n        _ command: SPMLLBuild.Command,\n        _: SPMLLBuild.BuildSystemCommandInterface\n    ) -> Bool {\n        let outputFilePath: AbsolutePath\n        let tool: WriteAuxiliaryFile!\n\n        do {\n            guard let buildDescription = self.context.buildDescription else {\n                throw InternalError(\"unknown build description\")\n            }\n            guard let _tool = buildDescription.writeCommands[command.name] else {\n                throw StringError(\"command \\(command.name) not registered\")\n            }\n            tool = _tool\n\n            guard let output = tool.outputs.first, output.kind == .file else {\n                throw StringError(\"invalid output path\")\n            }\n            outputFilePath = try AbsolutePath(validating: output.name)\n        } catch {\n            self.context.observabilityScope\n                .emit(error: \"failed to write auxiliary file: \\(error.interpolationDescription)\")\n            return false\n        }\n\n        do {\n            try self.context.fileSystem.writeIfChanged(path: outputFilePath, string: self.getFileContents(tool: tool))\n            return true\n        } catch {\n            self.context.observabilityScope\n                .emit(\n                    error: \"failed to write auxiliary file '\\(outputFilePath.pathString)': \\(error.interpolationDescription)\"\n                )\n            return false\n        }\n    }\n\n    func getFileContents(tool: WriteAuxiliaryFile) throws -> String {\n        guard tool.inputs.first?.kind == .virtual,\n              let generatedFileType = tool.inputs.first?.name.dropFirst().dropLast()\n        else {\n            throw StringError(\"invalid inputs\")\n        }\n\n        for fileType in WriteAuxiliary.fileTypes {\n            if generatedFileType == fileType.name {\n                return try fileType.getFileContents(inputs: Array(tool.inputs.dropFirst()))\n            }\n        }\n\n        throw InternalError(\"unhandled generated file type '\\(generatedFileType)'\")\n    }\n}\n\nfinal class PackageStructureCommand: CustomLLBuildCommand {\n    override func getSignature(_: SPMLLBuild.Command) -> [UInt8] {\n        let encoder = JSONEncoder.makeWithDefaults()\n        // Include build parameters and process env in the signature.\n        var hash = Data()\n        hash += try! encoder.encode(normalizeBuildParameters(self.context.productsBuildParameters))\n        hash += try! encoder.encode(normalizeBuildParameters(self.context.toolsBuildParameters))\n        hash += try! encoder.encode(Environment.current)\n        return [UInt8](hash)\n    }\n\n    override func execute(\n        _: SPMLLBuild.Command,\n        _: SPMLLBuild.BuildSystemCommandInterface\n    ) -> Bool {\n        unsafe_await {\n            await self.context.packageStructureDelegate.packageStructureChanged()\n        }\n    }\n\n    /// Normalize any build parameters whose modifications do not need to cause a recompilation.\n    /// For instance, building with or without `--verbose` should not cause a full rebuild.\n    private func normalizeBuildParameters(\n        _ buildParameters: BuildParameters\n    ) throws -> BuildParameters {\n        var buildParameters = buildParameters\n        buildParameters.outputParameters = BuildParameters.Output(\n            isColorized: false,\n            isVerbose: false\n        )\n        buildParameters.workers = 1\n\n        let optionTable = OptionTable()\n        let parsedOptions = try optionTable.parse(Array(buildParameters.flags.swiftCompilerFlags.rawFlags), for: .batch)\n        let buildRecordInfoHash = BuildRecordArguments.computeHash(parsedOptions)\n\n        // Replace the swiftCompilerFlags with a hash of themselves where arguments that\n        // do not affect incremental builds are removed.\n        // FIXME: This should use a type other than BuildFlags\n        buildParameters.flags.swiftCompilerFlags = [buildRecordInfoHash].constructBuildFlags(source: nil)\n\n        return buildParameters\n    }\n}\n\nfinal class CopyCommand: CustomLLBuildCommand {\n    override func execute(\n        _ command: SPMLLBuild.Command,\n        _: SPMLLBuild.BuildSystemCommandInterface\n    ) -> Bool {\n        do {\n            // This tool will never run without the build description.\n            guard let buildDescription = self.context.buildDescription else {\n                throw InternalError(\"unknown build description\")\n            }\n            guard let tool = buildDescription.copyCommands[command.name] else {\n                throw StringError(\"command \\(command.name) not registered\")\n            }\n\n            let input = try AbsolutePath(validating: tool.inputs[0].name)\n            let output = try AbsolutePath(validating: tool.outputs[0].name)\n            try self.context.fileSystem.createDirectory(output.parentDirectory, recursive: true)\n            try self.context.fileSystem.removeFileTree(output)\n            try self.context.fileSystem.copy(from: input, to: output)\n        } catch {\n            self.context.observabilityScope.emit(error)\n            return false\n        }\n        return true\n    }\n}\n"
  },
  {
    "path": "Sources/Build/LLBuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport LLBuildManifest\nimport SPMBuildCore\nimport PackageGraph\nimport PackageModel\n\nimport enum PackageModel.TraitConfiguration\n\nimport struct TSCBasic.ByteString\n\n/// Contains the description of the build that is needed during the execution.\npublic struct BuildDescription: Codable {\n    public typealias CommandName = String\n    public typealias TargetName = String\n    public typealias CommandLineFlag = String\n\n    /// The Swift compiler invocation targets.\n    let swiftCommands: [LLBuildManifest.CmdName: SwiftCompilerTool]\n\n    /// The Swift compiler frontend invocation targets.\n    let swiftFrontendCommands: [LLBuildManifest.CmdName: SwiftFrontendTool]\n\n    /// The map of test discovery commands.\n    let testDiscoveryCommands: [LLBuildManifest.CmdName: TestDiscoveryTool]\n\n    /// The map of test entry point commands.\n    let testEntryPointCommands: [LLBuildManifest.CmdName: TestEntryPointTool]\n\n    /// The map of copy commands.\n    let copyCommands: [LLBuildManifest.CmdName: CopyTool]\n\n    /// The map of write commands.\n    let writeCommands: [LLBuildManifest.CmdName: WriteAuxiliaryFile]\n\n    /// A flag that indicates this build should perform a check for whether targets only import\n    /// their explicitly-declared dependencies\n    let explicitTargetDependencyImportCheckingMode: BuildParameters.TargetDependencyImportCheckingMode\n\n    /// Every target's set of dependencies.\n    let targetDependencyMap: [TargetName: [TargetName]]\n\n    /// A full swift driver command-line invocation used to dependency-scan a given Swift target\n    let swiftTargetScanArgs: [TargetName: [CommandLineFlag]]\n\n    /// A set of all targets with generated source\n    let generatedSourceTargetSet: Set<TargetName>\n\n    /// The built test products.\n    public let builtTestProducts: [BuiltTestProduct]\n\n    /// Distilled information about any plugins defined in the package.\n    let pluginDescriptions: [PluginBuildDescription]\n\n    /// The enabled traits of the root package.\n    let traitConfiguration: TraitConfiguration?\n\n    public init(\n        plan: BuildPlan,\n        swiftCommands: [LLBuildManifest.CmdName: SwiftCompilerTool],\n        swiftFrontendCommands: [LLBuildManifest.CmdName: SwiftFrontendTool],\n        testDiscoveryCommands: [LLBuildManifest.CmdName: TestDiscoveryTool],\n        testEntryPointCommands: [LLBuildManifest.CmdName: TestEntryPointTool],\n        copyCommands: [LLBuildManifest.CmdName: CopyTool],\n        writeCommands: [LLBuildManifest.CmdName: WriteAuxiliaryFile],\n        pluginDescriptions: [PluginBuildDescription]\n    ) throws {\n        try self.init(\n            plan: plan,\n            swiftCommands: swiftCommands,\n            swiftFrontendCommands: swiftFrontendCommands,\n            testDiscoveryCommands: testDiscoveryCommands,\n            testEntryPointCommands: testEntryPointCommands,\n            copyCommands: copyCommands,\n            writeCommands: writeCommands,\n            pluginDescriptions: pluginDescriptions,\n            traitConfiguration: nil\n        )\n    }\n\n    package init(\n        plan: BuildPlan,\n        swiftCommands: [LLBuildManifest.CmdName: SwiftCompilerTool],\n        swiftFrontendCommands: [LLBuildManifest.CmdName: SwiftFrontendTool],\n        testDiscoveryCommands: [LLBuildManifest.CmdName: TestDiscoveryTool],\n        testEntryPointCommands: [LLBuildManifest.CmdName: TestEntryPointTool],\n        copyCommands: [LLBuildManifest.CmdName: CopyTool],\n        writeCommands: [LLBuildManifest.CmdName: WriteAuxiliaryFile],\n        pluginDescriptions: [PluginBuildDescription],\n        traitConfiguration: TraitConfiguration?\n    ) throws {\n        self.swiftCommands = swiftCommands\n        self.swiftFrontendCommands = swiftFrontendCommands\n        self.testDiscoveryCommands = testDiscoveryCommands\n        self.testEntryPointCommands = testEntryPointCommands\n        self.copyCommands = copyCommands\n        self.writeCommands = writeCommands\n        self.explicitTargetDependencyImportCheckingMode = plan.destinationBuildParameters.driverParameters\n            .explicitTargetDependencyImportCheckingMode\n        self.traitConfiguration = traitConfiguration\n        self.targetDependencyMap = try plan.targets\n            .reduce(into: [TargetName: [TargetName]]()) { partial, targetBuildDescription in\n                let deps = try targetBuildDescription.module.recursiveDependencies(\n                    satisfying: targetBuildDescription.buildParameters.buildEnvironment\n                )\n                .compactMap(\\.module).map(\\.c99name)\n                partial[targetBuildDescription.module.c99name] = deps\n            }\n        var targetCommandLines: [TargetName: [CommandLineFlag]] = [:]\n        var generatedSourceTargets: [TargetName] = []\n        for description in plan.targets {\n            guard case .swift(let desc) = description else {\n                continue\n            }\n            let buildParameters = description.buildParameters\n            targetCommandLines[desc.target.c99name] =\n                try desc.emitCommandLine(scanInvocation: true) + [\n                    \"-driver-use-frontend-path\", buildParameters.toolchain.swiftCompilerPath.pathString,\n                ]\n            if case .discovery = desc.testTargetRole {\n                generatedSourceTargets.append(desc.target.c99name)\n            }\n        }\n        generatedSourceTargets.append(\n            contentsOf: plan.pluginDescriptions\n                .map(\\.moduleC99Name)\n        )\n        self.swiftTargetScanArgs = targetCommandLines\n        self.generatedSourceTargetSet = Set(generatedSourceTargets)\n        self.builtTestProducts = try plan.buildProducts.filter { $0.product.type == .test }.map { desc in\n            try BuiltTestProduct(\n                productName: desc.product.name,\n                umbrellaProductName: nil,\n                binaryPath: desc.binaryPath,\n                packagePath: desc.package.path,\n                testEntryPointPath: desc.product.underlying.testEntryPointPath\n            )\n        }\n        self.pluginDescriptions = pluginDescriptions\n    }\n\n    public func write(fileSystem: Basics.FileSystem, path: AbsolutePath) throws {\n        let encoder = JSONEncoder.makeWithDefaults()\n        let data = try encoder.encode(self)\n        try fileSystem.writeFileContents(path, bytes: ByteString(data))\n    }\n\n    public static func load(fileSystem: Basics.FileSystem, path: AbsolutePath) throws -> BuildDescription {\n        let contents: Data = try fileSystem.readFileContents(path)\n        let decoder = JSONDecoder.makeWithDefaults()\n        return try decoder.decode(BuildDescription.self, from: contents)\n    }\n}\n"
  },
  {
    "path": "Sources/Build/LLBuildProgressTracker.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\nimport Dispatch\nimport Foundation\nimport LLBuildManifest\nimport PackageModel\nimport SPMBuildCore\nimport SPMLLBuild\n\nimport protocol TSCBasic.OutputByteStream\nimport struct TSCBasic.RegEx\nimport class TSCBasic.ThreadSafeOutputByteStream\n\nimport class TSCUtility.IndexStoreAPI\n\n#if canImport(llbuildSwift)\ntypealias LLBuildBuildSystemDelegate = llbuildSwift.BuildSystemDelegate\n#else\ntypealias LLBuildBuildSystemDelegate = llbuild.BuildSystemDelegate\n#endif\n\nprivate final class InProcessTool: Tool {\n    let context: BuildExecutionContext\n    let type: CustomLLBuildCommand.Type\n\n    init(_ context: BuildExecutionContext, type: CustomLLBuildCommand.Type) {\n        self.context = context\n        self.type = type\n    }\n\n    func createCommand(_: String) -> ExternalCommand? {\n        type.init(self.context)\n    }\n}\n\n/// A provider of advice about build errors.\npublic protocol BuildErrorAdviceProvider {\n    /// Invoked after a command fails and an error message is detected in the output. Should return a string containing\n    /// advice or additional information, if any, based on the build plan.\n    func provideBuildErrorAdvice(for target: String, command: String, message: String) -> String?\n}\n\n/// The context available during build execution.\npublic final class BuildExecutionContext {\n    /// Build parameters for products.\n    let productsBuildParameters: BuildParameters\n\n    /// Build parameters for build tools.\n    let toolsBuildParameters: BuildParameters\n\n    /// The build description.\n    ///\n    /// This is optional because we might not have a valid build description when performing the\n    /// build for PackageStructure target.\n    let buildDescription: BuildDescription?\n\n    /// The package structure delegate.\n    let packageStructureDelegate: PackageStructureDelegate\n\n    /// Optional provider of build error resolution advice.\n    let buildErrorAdviceProvider: BuildErrorAdviceProvider?\n\n    let fileSystem: Basics.FileSystem\n\n    let observabilityScope: ObservabilityScope\n\n    public init(\n        productsBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n        buildDescription: BuildDescription? = nil,\n        fileSystem: Basics.FileSystem,\n        observabilityScope: ObservabilityScope,\n        packageStructureDelegate: PackageStructureDelegate,\n        buildErrorAdviceProvider: BuildErrorAdviceProvider? = nil\n    ) {\n        self.productsBuildParameters = productsBuildParameters\n        self.toolsBuildParameters = toolsBuildParameters\n        self.buildDescription = buildDescription\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n        self.packageStructureDelegate = packageStructureDelegate\n        self.buildErrorAdviceProvider = buildErrorAdviceProvider\n    }\n\n    // MARK: - Private\n\n    private var indexStoreAPICache = ThreadSafeBox<Result<IndexStoreAPI, Error>?>()\n\n    /// Reference to the index store API.\n    var indexStoreAPI: Result<IndexStoreAPI, Error> {\n        self.indexStoreAPICache.memoize {\n            do {\n                #if os(Windows)\n                // The library's runtime component is in the `bin` directory on\n                // Windows rather than the `lib` directory as on Unix.  The `lib`\n                // directory contains the import library (and possibly static\n                // archives) which are used for linking.  The runtime component is\n                // not (necessarily) part of the SDK distributions.\n                //\n                // NOTE: the library name here `libIndexStore.dll` is technically\n                // incorrect as per the Windows naming convention.  However, the\n                // library is currently installed as `libIndexStore.dll` rather than\n                // `IndexStore.dll`.  In the future, this may require a fallback\n                // search, preferring `IndexStore.dll` over `libIndexStore.dll`.\n                let indexStoreLib = self.toolsBuildParameters.toolchain.swiftCompilerPath\n                    .parentDirectory\n                    .appending(\"libIndexStore.dll\")\n                #else\n                let ext = self.toolsBuildParameters.triple.dynamicLibraryExtension\n                let indexStoreLib = try toolsBuildParameters.toolchain.toolchainLibDir\n                    .appending(\"libIndexStore\" + ext)\n                #endif\n                return try .success(IndexStoreAPI(dylib: TSCAbsolutePath(indexStoreLib)))\n            } catch {\n                return .failure(error)\n            }\n        }\n    }\n}\n\npublic protocol PackageStructureDelegate {\n    func packageStructureChanged() async -> Bool\n}\n\n/// Convenient llbuild build system delegate implementation\nfinal class LLBuildProgressTracker: LLBuildBuildSystemDelegate, SwiftCompilerOutputParserDelegate {\n    private let outputStream: ThreadSafeOutputByteStream\n    private let progressAnimation: ProgressAnimationProtocol\n    private let logLevel: Basics.Diagnostic.Severity\n    private weak var delegate: SPMBuildCore.BuildSystemDelegate?\n    private let buildSystem: SPMBuildCore.BuildSystem\n    private let queue = DispatchQueue(label: \"org.swift.swiftpm.build-delegate\")\n    private var taskTracker = CommandTaskTracker()\n    private var errorMessagesByTarget: [String: [String]] = [:]\n    private let observabilityScope: ObservabilityScope\n    private var cancelled: Bool = false\n\n    /// Swift parsers keyed by llbuild command name.\n    private var swiftParsers: [String: SwiftCompilerOutputParser] = [:]\n\n    /// Buffer to accumulate non-swift output until command is finished\n    private var nonSwiftMessageBuffers: [String: [UInt8]] = [:]\n\n    /// The build execution context.\n    private let buildExecutionContext: BuildExecutionContext\n\n    init(\n        buildSystem: SPMBuildCore.BuildSystem,\n        buildExecutionContext: BuildExecutionContext,\n        outputStream: OutputByteStream,\n        progressAnimation: ProgressAnimationProtocol,\n        logLevel: Basics.Diagnostic.Severity,\n        observabilityScope: ObservabilityScope,\n        delegate: SPMBuildCore.BuildSystemDelegate?\n    ) {\n        self.buildSystem = buildSystem\n        self.buildExecutionContext = buildExecutionContext\n        // FIXME: Implement a class convenience initializer that does this once they are supported\n        // https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924\n        self.outputStream = outputStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(outputStream)\n        self.progressAnimation = progressAnimation\n        self.logLevel = logLevel\n        self.observabilityScope = observabilityScope\n        self.delegate = delegate\n\n        let swiftParsers = buildExecutionContext.buildDescription?.swiftCommands.mapValues { tool in\n            SwiftCompilerOutputParser(targetName: tool.moduleName, delegate: self)\n        } ?? [:]\n        self.swiftParsers = swiftParsers\n\n        self.taskTracker.onTaskProgressUpdateText = { [weak self] progressText, _ in\n            guard let self else { return }\n            self.queue.async { [weak self] in\n                guard let self else { return }\n                self.delegate?.buildSystem(self.buildSystem, didUpdateTaskProgress: progressText)\n            }\n        }\n    }\n\n    public func finalize(success: Bool) {\n        self.queue.async {\n            self.progressAnimation.complete(success: success)\n        }\n    }\n\n    // MARK: llbuildSwift.BuildSystemDelegate\n\n    var fs: SPMLLBuild.FileSystem? {\n        nil\n    }\n\n    func lookupTool(_ name: String) -> Tool? {\n        switch name {\n        case TestDiscoveryTool.name:\n            InProcessTool(self.buildExecutionContext, type: TestDiscoveryCommand.self)\n        case TestEntryPointTool.name:\n            InProcessTool(self.buildExecutionContext, type: TestEntryPointCommand.self)\n        case PackageStructureTool.name:\n            InProcessTool(self.buildExecutionContext, type: PackageStructureCommand.self)\n        case CopyTool.name:\n            InProcessTool(self.buildExecutionContext, type: CopyCommand.self)\n        case WriteAuxiliaryFile.name:\n            InProcessTool(self.buildExecutionContext, type: WriteAuxiliaryFileCommand.self)\n        default:\n            nil\n        }\n    }\n\n    func hadCommandFailure() {\n        do {\n            try self.buildSystem.cancel(deadline: .now())\n        } catch {\n            self.observabilityScope.emit(error: \"failed to cancel the build: \\(error)\")\n        }\n        self.delegate?.buildSystemDidCancel(self.buildSystem)\n    }\n\n    func handleDiagnostic(_ diagnostic: SPMLLBuild.Diagnostic) {\n        switch diagnostic.kind {\n        case .note:\n            self.observabilityScope.emit(info: diagnostic.message)\n        case .warning:\n            self.observabilityScope.emit(warning: diagnostic.message)\n        case .error:\n            self.observabilityScope.emit(error: diagnostic.message)\n        @unknown default:\n            self.observabilityScope.emit(info: diagnostic.message)\n        }\n    }\n\n    func commandStatusChanged(_ command: SPMLLBuild.Command, kind: CommandStatusKind) {\n        guard !self.logLevel.isVerbose,\n              !self.logLevel.isQuiet\n        else { return }\n        guard command.shouldShowStatus else { return }\n        guard !self.swiftParsers.keys.contains(command.name) else { return }\n\n        self.queue.async {\n            self.taskTracker.commandStatusChanged(command, kind: kind)\n            self.updateProgress()\n        }\n    }\n\n    func commandPreparing(_ command: SPMLLBuild.Command) {\n        self.queue.async {\n            self.delegate?.buildSystem(self.buildSystem, willStartCommand: BuildSystemCommand(command))\n        }\n    }\n\n    func commandStarted(_ command: SPMLLBuild.Command) {\n        guard command.shouldShowStatus else { return }\n\n        self.queue.async {\n            self.delegate?.buildSystem(self.buildSystem, didStartCommand: BuildSystemCommand(command))\n            if self.logLevel.isVerbose {\n                self.outputStream.send(\"\\(command.verboseDescription)\\n\")\n                self.outputStream.flush()\n            }\n        }\n    }\n\n    func shouldCommandStart(_: SPMLLBuild.Command) -> Bool {\n        true\n    }\n\n    func commandFinished(_ command: SPMLLBuild.Command, result: CommandResult) {\n        guard command.shouldShowStatus else { return }\n        guard !self.swiftParsers.keys.contains(command.name) else { return }\n\n        let commandName = command.name\n        let commandDescription = command.description\n\n        self.queue.async {\n            if result == .cancelled {\n                self.cancelled = true\n                self.delegate?.buildSystemDidCancel(self.buildSystem)\n            }\n\n            self.delegate?.buildSystem(self.buildSystem, didFinishCommand: BuildSystemCommand(command))\n\n            if !self.logLevel.isVerbose && !self.logLevel.isQuiet {\n                let targetName = self.swiftParsers[commandName]?.targetName\n                self.taskTracker.commandFinished(commandDescription, result: result, targetName: targetName)\n                self.updateProgress()\n            }\n        }\n    }\n\n    func commandHadError(_ command: SPMLLBuild.Command, message: String) {\n        self.observabilityScope.emit(error: message)\n    }\n\n    func commandHadNote(_ command: SPMLLBuild.Command, message: String) {\n        self.observabilityScope.emit(info: message)\n    }\n\n    func commandHadWarning(_ command: SPMLLBuild.Command, message: String) {\n        self.observabilityScope.emit(warning: message)\n    }\n\n    func commandCannotBuildOutputDueToMissingInputs(\n        _ command: SPMLLBuild.Command,\n        output: BuildKey,\n        inputs: [BuildKey]\n    ) {\n        self.observabilityScope.emit(.missingInputs(output: output, inputs: inputs))\n    }\n\n    func cannotBuildNodeDueToMultipleProducers(output: BuildKey, commands: [SPMLLBuild.Command]) {\n        self.observabilityScope.emit(.multipleProducers(output: output, commands: commands))\n    }\n\n    func commandProcessStarted(_ command: SPMLLBuild.Command, process: ProcessHandle) {}\n\n    func commandProcessHadError(_ command: SPMLLBuild.Command, process: ProcessHandle, message: String) {\n        self.observabilityScope.emit(.commandError(command: command, message: message))\n    }\n\n    func commandProcessHadOutput(_ command: SPMLLBuild.Command, process: ProcessHandle, data: [UInt8]) {\n        guard command.shouldShowStatus else { return }\n\n        if let swiftParser = swiftParsers[command.name] {\n            swiftParser.parse(bytes: data)\n        } else {\n            self.queue.async {\n                self.nonSwiftMessageBuffers[command.name, default: []] += data\n            }\n        }\n    }\n\n    func commandProcessFinished(\n        _ command: SPMLLBuild.Command,\n        process: ProcessHandle,\n        result: CommandExtendedResult\n    ) {\n        // FIXME: This should really happen at the command-level and is just a stopgap measure.\n        let shouldFilterOutput = !self.logLevel.isVerbose && command.verboseDescription.hasPrefix(\"codesign \") && result\n            .result != .failed\n\n        let commandName = command.name\n\n        self.queue.async {\n            if let buffer = self.nonSwiftMessageBuffers[commandName], !shouldFilterOutput {\n                self.progressAnimation.clear()\n                self.outputStream.send(buffer)\n                self.outputStream.flush()\n                self.nonSwiftMessageBuffers[commandName] = nil\n            }\n        }\n\n        switch result.result {\n        case .cancelled:\n            self.cancelled = true\n            self.delegate?.buildSystemDidCancel(self.buildSystem)\n        case .failed:\n            // The command failed, so we queue up an asynchronous task to see if we have any error messages from the\n            // target to provide advice about.\n            self.queue.async {\n                guard let target = self.swiftParsers[commandName]?.targetName else { return }\n                guard let errorMessages = self.errorMessagesByTarget[target] else { return }\n                for errorMessage in errorMessages {\n                    // Emit any advice that's provided for each error message.\n                    if let adviceMessage = self.buildExecutionContext.buildErrorAdviceProvider?.provideBuildErrorAdvice(\n                        for: target,\n                        command: commandName,\n                        message: errorMessage\n                    ) {\n                        self.outputStream.send(\"note: \\(adviceMessage)\\n\")\n                        self.outputStream.flush()\n                    }\n                }\n            }\n        case .succeeded, .skipped:\n            break\n        @unknown default:\n            break\n        }\n    }\n\n    func cycleDetected(rules: [BuildKey]) {\n        self.observabilityScope.emit(.cycleError(rules: rules))\n\n        self.queue.async {\n            self.delegate?.buildSystemDidDetectCycleInRules(self.buildSystem)\n        }\n    }\n\n    func shouldResolveCycle(rules: [BuildKey], candidate: BuildKey, action: CycleAction) -> Bool {\n        false\n    }\n\n    /// Invoked right before running an action taken before building.\n    func preparationStepStarted(_ name: String) {\n        guard !self.logLevel.isQuiet else { return }\n        self.queue.async {\n            self.taskTracker.buildPreparationStepStarted(name)\n            self.updateProgress()\n        }\n    }\n\n    /// Invoked when an action taken before building emits output.\n    /// when verboseOnly is set to true, the output will only be printed in verbose logging mode\n    func preparationStepHadOutput(_ name: String, output: String, verboseOnly: Bool) {\n        guard !logLevel.isQuiet else { return }\n        self.queue.async {\n            self.progressAnimation.clear()\n            if !verboseOnly || self.logLevel.isVerbose {\n                self.outputStream.send(\"\\(output.spm_chomp())\\n\")\n                self.outputStream.flush()\n            }\n        }\n    }\n\n    /// Invoked right after running an action taken before building. The result\n    /// indicates whether the action succeeded, failed, or was cancelled.\n    func preparationStepFinished(_ name: String, result: CommandResult) {\n        guard !self.logLevel.isQuiet else { return }\n        self.queue.async {\n            self.taskTracker.buildPreparationStepFinished(name)\n            self.updateProgress()\n        }\n    }\n\n    // MARK: SwiftCompilerOutputParserDelegate\n\n    func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didParse message: SwiftCompilerMessage) {\n        self.queue.async {\n            if self.logLevel.isVerbose {\n                if let text = message.verboseProgressText {\n                    self.outputStream.send(\"\\(text)\\n\")\n                    self.outputStream.flush()\n                }\n            } else if !self.logLevel.isQuiet {\n                self.taskTracker.swiftCompilerDidOutputMessage(message, targetName: parser.targetName)\n                self.updateProgress()\n            }\n\n            if let output = message.standardOutput {\n                // first we want to print the output so users have it handy\n                if !self.logLevel.isVerbose {\n                    self.progressAnimation.clear()\n                }\n\n                self.outputStream.send(output)\n                self.outputStream.flush()\n\n                // next we want to try and scoop out any errors from the output (if reasonable size, otherwise this\n                // will be very slow), so they can later be passed to the advice provider in case of failure.\n                if output.utf8.count < 1024 * 10 {\n                    let regex = try! RegEx(pattern: #\".*(error:[^\\n]*)\\n.*\"#, options: .dotMatchesLineSeparators)\n                    for match in regex.matchGroups(in: output) {\n                        self.errorMessagesByTarget[parser.targetName] = (\n                            self.errorMessagesByTarget[parser.targetName] ?? []\n                        ) + [match[0]]\n                    }\n                }\n            }\n        }\n    }\n\n    func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didFailWith error: Error) {\n        let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription\n        self.observabilityScope.emit(.swiftCompilerOutputParsingError(message))\n        self.hadCommandFailure()\n    }\n\n    func buildStart(configuration: BuildConfiguration) {\n        guard !logLevel.isQuiet else { return }\n        self.queue.sync {\n            self.progressAnimation.clear()\n            self.outputStream.send(\"Building for \\(configuration == .debug ? \"debugging\" : \"production\")...\\n\")\n            self.outputStream.flush()\n        }\n    }\n\n    func buildComplete(success: Bool, duration: DispatchTimeInterval, subsetDescriptor: String? = nil) {\n        let subsetString = if let subsetDescriptor {\n            \"of \\(subsetDescriptor) \"\n        } else {\n            \"\"\n        }\n\n        self.queue.sync {\n            self.progressAnimation.complete(success: success)\n            self.delegate?.buildSystem(self.buildSystem, didFinishWithResult: success)\n\n            if !self.logLevel.isQuiet, success {\n                let message = self.cancelled ? \"Build \\(subsetString)cancelled!\" : \"Build \\(subsetString)complete!\"\n                self.progressAnimation.clear()\n                self.outputStream.send(\"\\(message) (\\(duration.descriptionInSeconds))\\n\")\n                self.outputStream.flush()\n            }\n        }\n    }\n\n    // MARK: Private\n\n    private func updateProgress() {\n        if let progressText = taskTracker.latestFinishedText {\n            self.progressAnimation.update(\n                step: self.taskTracker.finishedCount,\n                total: self.taskTracker.totalCount,\n                text: progressText\n            )\n        }\n    }\n}\n\n/// Tracks tasks based on command status and swift compiler output.\nprivate struct CommandTaskTracker {\n    private(set) var totalCount = 0\n    private(set) var finishedCount = 0\n    private var swiftTaskProgressTexts: [Int: String] = [:]\n\n    /// The last task text before the task list was emptied.\n    private(set) var latestFinishedText: String?\n\n    var onTaskProgressUpdateText: ((_ text: String, _ targetName: String?) -> Void)?\n\n    mutating func commandStatusChanged(_ command: SPMLLBuild.Command, kind: CommandStatusKind) {\n        switch kind {\n        case .isScanning:\n            self.totalCount += 1\n        case .isUpToDate:\n            self.totalCount -= 1\n        case .isComplete:\n            self.finishedCount += 1\n        @unknown default:\n            assertionFailure(\"unhandled command status kind \\(kind) for command \\(command)\")\n        }\n    }\n\n    mutating func commandFinished(_ commandDescription: String, result: CommandResult, targetName: String?) {\n        let progressTextValue = self.progressText(of: commandDescription, targetName: targetName)\n        self.onTaskProgressUpdateText?(progressTextValue, targetName)\n\n        self.latestFinishedText = progressTextValue\n    }\n\n    mutating func swiftCompilerDidOutputMessage(_ message: SwiftCompilerMessage, targetName: String) {\n        switch message.kind {\n        case .began(let info):\n            if let text = progressText(of: message, targetName: targetName) {\n                self.swiftTaskProgressTexts[info.pid] = text\n                self.onTaskProgressUpdateText?(text, targetName)\n            }\n\n            self.totalCount += 1\n        case .finished(let info):\n            if let progressText = swiftTaskProgressTexts[info.pid] {\n                self.latestFinishedText = progressText\n                self.swiftTaskProgressTexts[info.pid] = nil\n            }\n\n            self.finishedCount += 1\n        case .unparsableOutput, .abnormal, .signalled, .skipped:\n            break\n        }\n    }\n\n    private func progressText(of commandDescription: String, targetName: String?) -> String {\n#if os(Windows)\n    let pathSep: Character = \"\\\\\"\n#else\n    let pathSep: Character = \"/\"\n#endif\n        // Transforms descriptions like \"Linking ./.build/x86_64-apple-macosx/debug/foo\" into \"Linking foo\".\n        if let firstSpaceIndex = commandDescription.firstIndex(of: \" \"),\n           let lastDirectorySeparatorIndex = commandDescription.lastIndex(of: pathSep)\n        {\n            let action = commandDescription[..<firstSpaceIndex]\n            let fileNameStartIndex = commandDescription.index(after: lastDirectorySeparatorIndex)\n            let fileName = commandDescription[fileNameStartIndex...]\n\n            if let targetName {\n                return \"\\(action) \\(targetName) \\(fileName)\"\n            } else {\n                return \"\\(action) \\(fileName)\"\n            }\n        } else {\n            return commandDescription\n        }\n    }\n\n    private func progressText(of message: SwiftCompilerMessage, targetName: String) -> String? {\n        if case .began(let info) = message.kind {\n            switch message.name {\n            case \"compile\":\n                if let sourceFile = info.inputs.first {\n                    let sourceFilePath = try! AbsolutePath(validating: sourceFile)\n                    return \"Compiling \\(targetName) \\(sourceFilePath.components.last!)\"\n                }\n            case \"link\":\n                return \"Linking \\(targetName)\"\n            case \"merge-module\":\n                return \"Merging module \\(targetName)\"\n            case \"emit-module\":\n                return \"Emitting module \\(targetName)\"\n            case \"generate-dsym\":\n                return \"Generating \\(targetName) dSYM\"\n            case \"generate-pch\":\n                return \"Generating \\(targetName) PCH\"\n            default:\n                break\n            }\n        }\n\n        return nil\n    }\n\n    mutating func buildPreparationStepStarted(_: String) {\n        self.totalCount += 1\n    }\n\n    mutating func buildPreparationStepFinished(_ name: String) {\n        self.latestFinishedText = name\n        self.finishedCount += 1\n    }\n}\n\nextension SwiftCompilerMessage {\n    fileprivate var verboseProgressText: String? {\n        switch kind {\n        case .began(let info):\n            ([info.commandExecutable] + info.commandArguments).joined(separator: \" \")\n        case .skipped, .finished, .abnormal, .signalled, .unparsableOutput:\n            nil\n        }\n    }\n\n    fileprivate var standardOutput: String? {\n        switch kind {\n        case .finished(let info),\n             .abnormal(let info),\n             .signalled(let info):\n            info.output\n        case .unparsableOutput(let output):\n            output\n        case .skipped, .began:\n            nil\n        }\n    }\n}\n\nextension Basics.Diagnostic {\n    fileprivate static func cycleError(rules: [BuildKey]) -> Self {\n        .error(\"build cycle detected: \" + rules.map(\\.key).joined(separator: \", \"))\n    }\n\n    fileprivate static func missingInputs(output: BuildKey, inputs: [BuildKey]) -> Self {\n        let missingInputs = inputs.map(\\.key).joined(separator: \", \")\n        return .error(\"couldn't build \\(output.key) because of missing inputs: \\(missingInputs)\")\n    }\n\n    fileprivate static func multipleProducers(output: BuildKey, commands: [SPMLLBuild.Command]) -> Self {\n        let producers = commands.map(\\.description).joined(separator: \", \")\n        return .error(\"couldn't build \\(output.key) because of multiple producers: \\(producers)\")\n    }\n\n    fileprivate static func commandError(command: SPMLLBuild.Command, message: String) -> Self {\n        .error(\"command \\(command.description) failed: \\(message)\")\n    }\n\n    fileprivate static func swiftCompilerOutputParsingError(_ error: String) -> Self {\n        .error(\"failed parsing the Swift compiler output: \\(error)\")\n    }\n}\n\nextension BuildSystemCommand {\n    fileprivate init(_ command: SPMLLBuild.Command) {\n        self.init(\n            name: command.name,\n            description: command.description,\n            verboseDescription: command.verboseDescription\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/Build/SwiftCompilerOutputParser.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\nimport class TSCUtility.JSONMessageStreamingParser\nimport protocol TSCUtility.JSONMessageStreamingParserDelegate\n\n/// Represents a message output by the Swift compiler in JSON output mode.\npublic struct SwiftCompilerMessage {\n    public enum Kind {\n        public struct Output {\n            public let type: String\n            public let path: String\n\n            public init(type: String, path: String) {\n                self.type = type\n                self.path = path\n            }\n        }\n\n        public struct BeganInfo {\n            public let pid: Int\n            public let inputs: [String]\n            public let outputs: [Output]?\n            public let commandExecutable: String\n            public let commandArguments: [String]\n\n            public init(\n                pid: Int,\n                inputs: [String],\n                outputs: [Output]?,\n                commandExecutable: String,\n                commandArguments: [String]\n            ) {\n                self.pid = pid\n                self.inputs = inputs\n                self.outputs = outputs\n                self.commandExecutable = commandExecutable\n                self.commandArguments = commandArguments\n            }\n        }\n\n        public struct SkippedInfo {\n            public let inputs: [String]\n            public let outputs: [Output]?\n\n            public init(inputs: [String], outputs: [SwiftCompilerMessage.Kind.Output]) {\n                self.inputs = inputs\n                self.outputs = outputs\n            }\n        }\n\n        public struct OutputInfo {\n            public let pid: Int\n            public let output: String?\n\n            public init(pid: Int, output: String?) {\n                self.pid = pid\n                self.output = output\n            }\n        }\n\n        case began(BeganInfo)\n        case skipped(SkippedInfo)\n        case finished(OutputInfo)\n        case abnormal(OutputInfo)\n        case signalled(OutputInfo)\n        case unparsableOutput(String)\n    }\n\n    public let name: String\n    public let kind: Kind\n\n    public init(name: String, kind: SwiftCompilerMessage.Kind) {\n        self.name = name\n        self.kind = kind\n    }\n}\n\n/// Protocol for the parser delegate to get notified of parsing events.\npublic protocol SwiftCompilerOutputParserDelegate: AnyObject {\n\n    /// Called for each message parsed.\n    func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didParse message: SwiftCompilerMessage)\n\n    /// Called on an un-expected parsing error. No more events will be received after that.\n    func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didFailWith error: Error)\n}\n\n/// Parser for the Swift compiler JSON output mode.\npublic final class SwiftCompilerOutputParser {\n\n    /// The underlying JSON message parser.\n    private var jsonParser: JSONMessageStreamingParser<SwiftCompilerOutputParser>!\n\n    /// Whether the parser is in a failing state.\n    private var hasFailed: Bool\n\n    /// Name of the target the compiler is compiling.\n    public let targetName: String\n\n    /// Delegate to notify of parsing events.\n    public weak var delegate: SwiftCompilerOutputParserDelegate?\n\n    /// Initializes the parser with a delegate to notify of parsing events.\n    /// - Parameters:\n    ///     - targetName: The name of the target being built.\n    ///     - delegate: Delegate to notify of parsing events.\n    public init(targetName: String, delegate: SwiftCompilerOutputParserDelegate) {\n        self.hasFailed = false\n        self.targetName = targetName\n        self.delegate = delegate\n\n        let decoder = JSONDecoder.makeWithDefaults()\n        decoder.keyDecodingStrategy = .convertFromSnakeCase\n        jsonParser = JSONMessageStreamingParser<SwiftCompilerOutputParser>(delegate: self, decoder: decoder)\n    }\n\n    /// Parse the next bytes of the Swift compiler JSON output.\n    /// - Note: If a parsing error is encountered, the delegate will be notified and the parser won't accept any further\n    ///   input.\n    public func parse<C>(bytes: C) where C: Collection, C.Element == UInt8 {\n        guard !hasFailed else {\n            return\n        }\n\n        jsonParser.parse(bytes: bytes)\n    }\n}\n\nextension SwiftCompilerOutputParser: JSONMessageStreamingParserDelegate {\n    public func jsonMessageStreamingParser(\n        _ parser: JSONMessageStreamingParser<SwiftCompilerOutputParser>,\n        didParse message: SwiftCompilerMessage\n    ) {\n        guard !hasFailed else {\n            return\n        }\n\n        delegate?.swiftCompilerOutputParser(self, didParse: message)\n\n        if case .signalled = message.kind {\n            hasFailed = true\n        }\n    }\n\n    public func jsonMessageStreamingParser(\n        _ parser: JSONMessageStreamingParser<SwiftCompilerOutputParser>,\n        didParseRawText text: String\n    ) {\n        guard !hasFailed else {\n            return\n        }\n\n        let message = SwiftCompilerMessage(name: \"unknown\", kind: .unparsableOutput(text + \"\\n\"))\n        delegate?.swiftCompilerOutputParser(self, didParse: message)\n    }\n\n    public func jsonMessageStreamingParser(\n        _ parser: JSONMessageStreamingParser<SwiftCompilerOutputParser>,\n        didFailWith error: Error\n    ) {\n        delegate?.swiftCompilerOutputParser(self, didFailWith: error)\n    }\n}\n\nextension SwiftCompilerMessage: Decodable, Equatable {\n    enum CodingKeys: CodingKey {\n        case pid\n        case name\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        name = try container.decode(String.self, forKey: .name)\n        kind = try Kind(from: decoder)\n    }\n}\n\nextension SwiftCompilerMessage.Kind: Decodable, Equatable {\n    enum CodingKeys: CodingKey {\n        case kind\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        let kind = try container.decode(String.self, forKey: .kind)\n        switch kind {\n        case \"began\":\n            self = try .began(BeganInfo(from: decoder))\n        case \"skipped\":\n            self = try .skipped(SkippedInfo(from: decoder))\n        case \"finished\":\n            self = try .finished(OutputInfo(from: decoder))\n        case \"abnormal-exit\":\n            self = try .abnormal(OutputInfo(from: decoder))\n        case \"signalled\":\n            self = try .signalled(OutputInfo(from: decoder))\n        default:\n            throw DecodingError.dataCorruptedError(forKey: .kind, in: container, debugDescription: \"invalid kind\")\n        }\n    }\n}\n\nextension SwiftCompilerMessage.Kind.Output: Decodable, Equatable {}\nextension SwiftCompilerMessage.Kind.BeganInfo: Decodable, Equatable {}\nextension SwiftCompilerMessage.Kind.SkippedInfo: Decodable, Equatable {}\nextension SwiftCompilerMessage.Kind.OutputInfo: Decodable, Equatable {}\n"
  },
  {
    "path": "Sources/Build/TestObservation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SPMBuildCore\n\npublic func generateTestObservationCode(buildParameters: BuildParameters) -> String {\n    guard buildParameters.triple.supportsTestSummary else {\n        return \"\"\n    }\n\n    let content =\n        \"\"\"\n        import Foundation\n        import XCTest\n\n        public final class SwiftPMXCTestObserver: NSObject {\n            public override init() {\n                super.init()\n                XCTestObservationCenter.shared.addTestObserver(self)\n            }\n        }\n\n        extension SwiftPMXCTestObserver: XCTestObservation {\n            var testOutputPath: String {\n                return \"\\(buildParameters.testOutputPath)\"\n            }\n\n            private func write(record: any Encodable) {\n                let lock = FileLock(at: URL(fileURLWithPath: self.testOutputPath + \".lock\"))\n                _ = try? lock.withLock {\n                    self._write(record: record)\n                }\n            }\n\n            private func _write(record: any Encodable) {\n                if let data = try? JSONEncoder().encode(record) {\n                    if let fileHandle = FileHandle(forWritingAtPath: self.testOutputPath) {\n                        defer { fileHandle.closeFile() }\n                        fileHandle.seekToEndOfFile()\n                        fileHandle.write(\"\\\\n\".data(using: .utf8)!)\n                        fileHandle.write(data)\n                    } else {\n                        _ = try? data.write(to: URL(fileURLWithPath: self.testOutputPath))\n                    }\n                }\n            }\n\n            public func testBundleWillStart(_ testBundle: Bundle) {\n                let record = TestBundleEventRecord(bundle: .init(testBundle), event: .start)\n                write(record: TestEventRecord(bundleEvent: record))\n            }\n\n            public func testSuiteWillStart(_ testSuite: XCTestSuite) {\n                let record = TestSuiteEventRecord(suite: .init(testSuite), event: .start)\n                write(record: TestEventRecord(suiteEvent: record))\n            }\n\n            public func testCaseWillStart(_ testCase: XCTestCase) {\n                let record = TestCaseEventRecord(testCase: .init(testCase), event: .start)\n                write(record: TestEventRecord(caseEvent: record))\n            }\n\n            #if canImport(Darwin)\n            public func testCase(_ testCase: XCTestCase, didRecord issue: XCTIssue) {\n                let record = TestCaseFailureRecord(testCase: .init(testCase), issue: .init(issue), failureKind: .unexpected)\n                write(record: TestEventRecord(caseFailure: record))\n            }\n\n            public func testCase(_ testCase: XCTestCase, didRecord expectedFailure: XCTExpectedFailure) {\n                let record = TestCaseFailureRecord(testCase: .init(testCase), issue: .init(expectedFailure.issue), failureKind: .expected(failureReason: expectedFailure.failureReason))\n                write(record: TestEventRecord(caseFailure: record))\n            }\n            #else\n            public func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: Int) {\n                let issue = TestIssue(description: description, inFile: filePath, atLine: lineNumber)\n                let record = TestCaseFailureRecord(testCase: .init(testCase), issue: issue, failureKind: .unexpected)\n                write(record: TestEventRecord(caseFailure: record))\n            }\n            #endif\n\n            public func testCaseDidFinish(_ testCase: XCTestCase) {\n                let record = TestCaseEventRecord(testCase: .init(testCase), event: .finish)\n                write(record: TestEventRecord(caseEvent: record))\n            }\n\n            #if canImport(Darwin)\n            public func testSuite(_ testSuite: XCTestSuite, didRecord issue: XCTIssue) {\n                let record = TestSuiteFailureRecord(suite: .init(testSuite), issue: .init(issue), failureKind: .unexpected)\n                write(record: TestEventRecord(suiteFailure: record))\n            }\n\n            public func testSuite(_ testSuite: XCTestSuite, didRecord expectedFailure: XCTExpectedFailure) {\n                let record = TestSuiteFailureRecord(suite: .init(testSuite), issue: .init(expectedFailure.issue), failureKind: .expected(failureReason: expectedFailure.failureReason))\n                write(record: TestEventRecord(suiteFailure: record))\n            }\n            #else\n            public func testSuite(_ testSuite: XCTestSuite, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: Int) {\n                let issue = TestIssue(description: description, inFile: filePath, atLine: lineNumber)\n                let record = TestSuiteFailureRecord(suite: .init(testSuite), issue: issue, failureKind: .unexpected)\n                write(record: TestEventRecord(suiteFailure: record))\n            }\n            #endif\n\n            public func testSuiteDidFinish(_ testSuite: XCTestSuite) {\n                let record = TestSuiteEventRecord(suite: .init(testSuite), event: .finish)\n                write(record: TestEventRecord(suiteEvent: record))\n            }\n\n            public func testBundleDidFinish(_ testBundle: Bundle) {\n                let record = TestBundleEventRecord(bundle: .init(testBundle), event: .finish)\n                write(record: TestEventRecord(bundleEvent: record))\n            }\n        }\n\n        // FIXME: Copied from `Lock.swift` in TSCBasic, would be nice if we had a better way\n\n        #if canImport(Glibc)\n        @_exported import Glibc\n        #elseif canImport(Musl)\n        @_exported import Musl\n        #elseif os(Windows)\n        @_exported import CRT\n        @_exported import WinSDK\n        #elseif os(WASI)\n        @_exported import WASILibc\n        #elseif canImport(Android)\n        @_exported import Android\n        #else\n        @_exported import Darwin.C\n        #endif\n\n        import Foundation\n\n        public final class FileLock {\n          #if os(Windows)\n            private var handle: HANDLE?\n          #else\n            private var fileDescriptor: CInt?\n          #endif\n\n            private let lockFile: URL\n\n            public init(at lockFile: URL) {\n                self.lockFile = lockFile\n            }\n\n            public func lock() throws {\n              #if os(Windows)\n                if handle == nil {\n                    let h: HANDLE = lockFile.path.withCString(encodedAs: UTF16.self, {\n                        CreateFileW(\n                            $0,\n                            UInt32(GENERIC_READ) | UInt32(GENERIC_WRITE),\n                            UInt32(FILE_SHARE_READ) | UInt32(FILE_SHARE_WRITE),\n                            nil,\n                            DWORD(OPEN_ALWAYS),\n                            DWORD(FILE_ATTRIBUTE_NORMAL),\n                            nil\n                        )\n                    })\n                    if h == INVALID_HANDLE_VALUE {\n                        throw FileSystemError(errno: Int32(GetLastError()), lockFile)\n                    }\n                    self.handle = h\n                }\n                var overlapped = OVERLAPPED()\n                overlapped.Offset = 0\n                overlapped.OffsetHigh = 0\n                overlapped.hEvent = nil\n                if !LockFileEx(handle, DWORD(LOCKFILE_EXCLUSIVE_LOCK), 0,\n                                   UInt32.max, UInt32.max, &overlapped) {\n                        throw ProcessLockError.unableToAquireLock(errno: Int32(GetLastError()))\n                    }\n              #elseif os(WASI)\n                // WASI doesn't support flock\n              #else\n                if fileDescriptor == nil {\n                    let fd = open(lockFile.path, O_WRONLY | O_CREAT | O_CLOEXEC, 0o666)\n                    if fd == -1 {\n                        fatalError(\"errno: \\\\(errno), lockFile: \\\\(lockFile)\")\n                    }\n                    self.fileDescriptor = fd\n                }\n                while true {\n                    if flock(fileDescriptor!, LOCK_EX) == 0 {\n                        break\n                    }\n                    if errno == EINTR { continue }\n                    fatalError(\"unable to acquire lock, errno: \\\\(errno)\")\n                }\n              #endif\n            }\n\n            public func unlock() {\n              #if os(Windows)\n                var overlapped = OVERLAPPED()\n                overlapped.Offset = 0\n                overlapped.OffsetHigh = 0\n                overlapped.hEvent = nil\n                UnlockFileEx(handle, 0, UInt32.max, UInt32.max, &overlapped)\n              #elseif os(WASI)\n                // WASI doesn't support flock\n              #else\n                guard let fd = fileDescriptor else { return }\n                flock(fd, LOCK_UN)\n              #endif\n            }\n\n            deinit {\n              #if os(Windows)\n                guard let handle = handle else { return }\n                CloseHandle(handle)\n              #elseif os(WASI)\n                // WASI doesn't support flock\n              #else\n                guard let fd = fileDescriptor else { return }\n                close(fd)\n              #endif\n            }\n\n            public func withLock<T>(_ body: () throws -> T) throws -> T {\n                try lock()\n                defer { unlock() }\n                return try body()\n            }\n\n            public func withLock<T>(_ body: () async throws -> T) async throws -> T {\n                try lock()\n                defer { unlock() }\n                return try await body()\n            }\n        }\n\n        // FIXME: Copied from `XCTEvents.swift`, would be nice if we had a better way\n\n        struct TestEventRecord: Codable {\n            let caseFailure: TestCaseFailureRecord?\n            let suiteFailure: TestSuiteFailureRecord?\n\n            let bundleEvent: TestBundleEventRecord?\n            let suiteEvent: TestSuiteEventRecord?\n            let caseEvent: TestCaseEventRecord?\n\n            init(\n                caseFailure: TestCaseFailureRecord? = nil,\n                suiteFailure: TestSuiteFailureRecord? = nil,\n                bundleEvent: TestBundleEventRecord? = nil,\n                suiteEvent: TestSuiteEventRecord? = nil,\n                caseEvent: TestCaseEventRecord? = nil\n            ) {\n                self.caseFailure = caseFailure\n                self.suiteFailure = suiteFailure\n                self.bundleEvent = bundleEvent\n                self.suiteEvent = suiteEvent\n                self.caseEvent = caseEvent\n            }\n        }\n\n        // MARK: - Records\n\n        struct TestAttachment: Codable {\n            let name: String?\n            // TODO: Handle `userInfo: [AnyHashable : Any]?`\n            let uniformTypeIdentifier: String\n            let payload: Data?\n        }\n\n        struct TestBundleEventRecord: Codable {\n            let bundle: TestBundle\n            let event: TestEvent\n        }\n\n        struct TestCaseEventRecord: Codable {\n            let testCase: TestCase\n            let event: TestEvent\n        }\n\n        struct TestCaseFailureRecord: Codable, CustomStringConvertible {\n            let testCase: TestCase\n            let issue: TestIssue\n            let failureKind: TestFailureKind\n\n            var description: String {\n                return \"\\\\(issue.sourceCodeContext.description)\\\\(testCase) \\\\(issue.compactDescription)\"\n            }\n        }\n\n        struct TestSuiteEventRecord: Codable {\n            let suite: TestSuiteRecord\n            let event: TestEvent\n        }\n\n        struct TestSuiteFailureRecord: Codable {\n            let suite: TestSuiteRecord\n            let issue: TestIssue\n            let failureKind: TestFailureKind\n        }\n\n        // MARK: Primitives\n\n        struct TestBundle: Codable {\n            let bundleIdentifier: String?\n            let bundlePath: String\n        }\n\n        struct TestCase: Codable {\n            let name: String\n        }\n\n        struct TestErrorInfo: Codable {\n            let description: String\n            let type: String\n        }\n\n        enum TestEvent: Codable {\n            case start\n            case finish\n        }\n\n        enum TestFailureKind: Codable, Equatable {\n            case unexpected\n            case expected(failureReason: String?)\n\n            var isExpected: Bool {\n                switch self {\n                case .expected: return true\n                case .unexpected: return false\n                }\n            }\n        }\n\n        struct TestIssue: Codable {\n            let type: TestIssueType\n            let compactDescription: String\n            let detailedDescription: String?\n            let associatedError: TestErrorInfo?\n            let sourceCodeContext: TestSourceCodeContext\n            let attachments: [TestAttachment]\n        }\n\n        enum TestIssueType: Codable {\n            case assertionFailure\n            case performanceRegression\n            case system\n            case thrownError\n            case uncaughtException\n            case unmatchedExpectedFailure\n            case unknown\n        }\n\n        struct TestLocation: Codable, CustomStringConvertible {\n            let file: String\n            let line: Int\n\n            var description: String {\n                return \"\\\\(file):\\\\(line) \"\n            }\n        }\n\n        struct TestSourceCodeContext: Codable, CustomStringConvertible {\n            let callStack: [TestSourceCodeFrame]\n            let location: TestLocation?\n\n            var description: String {\n                return location?.description ?? \"\"\n            }\n        }\n\n        struct TestSourceCodeFrame: Codable {\n            let address: UInt64\n            let symbolInfo: TestSourceCodeSymbolInfo?\n            let symbolicationError: TestErrorInfo?\n        }\n\n        struct TestSourceCodeSymbolInfo: Codable {\n            let imageName: String\n            let symbolName: String\n            let location: TestLocation?\n        }\n\n        struct TestSuiteRecord: Codable {\n            let name: String\n        }\n\n        // MARK: XCTest compatibility\n\n        extension TestIssue {\n            init(description: String, inFile filePath: String?, atLine lineNumber: Int) {\n                let location: TestLocation?\n                if let filePath = filePath {\n                    location = .init(file: filePath, line: lineNumber)\n                } else {\n                    location = nil\n                }\n                self.init(type: .assertionFailure, compactDescription: description, detailedDescription: description, associatedError: nil, sourceCodeContext: .init(callStack: [], location: location), attachments: [])\n            }\n        }\n\n        import XCTest\n\n        #if canImport(Darwin) // XCTAttachment is unavailable in swift-corelibs-xctest.\n        extension TestAttachment {\n            init(_ attachment: XCTAttachment) {\n                self.init(\n                    name: attachment.name,\n                    uniformTypeIdentifier: attachment.uniformTypeIdentifier,\n                    payload: attachment.value(forKey: \"payload\") as? Data\n                )\n            }\n        }\n        #endif\n\n        extension TestBundle {\n            init(_ testBundle: Bundle) {\n                self.init(\n                    bundleIdentifier: testBundle.bundleIdentifier,\n                    bundlePath: testBundle.bundlePath\n                )\n            }\n        }\n\n        extension TestCase {\n            init(_ testCase: XCTestCase) {\n                self.init(name: testCase.name)\n            }\n        }\n\n        extension TestErrorInfo {\n            init(_ error: any Swift.Error) {\n                self.init(description: \"\\\\(error)\", type: \"\\\\(Swift.type(of: error))\")\n            }\n        }\n\n        #if canImport(Darwin) // XCTIssue is unavailable in swift-corelibs-xctest.\n        extension TestIssue {\n            init(_ issue: XCTIssue) {\n                self.init(\n                    type: .init(issue.type),\n                    compactDescription: issue.compactDescription,\n                    detailedDescription: issue.detailedDescription,\n                    associatedError: issue.associatedError.map { .init($0) },\n                    sourceCodeContext: .init(issue.sourceCodeContext),\n                    attachments: issue.attachments.map { .init($0) }\n                )\n            }\n        }\n\n        extension TestIssueType {\n            init(_ type: XCTIssue.IssueType) {\n                switch type {\n                case .assertionFailure: self = .assertionFailure\n                case .thrownError: self = .thrownError\n                case .uncaughtException: self = .uncaughtException\n                case .performanceRegression: self = .performanceRegression\n                case .system: self = .system\n                case .unmatchedExpectedFailure: self = .unmatchedExpectedFailure\n                @unknown default: self = .unknown\n                }\n            }\n        }\n        #endif\n\n        #if canImport(Darwin) // XCTSourceCodeLocation/XCTSourceCodeContext/XCTSourceCodeFrame/XCTSourceCodeSymbolInfo is unavailable in swift-corelibs-xctest.\n        extension TestLocation {\n            init(_ location: XCTSourceCodeLocation) {\n                self.init(\n                    file: location.fileURL.absoluteString,\n                    line: location.lineNumber\n                )\n            }\n        }\n\n        extension TestSourceCodeContext {\n            init(_ context: XCTSourceCodeContext) {\n                self.init(\n                    callStack: context.callStack.map { .init($0) },\n                    location: context.location.map { .init($0) }\n                )\n            }\n        }\n\n        extension TestSourceCodeFrame {\n            init(_ frame: XCTSourceCodeFrame) {\n                self.init(\n                    address: frame.address,\n                    symbolInfo: (try? frame.symbolInfo()).map { .init($0) },\n                    symbolicationError: frame.symbolicationError.map { .init($0) }\n                )\n            }\n        }\n\n        extension TestSourceCodeSymbolInfo {\n            init(_ symbolInfo: XCTSourceCodeSymbolInfo) {\n                self.init(\n                    imageName: symbolInfo.imageName,\n                    symbolName: symbolInfo.symbolName,\n                    location: symbolInfo.location.map { .init($0) }\n                )\n            }\n        }\n        #endif\n\n        extension TestSuiteRecord {\n            init(_ testSuite: XCTestSuite) {\n                self.init(name: testSuite.name)\n            }\n        }\n        \"\"\"\n    return content\n}\n"
  },
  {
    "path": "Sources/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_compile_definitions(USE_IMPL_ONLY_IMPORTS)\n\nadd_subdirectory(_AsyncFileSystem)\nadd_subdirectory(Basics)\nadd_subdirectory(BinarySymbols)\nadd_subdirectory(Build)\nadd_subdirectory(Commands)\nadd_subdirectory(CoreCommands)\nadd_subdirectory(DriverSupport)\nadd_subdirectory(LLBuildManifest)\nadd_subdirectory(PackageCollections)\nadd_subdirectory(PackageCollectionsModel)\nadd_subdirectory(PackageCollectionsSigning)\nadd_subdirectory(PackageFingerprint)\nadd_subdirectory(PackageGraph)\nadd_subdirectory(PackageLoading)\nadd_subdirectory(PackageModel)\nadd_subdirectory(PackageRegistry)\nadd_subdirectory(PackageRegistryCommand)\nadd_subdirectory(PackageSigning)\nadd_subdirectory(QueryEngine)\nadd_subdirectory(SBOMModel)\nadd_subdirectory(SourceControl)\nadd_subdirectory(SourceKitLSPAPI)\nadd_subdirectory(SPMBuildCore)\nadd_subdirectory(SPMLLBuild)\nadd_subdirectory(SPMSQLite3)\nadd_subdirectory(SwiftFixIt)\nadd_subdirectory(swift-bootstrap)\nadd_subdirectory(swift-build)\nadd_subdirectory(swift-experimental-sdk)\nadd_subdirectory(swift-sdk)\nadd_subdirectory(swift-package)\nadd_subdirectory(swift-run)\nadd_subdirectory(swift-test)\nadd_subdirectory(SwiftPMBuildServer)\nadd_subdirectory(SwiftSDKCommand)\nadd_subdirectory(Workspace)\nadd_subdirectory(XCBuildSupport)\nadd_subdirectory(SwiftBuildSupport)\nadd_subdirectory(tsan_utils)\n\nif(SwiftPM_ENABLE_RUNTIME)\n  add_subdirectory(Runtimes)\n  # NOTE: maintain the custom output directory for the ManifestAPI modules to\n  # allow the boostrap scripts to continue functioning as they have historically.\n  # This is unnecessary with the split runtime build, but is left here to\n  # minimize disruption.\n  set_target_properties(CompilerPluginSupport PROPERTIES\n    Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI\n    OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI\n    ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI\n    LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI\n    RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI)\n  set_target_properties(PackageDescription PROPERTIES\n    Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI\n    OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI\n    ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI\n    LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI\n    RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/ManifestAPI)\n  set_target_properties(PackagePlugin PROPERTIES\n    Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/pm/PluginAPI\n    OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/PluginAPI\n    ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/PluginAPI\n    LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/PluginAPI\n    RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/pm/PluginAPI)\nendif()\n"
  },
  {
    "path": "Sources/Commands/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(Commands\n  PackageCommands/AddDependency.swift\n  PackageCommands/AddProduct.swift\n  PackageCommands/AddTarget.swift\n  PackageCommands/AddTargetDependency.swift\n  PackageCommands/AddSetting.swift\n  PackageCommands/APIDiff.swift\n  PackageCommands/ArchiveSource.swift\n  PackageCommands/AuditBinaryArtifact.swift\n  PackageCommands/BuildServer.swift\n  PackageCommands/CompletionCommand.swift\n  PackageCommands/ComputeChecksum.swift\n  PackageCommands/Config.swift\n  PackageCommands/Describe.swift\n  PackageCommands/DumpCommands.swift\n  PackageCommands/EditCommands.swift\n  PackageCommands/Format.swift\n  PackageCommands/GenerateSBOM.swift\n  PackageCommands/Init.swift\n  PackageCommands/Install.swift\n  PackageCommands/Learn.swift\n  PackageCommands/Migrate.swift\n  PackageCommands/PluginCommand.swift\n  PackageCommands/ResetCommands.swift\n  PackageCommands/Resolve.swift\n  PackageCommands/ShowDependencies.swift\n  PackageCommands/ShowExecutables.swift\n  PackageCommands/ShowTraits.swift\n  PackageCommands/SwiftPackageCommand.swift\n  PackageCommands/ToolsVersionCommand.swift\n  PackageCommands/Update.swift\n  Snippets/CardEvent.swift\n  Snippets/Cards/SnippetCard.swift\n  Snippets/Cards/SnippetGroupCard.swift\n  Snippets/Cards/TopCard.swift\n  Snippets/CardStack.swift\n  Snippets/Card.swift\n  Snippets/Colorful.swift\n  SwiftBuildCommand.swift\n  SwiftRunCommand.swift\n  SwiftTestCommand.swift\n  CommandWorkspaceDelegate.swift\n  Utilities/APIDigester.swift\n  Utilities/DependenciesSerializer.swift\n  Utilities/DescribedPackage.swift\n  Utilities/DOTManifestSerializer.swift\n  Utilities/MermaidPackageSerializer.swift\n  Utilities/MultiRootSupport.swift\n  Utilities/PlainTextEncoder.swift\n  Utilities/PluginDelegate.swift\n  Utilities/RefactoringSupport.swift\n  Utilities/SymbolGraphExtract.swift\n  Utilities/TestingSupport.swift\n  Utilities/XCTEvents.swift)\ntarget_link_libraries(Commands PUBLIC\n  SwiftCollections::OrderedCollections\n  SwiftSyntax::SwiftRefactor\n  SwiftSystem::SystemPackage\n  ArgumentParser\n  Basics\n  BinarySymbols\n  Build\n  CoreCommands\n  LLBuildManifest\n  PackageGraph\n  SBOMModel\n  SourceControl\n  SPMBuildCore\n  SwiftBuildSupport\n  SwiftFixIt\n  SwiftPMBuildServer\n  TSCBasic\n  TSCUtility\n  Workspace\n  XCBuildSupport\n  SwiftBuild::SwiftBuild\n  SwiftToolsProtocols::BuildServerProtocol\n  SwiftToolsProtocols::LanguageServerProtocol\n  SwiftToolsProtocols::LanguageServerProtocolTransport)\ntarget_link_libraries(Commands PRIVATE\n  DriverSupport\n  $<$<NOT:$<PLATFORM_ID:Darwin>>:FoundationXML>)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(Commands PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS Commands\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/Commands/CommandWorkspaceDelegate.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport CoreCommands\nimport Dispatch\nimport class Foundation.NSLock\nimport struct Foundation.URL\nimport OrderedCollections\nimport PackageGraph\nimport PackageModel\nimport SPMBuildCore\nimport Workspace\n\nimport protocol TSCBasic.OutputByteStream\nimport struct TSCUtility.Version\n\nfinal class CommandWorkspaceDelegate: WorkspaceDelegate {\n    private struct DownloadProgress {\n        let bytesDownloaded: Int64\n        let totalBytesToDownload: Int64\n    }\n\n    private struct FetchProgress {\n        let progress: Int64\n        let total: Int64\n    }\n\n    /// The progress of binary downloads.\n    private var binaryDownloadProgress = OrderedCollections.OrderedDictionary<String, DownloadProgress>()\n    private let binaryDownloadProgressLock = NSLock()\n\n    /// The progress of package  fetch operations.\n    private var fetchProgress = OrderedCollections.OrderedDictionary<PackageIdentity, FetchProgress>()\n    private let fetchProgressLock = NSLock()\n\n    private let observabilityScope: ObservabilityScope\n\n    private let outputHandler: (String, OutputCondition) -> Void\n    private let progressHandler: (Int64, Int64, String?) -> Void\n    private let inputHandler: (String, (String?) -> Void) -> Void\n\n    init(\n        observabilityScope: ObservabilityScope,\n        outputHandler: @escaping (String, OutputCondition) -> Void,\n        progressHandler: @escaping (Int64, Int64, String?) -> Void,\n        inputHandler: @escaping (String, (String?) -> Void) -> Void\n    ) {\n        self.observabilityScope = observabilityScope\n        self.outputHandler = outputHandler\n        self.progressHandler = progressHandler\n        self.inputHandler = inputHandler\n    }\n\n    func willFetchPackage(package: PackageIdentity, packageLocation: String?, fetchDetails: PackageFetchDetails) {\n        self.outputHandler(\"Fetching \\(packageLocation ?? package.description)\\(fetchDetails.fromCache ? \" from cache\" : \"\")\", .always)\n    }\n\n    func didFetchPackage(package: PackageIdentity, packageLocation: String?, result: Result<PackageFetchDetails, Error>, duration: DispatchTimeInterval) {\n        guard case .success = result, !self.observabilityScope.errorsReported else {\n            return\n        }\n\n        self.fetchProgressLock.withLock {\n            let progress = self.fetchProgress.values.reduce(0) { $0 + $1.progress }\n            let total = self.fetchProgress.values.reduce(0) { $0 + $1.total }\n\n            if progress == total && !self.fetchProgress.isEmpty {\n                self.fetchProgress.removeAll()\n            } else {\n                self.fetchProgress[package] = nil\n            }\n        }\n\n        self.outputHandler(\"Fetched \\(packageLocation ?? package.description) from cache (\\(duration.descriptionInSeconds))\", .always)\n    }\n\n    func fetchingPackage(package: PackageIdentity, packageLocation: String?, progress: Int64, total: Int64?) {\n        let (step, total, packages) = self.fetchProgressLock.withLock { () -> (Int64, Int64, String) in\n            self.fetchProgress[package] = FetchProgress(\n                progress: progress,\n                total: total ?? progress\n            )\n\n            let progress = self.fetchProgress.values.reduce(0) { $0 + $1.progress }\n            let total = self.fetchProgress.values.reduce(0) { $0 + $1.total }\n            let packages = self.fetchProgress.keys.map { $0.description }.joined(separator: \", \")\n            return (progress, total, packages)\n        }\n        self.progressHandler(step, total, \"Fetching \\(packages)\")\n    }\n\n    func willUpdateRepository(package: PackageIdentity, repository url: String) {\n        self.outputHandler(\"Updating \\(url)\", .always)\n    }\n\n    func didUpdateRepository(package: PackageIdentity, repository url: String, duration: DispatchTimeInterval) {\n        self.outputHandler(\"Updated \\(url) (\\(duration.descriptionInSeconds))\", .always)\n    }\n\n    func dependenciesUpToDate() {\n        self.outputHandler(\"Everything is already up-to-date\", .always)\n    }\n\n    func willCreateWorkingCopy(package: PackageIdentity, repository url: String, at path: AbsolutePath) {\n        self.outputHandler(\"Creating working copy for \\(url)\", .always)\n    }\n\n    func didCheckOut(package: PackageIdentity, repository url: String, revision: String, at path: AbsolutePath, duration: DispatchTimeInterval) {\n        self.outputHandler(\"Working copy of \\(url) resolved at \\(revision)\", .always)\n    }\n\n    func removing(package: PackageIdentity, packageLocation: String?) {\n        self.outputHandler(\"Removing \\(packageLocation ?? package.description)\", .always)\n    }\n\n    func willResolveDependencies(reason: WorkspaceResolveReason) {\n        self.outputHandler(Workspace.format(workspaceResolveReason: reason), .onlyWhenVerbose)\n    }\n\n    func willComputeVersion(package: PackageIdentity, location: String) {\n        self.outputHandler(\"Computing version for \\(location)\", .always)\n    }\n\n    func didComputeVersion(package: PackageIdentity, location: String, version: String, duration: DispatchTimeInterval) {\n        self.outputHandler(\"Computed \\(location) at \\(version) (\\(duration.descriptionInSeconds))\", .always)\n    }\n\n    func willDownloadBinaryArtifact(from url: String, fromCache: Bool) {\n        if fromCache {\n            self.outputHandler(\"Fetching binary artifact \\(url) from cache\", .always)\n        } else {\n            self.outputHandler(\"Downloading binary artifact \\(url)\", .always)\n        }\n    }\n\n    func didDownloadBinaryArtifact(from url: String, result: Result<(path: AbsolutePath, fromCache: Bool), Error>, duration: DispatchTimeInterval) {\n        guard case .success(let fetchDetails) = result, !self.observabilityScope.errorsReported else {\n            return\n        }\n\n        self.binaryDownloadProgressLock.withLock {\n            let progress = self.binaryDownloadProgress.values.reduce(0) { $0 + $1.bytesDownloaded }\n            let total = self.binaryDownloadProgress.values.reduce(0) { $0 + $1.totalBytesToDownload }\n\n            if progress == total && !self.binaryDownloadProgress.isEmpty {\n                self.binaryDownloadProgress.removeAll()\n            } else {\n                self.binaryDownloadProgress[url] = nil\n            }\n        }\n\n        if fetchDetails.fromCache {\n            self.outputHandler(\"Fetched \\(url) from cache (\\(duration.descriptionInSeconds))\", .always)\n        } else {\n            self.outputHandler(\"Downloaded \\(url) (\\(duration.descriptionInSeconds))\", .always)\n        }\n    }\n\n    func downloadingBinaryArtifact(from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?) {\n        let (step, total, artifacts) = self.binaryDownloadProgressLock.withLock { () -> (Int64, Int64, String) in\n            self.binaryDownloadProgress[url] = DownloadProgress(\n                bytesDownloaded: bytesDownloaded,\n                totalBytesToDownload: totalBytesToDownload ?? bytesDownloaded\n            )\n\n            let step = self.binaryDownloadProgress.values.reduce(0, { $0 + $1.bytesDownloaded })\n            let total = self.binaryDownloadProgress.values.reduce(0, { $0 + $1.totalBytesToDownload })\n            let artifacts = self.binaryDownloadProgress.keys.joined(separator: \", \")\n            return (step, total, artifacts)\n        }\n\n        self.progressHandler(step, total, \"Downloading \\(artifacts)\")\n    }\n\n    /// The workspace has started downloading a binary artifact.\n    func willDownloadPrebuilt(package: PackageIdentity, from url: String, fromCache: Bool) {\n        if fromCache {\n            self.outputHandler(\"Fetching package prebuilt \\(url) from cache\", .always)\n        } else {\n            self.outputHandler(\"Downloading package prebuilt \\(url)\", .always)\n        }\n    }\n\n    /// The workspace has finished downloading a binary artifact.\n    func didDownloadPrebuilt(\n        package: PackageIdentity,\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    ) {\n        guard case .success(let fetchDetails) = result, !self.observabilityScope.errorsReported else {\n            return\n        }\n\n        if fetchDetails.fromCache {\n            self.outputHandler(\"Fetched \\(url) from cache (\\(duration.descriptionInSeconds))\", .always)\n        } else {\n            self.outputHandler(\"Downloaded \\(url) (\\(duration.descriptionInSeconds))\", .always)\n        }\n    }\n\n    /// The workspace is downloading a binary artifact.\n    func downloadingPrebuilt(package: PackageIdentity, from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?) {\n\n    }\n\n    /// The workspace finished downloading all binary artifacts.\n    func didDownloadAllPrebuilts() {\n\n    }\n\n    // registry signature handlers\n\n    func onUnsignedRegistryPackage(registryURL: URL, package: PackageModel.PackageIdentity, version: TSCUtility.Version, completion: (Bool) -> Void) {\n        self.inputHandler(\"\\(package) \\(version) from \\(registryURL) is unsigned. okay to proceed? (yes/no) \") { response in\n            switch response?.lowercased() {\n            case \"yes\":\n                completion(true) // continue\n            case \"no\":\n                completion(false) // stop resolution\n            default:\n                self.outputHandler(\"invalid response: '\\(response ?? \"\")'\", .always)\n                completion(false)\n            }\n        }\n    }\n\n    func onUntrustedRegistryPackage(registryURL: URL, package: PackageModel.PackageIdentity, version: TSCUtility.Version, completion: (Bool) -> Void) {\n        self.inputHandler(\"\\(package) \\(version) from \\(registryURL) is signed with an untrusted certificate. okay to proceed? (yes/no) \") { response in\n            switch response?.lowercased() {\n            case \"yes\":\n                completion(true) // continue\n            case \"no\":\n                completion(false) // stop resolution\n            default:\n                self.outputHandler(\"invalid response: '\\(response ?? \"\")'\", .always)\n                completion(false)\n            }\n        }\n    }\n\n    public func willUpdateDependencies() {\n        self.observabilityScope.emit(debug: \"Updating dependencies\")\n        os_signpost(.begin, name: SignpostName.updatingDependencies)\n    }\n\n    public func didUpdateDependencies(duration: DispatchTimeInterval) {\n        self.observabilityScope.emit(debug: \"Dependencies updated in (\\(duration.descriptionInSeconds))\")\n        os_signpost(.end, name: SignpostName.updatingDependencies)\n    }\n\n    public func willResolveDependencies() {\n        self.observabilityScope.emit(debug: \"Resolving dependencies\")\n        os_signpost(.begin, name: SignpostName.resolvingDependencies)\n    }\n\n    public func didResolveDependencies(duration: DispatchTimeInterval) {\n        self.observabilityScope.emit(debug: \"Dependencies resolved in (\\(duration.descriptionInSeconds))\")\n        os_signpost(.end, name: SignpostName.resolvingDependencies)\n    }\n\n    func willLoadGraph() {\n        self.observabilityScope.emit(debug: \"Loading and validating graph\")\n        os_signpost(.begin, name: SignpostName.loadingGraph)\n    }\n\n    func didLoadGraph(duration: DispatchTimeInterval) {\n        self.observabilityScope.emit(debug: \"Graph loaded in (\\(duration.descriptionInSeconds))\")\n        os_signpost(.end, name: SignpostName.loadingGraph)\n    }\n\n    func didCompileManifest(packageIdentity: PackageIdentity, packageLocation: String, duration: DispatchTimeInterval) {\n        self.observabilityScope.emit(debug: \"Compiled manifest for '\\(packageIdentity)' (from '\\(packageLocation)') in \\(duration.descriptionInSeconds)\")\n    }\n\n    func didEvaluateManifest(packageIdentity: PackageIdentity, packageLocation: String, duration: DispatchTimeInterval) {\n        self.observabilityScope.emit(debug: \"Evaluated manifest for '\\(packageIdentity)' (from '\\(packageLocation)') in \\(duration.descriptionInSeconds)\")\n    }\n\n    func didLoadManifest(packageIdentity: PackageIdentity, packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind, manifest: Manifest?, diagnostics: [Basics.Diagnostic], duration: DispatchTimeInterval) {\n        self.observabilityScope.emit(debug: \"Loaded manifest for '\\(packageIdentity)' (from '\\(url)') in \\(duration.descriptionInSeconds)\")\n    }\n\n    // noop\n    func willCheckOut(package: PackageIdentity, repository url: String, revision: String, at path: AbsolutePath) {}\n    func didCreateWorkingCopy(package: PackageIdentity, repository url: String, at path: AbsolutePath, duration: DispatchTimeInterval) {}\n    func resolvedFileChanged() {}\n    func didDownloadAllBinaryArtifacts() {}\n    func willCompileManifest(packageIdentity: PackageIdentity, packageLocation: String) {}\n    func willEvaluateManifest(packageIdentity: PackageIdentity, packageLocation: String) {}\n    func willLoadManifest(packageIdentity: PackageIdentity, packagePath: AbsolutePath, url: String, version: Version?, packageKind: PackageReference.Kind) {}\n}\n\npublic extension _SwiftCommand {\n    var workspaceDelegateProvider: WorkspaceDelegateProvider {\n        return {\n            CommandWorkspaceDelegate(\n                observabilityScope: $0,\n                outputHandler: $1,\n                progressHandler: $2,\n                inputHandler: $3\n            )\n        }\n    }\n\n    var workspaceLoaderProvider: WorkspaceLoaderProvider {\n        return {\n            XcodeWorkspaceLoader(fileSystem: $0, observabilityScope: $1)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/APIDiff.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Dispatch\nimport PackageGraph\nimport PackageModel\nimport SourceControl\nimport SPMBuildCore\nimport TSCBasic\nimport TSCUtility\nimport _Concurrency\nimport Workspace\n\nstruct DeprecatedAPIDiff: ParsableCommand {\n    static let configuration = CommandConfiguration(commandName: \"experimental-api-diff\",\n                                                    abstract: \"Deprecated - use `swift package diagnose-api-breaking-changes` instead\",\n                                                    shouldDisplay: false,\n                                                    helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)])\n\n    @Argument(parsing: .captureForPassthrough)\n    var args: [String] = []\n\n    func run() throws {\n        print(\"`swift package experimental-api-diff` has been renamed to `swift package diagnose-api-breaking-changes`\")\n        throw ExitCode.failure\n    }\n}\n\nstruct APIDiff: AsyncSwiftCommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"diagnose-api-breaking-changes\",\n        abstract: \"Diagnose API-breaking changes to Swift modules in a package.\",\n        discussion: \"\"\"\n        The diagnose-api-breaking-changes command can be used to compare the Swift API of \\\n        a package to a baseline revision, diagnosing any breaking changes which have \\\n        been introduced. By default, it compares every Swift module from the baseline \\\n        revision which is part of a library product. For packages with many targets, this \\\n        behavior may be undesirable as the comparison can be slow. \\\n        The `--products` and `--targets` options may be used to restrict the scope of \\\n        the comparison.\n        \"\"\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    @Option(help: \"\"\"\n    The path to a text file containing breaking changes which should be ignored by the API comparison. \\\n    Each ignored breaking change in the file should appear on its own line and contain the exact message \\\n    to be ignored (for example, 'API breakage: func foo() has been removed').\n    \"\"\")\n    var breakageAllowlistPath: Basics.AbsolutePath?\n\n    @Argument(help: \"The baseline treeish to compare to (for example, a commit hash, branch name, tag, and so on).\")\n    var treeish: String\n\n    @Option(parsing: .upToNextOption,\n            help: \"One or more products to include in the API comparison. If present, only the specified products (and any targets specified using `--targets`) will be compared.\")\n    var products: [String] = []\n\n    @Option(parsing: .upToNextOption,\n            help: \"One or more targets to include in the API comparison. If present, only the specified targets (and any products specified using `--products`) will be compared.\")\n    var targets: [String] = []\n\n    @Option(name: .customLong(\"baseline-dir\"),\n            help: \"The path to a directory used to store API baseline files. If unspecified, a temporary directory will be used.\")\n    var overrideBaselineDir: Basics.AbsolutePath?\n\n    @Flag(help: \"Regenerate the API baseline, even if an existing one is available.\")\n    var regenerateBaseline: Bool = false\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        let packageRoot = try globalOptions.locations.packageDirectory ?? swiftCommandState.getPackageRoot()\n        let repository = GitRepository(path: packageRoot)\n        let baselineRevision = try repository.resolveRevision(identifier: treeish)\n\n        let baselineDir = try overrideBaselineDir?.appending(component: baselineRevision.identifier) ?? swiftCommandState.productsBuildParameters.apiDiff.appending(component: \"\\(baselineRevision.identifier)-baselines\")\n        let packageGraph = try await swiftCommandState.loadPackageGraph()\n        let modulesToDiff = try Self.determineModulesToDiff(\n            packageGraph: packageGraph,\n            productNames: products,\n            targetNames: targets,\n            observabilityScope: swiftCommandState.observabilityScope,\n            diagnoseMissingNames: true,\n        )\n\n        if swiftCommandState.options.build.buildSystem == .swiftbuild {\n            try await runWithIntegratedAPIDigesterSupport(\n                swiftCommandState,\n                baselineRevision: baselineRevision,\n                baselineDir: baselineDir,\n                modulesToDiff: modulesToDiff\n            )\n        } else {\n            let buildSystem = try await swiftCommandState.createBuildSystem(\n                cacheBuildManifest: false,\n            )\n            try await runWithSwiftPMCoordinatedDiffing(\n                swiftCommandState,\n                buildSystem: buildSystem,\n                baselineRevision: baselineRevision,\n                modulesToDiff: modulesToDiff\n            )\n        }\n    }\n\n    private func runWithSwiftPMCoordinatedDiffing(_ swiftCommandState: SwiftCommandState, buildSystem: any BuildSystem, baselineRevision: Revision, modulesToDiff: Set<String>) async throws {\n        let apiDigesterPath = try swiftCommandState.getTargetToolchain().getSwiftAPIDigester()\n        let apiDigesterTool = SwiftAPIDigester(fileSystem: swiftCommandState.fileSystem, tool: apiDigesterPath)\n\n        // Build the current package.\n        let buildResult = try await buildSystem.build(subset: .allExcludingTests, buildOutputs: [.buildPlan])\n        guard let buildPlan = buildResult.buildPlan else {\n            throw ExitCode.failure\n        }\n\n        // Dump JSON for the baseline package.\n        let baselineDumper = try APIDigesterBaselineDumper(\n            baselineRevision: baselineRevision,\n            packageRoot: swiftCommandState.getPackageRoot(),\n            productsBuildParameters: buildPlan.destinationBuildParameters,\n            toolsBuildParameters: buildPlan.toolsBuildParameters,\n            apiDigesterTool: apiDigesterTool,\n            observabilityScope: swiftCommandState.observabilityScope\n        )\n\n        let baselineDir = try await baselineDumper.emitAPIBaseline(\n            for: modulesToDiff,\n            at: overrideBaselineDir,\n            force: regenerateBaseline,\n            logLevel: swiftCommandState.logLevel,\n                    swiftCommandState: swiftCommandState\n        )\n\n        var skippedModules: Set<String> = []\n\n        let results = await withTaskGroup(of: SwiftAPIDigester.ComparisonResult?.self, returning: [SwiftAPIDigester.ComparisonResult].self) { taskGroup in\n\n            for module in modulesToDiff {\n                let moduleBaselinePath = baselineDir.appending(\"\\(module).json\")\n                guard swiftCommandState.fileSystem.exists(moduleBaselinePath) else {\n                    print(\"\\nSkipping \\(module) because it does not exist in the baseline\")\n                    skippedModules.insert(module)\n                    continue\n                }\n                taskGroup.addTask {\n                    do {\n                        if let comparisonResult = try apiDigesterTool.compareAPIToBaseline(\n                            at: moduleBaselinePath,\n                            for: module,\n                            buildPlan: buildPlan,\n                            except: breakageAllowlistPath\n                        ) {\n                            return comparisonResult\n                        }\n                    } catch {\n                        swiftCommandState.observabilityScope.emit(error: \"failed to compare API to baseline\", underlyingError: error)\n                    }\n                    return nil\n                }\n            }\n            var results = [SwiftAPIDigester.ComparisonResult]()\n            for await result in taskGroup {\n                guard let result else { continue }\n                results.append(result)\n            }\n            return results\n        }\n\n        let failedModules = modulesToDiff\n            .subtracting(skippedModules)\n            .subtracting(results.map(\\.moduleName))\n        for failedModule in failedModules {\n            swiftCommandState.observabilityScope.emit(error: \"failed to read API digester output for \\(failedModule)\")\n        }\n\n        for result in results {\n            try self.printComparisonResult(result, observabilityScope: swiftCommandState.observabilityScope)\n        }\n\n        guard failedModules.isEmpty && results.allSatisfy(\\.hasNoAPIBreakingChanges) else {\n            throw ExitCode.failure\n        }\n    }\n\n    private func runWithIntegratedAPIDigesterSupport(_ swiftCommandState: SwiftCommandState, baselineRevision: Revision, baselineDir: Basics.AbsolutePath, modulesToDiff: Set<String>) async throws {\n        // Build the baseline revision to generate baseline files.\n        let modulesWithBaselines = try await generateAPIBaselineUsingIntegratedAPIDigesterSupport(swiftCommandState, baselineRevision: baselineRevision, baselineDir: baselineDir, modulesNeedingBaselines: modulesToDiff)\n\n        // Build the package and run a comparison agains the baselines.\n        var productsBuildParameters = try swiftCommandState.productsBuildParameters\n        productsBuildParameters.apiDigesterMode = .compareToBaselines(\n            baselinesDirectory: baselineDir,\n            modulesToCompare: modulesWithBaselines,\n            breakageAllowListPath: breakageAllowlistPath\n        )\n        let delegate = DiagnosticsCapturingBuildSystemDelegate()\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            cacheBuildManifest: false,\n            productsBuildParameters: productsBuildParameters,\n            delegate: delegate\n        )\n        try await buildSystem.build()\n\n        // Report the results of the comparison.\n        var comparisonResults: [SwiftAPIDigester.ComparisonResult] = []\n        for (targetName, diagnosticPaths) in delegate.serializedDiagnosticsPathsByTarget {\n            guard let targetName, !diagnosticPaths.isEmpty else {\n                continue\n            }\n            var apiBreakingChanges: [SerializedDiagnostics.Diagnostic] = []\n            var otherDiagnostics: [SerializedDiagnostics.Diagnostic] = []\n            for path in diagnosticPaths {\n                let contents = try swiftCommandState.fileSystem.readFileContents(path)\n                guard contents.count > 0 else {\n                    continue\n                }\n                let serializedDiagnostics = try SerializedDiagnostics(bytes: contents)\n                let apiDigesterCategory = \"api-digester-breaking-change\"\n                apiBreakingChanges.append(contentsOf: serializedDiagnostics.diagnostics.filter { $0.category == apiDigesterCategory })\n                otherDiagnostics.append(contentsOf: serializedDiagnostics.diagnostics.filter { $0.category != apiDigesterCategory })\n            }\n            let result = SwiftAPIDigester.ComparisonResult(\n                moduleName: targetName,\n                apiBreakingChanges: apiBreakingChanges,\n                otherDiagnostics: otherDiagnostics\n            )\n            comparisonResults.append(result)\n        }\n\n        var detectedBreakingChange = false\n        for result in comparisonResults.sorted(by: { $0.moduleName < $1.moduleName }) {\n            if result.hasNoAPIBreakingChanges && !modulesToDiff.contains(result.moduleName) {\n                continue\n            }\n            try printComparisonResult(result, observabilityScope: swiftCommandState.observabilityScope)\n            detectedBreakingChange = detectedBreakingChange || !result.hasNoAPIBreakingChanges\n        }\n\n        for module in modulesToDiff.subtracting(modulesWithBaselines) {\n            print(\"\\nSkipping \\(module) because it does not exist in the baseline\")\n        }\n\n        if detectedBreakingChange {\n            throw ExitCode(1)\n        }\n    }\n\n    private func generateAPIBaselineUsingIntegratedAPIDigesterSupport(_ swiftCommandState: SwiftCommandState, baselineRevision: Revision, baselineDir: Basics.AbsolutePath, modulesNeedingBaselines: Set<String>) async throws -> Set<String> {\n        // Setup a temporary directory where we can checkout and build the baseline treeish.\n        let baselinePackageRoot = try swiftCommandState.productsBuildParameters.apiDiff.appending(\"\\(baselineRevision.identifier)-checkout\")\n        if swiftCommandState.fileSystem.exists(baselinePackageRoot) {\n            try swiftCommandState.fileSystem.removeFileTree(baselinePackageRoot)\n        }\n        if regenerateBaseline && swiftCommandState.fileSystem.exists(baselineDir) {\n            try swiftCommandState.fileSystem.removeFileTree(baselineDir)\n        }\n\n        // Clone the current package in a sandbox and checkout the baseline revision.\n        let repositoryProvider = GitRepositoryProvider()\n        let specifier = RepositorySpecifier(path: baselinePackageRoot)\n        let workingCopy = try await repositoryProvider.createWorkingCopy(\n            repository: specifier,\n            sourcePath: swiftCommandState.getPackageRoot(),\n            at: baselinePackageRoot,\n            editable: false\n        )\n\n        try workingCopy.checkout(revision: baselineRevision)\n\n        // Create the workspace for this package.\n        let workspace = try Workspace(\n            forRootPackage: baselinePackageRoot,\n            cancellator: swiftCommandState.cancellator\n        )\n\n        let graph = try await workspace.loadPackageGraph(\n            rootPath: baselinePackageRoot,\n            observabilityScope: swiftCommandState.observabilityScope\n        )\n\n        let baselineModules = try Self.determineModulesToDiff(\n            packageGraph: graph,\n            productNames: products,\n            targetNames: targets,\n            observabilityScope: swiftCommandState.observabilityScope,\n            diagnoseMissingNames: false\n        )\n\n        // Don't emit a baseline for a module that didn't exist yet in this revision.\n        var modulesNeedingBaselines = modulesNeedingBaselines\n        modulesNeedingBaselines.formIntersection(graph.apiDigesterModules)\n\n        // Abort if we weren't able to load the package graph.\n        if swiftCommandState.observabilityScope.errorsReported {\n            throw Diagnostics.fatalError\n        }\n\n        // Update the data path input build parameters so it's built in the sandbox.\n        var productsBuildParameters = try swiftCommandState.productsBuildParameters\n        productsBuildParameters.dataPath = workspace.location.scratchDirectory\n        productsBuildParameters.apiDigesterMode = .generateBaselines(baselinesDirectory: baselineDir, modulesRequestingBaselines: modulesNeedingBaselines)\n\n        // Build the baseline module.\n        // FIXME: We need to implement the build tool invocation closure here so that build tool plugins work with the APIDigester. rdar://86112934\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            cacheBuildManifest: false,\n            productsBuildParameters: productsBuildParameters,\n            packageGraphLoader: { graph }\n        )\n        try await buildSystem.build()\n        return baselineModules\n    }\n\n    private static func determineModulesToDiff(packageGraph: ModulesGraph, productNames: [String], targetNames: [String], observabilityScope: ObservabilityScope, diagnoseMissingNames: Bool) throws -> Set<String> {\n        var modulesToDiff: Set<String> = []\n        if productNames.isEmpty && targetNames.isEmpty {\n            modulesToDiff.formUnion(packageGraph.apiDigesterModules)\n        } else {\n            for productName in productNames {\n                guard let product = packageGraph\n                        .rootPackages\n                        .flatMap(\\.products)\n                        .first(where: { $0.name == productName }) else {\n                    if diagnoseMissingNames {\n                        observabilityScope.emit(error: \"no such product '\\(productName)'\")\n                    }\n                    continue\n                }\n                guard product.type.isLibrary else {\n                    if diagnoseMissingNames {\n                        observabilityScope.emit(error: \"'\\(productName)' is not a library product\")\n                    }\n                    continue\n                }\n                modulesToDiff.formUnion(product.modules.filter { $0.underlying is SwiftModule }.map(\\.c99name))\n            }\n            for targetName in targetNames {\n                guard let target = packageGraph\n                        .rootPackages\n                        .flatMap(\\.modules)\n                        .first(where: { $0.name == targetName }) else {\n                    if diagnoseMissingNames {\n                        observabilityScope.emit(error: \"no such target '\\(targetName)'\")\n                    }\n                    continue\n                }\n                guard target.type == .library else {\n                    if diagnoseMissingNames {\n                        observabilityScope.emit(error: \"'\\(targetName)' is not a library target\")\n                    }\n                    continue\n                }\n                guard target.underlying is SwiftModule else {\n                    if diagnoseMissingNames {\n                        observabilityScope.emit(error: \"'\\(targetName)' is not a Swift language target\")\n                    }\n                    continue\n                }\n                modulesToDiff.insert(target.c99name)\n            }\n            guard !observabilityScope.errorsReported else {\n                throw ExitCode.failure\n            }\n        }\n        return modulesToDiff\n    }\n\n    private func printComparisonResult(\n        _ comparisonResult: SwiftAPIDigester.ComparisonResult,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        for diagnostic in comparisonResult.otherDiagnostics {\n            let metadata = try diagnostic.location.map { location -> ObservabilityMetadata in\n                var metadata = ObservabilityMetadata()\n                metadata.fileLocation = .init(\n                    try .init(validating: location.filename),\n                    line: location.line < Int.max ? Int(location.line) : .none\n                )\n                return metadata\n            }\n\n            switch diagnostic.level {\n            case .error, .fatal:\n                observabilityScope.emit(error: diagnostic.text, metadata: metadata)\n            case .warning:\n                observabilityScope.emit(warning: diagnostic.text, metadata: metadata)\n            case .note:\n                observabilityScope.emit(info: diagnostic.text, metadata: metadata)\n            case .remark:\n                observabilityScope.emit(info: diagnostic.text, metadata: metadata)\n            case .ignored:\n                break\n            }\n        }\n\n        let moduleName = comparisonResult.moduleName\n        if comparisonResult.apiBreakingChanges.isEmpty {\n            print(\"\\nNo breaking changes detected in \\(moduleName)\")\n        } else {\n            let count = comparisonResult.apiBreakingChanges.count\n            print(\"\\n\\(count) breaking \\(count > 1 ? \"changes\" : \"change\") detected in \\(moduleName):\")\n            for change in comparisonResult.apiBreakingChanges {\n                print(\"  💔 \\(change.text)\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/AddDependency.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport SwiftParser\n@_spi(PackageRefactor) import SwiftRefactor\nimport SwiftSyntax\nimport TSCBasic\nimport TSCUtility\nimport Workspace\n\nimport class PackageModel.Manifest\n\nextension SwiftPackageCommand {\n    struct AddDependency: SwiftCommand {\n        package static let configuration = CommandConfiguration(\n            abstract: \"Add a package dependency to the manifest.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @Argument(help: \"The URL or directory of the package to add.\")\n        var dependency: String\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Option(help: \"The exact package version to depend on.\")\n        var exact: Version?\n\n        @Option(help: \"The specific package revision to depend on.\")\n        var revision: String?\n\n        @Option(help: \"The branch of the package to depend on.\")\n        var branch: String?\n\n        @Option(help: \"The package version to depend on (up to the next major version).\")\n        var from: Version?\n\n        @Option(help: \"The package version to depend on (up to the next minor version).\")\n        var upToNextMinorFrom: Version?\n\n        @Option(help: \"Specify upper bound on the package version range (exclusive).\")\n        var to: Version?\n\n        @Option(help: \"Specify dependency type.\")\n        var type: DependencyType = .url\n\n        enum DependencyType: String, Codable, CaseIterable, ExpressibleByArgument {\n            case url\n            case path\n            case registry\n        }\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            let workspace = try swiftCommandState.getActiveWorkspace()\n            guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else {\n                throw StringError(\"unknown package\")\n            }\n\n            switch self.type {\n            case .url:\n                try self.createSourceControlPackage(\n                    packagePath: packagePath,\n                    workspace: workspace,\n                    url: self.dependency\n                )\n            case .path:\n                try self.createFileSystemPackage(\n                    packagePath: packagePath,\n                    workspace: workspace,\n                    directory: self.dependency\n                )\n            case .registry:\n                try self.createRegistryPackage(\n                    packagePath: packagePath,\n                    workspace: workspace,\n                    id: self.dependency\n                )\n            }\n        }\n\n        private func createSourceControlPackage(\n            packagePath: Basics.AbsolutePath,\n            workspace: Workspace,\n            url: String\n        ) throws {\n            // Collect all of the possible version requirements.\n            var requirements: [PackageDependency.SourceControl.Requirement] = []\n            if let exact {\n                requirements.append(.exact(exact.description))\n            }\n\n            if let branch {\n                requirements.append(.branch(branch))\n            }\n\n            if let revision {\n                requirements.append(.revision(revision))\n            }\n\n            if let from {\n                requirements.append(.rangeFrom(from.description))\n            }\n\n            if let upToNextMinorFrom {\n                let range: Range<Version> = .upToNextMinor(from: upToNextMinorFrom)\n                requirements.append(\n                    .range(\n                        lowerBound: range.lowerBound.description,\n                        upperBound: range.upperBound.description\n                    )\n                )\n            }\n\n            if requirements.count > 1 {\n                throw StringError(\n                    \"must specify at most one of --exact, --branch, --revision, --from, or --up-to-next-minor-from\"\n                )\n            }\n\n            guard let firstRequirement = requirements.first else {\n                throw StringError(\n                    \"must specify one of --exact, --branch, --revision, --from, or --up-to-next-minor-from\"\n                )\n            }\n\n            let requirement: PackageDependency.SourceControl.Requirement\n            switch firstRequirement {\n            case .range(let lowerBound, _), .rangeFrom(let lowerBound):\n                requirement = if let to {\n                    .range(lowerBound: lowerBound, upperBound: to.description)\n                } else {\n                    firstRequirement\n                }\n            default:\n                requirement = firstRequirement\n\n                if self.to != nil {\n                    throw StringError(\"--to can only be specified with --from or --up-to-next-minor-from\")\n                }\n            }\n\n            try self.applyEdits(\n                packagePath: packagePath,\n                workspace: workspace,\n                packageDependency: .sourceControl(.init(location: url, requirement: requirement))\n            )\n        }\n\n        private func createRegistryPackage(\n            packagePath: Basics.AbsolutePath,\n            workspace: Workspace,\n            id: String\n        ) throws {\n            // Collect all of the possible version requirements.\n            var requirements: [PackageDependency.Registry.Requirement] = []\n            if let exact {\n                requirements.append(.exact(exact.description))\n            }\n\n            if let from {\n                requirements.append(.rangeFrom(from.description))\n            }\n\n            if let upToNextMinorFrom {\n                let range: Range<Version> = .upToNextMinor(from: upToNextMinorFrom)\n                requirements.append(\n                    .range(\n                        lowerBound: range.lowerBound.description,\n                        upperBound: range.upperBound.description\n                    )\n                )\n            }\n\n            if requirements.count > 1 {\n                throw StringError(\n                    \"must specify at most one of --exact, --from, or --up-to-next-minor-from\"\n                )\n            }\n\n            guard let firstRequirement = requirements.first else {\n                throw StringError(\n                    \"must specify one of --exact, --from, or --up-to-next-minor-from\"\n                )\n            }\n\n            let requirement: PackageDependency.Registry.Requirement\n            switch firstRequirement {\n            case .range(let lowerBound, _), .rangeFrom(let lowerBound):\n                requirement = if let to {\n                    .range(lowerBound: lowerBound, upperBound: to.description)\n                } else {\n                    firstRequirement\n                }\n            default:\n                requirement = firstRequirement\n\n                if self.to != nil {\n                    throw StringError(\"--to can only be specified with --from or --up-to-next-minor-from\")\n                }\n            }\n\n            try self.applyEdits(\n                packagePath: packagePath,\n                workspace: workspace,\n                packageDependency: .registry(.init(identity: id, requirement: requirement))\n            )\n        }\n\n        private func createFileSystemPackage(\n            packagePath: Basics.AbsolutePath,\n            workspace: Workspace,\n            directory: String\n        ) throws {\n            try self.applyEdits(\n                packagePath: packagePath,\n                workspace: workspace,\n                packageDependency: .fileSystem(.init(path: directory))\n            )\n        }\n\n        private func applyEdits(\n            packagePath: Basics.AbsolutePath,\n            workspace: Workspace,\n            packageDependency: PackageDependency\n        ) throws {\n            // Load the manifest file\n            let fileSystem = workspace.fileSystem\n            let manifestPath = packagePath.appending(component: Manifest.filename)\n            let manifestContents: ByteString\n            do {\n                manifestContents = try fileSystem.readFileContents(manifestPath)\n            } catch {\n                throw StringError(\"cannot find package manifest in \\(manifestPath)\")\n            }\n\n            // Parse the manifest.\n            let manifestSyntax = manifestContents.withData { data in\n                data.withUnsafeBytes { buffer in\n                    buffer.withMemoryRebound(to: UInt8.self) { buffer in\n                        Parser.parse(source: buffer)\n                    }\n                }\n            }\n\n            let editResult = try AddPackageDependency.textRefactor(\n                syntax: manifestSyntax,\n                in: .init(dependency: packageDependency)\n            )\n\n            try editResult.applyEdits(\n                to: fileSystem,\n                manifest: manifestSyntax,\n                manifestPath: manifestPath,\n                verbose: !self.globalOptions.logging.quiet\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/AddProduct.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport SwiftParser\n@_spi(PackageRefactor) import SwiftRefactor\nimport SwiftSyntax\nimport TSCBasic\nimport TSCUtility\nimport Workspace\n\nextension SwiftPackageCommand {\n    struct AddProduct: SwiftCommand {\n        /// The package product type used for the command-line. This is a\n        /// subset of `ProductType` that expands out the library types.\n        enum CommandProductType: String, Codable, ExpressibleByArgument, CaseIterable {\n            case executable\n            case library\n            case staticLibrary = \"static-library\"\n            case dynamicLibrary = \"dynamic-library\"\n            case plugin\n        }\n\n        package static let configuration = CommandConfiguration(\n            abstract: \"Add a new product to the manifest.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Argument(help: \"The name of the new product.\")\n        var name: String\n\n        @Option(help: \"The type of target to add.\")\n        var type: CommandProductType = .library\n\n        @Option(\n            parsing: .upToNextOption,\n            help: \"A list of targets that are part of this product.\"\n        )\n        var targets: [String] = []\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            let workspace = try swiftCommandState.getActiveWorkspace()\n\n            guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else {\n                throw StringError(\"unknown package\")\n            }\n\n            // Load the manifest file\n            let fileSystem = workspace.fileSystem\n            let manifestPath = packagePath.appending(\"Package.swift\")\n            let manifestContents: ByteString\n            do {\n                manifestContents = try fileSystem.readFileContents(manifestPath)\n            } catch {\n                throw StringError(\"cannot find package manifest in \\(manifestPath)\")\n            }\n\n            // Parse the manifest.\n            let manifestSyntax = manifestContents.withData { data in\n                data.withUnsafeBytes { buffer in\n                    buffer.withMemoryRebound(to: UInt8.self) { buffer in\n                        Parser.parse(source: buffer)\n                    }\n                }\n            }\n\n            // Map the product type.\n            let type: ProductDescription.ProductType = switch self.type {\n            case .executable: .executable\n            case .library: .library(.automatic)\n            case .dynamicLibrary: .library(.dynamic)\n            case .staticLibrary: .library(.static)\n            case .plugin: .plugin\n            }\n\n            let product = ProductDescription(\n                name: name,\n                type: type,\n                targets: targets\n            )\n\n            let editResult = try SwiftRefactor.AddProduct.textRefactor(\n                syntax: manifestSyntax,\n                in: .init(product: product)\n            )\n\n            try editResult.applyEdits(\n                to: fileSystem,\n                manifest: manifestSyntax,\n                manifestPath: manifestPath,\n                verbose: !globalOptions.logging.quiet\n            )\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/AddSetting.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SwiftParser\nimport SwiftSyntax\n@_spi(PackageRefactor) import SwiftRefactor\nimport TSCBasic\nimport TSCUtility\nimport Workspace\n\nextension SwiftPackageCommand {\n    struct AddSetting: SwiftCommand {\n        /// The Swift language setting that can be specified on the command line.\n        enum SwiftSetting: String, Codable, ExpressibleByArgument, CaseIterable {\n            case experimentalFeature\n            case upcomingFeature\n            case languageMode\n            case strictMemorySafety = \"StrictMemorySafety\"\n        }\n\n        package static let configuration = CommandConfiguration(\n            abstract: \"Add a new setting to the manifest.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Option(help: \"The target to add the setting to.\")\n        var target: String\n\n        @Option(\n            name: .customLong(\"swift\"),\n            parsing: .upToNextOption,\n            help: \"The Swift language setting(s) to add. Supported settings: \\(SwiftSetting.allCases.map(\\.rawValue).joined(separator: \", \")).\"\n        )\n        var _swiftSettings: [String]\n\n        var swiftSettings: [(SwiftSetting, String)] {\n            get throws {\n                var settings: [(SwiftSetting, String)] = []\n                for rawSetting in self._swiftSettings {\n                    let (name, value) = rawSetting.spm_split(around: \"=\")\n\n                    guard let setting = SwiftSetting(rawValue: name) else {\n                        throw ValidationError(\"Unknown Swift language setting: \\(name)\")\n                    }\n\n                    settings.append((setting, value ?? \"\"))\n                }\n\n                return settings\n            }\n        }\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            if !self._swiftSettings.isEmpty {\n                try Self.editSwiftSettings(\n                    of: self.target,\n                    using: swiftCommandState,\n                    self.swiftSettings,\n                    verbose: !self.globalOptions.logging.quiet\n                )\n            }\n        }\n\n        package static func editSwiftSettings(\n            of target: String,\n            using swiftCommandState: SwiftCommandState,\n            _ settings: [(SwiftSetting, String)],\n            verbose: Bool = false\n        ) throws {\n            let workspace = try swiftCommandState.getActiveWorkspace()\n            guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else {\n                throw StringError(\"unknown package\")\n            }\n\n            try self.applyEdits(\n                packagePath: packagePath,\n                workspace: workspace,\n                target: target,\n                swiftSettings: settings\n            )\n        }\n\n        private static func applyEdits(\n            packagePath: Basics.AbsolutePath,\n            workspace: Workspace,\n            target: String,\n            swiftSettings: [(SwiftSetting, String)],\n            verbose: Bool = false\n        ) throws {\n            // Load the manifest file\n            let fileSystem = workspace.fileSystem\n            let manifestPath = packagePath.appending(component: Manifest.filename)\n\n            for (setting, value) in swiftSettings {\n                let manifestContents: ByteString\n                do {\n                    manifestContents = try fileSystem.readFileContents(manifestPath)\n                } catch {\n                    throw StringError(\"cannot find package manifest in \\(manifestPath)\")\n                }\n\n                // Parse the manifest.\n                let manifestSyntax = manifestContents.withData { data in\n                    data.withUnsafeBytes { buffer in\n                        buffer.withMemoryRebound(to: UInt8.self) { buffer in\n                            Parser.parse(source: buffer)\n                        }\n                    }\n                }\n\n                let editResult: [SourceEdit]\n\n                switch setting {\n                case .experimentalFeature:\n                    try manifestSyntax.checkManifestAtLeast(.v5_8)\n\n                    editResult = try AddSwiftSetting.experimentalFeature(\n                        to: target,\n                        name: value,\n                        manifest: manifestSyntax\n                    )\n                case .upcomingFeature:\n                    try manifestSyntax.checkManifestAtLeast(.v5_8)\n\n                    editResult = try AddSwiftSetting.upcomingFeature(\n                        to: target,\n                        name: value,\n                        manifest: manifestSyntax\n                    )\n                case .languageMode:\n                    try manifestSyntax.checkManifestAtLeast(.v6_0)\n\n                    guard let mode = SwiftLanguageVersion(string: value) else {\n                        throw ValidationError(\"Unknown Swift language mode: \\(value)\")\n                    }\n\n                    editResult = try AddSwiftSetting.languageMode(\n                        to: target,\n                        mode: mode.rawValue,\n                        manifest: manifestSyntax\n                    )\n                case .strictMemorySafety:\n                    try manifestSyntax.checkManifestAtLeast(.v6_2)\n\n                    guard value.isEmpty || value == SwiftSetting.strictMemorySafety.rawValue else {\n                        throw ValidationError(\"'strictMemorySafety' does not support argument '\\(value)'\")\n                    }\n\n                    editResult = try AddSwiftSetting.strictMemorySafety(\n                        to: target,\n                        manifest: manifestSyntax\n                    )\n                }\n\n                try editResult.applyEdits(\n                    to: fileSystem,\n                    manifest: manifestSyntax,\n                    manifestPath: manifestPath,\n                    verbose: verbose\n                )\n            }\n        }\n    }\n}\n\nfileprivate extension SourceFileSyntax {\n    func checkManifestAtLeast(_ version: ToolsVersion) throws {\n        let toolsVersion = try ToolsVersionParser.parse(utf8String: description)\n        if toolsVersion < version {\n            throw StringError(\"package manifest version \\(toolsVersion) is too old: please update to manifest version \\(version) or newer\")\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/AddTarget.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport SwiftParser\n@_spi(PackageRefactor) import SwiftRefactor\nimport SwiftSyntax\nimport SwiftSyntaxBuilder\nimport Workspace\n\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.StringError\n\nextension AddPackageTarget.TestHarness: @retroactive ExpressibleByArgument {}\n\n/// The array of auxiliary files that can be added by a package editing\n/// operation.\nprivate typealias AuxiliaryFiles = [(RelativePath, SourceFileSyntax)]\n\nextension SwiftPackageCommand {\n    struct AddTarget: AsyncSwiftCommand {\n        /// The type of target that can be specified on the command line.\n        enum TargetType: String, Codable, ExpressibleByArgument, CaseIterable {\n            case library\n            case executable\n            case test\n            case macro\n        }\n\n        package static let configuration = CommandConfiguration(\n            abstract: \"Add a new target to the manifest.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Argument(help: \"The name of the new target.\")\n        var name: String\n\n        @Option(help: \"The type of target to add.\")\n        var type: TargetType = .library\n\n        @Option(\n            parsing: .upToNextOption,\n            help: \"A list of target dependency names.\"\n        )\n        var dependencies: [String] = []\n\n        @Option(help: \"The URL for a remote binary target.\")\n        var url: String?\n\n        @Option(help: \"The path to a local binary target.\")\n        var path: String?\n\n        @Option(help: \"The checksum for a remote binary target.\")\n        var checksum: String?\n\n        @Option(\n            help: \"The testing library to use when generating test targets, which can be one of 'xctest', 'swift-testing', or 'none'.\"\n        )\n        var testingLibrary: AddPackageTarget.TestHarness = .default\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let workspace = try swiftCommandState.getActiveWorkspace()\n\n            guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else {\n                throw StringError(\"unknown package\")\n            }\n\n            // Load the manifest file\n            let fileSystem = workspace.fileSystem\n            let manifestPath = packagePath.appending(\"Package.swift\")\n            let manifestContents: ByteString\n            do {\n                manifestContents = try fileSystem.readFileContents(manifestPath)\n            } catch {\n                throw StringError(\"cannot find package manifest in \\(manifestPath)\")\n            }\n\n            // Parse the manifest.\n            let manifestSyntax = manifestContents.withData { data in\n                data.withUnsafeBytes { buffer in\n                    buffer.withMemoryRebound(to: UInt8.self) { buffer in\n                        Parser.parse(source: buffer)\n                    }\n                }\n            }\n\n            // Move sources into their own folder if they're directly in `./Sources`.\n            try await self.moveSingleTargetSources(\n                workspace: workspace,\n                packagePath: packagePath,\n                verbose: !self.globalOptions.logging.quiet,\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n\n            // Map the target type.\n            let type: PackageTarget.TargetKind = switch self.type {\n            case .library: .library\n            case .executable: .executable\n            case .test: .test\n            case .macro: .macro\n            }\n\n            // Map dependencies\n            let dependencies: [PackageTarget.Dependency] = self.dependencies.map {\n                .byName(name: $0)\n            }\n\n            let target = PackageTarget(\n                name: name,\n                type: type,\n                dependencies: dependencies,\n                path: path,\n                url: url,\n                checksum: checksum\n            )\n\n            let editResult = try AddPackageTarget.textRefactor(\n                syntax: manifestSyntax,\n                in: .init(\n                    target: target,\n                    testHarness: self.testingLibrary\n                )\n            )\n\n            try editResult.applyEdits(\n                to: fileSystem,\n                manifest: manifestSyntax,\n                manifestPath: manifestPath,\n                verbose: !self.globalOptions.logging.quiet\n            )\n\n            // Once edits are applied, it's time to create new files for the target.\n            try self.addAuxiliaryFiles(\n                target: target,\n                testHarness: self.testingLibrary,\n                fileSystem: fileSystem,\n                rootPath: manifestPath.parentDirectory\n            )\n        }\n\n        // Check if the package has a single target with that target's sources located\n        // directly in `./Sources`. If so, move the sources into a folder named after\n        // the target before adding a new target.\n        private func moveSingleTargetSources(\n            workspace: Workspace,\n            packagePath: AbsolutePath,\n            verbose: Bool = false,\n            observabilityScope: ObservabilityScope\n        ) async throws {\n            let manifest = try await workspace.loadRootManifest(\n                at: packagePath,\n                observabilityScope: observabilityScope\n            )\n\n            guard let target = manifest.targets.first, manifest.targets.count == 1 else {\n                return\n            }\n\n            let sourcesFolder = packagePath.appending(\"Sources\")\n            let expectedTargetFolder = sourcesFolder.appending(target.name)\n\n            let fileSystem = workspace.fileSystem\n            // If there is one target then pull its name out and use that to look for a folder in `Sources/TargetName`.\n            // If the folder doesn't exist then we know we have a single target package and we need to migrate files\n            // into this folder before we can add a new target.\n            if !fileSystem.isDirectory(expectedTargetFolder) {\n                if verbose {\n                    print(\n                        \"\"\"\n                        Moving existing files from \\(\n                            sourcesFolder.relative(to: packagePath)\n                        ) to \\(\n                            expectedTargetFolder.relative(to: packagePath)\n                        )...\n                        \"\"\",\n                        terminator: \"\"\n                    )\n                }\n                let contentsToMove = try fileSystem.getDirectoryContents(sourcesFolder)\n                try fileSystem.createDirectory(expectedTargetFolder)\n                for file in contentsToMove {\n                    let source = sourcesFolder.appending(file)\n                    let destination = expectedTargetFolder.appending(file)\n                    try fileSystem.move(from: source, to: destination)\n                }\n                if verbose {\n                    print(\" done.\")\n                }\n            }\n        }\n\n        private func createAuxiliaryFile(\n            fileSystem: any FileSystem,\n            rootPath: AbsolutePath,\n            filePath: RelativePath,\n            contents: SourceFileSyntax,\n            verbose: Bool = false\n        ) throws {\n            // If the file already exists, skip it.\n            let filePath = rootPath.appending(filePath)\n            if fileSystem.exists(filePath) {\n                if verbose {\n                    print(\"Skipping \\(filePath.relative(to: rootPath)) because it already exists.\")\n                }\n\n                return\n            }\n\n            // If the directory does not exist yet, create it.\n            let fileDir = filePath.parentDirectory\n            if !fileSystem.exists(fileDir) {\n                if verbose {\n                    print(\"Creating directory \\(fileDir.relative(to: rootPath))...\", terminator: \"\")\n                }\n\n                try fileSystem.createDirectory(fileDir, recursive: true)\n\n                if verbose {\n                    print(\" done.\")\n                }\n            }\n\n            // Write the file.\n            if verbose {\n                print(\"Writing \\(filePath.relative(to: rootPath))...\", terminator: \"\")\n            }\n\n            try fileSystem.writeFileContents(\n                filePath,\n                string: contents.description\n            )\n\n            if verbose {\n                print(\" done.\")\n            }\n        }\n\n        private func addAuxiliaryFiles(\n            target: PackageTarget,\n            testHarness: AddPackageTarget.TestHarness,\n            fileSystem: any FileSystem,\n            rootPath: AbsolutePath\n        ) throws {\n            let outerDirectory: String? = switch target.type {\n            case .binary, .plugin, .system: nil\n            case .executable, .library, .macro: \"Sources\"\n            case .test: \"Tests\"\n            }\n\n            guard let outerDirectory else {\n                return\n            }\n\n            let targetDir = try RelativePath(validating: outerDirectory).appending(component: target.name)\n            let sourceFilePath = targetDir.appending(component: \"\\(target.name).swift\")\n\n            // Introduce imports for each of the dependencies that were specified.\n            var importModuleNames = target.dependencies.map {\n                switch $0 {\n                case .byName(let name),\n                     .target(let name),\n                     .product(let name, package: _):\n                    name\n                }\n            }\n\n            // Add appropriate test module dependencies.\n            if target.type == .test {\n                switch testHarness {\n                case .none:\n                    break\n\n                case .xctest:\n                    importModuleNames.append(\"XCTest\")\n\n                case .swiftTesting:\n                    importModuleNames.append(\"Testing\")\n                }\n            }\n\n            let importDecls = importModuleNames.lazy.sorted().map { name in\n                DeclSyntax(\"import \\(raw: name)\\n\")\n            }\n\n            let imports = CodeBlockItemListSyntax {\n                for importDecl in importDecls {\n                    importDecl\n                }\n            }\n\n            var files: AuxiliaryFiles = []\n            switch target.type {\n            case .binary, .plugin, .system:\n                break\n\n            case .macro:\n                files.addSourceFile(\n                    path: sourceFilePath,\n                    sourceCode: \"\"\"\n                    \\(imports)\n                    struct \\(raw: target.sanitizedName): Macro {\n                        /// TODO: Implement one or more of the protocols that inherit\n                        /// from Macro. The appropriate macro protocol is determined\n                        /// by the \"macro\" declaration that \\(raw: target.sanitizedName) implements.\n                        /// Examples include:\n                        ///     @freestanding(expression) macro --> ExpressionMacro\n                        ///     @attached(member) macro         --> MemberMacro\n                    }\n                    \"\"\"\n                )\n\n                // Add a file that introduces the main entrypoint and provided macros\n                // for a macro target.\n                files.addSourceFile(\n                    path: targetDir.appending(component: \"ProvidedMacros.swift\"),\n                    sourceCode: \"\"\"\n                    import SwiftCompilerPlugin\n\n                    @main\n                    struct \\(raw: target.sanitizedName)Macros: CompilerPlugin {\n                        let providingMacros: [Macro.Type] = [\n                            \\(raw: target.sanitizedName).self,\n                        ]\n                    }\n                    \"\"\"\n                )\n\n            case .test:\n                let sourceCode: SourceFileSyntax = switch testHarness {\n                case .none:\n                    \"\"\"\n                    \\(imports)\n                    // Test code here\n                    \"\"\"\n\n                case .xctest:\n                    \"\"\"\n                    \\(imports)\n                    class \\(raw: target.sanitizedName)Tests: XCTestCase {\n                        func test\\(raw: target.sanitizedName)() {\n                            XCTAssertEqual(42, 17 + 25)\n                        }\n                    }\n                    \"\"\"\n\n                case .swiftTesting:\n                    \"\"\"\n                    \\(imports)\n                    @Suite\n                    struct \\(raw: target.sanitizedName)Tests {\n                        @Test(\"\\(raw: target.sanitizedName) tests\")\n                        func example() {\n                            #expect(42 == 17 + 25)\n                        }\n                    }\n                    \"\"\"\n                }\n\n                files.addSourceFile(path: sourceFilePath, sourceCode: sourceCode)\n\n            case .library:\n                files.addSourceFile(\n                    path: sourceFilePath,\n                    sourceCode: \"\"\"\n                    \\(imports)\n                    \"\"\"\n                )\n\n            case .executable:\n                files.addSourceFile(\n                    path: sourceFilePath,\n                    sourceCode: \"\"\"\n                    \\(imports)\n                    @main\n                    struct \\(raw: target.sanitizedName)Main {\n                        static func main() {\n                            print(\"Hello, world\")\n                        }\n                    }\n                    \"\"\"\n                )\n            }\n\n            for (file, sourceCode) in files {\n                try self.createAuxiliaryFile(\n                    fileSystem: fileSystem,\n                    rootPath: rootPath,\n                    filePath: file,\n                    contents: sourceCode,\n                    verbose: !self.globalOptions.logging.quiet\n                )\n            }\n        }\n    }\n}\n\nextension AuxiliaryFiles {\n    /// Add a source file to the list of auxiliary files.\n    fileprivate mutating func addSourceFile(\n        path: RelativePath,\n        sourceCode: SourceFileSyntax\n    ) {\n        self.append((path, sourceCode))\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/AddTargetDependency.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport SwiftParser\n@_spi(PackageRefactor) import SwiftRefactor\nimport SwiftSyntax\nimport TSCBasic\nimport TSCUtility\nimport Workspace\n\nextension SwiftPackageCommand {\n    struct AddTargetDependency: SwiftCommand {\n        package static let configuration = CommandConfiguration(\n            abstract: \"Add a new target dependency to the manifest.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Argument(help: \"The name of the new dependency.\")\n        var dependencyName: String\n\n        @Argument(help: \"The name of the target to update.\")\n        var targetName: String\n\n        @Option(help: \"The package in which the dependency resides.\")\n        var package: String?\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            let workspace = try swiftCommandState.getActiveWorkspace()\n\n            guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else {\n                throw StringError(\"unknown package\")\n            }\n\n            // Load the manifest file\n            let fileSystem = workspace.fileSystem\n            let manifestPath = packagePath.appending(\"Package.swift\")\n            let manifestContents: ByteString\n            do {\n                manifestContents = try fileSystem.readFileContents(manifestPath)\n            } catch {\n                throw StringError(\"cannot find package manifest in \\(manifestPath)\")\n            }\n\n            // Parse the manifest.\n            let manifestSyntax = manifestContents.withData { data in\n                data.withUnsafeBytes { buffer in\n                    buffer.withMemoryRebound(to: UInt8.self) { buffer in\n                        Parser.parse(source: buffer)\n                    }\n                }\n            }\n\n            let dependency: PackageTarget.Dependency\n            if let package {\n                dependency = .product(name: dependencyName, package: package)\n            } else {\n                dependency = .target(name: dependencyName)\n            }\n\n            let editResult = try SwiftRefactor.AddTargetDependency.textRefactor(\n                syntax: manifestSyntax,\n                in: .init(\n                    dependency: dependency,\n                    targetName: targetName\n                )\n            )\n\n            try editResult.applyEdits(\n                to: fileSystem,\n                manifest: manifestSyntax,\n                manifestPath: manifestPath,\n                verbose: !globalOptions.logging.quiet\n            )\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/ArchiveSource.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageGraph\nimport PackageModel\nimport SourceControl\n\nextension SwiftPackageCommand {\n    struct ArchiveSource: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            commandName: \"archive-source\",\n            abstract: \"Create a source archive for the package.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Option(\n            name: [.short, .long],\n            help: \"The absolute or relative path for the generated source archive.\"\n        )\n        var output: AbsolutePath?\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let packageDirectory = try globalOptions.locations.packageDirectory ?? swiftCommandState.getPackageRoot()\n\n            let archivePath: AbsolutePath\n            if let output {\n                archivePath = output\n            } else {\n                let graph = try await swiftCommandState.loadPackageGraph()\n                let packageName = graph.rootPackages[graph.rootPackages.startIndex].manifest.displayName // TODO: use identity instead?\n                archivePath = packageDirectory.appending(\"\\(packageName).zip\")\n            }\n\n            try await SwiftPackageCommand.archiveSource(\n                at: packageDirectory,\n                to: archivePath,\n                fileSystem: localFileSystem,\n                cancellator: swiftCommandState.cancellator\n            )\n\n            if archivePath.isDescendantOfOrEqual(to: packageDirectory) {\n                let relativePath = archivePath.relative(to: packageDirectory)\n                print(\"Created \\(relativePath.pathString)\")\n            } else {\n                print(\"Created \\(archivePath.pathString)\")\n            }\n        }\n    }\n\n    public static func archiveSource(\n        at packageDirectory: AbsolutePath,\n        to archivePath: AbsolutePath,\n        fileSystem: FileSystem,\n        cancellator: Cancellator?\n    ) async throws {\n        let gitRepositoryProvider = GitRepositoryProvider()\n        if (try? gitRepositoryProvider.isValidDirectory(packageDirectory)) == true {\n            let repository = GitRepository(path: packageDirectory, cancellator: cancellator)\n            try repository.archive(to: archivePath)\n        } else {\n            let zipArchiver = ZipArchiver(fileSystem: fileSystem, cancellator: cancellator)\n            try await zipArchiver.compress(directory: packageDirectory, to: archivePath)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/AuditBinaryArtifact.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport BinarySymbols\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport SPMBuildCore\nimport Workspace\n\nimport struct TSCBasic.StringError\n\nstruct AuditBinaryArtifact: AsyncSwiftCommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"experimental-audit-binary-artifact\",\n        abstract: \"Audit a static library binary artifact for undefined symbols.\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    @Argument(help: \"The absolute or relative path to the binary artifact.\")\n    var path: AbsolutePath\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        let hostToolchain = try swiftCommandState.getHostToolchain()\n        let clang = try hostToolchain.getClangCompiler()\n        let objdump = try hostToolchain.getLLVMObjdump()\n        let hostTriple = try Triple.getVersionedHostTriple(\n            usingSwiftCompiler: hostToolchain.swiftCompilerPath)\n        let fileSystem = swiftCommandState.fileSystem\n\n        guard !(hostTriple.isDarwin() || hostTriple.isWindows()) else {\n            throw StringError(\n                \"experimental-audit-binary-artifact is not supported on Darwin and Windows platforms.\"\n            )\n        }\n\n        var hostDefaultSymbols = ReferencedSymbols()\n        let symbolProvider = LLVMObjdumpSymbolProvider(objdumpPath: objdump)\n        for binary in try await detectDefaultObjects(\n            clang: clang, fileSystem: fileSystem, hostTriple: hostTriple,\n            observabilityScope:\n                swiftCommandState.observabilityScope.makeChildScope(\n                    description: \"DefaultObjectsDetector\"))\n        {\n            try await symbolProvider.symbols(\n                for: binary, symbols: &hostDefaultSymbols, recordUndefined: false)\n        }\n\n        let extractedArtifact = try await extractArtifact(\n            fileSystem: fileSystem, scratchDirectory: swiftCommandState.scratchDirectory)\n\n        guard\n            let artifactKind = try Workspace.BinaryArtifactsManager.deriveBinaryArtifactKind(\n                fileSystem: fileSystem,\n                path: extractedArtifact,\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n        else {\n            throw StringError(\"Invalid binary artifact provided at \\(path)\")\n        }\n\n        let module = BinaryModule(\n            name: path.basenameWithoutExt, kind: artifactKind, path: extractedArtifact,\n            origin: .local)\n        for library in try module.parseLibraryArtifactArchives(\n            for: hostTriple, fileSystem: fileSystem)\n        {\n            var symbols = hostDefaultSymbols\n            try await symbolProvider.symbols(for: library.libraryPath, symbols: &symbols)\n\n            guard symbols.undefined.isEmpty else {\n                print(\n                    \"Invalid artifact binary \\(library.libraryPath.pathString), found undefined symbols:\"\n                )\n                for name in symbols.undefined {\n                    print(\"- \\(name)\")\n                }\n                throw ExitCode(1)\n            }\n        }\n\n        print(\n            \"Artifact is safe to use on the platforms runtime compatible with triple: \\(hostTriple.tripleString)\"\n        )\n    }\n\n    private func extractArtifact(fileSystem: any FileSystem, scratchDirectory: AbsolutePath)\n        async throws -> AbsolutePath\n    {\n        let archiver = UniversalArchiver(fileSystem)\n\n        if let lastPathComponent = path.components.last,\n            lastPathComponent.hasSuffix(\"artifactbundle\") {\n            return path\n        }\n\n        guard let lastPathComponent = path.components.last,\n            archiver.isFileSupported(lastPathComponent)\n        else {\n            let supportedExtensionList = archiver.supportedExtensions.joined(separator: \", \")\n            throw StringError(\n                \"unexpected file type; supported extensions are: \\(supportedExtensionList)\")\n        }\n\n        // Ensure that the path with the accepted extension is a file.\n        guard fileSystem.isFile(path) else {\n            throw StringError(\"file not found at path: \\(path.pathString)\")\n        }\n\n        let archiveDirectory = scratchDirectory.appending(\n            components: \"artifact-auditing\",\n            path.basenameWithoutExt, UUID().uuidString\n        )\n        try fileSystem.forceCreateDirectory(at: archiveDirectory)\n\n        try await archiver.extract(from: path, to: archiveDirectory)\n\n        let artifacts = try fileSystem.getDirectoryContents(archiveDirectory)\n            .map { archiveDirectory.appending(component: $0) }\n            .filter {\n                fileSystem.isDirectory($0)\n                    && $0.extension == BinaryModule.Kind.artifactsArchive(types: []).fileExtension\n            }\n\n        guard artifacts.count == 1 else {\n            throw StringError(\"Could not find an artifact bundle in the archive\")\n        }\n\n        return artifacts.first!\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/BuildServer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n#if canImport(LanguageServerProtocolTransport)\nimport ArgumentParser\nimport TSCBasic\nimport SwiftBuild\nimport BuildServerProtocol\nimport LanguageServerProtocol\nimport LanguageServerProtocolTransport\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport SwiftPMBuildServer\nimport SwiftBuildSupport\nimport SystemPackage\nimport SPMBuildCore\n\nstruct BuildServer: AsyncSwiftCommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"experimental-build-server\",\n        abstract: \"Launch a build server for Swift Packages\",\n        shouldDisplay: false\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        // Dup stdout and redirect the fd to stderr so that a careless print()\n        // will not break our connection stream.\n        let realStdout = try FileDescriptor.standardOutput.duplicate()\n        _ = try FileDescriptor.standardError.duplicate(as: FileDescriptor.standardOutput)\n\n        let realStdoutHandle = FileHandle(fileDescriptor: realStdout.rawValue, closeOnDealloc: false)\n\n        let clientConnection = JSONRPCConnection(\n            name: \"client\",\n            protocol: MessageRegistry.bspProtocol,\n            receiveFD: FileHandle.standardInput,\n            sendFD: realStdoutHandle,\n            receiveMirrorFile: nil,\n            sendMirrorFile: nil\n        )\n\n        let buildSystem = try await swiftCommandState.createBuildSystem(explicitBuildSystem: .swiftbuild)\n        guard let swiftBuildSystem = buildSystem as? SwiftBuildSystem else {\n            throw ArgumentParser.ValidationError(\"Failed to initialize the '--build-system swiftbuild' backend; expected a 'SwiftBuildSystem' but got '\\(buildSystem)'\")\n        }\n\n        guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else {\n            throw ArgumentParser.ValidationError(\"unknown package\")\n        }\n\n        let server = try await SwiftPMBuildServer(\n            packageRoot: packagePath,\n            buildSystem: swiftBuildSystem,\n            workspace: swiftCommandState.getActiveWorkspace(),\n            connectionToClient: clientConnection,\n            exitHandler: {_ in clientConnection.close() }\n        )\n        await withCheckedContinuation {continuation in\n            clientConnection.start(receiveHandler: server, closeHandler: { continuation.resume() })\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/CompletionCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageModel\nimport PackageGraph\n\nimport var TSCBasic.stdoutStream\n\nextension SwiftPackageCommand {\n    struct CompletionCommand: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            commandName: \"completion-tool\",\n            abstract: \"Command to generate shell completions.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        enum Mode: String, CaseIterable, ExpressibleByArgument {\n            case generateBashScript = \"generate-bash-script\"\n            case generateZshScript = \"generate-zsh-script\"\n            case generateFishScript = \"generate-fish-script\"\n            case listDependencies = \"list-dependencies\"\n            case listExecutables = \"list-executables\"\n            case listSnippets = \"list-snippets\"\n        }\n\n        /// A dummy version of the root `swift` command, to act as a parent\n        /// for all the subcommands.\n        fileprivate struct SwiftCommand: ParsableCommand {\n            static let configuration = CommandConfiguration(\n                commandName: \"swift\",\n                abstract: \"The Swift compiler\",\n                subcommands: [\n                    SwiftRunCommand.self,\n                    SwiftBuildCommand.self,\n                    SwiftTestCommand.self,\n                    SwiftPackageCommand.self,\n                ]\n            )\n        }\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Argument(help: \"Type of completions to list.\")\n        var mode: Mode\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            switch mode {\n            case .generateBashScript:\n                let script = SwiftCommand.completionScript(for: .bash)\n                print(script)\n            case .generateZshScript:\n                let script = SwiftCommand.completionScript(for: .zsh)\n                print(script)\n            case .generateFishScript:\n                let script = SwiftCommand.completionScript(for: .fish)\n                print(script)\n            case .listDependencies:\n                let graph = try await swiftCommandState.loadPackageGraph()\n                // command's result output goes on stdout\n                // ie \"swift package list-dependencies\" should output to stdout\n                ShowDependencies.dumpDependenciesOf(\n                    graph: graph,\n                    rootPackage: graph.rootPackages[graph.rootPackages.startIndex],\n                    mode: .flatlist,\n                    on: TSCBasic.stdoutStream\n                )\n            case .listExecutables:\n                let graph = try await swiftCommandState.loadPackageGraph()\n                let package = graph.rootPackages[graph.rootPackages.startIndex].underlying\n                let executables = package.products.filter { $0.type == .executable }.sorted()\n                for executable in executables {\n                    print(executable.name)\n                }\n            case .listSnippets:\n                let graph = try await swiftCommandState.loadPackageGraph()\n                let package = graph.rootPackages[graph.rootPackages.startIndex].underlying\n                let executables = package.modules.filter { $0.type == .snippet }.sorted()\n                for executable in executables {\n                    print(executable.name)\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/ComputeChecksum.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Workspace\n\nimport struct TSCBasic.SHA256\n\nstruct ComputeChecksum: SwiftCommand {\n    static let configuration = CommandConfiguration(\n        abstract: \"Compute the checksum for a binary artifact.\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    @Argument(help: \"The absolute or relative path to the binary artifact.\")\n    var path: AbsolutePath\n\n    func run(_ swiftCommandState: SwiftCommandState) throws {\n        let checksum = try Workspace.BinaryArtifactsManager.checksum(\n            forBinaryArtifactAt: self.path,\n            fileSystem: swiftCommandState.fileSystem\n        )\n        print(checksum)\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Config.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageGraph\nimport Workspace\n\nimport var TSCBasic.stderrStream\n\nextension SwiftPackageCommand {\n    struct Config: ParsableCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Manipulate configuration of the package\",\n            subcommands: [SetMirror.self, UnsetMirror.self, GetMirror.self],\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n    }\n}\n\nextension SwiftPackageCommand.Config {\n    struct SetMirror: SwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Set a mirror for a dependency.\"\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Option(name: .customLong(\"package-url\"), help: .hidden)\n        var _deprecate_packageURL: String?\n\n        @Option(name: .customLong(\"original-url\"), help: .hidden)\n        var _deprecate_originalURL: String?\n\n        @Option(name: .customLong(\"mirror-url\"), help: .hidden)\n        var _deprecate_mirrorURL: String?\n\n        @Option(help: \"The original url or identity.\")\n        var original: String?\n\n        @Option(help: \"The mirror url or identity.\")\n        var mirror: String?\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            let config = try getMirrorsConfig(swiftCommandState)\n\n            if self._deprecate_packageURL != nil {\n                swiftCommandState.observabilityScope.emit(\n                    warning: \"'--package-url' option is deprecated; use '--original' instead\"\n                )\n            }\n            if self._deprecate_originalURL != nil {\n                swiftCommandState.observabilityScope.emit(\n                    warning: \"'--original-url' option is deprecated; use '--original' instead\"\n                )\n            }\n            if self._deprecate_mirrorURL != nil {\n                swiftCommandState.observabilityScope.emit(\n                    warning: \"'--mirror-url' option is deprecated; use '--mirror' instead\"\n                )\n            }\n\n            guard let original = self._deprecate_packageURL ?? self._deprecate_originalURL ?? self.original else {\n                swiftCommandState.observabilityScope.emit(.missingRequiredArg(\"--original\"))\n                throw ExitCode.failure\n            }\n\n            guard let mirror = self._deprecate_mirrorURL ?? self.mirror else {\n                swiftCommandState.observabilityScope.emit(.missingRequiredArg(\"--mirror\"))\n                throw ExitCode.failure\n            }\n\n            try config.applyLocal { mirrors in\n                try mirrors.set(mirror: mirror, for: original)\n            }\n        }\n    }\n\n    struct UnsetMirror: SwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Remove an existing mirror.\"\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Option(name: .customLong(\"package-url\"), help: .hidden)\n        var _deprecate_packageURL: String?\n\n        @Option(name: .customLong(\"original-url\"), help: .hidden)\n        var _deprecate_originalURL: String?\n\n        @Option(name: .customLong(\"mirror-url\"), help: .hidden)\n        var _deprecate_mirrorURL: String?\n\n        @Option(help: \"The original url or identity.\")\n        var original: String?\n\n        @Option(help: \"The mirror url or identity.\")\n        var mirror: String?\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            let config = try getMirrorsConfig(swiftCommandState)\n\n            if self._deprecate_packageURL != nil {\n                swiftCommandState.observabilityScope.emit(\n                    warning: \"'--package-url' option is deprecated; use '--original' instead\"\n                )\n            }\n            if self._deprecate_originalURL != nil {\n                swiftCommandState.observabilityScope.emit(\n                    warning: \"'--original-url' option is deprecated; use '--original' instead\"\n                )\n            }\n            if self._deprecate_mirrorURL != nil {\n                swiftCommandState.observabilityScope.emit(\n                    warning: \"'--mirror-url' option is deprecated; use '--mirror' instead\"\n                )\n            }\n\n            guard let originalOrMirror = self._deprecate_packageURL ?? self._deprecate_originalURL ?? self\n                .original ?? self._deprecate_mirrorURL ?? self.mirror\n            else {\n                swiftCommandState.observabilityScope.emit(.missingRequiredArg(\"--original or --mirror\"))\n                throw ExitCode.failure\n            }\n\n            try config.applyLocal { mirrors in\n                try mirrors.unset(originalOrMirror: originalOrMirror)\n            }\n        }\n    }\n\n    struct GetMirror: SwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Print mirror configuration for the given package dependency.\"\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n        @Option(name: .customLong(\"package-url\"), help: .hidden)\n        var _deprecate_packageURL: String?\n\n        @Option(name: .customLong(\"original-url\"), help: .hidden)\n        var _deprecate_originalURL: String?\n\n        @Option(help: \"The original url or identity.\")\n        var original: String?\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            let config = try getMirrorsConfig(swiftCommandState)\n\n            if self._deprecate_packageURL != nil {\n                swiftCommandState.observabilityScope.emit(\n                    warning: \"'--package-url' option is deprecated; use '--original' instead\"\n                )\n            }\n            if self._deprecate_originalURL != nil {\n                swiftCommandState.observabilityScope.emit(\n                    warning: \"'--original-url' option is deprecated; use '--original' instead\"\n                )\n            }\n\n            guard let original = self._deprecate_packageURL ?? self._deprecate_originalURL ?? self.original else {\n                swiftCommandState.observabilityScope.emit(.missingRequiredArg(\"--original\"))\n                throw ExitCode.failure\n            }\n\n            if let mirror = config.mirrors.mirror(for: original) {\n                print(mirror)\n            } else {\n                stderrStream.send(\"not found\\n\")\n                stderrStream.flush()\n                throw ExitCode.failure\n            }\n        }\n    }\n\n    static func getMirrorsConfig(_ swiftCommandState: SwiftCommandState) throws -> Workspace.Configuration.Mirrors {\n        let workspace = try swiftCommandState.getActiveWorkspace()\n        return try .init(\n            fileSystem: swiftCommandState.fileSystem,\n            localMirrorsFile: workspace.location.localMirrorsConfigurationFile,\n            sharedMirrorsFile: workspace.location.sharedMirrorsConfigurationFile\n        )\n    }\n}\n\nextension Basics.Diagnostic {\n    fileprivate static func missingRequiredArg(_ argument: String) -> Self {\n        .error(\"missing required argument \\(argument)\")\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Describe.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport PackageGraph\nimport Workspace\n\nimport struct TSCBasic.StringError\n\nextension SwiftPackageCommand {\n    struct Describe: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Describe the current package.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n        \n        @Option(help: \"Set the output format.\")\n        var type: DescribeMode = .text\n        \n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let workspace = try swiftCommandState.getActiveWorkspace()\n            \n            guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else {\n                throw StringError(\"unknown package\")\n            }\n            \n            let package = try await workspace.loadRootPackage(\n                at: packagePath,\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n\n            try self.describe(package, in: type)\n        }\n        \n        /// Emits a textual description of `package` to `stream`, in the format indicated by `mode`.\n        func describe(_ package: Package, in mode: DescribeMode) throws {\n            let desc = DescribedPackage(from: package)\n            let data: Data\n            switch mode {\n            case .json:\n                let encoder = JSONEncoder.makeWithDefaults()\n                encoder.keyEncodingStrategy = .convertToSnakeCase\n                data = try encoder.encode(desc)\n            case .text:\n                var encoder = PlainTextEncoder()\n                encoder.formattingOptions = [.prettyPrinted]\n                data = try encoder.encode(desc)\n            case .mermaid:\n                data = Data(MermaidPackageSerializer(package: package).renderedMarkdown.utf8)\n            }\n            print(String(decoding: data, as: UTF8.self))\n        }\n        \n        enum DescribeMode: String, ExpressibleByArgument, CaseIterable {\n            /// JSON format (guaranteed to be parsable and stable across time).\n            case json\n            /// Human readable format (not guaranteed to be parsable).\n            case text\n            /// Mermaid flow charts format\n            case mermaid\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/DumpCommands.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport PackageGraph\nimport SPMBuildCore\nimport TSCBasic\nimport Workspace\nimport XCBuildSupport\n\nstruct DumpSymbolGraph: AsyncSwiftCommand {\n    static let configuration = CommandConfiguration(\n        abstract: \"Dump symbol graphs.\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n    static let defaultMinimumAccessLevel = SymbolGraphExtract.AccessLevel.public\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    @Flag(help: \"Pretty-print the output JSON.\")\n    var prettyPrint = false\n\n    @Flag(help: \"Skip members inherited through classes or default implementations.\")\n    var skipSynthesizedMembers = false\n\n    @Option(help: \"Include symbols with this access level or more. Possible values: \\(SymbolGraphExtract.AccessLevel.allValueStrings.joined(separator: \" | \")).\")\n    var minimumAccessLevel = defaultMinimumAccessLevel\n\n    @Flag(help: \"Skip emitting doc comments for members inherited through classes or default implementations.\")\n    var skipInheritedDocs = false\n\n    @Flag(help: \"Add symbols with SPI information to the symbol graph.\")\n    var includeSPISymbols = false\n\n    @Flag(help: \"Emit extension block symbols for extensions to external types or directly associate members and conformances with the extended nominal.\")\n    var extensionBlockSymbolBehavior: ExtensionBlockSymbolBehavior = .omitExtensionBlockSymbols\n\n    @Option(\n        help: .init(\n            \"Specify symbol graph output directory\",\n            visibility: .hidden,\n        ),\n    )\n    var outputDir: Basics.AbsolutePath? = nil\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        // Build the current package.\n        //\n        // We turn build manifest caching off because we need the build plan.\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            // We are enabling all traits for dumping the symbol graph.\n            enableAllTraits: true,\n            cacheBuildManifest: false\n        )\n        let buildResult = try await buildSystem.build(subset: .allExcludingTests, buildOutputs: [.symbolGraph(\n            BuildOutput.SymbolGraphOptions(\n                prettyPrint: prettyPrint,\n                minimumAccessLevel: .accessLevel(minimumAccessLevel),\n                includeInheritedDocs: !skipInheritedDocs,\n                includeSynthesized: !skipSynthesizedMembers,\n                includeSPI: includeSPISymbols,\n                emitExtensionBlocks: extensionBlockSymbolBehavior != .omitExtensionBlockSymbols,\n            )\n        ), .buildPlan])\n\n        let symbolGraphDirectory = try self.outputDir ?? swiftCommandState.productsBuildParameters.dataPath.appending(\"symbolgraph\")\n\n        let fs = swiftCommandState.fileSystem\n\n        try? fs.removeFileTree(symbolGraphDirectory)\n        try fs.createDirectory(symbolGraphDirectory, recursive: true)\n\n        if let symbolGraph = buildResult.symbolGraph {\n            // The build system produced symbol graphs for us, one for each target.\n            let buildPath = try swiftCommandState.productsBuildParameters.buildPath\n\n            // Copy the symbol graphs from the target-specific locations to the single output directory\n            for rootPackage in try await buildSystem.getPackageGraph().rootPackages {\n                for module in rootPackage.modules {\n                    let sgDir = symbolGraph.outputLocationForTarget(module.name, try swiftCommandState.productsBuildParameters)\n\n                    if case let sgDir = buildPath.appending(components: sgDir), fs.exists(sgDir) {\n                        for sgFile in try fs.getDirectoryContents(sgDir) {\n                            try fs.copy(from: sgDir.appending(components: sgFile), to: symbolGraphDirectory.appending(sgFile))\n                        }\n                    }\n                }\n            }\n        } else if let buildPlan = buildResult.buildPlan {\n            // Otherwise, with a build plan we can run the symbol graph extractor tool on the built targets.\n            let symbolGraphExtractor = try SymbolGraphExtract(\n                fileSystem: swiftCommandState.fileSystem,\n                tool: swiftCommandState.getTargetToolchain().getSymbolGraphExtract(),\n                observabilityScope: swiftCommandState.observabilityScope,\n                skipSynthesizedMembers: skipSynthesizedMembers,\n                minimumAccessLevel: minimumAccessLevel,\n                skipInheritedDocs: skipInheritedDocs,\n                includeSPISymbols: includeSPISymbols,\n                emitExtensionBlockSymbols: extensionBlockSymbolBehavior == .emitExtensionBlockSymbols,\n                outputFormat: .json(pretty: prettyPrint)\n            )\n\n            // Run the tool once for every library and executable target in the root package.\n            let modulesGraph = try await buildSystem.getPackageGraph()\n            for description in buildPlan.buildModules {\n                guard description.module.type == .library,\n                    modulesGraph.rootPackages[description.package.id] != nil\n                else {\n                    continue\n                }\n\n                print(\"-- Emitting symbol graph for\", description.module.name)\n                let result = try symbolGraphExtractor.extractSymbolGraph(\n                    for: description,\n                    outputRedirection: .collect(redirectStderr: true),\n                    outputDirectory: symbolGraphDirectory,\n                    verboseOutput: swiftCommandState.logLevel <= .info\n                )\n\n                if result.exitStatus != .terminated(code: 0) {\n                    let commandline = \"\\nUsing commandline: \\(result.arguments)\"\n                    switch result.output {\n                    case .success(let value):\n                        swiftCommandState.observabilityScope.emit(error: \"Failed to emit symbol graph for '\\(description.module.c99name)': \\(String(decoding: value, as: UTF8.self))\\(commandline)\")\n                    case .failure(let error):\n                        swiftCommandState.observabilityScope.emit(error: \"Internal error while emitting symbol graph for '\\(description.module.c99name)': \\(error)\\(commandline)\")\n                    }\n                }\n            }\n        } else {\n            throw InternalError(\"Build system \\(buildSystem) cannot produce a symbol graph.\")\n        }\n\n        print(\"Files written to\", symbolGraphDirectory.pathString)\n    }\n}\n\nenum ExtensionBlockSymbolBehavior: String, EnumerableFlag {\n    case emitExtensionBlockSymbols\n    case omitExtensionBlockSymbols\n}\n\nstruct DumpPackage: AsyncSwiftCommand {\n    static let configuration = CommandConfiguration(\n        abstract: \"Print parsed Package.swift as JSON.\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        let workspace = try swiftCommandState.getActiveWorkspace()\n        let root = try swiftCommandState.getWorkspaceRoot()\n\n        let rootManifests = try await workspace.loadRootManifests(\n            packages: root.packages,\n            observabilityScope: swiftCommandState.observabilityScope\n        )\n        guard let rootManifest = rootManifests.values.first else {\n            throw StringError(\"invalid manifests at \\(root.packages)\")\n        }\n\n        let encoder = JSONEncoder.makeWithDefaults()\n        encoder.userInfo[Manifest.dumpPackageKey] = true\n\n        let jsonData = try encoder.encode(rootManifest)\n        let jsonString = String(decoding: jsonData, as: UTF8.self)\n        print(jsonString)\n    }\n}\n\nstruct DumpPIF: AsyncSwiftCommand {\n    // hides this command from CLI `--help` output\n    static let configuration = CommandConfiguration(\n        shouldDisplay: false,\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .private)\n    var globalOptions: GlobalOptions\n\n    @Flag(help: \"Preserve the internal structure of PIF\")\n    var preserveStructure: Bool = false\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        let buildSystem = try await swiftCommandState.createBuildSystem()\n        let pif = try await buildSystem.generatePIF(preserveStructure: preserveStructure)\n        print(pif)\n    }\n\n    var toolWorkspaceConfiguration: ToolWorkspaceConfiguration {\n        return .init(wantsMultipleTestProducts: true)\n    }\n}\n\nfileprivate extension BuildOutput.SymbolGraphAccessLevel {\n    static func accessLevel(_ accessLevel: SymbolGraphExtract.AccessLevel) -> BuildOutput.SymbolGraphAccessLevel {\n        return BuildOutput.SymbolGraphAccessLevel.init(rawValue: accessLevel.rawValue)!\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/EditCommands.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport SourceControl\nimport Workspace\n\nextension SwiftPackageCommand {\n    struct Edit: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Put a package in editable mode.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Option(help: \"The revision to edit.\", transform: { Revision(identifier: $0) })\n        var revision: Revision?\n\n        @Option(name: .customLong(\"branch\"), help: \"The branch to create.\")\n        var checkoutBranch: String?\n\n        @Option(help: \"Create or use the checkout at this path.\")\n        var path: AbsolutePath?\n\n        @Argument(help: \"The identity of the package to edit.\")\n        var packageIdentity: String\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            try await swiftCommandState.resolve()\n            let workspace = try swiftCommandState.getActiveWorkspace()\n\n            // Put the dependency in edit mode.\n            await workspace.edit(\n                packageIdentity: packageIdentity,\n                path: path,\n                revision: revision,\n                checkoutBranch: checkoutBranch,\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n        }\n    }\n\n    struct Unedit: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Remove a package from editable mode.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Flag(name: .customLong(\"force\"),\n              help: \"Unedit the package even if it has uncommitted and unpushed changes.\")\n        var shouldForceRemove: Bool = false\n\n        @Argument(help: \"The identity of the package to unedit.\")\n        var packageIdentity: String\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            try await swiftCommandState.resolve()\n            let workspace = try swiftCommandState.getActiveWorkspace()\n\n            try await workspace.unedit(\n                packageIdentity: packageIdentity,\n                forceRemove: shouldForceRemove,\n                root: swiftCommandState.getWorkspaceRoot(),\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Format.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageModel\nimport PackageGraph\nimport TSCBasic\nimport Workspace\n\nimport class Basics.AsyncProcess\n\nimport enum TSCUtility.Diagnostics\n\nextension SwiftPackageCommand {\n    struct Format: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            commandName: \"_format\", shouldDisplay: false,\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .private)\n        var globalOptions: GlobalOptions\n\n        @Argument(parsing: .captureForPassthrough,\n                  help: \"Pass flag through to the swift-format tool.\")\n        var swiftFormatFlags: [String] = []\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            // Look for swift-format binary.\n            // FIXME: This should be moved to user toolchain.\n            let swiftFormatInEnv = Basics.lookupExecutablePath(filename: Environment.current[\"SWIFT_FORMAT\"])\n            guard let swiftFormat = swiftFormatInEnv ?? AsyncProcess.findExecutable(\"swift-format\") else {\n                swiftCommandState.observabilityScope.emit(error: \"Could not find swift-format in PATH or SWIFT_FORMAT\")\n                throw TSCUtility.Diagnostics.fatalError\n            }\n\n            // Get the root package.\n            let workspace = try swiftCommandState.getActiveWorkspace()\n\n            guard let packagePath = try swiftCommandState.getWorkspaceRoot().packages.first else {\n                throw StringError(\"unknown package\")\n            }\n\n            let package = try await workspace.loadRootPackage(\n                at: packagePath,\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n\n\n            // Use the user provided flags or default to formatting mode.\n            let formatOptions = swiftFormatFlags.isEmpty\n                ? [\"--mode\", \"format\", \"--in-place\", \"--parallel\"]\n                : swiftFormatFlags\n\n            // Process each target in the root package.\n            let paths = package.modules.flatMap { target in\n                target.sources.paths.filter { file in\n                    file.extension == SupportedLanguageExtension.swift.rawValue\n                }\n            }.map { $0.pathString }\n\n            let args = [swiftFormat.pathString] + formatOptions + [packagePath.pathString] + paths\n            print(\"Running:\", args.map{ $0.spm_shellEscaped() }.joined(separator: \" \"))\n\n            let result = try await AsyncProcess.popen(arguments: args)\n            let output = try (result.utf8Output() + result.utf8stderrOutput())\n\n            if result.exitStatus != .terminated(code: 0) {\n                print(\"Non-zero exit\", result.exitStatus)\n            }\n            if !output.isEmpty {\n                print(output)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/GenerateSBOM.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport SBOMModel\nimport SPMBuildCore\nimport Workspace\n\nextension SwiftPackageCommand {\n    \n    \n    struct GenerateSbom: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Generate a Software Bill of Materials (SBOM).\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)],\n        )\n\n        @OptionGroup()\n        var globalOptions: GlobalOptions\n\n        @Option(help: \"The product to generate an SBOM for.\")\n        var product: String?\n\n        @OptionGroup(title: \"Software Bill of Materials (SBOM)\")\n        var sbom: SBOMOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            do {\n                let workspace = try swiftCommandState.getActiveWorkspace()\n                let packageGraph = try await workspace.loadPackageGraph(\n                    rootInput: swiftCommandState.getWorkspaceRoot(),\n                    explicitProduct: self.product,\n                    forceResolvedVersions: self.globalOptions.resolver.forceResolvedVersions,\n                    observabilityScope: swiftCommandState.observabilityScope\n                )\n                let resolvedPackagesStore = try workspace.resolvedPackagesStore.load()\n\n                let specs = try self.sbom.sbomSpecs\n                let input = SBOMInput(\n                    modulesGraph: packageGraph,\n                    dependencyGraph: nil,\n                    store: resolvedPackagesStore,\n                    filter: try self.sbom.sbomFilter,\n                    product: self.product,\n                    specs: specs.isEmpty ? Spec.allCases : specs,\n                    dir: await SBOMCreator.resolveSBOMDirectory(from: self.sbom.sbomDirectory, withDefault: try swiftCommandState.productsBuildParameters.buildPath),\n                    observabilityScope: swiftCommandState.observabilityScope\n                )\n\n                let creator = SBOMCreator(input: input)\n                try await creator.createSBOMsWithLogging()\n                swiftCommandState.observabilityScope.emit(warning: \"`generate-sbom` subcommand may be inaccurate as it does not contain build-time conditionals.\")\n            } catch {\n                if sbom.sbomWarningOnly {\n                    swiftCommandState.observabilityScope.emit(warning: \"SBOM generation failed: \\(error.localizedDescription)\")\n                } else {\n                    throw error\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Init.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\n\n@_spi(SwiftPMInternal)\nimport CoreCommands\n\nimport PackageModel\nimport Workspace\nimport SPMBuildCore\n\nextension SwiftPackageCommand {\n    struct Init: SwiftCommand {\n        public static let configuration = CommandConfiguration(\n            abstract: \"Initialize a new package.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n        \n        @Option(\n            name: .customLong(\"type\"),\n            help: ArgumentHelp(\"Package type:\", discussion: \"\"\"\n                library           - A package with a library.\n                executable        - A package with an executable.\n                tool              - A package with an executable that uses\n                                    Swift Argument Parser. Use this template if you\n                                    plan to have a rich set of command-line arguments.\n                build-tool-plugin - A package that vends a build tool plugin.\n                command-plugin    - A package that vends a command plugin.\n                macro             - A package that vends a macro.\n                empty             - An empty package with a Package.swift manifest.\n                \"\"\"))\n        var initMode: InitPackage.PackageType = .library\n\n        /// Which testing libraries to use (and any related options.)\n        @OptionGroup()\n        var testLibraryOptions: TestLibraryOptions\n\n        @Option(name: .customLong(\"name\"), help: \"Provide a custom package name.\")\n        var packageName: String?\n\n        // This command should support creating the supplied --package-path if it isn't created.\n        var createPackagePath = true\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            guard let cwd = swiftCommandState.fileSystem.currentWorkingDirectory else {\n                throw InternalError(\"Could not find the current working directory\")\n            }\n\n            let packageName = self.packageName ?? cwd.basename\n\n            // Testing is on by default, with XCTest only enabled explicitly.\n            // For macros this is reversed, since we don't support testing\n            // macros with Swift Testing yet.\n            var supportedTestingLibraries = Set<TestingLibrary>()\n            if testLibraryOptions.isExplicitlyEnabled(.xctest, swiftCommandState: swiftCommandState) ||\n                (initMode == .macro && testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState)) {\n                supportedTestingLibraries.insert(.xctest)\n            }\n            if testLibraryOptions.isExplicitlyEnabled(.swiftTesting, swiftCommandState: swiftCommandState) ||\n                (initMode != .macro && testLibraryOptions.isEnabled(.swiftTesting, swiftCommandState: swiftCommandState)) {\n                supportedTestingLibraries.insert(.swiftTesting)\n            }\n\n            let initPackage = try InitPackage(\n                name: packageName,\n                packageType: initMode,\n                supportedTestingLibraries: supportedTestingLibraries,\n                destinationPath: cwd,\n                installedSwiftPMConfiguration: swiftCommandState.getHostToolchain().installedSwiftPMConfiguration,\n                fileSystem: swiftCommandState.fileSystem\n            )\n            initPackage.progressReporter = { message in\n                print(message)\n            }\n            try initPackage.writePackageStructure()\n        }\n    }\n}\n\nextension InitPackage.PackageType: ExpressibleByArgument {}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Install.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport struct Basics.Environment\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport SPMBuildCore\nimport TSCBasic\nimport Workspace\n\nextension SwiftPackageCommand {\n    struct Install: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            commandName: \"experimental-install\",\n            abstract: \"Offers the ability to install executable products of the current package.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup()\n        var globalOptions: GlobalOptions\n\n        @Option(help: \"The name of the executable product to install.\")\n        var product: String?\n\n        func run(_ commandState: SwiftCommandState) async throws {\n            let swiftpmBinDir = try commandState.fileSystem.getOrCreateSwiftPMInstalledBinariesDirectory()\n\n            let env = Environment.current\n\n            if let path = env[.path], !path.contains(swiftpmBinDir.pathString), !globalOptions.logging.quiet {\n                commandState.observabilityScope.emit(\n                    warning: \"\"\"\n                    PATH doesn't include \\(swiftpmBinDir.pathString)! This means you won't be able to access \\\n                    the installed executables by default, and will need to specify the full path.\n                    \"\"\"\n                )\n            }\n\n            let alreadyExisting = (try? InstalledPackageProduct.installedProducts(commandState.fileSystem)) ?? []\n\n            let workspace = try commandState.getActiveWorkspace()\n            let packageRoot = try commandState.getPackageRoot()\n\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootPath: packageRoot,\n                observabilityScope: commandState.observabilityScope\n            )\n\n            let possibleCandidates = packageGraph.rootPackages.flatMap(\\.products)\n                .filter { $0.type == .executable }\n\n            let productToInstall: Product\n\n            switch possibleCandidates.count {\n            case 0:\n                throw StringError(\"No Executable Products in Package.swift.\")\n            case 1:\n                productToInstall = possibleCandidates[0].underlying\n            default:\n                guard let product, let first = possibleCandidates.first(where: { $0.name == product }) else {\n                    throw StringError(\n                        \"\"\"\n                        Multiple candidates found, however, no product was specified. Specify a product with the \\\n                        `--product` option\n                        \"\"\"\n                    )\n                }\n\n                productToInstall = first.underlying\n            }\n\n            if let existingPkg = alreadyExisting.first(where: { $0.name == productToInstall.name }) {\n                throw StringError(\"\\(productToInstall.name) is already installed at \\(existingPkg.path)\")\n            }\n\n            if commandState.options.build.configuration == nil {\n                commandState.preferredBuildConfiguration = .release\n            }\n\n            try await commandState.createBuildSystem(explicitProduct: productToInstall.name)\n                .build(subset: .product(productToInstall.name), buildOutputs: [])\n\n            let binPath = try commandState.productsBuildParameters.buildPath.appending(component: productToInstall.name)\n            let finalBinPath = swiftpmBinDir.appending(component: binPath.basename)\n            try commandState.fileSystem.copy(from: binPath, to: finalBinPath)\n\n            print(\"Executable product `\\(productToInstall.name)` was successfully installed to \\(finalBinPath).\")\n        }\n    }\n\n    struct Uninstall: SwiftCommand {\n        static let configuration = CommandConfiguration(\n            commandName: \"experimental-uninstall\",\n            abstract: \"Offers the ability to uninstall executable products previously installed by `swift package experimental-install`.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup\n        var globalOptions: GlobalOptions\n\n        @Argument(help: \"Name of the executable to uninstall.\")\n        var name: String\n\n        func run(_ tool: SwiftCommandState) throws {\n            let alreadyInstalled = (try? InstalledPackageProduct.installedProducts(tool.fileSystem)) ?? []\n\n            guard let removedExecutable = alreadyInstalled.first(where: { $0.name == name }) else {\n                // The installed executable doesn't exist - let the user know, and stop here.\n                throw StringError(\"No such installed executable as \\(name)\")\n            }\n\n            try tool.fileSystem.removeFileTree(removedExecutable.path)\n            print(\"Executable product `\\(self.name)` was successfully uninstalled from \\(removedExecutable.path).\")\n        }\n    }\n}\n\nprivate struct InstalledPackageProduct {\n    static func installedProducts(_ fileSystem: FileSystem) throws -> [InstalledPackageProduct] {\n        let binPath = try fileSystem.getOrCreateSwiftPMInstalledBinariesDirectory()\n\n        let contents = ((try? fileSystem.getDirectoryContents(binPath)) ?? [])\n            .map { binPath.appending($0) }\n\n        return contents.map { path in\n            InstalledPackageProduct(path: .init(path))\n        }\n    }\n\n    /// The name of this installed product, being the basename of the path.\n    var name: String {\n        self.path.basename\n    }\n\n    /// Path of the executable.\n    let path: AbsolutePath\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Learn.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageModel\n\nextension SwiftPackageCommand {\n    struct Learn: AsyncSwiftCommand {\n\n        @OptionGroup()\n        var globalOptions: GlobalOptions\n\n        static let configuration = CommandConfiguration(\n            abstract: \"Learn about Swift and this package.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        func files(fileSystem: FileSystem, in directory: AbsolutePath, fileExtension: String? = nil) throws -> [AbsolutePath] {\n            guard fileSystem.isDirectory(directory) else {\n                return []\n            }\n\n            let files = try fileSystem.getDirectoryContents(directory)\n                .map { try AbsolutePath(validating: $0, relativeTo: directory) }\n                .filter { fileSystem.isFile($0) }\n\n            guard let fileExtension else {\n                return files\n            }\n\n            return files.filter { $0.extension == fileExtension }\n        }\n\n        func subdirectories(fileSystem: FileSystem, in directory: AbsolutePath) throws -> [AbsolutePath] {\n            guard fileSystem.isDirectory(directory) else {\n                return []\n            }\n            return try fileSystem.getDirectoryContents(directory)\n                .map { try AbsolutePath(validating: $0, relativeTo: directory) }\n                .filter { fileSystem.isDirectory($0) }\n        }\n\n        func loadSnippetsAndSnippetGroups(fileSystem: FileSystem, from package: ResolvedPackage) async throws -> [SnippetGroup] {\n            let snippetsDirectory = package.path.appending(\"Snippets\")\n            guard fileSystem.isDirectory(snippetsDirectory) else {\n                return []\n            }\n\n            let topLevelSnippets = try files(fileSystem: fileSystem, in: snippetsDirectory, fileExtension: \"swift\")\n                .map { try Snippet(parsing: $0) }\n\n            let topLevelSnippetGroup = SnippetGroup(name: \"Getting Started\",\n                                                    baseDirectory: snippetsDirectory,\n                                                    snippets: topLevelSnippets,\n                                                    explanation: \"\")\n\n            let subdirectoryGroups = try subdirectories(fileSystem: fileSystem, in: snippetsDirectory)\n                .map { subdirectory -> SnippetGroup in\n                    let snippets = try files(fileSystem: fileSystem, in: subdirectory, fileExtension: \"swift\")\n                        .map { try Snippet(parsing: $0) }\n\n                    let explanationFile = subdirectory.appending(\"Explanation.md\")\n\n                    let snippetGroupExplanation: String\n                    if fileSystem.isFile(explanationFile) {\n                        snippetGroupExplanation = try String(contentsOf: explanationFile.asURL)\n                    } else {\n                        snippetGroupExplanation = \"\"\n                    }\n\n                    return SnippetGroup(name: subdirectory.basename,\n                                        baseDirectory: subdirectory,\n                                        snippets: snippets,\n                                        explanation: snippetGroupExplanation)\n                }\n\n            let snippetGroups = [topLevelSnippetGroup] + subdirectoryGroups.sorted {\n                $0.baseDirectory.basename < $1.baseDirectory.basename\n            }\n\n            return snippetGroups.filter { !$0.snippets.isEmpty }\n        }\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let graph = try await swiftCommandState.loadPackageGraph()\n            let package = graph.rootPackages[graph.rootPackages.startIndex]\n            print(package.products.map { $0.description })\n\n            let snippetGroups = try await loadSnippetsAndSnippetGroups(fileSystem: swiftCommandState.fileSystem, from: package)\n\n            var cardStack = CardStack(package: package, snippetGroups: snippetGroups, swiftCommandState: swiftCommandState)\n\n            await cardStack.run()\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Migrate.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nimport Basics\n\n@_spi(SwiftPMInternal)\nimport CoreCommands\n\nimport Foundation\n\nimport OrderedCollections\n\nimport PackageGraph\nimport PackageModel\n\n@_spi(PackageRefactor)\nimport enum SwiftRefactor.ManifestEditError\n\nimport SPMBuildCore\nimport SwiftFixIt\n\nimport var TSCBasic.stdoutStream\n\nstruct MigrateOptions: ParsableArguments {\n    @Option(\n        name: .customLong(\"target\"),\n        help: \"A comma-separated list of targets to migrate. (default: all Swift targets)\"\n    )\n    var _targets: String?\n\n    var targets: OrderedSet<String> {\n        self._targets.flatMap { OrderedSet($0.components(separatedBy: \",\")) } ?? []\n    }\n\n    @Option(\n        name: .customLong(\"to-feature\"),\n        help: \"A comma-separated list of Swift language features to migrate to.\"\n    )\n    var _features: String\n\n    var features: Set<String> {\n        Set(self._features.components(separatedBy: \",\"))\n    }\n}\n\nextension SwiftPackageCommand {\n    struct Migrate: AsyncSwiftCommand {\n        package static let configuration = CommandConfiguration(\n            abstract: \"Migrate a package or its individual targets to use the given set of features.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        public var globalOptions: GlobalOptions\n\n        @OptionGroup()\n        var options: MigrateOptions\n\n        public func run(_ swiftCommandState: SwiftCommandState) async throws {\n            // First, validate and resolve the requested feature names.\n            let features = try self.resolveRequestedFeatures(swiftCommandState)\n\n            let buildSystem = try await createBuildSystem(\n                swiftCommandState,\n                targets: self.options.targets,\n                features: features\n            )\n\n            // Compute the set of targets to migrate.\n            let targetsToMigrate: Set<String>\n            if self.options.targets.isEmpty {\n                let graph = try await buildSystem.getPackageGraph()\n                targetsToMigrate = Set(\n                    graph.rootPackages.lazy.map { package in\n                        package.manifest.targets.lazy.filter { target in\n                            // FIXME: Plugin target init does not have Swift settings.\n                            // Exclude them from migration.\n                            target.type != .plugin\n                        }.map(\\.name)\n                    }.joined()\n                )\n            } else {\n                targetsToMigrate = Set(self.options.targets.elements)\n            }\n\n            // Next, let's build the requested targets or, if none were given,\n            // the whole project to get diagnostic files.\n            print(\"> Starting the build\")\n            var diagnosticFiles: [[AbsolutePath]] = []\n            if self.options.targets.isEmpty {\n                // No targets were requested. Build everything.\n                let buildResult = try await buildSystem.build(subset: .allIncludingTests, buildOutputs: [])\n                for (target, files) in try buildResult.serializedDiagnosticPathsByTargetName.get() {\n                    if targetsToMigrate.contains(target) {\n                        diagnosticFiles.append(files)\n                    }\n                }\n            } else {\n                // Build only requested targets.\n                for target in self.options.targets.elements {\n                    // TODO: It would be nice if BuildSubset had a case for an\n                    // array of targets so that we can move the build out of\n                    // this enclosing if/else and avoid repetition.\n                    let buildResult = try await buildSystem.build(subset: .target(target), buildOutputs: [])\n                    for (target, files) in try buildResult.serializedDiagnosticPathsByTargetName.get() {\n                        if targetsToMigrate.contains(target) {\n                            diagnosticFiles.append(files)\n                        }\n                    }\n                }\n            }\n\n            print(\"> Applying fix-its\")\n            var summary = SwiftFixIt.Summary(numberOfFixItsApplied: 0, numberOfFilesChanged: 0)\n            let fixItDuration = try ContinuousClock().measure {\n                let applier = try SwiftFixIt(\n                    diagnosticFiles: diagnosticFiles.joined(),\n                    categories: Set(features.flatMap(\\.categories)),\n                    excludedSourceDirectories: [swiftCommandState.scratchDirectory],\n                    fileSystem: swiftCommandState.fileSystem\n                )\n                summary = try applier.applyFixIts()\n            }\n\n            // Report the changes.\n            do {\n                var message = \"> Applied \\(summary.numberOfFixItsApplied) fix-it\"\n                if summary.numberOfFixItsApplied != 1 {\n                    message += \"s\"\n                }\n                message += \" in \\(summary.numberOfFilesChanged) file\"\n                if summary.numberOfFilesChanged != 1 {\n                    message += \"s\"\n                }\n                message += \" (\"\n                message += fixItDuration.formatted(\n                    .units(\n                        allowed: [.seconds],\n                        width: .narrow,\n                        fractionalPart: .init(lengthLimits: 0 ... 3, roundingRule: .up)\n                    )\n                )\n                message += \")\"\n\n                print(message)\n            }\n\n            // Once the fix-its were applied, it's time to update the\n            // manifest with newly adopted feature settings.\n            //\n            // Loop over a sorted array to produce deterministic results and\n            // order of diagnostics.\n            print(\"> Updating manifest\")\n            for target in targetsToMigrate.sorted() {\n                swiftCommandState.observabilityScope.emit(debug: \"Adding feature(s) to '\\(target)'\")\n                try self.updateManifest(\n                    for: target,\n                    add: features,\n                    using: swiftCommandState\n                )\n            }\n        }\n\n        /// Resolves the requested feature names.\n        ///\n        /// - Returns: An array of resolved features, sorted by name.\n        private func resolveRequestedFeatures(\n            _ swiftCommandState: SwiftCommandState\n        ) throws -> [SwiftCompilerFeature] {\n            let toolchain = try swiftCommandState.productsBuildParameters.toolchain\n\n            // Query the compiler for supported features.\n            let supportedFeatures = try toolchain.swiftCompilerSupportedFeatures\n\n            var resolvedFeatures: [SwiftCompilerFeature] = []\n\n            // Resolve the requested feature names, validating that they are\n            // supported by the compiler and migratable.\n            for name in self.options.features {\n                let feature = supportedFeatures.first { $0.name == name }\n\n                guard let feature else {\n                    let migratableCommaSeparatedFeatures = supportedFeatures\n                        .filter(\\.migratable)\n                        .map(\\.name)\n                        .sorted()\n                        .joined(separator: \", \")\n\n                    throw ValidationError(\n                        \"Unsupported feature '\\(name)'. Available features: \\(migratableCommaSeparatedFeatures)\"\n                    )\n                }\n\n                guard feature.migratable else {\n                    throw ValidationError(\"Feature '\\(name)' is not migratable\")\n                }\n\n                resolvedFeatures.append(feature)\n            }\n\n            return resolvedFeatures.sorted { lhs, rhs in\n                lhs.name < rhs.name\n            }\n        }\n\n        private func createBuildSystem(\n            _ swiftCommandState: SwiftCommandState,\n            targets: OrderedSet<String>,\n            features: [SwiftCompilerFeature]\n        ) async throws -> BuildSystem {\n            let toolsBuildParameters = try swiftCommandState.toolsBuildParameters\n            let destinationBuildParameters = try swiftCommandState.productsBuildParameters\n\n            let modulesGraph = try await swiftCommandState.loadPackageGraph()\n\n            let addFeaturesToModule = { (module: ResolvedModule) in\n                for feature in features {\n                    module.underlying.buildSettings.add(.init(values: feature.migrationFlags), for: .OTHER_SWIFT_FLAGS)\n                }\n            }\n\n            if !targets.isEmpty {\n                targets.lazy.compactMap {\n                    modulesGraph.module(for: $0)\n                }.forEach(addFeaturesToModule)\n            } else {\n                for package in modulesGraph.rootPackages {\n                    package.modules.filter {\n                        $0.type != .plugin\n                    }.forEach(addFeaturesToModule)\n                }\n            }\n\n            return try await swiftCommandState.createBuildSystem(\n                // Don't attempt to cache manifests with temporary\n                // feature flags added just for migration purposes.\n                cacheBuildManifest: false,\n                productsBuildParameters: destinationBuildParameters,\n                toolsBuildParameters: toolsBuildParameters,\n                // command result output goes on stdout\n                // ie \"swift build\" should output to stdout\n                packageGraphLoader: {\n                    modulesGraph\n                },\n                outputStream: TSCBasic.stdoutStream,\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n        }\n\n        private func updateManifest(\n            for target: String,\n            add features: [SwiftCompilerFeature],\n            using swiftCommandState: SwiftCommandState\n        ) throws {\n            typealias SwiftSetting = SwiftPackageCommand.AddSetting.SwiftSetting\n\n            let settings: [(SwiftSetting, String)] = try features.map {\n                (try $0.swiftSetting, $0.name)\n            }\n\n            do {\n                try SwiftPackageCommand.AddSetting.editSwiftSettings(\n                    of: target,\n                    using: swiftCommandState,\n                    settings,\n                    verbose: !self.globalOptions.logging.quiet\n                )\n            } catch {\n                var message =\n                    \"Could not update manifest to enable requested features for target '\\(target)' (\\(error))\"\n\n                // Do not suggest manual addition if something else is wrong or\n                // if the error implies that it cannot be done.\n                if let error = error as? ManifestEditError {\n                    switch error {\n                    case .cannotFindPackage,\n                         .cannotAddSettingsToPluginTarget,\n                         .existingDependency,\n                         .malformedManifest:\n                        break\n                    case .cannotFindArrayLiteralArgument,\n                         // This means the target could not be found\n                         // syntactically, not that it does not exist.\n                         .cannotFindTargets,\n                         .cannotFindTarget:\n                        let settings = try features.map {\n                            try $0.swiftSettingDescription\n                        }.joined(separator: \", \")\n\n                        message += \"\"\"\n                        . Please enable them manually by adding the following Swift settings to the target: \\\n                        '\\(settings)'\n                        \"\"\"\n                    }\n                }\n\n                swiftCommandState.observabilityScope.emit(error: message)\n            }\n        }\n\n        public init() {}\n    }\n}\n\nfileprivate extension SwiftCompilerFeature {\n    /// Produce the set of command-line flags to pass to the compiler to enable migration for this feature.\n    var migrationFlags: [String] {\n        precondition(migratable)\n\n        switch self {\n        case .upcoming(name: let name, migratable: _, categories: _, enabledIn: _):\n            return [\"-Xfrontend\", \"-enable-upcoming-feature\", \"-Xfrontend\", \"\\(name):migrate\"]\n        case .experimental(name: let name, migratable: _, categories: _):\n            return [\"-Xfrontend\", \"-enable-experimental-feature\", \"-Xfrontend\", \"\\(name):migrate\"]\n        case .optional(name: _, migratable: _, categories: _, flagName: let flagName):\n            let flags = flagName.split(separator: \" \")\n            var resultFlags: [String] = []\n            for (index, flag) in flags.enumerated() {\n                resultFlags.append(\"-Xfrontend\")\n                if index == flags.endIndex - 1 {\n                    resultFlags.append(String(flag) + \":migrate\")\n                } else {\n                    resultFlags.append(String(flag))\n                }\n            }\n\n            return resultFlags\n        }\n    }\n\n    /// Produce the Swift setting corresponding to this compiler feature.\n    var swiftSetting: SwiftPackageCommand.AddSetting.SwiftSetting {\n        get throws {\n            switch self {\n            case .upcoming:\n                return .upcomingFeature\n            case .experimental:\n                return .experimentalFeature\n            case .optional(name: \"StrictMemorySafety\", migratable: _, categories: _, flagName: _):\n                return .strictMemorySafety\n            case .optional(name: let name, migratable: _, categories: _, flagName: _):\n                throw InternalError(\"Unsupported optional feature: \\(name)\")\n            }\n        }\n    }\n\n    var swiftSettingDescription: String {\n        get throws {\n            switch self {\n            case .upcoming(name: let name, migratable: _, categories: _, enabledIn: _):\n                return #\".enableUpcomingFeature(\"\\#(name)\")\"#\n            case .experimental(name: let name, migratable: _, categories: _):\n                return #\".enableExperimentalFeature(\"\\#(name)\")\"#\n            case .optional(name: \"StrictMemorySafety\", migratable: _, categories: _, flagName: _):\n                return \".strictMemorySafety()\"\n            case .optional(name: let name, migratable: _, categories: _, flagName: _):\n                throw InternalError(\"Unsupported optional feature: \\(name)\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/PluginCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport _Concurrency\nimport CoreCommands\nimport Dispatch\nimport SPMBuildCore\nimport PackageGraph\nimport PackageModel\nimport TSCBasic\nimport TSCUtility\nimport Workspace\n\nstruct PluginCommand: AsyncSwiftCommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"plugin\",\n        abstract: \"Invoke a command plugin or perform other actions on command plugins.\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    @Flag(\n        name: .customLong(\"list\"),\n        help: \"List the available command plugins.\"\n    )\n    var listCommands: Bool = false\n\n    struct PluginOptions: ParsableArguments {\n        @Flag(\n            name: .customLong(\"allow-writing-to-package-directory\"),\n            help: \"Allow the plugin to write to the package directory.\"\n        )\n        var allowWritingToPackageDirectory: Bool = false\n\n        @Option(\n            name: .customLong(\"allow-writing-to-directory\"),\n            help: \"Allow the plugin to write to an additional directory.\"\n        )\n        var additionalAllowedWritableDirectories: [String] = []\n\n        enum NetworkPermission: EnumerableFlag, ExpressibleByArgument {\n            static var allCases: [PluginCommand.PluginOptions.NetworkPermission] {\n                return [.none, .local(ports: []), .all(ports: []), .docker, .unixDomainSocket]\n            }\n\n            case none\n            case local(ports: [Int])\n            case all(ports: [Int])\n            case docker\n            case unixDomainSocket\n\n            init?(argument: String) {\n                let arg = argument.lowercased()\n                switch arg {\n                case \"none\":\n                    self = .none\n                case \"docker\":\n                    self = .docker\n                case \"unixdomainsocket\":\n                    self = .unixDomainSocket\n                default:\n                    if \"all\" == arg.prefix(3) {\n                        let ports = Self.parsePorts(arg)\n                        self = .all(ports: ports)\n                    } else if \"local\" == arg.prefix(5) {\n                        let ports = Self.parsePorts(arg)\n                        self = .local(ports: ports)\n                    } else {\n                        return nil\n                    }\n                }\n            }\n\n            static func parsePorts(_ string: String) -> [Int] {\n                let parts = string.split(separator: \":\")\n                guard parts.count == 2 else {\n                    return []\n                }\n                return parts[1]\n                    .split(separator: \",\")\n                    .compactMap{ String($0).spm_chuzzle() }\n                    .compactMap { Int($0) }\n            }\n\n            var remedyDescription: String {\n                switch self {\n                case .none:\n                    return \"none\"\n                case .local(let ports):\n                    if ports.isEmpty {\n                        return \"local\"\n                    } else {\n                        return \"local:\\(ports.map(String.init).joined(separator: \",\"))\"\n                    }\n                case .all(let ports):\n                    if ports.isEmpty {\n                        return \"all\"\n                    } else {\n                        return \"all:\\(ports.map(String.init).joined(separator: \",\"))\"\n                    }\n                case .docker:\n                    return \"docker\"\n                case .unixDomainSocket:\n                    return \"unixDomainSocket\"\n                }\n            }\n        }\n\n        @Option(name: .customLong(\"allow-network-connections\"))\n        var allowNetworkConnections: NetworkPermission = .none\n\n        @Option(\n            name: .customLong(\"package\"),\n            help: \"Limit available plugins to a single package with the given identity.\"\n        )\n        var packageIdentity: String? = nil\n    }\n\n    @OptionGroup()\n    var pluginOptions: PluginOptions\n\n    @Argument(help: \"Verb of the command plugin to invoke.\")\n    var command: String = \"\"\n\n    @Argument(\n        parsing: .captureForPassthrough,\n        help: \"Arguments to pass to the command plugin.\"\n    )\n    var arguments: [String] = []\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        // Check for a missing plugin command verb.\n        if self.command == \"\" && !self.listCommands {\n            throw ValidationError(\"Missing expected plugin command\")\n        }\n\n        // List the available plugins, if asked to.\n        if self.listCommands {\n            let packageGraph = try await swiftCommandState.loadPackageGraph()\n            let allPlugins = PluginCommand.availableCommandPlugins(\n                in: packageGraph,\n                limitedTo: self.pluginOptions.packageIdentity\n            ).map {\n                $0.underlying as! PluginModule\n            }\n            for plugin in allPlugins.sorted(by: { $0.name < $1.name }) {\n                guard case .command(let intent, _) = plugin.capability else { continue }\n                var line = \"‘\\(intent.invocationVerb)’ (plugin ‘\\(plugin.name)’\"\n                if let package = packageGraph.packages\n                    .first(where: { $0.modules.contains(where: { $0.name == plugin.name }) })\n                {\n                    line += \" in package ‘\\(package.manifest.displayName)’\"\n                }\n                line += \")\"\n                print(line)\n            }\n            return\n        }\n\n        try await Self.run(\n            command: self.command,\n            options: self.pluginOptions,\n            arguments: self.arguments,\n            swiftCommandState: swiftCommandState\n        )\n    }\n\n    static func run(\n        command: String,\n        options: PluginOptions,\n        arguments: [String],\n        swiftCommandState: SwiftCommandState\n    ) async throws {\n        // Load the workspace and resolve the package graph.\n        let packageGraph = try await swiftCommandState.loadPackageGraph()\n\n        swiftCommandState.observabilityScope.emit(info: \"Finding plugin for command ‘\\(command)’\")\n        let matchingPlugins = PluginCommand.findPlugins(matching: command, in: packageGraph, limitedTo: options.packageIdentity)\n\n        // Complain if we didn't find exactly one.\n        if matchingPlugins.isEmpty {\n            throw ValidationError(\"Unknown subcommand or plugin name ‘\\(command)’\")\n        } else if matchingPlugins.count > 1 {\n            throw ValidationError(\"\\(matchingPlugins.count) plugins found for ‘\\(command)’\")\n        }\n\n        // handle plugin execution arguments that got passed after the plugin name\n        let unparsedArguments = Array(arguments.drop(while: { $0 == command }))\n        let pluginArguments = try PluginArguments.parse(unparsedArguments)\n        // merge the relevant plugin execution options\n        let pluginOptions = options.merged(with: pluginArguments.pluginOptions)\n        // sandbox is special since its generic not a specific plugin option\n        swiftCommandState.shouldDisableSandbox = swiftCommandState.shouldDisableSandbox || pluginArguments.globalOptions.security\n            .shouldDisableSandbox\n\n        let buildSystemKind =\n            pluginArguments.globalOptions.build.buildSystem != .native ?\n                pluginArguments.globalOptions.build.buildSystem :\n                swiftCommandState.options.build.buildSystem\n\n        // At this point we know we found exactly one command plugin, so we run it. In SwiftPM CLI, we have only one root package.\n        try await PluginCommand.run(\n            plugin: matchingPlugins[0],\n            package: packageGraph.rootPackages[packageGraph.rootPackages.startIndex],\n            packageGraph: packageGraph,\n            buildSystem: buildSystemKind,\n            options: pluginOptions,\n            arguments: unparsedArguments,\n            swiftCommandState: swiftCommandState\n        )\n    }\n\n    static func run(\n        plugin: ResolvedModule,\n        package: ResolvedPackage,\n        packageGraph: ModulesGraph,\n        buildSystem buildSystemKind: BuildSystemProvider.Kind,\n        options: PluginOptions,\n        arguments: [String],\n        swiftCommandState: SwiftCommandState\n    ) async throws {\n        let pluginTarget = plugin.underlying as! PluginModule\n\n        swiftCommandState.observabilityScope\n            .emit(\n                info: \"Running command plugin \\(plugin) on package \\(package) with options \\(options) and arguments \\(arguments)\"\n            )\n\n        // The `plugins` directory is inside the workspace's main data directory, and contains all temporary files related to this plugin in the workspace.\n        let pluginsDir = try swiftCommandState.getActiveWorkspace().location.pluginWorkingDirectory\n            .appending(component: plugin.name)\n\n        // The `cache` directory is in the plugin’s directory and is where the plugin script runner caches compiled plugin binaries and any other derived information for this plugin.\n        let pluginScriptRunner = try swiftCommandState.getPluginScriptRunner(\n            customPluginsDir: pluginsDir\n        )\n\n        // The `outputs` directory contains subdirectories for each combination of package and command plugin. Each usage of a plugin has an output directory that is writable by the plugin, where it can write additional files, and to which it can configure tools to write their outputs, etc.\n        let outputDir = pluginsDir.appending(\"outputs\")\n\n        var allowNetworkConnections = [SandboxNetworkPermission(options.allowNetworkConnections)]\n        // Determine the set of directories under which plugins are allowed to write. We always include the output directory.\n        var writableDirectories = [outputDir]\n        if options.allowWritingToPackageDirectory {\n            writableDirectories.append(package.path)\n        }\n\n        // If the plugin requires permissions, we ask the user for approval.\n        // If the sandbox is disabled, we skip the permission prompts.\n        if case .command(_, let permissions) = pluginTarget.capability,\n           !swiftCommandState.shouldDisableSandbox {\n            try permissions.forEach {\n                let permissionString: String\n                let reasonString: String\n                let remedyOption: String\n\n                switch $0 {\n                case .writeToPackageDirectory(let reason):\n                    guard !options.allowWritingToPackageDirectory else { return } // permission already granted\n                    permissionString = \"write to the package directory\"\n                    reasonString = reason\n                    remedyOption = \"--allow-writing-to-package-directory\"\n                case .allowNetworkConnections(let scope, let reason):\n                    guard scope != .none else { return } // no need to prompt\n                    guard options.allowNetworkConnections != .init(scope) else { return } // permission already granted\n\n                    switch scope {\n                    case .all, .local:\n                        let portsString = scope.ports\n                            .isEmpty ? \"on all ports\" :\n                            \"on ports: \\(scope.ports.map { \"\\($0)\" }.joined(separator: \", \"))\"\n                        permissionString = \"allow \\(scope.label) network connections \\(portsString)\"\n                    case .docker, .unixDomainSocket:\n                        permissionString = \"allow \\(scope.label) connections\"\n                    case .none:\n                        permissionString = \"\" // should not be reached\n                    }\n\n                    reasonString = reason\n                    remedyOption =\n                        \"--allow-network-connections \\(PluginCommand.PluginOptions.NetworkPermission(scope).remedyDescription)\"\n                }\n\n                let problem = \"Plugin ‘\\(plugin.name)’ wants permission to \\(permissionString).\"\n                let reason = \"Stated reason: “\\(reasonString)”.\"\n                if swiftCommandState.outputStream.isTTY {\n                    // We can ask the user directly, so we do so.\n                    let query = \"Allow this plugin to \\(permissionString)?\"\n                    swiftCommandState.outputStream.write(\"\\(problem)\\n\\(reason)\\n\\(query) (yes/no) \".utf8)\n                    swiftCommandState.outputStream.flush()\n                    let answer = readLine(strippingNewline: true)\n                    // Throw an error if we didn't get permission.\n                    if answer?.lowercased() != \"yes\" {\n                        throw StringError(\"Plugin was denied permission to \\(permissionString).\")\n                    }\n                } else {\n                    // We can't ask the user, so emit an error suggesting passing the flag.\n                    let remedy = \"Use `\\(remedyOption)` to allow this.\"\n                    throw StringError([problem, reason, remedy].joined(separator: \"\\n\"))\n                }\n\n                switch $0 {\n                case .writeToPackageDirectory:\n                    // Otherwise append the directory to the list of allowed ones.\n                    writableDirectories.append(package.path)\n                case .allowNetworkConnections(let scope, _):\n                    allowNetworkConnections.append(.init(scope))\n                }\n            }\n        }\n\n        for pathString in options.additionalAllowedWritableDirectories {\n            writableDirectories\n                .append(try AbsolutePath(validating: pathString, relativeTo: swiftCommandState.originalWorkingDirectory))\n        }\n\n        // Make sure that the package path is read-only unless it's covered by any of the explicitly writable directories.\n        let readOnlyDirectories = writableDirectories\n            .contains { package.path.isDescendantOfOrEqual(to: $0) } ? [] : [package.path]\n\n        // Use the directory containing the compiler as an additional search directory, and add the $PATH.\n        let toolSearchDirs = [try swiftCommandState.getTargetToolchain().swiftCompilerPath.parentDirectory]\n            + getEnvSearchPaths(pathString: Environment.current[.path], currentWorkingDirectory: .none)\n\n        var buildParameters = try swiftCommandState.toolsBuildParameters\n        buildParameters.buildSystemKind = buildSystemKind\n\n        // Build or bring up-to-date any executable host-side tools on which this plugin depends. Add them and any binary dependencies to the tool-names-to-path map.\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            explicitBuildSystem: buildSystemKind,\n            cacheBuildManifest: false,\n            productsBuildParameters: swiftCommandState.productsBuildParameters,\n            toolsBuildParameters: buildParameters,\n            packageGraphLoader: { packageGraph }\n        )\n\n        let accessibleTools = try await plugin.preparePluginTools(\n            fileSystem: swiftCommandState.fileSystem,\n            environment: buildParameters.buildEnvironment,\n            for: try pluginScriptRunner.hostTriple\n        ) { name, path in\n            // Build the product referenced by the tool, and add the executable to the tool map. Product dependencies are not supported within a package, so if the tool happens to be from the same package, we instead find the executable that corresponds to the product. There is always one, because of autogeneration of implicit executables with the same name as the target if there isn't an explicit one.\n            let buildResult = try await buildSystem.build(subset: .product(name, for: .host), buildOutputs: [.buildPlan])\n\n            if let buildPlan = buildResult.buildPlan {\n                if let builtTool = buildPlan.buildProducts.first(where: {\n                    $0.product.name == name && $0.buildParameters.destination == .host\n                }) {\n                    return try builtTool.binaryPath\n                } else {\n                    return nil\n                }\n            } else {\n                return buildParameters.buildPath.appending(path)\n            }\n        }\n\n        // Set up a delegate to handle callbacks from the command plugin.\n        let pluginDelegate = PluginDelegate(swiftCommandState: swiftCommandState, buildSystem: buildSystemKind, plugin: pluginTarget)\n        let delegateQueue = DispatchQueue(label: \"plugin-invocation\")\n\n        // Run the command plugin.\n\n        // TODO: use region based isolation when swift 6 is available\n        let writableDirectoriesCopy = writableDirectories\n        let allowNetworkConnectionsCopy = allowNetworkConnections\n\n        let buildEnvironment = buildParameters.buildEnvironment\n        let _ = try await pluginTarget.invoke(\n            action: .performCommand(package: package, arguments: arguments),\n            buildEnvironment: buildEnvironment,\n            workers: buildParameters.workers,\n            scriptRunner: pluginScriptRunner,\n            workingDirectory: swiftCommandState.originalWorkingDirectory,\n            outputDirectory: outputDir,\n            toolSearchDirectories: toolSearchDirs,\n            accessibleTools: accessibleTools,\n            writableDirectories: writableDirectoriesCopy,\n            readOnlyDirectories: readOnlyDirectories,\n            allowNetworkConnections: allowNetworkConnectionsCopy,\n            pkgConfigDirectories: swiftCommandState.options.locations.pkgConfigDirectories,\n            sdkRootPath: buildParameters.toolchain.sdkRootPath,\n            fileSystem: swiftCommandState.fileSystem,\n            modulesGraph: packageGraph,\n            observabilityScope: swiftCommandState.observabilityScope,\n            callbackQueue: delegateQueue,\n            delegate: pluginDelegate\n        )\n\n        // TODO: We should also emit a final line of output regarding the result.\n    }\n\n    static func availableCommandPlugins(in graph: ModulesGraph, limitedTo packageIdentity: String?) -> [ResolvedModule] {\n        // All targets from plugin products of direct dependencies are \"available\".\n        let directDependencyPackages = graph.rootPackages.flatMap {\n            $0.dependencies\n        }.filter {\n            $0.matching(identity: packageIdentity)\n        }.compactMap {\n            graph.package(for: $0)\n        }\n\n        let directDependencyPluginTargets = directDependencyPackages.flatMap { $0.products.filter { $0.type == .plugin } }.flatMap { $0.modules }\n        // As well as any plugin targets in root packages.\n        let rootPackageTargets = graph.rootPackages.filter { $0.identity.matching(identity: packageIdentity) }.flatMap { $0.modules }\n        return (directDependencyPluginTargets + rootPackageTargets).filter {\n            guard let plugin = $0.underlying as? PluginModule else {\n                return false\n            }\n\n            return switch plugin.capability {\n            case .buildTool: false\n            case .command: true\n            }\n        }\n    }\n\n    static func findPlugins(matching verb: String, in graph: ModulesGraph, limitedTo packageIdentity: String?) -> [ResolvedModule] {\n        // Find and return the command plugins that match the command.\n        Self.availableCommandPlugins(in: graph, limitedTo: packageIdentity).filter {\n            let plugin = $0.underlying as! PluginModule\n            // Filter out any non-command plugins and any whose verb is different.\n            guard case .command(let intent, _) = plugin.capability else { return false }\n            return verb == intent.invocationVerb\n        }\n    }\n}\n\n// helper to parse plugin arguments passed after the plugin name\nstruct PluginArguments: ParsableCommand {\n    static var configuration: CommandConfiguration {\n        .init(helpNames: [])\n    }\n\n    @OptionGroup\n    var globalOptions: GlobalOptions\n\n    @OptionGroup()\n    var pluginOptions: PluginCommand.PluginOptions\n\n    @Argument(parsing: .allUnrecognized)\n    var remaining: [String] = []\n}\n\nextension PluginCommandIntent {\n    var invocationVerb: String {\n        switch self {\n        case .documentationGeneration:\n            return \"generate-documentation\"\n        case .sourceCodeFormatting:\n            return \"format-source-code\"\n        case .custom(let verb, _):\n            return verb\n        }\n    }\n}\n\nextension SandboxNetworkPermission {\n    init(_ scope: PluginNetworkPermissionScope) {\n        switch scope {\n        case .none: self = .none\n        case .local(let ports): self = .local(ports: ports)\n        case .all(let ports): self = .all(ports: ports)\n        case .docker: self = .docker\n        case .unixDomainSocket: self = .unixDomainSocket\n        }\n    }\n}\n\nextension PluginCommand.PluginOptions.NetworkPermission {\n    fileprivate init(_ scope: PluginNetworkPermissionScope) {\n        switch scope {\n        case .unixDomainSocket: self = .unixDomainSocket\n        case .docker: self = .docker\n        case .none: self = .none\n        case .all(let ports): self = .all(ports: ports)\n        case .local(let ports): self = .local(ports: ports)\n        }\n    }\n}\n\nextension SandboxNetworkPermission {\n    init(_ permission: PluginCommand.PluginOptions.NetworkPermission) {\n        switch permission {\n        case .none: self = .none\n        case .local(let ports): self = .local(ports: ports)\n        case .all(let ports): self = .all(ports: ports)\n        case .docker: self = .docker\n        case .unixDomainSocket: self = .unixDomainSocket\n        }\n    }\n}\n\nextension PackageIdentity {\n    fileprivate func matching(identity: String?) -> Bool {\n        if let identity {\n            return self == .plain(identity)\n        } else {\n            return true\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/ResetCommands.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CoreCommands\nimport Workspace\n\nextension SwiftPackageCommand {\n    struct Clean: SwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Delete build artifacts.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            try swiftCommandState.getActiveWorkspace().clean(observabilityScope: swiftCommandState.observabilityScope)\n        }\n    }\n\n    struct PurgeCache: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Purge the global repository cache.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            try await swiftCommandState.purgeCaches(observabilityScope: swiftCommandState.observabilityScope)\n        }\n    }\n\n    struct Reset: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Reset the complete cache/build directory.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            try await swiftCommandState.getActiveWorkspace().reset(observabilityScope: swiftCommandState.observabilityScope)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Resolve.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport TSCUtility\nimport Workspace\n\nimport enum PackageModel.TraitConfiguration\n\nextension SwiftPackageCommand {\n    struct ResolveOptions: ParsableArguments {\n        @Option(help: \"The version to resolve at.\", transform: { Version($0) })\n        var version: Version?\n\n        @Option(help: \"The branch to resolve at.\")\n        var branch: String?\n\n        @Option(help: \"The revision to resolve at.\")\n        var revision: String?\n\n        @Argument(help: \"The name of the package to resolve.\")\n        var packageName: String?\n    }\n\n    struct Resolve: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Resolve package dependencies.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @OptionGroup()\n        var resolveOptions: ResolveOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            // If a package is provided, use that to resolve the dependencies.\n            if let packageName = resolveOptions.packageName {\n                let workspace = try swiftCommandState.getActiveWorkspace()\n                try await workspace.resolve(\n                    packageName: packageName,\n                    root: swiftCommandState.getWorkspaceRoot(),\n                    version: resolveOptions.version,\n                    branch: resolveOptions.branch,\n                    revision: resolveOptions.revision,\n                    observabilityScope: swiftCommandState.observabilityScope\n                )\n                if swiftCommandState.observabilityScope.errorsReported {\n                    throw ExitCode.failure\n                }\n            } else {\n                // Otherwise, run a normal resolve.\n                try await swiftCommandState.resolve()\n            }\n        }\n    }\n\n    struct Fetch: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            shouldDisplay: false,\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .private)\n        var globalOptions: GlobalOptions\n\n        @OptionGroup()\n        var resolveOptions: ResolveOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            swiftCommandState.observabilityScope.emit(warning: \"'fetch' command is deprecated; use 'resolve' instead\")\n\n            let resolveCommand = Resolve(globalOptions: _globalOptions, resolveOptions: _resolveOptions)\n            try await resolveCommand.run(swiftCommandState)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/ShowDependencies.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageGraph\n\nimport class TSCBasic.LocalFileOutputByteStream\nimport protocol TSCBasic.OutputByteStream\nimport var TSCBasic.stdoutStream\n\nextension SwiftPackageCommand {\n    struct ShowDependencies: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Print the resolved dependency graph.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Option(help: \"Set the output format.\")\n        var format: ShowDependenciesMode = .text\n\n        @Option(name: [.long, .customShort(\"o\") ],\n                help: \"The absolute or relative path to output the resolved dependency graph.\")\n        var outputPath: AbsolutePath?\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let graph = try await swiftCommandState.loadPackageGraph()\n            // command's result output goes on stdout\n            // ie \"swift package show-dependencies\" should output to stdout\n            let stream: OutputByteStream = try outputPath.map { try LocalFileOutputByteStream($0) } ?? TSCBasic.stdoutStream\n            Self.dumpDependenciesOf(\n                graph: graph,\n                rootPackage: graph.rootPackages[graph.rootPackages.startIndex],\n                mode: format,\n                on: stream\n            )\n        }\n\n        static func dumpDependenciesOf(\n            graph: ModulesGraph,\n            rootPackage: ResolvedPackage,\n            mode: ShowDependenciesMode,\n            on stream: OutputByteStream\n        ) {\n            let dumper: DependenciesDumper\n            switch mode {\n            case .text:\n                dumper = PlainTextDumper()\n            case .dot:\n                dumper = DotDumper()\n            case .json:\n                dumper = JSONDumper()\n            case .flatlist:\n                dumper = FlatListDumper()\n            }\n            dumper.dump(graph: graph, dependenciesOf: rootPackage, on: stream)\n            stream.flush()\n        }\n\n        enum ShowDependenciesMode: String, RawRepresentable, CustomStringConvertible, ExpressibleByArgument, CaseIterable {\n            case text, dot, json, flatlist\n\n            public init?(rawValue: String) {\n                switch rawValue.lowercased() {\n                case \"text\":\n                    self = .text\n                case \"dot\":\n                    self = .dot\n                case \"json\":\n                    self = .json\n                case \"flatlist\":\n                    self = .flatlist\n                default:\n                    return nil\n                }\n            }\n\n            public var description: String {\n                switch self {\n                case .text: return \"text\"\n                case .dot: return \"dot\"\n                case .json: return \"json\"\n                case .flatlist: return \"flatlist\"\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/ShowExecutables.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport PackageGraph\nimport Workspace\n\nstruct ShowExecutables: AsyncSwiftCommand {\n    static let configuration = CommandConfiguration(\n        abstract: \"List the available executables from this package.\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    @Option(help: \"Set the output format.\")\n    var format: ShowExecutablesMode = .flatlist\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        let packageGraph = try await swiftCommandState.loadPackageGraph()\n        let rootPackages = packageGraph.rootPackages.map { $0.identity }\n\n        let executables = packageGraph.allProducts.filter({\n            $0.type == .executable || $0.type == .snippet\n        }).map { product -> Executable in\n            if !rootPackages.contains(product.packageIdentity) {\n                return Executable(package: product.packageIdentity.description, name: product.name)\n            } else {\n                return Executable(package: Optional<String>.none, name: product.name)\n            }\n        }.sorted(by: {$0.name < $1.name})\n\n        switch self.format {\n        case .flatlist:\n            for executable in executables {\n                if let package = executable.package {\n                    print(\"\\(executable.name) (\\(package))\")\n                } else {\n                    print(executable.name)\n                }\n            }\n\n        case .json:\n            let encoder = JSONEncoder()\n            let data = try encoder.encode(executables)\n            if let output = String(data: data, encoding: .utf8) {\n                print(output)\n            }\n        }\n    }\n\n    struct Executable: Codable {\n        var package: String?\n        var name: String\n    }\n\n    enum ShowExecutablesMode: String, RawRepresentable, CustomStringConvertible, ExpressibleByArgument, CaseIterable {\n        case flatlist, json\n\n        public init?(rawValue: String) {\n            switch rawValue.lowercased() {\n            case \"flatlist\":\n                self = .flatlist\n            case \"json\":\n                self = .json\n            default:\n                return nil\n            }\n        }\n\n        public var description: String {\n            switch self {\n            case .flatlist: return \"flatlist\"\n            case .json: return \"json\"\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/ShowTraits.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport PackageGraph\nimport Workspace\n\nstruct ShowTraits: AsyncSwiftCommand {\n    static let configuration = CommandConfiguration(\n        abstract: \"List the available traits for a package.\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    @Option(help: \"Show traits for any package id in the transitive dependencies.\")\n    var packageId: String?\n\n    @Option(help: \"Set the output format.\")\n    var format: ShowTraitsMode = .text\n\n    func run(_ swiftCommandState: SwiftCommandState) async throws {\n        let packageGraph = try await swiftCommandState.loadPackageGraph()\n\n        let traits = if let packageId {\n            packageGraph.packages.filter({ $0.identity.description == packageId }).flatMap( { $0.manifest.traits } ).sorted(by: {$0.name < $1.name} )\n        } else {\n            packageGraph.rootPackages.flatMap( { $0.manifest.traits } ).sorted(by: {$0.name < $1.name} )\n        }\n\n        switch self.format {\n        case .text:\n            let defaultTraits = traits.filter( { $0.isDefault } ).flatMap( { $0.enabledTraits })\n\n            for trait in traits {\n                guard !trait.isDefault else {\n                    continue\n                }\n\n                print(\"\\(trait.name)\\(trait.description ?? \"\" != \"\" ? \" - \" + trait.description! : \"\")\\(defaultTraits.contains(trait.name) ? \" (default)\" : \"\")\")\n            }\n\n        case .json:\n            let encoder = JSONEncoder()\n            encoder.outputFormatting = .sortedKeys\n\n            let data = try encoder.encode(traits)\n            if let output = String(data: data, encoding: .utf8) {\n                print(output)\n            }\n        }\n    }\n\n    enum ShowTraitsMode: String, RawRepresentable, CustomStringConvertible, ExpressibleByArgument, CaseIterable {\n        case text, json\n\n        public init?(rawValue: String) {\n            switch rawValue.lowercased() {\n            case \"text\":\n                self = .text\n            case \"json\":\n                self = .json\n            default:\n                return nil\n            }\n        }\n\n        public var description: String {\n            switch self {\n            case .text: return \"text\"\n            case .json: return \"json\"\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/SwiftPackageCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SourceControl\nimport SPMBuildCore\nimport Workspace\nimport XCBuildSupport\n\nimport enum TSCUtility.Diagnostics\n\n/// swift-package tool namespace\npublic struct SwiftPackageCommand: AsyncParsableCommand {\n\n    private static var subcommands: [any ParsableCommand.Type] = {\n        var subcommands: [any ParsableCommand.Type] = [\n            AddDependency.self,\n            AddProduct.self,\n            AddTarget.self,\n            AddTargetDependency.self,\n            AddSetting.self,\n            AuditBinaryArtifact.self,\n            Clean.self,\n            PurgeCache.self,\n            Reset.self,\n            Update.self,\n            Describe.self,\n            Init.self,\n            Format.self,\n            Migrate.self,\n\n            Install.self,\n            Uninstall.self,\n\n            APIDiff.self,\n            DeprecatedAPIDiff.self,\n            DumpSymbolGraph.self,\n            DumpPIF.self,\n            DumpPackage.self,\n\n            Edit.self,\n            Unedit.self,\n\n            Config.self,\n            Resolve.self,\n            Fetch.self,\n\n            GenerateSbom.self, \n            \n            ShowDependencies.self,\n            ShowExecutables.self,\n            ShowTraits.self,\n            ToolsVersionCommand.self,\n            ComputeChecksum.self,\n            ArchiveSource.self,\n            CompletionCommand.self,\n            PluginCommand.self,\n\n            DefaultCommand.self,\n        ]\n        if ProcessInfo.processInfo.environment[\"SWIFTPM_ENABLE_SNIPPETS\"] == \"1\" {\n            subcommands.append(Learn.self)\n        }\n        #if canImport(LanguageServerProtocol)\n        subcommands.append(BuildServer.self)\n        #endif\n        return subcommands\n    }()\n\n    public static var configuration = CommandConfiguration(\n        commandName: \"package\",\n        _superCommandName: \"swift\",\n        abstract: \"Perform operations on Swift packages.\",\n        discussion: \"SEE ALSO: swift build, swift run, swift test \\n(Run this command without --help to see possible dynamic plugin commands.)\",\n        version: SwiftVersion.current.completeDisplayString,\n        subcommands: Self.subcommands,\n        defaultSubcommand: DefaultCommand.self,\n        helpNames: []\n    )\n\n    @OptionGroup()\n    var globalOptions: GlobalOptions\n\n    public static var _errorLabel: String { \"error\" }\n\n    public init() {}\n}\n\nextension SwiftPackageCommand {\n    // This command is the default when no other subcommand is passed. It is not shown in the help and is never invoked\n    // directly.\n    struct DefaultCommand: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            commandName: nil,\n            shouldDisplay: false\n        )\n\n        @OptionGroup(visibility: .private)\n        var globalOptions: GlobalOptions\n\n        @OptionGroup()\n        var pluginOptions: PluginCommand.PluginOptions\n\n        @Argument(parsing: .captureForPassthrough)\n        var remaining: [String] = []\n\n        @Flag(name: [.short, .long, .customLong(\"help\", withSingleDash: true)])\n        var help = false\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            // See if have a possible plugin command.\n            guard !self.help, let command = remaining.first else {\n                print(SwiftPackageCommand.helpMessage())\n                do {\n                    let pluginCommands = try await fetchAvailablePluginCommands(swiftCommandState: swiftCommandState)\n                    if !pluginCommands.isEmpty {\n                        print(\"\\nAVAILABLE PLUGIN COMMANDS:\")\n                        for cmd in pluginCommands {\n                            let formattedDescription = \"\\(cmd.name)\"\n                                .padding(toLength: 24, withPad: \" \", startingAt: 0) + cmd.description\n                            print(\"  \" + formattedDescription)\n                        }\n                    }\n                } catch {} // fail silently as user does not need to know we could not fetch plugin command's for the\n                // help screen\n                return\n            }\n\n            // Check for edge cases and unknown options to match the behavior in the absence of plugins.\n            if command.isEmpty {\n                throw ValidationError(\"Unknown argument '\\(command)'\")\n            } else if command.starts(with: \"-\") {\n                throw ValidationError(\"Unknown option '\\(command)'\")\n            }\n\n            // Otherwise see if we can find a plugin.\n            try await PluginCommand.run(\n                command: command,\n                options: self.pluginOptions,\n                arguments: self.remaining,\n                swiftCommandState: swiftCommandState\n            )\n        }\n\n        private func fetchAvailablePluginCommands(swiftCommandState: SwiftCommandState) async throws -> [(\n            name: String,\n            description: String\n        )] {\n            let packageGraph = try await swiftCommandState.loadPackageGraph()\n            let allPlugins = PluginCommand.availableCommandPlugins(\n                in: packageGraph,\n                limitedTo: self.pluginOptions.packageIdentity\n            ).map {\n                $0.underlying as! PluginModule\n            }\n\n            var result: [(String, String)] = []\n\n            for plugin in allPlugins.sorted(by: { $0.name < $1.name }) {\n                guard case .command(let intent, _) = plugin.capability else { continue }\n                let commandName = intent.invocationVerb\n                var commandDescription = \"(plugin ‘\\(plugin.name)’\"\n\n                if let package = packageGraph.packages\n                    .first(where: { $0.modules.contains(where: { $0.name == plugin.name }) })\n                {\n                    commandDescription += \" in package ‘\\(package.manifest.displayName)’\"\n                }\n                commandDescription += \")\"\n\n                result.append((commandName, commandDescription))\n            }\n\n            return result\n        }\n    }\n}\n\nextension PluginCommand.PluginOptions {\n    func merged(with other: Self) -> Self {\n        // validate against developer mistake\n        assert(\n            Mirror(reflecting: self).children.count == 4,\n            \"Property added to PluginOptions without updating merged(with:)!\"\n        )\n        // actual merge\n        var merged = self\n        merged.allowWritingToPackageDirectory = merged.allowWritingToPackageDirectory || other\n            .allowWritingToPackageDirectory\n        merged.additionalAllowedWritableDirectories.append(contentsOf: other.additionalAllowedWritableDirectories)\n        if other.allowNetworkConnections != .none {\n            merged.allowNetworkConnections = other.allowNetworkConnections\n        }\n        if other.packageIdentity != nil {\n            merged.packageIdentity = other.packageIdentity\n        }\n        return merged\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/ToolsVersionCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport CoreCommands\nimport PackageLoading\nimport PackageModel\nimport Workspace\n\n// This is named as `ToolsVersionCommand` instead of `ToolsVersion` to avoid naming conflicts, as the latter already\n// exists to denote the version itself.\nstruct ToolsVersionCommand: SwiftCommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"tools-version\",\n        abstract: \"Manipulate tools version of the current package.\",\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var globalOptions: GlobalOptions\n\n    @Flag(help: \"Set tools version of package to the current tools version in use.\")\n    var setCurrent: Bool = false\n\n    @Option(help: \"Set tools version of package to the given value.\")\n    var set: String?\n\n    enum ToolsVersionMode {\n        case display\n        case set(String)\n        case setCurrent\n    }\n\n    var toolsVersionMode: ToolsVersionMode {\n        // TODO: enforce exclusivity\n        if let set {\n            return .set(set)\n        } else if setCurrent {\n            return .setCurrent\n        } else {\n            return .display\n        }\n    }\n\n    func run(_ swiftCommandState: SwiftCommandState) throws {\n        let pkg = try swiftCommandState.getPackageRoot()\n\n        switch toolsVersionMode {\n        case .display:\n            let manifestPath = try ManifestLoader.findManifest(packagePath: pkg, fileSystem: swiftCommandState.fileSystem, currentToolsVersion: .current)\n            let version = try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: swiftCommandState.fileSystem)\n            print(\"\\(version)\")\n\n        case .set(let value):\n            guard let toolsVersion = ToolsVersion(string: value) else {\n                // FIXME: Probably lift this error definition to ToolsVersion.\n                throw ToolsVersionParser.Error.malformedToolsVersionSpecification(.versionSpecifier(.isMisspelt(value)))\n            }\n            try ToolsVersionSpecificationWriter.rewriteSpecification(\n                manifestDirectory: pkg,\n                toolsVersion: toolsVersion,\n                fileSystem: swiftCommandState.fileSystem\n            )\n\n        case .setCurrent:\n            // Write the tools version with current version but with patch set to zero.\n            // We do this to avoid adding unnecessary constraints to patch versions, if\n            // the package really needs it, they can do it using --set option.\n            try ToolsVersionSpecificationWriter.rewriteSpecification(\n                manifestDirectory: pkg,\n                toolsVersion: ToolsVersion.current.zeroedPatch,\n                fileSystem: swiftCommandState.fileSystem\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/PackageCommands/Update.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Dispatch\nimport PackageModel\nimport PackageGraph\nimport Workspace\n\nextension SwiftPackageCommand {\n    struct Update: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Update package dependencies.\",\n            helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n        \n        @Flag(name: [.long, .customShort(\"n\")],\n              help: \"Display the list of dependencies that can be updated.\")\n        var dryRun: Bool = false\n        \n        @Argument(help: \"The packages to update.\")\n        var packages: [String] = []\n        \n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let workspace = try swiftCommandState.getActiveWorkspace()\n            \n            let changes = try await workspace.updateDependencies(\n                root: swiftCommandState.getWorkspaceRoot(),\n                packages: packages,\n                dryRun: dryRun,\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n\n            if self.dryRun, let changes = changes, let resolvedPackagesStore = swiftCommandState.observabilityScope.trap({ try workspace.resolvedPackagesStore.load() }){\n                self.logPackageChanges(changes: changes, store: resolvedPackagesStore)\n            }\n            \n            if !self.dryRun {\n                // Throw if there were errors when loading the graph.\n                // The actual errors will be printed before exiting.\n                guard !swiftCommandState.observabilityScope.errorsReported else {\n                    throw ExitCode.failure\n                }\n            }\n        }\n        \n        private func logPackageChanges(changes: [(PackageReference, Workspace.PackageStateChange)], store: ResolvedPackagesStore) {\n            let changes = changes.filter { $0.1 != .unchanged }\n            \n            var report = \"[Dry-run] \\(changes.count) dependenc\\(changes.count == 1 ? \"y would\" : \"ies would\") change\\(changes.count > 0 ? \":\" : \".\")\"\n            for (package, change) in changes {\n                let currentVersion = store.resolvedPackages[package.identity]?.state.description ?? \"\"\n                switch change {\n                case let .added(state):\n                    report += \"\\n\"\n                    report += \"+ \\(package.identity) \\(state.requirement.prettyPrinted)\"\n                case let .updated(state):\n                    report += \"\\n\"\n                    report += \"~ \\(package.identity) \\(currentVersion) -> \\(package.identity) \\(state.requirement.prettyPrinted)\"\n                case .removed:\n                    report += \"\\n\"\n                    report += \"- \\(package.identity) \\(currentVersion)\"\n                case .unchanged:\n                    continue\n                }\n            }\n            \n            print(report)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/README.md",
    "content": "# Commands Library\n\nThis library defines interfaces to the high-level command line tools.\n"
  },
  {
    "path": "Sources/Commands/Snippets/Card.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A terminal menu that takes up the whole terminal, accepting input and\n/// rendering in response.\nprotocol Card {\n    /// Render the contents to be printed to the terminal.\n    func render() -> String\n\n    /// Accept a line of input from the user's terminal and provide\n    /// an optional ``CardEvent`` which can alter the card stack.\n    func acceptLineInput<S: StringProtocol>(_ line: S) async -> CardEvent?\n\n    /// The input prompt to present to the user when accepting a line of input.\n    var inputPrompt: String? { get }\n}\n\nextension Card {\n    var defaultPrompt: String {\n        return \"Press enter to continue.\"\n    }\n}\n\nextension Card {\n    var inputPrompt: String? {\n        return defaultPrompt\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Snippets/CardEvent.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// An event that alters the card stack after some input from the user.\nenum CardEvent {\n    /// Pop the top card from the stack, providing an optional error that\n    /// may have occurred.\n    case pop(Swift.Error? = nil)\n\n    /// Push a new card onto the stack.\n    case push(Card)\n\n    /// Quit the program, providing an optional error that may have occurred.\n    case quit(Swift.Error? = nil)\n}\n"
  },
  {
    "path": "Sources/Commands/Snippets/CardStack.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport CoreCommands\nimport PackageGraph\nimport PackageModel\n\nimport var TSCBasic.stdoutStream\nimport class TSCBasic.TerminalController\n\nfileprivate extension TerminalController {\n    func clearScreen() {\n        write(\"\\u{001b}[2J\")\n        write(\"\\u{001b}[H\")\n        flush()\n    }\n}\n\n/// A stack of \"cards\" to display one at a time at the command line.\nstruct CardStack {\n    var terminal: TerminalController\n\n    /// The representation of a stack of cards.\n    var cards = [Card]()\n\n    /// The tool used for eventually building and running a chosen snippet.\n    var swiftCommandState: SwiftCommandState\n\n    /// When true, the escape sequence for clearing the terminal should be\n    /// printed first.\n    private var needsToClearScreen = true\n\n    init(package: ResolvedPackage, snippetGroups: [SnippetGroup], swiftCommandState: SwiftCommandState) {\n        // this interaction is done on stdout\n        self.terminal = TerminalController(stream: TSCBasic.stdoutStream)!\n        self.cards = [TopCard(package: package, snippetGroups: snippetGroups, swiftCommandState: swiftCommandState)]\n        self.swiftCommandState = swiftCommandState\n    }\n\n    mutating func push(_ card: Card) {\n        cards.append(card)\n    }\n\n    mutating func pop() {\n        cards.removeLast()\n    }\n\n    mutating func clear() {\n        cards.removeAll()\n    }\n\n    func askForLineInput(prompt: String?) -> String? {\n        let isColorized: Bool = swiftCommandState.options.logging.colorDiagnostics\n\n        if let prompt {\n            isColorized ?\n                print(brightBlack { prompt }.terminalString()) :\n                print(plain { prompt }.terminalString())\n        }\n        isColorized ?\n            terminal.write(\">>> \", inColor: .green, bold: true)\n            : terminal.write(\">>> \", inColor: .noColor, bold: false)\n\n        return readLine(strippingNewline: true)\n    }\n\n    mutating func run() async {\n        var inputFinished = false\n        while !inputFinished {\n            guard let top = cards.last else {\n                break\n            }\n\n            if needsToClearScreen {\n                terminal.clearScreen()\n                needsToClearScreen = false\n            }\n\n            print(top.render())\n\n            // Assume input finished until proven otherwise, i.e. when readLine returns\n            // `nil`.\n            inputFinished = true\n\n            askForLine: while let line = askForLineInput(prompt: top.inputPrompt) {\n                inputFinished = false\n                let trimmedLine = String(\n                    line.drop { $0.isWhitespace }\n                        .reversed()\n                        .drop { $0.isWhitespace }\n                        .reversed()\n                )\n                let response = await top.acceptLineInput(trimmedLine)\n                switch response {\n                case .none:\n                    continue askForLine\n                case .push(let card):\n                    push(card)\n                    needsToClearScreen = true\n                    break askForLine\n                case let .pop(error):\n                    cards.removeLast()\n                    if let error {\n                        self.swiftCommandState.observabilityScope.emit(error)\n                        needsToClearScreen = false\n                    } else {\n                        needsToClearScreen = !cards.isEmpty\n                    }\n                    break askForLine\n                case .quit:\n                    return\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Snippets/Cards/SnippetCard.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport PackageGraph\nimport SPMBuildCore\n\nimport func TSCBasic.exec\nimport enum TSCBasic.ProcessEnv\n\n/// A card displaying a ``Snippet`` at the terminal.\nstruct SnippetCard: Card {\n    enum Error: Swift.Error, CustomStringConvertible {\n        case cantRunSnippet(reason: String)\n\n        var description: String {\n            switch self {\n            case let .cantRunSnippet(reason):\n                return \"Can't run snippet: \\(reason)\"\n            }\n        }\n    }\n\n    /// The snippet to display in the terminal.\n    var snippet: Snippet\n\n    /// The snippet's index within its group.\n    var number: Int\n\n    /// The tool used for eventually building and running a chosen snippet.\n    var swiftCommandState: SwiftCommandState\n\n    func render() -> String {\n        let isColorized: Bool = swiftCommandState.options.logging.colorDiagnostics\n        var rendered = isColorized ? colorized {\n            brightYellow {\n                \"# \"\n                snippet.name\n            }\n            \"\\n\\n\"\n        }.terminalString()\n            :\n            plain {\n                plain {\n                    \"# \"\n                    snippet.name\n                }\n                \"\\n\\n\"\n            }.terminalString()\n\n        if !snippet.explanation.isEmpty {\n            rendered += isColorized ? brightBlack {\n                snippet.explanation\n                    .split(separator: \"\\n\", omittingEmptySubsequences: false)\n                    .map { \"// \" + $0 }\n                    .joined(separator: \"\\n\")\n            }.terminalString()\n            : plain {\n                snippet.explanation\n                    .split(separator: \"\\n\", omittingEmptySubsequences: false)\n                    .map { \"// \" + $0 }\n                    .joined(separator: \"\\n\")\n            }.terminalString()\n\n            rendered += \"\\n\\n\"\n        }\n\n        rendered += snippet.presentationCode\n\n        return rendered\n    }\n\n    var inputPrompt: String? {\n        return \"\\nRun this snippet? [R: run, or press Enter to return]\"\n    }\n\n    func acceptLineInput<S>(_ line: S) async -> CardEvent? where S : StringProtocol {\n        let trimmed = line.drop { $0.isWhitespace }.prefix { !$0.isWhitespace }.lowercased()\n        guard !trimmed.isEmpty else {\n            return .pop()\n        }\n\n        switch trimmed {\n        case \"r\", \"run\":\n            do {\n                try await runExample()\n            } catch {\n                return .pop(SnippetCard.Error.cantRunSnippet(reason: error.localizedDescription))\n            }\n            break\n        case \"c\", \"copy\":\n            print(\"Unimplemented\")\n            break\n        default:\n            break\n        }\n\n        return .pop()\n    }\n\n    func runExample() async throws {\n        print(\"Building '\\(snippet.path)'\\n\")\n        let buildSystem = try await swiftCommandState.createBuildSystem(explicitProduct: snippet.name)\n        try await buildSystem.build(subset: .product(snippet.name), buildOutputs: [])\n        let executablePath = try swiftCommandState.productsBuildParameters.buildPath.appending(component: snippet.name)\n        if let exampleTarget = try await buildSystem.getPackageGraph().module(for: snippet.name) {\n            try ProcessEnv.chdir(exampleTarget.sources.paths[0].parentDirectory)\n        }\n        try exec(path: executablePath.pathString, args: [])\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Snippets/Cards/SnippetGroupCard.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport CoreCommands\nimport PackageModel\nimport TSCUtility\n\n/// A card showing the snippets in a ``SnippetGroup``.\nstruct SnippetGroupCard: Card {\n    /// The snippet group to display in the terminal.\n    var snippetGroup: SnippetGroup\n\n    /// The tool used for eventually building and running a chosen snippet.\n    var swiftCommandState: SwiftCommandState\n\n    var inputPrompt: String? {\n        return \"\"\"\n\n            Choose a number or a name from the list of snippets.\n            To go back, press enter.\n            To exit, enter `q`.\n            \"\"\"\n    }\n\n    func acceptLineInput<S>(_ line: S) -> CardEvent? where S : StringProtocol {\n        if line.isEmpty || line.allSatisfy({ $0.isWhitespace }) {\n            return .pop()\n        }\n        if line.prefix(while: { !$0.isWhitespace }).lowercased() == \"q\" {\n            return .quit()\n        }\n        if let index = Int(line),\n           snippetGroup.snippets.indices.contains(index) {\n            return .push(SnippetCard(snippet: snippetGroup.snippets[index], number: index, swiftCommandState: swiftCommandState))\n        } else if let foundSnippetIndex = snippetGroup.snippets.firstIndex(where: { $0.name == line }) {\n            return .push(SnippetCard(snippet: snippetGroup.snippets[foundSnippetIndex], number: foundSnippetIndex, swiftCommandState: swiftCommandState))\n        } else {\n            print(red { \"There is not a snippet by that name or index.\" })\n            return nil\n        }\n    }\n\n    func render() -> String {\n        let isColorized = swiftCommandState.options.logging.colorDiagnostics\n        precondition(!snippetGroup.snippets.isEmpty)\n\n        var rendered = isColorized ? brightYellow {\n            \"\"\"\n            # \\(snippetGroup.name)\n\n\n            \"\"\"\n        }.terminalString() :\n            plain {\n                \"\"\"\n                # \\(snippetGroup.name)\n\n\n                \"\"\"\n            }.terminalString()\n\n        if !snippetGroup.explanation.isEmpty {\n            rendered += snippetGroup.explanation\n        }\n\n        rendered += \"\\n\"\n        rendered += snippetGroup.snippets\n            .enumerated()\n            .map { pair -> String in\n                let (number, snippet) = pair\n                return isColorized ? brightCyan {\n                    \"\\(number). \\(snippet.name)\\n\"\n                    plain {\n                        snippet.explanation.spm_multilineIndent(count: 3)\n                    }\n                }.terminalString() :\n                    plain {\n                        \"\\(number). \\(snippet.name)\\n\"\n                        plain {\n                            snippet.explanation.spm_multilineIndent(count: 3)\n                        }\n                    }.terminalString()\n            }\n            .joined(separator: \"\\n\\n\")\n\n        return rendered\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Snippets/Cards/TopCard.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport TSCUtility\n\n/// The top menu card for a package's help contents, including snippets.\nstruct TopCard: Card {\n    /// The root package that hosts the snippets.\n    let package: ResolvedPackage\n\n    /// The top-level snippet groups residing in the `Snippets` subdirectory.\n    let snippetGroups: [SnippetGroup]\n\n    /// The tool used for eventually building and running a chosen snippet.\n    let swiftCommandState: SwiftCommandState\n\n    init(package: ResolvedPackage, snippetGroups: [SnippetGroup], swiftCommandState: SwiftCommandState) {\n        self.package = package\n        self.snippetGroups = snippetGroups\n        self.swiftCommandState = swiftCommandState\n    }\n\n    var inputPrompt: String? {\n        return \"\"\"\n            Choose a group by name or number.\n            To exit, enter 'q'.\n            \"\"\"\n    }\n\n    func renderProducts() -> String {\n        let isColorized = swiftCommandState.options.logging.colorDiagnostics\n        let libraries = package.products\n            .filter {\n                guard case .library = $0.type else {\n                    return false\n                }\n                return true\n            }\n            .sorted { $0.name < $1.name }\n            .map { \"- \\($0.name) (library)\" }\n\n        let executables = package.products\n            .filter { $0.type == .executable }\n            .sorted { $0.name < $1.name }\n            .map { \"- \\($0.name) (executable)\" }\n\n        guard !(libraries.isEmpty && executables.isEmpty) else {\n            return \"\"\n        }\n\n        var rendered = isColorized ? brightCyan {\n            \"\\n## Products\"\n            \"\\n\\n\"\n        }.terminalString() :\n            plain {\n                \"\\n## Products\"\n                \"\\n\\n\"\n            }.terminalString()\n\n        rendered += (libraries + executables).joined(separator: \"\\n\")\n\n        return rendered\n    }\n\n    func renderSnippets() -> String {\n        let isColorized = swiftCommandState.options.logging.colorDiagnostics\n        guard !snippetGroups.isEmpty else {\n            return \"\"\n        }\n        let snippetPreviews = snippetGroups.enumerated().map { pair -> String in\n            let (number, snippetGroup) = pair\n            let snippetNoun = snippetGroup.snippets.count > 1 ? \"snippets\" : \"snippet\"\n            let heading = \"\\(number). \\(snippetGroup.name) (\\(snippetGroup.snippets.count) \\(snippetNoun))\"\n            return isColorized ? colorized {\n                cyan {\n                    heading\n                    \"\\n\"\n                }\n                if !snippetGroup.explanation.isEmpty {\n                    \"\"\"\n                    \\(snippetGroup.explanation.spm_multilineIndent(count: 3))\n                    \"\"\"\n                }\n            }.terminalString() :\n                plain {\n                    plain {\n                        heading\n                        \"\\n\"\n                    }\n                    if !snippetGroup.explanation.isEmpty {\n                        \"\"\"\n                        \\(snippetGroup.explanation.spm_multilineIndent(count: 3))\n                        \"\"\"\n                    }\n                }.terminalString()\n        }\n\n        return isColorized ? colorized {\n            brightCyan {\n                \"\\n## Snippets\"\n            }\n            \"\\n\\n\"\n            snippetPreviews.joined(separator: \"\\n\\n\")\n            \"\\n\"\n        }.terminalString() :\n            plain {\n                plain {\n                    \"\\n## Snippets\"\n                }\n                \"\\n\\n\"\n                snippetPreviews.joined(separator: \"\\n\\n\")\n                \"\\n\"\n            }.terminalString()\n    }\n\n    func render() -> String {\n        let isColorized: Bool = self.swiftCommandState.options.logging.colorDiagnostics\n        let heading = isColorized ? brightYellow {\n            \"# \"\n            package.identity.description\n        } : plain {\n            \"# \"\n            package.identity.description\n        }\n\n        return \"\"\"\n        \\(heading)\n        \\(renderProducts())\n        \\(renderSnippets())\n        \"\"\"\n    }\n\n    func acceptLineInput<S>(_ line: S) -> CardEvent? where S : StringProtocol {\n        guard !line.isEmpty else {\n            print(\"\\u{0007}\")\n            return nil\n        }\n        if line.prefix(while: { !$0.isWhitespace }).lowercased() == \"q\" {\n            return .quit()\n        }\n        if let index = Int(line),\n           snippetGroups.indices.contains(index) {\n            return .push(SnippetGroupCard(snippetGroup: snippetGroups[index], swiftCommandState: swiftCommandState))\n        } else if let groupByName = snippetGroups.first(where: { $0.name == line }) {\n            return .push(SnippetGroupCard(snippetGroup: groupByName, swiftCommandState: swiftCommandState))\n        } else {\n            print(red { \"There is not a group by that name or index.\" })\n            return nil\n        }\n    }\n}\n\nfileprivate extension Module.Kind {\n    var pluralDescription: String {\n        switch self {\n        case .executable:\n            return \"executables\"\n        case .library:\n            return \"libraries\"\n        case .systemModule:\n            return \"system modules\"\n        case .test:\n            return \"tests\"\n        case .binary:\n            return \"binaries\"\n        case .plugin:\n            return \"plugins\"\n        case .snippet:\n            return \"snippets\"\n        case .macro:\n            return \"macros\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Snippets/Colorful.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic protocol Colorful: CustomStringConvertible {\n    func terminalString() -> String\n}\n\nextension Colorful {\n    public var description: String {\n        return terminalString()\n    }\n}\n\nextension Colorful where Self: RawRepresentable, RawValue: StringProtocol {\n    func terminalString() -> String {\n        return String(self.rawValue)\n    }\n}\n\nextension String: Colorful {\n    public func terminalString() -> String {\n        return self\n    }\n}\n\nextension Substring: Colorful {\n    public func terminalString() -> String {\n        return String(self)\n    }\n}\n\nextension Array: Colorful where Element == Colorful {\n    public func terminalString() -> String {\n        return self.map { $0.terminalString() }.joined()\n    }\n}\n\nextension Optional: @retroactive CustomStringConvertible where Wrapped: Colorful {\n    public var description: String {\n        return terminalString()\n    }\n}\n\nextension Optional: Colorful where Wrapped: Colorful {\n    public func terminalString() -> String {\n        if let unwrapped = self {\n            return unwrapped.terminalString()\n        } else {\n            return \"\"\n        }\n    }\n}\n\n@resultBuilder\npublic struct ColorBuilder {\n    public static func buildOptional(_ component: [Colorful]?) -> [Colorful] {\n        return component ?? []\n    }\n\n    public static func buildBlock(_ components: Colorful...) -> [Colorful] {\n        return components\n    }\n\n    public static func buildEither(first component: [Colorful]) -> [Colorful] {\n        return component\n    }\n\n    public static func buildEither(second component: [Colorful]) -> [Colorful] {\n        return component\n    }\n}\n\nprotocol Color: Colorful {}\n\nenum Color4: String, Color {\n    case black = \"\\u{001b}[30m\"\n    case red = \"\\u{001b}[31m\"\n    case green = \"\\u{001b}[32m\"\n    case yellow = \"\\u{001b}[33m\"\n    case blue = \"\\u{001b}[34m\"\n    case magenta = \"\\u{001b}[35m\"\n    case cyan = \"\\u{001b}[36m\"\n    case white = \"\\u{001b}[37m\"\n\n    case brightBlack = \"\\u{001b}[30;1m\"\n    case brightRed = \"\\u{001b}[31;1m\"\n    case brightGreen = \"\\u{001b}[32;1m\"\n    case brightYellow = \"\\u{001b}[33;1m\"\n    case brightBlue = \"\\u{001b}[34;1m\"\n    case brightMagenta = \"\\u{001b}[35;1m\"\n    case brightCyan = \"\\u{001b}[36;1m\"\n    case brightWhite = \"\\u{001b}[37;1m\"\n\n    case reset = \"\\u{001b}[0m\"\n\n    var bright: Color4 {\n        switch self {\n        case .black:\n            return .brightBlack\n        case .red:\n            return .brightRed\n        case .green:\n            return .brightGreen\n        case .yellow :\n            return .brightYellow\n        case .blue:\n            return .brightBlue\n        case .magenta:\n            return .brightMagenta\n        case .cyan:\n            return .brightCyan\n        case .white:\n            return .brightWhite\n        default:\n            return self\n        }\n    }\n\n    var description: String {\n        return self.rawValue\n    }\n}\n\npublic func colorized(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.reset, builder)\n}\n\npublic func plain(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.reset, builder)\n}\n\npublic func black(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.black, builder)\n}\n\npublic func brightBlack(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.brightBlack, builder)\n}\n\npublic func red(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.red, builder)\n}\n\npublic func brightRed(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.brightRed, builder)\n}\n\npublic func green(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.green, builder)\n}\n\npublic func brightGreen(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.brightGreen, builder)\n}\n\npublic func yellow(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.yellow, builder)\n}\n\npublic func brightYellow(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.brightYellow, builder)\n}\n\npublic func blue(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.blue, builder)\n}\n\npublic func brightBlue(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.brightBlue, builder)\n}\n\npublic func magenta(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.magenta, builder)\n}\n\npublic func brightMagenta(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.brightMagenta, builder)\n}\n\npublic func cyan(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.cyan, builder)\n}\n\npublic func brightCyan(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.brightCyan, builder)\n}\n\npublic func white(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.white, builder)\n}\n\npublic func brightWhite(@ColorBuilder builder: () -> [Colorful]) -> Colorful {\n    return Colorized(.brightWhite, builder)\n}\n\nstruct Colorized: Colorful {\n    var color: Color\n    var items: [Colorful]\n\n    init(_ color: Color = Color4.reset, _ items: [Colorful]) {\n        self.color = color\n        self.items = items\n    }\n\n    init(_ color: Color4 = .reset, @ColorBuilder _ builder: () -> [Colorful]) {\n        self.color = color\n        self.items = builder()\n    }\n\n    func terminalString() -> String {\n        let inner = items.map { $0.terminalString() }.joined()\n        guard inner.hasSuffix(Color4.reset.rawValue) else {\n            return color.terminalString() + inner + Color4.reset.rawValue\n        }\n        return color.terminalString() + inner\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/SwiftBuildCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\n\nimport Build\n\n@_spi(SwiftPMInternal)\nimport CoreCommands\n\nimport PackageGraph\n\nimport SPMBuildCore\nimport XCBuildSupport\nimport SwiftBuildSupport\n\nimport class Basics.AsyncProcess\nimport var TSCBasic.stdoutStream\n\nimport enum TSCUtility.Diagnostics\nimport func TSCUtility.getClangVersion\nimport struct TSCUtility.Version\n\nimport Foundation\nimport SBOMModel\nimport Workspace\n\nextension BuildSubset {\n    var argumentName: String {\n        switch self {\n        case .allExcludingTests:\n            fatalError(\"no corresponding argument\")\n        case .allIncludingTests:\n            return \"--build-tests\"\n        case .product:\n            return \"--product\"\n        case .target:\n            return \"--target\"\n        }\n    }\n}\n\nstruct BuildCommandOptions: ParsableArguments {\n    /// Returns the build subset specified with the options.\n    func buildSubset(observabilityScope: ObservabilityScope) -> BuildSubset? {\n        var allSubsets: [BuildSubset] = []\n\n        if let product {\n            allSubsets.append(.product(product))\n        }\n\n        if let target {\n            allSubsets.append(.target(target))\n        }\n\n        if buildTests {\n            allSubsets.append(.allIncludingTests)\n        }\n\n        guard allSubsets.count < 2 else {\n            observabilityScope.emit(.mutuallyExclusiveArgumentsError(arguments: allSubsets.map{ $0.argumentName }))\n            return nil\n        }\n\n        return allSubsets.first ?? .allExcludingTests\n    }\n\n    /// If the test should be built.\n    @Flag(help: \"Build both source and test targets.\")\n    var buildTests: Bool = false\n\n    /// Whether to enable code coverage.\n    @Flag(name: .customLong(\"code-coverage\"),\n          inversion: .prefixedEnableDisable,\n          help: \"Determines whether the build measures code coverage.\")\n    var enableCodeCoverage: Bool = false\n\n    /// If the binary output path should be printed.\n    @Flag(name: .customLong(\"show-bin-path\"), help: \"Print the binary output path.\")\n    var shouldPrintBinPath: Bool = false\n\n    /// Whether to output a graphviz file visualization of the combined job graph for all targets\n    @Flag(name: .customLong(\"print-manifest-job-graph\"),\n          help: \"Write the command graph for the build manifest as a Graphviz file.\")\n    var printManifestGraphviz: Bool = false\n\n    /// Whether to output a graphviz file visualization of the PIF JSON sent to Swift Build.\n    @Flag(name: .customLong(\"print-pif-manifest-graph\"),\n          help: \"Write the PIF JSON sent to Swift Build as a Graphviz file.\")\n    var printPIFManifestGraphviz: Bool = false\n\n    /// Specific target to build.\n    @Option(help: \"Build the specified target.\")\n    var target: String?\n\n    /// Specific product to build.\n    @Option(help: \"Build the specified product.\")\n    var product: String?\n\n    /// Testing library options.\n    ///\n    /// These options are no longer used but are needed by older versions of the\n    /// Swift VSCode plugin. They will be removed in a future update.\n    @OptionGroup(visibility: .private)\n    var testLibraryOptions: TestLibraryOptions\n\n    /// If should link the Swift stdlib statically.\n    @Flag(name: .customLong(\"static-swift-stdlib\"), inversion: .prefixedNo, help: \"Determines whether Swift stdlib links statically.\")\n    public var shouldLinkStaticSwiftStdlib: Bool = false\n\n    @OptionGroup(title: \"Software Bill of Materials (SBOM)\")\n    var sbom: SBOMOptions\n}\n\n/// swift-build command namespace\npublic struct SwiftBuildCommand: AsyncSwiftCommand {\n    public static var configuration = CommandConfiguration(\n        commandName: \"build\",\n        _superCommandName: \"swift\",\n        abstract: \"Build sources into binary products.\",\n        discussion: \"SEE ALSO: swift run, swift package, swift test\",\n        version: SwiftVersion.current.completeDisplayString,\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)])\n\n    @OptionGroup()\n    public var globalOptions: GlobalOptions\n\n    @OptionGroup()\n    var options: BuildCommandOptions\n\n    public func run(_ swiftCommandState: SwiftCommandState) async throws {\n        if options.shouldPrintBinPath {\n            return try print(swiftCommandState.productsBuildParameters.buildPath.description)\n        }\n\n        if options.printManifestGraphviz {\n            // FIXME: Doesn't seem ideal that we need an explicit build operation, but this concretely uses the `LLBuildManifest`.\n            guard let buildOperation = try await swiftCommandState.createBuildSystem(\n                explicitBuildSystem: .native,\n            ) as? BuildOperation else {\n                throw StringError(\"asked for native build system but did not get it\")\n            }\n            let buildManifest = try await buildOperation.getBuildManifest()\n            var serializer = DOTManifestSerializer(manifest: buildManifest)\n            // Print to stdout.\n            let outputStream = stdoutStream\n            serializer.writeDOT(to: outputStream)\n            outputStream.flush()\n            return\n        }\n\n        guard let subset = options.buildSubset(observabilityScope: swiftCommandState.observabilityScope) else {\n            throw ExitCode.failure\n        }\n\n        var productsBuildParameters = try swiftCommandState.productsBuildParameters\n        var toolsBuildParameters = try swiftCommandState.toolsBuildParameters\n\n        if self.options.enableCodeCoverage {\n            productsBuildParameters.testingParameters.enableCodeCoverage = true\n            toolsBuildParameters.testingParameters.enableCodeCoverage = true\n        }\n\n        if self.options.printPIFManifestGraphviz {\n            productsBuildParameters.printPIFManifestGraphviz = true\n            toolsBuildParameters.printPIFManifestGraphviz = true\n        }\n\n        if swiftCommandState.options.build.enableCodesizeProfile {\n            var driverParameters = productsBuildParameters.driverParameters\n            driverParameters.codesizeProfileEnabled = true\n            driverParameters.emitSILFiles = true\n            driverParameters.emitIRFiles = true\n            driverParameters.emitOptimizationRecord = true\n\n            if let outputDir = swiftCommandState.options.build.codesizeProfileOutputDirectory {\n                let outputPath = try AbsolutePath(validating: outputDir, relativeTo: swiftCommandState.originalWorkingDirectory)\n                driverParameters.silOutputDirectory = outputPath\n                driverParameters.irOutputDirectory = outputPath\n                driverParameters.optimizationRecordDirectory = outputPath\n            }\n            productsBuildParameters.driverParameters = driverParameters\n        }\n\n        do {\n            try await build(\n                swiftCommandState,\n                subset: subset,\n                productsBuildParameters: productsBuildParameters,\n                toolsBuildParameters: toolsBuildParameters,\n            )\n        } catch SwiftBuildSupport.PIFGenerationError.printedPIFManifestGraphviz {\n            throw ExitCode.success\n        } catch _ as Diagnostics {\n            throw ExitCode.failure\n        }\n    }\n\n    private func build(\n        _ swiftCommandState: SwiftCommandState,\n        subset: BuildSubset,\n        productsBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n    ) async throws {\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            explicitProduct: options.product,\n            shouldLinkStaticSwiftStdlib: options.shouldLinkStaticSwiftStdlib,\n            productsBuildParameters: productsBuildParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            // command result output goes on stdout\n            // ie \"swift build\" should output to stdout\n            outputStream: TSCBasic.stdoutStream\n        )\n        let buildResult = try await buildSystem.build(subset: subset, buildOutputs: try await getBuildOutputs())\n        try await processBuildResult(swiftCommandState, buildSystem: buildSystem, buildResult: buildResult)\n    }\n\n    private func getBuildOutputs() async throws -> [BuildOutput] {\n        return try self.options.sbom.sbomSpecs.isEmpty ? [] : [.dependencyGraph]\n    }\n\n    private func processBuildResult(\n        _ swiftCommandState: SwiftCommandState,\n        buildSystem: any BuildSystem,\n        buildResult: BuildResult) async throws {\n        if try !self.options.sbom.sbomSpecs.isEmpty {\n            try await generateSBOMs(swiftCommandState, buildSystem, buildResult)\n        }\n    }\n\n    private func generateSBOMs(\n        _ swiftCommandState: SwiftCommandState,\n        _ buildSystem: any BuildSystem,\n        _ buildResult: BuildResult) async throws {\n        do {\n            guard try self.options.sbom.sbomSpecs.isEmpty || options.target == nil else {\n                throw SBOMModel.SBOMCommandError.targetFlagNotSupported\n            }\n            let workspace = try swiftCommandState.getActiveWorkspace()\n            let packageGraph = try await buildSystem.getPackageGraph()\n            let resolvedPackagesStore = try workspace.resolvedPackagesStore.load()\n            let input = SBOMInput(\n                modulesGraph: packageGraph,\n                dependencyGraph: buildResult.dependencyGraph,\n                store: resolvedPackagesStore,\n                filter: try self.options.sbom.sbomFilter,\n                product: options.product,\n                specs: try self.options.sbom.sbomSpecs,\n                dir: await SBOMCreator.resolveSBOMDirectory(from: self.options.sbom.sbomDirectory, withDefault: try swiftCommandState.productsBuildParameters.buildPath),\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n\n            let creator = SBOMCreator(input: input)\n            try await creator.createSBOMsWithLogging()\n            if self.globalOptions.build.buildSystem != .swiftbuild {\n                swiftCommandState.observabilityScope.emit(warning: \"generating SBOM(s) without `--build-system swiftbuild` flag creates SBOM(s) without build-time conditionals.\")\n            }\n        } catch {\n            if self.options.sbom.sbomWarningOnly {\n                swiftCommandState.observabilityScope.emit(warning: \"SBOM generation failed: \\(error.localizedDescription)\")\n            } else {\n                throw error\n            }\n        }\n    }\n\n    public init() {}\n}\n\npublic extension _SwiftCommand {\n    func buildSystemProvider(_ swiftCommandState: SwiftCommandState) throws -> BuildSystemProvider {\n        swiftCommandState.defaultBuildSystemProvider\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/SwiftRunCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2016 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport SPMBuildCore\n\nimport enum TSCBasic.ProcessEnv\nimport func TSCBasic.exec\n\nimport enum TSCUtility.Diagnostics\n\n#if canImport(Android)\nimport Android\n#endif\n\n/// An enumeration of the errors that can be generated by the run tool.\nprivate enum RunError: Swift.Error {\n    /// The package manifest has no executable product.\n    case noExecutableFound\n\n    /// Could not find a specific executable in the package manifest.\n    case executableNotFound(String)\n\n    /// There are multiple executables and one must be chosen.\n    case multipleExecutables([String])\n}\n\nextension RunError: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .noExecutableFound:\n            return \"no executable product available\"\n        case .executableNotFound(let executable):\n            return \"no executable product named '\\(executable)'\"\n        case .multipleExecutables(let executables):\n            let joinedExecutables = executables.joined(separator: \", \")\n            return \"multiple executable products available: \\(joinedExecutables)\"\n        }\n    }\n}\n\nstruct RunCommandOptions: ParsableArguments {\n    enum RunMode: EnumerableFlag {\n        case repl\n        case debugger\n        case run\n\n        static func help(for value: RunCommandOptions.RunMode) -> ArgumentHelp? {\n            switch value {\n            case .repl:\n                return \"Launch Swift REPL for the package.\"\n            case .debugger:\n                return \"Launch the executable in a debugger session.\"\n            case .run:\n                return \"Launch the executable with the provided arguments.\"\n            }\n        }\n    }\n\n    /// The mode in with the tool command should run.\n    @Flag var mode: RunMode = .run\n\n    /// If the executable product should be built before running.\n    @Flag(name: .customLong(\"skip-build\"), help: \"Skip building the executable product.\")\n    var shouldSkipBuild: Bool = false\n\n    var shouldBuild: Bool { !shouldSkipBuild }\n\n    /// If the test should be built.\n    @Flag(name: .customLong(\"build-tests\"), help: \"Build both source and test targets.\")\n    var shouldBuildTests: Bool = false\n\n    /// The executable product to run.\n    @Argument(help: \"The executable to run.\", completion: .shellCommand(\"swift package completion-tool list-executables\"))\n    var executable: String?\n\n    /// The arguments to pass to the executable.\n    @Argument(parsing: .captureForPassthrough,\n              help: \"The arguments to pass to the executable.\")\n    var arguments: [String] = []\n}\n\n/// swift-run command namespace\npublic struct SwiftRunCommand: AsyncSwiftCommand {\n    public static var configuration = CommandConfiguration(\n        commandName: \"run\",\n        _superCommandName: \"swift\",\n        abstract: \"Build and run an executable product.\",\n        discussion: \"SEE ALSO: swift build, swift package, swift test\",\n        version: SwiftVersion.current.completeDisplayString,\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)])\n\n    @OptionGroup()\n    public var globalOptions: GlobalOptions\n\n    @OptionGroup()\n    var options: RunCommandOptions\n\n    public var toolWorkspaceConfiguration: ToolWorkspaceConfiguration {\n        return .init(wantsREPLProduct: options.mode == .repl)\n    }\n\n    public func run(_ swiftCommandState: SwiftCommandState) async throws {\n        if options.shouldBuildTests && options.shouldSkipBuild {\n            swiftCommandState.observabilityScope.emit(\n              .mutuallyExclusiveArgumentsError(arguments: [\"--build-tests\", \"--skip-build\"])\n            )\n            throw ExitCode.failure\n        }\n\n        switch options.mode {\n        case .repl:\n            // Load a custom package graph which has a special product for REPL.\n            let asyncUnsafeGraphLoader = {\n                try await swiftCommandState.loadPackageGraph(\n                    explicitProduct: self.options.executable\n                )\n            }\n\n            // Construct the build operation.\n            // FIXME: We need to implement the build tool invocation closure here so that build tool plugins work with the REPL. rdar://86112934\n            let buildSystem = try await swiftCommandState.createBuildSystem(\n                cacheBuildManifest: false,\n                packageGraphLoader: asyncUnsafeGraphLoader\n            )\n\n            // Perform build.\n            let buildResult = try await buildSystem.build(subset: .allExcludingTests, buildOutputs: [.replArguments])\n            guard let arguments = buildResult.replArguments else {\n                swiftCommandState.observabilityScope.emit(error: \"\\(globalOptions.build.buildSystem) build system does not support this command\")\n                throw ExitCode.failure\n            }\n\n            // Execute the REPL.\n            let interpreterPath = try swiftCommandState.getTargetToolchain().swiftInterpreterPath\n            swiftCommandState.outputStream.send(\"Launching Swift (interpreter at \\(interpreterPath)) REPL with arguments: \\(arguments.joined(separator: \" \"))\\n\")\n            swiftCommandState.outputStream.flush()\n            try self.run(\n                fileSystem: swiftCommandState.fileSystem,\n                executablePath: interpreterPath,\n                originalWorkingDirectory: swiftCommandState.originalWorkingDirectory,\n                arguments: arguments\n            )\n\n        case .debugger:\n            do {\n                let buildSystem = try await swiftCommandState.createBuildSystem(\n                    explicitProduct: options.executable,\n                )\n                let productName = try await findProductName(in: buildSystem.getPackageGraph())\n                if options.shouldBuildTests {\n                    try await buildSystem.build(subset: .allIncludingTests, buildOutputs: [])\n                } else if options.shouldBuild {\n                    try await buildSystem.build(subset: .product(productName), buildOutputs: [])\n                }\n\n                let productRelativePath = try swiftCommandState.productsBuildParameters.executablePath(for: productName)\n                let productAbsolutePath = try swiftCommandState.productsBuildParameters.buildPath.appending(productRelativePath)\n\n                // Make sure we are running from the original working directory.\n                let cwd: AbsolutePath? = swiftCommandState.fileSystem.currentWorkingDirectory\n                if cwd == nil || swiftCommandState.originalWorkingDirectory != cwd {\n                    try ProcessEnv.chdir(swiftCommandState.originalWorkingDirectory)\n                }\n\n                if let debugger = try swiftCommandState.getTargetToolchain().swiftSDK.toolset.knownTools[.debugger],\n                   let debuggerPath = debugger.path {\n                    try self.run(\n                        fileSystem: swiftCommandState.fileSystem,\n                        executablePath: debuggerPath,\n                        originalWorkingDirectory: swiftCommandState.originalWorkingDirectory,\n                        arguments: debugger.extraCLIOptions + [productAbsolutePath.pathString] + options.arguments\n                    )\n                } else {\n                    let pathRelativeToWorkingDirectory = productAbsolutePath.relative(to: swiftCommandState.originalWorkingDirectory)\n                    let lldbPath = try swiftCommandState.getTargetToolchain().getLLDB()\n                    try exec(path: lldbPath.pathString, args: [\"--\", pathRelativeToWorkingDirectory.pathString] + options.arguments)\n                }\n            } catch let error as RunError {\n                swiftCommandState.observabilityScope.emit(error)\n                throw ExitCode.failure\n            }\n\n        case .run:\n            // Detect deprecated uses of swift run to interpret scripts.\n            if let executable = options.executable, try isValidSwiftFilePath(fileSystem: swiftCommandState.fileSystem, path: executable) {\n                swiftCommandState.observabilityScope.emit(.runFileDeprecation(filePath: executable))\n                // Redirect execution to the toolchain's swift executable.\n                let swiftInterpreterPath = try swiftCommandState.getTargetToolchain().swiftInterpreterPath\n                // Prepend the script to interpret to the arguments.\n                let arguments = [executable] + options.arguments\n                try self.run(\n                    fileSystem: swiftCommandState.fileSystem,\n                    executablePath: swiftInterpreterPath,\n                    originalWorkingDirectory: swiftCommandState.originalWorkingDirectory,\n                    arguments: arguments\n                )\n                return\n            }\n\n            do {\n                let buildSystem = try await swiftCommandState.createBuildSystem(\n                    explicitProduct: options.executable,\n                )\n                let modulesGraph = try await buildSystem.getPackageGraph()\n                let productName = try findProductName(in: modulesGraph)\n                if options.shouldBuildTests {\n                    try await buildSystem.build(subset: .allIncludingTests, buildOutputs: [])\n                } else if options.shouldBuild {\n                    try await buildSystem.build(subset: .product(productName), buildOutputs: [])\n                }\n\n                let executablePath = try swiftCommandState.productsBuildParameters.buildPath.appending(component: productName)\n\n                let productRelativePath = try swiftCommandState.productsBuildParameters.executablePath(for: productName)\n                let productAbsolutePath = try swiftCommandState.productsBuildParameters.buildPath.appending(productRelativePath)\n\n                let runnerPath: AbsolutePath\n                let arguments: [String]\n\n                if let debugger = try swiftCommandState.getTargetToolchain().swiftSDK.toolset.knownTools[.debugger],\n                   let debuggerPath = debugger.path {\n                    runnerPath = debuggerPath\n                    arguments = debugger.extraCLIOptions + [productAbsolutePath.pathString] + options.arguments\n                } else {\n                    runnerPath = executablePath\n                    arguments = options.arguments\n                }\n\n                try self.run(\n                    fileSystem: swiftCommandState.fileSystem,\n                    executablePath: runnerPath,\n                    originalWorkingDirectory: swiftCommandState.originalWorkingDirectory,\n                    arguments: arguments\n                )\n            } catch Diagnostics.fatalError {\n                throw ExitCode.failure\n            } catch let error as RunError {\n                swiftCommandState.observabilityScope.emit(error)\n                throw ExitCode.failure\n            }\n        }\n    }\n\n    /// Returns the path to the correct executable based on options.\n    private func findProductName(in graph: ModulesGraph) throws -> String {\n        if let executable = options.executable {\n            // There should be only one product with the given name in the graph\n            // and it should be executable or snippet.\n            guard let product = graph.product(for: executable),\n                  product.type == .executable || product.type == .snippet\n            else {\n                throw RunError.executableNotFound(executable)\n            }\n            return executable\n        }\n\n        // If the executable is implicit, search through root products.\n        let rootExecutables = graph.rootPackages\n            .flatMap { $0.products }\n            // The type checker slows down significantly when ProductTypes arent explicitly typed.\n            .filter { $0.type == ProductType.executable || $0.type == ProductType.snippet }\n            .map { $0.name }\n\n        // Error out if the package contains no executables.\n        guard rootExecutables.count > 0 else {\n            throw RunError.noExecutableFound\n        }\n\n        // Only implicitly deduce the executable if it is the only one.\n        guard rootExecutables.count == 1 else {\n            throw RunError.multipleExecutables(rootExecutables)\n        }\n\n        return rootExecutables[0]\n    }\n\n    /// Executes the executable at the specified path.\n    private func run(\n        fileSystem: FileSystem,\n        executablePath: AbsolutePath,\n        originalWorkingDirectory: AbsolutePath,\n        arguments: [String]\n    ) throws {\n        // Make sure we are running from the original working directory.\n        let cwd: AbsolutePath? = fileSystem.currentWorkingDirectory\n        if cwd == nil || originalWorkingDirectory != cwd {\n            try ProcessEnv.chdir(originalWorkingDirectory)\n        }\n\n        let pathRelativeToWorkingDirectory = executablePath.relative(to: originalWorkingDirectory)\n        try execute(path: executablePath.pathString, args: [pathRelativeToWorkingDirectory.pathString] + arguments)\n    }\n\n    /// Determines if a path points to a valid swift file.\n    private func isValidSwiftFilePath(fileSystem: FileSystem, path: String) throws -> Bool {\n        guard path.hasSuffix(\".swift\") else { return false }\n        //FIXME: Return false when the path is not a valid path string.\n        let absolutePath: AbsolutePath\n        if path.first == \"/\" {\n            do {\n                absolutePath = try AbsolutePath(validating: path)\n            } catch {\n                return false\n            }\n        } else {\n            guard let cwd = fileSystem.currentWorkingDirectory else {\n                return false\n            }\n            absolutePath = try AbsolutePath(cwd, validating: path)\n        }\n        return fileSystem.isFile(absolutePath)\n    }\n\n    /// A safe wrapper of TSCBasic.exec.\n    private func execute(path: String, args: [String]) throws -> Never {\n        #if !os(Windows)\n        // Dispatch will disable almost all asynchronous signals on its worker threads, and this is called from `async`\n        // context. To correctly `exec` a freshly built binary, we will need to:\n        // 1. reset the signal masks\n        for i in 1..<NSIG {\n            signal(i, SIG_DFL)\n        }\n        var sig_set_all = sigset_t()\n        sigfillset(&sig_set_all)\n        sigprocmask(SIG_UNBLOCK, &sig_set_all, nil)\n\n        #if os(FreeBSD) || os(OpenBSD)\n        #if os(FreeBSD)\n        pthread_suspend_all_np()\n        #endif\n        closefrom(3)\n        #else\n        #if os(Android)\n        let number_fds = Int32(sysconf(_SC_OPEN_MAX))\n        #else\n        let number_fds = getdtablesize()\n        #endif /* os(Android) */\n\n        // 2. set to close all file descriptors on exec\n        for i in 3..<number_fds {\n            _ = fcntl(i, F_SETFD, FD_CLOEXEC)\n        }\n        #endif /* os(FreeBSD) || os(OpenBSD) */\n        #endif\n\n        try TSCBasic.exec(path: path, args: args)\n    }\n\n    public init() {}\n}\n\nprivate extension Basics.Diagnostic {\n    static func runFileDeprecation(filePath: String) -> Self {\n        .warning(\"'swift run \\(filePath)' command to interpret swift files is deprecated; use 'swift \\(filePath)' instead\")\n    }\n}\n\n"
  },
  {
    "path": "Sources/Commands/SwiftTestCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\n@_spi(SwiftPMInternal)\nimport Basics\nimport struct Basics.Triple\n\nimport _Concurrency\n\n@_spi(SwiftPMInternal)\nimport CoreCommands\n\nimport Dispatch\nimport Foundation\nimport PackageGraph\n\n@_spi(SwiftPMInternal)\nimport PackageModel\n\nimport SPMBuildCore\nimport TSCUtility\n\nimport func TSCLibc.exit\nimport Workspace\n\nimport class Basics.AsyncProcess\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.FileSystemError\nimport enum TSCBasic.JSON\nimport var TSCBasic.stdoutStream\nimport class TSCBasic.SynchronizedQueue\nimport class TSCBasic.Thread\n\n#if os(Windows)\nimport WinSDK // for ERROR_NOT_FOUND\n#elseif canImport(Android)\nimport Android\n#endif\n\nprivate enum TestError: Swift.Error {\n    case invalidListTestJSONData(context: String, underlyingError: Error? = nil)\n    case testsNotFound\n    case testProductNotFound(productName: String)\n    case productIsNotTest(productName: String)\n    case multipleTestProducts([String])\n    case xctestNotAvailable(reason: String)\n    case xcodeNotInstalled\n}\n\nextension TestError: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .testsNotFound:\n            return \"no tests found; create a target in the 'Tests' directory\"\n        case .testProductNotFound(let productName):\n            return \"there is no test product named '\\(productName)'\"\n        case .productIsNotTest(let productName):\n            return \"the product '\\(productName)' is not a test\"\n        case .invalidListTestJSONData(let context, let underlyingError):\n            let underlying = underlyingError != nil ? \", underlying error: \\(underlyingError!)\" : \"\"\n            return \"invalid list test JSON structure, produced by \\(context)\\(underlying)\"\n        case .multipleTestProducts(let products):\n            return \"found multiple test products: \\(products.joined(separator: \", \")); use --test-product to select one\"\n        case let .xctestNotAvailable(reason):\n            return \"XCTest not available: \\(reason)\"\n        case .xcodeNotInstalled:\n            return \"XCTest not available; download and install Xcode to use XCTest on this platform\"\n        }\n    }\n}\n\nstruct SharedOptions: ParsableArguments {\n    @Flag(name: .customLong(\"skip-build\"),\n          help: \"Skip building the test target.\")\n    var shouldSkipBuilding: Bool = false\n\n    /// The test product to use. This is useful when there are multiple test products\n    /// to choose from (usually in multiroot packages).\n    @Option(help: .hidden)\n    var testProduct: String?\n}\n\nstruct TestEventStreamOptions: ParsableArguments {\n    /// Legacy equivalent of ``configurationPath``.\n    @Option(name: .customLong(\"experimental-configuration-path\"),\n            help: .private)\n    var experimentalConfigurationPath: AbsolutePath?\n\n    /// Path where swift-testing's JSON configuration should be read.\n    @Option(name: .customLong(\"configuration-path\"),\n            help: .hidden)\n    var configurationPath: AbsolutePath?\n\n    /// Legacy equivalent of ``eventStreamOutputPath``.\n    @Option(name: .customLong(\"experimental-event-stream-output\"),\n            help: .private)\n    var experimentalEventStreamOutputPath: AbsolutePath?\n\n    /// Path where swift-testing's JSON output should be written.\n    @Option(name: .customLong(\"event-stream-output-path\"),\n            help: .hidden)\n    var eventStreamOutputPath: AbsolutePath?\n\n    /// The experimental version number of Swift Testing's event stream to use.\n    ///\n    /// Unlike ``eventStreamVersion``, this permits specifying a version which\n    /// is experimental.\n    @Option(name: .customLong(\"experimental-event-stream-version\"),\n            help: .private)\n    var experimentalEventStreamVersion: String?\n\n    /// The version number of Swift Testing's event stream to use.\n    @Option(name: .customLong(\"event-stream-version\"),\n            help: .hidden)\n    var eventStreamVersion: String?\n\n    /// Experimental path for writing attachments (Swift Testing only.)\n    @Option(name: .customLong(\"experimental-attachments-path\"),\n            help: .private)\n    var experimentalAttachmentsPath: AbsolutePath?\n\n    /// Path for writing attachments (Swift Testing only.)\n    @Option(name: .customLong(\"attachments-path\"),\n            help: \"Path where attachments should be written (Swift Testing only). This path must be an existing directory the current user can write to. If not specified, any attachments created during testing are discarded.\")\n    var attachmentsPath: AbsolutePath?\n}\n\nstruct TestCommandOptions: ParsableArguments {\n    @OptionGroup()\n    var globalOptions: GlobalOptions\n\n    @OptionGroup()\n    var sharedOptions: SharedOptions\n\n    /// Which testing libraries to use (and any related options.)\n    @OptionGroup()\n    var testLibraryOptions: TestLibraryOptions\n\n    /// Options for Swift Testing's event stream.\n    @OptionGroup()\n    var testEventStreamOptions: TestEventStreamOptions\n\n    /// If tests should run in parallel mode.\n    @Flag(name: .customLong(\"parallel\"),\n          inversion: .prefixedNo,\n          help: \"Determines whether tests run in parallel.\")\n    var shouldRunInParallel: Bool = false\n\n    /// Number of tests to execute in parallel\n    @Option(name: .customLong(\"num-workers\"),\n            help: \"Number of tests to execute in parallel.\")\n    var numberOfWorkers: Int?\n\n    /// Width of task group used by Swift Testing.\n    ///\n    /// This argument is consumed by Swift Testing and is passed through verbatim by SwiftPM.\n    @Option(help: .hidden)\n    var experimentalMaximumParallelizationWidth: Int? = nil\n\n    /// List the tests and exit.\n    @Flag(name: [.customLong(\"list-tests\"), .customShort(\"l\")],\n          help: \"List test methods in specifier format.\")\n    var _deprecated_shouldListTests: Bool = false\n\n    /// If the path of the exported code coverage JSON should be printed.\n    @Flag(name: [.customLong(\"show-codecov-path\"), .customLong(\"show-code-coverage-path\"), .customLong(\"show-coverage-path\")],\n          help: \"Print the path of the exported code coverage JSON file.\")\n    var shouldPrintCodeCovPath: Bool = false\n\n    var testCaseSpecifier: TestCaseSpecifier {\n        if !filter.isEmpty {\n            return .regex(filter)\n        }\n\n        return _testCaseSpecifier.map { .specific($0) } ?? .none\n    }\n\n    @Option(name: [.customShort(\"s\"), .customLong(\"specifier\")])\n    var _testCaseSpecifier: String?\n\n    @Option(help: \"\"\"\n        Run test cases that match a regular expression. \\\n        Format: <test-target>.<test-case> or <test-target>.<test-case>/<test>.\n        \"\"\")\n    var filter: [String] = []\n\n    @Option(name: .customLong(\"skip\"),\n            help: \"Skip test cases that match a regular expression. For example: '--skip PerformanceTests'.\")\n    var _testCaseSkip: [String] = []\n\n    /// Path where the xUnit xml file should be generated.\n    @Option(name: .customLong(\"xunit-output\"),\n            help: \"Path where the xUnit xml file should be generated.\")\n    var xUnitOutput: AbsolutePath?\n\n    @Flag(\n        name: .customLong(\"experimental-xunit-message-failure\"),\n        help: ArgumentHelp(\n            \"When set, include the content of stdout/stderr in failure messages (XCTest only, experimental).\",\n            visibility: .hidden\n        )\n    )\n    var shouldShowDetailedFailureMessage: Bool = false\n\n    /// Generate LinuxMain entries and exit.\n    @Flag(name: .customLong(\"testable-imports\"), inversion: .prefixedEnableDisable, help: \"Determines whether test modules use @testable imports.\")\n    var enableTestableImports: Bool = true\n\n    /// Whether to enable code coverage.\n    @Flag(name: .customLong(\"code-coverage\"),\n          inversion: .prefixedEnableDisable,\n          help: \"Determines whether testing measures code coverage.\")\n    var enableCodeCoverage: Bool = false\n\n    /// Configure test output.\n    @Option(help: ArgumentHelp(\"\", visibility: .hidden))\n    public var testOutput: TestOutput = .default\n\n    var enableExperimentalTestOutput: Bool {\n        return testOutput == .experimentalSummary\n    }\n}\n\n/// Tests filtering specifier, which is used to filter tests to run.\npublic enum TestCaseSpecifier {\n    /// No filtering\n    case none\n\n    /// Specify test with fully quantified name\n    case specific(String)\n\n    /// RegEx patterns for tests to run\n    case regex([String])\n\n    /// RegEx patterns for tests to skip\n    case skip([String])\n}\n\n/// Different styles of test output.\npublic enum TestOutput: String, ExpressibleByArgument {\n    /// Whatever `xctest` emits to the console.\n    case `default`\n\n    /// Capture XCTest events and provide a summary.\n    case experimentalSummary\n\n    /// Let the test process emit parseable output to the console.\n    case experimentalParseable\n}\n\n/// swift-test tool namespace\npublic struct SwiftTestCommand: AsyncSwiftCommand {\n    public static var configuration = CommandConfiguration(\n        commandName: \"test\",\n        _superCommandName: \"swift\",\n        abstract: \"Build and run tests.\",\n        discussion: \"SEE ALSO: swift build, swift run, swift package\",\n        version: SwiftVersion.current.completeDisplayString,\n        subcommands: [\n            List.self, Last.self\n        ],\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)])\n\n    public var globalOptions: GlobalOptions {\n        options.globalOptions\n    }\n\n    @OptionGroup()\n    var options: TestCommandOptions\n\n    /// The text of a note emitted after Swift Testing tests finish running if\n    /// at least one XCTest has failed, to inform the user.\n    ///\n    /// - Note: This is exposed as a property so it can be referenced by an\n    ///     accompanying test as well as the implementation.\n    public static let xctestFailedNote = \"Note: One or more XCTests failed, see logging above for details.\"\n\n    private func run(_ swiftCommandState: SwiftCommandState, buildParameters: BuildParameters, testProducts: [BuiltTestProduct]) async throws {\n        // Remove test output from prior runs and validate priors.\n        if self.options.enableExperimentalTestOutput && buildParameters.triple.supportsTestSummary {\n            _ = try? localFileSystem.removeFileTree(buildParameters.testOutputPath)\n        }\n\n        var results = [TestRunner.Result]()\n\n        // Run XCTest.\n        if options.testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState) {\n            // Validate XCTest is available on Darwin-based systems. If it's not available and we're hitting this code\n            // path, that means the developer must have explicitly passed --enable-xctest (or the toolchain is\n            // corrupt, I suppose.)\n            let toolchain = try swiftCommandState.getTargetToolchain()\n            if case let .unsupported(reason) = try swiftCommandState.getHostToolchain().swiftSDK.xctestSupport {\n                if let reason {\n                    throw TestError.xctestNotAvailable(reason: reason)\n                } else {\n                    throw TestError.xcodeNotInstalled\n                }\n            } else if toolchain.targetTriple.isDarwin() && toolchain.xctestPath == nil {\n                throw TestError.xcodeNotInstalled\n            }\n\n            if !self.options.shouldRunInParallel {\n                let (xctestArgs, testCount) = try xctestArgs(for: testProducts, swiftCommandState: swiftCommandState)\n                let result = try await runTestProducts(\n                    testProducts,\n                    additionalArguments: xctestArgs,\n                    productsBuildParameters: buildParameters,\n                    swiftCommandState: swiftCommandState,\n                    library: .xctest\n                )\n                if result == .success, testCount == 0 {\n                    results.append(.noMatchingTests)\n                } else {\n                    results.append(result)\n                }\n            } else {\n                let testSuites = try TestingSupport.getTestSuites(\n                    in: testProducts,\n                    swiftCommandState: swiftCommandState,\n                    enableCodeCoverage: options.enableCodeCoverage,\n                    shouldSkipBuilding: options.sharedOptions.shouldSkipBuilding,\n                    experimentalTestOutput: options.enableExperimentalTestOutput,\n                    sanitizers: globalOptions.build.sanitizers\n                )\n                let tests = try testSuites\n                    .filteredTests(specifier: options.testCaseSpecifier)\n                    .skippedTests(specifier: options.skippedTests(fileSystem: swiftCommandState.fileSystem))\n\n                let result: TestRunner.Result\n                let testResults: [ParallelTestRunner.TestResult]\n                if tests.isEmpty {\n                    testResults = []\n                    result = .noMatchingTests\n                } else {\n                    // Run the tests using the parallel runner.\n                    let runner = ParallelTestRunner(\n                        bundlePaths: testProducts.map { $0.bundlePath },\n                        cancellator: swiftCommandState.cancellator,\n                        toolchain: toolchain,\n                        numJobs: options.numberOfWorkers ?? ProcessInfo.processInfo.activeProcessorCount,\n                        buildOptions: globalOptions.build,\n                        productsBuildParameters: buildParameters,\n                        shouldOutputSuccess: swiftCommandState.logLevel <= .info,\n                        observabilityScope: swiftCommandState.observabilityScope\n                    )\n\n                    testResults = try runner.run(tests)\n                    result = runner.ranSuccessfully ? .success : .failure\n                }\n\n                try generateXUnitOutputIfRequested(for: testResults, swiftCommandState: swiftCommandState)\n                results.append(result)\n            }\n        }\n\n        // Run Swift Testing (parallel or not, it has a single entry point.)\n        if options.testLibraryOptions.isEnabled(.swiftTesting, swiftCommandState: swiftCommandState) {\n            // Determine whether any XCTest runs performed above failed, before Swift Testing runs.\n            let anyXCTestFailed = results.reduce() == .failure\n\n            lazy var testEntryPointPath = testProducts.lazy.compactMap(\\.testEntryPointPath).first\n            if options.testLibraryOptions.isExplicitlyEnabled(.swiftTesting, swiftCommandState: swiftCommandState) || testEntryPointPath == nil {\n                results.append(\n                    try await runTestProducts(\n                        testProducts,\n                        additionalArguments: [],\n                        productsBuildParameters: buildParameters,\n                        swiftCommandState: swiftCommandState,\n                        library: .swiftTesting\n                    )\n                )\n            } else if let testEntryPointPath {\n                // Cannot run Swift Testing because an entry point file was used and the developer\n                // didn't explicitly enable Swift Testing.\n                swiftCommandState.observabilityScope.emit(\n                    debug: \"Skipping automatic Swift Testing invocation because a test entry point path is present: \\(testEntryPointPath)\"\n                )\n            }\n\n            // After running Swift Testing tests, if we determined that any XCTests failed earlier,\n            // emit a message informing the user so they aren't misled and know to look elsewhere for\n            // those details.\n            if anyXCTestFailed {\n                // In theory this could, or should, use `observabilityScope.print(_:verbose:)`,\n                // but that causes tests which check for this output to fail in CI.\n                print(Self.xctestFailedNote)\n            }\n        }\n\n        switch results.reduce() {\n        case .success:\n            // Nothing to do here.\n            break\n        case .failure:\n            swiftCommandState.executionStatus = .failure\n            if self.options.enableExperimentalTestOutput {\n                try Self.handleTestOutput(productsBuildParameters: buildParameters, packagePath: testProducts[0].packagePath)\n            }\n        case .noMatchingTests:\n            swiftCommandState.observabilityScope.emit(.noMatchingTests)\n        }\n    }\n\n    private func xctestArgs(for testProducts: [BuiltTestProduct], swiftCommandState: SwiftCommandState) throws -> (arguments: [String], testCount: Int?) {\n        switch options.testCaseSpecifier {\n        case .none:\n            if case .skip = options.skippedTests(fileSystem: swiftCommandState.fileSystem) {\n                fallthrough\n            } else {\n                return ([], nil)\n            }\n\n        case .regex, .specific, .skip:\n            // If old specifier `-s` option was used, emit deprecation notice.\n            if case .specific = options.testCaseSpecifier {\n                swiftCommandState.observabilityScope.emit(warning: \"'--specifier' option is deprecated; use '--filter' instead\")\n            }\n\n            // Find the tests we need to run.\n            let testSuites = try TestingSupport.getTestSuites(\n                in: testProducts,\n                swiftCommandState: swiftCommandState,\n                enableCodeCoverage: options.enableCodeCoverage,\n                shouldSkipBuilding: options.sharedOptions.shouldSkipBuilding,\n                experimentalTestOutput: options.enableExperimentalTestOutput,\n                sanitizers: globalOptions.build.sanitizers\n            )\n            let tests = try testSuites\n                .filteredTests(specifier: options.testCaseSpecifier)\n                .skippedTests(specifier: options.skippedTests(fileSystem: swiftCommandState.fileSystem))\n\n            return (TestRunner.xctestArguments(forTestSpecifiers: tests.map(\\.specifier)), tests.count)\n        }\n    }\n\n    /// Generate xUnit file if requested.\n    private func generateXUnitOutputIfRequested(\n        for testResults: [ParallelTestRunner.TestResult],\n        swiftCommandState: SwiftCommandState\n    ) throws {\n        guard let xUnitOutput = options.xUnitOutput else {\n            return\n        }\n\n        let generator = XUnitGenerator(\n            fileSystem: swiftCommandState.fileSystem,\n            results: testResults\n        )\n        try generator.generate(\n            at: xUnitOutput,\n            detailedFailureMessage: self.options.shouldShowDetailedFailureMessage\n        )\n    }\n\n    // MARK: - Common implementation\n\n    public func run(_ swiftCommandState: SwiftCommandState) async throws {\n        do {\n            // Validate commands arguments\n            try self.validateArguments(swiftCommandState: swiftCommandState)\n        } catch {\n            swiftCommandState.observabilityScope.emit(error)\n            throw ExitCode.failure\n        }\n\n        if self.options.shouldPrintCodeCovPath {\n            try await printCodeCovPath(swiftCommandState)\n        } else if self.options._deprecated_shouldListTests {\n            // backward compatibility 6/2022 for deprecation of flag into a subcommand\n            let command = try List.parse()\n            try await command.run(swiftCommandState)\n        } else {\n            let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options)\n            let testProducts = try await buildTestsIfNeeded(swiftCommandState: swiftCommandState)\n\n            // Clean out the code coverage directory that may contain stale\n            // profraw files from a previous run of the code coverage tool.\n            if self.options.enableCodeCoverage {\n                try swiftCommandState.fileSystem.removeFileTree(productsBuildParameters.codeCovPath)\n            }\n\n            try await run(swiftCommandState, buildParameters: productsBuildParameters, testProducts: testProducts)\n\n            // Process code coverage if requested. We do not process it if the test run failed.\n            // See https://github.com/swiftlang/swift-package-manager/pull/6894 for more info.\n            if self.options.enableCodeCoverage, swiftCommandState.executionStatus != .failure {\n                try await processCodeCoverage(testProducts, swiftCommandState: swiftCommandState)\n            }\n        }\n    }\n\n    private func runTestProducts(\n        _ testProducts: [BuiltTestProduct],\n        additionalArguments: [String],\n        productsBuildParameters: BuildParameters,\n        swiftCommandState: SwiftCommandState,\n        library: TestingLibrary\n    ) async throws -> TestRunner.Result {\n        // Pass through all arguments from the command line to Swift Testing.\n        var additionalArguments = additionalArguments\n        if library == .swiftTesting {\n            // Reconstruct the arguments list. If an xUnit path was specified, remove it.\n            var commandLineArguments = [String]()\n            var originalCommandLineArguments = CommandLine.arguments.dropFirst().makeIterator()\n            while let arg = originalCommandLineArguments.next() {\n                if arg == \"--xunit-output\" {\n                    _ = originalCommandLineArguments.next()\n                } else {\n                    commandLineArguments.append(arg)\n                }\n            }\n            additionalArguments += commandLineArguments\n\n            if var xunitPath = options.xUnitOutput {\n                if options.testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState) {\n                    // We are running Swift Testing, XCTest is also running in this session, and an xUnit path\n                    // was specified. Make sure we don't stomp on XCTest's XML output by having Swift Testing\n                    // write to a different path.\n                    var xunitFileName = \"\\(xunitPath.basenameWithoutExt)-swift-testing\"\n                    if let ext = xunitPath.extension {\n                        xunitFileName = \"\\(xunitFileName).\\(ext)\"\n                    }\n                    xunitPath = xunitPath.parentDirectory.appending(xunitFileName)\n                }\n                additionalArguments += [\"--xunit-output\", xunitPath.pathString]\n            }\n        }\n\n        let toolchain = try swiftCommandState.getTargetToolchain()\n        let testEnv = try TestingSupport.constructTestEnvironment(\n            toolchain: toolchain,\n            destinationBuildParameters: productsBuildParameters,\n            sanitizers: globalOptions.build.sanitizers,\n            library: library,\n            testProductPaths: testProducts.map(\\.bundlePath)\n        )\n\n        let runnerPaths: [AbsolutePath] = switch library {\n        case .xctest:\n            testProducts.map(\\.bundlePath)\n        case .swiftTesting:\n            testProducts.map(\\.binaryPath)\n        }\n\n        let runner = TestRunner(\n            bundlePaths: runnerPaths,\n            additionalArguments: additionalArguments,\n            cancellator: swiftCommandState.cancellator,\n            toolchain: toolchain,\n            testEnv: testEnv,\n            observabilityScope: swiftCommandState.observabilityScope,\n            library: library\n        )\n\n        // Finally, run the tests.\n        return runner.test(outputHandler: {\n            // command's result output goes on stdout\n            // ie \"swift test\" should output to stdout\n            print($0, terminator: \"\")\n        })\n    }\n\n    private static func handleTestOutput(productsBuildParameters: BuildParameters, packagePath: AbsolutePath) throws {\n        guard localFileSystem.exists(productsBuildParameters.testOutputPath) else {\n            print(\"No existing test output found.\")\n            return\n        }\n\n        let lines = try String(contentsOfFile: productsBuildParameters.testOutputPath.pathString).components(separatedBy: \"\\n\")\n        let events = try lines.map { try JSONDecoder().decode(TestEventRecord.self, from: $0) }\n\n        let caseEvents = events.compactMap { $0.caseEvent }\n        let failureRecords = events.compactMap { $0.caseFailure }\n        let expectedFailures = failureRecords.filter({ $0.failureKind.isExpected == true })\n        let unexpectedFailures = failureRecords.filter { $0.failureKind.isExpected == false }.sorted(by: { lhs, rhs in\n            guard let lhsLocation = lhs.issue.sourceCodeContext.location, let rhsLocation = rhs.issue.sourceCodeContext.location else {\n                return lhs.description < rhs.description\n            }\n\n            if lhsLocation.file == rhsLocation.file {\n                return lhsLocation.line < rhsLocation.line\n            } else {\n                return lhsLocation.file < rhsLocation.file\n            }\n        }).map { $0.description(with: packagePath.pathString) }\n\n        let startedTests = caseEvents.filter { $0.event == .start }.count\n        let finishedTests = caseEvents.filter { $0.event == .finish }.count\n        let totalFailures = expectedFailures.count + unexpectedFailures.count\n        print(\"\\nRan \\(finishedTests)/\\(startedTests) tests, \\(totalFailures) failures (\\(unexpectedFailures.count) unexpected):\\n\")\n        print(\"\\(unexpectedFailures.joined(separator: \"\\n\"))\")\n    }\n\n    /// Processes the code coverage data and emits a json.\n    private func processCodeCoverage(\n        _ testProducts: [BuiltTestProduct],\n        swiftCommandState: SwiftCommandState\n    ) async throws {\n        let workspace = try swiftCommandState.getActiveWorkspace()\n        let root = try swiftCommandState.getWorkspaceRoot()\n        let rootManifests = try await workspace.loadRootManifests(\n            packages: root.packages,\n            observabilityScope: swiftCommandState.observabilityScope\n        )\n        guard let rootManifest = rootManifests.values.first else {\n            throw StringError(\"invalid manifests at \\(root.packages)\")\n        }\n\n        // Merge all the profraw files to produce a single profdata file.\n        try await mergeCodeCovRawDataFiles(swiftCommandState: swiftCommandState)\n\n        let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options)\n        for product in testProducts {\n            // Export the codecov data as JSON.\n            let jsonPath = productsBuildParameters.codeCovAsJSONPath(packageName: rootManifest.displayName)\n            try await exportCodeCovAsJSON(\n                to: jsonPath,\n                testBinary: product.binaryPath,\n                swiftCommandState: swiftCommandState,\n            )\n        }\n    }\n\n    /// Merges all profraw profiles in codecoverage directory into default.profdata file.\n    private func mergeCodeCovRawDataFiles(swiftCommandState: SwiftCommandState) async throws {\n        // Get the llvm-prof tool.\n        let llvmProf = try swiftCommandState.getTargetToolchain().getLLVMProf()\n\n        // Get the profraw files.\n        let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options)\n        let codeCovFiles = try swiftCommandState.fileSystem.getDirectoryContents(productsBuildParameters.codeCovPath)\n\n        // Construct arguments for invoking the llvm-prof tool.\n        var args = [llvmProf.pathString, \"merge\", \"-sparse\"]\n        for file in codeCovFiles {\n            let filePath = productsBuildParameters.codeCovPath.appending(component: file)\n            if filePath.extension == \"profraw\" {\n                args.append(filePath.pathString)\n            }\n        }\n        args += [\"-o\", productsBuildParameters.codeCovDataFile.pathString]\n        try await AsyncProcess.checkNonZeroExit(arguments: args)\n    }\n\n    /// Exports profdata as a JSON file.\n    private func exportCodeCovAsJSON(\n        to path: AbsolutePath,\n        testBinary: AbsolutePath,\n        swiftCommandState: SwiftCommandState\n    ) async throws {\n        // Export using the llvm-cov tool.\n        let llvmCov = try swiftCommandState.getTargetToolchain().getLLVMCov()\n        let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(options: self.options)\n        let archArgs: [String] = if let arch = productsBuildParameters.triple.llvmCovArchArgument {\n            [\"--arch\", \"\\(arch)\"]\n        } else {\n            []\n        }\n        let args = [\n            llvmCov.pathString,\n            \"export\",\n            \"-instr-profile=\\(productsBuildParameters.codeCovDataFile)\",\n        ] + archArgs + [\n            testBinary.pathString,\n        ]\n        let result = try await AsyncProcess.popen(arguments: args)\n\n        if result.exitStatus != .terminated(code: 0) {\n            let output = try result.utf8Output() + result.utf8stderrOutput()\n            throw StringError(\"Unable to export code coverage:\\n \\(output)\")\n        }\n        try swiftCommandState.fileSystem.writeFileContents(path, bytes: ByteString(result.output.get()))\n    }\n\n    /// Builds the \"test\" target if enabled in options.\n    ///\n    /// - Returns: The paths to the build test products.\n    private func buildTestsIfNeeded(\n        swiftCommandState: SwiftCommandState\n    ) async throws -> [BuiltTestProduct] {\n        let (productsBuildParameters, toolsBuildParameters) = try swiftCommandState.buildParametersForTest(options: self.options)\n        return try await Commands.buildTestsIfNeeded(\n            swiftCommandState: swiftCommandState,\n            productsBuildParameters: productsBuildParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            testProduct: self.options.sharedOptions.testProduct,\n            traitConfiguration: .init(traitOptions: self.globalOptions.traits)\n        )\n    }\n\n    /// Private function that validates the commands arguments\n    ///\n    /// - Throws: if a command argument is invalid\n    private func validateArguments(swiftCommandState: SwiftCommandState) throws {\n        // Validation for --num-workers.\n        if let workers = options.numberOfWorkers {\n            // The --num-worker option should be called with --parallel. Since\n            // this option does not affect swift-testing at this time, we can\n            // effectively ignore that it defaults to enabling parallelization.\n            guard options.shouldRunInParallel else {\n                throw StringError(\"--num-workers must be used with --parallel\")\n            }\n\n            guard workers > 0 else {\n                throw StringError(\"'--num-workers' must be greater than zero\")\n            }\n\n            guard options.testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState) else {\n                throw StringError(\"'--num-workers' is only supported when testing with XCTest\")\n            }\n        }\n\n        if options._deprecated_shouldListTests {\n            swiftCommandState.observabilityScope.emit(warning: \"'--list-tests' option is deprecated; use 'swift test list' instead\")\n        }\n    }\n\n    public init() {}\n}\n\nextension SwiftTestCommand {\n    func printCodeCovPath(_ swiftCommandState: SwiftCommandState) async throws {\n        let workspace = try swiftCommandState.getActiveWorkspace()\n        let root = try swiftCommandState.getWorkspaceRoot()\n        let rootManifests = try await workspace.loadRootManifests(\n            packages: root.packages,\n            observabilityScope: swiftCommandState.observabilityScope\n        )\n        guard let rootManifest = rootManifests.values.first else {\n            throw StringError(\"invalid manifests at \\(root.packages)\")\n        }\n        let (productsBuildParameters, _) = try swiftCommandState.buildParametersForTest(enableCodeCoverage: true)\n        print(productsBuildParameters.codeCovAsJSONPath(packageName: rootManifest.displayName))\n    }\n}\n\nfileprivate extension Triple {\n    var llvmCovArchArgument: String? {\n        guard let arch = self.arch else {\n            return nil\n        }\n        switch arch {\n        case .aarch64:\n            // Apple platforms uses arm64\n            return self.isApple() ? \"arm64\" : \"aarch64\"\n        default:\n            return \"\\(arch)\"\n        }\n    }\n}\n\nextension SwiftTestCommand {\n    struct Last: SwiftCommand {\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) throws {\n            try SwiftTestCommand.handleTestOutput(\n                productsBuildParameters: try swiftCommandState.productsBuildParameters,\n                packagePath: localFileSystem.currentWorkingDirectory ?? .root // by definition runs in the current working directory\n            )\n        }\n    }\n\n    struct List: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Lists test methods in specifier format\"\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @OptionGroup()\n        var sharedOptions: SharedOptions\n\n        /// Which testing libraries to use (and any related options.)\n        @OptionGroup()\n        var testLibraryOptions: TestLibraryOptions\n\n        /// Options for Swift Testing's event stream.\n        @OptionGroup()\n        var testEventStreamOptions: TestEventStreamOptions\n\n        // for deprecated passthrough from SwiftTestTool (parse will fail otherwise)\n        @Flag(name: [.customLong(\"list-tests\"), .customShort(\"l\")], help: .hidden)\n        var _deprecated_passthrough: Bool = false\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            do {\n                try await self.runCommand(swiftCommandState)\n            } catch let error as FileSystemError {\n                if sharedOptions.shouldSkipBuilding {\n                    throw ErrorWithContext(error, \"\"\"\n                        Test build artifacts were not found in the build folder.\n                        The `--skip-build` flag was provided; either build the tests first with \\\n                        `swift build --build tests` or rerun the `swift test list` command without \\\n                        `--skip-build`\n                        \"\"\"\n                    )\n                }\n                throw error\n            }\n        }\n\n        func runCommand(_ swiftCommandState: SwiftCommandState) async throws {\n            let (productsBuildParameters, toolsBuildParameters) = try swiftCommandState.buildParametersForTest(\n                enableCodeCoverage: false,\n                shouldSkipBuilding: sharedOptions.shouldSkipBuilding\n            )\n            let testProducts = try await buildTestsIfNeeded(\n                swiftCommandState: swiftCommandState,\n                productsBuildParameters: productsBuildParameters,\n                toolsBuildParameters: toolsBuildParameters\n            )\n\n            let toolchain = try swiftCommandState.getTargetToolchain()\n            let testEnv = try TestingSupport.constructTestEnvironment(\n                toolchain: toolchain,\n                destinationBuildParameters: productsBuildParameters,\n                sanitizers: globalOptions.build.sanitizers,\n                library: .swiftTesting,\n                testProductPaths: testProducts.map(\\.bundlePath)\n            )\n\n            if testLibraryOptions.isEnabled(.xctest, swiftCommandState: swiftCommandState) {\n                let testSuites = try TestingSupport.getTestSuites(\n                    in: testProducts,\n                    swiftCommandState: swiftCommandState,\n                    enableCodeCoverage: false,\n                    shouldSkipBuilding: sharedOptions.shouldSkipBuilding,\n                    experimentalTestOutput: false,\n                    sanitizers: globalOptions.build.sanitizers\n                )\n\n                // Print the tests.\n                for test in testSuites.allTests {\n                    print(test.specifier)\n                }\n            }\n\n            if testLibraryOptions.isEnabled(.swiftTesting, swiftCommandState: swiftCommandState) {\n                lazy var testEntryPointPath = testProducts.lazy.compactMap(\\.testEntryPointPath).first\n                if testLibraryOptions.isExplicitlyEnabled(.swiftTesting, swiftCommandState: swiftCommandState) || testEntryPointPath == nil {\n                    let additionalArguments = [\"--list-tests\"] + CommandLine.arguments.dropFirst()\n                    let runner = TestRunner(\n                        bundlePaths: testProducts.map(\\.binaryPath),\n                        additionalArguments: additionalArguments,\n                        cancellator: swiftCommandState.cancellator,\n                        toolchain: toolchain,\n                        testEnv: testEnv,\n                        observabilityScope: swiftCommandState.observabilityScope,\n                        library: .swiftTesting\n                    )\n\n                    // Finally, run the tests.\n                    let result = runner.test(outputHandler: {\n                        // command's result output goes on stdout\n                        // ie \"swift test\" should output to stdout\n                        print($0, terminator: \"\")\n                    })\n                    if result == .failure {\n                        swiftCommandState.executionStatus = .failure\n                        // If the runner reports failure do a check to ensure\n                        // all the binaries are present on the file system.\n                        for path in testProducts.map(\\.binaryPath) {\n                            if !swiftCommandState.fileSystem.exists(path) {\n                                throw FileSystemError(.noEntry, path)\n                            }\n                        }\n                    }\n                } else if let testEntryPointPath {\n                    // Cannot run Swift Testing because an entry point file was used and the developer\n                    // didn't explicitly enable Swift Testing.\n                    swiftCommandState.observabilityScope.emit(\n                        debug: \"Skipping automatic Swift Testing invocation (list) because a test entry point path is present: \\(testEntryPointPath)\"\n                    )\n                }\n            }\n        }\n\n        private func buildTestsIfNeeded(\n            swiftCommandState: SwiftCommandState,\n            productsBuildParameters: BuildParameters,\n            toolsBuildParameters: BuildParameters\n        ) async throws -> [BuiltTestProduct] {\n            return try await Commands.buildTestsIfNeeded(\n                swiftCommandState: swiftCommandState,\n                productsBuildParameters: productsBuildParameters,\n                toolsBuildParameters: toolsBuildParameters,\n                testProduct: self.sharedOptions.testProduct,\n                traitConfiguration: .init(traitOptions: self.globalOptions.traits)\n            )\n        }\n    }\n}\n\n/// A structure representing an individual unit test.\nstruct UnitTest {\n    /// The path to the test product containing the test.\n    let productPath: AbsolutePath\n\n    /// The name of the unit test.\n    let name: String\n\n    /// The name of the test case.\n    let testCase: String\n\n    /// The specifier argument which can be passed to XCTest.\n    var specifier: String {\n        return testCase + \"/\" + name\n    }\n}\n\n/// A class to run tests on a XCTest binary.\n///\n/// Note: Executes the XCTest with inherited environment as it is convenient to pass sensitive\n/// information like username, password etc to test cases via environment variables.\nfinal class TestRunner {\n    /// Path to valid XCTest binaries.\n    private let bundlePaths: [AbsolutePath]\n\n    /// Arguments to pass to the test runner process, if any.\n    private let additionalArguments: [String]\n\n    private let cancellator: Cancellator\n\n    // The toolchain to use.\n    private let toolchain: UserToolchain\n\n    private let testEnv: Environment\n\n    /// ObservabilityScope  to emit diagnostics.\n    private let observabilityScope: ObservabilityScope\n\n    /// Which testing library to use with this test run.\n    private let library: TestingLibrary\n\n    /// Get the arguments used on this platform to pass test specifiers to XCTest.\n    static func xctestArguments<S>(forTestSpecifiers testSpecifiers: S) -> [String] where S: Collection, S.Element == String {\n        let testSpecifier: String\n        if testSpecifiers.isEmpty {\n            testSpecifier = \"''\"\n        } else {\n            testSpecifier = testSpecifiers.joined(separator: \",\")\n        }\n\n#if os(macOS)\n        return [\"-XCTest\", testSpecifier]\n#else\n        return [testSpecifier]\n#endif\n    }\n\n    /// Creates an instance of TestRunner.\n    ///\n    /// - Parameters:\n    ///     - testPaths: Paths to valid XCTest binaries.\n    ///     - additionalArguments: Arguments to pass to the test runner process.\n    init(\n        bundlePaths: [AbsolutePath],\n        additionalArguments: [String],\n        cancellator: Cancellator,\n        toolchain: UserToolchain,\n        testEnv: Environment,\n        observabilityScope: ObservabilityScope,\n        library: TestingLibrary\n    ) {\n        self.bundlePaths = bundlePaths\n        self.additionalArguments = additionalArguments\n        self.cancellator = cancellator\n        self.toolchain = toolchain\n        self.testEnv = testEnv\n        self.observabilityScope = observabilityScope.makeChildScope(description: \"Test Runner\")\n        self.library = library\n    }\n\n    /// The result of running the test(s).\n    enum Result: Equatable {\n        /// The test(s) ran successfully.\n        case success\n\n        /// The test(s) failed.\n        case failure\n\n        /// There were no matching tests to run.\n        ///\n        /// XCTest does not report this result. It is used by Swift Testing only.\n        case noMatchingTests\n    }\n\n    /// Executes and returns execution status. Prints test output on standard streams if requested\n    /// - Returns: Result of spawning and running the test process, and the output stream result\n    func test(outputHandler: @escaping @Sendable (String) -> Void) -> Result {\n        var results = [Result]()\n        for path in self.bundlePaths {\n            let testSuccess = self.test(at: path, outputHandler: outputHandler)\n            results.append(testSuccess)\n        }\n        return results.reduce()\n    }\n\n    /// Constructs arguments to execute XCTest.\n    private func args(forTestAt testPath: AbsolutePath) throws -> [String] {\n        var args: [String] = []\n\n        if let runner = self.toolchain.swiftSDK.toolset.knownTools[.testRunner], let runnerPath = runner.path {\n            args.append(runnerPath.pathString)\n            args.append(contentsOf: runner.extraCLIOptions)\n            args.append(testPath.relative(to: localFileSystem.currentWorkingDirectory!).pathString)\n            args.append(contentsOf: self.additionalArguments)\n        } else {\n#if os(macOS)\n            switch library {\n            case .xctest:\n                guard let xctestPath = self.toolchain.xctestPath else {\n                    throw TestError.xcodeNotInstalled\n                }\n                args += [xctestPath.pathString]\n            case .swiftTesting:\n                let helper = try self.toolchain.getSwiftTestingHelper()\n                args += [helper.pathString, \"--test-bundle-path\", testPath.pathString]\n            }\n            args += self.additionalArguments\n            args += [testPath.pathString]\n    #else\n            args += [testPath.pathString]\n            args += self.additionalArguments\n    #endif\n        }\n\n        if library == .swiftTesting {\n            // HACK: tell the test bundle/executable that we want to run Swift Testing, not XCTest.\n            // XCTest doesn't understand this argument (yet), so don't pass it there.\n            args += [\"--testing-library\", \"swift-testing\"]\n        }\n\n        return args\n    }\n\n    private func test(at path: AbsolutePath, outputHandler: @escaping @Sendable (String) -> Void) -> Result {\n        let testObservabilityScope = self.observabilityScope.makeChildScope(description: \"running test at \\(path)\")\n\n        do {\n            let outputHandler: @Sendable ([UInt8]) -> Void = { (bytes: [UInt8]) in\n                if let output = String(bytes: bytes, encoding: .utf8) {\n                    outputHandler(output)\n                }\n            }\n            let outputRedirection = AsyncProcess.OutputRedirection.stream(\n                stdout: outputHandler,\n                stderr: outputHandler\n            )\n            let arguments = try args(forTestAt: path)\n            let process = AsyncProcess(arguments: arguments, environment: self.testEnv, outputRedirection: outputRedirection)\n            guard let terminationKey = self.cancellator.register(process) else {\n                return .failure // terminating\n            }\n            defer { self.cancellator.deregister(terminationKey) }\n            try process.launch()\n            let result = try process.waitUntilExit()\n            switch result.exitStatus {\n            case .terminated(code: 0):\n                return .success\n            case .terminated(code: EXIT_NO_TESTS_FOUND) where library == .swiftTesting:\n                return .noMatchingTests\n            #if !os(Windows)\n            case .signalled(let signal) where ![SIGINT, SIGKILL, SIGTERM].contains(signal):\n                testObservabilityScope.emit(error: \"Process '\\(arguments.joined(separator: \" \"))' exited with unexpected signal code \\(signal)\")\n                return .failure\n            #endif\n            default:\n                return .failure\n            }\n        } catch {\n            testObservabilityScope.emit(error)\n            return .failure\n        }\n    }\n}\n\nextension Collection where Element == TestRunner.Result {\n    /// Reduce all results in this collection into a single result.\n    func reduce() -> Element {\n        if contains(.failure) {\n            return .failure\n        } else if isEmpty || contains(.success) {\n            return .success\n        } else {\n            return .noMatchingTests\n        }\n    }\n}\n\n/// A class to run tests in parallel.\nfinal class ParallelTestRunner {\n    /// An enum representing result of a unit test execution.\n    struct TestResult {\n        var unitTest: UnitTest\n        var output: String\n        var success: Bool\n        var duration: DispatchTimeInterval\n    }\n\n    /// Path to XCTest binaries.\n    private let bundlePaths: [AbsolutePath]\n\n    /// The queue containing list of tests to run (producer).\n    private let pendingTests = SynchronizedQueue<UnitTest?>()\n\n    /// The queue containing tests which are finished running.\n    private let finishedTests = SynchronizedQueue<TestResult?>()\n\n    /// Instance of a terminal progress animation.\n    private let progressAnimation: ProgressAnimationProtocol\n\n    /// Number of tests that will be executed.\n    private var numTests = 0\n\n    /// Number of the current tests that has been executed.\n    private var numCurrentTest = 0\n\n    /// True if all tests executed successfully.\n    private(set) var ranSuccessfully = true\n\n    private let cancellator: Cancellator\n\n    private let toolchain: UserToolchain\n\n    private let buildOptions: BuildOptions\n    private let productsBuildParameters: BuildParameters\n\n    /// Number of tests to execute in parallel.\n    private let numJobs: Int\n\n    /// Whether to display output from successful tests.\n    private let shouldOutputSuccess: Bool\n\n    /// ObservabilityScope to emit diagnostics.\n    private let observabilityScope: ObservabilityScope\n\n    init(\n        bundlePaths: [AbsolutePath],\n        cancellator: Cancellator,\n        toolchain: UserToolchain,\n        numJobs: Int,\n        buildOptions: BuildOptions,\n        productsBuildParameters: BuildParameters,\n        shouldOutputSuccess: Bool,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.bundlePaths = bundlePaths\n        self.cancellator = cancellator\n        self.toolchain = toolchain\n        self.numJobs = numJobs\n        self.shouldOutputSuccess = shouldOutputSuccess\n        self.observabilityScope = observabilityScope.makeChildScope(description: \"Parallel Test Runner\")\n\n        // command's result output goes on stdout\n        // ie \"swift test\" should output to stdout\n        if Environment.current[\"SWIFTPM_TEST_RUNNER_PROGRESS_BAR\"] == \"lit\" {\n            self.progressAnimation = ProgressAnimation.percent(\n                stream: TSCBasic.stdoutStream,\n                verbose: false,\n                header: \"Testing:\",\n                isColorized: productsBuildParameters.outputParameters.isColorized\n            )\n        } else {\n            self.progressAnimation = ProgressAnimation.ninja(\n                stream: TSCBasic.stdoutStream,\n                verbose: false\n            )\n        }\n\n        self.buildOptions = buildOptions\n        self.productsBuildParameters = productsBuildParameters\n\n        assert(numJobs > 0, \"num jobs should be > 0\")\n    }\n\n    /// Updates the progress bar status.\n    private func updateProgress(for test: UnitTest) {\n        numCurrentTest += 1\n        progressAnimation.update(step: numCurrentTest, total: numTests, text: \"Testing \\(test.specifier)\")\n    }\n\n    private func enqueueTests(_ tests: [UnitTest]) throws {\n        // Enqueue all the tests.\n        for test in tests {\n            pendingTests.enqueue(test)\n        }\n        self.numTests = tests.count\n        self.numCurrentTest = 0\n        // Enqueue the sentinels, we stop a thread when it encounters a sentinel in the queue.\n        for _ in 0..<numJobs {\n            pendingTests.enqueue(nil)\n        }\n    }\n\n    /// Executes the tests spawning parallel workers. Blocks calling thread until all workers are finished.\n    func run(_ tests: [UnitTest]) throws -> [TestResult] {\n        assert(!tests.isEmpty, \"There should be at least one test to execute.\")\n\n        let testEnv = try TestingSupport.constructTestEnvironment(\n            toolchain: self.toolchain,\n            destinationBuildParameters: self.productsBuildParameters,\n            sanitizers: self.buildOptions.sanitizers,\n            library: .xctest, // swift-testing does not use ParallelTestRunner\n            testProductPaths: bundlePaths\n        )\n\n        // Enqueue all the tests.\n        try enqueueTests(tests)\n\n        // Create the worker threads.\n        let workers: [Thread] = (0..<numJobs).map({ _ in\n            let thread = Thread {\n                // Dequeue a specifier and run it till we encounter nil.\n                while let test = self.pendingTests.dequeue() {\n                    let additionalArguments = TestRunner.xctestArguments(forTestSpecifiers: CollectionOfOne(test.specifier))\n                    let testRunner = TestRunner(\n                        bundlePaths: [test.productPath],\n                        additionalArguments: additionalArguments,\n                        cancellator: self.cancellator,\n                        toolchain: self.toolchain,\n                        testEnv: testEnv,\n                        observabilityScope: self.observabilityScope,\n                        library: .xctest // swift-testing does not use ParallelTestRunner\n                    )\n                    let output = ThreadSafeBox<String>(\"\")\n                    let start = DispatchTime.now()\n                    let result = testRunner.test(outputHandler: { _output in output.append(_output) })\n                    let duration = start.distance(to: .now())\n                    if result == .failure {\n                        self.ranSuccessfully = false\n                    }\n                    self.finishedTests.enqueue(TestResult(\n                        unitTest: test,\n                        output: output.get(),\n                        success: result != .failure,\n                        duration: duration\n                    ))\n                }\n            }\n            thread.start()\n            return thread\n        })\n\n        // List of processed tests.\n        let processedTests = ThreadSafeArrayStore<TestResult>()\n\n        // Report (consume) the tests which have finished running.\n        while let result = finishedTests.dequeue() {\n            updateProgress(for: result.unitTest)\n\n            // Store the result.\n            processedTests.append(result)\n\n            // We can't enqueue a sentinel into finished tests queue because we won't know\n            // which test is last one so exit this when all the tests have finished running.\n            if numCurrentTest == numTests {\n                break\n            }\n        }\n\n        // Wait till all threads finish execution.\n        workers.forEach { $0.join() }\n\n        // Report the completion.\n        progressAnimation.complete(success: processedTests.get().contains(where: { !$0.success }))\n\n        // Print test results.\n        for test in processedTests.get() {\n            if (!test.success || shouldOutputSuccess) && !productsBuildParameters.testingParameters.experimentalTestOutput {\n                // command's result output goes on stdout\n                // ie \"swift test\" should output to stdout\n                print(test.output)\n            }\n        }\n\n        return processedTests.get()\n    }\n}\n\n/// A struct to hold the XCTestSuite data.\nstruct TestSuite {\n    /// A struct to hold a XCTestCase data.\n    struct TestCase {\n        /// Name of the test case.\n        let name: String\n\n        /// Array of test methods in this test case.\n        let tests: [String]\n    }\n\n    /// The name of the test suite.\n    let name: String\n\n    /// Array of test cases in this test suite.\n    let tests: [TestCase]\n\n    /// Parses a JSON String to array of TestSuite.\n    ///\n    /// - Parameters:\n    ///     - jsonString: JSON string to be parsed.\n    ///     - context: the commandline which produced the given JSON.\n    ///\n    /// - Throws: JSONDecodingError, TestError\n    ///\n    /// - Returns: Array of TestSuite.\n    static func parse(jsonString: String, context: String) throws -> [TestSuite] {\n        let json: JSON\n        do {\n            json = try JSON(string: jsonString)\n        } catch {\n            throw TestError.invalidListTestJSONData(context: context, underlyingError: error)\n        }\n        return try TestSuite.parse(json: json, context: context)\n    }\n\n    /// Parses the JSON object into array of TestSuite.\n    ///\n    /// - Parameters:\n    ///     - json: An object of JSON.\n    ///     - context: the commandline which produced the given JSON.\n    ///\n    /// - Throws: TestError\n    ///\n    /// - Returns: Array of TestSuite.\n    static func parse(json: JSON, context: String) throws -> [TestSuite] {\n        guard case let .dictionary(contents) = json,\n              case let .array(testSuites)? = contents[\"tests\"] else {\n            throw TestError.invalidListTestJSONData(context: context)\n        }\n\n        return try testSuites.map({ testSuite in\n            guard case let .dictionary(testSuiteData) = testSuite,\n                  case let .string(name)? = testSuiteData[\"name\"],\n                  case let .array(allTestsData)? = testSuiteData[\"tests\"] else {\n                throw TestError.invalidListTestJSONData(context: context)\n            }\n\n            let testCases: [TestSuite.TestCase] = try allTestsData.map({ testCase in\n                guard case let .dictionary(testCaseData) = testCase,\n                      case let .string(name)? = testCaseData[\"name\"],\n                      case let .array(tests)? = testCaseData[\"tests\"] else {\n                    throw TestError.invalidListTestJSONData(context: context)\n                }\n                let testMethods: [String] = try tests.map({ test in\n                    guard case let .dictionary(testData) = test,\n                          case let .string(testMethod)? = testData[\"name\"] else {\n                        throw TestError.invalidListTestJSONData(context: context)\n                    }\n                    return testMethod\n                })\n                return TestSuite.TestCase(name: name, tests: testMethods)\n            })\n\n            return TestSuite(name: name, tests: testCases)\n        })\n    }\n}\n\nfileprivate extension Dictionary where Key == AbsolutePath, Value == [TestSuite] {\n    /// Returns all the unit tests of the test suites.\n    var allTests: [UnitTest] {\n        var allTests: [UnitTest] = []\n        for (bundlePath, testSuites) in self {\n            for testSuite in testSuites {\n                for testCase in testSuite.tests {\n                    for test in testCase.tests {\n                        allTests.append(UnitTest(productPath: bundlePath, name: test, testCase: testCase.name))\n                    }\n                }\n            }\n        }\n        return allTests\n    }\n\n    /// Return tests matching the provided specifier\n    func filteredTests(specifier: TestCaseSpecifier) throws -> [UnitTest] {\n        switch specifier {\n        case .none:\n            return allTests\n        case .regex(let patterns):\n            return allTests.filter({ test in\n                patterns.contains { pattern in\n                    test.specifier.range(of: pattern,\n                                         options: .regularExpression) != nil\n                }\n            })\n        case .specific(let name):\n            return allTests.filter{ $0.specifier == name }\n        case .skip:\n            throw InternalError(\"Tests to skip should never have been passed here.\")\n        }\n    }\n}\n\nfileprivate extension Array where Element == UnitTest {\n    /// Skip tests matching the provided specifier\n    func skippedTests(specifier: TestCaseSpecifier) throws -> [UnitTest] {\n        switch specifier {\n        case .none:\n            return self\n        case .skip(let skippedTests):\n            var result = self\n            for skippedTest in skippedTests {\n                result = result.filter{\n                    $0.specifier.range(of: skippedTest, options: .regularExpression) == nil\n                }\n            }\n            return result\n        case .regex, .specific:\n            throw InternalError(\"Tests to filter should never have been passed here.\")\n        }\n    }\n}\n\n/// xUnit XML file generator for a swift-test run.\nfinal class XUnitGenerator {\n    typealias TestResult = ParallelTestRunner.TestResult\n\n    /// The file system to use\n    let fileSystem: FileSystem\n\n    /// The test results.\n    let results: [TestResult]\n\n    init(fileSystem: FileSystem, results: [TestResult]) {\n        self.fileSystem = fileSystem\n        self.results = results\n    }\n\n    /// Generate the file at the given path.\n    func generate(at path: AbsolutePath, detailedFailureMessage: Bool) throws {\n        var content =\n            \"\"\"\n            <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n            <testsuites>\n\n            \"\"\"\n\n        // Get the failure count.\n        let failures = results.filter({ !$0.success }).count\n        let duration = results.compactMap({ $0.duration.timeInterval() }).reduce(0.0, +)\n\n        // We need better output reporting from XCTest.\n        content +=\n            \"\"\"\n            <testsuite name=\"TestResults\" errors=\"0\" tests=\"\\(results.count)\" failures=\"\\(failures)\" time=\"\\(duration)\">\n\n            \"\"\"\n\n        // Generate a testcase entry for each result.\n        //\n        // FIXME: This is very minimal right now. We should allow including test output etc.\n        for result in results {\n            let test = result.unitTest\n            let duration = result.duration.timeInterval() ?? 0.0\n            content +=\n                \"\"\"\n                <testcase classname=\"\\(test.testCase)\" name=\"\\(test.name)\" time=\"\\(duration)\">\n\n                \"\"\"\n\n            if !result.success {\n                let failureMessage = detailedFailureMessage ? result.output.map(_escapeForXML).joined() : \"failure\"\n                content += \"<failure message=\\\"\\(failureMessage)\\\"></failure>\\n\"\n            }\n\n            content += \"</testcase>\\n\"\n        }\n\n        content +=\n            \"\"\"\n            </testsuite>\n            </testsuites>\n\n            \"\"\"\n\n        try self.fileSystem.writeFileContents(path, string: content)\n    }\n}\n\n/// Escape a single Unicode character for use in an XML-encoded string.\n///\n/// - Parameters:\n///   - character: The character to escape.\n///\n/// - Returns: `character`, or a string containing its escaped form.\nprivate func _escapeForXML(_ character: Character) -> String {\n    switch character {\n    case \"\\\"\":\n        \"&quot;\"\n    case \"<\":\n        \"&lt;\"\n    case \">\":\n        \"&gt;\"\n    case \"&\":\n        \"&amp;\"\n    case _ where !character.isASCII || character.isNewline:\n    character.unicodeScalars.lazy\n        .map(\\.value)\n        .map { \"&#\\($0);\" }\n        .joined()\n    default:\n    String(character)\n    }\n}\n\nextension SwiftCommandState {\n    func buildParametersForTest(\n        options: TestCommandOptions\n    ) throws -> (productsBuildParameters: BuildParameters, toolsBuildParameters: BuildParameters) {\n        try self.buildParametersForTest(\n            enableCodeCoverage: options.enableCodeCoverage,\n            enableTestability: options.enableTestableImports,\n            shouldSkipBuilding: options.sharedOptions.shouldSkipBuilding,\n            experimentalTestOutput: options.enableExperimentalTestOutput\n        )\n    }\n}\n\nextension TestCommandOptions {\n    func skippedTests(fileSystem: FileSystem) -> TestCaseSpecifier {\n        // TODO: Remove this once the environment variable is no longer used.\n        if let override = skippedTestsOverride(fileSystem: fileSystem) {\n            return override\n        }\n\n        return self._testCaseSkip.isEmpty\n            ? .none\n            : .skip(self._testCaseSkip)\n    }\n\n    /// Returns the test case specifier if overridden in the env.\n    private func skippedTestsOverride(fileSystem: FileSystem) -> TestCaseSpecifier? {\n        guard let override = Environment.current[\"_SWIFTPM_SKIP_TESTS_LIST\"] else {\n            return nil\n        }\n\n        do {\n            let skipTests: [String.SubSequence]\n            // Read from the file if it exists.\n            if let path = try? AbsolutePath(validating: override), fileSystem.exists(path) {\n                let contents: String = try fileSystem.readFileContents(path)\n                skipTests = contents.split(separator: \"\\n\", omittingEmptySubsequences: true)\n            } else {\n                // Otherwise, read the env variable.\n                skipTests = override.split(separator: \":\", omittingEmptySubsequences: true)\n            }\n\n            return .skip(skipTests.map(String.init))\n        } catch {\n            // FIXME: We should surface errors from here.\n        }\n        return nil\n    }\n}\n\nextension BuildParameters {\n    fileprivate func codeCovAsJSONPath(packageName: String) -> AbsolutePath {\n        return self.codeCovPath.appending(component: packageName + \".json\")\n    }\n}\n\nprivate extension Basics.Diagnostic {\n    static var noMatchingTests: Self {\n        .warning(\"No matching test cases were run\")\n    }\n}\n\n/// The exit code returned to Swift Package Manager by Swift Testing when no\n/// tests matched the inputs specified by the developer (or, for the case of\n/// `swift test list`, when no tests were found.)\n///\n/// Because Swift Package Manager does not directly link to the testing library,\n/// it duplicates the definition of this constant in its own source. Any changes\n/// to this constant in either package must be mirrored in the other.\nprivate var EXIT_NO_TESTS_FOUND: CInt {\n#if os(macOS) || os(Linux) || canImport(Android) || os(FreeBSD)\n    EX_UNAVAILABLE\n#elseif os(Windows)\n    ERROR_NOT_FOUND\n#else\n#warning(\"Platform-specific implementation missing: value for EXIT_NO_TESTS_FOUND unavailable\")\n    return 2 // We're assuming that EXIT_SUCCESS = 0 and EXIT_FAILURE = 1.\n#endif\n}\n\n/// Builds the \"test\" target if enabled in options.\n///\n/// - Returns: The paths to the build test products.\nprivate func buildTestsIfNeeded(\n    swiftCommandState: SwiftCommandState,\n    productsBuildParameters: BuildParameters,\n    toolsBuildParameters: BuildParameters,\n    testProduct: String?,\n    traitConfiguration: TraitConfiguration\n) async throws -> [BuiltTestProduct] {\n    let buildSystem = try await swiftCommandState.createBuildSystem(\n        productsBuildParameters: productsBuildParameters,\n        toolsBuildParameters: toolsBuildParameters\n    )\n\n    let subset: BuildSubset = if let testProduct {\n        .product(testProduct)\n    } else {\n        .allIncludingTests\n    }\n\n    try await buildSystem.build(subset: subset, buildOutputs: [])\n\n    // Find the test product.\n    let testProducts = await buildSystem.builtTestProducts\n    guard !testProducts.isEmpty else {\n        if let testProduct {\n            throw TestError.productIsNotTest(productName: testProduct)\n        } else {\n            throw TestError.testsNotFound\n        }\n    }\n\n    if let testProductName = testProduct {\n        if let selectedTestProduct = testProducts.first(where: { $0.productName == testProductName }) {\n            return [selectedTestProduct]\n        }\n\n        let selectedTestProducts = testProducts.filter({ $0.umbrellaProductName == testProductName })\n        if !selectedTestProducts.isEmpty {\n            return selectedTestProducts\n        }\n\n        throw TestError.testProductNotFound(productName: testProductName)\n    } else {\n        return testProducts\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/APIDigester.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Dispatch\nimport Foundation\n\nimport SPMBuildCore\nimport Basics\nimport CoreCommands\nimport PackageGraph\nimport PackageModel\nimport SourceControl\nimport Workspace\n\nimport protocol TSCBasic.DiagnosticLocation\nimport class Basics.AsyncProcess\nimport struct Basics.AsyncProcessResult\nimport func TSCBasic.withTemporaryFile\n\nimport enum TSCUtility.Diagnostics\nimport struct TSCUtility.SerializedDiagnostics\nimport var TSCUtility.verbosity\n\n/// Helper for emitting a JSON API baseline for a module.\nstruct APIDigesterBaselineDumper {\n\n    /// The revision to emit a baseline for.\n    let baselineRevision: Revision\n\n    /// The root package path.\n    let packageRoot: AbsolutePath\n\n    /// Parameters used when building end products.\n    let productsBuildParameters: BuildParameters\n\n    /// Parameters used when building tools (plugins and macros).\n    let toolsBuildParameters: BuildParameters\n\n    /// The API digester tool.\n    let apiDigesterTool: SwiftAPIDigester\n\n    /// The observabilityScope for emitting errors/warnings.\n    let observabilityScope: ObservabilityScope\n\n    init(\n        baselineRevision: Revision,\n        packageRoot: AbsolutePath,\n        productsBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n        apiDigesterTool: SwiftAPIDigester,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.baselineRevision = baselineRevision\n        self.packageRoot = packageRoot\n        self.productsBuildParameters = productsBuildParameters\n        self.toolsBuildParameters = toolsBuildParameters\n        self.apiDigesterTool = apiDigesterTool\n        self.observabilityScope = observabilityScope\n    }\n\n    /// Emit the API baseline files and return the path to their directory.\n    func emitAPIBaseline(\n        for modulesToDiff: Set<String>,\n        at baselineDir: AbsolutePath?,\n        force: Bool,\n        logLevel: Basics.Diagnostic.Severity,\n        swiftCommandState: SwiftCommandState\n    ) async throws -> AbsolutePath {\n        var modulesToDiff = modulesToDiff\n        let apiDiffDir = productsBuildParameters.apiDiff\n        let baselineDir = (baselineDir ?? apiDiffDir).appending(component: baselineRevision.identifier)\n        let baselinePath: (String)->AbsolutePath = { module in\n            baselineDir.appending(component: module + \".json\")\n        }\n\n        if !force {\n            // Baselines which already exist don't need to be regenerated.\n            modulesToDiff = modulesToDiff.filter {\n                !swiftCommandState.fileSystem.exists(baselinePath($0))\n            }\n        }\n\n        guard !modulesToDiff.isEmpty else {\n            // If none of the baselines need to be regenerated, return.\n            return baselineDir\n        }\n\n        // Setup a temporary directory where we can checkout and build the baseline treeish.\n        let baselinePackageRoot = apiDiffDir.appending(\"\\(baselineRevision.identifier)-checkout\")\n        if swiftCommandState.fileSystem.exists(baselinePackageRoot) {\n            try swiftCommandState.fileSystem.removeFileTree(baselinePackageRoot)\n        }\n\n        // Clone the current package in a sandbox and checkout the baseline revision.\n        let repositoryProvider = GitRepositoryProvider()\n        let specifier = RepositorySpecifier(path: baselinePackageRoot)\n        let workingCopy = try await repositoryProvider.createWorkingCopy(\n            repository: specifier,\n            sourcePath: packageRoot,\n            at: baselinePackageRoot,\n            editable: false\n        )\n\n        try workingCopy.checkout(revision: baselineRevision)\n\n        // Create the workspace for this package.\n        let workspace = try Workspace(\n            forRootPackage: baselinePackageRoot,\n            cancellator: swiftCommandState.cancellator\n        )\n\n        let graph = try await workspace.loadPackageGraph(\n            rootPath: baselinePackageRoot,\n            observabilityScope: self.observabilityScope\n        )\n\n        // Don't emit a baseline for a module that didn't exist yet in this revision.\n        modulesToDiff.formIntersection(graph.apiDigesterModules)\n\n        // Abort if we weren't able to load the package graph.\n        if observabilityScope.errorsReported {\n            throw Diagnostics.fatalError\n        }\n\n        // Update the data path input build parameters so it's built in the sandbox.\n        var productsBuildParameters = productsBuildParameters\n        productsBuildParameters.dataPath = workspace.location.scratchDirectory\n\n        // Build the baseline module.\n        // FIXME: We need to implement the build tool invocation closure here so that build tool plugins work with the APIDigester. rdar://86112934\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            explicitBuildSystem: .native,\n            cacheBuildManifest: false,\n            productsBuildParameters: productsBuildParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            packageGraphLoader: { graph }\n        )\n        let buildResult = try await buildSystem.build(subset: .allExcludingTests, buildOutputs: [.buildPlan])\n\n        guard let buildPlan = buildResult.buildPlan else {\n            throw Diagnostics.fatalError\n        }\n\n        // Dump the SDK JSON.\n        try swiftCommandState.fileSystem.createDirectory(baselineDir, recursive: true)\n\n        let errors = await withTaskGroup(of: Error?.self) { group in\n            for module in modulesToDiff {\n                group.addTask {\n                    do {\n                        try apiDigesterTool.emitAPIBaseline(\n                            to: baselinePath(module),\n                            for: module,\n                            buildPlan: buildPlan\n                        )\n                        return nil\n                    } catch {\n                        return error\n                    }\n                }\n            }\n            return await group.compactMap { $0 }.reduce(into: []) {\n                $0.append($1)\n            }\n        }\n\n        for error in errors {\n            observabilityScope.emit(error)\n        }\n        if observabilityScope.errorsReported {\n            throw Diagnostics.fatalError\n        }\n\n        return baselineDir\n    }\n}\n\n/// A wrapper for the swift-api-digester tool.\npublic struct SwiftAPIDigester {\n    /// The file system to use\n    let fileSystem: FileSystem\n\n    /// The absolute path to `swift-api-digester` in the toolchain.\n    let tool: AbsolutePath\n\n    init(fileSystem: FileSystem, tool: AbsolutePath) {\n        self.fileSystem = fileSystem\n        self.tool = tool\n    }\n\n    /// Emit an API baseline file for the specified module at the specified location.\n    public func emitAPIBaseline(\n        to outputPath: AbsolutePath,\n        for module: String,\n        buildPlan: SPMBuildCore.BuildPlan\n    ) throws {\n        var args = [\"-dump-sdk\", \"-compiler-style-diags\"]\n        args += try buildPlan.createAPIToolCommonArgs(includeLibrarySearchPaths: false)\n        args += [\"-module\", module, \"-o\", outputPath.pathString]\n\n        let result = try runTool(args)\n\n        if !self.fileSystem.exists(outputPath) {\n            throw Error.failedToGenerateBaseline(module: module, output: (try? result.utf8Output()) ?? \"\", error: (try? result.utf8stderrOutput()) ?? \"\")\n        }\n\n        try self.fileSystem.readFileContents(outputPath).withData { data in\n            if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {\n                guard let abiRoot = jsonObject[\"ABIRoot\"] as? [String:Any] else {\n                    throw Error.failedToValidateBaseline(module: module)\n                }\n\n                guard let symbols = abiRoot[\"children\"] as? NSArray, symbols.count > 0 else {\n                    throw Error.noSymbolsInBaseline(module: module, toolOutput: try result.utf8Output())\n                }\n            }\n        }\n\n    }\n\n    /// Compare the current package API to a provided baseline file.\n    public func compareAPIToBaseline(\n        at baselinePath: AbsolutePath,\n        for module: String,\n        buildPlan: SPMBuildCore.BuildPlan,\n        except breakageAllowlistPath: AbsolutePath?\n    ) throws -> ComparisonResult? {\n        var args = [\n            \"-diagnose-sdk\",\n            \"-baseline-path\", baselinePath.pathString,\n            \"-module\", module\n        ]\n        args.append(contentsOf: try buildPlan.createAPIToolCommonArgs(includeLibrarySearchPaths: false))\n        if let breakageAllowlistPath {\n            args.append(contentsOf: [\"-breakage-allowlist-path\", breakageAllowlistPath.pathString])\n        }\n\n        return try? withTemporaryFile(deleteOnClose: false) { file in\n            args.append(contentsOf: [\"-serialize-diagnostics-path\", file.path.pathString])\n            try runTool(args)\n            let contents = try self.fileSystem.readFileContents(file.path)\n            guard contents.count > 0 else {\n                return nil\n            }\n            let serializedDiagnostics = try SerializedDiagnostics(bytes: contents)\n            let apiDigesterCategory = \"api-digester-breaking-change\"\n            let apiBreakingChanges = serializedDiagnostics.diagnostics.filter { $0.category == apiDigesterCategory }\n            let otherDiagnostics = serializedDiagnostics.diagnostics.filter { $0.category != apiDigesterCategory }\n            return ComparisonResult(moduleName: module,\n                                    apiBreakingChanges: apiBreakingChanges,\n                                    otherDiagnostics: otherDiagnostics)\n        }\n    }\n\n    @discardableResult private func runTool(_ args: [String]) throws -> AsyncProcessResult {\n        let arguments = [tool.pathString] + args\n        let process = AsyncProcess(\n            arguments: arguments,\n            outputRedirection: .collect(redirectStderr: true)\n        )\n        try process.launch()\n        return try process.waitUntilExit()\n    }\n}\n\nextension SwiftAPIDigester {\n    public enum Error: Swift.Error, CustomStringConvertible {\n        case failedToGenerateBaseline(module: String, output: String, error: String)\n        case failedToValidateBaseline(module: String)\n        case noSymbolsInBaseline(module: String, toolOutput: String)\n\n        public var description: String {\n            switch self {\n            case .failedToGenerateBaseline(let module, let output, let error):\n                return \"failed to generate baseline for \\(module) (output: \\(output), error: \\(error)\"\n            case .failedToValidateBaseline(let module):\n                return \"failed to validate baseline for \\(module)\"\n            case .noSymbolsInBaseline(let module, let toolOutput):\n                return \"baseline for \\(module) contains no symbols, swift-api-digester output: \\(toolOutput)\"\n            }\n        }\n    }\n}\n\nextension SwiftAPIDigester {\n    /// The result of comparing a module's API to a provided baseline.\n    public struct ComparisonResult {\n        /// The name of the module being diffed.\n        var moduleName: String\n        /// Breaking changes made to the API since the baseline was generated.\n        var apiBreakingChanges: [SerializedDiagnostics.Diagnostic]\n        /// Other diagnostics emitted while comparing the current API to the baseline.\n        var otherDiagnostics: [SerializedDiagnostics.Diagnostic]\n\n        /// `true` if the comparison succeeded and no breaking changes were found, otherwise `false`.\n        var hasNoAPIBreakingChanges: Bool {\n            apiBreakingChanges.isEmpty && otherDiagnostics.filter { [.fatal, .error].contains($0.level) }.isEmpty\n        }\n    }\n}\n\nextension BuildParameters {\n    /// The directory containing artifacts for API diffing operations.\n    var apiDiff: AbsolutePath {\n        dataPath.appending(\"apidiff\")\n    }\n}\n\nextension ModulesGraph {\n    /// The list of modules that should be used as an input to the API digester.\n    var apiDigesterModules: [String] {\n        self.rootPackages\n            .flatMap(\\.products)\n            .filter { $0.type.isLibrary }\n            .flatMap(\\.modules)\n            .filter { $0.underlying is SwiftModule }\n            .map { $0.c99name }\n    }\n}\n\nextension SerializedDiagnostics.SourceLocation {\n    public var description: String {\n        return \"\\(filename):\\(line):\\(column)\"\n    }\n}\n\nextension SerializedDiagnostics.SourceLocation: @retroactive DiagnosticLocation {}\n"
  },
  {
    "path": "Sources/Commands/Utilities/DOTManifestSerializer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport LLBuildManifest\n\nimport protocol TSCBasic.OutputByteStream\n\n/// Serializes an LLBuildManifest graph to a .dot file.\nstruct DOTManifestSerializer {\n    var kindCounter = [String: Int]()\n    var hasEmittedStyling = Set<String>()\n    let manifest: LLBuildManifest\n\n    /// Creates a serializer that will serialize the given manifest.\n    init(manifest: LLBuildManifest) {\n        self.manifest = manifest\n    }\n\n    /// Gets a unique label for a job name.\n    mutating func label(for command: Command) -> String {\n        let toolName = \"\\(type(of: command.tool).name)\"\n        var label = toolName\n        if let count = kindCounter[label] {\n            label += \" \\(count)\"\n        }\n        kindCounter[toolName, default: 0] += 1\n        return label\n    }\n\n    /// Quote the name and escape the quotes and backslashes.\n    func quoteName(_ name: String) -> String {\n        \"\\\"\" + name.replacing(\"\\\"\", with: \"\\\\\\\"\")\n                   .replacing(\"\\\\\", with: \"\\\\\\\\\") + \"\\\"\"\n    }\n\n    mutating func writeDOT(to stream: OutputByteStream) {\n        stream.write(\"digraph Jobs {\\n\")\n        for (name, command) in manifest.commands {\n            let jobName = quoteName(label(for: command))\n            if !hasEmittedStyling.contains(jobName) {\n                stream.write(\"  \\(jobName) [style=bold];\")\n                stream.write(\"// \\(name)\\n\")\n            }\n            for input in command.tool.inputs {\n                let inputName = quoteName(input.name)\n                if hasEmittedStyling.insert(inputName).inserted {\n                    stream.write(\"  \\(inputName) [fontsize=12];\\n\")\n                }\n                stream.write(\"  \\(inputName) -> \\(jobName) [color=blue];\\n\")\n            }\n            for output in command.tool.outputs {\n                let outputName = quoteName(output.name)\n                if hasEmittedStyling.insert(outputName).inserted {\n                    stream.write(\"  \\(outputName) [fontsize=12];\\n\")\n                }\n                stream.write(\"  \\(jobName) -> \\(outputName) [color=green];\\n\")\n            }\n        }\n        stream.write(\"}\\n\")\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/DependenciesSerializer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport PackageGraph\nimport TSCUtility\n\nimport enum TSCBasic.JSON\nimport protocol TSCBasic.OutputByteStream\n\nprotocol DependenciesDumper {\n    func dump(graph: ModulesGraph, dependenciesOf: ResolvedPackage, on: OutputByteStream)\n}\n\nfinal class PlainTextDumper: DependenciesDumper {\n    func dump(graph: ModulesGraph, dependenciesOf rootpkg: ResolvedPackage, on stream: OutputByteStream) {\n        func recursiveWalk(packages: [ResolvedPackage], prefix: String = \"\") {\n            var hanger = prefix + \"├── \"\n\n            for (index, package) in packages.enumerated() {\n                if index == packages.count - 1 {\n                    hanger = prefix + \"└── \"\n                }\n\n                let pkgVersion = package.manifest.version?.description ?? \"unspecified\"\n\n                let traitsEnabled: String\n                if let enabled = package.enabledTraits, !enabled.isEmpty {\n                    traitsEnabled = \"(traits: \\(package.enabledTraits?.joined(separator: \", \") ?? \"\"))\"\n                } else {\n                    traitsEnabled = \"\"\n                }\n\n                stream.send(\"\\(hanger)\\(package.identity.description)<\\(package.manifest.packageLocation)@\\(pkgVersion)>\\(traitsEnabled)\\n\")\n\n                if !package.dependencies.isEmpty {\n                    let replacement = (index == packages.count - 1) ?  \"    \" : \"│   \"\n                    var childPrefix = hanger\n                    let startIndex = childPrefix.index(childPrefix.endIndex, offsetBy: -4)\n                    childPrefix.replaceSubrange(startIndex..<childPrefix.endIndex, with: replacement)\n                    recursiveWalk(packages: graph.directDependencies(for: package), prefix: childPrefix)\n                }\n            }\n        }\n\n        if !rootpkg.dependencies.isEmpty {\n            stream.send(\".\\n\")\n            recursiveWalk(packages: graph.directDependencies(for: rootpkg))\n        } else {\n            stream.send(\"No external dependencies found\\n\")\n        }\n    }\n}\n\nfinal class FlatListDumper: DependenciesDumper {\n    func dump(graph: ModulesGraph, dependenciesOf rootpkg: ResolvedPackage, on stream: OutputByteStream) {\n        func recursiveWalk(packages: [ResolvedPackage]) {\n            for package in packages {\n                stream.send(package.identity.description).send(\"\\n\")\n                if !package.dependencies.isEmpty {\n                    recursiveWalk(packages: graph.directDependencies(for: package))\n                }\n            }\n        }\n        if !rootpkg.dependencies.isEmpty {\n            recursiveWalk(packages: graph.directDependencies(for: rootpkg))\n        }\n    }\n}\n\nfinal class DotDumper: DependenciesDumper {\n    func dump(graph: ModulesGraph, dependenciesOf rootpkg: ResolvedPackage, on stream: OutputByteStream) {\n        var nodesAlreadyPrinted: Set<String> = []\n        func printNode(_ package: ResolvedPackage) {\n            let url = package.manifest.packageLocation\n            if nodesAlreadyPrinted.contains(url) { return }\n            let pkgVersion = package.manifest.version?.description ?? \"unspecified\"\n            stream.send(#\"\"\\#(url)\" [label=\"\\#(package.identity.description)\\n\\#(url)\\n\\#(pkgVersion)\"]\"#).send(\"\\n\")\n            nodesAlreadyPrinted.insert(url)\n        }\n\n        struct DependencyURLs: Hashable {\n            var root: String\n            var dependency: String\n        }\n        var dependenciesAlreadyPrinted: Set<DependencyURLs> = []\n        func recursiveWalk(rootpkg: ResolvedPackage) {\n            printNode(rootpkg)\n            for dependency in graph.directDependencies(for: rootpkg) {\n                let rootURL = rootpkg.manifest.packageLocation\n                let dependencyURL = dependency.manifest.packageLocation\n                let urlPair = DependencyURLs(root: rootURL, dependency: dependencyURL)\n                if dependenciesAlreadyPrinted.contains(urlPair) { continue }\n\n                printNode(dependency)\n                stream.send(#\"\"\\#(rootURL)\" -> \"\\#(dependencyURL)\"\"#).send(\"\\n\")\n                dependenciesAlreadyPrinted.insert(urlPair)\n\n                if !dependency.dependencies.isEmpty {\n                    recursiveWalk(rootpkg: dependency)\n                }\n            }\n        }\n\n        if !rootpkg.dependencies.isEmpty {\n            stream.send(\n                \"\"\"\n                digraph DependenciesGraph {\n                node [shape = box]\n\n                \"\"\"\n            )\n            recursiveWalk(rootpkg: rootpkg)\n            stream.send(\"}\\n\")\n        } else {\n            stream.send(\"No external dependencies found\\n\")\n        }\n    }\n}\n\nfinal class JSONDumper: DependenciesDumper {\n    func dump(graph: ModulesGraph, dependenciesOf rootpkg: ResolvedPackage, on stream: OutputByteStream) {\n        func convert(_ package: ResolvedPackage) -> JSON {\n            return .orderedDictionary([\n                \"identity\": .string(package.identity.description),\n                \"name\": .string(package.manifest.displayName), // TODO: remove?\n                \"url\": .string(package.manifest.packageLocation),\n                \"version\": .string(package.manifest.version?.description ?? \"unspecified\"),\n                \"path\": .string(package.path.pathString),\n                \"traits\": .array(package.enabledTraits?.map { .string($0) } ?? []),\n                \"dependencies\": .array(package.dependencies.compactMap { graph.packages[$0] }.map(convert)),\n            ])\n        }\n\n        stream.send(\"\\(convert(rootpkg).toString(prettyPrint: true))\\n\")\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/DescribedPackage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport Foundation\n\nimport class TSCBasic.BufferedOutputByteStream\nimport protocol TSCBasic.OutputByteStream\nimport func TSCBasic.transitiveClosure\n\n/// Represents a package for the sole purpose of generating a description.\nstruct DescribedPackage: Encodable {\n    let name: String // for backwards compatibility\n    let manifestDisplayName: String\n    let path: String\n    let toolsVersion: String\n    let dependencies: [DescribedPackageDependency]\n    let defaultLocalization: String?\n    let platforms: [DescribedPlatformRestriction]\n    let products: [DescribedProduct]\n    let targets: [DescribedTarget]\n    let cLanguageStandard: String?\n    let cxxLanguageStandard: String?\n    let swiftLanguagesVersions: [String]?\n\n    init(from package: Package) {\n        self.manifestDisplayName = package.manifest.displayName\n        self.name = self.manifestDisplayName // TODO: deprecate, backwards compatibility 11/2021\n        self.path = package.path.pathString\n        self.toolsVersion = \"\\(package.manifest.toolsVersion.major).\\(package.manifest.toolsVersion.minor)\"\n        + (package.manifest.toolsVersion.patch == 0 ? \"\" : \".\\(package.manifest.toolsVersion.patch)\")\n        self.dependencies = package.manifest.dependencies.map { DescribedPackageDependency(from: $0) }\n        self.defaultLocalization = package.manifest.defaultLocalization\n        self.platforms = package.manifest.platforms.map { DescribedPlatformRestriction(from: $0) }\n        // SwiftPM considers tests to be products, which is not how things are presented in the manifest.\n        let nonTestProducts = package.products.filter{ $0.type != .test }\n        self.products = nonTestProducts.map {\n            DescribedProduct(from: $0, in: package)\n        }\n        // Create a mapping from the targets to the products to which they contribute directly.  This excludes any\n        // contributions that occur through `.product()` dependencies, but since those targets are still part of a\n        // product of the package, the set of targets that contribute to products still accurately represents the\n        // set of targets reachable from external clients.\n        let targetProductPairs = nonTestProducts.flatMap{ p in\n            transitiveClosure(p.modules, successors: {\n                $0.dependencies.compactMap{ $0.module }\n            }).union(p.modules).map{ t in (t, p) }\n        }\n        let targetsToProducts = Dictionary(targetProductPairs.map{ ($0.0, [$0.1]) }, uniquingKeysWith: { $0 + $1 })\n        self.targets = package.modules.map {\n            return DescribedTarget(from: $0, in: package, productMemberships: targetsToProducts[$0]?.map{ $0.name })\n        }\n        self.cLanguageStandard = package.manifest.cLanguageStandard\n        self.cxxLanguageStandard = package.manifest.cxxLanguageStandard\n        self.swiftLanguagesVersions = package.manifest.swiftLanguageVersions?.map{ $0.description }\n    }\n    \n    /// Represents a platform restriction for the sole purpose of generating a description.\n    struct DescribedPlatformRestriction: Encodable {\n        let name: String\n        let version: String\n        let options: [String]?\n        \n        init(from platform: PlatformDescription) {\n            self.name = platform.platformName\n            self.version = platform.version\n            self.options = platform.options.isEmpty ? nil : platform.options\n        }\n    }\n    \n    /// Represents a package dependency for the sole purpose of generating a description.\n    enum DescribedPackageDependency: Encodable {\n        case fileSystem(identity: PackageIdentity, path: AbsolutePath)\n        case sourceControl(identity: PackageIdentity, location: String, requirement: PackageDependency.SourceControl.Requirement)\n        case registry(identity: PackageIdentity, requirement: PackageDependency.Registry.Requirement)\n\n        init(from dependency: PackageDependency) {\n            switch dependency {\n            case .fileSystem(let settings):\n                self = .fileSystem(identity: settings.identity, path: settings.path)\n            case .sourceControl(let settings):\n                switch settings.location {\n                case .local(let path):\n                    self = .sourceControl(identity: settings.identity, location: path.pathString, requirement: settings.requirement)\n                case .remote(let url):\n                    self = .sourceControl(identity: settings.identity, location: url.absoluteString, requirement: settings.requirement)\n                }\n            case .registry(let settings):\n                self = .registry(identity: settings.identity, requirement: settings.requirement)\n            }\n        }\n\n        private enum CodingKeys: CodingKey {\n            case type\n            case path\n            case url\n            case requirement\n            case identity\n        }\n\n        private enum Kind: String, Codable {\n            case fileSystem\n            case sourceControl\n            case registry\n        }\n\n        func encode(to encoder: Encoder) throws {\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            switch self {\n            case .fileSystem(let identity, let path):\n                try container.encode(Kind.fileSystem, forKey: .type)\n                try container.encode(identity, forKey: .identity)\n                try container.encode(path, forKey: .path)\n            case .sourceControl(let identity, let location, let requirement):\n                try container.encode(Kind.sourceControl, forKey: .type)\n                try container.encode(identity, forKey: .identity)\n                try container.encode(location, forKey: .url)\n                try container.encode(requirement, forKey: .requirement)\n            case .registry(let identity, let requirement):\n                try container.encode(Kind.registry, forKey: .type)\n                try container.encode(identity, forKey: .identity)\n                try container.encode(requirement, forKey: .requirement)\n            }\n        }\n    }\n\n    /// Represents a product for the sole purpose of generating a description.\n    struct DescribedProduct: Encodable {\n        let name: String\n        let type: ProductType\n        let targets: [String]\n\n        init(from product: Product, in package: Package) {\n            self.name = product.name\n            self.type = product.type\n            self.targets = product.modules.map { $0.name }\n        }\n    }\n\n    /// Represents a plugin capability for the sole purpose of generating a description.\n    struct DescribedPluginCapability: Encodable {\n        let type: String\n        let intent: CommandIntent?\n        let permissions: [Permission]?\n\n        init(from capability: PluginCapability, in package: Package) {\n            switch capability {\n            case .buildTool:\n                self.type = \"buildTool\"\n                self.intent = nil\n                self.permissions = nil\n            case .command(let intent, let permissions):\n                self.type = \"command\"\n                self.intent = .init(from: intent)\n                self.permissions = permissions.map{ .init(from: $0) }\n            }\n        }\n        \n        struct CommandIntent: Encodable {\n            let type: String\n            let verb: String?\n            let description: String?\n            \n            init(from intent: PackageModel.PluginCommandIntent) {\n                switch intent {\n                case .documentationGeneration:\n                    self.type = \"documentationGeneration\"\n                    self.verb = nil\n                    self.description = nil\n                case .sourceCodeFormatting:\n                    self.type = \"sourceCodeFormatting\"\n                    self.verb = nil\n                    self.description = nil\n                case .custom(let verb, let description):\n                    self.type = \"custom\"\n                    self.verb = verb\n                    self.description = description\n                }\n            }\n        }\n\n        struct Permission: Encodable {\n            enum NetworkScope: Encodable {\n                case none\n                case local(ports: [Int])\n                case all(ports: [Int])\n                case docker\n                case unixDomainSocket\n\n                init(_ scope: PluginNetworkPermissionScope) {\n                    switch scope {\n                    case .none: self = .none\n                    case .local(let ports): self = .local(ports: ports)\n                    case .all(let ports): self = .all(ports: ports)\n                    case .docker: self = .docker\n                    case .unixDomainSocket: self = .unixDomainSocket\n                    }\n                }\n            }\n\n            let type: String\n            let reason: String\n            let networkScope: NetworkScope\n            \n            init(from permission: PackageModel.PluginPermission) {\n                switch permission {\n                case .writeToPackageDirectory(let reason):\n                    self.type = \"writeToPackageDirectory\"\n                    self.reason = reason\n                    self.networkScope = .none\n                case .allowNetworkConnections(let scope, let reason):\n                    self.type = \"allowNetworkConnections\"\n                    self.reason = reason\n                    self.networkScope = .init(scope)\n                }\n            }\n        }\n    }\n\n    /// Represents a target for the sole purpose of generating a description.\n    struct DescribedTarget: Encodable {\n        let name: String\n        let type: String\n        let c99name: String?\n        let moduleType: String?\n        let pluginCapability: DescribedPluginCapability?\n        let path: String\n        let sources: [String]\n        let resources: [PackageModel.Resource]?\n        let targetDependencies: [String]?\n        let productDependencies: [String]?\n        let productMemberships: [String]?\n        \n        init(from target: Module, in package: Package, productMemberships: [String]?) {\n            self.name = target.name\n            self.type = target.type.rawValue\n            self.c99name = target.c99name\n            self.moduleType = Swift.type(of: target).typeDescription\n            self.pluginCapability = (target as? PluginModule).map{ DescribedPluginCapability(from: $0.capability, in: package) }\n            self.path = target.sources.root.relative(to: package.path).pathString\n            self.sources = target.sources.relativePaths.map{ $0.pathString }\n            self.resources = target.resources.isEmpty ? nil : target.resources\n            let targetDependencies = target.dependencies.compactMap{ $0.module }\n            self.targetDependencies = targetDependencies.isEmpty ? nil : targetDependencies.map{ $0.name }\n            let productDependencies = target.dependencies.compactMap{ $0.product }\n            self.productDependencies = productDependencies.isEmpty ? nil : productDependencies.map{ $0.name }\n            self.productMemberships = productMemberships\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/MermaidPackageSerializer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct OrderedCollections.OrderedDictionary\nimport class PackageModel.Package\nimport class PackageModel.Product\nimport class PackageModel.Module\n\nstruct MermaidPackageSerializer {\n    let package: Package\n    var shouldIncludeLegend = false\n\n    var renderedMarkdown: String {\n        var subgraphs = OrderedDictionary<String, [Edge]>()\n        subgraphs[package.identity.description] = package.products.productTargetEdges\n        \n        for edge in package.modules.targetDependencyEdges {\n            if let subgraph = edge.to.subgraph {\n                subgraphs[subgraph, default: []].append(edge)\n            } else {\n                subgraphs[package.identity.description]?.append(edge)\n            }\n        }\n\n        return \"\"\"\n        ```mermaid\n        flowchart TB\n            \\(\n                shouldIncludeLegend ?\n                    \"\"\"\n                    subgraph legend\n                        legend:target(target)\n                        legend:product[[product]]\n                        legend:dependency{{package dependency}}\n                    end\n\n                    \"\"\" : \"\"\n            )\\(\n                subgraphs.map { subgraph, edges in\n                    \"\"\"\n                    subgraph \\(subgraph)\n                            \\(\n                                edges.map(\\.description).joined(separator: \"\\n        \")\n                            )\n                        end\n                    \"\"\"\n                }.joined(separator: \"\\n\\n    \")\n            )\n        ```\n\n        \"\"\"\n    }\n\n    fileprivate struct Node {\n        enum Border {\n            case roundedCorners\n            case doubled\n            case hexagon\n\n            func added(to title: String) -> String {\n                switch self {\n                case .roundedCorners:\n                    \"(\\(title))\"\n                case .doubled:\n                    \"[[\\(title)]]\"\n                case .hexagon:\n                    \"{{\\(title)}}\"\n                }\n            }\n        }\n\n        let id: String\n        let title: String\n        let border: Border\n        let subgraph: String?\n    }\n\n    fileprivate struct Edge {\n        let from: Node\n        let to: Node\n    }\n}\n\nextension MermaidPackageSerializer.Node {\n    init(id: String, title: String) {\n        self.id = id\n        self.border = .roundedCorners\n        self.title = title\n        self.subgraph = nil\n    }\n\n    init(product: Product) {\n        self.init(id: \"product:\\(product.name)\", title: product.name, border: .doubled, subgraph: nil)\n    }\n\n    init(target: Module) {\n        self.init(id: \"target:\\(target.name)\", title: target.name)\n    }\n\n    init(dependency: Module.Dependency) {\n        switch dependency {\n        case let .product(product, _):\n            self.init(\n                id: product.name,\n                title: product.name,\n                border: .hexagon,\n                subgraph: product.package\n            )\n        case let .module(target, _):\n            self.init(target: target)\n        }\n    }\n}\n\nextension MermaidPackageSerializer.Node: CustomStringConvertible {\n    var description: String {\n        \"\\(self.id)\\(self.border.added(to: self.title))\"\n    }\n}\n\nextension MermaidPackageSerializer.Edge {\n    init(product: Product, target: Module) {\n        self.from = .init(product: product)\n        self.to = .init(target: target)\n    }\n}\n\nextension MermaidPackageSerializer.Edge: CustomStringConvertible {\n    var description: String {\n        \"\\(self.from.description)-->\\(self.to.description)\"\n    }\n}\n\nextension [Product] {\n    fileprivate var productTargetEdges: [MermaidPackageSerializer.Edge] {\n        self.flatMap { product in\n            product.modules.map { target in (product, target) }\n        }.map(MermaidPackageSerializer.Edge.init)\n    }\n}\n\nextension [Module] {\n    fileprivate var targetDependencyEdges: [MermaidPackageSerializer.Edge] {\n        self.flatMap { target in\n            target.dependencies.map {\n                let dependencyNode = MermaidPackageSerializer.Node(dependency: $0)\n\n                return .init(\n                    from: .init(target: target),\n                    to: dependencyNode\n                )\n            }\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/Commands/Utilities/MultiRootSupport.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport CoreCommands\nimport Foundation\nimport TSCBasic\n\n#if canImport(FoundationXML)\nimport FoundationXML\n#endif\nimport class PackageModel.Manifest\n\n/// A bare minimum loader for Xcode workspaces.\n///\n/// Warning: This is only useful for debugging workspaces that contain Swift packages.\npublic struct XcodeWorkspaceLoader: WorkspaceLoader {\n\n    /// The parsed location.\n    private struct Location {\n        /// The kind of location.\n        enum Kind: String {\n            case absolute\n            case group\n        }\n\n        var kind: Kind\n        var path: String\n    }\n\n    private let fileSystem: FileSystem\n    private let observabilityScope: ObservabilityScope\n\n    public init(fileSystem: FileSystem, observabilityScope: ObservabilityScope) {\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n    }\n\n    /// Load the given workspace and return the file ref paths from it.\n    public func load(workspace: Basics.AbsolutePath) throws -> [Basics.AbsolutePath] {\n        let path = workspace.appending(\"contents.xcworkspacedata\")\n        let contents: Data = try self.fileSystem.readFileContents(path)\n\n        let delegate = ParserDelegate(observabilityScope: self.observabilityScope)\n        let parser = XMLParser(data: contents)\n        parser.delegate = delegate\n        if !parser.parse() {\n            throw StringError(\"unable to load file refs from \\(path)\")\n        }\n\n        /// Convert the parsed result into absolute paths.\n        var result: [Basics.AbsolutePath] = []\n        for location in delegate.locations {\n            let path: Basics.AbsolutePath\n\n            switch location.kind {\n            case .absolute:\n                path = try AbsolutePath(validating: location.path)\n            case .group:\n                path = try AbsolutePath(validating: location.path, relativeTo: workspace.parentDirectory)\n            }\n\n            if self.fileSystem.exists(path.appending(component: Manifest.filename)) {\n                result.append(path)\n            } else {\n                self.observabilityScope.emit(warning: \"ignoring non-package fileref \\(path)\")\n            }\n        }\n        return result\n    }\n\n    /// Parser delegate for the workspace.\n    private class ParserDelegate: NSObject, XMLParserDelegate {\n        var locations: [Location] = []\n\n        let observabilityScope: ObservabilityScope\n\n        init(observabilityScope: ObservabilityScope) {\n            self.observabilityScope = observabilityScope\n        }\n\n        func parser(\n            _ parser: XMLParser,\n            didStartElement elementName: String,\n            namespaceURI: String?,\n            qualifiedName qName: String?,\n            attributes attributeDict: [String : String] = [:]\n        ) {\n            guard elementName == \"FileRef\" else { return }\n            guard let location = attributeDict[\"location\"] else { return }\n\n            let splitted = location.split(separator: \":\", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)\n            guard splitted.count == 2 else {\n                self.observabilityScope.emit(warning: \"location split count is not two: \\(splitted)\")\n                return\n            }\n            guard let kind = Location.Kind(rawValue: splitted[0]) else {\n                self.observabilityScope.emit(warning: \"unknown kind \\(splitted[0]) for location \\(location)\")\n                return\n            }\n\n            locations.append(Location(kind: kind, path: splitted[1]))\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/PlainTextEncoder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.Data\nimport class TSCBasic.BufferedOutputByteStream\nimport protocol TSCBasic.OutputByteStream\n\nstruct PlainTextEncoder {\n    /// The formatting of the output plain-text data.\n    struct FormattingOptions: OptionSet {\n        let rawValue: UInt\n\n        init(rawValue: UInt) {\n            self.rawValue = rawValue\n        }\n\n        /// Produce plain-text format with indented output.\n        static let prettyPrinted = FormattingOptions(rawValue: 1 << 0)\n    }\n\n    /// The output format to produce. Defaults to `[]`.\n    var formattingOptions: FormattingOptions = []\n\n    /// Contextual user-provided information for use during encoding.\n    var userInfo: [CodingUserInfoKey: Any] = [:]\n\n    /// Encodes the given top-level value and returns its plain text representation.\n    ///\n    /// - parameter value: The value to encode.\n    /// - returns: A new `Data` value containing the encoded plan-text data.\n    /// - throws: An error if any value throws an error during encoding.\n    func encode<T: Encodable>(_ value: T) throws -> Data {\n        let outputStream = BufferedOutputByteStream()\n        let encoder = _PlainTextEncoder(\n            outputStream: outputStream,\n            formattingOptions: formattingOptions,\n            userInfo: userInfo\n        )\n        try value.encode(to: encoder)\n        return Data(outputStream.bytes.contents)\n    }\n\n    /// Private helper function to format key names with an uppercase initial letter and space-separated components.\n    private static func displayName(for key: CodingKey) -> String {\n        var result = \"\"\n        for ch in key.stringValue {\n            if result.isEmpty {\n                result.append(ch.uppercased())\n            }\n            else if ch.isUppercase {\n                result.append(\" \")\n                result.append(ch.lowercased())\n            }\n            else {\n                result.append(ch)\n            }\n        }\n        return result\n    }\n\n    /// Private Encoder implementation for PlainTextEncoder.\n    private struct _PlainTextEncoder: Encoder {\n        /// Output stream.\n        var outputStream: OutputByteStream\n\n        /// Formatting options set on the top-level encoder.\n        let formattingOptions: PlainTextEncoder.FormattingOptions\n\n        /// Contextual user-provided information for use during encoding.\n        let userInfo: [CodingUserInfoKey: Any]\n\n        /// The path to the current point in encoding.\n        let codingPath: [CodingKey]\n\n        /// Initializes `self` with the given top-level encoder options.\n        init(outputStream: OutputByteStream, formattingOptions: PlainTextEncoder.FormattingOptions, userInfo: [CodingUserInfoKey: Any], codingPath: [CodingKey] = []) {\n            self.outputStream = outputStream\n            self.formattingOptions = formattingOptions\n            self.userInfo = userInfo\n            self.codingPath = codingPath\n        }\n\n        func container<Key: CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {\n            return KeyedEncodingContainer(PlainTextKeyedEncodingContainer<Key>(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath))\n        }\n\n        func unkeyedContainer() -> UnkeyedEncodingContainer {\n            return PlainTextUnkeyedEncodingContainer(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath)\n        }\n\n        func singleValueContainer() -> SingleValueEncodingContainer {\n            return TextSingleValueEncodingContainer(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath)\n        }\n\n        /// Private KeyedEncodingContainer implementation for PlainTextEncoder.\n        private struct PlainTextKeyedEncodingContainer<Key: CodingKey>: KeyedEncodingContainerProtocol {\n            let outputStream: OutputByteStream\n            let formattingOptions: PlainTextEncoder.FormattingOptions\n            let userInfo: [CodingUserInfoKey: Any]\n            let codingPath: [CodingKey]\n\n            private mutating func emit(_ key: CodingKey, _ value: String?) {\n                outputStream.send(\"\\(String(repeating: \"    \", count: codingPath.count))\\(displayName(for: key)):\")\n                if let value { outputStream.send(\" \\(value)\") }\n                outputStream.send(\"\\n\")\n            }\n            mutating func encodeNil(forKey key: Key) throws { emit(key, \"nil\") }\n            mutating func encode(_ value: Bool, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: String, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: Double, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: Float, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: Int, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: Int8, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: Int16, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: Int32, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: Int64, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: UInt, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: UInt8, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: UInt16, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: UInt32, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode(_ value: UInt64, forKey key: Key) throws { emit(key, \"\\(value)\") }\n            mutating func encode<T: Encodable>(_ value: T, forKey key: Key) throws {\n                emit(key, nil)\n                let textEncoder = _PlainTextEncoder(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath + [key])\n                try value.encode(to: textEncoder)\n            }\n\n            mutating func nestedContainer<NestedKey: CodingKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {\n                emit(key, nil)\n                return KeyedEncodingContainer(PlainTextKeyedEncodingContainer<NestedKey>(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath + [key]))\n            }\n\n            mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {\n                emit(key, nil)\n                return PlainTextUnkeyedEncodingContainer(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath + [key])\n            }\n\n            mutating func superEncoder() -> Encoder {\n                return superEncoder(forKey: Key(stringValue: \"super\")!)\n            }\n\n            mutating func superEncoder(forKey key: Key) -> Encoder {\n                return _PlainTextEncoder(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath + [key])\n            }\n        }\n\n        /// Private UnkeyedEncodingContainer implementation for PlainTextEncoder.\n        private struct PlainTextUnkeyedEncodingContainer: UnkeyedEncodingContainer {\n            let outputStream: OutputByteStream\n            let formattingOptions: PlainTextEncoder.FormattingOptions\n            let userInfo: [CodingUserInfoKey: Any]\n            let codingPath: [CodingKey]\n            private(set) var count: Int = 0\n\n            private mutating func emit(_ value: String) {\n                outputStream.send(\"\\(String(repeating: \"    \", count: codingPath.count))\\(value)\\n\")\n                count += 1\n            }\n            mutating func encodeNil() throws { emit(\"nil\") }\n            mutating func encode(_ value: Bool) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: String) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Double) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Float) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int8) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int16) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int32) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int64) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt8) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt16) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt32) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt64) throws { emit(\"\\(value)\") }\n            mutating func encode<T: Encodable>(_ value: T) throws {\n                let textEncoder = _PlainTextEncoder(\n                    outputStream: outputStream,\n                    formattingOptions: formattingOptions,\n                    userInfo: userInfo,\n                    codingPath: codingPath\n                )\n                try value.encode(to: textEncoder)\n                count += 1\n                // FIXME: This is a bit arbitrary and should be controllable.  We may also want an option to only emit\n                // newlines between entries, not after each one.\n                if codingPath.count < 2 { outputStream.send(\"\\n\") }\n            }\n\n            mutating func nestedContainer<NestedKey: CodingKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> {\n                KeyedEncodingContainer(PlainTextKeyedEncodingContainer<NestedKey>(\n                    outputStream: outputStream,\n                    formattingOptions: formattingOptions,\n                    userInfo: userInfo,\n                    codingPath: codingPath\n                ))\n            }\n\n            mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {\n                return PlainTextUnkeyedEncodingContainer(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath)\n            }\n\n            mutating func superEncoder() -> Encoder {\n                return _PlainTextEncoder(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath)\n            }\n        }\n\n        /// Private SingleValueEncodingContainer implementation for PlainTextEncoder.\n        private struct TextSingleValueEncodingContainer: SingleValueEncodingContainer {\n            let outputStream: OutputByteStream\n            let formattingOptions: PlainTextEncoder.FormattingOptions\n            let userInfo: [CodingUserInfoKey: Any]\n            let codingPath: [CodingKey]\n\n            private mutating func emit(_ value: String) {\n                outputStream.send(\"\\(String(repeating: \"    \", count: codingPath.count))\\(value)\\n\")\n            }\n            mutating func encodeNil() throws { emit(\"nil\") }\n            mutating func encode(_ value: Bool) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: String) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Double) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Float) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int8) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int16) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int32) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: Int64) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt8) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt16) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt32) throws { emit(\"\\(value)\") }\n            mutating func encode(_ value: UInt64) throws { emit(\"\\(value)\") }\n            mutating func encode<T: Encodable>(_ value: T) throws {\n                let textEncoder = _PlainTextEncoder(outputStream: outputStream, formattingOptions: formattingOptions, userInfo: userInfo, codingPath: codingPath)\n                try value.encode(to: textEncoder)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/PluginDelegate.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport SPMBuildCore\nimport PackageGraph\n\nimport protocol TSCBasic.OutputByteStream\nimport class TSCBasic.BufferedOutputByteStream\nimport class Basics.AsyncProcess\nimport struct Basics.AsyncProcessResult\n\nfinal class PluginDelegate: PluginInvocationDelegate {\n    let swiftCommandState: SwiftCommandState\n    let buildSystem: BuildSystemProvider.Kind\n    let plugin: PluginModule\n    var lineBufferedOutput: Data\n\n    init(swiftCommandState: SwiftCommandState, buildSystem: BuildSystemProvider.Kind, plugin: PluginModule) {\n        self.swiftCommandState = swiftCommandState\n        self.buildSystem = buildSystem\n        self.plugin = plugin\n        self.lineBufferedOutput = Data()\n    }\n\n    func pluginCompilationStarted(commandLine: [String], environment: [String: String]) {\n    }\n\n    func pluginCompilationEnded(result: PluginCompilationResult) {\n    }\n\n    func pluginCompilationWasSkipped(cachedResult: PluginCompilationResult) {\n    }\n\n    func pluginEmittedOutput(_ data: Data) {\n        lineBufferedOutput += data\n        while let newlineIdx = lineBufferedOutput.firstIndex(of: UInt8(ascii: \"\\n\")) {\n            let lineData = lineBufferedOutput.prefix(upTo: newlineIdx)\n            print(String(decoding: lineData, as: UTF8.self))\n            lineBufferedOutput = lineBufferedOutput.suffix(from: newlineIdx.advanced(by: 1))\n        }\n    }\n\n    func pluginEmittedDiagnostic(_ diagnostic: Basics.Diagnostic) {\n        swiftCommandState.observabilityScope.emit(diagnostic)\n    }\n\n    func pluginEmittedProgress(_ message: String) {\n        swiftCommandState.outputStream.write(\"[\\(plugin.name)] \\(message)\\n\")\n        swiftCommandState.outputStream.flush()\n    }\n\n    func pluginRequestedBuildOperation(\n        subset: PluginInvocationBuildSubset,\n        parameters: PluginInvocationBuildParameters,\n        completion: @escaping (Result<PluginInvocationBuildResult, Error>) -> Void\n    ) {\n        // Run the build in the background and call the completion handler when done.\n        Task {\n            do {\n                try await completion(.success(self.performBuildForPlugin(subset: subset, parameters: parameters)))\n            } catch {\n                completion(.failure(error))\n            }\n        }\n    }\n\n    class TeeOutputByteStream: OutputByteStream {\n        var downstreams: [OutputByteStream]\n\n        public init(_ downstreams: [OutputByteStream]) {\n            self.downstreams = downstreams\n        }\n\n        var position: Int {\n            return 0 // should be related to the downstreams somehow\n        }\n\n        public func write(_ byte: UInt8) {\n            for downstream in downstreams {\n                downstream.write(byte)\n            }\n        }\n\n        func write<C: Collection>(_ bytes: C) where C.Element == UInt8 {\n            for downstream in downstreams {\n                downstream.write(bytes)\n            }\n\t\t}\n\n        public func flush() {\n            for downstream in downstreams {\n                downstream.flush()\n            }\n        }\n\n        public func addStream(_ stream: OutputByteStream) {\n            self.downstreams.append(stream)\n        }\n    }\n\n    private func performBuildForPlugin(\n        subset: PluginInvocationBuildSubset,\n        parameters: PluginInvocationBuildParameters\n    ) async throws -> PluginInvocationBuildResult {\n        // Configure the build parameters.\n        var buildParameters = try self.swiftCommandState.productsBuildParameters\n        switch parameters.configuration {\n        case .debug:\n            buildParameters.configuration = .debug\n        case .release:\n            buildParameters.configuration = .release\n        case .inherit:\n            // The top level argument parser set buildParameters.configuration according to the\n            // --configuration command line parameter.   We don't need to do anything to inherit it.\n            break\n        }\n        buildParameters.flags.cCompilerFlags.append(contentsOf: parameters.otherCFlags.constructBuildFlags(source: .plugin))\n        buildParameters.flags.cxxCompilerFlags.append(contentsOf: parameters.otherCxxFlags.constructBuildFlags(source: .plugin))\n        buildParameters.flags.swiftCompilerFlags.append(contentsOf: parameters.otherSwiftcFlags.constructBuildFlags(source: .plugin))\n        buildParameters.flags.linkerFlags.append(contentsOf: parameters.otherLinkerFlags.constructBuildFlags(source: .plugin))\n\n        // Configure the verbosity of the output.\n        let logLevel: Basics.Diagnostic.Severity\n        switch parameters.logging {\n        case .concise:\n            logLevel = .warning\n        case .verbose:\n            logLevel = .info\n        case .debug:\n            logLevel = .debug\n        }\n\n        // Determine the subset of products and targets to build.\n        var explicitProduct: String? = .none\n        let buildSubset: BuildSubset\n        switch subset {\n        case .all(let includingTests):\n            buildSubset = includingTests ? .allIncludingTests : .allExcludingTests\n            if includingTests {\n                // Enable testability if we're building tests explicitly.\n                buildParameters.testingParameters.explicitlyEnabledTestability = true\n            }\n        case .product(let name):\n            buildSubset = .product(name)\n            explicitProduct = name\n        case .target(let name):\n            buildSubset = .target(name)\n        }\n\n        // Create a build operation. We have to disable the cache in order to get a build plan created.\n        let bufferedOutputStream = BufferedOutputByteStream()\n        let outputStream = TeeOutputByteStream([bufferedOutputStream])\n        if parameters.echoLogs {\n            outputStream.addStream(swiftCommandState.outputStream)\n        }\n\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            explicitBuildSystem: buildSystem,\n            explicitProduct: explicitProduct,\n            cacheBuildManifest: false,\n            productsBuildParameters: buildParameters,\n            outputStream: outputStream,\n            logLevel: logLevel\n        )\n\n        // Run the build. This doesn't return until the build is complete.\n        let result = await buildSystem.buildIgnoringError(subset: buildSubset, buildOutputs: [.builtArtifacts])\n        let success = result != nil\n\n        _ = try await buildSystem.getPackageGraph()\n\n        let builtArtifacts: [PluginInvocationBuildResult.BuiltArtifact] = (result?.builtArtifacts ?? []).filter { (name, _) in\n            switch subset {\n            case .all:\n                return true\n            case .product(let productName):\n                return name == productName\n            case .target(let targetName):\n                return name == targetName\n            }\n        }.map(\\.1)\n\n        return PluginInvocationBuildResult(\n            succeeded: success,\n            logText: bufferedOutputStream.bytes.cString,\n            builtArtifacts: builtArtifacts)\n    }\n\n    func pluginRequestedTestOperation(\n        subset: PluginInvocationTestSubset,\n        parameters: PluginInvocationTestParameters,\n        completion: @escaping (Result<PluginInvocationTestResult, Error>\n        ) -> Void) {\n        // Run the test in the background and call the completion handler when done.\n        Task {\n            do {\n                try await completion(.success(self.performTestsForPlugin(subset: subset, parameters: parameters)))\n            } catch {\n                completion(.failure(error))\n            }\n        }\n    }\n\n    func performTestsForPlugin(\n        subset: PluginInvocationTestSubset,\n        parameters: PluginInvocationTestParameters\n    ) async throws -> PluginInvocationTestResult {\n        // Build the tests. Ideally we should only build those that match the subset, but we don't have a way to know\n        // which ones they are until we've built them and can examine the binaries.\n        let toolchain = try swiftCommandState.getHostToolchain()\n        var toolsBuildParameters = try swiftCommandState.toolsBuildParameters\n        toolsBuildParameters.testingParameters.explicitlyEnabledTestability = true\n        toolsBuildParameters.testingParameters.enableCodeCoverage = parameters.enableCodeCoverage\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            toolsBuildParameters: toolsBuildParameters\n        )\n        try await buildSystem.build(subset: .allIncludingTests, buildOutputs: [])\n\n        // Clean out the code coverage directory that may contain stale `profraw` files from a previous run of\n        // the code coverage tool.\n        if parameters.enableCodeCoverage {\n            try swiftCommandState.fileSystem.removeFileTree(toolsBuildParameters.codeCovPath)\n        }\n\n        // Construct the environment we'll pass down to the tests.\n        let testEnvironment = try await TestingSupport.constructTestEnvironment(\n            toolchain: toolchain,\n            destinationBuildParameters: toolsBuildParameters,\n            sanitizers: swiftCommandState.options.build.sanitizers,\n            library: .xctest, // FIXME: support both libraries\n            testProductPaths: buildSystem.builtTestProducts.map(\\.bundlePath)\n        )\n\n        // Iterate over the tests and run those that match the filter.\n        var testTargetResults: [PluginInvocationTestResult.TestTarget] = []\n        var numFailedTests = 0\n        for testProduct in await buildSystem.builtTestProducts {\n            // Get the test suites in the bundle. Each is just a container for test cases.\n            let testSuites = try TestingSupport.getTestSuites(\n                fromTestAt: testProduct.bundlePath,\n                swiftCommandState: swiftCommandState,\n                enableCodeCoverage: parameters.enableCodeCoverage,\n                shouldSkipBuilding: false,\n                experimentalTestOutput: false,\n                sanitizers: swiftCommandState.options.build.sanitizers\n            )\n            for testSuite in testSuites {\n                // Each test suite is just a container for test cases (confusingly called \"tests\",\n                // though they are test cases).\n                for testCase in testSuite.tests {\n                    // Each test case corresponds to a combination of target and a XCTestCase, and is\n                    // a collection of tests that can actually be run.\n                    var testResults: [PluginInvocationTestResult.TestTarget.TestCase.Test] = []\n                    for testName in testCase.tests {\n                        // Check if we should filter out this test.\n                        let testSpecifier = testCase.name + \"/\" + testName\n                        if case .filtered(let regexes) = subset {\n                            guard regexes.contains(\n                                where: { testSpecifier.range(of: $0, options: .regularExpression) != nil }\n                            ) else {\n                                continue\n                            }\n                        }\n\n                        // Configure a test runner.\n                        let additionalArguments = TestRunner.xctestArguments(forTestSpecifiers: CollectionOfOne(testSpecifier))\n                        let testRunner = TestRunner(\n                            bundlePaths: [testProduct.bundlePath],\n                            additionalArguments: additionalArguments,\n                            cancellator: swiftCommandState.cancellator,\n                            toolchain: toolchain,\n                            testEnv: testEnvironment,\n                            observabilityScope: swiftCommandState.observabilityScope,\n                            library: .xctest) // FIXME: support both libraries\n\n                        // Run the test — for now we run the sequentially so we can capture accurate timing results.\n                        let startTime = DispatchTime.now()\n                        let result = testRunner.test(outputHandler: { _ in }) // this drops the tests output\n                        let duration = Double(startTime.distance(to: .now()).milliseconds() ?? 0) / 1000.0\n                        numFailedTests += (result != .failure) ? 0 : 1\n                        testResults.append(\n                            .init(name: testName, result: (result != .failure) ? .succeeded : .failed, duration: duration)\n                        )\n                    }\n\n                    // Don't add any results if we didn't run any tests.\n                    if testResults.isEmpty { continue }\n\n                    // Otherwise we either create a new create a new target result or add to the previous one,\n                    // depending on whether the target name is the same.\n                    let testTargetName = testCase.name.prefix(while: { $0 != \".\" })\n                    if let lastTestTargetName = testTargetResults.last?.name, testTargetName == lastTestTargetName {\n                        // Same as last one, just extend its list of cases. We know we have a last one at this point.\n                        testTargetResults[testTargetResults.count-1].testCases.append(\n                            .init(name: testCase.name, tests: testResults)\n                        )\n                    }\n                    else {\n                        // Not the same, so start a new target result.\n                        testTargetResults.append(\n                            .init(\n                                name: String(testTargetName),\n                                testCases: [.init(name: testCase.name, tests: testResults)]\n                            )\n                        )\n                    }\n                }\n            }\n        }\n\n        // Deal with code coverage, if enabled.\n        let codeCoverageDataFile: AbsolutePath?\n        if parameters.enableCodeCoverage {\n            // Use `llvm-prof` to merge all the `.profraw` files into a single `.profdata` file.\n            let mergedCovFile = toolsBuildParameters.codeCovDataFile\n            let codeCovFileNames = try swiftCommandState.fileSystem.getDirectoryContents(toolsBuildParameters.codeCovPath)\n            var llvmProfCommand = [try toolchain.getLLVMProf().pathString]\n            llvmProfCommand += [\"merge\", \"-sparse\"]\n            for fileName in codeCovFileNames where fileName.hasSuffix(\".profraw\") {\n                let filePath = toolsBuildParameters.codeCovPath.appending(component: fileName)\n                llvmProfCommand.append(filePath.pathString)\n            }\n            llvmProfCommand += [\"-o\", mergedCovFile.pathString]\n            try await AsyncProcess.checkNonZeroExit(arguments: llvmProfCommand)\n\n            // Use `llvm-cov` to export the merged `.profdata` file contents in JSON form.\n            var llvmCovCommand = [try toolchain.getLLVMCov().pathString]\n            llvmCovCommand += [\"export\", \"-instr-profile=\\(mergedCovFile.pathString)\"]\n            for product in await buildSystem.builtTestProducts {\n                llvmCovCommand.append(\"-object\")\n                llvmCovCommand.append(product.binaryPath.pathString)\n            }\n            // We get the output on stdout, and have to write it to a JSON ourselves.\n            let jsonOutput = try await AsyncProcess.checkNonZeroExit(arguments: llvmCovCommand)\n            let jsonCovFile = toolsBuildParameters.codeCovDataFile.parentDirectory.appending(\n                component: toolsBuildParameters.codeCovDataFile.basenameWithoutExt + \".json\"\n            )\n            try swiftCommandState.fileSystem.writeFileContents(jsonCovFile, string: jsonOutput)\n\n            // Return the path of the exported code coverage data file.\n            codeCoverageDataFile = jsonCovFile\n        }\n        else {\n            codeCoverageDataFile = nil\n        }\n\n        // Return the results to the plugin. We only consider the test run a success if no test failed.\n        return PluginInvocationTestResult(\n            succeeded: (numFailedTests == 0),\n            testTargets: testTargetResults,\n            codeCoverageDataFile: codeCoverageDataFile?.pathString)\n    }\n\n    func pluginRequestedSymbolGraph(\n        forTarget targetName: String,\n        options: PluginInvocationSymbolGraphOptions,\n        completion: @escaping (Result<PluginInvocationSymbolGraphResult, Error>) -> Void\n    ) {\n        // Extract the symbol graph in the background and call the completion handler when done.\n        Task {\n            do {\n                try await completion(.success(self.createSymbolGraphForPlugin(forTarget: targetName, options: options)))\n            } catch {\n                completion(.failure(error))\n            }\n        }\n    }\n\n    private func createSymbolGraphForPlugin(\n        forTarget targetName: String,\n        options: PluginInvocationSymbolGraphOptions\n    ) async throws -> PluginInvocationSymbolGraphResult {\n        // Current implementation uses `SymbolGraphExtract()`, but in the future we should emit the symbol graph\n        // while building.\n\n        // Create a build system for building the target., skipping the the cache because we need the build plan.\n        let buildSystem = try await swiftCommandState.createBuildSystem(\n            explicitBuildSystem: buildSystem,\n            enableAllTraits: true,\n            cacheBuildManifest: false\n        )\n\n        // Build the target, if needed. We are interested in symbol graph (ideally) or a build plan.\n        let buildResult = try await buildSystem.build(subset: .target(targetName), buildOutputs: [.symbolGraph(options), .buildPlan])\n\n        if let symbolGraph = buildResult.symbolGraph {\n            let path = (try swiftCommandState.productsBuildParameters.buildPath)\n            return PluginInvocationSymbolGraphResult(directoryPath: \"\\(path)/\\(symbolGraph.outputLocationForTarget(targetName, try swiftCommandState.productsBuildParameters).joined(separator:\"/\"))\")\n        } else if let buildPlan = buildResult.buildPlan {\n            func lookupDescription(\n                for moduleName: String,\n                destination: BuildParameters.Destination\n            ) -> ModuleBuildDescription? {\n                buildPlan.buildModules.first {\n                    $0.module.name == moduleName && $0.buildParameters.destination == destination\n                }\n            }\n\n            // FIXME: The name alone doesn't give us enough information to figure out what\n            // the destination is, this logic prefers \"target\" over \"host\" because that's\n            // historically how this was setup. Ideally we should be building for both \"host\"\n            // and \"target\" if module is configured for them but that would require changing\n            // `PluginInvocationSymbolGraphResult` to carry multiple directories.\n            let description = if let targetDescription = lookupDescription(for: targetName, destination: .target) {\n                targetDescription\n            } else if let hostDescription = lookupDescription(for: targetName, destination: .host) {\n                hostDescription\n            } else {\n                throw InternalError(\"could not find a target named: \\(targetName)\")\n            }\n\n            // Configure the symbol graph extractor.\n            var symbolGraphExtractor = try SymbolGraphExtract(\n                fileSystem: swiftCommandState.fileSystem,\n                tool: swiftCommandState.getTargetToolchain().getSymbolGraphExtract(),\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n            symbolGraphExtractor.skipSynthesizedMembers = !options.includeSynthesized\n            switch options.minimumAccessLevel {\n            case .private:\n                symbolGraphExtractor.minimumAccessLevel = .private\n            case .fileprivate:\n                symbolGraphExtractor.minimumAccessLevel = .fileprivate\n            case .internal:\n                symbolGraphExtractor.minimumAccessLevel = .internal\n            case .package:\n                symbolGraphExtractor.minimumAccessLevel = .package\n            case .public:\n                symbolGraphExtractor.minimumAccessLevel = .public\n            case .open:\n                symbolGraphExtractor.minimumAccessLevel = .open\n            }\n            symbolGraphExtractor.skipInheritedDocs = !options.includeInheritedDocs\n            symbolGraphExtractor.includeSPISymbols = options.includeSPI\n            symbolGraphExtractor.emitExtensionBlockSymbols = options.emitExtensionBlocks\n\n            // Determine the output directory, and remove any old version if it already exists.\n            let outputDir = description.buildParameters.dataPath.appending(\n                components: \"extracted-symbols\",\n                description.package.identity.description,\n                targetName\n            )\n            try swiftCommandState.fileSystem.removeFileTree(outputDir)\n\n            // Run the symbol graph extractor on the target.\n            let result = try symbolGraphExtractor.extractSymbolGraph(\n                for: description,\n                outputRedirection: .collect,\n                outputDirectory: outputDir,\n                verboseOutput: self.swiftCommandState.logLevel <= .info\n            )\n\n            guard result.exitStatus == .terminated(code: 0) else {\n                throw AsyncProcessResult.Error.nonZeroExit(result)\n            }\n\n            // Return the results to the plugin.\n            return PluginInvocationSymbolGraphResult(directoryPath: outputDir.pathString)\n        } else {\n            throw InternalError(\"Build system \\(buildSystem) doesn't have plugin support.\")\n        }\n    }\n}\n\nextension BuildSystem {\n    fileprivate func buildIgnoringError(subset: BuildSubset, buildOutputs: [BuildOutput]) async -> BuildResult? {\n        do {\n            return try await self.build(subset: subset, buildOutputs: buildOutputs)\n        } catch {\n            return nil\n        }\n    }\n}\n\nextension BuildOutput {\n    static func symbolGraph(_ options: PluginInvocationSymbolGraphOptions) -> BuildOutput {\n        return .symbolGraph(SymbolGraphOptions(\n                minimumAccessLevel: .accessLevel(options.minimumAccessLevel),\n                includeInheritedDocs: options.includeInheritedDocs,\n                includeSynthesized: options.includeSynthesized,\n                includeSPI: options.includeSPI,\n                emitExtensionBlocks: options.emitExtensionBlocks\n        ))\n    }\n}\n\nfileprivate extension BuildOutput.SymbolGraphAccessLevel {\n    static func accessLevel(_ accessLevel: PluginInvocationSymbolGraphOptions.AccessLevel) -> BuildOutput.SymbolGraphAccessLevel {\n        return switch accessLevel {\n        case .private:\n            .private\n        case .fileprivate:\n            .fileprivate\n        case .internal:\n            .internal\n        case .package:\n            .package\n        case .public:\n            .public\n        case .open:\n            .open\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/RefactoringSupport.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@_spi(FixItApplier) import SwiftIDEUtils\n@_spi(PackageRefactor) import SwiftRefactor\nimport SwiftSyntax\n\npackage extension [SourceEdit] {\n    /// Apply the edits for the given manifest to the specified file system,\n    /// updating the manifest to the given manifest\n    func applyEdits(\n        to filesystem: any FileSystem,\n        manifest: SourceFileSyntax,\n        manifestPath: AbsolutePath,\n        verbose: Bool\n    ) throws {\n        let rootPath = manifestPath.parentDirectory\n\n        // Update the manifest\n        if verbose {\n            print(\"Updating package manifest at \\(manifestPath.relative(to: rootPath))...\", terminator: \"\")\n        }\n\n        let updatedManifestSource = FixItApplier.apply(\n            edits: self,\n            to: manifest\n        )\n        try filesystem.writeFileContents(\n            manifestPath,\n            string: updatedManifestSource\n        )\n        if verbose {\n            print(\" done.\")\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/SymbolGraphExtract.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport SPMBuildCore\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import DriverSupport\n#else\nimport DriverSupport\n#endif\n\nimport class Basics.AsyncProcess\nimport struct Basics.AsyncProcessResult\n\n/// A wrapper for swift-symbolgraph-extract tool.\npackage struct SymbolGraphExtract {\n    let fileSystem: FileSystem\n    let tool: AbsolutePath\n    let observabilityScope: ObservabilityScope\n    \n    var skipSynthesizedMembers = false\n    var minimumAccessLevel = AccessLevel.public\n    var skipInheritedDocs = false\n    var includeSPISymbols = false\n    var emitExtensionBlockSymbols = false\n    var outputFormat = OutputFormat.json(pretty: false)\n\n    /// Access control levels.\n    public enum AccessLevel: String, RawRepresentable, CaseIterable, ExpressibleByArgument {\n        // The cases reflect those found in `include/swift/AST/AttrKind.h` of the swift compiler (at commit ca96a2b)\n        case `private`, `fileprivate`, `internal`, `package`, `public`, `open`\n    }\n\n    /// Output format of the generated symbol graph.\n    public enum OutputFormat {\n        /// JSON format, optionally \"pretty-printed\" be more human-readable.\n        case json(pretty: Bool)\n    }\n    \n    /// Creates a symbol graph for `module` in `outputDirectory` using the build information from `buildPlan`.\n    /// The `outputDirection` determines how the output from the tool subprocess is handled, and `verbosity` specifies\n    /// how much console output to ask the tool to emit.\n    package func extractSymbolGraph(\n        for description: ModuleBuildDescription,\n        outputRedirection: AsyncProcess.OutputRedirection = .none,\n        outputDirectory: AbsolutePath,\n        verboseOutput: Bool\n    ) throws -> AsyncProcessResult {\n        try self.fileSystem.createDirectory(outputDirectory, recursive: true)\n\n        // Construct arguments for extracting symbols for a single target.\n        var commandLine = [self.tool.pathString]\n        commandLine += try description.symbolGraphExtractArguments()\n\n        // FIXME: everything here should be in symbolGraphExtractArguments\n        if verboseOutput {\n            commandLine += [\"-v\"]\n        }\n        commandLine += [\"-minimum-access-level\", minimumAccessLevel.rawValue]\n        if skipSynthesizedMembers {\n            commandLine += [\"-skip-synthesized-members\"]\n        }\n        if skipInheritedDocs {\n            commandLine += [\"-skip-inherited-docs\"]\n        }\n        if includeSPISymbols {\n            commandLine += [\"-include-spi-symbols\"]\n        }\n        \n        let extensionBlockSymbolsFlag = emitExtensionBlockSymbols ? \"-emit-extension-block-symbols\" : \"-omit-extension-block-symbols\"\n        if DriverSupport.checkSupportedFrontendFlags(\n            flags: [extensionBlockSymbolsFlag.trimmingCharacters(in: [\"-\"])],\n            toolchain: description.buildParameters.toolchain,\n            fileSystem: fileSystem\n        ) {\n            commandLine += [extensionBlockSymbolsFlag]\n        } else {\n            observabilityScope.emit(warning: \"dropped \\(extensionBlockSymbolsFlag) flag because it is not supported by this compiler version\")\n        }\n        \n        switch outputFormat {\n        case .json(let pretty):\n            if pretty {\n                commandLine += [\"-pretty-print\"]\n            }\n        }\n        commandLine += [\"-output-dir\", outputDirectory.pathString]\n\n        // Run the extraction.\n        let process = AsyncProcess(\n            arguments: commandLine,\n            outputRedirection: outputRedirection\n        )\n        try process.launch()\n        return try process.waitUntilExit()\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/TestingSupport.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport CoreCommands\nimport PackageModel\nimport SPMBuildCore\nimport TSCUtility\nimport Workspace\n\nimport struct TSCBasic.FileSystemError\nimport class Basics.AsyncProcess\nimport var TSCBasic.stderrStream\nimport var TSCBasic.stdoutStream\nimport func TSCBasic.withTemporaryFile\n\n/// Internal helper functionality for the SwiftTestTool command and for the\n/// plugin support.\n///\n/// Note: In the long term this should be factored into a reusable module that\n/// can run and report results on tests from both CLI and libSwiftPM API.\nenum TestingSupport {\n    /// Locates XCTestHelper tool inside the libexec directory and bin directory.\n    /// Note: It is a fatalError if we are not able to locate the tool.\n    ///\n    /// - Returns: Path to XCTestHelper tool.\n    static func xctestHelperPath(swiftCommandState: SwiftCommandState) throws -> AbsolutePath {\n        var triedPaths = [AbsolutePath]()\n\n        func findXCTestHelper(swiftBuildPath: AbsolutePath) -> AbsolutePath? {\n            // XCTestHelper tool is installed in libexec.\n            let maybePath = swiftBuildPath.parentDirectory.parentDirectory.appending(\n                components: \"libexec\", \"swift\", \"pm\", \"swiftpm-xctest-helper\"\n            )\n            if swiftCommandState.fileSystem.isFile(maybePath) {\n                return maybePath\n            } else {\n                triedPaths.append(maybePath)\n                return nil\n            }\n        }\n\n        if let firstCLIArgument = CommandLine.arguments.first {\n            let runningSwiftBuildPath = try AbsolutePath(validating: firstCLIArgument, relativeTo: swiftCommandState.originalWorkingDirectory)\n            if let xctestHelperPath = findXCTestHelper(swiftBuildPath: runningSwiftBuildPath) {\n                return xctestHelperPath\n            }\n        }\n\n        // This will be true during swiftpm development or when using swift.org toolchains.\n        let xcodePath = try AsyncProcess.checkNonZeroExit(args: \"/usr/bin/xcode-select\", \"--print-path\").spm_chomp()\n        let installedSwiftBuildPath = try AsyncProcess.checkNonZeroExit(\n            args: \"/usr/bin/xcrun\", \"--find\", \"swift-build\",\n            environment: [\"DEVELOPER_DIR\": xcodePath]\n        ).spm_chomp()\n        if let xctestHelperPath = findXCTestHelper(swiftBuildPath: try AbsolutePath(validating: installedSwiftBuildPath)) {\n            return xctestHelperPath\n        }\n\n        throw InternalError(\"XCTestHelper binary not found, tried \\(triedPaths.map { $0.pathString }.joined(separator: \", \"))\")\n    }\n\n    static func getTestSuites(\n        in testProducts: [BuiltTestProduct],\n        swiftCommandState: SwiftCommandState,\n        enableCodeCoverage: Bool,\n        shouldSkipBuilding: Bool,\n        experimentalTestOutput: Bool,\n        sanitizers: [Sanitizer]\n    ) throws -> [AbsolutePath: [TestSuite]] {\n        let testSuitesByProduct = try testProducts\n            .map {(\n                $0.bundlePath,\n                try Self.getTestSuites(\n                    fromTestAt: $0.bundlePath,\n                    swiftCommandState: swiftCommandState,\n                    enableCodeCoverage: enableCodeCoverage,\n                    shouldSkipBuilding: shouldSkipBuilding,\n                    experimentalTestOutput: experimentalTestOutput,\n                    sanitizers: sanitizers\n                )\n            )}\n        return try Dictionary(throwingUniqueKeysWithValues: testSuitesByProduct)\n    }\n\n    /// Runs the corresponding tool to get tests JSON and create TestSuite array.\n    /// On macOS, we use the swiftpm-xctest-helper tool bundled with swiftpm.\n    /// On Linux, XCTest can dump the json using `--dump-tests-json` mode.\n    ///\n    /// - Parameters:\n    ///     - path: Path to the XCTest bundle(macOS) or executable(Linux).\n    ///\n    /// - Throws: TestError, SystemError, TSCUtility.Error\n    ///\n    /// - Returns: Array of TestSuite\n    static func getTestSuites(\n        fromTestAt path: AbsolutePath,\n        swiftCommandState: SwiftCommandState,\n        enableCodeCoverage: Bool,\n        shouldSkipBuilding: Bool,\n        experimentalTestOutput: Bool,\n        sanitizers: [Sanitizer]\n    ) throws -> [TestSuite] {\n        // Run the correct tool.\n        var args = [String]()\n        #if os(macOS)\n        let data: String = try withTemporaryFile { tempFile in\n            args = [try Self.xctestHelperPath(swiftCommandState: swiftCommandState).pathString, path.pathString, tempFile.path.pathString]\n            let env = try Self.constructTestEnvironment(\n                toolchain: try swiftCommandState.getTargetToolchain(),\n                destinationBuildParameters: swiftCommandState.buildParametersForTest(\n                    enableCodeCoverage: enableCodeCoverage,\n                    shouldSkipBuilding: shouldSkipBuilding,\n                    experimentalTestOutput: experimentalTestOutput\n                ).productsBuildParameters,\n                sanitizers: sanitizers,\n                library: .xctest,\n                testProductPaths: [path]\n            )\n            try Self.runProcessWithExistenceCheck(\n                path: path,\n                fileSystem: swiftCommandState.fileSystem,\n                args: args,\n                env: env\n            )\n\n            // Read the temporary file's content.\n            return try swiftCommandState.fileSystem.readFileContents(AbsolutePath(tempFile.path))\n        }\n        #else\n        let env = try Self.constructTestEnvironment(\n            toolchain: try swiftCommandState.getTargetToolchain(),\n            destinationBuildParameters: swiftCommandState.buildParametersForTest(\n                enableCodeCoverage: enableCodeCoverage,\n                shouldSkipBuilding: shouldSkipBuilding\n            ).productsBuildParameters,\n            sanitizers: sanitizers,\n            library: .xctest,\n            testProductPaths: [path]\n        )\n        args = [path.description, \"--dump-tests-json\"]\n        let data = try Self.runProcessWithExistenceCheck(\n            path: path,\n            fileSystem: swiftCommandState.fileSystem,\n            args: args,\n            env: env\n        )\n        #endif\n        // Parse json and return TestSuites.\n        return try TestSuite.parse(jsonString: data, context: args.joined(separator: \" \"))\n    }\n\n    /// Run a process and throw a more specific error if the file doesn't exist.\n    @discardableResult\n    private static func runProcessWithExistenceCheck(\n        path: AbsolutePath,\n        fileSystem: FileSystem,\n        args: [String],\n        env: Environment\n    ) throws -> String {\n        do {\n            return try AsyncProcess.checkNonZeroExit(arguments: args, environment: env)\n        } catch {\n            // If the file doesn't exist, throw a more specific error.\n            if !fileSystem.exists(path) {\n                throw FileSystemError(.noEntry, path)\n            }\n            throw error\n        }\n    }\n\n    /// Creates the environment needed to test related tools.\n    static func constructTestEnvironment(\n        toolchain: UserToolchain,\n        destinationBuildParameters buildParameters: BuildParameters,\n        sanitizers: [Sanitizer],\n        library: TestingLibrary,\n        testProductPaths: [AbsolutePath]\n    ) throws -> Environment {\n        var env = Environment.current\n\n        // If the standard output or error stream is NOT a TTY, set the NO_COLOR\n        // environment variable. This environment variable is a de facto\n        // standard used to inform downstream processes not to add ANSI escape\n        // codes to their output. SEE: https://www.no-color.org\n        if !stdoutStream.isTTY || !stderrStream.isTTY {\n            env[\"NO_COLOR\"] = \"1\"\n        }\n\n        // Add library paths so that test runner executables are able to find the\n        // corresponding test libraries, even if local rpaths were disabled in the\n        // build.\n        for path in testProductPaths {\n            env.appendPath(key: .libraryPath, value: path.parentDirectory.pathString)\n        }\n\n        // Add the code coverage related variables.\n        if buildParameters.testingParameters.enableCodeCoverage {\n            // Defines the path at which the profraw files will be written on test execution.\n            //\n            // `%Nm` will create a pool of N profraw files and append the data from each execution\n            // in one of the files. The runtime takes care of selecting a raw profile from the pool,\n            // locking it, and updating it before the program exits. If N is not specified, it is\n            // inferred to be 1.\n            //\n            // This is fine for parallel execution within a process, but for parallel tests, SwiftPM\n            // repeatedly invokes the test binary with the testcase name as the filter and the\n            // locking cannot be enforced by the runtime across the process boundaries.\n            //\n            // It's also possible that tests themselves will fork (e.g. for exit tests provided by\n            // Swift Testing), which will inherit the environment of the parent process, and so\n            // write to the same file, leading to profile data corruption.\n            //\n            // For these reasons, we unilaterally also add a %p, which will cause uniquely named\n            // files per process.\n            //\n            // These are all merged using `llvm-profdata merge` once the outer test command has\n            // completed.\n            let codecovProfile = buildParameters.buildPath.appending(components: \"codecov\", \"\\(library)%m.%p.profraw\")\n            env[\"LLVM_PROFILE_FILE\"] = codecovProfile.pathString\n        }\n        #if !os(macOS)\n        #if os(Windows)\n        if let xctestLocation = toolchain.xctestPath {\n            env.prependPath(key: .path, value: xctestLocation.pathString)\n        }\n        if let swiftTestingLocation = toolchain.swiftTestingPath {\n            env.prependPath(key: .path, value: swiftTestingLocation.pathString)\n        }\n        #endif\n        return env\n        #else\n        // Add path to swift-testing override if there is one\n        if let swiftTestingPath = toolchain.swiftTestingPath {\n            if swiftTestingPath.extension == \"framework\" {\n                env.appendPath(key: \"DYLD_FRAMEWORK_PATH\", value: swiftTestingPath.pathString)\n            } else {\n                env.appendPath(key: \"DYLD_LIBRARY_PATH\", value: swiftTestingPath.pathString)\n            }\n        }\n\n        // Add the sdk platform path if we have it.\n        // Since XCTestHelper targets macOS, we need the macOS platform paths here.\n        if let sdkPlatformPaths = try? SwiftSDK.sdkPlatformPaths(for: .macOS) {\n            // appending since we prefer the user setting (if set) to the one we inject\n            for frameworkPath in sdkPlatformPaths.runtimeFrameworkSearchPaths {\n                env.appendPath(key: \"DYLD_FRAMEWORK_PATH\", value: frameworkPath.pathString)\n            }\n            for libraryPath in sdkPlatformPaths.runtimeLibrarySearchPaths {\n                env.appendPath(key: \"DYLD_LIBRARY_PATH\", value: libraryPath.pathString)\n            }\n        }\n\n        // We aren't using XCTest's harness logic to run Swift Testing tests.\n        if library == .xctest {\n            env[\"SWIFT_TESTING_ENABLED\"] = \"0\"\n        }\n\n        // Fast path when no sanitizers are enabled.\n        if sanitizers.isEmpty {\n            return env\n        }\n\n        // Get the runtime libraries.\n        var runtimes = try sanitizers.map({ sanitizer in\n            return try toolchain.runtimeLibrary(for: sanitizer).pathString\n        })\n\n        // Append any existing value to the front.\n        if let existingValue = env[\"DYLD_INSERT_LIBRARIES\"], !existingValue.isEmpty {\n            runtimes.insert(existingValue, at: 0)\n        }\n\n        env[\"DYLD_INSERT_LIBRARIES\"] = runtimes.joined(separator: \":\")\n        return env\n        #endif\n    }\n}\n\nextension SwiftCommandState {\n    func buildParametersForTest(\n        enableCodeCoverage: Bool,\n        enableTestability: Bool? = nil,\n        shouldSkipBuilding: Bool = false,\n        experimentalTestOutput: Bool = false\n    ) throws -> (productsBuildParameters: BuildParameters, toolsBuildParameters: BuildParameters) {\n        let productsBuildParameters = buildParametersForTest(\n            modifying: try productsBuildParameters,\n            enableCodeCoverage: enableCodeCoverage,\n            enableTestability: enableTestability,\n            shouldSkipBuilding: shouldSkipBuilding,\n            experimentalTestOutput: experimentalTestOutput\n        )\n        let toolsBuildParameters = buildParametersForTest(\n            modifying: try toolsBuildParameters,\n            enableCodeCoverage: enableCodeCoverage,\n            enableTestability: enableTestability,\n            shouldSkipBuilding: shouldSkipBuilding,\n            experimentalTestOutput: experimentalTestOutput\n        )\n        return (productsBuildParameters, toolsBuildParameters)\n    }\n\n    private func buildParametersForTest(\n        modifying parameters: BuildParameters,\n        enableCodeCoverage: Bool,\n        enableTestability: Bool?,\n        shouldSkipBuilding: Bool,\n        experimentalTestOutput: Bool\n    ) -> BuildParameters {\n        var parameters = parameters\n        parameters.testingParameters.enableCodeCoverage = enableCodeCoverage\n        // for test commands, we normally enable building with testability\n        // but we let users override this with a flag\n        parameters.testingParameters.explicitlyEnabledTestability = enableTestability ?? true\n        parameters.shouldSkipBuilding = shouldSkipBuilding\n        parameters.testingParameters.experimentalTestOutput = experimentalTestOutput\n        return parameters\n    }\n}\n"
  },
  {
    "path": "Sources/Commands/Utilities/XCTEvents.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct TestEventRecord: Codable {\n    let caseFailure: TestCaseFailureRecord?\n    let suiteFailure: TestSuiteFailureRecord?\n\n    let bundleEvent: TestBundleEventRecord?\n    let suiteEvent: TestSuiteEventRecord?\n    let caseEvent: TestCaseEventRecord?\n\n    init(\n        caseFailure: TestCaseFailureRecord? = nil,\n        suiteFailure: TestSuiteFailureRecord? = nil,\n        bundleEvent: TestBundleEventRecord? = nil,\n        suiteEvent: TestSuiteEventRecord? = nil,\n        caseEvent: TestCaseEventRecord? = nil\n    ) {\n        self.caseFailure = caseFailure\n        self.suiteFailure = suiteFailure\n        self.bundleEvent = bundleEvent\n        self.suiteEvent = suiteEvent\n        self.caseEvent = caseEvent\n    }\n}\n\n// MARK: - Records\n\nstruct TestAttachment: Codable {\n    let name: String?\n    // TODO: Handle `userInfo: [AnyHashable : Any]?`\n    let uniformTypeIdentifier: String\n    let payload: Data?\n}\n\nstruct TestBundleEventRecord: Codable {\n    let bundle: TestBundle\n    let event: TestEvent\n}\n\nstruct TestCaseEventRecord: Codable {\n    let testCase: TestCase\n    let event: TestEvent\n}\n\nstruct TestCaseFailureRecord: Codable, CustomStringConvertible {\n    let testCase: TestCase\n    let issue: TestIssue\n    let failureKind: TestFailureKind\n\n    var description: String {\n        return \"\\(issue.sourceCodeContext.description)\\(testCase) \\(issue.compactDescription)\"\n    }\n\n    func description(with knownLocation: String) -> String {\n        return \"\\(issue.sourceCodeContext.description(with: knownLocation))\\(testCase) \\(issue.compactDescription)\"\n    }\n}\n\nstruct TestSuiteEventRecord: Codable {\n    let suite: TestSuiteRecord\n    let event: TestEvent\n}\n\nstruct TestSuiteFailureRecord: Codable {\n    let suite: TestSuiteRecord\n    let issue: TestIssue\n    let failureKind: TestFailureKind\n}\n\n// MARK: Primitives\n\nstruct TestBundle: Codable {\n    let bundleIdentifier: String?\n    let bundlePath: String\n}\n\nstruct TestCase: Codable, CustomStringConvertible {\n    let name: String\n\n    var description: String {\n        return name\n    }\n}\n\nstruct TestErrorInfo: Codable {\n    let description: String\n    let type: String\n}\n\nenum TestEvent: Codable {\n    case start\n    case finish\n}\n\nenum TestFailureKind: Codable, Equatable {\n    case unexpected\n    case expected(failureReason: String?)\n\n    var isExpected: Bool {\n        switch self {\n        case .expected: return true\n        case .unexpected: return false\n        }\n    }\n}\n\nstruct TestIssue: Codable {\n    let type: TestIssueType\n    let compactDescription: String\n    let detailedDescription: String?\n    let associatedError: TestErrorInfo?\n    let sourceCodeContext: TestSourceCodeContext\n    let attachments: [TestAttachment]\n}\n\nenum TestIssueType: Codable {\n    case assertionFailure\n    case performanceRegression\n    case system\n    case thrownError\n    case uncaughtException\n    case unmatchedExpectedFailure\n    case unknown\n}\n\nstruct TestLocation: Codable, CustomStringConvertible {\n    let file: String\n    let line: Int\n\n    var description: String {\n        return \"\\(file):\\(line) \"\n    }\n\n    func description(with knownLocation: String) -> String {\n        var file = self.file\n        [\"file:/\", knownLocation].forEach {\n            if file.hasPrefix($0) {\n                file = String(file.dropFirst($0.count + 1))\n            }\n        }\n        return \"\\(file):\\(line) \"\n    }\n}\n\nstruct TestSourceCodeContext: Codable, CustomStringConvertible {\n    let callStack: [TestSourceCodeFrame]\n    let location: TestLocation?\n\n    var description: String {\n        return location?.description ?? \"\"\n    }\n\n    func description(with knownLocation: String) -> String {\n        return location?.description(with: knownLocation) ?? \"\"\n    }\n}\n\nstruct TestSourceCodeFrame: Codable {\n    let address: UInt64\n    let symbolInfo: TestSourceCodeSymbolInfo?\n    let symbolicationError: TestErrorInfo?\n}\n\nstruct TestSourceCodeSymbolInfo: Codable {\n    let imageName: String\n    let symbolName: String\n    let location: TestLocation?\n}\n\nstruct TestSuiteRecord: Codable {\n    let name: String\n}\n\n// MARK: XCTest compatibility\n\nextension TestIssue {\n    init(description: String, inFile filePath: String?, atLine lineNumber: Int) {\n        let location: TestLocation?\n        if let filePath = filePath {\n            location = .init(file: filePath, line: lineNumber)\n        } else {\n            location = nil\n        }\n        self.init(type: .assertionFailure, compactDescription: description, detailedDescription: description, associatedError: nil, sourceCodeContext: .init(callStack: [], location: location), attachments: [])\n    }\n}\n\n#if false // This is just here for pre-flighting the code generation done in `SwiftTargetBuildDescription`.\nimport XCTest\n\n#if canImport(Darwin) // XCTAttachment is unavailable in swift-corelibs-xctest.\nextension TestAttachment {\n    init(_ attachment: XCTAttachment) {\n        self.init(\n            name: attachment.name,\n            uniformTypeIdentifier: attachment.uniformTypeIdentifier,\n            payload: attachment.value(forKey: \"payload\") as? Data\n        )\n    }\n}\n#endif\n\nextension TestBundle {\n    init(_ testBundle: Bundle) {\n        self.init(\n            bundleIdentifier: testBundle.bundleIdentifier,\n            bundlePath: testBundle.bundlePath\n        )\n    }\n}\n\nextension TestCase {\n    init(_ testCase: XCTestCase) {\n        self.init(name: testCase.name)\n    }\n}\n\nextension TestErrorInfo {\n    init(_ error: Swift.Error) {\n        self.init(description: \"\\(error)\", type: \"\\(Swift.type(of: error))\")\n    }\n}\n\n#if canImport(Darwin) // XCTIssue is unavailable in swift-corelibs-xctest.\nextension TestIssue {\n    init(_ issue: XCTIssue) {\n        self.init(\n            type: .init(defaultBuildParameters: issue.type),\n            compactDescription: issue.compactDescription,\n            detailedDescription: issue.detailedDescription,\n            associatedError: issue.associatedError.map { .init(defaultBuildParameters: $0) },\n            sourceCodeContext: .init(defaultBuildParameters: issue.sourceCodeContext),\n            attachments: issue.attachments.map { .init(defaultBuildParameters: $0) }\n        )\n    }\n}\n\nextension TestIssueType {\n    init(_ type: XCTIssue.IssueType) {\n        switch type {\n        case .assertionFailure: self = .assertionFailure\n        case .thrownError: self = .thrownError\n        case .uncaughtException: self = .uncaughtException\n        case .performanceRegression: self = .performanceRegression\n        case .system: self = .system\n        case .unmatchedExpectedFailure: self = .unmatchedExpectedFailure\n        @unknown default: self = .unknown\n        }\n    }\n}\n#endif\n\n#if canImport(Darwin) // XCTSourceCodeLocation/XCTSourceCodeContext/XCTSourceCodeFrame/XCTSourceCodeSymbolInfo is unavailable in swift-corelibs-xctest.\nextension TestLocation {\n    init(_ location: XCTSourceCodeLocation) {\n        self.init(\n            file: location.fileURL.absoluteString,\n            line: location.lineNumber\n        )\n    }\n}\n\nextension TestSourceCodeContext {\n    init(_ context: XCTSourceCodeContext) {\n        self.init(\n            callStack: context.callStack.map { .init(defaultBuildParameters: $0) },\n            location: context.location.map { .init(defaultBuildParameters: $0) }\n        )\n    }\n}\n\nextension TestSourceCodeFrame {\n    init(_ frame: XCTSourceCodeFrame) {\n        self.init(\n            address: frame.address,\n            symbolInfo: (try? frame.symbolInfo()).map { .init(defaultBuildParameters: $0) },\n            symbolicationError: frame.symbolicationError.map { .init(defaultBuildParameters: $0) }\n        )\n    }\n}\n\nextension TestSourceCodeSymbolInfo {\n    init(_ symbolInfo: XCTSourceCodeSymbolInfo) {\n        self.init(\n            imageName: symbolInfo.imageName,\n            symbolName: symbolInfo.symbolName,\n            location: symbolInfo.location.map { .init(defaultBuildParameters: $0) }\n        )\n    }\n}\n#endif\n\nextension TestSuiteRecord {\n    init(_ testSuite: XCTestSuite) {\n        self.init(name: testSuite.name)\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/CoreCommands/BuildSystemSupport.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Build\nimport SPMBuildCore\nimport XCBuildSupport\nimport SwiftBuildSupport\nimport PackageGraph\nimport Workspace\n\nimport class Basics.ObservabilityScope\nimport struct PackageGraph.ModulesGraph\nimport struct PackageLoading.FileRuleDescription\nimport protocol TSCBasic.OutputByteStream\nimport enum PackageModel.TraitConfiguration\n\nprivate struct NativeBuildSystemFactory: BuildSystemFactory {\n    let swiftCommandState: SwiftCommandState\n\n    func makeBuildSystem(\n        explicitProduct: String?,\n        enableAllTraits: Bool,\n        cacheBuildManifest: Bool,\n        productsBuildParameters: BuildParameters?,\n        toolsBuildParameters: BuildParameters?,\n        packageGraphLoader: (() async throws -> ModulesGraph)?,\n        outputStream: OutputByteStream?,\n        logLevel: Diagnostic.Severity?,\n        observabilityScope: ObservabilityScope?,\n        delegate: BuildSystemDelegate?\n    ) async throws -> any BuildSystem {\n        _ = try await swiftCommandState.getRootPackageInformation(enableAllTraits)\n        let testEntryPointPath = productsBuildParameters?.testProductStyle.explicitlySpecifiedEntryPointPath\n        let cacheBuildManifest = if cacheBuildManifest {\n            try await self.swiftCommandState.canUseCachedBuildManifest()\n        } else {\n            false\n        }\n        return try BuildOperation(\n            productsBuildParameters: try productsBuildParameters ?? self.swiftCommandState.productsBuildParameters,\n            toolsBuildParameters: try toolsBuildParameters ?? self.swiftCommandState.toolsBuildParameters,\n            cacheBuildManifest: cacheBuildManifest,\n            packageGraphLoader: packageGraphLoader ?? {\n                try await self.swiftCommandState.loadPackageGraph(\n                    explicitProduct: explicitProduct,\n                    enableAllTraits: enableAllTraits,\n                    testEntryPointPath: testEntryPointPath\n                )\n            },\n            pluginConfiguration: .init(\n                scriptRunner: self.swiftCommandState.getPluginScriptRunner(),\n                workDirectory: try self.swiftCommandState.getActiveWorkspace().location.pluginWorkingDirectory,\n                disableSandbox: self.swiftCommandState.shouldDisableSandbox\n            ),\n            scratchDirectory: self.swiftCommandState.scratchDirectory,\n            traitConfiguration: enableAllTraits ? .enableAllTraits : self.swiftCommandState.traitConfiguration,\n            additionalFileRules: FileRuleDescription.swiftpmFileTypes,\n            pkgConfigDirectories: self.swiftCommandState.options.locations.pkgConfigDirectories,\n            outputStream: outputStream ?? self.swiftCommandState.outputStream,\n            logLevel: logLevel ?? self.swiftCommandState.logLevel,\n            fileSystem: self.swiftCommandState.fileSystem,\n            observabilityScope: observabilityScope ?? self.swiftCommandState.observabilityScope,\n            delegate: delegate)\n    }\n}\n\nprivate struct XcodeBuildSystemFactory: BuildSystemFactory {\n    let swiftCommandState: SwiftCommandState\n\n    func makeBuildSystem(\n        explicitProduct: String?,\n        enableAllTraits: Bool,\n        cacheBuildManifest: Bool,\n        productsBuildParameters: BuildParameters?,\n        toolsBuildParameters: BuildParameters?,\n        packageGraphLoader: (() async throws -> ModulesGraph)?,\n        outputStream: OutputByteStream?,\n        logLevel: Diagnostic.Severity?,\n        observabilityScope: ObservabilityScope?,\n        delegate: BuildSystemDelegate?\n    ) throws -> any BuildSystem {\n        return try XcodeBuildSystem(\n            buildParameters: productsBuildParameters ?? self.swiftCommandState.productsBuildParameters,\n            packageGraphLoader: packageGraphLoader ?? {\n                try await self.swiftCommandState.loadPackageGraph(\n                    explicitProduct: explicitProduct,\n                    enableAllTraits: enableAllTraits\n                )\n            },\n            outputStream: outputStream ?? self.swiftCommandState.outputStream,\n            logLevel: logLevel ?? self.swiftCommandState.logLevel,\n            fileSystem: self.swiftCommandState.fileSystem,\n            observabilityScope: observabilityScope ?? self.swiftCommandState.observabilityScope,\n            delegate: delegate\n        )\n    }\n}\n\nprivate struct SwiftBuildSystemFactory: BuildSystemFactory {\n    let swiftCommandState: SwiftCommandState\n\n    func makeBuildSystem(\n        explicitProduct: String?,\n        enableAllTraits: Bool,\n        cacheBuildManifest: Bool,\n        productsBuildParameters: BuildParameters?,\n        toolsBuildParameters: BuildParameters?,\n        packageGraphLoader: (() async throws -> ModulesGraph)?,\n        outputStream: OutputByteStream?,\n        logLevel: Diagnostic.Severity?,\n        observabilityScope: ObservabilityScope?,\n        delegate: BuildSystemDelegate?\n    ) throws -> any BuildSystem {\n        return try SwiftBuildSystem(\n            buildParameters: productsBuildParameters ?? self.swiftCommandState.productsBuildParameters,\n            packageGraphLoader: packageGraphLoader ?? {\n                try await self.swiftCommandState.loadPackageGraph(\n                    explicitProduct: explicitProduct,\n                    enableAllTraits: enableAllTraits,\n                )\n            },\n            packageManagerResourcesDirectory: swiftCommandState.packageManagerResourcesDirectory,\n            additionalFileRules: FileRuleDescription.swiftpmFileTypes + FileRuleDescription.xcbuildFileTypes,\n            outputStream: outputStream ?? self.swiftCommandState.outputStream,\n            logLevel: logLevel ?? self.swiftCommandState.logLevel,\n            fileSystem: self.swiftCommandState.fileSystem,\n            observabilityScope: observabilityScope ?? self.swiftCommandState.observabilityScope,\n            pluginConfiguration: .init(\n                scriptRunner: self.swiftCommandState.getPluginScriptRunner(),\n                workDirectory: try self.swiftCommandState.getActiveWorkspace().location.pluginWorkingDirectory,\n                disableSandbox: self.swiftCommandState.shouldDisableSandbox\n            ),\n            delegate: delegate\n        )\n    }\n}\n\nextension SwiftCommandState {\n    public var defaultBuildSystemProvider: BuildSystemProvider {\n        .init(providers: [\n            .native: NativeBuildSystemFactory(swiftCommandState: self),\n            .swiftbuild: SwiftBuildSystemFactory(swiftCommandState: self),\n            .xcode: XcodeBuildSystemFactory(swiftCommandState: self)\n        ])\n    }\n}\n"
  },
  {
    "path": "Sources/CoreCommands/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2022 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(CoreCommands\n  BuildSystemSupport.swift\n  SwiftCommandState.swift\n  SwiftCommandObservabilityHandler.swift\n  Options.swift)\ntarget_link_libraries(CoreCommands PUBLIC\n  ArgumentParser\n  Basics\n  Build\n  PackageGraph\n  PackageModel\n  SBOMModel\n  TSCBasic\n  TSCUtility\n  Workspace\n  XCBuildSupport\n  SwiftBuildSupport)\ntarget_link_libraries(CoreCommands PRIVATE\n  DriverSupport\n  $<$<NOT:$<PLATFORM_ID:Darwin>>:FoundationXML>)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(CoreCommands PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS CoreCommands\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/CoreCommands/Options.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\nimport struct Basics.AbsolutePath\nimport var Basics.localFileSystem\nimport enum Basics.TestingLibrary\nimport struct Basics.Triple\n\nimport struct Foundation.URL\n\nimport enum PackageModel.BuildConfiguration\nimport struct PackageModel.BuildFlags\nimport struct PackageModel.EnabledSanitizers\nimport class PackageModel.Manifest\nimport struct PackageModel.PackageIdentity\nimport enum PackageModel.Sanitizer\n@_spi(SwiftPMInternal) import struct PackageModel.SwiftSDK\n\nimport enum PackageModel.TraitConfiguration\n\nimport enum SBOMModel.Filter\nimport enum SBOMModel.Spec\nimport enum SBOMModel.SBOMCommandError\n\nimport struct SPMBuildCore.BuildParameters\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum SPMBuildCore.ConfigurableEnvVar\n\nimport struct TSCBasic.StringError\n\nimport struct TSCUtility.Version\n\nimport Foundation\nimport class Workspace.Workspace\nimport struct Workspace.WorkspaceConfiguration\n\npublic struct GlobalOptions: ParsableArguments {\n    public init() {}\n\n    @OptionGroup(title: \"Paths & Locations\")\n    public var locations: LocationOptions\n\n    @OptionGroup(title: \"Caching\")\n    public var caching: CachingOptions\n\n    @OptionGroup(title: \"Logging\")\n    public var logging: LoggingOptions\n\n    @OptionGroup(title: \"Security\")\n    public var security: SecurityOptions\n\n    @OptionGroup(title: \"Resolution\")\n    public var resolver: ResolverOptions\n\n    @OptionGroup(title: \"Build Options\")\n    public var build: BuildOptions\n\n    @OptionGroup(title: \"Build Options\")\n    public var linker: LinkerOptions\n\n    @OptionGroup(title: \"Trait Options\")\n    public var traits: TraitOptions\n}\n\npublic struct LocationOptions: ParsableArguments {\n    public init() {}\n\n    @Option(\n        name: .customLong(\"package-path\"),\n        help: \"Specify the package path to operate on (default current directory). This changes the working directory before any other operation.\",\n        completion: .directory\n    )\n    public var packageDirectory: AbsolutePath?\n\n    @Option(name: .customLong(\"cache-path\"), help: \"Specify the shared cache directory path.\", completion: .directory)\n    public var cacheDirectory: AbsolutePath?\n\n    @Option(\n        name: .customLong(\"config-path\"),\n        help: \"Specify the shared configuration directory path.\",\n        completion: .directory\n    )\n    public var configurationDirectory: AbsolutePath?\n\n    @Option(\n        name: .customLong(\"security-path\"),\n        help: \"Specify the shared security directory path.\",\n        completion: .directory\n    )\n    public var securityDirectory: AbsolutePath?\n\n    /// The custom .build directory, if provided.\n    @Option(\n        name: .customLong(\"scratch-path\"),\n        help: \"Specify a custom scratch directory path. (default .build)\",\n        completion: .directory\n    )\n    var _scratchDirectory: AbsolutePath?\n\n    @Option(name: .customLong(\"build-path\"), help: .hidden)\n    var _deprecated_buildPath: AbsolutePath?\n\n    var scratchDirectory: AbsolutePath? {\n        self._scratchDirectory ?? self._deprecated_buildPath\n    }\n\n    /// The path to the file containing multiroot package data. This is currently Xcode's workspace file.\n    @Option(name: .customLong(\"multiroot-data-file\"), help: .hidden, completion: .directory)\n    public var multirootPackageDataFile: AbsolutePath?\n\n    /// Path to the compilation destination describing JSON file.\n    @Option(name: .customLong(\"destination\"), help: .hidden, completion: .directory)\n    public var customCompileDestination: AbsolutePath?\n\n    @Option(name: .customLong(\"experimental-swift-sdks-path\"), help: .hidden, completion: .directory)\n    public var deprecatedSwiftSDKsDirectory: AbsolutePath?\n\n    /// Path to the directory containing installed Swift SDKs.\n    @Option(\n        name: .customLong(\"swift-sdks-path\"),\n        help: \"Path to the directory containing installed Swift SDKs.\",\n        completion: .directory\n    )\n    public var swiftSDKsDirectory: AbsolutePath?\n\n    @Option(\n        name: .customLong(\"toolset\"),\n        help: \"\"\"\n            Specify a toolset JSON file to use when building for the target platform. \\\n            Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order \\\n            they're specified into a single final toolset for the current build.\n            \"\"\",\n        completion: .file(extensions: [\".json\"])\n    )\n    public var toolsetPaths: [AbsolutePath] = []\n\n    @Option(\n        name: .customLong(\"pkg-config-path\"),\n        help:\n        \"\"\"\n        Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\n        specify more than one path.\n        \"\"\",\n        completion: .directory\n    )\n    public var pkgConfigDirectories: [AbsolutePath] = []\n\n    @Option(\n        help: .init(\"Specify alternate path to search for resources required for SwiftPM to operate. (default: <Toolchain Directory>/usr/share/pm)\", visibility: .hidden),\n        completion: .directory\n    )\n    public var packageManagerResourcesDirectory: AbsolutePath?\n\n    @Flag(name: .customLong(\"ignore-lock\"), help: .hidden)\n    public var ignoreLock: Bool = false\n\n    @Flag(name: .customLong(\"experimental-skip-acquiring-lock\"), help: .hidden)\n    public var skipAcquiringLock: Bool = false\n}\n\npublic struct CachingOptions: ParsableArguments {\n    public init() {}\n\n    /// Disables package caching.\n    @Flag(name: .customLong(\"dependency-cache\"),\n        inversion: .prefixedEnableDisable,\n        help: \"Determines whether dependency fetching uses a shared cache.\"\n    )\n    public var useDependenciesCache: Bool = true\n\n    /// Disables manifest caching.\n    @Flag(name: .customLong(\"disable-package-manifest-caching\"), help: .hidden)\n    public var shouldDisableManifestCaching: Bool = false\n\n    /// Whether to enable llbuild manifest caching.\n    @Flag(name: .customLong(\"build-manifest-caching\"), inversion: .prefixedEnableDisable)\n    public var cacheBuildManifest: Bool = true\n\n    /// Disables manifest caching.\n    @Option(\n        name: .customLong(\"manifest-cache\"),\n        help: \"Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)\"\n    )\n    public var manifestCachingMode: ManifestCachingMode = .shared\n\n    public enum ManifestCachingMode: String, ExpressibleByArgument {\n        case none\n        case local\n        case shared\n\n        public init?(argument: String) {\n            self.init(rawValue: argument)\n        }\n    }\n\n    /// Whether to use macro prebuilts or not\n    @Flag(name: .customLong(\"experimental-prebuilts\"),\n          inversion: .prefixedEnableDisable,\n          help: \"Determines whether macros use prebuilt swift-syntax libraries.\")\n    public var usePrebuilts: Bool = true\n\n    /// Hidden option to override the prebuilts download location for testing\n    @Option(\n        name: .customLong(\"experimental-prebuilts-download-url\"),\n        help: .hidden\n    )\n    public var prebuiltsDownloadURL: String?\n\n    @Option(\n        name: .customLong(\"experimental-prebuilts-root-cert\"),\n        help: .hidden\n    )\n    public var prebuiltsRootCertPath: String?\n}\n\npublic struct LoggingOptions: ParsableArguments {\n    public init() {}\n\n    /// The verbosity of informational output.\n    @Flag(name: .shortAndLong, help: \"Increase verbosity to include informational output.\")\n    public var verbose: Bool = false\n\n    /// The verbosity of informational output.\n    @Flag(name: [.long, .customLong(\"vv\")], help: \"Increase verbosity to include debug output.\")\n    public var veryVerbose: Bool = false\n\n    /// Whether logging output should be limited to `.error`.\n    @Flag(name: .shortAndLong, help: \"Decrease verbosity to only include error output.\")\n    public var quiet: Bool = false\n\n    @Flag(name: .customLong(\"color-diagnostics\"),\n          inversion: .prefixedNo,\n          help:\n            \"\"\"\n            Determines whether color diagnostics appear when printing to a TTY.\n            By default, color diagnostics are enabled when connected to a TTY and disabled otherwise.\n            \"\"\")\n    public var colorDiagnostics: Bool = ProcessInfo.processInfo.environment[\"NO_COLOR\"] == nil\n}\n\npublic struct SecurityOptions: ParsableArguments {\n    public init() {}\n\n    /// Disables sandboxing when executing subprocesses.\n    @Flag(name: .customLong(\"disable-sandbox\"), help: \"Disable the sandbox when executing subprocesses.\")\n    public var shouldDisableSandbox: Bool = false\n\n    /// Force usage of the netrc file even in cases where it is not allowed.\n    @Flag(name: .customLong(\"netrc\"), help: \"Use netrc file even in cases where other credential stores are preferred.\")\n    public var forceNetrc: Bool = false\n\n    /// Whether to load netrc files for authenticating with remote servers\n    /// when downloading binary artifacts. This has no effects on registry\n    /// communications.\n    @Flag(\n        inversion: .prefixedEnableDisable,\n        exclusivity: .exclusive,\n        help: \"Determines whether SwiftPM loads credentials from a netrc file.\"\n    )\n    public var netrc: Bool = true\n\n    /// The path to the netrc file used when `netrc` is `true`.\n    @Option(\n        name: .customLong(\"netrc-file\"),\n        help: \"Specify the netrc file path.\",\n        completion: .file()\n    )\n    public var netrcFilePath: AbsolutePath?\n\n    /// Whether to use keychain for authenticating with remote servers\n    /// when downloading binary artifacts. This has no effects on registry\n    /// communications.\n    #if canImport(Security)\n    @Flag(\n        inversion: .prefixedEnableDisable,\n        exclusivity: .exclusive,\n        help: \"Determines whether SwiftPM searches for credentials in the macOS keychain.\"\n    )\n    public var keychain: Bool = true\n    #else\n    @Flag(\n        inversion: .prefixedEnableDisable,\n        exclusivity: .exclusive,\n        help: .hidden\n    )\n    public var keychain: Bool = false\n    #endif\n\n    @Option(name: .customLong(\"resolver-fingerprint-checking\"))\n    public var fingerprintCheckingMode: WorkspaceConfiguration.CheckingMode = .strict\n\n    @Option(name: .customLong(\"resolver-signing-entity-checking\"))\n    public var signingEntityCheckingMode: WorkspaceConfiguration.CheckingMode = .warn\n\n    @Flag(\n        inversion: .prefixedEnableDisable,\n        exclusivity: .exclusive,\n        help: \"Determines whether SwiftPM validates signatures on package releases downloaded from the registry.\"\n    )\n    public var signatureValidation: Bool = true\n}\n\npublic struct ResolverOptions: ParsableArguments {\n    public init() {}\n\n    /// Enable prefetching in resolver which will kick off parallel git cloning.\n    @Flag(name: .customLong(\"prefetching\"), inversion: .prefixedEnableDisable)\n    public var shouldEnableResolverPrefetching: Bool = true\n\n    /// Use Package.resolved file for resolving dependencies.\n    @Flag(\n        name: [.long, .customLong(\"disable-automatic-resolution\"), .customLong(\"only-use-versions-from-resolved-file\")],\n        help: \"Only use versions from the Package.resolved file and fail resolution if it is out-of-date.\"\n    )\n    public var forceResolvedVersions: Bool = false\n\n    /// Skip updating dependencies from their remote during a resolution.\n    @Flag(name: .customLong(\"skip-update\"), help: \"Skip updating dependencies from their remote during a resolution.\")\n    public var skipDependencyUpdate: Bool = false\n\n    @Flag(help: \"Define automatic transformation of source control based dependencies to registry based ones.\")\n    public var sourceControlToRegistryDependencyTransformation: SourceControlToRegistryDependencyTransformation =\n        .disabled\n\n    /// Enables pruning unused dependencies to omit redundant calculations during resolution, and each phase thereafter.\n    /// Hidden from the generated help text as this feature is only currently being considered for traits.\n    @Flag(\n        name: .customLong(\"experimental-prune-unused-dependencies\"),\n        help: ArgumentHelp(\n            \"Enables the ability to prune unused dependencies of the package to avoid redundant loads during resolution.\",\n            visibility: .hidden\n        )\n    )\n    public var pruneDependencies: Bool = false\n\n    @Option(help: \"Default registry URL to use, instead of the registries.json configuration file.\")\n    public var defaultRegistryURL: URL?\n\n    public enum SourceControlToRegistryDependencyTransformation: EnumerableFlag {\n        case disabled\n        case identity\n        case swizzle\n\n        public static func name(for value: Self) -> NameSpecification {\n            switch value {\n            case .disabled:\n                return .customLong(\"disable-scm-to-registry-transformation\")\n            case .identity:\n                return .customLong(\"use-registry-identity-for-scm\")\n            case .swizzle:\n                return .customLong(\"replace-scm-with-registry\")\n            }\n        }\n\n        public static func help(for value: SourceControlToRegistryDependencyTransformation) -> ArgumentHelp? {\n            switch value {\n            case .disabled:\n                return \"Disable source control to registry transformation.\"\n            case .identity:\n                return \"Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.\"\n            case .swizzle:\n                return \"Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.\"\n            }\n        }\n    }\n}\n\npublic struct BuildOptions: ParsableArguments {\n    public init() {}\n\n    /// Build configuration.\n    @Option(name: .shortAndLong, help: \"Build with the specified configuration.\")\n    public var configuration: BuildConfiguration?\n\n    @Option(\n        name: .customLong(\"Xcc\", withSingleDash: true),\n        parsing: .unconditionalSingleValue,\n        help: \"Pass flag through to all C compiler invocations.\"\n    )\n    var cCompilerFlags: [String] = []\n\n    @Option(\n        name: .customLong(\"Xswiftc\", withSingleDash: true),\n        parsing: .unconditionalSingleValue,\n        help: \"Pass flag through to all Swift compiler invocations.\"\n    )\n    var swiftCompilerFlags: [String] = []\n\n    @Option(\n        name: .customLong(\"Xlinker\", withSingleDash: true),\n        parsing: .unconditionalSingleValue,\n        help: \"Pass flag through to all linker invocations.\"\n    )\n    var linkerFlags: [String] = []\n\n    @Option(\n        name: .customLong(\"Xcxx\", withSingleDash: true),\n        parsing: .unconditionalSingleValue,\n        help: \"Pass flag through to all C++ compiler invocations.\"\n    )\n    var cxxCompilerFlags: [String] = []\n\n    @Option(\n        name: .customLong(\"Xxcbuild\", withSingleDash: true),\n        parsing: .unconditionalSingleValue,\n        help: ArgumentHelp(\n            \"Pass flag through to the Xcode build system invocations.\",\n            visibility: .hidden\n        )\n    )\n    public var xcbuildFlags: [String] = []\n\n    @Option(\n        name: .customLong(\"Xbuild-tools-swiftc\", withSingleDash: true),\n        parsing: .unconditionalSingleValue,\n        help: ArgumentHelp(\n            \"Pass flag to Swift compiler invocations for build-time executables (manifest and plugins).\",\n            visibility: .hidden\n        )\n    )\n    public var _buildToolsSwiftCFlags: [String] = []\n\n    @Option(\n        name: .customLong(\"Xmanifest\", withSingleDash: true),\n        parsing: .unconditionalSingleValue,\n        help: ArgumentHelp(\n            \"Pass flag to the manifest build invocation. Deprecated: use '-Xbuild-tools-swiftc' instead.\",\n            visibility: .hidden\n        )\n    )\n    public var _deprecated_manifestFlags: [String] = []\n\n    var manifestFlags: [String] {\n        self._deprecated_manifestFlags.isEmpty ?\n            self._buildToolsSwiftCFlags :\n            self._deprecated_manifestFlags\n    }\n\n    var pluginSwiftCFlags: [String] {\n        self._buildToolsSwiftCFlags\n    }\n\n    public var buildFlags: BuildFlags {\n        BuildFlags(\n            cCompilerFlags: self.cCompilerFlags.constructBuildFlags(source: .commandLineOptions),\n            cxxCompilerFlags: self.cxxCompilerFlags.constructBuildFlags(source: .commandLineOptions),\n            swiftCompilerFlags: self.swiftCompilerFlags.constructBuildFlags(source: .commandLineOptions),\n            linkerFlags: self.linkerFlags.constructBuildFlags(source: .commandLineOptions),\n            xcbuildFlags: self.xcbuildFlags\n        )\n    }\n\n    /// The compilation destination’s target triple.\n    @Option(name: .customLong(\"triple\"), transform: Triple.init)\n    public var customCompileTriple: Triple?\n\n    /// Path to the compilation destination’s SDK.\n    @Option(name: .customLong(\"sdk\"))\n    public var customCompileSDK: AbsolutePath?\n\n    /// Path to the compilation destination’s toolchain.\n    @Option(name: .customLong(\"toolchain\"))\n    public var customCompileToolchain: AbsolutePath?\n\n    /// The architectures to compile for.\n    @Option(\n        name: .customLong(\"arch\"),\n        help: ArgumentHelp(\n            \"Build the package for the specified architectures.\",\n            visibility: .hidden\n        )\n    )\n    public var architectures: [String] = []\n\n    @Option(name: .customLong(\"experimental-swift-sdk\"), help: .hidden)\n    public var deprecatedSwiftSDKSelector: String?\n\n    /// Filter for selecting a specific Swift SDK to build with.\n    @Option(\n        name: .customLong(\"swift-sdk\"),\n        help: \"Filter for selecting a specific Swift SDK to build with.\"\n    )\n    public var swiftSDKSelector: String?\n\n    /// Which compile-time sanitizers should be enabled.\n    @Option(\n        name: .customLong(\"sanitize\"),\n        help: \"Turn on runtime checks for erroneous behavior.\"\n    )\n    public var sanitizers: [Sanitizer] = []\n\n    public var enabledSanitizers: EnabledSanitizers {\n        EnabledSanitizers(Set(sanitizers))\n    }\n\n    @Flag(help: \"Determines whether to automatically index while building.\")\n    public var indexStoreMode: StoreMode = .autoIndexStore\n\n    /// Instead of building the target, perform the minimal amount of work to prepare it for indexing.\n    ///\n    /// This builds Swift module files for all dependencies but skips generation of object files. It also continues\n    /// building modules in the presence of compilation errors.\n    @Flag(name: .customLong(\"experimental-prepare-for-indexing\"), help: .hidden)\n    var prepareForIndexing: Bool = false\n\n    /// Don't pass `-experimental-lazy-typecheck` during preparation.\n    ///\n    /// This is intended as a workaround if lazy type checking is causing compiler crashes.\n    ///\n    /// Only applicable in conjunction with `--experimental-prepare-for-indexing`\n    @Flag(name: .customLong(\"experimental-prepare-for-indexing-no-lazy\"), help: .hidden)\n    var prepareForIndexingNoLazy: Bool = false\n\n    /// Hidden option to allow XCFrameworks on Linux\n    @Flag(\n        name: .customLong(\"experimental-xcframeworks-on-linux\"),\n        help: .hidden\n    )\n    public var enableXCFrameworksOnLinux: Bool = false\n\n    /// Whether to enable generation of `.swiftinterface`s alongside `.swiftmodule`s.\n    @Flag(name: .customLong(\"enable-parseable-module-interfaces\"))\n    public var shouldEnableParseableModuleInterfaces: Bool = false\n\n    /// The number of jobs for llbuild to start (aka the number of schedulerLanes)\n    @Option(name: .shortAndLong, help: \"The number of jobs to spawn in parallel during the build process.\")\n    public var jobs: UInt32 = UInt32(ProcessInfo.processInfo.activeProcessorCount)\n\n    /// Whether to use the integrated Swift driver rather than shelling out\n    /// to a separate process.\n    @Flag()\n    /// This flag is deprecated but cannot indicate so in Swift Argument Parser until https://github.com/apple/swift-argument-parser/issues/656\n    public var useIntegratedSwiftDriver: Bool = false\n\n    /// A flag that indicates this build should check whether targets only import\n    /// their explicitly-declared dependencies\n    @Option(help: \"Check that targets only import their explicitly declared dependencies.\")\n    public var explicitTargetDependencyImportCheck: TargetDependencyImportCheckingMode = .none\n\n    /// The build system to use.\n    @Option(\n        name: .customLong(\"build-system\"),\n        help: \"Specify the build system to use.\",\n    )\n    var _buildSystem: BuildSystemProvider.Kind = .native\n\n    /// The Debug Information Format to use.\n    @Option(name: .customLong(\"debug-info-format\", withSingleDash: true), help: \"The Debug Information Format to use.\")\n    public var debugInfoFormat: DebugInfoFormat = .dwarf\n\n    public var buildSystem: BuildSystemProvider.Kind {\n        switch self._buildSystem {\n        case .swiftbuild, .xcode:\n            return self._buildSystem\n        case .native:\n            // Maintain legacy behavior and force use of the Xcode build system if we want to build more than one arch.\n            return self.architectures.count > 1 ? .xcode : .native\n        }\n    }\n\n    /// Whether to enable test discovery on platforms without Objective-C runtime.\n    @Flag(help: .hidden)\n    public var enableTestDiscovery: Bool = false\n\n    /// Path of test entry point file to use, instead of synthesizing one or using `XCTMain.swift` in the package (if\n    /// present).\n    /// This implies `--enable-test-discovery`\n    @Option(\n        name: .customLong(\"experimental-test-entry-point-path\"),\n        help: .hidden\n    )\n    public var testEntryPointPath: AbsolutePath?\n\n    /// The lto mode to use if any.\n    @Option(\n        name: .customLong(\"experimental-lto-mode\"),\n        help: .hidden\n    )\n    public var linkTimeOptimizationMode: LinkTimeOptimizationMode?\n\n    @Flag(inversion: .prefixedEnableDisable, help: .hidden)\n    public var getTaskAllowEntitlement: Bool? = nil\n\n    // Whether to omit frame pointers\n    // this can be removed once the backtracer uses DWARF instead of frame pointers\n    @Flag(inversion: .prefixedNo, help: .hidden)\n    public var omitFramePointers: Bool? = nil\n\n    // Whether to enable task backtrace logging.\n    @Flag(name: .customLong(\"experimental-task-backtraces\"), help: .hidden)\n    public var enableTaskBacktraces: Bool = false\n\n    // Build dynamic library targets as frameworks (only available for Darwin targets and only when using the 'swiftbuild' build-system (currently used for tests).\n    @Flag(name: .customLong(\"experimental-build-dylibs-as-frameworks\"), help: .hidden )\n    public var shouldBuildDylibsAsFrameworks: Bool = false\n\n    /// Enable code size profiling by emitting SIL, LLVM IR, and optimization records.\n    @Flag(name: .customLong(\"experimental-enable-codesize-profile\"), help: \"Generate SIL, LLVM IR, and optimization record files for code size profiling.\")\n    public var enableCodesizeProfile: Bool = false\n\n    /// Directory for code size profiling output files (SIL, IR, optimization records).\n    @Option(name: .customLong(\"experimental-codesize-profile-output-dir\"), help: \"Directory to store code size profiling output files.\")\n    public var codesizeProfileOutputDirectory: String?\n\n    // @Flag works best when there is a default value present\n    // if true, false aren't enough and a third state is needed\n    // nil should not be the goto. Instead create an enum\n    public enum StoreMode: EnumerableFlag {\n        case autoIndexStore\n        case enableIndexStore\n        case disableIndexStore\n    }\n\n    public enum TargetDependencyImportCheckingMode: String, Codable, ExpressibleByArgument, CaseIterable {\n        case none\n        case warn\n        case error\n    }\n\n    /// See `BuildParameters.LinkTimeOptimizationMode` for details.\n    public enum LinkTimeOptimizationMode: String, Codable, ExpressibleByArgument {\n        /// See `BuildParameters.LinkTimeOptimizationMode.full` for details.\n        case full\n        /// See `BuildParameters.LinkTimeOptimizationMode.thin` for details.\n        case thin\n    }\n\n    /// See `BuildParameters.DebugInfoFormat` for details.\n    public enum DebugInfoFormat: String, Codable, ExpressibleByArgument, CaseIterable {\n        /// See `BuildParameters.DebugInfoFormat.dwarf` for details.\n        case dwarf\n        /// See `BuildParameters.DebugInfoFormat.codeview` for details.\n        case codeview\n        /// See `BuildParameters.DebugInfoFormat.none` for details.\n        case none\n    }\n}\n\npublic struct LinkerOptions: ParsableArguments {\n    public init() {}\n\n    @Flag(\n        name: .customLong(\"dead-strip\"),\n        inversion: .prefixedEnableDisable,\n        help: \"Determines whether the linker strips dead code.\"\n    )\n    public var linkerDeadStrip: Bool = true\n\n    /// Disables adding $ORIGIN/@loader_path to the rpath, useful when deploying\n    @Flag(name: .customLong(\"disable-local-rpath\"), help: \"Disable adding $ORIGIN/@loader_path to the rpath by default.\")\n    public var shouldDisableLocalRpath: Bool = false\n}\n\n/// Which testing libraries to use (and any related options.)\n@_spi(SwiftPMInternal)\npublic struct TestLibraryOptions: ParsableArguments {\n    public init() {}\n\n    /// Whether to enable support for XCTest (as explicitly specified by the user.)\n    ///\n    /// Callers will generally want to use ``enableXCTestSupport`` since it will\n    /// have the correct default value if the user didn't specify one.\n    @Flag(name: .customLong(\"xctest\"),\n          inversion: .prefixedEnableDisable,\n          help: \"Determines whether the build includes XCTest support.\")\n    public var explicitlyEnableXCTestSupport: Bool?\n\n    /// Whether to enable support for Swift Testing (as explicitly specified by the user.)\n    ///\n    /// Callers will generally want to use ``enableSwiftTestingLibrarySupport`` since it will\n    /// have the correct default value if the user didn't specify one.\n    @Flag(name: .customLong(\"swift-testing\"),\n          inversion: .prefixedEnableDisable,\n          help: \"Determines whether the build includes Swift Testing support.\")\n    public var explicitlyEnableSwiftTestingLibrarySupport: Bool?\n\n    /// Legacy experimental equivalent of ``explicitlyEnableSwiftTestingLibrarySupport``.\n    ///\n    /// This option will be removed in a future update.\n    @Flag(name: .customLong(\"experimental-swift-testing\"),\n          inversion: .prefixedEnableDisable,\n          help: .private)\n    public var explicitlyEnableExperimentalSwiftTestingLibrarySupport: Bool?\n\n    /// The common implementation for `isEnabled()` and `isExplicitlyEnabled()`.\n    ///\n    /// It is intentional that `isEnabled()` is not simply this function with a\n    /// default value for the `default` argument. There's no \"true\" default\n    /// value to use; it depends on the semantics the caller is interested in.\n    private func isEnabled(_ library: TestingLibrary, `default`: Bool, swiftCommandState: SwiftCommandState) -> Bool {\n        switch library {\n        case .xctest:\n            if let explicitlyEnableXCTestSupport {\n                return explicitlyEnableXCTestSupport\n            }\n            if let toolchain = try? swiftCommandState.getHostToolchain(),\n               toolchain.swiftSDK.xctestSupport == .supported {\n                return `default`\n            }\n            return false\n        case .swiftTesting:\n            return explicitlyEnableSwiftTestingLibrarySupport ?? explicitlyEnableExperimentalSwiftTestingLibrarySupport ?? `default`\n        }\n    }\n\n    /// Test whether or not a given library is enabled.\n    public func isEnabled(_ library: TestingLibrary, swiftCommandState: SwiftCommandState) -> Bool {\n        isEnabled(library, default: true, swiftCommandState: swiftCommandState)\n    }\n\n    /// Test whether or not a given library was explicitly enabled by the developer.\n    public func isExplicitlyEnabled(_ library: TestingLibrary, swiftCommandState: SwiftCommandState) -> Bool {\n        isEnabled(library, default: false, swiftCommandState: swiftCommandState)\n    }\n}\n\npublic struct TraitOptions: ParsableArguments {\n    public init() {}\n\n    /// The traits to enable for the package.\n    @Option(\n        name: .customLong(\"traits\"),\n        help: \"Enable the specified traits of the package. Specify multiple traits as a comma-separated list, for example: `--traits Trait1,Trait2`. When enabling specific traits, the default traits must also be explicitly enabled by passing `defaults` to this option.\"\n    )\n    package var _enabledTraits: String?\n\n    /// The set of enabled traits for the package.\n    public var enabledTraits: Set<String>? {\n        self._enabledTraits.flatMap { Set($0.components(separatedBy: \",\")) }\n    }\n\n    /// Enables all traits of the package.\n    @Flag(\n        name: .customLong(\"enable-all-traits\"),\n        help: \"Enable all traits of the package.\"\n    )\n    public var enableAllTraits: Bool = false\n\n    /// Disables all default traits of the package.\n    @Flag(\n        name: .customLong(\"disable-default-traits\"),\n        help: \"Disable all default traits of the package.\"\n    )\n    public var disableDefaultTraits: Bool = false\n}\n\nextension TraitConfiguration {\n    public init(traitOptions: TraitOptions) {\n        var enabledTraits = traitOptions.enabledTraits\n        if traitOptions.disableDefaultTraits {\n            // If there are no enabled traits specified we can disable the\n            // default trait by passing in an empty set. Otherwise the enabling specific traits\n            // requires the user to pass the default as well.\n            enabledTraits = enabledTraits ?? []\n        }\n        self.init(\n            enabledTraits: enabledTraits,\n            enableAllTraits: traitOptions.enableAllTraits\n        )\n    }\n}\n\npublic struct SBOMOptions: ParsableArguments {\n    public init() {}\n\n    /// SBOM specification(s) to generate.\n    @Option(\n        name: .customLong(\"sbom-spec\"),\n        help: ArgumentHelp(\"Set the SBOM specification and generate an SBOM.\")\n    )\n    package var _sbomSpecs: [SBOMModel.Spec] = []\n\n    /// Directory path to generate SBOM(s) in.\n    @Option(\n        name: .customLong(\"sbom-output-dir\"),\n        help: ArgumentHelp(\"The absolute or relative directory path to generate the SBOM(s) in. Must be used with --sbom-spec. (default: <scratch_path>/sboms).\"),\n        completion: .directory\n    )\n    package var _sbomDirectory: AbsolutePath?\n\n    /// Filter SBOM components and dependencies by entity.\n    @Option(\n        name: .customLong(\"sbom-filter\"),\n        help: ArgumentHelp(\"Filter the SBOM components and dependencies by products and/or packages. Must be used with --sbom-spec.\")\n    )\n    package var _sbomFilter: SBOMModel.Filter? = nil\n\n    /// Whether to treat SBOM generation errors as warnings\n    @Flag(\n        name: .customLong(\"sbom-warning-only\"),\n        help: ArgumentHelp(\"Treat SBOM generation errors as warnings. Must be used with --sbom-spec. (default: false).\")\n    )\n    package var _sbomWarningOnly: Bool = false\n\n    // MARK: - Computed properties with environment variable support\n\n    /// SBOM specifications with environment variable fallback. CLI flag takes precedence.\n    /// Throws an error if the environment variable contains an invalid value.\n    package var sbomSpecs: [SBOMModel.Spec] {\n        get throws {\n            if !_sbomSpecs.isEmpty {\n                return _sbomSpecs\n            }\n            if let envSpecs = SPMBuildCore.ConfigurableEnvVar.SWIFTPM_BUILD_SBOM_SPEC.getEnvVar() {\n                let specStrings = envSpecs.components(separatedBy: \",\").map { $0.trimmingCharacters(in: .whitespaces) }\n                var specs: Set<SBOMModel.Spec> = []\n                for specString in specStrings {\n                    guard let spec = SBOMModel.Spec(rawValue: specString) else {\n                        throw SBOMModel.SBOMCommandError.invalidSpecValue(value: specString)\n                    }\n                    specs.insert(spec)\n                }\n                if !specs.isEmpty {\n                    return specs.sorted { $0.rawValue < $1.rawValue }\n                }\n            }\n            return []\n        }\n    }\n\n    /// SBOM directory with environment variable fallback. CLI flag takes precedence.\n    package var sbomDirectory: AbsolutePath? {\n        if let cmdLineDir = _sbomDirectory {\n            return cmdLineDir\n        }\n        if let envDir = SPMBuildCore.ConfigurableEnvVar.SWIFTPM_BUILD_SBOM_OUTPUT_DIR.getEnvVar() {\n            guard let path = AbsolutePath(argument: envDir) else {\n                return nil\n            }\n            return path\n        }\n        return nil\n    }\n\n    /// SBOM filter with environment variable fallback. CLI flag takes precedence.\n    /// Throws an error if the environment variable contains an invalid value.\n    package var sbomFilter: SBOMModel.Filter {\n        get throws {\n            if let cliFilter = _sbomFilter {\n                return cliFilter\n            }\n            if let envFilter = SPMBuildCore.ConfigurableEnvVar.SWIFTPM_BUILD_SBOM_FILTER.getEnvVar() {\n                guard let filter = SBOMModel.Filter(rawValue: envFilter) else {\n                    throw SBOMModel.SBOMCommandError.invalidFilterValue(value: envFilter)\n                }\n                return filter\n            }\n            return .all\n        }\n    }\n\n    /// SBOM warning-only mode with environment variable fallback. CLI flag takes precedence.\n    package var sbomWarningOnly: Bool {\n        if _sbomWarningOnly {\n            return true\n        }\n        if let envWarningOnly = SPMBuildCore.ConfigurableEnvVar.SWIFTPM_BUILD_SBOM_WARNING_ONLY.getEnvVar() {\n            let lowercased = envWarningOnly.lowercased()\n            return ![\"false\", \"0\", \"no\"].contains(lowercased)\n        }\n        return false\n    }\n}\n\n// MARK: - Extensions\n\nextension BuildConfiguration {\n    public init?(argument: String) {\n        self.init(rawValue: argument)\n    }\n}\n\nextension AbsolutePath {\n    public init?(argument: String) {\n        if let cwd = localFileSystem.currentWorkingDirectory {\n            guard let path = try? AbsolutePath(validating: argument, relativeTo: cwd) else {\n                return nil\n            }\n            self = path\n        } else {\n            guard let path = try? AbsolutePath(validating: argument) else {\n                return nil\n            }\n            self = path\n        }\n    }\n\n    public static var defaultCompletionKind: CompletionKind {\n        // This type is most commonly used to select a directory, not a file.\n        // Specify '.file()' in an argument declaration when necessary.\n        .directory\n    }\n}\n\nextension WorkspaceConfiguration.CheckingMode {\n    public init?(argument: String) {\n        self.init(rawValue: argument)\n    }\n}\n\nextension Sanitizer {\n    public init?(argument: String) {\n        if let sanitizer = Sanitizer(rawValue: argument) {\n            self = sanitizer\n            return\n        }\n\n        for sanitizer in Sanitizer.allCases where sanitizer.shortName == argument {\n            self = sanitizer\n            return\n        }\n\n        return nil\n    }\n\n    /// All sanitizer options in a comma separated string\n    fileprivate static var formattedValues: String {\n        Sanitizer.allCases.map(\\.rawValue).joined(separator: \", \")\n    }\n}\n\nextension PackageIdentity {\n    public init?(argument: String) {\n        self = .plain(argument)\n    }\n}\n\nextension URL {\n    public init?(argument: String) {\n        self.init(string: argument)\n    }\n}\n\nextension BuildConfiguration: ExpressibleByArgument {}\nextension AbsolutePath: ExpressibleByArgument {}\nextension WorkspaceConfiguration.CheckingMode: ExpressibleByArgument {}\nextension Sanitizer: ExpressibleByArgument {}\nextension BuildSystemProvider.Kind: ExpressibleByArgument {}\nextension Version: @retroactive ExpressibleByArgument {}\nextension PackageIdentity: ExpressibleByArgument {}\nextension URL: @retroactive ExpressibleByArgument {}\n"
  },
  {
    "path": "Sources/CoreCommands/SwiftCommandObservabilityHandler.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\nimport Dispatch\nimport PackageModel\n\nimport protocol TSCBasic.OutputByteStream\nimport class TSCBasic.TerminalController\nimport class TSCBasic.ThreadSafeOutputByteStream\n\nimport class TSCBasic.BufferedOutputByteStream\nimport class TSCBasic.LocalFileOutputByteStream\nimport class TSCUtility.MultiLineNinjaProgressAnimation\nimport class TSCUtility.NinjaProgressAnimation\nimport protocol TSCUtility.ProgressAnimationProtocol\n\npublic struct SwiftCommandObservabilityHandler: ObservabilityHandlerProvider {\n    private let outputHandler: OutputHandler\n\n    public var diagnosticsHandler: DiagnosticsHandler {\n        self.outputHandler\n    }\n\n    /// Initializes a new observability handler provider.\n    /// - Parameters:\n    ///   - outputStream: an instance of a stream used for output.\n    ///   - logLevel: the lowest severity of diagnostics that this handler will forward to `outputStream`. Diagnostics\n    ///   emitted below this level will be ignored.\n\n    public init(outputStream: OutputByteStream, logLevel: Basics.Diagnostic.Severity, colorDiagnostics: Bool = true) {\n        let threadSafeOutputByteStream = outputStream as? ThreadSafeOutputByteStream ??\n            ThreadSafeOutputByteStream(outputStream)\n        self.outputHandler = OutputHandler(\n            logLevel: logLevel,\n            outputStream: threadSafeOutputByteStream,\n            colorDiagnostics: colorDiagnostics\n        )\n    }\n\n    // for raw output reporting\n    func print(_ output: String, condition: OutputCondition) {\n        self.outputHandler.print(output, condition: condition)\n    }\n\n    // for raw progress reporting\n    func progress(step: Int64, total: Int64, description: String?) {\n        self.outputHandler.progress(step: step, total: total, description: description)\n    }\n\n    // FIXME: deprecate this one we are further along refactoring the call sites that use it\n    var outputStream: OutputByteStream {\n        self.outputHandler.outputStream\n    }\n\n    // prompt for user input\n    func prompt(_ message: String, completion: (String?) -> Void) {\n        self.outputHandler.prompt(message: message, completion: completion)\n    }\n\n    public func wait(timeout: DispatchTime) {\n        self.outputHandler.wait(timeout: timeout)\n    }\n\n    struct OutputHandler {\n        private let logLevel: Diagnostic.Severity\n        internal let outputStream: ThreadSafeOutputByteStream\n        private let writer: InteractiveWriter\n        private let progressAnimation: ProgressAnimationProtocol\n        private let colorDiagnostics: Bool\n        private let queue = DispatchQueue(label: \"org.swift.swiftpm.tools-output\")\n        private let sync = DispatchGroup()\n\n        init(logLevel: Diagnostic.Severity, outputStream: ThreadSafeOutputByteStream, colorDiagnostics: Bool) {\n            self.logLevel = logLevel\n            self.outputStream = outputStream\n            self.writer = InteractiveWriter(stream: outputStream)\n            self.progressAnimation = ProgressAnimation.ninja(\n                stream: self.outputStream,\n                verbose: self.logLevel.isVerbose\n            )\n            self.colorDiagnostics = colorDiagnostics\n        }\n\n        func handleDiagnostic(scope: ObservabilityScope, diagnostic: Basics.Diagnostic) {\n            self.queue.async(group: self.sync) {\n                guard diagnostic.severity >= self.logLevel else {\n                    return\n                }\n\n                // TODO: do something useful with scope\n                var output: String\n\n                let prefix = diagnostic.severity.logLabel\n                let color = self.colorDiagnostics ? diagnostic.severity.color : .noColor\n                let bold = self.colorDiagnostics ? diagnostic.severity.isBold : false\n\n                output = self.writer.format(prefix, inColor: color, bold: bold)\n                if let diagnosticPrefix = diagnostic.metadata?.diagnosticPrefix {\n                    output += diagnosticPrefix\n                    output += \": \"\n                }\n\n                output += diagnostic.message\n                self.write(output)\n            }\n        }\n\n        // for raw output reporting\n        func print(_ output: String, condition: OutputCondition) {\n            self.queue.async(group: self.sync) {\n                switch condition {\n                case .always:\n                    self.write(output)\n                case .onlyWhenVerbose:\n                    guard self.logLevel.isVerbose else { return }\n                    self.write(output)\n                }\n            }\n        }\n\n        // for raw progress reporting\n        func progress(step: Int64, total: Int64, description: String?) {\n            self.queue.async(group: self.sync) {\n                self.progressAnimation.update(\n                    step: step > Int.max ? Int.max : Int(step),\n                    total: total > Int.max ? Int.max : Int(total),\n                    text: description ?? \"\"\n                )\n            }\n        }\n\n        // to read input from user\n        func prompt(message: String, completion: (String?) -> Void) {\n            guard self.outputStream.isTTY else {\n                return completion(.none)\n            }\n            let answer = self.queue.sync {\n                self.progressAnimation.clear()\n                self.outputStream.write(message.utf8)\n                self.outputStream.flush()\n                return readLine(strippingNewline: true)\n            }\n            completion(answer)\n        }\n\n        func wait(timeout: DispatchTime) {\n            switch self.sync.wait(timeout: timeout) {\n            case .success:\n                break\n            case .timedOut:\n                self.write(\"warning: failed to process all diagnostics\")\n            }\n        }\n\n        private func write(_ output: String) {\n            self.progressAnimation.clear()\n            var output = output\n            if !output.hasSuffix(\"\\n\") {\n                output += \"\\n\"\n            }\n            self.writer.write(output)\n        }\n    }\n}\n\nextension SwiftCommandObservabilityHandler.OutputHandler: @unchecked Sendable {}\nextension SwiftCommandObservabilityHandler.OutputHandler: DiagnosticsHandler {}\n\n/// This type is used to write on the underlying stream.\n///\n/// If underlying stream is a not tty, the string will be written in without any\n/// formatting.\nprivate struct InteractiveWriter {\n    /// The terminal controller, if present.\n    let term: TerminalController?\n\n    /// The output byte stream reference.\n    let stream: OutputByteStream\n\n    /// Create an instance with the given stream.\n    init(stream: OutputByteStream) {\n        self.term = TerminalController(stream: stream)\n        self.stream = stream\n    }\n\n    /// Write the string to the contained terminal or stream.\n    func write(_ string: String, inColor color: TerminalController.Color = .noColor, bold: Bool = false) {\n        if let term {\n            term.write(string, inColor: color, bold: bold)\n        } else {\n            string.write(to: stream)\n            stream.flush()\n        }\n    }\n\n    func format(_ string: String, inColor color: TerminalController.Color = .noColor, bold: Bool = false) -> String {\n        if let term {\n            return term.wrap(string, inColor: color, bold: bold)\n        } else {\n            return string\n        }\n    }\n}\n\n// FIXME: this is for backwards compatibility with existing diagnostics printing format\n// we should remove this as we make use of the new scope and metadata to provide better contextual information\nextension ObservabilityMetadata {\n    fileprivate var diagnosticPrefix: String? {\n        if let packageIdentity {\n            return \"'\\(packageIdentity)'\"\n        } else {\n            return .none\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/CoreCommands/SwiftCommandState.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport ArgumentParser\nimport Basics\nimport Dispatch\nimport class Foundation.NSLock\nimport class Foundation.ProcessInfo\nimport PackageFingerprint\nimport PackageGraph\nimport PackageLoading\n@_spi(SwiftPMInternal)\nimport PackageModel\nimport PackageRegistry\nimport PackageSigning\nimport SourceControl\nimport SPMBuildCore\nimport Workspace\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly\n@_spi(SwiftPMInternal)\nimport DriverSupport\n#else\n@_spi(SwiftPMInternal)\nimport DriverSupport\n#endif\n\n#if canImport(WinSDK)\nimport WinSDK\n#elseif canImport(Darwin)\nimport Darwin\n#elseif canImport(Glibc)\nimport Glibc\n#elseif canImport(Musl)\nimport Musl\n#elseif canImport(Bionic)\nimport Bionic\n#endif\n\nimport class Basics.AsyncProcess\nimport func TSCBasic.exec\nimport class TSCBasic.FileLock\nimport enum TSCBasic.JSON\nimport protocol TSCBasic.OutputByteStream\nimport enum TSCBasic.ProcessEnv\nimport struct TSCBasic.SHA256\nimport enum TSCBasic.ProcessLockError\nimport var TSCBasic.stderrStream\nimport class TSCBasic.TerminalController\nimport class TSCBasic.ThreadSafeOutputByteStream\nimport enum TSCBasic.SystemError\n\nimport var TSCUtility.verbosity\n\ntypealias Diagnostic = Basics.Diagnostic\n\npublic struct ToolWorkspaceConfiguration {\n    let shouldInstallSignalHandlers: Bool\n    let wantsMultipleTestProducts: Bool\n    let wantsREPLProduct: Bool\n\n    public init(\n        shouldInstallSignalHandlers: Bool = true,\n        wantsMultipleTestProducts: Bool = false,\n        wantsREPLProduct: Bool = false\n    ) {\n        self.shouldInstallSignalHandlers = shouldInstallSignalHandlers\n        self.wantsMultipleTestProducts = wantsMultipleTestProducts\n        self.wantsREPLProduct = wantsREPLProduct\n    }\n}\n\npublic typealias WorkspaceDelegateProvider = (\n    _ observabilityScope: ObservabilityScope,\n    _ outputHandler: @escaping (String, OutputCondition) -> Void,\n    _ progressHandler: @escaping (Int64, Int64, String?) -> Void,\n    _ inputHandler: @escaping (String, (String?) -> Void) -> Void\n) -> WorkspaceDelegate\n\npublic typealias WorkspaceLoaderProvider = (_ fileSystem: FileSystem, _ observabilityScope: ObservabilityScope)\n    -> WorkspaceLoader\n\npublic protocol _SwiftCommand {\n    var globalOptions: GlobalOptions { get }\n    var toolWorkspaceConfiguration: ToolWorkspaceConfiguration { get }\n    var workspaceDelegateProvider: WorkspaceDelegateProvider { get }\n    var workspaceLoaderProvider: WorkspaceLoaderProvider { get }\n    func buildSystemProvider(_ swiftCommandState: SwiftCommandState) throws -> BuildSystemProvider\n\n    // If a packagePath is specificed, this indicates that the command allows\n    // creating the directory if it doesn't exist.\n    var createPackagePath: Bool { get }\n}\n\nextension _SwiftCommand {\n    public var toolWorkspaceConfiguration: ToolWorkspaceConfiguration {\n        .init()\n    }\n\n    public var createPackagePath: Bool {\n        return false\n    }\n}\n\npublic protocol SwiftCommand: ParsableCommand, _SwiftCommand {\n    func run(_ swiftCommandState: SwiftCommandState) throws\n}\n\nextension SwiftCommand {\n    public static var _errorLabel: String { \"error\" }\n\n    public func run() throws {\n        let swiftCommandState = try SwiftCommandState(\n            options: globalOptions,\n            toolWorkspaceConfiguration: self.toolWorkspaceConfiguration,\n            workspaceDelegateProvider: self.workspaceDelegateProvider,\n            workspaceLoaderProvider: self.workspaceLoaderProvider,\n            createPackagePath: self.createPackagePath\n        )\n\n        // We use this to attempt to catch misuse of the locking APIs since we only release the lock from here.\n        swiftCommandState.setNeedsLocking()\n\n        swiftCommandState.buildSystemProvider = try buildSystemProvider(swiftCommandState)\n        var toolError: Error? = .none\n        do {\n            try self.run(swiftCommandState)\n            if swiftCommandState.observabilityScope.errorsReported || swiftCommandState.executionStatus == .failure {\n                throw ExitCode.failure\n            }\n        } catch {\n            toolError = error\n        }\n\n        swiftCommandState.releaseLockIfNeeded()\n\n        // wait for all observability items to process\n        swiftCommandState.waitForObservabilityEvents(timeout: .now() + 5)\n\n        if let toolError {\n            throw toolError\n        }\n    }\n}\n\npublic protocol AsyncSwiftCommand: AsyncParsableCommand, _SwiftCommand {\n    func run(_ swiftCommandState: SwiftCommandState) async throws\n}\n\nextension AsyncSwiftCommand {\n    public static var _errorLabel: String { \"error\" }\n\n    // FIXME: It doesn't seem great to have this be duplicated with `SwiftCommand`.\n    public func run() async throws {\n        let swiftCommandState = try SwiftCommandState(\n            options: globalOptions,\n            toolWorkspaceConfiguration: self.toolWorkspaceConfiguration,\n            workspaceDelegateProvider: self.workspaceDelegateProvider,\n            workspaceLoaderProvider: self.workspaceLoaderProvider,\n            createPackagePath: self.createPackagePath\n        )\n\n        // We use this to attempt to catch misuse of the locking APIs since we only release the lock from here.\n        swiftCommandState.setNeedsLocking()\n\n        swiftCommandState.buildSystemProvider = try buildSystemProvider(swiftCommandState)\n        var toolError: Error? = .none\n        do {\n            try await self.run(swiftCommandState)\n            if swiftCommandState.observabilityScope.errorsReported || swiftCommandState.executionStatus == .failure {\n                throw ExitCode.failure\n            }\n        } catch {\n            toolError = error\n        }\n\n        swiftCommandState.releaseLockIfNeeded()\n\n        // wait for all observability items to process\n        swiftCommandState.waitForObservabilityEvents(timeout: .now() + 5)\n\n        if let toolError {\n            throw toolError\n        }\n    }\n}\n\npublic final class SwiftCommandState {\n    #if os(Windows)\n    // unfortunately this is needed for C callback handlers used by Windows shutdown handler\n    static var cancellator: Cancellator?\n    #endif\n\n    /// The original working directory.\n    public let originalWorkingDirectory: AbsolutePath\n\n    /// The options of this tool.\n    public let options: GlobalOptions\n\n    /// Path to the root package directory, nil if manifest is not found.\n    private let packageRoot: AbsolutePath?\n\n    /// Helper function to get package root or throw error if it is not found.\n    public func getPackageRoot() throws -> AbsolutePath {\n        guard let packageRoot else {\n            throw StringError(\"Could not find \\(Manifest.filename) in this directory or any of its parent directories.\")\n        }\n        return packageRoot\n    }\n\n    /// Get the current workspace root object.\n    public func getWorkspaceRoot() throws -> PackageGraphRootInput {\n        let packages: [AbsolutePath]\n\n        if let workspace = options.locations.multirootPackageDataFile {\n            packages = try self.workspaceLoaderProvider(self.fileSystem, self.observabilityScope)\n                .load(workspace: workspace)\n        } else {\n            packages = try [self.getPackageRoot()]\n        }\n\n        return PackageGraphRootInput(packages: packages, traitConfiguration: self.traitConfiguration)\n    }\n\n    /// Scratch space (.build) directory.\n    public let scratchDirectory: AbsolutePath\n\n    /// Path to the shared security directory\n    public let sharedSecurityDirectory: AbsolutePath\n\n    /// Path to the shared cache directory\n    public let sharedCacheDirectory: AbsolutePath\n\n    /// Path to the shared configuration directory\n    public let sharedConfigurationDirectory: AbsolutePath\n    \n    /// Path to the package manager's own resources directory.\n    public let packageManagerResourcesDirectory: AbsolutePath?\n\n    /// Path to the cross-compilation Swift SDKs directory.\n    public let sharedSwiftSDKsDirectory: AbsolutePath\n\n    /// Cancellator to handle cancellation of outstanding work when handling SIGINT\n    public let cancellator: Cancellator\n\n    /// The execution status of the tool.\n    public var executionStatus: ExecutionStatus = .success\n\n    /// Holds the currently active workspace.\n    ///\n    /// It is not initialized in init() because for some of the commands like `package init`, usage etc,\n    /// a workspace is not needed. In fact it would be an error to ask for the workspace object\n    /// for `package init` because the manifest file should *not* be present.\n    private var _workspace: Workspace?\n    private var _workspaceDelegate: WorkspaceDelegate?\n\n    private let observabilityHandler: SwiftCommandObservabilityHandler\n\n    /// The observability scope to emit diagnostics event on\n    public let observabilityScope: ObservabilityScope\n\n    /// The min severity at which to log diagnostics\n    public let logLevel: Basics.Diagnostic.Severity\n\n    // should use sandbox on external subcommands\n    public var shouldDisableSandbox: Bool\n\n    /// The file system in use\n    public let fileSystem: FileSystem\n\n    /// Provider which can create a `WorkspaceDelegate` if needed.\n    private let workspaceDelegateProvider: WorkspaceDelegateProvider\n\n    /// Provider which can create a `WorkspaceLoader` if needed.\n    private let workspaceLoaderProvider: WorkspaceLoaderProvider\n\n    private let toolWorkspaceConfiguration: ToolWorkspaceConfiguration\n\n    fileprivate var buildSystemProvider: BuildSystemProvider?\n\n    private let environment: Environment\n\n    private let hostTriple: Basics.Triple?\n\n    private let targetInfo: JSON?\n\n    package var preferredBuildConfiguration = BuildConfiguration.debug\n\n    package let traitConfiguration: TraitConfiguration\n\n    /// Create an instance of this tool.\n    ///\n    /// - parameter options: The command line options to be passed to this tool.\n    public convenience init(\n        options: GlobalOptions,\n        toolWorkspaceConfiguration: ToolWorkspaceConfiguration = .init(),\n        workspaceDelegateProvider: @escaping WorkspaceDelegateProvider,\n        workspaceLoaderProvider: @escaping WorkspaceLoaderProvider,\n        createPackagePath: Bool\n    ) throws {\n        // output from background activities goes to stderr, this includes diagnostics and output from build operations,\n        // package resolution that take place as part of another action\n        // CLI commands that have user facing output, use stdout directly to emit the final result\n        // this means that the build output from \"swift build\" goes to stdout\n        // but the build output from \"swift test\" goes to stderr, while the tests output go to stdout\n        try self.init(\n            outputStream: TSCBasic.stderrStream,\n            options: options,\n            toolWorkspaceConfiguration: toolWorkspaceConfiguration,\n            workspaceDelegateProvider: workspaceDelegateProvider,\n            workspaceLoaderProvider: workspaceLoaderProvider,\n            createPackagePath: createPackagePath\n        )\n    }\n\n    // marked internal for testing\n    init(\n        outputStream: OutputByteStream,\n        options: GlobalOptions,\n        toolWorkspaceConfiguration: ToolWorkspaceConfiguration,\n        workspaceDelegateProvider: @escaping WorkspaceDelegateProvider,\n        workspaceLoaderProvider: @escaping WorkspaceLoaderProvider,\n        createPackagePath: Bool,\n        hostTriple: Basics.Triple? = nil,\n        targetInfo: JSON? = nil,\n        fileSystem: any FileSystem = localFileSystem,\n        environment: Environment = .current\n    ) throws {\n        self.hostTriple = hostTriple\n        self.targetInfo = targetInfo\n        self.fileSystem = fileSystem\n        self.environment = environment\n        // first, bootstrap the observability system\n        self.logLevel = options.logging.logLevel\n        self.observabilityHandler = SwiftCommandObservabilityHandler(\n            outputStream: outputStream,\n            logLevel: self.logLevel,\n            colorDiagnostics: options.logging.colorDiagnostics\n        )\n        let observabilitySystem = ObservabilitySystem(self.observabilityHandler)\n        let observabilityScope = observabilitySystem.topScope\n        self.observabilityScope = observabilityScope\n        self.shouldDisableSandbox = options.security.shouldDisableSandbox\n        self.toolWorkspaceConfiguration = toolWorkspaceConfiguration\n        self.workspaceDelegateProvider = workspaceDelegateProvider\n        self.workspaceLoaderProvider = workspaceLoaderProvider\n\n        let cancellator = Cancellator(observabilityScope: self.observabilityScope)\n\n        // Capture the original working directory ASAP.\n        guard let cwd = self.fileSystem.currentWorkingDirectory else {\n            self.observabilityScope.emit(error: \"couldn't determine the current working directory\")\n            throw ExitCode.failure\n        }\n        self.originalWorkingDirectory = cwd\n\n        do {\n            try Self.postprocessArgParserResult(options: options, observabilityScope: self.observabilityScope)\n            self.options = options\n\n            // Honor package-path option is provided.\n            try Self.chdirIfNeeded(\n                packageDirectory: self.options.locations.packageDirectory,\n                createPackagePath: createPackagePath\n            )\n        } catch {\n            self.observabilityScope.emit(error)\n            throw ExitCode.failure\n        }\n\n        if toolWorkspaceConfiguration.shouldInstallSignalHandlers {\n            cancellator.installSignalHandlers()\n        }\n        self.cancellator = cancellator\n\n        // Create local variables to use while finding build path to avoid capture self before init error.\n        let packageRoot = findPackageRoot(fileSystem: fileSystem)\n\n        self.packageRoot = packageRoot\n        self.scratchDirectory =\n            try BuildSystemUtilities.getEnvBuildPath(workingDir: cwd) ??\n            options.locations.scratchDirectory ??\n            (packageRoot ?? cwd).appending(\".build\")\n\n        // make sure common directories are created\n        self.sharedSecurityDirectory = try getSharedSecurityDirectory(options: options, fileSystem: fileSystem)\n        self.sharedConfigurationDirectory = try getSharedConfigurationDirectory(\n            options: options,\n            fileSystem: fileSystem\n        )\n        self.sharedCacheDirectory = try getSharedCacheDirectory(options: options, fileSystem: fileSystem)\n        if options.locations.deprecatedSwiftSDKsDirectory != nil {\n            self.observabilityScope.emit(\n                warning: \"`--experimental-swift-sdks-path` is deprecated and will be removed in a future version of SwiftPM. Use `--swift-sdks-path` instead.\"\n            )\n        }\n        \n        if let packageManagerResourcesDirectory = options.locations.packageManagerResourcesDirectory {\n            self.packageManagerResourcesDirectory = packageManagerResourcesDirectory\n        } else if let cwd = localFileSystem.currentWorkingDirectory {\n            self.packageManagerResourcesDirectory = try? AbsolutePath(validating: CommandLine.arguments[0], relativeTo: cwd)\n                .parentDirectory.parentDirectory.appending(components: [\"share\", \"pm\"])\n        } else {\n            self.packageManagerResourcesDirectory = try? AbsolutePath(validating: CommandLine.arguments[0])\n                .parentDirectory.parentDirectory.appending(components: [\"share\", \"pm\"])\n        }\n        \n        self.sharedSwiftSDKsDirectory = try fileSystem.getSharedSwiftSDKsDirectory(\n            explicitDirectory: options.locations.swiftSDKsDirectory ?? options.locations.deprecatedSwiftSDKsDirectory\n        )\n\n        // Set the trait configuration from user-passed trait options.\n        self.traitConfiguration = .init(traitOptions: options.traits)\n\n        // set global process logging handler\n        AsyncProcess.loggingHandler = { self.observabilityScope.emit(debug: $0) }\n    }\n\n    static func postprocessArgParserResult(options: GlobalOptions, observabilityScope: ObservabilityScope) throws {\n        if options.locations.multirootPackageDataFile != nil {\n            observabilityScope.emit(.unsupportedFlag(\"--multiroot-data-file\"))\n        }\n\n        if !options.build.architectures.isEmpty && options.build.customCompileTriple != nil {\n            observabilityScope.emit(.mutuallyExclusiveArgumentsError(arguments: [\"--arch\", \"--triple\"]))\n        }\n\n        // --enable-test-discovery should never be called on darwin based platforms\n        #if canImport(Darwin)\n        if options.build.enableTestDiscovery {\n            observabilityScope\n                .emit(\n                    warning: \"'--enable-test-discovery' option is deprecated; tests are automatically discovered on all platforms\"\n                )\n        }\n        #endif\n\n        if options.caching.shouldDisableManifestCaching {\n            observabilityScope\n                .emit(\n                    warning: \"'--disable-package-manifest-caching' option is deprecated; use '--manifest-caching' instead\"\n                )\n        }\n\n        if let _ = options.security.netrcFilePath, options.security.netrc == false {\n            observabilityScope.emit(.mutuallyExclusiveArgumentsError(arguments: [\"--disable-netrc\", \"--netrc-file\"]))\n        }\n\n        if !options.build._deprecated_manifestFlags.isEmpty {\n            observabilityScope.emit(warning: \"'-Xmanifest' option is deprecated; use '-Xbuild-tools-swiftc' instead\")\n        }\n\n        if options.build.enableTaskBacktraces {\n            // Task backtraces require at least verbose output to be logged\n            if !options.logging.verbose && !options.logging.veryVerbose {\n                observabilityScope.emit(\n                    warning: \"'--experimental-task-backtraces' requires '--verbose' or '--very-verbose'\"\n                )\n            }\n\n            // Task backtraces are only supported by the swiftbuild build system\n            if options.build.buildSystem != .swiftbuild {\n                observabilityScope.emit(\n                    warning: \"'--experimental-task-backtraces' is only supported when using '--build-system swiftbuild'\"\n                )\n            }\n        }\n    }\n\n    func waitForObservabilityEvents(timeout: DispatchTime) {\n        self.observabilityHandler.wait(timeout: timeout)\n    }\n\n    /// Returns the currently active workspace.\n    public func getActiveWorkspace(emitDeprecatedConfigurationWarning: Bool = false, enableAllTraits: Bool = false) throws -> Workspace {\n        if var workspace = _workspace {\n            // if we decide to override the trait configuration, we can resolve accordingly for\n            // calls like createSymbolGraphForPlugin.\n            if enableAllTraits {\n                workspace = workspace.updateConfiguration(with: .enableAllTraits)\n            }\n            return workspace\n        }\n\n        // Before creating the workspace, we need to acquire a lock on the build directory.\n        try self.acquireLockIfNeeded()\n\n        if self.options.resolver.skipDependencyUpdate {\n            self.observabilityScope\n                .emit(warning: \"'--skip-update' option is deprecated and will be removed in a future release\")\n        }\n\n        let delegate = self.workspaceDelegateProvider(\n            self.observabilityScope,\n            self.observabilityHandler.print,\n            self.observabilityHandler.progress,\n            self.observabilityHandler.prompt\n        )\n        let workspace = try Workspace(\n            fileSystem: self.fileSystem,\n            location: .init(\n                scratchDirectory: self.scratchDirectory,\n                editsDirectory: self.getEditsDirectory(),\n                resolvedVersionsFile: self.getResolvedVersionsFile(),\n                localConfigurationDirectory: self.getLocalConfigurationDirectory(),\n                sharedConfigurationDirectory: self.sharedConfigurationDirectory,\n                sharedSecurityDirectory: self.sharedSecurityDirectory,\n                sharedCacheDirectory: self.sharedCacheDirectory,\n                emitDeprecatedConfigurationWarning: emitDeprecatedConfigurationWarning\n            ),\n            authorizationProvider: self.getAuthorizationProvider(),\n            registryAuthorizationProvider: self.getRegistryAuthorizationProvider(),\n            configuration: .init(\n                skipDependenciesUpdates: options.resolver.skipDependencyUpdate,\n                prefetchBasedOnResolvedFile: options.resolver.shouldEnableResolverPrefetching,\n                shouldCreateMultipleTestProducts: toolWorkspaceConfiguration.wantsMultipleTestProducts || options.build.buildSystem.shouldCreateMultipleTestProducts,\n                createREPLProduct: toolWorkspaceConfiguration.wantsREPLProduct,\n                additionalFileRules: options.build.buildSystem.additionalFileRules,\n                sharedDependenciesCacheEnabled: self.options.caching.useDependenciesCache,\n                fingerprintCheckingMode: self.options.security.fingerprintCheckingMode,\n                signingEntityCheckingMode: self.options.security.signingEntityCheckingMode,\n                skipSignatureValidation: !self.options.security.signatureValidation,\n                sourceControlToRegistryDependencyTransformation: self.options.resolver\n                    .sourceControlToRegistryDependencyTransformation.workspaceConfiguration,\n                defaultRegistry: self.options.resolver.defaultRegistryURL.flatMap {\n                    // TODO: should supportsAvailability be a flag as well?\n                    .init(url: $0, supportsAvailability: true)\n                },\n                manifestImportRestrictions: .none,\n                usePrebuilts: self.options.caching.usePrebuilts,\n                prebuiltsDownloadURL: options.caching.prebuiltsDownloadURL,\n                prebuiltsRootCertPath: options.caching.prebuiltsRootCertPath,\n                pruneDependencies: self.options.resolver.pruneDependencies,\n                traitConfiguration: self.traitConfiguration\n            ),\n            cancellator: self.cancellator,\n            initializationWarningHandler: { self.observabilityScope.emit(warning: $0) },\n            customHostToolchain: self.getHostToolchain(),\n            customManifestLoader: self.getManifestLoader(),\n            delegate: delegate\n        )\n        self._workspace = workspace\n        self._workspaceDelegate = delegate\n        return workspace\n    }\n\n    /// Purges all global caches without requiring workspace initialization.\n    /// This method creates minimal cache managers directly and calls their purgeCache methods.\n    public func purgeCaches(observabilityScope: ObservabilityScope) async throws {\n        // Create repository manager for repository cache\n        let repositoryManager = RepositoryManager(\n            fileSystem: self.fileSystem,\n            path: self.scratchDirectory.appending(\"repositories\"),\n            provider: GitRepositoryProvider(),\n            cachePath: self.sharedCacheDirectory.appending(\"repositories\"),\n            initializationWarningHandler: { observabilityScope.emit(warning: $0) },\n            delegate: nil\n        )\n\n        // Create manifest loader for manifest cache\n        let manifestLoader = ManifestLoader(\n            toolchain: try self.getHostToolchain(),\n            cacheDir: Workspace.DefaultLocations.manifestsDirectory(at: self.sharedCacheDirectory),\n            importRestrictions: nil,\n            delegate: nil,\n            pruneDependencies: false\n        )\n\n        // Create registry downloads manager for registry cache\n        let registryClient = RegistryClient(\n            configuration: .init(),\n            fingerprintStorage: nil,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: nil,\n            signingEntityCheckingMode: .strict,\n            authorizationProvider: nil,\n            delegate: nil,\n            checksumAlgorithm: SHA256()\n        )\n\n        let registryDownloadsManager = RegistryDownloadsManager(\n            fileSystem: self.fileSystem,\n            path: self.scratchDirectory.appending(components: \"registry\", \"downloads\"),\n            cachePath: self.sharedCacheDirectory.appending(components: \"registry\", \"downloads\"),\n            registryClient: registryClient,\n            delegate: nil\n        )\n\n        // Purge all caches\n        repositoryManager.purgeCache(observabilityScope: observabilityScope)\n        registryDownloadsManager.purgeCache(observabilityScope: observabilityScope)\n        await manifestLoader.purgeCache(observabilityScope: observabilityScope)\n    }\n\n    public func getRootPackageInformation(_ enableAllTraits: Bool = false) async throws -> (dependencies: [PackageIdentity: [PackageIdentity]], targets: [PackageIdentity: [String]]) {\n        let workspace = try self.getActiveWorkspace(enableAllTraits: enableAllTraits)\n        let root = try self.getWorkspaceRoot()\n        let rootManifests = try await workspace.loadRootManifests(\n            packages: root.packages,\n            observabilityScope: self.observabilityScope\n        )\n\n        var identities = [PackageIdentity: [PackageIdentity]]()\n        var targets = [PackageIdentity: [String]]()\n\n        for rootManifest in rootManifests {\n            let identity = PackageIdentity(path: rootManifest.key)\n            identities[identity] = rootManifest.value.dependencies.map(\\.identity)\n            targets[identity] = rootManifest.value.targets.map { $0.name.spm_mangledToC99ExtendedIdentifier() }\n        }\n\n        return (identities, targets)\n    }\n\n    private static func chdirIfNeeded(packageDirectory: AbsolutePath?, createPackagePath: Bool) throws {\n        if let packagePath = packageDirectory {\n            do {\n                try ProcessEnv.chdir(packagePath)\n            } catch let SystemError.chdir(errorCode, path) {\n                // If the command allows for the directory at the package path\n                // to not be present then attempt to create it and chdir again.\n                if createPackagePath {\n                    try makeDirectories(packagePath)\n                    try ProcessEnv.chdir(packagePath)\n                } else {\n                    throw SystemError.chdir(errorCode, path)\n                }\n            }\n        }\n    }\n\n    private func getEditsDirectory() throws -> AbsolutePath {\n        // TODO: replace multiroot-data-file with explicit overrides\n        if let multiRootPackageDataFile = options.locations.multirootPackageDataFile {\n            return multiRootPackageDataFile.appending(\"Packages\")\n        }\n        return try Workspace.DefaultLocations.editsDirectory(forRootPackage: self.getPackageRoot())\n    }\n\n    private func getResolvedVersionsFile() throws -> AbsolutePath {\n        // TODO: replace multiroot-data-file with explicit overrides\n        if let multiRootPackageDataFile = options.locations.multirootPackageDataFile {\n            return multiRootPackageDataFile.appending(\n                components: \"xcshareddata\",\n                \"swiftpm\",\n                Workspace.DefaultLocations.resolvedFileName\n            )\n        }\n        return try Workspace.DefaultLocations.resolvedVersionsFile(forRootPackage: self.getPackageRoot())\n    }\n\n    func getLocalConfigurationDirectory() throws -> AbsolutePath {\n        // Otherwise, use the default path.\n        // TODO: replace multiroot-data-file with explicit overrides\n        if let multiRootPackageDataFile = options.locations.multirootPackageDataFile {\n            // migrate from legacy location\n            let legacyPath = multiRootPackageDataFile.appending(components: \"xcshareddata\", \"swiftpm\", \"config\")\n            let newPath = Workspace.DefaultLocations\n                .mirrorsConfigurationFile(\n                    at: multiRootPackageDataFile\n                        .appending(components: \"xcshareddata\", \"swiftpm\", \"configuration\")\n                )\n            return try Workspace.migrateMirrorsConfiguration(\n                from: legacyPath,\n                to: newPath,\n                observabilityScope: self.observabilityScope\n            )\n        } else {\n            // migrate from legacy location\n            let legacyPath = try self.getPackageRoot().appending(components: \".swiftpm\", \"config\")\n            let newPath = try Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: self.getPackageRoot())\n            return try Workspace.migrateMirrorsConfiguration(\n                from: legacyPath,\n                to: newPath,\n                observabilityScope: self.observabilityScope\n            )\n        }\n    }\n\n    public func getAuthorizationProvider() throws -> AuthorizationProvider? {\n        var authorization = Workspace.Configuration.Authorization.default\n        if !self.options.security.netrc {\n            authorization.netrc = .disabled\n        } else if let configuredPath = options.security.netrcFilePath {\n            authorization.netrc = .custom(configuredPath)\n        } else {\n            authorization.netrc = .user\n        }\n\n        #if canImport(Security)\n        authorization.keychain = self.options.security.keychain ? .enabled : .disabled\n        #endif\n\n        return try authorization.makeAuthorizationProvider(\n            fileSystem: self.fileSystem,\n            observabilityScope: self.observabilityScope\n        )\n    }\n\n    public func getRegistryAuthorizationProvider() throws -> AuthorizationProvider? {\n        var authorization = Workspace.Configuration.Authorization.default\n        if let configuredPath = options.security.netrcFilePath {\n            authorization.netrc = .custom(configuredPath)\n        } else {\n            authorization.netrc = .user\n        }\n\n        // Don't use OS credential store if user wants netrc\n        #if canImport(Security)\n        authorization.keychain = self.options.security.forceNetrc ? .disabled : .enabled\n        #endif\n\n        return try authorization.makeRegistryAuthorizationProvider(\n            fileSystem: self.fileSystem,\n            observabilityScope: self.observabilityScope\n        )\n    }\n\n    /// Resolve the dependencies.\n    public func resolve() async throws {\n        let workspace = try getActiveWorkspace()\n        let root = try getWorkspaceRoot()\n\n        try await workspace.resolve(\n            root: root,\n            forceResolution: false,\n            forceResolvedVersions: self.options.resolver.forceResolvedVersions,\n            observabilityScope: self.observabilityScope\n        )\n\n        // Throw if there were errors when loading the graph.\n        // The actual errors will be printed before exiting.\n        guard !self.observabilityScope.errorsReported else {\n            throw ExitCode.failure\n        }\n    }\n\n    /// Fetch and load the complete package graph.\n    ///\n    /// - Parameters:\n    ///   - explicitProduct: The product specified on the command line to a “swift run” or “swift build” command. This\n    /// allows executables from dependencies to be run directly without having to hook them up to any particular target.\n    @discardableResult\n    public func loadPackageGraph(\n        explicitProduct: String? = nil,\n        testEntryPointPath: AbsolutePath? = nil\n    ) async throws -> ModulesGraph {\n        try await self.loadPackageGraph(\n            explicitProduct: explicitProduct,\n            enableAllTraits: false,\n            testEntryPointPath: testEntryPointPath\n        )\n    }\n\n    /// Fetch and load the complete package graph.\n    ///\n    /// - Parameters:\n    ///   - explicitProduct: The product specified on the command line to a “swift run” or “swift build” command. This\n    /// allows executables from dependencies to be run directly without having to hook them up to any particular target.\n    @discardableResult\n    package func loadPackageGraph(\n        explicitProduct: String? = nil,\n        enableAllTraits: Bool = false,\n        testEntryPointPath: AbsolutePath? = nil\n    ) async throws -> ModulesGraph {\n        do {\n            let workspace = try getActiveWorkspace(enableAllTraits: enableAllTraits)\n\n            // Fetch and load the package graph.\n            let graph = try await workspace.loadPackageGraph(\n                rootInput: self.getWorkspaceRoot(),\n                explicitProduct: explicitProduct,\n                forceResolvedVersions: self.options.resolver.forceResolvedVersions,\n                testEntryPointPath: testEntryPointPath,\n                observabilityScope: self.observabilityScope\n            )\n\n            // Throw if there were errors when loading the graph.\n            // The actual errors will be printed before exiting.\n            guard !self.observabilityScope.errorsReported else {\n                throw ExitCode.failure\n            }\n            return graph\n        } catch {\n            throw error\n        }\n    }\n\n    public func getPluginScriptRunner(customPluginsDir: AbsolutePath? = .none) throws -> PluginScriptRunner {\n        let pluginsDir = try customPluginsDir ?? self.getActiveWorkspace().location.pluginWorkingDirectory\n        let cacheDir = pluginsDir.appending(\"cache\")\n        let pluginScriptRunner = try DefaultPluginScriptRunner(\n            fileSystem: self.fileSystem,\n            cacheDir: cacheDir,\n            toolchain: self.getHostToolchain(),\n            extraPluginSwiftCFlags: self.options.build.pluginSwiftCFlags,\n            enableSandbox: !self.shouldDisableSandbox,\n            verboseOutput: self.logLevel <= .info\n        )\n        // register the plugin runner system with the cancellation handler\n        self.cancellator.register(name: \"plugin runner\", handler: pluginScriptRunner)\n        return pluginScriptRunner\n    }\n\n    /// Returns the user toolchain to compile the actual product.\n    public func getTargetToolchain() throws -> UserToolchain {\n        try self._targetToolchain.get()\n    }\n\n    public func getHostToolchain() throws -> UserToolchain {\n        try self._hostToolchain.get()\n    }\n\n    func getManifestLoader() throws -> ManifestLoader {\n        try self._manifestLoader.get()\n    }\n\n    public func canUseCachedBuildManifest(_ traitConfiguration: TraitConfiguration = .default) async throws -> Bool {\n        if !self.options.caching.cacheBuildManifest {\n            return false\n        }\n\n        let buildParameters = try self.productsBuildParameters\n        let haveBuildManifestAndDescription =\n            self.fileSystem.exists(buildParameters.llbuildManifest) &&\n            self.fileSystem.exists(buildParameters.buildDescriptionPath)\n\n        if !haveBuildManifestAndDescription {\n            return false\n        }\n\n        // Perform steps for build manifest caching if we can enabled it.\n        //\n        // FIXME: We don't add edited packages in the package structure command yet (SR-11254).\n        let hasEditedPackages = try await self.getActiveWorkspace().state.dependencies.contains(where: \\.isEdited)\n        if hasEditedPackages {\n            return false\n        }\n\n        return true\n    }\n\n    // note: do not customize the OutputStream unless absolutely necessary\n    // \"customOutputStream\" is designed to support build output redirection\n    // but it is only expected to be used when invoking builds from \"swift build\" command.\n    // in all other cases, the build output should go to the default which is stderr\n    public func createBuildSystem(\n        explicitBuildSystem: BuildSystemProvider.Kind? = .none,\n        explicitProduct: String? = .none,\n        enableAllTraits: Bool = false,\n        cacheBuildManifest: Bool = true,\n        shouldLinkStaticSwiftStdlib: Bool = false,\n        productsBuildParameters: BuildParameters? = .none,\n        toolsBuildParameters: BuildParameters? = .none,\n        packageGraphLoader: (() async throws -> ModulesGraph)? = .none,\n        outputStream: OutputByteStream? = .none,\n        logLevel: Basics.Diagnostic.Severity? = nil,\n        observabilityScope: ObservabilityScope? = .none,\n        delegate: BuildSystemDelegate? = nil\n    ) async throws -> BuildSystem {\n\n        if self.options.build.useIntegratedSwiftDriver && self.options.build.buildSystem == .native {\n            self.observabilityScope.emit(warning: \"`--use-integrated-swift-driver` option is deprecated as the feature is not fully functional.\")\n        }\n\n        guard let buildSystemProvider else {\n            fatalError(\"build system provider not initialized\")\n        }\n        var productsParameters = try productsBuildParameters ?? self.productsBuildParameters\n        productsParameters.linkingParameters.shouldLinkStaticSwiftStdlib = shouldLinkStaticSwiftStdlib\n        let buildSystem = try await buildSystemProvider.createBuildSystem(\n            kind: explicitBuildSystem ?? self.options.build.buildSystem,\n            explicitProduct: explicitProduct,\n            enableAllTraits: enableAllTraits,\n            cacheBuildManifest: cacheBuildManifest,\n            productsBuildParameters: productsParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            packageGraphLoader: packageGraphLoader,\n            outputStream: outputStream,\n            logLevel: logLevel ?? self.logLevel,\n            observabilityScope: observabilityScope,\n            delegate: delegate\n        )\n\n        // register the build system with the cancellation handler\n        self.cancellator.register(name: \"build system\", handler: buildSystem.cancel)\n        return buildSystem\n    }\n\n    static let entitlementsMacOSWarning = \"\"\"\n    `--enable-get-task-allow-entitlement` and `--disable-get-task-allow-entitlement` only have an effect \\\n    when building on macOS.\n    \"\"\"\n\n    private func _buildParams(\n        toolchain: UserToolchain,\n        destination: BuildParameters.Destination,\n        prepareForIndexing: Bool\n    ) throws -> BuildParameters {\n        let triple = toolchain.targetTriple\n\n        let dataPath = self.scratchDirectory.appending(\n            component: triple.platformBuildPathComponent(buildSystem: self.options.build.buildSystem)\n        )\n\n        if self.options.build.getTaskAllowEntitlement != nil && !triple.isMacOSX {\n            self.observabilityScope.emit(warning: Self.entitlementsMacOSWarning)\n        }\n\n        let prepareForIndexingMode: BuildParameters.PrepareForIndexingMode =\n            switch (prepareForIndexing, self.options.build.prepareForIndexingNoLazy) {\n            case (false, _): .off\n            case (true, false): .on\n            case (true, true): .noLazy\n            }\n\n        return try BuildParameters(\n            destination: destination,\n            dataPath: dataPath,\n            configuration: self.options.build.configuration ?? self.preferredBuildConfiguration,\n            toolchain: toolchain,\n            triple: triple,\n            flags: options.build.buildFlags,\n            buildSystemKind: options.build.buildSystem,\n            pkgConfigDirectories: options.locations.pkgConfigDirectories,\n            customToolsetPaths: options.locations.toolsetPaths,\n            architectures: options.build.architectures,\n            workers: options.build.jobs,\n            shouldCreateDylibForDynamicProducts: !self.options.build.shouldBuildDylibsAsFrameworks,\n            sanitizers: options.build.enabledSanitizers,\n            indexStoreMode: options.build.indexStoreMode.buildParameter,\n            prepareForIndexing: prepareForIndexingMode,\n            enableXCFrameworksOnLinux: options.build.enableXCFrameworksOnLinux,\n            debuggingParameters: .init(\n                debugInfoFormat: self.options.build.debugInfoFormat.buildParameter,\n                triple: triple,\n                shouldEnableDebuggingEntitlement:\n                self.options.build\n                    .getTaskAllowEntitlement ??\n                    (self.options.build.configuration ?? self.preferredBuildConfiguration == .debug),\n                omitFramePointers: self.options.build.omitFramePointers\n            ),\n            driverParameters: .init(\n                canRenameEntrypointFunctionName: DriverSupport.checkSupportedFrontendFlags(\n                    flags: [\"entry-point-function-name\"],\n                    toolchain: toolchain,\n                    fileSystem: self.fileSystem\n                ) && !options.build.sanitizers.contains(.fuzzer),\n                enableParseableModuleInterfaces: self.options.build.shouldEnableParseableModuleInterfaces,\n                explicitTargetDependencyImportCheckingMode: self.options.build.explicitTargetDependencyImportCheck\n                    .modeParameter,\n                useIntegratedSwiftDriver: self.options.build.useIntegratedSwiftDriver,\n                isPackageAccessModifierSupported: DriverSupport.isPackageNameSupported(\n                    toolchain: toolchain,\n                    fileSystem: self.fileSystem\n                )\n            ),\n            linkingParameters: .init(\n                linkerDeadStrip: self.options.linker.linkerDeadStrip,\n                linkTimeOptimizationMode: self.options.build.linkTimeOptimizationMode?.buildParameter,\n                shouldDisableLocalRpath: self.options.linker.shouldDisableLocalRpath\n            ),\n            outputParameters: .init(\n                isColorized: self.options.logging.colorDiagnostics,\n                isVerbose: self.logLevel <= .info,\n                enableTaskBacktraces: self.options.build.enableTaskBacktraces\n            ),\n            testingParameters: .init(\n                forceTestDiscovery: self.options.build.enableTestDiscovery,\n                // backwards compatibility, remove with --enable-test-discovery\n                testEntryPointPath: self.options.build.testEntryPointPath\n            )\n        )\n    }\n\n    /// Return the build parameters for the host toolchain.\n    public var toolsBuildParameters: BuildParameters {\n        get throws {\n            try self._toolsBuildParameters.get()\n        }\n    }\n\n    private lazy var _toolsBuildParameters: Result<BuildParameters, Swift.Error> = Result(catching: {\n        // Tools need to do a full build\n        try self._buildParams(toolchain: self.getHostToolchain(), destination: .host, prepareForIndexing: false)\n    })\n\n    public var productsBuildParameters: BuildParameters {\n        get throws {\n            try self._productsBuildParameters.get()\n        }\n    }\n\n    private lazy var _productsBuildParameters: Result<BuildParameters, Swift.Error> = Result(catching: {\n        try self._buildParams(\n            toolchain: self.getTargetToolchain(),\n            destination: .target,\n            prepareForIndexing: self.options.build.prepareForIndexing\n        )\n    })\n\n    /// Lazily compute the target toolchain.\n    private lazy var _targetToolchain: Result<UserToolchain, Swift.Error> = {\n        let swiftSDK: SwiftSDK\n        let hostSwiftSDK: SwiftSDK\n        do {\n            let hostToolchain = try _hostToolchain.get()\n            hostSwiftSDK = hostToolchain.swiftSDK\n\n            if self.options.build.deprecatedSwiftSDKSelector != nil {\n                self.observabilityScope.emit(\n                    warning: \"`--experimental-swift-sdk` is deprecated and will be removed in a future version of SwiftPM. Use `--swift-sdk` instead.\"\n                )\n            }\n\n            let store = SwiftSDKBundleStore(\n                swiftSDKsDirectory: self.sharedSwiftSDKsDirectory,\n                hostToolchainBinDir: hostToolchain.swiftCompilerPath.parentDirectory,\n                fileSystem: self.fileSystem,\n                observabilityScope: self.observabilityScope,\n                outputHandler: { print($0.description) }\n            )\n\n            swiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostToolchain.targetTriple,\n                customToolsets: self.options.locations.toolsetPaths,\n                customCompileDestination: self.options.locations.customCompileDestination,\n                customCompileTriple: self.options.build.customCompileTriple,\n                customCompileToolchain: self.options.build.customCompileToolchain,\n                customCompileSDK: self.options.build.customCompileSDK,\n                swiftSDKSelector: self.options.build.swiftSDKSelector ?? self.options.build.deprecatedSwiftSDKSelector,\n                architectures: self.options.build.architectures,\n                store: store,\n                observabilityScope: self.observabilityScope,\n                fileSystem: self.fileSystem\n            )\n        } catch {\n            return .failure(error)\n        }\n        // Check if we ended up with the host toolchain.\n        if hostSwiftSDK == swiftSDK {\n            return self._hostToolchain\n        }\n\n        return Result(catching: {\n            try UserToolchain(\n                swiftSDK: swiftSDK,\n                environment: self.environment,\n                customTargetInfo: targetInfo,\n                observabilityScope: self.observabilityScope,\n                fileSystem: self.fileSystem)\n        })\n    }()\n\n    /// Lazily compute the host toolchain used to compile the package description.\n    private lazy var _hostToolchain: Result<UserToolchain, Swift.Error> = Result(catching: {\n        var hostSwiftSDK = try SwiftSDK.hostSwiftSDK(\n            environment: self.environment,\n            observabilityScope: self.observabilityScope\n        )\n        hostSwiftSDK.targetTriple = self.hostTriple\n\n        return try UserToolchain(\n            swiftSDK: hostSwiftSDK,\n            environment: self.environment,\n            customTargetInfo: targetInfo,\n            observabilityScope: self.observabilityScope,\n            fileSystem: self.fileSystem\n        )\n    })\n\n    private lazy var _manifestLoader: Result<ManifestLoader, Swift.Error> = Result(catching: {\n        let cachePath: AbsolutePath? = switch (\n            self.options.caching.shouldDisableManifestCaching,\n            self.options.caching.manifestCachingMode\n        ) {\n        case (true, _):\n            // backwards compatibility\n            .none\n        case (false, .none):\n            .none\n        case (false, .local):\n            self.scratchDirectory\n        case (false, .shared):\n            Workspace.DefaultLocations.manifestsDirectory(at: self.sharedCacheDirectory)\n        }\n\n        var extraManifestFlags = self.options.build.manifestFlags\n        if self.logLevel <= .info {\n            extraManifestFlags.append(\"-v\")\n        }\n\n        return try ManifestLoader(\n            // Always use the host toolchain's resources for parsing manifest.\n            toolchain: self.getHostToolchain(),\n            isManifestSandboxEnabled: !self.shouldDisableSandbox,\n            cacheDir: cachePath,\n            extraManifestFlags: extraManifestFlags,\n            importRestrictions: .none,\n            pruneDependencies: self.options.resolver.pruneDependencies\n        )\n    })\n\n    /// An enum indicating the execution status of run commands.\n    public enum ExecutionStatus {\n        case success\n        case failure\n    }\n\n    // MARK: - Locking\n\n    // This is used to attempt to prevent accidental misuse of the locking APIs.\n    private enum WorkspaceLockState {\n        case unspecified\n        case needsLocking\n        case locked\n        case unlocked\n    }\n\n    private var workspaceLockState: WorkspaceLockState = .unspecified\n    private var workspaceLock: FileLock?\n\n    fileprivate func setNeedsLocking() {\n        assert(\n            self.workspaceLockState == .unspecified,\n            \"attempting to `setNeedsLocking()` from unexpected state: \\(self.workspaceLockState)\"\n        )\n        self.workspaceLockState = .needsLocking\n    }\n\n    private func acquireLockIfNeeded() throws {\n        guard !options.locations.skipAcquiringLock else {\n            return\n        }\n        guard self.packageRoot != nil else {\n            return\n        }\n        assert(\n            self.workspaceLockState == .needsLocking,\n            \"attempting to `acquireLockIfNeeded()` from unexpected state: \\(self.workspaceLockState)\"\n        )\n        guard workspaceLock == nil else {\n            throw InternalError(\"acquireLockIfNeeded() called multiple times\")\n        }\n        self.workspaceLockState = .locked\n\n        let workspaceLock = try FileLock.prepareLock(fileToLock: self.scratchDirectory)\n        let lockFile = self.scratchDirectory.appending(\".lock\").pathString\n\n        // Try a non-blocking lock first so that we can inform the user about an already running SwiftPM.\n        do {\n            try workspaceLock.lock(type: .exclusive, blocking: false)\n            let pid = ProcessInfo.processInfo.processIdentifier\n            try? String(pid).write(toFile: lockFile, atomically: true, encoding: .utf8)\n        } catch ProcessLockError.unableToAquireLock(let errno) {\n            if errno == EWOULDBLOCK {\n                let lockingPID = try? String(contentsOfFile: lockFile, encoding: .utf8)\n                let pidInfo = lockingPID.map { \"(PID: \\($0)) \" } ?? \"\"\n                \n                if self.options.locations.ignoreLock {\n                    self.outputStream\n                        .write(\n                            \"Another instance of SwiftPM \\(pidInfo)is already running using '\\(self.scratchDirectory)', but this will be ignored since `--ignore-lock` has been passed\"\n                                .utf8\n                        )\n                    self.outputStream.flush()\n                } else {\n                    self.outputStream\n                        .write(\n                            \"Another instance of SwiftPM \\(pidInfo)is already running using '\\(self.scratchDirectory)', waiting until that process has finished execution...\"\n                                .utf8\n                        )\n                    self.outputStream.flush()\n\n                    // Only if we fail because there's an existing lock we need to acquire again as blocking.\n                    try workspaceLock.lock(type: .exclusive, blocking: true)\n\n                    let pid = ProcessInfo.processInfo.processIdentifier\n                    try? String(pid).write(toFile: lockFile, atomically: true, encoding: .utf8)\n                }\n            }\n        }\n\n        self.workspaceLock = workspaceLock\n    }\n\n    fileprivate func releaseLockIfNeeded() {\n        // Never having acquired the lock is not an error case.\n        assert(\n            self.workspaceLockState == .locked || self.workspaceLockState == .needsLocking,\n            \"attempting to `releaseLockIfNeeded()` from unexpected state: \\(self.workspaceLockState)\"\n        )\n        self.workspaceLockState = .unlocked\n\n        self.workspaceLock?.unlock()\n    }\n}\n\nextension BuildSystemProvider.Kind {\n    fileprivate var shouldCreateMultipleTestProducts: Bool {\n        switch self {\n        case .xcode, .swiftbuild:\n            return true\n        case .native:\n            return false\n        }\n    }\n\n    fileprivate var additionalFileRules: [FileRuleDescription] {\n        switch self {\n        case .xcode, .swiftbuild:\n            return FileRuleDescription.xcbuildFileTypes\n        case .native:\n            return FileRuleDescription.swiftpmFileTypes\n        }\n    }\n}\n\n/// Returns path of the nearest directory containing the manifest file w.r.t\n/// current working directory.\nprivate func findPackageRoot(fileSystem: FileSystem) -> AbsolutePath? {\n    guard var root = fileSystem.currentWorkingDirectory else {\n        return nil\n    }\n    // FIXME: It would be nice to move this to a generalized method which takes path and predicate and\n    // finds the lowest path for which the predicate is true.\n    while !fileSystem.isFile(root.appending(component: Manifest.filename)) {\n        root = root.parentDirectory\n        guard !root.isRoot else {\n            return nil\n        }\n    }\n    return root\n}\n\nprivate func getSharedSecurityDirectory(options: GlobalOptions, fileSystem: FileSystem) throws -> AbsolutePath {\n    if let explicitSecurityDirectory = options.locations.securityDirectory {\n        // Create the explicit security path if necessary\n        if !fileSystem.exists(explicitSecurityDirectory) {\n            try fileSystem.createDirectory(explicitSecurityDirectory, recursive: true)\n        }\n        return explicitSecurityDirectory\n    } else {\n        // further validation is done in workspace\n        return try fileSystem.swiftPMSecurityDirectory\n    }\n}\n\nprivate func getSharedConfigurationDirectory(options: GlobalOptions, fileSystem: FileSystem) throws -> AbsolutePath {\n    if let explicitConfigurationDirectory = options.locations.configurationDirectory {\n        // Create the explicit config path if necessary\n        if !fileSystem.exists(explicitConfigurationDirectory) {\n            try fileSystem.createDirectory(explicitConfigurationDirectory, recursive: true)\n        }\n        return explicitConfigurationDirectory\n    } else {\n        // further validation is done in workspace\n        return try fileSystem.swiftPMConfigurationDirectory\n    }\n}\n\nprivate func getSharedCacheDirectory(options: GlobalOptions, fileSystem: FileSystem) throws -> AbsolutePath {\n    if let explicitCacheDirectory = options.locations.cacheDirectory {\n        // Create the explicit cache path if necessary\n        if !fileSystem.exists(explicitCacheDirectory) {\n            try fileSystem.createDirectory(explicitCacheDirectory, recursive: true)\n        }\n        return explicitCacheDirectory\n    } else {\n        // further validation is done in workspace\n        return try fileSystem.swiftPMCacheDirectory\n    }\n}\n\nextension Basics.Diagnostic {\n    static func unsupportedFlag(_ flag: String) -> Self {\n        .warning(\"\\(flag) is an *unsupported* option which can be removed at any time; do not rely on it\")\n    }\n}\n\n// MARK: - Support for loading external workspaces\n\npublic protocol WorkspaceLoader {\n    func load(workspace: AbsolutePath) throws -> [AbsolutePath]\n}\n\n// MARK: - Diagnostics\n\nextension SwiftCommandState {\n    // FIXME: deprecate these one we are further along refactoring the call sites that use it\n    /// The stream to print standard output on.\n    public var outputStream: OutputByteStream {\n        self.observabilityHandler.outputStream\n    }\n}\n\nextension Workspace.ManagedDependency {\n    fileprivate var isEdited: Bool {\n        if case .edited = self.state { return true }\n        return false\n    }\n}\n\nextension LoggingOptions {\n    fileprivate var logLevel: Diagnostic.Severity {\n        if self.verbose {\n            .info\n        } else if self.veryVerbose {\n            .debug\n        } else if self.quiet {\n            .error\n        } else {\n            .warning\n        }\n    }\n}\n\nextension ResolverOptions.SourceControlToRegistryDependencyTransformation {\n    fileprivate var workspaceConfiguration: WorkspaceConfiguration.SourceControlToRegistryDependencyTransformation {\n        switch self {\n        case .disabled:\n            .disabled\n        case .identity:\n            .identity\n        case .swizzle:\n            .swizzle\n        }\n    }\n}\n\nextension BuildOptions.StoreMode {\n    fileprivate var buildParameter: BuildParameters.IndexStoreMode {\n        switch self {\n        case .autoIndexStore:\n            .auto\n        case .enableIndexStore:\n            .on\n        case .disableIndexStore:\n            .off\n        }\n    }\n}\n\nextension BuildOptions.TargetDependencyImportCheckingMode {\n    fileprivate var modeParameter: BuildParameters.TargetDependencyImportCheckingMode {\n        switch self {\n        case .none:\n            .none\n        case .warn:\n            .warn\n        case .error:\n            .error\n        }\n    }\n}\n\nextension BuildOptions.LinkTimeOptimizationMode {\n    fileprivate var buildParameter: BuildParameters.LinkTimeOptimizationMode? {\n        switch self {\n        case .full:\n            .full\n        case .thin:\n            .thin\n        }\n    }\n}\n\nextension BuildOptions.DebugInfoFormat {\n    fileprivate var buildParameter: BuildParameters.DebugInfoFormat {\n        switch self {\n        case .dwarf:\n            .dwarf\n        case .codeview:\n            .codeview\n        case .none:\n            .none\n        }\n    }\n}\n\nextension Basics.Diagnostic {\n    public static func mutuallyExclusiveArgumentsError(arguments: [String]) -> Self {\n        .error(arguments.map { \"'\\($0)'\" }.spm_localizedJoin(type: .conjunction) + \" are mutually exclusive\")\n    }\n}\n\n"
  },
  {
    "path": "Sources/DriverSupport/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2022 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(DriverSupport\n  DriverSupportUtils.swift\n  SPMSwiftDriverExecutor.swift)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(DriverSupport PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\ntarget_link_libraries(DriverSupport PUBLIC\n  Basics\n  PackageModel\n  SwiftDriver)\n\ninstall(TARGETS DriverSupport\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS DriverSupport)\n"
  },
  {
    "path": "Sources/DriverSupport/DriverSupportUtils.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\nimport Foundation\nimport PackageModel\nimport SwiftDriver\nimport class TSCBasic.Process\nimport struct TSCBasic.ProcessResult\n\npublic enum DriverSupport {\n    private static var flagsMap = ThreadSafeBox<[String: Set<String>]>([:])\n\n    /// This checks _frontend_ supported flags, which are not necessarily supported in the driver.\n    public static func checkSupportedFrontendFlags(\n        flags: Set<String>,\n        toolchain: PackageModel.Toolchain,\n        fileSystem: FileSystem\n    ) -> Bool {\n        let trimmedFlagSet = Set(flags.map { $0.trimmingCharacters(in: [\"-\"]) })\n        let swiftcPathString = toolchain.swiftCompilerPath.pathString\n        let entry = flagsMap.get()\n\n        if let cachedSupportedFlagSet = entry[swiftcPathString + \"-frontend\"] {\n            return cachedSupportedFlagSet.intersection(trimmedFlagSet) == trimmedFlagSet\n        }\n        do {\n            let executor = try SPMSwiftDriverExecutor(\n                resolver: ArgsResolver(fileSystem: fileSystem),\n                fileSystem: fileSystem,\n                env: [:]\n            )\n            let driver = try Driver(\n                args: [\"swiftc\"],\n                executor: executor,\n                compilerIntegratedTooling: false,\n                compilerExecutableDir: TSCAbsolutePath(toolchain.swiftCompilerPath.parentDirectory)\n            )\n            let supportedFlagSet = Set(driver.supportedFrontendFlags.map { $0.trimmingCharacters(in: [\"-\"]) })\n            flagsMap.put([swiftcPathString + \"-frontend\": supportedFlagSet])\n            return supportedFlagSet.intersection(trimmedFlagSet) == trimmedFlagSet\n        } catch {\n            return false\n        }\n    }\n\n    // This checks if given flags are supported in the built-in toolchain driver. Currently\n    // there's no good way to get the supported flags from it, so run `swiftc -h` directly\n    // to get the flags and cache the result.\n    static func checkToolchainDriverFlags(\n        flags: Set<String>,\n        toolchain: PackageModel.Toolchain,\n        fileSystem: FileSystem\n    ) -> Bool {\n        let trimmedFlagSet = Set(flags.map { $0.trimmingCharacters(in: [\"-\"]) })\n        let swiftcPathString = toolchain.swiftCompilerPath.pathString\n        let entry = flagsMap.get()\n\n        if let cachedSupportedFlagSet = entry[swiftcPathString + \"-driver\"] {\n            return cachedSupportedFlagSet.intersection(trimmedFlagSet) == trimmedFlagSet\n        }\n        do {\n            let helpJob = try TSCBasic.Process.launchProcess(\n                arguments: [swiftcPathString, \"-h\"],\n                env: .init(Environment.current)\n            )\n            let processResult = try helpJob.waitUntilExit()\n            guard processResult.exitStatus == .terminated(code: 0) else {\n                return false\n            }\n            let helpOutput = try processResult.utf8Output()\n            let helpFlags = helpOutput.components(separatedBy: \" \").map { $0.trimmingCharacters(in: [\"-\"]) }\n            let supportedFlagSet = Set(helpFlags)\n            flagsMap.put([swiftcPathString + \"-driver\": supportedFlagSet])\n            return supportedFlagSet.intersection(trimmedFlagSet) == trimmedFlagSet\n        } catch {\n            return false\n        }\n    }\n\n    @_spi(SwiftPMInternal)\n    public static func isPackageNameSupported(toolchain: PackageModel.Toolchain, fileSystem: FileSystem) -> Bool {\n        DriverSupport.checkToolchainDriverFlags(flags: [\"-package-name\"], toolchain: toolchain, fileSystem: fileSystem)\n    }\n}\n"
  },
  {
    "path": "Sources/DriverSupport/SPMSwiftDriverExecutor.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\n\nimport SwiftDriver\n\nimport class TSCBasic.Process\nimport struct TSCBasic.ProcessResult\n\npublic final class SPMSwiftDriverExecutor: DriverExecutor {\n    \n    private enum Error: Swift.Error, CustomStringConvertible {\n        case inPlaceExecutionUnsupported\n        \n        var description: String {\n            switch self {\n            case .inPlaceExecutionUnsupported:\n                return \"the integrated Swift driver does not support in-place execution\"\n            }\n        }\n    }\n    \n    public let resolver: ArgsResolver\n    let fileSystem: FileSystem\n    let env: Environment\n\n    public init(resolver: ArgsResolver,\n         fileSystem: FileSystem,\n         env: Environment) {\n        self.resolver = resolver\n        self.fileSystem = fileSystem\n        self.env = env\n    }\n    \n    public func execute(job: Job,\n                 forceResponseFiles: Bool,\n                 recordedInputModificationDates: [TypedVirtualPath : TimePoint]) throws -> ProcessResult {\n        let arguments: [String] = try resolver.resolveArgumentList(for: job,\n                                                                   useResponseFiles: forceResponseFiles ? .forced : .heuristic)\n        \n        try job.verifyInputsNotModified(since: recordedInputModificationDates,\n                                        fileSystem: fileSystem)\n        \n        if job.requiresInPlaceExecution {\n            throw Error.inPlaceExecutionUnsupported\n        }\n        \n        \n        var childEnv = [String: String](env)\n        childEnv.merge(job.extraEnvironment, uniquingKeysWith: { (_, new) in new })\n\n        let process = try Process.launchProcess(arguments: arguments, env: childEnv)\n        return try process.waitUntilExit()\n    }\n    \n    public func execute(workload: DriverExecutorWorkload,\n                 delegate: JobExecutionDelegate,\n                 numParallelJobs: Int, forceResponseFiles: Bool,\n                 recordedInputModificationDates: [TypedVirtualPath : TimePoint]) throws {\n        throw InternalError(\"Multi-job build plans should be lifted into the SPM build graph.\")\n    }\n    \n    public func checkNonZeroExit(args: String..., environment: [String : String]) throws -> String {\n        try AsyncProcess.checkNonZeroExit(arguments: args, environment: .init(environment))\n    }\n    \n    public func description(of job: Job, forceResponseFiles: Bool) throws -> String {\n        // FIXME: This is duplicated from SwiftDriver, maybe it shouldn't be a protocol requirement.\n        let (args, usedResponseFile) = try resolver.resolveArgumentList(for: job,\n                                                                        useResponseFiles: forceResponseFiles ? .forced : .heuristic)\n        var result = args.joined(separator: \" \")\n        \n        if usedResponseFile {\n            // Print the response file arguments as a comment.\n            result += \" # \\(job.commandLine.joinedUnresolvedArguments)\"\n        }\n        \n        if !job.extraEnvironment.isEmpty {\n            result += \" #\"\n            for (envVar, val) in job.extraEnvironment {\n                result += \" \\(envVar)=\\(val)\"\n            }\n        }\n        return result\n    }\n}\n"
  },
  {
    "path": "Sources/LLBuildManifest/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(LLBuildManifest STATIC\n  Command.swift\n  LLBuildManifest.swift\n  LLBuildManifestWriter.swift\n  Node.swift\n  Target.swift\n  Tools.swift)\ntarget_link_libraries(LLBuildManifest PUBLIC\n  TSCBasic\n  Basics)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(LLBuildManifest PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n"
  },
  {
    "path": "Sources/LLBuildManifest/Command.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct Command {\n    /// The name of the command.\n    public var name: String\n\n    /// The tool used for this command.\n    public var tool: ToolProtocol\n\n    init(name: String, tool: ToolProtocol) {\n        self.name = name\n        self.tool = tool\n    }\n}\n"
  },
  {
    "path": "Sources/LLBuildManifest/LLBuildManifest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport TSCBasic\nimport TSCUtility\n\nimport class Basics.AsyncProcess\n\npublic protocol AuxiliaryFileType {\n    static var name: String { get }\n\n    static func getFileContents(inputs: [Node]) throws -> String\n}\n\npublic enum WriteAuxiliary {\n    public static let fileTypes: [AuxiliaryFileType.Type] = [\n        EntitlementPlist.self,\n        LinkFileList.self,\n        SourcesFileList.self,\n        SwiftGetVersion.self,\n        XCTestInfoPlist.self,\n        EmbeddedResources.self,\n    ]\n\n    public struct EntitlementPlist: AuxiliaryFileType {\n        public static let name = \"entitlement-plist\"\n\n        public static func computeInputs(entitlement: String) -> [Node] {\n            [.virtual(Self.name), .virtual(entitlement)]\n        }\n\n        public static func getFileContents(inputs: [Node]) throws -> String {\n            guard let entitlementName = inputs.last?.extractedVirtualNodeName else {\n                throw Error.undefinedEntitlementName\n            }\n            let encoder = PropertyListEncoder()\n            encoder.outputFormat = .xml\n            let result = try encoder.encode([entitlementName: true])\n\n            let contents = String(decoding: result, as: UTF8.self)\n            return contents\n        }\n\n        private enum Error: Swift.Error {\n            case undefinedEntitlementName\n        }\n    }\n\n    public struct LinkFileList: AuxiliaryFileType {\n        public static let name = \"link-file-list\"\n\n        // FIXME: We should extend the `InProcessTool` support to allow us to specify these in a typed way, but today we have to flatten all the inputs into a generic `Node` array (rdar://109844243).\n        public static func computeInputs(objects: [Basics.AbsolutePath]) -> [Node] {\n            return [.virtual(Self.name)] + objects.map { Node.file($0) }\n        }\n\n        public static func getFileContents(inputs: [Node]) throws -> String {\n            let objects = inputs.compactMap {\n                if $0.kind == .file {\n                    return $0.name\n                } else {\n                    return nil\n                }\n            }\n\n            var content = objects\n                .map { $0.spm_shellEscaped() }\n                .joined(separator: \"\\n\")\n\n            // not sure this is needed, added here for backward compatibility\n            if !content.isEmpty {\n                content.append(\"\\n\")\n            }\n\n            return content\n        }\n    }\n\n    public struct SourcesFileList: AuxiliaryFileType {\n        public static let name = \"sources-file-list\"\n\n        public static func computeInputs(sources: [Basics.AbsolutePath]) -> [Node] {\n            return [.virtual(Self.name)] + sources.map { Node.file($0) }\n        }\n\n        public static func getFileContents(inputs: [Node]) throws -> String {\n            let sources = inputs.compactMap {\n                if $0.kind == .file {\n                    return $0.name\n                } else {\n                    return nil\n                }\n            }\n\n            guard sources.count > 0 else { return \"\" }\n\n            var contents = sources\n                .map { $0.spm_shellEscaped() }\n                .joined(separator: \"\\n\")\n            contents.append(\"\\n\")\n            return contents\n        }\n    }\n\n    public struct SwiftGetVersion: AuxiliaryFileType {\n        public static let name = \"swift-get-version\"\n\n        public static func computeInputs(swiftCompilerPath: Basics.AbsolutePath) -> [Node] {\n            return [.virtual(Self.name), .file(swiftCompilerPath)]\n        }\n\n        public static func getFileContents(inputs: [Node]) throws -> String {\n            guard let swiftCompilerPathString = inputs.first(where: { $0.kind == .file })?.name else {\n                throw Error.unknownSwiftCompilerPath\n            }\n            let swiftCompilerPath = try Basics.AbsolutePath(validating: swiftCompilerPathString)\n            return try AsyncProcess.checkNonZeroExit(args: swiftCompilerPath.pathString, \"-version\")\n        }\n\n        private enum Error: Swift.Error {\n            case unknownSwiftCompilerPath\n        }\n    }\n\n    public struct XCTestInfoPlist: AuxiliaryFileType {\n        public static let name = \"xctest-info-plist\"\n\n        public static func computeInputs(principalClass: String) -> [Node] {\n            return [.virtual(Self.name), .virtual(principalClass)]\n        }\n\n        public static func getFileContents(inputs: [Node]) throws -> String {\n            guard let principalClass = inputs.last?.extractedVirtualNodeName else {\n                throw Error.undefinedPrincipalClass\n            }\n\n            let plist = InfoPlist(NSPrincipalClass: String(principalClass))\n            let encoder = PropertyListEncoder()\n            encoder.outputFormat = .xml\n            let result = try encoder.encode(plist)\n\n            let contents = String(decoding: result, as: UTF8.self)\n            return contents\n        }\n\n        private struct InfoPlist: Codable {\n            let NSPrincipalClass: String\n        }\n\n        private enum Error: Swift.Error {\n            case undefinedPrincipalClass\n        }\n    }\n\n    public struct EmbeddedResources: AuxiliaryFileType {\n        public static let name = \"embedded-resources\"\n\n        public static func computeInputs(resources: [Basics.AbsolutePath]) -> [Node] {\n            return [.virtual(Self.name)] + resources.map { Node.file($0) }\n        }\n\n        // FIXME: This will not work well for large files, as we will store the entire contents, plus its byte array\n        // representation in memory.\n        public static func getFileContents(inputs: [Node]) throws -> String {\n            var content =\n                \"\"\"\n                struct PackageResources {\n\n                \"\"\"\n\n            for input in inputs where input.kind == .file {\n                let resourcePath = try Basics.AbsolutePath(validating: input.name)\n                let variableName = resourcePath.basename.spm_mangledToC99ExtendedIdentifier()\n                let fileContent = try Data(contentsOf: URL(fileURLWithPath: resourcePath.pathString)).map { String($0) }.joined(separator: \",\")\n\n                content += \"static let \\(variableName): [UInt8] = [\\(fileContent)]\\n\"\n            }\n\n            content += \"}\"\n            return content\n        }\n    }\n}\n\npublic struct LLBuildManifest {\n    public typealias TargetName = String\n    public typealias CmdName = String\n\n    /// The targets in the manifest.\n    public private(set) var targets: [TargetName: Target] = [:]\n\n    /// The commands in the manifest.\n    public private(set) var commands: [CmdName: Command] = [:]\n\n    /// The default target to build.\n    public var defaultTarget: String = \"\"\n\n    public init() {\n    }\n\n    public func getCmdToolMap<T: ToolProtocol>(kind: T.Type) -> [CmdName: T] {\n        var result = [CmdName: T]()\n        for (cmdName, cmd) in commands {\n            if let tool = cmd.tool as? T {\n                result[cmdName] = tool\n            }\n        }\n        return result\n    }\n\n    public mutating func createTarget(_ name: TargetName) {\n        guard !targets.keys.contains(name) else { return }\n        targets[name] = Target(name: name, nodes: [])\n    }\n\n    public mutating func addNode(_ node: Node, toTarget target: TargetName) {\n        targets[target, default: Target(name: target, nodes: [])].nodes.append(node)\n    }\n\n    private mutating func addCommand(name: String, tool: ToolProtocol) {\n        assert(commands[name] == nil, \"already had a command named '\\(name)'\")\n        commands[name] = Command(name: name, tool: tool)\n    }\n\n    public mutating func addPhonyCmd(\n        name: String,\n        inputs: [Node],\n        outputs: [Node]\n    ) {\n        let tool = PhonyTool(inputs: inputs, outputs: outputs)\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addTestDiscoveryCmd(\n        name: String,\n        inputs: [Node],\n        outputs: [Node]\n    ) {\n        let tool = TestDiscoveryTool(inputs: inputs, outputs: outputs)\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addTestEntryPointCmd(\n        name: String,\n        inputs: [Node],\n        outputs: [Node]\n    ) {\n        let tool = TestEntryPointTool(inputs: inputs, outputs: outputs)\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addCopyCmd(\n        name: String,\n        inputs: [Node],\n        outputs: [Node]\n    ) {\n        let tool = CopyTool(inputs: inputs, outputs: outputs)\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addEntitlementPlistCommand(entitlement: String, outputPath: Basics.AbsolutePath) {\n        let inputs = WriteAuxiliary.EntitlementPlist.computeInputs(entitlement: entitlement)\n        let tool = WriteAuxiliaryFile(inputs: inputs, outputFilePath: outputPath)\n        let name = outputPath.pathString\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addWriteLinkFileListCommand(\n        objects: [Basics.AbsolutePath],\n        linkFileListPath: Basics.AbsolutePath\n    ) {\n        let inputs = WriteAuxiliary.LinkFileList.computeInputs(objects: objects)\n        let tool = WriteAuxiliaryFile(inputs: inputs, outputFilePath: linkFileListPath)\n        let name = linkFileListPath.pathString\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addWriteSourcesFileListCommand(\n        sources: [Basics.AbsolutePath],\n        sourcesFileListPath: Basics.AbsolutePath\n    ) {\n        let inputs = WriteAuxiliary.SourcesFileList.computeInputs(sources: sources)\n        let tool = WriteAuxiliaryFile(inputs: inputs, outputFilePath: sourcesFileListPath)\n        let name = sourcesFileListPath.pathString\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addSwiftGetVersionCommand(\n        swiftCompilerPath: Basics.AbsolutePath,\n        swiftVersionFilePath: Basics.AbsolutePath\n    ) {\n        let inputs = WriteAuxiliary.SwiftGetVersion.computeInputs(swiftCompilerPath: swiftCompilerPath)\n        let tool = WriteAuxiliaryFile(inputs: inputs, outputFilePath: swiftVersionFilePath, alwaysOutOfDate: true)\n        let name = swiftVersionFilePath.pathString\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addWriteInfoPlistCommand(principalClass: String, outputPath: Basics.AbsolutePath) {\n        let inputs = WriteAuxiliary.XCTestInfoPlist.computeInputs(principalClass: principalClass)\n        let tool = WriteAuxiliaryFile(inputs: inputs, outputFilePath: outputPath)\n        let name = outputPath.pathString\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addWriteEmbeddedResourcesCommand(\n        resources: [Basics.AbsolutePath],\n        outputPath: Basics.AbsolutePath\n    ) {\n        let inputs = WriteAuxiliary.EmbeddedResources.computeInputs(resources: resources)\n        let tool = WriteAuxiliaryFile(inputs: inputs, outputFilePath: outputPath)\n        let name = outputPath.pathString\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addPkgStructureCmd(\n        name: String,\n        inputs: [Node],\n        outputs: [Node]\n    ) {\n        let tool = PackageStructureTool(inputs: inputs, outputs: outputs)\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addShellCmd(\n        name: String,\n        description: String,\n        inputs: [Node],\n        outputs: [Node],\n        arguments: [String],\n        environment: Environment = [:],\n        workingDirectory: String? = nil,\n        allowMissingInputs: Bool = false\n    ) {\n        let tool = ShellTool(\n            description: description,\n            inputs: inputs,\n            outputs: outputs,\n            arguments: arguments,\n            environment: environment,\n            workingDirectory: workingDirectory,\n            allowMissingInputs: allowMissingInputs\n        )\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addSwiftFrontendCmd(\n        name: String,\n        moduleName: String,\n        packageName: String,\n        description: String,\n        inputs: [Node],\n        outputs: [Node],\n        arguments: [String]\n    ) {\n        let tool = SwiftFrontendTool(\n                moduleName: moduleName,\n                description: description,\n                inputs: inputs,\n                outputs: outputs,\n                arguments: arguments\n        )\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addClangCmd(\n        name: String,\n        description: String,\n        inputs: [Node],\n        outputs: [Node],\n        arguments: [String],\n        dependencies: String? = nil\n    ) {\n        let tool = ClangTool(\n            description: description,\n            inputs: inputs,\n            outputs: outputs,\n            arguments: arguments,\n            dependencies: dependencies\n        )\n        addCommand(name: name, tool: tool)\n    }\n\n    public mutating func addSwiftCmd(\n        name: String,\n        inputs: [Node],\n        outputs: [Node],\n        executable: Basics.AbsolutePath,\n        moduleName: String,\n        moduleAliases: [String: String]?,\n        moduleOutputPath: Basics.AbsolutePath,\n        importPath: Basics.AbsolutePath,\n        tempsPath: Basics.AbsolutePath,\n        objects: [Basics.AbsolutePath],\n        otherArguments: [String],\n        sources: [Basics.AbsolutePath],\n        fileList: Basics.AbsolutePath,\n        isLibrary: Bool,\n        wholeModuleOptimization: Bool,\n        outputFileMapPath: Basics.AbsolutePath,\n        prepareForIndexing: Bool\n    ) {\n        let tool = SwiftCompilerTool(\n            inputs: inputs,\n            outputs: outputs,\n            executable: executable,\n            moduleName: moduleName,\n            moduleAliases: moduleAliases,\n            moduleOutputPath: moduleOutputPath,\n            importPath: importPath,\n            tempsPath: tempsPath,\n            objects: objects,\n            otherArguments: otherArguments,\n            sources: sources,\n            fileList: fileList,\n            isLibrary: isLibrary,\n            wholeModuleOptimization: wholeModuleOptimization,\n            outputFileMapPath: outputFileMapPath,\n            prepareForIndexing: prepareForIndexing\n        )\n        addCommand(name: name, tool: tool)\n    }\n}\n"
  },
  {
    "path": "Sources/LLBuildManifest/LLBuildManifestWriter.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nprivate let namesToExclude = [\".git\", \".build\"]\n\npublic struct LLBuildManifestWriter {\n    private let manifest: LLBuildManifest\n    // FIXME: since JSON is a superset of YAML and we don't need to parse these manifests,\n    // we should just use `JSONEncoder` instead.\n    private var buffer = \"\"\"\n    client:\n      name: basic\n      file-system: device-agnostic\n    tools: {}\n\n    \"\"\"\n\n    private init(manifest: LLBuildManifest) {\n        self.manifest = manifest\n\n        self.render(targets: manifest.targets)\n\n        self.buffer += \"default: \\(manifest.defaultTarget.asJSON)\\n\"\n\n        self.render(nodes: manifest.commands.values.flatMap { $0.tool.inputs + $0.tool.outputs })\n\n        self.render(commands: manifest.commands)\n    }\n\n    public static func write(_ manifest: LLBuildManifest, at path: AbsolutePath, fileSystem: FileSystem) throws {\n        let writer = LLBuildManifestWriter(manifest: manifest)\n\n        try fileSystem.writeFileContents(path, string: writer.buffer)\n    }\n\n    private mutating func render(targets: [LLBuildManifest.TargetName: Target]) {\n        self.buffer += \"targets:\\n\"\n        for (_, target) in targets.sorted(by: { $0.key < $1.key }) {\n            self.buffer += \"  \\(target.name.asJSON): \\(target.nodes.map(\\.name).sorted().asJSON)\\n\"\n        }\n    }\n\n    private mutating func render(nodes: [Node]) {\n        // We need to explicitly configure certain kinds of nodes.\n        let directoryStructureNodes = Set(nodes.filter { $0.kind == .directoryStructure })\n            .sorted(by: { $0.name < $1.name })\n        let commandTimestampNodes = Set(nodes.filter { $0.attributes?.isCommandTimestamp == true })\n            .sorted(by: { $0.name < $1.name })\n        let mutatedNodes = Set(nodes.filter { $0.attributes?.isMutated == true })\n            .sorted(by: { $0.name < $1.name })\n\n        if !directoryStructureNodes.isEmpty || !mutatedNodes.isEmpty || !commandTimestampNodes.isEmpty {\n            self.buffer += \"nodes:\\n\"\n        }\n\n        for node in directoryStructureNodes {\n            self.render(directoryStructure: node)\n        }\n\n        for node in commandTimestampNodes {\n            self.render(isCommandTimestamp: node)\n        }\n\n        for node in mutatedNodes {\n            self.render(isMutated: node)\n        }\n    }\n\n    private mutating func render(directoryStructure node: Node) {\n        self.buffer += \"\"\"\n          \\(node.asJSON):\n            is-directory-structure: true\n            content-exclusion-patterns: \\(namesToExclude.asJSON)\n\n        \"\"\"\n    }\n\n    private mutating func render(isCommandTimestamp node: Node) {\n        self.buffer += \"\"\"\n          \\(node.asJSON):\n            is-command-timestamp: true\n\n        \"\"\"\n    }\n\n    private mutating func render(isMutated node: Node) {\n        self.buffer += \"\"\"\n          \\(node.asJSON):\n            is-mutated: true\n\n        \"\"\"\n    }\n\n    private mutating func render(commands: [LLBuildManifest.CmdName: Command]) {\n        self.buffer += \"commands:\\n\"\n        for (_, command) in commands.sorted(by: { $0.key < $1.key }) {\n            self.buffer += \"  \\(command.name.asJSON):\\n\"\n\n            let tool = command.tool\n\n            var manifestToolWriter = ManifestToolStream()\n            manifestToolWriter[\"tool\"] = tool\n            manifestToolWriter[\"inputs\"] = tool.inputs\n            manifestToolWriter[\"outputs\"] = tool.outputs\n\n            if tool.alwaysOutOfDate {\n                manifestToolWriter[\"always-out-of-date\"] = \"true\"\n            }\n\n            tool.write(to: &manifestToolWriter)\n\n            self.buffer += \"\\(manifestToolWriter.buffer)\\n\"\n        }\n    }\n}\n\npublic struct ManifestToolStream {\n    fileprivate var buffer = \"\"\n\n    public subscript(key: String) -> Int {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return an Int\") }\n        set {\n            self.buffer += \"    \\(key): \\(newValue.description.asJSON)\\n\"\n        }\n    }\n\n    public subscript(key: String) -> String {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return a String\") }\n        set {\n            self.buffer += \"    \\(key): \\(newValue.asJSON)\\n\"\n        }\n    }\n\n    public subscript(key: String) -> ToolProtocol {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return a ToolProtocol\") }\n        set {\n            self.buffer += \"    \\(key): \\(type(of: newValue).name)\\n\"\n        }\n    }\n\n    public subscript(key: String) -> AbsolutePath {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return an AbsolutePath\") }\n        set {\n            self.buffer += \"    \\(key): \\(newValue.pathString.asJSON)\\n\"\n        }\n    }\n\n    public subscript(key: String) -> [AbsolutePath] {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return an array of AbsolutePath\") }\n        set {\n            self.buffer += \"    \\(key): \\(newValue.map(\\.pathString).asJSON)\\n\"\n        }\n    }\n\n    public subscript(key: String) -> [Node] {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return an array of Node\") }\n        set {\n            self.buffer += \"    \\(key): \\(newValue.map(\\.encodingName).asJSON)\\n\"\n        }\n    }\n\n    public subscript(key: String) -> Bool {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return a Bool\") }\n        set {\n            self.buffer += \"    \\(key): \\(newValue.description)\\n\"\n        }\n    }\n\n    public subscript(key: String) -> [String] {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return an array of String\") }\n        set {\n            self.buffer += \"    \\(key): \\(newValue.asJSON)\\n\"\n        }\n    }\n\n    public subscript(key: String) -> [String: String] {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return a [String: String]\") }\n        set {\n            self.buffer += \"    \\(key):\\n\"\n            for (key, value) in newValue.sorted(by: { $0.key < $1.key }) {\n                self.buffer += \"      \\(key.asJSON): \\(value.asJSON)\\n\"\n            }\n        }\n    }\n\n    package subscript(key: String) -> Environment {\n        get { fatalError(\"\\(#file):\\(#line) at function \\(#function) - Cannot get subscript that return an Environment\") }\n        set {\n            self.buffer += \"    \\(key):\\n\"\n            for (key, value) in newValue.sorted(by: { $0.key < $1.key }) {\n                self.buffer += \"      \\(key.rawValue.asJSON): \\(value.asJSON)\\n\"\n            }\n        }\n    }\n}\n\nextension [String] {\n    fileprivate var asJSON: String {\n        \"\"\"\n        [\\(self.map(\\.asJSON).joined(separator: \",\"))]\n        \"\"\"\n    }\n}\n\nextension Node {\n    fileprivate var asJSON: String {\n        self.encodingName.asJSON\n    }\n}\n\nextension Node {\n    fileprivate var encodingName: String {\n        switch kind {\n        case .virtual, .file:\n            return name\n        case .directory, .directoryStructure:\n            return name + \"/\"\n        }\n    }\n}\n\nextension String {\n    fileprivate var asJSON: String {\n        \"\\\"\\(self.jsonEscaped)\\\"\"\n    }\n\n    private var jsonEscaped: String {\n        // See RFC7159 for reference: https://tools.ietf.org/html/rfc7159\n        String(decoding: self.utf8.flatMap { character -> [UInt8] in\n            // Handle string escapes; we use constants here to directly match the RFC.\n            switch character {\n            // Literal characters.\n            case 0x20 ... 0x21, 0x23 ... 0x5B, 0x5D ... 0xFF:\n                return [character]\n\n            // Single-character escaped characters.\n            case 0x22: // '\"'\n                return [\n                    0x5C, // '\\'\n                    0x22, // '\"'\n                ]\n            case 0x5C: // '\\\\'\n                return [\n                    0x5C, // '\\'\n                    0x5C, // '\\'\n                ]\n            case 0x08: // '\\b'\n                return [\n                    0x5C, // '\\'\n                    0x62, // 'b'\n                ]\n            case 0x0C: // '\\f'\n                return [\n                    0x5C, // '\\'\n                    0x66, // 'b'\n                ]\n            case 0x0A: // '\\n'\n                return [\n                    0x5C, // '\\'\n                    0x6E, // 'n'\n                ]\n            case 0x0D: // '\\r'\n                return [\n                    0x5C, // '\\'\n                    0x72, // 'r'\n                ]\n            case 0x09: // '\\t'\n                return [\n                    0x5C, // '\\'\n                    0x74, // 't'\n                ]\n\n            // Multi-character escaped characters.\n            default:\n                return [\n                    0x5C, // '\\'\n                    0x75, // 'u'\n                    hexdigit(0),\n                    hexdigit(0),\n                    hexdigit(character >> 4),\n                    hexdigit(character & 0xF),\n                ]\n            }\n        }, as: UTF8.self)\n    }\n}\n\n/// Convert an integer in 0..<16 to its hexadecimal ASCII character.\nprivate func hexdigit(_ value: UInt8) -> UInt8 {\n    value < 10 ? (0x30 + value) : (0x41 + value - 10)\n}\n"
  },
  {
    "path": "Sources/LLBuildManifest/Node.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\npublic struct Node: Hashable, Codable {\n    public enum Kind: String, Hashable, Codable {\n        case virtual\n        case file\n        case directory\n        case directoryStructure\n    }\n\n    struct Attributes: Hashable, Codable {\n        var isMutated = false\n        var isCommandTimestamp = false\n    }\n\n    /// The name used to identify the node.\n    public var name: String\n\n    /// The kind of node.\n    public var kind: Kind\n\n    let attributes: Attributes?\n\n    private init(name: String, kind: Kind, attributes: Attributes? = nil) {\n        self.name = name\n        self.kind = kind\n        self.attributes = attributes\n    }\n    \n    /// Extracts `name` property if this node was constructed as `Node//virtual`.\n    public var extractedVirtualNodeName: String {\n        precondition(kind == .virtual)\n        return String(self.name.dropFirst().dropLast())\n    }\n\n    public static func virtual(_ name: String, isCommandTimestamp: Bool = false) -> Node {\n        precondition(name.first != \"<\" && name.last != \">\", \"<> will be inserted automatically\")\n        return Node(\n            name: \"<\" + name + \">\",\n            kind: .virtual,\n            attributes: isCommandTimestamp ? .init(isCommandTimestamp: isCommandTimestamp) : nil\n        )\n    }\n\n    public static func file(_ name: AbsolutePath) -> Node {\n        Node(name: name.pathString, kind: .file)\n    }\n\n    public static func file(_ name: AbsolutePath, isMutated: Bool) -> Node {\n        Node(\n            name: name.pathString,\n            kind: .file,\n            attributes: .init(isMutated: isMutated)\n        )\n    }\n\n    public static func directory(_ name: AbsolutePath) -> Node {\n        Node(name: name.pathString, kind: .directory)\n    }\n\n    public static func directoryStructure(_ name: AbsolutePath) -> Node {\n        Node(name: name.pathString, kind: .directoryStructure)\n    }\n}\n\nextension Array where Element == Node {\n    public mutating func append(file path: AbsolutePath) {\n        self.append(.file(path))\n    }\n\n    public mutating func append(directory path: AbsolutePath) {\n        self.append(.directory(path))\n    }\n\n    public mutating func append(directoryStructure path: AbsolutePath) {\n        self.append(.directoryStructure(path))\n    }\n}\n"
  },
  {
    "path": "Sources/LLBuildManifest/Target.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct Target {\n    /// The name of the target.\n    public var name: String\n\n    /// The list of nodes that should be computed to build this target.\n    public var nodes: [Node]\n\n    public init(name: String, nodes: [Node]) {\n        self.name = name\n        self.nodes = nodes\n    }\n}\n"
  },
  {
    "path": "Sources/LLBuildManifest/Tools.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport class Foundation.ProcessInfo\n\npublic protocol ToolProtocol: Codable {\n    /// The name of the tool.\n    static var name: String { get }\n\n    /// Whether or not the tool should run on every build instead of using dependency tracking.\n    var alwaysOutOfDate: Bool { get }\n\n    /// The list of inputs to declare.\n    var inputs: [Node] { get }\n\n    /// The list of outputs to declare.\n    var outputs: [Node] { get }\n\n    /// Write a description of the tool to the given output `stream`.\n    func write(to stream: inout ManifestToolStream)\n}\n\nextension ToolProtocol {\n    public var alwaysOutOfDate: Bool { return false }\n\n    public func write(to stream: inout ManifestToolStream) {}\n}\n\npublic struct PhonyTool: ToolProtocol {\n    public static let name: String = \"phony\"\n\n    public var inputs: [Node]\n    public var outputs: [Node]\n\n    init(inputs: [Node], outputs: [Node]) {\n        self.inputs = inputs\n        self.outputs = outputs\n    }\n}\n\npublic struct TestDiscoveryTool: ToolProtocol {\n    public static let name: String = \"test-discovery-tool\"\n    public static let mainFileName: String = \"all-discovered-tests.swift\"\n\n    public var inputs: [Node]\n    public var outputs: [Node]\n\n    init(inputs: [Node], outputs: [Node]) {\n        self.inputs = inputs\n        self.outputs = outputs\n    }\n}\n\npublic struct TestEntryPointTool: ToolProtocol {\n    public static let name: String = \"test-entry-point-tool\"\n\n    public var inputs: [Node]\n    public var outputs: [Node]\n\n    init(inputs: [Node], outputs: [Node]) {\n        self.inputs = inputs\n        self.outputs = outputs\n    }\n}\n\npublic struct CopyTool: ToolProtocol {\n    public static let name: String = \"copy-tool\"\n\n    public var inputs: [Node]\n    public var outputs: [Node]\n\n    init(inputs: [Node], outputs: [Node]) {\n        self.inputs = inputs\n        self.outputs = outputs\n    }\n\n    public func write(to stream: inout ManifestToolStream) {\n        stream[\"description\"] = \"Copying \\(inputs[0].name)\"\n    }\n}\n\n/// Package structure tool is used to determine if the package has changed in some way\n/// that requires regenerating the build manifest file. This allows us to skip a lot of\n/// redundant work (package graph loading, build planning, manifest generation) during\n/// incremental builds.\npublic struct PackageStructureTool: ToolProtocol {\n    public static let name: String = \"package-structure-tool\"\n\n    public var inputs: [Node]\n    public var outputs: [Node]\n\n    init(inputs: [Node], outputs: [Node]) {\n        self.inputs = inputs\n        self.outputs = outputs\n    }\n\n    public func write(to stream: inout ManifestToolStream) {\n        stream[\"description\"] = \"Planning build\"\n        stream[\"allow-missing-inputs\"] = true\n    }\n}\n\npublic struct ShellTool: ToolProtocol {\n    public static let name: String = \"shell\"\n\n    public var description: String\n    public var inputs: [Node]\n    public var outputs: [Node]\n    public var arguments: [String]\n    public var environment: Environment\n    public var workingDirectory: String?\n    public var allowMissingInputs: Bool\n\n    init(\n        description: String,\n        inputs: [Node],\n        outputs: [Node],\n        arguments: [String],\n        environment: Environment,\n        workingDirectory: String? = nil,\n        allowMissingInputs: Bool = false\n    ) {\n        self.description = description\n        self.inputs = inputs\n        self.outputs = outputs\n        self.arguments = arguments\n        self.environment = environment\n        self.workingDirectory = workingDirectory\n        self.allowMissingInputs = allowMissingInputs\n    }\n\n    public func write(to stream: inout ManifestToolStream) {\n        stream[\"description\"] = description\n        stream[\"args\"] = arguments\n        if !environment.isEmpty {\n            stream[\"env\"] = environment\n        }\n        if let workingDirectory {\n            stream[\"working-directory\"] = workingDirectory\n        }\n        if allowMissingInputs {\n            stream[\"allow-missing-inputs\"] = true\n        }\n    }\n}\n\npublic struct WriteAuxiliaryFile: Equatable, ToolProtocol {\n    public static let name: String = \"write-auxiliary-file\"\n\n    public let inputs: [Node]\n    private let outputFilePath: AbsolutePath\n    public let alwaysOutOfDate: Bool\n\n    public init(inputs: [Node], outputFilePath: AbsolutePath, alwaysOutOfDate: Bool = false) {\n        self.inputs = inputs\n        self.outputFilePath = outputFilePath\n        self.alwaysOutOfDate = alwaysOutOfDate\n    }\n\n    public var outputs: [Node] {\n        return [.file(outputFilePath)]\n    }\n\n    public func write(to stream: inout ManifestToolStream) {\n        stream[\"description\"] = \"Write auxiliary file \\(outputFilePath.pathString)\"\n    }\n}\n\npublic struct ClangTool: ToolProtocol {\n    public static let name: String = \"clang\"\n\n    public var description: String\n    public var inputs: [Node]\n    public var outputs: [Node]\n    public var arguments: [String]\n    public var dependencies: String?\n\n    init(\n        description: String,\n        inputs: [Node],\n        outputs: [Node],\n        arguments: [String],\n        dependencies: String? = nil\n    ) {\n        self.description = description\n        self.inputs = inputs\n        self.outputs = outputs\n        self.arguments = arguments\n        self.dependencies = dependencies\n    }\n\n    public func write(to stream: inout ManifestToolStream) {\n        stream[\"description\"] = description\n        stream[\"args\"] = arguments\n        if let dependencies {\n            stream[\"deps\"] = dependencies\n        }\n    }\n}\n\npublic struct ArchiveTool: ToolProtocol {\n    public static let name: String = \"archive\"\n\n    public var inputs: [Node]\n    public var outputs: [Node]\n\n    init(inputs: [Node], outputs: [Node]) {\n        self.inputs = inputs\n        self.outputs = outputs\n    }\n}\n\n/// Swift frontend tool, which maps down to a shell tool.\npublic struct SwiftFrontendTool: ToolProtocol {\n    public static let name: String = \"shell\"\n\n    public let moduleName: String\n    public var description: String\n    public var inputs: [Node]\n    public var outputs: [Node]\n    public var arguments: [String]\n\n    init(\n        moduleName: String,\n        description: String,\n        inputs: [Node],\n        outputs: [Node],\n        arguments: [String]\n    ) {\n        self.moduleName = moduleName\n        self.description = description\n        self.inputs = inputs\n        self.outputs = outputs\n        self.arguments = arguments\n    }\n\n    public func write(to stream: inout ManifestToolStream) {\n        ShellTool(description: description, inputs: inputs, outputs: outputs, arguments: arguments, environment: [:]).write(to: &stream)\n    }\n}\n\n/// Swift compiler llbuild tool.\npublic struct SwiftCompilerTool: ToolProtocol {\n    public static let name: String = \"shell\"\n\n    public static let numThreads: Int = ProcessInfo.processInfo.activeProcessorCount\n\n    public var inputs: [Node]\n    public var outputs: [Node]\n\n    public var executable: AbsolutePath\n    public var moduleName: String\n    public var moduleAliases: [String: String]?\n    public var moduleOutputPath: AbsolutePath\n    public var importPath: AbsolutePath\n    public var tempsPath: AbsolutePath\n    public var objects: [AbsolutePath]\n    public var otherArguments: [String]\n    public var sources: [AbsolutePath]\n    public var fileList: AbsolutePath\n    public var isLibrary: Bool\n    public var wholeModuleOptimization: Bool\n    public var outputFileMapPath: AbsolutePath\n    public var prepareForIndexing: Bool\n\n    init(\n        inputs: [Node],\n        outputs: [Node],\n        executable: AbsolutePath,\n        moduleName: String,\n        moduleAliases: [String: String]?,\n        moduleOutputPath: AbsolutePath,\n        importPath: AbsolutePath,\n        tempsPath: AbsolutePath,\n        objects: [AbsolutePath],\n        otherArguments: [String],\n        sources: [AbsolutePath],\n        fileList: AbsolutePath,\n        isLibrary: Bool,\n        wholeModuleOptimization: Bool,\n        outputFileMapPath: AbsolutePath,\n        prepareForIndexing: Bool\n    ) {\n        self.inputs = inputs\n        self.outputs = outputs\n        self.executable = executable\n        self.moduleName = moduleName\n        self.moduleAliases = moduleAliases\n        self.moduleOutputPath = moduleOutputPath\n        self.importPath = importPath\n        self.tempsPath = tempsPath\n        self.objects = objects\n        self.otherArguments = otherArguments\n        self.sources = sources\n        self.fileList = fileList\n        self.isLibrary = isLibrary\n        self.wholeModuleOptimization = wholeModuleOptimization\n        self.outputFileMapPath = outputFileMapPath\n        self.prepareForIndexing = prepareForIndexing\n    }\n\n    var description: String {\n        return \"Compiling Swift Module '\\(moduleName)' (\\(sources.count) sources)\"\n    }\n\n    var arguments: [String] {\n        var arguments = [\n            executable.pathString,\n            \"-module-name\", moduleName,\n        ]\n        if let moduleAliases = moduleAliases {\n            for (original, alias) in moduleAliases {\n                arguments += [\"-module-alias\", \"\\(original)=\\(alias)\"]\n            }\n        }\n        arguments += [\n            \"-emit-dependencies\",\n            \"-emit-module\",\n            \"-emit-module-path\", moduleOutputPath.pathString,\n            \"-output-file-map\", outputFileMapPath.pathString,\n        ]\n        if isLibrary {\n            arguments += [\"-parse-as-library\"]\n        }\n        if wholeModuleOptimization {\n            arguments += [\"-whole-module-optimization\", \"-num-threads\", \"\\(Self.numThreads)\"]\n        } else {\n            arguments += [\"-incremental\"]\n        }\n        if !prepareForIndexing {\n            arguments += [\"-c\"]\n        }\n        arguments += [\"@\\(self.fileList.pathString)\"]\n        arguments += [\"-I\", importPath.pathString]\n        arguments += otherArguments\n        return arguments\n    }\n\n    public func write(to stream: inout ManifestToolStream) {\n        ShellTool(description: description, inputs: inputs, outputs: outputs, arguments: arguments, environment: [:]).write(to: &stream)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/API.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\nimport PackageModel\nimport SourceControl\nimport Basics\n\n// MARK: - Package collection\n\npublic protocol PackageCollectionsProtocol {\n    // MARK: - Package collection APIs\n\n    /// Returns packages organized into collections.\n    ///\n    /// Package collections are not mutually exclusive; a package may belong to more than one collection. As such,\n    /// the ordering of `PackageCollection`s should be preserved and respected during conflict resolution.\n    ///\n    /// - Parameters:\n    ///   - identifiers: Optional. If specified, only `PackageCollection`s with matching identifiers will be returned.\n    func listCollections(\n        identifiers: Set<PackageCollectionsModel.CollectionIdentifier>?\n    ) async throws -> [PackageCollectionsModel.Collection]\n\n    /// Refreshes all configured package collections.\n    func refreshCollections() async throws -> [PackageCollectionsModel.CollectionSource]\n\n    /// Refreshes a package collection.\n    ///\n    /// - Parameters:\n    ///   - source: The package collection to be refreshed\n    func refreshCollection(\n        _ source: PackageCollectionsModel.CollectionSource\n    ) async throws -> PackageCollectionsModel.Collection\n\n    /// Adds a package collection.\n    ///\n    /// - Parameters:\n    ///   - source: The package collection's source\n    ///   - order: Optional. The order that the `PackageCollection` should take after being added to the list.\n    ///            By default the new collection is appended to the end (i.e., the least relevant order).\n    ///   - trustConfirmationProvider: The closure to invoke when the collection is not signed and user confirmation is required to proceed\n    func addCollection(\n        _ source: PackageCollectionsModel.CollectionSource,\n        order: Int?,\n        trustConfirmationProvider: ((PackageCollectionsModel.Collection, @escaping (Bool) -> Void) -> Void)?\n    ) async throws -> PackageCollectionsModel.Collection\n\n    /// Removes a package collection.\n    ///\n    /// - Parameters:\n    ///   - source: The package collection's source\n    func removeCollection(\n        _ source: PackageCollectionsModel.CollectionSource\n    ) async throws\n\n    /// Moves a package collection to a different order.\n    ///\n    /// - Parameters:\n    ///   - source: The source of the `PackageCollection` to be reordered\n    ///   - order: The new order that the `PackageCollection` should be positioned after the move\n    func moveCollection(\n        _ source: PackageCollectionsModel.CollectionSource,\n        to order: Int\n    ) async throws\n\n    /// Updates settings of a `PackageCollection` source (e.g., if it is trusted or not).\n    ///\n    /// - Parameters:\n    ///   - source: The `PackageCollection` source to be updated\n    func updateCollection(\n        _ source: PackageCollectionsModel.CollectionSource\n    ) async throws -> PackageCollectionsModel.Collection\n\n    /// Returns information about a package collection. The collection is not required to be in the configured list. If\n    /// not found locally, the collection will be fetched from the source.\n    ///\n    /// - Parameters:\n    ///   - source: The package collection's source\n    func getCollection(\n        _ source: PackageCollectionsModel.CollectionSource\n    ) async throws -> PackageCollectionsModel.Collection\n\n    /// Returns metadata for the package identified by the given `PackageIdentity`, along with the\n    /// identifiers of `PackageCollection`s where the package is found.\n    ///\n    /// A failure is returned if the package is not found.\n    ///\n    /// - Parameters:\n    ///   - identity: The package identity\n    ///   - location: The package location (optional for deduplication)\n    ///   - collections: Optional. If specified, only look for package in these collections. Data from the most recently\n    ///                  processed collection will be used.\n    func getPackageMetadata(\n        identity: PackageIdentity,\n        location: String?,\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>?\n    ) async throws -> PackageCollectionsModel.PackageMetadata\n\n    /// Lists packages from the specified collections.\n    ///\n    /// - Parameters:\n    ///   - collections: Optional. If specified, only packages in these collections are included.\n    func listPackages(\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>?\n    ) async throws -> PackageCollectionsModel.PackageSearchResult\n\n    // MARK: - Target (Module) APIs\n\n    /// List all known targets.\n    ///\n    /// A target name may be found in different packages and/or different versions of a package, and a package\n    /// may belong to multiple package collections. This API's result items will be consolidated by target then package,\n    /// with the package's versions list filtered to only include those that contain the target.\n    ///\n    /// - Parameters:\n    ///   - collections: Optional. If specified, only list targets within these collections.\n    func listTargets(\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>?\n    ) async throws -> PackageCollectionsModel.TargetListResult\n\n    // MARK: - Search APIs\n\n    /// Finds and returns packages that match the query.\n    ///\n    /// If applicable, for example when we search by package name which might change between versions,\n    /// the versions list in the result will be filtered to only include those matching the query.\n    ///\n    /// - Parameters:\n    ///   - query: The search query\n    ///   - collections: Optional. If specified, only search within these collections.\n    func findPackages(\n        _ query: String,\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>?\n    ) async throws -> PackageCollectionsModel.PackageSearchResult\n\n    /// Finds targets by name and returns the corresponding packages.\n    ///\n    /// This API's result items will be consolidated by target then package, with the\n    /// package's versions list filtered to only include those that contain the target.\n    ///\n    /// - Parameters:\n    ///   - query: The search query\n    ///   - searchType: Optional. Target names must either match exactly or contain the prefix.\n    ///                 For more flexibility, use the `findPackages` API instead.\n    ///   - collections: Optional. If specified, only search within these collections.\n    func findTargets(\n        _ query: String,\n        searchType: PackageCollectionsModel.TargetSearchType?,\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>?\n    ) async throws -> PackageCollectionsModel.TargetSearchResult\n}\n\n\npublic enum PackageCollectionError: Equatable, Error {\n    /// Package collection is not signed and there is no record of user's trust selection\n    case trustConfirmationRequired\n\n    /// Package collection is not signed and user explicitly marks it untrusted\n    case untrusted\n\n    /// There are no trusted root certificates. Signature check cannot be done in this case since it involves validating\n    /// the certificate chain that is used for signing and one requirement is that the root certificate must be trusted.\n    case cannotVerifySignature\n\n    case invalidSignature\n\n    case missingSignature\n\n    case unsupportedPlatform\n}\n\n// MARK: - Package index\n\npublic protocol PackageIndexProtocol {\n    /// Returns true if the package index is configured.\n    var isEnabled: Bool { get }\n    \n    /// Returns metadata for the package identified by the given `PackageIdentity`.\n    ///\n    /// A failure is returned if the package is not found.\n    ///\n    /// - Parameters:\n    ///   - identity: The package identity\n    ///   - location: The package location (optional for deduplication)\n    func getPackageMetadata(\n        identity: PackageIdentity,\n        location: String?\n    ) async throws -> PackageCollectionsModel.PackageMetadata\n\n    /// Finds and returns packages that match the query.\n    ///\n    /// - Parameters:\n    ///   - query: The search query\n    func findPackages(\n        _ query: String\n    ) async throws -> PackageCollectionsModel.PackageSearchResult\n\n    /// A paginated list of packages in the index.\n    ///\n    /// - Parameters:\n    ///   - offset: Offset of the first item in the result\n    ///   - limit: Number of items to return in the result. Implementations might impose a threshold for this.\n    func listPackages(\n        offset: Int,\n        limit: Int\n    ) async throws -> PackageCollectionsModel.PaginatedPackageList\n}\n\npublic enum PackageIndexError: Equatable, Error {\n    /// Package index support is disabled\n    case featureDisabled\n    /// No package index configured\n    case notConfigured\n    \n    case invalidURL(URL)\n    case invalidResponse(URL, String)\n}\n"
  },
  {
    "path": "Sources/PackageCollections/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageCollections\n  API.swift\n  Model/CVE.swift\n  Model/Collection.swift\n  Model/License.swift\n  Model/PackageList.swift\n  Model/PackageTypes.swift\n  Model/Search.swift\n  Model/TargetListResult.swift\n  PackageCollections+CertificatePolicy.swift\n  PackageCollections+Configuration.swift\n  PackageCollections+Storage.swift\n  PackageCollections+Validation.swift\n  PackageCollections.swift\n  PackageIndex+Configuration.swift\n  PackageIndex.swift\n  PackageIndexAndCollections.swift\n  Providers/GitHubPackageMetadataProvider.swift\n  Providers/JSONPackageCollectionProvider.swift\n  Providers/PackageCollectionProvider.swift\n  Providers/PackageMetadataProvider.swift\n  Storage/FilePackageCollectionsSourcesStorage.swift\n  Storage/PackageCollectionsSourcesStorage.swift\n  Storage/PackageCollectionsStorage.swift\n  Storage/SQLitePackageCollectionsStorage.swift\n  Storage/Trie.swift\n  Utility.swift)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageCollections PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\ntarget_link_libraries(PackageCollections PUBLIC\n  Basics\n  PackageCollectionsModel\n  PackageCollectionsSigning\n  PackageModel\n  SourceControl\n  TSCBasic\n  TSCUtility)\nif(NOT APPLE)\n  if(Foundation_FOUND)\n    target_link_directories(PackageCollections PRIVATE\n      $<TARGET_LINKER_FILE_DIR:Fooundation>)\n  endif()\n  if(dispatch_FOUND)\n    target_link_directories(PackageCollections PRIVATE\n      $<TARGET_LINKER_FILE_DIR:Dispatch>)\n  endif()\nendif()\n\ninstall(TARGETS PackageCollections\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/PackageCollections/Model/CVE.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\n\nextension PackageCollectionsModel {\n    /// A representation of Common Vulnerabilities and Exposures (CVE)\n    public struct CVE: Equatable {\n        /// CVE identifier\n        public let identifier: String\n\n        /// URL of the CVE\n        public let url: URL\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Model/Collection.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport struct Foundation.Date\nimport struct Foundation.URL\nimport PackageModel\nimport SourceControl\n\npublic enum PackageCollectionsModel {}\n\n// make things less verbose internally\ninternal typealias Model = PackageCollectionsModel\n\nextension PackageCollectionsModel {\n    /// A `Collection` is a collection of packages.\n    public struct Collection: Equatable, Codable {\n        public typealias Identifier = CollectionIdentifier\n        public typealias Source = CollectionSource\n\n        /// The identifier of the collection\n        public let identifier: Identifier\n\n        /// Where the collection and its contents are obtained\n        public internal(set) var source: Source\n\n        /// The name of the collection\n        public let name: String\n\n        /// The description of the collection\n        public let overview: String?\n\n        /// Keywords for the collection\n        public let keywords: [String]?\n\n        /// Metadata of packages belonging to the collection\n        public let packages: [Package]\n\n        /// When this collection was created/published by the source\n        public let createdAt: Date\n\n        /// Who authored this collection\n        public let createdBy: Author?\n\n        /// When this collection was last processed locally\n        public let lastProcessedAt: Date\n\n        /// The collection's signature metadata\n        public let signature: SignatureData?\n\n        /// Indicates if the collection is signed\n        public var isSigned: Bool {\n            self.signature != nil\n        }\n\n        /// Initializes a `Collection`\n        init(\n            source: Source,\n            name: String,\n            overview: String?,\n            keywords: [String]?,\n            packages: [Package],\n            createdAt: Date,\n            createdBy: Author?,\n            signature: SignatureData?,\n            lastProcessedAt: Date = Date()\n        ) {\n            self.identifier = .init(from: source)\n            self.source = source\n            self.name = name\n            self.overview = overview\n            self.keywords = keywords\n            self.packages = packages\n            self.createdAt = createdAt\n            self.createdBy = createdBy\n            self.signature = signature\n            self.lastProcessedAt = lastProcessedAt\n        }\n    }\n}\n\nextension PackageCollectionsModel {\n    /// Represents the source of a `Collection`\n    public struct CollectionSource: Equatable, Hashable, Codable {\n        /// Source type\n        public let type: CollectionSourceType\n\n        /// URL of the source file\n        public let url: URL\n\n        /// Indicates if the source is explicitly trusted or untrusted by the user\n        public var isTrusted: Bool?\n\n        /// Indicates if the source can skip signature validation\n        public var skipSignatureCheck: Bool\n\n        /// The source's absolute file system path, if its URL is of 'file' scheme.\n        let absolutePath: AbsolutePath?\n\n        public init(type: CollectionSourceType, url: URL, isTrusted: Bool? = nil, skipSignatureCheck: Bool = false) {\n            self.type = type\n            self.url = url\n            self.isTrusted = isTrusted\n            self.skipSignatureCheck = skipSignatureCheck\n\n            if url.scheme?.lowercased() == \"file\", let absolutePath = try? AbsolutePath(validating: url.path) {\n                self.absolutePath = absolutePath\n            } else {\n                self.absolutePath = nil\n            }\n        }\n\n        public static func == (lhs: CollectionSource, rhs: CollectionSource) -> Bool {\n            lhs.type == rhs.type && lhs.url == rhs.url\n        }\n\n        public func hash(into hasher: inout Hasher) {\n            hasher.combine(self.type)\n            hasher.combine(self.url)\n        }\n    }\n\n    /// Represents the source type of a `Collection`\n    public enum CollectionSourceType: String, Codable, CaseIterable {\n        case json\n    }\n}\n\nextension PackageCollectionsModel {\n    /// Represents the identifier of a `Collection`\n    public enum CollectionIdentifier: Hashable, Comparable {\n        /// JSON based package collection at URL\n        case json(URL)\n\n        /// Creates an `Identifier` from `Source`\n        init(from source: CollectionSource) {\n            switch source.type {\n            case .json:\n                self = .json(source.url)\n            }\n        }\n\n        public static func < (lhs: Self, rhs: Self) -> Bool {\n            switch (lhs, rhs) {\n            case (.json(let lhs), .json(let rhs)):\n                return lhs.absoluteString < rhs.absoluteString\n            }\n        }\n    }\n}\n\nextension PackageCollectionsModel.CollectionIdentifier: Codable {\n    public enum DiscriminatorKeys: String, Codable {\n        case json\n    }\n\n    public enum CodingKeys: CodingKey {\n        case _case\n        case url\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        switch try container.decode(DiscriminatorKeys.self, forKey: ._case) {\n        case .json:\n            let url = try container.decode(URL.self, forKey: .url)\n            self = .json(url)\n        }\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .json(let url):\n            try container.encode(DiscriminatorKeys.json, forKey: ._case)\n            try container.encode(url, forKey: .url)\n        }\n    }\n}\n\nextension PackageCollectionsModel.Collection {\n    /// Represents the author of a `Collection`\n    public struct Author: Equatable, Codable {\n        /// The name of the author\n        public let name: String\n    }\n}\n\nextension PackageCollectionsModel {\n    /// Package collection signature metadata\n    public struct SignatureData: Equatable, Codable {\n        /// Details about the certificate used to generate the signature\n        public let certificate: Certificate\n\n        /// Indicates if the signature has been validated. This is set to false if signature check didn't take place.\n        public let isVerified: Bool\n\n        public init(certificate: Certificate, isVerified: Bool) {\n            self.certificate = certificate\n            self.isVerified = isVerified\n        }\n\n        public struct Certificate: Equatable, Codable {\n            /// Subject of the certificate\n            public let subject: Name\n\n            /// Issuer of the certificate\n            public let issuer: Name\n\n            /// Creates a `Certificate`\n            public init(subject: Name, issuer: Name) {\n                self.subject = subject\n                self.issuer = issuer\n            }\n\n            /// Generic certificate name (e.g., subject, issuer)\n            public struct Name: Equatable, Codable {\n                /// User ID\n                public let userID: String?\n\n                /// Common name\n                public let commonName: String?\n\n                /// Organizational unit\n                public let organizationalUnit: String?\n\n                /// Organization\n                public let organization: String?\n\n                /// Creates a `Name`\n                public init(userID: String?,\n                            commonName: String?,\n                            organizationalUnit: String?,\n                            organization: String?) {\n                    self.userID = userID\n                    self.commonName = commonName\n                    self.organizationalUnit = organizationalUnit\n                    self.organization = organization\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Model/License.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\n\nextension PackageCollectionsModel {\n    /// A representation of a package license\n    public struct License: Equatable, Codable {\n        /// License type\n        public let type: LicenseType\n\n        /// URL of the license file\n        public let url: URL\n    }\n\n    /// An enum of license types\n    public enum LicenseType: Equatable, CaseIterable, CustomStringConvertible {\n        // This list is taken from https://opensource.org/licenses\n\n        /// Apache License 2.0\n        case Apache2_0\n\n        /// BSD 2-Clause license\n        case BSD2Clause\n\n        /// BSD 3-Clause license\n        case BSD3Clause\n\n        /// GNU General Public License 2.0\n        case GPL2_0\n\n        /// GNU General Public License 3.0\n        case GPL3_0\n\n        /// GNU Library General Public License 2.0\n        case LGPL2_0\n\n        /// GNU Library General Public License 2.1\n        case LGPL2_1\n\n        /// GNU Library General Public License 3.0\n        case LGPL3_0\n\n        /// MIT license\n        case MIT\n\n        /// Mozilla Public License 2.0\n        case MPL2_0\n\n        /// Common Development and Distribution License 1.0\n        case CDDL1_0\n\n        /// Eclipse Public License version 2.0\n        case EPL2_0\n\n        /// Other license type\n        case other(String?)\n\n        public var description: String {\n            switch self {\n            case .Apache2_0:\n                return \"Apache-2.0\"\n            case .BSD2Clause:\n                return \"BSD-2-Clause\"\n            case .BSD3Clause:\n                return \"BSD-3-Clause\"\n            case .GPL2_0:\n                return \"GPL-2.0\"\n            case .GPL3_0:\n                return \"GPL-3.0\"\n            case .LGPL2_0:\n                return \"LGPL-2.0\"\n            case .LGPL2_1:\n                return \"LGPL-2.1\"\n            case .LGPL3_0:\n                return \"LGPL-3.0\"\n            case .MIT:\n                return \"MIT\"\n            case .MPL2_0:\n                return \"MPL-2.0\"\n            case .CDDL1_0:\n                return \"CDDL-1.0\"\n            case .EPL2_0:\n                return \"EPL-2.0\"\n            case .other(let name):\n                return name ?? \"other\"\n            }\n        }\n\n        /// All except .other\n        public static var allCases: [LicenseType] {\n            [.Apache2_0, .BSD2Clause, .BSD3Clause, .GPL2_0, .GPL3_0, .LGPL2_0, .LGPL2_1, .LGPL3_0, .MIT, .MPL2_0, .CDDL1_0, .EPL2_0]\n        }\n    }\n}\n\nextension PackageCollectionsModel.LicenseType {\n    public init(string: String?) {\n        self = string.map { s in Self.allCases.first { $0.description.lowercased() == s.lowercased() } ?? .other(s) } ?? .other(nil)\n    }\n}\n\nextension PackageCollectionsModel.LicenseType: Codable {\n    public enum DiscriminatorKeys: String, Codable {\n        case Apache2_0\n        case BSD2Clause\n        case BSD3Clause\n        case GPL2_0\n        case GPL3_0\n        case LGPL2_0\n        case LGPL2_1\n        case LGPL3_0\n        case MIT\n        case MPL2_0\n        case CDDL1_0\n        case EPL2_0\n        case other\n    }\n\n    public enum CodingKeys: CodingKey {\n        case _case\n        case name\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        switch try container.decode(DiscriminatorKeys.self, forKey: ._case) {\n        case .Apache2_0:\n            self = .Apache2_0\n        case .BSD2Clause:\n            self = .BSD2Clause\n        case .BSD3Clause:\n            self = .BSD3Clause\n        case .GPL2_0:\n            self = .GPL2_0\n        case .GPL3_0:\n            self = .GPL3_0\n        case .LGPL2_0:\n            self = .LGPL2_0\n        case .LGPL2_1:\n            self = .LGPL2_1\n        case .LGPL3_0:\n            self = .LGPL3_0\n        case .MIT:\n            self = .MIT\n        case .MPL2_0:\n            self = .MPL2_0\n        case .CDDL1_0:\n            self = .CDDL1_0\n        case .EPL2_0:\n            self = .EPL2_0\n        case .other:\n            let name = try container.decode(String.self, forKey: .name)\n            self = .other(name)\n        }\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .Apache2_0:\n            try container.encode(DiscriminatorKeys.Apache2_0, forKey: ._case)\n        case .BSD2Clause:\n            try container.encode(DiscriminatorKeys.BSD2Clause, forKey: ._case)\n        case .BSD3Clause:\n            try container.encode(DiscriminatorKeys.BSD3Clause, forKey: ._case)\n        case .GPL2_0:\n            try container.encode(DiscriminatorKeys.GPL2_0, forKey: ._case)\n        case .GPL3_0:\n            try container.encode(DiscriminatorKeys.GPL3_0, forKey: ._case)\n        case .LGPL2_0:\n            try container.encode(DiscriminatorKeys.LGPL2_0, forKey: ._case)\n        case .LGPL2_1:\n            try container.encode(DiscriminatorKeys.LGPL2_1, forKey: ._case)\n        case .LGPL3_0:\n            try container.encode(DiscriminatorKeys.LGPL3_0, forKey: ._case)\n        case .MIT:\n            try container.encode(DiscriminatorKeys.MIT, forKey: ._case)\n        case .MPL2_0:\n            try container.encode(DiscriminatorKeys.MPL2_0, forKey: ._case)\n        case .CDDL1_0:\n            try container.encode(DiscriminatorKeys.CDDL1_0, forKey: ._case)\n        case .EPL2_0:\n            try container.encode(DiscriminatorKeys.EPL2_0, forKey: ._case)\n        case .other(let name):\n            try container.encode(DiscriminatorKeys.other, forKey: ._case)\n            try container.encode(name, forKey: .name)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Model/PackageList.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension PackageCollectionsModel {\n    /// A representation of paginated list of packages.\n    public struct PaginatedPackageList {\n        /// List of packages\n        public let items: [PackageCollectionsModel.Package]\n\n        /// Offset of the first item in the result\n        public let offset: Int\n        \n        /// The requested page size\n        public let limit: Int\n        \n        /// Total number of packages\n        public let total: Int\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Model/PackageTypes.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.Date\nimport struct Foundation.URL\n\nimport PackageModel\nimport SourceControl\n\nimport struct TSCUtility.Version\n\nextension PackageCollectionsModel {\n    /// Package metadata\n    public struct Package: Codable, Equatable {\n        /// Package identity\n        public let identity: PackageIdentity\n\n        /// Package location\n        public let location: String\n\n        /// Package description\n        public let summary: String?\n\n        /// Keywords for the package\n        public let keywords: [String]?\n\n        /// Published versions of the package\n        public let versions: [Version]\n\n        /// The latest published version of the package\n        ///\n        /// - Note:\n        ///     This would be the latest released version, unless no release versions are published\n        ///     in which case it will be the latest pre-release version.\n        ///\n        ///     E.g. given:\n        ///     3.0.0-beta.1\n        ///     2.1.1\n        ///     2.1.0\n        ///     2.0.0\n        ///     2.0.0-beta.2\n        ///     2.0.0-beta.1\n        ///     1.0.1\n        ///     1.0.0\n        ///\n        ///     Latest =  2.1.1\n        ///\n        ///     And given:\n        ///     1.0.0-beta.3\n        ///     1.0.0-beta.2\n        ///     1.0.0-beta.1\n        ///\n        ///     Latest = 1.0.0-beta.3\n        public var latestVersion: Version? {\n            self.latestReleaseVersion ?? self.latestPrereleaseVersion\n        }\n\n        public var latestReleaseVersion: Version? {\n            self.versions.latestRelease\n        }\n\n        public var latestPrereleaseVersion: Version? {\n            self.versions.latestPrerelease\n        }\n\n        /// Number of watchers\n        public let watchersCount: Int?\n\n        /// URL of the package's README\n        public let readmeURL: URL?\n\n        /// The package's current license info\n        public let license: License?\n\n        /// Package authors\n        public let authors: [Author]?\n\n        /// The package's programming languages\n        public let languages: Set<String>?\n\n        /// Initializes a `Package`\n        init(\n            identity: PackageIdentity,\n            location: String,\n            summary: String?,\n            keywords: [String]?,\n            versions: [Version],\n            watchersCount: Int?,\n            readmeURL: URL?,\n            license: License?,\n            authors: [Author]?,\n            languages: Set<String>?\n        ) {\n            self.identity = identity\n            self.location = location\n            self.summary = summary\n            self.keywords = keywords\n            self.versions = versions\n            self.watchersCount = watchersCount\n            self.readmeURL = readmeURL\n            self.license = license\n            self.authors = authors\n            self.languages = languages\n        }\n    }\n}\n\nextension PackageCollectionsModel.Package {\n    /// A representation of package version\n    public struct Version: Codable, Equatable {\n        public typealias Target = PackageCollectionsModel.Target\n        public typealias Product = PackageCollectionsModel.Product\n\n        /// The version\n        public let version: TSCUtility.Version\n\n        /// The title or name of the version\n        public let title: String?\n\n        /// Package version description\n        public let summary: String?\n        \n        /// Manifests by tools version\n        public let manifests: [ToolsVersion: Manifest]\n\n        /// Tools version of the default manifest\n        public let defaultToolsVersion: ToolsVersion\n\n        /// An array of compatible platforms and Swift versions that has been tested and verified for.\n        public let verifiedCompatibility: [PackageCollectionsModel.Compatibility]?\n\n        /// The package version's license\n        public let license: PackageCollectionsModel.License?\n        \n        /// The package version's author\n        public let author: PackageCollectionsModel.Package.Author?\n        \n        /// The package version's signer\n        public let signer: PackageCollectionsModel.Signer?\n\n        /// When the package version was created\n        public let createdAt: Date?\n\n        public struct Manifest: Equatable, Codable {\n            /// The Swift tools version specified in `Package.swift`.\n            public let toolsVersion: ToolsVersion\n\n            /// The package name\n            public let packageName: String\n\n            // Custom instead of `PackageModel.Target` because we don't need the additional details\n            /// The package version's targets\n            public let targets: [Target]\n\n            // Custom instead of `PackageModel.Product` because of the simplified `Target`\n            /// The package version's products\n            public let products: [Product]\n\n            /// The package version's supported platforms\n            public let minimumPlatformVersions: [SupportedPlatform]?\n        }\n    }\n}\n\nextension PackageCollectionsModel {\n    /// A representation of package target\n    public struct Target: Equatable, Hashable, Codable {\n        /// The target name\n        public let name: String\n\n        /// Target module name\n        public let moduleName: String?\n    }\n}\n\nextension PackageCollectionsModel {\n    /// A representation of package product\n    public struct Product: Equatable, Codable {\n        /// The product name\n        public let name: String\n\n        /// The product type\n        public let type: ProductType\n\n        /// The product's targets\n        public let targets: [Target]\n    }\n}\n\nextension PackageCollectionsModel {\n    /// Compatible platform and Swift version.\n    public struct Compatibility: Equatable, Codable {\n        /// The platform (e.g., macOS, Linux, etc.)\n        public let platform: PackageModel.Platform\n\n        /// The Swift version\n        public let swiftVersion: SwiftLanguageVersion\n    }\n}\n\nextension PackageCollectionsModel.Package {\n    /// A representation of package author\n    public struct Author: Equatable, Codable {\n        /// Author's username\n        public let username: String\n\n        /// Author's URL (e.g., profile)\n        public let url: URL?\n\n        /// Service that provides the user information\n        public let service: Service?\n\n        /// A representation of user service\n        public struct Service: Equatable, Codable {\n            /// The service name\n            public let name: String\n        }\n    }\n}\n\nextension PackageCollectionsModel {\n    public struct Signer: Equatable, Codable {\n        /// The signer type.\n        public let type: SignerType\n        \n        /// The common name of the signing certificate's subject.\n        public let commonName: String\n        \n        /// The organizational unit name of the signing certificate's subject.\n        public let organizationalUnitName: String\n        \n        /// The organization name of the signing certificate's subject.\n        public let organizationName: String\n\n        public init(\n            type: SignerType,\n            commonName: String,\n            organizationalUnitName: String,\n            organizationName: String\n        ) {\n            self.type = type\n            self.commonName = commonName\n            self.organizationalUnitName = organizationalUnitName\n            self.organizationName = organizationName\n        }\n    }\n    \n    public enum SignerType: String, Codable {\n        case adp // Apple Developer Program\n    }\n}\n\nextension PackageCollectionsModel {\n    public typealias PackageMetadata = (package: PackageCollectionsModel.Package, collections: [PackageCollectionsModel.CollectionIdentifier], provider: PackageMetadataProviderContext?)\n}\n\n// MARK: - Utilities\n\nextension PackageCollectionsModel.Package.Version: Comparable {\n    public static func < (lhs: PackageCollectionsModel.Package.Version, rhs: PackageCollectionsModel.Package.Version) -> Bool {\n        lhs.version < rhs.version\n    }\n}\n\nextension Array where Element == PackageCollectionsModel.Package.Version {\n    var latestRelease: PackageCollectionsModel.Package.Version? {\n        self.filter { $0.version.prereleaseIdentifiers.isEmpty }\n            .sorted(by: >)\n            .first\n    }\n\n    var latestPrerelease: PackageCollectionsModel.Package.Version? {\n        self.filter { !$0.version.prereleaseIdentifiers.isEmpty }\n            .sorted(by: >)\n            .first\n    }\n}\n\nextension PackageCollectionsModel.Package.Version {\n    public var defaultManifest: Manifest? {\n        self.manifests[self.defaultToolsVersion]\n    }\n}\n\nextension Model.Package {\n    var displayName: String {\n        self.identity.description\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Model/Search.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\n\nextension PackageCollectionsModel {\n    /// A representation of package in search result\n    public struct PackageSearchResult {\n        /// Result items of the search\n        public let items: [Item]\n\n        /// Represents a search result item\n        public struct Item: Encodable {\n            // Merged package metadata from across collections\n            /// The matching package\n            public let package: PackageCollectionsModel.Package\n\n            /// Package collections that contain the package\n            public internal(set) var collections: [PackageCollectionsModel.CollectionIdentifier]\n            \n            /// Package indexes that contain the package\n            public internal(set) var indexes: [URL]\n            \n            init(\n                package: PackageCollectionsModel.Package,\n                collections: [PackageCollectionsModel.CollectionIdentifier] = [],\n                indexes: [URL] = []\n            ) {\n                self.package = package\n                self.collections = collections\n                self.indexes = indexes\n            }\n        }\n    }\n\n    /// An enum of target search types\n    public enum TargetSearchType {\n        case prefix\n        case exactMatch\n    }\n\n    /// A representation of target in search result\n    public struct TargetSearchResult {\n        /// Result items of the search\n        public let items: [TargetListItem]\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Model/TargetListResult.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport PackageModel\nimport SourceControl\n\nimport struct TSCUtility.Version\n\nextension PackageCollectionsModel {\n    public typealias TargetListResult = [TargetListItem]\n\n    public struct TargetListItem: Encodable {\n        public typealias Package = PackageCollectionsModel.TargetListResult.Package\n\n        /// Target\n        public let target: Target\n\n        /// Packages where the target is found\n        public let packages: [Package]\n    }\n}\n\nextension PackageCollectionsModel.TargetListResult {\n    /// Metadata of package that contains the target\n    public struct Package: Hashable, Encodable {\n        public typealias Version = PackageCollectionsModel.TargetListResult.PackageVersion\n\n        /// Package's identity\n        public let identity: PackageIdentity\n\n        /// Package's location\n        public let location: String\n\n        /// Package description\n        public let summary: String?\n\n        /// Package versions that contain the target\n        public let versions: [Version]\n\n        /// Package collections that contain this package and at least one of the `versions`\n        public let collections: [PackageCollectionsModel.CollectionIdentifier]\n    }\n}\n\nextension PackageCollectionsModel.TargetListResult {\n    /// Represents a package version\n    public struct PackageVersion: Hashable, Encodable, Comparable {\n        /// The version\n        public let version: TSCUtility.Version\n\n        /// Tools version\n        public let toolsVersion: ToolsVersion\n\n        /// Package name\n        public let packageName: String\n\n        public static func < (lhs: PackageVersion, rhs: PackageVersion) -> Bool {\n            lhs.version < rhs.version && lhs.toolsVersion < rhs.toolsVersion\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/PackageCollections+CertificatePolicy.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\n\nimport PackageCollectionsSigning\n\n/// Configuration in this file is intended for package collection sources to define certificate policies\n/// that are more restrictive. For example, a source may want to require that all their package\n/// collections be signed using certificate that belongs to certain subject user ID.\ninternal struct PackageCollectionSourceCertificatePolicy {\n    private static let defaultSourceCertPolicies: [String: [CertificatePolicyConfig]] = [\n        \"developer.apple.com\": [\n            CertificatePolicyConfig(\n                certPolicyKey: .appleSwiftPackageCollection(subjectOrganizationalUnit: \"XLVRDL8TZV\"),\n                base64EncodedRootCerts: [\n                    // AppleComputerRootCertificate.cer\n                    \"MIIFujCCBKKgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBhjELMAkGA1UEBhMCVVMxHTAbBgNVBAoTFEFwcGxlIENvbXB1dGVyLCBJbmMuMS0wKwYDVQQLEyRBcHBsZSBDb21wdXRlciBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxKTAnBgNVBAMTIEFwcGxlIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTA1MDIxMDAwMTgxNFoXDTI1MDIxMDAwMTgxNFowgYYxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRBcHBsZSBDb21wdXRlciwgSW5jLjEtMCsGA1UECxMkQXBwbGUgQ29tcHV0ZXIgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MSkwJwYDVQQDEyBBcHBsZSBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOSRqQkfkdseR1DrBe1eeYQt6zaiV0xV7IsZid75S2z1B6siMALoGD74UAnTf0GomPnRymacJGsR0KO75Bsqwx+VnnoMpEeLW9QWNzPLxA9NzhRp0ckZcvVdDtV/X5vyJQO6VY9NXQ3xZDUjFUsVWR2zlPf2nJ7PULrBWFBnjwi0IPfLrCwgb3C2PwEwjLdDzw+dPfMrSSgayP7OtbkO2V4c1ss9tTqt9A8OAJILsSEWLnTVPA3bYharo3GSR1NVwa8vQbP4++NwzeajTEV+H0xrUJZBicR0YgsQg0GHM4qBsTBY7FoEMoxos48d3mVz/2deZbxJ2HafMxRloXeUyS0CAwEAAaOCAi8wggIrMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQr0GlHlHYJ/vRrjS5ApvdHTX8IXjAfBgNVHSMEGDAWgBQr0GlHlHYJ/vRrjS5ApvdHTX8IXjCCASkGA1UdIASCASAwggEcMIIBGAYJKoZIhvdjZAUBMIIBCTBBBggrBgEFBQcCARY1aHR0cHM6Ly93d3cuYXBwbGUuY29tL2NlcnRpZmljYXRlYXV0aG9yaXR5L3Rlcm1zLmh0bWwwgcMGCCsGAQUFBwICMIG2GoGzUmVsaWFuY2Ugb24gdGhpcyBjZXJ0aWZpY2F0ZSBieSBhbnkgcGFydHkgYXNzdW1lcyBhY2NlcHRhbmNlIG9mIHRoZSB0aGVuIGFwcGxpY2FibGUgc3RhbmRhcmQgdGVybXMgYW5kIGNvbmRpdGlvbnMgb2YgdXNlLCBjZXJ0aWZpY2F0ZSBwb2xpY3kgYW5kIGNlcnRpZmljYXRpb24gcHJhY3RpY2Ugc3RhdGVtZW50cy4wRAYDVR0fBD0wOzA5oDegNYYzaHR0cHM6Ly93d3cuYXBwbGUuY29tL2NlcnRpZmljYXRlYXV0aG9yaXR5L3Jvb3QuY3JsMFUGCCsGAQUFBwEBBEkwRzBFBggrBgEFBQcwAoY5aHR0cHM6Ly93d3cuYXBwbGUuY29tL2NlcnRpZmljYXRlYXV0aG9yaXR5L2Nhc2lnbmVycy5odG1sMA0GCSqGSIb3DQEBBQUAA4IBAQCd2i0oWC99dgS5BNM+zrdmY06PL9T+S61yvaM5xlJNBZhS9YlRASR5vhoy9+VEi0tEBzmC1lrKtCBe2a4VXR2MHTK/ODFiSF3H4ZCx+CRA+F9Ym1FdV53B5f88zHIhbsTp6aF31ywXJsM/65roCwO66bNKcuszCVut5mIxauivL9WvHld2j383LS4CXN1jyfJxuCZA3xWNdUQ/eb3mHZnhQyw+rW++uaT+DjUZUWOxw961kj5ReAFziqQjyqSI8R5cH0EWLX6VCqrpiUGYGxrdyyC/R14MJsVVNU3GMIuZZxTHCR+6R8faAQmHJEKVvRNgGQrv6n8Obs3BREM6StXj\",\n                    // AppleIncRootCertificate.cer\n                    \"MIIEuzCCA6OgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQGEwJVUzETMBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwHhcNMDYwNDI1MjE0MDM2WhcNMzUwMjA5MjE0MDM2WjBiMQswCQYDVQQGEwJVUzETMBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkkakJH5HbHkdQ6wXtXnmELes2oldMVeyLGYne+Uts9QerIjAC6Bg++FAJ039BqJj50cpmnCRrEdCju+QbKsMflZ56DKRHi1vUFjczy8QPTc4UadHJGXL1XQ7Vf1+b8iUDulWPTV0N8WQ1IxVLFVkds5T39pyez1C6wVhQZ48ItCD3y6wsIG9wtj8BMIy3Q88PnT3zK0koGsj+zrW5DtleHNbLPbU6rfQPDgCSC7EhFi501TwN22IWq6NxkkdTVcGvL0Gz+PvjcM3mo0xFfh9Ma1CWQYnEdGILEINBhzOKgbEwWOxaBDKMaLOPHd5lc/9nXmW8Sdh2nzMUZaF3lMktAgMBAAGjggF6MIIBdjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUK9BpR5R2Cf70a40uQKb3R01/CF4wHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/CF4wggERBgNVHSAEggEIMIIBBDCCAQAGCSqGSIb3Y2QFATCB8jAqBggrBgEFBQcCARYeaHR0cHM6Ly93d3cuYXBwbGUuY29tL2FwcGxlY2EvMIHDBggrBgEFBQcCAjCBthqBs1JlbGlhbmNlIG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBjb25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZpY2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMA0GCSqGSIb3DQEBBQUAA4IBAQBcNplMLXi37Yyb3PN3m/J20ncwT8EfhYOFG5k9RzfyqZtAjizUsZAS2L70c5vu0mQPy3lPNNiiPvl4/2vIB+x9OYOLUyDTOMSxv5pPCmv/K/xZpwUJfBdAVhEedNO3iyM7R6PVbyTi69G3cN8PReEnyvFteO3ntRcXqNx+IjXKJdXZD9Zr1KIkIxH3oayPc4FgxhtbCS+SsvhESPBgOJ4V9T0mZyCKM2r3DYLP3uujL/lTaltkwGMzd/c6ByxW69oPIQ7aunMZT7XZNn/Bh1XZp5m5MkL72NVxnn6hUrcbvZNCJBIqxw8dtk2cXmPIS4AXUKqK1drk/NAJBzewdXUh\",\n                    // AppleRootCA-G2.cer\n                    \"MIIFkjCCA3qgAwIBAgIIAeDltYNno+AwDQYJKoZIhvcNAQEMBQAwZzEbMBkGA1UEAwwSQXBwbGUgUm9vdCBDQSAtIEcyMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcNMTQwNDMwMTgxMDA5WhcNMzkwNDMwMTgxMDA5WjBnMRswGQYDVQQDDBJBcHBsZSBSb290IENBIC0gRzIxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANgREkhI2imKScUcx+xuM23+TfvgHN6sXuI2pyT5f1BrTM65MFQn5bPW7SXmMLYFN14UIhHF6Kob0vuy0gmVOKTvKkmMXT5xZgM4+xb1hYjkWpIMBDLyyED7Ul+f9sDx47pFoFDVEovy3d6RhiPw9bZyLgHaC/YuOQhfGaFjQQscp5TBhsRTL3b2CtcM0YM/GlMZ81fVJ3/8E7j4ko380yhDPLVoACVdJ2LT3VXdRCCQgzWTxb+4Gftr49wIQuavbfqeQMpOhYV4SbHXw8EwOTKrfl+q04tvny0aIWhwZ7Oj8ZhBbZF8+NfbqOdfIRqMM78xdLe40fTgIvS/cjTf94FNcX1RoeKz8NMoFnNvzcytN31O661A4T+B/fc9Cj6i8b0xlilZ3MIZgIxbdMYs0xBTJh0UT8TUgWY8h2czJxQI6bR3hDRSj4n4aJgXv8O7qhOTH11UL6jHfPsNFL4VPSQ08prcdUFmIrQB1guvkJ4M6mL4m1k8COKWNORj3rw31OsMiANDC1CvoDTdUE0V+1ok2Az6DGOeHwOx4e7hqkP0ZmUoNwIx7wHHHtHMn23KVDpA287PT0aLSmWaasZobNfMmRtHsHLDd4/E92GcdB/O/WuhwpyUgquUoue9G7q5cDmVF8Up8zlYNPXEpMZ7YLlmQ1A/bmH8DvmGqmAMQ0uVAgMBAAGjQjBAMB0GA1UdDgQWBBTEmRNsGAPCe8CjoA1/coB6HHcmjTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQwFAAOCAgEAUabz4vS4PZO/Lc4Pu1vhVRROTtHlznldgX/+tvCHM/jvlOV+3Gp5pxy+8JS3ptEwnMgNCnWefZKVfhidfsJxaXwU6s+DDuQUQp50DhDNqxq6EWGBeNjxtUVAeKuowM77fWM3aPbn+6/Gw0vsHzYmE1SGlHKy6gLti23kDKaQwFd1z4xCfVzmMX3zybKSaUYOiPjjLUKyOKimGY3xn83uamW8GrAlvacp/fQ+onVJv57byfenHmOZ4VxG/5IFjPoeIPmGlFYl5bRXOJ3riGQUIUkhOb9iZqmxospvPyFgxYnURTbImHy99v6ZSYA7LNKmp4gDBDEZt7Y6YUX6yfIjyGNzv1aJMbDZfGKnexWoiIqrOEDCzBL/FePwN983csvMmOa/orz6JopxVtfnJBtIRD6e/J/JzBrsQzwBvDR4yGn1xuZW7AYJNpDrFEobXsmII9oDMJELuDY++ee1KG++P+w8j2Ud5cAeh6Squpj9kuNsJnfdBrRkBof0Tta6SqoWqPQFZ2aWuuJVecMsXUmPgEkrihLHdoBR37q9ZV0+N0djMenl9MU/S60EinpxLK8JQzcPqOMyT/RFtm2XNuyE9QoB6he7hY1Ck3DDUOUUi78/w0EP3SIEIwiKum1xRKtzCTrJ+VKACd+66eYWyi4uTLLT3OUEVLLUNIAytbwPF+E=\",\n                    // AppleRootCA-G3.cer\n                    \"MIICQzCCAcmgAwIBAgIILcX8iNLFS5UwCgYIKoZIzj0EAwMwZzEbMBkGA1UEAwwSQXBwbGUgUm9vdCBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcNMTQwNDMwMTgxOTA2WhcNMzkwNDMwMTgxOTA2WjBnMRswGQYDVQQDDBJBcHBsZSBSb290IENBIC0gRzMxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABJjpLz1AcqTtkyJygRMc3RCV8cWjTnHcFBbZDuWmBSp3ZHtfTjjTuxxEtX/1H7YyYl3J6YRbTzBPEVoA/VhYDKX1DyxNB0cTddqXl5dvMVztK517IDvYuVTZXpmkOlEKMaNCMEAwHQYDVR0OBBYEFLuw3qFYM4iapIqZ3r6966/ayySrMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gAMGUCMQCD6cHEFl4aXTQY2e3v9GwOAEZLuN+yRhHFD/3meoyhpmvOwgPUnPWTxnS4at+qIxUCMG1mihDK1A3UT82NQz60imOlM27jbdoXt2QfyFMm+YhidDkLF1vLUagM6BgD56KyKA==\",\n                ]\n            ),\n        ],\n    ]\n\n    private let sourceCertPolicies: [String: [CertificatePolicyConfig]]\n\n    var allRootCerts: Set<String>? {\n        let allRootCerts = self.sourceCertPolicies.values\n            .flatMap { configs in configs.compactMap(\\.base64EncodedRootCerts) }\n            .flatMap { $0 }\n        return allRootCerts.isEmpty ? nil : Set(allRootCerts)\n    }\n\n    init(sourceCertPolicies: [String: [CertificatePolicyConfig]]? = nil) {\n        guard sourceCertPolicies?.values.first(where: { $0.isEmpty }) == nil else {\n            preconditionFailure(\"CertificatePolicyConfig array must not be empty\")\n        }\n        self.sourceCertPolicies = sourceCertPolicies ?? Self.defaultSourceCertPolicies\n    }\n\n    func mustBeSigned(source: Model.CollectionSource) -> Bool {\n        source.certPolicyConfigKey.map { self.sourceCertPolicies[$0] != nil } ?? false\n    }\n\n    func certificatePolicyKeys(for source: Model.CollectionSource) -> [CertificatePolicyKey]? {\n        // Certificate policy is associated to a collection host\n        source.certPolicyConfigKey.flatMap { self.sourceCertPolicies[$0]?.map(\\.certPolicyKey) }\n    }\n\n    struct CertificatePolicyConfig {\n        let certPolicyKey: CertificatePolicyKey\n\n        /// Root CAs of the signing certificates. Each item is the base64-encoded string\n        /// of the DER representation of a root CA.\n        let base64EncodedRootCerts: [String]?\n    }\n}\n\nextension Model.CollectionSource {\n    fileprivate var certPolicyConfigKey: String? {\n        self.url.host\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/PackageCollections+Configuration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n// TODO: how do we read default config values? ENV variables? user settings?\nextension PackageCollections {\n    public struct Configuration {\n        // TODO: add configuration including:\n        // JSONPackageCollectionProvider: maximumSizeInBytes\n        // JSONPackageCollectionValidator: maximumPackageCount, maximumMajorVersionCount, maximumMinorVersionCount\n        \n        /// Path of the parent directory for collections-related configuration files\n        public var configurationDirectory: AbsolutePath?\n        \n        /// Path of the parent directory for collections-related cache(s)\n        public var cacheDirectory: AbsolutePath?\n\n        /// Auth tokens for the collections or metadata provider\n        public var authTokens: () -> [AuthTokenType: String]?\n\n        public init(\n            configurationDirectory: AbsolutePath? = nil,\n            cacheDirectory: AbsolutePath? = nil,\n            authTokens: @escaping () -> [AuthTokenType: String]? = { nil }\n        ) {\n            self.authTokens = authTokens\n        }\n    }\n}\n\npublic enum AuthTokenType: Hashable {\n    case github(_ host: String)\n}\n"
  },
  {
    "path": "Sources/PackageCollections/PackageCollections+Storage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport protocol TSCBasic.Closable\n\nextension PackageCollections {\n    struct Storage: Closable {\n        let sources: PackageCollectionsSourcesStorage\n        let collections: PackageCollectionsStorage\n\n        init(sources: PackageCollectionsSourcesStorage, collections: PackageCollectionsStorage) {\n            self.sources = sources\n            self.collections = collections\n        }\n    }\n}\n\nextension PackageCollections.Storage {\n    func close() throws {\n        var errors = [Error]()\n\n        let tryClose = { (item: Any) in\n            if let closable = item as? Closable {\n                do {\n                    try closable.close()\n                } catch {\n                    errors.append(error)\n                }\n            }\n        }\n\n        tryClose(self.sources)\n        tryClose(self.collections)\n\n        if !errors.isEmpty {\n            throw MultipleErrors(errors)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/PackageCollections+Validation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageCollectionsModel\nimport PackageModel\n\nimport struct TSCUtility.Version\n\n// MARK: - Model validations\n\nextension Model.CollectionSource {\n    func validate(fileSystem: FileSystem) -> [ValidationMessage]? {\n        var messages: [ValidationMessage]?\n        let appendMessage = { (message: ValidationMessage) in\n            if messages == nil {\n                messages = .init()\n            }\n            messages?.append(message)\n        }\n\n        let allowedSchemes = Set([\"https\", \"file\"])\n\n        switch self.type {\n        case .json:\n            let scheme = url.scheme?.lowercased() ?? \"\"\n            if !allowedSchemes.contains(scheme) {\n                appendMessage(.error(\"Scheme (\\\"\\(scheme)\\\") not allowed: \\(url.absoluteString). Must be one of \\(allowedSchemes).\"))\n            } else if scheme == \"file\" {\n                let absolutePath = self.absolutePath\n\n                if absolutePath == nil {\n                    appendMessage(.error(\"Invalid file path: \\(self.url.path). It must be an absolute file system path.\"))\n                } else if let absolutePath, !fileSystem.exists(absolutePath) {\n                    appendMessage(.error(\"\\(self.url.path) is either a non-local path or the file does not exist.\"))\n                }\n            }\n        }\n\n        return messages\n    }\n}\n\n// MARK: - JSON model validations\n\nextension PackageCollectionModel.V1 {\n    public struct Validator {\n        public let configuration: Configuration\n\n        public init(configuration: Configuration = .init()) {\n            self.configuration = configuration\n        }\n\n        public func validate(collection: Collection) -> [ValidationMessage]? {\n            var messages = [ValidationMessage]()\n\n            let packages = collection.packages\n            // Stop validating if collection doesn't pass basic checks\n            if packages.isEmpty {\n                messages.append(.error(\"A collection must contain at least one package.\", property: \"packages\"))\n            } else if packages.count > self.configuration.maximumPackageCount {\n                messages.append(.warning(\"The collection has (\\(packages.count)) packages, which is more than the recommended maximum (\\(self.configuration.maximumPackageCount)) and extra data might be ignored.\", property: \"packages\"))\n            } else {\n                packages.forEach { self.validate(package: $0, messages: &messages) }\n            }\n\n            guard messages.isEmpty else {\n                return messages\n            }\n\n            return nil\n        }\n\n        // TODO: validate package url?\n        private func validate(package: Collection.Package, messages: inout [ValidationMessage]) {\n            let packageID = \"\\(PackageIdentity(url: SourceControlURL(package.url)).description) (\\(package.url.absoluteString))\"\n\n            guard !package.versions.isEmpty else {\n                messages.append(.error(\"Package \\(packageID) does not have any versions.\", property: \"package.versions\"))\n                return\n            }\n\n            // Check for duplicate versions\n            let nonUniqueVersions = Dictionary(grouping: package.versions, by: { $0.version }).filter { $1.count > 1 }.keys\n            if !nonUniqueVersions.isEmpty {\n                messages.append(.error(\"Duplicate version(s) found in package \\(packageID): \\(nonUniqueVersions).\", property: \"package.versions\"))\n            }\n\n            var nonSemanticVersions = [String]()\n            let semanticVersions: [TSCUtility.Version] = package.versions.compactMap {\n                let semver = TSCUtility.Version(tag: $0.version)\n                if semver == nil {\n                    nonSemanticVersions.append($0.version)\n                }\n                return semver\n            }\n\n            guard nonSemanticVersions.isEmpty else {\n                messages.append(.error(\"Non semantic version(s) found in package \\(packageID): \\(nonSemanticVersions).\", property: \"package.versions\"))\n                // The next part of validation requires sorting the semvers. Cannot continue if non-semver.\n                return\n            }\n\n            let sortedVersions = semanticVersions.sorted(by: >)\n\n            var currentMajor: Int?\n            var majorCount = 0\n            var minorCount = 0\n            for version in sortedVersions {\n                if version.major != currentMajor {\n                    currentMajor = version.major\n                    majorCount += 1\n                    minorCount = 0\n                }\n\n                guard majorCount <= self.configuration.maximumMajorVersionCount else {\n                    messages.append(.warning(\"Package \\(packageID) includes too many major versions. Only \\(self.configuration.maximumMajorVersionCount) is allowed and extra data might be ignored.\", property: \"package.versions\"))\n                    break\n                }\n                guard minorCount < self.configuration.maximumMinorVersionCount else {\n                    // !-safe currentMajor cannot be nil at this point\n                    messages.append(.warning(\"Package \\(packageID) includes too many minor versions for major version \\(currentMajor!). Only \\(self.configuration.maximumMinorVersionCount) is allowed and extra data might be ignored.\", property: \"package.versions\"))\n                    break\n                }\n\n                minorCount += 1\n            }\n\n            package.versions.forEach { version in\n                guard !version.manifests.isEmpty else {\n                    messages.append(.error(\"Package \\(packageID) version \\(version.version) does not have any manifests.\", property: \"version.manifest\"))\n                    return\n                }\n                guard version.manifests[version.defaultToolsVersion] != nil else {\n                    messages.append(.error(\"Package \\(packageID) version \\(version.version) is missing the default manifest (tools version: \\(version.defaultToolsVersion))\", property: \"version.manifest\"))\n                    return\n                }\n\n                version.manifests.forEach { toolsVersion, manifest in\n                    if toolsVersion != manifest.toolsVersion {\n                        messages.append(.error(\"Package \\(packageID) manifest tools version \\(manifest.toolsVersion) does not match \\(toolsVersion)\", property: \"version.manifest\"))\n                    }\n\n                    if manifest.products.isEmpty {\n                        messages.append(.error(\"Package \\(packageID) version \\(version.version) tools-version \\(toolsVersion) does not contain any products.\", property: \"version.manifest.products\"))\n                    }\n                    manifest.products.forEach { product in\n                        if product.targets.isEmpty {\n                            messages.append(.error(\"Product \\(product.name) of package \\(packageID) version \\(version.version) tools-version \\(toolsVersion) does not contain any targets.\", property: \"product.targets\"))\n                        }\n                    }\n\n                    if manifest.targets.isEmpty {\n                        messages.append(.error(\"Package \\(packageID) version \\(version.version) tools-version \\(toolsVersion) does not contain any targets.\", property: \"version.manifest.targets\"))\n                    }\n                }\n            }\n        }\n\n        public struct Configuration {\n            public var maximumPackageCount: Int\n            public var maximumMajorVersionCount: Int\n            public var maximumMinorVersionCount: Int\n\n            public init(maximumPackageCount: Int? = nil,\n                        maximumMajorVersionCount: Int? = nil,\n                        maximumMinorVersionCount: Int? = nil) {\n                // TODO: where should we read defaults from?\n                self.maximumPackageCount = maximumPackageCount ?? 50\n                self.maximumMajorVersionCount = maximumMajorVersionCount ?? 2\n                self.maximumMinorVersionCount = maximumMinorVersionCount ?? 3\n            }\n        }\n    }\n}\n\n// MARK: - ValidationMessage and ValidationError\n\npublic struct ValidationMessage: Equatable, CustomStringConvertible {\n    public let message: String\n    public let level: Level\n    public let property: String?\n\n    private init(_ message: String, level: Level, property: String? = nil) {\n        self.message = message\n        self.level = level\n        self.property = property\n    }\n\n    static func error(_ message: String, property: String? = nil) -> ValidationMessage {\n        .init(message, level: .error, property: property)\n    }\n\n    static func warning(_ message: String, property: String? = nil) -> ValidationMessage {\n        .init(message, level: .warning, property: property)\n    }\n\n    public enum Level: String, Equatable {\n        case warning\n        case error\n    }\n\n    public var description: String {\n        \"[\\(self.level)] \\(self.property.map { \"\\($0): \" } ?? \"\")\\(self.message)\"\n    }\n}\n\nextension Array where Element == ValidationMessage {\n    func errors(include levels: Set<ValidationMessage.Level> = [.error]) -> [ValidationError]? {\n        let errors = self.filter { levels.contains($0.level) }\n\n        guard !errors.isEmpty else { return nil }\n\n        return errors.map {\n            if let property = $0.property {\n                return ValidationError.property(name: property, message: $0.message)\n            } else {\n                return ValidationError.other(message: $0.message)\n            }\n        }\n    }\n}\n\npublic enum ValidationError: Error, Equatable, CustomStringConvertible {\n    case property(name: String, message: String)\n    case other(message: String)\n    \n    public var message: String {\n        switch self {\n        case .property(_, let message):\n            return message\n        case .other(let message):\n            return message\n        }\n    }\n\n    public var description: String {\n        switch self {\n        case .property(let name, let message):\n            return \"\\(name): \\(message)\"\n        case .other(let message):\n            return message\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/PackageCollections.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Basics\nimport PackageModel\nimport Foundation\n\nimport protocol TSCBasic.Closable\n\n// TODO: is there a better name? this conflicts with the module name which is okay in this case but not ideal in Swift\npublic struct PackageCollections: PackageCollectionsProtocol, Closable {\n    // Check JSONPackageCollectionProvider.isSignatureCheckSupported before updating or removing this\n    #if os(macOS) || os(Linux) || os(Windows) || os(Android)\n    static let isSupportedPlatform = true\n    #else\n    static let isSupportedPlatform = false\n    #endif\n\n    let configuration: Configuration\n    private let fileSystem: FileSystem\n    private let observabilityScope: ObservabilityScope\n    private let storageContainer: (storage: Storage, owned: Bool)\n    private let collectionProviders: [Model.CollectionSourceType: PackageCollectionProvider]\n    let metadataProvider: PackageMetadataProvider\n\n    private var storage: Storage {\n        self.storageContainer.storage\n    }\n\n    // initialize with defaults\n    public init(\n        configuration: Configuration = .init(),\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.init(\n            configuration: configuration,\n            customMetadataProvider: nil,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n    }\n    \n    init(\n        configuration: Configuration = .init(),\n        customMetadataProvider: PackageMetadataProvider?,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        let storage = Storage(\n            sources: FilePackageCollectionsSourcesStorage(\n                fileSystem: fileSystem,\n                path: configuration.configurationDirectory?.appending(\"collections.json\")\n            ),\n            collections: SQLitePackageCollectionsStorage(\n                location: configuration.cacheDirectory.map { .path($0.appending(components: \"package-collection.db\")) },\n                observabilityScope: observabilityScope\n            )\n        )\n\n        let collectionProviders = [\n            Model.CollectionSourceType.json: JSONPackageCollectionProvider(\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n        ]\n\n        let metadataProvider = customMetadataProvider ?? GitHubPackageMetadataProvider(\n            configuration: .init(\n                authTokens: configuration.authTokens,\n                cacheDir: configuration.cacheDirectory?.appending(components: \"package-metadata\")\n            ),\n            observabilityScope: observabilityScope\n        )\n\n        self.configuration = configuration\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n        self.storageContainer = (storage, true)\n        self.collectionProviders = collectionProviders\n        self.metadataProvider = metadataProvider\n    }\n\n    // internal initializer for testing\n    init(configuration: Configuration = .init(),\n         fileSystem: FileSystem,\n         observabilityScope: ObservabilityScope,\n         storage: Storage,\n         collectionProviders: [Model.CollectionSourceType: PackageCollectionProvider],\n         metadataProvider: PackageMetadataProvider\n    ) {\n        self.configuration = configuration\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n        self.storageContainer = (storage, false)\n        self.collectionProviders = collectionProviders\n        self.metadataProvider = metadataProvider\n    }\n\n    public func shutdown() throws {\n        if self.storageContainer.owned {\n            try self.storageContainer.storage.close()\n        }\n        \n        if let metadataProvider = self.metadataProvider as? Closable {\n            try metadataProvider.close()\n        }\n    }\n    \n    public func close() throws {\n        try self.shutdown()\n    }\n\n    // MARK: - Collections\n\n    public func listCollections(identifiers: Set<PackageCollectionsModel.CollectionIdentifier>? = nil) async throws -> [PackageCollectionsModel.Collection] {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        let sources = try await self.storage.sources.list()\n        let identiferSource = sources.reduce(into: [PackageCollectionsModel.CollectionIdentifier: PackageCollectionsModel.CollectionSource]()) { result, source in\n            result[.init(from: source)] = source\n        }\n        let identifiersToFetch = identiferSource.keys.filter { identifiers?.contains($0) ?? true }\n\n        if identifiersToFetch.isEmpty {\n            return []\n        }\n\n        var collections = try await self.storage.collections.list(identifiers: identifiersToFetch)\n\n        let sourceOrder = sources.enumerated().reduce(into: [Model.CollectionIdentifier: Int]()) { result, item in\n            result[.init(from: item.element)] = item.offset\n        }\n\n        // re-order by profile order which reflects the user's election\n        let sort = { (lhs: PackageCollectionsModel.Collection, rhs: PackageCollectionsModel.Collection) -> Bool in\n            sourceOrder[lhs.identifier] ?? 0 < sourceOrder[rhs.identifier] ?? 0\n        }\n\n        // We've fetched all the wanted collections and we're done\n        if collections.count == identifiersToFetch.count {\n            collections.sort(by: sort)\n            return collections\n        }\n\n        // Some of the results are missing. This happens when deserialization of stored collections fail,\n        // so we will try refreshing the missing collections to update data in storage.\n        let missingSources = Set(identifiersToFetch.compactMap { identiferSource[$0] }).subtracting(Set(collections.map { $0.source }))\n        var refreshResults = [Model.Collection]()\n        for source in missingSources {\n            guard let refreshResult = try? await self.refreshCollectionFromSource(source: source, trustConfirmationProvider: nil) else {\n                continue\n            }\n            refreshResults.append(refreshResult)\n        }\n        var result = collections + refreshResults\n        result.sort(by: sort)\n        return result\n    }\n\n    public func refreshCollections() async throws -> [PackageCollectionsModel.CollectionSource] {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        let sources = try await self.storage.sources.list()\n        guard !sources.isEmpty else {\n            return []\n        }\n\n        var refreshResults = [Result<Model.Collection, Error>]()\n        for source in sources {\n            do {\n                try await refreshResults.append(.success(self.refreshCollectionFromSource(source: source, trustConfirmationProvider: nil)))\n            } catch {\n                refreshResults.append(.failure(error))\n            }\n        }\n        let failures = refreshResults.compactMap { $0.failure }\n        guard failures.isEmpty else {\n            throw MultipleErrors(failures)\n        }\n        return sources\n    }\n\n    public func refreshCollection(_ source: PackageCollectionsModel.CollectionSource) async throws -> PackageCollectionsModel.Collection {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        let sources = try await self.storage.sources.list()\n        guard let savedSource = sources.first(where: { $0 == source }) else {\n            throw NotFoundError(\"\\(source)\")\n        }\n        return try await self.refreshCollectionFromSource(source: savedSource, trustConfirmationProvider: nil)\n    }\n\n    public func addCollection(_ source: PackageCollectionsModel.CollectionSource, order: Int? = nil, trustConfirmationProvider: ((PackageCollectionsModel.Collection, @escaping (Bool) -> Void) -> Void)? = nil) async throws -> PackageCollectionsModel.Collection {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        if let errors = source.validate(fileSystem: self.fileSystem)?.errors() {\n            throw MultipleErrors(errors)\n        }\n\n        // first record the registration\n        try await self.storage.sources.add(source: source, order: order)\n        // next try to fetch the collection from the network and store it locally so future operations dont need to access the network\n        do {\n            return try await self.refreshCollectionFromSource(source: source, trustConfirmationProvider: trustConfirmationProvider)\n        } catch {\n            // Don't delete the source if we are either pending user confirmation or have recorded user's preference.\n            // It is also possible that we can't verify signature (yet) due to config issue, which user can fix and we retry later.\n            if let error = error as? PackageCollectionError, error == .trustConfirmationRequired || error == .untrusted || error == .cannotVerifySignature {\n                throw error\n            }\n            // Otherwise remove source since it fails to be fetched\n            try? await self.storage.sources.remove(source: source)\n            // Whether removal succeeds or not, return the refresh error\n            throw error\n        }\n\n    }\n\n    public func removeCollection(_ source: PackageCollectionsModel.CollectionSource) async throws {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        try await self.storage.sources.remove(source: source)\n        try await self.storage.collections.remove(identifier: .init(from: source))\n    }\n\n    public func moveCollection(_ source: PackageCollectionsModel.CollectionSource, to order: Int) async throws {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        try await self.storage.sources.move(source: source, to: order)\n    }\n\n    public func updateCollection(_ source: PackageCollectionsModel.CollectionSource) async throws -> PackageCollectionsModel.Collection {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        try await self.storage.sources.update(source: source)\n        return try await self.refreshCollectionFromSource(source: source, trustConfirmationProvider: nil)\n    }\n\n    // Returns information about a package collection.\n    // The collection is not required to be in the configured list.\n    // If not found locally (storage), the collection will be fetched from the source.\n    public func getCollection(_ source: PackageCollectionsModel.CollectionSource) async throws -> PackageCollectionsModel.Collection {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        do {\n            return try await self.storage.collections.get(identifier: .init(from: source))\n        } catch {\n            // The collection is not in storage. Validate the source before fetching it.\n            if let errors = source.validate(fileSystem: self.fileSystem)?.errors() {\n                throw MultipleErrors(errors)\n            }\n            guard let provider = self.collectionProviders[source.type] else {\n                throw UnknownProvider(source.type)\n            }\n            return try await provider.get(source)\n        }\n    }\n\n    // MARK: - Packages\n\n    public func findPackages(\n        _ query: String,\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> PackageCollectionsModel.PackageSearchResult{\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n        let sources = try await self.storage.sources.list()\n\n        let identifiers = sources.map { .init(from: $0) }.filter { collections?.contains($0) ?? true }\n        if identifiers.isEmpty {\n            return Model.PackageSearchResult(items: [])\n        }\n        return try await self.storage.collections.searchPackages(identifiers: identifiers, query: query)\n    }\n\n    public func listPackages(collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil) async throws -> PackageCollectionsModel.PackageSearchResult {\n        let collections = try await self.listCollections(identifiers: collections)\n\n        var packageCollections = [PackageIdentity: (package: Model.Package, collections: Set<Model.CollectionIdentifier>)]()\n        // Use package data from the most recently processed collection\n        collections.sorted(by: { $0.lastProcessedAt > $1.lastProcessedAt }).forEach { collection in\n            collection.packages.forEach { package in\n                var entry = packageCollections.removeValue(forKey: package.identity)\n                if entry == nil {\n                    entry = (package, .init())\n                }\n\n                if var entry = entry {\n                    entry.collections.insert(collection.identifier)\n                    packageCollections[package.identity] = entry\n                }\n            }\n        }\n\n        return PackageCollectionsModel.PackageSearchResult(\n            items: packageCollections.sorted { $0.value.package.displayName < $1.value.package.displayName }\n                .map { entry in\n                .init(package: entry.value.package, collections: Array(entry.value.collections))\n                }\n        )\n    }\n\n    // MARK: - Package Metadata\n\n    public func getPackageMetadata(\n        identity: PackageModel.PackageIdentity,\n        location: String? = nil,\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> PackageCollectionsModel.PackageMetadata {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        // first find in storage\n        let packageSearchResult = try await self.findPackage(identity: identity, location: location, collections: collections)\n        // then try to get more metadata from provider (optional)\n        let (basicMetadata, provider) = await self.metadataProvider.get(identity: packageSearchResult.package.identity, location: packageSearchResult.package.location)\n        do {\n            return try Model.PackageMetadata(\n                package: Self.mergedPackageMetadata(package: packageSearchResult.package, basicMetadata: basicMetadata.get()),\n                collections: packageSearchResult.collections,\n                provider: provider\n            )\n        } catch {\n            self.observabilityScope.emit(\n                warning: \"Failed fetching information about \\(identity) from \\(self.metadataProvider.self)\",\n                underlyingError: error\n            )\n            return Model.PackageMetadata(\n                package: Self.mergedPackageMetadata(package: packageSearchResult.package, basicMetadata: nil),\n                collections: packageSearchResult.collections,\n                provider: provider\n            )\n        }\n    }\n\n    // MARK: - Targets\n\n    public func listTargets(collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil) async throws -> PackageCollectionsModel.TargetListResult {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        let collections = try await self.listCollections(identifiers: collections)\n        return self.targetListResultFromCollections(collections)\n    }\n\n    public func findTargets(\n        _ query: String,\n        searchType: PackageCollectionsModel.TargetSearchType? = nil,\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> PackageCollectionsModel.TargetSearchResult {\n        guard Self.isSupportedPlatform else {\n            throw PackageCollectionError.unsupportedPlatform\n        }\n\n        let searchType = searchType ?? .exactMatch\n\n        let sources = try await self.storage.sources.list()\n        let identifiers = sources.map { .init(from: $0) }.filter { collections?.contains($0) ?? true }\n        if identifiers.isEmpty {\n            return PackageCollectionsModel.TargetSearchResult(items: [])\n        }\n        return try await self.storage.collections.searchTargets(identifiers: identifiers, query: query, type: searchType)\n    }\n\n    // MARK: - Private\n\n    // Fetch the collection from the network and store it in local storage\n    // This helps avoid network access in normal operations\n    private func refreshCollectionFromSource(\n        source: PackageCollectionsModel.CollectionSource,\n        trustConfirmationProvider: ((PackageCollectionsModel.Collection, @escaping (Bool) -> Void) -> Void)? = nil\n    ) async throws -> Model.Collection {\n        guard let provider = self.collectionProviders[source.type] else {\n            throw UnknownProvider(source.type)\n        }\n        var collection: Model.Collection\n        do {\n            collection = try await provider.get(source)\n        } catch {\n            // Remove the unavailable/invalid collection (if previously saved) from storage before calling back\n            try? await self.storage.collections.remove(identifier: PackageCollectionsModel.CollectionIdentifier(from: source))\n            throw error\n        }\n        // If collection is signed and signature is valid, save to storage. `provider.get`\n        // would have failed if signature were invalid.\n        if collection.isSigned {\n            return try await self.storage.collections.put(collection: collection)\n        }\n\n        // If collection is not signed, check if it's trusted by user and prompt user if needed.\n        if let isTrusted = source.isTrusted {\n            guard isTrusted else {\n                // Try to remove the untrusted collection (if previously saved) from storage before calling back\n                try? await self.storage.collections.remove(identifier: collection.identifier)\n                throw PackageCollectionError.untrusted\n            }\n            return try await self.storage.collections.put(collection: collection)\n        }\n\n\n        // No user preference recorded, so we need to prompt if we can.\n        guard let trustConfirmationProvider else {\n            // Try to remove the untrusted collection (if previously saved) from storage before calling back\n            try? await self.storage.collections.remove(identifier: collection.identifier)\n            throw PackageCollectionError.trustConfirmationRequired\n        }\n        let userTrusted = await withCheckedContinuation { continuation in\n            trustConfirmationProvider(collection) { result in\n                continuation.resume(returning: result)\n            }\n        }\n        var source = source\n        source.isTrusted = userTrusted\n        // Record user preference then save collection to storage\n        try await self.storage.sources.update(source: source)\n\n        guard userTrusted else {\n            // Try to remove the untrusted collection (if previously saved) from storage before calling back\n            try? await self.storage.collections.remove(identifier: collection.identifier)\n            throw PackageCollectionError.untrusted\n        }\n        collection.source = source\n        return try await self.storage.collections.put(collection: collection)\n    }\n\n    func findPackage(identity: PackageIdentity,\n                     location: String? = nil,\n                     collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> PackageCollectionsModel.PackageSearchResult.Item {\n        let notFoundError = NotFoundError(\"identity: \\(identity), location: \\(location ?? \"none\")\")\n\n        let sources: [PackageCollectionsModel.CollectionSource]\n        do {\n            sources = try await self.storage.sources.list()\n        } catch is NotFoundError {\n            throw notFoundError\n        }\n\n        var collectionIdentifiers = sources.map { Model.CollectionIdentifier(from: $0) }\n        if let collections {\n            collectionIdentifiers = collectionIdentifiers.filter { collections.contains($0) }\n        }\n        guard !collectionIdentifiers.isEmpty else {\n            throw notFoundError\n        }\n        let packagesCollections: (packages: [PackageCollectionsModel.Package], collections: [PackageCollectionsModel.CollectionIdentifier])\n        do {\n            packagesCollections = try await self.storage.collections.findPackage(identifier: identity, collectionIdentifiers: collectionIdentifiers)\n        } catch is NotFoundError {\n            throw notFoundError\n        }\n\n        let matches: [PackageCollectionsModel.Package]\n        if let location {\n            // A package identity can be associated with multiple repository URLs\n            matches = packagesCollections.packages.filter { CanonicalPackageLocation($0.location) == CanonicalPackageLocation(location) }\n        }\n        else {\n            matches = packagesCollections.packages\n        }\n        guard let package = matches.first else {\n            throw notFoundError\n        }\n        return PackageCollectionsModel.PackageSearchResult.Item(\n            package: package,\n            collections: packagesCollections.collections)\n\n    }\n\n    private func targetListResultFromCollections(_ collections: [Model.Collection]) -> Model.TargetListResult {\n        var packageCollections = [PackageIdentity: (package: Model.Package, collections: Set<Model.CollectionIdentifier>)]()\n        var targetsPackages = [String: (target: Model.Target, packages: Set<PackageIdentity>)]()\n\n        collections.forEach { collection in\n            collection.packages.forEach { package in\n                // Avoid copy-on-write: remove entry from dictionary before mutating\n                var entry = packageCollections.removeValue(forKey: package.identity) ?? (package, .init())\n                entry.collections.insert(collection.identifier)\n                packageCollections[package.identity] = entry\n\n                package.versions.forEach { version in\n                    version.manifests.values.forEach { manifest in\n                        manifest.targets.forEach { target in\n                            // Avoid copy-on-write: remove entry from dictionary before mutating\n                            var entry = targetsPackages.removeValue(forKey: target.name) ?? (target: target, packages: .init())\n                            entry.packages.insert(package.identity)\n                            targetsPackages[target.name] = entry\n                        }\n                    }\n                }\n            }\n        }\n\n        return targetsPackages.map { _, pair in\n            let targetPackages = pair.packages\n                .compactMap { packageCollections[$0] }\n                .map { pair -> Model.TargetListResult.Package in\n                    let versions = pair.package.versions.flatMap { version in\n                        version.manifests.values.map { manifest in\n                            Model.TargetListResult.PackageVersion(\n                                version: version.version,\n                                toolsVersion: manifest.toolsVersion,\n                                packageName: manifest.packageName\n                            )\n                        }\n                    }\n                    return .init(identity: pair.package.identity,\n                                 location: pair.package.location,\n                                 summary: pair.package.summary,\n                                 versions: versions,\n                                 collections: Array(pair.collections))\n                }\n\n            return Model.TargetListItem(target: pair.target, packages: targetPackages)\n        }\n    }\n\n    internal static func mergedPackageMetadata(package: Model.Package,\n                                               basicMetadata: Model.PackageBasicMetadata?) -> Model.Package {\n        // This dictionary contains recent releases and might not contain everything that's in package.versions.\n        let basicVersionMetadata = basicMetadata.map { Dictionary($0.versions.map { ($0.version, $0) }, uniquingKeysWith: { first, _ in first }) } ?? [:]\n        var versions = package.versions.map { packageVersion -> Model.Package.Version in\n            let versionMetadata = basicVersionMetadata[packageVersion.version]\n            return .init(version: packageVersion.version,\n                         title: versionMetadata?.title ?? packageVersion.title,\n                         summary: versionMetadata?.summary ?? packageVersion.summary,\n                         manifests: packageVersion.manifests,\n                         defaultToolsVersion: packageVersion.defaultToolsVersion,\n                         verifiedCompatibility: packageVersion.verifiedCompatibility,\n                         license: packageVersion.license,\n                         author: versionMetadata?.author ?? packageVersion.author,\n                         signer: packageVersion.signer,\n                         createdAt: versionMetadata?.createdAt ?? packageVersion.createdAt)\n        }\n        versions.sort(by: >)\n\n        return Model.Package(\n            identity: package.identity,\n            location: package.location,\n            summary: basicMetadata?.summary ?? package.summary,\n            keywords: basicMetadata?.keywords ?? package.keywords,\n            versions: versions,\n            watchersCount: basicMetadata?.watchersCount,\n            readmeURL: basicMetadata?.readmeURL ?? package.readmeURL,\n            license: basicMetadata?.license ?? package.license,\n            authors: basicMetadata?.authors ?? package.authors,\n            languages: basicMetadata?.languages ?? package.languages\n        )\n    }\n}\n\nprivate struct UnknownProvider: Error {\n    let sourceType: Model.CollectionSourceType\n\n    init(_ sourceType: Model.CollectionSourceType) {\n        self.sourceType = sourceType\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/PackageIndex+Configuration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\npublic struct PackageIndexConfiguration: Equatable {\n    public var url: URL?\n    public var searchResultMaxItemsCount: Int\n    public var cacheDirectory: AbsolutePath\n    public var cacheTTLInSeconds: Int\n    public var cacheMaxSizeInMegabytes: Int\n    \n    // TODO: rdar://87575573 remove feature flag\n    public internal(set) var enabled = ProcessInfo.processInfo.environment[\"SWIFTPM_ENABLE_PACKAGE_INDEX\"] == \"1\"\n    \n    public init(\n        url: URL? = nil,\n        searchResultMaxItemsCount: Int? = nil,\n        disableCache: Bool = false,\n        cacheDirectory: AbsolutePath? = nil,\n        cacheTTLInSeconds: Int? = nil,\n        cacheMaxSizeInMegabytes: Int? = nil\n    ) {\n        self.url = url\n        self.searchResultMaxItemsCount = searchResultMaxItemsCount ?? 50\n        self.cacheDirectory = (try? cacheDirectory.map(resolveSymlinks)) ?? (try? localFileSystem.swiftPMCacheDirectory.appending(components: \"package-metadata\")) ?? .root\n        self.cacheTTLInSeconds = disableCache ? -1 : (cacheTTLInSeconds ?? 3600)\n        self.cacheMaxSizeInMegabytes = cacheMaxSizeInMegabytes ?? 10\n    }\n}\n\npublic struct PackageIndexConfigurationStorage {\n    private let path: AbsolutePath\n    private let fileSystem: FileSystem\n\n    private let encoder: JSONEncoder\n    private let decoder: JSONDecoder\n\n    public init(path: AbsolutePath, fileSystem: FileSystem) {\n        self.path = path\n        self.fileSystem = fileSystem\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n    }\n    \n    public func load() throws -> PackageIndexConfiguration {\n        guard self.fileSystem.exists(self.path) else {\n            return .init()\n        }\n        let data: Data = try self.fileSystem.readFileContents(self.path)\n        guard data.count > 0 else {\n            return .init()\n        }\n        let container = try decoder.decode(StorageModel.Container.self, from: data)\n        return try PackageIndexConfiguration(container.index)\n    }\n\n    public func save(_ configuration: PackageIndexConfiguration) throws {\n        if !self.fileSystem.exists(self.path.parentDirectory) {\n            try self.fileSystem.createDirectory(self.path.parentDirectory, recursive: true)\n        }\n        let container = StorageModel.Container(configuration)\n        let buffer = try encoder.encode(container)\n        try self.fileSystem.writeFileContents(self.path, data: buffer)\n    }\n    \n    @discardableResult\n    public func update(with handler: (inout PackageIndexConfiguration) throws -> Void) throws -> PackageIndexConfiguration {\n        let configuration = try self.load()\n        var updatedConfiguration = configuration\n        try handler(&updatedConfiguration)\n        if updatedConfiguration != configuration {\n            try self.save(updatedConfiguration)\n        }\n        return updatedConfiguration\n    }\n}\n\nprivate enum StorageModel {\n    struct Container: Codable {\n        var index: Index\n\n        init(_ from: PackageIndexConfiguration) {\n            self.index = .init(\n                url: from.url?.absoluteString,\n                searchResultMaxItemsCount: from.searchResultMaxItemsCount,\n                cacheDirectory: from.cacheDirectory.pathString,\n                cacheTTLInSeconds: from.cacheTTLInSeconds,\n                cacheMaxSizeInMegabytes: from.cacheMaxSizeInMegabytes\n            )\n        }\n    }\n\n    struct Index: Codable {\n        let url: String?\n        let searchResultMaxItemsCount: Int?\n        let cacheDirectory: String?\n        let cacheTTLInSeconds: Int?\n        let cacheMaxSizeInMegabytes: Int?\n    }\n}\n\n// MARK: - Utility\n\nprivate extension PackageIndexConfiguration {\n    init(_ from: StorageModel.Index) throws {\n        let url: URL?\n        switch from.url {\n        case .none:\n            url = nil\n        case .some(let urlString):\n            url = URL(string: urlString)\n            guard url != nil else {\n                throw SerializationError.invalidURL(urlString)\n            }\n        }\n        \n        let cacheDirectory: AbsolutePath?\n        switch from.cacheDirectory {\n        case .none:\n            cacheDirectory = nil\n        case .some(let path):\n            cacheDirectory = try? AbsolutePath(validating: path)\n            guard cacheDirectory != nil else {\n                throw SerializationError.invalidPath(path)\n            }\n        }\n\n        self.init(\n            url: url,\n            searchResultMaxItemsCount: from.searchResultMaxItemsCount,\n            cacheDirectory: cacheDirectory,\n            cacheTTLInSeconds: from.cacheTTLInSeconds,\n            cacheMaxSizeInMegabytes: from.cacheMaxSizeInMegabytes\n        )\n    }\n}\n\nprivate enum SerializationError: Error {\n    case invalidURL(String)\n    case invalidPath(String)\n}\n"
  },
  {
    "path": "Sources/PackageCollections/PackageIndex.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport Foundation\nimport PackageModel\n\nimport protocol TSCBasic.Closable\n\nstruct PackageIndex: PackageIndexProtocol, Closable {\n    private let configuration: PackageIndexConfiguration\n    private let httpClient: LegacyHTTPClient\n    private let callbackQueue: DispatchQueue\n    private let observabilityScope: ObservabilityScope\n    \n    private let decoder: JSONDecoder\n\n    private let cache: SQLiteBackedCache<CacheValue>?\n    \n    var isEnabled: Bool {\n        self.configuration.enabled && self.configuration.url != .none\n    }\n\n    init(\n        configuration: PackageIndexConfiguration,\n        customHTTPClient: LegacyHTTPClient? = nil,\n        callbackQueue: DispatchQueue,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.configuration = configuration\n        self.httpClient = customHTTPClient ?? Self.makeDefaultHTTPClient()\n        self.callbackQueue = callbackQueue\n        self.observabilityScope = observabilityScope\n        \n        self.decoder = JSONDecoder.makeWithDefaults()\n        \n        if configuration.cacheTTLInSeconds > 0 {\n            var cacheConfig = SQLiteBackedCacheConfiguration()\n            cacheConfig.maxSizeInMegabytes = configuration.cacheMaxSizeInMegabytes\n            self.cache = SQLiteBackedCache<CacheValue>(\n                tableName: \"package_index_cache\",\n                path: configuration.cacheDirectory.appending(\"index-package-metadata.db\"),\n                configuration: cacheConfig\n            )\n        } else {\n            self.cache = nil\n        }\n    }\n    \n    func close() throws {\n        try self.cache?.close()\n    }\n\n    func getPackageMetadata(\n        identity: PackageIdentity,\n        location: String?\n    ) async throws -> PackageCollectionsModel.PackageMetadata {\n        let url = try await self.urlIfConfigured()\n        if let cached = try? self.cache?.get(key: identity.description),\n           cached.dispatchTime + DispatchTimeInterval.seconds(self.configuration.cacheTTLInSeconds) > DispatchTime.now() {\n            return (package: cached.package, collections: [], provider: self.createContext(host: url.host, error: nil))\n        }\n\n        // TODO: rdar://87582621 call package index's get metadata API\n        let metadataURL = url.appendingPathComponent(\"packages\").appendingPathComponent(identity.description)\n        let response = try await self.httpClient.get(metadataURL)\n        switch response.statusCode {\n        case 200:\n            guard let package = try response.decodeBody(PackageCollectionsModel.Package.self, using: self.decoder) else {\n                throw PackageIndexError.invalidResponse(metadataURL, \"Empty body\")\n            }\n\n            do {\n                try self.cache?.put(\n                    key: identity.description,\n                    value: CacheValue(package: package, timestamp: DispatchTime.now()),\n                    replace: true,\n                    observabilityScope: self.observabilityScope\n                )\n            } catch {\n                self.observabilityScope.emit(\n                    warning: \"Failed to save index metadata for package \\(identity) to cache\",\n                    underlyingError: error\n                )\n            }\n\n            return (package: package, collections: [], provider: self.createContext(host: url.host, error: nil))\n        default:\n            throw PackageIndexError.invalidResponse(metadataURL, \"Invalid status code: \\(response.statusCode)\")\n        }\n    }\n    \n    func findPackages(\n        _ query: String\n    ) async throws -> PackageCollectionsModel.PackageSearchResult {\n        let url = try await self.urlIfConfigured()\n        guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true) else {\n            throw PackageIndexError.invalidURL(url)\n        }\n        urlComponents.path = (urlComponents.path.last == \"/\" ? \"\" : \"/\") + \"search\"\n        urlComponents.queryItems = [\n            URLQueryItem(name: \"q\", value: query),\n        ]\n\n        // TODO: rdar://87582621 call package index's search API\n        guard let searchURL = urlComponents.url else {\n            throw PackageIndexError.invalidURL(url)\n        }\n        let response = try await self.httpClient.get(searchURL)\n        switch response.statusCode {\n        case 200:\n            guard let packages = try response.decodeBody([PackageCollectionsModel.Package].self, using: self.decoder) else {\n                throw PackageIndexError.invalidResponse(searchURL, \"Empty body\")\n            }\n            // Limit the number of items\n            let items = packages[..<min(packages.count, self.configuration.searchResultMaxItemsCount)].map {\n                PackageCollectionsModel.PackageSearchResult.Item(package: $0, indexes: [url])\n            }\n            return PackageCollectionsModel.PackageSearchResult(items: items)\n        default:\n            throw PackageIndexError.invalidResponse(searchURL, \"Invalid status code: \\(response.statusCode)\")\n        }\n    }\n\n    func listPackages(\n        offset: Int,\n        limit: Int\n    ) async throws -> PackageCollectionsModel.PaginatedPackageList {\n        let url = try await self.urlIfConfigured()\n\n        guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true) else {\n            throw PackageIndexError.invalidURL(url)\n        }\n        urlComponents.path = (urlComponents.path.last == \"/\" ? \"\" : \"/\") + \"packages\"\n        urlComponents.queryItems = [\n            URLQueryItem(name: \"offset\", value: \"\\(offset)\"),\n            URLQueryItem(name: \"limit\", value: \"\\(limit)\"),\n        ]\n\n        // TODO: rdar://87582621 call package index's list API\n        guard let listURL = urlComponents.url else {\n            throw PackageIndexError.invalidURL(url)\n        }\n        let response = try await self.httpClient.get(listURL)\n        switch response.statusCode {\n        case 200:\n            guard let listResponse = try response.decodeBody(ListResponse.self, using: self.decoder) else {\n                throw PackageIndexError.invalidResponse(listURL, \"Empty body\")\n            }\n            return PackageCollectionsModel.PaginatedPackageList(\n                items: listResponse.items,\n                offset: offset,\n                limit: limit,\n                total: listResponse.total\n            )\n        default:\n            throw PackageIndexError.invalidResponse(listURL, \"Invalid status code: \\(response.statusCode)\")\n        }\n    }\n\n    private func urlIfConfigured() async throws -> URL {\n        guard self.configuration.enabled else {\n            throw PackageIndexError.featureDisabled\n        }\n        guard let url = self.configuration.url else {\n            throw PackageIndexError.notConfigured\n        }\n        return url\n    }\n    \n    private func createContext(host: String?, error: Error?) -> PackageMetadataProviderContext? {\n        let name = host ?? \"package index\"\n        return PackageMetadataProviderContext(\n            name: name,\n            // Package index doesn't require auth\n            authTokenType: nil,\n            isAuthTokenConfigured: true\n        )\n    }\n    \n    private static func makeDefaultHTTPClient() -> LegacyHTTPClient {\n        let client = LegacyHTTPClient()\n        // TODO: make these defaults configurable?\n        client.configuration.requestTimeout = .seconds(1)\n        client.configuration.retryStrategy = .exponentialBackoff(maxAttempts: 3, baseDelay: .milliseconds(50))\n        client.configuration.circuitBreakerStrategy = .hostErrors(maxErrors: 50, age: .seconds(30))\n        return client\n    }\n\n    private struct CacheValue: Codable {\n        let package: Model.Package\n        let timestamp: UInt64\n\n        var dispatchTime: DispatchTime {\n            DispatchTime(uptimeNanoseconds: self.timestamp)\n        }\n\n        init(package: Model.Package, timestamp: DispatchTime) {\n            self.package = package\n            self.timestamp = timestamp.uptimeNanoseconds\n        }\n    }\n}\n\nextension PackageIndex {\n    struct ListResponse: Codable {\n        let items: [PackageCollectionsModel.Package]\n        let total: Int\n    }\n}\n\n// MARK: - PackageMetadataProvider conformance\n\nextension PackageIndex: PackageMetadataProvider {\n    func get(\n        identity: PackageIdentity,\n        location: String\n    ) async -> (Result<PackageCollectionsModel.PackageBasicMetadata, Error>, PackageMetadataProviderContext?) {\n        do {\n            let metadata = try await self.getPackageMetadata(identity: identity, location: location)\n\n            let package = metadata.package\n            let basicMetadata = PackageCollectionsModel.PackageBasicMetadata(\n                summary: package.summary,\n                keywords: package.keywords,\n                versions: package.versions.map { version in\n                    PackageCollectionsModel.PackageBasicVersionMetadata(\n                        version: version.version,\n                        title: version.title,\n                        summary: version.summary,\n                        author: version.author,\n                        createdAt: version.createdAt\n                    )\n                },\n                watchersCount: package.watchersCount,\n                readmeURL: package.readmeURL,\n                license: package.license,\n                authors: package.authors,\n                languages: package.languages\n            )\n            return (.success(basicMetadata), metadata.provider)\n        } catch {\n            return (.failure(error), nil)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/PackageIndexAndCollections.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport struct Foundation.URL\nimport PackageModel\n\nimport protocol TSCBasic.Closable\n\npublic struct PackageIndexAndCollections: Closable {\n    private let index: PackageIndexProtocol\n    private let collections: PackageCollectionsProtocol\n    private let observabilityScope: ObservabilityScope\n    \n    public init(\n        indexConfiguration: PackageIndexConfiguration = .init(),\n        collectionsConfiguration: PackageCollections.Configuration = .init(),\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        let index = PackageIndex(\n            configuration: indexConfiguration,\n            callbackQueue: .sharedConcurrent,\n            observabilityScope: observabilityScope\n        )\n        let metadataProvider = PackageIndexMetadataProvider(\n            index: index,\n            alternativeContainer: (\n                provider: GitHubPackageMetadataProvider(\n                    configuration: .init(authTokens: collectionsConfiguration.authTokens),\n                    observabilityScope: observabilityScope\n                ),\n                managed: true\n            )\n        )\n        \n        self.index = index\n        self.collections = PackageCollections(\n            configuration: collectionsConfiguration,\n            customMetadataProvider: metadataProvider,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n        self.observabilityScope = observabilityScope\n    }\n    \n    init(index: PackageIndexProtocol, collections: PackageCollectionsProtocol, observabilityScope: ObservabilityScope) {\n        self.index = index\n        self.collections = collections\n        self.observabilityScope = observabilityScope\n    }\n    \n    public func close() throws {\n        if let index = self.index as? Closable {\n            try index.close()\n        }\n        if let collections = self.collections as? Closable {\n            try collections.close()\n        }\n    }\n    \n    // MARK: - Package collection specific APIs\n    \n    public func listCollections(\n        identifiers: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> [PackageCollectionsModel.Collection] {\n        try await self.collections.listCollections(identifiers: identifiers)\n    }\n\n    \n    public func refreshCollections() async throws -> [PackageCollectionsModel.CollectionSource] {\n        try await self.collections.refreshCollections()\n    }\n\n    public func refreshCollection(_ source: PackageCollectionsModel.CollectionSource) async throws -> PackageCollectionsModel.Collection {\n        try await self.collections.refreshCollection(source)\n    }\n\n    public func addCollection(\n        _ source: PackageCollectionsModel.CollectionSource,\n        order: Int? = nil,\n        trustConfirmationProvider: ((PackageCollectionsModel.Collection, @escaping (Bool) -> Void) -> Void)? = nil\n    ) async throws -> PackageCollectionsModel.Collection {\n        try await self.collections.addCollection(\n            source,\n            order: order,\n            trustConfirmationProvider: trustConfirmationProvider\n        )\n    }\n    \n    public func removeCollection(\n        _ source: PackageCollectionsModel.CollectionSource\n    ) async throws {\n        try await self.collections.removeCollection(source)\n    }\n\n    public func getCollection(\n        _ source: PackageCollectionsModel.CollectionSource\n    ) async throws -> PackageCollectionsModel.Collection {\n        try await self.collections.getCollection(source)\n    }\n\n    public func listPackages(\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> PackageCollectionsModel.PackageSearchResult {\n        try await self.collections.listPackages(collections: collections)\n    }\n    \n    public func listTargets(\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> PackageCollectionsModel.TargetListResult {\n        try await self.collections.listTargets(collections: collections)\n    }\n\n    public func findTargets(\n        _ query: String,\n        searchType: PackageCollectionsModel.TargetSearchType? = nil,\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> PackageCollectionsModel.TargetSearchResult {\n        try await self.collections.findTargets(\n            query,\n            searchType: searchType,\n            collections: collections\n        )\n    }\n\n\n    // MARK: - Package index specific APIs\n\n    /// Indicates if package index is configured.\n    public func isIndexEnabled() -> Bool {\n        self.index.isEnabled\n    }\n    \n    public func listPackagesInIndex(\n        offset: Int,\n        limit: Int\n    ) async throws -> PackageCollectionsModel.PaginatedPackageList {\n        try await self.index.listPackages(offset: offset, limit: limit)\n    }\n\n\n    // MARK: - APIs that make use of both package index and collections\n\n    /// Returns metadata for the package identified by the given `PackageIdentity`, using package index (if configured)\n    /// and collections data.\n    ///\n    /// A failure is returned if the package is not found.\n    ///\n    /// - Parameters:\n    ///   - identity: The package identity\n    ///   - location: The package location (optional for deduplication)\n    ///   - collections: Optional. If specified, only these collections are used to construct the result.\n    public func getPackageMetadata(\n        identity: PackageIdentity,\n        location: String? = nil,\n        collections: Set<PackageCollectionsModel.CollectionIdentifier>? = nil\n    ) async throws -> PackageCollectionsModel.PackageMetadata {\n        // Package index not available - fallback to collections\n        guard self.index.isEnabled else {\n            return try await self.collections.getPackageMetadata(identity: identity, location: location, collections: collections)\n        }\n\n        // This uses package index only\n        async let indexResult = self.index.getPackageMetadata(identity: identity, location: location)\n\n        // This uses either package index or \"alternative\" (e.g., GitHub) as metadata provider,\n        // then merge the supplementary metadata with data coming from collections. The package\n        // must belong to at least one collection.\n        async let collectionsResult = self.collections.getPackageMetadata(identity: identity, location: location, collections: collections)\n\n\n        do {\n            let indexPackageMetadata = try await indexResult\n            return PackageCollectionsModel.PackageMetadata(\n                package: indexPackageMetadata.package,\n                collections: (try? await collectionsResult)?.collections ?? [],\n                provider: indexPackageMetadata.provider\n            )\n        } catch {\n            self.observabilityScope.emit(warning: \"PackageIndex.getPackageMetadata failed: \\(error)\")\n            do {\n                return try await collectionsResult\n            } catch let collectionsError {\n                self.observabilityScope.emit(warning: \"PackageCollections.getPackageMetadata failed: \\(collectionsError)\")\n            }\n            throw error\n        }\n    }\n\n    /// Finds and returns packages that match the query.\n    ///\n    /// - Parameters:\n    ///   - query: The search query\n    ///   - in: Indicates whether to search in the index only, collections only, or both.\n    ///         The optional `Set<CollectionIdentifier>` in some enum cases restricts search within those collections only.\n    public func findPackages(\n        _ query: String,\n        in searchIn: SearchIn = .both(collections: nil)\n    ) async throws -> PackageCollectionsModel.PackageSearchResult {\n        switch searchIn {\n        case .index:\n            guard self.index.isEnabled else {\n                self.observabilityScope.emit(debug: \"Package index is not enabled. Returning empty result.\")\n                return PackageCollectionsModel.PackageSearchResult(items: [])\n            }\n            return try await self.index.findPackages(query)\n        case .collections(let collections):\n            return try await self.collections.findPackages(query, collections: collections)\n        case .both(let collections):\n            // Find packages in both package index and collections\n            async let pendingIndexPackages = self.index.findPackages(query)\n            async let pendingcollectionPackages = self.collections.findPackages(query, collections: collections)\n\n            do {\n                let indexSearchResult = try await pendingIndexPackages\n                do {\n                    let collectionsSearchResult = try await pendingcollectionPackages\n\n                    let indexItems = Dictionary(uniqueKeysWithValues: indexSearchResult.items.map {\n                        (SearchResultItemKey(identity: $0.package.identity, location: $0.package.location), $0)\n                    })\n                    let collectionItems = Dictionary(uniqueKeysWithValues: collectionsSearchResult.items.map {\n                        (SearchResultItemKey(identity: $0.package.identity, location: $0.package.location), $0)\n                    })\n\n                    // An array of combined results, with index items listed first.\n                    var items = [PackageCollectionsModel.PackageSearchResult.Item]()\n                    // Iterating through the dictionary would simplify the code, but we want to keep the ordering of the search result.\n                    indexSearchResult.items.forEach {\n                        var item = $0\n                        let key = SearchResultItemKey(identity: $0.package.identity, location: $0.package.location)\n                        // This item is found in collections too\n                        if let collectionsMatch = collectionItems[key] {\n                            item.collections = collectionsMatch.collections\n                        }\n                        items.append(item)\n                    }\n                    collectionsSearchResult.items.forEach {\n                        let key = SearchResultItemKey(identity: $0.package.identity, location: $0.package.location)\n                        // This item is found in index as well, but skipping since it has already been handled in the loop above.\n                        guard indexItems[key] == nil else {\n                            return\n                        }\n                        items.append($0)\n                    }\n                    return PackageCollectionsModel.PackageSearchResult(items: items)\n\n                } catch let collectionsError {\n                    self.observabilityScope.emit(warning: \"PackageCollections.findPackages failed: \\(collectionsError)\")\n\n                    // Collections query failed, try another way to find the collections that an item belongs to.\n                    do {\n                        let collectionsSearchResult = try await self.collections.listPackages(collections: collections)\n                        let items = indexSearchResult.items.map { item in\n                            PackageCollectionsModel.PackageSearchResult.Item(\n                                package: item.package,\n                                collections: collectionsSearchResult.items.first(where: {\n                                    item.package.identity == $0.package.identity && item.package.location == $0.package.location\n                                })?.collections ?? [],\n                                indexes: item.indexes\n                            )\n                        }\n                        return PackageCollectionsModel.PackageSearchResult(items: items)\n                    } catch {\n                        return indexSearchResult\n                    }\n                }\n            } catch let indexError {\n                self.observabilityScope.emit(warning: \"PackageIndex.findPackages failed: \\(indexError)\")\n                do {\n                    return try await pendingcollectionPackages\n                } catch let collectionsError {\n                    // Failed to find packages through `PackageIndex` and `PackageCollections`.\n                    // Return index's error.\n                    self.observabilityScope.emit(warning: \"PackageCollections.findPackages failed: \\(collectionsError)\")\n                    throw indexError\n                }\n            }\n\n            struct SearchResultItemKey: Hashable {\n                let identity: PackageIdentity\n                let location: String\n            }\n        }\n    }\n    \n    private enum Source: Hashable {\n        case index\n        case collections\n    }\n}\n\nstruct PackageIndexMetadataProvider: PackageMetadataProvider, Closable {\n    typealias ProviderContainer = (provider: PackageMetadataProvider, managed: Bool)\n    \n    let index: PackageIndex\n    let alternativeContainer: ProviderContainer\n    \n    var alternative: PackageMetadataProvider {\n        self.alternativeContainer.provider\n    }\n\n    func get(\n        identity: PackageIdentity,\n        location: String\n    ) async -> (Result<PackageCollectionsModel.PackageBasicMetadata, Error>, PackageMetadataProviderContext?) {\n        if self.index.isEnabled {\n            return await self.index.get(identity: identity, location: location)\n        } else {\n            return await self.alternative.get(identity: identity, location: location)\n        }\n    }\n    \n    func close() throws {\n        guard self.alternativeContainer.managed else {\n            return\n        }\n        if let alternative = self.alternative as? Closable {\n            try alternative.close()\n        }\n    }\n}\n\nextension PackageIndexAndCollections {\n    public enum SearchIn {\n        case index\n        case collections(Set<PackageCollectionsModel.CollectionIdentifier>?)\n        case both(collections: Set<PackageCollectionsModel.CollectionIdentifier>?)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport struct Foundation.NSRange\nimport class Foundation.NSRegularExpression\nimport struct Foundation.URL\nimport PackageModel\n\nimport protocol TSCBasic.Closable\n\nimport struct TSCUtility.Version\n\nstruct GitHubPackageMetadataProvider: PackageMetadataProvider, Closable {\n    private static let apiHostPrefix = \"api.\"\n    private static let service = Model.Package.Author.Service(name: \"GitHub\")\n\n    let configuration: Configuration\n    private let observabilityScope: ObservabilityScope\n    private let httpClient: LegacyHTTPClient\n    private let decoder: JSONDecoder\n\n    private let cache: SQLiteBackedCache<CacheValue>?\n\n    init(configuration: Configuration = .init(), observabilityScope: ObservabilityScope, httpClient: LegacyHTTPClient? = nil) {\n        self.configuration = configuration\n        self.observabilityScope = observabilityScope\n        self.httpClient = httpClient ?? Self.makeDefaultHTTPClient()\n        self.decoder = JSONDecoder.makeWithDefaults()\n        if configuration.cacheTTLInSeconds > 0 {\n            var cacheConfig = SQLiteBackedCacheConfiguration()\n            cacheConfig.maxSizeInMegabytes = configuration.cacheSizeInMegabytes\n            self.cache = SQLiteBackedCache<CacheValue>(\n                tableName: \"github_cache\",\n                path: configuration.cacheDir.appending(\"package-metadata.db\"),\n                configuration: cacheConfig\n            )\n        } else {\n            self.cache = nil\n        }\n    }\n\n    func close() throws {\n        try self.cache?.close()\n    }\n\n    func get(\n        identity: PackageModel.PackageIdentity,\n        location: String\n    ) async -> (Result<PackageCollectionsModel.PackageBasicMetadata, any Error>, PackageMetadataProviderContext?) {\n        guard let baseURL = Self.apiURL(location) else {\n            return self.metadataErrorResponse(GitHubPackageMetadataProviderError.invalidSourceControlURL(location), apiHost: nil)\n        }\n        // TODO: baseURL.host is used / unwrapped repeatedly does it make sense to proceed if baseURL.host is nil?\n\n        if let cached = try? self.cache?.get(key: identity.description) {\n            if cached.dispatchTime + DispatchTimeInterval.seconds(self.configuration.cacheTTLInSeconds) > DispatchTime.now() {\n                return (.success(cached.package), self.createContext(apiHost: baseURL.host, error: nil))\n            }\n        }\n\n        do {\n            let metadataURL = baseURL\n            // TODO: make `per_page` configurable? GitHub API's max/default is 100\n            let releasesURL = URL(string: baseURL.appendingPathComponent(\"releases\").absoluteString + \"?per_page=20\") ?? baseURL.appendingPathComponent(\"releases\")\n            let contributorsURL = baseURL.appendingPathComponent(\"contributors\")\n            let readmeURL = baseURL.appendingPathComponent(\"readme\")\n            let licenseURL = baseURL.appendingPathComponent(\"license\")\n            let languagesURL = baseURL.appendingPathComponent(\"languages\")\n\n            // get the main data\n            var metadataHeaders = HTTPClientHeaders()\n            metadataHeaders.add(name: \"Accept\", value: \"application/vnd.github.mercy-preview+json\")\n            let metadataOptions = self.makeRequestOptions(validResponseCodes: [200, 401, 403, 404])\n            let hasAuthorization = metadataOptions.authorizationProvider?(metadataURL) != nil\n            let response = try await httpClient.get(metadataURL, headers: metadataHeaders, options: metadataOptions)\n\n            let apiLimit = response.headers.get(\"X-RateLimit-Limit\").first.flatMap(Int.init) ?? -1\n            let apiRemaining = response.headers.get(\"X-RateLimit-Remaining\").first.flatMap(Int.init) ?? -1\n            switch (response.statusCode, hasAuthorization, apiRemaining) {\n            case (_, _, 0):\n                self.observabilityScope.emit(warning: \"Exceeded API limits on \\(metadataURL.host ?? metadataURL.absoluteString) (\\(apiRemaining)/\\(apiLimit)), consider configuring an API token for this service.\")\n                return self.metadataErrorResponse(GitHubPackageMetadataProviderError.apiLimitsExceeded(metadataURL, apiLimit), apiHost: baseURL.host)\n            case (401, true, _):\n                return self.metadataErrorResponse(GitHubPackageMetadataProviderError.invalidAuthToken(metadataURL), apiHost: baseURL.host)\n            case (401, false, _):\n                return self.metadataErrorResponse(GitHubPackageMetadataProviderError.permissionDenied(metadataURL), apiHost: baseURL.host)\n            case (403, _, _):\n                return self.metadataErrorResponse(GitHubPackageMetadataProviderError.permissionDenied(metadataURL), apiHost: baseURL.host)\n            case (404, _, _):\n                return self.metadataErrorResponse(NotFoundError(\"\\(baseURL)\"), apiHost: baseURL.host)\n            case (200, _, _):\n                if apiRemaining < self.configuration.apiLimitWarningThreshold {\n                    self.observabilityScope.emit(warning: \"Approaching API limits on \\(metadataURL.host ?? metadataURL.absoluteString) (\\(apiRemaining)/\\(apiLimit)), consider configuring an API token for this service.\")\n                }\n            default:\n                return self.metadataErrorResponse(GitHubPackageMetadataProviderError.invalidResponse(metadataURL, \"Invalid status code: \\(response.statusCode)\"), apiHost: baseURL.host)\n            }\n\n            let makeRequest = { (url: URL) async throws -> LegacyHTTPClient.Response in\n                var headers = HTTPClientHeaders()\n                headers.add(name: \"Accept\", value: \"application/vnd.github.v3+json\")\n                let options = self.makeRequestOptions(validResponseCodes: [200])\n                return try await self.httpClient.get(url, headers: headers, options: options)\n            }\n\n            async let releasesResponse = makeRequest(releasesURL)\n            async let contributorsResponse = makeRequest(contributorsURL)\n            async let readmeResponse = makeRequest(readmeURL)\n            async let licenseResponse = makeRequest(licenseURL)\n            async let languagesResponse = makeRequest(languagesURL)\n\n            // process results\n            guard let metadata = try response.decodeBody(GetRepositoryResponse.self, using: self.decoder) else {\n                throw GitHubPackageMetadataProviderError.invalidResponse(metadataURL, \"Invalid status code: \\(response.statusCode)\")\n            }\n            let releases = (try? await releasesResponse.decodeBody([Release].self, using: self.decoder)) ?? []\n            let contributors = try? await contributorsResponse.decodeBody([Contributor].self, using: self.decoder)\n            let readme = try? await readmeResponse.decodeBody(Readme.self, using: self.decoder)\n            let license = try? await licenseResponse.decodeBody(License.self, using: self.decoder)\n            let languages = try? await languagesResponse.decodeBody([String: Int].self, using: self.decoder)?.keys\n\n            let model = Model.PackageBasicMetadata(\n                summary: metadata.description,\n                keywords: metadata.topics,\n                // filters out non-semantic versioned tags\n                versions: releases.compactMap {\n                    guard let version = $0.tagName.flatMap(TSCUtility.Version.init(tag:)) else {\n                        return nil\n                    }\n                    return Model.PackageBasicVersionMetadata(\n                        version: version,\n                        title: $0.name,\n                        summary: $0.body,\n                        author: $0.author.map { .init(username: $0.login, url: $0.url, service: Self.service) },\n                        createdAt: $0.createdAt\n                    )\n                },\n                watchersCount: metadata.watchersCount,\n                readmeURL: readme?.downloadURL,\n                license: license.flatMap { .init(type: Model.LicenseType(string: $0.license.spdxID), url: $0.downloadURL) },\n                authors: contributors?.map { .init(username: $0.login, url: $0.url, service: Self.service) },\n                languages: languages.flatMap(Set.init) ?? metadata.language.map { [$0] }\n            )\n\n            do {\n                try self.cache?.put(\n                    key: identity.description,\n                    value: CacheValue(package: model, timestamp: DispatchTime.now()),\n                    replace: true,\n                    observabilityScope: self.observabilityScope\n                )\n            } catch {\n                self.observabilityScope.emit(\n                    warning: \"Failed to save GitHub metadata for package \\(identity) to cache\",\n                    underlyingError: error\n                )\n            }\n            return (.success(model), self.createContext(apiHost: baseURL.host, error: nil))\n        } catch {\n            return self.metadataErrorResponse(error, apiHost: baseURL.host)\n        }\n    }\n    \n    private func metadataErrorResponse(\n        _ error: Error,\n        apiHost: String?\n    ) -> (Result<PackageCollectionsModel.PackageBasicMetadata, any Error>, PackageMetadataProviderContext?) {\n        return (.failure(error), self.createContext(apiHost: apiHost, error: error))\n    }\n    \n    private func createContext(apiHost: String?, error: Error?) -> PackageMetadataProviderContext? {\n        // We can't do anything if we can't determine API host\n        guard let apiHost else {\n            return nil\n        }\n        \n        let authTokenType = self.getAuthTokenType(for: apiHost)\n        let isAuthTokenConfigured = self.configuration.authTokens()?[authTokenType] != nil\n        \n        // This provider should only deal with GitHub token type\n        guard case .github(let host) = authTokenType else {\n            return nil\n        }\n        \n        guard let error else {\n            // It's possible for the request to complete successfully without auth token configured, in\n            // which case we will hit the API limit much more easily, so we should always communicate\n            // auth token state to the caller (e.g., so it can prompt user to configure auth token).\n            return PackageMetadataProviderContext(\n                name: host,\n                authTokenType: authTokenType,\n                isAuthTokenConfigured: isAuthTokenConfigured\n            )\n        }\n        \n        switch error {\n        case let error as GitHubPackageMetadataProviderError:\n            guard let providerError = PackageMetadataProviderError.from(error) else {\n                // Only auth-related GitHub errors can be translated, so for all others\n                // assume this provider cannot be used for the package.\n                return nil\n            }\n            \n            return PackageMetadataProviderContext(\n                name: host,\n                authTokenType: authTokenType,\n                isAuthTokenConfigured: isAuthTokenConfigured,\n                error: providerError\n            )\n        default:\n            // For all other errors, including NotFoundError, assume this provider is not\n            // intended for the package (e.g., the repository might not be hosted on GitHub).\n            return nil\n        }\n    }\n    \n    private func getAuthTokenType(for host: String) -> AuthTokenType {\n        let host = host.hasPrefix(Self.apiHostPrefix) ? String(host.dropFirst(Self.apiHostPrefix.count)) : host\n        return .github(host)\n    }\n\n    // FIXME: use URL instead of string\n    internal static func apiURL(_ url: String) -> URL? {\n        do {\n            let regex = try NSRegularExpression(pattern: #\"([^/@]+)[:/]([^:/]+)/([^/.]+)(\\.git)?$\"#, options: .caseInsensitive)\n            if let match = regex.firstMatch(in: url, options: [], range: NSRange(location: 0, length: url.count)) {\n                if let hostRange = Range(match.range(at: 1), in: url),\n                    let ownerRange = Range(match.range(at: 2), in: url),\n                    let repoRange = Range(match.range(at: 3), in: url) {\n                    let host = String(url[hostRange])\n                    let owner = String(url[ownerRange])\n                    let repo = String(url[repoRange])\n\n                    return URL(string: \"https://\\(Self.apiHostPrefix)\\(host)/repos/\\(owner)/\\(repo)\")\n                }\n            }\n            return nil\n        } catch {\n            return nil\n        }\n    }\n\n    private func makeRequestOptions(validResponseCodes: [Int]) -> LegacyHTTPClientRequest.Options {\n        var options = LegacyHTTPClientRequest.Options()\n        options.addUserAgent = true\n        options.validResponseCodes = validResponseCodes\n        options.authorizationProvider = { url in\n            url.host.flatMap { host in\n                let tokenType = self.getAuthTokenType(for: host)\n                return self.configuration.authTokens()?[tokenType].flatMap { token in\n                    \"token \\(token)\"\n                }\n            }\n        }\n        return options\n    }\n\n    private static func makeDefaultHTTPClient() -> LegacyHTTPClient {\n        let client = LegacyHTTPClient()\n        // TODO: make these defaults configurable?\n        client.configuration.requestTimeout = .seconds(1)\n        client.configuration.retryStrategy = .exponentialBackoff(maxAttempts: 3, baseDelay: .milliseconds(50))\n        client.configuration.circuitBreakerStrategy = .hostErrors(maxErrors: 50, age: .seconds(30))\n        return client\n    }\n\n    public struct Configuration {\n        public var authTokens: () -> [AuthTokenType: String]?\n        public var apiLimitWarningThreshold: Int\n        public var cacheDir: AbsolutePath\n        public var cacheTTLInSeconds: Int\n        public var cacheSizeInMegabytes: Int\n\n        public init(\n            authTokens: @escaping () -> [AuthTokenType: String]? = { nil },\n            apiLimitWarningThreshold: Int? = nil,\n            disableCache: Bool = false,\n            cacheDir: AbsolutePath? = nil,\n            cacheTTLInSeconds: Int? = nil,\n            cacheSizeInMegabytes: Int? = nil            \n        ) {\n            self.authTokens = authTokens\n            self.apiLimitWarningThreshold = apiLimitWarningThreshold ?? 5\n            self.cacheDir = (try? cacheDir.map(resolveSymlinks)) ?? (try? localFileSystem.swiftPMCacheDirectory.appending(components: \"package-metadata\")) ?? .root\n            self.cacheTTLInSeconds = disableCache ? -1 : (cacheTTLInSeconds ?? 3600)\n            self.cacheSizeInMegabytes = cacheSizeInMegabytes ?? 10\n        }\n    }\n\n    private struct CacheValue: Codable {\n        let package: Model.PackageBasicMetadata\n        let timestamp: UInt64\n\n        var dispatchTime: DispatchTime {\n            DispatchTime(uptimeNanoseconds: self.timestamp)\n        }\n\n        init(package: Model.PackageBasicMetadata, timestamp: DispatchTime) {\n            self.package = package\n            self.timestamp = timestamp.uptimeNanoseconds\n        }\n    }\n}\n\nenum GitHubPackageMetadataProviderError: Error, Equatable {\n    case invalidSourceControlURL(String)\n    case invalidResponse(URL, String)\n    case permissionDenied(URL)\n    case invalidAuthToken(URL)\n    case apiLimitsExceeded(URL, Int)\n}\n\nprivate extension PackageMetadataProviderError {\n    static func from(_ error: GitHubPackageMetadataProviderError) -> PackageMetadataProviderError? {\n        switch error {\n        case .invalidResponse(_, let errorMessage):\n            return .invalidResponse(errorMessage: errorMessage)\n        case .permissionDenied:\n            return .permissionDenied\n        case .invalidAuthToken:\n            return .invalidAuthToken\n        case .apiLimitsExceeded:\n            return .apiLimitsExceeded\n        default:\n            // This metadata provider is not intended for the given package reference\n            return nil\n        }\n    }\n}\n\nextension GitHubPackageMetadataProvider {\n    fileprivate struct GetRepositoryResponse: Codable {\n        let name: String\n        let fullName: String\n        let description: String?\n        let topics: [String]?\n        let isPrivate: Bool\n        let isFork: Bool\n        let defaultBranch: String\n        let updatedAt: Date\n        let sshURL: URL\n        let cloneURL: URL\n        let tagsURL: URL\n        let contributorsURL: URL\n        let language: String?\n        let watchersCount: Int\n        let forksCount: Int\n\n        private enum CodingKeys: String, CodingKey {\n            case name\n            case fullName = \"full_name\"\n            case description\n            case topics\n            case isPrivate = \"private\"\n            case isFork = \"fork\"\n            case defaultBranch = \"default_branch\"\n            case updatedAt = \"updated_at\"\n            case sshURL = \"ssh_url\"\n            case cloneURL = \"clone_url\"\n            case tagsURL = \"tags_url\"\n            case contributorsURL = \"contributors_url\"\n            case language\n            case watchersCount = \"watchers_count\"\n            case forksCount = \"forks_count\"\n        }\n    }\n}\n\nextension GitHubPackageMetadataProvider {\n    fileprivate struct Release: Codable {\n        let name: String\n        let tagName: String?\n        // This might contain rich-text\n        let body: String?\n        let createdAt: Date\n        let publishedAt: Date?\n        let author: Author?\n\n        private enum CodingKeys: String, CodingKey {\n            case name\n            case tagName = \"tag_name\"\n            case body\n            case createdAt = \"created_at\"\n            case publishedAt = \"published_at\"\n            case author\n        }\n        \n        fileprivate struct Author: Codable {\n            let login: String\n            let url: URL?\n        }\n    }\n\n    fileprivate struct Tag: Codable {\n        let name: String\n        let tarballURL: URL\n        let commit: Commit\n\n        private enum CodingKeys: String, CodingKey {\n            case name\n            case tarballURL = \"tarball_url\"\n            case commit\n        }\n    }\n\n    fileprivate struct Commit: Codable {\n        let sha: String\n        let url: URL\n    }\n\n    fileprivate struct Contributor: Codable {\n        let login: String\n        let url: URL\n        let contributions: Int\n    }\n\n    fileprivate struct Readme: Codable {\n        let url: URL\n        let htmlURL: URL\n        let downloadURL: URL\n\n        private enum CodingKeys: String, CodingKey {\n            case url\n            case htmlURL = \"html_url\"\n            case downloadURL = \"download_url\"\n        }\n    }\n\n    fileprivate struct License: Codable {\n        let url: URL\n        let htmlURL: URL\n        let downloadURL: URL\n        let license: License\n\n        private enum CodingKeys: String, CodingKey {\n            case url\n            case htmlURL = \"html_url\"\n            case downloadURL = \"download_url\"\n            case license\n        }\n\n        fileprivate struct License: Codable {\n            let name: String\n            let spdxID: String\n\n            private enum CodingKeys: String, CodingKey {\n                case name\n                case spdxID = \"spdx_id\"\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Providers/JSONPackageCollectionProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\n\nimport Basics\nimport Dispatch\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport class Foundation.JSONDecoder\nimport class Foundation.ProcessInfo\nimport struct Foundation.URL\n\nimport PackageCollectionsModel\nimport PackageCollectionsSigning\nimport PackageModel\nimport SourceControl\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\nprivate typealias JSONModel = PackageCollectionModel.V1\n\nstruct JSONPackageCollectionProvider: PackageCollectionProvider {\n    // TODO: This can be removed when the `Security` framework APIs that the `PackageCollectionsSigning`\n    // module depends on are available on all Apple platforms.\n    #if os(macOS) || os(Linux) || os(Windows) || os(Android) || os(FreeBSD)\n    static let isSignatureCheckSupported = true\n    #else\n    static let isSignatureCheckSupported = false\n    #endif\n\n    static let defaultCertPolicyKeys: [CertificatePolicyKey] = [.default]\n\n    private let configuration: Configuration\n    private let fileSystem: FileSystem\n    private let observabilityScope: ObservabilityScope\n    private let httpClient: LegacyHTTPClient\n    private let decoder: JSONDecoder\n    private let validator: JSONModel.Validator\n    private let signatureValidator: PackageCollectionSignatureValidator\n    private let sourceCertPolicy: PackageCollectionSourceCertificatePolicy\n\n    init(\n        configuration: Configuration = .init(),\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        sourceCertPolicy: PackageCollectionSourceCertificatePolicy = PackageCollectionSourceCertificatePolicy(),\n        customHTTPClient: LegacyHTTPClient? = nil,\n        customSignatureValidator: PackageCollectionSignatureValidator? = nil\n    ) {\n        self.configuration = configuration\n        self.validator = JSONModel.Validator(configuration: configuration.validator)\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n        self.httpClient = customHTTPClient ?? Self.makeDefaultHTTPClient()\n        self.signatureValidator = customSignatureValidator ?? PackageCollectionSigning(\n            trustedRootCertsDir: configuration.trustedRootCertsDir ??\n                (try? fileSystem.swiftPMConfigurationDirectory.appending(\"trust-root-certs\").asURL) ?? Basics.AbsolutePath.root.asURL,\n            additionalTrustedRootCerts: sourceCertPolicy.allRootCerts.map { Array($0) },\n            observabilityScope: observabilityScope\n        )\n        self.sourceCertPolicy = sourceCertPolicy\n        self.decoder = JSONDecoder.makeWithDefaults()\n    }\n\n    func get(_ source: Model.CollectionSource) async throws -> Model.Collection {\n        guard case .json = source.type else {\n            throw InternalError(\n                \"JSONPackageCollectionProvider can only be used for fetching 'json' package collections\"\n            )\n        }\n\n        if let errors = source.validate(fileSystem: fileSystem)?.errors() {\n            throw JSONPackageCollectionProviderError.invalidSource(\"\\(errors)\")\n        }\n\n        // Source is a local file\n        if let absolutePath = source.absolutePath {\n            let data: Data = try self.fileSystem.readFileContents(absolutePath)\n            return try await self.decodeAndRunSignatureCheck(\n                source: source,\n                data: data,\n                certPolicyKeys: Self.defaultCertPolicyKeys\n            )\n        }\n\n        // first do a head request to check content size compared to the maximumSizeInBytes constraint\n        let headOptions = self.makeRequestOptions(validResponseCodes: [200])\n        let headers = self.makeRequestHeaders()\n        let response: LegacyHTTPClient.Response\n        do {\n            response = try await self.httpClient.head(source.url, headers: headers, options: headOptions)\n        } catch HTTPClientError.badResponseStatusCode(let statusCode) {\n            if statusCode == 404 {\n                throw JSONPackageCollectionProviderError\n                    .collectionNotFound(source.url)\n            }\n            throw JSONPackageCollectionProviderError\n                .collectionUnavailable(source.url, statusCode)\n        }\n        guard let contentLength = response.headers.get(\"Content-Length\").first.flatMap(Int64.init) else {\n            throw JSONPackageCollectionProviderError\n                .invalidResponse(source.url, \"Missing Content-Length header\")\n        }\n        guard contentLength <= self.configuration.maximumSizeInBytes else {\n            throw JSONPackageCollectionProviderError\n                .responseTooLarge(source.url, contentLength)\n        }\n        // next do a get request to get the actual content\n        var getOptions = self.makeRequestOptions(validResponseCodes: [200])\n        getOptions.maximumResponseSizeInBytes = self.configuration.maximumSizeInBytes\n\n        let getResponse: LegacyHTTPClient.Response\n        do {\n            getResponse = try await self.httpClient.get(source.url, headers: headers, options: getOptions)\n        } catch HTTPClientError.badResponseStatusCode(let statusCode) {\n            if statusCode == 404 {\n                throw JSONPackageCollectionProviderError\n                    .collectionNotFound(source.url)\n            }\n            throw JSONPackageCollectionProviderError\n                .collectionUnavailable(source.url, statusCode)\n        }\n\n        // check content length again so we can record this as a bad actor\n        // if not returning head and exceeding size\n        // TODO: store bad actors to prevent server DoS\n        guard let contentLength = getResponse.headers.get(\"Content-Length\").first.flatMap(Int64.init)\n        else {\n            throw JSONPackageCollectionProviderError\n                .invalidResponse(source.url, \"Missing Content-Length header\")\n        }\n        guard contentLength < self.configuration.maximumSizeInBytes else {\n            throw JSONPackageCollectionProviderError\n                .responseTooLarge(source.url, contentLength)\n        }\n        guard let body = getResponse.body else {\n            throw JSONPackageCollectionProviderError\n                .invalidResponse(source.url, \"Body is empty\")\n        }\n\n        let certPolicyKeys = self.sourceCertPolicy.certificatePolicyKeys(for: source) ?? Self\n            .defaultCertPolicyKeys\n        return try await self.decodeAndRunSignatureCheck(\n            source: source,\n            data: body,\n            certPolicyKeys: certPolicyKeys\n        )\n    }\n\n    private func decodeAndRunSignatureCheck(\n        source: Model.CollectionSource,\n        data: Data,\n        certPolicyKeys: [CertificatePolicyKey]\n    ) async throws -> Model.Collection {\n        let signedCollection: JSONModel.SignedCollection\n        do {\n            // This fails if collection is not signed (i.e., no \"signature\")\n            signedCollection = try self.decoder.decode(JSONModel.SignedCollection.self, from: data)\n        } catch {\n            // Bad: collection is supposed to be signed but it isn't\n            guard !self.sourceCertPolicy.mustBeSigned(source: source) else {\n                throw PackageCollectionError.missingSignature\n            }\n            // Collection is unsigned\n            guard let collection = try? self.decoder.decode(JSONModel.Collection.self, from: data) else {\n                throw JSONPackageCollectionProviderError.invalidJSON(source.url)\n            }\n            return try self.makeCollection(from: collection, source: source, signature: nil)\n        }\n        if source.skipSignatureCheck {\n            // Don't validate signature; set isVerified=false\n            return try self.makeCollection(\n                from: signedCollection.collection,\n                source: source,\n                signature: Model.SignatureData(from: signedCollection.signature, isVerified: false)\n            )\n        } else if !Self.isSignatureCheckSupported {\n            throw StringError(\"Unsupported platform\")\n        }\n        // Check the signature\n        do {\n            return try await withThrowingTaskGroup(of: Void.self) { group in\n                for certPolicyKey in certPolicyKeys {\n                    group.addTask {\n                        try await self.signatureValidator.validate(\n                            signedCollection: signedCollection,\n                            certPolicyKey: certPolicyKey\n                        )\n                    }\n                }\n\n                // if there is one valid key return the validated collection\n                // otherwise throw the error for the last key\n                var results = 0\n                while results < certPolicyKeys.count {\n                    results += 1\n                    do {\n                        try await group.next()\n                        break\n                    } catch {\n                        if results == certPolicyKeys.count {\n                            throw error\n                        }\n                    }\n                }\n                return try self.makeCollection(\n                    from: signedCollection.collection,\n                    source: source,\n                    signature: Model.SignatureData(from: signedCollection.signature, isVerified: true)\n                )\n            }\n        } catch {\n            self.observabilityScope.emit(\n                warning: \"The signature of package collection [\\(source)] is invalid\",\n                underlyingError: error\n            )\n            if PackageCollectionSigningError\n                .noTrustedRootCertsConfigured == error as? PackageCollectionSigningError\n            {\n                throw PackageCollectionError.cannotVerifySignature\n            } else {\n                throw PackageCollectionError.invalidSignature\n            }\n        }\n    }\n\n    private func makeCollection(\n        from collection: JSONModel.Collection,\n        source: Model.CollectionSource,\n        signature: Model.SignatureData?\n    ) throws -> Model.Collection {\n        if let errors = self.validator.validate(collection: collection)?.errors() {\n            throw JSONPackageCollectionProviderError\n                .invalidCollection(\"\\(errors.map(\\.message).joined(separator: \" \"))\")\n        }\n\n        var serializationOkay = true\n        let packages = try collection.packages.map { package -> Model.Package in\n            let versions = try package.versions.compactMap { version -> Model.Package.Version? in\n                // note this filters out / ignores missing / bad data in attempt to make the most out of the\n                // provided set\n                guard let parsedVersion = TSCUtility.Version(tag: version.version) else {\n                    return nil\n                }\n\n                let manifests: [ToolsVersion: Model.Package.Version.Manifest] =\n                try Dictionary(throwingUniqueKeysWithValues: version.manifests.compactMap { key, value in\n                    guard let keyToolsVersion = ToolsVersion(string: key),\n                          let manifestToolsVersion = ToolsVersion(string: value.toolsVersion)\n                    else {\n                        return nil\n                    }\n\n                    let targets = value.targets.map { Model.Target(name: $0.name, moduleName: $0.moduleName) }\n                    if targets.count != value.targets.count {\n                        serializationOkay = false\n                    }\n                    let products = value.products\n                        .compactMap { Model.Product(from: $0, packageTargets: targets) }\n                    if products.count != value.products.count {\n                        serializationOkay = false\n                    }\n                    let minimumPlatformVersions: [PackageModel.SupportedPlatform]? = value\n                        .minimumPlatformVersions?\n                        .compactMap { PackageModel.SupportedPlatform(from: $0) }\n                    if minimumPlatformVersions?.count != value.minimumPlatformVersions?.count {\n                        serializationOkay = false\n                    }\n\n                    let manifest = Model.Package.Version.Manifest(\n                        toolsVersion: manifestToolsVersion,\n                        packageName: value.packageName,\n                        targets: targets,\n                        products: products,\n                        minimumPlatformVersions: minimumPlatformVersions\n                    )\n                    return (keyToolsVersion, manifest)\n                })\n                if manifests.count != version.manifests.count {\n                    serializationOkay = false\n                }\n\n                guard let defaultToolsVersion = ToolsVersion(string: version.defaultToolsVersion) else {\n                    return nil\n                }\n\n                let verifiedCompatibility = version.verifiedCompatibility?\n                    .compactMap { Model.Compatibility(from: $0) }\n                if verifiedCompatibility?.count != version.verifiedCompatibility?.count {\n                    serializationOkay = false\n                }\n                let license = version.license.flatMap { Model.License(from: $0) }\n\n                let signer: Model.Signer?\n                if let versionSigner = version.signer,\n                   let signerType = Model.SignerType(rawValue: versionSigner.type.lowercased())\n                {\n                    signer = .init(\n                        type: signerType,\n                        commonName: versionSigner.commonName,\n                        organizationalUnitName: versionSigner.organizationalUnitName,\n                        organizationName: versionSigner.organizationName\n                    )\n                } else {\n                    signer = nil\n                }\n\n                return .init(\n                    version: parsedVersion,\n                    title: nil,\n                    summary: version.summary,\n                    manifests: manifests,\n                    defaultToolsVersion: defaultToolsVersion,\n                    verifiedCompatibility: verifiedCompatibility,\n                    license: license,\n                    author: version.author.map { .init(username: $0.name, url: nil, service: nil) },\n                    signer: signer,\n                    createdAt: version.createdAt\n                )\n            }\n            if versions.count != package.versions.count {\n                serializationOkay = false\n            }\n\n            // If package identity is set, use that. Otherwise create one from URL.\n            return .init(\n                identity: package.identity.map { PackageIdentity.plain($0) } ?? PackageIdentity(url: SourceControlURL(package.url)),\n                location: package.url.absoluteString,\n                summary: package.summary,\n                keywords: package.keywords,\n                versions: versions,\n                watchersCount: nil,\n                readmeURL: package.readmeURL,\n                license: package.license.flatMap { Model.License(from: $0) },\n                authors: nil,\n                languages: nil\n            )\n        }\n\n        if !serializationOkay {\n            self.observabilityScope\n                .emit(\n                    warning: \"Some of the information from \\(collection.name) could not be deserialized correctly, likely due to invalid format. Contact the collection's author (\\(collection.generatedBy?.name ?? \"n/a\")) to address this issue.\"\n                )\n        }\n\n        return .init(\n            source: source,\n            name: collection.name,\n            overview: collection.overview,\n            keywords: collection.keywords,\n            packages: packages,\n            createdAt: collection.generatedAt,\n            createdBy: collection.generatedBy.flatMap { Model.Collection.Author(name: $0.name) },\n            signature: signature,\n            lastProcessedAt: Date()\n        )\n    }\n\n    private func makeRequestOptions(validResponseCodes: [Int]) -> LegacyHTTPClientRequest.Options {\n        var options = LegacyHTTPClientRequest.Options()\n        options.addUserAgent = true\n        options.validResponseCodes = validResponseCodes\n        return options\n    }\n\n    private func makeRequestHeaders() -> HTTPClientHeaders {\n        var headers = HTTPClientHeaders()\n        // Include \"Accept-Encoding\" header so we receive \"Content-Length\" header in the response\n        headers.add(name: \"Accept-Encoding\", value: \"deflate, identity, gzip;q=0\")\n        return headers\n    }\n\n    private static func makeDefaultHTTPClient() -> LegacyHTTPClient {\n        let client = LegacyHTTPClient()\n        // TODO: make these defaults configurable?\n        client.configuration.requestTimeout = .seconds(5)\n        client.configuration.retryStrategy = .exponentialBackoff(maxAttempts: 3, baseDelay: .milliseconds(50))\n        client.configuration.circuitBreakerStrategy = .hostErrors(maxErrors: 50, age: .seconds(30))\n        return client\n    }\n\n    public struct Configuration {\n        public var maximumSizeInBytes: Int64\n        public var trustedRootCertsDir: URL?\n\n        var validator: PackageCollectionModel.V1.Validator.Configuration\n\n        public var maximumPackageCount: Int {\n            get {\n                self.validator.maximumPackageCount\n            }\n            set(newValue) {\n                self.validator.maximumPackageCount = newValue\n            }\n        }\n\n        public var maximumMajorVersionCount: Int {\n            get {\n                self.validator.maximumMajorVersionCount\n            }\n            set(newValue) {\n                self.validator.maximumMajorVersionCount = newValue\n            }\n        }\n\n        public var maximumMinorVersionCount: Int {\n            get {\n                self.validator.maximumMinorVersionCount\n            }\n            set(newValue) {\n                self.validator.maximumMinorVersionCount = newValue\n            }\n        }\n\n        public init(\n            maximumSizeInBytes: Int64? = nil,\n            trustedRootCertsDir: URL? = nil,\n            maximumPackageCount: Int? = nil,\n            maximumMajorVersionCount: Int? = nil,\n            maximumMinorVersionCount: Int? = nil\n        ) {\n            // TODO: where should we read defaults from?\n            self.maximumSizeInBytes = maximumSizeInBytes ?? 5_000_000 // 5MB\n            self.trustedRootCertsDir = trustedRootCertsDir\n            self.validator = JSONModel.Validator.Configuration(\n                maximumPackageCount: maximumPackageCount,\n                maximumMajorVersionCount: maximumMajorVersionCount,\n                maximumMinorVersionCount: maximumMinorVersionCount\n            )\n        }\n    }\n}\n\npublic enum JSONPackageCollectionProviderError: Error, Equatable, CustomStringConvertible {\n    case invalidSource(String)\n    case invalidJSON(URL)\n    case invalidCollection(String)\n    case invalidResponse(URL, String)\n    case responseTooLarge(URL, Int64)\n    case collectionNotFound(URL)\n    case collectionUnavailable(URL, Int)\n\n    public var description: String {\n        switch self {\n        case .invalidSource(let errorMessage), .invalidCollection(let errorMessage):\n            return errorMessage\n        case .invalidJSON(let url):\n            return \"The package collection at \\(url.absoluteString) contains invalid JSON.\"\n        case .invalidResponse(let url, let message):\n            return \"Received invalid response for package collection at \\(url.absoluteString): \\(message)\"\n        case .responseTooLarge(let url, _):\n            return \"The package collection at \\(url.absoluteString) is too large.\"\n        case .collectionNotFound(let url):\n            return \"No package collection found at \\(url.absoluteString). Please make sure the URL is correct.\"\n        case .collectionUnavailable(let url, _):\n            return \"The package collection at \\(url.absoluteString) is unavailable. Please make sure the URL is correct or try again later.\"\n        }\n    }\n}\n\n// MARK: - Extensions for mapping from JSON to PackageCollectionsModel\n\nextension Model.Product {\n    fileprivate init(from: JSONModel.Product, packageTargets: [Model.Target]) {\n        let targets = packageTargets.filter { from.targets.map { $0.lowercased() }.contains($0.name.lowercased()) }\n        self = .init(name: from.name, type: .init(from: from.type), targets: targets)\n    }\n}\n\nextension PackageModel.ProductType {\n    fileprivate init(from: JSONModel.ProductType) {\n        switch from {\n        case .library(let libraryType):\n            self = .library(.init(from: libraryType))\n        case .executable:\n            self = .executable\n        case .plugin:\n            self = .plugin\n        case .snippet:\n            self = .snippet\n        case .test:\n            self = .test\n        case .macro:\n            self = .macro\n        }\n    }\n}\n\nextension PackageModel.ProductType.LibraryType {\n    fileprivate init(from: JSONModel.ProductType.LibraryType) {\n        switch from {\n        case .static:\n            self = .static\n        case .dynamic:\n            self = .dynamic\n        case .automatic:\n            self = .automatic\n        }\n    }\n}\n\nextension PackageModel.SupportedPlatform {\n    fileprivate init?(from: JSONModel.PlatformVersion) {\n        guard let platform = Platform(name: from.name) else {\n            return nil\n        }\n        let version = PlatformVersion(from.version)\n        self.init(platform: platform, version: version)\n    }\n}\n\nextension PackageModel.Platform {\n    fileprivate init?(from: JSONModel.Platform) {\n        self.init(name: from.name)\n    }\n\n    fileprivate init?(name: String) {\n        switch name.lowercased() {\n        case let name where name.contains(\"macos\"):\n            self = PackageModel.Platform.macOS\n        case let name where name.contains(\"maccatalyst\"):\n            self = PackageModel.Platform.macCatalyst\n        case let name where name.contains(\"ios\"):\n            self = PackageModel.Platform.iOS\n        case let name where name.contains(\"tvos\"):\n            self = PackageModel.Platform.tvOS\n        case let name where name.contains(\"watchos\"):\n            self = PackageModel.Platform.watchOS\n        case let name where name.contains(\"visionos\"):\n            self = PackageModel.Platform.visionOS\n        case let name where name.contains(\"driverkit\"):\n            self = PackageModel.Platform.driverKit\n        case let name where name.contains(\"linux\"):\n            self = PackageModel.Platform.linux\n        case let name where name.contains(\"android\"):\n            self = PackageModel.Platform.android\n        case let name where name.contains(\"windows\"):\n            self = PackageModel.Platform.windows\n        case let name where name.contains(\"wasi\"):\n            self = PackageModel.Platform.wasi\n        case let name where name.contains(\"openbsd\"):\n            self = PackageModel.Platform.openbsd\n        case let name where name.contains(\"freebsd\"):\n            self = PackageModel.Platform.freebsd\n        default:\n            return nil\n        }\n    }\n}\n\nextension Model.Compatibility {\n    fileprivate init?(from: JSONModel.Compatibility) {\n        guard let platform = PackageModel.Platform(from: from.platform),\n              let swiftVersion = SwiftLanguageVersion(string: from.swiftVersion)\n        else {\n            return nil\n        }\n        self.init(platform: platform, swiftVersion: swiftVersion)\n    }\n}\n\nextension Model.License {\n    fileprivate init(from: JSONModel.License) {\n        self.init(type: Model.LicenseType(string: from.name), url: from.url)\n    }\n}\n\nextension Model.SignatureData {\n    fileprivate init(from: JSONModel.Signature, isVerified: Bool) {\n        self.certificate = .init(from: from.certificate)\n        self.isVerified = isVerified\n    }\n}\n\nextension Model.SignatureData.Certificate {\n    fileprivate init(from: JSONModel.Signature.Certificate) {\n        self.subject = .init(from: from.subject)\n        self.issuer = .init(from: from.issuer)\n    }\n}\n\nextension Model.SignatureData.Certificate.Name {\n    fileprivate init(from: JSONModel.Signature.Certificate.Name) {\n        self.userID = from.userID\n        self.commonName = from.commonName\n        self.organizationalUnit = from.organizationalUnit\n        self.organization = from.organization\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Providers/PackageCollectionProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// `PackageCollection` provider. For example, package feeds, (future) Package Index.\nprotocol PackageCollectionProvider {\n    /// Retrieves `PackageCollection` from the specified source.\n    ///\n    /// - Parameters:\n    ///   - source: Where the `PackageCollection` is located\n    func get(_ source: Model.CollectionSource) async throws -> Model.Collection\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Providers/PackageMetadataProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.Date\nimport struct Foundation.URL\n\nimport PackageModel\n\nimport struct TSCUtility.Version\n\n/// `PackageBasicMetadata` provider\nprotocol PackageMetadataProvider {\n\n    // TODO: Review if this API is correct\n    // This API is awkward because it unconditionally provides a context\n    // Does it make sense to have a context if you don't have metadata?\n    // The only use of provider on failure is PackageCollections.getPackageMetadata\n    // It would be nice to change the API to\n    // async throw -> (PackageCollectionsModel.PackageBasicMetadata, PackageMetadataProviderContext?)\n    // or even\n    // async throw -> (PackageCollectionsModel.PackageBasicMetadata, PackageMetadataProviderContext)\n\n    /// Retrieves metadata for a package with the given identity and repository address.\n    ///\n    /// - Parameters:\n    ///   - identity: The package's identity\n    ///   - location: The package's location\n    func get(\n        identity: PackageIdentity,\n        location: String\n    ) async -> (Result<PackageCollectionsModel.PackageBasicMetadata, Error>, PackageMetadataProviderContext?)\n}\n\nextension Model {\n    struct PackageBasicMetadata: Equatable, Codable {\n        let summary: String?\n        let keywords: [String]?\n        let versions: [PackageBasicVersionMetadata]\n        let watchersCount: Int?\n        let readmeURL: URL?\n        let license: PackageCollectionsModel.License?\n        let authors: [PackageCollectionsModel.Package.Author]?\n        let languages: Set<String>?\n    }\n\n    struct PackageBasicVersionMetadata: Equatable, Codable {\n        let version: TSCUtility.Version\n        let title: String?\n        let summary: String?\n        let author: PackageCollectionsModel.Package.Author?\n        let createdAt: Date?\n    }\n}\n\npublic struct PackageMetadataProviderContext: Equatable {\n    public let name: String\n    public let authTokenType: AuthTokenType?\n    public let isAuthTokenConfigured: Bool\n    public let error: PackageMetadataProviderError?\n\n    init(\n        name: String,\n        authTokenType: AuthTokenType?,\n        isAuthTokenConfigured: Bool,\n        error: PackageMetadataProviderError? = nil\n    ) {\n        self.name = name\n        self.authTokenType = authTokenType\n        self.isAuthTokenConfigured = isAuthTokenConfigured\n        self.error = error\n    }\n}\n\npublic enum PackageMetadataProviderError: Error, Equatable {\n    case invalidResponse(errorMessage: String)\n    case permissionDenied\n    case invalidAuthToken\n    case apiLimitsExceeded\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Storage/FilePackageCollectionsSourcesStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Basics\nimport Dispatch\nimport TSCBasic\nimport struct Foundation.Data\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\nimport struct Foundation.URL\n\nstruct FilePackageCollectionsSourcesStorage: PackageCollectionsSourcesStorage {\n    let fileSystem: FileSystem\n    let path: Basics.AbsolutePath\n\n    private let encoder: JSONEncoder\n    private let decoder: JSONDecoder\n\n    init(fileSystem: FileSystem, path: Basics.AbsolutePath? = nil) {\n        self.fileSystem = fileSystem\n\n        self.path = path ?? (try? fileSystem.swiftPMConfigurationDirectory.appending(\"collections.json\")) ?? .root\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n    }\n\n    func list() async throws -> [PackageCollectionsModel.CollectionSource] {\n        try self.withLock {\n            try self.loadFromDisk()\n        }\n    }\n\n    func add(source: PackageCollectionsModel.CollectionSource, order: Int? = nil) async throws {\n        try self.withLock {\n            var sources = try self.loadFromDisk()\n            sources = sources.filter { $0 != source }\n            let order = order.flatMap { $0 >= 0 && $0 < sources.endIndex ? order : sources.endIndex } ?? sources.endIndex\n            sources.insert(source, at: order)\n            try self.saveToDisk(sources)\n        }\n    }\n\n    func remove(source: PackageCollectionsModel.CollectionSource) async throws {\n        try self.withLock {\n            var sources = try self.loadFromDisk()\n            sources = sources.filter { $0 != source }\n            try self.saveToDisk(sources)\n        }\n    }\n\n    func move(source: PackageCollectionsModel.CollectionSource, to order: Int) async throws {\n        try self.withLock {\n            var sources = try self.loadFromDisk()\n            sources = sources.filter { $0 != source }\n            let order = order >= 0 && order < sources.endIndex ? order : sources.endIndex\n            sources.insert(source, at: order)\n            try self.saveToDisk(sources)\n        }\n    }\n\n    func exists(source: PackageCollectionsModel.CollectionSource) async throws -> Bool {\n        try self.withLock {\n            try self.loadFromDisk()\n        }.contains(source)\n    }\n\n    func update(source: PackageCollectionsModel.CollectionSource) async throws {\n        try self.withLock {\n            var sources = try self.loadFromDisk()\n            if let index = sources.firstIndex(where: { $0 == source }) {\n                sources[index] = source\n                try self.saveToDisk(sources)\n            }\n        }\n    }\n\n    private func loadFromDisk() throws -> [Model.CollectionSource] {\n        guard self.fileSystem.exists(self.path) else {\n            return .init()\n        }\n        let data: Data = try fileSystem.readFileContents(self.path)\n        guard data.count > 0 else {\n            return .init()\n        }\n        let container = try decoder.decode(StorageModel.Container.self, from: data)\n        return try container.sources()\n    }\n\n    private func saveToDisk(_ sources: [Model.CollectionSource]) throws {\n        if !self.fileSystem.exists(self.path.parentDirectory) {\n            try self.fileSystem.createDirectory(self.path.parentDirectory, recursive: true)\n        }\n        let container = StorageModel.Container(sources)\n        let buffer = try encoder.encode(container)\n        try self.fileSystem.writeFileContents(self.path, data: buffer)\n    }\n\n    private func withLock<T>(_ body: () throws -> T) throws -> T {\n        if !fileSystem.exists(self.path.parentDirectory) {\n            try self.fileSystem.createDirectory(self.path.parentDirectory, recursive: true)\n        }\n        return try self.fileSystem.withLock(on: self.path.parentDirectory, type: .exclusive, body)\n    }\n}\n\n// MARK: - FilePackageCollectionsSourcesStorage Serialization\n\nprivate enum StorageModel {\n    struct Container: Codable {\n        var data: [Source]\n\n        init() {\n            self.data = .init()\n        }\n\n        init(_ from: [Model.CollectionSource]) {\n            self.data = from.map { $0.source() }\n        }\n\n        func sources() throws -> [Model.CollectionSource] {\n            return try self.data.map { try Model.CollectionSource($0) }\n        }\n    }\n\n    struct Source: Codable {\n        let type: String\n        let value: String\n        let isTrusted: Bool?\n        let skipSignatureCheck: Bool?\n    }\n\n    enum SourceType: String {\n        case json\n    }\n}\n\n// MARK: - Utility\n\nprivate extension Model.CollectionSource {\n    init(_ from: StorageModel.Source) throws {\n        guard let url = URL(string: from.value) else {\n            throw SerializationError.invalidURL(from.value)\n        }\n\n        switch from.type {\n        case StorageModel.SourceType.json.rawValue:\n            self.init(type: .json, url: url, isTrusted: from.isTrusted, skipSignatureCheck: from.skipSignatureCheck ?? false)\n        default:\n            throw SerializationError.unknownType(from.type)\n        }\n    }\n\n    func source() -> StorageModel.Source {\n        switch self.type {\n        case .json:\n            return .init(type: StorageModel.SourceType.json.rawValue, value: self.url.absoluteString,\n                         isTrusted: self.isTrusted, skipSignatureCheck: self.skipSignatureCheck)\n        }\n    }\n}\n\nprivate enum SerializationError: Error {\n    case unknownType(String)\n    case invalidURL(String)\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Storage/PackageCollectionsSourcesStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\npublic protocol PackageCollectionsSourcesStorage {\n    /// Lists all `PackageCollectionSource`s.\n    func list() async throws -> [PackageCollectionsModel.CollectionSource]\n\n    /// Adds the given source.\n    ///\n    /// - Parameters:\n    ///   - source: The `PackageCollectionSource` to add\n    ///   - order: Optional. The order that the source should take after being added.\n    ///            By default the new source is appended to the end (i.e., the least relevant order).\n    func add(source: PackageCollectionsModel.CollectionSource,\n             order: Int?) async throws\n\n    /// Removes the given source.\n    ///\n    /// - Parameters:\n    ///   - source: The `PackageCollectionSource` to remove\n    ///   - profile: The `Profile` to remove source\n    func remove(source: PackageCollectionsModel.CollectionSource) async throws\n\n    /// Moves source to a different order.\n    ///\n    /// - Parameters:\n    ///   - source: The `PackageCollectionSource` to move\n    ///   - order: The order that the source should take.\n    func move(source: PackageCollectionsModel.CollectionSource, to order: Int) async throws\n\n    /// Checks if a source has already been added.\n    ///\n    /// - Parameters:\n    ///   - source: The `PackageCollectionSource`\n    func exists(source: PackageCollectionsModel.CollectionSource) async throws -> Bool\n\n    /// Updates the given source.\n    ///\n    /// - Parameters:\n    ///   - source: The `PackageCollectionSource` to update\n    func update(source: PackageCollectionsModel.CollectionSource) async throws\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Storage/PackageCollectionsStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport PackageModel\nimport Basics\n\npublic protocol PackageCollectionsStorage {\n    /// Writes `PackageCollection` to storage.\n    ///\n    /// - Parameters:\n    ///   - collection: The `PackageCollection`\n    func put(collection: PackageCollectionsModel.Collection) async throws -> PackageCollectionsModel.Collection\n\n    /// Removes `PackageCollection` from storage.\n    ///\n    /// - Parameters:\n    ///   - identifier: The identifier of the `PackageCollection`\n    func remove(identifier: PackageCollectionsModel.CollectionIdentifier) async throws\n\n    /// Returns `PackageCollection` for the given identifier.\n    ///\n    /// - Parameters:\n    ///   - identifier: The identifier of the `PackageCollection`\n    func get(identifier: PackageCollectionsModel.CollectionIdentifier) async throws -> PackageCollectionsModel.Collection\n\n    /// Returns `PackageCollection`s for the given identifiers, or all if none specified.\n    ///\n    /// - Parameters:\n    ///   - identifiers: Optional. The identifiers of the `PackageCollection`\n    func list(identifiers: [PackageCollectionsModel.CollectionIdentifier]?) async throws -> [PackageCollectionsModel.Collection]\n\n    /// Returns `PackageSearchResult` for the given search criteria.\n    ///\n    /// - Parameters:\n    ///   - identifiers: Optional. The identifiers of the `PackageCollection`s\n    ///   - query: The search query expression\n    func searchPackages(\n        identifiers: [PackageCollectionsModel.CollectionIdentifier]?,\n        query: String\n    ) async throws -> PackageCollectionsModel.PackageSearchResult\n\n    /// Returns packages for the given package identity.\n    ///\n    /// Since a package identity can be associated with more than one repository URL, the result may contain multiple items.\n    ///\n    /// - Parameters:\n    ///   - identifier: The package identifier\n    ///   - collectionIdentifiers: Optional. The identifiers of the `PackageCollection`s\n    func findPackage(\n        identifier: PackageIdentity,\n        collectionIdentifiers: [PackageCollectionsModel.CollectionIdentifier]?\n    ) async throws -> (packages: [PackageCollectionsModel.Package], collections: [PackageCollectionsModel.CollectionIdentifier])\n\n    /// Returns `TargetSearchResult` for the given search criteria.\n    ///\n    /// - Parameters:\n    ///   - identifiers: Optional. The identifiers of the `PackageCollection`\n    ///   - query: The search query expression\n    ///   - type: The search type\n    func searchTargets(\n        identifiers: [PackageCollectionsModel.CollectionIdentifier]?,\n        query: String,\n        type: PackageCollectionsModel.TargetSearchType\n    ) async throws -> PackageCollectionsModel.TargetSearchResult\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport struct Foundation.Data\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\nimport class Foundation.NSLock\nimport struct Foundation.URL\nimport PackageModel\nimport TSCUtility\n\nimport protocol TSCBasic.Closable\n\nfinal class SQLitePackageCollectionsStorage: PackageCollectionsStorage, Closable {\n    private static let packageCollectionsTableName = \"package_collections\"\n    private static let packagesFTSName = \"fts_packages\"\n    private static let targetsFTSNameV0 = \"fts_targets\" // TODO: remove as this has been replaced by v1\n    private static let targetsFTSNameV1 = \"fts_targets_1\"\n\n    let fileSystem: FileSystem\n    let location: SQLite.Location\n    let configuration: Configuration\n\n    private let observabilityScope: ObservabilityScope\n\n    private let encoder: JSONEncoder\n    private let decoder: JSONDecoder\n\n    private var state = State.idle\n    private let stateLock = NSLock()\n\n    private let cache = ThreadSafeKeyValueStore<Model.CollectionIdentifier, Model.Collection>()\n\n    // NSLock helps prevent concurrency errors with transaction statements during e.g. `refreshCollections`,\n    // since only one transaction is allowed per SQLite connection. We need transactions to speed up bulk updates.\n    // TODO: we could potentially optimize this with db connection pool\n    private let ftsLock = NSLock()\n    // FTS not supported on some platforms; the code falls back to \"slow path\" in that case\n    // marked internal for testing\n    internal let useSearchIndices = ThreadSafeBox<Bool>(false)\n\n    // Targets have in-memory trie in addition to SQLite FTS as optimization\n    private let targetTrie = Trie<CollectionPackage>()\n    private var targetTrieReady: Bool?\n    private let populateTargetTrieLock = NSLock()\n\n    init(location: SQLite.Location? = nil, configuration: Configuration = .init(), observabilityScope: ObservabilityScope) {\n        self.location = location ?? (try? .path(localFileSystem.swiftPMCacheDirectory.appending(components: \"package-collection.db\"))) ?? .memory\n        switch self.location {\n        case .path, .temporary:\n            self.fileSystem = localFileSystem\n        case .memory:\n            self.fileSystem = InMemoryFileSystem()\n        }\n        self.configuration = configuration\n        self.observabilityScope = observabilityScope\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n\n        if configuration.initializeTargetTrie {\n            self.populateTargetTrie()\n        }\n    }\n\n    convenience init(path: AbsolutePath, observabilityScope: ObservabilityScope) {\n        self.init(location: .path(path), observabilityScope: observabilityScope)\n    }\n\n    deinit {\n        guard case .disconnected = (try? self.withStateLock { self.state }) else {\n            return self.observabilityScope.emit(warning: \"SQLitePackageCollectionsStorage de-initialized but db is not closed\")\n        }\n    }\n\n    func close() throws {\n        func retryClose(db: SQLite, exponentialBackoff: inout ExponentialBackoff) throws {\n            let semaphore = DispatchSemaphore(value: 0)\n            let callback = { (result: Result<Void, Error>) in\n                // If it has failed, the semaphore will timeout in which case we will retry\n                if case .success = result {\n                    semaphore.signal()\n                }\n            }\n\n            // This throws error if we have exhausted our attempts\n            let delay = try exponentialBackoff.nextDelay()\n            DispatchQueue.sharedConcurrent.asyncAfter(deadline: .now() + delay) {\n                do {\n                    try db.close()\n                    callback(.success(()))\n                } catch {\n                    callback(.failure(error))\n                }\n            }\n            // Add some buffer to allow `asyncAfter` to run\n            guard case .success = semaphore.wait(timeout: .now() + delay + .milliseconds(50)) else {\n                return try retryClose(db: db, exponentialBackoff: &exponentialBackoff)\n            }\n        }\n\n        // Signal long-running operation (e.g., populateTargetTrie) to stop\n        if case .connected(let db) = try self.withStateLock({ self.state }) {\n            try self.withStateLock {\n                self.state = .disconnecting(db)\n            }\n\n            do {\n                try db.close()\n            } catch {\n                do {\n                    var exponentialBackoff = ExponentialBackoff()\n                    try retryClose(db: db, exponentialBackoff: &exponentialBackoff)\n                } catch {\n                    throw StringError(\"Failed to close database\")\n                }\n            }\n        }\n\n        try self.withStateLock {\n            self.state = .disconnected\n        }\n    }\n\n    func put(collection: PackageCollectionsModel.Collection) async throws -> PackageCollectionsModel.Collection {\n\n        let dbCollection = try? await self.get(identifier: collection.identifier)\n\n        // write to db\n        let query = \"INSERT OR REPLACE INTO \\(Self.packageCollectionsTableName) VALUES (?, ?);\"\n        try self.executeStatement(query) { statement -> Void in\n            let data = try self.encoder.encode(collection)\n\n            let bindings: [SQLite.SQLiteValue] = [\n                .string(collection.identifier.databaseKey()),\n                .blob(data),\n            ]\n            try statement.bind(bindings)\n            try statement.step()\n        }\n\n        if dbCollection?.packages != collection.packages {\n            try self.insertToSearchIndices(collection: collection)\n        }\n        self.cache[collection.identifier] = collection\n        return collection\n    }\n\n    func remove(identifier: PackageCollectionsModel.CollectionIdentifier) async throws {\n        // write to db\n        let query = \"DELETE FROM \\(Self.packageCollectionsTableName) WHERE key = ?;\"\n        try self.executeStatement(query) { statement -> Void in\n            let bindings: [SQLite.SQLiteValue] = [\n                .string(identifier.databaseKey()),\n            ]\n            try statement.bind(bindings)\n            try statement.step()\n        }\n\n        // remove from search indices\n        try self.removeFromSearchIndices(identifier: identifier)\n\n        // write to cache\n        self.cache[identifier] = nil\n    }\n\n    func get(identifier: PackageCollectionsModel.CollectionIdentifier) async throws -> PackageCollectionsModel.Collection {\n        // try read to cache\n        if let collection = self.cache[identifier] {\n            return collection\n        }\n\n        // go to db if not found\n        let query = \"SELECT value FROM \\(Self.packageCollectionsTableName) WHERE key = ? LIMIT 1;\"\n        return try self.executeStatement(query) { statement -> Model.Collection in\n            try statement.bind([.string(identifier.databaseKey())])\n\n            let row = try statement.step()\n            guard let data = row?.blob(at: 0) else {\n                throw NotFoundError(\"\\(identifier)\")\n            }\n\n            return try self.decoder.decode(Model.Collection.self, from: data)\n        }\n    }\n\n    func list(identifiers: [PackageCollectionsModel.CollectionIdentifier]? = nil) async throws -> [PackageCollectionsModel.Collection] {\n        // try read to cache\n        let cached = identifiers?.compactMap { self.cache[$0] }\n        if let cached, cached.count > 0, cached.count == identifiers?.count {\n            return cached\n        }\n\n        // go to db if not found\n        var blobs = [Data]()\n        if let identifiers {\n            var index = 0\n            while index < identifiers.count {\n                let slice = identifiers[index ..< min(index + self.configuration.batchSize, identifiers.count)]\n                let query = \"SELECT value FROM \\(Self.packageCollectionsTableName) WHERE key in (\\(slice.map { _ in \"?\" }.joined(separator: \",\")));\"\n                try self.executeStatement(query) { statement in\n                    try statement.bind(slice.compactMap { .string($0.databaseKey()) })\n                    while let row = try statement.step() {\n                        blobs.append(row.blob(at: 0))\n                    }\n                }\n                index += self.configuration.batchSize\n            }\n        } else {\n            let query = \"SELECT value FROM \\(Self.packageCollectionsTableName);\"\n            try self.executeStatement(query) { statement in\n                while let row = try statement.step() {\n                    blobs.append(row.blob(at: 0))\n                }\n            }\n        }\n\n        // decoding is a performance bottleneck (10+s for 1000 collections)\n        // workaround is to decode in parallel if list is large enough to justify it\n        let collections: [Model.Collection]\n        if blobs.count < self.configuration.batchSize {\n            collections = blobs.compactMap { data -> Model.Collection? in\n                try? self.decoder.decode(Model.Collection.self, from: data)\n            }\n        } else {\n            collections = await withTaskGroup(of: Model.Collection?.self) { group in\n                for data in blobs {\n                    group.addTask {\n                        try? self.decoder.decode(Model.Collection.self, from: data)\n                    }\n                }\n\n                return await group\n                    .compactMap { $0 }\n                    .reduce(into:[Model.Collection]()) {\n                        $0.append($1)\n                    }\n            }\n        }\n        if collections.count != blobs.count {\n            self.observabilityScope.emit(warning: \"Some stored collections could not be deserialized. Please refresh the collections to resolve this issue.\")\n        }\n        return collections\n    }\n\n    func searchPackages(\n        identifiers: [PackageCollectionsModel.CollectionIdentifier]? = nil,\n        query: String\n    ) async throws -> PackageCollectionsModel.PackageSearchResult {\n        guard try self.shouldUseSearchIndices() else {\n            let collections = try await self.list(identifiers: identifiers)\n\n            let queryString = query.lowercased()\n            let collectionsPackages = collections.reduce([Model.CollectionIdentifier: [Model.Package]]()) { partial, collection in\n                var map = partial\n                map[collection.identifier] = collection.packages.filter { package in\n                    if package.identity.description.lowercased().contains(queryString) { return true }\n                    if package.location.lowercased().contains(queryString) { return true }\n                    if let summary = package.summary, summary.lowercased().contains(queryString) { return true }\n                    if let keywords = package.keywords, (keywords.map { $0.lowercased() }).contains(queryString) { return true }\n                    return package.versions.contains(where: { version in\n                        version.manifests.values.contains { manifest in\n                            if manifest.packageName.lowercased().contains(queryString) { return true }\n                            if manifest.products.contains(where: { $0.name.lowercased().contains(queryString) }) { return true }\n                            return manifest.targets.contains(where: { $0.name.lowercased().contains(queryString) })\n                        }\n                    })\n                }\n                return map\n            }\n\n            var packageCollections = [PackageIdentity: (package: Model.Package, collections: Set<Model.CollectionIdentifier>)]()\n            collectionsPackages.forEach { collectionIdentifier, packages in\n                packages.forEach { package in\n                    // Avoid copy-on-write: remove entry from dictionary before mutating\n                    var entry = packageCollections.removeValue(forKey: package.identity) ?? (package, .init())\n                    entry.collections.insert(collectionIdentifier)\n                    packageCollections[package.identity] = entry\n                }\n            }\n\n            // Sort by package name for consistent ordering in results\n            return Model.PackageSearchResult(items: packageCollections.sorted { $0.value.package.displayName < $1.value.package.displayName }.map { entry in\n                .init(package: entry.value.package, collections: Array(entry.value.collections))\n            })\n        }\n\n        // rdar://84218640\n        //let packageQuery = \"SELECT collection_id_blob_base64, repository_url FROM \\(Self.packagesFTSName) WHERE \\(Self.packagesFTSName) MATCH ?;\"\n        let packageQuery = \"SELECT collection_id_blob_base64, id FROM \\(Self.packagesFTSName) WHERE name LIKE ? OR summary LIKE ? OR keywords LIKE ? OR products LIKE ? OR targets LIKE ? OR repository_url LIKE ? OR id LIKE ?;\"\n\n        var matches = [(collection: Model.CollectionIdentifier, package: PackageIdentity)]()\n        var matchingCollections = Set<Model.CollectionIdentifier>()\n        try self.executeStatement(packageQuery) { statement in\n            try statement.bind((1...7).map { _ in .string(\"%\\(query)%\") })\n\n            while let row = try statement.step() {\n                if let collectionData = Data(base64Encoded: row.string(at: 0)),\n                    let collection = try? self.decoder.decode(Model.CollectionIdentifier.self, from: collectionData) {\n                    matches.append((collection: collection, package: PackageIdentity.plain(row.string(at: 1))))\n                    matchingCollections.insert(collection)\n                }\n            }\n        }\n\n        // Optimization: return early if no matches\n        guard !matches.isEmpty else {\n            return Model.PackageSearchResult(items: [])\n        }\n\n        // Optimization: fetch only those collections that contain matching packages\n        let collections = try await self.list(identifiers: Array(identifiers.map { Set($0).intersection(matchingCollections) } ?? matchingCollections))\n        let collectionDict = collections.reduce(into: [Model.CollectionIdentifier: Model.Collection]()) { result, collection in\n            result[collection.identifier] = collection\n        }\n\n        // For each package, find the containing collections\n        let packageCollections = matches.filter { collectionDict.keys.contains($0.collection) }\n            .reduce(into: [PackageIdentity: (package: Model.Package, collections: Set<Model.CollectionIdentifier>)]()) { result, match in\n                var entry = result.removeValue(forKey: match.package)\n                if entry == nil {\n                    guard let package = collectionDict[match.collection].flatMap({ collection in\n                        collection.packages.first(where: { $0.identity == match.package })\n                    }) else {\n                        return\n                    }\n                    entry = (package, .init())\n                }\n\n                if var entry = entry {\n                    entry.collections.insert(match.collection)\n                    result[match.package] = entry\n                }\n            }\n\n        // FTS results are not sorted by relevance at all (FTS5 supports ORDER BY rank but FTS4 requires additional SQL function)\n        // Sort by package name for consistent ordering in results\n        return Model.PackageSearchResult(items: packageCollections.sorted { $0.value.package.displayName < $1.value.package.displayName }.map { entry in\n            .init(package: entry.value.package, collections: Array(entry.value.collections))\n        })\n    }\n\n    func findPackage(\n        identifier: PackageModel.PackageIdentity,\n        collectionIdentifiers: [PackageCollectionsModel.CollectionIdentifier]? = nil\n    ) async throws -> (packages: [PackageCollectionsModel.Package], collections: [PackageCollectionsModel.CollectionIdentifier]) {\n\n        guard try self.shouldUseSearchIndices() else {\n            let collections = try await self.list(identifiers: collectionIdentifiers)\n            // sorting by collection processing date so the latest metadata is first\n            let collectionPackages = collections.sorted(by: { lhs, rhs in lhs.lastProcessedAt > rhs.lastProcessedAt }).compactMap { collection in\n                collection.packages\n                    .first(where: { $0.identity == identifier })\n                    .flatMap { (collection: collection.identifier, package: $0) }\n            }\n\n            // rdar://79069839 - Package identities are not unique to repository URLs so there can be more than one result.\n            // It's up to the caller to filter out the best-matched package(s). Results are sorted with the latest ones first.\n            let packages = collectionPackages.map { $0.package }\n\n            guard !packages.isEmpty else {\n                throw NotFoundError(\"\\(identifier)\")\n            }\n\n            return (packages: packages, collections: collectionPackages.map { $0.collection })\n        }\n\n        var matchingCollections = Set<Model.CollectionIdentifier>()\n\n        let packageQuery = \"SELECT collection_id_blob_base64, repository_url FROM \\(Self.packagesFTSName) WHERE id = ?;\"\n        try self.executeStatement(packageQuery) { statement in\n            try statement.bind([.string(identifier.description)])\n\n            while let row = try statement.step() {\n                if let collectionData = Data(base64Encoded: row.string(at: 0)),\n                    let collection = try? self.decoder.decode(Model.CollectionIdentifier.self, from: collectionData) {\n                    matchingCollections.insert(collection)\n                }\n            }\n        }\n\n        // Optimization: return early if no matches\n        guard !matchingCollections.isEmpty else {\n            throw NotFoundError(\"\\(identifier)\")\n        }\n\n        // Optimization: fetch only those collections that contain matching packages\n        let collections = try await self.list(identifiers: Array(collectionIdentifiers.map { Set($0).intersection(matchingCollections) } ?? matchingCollections))\n\n        let collectionDict = collections.reduce(into: [Model.CollectionIdentifier: Model.Collection]()) { result, collection in\n            result[collection.identifier] = collection\n        }\n\n        let filteredCollections = matchingCollections.filter { collectionDict.keys.contains($0) }\n            .compactMap { collectionDict[$0] }\n            // Sort collections by processing date so the latest metadata is first\n            .sorted(by: { lhs, rhs in lhs.lastProcessedAt > rhs.lastProcessedAt })\n\n        // rdar://79069839 - Package identities are not unique to repository URLs so there can be more than one result.\n        // It's up to the caller to filter out the best-matched package(s). Results are sorted with the latest ones first.\n        let packages = filteredCollections.flatMap { collection in\n            collection.packages.filter { $0.identity == identifier }\n        }\n\n        guard !packages.isEmpty else {\n            throw NotFoundError(\"\\(identifier)\")\n        }\n        return (packages: packages, collections: filteredCollections.map { $0.identifier })\n    }\n\n    func searchTargets(\n        identifiers: [PackageCollectionsModel.CollectionIdentifier]? = nil,\n        query: String,\n        type: PackageCollectionsModel.TargetSearchType\n    ) async throws -> PackageCollectionsModel.TargetSearchResult {\n        let query = query.lowercased()\n\n        // For each package, find the containing collections\n        var packageCollections = [PackageIdentity: (package: Model.Package, collections: Set<Model.CollectionIdentifier>)]()\n        // For each matching target, find the containing package version(s)\n        var targetPackageVersions = [Model.Target: [PackageIdentity: Set<Model.TargetListResult.PackageVersion>]]()\n\n        func buildResult() -> Model.TargetSearchResult {\n            // Sort by target name for consistent ordering in results\n            return Model.TargetSearchResult(items: targetPackageVersions.sorted { $0.key.name < $1.key.name }.map { target, packageVersions in\n                let targetPackages: [Model.TargetListItem.Package] = packageVersions.compactMap { identity, versions in\n                    guard let packageEntry = packageCollections[identity] else {\n                        return nil\n                    }\n                    return Model.TargetListItem.Package(\n                        identity: packageEntry.package.identity,\n                        location: packageEntry.package.location,\n                        summary: packageEntry.package.summary,\n                        versions: Array(versions).sorted(by: >),\n                        collections: Array(packageEntry.collections)\n                    )\n                }\n                return Model.TargetListItem(target: target, packages: targetPackages)\n            })\n        }\n\n        guard try self.shouldUseSearchIndices() else {\n            let collections = try await self.list(identifiers: identifiers)\n            let collectionsPackages = collections.reduce([Model.CollectionIdentifier: [(target: Model.Target, package: Model.Package)]]()) { partial, collection in\n                var map = partial\n                collection.packages.forEach { package in\n                    package.versions.forEach { version in\n                        version.manifests.values.forEach { manifest in\n                            manifest.targets.forEach { target in\n                                let match: Bool\n                                switch type {\n                                case .exactMatch:\n                                    match = target.name.lowercased() == query\n                                case .prefix:\n                                    match = target.name.lowercased().hasPrefix(query)\n                                }\n                                if match {\n                                    // Avoid copy-on-write: remove entry from dictionary before mutating\n                                    var entry = map.removeValue(forKey: collection.identifier) ?? .init()\n                                    entry.append((target, package))\n                                    map[collection.identifier] = entry\n                                }\n                            }\n                        }\n                    }\n                }\n                return map\n            }\n\n            collectionsPackages.forEach { collectionIdentifier, packagesAndTargets in\n                packagesAndTargets.forEach { item in\n                    // Avoid copy-on-write: remove entry from dictionary before mutating\n                    var packageCollectionsEntry = packageCollections.removeValue(forKey: item.package.identity) ?? (item.package, .init())\n                    packageCollectionsEntry.collections.insert(collectionIdentifier)\n                    packageCollections[item.package.identity] = packageCollectionsEntry\n\n                    packageCollectionsEntry.package.versions.forEach { version in\n                        version.manifests.values.forEach { manifest in\n                            let targets = manifest.targets.filter { $0.name.lowercased() == item.target.name.lowercased() }\n                            targets.forEach { target in\n                                var targetEntry = targetPackageVersions.removeValue(forKey: item.target) ?? [:]\n                                var targetPackageEntry = targetEntry.removeValue(forKey: item.package.identity) ?? .init()\n                                targetPackageEntry.insert(.init(version: version.version, toolsVersion: manifest.toolsVersion, packageName: manifest.packageName))\n                                targetEntry[item.package.identity] = targetPackageEntry\n                                targetPackageVersions[target] = targetEntry\n                            }\n                        }\n                    }\n                }\n            }\n            return buildResult()\n        }\n        var matches = [(collection: Model.CollectionIdentifier, package: PackageIdentity, packageLocation: String, targetName: String)]()\n        var matchingCollections = Set<Model.CollectionIdentifier>()\n\n        // Trie is more performant for target search; use it if available\n        if self.populateTargetTrieLock.withLock({ self.targetTrieReady }) ?? false {\n            do {\n                switch type {\n                case .exactMatch:\n                    try self.targetTrie.find(word: query).forEach {\n                        matches.append((collection: $0.collection, package: $0.package, packageLocation: $0.packageLocation, targetName: query))\n                        matchingCollections.insert($0.collection)\n                    }\n                case .prefix:\n                    try self.targetTrie.findWithPrefix(query).forEach { targetName, collectionPackages in\n                        collectionPackages.forEach {\n                            matches.append((collection: $0.collection, package: $0.package, packageLocation: $0.packageLocation, targetName: targetName))\n                            matchingCollections.insert($0.collection)\n                        }\n                    }\n                }\n            } catch is NotFoundError {\n                // Do nothing if no matches found\n            }\n        } else {\n            let targetV1Query = \"SELECT collection_id_blob_base64, package_id, package_repository_url, name FROM \\(Self.targetsFTSNameV1) WHERE name LIKE ?;\"\n            try self.executeStatement(targetV1Query) { statement in\n                switch type {\n                case .exactMatch:\n                    try statement.bind([.string(\"\\(query)\")])\n                case .prefix:\n                    try statement.bind([.string(\"\\(query)%\")])\n                }\n\n                while let row = try statement.step() {\n                    if let collectionData = Data(base64Encoded: row.string(at: 0)),\n                        let collection = try? self.decoder.decode(Model.CollectionIdentifier.self, from: collectionData) {\n                        matches.append((\n                            collection: collection,\n                            package: PackageIdentity.plain(row.string(at: 1)),\n                            packageLocation: row.string(at: 2),\n                            targetName: row.string(at: 3)\n                        ))\n                        matchingCollections.insert(collection)\n                    }\n                }\n            }\n            let targetV0Query = \"SELECT collection_id_blob_base64, package_repository_url, name FROM \\(Self.targetsFTSNameV0) WHERE name LIKE ?;\"\n            try self.executeStatement(targetV0Query) { statement in\n                switch type {\n                case .exactMatch:\n                    try statement.bind([.string(\"\\(query)\")])\n                case .prefix:\n                    try statement.bind([.string(\"\\(query)%\")])\n                }\n\n                while let row = try statement.step() {\n                    if let collectionData = Data(base64Encoded: row.string(at: 0)),\n                        let collection = try? self.decoder.decode(Model.CollectionIdentifier.self, from: collectionData) {\n                        matches.append((\n                            collection: collection,\n                            package: PackageIdentity(urlString: row.string(at: 1)),\n                            packageLocation: row.string(at: 1),\n                            targetName: row.string(at: 2)\n                        ))\n                        matchingCollections.insert(collection)\n                    }\n                }\n            }\n        }\n\n        // Optimization: return early if no matches\n        guard !matches.isEmpty else {\n            return Model.TargetSearchResult(items: [])\n        }\n\n        // Optimization: fetch only those collections that contain matching packages\n        let collections = try await self.list(identifiers: Array(identifiers.map { Set($0).intersection(matchingCollections) } ?? matchingCollections))\n\n        let collectionDict = collections.reduce(into: [Model.CollectionIdentifier: Model.Collection]()) { result, collection in\n            result[collection.identifier] = collection\n        }\n\n        matches.filter { collectionDict.keys.contains($0.collection) }.forEach { match in\n            var packageEntry = packageCollections.removeValue(forKey: match.package)\n            if packageEntry == nil {\n                guard let package = collectionDict[match.collection].flatMap({ collection in\n                    collection.packages.first(where: { $0.identity == match.package || $0.location == match.packageLocation })\n                }) else {\n                    return\n                }\n                packageEntry = (package, .init())\n            }\n\n            if var packageEntry = packageEntry {\n                packageEntry.collections.insert(match.collection)\n                packageCollections[match.package] = packageEntry\n\n                packageEntry.package.versions.forEach { version in\n                    version.manifests.values.forEach { manifest in\n                        let targets = manifest.targets.filter { $0.name.lowercased() == match.targetName.lowercased() }\n                        targets.forEach { target in\n                            var targetEntry = targetPackageVersions.removeValue(forKey: target) ?? [:]\n                            var targetPackageEntry = targetEntry.removeValue(forKey: packageEntry.package.identity) ?? .init()\n                            targetPackageEntry.insert(.init(version: version.version, toolsVersion: manifest.toolsVersion, packageName: manifest.packageName))\n                            targetEntry[packageEntry.package.identity] = targetPackageEntry\n                            targetPackageVersions[target] = targetEntry\n                        }\n                    }\n                }\n            }\n        }\n        return buildResult()\n    }\n\n    private func insertToSearchIndices(collection: Model.Collection) throws {\n        guard try self.shouldUseSearchIndices() else { return }\n\n        try self.ftsLock.withLock {\n            // First delete existing data\n            try self.removeFromSearchIndices(identifier: collection.identifier)\n            // Update search indices\n            try self.withDB { db in\n                let packagesStatement = try db.prepare(query: \"INSERT INTO \\(Self.packagesFTSName) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);\")\n                let targetsStatement = try db.prepare(query: \"INSERT INTO \\(Self.targetsFTSNameV1) VALUES (?, ?, ?, ?);\")\n\n                try db.exec(query: \"BEGIN TRANSACTION;\")\n                do {\n                    // Then insert new data\n                    try collection.packages.forEach { package in\n                        var targets = Set<String>()\n\n                        try package.versions.forEach { version in\n                            try version.manifests.values.forEach { manifest in\n                                // Packages FTS\n                                let packagesBindings: [SQLite.SQLiteValue] = [\n                                    .string(try self.encoder.encode(collection.identifier).base64EncodedString()),\n                                    .string(package.identity.description),\n                                    .string(version.version.description),\n                                    .string(manifest.packageName),\n                                    .string(package.location),\n                                    package.summary.map { .string($0) } ?? .null,\n                                    package.keywords.map { .string($0.joined(separator: \",\")) } ?? .null,\n                                    .string(manifest.products.map { $0.name }.joined(separator: \",\")),\n                                    .string(manifest.targets.map { $0.name }.joined(separator: \",\")),\n                                ]\n                                try packagesStatement.bind(packagesBindings)\n                                try packagesStatement.step()\n\n                                try packagesStatement.clearBindings()\n                                try packagesStatement.reset()\n\n                                manifest.targets.forEach { targets.insert($0.name) }\n                            }\n                        }\n\n                        let collectionPackage = CollectionPackage(\n                            collection: collection.identifier,\n                            package: package.identity,\n                            packageLocation: package.location\n                        )\n                        try targets.forEach { target in\n                            // Targets in-memory trie\n                            self.targetTrie.insert(word: target.lowercased(), foundIn: collectionPackage)\n\n                            // Targets FTS\n                            let targetsBindings: [SQLite.SQLiteValue] = [\n                                .string(try self.encoder.encode(collection.identifier).base64EncodedString()),\n                                .string(package.identity.description),\n                                .string(package.location),\n                                .string(target),\n                            ]\n                            try targetsStatement.bind(targetsBindings)\n                            try targetsStatement.step()\n\n                            try targetsStatement.clearBindings()\n                            try targetsStatement.reset()\n                        }\n                    }\n\n                    try db.exec(query: \"COMMIT;\")\n                } catch {\n                    try db.exec(query: \"ROLLBACK;\")\n                    throw error\n                }\n\n                try packagesStatement.finalize()\n                try targetsStatement.finalize()\n            }\n        }\n    }\n\n    private func removeFromSearchIndices(identifier: Model.CollectionIdentifier) throws {\n        guard try self.shouldUseSearchIndices() else { return }\n\n        let identifierBase64 = try self.encoder.encode(identifier).base64EncodedString()\n\n        let packagesQuery = \"DELETE FROM \\(Self.packagesFTSName) WHERE collection_id_blob_base64 = ?;\"\n        try self.executeStatement(packagesQuery) { statement -> Void in\n            let bindings: [SQLite.SQLiteValue] = [.string(identifierBase64)]\n            try statement.bind(bindings)\n            try statement.step()\n        }\n\n        let targetsV0Query = \"DELETE FROM \\(Self.targetsFTSNameV0) WHERE collection_id_blob_base64 = ?;\"\n        try self.executeStatement(targetsV0Query) { statement -> Void in\n            let bindings: [SQLite.SQLiteValue] = [.string(identifierBase64)]\n            try statement.bind(bindings)\n            try statement.step()\n        }\n\n        let targetsV1Query = \"DELETE FROM \\(Self.targetsFTSNameV1) WHERE collection_id_blob_base64 = ?;\"\n        try self.executeStatement(targetsV1Query) { statement -> Void in\n            let bindings: [SQLite.SQLiteValue] = [.string(identifierBase64)]\n            try statement.bind(bindings)\n            try statement.step()\n        }\n\n        self.targetTrie.remove { $0.collection == identifier }\n    }\n\n    private func shouldUseSearchIndices() throws -> Bool {\n        // Make sure createSchemaIfNecessary is called and useSearchIndices is set before reading it\n        try self.withDB { _ in\n            self.useSearchIndices.get()\n        }\n    }\n\n    internal func populateTargetTrie() async throws {\n        try await withCheckedThrowingContinuation { continuation in\n            self.populateTargetTrie(callback: {\n                continuation.resume(with: $0)\n            })\n        }\n    }\n\n    internal func populateTargetTrie(callback: @escaping (Result<Void, Error>) -> Void = { _ in }) {\n        // Check to see if there is any data before submitting task to queue because otherwise it's no-op anyway\n        do {\n            let numberOfCollections: Int = try self.executeStatement(\"SELECT COUNT(*) FROM \\(Self.packageCollectionsTableName);\") { statement in\n                let row = try statement.step()\n                guard let count = row?.int(at: 0) else {\n                    throw StringError(\"Failed to get count of \\(Self.packageCollectionsTableName) table\")\n                }\n                return count\n            }\n            // No collections means no data, so no need to populate target trie\n            guard numberOfCollections > 0 else {\n                self.populateTargetTrieLock.withLock {\n                    self.targetTrieReady = true\n                }\n                return callback(.success(()))\n            }\n        } catch {\n            self.observabilityScope.emit(\n                warning: \"Failed to determine if database is empty or not\",\n                underlyingError: error\n            )\n            // Try again in background\n        }\n\n        DispatchQueue.sharedConcurrent.async(group: nil, qos: .background, flags: .assignCurrentContext) {\n            do {\n                try self.populateTargetTrieLock.withLock { // Prevent race to populate targetTrie\n                    // Exit early if we've already done the computation before\n                    guard self.targetTrieReady == nil else {\n                        return\n                    }\n\n                    // since running on low priority thread make sure the database has not already gone away\n                    switch (try self.withStateLock { self.state }) {\n                    case .disconnected, .disconnecting:\n                        self.targetTrieReady = false\n                        return\n                    default:\n                        break\n                    }\n\n                    // Use collectionsProcessed to make sure we don't end up with duplicates\n                    // in the trie. If a collection is in targetsFTSNameV1, then the data\n                    // in targetsFTSNameV0 (if any) must be stale.\n                    var collectionsProcessed = Set<Model.CollectionIdentifier>()\n\n                    // Use FTS to build the trie\n                    let queryV1 = \"SELECT collection_id_blob_base64, package_id, package_repository_url, name FROM \\(Self.targetsFTSNameV1);\"\n                    try self.executeStatement(queryV1) { statement in\n                        while let row = try statement.step() {\n                            #if os(Linux)\n                            // lock not required since executeStatement locks\n                            guard case .connected = self.state else {\n                                return\n                            }\n                            #else\n                            guard case .connected = (try self.withStateLock { self.state }) else {\n                                return\n                            }\n                            #endif\n\n                            let targetName = row.string(at: 3)\n\n                            if let collectionData = Data(base64Encoded: row.string(at: 0)),\n                               let collection = try? self.decoder.decode(Model.CollectionIdentifier.self, from: collectionData) {\n                                let collectionPackage = CollectionPackage(\n                                    collection: collection,\n                                    package: PackageIdentity.plain(row.string(at: 1)),\n                                    packageLocation: row.string(at: 2)\n                                )\n                                self.targetTrie.insert(word: targetName.lowercased(), foundIn: collectionPackage)\n                                collectionsProcessed.insert(collection)\n                            }\n                        }\n                    }\n\n                    let queryV0 = \"SELECT collection_id_blob_base64, package_repository_url, name FROM \\(Self.targetsFTSNameV0);\"\n                    try self.executeStatement(queryV0) { statement in\n                        while let row = try statement.step() {\n                            #if os(Linux)\n                            // lock not required since executeStatement locks\n                            guard case .connected = self.state else {\n                                return\n                            }\n                            #else\n                            guard case .connected = (try self.withStateLock { self.state }) else {\n                                return\n                            }\n                            #endif\n\n                            let targetName = row.string(at: 2)\n\n                            if let collectionData = Data(base64Encoded: row.string(at: 0)),\n                               let collection = try? self.decoder.decode(Model.CollectionIdentifier.self, from: collectionData),\n                               !collectionsProcessed.contains(collection) {\n                                let collectionPackage = CollectionPackage(\n                                    collection: collection,\n                                    package: PackageIdentity(urlString: row.string(at: 1)),\n                                    packageLocation: row.string(at: 1)\n                                )\n                                self.targetTrie.insert(word: targetName.lowercased(), foundIn: collectionPackage)\n                            }\n                        }\n                    }\n                    self.targetTrieReady = true\n                }\n                callback(.success(()))\n            } catch {\n                callback(.failure(error))\n            }\n        }\n    }\n\n    // for testing\n    internal func resetCache() {\n        self.cache.clear()\n    }\n\n    // MARK: -  Private\n\n    private func executeStatement<T>(_ query: String, _ body: (SQLite.PreparedStatement) throws -> T) throws -> T {\n        try self.withDB { db in\n            let result: Result<T, Error>\n            let statement = try db.prepare(query: query)\n            do {\n                result = .success(try body(statement))\n            } catch {\n                result = .failure(error)\n            }\n            try statement.finalize()\n            switch result {\n            case .failure(let error):\n                throw error\n            case .success(let value):\n                return value\n            }\n        }\n    }\n\n    private func withDB<T>(_ body: (SQLite) throws -> T) throws -> T {\n        let createDB = { () throws -> SQLite in\n            let db = try SQLite(location: self.location, configuration: self.configuration.underlying)\n            try self.createSchemaIfNecessary(db: db)\n            return db\n        }\n\n        let db = try self.withStateLock { () -> SQLite in\n            let db: SQLite\n            switch (self.location, self.state) {\n            case (_, .disconnecting), (_, .disconnected):\n                throw StringError(\"DB is disconnecting or disconnected\")\n            case (.path(let path), .connected(let database)):\n                if self.fileSystem.exists(path) {\n                    db = database\n                } else {\n                    try database.close()\n                    try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)\n                    db = try createDB()\n                }\n            case (.path(let path), _):\n                if !self.fileSystem.exists(path) {\n                    try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)\n                }\n                db = try createDB()\n            case (_, .connected(let database)):\n                db = database\n            case (_, _):\n                db = try createDB()\n            }\n            self.state = .connected(db)\n            return db\n        }\n\n        // FIXME: workaround linux sqlite concurrency issues causing CI failures\n        #if os(Linux)\n        return try self.withStateLock {\n            try body(db)\n        }\n        #else\n        return try body(db)\n        #endif\n    }\n\n    private func createSchemaIfNecessary(db: SQLite) throws {\n        let table = \"\"\"\n            CREATE TABLE IF NOT EXISTS \\(Self.packageCollectionsTableName) (\n                key STRING PRIMARY KEY NOT NULL,\n                value BLOB NOT NULL\n            );\n        \"\"\"\n        try db.exec(query: table)\n\n        #if os(Android)\n        // FTS queries for strings containing hyphens isn't working in SQLite on\n        // Android, so disable for now.\n        self.useSearchIndices.put(false)\n        #else\n        do {\n            let ftsPackages = \"\"\"\n                CREATE VIRTUAL TABLE IF NOT EXISTS \\(Self.packagesFTSName) USING fts4(\n                    collection_id_blob_base64, id, version, name, repository_url, summary, keywords, products, targets,\n                    notindexed=collection_id_blob_base64,\n                    tokenize=unicode61\n                );\n            \"\"\"\n            try db.exec(query: ftsPackages)\n\n            // We don't insert to this anymore but keeping it for queries to work\n            let ftsTargetsV0 = \"\"\"\n                CREATE VIRTUAL TABLE IF NOT EXISTS \\(Self.targetsFTSNameV0) USING fts4(\n                    collection_id_blob_base64, package_repository_url, name,\n                    notindexed=collection_id_blob_base64,\n                    tokenize=unicode61\n                );\n            \"\"\"\n            try db.exec(query: ftsTargetsV0)\n\n            let ftsTargetsV1 = \"\"\"\n                CREATE VIRTUAL TABLE IF NOT EXISTS \\(Self.targetsFTSNameV1) USING fts4(\n                    collection_id_blob_base64, package_id, package_repository_url, name,\n                    notindexed=collection_id_blob_base64,\n                    tokenize=unicode61\n                );\n            \"\"\"\n            try db.exec(query: ftsTargetsV1)\n\n            self.useSearchIndices.put(true)\n        } catch {\n            // We can use FTS3 tables but queries yield different results when run on different\n            // platforms. This could be because of SQLite version perhaps? But since we can't get\n            // consistent results we will not fallback to FTS3 and just give up if FTS4 is not available.\n            self.useSearchIndices.put(false)\n        }\n        #endif\n\n        try db.exec(query: \"PRAGMA journal_mode=WAL;\")\n    }\n\n    private func withStateLock<T>(_ body: () throws -> T) throws -> T {\n        try self.stateLock.withLock(body)\n        /* switch self.location {\n         case .path(let path):\n             if !self.fileSystem.exists(path.parentDirectory) {\n                 try self.fileSystem.createDirectory(path.parentDirectory)\n             }\n             return try self.fileSystem.withLock(on: path, type: .exclusive, body)\n         case .memory, .temporary:\n             return try self.stateLock.withLock(body)\n         } */\n    }\n\n    private enum State {\n        case idle\n        case connected(SQLite)\n        case disconnecting(SQLite)\n        case disconnected\n        case error\n    }\n\n    // For `Trie`\n    private struct CollectionPackage: Hashable, CustomStringConvertible {\n        let collection: Model.CollectionIdentifier\n        let package: PackageIdentity\n        let packageLocation: String\n\n        var description: String {\n            \"\\(collection): \\(package)\"\n        }\n    }\n\n    // For shutdown\n    private struct ExponentialBackoff {\n        let intervalInMilliseconds: Int\n        let randomizationFactor: Int\n        let maximumAttempts: Int\n\n        var attempts: Int = 0\n        var multiplier: Int = 1\n\n        var canRetry: Bool {\n            self.attempts < self.maximumAttempts\n        }\n\n        init(intervalInMilliseconds: Int = 100, randomizationFactor: Int = 100, maximumAttempts: Int = 3) {\n            self.intervalInMilliseconds = intervalInMilliseconds\n            self.randomizationFactor = randomizationFactor\n            self.maximumAttempts = maximumAttempts\n        }\n\n        mutating func nextDelay() throws -> DispatchTimeInterval {\n            guard self.canRetry else {\n                throw StringError(\"Maximum attempts reached\")\n            }\n            let delay = self.multiplier * intervalInMilliseconds\n            let jitter = Int.random(in: 0 ... self.randomizationFactor)\n            self.attempts += 1\n            self.multiplier *= 2\n            return .milliseconds(delay + jitter)\n        }\n    }\n\n    struct Configuration {\n        var batchSize: Int\n        var initializeTargetTrie: Bool\n\n        fileprivate var underlying: SQLite.Configuration\n\n        init(initializeTargetTrie: Bool = true) {\n            self.batchSize = 100\n            self.initializeTargetTrie = initializeTargetTrie\n\n            self.underlying = .init()\n            self.maxSizeInMegabytes = 100\n            // see https://www.sqlite.org/c3ref/busy_timeout.html\n            self.busyTimeoutMilliseconds = 1000\n        }\n\n        var maxSizeInMegabytes: Int? {\n            get {\n                self.underlying.maxSizeInMegabytes\n            }\n            set {\n                self.underlying.maxSizeInMegabytes = newValue\n            }\n        }\n\n        var busyTimeoutMilliseconds: Int32 {\n            get {\n                self.underlying.busyTimeoutMilliseconds\n            }\n            set {\n                self.underlying.busyTimeoutMilliseconds = newValue\n            }\n        }\n    }\n}\n\n// MARK: - Utility\n\nprivate extension Model.Collection.Identifier {\n    func databaseKey() -> String {\n        switch self {\n        case .json(let url):\n            return url.absoluteString\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Storage/Trie.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.NSLock\nimport PackageModel\n\nstruct Trie<Document: Hashable> {\n    private typealias Node = TrieNode<Character, Document>\n\n    private let root: Node\n    private let lock = NSLock()\n\n    init() {\n        self.root = Node()\n    }\n\n    /// Inserts a word and its document to the trie.\n    func insert(word: String, foundIn document: Document) {\n        guard !word.isEmpty else { return }\n\n        self.lock.withLock {\n            var currentNode = self.root\n            // Check if word already exists otherwise creates the node path\n            for character in word.lowercased() {\n                if let child = currentNode.children[character] {\n                    currentNode = child\n                } else {\n                    currentNode = currentNode.add(value: character)\n                }\n            }\n\n            currentNode.add(document: document)\n        }\n    }\n\n    /// Removes word occurrences found in the given document.\n    func remove(document: Document) {\n        func removeInSubTrie(root: Node, document: Document) {\n            if root.isTerminating {\n                root.remove(document: document)\n            }\n\n            // Clean up sub-tries\n            root.children.values.forEach {\n                removeInSubTrie(root: $0, document: document)\n            }\n\n            root.children.forEach { value, node in\n                // If a child node doesn't have children (i.e., there are no words under it),\n                // and itself is not a word, delete it since its path has become a deadend.\n                if node.isLeaf, !node.isTerminating {\n                    root.remove(value: value)\n                }\n            }\n        }\n\n        self.lock.withLock {\n            removeInSubTrie(root: self.root, document: document)\n        }\n    }\n\n    /// Removes word occurrences found in matching document(s).\n    func remove(where predicate: @escaping (Document) -> Bool) {\n        func removeInSubTrie(root: Node, where predicate: @escaping (Document) -> Bool) {\n            if root.isTerminating {\n                root.remove(where: predicate)\n            }\n\n            // Clean up sub-tries\n            root.children.values.forEach {\n                removeInSubTrie(root: $0, where: predicate)\n            }\n\n            root.children.forEach { value, node in\n                // If a child node doesn't have children (i.e., there are no words under it),\n                // and itself is not a word, delete it since its path has become a deadend.\n                if node.isLeaf, !node.isTerminating {\n                    root.remove(value: value)\n                }\n            }\n        }\n\n        self.lock.withLock {\n            removeInSubTrie(root: self.root, where: predicate)\n        }\n    }\n\n    /// Checks if the trie contains the exact word or words with matching prefix.\n    func contains(word: String, prefixMatch: Bool = false) -> Bool {\n        guard let node = self.findLastNodeOf(word: word) else {\n            return false\n        }\n        return prefixMatch || node.isTerminating\n    }\n\n    /// Finds the word in this trie and returns its documents.\n    func find(word: String) throws -> Set<Document> {\n        guard let node = self.findLastNodeOf(word: word), node.isTerminating else {\n            throw NotFoundError(word)\n        }\n        return node.documents\n    }\n\n    /// Finds words with matching prefix in this trie and returns their documents.\n    func findWithPrefix(_ prefix: String) throws -> [String: Set<Document>] {\n        guard let node = self.findLastNodeOf(word: prefix) else {\n            throw NotFoundError(prefix)\n        }\n\n        func wordsInSubTrie(root: Node, prefix: String) -> [String: Set<Document>] {\n            precondition(root.value != nil, \"Sub-trie root's value should not be nil\")\n\n            var subTrieWords = [String: Set<Document>]()\n\n            // Construct the new prefix by adding the sub-trie root's character\n            var previousCharacters = prefix\n            previousCharacters.append(root.value!.lowercased()) // !-safe; see precondition\n\n            // The root actually forms a word\n            if root.isTerminating {\n                subTrieWords[previousCharacters] = root.documents\n            }\n\n            // Collect all words under this sub-trie\n            root.children.values.forEach {\n                let childWords = wordsInSubTrie(root: $0, prefix: previousCharacters)\n                subTrieWords.merge(childWords, uniquingKeysWith: { _, child in child })\n            }\n\n            return subTrieWords\n        }\n\n        var words = [String: Set<Document>]()\n\n        let prefix = prefix.lowercased()\n        // The prefix is actually a word\n        if node.isTerminating {\n            words[prefix] = node.documents\n        }\n\n        node.children.values.forEach {\n            let childWords = wordsInSubTrie(root: $0, prefix: prefix)\n            words.merge(childWords, uniquingKeysWith: { _, child in child })\n        }\n\n        return words\n    }\n\n    /// Finds the last node in the path of the given word if it exists in this trie.\n    private func findLastNodeOf(word: String) -> Node? {\n        guard !word.isEmpty else { return nil }\n\n        return self.lock.withLock {\n            var currentNode = self.root\n            // Traverse down the trie as far as we can\n            for character in word.lowercased() {\n                guard let child = currentNode.children[character] else {\n                    return nil\n                }\n                currentNode = child\n            }\n            return currentNode\n        }\n    }\n}\n\nprivate final class TrieNode<T: Hashable, Document: Hashable> {\n    /// The value (i.e., character) that this node stores. `nil` if root.\n    let value: T?\n\n    /// The parent of this node. `nil` if root.\n    private weak var parent: TrieNode<T, Document>?\n\n    /// The children of this node identified by their corresponding value.\n    private var _children = [T: TrieNode<T, Document>]()\n    private let childrenLock = NSLock()\n\n    /// If the path to this node forms a valid word, these are the documents where the word can be found.\n    private var _documents = Set<Document>()\n    private let documentsLock = NSLock()\n\n    var isLeaf: Bool {\n        self.childrenLock.withLock {\n            self._children.isEmpty\n        }\n    }\n\n    /// `true` indicates the path to this node forms a valid word.\n    var isTerminating: Bool {\n        self.documentsLock.withLock {\n            !self._documents.isEmpty\n        }\n    }\n\n    var children: [T: TrieNode<T, Document>] {\n        self.childrenLock.withLock {\n            self._children\n        }\n    }\n\n    var documents: Set<Document> {\n        self.documentsLock.withLock {\n            self._documents\n        }\n    }\n\n    init(value: T? = nil, parent: TrieNode<T, Document>? = nil) {\n        self.value = value\n        self.parent = parent\n    }\n\n    /// Adds a subpath under this node.\n    func add(value: T) -> TrieNode<T, Document> {\n        self.childrenLock.withLock {\n            if let existing = self._children[value] {\n                return existing\n            }\n\n            let child = TrieNode<T, Document>(value: value, parent: self)\n            self._children[value] = child\n            return child\n        }\n    }\n\n    /// Removes a subpath from this node.\n    func remove(value: T) {\n        _ = self.childrenLock.withLock {\n            self._children.removeValue(forKey: value)\n        }\n    }\n\n    /// Adds a document in which the word formed by path leading to this node can be found.\n    func add(document: Document) {\n        _ = self.documentsLock.withLock {\n            self._documents.insert(document)\n        }\n    }\n\n    /// Removes a referenced document.\n    func remove(document: Document) {\n        _ = self.documentsLock.withLock {\n            self._documents.remove(document)\n        }\n    }\n\n    /// Removes documents that satisfy the given predicate.\n    func remove(where predicate: @escaping (Document) -> Bool) {\n        self.documentsLock.withLock {\n            for document in self._documents {\n                if predicate(document) {\n                    self._documents.remove(document)\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollections/Utility.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageModel\nimport SourceControl\n\nstruct MultipleErrors: Error, CustomStringConvertible {\n    let errors: [Error]\n    \n    init(_ errors: [Error]) {\n        self.errors = errors\n    }\n\n    var description: String {\n        \"\\(self.errors)\"\n    }\n}\n\nstruct NotFoundError: Error {\n    let item: String\n\n    init(_ item: String) {\n        self.item = item\n    }\n}\n\ninternal extension Result {\n    var failure: Failure? {\n        switch self {\n        case .failure(let failure):\n            return failure\n        case .success:\n            return nil\n        }\n    }\n\n    var success: Success? {\n        switch self {\n        case .failure:\n            return nil\n        case .success(let value):\n            return value\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsCommand/PackageCollectionsCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport Commands\nimport CoreCommands\nimport Foundation\nimport PackageCollections\nimport PackageModel\n\nimport struct TSCUtility.Version\n\nprivate enum CollectionsError: Swift.Error {\n    case invalidArgument(String)\n    case invalidVersionString(String)\n    case unsigned\n    case cannotVerifySignature\n    case invalidSignature\n    case missingSignature\n}\n\n// FIXME: add links to docs in error messages\nextension CollectionsError: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .invalidArgument(let argumentName):\n            return \"Invalid argument '\\(argumentName)'\"\n        case .invalidVersionString(let versionString):\n            return \"Invalid version string '\\(versionString)'\"\n        case .unsigned:\n            return \"The collection is not signed. If you would still like to add it please rerun 'add' with '--trust-unsigned'.\"\n        case .cannotVerifySignature:\n            return \"The collection's signature cannot be verified due to missing configuration. Please refer to documentations on how to set up trusted root certificates or rerun command with '--skip-signature-check'.\"\n        case .invalidSignature:\n            return \"The collection's signature is invalid. If you would like to continue please rerun command with '--skip-signature-check'.\"\n        case .missingSignature:\n            return \"The collection is missing required signature, which means it might have been compromised. Please contact the collection's authors and alert them of the issue.\"\n        }\n    }\n}\n\nstruct JSONOptions: ParsableArguments {\n    @Flag(name: .long, help: \"Output as JSON\")\n    var json: Bool = false\n}\n\npublic struct PackageCollectionsCommand: AsyncParsableCommand {\n    public static var configuration = CommandConfiguration(\n        commandName: \"package-collection\",\n        _superCommandName: \"swift\",\n        abstract: \"Interact with package collections.\",\n        discussion: \"SEE ALSO: swift build, swift package, swift run, swift test\",\n        version: SwiftVersion.current.completeDisplayString,\n        subcommands: [\n            Add.self,\n            Describe.self,\n            List.self,\n            Refresh.self,\n            Remove.self,\n            Search.self,\n        ],\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    public init() {}\n\n    // MARK: Collections\n\n    struct List: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(abstract: \"List configured collections.\")\n\n        @OptionGroup\n        var jsonOptions: JSONOptions\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let collections = try await withState(swiftCommandState) { collections in\n                try await collections.listCollections(identifiers: nil)\n            }\n\n            if self.jsonOptions.json {\n                try JSONEncoder.makeWithDefaults().print(collections)\n            } else {\n                collections.forEach {\n                    print(\"\\($0.name) - \\($0.source.url)\")\n                }\n            }\n        }\n    }\n\n    struct Refresh: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(abstract: \"Refresh configured collections.\")\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let collections = try await withState(swiftCommandState) { collections in\n                try await collections.refreshCollections()\n            }\n            print(\"Refreshed \\(collections.count) configured package collection\\(collections.count == 1 ? \"\" : \"s\").\")\n        }\n    }\n\n    struct Add: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(abstract: \"Add a new collection.\")\n\n        @Argument(help: \"URL of the collection to add.\")\n        var collectionURL: String\n\n        @Option(name: .long, help: \"Sort order for the added collection.\")\n        var order: Int?\n\n        @Flag(name: .long, help: \"Trust the collection even if it is unsigned.\")\n        var trustUnsigned: Bool = false\n\n        @Flag(name: .long, help: \"Skip signature check if the collection is signed.\")\n        var skipSignatureCheck: Bool = false\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let collectionURL = try url(self.collectionURL)\n\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: collectionURL, skipSignatureCheck: self.skipSignatureCheck)\n            let collection: PackageCollectionsModel.Collection = try await withState(swiftCommandState) { collections in\n                do {\n                    let userTrusted = self.trustUnsigned\n                    return try await collections.addCollection(source, order: order) { _, callback in\n                        callback(userTrusted)\n                    }\n                } catch PackageCollectionError.trustConfirmationRequired, PackageCollectionError.untrusted {\n                    throw CollectionsError.unsigned\n                } catch PackageCollectionError.cannotVerifySignature {\n                    throw CollectionsError.cannotVerifySignature\n                } catch PackageCollectionError.invalidSignature {\n                    throw CollectionsError.invalidSignature\n                } catch PackageCollectionError.missingSignature {\n                    throw CollectionsError.missingSignature\n                }\n            }\n\n            print(\"Added \\\"\\(collection.name)\\\" to your package collections.\")\n        }\n    }\n\n    struct Remove: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(abstract: \"Remove a configured collection.\")\n\n        @Argument(help: \"URL of the collection to remove.\")\n        var collectionURL: String\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let collectionURL = try url(self.collectionURL)\n\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: collectionURL)\n            try await withState(swiftCommandState) { collections in\n                let collection = try await collections.getCollection(source)\n                _ = try await collections.removeCollection(source)\n                print(\"Removed \\\"\\(collection.name)\\\" from your package collections.\")\n            }\n        }\n    }\n\n    // MARK: Search\n\n    enum SearchMethod: String, EnumerableFlag {\n        case keywords\n        case module\n    }\n\n    struct Search: AsyncSwiftCommand {\n        static var configuration = CommandConfiguration(abstract: \"Search for packages by keywords or module names.\")\n\n        @OptionGroup\n        var jsonOptions: JSONOptions\n\n        @Flag(help: \"Pick the method for searching.\")\n        var searchMethod: SearchMethod\n\n        @Argument(help: \"The search query.\")\n        var searchQuery: String\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            try await withState(swiftCommandState) { collections in\n                switch searchMethod {\n                case .keywords:\n                    let results = try await collections.findPackages(searchQuery, collections: nil)\n\n                    if jsonOptions.json {\n                        try JSONEncoder.makeWithDefaults().print(results.items)\n                    } else {\n                        results.items.forEach {\n                            print(\"\\($0.package.identity): \\($0.package.summary ?? \"\")\")\n                        }\n                    }\n\n                case .module:\n                    let results = try await collections.findTargets(searchQuery, searchType: .exactMatch, collections: nil)\n\n                    let packages = Set(results.items.flatMap { $0.packages })\n                    if jsonOptions.json {\n                        try JSONEncoder.makeWithDefaults().print(packages)\n                    } else {\n                        packages.forEach {\n                            print(\"\\($0.identity): \\($0.summary ?? \"\")\")\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // MARK: Packages\n\n    struct Describe: AsyncSwiftCommand {\n        static var configuration = CommandConfiguration(abstract: \"Get metadata for a collection or a package included in an imported collection.\")\n\n        @OptionGroup\n        var jsonOptions: JSONOptions\n\n        @Argument(help: \"URL of the package or collection to get information for.\")\n        var packageURL: String\n\n        @Option(name: .long, help: \"Version of the package to get information for.\")\n        var version: String?\n\n        @Flag(name: .long, help: \"Skip signature check if the collection is signed.\")\n        var skipSignatureCheck: Bool = false\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        private func printVersion(_ version: PackageCollectionsModel.Package.Version?) -> String? {\n            guard let version else {\n                return nil\n            }\n            guard let defaultManifest = version.defaultManifest else {\n                return nil\n            }\n\n            let manifests = version.manifests.values.filter { $0.toolsVersion != version.defaultToolsVersion }.map { printManifest($0) }.joined(separator: \"\\n\")\n            let compatibility = optionalRow(\n                \"Verified Compatibility (Platform, Swift Version)\",\n                version.verifiedCompatibility?.map { \"(\\($0.platform.name), \\($0.swiftVersion.rawValue))\" }.joined(separator: \", \")\n            )\n            let license = optionalRow(\"License\", version.license?.type.description)\n\n            return \"\"\"\n            \\(version.version)\n            \\(self.printManifest(defaultManifest))\\(manifests)\\(compatibility)\\(license)\n            \"\"\"\n        }\n\n        private func printManifest(_ manifest: PackageCollectionsModel.Package.Version.Manifest) -> String {\n            let modules = manifest.targets.compactMap { $0.moduleName }.joined(separator: \", \")\n            let products = optionalRow(\"Products\", manifest.products.isEmpty ? nil : manifest.products.compactMap { $0.name }.joined(separator: \", \"), indentationLevel: 3)\n\n            return \"\"\"\n                    Tools Version: \\(manifest.toolsVersion.description)\n                        Package Name: \\(manifest.packageName)\n                        Modules: \\(modules)\\(products)\n            \"\"\"\n        }\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            try await withState(swiftCommandState) { collections in\n                let identity = PackageIdentity(urlString: self.packageURL)\n\n                do { // assume URL is for a package in an imported collection\n                    let result = try await collections.getPackageMetadata(identity: identity, location: self.packageURL, collections: nil)\n\n                    if let versionString = version {\n                        guard let version = TSCUtility.Version(versionString), let result = result.package.versions.first(where: { $0.version == version }), let printedResult = printVersion(result) else {\n                            throw CollectionsError.invalidVersionString(versionString)\n                        }\n\n                        if jsonOptions.json {\n                            try JSONEncoder.makeWithDefaults().print(result)\n                        } else {\n                            print(\"\\(indent())Version: \\(printedResult)\")\n                        }\n                    } else {\n                        let description = optionalRow(\"Description\", result.package.summary)\n                        let versions = result.package.versions.map { \"\\($0.version)\" }.joined(separator: \", \")\n                        let stars = optionalRow(\"Stars\", result.package.watchersCount?.description)\n                        let readme = optionalRow(\"Readme\", result.package.readmeURL?.absoluteString)\n                        let authors = optionalRow(\"Authors\", result.package.authors?.map { $0.username }.joined(separator: \", \"))\n                        let license =  optionalRow(\"License\", result.package.license.map { \"\\($0.type) (\\($0.url))\" })\n                        let languages = optionalRow(\"Languages\", result.package.languages?.joined(separator: \", \"))\n                        let latestVersion = optionalRow(\"\\(String(repeating: \"-\", count: 60))\\n\\(indent())Latest Version\", printVersion(result.package.latestVersion))\n\n                        if jsonOptions.json {\n                            try JSONEncoder.makeWithDefaults().print(result.package)\n                        } else {\n                            print(\"\"\"\n                                \\(description)\n                                Available Versions: \\(versions)\\(readme)\\(license)\\(authors)\\(stars)\\(languages)\\(latestVersion)\n                            \"\"\")\n                        }\n                    }\n                } catch { // assume URL is for a collection\n                    // If a version argument was given, we do not perform the fallback.\n                    if version != nil {\n                        throw error\n                    }\n\n                    let collectionURL = try url(self.packageURL)\n\n                    do {\n                        let source = PackageCollectionsModel.CollectionSource(type: .json, url: collectionURL, skipSignatureCheck: self.skipSignatureCheck)\n                        let collection = try await collections.getCollection(source)\n\n                        let description = optionalRow(\"Description\", collection.overview)\n                        let keywords = optionalRow(\"Keywords\", collection.keywords?.joined(separator: \", \"))\n                        let createdAt = optionalRow(\"Created At\", DateFormatter().string(from: collection.createdAt))\n                        let packages = collection.packages.map { \"\\($0.identity)\" }.joined(separator: \"\\n\\(indent(levels: 2))\")\n\n                        if jsonOptions.json {\n                            try JSONEncoder.makeWithDefaults().print(collection)\n                        } else {\n                            let signature = optionalRow(\"Signed By\", collection.signature.map { \"\\($0.certificate.subject.commonName ?? \"Unspecified\") (\\($0.isVerified ? \"\" : \"not \")verified)\" })\n\n                            print(\"\"\"\n                                Name: \\(collection.name)\n                                Source: \\(collection.source.url)\\(description)\\(keywords)\\(createdAt)\n                                Packages:\n                                    \\(packages)\\(signature)\n                            \"\"\")\n                        }\n                    } catch PackageCollectionError.cannotVerifySignature {\n                        throw CollectionsError.cannotVerifySignature\n                    } catch PackageCollectionError.invalidSignature {\n                        throw CollectionsError.invalidSignature\n                    } catch {\n                        print(\"Failed to get metadata. The given URL either belongs to a collection that is invalid or unavailable, or a package that is not found in any of the imported collections.\")\n                    }\n                }\n            }\n        }\n    }\n}\n\nprivate func indent(levels: Int = 1) -> String {\n    return String(repeating: \"    \", count: levels)\n}\n\nprivate func optionalRow(_ title: String, _ contents: String?, indentationLevel: Int = 1) -> String {\n    if let contents, !contents.isEmpty {\n        return \"\\n\\(indent(levels: indentationLevel))\\(title): \\(contents)\"\n    } else {\n        return \"\"\n    }\n}\n\nprivate extension JSONEncoder {\n    func print<T>(_ value: T) throws where T: Encodable {\n        let jsonData = try self.encode(value)\n        let jsonString = String(decoding: jsonData, as: UTF8.self)\n        Swift.print(jsonString)\n    }\n}\n\nprivate extension ParsableCommand {\n    func withState<T>(\n        _ swiftCommandState: SwiftCommandState,\n        handler: (_ collections: PackageCollectionsProtocol) async throws -> T\n    ) async throws -> T {\n        _ = try? swiftCommandState.getActiveWorkspace(emitDeprecatedConfigurationWarning: true)\n        let collections = PackageCollections(\n            configuration: .init(\n                configurationDirectory: swiftCommandState.sharedConfigurationDirectory,\n                cacheDirectory: swiftCommandState.sharedCacheDirectory\n            ),\n            fileSystem: swiftCommandState.fileSystem,\n            observabilityScope: swiftCommandState.observabilityScope\n        )\n        defer {\n            do {\n                try collections.shutdown()\n            } catch {\n                Self.exit(withError: error)\n            }\n        }\n\n        return try await handler(collections)\n    }\n\n    func url(_ urlString: String) throws -> URL {\n        guard let url = URL(string: urlString) else {\n            let filePrefix = \"file://\"\n            guard urlString.hasPrefix(filePrefix) else {\n                throw CollectionsError.invalidArgument(\"collectionURL\")\n            }\n            // URL(fileURLWithPath:) can handle whitespaces in path\n            return URL(fileURLWithPath: String(urlString.dropFirst(filePrefix.count)))\n        }\n        return url\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsModel/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageCollectionsModel\n  PackageCollectionModel+v1.swift\n  PackageCollectionModel.swift)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageCollectionsModel PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\nif(NOT APPLE)\n  if(Foundation_FOUND)\n    target_link_directories(PackageCollectionsModel PRIVATE\n      $<TARGET_LINKER_FILE_DIR:Fooundation>)\n  endif()\nendif()\n\ninstall(TARGETS PackageCollectionsModel\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/PackageCollectionsModel/Formats/v1.md",
    "content": "# Package Collection\n\nPackage collections are short, curated lists of packages and associated metadata that can be imported\nby SwiftPM to make package discovery easier. Educators and community influencers can publish\npackage collections to go along with course materials or blog posts, removing the friction of using\npackages for the first time and the cognitive overload of deciding which packages are useful for\na particular task. Enterprises may use collections to narrow the decision space for their internal\nengineering teams, focusing them on a trusted set of vetted packages.\n\n## Creating a Package Collection\n\nA package collection is a JSON document that contains a list of packages and metadata per package.\n\nTo begin, define the top-level metadata about the collection:\n\n* `name`: The name of the package collection, for display purposes only.\n* `overview`: A description of the package collection. **Optional.**\n* `keywords`: An array of keywords that the collection is associated with. **Optional.**\n* `formatVersion`: The version of the format to which the collection conforms. Currently, `1.0` is the only allowed value.\n* `revision`: The revision number of this package collection. **Optional.**\n* `generatedAt`: The ISO 8601-formatted datetime string when the package collection was generated.\n* `generatedBy`: The author of this package collection. **Optional.**\n    * `name`: The author name.\n* `packages`: A non-empty array of package objects.\n\n#### Add packages to the collection\n\nEach item in the `packages` array is a package object with the following properties:\n\n* `url`: The URL of the package. Currently only Git repository URLs are supported. URL should be HTTPS and may contain `.git` suffix.\n* `identity`: The [identity](https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/PackageRegistry/Registry.md#36-package-identification) of the package if published to registry. **Optional.**\n* `summary`: A description of the package. **Optional.**\n* `keywords`: An array of keywords that the package is associated with. **Optional.**\n* `readmeURL`: The URL of the package's README. **Optional.**\n* `license`: The package's *current* license information. **Optional.**\n    * `url`: The URL of the license file.\n    * `name`: License name. [SPDX identifier](https://spdx.org/licenses/) (e.g., `Apache-2.0`, `MIT`, etc.) preferred. Omit if unknown. **Optional.**\n* `versions`: An array of version objects representing the most recent and/or relevant releases of the package.\n\n#### Add versions to a package\n\nA version object has metadata extracted from `Package.swift` and optionally additional metadata from other sources:\n\n* `version`: The semantic version string.\n* `summary`: A description of the package version. **Optional.**\n* `manifests`: A non-empty map of manifests by Swift tools version. The keys are (semantic) tools version (more on this below), while the values are:\n    * `toolsVersion`: The Swift tools version specified in the manifest.\n    * `packageName`: The name of the package.\n    * `targets`: An array of the package version's targets.\n        * `name`: The target name.\n        * `moduleName`: The module name if this target can be imported as a module. **Optional.**\n    * `products`: An array of the package version's products.\n        * `name`: The product name.\n        * `type`: The product type. This must have the same JSON representation as SwiftPM's `PackageModel.ProductType`.\n        * `target`: An array of the product’s targets.\n    * `minimumPlatformVersions`: An array of the package version’s supported platforms specified in `Package.swift`. **Optional.** \n\n```json\n{\n  \"5.2\": {\n    \"toolsVersion\": \"5.2\",\n    \"packageName\": \"MyPackage\",\n    \"targets\": [\n      {\n        \"name\": \"MyTarget\",\n        \"moduleName\": \"MyTarget\"\n      }\n    ],\n    \"products\": [\n      {\n        \"name\": \"MyProduct\",\n        \"type\": {\n          \"library\": [\"automatic\"]\n        },\n        \"targets\": [\"MyTarget\"]\n      }\n    ],\n    \"minimumPlatformVersions\": [\n      {\n        \"name\": \"macOS\",\n        \"version\": \"10.15\"\n      }\n    ]\n  }\n}\n```\n\n* `defaultToolsVersion`: The Swift tools version of the default manifest. The `manifests` map must contain this in its keys. \n* `verifiedCompatibility`: An array of compatible platforms and Swift versions that has been tested and verified for. Valid platform names include `macOS`, `iOS`, `tvOS`, `watchOS`, `Linux`, `Android`, and `Windows`. Swift version should be semantic version string and as specific as possible. **Optional.**\n\n```json\n{\n  \"platform\": {\n    \"name\": \"macOS\"\n  },\n  \"swiftVersion\": \"5.3.2\"\n}\n```\n\n* `license`: The package version's license. **Optional.**\n    * `url`: The URL of the license file.\n    * `name`: License name. [SPDX identifier](https://spdx.org/licenses/) (e.g., `Apache-2.0`, `MIT`, etc.) preferred. Omit if unknown. **Optional.**\n* `author`: The package version's author. **Optional.**\n    * `name`: The author of the package version.\n* `signer`: The signer of the package version. **Optional.** Refer to [documentation](https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/PackageRegistry/PackageRegistryUsage.md#package-signing) on package signing for details.\n    * `type`: The signer type. Currently the only valid value is `ADP` (Apple Developer Program).\n    * `commonName`: The common name of the signing certificate's subject.\n    * `organizationalUnitName`: The organizational unit name of the signing certificate's subject.\n    * `organizationName`: The organization name of the signing certificate's subject.           \n* `createdAt`: The ISO 8601-formatted datetime string when the package version was created. **Optional.**\n\n##### Version-specific manifests\n\nPackage collection generators should include data from the \"default\" manifest `Package.swift` as well as [version-specific manifest(s)](https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/Usage.md#version-specific-manifest-selection).\n\nThe keys of the `manifests` map are Swift tools (semantic) versions:\n* For `Package.swift`, the tools version specified in `Package.swift` should be used.\n* For version-specific manifests, the tools version specified in the filename should be used. For example, for `Package@swift-4.2.swift` it would be `4.2`. The tools version in the manifest must match that in the filename. \n\n##### Version-specific tags\n\n[Version-specific tags](https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/Usage.md#version-specific-tag-selection) are not\nsupported by package collections.\n\n## Example\n\n```json\n{\n  \"name\": \"Sample Package Collection\",\n  \"overview\": \"This is a sample package collection listing made-up packages.\",\n  \"keywords\": [\"sample package collection\"],\n  \"formatVersion\": \"1.0\",\n  \"revision\": 3,\n  \"generatedAt\": \"2020-10-22T06:03:52Z\",\n  \"packages\": [\n    {\n      \"url\": \"https://www.example.com/repos/RepoOne.git\",\n      \"summary\": \"Package One\",\n      \"readmeURL\": \"https://www.example.com/repos/RepoOne/README\",\n      \"license\": {\n        \"name\": \"Apache-2.0\",\n        \"url\": \"https://www.example.com/repos/RepoOne/LICENSE\"\n      },\n      \"versions\": [\n        {\n          \"version\": \"0.1.0\",\n          \"summary\": \"Fixed a few bugs\",\n          \"manifests\": {\n            \"5.1\": {\n              \"toolsVersion\": \"5.1\",\n              \"packageName\": \"PackageOne\",\n              \"targets\": [\n                {\n                  \"name\": \"Foo\",\n                  \"moduleName\": \"Foo\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Foo\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Foo\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.1\",\n          \"verifiedCompatibility\": [\n            {\n              \"platform\": { \"name\": \"macOS\" },\n              \"swiftVersion\": \"5.1\"\n            },\n            {\n              \"platform\": { \"name\": \"iOS\" },\n              \"swiftVersion\": \"5.1\"\n            },\n            {\n              \"platform\": { \"name\": \"Linux\" },\n              \"swiftVersion\": \"5.1\"\n            }\n          ],\n          \"license\": {\n            \"name\": \"Apache-2.0\",\n            \"url\": \"https://www.example.com/repos/RepoOne/LICENSE\"\n          },\n          \"createdAt\": \"2020-10-21T09:25:36Z\"\n        }\n      ]\n    },\n    {\n      \"url\": \"https://www.example.com/repos/RepoTwo.git\",\n      \"summary\": \"Package Two\",\n      \"readmeURL\": \"https://www.example.com/repos/RepoTwo/README\",\n      \"versions\": [\n        {\n          \"version\": \"2.1.0\",\n          \"manifests\": {\n            \"5.2\": {\n              \"toolsVersion\": \"5.2\",\n              \"packageName\": \"PackageTwo\",\n              \"targets\": [\n                {\n                  \"name\": \"Bar\",\n                  \"moduleName\": \"Bar\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Bar\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Bar\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.2\"\n        },\n        {\n          \"version\": \"1.8.3\",\n          \"manifests\": {\n            \"5.0\": {\n              \"toolsVersion\": \"5.0\",\n              \"packageName\": \"PackageTwo\",\n              \"targets\": [\n                {\n                  \"name\": \"Bar\",\n                  \"moduleName\": \"Bar\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Bar\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Bar\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.0\"\n        }\n      ]\n    }\n  ]\n}\n```\n"
  },
  {
    "path": "Sources/PackageCollectionsModel/PackageCollectionModel+v1.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension PackageCollectionModel {\n    public enum V1 {}\n}\n\nextension PackageCollectionModel.V1 {\n    public struct Collection: Equatable, Codable {\n        /// The name of the package collection, for display purposes only.\n        public let name: String\n\n        /// A description of the package collection.\n        public let overview: String?\n\n        /// An array of keywords that the collection is associated with.\n        public let keywords: [String]?\n\n        /// An array of package metadata objects\n        public let packages: [PackageCollectionModel.V1.Collection.Package]\n\n        /// The version of the format to which the collection conforms.\n        public let formatVersion: PackageCollectionModel.FormatVersion\n\n        /// The revision number of this package collection.\n        public let revision: Int?\n\n        /// When the package collection was generated.\n        public let generatedAt: Date\n\n        /// The author of this package collection.\n        public let generatedBy: Author?\n\n        /// Creates a `Collection`\n        public init(\n            name: String,\n            overview: String?,\n            keywords: [String]?,\n            packages: [PackageCollectionModel.V1.Collection.Package],\n            formatVersion: PackageCollectionModel.FormatVersion,\n            revision: Int?,\n            generatedAt: Date = Date(),\n            generatedBy: Author?\n        ) {\n            precondition(formatVersion == .v1_0, \"Unsupported format version: \\(formatVersion)\")\n\n            self.name = name\n            self.overview = overview\n            self.keywords = keywords\n            self.packages = packages\n            self.formatVersion = formatVersion\n            self.revision = revision\n            self.generatedAt = generatedAt\n            self.generatedBy = generatedBy\n        }\n\n        public struct Author: Equatable, Codable {\n            /// The author name.\n            public let name: String\n\n            /// Creates an `Author`\n            public init(name: String) {\n                self.name = name\n            }\n        }\n    }\n}\n\nextension PackageCollectionModel.V1.Collection {\n    public struct Package: Equatable, Codable {\n        /// The URL of the package. Currently only Git repository URLs are supported.\n        public let url: URL\n        \n        /// Package identity for registry (https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/PackageRegistry/Registry.md#36-package-identification).\n        public let identity: String?\n\n        /// A description of the package.\n        public let summary: String?\n\n        /// An array of keywords that the package is associated with.\n        public let keywords: [String]?\n\n        /// An array of version objects representing the most recent and/or relevant releases of the package.\n        public let versions: [PackageCollectionModel.V1.Collection.Package.Version]\n\n        /// The URL of the package's README.\n        public let readmeURL: URL?\n\n        /// The package's current license info\n        public let license: PackageCollectionModel.V1.License?\n\n        /// Creates a `Package`\n        public init(\n            url: URL,\n            identity: String? = nil,\n            summary: String?,\n            keywords: [String]?,\n            versions: [PackageCollectionModel.V1.Collection.Package.Version],\n            readmeURL: URL?,\n            license: PackageCollectionModel.V1.License?\n        ) {\n            self.url = url\n            self.identity = identity\n            self.summary = summary\n            self.keywords = keywords\n            self.versions = versions\n            self.readmeURL = readmeURL\n            self.license = license\n        }\n    }\n}\n\nextension PackageCollectionModel.V1.Collection.Package {\n    public struct Version: Equatable, Codable {\n        /// The semantic version string.\n        public let version: String\n\n        /// A description of the package version.\n        public let summary: String?\n\n        /// Manifests by tools version.\n        public let manifests: [String: Manifest]\n\n        /// Tools version of the default manifest.\n        public let defaultToolsVersion: String\n\n        /// An array of compatible platforms and Swift versions that has been tested and verified for.\n        public let verifiedCompatibility: [PackageCollectionModel.V1.Compatibility]?\n\n        /// The package version's license.\n        public let license: PackageCollectionModel.V1.License?\n\n        /// The author of the package version.\n        public let author: Author?\n\n        /// The signer of the package version.\n        public let signer: PackageCollectionModel.V1.Signer?\n\n        /// When the package version was created.\n        public let createdAt: Date?\n\n        /// Creates a `Version`\n        public init(\n            version: String,\n            summary: String?,\n            manifests: [String: Manifest],\n            defaultToolsVersion: String,\n            verifiedCompatibility: [PackageCollectionModel.V1.Compatibility]?,\n            license: PackageCollectionModel.V1.License?,\n            author: Author?,\n            signer: PackageCollectionModel.V1.Signer?,\n            createdAt: Date?\n        ) {\n            self.version = version\n            self.summary = summary\n            self.manifests = manifests\n            self.defaultToolsVersion = defaultToolsVersion\n            self.verifiedCompatibility = verifiedCompatibility\n            self.license = license\n            self.author = author\n            self.signer = signer\n            self.createdAt = createdAt\n        }\n\n        public struct Manifest: Equatable, Codable {\n            /// The tools (semantic) version specified in `Package.swift`.\n            public let toolsVersion: String\n\n            /// The name of the package.\n            public let packageName: String\n\n            /// An array of the package version's targets.\n            public let targets: [PackageCollectionModel.V1.Target]\n\n            /// An array of the package version's products.\n            public let products: [PackageCollectionModel.V1.Product]\n\n            /// An array of the package version’s supported platforms specified in `Package.swift`.\n            public let minimumPlatformVersions: [PackageCollectionModel.V1.PlatformVersion]?\n\n            /// Creates a `Manifest`\n            public init(\n                toolsVersion: String,\n                packageName: String,\n                targets: [PackageCollectionModel.V1.Target],\n                products: [PackageCollectionModel.V1.Product],\n                minimumPlatformVersions: [PackageCollectionModel.V1.PlatformVersion]?\n            ) {\n                self.toolsVersion = toolsVersion\n                self.packageName = packageName\n                self.targets = targets\n                self.products = products\n                self.minimumPlatformVersions = minimumPlatformVersions\n            }\n        }\n\n        public struct Author: Equatable, Codable {\n            /// The author name.\n            public let name: String\n\n            /// Creates an `Author`\n            public init(name: String) {\n                self.name = name\n            }\n        }\n    }\n}\n\nextension PackageCollectionModel.V1 {\n    public struct Target: Equatable, Codable {\n        /// The target name.\n        public let name: String\n\n        /// The module name if this target can be imported as a module.\n        public let moduleName: String?\n\n        /// Creates a `Target`\n        public init(name: String, moduleName: String?) {\n            self.name = name\n            self.moduleName = moduleName\n        }\n    }\n\n    public struct Product: Equatable, Codable {\n        /// The product name.\n        public let name: String\n\n        /// The product type.\n        public let type: ProductType\n\n        /// An array of the product’s targets.\n        public let targets: [String]\n\n        /// Creates a `Product`\n        public init(\n            name: String,\n            type: ProductType,\n            targets: [String]\n        ) {\n            self.name = name\n            self.type = type\n            self.targets = targets\n        }\n    }\n\n    public struct PlatformVersion: Equatable, Codable {\n        /// The name of the platform (e.g., macOS, Linux, etc.).\n        public let name: String\n\n        /// The semantic version of the platform.\n        public let version: String\n\n        /// Creates a `PlatformVersion`\n        public init(name: String, version: String) {\n            self.name = name\n            self.version = version\n        }\n    }\n\n    public struct Platform: Equatable, Codable {\n        /// The name of the platform (e.g., macOS, Linux, etc.).\n        public let name: String\n\n        /// Creates a `Platform`\n        public init(name: String) {\n            self.name = name\n        }\n    }\n\n    /// Compatible platform and Swift version.\n    public struct Compatibility: Equatable, Codable {\n        /// The platform (e.g., macOS, Linux, etc.)\n        public let platform: Platform\n\n        /// The Swift version\n        public let swiftVersion: String\n\n        /// Creates a `Compatibility`\n        public init(platform: Platform, swiftVersion: String) {\n            self.platform = platform\n            self.swiftVersion = swiftVersion\n        }\n    }\n\n    public struct License: Equatable, Codable {\n        /// License name (e.g., Apache-2.0, MIT, etc.)\n        public let name: String?\n\n        /// The URL of the license file.\n        public let url: URL\n\n        /// Creates a `License`\n        public init(name: String?, url: URL) {\n            self.name = name\n            self.url = url\n        }\n    }\n\n    public struct Signer: Equatable, Codable {\n        /// The signer type. (e.g., ADP)\n        public let type: String\n\n        /// The common name of the signing certificate's subject.\n        public let commonName: String\n\n        /// The organizational unit name of the signing certificate's subject.\n        public let organizationalUnitName: String\n\n        /// The organization name of the signing certificate's subject.\n        public let organizationName: String\n\n        public init(\n            type: String,\n            commonName: String,\n            organizationalUnitName: String,\n            organizationName: String\n        ) {\n            self.type = type\n            self.commonName = commonName\n            self.organizationalUnitName = organizationalUnitName\n            self.organizationName = organizationName\n        }\n    }\n}\n\nextension PackageCollectionModel.V1.Platform: Hashable {\n    public var hashValue: Int { name.hashValue }\n\n    public func hash(into hasher: inout Hasher) {\n        name.hash(into: &hasher)\n    }\n}\n\nextension PackageCollectionModel.V1.Platform: Comparable {\n    public static func < (lhs: Self, rhs: Self) -> Bool {\n        lhs.name < rhs.name\n    }\n}\n\nextension PackageCollectionModel.V1.Compatibility: Comparable {\n    public static func < (lhs: Self, rhs: Self) -> Bool {\n        if lhs.platform != rhs.platform { return lhs.platform < rhs.platform }\n        return lhs.swiftVersion < rhs.swiftVersion\n    }\n}\n\n// MARK: -  Copy `PackageModel.ProductType` to minimize the module's dependencies\n\nextension PackageCollectionModel.V1 {\n    /// The type of product.\n    public enum ProductType: Equatable {\n        /// The type of library.\n        public enum LibraryType: String, Codable {\n            /// Static library.\n            case `static`\n\n            /// Dynamic library.\n            case dynamic\n\n            /// The type of library is unspecified and should be decided by package manager.\n            case automatic\n        }\n\n        /// A library product.\n        case library(LibraryType)\n\n        /// An executable product.\n        case executable\n\n        /// An plugin product.\n        case plugin\n        \n        /// An executable code snippet.\n        case snippet\n\n        /// A test product.\n        case test\n        \n        /// A macro product.\n        case `macro`\n    }\n}\n\nextension PackageCollectionModel.V1.ProductType: Codable {\n    private enum CodingKeys: String, CodingKey {\n        case library, executable, plugin, snippet, test, `macro`\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .library(let a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .library)\n            try unkeyedContainer.encode(a1)\n        case .executable:\n            try container.encodeNil(forKey: .executable)\n        case .plugin:\n            try container.encodeNil(forKey: .plugin)\n        case .snippet:\n            try container.encodeNil(forKey: .snippet)\n        case .test:\n            try container.encodeNil(forKey: .test)\n        case .macro:\n            try container.encodeNil(forKey: .macro)\n        }\n    }\n\n    public init(from decoder: Decoder) throws {\n        let values = try decoder.container(keyedBy: CodingKeys.self)\n        guard let key = values.allKeys.first(where: values.contains) else {\n            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: \"Did not find a matching key\"))\n        }\n        switch key {\n        case .library:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode(PackageCollectionModel.V1.ProductType.LibraryType.self)\n            self = .library(a1)\n        case .executable:\n            self = .executable\n        case .plugin:\n            self = .plugin\n        case .snippet:\n            self = .snippet\n        case .test:\n            self = .test\n        case .macro:\n            self = .macro\n        }\n    }\n}\n\n// MARK: - Signed package collection\n\nextension PackageCollectionModel.V1 {\n    /// A  signed package collection. The only difference between this and `Collection`\n    /// is the presence of `signature`.\n    public struct SignedCollection: Equatable {\n        /// The package collection\n        public let collection: PackageCollectionModel.V1.Collection\n\n        /// The signature and metadata\n        public let signature: PackageCollectionModel.V1.Signature\n\n        /// Creates a `SignedCollection`\n        public init(collection: PackageCollectionModel.V1.Collection, signature: PackageCollectionModel.V1.Signature) {\n            self.collection = collection\n            self.signature = signature\n        }\n    }\n\n    /// Package collection signature and associated metadata\n    public struct Signature: Equatable, Codable {\n        /// The signature\n        public let signature: String\n\n        /// Details about the certificate used to generate the signature\n        public let certificate: Certificate\n\n        public init(signature: String, certificate: Certificate) {\n            self.signature = signature\n            self.certificate = certificate\n        }\n\n        public struct Certificate: Equatable, Codable {\n            /// Subject of the certificate\n            public let subject: Name\n\n            /// Issuer of the certificate\n            public let issuer: Name\n\n            /// Creates a `Certificate`\n            public init(subject: Name, issuer: Name) {\n                self.subject = subject\n                self.issuer = issuer\n            }\n\n            /// Generic certificate name (e.g., subject, issuer)\n            public struct Name: Equatable, Codable {\n                /// User ID\n                public let userID: String?\n\n                /// Common name\n                public let commonName: String?\n\n                /// Organizational unit\n                public let organizationalUnit: String?\n\n                /// Organization\n                public let organization: String?\n\n                /// Creates a `Name`\n                public init(userID: String?,\n                            commonName: String?,\n                            organizationalUnit: String?,\n                            organization: String?) {\n                    self.userID = userID\n                    self.commonName = commonName\n                    self.organizationalUnit = organizationalUnit\n                    self.organization = organization\n                }\n            }\n        }\n    }\n}\n\nextension PackageCollectionModel.V1.SignedCollection: Codable {\n    enum CodingKeys: String, CodingKey {\n        // Collection properties\n        case name\n        case overview\n        case keywords\n        case packages\n        case formatVersion\n        case revision\n        case generatedAt\n        case generatedBy\n\n        case signature\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        try container.encode(self.collection.name, forKey: .name)\n        try container.encodeIfPresent(self.collection.overview, forKey: .overview)\n        try container.encodeIfPresent(self.collection.keywords, forKey: .keywords)\n        try container.encode(self.collection.packages, forKey: .packages)\n        try container.encode(self.collection.formatVersion, forKey: .formatVersion)\n        try container.encodeIfPresent(self.collection.revision, forKey: .revision)\n        try container.encode(self.collection.generatedAt, forKey: .generatedAt)\n        try container.encodeIfPresent(self.collection.generatedBy, forKey: .generatedBy)\n        try container.encode(self.signature, forKey: .signature)\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        self.collection = try PackageCollectionModel.V1.Collection(from: decoder)\n        self.signature = try container.decode(PackageCollectionModel.V1.Signature.self, forKey: .signature)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsModel/PackageCollectionModel.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n// Models used for creating and publishing package collections\npublic enum PackageCollectionModel {}\n\nextension PackageCollectionModel {\n    /// Representation of package collection (JSON) schema version\n    public enum FormatVersion: String, Codable {\n        case v1_0 = \"1.0\"\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsSigning/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageCollectionsSigning\n  CertificatePolicy.swift\n  PackageCollectionSigning.swift\n  Signature.swift\n  Utilities/Base64URL.swift\n  Utilities/Utilities.swift\n  X509Extensions.swift\n  embedded_resources.swift)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageCollectionsSigning PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\ntarget_link_libraries(PackageCollectionsSigning PUBLIC\n  Basics\n  PackageCollectionsModel\n  Crypto\n  _CryptoExtras\n  SwiftASN1\n  X509)\nif(NOT APPLE)\n  if(Foundation_FOUND)\n    target_link_directories(PackageCollectionsSigning PRIVATE\n      $<TARGET_LINKER_FILE_DIR:Fooundation>)\n  endif()\n  if(dispatch_FOUND)\n    target_link_directories(PackageCollectionsSigning PRIVATE\n      $<TARGET_LINKER_FILE_DIR:dispatch>)\n  endif()\nendif()\n\ninstall(TARGETS PackageCollectionsSigning\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/PackageCollectionsSigning/CertificatePolicy.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Dispatch\nimport Foundation\n\nimport Basics\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftASN1\n@_implementationOnly import X509\n#else\nimport SwiftASN1\nimport X509\n#endif\n\npublic enum CertificatePolicyKey: Hashable, CustomStringConvertible {\n    case `default`(subjectUserID: String? = nil, subjectOrganizationalUnit: String? = nil)\n    case appleSwiftPackageCollection(subjectUserID: String? = nil, subjectOrganizationalUnit: String? = nil)\n\n    @available(*, deprecated, message: \"use `appleSwiftPackageCollection` instead\")\n    case appleDistribution(subjectUserID: String? = nil, subjectOrganizationalUnit: String? = nil)\n\n    /// For testing only\n    case custom\n\n    public var description: String {\n        switch self {\n        case .default(let userID, let organizationalUnit):\n            return \"Default certificate policy\\(userID.map { \" (userID: \\($0))\" } ?? \"\")\\(organizationalUnit.map { \" (organizationalUnit: \\($0))\" } ?? \"\")\"\n        case .appleSwiftPackageCollection(let userID, let organizationalUnit):\n            return \"Swift Package Collection certificate policy\\(userID.map { \" (userID: \\($0))\" } ?? \"\")\\(organizationalUnit.map { \" (organizationalUnit: \\($0))\" } ?? \"\")\"\n        case .appleDistribution(let userID, let organizationalUnit):\n            return \"Distribution certificate policy\\(userID.map { \" (userID: \\($0))\" } ?? \"\")\\(organizationalUnit.map { \" (organizationalUnit: \\($0))\" } ?? \"\")\"\n        case .custom:\n            return \"Custom certificate policy\"\n        }\n    }\n\n    public static let `default` = CertificatePolicyKey.default()\n    public static let appleSwiftPackageCollection = CertificatePolicyKey.appleSwiftPackageCollection()\n    @available(*, deprecated, message: \"use `appleSwiftPackageCollection` instead\")\n    public static let appleDistribution = CertificatePolicyKey.appleDistribution()\n}\n\n// MARK: - Certificate policies\n\nprotocol CertificatePolicy {\n    /// Validates the given certificate chain.\n    ///\n    /// - Parameters:\n    ///   - certChain: The certificate being verified must be the first element of the array, with its issuer the next\n    ///                element and so on, and the root CA certificate is last.\n    ///   - validationTime: Overrides the timestamp used for checking certificate expiry (e.g., for testing).\n    ///                     By default the current time is used.\n    func validate(certChain: [Certificate], validationTime: Date) async throws\n}\n\nextension CertificatePolicy {\n    /// Validates the given certificate chain.\n    ///\n    /// - Parameters:\n    ///   - certChain: The certificate being verified must be the first element of the array, with its issuer the next\n    ///                element and so on, and the root CA certificate is last.\n    func validate(certChain: [Certificate]) async throws {\n        try await self.validate(certChain: certChain, validationTime: Date())\n    }\n\n    func verify(\n        certChain: [Certificate],\n        trustedRoots: [Certificate]?,\n        @PolicyBuilder policies: () -> some VerifierPolicy,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        guard !certChain.isEmpty else {\n            throw CertificatePolicyError.emptyCertChain\n        }\n\n        let policies = policies()\n\n        var trustStore = CertificateStores.defaultTrustRoots\n        if let trustedRoots {\n            trustStore.append(contentsOf: trustedRoots)\n        }\n\n        guard !trustStore.isEmpty else {\n            throw CertificatePolicyError.noTrustedRootCertsConfigured\n        }\n\n        var verifier = Verifier(rootCertificates: CertificateStore(trustStore)) {\n            policies\n        }\n        let result = await verifier.validate(\n            leafCertificate: certChain[0],\n            intermediates: CertificateStore(certChain)\n        )\n\n        switch result {\n        case .validCertificate:\n            return\n        case .couldNotValidate(let failures):\n            observabilityScope.emit(error: \"Failed to validate certificate chain \\(certChain): \\(failures)\")\n            throw CertificatePolicyError.invalidCertChain\n        }\n    }\n}\n\nenum CertificatePolicyError: Error, Equatable {\n    case noTrustedRootCertsConfigured\n    case emptyCertChain\n    case invalidCertChain\n}\n\n/// Default policy for validating certificates used to sign package collections.\n///\n/// Certificates must satisfy these conditions:\n///   - The timestamp at which signing/verification is done must fall within the signing certificate’s validity period.\n///   - The certificate’s “Extended Key Usage” extension must include “Code Signing”.\n///   - The certificate must use either 256-bit EC (recommended) or 2048-bit RSA key.\n///   - The certificate must not be revoked. The certificate authority must support OCSP.\n///   - The certificate chain is valid and root certificate must be trusted.\nstruct DefaultCertificatePolicy: CertificatePolicy {\n    let trustedRoots: [Certificate]\n    let expectedSubjectUserID: String?\n    let expectedSubjectOrganizationalUnit: String?\n\n    private let httpClient: HTTPClient\n    private let observabilityScope: ObservabilityScope\n\n    /// Initializes a `DefaultCertificatePolicy`.\n    ///\n    /// - Parameters:\n    ///   - trustedRootCertsDir: Users may specify root certificates in addition to SwiftPM's default trust\n    ///                          store by placing them in this directory.\n    ///   - additionalTrustedRootCerts: Root certificates to be trusted in addition to those in `trustedRootCertsDir`.\n    ///                                 The difference between this and `trustedRootCertsDir` is that the latter is\n    ///                                 user configured and dynamic, while this is configured by SwiftPM and static.\n    ///   - expectedSubjectUserID: The subject user ID that must match if specified.\n    ///   - expectedSubjectOrganizationalUnit: The subject organizational unit name that must match if specified.\n    init(\n        trustedRootCertsDir: URL?,\n        additionalTrustedRootCerts: [Certificate]?,\n        expectedSubjectUserID: String? = nil,\n        expectedSubjectOrganizationalUnit: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) {\n        var trustedRoots = [Certificate]()\n        if let trustedRootCertsDir {\n            trustedRoots\n                .append(contentsOf: Self.loadCerts(at: trustedRootCertsDir, observabilityScope: observabilityScope))\n        }\n        if let additionalTrustedRootCerts {\n            trustedRoots.append(contentsOf: additionalTrustedRootCerts)\n        }\n        self.trustedRoots = trustedRoots\n        self.expectedSubjectUserID = expectedSubjectUserID\n        self.expectedSubjectOrganizationalUnit = expectedSubjectOrganizationalUnit\n        self.httpClient = HTTPClient.makeDefault()\n        self.observabilityScope = observabilityScope\n    }\n\n    func validate(certChain: [Certificate], validationTime: Date) async throws {\n        guard !certChain.isEmpty else {\n            throw CertificatePolicyError.emptyCertChain\n        }\n\n        try await self.verify(\n            certChain: certChain,\n            trustedRoots: self.trustedRoots,\n            policies: {\n                _ADPCertificatePolicy() // included for testing\n                // Check if subject name matches\n                _SubjectNamePolicy(\n                    expectedUserID: self.expectedSubjectUserID,\n                    expectedOrganizationalUnit: self.expectedSubjectOrganizationalUnit\n                )\n                // Must be a code signing certificate\n                _CodeSigningPolicy()\n                // Basic validations including expiry check\n                RFC5280Policy(validationTime: validationTime)\n                // Must support OCSP\n                _OCSPVerifierPolicy(\n                    httpClient: self.httpClient,\n                    validationTime: validationTime\n                )\n            },\n            observabilityScope: self.observabilityScope\n        )\n    }\n}\n\n/// Policy for validating developer.apple.com Swift Package Collection certificates.\n///\n/// This has the same requirements as `DefaultCertificatePolicy` plus additional\n/// marker extensions for Swift Package Collection certifiicates.\nstruct ADPSwiftPackageCollectionCertificatePolicy: CertificatePolicy {\n    let trustedRoots: [Certificate]\n    let expectedSubjectUserID: String?\n    let expectedSubjectOrganizationalUnit: String?\n\n    private let httpClient: HTTPClient\n    private let observabilityScope: ObservabilityScope\n\n    /// Initializes a `ADPSwiftPackageCollectionCertificatePolicy`.\n    ///\n    /// - Parameters:\n    ///   - trustedRootCertsDir: Users may specify root certificates in addition to SwiftPM's default trust\n    ///                          store by placing them in this directory.\n    ///   - additionalTrustedRootCerts: Root certificates to be trusted in addition to those in `trustedRootCertsDir`.\n    ///                                 The difference between this and `trustedRootCertsDir` is that the latter is\n    ///                                 user configured and dynamic, while this is configured by SwiftPM and static.\n    ///   - expectedSubjectUserID: The subject user ID that must match if specified.\n    ///   - expectedSubjectOrganizationalUnit: The subject organizational unit name that must match if specified.\n    init(\n        trustedRootCertsDir: URL?,\n        additionalTrustedRootCerts: [Certificate]?,\n        expectedSubjectUserID: String? = nil,\n        expectedSubjectOrganizationalUnit: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) {\n        var trustedRoots = [Certificate]()\n        if let trustedRootCertsDir {\n            trustedRoots\n                .append(contentsOf: Self.loadCerts(at: trustedRootCertsDir, observabilityScope: observabilityScope))\n        }\n        if let additionalTrustedRootCerts {\n            trustedRoots.append(contentsOf: additionalTrustedRootCerts)\n        }\n        self.trustedRoots = trustedRoots\n        self.expectedSubjectUserID = expectedSubjectUserID\n        self.expectedSubjectOrganizationalUnit = expectedSubjectOrganizationalUnit\n        self.httpClient = HTTPClient.makeDefault()\n        self.observabilityScope = observabilityScope\n    }\n\n    func validate(certChain: [Certificate], validationTime: Date) async throws {\n        guard !certChain.isEmpty else {\n            throw CertificatePolicyError.emptyCertChain\n        }\n\n        try await self.verify(\n            certChain: certChain,\n            trustedRoots: self.trustedRoots,\n            policies: {\n                // Check for specific markers\n                _ADPSwiftPackageCertificatePolicy()\n                _ADPCertificatePolicy() // included for testing\n                // Check if subject name matches\n                _SubjectNamePolicy(\n                    expectedUserID: self.expectedSubjectUserID,\n                    expectedOrganizationalUnit: self.expectedSubjectOrganizationalUnit\n                )\n                // Must be a code signing certificate\n                _CodeSigningPolicy()\n                // Basic validations including expiry check\n                RFC5280Policy(validationTime: validationTime)\n                // Must support OCSP\n                _OCSPVerifierPolicy(\n                    httpClient: self.httpClient,\n                    validationTime: validationTime\n                )\n            },\n            observabilityScope: self.observabilityScope\n        )\n    }\n}\n\n/// Policy for validating developer.apple.com Apple Distribution certificates.\n///\n/// This has the same requirements as `DefaultCertificatePolicy` plus additional\n/// marker extensions for Apple Distribution certifiicates.\nstruct ADPAppleDistributionCertificatePolicy: CertificatePolicy {\n    let trustedRoots: [Certificate]\n    let expectedSubjectUserID: String?\n    let expectedSubjectOrganizationalUnit: String?\n\n    private let httpClient: HTTPClient\n    private let observabilityScope: ObservabilityScope\n\n    /// Initializes a `ADPAppleDistributionCertificatePolicy`.\n    ///\n    /// - Parameters:\n    ///   - trustedRootCertsDir: Users may specify root certificates in addition to SwiftPM's default trust\n    ///                          store by placing them in this directory.\n    ///   - additionalTrustedRootCerts: Root certificates to be trusted in addition to those in `trustedRootCertsDir`.\n    ///                                 The difference between this and `trustedRootCertsDir` is that the latter is\n    ///                                 user configured and dynamic, while this is configured by SwiftPM and static.\n    ///   - expectedSubjectUserID: The subject user ID that must match if specified.\n    ///   - expectedSubjectOrganizationalUnit: The subject organizational unit name that must match if specified.\n    init(\n        trustedRootCertsDir: URL?,\n        additionalTrustedRootCerts: [Certificate]?,\n        expectedSubjectUserID: String? = nil,\n        expectedSubjectOrganizationalUnit: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) {\n        var trustedRoots = [Certificate]()\n        if let trustedRootCertsDir {\n            trustedRoots\n                .append(contentsOf: Self.loadCerts(at: trustedRootCertsDir, observabilityScope: observabilityScope))\n        }\n        if let additionalTrustedRootCerts {\n            trustedRoots.append(contentsOf: additionalTrustedRootCerts)\n        }\n        self.trustedRoots = trustedRoots\n        self.expectedSubjectUserID = expectedSubjectUserID\n        self.expectedSubjectOrganizationalUnit = expectedSubjectOrganizationalUnit\n        self.httpClient = HTTPClient.makeDefault()\n        self.observabilityScope = observabilityScope\n    }\n\n    func validate(certChain: [Certificate], validationTime: Date) async throws {\n        guard !certChain.isEmpty else {\n            throw CertificatePolicyError.emptyCertChain\n        }\n\n        try await self.verify(\n            certChain: certChain,\n            trustedRoots: self.trustedRoots,\n            policies: {\n                // Check for specific markers\n                _ADPAppleDistributionCertificatePolicy()\n                _ADPCertificatePolicy() // included for testing\n                // Check if subject name matches\n                _SubjectNamePolicy(\n                    expectedUserID: self.expectedSubjectUserID,\n                    expectedOrganizationalUnit: self.expectedSubjectOrganizationalUnit\n                )\n                // Must be a code signing certificate\n                _CodeSigningPolicy()\n                // Basic validations including expiry check\n                RFC5280Policy(validationTime: validationTime)\n                // Must support OCSP\n                _OCSPVerifierPolicy(\n                    httpClient: self.httpClient,\n                    validationTime: validationTime\n                )\n            },\n            observabilityScope: self.observabilityScope\n        )\n    }\n}\n\n// MARK: - Verifier policies\n\n/// Policy for code signing certificates.\nstruct _CodeSigningPolicy: VerifierPolicy {\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = [\n        ASN1ObjectIdentifier.X509ExtensionID.keyUsage,\n        ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage,\n    ]\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        let isCodeSigning = (\n            try? chain.leaf.extensions.extendedKeyUsage?.contains(ExtendedKeyUsage.Usage.codeSigning)\n        ) ?? false\n        guard isCodeSigning else {\n            return .failsToMeetPolicy(reason: \"Certificate \\(chain.leaf) does not have code signing extended key usage\")\n        }\n        return .meetsPolicy\n    }\n}\n\n/// Policy for revocation check via OCSP.\nstruct _OCSPVerifierPolicy: VerifierPolicy {\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []\n\n    private static let cacheTTL: DispatchTimeInterval = .seconds(5 * 60)\n    private let cache = ThreadSafeKeyValueStore<\n        UnverifiedCertificateChain,\n        (result: PolicyEvaluationResult, expires: DispatchTime)\n    >()\n\n    private var underlying: OCSPVerifierPolicy<_OCSPRequester>\n\n    init(httpClient: HTTPClient, validationTime: Date) {\n        self.underlying = OCSPVerifierPolicy(\n            failureMode: .soft,\n            requester: _OCSPRequester(httpClient: httpClient),\n            validationTime: validationTime\n        )\n    }\n\n    mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        // Look for cached result\n        if let cached = self.cache[chain], cached.expires < .now() {\n            return cached.result\n        }\n\n        // This makes HTTP requests\n        let result = await self.underlying.chainMeetsPolicyRequirements(chain: chain)\n\n        // Save result to cache\n        self.cache[chain] = (result: result, expires: .now() + Self.cacheTTL)\n        return result\n    }\n}\n\nprivate struct _OCSPRequester: OCSPRequester {\n    let httpClient: HTTPClient\n\n    func query(request: [UInt8], uri: String) async -> OCSPRequesterQueryResult {\n        guard let url = URL(string: uri), let host = url.host else {\n            return .terminalError(SwiftOCSPRequesterError.invalidURL(uri))\n        }\n\n        do {\n            let response = try await self.httpClient.post(\n                url,\n                body: Data(request),\n                headers: [\n                    \"Content-Type\": \"application/ocsp-request\",\n                    \"Host\": host,\n                ]\n            )\n\n            guard response.statusCode == 200 else {\n                throw SwiftOCSPRequesterError.invalidResponse(statusCode: response.statusCode)\n            }\n            guard let responseBody = response.body else {\n                throw SwiftOCSPRequesterError.emptyResponse\n            }\n            return .response(Array(responseBody))\n        } catch {\n            return .nonTerminalError(error)\n        }\n    }\n}\n\nenum SwiftOCSPRequesterError: Error {\n    case invalidURL(String)\n    case emptyResponse\n    case invalidResponse(statusCode: Int)\n}\n\n/// Policy for matching subject name.\nstruct _SubjectNamePolicy: VerifierPolicy {\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []\n\n    let expectedUserID: String?\n    let expectedOrganizationalUnit: String?\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        if let expectedUserID {\n            let userID = chain.leaf.subject.userID\n            guard userID == expectedUserID else {\n                return .failsToMeetPolicy(\n                    reason: \"Subject user ID '\\(String(describing: userID))' does not match expected '\\(expectedUserID)'\"\n                )\n            }\n        }\n\n        if let expectedOrganizationalUnit {\n            let organizationUnit = chain.leaf.subject.organizationalUnitName\n            guard organizationUnit == expectedOrganizationalUnit else {\n                return .failsToMeetPolicy(\n                    reason: \"Subject organizational unit name '\\(String(describing: organizationUnit))' does not match expected '\\(expectedOrganizationalUnit)'\"\n                )\n            }\n        }\n\n        return .meetsPolicy\n    }\n}\n\n/// Policy for ADP certificates.\nstruct _ADPCertificatePolicy: VerifierPolicy {\n    /// Include custom marker extensions (which can be critical) so they would not\n    /// be considered unhandled and cause certificate chain validation to fail.\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] =\n        ASN1ObjectIdentifier.NameAttributes.adpAppleDevelopmentMarkers // included for testing\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        // Not policing anything here. This policy is mainly for\n        // listing marker extensions to prevent chain validation\n        // from failing prematurely.\n        .meetsPolicy\n    }\n}\n\n/// Policy for ADP Swift Package (Collection) certificates.\nstruct _ADPSwiftPackageCertificatePolicy: VerifierPolicy {\n    /// Include custom marker extensions (which can be critical) so they would not\n    /// be considered unhandled and cause certificate chain validation to fail.\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = [\n        ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageCollectionMarker,\n        ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageMarker,\n    ]\n\n    // developer.apple.com cert chain is always 3-long\n    private static let expectedCertChainLength = 3\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        guard chain.count == Self.expectedCertChainLength else {\n            return .failsToMeetPolicy(\n                reason: \"Certificate chain should have length \\(Self.expectedCertChainLength) but it's \\(chain.count)\"\n            )\n        }\n\n        // Package collection can be signed with \"Swift Package Collection\"\n        // or \"Swift Package\" certificate\n        guard chain.leaf.hasExtension(oid: ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageCollectionMarker)\n            || chain.leaf.hasExtension(oid: ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageMarker)\n        else {\n            return .failsToMeetPolicy(reason: \"Leaf certificate missing marker OID\")\n        }\n\n        for marker in ASN1ObjectIdentifier.NameAttributes.wwdrIntermediateMarkers {\n            if chain[1].hasExtension(oid: marker) {\n                return .meetsPolicy\n            }\n        }\n        return .failsToMeetPolicy(reason: \"Intermediate missing marker OID\")\n    }\n}\n\n/// Policy for ADP Apple Distribution certificates.\nstruct _ADPAppleDistributionCertificatePolicy: VerifierPolicy {\n    /// Include custom marker extensions (which can be critical) so they would not\n    /// be considered unhandled and cause certificate chain validation to fail.\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] =\n        ASN1ObjectIdentifier.NameAttributes.adpAppleDistributionMarkers\n\n    // developer.apple.com cert chain is always 3-long\n    private static let expectedCertChainLength = 3\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        guard chain.count == Self.expectedCertChainLength else {\n            return .failsToMeetPolicy(\n                reason: \"Certificate chain should have length \\(Self.expectedCertChainLength) but it's \\(chain.count)\"\n            )\n        }\n\n        var hasMarker = false\n        for marker in ASN1ObjectIdentifier.NameAttributes.adpAppleDistributionMarkers {\n            if chain.leaf.hasExtension(oid: marker) {\n                hasMarker = true\n                break\n            }\n        }\n        guard hasMarker else {\n            return .failsToMeetPolicy(reason: \"Leaf certificate missing marker OID\")\n        }\n\n        for marker in ASN1ObjectIdentifier.NameAttributes.wwdrIntermediateMarkers {\n            if chain[1].hasExtension(oid: marker) {\n                return .meetsPolicy\n            }\n        }\n        return .failsToMeetPolicy(reason: \"Intermediate missing marker OID\")\n    }\n}\n\n// MARK: - Default trust store\n\nenum Certificates {\n    static let appleRootsRaw = [\n        PackageResources.AppleComputerRootCertificate_cer,\n        PackageResources.AppleIncRootCertificate_cer,\n        PackageResources.AppleRootCA_G2_cer,\n        PackageResources.AppleRootCA_G3_cer,\n    ]\n\n    static let appleRoots = Self.appleRootsRaw.compactMap {\n        try? Certificate(derEncoded: $0)\n    }\n}\n\nenum CertificateStores {\n    static let defaultTrustRoots = Certificates.appleRoots\n}\n\n// MARK: - Utils\n\nextension CertificatePolicy {\n    fileprivate static func loadCerts(at directory: URL, observabilityScope: ObservabilityScope) -> [Certificate] {\n        var certs = [Certificate]()\n        if let enumerator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: nil) {\n            for case let fileURL as URL in enumerator {\n                do {\n                    let certData = try Data(contentsOf: fileURL)\n                    certs.append(try Certificate(derEncoded: Array(certData)))\n                } catch {\n                    observabilityScope.emit(\n                        warning: \"The certificate \\(fileURL) is invalid\",\n                        underlyingError: error\n                    )\n                }\n            }\n        }\n        return certs\n    }\n}\n\nextension HTTPClient {\n    fileprivate static func makeDefault() -> HTTPClient {\n        var httpClientConfig = HTTPClientConfiguration()\n        httpClientConfig.requestTimeout = .seconds(1)\n        return HTTPClient(configuration: httpClientConfig)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsSigning/PackageCollectionSigning.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\nimport Basics\nimport Dispatch\nimport Foundation\nimport PackageCollectionsModel\nimport SwiftASN1\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import _CryptoExtras\n@_implementationOnly import Crypto\n@_implementationOnly import X509\n#else\nimport _CryptoExtras\nimport Crypto\nimport X509\n#endif\n\npublic protocol PackageCollectionSigner {\n    /// Signs package collection using the given certificate and key.\n    ///\n    /// - Parameters:\n    ///   - collection: The package collection to be signed\n    ///   - certChainPaths: Paths to all DER-encoded certificates in the chain. The certificate used for signing\n    ///                     must be the first in the array.\n    ///   - privateKeyPEM: Data of the private key (*.pem) of the certificate\n    ///   - certPolicyKey: The key of the `CertificatePolicy` to use for validating certificates\n    func sign(\n        collection: PackageCollectionModel.V1.Collection,\n        certChainPaths: [URL],\n        privateKeyPEM: Data,\n        certPolicyKey: CertificatePolicyKey\n    ) async throws -> PackageCollectionModel.V1.SignedCollection\n}\n\nextension PackageCollectionSigner {\n    /// Signs package collection using the given certificate and key.\n    ///\n    /// - Parameters:\n    ///   - collection: The package collection to be signed\n    ///   - certChainPaths: Paths to all DER-encoded certificates in the chain. The certificate used for signing\n    ///                     must be the first in the array.\n    ///   - certPrivateKeyPath: Path to the private key (*.pem) of the certificate\n    ///   - certPolicyKey: The key of the `CertificatePolicy` to use for validating certificates\n    public func sign(\n        collection: PackageCollectionModel.V1.Collection,\n        certChainPaths: [URL],\n        certPrivateKeyPath: URL,\n        certPolicyKey: CertificatePolicyKey = .default\n    ) async throws -> PackageCollectionModel.V1.SignedCollection {\n        let privateKey = try Data(contentsOf: certPrivateKeyPath)\n        return try await self.sign(\n            collection: collection,\n            certChainPaths: certChainPaths,\n            privateKeyPEM: privateKey,\n            certPolicyKey: certPolicyKey\n        )\n    }\n}\n\npublic protocol PackageCollectionSignatureValidator {\n    /// Validates a signed package collection.\n    ///\n    /// - Parameters:\n    ///   - signedCollection: The signed package collection\n    ///   - certPolicyKey: The key of the `CertificatePolicy` to use for validating certificates\n    func validate(\n        signedCollection: PackageCollectionModel.V1.SignedCollection,\n        certPolicyKey: CertificatePolicyKey\n    ) async throws\n}\n\n// MARK: - Implementation\n\npublic actor PackageCollectionSigning: PackageCollectionSigner, PackageCollectionSignatureValidator {\n    public typealias Model = PackageCollectionModel.V1\n\n    private static let minimumRSAKeySizeInBits = 2048\n\n    /// URL of the optional directory containing root certificates to be trusted.\n    private let trustedRootCertsDir: URL?\n    /// Root certificates to be trusted in additional to those found in `trustedRootCertsDir`\n    private let additionalTrustedRootCerts: [Certificate]?\n\n    /// Internal cache/storage of `CertificatePolicy`s\n    private let certPolicies: [CertificatePolicyKey: CertificatePolicy]\n\n    private let encoder: JSONEncoder\n    private let decoder: JSONDecoder\n\n    private let observabilityScope: ObservabilityScope\n\n    public init(\n        trustedRootCertsDir: URL? = nil,\n        additionalTrustedRootCerts: [String]? = nil,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.trustedRootCertsDir = trustedRootCertsDir\n        self.additionalTrustedRootCerts = additionalTrustedRootCerts.map { $0.compactMap {\n            guard let data = Data(base64Encoded: $0) else {\n                observabilityScope.emit(error: \"The certificate \\($0) is not in valid base64 encoding\")\n                return nil\n            }\n            do {\n                return try Certificate(derEncoded: Array(data))\n            } catch {\n                observabilityScope.emit(\n                    error: \"The certificate \\($0) is not in valid DER format\",\n                    underlyingError: error\n                )\n                return nil\n            }\n        } }\n\n        self.certPolicies = [:]\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n        self.observabilityScope = observabilityScope\n    }\n\n    init(certPolicy: CertificatePolicy, observabilityScope: ObservabilityScope) {\n        // These should be set through the given CertificatePolicy\n        self.trustedRootCertsDir = nil\n        self.additionalTrustedRootCerts = nil\n\n        self.certPolicies = [CertificatePolicyKey.custom: certPolicy]\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n        self.observabilityScope = observabilityScope\n    }\n\n    private func getCertificatePolicy(key: CertificatePolicyKey) throws -> CertificatePolicy {\n        switch key {\n        case .default(let subjectUserID, let subjectOrganizationalUnit):\n            // Create new instance each time since contents of trustedRootCertsDir might change\n            return DefaultCertificatePolicy(\n                trustedRootCertsDir: self.trustedRootCertsDir,\n                additionalTrustedRootCerts: self.additionalTrustedRootCerts,\n                expectedSubjectUserID: subjectUserID,\n                expectedSubjectOrganizationalUnit: subjectOrganizationalUnit,\n                observabilityScope: self.observabilityScope\n            )\n        case .appleSwiftPackageCollection(let subjectUserID, let subjectOrganizationalUnit):\n            // Create new instance each time since contents of trustedRootCertsDir might change\n            return ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: self.trustedRootCertsDir,\n                additionalTrustedRootCerts: self.additionalTrustedRootCerts,\n                expectedSubjectUserID: subjectUserID,\n                expectedSubjectOrganizationalUnit: subjectOrganizationalUnit,\n                observabilityScope: self.observabilityScope\n            )\n        case .appleDistribution(let subjectUserID, let subjectOrganizationalUnit):\n            // Create new instance each time since contents of trustedRootCertsDir might change\n            return ADPAppleDistributionCertificatePolicy(\n                trustedRootCertsDir: self.trustedRootCertsDir,\n                additionalTrustedRootCerts: self.additionalTrustedRootCerts,\n                expectedSubjectUserID: subjectUserID,\n                expectedSubjectOrganizationalUnit: subjectOrganizationalUnit,\n                observabilityScope: self.observabilityScope\n            )\n        case .custom:\n            // Custom `CertificatePolicy` can be set using the internal initializer only\n            guard let certPolicy = self.certPolicies[key] else {\n                throw PackageCollectionSigningError.certPolicyNotFound\n            }\n            return certPolicy\n        }\n    }\n\n    public func sign(\n        collection: Model.Collection,\n        certChainPaths: [URL],\n        privateKeyPEM: Data,\n        certPolicyKey: CertificatePolicyKey = .default\n    ) async throws -> Model.SignedCollection {\n        let certChainData = try certChainPaths.map { try Data(contentsOf: $0) }\n        // Check that the certificate is valid\n        let certChain = try await self.validateCertChain(certChainData, certPolicyKey: certPolicyKey)\n\n        let privateKeyPEMString = String(decoding: privateKeyPEM, as: UTF8.self)\n\n        let signatureAlgorithm: Signature.Algorithm\n        let signatureProvider: (Data) throws -> Data\n        // Determine key type\n        do {\n            let privateKey = try P256.Signing.PrivateKey(pemRepresentation: privateKeyPEMString)\n            signatureAlgorithm = .ES256\n            signatureProvider = {\n                try privateKey.signature(for: SHA256.hash(data: $0)).rawRepresentation\n            }\n        } catch {\n            do {\n                let privateKey = try _RSA.Signing.PrivateKey(pemRepresentation: privateKeyPEMString)\n\n                guard privateKey.keySizeInBits >= Self.minimumRSAKeySizeInBits else {\n                    throw PackageCollectionSigningError\n                        .invalidKeySize(minimumBits: Self.minimumRSAKeySizeInBits)\n                }\n\n                signatureAlgorithm = .RS256\n                signatureProvider = {\n                    try privateKey.signature(for: SHA256.hash(data: $0), padding: Signature.rsaSigningPadding)\n                        .rawRepresentation\n                }\n            } catch let error as PackageCollectionSigningError {\n                throw error\n            } catch {\n                throw PackageCollectionSigningError.unsupportedKeyType\n            }\n        }\n\n        // Generate signature\n        let signatureData = try Signature.generate(\n            payload: collection,\n            certChainData: certChainData,\n            jsonEncoder: self.encoder,\n            signatureAlgorithm: signatureAlgorithm,\n            signatureProvider: signatureProvider\n        )\n\n        guard let signature = String(bytes: signatureData, encoding: .utf8) else {\n            throw PackageCollectionSigningError.invalidSignature\n        }\n\n        let certificate = certChain.first! // !-safe because certChain cannot be empty at this point\n        let collectionSignature = Model.Signature(\n            signature: signature,\n            certificate: Model.Signature.Certificate(\n                subject: Model.Signature.Certificate.Name(from: certificate.subject),\n                issuer: Model.Signature.Certificate.Name(from: certificate.issuer)\n            )\n        )\n        return Model.SignedCollection(collection: collection, signature: collectionSignature)\n    }\n\n    public func validate(\n        signedCollection: Model.SignedCollection,\n        certPolicyKey: CertificatePolicyKey = .default\n    ) async throws {\n        let signatureBytes = Data(signedCollection.signature.signature.utf8).copyBytes()\n\n        // Parse the signature\n        let certChainValidate = { certChainData in\n            try await self.validateCertChain(certChainData, certPolicyKey: certPolicyKey)\n        }\n        let signature = try await Signature.parse(\n            signatureBytes,\n            certChainValidate: certChainValidate,\n            jsonDecoder: self.decoder\n        )\n\n        // Verify the collection embedded in the signature is the same as received\n        // i.e., the signature is associated with the given collection and not another\n        guard let collectionFromSignature = try? self.decoder.decode(\n            Model.Collection.self,\n            from: signature.payload\n        ),\n            signedCollection.collection == collectionFromSignature\n        else {\n            throw PackageCollectionSigningError.invalidSignature\n        }\n    }\n\n    private func validateCertChain(\n        _ certChainData: [Data],\n        certPolicyKey: CertificatePolicyKey\n    ) async throws -> [Certificate] {\n        guard !certChainData.isEmpty else {\n            throw PackageCollectionSigningError.emptyCertChain\n        }\n\n        do {\n            let certChain = try certChainData.map { try Certificate(derEncoded: Array($0)) }\n            let certPolicy = try self.getCertificatePolicy(key: certPolicyKey)\n\n            do {\n                try await certPolicy.validate(certChain: certChain)\n                return certChain\n            } catch {\n                self.observabilityScope.emit(\n                    error: \"\\(certPolicyKey): The certificate chain is invalid\",\n                    underlyingError: error\n                )\n\n                if CertificatePolicyError.noTrustedRootCertsConfigured == error as? CertificatePolicyError {\n                    throw PackageCollectionSigningError.noTrustedRootCertsConfigured\n                } else {\n                    throw PackageCollectionSigningError.invalidCertChain\n                }\n            }\n        } catch let error as PackageCollectionSigningError {\n            throw error\n        } catch {\n            self.observabilityScope.emit(\n                error: \"An error has occurred while validating certificate chain\",\n                underlyingError: error\n            )\n            throw PackageCollectionSigningError.invalidCertChain\n        }\n    }\n}\n\npublic enum PackageCollectionSigningError: Error, Equatable {\n    case certPolicyNotFound\n    case emptyCertChain\n    case noTrustedRootCertsConfigured\n    case invalidCertChain\n\n    case invalidSignature\n\n    case unsupportedKeyType\n    case invalidKeySize(minimumBits: Int)\n}\n\nextension PackageCollectionModel.V1.Signature.Certificate.Name {\n    fileprivate init(from name: DistinguishedName) {\n        self.init(\n            userID: name.userID,\n            commonName: name.commonName,\n            organizationalUnit: name.organizationalUnitName,\n            organization: name.organizationName\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsSigning/Signature.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Vapor open source project\n//\n// Copyright (c) 2017-2020 Vapor project authors\n// Licensed under MIT\n//\n// See LICENSE for license information\n//\n// SPDX-License-Identifier: MIT\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import _CryptoExtras\n@_implementationOnly import Crypto\n@_implementationOnly import X509\n#else\nimport _CryptoExtras\nimport Crypto\nimport X509\n#endif\n\n// The logic in this source file loosely follows https://www.rfc-editor.org/rfc/rfc7515.html\n// for JSON Web Signature (JWS).\n\nstruct Signature {\n    let header: Header\n    let payload: Data\n    let signature: Data\n}\n\nextension Signature {\n    enum Algorithm: String, Codable {\n        case RS256 // RSASSA-PKCS1-v1_5 using SHA-256\n        case ES256 // ECDSA using P-256 and SHA-256\n    }\n\n    struct Header: Equatable, Codable {\n        // https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.1\n        let algorithm: Algorithm\n\n        /// Base64 encoded certificate chain\n        let certChain: [String]\n\n        enum CodingKeys: String, CodingKey {\n            case algorithm = \"alg\"\n            case certChain = \"x5c\"\n        }\n    }\n}\n\n// Reference: https://github.com/vapor/jwt-kit/blob/main/Sources/JWTKit/JWTSerializer.swift\nextension Signature {\n    static let rsaSigningPadding = _RSA.Signing.Padding.insecurePKCS1v1_5\n\n    static func generate(\n        payload: some Encodable,\n        certChainData: [Data],\n        jsonEncoder: JSONEncoder,\n        signatureAlgorithm: Signature.Algorithm,\n        signatureProvider: @escaping (Data) throws -> Data\n    ) throws -> Data {\n        let header = Signature.Header(\n            algorithm: signatureAlgorithm,\n            certChain: certChainData.map { $0.base64EncodedString() }\n        )\n        let headerData = try jsonEncoder.encode(header)\n        let encodedHeader = headerData.base64URLEncodedBytes()\n\n        let payloadData = try jsonEncoder.encode(payload)\n        let encodedPayload = payloadData.base64URLEncodedBytes()\n\n        // https://www.rfc-editor.org/rfc/rfc7515.html#section-5.1\n        // Signing input: BASE64URL(header) + '.' + BASE64URL(payload)\n        let signatureData = try signatureProvider(encodedHeader + .period + encodedPayload)\n        let encodedSignature = signatureData.base64URLEncodedBytes()\n\n        // Result: header.payload.signature\n        let bytes = encodedHeader\n            + .period\n            + encodedPayload\n            + .period\n            + encodedSignature\n        return bytes\n    }\n}\n\n// Reference: https://github.com/vapor/jwt-kit/blob/main/Sources/JWTKit/JWTParser.swift\nextension Signature {\n    typealias CertChainValidate = ([Data]) async throws -> [Certificate]\n\n    static func parse(\n        _ signature: String,\n        certChainValidate: CertChainValidate,\n        jsonDecoder: JSONDecoder\n    ) async throws -> Signature {\n        let bytes = Array(signature.utf8)\n        return try await Self.parse(bytes, certChainValidate: certChainValidate, jsonDecoder: jsonDecoder)\n    }\n\n    static func parse(\n        _ signature: some DataProtocol,\n        certChainValidate: CertChainValidate,\n        jsonDecoder: JSONDecoder\n    ) async throws -> Signature {\n        let parts = signature.copyBytes().split(separator: .period)\n        guard parts.count == 3 else {\n            throw SignatureError.malformedSignature\n        }\n\n        let encodedHeader = parts[0]\n        let encodedPayload = parts[1]\n        let encodedSignature = parts[2]\n\n        guard let headerBytes = encodedHeader.base64URLDecodedBytes(),\n              let header = try? jsonDecoder.decode(Header.self, from: headerBytes)\n        else {\n            throw SignatureError.malformedSignature\n        }\n\n        // Signature header contains the certificate and public key for verification\n        let certChainData = header.certChain.compactMap { Data(base64Encoded: $0) }\n        // Make sure we restore all certs successfully\n        guard certChainData.count == header.certChain.count else {\n            throw SignatureError.malformedSignature\n        }\n\n        let certChain = try await certChainValidate(certChainData)\n\n        guard let payloadBytes = encodedPayload.base64URLDecodedBytes(),\n              let signatureBytes = encodedSignature.base64URLDecodedBytes()\n        else {\n            throw SignatureError.malformedSignature\n        }\n\n        // Extract public key from the certificate\n        let certificate = certChain.first! // !-safe because certChain is not empty at this point\n        // Verify the key was used to generate the signature\n        let message = Data(encodedHeader) + .period + Data(encodedPayload)\n        let digest = SHA256.hash(data: message)\n\n        switch header.algorithm {\n        case .ES256:\n            guard let publicKey = P256.Signing.PublicKey(certificate.publicKey) else {\n                throw SignatureError.invalidPublicKey\n            }\n            guard try publicKey.isValidSignature(.init(rawRepresentation: signatureBytes), for: digest)\n            else {\n                throw SignatureError.invalidSignature\n            }\n        case .RS256:\n            guard let publicKey = _RSA.Signing.PublicKey(certificate.publicKey) else {\n                throw SignatureError.invalidPublicKey\n            }\n            guard publicKey.isValidSignature(\n                .init(rawRepresentation: signatureBytes),\n                for: digest,\n                padding: .insecurePKCS1v1_5\n            ) else {\n                throw SignatureError.invalidSignature\n            }\n        }\n\n        return Signature(header: header, payload: payloadBytes, signature: signatureBytes)\n    }\n}\n\nenum SignatureError: Error {\n    case malformedSignature\n    case invalidSignature\n    case invalidPublicKey\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsSigning/Utilities/Base64URL.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Vapor open source project\n//\n// Copyright (c) 2017-2020 Vapor project authors\n// Licensed under MIT\n//\n// See LICENSE for license information\n//\n// SPDX-License-Identifier: MIT\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n// Source: https://github.com/vapor/jwt-kit/blob/main/Sources/JWTKit/Utilities/Base64URL.swift\n\nextension DataProtocol {\n    func base64URLDecodedBytes() -> Data? {\n        var data = Data(self)\n        data.base64URLUnescape()\n        return Data(base64Encoded: data)\n    }\n\n    func base64URLEncodedBytes() -> Data {\n        var data = Data(self).base64EncodedData()\n        data.base64URLEscape()\n        return data\n    }\n}\n\nextension Data {\n    /// Converts base64-url encoded data to a base64 encoded data.\n    ///\n    /// https://tools.ietf.org/html/rfc4648#page-7\n    mutating func base64URLUnescape() {\n        for i in 0 ..< self.count {\n            switch self[i] {\n            case 0x2D: self[self.index(self.startIndex, offsetBy: i)] = 0x2B\n            case 0x5F: self[self.index(self.startIndex, offsetBy: i)] = 0x2F\n            default: break\n            }\n        }\n        /// https://stackoverflow.com/questions/43499651/decode-base64url-to-base64-swift\n        let padding = count % 4\n        if padding > 0 {\n            self += Data(repeating: 0x3D, count: 4 - padding)\n        }\n    }\n\n    /// Converts base64 encoded data to a base64-url encoded data.\n    ///\n    /// https://tools.ietf.org/html/rfc4648#page-7\n    mutating func base64URLEscape() {\n        for i in 0 ..< self.count {\n            switch self[i] {\n            case 0x2B: self[self.index(self.startIndex, offsetBy: i)] = 0x2D\n            case 0x2F: self[self.index(self.startIndex, offsetBy: i)] = 0x5F\n            default: break\n            }\n        }\n        self = split(separator: 0x3D).first ?? .init()\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsSigning/Utilities/Utilities.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension DataProtocol {\n    func copyBytes() -> [UInt8] {\n        [UInt8](unsafeUninitializedCapacity: self.count) { buffer, initializedCount in\n            self.copyBytes(to: buffer)\n            initializedCount = self.count\n        }\n    }\n}\n\nextension UInt8 {\n    static var period: UInt8 {\n        UInt8(ascii: \".\")\n    }\n}\n\n/// Cannot use `extension Data` if `period` is going to be used with\n/// `+` operator via leading-dot syntax, for example: `Data(...) + .period`\n/// because `+` is declared as `(Self, Other) -> Self` where\n/// `Other: RangeReplaceableCollection, Other.Element == Self.Element`\n/// which means that `.period` couldn't get `Data` inferred from the first argument.\nextension RangeReplaceableCollection where Self == Data {\n    static var period: Data {\n        Data([UInt8.period])\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsSigning/X509Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftASN1\n@_implementationOnly import X509\n#else\nimport SwiftASN1\nimport X509\n#endif\n\nextension Certificate {\n    func hasExtension(oid: ASN1ObjectIdentifier) -> Bool {\n        self.extensions[oid: oid] != nil\n    }\n}\n\nextension ASN1ObjectIdentifier.NameAttributes {\n    static let userID: ASN1ObjectIdentifier = [0, 9, 2342, 19_200_300, 100, 1, 1]\n\n    // Marker OIDs for ADP certificates\n    static let adpSwiftPackageMarker: ASN1ObjectIdentifier = [1, 2, 840, 113_635, 100, 6, 1, 35]\n    static let adpSwiftPackageCollectionMarker: ASN1ObjectIdentifier = [1, 2, 840, 113_635, 100, 6, 1, 35]\n    static let adpAppleDevelopmentMarkers: [ASN1ObjectIdentifier] = [\n        [1, 2, 840, 113_635, 100, 6, 1, 2],\n        [1, 2, 840, 113_635, 100, 6, 1, 12],\n    ]\n    static let adpAppleDistributionMarkers: [ASN1ObjectIdentifier] = [\n        [1, 2, 840, 113_635, 100, 6, 1, 4],\n        [1, 2, 840, 113_635, 100, 6, 1, 7],\n    ]\n    static let wwdrIntermediateMarkers: [ASN1ObjectIdentifier] = [\n        [1, 2, 840, 113_635, 100, 6, 2, 1],\n        [1, 2, 840, 113_635, 100, 6, 2, 15],\n    ]\n}\n\nextension DistinguishedName {\n    var userID: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.userID)\n    }\n\n    var commonName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.commonName)\n    }\n\n    var organizationalUnitName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.organizationalUnitName)\n    }\n\n    var organizationName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.organizationName)\n    }\n\n    private func stringAttribute(oid: ASN1ObjectIdentifier) -> String? {\n        for relativeDistinguishedName in self {\n            for attribute in relativeDistinguishedName where attribute.type == oid {\n                return attribute.value.description\n            }\n        }\n        return nil\n    }\n}\n"
  },
  {
    "path": "Sources/PackageCollectionsSigning/embedded_resources.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct PackageResources {\nstatic let AppleWWDRCAG2_cer: [UInt8] = [48,130,2,247,48,130,2,124,160,3,2,1,2,2,8,111,239,216,245,233,163,167,238,48,10,6,8,42,134,72,206,61,4,3,2,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,53,48,54,50,51,52,51,50,52,90,23,13,50,57,48,53,48,54,50,51,52,51,50,52,90,48,129,128,49,52,48,50,6,3,85,4,3,12,43,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,221,240,183,6,75,207,221,115,4,19,196,67,137,3,147,128,251,94,246,116,173,66,97,82,88,2,38,83,25,200,99,34,7,9,82,97,202,196,217,87,239,109,38,104,139,116,145,140,196,249,128,104,40,252,9,104,240,16,218,233,208,46,201,26,163,129,247,48,129,244,48,70,6,8,43,6,1,5,5,7,1,1,4,58,48,56,48,54,6,8,43,6,1,5,5,7,48,1,134,42,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,52,45,97,112,112,108,101,114,111,111,116,99,97,103,51,48,29,6,3,85,29,14,4,22,4,20,132,182,132,204,58,134,98,114,22,89,148,232,26,163,189,72,223,58,223,11,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,31,6,3,85,29,35,4,24,48,22,128,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,55,6,3,85,29,31,4,48,48,46,48,44,160,42,160,40,134,38,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,114,111,111,116,99,97,103,51,46,99,114,108,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,15,4,2,5,0,48,10,6,8,42,134,72,206,61,4,3,2,3,105,0,48,102,2,49,0,217,177,199,49,198,35,246,79,77,208,217,71,197,125,24,105,17,135,113,39,211,104,173,224,155,101,154,190,108,223,63,70,166,144,9,190,110,161,59,44,176,81,137,65,60,135,210,191,2,49,0,252,100,82,137,75,60,93,191,107,28,194,137,152,47,114,174,181,155,170,26,11,35,84,119,84,232,21,67,162,197,18,218,151,80,115,124,94,208,110,178,92,98,80,215,81,241,58,90]\nstatic let AppleWWDRCAG3_cer: [UInt8] = [48,130,4,81,48,130,3,57,160,3,2,1,2,2,16,124,175,105,10,37,183,57,254,123,155,68,122,193,120,197,238,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,48,50,49,57,49,56,49,51,52,55,90,23,13,51,48,48,50,50,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,51,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,216,245,137,252,168,89,11,135,199,76,145,46,45,86,144,211,120,29,164,48,233,165,72,239,11,67,191,45,132,251,36,93,69,27,229,235,89,54,18,92,84,100,158,108,98,45,180,198,151,202,204,60,246,214,6,145,252,229,2,166,28,106,180,121,213,103,203,172,233,63,7,17,225,132,188,71,29,102,142,57,162,232,180,73,237,58,210,225,16,96,122,142,147,140,202,192,218,12,192,131,208,227,249,145,214,167,140,200,193,115,226,174,70,209,98,157,146,168,144,96,55,125,104,150,205,141,224,252,155,250,120,187,227,123,175,45,23,221,91,254,128,89,35,117,23,184,18,193,237,27,229,52,206,254,34,181,158,73,176,229,85,191,143,132,162,60,168,186,197,134,149,22,228,0,201,159,3,208,204,179,58,22,123,214,5,92,157,235,71,174,13,181,45,140,14,105,77,64,208,75,76,59,4,158,141,33,177,172,46,67,84,48,206,193,138,134,148,152,75,223,106,13,63,254,251,28,174,151,23,194,120,10,48,224,95,31,84,59,73,183,37,0,26,55,130,210,86,151,165,82,73,124,96,56,155,239,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,9,254,192,21,144,249,175,100,10,146,18,185,38,40,99,12,151,236,167,178,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,173,101,19,232,246,224,129,119,68,2,71,66,190,95,165,57,32,234,98,169,253,197,144,201,115,19,213,158,155,208,170,15,141,141,203,237,1,207,108,40,64,91,199,85,36,65,248,252,207,193,181,35,233,220,236,241,111,202,128,29,119,194,196,97,73,37,103,175,15,202,57,37,173,211,227,122,204,51,40,13,14,46,161,87,64,115,250,230,92,174,6,81,41,237,227,133,12,79,97,220,50,22,139,119,208,68,202,93,114,3,49,70,156,174,155,64,26,250,244,224,211,62,250,47,140,102,159,151,196,84,89,239,210,72,244,7,153,73,96,89,25,199,221,148,209,192,193,108,127,120,33,239,12,235,59,108,153,130,75,82,96,56,181,57,130,109,236,82,49,83,190,15,145,76,73,73,116,143,166,81,203,132,71,78,29,117,39,110,189,249,210,92,243,127,194,108,11,9,54,226,100,228,194,55,3,20,25,213,234,106,148,170,169,219,254,246,154,8,103,139,239,43,184,170,23,73,131,175,207,203,188,233,207,234,149,113,176,180,69,162,204,229,135,170,10,195,65,58,121,92,218,80,52,157,149,59]\nstatic let AppleWWDRCAG5_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,59,126,128,10,238,211,2,161,230,236,219,151,217,202,172,40,156,241,105,148,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,49,50,49,54,49,57,51,56,53,54,90,23,13,51,48,49,50,49,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,53,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,159,93,218,31,251,250,188,208,75,34,60,199,214,38,250,23,247,244,159,30,62,100,17,102,154,239,94,190,171,52,189,170,44,33,110,214,30,148,33,133,44,116,193,14,16,97,170,60,99,74,126,74,227,200,117,214,207,194,156,8,72,123,106,185,41,177,201,102,253,200,138,22,209,178,4,60,130,186,128,108,226,255,10,114,235,172,254,59,111,72,190,158,139,17,77,149,125,178,123,144,47,2,28,78,252,73,190,215,111,181,79,190,120,198,218,222,178,205,201,217,102,17,59,90,233,9,69,115,137,80,212,78,226,104,5,126,218,117,156,75,1,174,218,227,207,109,116,77,222,83,208,213,26,56,130,58,208,157,227,93,41,123,177,129,234,41,39,11,251,96,124,134,18,251,240,98,79,6,231,76,209,31,217,109,158,237,115,218,120,33,13,157,112,217,70,87,144,95,103,132,193,115,119,10,168,98,98,182,174,112,134,187,117,35,137,173,121,246,230,164,212,253,131,38,50,10,59,36,146,91,32,161,156,209,47,128,24,155,221,60,11,231,181,253,236,128,87,15,23,158,63,43,135,39,187,247,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,25,139,151,141,74,91,97,120,87,244,165,92,53,18,138,57,8,227,176,117,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,90,196,53,162,217,230,10,158,82,162,0,130,34,119,205,114,47,144,249,34,175,20,37,204,170,10,66,96,146,194,189,117,29,235,76,202,21,229,126,107,64,16,94,251,91,69,116,13,240,122,125,136,145,206,222,99,139,66,137,210,24,223,65,179,88,158,6,8,135,72,221,64,175,35,213,237,235,44,96,229,235,164,127,28,233,156,131,214,148,95,76,98,57,138,78,174,19,141,125,67,184,220,94,172,190,24,64,242,230,15,44,93,19,147,241,123,101,168,194,104,72,222,255,180,150,155,12,251,50,54,158,158,13,149,95,56,10,139,150,210,18,108,183,139,11,142,215,62,236,111,1,170,206,77,69,96,219,132,113,102,98,229,25,101,48,205,138,255,69,83,251,110,251,136,119,67,195,72,99,249,247,81,179,114,94,121,226,86,207,188,187,132,185,56,90,120,174,17,72,82,187,13,53,139,148,222,204,116,154,104,245,73,96,148,172,242,168,179,21,134,144,208,204,48,67,134,211,229,112,2,81,180,129,192,168,151,212,234,234,176,140,9,64,239,56,147,178,205,34,3,235,103,67,101,200,69]\nstatic let AppleRootCA_G2_cer: [UInt8] = [48,130,5,146,48,130,3,122,160,3,2,1,2,2,8,1,224,229,181,131,103,163,224,48,13,6,9,42,134,72,134,247,13,1,1,12,5,0,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,52,51,48,49,56,49,48,48,57,90,23,13,51,57,48,52,51,48,49,56,49,48,48,57,90,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,2,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,2,15,0,48,130,2,10,2,130,2,1,0,216,17,18,72,72,218,41,138,73,197,28,199,236,110,51,109,254,77,251,224,28,222,172,94,226,54,167,36,249,127,80,107,76,206,185,48,84,39,229,179,214,237,37,230,48,182,5,55,94,20,34,17,197,232,170,27,210,251,178,210,9,149,56,164,239,42,73,140,93,62,113,102,3,56,251,22,245,133,136,228,90,146,12,4,50,242,200,64,251,82,95,159,246,192,241,227,186,69,160,80,213,18,139,242,221,222,145,134,35,240,245,182,114,46,1,218,11,246,46,57,8,95,25,161,99,65,11,28,167,148,193,134,196,83,47,118,246,10,215,12,209,131,63,26,83,25,243,87,213,39,127,252,19,184,248,146,141,252,211,40,67,60,181,104,0,37,93,39,98,211,221,85,221,68,32,144,131,53,147,197,191,184,25,251,107,227,220,8,66,230,175,109,250,158,64,202,78,133,133,120,73,177,215,195,193,48,57,50,171,126,95,170,211,139,111,159,45,26,33,104,112,103,179,163,241,152,65,109,145,124,248,215,219,168,231,95,33,26,140,51,191,49,116,183,184,209,244,224,34,244,191,114,52,223,247,129,77,113,125,81,161,226,179,240,211,40,22,115,111,205,204,173,55,125,78,235,173,64,225,63,129,253,247,61,10,62,162,241,189,49,150,41,89,220,194,25,128,140,91,116,198,44,211,16,83,38,29,20,79,196,212,129,102,60,135,103,51,39,20,8,233,180,119,132,52,82,143,137,248,104,152,23,191,195,187,170,19,147,31,93,84,47,168,199,124,251,13,20,190,21,61,36,52,242,154,220,117,65,102,34,180,1,214,11,175,144,158,12,234,98,248,155,89,60,8,226,150,52,228,99,222,188,55,212,235,12,136,3,67,11,80,175,160,52,221,80,77,21,251,90,36,216,12,250,12,99,158,31,3,177,225,238,225,170,67,244,102,101,40,55,2,49,239,1,199,30,209,204,159,109,202,84,58,64,219,206,207,79,70,139,74,101,154,106,198,104,108,215,204,153,27,71,176,114,195,119,143,196,247,97,156,116,31,206,253,107,161,194,156,148,130,171,148,162,231,189,27,186,185,112,57,149,23,197,41,243,57,88,52,245,196,164,198,123,96,185,102,67,80,63,110,97,252,14,249,134,170,96,12,67,75,149,2,3,1,0,1,163,66,48,64,48,29,6,3,85,29,14,4,22,4,20,196,153,19,108,24,3,194,123,192,163,160,13,127,114,128,122,28,119,38,141,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,13,6,9,42,134,72,134,247,13,1,1,12,5,0,3,130,2,1,0,81,166,243,226,244,184,61,147,191,45,206,15,187,91,225,85,20,78,78,209,229,206,121,93,129,127,254,182,240,135,51,248,239,148,229,126,220,106,121,167,28,190,240,148,183,166,209,48,156,200,13,10,117,158,125,146,149,126,24,157,126,194,113,105,124,20,234,207,131,14,228,20,66,158,116,14,16,205,171,26,186,17,97,129,120,216,241,181,69,64,120,171,168,192,206,251,125,99,55,104,246,231,251,175,198,195,75,236,31,54,38,19,84,134,148,114,178,234,2,237,139,109,228,12,166,144,192,87,117,207,140,66,125,92,230,49,125,243,201,178,146,105,70,14,136,248,227,45,66,178,56,168,166,25,141,241,159,205,238,106,101,188,26,176,37,189,167,41,253,244,62,162,117,73,191,158,219,201,247,167,30,99,153,225,92,70,255,146,5,140,250,30,32,249,134,148,86,37,229,180,87,56,157,235,136,100,20,33,73,33,57,191,98,102,169,177,162,202,111,63,33,96,197,137,212,69,54,200,152,124,189,246,254,153,73,128,59,44,210,166,167,136,3,4,49,25,183,182,58,97,69,250,201,242,35,200,99,115,191,86,137,49,176,217,124,98,167,123,21,168,136,138,171,56,64,194,204,18,255,21,227,240,55,223,55,114,203,204,152,230,191,162,188,250,38,138,113,86,215,231,36,27,72,68,62,158,252,159,201,204,26,236,67,60,1,188,52,120,200,105,245,198,230,86,236,6,9,54,144,235,20,74,27,94,201,136,35,218,3,48,145,11,184,54,62,249,231,181,40,111,190,63,236,60,143,101,29,229,192,30,135,164,170,186,152,253,146,227,108,38,119,221,6,180,100,6,135,244,78,214,186,74,170,22,168,244,5,103,102,150,186,226,85,121,195,44,93,73,143,128,73,43,138,18,199,118,128,81,223,186,189,101,93,62,55,71,99,49,233,229,244,197,63,75,173,4,138,122,113,44,175,9,67,55,15,168,227,50,79,244,69,182,109,151,54,236,132,245,10,1,234,23,187,133,141,66,147,112,195,80,229,20,139,191,63,195,65,15,221,34,4,35,8,138,186,109,113,68,171,115,9,58,201,249,82,128,9,223,186,233,230,22,202,46,46,76,178,211,220,229,4,84,178,212,52,128,50,181,188,15,23,225]\nstatic let AppleComputerRootCertificate_cer: [UInt8] = [48,130,5,186,48,130,4,162,160,3,2,1,2,2,1,1,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,129,134,49,11,48,9,6,3,85,4,6,19,2,85,83,49,29,48,27,6,3,85,4,10,19,20,65,112,112,108,101,32,67,111,109,112,117,116,101,114,44,32,73,110,99,46,49,45,48,43,6,3,85,4,11,19,36,65,112,112,108,101,32,67,111,109,112,117,116,101,114,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,49,41,48,39,6,3,85,4,3,19,32,65,112,112,108,101,32,82,111,111,116,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,48,30,23,13,48,53,48,50,49,48,48,48,49,56,49,52,90,23,13,50,53,48,50,49,48,48,48,49,56,49,52,90,48,129,134,49,11,48,9,6,3,85,4,6,19,2,85,83,49,29,48,27,6,3,85,4,10,19,20,65,112,112,108,101,32,67,111,109,112,117,116,101,114,44,32,73,110,99,46,49,45,48,43,6,3,85,4,11,19,36,65,112,112,108,101,32,67,111,109,112,117,116,101,114,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,49,41,48,39,6,3,85,4,3,19,32,65,112,112,108,101,32,82,111,111,116,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,228,145,169,9,31,145,219,30,71,80,235,5,237,94,121,132,45,235,54,162,87,76,85,236,139,25,137,222,249,75,108,245,7,171,34,48,2,232,24,62,248,80,9,211,127,65,168,152,249,209,202,102,156,36,107,17,208,163,187,228,27,42,195,31,149,158,122,12,164,71,139,91,212,22,55,51,203,196,15,77,206,20,105,209,201,25,114,245,93,14,213,127,95,155,242,37,3,186,85,143,77,93,13,241,100,53,35,21,75,21,89,29,179,148,247,246,156,158,207,80,186,193,88,80,103,143,8,180,32,247,203,172,44,32,111,112,182,63,1,48,140,183,67,207,15,157,61,243,43,73,40,26,200,254,206,181,185,14,217,94,28,214,203,61,181,58,173,244,15,14,0,146,11,177,33,22,46,116,213,60,13,219,98,22,171,163,113,146,71,83,85,193,175,47,65,179,248,251,227,112,205,230,163,76,69,126,31,76,107,80,150,65,137,196,116,98,11,16,131,65,135,51,138,129,177,48,88,236,90,4,50,140,104,179,143,29,222,101,115,255,103,94,101,188,73,216,118,159,51,20,101,161,119,148,201,45,2,3,1,0,1,163,130,2,47,48,130,2,43,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,29,6,3,85,29,14,4,22,4,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,130,1,41,6,3,85,29,32,4,130,1,32,48,130,1,28,48,130,1,24,6,9,42,134,72,134,247,99,100,5,1,48,130,1,9,48,65,6,8,43,6,1,5,5,7,2,1,22,53,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,116,101,114,109,115,46,104,116,109,108,48,129,195,6,8,43,6,1,5,5,7,2,2,48,129,182,26,129,179,82,101,108,105,97,110,99,101,32,111,110,32,116,104,105,115,32,99,101,114,116,105,102,105,99,97,116,101,32,98,121,32,97,110,121,32,112,97,114,116,121,32,97,115,115,117,109,101,115,32,97,99,99,101,112,116,97,110,99,101,32,111,102,32,116,104,101,32,116,104,101,110,32,97,112,112,108,105,99,97,98,108,101,32,115,116,97,110,100,97,114,100,32,116,101,114,109,115,32,97,110,100,32,99,111,110,100,105,116,105,111,110,115,32,111,102,32,117,115,101,44,32,99,101,114,116,105,102,105,99,97,116,101,32,112,111,108,105,99,121,32,97,110,100,32,99,101,114,116,105,102,105,99,97,116,105,111,110,32,112,114,97,99,116,105,99,101,32,115,116,97,116,101,109,101,110,116,115,46,48,68,6,3,85,29,31,4,61,48,59,48,57,160,55,160,53,134,51,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,114,111,111,116,46,99,114,108,48,85,6,8,43,6,1,5,5,7,1,1,4,73,48,71,48,69,6,8,43,6,1,5,5,7,48,2,134,57,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,99,97,115,105,103,110,101,114,115,46,104,116,109,108,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,157,218,45,40,88,47,125,118,4,185,4,211,62,206,183,102,99,78,143,47,212,254,75,173,114,189,163,57,198,82,77,5,152,82,245,137,81,1,36,121,190,26,50,247,229,68,139,75,68,7,57,130,214,90,202,180,32,94,217,174,21,93,29,140,29,50,191,56,49,98,72,93,199,225,144,177,248,36,64,248,95,88,155,81,93,87,157,193,229,255,60,204,114,33,110,196,233,233,161,119,215,44,23,38,195,63,235,154,232,11,3,186,233,179,74,114,235,51,9,91,173,230,98,49,106,232,175,47,213,175,30,87,118,143,127,55,45,46,2,92,221,99,201,242,113,184,38,64,223,21,141,117,68,63,121,189,230,29,153,225,67,44,62,173,111,190,185,164,254,14,53,25,81,99,177,195,222,181,146,62,81,120,1,115,138,164,35,202,164,136,241,30,92,31,65,22,45,126,149,10,170,233,137,65,152,27,26,221,203,32,191,71,94,12,38,197,85,53,77,198,48,139,153,103,20,199,9,31,186,71,199,218,1,9,135,36,66,149,189,19,96,25,10,239,234,127,14,110,205,193,68,67,58,74,213,227]\nstatic let AppleWWDRCAG7_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,52,24,88,255,1,254,6,63,142,241,159,31,233,60,1,180,193,70,255,201,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,50,49,49,49,55,50,48,52,48,53,51,90,23,13,50,51,49,49,49,55,50,48,52,48,53,50,90,48,117,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,11,12,2,71,55,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,172,174,209,211,182,138,177,27,40,149,173,222,81,81,76,63,51,225,78,92,175,179,252,2,210,101,79,42,212,116,104,140,117,23,101,207,40,228,72,9,152,113,82,50,44,22,78,120,142,146,86,100,169,221,139,205,226,212,199,59,162,18,69,55,2,25,98,100,47,127,97,198,211,89,34,191,171,249,20,163,237,182,158,153,186,47,241,177,220,48,66,79,182,182,178,198,116,170,98,86,187,237,68,54,15,209,229,32,116,147,87,58,93,158,220,1,252,120,111,105,22,53,195,110,1,194,158,114,212,113,54,177,118,9,122,190,13,42,151,241,176,94,11,27,18,173,43,171,7,223,99,45,245,136,233,50,18,162,85,88,67,118,60,61,23,128,31,41,219,177,169,159,171,150,5,157,21,220,221,219,78,15,231,19,124,90,43,46,2,65,246,238,122,106,182,115,96,247,151,25,20,139,149,51,56,147,218,0,37,54,174,85,90,124,159,249,244,98,4,7,116,233,29,167,149,87,35,172,43,36,218,100,79,40,114,233,150,176,8,60,136,27,20,99,67,215,137,174,152,193,242,45,142,227,81,37,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,93,66,16,108,27,187,199,82,151,78,68,189,19,39,185,58,18,119,131,43,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,82,163,8,41,19,101,183,181,31,230,52,3,237,246,24,119,188,61,202,39,181,112,236,236,108,51,75,246,153,37,148,7,158,33,51,3,106,245,125,10,46,43,223,8,169,130,222,74,127,225,231,11,75,5,184,39,152,73,221,193,12,134,215,129,100,174,130,156,196,69,241,234,143,28,34,48,227,162,37,97,68,137,254,133,122,86,240,114,146,124,12,68,84,36,183,181,164,159,38,240,50,249,87,157,106,121,108,64,237,15,52,6,6,66,255,216,14,49,101,109,230,46,1,217,6,191,197,202,13,174,71,212,5,23,136,60,233,156,228,25,100,109,138,148,173,17,220,1,246,229,120,175,173,232,112,215,13,93,129,62,70,42,44,174,36,161,199,210,224,125,191,29,245,54,107,197,222,169,10,154,128,177,17,94,178,100,126,179,193,87,204,194,108,89,153,183,244,176,221,49,218,72,214,106,129,238,178,139,80,53,22,230,231,92,113,98,110,176,242,81,226,168,109,248,42,203,104,115,198,166,196,26,67,73,1,62,169,169,0,138,134,108,131,136,210,92,112,87,122,218,248,118,204,25,213,176]\nstatic let AppleIncRootCertificate_cer: [UInt8] = [48,130,4,187,48,130,3,163,160,3,2,1,2,2,1,2,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,48,54,48,52,50,53,50,49,52,48,51,54,90,23,13,51,53,48,50,48,57,50,49,52,48,51,54,90,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,228,145,169,9,31,145,219,30,71,80,235,5,237,94,121,132,45,235,54,162,87,76,85,236,139,25,137,222,249,75,108,245,7,171,34,48,2,232,24,62,248,80,9,211,127,65,168,152,249,209,202,102,156,36,107,17,208,163,187,228,27,42,195,31,149,158,122,12,164,71,139,91,212,22,55,51,203,196,15,77,206,20,105,209,201,25,114,245,93,14,213,127,95,155,242,37,3,186,85,143,77,93,13,241,100,53,35,21,75,21,89,29,179,148,247,246,156,158,207,80,186,193,88,80,103,143,8,180,32,247,203,172,44,32,111,112,182,63,1,48,140,183,67,207,15,157,61,243,43,73,40,26,200,254,206,181,185,14,217,94,28,214,203,61,181,58,173,244,15,14,0,146,11,177,33,22,46,116,213,60,13,219,98,22,171,163,113,146,71,83,85,193,175,47,65,179,248,251,227,112,205,230,163,76,69,126,31,76,107,80,150,65,137,196,116,98,11,16,131,65,135,51,138,129,177,48,88,236,90,4,50,140,104,179,143,29,222,101,115,255,103,94,101,188,73,216,118,159,51,20,101,161,119,148,201,45,2,3,1,0,1,163,130,1,122,48,130,1,118,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,29,6,3,85,29,14,4,22,4,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,130,1,17,6,3,85,29,32,4,130,1,8,48,130,1,4,48,130,1,0,6,9,42,134,72,134,247,99,100,5,1,48,129,242,48,42,6,8,43,6,1,5,5,7,2,1,22,30,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,99,97,47,48,129,195,6,8,43,6,1,5,5,7,2,2,48,129,182,26,129,179,82,101,108,105,97,110,99,101,32,111,110,32,116,104,105,115,32,99,101,114,116,105,102,105,99,97,116,101,32,98,121,32,97,110,121,32,112,97,114,116,121,32,97,115,115,117,109,101,115,32,97,99,99,101,112,116,97,110,99,101,32,111,102,32,116,104,101,32,116,104,101,110,32,97,112,112,108,105,99,97,98,108,101,32,115,116,97,110,100,97,114,100,32,116,101,114,109,115,32,97,110,100,32,99,111,110,100,105,116,105,111,110,115,32,111,102,32,117,115,101,44,32,99,101,114,116,105,102,105,99,97,116,101,32,112,111,108,105,99,121,32,97,110,100,32,99,101,114,116,105,102,105,99,97,116,105,111,110,32,112,114,97,99,116,105,99,101,32,115,116,97,116,101,109,101,110,116,115,46,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,92,54,153,76,45,120,183,237,140,155,220,243,119,155,242,118,210,119,48,79,193,31,133,131,133,27,153,61,71,55,242,169,155,64,142,44,212,177,144,18,216,190,244,115,155,238,210,100,15,203,121,79,52,216,162,62,249,120,255,107,200,7,236,125,57,131,139,83,32,211,56,196,177,191,154,79,10,107,255,43,252,89,167,5,9,124,23,64,86,17,30,116,211,183,139,35,59,71,163,213,111,36,226,235,209,183,112,223,15,69,225,39,202,241,109,120,237,231,181,23,23,168,220,126,34,53,202,37,213,217,15,214,107,212,162,36,35,17,247,161,172,143,115,129,96,198,27,91,9,47,146,178,248,68,72,240,96,56,158,21,245,61,38,103,32,138,51,106,247,13,130,207,222,235,163,47,249,83,106,91,100,192,99,51,119,247,58,7,44,86,235,218,15,33,14,218,186,115,25,79,181,217,54,127,193,135,85,217,167,153,185,50,66,251,216,213,113,158,126,161,82,183,27,189,147,66,36,18,42,199,15,29,182,77,156,94,99,200,75,128,23,80,170,138,213,218,228,252,208,9,7,55,176,117,117,33]\nstatic let AppleWWDRCAG4_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,19,220,119,149,82,113,229,61,198,50,232,204,255,229,33,243,204,197,206,210,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,49,50,49,54,49,57,51,54,48,52,90,23,13,51,48,49,50,49,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,52,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,208,31,120,170,122,39,50,176,70,95,231,23,118,216,160,157,14,41,142,173,61,50,165,196,107,55,201,228,65,145,106,183,121,113,93,12,52,4,96,117,247,174,67,143,71,196,134,30,8,232,191,214,57,82,47,30,103,252,113,241,130,109,60,126,6,82,118,157,44,188,213,67,233,177,180,188,64,58,120,81,93,81,161,37,225,190,108,145,157,107,33,89,24,65,213,15,141,109,65,42,57,74,33,224,144,159,78,19,79,208,140,154,50,184,215,106,146,30,37,106,164,50,206,34,25,133,5,96,220,2,74,242,90,235,119,121,2,125,192,151,84,108,146,142,118,1,230,70,143,229,230,42,251,162,176,173,24,173,109,51,133,56,35,139,234,138,150,237,159,174,102,79,163,12,64,39,109,149,208,98,136,217,67,41,39,253,237,164,191,83,46,144,21,101,60,217,46,98,100,51,29,108,106,221,142,33,170,164,95,21,198,48,237,95,230,140,54,146,148,183,220,57,2,0,251,100,140,212,12,129,242,63,213,52,151,135,117,38,194,111,174,3,99,33,12,123,212,27,177,98,197,2,156,189,253,175,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,91,217,250,29,231,154,26,11,163,153,118,34,80,134,62,145,200,91,119,168,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,63,86,61,158,229,182,195,121,230,69,32,104,189,191,115,139,44,18,158,2,227,174,128,34,140,4,30,195,82,200,112,128,168,251,206,167,176,213,66,68,130,3,130,79,6,252,59,73,20,251,216,116,82,133,175,167,157,33,231,1,18,3,159,205,64,88,208,1,215,191,50,131,43,83,88,40,60,238,156,159,84,118,61,100,39,198,126,141,29,56,77,45,174,129,230,185,165,184,156,137,148,247,159,199,135,165,81,102,52,27,57,113,57,36,227,135,103,239,165,177,104,123,140,238,61,247,174,182,123,226,210,255,223,97,198,106,117,73,149,34,68,168,4,252,148,184,11,46,57,17,73,18,209,229,129,234,89,0,79,91,60,90,54,218,122,34,115,9,9,105,205,192,124,234,226,36,254,152,68,184,248,239,178,113,63,26,93,212,93,126,51,77,156,29,36,190,0,240,144,3,88,153,65,61,49,90,98,64,175,57,168,81,67,146,171,4,168,156,194,77,177,75,210,171,124,74,95,235,157,59,188,79,136,64,6,19,255,144,23,138,8,71,41,232,98,152,41,165,79,17,5,105,58,207,242,159]\nstatic let AppleWWDRCAG6_cer: [UInt8] = [48,130,3,22,48,130,2,156,160,3,2,1,2,2,20,34,193,161,71,10,116,115,105,239,83,134,18,201,198,159,61,56,243,108,215,48,10,6,8,42,134,72,206,61,4,3,3,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,50,49,48,51,49,55,50,48,51,55,49,48,90,23,13,51,54,48,51,49,57,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,54,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,118,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,3,98,0,4,110,196,10,11,222,15,174,85,166,101,121,215,130,220,115,117,82,75,241,61,18,25,137,224,13,17,169,158,9,247,55,163,211,240,147,4,111,177,67,139,134,193,152,248,66,157,157,255,178,174,143,23,247,6,112,165,214,176,190,111,58,215,145,135,34,120,231,29,192,72,254,220,56,31,154,106,143,116,125,202,113,74,255,196,100,86,231,136,6,205,129,145,161,34,26,72,163,129,250,48,129,247,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,70,6,8,43,6,1,5,5,7,1,1,4,58,48,56,48,54,6,8,43,6,1,5,5,7,48,1,134,42,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,103,51,48,55,6,3,85,29,31,4,48,48,46,48,44,160,42,160,40,134,38,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,114,111,111,116,99,97,103,51,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,63,47,148,35,81,211,80,201,154,40,61,237,176,124,229,207,165,144,98,153,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,10,6,8,42,134,72,206,61,4,3,3,3,104,0,48,101,2,48,64,94,20,170,228,140,138,162,3,2,62,220,56,247,64,90,7,174,251,9,161,6,37,123,159,64,31,196,169,145,157,232,36,163,136,43,78,158,227,19,109,117,87,155,28,92,197,249,2,49,0,211,72,252,90,173,149,239,54,185,49,83,116,228,80,194,55,223,44,239,21,85,81,79,140,49,88,144,189,247,131,172,117,198,120,249,17,141,177,128,242,71,152,38,118,189,39,12,104]\nstatic let AppleWWDRCAG8_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,84,181,11,175,121,13,141,127,140,175,104,76,86,47,80,105,10,26,186,95,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,51,48,54,50,48,50,51,51,55,49,53,90,23,13,50,53,48,49,50,52,48,48,48,48,48,48,90,48,117,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,11,12,2,71,56,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,208,64,16,212,8,249,82,33,99,79,60,104,247,212,156,130,2,140,131,104,188,183,141,127,136,231,66,77,44,239,34,165,194,137,222,189,12,215,77,97,80,45,57,228,48,115,165,210,213,104,154,51,242,239,217,42,173,46,31,3,186,248,165,241,66,11,87,46,70,198,208,88,211,112,95,247,178,55,239,106,31,62,191,137,57,194,173,254,245,5,251,88,150,49,200,135,44,213,35,186,117,176,44,245,171,160,186,242,32,12,76,235,36,99,105,233,34,64,240,142,88,91,222,100,123,137,27,81,18,4,224,23,178,89,205,223,241,231,206,175,44,50,232,105,193,208,8,126,29,162,71,115,209,75,59,253,185,133,220,71,167,40,130,121,41,72,137,2,40,226,193,236,44,31,91,134,252,216,182,203,113,192,115,1,75,252,5,17,17,108,1,3,52,90,246,129,194,94,31,124,20,14,222,63,107,33,203,79,245,215,97,230,132,3,146,188,231,37,41,158,205,91,12,193,219,227,196,58,217,118,87,172,47,56,20,25,200,183,177,162,85,79,95,78,142,25,89,169,218,253,114,218,176,4,33,5,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,181,189,188,128,196,12,227,56,164,244,183,173,35,179,239,68,206,185,90,133,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,76,179,235,122,57,148,74,149,102,250,22,49,234,13,138,143,93,66,56,198,7,205,232,201,34,172,252,8,66,126,95,147,95,49,42,168,34,193,118,25,43,238,174,114,233,189,86,207,73,36,146,8,247,205,25,117,195,249,26,39,13,14,220,41,141,63,182,219,165,79,76,114,196,96,145,137,17,126,36,149,67,34,96,103,188,223,255,171,229,60,22,23,157,130,20,78,157,244,117,254,80,185,173,5,178,184,121,246,149,214,16,229,246,83,244,207,35,230,119,15,236,184,75,105,248,226,158,2,49,217,142,217,202,190,99,94,95,225,160,105,206,193,205,110,73,163,120,97,175,57,60,106,75,10,52,37,100,213,48,181,60,171,221,17,129,57,113,232,192,195,88,128,17,16,26,17,210,194,188,89,240,138,217,53,115,192,230,109,228,201,125,98,20,62,130,2,169,16,105,55,121,97,111,240,70,148,62,53,245,171,172,99,208,216,94,89,87,105,209,184,75,110,93,212,95,19,156,112,78,37,17,220,36,44,30,22,158,150,90,4,237,69,238,58,238,103,93,143,195,134,176,245,76,31,104,16]\nstatic let AppleRootCA_G3_cer: [UInt8] = [48,130,2,67,48,130,1,201,160,3,2,1,2,2,8,45,197,252,136,210,197,75,149,48,10,6,8,42,134,72,206,61,4,3,3,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,52,51,48,49,56,49,57,48,54,90,23,13,51,57,48,52,51,48,49,56,49,57,48,54,90,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,118,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,3,98,0,4,152,233,47,61,64,114,164,237,147,34,114,129,19,28,221,16,149,241,197,163,78,113,220,20,22,217,14,229,166,5,42,119,100,123,95,78,56,211,187,28,68,181,127,245,31,182,50,98,93,201,233,132,91,79,48,79,17,90,0,253,88,88,12,165,245,15,44,77,7,71,19,117,218,151,151,151,111,49,92,237,43,157,123,32,59,216,185,84,217,94,153,164,58,81,10,49,163,66,48,64,48,29,6,3,85,29,14,4,22,4,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,10,6,8,42,134,72,206,61,4,3,3,3,104,0,48,101,2,49,0,131,233,193,196,22,94,26,93,52,24,217,237,239,244,108,14,0,70,75,184,223,178,70,17,197,15,253,230,122,140,161,166,107,206,194,3,212,156,245,147,198,116,184,106,223,170,35,21,2,48,109,102,138,16,202,212,13,212,79,205,141,67,62,180,138,99,165,51,110,227,109,218,23,183,100,31,200,83,38,249,136,98,116,57,11,23,91,203,81,168,12,232,24,3,231,162,178,40]\n}\n"
  },
  {
    "path": "Sources/PackageFingerprint/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageFingerprint STATIC\n  FilePackageFingerprintStorage.swift\n  Model.swift\n  PackageFingerprintStorage.swift)\ntarget_link_libraries(PackageFingerprint PUBLIC\n  Basics\n  PackageModel\n  TSCBasic\n  TSCUtility)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageFingerprint PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n"
  },
  {
    "path": "Sources/PackageFingerprint/FilePackageFingerprintStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport Foundation\nimport PackageModel\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\npublic struct FilePackageFingerprintStorage: PackageFingerprintStorage {\n    let fileSystem: FileSystem\n    let directoryPath: Basics.AbsolutePath\n\n    private let encoder: JSONEncoder\n    private let decoder: JSONDecoder\n\n    public init(fileSystem: FileSystem, directoryPath: Basics.AbsolutePath) {\n        self.fileSystem = fileSystem\n        self.directoryPath = directoryPath\n\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n    }\n\n    public func get(\n        package: PackageIdentity,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] {\n        try self.get(\n            reference: package,\n            version: version,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    public func put(\n        package: PackageIdentity,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.put(\n            reference: package,\n            version: version,\n            fingerprint: fingerprint,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    public func get(\n        package: PackageReference,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] {\n        try self.get(\n            reference: package,\n            version: version,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    public func put(\n        package: PackageReference,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.put(\n            reference: package,\n            version: version,\n            fingerprint: fingerprint,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    private func get(\n        reference: FingerprintReference,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] {\n        let packageFingerprints = try self.withLock {\n            try self.loadFromDisk(reference: reference)\n        }\n\n        guard let fingerprints = packageFingerprints[version] else {\n            throw PackageFingerprintStorageError.notFound\n        }\n        return fingerprints\n    }\n\n    private func put(\n        reference: FingerprintReference,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.withLock {\n            var packageFingerprints = try self.loadFromDisk(reference: reference)\n\n            if let existing = packageFingerprints[version]?[fingerprint.origin.kind]?[fingerprint.contentType] {\n                // Error if we try to write a different fingerprint\n                guard fingerprint == existing else {\n                    throw PackageFingerprintStorageError.conflict(given: fingerprint, existing: existing)\n                }\n                // Don't need to do anything if fingerprints are the same\n                return\n            }\n\n            var fingerprintsForVersion = packageFingerprints.removeValue(forKey: version) ?? [:]\n            var fingerprintsForKind = fingerprintsForVersion.removeValue(forKey: fingerprint.origin.kind) ?? [:]\n            fingerprintsForKind[fingerprint.contentType] = fingerprint\n            fingerprintsForVersion[fingerprint.origin.kind] = fingerprintsForKind\n            packageFingerprints[version] = fingerprintsForVersion\n\n            try self.saveToDisk(reference: reference, fingerprints: packageFingerprints)\n        }\n    }\n\n    private func loadFromDisk(reference: FingerprintReference) throws -> PackageFingerprints {\n        let path = try self.directoryPath.appending(component: reference.fingerprintsFilename)\n\n        guard self.fileSystem.exists(path) else {\n            return .init()\n        }\n\n        let data: Data = try fileSystem.readFileContents(path)\n        guard data.count > 0 else {\n            return .init()\n        }\n\n        return try StorageModel.decode(data: data, decoder: self.decoder)\n    }\n\n    private func saveToDisk(reference: FingerprintReference, fingerprints: PackageFingerprints) throws {\n        if !self.fileSystem.exists(self.directoryPath) {\n            try self.fileSystem.createDirectory(self.directoryPath, recursive: true)\n        }\n\n        let buffer = try StorageModel.encode(packageFingerprints: fingerprints, encoder: self.encoder)\n        let path = try self.directoryPath.appending(component: reference.fingerprintsFilename)\n        try self.fileSystem.writeFileContents(path, data: buffer)\n    }\n\n    private func withLock<T>(_ body: () throws -> T) throws -> T {\n        if !self.fileSystem.exists(self.directoryPath) {\n            try self.fileSystem.createDirectory(self.directoryPath, recursive: true)\n        }\n        return try self.fileSystem.withLock(on: self.directoryPath, type: .exclusive, body)\n    }\n\n    private func makeAsync<T>(\n        _ closure: @escaping (Result<T, Error>) -> Void,\n        on queue: DispatchQueue\n    ) -> (Result<T, Error>) -> Void {\n        { result in queue.async { closure(result) } }\n    }\n}\n\nprivate enum StorageModel {\n    struct SchemaVersion: Codable {\n        let version: Int?\n    }\n\n    enum Container {\n        struct V1: Codable {\n            let version: Int?\n            // version -> fingerprint kind\n            let versionFingerprints: [String: [String: StoredFingerprint]]\n\n            struct StoredFingerprint: Codable {\n                let origin: String\n                let fingerprint: String\n            }\n        }\n\n        struct V2: Codable {\n            let version: Int\n            // version -> fingerprint kind -> fingerprint content type\n            let versionFingerprints: [String: [String: [String: StoredFingerprint]]]\n\n            struct StoredFingerprint: Codable {\n                let origin: String\n                let fingerprint: String\n                let contentType: ContentType\n\n                enum ContentType: Codable {\n                    case sourceCode\n                    case manifest\n                    case versionSpecificManifest(toolsVersion: ToolsVersion)\n\n                    static func from(contentType: Fingerprint.ContentType) -> ContentType {\n                        switch contentType {\n                        case .sourceCode:\n                            return .sourceCode\n                        case .manifest(.none):\n                            return .manifest\n                        case .manifest(.some(let toolsVersion)):\n                            return .versionSpecificManifest(toolsVersion: toolsVersion)\n                        }\n                    }\n                }\n            }\n\n            init(versionFingerprints: [String: [String: [String: StoredFingerprint]]]) {\n                self.version = 2\n                self.versionFingerprints = versionFingerprints\n            }\n\n            func packageFingerprints() throws -> PackageFingerprints {\n                try Dictionary(\n                    throwingUniqueKeysWithValues: self.versionFingerprints.map { version, fingerprintsForVersion in\n                        let fingerprintsByKind = try Dictionary(\n                            throwingUniqueKeysWithValues: fingerprintsForVersion.map { kind, fingerprintsForKind in\n                                guard let kind = Fingerprint.Kind(rawValue: kind) else {\n                                    throw SerializationError.unknownKind(kind)\n                                }\n\n                                let fingerprintsByContentType = try Dictionary(\n                                    throwingUniqueKeysWithValues: fingerprintsForKind.map { _, storedFingerprint in\n                                        let origin: Fingerprint.Origin\n                                        switch kind {\n                                        case .sourceControl:\n                                            origin = .sourceControl(SourceControlURL(storedFingerprint.origin))\n                                        case .registry:\n                                            guard let originURL = URL(string: storedFingerprint.origin) else {\n                                                throw SerializationError.invalidURL(storedFingerprint.origin)\n                                            }\n                                            origin = .registry(originURL)\n                                        }\n\n                                        let contentType = Fingerprint.ContentType.from(storedFingerprint.contentType)\n                                        let fingerprint = Fingerprint(\n                                            origin: origin,\n                                            value: storedFingerprint.fingerprint,\n                                            contentType: contentType\n                                        )\n                                        return (contentType, fingerprint)\n                                    }\n                                )\n\n                                return (kind, fingerprintsByContentType)\n                            }\n                        )\n                        return (Version(stringLiteral: version), fingerprintsByKind)\n                    }\n                )\n            }\n        }\n    }\n\n    static func decode(data: Data, decoder: JSONDecoder) throws -> PackageFingerprints {\n        let schemaVersion = try decoder.decode(SchemaVersion.self, from: data)\n        switch schemaVersion.version {\n        case .some(2):\n            let container = try decoder.decode(Container.V2.self, from: data)\n            return try container.packageFingerprints()\n        case .some(1), .none: // v1\n            let containerV1 = try decoder.decode(Container.V1.self, from: data)\n            // Convert v1 to v2\n            let containerV2 = Container.V2(versionFingerprints: try Dictionary(\n                throwingUniqueKeysWithValues: containerV1.versionFingerprints.map { version, fingerprintsForVersion in\n                    let fingerprintsByKind = try Dictionary(\n                        throwingUniqueKeysWithValues: fingerprintsForVersion.map { kind, fingerprint in\n                            // All v1 fingerprints are for source code\n                            let contentType = Container.V2.StoredFingerprint.ContentType.sourceCode\n                            let fingerprintV2 = Container.V2.StoredFingerprint(\n                                origin: fingerprint.origin,\n                                fingerprint: fingerprint.fingerprint,\n                                contentType: contentType\n                            )\n                            return (\n                                kind,\n                                [Fingerprint.ContentType.from(contentType).description: fingerprintV2]\n                            )\n                        }\n                    )\n                    return (version, fingerprintsByKind)\n                }\n            ))\n            return try containerV2.packageFingerprints()\n        default:\n            throw StringError(\n                \"unknown package fingerprint storage version '\\(String(describing: schemaVersion.version))'\"\n            )\n        }\n    }\n\n    static func encode(packageFingerprints: PackageFingerprints, encoder: JSONEncoder) throws -> Data {\n        let container = Container.V2(versionFingerprints: try Dictionary(\n            throwingUniqueKeysWithValues: packageFingerprints.map { version, fingerprintsForVersion in\n                let fingerprintsByKind = try Dictionary(\n                    throwingUniqueKeysWithValues: fingerprintsForVersion.map { kind, fingerprintsForKind in\n                        let fingerprintsByContentType = try Dictionary(\n                            throwingUniqueKeysWithValues: fingerprintsForKind.map { contentType, fingerprint in\n                                let origin: String\n                                switch fingerprint.origin {\n                                case .sourceControl(let url):\n                                    origin = url.absoluteString\n                                case .registry(let url):\n                                    origin = url.absoluteString\n                                }\n\n                                let storedFingerprint = Container.V2.StoredFingerprint(\n                                    origin: origin,\n                                    fingerprint: fingerprint.value,\n                                    contentType: .from(contentType: contentType)\n                                )\n                                return (contentType.description, storedFingerprint)\n                            }\n                        )\n                        return (kind.rawValue, fingerprintsByContentType)\n                    }\n                )\n                return (version.description, fingerprintsByKind)\n            }\n        ))\n        return try encoder.encode(container)\n    }\n}\n\nextension Fingerprint.ContentType {\n    fileprivate static func from(_ storage: StorageModel.Container.V2.StoredFingerprint.ContentType) -> Fingerprint\n        .ContentType\n    {\n        switch storage {\n        case .sourceCode:\n            return .sourceCode\n        case .manifest:\n            return .manifest(.none)\n        case .versionSpecificManifest(let toolsVersion):\n            return .manifest(toolsVersion)\n        }\n    }\n}\n\nprotocol FingerprintReference {\n    var fingerprintsFilename: String { get throws }\n}\n\nextension PackageIdentity: FingerprintReference {\n    var fingerprintsFilename: String {\n        \"\\(self.description).json\"\n    }\n}\n\nextension PackageReference: FingerprintReference {\n    var fingerprintsFilename: String {\n        get throws {\n            guard case .remoteSourceControl(let sourceControlURL) = self.kind else {\n                throw StringError(\"Package kind [\\(self.kind)] does not support fingerprints\")\n            }\n            \n            let canonicalLocation = CanonicalPackageLocation(sourceControlURL.absoluteString)\n            // Cannot use hashValue because it is not consistent across executions\n            let locationHash = canonicalLocation.description.sha256Checksum.prefix(8)\n            return \"\\(self.identity.description)-\\(locationHash).json\"\n        }\n    }\n}\n\nprivate enum SerializationError: Error {\n    case unknownKind(String)\n    case invalidURL(String)\n}\n"
  },
  {
    "path": "Sources/PackageFingerprint/Model.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\n\nimport Basics\nimport PackageModel\nimport struct TSCUtility.Version\n\npublic struct Fingerprint: Equatable {\n    public let origin: Origin\n    public let value: String\n    public let contentType: ContentType\n\n    public init(origin: Origin, value: String, contentType: ContentType) {\n        self.origin = origin\n        self.value = value\n        self.contentType = contentType\n    }\n}\n\nextension Fingerprint {\n    public enum Kind: String, Hashable {\n        case sourceControl\n        case registry\n    }\n\n    public enum Origin: Equatable, CustomStringConvertible {\n        case sourceControl(SourceControlURL)\n        case registry(URL)\n\n        public var kind: Fingerprint.Kind {\n            switch self {\n            case .sourceControl:\n                return .sourceControl\n            case .registry:\n                return .registry\n            }\n        }\n\n        public var url: SourceControlURL? {\n            switch self {\n            case .sourceControl(let url):\n                return url\n            case .registry(let url):\n                return SourceControlURL(url.absoluteString)\n            }\n        }\n\n        public var description: String {\n            switch self {\n            case .sourceControl(let url):\n                return \"sourceControl(\\(url))\"\n            case .registry(let url):\n                return \"registry(\\(url))\"\n            }\n        }\n    }\n\n    /// Each package version has a dictionary of fingerprints identified by content type.\n    /// Fingerprints of content type `sourceCode` can come from registry (i.e., source archive checksum)\n    /// or git repo (commit hash). However, the current implementation only stores fingerprints for manifests\n    /// downloaded from registry. It doesn't not save fingerprints for manifests in git repo.\n    public enum ContentType: Hashable, CustomStringConvertible {\n        case sourceCode\n        case manifest(ToolsVersion?)\n\n        public var description: String {\n            switch self {\n            case .sourceCode:\n                return \"sourceCode\"\n            case .manifest(.none):\n                return Manifest.filename\n            case .manifest(.some(let toolsVersion)):\n                return \"Package@swift-\\(toolsVersion).swift\"\n            }\n        }\n    }\n}\n\npublic typealias PackageFingerprints = [Version: [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]]]\n\npublic enum FingerprintCheckingMode: String {\n    case strict\n    case warn\n}\n"
  },
  {
    "path": "Sources/PackageFingerprint/PackageFingerprintStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport PackageModel\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\npublic protocol PackageFingerprintStorage {\n    func get(\n        package: PackageIdentity,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]]\n\n    func put(\n        package: PackageIdentity,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws\n\n    func get(\n        package: PackageReference,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]]\n\n    func put(\n        package: PackageReference,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws\n}\n\nextension PackageFingerprintStorage {\n    public func get(\n        package: PackageIdentity,\n        version: Version,\n        kind: Fingerprint.Kind,\n        contentType: Fingerprint.ContentType,\n        observabilityScope: ObservabilityScope\n    ) throws -> Fingerprint {\n        let fingerprints = try self.get(\n            package: package,\n            version: version,\n            observabilityScope: observabilityScope\n        )\n        guard let fingerprint = fingerprints[kind]?[contentType] else {\n            throw PackageFingerprintStorageError.notFound\n        }\n        return fingerprint\n    }\n\n    public func get(\n        package: PackageReference,\n        version: Version,\n        kind: Fingerprint.Kind,\n        contentType: Fingerprint.ContentType,\n        observabilityScope: ObservabilityScope\n    ) throws -> Fingerprint{\n        let fingerprints = try self.get(\n            package: package,\n            version: version,\n            observabilityScope: observabilityScope\n        )\n        guard let fingerprint = fingerprints[kind]?[contentType] else {\n            throw PackageFingerprintStorageError.notFound\n        }\n        return fingerprint\n    }\n\n    private func get(\n        kind: Fingerprint.Kind,\n        contentType: Fingerprint.ContentType,\n        _ fingerprintsByKindResult: Result<[Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]], Error>,\n        callback: @escaping (Result<Fingerprint, Error>) -> Void\n    ) {\n        callback(fingerprintsByKindResult.tryMap { fingerprintsByKind in\n            guard let fingerprintsByContentType = fingerprintsByKind[kind],\n                  let fingerprint = fingerprintsByContentType[contentType]\n            else {\n                throw PackageFingerprintStorageError.notFound\n            }\n            return fingerprint\n        })\n    }\n}\n\npublic enum PackageFingerprintStorageError: Error, Equatable, CustomStringConvertible {\n    case conflict(given: Fingerprint, existing: Fingerprint)\n    case notFound\n\n    public var description: String {\n        switch self {\n        case .conflict(let given, let existing):\n            return \"fingerprint \\(given) is different from previously recorded value \\(existing)\"\n        case .notFound:\n            return \"not found\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/BoundVersion.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCUtility.Version\n\n/// A bound version for a package within an assignment.\npublic enum BoundVersion: Equatable, Hashable {\n    /// The assignment should not include the package.\n    ///\n    /// This is different from the absence of an assignment for a particular\n    /// package, which only indicates the assignment is agnostic to its\n    /// version. This value signifies the package *may not* be present.\n    case excluded\n\n    /// The version of the package to include.\n    case version(Version)\n\n    /// The package assignment is unversioned.\n    case unversioned\n\n    /// The package assignment is this revision.\n    case revision(String, branch: String? = nil)\n}\n\nextension BoundVersion: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .excluded:\n            return \"excluded\"\n        case .version(let version):\n            return version.description\n        case .unversioned:\n            return \"unversioned\"\n        case .revision(let identifier, _):\n            return identifier\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageGraph\n  BoundVersion.swift\n  DependencyMirrors.swift\n  Diagnostics.swift\n  GraphLoadingNode.swift\n  ModuleAliasTracker.swift\n  ModulesGraph.swift\n  ModulesGraph+Loading.swift\n  PackageContainer.swift\n  PackageGraphRoot.swift\n  PackageModel+Extensions.swift\n  PackageRequirement.swift\n  ResolvedPackagesStore.swift\n  Resolution/PubGrub/Assignment.swift\n  Resolution/PubGrub/ContainerProvider.swift\n  Resolution/PubGrub/DiagnosticReportBuilder.swift\n  Resolution/PubGrub/Incompatibility.swift\n  Resolution/PubGrub/PartialSolution.swift\n  Resolution/PubGrub/PubGrubDependencyResolver.swift\n  Resolution/PubGrub/PubGrubPackageContainer.swift\n  Resolution/PubGrub/Term.swift\n  Resolution/DependencyResolutionNode.swift\n  Resolution/DependencyResolverBinding.swift\n  Resolution/DependencyResolverDelegate.swift\n  Resolution/DependencyResolverError.swift\n  Resolution/PlatformVersionProvider.swift\n  Resolution/ResolvedPackage.swift\n  Resolution/ResolvedProduct.swift\n  Resolution/ResolvedModule.swift\n  Version+Extensions.swift\n  VersionSetSpecifier.swift)\ntarget_link_libraries(PackageGraph PUBLIC\n  SwiftCollections::OrderedCollections\n  TSCBasic\n  Basics\n  PackageLoading\n  PackageModel\n  TSCUtility)\ntarget_link_libraries(PackageGraph PRIVATE\n  SourceControl)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageGraph PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS PackageGraph\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS PackageGraph)\n"
  },
  {
    "path": "Sources/PackageGraph/DependencyMirrors.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport OrderedCollections\nimport PackageModel\n\nimport struct TSCBasic.StringError\n\n/// A collection of dependency mirrors.\npublic final class DependencyMirrors: Equatable {\n    private var index: [String: String]\n    private var mirrorIndex: [PackageIdentity: PackageIdentity]\n    private var reverseIndex: [String: [String]]\n    private var visited: OrderedCollections.OrderedSet<String>\n    private let lock = NSLock()\n\n    public var mapping: [String: String] {\n        self.lock.withLock {\n            self.index\n        }\n    }\n\n    public init(_ mirrors: [String: String] = [:]) throws {\n        self.index = mirrors\n        self.reverseIndex = [String: [String]]()\n        self.mirrorIndex = [PackageIdentity: PackageIdentity]()\n        for entry in mirrors {\n            self.reverseIndex[entry.value, default: []].append(entry.key)\n            self.mirrorIndex[try Self.parseLocation(entry.key)] = try Self.parseLocation(entry.value)\n        }\n        self.visited = .init()\n    }\n\n    public static func == (lhs: DependencyMirrors, rhs: DependencyMirrors) -> Bool {\n        lhs.mapping == rhs.mapping\n    }\n\n    /// Sets a mirror for the given origin.\n    /// - Parameters:\n    ///   - mirror: The mirror\n    ///   - for: The original\n    public func set(mirror: String, for key: String) throws {\n        try self.lock.withLock {\n            self.index[key] = mirror\n            self.reverseIndex[mirror, default: []].append(key)\n            self.mirrorIndex[try Self.parseLocation(key)] = try Self.parseLocation(mirror)\n        }\n    }\n\n    /// Unsets a mirror for the given.\n    /// - Parameters:\n    ///   - originalOrMirror: The original or the mirrored\n    /// - Throws: `Error.mirrorNotFound` if no mirror exists for the provided origin or mirror.\n    public func unset(originalOrMirror: String) throws {\n        try self.lock.withLock {\n            if let value = self.index[originalOrMirror] {\n                self.index[originalOrMirror] = nil\n                self.reverseIndex[value] = nil\n                self.mirrorIndex[try Self.parseLocation(value)] = nil\n            } else if let mirror = self.index.first(where: { $0.value == originalOrMirror }) {\n                self.index[mirror.key] = nil\n                self.reverseIndex[originalOrMirror] = nil\n                self.mirrorIndex[try Self.parseLocation(originalOrMirror)] = nil\n            } else {\n                throw StringError(\"Mirror not found for '\\(originalOrMirror)'\")\n            }\n        }\n    }\n\n    /// Append the content of a different DependencyMirrors into this one\n    /// - Parameters:\n    ///   - contentsOf: The DependencyMirrors to append from.\n    public func append(contentsOf mirrors: DependencyMirrors) throws {\n        try mirrors.index.forEach {\n            try self.set(mirror: $0.value, for: $0.key)\n        }\n    }\n\n    // Removes all mirrors\n    public func removeAll() {\n        self.lock.withLock {\n            self.index.removeAll()\n            self.reverseIndex.removeAll()\n        }\n    }\n\n    // Count\n    public var count: Int {\n        self.lock.withLock {\n            self.index.count\n        }\n    }\n\n    // Is empty\n    public var isEmpty: Bool {\n        self.lock.withLock {\n            self.index.isEmpty\n        }\n    }\n\n    /// Returns the mirrored for a package dependency.\n    /// - Parameters:\n    ///   - for: The original\n    /// - Returns: The mirrored, if one exists.\n    public func mirror(for key: String) -> String? {\n        self.lock.withLock {\n            let value = self.index[key]\n            if value != nil {\n                // record visited mirrors for reverse index lookup sorting\n                self.visited.append(key)\n            }\n            return value\n        }\n    }\n\n    /// Returns the effective value for a package dependency.\n    /// - Parameters:\n    ///   - for: The original\n    /// - Returns: The mirrored if it exists, otherwise the original.\n    public func effective(for key: String) -> String {\n        self.mirror(for: key) ?? key\n    }\n\n    /// Returns the original for a mirrored package dependency.\n    /// - Parameters:\n    ///   - for: The mirror\n    /// - Returns: The original , if one exists.\n    public func original(for key: String) -> String? {\n        self.lock.withLock {\n            let alternatives = self.reverseIndex[key]\n            // since there are potentially multiple mapping, we need to sort them to produce deterministic results\n            let sorted = alternatives?.sorted(by: { lhs, rhs in\n                // check if it was visited (which means it used by the package)\n                switch (self.visited.firstIndex(of: lhs), self.visited.firstIndex(of: rhs)) {\n                case (.some(let lhsIndex), .some(let rhsIndex)):\n                    return lhsIndex < rhsIndex\n                case (.some, .none):\n                    return true\n                case (.none, .some):\n                    return false\n                case (.none, .none):\n                    // otherwise sort alphabetically\n                    return lhs < rhs\n                }\n            })\n            return sorted?.first\n        }\n    }\n\n    public func effectiveIdentity(for identity: PackageIdentity) throws -> PackageIdentity {\n        return mirrorIndex[identity] ?? identity\n    }\n\n    private static func parseLocation(_ location: String) throws -> PackageIdentity {\n        if PackageIdentity.plain(location).isRegistry {\n            return PackageIdentity.plain(location)\n        } else if let path = try? AbsolutePath(validating: location) {\n            return PackageIdentity(path: path)\n        } else {\n            return PackageIdentity(url: SourceControlURL(location))\n        }\n    }\n}\n\nextension DependencyMirrors: Collection {\n    public typealias Index = Dictionary<String, String>.Index\n    public typealias Element = String\n\n    public var startIndex: Index {\n        self.lock.withLock {\n            self.index.startIndex\n        }\n    }\n\n    public var endIndex: Index {\n        self.lock.withLock {\n            self.index.endIndex\n        }\n    }\n\n    public subscript(index: Index) -> Element {\n        self.lock.withLock {\n            self.index[index].value\n        }\n    }\n\n    public func index(after index: Index) -> Index {\n        self.lock.withLock {\n            self.index.index(after: index)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Diagnostics.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nextension Basics.Diagnostic {\n    static func unusedDependency(_ name: String) -> Self {\n        .warning(\"dependency '\\(name)' is not used by any target\")\n    }\n\n    static func productUsesUnsafeFlags(product: String, target: String) -> Self {\n        .error(\"the target '\\(target)' in product '\\(product)' contains unsafe build flags\")\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/GraphLoadingNode.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\n\n/// A node used while loading the packages in a resolved graph.\n///\n/// This node uses the product filter that was already finalized during resolution.\n///\n/// - SeeAlso: ``DependencyResolutionNode``\npublic struct GraphLoadingNode: Equatable, Hashable {\n    /// The package identity.\n    public let identity: PackageIdentity\n\n    /// The package manifest.\n    public let manifest: Manifest\n\n    /// The product filter applied to the package.\n    public let productFilter: ProductFilter\n\n    /// The enabled traits for this package.\n    package var enabledTraits: EnabledTraits\n\n    public init(\n        identity: PackageIdentity,\n        manifest: Manifest,\n        productFilter: ProductFilter,\n        enabledTraits: EnabledTraits\n    ) throws {\n        self.identity = identity\n        self.manifest = manifest\n        self.productFilter = productFilter\n        self.enabledTraits = enabledTraits\n    }\n\n    /// Returns the dependencies required by this node.\n    var requiredDependencies: [PackageDependency] {\n        guard let requiredDeps = try? self.manifest.dependenciesRequired(for: self.productFilter, enabledTraits) else {\n            return []\n        }\n        return requiredDeps\n    }\n\n    var traitGuardedDependencies: [PackageDependency] {\n        self.manifest.dependenciesTraitGuarded(withEnabledTraits: self.enabledTraits)\n    }\n}\n\nextension GraphLoadingNode: CustomStringConvertible {\n    public var description: String {\n        switch self.productFilter {\n        case .everything:\n            self.identity.description\n        case .specific(let set):\n            \"\\(self.identity.description)[\\(set.sorted().joined(separator: \", \"))]\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/ModuleAliasTracker.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageModel\nimport Basics\n\n// This is a helper class that tracks module aliases in a package dependency graph\n// and handles overriding upstream aliases where aliases themselves conflict.\nstruct ModuleAliasTracker {\n    fileprivate var aliasMap = [String: [ModuleAliasModel]]()\n    fileprivate var idToAliasMap = [PackageIdentity: [String: [ModuleAliasModel]]]()\n    var idToProductToAllModules = [PackageIdentity: [String: [Module]]]()\n    var productToDirectModules = [String: [Module]]()\n    var productToAllModules = [String: [Module]]()\n    var parentToChildProducts = [String: [String]]()\n    var parentToChildIDs = [PackageIdentity: [PackageIdentity]]()\n    var childToParentID = [PackageIdentity: PackageIdentity]()\n    var appliedAliases = Set<String>()\n\n    init() {}\n    mutating func addModuleAliases(modules: [Module], package: PackageIdentity) throws {\n        let moduleDependencies = modules.flatMap(\\.dependencies)\n        for dep in moduleDependencies {\n            if case let .product(productRef, _) = dep,\n               let productPkg = productRef.package {\n                let productPkgID = PackageIdentity.plain(productPkg)\n                // Track dependency package ID chain\n                addPackageIDChain(parent: package, child: productPkgID)\n                if let aliasList = productRef.moduleAliases {\n                    // Track aliases for this product\n                    try addAliases(aliasList,\n                                   productID: productRef.identity,\n                                   productName: productRef.name,\n                                   originPackage: productPkgID,\n                                   consumingPackage: package)\n                }\n            }\n        }\n    }\n\n    mutating func addAliases(\n        _ aliases: [String: String],\n        productID: String,\n        productName: String,\n        originPackage: PackageIdentity,\n        consumingPackage: PackageIdentity\n    ) throws {\n        if let aliasDict = idToAliasMap[originPackage] {\n            let existingAliases = aliasDict.values.flatMap{$0}.filter {  aliases.keys.contains($0.name) }\n            for existingAlias in existingAliases {\n                if let newAlias = aliases[existingAlias.name], newAlias != existingAlias.alias {\n                    // Error if there are multiple different aliases specified for\n                    // modules in this product\n                    throw PackageGraphError.multipleModuleAliases(module: existingAlias.name, product: productName, package: originPackage.description, aliases: existingAliases.map{$0.alias} + [newAlias])\n                }\n            }\n        }\n\n        for (originalName, newName) in aliases {\n            let model = ModuleAliasModel(name: originalName, alias: newName, originPackage: originPackage, consumingPackage: consumingPackage, productName: productName)\n            idToAliasMap[originPackage, default: [:]][productID, default: []].append(model)\n            aliasMap[productID, default: []].append(model)\n        }\n    }\n\n    mutating func addPackageIDChain(parent: PackageIdentity, child: PackageIdentity) {\n        if parentToChildIDs[parent]?.contains(child) ?? false {\n            // Already added\n        } else {\n            parentToChildIDs[parent, default: []].append(child)\n            // Used to track the top-most level package\n            childToParentID[child] = parent\n        }\n    }\n\n    // This func should be called once per product\n    mutating func trackModulesPerProduct(product: Product, package: PackageIdentity) {\n        let moduleDeps = product.modules.flatMap(\\.dependencies)\n        var allModuleDeps = product.modules.flatMap{$0.recursiveDependentModules.map{$0.dependencies}}.flatMap{$0}\n        allModuleDeps.append(contentsOf: moduleDeps)\n        for dep in allModuleDeps {\n            if case let .product(depRef, _) = dep {\n                parentToChildProducts[product.identity, default: []].append(depRef.identity)\n            }\n        }\n\n        var allModulesInProduct = moduleDeps.compactMap(\\.module)\n        allModulesInProduct.append(contentsOf: product.modules)\n        idToProductToAllModules[package, default: [:]][product.identity] = allModulesInProduct\n        productToDirectModules[product.identity] = product.modules\n        productToAllModules[product.identity] = allModulesInProduct\n    }\n\n    func validateAndApplyAliases(product: Product,\n                                 package: PackageIdentity,\n                                 observabilityScope: ObservabilityScope) throws {\n        guard let modules = idToProductToAllModules[package]?[product.identity] else { return }\n        let modulesWithAliases = modules.filter{ $0.moduleAliases != nil }\n        for moduleWithAlias in modulesWithAliases {\n            if moduleWithAlias.sources.containsNonSwiftFiles {\n                let aliasesMsg = moduleWithAlias.moduleAliases?.map{\"'\\($0.key)' as '\\($0.value)'\"}.joined(separator: \", \") ?? \"\"\n                observabilityScope.emit(warning: \"target '\\(moduleWithAlias.name)' for product '\\(product.name)' from package '\\(package.description)' has module aliases: [\\(aliasesMsg)] but may contain non-Swift sources; there might be a conflict among non-Swift symbols\")\n            }\n            moduleWithAlias.applyAlias()\n        }\n    }\n\n    mutating func propagateAliases(observabilityScope: ObservabilityScope) {\n        // First get the root package ID\n        var pkgID = childToParentID.first?.key\n        var rootPkg = pkgID\n        while pkgID != nil {\n            rootPkg = pkgID\n            // pkgID is not nil here so can be force unwrapped\n            pkgID = childToParentID[pkgID!]\n        }\n        guard let rootPkg else { return }\n\n        if let productToAllModules = idToProductToAllModules[rootPkg] {\n            // First, propagate aliases upstream\n            for productID in productToAllModules.keys {\n                var aliasBuffer = [String: ModuleAliasModel]()\n                propagate(productID: productID, observabilityScope: observabilityScope, aliasBuffer: &aliasBuffer)\n            }\n\n            // Then, merge or override upstream aliases downwards\n            for productID in productToAllModules.keys {\n                merge(productID: productID, observabilityScope: observabilityScope)\n            }\n        }\n        // Finally, fill in aliases for modules in products that are in the\n        // dependency chain but not in a product consumed by other packages\n        fillInRest(package: rootPkg)\n    }\n\n    // Propagate defined aliases upstream. If they are chained, the final\n    // alias value will be applied\n    mutating private func propagate(\n        productID: String,\n        observabilityScope: ObservabilityScope,\n        aliasBuffer: inout [String: ModuleAliasModel]\n    ) {\n        let productAliases = aliasMap[productID] ?? []\n        for aliasModel in productAliases {\n            // Alias buffer is used to carry down aliases defined upstream\n            if let existing = aliasBuffer[aliasModel.name],\n               existing.alias != aliasModel.alias {\n                // check to allow only the most downstream alias is added\n            } else {\n                aliasBuffer[aliasModel.name] = aliasModel\n            }\n        }\n\n        if let curDirectModules = productToDirectModules[productID] {\n            var relevantModules = curDirectModules.map{$0.recursiveDependentModules}.flatMap{$0}\n            relevantModules.append(contentsOf: curDirectModules)\n\n            for relevantModule in relevantModules {\n                if let val = lookupAlias(key: relevantModule.name, in: aliasBuffer) {\n                    appliedAliases.insert(relevantModule.name)\n                    relevantModule.addModuleAlias(for: relevantModule.name, as: val)\n                    if let prechainVal = aliasBuffer[relevantModule.name],\n                       prechainVal.alias != val {\n                        relevantModule.addPrechainModuleAlias(for: relevantModule.name, as: prechainVal.alias)\n                        appliedAliases.insert(prechainVal.alias)\n                        relevantModule.addPrechainModuleAlias(for: prechainVal.alias, as: val)\n                        observabilityScope.emit(info: \"Module alias '\\(prechainVal.alias)' defined in package '\\(prechainVal.consumingPackage)' for target '\\(relevantModule.name)' in package/product '\\(productID)' is overridden by alias '\\(val)'; if this override is not intended, remove '\\(val)' from 'moduleAliases' in its manifest\")\n                        aliasBuffer.removeValue(forKey: prechainVal.alias)\n\n                        // Since we're overriding an alias here, we have to pretend it was applied to avoid follow-on warnings.\n                        var currentAlias: String? = val\n                        while let _currentAlias = currentAlias, !appliedAliases.contains(_currentAlias) {\n                            appliedAliases.insert(_currentAlias)\n                            currentAlias = aliasBuffer.values.first { $0.alias == _currentAlias }?.name\n                        }\n                    }\n                    aliasBuffer.removeValue(forKey: relevantModule.name)\n                }\n            }\n        }\n\n        guard let children = parentToChildProducts[productID] else {\n            return\n        }\n        for childID in children {\n            propagate(productID: childID,\n                      observabilityScope: observabilityScope,\n                      aliasBuffer: &aliasBuffer)\n        }\n    }\n\n    // Merge all the upstream aliases and override them if necessary\n    mutating func merge(productID: String, observabilityScope: ObservabilityScope) {\n        guard let children = parentToChildProducts[productID] else {\n            return\n        }\n        for childID in children {\n            merge(productID: childID,\n                  observabilityScope: observabilityScope)\n        }\n\n        if let curDirectModules = productToDirectModules[productID] {\n            let depModules = curDirectModules.map{$0.recursiveDependentModules}.flatMap{$0}\n            let depModuleAliases = toDictionary(depModules.compactMap{$0.moduleAliases})\n            let depChildModules = dependencyProductModules(of: depModules)\n            let depChildAliases = toDictionary(depChildModules.compactMap{$0.moduleAliases})\n            let depChildPrechainAliases = toDictionary(depChildModules.compactMap{$0.prechainModuleAliases})\n            chainModuleAliases(modules: depModules,\n                               checkedModules: depModules,\n                               moduleAliases: depModuleAliases,\n                               childModules: depChildModules,\n                               childAliases: depChildAliases,\n                               childPrechainAliases: depChildPrechainAliases,\n                               observabilityScope: observabilityScope)\n\n            let relevantModules = depModules + curDirectModules\n            let moduleAliases = toDictionary(relevantModules.compactMap{$0.moduleAliases})\n            let depProductModules = dependencyProductModules(of: relevantModules)\n            var depProductAliases = [String: [String]]()\n            let depProductPrechainAliases = toDictionary(depProductModules.compactMap{$0.prechainModuleAliases})\n\n            for depProdModule in depProductModules {\n                let depProdModuleAliases = depProdModule.moduleAliases ?? [:]\n                for (key, val) in depProdModuleAliases {\n                    var shouldAddAliases = false\n                    if depProdModule.name == key {\n                        shouldAddAliases = true\n                    } else if !depProductModules.map({$0.name}).contains(key) {\n                        shouldAddAliases = true\n                    }\n                    if shouldAddAliases {\n                        if depProductAliases[key]?.contains(val) ?? false {\n                            // don't add a duplicate\n                        } else {\n                            depProductAliases[key, default: []].append(val)\n                        }\n                    }\n                }\n            }\n            chainModuleAliases(modules: curDirectModules,\n                               checkedModules: relevantModules,\n                               moduleAliases: moduleAliases,\n                               childModules: depProductModules,\n                               childAliases: depProductAliases,\n                               childPrechainAliases: depProductPrechainAliases,\n                               observabilityScope: observabilityScope)\n        }\n    }\n\n    // This fills in aliases for modules in products that are in the dependency\n    // chain but not in a product consumed by other packages. Such modules still\n    // need to have aliases applied to them so they can be built with correct\n    // dependent binary names\n    mutating func fillInRest(package: PackageIdentity) {\n        if let productToModules = idToProductToAllModules[package] {\n            for (_, productModules) in productToModules {\n                let unAliased = productModules.contains { $0.moduleAliases == nil }\n                if unAliased {\n                    for module in productModules {\n                        let depAliases = module.recursiveDependentModules.compactMap{$0.moduleAliases}.flatMap{$0}\n                        for (key, alias) in depAliases {\n                            appliedAliases.insert(key)\n                            module.addModuleAlias(for: key, as: alias)\n                        }\n                    }\n                }\n            }\n        }\n        guard let children = parentToChildIDs[package] else { return }\n        for child in children {\n            fillInRest(package: child)\n        }\n    }\n\n    func diagnoseUnappliedAliases(observabilityScope: ObservabilityScope) {\n        for aliasList in aliasMap.values {\n            for productAlias in aliasList {\n                if !appliedAliases.contains(productAlias.name) {\n                    observabilityScope.emit(warning: \"module alias for target '\\(productAlias.name)', declared in package '\\(productAlias.consumingPackage)', does not match any recursive target dependency of product '\\(productAlias.productName)' from package '\\(productAlias.originPackage)'\")\n                }\n            }\n        }\n    }\n\n    private mutating func chainModuleAliases(\n        modules: [Module],\n        checkedModules: [Module],\n        moduleAliases: [String: [String]],\n        childModules: [Module],\n        childAliases: [String: [String]],\n        childPrechainAliases: [String: [String]],\n        observabilityScope: ObservabilityScope\n    ) {\n        guard !modules.isEmpty else { return }\n        var aliasDict = [String: String]()\n        var prechainAliasDict = [String: [String]]()\n        var directRefAliasDict = [String: [String]]()\n        let childDirectRefAliases = toDictionary(childModules.compactMap{$0.directRefAliases})\n        for (childModuleName, childModuleAliases) in childAliases {\n            // Tracks whether to add prechain aliases to modules\n            var addPrechainAliases = false\n            // Current modules and their dependents contain this child product\n            // module name\n            if checkedModules.map(\\.name).contains(childModuleName) {\n                addPrechainAliases = true\n            }\n            if let overlappingModuleAliases = moduleAliases[childModuleName], !overlappingModuleAliases.isEmpty {\n                // Current module aliases have the same key as this child\n                // module name, so the child module alias should not be applied\n                addPrechainAliases = true\n                aliasDict[childModuleName] = overlappingModuleAliases.first\n            } else if childModuleAliases.count > 1 {\n                // Multiple aliases from different products for this child module\n                // name exist so they should not be applied; their aliases / new\n                // names should be used directly\n                addPrechainAliases = true\n            } else if childModules.filter({$0.name == childModuleName}).count > 1 {\n                // Modules from different products have the same name as this child\n                // module name, so their aliases should not be applied\n                addPrechainAliases = true\n            }\n\n            if addPrechainAliases {\n                if let prechainAliases = childPrechainAliases[childModuleName] {\n                   for prechainAliasKey in prechainAliases {\n                       if let prechainAliasVals = childPrechainAliases[prechainAliasKey] {\n                           // If aliases are chained, keep track of prechain\n                           // aliases\n                           prechainAliasDict[prechainAliasKey, default: []].append(contentsOf: prechainAliasVals)\n                           // Add prechained aliases to the list of aliases\n                           // that should be directly referenced in source code\n                           directRefAliasDict[childModuleName, default: []].append(prechainAliasKey)\n                           directRefAliasDict[prechainAliasKey, default: []].append(contentsOf: prechainAliasVals)\n                       }\n                    }\n                } else if aliasDict[childModuleName] == nil {\n                    // If not added to aliasDict, use the renamed module directly\n                    directRefAliasDict[childModuleName, default: []].append(contentsOf: childModuleAliases)\n                }\n            } else if let productModuleAlias = childModuleAliases.first {\n                if childModuleAliases.count > 1 {\n                    observabilityScope.emit(warning: \"There should be one alias for target '\\(childModuleName)' but there are [\\(childModuleAliases.map{\"'\\($0)'\"}.joined(separator: \", \"))]\")\n                }\n                // Check if not in child modules' direct ref aliases list, then add\n                if lookupAlias(value: childModuleName, in: childDirectRefAliases).isEmpty,\n                   childDirectRefAliases[childModuleName] == nil {\n                    aliasDict[childModuleName] = productModuleAlias\n                }\n            }\n        }\n\n        for module in modules {\n            for (key, val) in aliasDict {\n                appliedAliases.insert(key)\n                module.addModuleAlias(for: key, as: val)\n            }\n            for (key, valList) in prechainAliasDict {\n                if let val = valList.first,\n                    valList.count <= 1 {\n                    appliedAliases.insert(key)\n                    module.addModuleAlias(for: key, as: val)\n                    module.addPrechainModuleAlias(for: key, as: val)\n                }\n            }\n            for (key, list) in directRefAliasDict {\n                module.addDirectRefAliases(for: key, as: list)\n                observabilityScope.emit(info: \"Target '\\(module.name)' has a dependency on multiple targets named '\\(key)'; the aliased names are [\\(list.map{\"'\\($0)'\"}.joined(separator: \", \"))] and should be used directly in source code if referenced from '\\(module.name)'\")\n            }\n        }\n    }\n\n    private func lookupAlias(key: String, in buffer: [String: ModuleAliasModel]) -> String? {\n        var next = key\n        while let nextValue = buffer[next] {\n            next = nextValue.alias\n        }\n        return next == key ? nil : next\n    }\n\n    private func lookupAlias(value: String, in dict: [String: [String]]) -> [String] {\n        let keys = dict.filter{$0.value.contains(value)}.map{$0.key}\n        return keys\n    }\n\n    private func toDictionary(_ list: [[String: [String]]]) -> [String: [String]] {\n        var dict = [String: [String]]()\n        for entry in list {\n            for (entryKey, entryVal) in entry {\n                dict[entryKey, default: []].append(contentsOf: entryVal)\n            }\n        }\n        return dict\n    }\n\n    private func toDictionary(_ list: [[String: String]]) -> [String: [String]] {\n        var dict = [String: [String]]()\n        for entry in list {\n            for (entryKey, entryVal) in entry {\n                if let existing = dict[entryKey], existing.contains(entryVal) {\n                    // don't add a duplicate\n                } else {\n                    dict[entryKey, default: []].append(entryVal)\n                }\n            }\n        }\n        return dict\n    }\n\n    private func dependencyProductModules(of modules: [Module]) -> [Module] {\n        let result = modules.map{$0.dependencies.compactMap{$0.product?.identity}}.flatMap{$0}.compactMap{productToAllModules[$0]}.flatMap{$0}\n        return result\n    }\n}\n\n// Used to keep track of module alias info for each package\nprivate class ModuleAliasModel {\n    let name: String\n    var alias: String\n    let originPackage: PackageIdentity\n    let consumingPackage: PackageIdentity\n    let productName: String\n\n    init(name: String, alias: String, originPackage: PackageIdentity, consumingPackage: PackageIdentity, productName: String) {\n        self.name = name\n        self.alias = alias\n        self.originPackage = originPackage\n        self.consumingPackage = consumingPackage\n        self.productName = productName\n    }\n}\n\nextension Module {\n    func dependsOn(productID: String) -> Bool {\n        return self.dependencies.contains { dep in\n            if case let .product(prodRef, _) = dep {\n                return prodRef.identity == productID\n            }\n            return false\n        }\n    }\n\n    var recursiveDependentModules: [Module] {\n        var list = [Module]()\n        var nextDeps = self.dependencies\n        while !nextDeps.isEmpty {\n            let nextModules = nextDeps.compactMap{$0.module}\n            list.append(contentsOf: nextModules)\n            nextDeps = nextModules.map{$0.dependencies}.flatMap{$0}\n        }\n        return list\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/ModulesGraph+Loading.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport OrderedCollections\nimport PackageLoading\nimport PackageModel\nimport Foundation\n\nimport func TSCBasic.bestMatch\nimport func TSCBasic.findCycle\nimport struct TSCBasic.KeyedPair\n\nextension ModulesGraph {\n    /// Load the package graph for the given package path.\n    package static func load(\n        root: PackageGraphRoot,\n        identityResolver: IdentityResolver,\n        additionalFileRules: [FileRuleDescription] = [],\n        externalManifests: OrderedCollections.OrderedDictionary<PackageIdentity, (manifest: Manifest, fs: FileSystem)>,\n        requiredDependencies: [PackageReference] = [],\n        unsafeAllowedPackages: Set<PackageReference> = [],\n        binaryArtifacts: [PackageIdentity: [String: BinaryArtifact]],\n        prebuilts: [PackageIdentity: [String: PrebuiltLibrary]], // Product name to library mapping\n        shouldCreateMultipleTestProducts: Bool = false,\n        createREPLProduct: Bool = false,\n        customPlatformsRegistry: PlatformRegistry? = .none,\n        customXCTestMinimumDeploymentTargets: [PackageModel.Platform: PlatformVersion]? = .none,\n        testEntryPointPath: AbsolutePath? = nil,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        productsFilter: ((Product) -> Bool)? = nil,\n        modulesFilter: ((Module) -> Bool)? = nil,\n        enabledTraitsMap: EnabledTraitsMap\n    ) throws -> ModulesGraph {\n        let observabilityScope = observabilityScope.makeChildScope(description: \"Loading Package Graph\")\n\n        // Create a map of the manifests, keyed by their identity.\n        var manifestMap = externalManifests\n        // prefer roots\n        for manifest in root.manifests {\n            manifestMap[manifest.key] = (manifest.value, fileSystem)\n        }\n\n        // Construct the root dependencies set.\n        let rootDependencies = Set(root.dependencies.compactMap {\n            manifestMap[$0.identity]?.manifest\n        })\n\n        let rootManifestNodes = try root.packages.map { identity, package in\n            // If we have enabled traits passed then we start with those. If there are no enabled\n            // traits passed then the default traits will be used.\n            return try GraphLoadingNode(\n                identity: identity,\n                manifest: package.manifest,\n                productFilter: .everything,\n                enabledTraits: enabledTraitsMap[identity]\n            )\n        }\n        let rootDependencyNodes = try root.dependencies.lazy.filter { requiredDependencies.contains($0.packageRef) }\n            .compactMap { dependency in\n                try manifestMap[dependency.identity].map {\n                    try GraphLoadingNode(\n                        identity: dependency.identity,\n                        manifest: $0.manifest,\n                        productFilter: dependency.productFilter,\n                        enabledTraits: enabledTraitsMap[dependency.identity]\n                    )\n                }\n            }\n\n        let inputManifests = (rootManifestNodes + rootDependencyNodes).map {\n            KeyedPair($0, key: $0.identity)\n        }\n\n        // Collect the manifests for which we are going to build packages.\n        var allNodes = OrderedDictionary<PackageIdentity, GraphLoadingNode>()\n\n        let nodeSuccessorProvider = { (node: KeyedPair<GraphLoadingNode, PackageIdentity>) in\n            try (node.item.requiredDependencies + node.item.traitGuardedDependencies)\n                .compactMap { dependency -> KeyedPair<\n                    GraphLoadingNode,\n                    PackageIdentity\n                >? in\n                    return try manifestMap[dependency.identity].map { manifest, _ in\n                        // We are going to check the conditionally enabled traits here and enable them if\n                        // required. This checks the current node and then enables the conditional\n                        // dependencies of the dependency node.\n\n                        return try KeyedPair(\n                            GraphLoadingNode(\n                                identity: dependency.identity,\n                                manifest: manifest,\n                                productFilter: dependency.productFilter,\n                                enabledTraits: enabledTraitsMap[manifest.packageIdentity]\n                            ),\n                            key: dependency.identity\n                        )\n                    }\n                }\n        }\n\n        // Package dependency cycles feature is gated on tools version 6.0.\n        if !root.manifests.allSatisfy({ $1.toolsVersion >= .v6_0 }) {\n            if let cycle = try findCycle(inputManifests, successors: nodeSuccessorProvider) {\n                let path = (cycle.path + cycle.cycle).map(\\.item.manifest)\n                observabilityScope.emit(PackageGraphError.dependencyCycleDetected(\n                    path: path, cycle: cycle.cycle[0].item.manifest\n                ))\n\n                return try ModulesGraph(\n                    rootPackages: [],\n                    rootDependencies: [],\n                    packages: IdentifiableSet(),\n                    dependencies: requiredDependencies,\n                    binaryArtifacts: binaryArtifacts\n                )\n            }\n        }\n\n        // Cycles in dependencies don't matter as long as there are no module cycles between packages.\n        try depthFirstSearch(\n            inputManifests,\n            successors: nodeSuccessorProvider\n        ) {\n            allNodes[$0.key] = $0.item\n        } onDuplicate: { _, _ in\n            // Nothing we need to compute here.\n        }\n\n        // Create the packages.\n        var manifestToPackage: [Manifest: Package] = [:]\n        for node in allNodes.values {\n            let nodeObservabilityScope = observabilityScope.makeChildScope(\n                description: \"loading package \\(node.identity)\",\n                metadata: .packageMetadata(identity: node.identity, kind: node.manifest.packageKind)\n            )\n\n            let manifest = node.manifest\n            // Derive the path to the package.\n            //\n            // FIXME: Lift this out of the manifest.\n            let packagePath = manifest.path.parentDirectory\n            nodeObservabilityScope.trap {\n                // Create a package from the manifest and sources.\n\n                // Special case to handle: if the traits enabled for this node is simply [\"default\"],\n                // this means that we don't have any defined traits for this package and should there\n                // flatten the set to be empty for the PackageBuilder.\n                var enabledTraits = node.enabledTraits\n                if enabledTraits == [\"default\"] {\n                    enabledTraits = []\n                }\n                let builder = PackageBuilder(\n                    identity: node.identity,\n                    manifest: manifest,\n                    productFilter: node.productFilter,\n                    path: packagePath,\n                    additionalFileRules: additionalFileRules,\n                    binaryArtifacts: binaryArtifacts[node.identity] ?? [:],\n                    shouldCreateMultipleTestProducts: shouldCreateMultipleTestProducts,\n                    testEntryPointPath: testEntryPointPath,\n                    createREPLProduct: manifest.packageKind.isRoot ? createREPLProduct : false,\n                    fileSystem: fileSystem,\n                    observabilityScope: nodeObservabilityScope,\n                    enabledTraits: enabledTraits\n                )\n                let package = try builder.construct()\n                manifestToPackage[manifest] = package\n\n                // Throw if any of the non-root package is empty.\n                if package.modules.isEmpty // System packages have modules in the package but not the manifest.\n                    && package.manifest.targets\n                    .isEmpty // An unneeded dependency will not have loaded anything from the manifest.\n                    && !manifest.packageKind.isRoot\n                {\n                    throw PackageGraphError.noModules(package)\n                }\n            }\n        }\n\n        let platformVersionProvider: PlatformVersionProvider = if let customXCTestMinimumDeploymentTargets {\n            .init(implementation: .customXCTestMinimumDeploymentTargets(customXCTestMinimumDeploymentTargets))\n        } else {\n            .init(implementation: .minimumDeploymentTargetDefault)\n        }\n\n        // Resolve dependencies and create resolved packages.\n        let resolvedPackages = try createResolvedPackages(\n            nodes: Array(allNodes.values),\n            identityResolver: identityResolver,\n            manifestToPackage: manifestToPackage,\n            root: root,\n            unsafeAllowedPackages: unsafeAllowedPackages,\n            prebuilts: prebuilts,\n            platformRegistry: customPlatformsRegistry ?? .default,\n            platformVersionProvider: platformVersionProvider,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            productsFilter: productsFilter,\n            modulesFilter: modulesFilter\n        )\n\n        let rootPackages = resolvedPackages.filter { root.manifests.values.contains($0.manifest) }\n        checkAllDependenciesAreUsed(\n            packages: resolvedPackages,\n            rootPackages,\n            prebuilts: prebuilts,\n            observabilityScope: observabilityScope\n        )\n\n        return try ModulesGraph(\n            rootPackages: rootPackages,\n            rootDependencies: resolvedPackages.filter { rootDependencies.contains($0.manifest) },\n            packages: resolvedPackages,\n            dependencies: requiredDependencies,\n            binaryArtifacts: binaryArtifacts\n        )\n    }\n}\n\nprivate func checkAllDependenciesAreUsed(\n    packages: IdentifiableSet<ResolvedPackage>,\n    _ rootPackages: [ResolvedPackage],\n    prebuilts: [PackageIdentity: [String: PrebuiltLibrary]],\n    observabilityScope: ObservabilityScope\n) {\n    for package in rootPackages {\n        // List all dependency products dependent on by the package modules.\n        let productDependencies = IdentifiableSet(package.modules.flatMap { module in\n            module.dependencies.compactMap { moduleDependency in\n                switch moduleDependency {\n                case .product(let product, _):\n                    product\n                case .module:\n                    nil\n                }\n            }\n        })\n\n        // List all dependencies of modules that are guarded by a trait.\n        let traitGuardedProductDependencies = Set(package.underlying.modules.flatMap { module in\n            module.dependencies.compactMap { moduleDependency in\n                switch moduleDependency {\n                case .product(let product, let conditions):\n                    if conditions.contains(where: { $0.traitCondition != nil }) {\n                        // This is a product dependency that was enabled by a trait\n                        return product.name\n                    }\n                    return nil\n                case .module:\n                    return nil\n                }\n            }\n        })\n\n        for dependencyId in package.dependencies {\n            guard let dependency = packages[dependencyId] else {\n                observabilityScope.emit(.error(\"Unknown package: \\(dependencyId)\"))\n                return\n            }\n\n            // We continue if the dependency contains executable products to make sure we don't\n            // warn on a valid use-case for a lone dependency: swift run dependency executables.\n            guard !dependency.products.contains(where: { $0.type == .executable }) else {\n                continue\n            }\n            // Skip this check if this dependency is a system module because system module packages\n            // have no products.\n            //\n            // FIXME: Do/should we print a warning if a dependency has no products?\n            if dependency.products.isEmpty && dependency.modules.filter({ $0.type == .systemModule }).count == 1 {\n                continue\n            }\n\n            // Skip this check if this dependency contains a command plugin product.\n            if dependency.products.contains(where: \\.isCommandPlugin) {\n                continue\n            }\n\n            // Skip this check if traits are enabled since it is valid to add a dependency just\n            // to enable traits on it. This is useful if there is a transitive dependency in the graph\n            // that can be configured by enabling traits e.g. the depdency has a trait for its logging\n            // behaviour. This allows the root package to configure traits of transitive dependencies\n            // without emitting an unused dependency warning.\n            if dependency.manifest.supportsTraits {\n                continue\n            }\n\n            // Make sure that any diagnostics we emit below are associated with the package.\n            let packageDiagnosticsScope = observabilityScope.makeChildScope(\n                description: \"Package Dependency Validation\",\n                metadata: package.underlying.diagnosticsMetadata\n            )\n\n            // Otherwise emit a warning if none of the dependency package's products are used.\n            let dependencyIsUsed = dependency.products.contains { product in\n                // Don't compare by product ID, but by product name to make sure both build triples as properties of\n                // `ResolvedProduct.ID` are allowed.\n                let usedByPackage = productDependencies.contains { $0.name == product.name }\n                // We check if any of the products of this dependency is guarded by a trait.\n                let traitGuarded = traitGuardedProductDependencies.contains(product.name)\n                // Consider prebuilts as used\n                let prebuilt = prebuilts[dependency.identity]?.keys.contains(product.name) ?? false\n\n                return usedByPackage || traitGuarded || prebuilt\n            }\n\n            if !dependencyIsUsed && !observabilityScope.errorsReportedInAnyScope {\n                packageDiagnosticsScope.emit(.unusedDependency(dependency.identity.description))\n            }\n        }\n    }\n}\n\nfileprivate extension ResolvedProduct {\n    /// Returns true if and only if the product represents a command plugin module.\n    var isCommandPlugin: Bool {\n        guard type == .plugin else { return false }\n        guard let module = underlying.modules.compactMap({ $0 as? PluginModule }).first else { return false }\n        guard case .command = module.capability else { return false }\n        return true\n    }\n}\n\n/// Find all transitive dependencies between `root` and `dependency`.\n/// - root: A root package to start search from\n/// - dependency: A dependency which to find transitive dependencies for.\n/// - graph: List of resolved package builders representing a dependency graph.\n/// The function returns all possible dependency chains, each chain is a list of nodes representing transitive\n/// dependencies between `root` and `dependency`. A dependency chain\n/// \"A root depends on B, which depends on C\" is returned as [Root, B, C].\n/// If `root` doesn't actually depend on `dependency` then the function returns empty list.\nprivate func findAllTransitiveDependencies(\n    root: CanonicalPackageLocation,\n    dependency: CanonicalPackageLocation,\n    graph: [ResolvedPackageBuilder]\n) throws -> [[CanonicalPackageLocation]] {\n    let edges = try Dictionary(uniqueKeysWithValues: graph.map { try (\n        $0.package.manifest.canonicalPackageLocation,\n        Set(\n            $0.package.manifest.dependenciesRequired(for: $0.productFilter, $0.enabledTraits)\n                .map(\\.packageRef.canonicalLocation)\n        )\n    ) })\n    // Use BFS to find paths between start and finish.\n    var queue: [(CanonicalPackageLocation, [CanonicalPackageLocation])] = []\n    var foundPaths: [[CanonicalPackageLocation]] = []\n    queue.append((root, []))\n    while !queue.isEmpty {\n        let currentItem = queue.removeFirst()\n        let current = currentItem.0\n        let pathToCurrent = currentItem.1\n        if current == dependency {\n            let pathToFinish = pathToCurrent + [current]\n            foundPaths.append(pathToFinish)\n        }\n        for dependency in edges[current] ?? [] {\n            queue.append((dependency, pathToCurrent + [current]))\n        }\n    }\n    return foundPaths\n}\n\n/// Create resolved packages from the loaded packages.\nprivate func createResolvedPackages(\n    nodes: [GraphLoadingNode],\n    identityResolver: IdentityResolver,\n    manifestToPackage: [Manifest: Package],\n    // FIXME: This shouldn't be needed once <rdar://problem/33693433> is fixed.\n    root: PackageGraphRoot,\n    unsafeAllowedPackages: Set<PackageReference>,\n    prebuilts: [PackageIdentity: [String: PrebuiltLibrary]],\n    platformRegistry: PlatformRegistry,\n    platformVersionProvider: PlatformVersionProvider,\n    fileSystem: FileSystem,\n    observabilityScope: ObservabilityScope,\n    productsFilter: ((Product) -> Bool)?,\n    modulesFilter: ((Module) -> Bool)?\n) throws -> IdentifiableSet<ResolvedPackage> {\n    // Create package builder objects from the input manifests.\n    var packageBuilders: [ResolvedPackageBuilder] = nodes.compactMap { node in\n        guard let package = manifestToPackage[node.manifest] else {\n            return nil\n        }\n        let isAllowedToVendUnsafeProducts = unsafeAllowedPackages.contains { $0.identity == package.identity }\n\n        let allowedToOverride = root.manifests.values.contains(node.manifest)\n        return ResolvedPackageBuilder(\n            package,\n            productFilter: node.productFilter,\n            enabledTraits: node.enabledTraits,\n            isAllowedToVendUnsafeProducts: isAllowedToVendUnsafeProducts,\n            allowedToOverride: allowedToOverride,\n            platformVersionProvider: platformVersionProvider,\n            prebuilts: prebuilts[package.identity]\n        )\n    }\n\n    // Create a map of package builders keyed by the package identity.\n    // This is guaranteed to be unique so we can use spm_createDictionary\n    let packagesByIdentity: [PackageIdentity: ResolvedPackageBuilder] = packageBuilders.spm_createDictionary {\n        ($0.package.identity, $0)\n    }\n\n    // Resolve module aliases, if specified, for modules and their dependencies\n    // across packages. Aliasing will result in module renaming.\n    let moduleAliasingUsed = try resolveModuleAliases(\n        packageBuilders: packageBuilders,\n        observabilityScope: observabilityScope\n    )\n\n    // Scan and validate the dependencies\n    for packageBuilder in packageBuilders {\n        let package = packageBuilder.package\n\n        let packageObservabilityScope = observabilityScope.makeChildScope(\n            description: \"Validating package dependencies\",\n            metadata: package.diagnosticsMetadata\n        )\n\n        var dependencies = OrderedCollections.OrderedDictionary<PackageIdentity, ResolvedPackageBuilder>()\n        var dependenciesByNameForModuleDependencyResolution = [String: ResolvedPackageBuilder]()\n        var dependencyNamesForModuleDependencyResolutionOnly = [PackageIdentity: String]()\n\n        try package.manifest.dependenciesRequired(\n            for: packageBuilder.productFilter,\n            packageBuilder.enabledTraits\n        ).forEach { dependency in\n            let dependencyPackageRef = dependency.packageRef\n\n            // Otherwise, look it up by its identity.\n            if let resolvedPackage = packagesByIdentity[dependency.identity] {\n                // check if this resolved package already listed in the dependencies\n                // this means that the dependencies share the same identity\n                // FIXME: this works but the way we find out about this is based on a side effect, need to improve it\n                guard dependencies[resolvedPackage.package.identity] == nil else {\n                    let error = PackageGraphError.dependencyAlreadySatisfiedByIdentifier(\n                        package: package.identity.description,\n                        identity: dependency.identity,\n                        dependencyLocation: dependencyPackageRef.canonicalLocation.description,\n                        otherDependencyLocation: resolvedPackage.package.manifest.canonicalPackageLocation.description\n                    )\n                    return packageObservabilityScope.emit(error)\n                }\n\n                // check if the resolved package location is the same as the dependency one\n                // if not, this means that the dependencies share the same identity\n                // which only allowed when overriding\n                if resolvedPackage.package.manifest.canonicalPackageLocation != dependencyPackageRef\n                    .canonicalLocation && !resolvedPackage.allowedToOverride\n                {\n                    let rootPackages = packageBuilders.filter { $0.allowedToOverride == true }\n                    let dependenciesPaths = try rootPackages.map { try findAllTransitiveDependencies(\n                        root: $0.package.manifest.canonicalPackageLocation,\n                        dependency: dependencyPackageRef.canonicalLocation,\n                        graph: packageBuilders\n                    ) }.filter { !$0.isEmpty }.flatMap { $0 }\n                    let otherDependenciesPaths = try rootPackages.map { try findAllTransitiveDependencies(\n                        root: $0.package.manifest.canonicalPackageLocation,\n                        dependency: resolvedPackage.package.manifest.canonicalPackageLocation,\n                        graph: packageBuilders\n                    ) }.filter { !$0.isEmpty }.flatMap { $0 }\n                    packageObservabilityScope\n                        .emit(\n                            debug: (\n                                \"Conflicting identity for \\(dependency.identity): \" +\n                                \"chains of dependencies for \\(dependencyPackageRef.locationString): \" +\n                                \"\\(String(describing: dependenciesPaths))\"\n                            )\n                        )\n                    packageObservabilityScope\n                        .emit(\n                            debug: (\n                                \"Conflicting identity for \\(dependency.identity): \" +\n                                \"chains of dependencies for \\(resolvedPackage.package.manifest.packageLocation): \" +\n                                \"\\(String(describing: otherDependenciesPaths))\"\n                            )\n                        )\n                    let error = PackageGraphError.dependencyAlreadySatisfiedByIdentifier(\n                        package: package.identity.description,\n                        identity: dependency.identity,\n                        dependencyLocation: dependencyPackageRef.canonicalLocation.description,\n                        otherDependencyLocation: resolvedPackage.package.manifest.canonicalPackageLocation.description,\n                        dependencyPath: (dependenciesPaths.first ?? []).map(\\.description),\n                        otherDependencyPath: (otherDependenciesPaths.first ?? []).map(\\.description)\n                    )\n                    // 9/2021 this is currently emitting a warning only to support\n                    // backwards compatibility with older versions of SwiftPM that had too weak of a validation\n                    // we will upgrade this to an error in a few versions to tighten up the validation\n                    if dependency.explicitNameForModuleDependencyResolutionOnly == .none ||\n                        resolvedPackage.package.manifest.displayName == dependency\n                        .explicitNameForModuleDependencyResolutionOnly\n                    {\n                        packageObservabilityScope\n                            .emit(\n                                warning: error\n                                    .description + \" This will be escalated to an error in future versions of SwiftPM.\"\n                            )\n                    } else {\n                        return packageObservabilityScope.emit(error)\n                    }\n                } else if resolvedPackage.package.manifest.canonicalPackageLocation == dependencyPackageRef\n                    .canonicalLocation &&\n                    resolvedPackage.package.manifest.packageLocation != dependencyPackageRef.locationString &&\n                    !resolvedPackage.allowedToOverride\n                {\n                    packageObservabilityScope\n                        .emit(\n                            info: \"dependency on '\\(resolvedPackage.package.identity)' is represented by similar locations ('\\(resolvedPackage.package.manifest.packageLocation)' and '\\(dependencyPackageRef.locationString)') which are treated as the same canonical location '\\(dependencyPackageRef.canonicalLocation)'.\"\n                        )\n                }\n\n                // checks if two dependencies have the same explicit name which can cause module based dependency\n                // package lookup issue\n                if let explicitDependencyName = dependency.explicitNameForModuleDependencyResolutionOnly {\n                    if let previouslyResolvedPackage =\n                        dependenciesByNameForModuleDependencyResolution[explicitDependencyName]\n                    {\n                        let error = PackageGraphError.dependencyAlreadySatisfiedByName(\n                            package: package.identity.description,\n                            dependencyLocation: dependencyPackageRef.locationString,\n                            otherDependencyURL: previouslyResolvedPackage.package.manifest.packageLocation,\n                            name: explicitDependencyName\n                        )\n                        return packageObservabilityScope.emit(error)\n                    }\n                }\n\n                // checks if two dependencies have the same implicit (identity based) name which can cause module based\n                // dependency package lookup issue\n                if let previouslyResolvedPackage =\n                    dependenciesByNameForModuleDependencyResolution[dependency.identity.description]\n                {\n                    let error = PackageGraphError.dependencyAlreadySatisfiedByName(\n                        package: package.identity.description,\n                        dependencyLocation: dependencyPackageRef.locationString,\n                        otherDependencyURL: previouslyResolvedPackage.package.manifest.packageLocation,\n                        name: dependency.identity.description\n                    )\n                    return packageObservabilityScope.emit(error)\n                }\n\n                let nameForModuleDependencyResolution = dependency\n                    .explicitNameForModuleDependencyResolutionOnly ?? dependency.identity.description\n                dependenciesByNameForModuleDependencyResolution[nameForModuleDependencyResolution] = resolvedPackage\n                dependencyNamesForModuleDependencyResolutionOnly[resolvedPackage.package.identity] =\n                    nameForModuleDependencyResolution\n\n                dependencies[resolvedPackage.package.identity] = resolvedPackage\n            }\n        }\n\n        packageBuilder.dependencies = Array(dependencies.values)\n        packageBuilder\n            .dependencyNamesForModuleDependencyResolutionOnly = dependencyNamesForModuleDependencyResolutionOnly\n\n        packageBuilder.defaultLocalization = package.manifest.defaultLocalization\n\n        packageBuilder.supportedPlatforms = computePlatforms(\n            package: package,\n            platformRegistry: platformRegistry\n        )\n\n        // Create module builders for each module in the package.\n        let modules: [Module] = if let modulesFilter {\n            package.modules.filter(modulesFilter)\n        } else {\n            package.modules\n        }\n        let moduleBuilders = modules.map {\n            ResolvedModuleBuilder(\n                packageIdentity: package.identity,\n                module: $0,\n                observabilityScope: packageObservabilityScope,\n                platformVersionProvider: platformVersionProvider\n            )\n        }\n        packageBuilder.modules = moduleBuilders\n\n        // Establish dependencies between the modules. A module can only depend on another module present in the same\n        // package.\n        let modulesMap = moduleBuilders.spm_createDictionary { ($0.module, $0) }\n        for moduleBuilder in moduleBuilders {\n            moduleBuilder.dependencies += try moduleBuilder.module.dependencies.compactMap { dependency in\n                switch dependency {\n                case .module(let moduleDependency, let conditions):\n                    try moduleBuilder.module.validateDependency(module: moduleDependency)\n                    guard let moduleBuilder = modulesMap[moduleDependency] else {\n                        throw InternalError(\"unknown target \\(moduleDependency.name)\")\n                    }\n                    return .module(moduleBuilder, conditions: conditions)\n                case .product:\n                    return nil\n                }\n            }\n            moduleBuilder.defaultLocalization = packageBuilder.defaultLocalization\n            moduleBuilder.supportedPlatforms = packageBuilder.supportedPlatforms\n        }\n\n        // Create product builders for each product in the package. A product can only contain a module present in the\n        // same package.\n        let products: [Product] = if let productsFilter {\n            package.products.filter(productsFilter)\n        } else {\n            package.products\n        }\n\n        packageBuilder.products = try products.map { product in\n            try ResolvedProductBuilder(\n                product: product,\n                packageBuilder: packageBuilder,\n                moduleBuilders: product.modules.map {\n                    guard let module = modulesMap[$0] else {\n                        throw InternalError(\"unknown target \\($0)\")\n                    }\n                    return module\n                }\n            )\n        }\n\n        // add registry metadata if available\n        if fileSystem.exists(package.path.appending(component: RegistryReleaseMetadataStorage.fileName)) {\n            packageBuilder.registryMetadata = try RegistryReleaseMetadataStorage.load(\n                from: package.path.appending(component: RegistryReleaseMetadataStorage.fileName),\n                fileSystem: fileSystem\n            )\n        }\n    }\n\n    let dupProductsChecker = DuplicateProductsChecker(\n        packageBuilders: packageBuilders,\n        moduleAliasingUsed: moduleAliasingUsed,\n        observabilityScope: observabilityScope\n    )\n    try dupProductsChecker.run(lookupByProductIDs: moduleAliasingUsed, observabilityScope: observabilityScope)\n\n    // The set of all module names.\n    var allModuleNames = Set<String>()\n\n    // Track if multiple modules are found with the same name.\n    var foundDuplicateModule = false\n\n    for packageBuilder in packageBuilders {\n        for moduleBuilder in packageBuilder.modules {\n            // Record if we see a duplicate module.\n            foundDuplicateModule = foundDuplicateModule || !allModuleNames.insert(moduleBuilder.module.name).inserted\n        }\n    }\n\n    // Do another pass and establish product dependencies of each module.\n    for packageBuilder in packageBuilders {\n        let package = packageBuilder.package\n\n        let packageObservabilityScope = observabilityScope.makeChildScope(\n            description: \"Validating package targets\",\n            metadata: package.diagnosticsMetadata\n        )\n\n        // Get all implicit system library dependencies in this package.\n        let implicitSystemLibraryDeps = packageBuilder.dependencies\n            .flatMap(\\.modules)\n            .filter {\n                if case let systemLibrary as SystemLibraryModule = $0.module {\n                    return systemLibrary.implicit\n                }\n                return false\n            }\n\n        let packageDoesNotSupportProductAliases = packageBuilder.package.doesNotSupportProductAliases\n        let lookupByProductIDs = !packageDoesNotSupportProductAliases &&\n            (packageBuilder.package.manifest.disambiguateByProductIDs || moduleAliasingUsed)\n\n        // Get all the products from dependencies of this package.\n        let productDependencies = packageBuilder.dependencies\n            .flatMap { (dependency: ResolvedPackageBuilder) -> [ResolvedProductBuilder] in\n                // Filter out synthesized products such as tests and implicit executables.\n                // Check if a dependency product is explicitly declared as a product in its package manifest\n                let manifestProducts = dependency.package.manifest.products.lazy.map(\\.name)\n                let explicitProducts = dependency.package.products.filter { manifestProducts.contains($0.name) }\n                let explicitIdsOrNames = Set(explicitProducts.lazy.map { lookupByProductIDs ? $0.identity : $0.name })\n                return dependency.products\n                    .filter {\n                        lookupByProductIDs ? explicitIdsOrNames.contains($0.product.identity) : explicitIdsOrNames\n                            .contains($0.product.name)\n                    }\n            }\n\n        let productDependencyMap: [String: ResolvedProductBuilder] = if lookupByProductIDs {\n            try Dictionary(uniqueKeysWithValues: productDependencies.map {\n                guard let packageName = packageBuilder\n                    .dependencyNamesForModuleDependencyResolutionOnly[$0.packageBuilder.package.identity]\n                else {\n                    throw InternalError(\n                        \"could not determine name for dependency on package '\\($0.packageBuilder.package.identity)' from package '\\(packageBuilder.package.identity)'\"\n                    )\n                }\n                let key = \"\\(packageName.lowercased())_\\($0.product.name)\"\n                return (key, $0)\n            })\n        } else {\n            try Dictionary(\n                productDependencies.map { ($0.product.name, $0) },\n                uniquingKeysWith: { lhs, _ in\n                    let duplicates = productDependencies.filter { $0.product.name == lhs.product.name }\n                    throw emitDuplicateProductDiagnostic(\n                        productName: lhs.product.name,\n                        packages: duplicates.map(\\.packageBuilder.package),\n                        moduleAliasingUsed: moduleAliasingUsed,\n                        observabilityScope: observabilityScope\n                    )\n                }\n            )\n        }\n\n        // Establish dependencies in each module.\n        for moduleBuilder in packageBuilder.modules {\n            // Directly add all the system module dependencies.\n            moduleBuilder.dependencies += implicitSystemLibraryDeps.map { .module($0, conditions: []) }\n\n            // Establish product dependencies.\n            for case .product(let productRef, let conditions) in moduleBuilder.module.dependencies {\n                // Find the product in this package's dependency products.\n                // Look it up by ID if module aliasing is used, otherwise by name.\n                let product = lookupByProductIDs ? productDependencyMap[productRef.identity] :\n                    productDependencyMap[productRef.name]\n                guard let product else {\n                    // Only emit a diagnostic if there are no other diagnostics.\n                    // This avoids flooding the diagnostics with product not\n                    // found errors when there are more important errors to\n                    // resolve (like authentication issues).\n                    if !observabilityScope.errorsReportedInAnyScope {\n                        let error = prepareProductDependencyNotFoundError(\n                            packageBuilder: packageBuilder,\n                            moduleBuilder: moduleBuilder,\n                            dependency: productRef,\n                            lookupByProductIDs: lookupByProductIDs\n                        )\n                        packageObservabilityScope.emit(error)\n                    }\n                    continue\n                }\n\n                // Starting in 5.2, and module-based dependency, we require module product dependencies to\n                // explicitly reference the package containing the product, or for the product, package and\n                // dependency to share the same name. We don't check this in manifest loading for root-packages so\n                // we can provide a more detailed diagnostic here.\n                if packageBuilder.package.manifest.toolsVersion >= .v5_2 && productRef.package == nil {\n                    let referencedPackageIdentity = product.packageBuilder.package.identity\n                    guard let referencedPackageDependency = (\n                        packageBuilder.package.manifest.dependencies\n                            .first { package in\n                                package.identity == referencedPackageIdentity\n                            }\n                    ) else {\n                        throw InternalError(\n                            \"dependency reference for \\(product.packageBuilder.package.manifest.packageLocation) not found\"\n                        )\n                    }\n                    let referencedPackageName = referencedPackageDependency.nameForModuleDependencyResolutionOnly\n                    if productRef.name != referencedPackageName {\n                        let error = PackageGraphError.productDependencyMissingPackage(\n                            productName: productRef.name,\n                            moduleName: moduleBuilder.module.name,\n                            packageIdentifier: referencedPackageName\n                        )\n                        packageObservabilityScope.emit(error)\n                    }\n                }\n\n                moduleBuilder.dependencies.append(.product(product, conditions: conditions))\n            }\n        }\n    }\n\n    // If a module with similar name was encountered before, we emit a diagnostic.\n    if foundDuplicateModule {\n        var duplicateModules = [String: [Package]]()\n        for moduleName in Set(allModuleNames).sorted() {\n            let packages = packageBuilders\n                .filter { $0.modules.contains(where: { $0.module.name == moduleName }) }\n                .map(\\.package)\n            if packages.count > 1 {\n                duplicateModules[moduleName, default: []].append(contentsOf: packages)\n            }\n        }\n\n        var potentiallyDuplicatePackages = [Pair: [String]]()\n        for entry in duplicateModules {\n            // the duplicate is across exactly two packages\n            if entry.value.count == 2 {\n                potentiallyDuplicatePackages[Pair(package1: entry.value[0], package2: entry.value[1]), default: []]\n                    .append(entry.key)\n            }\n        }\n\n        var duplicateModulesAddressed = [String]()\n        for potentiallyDuplicatePackage in potentiallyDuplicatePackages {\n            // more than three module matches, or all modules in the package match\n            if potentiallyDuplicatePackage.value.count > 3 ||\n                (\n                    potentiallyDuplicatePackage.value.sorted() == potentiallyDuplicatePackage.key.package1.modules\n                        .map(\\.name).sorted()\n                        &&\n                        potentiallyDuplicatePackage.value.sorted() == potentiallyDuplicatePackage.key.package2.modules\n                        .map(\\.name).sorted()\n                )\n            {\n                switch (\n                    potentiallyDuplicatePackage.key.package1.identity.registry,\n                    potentiallyDuplicatePackage.key.package2.identity.registry\n                ) {\n                case (.some(let registryIdentity), .none):\n                    observabilityScope.emit(\n                        ModuleError.duplicateModulesScmAndRegistry(\n                            registryPackage: registryIdentity,\n                            scmPackage: potentiallyDuplicatePackage.key.package2.identity,\n                            modules: potentiallyDuplicatePackage.value\n                        )\n                    )\n                case (.none, .some(let registryIdentity)):\n                    observabilityScope.emit(\n                        ModuleError.duplicateModulesScmAndRegistry(\n                            registryPackage: registryIdentity,\n                            scmPackage: potentiallyDuplicatePackage.key.package1.identity,\n                            modules: potentiallyDuplicatePackage.value\n                        )\n                    )\n                default:\n                    observabilityScope.emit(\n                        ModuleError.duplicateModules(\n                            package: potentiallyDuplicatePackage.key.package1.identity,\n                            otherPackage: potentiallyDuplicatePackage.key.package2.identity,\n                            modules: potentiallyDuplicatePackage.value\n                        )\n                    )\n                }\n                duplicateModulesAddressed += potentiallyDuplicatePackage.value\n            }\n        }\n\n        for entry in duplicateModules.filter({ !duplicateModulesAddressed.contains($0.key) }) {\n            observabilityScope.emit(\n                ModuleError.duplicateModule(\n                    moduleName: entry.key,\n                    packages: entry.value.map(\\.identity)\n                )\n            )\n        }\n    }\n\n    do {\n        let moduleBuilders = packageBuilders.flatMap {\n            $0.modules.map {\n                KeyedPair($0, key: $0.module)\n            }\n        }\n        if let cycle = findCycle(moduleBuilders, successors: {\n            $0.item.dependencies.flatMap {\n                switch $0 {\n                case .product(let productBuilder, conditions: _):\n                    return productBuilder.moduleBuilders.map { KeyedPair($0, key: $0.module) }\n                case .module:\n                    return [] // local modules were checked by PackageBuilder.\n                }\n            }\n        }) {\n            observabilityScope.emit(\n                ModuleError.cycleDetected(\n                    (cycle.path.map(\\.key.name), cycle.cycle.map(\\.key.name))\n                )\n            )\n            return IdentifiableSet()\n        }\n    }\n\n    // Adjust the package graph for any prebuilts, removing any that are no longer needed.\n    handlePrebuilts(packageBuilders: packageBuilders, root: root)\n\n    return try IdentifiableSet(packageBuilders.map { try $0.construct() })\n}\n\n// Adjust the graph to integrate prebuilts\nprivate func handlePrebuilts(packageBuilders: [ResolvedPackageBuilder], root: PackageGraphRoot) {\n    // Skip this if there are no prebuilts. Modules are unconstrained by default.\n    guard packageBuilders.contains(where: { $0.prebuilts != nil }) else {\n        return\n    }\n\n    // First decorate the platform constraints from products in the root packages\n    for packageBuilder in packageBuilders where root.isExporting(packageBuilder.package.identity) {\n        for productBuilder in packageBuilder.products {\n            for moduleBuilder in productBuilder.moduleBuilders {\n                func markExternal(_ depModule: ResolvedModuleBuilder) {\n                    guard depModule.platformConstraint != .all else {\n                        return\n                    }\n                    guard !depModule.isHostOnly else {\n                        // Macros, macro tests, and plugins are host only\n                        return\n                    }\n                    depModule.platformConstraint = .all\n                    for dep in depModule.allModuleDependencies {\n                        markExternal(dep)\n                    }\n                }\n                markExternal(moduleBuilder)\n            }\n        }\n    }\n\n    // Find those not marked that are references from macro and plugins.\n    // For now we can't have host modules depending on .all modules so only\n    // mark as .host if all the deps are .host\n    for packageBuilder in packageBuilders {\n        for moduleBuilder in packageBuilder.modules where moduleBuilder.isHostOnly {\n            func markHost(_ depModule: ResolvedModuleBuilder) -> Bool {\n                switch depModule.platformConstraint {\n                case .all:\n                    return false\n                case .host:\n                    return true\n                case .none:\n                    break\n                }\n\n                for dep in depModule.allModuleDependencies {\n                    if !markHost(dep) {\n                        // Depending on .all, revisit all deps and mark .all so we don't mix\n                        func markExternal(_ depModule: ResolvedModuleBuilder) {\n                            guard depModule.platformConstraint == .host else {\n                                return\n                            }\n                            depModule.platformConstraint = .all\n                            for dep in depModule.allModuleDependencies {\n                                markExternal(dep)\n                            }\n                        }\n                        markExternal(depModule)\n                        return false\n                    }\n                }\n                depModule.platformConstraint = .host\n                return true\n            }\n            _ = markHost(moduleBuilder)\n        }\n    }\n\n    // Also for now, to ensure we're not mixing prebuilts and not prebuilts in the build graph,\n    // Only use prebuilts if we can use them for all host only modules\n    guard packageBuilders.allSatisfy({\n        $0.modules.allSatisfy { moduleBuilder in\n            guard moduleBuilder.isHostOnly else {\n                return true\n            }\n            return moduleBuilder.platformConstraint == .host\n        }\n    }) else {\n        // Remove the platform constraints\n        for packageBuilder in packageBuilders {\n            for moduleBuilder in packageBuilder.modules {\n                moduleBuilder.platformConstraint = nil\n            }\n        }\n        return\n    }\n\n    // find uses of prebuilts and adjust the modules to use them\n    for packageBuilder in packageBuilders {\n        for moduleBuilder in packageBuilder.modules {\n            guard moduleBuilder.platformConstraint == .host else {\n                // Prebuilts are host only for now\n                continue\n            }\n\n            let prebuiltDeps: [ResolvedProductBuilder] = moduleBuilder.dependencies.compactMap {\n                guard case .product(let productBuilder, conditions: _) = $0,\n                      productBuilder.packageBuilder.prebuilts?[productBuilder.product.name] != nil\n                else {\n                    return nil\n                }\n                return productBuilder\n            }\n\n            guard !prebuiltDeps.isEmpty else {\n                continue\n            }\n\n            // Filter out the deps from the prebuilts' products\n            moduleBuilder.dependencies = moduleBuilder.dependencies.filter {\n                guard case .product(let productBuilder, conditions: _) = $0,\n                      productBuilder.packageBuilder.prebuilts?[productBuilder.product.name] != nil\n                else {\n                    return true\n                }\n                return false\n            }\n\n            // Add build settings to hook up the prebuilts\n            // TODO: prebuilts should really be modules e.g system libraries\n            // TODO: so we don't have to alter the underyling modules build settings\n            let prebuiltLibraries = prebuiltDeps.reduce(into: [String: PrebuiltLibrary]()) {\n                guard let prebuilt = $1.packageBuilder.prebuilts?[$1.product.name] else {\n                    return\n                }\n                $0[prebuilt.libraryName] = prebuilt\n            }\n\n            for prebuilt in prebuiltLibraries.values {\n                var libPathAssignment = BuildSettings.Assignment()\n                libPathAssignment.values.append(prebuilt.path.appending(component: \"lib\").pathString)\n                moduleBuilder.module.buildSettings.add(libPathAssignment, for: .PREBUILT_LIBRARY_PATHS)\n\n                var libsAssignment = BuildSettings.Assignment()\n                libsAssignment.values.append(prebuilt.libraryName)\n                moduleBuilder.module.buildSettings.add(libsAssignment, for: .PREBUILT_LIBRARIES)\n\n                var includeAssignment = BuildSettings.Assignment()\n                includeAssignment.values.append(prebuilt.path.appending(component: \"Modules\").pathString)\n                if let checkoutPath = prebuilt.checkoutPath, let includePath = prebuilt.includePath {\n                    for includeDir in includePath {\n                        includeAssignment.values.append(checkoutPath.appending(includeDir).pathString)\n                    }\n                } else {\n                    for cModule in prebuilt.cModules {\n                        includeAssignment.values.append(prebuilt.path.appending(components: \"include\", cModule).pathString)\n                    }\n                }\n                moduleBuilder.module.buildSettings.add(includeAssignment, for: .PREBUILT_INCLUDE_PATHS)\n            }\n        }\n    }\n\n    // Remove the package dependencies to the prebuilts if they are no longer used\n    let nonPrebuilts = packageBuilders.filter { $0.prebuilts == nil }\n    for packageBuilder in packageBuilders where packageBuilder.prebuilts != nil {\n        for nonPrebuilt in nonPrebuilts {\n            if nonPrebuilt.modules.allSatisfy({\n                $0.dependencies.allSatisfy {\n                    switch $0 {\n                    case .module:\n                        return true\n                    case .product(let product, conditions: _):\n                        return product.packageBuilder.package.identity != packageBuilder.package.identity\n                    }\n                }\n            }) {\n                nonPrebuilt.dependencies = nonPrebuilt.dependencies.filter {\n                    $0.package.identity != packageBuilder.package.identity\n                }\n            }\n        }\n    }\n}\n\nprivate func prepareProductDependencyNotFoundError(\n    packageBuilder: ResolvedPackageBuilder,\n    moduleBuilder: ResolvedModuleBuilder,\n    dependency: Module.ProductReference,\n    lookupByProductIDs: Bool\n) -> PackageGraphError {\n    let packageName = packageBuilder.package.identity.description\n    // Module's dependency is either a local module or a product from another package.\n    // If dependency is a product from the current package, that's an incorrect\n    // declaration of the dependency and we should show relevant error. Let's see\n    // if indeed the dependency matches any of the products.\n    let declProductsAsDependency = packageBuilder.package.products.filter { product in\n        lookupByProductIDs ? product.identity == dependency.identity : product.name == dependency.name\n    }.flatMap(\\.modules).filter { t in\n        t.name != dependency.name\n    }\n    if !declProductsAsDependency.isEmpty {\n        return PackageGraphError.productDependencyNotFound(\n            package: packageName,\n            moduleName: moduleBuilder.module.name,\n            dependencyProductName: dependency.name,\n            dependencyPackageName: dependency.package,\n            dependencyProductInDecl: true,\n            similarProductName: nil,\n            packageContainingSimilarProduct: nil\n        )\n    }\n\n    // If dependency name is a typo, find best possible match from the available destinations.\n    // Depending on how the dependency is declared, \"available destinations\" might be:\n    // - modules within the current package\n    // - products across all packages in the graph\n    // - products from a specific package\n    var packageContainingBestMatchedProduct: String?\n    var bestMatchedProductName: String?\n    if dependency.package == nil {\n        // First assume it's a dependency on modules within the same package.\n        let localModules = Array(packageBuilder.modules.map(\\.module.name).filter { $0 != moduleBuilder.module.name })\n        bestMatchedProductName = bestMatch(for: dependency.name, from: localModules)\n        if bestMatchedProductName != nil {\n            return PackageGraphError.productDependencyNotFound(\n                package: packageName,\n                moduleName: moduleBuilder.module.name,\n                dependencyProductName: dependency.name,\n                dependencyPackageName: nil,\n                dependencyProductInDecl: false,\n                similarProductName: bestMatchedProductName,\n                packageContainingSimilarProduct: nil\n            )\n        }\n        // Since there's no package name in the dependency declaration, and no match across\n        // the local modules, we assume the user actually meant to use product dependency,\n        // but didn't specify package to use the product from. Since products are globally\n        // unique, we should be able to find a good match across the graph, if the package\n        // is already a part of the dependency tree.\n        let availableProducts = Dictionary(\n            uniqueKeysWithValues: packageBuilder.dependencies\n                .flatMap { (packageDep: ResolvedPackageBuilder) -> [(\n                    String,\n                    String\n                )] in\n                    let manifestProducts = packageDep.package.manifest.products.map(\\.name)\n                    let explicitProducts = packageDep.package.products.filter { manifestProducts.contains($0.name) }\n                    let explicitIdsOrNames = Set(explicitProducts.map { lookupByProductIDs ? $0.identity : $0.name })\n                    return explicitIdsOrNames.map { ($0, packageDep.package.identity.description) }\n                }\n        )\n        bestMatchedProductName = bestMatch(for: dependency.name, from: Array(availableProducts.keys))\n        if bestMatchedProductName != nil {\n            packageContainingBestMatchedProduct = availableProducts[bestMatchedProductName!]\n        }\n        return PackageGraphError.productDependencyNotFound(\n            package: packageName,\n            moduleName: moduleBuilder.module.name,\n            dependencyProductName: dependency.name,\n            dependencyPackageName: nil,\n            dependencyProductInDecl: false,\n            similarProductName: bestMatchedProductName,\n            packageContainingSimilarProduct: packageContainingBestMatchedProduct\n        )\n    } else {\n        // Package is explicitly listed in the product dependency, we shall search\n        // within the products from that package.\n        let availableProducts = packageBuilder.dependencies\n            .filter { $0.package.identity.description == dependency.package }\n            .flatMap { (packageDep: ResolvedPackageBuilder) -> [String] in\n                let manifestProducts = packageDep.package.manifest.products.map(\\.name)\n                let explicitProducts = packageDep.package.products.filter { manifestProducts.contains($0.name) }\n                let explicitIdsOrNames = Set(explicitProducts.map { lookupByProductIDs ? $0.identity : $0.name })\n                return Array(explicitIdsOrNames)\n            }\n        bestMatchedProductName = bestMatch(for: dependency.name, from: availableProducts)\n        return PackageGraphError.productDependencyNotFound(\n            package: packageName,\n            moduleName: moduleBuilder.module.name,\n            dependencyProductName: dependency.name,\n            dependencyPackageName: dependency.package,\n            dependencyProductInDecl: false,\n            similarProductName: bestMatchedProductName,\n            packageContainingSimilarProduct: dependency.package\n        )\n    }\n}\n\nprivate func emitDuplicateProductDiagnostic(\n    productName: String,\n    packages: [Package],\n    moduleAliasingUsed: Bool,\n    observabilityScope: ObservabilityScope\n) -> PackageGraphError {\n    if moduleAliasingUsed {\n        for package in packages.filter(\\.doesNotSupportProductAliases) {\n            // Emit an additional warning about product aliasing in case of older tools-versions.\n            observabilityScope\n                .emit(\n                    warning: \"product aliasing requires tools-version 5.2 or later, so it is not supported by '\\(package.identity.description)'\"\n                )\n        }\n    }\n    return PackageGraphError.duplicateProduct(\n        product: productName,\n        packages: packages\n    )\n}\n\nprivate func calculateEnabledTraits(\n    parentPackage: PackageIdentity?,\n    identity: PackageIdentity,\n    manifest: Manifest,\n    explictlyEnabledTraits: Set<String>?\n) throws -> Set<String> {\n    // This the point where we flatten the enabled traits and resolve the recursive traits\n    var recursiveEnabledTraits = explictlyEnabledTraits ?? []\n    let areDefaultsEnabled = recursiveEnabledTraits.remove(\"default\") != nil\n\n    // We are going to calculate which traits are actually enabled for a node here. To do this\n    // we have to check if default traits should be used and then flatten all the enabled traits.\n    for trait in recursiveEnabledTraits {\n        // Check if the enabled trait is a valid trait\n        if manifest.traits.first(where: { $0.name == trait }) == nil {\n            // The enabled trait is invalid\n            throw ModuleError.invalidTrait(package: identity, trait: trait)\n        }\n    }\n\n    if let parentPackage, !(explictlyEnabledTraits == nil || areDefaultsEnabled) && !manifest.supportsTraits {\n        // We throw an error when default traits are disabled for a package without any traits\n        // This allows packages to initially move new API behind traits once.\n        throw ModuleError.disablingDefaultTraitsOnEmptyTraits(\n            parentPackage: parentPackage,\n            packageName: manifest.displayName\n        )\n    }\n\n    // We have to enable all default traits if no traits are enabled or the defaults are explicitly enabled\n    if explictlyEnabledTraits == nil || areDefaultsEnabled {\n        recursiveEnabledTraits.formUnion(manifest.traits.first { $0.name == \"default\" }?.enabledTraits ?? [])\n    }\n\n    while true {\n        let flattendEnabledTraits = Set(\n            manifest.traits\n                .lazy\n                .filter { recursiveEnabledTraits.contains($0.name) }\n                .map(\\.enabledTraits)\n                .joined()\n        )\n        let newRecursiveEnabledTraits = recursiveEnabledTraits.union(flattendEnabledTraits)\n        if newRecursiveEnabledTraits.count == recursiveEnabledTraits.count {\n            break\n        } else {\n            recursiveEnabledTraits = newRecursiveEnabledTraits\n        }\n    }\n\n    return recursiveEnabledTraits\n}\n\nextension Package {\n    fileprivate var doesNotSupportProductAliases: Bool {\n        // We can never use the identity based lookup for older packages because they lack the necessary information.\n        self.manifest.toolsVersion < .v5_2\n    }\n}\n\nprivate struct Pair: Hashable {\n    let package1: Package\n    let package2: Package\n\n    static func == (lhs: Pair, rhs: Pair) -> Bool {\n        lhs.package1.identity == rhs.package1.identity &&\n            lhs.package2.identity == rhs.package2.identity\n    }\n\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(self.package1.identity)\n        hasher.combine(self.package2.identity)\n    }\n}\n\nextension Product {\n    fileprivate var isDefaultLibrary: Bool {\n        type == .library(.automatic)\n    }\n}\n\nprivate class DuplicateProductsChecker {\n    var packageIDToBuilder = [PackageIdentity: ResolvedPackageBuilder]()\n    var checkedPkgIDs = [PackageIdentity]()\n\n    let moduleAliasingUsed: Bool\n    let observabilityScope: ObservabilityScope\n\n    init(packageBuilders: [ResolvedPackageBuilder], moduleAliasingUsed: Bool, observabilityScope: ObservabilityScope) {\n        for packageBuilder in packageBuilders {\n            let pkgID = packageBuilder.package.identity\n            self.packageIDToBuilder[pkgID] = packageBuilder\n        }\n        self.moduleAliasingUsed = moduleAliasingUsed\n        self.observabilityScope = observabilityScope\n    }\n\n    func run(lookupByProductIDs: Bool = false, observabilityScope: ObservabilityScope) throws {\n        var productToPkgMap = [String: Set<PackageIdentity>]()\n        for (pkgID, pkgBuilder) in self.packageIDToBuilder {\n            let useProductIDs = pkgBuilder.package.manifest.disambiguateByProductIDs || lookupByProductIDs\n            let depProductRefs = pkgBuilder.package.modules.map(\\.dependencies).flatMap { $0 }.compactMap(\\.product)\n            for depRef in depProductRefs {\n                if let depPkg = depRef.package.map(PackageIdentity.plain) {\n                    if !self.checkedPkgIDs.contains(depPkg) {\n                        self.checkedPkgIDs.append(depPkg)\n                    }\n                    let depProductIDs = self.packageIDToBuilder[depPkg]?.package.products\n                        .filter { $0.identity == depRef.identity }\n                        .map { useProductIDs && $0.isDefaultLibrary ? $0.identity : $0.name } ?? []\n                    for depID in depProductIDs {\n                        productToPkgMap[depID, default: .init()].insert(depPkg)\n                    }\n                } else {\n                    let depPkgs = pkgBuilder.dependencies\n                        .filter { $0.products.contains { $0.product.name == depRef.name }}.map(\\.package.identity)\n                    productToPkgMap[depRef.name, default: .init()].formUnion(Set(depPkgs))\n                    self.checkedPkgIDs.append(contentsOf: depPkgs)\n                }\n                if !self.checkedPkgIDs.contains(pkgID) {\n                    self.checkedPkgIDs.append(pkgID)\n                }\n            }\n            for (depIDOrName, depPkgs) in productToPkgMap.filter({ Set($0.value).count > 1 }) {\n                let name = depIDOrName.components(separatedBy: \"_\").dropFirst().joined(separator: \"_\")\n                throw emitDuplicateProductDiagnostic(\n                    productName: name.isEmpty ? depIDOrName : name,\n                    packages: depPkgs.compactMap { self.packageIDToBuilder[$0]?.package },\n                    moduleAliasingUsed: self.moduleAliasingUsed,\n                    observabilityScope: self.observabilityScope\n                )\n            }\n        }\n\n        // Check packages that exist but are not in a dependency graph\n        let untrackedPkgs = self.packageIDToBuilder.filter { !self.checkedPkgIDs.contains($0.key) }\n        for (pkgID, pkgBuilder) in untrackedPkgs {\n            for product in pkgBuilder.products {\n                // Check if checking product ID only is safe\n                let useIDOnly = lookupByProductIDs && product.product.isDefaultLibrary\n                if !useIDOnly {\n                    // This untracked pkg could have a product name conflicting with a\n                    // product name from another package, but since it's not depended on\n                    // by other packages, keep track of both this product's name and ID\n                    // just in case other packages are < .v5_8\n                    productToPkgMap[product.product.name, default: .init()].insert(pkgID)\n                }\n                productToPkgMap[product.product.identity, default: .init()].insert(pkgID)\n            }\n        }\n\n        let duplicates = productToPkgMap.filter { $0.value.count > 1 }\n        for (productName, pkgs) in duplicates {\n            throw emitDuplicateProductDiagnostic(\n                productName: productName,\n                packages: pkgs.compactMap { self.packageIDToBuilder[$0]?.package },\n                moduleAliasingUsed: self.moduleAliasingUsed,\n                observabilityScope: self.observabilityScope\n            )\n        }\n    }\n}\n\nprivate func computePlatforms(\n    package: Package,\n    platformRegistry: PlatformRegistry\n) -> [SupportedPlatform] {\n    // the supported platforms as declared in the manifest\n    let declaredPlatforms: [SupportedPlatform] = package.manifest.platforms.map { platform in\n        let declaredPlatform = platformRegistry.platformByName[platform.platformName]\n            ?? PackageModel.Platform.custom(name: platform.platformName, oldestSupportedVersion: platform.version)\n        return SupportedPlatform(\n            platform: declaredPlatform,\n            version: .init(platform.version),\n            options: platform.options\n        )\n    }\n\n    return declaredPlatforms.sorted(by: { $0.platform.name < $1.platform.name })\n}\n\n// Track and override module aliases specified for modules in a package graph\nprivate func resolveModuleAliases(\n    packageBuilders: [ResolvedPackageBuilder],\n    observabilityScope: ObservabilityScope\n) throws -> Bool {\n    // If there are no module aliases specified, return early\n    let hasAliases = packageBuilders.contains { $0.package.modules.contains {\n        $0.dependencies.contains { dep in\n            if case .product(let prodRef, _) = dep {\n                return prodRef.moduleAliases != nil\n            }\n            return false\n        }\n    }\n    }\n\n    guard hasAliases else { return false }\n    var aliasTracker = ModuleAliasTracker()\n    for packageBuilder in packageBuilders {\n        try aliasTracker.addModuleAliases(\n            modules: packageBuilder.package.modules,\n            package: packageBuilder.package.identity\n        )\n    }\n\n    // Track modules that need module aliases for each package\n    for packageBuilder in packageBuilders {\n        for product in packageBuilder.package.products {\n            aliasTracker.trackModulesPerProduct(\n                product: product,\n                package: packageBuilder.package.identity\n            )\n        }\n    }\n\n    // Override module aliases upstream if needed\n    aliasTracker.propagateAliases(observabilityScope: observabilityScope)\n\n    // Validate sources (Swift files only) for modules being aliased.\n    // Needs to be done after `propagateAliases` since aliases defined\n    // upstream can be overridden.\n    for packageBuilder in packageBuilders {\n        for product in packageBuilder.package.products {\n            try aliasTracker.validateAndApplyAliases(\n                product: product,\n                package: packageBuilder.package.identity,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    // Emit diagnostics for any module aliases that did not end up being applied.\n    aliasTracker.diagnoseUnappliedAliases(observabilityScope: observabilityScope)\n\n    return true\n}\n\n/// A generic builder for `Resolved` models.\nprivate class ResolvedBuilder<T> {\n    /// The constructed object, available after the first call to `construct()`.\n    private var _constructedObject: T?\n\n    /// Construct the object with the accumulated data.\n    ///\n    /// Note that once the object is constructed, future calls to\n    /// this method will return the same object.\n    final func construct() throws -> T {\n        if let _constructedObject {\n            return _constructedObject\n        }\n        let constructedObject = try self.constructImpl()\n        _constructedObject = constructedObject\n        return constructedObject\n    }\n\n    /// The object construction implementation.\n    func constructImpl() throws -> T {\n        fatalError(\"Should be implemented by subclasses\")\n    }\n}\n\n/// Builder for resolved product.\nprivate final class ResolvedProductBuilder: ResolvedBuilder<ResolvedProduct> {\n    /// The reference to its package.\n    unowned let packageBuilder: ResolvedPackageBuilder\n\n    /// The product reference.\n    let product: Product\n\n    /// The module builders in the product.\n    let moduleBuilders: [ResolvedModuleBuilder]\n\n    init(product: Product, packageBuilder: ResolvedPackageBuilder, moduleBuilders: [ResolvedModuleBuilder]) {\n        self.product = product\n        self.packageBuilder = packageBuilder\n        self.moduleBuilders = moduleBuilders\n    }\n\n    override func constructImpl() throws -> ResolvedProduct {\n        try ResolvedProduct(\n            packageIdentity: self.packageBuilder.package.identity,\n            product: self.product,\n            modules: IdentifiableSet(self.moduleBuilders.map { try $0.construct() })\n        )\n    }\n}\n\n/// Builder for resolved module.\nprivate final class ResolvedModuleBuilder: ResolvedBuilder<ResolvedModule> {\n    /// Enumeration to represent module dependencies.\n    enum Dependency {\n        /// Dependency to another module, with conditions.\n        case module(_ module: ResolvedModuleBuilder, conditions: [PackageCondition])\n\n        /// Dependency to a product, with conditions.\n        case product(_ product: ResolvedProductBuilder, conditions: [PackageCondition])\n    }\n\n    /// The reference to its package.\n    let packageIdentity: PackageIdentity\n\n    /// The module reference.\n    let module: Module\n\n    /// The module dependencies of this module.\n    var dependencies: [Dependency] = []\n\n    /// All the modules this module depends on ignoring the conditions\n    var allModuleDependencies: [ResolvedModuleBuilder] {\n        dependencies.flatMap {\n            switch $0 {\n            case .module(let childModule, conditions: _):\n                return [childModule]\n            case .product(let childProduct, conditions: _):\n                return childProduct.moduleBuilders\n            }\n        }\n    }\n\n    /// The defaultLocalization for this package\n    var defaultLocalization: String? = nil\n\n    /// The platforms supported by this package.\n    var supportedPlatforms: [SupportedPlatform] = []\n\n    /// A constraint on which platforms this module needs to build for.\n    var platformConstraint: PlatformConstraint? = nil\n\n    var isHostOnly: Bool {\n        module.type == .macro || (module.type == .test && dependencies.contains(where: {\n                switch $0 {\n                case .product(let productDependency, _):\n                    productDependency.product.type == .macro\n                case .module(let moduleDependency, _):\n                    moduleDependency.module.type == .macro\n                }\n            })\n        )\n    }\n\n    let observabilityScope: ObservabilityScope\n    let platformVersionProvider: PlatformVersionProvider\n\n    init(\n        packageIdentity: PackageIdentity,\n        module: Module,\n        observabilityScope: ObservabilityScope,\n        platformVersionProvider: PlatformVersionProvider\n    ) {\n        self.packageIdentity = packageIdentity\n        self.module = module\n        self.observabilityScope = observabilityScope\n        self.platformVersionProvider = platformVersionProvider\n    }\n\n    override func constructImpl() throws -> ResolvedModule {\n        let diagnosticsEmitter = self.observabilityScope.makeDiagnosticsEmitter {\n            var metadata = ObservabilityMetadata()\n            metadata.moduleName = self.module.name\n            return metadata\n        }\n\n        let dependencies = try self.dependencies.map { dependency -> ResolvedModule.Dependency in\n            switch dependency {\n            case .module(let moduleBuilder, let conditions):\n                return try .module(moduleBuilder.construct(), conditions: conditions)\n            case .product(let productBuilder, let conditions):\n                try self.module.validateDependency(\n                    product: productBuilder.product,\n                    productPackage: productBuilder.packageBuilder.package.identity\n                )\n                let product = try productBuilder.construct()\n                if !productBuilder.packageBuilder.isAllowedToVendUnsafeProducts {\n                    try product.diagnoseInvalidUseOfUnsafeFlags(diagnosticsEmitter)\n                }\n                return .product(product, conditions: conditions)\n            }\n        }\n\n        return ResolvedModule(\n            packageIdentity: self.packageIdentity,\n            underlying: self.module,\n            dependencies: dependencies,\n            defaultLocalization: self.defaultLocalization,\n            supportedPlatforms: self.supportedPlatforms,\n            // maintain existing functionality and default to .all\n            platformConstraint: self.platformConstraint ?? .all,\n            platformVersionProvider: self.platformVersionProvider\n        )\n    }\n}\n\nextension Module {\n    func validateDependency(module: Module) throws {\n        if self.type == .plugin && module.type == .library {\n            throw PackageGraphError.unsupportedPluginDependency(\n                moduleName: self.name,\n                dependencyName: module.name,\n                dependencyType: module.type.rawValue,\n                dependencyPackage: nil\n            )\n        }\n    }\n\n    func validateDependency(product: Product, productPackage: PackageIdentity) throws {\n        if self.type == .plugin && product.type.isLibrary {\n            throw PackageGraphError.unsupportedPluginDependency(\n                moduleName: self.name,\n                dependencyName: product.name,\n                dependencyType: product.type.description,\n                dependencyPackage: productPackage.description\n            )\n        }\n    }\n}\n\n/// Builder for resolved package.\nprivate final class ResolvedPackageBuilder: ResolvedBuilder<ResolvedPackage> {\n    /// The package reference.\n    let package: Package\n\n    /// The product filter applied to the package.\n    let productFilter: ProductFilter\n\n    /// Package can vend unsafe products\n    let isAllowedToVendUnsafeProducts: Bool\n\n    /// Package can be overridden\n    let allowedToOverride: Bool\n\n    /// The modules in the package.\n    var modules: [ResolvedModuleBuilder] = []\n\n    /// The products in this package.\n    var products: [ResolvedProductBuilder] = []\n\n    /// The enabled traits of this package.\n    var enabledTraits: EnabledTraits\n\n    /// The dependencies of this package.\n    var dependencies: [ResolvedPackageBuilder] = []\n\n    /// The prebuilt libraries for this package\n    var prebuilts: [String: PrebuiltLibrary]?\n\n    /// Map from package identity to the local name for module dependency resolution that has been given to that package\n    /// through the dependency declaration.\n    var dependencyNamesForModuleDependencyResolutionOnly: [PackageIdentity: String] = [:]\n\n    /// The defaultLocalization for this package.\n    var defaultLocalization: String? = nil\n\n    /// The platforms supported by this package.\n    var supportedPlatforms: [SupportedPlatform] = []\n\n    /// If the given package's source is a registry release, this provides additional metadata and signature\n    /// information.\n    var registryMetadata: RegistryReleaseMetadata?\n\n    let platformVersionProvider: PlatformVersionProvider\n\n    init(\n        _ package: Package,\n        productFilter: ProductFilter,\n        enabledTraits: EnabledTraits,\n        isAllowedToVendUnsafeProducts: Bool,\n        allowedToOverride: Bool,\n        platformVersionProvider: PlatformVersionProvider,\n        prebuilts: [String: PrebuiltLibrary]?\n    ) {\n        self.package = package\n        self.productFilter = productFilter\n        self.enabledTraits = enabledTraits\n        self.isAllowedToVendUnsafeProducts = isAllowedToVendUnsafeProducts\n        self.allowedToOverride = allowedToOverride\n        self.platformVersionProvider = platformVersionProvider\n        self.prebuilts = prebuilts\n    }\n\n    override func constructImpl() throws -> ResolvedPackage {\n        let products = try self.products.map { try $0.construct() }\n        var modules = products.reduce(into: IdentifiableSet()) { $0.formUnion($1.modules) }\n        try modules.formUnion(self.modules.map { try $0.construct() })\n\n        return ResolvedPackage(\n            underlying: self.package,\n            defaultLocalization: self.defaultLocalization,\n            supportedPlatforms: self.supportedPlatforms,\n            dependencies: self.dependencies.map(\\.package.identity),\n            enabledTraits: self.enabledTraits.names,\n            modules: modules,\n            products: products,\n            registryMetadata: self.registryMetadata,\n            platformVersionProvider: self.platformVersionProvider\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/ModulesGraph.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport OrderedCollections\nimport PackageLoading\nimport PackageModel\nimport TSCBasic\n\nimport protocol Basics.FileSystem\nimport class Basics.ObservabilityScope\nimport struct Basics.IdentifiableSet\n\nenum PackageGraphError: Swift.Error {\n    /// Indicates a non-root package with no modules.\n    case noModules(Package)\n\n    /// The package dependency declaration has cycle in it.\n    case dependencyCycleDetected(path: [Manifest], cycle: Manifest)\n\n    /// The product dependency not found.\n    case productDependencyNotFound(\n        package: String,\n        moduleName: String,\n        dependencyProductName: String,\n        dependencyPackageName: String?,\n        dependencyProductInDecl: Bool,\n        similarProductName: String?,\n        packageContainingSimilarProduct: String?\n    )\n\n    /// The package dependency already satisfied by a different dependency package\n    ///  - package: Package for which the dependency conflict was detected.\n    ///  - identity: Conflicting identity.\n    ///  - dependencyLocation: Dependency from the current package which triggered the conflict.\n    ///  - otherDependencyLocation: Conflicting dependency from another package.\n    ///  - dependencyPath: a dependency path as a list of locations from the root to the dependency that triggered the conflict.\n    ///  - otherDependencyPath: a dependency path as a list of locations from the root to the conflicting dependency from another package.\n    case dependencyAlreadySatisfiedByIdentifier(\n        package: String,\n        identity: PackageIdentity,\n        dependencyLocation: String,\n        otherDependencyLocation: String,\n        dependencyPath: [String] = [],\n        otherDependencyPath: [String] = []\n    )\n\n    /// The package dependency already satisfied by a different dependency package\n    case dependencyAlreadySatisfiedByName(\n        package: String,\n        dependencyLocation: String,\n        otherDependencyURL: String,\n        name: String\n    )\n\n    /// The product dependency was found but the package name was not referenced correctly (tools version > 5.2).\n    case productDependencyMissingPackage(\n        productName: String,\n        moduleName: String,\n        packageIdentifier: String\n    )\n    /// Dependency between a plugin and a dependent target/product of a given type is unsupported\n    case unsupportedPluginDependency(\n        moduleName: String,\n        dependencyName: String,\n        dependencyType: String,\n        dependencyPackage: String?\n    )\n\n    /// A product was found in multiple packages.\n    case duplicateProduct(product: String, packages: [Package])\n\n    /// Duplicate aliases for a target found in a product.\n    case multipleModuleAliases(\n        module: String,\n        product: String,\n        package: String,\n        aliases: [String]\n    )\n}\n\n@available(*,\n    deprecated,\n    renamed: \"ModulesGraph\",\n    message: \"PackageGraph had a misleading name, it's a graph of dependencies between modules, not just packages\"\n)\npublic typealias PackageGraph = ModulesGraph\n\n/// A collection of packages.\npublic struct ModulesGraph {\n    /// The root packages.\n    public let rootPackages: IdentifiableSet<ResolvedPackage>\n\n    /// The complete set of contained packages.\n    public let packages: IdentifiableSet<ResolvedPackage>\n\n    @available(*, deprecated, renamed: \"reachableModules\")\n    public var reachableTargets: IdentifiableSet<ResolvedModule> { self.reachableModules }\n\n    /// The list of all modules reachable from root modules.\n    public private(set) var reachableModules: IdentifiableSet<ResolvedModule>\n\n    /// The list of all products reachable from root modules.\n    public private(set) var reachableProducts: IdentifiableSet<ResolvedProduct>\n\n    @available(*, deprecated, renamed: \"allModules\")\n    public var allTargets: IdentifiableSet<ResolvedModule> { self.allModules }\n\n    /// Returns all the modules in the graph, regardless if they are reachable from the root modules or not.\n    public private(set) var allModules: IdentifiableSet<ResolvedModule>\n\n    /// Returns all the products in the graph, regardless if they are reachable from the root modules or not.\n    public private(set) var allProducts: IdentifiableSet<ResolvedProduct>\n\n    /// Package dependencies required for a fully resolved graph.\n    ///\n    /// This will include a references to dependencies that are currently present\n    /// in the graph due to loading errors. This does not include the root packages.\n    public let requiredDependencies: [PackageReference]\n\n    /// Returns true if a given module is present in root packages and is not excluded for the given build environment.\n    public func isInRootPackages(_ module: ResolvedModule, satisfying buildEnvironment: BuildEnvironment) -> Bool {\n        // FIXME: This can be easily cached.\n        return rootPackages.reduce(\n            into: IdentifiableSet<ResolvedModule>()\n        ) { (accumulator: inout IdentifiableSet<ResolvedModule>, package: ResolvedPackage) in\n            let allDependencies = package.modules.flatMap { $0.dependencies }\n            let unsatisfiedDependencies = allDependencies.filter { !$0.satisfies(buildEnvironment) }\n            let unsatisfiedDependencyModules = unsatisfiedDependencies.compactMap { (\n                dep: ResolvedModule.Dependency\n            ) -> ResolvedModule? in\n                switch dep {\n                case .module(let moduleDependency, _):\n                    return moduleDependency\n                default:\n                    return nil\n                }\n            }\n\n            accumulator.formUnion(IdentifiableSet(package.modules).subtracting(unsatisfiedDependencyModules))\n        }.contains(id: module.id)\n    }\n\n    public func isRootPackage(_ package: ResolvedPackage) -> Bool {\n        // FIXME: This can be easily cached.\n        return self.rootPackages.contains(id: package.id)\n    }\n\n    /// Returns the package  based on the given identity, or nil if the package isn't in the graph.\n    public func package(for identity: PackageIdentity) -> ResolvedPackage? {\n        packages[identity]\n    }\n\n    /// Returns the package that contains the module, or nil if the module isn't in the graph.\n    public func package(for module: ResolvedModule) -> ResolvedPackage? {\n        self.package(for: module.packageIdentity)\n    }\n\n    /// Returns the package that contains the product, or nil if the product isn't in the graph.\n    public func package(for product: ResolvedProduct) -> ResolvedPackage? {\n        self.package(for: product.packageIdentity)\n    }\n\n    /// Returns all of the packages that the given package depends on directly.\n    public func directDependencies(for package: ResolvedPackage) -> [ResolvedPackage] {\n        package.dependencies.compactMap { self.package(for: $0) }\n    }\n\n    /// Find a product given a name and an optional destination. If a destination is not specified\n    /// this method uses `.destination` and falls back to `.tools` for macros, plugins, and tests.\n    public func product(for name: String) -> ResolvedProduct? {\n        self.allProducts.first { $0.name == name }\n    }\n\n    @available(*, deprecated, renamed: \"module(for:)\")\n    public func target(for name: String) -> ResolvedModule? {\n        self.module(for: name)\n    }\n\n    /// Find a module given a name and an optional destination. If a destination is not specified\n    /// this method uses `.destination` and falls back to `.tools` for macros, plugins, and tests.\n    public func module(for name: String) -> ResolvedModule? {\n        self.allModules.first { $0.name == name }\n    }\n\n    /// All root and root dependency packages provided as input to the graph.\n    public let inputPackages: [ResolvedPackage]\n\n    /// Any binary artifacts referenced by the graph.\n    public let binaryArtifacts: [PackageIdentity: [String: BinaryArtifact]]\n\n    /// Construct a package graph directly.\n    public init(\n        rootPackages: [ResolvedPackage],\n        rootDependencies: [ResolvedPackage] = [],\n        packages: IdentifiableSet<ResolvedPackage>,\n        dependencies requiredDependencies: [PackageReference],\n        binaryArtifacts: [PackageIdentity: [String: BinaryArtifact]]\n    ) throws {\n        let rootPackages = IdentifiableSet(rootPackages)\n        self.requiredDependencies = requiredDependencies\n        self.inputPackages = rootPackages + rootDependencies\n        self.binaryArtifacts = binaryArtifacts\n        self.packages = packages\n\n        var allModules = IdentifiableSet<ResolvedModule>()\n        var allProducts = IdentifiableSet<ResolvedProduct>()\n        for package in self.packages {\n            let modulesToInclude = if rootPackages.contains(id: package.id) {\n                Array(package.modules)\n            } else {\n                // Don't include tests modules from non-root packages so swift-test doesn't\n                // try to run them.\n                package.modules.filter { $0.type != .test }\n            }\n\n            for module in modulesToInclude {\n                allModules.insert(module)\n            }\n\n            if rootPackages.contains(id: package.id) {\n                allProducts.formUnion(package.products)\n            } else {\n                // Don't include test products from non-root packages so swift-test doesn't\n                // try to run them.\n                allProducts.formUnion(package.products.filter { $0.type != .test })\n            }\n        }\n\n        // Compute the reachable modules and products.\n        let inputModules = self.inputPackages.flatMap { $0.modules }\n        let inputProducts = self.inputPackages.flatMap { $0.products }\n        let recursiveDependencies = try inputModules.lazy.flatMap { try $0.recursiveDependencies() }\n\n        self.reachableModules = IdentifiableSet(inputModules).union(recursiveDependencies.compactMap { $0.module })\n        self.reachableProducts = IdentifiableSet(inputProducts).union(recursiveDependencies.compactMap { $0.product })\n        self.rootPackages = rootPackages\n        self.allModules = allModules\n        self.allProducts = allProducts\n    }\n\n    @_spi(SwiftPMInternal)\n    @available(*, deprecated, renamed: \"computeTestModulesForExecutableModules\")\n    public func computeTestTargetsForExecutableTargets() throws -> [ResolvedModule.ID: [ResolvedModule]] {\n        try self.computeTestModulesForExecutableModules()\n    }\n\n    /// Computes a map from each executable module in any of the root packages to the corresponding test modules.\n    @_spi(SwiftPMInternal)\n    public func computeTestModulesForExecutableModules() throws -> [ResolvedModule.ID: [ResolvedModule]] {\n        var result = [ResolvedModule.ID: [ResolvedModule]]()\n\n        let rootModules = IdentifiableSet(rootPackages.flatMap { $0.modules })\n\n        // Create map of test module to set of its direct dependencies.\n        let testModuleDepMap: [ResolvedModule.ID: IdentifiableSet<ResolvedModule>] = try {\n            let testModuleDeps = rootModules.filter({ $0.type == .test }).map({\n                ($0.id, IdentifiableSet($0.dependencies.compactMap { $0.module }.filter { $0.type != .plugin }))\n            })\n            return try Dictionary(throwingUniqueKeysWithValues: testModuleDeps)\n        }()\n\n        for module in rootModules where module.type == .executable {\n            // Find all dependencies of this module within its package. Note that we do not traverse plugin usages.\n            let dependencies = try topologicalSortIdentifiable(module.dependencies, successors: {\n                $0.dependencies.compactMap{ $0.module }.filter{ $0.type != .plugin }.map{ .module($0, conditions: []) }\n            }).compactMap({ $0.module })\n\n            // Include the test modules whose dependencies intersect with the\n            // current module's (recursive) dependencies.\n            let testModules = testModuleDepMap.filter({ (testModule, deps) in\n                !deps.intersection(dependencies + [module]).isEmpty\n            }).map({ $0.key })\n\n            result[module.id] = testModules.compactMap { rootModules[$0] }\n        }\n\n        return result\n    }\n\n    public func getReplProductName() throws -> String {\n        if self.rootPackages.isEmpty {\n            throw StringError(\"Root package does not exist.\")\n        }\n        return self.rootPackages[self.rootPackages.startIndex].identity.description +\n            Product.replProductSuffix\n    }\n}\n\nextension PackageGraphError: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .noModules(let package):\n            return \"package '\\(package)' contains no products\"\n\n        case .dependencyCycleDetected(let path, let package):\n            return \"cyclic dependency between packages \" +\n            (path.map({ $0.displayName }).joined(separator: \" -> \")) +\n            \" -> \\(package.displayName) requires tools-version 6.0 or later\"\n\n        case .productDependencyNotFound(let package, let moduleName, let dependencyProductName, let dependencyPackageName, let dependencyProductInDecl, let similarProductName, let packageContainingSimilarProduct):\n            if dependencyProductInDecl {\n                return \"product '\\(dependencyProductName)' is declared in the same package '\\(package)' and can't be used as a dependency for target '\\(moduleName)'.\"\n            } else {\n                var description = \"product '\\(dependencyProductName)' required by package '\\(package)' target '\\(moduleName)' \\(dependencyPackageName.map{ \"not found in package '\\($0)'\" } ?? \"not found\").\"\n                if let similarProductName, let packageContainingSimilarProduct {\n                    description += \" Did you mean '.product(name: \\\"\\(similarProductName)\\\", package: \\\"\\(packageContainingSimilarProduct)\\\")'?\"\n                } else if let similarProductName {\n                    description += \" Did you mean '\\(similarProductName)'?\"\n                }\n                return description\n            }\n        case .dependencyAlreadySatisfiedByIdentifier(\n            _,\n            let identity,\n            let dependencyURL,\n            let otherDependencyURL,\n            let dependencyPath,\n            let otherDependencyPath\n        ):\n            var description =\n                \"Conflicting identity for \\(identity): \" +\n                \"dependency '\\(dependencyURL)' and dependency '\\(otherDependencyURL)' \" +\n                \"both point to the same package identity '\\(identity)'.\"\n            if !dependencyPath.isEmpty && !otherDependencyPath.isEmpty {\n                let chainA = dependencyPath.map { String(describing: $0) }.joined(separator: \"->\")\n                let chainB = otherDependencyPath.map { String(describing: $0) }.joined(separator: \"->\")\n                description += (\n                    \" The dependencies are introduced through the following chains: \" +\n                    \"(A) \\(chainA) (B) \\(chainB). If there are multiple chains that lead to the same dependency, \" +\n                    \"only the first chain is shown here. To see all chains use debug output option. \" +\n                    \"To resolve the conflict, coordinate with the maintainer of the package \" +\n                    \"that introduces the conflicting dependency.\"\n                )\n            }\n            return description\n\n        case .dependencyAlreadySatisfiedByName(let package, let dependencyURL, let otherDependencyURL, let name):\n            return \"'\\(package)' dependency on '\\(dependencyURL)' conflicts with dependency on '\\(otherDependencyURL)' which has the same explicit name '\\(name)'\"\n\n        case .productDependencyMissingPackage(\n            let productName,\n            let moduleName,\n            let packageIdentifier\n        ):\n\n            let solution = \"\"\"\n            reference the package in the target dependency with '.product(name: \"\\(productName)\", package: \\\n            \"\\(packageIdentifier)\")'\n            \"\"\"\n\n            return \"dependency '\\(productName)' in target '\\(moduleName)' requires explicit declaration; \\(solution)\"\n\n        case .duplicateProduct(let product, let packages):\n            let packagesDescriptions = packages.sorted(by: { $0.identity < $1.identity }).map {\n                var description = \"'\\($0.identity)'\"\n                switch $0.manifest.packageKind {\n                case .root(let path),\n                        .fileSystem(let path),\n                        .localSourceControl(let path):\n                    description += \" (at '\\(path)')\"\n                case .remoteSourceControl(let url):\n                    description += \" (from '\\(url)')\"\n                case .registry:\n                    break\n                }\n                return description\n            }\n            return \"multiple packages (\\(packagesDescriptions.joined(separator: \", \"))) declare products with a conflicting name: '\\(product)’; product names need to be unique across the package graph\"\n        case .multipleModuleAliases(let target, let product, let package, let aliases):\n            return \"multiple aliases: ['\\(aliases.joined(separator: \"', '\"))'] found for target '\\(target)' in product '\\(product)' from package '\\(package)'\"\n        case .unsupportedPluginDependency(let targetName, let dependencyName, let dependencyType,  let dependencyPackage):\n            var trailingMsg = \"\"\n            if let dependencyPackage {\n              trailingMsg = \" from package '\\(dependencyPackage)'\"\n            }\n            return \"plugin '\\(targetName)' cannot depend on '\\(dependencyName)' of type '\\(dependencyType)'\\(trailingMsg); this dependency is unsupported\"\n        }\n    }\n}\n\nenum GraphError: Error {\n    /// A cycle was detected in the input.\n    case unexpectedCycle\n}\n\n/// Perform a topological sort of an graph.\n///\n/// This function is optimized for use cases where cycles are unexpected, and\n/// does not attempt to retain information on the exact nodes in the cycle.\n///\n/// - Parameters:\n///   - nodes: The list of input nodes to sort.\n///   - successors: A closure for fetching the successors of a particular node.\n///\n/// - Returns: A list of the transitive closure of nodes reachable from the\n/// inputs, ordered such that every node in the list follows all of its\n/// predecessors.\n///\n/// - Throws: GraphError.unexpectedCycle\n///\n/// - Complexity: O(v + e) where (v, e) are the number of vertices and edges\n/// reachable from the input nodes via the relation.\nfunc topologicalSortIdentifiable<T: Identifiable>(\n    _ nodes: [T], successors: (T) throws -> [T]\n) throws -> [T] {\n    // Implements a topological sort via recursion and reverse postorder DFS.\n    func visit(_ node: T,\n               _ stack: inout OrderedCollections.OrderedSet<T.ID>, _ visited: inout Set<T.ID>, _ result: inout [T],\n               _ successors: (T) throws -> [T]) throws {\n        // Mark this node as visited -- we are done if it already was.\n        if !visited.insert(node.id).inserted {\n            return\n        }\n\n        // Otherwise, visit each adjacent node.\n        for succ in try successors(node) {\n            guard stack.append(succ.id).inserted else {\n                // If the successor is already in this current stack, we have found a cycle.\n                //\n                // FIXME: We could easily include information on the cycle we found here.\n                throw GraphError.unexpectedCycle\n            }\n            try visit(succ, &stack, &visited, &result, successors)\n            let popped = stack.removeLast()\n            assert(popped == succ.id)\n        }\n\n        // Add to the result.\n        result.append(node)\n    }\n\n    // FIXME: This should use a stack not recursion.\n    var visited = Set<T.ID>()\n    var result = [T]()\n    var stack = OrderedCollections.OrderedSet<T.ID>()\n    for node in nodes {\n        precondition(stack.isEmpty)\n        stack.append(node.id)\n        try visit(node, &stack, &visited, &result, successors)\n        let popped = stack.removeLast()\n        assert(popped == node.id)\n    }\n\n    return result.reversed()\n}\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\npublic func loadModulesGraph(\n    identityResolver: IdentityResolver = DefaultIdentityResolver(),\n    fileSystem: FileSystem,\n    manifests: [Manifest],\n    binaryArtifacts: [PackageIdentity: [String: BinaryArtifact]] = [:],\n    prebuilts: [PackageIdentity: [String: PrebuiltLibrary]] = [:],\n    explicitProduct: String? = .none,\n    shouldCreateMultipleTestProducts: Bool = false,\n    createREPLProduct: Bool = false,\n    useXCBuildFileRules: Bool = false,\n    customXCTestMinimumDeploymentTargets: [PackageModel.Platform: PlatformVersion]? = .none,\n    observabilityScope: ObservabilityScope,\n    traitConfiguration: TraitConfiguration = .default,\n    enabledTraitsMap: EnabledTraitsMap = .init()\n) throws -> ModulesGraph {\n    let rootManifests = manifests.filter(\\.packageKind.isRoot).spm_createDictionary { ($0.path, $0) }\n    let externalManifests = try manifests.filter { !$0.packageKind.isRoot }\n        .reduce(\n            into: OrderedCollections\n                .OrderedDictionary<PackageIdentity, (manifest: Manifest, fs: FileSystem)>()\n        ) { partial, item in\n            partial[try identityResolver.resolveIdentity(for: item.packageKind)] = (item, fileSystem)\n        }\n\n    let packages = Array(rootManifests.keys)\n\n    let input = PackageGraphRootInput(packages: packages, traitConfiguration: traitConfiguration)\n    let graphRoot = try PackageGraphRoot(\n        input: input,\n        manifests: rootManifests,\n        explicitProduct: explicitProduct,\n        observabilityScope: observabilityScope,\n        enabledTraitsMap: enabledTraitsMap\n    )\n\n    return try ModulesGraph.load(\n        root: graphRoot,\n        identityResolver: identityResolver,\n        additionalFileRules: useXCBuildFileRules ? FileRuleDescription.xcbuildFileTypes : FileRuleDescription\n            .swiftpmFileTypes,\n        externalManifests: externalManifests,\n        binaryArtifacts: binaryArtifacts,\n        prebuilts: prebuilts,\n        shouldCreateMultipleTestProducts: shouldCreateMultipleTestProducts,\n        createREPLProduct: createREPLProduct,\n        customXCTestMinimumDeploymentTargets: customXCTestMinimumDeploymentTargets,\n        fileSystem: fileSystem,\n        observabilityScope: observabilityScope,\n        productsFilter: nil,\n        modulesFilter: nil,\n        enabledTraitsMap: enabledTraitsMap\n    )\n}\n"
  },
  {
    "path": "Sources/PackageGraph/PackageContainer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport PackageModel\n\nimport struct TSCUtility.Version\n\n/// A container of packages.\n///\n/// This is the top-level unit of package resolution, i.e. the unit at which\n/// versions are associated.\n///\n/// It represents a package container (e.g., a source repository) which can be\n/// identified unambiguously and which contains a set of available package\n/// versions and the ability to retrieve the dependency constraints for each of\n/// those versions.\n///\n/// We use the \"container\" terminology here to differentiate between two\n/// conceptual notions of what the package is: (1) informally, the repository\n/// containing the package, but from which a package cannot be loaded by itself\n/// and (2) the repository at a particular version, at which point the package\n/// can be loaded and dependencies enumerated.\n///\n/// This is also designed in such a way to extend naturally to multiple packages\n/// being contained within a single repository, should we choose to support that\n/// later.\npublic protocol PackageContainer {\n\n    /// The identifier for the package.\n    var package: PackageReference { get }\n\n    var shouldInvalidatePinnedVersions: Bool { get }\n\n    /// Returns true if the tools version is compatible at the given version.\n    func isToolsVersionCompatible(at version: Version) async -> Bool\n\n    /// Returns the tools version for the given version\n    func toolsVersion(for version: Version) async throws -> ToolsVersion\n\n    /// Get the list of versions which are available for the package.\n    ///\n    /// The list will be returned in sorted order, with the latest version *first*.\n    /// All versions will not be requested at once. Resolver will request the next one only\n    /// if the previous one did not satisfy all constraints.\n    func toolsVersionsAppropriateVersionsDescending() async throws -> [Version]\n\n    /// Get the list of versions in the repository sorted in the ascending order, that is the earliest\n    /// version appears first.\n    func versionsAscending() async throws -> [Version]\n\n    /// Get the list of versions in the repository sorted in the descending order, that is the latest\n    /// version appears first.\n    func versionsDescending() async throws -> [Version]\n\n    // FIXME: We should perhaps define some particularly useful error codes\n    // here, so the resolver can handle errors more meaningfully.\n    //\n    /// Fetch the declared dependencies for a particular version.\n    ///\n    /// This property is expected to be efficient to access, and cached by the\n    /// client if necessary.\n    ///\n    /// - Precondition: `versions.contains(version)`\n    /// - Throws: If the version could not be resolved; this will abort\n    ///   dependency resolution completely.\n    func getDependencies(at version: Version, productFilter: ProductFilter, _ enabledTraits: EnabledTraits) async throws -> [PackageContainerConstraint]\n\n    /// Fetch the declared dependencies for a particular revision.\n    ///\n    /// This property is expected to be efficient to access, and cached by the\n    /// client if necessary.\n    ///\n    /// - Throws: If the revision could not be resolved; this will abort\n    ///   dependency resolution completely.\n    func getDependencies(at revision: String, productFilter: ProductFilter, _ enabledTraits: EnabledTraits) async throws -> [PackageContainerConstraint]\n\n    /// Fetch the dependencies of an unversioned package container.\n    ///\n    /// NOTE: This method should not be called on a versioned container.\n    func getUnversionedDependencies(productFilter: ProductFilter, _ enabledTraits: EnabledTraits) async throws -> [PackageContainerConstraint]\n\n    /// Get the updated identifier at a bound version.\n    ///\n    /// This can be used by the containers to fill in the missing information that is obtained\n    /// after the container is available. The updated identifier is returned in result of the\n    /// dependency resolution.\n    func loadPackageReference(at boundVersion: BoundVersion) async throws -> PackageReference\n}\n\nextension PackageContainer {\n    public func reversedVersions() async throws -> [Version] {\n        try await self.versionsDescending()\n    }\n\n    public func versionsDescending() async throws -> [Version] {\n        try await self.versionsAscending().reversed()\n    }\n\n    public var shouldInvalidatePinnedVersions: Bool {\n        return true\n    }\n\n    func getDependencies(at revision: String, productFilter: ProductFilter, _ enabledTraits: Set<String> = [\"default\"]) async throws -> [PackageContainerConstraint] {\n        return []\n    }\n}\n\npublic protocol CustomPackageContainer: PackageContainer {\n    /// Retrieve the package using this package container.\n    func retrieve(\n       at version: Version,\n       progressHandler: ((_ bytesReceived: Int64, _ totalBytes: Int64?) -> Void)?,\n       observabilityScope: ObservabilityScope\n    ) throws -> AbsolutePath\n\n    /// Get the custom file system for this package container.\n    func getFileSystem() throws -> FileSystem?\n}\n\npublic extension CustomPackageContainer {\n    func retrieve(at version: Version, observabilityScope: ObservabilityScope) throws -> AbsolutePath {\n        return try self.retrieve(at: version, progressHandler: .none, observabilityScope: observabilityScope)\n    }\n}\n\n// MARK: - PackageContainerConstraint\n\n/// An individual constraint onto a container.\npublic struct PackageContainerConstraint: Equatable, Hashable {\n\n    /// The identifier for the container the constraint is on.\n    public let package: PackageReference\n\n    /// The constraint requirement.\n    public let requirement: PackageRequirement\n\n    /// The required products.\n    public let products: ProductFilter\n\n    /// The traits that have been enabled for the package.\n    public let enabledTraits: EnabledTraits\n\n    /// Create a constraint requiring the given `container` satisfying the\n    /// `requirement`.\n    public init(package: PackageReference, requirement: PackageRequirement, products: ProductFilter, enabledTraits: EnabledTraits = [\"default\"]) {\n        self.package = package\n        self.requirement = requirement\n        self.products = products\n        self.enabledTraits = enabledTraits\n    }\n\n    /// Create a constraint requiring the given `container` satisfying the\n    /// `versionRequirement`.\n    public init(package: PackageReference, versionRequirement: VersionSetSpecifier, products: ProductFilter, enabledTraits: EnabledTraits = [\"default\"]) {\n        self.init(package: package, requirement: .versionSet(versionRequirement), products: products, enabledTraits: enabledTraits)\n    }\n\n    /// Custom implementation for the hash method due to interference of traits in its computation.\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(package)\n        hasher.combine(requirement)\n        hasher.combine(products)\n    }\n\n    /// Custom implementation to check equality due to interference of traits in its computation.\n    static public func == (lhs: PackageContainerConstraint, rhs: PackageContainerConstraint) -> Bool {\n        return lhs.package == rhs.package && lhs.requirement == rhs.requirement && lhs.products == rhs.products\n    }\n}\n\nextension PackageContainerConstraint: CustomStringConvertible {\n    public var description: String {\n        return \"Constraint(\\(self.package), \\(requirement), \\(products), \\(enabledTraits)\"\n    }\n}\n\n// MARK: - PackageContainerProvider\n\n/// An interface for resolving package containers.\npublic protocol PackageContainerProvider {\n    /// Get the container for a particular identifier asynchronously.\n    func getContainer(\n        for package: PackageReference,\n        updateStrategy: ContainerUpdateStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> PackageContainer\n}\n\npublic extension PackageContainerProvider {\n    @available(*, noasync, message: \"Use the async alternative\")\n    func getContainer(\n        for package: PackageReference,\n        updateStrategy: ContainerUpdateStrategy,\n        observabilityScope: ObservabilityScope,\n        on queue: DispatchQueue,\n        completion: @escaping @Sendable (Result<PackageContainer, Error>) -> Void\n    ) {\n        queue.asyncResult(completion) {\n            try await self.getContainer(\n                for: package,\n                updateStrategy: updateStrategy,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n}\n\n/// Only used for source control containers and as such a mirror of RepositoryUpdateStrategy\n/// This duplication is unfortunate - ideally this is not a concern of the ContainerProvider at all\n/// but it is required give how PackageContainerProvider currently integrated into the resolver\npublic enum ContainerUpdateStrategy {\n    case never\n    case always\n    case ifNeeded(revision: String)\n}\n"
  },
  {
    "path": "Sources/PackageGraph/PackageGraphRoot.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\n\nimport enum TSCUtility.Git\n\n/// Represents the input to the package graph root.\npublic struct PackageGraphRootInput {\n    /// The list of root packages.\n    public let packages: [AbsolutePath]\n\n    /// Top level dependencies to the graph.\n    public let dependencies: [PackageDependency]\n\n    /// The trait configuration for the root packages.\n    public let traitConfiguration: TraitConfiguration\n\n    /// Create a package graph root.\n    public init(\n        packages: [AbsolutePath],\n        dependencies: [PackageDependency] = [],\n        traitConfiguration: TraitConfiguration = .default\n    ) {\n        self.packages = packages\n        self.dependencies = dependencies\n        self.traitConfiguration = traitConfiguration\n    }\n}\n\n/// Represents the inputs to the package graph.\npublic struct PackageGraphRoot {\n\n    /// The root packages.\n    public let packages: [PackageIdentity: (reference: PackageReference, manifest: Manifest)]\n\n    /// The root manifests.\n    public var manifests: [PackageIdentity: Manifest] {\n        return self.packages.compactMapValues { $0.manifest }\n    }\n\n    /// The root package references.\n    public var packageReferences: [PackageReference] {\n        return self.packages.values.map { $0.reference }\n    }\n\n    private let _dependencies: [PackageDependency]\n\n    /// The top level dependencies.\n    public var dependencies: [PackageDependency] {\n        guard let dependencyMapper else {\n            return self._dependencies\n        }\n\n        return self._dependencies.map { dependency in\n            do {\n                return try dependencyMapper.mappedDependency(\n                    MappablePackageDependency(\n                        dependency,\n                        parentPackagePath: localFileSystem.currentWorkingDirectory ?? .root\n                    ),\n                    fileSystem: localFileSystem\n                )\n            } catch {\n                observabilityScope.emit(warning: \"could not map dependency \\(dependency.identity): \\(error.interpolationDescription)\")\n                return dependency\n            }\n        }\n    }\n\n    /// Whether a package is exporting out the root, i.e. a root package or a root dependency\n    public func isExporting(_ identity: PackageIdentity) -> Bool{\n        return packages[identity] != nil || dependencies.contains(where: { $0.identity == identity })\n    }\n\n    private let dependencyMapper: DependencyMapper?\n    private let observabilityScope: ObservabilityScope\n\n    /// Create a package graph root.\n    /// Note this quietly skip inputs for which manifests are not found. this could be because the manifest  failed to load or for some other reasons\n    // FIXME: This API behavior wrt to non-found manifests is fragile, but required by IDEs\n    // it may lead to incorrect assumption in downstream code which may expect an error if a manifest was not found\n    // we should refactor this API to more clearly return errors for inputs that do not have a corresponding manifest\n    public init(\n        input: PackageGraphRootInput,\n        manifests: [AbsolutePath: Manifest],\n        explicitProduct: String? = nil,\n        dependencyMapper: DependencyMapper? = nil,\n        observabilityScope: ObservabilityScope,\n        enabledTraitsMap: EnabledTraitsMap = .init()\n    ) throws {\n        self.packages = input.packages.reduce(into: .init(), { partial, inputPath in\n            if let manifest = manifests[inputPath]  {\n                let packagePath = manifest.path.parentDirectory\n                let identity = PackageIdentity(path: packagePath) // this does not use the identity resolver which is fine since these are the root packages\n                partial[identity] = (.root(identity: identity, path: packagePath), manifest)\n            }\n        })\n\n        // FIXME: Deprecate special casing once the manifest supports declaring used executable products.\n        // Special casing explicit products like this is necessary to pass the test suite and satisfy backwards compatibility.\n        // However, changing the dependencies based on the command line arguments may force `Package.resolved` to temporarily change,\n        // which can become a nuisance.\n        // Such pin switching can currently be worked around by declaring the executable product as a dependency of a dummy target.\n        // But in the future it might be worth providing a way of declaring them in the manifest without a dummy target,\n        // at which time the current special casing can be deprecated.\n        var adjustedDependencies = input.dependencies.filter({ dep in\n            guard !manifests.isEmpty else { return true }\n            // Check that the dependency is used in at least one of the manifests.\n            // If not, then we can omit this dependency if pruning unused dependencies\n            // is enabled.\n            return manifests.values.reduce(false) { result, manifest in\n                let enabledTraits = enabledTraitsMap[manifest.packageIdentity]\n                if let isUsed = try? manifest.isPackageDependencyUsed(dep, enabledTraits: enabledTraits) {\n                    return result || isUsed\n                }\n\n                return true\n            }\n        })\n\n        if let explicitProduct {\n            // FIXME: `dependenciesRequired` modifies manifests and prevents conversion of `Manifest` to a value type\n            let deps = try? manifests.values.lazy\n                .map({ manifest -> [PackageDependency] in\n                    let enabledTraits = enabledTraitsMap[manifest.packageIdentity]\n                    return try manifest.dependenciesRequired(for: .everything, enabledTraits)\n                })\n                .flatMap({ $0 })\n\n            for dependency in deps ?? [] {\n                adjustedDependencies.append(dependency.filtered(by: .specific([explicitProduct])))\n            }\n        }\n\n        self._dependencies = adjustedDependencies\n        self.dependencyMapper = dependencyMapper\n        self.observabilityScope = observabilityScope\n    }\n\n    /// Returns the constraints imposed by root manifests + dependencies.\n    public func constraints(_ enabledTraitsMap: EnabledTraitsMap) throws -> [PackageContainerConstraint] {\n        var rootEnabledTraits: EnabledTraits = []\n        let constraints = self.packages.map { (identity, package) in\n            let enabledTraits = enabledTraitsMap[identity]\n            rootEnabledTraits.formUnion(enabledTraits)\n            return PackageContainerConstraint(\n                package: package.reference,\n                requirement: .unversioned,\n                products: .everything,\n                enabledTraits: enabledTraits\n            )\n        }\n        \n        let depend = try dependencies\n            .map { dep in\n                let enabledTraits = dep.traits?.filter {\n                    guard let condition = $0.condition else { return true }\n                    return condition.isSatisfied(by: rootEnabledTraits.names)\n                }.map({ EnabledTrait(name: $0.name, setBy: .package(.init(identity: \"root\"))) })\n\n                var enabledTraitsSet = enabledTraitsMap[dep.identity]\n                enabledTraitsSet.formUnion(enabledTraits ?? [])\n\n                return PackageContainerConstraint(\n                    package: dep.packageRef,\n                    requirement: try dep.toConstraintRequirement(),\n                    products: dep.productFilter,\n                    enabledTraits: enabledTraitsSet\n                )\n        }\n\n        return constraints + depend\n    }\n}\n\nextension PackageDependency {\n    /// Returns the constraint requirement representation.\n    public func toConstraintRequirement() throws -> PackageRequirement {\n        switch self {\n        case .fileSystem:\n            return .unversioned\n        case .sourceControl(let settings):\n            return try settings.requirement.toConstraintRequirement()\n        case .registry(let settings):\n            return try settings.requirement.toConstraintRequirement()\n        }\n    }\n}\n\nextension PackageDependency.SourceControl.Requirement {\n    /// Returns the constraint requirement representation.\n    public func toConstraintRequirement() throws -> PackageRequirement {\n        switch self {\n        case .range(let range):\n            return .versionSet(.range(range))\n        case .revision(let identifier):\n            return .revision(identifier)\n        case .branch(let name):\n            return .revision(name)\n        case .exact(let version):\n            return .versionSet(.exact(version))\n        }\n    }\n}\n\nextension PackageDependency.Registry.Requirement {\n    /// Returns the constraint requirement representation.\n    public func toConstraintRequirement() throws -> PackageRequirement {\n        switch self {\n        case .range(let range):\n            return .versionSet(.range(range))\n        case .exact(let version):\n            return .versionSet(.exact(version))\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/PackageGraph/PackageModel+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageModel\n\nextension PackageDependency {\n    /// Create the package reference object for the dependency.\n    public var packageRef: PackageReference {\n        let packageKind: PackageReference.Kind\n        switch self {\n        case .fileSystem(let settings):\n            packageKind = .fileSystem(settings.path)\n        case .sourceControl(let settings):\n            switch settings.location {\n            case .local(let path):\n                packageKind = .localSourceControl(path)\n            case .remote(let url):\n                packageKind = .remoteSourceControl(url)\n            }\n        case .registry(let settings):\n            packageKind = .registry(settings.identity)\n        }\n        return PackageReference(identity: self.identity, kind: packageKind)\n    }\n}\n\nextension Manifest {\n    /// Constructs constraints of the dependencies in the raw package.\n    public func dependencyConstraints(productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        return try self.dependenciesRequired(for: productFilter, enabledTraits).map({\n            let explicitlyEnabledTraits = $0.traits?.filter {\n                guard let condition = $0.condition else { return true }\n                return condition.isSatisfied(by: enabledTraits.names)\n            }.map(\\.name)\n\n            let enabledTraitsSet = EnabledTraits(explicitlyEnabledTraits ?? [], setBy: .package(.init(identity: self.packageIdentity, name: self.displayName)))\n\n            return PackageContainerConstraint(\n                package: $0.packageRef,\n                requirement: try $0.toConstraintRequirement(),\n                products: $0.productFilter,\n                enabledTraits: enabledTraitsSet\n            )\n        })\n    }\n}\n\nextension PackageContainerConstraint {\n    /// Constructs a structure of dependency nodes in a package.\n    /// - returns: An array of ``DependencyResolutionNode``\n    internal func nodes() -> [DependencyResolutionNode] {\n        switch products {\n        case .everything:\n            return [.root(package: self.package, enabledTraits: self.enabledTraits)]\n        case .specific:\n            switch products {\n            case .everything:\n                assertionFailure(\"Attempted to enumerate a root package’s product filter; root packages have no filter.\")\n                return []\n            case .specific(let set):\n                if set.isEmpty { // Pointing at the package without a particular product.\n                    return [.empty(package: self.package)]\n                } else {\n                    return set.sorted().map { .product($0, package: self.package, enabledTraits: self.enabledTraits) }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/PackageRequirement.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A requirement that a package must satisfy.\npublic enum PackageRequirement: Hashable {\n\n    /// The requirement is specified by the version set.\n    case versionSet(VersionSetSpecifier)\n\n    /// The requirement is specified by the revision.\n    ///\n    /// The revision string (identifier) should be valid and present in the\n    /// container. Only one revision requirement per container is possible\n    /// i.e. two revision requirements for same container will lead to\n    /// unsatisfiable resolution. The revision requirement can either come\n    /// from initial set of constraints or from dependencies of a revision\n    /// requirement.\n    case revision(String)\n\n    /// Un-versioned requirement i.e. a version should not resolved.\n    case unversioned\n}\n\nextension PackageRequirement: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .versionSet(let versionSet): return versionSet.description\n        case .revision(let revision): return revision\n        case .unversioned: return \"unversioned\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/README.md",
    "content": "# PackageGraph Library\n\nThis library defines the support for connecting a set of packages together into\nan overall graph which can be used for the high-level package manager\noperations.\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/DependencyResolutionNode.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageModel\n\nimport struct TSCUtility.Version\n\n/// A node in the dependency resolution graph.\n///\n/// See the documentation of each case for more detailed descriptions of each kind and how they interact.\n///\n/// - SeeAlso: ``GraphLoadingNode``\npublic enum DependencyResolutionNode {\n\n    /// An empty package node.\n    ///\n    /// This node indicates that a package needs to be present, but does not indicate that any of its contents are needed.\n    ///\n    /// Empty package nodes are always leaf nodes; they have no dependencies.\n    case empty(package: PackageReference)\n\n    /// A product node.\n    ///\n    /// This node indicates that a particular product in a particular package is required.\n    ///\n    /// Product nodes always have dependencies. A product node has...\n    ///\n    /// - one implicit dependency on its own package at an exact version (as an empty package node).\n    ///   This dependency is what ensures the resolver does not select two products from the same package at different versions.\n    /// - zero or more dependencies on the product nodes of other packages.\n    ///   These are all the external products required to build all of the modules vended by this product.\n    ///   They derive from the manifest.\n    ///\n    ///   Tools versions before 5.2 do not know which products belong to which packages, so each product is required from every dependency.\n    ///   Since a non‐existent product ends up with only its implicit dependency on its own package,\n    ///   only whichever package contains the product will end up adding additional constraints.\n    ///   See `ProductFilter` and `Manifest.register(...)`.\n    case product(String, package: PackageReference, enabledTraits: EnabledTraits = [\"default\"])\n\n    /// A root node.\n    ///\n    /// This node indicates a root node in the graph, which is required no matter what.\n    ///\n    /// Root nodes may have dependencies. A root node has...\n    ///\n    /// - zero or more dependencies on each external product node required to build any of its modules (vended or not).\n    /// - zero or more dependencies directly on external empty package nodes.\n    ///   This special case occurs when a dependency is declared but not used.\n    ///   It is a warning condition, and builds do not actually need these dependencies.\n    ///   However, forcing the graph to resolve and fetch them anyway allows the diagnostics passes access\n    ///   to the information needed in order to provide actionable suggestions to help the user stitch up the dependency declarations properly.\n    case root(package: PackageReference, enabledTraits: EnabledTraits = [\"default\"])\n\n    /// The package.\n    public var package: PackageReference {\n        switch self {\n        case .empty(let package), .product(_, let package, _), .root(let package, _):\n            return package\n        }\n    }\n\n    /// The name of the specific product if the node is a product node, otherwise `nil`.\n    public var specificProduct: String? {\n        switch self {\n        case .empty, .root:\n            return nil\n        case .product(let product, _, _):\n            return product\n        }\n    }\n\n    /// Assembles the product filter to use on the manifest for this node to determine its dependencies.\n    public var productFilter: ProductFilter {\n        switch self {\n        case .empty:\n            return .specific([])\n        case .product(let product, _, _):\n            return .specific([product])\n        case .root:\n            return .everything\n        }\n    }\n\n    /// Returns the enabled traits for this node's manifest.\n    public var enabledTraits: EnabledTraits {\n        switch self {\n        case .root(_, let enabledTraits), .product(_, _, let enabledTraits):\n            return enabledTraits\n        default:\n            return [\"default\"]\n        }\n    }\n\n    /// Returns the dependency that a product has on its own package, if relevant.\n    ///\n    /// This is the constraint that requires all products from a package resolve to the same version.\n    internal func versionLock(version: Version) -> PackageContainerConstraint? {\n        // Don’t create a version lock for anything but a product.\n        guard specificProduct != nil else { return nil }\n        return PackageContainerConstraint(\n            package: self.package,\n            versionRequirement: .exact(version),\n            products: .specific([]),\n            enabledTraits: self.enabledTraits\n        )\n    }\n\n    /// Returns the dependency that a product has on its own package, if relevant.\n    ///\n    /// This is the constraint that requires all products from a package resolve to the same revision.\n    internal func revisionLock(revision: String) -> PackageContainerConstraint? {\n        // Don’t create a revision lock for anything but a product.\n        guard specificProduct != nil else { return nil }\n        return PackageContainerConstraint(\n            package: self.package,\n            requirement: .revision(revision),\n            products: .specific([]),\n            enabledTraits: self.enabledTraits\n        )\n    }\n}\n\nextension DependencyResolutionNode: Equatable {\n    public static func ==(lhs: DependencyResolutionNode, rhs: DependencyResolutionNode) -> Bool {\n        return (lhs.package, lhs.specificProduct) == (rhs.package, rhs.specificProduct)\n    }\n}\n\nextension DependencyResolutionNode: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(self.package)\n        hasher.combine(self.specificProduct)\n    }\n}\n\nextension DependencyResolutionNode: CustomStringConvertible {\n    public var description: String {\n        return \"\\(self.package.identity)\\(self.productFilter)\"\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/DependencyResolverBinding.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport enum PackageModel.ProductFilter\nimport struct PackageModel.PackageReference\n\npublic struct DependencyResolverBinding {\n    public let package: PackageReference\n    public let boundVersion: BoundVersion\n    public let products: ProductFilter\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/DependencyResolverDelegate.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport PackageModel\n\nimport struct TSCUtility.Version\n\npublic protocol DependencyResolverDelegate {\n    func willResolve(term: Term)\n    func didResolve(term: Term, version: Version, duration: DispatchTimeInterval)\n\n    func derived(term: Term)\n    func conflict(conflict: Incompatibility)\n    func satisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility)\n    func partiallySatisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility, difference: Term)\n    func failedToResolve(incompatibility: Incompatibility)\n    func solved(result: [DependencyResolverBinding])\n}\n\npublic struct ObservabilityDependencyResolverDelegate: DependencyResolverDelegate {\n    private let observabilityScope: ObservabilityScope\n\n    public init (observabilityScope: ObservabilityScope) {\n        self.observabilityScope = observabilityScope.makeChildScope(description: \"DependencyResolver\")\n    }\n\n    public func willResolve(term: Term) {\n        self.debug(\"resolving '\\(term.node.package.identity)'\")\n    }\n\n    public func didResolve(term: Term, version: Version, duration: DispatchTimeInterval) {\n        self.debug(\"resolved '\\(term.node.package.identity)' @ '\\(version)'\")\n    }\n\n    public func derived(term: Term) {\n        self.debug(\"derived '\\(term.node.package.identity)' requirement '\\(term.requirement)'\")\n    }\n\n    public func conflict(conflict: Incompatibility) {\n        self.debug(\"conflict: \\(conflict)\")\n    }\n\n    public func failedToResolve(incompatibility: Incompatibility) {\n        self.debug(\"failed to resolve '\\(incompatibility)'\")\n    }\n\n    public func satisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility) {\n        self.debug(\"'\\(term)' is satisfied by '\\(assignment)', which is caused by '\\(assignment.cause?.description ?? \"unknown cause\")'. new incompatibility: '\\(incompatibility)'\")\n    }\n\n    public func partiallySatisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility, difference: Term) {\n        self.debug(\"\\(term) is partially satisfied by '\\(assignment)', which is caused by '\\(assignment.cause?.description ?? \"unknown cause\")'. new incompatibility \\(incompatibility)\")\n    }\n\n    public func solved(result: [DependencyResolverBinding]) {\n        for binding in result {\n            self.debug(\"solved '\\(binding.package.identity)' (\\(binding.package.locationString)) at '\\(binding.boundVersion)'\")\n        }\n        self.debug(\"dependency resolution complete!\")\n    }\n\n    private func debug(_ message: String) {\n        self.observabilityScope.emit(debug: \"[DependencyResolver] \\(message)\")\n    }\n}\n\npublic struct MultiplexResolverDelegate: DependencyResolverDelegate {\n    private let underlying: [DependencyResolverDelegate]\n\n    public init (_ underlying: [DependencyResolverDelegate]) {\n        self.underlying = underlying\n    }\n\n    public func willResolve(term: Term) {\n        underlying.forEach { $0.willResolve(term: term)  }\n    }\n\n    public func didResolve(term: Term, version: Version, duration: DispatchTimeInterval) {\n        underlying.forEach { $0.didResolve(term: term, version: version, duration: duration)  }\n    }\n\n    public func derived(term: Term) {\n        underlying.forEach { $0.derived(term: term)  }\n    }\n\n    public func conflict(conflict: Incompatibility) {\n        underlying.forEach { $0.conflict(conflict: conflict)  }\n    }\n\n    public func satisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility) {\n        underlying.forEach { $0.satisfied(term: term, by: assignment, incompatibility: incompatibility)  }\n    }\n\n    public func partiallySatisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility, difference: Term) {\n        underlying.forEach { $0.partiallySatisfied(term: term, by: assignment, incompatibility: incompatibility, difference: difference)  }\n    }\n\n    public func failedToResolve(incompatibility: Incompatibility) {\n        underlying.forEach { $0.failedToResolve(incompatibility: incompatibility)  }\n    }\n\n    public func solved(result: [DependencyResolverBinding]) {\n        underlying.forEach { $0.solved(result: result)  }\n    }\n\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/DependencyResolverError.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npublic enum DependencyResolverError: Error, Equatable {\n     /// A revision-based dependency contains a local package dependency.\n    case revisionDependencyContainsLocalPackage(dependency: String, localPackage: String)\n}\n\nextension DependencyResolverError: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .revisionDependencyContainsLocalPackage(let dependency, let localPackage):\n            return \"package '\\(dependency)' is required using a revision-based requirement and it depends on local package '\\(localPackage)', which is not supported\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PlatformVersionProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.IdentifiableSet\nimport struct PackageModel.MinimumDeploymentTarget\nimport struct PackageModel.Platform\nimport struct PackageModel.PlatformVersion\nimport struct PackageModel.SupportedPlatform\n\n/// Merging two sets of supported platforms, preferring the max constraint\nfunc merge(into partial: inout [SupportedPlatform], platforms: [SupportedPlatform]) {\n    for platformSupport in platforms {\n        if let existing = partial.firstIndex(where: { $0.platform == platformSupport.platform }) {\n            if partial[existing].version < platformSupport.version {\n                partial.remove(at: existing)\n                partial.append(platformSupport)\n            }\n        } else {\n            partial.append(platformSupport)\n        }\n    }\n}\n\npublic struct PlatformVersionProvider: Hashable {\n    public enum Implementation: Hashable {\n        case mergingFromModules(IdentifiableSet<ResolvedModule>)\n        case customXCTestMinimumDeploymentTargets([PackageModel.Platform: PlatformVersion])\n        case minimumDeploymentTargetDefault\n    }\n\n    private let implementation: Implementation\n\n    public init(implementation: Implementation) {\n        self.implementation = implementation\n    }\n\n    func derivedXCTestPlatformProvider(_ declared: PackageModel.Platform) -> PlatformVersion? {\n        switch self.implementation {\n        case .mergingFromModules(let targets):\n            let platforms = targets.reduce(into: [SupportedPlatform]()) { partial, item in\n                merge(\n                    into: &partial,\n                    platforms: [item.getSupportedPlatform(for: declared, usingXCTest: item.type == .test)]\n                )\n            }\n            return platforms.first!.version\n\n        case .customXCTestMinimumDeploymentTargets(let customXCTestMinimumDeploymentTargets):\n            return customXCTestMinimumDeploymentTargets[declared]\n\n        case .minimumDeploymentTargetDefault:\n            return MinimumDeploymentTarget.default.computeXCTestMinimumDeploymentTarget(for: declared)\n        }\n    }\n\n    /// Returns the supported platform instance for the given platform.\n    func getDerived(declared: [SupportedPlatform], for platform: Platform, usingXCTest: Bool) -> SupportedPlatform {\n        // derived platform based on known minimum deployment target logic\n        if let declaredPlatform = declared.first(where: { $0.platform == platform }) {\n            var version = declaredPlatform.version\n\n            if usingXCTest,\n               let xcTestMinimumDeploymentTarget = self.derivedXCTestPlatformProvider(platform),\n               version < xcTestMinimumDeploymentTarget\n            {\n                version = xcTestMinimumDeploymentTarget\n            }\n\n            // If the declared version is smaller than the oldest supported one, we raise the derived version to that.\n            if version < platform.oldestSupportedVersion {\n                version = platform.oldestSupportedVersion\n            }\n\n            return SupportedPlatform(\n                platform: declaredPlatform.platform,\n                version: version,\n                options: declaredPlatform.options\n            )\n        } else {\n            let minimumSupportedVersion: PlatformVersion\n            if usingXCTest,\n               let xcTestMinimumDeploymentTarget = self.derivedXCTestPlatformProvider(platform),\n               xcTestMinimumDeploymentTarget > platform.oldestSupportedVersion\n            {\n                minimumSupportedVersion = xcTestMinimumDeploymentTarget\n            } else {\n                minimumSupportedVersion = platform.oldestSupportedVersion\n            }\n\n            let oldestSupportedVersion: PlatformVersion\n            if platform == .macCatalyst {\n                let iOS = self.getDerived(declared: declared, for: .iOS, usingXCTest: usingXCTest)\n                // If there was no deployment target specified for Mac Catalyst, fall back to the iOS deployment target.\n                oldestSupportedVersion = max(minimumSupportedVersion, iOS.version)\n            } else {\n                oldestSupportedVersion = minimumSupportedVersion\n            }\n\n            return SupportedPlatform(\n                platform: platform,\n                version: oldestSupportedVersion,\n                options: []\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PubGrub/Assignment.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// An assignment that is either decided upon during decision making or derived\n/// from previously known incompatibilities during unit propagation.\n///\n/// All assignments store a term (a package identifier and a version\n/// requirement) and a decision level, which represents the number of decisions\n/// at or before it in the partial solution that caused it to be derived. This\n/// is later used during conflict resolution to figure out how far back to jump\n/// when a conflict is found.\npublic struct Assignment: Equatable {\n    public let term: Term\n    public let decisionLevel: Int\n    public let cause: Incompatibility?\n    public let isDecision: Bool\n\n    private init(\n        term: Term,\n        decisionLevel: Int,\n        cause: Incompatibility?,\n        isDecision: Bool\n    ) {\n        self.term = term\n        self.decisionLevel = decisionLevel\n        self.cause = cause\n        self.isDecision = isDecision\n    }\n\n    /// An assignment made during decision making.\n    public static func decision(_ term: Term, decisionLevel: Int) -> Assignment {\n        assert(\n            term.requirement.isExact,\n            \"Cannot create a decision assignment with a non-exact version selection: \\(term.requirement)\"\n        )\n\n        return self.init(\n            term: term,\n            decisionLevel: decisionLevel,\n            cause: nil,\n            isDecision: true\n        )\n    }\n\n    /// An assignment derived from previously known incompatibilities during\n    /// unit propagation.\n    public static func derivation(\n        _ term: Term,\n        cause: Incompatibility,\n        decisionLevel: Int\n    ) -> Assignment {\n        self.init(\n            term: term,\n            decisionLevel: decisionLevel,\n            cause: cause,\n            isDecision: false\n        )\n    }\n}\n\nextension Assignment: CustomStringConvertible {\n    public var description: String {\n        switch self.isDecision {\n        case true:\n            \"[Decision \\(self.decisionLevel): \\(self.term)]\"\n        case false:\n            \"[Derivation: \\(self.term) ← \\(self.cause?.description ?? \"-\")]\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PubGrub/ContainerProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport PackageModel\nimport TSCBasic\n\n/// An utility class around PackageContainerProvider that allows \"prefetching\" the containers\n/// in parallel. The basic idea is to kick off container fetching before starting the resolution\n/// by using the list of URLs from the Package.resolved file.\nfinal class ContainerProvider {\n    /// The actual package container provider.\n    private let underlying: PackageContainerProvider\n\n    /// Whether to perform update (git fetch) on existing cloned repositories or not.\n    private let skipUpdate: Bool\n\n    /// `Package.resolved` file representation.\n    private let resolvedPackages: ResolvedPackagesStore.ResolvedPackages\n\n    /// Observability scope to emit diagnostics with\n    private let observabilityScope: ObservabilityScope\n\n    //// Store cached containers\n    private var containersCache = ThreadSafeKeyValueStore<PackageReference, PubGrubPackageContainer>()\n\n    //// Store prefetches synchronization\n    private var prefetches = ThreadSafeKeyValueStore<PackageReference, DispatchGroup>()\n\n    init(\n        provider underlying: PackageContainerProvider,\n        skipUpdate: Bool,\n        resolvedPackages: ResolvedPackagesStore.ResolvedPackages,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.underlying = underlying\n        self.skipUpdate = skipUpdate\n        self.resolvedPackages = resolvedPackages\n        self.observabilityScope = observabilityScope\n    }\n\n    /// Get a cached container for the given identifier, asserting / throwing if not found.\n    func getCachedContainer(for package: PackageReference) throws -> PubGrubPackageContainer {\n        guard let container = self.containersCache[package] else {\n            throw InternalError(\"container for \\(package.identity) expected to be cached\")\n        }\n        return container\n    }\n\n    /// Get the container for the given identifier, loading it if necessary.\n    func getContainer(\n        for package: PackageReference,\n        completion: @escaping (Result<PubGrubPackageContainer, Error>) -> Void\n    ) {\n        // Return the cached container, if available.\n        if let container = self.containersCache[comparingLocation: package] {\n            return completion(.success(container))\n        }\n\n        if let prefetchSync = self.prefetches[package] {\n            // If this container is already being prefetched, wait for that to complete\n            prefetchSync.notify(queue: .sharedConcurrent) {\n                if let container = self.containersCache[comparingLocation: package] {\n                    // should be in the cache once prefetch completed\n                    return completion(.success(container))\n                } else {\n                    // if prefetch failed, remove from list of prefetches and try again\n                    self.prefetches[package] = nil\n                    return self.getContainer(for: package, completion: completion)\n                }\n            }\n        } else {\n            // Otherwise, fetch the container from the provider\n            self.underlying.getContainer(\n                for: package,\n                updateStrategy: self.skipUpdate ? .never : .always, // TODO: make this more elaborate\n                observabilityScope: self.observabilityScope.makeChildScope(description: \"getting package container\", metadata: package.diagnosticsMetadata),\n                on: .sharedConcurrent\n            ) { result in\n                let result = result.tryMap { container -> PubGrubPackageContainer in\n                    let pubGrubContainer = PubGrubPackageContainer(underlying: container, resolvedPackages: self.resolvedPackages)\n                    // only cache positive results\n                    self.containersCache[package] = pubGrubContainer\n                    return pubGrubContainer\n                }\n                completion(result)\n            }\n        }\n    }\n\n    /// Starts prefetching the given containers.\n    func prefetch(containers identifiers: [PackageReference]) {\n        // Process each container.\n        for identifier in identifiers {\n            var needsFetching = false\n            self.prefetches.memoize(identifier) {\n                let group = DispatchGroup()\n                group.enter()\n                needsFetching = true\n                return group\n            }\n            if needsFetching {\n                self.underlying.getContainer(\n                    for: identifier,\n                    updateStrategy: self.skipUpdate ? .never : .always, // TODO: make this more elaborate\n                    observabilityScope: self.observabilityScope.makeChildScope(description: \"prefetching package container\", metadata: identifier.diagnosticsMetadata),\n                    on: .sharedConcurrent\n                ) { result in\n                    defer { self.prefetches[identifier]?.leave() }\n                    // only cache positive results\n                    if case .success(let container) = result {\n                        self.containersCache[identifier] = PubGrubPackageContainer(underlying: container, resolvedPackages: self.resolvedPackages)\n                    }\n                }\n            }\n        }\n    }\n}\n\nextension ThreadSafeKeyValueStore where Key == PackageReference, Value == PubGrubPackageContainer {\n    subscript(comparingLocation package: PackageReference) -> PubGrubPackageContainer? {\n        if let container = self[package], container.package.equalsIncludingLocation(package) {\n            return container\n        }\n        return .none\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PubGrub/DiagnosticReportBuilder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport PackageModel\nimport TSCUtility\n\nstruct DiagnosticReportBuilder {\n    let rootNode: DependencyResolutionNode\n    let incompatibilities: [DependencyResolutionNode: [Incompatibility]]\n\n    private var lines: [(number: Int, message: String)] = []\n    private var derivations: [Incompatibility: Int] = [:]\n    private var lineNumbers: [Incompatibility: Int] = [:]\n    private let provider: ContainerProvider\n\n    init(\n        root: DependencyResolutionNode,\n        incompatibilities: [DependencyResolutionNode: [Incompatibility]],\n        provider: ContainerProvider\n    ) {\n        self.rootNode = root\n        self.incompatibilities = incompatibilities\n        self.provider = provider\n    }\n\n    mutating func makeErrorReport(for rootCause: Incompatibility) async throws -> String {\n        /// Populate `derivations`.\n        func countDerivations(_ i: Incompatibility) {\n            self.derivations[i, default: 0] += 1\n            if case .conflict(let cause) = i.cause {\n                countDerivations(cause.conflict)\n                countDerivations(cause.other)\n            }\n        }\n\n        countDerivations(rootCause)\n\n        if rootCause.cause.isConflict {\n            try await self.visit(rootCause)\n        } else {\n            assertionFailure(\"Unimplemented\")\n            try await self.record(\n                rootCause,\n                message: self.description(for: rootCause),\n                isNumbered: false\n            )\n        }\n\n        var content = \"\"\n        let padding = self.lineNumbers.isEmpty ? 0 : \"\\(Array(self.lineNumbers.values).last!) \".count\n\n        for (idx, line) in self.lines.enumerated() {\n            content += String(repeating: \" \", count: padding)\n            if line.number != -1 {\n                content += String(repeating: \" \", count: padding)\n                content += \" (\\(line.number)) \"\n            }\n            content += line.message.prefix(1).capitalized\n            content += line.message.dropFirst()\n\n            if self.lines.count - 1 != idx {\n                content += \"\\n\"\n            }\n        }\n\n        return content\n    }\n\n    private mutating func visit(\n        _ incompatibility: Incompatibility,\n        isConclusion: Bool = false\n    ) async throws {\n        let isNumbered = isConclusion || self.derivations[incompatibility]! > 1\n        let conjunction = isConclusion || incompatibility.cause == .root ? \"As a result, \" : \"\"\n        let incompatibilityDesc = try await description(for: incompatibility)\n\n        guard case .conflict(let cause) = incompatibility.cause else {\n            assertionFailure(\"\\(incompatibility)\")\n            return\n        }\n\n        if cause.conflict.cause.isConflict && cause.other.cause.isConflict {\n            let conflictLine = self.lineNumbers[cause.conflict]\n            let otherLine = self.lineNumbers[cause.other]\n\n            if let conflictLine, let otherLine {\n                try await self.record(\n                    incompatibility,\n                    message: \"\\(incompatibilityDesc) because \\(self.description(for: cause.conflict)) (\\(conflictLine)) and \\(self.description(for: cause.other)) (\\(otherLine).\",\n                    isNumbered: isNumbered\n                )\n            } else if conflictLine != nil || otherLine != nil {\n                let withLine: Incompatibility\n                let withoutLine: Incompatibility\n                let line: Int\n                if let conflictLine {\n                    withLine = cause.conflict\n                    withoutLine = cause.other\n                    line = conflictLine\n                } else {\n                    withLine = cause.other\n                    withoutLine = cause.conflict\n                    line = otherLine!\n                }\n\n                try await self.visit(withoutLine)\n                try await self.record(\n                    incompatibility,\n                    message: \"\\(conjunction)\\(incompatibilityDesc) because \\(self.description(for: withLine)) \\(line).\",\n                    isNumbered: isNumbered\n                )\n            } else {\n                let singleLineConflict = cause.conflict.cause.isSingleLine\n                let singleLineOther = cause.other.cause.isSingleLine\n                if singleLineOther || singleLineConflict {\n                    let first = singleLineOther ? cause.conflict : cause.other\n                    let second = singleLineOther ? cause.other : cause.conflict\n                    try await self.visit(first)\n                    try await self.visit(second)\n                    self.record(\n                        incompatibility,\n                        message: \"\\(incompatibilityDesc).\",\n                        isNumbered: isNumbered\n                    )\n                } else {\n                    try await self.visit(cause.conflict, isConclusion: true)\n                    try await self.visit(cause.other)\n                    try await self.record(\n                        incompatibility,\n                        message: \"\\(conjunction)\\(incompatibilityDesc) because \\(self.description(for: cause.conflict)) (\\(self.lineNumbers[cause.conflict]!)).\",\n                        isNumbered: isNumbered\n                    )\n                }\n            }\n        } else if cause.conflict.cause.isConflict || cause.other.cause.isConflict {\n            let derived = cause.conflict.cause.isConflict ? cause.conflict : cause.other\n            let ext = cause.conflict.cause.isConflict ? cause.other : cause.conflict\n            let derivedLine = self.lineNumbers[derived]\n            if let derivedLine {\n                try await self.record(\n                    incompatibility,\n                    message: \"\\(incompatibilityDesc) because \\(self.description(for: ext)) and \\(self.description(for: derived)) (\\(derivedLine)).\",\n                    isNumbered: isNumbered\n                )\n            } else if self.isCollapsible(derived) {\n                guard case .conflict(let derivedCause) = derived.cause else {\n                    assertionFailure(\"unreachable\")\n                    return\n                }\n\n                let collapsedDerived = derivedCause.conflict.cause.isConflict ? derivedCause.conflict : derivedCause\n                    .other\n                let collapsedExt = derivedCause.conflict.cause.isConflict ? derivedCause.other : derivedCause.conflict\n\n                try await self.visit(collapsedDerived)\n                try await self.record(\n                    incompatibility,\n                    message: \"\\(conjunction)\\(incompatibilityDesc) because \\(self.description(for: collapsedExt)) and \\(self.description(for: ext)).\",\n                    isNumbered: isNumbered\n                )\n            } else {\n                try await self.visit(derived)\n                try await self.record(\n                    incompatibility,\n                    message: \"\\(conjunction)\\(incompatibilityDesc) because \\(self.description(for: ext)).\",\n                    isNumbered: isNumbered\n                )\n            }\n        } else {\n            try await self.record(\n                incompatibility,\n                message: \"\\(incompatibilityDesc) because \\(self.description(for: cause.conflict)) and \\(self.description(for: cause.other)).\",\n                isNumbered: isNumbered\n            )\n        }\n    }\n\n    private func description(for incompatibility: Incompatibility) async throws -> String {\n        switch incompatibility.cause {\n        case .dependency(let causeNode):\n            assert(incompatibility.terms.count == 2)\n            let depender = incompatibility.terms.first!\n            let dependee = incompatibility.terms.last!\n            assert(depender.isPositive)\n            assert(!dependee.isPositive)\n\n            let dependerDesc: String\n            // when depender is the root node, the causeNode may be different as it may represent root's indirect dependencies (e.g. dependencies of root's unversioned dependencies)\n            if depender.node == self.rootNode, causeNode != self.rootNode {\n                dependerDesc = causeNode.nameForDiagnostics\n            } else {\n                dependerDesc = try await self.description(for: depender, normalizeRange: true)\n            }\n            let dependeeDesc = try await description(for: dependee)\n            return \"\\(dependerDesc) depends on \\(dependeeDesc)\"\n        case .noAvailableVersion:\n            assert(incompatibility.terms.count == 1)\n            let term = incompatibility.terms.first!\n            assert(term.isPositive)\n            return \"no versions of \\(term.node.nameForDiagnostics) match the requirement \\(term.requirement)\"\n        case .root:\n            // FIXME: This will never happen I think.\n            assert(incompatibility.terms.count == 1)\n            let term = incompatibility.terms.first!\n            assert(term.isPositive)\n            return \"\\(term.node.nameForDiagnostics) is \\(term.requirement)\"\n        case .conflict where incompatibility.terms.count == 1 && incompatibility.terms.first?.node == self.rootNode:\n            return \"dependencies could not be resolved\"\n        case .conflict:\n            break\n        case .versionBasedDependencyContainsUnversionedDependency(let versionedDependency, let unversionedDependency):\n            return \"package '\\(versionedDependency.identity)' is required using a stable-version but '\\(versionedDependency.identity)' depends on an unstable-version package '\\(unversionedDependency.identity)'\"\n        case .incompatibleToolsVersion(let version):\n            let term = incompatibility.terms.first!\n            return try \"\\(await self.description(for: term, normalizeRange: true)) contains incompatible tools version (\\(version))\"\n        }\n\n        let terms = incompatibility.terms\n        if terms.count == 1 {\n            let term = terms.first!\n            let prefix = try await hasEffectivelyAnyRequirement(term) ? term.node.nameForDiagnostics : self.description(\n                for: term,\n                normalizeRange: true\n            )\n            return \"\\(prefix) \" + (term.isPositive ? \"cannot be used\" : \"is required\")\n        } else if terms.count == 2 {\n            let term1 = terms.first!\n            let term2 = terms.last!\n            if term1.isPositive == term2.isPositive {\n                if term1.isPositive {\n                    return \"\\(term1.node.nameForDiagnostics) is incompatible with \\(term2.node.nameForDiagnostics)\"\n                } else {\n                    return \"either \\(term1.node.nameForDiagnostics) or \\(term2)\"\n                }\n            }\n        }\n\n        var positive: [String] = []\n        var negative: [String] = []\n        for term in terms {\n            if term.isPositive {\n                try await positive.append(self.description(for: term))\n            } else {\n                try await negative.append(self.description(for: term))\n            }\n        }\n\n        if !positive.isEmpty, !negative.isEmpty {\n            if positive.count == 1 {\n                let positiveTerm = terms.first { $0.isPositive }!\n                return try await \"\\(self.description(for: positiveTerm, normalizeRange: true)) practically depends on \\(negative.joined(separator: \" or \"))\"\n            } else {\n                return \"if \\(positive.joined(separator: \" and \")) then \\(negative.joined(separator: \" or \"))\"\n            }\n        } else if !positive.isEmpty {\n            return \"one of \\(positive.joined(separator: \" or \")) must be true\"\n        } else {\n            return \"one of \\(negative.joined(separator: \" or \")) must be true\"\n        }\n    }\n\n    /// Returns true if the requirement on this term is effectively \"any\" because of either the actual\n    /// `any` requirement or because the version range is large enough to fit all current available versions.\n    private func hasEffectivelyAnyRequirement(_ term: Term) async throws -> Bool {\n        switch term.requirement {\n        case .any:\n            return true\n        case .empty, .exact, .ranges:\n            return false\n        case .range(let range):\n            // container expected to be cached at this point\n            guard let container = try? provider.getCachedContainer(for: term.node.package) else {\n                return false\n            }\n            let bounds = try await container.computeBounds(for: range)\n            return !bounds.includesLowerBound && !bounds.includesUpperBound\n        }\n    }\n\n    private func isCollapsible(_ incompatibility: Incompatibility) -> Bool {\n        if self.derivations[incompatibility]! > 1 {\n            return false\n        }\n\n        guard case .conflict(let cause) = incompatibility.cause else {\n            assertionFailure(\"unreachable\")\n            return false\n        }\n\n        if cause.conflict.cause.isConflict, cause.other.cause.isConflict {\n            return false\n        }\n\n        if !cause.conflict.cause.isConflict, !cause.other.cause.isConflict {\n            return false\n        }\n\n        let complex = cause.conflict.cause.isConflict ? cause.conflict : cause.other\n        return !self.lineNumbers.keys.contains(complex)\n    }\n\n    private func description(for term: Term, normalizeRange: Bool = false) async throws -> String {\n        let name = term.node.nameForDiagnostics\n\n        switch term.requirement {\n        case .any: return name\n        case .empty: return \"no version of \\(name)\"\n        case .exact(let version):\n            // For the root package, don't output the useless version 1.0.0.\n            if term.node == self.rootNode {\n                return \"root\"\n            }\n            return \"\\(name) \\(version)\"\n        case .range(let range):\n            // container expected to be cached at this point\n            guard normalizeRange, let container = try? provider.getCachedContainer(for: term.node.package) else {\n                return \"\\(name) \\(range.description)\"\n            }\n\n            switch try await container.computeBounds(for: range) {\n            case (true, true):\n                return \"\\(name) \\(range.description)\"\n            case (false, false):\n                return name\n            case (true, false):\n                return \"\\(name) >= \\(range.lowerBound)\"\n            case (false, true):\n                return \"\\(name) < \\(range.upperBound)\"\n            }\n        case .ranges(let ranges):\n            let ranges = \"{\" + ranges.map {\n                if $0.lowerBound == $0.upperBound {\n                    return $0.lowerBound.description\n                }\n                return $0.lowerBound.description + \"..<\" + $0.upperBound.description\n            }.joined(separator: \", \") + \"}\"\n            return \"\\(name) \\(ranges)\"\n        }\n    }\n\n    /// Write a given output message to a stream. The message should describe\n    /// the incompatibility and how it as derived. If `isNumbered` is true, a\n    /// line number will be assigned to this incompatibility so that it can be\n    /// referred to again.\n    private mutating func record(\n        _ incompatibility: Incompatibility,\n        message: String,\n        isNumbered: Bool\n    ) {\n        var number = -1\n        if isNumbered {\n            number = self.lineNumbers.count + 1\n            self.lineNumbers[incompatibility] = number\n        }\n        let line = (number: number, message: message)\n        if isNumbered {\n            self.lines.append(line)\n        } else {\n            self.lines.insert(line, at: 0)\n        }\n    }\n}\n\nextension DependencyResolutionNode {\n    fileprivate var nameForDiagnostics: String {\n        \"'\\(self.package.identity)'\"\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PubGrub/Incompatibility.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport OrderedCollections\nimport PackageModel\n\n/// A set of terms that are incompatible with each other and can therefore not\n/// all be true at the same time. In dependency resolution, these are derived\n/// from version requirements and when running into unresolvable situations.\npublic struct Incompatibility: Equatable, Hashable {\n    public let terms: OrderedCollections.OrderedSet<Term>\n    public let cause: Cause\n\n    public init(terms: OrderedCollections.OrderedSet<Term>, cause: Cause) {\n        self.terms = terms\n        self.cause = cause\n    }\n\n    public init(_ terms: Term..., root: DependencyResolutionNode, cause: Cause = .root) throws {\n        let termSet = OrderedCollections.OrderedSet(terms)\n        try self.init(termSet, root: root, cause: cause)\n    }\n\n    public init(_ terms: OrderedCollections.OrderedSet<Term>, root: DependencyResolutionNode, cause: Cause) throws {\n        if terms.isEmpty {\n            self.init(terms: terms, cause: cause)\n            return\n        }\n\n        // Remove the root package from generated incompatibilities, since it will\n        // always be selected.\n        var terms = terms\n        if terms.count > 1, cause.isConflict,\n           terms.contains(where: { $0.isPositive && $0.node == root })\n        {\n            terms = OrderedSet(terms.filter { !$0.isPositive || $0.node != root })\n        }\n\n        let normalizedTerms = try normalize(terms: terms.elements)\n        guard normalizedTerms.count > 0 else {\n            throw InternalError(\"An incompatibility must contain at least one term after normalization.\")\n        }\n        self.init(terms: OrderedSet(normalizedTerms), cause: cause)\n    }\n}\n\nextension Incompatibility: CustomStringConvertible {\n    public var description: String {\n        let terms = self.terms\n            .map(String.init)\n            .joined(separator: \", \")\n        return \"{\\(terms)}\"\n    }\n}\n\nextension Incompatibility {\n    /// Every incompatibility has a cause to explain its presence in the\n    /// derivation graph. Only the root incompatibility uses `.root`. All other\n    /// incompatibilities are either obtained from dependency constraints,\n    /// decided upon in decision making or derived during unit propagation or\n    /// conflict resolution.\n    /// Using this information we can build up a derivation graph by following\n    /// the tree of causes. All leaf nodes are external dependencies and all\n    /// internal nodes are derived incompatibilities.\n    ///\n    /// An example graph could look like this:\n    /// ```\n    /// ┌────────────────────────────┐ ┌────────────────────────────┐\n    /// │{foo ^1.0.0, not bar ^2.0.0}│ │{bar ^2.0.0, not baz ^3.0.0}│\n    /// └─────────────┬──────────────┘ └──────────────┬─────────────┘\n    ///               │      ┌────────────────────────┘\n    ///               ▼      ▼\n    /// ┌─────────────┴──────┴───────┐ ┌────────────────────────────┐\n    /// │{foo ^1.0.0, not baz ^3.0.0}│ │{root 1.0.0, not foo ^1.0.0}│\n    /// └─────────────┬──────────────┘ └──────────────┬─────────────┘\n    ///               │   ┌───────────────────────────┘\n    ///               ▼   ▼\n    ///         ┌─────┴───┴──┐\n    ///         │{root 1.0.0}│\n    ///         └────────────┘\n    /// ```\n    public indirect enum Cause: Equatable, Hashable {\n        public struct ConflictCause: Hashable {\n            public let conflict: Incompatibility\n            public let other: Incompatibility\n        }\n\n        /// The root incompatibility.\n        case root\n\n        /// The incompatibility represents a package's dependency on another\n        /// package.\n        case dependency(node: DependencyResolutionNode)\n\n        /// The incompatibility was derived from two others during conflict\n        /// resolution.\n        case conflict(cause: ConflictCause)\n\n        /// There exists no version to fulfill the specified requirement.\n        case noAvailableVersion\n\n        /// A version-based dependency contains unversioned-based dependency.\n        case versionBasedDependencyContainsUnversionedDependency(\n            versionedDependency: PackageReference,\n            unversionedDependency: PackageReference\n        )\n\n        /// The package's tools version is incompatible.\n        case incompatibleToolsVersion(ToolsVersion)\n\n        public var isConflict: Bool {\n            if case .conflict = self { return true }\n            return false\n        }\n\n        /// Returns whether this cause can be represented in a single line of the\n        /// error output.\n        public var isSingleLine: Bool {\n            guard case .conflict(let cause) = self else {\n                assertionFailure(\"unreachable\")\n                return false\n            }\n            return !cause.conflict.cause.isConflict && !cause.other.cause.isConflict\n        }\n    }\n}\n\n/// Normalize terms so that at most one term refers to one package/polarity\n/// combination. E.g. we don't want both a^1.0.0 and a^1.5.0 to be terms in the\n/// same incompatibility, but have these combined by intersecting their version\n/// requirements to a^1.5.0.\nprivate func normalize(terms: [Term]) throws -> [Term] {\n    let dict = try terms.reduce(into: OrderedCollections.OrderedDictionary<DependencyResolutionNode, (req: VersionSetSpecifier, polarity: Bool)>()) {\n        res, term in\n        // Don't try to intersect if this is the first time we're seeing this package.\n        guard let previous = res[term.node] else {\n            res[term.node] = (term.requirement, term.isPositive)\n            return\n        }\n\n        guard let intersection = term.intersect(withRequirement: previous.req, andPolarity: previous.polarity) else {\n            throw InternalError(\"\"\"\n            Attempting to create an incompatibility with terms for \\(term.node) \\\n            intersecting versions \\(previous) and \\(term.requirement). These are \\\n            mutually exclusive and can't be intersected, making this incompatibility \\\n            irrelevant.\n            \"\"\")\n        }\n        res[term.node] = (intersection.requirement, intersection.isPositive)\n    }\n    return dict.map { Term(node: $0, requirement: $1.req, isPositive: $1.polarity) }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PubGrub/PartialSolution.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport OrderedCollections\n\nimport struct TSCUtility.Version\n\n/// The partial solution is a constantly updated solution used throughout the\n/// dependency resolution process, tracking known assignments.\npublic struct PartialSolution {\n    var root: DependencyResolutionNode?\n\n    /// All known assignments.\n    public private(set) var assignments: [Assignment]\n\n    /// All known decisions.\n    public private(set) var decisions: [DependencyResolutionNode: Version] = [:]\n\n    /// The intersection of all positive assignments for each package, minus any\n    /// negative assignments that refer to that package.\n    public private(set) var _positive: OrderedCollections.OrderedDictionary<DependencyResolutionNode, Term> = [:]\n\n    /// Union of all negative assignments for a package.\n    ///\n    /// Only present if a package has no positive assignment.\n    public private(set) var _negative: [DependencyResolutionNode: Term] = [:]\n\n    /// The current decision level.\n    public var decisionLevel: Int {\n        self.decisions.count - 1\n    }\n\n    public init(assignments: [Assignment] = []) {\n        self.assignments = assignments\n        for assignment in assignments {\n            self.register(assignment)\n        }\n    }\n\n    /// A list of all packages that have been assigned, but are not yet satisfied.\n    public var undecided: [Term] {\n        self._positive.values.filter { !self.decisions.keys.contains($0.node) }\n    }\n\n    /// Create a new derivation assignment and add it to the partial solution's\n    /// list of known assignments.\n    public mutating func derive(_ term: Term, cause: Incompatibility) {\n        let derivation = Assignment.derivation(term, cause: cause, decisionLevel: self.decisionLevel)\n        self.assignments.append(derivation)\n        self.register(derivation)\n    }\n\n    /// Create a new decision assignment and add it to the partial solution's\n    /// list of known assignments.\n    public mutating func decide(_ node: DependencyResolutionNode, at version: Version) {\n        self.decisions[node] = version\n        let term = Term(node, .exact(version))\n        let decision = Assignment.decision(term, decisionLevel: self.decisionLevel)\n        self.assignments.append(decision)\n        self.register(decision)\n    }\n\n    /// Populates the _positive and _negative properties with the assignment.\n    private mutating func register(_ assignment: Assignment) {\n        let term = assignment.term\n        let pkg = term.node\n\n        if let positive = _positive[pkg] {\n            self._positive[term.node] = positive.intersect(with: term)\n            return\n        }\n\n        let newTerm = self._negative[pkg].flatMap { term.intersect(with: $0) } ?? term\n\n        if newTerm.isPositive {\n            self._negative[pkg] = nil\n            self._positive[pkg] = newTerm\n        } else {\n            self._negative[pkg] = newTerm\n        }\n    }\n\n    /// Returns the first Assignment in this solution such that the list of\n    /// assignments up to and including that entry satisfies term.\n    public func satisfier(for term: Term) throws -> Assignment {\n        var assignedTerm: Term?\n\n        for assignment in self.assignments {\n            guard assignment.term.node == term.node else {\n                continue\n            }\n            assignedTerm = assignedTerm.flatMap { $0.intersect(with: assignment.term) } ?? assignment.term\n\n            if assignedTerm!.satisfies(term) {\n                return assignment\n            }\n        }\n\n        throw InternalError(\"term \\(term) not satisfied\")\n    }\n\n    /// Backtrack to a specific decision level by dropping all assignments with\n    /// a decision level which is greater.\n    public mutating func backtrack(toDecisionLevel decisionLevel: Int) {\n        var toBeRemoved: [(Int, Assignment)] = []\n\n        for (idx, assignment) in zip(0..., self.assignments) {\n            if assignment.decisionLevel > decisionLevel {\n                toBeRemoved.append((idx, assignment))\n            }\n        }\n\n        for (idx, remove) in toBeRemoved.reversed() {\n            let assignment = self.assignments.remove(at: idx)\n            if assignment.isDecision {\n                self.decisions.removeValue(forKey: remove.term.node)\n            }\n        }\n\n        // FIXME: We can optimize this by recomputing only the removed things.\n        self._negative.removeAll()\n        self._positive.removeAll()\n        for assignment in self.assignments {\n            self.register(assignment)\n        }\n    }\n\n    /// Returns true if the given term satisfies the partial solution.\n    func satisfies(_ term: Term) -> Bool {\n        self.relation(with: term) == .subset\n    }\n\n    /// Returns the set relation of the partial solution with the given term.\n    func relation(with term: Term) -> Term.SetRelation {\n        let pkg = term.node\n        if let positive = _positive[pkg] {\n            return positive.relation(with: term)\n        } else if let negative = _negative[pkg] {\n            return negative.relation(with: term)\n        }\n        return .overlap\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PubGrub/PubGrubDependencyResolver.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport class Foundation.NSLock\nimport OrderedCollections\nimport PackageModel\n\nimport struct TSCUtility.Version\n\n/// The solver that is able to transitively resolve a set of package constraints\n/// specified by a root package.\npublic struct PubGrubDependencyResolver {\n    /// The type of the constraints the resolver operates on.\n    public typealias Constraint = PackageContainerConstraint\n\n    /// the mutable state that get computed\n    internal final class State {\n        /// The root package reference.\n        let root: DependencyResolutionNode\n\n        /// The list of packages that are overridden in the graph. A local package reference will\n        /// always override any other kind of package reference and branch-based reference will override\n        /// version-based reference.\n        let overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)]\n\n        /// A collection of all known incompatibilities matched to the packages they\n        /// refer to. This means an incompatibility can occur several times.\n        public private(set) var incompatibilities: [DependencyResolutionNode: [Incompatibility]] = [:]\n\n        /// The current best guess for a solution satisfying all requirements.\n        public private(set) var solution: PartialSolution\n\n        private let lock = NSLock()\n\n        init(root: DependencyResolutionNode,\n             overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)] = [:],\n             solution: PartialSolution = PartialSolution())\n        {\n            self.root = root\n            self.overriddenPackages = overriddenPackages\n            self.solution = solution\n        }\n\n        func addIncompatibility(_ incompatibility: Incompatibility, at location: LogLocation) {\n            self.lock.withLock {\n                // log(\"incompat: \\(incompatibility) \\(location)\")\n                for package in incompatibility.terms.map(\\.node) {\n                    if let incompats = self.incompatibilities[package] {\n                        if !incompats.contains(incompatibility) {\n                            self.incompatibilities[package]!.append(incompatibility)\n                        }\n                    } else {\n                        self.incompatibilities[package] = [incompatibility]\n                    }\n                }\n            }\n        }\n\n        /// Find all incompatibilities containing a positive term for a given package.\n        func positiveIncompatibilities(for node: DependencyResolutionNode) -> [Incompatibility]? {\n            self.lock.withLock {\n                guard let all = self.incompatibilities[node] else {\n                    return nil\n                }\n                return all.filter {\n                    $0.terms.first { $0.node == node }!.isPositive\n                }\n            }\n        }\n\n        func decide(_ node: DependencyResolutionNode, at version: Version) {\n            let term = Term(node, .exact(version))\n            self.lock.withLock {\n                assert(term.isValidDecision(for: self.solution))\n                self.solution.decide(node, at: version)\n            }\n        }\n\n        func derive(_ term: Term, cause: Incompatibility) {\n            self.lock.withLock {\n                self.solution.derive(term, cause: cause)\n            }\n        }\n\n        func backtrack(toDecisionLevel: Int) {\n            self.lock.withLock {\n                self.solution.backtrack(toDecisionLevel: toDecisionLevel)\n            }\n        }\n    }\n\n    /// `Package.resolved` representation.\n    private let resolvedPackages: ResolvedPackagesStore.ResolvedPackages\n\n    /// The container provider used to load package containers.\n    private let provider: ContainerProvider\n\n    /// Reference to the package container provider.\n    private let packageContainerProvider: PackageContainerProvider\n\n    /// Should resolver prefetch the containers.\n    private let prefetchBasedOnResolvedFile: Bool\n\n    /// Update containers while fetching them.\n    private let skipDependenciesUpdates: Bool\n\n    /// Resolver delegate\n    private let delegate: DependencyResolverDelegate?\n\n    @available(*,\n        deprecated,\n        renamed: \"init(provider:resolvedPackages:skipDependenciesUpdates:prefetchBasedOnResolvedFile:observabilityScope:delegate:)\",\n        message: \"Renamed for consistency with the actual name of the feature\"\n    )\n    @_disfavoredOverload\n    public init(\n        provider: PackageContainerProvider,\n        pins: ResolvedPackagesStore.ResolvedPackages = [:],\n        skipDependenciesUpdates: Bool = false,\n        prefetchBasedOnResolvedFile: Bool = false,\n        observabilityScope: ObservabilityScope,\n        delegate: DependencyResolverDelegate? = nil\n    ) {\n        self.init(\n            provider: provider,\n            resolvedPackages: pins,\n            skipDependenciesUpdates: skipDependenciesUpdates,\n            prefetchBasedOnResolvedFile: prefetchBasedOnResolvedFile,\n            observabilityScope: observabilityScope,\n            delegate: delegate\n        )\n    }\n\n    public init(\n        provider: PackageContainerProvider,\n        resolvedPackages: ResolvedPackagesStore.ResolvedPackages = [:],\n        skipDependenciesUpdates: Bool = false,\n        prefetchBasedOnResolvedFile: Bool = false,\n        observabilityScope: ObservabilityScope,\n        delegate: DependencyResolverDelegate? = nil\n    ) {\n        self.packageContainerProvider = provider\n        self.resolvedPackages = resolvedPackages\n        self.skipDependenciesUpdates = skipDependenciesUpdates\n        self.prefetchBasedOnResolvedFile = prefetchBasedOnResolvedFile\n        self.provider = ContainerProvider(\n            provider: self.packageContainerProvider,\n            skipUpdate: self.skipDependenciesUpdates,\n            resolvedPackages: self.resolvedPackages,\n            observabilityScope: observabilityScope\n        )\n        self.delegate = delegate\n    }\n\n    /// Execute the resolution algorithm to find a valid assignment of versions.\n    public func solve(constraints: [Constraint]) async -> Result<[DependencyResolverBinding], Error> {\n        // the graph resolution root\n        let root: DependencyResolutionNode\n        if constraints.count == 1, let constraint = constraints.first, constraint.package.kind.isRoot {\n            // root level package, use it as our resolution root\n            root = .root(package: constraint.package, enabledTraits: constraint.enabledTraits)\n        } else {\n            // more complex setup requires a synthesized root\n            root = .root(\n                package: .root(\n                    identity: .plain(\"<synthesized-root>\"),\n                    path: .root\n                ),\n                enabledTraits: [\"default\"]\n            )\n        }\n\n        do {\n            // strips state\n            let bindings = try await self.solve(root: root, constraints: constraints).bindings\n            return .success(bindings)\n        } catch {\n            // If version solving failing, build the user-facing diagnostic.\n            if let pubGrubError = error as? PubGrubError, let rootCause = pubGrubError.rootCause, let incompatibilities = pubGrubError.incompatibilities {\n                do {\n                    var builder = DiagnosticReportBuilder(\n                        root: root,\n                        incompatibilities: incompatibilities,\n                        provider: self.provider\n                    )\n                    let diagnostic = try await builder.makeErrorReport(for: rootCause)\n                    return .failure(PubGrubError.unresolvable(diagnostic))\n                } catch {\n                    // failed to construct the report, will report the original error\n                    return .failure(error)\n                }\n            }\n            return .failure(error)\n        }\n    }\n\n    /// Find a set of dependencies that fit the given constraints. If dependency\n    /// resolution is unable to provide a result, an error is thrown.\n    /// - Warning: It is expected that the root package reference has been set  before this is called.\n    internal func solve(root: DependencyResolutionNode, constraints: [Constraint]) async throws -> (bindings: [DependencyResolverBinding], state: State) {\n        // first process inputs\n        let inputs = try await self.processInputs(root: root, with: constraints)\n\n        // Prefetch the containers if prefetching is enabled.\n        if self.prefetchBasedOnResolvedFile {\n            // We avoid prefetching packages that are overridden since\n            // otherwise we'll end up creating a repository container\n            // for them.\n            let resolvedPackageReferences = self.resolvedPackages.values\n                .map(\\.packageRef)\n                .filter { !inputs.overriddenPackages.keys.contains($0) }\n            self.provider.prefetch(containers: resolvedPackageReferences)\n        }\n\n        let state = State(root: root, overriddenPackages: inputs.overriddenPackages)\n\n        // Decide root at v1.\n        state.decide(state.root, at: \"1.0.0\")\n\n        // Add the root incompatibility.\n        state.addIncompatibility(Incompatibility(terms: [Term(not: root, .exact(\"1.0.0\"))], cause: .root), at: .topLevel)\n\n        // Add inputs root incompatibilities.\n        for incompatibility in inputs.rootIncompatibilities {\n            state.addIncompatibility(incompatibility, at: .topLevel)\n        }\n\n        try await self.run(state: state)\n\n        let decisions = state.solution.assignments.filter(\\.isDecision)\n        var flattenedAssignments: [PackageReference: (binding: BoundVersion, products: ProductFilter)] = [:]\n        for assignment in decisions {\n            if assignment.term.node == state.root {\n                continue\n            }\n\n            let boundVersion: BoundVersion\n            switch assignment.term.requirement {\n            case .exact(let version):\n                boundVersion = .version(version)\n            case .range, .any, .empty, .ranges:\n                throw InternalError(\"unexpected requirement value for assignment \\(assignment.term)\")\n            }\n\n            let products = assignment.term.node.productFilter\n            let container = try await withCheckedThrowingContinuation { continuation in\n                self.provider.getContainer(\n                    for: assignment.term.node.package,\n                    completion: {\n                        continuation.resume(with: $0)\n                    }\n                )\n            }\n            let updatePackage = try await container.underlying.loadPackageReference(at: boundVersion)\n\n            if var existing = flattenedAssignments[updatePackage] {\n                guard existing.binding == boundVersion else {\n                    throw InternalError(\"Two products in one package resolved to different versions: \\(existing.products)@\\(existing.binding) vs \\(products)@\\(boundVersion)\")\n                }\n                existing.products.formUnion(products)\n                flattenedAssignments[updatePackage] = existing\n            } else {\n                flattenedAssignments[updatePackage] = (binding: boundVersion, products: products)\n            }\n        }\n        var finalAssignments: [DependencyResolverBinding]\n            = flattenedAssignments.keys.sorted(by: { $0.deprecatedName < $1.deprecatedName }).map { package in\n                let details = flattenedAssignments[package]!\n                return .init(package: package, boundVersion: details.binding, products: details.products)\n            }\n\n        // Add overridden packages to the result.\n        for (package, override) in state.overriddenPackages {\n            let container = try await withCheckedThrowingContinuation { continuation in\n                self.provider.getContainer(for: package, completion: {\n                    continuation.resume(with: $0)\n                })\n            }\n            let updatePackage = try await container.underlying.loadPackageReference(at: override.version)\n            finalAssignments.append(.init(\n                    package: updatePackage,\n                    boundVersion: override.version,\n                    products: override.products\n            ))\n        }\n\n        self.delegate?.solved(result: finalAssignments)\n\n        return (finalAssignments, state)\n    }\n\n    private func processInputs(\n        root: DependencyResolutionNode,\n        with constraints: [Constraint]\n    ) async throws -> (\n        overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)],\n        rootIncompatibilities: [Incompatibility]\n    ) {\n        // The list of constraints that we'll be working with. We start with the input constraints\n        // and process them in two phases. The first phase finds all unversioned constraints and\n        // the second phase discovers all branch-based constraints.\n        var constraints = OrderedCollections.OrderedSet(constraints)\n\n        // The list of packages that are overridden in the graph. A local package reference will\n        // always override any other kind of package reference and branch-based reference will override\n        // version-based reference.\n        var overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)] = [:]\n\n        // The list of version-based references reachable via local and branch-based references.\n        // These are added as top-level incompatibilities since they always need to be satisfied.\n        // Some of these might be overridden as we discover local and branch-based references.\n        var versionBasedDependencies = OrderedCollections.OrderedDictionary<DependencyResolutionNode, [VersionBasedConstraint]>()\n\n        // Process unversioned constraints in first phase. We go through all of the unversioned packages\n        // and collect them and their dependencies. This gives us the complete list of unversioned\n        // packages in the graph since unversioned packages can only be referred by other\n        // unversioned packages.\n        while let constraint = constraints.first(where: { $0.requirement == .unversioned }) {\n            constraints.remove(constraint)\n\n            // Mark the package as overridden.\n            if var existing = overriddenPackages[constraint.package] {\n                guard existing.version == .unversioned else {\n                    throw InternalError(\"Overridden package is not unversioned: \\(constraint.package)@\\(existing.version)\")\n                }\n                existing.products.formUnion(constraint.products)\n                overriddenPackages[constraint.package] = existing\n            } else {\n                overriddenPackages[constraint.package] = (version: .unversioned, products: constraint.products)\n            }\n\n            for node in constraint.nodes() {\n                // Process dependencies of this package.\n                //\n                // We collect all version-based dependencies in a separate structure so they can\n                // be process at the end. This allows us to override them when there is a non-version\n                // based (unversioned/branch-based) constraint present in the graph.\n                let container = try await withCheckedThrowingContinuation { continuation in\n                    self.provider.getContainer(\n                        for: node.package,\n                        completion: {\n                            continuation.resume(with: $0)\n                        }\n                    )\n                }\n\n                for dependency in try await container.underlying\n                    .getUnversionedDependencies(productFilter: node.productFilter, node.enabledTraits)\n                {\n                    if let versionedBasedConstraints = VersionBasedConstraint.constraints(dependency) {\n                        for constraint in versionedBasedConstraints {\n                            versionBasedDependencies[node, default: []].append(constraint)\n                        }\n                    } else if !overriddenPackages.keys.contains(dependency.package) {\n                        // Add the constraint if its not already present. This will ensure we don't\n                        // end up looping infinitely due to a cycle (which are diagnosed separately).\n                        constraints.append(dependency)\n                    }\n                }\n            }\n        }\n\n        // Process revision-based constraints in the second phase. Here we do the similar processing\n        // as the first phase but we also ignore the constraints that are overridden due to\n        // presence of unversioned constraints.\n        while let constraint = constraints.first(where: { $0.requirement.isRevision }) {\n            guard case .revision(let revision) = constraint.requirement else {\n                throw InternalError(\"Expected revision requirement\")\n            }\n            constraints.remove(constraint)\n            let package = constraint.package\n\n            // Check if there is an existing value for this package in the overridden packages.\n            switch overriddenPackages[package]?.version {\n            case .excluded?, .version?:\n                // These values are not possible.\n                throw InternalError(\"Unexpected value for overridden package \\(package) in \\(overriddenPackages)\")\n            case .unversioned?:\n                // This package is overridden by an unversioned package so we can ignore this constraint.\n                continue\n            case .revision(let existingRevision, let branch)?:\n                // If this branch-based package was encountered before, ensure the references match.\n                if (branch ?? existingRevision) != revision {\n                    throw PubGrubError.unresolvable(\"\\(package.identity) is required using two different revision-based requirements (\\(existingRevision) and \\(revision)), which is not supported\")\n                } else {\n                    // Otherwise, continue since we've already processed this constraint. Any cycles will be diagnosed separately.\n                    continue\n                }\n            case nil:\n                break\n            }\n\n            // Process dependencies of this package, similar to the first phase but branch-based dependencies\n            // are not allowed to contain local/unversioned packages.\n            let container = try await withCheckedThrowingContinuation { continuation in\n                self.provider.getContainer(for: package, completion: {\n                    continuation.resume(with: $0)\n                })\n            }\n\n            // If there is a pin for this revision-based dependency, get\n            // the dependencies at the pinned revision instead of using\n            // latest commit on that branch. Note that if this revision-based dependency is\n            // already a commit, then its pin entry doesn't matter in practice.\n            let revisionForDependencies: String\n            if case .branch(revision, let pinRevision) = self.resolvedPackages[package.identity]?.state {\n                revisionForDependencies = pinRevision\n\n                // Mark the package as overridden with the pinned revision and record the branch as well.\n                overriddenPackages[package] = (version: .revision(revisionForDependencies, branch: revision), products: constraint.products)\n            } else {\n                revisionForDependencies = revision\n\n                // Mark the package as overridden.\n                overriddenPackages[package] = (version: .revision(revision), products: constraint.products)\n            }\n\n            for node in constraint.nodes() {\n                var unprocessedDependencies = try await container.underlying.getDependencies(\n                    at: revisionForDependencies,\n                    productFilter: constraint.products,\n                    node.enabledTraits\n                )\n                if let sharedRevision = node.revisionLock(revision: revision) {\n                    unprocessedDependencies.append(sharedRevision)\n                }\n                for dependency in unprocessedDependencies {\n                    switch dependency.requirement {\n                    case .versionSet(let req):\n                        for node in dependency.nodes() {\n                            let versionedBasedConstraint = VersionBasedConstraint(node: node, req: req)\n                            versionBasedDependencies[.root(package: constraint.package), default: []].append(versionedBasedConstraint)\n                        }\n                    case .revision:\n                        constraints.append(dependency)\n                    case .unversioned:\n                        throw DependencyResolverError.revisionDependencyContainsLocalPackage(\n                            dependency: package.identity.description,\n                            localPackage: dependency.package.identity.description\n                        )\n                    }\n                }\n            }\n        }\n\n        // At this point, we should be left with only version-based requirements in our constraints\n        // list. Add them to our version-based dependency list.\n        for constraint in constraints {\n            switch constraint.requirement {\n            case .versionSet(let req):\n                for node in constraint.nodes() {\n                    let versionedBasedConstraint = VersionBasedConstraint(node: node, req: req)\n                    versionBasedDependencies[root, default: []].append(versionedBasedConstraint)\n                }\n            case .revision, .unversioned:\n                throw InternalError(\"Unexpected revision/unversioned requirement in the constraints list: \\(constraints)\")\n            }\n        }\n\n        // Finally, compute the root incompatibilities (which will be all version-based).\n        // note versionBasedDependencies may point to the root package dependencies, or the dependencies of root's non-versioned dependencies\n        var rootIncompatibilities: [Incompatibility] = []\n        for (node, constraints) in versionBasedDependencies {\n            for constraint in constraints {\n                if overriddenPackages.keys.contains(constraint.node.package) { continue }\n                let incompat = try Incompatibility(\n                    Term(root, .exact(\"1.0.0\")),\n                    Term(not: constraint.node, constraint.requirement),\n                    root: root,\n                    cause: .dependency(node: node)\n                )\n                rootIncompatibilities.append(incompat)\n            }\n        }\n\n        return (overriddenPackages, rootIncompatibilities)\n    }\n\n    /// Perform unit propagation, resolving conflicts if necessary and making\n    /// decisions if nothing else is left to be done.\n    /// After this method returns `solution` is either populated with a list of\n    /// final version assignments or an error is thrown.\n    private func run(state: State) async throws {\n        var next: DependencyResolutionNode? = state.root\n\n        while let nxt = next {\n            try self.propagate(state: state, node: nxt)\n\n            // initiate prefetch of known packages that will be used to make the decision on the next step\n            self.provider.prefetch(containers: state.solution.undecided.map(\\.node.package))\n\n            // If decision making determines that no more decisions are to be\n            // made, it returns nil to signal that version solving is done.\n            next = try await self.makeDecision(state: state)\n        }\n    }\n\n    /// Perform unit propagation to derive new assignments based on the current\n    /// partial solution.\n    /// If a conflict is found, the conflicting incompatibility is returned to\n    /// resolve the conflict on.\n    internal func propagate(state: State, node: DependencyResolutionNode) throws {\n        var changed: OrderedCollections.OrderedSet<DependencyResolutionNode> = [node]\n\n        while !changed.isEmpty {\n            let package = changed.removeFirst()\n            loop: for incompatibility in state.positiveIncompatibilities(for: package)?.reversed() ?? [] {\n                let result = self.propagate(state: state, incompatibility: incompatibility)\n\n                switch result {\n                case .conflict:\n                    let rootCause = try self.resolve(state: state, conflict: incompatibility)\n                    let rootCauseResult = self.propagate(state: state, incompatibility: rootCause)\n\n                    guard case .almostSatisfied(let pkg) = rootCauseResult else {\n                        throw InternalError(\"\"\"\n                        Expected root cause \\(rootCause) to almost satisfy the \\\n                        current partial solution:\n                        \\(state.solution.assignments.map { \" * \\($0.description)\" }.joined(separator: \"\\n\"))\\n\n                        \"\"\")\n                    }\n\n                    changed.removeAll(keepingCapacity: false)\n                    changed.append(pkg)\n\n                    break loop\n                case .almostSatisfied(let package):\n                    changed.append(package)\n                case .none:\n                    break\n                }\n            }\n        }\n    }\n\n    private func propagate(state: State, incompatibility: Incompatibility) -> PropagationResult {\n        var unsatisfied: Term?\n\n        for term in incompatibility.terms {\n            let relation = state.solution.relation(with: term)\n\n            if relation == .disjoint {\n                return .none\n            } else if relation == .overlap {\n                if unsatisfied != nil {\n                    return .none\n                }\n                unsatisfied = term\n            }\n        }\n\n        // We have a conflict if all the terms of the incompatibility were satisfied.\n        guard let unsatisfiedTerm = unsatisfied else {\n            return .conflict\n        }\n\n\n        state.derive(unsatisfiedTerm.inverse, cause: incompatibility)\n        self.delegate?.derived(term: unsatisfiedTerm.inverse)\n        return .almostSatisfied(node: unsatisfiedTerm.node)\n    }\n\n    // Based on:\n    // https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution               //ignore-unacceptable-language\n    // https://github.com/dart-lang/pub/blob/master/lib/src/solver/version_solver.dart#L201         //ignore-unacceptable-language\n    internal func resolve(state: State, conflict: Incompatibility) throws -> Incompatibility {\n        self.delegate?.conflict(conflict: conflict)\n\n        var incompatibility = conflict\n        var createdIncompatibility = false\n\n        // rdar://93335995\n        // hard protection from infinite loops\n        let maxIterations = 1000\n        var iterations = 0\n\n        while !isCompleteFailure(incompatibility, root: state.root) {\n            var mostRecentTerm: Term?\n            var mostRecentSatisfier: Assignment?\n            var difference: Term?\n            var previousSatisfierLevel = 0\n\n            for term in incompatibility.terms {\n                let satisfier = try state.solution.satisfier(for: term)\n\n                if let _mostRecentSatisfier = mostRecentSatisfier {\n                    let mostRecentSatisfierIdx = state.solution.assignments.firstIndex(of: _mostRecentSatisfier)!\n                    let satisfierIdx = state.solution.assignments.firstIndex(of: satisfier)!\n\n                    if mostRecentSatisfierIdx < satisfierIdx {\n                        previousSatisfierLevel = max(previousSatisfierLevel, _mostRecentSatisfier.decisionLevel)\n                        mostRecentTerm = term\n                        mostRecentSatisfier = satisfier\n                        difference = nil\n                    } else {\n                        previousSatisfierLevel = max(previousSatisfierLevel, satisfier.decisionLevel)\n                    }\n                } else {\n                    mostRecentTerm = term\n                    mostRecentSatisfier = satisfier\n                }\n\n                if mostRecentTerm == term {\n                    difference = mostRecentSatisfier?.term.difference(with: term)\n                    if let difference {\n                        previousSatisfierLevel = max(previousSatisfierLevel, try state.solution.satisfier(for: difference.inverse).decisionLevel)\n                    }\n                }\n            }\n\n            guard let _mostRecentSatisfier = mostRecentSatisfier else {\n                throw InternalError(\"mostRecentSatisfier not set\")\n            }\n\n            if previousSatisfierLevel < _mostRecentSatisfier.decisionLevel || _mostRecentSatisfier.cause == nil {\n                state.backtrack(toDecisionLevel: previousSatisfierLevel)\n                if createdIncompatibility {\n                    state.addIncompatibility(incompatibility, at: .conflictResolution)\n                }\n                return incompatibility\n            }\n\n            let priorCause = _mostRecentSatisfier.cause!\n\n            var newTerms = Array(incompatibility.terms.filter { $0 != mostRecentTerm })\n            newTerms += priorCause.terms.filter { $0.node != _mostRecentSatisfier.term.node }\n\n            if let _difference = difference {\n                // rdar://93335995\n                // do not add the exact inverse of a requirement as it can lead to endless loops\n                if _difference.inverse != mostRecentTerm {\n                    newTerms.append(_difference.inverse)\n                }\n            }\n\n            incompatibility = try Incompatibility(\n                OrderedCollections.OrderedSet(newTerms),\n                root: state.root,\n                cause: .conflict(cause: .init(conflict: incompatibility, other: priorCause))\n            )\n            createdIncompatibility = true\n\n            if let mostRecentTerm {\n                if let difference {\n                    self.delegate?.partiallySatisfied(term: mostRecentTerm, by: _mostRecentSatisfier, incompatibility: incompatibility, difference: difference)\n                } else {\n                    self.delegate?.satisfied(term: mostRecentTerm, by: _mostRecentSatisfier, incompatibility: incompatibility)\n                }\n            }\n\n            // rdar://93335995\n            // hard protection from infinite loops\n            iterations = iterations + 1\n            if iterations >= maxIterations {\n                break\n            }\n        }\n\n        self.delegate?.failedToResolve(incompatibility: incompatibility)\n        throw PubGrubError._unresolvable(incompatibility, state.incompatibilities)\n    }\n\n    /// Does a given incompatibility specify that version solving has entirely\n    /// failed, meaning this incompatibility is either empty or only for the root\n    /// package.\n    private func isCompleteFailure(_ incompatibility: Incompatibility, root: DependencyResolutionNode) -> Bool {\n        incompatibility.terms.isEmpty || (incompatibility.terms.count == 1 && incompatibility.terms.first?.node == root)\n    }\n\n    private func computeCounts(\n        for terms: [Term]\n    ) async throws -> [Term: Int] {\n        if terms.isEmpty {\n            return [:]\n        }\n        return try await withThrowingTaskGroup(of: (Term, Int).self) { group in\n            for term in terms {\n                group.addTask {\n                    let container = try await withCheckedThrowingContinuation { continuation in\n                        self.provider.getContainer(for: term.node.package, completion: {\n                            continuation.resume(with: $0)\n                        })\n                    }\n                    return try await (term, container.versionCount(term.requirement))\n                }\n            }\n\n            return try await group.reduce(into: [:]) { partialResult, termCount in\n                partialResult[termCount.0] = termCount.1\n            }\n        }\n    }\n\n    internal func makeDecision(\n        state: State\n    ) async throws -> DependencyResolutionNode? {\n        // If there are no more undecided terms, version solving is complete.\n        let undecided = state.solution.undecided\n        guard !undecided.isEmpty else {\n            return nil\n        }\n\n        // Prefer packages with least number of versions that fit the current requirements so we\n        // get conflicts (if any) sooner.\n        let start = DispatchTime.now()\n        let counts = try await self.computeCounts(for: undecided)\n        // forced unwraps safe since we are testing for count and errors above\n        let pkgTerm = undecided.min {\n            // Prefer packages that don't allow pre-release versions\n            // to allow propagation logic to find dependencies that\n            // limit the range before making any decisions. This means\n            // that we'd always prefer release versions.\n            if $0.supportsPrereleases != $1.supportsPrereleases {\n                return !$0.supportsPrereleases\n            }\n\n            return counts[$0]! < counts[$1]!\n        }!\n        self.delegate?.willResolve(term: pkgTerm)\n        // at this point the container is cached\n        let container = try self.provider.getCachedContainer(for: pkgTerm.node.package)\n\n        // Get the best available version for this package.\n        guard let version = try await container.getBestAvailableVersion(for: pkgTerm) else {\n            state.addIncompatibility(try Incompatibility(pkgTerm, root: state.root, cause: .noAvailableVersion), at: .decisionMaking)\n            return pkgTerm.node\n        }\n\n        // Add all of this version's dependencies as incompatibilities.\n        let depIncompatibilities = try await container.incompatibilites(\n            at: version,\n            node: pkgTerm.node,\n            overriddenPackages: state.overriddenPackages,\n            root: state.root\n        )\n\n        var haveConflict = false\n        for incompatibility in depIncompatibilities {\n            // Add the incompatibility to our partial solution.\n            state.addIncompatibility(incompatibility, at: .decisionMaking)\n\n            // Check if this incompatibility will satisfy the solution.\n            haveConflict = haveConflict || incompatibility.terms.allSatisfy {\n                // We only need to check if the terms other than this package\n                // are satisfied because we _know_ that the terms matching\n                // this package will be satisfied if we make this version\n                // as a decision.\n                $0.node == pkgTerm.node || state.solution.satisfies($0)\n            }\n        }\n\n        // Decide this version if there was no conflict with its dependencies.\n        if !haveConflict {\n            self.delegate?.didResolve(term: pkgTerm, version: version, duration: start.distance(to: .now()))\n            state.decide(pkgTerm.node, at: version)\n        }\n\n        return pkgTerm.node\n    }\n}\n\ninternal enum LogLocation: String {\n    case topLevel = \"top level\"\n    case unitPropagation = \"unit propagation\"\n    case decisionMaking = \"decision making\"\n    case conflictResolution = \"conflict resolution\"\n}\n\npublic extension PubGrubDependencyResolver {\n    enum PubGrubError: Swift.Error, CustomStringConvertible {\n        case _unresolvable(Incompatibility, [DependencyResolutionNode: [Incompatibility]])\n        case unresolvable(String)\n\n        public var description: String {\n            switch self {\n            case ._unresolvable(let rootCause, _):\n                rootCause.description\n            case .unresolvable(let error):\n                error\n            }\n        }\n\n        var rootCause: Incompatibility? {\n            switch self {\n            case ._unresolvable(let rootCause, _):\n                rootCause\n            case .unresolvable:\n                nil\n            }\n        }\n\n        var incompatibilities: [DependencyResolutionNode: [Incompatibility]]? {\n            switch self {\n            case ._unresolvable(_, let incompatibilities):\n                incompatibilities\n            case .unresolvable:\n                nil\n            }\n        }\n    }\n}\n\nextension PubGrubDependencyResolver {\n    private struct VersionBasedConstraint {\n        let node: DependencyResolutionNode\n        let requirement: VersionSetSpecifier\n\n        init(node: DependencyResolutionNode, req: VersionSetSpecifier) {\n            self.node = node\n            self.requirement = req\n        }\n\n        internal static func constraints(_ constraint: Constraint) -> [VersionBasedConstraint]? {\n            switch constraint.requirement {\n            case .versionSet(let req):\n                constraint.nodes().map { VersionBasedConstraint(node: $0, req: req) }\n            case .revision:\n                nil\n            case .unversioned:\n                nil\n            }\n        }\n    }\n}\n\nprivate enum PropagationResult {\n    case conflict\n    case almostSatisfied(node: DependencyResolutionNode)\n    case none\n}\n\nprivate extension PackageRequirement {\n    var isRevision: Bool {\n        switch self {\n        case .versionSet, .unversioned:\n            false\n        case .revision:\n            true\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PubGrub/PubGrubPackageContainer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport OrderedCollections\nimport PackageModel\n\nimport struct TSCUtility.Version\n\n/// A container for an individual package. This enhances PackageContainer to add PubGrub specific\n/// logic which is mostly related to computing incompatibilities at a particular version.\nfinal class PubGrubPackageContainer {\n    /// The underlying package container.\n    let underlying: PackageContainer\n\n    /// `Package.resolved` in-memory representation.\n    private let resolvedPackages: ResolvedPackagesStore.ResolvedPackages\n\n    init(underlying: PackageContainer, resolvedPackages: ResolvedPackagesStore.ResolvedPackages) {\n        self.underlying = underlying\n        self.resolvedPackages = resolvedPackages\n    }\n\n    var package: PackageReference {\n        self.underlying.package\n    }\n\n    /// Returns the pinned version for this package, if any.\n    var pinnedVersion: Version? {\n        switch self.resolvedPackages[self.underlying.package.identity]?.state {\n        case .version(let version, _):\n            version\n        default:\n            .none\n        }\n    }\n\n    /// Returns the numbers of versions that are satisfied by the given version requirement.\n    func versionCount(_ requirement: VersionSetSpecifier) async throws -> Int {\n        if let pinnedVersion, requirement.contains(pinnedVersion) {\n            return 1\n        }\n        return try await self.underlying.versionsDescending().filter(requirement.contains).count\n    }\n\n    /// Computes the bounds of the given range against the versions available in the package.\n    ///\n    /// `includesLowerBound` is `false` if range's lower bound is less than or equal to the lowest available version.\n    /// Similarly, `includesUpperBound` is `false` if range's upper bound is greater than or equal to the highest\n    /// available version.\n    func computeBounds(for range: Range<Version>) async throws -> (includesLowerBound: Bool, includesUpperBound: Bool) {\n        var includeLowerBound = true\n        var includeUpperBound = true\n\n        let versions = try await self.underlying.versionsDescending()\n\n        if let last = versions.last, range.lowerBound < last {\n            includeLowerBound = false\n        }\n\n        if let first = versions.first, range.upperBound > first {\n            includeUpperBound = false\n        }\n\n        return (includeLowerBound, includeUpperBound)\n    }\n\n    /// Returns the best available version for a given term.\n    func getBestAvailableVersion(for term: Term) async throws -> Version? {\n        assert(term.isPositive, \"Expected term to be positive\")\n        var versionSet = term.requirement\n\n        // Restrict the selection to the pinned version if is allowed by the current requirements.\n        if let pinnedVersion = self.pinnedVersion {\n            if versionSet.contains(pinnedVersion) {\n                if !self.underlying.shouldInvalidatePinnedVersions {\n                    versionSet = .exact(pinnedVersion)\n                } else {\n                    // Make sure the pinned version is still available\n                    let version = try await self.underlying.versionsDescending().first { pinnedVersion == $0 }\n                    if version != nil {\n                        return version\n                    }\n                }\n            }\n        }\n\n        // Return the highest version that is allowed by the input requirement.\n        return try await self.underlying.versionsDescending().first { versionSet.contains($0) }\n    }\n\n    /// Compute the bounds of incompatible tools version starting from the given version.\n    private func computeIncompatibleToolsVersionBounds(fromVersion: Version) async throws -> VersionSetSpecifier {\n        // TODO: do we really want to compute this for an assert?\n        // assert(!self.underlying.isToolsVersionCompatible(at: fromVersion))\n        let versions: [Version] = try await self.underlying.versionsAscending()\n\n        // This is guaranteed to be present.\n        let idx = versions.firstIndex(of: fromVersion)!\n\n        var lowerBound = fromVersion\n        var upperBound = fromVersion\n\n        for version in versions.dropFirst(idx + 1) {\n            let isToolsVersionCompatible = await self.underlying.isToolsVersionCompatible(at: version)\n            if isToolsVersionCompatible {\n                break\n            }\n            upperBound = version\n        }\n\n        for version in versions.dropLast(versions.count - idx).reversed() {\n            let isToolsVersionCompatible = await self.underlying.isToolsVersionCompatible(at: version)\n            if isToolsVersionCompatible {\n                break\n            }\n            lowerBound = version\n        }\n\n        // If lower and upper bounds didn't change then this is the sole incompatible version.\n        if lowerBound == upperBound {\n            return .exact(lowerBound)\n        }\n\n        // If lower bound is the first version then we can use 0 as the sentinel. This\n        // will end up producing a better diagnostic since we can omit the lower bound.\n        if lowerBound == versions.first {\n            lowerBound = \"0.0.0\"\n        }\n\n        if upperBound == versions.last {\n            // If upper bound is the last version then we can use the next major version as the sentinel.\n            // This will end up producing a better diagnostic since we can omit the upper bound.\n            upperBound = Version(upperBound.major + 1, 0, 0)\n        } else {\n            // Use the next patch since the upper bound needs to be inclusive here.\n            upperBound = upperBound.nextPatch()\n        }\n        return .range(lowerBound ..< upperBound.nextPatch())\n    }\n\n    /// Returns the incompatibilities of a package at the given version.\n    func incompatibilites(\n        at version: Version,\n        node: DependencyResolutionNode,\n        overriddenPackages: [PackageReference: (version: BoundVersion, products: ProductFilter)],\n        root: DependencyResolutionNode\n    ) async throws -> [Incompatibility] {\n        // FIXME: It would be nice to compute bounds for this as well.\n        if await !self.underlying.isToolsVersionCompatible(at: version) {\n            let requirement = try await self.computeIncompatibleToolsVersionBounds(fromVersion: version)\n            let toolsVersion = try await self.underlying.toolsVersion(for: version)\n            return try [Incompatibility(\n                Term(node, requirement),\n                root: root,\n                cause: .incompatibleToolsVersion(toolsVersion)\n            )]\n        }\n\n        var unprocessedDependencies = try await self.underlying.getDependencies(\n            at: version,\n            productFilter: node.productFilter,\n            node.enabledTraits\n        )\n        if let sharedVersion = node.versionLock(version: version) {\n            unprocessedDependencies.append(sharedVersion)\n        }\n        var constraints: [PackageContainerConstraint] = []\n        for dep in unprocessedDependencies {\n            // Version-based packages are not allowed to contain unversioned dependencies.\n            guard case .versionSet = dep.requirement else {\n                let cause: Incompatibility.Cause = .versionBasedDependencyContainsUnversionedDependency(\n                    versionedDependency: self.package,\n                    unversionedDependency: dep.package\n                )\n                return try [Incompatibility(Term(node, .exact(version)), root: root, cause: cause)]\n            }\n\n            // Skip if this package is overridden.\n            if overriddenPackages.keys.contains(dep.package) {\n                continue\n            }\n\n            for node in dep.nodes() {\n                constraints.append(\n                    PackageContainerConstraint(\n                        package: node.package,\n                        requirement: dep.requirement,\n                        products: node.productFilter,\n                        enabledTraits: dep.enabledTraits\n                    )\n                )\n            }\n        }\n\n        return try constraints.flatMap { constraint -> [Incompatibility] in\n            // We only have version-based requirements at this point.\n            guard case .versionSet(let constraintRequirement) = constraint.requirement else {\n                throw InternalError(\"Unexpected unversioned requirement: \\(constraint)\")\n            }\n            return try constraint.nodes().compactMap { constraintNode in\n                // cycle\n                guard node != constraintNode else {\n                    return nil\n                }\n\n                var terms: OrderedCollections.OrderedSet<Term> = []\n                // the package version requirement\n                terms.append(Term(node, .exact(version)))\n                // the dependency's version requirement\n                terms.append(Term(not: constraintNode, constraintRequirement))\n\n                return try Incompatibility(terms, root: root, cause: .dependency(node: node))\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/PubGrub/Term.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A term represents a statement about a package that may be true or false.\npublic struct Term: Equatable, Hashable {\n    public let node: DependencyResolutionNode\n    public let requirement: VersionSetSpecifier\n    public let isPositive: Bool\n\n    public init(node: DependencyResolutionNode, requirement: VersionSetSpecifier, isPositive: Bool) {\n        self.node = node\n        self.requirement = requirement\n        self.isPositive = isPositive\n    }\n\n    public init(_ node: DependencyResolutionNode, _ requirement: VersionSetSpecifier) {\n        self.init(node: node, requirement: requirement, isPositive: true)\n    }\n\n    /// Create a new negative term.\n    public init(not node: DependencyResolutionNode, _ requirement: VersionSetSpecifier) {\n        self.init(node: node, requirement: requirement, isPositive: false)\n    }\n\n    /// The same term with an inversed `isPositive` value.\n    public var inverse: Term {\n        Term(\n            node: self.node,\n            requirement: self.requirement,\n            isPositive: !self.isPositive\n        )\n    }\n\n    package var supportsPrereleases: Bool {\n        self.requirement.supportsPrereleases\n    }\n\n    /// Check if this term satisfies another term, e.g. if `self` is true,\n    /// `other` must also be true.\n    public func satisfies(_ other: Term) -> Bool {\n        // TODO: This probably makes more sense as isSatisfied(by:) instead.\n        guard self.node == other.node else { return false }\n        return self.relation(with: other) == .subset\n    }\n\n    /// Create an intersection with another term.\n    public func intersect(with other: Term) -> Term? {\n        guard self.node == other.node else { return nil }\n        return self.intersect(withRequirement: other.requirement, andPolarity: other.isPositive)\n    }\n\n    /// Create an intersection with a requirement and polarity returning a new\n    /// term which represents the version constraints allowed by both the current\n    /// and given term.\n    ///\n    /// - returns: `nil` if an intersection is not possible.\n    public func intersect(\n        withRequirement requirement: VersionSetSpecifier,\n        andPolarity otherIsPositive: Bool\n    ) -> Term? {\n        let lhs = self.requirement\n        let rhs = requirement\n\n        let intersection: VersionSetSpecifier?\n        let isPositive: Bool\n        switch (self.isPositive, otherIsPositive) {\n        case (false, false):\n            intersection = lhs.union(rhs)\n            isPositive = false\n        case (true, true):\n            intersection = lhs.intersection(rhs)\n            isPositive = true\n        case (true, false):\n            intersection = lhs.difference(rhs)\n            isPositive = true\n        case (false, true):\n            intersection = rhs.difference(lhs)\n            isPositive = true\n        }\n\n        guard let versionIntersection = intersection, versionIntersection != .empty else {\n            return nil\n        }\n\n        return Term(node: self.node, requirement: versionIntersection, isPositive: isPositive)\n    }\n\n    public func difference(with other: Term) -> Term? {\n        self.intersect(with: other.inverse)\n    }\n\n    /// Verify if the term fulfills all requirements to be a valid choice for\n    /// making a decision in the given partial solution.\n    /// - There has to exist a positive derivation for it.\n    /// - There has to be no decision for it.\n    /// - The package version has to match all assignments.\n    public func isValidDecision(for solution: PartialSolution) -> Bool {\n        // The intersection between release and pre-release ranges is\n        // allowed to produce a pre-release range. This means that the\n        // solver is allowed to make a pre-release version decision\n        // even when some of the versions didn't allow pre-releases.\n        //\n        // This means that we should ignore pre-release differences\n        // while checking derivations and assert only if the term is\n        // pre-release but the last assignment wasn't.\n        if self.supportsPrereleases {\n            if let assignment = solution.assignments.last(where: { $0.term.node == self.node }) {\n                assert(assignment.term.supportsPrereleases)\n            }\n        }\n\n        for assignment in solution.assignments where assignment.term.node == self.node {\n            assert(!assignment.isDecision, \"Expected assignment to be a derivation.\")\n\n            // This is not great but dragging `ignorePrereleases` through all the APIs seems\n            // worse. This is valid because we can have a derivation chain which is something\n            // like - \"0.0.1\"..<\"1.0.0\" -> \"0.0.4-latest\"..<\"0.0.6\" and make a decision\n            // `0.0.4-alpha5` based on that if there is no `0.0.4` release. In vacuum this is\n            // (currently) incorrect because `0.0.4-alpha5` doesn't satisfy the initial\n            // range that doesn't support pre-release versions. Since the solver is\n            // allowed to derive a pre-release range we consider the original range to\n            // be pre-release range implicitly.\n            let term = if self.supportsPrereleases && !assignment.term.supportsPrereleases {\n                Term(self.node, self.requirement.withoutPrereleases)\n            } else {\n                self\n            }\n\n            guard term.satisfies(assignment.term) else { return false }\n        }\n        return true\n    }\n\n    // From: https://github.com/dart-lang/pub/blob/master/lib/src/solver/term.dart                  //ignore-unacceptable-language\n    public func relation(with other: Term) -> SetRelation {\n        if self.node != other.node {\n            assertionFailure(\"attempting to compute relation between different packages \\(self) \\(other)\")\n            return .error\n        }\n\n        if other.isPositive {\n            if self.isPositive {\n                // If the second requirement contains all the elements of\n                // the first requirement, then it is a subset relation.\n                if other.requirement.containsAll(self.requirement) {\n                    return .subset\n                }\n\n                // If second requirement contains any requirements of\n                // the first, then the relation is overlapping.\n                if other.requirement.containsAny(self.requirement) {\n                    return .overlap\n                }\n\n                // Otherwise it is disjoint.\n                return .disjoint\n            } else {\n                if self.requirement.containsAll(other.requirement) {\n                    return .disjoint\n                }\n                return .overlap\n            }\n        } else {\n            if self.isPositive {\n                if !other.requirement.containsAny(self.requirement) {\n                    return .subset\n                }\n                if other.requirement.containsAll(self.requirement) {\n                    return .disjoint\n                }\n                return .overlap\n            } else {\n                if self.requirement.containsAll(other.requirement) {\n                    return .subset\n                }\n                return .overlap\n            }\n        }\n    }\n\n    public enum SetRelation: Equatable {\n        /// The sets have nothing in common.\n        case disjoint\n        /// The sets have elements in common but first set is not a subset of second.\n        case overlap\n        /// The second set contains all elements of the first set.\n        case subset\n        // for error condition\n        case error\n    }\n}\n\nextension Term: CustomStringConvertible {\n    public var description: String {\n        let pkg = \"\\(node)\"\n        let req = self.requirement.description\n\n        if !self.isPositive {\n            return \"¬\\(pkg) \\(req)\"\n        }\n        return \"\\(pkg) \\(req)\"\n    }\n}\n\nextension VersionSetSpecifier {\n    fileprivate func containsAll(_ other: VersionSetSpecifier) -> Bool {\n        self.intersection(other) == other\n    }\n\n    fileprivate func containsAny(_ other: VersionSetSpecifier) -> Bool {\n        self.intersection(other) != .empty\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/ResolvedModule.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageModel\n\nimport func TSCBasic.topologicalSort\nimport struct Basics.IdentifiableSet\n\n@available(*, deprecated, renamed: \"ResolvedModule\")\npublic typealias ResolvedTarget = ResolvedModule\n\n/// Represents a fully resolved module. All the dependencies for this module are also stored as resolved.\npublic struct ResolvedModule {\n    /// Represents dependency of a resolved module.\n    public enum Dependency {\n        /// Direct dependency of the module. This module is in the same package and should be statically linked.\n        case module(_ module: ResolvedModule, conditions: [PackageCondition])\n\n        /// The module depends on this product.\n        case product(_ product: ResolvedProduct, conditions: [PackageCondition])\n\n        public var module: ResolvedModule? {\n            switch self {\n            case .module(let module, _): return module\n            case .product: return nil\n            }\n        }\n\n        public var product: ResolvedProduct? {\n            switch self {\n            case .module: return nil\n            case .product(let product, _): return product\n            }\n        }\n\n        public var conditions: [PackageCondition] {\n            switch self {\n            case .module(_, let conditions): return conditions\n            case .product(_, let conditions): return conditions\n            }\n        }\n\n        /// Returns the direct dependencies of the underlying dependency, across the package graph.\n        public var dependencies: [ResolvedModule.Dependency] {\n            switch self {\n            case .module(let module, _):\n                return module.dependencies\n            case .product(let product, _):\n                return product.modules.map { .module($0, conditions: []) }\n            }\n        }\n\n        /// Returns the direct dependencies of the underlying dependency, limited to the module's package.\n        public var packageDependencies: [ResolvedModule.Dependency] {\n            switch self {\n            case .module(let module, _):\n                return module.dependencies\n            case .product:\n                return []\n            }\n        }\n\n        public func satisfies(_ environment: BuildEnvironment) -> Bool {\n            conditions.allSatisfy { $0.satisfies(environment) }\n        }\n    }\n\n    /// The name of this module.\n    public var name: String {\n        self.underlying.name\n    }\n\n    /// Returns dependencies which satisfy the input build environment, based on their conditions.\n    /// - Parameters:\n    ///     - environment: The build environment to use to filter dependencies on.\n    public func dependencies(satisfying environment: BuildEnvironment) -> [Dependency] {\n        return dependencies.filter { $0.satisfies(environment) }\n    }\n\n    /// Returns the recursive dependencies, across the whole package-graph.\n    public func recursiveDependencies() throws -> [Dependency] {\n        try topologicalSort(self.dependencies) { $0.dependencies }\n    }\n\n    /// Returns the recursive module dependencies, across the whole package-graph.\n    public func recursiveModuleDependencies() throws -> [ResolvedModule] {\n        try topologicalSort(self.dependencies) { $0.dependencies }.compactMap { $0.module }\n    }\n\n    /// Returns the recursive dependencies, across the whole modules graph, which satisfy the input build environment,\n    /// based on their conditions.\n    /// - Parameters:\n    ///     - environment: The build environment to use to filter dependencies on.\n    public func recursiveDependencies(satisfying environment: BuildEnvironment) throws -> [Dependency] {\n        try topologicalSort(dependencies(satisfying: environment)) { dependency in\n            dependency.dependencies.filter { $0.satisfies(environment) }\n        }\n    }\n\n    /// Collect all of the plugins that the current target depends on.\n    package func pluginDependencies(satisfying environment: BuildEnvironment) -> [ResolvedModule] {\n        var plugins = IdentifiableSet<ResolvedModule>()\n        for dependency in self.dependencies(satisfying: environment) {\n            switch dependency {\n            case .module(let module, _):\n                if let plugin = module.underlying as? PluginModule {\n                    assert(plugin.capability == .buildTool)\n                    plugins.insert(module)\n                }\n            case .product(let product, _):\n                for plugin in product.modules.filter({ $0.underlying is PluginModule }) {\n                    plugins.insert(plugin)\n                }\n            }\n        }\n        return Array(plugins)\n    }\n\n    /// The language-level module name.\n    public var c99name: String {\n        self.underlying.c99name\n    }\n\n    /// Module aliases for dependencies of this module. The key is an\n    /// original module name and the value is a new unique name mapped\n    /// to the name of its .swiftmodule binary.\n    public var moduleAliases: [String: String]? {\n        self.underlying.moduleAliases\n    }\n\n    /// Allows access to package symbols from other modules in the package\n    public var packageAccess: Bool {\n        self.underlying.packageAccess\n    }\n\n    /// The \"type\" of the module.\n    public var type: Module.Kind {\n        self.underlying.type\n    }\n\n    /// The sources for the module.\n    public var sources: Sources {\n        self.underlying.sources\n    }\n\n    package let packageIdentity: PackageIdentity\n\n    /// The underlying module represented in this resolved module.\n    public let underlying: Module\n\n    /// The dependencies of this module.\n    public internal(set) var dependencies: [Dependency]\n\n    /// The default localization for resources.\n    public let defaultLocalization: String?\n\n    /// The list of platforms that are supported by this module.\n    public let supportedPlatforms: [SupportedPlatform]\n\n    /// A constraint on which platforms this module needs to build for.\n    /// Note: currently only set to .host if prebuilts are enabled.\n    public let platformConstraint: PlatformConstraint\n\n    @_spi(SwiftPMInternal)\n    public let platformVersionProvider: PlatformVersionProvider\n\n    package var hasDirectMacroDependencies: Bool {\n        self.dependencies.contains(where: {\n            switch $0 {\n            case .product(let productDependency, _):\n                productDependency.type == .macro\n            case .module(let moduleDependency, _):\n                moduleDependency.type == .macro\n            }\n        })\n    }\n\n    /// Whether this module comes from a declaration in the manifest file\n    /// or was synthesized (i.e. some test modules are synthesized).\n    public var implicit: Bool {\n        self.underlying.implicit\n    }\n\n    /// Create a resolved module instance.\n    public init(\n        packageIdentity: PackageIdentity,\n        underlying: Module,\n        dependencies: [ResolvedModule.Dependency],\n        defaultLocalization: String? = nil,\n        supportedPlatforms: [SupportedPlatform],\n        platformConstraint: PlatformConstraint,\n        platformVersionProvider: PlatformVersionProvider\n    ) {\n        self.packageIdentity = packageIdentity\n        self.underlying = underlying\n        self.dependencies = dependencies\n        self.defaultLocalization = defaultLocalization\n        self.supportedPlatforms = supportedPlatforms\n        self.platformConstraint = platformConstraint\n        self.platformVersionProvider = platformVersionProvider\n    }\n\n    public func getSupportedPlatform(for platform: Platform, usingXCTest: Bool) -> SupportedPlatform {\n        self.platformVersionProvider.getDerived(\n            declared: self.supportedPlatforms,\n            for: platform,\n            usingXCTest: usingXCTest\n        )\n    }\n}\n\nextension ResolvedModule: CustomStringConvertible {\n    public var description: String {\n        return \"<ResolvedModule: \\(self.name), \\(self.type)>\"\n    }\n}\n\nextension ResolvedModule.Dependency: CustomStringConvertible {\n    public var description: String {\n        var str = \"<ResolvedModule.Dependency: \"\n        switch self {\n        case .product(let p, _):\n            str += p.description\n        case .module(let t, _):\n            str += t.description\n        }\n        str += \">\"\n        return str\n    }\n}\n\nextension ResolvedModule.Dependency: Identifiable {\n    public struct ID: Hashable {\n        enum Kind: Hashable {\n            case module\n            case product\n\n            @available(*, deprecated, renamed: \"module\")\n            public static let target: Kind = .module\n        }\n\n        let kind: Kind\n        let packageIdentity: PackageIdentity\n        let name: String\n    }\n\n    public var id: ID {\n        switch self {\n        case .module(let module, _):\n            return .init(kind: .module, packageIdentity: module.packageIdentity, name: module.name)\n        case .product(let product, _):\n            return .init(kind: .product, packageIdentity: product.packageIdentity, name: product.name)\n        }\n    }\n}\n\nextension ResolvedModule.Dependency: Equatable {\n    public static func == (lhs: ResolvedModule.Dependency, rhs: ResolvedModule.Dependency) -> Bool {\n        switch (lhs, rhs) {\n        case (.module(let lhsModule, _), .module(let rhsModule, _)):\n            return lhsModule.id == rhsModule.id\n        case (.product(let lhsProduct, _), .product(let rhsProduct, _)):\n            return lhsProduct.id == rhsProduct.id\n        case (.product, .module), (.module, .product):\n            return false\n        }\n    }\n}\n\nextension ResolvedModule.Dependency: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        switch self {\n        case .module(let module, _):\n            hasher.combine(module.id)\n        case .product(let product, _):\n            hasher.combine(product.id)\n        }\n    }\n}\n\nextension ResolvedModule: Identifiable {\n    /// Resolved module identity that uniquely identifies it in a modules graph.\n    public struct ID: Hashable {\n        @available(*, deprecated, renamed: \"moduleName\")\n        public var targetName: String { self.moduleName }\n\n        public let moduleName: String\n        let packageIdentity: PackageIdentity\n    }\n\n    public var id: ID {\n        ID(moduleName: self.name, packageIdentity: self.packageIdentity)\n    }\n}\n\n@available(*, unavailable, message: \"Use `Identifiable` conformance or `IdentifiableSet` instead\")\nextension ResolvedModule: Hashable {}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/ResolvedPackage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\n\n/// A fully resolved package. Contains resolved modules, products and dependencies of the package.\npublic struct ResolvedPackage {\n    // The identity of the package.\n    public var identity: PackageIdentity {\n        return self.underlying.identity\n    }\n\n    /// The manifest describing the package.\n    public var manifest: Manifest {\n        return self.underlying.manifest\n    }\n\n    /// The local path of the package.\n    public var path: AbsolutePath {\n        return self.underlying.path\n    }\n\n    /// The underlying package reference.\n    public let underlying: Package\n\n    /// The modules contained in the package.\n    public let modules: IdentifiableSet<ResolvedModule>\n\n    /// The products produced by the package.\n    public let products: [ResolvedProduct]\n\n    /// The enabled traits of this package.\n    public let enabledTraits: Set<String>?\n\n    /// The dependencies of the package.\n    public let dependencies: [PackageIdentity]\n\n    /// The default localization for resources.\n    public let defaultLocalization: String?\n\n    /// The list of platforms that are supported by this package.\n    public let supportedPlatforms: [SupportedPlatform]\n\n    /// If the given package's source is a registry release, this provides additional metadata and signature information.\n    public let registryMetadata: RegistryReleaseMetadata?\n\n    @_spi(SwiftPMInternal)\n    public let platformVersionProvider: PlatformVersionProvider\n\n    public init(\n        underlying: Package,\n        defaultLocalization: String?,\n        supportedPlatforms: [SupportedPlatform],\n        dependencies: [PackageIdentity],\n        enabledTraits: Set<String>?,\n        modules: IdentifiableSet<ResolvedModule>,\n        products: [ResolvedProduct],\n        registryMetadata: RegistryReleaseMetadata?,\n        platformVersionProvider: PlatformVersionProvider\n    ) {\n        self.underlying = underlying\n        self.products = products\n        self.modules = modules\n        self.dependencies = dependencies\n        self.defaultLocalization = defaultLocalization\n        self.supportedPlatforms = supportedPlatforms\n        self.registryMetadata = registryMetadata\n        self.platformVersionProvider = platformVersionProvider\n        self.enabledTraits = enabledTraits\n    }\n\n    public func getSupportedPlatform(for platform: Platform, usingXCTest: Bool) -> SupportedPlatform {\n        self.platformVersionProvider.getDerived(\n            declared: self.supportedPlatforms,\n            for: platform,\n            usingXCTest: usingXCTest\n        )\n    }\n}\n\nextension ResolvedPackage: CustomStringConvertible {\n    public var description: String {\n        return \"<ResolvedPackage: \\(self.identity)>\"\n    }\n}\n\nextension ResolvedPackage: Identifiable {\n    public var id: PackageIdentity { self.underlying.identity }\n}\n\nextension ResolvedPackage: Comparable {\n    public static func < (lhs: ResolvedPackage, rhs: ResolvedPackage) -> Bool {\n        return lhs.id < rhs.id\n    }\n}\n\n@available(*, unavailable, message: \"Use `Identifiable` conformance or `IdentifiableSet` instead\")\nextension ResolvedPackage: Hashable {}\n"
  },
  {
    "path": "Sources/PackageGraph/Resolution/ResolvedProduct.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\n\npublic struct ResolvedProduct {\n    /// The name of this product.\n    public var name: String {\n        self.underlying.name\n    }\n\n    /// The type of this product.\n    public var type: ProductType {\n        self.underlying.type\n    }\n\n    public let packageIdentity: PackageIdentity\n\n    /// The underlying product.\n    public let underlying: Product\n\n    @available(*, deprecated, renamed: \"modules\")\n    public var targets: IdentifiableSet<ResolvedModule> { self.modules }\n\n    /// The top level modules contained in this product.\n    public internal(set) var modules: IdentifiableSet<ResolvedModule>\n\n    @available(*, deprecated, renamed: \"testEntryPointModule\")\n    public var testEntryPointTarget: ResolvedModule? { self.testEntryPointModule }\n\n    /// Executable module for test entry point file.\n    public let testEntryPointModule: ResolvedModule?\n\n    /// The default localization for resources.\n    public let defaultLocalization: String?\n\n    /// The list of platforms that are supported by this product.\n    public let supportedPlatforms: [SupportedPlatform]\n\n    /// The platform constraint that applies to this product. If any module is .all, the product is .all\n    public var platformConstraint: PlatformConstraint {\n        modules.contains(where: { $0.platformConstraint == .all }) ? .all : .host\n    }\n\n    @_spi(SwiftPMInternal)\n    public let platformVersionProvider: PlatformVersionProvider\n\n    @available(*, deprecated, renamed: \"executableModule\")\n    public var executableTarget: ResolvedModule { get throws { try self.executableModule } }\n\n    /// The main executable module of this product.\n    ///\n    /// Note: This property is only valid for executable products.\n    public var executableModule: ResolvedModule {\n        get throws {\n            guard self.type == .executable || self.type == .snippet || self.type == .macro else {\n                throw InternalError(\"`executableTarget` should only be called for executable targets\")\n            }\n            guard let underlyingExecutableModule = modules.map(\\.underlying).executables.first,\n                  let executableModule = modules.first(where: { $0.underlying == underlyingExecutableModule })\n            else {\n                throw InternalError(\"could not determine executable target\")\n            }\n            return executableModule\n        }\n    }\n\n    package var hasDirectMacroDependencies: Bool {\n        self.modules.contains(where: \\.hasDirectMacroDependencies)\n    }\n\n    @available(*, deprecated, renamed: \"init(packageIdentity:product:modules:)\")\n    public init(\n        packageIdentity: PackageIdentity,\n        product: Product,\n        targets: IdentifiableSet<ResolvedModule>\n    ) {\n        self.init(packageIdentity: packageIdentity, product: product, modules: targets)\n    }\n\n    public init(\n        packageIdentity: PackageIdentity,\n        product: Product,\n        modules: IdentifiableSet<ResolvedModule>\n    ) {\n        assert(product.modules.count == modules.count && product.modules.map(\\.name).sorted() == modules.map(\\.name).sorted())\n        self.packageIdentity = packageIdentity\n        self.underlying = product\n        self.modules = modules\n\n        // defaultLocalization is currently shared across the entire package\n        // this may need to be enhanced if / when we support localization per module or product\n        let defaultLocalization = self.modules.first?.defaultLocalization\n        self.defaultLocalization = defaultLocalization\n\n        let (platforms, platformVersionProvider) = Self.computePlatforms(modules: modules)\n        self.supportedPlatforms = platforms\n        self.platformVersionProvider = platformVersionProvider\n\n        self.testEntryPointModule = product.testEntryPointPath.map { testEntryPointPath in\n            // Create an executable resolved module with the entry point file, adding product's modules as dependencies.\n            let dependencies: [Module.Dependency] = product.modules.map { .module($0, conditions: []) }\n            let swiftModule = SwiftModule(\n                name: product.name,\n                dependencies: dependencies,\n                packageAccess: true, // entry point module so treated as a part of the package\n                testEntryPointPath: testEntryPointPath\n            )\n            return ResolvedModule(\n                packageIdentity: packageIdentity,\n                underlying: swiftModule,\n                dependencies: modules.map { .module($0, conditions: []) },\n                defaultLocalization: defaultLocalization ?? .none, // safe since this is a derived product\n                supportedPlatforms: platforms,\n                platformConstraint: .all,\n                platformVersionProvider: platformVersionProvider\n            )\n        }\n    }\n\n    @available(*, deprecated, renamed: \"containsSwiftModules\")\n    public var containsSwiftTargets: Bool { self.containsSwiftModules }\n\n    /// True if this product contains Swift modules.\n    public var containsSwiftModules: Bool {\n        //  C modules can't import Swift modules in SwiftPM (at least not right\n        // now), so we can just look at the top-level modules.\n        //\n        // If that ever changes, we'll need to do something more complex here,\n        // recursively checking dependencies for SwiftModules, and considering\n        // dynamic library modules to be Swift modules (since the dylib could\n        // contain Swift code we don't know about as part of this build).\n        self.modules.contains { $0.underlying is SwiftModule }\n    }\n\n    @available(*, deprecated, renamed: \"recursiveModuleDependencies\")\n    public func recursiveTargetDependencies() throws -> [ResolvedModule] { try self.recursiveModuleDependencies() }\n\n    /// Returns the recursive module dependencies.\n    public func recursiveModuleDependencies() throws -> [ResolvedModule] {\n        let recursiveDependencies = try modules.lazy.flatMap { try $0.recursiveModuleDependencies() }\n        return Array(IdentifiableSet(self.modules).union(recursiveDependencies))\n    }\n\n    private static func computePlatforms(\n        modules: IdentifiableSet<ResolvedModule>\n    ) -> ([SupportedPlatform], PlatformVersionProvider) {\n        let declaredPlatforms = modules.reduce(into: [SupportedPlatform]()) { partial, item in\n            merge(into: &partial, platforms: item.supportedPlatforms)\n        }\n\n        return (\n            declaredPlatforms.sorted(by: { $0.platform.name < $1.platform.name }),\n            PlatformVersionProvider(implementation: .mergingFromModules(modules))\n        )\n    }\n\n    public func getSupportedPlatform(for platform: Platform, usingXCTest: Bool) -> SupportedPlatform {\n        self.platformVersionProvider.getDerived(\n            declared: self.supportedPlatforms,\n            for: platform,\n            usingXCTest: usingXCTest\n        )\n    }\n\n    func diagnoseInvalidUseOfUnsafeFlags(_ diagnosticsEmitter: DiagnosticsEmitter) throws {\n        // Diagnose if any module in this product uses an unsafe flag.\n        for module in try self.recursiveModuleDependencies() {\n            if module.underlying.usesUnsafeFlags {\n                diagnosticsEmitter.emit(.productUsesUnsafeFlags(product: self.name, target: module.name))\n            }\n        }\n    }\n}\n\nextension ResolvedProduct: CustomStringConvertible {\n    public var description: String {\n        \"<ResolvedProduct: \\(self.packageIdentity), \\(self.name), \\(self.type)>\"\n    }\n}\n\nextension ResolvedProduct {\n    public var isLinkingXCTest: Bool {\n        // To retain existing behavior, we have to check both the product type, as well as the types of all of its\n        // modules.\n        self.type == .test || self.modules.contains(where: { $0.type == .test })\n    }\n}\n\nextension ResolvedProduct: Identifiable {\n    /// Resolved module identity that uniquely identifies it in a resolution graph.\n    public struct ID: Hashable {\n        public let productName: String\n        let packageIdentity: PackageIdentity\n    }\n\n    public var id: ID {\n        ID(productName: self.name, packageIdentity: self.packageIdentity)\n    }\n}\n\n@available(*, unavailable, message: \"Use `Identifiable` conformance or `IdentifiableSet` instead\")\nextension ResolvedProduct: Hashable {}\n"
  },
  {
    "path": "Sources/PackageGraph/ResolvedPackagesStore.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\n\nimport enum TSCBasic.JSON\n\nimport struct TSCUtility.Version\n\n@available(*, deprecated, renamed: \"PackageResolvedStore\", message: \"Renamed for consistency with the actual name of the feature\")\npublic typealias PinsStore = ResolvedPackagesStore\n\n\n/// An in-memory representation of `Package.resolved` file.\npublic final class ResolvedPackagesStore {\n    @available(*, deprecated, renamed: \"ResolvedPackages\", message: \"Renamed for consistency with the actual name of the feature\")\n    public typealias Pins = ResolvedPackages\n\n    public typealias ResolvedPackages = [PackageIdentity: ResolvedPackagesStore.ResolvedPackage]\n\n    @available(*, deprecated, renamed: \"ResolvedPackage\", message: \"Renamed for consistency with the actual name of the feature\")\n    public typealias Pin = ResolvedPackage\n\n    public struct ResolvedPackage: Equatable {\n        /// The package reference of the resolved dependency.\n        public let packageRef: PackageReference\n\n        /// The resolved state.\n        public let state: ResolutionState\n\n        public init(packageRef: PackageReference, state: ResolutionState) {\n            self.packageRef = packageRef\n            self.state = state\n        }\n    }\n\n    @available(*, deprecated, renamed: \"PackageResolvedStore\", message: \"Renamed for consistency with the actual name of the feature\")\n    public typealias PinState = ResolutionState\n\n    public enum ResolutionState: Equatable, CustomStringConvertible {\n        case branch(name: String, revision: String)\n        case version(_ version: Version, revision: String?)\n        case revision(_ revision: String)\n\n        public var description: String {\n            switch self {\n            case .version(let version, _):\n                return version.description\n            case .branch(let name, _):\n                return name\n            case .revision(let revision):\n                return revision\n            }\n        }\n    }\n\n    private let mirrors: DependencyMirrors\n\n    /// storage\n    private let storage: ResolvedPackagesStorage\n    private let _resolvedPackages: ThreadSafeKeyValueStore<PackageIdentity, ResolvedPackagesStore.ResolvedPackage>\n    public let originHash: String?\n\n    /// The current resolved packages.\n    @available(*, deprecated, renamed: \"resolvedPackages\", message: \"Renamed for consistency with the actual name of the feature\")\n    public var pins: ResolvedPackages {\n        self.resolvedPackages\n    }\n\n    /// The current pins.\n    public var resolvedPackages: ResolvedPackages {\n        self._resolvedPackages.get()\n    }\n\n    @available(*, deprecated, renamed: \"init(packageResolvedFile:workingDirectory:fileSystem:mirrors:)\", message: \"Renamed for consistency with the actual name of the feature\")\n    public convenience init(\n        pinsFile: AbsolutePath,\n        workingDirectory: AbsolutePath,\n        fileSystem: FileSystem,\n        mirrors: DependencyMirrors\n    ) throws {\n        try self.init(\n            packageResolvedFile: pinsFile,\n            workingDirectory: workingDirectory,\n            fileSystem: fileSystem,\n            mirrors: mirrors\n        )\n    }\n\n    /// Create a new `Package.resolved` store.\n    ///\n    /// - Parameters:\n    ///   - packageResolvedFile: Path to the `Package.resolved` file.\n    ///   - fileSystem: The filesystem to manage the `Package.resolved` file on.\n    public init(\n        packageResolvedFile: AbsolutePath,\n        workingDirectory: AbsolutePath,\n        fileSystem: FileSystem,\n        mirrors: DependencyMirrors\n    ) throws {\n        self.storage = .init(path: packageResolvedFile, workingDirectory: workingDirectory, fileSystem: fileSystem)\n        self.mirrors = mirrors\n\n        do {\n            let (resolvedPackagesStorage, originHash) = try self.storage.load(mirrors: mirrors)\n            self._resolvedPackages = .init(resolvedPackagesStorage)\n            self.originHash = originHash\n        } catch {\n            self._resolvedPackages = .init()\n            throw StringError(\n                \"\\(packageResolvedFile) file is corrupted or malformed; fix or delete the file to continue: \\(error.interpolationDescription)\"\n            )\n        }\n    }\n\n    /// Track a resolved package with a given state.\n    ///\n    /// This method does not automatically write to state file.\n    ///\n    /// - Parameters:\n    ///   - packageRef: The package reference to track.\n    ///   - state: The state to track with.\n    public func track(packageRef: PackageReference, state: ResolutionState) {\n        self.add(.init(\n            packageRef: packageRef,\n            state: state\n        ))\n    }\n\n    /// Add a resolved package.\n    ///\n    /// This will replace any previous resolutions with same package name.\n    public func add(_ resolvedPackage: ResolvedPackage) {\n        self._resolvedPackages[resolvedPackage.packageRef.identity] = resolvedPackage\n    }\n\n    /// Remove a pin.\n    ///\n    /// This will replace any previous pin with same package name.\n    public func remove(_ resolvedPackage: ResolvedPackage) {\n        self._resolvedPackages[resolvedPackage.packageRef.identity] = nil\n    }\n\n    /// Stop tracking all of the currently tracked resolved packages.\n    ///\n    /// This method does not automatically write to state file.\n    public func reset() {\n        // Reset the resolved packages map.\n        self._resolvedPackages.clear()\n    }\n\n    public func saveState(\n        toolsVersion: ToolsVersion,\n        originHash: String?\n    ) throws {\n        try self.storage.save(\n            toolsVersion: toolsVersion,\n            resolvedPackages: self._resolvedPackages.get(),\n            mirrors: self.mirrors,\n            originHash: originHash,\n            removeIfEmpty: true\n        )\n    }\n\n    // for testing\n    public func schemeVersion() throws -> Int {\n        try self.storage.schemeVersion()\n    }\n}\n\n// MARK: - Serialization\n\nprivate struct ResolvedPackagesStorage {\n    private let path: AbsolutePath\n    private let lockFilePath: AbsolutePath\n    private let fileSystem: FileSystem\n    private let encoder = JSONEncoder.makeWithDefaults()\n    private let decoder = JSONDecoder.makeWithDefaults()\n\n    init(path: AbsolutePath, workingDirectory: AbsolutePath, fileSystem: FileSystem) {\n        self.path = path\n        self.lockFilePath = workingDirectory.appending(component: path.basename)\n        self.fileSystem = fileSystem\n    }\n\n    func load(mirrors: DependencyMirrors) throws -> (resolvedPackages: ResolvedPackagesStore.ResolvedPackages, originHash: String?) {\n        if !self.fileSystem.exists(self.path) {\n            return (resolvedPackages: [:], originHash: .none)\n        }\n\n        return try self.fileSystem.withLock(on: self.lockFilePath, type: .shared) {\n            let version = try self.decoder.decode(path: self.path, fileSystem: self.fileSystem, as: Version.self)\n            switch version.version {\n            case V1.version:\n                let v1 = try decoder.decode(path: self.path, fileSystem: self.fileSystem, as: V1.self)\n                return (\n                    resolvedPackages: try v1.object.pins\n                        .map { try ResolvedPackagesStore.ResolvedPackage($0, mirrors: mirrors) }\n                        .reduce(into: [PackageIdentity: ResolvedPackagesStore.ResolvedPackage]()) { partial, iterator in\n                            if partial.keys.contains(iterator.packageRef.identity) {\n                                throw StringError(\"duplicated entry for package \\\"\\(iterator.packageRef.identity)\\\"\")\n                            }\n                            partial[iterator.packageRef.identity] = iterator\n                        },\n                    originHash: .none\n                )\n            case V2.version:\n                let v2 = try decoder.decode(path: self.path, fileSystem: self.fileSystem, as: V2.self)\n                return (\n                    resolvedPackages: try v2.pins\n                        .map { try ResolvedPackagesStore.ResolvedPackage($0, mirrors: mirrors) }\n                        .reduce(into: [PackageIdentity: ResolvedPackagesStore.ResolvedPackage]()) { partial, iterator in\n                            if partial.keys.contains(iterator.packageRef.identity) {\n                                throw StringError(\"duplicated entry for package \\\"\\(iterator.packageRef.identity)\\\"\")\n                            }\n                            partial[iterator.packageRef.identity] = iterator\n                        },\n                    originHash: .none\n                )\n            case V3.version:\n                let v3 = try decoder.decode(path: self.path, fileSystem: self.fileSystem, as: V3.self)\n                return (\n                    resolvedPackages: try v3.pins\n                        .map { try ResolvedPackagesStore.ResolvedPackage($0, mirrors: mirrors) }\n                        .reduce(into: [PackageIdentity: ResolvedPackagesStore.ResolvedPackage]()) { partial, iterator in\n                            if partial.keys.contains(iterator.packageRef.identity) {\n                                throw StringError(\"duplicated entry for package \\\"\\(iterator.packageRef.identity)\\\"\")\n                            }\n                            partial[iterator.packageRef.identity] = iterator\n                        },\n                    originHash: v3.originHash\n                )\n            default:\n                throw StringError(\"unknown 'Package.resolved' version '\\(version.version)' at '\\(self.path)'.\")\n            }\n        }\n    }\n\n    func save(\n        toolsVersion: ToolsVersion,\n        resolvedPackages: ResolvedPackagesStore.ResolvedPackages,\n        mirrors: DependencyMirrors,\n        originHash: String?,\n        removeIfEmpty: Bool\n    ) throws {\n        if !self.fileSystem.exists(self.path.parentDirectory) {\n            try self.fileSystem.createDirectory(self.path.parentDirectory)\n        }\n        try self.fileSystem.withLock(on: self.lockFilePath, type: .exclusive) {\n            // Remove the pins file if there are zero pins to save.\n            //\n            // This can happen if all dependencies are path-based or edited\n            // dependencies.\n            if removeIfEmpty && resolvedPackages.isEmpty {\n                try self.fileSystem.removeFileTree(self.path)\n                return\n            }\n\n            var data: Data\n            if toolsVersion > .v5_9  {\n                let container = try V3(\n                    pins: resolvedPackages,\n                    mirrors: mirrors,\n                    originHash: originHash\n                )\n                data = try self.encoder.encode(container)\n            } else if toolsVersion >= .v5_6 {\n                let container = try V2(\n                    pins: resolvedPackages,\n                    mirrors: mirrors\n                )\n                data = try self.encoder.encode(container)\n            } else {\n                let container = try V1(pins: resolvedPackages, mirrors: mirrors)\n                let json = container.toLegacyJSON()\n                let bytes = json.toBytes(prettyPrint: true)\n                data = Data(bytes.contents)\n            }\n            #if !os(Windows)\n            // rdar://83646952: add newline for POSIXy systems\n            if data.last != 0x0A {\n                data.append(0x0A)\n            }\n            #endif\n            try self.fileSystem.writeFileContents(self.path, data: data)\n        }\n    }\n\n    func reset() throws {\n        if !self.fileSystem.exists(self.path.parentDirectory) {\n            return\n        }\n        try self.fileSystem.withLock(on: self.lockFilePath, type: .exclusive) {\n            try self.fileSystem.removeFileTree(self.path)\n        }\n    }\n\n    // for testing\n    func schemeVersion() throws -> Int {\n        try self.decoder.decode(path: self.path, fileSystem: self.fileSystem, as: Version.self).version\n    }\n\n    // version reader\n    struct Version: Codable {\n        let version: Int\n    }\n\n    // v1 storage format\n    struct V1: Codable {\n        static let version = 1\n\n        let version: Int\n        let object: Container\n\n        init(pins: ResolvedPackagesStore.ResolvedPackages, mirrors: DependencyMirrors) throws {\n            self.version = Self.version\n            self.object = try .init(\n                pins: pins.values\n                    .sorted(by: { $0.packageRef.identity < $1.packageRef.identity })\n                    .map { try Pin($0, mirrors: mirrors) }\n            )\n        }\n\n        // backwards compatibility of JSON format\n        func toLegacyJSON() -> JSON {\n            .init([\n                \"version\": self.version.toJSON(),\n                \"object\": self.object.toLegacyJSON(),\n            ])\n        }\n\n        struct Container: Codable {\n            var pins: [Pin]\n\n            // backwards compatibility of JSON format\n            func toLegacyJSON() -> JSON {\n                .init([\n                    \"pins\": self.pins.map { $0.toLegacyJSON() },\n                ])\n            }\n        }\n\n        struct Pin: Codable {\n            let package: String?\n            let repositoryURL: String\n            let state: State\n\n            init(_ pin: ResolvedPackagesStore.ResolvedPackage, mirrors: DependencyMirrors) throws {\n                let location: String\n                switch pin.packageRef.kind {\n                case .localSourceControl(let path):\n                    location = path.pathString\n                case .remoteSourceControl(let url):\n                    location = url.absoluteString\n                default:\n                    throw StringError(\"invalid package type \\(pin.packageRef.kind)\")\n                }\n\n                self.package = pin.packageRef.deprecatedName\n                // rdar://52529014, rdar://52529011: pin file should store the original location but remap when loading\n                self.repositoryURL = mirrors.original(for: location) ?? location\n                self.state = try .init(pin.state)\n            }\n\n            // backwards compatibility of JSON format\n            func toLegacyJSON() -> JSON {\n                .init([\n                    \"package\": self.package.toJSON(),\n                    \"repositoryURL\": self.repositoryURL.toJSON(),\n                    \"state\": self.state.toLegacyJSON(),\n                ])\n            }\n        }\n\n        struct State: Codable {\n            let revision: String\n            let branch: String?\n            let version: String?\n\n            init(_ state: ResolvedPackagesStore.ResolutionState) throws {\n                switch state {\n                case .version(let version, let revision) where revision != nil:\n                    self.version = version.description\n                    self.branch = nil\n                    self.revision = revision! // nil guarded above in case\n                case .branch(let branch, let revision):\n                    self.version = nil\n                    self.branch = branch\n                    self.revision = revision\n                case .revision(let revision):\n                    self.version = nil\n                    self.branch = nil\n                    self.revision = revision\n                default:\n                    throw StringError(\"invalid pin state: \\(state)\")\n                }\n            }\n\n            // backwards compatibility of JSON format\n            func toLegacyJSON() -> JSON {\n                .init([\n                    \"revision\": self.revision.toJSON(),\n                    \"version\": self.version.toJSON(),\n                    \"branch\": self.branch.toJSON(),\n                ])\n            }\n        }\n    }\n\n    // v2 storage format\n    struct V2: Codable {\n        static let version = 2\n\n        let version: Int\n        let pins: [Pin]\n\n        init(\n            pins: ResolvedPackagesStore.ResolvedPackages,\n            mirrors: DependencyMirrors\n        ) throws {\n            self.version = Self.version\n            self.pins = try pins.values\n                .sorted(by: { $0.packageRef.identity < $1.packageRef.identity })\n                .map { try Pin($0, mirrors: mirrors) }\n        }\n\n        struct Pin: Codable {\n            let identity: PackageIdentity\n            let kind: Kind\n            let location: String\n            let state: State\n\n            init(_ pin: ResolvedPackagesStore.ResolvedPackage, mirrors: DependencyMirrors) throws {\n                let kind: Kind\n                let location: String\n                switch pin.packageRef.kind {\n                case .localSourceControl(let path):\n                    kind = .localSourceControl\n                    location = path.pathString\n                case .remoteSourceControl(let url):\n                    kind = .remoteSourceControl\n                    location = url.absoluteString\n                case .registry:\n                    kind = .registry\n                    location = \"\" // FIXME: this is likely not correct\n                default:\n                    throw StringError(\"invalid package type \\(pin.packageRef.kind)\")\n                }\n\n                self.identity = pin.packageRef.identity\n                self.kind = kind\n                // rdar://52529014, rdar://52529011: pin file should store the original location but remap when loading\n                self.location = mirrors.original(for: location) ?? location\n                self.state = .init(pin.state)\n            }\n        }\n\n        enum Kind: String, Codable {\n            case localSourceControl\n            case remoteSourceControl\n            case registry\n        }\n\n        struct State: Codable {\n            let version: String?\n            let branch: String?\n            let revision: String?\n\n            init(_ state: ResolvedPackagesStore.ResolutionState) {\n                switch state {\n                case .version(let version, let revision):\n                    self.version = version.description\n                    self.branch = nil\n                    self.revision = revision\n                case .branch(let branch, let revision):\n                    self.version = nil\n                    self.branch = branch\n                    self.revision = revision\n                case .revision(let revision):\n                    self.version = nil\n                    self.branch = nil\n                    self.revision = revision\n                }\n            }\n        }\n    }\n\n    // v3 storage format\n    struct V3: Codable {\n        static let version = 3\n\n        let version: Int\n        let originHash: String?\n        let pins: [V2.Pin]\n\n        init(\n            pins: ResolvedPackagesStore.ResolvedPackages,\n            mirrors: DependencyMirrors,\n            originHash: String?\n        ) throws {\n            self.version = Self.version\n            self.pins = try pins.values\n                .sorted(by: { $0.packageRef.identity < $1.packageRef.identity })\n                .map { try V2.Pin($0, mirrors: mirrors) }\n            self.originHash = originHash\n        }\n    }\n}\n\nextension ResolvedPackagesStore.ResolvedPackage {\n    fileprivate init(_ pin: ResolvedPackagesStorage.V1.Pin, mirrors: DependencyMirrors) throws {\n        // rdar://52529014, rdar://52529011: pin file should store the original location but remap when loading\n        let location = mirrors.effective(for: pin.repositoryURL)\n        let identity = PackageIdentity(urlString: location) // FIXME: pin store should also encode identity\n        var packageRef: PackageReference\n        if let path = try? AbsolutePath(validating: location) {\n            packageRef = .localSourceControl(identity: identity, path: path)\n        } else {\n            packageRef = .remoteSourceControl(identity: identity, url: SourceControlURL(location))\n        }\n        if let newName = pin.package {\n            packageRef = packageRef.withName(newName)\n        }\n        self.init(\n            packageRef: packageRef,\n            state: try .init(pin.state)\n        )\n    }\n}\n\nextension ResolvedPackagesStore.ResolutionState {\n    fileprivate init(_ state: ResolvedPackagesStorage.V1.State) throws {\n        let revision = state.revision\n        if let version = state.version {\n            self = try .version(Version(versionString: version), revision: revision)\n        } else if let branch = state.branch {\n            self = .branch(name: branch, revision: revision)\n        } else {\n            self = .revision(revision)\n        }\n    }\n}\n\nextension ResolvedPackagesStore.ResolvedPackage {\n    fileprivate init(_ pin: ResolvedPackagesStorage.V2.Pin, mirrors: DependencyMirrors) throws {\n        let packageRef: PackageReference\n        let identity = pin.identity\n        // rdar://52529014, rdar://52529011: pin file should store the original location but remap when loading\n        let location = mirrors.effective(for: pin.location)\n        switch pin.kind {\n        case .localSourceControl:\n            packageRef = try .localSourceControl(identity: identity, path: AbsolutePath(validating: location))\n        case .remoteSourceControl:\n            packageRef = .remoteSourceControl(identity: identity, url: SourceControlURL(location))\n        case .registry:\n            packageRef = .registry(identity: identity)\n        }\n        self.init(\n            packageRef: packageRef,\n            state: try .init(pin.state)\n        )\n    }\n}\n\nextension ResolvedPackagesStore.ResolutionState {\n    fileprivate init(_ state: ResolvedPackagesStorage.V2.State) throws {\n        if let version = state.version {\n            self = try .version(Version(versionString: version), revision: state.revision)\n        } else if let branch = state.branch, let revision = state.revision {\n            self = .branch(name: branch, revision: revision)\n        } else if let revision = state.revision {\n            self = .revision(revision)\n        } else {\n            throw StringError(\"invalid pin state: \\(state)\")\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/Version+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCUtility.Version\n\nextension Version {\n    func nextPatch() -> Version {\n        if self.prereleaseIdentifiers.isEmpty {\n            return Version(self.major, self.minor, self.patch + 1)\n        } else {\n            return Version(self.major, self.minor, self.patch, prereleaseIdentifiers: self.prereleaseIdentifiers + [\"0\"])\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageGraph/VersionSetSpecifier.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCUtility.Version\n\n/// An abstract definition for a set of versions.\npublic enum VersionSetSpecifier: Hashable {\n    /// The universal set.\n    case any\n\n    /// The empty set.\n    case empty\n\n    /// A non-empty range of version.\n    case range(Range<Version>)\n\n    /// The exact version that is required.\n    case exact(Version)\n\n    /// A range of disjoint versions (sorted).\n    case ranges([Range<Version>])\n}\n\nextension VersionSetSpecifier: Equatable {\n    public static func ==(lhs: VersionSetSpecifier, rhs: VersionSetSpecifier) -> Bool {\n        switch (lhs, rhs) {\n        // Basic cases.\n        case (.any, .any):\n            return true\n        case (.empty, .empty):\n            return true\n        case (let .range(lhsRange), let .range(rhsRange)):\n            return lhsRange == rhsRange\n        case (let .exact(lhsExact), let .exact(rhsExact)):\n            return lhsExact == rhsExact\n        case (let .ranges(lhsRanges), let .ranges(rhsRanges)):\n            return lhsRanges == rhsRanges\n\n        // Empty is equivalent to an empty list of ranges or if the list contains one range where the lower bound equals the upper bound.\n        case (.empty, let .ranges(ranges)):\n            fallthrough\n        case (let .ranges(ranges), .empty):\n            return ranges.isEmpty || (ranges.count == 1 && ranges[0].lowerBound == ranges[0].upperBound)\n\n        // Empty is equivalent to a range where the lower bound equals the upper bound.\n        case (.empty, let .range(range)):\n            fallthrough\n        case (let .range(range), .empty):\n            return range.upperBound == range.lowerBound\n\n        // Exact is equal to a range that spans a single patch.\n        case (let .exact(exact), let .range(range)):\n            fallthrough\n        case (let .range(range), let .exact(exact)):\n            return range.lowerBound == exact && range.upperBound == exact.nextPatch()\n\n        // Exact is also equal to a list of ranges with one entry that spans a single patch.\n        case (let .exact(exact), let .ranges(ranges)):\n            fallthrough\n        case (let .ranges(ranges), let .exact(exact)):\n            return ranges.count == 1 && ranges[0].lowerBound == exact && ranges[0].upperBound == exact.nextPatch()\n\n        // A range is equal to a list of ranges with that one range.\n        case (let .range(range), let .ranges(ranges)):\n            fallthrough\n        case (let .ranges(ranges), let .range(range)):\n            return ranges.count == 1 && ranges[0] == range\n\n        default:\n            return false\n        }\n    }\n}\n\nextension VersionSetSpecifier {\n    var isExact: Bool {\n        switch self {\n        case .any, .empty, .range, .ranges:\n            return false\n        case .exact:\n            return true\n        }\n    }\n}\n\nextension VersionSetSpecifier {\n    public static func union(from range: Swift.Range<Version>) -> VersionSetSpecifier {\n        return .union(from: [range])\n    }\n\n    public static func union(from ranges: [Swift.Range<Version>]) -> VersionSetSpecifier {\n        switch ranges.count {\n        case 0:\n            return .empty\n        case 1:\n            let range = ranges[0]\n            // FIXME: Can we avoid this? testConflict1 goes into a loop if we don't do this.\n            if range.lowerBound.nextPatch() == range.upperBound {\n                return .exact(range.lowerBound)\n            }\n            return .range(range)\n        default:\n            let ranges = ranges.sorted(by: { $0.lowerBound < $1.lowerBound })\n\n            var result: [Range<Version>] = []\n            for range in ranges {\n                // We can merge if next range starts immediately after this one or if they overlap.\n                if let last = result.last, last.upperBound == range.lowerBound || range.overlaps(last) || last.lowerBound.nextPatch() == range.lowerBound {\n                    let newResult: Range<Version>\n\n                    if range.lowerBound == range.upperBound {\n                        // 1.0.0..<1.0.1 U 1.0.1..<1.0.1 is 1.0.0..<1.0.2\n                        let version = range.lowerBound\n                        if last.upperBound == version {\n                            newResult = last.lowerBound ..< version.nextPatch()\n                        } else {\n                            continue\n                        }\n                    } else {\n                        let lower = min(last.lowerBound, range.lowerBound)\n                        let upper = max(last.upperBound, range.upperBound)\n                        newResult = lower ..< upper\n                    }\n\n                    result[result.count - 1] = newResult\n                } else {\n                    result.append(range)\n                }\n            }\n\n            if result.count == 1 {\n                return .range(result[0])\n            }\n            return .ranges(result)\n        }\n    }\n\n    public func union(_ rhs: VersionSetSpecifier) -> VersionSetSpecifier {\n        switch (self, rhs) {\n        case (_, .any), (.any, _):\n            return .any\n        case (.empty, _):\n            return rhs\n        case (_, .empty):\n            return self\n        case (.exact(let v1), .exact(let v2)):\n            if v1 == v2 {\n                return self\n            }\n            return VersionSetSpecifier.union(from: [v1..<v1, v2..<v2])\n\n        case (.range(let v2), .exact(let v1)),\n             (.exact(let v1), .range(let v2)):\n            return VersionSetSpecifier.union(from: [v1..<v1, v2])\n\n        case (.ranges(let ranges), .exact(let exact)), (.exact(let exact), .ranges(let ranges)):\n            return VersionSetSpecifier.union(from: [exact..<exact] + ranges)\n\n        case (.range(let lhs), .range(let rhs)):\n            return VersionSetSpecifier.union(from: [lhs, rhs])\n\n        case (.ranges(let ranges), .range(let range)), (.range(let range), .ranges(let ranges)):\n            return VersionSetSpecifier.union(from: [range] + ranges)\n\n        case (.ranges(let r1), .ranges(let r2)):\n            return VersionSetSpecifier.union(from: r1 + r2)\n        }\n    }\n}\n\nextension VersionSetSpecifier {\n    /// Compute the intersection of two set specifiers.\n    public func intersection(_ rhs: VersionSetSpecifier) -> VersionSetSpecifier {\n        switch (self, rhs) {\n        case (.any, _):\n            return rhs\n        case (_, .any):\n            return self\n        case (.empty, _):\n            return .empty\n        case (_, .empty):\n            return .empty\n        case (.range(let lhs), .range(let rhs)):\n            if let result = VersionSetSpecifier.intersection(lhs, rhs) {\n                return .range(result)\n            }\n            return .empty\n        case (.exact(let v), _):\n            if rhs.contains(v) {\n                return self\n            }\n            return .empty\n        case (_, .exact(let v)):\n            if contains(v) {\n                return rhs\n            }\n            return .empty\n\n        case (.ranges(let ranges), .range(let range)), (.range(let range), .ranges(let ranges)):\n            return .intersection(ranges, [range])\n        case (.ranges(let lhs), .ranges(let rhs)):\n             return .intersection(lhs, rhs)\n        }\n    }\n\n    fileprivate static func intersection(_ lhs: Range<Version>, _ rhs: Range<Version>) -> Range<Version>? {\n        let start = Swift.max(lhs.lowerBound, rhs.lowerBound)\n        let end = Swift.min(lhs.upperBound, rhs.upperBound)\n        if start < end {\n            return start..<end\n        }\n        return nil\n    }\n\n    fileprivate static func intersection(_ lhs: [Range<Version>], _ rhs: [Range<Version>]) -> VersionSetSpecifier {\n        var lhsItr = lhs.makeIterator()\n        var rhsItr = rhs.makeIterator()\n\n        var currentLhs = lhsItr.next()\n        var currentRhs = rhsItr.next()\n\n        var result: [Range<Version>] = []\n\n        while let lhs = currentLhs, let rhs = currentRhs {\n            if let current = VersionSetSpecifier.intersection(lhs, rhs) {\n                result.append(current)\n            }\n\n            // Move the one with lower upper bound so large ranges have a chance to match multiple\n            // small ranges they contain.\n            if lhs.upperBound < rhs.upperBound {\n                currentLhs = lhsItr.next()\n            } else {\n                currentRhs = rhsItr.next()\n            }\n        }\n\n        return .union(from: result)\n    }\n}\n\nextension VersionSetSpecifier {\n    public func difference(_ rhs: VersionSetSpecifier) -> VersionSetSpecifier {\n        switch (self, rhs) {\n        case (_, .any):\n            return .empty\n        case (.any, _):\n            fatalError(\"\\(#file):\\(#line) - Illegal call of \\(#function) on left hand side value of `.any`\")\n        case (.empty, _):\n            return .empty\n        case (_, .empty):\n            return self\n        case (.exact(let v1), .exact(let v2)):\n            if v1 == v2 {\n                return .empty\n            }\n            return self\n\n        case (.exact(let lhs), .range(let rhs)):\n            if rhs.contains(version: lhs) {\n                return .empty\n            }\n            return .exact(lhs)\n        case (.range(let lhs), .exact(let rhs)):\n            if !lhs.contains(version: rhs) {\n                return .range(lhs)\n            }\n\n            if lhs.lowerBound == rhs {\n                // Return empty if the range is empty. This means upper and lower bounds are equal since the range is half-open and there are no negative results here.\n                if lhs.lowerBound == lhs.upperBound {\n                    return .empty\n                }\n                // If there is exactly one patch between lower and upper bound, the range represent the lower bound as an exact version. So the range is empty in this case as well.\n                if lhs.lowerBound.nextPatch() == lhs.upperBound {\n                    return .empty\n                }\n                return .range(rhs.nextPatch()..<lhs.upperBound)\n            }\n\n            return .union(from: [lhs.lowerBound..<rhs, rhs.nextPatch()..<lhs.upperBound])\n\n        case (.ranges(let ranges), .exact(let exact)):\n            var result = [Range<Version>]()\n\n            for range in ranges {\n                // FIXME: is this worth merging with the logic in (range, exact) case above?\n                if !range.contains(version: exact) {\n                    result.append(range)\n                } else if range.lowerBound == exact {\n                    if range.lowerBound == range.upperBound {\n                        continue\n                    }\n\n                    if exact.nextPatch() < range.upperBound {\n                        result.append(exact.nextPatch()..<range.upperBound)\n                    }\n                } else {\n                    result += [range.lowerBound..<exact]\n                    if exact.nextPatch() < range.upperBound {\n                        result += [exact.nextPatch()..<range.upperBound]\n                    }\n                }\n            }\n            return .union(from: result)\n\n        case (.exact(let exact), .ranges(let ranges)):\n            for range in ranges {\n                if range.contains(version: exact) {\n                    return .empty\n                }\n            }\n            return self\n\n        case (.range(let lhs), .range(let rhs)):\n            if lhs == rhs { return .empty }\n            if !lhs.overlaps(rhs) { return .range(lhs) }\n\n            var result = [Range<Version>]()\n            if lhs.lowerBound < rhs.lowerBound {\n                result.append(lhs.lowerBound..<rhs.lowerBound)\n            }\n\n            if rhs.upperBound < lhs.upperBound {\n                result.append(rhs.upperBound..<lhs.upperBound)\n            }\n            return .union(from: result)\n\n        case (.range(let inputRange), .ranges(let ranges)):\n            var result = [Range<Version>]()\n            var lhs = inputRange\n            for range in ranges {\n                // Skip the ranges that don't overlap with the current lhs range.\n                // FIXME: We can exit the loop early when the range goes above lhs.\n                if !range.overlaps(lhs) { continue }\n\n                let diff = VersionSetSpecifier.range(lhs).difference(.range(range))\n                switch diff {\n                case .empty:\n                    return .empty\n                case .any:\n                    fatalError(\"unexpected any result\")\n                case .exact(let v):\n                    lhs = v..<v.nextPatch()\n                case .range(let r):\n                    lhs = r\n                case .ranges(let rs):\n                    // If the difference end up being a disjoint set, append the first one to\n                    // our result and continue reducing the second set.\n                    precondition(rs.count == 2, \"expected 2 elements in ranges \\(rs)\")\n                    result.append(rs[0])\n                    lhs = rs[1]\n                }\n            }\n            return .union(from: result + [lhs])\n\n        case (.ranges(_), .range(let r)):\n            return self.difference(.ranges([r]))\n\n        case (.ranges(let lhs), .ranges(let rhs)):\n            // Based on the difference method in https://github.com/dart-lang/pub_semver/blob/master/lib/src/version_union.dart     //ignore-unacceptable-language\n            var lhsItr = lhs.makeIterator()\n            var rhsItr = rhs.makeIterator()\n\n            var currentLHS = lhsItr.next()!\n            var currentRHS = rhsItr.next()!\n\n            var result: [Range<Version>] = []\n\n            func moveRHS() -> Bool {\n                if let value = rhsItr.next() {\n                    currentRHS = value\n                    return true\n                }\n\n                // RHS is done so add remaining on LHS ranges to the final result.\n                result.append(currentLHS)\n                while let value = lhsItr.next() {\n                    result.append(value)\n                }\n                return false\n            }\n\n            func moveLHS(addCurrentLHS: Bool = true) -> Bool {\n                if addCurrentLHS {\n                    result.append(currentLHS)\n                }\n\n                if let value = lhsItr.next() {\n                    currentLHS = value\n                    return true\n                }\n                return false\n            }\n\n            outer: while true {\n                if currentRHS.isLowerThan(currentLHS) {\n                    if !moveRHS() { break outer }\n                    continue\n                }\n\n                if currentRHS.isHigherThan(currentLHS) {\n                    if !moveLHS() { break outer }\n                    continue\n                }\n\n                var diff = VersionSetSpecifier.range(currentLHS).difference(.range(currentRHS))\n                // Transform exact to a range so it is handled in the range case below.\n                if case .exact(let v) = diff {\n                    diff = .range(v..<v.nextPatch())\n                }\n\n                switch diff {\n                case .empty:\n                    if !moveLHS(addCurrentLHS: false) { break outer }\n                case .any, .exact:\n                    fatalError(\"Unexpected result \\(diff)\")\n                case .range(let r):\n                    currentLHS = r\n                    // Move the one with lower upper bound so large ranges have a chance to match multiple\n                    // small ranges they contain.\n                    if currentLHS.upperBound < currentRHS.upperBound {\n                        if !moveRHS() { break outer }\n                    } else {\n                        if !moveLHS() { break outer }\n                    }\n                case .ranges(let rs):\n                    // If the difference end up being a disjoint set, append the first one to\n                    // our result and continue reducing the second set.\n                    precondition(rs.count == 2, \"expected 2 elements in ranges \\(rs)\")\n                    result.append(rs[0])\n                    currentLHS = rs[1]\n                    if !moveRHS() { break outer }\n                }\n            }\n\n            return .union(from: result)\n        }\n    }\n}\n\nextension VersionSetSpecifier {\n    /// Check if the set contains a version.\n    public func contains(_ version: Version) -> Bool {\n        switch self {\n        case .empty:\n            return false\n        case .range(let range):\n            return range.contains(version: version)\n        case .ranges(let ranges):\n            return ranges.contains(where: { $0.contains(version: version) })\n        case .any:\n            return true\n        case .exact(let v):\n            return v == version\n        }\n    }\n}\n\nextension VersionSetSpecifier {\n    package var supportsPrereleases: Bool {\n        switch self {\n        case .empty, .any:\n            false\n        case .exact(let version):\n            version.supportsPrerelease\n        case .range(let range):\n            range.supportsPrereleases\n        case .ranges(let ranges):\n            ranges.contains(where: \\.supportsPrereleases)\n        }\n    }\n\n    package var withoutPrereleases: VersionSetSpecifier {\n        if !supportsPrereleases {\n            return self\n        }\n\n        return switch self {\n        case .empty, .any:\n            self\n        case .range(let range):\n            .range(range.withoutPrerelease)\n        case .ranges(let ranges):\n            .ranges(ranges.map { $0.withoutPrerelease })\n        case .exact(let version):\n            .exact(version.withoutPrerelease)\n        }\n    }\n}\n\nextension VersionSetSpecifier: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .any:\n            return \"any\"\n        case .empty:\n            return \"empty\"\n        case .ranges(let ranges):\n            return \"{\" + ranges.map{\n                if $0.lowerBound == $0.upperBound {\n                    return $0.lowerBound.description\n                }\n                return $0.lowerBound.description + \"..<\" + $0.upperBound.description\n            }.joined(separator: \", \") + \"}\"\n        case .range(let range):\n            var upperBound = range.upperBound\n            // Patch the version range representation. This shouldn't be\n            // required once we have custom version range structure.\n            if upperBound.minor == .max && upperBound.patch == .max {\n                upperBound = Version(upperBound.major + 1, 0, 0)\n            }\n            if upperBound.minor != .max && upperBound.patch == .max {\n                upperBound = Version(upperBound.major, upperBound.minor + 1, 0)\n            }\n            return range.lowerBound.description + \"..<\" + upperBound.description\n        case .exact(let version):\n            return version.description\n        }\n    }\n}\n\nfileprivate extension Range where Bound == Version {\n    func isLowerThan(_ other: Range<Bound>) -> Bool {\n        return self.lowerBound < other.lowerBound && self.upperBound < other.upperBound\n    }\n\n    func isHigherThan(_ other: Range<Bound>) -> Bool {\n        return other.isLowerThan(self)\n    }\n\n    var supportsPrereleases: Bool {\n        self.lowerBound.supportsPrerelease || self.upperBound.supportsPrerelease\n    }\n\n    var withoutPrerelease: Range<Version> {\n        if !supportsPrereleases {\n            return self\n        }\n\n        return Range(uncheckedBounds: (\n            lower: self.lowerBound.withoutPrerelease,\n            upper: self.upperBound.withoutPrerelease\n        ))\n    }\n}\n\nfileprivate extension Version {\n    var supportsPrerelease: Bool {\n        !self.prereleaseIdentifiers.isEmpty\n    }\n\n    var withoutPrerelease: Version {\n        Version(\n            self.major,\n            self.minor,\n            self.patch,\n            prereleaseIdentifiers: [],\n            buildMetadataIdentifiers: self.buildMetadataIdentifiers\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageLoading\n  ContextModel.swift\n  Diagnostics.swift\n  ManifestJSONParser.swift\n  ManifestLoader.swift\n  ManifestLoader+Validation.swift\n  ManifestSignatureParser.swift\n  ModuleMapGenerator.swift\n  PackageBuilder.swift\n  PackageDescriptionSerialization.swift\n  Platform.swift\n  PkgConfig.swift\n  RegistryReleaseMetadataSerialization.swift\n  Target+PkgConfig.swift\n  TargetSourcesBuilder.swift\n  ToolsVersionParser.swift)\ntarget_link_libraries(PackageLoading PUBLIC\n  TSCBasic\n  Basics\n  PackageModel\n  TSCUtility)\ntarget_link_libraries(PackageLoading PUBLIC\n  $<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>)\ntarget_link_libraries(PackageLoading PRIVATE\n  SourceControl)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageLoading PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS PackageLoading\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS PackageLoading)\n"
  },
  {
    "path": "Sources/PackageLoading/ContextModel.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import Foundation\n#else\nimport Foundation\n#endif\n\nstruct ContextModel {\n    let packageDirectory : String\n    let gitInformation: GitInformation?\n    \n    var environment : [String : String] {\n        ProcessInfo.processInfo.environment\n    }\n\n    struct GitInformation: Codable {\n        let currentTag: String?\n        let currentCommit: String\n        let hasUncommittedChanges: Bool\n    }\n}\n\nextension ContextModel : Codable {\n    func encode() throws -> String {\n        let encoder = JSONEncoder()\n        let data = try encoder.encode(self)\n        return String(decoding: data, as: UTF8.self)\n    }\n\n    static func decode() throws -> ContextModel {\n        var args = Array(ProcessInfo.processInfo.arguments[1...]).makeIterator()\n        while let arg = args.next() {\n            if arg == \"-context\", let json = args.next() {\n                let decoder = JSONDecoder()\n                let data = Data(json.utf8)\n                return try decoder.decode(ContextModel.self, from: data)\n            }\n        }\n        throw StringError(description: \"Could not decode ContextModel parameter.\")\n    }\n\n    struct StringError: Error, CustomStringConvertible {\n        let description: String\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/Diagnostics.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\n\nextension Basics.Diagnostic {\n    static func targetHasNoSources(name: String, type: TargetDescription.TargetKind, shouldSuggestRelaxedSourceDir: Bool) -> Self {\n        let folderName = PackageBuilder.suggestedPredefinedSourceDirectory(type: type)\n        var clauses = [\"Source files for target \\(name) should be located under '\\(folderName)/\\(name)'\"]\n        if shouldSuggestRelaxedSourceDir {\n            clauses.append(\"'\\(folderName)'\")\n        }\n        clauses.append(\"or a custom sources path can be set with the 'path' property in Package.swift\")\n        return .warning(clauses.joined(separator: \", \"))\n    }\n\n    static func targetNameHasIncorrectCase(target: String) -> Self {\n        .warning(\"the target name \\(target) has different case on the filesystem and the Package.swift manifest file\")\n    }\n\n    static func unsupportedCTestTarget(package: String, target: String) -> Self {\n        .warning(\"ignoring target '\\(target)' in package '\\(package)'; C language in tests is not yet supported\")\n    }\n\n    static func duplicateProduct(product: Product) -> Self {\n        let typeString: String\n        switch product.type {\n        case .library(.automatic):\n            typeString = \"\"\n        case .executable, .snippet, .plugin, .test, .macro,\n             .library(.dynamic), .library(.static):\n            typeString = \" (\\(product.type))\"\n        }\n\n        return .warning(\"ignoring duplicate product '\\(product.name)'\\(typeString)\")\n    }\n\n    static func duplicateProduct(name: String, package: String) -> Self {\n        return .warning(\"ignoring duplicate product '\\(name)' from package '\\(package)'\")\n    }\n\n    static func duplicateTargetDependency(dependency: String, target: String, package: String) -> Self {\n        .warning(\"invalid duplicate target dependency declaration '\\(dependency)' in target '\\(target)' from package '\\(package)'\")\n    }\n\n    static var systemPackageDeprecation: Self {\n        .warning(\"system packages are deprecated; use system library targets instead\")\n    }\n\n    static func systemPackageDeclaresTargets(targets: [String]) -> Self {\n        .warning(\"ignoring declared target(s) '\\(targets.joined(separator: \", \"))' in the system package\")\n    }\n\n    static func systemPackageProductValidation(product: String) -> Self {\n        .error(\"system library product \\(product) shouldn't have a type and contain only one target\")\n    }\n\n    static func libraryProductWithExecutableTarget(product: String, executableTargets: [String]) -> Self {\n        .error(\"library product '\\(product)' should not contain executable targets (it has \\(executableTargets.map{ \"'\\($0)'\" }.joined(separator: \", \")))\")\n    }\n\n    static func nonPluginProductWithPluginTargets(product: String, type: ProductType, pluginTargets: [String]) -> Self {\n        .error(\"\\(type.description) product '\\(product)' should not contain plugin targets (it has \\(pluginTargets.map{ \"'\\($0)'\" }.joined(separator: \", \")))\")\n    }\n\n    static func executableProductTargetNotExecutable(product: String, target: String) -> Self {\n        .error(\"\"\"\n            executable product '\\(product)' expects target '\\(target)' to be executable; an executable target requires \\\n            a 'main.swift' file\n            \"\"\")\n    }\n\n    static func executableProductWithoutExecutableTarget(product: String) -> Self {\n        .error(\"\"\"\n            executable product '\\(product)' should have one executable target; an executable target requires a \\\n            'main.swift' file\n            \"\"\")\n    }\n\n    static func executableProductWithMoreThanOneExecutableTarget(product: String) -> Self {\n        .error(\"executable product '\\(product)' should not have more than one executable target\")\n    }\n\n    static func pluginNotFound(name: String) -> Self {\n        .error(\"no plugin named '\\(name)' found\")\n    }\n\n    static func pluginProductWithNoTargets(product: String) -> Self {\n        .error(\"plugin product '\\(product)' should have at least one plugin target\")\n    }\n\n    static func pluginProductWithNonPluginTargets(product: String, otherTargets: [String]) -> Self {\n        .error(\"plugin product '\\(product)' should have only plugin targets (it has \\(otherTargets.map{ \"'\\($0)'\" }.joined(separator: \", \")))\")\n    }\n\n    static var noLibraryTargetsForREPL: Self {\n        .error(\"unable to synthesize a REPL product as there are no library targets in the package\")\n    }\n\n    static func brokenSymlink(_ path: AbsolutePath) -> Self {\n        .warning(\"ignoring broken symlink \\(path)\")\n    }\n\n    static func conflictingResource(path: RelativePath, targetName: String) -> Self {\n        .error(\"multiple resources named '\\(path)' in target '\\(targetName)'\")\n    }\n\n    static func fileReference(path: RelativePath) -> Self {\n        .info(\"found '\\(path)'\")\n    }\n\n    static func infoPlistResourceConflict(\n        path: RelativePath,\n        targetName: String\n    ) -> Self {\n        .error(\"\"\"\n            resource '\\(path)' in target '\\(targetName)' is forbidden; Info.plist is not supported as a top-level \\\n            resource file in the resources bundle\n            \"\"\")\n    }\n\n    static func copyConflictWithLocalizationDirectory(path: RelativePath, targetName: String) -> Self {\n        .error(\"resource '\\(path)' in target '\\(targetName)' conflicts with other localization directories\")\n    }\n\n    static func missingDefaultLocalization() -> Self {\n        .error(\"missing manifest property 'defaultLocalization'; it is required in the presence of localized resources\")\n    }\n\n    static func localizationAmbiguity(path: RelativePath, targetName: String) -> Self {\n        .error(\"\"\"\n            resource '\\(path)' in target '\\(targetName)' is in a localization directory and has an explicit \\\n            localization declaration in the package manifest; choose one or the other to avoid any ambiguity\n            \"\"\")\n    }\n\n    static func localizedAndUnlocalizedVariants(resource: String, targetName: String) -> Self {\n        .warning(\"\"\"\n            resource '\\(resource)' in target '\\(targetName)' has both localized and un-localized variants; the \\\n            localized variants will never be chosen\n            \"\"\")\n    }\n}\n\nextension ObservabilityMetadata {\n    public var manifestLoadingDiagnosticFile: AbsolutePath? {\n        get {\n            self[ManifestLoadingDiagnosticFileKey.self]\n        }\n        set {\n            self[ManifestLoadingDiagnosticFileKey.self] = newValue\n        }\n    }\n\n    enum ManifestLoadingDiagnosticFileKey: Key {\n        typealias Value = AbsolutePath\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/ManifestJSONParser.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport PackageModel\n\nimport struct Basics.AbsolutePath\nimport protocol Basics.FileSystem\nimport struct Basics.SourceControlURL\nimport struct Basics.InternalError\nimport struct Basics.RelativePath\n\nimport enum TSCBasic.PathValidationError\nimport struct TSCBasic.RegEx\nimport struct TSCBasic.StringError\n\nimport struct TSCUtility.Version\n\nenum ManifestJSONParser {\n    struct Input: Codable {\n        let package: Serialization.Package\n        let errors: [String]\n    }\n\n    struct VersionedInput: Codable {\n        let version: Int\n    }\n\n    struct Result {\n        var name: String\n        var defaultLocalization: String?\n        var platforms: [PlatformDescription] = []\n        var targets: [TargetDescription] = []\n        var pkgConfig: String?\n        var swiftLanguageVersions: [SwiftLanguageVersion]?\n        var dependencies: [PackageDependency] = []\n        var providers: [SystemPackageProviderDescription]?\n        var products: [ProductDescription] = []\n        var traits: Set<TraitDescription> = []\n        var cxxLanguageStandard: String?\n        var cLanguageStandard: String?\n    }\n\n    static func parse(\n        v4 jsonString: String,\n        toolsVersion: ToolsVersion,\n        packageKind: PackageReference.Kind,\n        packagePath: AbsolutePath,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fileSystem: FileSystem\n    ) throws -> ManifestJSONParser.Result {\n        let decoder = JSONDecoder.makeWithDefaults()\n\n        // Validate the version first to detect use of a mismatched PD library.\n        let versionedInput: VersionedInput\n        do {\n            versionedInput = try decoder.decode(VersionedInput.self, from: jsonString)\n        } catch {\n            // If we cannot even decode the version, assume that a pre-5.9 PD library is being used which emits an incompatible JSON format.\n            throw ManifestParseError.unsupportedVersion(version: 1, underlyingError: \"\\(error.interpolationDescription)\")\n        }\n        guard versionedInput.version == 2 else {\n            throw ManifestParseError.unsupportedVersion(version: versionedInput.version)\n        }\n\n        let input = try decoder.decode(Input.self, from: jsonString)\n\n        guard input.errors.isEmpty else {\n            throw ManifestParseError.runtimeManifestErrors(input.errors)\n        }\n\n        var packagePath = packagePath\n        switch packageKind {\n        case .localSourceControl(let _packagePath):\n            // we have a more accurate path than the virtual one\n            packagePath = _packagePath\n        case .root(let _packagePath), .fileSystem(let _packagePath):\n            // we dont have a more accurate path, and they should be the same\n            // asserting (debug only) to make sure refactoring is correct 11/2023\n            assert(packagePath == _packagePath, \"expecting package path '\\(packagePath)' to be the same as '\\(_packagePath)'\")\n            break\n        case .remoteSourceControl, .registry:\n            // we dont have a more accurate path\n            break\n        }\n\n        let dependencies = try input.package.dependencies.map {\n            try Self.parseDependency(\n                dependency: $0,\n                toolsVersion: toolsVersion,\n                parentPackagePath: packagePath,\n                identityResolver: identityResolver,\n                dependencyMapper: dependencyMapper,\n                fileSystem: fileSystem\n            )\n        }\n\n        return Result(\n            name: input.package.name,\n            defaultLocalization: input.package.defaultLocalization?.tag,\n            platforms: try input.package.platforms.map { try Self.parsePlatforms($0) } ?? [],\n            targets: try input.package.targets.map { try Self.parseTarget(target: $0, identityResolver: identityResolver) },\n            pkgConfig: input.package.pkgConfig,\n            swiftLanguageVersions: try input.package.swiftLanguageVersions.map { try Self.parseSwiftLanguageVersions($0) },\n            dependencies: dependencies,\n            providers: input.package.providers?.map { .init($0) },\n            products: try input.package.products.map { try .init($0) },\n            traits: Set(input.package.traits?.map { TraitDescription($0) } ?? []),\n            cxxLanguageStandard: input.package.cxxLanguageStandard?.rawValue,\n            cLanguageStandard: input.package.cLanguageStandard?.rawValue\n        )\n    }\n\n    private static func parsePlatforms(_ declaredPlatforms: [Serialization.SupportedPlatform]) throws -> [PlatformDescription] {\n        // Empty list is not supported.\n        if declaredPlatforms.isEmpty {\n            throw ManifestParseError.runtimeManifestErrors([\"supported platforms can't be empty\"])\n        }\n\n        var platforms: [PlatformDescription] = []\n\n        for platform in declaredPlatforms {\n            let description = PlatformDescription(platform)\n\n            // Check for duplicates.\n            if platforms.map({ $0.platformName }).contains(description.platformName) {\n                // FIXME: We need to emit the API name and not the internal platform name.\n                throw ManifestParseError.runtimeManifestErrors([\"found multiple declaration for the platform: \\(description.platformName)\"])\n            }\n\n            platforms.append(description)\n        }\n\n        return platforms\n    }\n\n    private static func parseSwiftLanguageVersions(_ versions: [Serialization.SwiftVersion]) throws -> [SwiftLanguageVersion] {\n        return try versions.map {\n            let languageVersionString: String\n            switch $0 {\n            case .v3: languageVersionString = \"3\"\n            case .v4: languageVersionString = \"4\"\n            case .v4_2: languageVersionString = \"4.2\"\n            case .v5: languageVersionString = \"5\"\n            case .v6: languageVersionString = \"6\"\n            case .version(let version): languageVersionString = version\n            }\n            guard let languageVersion = SwiftLanguageVersion(string: languageVersionString) else {\n                throw ManifestParseError.runtimeManifestErrors([\"invalid Swift language version: \\(languageVersionString)\"])\n            }\n            return languageVersion\n        }\n    }\n\n    private static func parseDependency(\n        dependency: Serialization.PackageDependency,\n        toolsVersion: ToolsVersion,\n        parentPackagePath: AbsolutePath,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fileSystem: FileSystem\n    ) throws -> PackageDependency {\n        do {\n            return try dependencyMapper.mappedDependency(\n                MappablePackageDependency(dependency, parentPackagePath: parentPackagePath),\n                fileSystem: fileSystem\n            )\n        } catch let error as TSCBasic.PathValidationError {\n            if case .fileSystem(_, let path) = dependency.kind {\n                throw ManifestParseError.invalidManifestFormat(\"'\\(path)' is not a valid path for path-based dependencies; use relative or absolute path instead.\", diagnosticFile: nil, compilerCommandLine: nil)\n            } else {\n                throw error\n            }\n        } catch {\n            throw ManifestParseError.invalidManifestFormat(\"\\(error.interpolationDescription)\", diagnosticFile: nil, compilerCommandLine: nil)\n        }\n    }\n\n    private static func parseTarget(\n        target: Serialization.Target,\n        identityResolver: IdentityResolver\n    ) throws -> TargetDescription {\n        let providers = target.providers?.map { SystemPackageProviderDescription($0) }\n        let pluginCapability = target.pluginCapability.map { TargetDescription.PluginCapability($0) }\n        let dependencies = try target.dependencies.map { try TargetDescription.Dependency($0, identityResolver: identityResolver) }\n\n        try target.sources?.forEach{ _ = try RelativePath(validating: $0) }\n        try target.exclude.forEach{ _ = try RelativePath(validating: $0) }\n\n        let pluginUsages = target.pluginUsages?.map { TargetDescription.PluginUsage.init($0) }\n\n        return try TargetDescription(\n            name: target.name,\n            dependencies: dependencies,\n            path: target.path,\n            url: target.url,\n            exclude: target.exclude,\n            sources: target.sources,\n            resources: try Self.parseResources(target.resources),\n            publicHeadersPath: target.publicHeadersPath,\n            type: .init(target.type),\n            packageAccess: target.packageAccess,\n            pkgConfig: target.pkgConfig,\n            providers: providers,\n            pluginCapability: pluginCapability,\n            settings: try Self.parseBuildSettings(target),\n            checksum: target.checksum,\n            pluginUsages: pluginUsages\n        )\n    }\n\n    private static func parseResources(_ resources: [Serialization.Resource]?) throws -> [TargetDescription.Resource] {\n        return try resources?.map {\n            let path = try RelativePath(validating: $0.path)\n            switch $0.rule {\n            case \"process\":\n                let localization = $0.localization.map({ TargetDescription.Resource.Localization(rawValue: $0.rawValue)! })\n                return .init(rule: .process(localization: localization), path: path.pathString)\n            case \"copy\":\n                return .init(rule: .copy, path: path.pathString)\n            case \"embedInCode\":\n                return .init(rule: .embedInCode, path: path.pathString)\n            default:\n                throw InternalError(\"invalid resource rule \\($0.rule)\")\n            }\n        } ?? []\n    }\n\n    private static func parseBuildSettings(_ target: Serialization.Target) throws -> [TargetBuildSettingDescription.Setting] {\n        var settings: [TargetBuildSettingDescription.Setting] = []\n        try target.cSettings?.forEach {\n            settings.append(try .init($0))\n        }\n        try target.cxxSettings?.forEach {\n            settings.append(try .init($0))\n        }\n        try target.swiftSettings?.forEach {\n            settings.append(try .init($0))\n        }\n        try target.linkerSettings?.forEach {\n            settings.append(try .init($0))\n        }\n        return settings\n    }\n\n    /// Looks for Xcode-style build setting macros \"$()\".\n    fileprivate static let invalidValueRegex = try! RegEx(pattern: #\"(\\$\\(.*?\\))\"#)\n}\n\nextension SystemPackageProviderDescription {\n    init(_ provider: Serialization.SystemPackageProvider) {\n        switch provider {\n        case .brew(let values):\n            self = .brew(values)\n        case .apt(let values):\n            self = .apt(values)\n        case .yum(let values):\n            self = .yum(values)\n        case .nuget(let values):\n            self = .nuget(values)\n        }\n    }\n}\n\nextension PackageDependency.SourceControl.Requirement {\n    init(_ requirement: Serialization.PackageDependency.SourceControlRequirement) {\n        switch requirement {\n        case .exact(let version):\n            self = .exact(.init(version))\n        case .range(let lowerBound, let upperBound):\n            let lower: TSCUtility.Version = .init(lowerBound)\n            let upper: TSCUtility.Version = .init(upperBound)\n            self = .range(lower..<upper)\n        case .revision(let revision):\n            self = .revision(revision)\n        case .branch(let branch):\n            self = .branch(branch)\n        }\n    }\n}\n\nextension PackageDependency.Registry.Requirement {\n    init(_ requirement: Serialization.PackageDependency.RegistryRequirement) {\n        switch requirement {\n        case .exact(let version):\n            self = .exact(.init(version))\n        case .range(let lowerBound, let upperBound):\n            let lower: TSCUtility.Version = .init(lowerBound)\n            let upper: TSCUtility.Version = .init(upperBound)\n            self = .range(lower..<upper)\n        }\n    }\n}\n\n#if ENABLE_APPLE_PRODUCT_TYPES\nextension ProductSetting {\n    init(_ setting: Serialization.ProductSetting) {\n        switch setting {\n        case .bundleIdentifier(let value):\n            self = .bundleIdentifier(value)\n        case .teamIdentifier(let value):\n            self = .teamIdentifier(value)\n        case .displayVersion(let value):\n            self = .displayVersion(value)\n        case .bundleVersion(let value):\n            self = .bundleVersion(value)\n        case .iOSAppInfo(let appInfo):\n            self = .iOSAppInfo(.init(appInfo))\n        }\n    }\n}\n\nextension ProductSetting.IOSAppInfo {\n    init(_ appInfo: Serialization.ProductSetting.IOSAppInfo) {\n        self.init(\n            appIcon: appInfo.appIcon.map { .init($0) },\n            accentColor: appInfo.accentColor.map { .init($0) },\n            supportedDeviceFamilies: appInfo.supportedDeviceFamilies.map { .init($0) },\n            supportedInterfaceOrientations: appInfo.supportedInterfaceOrientations.map { .init($0) },\n            capabilities: appInfo.capabilities.map { .init($0) },\n            appCategory: appInfo.appCategory.map { .init($0) },\n            additionalInfoPlistContentFilePath: appInfo.additionalInfoPlistContentFilePath\n        )\n    }\n}\n\nextension ProductSetting.IOSAppInfo.DeviceFamily {\n    init(_ deviceFamily: Serialization.ProductSetting.IOSAppInfo.DeviceFamily) {\n        switch deviceFamily {\n        case .phone: self = .phone\n        case .pad: self = .pad\n        case .mac: self = .mac\n        }\n    }\n}\n\nextension ProductSetting.IOSAppInfo.DeviceFamilyCondition {\n    init(_ condition: Serialization.ProductSetting.IOSAppInfo.DeviceFamilyCondition) {\n        self.init(deviceFamilies: condition.deviceFamilies.map { .init($0) })\n    }\n}\n\nextension ProductSetting.IOSAppInfo.InterfaceOrientation {\n    init(_ interfaceOrientation: Serialization.ProductSetting.IOSAppInfo.InterfaceOrientation) {\n        switch interfaceOrientation {\n        case .portrait(let condition):\n            self = .portrait(condition: condition.map { .init($0) })\n        case .portraitUpsideDown(let condition):\n            self = .portraitUpsideDown(condition: condition.map { .init($0) })\n        case .landscapeRight(let condition):\n            self = .landscapeRight(condition: condition.map { .init($0) })\n        case .landscapeLeft(let condition):\n            self = .landscapeLeft(condition: condition.map { .init($0) })\n        }\n    }\n}\n\nextension ProductSetting.IOSAppInfo.AppIcon {\n    init(_ icon: Serialization.ProductSetting.IOSAppInfo.AppIcon) {\n        switch icon {\n        case .placeholder(icon: let icon):\n            self = .placeholder(icon: .init(icon))\n        case .asset(let name):\n            self = .asset(name: name)\n        }\n    }\n}\n\nextension ProductSetting.IOSAppInfo.AppIcon.PlaceholderIcon {\n    init(_ icon: Serialization.ProductSetting.IOSAppInfo.AppIcon.PlaceholderIcon) {\n        self.init(rawValue: icon.rawValue)\n    }\n}\n\nextension ProductSetting.IOSAppInfo.AccentColor {\n    init(_ color: Serialization.ProductSetting.IOSAppInfo.AccentColor) {\n        switch color {\n        case .presetColor(let color):\n            self = .presetColor(presetColor: .init(color))\n        case .asset(let name):\n            self = .asset(name: name)\n        }\n    }\n}\n\nextension ProductSetting.IOSAppInfo.AccentColor.PresetColor {\n    init(_ color: Serialization.ProductSetting.IOSAppInfo.AccentColor.PresetColor) {\n        self.init(rawValue: color.rawValue)\n    }\n}\n\nextension ProductSetting.IOSAppInfo.Capability {\n    init(_ capability: Serialization.ProductSetting.IOSAppInfo.Capability) {\n        switch capability {\n        case .appTransportSecurity(configuration: let configuration, let condition):\n            self.init(purpose: \"appTransportSecurity\", appTransportSecurityConfiguration: .init(configuration), condition: condition.map { .init($0) })\n        case .bluetoothAlways(purposeString: let purposeString, let condition):\n            self.init(purpose: \"bluetoothAlways\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .calendars(purposeString: let purposeString, let condition):\n            self.init(purpose: \"calendars\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .camera(purposeString: let purposeString, let condition):\n            self.init(purpose: \"camera\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .contacts(purposeString: let purposeString, let condition):\n            self.init(purpose: \"contacts\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .faceID(purposeString: let purposeString, let condition):\n            self.init(purpose: \"faceID\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .fileAccess(let location, mode: let mode, let condition):\n            self.init(purpose: \"fileAccess\", fileAccessLocation: location.rawValue, fileAccessMode: mode.rawValue, condition: condition.map { .init($0) })\n        case .incomingNetworkConnections(let condition):\n            self.init(purpose: \"incomingNetworkConnections\", condition: condition.map { .init($0) })\n        case .localNetwork(purposeString: let purposeString, bonjourServiceTypes: let bonjourServiceTypes, let condition):\n            self.init(purpose: \"localNetwork\", purposeString: purposeString, bonjourServiceTypes: bonjourServiceTypes, condition: condition.map { .init($0) })\n        case .locationAlwaysAndWhenInUse(purposeString: let purposeString, let condition):\n            self.init(purpose: \"locationAlwaysAndWhenInUse\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .locationWhenInUse(purposeString: let purposeString, let condition):\n            self.init(purpose: \"locationWhenInUse\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .mediaLibrary(purposeString: let purposeString, let condition):\n            self.init(purpose: \"mediaLibrary\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .microphone(purposeString: let purposeString, let condition):\n            self.init(purpose: \"microphone\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .motion(purposeString: let purposeString, let condition):\n            self.init(purpose: \"motion\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .nearbyInteractionAllowOnce(purposeString: let purposeString, let condition):\n            self.init(purpose: \"nearbyInteractionAllowOnce\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .outgoingNetworkConnections(let condition):\n            self.init(purpose: \"outgoingNetworkConnections\", condition: condition.map { .init($0) })\n        case .photoLibrary(purposeString: let purposeString, let condition):\n            self.init(purpose: \"photoLibrary\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .photoLibraryAdd(purposeString: let purposeString, let condition):\n            self.init(purpose: \"photoLibraryAdd\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .reminders(purposeString: let purposeString, let condition):\n            self.init(purpose: \"reminders\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .speechRecognition(purposeString: let purposeString, let condition):\n            self.init(purpose: \"speechRecognition\", purposeString: purposeString, condition: condition.map { .init($0) })\n        case .userTracking(purposeString: let purposeString, let condition):\n            self.init(purpose: \"userTracking\", purposeString: purposeString, condition: condition.map { .init($0) })\n        }\n    }\n}\n\nextension ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration {\n    init(_ configuration: Serialization.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration) {\n        self.init(\n            allowsArbitraryLoadsInWebContent: configuration.allowsArbitraryLoadsInWebContent,\n            allowsArbitraryLoadsForMedia: configuration.allowsArbitraryLoadsForMedia,\n            allowsLocalNetworking: configuration.allowsLocalNetworking,\n            exceptionDomains: configuration.exceptionDomains?.map { .init($0) },\n            pinnedDomains: configuration.pinnedDomains?.map { .init($0) }\n        )\n    }\n}\n\nextension ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.ExceptionDomain {\n    init(_ exceptionDomain: Serialization.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.ExceptionDomain) {\n        self.init(\n            domainName: exceptionDomain.domainName,\n            includesSubdomains: exceptionDomain.includesSubdomains,\n            exceptionAllowsInsecureHTTPLoads: exceptionDomain.exceptionAllowsInsecureHTTPLoads,\n            exceptionMinimumTLSVersion: exceptionDomain.exceptionMinimumTLSVersion,\n            exceptionRequiresForwardSecrecy: exceptionDomain.exceptionRequiresForwardSecrecy,\n            requiresCertificateTransparency: exceptionDomain.requiresCertificateTransparency\n        )\n    }\n}\n\nextension ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.PinnedDomain {\n    init(_ pinnedDomain: Serialization.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.PinnedDomain) {\n        self.init(\n            domainName: pinnedDomain.domainName,\n            includesSubdomains: pinnedDomain.includesSubdomains,\n            pinnedCAIdentities: pinnedDomain.pinnedCAIdentities,\n            pinnedLeafIdentities: pinnedDomain.pinnedLeafIdentities\n        )\n    }\n}\n\nextension ProductSetting.IOSAppInfo.AppCategory {\n    init(_ category: Serialization.ProductSetting.IOSAppInfo.AppCategory) {\n        self.init(rawValue: category.rawValue)\n    }\n}\n#endif\n\nextension ProductDescription {\n    init(_ product: Serialization.Product) throws {\n        let productType: ProductType\n        switch product.productType {\n        case .executable:\n            productType = .executable\n        case .plugin:\n            productType = .plugin\n        case .library(let type):\n            productType = .library(.init(type))\n        }\n        #if ENABLE_APPLE_PRODUCT_TYPES\n        try self.init(name: product.name, type: productType, targets: product.targets, settings: product.settings.map { .init($0) })\n        #else\n        try self.init(name: product.name, type: productType, targets: product.targets)\n        #endif\n    }\n}\n\nextension ProductType.LibraryType {\n    init(_ libraryType: Serialization.Product.ProductType.LibraryType) {\n        switch libraryType {\n        case .dynamic:\n            self = .dynamic\n        case .static:\n            self = .static\n        case .automatic:\n            self = .automatic\n        }\n    }\n}\n\nextension TargetDescription.Dependency {\n    init(_ dependency: Serialization.TargetDependency, identityResolver: IdentityResolver) throws {\n        switch dependency {\n        case .target(let name, let condition):\n            self = .target(name: name, condition: condition.map { .init($0) })\n        case .product(let name, let package, let moduleAliases, let condition):\n            var package: String? = package\n            if let packageName = package {\n                package = try identityResolver.mappedIdentity(for: .plain(packageName)).description\n            }\n            self = .product(name: name, package: package, moduleAliases: moduleAliases, condition: condition.map { .init($0) })\n        case .byName(let name, let condition):\n            self = .byName(name: name, condition: condition.map { .init($0) })\n        }\n    }\n}\n\nextension PackageConditionDescription {\n    init(_ condition: Serialization.TargetDependency.Condition) {\n        self.init(\n            platformNames: condition.platforms?.map { $0.name } ?? [],\n            traits: condition.traits\n        )\n    }\n}\n\nextension TargetDescription.TargetKind {\n    init(_ type: Serialization.TargetType) {\n        switch type {\n        case .regular:\n            self = .regular\n        case .executable:\n            self = .executable\n        case .test:\n            self = .test\n        case .system:\n            self = .system\n        case .binary:\n            self = .binary\n        case .plugin:\n            self = .plugin\n        case .macro:\n            self = .macro\n        }\n    }\n}\n\nextension TargetDescription.PluginCapability {\n    init(_ capability: Serialization.PluginCapability) {\n        switch capability {\n        case .buildTool:\n            self = .buildTool\n        case .command(let intent, let permissions):\n            self = .command(intent: .init(intent), permissions: permissions.map { .init($0) })\n        }\n    }\n}\n\nextension TargetDescription.PluginCommandIntent {\n    init(_ intent: Serialization.PluginCommandIntent) {\n        switch intent {\n        case .documentationGeneration:\n            self = .documentationGeneration\n        case .sourceCodeFormatting:\n            self = .sourceCodeFormatting\n        case .custom(let verb, let description):\n            self = .custom(verb: verb, description: description)\n        }\n    }\n}\n\nextension TargetDescription.PluginPermission {\n    init(_ permission: Serialization.PluginPermission) {\n        switch permission {\n        case .allowNetworkConnections(let scope, let reason):\n            self = .allowNetworkConnections(scope: .init(scope), reason: reason)\n        case .writeToPackageDirectory(let reason):\n            self = .writeToPackageDirectory(reason: reason)\n        }\n    }\n}\n\nextension TargetDescription.PluginNetworkPermissionScope {\n    init(_ scope: Serialization.PluginNetworkPermissionScope) {\n        switch scope {\n        case .none:\n            self = .none\n        case .local(let ports):\n            self = .local(ports: ports)\n        case .all(ports: let ports):\n            self = .all(ports: ports)\n        case .docker:\n            self = .docker\n        case .unixDomainSocket:\n            self = .unixDomainSocket\n        }\n    }\n}\n\nextension TargetDescription.PluginUsage {\n    init(_ usage: Serialization.PluginUsage) {\n        switch usage {\n        case .plugin(let name, let package):\n            self = .plugin(name: name, package: package)\n        }\n    }\n}\n\nextension TSCUtility.Version {\n    init(_ version: Serialization.Version) {\n        self.init(\n            version.major,\n            version.minor,\n            version.patch,\n            prereleaseIdentifiers: version.prereleaseIdentifiers,\n            buildMetadataIdentifiers: version.buildMetadataIdentifiers\n        )\n    }\n}\n\nextension PlatformDescription {\n    init(_ platform: Serialization.SupportedPlatform) {\n        let platformName = platform.platform.name\n        let versionString = platform.version ?? \"\"\n\n        let versionComponents = versionString.split(\n            separator: \".\",\n            omittingEmptySubsequences: false\n        )\n        var version: [String.SubSequence] = []\n        var options: [String.SubSequence] = []\n\n        for (idx, component) in versionComponents.enumerated() {\n            if idx < 2 {\n                version.append(component)\n                continue\n            }\n\n            if idx == 2, UInt(component) != nil {\n                version.append(component)\n                continue\n            }\n\n            options.append(component)\n        }\n\n        self.init(\n            name: platformName,\n            version: version.joined(separator: \".\"),\n            options: options.map{ String($0) }\n        )\n    }\n}\n\nextension TargetBuildSettingDescription.Kind {\n    static func from(_ name: String, values: [String]) throws -> Self {\n        // Diagnose invalid values.\n        for item in values {\n            let groups = ManifestJSONParser.invalidValueRegex.matchGroups(in: item).flatMap{ $0 }\n            if !groups.isEmpty {\n                let error = \"the build setting '\\(name)' contains invalid component(s): \\(groups.joined(separator: \" \"))\"\n                throw ManifestParseError.runtimeManifestErrors([error])\n            }\n        }\n\n        switch name {\n        case \"headerSearchPath\":\n            guard let value = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n            return .headerSearchPath(value)\n        case \"define\":\n            guard let value = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n            return .define(value)\n        case \"linkedLibrary\":\n            guard let value = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n            return .linkedLibrary(value)\n        case \"linkedFramework\":\n            guard let value = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n            return .linkedFramework(value)\n        case \"interoperabilityMode\":\n            guard let rawLang = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n            guard let lang = TargetBuildSettingDescription.InteroperabilityMode(rawValue: rawLang) else {\n                throw InternalError(\"unknown interoperability mode: \\(rawLang)\")\n            }\n            if values.count > 1 {\n                throw InternalError(\"invalid build settings value\")\n            }\n            return .interoperabilityMode(lang)\n        case \"enableUpcomingFeature\":\n            guard let value = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n            return .enableUpcomingFeature(value)\n        case \"enableExperimentalFeature\":\n            guard let value = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n            return .enableExperimentalFeature(value)\n        case \"strictMemorySafety\":\n            return .strictMemorySafety\n        case \"unsafeFlags\":\n            return .unsafeFlags(values)\n\n        case \"swiftLanguageVersion\", \"swiftLanguageMode\":\n            guard let rawVersion = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n\n            if values.count > 1 {\n                throw InternalError(\"invalid build settings value\")\n            }\n\n            guard let version = SwiftLanguageVersion(string: rawVersion) else {\n                throw InternalError(\"unknown swift language version: \\(rawVersion)\")\n            }\n\n            return .swiftLanguageMode(version)\n        case \"treatAllWarnings\":\n            guard values.count == 1 else {\n                throw InternalError(\"invalid build settings value\")\n            }\n\n            let rawLevel = values[0]\n\n            guard let level = TargetBuildSettingDescription.WarningLevel(rawValue: rawLevel) else {\n                throw InternalError(\"unknown warning treat level: \\(rawLevel)\")\n            }\n\n            return .treatAllWarnings(level)\n\n        case \"treatWarning\":\n            guard values.count == 2 else {\n                throw InternalError(\"invalid build settings value\")\n            }\n\n            let name = values[0]\n            let rawValue = values[1]\n\n            guard let level = TargetBuildSettingDescription.WarningLevel(rawValue: rawValue) else {\n                throw InternalError(\"unknown warning treat level: \\(rawValue)\")\n            }\n\n            return .treatWarning(name, level)\n\n        case \"enableWarning\":\n            guard values.count == 1 else {\n                throw InternalError(\"invalid build settings value\")\n            }\n            return .enableWarning(values[0])\n\n        case \"disableWarning\":\n            guard values.count == 1 else {\n                throw InternalError(\"invalid build settings value\")\n            }\n            return .disableWarning(values[0])\n\n        case \"defaultIsolation\":\n            guard let rawValue = values.first else {\n                throw InternalError(\"invalid (empty) build settings value\")\n            }\n            guard let isolation = TargetBuildSettingDescription.DefaultIsolation(rawValue: rawValue) else {\n                throw InternalError(\"unknown default isolation: \\(rawValue)\")\n            }\n\n            return .defaultIsolation(isolation)\n        default:\n            throw InternalError(\"invalid build setting \\(name)\")\n        }\n    }\n}\n\nextension PackageConditionDescription {\n    init(_ condition: Serialization.BuildSettingCondition) {\n        self.init(platformNames: condition.platforms?.map { $0.name } ?? [], config: condition.config?.config, traits: condition.traits)\n    }\n}\n\nextension TargetBuildSettingDescription.Setting {\n    init(_ setting: Serialization.CSetting) throws {\n        self.init(\n            tool: .c,\n            kind: try .from(setting.data.name, values: setting.data.value),\n            condition: setting.data.condition.map { .init($0) }\n        )\n    }\n\n    init(_ setting: Serialization.CXXSetting) throws {\n        self.init(\n            tool: .cxx,\n            kind: try .from(setting.data.name, values: setting.data.value),\n            condition: setting.data.condition.map { .init($0) }\n        )\n    }\n\n    init(_ setting: Serialization.LinkerSetting) throws {\n        self.init(\n            tool: .linker,\n            kind: try .from(setting.data.name, values: setting.data.value),\n            condition: setting.data.condition.map { .init($0) }\n        )\n    }\n\n    init(_ setting: Serialization.SwiftSetting) throws {\n        self.init(\n            tool: .swift,\n            kind: try .from(setting.data.name, values: setting.data.value),\n            condition: setting.data.condition.map { .init($0) }\n        )\n    }\n}\n\nextension TraitDescription {\n    init(_ trait: Serialization.Trait) {\n        self.init(\n            name: trait.name,\n            description: trait.description,\n            enabledTraits: trait.enabledTraits\n        )\n    }\n}\n\nextension PackageDependency.Trait {\n    init(_ trait: Serialization.PackageDependency.Trait) {\n        self.init(\n            name: trait.name,\n            condition: trait.condition.flatMap { .init($0) }\n        )\n    }\n}\n\n\nextension PackageDependency.Trait.Condition {\n    init(_ condition: Serialization.PackageDependency.Trait.Condition) {\n        self.init(traits: condition.traits)\n    }\n}\n\nextension MappablePackageDependency {\n    fileprivate init(_ seed: Serialization.PackageDependency, parentPackagePath: AbsolutePath) {\n        switch seed.kind {\n        case .fileSystem(let name, let path):\n            self.init(\n                parentPackagePath: parentPackagePath,\n                kind: .fileSystem(\n                    name: name,\n                    path: path\n                ),\n                productFilter: .everything,\n                traits: seed.traits.flatMap { Set($0.map { PackageDependency.Trait.init($0) } ) }\n            )\n        case .sourceControl(let name, let location, let requirement):\n            self.init(\n                parentPackagePath: parentPackagePath,\n                kind: .sourceControl(\n                    name: name,\n                    location: location,\n                    requirement: .init(requirement)\n                ),\n                productFilter: .everything,\n                traits: seed.traits.flatMap { Set($0.map { PackageDependency.Trait.init($0) } ) }\n            )\n        case .registry(let id, let requirement):\n            self.init(\n                parentPackagePath: parentPackagePath,\n                kind: .registry(\n                    id: id,\n                    requirement: .init(requirement)\n                ),\n                productFilter: .everything,\n                traits: seed.traits.flatMap { Set($0.map { PackageDependency.Trait.init($0) } ) }\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/ManifestLoader+Validation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\nimport TSCBasic\nimport TSCUtility\n\npublic struct ManifestValidator {\n    static var supportedLocalBinaryDependencyExtensions: [String] {\n        Set([\"zip\"] + BinaryModule.Kind.allCases.filter { !$0.isUnknown }.map { $0.fileExtension }).sorted()\n    }\n    static var supportedRemoteBinaryDependencyExtensions: [String] {\n        [\"artifactbundleindex\", \"zip\"]\n    }\n\n    private let manifest: Manifest\n    private let sourceControlValidator: ManifestSourceControlValidator\n    private let fileSystem: FileSystem\n\n    public init(manifest: Manifest, sourceControlValidator: ManifestSourceControlValidator, fileSystem: FileSystem) {\n        self.manifest = manifest\n        self.sourceControlValidator = sourceControlValidator\n        self.fileSystem = fileSystem\n    }\n\n    /// Validate the provided manifest.\n    public func validate() -> [Basics.Diagnostic] {\n        var diagnostics = [Basics.Diagnostic]()\n\n        diagnostics += self.validateTargets()\n        diagnostics += self.validateProducts()\n        diagnostics += self.validateDependencies()\n        diagnostics += self.validateTraits()\n\n        // Checks reserved for tools version 5.2 features\n        if self.manifest.toolsVersion >= .v5_2 {\n            diagnostics += self.validateTargetDependencyReferences()\n            diagnostics += self.validateBinaryTargets()\n        }\n\n        return diagnostics\n    }\n\n    private func validateTargets() -> [Basics.Diagnostic] {\n        var diagnostics = [Basics.Diagnostic]()\n\n        let duplicateTargetNames = self.manifest.targets.map({ $0.name }).spm_findDuplicates()\n        for name in duplicateTargetNames {\n            diagnostics.append(.duplicateTargetName(targetName: name))\n        }\n\n        return diagnostics\n    }\n\n    private func validateProducts()  -> [Basics.Diagnostic] {\n        var diagnostics = [Basics.Diagnostic]()\n        \n        for product in self.manifest.products {\n            // Check that the product contains targets.\n            guard !product.targets.isEmpty else {\n                diagnostics.append(.emptyProductTargets(productName: product.name))\n                continue\n            }\n\n            // Check that the product references existing targets.\n            for target in product.targets {\n                if !self.manifest.targetMap.keys.contains(target) {\n                    diagnostics.append(.productTargetNotFound(productName: product.name, targetName: target, validTargets: self.manifest.targetMap.keys.sorted()))\n                }\n            }\n\n            // Check that products that reference only binary targets don't define an explicit library type.\n            if product.targets.allSatisfy({ self.manifest.targetMap[$0]?.type == .binary }) {\n                switch product.type {\n                case .library(.automatic), .executable:\n                    break\n                default:\n                    diagnostics.append(.invalidBinaryProductType(productName: product.name))\n                }\n            }\n        }\n\n        return diagnostics\n    }\n\n    private func validateTraits() -> [Basics.Diagnostic] {\n        var diagnostics = [Basics.Diagnostic]()\n\n        if self.manifest.traits.count > 300 {\n            // We limit the number of traits to 300 for now\n            diagnostics.append(.tooManyTraits())\n        }\n\n        for trait in self.manifest.traits {\n            let traitName = trait.name\n            guard traitName.count > 0 else {\n                diagnostics.append(.emptyTraitName())\n                continue\n            }\n\n            guard traitName.isValidIdentifier else {\n                diagnostics.append(.invalidTraitName(trait: traitName))\n                continue\n            }\n        }\n\n        let traitKeys = Set(self.manifest.traits.map { $0.name })\n\n        for trait in self.manifest.traits {\n            for otherTrait in trait.enabledTraits {\n                if !traitKeys.contains(otherTrait) {\n                    // The trait is not contained in the other trait.\n                    // This means they reference a trait that this package doesn't define.\n                    diagnostics.append(.invalidEnabledTrait(trait: otherTrait, enabledBy: trait.name))\n                }\n            }\n        }\n\n        return diagnostics\n    }\n\n    private func validateDependencies() -> [Basics.Diagnostic] {\n        var diagnostics = [Basics.Diagnostic]()\n\n        // validate dependency requirements\n        for dependency in self.manifest.dependencies {\n            switch dependency {\n            case .sourceControl(let sourceControl):\n                diagnostics += validateSourceControlDependency(sourceControl)\n            default:\n                break\n            }\n        }\n\n        return diagnostics\n    }\n\n    private func validateBinaryTargets() -> [Basics.Diagnostic] {\n        var diagnostics = [Basics.Diagnostic]()\n\n        // Check that binary targets point to the right file type.\n        for target in self.manifest.targets where target.type == .binary {\n            if target.isLocal {\n                guard let path = target.path else {\n                    diagnostics.append(.invalidBinaryLocation(targetName: target.name))\n                    continue\n                }\n\n                guard let path = path.spm_chuzzle(), !path.isEmpty else {\n                    diagnostics.append(.invalidLocalBinaryPath(path: path, targetName: target.name))\n                    continue\n                }\n\n                guard let relativePath = try? Basics.RelativePath(validating: path) else {\n                    diagnostics.append(.invalidLocalBinaryPath(path: path, targetName: target.name))\n                    continue\n                }\n\n                let validExtensions = Self.supportedLocalBinaryDependencyExtensions\n                guard let fileExtension = relativePath.extension, validExtensions.contains(fileExtension) else {\n                    diagnostics.append(.unsupportedBinaryLocationExtension(\n                        targetName: target.name,\n                        validExtensions: validExtensions\n                    ))\n                    continue\n                }\n            } else if target.isRemote {\n                guard let url = target.url else {\n                    diagnostics.append(.invalidBinaryLocation(targetName: target.name))\n                    continue\n                }\n\n                guard let url = url.spm_chuzzle(), !url.isEmpty else {\n                    diagnostics.append(.invalidBinaryURL(url: url, targetName: target.name))\n                    continue\n                }\n\n                guard let url = URL(string: url) else {\n                    diagnostics.append(.invalidBinaryURL(url: url, targetName: target.name))\n                    continue\n                }\n\n                let validSchemes = [\"https\"]\n                guard url.scheme.map({ validSchemes.contains($0) }) ?? false else {\n                    diagnostics.append(.invalidBinaryURLScheme(\n                        targetName: target.name,\n                        validSchemes: validSchemes\n                    ))\n                    continue\n                }\n\n                guard Self.supportedRemoteBinaryDependencyExtensions.contains(url.pathExtension) else {\n                    diagnostics.append(.unsupportedBinaryLocationExtension(\n                        targetName: target.name,\n                        validExtensions: Self.supportedRemoteBinaryDependencyExtensions\n                    ))\n                    continue\n                }\n\n            } else {\n                diagnostics.append(.invalidBinaryLocation(targetName: target.name))\n                continue\n            }\n        }\n\n        return diagnostics\n    }\n\n    /// Validates that product target dependencies reference an existing package.\n    private func validateTargetDependencyReferences() -> [Basics.Diagnostic] {\n        var diagnostics = [Basics.Diagnostic]()\n\n        for target in self.manifest.targets {\n            for targetDependency in target.dependencies {\n                switch targetDependency {\n                case .target:\n                    // If this is a target dependency, we don't need to check anything.\n                    break\n                case .product(_, let packageName, _, _):\n                    if self.manifest.packageDependency(referencedBy: targetDependency) == nil {\n                        diagnostics.append(.unknownTargetPackageDependency(\n                            packageName: packageName,\n                            targetName: target.name,\n                            validPackages: self.manifest.dependencies\n                        ))\n                    }\n                case .byName(let name, _):\n                    // Don't diagnose root manifests so we can emit a better diagnostic during package loading.\n                    if !self.manifest.packageKind.isRoot &&\n                        !self.manifest.targetMap.keys.contains(name) &&\n                        self.manifest.packageDependency(referencedBy: targetDependency) == nil\n                    {\n                        diagnostics.append(.unknownTargetDependency(\n                            dependency: name,\n                            targetName: target.name,\n                            validDependencies: self.manifest.dependencies\n                        ))\n                    }\n                }\n            }\n        }\n\n        return diagnostics\n    }\n\n    func validateSourceControlDependency(_ dependency: PackageDependency.SourceControl) -> [Basics.Diagnostic] {\n        var diagnostics = [Basics.Diagnostic]()\n        // if a location is on file system, validate it is in fact a git repo\n        // there is a case to be made to throw early (here) if the path does not exists\n        // but many of our tests assume they can pass a non existent path\n        if case .local(let localPath) = dependency.location, self.fileSystem.exists(localPath) {\n            do {\n                if try !self.sourceControlValidator.isValidDirectory(localPath) {\n                    // Provides better feedback when mistakenly using url: for a dependency that\n                    // is a local package. Still allows for using url with a local package that has\n                    // also been initialized by git\n                    diagnostics.append(.invalidSourceControlDirectory(localPath))\n                }\n            } catch {\n                diagnostics.append(.invalidSourceControlDirectory(localPath, underlyingError: error))\n            }\n        }\n        return diagnostics\n    }\n}\n\npublic protocol ManifestSourceControlValidator {\n    func isValidDirectory(_ path: Basics.AbsolutePath) throws -> Bool\n}\n\nextension Basics.Diagnostic {\n    static func duplicateTargetName(targetName: String) -> Self {\n        .error(\"duplicate target named '\\(targetName)'\")\n    }\n\n    static func emptyProductTargets(productName: String) -> Self {\n        .error(\"product '\\(productName)' doesn't reference any targets\")\n    }\n\n    static func productTargetNotFound(productName: String, targetName: String, validTargets: [String]) -> Self {\n        .error(\"target '\\(targetName)' referenced in product '\\(productName)' could not be found; valid targets are: '\\(validTargets.joined(separator: \"', '\"))'\")\n    }\n\n    static func invalidBinaryProductType(productName: String) -> Self {\n        .error(\"invalid type for binary product '\\(productName)'; products referencing only binary targets must be executable or automatic library products\")\n    }\n\n    static func unknownTargetDependency(dependency: String, targetName: String, validDependencies: [PackageDependency]) -> Self {\n\n        .error(\"unknown dependency '\\(dependency)' in target '\\(targetName)'; valid dependencies are: \\(validDependencies.map{ \"\\($0.descriptionForValidation)\" }.joined(separator: \", \"))\")\n    }\n\n    static func unknownTargetPackageDependency(packageName: String?, targetName: String, validPackages: [PackageDependency]) -> Self {\n        let messagePrefix: String\n        if let packageName {\n            messagePrefix = \"unknown package '\\(packageName)'\"\n        } else {\n            messagePrefix = \"undeclared package\"\n        }\n        return .error(\"\\(messagePrefix) in dependencies of target '\\(targetName)'; valid packages are: \\(validPackages.map{ \"\\($0.descriptionForValidation)\" }.joined(separator: \", \"))\")\n    }\n\n    static func invalidDependencyOnTestTarget(dependency: Module.Dependency, targetName: String) -> Self {\n        .error(\n            \"Invalid dependency: '\\(targetName)' cannot depend on test target dependency '\\(dependency.name)'. Only test targets can depend on other test targets\"\n        )\n    }\n\n    static func invalidBinaryLocation(targetName: String) -> Self {\n        .error(\"invalid location for binary target '\\(targetName)'\")\n    }\n\n    static func invalidBinaryURL(url: String, targetName: String) -> Self {\n        .error(\"invalid URL '\\(url)' for binary target '\\(targetName)'\")\n    }\n\n    static func invalidLocalBinaryPath(path: String, targetName: String) -> Self {\n        .error(\"invalid local path '\\(path)' for binary target '\\(targetName)', path expected to be relative to package root.\")\n    }\n\n    static func invalidBinaryURLScheme(targetName: String, validSchemes: [String]) -> Self {\n        .error(\"invalid URL scheme for binary target '\\(targetName)'; valid schemes are: '\\(validSchemes.joined(separator: \"', '\"))'\")\n    }\n\n    static func unsupportedBinaryLocationExtension(targetName: String, validExtensions: [String]) -> Self {\n        .error(\"unsupported extension for binary target '\\(targetName)'; valid extensions are: '\\(validExtensions.joined(separator: \"', '\"))'\")\n    }\n\n    static func invalidLanguageTag(_ languageTag: String) -> Self {\n        .error(\"\"\"\n            invalid language tag '\\(languageTag)'; the pattern for language tags is groups of latin characters and \\\n            digits separated by hyphens\n            \"\"\")\n    }\n\n    static func errorSuffix(_ error: Error?) -> String {\n        if let error {\n            return \": \\(error.interpolationDescription)\"\n        } else {\n            return \"\"\n        }\n    }\n\n    static func invalidSourceControlDirectory(_ path: Basics.AbsolutePath, underlyingError: Error? = nil) -> Self {\n        .error(\"cannot clone from local directory \\(path)\\nPlease git init or use \\\"path:\\\" for \\(path)\\(errorSuffix(underlyingError))\")\n    }\n\n    static func tooManyTraits() -> Self {\n        .error(\"A package can define a maximum of 300 traits\")\n    }\n\n    static func emptyTraitName() -> Self {\n        .error(\"Empty strings are not allowed as trait names\")\n    }\n\n    static func invalidTraitName(trait: String) -> Self {\n        .error(\"Invalid trait name \\(trait). Trait names must be valid Swift identifiers\")\n    }\n\n    static func invalidEnabledTrait(trait: String, enabledBy enablerTrait: String) -> Self {\n        .error(\"Trait \\(enablerTrait) enables \\(trait) which is not defined in the package\")\n    }\n\n    static func invalidDefaultTrait(defaultTrait: String) -> Self {\n        .error(\"Default trait \\(defaultTrait) is not defined in the package\")\n    }\n}\n\nextension TargetDescription {\n    fileprivate var isRemote: Bool { url != nil }\n    fileprivate var isLocal: Bool { path != nil }\n}\n\nextension PackageDependency {\n    fileprivate var descriptionForValidation: String {\n        var description = \"'\\(self.nameForModuleDependencyResolutionOnly)'\"\n\n        if let locationsString = {\n            switch self {\n            case .fileSystem(let settings):\n                return \"at '\\(settings.path.pathString)'\"\n            case .sourceControl(let settings):\n                switch settings.location {\n                case .local(let path):\n                    return \"at '\\(path.pathString)'\"\n                case .remote(let url):\n                    return \"from '\\(url.absoluteString)'\"\n                }\n            case .registry:\n                return .none\n            }\n        }() {\n            description += \" (\\(locationsString))\"\n        }\n\n        return description\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/ManifestLoader.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Basics\nimport Dispatch\nimport Foundation\nimport PackageModel\nimport SourceControl\n\nimport class TSCBasic.BufferedOutputByteStream\nimport struct TSCBasic.ByteString\nimport class Basics.AsyncProcess\nimport struct Basics.AsyncProcessResult\n\nimport enum TSCUtility.Diagnostics\nimport struct TSCUtility.Version\n\n#if os(Windows)\nimport WinSDK\n#endif\n\nextension AbsolutePath {\n    /// Returns the `pathString` on non-Windows platforms.  On Windows\n    /// platforms, this provides the path string normalized as per the Windows\n    /// path normalization rules.  In the case that the path is a long path, the\n    /// path will use the extended path syntax (UNC style, NT Path).\n    internal var _normalized: String {\n#if os(Windows)\n        return self.pathString.withCString(encodedAs: UTF16.self) { pwszPath in\n            let dwLength = GetFullPathNameW(pwszPath, 0, nil, nil)\n            return withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(dwLength)) {\n                _ = GetFullPathNameW(pwszPath, dwLength, $0.baseAddress, nil)\n                return String(decodingCString: $0.baseAddress!, as: UTF16.self)\n            }\n        }\n#else\n        return self.pathString\n#endif\n    }\n}\n\npublic enum ManifestParseError: Swift.Error, Equatable {\n    /// The manifest is empty, or at least from SwiftPM's perspective it is.\n    case emptyManifest(path: AbsolutePath)\n    /// The manifest contains invalid format.\n    case invalidManifestFormat(String, diagnosticFile: AbsolutePath?)\n    // TODO: Test this error.\n    case invalidManifestFormat(String, diagnosticFile: AbsolutePath?, compilerCommandLine: [String]?)\n\n    /// The manifest was successfully loaded by swift interpreter but there were runtime issues.\n    case runtimeManifestErrors([String])\n\n    /// The manifest loader specified import restrictions that the given manifest violated.\n    case importsRestrictedModules([String])\n\n    /// The JSON payload received from executing the manifest has an unsupported version, usually indicating an invalid mix-and-match of SwiftPM and PackageDescription libraries.\n    case unsupportedVersion(version: Int, underlyingError: String? = nil)\n}\n\n// used to output the errors via the observability system\nextension ManifestParseError: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .emptyManifest(let manifestPath):\n            return \"'\\(manifestPath)' is empty\"\n        case .invalidManifestFormat(let error, _, let compilerCommandLine):\n            let suffix: String\n            if let compilerCommandLine {\n                suffix = \" (compiled with: \\(compilerCommandLine))\"\n            } else {\n                suffix = \"\"\n            }\n            return \"Invalid manifest\\(suffix)\\n\\(error)\"\n        case .runtimeManifestErrors(let errors):\n            return \"invalid manifest (evaluation failed)\\n\\(errors.joined(separator: \"\\n\"))\"\n        case .importsRestrictedModules(let modules):\n            return \"invalid manifest, imports restricted modules: \\(modules.joined(separator: \", \"))\"\n        case .unsupportedVersion(let version, let underlyingError):\n            let message = \"serialized JSON uses unsupported version \\(version), indicating use of a mismatched PackageDescription library\"\n            if let underlyingError {\n                return \"\\(message), underlying error: \\(underlyingError)\"\n            }\n            return message\n        }\n    }\n}\n\n// MARK: - ManifestLoaderProtocol\n\n/// Protocol for the manifest loader interface.\npublic protocol ManifestLoaderProtocol {\n    /// Load the manifest for the package at `path`.\n    ///\n    /// - Parameters:\n    ///   - manifestPath: The root path of the package.\n    ///   - manifestToolsVersion: The version of the tools the manifest supports.\n    ///   - packageIdentity: the identity of the package\n    ///   - packageKind: The kind of package the manifest is from.\n    ///   - packageLocation: The location the package the manifest was loaded from.\n    ///   - packageVersion: Optional. The version and revision of the package.\n    ///   - identityResolver: A helper to resolve identities based on configuration\n    ///   - dependencyMapper: A helper to map dependencies.\n    ///   - fileSystem: File system to load from.\n    ///   - observabilityScope: Observability scope to emit diagnostics.\n    ///   - callbackQueue: The dispatch queue to perform completion handler on.\n    ///   - completion: The completion handler .\n    func load(\n        manifestPath: AbsolutePath,\n        manifestToolsVersion: ToolsVersion,\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packageLocation: String,\n        packageVersion: (version: Version?, revision: String?)?,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        delegateQueue: DispatchQueue\n    ) async throws -> Manifest\n\n    /// Reset any internal cache held by the manifest loader.\n    func resetCache(observabilityScope: ObservabilityScope) async\n\n    /// Reset any internal cache held by the manifest loader and purge any entries in a shared cache\n    func purgeCache(observabilityScope: ObservabilityScope) async\n}\n\npublic protocol ManifestLoaderDelegate: Sendable {\n    func willLoad(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath\n    )\n    func didLoad(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath,\n        duration: DispatchTimeInterval\n    )\n\n    func willParse(\n        packageIdentity: PackageIdentity,\n        packageLocation: String\n    )\n    func didParse(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        duration: DispatchTimeInterval\n    )\n\n    func willCompile(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath\n    )\n    func didCompile(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath,\n        duration: DispatchTimeInterval\n    )\n\n    func willEvaluate(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath\n    )\n    func didEvaluate(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath,\n        duration: DispatchTimeInterval\n    )\n}\n\n// loads a manifest given a package root path\n// this will first find the most appropriate manifest file in the package directory\n// bases on the toolchain's tools-version and proceed to load that manifest\nextension ManifestLoaderProtocol {\n    public func load(\n        packagePath: AbsolutePath,\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packageLocation: String,\n        packageVersion: (version: Version?, revision: String?)?,\n        currentToolsVersion: ToolsVersion,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        delegateQueue: DispatchQueue\n    ) async throws -> Manifest {\n        // find the manifest path and parse it's tools-version\n        let manifestPath = try ManifestLoader.findManifest(\n            packagePath: packagePath,\n            fileSystem: fileSystem,\n            currentToolsVersion: currentToolsVersion\n        )\n        let manifestToolsVersion = try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fileSystem)\n        // validate the manifest tools-version against the toolchain tools-version\n        try manifestToolsVersion.validateToolsVersion(\n            currentToolsVersion,\n            packageIdentity: packageIdentity,\n            packageVersion: packageVersion?.version?.description ?? packageVersion?.revision\n        )\n\n        return try await self.load(\n            manifestPath: manifestPath,\n            manifestToolsVersion: manifestToolsVersion,\n            packageIdentity: packageIdentity,\n            packageKind: packageKind,\n            packageLocation: packageLocation,\n            packageVersion: packageVersion,\n            identityResolver: identityResolver,\n            dependencyMapper: dependencyMapper,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            delegateQueue: delegateQueue\n        )\n    }\n}\n\n// MARK: - ManifestCacheActor\n\nactor ManifestCacheActor {\n    private var memoryCache: [ManifestLoader.CacheKey: ManifestJSONParser.Result] = [:]\n\n    func get(key: ManifestLoader.CacheKey) -> ManifestJSONParser.Result? {\n        memoryCache[key]\n    }\n\n    func set(key: ManifestLoader.CacheKey, value: ManifestJSONParser.Result) {\n        memoryCache[key] = value\n    }\n\n    func clear() {\n        memoryCache.removeAll()\n    }\n}\n\n// MARK: - ManifestLoader\n\n/// Utility class for loading manifest files.\n///\n/// This class is responsible for reading the manifest data and produce a\n/// properly formed `PackageModel.Manifest` object. It currently does so by\n/// interpreting the manifest source using Swift -- that produces a JSON\n/// serialized form of the manifest (as implemented by `PackageDescription`'s\n/// `atexit()` handler) which is then deserialized and loaded.\npublic final class ManifestLoader: ManifestLoaderProtocol {\n    public typealias Delegate = ManifestLoaderDelegate\n\n    private let toolchain: UserToolchain\n    private let serializedDiagnostics: Bool\n    private let isManifestSandboxEnabled: Bool\n    private let extraManifestFlags: [String]\n    private let importRestrictions: (startingToolsVersion: ToolsVersion, allowedImports: [String])?\n    private let pruneDependencies: Bool\n\n    // not thread safe\n    public var delegate: Delegate?\n\n    private let databaseCacheDir: AbsolutePath?\n\n    private let useInMemoryCache: Bool\n    private let memoryCacheActor = ManifestCacheActor()\n\n    public init(\n        toolchain: UserToolchain,\n        serializedDiagnostics: Bool = false,\n        isManifestSandboxEnabled: Bool = true,\n        useInMemoryCache: Bool = true,\n        cacheDir: AbsolutePath? = .none,\n        extraManifestFlags: [String]? = .none,\n        importRestrictions: (startingToolsVersion: ToolsVersion, allowedImports: [String])? = .none,\n        delegate: Delegate? = .none,\n        pruneDependencies: Bool = false\n    ) {\n        self.toolchain = toolchain\n        self.serializedDiagnostics = serializedDiagnostics\n        self.isManifestSandboxEnabled = isManifestSandboxEnabled\n        self.extraManifestFlags = extraManifestFlags ?? []\n        self.importRestrictions = importRestrictions\n\n        self.delegate = delegate\n\n        self.useInMemoryCache = useInMemoryCache\n        self.databaseCacheDir = try? cacheDir.map(resolveSymlinks)\n        self.pruneDependencies = pruneDependencies\n    }\n\n    public func load(\n        manifestPath: AbsolutePath,\n        manifestToolsVersion: ToolsVersion,\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packageLocation: String,\n        packageVersion: (version: Version?, revision: String?)?,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        delegateQueue: DispatchQueue\n    ) async throws -> Manifest {\n        // Inform the delegate.\n        let start = DispatchTime.now()\n        delegateQueue.async { [delegate = self.delegate] in\n            delegate?.willLoad(\n                packageIdentity: packageIdentity,\n                packageLocation: packageLocation,\n                manifestPath: manifestPath\n            )\n        }\n\n        // Validate that the file exists.\n        guard fileSystem.isFile(manifestPath) else {\n            throw PackageModel.Package.Error.noManifest(at: manifestPath, version: packageVersion?.version)\n        }\n\n        let parsedManifest = try await self.loadAndCacheManifest(\n            at: manifestPath,\n            toolsVersion: manifestToolsVersion,\n            packageIdentity: packageIdentity,\n            packageKind: packageKind,\n            packageLocation: packageLocation,\n            packageVersion: packageVersion?.version,\n            identityResolver: identityResolver,\n            dependencyMapper: dependencyMapper,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            delegate: delegate,\n            delegateQueue: delegateQueue\n        )\n        // Convert legacy system packages to the current target‐based model.\n        var products = parsedManifest.products\n        var targets = parsedManifest.targets\n        if products.isEmpty, targets.isEmpty,\n            fileSystem.isFile(manifestPath.parentDirectory.appending(component: moduleMapFilename)) {\n            try products.append(ProductDescription(\n                name: parsedManifest.name,\n                type: .library(.automatic),\n                targets: [parsedManifest.name])\n            )\n            targets.append(try TargetDescription(\n                name: parsedManifest.name,\n                path: \"\",\n                type: .system,\n                packageAccess: false,\n                pkgConfig: parsedManifest.pkgConfig,\n                providers: parsedManifest.providers\n            ))\n        }\n\n        let manifest = Manifest(\n            displayName: parsedManifest.name,\n            packageIdentity: packageIdentity,\n            path: manifestPath,\n            packageKind: packageKind,\n            packageLocation: packageLocation,\n            defaultLocalization: parsedManifest.defaultLocalization,\n            platforms: parsedManifest.platforms,\n            version: packageVersion?.version,\n            revision: packageVersion?.revision,\n            toolsVersion: manifestToolsVersion,\n            pkgConfig: parsedManifest.pkgConfig,\n            providers: parsedManifest.providers,\n            cLanguageStandard: parsedManifest.cLanguageStandard,\n            cxxLanguageStandard: parsedManifest.cxxLanguageStandard,\n            swiftLanguageVersions: parsedManifest.swiftLanguageVersions,\n            dependencies: parsedManifest.dependencies,\n            products: products,\n            targets: targets,\n            traits: parsedManifest.traits,\n            pruneDependencies: self.pruneDependencies\n        )\n\n        // Inform the delegate.\n        delegateQueue.async { [delegate = self.delegate] in\n            delegate?.didLoad(\n                packageIdentity: packageIdentity,\n                packageLocation: packageLocation,\n                manifestPath: manifestPath,\n                duration: start.distance(to: .now())\n            )\n        }\n\n        return manifest\n    }\n\n    /// Load the JSON string for the given manifest.\n    private func parseManifest(\n        _ result: EvaluationResult,\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packagePath: AbsolutePath,\n        packageLocation: String,\n        toolsVersion: ToolsVersion,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fileSystem: FileSystem,\n        emitCompilerOutput: Bool,\n        observabilityScope: ObservabilityScope,\n        delegate: Delegate?,\n        delegateQueue: DispatchQueue?\n    ) throws -> ManifestJSONParser.Result {\n        // Throw now if we weren't able to parse the manifest.\n        guard let manifestJSON = result.manifestJSON, !manifestJSON.isEmpty else {\n            let errors = result.errorOutput ?? result.compilerOutput ?? \"Missing or empty JSON output from manifest compilation for \\(packageIdentity)\"\n            throw ManifestParseError.invalidManifestFormat(errors, diagnosticFile: result.diagnosticFile, compilerCommandLine: result.compilerCommandLine)\n        }\n\n        // We should not have any fatal error at this point.\n        guard result.errorOutput == nil else {\n            throw InternalError(\"unexpected error output: \\(result.errorOutput!)\")\n        }\n\n        // We might have some non-fatal output (warnings/notes) from the compiler even when\n        // we were able to parse the manifest successfully.\n        if emitCompilerOutput, let compilerOutput = result.compilerOutput {\n            let metadata = result.diagnosticFile.map { diagnosticFile -> ObservabilityMetadata in\n                var metadata = ObservabilityMetadata()\n                metadata.manifestLoadingDiagnosticFile = diagnosticFile\n                return metadata\n            }\n            observabilityScope.emit(warning: compilerOutput, metadata: metadata)\n        }\n\n        let start = DispatchTime.now()\n        delegateQueue?.async {\n            delegate?.willParse(\n                packageIdentity: packageIdentity,\n                packageLocation: packageLocation\n            )\n        }\n\n        let result = try ManifestJSONParser.parse(\n            v4: manifestJSON,\n            toolsVersion: toolsVersion,\n            packageKind: packageKind,\n            packagePath: packagePath,\n            identityResolver: identityResolver,\n            dependencyMapper: dependencyMapper,\n            fileSystem: fileSystem\n        )\n        delegateQueue?.async {\n            delegate?.didParse(\n                packageIdentity: packageIdentity,\n                packageLocation: packageLocation,\n                duration: start.distance(to: .now())\n            )\n        }\n        return result\n    }\n\n    private func loadAndCacheManifest(\n        at path: AbsolutePath,\n        toolsVersion: ToolsVersion,\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packageLocation: String,\n        packageVersion: Version?,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        delegate: Delegate?,\n        delegateQueue: DispatchQueue?\n    ) async throws -> ManifestJSONParser.Result {\n        let key = try CacheKey(\n            packageIdentity: packageIdentity,\n            packageLocation: packageLocation,\n            manifestPath: path,\n            toolsVersion: toolsVersion,\n            env: Environment.current.cachable,\n            swiftpmVersion: SwiftVersion.current.displayString,\n            extraManifestFlags: self.extraManifestFlags,\n            fileSystem: fileSystem\n        )\n\n        // try from in-memory cache\n        if self.useInMemoryCache, let parsedManifest = await self.memoryCacheActor.get(key: key) {\n            observabilityScope.emit(debug: \"loading manifest for '\\(packageIdentity)' v. \\(packageVersion?.description ?? \"unknown\") from memory cache\")\n            return parsedManifest\n        }\n\n        // initialize db cache\n        let dbCache = self.databaseCacheDir.map { cacheDir in\n            let path = Self.manifestCacheDBPath(cacheDir)\n            var configuration = SQLiteBackedCacheConfiguration()\n            // FIXME: expose as user-facing configuration\n            configuration.maxSizeInMegabytes = 100\n            configuration.truncateWhenFull = true\n            return SQLiteBackedCache<EvaluationResult>(\n                tableName: \"MANIFEST_CACHE\",\n                location: .path(path),\n                configuration: configuration\n            )\n        }\n        // Ensure dbCache is closed on exit\n        defer {\n            do {\n                try dbCache?.close()\n            } catch {\n                observabilityScope.emit(\n                    warning: \"failed closing manifest db cache\",\n                    underlyingError: error\n                )\n            }\n        }\n\n\n        do {\n            // try to get it from the cache\n            if let evaluationResult = try dbCache?.get(key: key.sha256Checksum), let manifestJSON = evaluationResult.manifestJSON, !manifestJSON.isEmpty {\n                observabilityScope.emit(debug: \"loading manifest for '\\(packageIdentity)' v. \\(packageVersion?.description ?? \"unknown\") from db cache\")\n                let parsedManifest = try self.parseManifest(\n                    evaluationResult,\n                    packageIdentity: packageIdentity,\n                    packageKind: packageKind,\n                    packagePath: path.parentDirectory,\n                    packageLocation: packageLocation,\n                    toolsVersion: toolsVersion,\n                    identityResolver: identityResolver,\n                    dependencyMapper: dependencyMapper,\n                    fileSystem: fileSystem,\n                    emitCompilerOutput: false,\n                    observabilityScope: observabilityScope,\n                    delegate: delegate,\n                    delegateQueue: delegateQueue // Pass the delegate queue\n                )\n                // Store in memory cache if enabled\n                if self.useInMemoryCache {\n                    await self.memoryCacheActor.set(key: key, value: parsedManifest)\n                }\n                return parsedManifest\n            }\n        } catch {\n            observabilityScope.emit(\n                warning: \"failed loading cached manifest for '\\(key.packageIdentity)'\",\n                underlyingError: error\n            )\n        }\n\n        // shells out and compiles the manifest, finally output a JSON\n        observabilityScope.emit(debug: \"evaluating manifest for '\\(packageIdentity)' v. \\(packageVersion?.description ?? \"unknown\")\")\n\n        let evaluationResult = try await self.evaluateManifest(\n            packageIdentity: key.packageIdentity,\n            packageLocation: packageLocation,\n            manifestPath: key.manifestPath,\n            manifestContents: key.manifestContents,\n            toolsVersion: key.toolsVersion,\n            observabilityScope: observabilityScope,\n            delegate: delegate,\n            delegateQueue: delegateQueue // Pass the delegate queue\n        )\n\n        // only cache successfully parsed manifests\n        let parsedManifest = try self.parseManifest(\n            evaluationResult,\n            packageIdentity: packageIdentity,\n            packageKind: packageKind,\n            packagePath: path.parentDirectory,\n            packageLocation: packageLocation,\n            toolsVersion: toolsVersion,\n            identityResolver: identityResolver,\n            dependencyMapper: dependencyMapper,\n            fileSystem: fileSystem,\n            emitCompilerOutput: true,\n            observabilityScope: observabilityScope,\n            delegate: delegate,\n            delegateQueue: delegateQueue\n        )\n\n        do {\n            // Store in memory cache\n            await self.memoryCacheActor.set(key: key, value: parsedManifest)\n            // Store in db cache\n            try dbCache?.put(key: key.sha256Checksum, value: evaluationResult, observabilityScope: observabilityScope)\n        } catch {\n            observabilityScope.emit(\n                warning: \"failed storing manifest for '\\(key.packageIdentity)' in cache\",\n                underlyingError: error\n            )\n        }\n\n        return parsedManifest\n    }\n\n    private func validateImports(\n        manifestPath: AbsolutePath,\n        toolsVersion: ToolsVersion\n    ) async throws {\n        // If there are no import restrictions, we do not need to validate.\n        guard let importRestrictions = self.importRestrictions, toolsVersion >= importRestrictions.startingToolsVersion else {\n            return\n        }\n\n        // Allowed are the expected defaults, plus anything allowed by the configured restrictions.\n        let allowedImports = [\n            \"PackageDescription\",\n            \"Swift\",\n            \"SwiftOnoneSupport\",\n            \"_SwiftConcurrencyShims\"\n        ] + importRestrictions.allowedImports\n\n        let importScanner = SwiftcImportScanner(\n            swiftCompilerEnvironment: self.toolchain.swiftCompilerEnvironment,\n            swiftCompilerFlags: self.extraManifestFlags,\n            swiftCompilerPath: self.toolchain.swiftCompilerPathForManifests\n        )\n        let result = try await importScanner.scanImports(manifestPath)\n\n        let imports = result.filter { !allowedImports.contains($0) }\n        guard imports.isEmpty else {\n            throw ManifestParseError.importsRestrictedModules(imports)\n        }\n    }\n\n    /// Compiler the manifest at the given path and retrieve the JSON.\n    fileprivate func evaluateManifest(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath,\n        manifestContents: [UInt8],\n        toolsVersion: ToolsVersion,\n        observabilityScope: ObservabilityScope,\n        delegate: Delegate?,\n        delegateQueue: DispatchQueue?\n    ) async throws -> EvaluationResult {\n        let manifestPreamble: ByteString\n        if toolsVersion >= .v5_8 {\n            manifestPreamble = ByteString()\n        } else {\n            manifestPreamble = ByteString(\"\\nimport Foundation\")\n        }\n\n        return try await Basics.withTemporaryDirectory(removeTreeOnDeinit: true) { tempDir in\n            let manifestTempFilePath = tempDir.appending(\"manifest.swift\")\n            // Since this isn't overwriting the original file, append Foundation library\n            // import to avoid having diagnostics being displayed on the incorrect line.\n            try localFileSystem.writeFileContents(manifestTempFilePath, bytes: ByteString(manifestContents + manifestPreamble.contents))\n\n            let vfsOverlayTempFilePath = tempDir.appending(\"vfs.yaml\")\n            try VFSOverlay(roots: [\n                VFSOverlay.File(\n                    name: manifestPath._normalized.replacing(#\"\\\"#, with: #\"\\\\\"#),\n                    externalContents: manifestTempFilePath._nativePathString(escaped: true)\n                )\n            ]).write(to: vfsOverlayTempFilePath, fileSystem: localFileSystem)\n\n            try await validateImports(\n                manifestPath: manifestTempFilePath,\n                toolsVersion: toolsVersion\n            )\n            let result = try await self.evaluateManifest(\n                at: manifestPath,\n                vfsOverlayPath: vfsOverlayTempFilePath,\n                packageIdentity: packageIdentity,\n                packageLocation: packageLocation,\n                toolsVersion: toolsVersion,\n                observabilityScope: observabilityScope,\n                delegate: delegate,\n                delegateQueue: delegateQueue\n            )\n\n            return result\n        }\n    }\n\n    /// Helper method for evaluating the manifest.\n    func evaluateManifest(\n        at manifestPath: AbsolutePath,\n        vfsOverlayPath: AbsolutePath? = nil,\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        toolsVersion: ToolsVersion,\n        observabilityScope: ObservabilityScope,\n        delegate: Delegate?,\n        delegateQueue: DispatchQueue?\n    ) async throws -> EvaluationResult {\n        // The compiler has special meaning for files with extensions like .ll, .bc etc.\n        // Assert that we only try to load files with extension .swift to avoid unexpected loading behavior.\n        guard manifestPath.extension == \"swift\" else {\n            throw InternalError(\"Manifest files must contain .swift suffix in their name, given: \\(manifestPath).\")\n        }\n\n        var evaluationResult = EvaluationResult()\n\n        // For now, we load the manifest by having Swift interpret it directly.\n        // Eventually, we should have two loading processes, one that loads only\n        // the declarative package specification using the Swift compiler directly\n        // and validates it.\n\n        // Compute the path to runtime we need to load.\n        let runtimePath = self.toolchain.swiftPMLibrariesLocation.manifestLibraryPath\n\n        // FIXME: Workaround for the module cache bug that's been haunting Swift CI\n        // <rdar://problem/48443680>\n        let moduleCachePath = try (\n            Environment.current[\"SWIFTPM_MODULECACHE_OVERRIDE\"] ??\n            Environment.current[\"SWIFTPM_TESTS_MODULECACHE\"]).flatMap { try AbsolutePath(validating: $0) }\n\n        var cmd: [String] = []\n        cmd += [self.toolchain.swiftCompilerPathForManifests.pathString]\n\n        if let vfsOverlayPath {\n            cmd += [\"-vfsoverlay\", vfsOverlayPath.pathString]\n        }\n\n        // if runtimePath is set to \"PackageFrameworks\" that means we could be developing SwiftPM in Xcode\n        // which produces a framework for dynamic package products.\n        if runtimePath.extension == \"framework\" {\n            cmd += [\n                \"-F\", runtimePath.parentDirectory.pathString,\n                \"-Xlinker\", \"-rpath\", \"-Xlinker\", runtimePath.parentDirectory.pathString,\n            ]\n\n            // Explicitly link `AppleProductTypes` since auto-linking won't work here.\n#if ENABLE_APPLE_PRODUCT_TYPES\n            cmd += [\"-framework\", \"AppleProductTypes\"]\n#else\n            cmd += [\"-framework\", \"PackageDescription\"]\n#endif\n        } else {\n            cmd += [\n                \"-L\", runtimePath.pathString,\n                \"-lPackageDescription\",\n            ]\n#if !os(Windows)\n            // -rpath argument is not supported on Windows,\n            // so we add runtimePath to PATH when executing the manifest instead\n            cmd += [\"-Xlinker\", \"-rpath\", \"-Xlinker\", runtimePath.pathString]\n#endif\n        }\n\n        // Use the same minimum deployment target as the PackageDescription library (with a fallback to the default host triple).\n#if os(macOS)\n        if let version = self.toolchain.swiftPMLibrariesLocation.manifestLibraryMinimumDeploymentTarget?.versionString {\n            cmd += [\"-target\", \"\\(self.toolchain.targetTriple.tripleString(forPlatformVersion: version))\"]\n        } else {\n            cmd += [\"-target\", self.toolchain.targetTriple.tripleString]\n        }\n#endif\n\n        // Add any extra flags required as indicated by the ManifestLoader.\n        cmd += self.toolchain.swiftCompilerFlags\n\n        cmd += self.interpreterFlags(for: toolsVersion)\n        if let moduleCachePath {\n            cmd += [\"-module-cache-path\", moduleCachePath.pathString]\n        }\n\n        // Add the arguments for emitting serialized diagnostics, if requested.\n        if self.serializedDiagnostics, let databaseCacheDir = self.databaseCacheDir {\n            let diaDir = databaseCacheDir.appending(\"ManifestLoading\")\n            let diagnosticFile = diaDir.appending(\"\\(packageIdentity).dia\")\n            try localFileSystem.createDirectory(diaDir, recursive: true)\n            cmd += [\"-Xfrontend\", \"-serialize-diagnostics-path\", \"-Xfrontend\", diagnosticFile.pathString]\n            evaluationResult.diagnosticFile = diagnosticFile\n        }\n\n        cmd += [manifestPath._normalized]\n\n        cmd += self.extraManifestFlags\n\n        // Compile the manifest in a temporary directory\n        return try await Basics.withTemporaryDirectory(removeTreeOnDeinit: true) { tmpDir in\n            // Set path to compiled manifest executable.\n            #if os(Windows)\n            let executableSuffix = \".exe\"\n            #else\n            let executableSuffix = \"\"\n            #endif\n            let compiledManifestFile = tmpDir.appending(\"\\(packageIdentity)-manifest\\(executableSuffix)\")\n            cmd += [\"-o\", compiledManifestFile.pathString]\n\n            evaluationResult.compilerCommandLine = cmd\n\n            delegateQueue?.async { [delegate = self.delegate] in\n                delegate?.willCompile(\n                    packageIdentity: packageIdentity,\n                    packageLocation: packageLocation,\n                    manifestPath: manifestPath\n                )\n            }\n            // Compile the manifest.\n            let compileStart = DispatchTime.now()\n            let compilerResult: AsyncProcessResult\n            do {\n                 compilerResult = try await AsyncProcess.popen(arguments: cmd, environment: self.toolchain.swiftCompilerEnvironment)\n                 evaluationResult.compilerOutput = try (compilerResult.utf8Output() + compilerResult.utf8stderrOutput()).spm_chuzzle()\n            } catch {\n                delegateQueue?.async { [delegate = self.delegate] in\n                    delegate?.didCompile(\n                        packageIdentity: packageIdentity,\n                        packageLocation: packageLocation,\n                        manifestPath: manifestPath,\n                        duration: compileStart.distance(to: .now())\n                    )\n                }\n                throw error // Re-throw process errors\n            }\n\n            delegateQueue?.async { [delegate = self.delegate] in\n                delegate?.didCompile(\n                    packageIdentity: packageIdentity,\n                    packageLocation: packageLocation,\n                    manifestPath: manifestPath,\n                    duration: compileStart.distance(to: .now())\n                )\n            }\n\n            // Return now if there was a compilation error.\n            if compilerResult.exitStatus != .terminated(code: 0) {\n                // If there's compiler output, it's a format error. Otherwise, maybe something else went wrong.\n                 evaluationResult.errorOutput = evaluationResult.compilerOutput ?? \"Manifest compilation failed with exit status \\(compilerResult.exitStatus)\"\n                 return evaluationResult // Return the result containing the error output\n            }\n\n            // Pass an open file descriptor of a file to which the JSON representation of the manifest will be written.\n            let jsonOutputFile = tmpDir.appending(\"\\(packageIdentity)-output.json\")\n            guard let jsonOutputFileDesc = fopen(jsonOutputFile.pathString, \"w\") else {\n                 throw StringError(\"couldn't create the manifest's JSON output file\")\n            }\n            // Ensure the file is closed\n            defer { fclose(jsonOutputFileDesc) }\n\n\n            var runCmd = [compiledManifestFile.pathString]\n            #if os(Windows)\n            // NOTE: `_get_osfhandle` returns a non-owning, unsafe,\n            // unretained HANDLE.  DO NOT invoke `CloseHandle` on `hFile`.\n            let hFile: Int = _get_osfhandle(_fileno(jsonOutputFileDesc))\n            runCmd += [\"-handle\", \"\\(String(hFile, radix: 16))\"]\n            #else\n            runCmd += [\"-fileno\", \"\\(fileno(jsonOutputFileDesc))\"]\n            #endif\n\n            do {\n                let packageDirectory = manifestPath.parentDirectory.pathString\n\n                let gitInformation: ContextModel.GitInformation?\n                do {\n                    let repo = GitRepository(path: manifestPath.parentDirectory)\n                    // These Git operations might block, consider making them async if performance is critical\n                    gitInformation = ContextModel.GitInformation(\n                        currentTag: repo.getCurrentTag(),\n                        currentCommit: try repo.getCurrentRevision().identifier,\n                        hasUncommittedChanges: repo.hasUncommittedChanges()\n                    )\n                } catch {\n                    // Ignore errors getting git info\n                    gitInformation = nil\n                }\n\n                let contextModel = ContextModel(\n                    packageDirectory: packageDirectory,\n                    gitInformation: gitInformation\n                )\n                runCmd += [\"-context\", try contextModel.encode()]\n            } catch {\n                throw error // Re-throw encoding errors\n            }\n\n            // If enabled, run command in a sandbox.\n            // This provides some safety against arbitrary code execution when parsing manifest files.\n            // We only allow the permissions which are absolutely necessary.\n            if self.isManifestSandboxEnabled {\n                let cacheDirectories = [self.databaseCacheDir?.appending(\"ManifestLoading\"), moduleCachePath].compactMap{ $0 }\n                let strictness: Sandbox.Strictness = toolsVersion < .v5_3 ? .manifest_pre_53 : .default\n                do {\n                    runCmd = try Sandbox.apply(command: runCmd, fileSystem: localFileSystem, strictness: strictness, writableDirectories: cacheDirectories)\n                } catch {\n                    throw error // Re-throw sandbox errors\n                }\n            }\n\n            // Run the compiled manifest.\n            let evaluationStart = DispatchTime.now()\n\n            delegateQueue?.async { [delegate = self.delegate] in\n                delegate?.willEvaluate(\n                    packageIdentity: packageIdentity,\n                    packageLocation: packageLocation,\n                    manifestPath: manifestPath\n                )\n            }\n\n            var environment = Environment.current\n            #if os(Windows)\n            let windowsPathComponent = runtimePath.pathString.replacing(\"/\", with: \"\\\\\")\n            environment.prependPath(key: .path, value: windowsPathComponent)\n            #endif\n\n            let runResult: AsyncProcessResult\n            do {\n                runResult = try await AsyncProcess.popen(arguments: runCmd, environment: environment)\n                if let runOutput = try (runResult.utf8Output() + runResult.utf8stderrOutput()).spm_chuzzle() {\n                    // Append the runtime output to any compiler output we've received.\n                    evaluationResult.compilerOutput = (evaluationResult.compilerOutput ?? \"\") + runOutput\n                }\n            } catch {\n                delegateQueue?.async { [delegate = self.delegate] in\n                    delegate?.didEvaluate(\n                        packageIdentity: packageIdentity,\n                        packageLocation: packageLocation,\n                        manifestPath: manifestPath,\n                        duration: evaluationStart.distance(to: .now())\n                    )\n                }\n                throw error // Re-throw process errors\n            }\n\n            delegateQueue?.async { [delegate = self.delegate] in\n                delegate?.didEvaluate(\n                    packageIdentity: packageIdentity,\n                    packageLocation: packageLocation,\n                    manifestPath: manifestPath,\n                    duration: evaluationStart.distance(to: .now())\n                )\n            }\n\n            // Return now if there was a runtime error.\n            if runResult.exitStatus != .terminated(code: 0) {\n                 // The runtime output is the error\n                 evaluationResult.errorOutput = evaluationResult.compilerOutput\n                 return evaluationResult // Return the result containing the error output\n            }\n\n            // Read the JSON output that was emitted by libPackageDescription.\n            let jsonOutput: String = try localFileSystem.readFileContents(jsonOutputFile)\n            evaluationResult.manifestJSON = jsonOutput\n\n            // withTemporaryDirectory handles cleanup automatically\n            return evaluationResult\n        }\n    }\n\n    package static func interpreterFlags(\n        for toolsVersion: ToolsVersion,\n        toolchain: some Toolchain\n    ) -> [String] {\n        var cmd = [String]()\n        let modulesPath = toolchain.swiftPMLibrariesLocation.manifestModulesPath\n        cmd += [\"-swift-version\", toolsVersion.swiftLanguageVersion.rawValue]\n        // if runtimePath is set to \"PackageFrameworks\" that means we could be developing SwiftPM in Xcode\n        // which produces a framework for dynamic package products.\n        if modulesPath.extension == \"framework\" {\n            cmd += [\"-I\", modulesPath.parentDirectory.parentDirectory.pathString]\n        } else {\n            cmd += [\"-I\", modulesPath.pathString]\n        }\n      #if os(macOS)\n        if let sdkRoot = toolchain.sdkRootPath {\n            cmd += [\"-sdk\", sdkRoot.pathString]\n        }\n      #endif\n        cmd += [\"-package-description-version\", toolsVersion.description]\n        return cmd\n    }\n\n    /// Returns the interpreter flags for a manifest.\n    public func interpreterFlags(\n        for toolsVersion: ToolsVersion\n    ) -> [String] {\n        return Self.interpreterFlags(for: toolsVersion, toolchain: toolchain)\n    }\n\n    /// Returns path to the manifest database inside the given cache directory.\n    private static func manifestCacheDBPath(_ cacheDir: AbsolutePath) -> AbsolutePath {\n        return cacheDir.appending(\"manifest.db\")\n    }\n\n    /// reset internal cache\n    public func resetCache(observabilityScope: ObservabilityScope) async {\n        await self.memoryCacheActor.clear()\n    }\n\n    /// reset internal state and purge shared cache\n    public func purgeCache(observabilityScope: ObservabilityScope) async {\n        await self.resetCache(observabilityScope: observabilityScope)\n\n        guard let manifestCacheDBPath = self.databaseCacheDir.flatMap({ Self.manifestCacheDBPath($0) }) else {\n            return\n        }\n\n        guard localFileSystem.exists(manifestCacheDBPath) else {\n            return\n        }\n\n        observabilityScope.emit(info: \"Purging manifest cache at '\\(manifestCacheDBPath)'\")\n\n        do {\n            try localFileSystem.removeFileTree(manifestCacheDBPath)\n        } catch {\n            observabilityScope.emit(\n                error: \"Error purging manifests cache at '\\(manifestCacheDBPath)'\",\n                underlyingError: error\n            )\n        }\n    }\n}\n\nextension ManifestLoader {\n    struct CacheKey: Hashable {\n        let packageIdentity: PackageIdentity\n        let manifestPath: AbsolutePath\n        let manifestContents: [UInt8]\n        let toolsVersion: ToolsVersion\n        let env: Environment\n        let swiftpmVersion: String\n        let sha256Checksum: String\n\n        init (packageIdentity: PackageIdentity,\n              packageLocation: String,\n              manifestPath: AbsolutePath,\n              toolsVersion: ToolsVersion,\n              env: Environment,\n              swiftpmVersion: String,\n              extraManifestFlags: [String],\n              fileSystem: FileSystem\n        ) throws {\n            let manifestContents = try fileSystem.readFileContents(manifestPath).contents\n            let sha256Checksum = try Self.computeSHA256Checksum(\n                packageIdentity: packageIdentity,\n                packageLocation: packageLocation,\n                manifestContents: manifestContents,\n                toolsVersion: toolsVersion,\n                env: env,\n                extraManifestFlags: extraManifestFlags,\n                swiftpmVersion: swiftpmVersion\n            )\n\n            self.packageIdentity = packageIdentity\n            self.manifestPath = manifestPath\n            self.manifestContents = manifestContents\n            self.toolsVersion = toolsVersion\n            self.env = env\n            self.swiftpmVersion = swiftpmVersion\n            self.sha256Checksum = sha256Checksum\n        }\n\n        func hash(into hasher: inout Hasher) {\n            hasher.combine(self.sha256Checksum)\n        }\n\n        private static func computeSHA256Checksum(\n            packageIdentity: PackageIdentity,\n            packageLocation: String,\n            manifestContents: [UInt8],\n            toolsVersion: ToolsVersion,\n            env: Environment,\n            extraManifestFlags: [String],\n            swiftpmVersion: String\n        ) throws -> String {\n            let stream = BufferedOutputByteStream()\n            stream.send(packageIdentity)\n            stream.send(packageLocation)\n            stream.send(manifestContents)\n            stream.send(toolsVersion.description)\n            for (key, value) in env.sorted(by: { $0.key > $1.key }) {\n                stream.send(key.rawValue).send(value)\n            }\n            stream.send(swiftpmVersion)\n            for flag in extraManifestFlags {\n                stream.send(flag)\n            }\n            return stream.bytes.sha256Checksum\n        }\n    }\n}\n\nextension ManifestLoader {\n    struct EvaluationResult: Codable {\n        /// The path to the diagnostics file (.dia).\n        ///\n        /// This is only present if serialized diagnostics are enabled.\n        var diagnosticFile: AbsolutePath?\n\n        /// The output from compiler, if any.\n        ///\n        /// This would contain the errors and warnings produced when loading the manifest file.\n        var compilerOutput: String?\n\n        /// The manifest in JSON format.\n        var manifestJSON: String?\n\n        /// The command line used to compile the manifest\n        var compilerCommandLine: [String]?\n\n        /// Any non-compiler error that might have occurred during manifest loading.\n        ///\n        /// For e.g., we could have failed to spawn the process or create temporary file.\n        var errorOutput: String? {\n            didSet {\n                assert(self.manifestJSON == nil)\n            }\n        }\n\n        var hasErrors: Bool {\n            return self.manifestJSON == nil\n        }\n    }\n}\n\nextension ManifestLoader {\n    /// Represents behavior that can be deferred until a more appropriate time.\n    struct DelayableAction<T> {\n        var target: T?\n        var action: ((T) -> Void)?\n\n        func perform() {\n            if let value = target, let cleanup = action {\n                cleanup(value)\n            }\n        }\n\n        mutating func delay() -> DelayableAction {\n            let next = DelayableAction(target: target, action: action)\n            target = nil\n            action = nil\n            return next\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/ManifestSignatureParser.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport struct Foundation.Data\n\npublic enum ManifestSignatureParser {\n    public static func parse(manifestPath: AbsolutePath, fileSystem: FileSystem) throws -> ManifestSignature? {\n        let manifestContents: String\n        do {\n            manifestContents = try fileSystem.readFileContents(manifestPath)\n        } catch {\n            throw Error.inaccessibleManifest(path: manifestPath, reason: String(describing: error))\n        }\n        return try self.parse(utf8String: manifestContents)\n    }\n\n    public static func parse(utf8String: String) throws -> ManifestSignature? {\n        let manifestComponents = Self.split(utf8String)\n\n        guard let signatureComponents = manifestComponents.signatureComponents else {\n            return .none\n        }\n\n        guard let signature = Data(base64Encoded: String(signatureComponents.signatureBase64Encoded)) else {\n            throw Error.malformedManifestSignature\n        }\n\n        return ManifestSignature(\n            contents: Array(String(manifestComponents.contentsBeforeSignatureComponents).utf8),\n            signatureFormat: String(signatureComponents.signatureFormat),\n            signature: Array(signature)\n        )\n    }\n\n    /// Splits the given manifest into its constituent components.\n    ///\n    /// A **signed** manifest consists of the following parts:\n    ///\n    ///                                                    ⎫\n    ///                                                    ┇\n    ///                                                    ⎬ manifest's contents (returned by this function)\n    ///                                                    ┇\n    ///                                                    ⎭\n    ///       ┌ manifest signature\n    ///       ⌄~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n    ///       //  signature:  cms-1.0.0;MIIFujCCBKKgAw...  } the manifest signature line\n    ///     ⌃~⌃~⌃~⌃~~~~~~~~~⌃~⌃~~~~~~~~^^~~~~~~~~~~~~~~~~\n    ///     | | | |         | |        |└ signature base64-encoded (returned by this function)\n    ///     | │ │ └ label   │ |        └ signature format terminator\n    ///     | | |           | └ signature format (returned by this function)\n    ///     | │ └ spacing   └ spacing\n    ///     | └ comment marker\n    ///     └ additional leading whitespace\n    ///\n    /// - Parameter manifest: The UTF-8-encoded content of the manifest.\n    /// - Returns: The components of the given manifest.\n    private static func split(_ manifest: String) -> ManifestComponents {\n        // The signature, if any, is the last line in the manifest.\n        let endIndexOfSignatureLine = manifest.lastIndex(where: { !$0.isWhitespace }) ?? manifest.endIndex\n        let endIndexOfManifestContents = manifest[..<endIndexOfSignatureLine]\n            .lastIndex(where: { $0.isNewline }) ?? manifest.endIndex\n        let startIndexOfCommentMarker = manifest[endIndexOfManifestContents...]\n            .firstIndex(where: { $0 == \"/\" }) ?? manifest.endIndex\n\n        // There doesn't seem to be a signature, return manifest as-is.\n        guard startIndexOfCommentMarker < endIndexOfSignatureLine else {\n            return ManifestComponents(contentsBeforeSignatureComponents: manifest[...], signatureComponents: .none)\n        }\n\n        let endIndexOfCommentMarker = manifest[startIndexOfCommentMarker...]\n            .firstIndex(where: { $0 != \"/\" }) ?? manifest.endIndex\n\n        let startIndexOfLabel = manifest[endIndexOfCommentMarker...].firstIndex(where: { !$0.isWhitespace }) ?? manifest\n            .endIndex\n        let endIndexOfLabel = manifest[startIndexOfLabel...].firstIndex(where: { $0 == \":\" }) ?? manifest.endIndex\n\n        // Missing \"signature:\" label, assume there is no signature.\n        guard startIndexOfLabel < endIndexOfLabel,\n              String(manifest[startIndexOfLabel ..< endIndexOfLabel]).lowercased() == \"signature\"\n        else {\n            return ManifestComponents(contentsBeforeSignatureComponents: manifest[...], signatureComponents: .none)\n        }\n\n        let startIndexOfSignatureFormat = manifest[endIndexOfLabel...]\n            .firstIndex(where: { $0 != \":\" && !$0.isWhitespace }) ?? manifest.endIndex\n        let endIndexOfSignatureFormat = manifest[startIndexOfSignatureFormat...]\n            .firstIndex(where: { $0 == \";\" }) ?? manifest.endIndex\n\n        // Missing signature format, assume there is no signature.\n        guard startIndexOfSignatureFormat < endIndexOfSignatureFormat else {\n            return ManifestComponents(contentsBeforeSignatureComponents: manifest[...], signatureComponents: .none)\n        }\n\n        let startIndexOfSignatureBase64Encoded = manifest[endIndexOfSignatureFormat...]\n            .firstIndex(where: { $0 != \";\" }) ?? manifest.endIndex\n\n        // Missing base64-encoded signature, assume there is no signature.\n        guard startIndexOfSignatureBase64Encoded < endIndexOfSignatureLine else {\n            return ManifestComponents(contentsBeforeSignatureComponents: manifest[...], signatureComponents: .none)\n        }\n\n        return ManifestComponents(\n            contentsBeforeSignatureComponents: manifest[..<endIndexOfManifestContents],\n            signatureComponents: SignatureComponents(\n                signatureFormat: manifest[startIndexOfSignatureFormat ..< endIndexOfSignatureFormat],\n                signatureBase64Encoded: manifest[startIndexOfSignatureBase64Encoded ... endIndexOfSignatureLine]\n            )\n        )\n    }\n\n    public struct ManifestSignature {\n        public let contents: [UInt8]\n        public let signatureFormat: String\n        public let signature: [UInt8]\n    }\n\n    public enum Error: Swift.Error {\n        /// Package manifest file is inaccessible (missing, unreadable, etc).\n        case inaccessibleManifest(path: AbsolutePath, reason: String)\n        /// Malformed manifest signature.\n        case malformedManifestSignature\n    }\n}\n\nextension ManifestSignatureParser {\n    /// A representation of a manifest in its constituent parts.\n    public struct ManifestComponents {\n        /// The contents of the manifest up to the signature line.\n        /// A manifest doesn't have to be signed so this can be the entire manifest contents.\n        public let contentsBeforeSignatureComponents: Substring\n        /// The manifest signature (if any) represented in its constituent parts.\n        public let signatureComponents: SignatureComponents?\n    }\n\n    /// A representation of manifest signature in its constituent parts.\n    ///\n    /// A manifest signature consists of the following parts:\n    ///\n    ///     //  signature:  cms-1.0.0;MIIFujCCBKKgAwIBAgIBATANBgkqhkiG9w0BAQUFAD...\n    ///     ⌃~⌃~⌃~~~~~~~~~⌃~⌃~~~~~~~~^^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n    ///     | | |         | |        |└ signature base64-encoded\n    ///     │ │ └ label   │ |        └ signature format terminator\n    ///     | |           | └ signature format\n    ///     │ └ spacing   └ spacing\n    ///     └ comment marker\n    ///\n    public struct SignatureComponents {\n        /// The signature format.\n        public let signatureFormat: Substring\n\n        /// The base64-encoded signature.\n        public let signatureBase64Encoded: Substring\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/ModuleMapGenerator.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\nimport TSCBasic\n\n/// Name of the module map file recognized by the Clang and Swift compilers.\npublic let moduleMapFilename = \"module.modulemap\"\n\n/// A protocol for targets which might have a modulemap.\nprotocol ModuleMapProtocol {\n    var moduleMapPath: Basics.AbsolutePath { get }\n\n    var moduleMapDirectory: Basics.AbsolutePath { get }\n}\n\nextension SystemLibraryModule: ModuleMapProtocol {\n    var moduleMapDirectory: Basics.AbsolutePath {\n        return path\n    }\n\n    public var moduleMapPath: Basics.AbsolutePath {\n        return moduleMapDirectory.appending(component: moduleMapFilename)\n    }\n}\n\nextension ClangModule: ModuleMapProtocol {\n    var moduleMapDirectory: Basics.AbsolutePath {\n        return includeDir\n    }\n\n    public var moduleMapPath: Basics.AbsolutePath {\n        return moduleMapDirectory.appending(component: moduleMapFilename)\n    }\n}\n\n/// A module map generator for Clang targets.  Module map generation consists of two steps:\n/// 1. Examining a module's public-headers directory to determine the appropriate module map type\n/// 2. Generating a module map for any module that doesn't have a custom module map file\n///\n/// When a custom module map exists in the header directory, it is used as-is.  When a custom module map does not exist, a module map is generated based on the following rules:\n///\n/// *  If \"include/foo/foo.h\" exists and `foo` is the only directory under the \"include\" directory, and the \"include\" directory contains no header files:\n///    Generates: `umbrella header \"/path/to/include/foo/foo.h\"`\n/// *  If \"include/foo.h\" exists and \"include\" contains no other subdirectory:\n///    Generates: `umbrella header \"/path/to/include/foo.h\"`\n/// *  Otherwise, if the \"include\" directory only contains header files and no other subdirectory:\n///    Generates: `umbrella \"path/to/include\"`\n///\n/// These rules are documented at https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/Usage.md#creating-c-language-targets.  To avoid breaking existing packages, do not change the semantics here without making any change conditional on the tools version of the package that defines the module.\n///\n/// Note that a module map generator doesn't require a module to already have been instantiated; it can operate on information that will later be used to instantiate a module.\npublic struct ModuleMapGenerator {\n\n    /// The name of the Clang target (for diagnostics).\n    private let targetName: String\n\n    /// The module name of the target.\n    private let moduleName: String\n\n    /// The target's public-headers directory.\n    private let publicHeadersDir: Basics.AbsolutePath\n\n    /// The file system to be used.\n    private let fileSystem: FileSystem\n\n    public init(targetName: String, moduleName: String, publicHeadersDir: Basics.AbsolutePath, fileSystem: FileSystem) {\n        self.targetName = targetName\n        self.moduleName = moduleName\n        self.publicHeadersDir = publicHeadersDir\n        self.fileSystem = fileSystem\n    }\n\n    /// Inspects the file system at the public-headers directory with which the module map generator was instantiated, and returns the type of module map that applies to that directory.  This function contains all of the heuristics that implement module map policy for package targets; other functions just use the results of this determination.\n    public func determineModuleMapType(observabilityScope: ObservabilityScope) -> ModuleMapType {\n        // The following rules are documented at https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/Usage.md#creating-c-language-targets.  To avoid breaking existing packages, do not change the semantics here without making any change conditional on the tools version of the package that defines the module.\n\n        let diagnosticsEmitter = observabilityScope.makeDiagnosticsEmitter {\n            var metadata = ObservabilityMetadata()\n            metadata.moduleName = self.targetName\n            return metadata\n        }\n\n        // First check for a custom module map.\n        let customModuleMapFile = publicHeadersDir.appending(component: moduleMapFilename)\n        if fileSystem.isFile(customModuleMapFile) {\n            return .custom(customModuleMapFile)\n        }\n\n        // Warn if the public-headers directory is missing.  For backward compatibility reasons, this is not an error, we just won't generate a module map in that case.\n        guard fileSystem.exists(publicHeadersDir) else {\n            diagnosticsEmitter.emit(.missingPublicHeadersDirectory(targetName: targetName, publicHeadersDir: publicHeadersDir))\n            return .none\n        }\n\n        // Next try to get the entries in the public-headers directory.\n        let entries: Set<Basics.AbsolutePath>\n        do {\n            entries = try Set(fileSystem.getDirectoryContents(publicHeadersDir).map({ publicHeadersDir.appending(component: $0) }))\n        }\n        catch {\n            // This might fail because of a file system error, etc.\n            diagnosticsEmitter.emit(.inaccessiblePublicHeadersDirectory(targetName: targetName, publicHeadersDir: publicHeadersDir, fileSystemError: error))\n            return .none\n        }\n\n        // Filter out headers and directories at the top level of the public-headers directory.\n        // FIXME: What about .hh files, or .hpp, etc?  We should centralize the detection of file types based on names (and ideally share with SwiftDriver).\n        let headers = entries.filter({ fileSystem.isFile($0) && $0.suffix == \".h\" })\n        let directories = entries.filter({ fileSystem.isDirectory($0) })\n\n        // If 'PublicHeadersDir/ModuleName.h' exists, then use it as the umbrella header.\n        let umbrellaHeader = publicHeadersDir.appending(component: moduleName + \".h\")\n        if fileSystem.isFile(umbrellaHeader) {\n            // In this case, 'PublicHeadersDir' is expected to contain no subdirectories.\n            if directories.count != 0 {\n                diagnosticsEmitter.emit(.umbrellaHeaderHasSiblingDirectories(targetName: targetName, umbrellaHeader: umbrellaHeader, siblingDirs: directories))\n                return .none\n            }\n            return .umbrellaHeader(umbrellaHeader)\n        }\n\n        /// Check for the common mistake of naming the umbrella header 'TargetName.h' instead of 'ModuleName.h'.\n        let misnamedUmbrellaHeader = publicHeadersDir.appending(component: targetName + \".h\")\n        if fileSystem.isFile(misnamedUmbrellaHeader) {\n            diagnosticsEmitter.emit(.misnamedUmbrellaHeader(misnamedUmbrellaHeader: misnamedUmbrellaHeader, umbrellaHeader: umbrellaHeader))\n        }\n\n        // If 'PublicHeadersDir/ModuleName/ModuleName.h' exists, then use it as the umbrella header.\n        let nestedUmbrellaHeader = publicHeadersDir.appending(components: moduleName, moduleName + \".h\")\n        if fileSystem.isFile(nestedUmbrellaHeader) {\n            // In this case, 'PublicHeadersDir' is expected to contain no subdirectories other than 'ModuleName'.\n            if directories.count != 1 {\n                diagnosticsEmitter.emit(.umbrellaHeaderParentDirHasSiblingDirectories(targetName: targetName, umbrellaHeader: nestedUmbrellaHeader, siblingDirs: directories.filter{ $0.basename != moduleName }))\n                return .none\n            }\n            // In this case, 'PublicHeadersDir' is also expected to contain no header files.\n            if headers.count != 0 {\n                diagnosticsEmitter.emit(.umbrellaHeaderParentDirHasSiblingHeaders(targetName: targetName, umbrellaHeader: nestedUmbrellaHeader, siblingHeaders: headers))\n                return .none\n            }\n            return .umbrellaHeader(nestedUmbrellaHeader)\n        }\n\n        /// Check for the common mistake of naming the nested umbrella header 'TargetName.h' instead of 'ModuleName.h'.\n        let misnamedNestedUmbrellaHeader = publicHeadersDir.appending(components: moduleName, targetName + \".h\")\n        if fileSystem.isFile(misnamedNestedUmbrellaHeader) {\n            diagnosticsEmitter.emit(.misnamedUmbrellaHeader(misnamedUmbrellaHeader: misnamedNestedUmbrellaHeader, umbrellaHeader: nestedUmbrellaHeader))\n        }\n\n        // Otherwise, if 'PublicHeadersDir' contains only header files and no subdirectories, use it as the umbrella directory.\n        if headers.count == entries.count {\n            return .umbrellaDirectory(publicHeadersDir)\n        }\n\n        // Otherwise, the module's public headers are considered to be incompatible with modules.  Per the original design, though, an umbrella directory is still created for them.  This will lead to build failures if those headers are included and they are not compatible with modules.  A future evolution proposal should revisit these semantics, especially to make it easier to existing wrap C source bases that are incompatible with modules.\n        return .umbrellaDirectory(publicHeadersDir)\n    }\n\n    /// Generates a module map based of the specified type, throwing an error if anything goes wrong.  Any diagnostics are added to the receiver's diagnostics engine.\n    public func generateModuleMap(type: GeneratedModuleMapType, at path: Basics.AbsolutePath) throws {\n        var moduleMap = \"module \\(moduleName) {\\n\"\n        switch type {\n        case .umbrellaHeader(let hdr):\n            moduleMap.append(\"    umbrella header \\\"\\(hdr.escapedPathString)\\\"\\n\")\n        case .umbrellaDirectory(let dir):\n            moduleMap.append(\"    umbrella \\\"\\(dir.escapedPathString)\\\"\\n\")\n        }\n        moduleMap.append(\n            \"\"\"\n                export *\n            }\n\n            \"\"\"\n        )\n\n        // FIXME: This doesn't belong here.\n        try fileSystem.createDirectory(path.parentDirectory, recursive: true)\n\n        // If the file exists with the identical contents, we don't need to rewrite it.\n        // Otherwise, compiler will recompile even if nothing else has changed.\n        if let contents = try? fileSystem.readFileContents(path).validDescription, contents == moduleMap {\n            return\n        }\n        try fileSystem.writeFileContents(path, string: moduleMap)\n    }\n}\n\n\n/// A type of module map to generate.\npublic enum GeneratedModuleMapType {\n    case umbrellaHeader(Basics.AbsolutePath)\n    case umbrellaDirectory(Basics.AbsolutePath)\n}\n\npublic extension ModuleMapType {\n    /// Returns the type of module map to generate for this kind of module map, or nil to not generate one at all.\n    var generatedModuleMapType: GeneratedModuleMapType? {\n        switch self {\n        case .umbrellaHeader(let path): return .umbrellaHeader(path)\n        case .umbrellaDirectory(let path): return .umbrellaDirectory(path)\n        case .none, .custom(_): return nil\n        }\n    }\n}\n\nprivate extension Basics.Diagnostic {\n\n    /// Warning emitted if the public-headers directory is missing.\n    static func missingPublicHeadersDirectory(targetName: String, publicHeadersDir: Basics.AbsolutePath) -> Self {\n        .warning(\"no include directory found for target '\\(targetName)'; libraries cannot be imported without public headers\")\n    }\n\n    /// Error emitted if the public-headers directory is inaccessible.\n    static func inaccessiblePublicHeadersDirectory(targetName: String, publicHeadersDir: Basics.AbsolutePath, fileSystemError: Error) -> Self {\n        .error(\"cannot access public-headers directory for target '\\(targetName)': \\(String(describing: fileSystemError))\")\n    }\n\n    /// Warning emitted if a misnamed umbrella header was found.\n    static func misnamedUmbrellaHeader(misnamedUmbrellaHeader: Basics.AbsolutePath, umbrellaHeader: Basics.AbsolutePath) -> Self {\n        .warning(\"\\(misnamedUmbrellaHeader) should be renamed to \\(umbrellaHeader) to be used as an umbrella header\")\n    }\n\n    /// Error emitted if there are directories next to a top-level umbrella header.\n    static func umbrellaHeaderHasSiblingDirectories(targetName: String, umbrellaHeader: Basics.AbsolutePath, siblingDirs: Set<Basics.AbsolutePath>) -> Self {\n        .error(\"target '\\(targetName)' has invalid header layout: umbrella header found at '\\(umbrellaHeader)', but directories exist next to it: \\(siblingDirs.map({ String(describing: $0) }).sorted().joined(separator: \", \")); consider removing them\")\n    }\n\n    /// Error emitted if there are other directories next to the parent directory of a nested umbrella header.\n    static func umbrellaHeaderParentDirHasSiblingDirectories(targetName: String, umbrellaHeader: Basics.AbsolutePath, siblingDirs: Set<Basics.AbsolutePath>) -> Self {\n        .error(\"target '\\(targetName)' has invalid header layout: umbrella header found at '\\(umbrellaHeader)', but more than one directory exists next to its parent directory: \\(siblingDirs.map({ String(describing: $0) }).sorted().joined(separator: \", \")); consider reducing them to one\")\n    }\n\n    /// Error emitted if there are other headers next to the parent directory of a nested umbrella header.\n    static func umbrellaHeaderParentDirHasSiblingHeaders(targetName: String, umbrellaHeader: Basics.AbsolutePath, siblingHeaders: Set<Basics.AbsolutePath>) -> Self {\n        .error(\"target '\\(targetName)' has invalid header layout: umbrella header found at '\\(umbrellaHeader)', but additional header files exist: \\((siblingHeaders.map({ String(describing: $0) }).sorted().joined(separator: \", \"))); consider reducing them to one\")\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/PackageBuilder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport OrderedCollections\nimport PackageModel\nimport Foundation\nimport TSCUtility\n\nimport func TSCBasic.findCycle\nimport struct TSCBasic.KeyedPair\nimport func TSCBasic.topologicalSort\n\n/// An error in the structure or layout of a package.\npublic enum ModuleError: Swift.Error {\n    /// Describes a way in which a package layout is invalid.\n    public enum InvalidLayoutType {\n        case multipleSourceRoots([AbsolutePath])\n        case modulemapInSources(AbsolutePath)\n        case modulemapMissing(AbsolutePath)\n    }\n\n    /// Indicates two targets with the same name and their corresponding packages.\n    case duplicateModule(moduleName: String, packages: [PackageIdentity])\n\n    /// The referenced target could not be found.\n    case moduleNotFound(String, TargetDescription.TargetKind, shouldSuggestRelaxedSourceDir: Bool)\n\n    /// The artifact for the binary target could not be found.\n    case artifactNotFound(moduleName: String, expectedArtifactName: String)\n\n    /// Invalid module alias.\n    case invalidModuleAlias(originalName: String, newName: String)\n\n    /// Invalid custom path.\n    case invalidCustomPath(moduleName: String, path: String)\n\n    /// Package layout is invalid.\n    case invalidLayout(InvalidLayoutType)\n\n    /// The manifest has invalid configuration wrt type of the target.\n    case invalidManifestConfig(String, String)\n\n    /// The target dependency declaration has cycle in it.\n    case cycleDetected((path: [String], cycle: [String]))\n\n    /// The public headers directory is at an invalid path.\n    case invalidPublicHeadersDirectory(String)\n\n    /// The sources of a target are overlapping with another target.\n    case overlappingSources(target: String, sources: [AbsolutePath])\n\n    /// We found multiple test entry point files.\n    case multipleTestEntryPointFilesFound(package: String, files: [AbsolutePath])\n\n    /// The tools version in use is not compatible with target's sources.\n    case incompatibleToolsVersions(package: String, required: [SwiftLanguageVersion], current: ToolsVersion)\n\n    /// The target path is outside the package.\n    case targetOutsidePackage(package: String, target: String)\n\n    /// Unsupported target path\n    case unsupportedTargetPath(String)\n\n    /// Invalid header search path.\n    case invalidHeaderSearchPath(String)\n\n    /// Default localization not set in the presence of localized resources.\n    case defaultLocalizationNotSet\n\n    /// A plugin target didn't declare a capability.\n    case pluginCapabilityNotDeclared(target: String)\n\n    /// A C target has declared an embedded resource\n    case embedInCodeNotSupported(target: String)\n\n    /// Indicates several targets with the same name exist in packages\n    case duplicateModules(package: PackageIdentity, otherPackage: PackageIdentity, modules: [String])\n\n    /// Indicates several targets with the same name exist in a registry and scm package\n    case duplicateModulesScmAndRegistry(\n        registryPackage: PackageIdentity.RegistryIdentity,\n        scmPackage: PackageIdentity,\n        modules: [String]\n    )\n\n    /// Indicates that an invalid trait was enabled.\n    case invalidTrait(\n        package: PackageIdentity,\n        trait: String\n    )\n    \n    case disablingDefaultTraitsOnEmptyTraits(\n        parentPackage: PackageIdentity,\n        packageName: String\n    )\n}\n\nextension ModuleError: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .duplicateModule(let target, let packages):\n            let packages = packages.map(\\.description).sorted().joined(separator: \"', '\")\n            return \"multiple packages ('\\(packages)') declare targets with a conflicting name: '\\(target)’; target names need to be unique across the package graph\"\n        case .moduleNotFound(let target, let type, let shouldSuggestRelaxedSourceDir):\n            let folderName = (type == .test) ? \"Tests\" : (type == .plugin) ? \"Plugins\" : \"Sources\"\n            var clauses = [\"Source files for target \\(target) should be located under '\\(folderName)/\\(target)'\"]\n            if shouldSuggestRelaxedSourceDir {\n                clauses.append(\"'\\(folderName)'\")\n            }\n            clauses.append(\"or a custom sources path can be set with the 'path' property in Package.swift\")\n            return clauses.joined(separator: \", \")\n        case .artifactNotFound(let targetName, let expectedArtifactName):\n            return \"binary target '\\(targetName)' could not be mapped to an artifact with expected name '\\(expectedArtifactName)'\"\n        case .invalidModuleAlias(let originalName, let newName):\n            return \"empty or invalid module alias; ['\\(originalName)': '\\(newName)']\"\n        case .invalidLayout(let type):\n            return \"package has unsupported layout; \\(type)\"\n        case .invalidManifestConfig(let package, let message):\n            return \"configuration of package '\\(package)' is invalid; \\(message)\"\n        case .cycleDetected(let cycle):\n            return \"cyclic dependency declaration found: \" +\n                (cycle.path + cycle.cycle).joined(separator: \" -> \") +\n                \" -> \" + cycle.cycle[0]\n        case .invalidPublicHeadersDirectory(let name):\n            return \"public headers (\\\"include\\\") directory path for '\\(name)' is invalid or not contained in the target\"\n        case .overlappingSources(let target, let sources):\n            return \"target '\\(target)' has overlapping sources: \" +\n                sources.map(\\.description).joined(separator: \", \")\n        case .multipleTestEntryPointFilesFound(let package, let files):\n            return \"package '\\(package)' has multiple test entry point files: \" +\n                files.map(\\.description).sorted().joined(separator: \", \")\n        case .incompatibleToolsVersions(let package, let required, let current):\n            if required.isEmpty {\n                return \"package '\\(package)' supported Swift language versions is empty\"\n            }\n            return \"package '\\(package)' requires minimum Swift language version \\(required[0]) which is not supported by the current tools version (\\(current))\"\n        case .targetOutsidePackage(let package, let target):\n            return \"target '\\(target)' in package '\\(package)' is outside the package root\"\n        case .unsupportedTargetPath(let targetPath):\n            return \"target path '\\(targetPath)' is not supported; it should be relative to package root\"\n        case .invalidCustomPath(let target, let path):\n            return \"invalid custom path '\\(path)' for target '\\(target)'\"\n        case .invalidHeaderSearchPath(let path):\n            return \"invalid header search path '\\(path)'; header search path should not be outside the package root\"\n        case .defaultLocalizationNotSet:\n            return \"manifest property 'defaultLocalization' not set; it is required in the presence of localized resources\"\n        case .pluginCapabilityNotDeclared(let target):\n            return \"plugin target '\\(target)' doesn't have a 'capability' property\"\n        case .embedInCodeNotSupported(let target):\n            return \"embedding resources in code not supported for C-family language target \\(target)\"\n        case .duplicateModules(let package, let otherPackage, let targets):\n            var targetsDescription = \"'\\(targets.sorted().prefix(3).joined(separator: \"', '\"))'\"\n            if targets.count > 3 {\n                targetsDescription += \" and \\(targets.count - 3) others\"\n            }\n            return \"\"\"\n            multiple similar targets \\(targetsDescription) appear in package '\\(package)' and '\\(otherPackage)', \\\n            this may indicate that the two packages are the same and can be de-duplicated by using mirrors. \\\n            if they are not duplicate consider using the `moduleAliases` parameter in manifest to provide unique names\n            \"\"\"\n        case .duplicateModulesScmAndRegistry(let registryPackage, let scmPackage, let targets):\n            var targetsDescription = \"'\\(targets.sorted().prefix(3).joined(separator: \"', '\"))'\"\n            if targets.count > 3 {\n                targetsDescription += \" and \\(targets.count - 3) others\"\n            }\n            return \"\"\"\n            multiple similar targets \\(targetsDescription) appear in registry package '\\(\n                registryPackage\n            )' and source control package '\\(scmPackage)', \\\n            this may indicate that the two packages are the same and can be de-duplicated \\\n            by activating the automatic source-control to registry replacement, or by using mirrors. \\\n            if they are not duplicate consider using the `moduleAliases` parameter in manifest to provide unique names\n            \"\"\"\n        case .invalidTrait(let package, let trait):\n            return \"\"\"\n            Trait '\"\\(trait)\"' is not declared by package '\\(package)'.\n            \"\"\"\n        case .disablingDefaultTraitsOnEmptyTraits(let parentPackage, let packageName):\n            return \"\"\"\n            Disabled default traits by package '\\(parentPackage)' on package '\\(packageName)' that declares no traits. This is prohibited to allow packages to adopt traits initially without causing an API break.\n            \"\"\"\n        }\n    }\n}\n\nextension ModuleError.InvalidLayoutType: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .multipleSourceRoots(let paths):\n            \"multiple source roots found: \" + paths.map(\\.description).sorted().joined(separator: \", \")\n        case .modulemapInSources(let path):\n            \"modulemap '\\(path)' should be inside the 'include' directory\"\n        case .modulemapMissing(let path):\n            \"missing system target module map at '\\(path)'\"\n        }\n    }\n}\n\nextension Module {\n    /// An error in the organization or configuration of an individual target.\n    enum Error: Swift.Error {\n        /// The target's name is invalid.\n        case invalidName(path: RelativePath, problem: ModuleNameProblem)\n        enum ModuleNameProblem {\n            /// Empty target name.\n            case emptyName\n        }\n\n        /// The target contains an invalid mix of languages (e.g. both Swift and C).\n        case mixedSources(AbsolutePath)\n    }\n}\n\nextension Module.Error: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .invalidName(let path, let problem):\n            \"invalid target name at '\\(path)'; \\(problem)\"\n        case .mixedSources(let path):\n            \"target at '\\(path)' contains mixed language source files; feature not supported\"\n        }\n    }\n}\n\nextension Module.Error.ModuleNameProblem: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .emptyName:\n            \"target names can not be empty\"\n        }\n    }\n}\n\nextension Product {\n    /// An error in a product definition.\n    enum Error: Swift.Error {\n        case emptyName\n        case moduleEmpty(product: String, target: String)\n    }\n}\n\nextension Product.Error: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .emptyName:\n            \"product names can not be empty\"\n        case .moduleEmpty(let product, let target):\n            \"target '\\(target)' referenced in product '\\(product)' is empty\"\n        }\n    }\n}\n\n/// A structure representing the remote artifact information necessary to construct the package.\npublic struct BinaryArtifact {\n    /// The kind of the artifact.\n    public let kind: BinaryModule.Kind\n\n    /// The URL the artifact was downloaded from.\n    public let originURL: String?\n\n    /// The path to the  artifact.\n    public let path: AbsolutePath\n\n    public init(kind: BinaryModule.Kind, originURL: String?, path: AbsolutePath) {\n        self.kind = kind\n        self.originURL = originURL\n        self.path = path\n    }\n}\n\n/// Helper for constructing a package following the convention system.\n///\n/// The 'builder' here refers to the builder pattern and not any build system\n/// related function.\npublic final class PackageBuilder {\n    /// Predefined source directories, in order of preference.\n    public static let predefinedSourceDirectories = [\"Sources\", \"Source\", \"src\", \"srcs\"]\n    /// Predefined test directories, in order of preference.\n    public static let predefinedTestDirectories = [\"Tests\", \"Sources\", \"Source\", \"src\", \"srcs\"]\n    /// Predefined plugin directories, in order of preference.\n    public static let predefinedPluginDirectories = [\"Plugins\"]\n\n    /// The identity for the package being constructed.\n    private let identity: PackageIdentity\n\n    /// The manifest for the package being constructed.\n    private let manifest: Manifest\n\n    /// The product filter to apply to the package.\n    private let productFilter: ProductFilter\n\n    /// The path of the package.\n    private let packagePath: AbsolutePath\n\n    /// Information concerning the different downloaded or local (archived) binary target artifacts.\n    private let binaryArtifacts: [String: BinaryArtifact]\n\n    /// Create multiple test products.\n    ///\n    /// If set to true, one test product will be created for each test target.\n    private let shouldCreateMultipleTestProducts: Bool\n\n    /// Path to test entry point file, if specified explicitly.\n    private let testEntryPointPath: AbsolutePath?\n\n    /// Temporary parameter controlling whether to warn about implicit executable targets when tools version is 5.4.\n    private let warnAboutImplicitExecutableTargets: Bool\n\n    /// Create the special REPL product for this package.\n    private let createREPLProduct: Bool\n\n    /// The additional file detection rules.\n    private let additionalFileRules: [FileRuleDescription]\n\n    /// ObservabilityScope with which to emit diagnostics\n    private let observabilityScope: ObservabilityScope\n\n    /// The filesystem package builder will run on.\n    private let fileSystem: FileSystem\n\n    private var platformRegistry: PlatformRegistry {\n        PlatformRegistry.default\n    }\n\n    // The set of the sources computed so far, used to validate source overlap\n    private var allSources = Set<AbsolutePath>()\n\n    // Caches all declared versions for this package.\n    private var declaredSwiftVersionsCache: [SwiftLanguageVersion]? = nil\n\n    // Caches the version we chose to build for.\n    private var swiftVersionCache: SwiftLanguageVersion? = nil\n\n    /// The enabled traits of this package.\n    private let enabledTraits: EnabledTraits\n\n    /// Create a builder for the given manifest and package `path`.\n    ///\n    /// - Parameters:\n    ///   - identity: The identity of this package.\n    ///   - manifest: The manifest of this package.\n    ///   - path: The root path of the package.\n    ///   - artifactPaths: Paths to the downloaded binary target artifacts.\n    ///   - createMultipleTestProducts: If enabled, create one test product for\n    ///     each test target.\n    ///   - fileSystem: The file system on which the builder should be run.///\n    public init(\n        identity: PackageIdentity,\n        manifest: Manifest,\n        productFilter: ProductFilter,\n        path: AbsolutePath,\n        additionalFileRules: [FileRuleDescription],\n        binaryArtifacts: [String: BinaryArtifact],\n        shouldCreateMultipleTestProducts: Bool = false,\n        testEntryPointPath: AbsolutePath? = nil,\n        warnAboutImplicitExecutableTargets: Bool = true,\n        createREPLProduct: Bool = false,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        enabledTraits: EnabledTraits\n    ) {\n        self.identity = identity\n        self.manifest = manifest\n        self.productFilter = productFilter\n        self.packagePath = path\n        self.additionalFileRules = additionalFileRules\n        self.binaryArtifacts = binaryArtifacts\n        self.shouldCreateMultipleTestProducts = shouldCreateMultipleTestProducts\n        self.testEntryPointPath = testEntryPointPath\n        self.createREPLProduct = createREPLProduct\n        self.warnAboutImplicitExecutableTargets = warnAboutImplicitExecutableTargets\n        self.observabilityScope = observabilityScope.makeChildScope(\n            description: \"PackageBuilder\",\n            metadata: .packageMetadata(identity: self.identity, kind: self.manifest.packageKind)\n        )\n        self.fileSystem = fileSystem\n        self.enabledTraits = enabledTraits\n    }\n\n    /// Build a new package following the conventions.\n    public func construct() throws -> Package {\n        let targets = try self.constructTargets()\n        let products = try self.constructProducts(targets)\n        // Find the special directory for targets.\n        let targetSpecialDirs = self.findTargetSpecialDirs(targets)\n\n        return Package(\n            identity: self.identity,\n            manifest: self.manifest,\n            path: self.packagePath,\n            targets: targets,\n            products: products,\n            targetSearchPath: self.packagePath.appending(component: targetSpecialDirs.targetDir),\n            testTargetSearchPath: self.packagePath.appending(component: targetSpecialDirs.testTargetDir)\n        )\n    }\n\n    /// Computes the special directory where targets are present or should be placed in future.\n    private func findTargetSpecialDirs(_ targets: [Module]) -> (targetDir: String, testTargetDir: String) {\n        let predefinedDirs = self.findPredefinedTargetDirectory()\n\n        // Select the preferred tests directory.\n        var testTargetDir = PackageBuilder.predefinedTestDirectories[0]\n\n        // If found predefined test directory is not same as preferred test directory,\n        // check if any of the test target is actually inside the predefined test directory.\n        if predefinedDirs.testTargetDir != testTargetDir {\n            let expectedTestsDir = self.packagePath.appending(component: predefinedDirs.testTargetDir)\n            for target in targets where target.type == .test {\n                // If yes, use the predefined test directory as preferred test directory.\n                if expectedTestsDir == target.sources.root.parentDirectory {\n                    testTargetDir = predefinedDirs.testTargetDir\n                    break\n                }\n            }\n        }\n\n        return (predefinedDirs.targetDir, testTargetDir)\n    }\n\n    // MARK: Utility Predicates\n\n    private func isValidSource(_ path: AbsolutePath) -> Bool {\n        // Ignore files which don't match the expected extensions.\n        guard let ext = path.extension,\n              SupportedLanguageExtension.validExtensions(toolsVersion: self.manifest.toolsVersion).contains(ext)\n        else {\n            return false\n        }\n\n        let basename = path.basename\n\n        // Ignore dotfiles.\n        if basename.hasPrefix(\".\") { return false }\n\n        // Ignore test entry point files.\n        if SwiftModule.testEntryPointNames.contains(basename) { return false }\n\n        // Ignore paths which are not valid files.\n        if !self.fileSystem.isFile(path) {\n            // Diagnose broken symlinks.\n            if self.fileSystem.isSymlink(path) {\n                self.observabilityScope.emit(.brokenSymlink(path))\n            }\n\n            return false\n        }\n\n        // Ignore manifest files.\n        if path.parentDirectory == self.packagePath {\n            if basename == Manifest.filename { return false }\n\n            // Ignore version-specific manifest files.\n            if basename.hasPrefix(Manifest.basename + \"@\") && basename.hasSuffix(\".swift\") {\n                return false\n            }\n        }\n\n        // Otherwise, we have a valid source file.\n        return true\n    }\n\n    /// Returns path to all the items in a directory.\n    // FIXME: This is generic functionality, and should move to FileSystem.\n    func directoryContents(_ path: AbsolutePath) throws -> [AbsolutePath] {\n        try self.fileSystem.getDirectoryContents(path).map { path.appending(component: $0) }\n    }\n\n    /// Private function that creates and returns a list of targets defined by a package.\n    private func constructTargets() throws -> [Module] {\n        // Check for a modulemap file, which indicates a system target.\n        let moduleMapPath = self.packagePath.appending(component: moduleMapFilename)\n        if self.fileSystem.isFile(moduleMapPath) {\n            // Warn about any declared targets.\n            if !self.manifest.targets.isEmpty {\n                self.observabilityScope.emit(\n                    .systemPackageDeclaresTargets(targets: Array(self.manifest.targets.map(\\.name)))\n                )\n            }\n\n            // Emit deprecation notice.\n            if self.manifest.toolsVersion >= .v4_2 {\n                self.observabilityScope.emit(.systemPackageDeprecation)\n            }\n\n            // Package contains a modulemap at the top level, so we assuming\n            // it's a system library target.\n            return [\n                SystemLibraryModule(\n                    name: self.manifest.displayName, // FIXME: use identity instead?\n                    path: self.packagePath,\n                    isImplicit: true,\n                    pkgConfig: self.manifest.pkgConfig,\n                    providers: self.manifest.providers\n                ),\n            ]\n        }\n\n        // At this point the target can't be a system target, make sure manifest doesn't contain\n        // system target specific configuration.\n        guard self.manifest.pkgConfig == nil else {\n            throw ModuleError.invalidManifestConfig(\n                self.identity.description, \"the 'pkgConfig' property can only be used with a System Module Package\"\n            )\n        }\n\n        guard self.manifest.providers == nil else {\n            throw ModuleError.invalidManifestConfig(\n                self.identity.description, \"the 'providers' property can only be used with a System Module Package\"\n            )\n        }\n\n        return try self.constructV4Targets()\n    }\n\n    /// Finds the predefined directories for regular targets, test targets, and plugin targets.\n    private func findPredefinedTargetDirectory()\n        -> (targetDir: String, testTargetDir: String, pluginTargetDir: String)\n    {\n        let targetDir = PackageBuilder.predefinedSourceDirectories.first(where: {\n            self.fileSystem.isDirectory(self.packagePath.appending(component: $0))\n        }) ?? PackageBuilder.predefinedSourceDirectories[0]\n\n        let testTargetDir = PackageBuilder.predefinedTestDirectories.first(where: {\n            self.fileSystem.isDirectory(self.packagePath.appending(component: $0))\n        }) ?? PackageBuilder.predefinedTestDirectories[0]\n\n        let pluginTargetDir = PackageBuilder.predefinedPluginDirectories.first(where: {\n            self.fileSystem.isDirectory(self.packagePath.appending(component: $0))\n        }) ?? PackageBuilder.predefinedPluginDirectories[0]\n\n        return (targetDir, testTargetDir, pluginTargetDir)\n    }\n\n    /// Construct targets according to PackageDescription 4 conventions.\n    private func constructV4Targets() throws -> [Module] {\n        // Select the correct predefined directory list.\n        let predefinedDirs = self.findPredefinedTargetDirectory()\n\n        let predefinedTargetDirectory = PredefinedTargetDirectory(\n            fs: fileSystem,\n            path: packagePath.appending(component: predefinedDirs.targetDir)\n        )\n        let predefinedTestTargetDirectory = PredefinedTargetDirectory(\n            fs: fileSystem,\n            path: packagePath.appending(component: predefinedDirs.testTargetDir)\n        )\n        let predefinedPluginTargetDirectory = PredefinedTargetDirectory(\n            fs: fileSystem,\n            path: packagePath.appending(component: predefinedDirs.pluginTargetDir)\n        )\n\n        /// Returns the path of the given target.\n        func findPath(for target: TargetDescription) throws -> AbsolutePath {\n            if target.type == .binary {\n                guard let artifact = self.binaryArtifacts[target.name] else {\n                    throw ModuleError.artifactNotFound(moduleName: target.name, expectedArtifactName: target.name)\n                }\n                return artifact.path\n            } else if let subpath = target.path { // If there is a custom path defined, use that.\n                if subpath == \"\" || subpath == \".\" {\n                    return self.packagePath\n                }\n\n                // Make sure target is not referenced by absolute path\n                guard let relativeSubPath = try? RelativePath(validating: subpath) else {\n                    throw ModuleError.unsupportedTargetPath(subpath)\n                }\n\n                let path = self.packagePath.appending(relativeSubPath)\n                // Make sure the target is inside the package root.\n                guard path.isDescendantOfOrEqual(to: self.packagePath) else {\n                    throw ModuleError.targetOutsidePackage(package: self.identity.description, target: target.name)\n                }\n                if self.fileSystem.isDirectory(path) {\n                    return path\n                }\n                throw ModuleError.invalidCustomPath(moduleName: target.name, path: subpath)\n            }\n\n            // Check if target is present in the predefined directory.\n            let predefinedDir: PredefinedTargetDirectory = switch target.type {\n            case .test:\n                predefinedTestTargetDirectory\n            case .plugin:\n                predefinedPluginTargetDirectory\n            default:\n                predefinedTargetDirectory\n            }\n            let path = predefinedDir.path.appending(component: target.name)\n\n            // Return the path if the predefined directory contains it.\n            if predefinedDir.contents.contains(target.name) {\n                return path\n            }\n\n            let commonTargetsOfSimilarType = self.manifest.targetsWithCommonSourceRoot(type: target.type).count\n            // If there is only one target defined, it may be allowed to occupy the\n            // entire predefined target directory.\n            if self.manifest.toolsVersion >= .v5_9 {\n                if commonTargetsOfSimilarType == 1 {\n                    return predefinedDir.path\n                }\n            }\n\n            // Otherwise, if the path \"exists\" then the case in manifest differs from the case on the file system.\n            if self.fileSystem.isDirectory(path) {\n                self.observabilityScope.emit(.targetNameHasIncorrectCase(target: target.name))\n                return path\n            }\n            throw ModuleError.moduleNotFound(\n                target.name,\n                target.type,\n                shouldSuggestRelaxedSourceDir: self.manifest\n                    .shouldSuggestRelaxedSourceDir(type: target.type)\n            )\n        }\n\n        // Create potential targets.\n        let potentialTargets: [PotentialModule]\n        potentialTargets = try self.manifest.targetsRequired(for: self.productFilter).map { target in\n            let path = try findPath(for: target)\n            return PotentialModule(\n                name: target.name,\n                path: path,\n                type: target.type,\n                packageAccess: target.packageAccess\n            )\n        }\n\n        let targets = try createModules(potentialTargets)\n\n        let snippetTargets: [Module]\n\n        if self.manifest.packageKind.isRoot {\n            // Snippets: depend on all available library targets in the package.\n            // TODO: Do we need to filter out targets that aren't available on the host platform?\n            let productTargets = Set(manifest.products.flatMap(\\.targets))\n            let snippetDependencies = targets\n                .filter { $0.type == .library && productTargets.contains($0.name) }\n                .map { Module.Dependency.module($0, conditions: []) }\n            snippetTargets = try createSnippetModules(dependencies: snippetDependencies)\n        } else {\n            snippetTargets = []\n        }\n\n        return targets + snippetTargets\n    }\n\n    // Create targets from the provided potential targets.\n    private func createModules(_ potentialModules: [PotentialModule]) throws -> [Module] {\n        // Find if manifest references a target which isn't present on disk.\n        let allVisibleModuleNames = self.manifest.visibleModuleNames(for: self.productFilter)\n        let potentialModulesName = Set(potentialModules.map(\\.name))\n        let missingModuleNames = allVisibleModuleNames.subtracting(potentialModulesName)\n        if let missingModuleName = missingModuleNames.first {\n            let type = potentialModules.first(where: { $0.name == missingModuleName })?.type ?? .regular\n            throw ModuleError.moduleNotFound(\n                missingModuleName,\n                type,\n                shouldSuggestRelaxedSourceDir: self.manifest.shouldSuggestRelaxedSourceDir(type: type)\n            )\n        }\n\n        let products = Dictionary(manifest.products.map { ($0.name, $0) }, uniquingKeysWith: { $1 })\n\n        // If there happens to be a plugin product with the right name in the same package, we want to use that\n        // automatically.\n        func pluginTargetName(for productName: String) -> String? {\n            if let product = products[productName], product.type == .plugin {\n                product.targets.first\n            } else {\n                nil\n            }\n        }\n\n        let potentialModuleMap = Dictionary(potentialModules.map { ($0.name, $0) }, uniquingKeysWith: { $1 })\n        let successors: (PotentialModule) throws -> [PotentialModule] = {\n            // No reference of this target in manifest, i.e. it has no dependencies.\n            guard let target = self.manifest.targetMap[$0.name] else { return [] }\n            // Collect the successors from declared dependencies.\n            var successors: [PotentialModule] = try target.dependencies.compactMap { dep in\n                guard try self.manifest.isTargetDependencyEnabled(target: target.name, dep, enabledTraits: self.enabledTraits) else {\n                    return nil\n                }\n                switch dep {\n                case .target(let name, _):\n                    // Since we already checked above that all referenced targets\n                    // has to present, we always expect this target to be present in\n                    // potentialModules dictionary.\n                    return potentialModuleMap[name]!\n                case .product:\n                    return nil\n                case .byName(let name, _):\n                    // By name dependency may or may not be a target dependency.\n                    return potentialModuleMap[name]\n                }\n            }\n            // If there are plugin usages, consider them to be dependencies too.\n            if let pluginUsages = target.pluginUsages {\n                successors += pluginUsages.compactMap {\n                    switch $0 {\n                    case .plugin(_, .some(_)):\n                        nil\n                    case .plugin(let name, nil):\n                        if let potentialModule = potentialModuleMap[name] {\n                            potentialModule\n                        } else if let targetName = pluginTargetName(for: name),\n                                  let potentialModule = potentialModuleMap[targetName]\n                        {\n                            potentialModule\n                        } else {\n                            nil\n                        }\n                    }\n                }\n            }\n            return successors\n        }\n        // Look for any cycle in the dependencies.\n        if let cycle = try findCycle(potentialModules.sorted(by: { $0.name < $1.name }), successors: successors) {\n            throw ModuleError.cycleDetected((cycle.path.map(\\.name), cycle.cycle.map(\\.name)))\n        }\n        // There was no cycle so we sort the targets topologically.\n        let potentialModules = try topologicalSort(potentialModules, successors: successors)\n\n        // The created targets mapped to their name.\n        var targets = [String: Module]()\n        // If a directory is empty, we don't create a target object for them.\n        var emptyModules = Set<String>()\n\n        // Start iterating the potential targets.\n        for potentialModule in potentialModules.lazy.reversed() {\n            // Validate the target name.  This function will throw an error if it detects a problem.\n            try validateModuleName(potentialModule.path, potentialModule.name, isTest: potentialModule.isTest)\n\n            // Get the target from the manifest.\n            let manifestTarget = manifest.targetMap[potentialModule.name]\n\n            // Get the dependencies of this target.\n            let dependencies: [Module.Dependency] = try manifestTarget.map { target in\n                try target.dependencies.compactMap { dependency -> Module.Dependency? in\n                    // We don't create an object for target dependencies that aren't enabled.\n                    guard try self.manifest.isTargetDependencyEnabled(target: target.name, dependency, enabledTraits: self.enabledTraits) else {\n                        return nil\n                    }\n                    switch dependency {\n                    case .target(let name, let condition):\n                        // We don't create an object for targets which have no sources.\n                        if emptyModules.contains(name) { return nil }\n                        guard let target = targets[name] else { return nil }\n                        return .module(target, conditions: buildConditions(from: condition))\n\n                    case .product(let name, let package, let moduleAliases, let condition):\n                        try validateModuleAliases(moduleAliases)\n                        return .product(\n                            .init(name: name, package: package, moduleAliases: moduleAliases),\n                            conditions: buildConditions(from: condition)\n                        )\n                    case .byName(let name, let condition):\n                        // We don't create an object for targets which have no sources.\n                        if emptyModules.contains(name) { return nil }\n                        if let target = targets[name] {\n                            return .module(target, conditions: buildConditions(from: condition))\n                        } else if potentialModuleMap[name] == nil {\n                            return .product(\n                                .init(name: name, package: nil),\n                                conditions: buildConditions(from: condition)\n                            )\n                        } else {\n                            return nil\n                        }\n                    }\n                }\n            } ?? []\n\n            // Get dependencies from the plugin usages of this target.\n            let pluginUsages: [Module.PluginUsage] = manifestTarget?.pluginUsages.map {\n                $0.compactMap { usage in\n                    switch usage {\n                    case .plugin(let name, let package):\n                        if let package {\n                            return .product(Module.ProductReference(name: name, package: package), conditions: [])\n                        } else {\n                            if let target = targets[name] {\n                                return .module(target, conditions: [])\n                            } else if let targetName = pluginTargetName(for: name), let target = targets[targetName] {\n                                return .module(target, conditions: [])\n                            } else {\n                                self.observabilityScope.emit(.pluginNotFound(name: name))\n                                return nil\n                            }\n                        }\n                    }\n                }\n            } ?? []\n\n            // Create the target, adding the inferred dependencies from plugin usages to the declared dependencies.\n            let target = try createTarget(\n                potentialModule: potentialModule,\n                manifestTarget: manifestTarget,\n                dependencies: dependencies + pluginUsages\n            )\n            // Add the created target to the map or print no sources warning.\n            if let createdTarget = target {\n                targets[createdTarget.name] = createdTarget\n            } else {\n                emptyModules.insert(potentialModule.name)\n                self.observabilityScope.emit(.targetHasNoSources(\n                    name: potentialModule.name,\n                    type: potentialModule.type,\n                    shouldSuggestRelaxedSourceDir: manifest\n                        .shouldSuggestRelaxedSourceDir(\n                            type: potentialModule\n                                .type\n                        )\n                ))\n            }\n        }\n\n        return targets.values.sorted { $0.name > $1.name }\n    }\n\n    /// Private function that checks whether a target name is valid.  This method doesn't return anything, but rather,\n    /// if there's a problem, it throws an error describing what the problem is.\n    private func validateModuleName(_ path: AbsolutePath, _ name: String, isTest: Bool) throws {\n        if name.isEmpty {\n            throw Module.Error.invalidName(\n                path: path.relative(to: self.packagePath),\n                problem: .emptyName\n            )\n        }\n    }\n\n    /// Validates module alias key and value pairs and throws an error if empty or contains invalid characters.\n    private func validateModuleAliases(_ aliases: [String: String]?) throws {\n        guard let aliases else { return }\n        for (aliasKey, aliasValue) in aliases {\n            if !aliasKey.isValidIdentifier ||\n                !aliasValue.isValidIdentifier ||\n                aliasKey == aliasValue\n            {\n                throw ModuleError.invalidModuleAlias(originalName: aliasKey, newName: aliasValue)\n            }\n        }\n    }\n\n    /// Private function that constructs a single Target object for the potential target.\n    private func createTarget(\n        potentialModule: PotentialModule,\n        manifestTarget: TargetDescription?,\n        dependencies: [Module.Dependency]\n    ) throws -> Module? {\n        guard let manifestTarget else { return nil }\n\n        // Create system library target.\n        if potentialModule.type == .system {\n            let moduleMapPath = potentialModule.path.appending(component: moduleMapFilename)\n            guard self.fileSystem.isFile(moduleMapPath) else {\n                throw ModuleError.invalidLayout(.modulemapMissing(moduleMapPath))\n            }\n\n            return SystemLibraryModule(\n                name: potentialModule.name,\n                path: potentialModule.path, isImplicit: false,\n                pkgConfig: manifestTarget.pkgConfig,\n                providers: manifestTarget.providers\n            )\n        } else if potentialModule.type == .binary {\n            guard let artifact = self.binaryArtifacts[potentialModule.name] else {\n                throw InternalError(\"unknown binary artifact for '\\(potentialModule.name)'\")\n            }\n            let artifactOrigin: BinaryModule.Origin = artifact.originURL.flatMap { .remote(url: $0) } ?? .local\n            return BinaryModule(\n                name: potentialModule.name,\n                kind: artifact.kind,\n                path: potentialModule.path,\n                origin: artifactOrigin\n            )\n        }\n\n        // Check for duplicate target dependencies\n        if self.manifest.disambiguateByProductIDs {\n            let dupProductIDs = dependencies.compactMap { $0.product?.identity }.spm_findDuplicates()\n            for dupProductID in dupProductIDs {\n                let comps = dupProductID.components(separatedBy: \"_\")\n                let pkg = comps.first ?? \"\"\n                let name = comps.dropFirst().joined(separator: \"_\")\n                let dupProductName = name.isEmpty ? dupProductID : name\n                self.observabilityScope.emit(.duplicateProduct(name: dupProductName, package: pkg))\n            }\n            let dupTargetNames = dependencies.compactMap { $0.module?.name }.spm_findDuplicates()\n            for dupTargetName in dupTargetNames {\n                self.observabilityScope.emit(.duplicateTargetDependency(\n                    dependency: dupTargetName,\n                    target: potentialModule.name,\n                    package: self.identity.description\n                ))\n            }\n        } else {\n            dependencies.filter { $0.product?.moduleAliases == nil }.spm_findDuplicateElements(by: \\.nameAndType)\n                .map(\\.[0].name).forEach {\n                    self.observabilityScope\n                        .emit(.duplicateTargetDependency(\n                            dependency: $0,\n                            target: potentialModule.name,\n                            package: self.identity.description\n                        ))\n                }\n        }\n\n        // Ensure non-test targets do not depend on test targets.\n        // Only test targets are allowed to have dependencies on other test targets.\n        if !potentialModule.isTest {\n            for dependency in dependencies {\n                if let depTarget = dependency.module, depTarget.type == .test {\n                    self.observabilityScope.emit(.invalidDependencyOnTestTarget(\n                        dependency: dependency,\n                        targetName: potentialModule.name\n                    ))\n                }\n            }\n        }\n\n        // Create the build setting assignment table for this target.\n        let buildSettings = try self.buildSettings(\n            for: manifestTarget,\n            targetRoot: potentialModule.path,\n            cxxLanguageStandard: self.manifest.cxxLanguageStandard,\n            toolsSwiftVersion: self.toolsSwiftVersion()\n        )\n\n        // Compute the path to public headers directory.\n        let publicHeaderComponent = manifestTarget.publicHeadersPath ?? ClangModule.defaultPublicHeadersComponent\n        let publicHeadersPath = try potentialModule.path.appending(RelativePath(validating: publicHeaderComponent))\n        guard publicHeadersPath.isDescendantOfOrEqual(to: potentialModule.path) else {\n            throw ModuleError.invalidPublicHeadersDirectory(potentialModule.name)\n        }\n\n        let sourcesBuilder = TargetSourcesBuilder(\n            packageIdentity: self.identity,\n            packageKind: self.manifest.packageKind,\n            packagePath: self.packagePath,\n            target: manifestTarget,\n            path: potentialModule.path,\n            defaultLocalization: self.manifest.defaultLocalization,\n            additionalFileRules: self.additionalFileRules,\n            toolsVersion: self.manifest.toolsVersion,\n            fileSystem: self.fileSystem,\n            observabilityScope: self.observabilityScope\n        )\n        let (sources, resources, headers, ignored, others) = try sourcesBuilder.run()\n\n        // Make sure defaultLocalization is set if the target has localized resources.\n        let hasLocalizedResources = resources.contains(where: { $0.localization != nil })\n        if hasLocalizedResources && self.manifest.defaultLocalization == nil {\n            throw ModuleError.defaultLocalizationNotSet\n        }\n\n        // FIXME: use identity instead?\n        // The name of the bundle, if one is being generated.\n        let potentialBundleName = self.manifest.displayName + \"_\" + potentialModule.name\n\n        if sources.relativePaths.isEmpty && resources.isEmpty && headers.isEmpty {\n            return nil\n        }\n        try self.validateSourcesOverlapping(forTarget: potentialModule.name, sources: sources.paths)\n\n        // Deal with package plugin targets.\n        if potentialModule.type == .plugin {\n            // Check that the target has a declared capability; we should not have come this far if not.\n            guard let declaredCapability = manifestTarget.pluginCapability else {\n                throw ModuleError.pluginCapabilityNotDeclared(target: manifestTarget.name)\n            }\n\n            // Create and return an PluginTarget configured with the information from the manifest.\n            return PluginModule(\n                name: potentialModule.name,\n                sources: sources,\n                apiVersion: self.manifest.toolsVersion,\n                pluginCapability: PluginCapability(from: declaredCapability),\n                dependencies: dependencies,\n                packageAccess: potentialModule.packageAccess\n            )\n        }\n\n        /// Determine the module's kind, or leave nil to check the source directory.\n        let moduleKind: Module.Kind\n        switch potentialModule.type {\n        case .test:\n            moduleKind = .test\n        case .executable:\n            moduleKind = .executable\n        case .macro:\n            moduleKind = .macro\n        default:\n            moduleKind = sources.computeModuleKind()\n            if moduleKind == .executable && self.manifest.toolsVersion >= .v5_4 && self\n                .warnAboutImplicitExecutableTargets\n            {\n                self.observabilityScope\n                    .emit(\n                        warning: \"'\\(potentialModule.name)' was identified as an executable target given the presence of a 'main' file. Starting with tools version \\(ToolsVersion.v5_4) executable targets should be declared as 'executableTarget()'\"\n                    )\n            }\n        }\n\n        // Create and return the right kind of target depending on what kind of sources we found.\n        if sources.hasSwiftSources {\n            return try SwiftModule(\n                name: potentialModule.name,\n                potentialBundleName: potentialBundleName,\n                type: moduleKind,\n                path: potentialModule.path,\n                sources: sources,\n                resources: resources,\n                ignored: ignored,\n                others: others,\n                dependencies: dependencies,\n                packageAccess: potentialModule.packageAccess,\n                declaredSwiftVersions: self.declaredSwiftVersions(),\n                buildSettings: buildSettings,\n                buildSettingsDescription: manifestTarget.settings,\n                // unsafe flags check disabled in 6.2\n                usesUnsafeFlags: manifest.toolsVersion >= .v6_2 ? false : manifestTarget.usesUnsafeFlags,\n                implicit: false\n            )\n        } else {\n            // It's not a Swift target, so it's a Clang target (those are the only two types of source target currently\n            // supported).\n\n            // First determine the type of module map that will be appropriate for the target based on its header\n            // layout.\n            let moduleMapType: ModuleMapType\n\n            if self.fileSystem.exists(publicHeadersPath) {\n                let moduleMapGenerator = ModuleMapGenerator(\n                    targetName: potentialModule.name,\n                    moduleName: potentialModule.name.spm_mangledToC99ExtendedIdentifier(),\n                    publicHeadersDir: publicHeadersPath,\n                    fileSystem: self.fileSystem\n                )\n                moduleMapType = moduleMapGenerator.determineModuleMapType(observabilityScope: self.observabilityScope)\n            } else if moduleKind == .library, self.manifest.toolsVersion >= .v5_5 {\n                // If this clang target is a library, it must contain \"include\" directory.\n                throw ModuleError.invalidPublicHeadersDirectory(potentialModule.name)\n            } else {\n                moduleMapType = .none\n            }\n\n            if resources.contains(where: { $0.rule == .embedInCode }) {\n                throw ModuleError.embedInCodeNotSupported(target: potentialModule.name)\n            }\n\n            return try ClangModule(\n                name: potentialModule.name,\n                potentialBundleName: potentialBundleName,\n                cLanguageStandard: self.manifest.cLanguageStandard,\n                cxxLanguageStandard: self.manifest.cxxLanguageStandard,\n                includeDir: publicHeadersPath,\n                moduleMapType: moduleMapType,\n                headers: headers,\n                type: moduleKind,\n                path: potentialModule.path,\n                sources: sources,\n                resources: resources,\n                ignored: ignored,\n                dependencies: dependencies,\n                buildSettings: buildSettings,\n                buildSettingsDescription: manifestTarget.settings,\n                // unsafe flags check disabled in 6.2\n                usesUnsafeFlags: manifest.toolsVersion >= .v6_2 ? false : manifestTarget.usesUnsafeFlags,\n                implicit: false\n            )\n        }\n    }\n\n    /// Creates build setting assignment table for the given target.\n    func buildSettings(\n        for target: TargetDescription?,\n        targetRoot: AbsolutePath,\n        cxxLanguageStandard: String? = nil,\n        toolsSwiftVersion: SwiftLanguageVersion\n    ) throws -> BuildSettings.AssignmentTable {\n        var table = BuildSettings.AssignmentTable()\n        guard let target else { return table }\n\n        // First let's add a default assignments for tools swift version.\n        var versionAssignment = BuildSettings.Assignment(default: true)\n        versionAssignment.values = [toolsSwiftVersion.rawValue]\n\n        table.add(versionAssignment, for: .SWIFT_VERSION)\n\n        // Process each setting.\n        for setting in target.settings {\n            if let traits = setting.condition?.traits, traits.intersection(self.enabledTraits.names).isEmpty {\n                // The setting is currently not enabled so we should skip it\n                continue\n            }\n        \n            let decl: BuildSettings.Declaration\n            let values: [String]\n\n            // Compute appropriate declaration for the setting.\n            switch setting.kind {\n            case .headerSearchPath(let value):\n                values = [value]\n\n                switch setting.tool {\n                case .c, .cxx:\n                    decl = .HEADER_SEARCH_PATHS\n                case .swift, .linker:\n                    throw InternalError(\"unexpected tool for setting type \\(setting)\")\n                }\n\n                // Ensure that the search path is contained within the package.\n                _ = try RelativePath(validating: value)\n                let path = try AbsolutePath(validating: value, relativeTo: targetRoot)\n                guard path.isDescendantOfOrEqual(to: self.packagePath) else {\n                    throw ModuleError.invalidHeaderSearchPath(value)\n                }\n\n            case .define(let value):\n                values = [value]\n\n                switch setting.tool {\n                case .c, .cxx:\n                    decl = .GCC_PREPROCESSOR_DEFINITIONS\n                case .swift:\n                    decl = .SWIFT_ACTIVE_COMPILATION_CONDITIONS\n                case .linker:\n                    throw InternalError(\"unexpected tool for setting type \\(setting)\")\n                }\n\n            case .linkedLibrary(let value):\n                values = [value]\n\n                switch setting.tool {\n                case .c, .cxx, .swift:\n                    throw InternalError(\"unexpected tool for setting type \\(setting)\")\n                case .linker:\n                    decl = .LINK_LIBRARIES\n                }\n\n            case .linkedFramework(let value):\n                values = [value]\n\n                switch setting.tool {\n                case .c, .cxx, .swift:\n                    throw InternalError(\"unexpected tool for setting type \\(setting)\")\n                case .linker:\n                    decl = .LINK_FRAMEWORKS\n                }\n\n            case .interoperabilityMode(let lang):\n                switch setting.tool {\n                case .c, .cxx, .linker:\n                    throw InternalError(\"only Swift supports interoperability\")\n\n                case .swift:\n                    decl = .OTHER_SWIFT_FLAGS\n                }\n\n                if lang == .Cxx {\n                    values = [\"-cxx-interoperability-mode=default\"] +\n                        (cxxLanguageStandard.flatMap { [\"-Xcc\", \"-std=\\($0)\"] } ?? [])\n                } else {\n                    values = []\n                }\n\n            case .unsafeFlags(let _values):\n                values = _values\n\n                switch setting.tool {\n                case .c:\n                    decl = .OTHER_CFLAGS\n                case .cxx:\n                    decl = .OTHER_CPLUSPLUSFLAGS\n                case .swift:\n                    decl = .OTHER_SWIFT_FLAGS\n                case .linker:\n                    decl = .OTHER_LDFLAGS\n                }\n\n            case .enableUpcomingFeature(let value):\n                switch setting.tool {\n                case .c, .cxx, .linker:\n                    throw InternalError(\"only Swift supports upcoming features\")\n\n                case .swift:\n                    decl = .OTHER_SWIFT_FLAGS\n                }\n\n                values = [\"-enable-upcoming-feature\", value]\n\n            case .enableExperimentalFeature(let value):\n                switch setting.tool {\n                case .c, .cxx, .linker:\n                    throw InternalError(\n                        \"only Swift supports experimental features\"\n                    )\n\n                case .swift:\n                    decl = .OTHER_SWIFT_FLAGS\n                }\n\n                values = [\"-enable-experimental-feature\", value]\n\n            case .strictMemorySafety:\n                switch setting.tool {\n                case .c, .cxx, .linker:\n                    throw InternalError(\n                        \"only Swift supports strict memory safety\"\n                    )\n\n                case .swift:\n                    decl = .OTHER_SWIFT_FLAGS\n                }\n\n                values = [\"-strict-memory-safety\"]\n\n            case .swiftLanguageMode(let version):\n                switch setting.tool {\n                case .c, .cxx, .linker:\n                    throw InternalError(\"only Swift supports swift language version\")\n\n                case .swift:\n                    decl = .SWIFT_VERSION\n                }\n\n                values = [version.rawValue]\n\n            case .treatAllWarnings(let level):\n                switch setting.tool {\n                case .c:\n                    decl = .OTHER_CFLAGS\n                    let flag = switch level {\n                    case .error: \"-Werror\"\n                    case .warning: \"-Wno-error\"\n                    }\n                    values = [flag]\n                    \n                case .cxx:\n                    decl = .OTHER_CPLUSPLUSFLAGS\n                    let flag = switch level {\n                    case .error: \"-Werror\"\n                    case .warning: \"-Wno-error\"\n                    }\n                    values = [flag]\n                    \n                case .linker:\n                    throw InternalError(\"linker does not support treatAllWarnings\")\n\n                case .swift:\n                    // We can't use SWIFT_WARNINGS_AS_WARNINGS_GROUPS and\n                    // SWIFT_WARNINGS_AS_ERRORS_GROUPS here.\n                    // See https://github.com/swiftlang/swift-build/issues/248\n                    decl = .OTHER_SWIFT_FLAGS\n                    let flag = switch level {\n                    case .error: \"-warnings-as-errors\"\n                    case .warning: \"-no-warnings-as-errors\"\n                    }\n                    values = [flag]\n                }\n\n            case .treatWarning(let name, let level):\n                switch setting.tool {\n                case .c:\n                    decl = .OTHER_CFLAGS\n                    let flag = switch level {\n                    case .error: \"-Werror=\\(name)\"\n                    case .warning: \"-Wno-error=\\(name)\"\n                    }\n                    values = [flag]\n                    \n                case .cxx:\n                    decl = .OTHER_CPLUSPLUSFLAGS\n                    let flag = switch level {\n                    case .error: \"-Werror=\\(name)\"\n                    case .warning: \"-Wno-error=\\(name)\"\n                    }\n                    values = [flag]\n                    \n                case .linker:\n                    throw InternalError(\"linker does not support treatWarning\")\n\n                case .swift:\n                    // We can't use SWIFT_WARNINGS_AS_WARNINGS_GROUPS and\n                    // SWIFT_WARNINGS_AS_ERRORS_GROUPS here.\n                    // See https://github.com/swiftlang/swift-build/issues/248\n                    decl = .OTHER_SWIFT_FLAGS\n                    let flag = switch level {\n                    case .error: \"-Werror\"\n                    case .warning: \"-Wwarning\"\n                    }\n                    values = [flag, name]\n                }\n\n            case .enableWarning(let name):\n                switch setting.tool {\n                case .c:\n                    decl = .OTHER_CFLAGS\n                    values = [\"-W\\(name)\"]\n                case .cxx:\n                    decl = .OTHER_CPLUSPLUSFLAGS\n                    values = [\"-W\\(name)\"]\n                case .swift, .linker:\n                    throw InternalError(\"enableWarning is supported by C/C++\")\n                }\n\n            case .disableWarning(let name):\n                switch setting.tool {\n                case .c:\n                    decl = .OTHER_CFLAGS\n                    values = [\"-Wno-\\(name)\"]\n                case .cxx:\n                    decl = .OTHER_CPLUSPLUSFLAGS\n                    values = [\"-Wno-\\(name)\"]\n                case .swift, .linker:\n                    throw InternalError(\"disableWarning is supported by C/C++\")\n                }\n\n            case .defaultIsolation(let isolation):\n                switch setting.tool {\n                case .c, .cxx, .linker:\n                    throw InternalError(\"only Swift supports default isolation\")\n\n                case .swift:\n                    decl = .OTHER_SWIFT_FLAGS\n                }\n\n                values = [\"-default-isolation\", isolation.rawValue]\n            }\n\n            // Create an assignment for this setting.\n            var assignment = BuildSettings.Assignment()\n            assignment.values = values\n            assignment.conditions = self.buildConditions(from: setting.condition)\n\n            // Finally, add the assignment to the assignment table.\n            table.add(assignment, for: decl)\n        }\n\n        // For each trait we are now generating an additional define\n        for trait in self.enabledTraits {\n            var assignment = BuildSettings.Assignment()\n            assignment.values = [\"\\(trait)\"]\n            assignment.conditions = []\n            table.add(assignment, for: .SWIFT_ACTIVE_COMPILATION_CONDITIONS)\n        }\n\n        return table\n    }\n\n    func buildConditions(from condition: PackageConditionDescription?) -> [PackageCondition] {\n        var conditions: [PackageCondition] = []\n\n        if let config = condition?.config.flatMap({ BuildConfiguration(rawValue: $0) }) {\n            conditions.append(.init(configuration: config))\n        }\n\n        if let platforms = condition?.platformNames.map({\n            if let platform = platformRegistry.platformByName[$0] {\n                platform\n            } else {\n                PackageModel.Platform.custom(name: $0, oldestSupportedVersion: .unknown)\n            }\n        }), !platforms.isEmpty {\n            conditions.append(.init(platforms: platforms))\n        }\n\n        if let traits = condition?.traits {\n            conditions.append(.traits(.init(traits: traits)))\n        }\n\n        return conditions\n    }\n\n    private func declaredSwiftVersions() throws -> [SwiftLanguageVersion] {\n        if let versions = self.declaredSwiftVersionsCache {\n            return versions\n        }\n\n        let versions: [SwiftLanguageVersion]\n        if let swiftLanguageVersions = manifest.swiftLanguageVersions {\n            versions = swiftLanguageVersions.sorted(by: >).filter { $0 <= ToolsVersion.current }\n\n            if versions.isEmpty {\n                throw ModuleError.incompatibleToolsVersions(\n                    package: self.identity.description, required: swiftLanguageVersions, current: .current\n                )\n            }\n        } else {\n            versions = []\n        }\n\n        self.declaredSwiftVersionsCache = versions\n        return versions\n    }\n\n    /// Computes the swift version to use for this manifest.\n    private func toolsSwiftVersion() throws -> SwiftLanguageVersion {\n        if let swiftVersion = self.swiftVersionCache {\n            return swiftVersion\n        }\n\n        // Figure out the swift version from declared list in the manifest.\n        let declaredSwiftVersions = try declaredSwiftVersions()\n        let computedSwiftVersion: SwiftLanguageVersion = if let declaredSwiftVersion = declaredSwiftVersions.first {\n            declaredSwiftVersion\n        } else {\n            // Otherwise, use the version depending on the manifest version.\n            self.manifest.toolsVersion.swiftLanguageVersion\n        }\n        self.swiftVersionCache = computedSwiftVersion\n        return computedSwiftVersion\n    }\n\n    /// Validates that the sources of a target are not already present in another target.\n    private func validateSourcesOverlapping(forTarget target: String, sources: [AbsolutePath]) throws {\n        // Compute the sources which overlap with already computed targets.\n        var overlappingSources: Set<AbsolutePath> = []\n        for source in sources {\n            if !self.allSources.insert(source).inserted {\n                overlappingSources.insert(source)\n            }\n        }\n\n        // Throw if we found any overlapping sources.\n        if !overlappingSources.isEmpty {\n            throw ModuleError.overlappingSources(target: target, sources: Array(overlappingSources))\n        }\n    }\n\n    /// Find the test entry point file for the package.\n    private func findTestEntryPoint(in testTargets: [Module]) throws -> AbsolutePath? {\n        if let testEntryPointPath {\n            return testEntryPointPath\n        }\n\n        var testEntryPointFiles = Set<AbsolutePath>()\n        var pathsSearched = Set<AbsolutePath>()\n\n        // Look for entry point file adjacent to each test target root, iterating upto package root.\n        for target in testTargets {\n            // Form the initial search path.\n            //\n            // If the target root's parent directory is inside the package, start\n            // search there. Otherwise, we start search from the target root.\n            var searchPath = target.sources.root.parentDirectory\n            if !searchPath.isDescendantOfOrEqual(to: self.packagePath) {\n                searchPath = target.sources.root\n            }\n\n            while true {\n                guard searchPath.isDescendantOfOrEqual(to: self.packagePath) else {\n                    throw InternalError(\"search path \\(searchPath) is outside the package \\(self.packagePath)\")\n                }\n                // If we have already searched this path, skip.\n                if !pathsSearched.contains(searchPath) {\n                    for name in SwiftModule.testEntryPointNames {\n                        let path = searchPath.appending(component: name)\n                        if self.fileSystem.isFile(path) {\n                            testEntryPointFiles.insert(path)\n                        }\n                    }\n                    pathsSearched.insert(searchPath)\n                }\n                // Break if we reached all the way to package root.\n                if searchPath == self.packagePath { break }\n                // Go one level up.\n                searchPath = searchPath.parentDirectory\n            }\n        }\n\n        // It is an error if there are multiple linux main files.\n        if testEntryPointFiles.count > 1 {\n            throw ModuleError.multipleTestEntryPointFilesFound(\n                package: self.identity.description, files: testEntryPointFiles.map { $0 }\n            )\n        }\n        return testEntryPointFiles.first\n    }\n\n    /// Collects the products defined by a package.\n    private func constructProducts(_ modules: [Module]) throws -> [Product] {\n        var products = OrderedCollections.OrderedSet<KeyedPair<Product, String>>()\n\n        /// Helper method to append to products array.\n        func append(_ product: Product) {\n            let inserted = products.append(KeyedPair(product, key: product.name)).inserted\n            if !inserted {\n                self.observabilityScope.emit(.duplicateProduct(product: product))\n            }\n        }\n\n        // Collect all test modules.\n        let testModules = modules.filter { module in\n            guard module.type == .test else { return false }\n            #if os(Linux)\n            // FIXME: Ignore C language test targets on linux for now.\n            if module is ClangModule {\n                self.observabilityScope\n                    .emit(.unsupportedCTestTarget(package: self.identity.description, target: module.name))\n                return false\n            }\n            #endif\n            return true\n        }\n\n        // If enabled, create one test product for each test module.\n        if self.shouldCreateMultipleTestProducts {\n            for testModule in testModules {\n                let product = try Product(\n                    package: self.identity,\n                    name: testModule.name,\n                    type: .test,\n                    modules: [testModule]\n                )\n                append(product)\n            }\n        } else if !testModules.isEmpty {\n            // Otherwise we only need to create one test product for all of the\n            // test targets.\n            //\n            // Add suffix 'PackageTests' to test product name so the target name\n            // of linux executable don't collide with main package, if present.\n            // FIXME: use identity instead\n            let productName = self.manifest.umbrellaPackageTestsProductName\n            let testEntryPointPath = try self.findTestEntryPoint(in: testModules)\n\n            let product = try Product(\n                package: self.identity,\n                name: productName,\n                type: .test,\n                modules: testModules,\n                testEntryPointPath: testEntryPointPath\n            )\n            append(product)\n        }\n\n        // Map containing modules mapped to their names.\n        let modulesMap = Dictionary(modules.map { ($0.name, $0) }, uniquingKeysWith: { $1 })\n\n        /// Helper method to get targets from target names.\n        func modulesFrom(moduleNames names: [String], product: String) throws -> [Module] {\n            // Get targets from target names.\n            try names.map { targetName in\n                // Ensure we have this target.\n                guard let target = modulesMap[targetName] else {\n                    throw Product.Error.moduleEmpty(product: product, target: targetName)\n                }\n                return target\n            }\n        }\n\n        // First add explicit products.\n\n        let filteredProducts: [ProductDescription] = switch self.productFilter {\n        case .everything:\n            self.manifest.products\n        case .specific(let set):\n            self.manifest.products.filter { set.contains($0.name) }\n        }\n        for product in filteredProducts {\n            if product.name.isEmpty {\n                throw Product.Error.emptyName\n            }\n\n            let modules = try modulesFrom(moduleNames: product.targets, product: product.name)\n            // Perform special validations if this product is exporting\n            // a system library target.\n            if modules.contains(where: { $0 is SystemLibraryModule }) {\n                if product.type != .library(.automatic) || modules.count != 1 {\n                    self.observabilityScope.emit(.systemPackageProductValidation(product: product.name))\n                    continue\n                }\n            }\n\n            // Do some validation based on the product type.\n            switch product.type {\n            case .library:\n                guard self.validateLibraryProduct(product, with: modules) else {\n                    continue\n                }\n            case .test, .macro:\n                break\n            case .executable, .snippet:\n                guard self.validateExecutableProduct(product, with: modules) else {\n                    continue\n                }\n            case .plugin:\n                guard self.validatePluginProduct(product, with: modules) else {\n                    continue\n                }\n            }\n\n            try append(Product(package: self.identity, name: product.name, type: product.type, modules: modules))\n        }\n\n        // Add implicit executables - for root packages and for dependency plugins.\n\n        // Compute the list of targets which are being used in an\n        // executable product so we don't create implicit executables\n        // for them.\n        let explicitProductsModules = Set(self.manifest.products.flatMap { product -> [String] in\n            switch product.type {\n            case .library, .plugin, .test, .macro:\n                return []\n            case .executable, .snippet:\n                return product.targets\n            }\n        })\n\n        let productMap = products.reduce(into: [String: Product]()) { partial, iterator in\n            partial[iterator.key] = iterator.item\n        }\n\n        let implicitPlugInExecutables = Set(\n            modules.lazy\n                .filter { $0.type == .plugin }\n                .flatMap(\\.dependencies)\n                .map(\\.name)\n        )\n\n        for module in modules where module.type == .executable {\n            if self.manifest.packageKind.isRoot && explicitProductsModules.contains(module.name) {\n                // If there is already an executable module with this name, skip generating a product for it\n                // (This shortcut only works for the root manifest, because for dependencies,\n                // products that correspond to plug‐ins may have been culled during resolution.)\n                continue\n            } else if let product = productMap[module.name] {\n                // If there is already a product with this name skip generating a product for it,\n                // but warn if that product is not executable\n                if product.type != .executable {\n                    self.observabilityScope\n                        .emit(\n                            warning: \"The target named '\\(module.name)' was identified as an executable target but a non-executable product with this name already exists.\"\n                        )\n                }\n                continue\n            } else {\n                if self.manifest.packageKind.isRoot || implicitPlugInExecutables.contains(module.name) {\n                    // Generate an implicit product for the executable target\n                    let product = try Product(\n                        package: self.identity,\n                        name: module.name,\n                        type: .executable,\n                        modules: [module],\n                        isImplicit: true\n                    )\n                    append(product)\n                }\n            }\n        }\n\n        // Create a special REPL product that contains all the library targets.\n\n        if self.createREPLProduct {\n            let libraryTargets = modules.filter { $0.type == .library }\n            if libraryTargets.isEmpty {\n                self.observabilityScope.emit(.noLibraryTargetsForREPL)\n            } else {\n                let replProduct = try Product(\n                    package: self.identity,\n                    name: self.identity.description + Product.replProductSuffix,\n                    type: .library(.dynamic),\n                    modules: libraryTargets\n                )\n                append(replProduct)\n            }\n        }\n\n        // Create implicit snippet products\n        try modules\n            .filter { $0.type == .snippet }\n            .map { try Product(package: self.identity, name: $0.name, type: .snippet, modules: [$0]) }\n            .forEach(append)\n\n        // Create implicit macro products\n        try modules\n            .filter { $0.type == .macro }\n            .map { try Product(package: self.identity, name: $0.name, type: .macro, modules: [$0]) }\n            .forEach(append)\n\n        return products.map(\\.item)\n    }\n\n    private func validateLibraryProduct(_ product: ProductDescription, with targets: [Module]) -> Bool {\n        let pluginTargets = targets.filter { $0.type == .plugin }\n        guard pluginTargets.isEmpty else {\n            self.observabilityScope.emit(.nonPluginProductWithPluginTargets(\n                product: product.name,\n                type: product.type,\n                pluginTargets: pluginTargets.map(\\.name)\n            ))\n            return false\n        }\n        if self.manifest.toolsVersion >= .v5_7 {\n            let executableTargets = targets.filter { $0.type == .executable }\n            guard executableTargets.isEmpty else {\n                self.observabilityScope\n                    .emit(.libraryProductWithExecutableTarget(\n                        product: product.name,\n                        executableTargets: executableTargets.map(\\.name)\n                    ))\n                return false\n            }\n        }\n        return true\n    }\n\n    private func validateExecutableProduct(_ product: ProductDescription, with targets: [Module]) -> Bool {\n        let executableTargetCount = targets.executables.count\n        guard executableTargetCount == 1 else {\n            if executableTargetCount == 0 {\n                if let target = targets.spm_only {\n                    self.observabilityScope\n                        .emit(.executableProductTargetNotExecutable(product: product.name, target: target.name))\n                } else {\n                    self.observabilityScope.emit(.executableProductWithoutExecutableTarget(product: product.name))\n                }\n            } else {\n                self.observabilityScope.emit(.executableProductWithMoreThanOneExecutableTarget(product: product.name))\n            }\n            return false\n        }\n        let pluginTargets = targets.filter { $0.type == .plugin }\n        guard pluginTargets.isEmpty else {\n            self.observabilityScope.emit(.nonPluginProductWithPluginTargets(\n                product: product.name,\n                type: product.type,\n                pluginTargets: pluginTargets.map(\\.name)\n            ))\n            return false\n        }\n        return true\n    }\n\n    private func validatePluginProduct(_ product: ProductDescription, with targets: [Module]) -> Bool {\n        let nonPluginTargets = targets.filter { $0.type != .plugin }\n        guard nonPluginTargets.isEmpty else {\n            self.observabilityScope\n                .emit(.pluginProductWithNonPluginTargets(\n                    product: product.name,\n                    otherTargets: nonPluginTargets.map(\\.name)\n                ))\n            return false\n        }\n        guard !targets.isEmpty else {\n            self.observabilityScope.emit(.pluginProductWithNoTargets(product: product.name))\n            return false\n        }\n        return true\n    }\n\n    /// Returns the first suggested predefined source directory for a given target type.\n    public static func suggestedPredefinedSourceDirectory(type: TargetDescription.TargetKind) -> String {\n        // These are static constants, safe to access by index; the first choice is preferred.\n        switch type {\n        case .test:\n            self.predefinedTestDirectories[0]\n        case .plugin:\n            self.predefinedPluginDirectories[0]\n        default:\n            self.predefinedSourceDirectories[0]\n        }\n    }\n}\n\nextension PackageBuilder {\n    struct PredefinedTargetDirectory {\n        let path: AbsolutePath\n        let contents: [String]\n\n        init(fs: FileSystem, path: AbsolutePath) {\n            self.path = path\n            self.contents = (try? fs.getDirectoryContents(path)) ?? []\n        }\n    }\n}\n\n/// We create this structure after scanning the filesystem for potential modules.\nprivate struct PotentialModule: Hashable {\n    /// Name of the module.\n    let name: String\n\n    /// The path of the module.\n    let path: AbsolutePath\n\n    /// If this should be a test module.\n    var isTest: Bool {\n        self.type == .test\n    }\n\n    /// The module type.\n    let type: TargetDescription.TargetKind\n\n    /// If true, access to package declarations from other modules is allowed.\n    let packageAccess: Bool\n}\n\nextension Manifest {\n    /// Returns the names of all the visible modules in the manifest.\n    fileprivate func visibleModuleNames(for productFilter: ProductFilter) -> Set<String> {\n        let names = targetsRequired(for: productFilter).flatMap { target in\n            [target.name] + target.dependencies.compactMap {\n                switch $0 {\n                case .target(let name, _):\n                    name\n                case .byName, .product:\n                    nil\n                }\n            }\n        }\n        return Set(names)\n    }\n\n    package var umbrellaPackageTestsProductName: String {\n        \"\\(self.displayName)PackageTests\"\n    }\n}\n\nextension Sources {\n    var hasSwiftSources: Bool {\n        paths.contains { path in\n            guard let ext = path.extension else { return false }\n\n            return FileRuleDescription.swift.fileTypes.contains(ext)\n        }\n    }\n\n    var hasClangSources: Bool {\n        let supportedClangFileExtensions = FileRuleDescription.clang.fileTypes.union(FileRuleDescription.asm.fileTypes)\n\n        return paths.contains { path in\n            guard let ext = path.extension else { return false }\n\n            return supportedClangFileExtensions.contains(ext)\n        }\n    }\n\n    var containsMixedLanguage: Bool {\n        self.hasSwiftSources && self.hasClangSources\n    }\n\n    /// Determine module type based on the sources.\n    fileprivate func computeModuleKind() -> Module.Kind {\n        let isLibrary = !relativePaths.contains { path in\n            let file = path.basename.lowercased()\n            // Look for a main.xxx file avoiding cases like main.xxx.xxx\n            return file.hasPrefix(\"main.\") && String(file.filter { $0 == \".\" }).count == 1\n        }\n        return isLibrary ? .library : .executable\n    }\n}\n\nextension Module.Dependency {\n    fileprivate var nameAndType: String {\n        switch self {\n        case .module:\n            \"target-\\(name)\"\n        case .product:\n            \"product-\\(name)\"\n        }\n    }\n}\n\n// MARK: - Snippets\n\nextension PackageBuilder {\n    private func createSnippetModules(dependencies: [Module.Dependency]) throws -> [Module] {\n        let snippetsDirectory = self.packagePath.appending(\"Snippets\")\n        guard self.fileSystem.isDirectory(snippetsDirectory) else {\n            return []\n        }\n\n        return try walk(snippetsDirectory, fileSystem: self.fileSystem)\n            .filter { self.fileSystem.isFile($0) && $0.extension == \"swift\" }\n            .map { sourceFile in\n                let name = sourceFile.basenameWithoutExt\n                let sources = Sources(paths: [sourceFile], root: sourceFile.parentDirectory)\n                let buildSettings: BuildSettings.AssignmentTable\n\n                let targetDescription = try TargetDescription(\n                    name: name,\n                    dependencies: dependencies\n                        .map {\n                            TargetDescription.Dependency.target(name: $0.name)\n                        },\n                    path: sourceFile.parentDirectory.pathString,\n                    sources: [sourceFile.pathString],\n                    type: .executable,\n                    packageAccess: false\n                )\n                buildSettings = try self.buildSettings(\n                    for: targetDescription,\n                    targetRoot: sourceFile.parentDirectory,\n                    toolsSwiftVersion: self.toolsSwiftVersion()\n                )\n\n                return SwiftModule(\n                    name: name,\n                    type: .snippet,\n                    path: .root,\n                    sources: sources,\n                    dependencies: dependencies,\n                    packageAccess: false,\n                    buildSettings: buildSettings,\n                    buildSettingsDescription: targetDescription.settings,\n                    usesUnsafeFlags: false,\n                    implicit: true\n                )\n            }\n    }\n}\n\nextension Sequence {\n    /// Construct a new array where each of the elements in the \\c self\n    /// sequence is preceded by the \\c prefixElement.\n    ///\n    /// For example:\n    /// ```\n    /// [\"Alice\", \"Bob\", \"Charlie\"].precedeElements(with: \"Hi\")\n    /// ```\n    ///\n    /// produces `[\"Hi\", \"Alice\", \"Hi\", \"Bob\", \"Hi\", \"Charlie\"]`.\n    private func precedeElements(with prefixElement: Element) -> [Element] {\n        var results: [Element] = []\n        for element in self {\n            results.append(prefixElement)\n            results.append(element)\n        }\n        return results\n    }\n}\n\nextension TargetDescription {\n    fileprivate var usesUnsafeFlags: Bool {\n        settings.filter(\\.kind.isUnsafeFlags).isEmpty == false\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/PkgConfig.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport OrderedCollections\nimport TSCUtility\nimport TSCBasic\n\nimport class Basics.AsyncProcess\n\n/// Information on an individual `pkg-config` supported package.\npublic struct PkgConfig {\n    /// The name of the package.\n    public let name: String\n\n    /// The path to the definition file.\n    public let pcFile: Basics.AbsolutePath\n\n    /// The list of C compiler flags in the definition.\n    public let cFlags: [String]\n\n    /// The list of libraries to link.\n    public let libs: [String]\n\n    /// Load the information for the named package.\n    ///\n    /// It will search `fileSystem` for the pkg config file in the following order:\n    /// * Paths defined in `PKG_CONFIG_PATH` environment variable\n    /// * Paths defined in `additionalSearchPaths` argument\n    /// * Built-in search paths (see `PCFileFinder.searchPaths`)\n    ///\n    /// - parameter name: Name of the pkg config file (without file extension).\n    /// - parameter additionalSearchPaths: Additional paths to search for pkg config file.\n    /// - parameter fileSystem: The file system to use\n    ///\n    /// - throws: PkgConfigError\n    public init(\n        name: String,\n        additionalSearchPaths: [Basics.AbsolutePath]? = .none,\n        brewPrefix: Basics.AbsolutePath? = .none,\n        sysrootDir: Basics.AbsolutePath? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.init(\n            name: name,\n            additionalSearchPaths: additionalSearchPaths ?? [],\n            brewPrefix: brewPrefix,\n            sysrootDir: sysrootDir,\n            loadingContext: LoadingContext(),\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    private init(\n        name: String,\n        additionalSearchPaths: [Basics.AbsolutePath],\n        brewPrefix: Basics.AbsolutePath?,\n        sysrootDir: Basics.AbsolutePath?,\n        loadingContext: LoadingContext,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        loadingContext.pkgConfigStack.append(name)\n\n        if let path = try? Basics.AbsolutePath(validating: name) {\n            guard fileSystem.isFile(path) else { throw PkgConfigError.couldNotFindConfigFile(name: name) }\n            self.name = path.basenameWithoutExt\n            self.pcFile = path\n        } else {\n            self.name = name\n            let pkgFileFinder = PCFileFinder(brewPrefix: brewPrefix)\n            self.pcFile = try pkgFileFinder.locatePCFile(\n                name: name,\n                customSearchPaths: try PkgConfig.envSearchPaths + additionalSearchPaths,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n        }\n\n        var parser = try PkgConfigParser(pcFile: pcFile, fileSystem: fileSystem, sysrootDir: Environment.current[\"PKG_CONFIG_SYSROOT_DIR\"])\n        try parser.parse()\n\n        func getFlags(from dependencies: [String]) throws -> (cFlags: [String], libs: [String]) {\n            var cFlags = [String]()\n            var libs = [String]()\n\n            for dep in dependencies {\n                if let index = loadingContext.pkgConfigStack.firstIndex(of: dep) {\n                    observabilityScope.emit(warning: \"circular dependency detected while parsing \\(loadingContext.pkgConfigStack[0]): \\(loadingContext.pkgConfigStack[index..<loadingContext.pkgConfigStack.count].joined(separator: \" -> \")) -> \\(dep)\")\n                    continue\n                }\n\n                // FIXME: This is wasteful, we should be caching the PkgConfig result.\n                let pkg = try PkgConfig(\n                    name: dep,\n                    additionalSearchPaths: additionalSearchPaths,\n                    brewPrefix: brewPrefix,\n                    sysrootDir: sysrootDir,\n                    loadingContext: loadingContext,\n                    fileSystem: fileSystem,\n                    observabilityScope: observabilityScope\n                )\n\n                cFlags += pkg.cFlags\n                libs += pkg.libs\n            }\n\n            return (cFlags: cFlags, libs: libs)\n        }\n\n        let dependencyFlags = try getFlags(from: parser.dependencies)\n        let privateDependencyFlags = try getFlags(from: parser.privateDependencies)\n\n        self.cFlags = parser.cFlags + dependencyFlags.cFlags + privateDependencyFlags.cFlags\n        self.libs = parser.libs + dependencyFlags.libs\n\n        loadingContext.pkgConfigStack.removeLast();\n    }\n\n    private static var envSearchPaths: [Basics.AbsolutePath] {\n        get throws {\n            if let configPath = Environment.current[\"PKG_CONFIG_PATH\"] {\n                #if os(Windows)\n                return try configPath.split(separator: \";\").map({ try AbsolutePath(validating: String($0)) })\n                #else\n                return try configPath.split(separator: \":\").map({ try AbsolutePath(validating: String($0)) })\n                #endif\n            }\n            return []\n        }\n    }\n}\n\nextension PkgConfig {\n    /// Information to track circular dependencies and other PkgConfig issues\n    public class LoadingContext {\n        public init() {\n            pkgConfigStack = [String]()\n        }\n\n        public var pkgConfigStack: [String]\n    }\n}\n\n\n/// Parser for the `pkg-config` `.pc` file format.\n///\n/// See: https://www.freedesktop.org/wiki/Software/pkg-config/\n// This is only internal so it can be unit tested.\ninternal struct PkgConfigParser {\n    public let pcFile: Basics.AbsolutePath\n    private let fileSystem: FileSystem\n    public private(set) var variables = [String: String]()\n    public private(set) var dependencies = [String]()\n    public private(set) var privateDependencies = [String]()\n    public private(set) var cFlags = [String]()\n    public private(set) var libs = [String]()\n    public private(set) var sysrootDir: String?\n\n    public init(pcFile: Basics.AbsolutePath, fileSystem: FileSystem, sysrootDir: String?) throws {\n        guard fileSystem.isFile(pcFile) else {\n            throw StringError(\"invalid pcfile \\(pcFile)\")\n        }\n        self.pcFile = pcFile\n        self.fileSystem = fileSystem\n        self.sysrootDir = sysrootDir\n    }\n\n    // Compress repeated path separators to one.\n    private func compressPathSeparators(_ value: String) -> String {\n        let components = value.components(separatedBy: \"/\").filter { !$0.isEmpty }.joined(separator: \"/\")\n        if value.hasPrefix(\"/\") {\n            return \"/\" + components\n        } else {\n            return components\n        }\n    }\n\n    // Trim duplicate sysroot prefixes, matching the approach of pkgconf\n    private func trimDuplicateSysroot(_ value: String) -> String {\n        // If sysroot has been applied more than once, remove the first instance.\n        // pkgconf makes this check after variable expansion to handle rare .pc\n        // files which expand ${pc_sysrootdir} directly:\n        //    https://github.com/pkgconf/pkgconf/issues/123\n        //\n        // For example:\n        //       /sysroot/sysroot/remainder -> /sysroot/remainder\n        //\n        // However, pkgconf's algorithm searches for an additional sysrootdir anywhere in\n        // the string after the initial prefix, rather than looking for two sysrootdir prefixes\n        // directly next to each other:\n        //\n        //     /sysroot/filler/sysroot/remainder -> /filler/sysroot/remainder\n        //\n        // It might seem more logical not to strip sysroot in this case, as it is not a double\n        // prefix, but for compatibility trimDuplicateSysroot is faithful to pkgconf's approach\n        // in the functions `pkgconf_tuple_parse` and `should_rewrite_sysroot`.\n\n        // Only trim if sysroot is defined with a meaningful value\n        guard let sysrootDir, sysrootDir != \"/\" else {\n           return value\n        }\n\n        // Only trim absolute paths starting with sysroot\n        guard value.hasPrefix(\"/\"), value.hasPrefix(sysrootDir) else {\n            return value\n        }\n\n        // If sysroot appears multiple times, trim the prefix\n        // N.B. sysroot can appear anywhere in the remainder\n        // of the value, mirroring pkgconf's logic\n        let pathSuffix = value.dropFirst(sysrootDir.count)\n        if pathSuffix.contains(sysrootDir) {\n            return String(pathSuffix)\n        } else {\n            return value\n        }\n    }\n\n    // Apply sysroot to generated paths, matching the approach of pkgconf\n    private func applySysroot(_ value: String) -> String {\n        // The two main pkg-config implementations handle sysroot differently:\n        //\n        //     `pkg-config` (freedesktop.org) prepends sysroot after variable expansion, when in creates the compiler flag lists\n        //     `pkgconf` prepends sysroot to variables when they are defined, so sysroot is included when they are expanded\n        //\n        // pkg-config's method skips single character compiler flags, such as '-I' and '-L', and has special cases for longer options.\n        // It does not handle spaces between the flags and their values properly, and prepends sysroot multiple times in some cases,\n        // such as when the .pc file uses the sysroot_dir variable directly or has been rewritten to hard-code the sysroot prefix.\n        //\n        // pkgconf's method handles spaces correctly, although it also requires extra checks to ensure that sysroot is not applied\n        // more than once.\n        //\n        // In 2024 pkg-config is the more popular option according to Homebrew installation statistics, but the major Linux distributions\n        // have generally switched to pkgconf.\n        //\n        // We will use pkgconf's method here as it seems more robust than pkg-config's, and pkgconf's greater popularity on Linux\n        // means libraries developed there may depend on the specific way it handles .pc files.\n\n        if value.hasPrefix(\"/\"), let sysrootDir, !value.hasPrefix(sysrootDir) {\n            return compressPathSeparators(trimDuplicateSysroot(sysrootDir + value))\n        } else {\n            return compressPathSeparators(trimDuplicateSysroot(value))\n        }\n    }\n\n    public mutating func parse() throws {\n        func removeComment(line: String) -> String {\n            if let commentIndex = line.firstIndex(of: \"#\") {\n                return String(line[line.startIndex..<commentIndex])\n            }\n            return line\n        }\n\n        // Add pcfiledir variable. This is the path of the directory containing this pc file.\n        variables[\"pcfiledir\"] = pcFile.parentDirectory.pathString\n\n        // Add pc_sysrootdir variable. This is the path of the sysroot directory for pc files.\n        // pkgconf does not define pc_sysrootdir if the path of the .pc file is outside sysrootdir.\n        // SwiftPM does not currently make that check.\n        variables[\"pc_sysrootdir\"] = sysrootDir ?? Basics.AbsolutePath.root.pathString\n\n        let fileContents: String = try fileSystem.readFileContents(pcFile)\n        for line in fileContents.components(separatedBy: .newlines) {\n            // Remove commented or any trailing comment from the line.\n            let uncommentedLine = removeComment(line: line)\n            // Ignore any empty or whitespace line.\n            guard let line = uncommentedLine.spm_chuzzle() else { continue }\n\n            if line.contains(\":\") {\n                // Found a key-value pair.\n                try parseKeyValue(line: line)\n            } else if line.contains(\"=\") {\n                // Found a variable.\n                let (name, maybeValue) = line.spm_split(around: \"=\")\n                let value = maybeValue?.spm_chuzzle() ?? \"\"\n                variables[name.spm_chuzzle() ?? \"\"] = try applySysroot(resolveVariables(value))\n            } else {\n                // Unexpected thing in the pc file, abort.\n                throw PkgConfigError.parsingError(\"Unexpected line: \\(line) in \\(pcFile)\")\n            }\n        }\n    }\n\n    private mutating func parseKeyValue(line: String) throws {\n        guard line.contains(\":\") else {\n            throw InternalError(\"invalid pcfile, expecting line to contain :\")\n        }\n        let (key, maybeValue) = line.spm_split(around: \":\")\n        let value = try resolveVariables(maybeValue?.spm_chuzzle() ?? \"\")\n        switch key.lowercased() {\n        case \"requires\":\n            dependencies = try parseDependencies(value)\n        case \"requires.private\":\n            privateDependencies = try parseDependencies(value)\n        case \"libs\":\n            libs = try splitEscapingSpace(value)\n        case \"cflags\":\n            cFlags = try splitEscapingSpace(value)\n        default:\n            break\n        }\n    }\n\n    /// Parses `Requires: ` string into array of dependencies.\n    ///\n    /// The dependency string has separator which can be (multiple) space or a\n    /// comma. Additionally each there can be an optional version constraint to\n    /// a dependency.\n    private func parseDependencies(_ depString: String) throws -> [String] {\n        let operators = [\"=\", \"<\", \">\", \"<=\", \">=\"]\n        let separators = [\" \", \",\"]\n\n        // Look at a char at an index if present.\n        func peek(idx: Int) -> Character? {\n            guard idx <= depString.count - 1 else { return nil }\n            return depString[depString.index(depString.startIndex, offsetBy: idx)]\n        }\n\n        // This converts the string which can be separated by comma or spaces\n        // into an array of string.\n        func tokenize() -> [String] {\n            var tokens = [String]()\n            var token = \"\"\n            for (idx, char) in depString.enumerated() {\n                // Encountered a separator, use the token.\n                if separators.contains(String(char)) {\n                    // If next character is a space skip.\n                    if let peeked = peek(idx: idx+1), peeked == \" \" { continue }\n                    // Append to array of tokens and reset token variable.\n                    tokens.append(token)\n                    token = \"\"\n                } else {\n                    token += String(char)\n                }\n            }\n            // Append the last collected token if present.\n            if !token.isEmpty { tokens += [token] }\n            return tokens\n        }\n\n        var deps = [String]()\n        var it = tokenize().makeIterator()\n        while let arg = it.next() {\n            // If we encounter an operator then we need to skip the next token.\n            if operators.contains(arg) {\n                // We should have a version number next, skip.\n                guard it.next() != nil else {\n                    throw PkgConfigError.parsingError(\"\"\"\n                        Expected version number after \\(deps.last.debugDescription) \\(arg) in \\\"\\(depString)\\\" in \\\n                        \\(pcFile)\n                        \"\"\")\n                }\n            } else if !arg.isEmpty {\n                // Otherwise it is a dependency.\n                deps.append(arg)\n            }\n        }\n        return deps\n    }\n\n    /// Perform variable expansion on the line by processing the each fragment\n    /// of the string until complete.\n    ///\n    /// Variables occur in form of ${variableName}, we search for a variable\n    /// linearly in the string and if found, lookup the value of the variable in\n    /// our dictionary and replace the variable name with its value.\n    private func resolveVariables(_ line: String) throws -> String {\n        // Returns variable name, start index and end index of a variable in a string if present.\n        // We make sure it of form ${name} otherwise it is not a variable.\n        func findVariable(_ fragment: String)\n            -> (name: String, startIndex: String.Index, endIndex: String.Index)? {\n            guard let dollar = fragment.firstIndex(of: \"$\"),\n                  dollar != fragment.endIndex && fragment[fragment.index(after: dollar)] == \"{\",\n                  let variableEndIndex = fragment.firstIndex(of: \"}\")\n            else { return nil }\n            return (String(fragment[fragment.index(dollar, offsetBy: 2)..<variableEndIndex]), dollar, variableEndIndex)\n        }\n\n        var result = \"\"\n        var fragment = line\n        while !fragment.isEmpty {\n            // Look for a variable in our current fragment.\n            if let variable = findVariable(fragment) {\n                // Append the contents before the variable.\n                result += fragment[fragment.startIndex..<variable.startIndex]\n                guard let variableValue = variables[variable.name] else {\n                    throw PkgConfigError.parsingError(\n                        \"Expected a value for variable '\\(variable.name)' in \\(pcFile). Variables: \\(variables)\")\n                }\n                // Append the value of the variable.\n                result += variableValue\n                // Update the fragment with post variable string.\n                fragment = String(fragment[fragment.index(after: variable.endIndex)...])\n            } else {\n                // No variable found, just append rest of the fragment to result.\n                result += fragment\n                fragment = \"\"\n            }\n        }\n        return String(result)\n    }\n\n    /// Split line on unescaped spaces.\n    ///\n    /// Will break on space in \"abc def\" and \"abc\\\\ def\" but not in \"abc\\ def\"\n    /// and ignore multiple spaces such that \"abc def\" will split into [\"abc\",\n    /// \"def\"].\n    private func splitEscapingSpace(_ line: String) throws -> [String] {\n        var splits = [String]()\n        var fragment = [Character]()\n\n        func saveFragment() {\n            if !fragment.isEmpty {\n                splits.append(String(fragment))\n                fragment.removeAll()\n            }\n        }\n\n        var it = line.makeIterator()\n        // Indicates if we're in a quoted fragment, we shouldn't append quote.\n        var inQuotes = false\n        while let char = it.next() {\n            if char == \"\\\"\" {\n                inQuotes = !inQuotes\n            } else if char == \"\\\\\" {\n                if let next = it.next() {\n#if os(Windows)\n                    if ![\" \", \"\\\\\"].contains(next) { fragment.append(\"\\\\\") }\n#endif\n                    fragment.append(next)\n                }\n            } else if char == \" \" && !inQuotes {\n                saveFragment()\n            } else {\n                fragment.append(char)\n            }\n        }\n        guard !inQuotes else {\n            throw PkgConfigError.parsingError(\n                \"Text ended before matching quote was found in line: \\(line) file: \\(pcFile)\")\n        }\n        saveFragment()\n        return splits\n    }\n}\n\n// This is only internal so it can be unit tested.\ninternal struct PCFileFinder {\n    /// Cached results of locations `pkg-config` will search for `.pc` files\n    /// FIXME: This shouldn't use a static variable, since the first lookup\n    /// will cache the result of whatever `brewPrefix` was passed in.  It is\n    /// also not threadsafe.\n    public private(set) static var pkgConfigPaths: [Basics.AbsolutePath]? // FIXME: @testable(internal)\n    private static var shouldEmitPkgConfigPathsDiagnostic = false\n\n    /// The built-in search path list.\n    ///\n    /// By default, this is combined with the search paths inferred from\n    /// `pkg-config` itself.\n    static let searchPaths = [\n        try? Basics.AbsolutePath(validating: \"/usr/local/lib/pkgconfig\"),\n        try? AbsolutePath(validating: \"/usr/local/share/pkgconfig\"),\n        try? AbsolutePath(validating: \"/usr/lib/pkgconfig\"),\n        try? AbsolutePath(validating: \"/usr/share/pkgconfig\"),\n    ].compactMap({ $0 })\n\n    /// Get search paths from `pkg-config` itself to locate `.pc` files.\n    ///\n    /// This is needed because on Linux machines, the search paths can be different\n    /// from the standard locations that we are currently searching.\n    private init(pkgConfigPath: String) {\n        if PCFileFinder.pkgConfigPaths == nil {\n            do {\n                let searchPaths = try AsyncProcess.checkNonZeroExit(args:\n                    pkgConfigPath, \"--variable\", \"pc_path\", \"pkg-config\"\n                ).spm_chomp()\n\n#if os(Windows)\n                PCFileFinder.pkgConfigPaths = try searchPaths.split(separator: \";\").map({ try AbsolutePath(validating: String($0)) })\n#else\n                PCFileFinder.pkgConfigPaths = try searchPaths.split(separator: \":\").map({ try AbsolutePath(validating: String($0)) })\n#endif\n            } catch {\n                PCFileFinder.shouldEmitPkgConfigPathsDiagnostic = true\n                PCFileFinder.pkgConfigPaths = []\n            }\n        }\n    }\n\n    public init(brewPrefix: Basics.AbsolutePath?) {\n        self.init(pkgConfigPath: brewPrefix?.appending(components: \"bin\", \"pkg-config\").pathString ?? \"pkg-config\")\n    }\n\n    public init(pkgConfig: Basics.AbsolutePath? = .none) {\n        self.init(pkgConfigPath: pkgConfig?.pathString ?? \"pkg-config\")\n    }\n\n    /// Reset the cached `pkgConfigPaths` property, so that it will be evaluated\n    /// again when instantiating a `PCFileFinder()`.  This is intended only for\n    /// use by testing.  This is a temporary workaround for the use of a static\n    /// variable by this class.\n    internal static func resetCachedPkgConfigPaths() {\n        PCFileFinder.pkgConfigPaths = nil\n    }\n\n    public func locatePCFile(\n        name: String,\n        customSearchPaths: [Basics.AbsolutePath],\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws -> Basics.AbsolutePath {\n        // FIXME: We should consider building a registry for all items in the\n        // search paths, which is likely to be substantially more efficient if\n        // we end up searching for a reasonably sized number of packages.\n        for path in OrderedSet(customSearchPaths + PCFileFinder.pkgConfigPaths! + PCFileFinder.searchPaths) {\n            let pcFile = path.appending(component: name + \".pc\")\n            if fileSystem.isFile(pcFile) {\n                return pcFile\n            }\n        }\n        if PCFileFinder.shouldEmitPkgConfigPathsDiagnostic {\n            PCFileFinder.shouldEmitPkgConfigPathsDiagnostic = false\n            observabilityScope.emit(warning: \"failed to retrieve search paths with pkg-config; maybe pkg-config is not installed\")\n        }\n        throw PkgConfigError.couldNotFindConfigFile(name: name)\n    }\n}\n\ninternal enum PkgConfigError: Swift.Error, CustomStringConvertible {\n    case couldNotFindConfigFile(name: String)\n    case parsingError(String)\n    case prohibitedFlags(String)\n\n    public var description: String {\n        switch self {\n        case .couldNotFindConfigFile(let name):\n            return \"couldn't find pc file for \\(name)\"\n        case .parsingError(let error):\n            return \"parsing error(s): \\(error)\"\n        case .prohibitedFlags(let flags):\n            return \"prohibited flag(s): \\(flags)\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/Platform.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport TSCBasic\n\nimport class Basics.AsyncProcess\n\nprivate func isAndroid() -> Bool {\n    (try? Basics.localFileSystem.isFile(AbsolutePath(validating: \"/system/bin/toolchain\"))) ?? false ||\n        (try? Basics.localFileSystem.isFile(AbsolutePath(validating: \"/system/bin/toybox\"))) ?? false\n}\n\npublic enum Platform: Equatable, Sendable {\n    case android\n    case darwin\n    case linux(LinuxFlavor)\n    case windows\n    case freebsd\n\n    /// Recognized flavors of linux.\n    public enum LinuxFlavor: Equatable, Sendable {\n        case debian\n        case fedora\n    }\n}\n\nextension Platform {\n    public static let current: Platform? = {\n        #if os(Windows)\n        return .windows\n        #else\n        switch try? AsyncProcess.checkNonZeroExit(args: \"uname\")\n            .trimmingCharacters(in: .whitespacesAndNewlines)\n            .lowercased()\n        {\n        case \"darwin\"?:\n            return .darwin\n        case \"freebsd\"?:\n            return .freebsd\n        case \"linux\"?:\n            return Platform.findCurrentPlatformLinux(Basics.localFileSystem)\n        default:\n            return nil\n        }\n        #endif\n    }()\n\n    private static func findCurrentPlatformLinux(_ fileSystem: FileSystem) -> Platform? {\n        do {\n            if try fileSystem.isFile(AbsolutePath(validating: \"/etc/debian_version\")) {\n                return .linux(.debian)\n            }\n            if try fileSystem.isFile(AbsolutePath(validating: \"/system/bin/toolbox\")) ||\n                fileSystem.isFile(AbsolutePath(validating: \"/system/bin/toybox\"))\n            {\n                return .android\n            }\n            if try fileSystem.isFile(AbsolutePath(validating: \"/etc/redhat-release\")) ||\n                fileSystem.isFile(AbsolutePath(validating: \"/etc/centos-release\")) ||\n                fileSystem.isFile(AbsolutePath(validating: \"/etc/fedora-release\")) ||\n                Platform.isAmazonLinux2(fileSystem)\n            {\n                return .linux(.fedora)\n            }\n        } catch {}\n\n        return nil\n    }\n\n    private static func isAmazonLinux2(_ fileSystem: FileSystem) -> Bool {\n        do {\n            let release = try fileSystem.readFileContents(AbsolutePath(validating: \"/etc/system-release\")).cString\n            return release.hasPrefix(\"Amazon Linux release 2\")\n        } catch {\n            return false\n        }\n    }\n}\n\nextension Platform {\n    /// The file extension used for a dynamic library on this platform.\n    public var dynamicLibraryExtension: String {\n        switch self {\n        case .darwin: return \".dylib\"\n        case .linux, .android, .freebsd: return \".so\"\n        case .windows: return \".dll\"\n        }\n    }\n\n    public var executableExtension: String {\n        switch self {\n        case .windows: return \".exe\"\n        case .linux, .android, .darwin, .freebsd: return \"\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/README.md",
    "content": "# PackageLoading Library\n\nThis library defines the logic which translates between the Swift package\nmanager conventions and the underlying project model.\n\nThe intent is that it is largely a transformation taking the input project model\nobjects described in a manifest.\n\nUltimately, this library should *only* deal with the content which is _local_ to\na single package. Any cross-package information should be managed by the\n[`PackageGraph`](../PackageGraph/README.md) module.\n"
  },
  {
    "path": "Sources/PackageLoading/RegistryReleaseMetadataSerialization.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\nimport TSCBasic\n\npublic enum RegistryReleaseMetadataStorage {\n    public static let fileName = \".registry-metadata\"\n\n    private static let encoder = JSONEncoder.makeWithDefaults()\n    private static let decoder = JSONDecoder.makeWithDefaults()\n\n    public static func save(_ metadata: RegistryReleaseMetadata, to path: Basics.AbsolutePath, fileSystem: FileSystem) throws {\n        let codableMetadata = CodableRegistryReleaseMetadata(metadata)\n        let data = try Self.encoder.encode(codableMetadata)\n        try fileSystem.writeFileContents(path, data: data)\n    }\n\n    public static func load(from path: Basics.AbsolutePath, fileSystem: FileSystem) throws -> RegistryReleaseMetadata {\n        let codableMetadata = try Self.decoder.decode(\n            path: path,\n            fileSystem: fileSystem,\n            as: CodableRegistryReleaseMetadata.self\n        )\n        return try RegistryReleaseMetadata(codableMetadata)\n    }\n}\n\nprivate struct CodableRegistryReleaseMetadata: Codable {\n    public let registry: URL\n    public let signature: Signature?\n    public let author: Author?\n    public let description: String?\n    public let licenseURL: URL?\n    public let readmeURL: URL?\n    public let scmRepositoryURLs: [SourceControlURL]?\n\n    init(_ seed: RegistryReleaseMetadata) {\n        switch seed.source {\n        case .registry(let url):\n            self.registry = url\n        }\n        self.signature = seed.signature.map { signature in\n            .init(\n                signedBy: signature.signedBy.flatMap {\n                    switch $0 {\n                    case .recognized(let type, let commonName, let organization, let identity):\n                        return .recognized(\n                            type: type,\n                            commonName: commonName,\n                            organization: organization,\n                            identity: identity\n                        )\n                    case .unrecognized(let commonName, let organization):\n                        return .unrecognized(commonName: commonName, organization: organization)\n                    }\n                },\n                format: signature.format,\n                base64: Data(signature.value).base64EncodedString()\n            )\n        }\n        self.author = seed.metadata.author.map {\n            .init(\n                name: $0.name,\n                emailAddress: $0.emailAddress,\n                description: $0.description,\n                url: $0.url,\n                organization: $0.organization.map {\n                    .init(\n                        name: $0.name,\n                        emailAddress: $0.emailAddress,\n                        description: $0.description,\n                        url: $0.url\n                    )\n                }\n            )\n        }\n        self.description = seed.metadata.description\n        self.licenseURL = seed.metadata.licenseURL\n        self.readmeURL = seed.metadata.readmeURL\n        self.scmRepositoryURLs = seed.metadata.scmRepositoryURLs\n    }\n\n    public struct Signature: Codable {\n        let signedBy: SigningEntity?\n        let format: String\n        let base64: String\n    }\n\n    public enum SigningEntity: Codable {\n        case recognized(type: String, commonName: String?, organization: String?, identity: String?)\n        case unrecognized(commonName: String?, organization: String?)\n    }\n\n    public struct Author: Codable {\n        let name: String\n        let emailAddress: String?\n        let description: String?\n        let url: URL?\n        let organization: Organization?\n    }\n\n    struct Organization: Codable {\n        let name: String\n        let emailAddress: String?\n        let description: String?\n        let url: URL?\n    }\n}\n\nextension RegistryReleaseMetadata {\n    fileprivate init(_ seed: CodableRegistryReleaseMetadata) throws {\n        self.init(\n            source: .registry(seed.registry),\n            metadata: .init(\n                author: seed.author.flatMap {\n                    .init(\n                        name: $0.name,\n                        emailAddress: $0.emailAddress,\n                        description: $0.description,\n                        url: $0.url,\n                        organization: $0.organization.flatMap {\n                            .init(\n                                name: $0.name,\n                                emailAddress: $0.emailAddress,\n                                description: $0.description,\n                                url: $0.url\n                            )\n                        }\n                    )\n                },\n                description: seed.description,\n                licenseURL: seed.licenseURL,\n                readmeURL: seed.readmeURL,\n                scmRepositoryURLs: seed.scmRepositoryURLs\n            ),\n            signature: try seed.signature.flatMap { signature in\n                guard let signatureData = Data(base64Encoded: signature.base64) else {\n                    throw StringError(\"invalid base64 signature\")\n                }\n                return .init(\n                    signedBy: signature.signedBy.flatMap {\n                        switch $0 {\n                        case .recognized(let type, let commonName, let organization, let identity):\n                            return .recognized(\n                                type: type,\n                                commonName: commonName,\n                                organization: organization,\n                                identity: identity\n                            )\n                        case .unrecognized(let commonName, let organization):\n                            return .unrecognized(commonName: commonName, organization: organization)\n                        }\n                    },\n                    format: signature.format,\n                    value: Array(signatureData)\n                )\n            }\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/Target+PkgConfig.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport Foundation\n\nimport class Basics.AsyncProcess\nimport struct TSCBasic.RegEx\n\nimport enum TSCUtility.Platform\n\n/// Wrapper struct containing result of a pkgConfig query.\npublic struct PkgConfigResult {\n\n    /// The name of the pkgConfig file.\n    public let pkgConfigName: String\n\n    /// The cFlags from pkgConfig.\n    public let cFlags: [String]\n\n    /// The library flags from pkgConfig.\n    public let libs: [String]\n\n    /// Available provider, if any.\n    public let provider: SystemPackageProviderDescription?\n\n    /// Any error encountered during operation.\n    public let error: Swift.Error?\n\n    /// If the pc file was not found.\n    public var couldNotFindConfigFile: Bool {\n        switch error {\n            case PkgConfigError.couldNotFindConfigFile?: return true\n            default: return false\n        }\n    }\n\n    /// Create a result.\n    fileprivate init(\n        pkgConfigName: String,\n        cFlags: [String] = [],\n        libs: [String] = [],\n        error: Swift.Error? = nil,\n        provider: SystemPackageProviderDescription? = nil\n    ) {\n        self.cFlags = cFlags\n        self.libs = libs\n        self.error = error\n        self.provider = provider\n        self.pkgConfigName = pkgConfigName\n    }\n}\n\n/// Get pkgConfig result for a system library target.\npublic func pkgConfigArgs(\n    for target: SystemLibraryModule,\n    pkgConfigDirectories: [AbsolutePath],\n    sdkRootPath: AbsolutePath? = nil,\n    brewPrefix: AbsolutePath? = .none,\n    fileSystem: FileSystem,\n    observabilityScope: ObservabilityScope\n) throws -> [PkgConfigResult] {\n    // If there is no pkg config name defined, we're done.\n    guard let pkgConfigNames = target.pkgConfig else { return [] }\n\n    // Compute additional search paths for the provider, if any.\n    let provider = target.providers?.first { $0.isAvailable }\n\n    let additionalSearchPaths: [AbsolutePath]\n    // Give priority to `pkgConfigDirectories` passed as an argument to this function.\n    if let providerSearchPaths = try provider?.pkgConfigSearchPath(brewPrefixOverride: brewPrefix) {\n        additionalSearchPaths = pkgConfigDirectories + providerSearchPaths\n    } else {\n        additionalSearchPaths = pkgConfigDirectories\n    }\n\n    var ret: [PkgConfigResult] = []\n    // Get the pkg config flags.\n    for pkgConfigName in pkgConfigNames.components(separatedBy: \" \") {\n        let result: PkgConfigResult\n        do {\n            let pkgConfig = try PkgConfig(\n                name: pkgConfigName,\n                additionalSearchPaths: additionalSearchPaths,\n                brewPrefix: brewPrefix,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n\n            // Run the allow list checker.\n            let filtered = try allowlist(pcFile: pkgConfigName, flags: (pkgConfig.cFlags, pkgConfig.libs))\n\n            // Remove any default flags which compiler adds automatically.\n            var (cFlags, libs) = try removeDefaultFlags(cFlags: filtered.cFlags, libs: filtered.libs)\n\n            // Patch any paths containing an SDK to the current SDK\n            // See https://github.com/swiftlang/swift-package-manager/issues/6439\n            if let sdkRootPath = sdkRootPath {\n                cFlags = try patchSDKPaths(in: cFlags, to: sdkRootPath)\n                libs = try patchSDKPaths(in: libs, to: sdkRootPath)\n            }\n\n            // Set the error if there are any disallowed flags.\n            var error: Swift.Error?\n            if !filtered.disallowed.isEmpty {\n                error = PkgConfigError.prohibitedFlags(filtered.disallowed.joined(separator: \", \"))\n            }\n\n            result = PkgConfigResult(\n                pkgConfigName: pkgConfigName,\n                cFlags: cFlags,\n                libs: libs,\n                error: error,\n                provider: provider\n            )\n        } catch {\n            result = PkgConfigResult(pkgConfigName: pkgConfigName, error: error, provider: provider)\n        }\n\n        // If there is no pc file on system and we have an available provider, emit a warning.\n        if let provider = result.provider, result.couldNotFindConfigFile {\n            observabilityScope.emit(\n                warning: \"you may be able to install \\(result.pkgConfigName) using your system-packager:\\n\\(provider.installText)\"\n            )\n        } else if let error = result.error {\n            observabilityScope.emit(\n                warning: error.interpolationDescription,\n                metadata: .pkgConfig(pcFile: result.pkgConfigName, targetName: target.name)\n            )\n        }\n\n        ret.append(result)\n    }\n    return ret\n}\n\nextension SystemPackageProviderDescription {\n    public var installText: String {\n        switch self {\n        case .brew(let packages):\n            return \"    brew install \\(packages.joined(separator: \" \"))\\n\"\n        case .apt(let packages):\n            return \"    apt-get install \\(packages.joined(separator: \" \"))\\n\"\n        case .yum(let packages):\n            return \"    yum install \\(packages.joined(separator: \" \"))\\n\"\n        case .nuget(let packages):\n            return \"    nuget install \\(packages.joined(separator: \" \"))\\n\"\n        case .pkg(let packages):\n            return \"    pkg install \\(packages.joined(separator: \" \"))\\n\"\n        }\n    }\n\n    /// Check if the provider is available for the current platform.\n    var isAvailable: Bool {\n        guard let platform = Platform.current else { return false }\n        switch self {\n        case .brew:\n            if case .darwin = platform {\n                return true\n            }\n        case .apt:\n            if case .linux(.debian) = platform {\n                return true\n            }\n            if case .android = platform {\n                return true\n            }\n        case .yum:\n            if case .linux(.fedora) = platform {\n                return true\n            }\n        case .nuget:\n            switch platform {\n            case .darwin, .windows, .linux:\n                return true\n            case .android, .freebsd:\n                return false\n            }\n        case .pkg:\n            if case .freebsd = platform {\n                return true\n            }\n        }\n        return false\n    }\n\n    func pkgConfigSearchPath(brewPrefixOverride: AbsolutePath?) throws -> [AbsolutePath] {\n        switch self {\n        case .brew(let packages):\n            let brewPrefix: String\n            if let brewPrefixOverride {\n                brewPrefix = brewPrefixOverride.pathString\n            } else {\n                // Homebrew can have multiple versions of the same package. The\n                // user can choose another version than the latest by running\n                // ``brew switch NAME VERSION``, so we shouldn't assume to link\n                // to the latest version. Instead use the version as symlinked\n                // in /usr/local/opt/(NAME)/lib/pkgconfig.\n                struct Static {\n                    static let value = { try? AsyncProcess.checkNonZeroExit(args: \"brew\", \"--prefix\").spm_chomp() }()\n                }\n                if let value = Static.value {\n                    brewPrefix = value\n                } else {\n                    return []\n                }\n            }\n            return try packages.map({ try AbsolutePath(validating: brewPrefix).appending(components: \"opt\", $0, \"lib\", \"pkgconfig\") })\n        case .apt:\n            return []\n        case .yum:\n            return []\n        case .nuget:\n            return []\n        case .pkg:\n            return []\n        }\n    }\n\n    // FIXME: Get rid of this method once we move on to new Build code.\n    static func providerForCurrentPlatform(providers: [SystemPackageProviderDescription]) -> SystemPackageProviderDescription? {\n        return providers.first(where: { $0.isAvailable })\n    }\n}\n\n/// Filters the flags with allowed arguments so unexpected arguments are not passed to\n/// compiler/linker. List of allowed flags:\n/// cFlags: -I, -F\n/// libs: -L, -l, -F, -framework, -w\npublic func allowlist(\n    pcFile: String,\n    flags: (cFlags: [String], libs: [String])\n) throws -> (cFlags: [String], libs: [String], disallowed: [String]) {\n    // Returns a tuple with the array of allowed flag and the array of disallowed flags.\n    func filter(flags: [String], filters: [String]) throws -> (allowed: [String], disallowed: [String]) {\n        var allowed = [String]()\n        var disallowed = [String]()\n        var it = flags.makeIterator()\n        while let flag = it.next() {\n            guard let filter = filters.filter({ flag.hasPrefix($0) }).first else {\n                disallowed += [flag]\n                continue\n            }\n\n          // Warning suppression flag has no arguments and is not suffixed.\n          guard !flag.hasPrefix(\"-w\") || flag == \"-w\" else {\n            disallowed += [flag]\n            continue\n          }\n\n            // If the flag and its value are separated, skip next flag.\n            if flag == filter && flag != \"-w\" {\n                guard let associated = it.next() else {\n                    throw InternalError(\"Expected associated value\")\n                }\n                if flag == \"-framework\" {\n                    allowed += [flag, associated]\n                    continue\n                }\n            }\n            allowed += [flag]\n        }\n        return (allowed, disallowed)\n    }\n\n    let filteredCFlags = try filter(flags: flags.cFlags, filters: [\"-I\", \"-F\"])\n    let filteredLibs = try filter(flags: flags.libs, filters: [\"-L\", \"-l\", \"-F\", \"-framework\", \"-w\"])\n\n    return (filteredCFlags.allowed, filteredLibs.allowed, filteredCFlags.disallowed + filteredLibs.disallowed)\n}\n\n/// Maps values of the given flag with the given transform, removing those where the transform returns `nil`.\nprivate func patch(flag: String, in flags: [String], transform: (String) -> String?) throws -> [String] {\n    var result = [String]()\n    var it = flags.makeIterator()\n    while let current = it.next() {\n        if current == flag {\n            // Handle <flag><space><value> style.\n            guard let value = it.next() else {\n                throw InternalError(\"Expected associated value\")\n            }\n            if let newValue = transform(value) {\n                result.append(flag)\n                result.append(newValue)\n            }\n        } else if current.starts(with: flag) {\n            // Handle <flag><value> style\n            let value = String(current.dropFirst(flag.count))\n            if let newValue = transform(value) {\n                result.append(flag + newValue)\n            }\n        } else {\n            // Leave other flags as-is\n            result.append(current)\n        }\n    }\n    return result\n}\n\n/// Removes the given flag from the given flags.\nprivate func remove(flag: String, with expectedValue: String, from flags: [String]) throws -> [String] {\n    try patch(flag: flag, in: flags) { value in value == expectedValue ? nil : value }\n}\n\n/// Remove the default flags which are already added by the compiler.\n///\n/// This behavior is similar to pkg-config cli tool and helps avoid conflicts between\n/// sdk and default search paths in macOS.\npublic func removeDefaultFlags(cFlags: [String], libs: [String]) throws -> ([String], [String]) {\n    return (\n        try remove(flag: \"-I\", with: \"/usr/include\", from: cFlags),\n        try remove(flag: \"-L\", with: \"/usr/lib\", from: libs)\n    )\n}\n\n/// Replaces any path containing *.sdk with the current SDK to avoid conflicts.\n///\n/// See https://github.com/swiftlang/swift-package-manager/issues/6439 for details.\npublic func patchSDKPaths(in flags: [String], to sdkRootPath: AbsolutePath) throws -> [String] {\n    let sdkRegex = try! RegEx(pattern: #\"^.*\\.sdk(\\/.*|$)\"#)\n\n    return try [\"-I\", \"-L\"].reduce(flags) { (flags, flag) in\n        try patch(flag: flag, in: flags) { value in\n            guard let groups = sdkRegex.matchGroups(in: value).first else {\n                return value\n            }\n            return sdkRootPath.pathString + groups[0]\n        }\n    }\n}\n\nextension ObservabilityMetadata {\n    public static func pkgConfig(pcFile: String, targetName: String) -> Self {\n        var metadata = ObservabilityMetadata()\n        metadata.pcFile = \"\\(pcFile).pc\"\n        metadata.moduleName = targetName\n        return metadata\n    }\n}\n\nextension ObservabilityMetadata {\n    public var pcFile: String? {\n        get {\n            self[pcFileKey.self]\n        }\n        set {\n            self[pcFileKey.self] = newValue\n        }\n    }\n\n    enum pcFileKey: Key {\n        typealias Value = String\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/TargetSourcesBuilder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport OrderedCollections\nimport PackageModel\nimport TSCBasic\n\n/// A utility to compute the source/resource files of a target.\npublic struct TargetSourcesBuilder {\n    /// The package identity.\n    public let packageIdentity: PackageIdentity\n\n    /// The package kind.\n    public let packageKind: PackageReference.Kind\n\n    /// The package path.\n    public let packagePath: Basics.AbsolutePath\n\n    /// The target for which we're computing source/resource files.\n    public let target: TargetDescription\n\n    /// The path of the target.\n    public let targetPath: Basics.AbsolutePath\n\n    /// The list of declared sources in the package manifest.\n    public let declaredSources: OrderedCollections.OrderedSet<Basics.AbsolutePath>?\n\n    /// The list of declared resources in the package manifest.\n    public let declaredResources: [(path: Basics.AbsolutePath, rule: TargetDescription.Resource.Rule)]\n\n    /// The default localization.\n    public let defaultLocalization: String?\n\n    /// The rules that can be applied to files in the target.\n    public let rules: [FileRuleDescription]\n\n    /// The tools version associated with the target's package.\n    public let toolsVersion: ToolsVersion\n\n    /// The set of paths that should be excluded from any consideration.\n    public let excludedPaths: Set<Basics.AbsolutePath>\n\n    /// The set of opaque directories extensions (should not be treated as source)\n    private let opaqueDirectoriesExtensions: Set<String>\n\n    /// The file system to operate on.\n    private let fileSystem: FileSystem\n\n    /// ObservabilityScope with which to emit diagnostics\n    private let observabilityScope: ObservabilityScope\n\n    /// Create a new target builder.\n    public init(\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packagePath: Basics.AbsolutePath,\n        target: TargetDescription,\n        path: Basics.AbsolutePath,\n        defaultLocalization: String?,\n        additionalFileRules: [FileRuleDescription],\n        toolsVersion: ToolsVersion,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.packageIdentity = packageIdentity\n        self.packageKind = packageKind\n        self.packagePath = packagePath\n        self.target = target\n        self.defaultLocalization = defaultLocalization\n        self.targetPath = path\n        self.rules = Self.rules(additionalFileRules: additionalFileRules, toolsVersion: toolsVersion)\n        self.toolsVersion = toolsVersion\n        let excludedPaths = target.exclude.compactMap { try? AbsolutePath(validating: $0, relativeTo: path) }\n        self.excludedPaths = Set(excludedPaths)\n        self.opaqueDirectoriesExtensions = FileRuleDescription.opaqueDirectoriesExtensions.union(\n            additionalFileRules.reduce(into: Set<String>(), { partial, item in\n                partial.formUnion(item.fileTypes)\n            })\n        )\n        self.fileSystem = fileSystem\n\n        let childObservabilityScope = observabilityScope.makeChildScope(description: \"TargetSourcesBuilder\") {\n            var metadata = ObservabilityMetadata.packageMetadata(identity: packageIdentity, kind: packageKind)\n            metadata.moduleName = target.name\n            return metadata\n        }\n        self.observabilityScope = childObservabilityScope\n\n        var declaredSources: OrderedCollections.OrderedSet<Basics.AbsolutePath>? = nil\n\n        if let targetSources = target.sources {\n            for targetSource in targetSources {\n                if let targetSourcePath = try? AbsolutePath(validating: targetSource, relativeTo: path) {\n                    declaredSources = declaredSources ?? OrderedCollections.OrderedSet<Basics.AbsolutePath>()\n                    if declaredSources?.updateOrAppend(targetSourcePath) != nil {\n                        childObservabilityScope.emit(warning: \"found duplicate sources declaration in the package manifest: \\(targetSourcePath.pathString)\")\n\n                    }\n                }\n            }\n        }\n\n        self.declaredSources = declaredSources\n\n        self.declaredResources = (try? target.resources.map {\n            (path: try AbsolutePath(validating: $0.path, relativeTo: path), rule: $0.rule)\n        }) ?? []\n\n        self.excludedPaths.forEach { exclude in\n            if let message = validTargetPath(at: exclude), self.packageKind.emitAuthorWarnings {\n                let warning = \"Invalid Exclude '\\(exclude)': \\(message).\"\n                self.observabilityScope.emit(warning: warning)\n            }\n        }\n\n        self.declaredSources?.forEach { source in\n            if let message = validTargetPath(at: source) {\n                let warning = \"Invalid Source '\\(source)': \\(message).\"\n                self.observabilityScope.emit(warning: warning)\n            }\n        }\n\n      #if DEBUG\n        validateRules(self.rules)\n      #endif\n    }\n\n    private static func rules(additionalFileRules: [FileRuleDescription], toolsVersion: ToolsVersion) -> [FileRuleDescription] {\n        // In version 5.4 and earlier, SwiftPM did not support `additionalFileRules` and always implicitly included XCBuild file types.\n        let actualAdditionalRules = (toolsVersion <= .v5_4 ? FileRuleDescription.xcbuildFileTypes : additionalFileRules)\n        return FileRuleDescription.builtinRules + actualAdditionalRules\n    }\n\n    @discardableResult\n    private func validTargetPath(at: Basics.AbsolutePath) -> Error? {\n        // Check if paths that are enumerated in targets: [] exist\n        guard self.fileSystem.exists(at) else {\n            return StringError(\"File not found\")\n        }\n\n        // Excludes, Sources, and Resources should be found at the root of the package and or\n        // its subdirectories\n        guard at.pathString.hasPrefix(self.packagePath.pathString) else {\n            return StringError(\"File must be within the package directory structure\")\n        }\n\n        return nil\n    }\n\n    /// Emits an error in debug mode if we have conflicting rules for any file type.\n    private func validateRules(_ rules: [FileRuleDescription]) {\n        var extensionMap: [String: FileRuleDescription] = [:]\n        for rule in rules {\n            for ext in rule.fileTypes {\n                if let existingRule = extensionMap[ext] {\n                    self.observabilityScope.emit(error: \"conflicting rules \\(rule) and \\(existingRule) for extension \\(ext)\")\n                }\n                extensionMap[ext] = rule\n            }\n        }\n    }\n\n    /// Run the builder to produce the sources of the target.\n    public func run() throws -> (sources: Sources, resources: [Resource], headers: [Basics.AbsolutePath], ignored: [Basics.AbsolutePath], others: [Basics.AbsolutePath]) {\n        let contents = self.computeContents()\n        var pathToRule: [Basics.AbsolutePath: FileRuleDescription.Rule] = [:]\n\n        var handledResources = [Basics.AbsolutePath]()\n        for path in contents {\n            pathToRule[path] = Self.computeRule(\n                for: path,\n                toolsVersion: toolsVersion,\n                rules: rules,\n                declaredResources: declaredResources,\n                declaredSources: declaredSources,\n                matchingResourceRuleHandler: {\n                    handledResources.append($0)\n                },\n                observabilityScope: observabilityScope\n            )\n        }\n\n        let additionalResources: [Resource]\n        if toolsVersion >= .v6_0 {\n            additionalResources = declaredResources.compactMap { resource in\n                if handledResources.contains(resource.path) {\n                    return nil\n                } else {\n                    self.observabilityScope.emit(info: \"Found unhandled resource at \\(resource.path)\")\n                    return self.resource(for: resource.path, with: .init(resource.rule))\n                }\n            }\n        } else {\n            additionalResources = []\n        }\n\n        let headers = pathToRule.lazy.filter { $0.value == .header }.map { $0.key }.sorted()\n        let compilePaths = pathToRule.lazy.filter { $0.value == .compile }.map { $0.key }\n        let sources = Sources(paths: Array(compilePaths).sorted(), root: targetPath)\n        let resources: [Resource] = (pathToRule.compactMap { resource(for: $0.key, with: $0.value) } + additionalResources).sorted { a, b in\n            a.path.pathString < b.path.pathString\n        }\n        let ignored = pathToRule.filter { $0.value == .ignored }.map { $0.key }.sorted()\n        let others = pathToRule.filter { $0.value == .none }.map { $0.key }.sorted()\n\n        try diagnoseConflictingResources(in: resources)\n        diagnoseCopyConflictsWithLocalizationDirectories(in: resources)\n        diagnoseLocalizedAndUnlocalizedVariants(in: resources)\n        try diagnoseInfoPlistConflicts(in: resources)\n        diagnoseInvalidResource(in: target.resources)\n\n        // It's an error to contain mixed language source files.\n        if sources.containsMixedLanguage {\n            throw Module.Error.mixedSources(targetPath)\n        }\n\n        return (sources, resources, headers, ignored, others)\n    }\n\n    /// Compute the rule for the given path.\n    private static func computeRule(for path: Basics.AbsolutePath,\n                                    toolsVersion: ToolsVersion,\n                                    additionalFileRules: [FileRuleDescription],\n                                    observabilityScope: ObservabilityScope) -> FileRuleDescription.Rule {\n        let rules = Self.rules(additionalFileRules: additionalFileRules, toolsVersion: toolsVersion)\n        // For now, we are not passing in any declared resources or sources here and instead handle any generated files automatically at the callsite. Eventually, we will want the ability to declare opinions for generated files in the manifest as well.\n        return Self.computeRule(for: path, toolsVersion: toolsVersion, rules: rules, declaredResources: [], declaredSources: nil, observabilityScope: observabilityScope)\n    }\n\n    private static func computeRule(\n        for path: Basics.AbsolutePath, \n        toolsVersion: ToolsVersion,\n        rules: [FileRuleDescription],\n        declaredResources: [(path: Basics.AbsolutePath, rule: TargetDescription.Resource.Rule)],\n        declaredSources: OrderedCollections.OrderedSet<Basics.AbsolutePath>?,\n        matchingResourceRuleHandler: (Basics.AbsolutePath) -> () = { _ in },\n        observabilityScope: ObservabilityScope\n    ) -> FileRuleDescription.Rule {\n        var matchedRule: FileRuleDescription.Rule = .none\n\n        // First match any resources explicitly declared in the manifest file.\n        for declaredResource in declaredResources {\n            let resourcePath = declaredResource.path\n            if path.isDescendantOfOrEqual(to: resourcePath) {\n                if matchedRule != .none {\n                    observabilityScope.emit(error: \"duplicate resource rule '\\(declaredResource.rule)' found for file at '\\(path)'\")\n                }\n                matchedRule = .init(declaredResource.rule)\n                matchingResourceRuleHandler(declaredResource.path)\n            }\n        }\n\n        // Match any sources explicitly declared in the manifest file.\n        if let declaredSources {\n            if isDescendantOfOrEqualToAny(path, declaredSources) {\n                if matchedRule != .none {\n                    observabilityScope.emit(error: \"duplicate rule found for file at '\\(path)'\")\n                }\n\n                    // Check for header files as they're allowed to be mixed with sources.\n                    if let ext = path.extension,\n                      FileRuleDescription.header.fileTypes.contains(ext) {\n                        matchedRule = .header\n                    } else if toolsVersion >= .v5_3 {\n                        matchedRule = .compile\n                    } else if let ext = path.extension,\n                      SupportedLanguageExtension.validExtensions(toolsVersion: toolsVersion).contains(ext) {\n                        matchedRule = .compile\n                    }\n                    // The source file might have been declared twice so\n                    // exit on first match.\n                    // FIXME: We should emitting warnings for duplicate// declarations.\n                }\n            }\n\n        // We haven't found a rule using that's explicitly declared in the manifest\n        // so try doing an automatic match.\n        if matchedRule == .none {\n            let effectiveRules: [FileRuleDescription] = {\n                // Don't automatically match compile rules if target's sources are\n                // explicitly declared in the package manifest.\n                if declaredSources != nil {\n                    return rules.filter { $0.rule != .compile }\n                }\n                return rules\n            }()\n\n            if let needle = effectiveRules.first(where: { $0.match(path: path, toolsVersion: toolsVersion) }) {\n                matchedRule = needle.rule\n            } else if path.parentDirectory.extension == Resource.localizationDirectoryExtension {\n                matchedRule = .processResource(localization: .none)\n            }\n        }\n\n        return matchedRule\n    }\n    \n    private static func isDescendantOfOrEqualToAny(_ path: Basics.AbsolutePath, _ ancestorPaths: OrderedCollections.OrderedSet<Basics.AbsolutePath>) -> Bool {\n        var currentPath = path\n        while true {\n            if ancestorPaths.contains(currentPath) {\n                return true\n            }\n\n            let parentPath = currentPath.parentDirectory\n            if parentPath == currentPath {\n                break\n            }\n            currentPath = parentPath\n        }\n\n        return false\n    }\n\n    /// Returns the `Resource` file associated with a file and a particular rule, if there is one.\n    private static func resource(for path: Basics.AbsolutePath, with rule: FileRuleDescription.Rule, defaultLocalization: String?, targetName: String, targetPath: Basics.AbsolutePath, observabilityScope: ObservabilityScope) -> Resource? {\n        switch rule {\n        case .compile, .header, .none, .modulemap, .apinotes, .ignored:\n            return nil\n        case .processResource:\n            let implicitLocalization: String? = {\n                if path.parentDirectory.extension == Resource.localizationDirectoryExtension {\n                    return path.parentDirectory.basenameWithoutExt\n                } else {\n                    return nil\n                }\n            }()\n\n            let explicitLocalization: String? = {\n                switch rule  {\n                case .processResource(localization: .default):\n                    return defaultLocalization ?? \"en\"\n                case .processResource(localization: .base):\n                    return \"Base\"\n                default:\n                    return .none\n                }\n            }()\n\n            // If a resource is both inside a localization directory and has an explicit localization, it's ambiguous.\n            guard implicitLocalization == nil || explicitLocalization == nil else {\n                let relativePath = path.relative(to: targetPath)\n                observabilityScope.emit(.localizationAmbiguity(path: relativePath, targetName: targetName))\n                return nil\n            }\n\n            return Resource(rule: .process(localization: implicitLocalization ?? explicitLocalization), path: path)\n        case .copyResource:\n            return Resource(rule: .copy, path: path)\n        case .embedResourceInCode:\n            return Resource(rule: .embedInCode, path: path)\n        }\n    }\n\n    private func resource(for path: Basics.AbsolutePath, with rule: FileRuleDescription.Rule) -> Resource? {\n        return Self.resource(for: path, with: rule, defaultLocalization: defaultLocalization, targetName: target.name, targetPath: targetPath, observabilityScope: observabilityScope)\n    }\n\n    private func diagnoseConflictingResources(in resources: [Resource]) throws {\n        let duplicateResources = resources.spm_findDuplicateElements(by: \\.destinationForGrouping)\n        for resources in duplicateResources {\n            try self.observabilityScope.emit(.conflictingResource(path: resources[0].destination, targetName: target.name))\n\n            for resource in resources {\n                let relativePath = resource.path.relative(to: targetPath)\n                self.observabilityScope.emit(.fileReference(path: relativePath))\n            }\n        }\n    }\n\n    private func diagnoseCopyConflictsWithLocalizationDirectories(in resources: [Resource]) {\n        let localizationDirectories = Set(resources\n            .lazy\n            .compactMap({ $0.localization })\n            .map({ \"\\($0).\\(Resource.localizationDirectoryExtension)\" }))\n\n        for resource in resources where resource.rule == .copy {\n            if localizationDirectories.contains(resource.path.basename.lowercased()) {\n                let relativePath = resource.path.relative(to: targetPath)\n                self.observabilityScope.emit(.copyConflictWithLocalizationDirectory(path: relativePath, targetName: target.name))\n            }\n        }\n    }\n\n    private func diagnoseLocalizedAndUnlocalizedVariants(in resources: [Resource]) {\n        let resourcesByBasename = Dictionary(grouping: resources, by: { $0.path.basename })\n        for (basename, resources) in resourcesByBasename {\n            let hasLocalizations = resources.contains(where: { $0.localization != nil })\n            let hasUnlocalized = resources.contains(where: { $0.localization == nil })\n            if hasLocalizations && hasUnlocalized {\n                self.observabilityScope.emit(.localizedAndUnlocalizedVariants(resource: basename, targetName: target.name))\n            }\n        }\n    }\n\n    private func diagnoseInfoPlistConflicts(in resources: [Resource]) throws {\n        for resource in resources {\n            if try resource.destination == RelativePath(validating: \"Info.plist\") {\n                self.observabilityScope.emit(.infoPlistResourceConflict(\n                    path: resource.path.relative(to: targetPath),\n                    targetName: target.name))\n            }\n        }\n    }\n\n    private func diagnoseInvalidResource(in resources: [TargetDescription.Resource]) {\n        resources.forEach { resource in\n            guard let resourcePath = try? AbsolutePath(validating: resource.path, relativeTo: self.targetPath) else {\n                return\n            }\n            if let message = validTargetPath(at: resourcePath), self.packageKind.emitAuthorWarnings {\n                let warning = \"Invalid Resource '\\(resource.path)': \\(message).\"\n                self.observabilityScope.emit(warning: warning)\n            }\n        }\n    }\n\n    /// Returns true if the given path is a declared source.\n    func isDeclaredSource(_ path: Basics.AbsolutePath) -> Bool {\n        return path == targetPath || declaredSources?.contains(path) == true\n    }\n\n    /// Compute the contents of the files in a target.\n    ///\n    /// This avoids recursing into certain directories like exclude or the\n    /// ones that should be copied as-is.\n    public func computeContents() -> [Basics.AbsolutePath] {\n        var contents: [Basics.AbsolutePath] = []\n        var queue: [Basics.AbsolutePath] = [targetPath]\n\n        // Ignore xcodeproj and playground directories.\n        var ignoredDirectoryExtensions = [\"xcodeproj\", \"playground\", \"xcworkspace\"]\n\n        // Ignore localization directories if not supported.\n        if toolsVersion < .v5_3 {\n            ignoredDirectoryExtensions.append(Resource.localizationDirectoryExtension)\n        }\n\n        while let path = queue.popLast() {\n            // Ignore dot files.\n            if path.basename.hasPrefix(\".\") { continue }\n\n            if let ext = path.extension, ignoredDirectoryExtensions.contains(ext) {\n                continue\n            }\n\n            // Ignore manifest files.\n            if path.parentDirectory == self.packagePath {\n                if path.basename == Manifest.filename { continue }\n                if path.basename == \"Package.resolved\" { continue }\n\n                // Ignore version-specific manifest files.\n                if path.basename.hasPrefix(Manifest.basename + \"@\") && path.extension == \"swift\" {\n                    continue\n                }\n            }\n\n            // Ignore if this is an excluded path.\n            if self.excludedPaths.contains(path) { continue }\n\n            if self.fileSystem.isSymlink(path) && !self.fileSystem.exists(path, followSymlink: true) {\n                self.observabilityScope.emit(.brokenSymlink(path))\n                continue\n            }\n\n            // Consider non-directories as source files.\n            if !self.fileSystem.isDirectory(path) {\n                contents.append(path)\n                continue\n            }\n\n            // At this point, path can only be a directory.\n            //\n            // Starting tools version with resources, treat directories of known extension as resources\n            // ie, do not include their content, and instead treat the directory itself as the content\n            if toolsVersion >= .v5_6 {\n                if let directoryExtension = path.extension,\n                   self.opaqueDirectoriesExtensions.contains(directoryExtension),\n                   directoryExtension != Resource.localizationDirectoryExtension,\n                   !isDeclaredSource(path)\n                {\n                    contents.append(path)\n                    continue\n                }\n            } else if toolsVersion >= .v5_3 {\n                // maintain the broken behavior prior to fixing it in 5.6\n                // see rdar://82933763\n                if let directoryExtension = path.extension,\n                   directoryExtension != Resource.localizationDirectoryExtension,\n                   !isDeclaredSource(path)\n                {\n                    contents.append(path)\n                    continue\n                }\n            }\n\n            // Check if the directory is marked to be copied.\n            let directoryMarkedToBeCopied = target.resources.contains{ resource in\n                let resourcePath = try? AbsolutePath(validating: resource.path, relativeTo: self.targetPath)\n                if resource.rule == .copy && resourcePath == path {\n                    return true\n                }\n                return false\n            }\n\n            // If the directory is marked to be copied, don't look inside it.\n            if directoryMarkedToBeCopied {\n                contents.append(path)\n                continue\n            }\n\n            // We found a directory inside a localization directory, which is forbidden.\n            if path.parentDirectory.extension == Resource.localizationDirectoryExtension {\n                let relativePath = path.parentDirectory.relative(to: targetPath)\n                self.observabilityScope.emit(.localizationDirectoryContainsSubDirectories(\n                    localizationDirectory: relativePath,\n                    targetName: target.name))\n                continue\n            }\n\n            // Otherwise, add its content to the queue.\n            let dirContents = self.observabilityScope.trap {\n                try self.fileSystem.getDirectoryContents(path).map({ path.appending(component: $0) })\n            }\n            queue += dirContents ?? []\n        }\n\n        return contents\n    }\n\n    public static func computeContents(\n        for generatedFiles: [Basics.AbsolutePath],\n        toolsVersion: ToolsVersion,\n        additionalFileRules: [FileRuleDescription],\n        defaultLocalization: String?,\n        module: Module,\n        observabilityScope: ObservabilityScope) -> GeneratedFiles\n    {\n        var files = GeneratedFiles()\n\n        generatedFiles.forEach { absPath in\n            // 5.6 handled treated all generated files as sources.\n            if toolsVersion <= .v5_6 {\n                files.sources.append(absPath)\n                return\n            }\n\n            var rule = Self.computeRule(for: absPath, toolsVersion: toolsVersion, additionalFileRules: additionalFileRules, observabilityScope: observabilityScope)\n\n            // If we did not find a rule for a generated file, we treat it as to be processed for now. Eventually, we should handle generated files the same as other files and require explicit handling in the manifest for unknown types.\n            if rule == .none {\n                rule = .processResource(localization: .none)\n            }\n\n            switch rule {\n            case .compile:\n                if absPath.extension == \"swift\" {\n                    files.sources.append(absPath)\n                } else if toolsVersion.experimentalCGen {\n                    if module is ClangModule {\n                        files.sources.append(absPath)\n                    } else {\n                        observabilityScope.emit(warning: \"Only C modules support plugin generated C source files: \\(absPath)\")\n                    }\n                } else {\n                    observabilityScope.emit(warning: \"C source file generation not enabled: \\(absPath)\")\n                }\n            case .copyResource, .processResource, .embedResourceInCode:\n                if let resource = Self.resource(for: absPath, with: rule, defaultLocalization: defaultLocalization, targetName: module.name, targetPath: module.path, observabilityScope: observabilityScope) {\n                    files.resources[resource.path] = resource\n                } else {\n                    // If this is reached, `TargetSourcesBuilder` already emitted a diagnostic, so we can ignore this case here.\n                }\n            case .header:\n                if toolsVersion.experimentalCGen {\n                    if module is ClangModule {\n                        files.headers.append(absPath)\n                    } else {\n                        observabilityScope.emit(warning: \"Only C modules support plugin generated C header files: \\(absPath)\")\n                    }\n                } else {\n                    observabilityScope.emit(warning: \"C header file generation not enabled: \\(absPath)\")\n                }\n            case .modulemap:\n                if toolsVersion.experimentalCGen {\n                    if module is ClangModule {\n                        files.moduleMaps.append(absPath)\n                    } else {\n                        observabilityScope.emit(warning: \"Only C modules support plugin generated module map files: \\(absPath)\")\n                    }\n                } else {\n                    observabilityScope.emit(warning: \"Module map generation not enabled: \\(absPath)\")\n                }\n            case .apinotes:\n                if toolsVersion.experimentalCGen {\n                    if module is ClangModule {\n                        files.apiNotes.append(absPath)\n                    } else {\n                        observabilityScope.emit(warning: \"Only C modules support plugin generated API notes files: \\(absPath)\")\n                    }\n                } else {\n                    observabilityScope.emit(warning: \"API notes generation not enabled: \\(absPath)\")\n                }\n            case .ignored, .none:\n                break\n            }\n        }\n\n        return files\n    }\n}\n\npublic struct GeneratedFiles {\n    public var publicHeaderPaths: [Basics.AbsolutePath] = []\n    public var sources: [Basics.AbsolutePath]\n    public var headers: [Basics.AbsolutePath]\n    public var moduleMaps: [Basics.AbsolutePath]\n    public var apiNotes: [Basics.AbsolutePath]\n    public var resources: [Basics.AbsolutePath: Resource]\n\n    public init(\n        sources: [Basics.AbsolutePath] = [],\n        headers: [Basics.AbsolutePath] = [],\n        moduleMaps: [Basics.AbsolutePath] = [],\n        apiNotes: [Basics.AbsolutePath] = [],\n        resources: [Basics.AbsolutePath: Resource] = [:])\n    {\n        self.sources = sources\n        self.headers = headers\n        self.moduleMaps = moduleMaps\n        self.apiNotes = apiNotes\n        self.resources = resources\n    }\n\n    public mutating func add(_ other: GeneratedFiles) {\n        sources.append(contentsOf: other.sources)\n        headers.append(contentsOf: other.headers)\n        moduleMaps.append(contentsOf: other.moduleMaps)\n        apiNotes.append(contentsOf: other.apiNotes)\n        resources.merge(other.resources, uniquingKeysWith: { winner, _ in winner })\n    }\n}\n\n/// Describes a rule for including a source or resource file in a target.\npublic struct FileRuleDescription: Sendable {\n    /// A rule semantically describes a file/directory in a target.\n    ///\n    /// It is up to the build system to translate a rule into a build command.\n    public enum Rule: Equatable, Sendable {\n        /// The compile rule for `sources` in a package.\n        case compile\n\n        /// Process resource file rule for any type of platform-specific processing.\n        ///\n        /// This defaults to copy if there's no specialized behavior.\n        case processResource(localization: TargetDescription.Resource.Localization?)\n\n        /// The embed rule.\n        case embedResourceInCode\n\n        /// The copy rule.\n        case copyResource\n\n        /// The modulemap rule.\n        case modulemap\n\n        /// A header file.\n        case header\n\n        /// An apinotes file, needs to be located in same directory as module map\n        case apinotes\n\n        /// Indicates that the file should be treated as ignored, without causing an unhandled-file warning.\n        case ignored\n\n        /// Sentinel to indicate that no rule was chosen for a given file.\n        case none\n    }\n\n    /// The rule associated with this description.\n    public let rule: Rule\n\n    /// The tools version supported by this rule.\n    public let toolsVersion: ToolsVersion\n\n    /// The list of file extensions support by this rule.\n    ///\n    /// No two rule can have the same file extension.\n    public let fileTypes: Set<String>\n\n    public init(rule: Rule, toolsVersion: ToolsVersion, fileTypes: Set<String>) {\n        self.rule = rule\n        self.toolsVersion = toolsVersion\n        self.fileTypes = fileTypes\n    }\n\n    /// Match the given path to the rule.\n    public func match(path: Basics.AbsolutePath, toolsVersion: ToolsVersion) -> Bool {\n        if toolsVersion < self.toolsVersion {\n            return false\n        }\n\n        if let ext = path.extension {\n            return self.fileTypes.contains(ext)\n        }\n        return false\n    }\n\n    /// The swift compiler rule.\n    public static let swift: FileRuleDescription = {\n        .init(\n            rule: .compile,\n            toolsVersion: .minimumRequired,\n            fileTypes: [\"swift\"]\n        )\n    }()\n\n    /// The clang compiler rule.\n    public static let clang: FileRuleDescription = {\n        .init(\n            rule: .compile,\n            toolsVersion: .minimumRequired,\n            fileTypes: [\"c\", \"m\", \"mm\", \"cc\", \"cpp\", \"cxx\"]\n        )\n    }()\n\n    /// The rule for compiling asm files.\n    public static let asm: FileRuleDescription = {\n        .init(\n            rule: .compile,\n            toolsVersion: .v5,\n            fileTypes: [\"s\", \"S\"]\n        )\n    }()\n\n    /// The rule for detecting modulemap files.\n    public static let modulemap: FileRuleDescription = {\n        .init(\n            rule: .modulemap,\n            toolsVersion: .minimumRequired,\n            fileTypes: [\"modulemap\"]\n        )\n    }()\n\n    /// the rule for detecting apinotes files.\n    public static let apinotes: FileRuleDescription = {\n        .init(\n            rule: .apinotes,\n            toolsVersion: .minimumRequired,\n            fileTypes: [\"apinotes\"]\n        )\n    }()\n\n    /// The rule for detecting header files.\n    public static let header: FileRuleDescription = {\n        .init(\n            rule: .header,\n            toolsVersion: .minimumRequired,\n            fileTypes: [\"h\", \"hh\", \"hpp\", \"h++\", \"hp\", \"hxx\", \"H\", \"ipp\", \"def\"]\n        )\n    }()\n\n    /// File types related to the interface builder and storyboards.\n    public static let xib: FileRuleDescription = {\n        .init(\n            rule: .processResource(localization: .none),\n            toolsVersion: .v5_3,\n            fileTypes: [\"nib\", \"xib\", \"storyboard\"]\n        )\n    }()\n\n    /// File types related to the asset catalog.\n    public static let assetCatalog: FileRuleDescription = {\n        .init(\n            rule: .processResource(localization: .none),\n            toolsVersion: .v5_3,\n            fileTypes: [\"xcassets\"]\n        )\n    }()\n\n    /// File types related to the string catalog.\n    public static let stringCatalog: FileRuleDescription = {\n        .init(\n            rule: .processResource(localization: .none),\n            toolsVersion: .v5_9,\n            fileTypes: [\"xcstrings\"]\n        )\n    }()\n\n    /// File types related to the CoreData.\n    public static let coredata: FileRuleDescription = {\n        .init(\n            rule: .processResource(localization: .none),\n            toolsVersion: .v5_3,\n            fileTypes: [\"xcdatamodeld\", \"xcdatamodel\", \"xcmappingmodel\"]\n        )\n    }()\n\n    /// File types related to Metal.\n    public static let metal: FileRuleDescription = {\n        .init(\n            rule: .processResource(localization: .none),\n            toolsVersion: .v5_3,\n            fileTypes: [\"metal\"]\n        )\n    }()\n\n    /// File rule to ignore .docc (in the SwiftPM build system).\n    public static let docc: FileRuleDescription = {\n        .init(\n            rule: .ignored,\n            toolsVersion: .v5_5,\n            fileTypes: [\"docc\"]\n        )\n    }()\n\n    /// File rule to copy `.xcprivacy` (in the Xcode build system).\n    public static let xcprivacyCopied: FileRuleDescription = {\n        .init(\n            rule: .copyResource,\n            toolsVersion: .v6_0,\n            fileTypes: [\"xcprivacy\"]\n        )\n    }()\n\n    /// File rule to ignore `.xcprivacy` (in the SwiftPM build system).\n    public static let xcprivacyIgnored: FileRuleDescription = {\n        .init(\n            rule: .ignored,\n            toolsVersion: .v6_0,\n            fileTypes: [\"xcprivacy\"]\n        )\n    }()\n\n    /// List of all the builtin rules.\n    public static let builtinRules: [FileRuleDescription] = [\n        swift,\n        clang,\n        asm,\n        modulemap,\n        apinotes,\n        header,\n    ]\n\n    /// List of file types that requires the Xcode build system.\n    public static let xcbuildFileTypes: [FileRuleDescription] = [\n        xib,\n        assetCatalog,\n        stringCatalog,\n        coredata,\n        metal,\n        xcprivacyCopied,\n    ]\n\n    /// List of file types that apply just to the SwiftPM build system.\n    public static let swiftpmFileTypes: [FileRuleDescription] = [\n        docc,\n        xcprivacyIgnored,\n    ]\n\n    /// List of file directory extensions that should be treated as opaque, non source, directories.\n    public static var opaqueDirectoriesExtensions: Set<String> {\n        let types = Self.xcbuildFileTypes + Self.swiftpmFileTypes\n        return types.reduce(into: Set<String>(), { partial, item in\n            partial.formUnion(item.fileTypes)\n        })\n    }\n}\n\nextension FileRuleDescription.Rule {\n    init(_ seed: TargetDescription.Resource.Rule)  {\n        switch seed {\n        case .process(let localization):\n            self = .processResource(localization: localization)\n        case .copy:\n            self = .copyResource\n        case .embedInCode:\n            self = .embedResourceInCode\n        }\n    }\n}\n\nextension Resource {\n    var localization: String? {\n        switch self.rule {\n        case .process(let localization):\n            return localization\n        default:\n            return .none\n        }\n    }\n}\n\nextension Basics.Diagnostic {\n    static func symlinkInSources(symlink: Basics.RelativePath, targetName: String) -> Self {\n        .warning(\"ignoring symlink at '\\(symlink)' in target '\\(targetName)'\")\n    }\n\n    static func localizationDirectoryContainsSubDirectories(\n        localizationDirectory: Basics.RelativePath,\n        targetName: String\n    ) -> Self {\n        .error(\"localization directory '\\(localizationDirectory)' in target '\\(targetName)' contains sub-directories, which is forbidden\")\n    }\n}\n\nextension ObservabilityMetadata {\n    public var moduleName: String? {\n        get {\n            self[ModuleNameKey.self]\n        }\n        set {\n            self[ModuleNameKey.self] = newValue\n        }\n    }\n\n    enum ModuleNameKey: Key {\n        typealias Value = String\n    }\n}\n\nextension PackageReference.Kind {\n    fileprivate var emitAuthorWarnings: Bool {\n        switch self {\n        case .remoteSourceControl, .registry:\n            return false\n        default:\n            return true\n        }\n    }\n}\n\nextension PackageModel.Resource {\n    fileprivate var destinationForGrouping: Basics.RelativePath? {\n        do {\n            return try self.destination\n        } catch {\n            return .none\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageLoading/ToolsVersionParser.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\n\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.RegEx\n\nimport struct TSCUtility.Version\n\n/// Protocol for the manifest loader interface.\npublic struct ToolsVersionParser {\n    // designed to be used as a static utility\n    private init() {}\n\n    public static func parse(manifestPath: AbsolutePath, fileSystem: FileSystem) throws -> ToolsVersion {\n        // FIXME: We should diagnose errors not specific to the tools version specification outside of this function.\n        // In order to that, maybe we can restructure the parsing to something like this:\n        //     parse(_ manifestContent: String) throws -> Manifest {\n        //         ...\n        //         guard !manifestContent.isEmpty else { throw appropriateError }\n        //         let (toolsVersion, remainingContent) = parseAndConsumeToolsVersionSpecification(manifestContent)\n        //         let packageDetails = parsePackageDetails(remainingContent)\n        //         ...\n        //         return Manifest(toolsVersion, ...)\n        //     }\n\n        let manifestContents: ByteString\n        do {\n            manifestContents = try fileSystem.readFileContents(manifestPath)\n        } catch {\n            throw Error.inaccessibleManifest(path: manifestPath, reason: String(describing: error))\n        }\n\n        // FIXME: This is doubly inefficient.\n        // `contents`'s value comes from `FileSystem.readFileContents(_)`, which is [inefficient](https://github.com/apple/swift-tools-support-core/blob/8f9838e5d4fefa0e12267a1ff87d67c40c6d4214/Sources/TSCBasic/FileSystem.swift#L167). Calling `ByteString.validDescription` on `contents` is also [inefficient, and possibly incorrect](https://github.com/apple/swift-tools-support-core/blob/8f9838e5d4fefa0e12267a1ff87d67c40c6d4214/Sources/TSCBasic/ByteString.swift#L121). However, this is a one-time thing for each package manifest, and almost necessary in order to work with all Unicode line-terminators. We probably can improve its efficiency and correctness by using `URL` for the file's path, and get is content via `Foundation.String(contentsOf:encoding:)`. Swift System's [`FilePath`](https://github.com/apple/swift-system/blob/8ffa04c0a0592e6f4f9c30926dedd8fa1c5371f9/Sources/System/FilePath.swift) and friends might help as well.\n        // This is source-breaking.\n        // A manifest that has an [invalid byte sequence](https://en.wikipedia.org/wiki/UTF-8#Invalid_sequences_and_error_handling) (such as `0x7F8F`) after the tools version specification line could work in Swift < 5.4, but results in an error since Swift 5.4.\n        guard let manifestContentsDecodedWithUTF8 = manifestContents.validDescription else {\n            throw Error.nonUTF8EncodedManifest(path: manifestPath)\n        }\n\n        guard !manifestContentsDecodedWithUTF8.isEmpty else {\n            throw ManifestParseError.emptyManifest(path: manifestPath)\n        }\n\n        do {\n          return try self.parse(utf8String: manifestContentsDecodedWithUTF8)\n        } catch Error.malformedToolsVersionSpecification(.commentMarker(.isMissing)) {\n          throw UnsupportedToolsVersion(packageIdentity: .init(path: manifestPath), currentToolsVersion: .current, packageToolsVersion: .v3)\n        }\n    }\n\n    public static func parse(utf8String: String) throws -> ToolsVersion {\n        do {\n            return try Self._parse(utf8String: utf8String)\n        } catch {\n            // Keep scanning in case the tools-version is specified somewhere further down in the file.\n            var string = utf8String\n            while let newlineIndex = string.firstIndex(where: { $0.isNewline }) {\n                string = String(string[newlineIndex...].dropFirst())\n                if !string.isEmpty, let result = try? Self._parse(utf8String: string) {\n                    if result >= ToolsVersion.v6_0 {\n                        return result\n                    } else {\n                        throw Error.backwardIncompatiblePre6_0(.toolsVersionNeedsToBeFirstLine, specifiedVersion: result)\n                    }\n                }\n            }\n            // If we fail to find a tools-version in the entire manifest, throw the original error.\n            throw error\n        }\n    }\n\n    private static func _parse(utf8String: String) throws -> ToolsVersion {\n        assert(!utf8String.isEmpty, \"empty manifest should've been diagnosed before parsing the tools version specification\")\n        /// The manifest represented in its constituent parts.\n        let manifestComponents = Self.split(utf8String)\n        /// The Swift tools version specification represented in its constituent parts.\n        let toolsVersionSpecificationComponents = manifestComponents.toolsVersionSpecificationComponents\n\n        // The diagnosis of the manifest's formatting's correctness goes in the following order:\n        //\n        // 1. Check that the comment marker, the label, and the version specifier in the Swift tools version specification are not missing (empty).\n        //\n        // 2. Check that everything in the Swift tools version specification up to the version specifier is formatted correctly according to the relaxed rules since Swift 5.4. Backward-compatibility is not considered here, because the user-specified version is unknown yet.\n        //\n        //    1. Check that the comment marker is formatted correctly.\n        //\n        //    2. Check that the label is formatted correctly\n        //\n        //    3. Check that there is no unforeseen formatting error in the Swift tools version specification up to the version specifier.\n        //\n        // 3. Check that the version spicier is formatted correctly.\n        //\n        // 4. Check that the manifest is formatted backward-compatibly, if the user-specified version is < 5.4. Backward-compatibility checks are now possible, because the user-specified version has become known since the previous step.\n        //\n        //    1. Check that the manifest's leading whitespace is backward-compatible with Swift < 5.4.\n        //\n        //    2. Check that the spacing after the comment marker in the Swift tools version specification is backward-compatible with Swift < 5.4.\n        //\n        //    3. Check that the spacing after the label in the Swift tools version specification is backward-compatible with Swift < 5.4.\n        //\n        // This order is based on the general idea that a manifest's readability should come before its validity when being diagnosed. The package manager must first understand what is written in the manifest before it can tell if anything is wrong. This idea is manifested (no pun intended) in 2 areas of the diagnosis process:\n        //\n        // 1. The version specifier contains the most important piece of information, but it's checked last in the Swift tools version specification. This happens twice: both in checking its existence and in checking its correctness.\n        //\n        //    This is because the package manager must be confident that the version specifier it sees is exactly what the user has provided, not polluted by anything that comes before it. With English written left-to-right, and the manifest parsed largely left-to-right, errors in the comment marker and the label could be mistaken by the package manager as the version specifier's. Consider the following Swift tools version specification, where an \"l\" is mistyped with \"1\":\n        //\n        //        // swift-too1s-version: 5.3\n        //\n        //    Were the version specifier checked before everything else, the package manager will mistake \"1s-version: 5.3\" as the version specifier, treating the typo in the label as an error in the version specifier. The user will likely be confused, when informed by the diagnostics message that the version specifier is misspelt.\n        //\n        //    With the label checked before the version specifier, the diagnosis can be more precise, and this kind of confusion to the user can be avoided.\n        //\n        // 2. Backward-compatibility checks of the manifest are after the formatting checks of the Swift tools version specification, not during them.\n        //\n        //    Although it makes more sense, form a human's perspective, if the backward-compatibility checks is integrated within the formatting checks, the package manager can not see things as holistically as a human does. It can not pinpoint all errors in the manifest simultaneously, or understand the user's intention when the manifest has formatting errors, let alone finding any backward-incompatibility. It is better to first ensure that the manifest is formatted correctly according to the latest rules, then compare it against old rules to find backward-incompatibilities.\n\n        let commentMarker = toolsVersionSpecificationComponents.commentMarker\n        guard !commentMarker.isEmpty else {\n            throw Error.malformedToolsVersionSpecification(.commentMarker(.isMissing))\n        }\n\n        let label = toolsVersionSpecificationComponents.label\n        guard !label.isEmpty else {\n            throw Error.malformedToolsVersionSpecification(.label(.isMissing))\n        }\n\n        let versionSpecifier = toolsVersionSpecificationComponents.versionSpecifier\n        guard !versionSpecifier.isEmpty else {\n            throw Error.malformedToolsVersionSpecification(.versionSpecifier(.isMissing))\n        }\n\n        guard toolsVersionSpecificationComponents.everythingUpToVersionSpecifierIsWellFormed else {\n            if commentMarker != \"//\" {\n                throw Error.malformedToolsVersionSpecification(.commentMarker(.isMisspelt(String(commentMarker))))\n            }\n\n            if label.lowercased() != \"swift-tools-version:\" {\n                throw Error.malformedToolsVersionSpecification(.label(.isMisspelt(String(label))))\n            }\n\n            // The above If-statements should have covered all possible malformations in Swift tools version specification up to the version specifier.\n            // If you changed the logic in this file, and this fatal error is triggered, then you need to re-check the logic, and make sure all possible error conditions are covered in the Else-block.\n            throw Error.malformedToolsVersionSpecification(.unidentified)\n        }\n\n        guard let version = ToolsVersion(string: String(versionSpecifier), experimentalFeatures: manifestComponents.experimentalFeatures) else {\n            throw Error.malformedToolsVersionSpecification(.versionSpecifier(.isMisspelt(String(versionSpecifier))))\n        }\n\n        guard version >= .v5_4 || manifestComponents.isCompatibleWithPreSwift5_4 else {\n            let manifestLeadingWhitespace = manifestComponents.leadingWhitespace\n            if !manifestLeadingWhitespace.allSatisfy({ $0 == \"\\n\" }) {\n                throw Error.backwardIncompatiblePre5_4(.leadingWhitespace(String(manifestLeadingWhitespace)), specifiedVersion: version)\n            }\n\n            let spacingAfterCommentMarker = toolsVersionSpecificationComponents.spacingAfterCommentMarker\n            if spacingAfterCommentMarker != \"\\u{20}\" {\n                throw Error.backwardIncompatiblePre5_4(.spacingAfterCommentMarker(String(spacingAfterCommentMarker)), specifiedVersion: version)\n            }\n\n            let spacingAfterLabel = toolsVersionSpecificationComponents.spacingAfterLabel\n            if !spacingAfterLabel.isEmpty {\n                throw Error.backwardIncompatiblePre5_4(.spacingAfterLabel(String(spacingAfterLabel)), specifiedVersion: version)\n            }\n\n            // The above If-statements should have covered all possible backward incompatibilities with Swift < 5.4.\n            // If you changed the logic in this file, and this fatal error is triggered, then you need to re-check the logic, and make sure all possible error conditions are covered in the Else-block.\n            throw Error.backwardIncompatiblePre5_4(.unidentified, specifiedVersion: version)\n        }\n\n        return version\n    }\n\n    /// Splits the given manifest into its constituent components.\n    ///\n    /// A manifest consists of the following parts:\n    ///\n    ///                                                    ⎫\n    ///                                                    ⎪\n    ///                                                    ⎬ leading whitespace-only lines\n    ///                                                    ⎪\n    ///                                                    ⎭\n    ///       ┌ Swift tools version specification\n    ///       │                            ┌ ignored trailing contents\n    ///       ⌄~~~~~~~~~~~~~~~~~~~~~~~~~~~~⌄~~~~~~~~~~\n    ///       //  swift-tools-version:  5.4;2020-09-16     } the Swift tools version specification line\n    ///     ⌃~⌃~⌃~⌃~~~~~~~~~~~~~~~~~~~⌃~⌃~~⌃⌃~~~~~~~~~\n    ///     │ │ │ └ label             │ │  │└ trailing comment segment including a trailing line terminator, if any (not returned by this function)\n    ///     │ │ └ spacing             │ │  └ specification terminator (not returned by this function)\n    ///     │ └ comment marker        │ └ version specifier\n    ///     │                         └ spacing\n    ///     └ additional leading whitespace\n    ///                                                    ⎫\n    ///                                                    ┇\n    ///                                                    ⎬ the rest of the manifest's contents\n    ///                                                    ┇\n    ///                                                    ⎭\n    ///\n    /// - Note: The splitting mostly assumes that the manifest is well-formed. A malformed component may lead to incorrect identification of other components.\n    ///\n    ///   For example, a malformed Swift tools version specification `\"// swift-too1s-version:5.3\"` misleads this function to identify `\"swift-too\"` as the label, and `\"1s-version:5.3\"` the version specifier.\n    ///\n    /// - Parameter manifest: The UTF-8-encoded content of the manifest.\n    /// - Returns: The components of the given manifest.\n    public static func split(_ manifest: String) -> ManifestComponents {\n\n        // We split the string manually instead of using `Collection.split(maxSplits:omittingEmptySubsequences:whereSeparator:)`, because the latter \"strips\" leading and trailing whitespace, and we need to record the leading whitespace to check for backward-compatibility later.\n\n        /// The position of the first character of the Swift tools version specification line in the manifest.\n        ///\n        /// Because the tools version specification line is the first non-whitespace-only line in the manifest, the position of its first character is also the position of the first non-whitespace character in the manifest. If there is only whitespace in the manifest, then this position is the `endIndex` of the manifest.\n        let startIndexOfSpecification = manifest.firstIndex(where: { !$0.isWhitespace } ) ?? manifest.endIndex\n\n        /// The whitespace at the start of the manifest.\n        ///\n        /// Because the tools version specification is the first non-whitespace-only character sequence in the manifest, the manifest's leading whitespace are the only characters in front of the tools version specification.\n        let leadingWhitespace = manifest[..<startIndexOfSpecification]\n\n        /// The position right past the last character of the Swift tools version specification line in the manifest.\n        ///\n        /// Because the specification line ends at a line terminator, the position right past the line's last character is the position of the terminator of the line. If no such line terminator exists, then this position is the `endIndex` of the manifest.\n        let endIndexOfSpecificationLine = manifest[startIndexOfSpecification...].firstIndex(where: \\.isNewline) ?? manifest.endIndex\n\n        /// The Swift tools version specification with ignored trailing contents.\n        ///\n        /// The specification is the first comment (until its terminator) in the manifest that declares the version of the `PackageDescription` library, the minimum version of the Swift tools and Swift language compatibility version to process the manifest, and the minimum version of the Swift tools that are needed to use the Swift package.\n        ///\n        /// The ignored trailing contents are everything starting from the first semicolon after the version specifier in the line.\n        let specificationWithIgnoredTrailingContents = manifest[startIndexOfSpecification..<endIndexOfSpecificationLine]\n\n        /// The position right past the last character of the Swift tools version specification's comment marker.\n        ///\n        /// This is the same as the position of the first character that is neither `\"/\"` nor `\"*\"` in the Swift tools version specification. If no such character exists, then this position is the `endIndex` of the Swift tools version specification.\n        let endIndexOfCommentMarker = specificationWithIgnoredTrailingContents.firstIndex(where: { $0 != \"/\" && $0 != \"*\" } ) ?? specificationWithIgnoredTrailingContents.endIndex\n\n        /// The comment marker of the Swift tools version specification.\n        ///\n        /// The continuous sequence of `\"/\"`s and `\"*\"`s immediately following the leading whitespace is considered as the comment marker, regardless of its validity.\n        let commentMarker = specificationWithIgnoredTrailingContents[..<endIndexOfCommentMarker]\n\n        /// The position right past the last character of the spacing that immediately follows the comment marker.\n        ///\n        /// Because the spacing consists of only horizontal whitespace characters, this position is the same as the first character that's not a horizontal whitespace after `commentMarker`. If no such character exists, then the position is the `endIndex` of the Swift tools version specification line.\n        let startIndexOfLabel = specificationWithIgnoredTrailingContents[endIndexOfCommentMarker...].firstIndex(where: { !$0.isWhitespace } ) ?? specificationWithIgnoredTrailingContents.endIndex\n        //                                                                                                                  ☝️\n        // Technically, this is looking for the position of the first character that's not a whitespace, BOTH HORIZONTAL AND VERTICAL. However, since all vertical horizontal whitespace characters are also line terminators, and because the Swift tools version specification does not contain any line terminator, we can safely use `Character.isWhitespace` to check if a character is a horizontal whitespace.\n\n        /// The spacing that immediately follows `commentMarker`.\n        ///\n        /// The spacing consists of only horizontal whitespace characters.\n        let spacingAfterCommentMarker = specificationWithIgnoredTrailingContents[endIndexOfCommentMarker..<startIndexOfLabel]\n\n        // FIXME: Improve the logic for identifying the label and the version specifier.\n        //\n        // At this point, everything before the label has been parsed, and everything starting from the label until the end of the Swift tools version specification line hasn't.\n        //\n        // The task that remains is to identify and record the following well defined components: a label, a version specifier, and an optional spacing between the label and the version specifier. However, because of the countless misspellings there could be, it's virtually impossible to teach SwiftPM to perfectly tell where the label ends and where the version specifier begins, without making the logic too complex.\n        //\n        // Let's explore this problem starting from a well-formed Swift tools version specification, because it's the only invariable that we can rely on. The current `Substring`-based strategy depends on landmarks that sit on either the `startIndex` or the `endIndex` of a component. We already know where the label starts, and it's trivial to find where the version specifier ends (its terminator is well-defined), so all that we need look for now are the `endIndex` of the label and the `startIndex` of the version specifier. In a well-formatted Swift tools version specification, the label ends with a \":\", and the version specifier starts with a digit. Let's see how these 2 landmarks fare with some examples:\n        //\n        // 1. A well-formatted Swift tools version specification\n        //\n        //        // swift-tools-version: 5.4\n        //\n        //    The `endIndex` of the label can be clearly identified with the first \":\", and the `startIndex` of the version specifier can be clearly identified with the first digit \"5\".\n        //\n        // 2. A misspelt label with a digit within:\n        //\n        //        // swift-too1s-version: 5.4\n        //    The `endIndex` of the label can be identified with the first \":\"; the `startIndex` of the version specifier can be identified with the digit \"5\", if and only if the search for the first \":\" takes precedence.\n        //\n        // 3. A misspelt label with a colon and a digit within:\n        //\n        //        // sw:ft-too1s-version: 5.4\n        //\n        //    The `endIndex` of the label can be identified with the last \":\";  the `startIndex` of the version specifier can be identified with the digit \"5\", if and only if the search for the last \":\" takes precedence.\n        //\n        // Between example 2 and 3, the rules are already conflicting. Although the examples above are purposely constructed to illustrate the ineffectiveness of using \":\" and digits to locate the label and the version specifier, it's undeniable a human can flawlessly point out where the labels and version specifiers are at a glance. There are more examples that shows it's even harder to find a one-size-fits-all landmark-based rule than illustrated above:\n        //\n        //     // swift-too1s-version:-5.4\n        //     // swift-too1s-version 5:4:0\n        //     // swift tools version 5-4-1\n        //     // swift-tools-version: S.A.I\n        //     // swift-tools-version::5.4\n        //     ...\n        //\n        // One useful information we can glean from these examples is that using both \":\" and digits as landmarks doesn't work, so it's better to stick with just one of them and ignore the other. Because the version specifier is the more important component than the label is, the current implementation of this function searches for the first numerical character in the sequence to prioritize the identification of the version specifier. The \":\"-first approach isn't completely abandoned, either: If the sequence is prefixed with \"swift-tools-version:\" (case-insensitive), then we can be mostly certain that the user has provided a well-formatted label, and use the position past that of the first \":\" in the sequence as the `startIndex` of the label. There are still countless label misspellings that begin with \"swift-tools-version:\", but since for all of them, the misspelt part comes after the well-formed part, in the interest of keeping the logic relatively straightforward, the labels' misspellings in this sort of situation are carried over as the version specifiers'.\n        //\n        // Although it's possible to replace the landmark-based logic altogether with a fuzzy matching-based approach or some heuristics, it overly complicates this function. Even if a more advanced method is applied at the expense of high complexity, it's still unlikely to be perfect. Maybe someone can find better solution without incurring much additional cost.\n\n        /// The position right past the last character in the label part of the Swift tool version specification.\n        ///\n        /// If the label begins with exactly `\"swift-tools-version:\"`, then this position is right after the `\":\"`'s. Otherwise, it's the position of the first horizontal whitespace character since the spacing after the comment marker (if there is a spacing between the label and the version specifier) or the `startIndex` of the version specifier (if there is no spacing between the label and the version specifier).\n        let endIndexOfLabel: Substring.Index\n\n        /// The position of the first character in the version specifier.\n        ///\n        /// If the label begins with exactly `\"swift-tools-version:\"`,  then this position is that of the first non-whitespace character after the label in the Swift tools version specification line. Otherwise, it's the same as the position of the first numeric character in the Swift tools version specification line. If no suitable character exists in either case, then this position is the `endIndex` of the line.\n        ///\n        /// - Note:\n        ///\n        ///   For a misspelt Swift tools version specification `\"// swift-too1s-version:5.3\"`, the first `\"1\"` is considered as the first character of the version specifier, and so `\"1s-version:5.3\"` is taken as the version specifier.\n        ///\n        ///   For a misspelt Swift tools version specification `\"// swift-tools-version:-5.3\"`, the label begins with `\"swift-tools-version:\"`, so all the misspelling is treated as the version specifiers, and so `\"-5.3\"` is taken as the version specifier.\n        let startIndexOfVersionSpecifier: Substring.Index\n\n        /// The trailing slice of the Swift tools version specification line starting from the label.\n        let specificationSnippetFromLabelToLineTerminator = specificationWithIgnoredTrailingContents[startIndexOfLabel...]\n\n        if specificationSnippetFromLabelToLineTerminator.lowercased().hasPrefix(\"swift-tools-version:\") {\n            // The optional index can be safely unwrapped, because we know for sure there is a \":\" in the substring.                                     👇\n            endIndexOfLabel = specificationSnippetFromLabelToLineTerminator.index(after: specificationSnippetFromLabelToLineTerminator.firstIndex(of: \":\")!)\n            // Because there is potentially a spacing between the label and the version specifier, we need to skip the whitespace first.\n            startIndexOfVersionSpecifier = specificationSnippetFromLabelToLineTerminator[endIndexOfLabel...].firstIndex(where: { !$0.isWhitespace } ) ?? specificationSnippetFromLabelToLineTerminator.endIndex\n        } else {\n            // FIXME: Use `CharacterSet.decimalDigits` instead?\n            // `Character.isNumber` is true for more than just decimal characters (e.g. ㊅ and 𝟘), but `CharacterSet.contains(_:)` works only on Unicode scalars.\n            startIndexOfVersionSpecifier = specificationSnippetFromLabelToLineTerminator.firstIndex(where: \\.isNumber) ?? specificationWithIgnoredTrailingContents.endIndex\n            /// The label part of the Swift tools version specification with the whitespace sequence between the label and the version specifier.\n            /// - Note: For a misspelt Swift tools version specification `\"// swift-too1s-version: 5.4\"`, the label stops at the second `\"o\"`, so only `\"swift-too\"` is recognised as the label with no spacing following it.\n            let labelWithTrailingWhitespace = specificationWithIgnoredTrailingContents[startIndexOfLabel..<startIndexOfVersionSpecifier]\n            // Because there is no whitespace within the label, and because the spacing consists of only horizontal whitespace characters, the end index of the label is the same as the position of the first whitespace character between the beginning of the label and the beginning of the version specifier. If no such whitespace character exists, then there is no spacing, and so this position is the `endIndex` of these sequence of characters (i.e. the starting position of the version specifier).\n            endIndexOfLabel = labelWithTrailingWhitespace.firstIndex(where: \\.isWhitespace) ?? startIndexOfVersionSpecifier\n        }\n\n        /// The label part of the Swift tools version specification.\n        /// - Note: For a misspelt Swift tools version specification `\"// swift-too1s-version: 5.4\"`, the label stops at the second `\"o\"`, so only `\"swift-too\"` is recognised as the label.\n        let label = specificationSnippetFromLabelToLineTerminator[startIndexOfLabel..<endIndexOfLabel]\n\n        /// The spacing between the label part of the Swift tools version specification and the version specifier.\n        /// - Note: For a misspelt Swift tools version specification `\"// swift-too1s-version: 5.4\"`, the label stops at the second `\"o\"`, and the version specifier starts from the first `\"1\"`, so no spacing is recognised.\n        let spacingAfterLabel = specificationSnippetFromLabelToLineTerminator[endIndexOfLabel..<startIndexOfVersionSpecifier]\n\n        /// The position of the version specifier's terminator.\n        ///\n        /// The terminator can be either a `\";\"` or a line terminator. If no such character exists, then this position is the `endIndex` of the Swift tools version specification.\n        let indexOfVersionSpecifierTerminator = specificationWithIgnoredTrailingContents[startIndexOfVersionSpecifier...].firstIndex(where: { $0 == \";\" } ) ?? specificationWithIgnoredTrailingContents.endIndex\n        //                                                                                                                                          ☝️\n        // Technically, this is looking for the position of the first \";\" only, not the first line terminator. However, because the Swift tools version specification does not contain any line terminator, we can safely search just the first \";\".\n\n        // If the label doesn't start with \"// swift-too1s-version: 5.4\", the version specifier and its terminator together are first found by locating the first numeric character in the specification line, and the version specifier starts with that first numeric character. So, if the version specifier is empty, then the line has no numeric characters, then the specification's ignored trailing contents are empty too. Basically, if the version specifier is empty, then the specification has no ignored trailing contents. This is only true for when the label doesn't start with \"// swift-too1s-version: 5.4\".\n\n        /// The version specifier.\n        /// - Note: For a misspelt Swift tools version specification `\"// swift-too1s-version:5.3\"`, the first `\"1\"` is considered as the first character of the version specifier, and so `\"1s-version:5.3\"` is taken as the version specifier.\n        let versionSpecifier = specificationSnippetFromLabelToLineTerminator[startIndexOfVersionSpecifier..<indexOfVersionSpecifierTerminator]\n\n        /// Look for experimental features. They are space separated values contained in parenthases right after the \";\", e.g. \"// swift-tools-version: 6.3;(experimentalCGen)\"\n        var experimentalFeatures: Set<ToolsVersion.ExperimentalFeature> = []\n        if indexOfVersionSpecifierTerminator < specificationWithIgnoredTrailingContents.endIndex, specificationWithIgnoredTrailingContents[indexOfVersionSpecifierTerminator...].hasPrefix(\";(\") {\n            let startOfExperimentalFeatures = specificationWithIgnoredTrailingContents.index(indexOfVersionSpecifierTerminator, offsetBy: 2)\n            if let endOfExperimentalFeatures = specificationWithIgnoredTrailingContents[startOfExperimentalFeatures...].firstIndex(where: { $0 == \")\" }) {\n                for featureString in specificationWithIgnoredTrailingContents[startOfExperimentalFeatures..<endOfExperimentalFeatures].split(separator: \" \", omittingEmptySubsequences: true) {\n                    if let feature = ToolsVersion.ExperimentalFeature(rawValue: String(featureString)) {\n                        experimentalFeatures.insert(feature)\n                    }\n                    // TODO: Should we record the ones that don't match to present in diagnostics?\n                }\n            }\n        }\n\n        // The tertiary condition checks if the specification line's end index is the same as the manifest's.\n        // If it is, then just use the index, because the rest of the manifest is empty, and because using `index(after:)` on it results in an index-out-of-bound error.\n        /// The position of the first character following the tools version specification line in the manifest.\n        ///\n        /// If no such character exists, then the position is the `endIndex` of the manifest.\n        let startIndexOfManifestAfterSpecification = endIndexOfSpecificationLine == manifest.endIndex ? manifest.endIndex : manifest.index(after: endIndexOfSpecificationLine)\n\n        /// The remaining contents of the manifest that follows right after the tools version specification line.\n        let manifestAfterSpecification = manifest[startIndexOfManifestAfterSpecification...]\n\n        return ManifestComponents(\n            leadingWhitespace: leadingWhitespace,\n            toolsVersionSpecificationComponents: ToolsVersionSpecificationComponents(\n                commentMarker: commentMarker,\n                spacingAfterCommentMarker: spacingAfterCommentMarker,\n                label: label,\n                spacingAfterLabel: spacingAfterLabel,\n                versionSpecifier: versionSpecifier\n            ),\n            experimentalFeatures: experimentalFeatures,\n            contentsAfterToolsVersionSpecification: manifestAfterSpecification\n        )\n    }\n}\n\nextension ToolsVersionParser {\n    /// A representation of a manifest in its constituent parts.\n    public struct ManifestComponents {\n        /// The largest contiguous sequence of whitespace characters at the very beginning of the manifest.\n        public let leadingWhitespace: Substring\n        /// The Swift tools version specification represented in its constituent parts.\n        public let toolsVersionSpecificationComponents: ToolsVersionSpecificationComponents\n        /// List of recognized experimental features\n        public let experimentalFeatures: Set<ToolsVersion.ExperimentalFeature>\n        /// The remaining contents of the manifest that follows right after the tools version specification line.\n        public let contentsAfterToolsVersionSpecification: Substring\n        /// A Boolean value indicating whether the manifest represented in its constituent parts is backward-compatible with Swift < 5.4.\n        public var isCompatibleWithPreSwift5_4: Bool {\n            leadingWhitespace.allSatisfy { $0 == \"\\n\" } && toolsVersionSpecificationComponents.isCompatibleWithPreSwift5_4\n        }\n    }\n\n    /// A representation of a Swift tools version specification in its constituent parts.\n    ///\n    /// A Swift tools version specification consists of the following parts:\n    ///\n    ///     //  swift-tools-version:  5.4\n    ///     ⌃~⌃~⌃~~~~~~~~~~~~~~~~~~~⌃~⌃~~\n    ///     │ │ └ label             │ └ version specifier\n    ///     │ └ spacing             └ spacing\n    ///     └ comment marker\n    ///\n    public struct ToolsVersionSpecificationComponents {\n        /// The comment marker.\n        ///\n        /// In a well-formed Swift tools version specification, the comment marker is `\"//\"`.\n        public let commentMarker: Substring\n\n        /// The spacing after the comment marker\n        ///\n        /// In a well-formed Swift tools version specification, the spacing after the comment marker is a continuous sequence of horizontal whitespace characters.\n        ///\n        /// For Swift < 5.4, the spacing after the comment marker must be a single `U+0020`.\n        public let spacingAfterCommentMarker: Substring\n\n        /// The label part of the Swift tools version specification.\n        ///\n        /// In a well-formed Swift tools version specification, the label is `\"swift-tools-version:\"`\n        public let label: Substring\n\n        /// The spacing between the label part of the Swift tools version specification and the version specifier.\n        ///\n        /// In a well-formed Swift tools version specification, the spacing after the label is a continuous sequence of horizontal whitespace characters.\n        ///\n        /// For Swift < 5.4, no spacing is allowed after the label.\n        public let spacingAfterLabel: Substring\n\n        /// The version specifier.\n        public let versionSpecifier: Substring\n\n        /// A Boolean value indicating whether everything up to the version specifier in the Swift tools version specification represented in its constituent parts is well-formed.\n        public var everythingUpToVersionSpecifierIsWellFormed: Bool {\n            // The label is case-insensitive.\n            // Making it case-sensitive is source breaking for all existing Swift versions.\n            //\n            // An argument for making it case-sensitive is that it can make the package manager slightly more efficient:\n            //\n            // \"swift-tools-version:\" has more than 15 UTF-8 code units, so `label` is likely to have more than 15 UTF-8 code units too.\n            // Strings with more than 15 UTF-8 code units are heap-allocated on 64-bit platforms, 10 on 32-bit platforms.\n            // `Substring.lowercase()` returns a heap-allocated string here, and this is inefficient.\n            // Although, the allocation happens only once per manifest (once per loading attempt), so the inefficiency is rather insignificant.\n            // Short-circuiting the `lowercase()` can remove an allocation.\n            commentMarker == \"//\" && label.lowercased() == \"swift-tools-version:\"\n        }\n\n        /// A Boolean value indicating whether the Swift tools version specification represented in its constituent parts is backward-compatible with Swift < 5.4.\n        public var isCompatibleWithPreSwift5_4: Bool {\n            everythingUpToVersionSpecifierIsWellFormed && spacingAfterCommentMarker == \"\\u{20}\" && spacingAfterLabel.isEmpty\n        }\n    }\n}\n\nextension ToolsVersionParser {\n    // Parameter names for associated values help the auto-complete provide hints at the call site, even when the argument label is suppressed.\n\n    // FIXME: Use generic associated type `T: StringProtocol` instead of concrete types `String` and `Substring`, when/if this feature comes to Swift.\n    public enum Error: Swift.Error, CustomStringConvertible {\n\n        /// Location of the tools version specification's malformation.\n        public enum ToolsVersionSpecificationMalformationLocation {\n            /// The nature of malformation at the location in Swift tools version specification.\n            public enum MalformationDetails {\n                /// The Swift tools version specification component is missing in the non-empty manifest.\n                case isMissing\n                /// The Swift tools version specification component is misspelt.\n                case isMisspelt(_ misspelling: String)\n            }\n            /// The comment marker is malformed.\n            ///\n            /// If the comment marker is missing, it could be an indication that the entire Swift tools version specification is missing.\n            case commentMarker(_ malformationDetails: MalformationDetails)\n            /// The label part of the Swift tools version specification is malformed.\n            case label(_ malformationDetails: MalformationDetails)\n            /// The version specifier is malformed.\n            ///\n            /// If the version specifier is diagnosed as missing, it could be a misdiagnosis of some misspellings in the label due to a compromise made in `ToolsVersionLoader.split(_:)`. For example, the following Swift tools version specification will be misdiagnosed to be missing a version specifier:\n            ///\n            ///     // swift-tools-version:;5.3\n            ///\n            /// This is because the position right past `\":\"` is considered as the `startIndex` of the version specifier, but at the same time the character at this position is `\";\"`, a terminator of the Swift tools version specification. This misleads `ToolsVersionLoader.load(file:fileSystem:)` to believe the version specifier is empty (i.e. missing).\n            case versionSpecifier(_ malformationDetails: MalformationDetails)\n            /// An unidentifiable component of the Swift tools version specification is malformed.\n            case unidentified\n        }\n\n        /// Details of backward-incompatible contents with Swift tools version < 5.4.\n        ///\n        /// A backward-incompatibility is not necessarily a malformation.\n        public enum BackwardIncompatibilityPre5_4 {\n            /// The whitespace at the start of the manifest is not all `U+000A`.\n            case leadingWhitespace(_ whitespace: String)\n            /// The horizontal spacing between \"//\" and  \"swift-tools-version\" either is empty or uses whitespace characters unsupported by Swift < 5.4.\n            case spacingAfterCommentMarker(_ spacing: String)\n            /// There is a non-empty spacing between the label part of the Swift tools version specification and the version specifier.\n            case spacingAfterLabel(_ spacing: String)\n            /// There is an unidentifiable backward-incompatibility with Swift tools version < 5.4 within the manifest.\n            case unidentified\n        }\n\n        /// Details of backward-incompatible contents with Swift tools version < 6.0.\n        public enum BackwardIncompatibilityPre6_0 {\n            /// Tools-versions on subsequent lines of the manifest are only accepted by 6.0 or later.\n            case toolsVersionNeedsToBeFirstLine\n        }\n\n        /// Package directory is inaccessible (missing, unreadable, etc).\n        case inaccessiblePackage(path: AbsolutePath, reason: String)\n        /// Package manifest file is inaccessible (missing, unreadable, etc).\n        case inaccessibleManifest(path: AbsolutePath, reason: String)\n        /// Package manifest file's content can not be decoded as a UTF-8 string.\n        case nonUTF8EncodedManifest(path: AbsolutePath)\n        /// Malformed tools version specification.\n        case malformedToolsVersionSpecification(_ malformationLocation: ToolsVersionSpecificationMalformationLocation)\n        /// Backward-incompatible contents with Swift tools version < 5.4.\n        case backwardIncompatiblePre5_4(_ incompatibility: BackwardIncompatibilityPre5_4, specifiedVersion: ToolsVersion)\n        /// Backward-incompatible contents with Swift tools version < 6.0.\n        case backwardIncompatiblePre6_0(_ incompatibility: BackwardIncompatibilityPre6_0, specifiedVersion: ToolsVersion)\n\n        public var description: String {\n\n            /// Returns a description of the given characters' Unicode code points.\n            ///\n            /// This tells the user what characters are currently used in the specification.\n            ///\n            /// - Parameter characters: The given characters the description of whose code points are to be returned.\n            /// - Returns: A list of `characters`' code points, each prefixed by \"U+\", separated by commas, and bounded together by a pair of square brackets.\n            func unicodeCodePointsPrefixedByUPlus<T: StringProtocol>(of characters: T) -> String {\n                let unicodeCodePointsOfCharacters: [UInt32] = characters.flatMap(\\.unicodeScalars).map(\\.value)\n                let unicodeCodePointsOfCharactersPrefixedByUPlus: [String] = unicodeCodePointsOfCharacters.map { codePoint in\n                    var codePointString = String(codePoint, radix: 16).uppercased()\n                    if codePointString.count < 4 {\n                        codePointString = String(repeating: \"0\", count: 4 - codePointString.count) + codePointString\n                    }\n                    return \"U+\\(codePointString)\"\n                }\n                // FIXME: Use `ListFormatter` instead?\n                return \"[\\(unicodeCodePointsOfCharactersPrefixedByUPlus.joined(separator: \", \"))]\"\n            }\n\n            switch self {\n            case let .inaccessiblePackage(packageDirectoryPath, reason):\n                return \"the package at '\\(packageDirectoryPath)' cannot be accessed (\\(reason))\"\n            case let .inaccessibleManifest(manifestFilePath, reason):\n                return \"the package manifest at '\\(manifestFilePath)' cannot be accessed (\\(reason))\"\n            case let .nonUTF8EncodedManifest(manifestFilePath):\n                return \"the package manifest at '\\(manifestFilePath)' cannot be decoded using UTF-8\"\n            case let .malformedToolsVersionSpecification(malformationLocation):\n                switch malformationLocation {\n                case .commentMarker(let commentMarker):\n                    switch commentMarker {\n                    case .isMissing:\n                        return \"the manifest is missing a Swift tools version specification; consider prepending to the manifest '\\(ToolsVersion.current.specification())' to specify the current Swift toolchain version as the lowest Swift version supported by the project; if such a specification already exists, consider moving it to the top of the manifest, or prepending it with '//' to help Swift Package Manager find it\"\n                    case .isMisspelt(let misspeltCommentMarker):\n                        return \"the comment marker '\\(misspeltCommentMarker)' is misspelt for the Swift tools version specification; consider replacing it with '//'\"\n                    }\n                case .label(let label):\n                    switch label {\n                    case .isMissing:\n                        return \"the Swift tools version specification is missing a label; consider inserting 'swift-tools-version:' between the comment marker and the version specifier\"\n                    case .isMisspelt(let misspeltLabel):\n                        return \"the Swift tools version specification's label '\\(misspeltLabel)' is misspelt; consider replacing it with 'swift-tools-version:'\"\n                    }\n                case .versionSpecifier(let versionSpecifier):\n                    switch versionSpecifier {\n                    case .isMissing:\n                        return \"the Swift tools version specification is possibly missing a version specifier; consider using '\\(ToolsVersion.current.specification())' to specify the current Swift toolchain version as the lowest Swift version supported by the project\"\n                    case .isMisspelt(let misspeltVersionSpecifier):\n                        return \"the Swift tools version '\\(misspeltVersionSpecifier)' is misspelt or otherwise invalid; consider replacing it with '\\(ToolsVersion.current.specification())' to specify the current Swift toolchain version as the lowest Swift version supported by the project\"\n                    }\n                case .unidentified:\n                    return \"the Swift tools version specification has a formatting error, but the package manager is unable to find either the location or cause of it; consider replacing it with '\\(ToolsVersion.current.specification())' to specify the current Swift toolchain version as the lowest Swift version supported by the project; additionally, please consider filing a bug report on https://bugs.swift.org with this file attached\"\n                }\n            case let .backwardIncompatiblePre5_4(incompatibility, specifiedVersion):\n                switch incompatibility {\n                case .leadingWhitespace(let whitespace):\n                    return \"leading whitespace sequence \\(unicodeCodePointsPrefixedByUPlus(of: whitespace)) in manifest is supported by only Swift ≥ 5.4; the specified version \\(specifiedVersion) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest\"\n                case .spacingAfterCommentMarker(let spacing):\n                    return \"\\(spacing.isEmpty ? \"zero spacing\" : \"horizontal whitespace sequence \\(unicodeCodePointsPrefixedByUPlus(of: spacing))\") between '//' and 'swift-tools-version' is supported by only Swift ≥ 5.4; consider replacing the sequence with a single space (U+0020) for Swift \\(specifiedVersion)\"\n                case .spacingAfterLabel(let spacing):\n                    return \"horizontal whitespace sequence \\(unicodeCodePointsPrefixedByUPlus(of: spacing)) immediately preceding the version specifier is supported by only Swift ≥ 5.4; consider removing the sequence for Swift \\(specifiedVersion)\"\n                case .unidentified:\n                    return \"the manifest is backward-incompatible with Swift < 5.4, but the package manager is unable to pinpoint the exact incompatibility; consider replacing the current Swift tools version specification with '\\(specifiedVersion.specification())' to specify Swift \\(specifiedVersion) as the lowest Swift version supported by the project, then move the new specification to the very beginning of this manifest file; additionally, please consider filing a bug report on https://bugs.swift.org with this file attached\"\n                }\n            case let .backwardIncompatiblePre6_0(incompatibility, _):\n                switch incompatibility {\n                case .toolsVersionNeedsToBeFirstLine:\n                    return \"the manifest is backward-incompatible with Swift < 6.0 because the tools-version was specified in a subsequent line of the manifest, not the first line. Either move the tools-version specification or increase the required tools-version of your manifest\"\n                }\n            }\n\n        }\n    }\n}\n\nextension ManifestLoader {\n    /// Returns the manifest at the given package path.\n    ///\n    /// Version specific manifest is chosen if present, otherwise path to regular\n    /// manifest is returned.\n    public static func findManifest(\n        packagePath: AbsolutePath,\n        fileSystem: FileSystem,\n        currentToolsVersion: ToolsVersion\n    ) throws -> AbsolutePath {\n        // Look for a version-specific manifest.\n        for versionSpecificKey in ToolsVersion.current.versionSpecificKeys {\n            let versionSpecificPath = packagePath.appending(component: Manifest.basename + versionSpecificKey + \".swift\")\n            if fileSystem.isFile(versionSpecificPath) {\n                return versionSpecificPath\n            }\n        }\n\n        let contents: [String]\n        do { contents = try fileSystem.getDirectoryContents(packagePath) } catch {\n            throw ToolsVersionParser.Error.inaccessiblePackage(path: packagePath, reason: String(describing: error))\n        }\n        let regex = try! RegEx(pattern: #\"^Package@swift-(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?.swift$\"#)\n\n        // Collect all version-specific manifests at the given package path.\n        let versionSpecificManifests = Dictionary(contents.compactMap{ file -> (ToolsVersion, String)? in\n            let parsedVersion = regex.matchGroups(in: file)\n            guard parsedVersion.count == 1, parsedVersion[0].count == 3 else {\n                return nil\n            }\n\n            let major = Int(parsedVersion[0][0])!\n            let minor = parsedVersion[0][1].isEmpty ? 0 : Int(parsedVersion[0][1])!\n            let patch = parsedVersion[0][2].isEmpty ? 0 : Int(parsedVersion[0][2])!\n\n            return (ToolsVersion(version: Version(major, minor, patch)), file)\n        }, uniquingKeysWith: { $1 })\n\n        let regularManifest = packagePath.appending(component: Manifest.filename)\n\n        // Try to get the tools version of the regular manifest.  As the comment marker is missing, we default to\n        // tools version 3.1.0 (as documented).\n        let regularManifestToolsVersion: ToolsVersion\n        do {\n            regularManifestToolsVersion = try ToolsVersionParser.parse(manifestPath: regularManifest, fileSystem: fileSystem)\n        }\n        catch let error as UnsupportedToolsVersion where error.packageToolsVersion == .v3 {\n          regularManifestToolsVersion = .v3\n        }\n\n        // Find the newest version-specific manifest that is compatible with the current tools version.\n        guard let versionSpecificCandidate = versionSpecificManifests.keys.sorted(by: >).first(where: { $0 <= currentToolsVersion }) else {\n            // Otherwise, return the regular manifest.\n            return regularManifest\n        }\n\n        let versionSpecificManifest = packagePath.appending(component: versionSpecificManifests[versionSpecificCandidate]!)\n\n        // SwiftPM 4 introduced tools-version designations; earlier packages default to tools version 3.1.0.\n        // See https://swift.org/blog/swift-package-manager-manifest-api-redesign.\n        let versionSpecificManifestToolsVersion: ToolsVersion\n        if versionSpecificCandidate < .v4 {\n            versionSpecificManifestToolsVersion = .v3\n        }\n        else {\n            versionSpecificManifestToolsVersion = try ToolsVersionParser.parse(manifestPath: versionSpecificManifest, fileSystem: fileSystem)\n        }\n\n        // Compare the tools version of this manifest with the regular\n        // manifest and use the version-specific manifest if it has\n        // a greater tools version.\n        if versionSpecificManifestToolsVersion > regularManifestToolsVersion {\n            return versionSpecificManifest\n        } else {\n            // If there's no primary candidate, validate the regular manifest.\n            if regularManifestToolsVersion.validateToolsVersion(currentToolsVersion) {\n                return regularManifest\n            } else {\n                // If that's incompatible, use the closest version-specific manifest we got.\n                return versionSpecificManifest\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/BundlingResources.md",
    "content": "# Bundling resources with a Swift package\n\nAdd resource files to your Swift package and access them in your code.\n\n## Overview\n\nIf you declare `// swift-tools-version: 5.3` or later in your `Package.swift` file, you can bundle resources alongside your source code in Swift packages.\nFor example, Swift packages can contain asset catalogs, test fixtures, and so on.\n\n### Add resource files\n\nPackage manager treats non-source files found in the target's sources directory as assets, scoped to that target.\nFor example, any resources for the `MyLibrary` target reside by default in `Sources/MyLibrary`.\nTo easily distinguish resources from source files, create and use a subfolder for the resources. \nFor example, put all resource files into a directory named `Resources`, resulting in all of your resource files residing at `Sources/MyLibrary/Resources`.\n\n### Explicitly declare or exclude resources\n\nTo add a resource that the compiler doesn't handle automatically, explicitly declare it as a resource in your package manifest.\nIf you're building your package with Xcode, it automatically handles a number of kinds of resources.\n\nFor example, to include a file `text.txt` as a resource, add the file into `Sources/MyLibrary/Resources`.\nThen explicitly declare it as a package resource by adding the name of the file to the list of resources for your target:\n\n```swift\ntargets: [\n    .target(\n        name: \"MyLibrary\",\n        resources: [\n            .process(\"Resources/text.txt\")]\n    ),\n]\n```\n\nThe example above uses  [process(_:localization:)](https://developer.apple.com/documentation/PackageDescription/Resource/process(_:localization:)) to identify the resource.\nWhen you explicitly declare a resource, choose a rule to determine how Swift treats the resource file.\nThe options include:\n\n- term Process rule: For most use cases, use [process(_:localization:)](https://developer.apple.com/documentation/PackageDescription/Resource/process(_:localization:)). This requests the compiler to apply any processing known for the type of resource, according to the platform you’re building the package for. \nFor example, Xcode may optimize image files for a platform that supports such optimizations.\nIf you apply the process rule to a directory’s path, Xcode applies the rule recursively to all files within the directory. \nIf no special processing is available for a resource, the compiler copies the resource as is to the resource bundle’s top-level directory.\n\n- term Copy rule: Some Swift packages may require a resource file to remain untouched or to retain a certain directory structure for resources. \nUse the [copy(_:)](https://developer.apple.com/documentation/PackageDescription/Resource/copy(_:)) function to apply this rule and copy the resource as is to the top level of the resource bundle. \nIf you pass a directory path to the copy rule, the compiler retains the directory’s structure.\n\nIf a file resides inside a target’s folder and you don’t want it to be a package resource, pass it to the target initializer’s `exclude` parameter.\nFor example, if you have a file called `instructions.md` in the sources directory, meant only for local use and not intended to be bundled, use `exclude`:\n\n```swift\ntargets: [\n    .target(\n        name: \"MyLibrary\",\n        exclude:[\"instructions.md\"]\n    ),\n]\n```\n\nIn general, avoid placing files that aren’t resources in a target's source folder. \nIf that's not feasible, avoid excluding every file individually, place all files you want to exclude in a directory, and add the directory path to the array of excluded files.\nSwift Package Manager warns you about files it doesn't recognize in a target's `Sources` directory.\n\n### Access a resource in code\n\nIf a target includes resources, the compiler creates a resource bundle and an internal static extension on [Bundle](https://developer.apple.com/documentation/Foundation/Bundle) to access it for each module. \nUse the extension to locate package resources.\nFor example, use the following to retrieve the URL to a property list you bundle with your package:\n\n```swift\nlet settingsURL = Bundle.module.url(forResource: \"settings\", withExtension: \"plist\")\n```\n\n> Important: Always use `Bundle.module` to access resources.\n> A package shouldn’t make assumptions about the exact location of a resource.\n\nIf you want to make a package resource available to apps that depend on your Swift package, declare a public constant for it.\nFor example, use the following to expose a property list file to apps that use your Swift package:\n\n```swift\nlet settingsURL = Bundle.module.url(forResource: \"settings\", withExtension: \"plist\")\n```\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/ContinuousIntegration.md",
    "content": "# Continuous Integration Workflows\n\nBuild Swift packages with an existing continuous integration setup and prepare apps that consume package dependencies within an existing CI pipeline.\n\n## Overview\n\n*Continuous integration* (*CI*) is the process of automating and streamlining the building, analyzing, testing, archiving, and publishing of your apps to ensure that they're always in a releasable state.\nMost projects that contain or depend on Swift packages don't require additional configuration.\n\n## Use the Expected Version of a Package Dependency\n\nTo ensure a CI workflow’s reliability, verify it uses the appropriate version of package dependencies.\nSwiftPM records the result of dependency resolution in the file `Package.resolved`, at the top-level of the package.\nWhen available, it's used when performing dependency resolution.\n\nRun <doc:PackageUpdate> to update dependencies to the latest eligible versions and update `Package.resolved`.\nFor more information on resolving and updating dependencies, see <doc:ResolvingPackageVersions>.\n\n\n## Provide Credentials\n\nTo resolve package dependencies that require authentication, such as private packages, provide credentials to your CI setup.\nPackage manager honors the machine's SSH configuration - there's no additional setup required.\nFor private package, use the SSH-based Git URLs and configure SSH credentials.\nYou may also need to set up a `known_hosts` file in the `~/.ssh` directory of the user that runs your CI tasks.\n\nCI services like [Jenkins](https://www.jenkins.io/doc/book/using/using-credentials), [Github Action](https://docs.github.com/en/free-pro-team@latest/actions/reference/authentication-in-a-workflow), [TravisCI](https://docs.travis-ci.com/user/private-dependencies), and [CircleCI](https://circleci.com/docs/2.0/gh-bb-integration/#security) provide ways to set up SSH keys or other techniques to access private repositories.\nSince Package manager uses git to clone the repositories there's no additional setup required; Package manager honors the machine's SSH and Git configuration.\n\n## Using xcodebuild\n\nWhen building on macOS based CI hosts you can use the command-line tool `xcodebuild`.\n`xcodebuild` uses Xcode's built-in Git tooling to connect to repositories.\n\nIn many cases, you don't need to make changes to how xcodebuild connects to them.\nHowever, some use cases require you use the git configuration — for example URL remapping, the use of proxies, or advanced SSH configurations.\nTo have xcodebuild use your Mac's Git installation and configuration instead of Xcode's built-in Git tooling, pass `-scmProvider system` to the xcodebuild command.\n\nFor more information on using xcodebuild in continuous integration workflows, visit [Building Swift packages or apps that use them in continuous integration workflows](https://developer.apple.com/documentation/swift_packages/building_swift_packages_or_apps_that_use_them_in_continuous_integration_workflows).\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/CreatingCLanguageTargets.md",
    "content": "# Creating C language targets\n\nInclude C language code as a target in your Swift package.\n\n## Overview\n\nC language targets are structured similarly to Swift targets, with the additional of a directory, commonly named `include`, to hold public header files.\nIf you use a directory other than `include` for public headers, declare it using the [publicHeadersPath parameter](https://developer.apple.com/documentation/packagedescription/target/publicheaderspath) on [target](https://developer.apple.com/documentation/packagedescription/target).\n\nSwift Package manager allows only one valid C language main file for executable targets. \nFor example, it is invalid to have `main.c` and `main.cpp` in the same target.\n\n### Exposing C functions to Swift\n\nSwift Package Manager automatically generates a module map for each C language library target for these use cases:\n\n* If `include/Foo/Foo.h` exists, `Foo` is the only directory under the include directory, and the include directory contains no header files, then Swift package manager uses `include/Foo/Foo.h` as the umbrella header.\n\n* If `include/Foo.h` exists and `include` contains no other subdirectory, then Swift package manager uses `include/Foo.h` as the umbrella header for the module map.\n\n* Otherwise, Swift package manager uses the `include` directory as an umbrella directory; all headers under it are included in the module.\n\nIn case of complicated `include` layouts or headers that are not compatible with modules, provide a `module.modulemap` in the `include` directory.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/CreatingSwiftPackage.md",
    "content": "# Creating a Swift package\n\nBundle executable or shareable code into a standalone Swift package.\n\n## Overview\n\nA Swift package is a directory that contains sources, dependencies, and has a `Package.swift` manifest file at its root.\nSwift packages can provide libraries, executables, tests, plugins, and macros.\nThe package manifest defines what is in the package, which is itself written in Swift.\nThe [API reference for PackageDescription](https://developer.apple.com/documentation/packagedescription) defines the types, properties, and functions that go into assembling a package manifest.\n\n### Creating a Library Package\n\nSwift package manager supports creating packages using <doc:PackageInit>.\nBy default, the package manager creates a package structure focused on providing a library.\nFor example, you can create a directory and run the command `swift package init` to create a package:\n\n```bash\n$ mkdir MyPackage\n$ cd MyPackage\n$ swift package init\n```\n\nThe structure provided follows package manager conventions, and provides a fully operational example.\nIn addition to the package manifest, Swift sources are collected by target name under the `Sources` directory, and tests collected, also by target name, under the `Tests` directory:\n\n```\n├── Package.swift\n├── Sources\n│   └── MyPackage\n│       └── MyPackage.swift\n└── Tests\n    └── MyPackageTests\n        └── MyPackageTests.swift\n```\n\nYou can immediately use both of <doc:SwiftBuild> and <doc:SwiftTest>:\n\n```bash\n$ swift build\n$ swift test\n```\n\n### Creating an Executable Package\n\nSwift Package Manager can also create a new package with a simplified structure focused on creating executables.\nFor example, create a directory and run the `init` command with the option `--type executable` to get a package that provides a \"Hello World\" executable:\n\n```bash\n$ mkdir MyExecutable\n$ cd MyExecutable\n$ swift package init --type executable\n$ swift run\nHello, World!\n```\n\nThere is an additional option for creating a command-line executable based on the `swift-argument-parser`, convenient for parsing command line arguments and structuring commands.\nUse `tool` for the `type` option in <doc:PackageInit>.\nLike the `executable` template, it is fully operational and also prints \"Hello World\".\n\n### Creating a Macro Package\n\nSwift Package Manager can generate boilerplate for custom macros:\n\n```bash\n$ mkdir MyMacro\n$ cd MyMacro\n$ swift package init --type macro\n$ swift build\n$ swift run\nThe value 42 was produced by the code \"a + b\"\n```\n\nThis creates a package with:\n\n- A `.macro` type target with its required dependencies on [swift-syntax](https://github.com/swiftlang/swift-syntax),\n- A library `.target`  containing the macro's code.\n- An `.executableTarget` for running the macro.\n- A `.testTarget` for test the macro implementation.\n\nThe sample macro, `StringifyMacro`, is documented in the Swift Evolution proposal for [Expression Macros](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0382-expression-macros.md)\nand the WWDC [Write Swift macros](https://developer.apple.com/videos/play/wwdc2023/10166) video.\nFor further documentation, see macros in [The Swift Programming Language](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/macros/) book.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Dependencies/AddingDependencies.md",
    "content": "# Adding dependencies to a Swift package\n\nUse other Swift packages, system libraries, or binary dependencies in your package.\n\n## Overview\n\nTo depend on another Swift package, define a dependency and the requirements for its version if it's remote, then add a product of that dependency to one or more of your targets.\n\nA remote dependency requires a location, represented by a URL, and a requirement on the versions the package manager may use.\n\nThe following example illustrates a package that depends on [PlayingCard](https://github.com/apple/example-package-playingcard), using `from` to require at least version `4.0.0`, and allow any other version up to the next major version that is available at the time of dependency resolution.\nIt then uses the product `PlayingCard` as a dependency for the target `MyPackage`:\n\n```swift\n// swift-tools-version:6.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyPackage\",\n    dependencies: [\n        .package(url: \"https://github.com/apple/example-package-playingcard.git\", \n                 from: \"4.0.0\"),\n    ],\n    targets: [\n        .target(\n            name: \"MyPackage\",\n            dependencies: [\n                .product(name: \"PlayingCard\", \n                         package: \"example-package-playingcard\")\n            ]\n        ),\n        .testTarget(\n            name: \"MyPackageTests\",\n            dependencies: [\"MyPackage\"]\n        ),\n    ]\n)\n```\n\nThe package manager automatically resolves packages when you invoke <doc:SwiftRun> or <doc:SwiftBuild>. \nYou can explicitly resolve the packages with the command <doc:PackageResolve>.\nFor more information on resolving package versions, see <doc:ResolvingPackageVersions>.\n\n### Constraining dependency versions\n\nConstrain the version of a remote dependency when you declare the dependency.\nThe package manager uses git tags, interpreted as a semantic version, to identify eligible versions of packages.\n\n> Note: tags for package versions should include all three components of a semantic version: major, minor, and patch.\n> Tags that only include one or two of those components are not interpreted as semantic versions.\n\nUse the version requirement when you declare the dependency to limit what the package manager can choose.\nThe version requirement can be a range of possible semantic versions, a specific semantic version, a branch name, or a commit hash.\nThe API reference documentation for [Package.Dependency](https://docs.swift.org/swiftpm/documentation/packagedescription/package/dependency) defines the methods to use.\n\n### Packages with Traits\n\nTraits, introduced with Swift 6.1, allow packages to offer additional API that may include optional dependencies.\nPackages should offer traits to provide API beyond the core of a package.\nFor example, a package may provide an experimental API, an optional API that requires additional dependencies, or functionality that isn't critical that a developer may want to enable only in specific circumstances.\n\nIf a package offers traits and you depend on it without defining the traits to use, the package uses its default set of traits.\nIn the following example, the dependency `example-package-playingcard` uses its default traits, if it offers any:\n```swift\ndependencies: [\n  .package(url: \"https://github.com/swiftlang/example-package-playingcard\", \n           from: \"4.0.0\")\n]\n```\n\nTo determine what traits a package offers, including its defaults, either inspect its `Package.swift` manifest or use <doc:PackageShowDependencies> to print out the resolved dependencies and their traits.\n\nEnabling a trait should only expand the API offered by a package.\nIf a package offers default traits, you can choose to not use those traits by declaring an empty set of traits when you declare the dependency.\nThe following example dependency declaration uses the dependency with no traits, even if the package normally provides a set of default traits to enable:\n\n```swift\ndependencies: [\n  .package(url: \"https://github.com/swiftlang/example-package-playingcard\", \n           from: \"4.0.0\",\n           traits: [])\n]\n```\n\nSwift package manager determines the traits to enable using the entire graph of dependencies in a project.\nThe traits enabled for a dependency is the union of all of the traits that for packages that depend upon it.\nFor example, if you opt out of all traits, but a dependency you use uses the same package with some trait enabled, the package will use the depdendency with the requested traits enabled.\n\n> Note: By disabling any default traits, you may be removing available APIs from the dependency you use. \n\nTo learn how to provide packages with traits, see <doc:PackageTraits>.\n\n### Local Dependencies\n\nTo use a local package as a dependency, use either [package(name:path:)](https://developer.apple.com/documentation/packagedescription/package/dependency/package(name:path:)) or [package(path:)](https://developer.apple.com/documentation/packagedescription/package/dependency/package(path:)) to define it with the local path to the package.\nLocal dependencies do not enforce version constraints, and instead use the version that is available at the path you provide.\n\n### System Library Dependencies\n\nIn addition to depending on Swift packages, you can also depend on system libraries or, on Apple platforms, precompiled binary dependencies.\n\nFor more information on using a library provided by the system as a dependency, see <doc:AddingSystemLibraryDependency>.\n\n### Precompiled Binary Targets for Apple platforms\n\nTo add a dependency on a precompiled binary target, specify a `.binaryTarget` in your list of targets, using either \n[binarytarget(name:url:checksum:)](https://developer.apple.com/documentation/packagedescription/target/binarytarget(name:url:checksum:)) for a downloadable target, \nor [binarytarget(name:path:)](https://developer.apple.com/documentation/packagedescription/target/binarytarget(name:path:)) for a local binary.\nAfter adding the binary target, you can add it to the list of dependencies for any other target. \n\nFor more information on identifying and verifying a binary target, see [Identifying binary dependencies](https://developer.apple.com/documentation/xcode/identifying-binary-dependencies).\nFor more information on creating a binary target, see [Creating a multiplatform binary framework bundle](https://developer.apple.com/documentation/xcode/creating-a-multi-platform-binary-framework-bundle).\n\n## Topics\n\n- <doc:ResolvingPackageVersions>\n- <doc:PackageTraits>\n- <doc:ResolvingDependencyFailures>\n- <doc:AddingSystemLibraryDependency>\n- <doc:ExampleSystemLibraryPkgConfig>\n- <doc:EditingDependencyPackage>\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Dependencies/AddingSystemLibraryDependency.md",
    "content": "# Adding a dependency on a system library.\n\nDefine the location for the library and provide module map to expose C headers to Swift. \n\n## Overview\n\nYou can link against system libraries, using them as a dependency in your code, using the package manager. \nTo do so, add a `target` of type [systemLibrary](https://developer.apple.com/documentation/packagedescription/target/systemlibrary(name:path:pkgconfig:providers:)), and a `module.modulemap` for each system library you're using.\n\n### Using pkg-config to provide header and linker search paths\n\nFor Unix-like systems, Swift Package Manager can use [pkgConfig](https://en.wikipedia.org/wiki/Pkg-config) to provide the compiler with the paths for including library headers and linking to binaries.\nIf your system doesn't provide pkgConfig, or the library doesn't include package config files, you can provide the options to the Swift compiler directly.\n\n`pkgConfig` looks up libraries by name, which is the parameter that you pass to the systemLibrary target.\nThe following two examples illustrate using `libgit2` to manually look up paths for that library: \n\n```bash\n$ pkg-config --cflags libgit2\n-I/opt/homebrew/Cellar/libgit2/1.9.0/include\n```\n\nTo manually provide search paths for headers, use the `-Xcc -I/path/to/include/` as additional parameters to `swift build`.\nTo match the above example from `pkgConfig`, the additional command line options would be:\n`-Xcc -I/opt/homebrew/Cellar/libgit2/1.9.0/include`\n\n```bash\n$ pkg-config --libs-only-L libgit2\n-L/opt/homebrew/Cellar/libgit2/1.9.0/lib\n```\n\nTo manually provide search paths for linking to binaries, use the `-Xlinker -L/path/to/include/` as additional parameters to `swift build`.\nTo match the above example from `pkgConfig`, the additional command line options would be:\n`-Xlinker -L/opt/homebrew/Cellar/libgit2/1.9.0/lib`.\n\n### Declaring the system library\n\nThe `systemLibrary` definition informs the Swift compiler of where to find the C library.\nWhen building on Unix-like systems, the package manager can use `pkg-config` to look up where a library is installed.\nSpecify the name of the C library you want to look up for the `pkgConfig` parameter.\nTo use the Swift Package Manager to install the package locally, if it isn't already installed, you can specify one or more providers.\n\nThe following example provides a declaration for the `libgit2` library, installing the library with homebrew on macOS or apt on a Debian based Linux system:\n\n```swift\n.systemLibrary(\n    name: \"Clibgit\",\n    pkgConfig: \"libgit2\",\n    providers: [\n        .brew([\"libgit2\"]),\n        .apt([\"libgit2-dev\"])\n    ]\n)\n```\n\n### Authoring a module map\n\nThe `module.modulemap` file declares the C library headers, and what parts of them, to expose as one or more clang modules that can be imported in Swift code.\nEach defines:\n\n- A name for the module to be exposed\n- One or more header files to reference\n- A reference to the name of the C library\n- One or more export lines that identify what to expose to Swift\n\nFor example, the following module map uses the header `git2.h`, links to `libgit2`, and exports all functions defined in the header `git2.h` to Swift:\n\n```\nmodule Clibgit [system] {\n  header \"git2.h\"\n  link \"git2\"\n  export *\n}\n```\n\nTry to reference headers that reside in the same directory or as a local path to provide the greatest flexibility.\nYou can use an absolute path, although that makes the declaration more brittle, as different systems install system libraries in a variety of paths.\n\n> Note: Not all libraries are easily made into modules. You may have to create additional shim headers to provide the Swift compiler with the references needed to fully compile and link the library.\n\nFor more information on the structure of module maps, see the [LLVM](https://llvm.org/) documentation: [Module Map Language](https://clang.llvm.org/docs/Modules.html#module-map-language).\n\n#### Versioning Modules from system libraries\n\nWhen creating a module map, follow the conventions of system packagers as you name the module with version information.\nFor example, the Debian package for `python3` is called `python3`.\nIn Debian, there is not a single package for python; the system packagers designed it to be installed side-by-side with other versions.\nBased on that, a recommended name for a module map for `python3` on a Debian system is `CPython3`.\n\n#### System Libraries With Optional Dependencies\n\n<!-- (heckj) I need to verify this is still the case for C libraries with optional dependencies - are distinct packages still needed? -->\n\nTo reference a system library with optional dependencies, you need to make another package to represent the optional library.\n\nFor example, the library `libarchive` optionally depends on `xz`, which means it can be compiled with `xz` support, but it isn't required. \nTo provide a package that uses libarchive with xz, make a `CArchive+CXz` package that depends on `CXz` and provides `CArchive`.\n\n\n<!--#### Packages That Provide Multiple Libraries-->\n<!---->\n<!--To use a system package that provides multiple libraries, such as `.so` and `.dylib` files, add all the libraries to the `module.modulemap` file. -->\n<!---->\n<!--```-->\n<!--module CFoo [system] {-->\n<!--    header \"/usr/local/include/foo/foo.h\"-->\n<!--    link \"foo\"-->\n<!--    export *-->\n<!--}-->\n<!---->\n<!--module CFooBar [system] {-->\n<!--    header \"/usr/include/foo/bar.h\"-->\n<!--    link \"foobar\"-->\n<!--    export *-->\n<!--}-->\n<!---->\n<!--module CFooBaz [system] {-->\n<!--    header \"/usr/include/foo/baz.h\"-->\n<!--    link \"foobaz\"-->\n<!--    export *-->\n<!--}-->\n<!--```-->\n<!---->\n<!--^^ refine this out into a full example, with code included form the headers to make it possible to follow it - and drop the FOO stuff!-->\n<!---->\n<!--In the above example `foobar` and `foobaz` link to `foo`. -->\n<!--You don’t need to specify this information in the module map because the headers `foo/bar.h` and `foo/baz.h` both include `foo/foo.h`. -->\n<!--It is very important however that those headers do include their dependent headers.-->\n<!--Otherwise when the modules are imported into Swift the dependent modules are not imported automatically and you will receive link errors. -->\n<!--If link errors occur for consumers of your package, the link errors can be especially difficult to debug.-->\n\n## See Also\n\n- <doc:ExampleSystemLibraryPkgConfig>\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Dependencies/EditingDependencyPackage.md",
    "content": "# Editing a remote dependency used in a Swift package\n\nTemporarily switch a remote dependency to local in order to edit the dependency.\n\n## Overview\n\nSwift package manager supports editing dependencies, when your work requires making a change to one of your dependencies (for example, to fix a bug, or add a new API).\nThe package manager moves the dependency into a location under the `Packages/` directory where it can be edited.\n\nFor the packages which are in the editable state, `swift build` uses the exact sources in this directory to build, regardless of their state, Git repository status, tags, or the tag desired by dependency resolution.\nIn other words, this _just builds_ against the sources that are present.\nWhen an editable package is present, it is used to satisfy all instances of that package in the dependency graph.\nIt is possible to edit all, some, or none of the packages in a dependency graph, without restriction.\n\nEditable packages are best used to do experimentation with dependency code, or to create and submit a patch in the dependency owner's repository (upstream).\nThere are two ways to put a package in editable state, using <doc:PackageEdit>.\nThe first example creates a branch called `bugFix` from the currently resolved version and puts the dependency `PlayingCard` in the `Packages/` directory:\n\n```bash\n$ swift package edit PlayingCard --branch bugFix\n```\n\nThe second is similar, except that the Package Manager leaves the dependency at a detached HEAD at the commit you specified.\n\n```bash\n$ swift package edit PlayingCard --revision 969c6a9\n```\n\n> Note: If the branch or revision option is not provided, the Package Manager uses the currently resolved version on a detached HEAD.\n\nOnce a package is in an editable state, you can navigate to the directory `Packages/PlayingCard` to make changes, build and then push the changes or open a pull request to the upstream repository.\n\nYou can end editing a package with <doc:PackageUnedit>.\n\n\n```bash\n$ swift package unedit PlayingCard\n```\n\nThis removes the edited dependency from `Packages/` and restores the originally resolved version.\n\nThis command fails if you have uncommitted changes or changes which are not pushed to the remote repository.\nIf you want to discard these changes and unedit, use the `--force` option:\n\n```bash\n$ swift package unedit PlayingCard --force\n```\n\n### Top of Tree Development\n\nThis feature allows overriding a dependency with a local checkout on the filesystem.\nThis checkout is completely unmanaged by the package manager and is used as-is.\nThe only requirement is that the package name in the overridden checkout shouldn't change.\nThis is useful when developing multiple packages in tandem, or when working on packages alongside an\napplication.\n\nThe command to attach (or create) a local checkout is:\n\n```bash\n$ swift package edit <package name> \\\n    --path <path/to/dependency>\n```\n\nFor example, if `PlayingCard` depends on `swift-collections` and you have a checkout of `swift-collections` at\n`/workspace/swift-collections`:\n\n```bash\n$ swift package edit swift-collections \\\n    --path /workspace/swift-collections\n```\n\nA checkout of `swift-collections` is created if it doesn't exist at the path you specified.\nIf a checkout exists, package manager validates the package name at the given path and attaches to it.\n\nThe package manager also creates a symlink in the `Packages/` directory to the checkout path.\n\nUse <doc:PackageUnedit> command to stop using the local checkout:\n\n```bash\n$ swift package unedit swift-collections\n```\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Dependencies/ExampleSystemLibraryPkgConfig.md",
    "content": "# Swift package example that uses system library dependency with pkg-config\n\nCreate an Command-line executable package that uses libgit2 as a system library dependency.\n\n## Overview\n\nThe following example walks through creating a binary executable that depends on [libgit2](https://github.com/libgit2/libgit2).\n\n### Set up the package\n\nCreate a directory called `example`, and initialize it as a package that builds an executable:\n\n```bash\n$ mkdir example\n$ cd example\nexample$ swift package init --type executable\n```\n\nEdit the `Sources/example/main.swift` so it consists of this code:\n\n```swift\nimport Clibgit\n\nlet options = git_repository_init_options()\nprint(options)\n```\n\n### Add a system library target\n\nAdd a `systemLibrary` target to `Package.swift` that uses the `pkgConfig` parameter to look up the location of the library. \n\n```swift\n// swift-tools-version:6.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"example\",\n    targets: [\n        .systemLibrary(\n            name: \"Clibgit\",\n            pkgConfig: \"libgit2\",\n            providers: [\n                .brew([\"libgit2\"]),\n                .apt([\"libgit2-dev\"])\n            ]\n        )\n    ]\n)\n\n```\n\nThe above example specifies two `providers` that Swift Package Manager can use to install the dependency, if needed.\n\n> Note: For Windows-only packages `pkgConfig` should be omitted as `pkg-config` is not expected to be available. \n> If you can't or don't want to use the `pkgConfig` parameter, pass the path of a directory containing the\n> library using the `-L` flag in the command line when building your package instead.\n> \n> ```bash\n> % swift build -Xlinker -L/usr/local/lib/\n> ```\n\nThis example follows the convention of prefixing modules with `C` and using camelcase for the rest of the library, following Swift module name conventions.\nThis allows you to create and use another module more directly named after the library that provides idiomatic Swift wrappers around the underlying C functions.\n\n### Create a module map and local header\n\nCreate a directory `Sources/Clibgit` in your `example` project, and add a `module.modulemap` in the directory:\n\n```\nmodule Clibgit [system] {\n  header \"git2.h\"\n  link \"git2\"\n  export *\n}\n```\n\nIn the same directory, create the header file, `git2.h`, that the above module map references: \n\n```c\n// git2.h\n#pragma once\n#include <git2.h>\n```\n\n> Tip: Try to avoid specifying an absolute system path in the module map to the `git2.h` header provided by the library. \n> Doing so will break compatibility of your project between machines that use a different file system layout or install libraries to different paths.\n\nThe `example` directory structure should look like this now:\n\n```\n.\n├── Package.swift\n└── Sources\n    ├── Clibgit\n    │   ├── git2.h\n    │   └── module.modulemap\n    └── main.swift\n```\n\n### Add the system library dependency to the executable target\n\nWith the system library target fully defined, you can now use it as a dependency in other targets.\n\nFor example, in `Package.swift`:\n\n```swift\n// swift-tools-version:6.1\nimport PackageDescription\n\nlet package = Package(\n    name: \"example\",\n    targets: [\n        .executableTarget(\n            name: \"example\",\n            dependencies: [\"Clibgit\"],\n            path: \"Sources\"\n        ),\n        .systemLibrary(\n            name: \"Clibgit\",\n            pkgConfig: \"libgit2\",\n            providers: [\n                .brew([\"libgit2\"]),\n                .apt([\"libgit2-dev\"])\n            ]\n        )\n    ]\n)\n\n```\n\n### Run the example\n\nNow run the command `swift run` in the example directory to create and run the executable:\n\n```bash\n% example swift run\nBuilding for debugging...\n[1/1] Write swift-version-3E695E30EE234B31.txt\nBuild of product 'example' complete! (0.10s)\ngit_repository_init_options(version: 0, flags: 0, mode: 0, workdir_path: nil, description: nil, template_path: nil, initial_head: nil, origin_url: nil)\n```\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Dependencies/PackageTraits.md",
    "content": "# Providing configurable packages using traits\n\nDefine one or more package traits to offer default and configurable features for a package.\n\n## Overview\n\nSwift packages before version 6.1 offer a non-configurable API surface for each version.\nStarting with Swift 6.1, packages may offer traits, which express a configurable API surface for a package.\n\nUse traits to enable additional API beyond the core API of the package.\nFor example, a trait may enable an experimental API, optional extended functionality that requires additional dependencies, or functionality you may want to enable only in specific circumstances.\n\nTraits that you specify when building a package only activate within the package you're building.\nIf your package wants to use a trait in a dependent package, it needs to encode the traits it needs in its dependencies.\n\n> Note: Don't remove or disable public API when you enable a trait.\n\nWithin the package that defines a trait, the trait expresses conditional compilation.\nSwift Package Manager exposes enabled traits as conditional blocks (for example, `#if YourTrait`) that you can use to conditionally enable imports or different compilation paths in code.\n\nTrait names are namespaced within the package that hosts them.\nA trait name in one package has no impact on any other package.\nTrait names must be [valid Swift identifiers](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/lexicalstructure#Identifiers) with the addition of the characters of `-` and `+`.\nDon't use the trait names `default` or `defaults` (regardless of capitalization).\nThese values aren't allowed to avoid confusion with the default traits that a package defines.\n\n### Declare traits\n\nCreate a trait to define additional functionality, and define it in the [traits](https://docs.swift.org/swiftpm/documentation/packagedescription/package/traits) property of the package manifest.\nUse [`.default(enabledTraits:)`](https://docs.swift.org/swiftpm/documentation/packagedescription/trait/default(enabledtraits:)) to provide the set of traits that the package uses by default.\nIf you don't define a default set of traits to enable, Swift Package Manager enables no traits by default.\n\nThe following example illustrates a single trait, `FeatureA`, that is enabled by default:\n\n```swift\n// ...\ntraits: [\n    .trait(name: \"FeatureA\"),\n    .default(enabledTraits: [\"FeatureA\"]),\n],\n// ...\n```\n\nTraits can also represent a set of other traits, which allows you to group features together.\nThe following example illustrates defining three traits, and an additional trait (`B-and-C`) that enables both traits `FeatureB` and `FeatureC`:\n\n```swift\n// ...\ntraits: [\n    .trait(name: \"FeatureA\"),\n    .trait(name: \"FeatureB\"),\n    .trait(name: \"FeatureC\"),\n    .trait(name: \"B-and-C\", enabledTraits: [\"FeatureB\", \"FeatureC\"]),\n    .default(enabledTraits: [\"FeatureA\"]),\n],\n// ...\n```\n\nFor the example above, the default trait is `FeatureA`.\n\n> Note: Changing the default set of traits for your package is a major semantic version change if it removes API surface.\n> Adding traits isn't a major version change.\n\nSwift Package Manager treats traits as purely additive, and unifies enabled traits across all packages within the build graph.\nDesign your traits so that they enable additional API (and their dependencies, if needed).\n\n#### Define mutually exclusive traits\n\nThe package manifest format doesn't support declaring mutually exclusive traits.\nIn the rare case that you need to offer mutually exclusive traits, protect that scenario in code:\n\n```swift\n#if FeatureA && FeatureC\n#error(\"FeatureA and FeatureC are mutually exclusive\")\n#endif // FeatureA && FeatureC\n```\n\n> Note: Providing mutually exclusive traits can result in compilation errors when a developer enables them.\n\n### Depend on a package with a trait\n\nA package dependency that doesn't specify traits uses the package with its default traits enabled.\nTo enable specific traits, add them to the `traits` parameter in the package dependency declaration.\n\nThe following example shows how to depend on `swift-configuration` with both the `defaults` and `YAML` traits enabled:\n\n```swift\ndependencies: [\n    .package(\n        url: \"https://github.com/apple/swift-configuration.git\",\n        from: \"1.0.0\",\n        traits: [\n            .defaults,\n            \"YAML\"\n        ]\n    ),\n]\n```\n\n> Tip: When you specify traits for a dependency, you explicitly define which traits to enable.\n> The default traits aren't included automatically.\n> To use both the default and additional traits, add `.defaults` to the list of traits you specify.\n\n### Use traits in your code\n\nUse the name of a trait for conditional compilation.\nWrap the additional API surface for that trait within a conditional compilation block.\nFor example, if the trait `FeatureA` is defined and enabled, the compiler sees and compiles the function `additionalAPI()`:\n\n```swift\n#if FeatureA\npublic func additionalAPI() {\n  // ...\n}\n#endif // FeatureA\n```\n\n### Use a trait to enable conditional dependencies\n\nYou can use a trait to optionally include a dependency, or a dependency with specific traits enabled, to support the functionality you expose with a trait.\nTo do so, add the dependency you need to the manifest's `dependencies` declaration,\nthen use a conditional dependency for a trait or traits defined in the package to add that dependency to a target.\n\nThe following example illustrates the relevant portions of a package manifest that defines a trait `FeatureB`, a local dependency that is used only when the trait is enabled:\n\n```swift\n// ...\ntraits: [\n    \"FeatureB\"\n    // this trait exists only within *this* package\n],\ndependencies: [\n    .package( \n        path: \"../some/local/path\",\n        traits: [\"DependencyFeatureTrait\"] \n    // this enables the trait DependencyFeatureTrait on \n    // the local dependency at ../some/local/path.\n    )\n]\n// ... \ntargets: [\n    .target(\n        name: \"MyTarget\",\n        dependencies: [\n            .product(\n                name: \"MyAPI\",\n                package: \"MyDependency\",\n                condition: .when(traits: [\"FeatureB\"]) \n    // if the FeatureB trait is enabled in *this* package, then\n    // the `MyAPI` product is included as a dependency for `MyTarget`.\n            )\n        ]\n    ),\n]\n```\n\nThe following code wraps the import with the trait's conditional compilation, and defines additional API that uses the dependency:\n\n```swift\n#if FeatureB\n    import MyAPI\n#endif // FeatureB\n\n// ...\n\n#if FeatureB\n    public func additionalAPI() {\n        MyAPI.provideExtraFunctionality()\n        // ...\n    }\n#endif // FeatureB\n```\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Dependencies/ResolvingDependencyFailures.md",
    "content": "# Resolving package dependency failures\n\nUnderstand dependency failure scenarios.\n\n## Overview\n\nYou define constraints for dependencies when you add them to your package, and those constraints can not always be met.\n\nPrior to running a build or test, or when you run <doc:PackageResolve>, the package manager walks through the dependencies in your package, and all their dependencies recursively, to build a complete list.\nIt then attempts to choose a version of each dependency that fits within the constraints of your package, and any constraints provided by your dependencies.\n\nIf all the dependencies are available and resolved, the versions are recorded locally in the file `Package.resolved`.\nYou can view these dependencies using the command <doc:PackageShowDependencies>, which provides a succint list of the entire set of dependencies.\n\nIf the dependencies can't be resolved, for example when the packages your package depends on have conflicting constraints, the package manager returns an error, describing the conflicting constraint: \n```\nerror: Dependencies could not be resolved because root depends on 'pkgb' 0.1.0.\n'pkgb' 0.1.0 cannot be used because 'pkgb' 0.1.0 depends on 'pkga' 0.3.0 and root depends on 'pkga' 0.4.0.\n```\n\nRework your dependencies, or update a package you want to depend upon, to resolve any conflicting constraints.\n\n### Failure Scenarios\n\nThere are a variety of scenarios that may occur, including:\n\n- term Inappropriate Versioning: A package may specify an inappropriate version for a release. \n  For example, a version is tagged `1.2.3`, but introduces extensive, breaking API changes that should be reflected by a major version bump to `2.0.0`.\n\n- term Incompatible Major Version Requirements: A package may have dependencies with incompatible version requirements for the same package. \n  For example, if `Foo` depends on `Baz` at version `~>1.0` and `Bar` depends on `Baz` at version `~>2.0`, then there is no one version of `Baz` that can satisfy both requirements. \n  This situation often arises when a dependency shared by many packages updates to a new major version, and it takes a long time for all of those packages to update their dependency.\n\n- term Incompatible Minor or Update Version Requirements: A package may have dependencies that are specified too strictly, such that version requirements are incompatible for different minor or update versions. \n  For example, if `Foo` depends on `Baz` at version `==2.0.1` and `Bar` depends on `Baz` at version `==2.0.2`, once again, there is no one version of `Baz` that can satisfy both requirements. \n  This is often the result of a regression introduced in a patch release of a dependency, which causes a package to lock that dependency to a particular version.\n\n- term Namespace Collision: A package may have two or more dependencies that have the same name. \n  For example, a `Person` package depends on an `Addressable` package that defines a protocol for assigning a mailing address to a person, as well as an `Addressable` package that defines a protocol for speaking formally to another person.\n\n- term Broken Software: A package may have a dependency with an outstanding bug that is impacting usability, security, or performance.\n  This may simply be a matter of timeliness on the part of the package maintainers, or a disagreement about their expectations for the package.\n\n- term Global State Conflict: A package may have two or more dependencies that presume to have exclusive access to the same global state.\n  For example, one package may not be able to accommodate another package writing to a particular file path while reading from that same file path.\n\n- term Package Becomes Unavailable: A package may have a dependency on a package that becomes unavailable.\n  This may be caused by the source URL becoming inaccessible, or maintainers deleting a published version.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Documentation.md",
    "content": "# ``PackageManagerDocs``\n\n@Metadata {\n    @DisplayName(\"Swift Package Manager\")\n}\n\nOrganize, manage, and edit Swift packages.\n\n## Overview\n\nThe Swift Package Manager lets you share your code as a package, depend on and use other shared packages, as well as build, test, document, and run your code.\n\n> Note: Swift Package Manager is previewing the Swift Build build system. Learn more [here](<doc:SwiftBuildPreview>).\n\n## Topics\n\n### Essentials\n\n- <doc:GettingStarted>\n- <doc:IntroducingPackages>\n- <doc:PackageSecurity>\n\n### Guides\n\n- <doc:SwiftBuildPreview>\n- <doc:CreatingSwiftPackage>\n- <doc:SettingSwiftToolsVersion>\n- <doc:AddingDependencies>\n- <doc:ResolvingPackageVersions>\n- <doc:CreatingCLanguageTargets>\n- <doc:UsingBuildConfigurations>\n- <doc:SwiftVersionSpecificPackaging>\n- <doc:BundlingResources>\n- <doc:ReleasingPublishingAPackage>\n- <doc:GeneratingSBOMs>\n- <doc:ContinuousIntegration>\n- <doc:Plugins>\n- <doc:ModuleAliasing>\n- <doc:UsingSwiftPackageRegistry>\n- <doc:PackageCollections>\n- <doc:UsingShellCompletion>\n- <doc:SwiftPMAsALibrary>\n\n<!-- ### Command Plugins -->\n<!-- placeholder for content about swift package manager extensions - command plugins -->\n<!-- - <doc:swift-format> -->\n<!-- - <doc:swift-docc-plugin> -->\n<!-- - <doc:swift-container-plugin> -->\n\n<!-- reference content for the CLI commands `swift ...` -->\n### Swift Commands\n\n- <doc:SwiftBuild>\n- <doc:SwiftTest>\n- <doc:SwiftPackageCommands>\n- <doc:SwiftSDKCommands>\n- <doc:SwiftPackageRegistryCommands>\n- <doc:SwiftPackageCollectionCommands>\n- <doc:SwiftRun>\n\n### Design\n\n- <doc:RegistryServerSpecification>\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/GeneratingSBOMs.md",
    "content": "# Generating Software Bill of Materials (SBOM)\n\nCreate an inventory of components and dependencies using SBOM documents.\n\n## Overview\n\nSwift Package Manager generates Software Bill of Materials (SBOM) documents for Swift packages and products.\n\nSwift Package Manager currently supports two SBOM formats: CycloneDX and SPDX. \n\nGenerate SBOMs using either the [`swift build`](doc:SwiftBuild) command with SBOM flags or the dedicated [`swift package generate-sbom`](doc:PackageGenerateSBOM) subcommand.\n\n### Use the build command to generate SBOMs\n\nUse the command `swift build` to compile your project and generate SBOMs.\nUsing the `--sbom-spec` and `--target` flags together causes an error.\n\nGenerating SBOMs through the Swift Build build backend factors in build-time conditionals.\n\n```bash\nswift build --build-system swiftbuild --sbom-spec cyclonedx\nswift build --build-system swiftbuild --sbom-spec spdx\nswift build --build-system swiftbuild --sbom-spec cyclonedx --sbom-spec spdx\n```\n\nThe following examples generate SBOMs without using the Swift Build build backend. SBOMs generated without Swift Build may not be fully accurate, as build-time conditionals aren't applied to the SBOMs.\n\n```bash\nswift build --sbom-spec cyclonedx\nswift build --sbom-spec spdx\nswift build --sbom-spec cyclonedx --sbom-spec spdx\n```\n\n### Use the package command to generates SBOMs\n\n[`swift package generate-sbom`](doc:PackageGenerateSBOM) generates an SBOM without building.\nThis SBOM is less accurate than an SBOM generated from `swift build --build-system swiftbuild` because build-time conditionals aren't applied.\n\nFor the highest accuracy, generate SBOMs using the command `swift build --build-system swiftbuild`.\n\nNot specifying `--sbom-spec` generates all SBOM specs supported by Swift Package Manager.\n\n```bash\nswift package generate-sbom --sbom-spec cyclonedx\nswift package generate-sbom --sbom-spec spdx\nswift package generate-sbom --sbom-spec cyclonedx --sbom-spec spdx\nswift package generate-sbom\n```\n\n### Configure additional flags\n\nThe following flags apply to both `swift build` and `swift package generate-sbom`:\n\n#### Generate SBOM for a single product\n\nGenerate an SBOM for a specific product in a package using the `--product` flag.\n\n```bash\nswift build --build-system swiftbuild --product MyProduct --sbom-spec cyclonedx\nswift package generate-sbom --product MyProduct --sbom-spec spdx\n```\n\n#### Filter SBOM contents\n\nFilter an SBOM by packages or products by using `--sbom-filter <type>`. By default, an SBOM includes both packages and products.\nSwift Package Manager always includes the primary component, regardless of the applied filter.\n\n```bash\nswift build --build-system swiftbuild --sbom-spec cyclonedx --sbom-filter package\nswift package generate-sbom --sbom-spec spdx --sbom-filter product\n```\n\n#### Output SBOM to custom directory\n\nSwift Package Manager places generated SBOMs in `<build_output>/sboms` by default.\nUse `--sbom-output-dir` to specify a different directory for generated SBOMs.\n\n```bash\nswift build --build-system swiftbuild --sbom-spec cyclonedx --sbom-output-dir <path>\nswift package generate-sbom --sbom-spec spdx --sbom-output-dir <path>\n```\n\n#### Reduce SBOM generation errors to warnings\n\nBy default, if SBOM generation fails, the `build` or `package` command also fails.\nThe `--sbom-warning-only` flag converts all SBOM generation errors to warnings.\n\n```bash\nswift build --build-system swiftbuild --sbom-spec cyclonedx --sbom-warning-only\nswift package generate-sbom --sbom-spec spdx --sbom-warning-only\n```\n\n### Configure environment variables\n\nGenerating SBOMs can be triggered and configured using environment variables that you set prior to running `swift build` or `swift package generate-sbom`.\nWhen you use CLI flags, they take precedence over environment variables.\n\nConfigure the following environment variables:\n\n- `SWIFTPM_BUILD_SBOM_SPEC`\n- `SWIFTPM_BUILD_SBOM_OUTPUT_DIR`\n- `SWIFTPM_BUILD_SBOM_FILTER`\n- `SWIFTPM_BUILD_SBOM_WARNING_ONLY`\n\n```bash\nSWIFTPM_BUILD_SBOM_SPEC=cyclonedx,spdx swift build --build-system swiftbuild\nSWIFTPM_BUILD_SBOM_SPEC=cyclonedx swift package generate-sbom\n```\n\nWhen generating SBOMs using `swift build` and environment variables, `swift build` will generate SBOMS if, and only if, the `SWIFTPM_BUILD_SBOM_SPEC` is set.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/GettingStarted.md",
    "content": "# Getting Started\n\nLearn to create and use Swift packages.\n\n## Overview\n\nTo provide a more complete look at what the Swift Package Manager can do, the following example consists of three interdependent packages, which you can explore:\n\n- [PlayingCard](https://github.com/apple/example-package-playingcard) - Defines PlayingCard, Suit, and Rank types.\n- [DeckOfPlayingCards](https://github.com/apple/example-package-deckofplayingcards) - Defines a Deck type that shuffles and deals an array of PlayingCard values.\n- [Dealer](https://github.com/apple/example-package-dealer) - Defines an executable that creates a DeckOfPlayingCards, shuffles it, and deals the first 10 cards.\n\nThis guide shows you how to create a library that uses another library as a dependency, use the Package Manager to build and test your code, and show you how you might release your own package.\n\n### Creating a library package\n\nThis example starts with using an existing package that represents a playing card in a standard 52-card deck.\nThe package, [PlayingCard](https://github.com/apple/example-package-playingcard), is available through git and provides a library (`PlayingCard`) that this guide uses and expands upon.\n\nThis example creates the library `DeckOfPlayingCards` that provides a type that represents a deck of cards and common interactions with the deck, including shuffling, counting, and dealing. \nTo start a new library, first make an empty directory, and within it run the `swift package init` command to initialize a new package:\n\n```bash\nmkdir DeckOfPlayingCards\ncd DeckOfPlayingCards\nswift package init\n```\n\nThe default template that Package Manager creates is a library, which you can control with the `--type` parameter.\nThe name of the package defaults to the name of the directory you created, and can be overridden with the `--name` parameter to the `swift package init` command.\nFor the complete details on options for this command, see the [swift package init documentation](https://docs.swift.org/swiftpm/documentation/packagemanagerdocs/packageinit).\n\nThe template generates a structure of files in the directory that follow the defaults for a Swift package:\n\n```bash\nDeckOfPlayingCards\n├── .gitignore\n├── Package.swift\n├── Sources\n│   └── DeckOfPlayingCards\n│       └── DeckOfPlayingCards.swift\n└── Tests\n    └── DeckOfPlayingCardsTests\n        └── DeckOfPlayingCardsTests.swift\n```\n\nThe template provides a directory to host a single module that is exposed as a library at `Sources/DeckOfPlayingcards`, and a matching directory to host the tests.\nThe default package structure provides a library that consists of a single target, both of which are named the same as the package: `DeckOfPlayingCards`, and a test target where you can add tests as you develop your code.\n\n```swift\nlet package = Package(\n    name: \"DeckOfPlayingCards\",\n    products: [\n        // Products define the executables and libraries a package produces, making them visible to other packages.\n        .library(\n            name: \"DeckOfPlayingCards\",\n            targets: [\"DeckOfPlayingCards\"]\n        ),\n    ],\n    targets: [\n        // Targets are the basic building blocks of a package, defining a module or a test suite.\n        // Targets can depend on other targets in this package and products from dependencies.\n        .target(\n            name: \"DeckOfPlayingCards\"\n        ),\n        .testTarget(\n            name: \"DeckOfPlayingCardsTests\",\n            dependencies: [\"DeckOfPlayingCards\"]\n        ),\n    ]\n)\n```\n\n### Adding a dependency\n\nTo add the dependency on the library that provides a PlayingCard so that this example can use it, use the `add-dependency` command, providing the location where the package is hosted. \n\n```bash\nswift package add-dependency https://github.com/apple/example-package-playingcard --from 3.0.0\n```\n\nEach dependency within a package specifies a source URL and version requirements.\nThe source URL is a URL accessible to the current user that resolves to a Git repository.\nThe package manager uses the version requirements, which follow Semantic Versioning (SemVer) conventions, to determine which Git tag to check out and use to build the dependency.\n\nThe above example uses the parameter `--from 3.0.0`, to indicate the version requirements for the dependency.\nThe `from` constrains the dependency chosen to a minimum of `3.0.0` and extending up to the highest minor and patch release available from the git repository.\nPackage Manager uses tags, interpreting them as semantic versions, to determine the versions available.\nThe command updated the `Package.swift` manifest file, adding the `dependencies` section:\n\n```swift\nlet package = Package(\n    name: \"DeckOfPlayingCards\",\n    products: [\n        ...\n    ],\n    dependencies: [\n        .package(url: \"https://github.com/apple/example-package-playingcard\", from: \"3.0.0\"),\n    ],\n    targets: [\n        ...\n    ]\n)\n```\n\nAdding the dependency makes it available to the package, but doesn't include it by default into the targets within the package.\nFor example, if you are attempting to build the package using `swift build`, the build would succeed, but provide the warning:\n\n```bash\nwarning: 'deckofplayingcards': dependency 'example-package-playingcard' is not used by any target\n```\n\nIf you attempted to use the library in the source, for example `import PlayingCard`, the compiler reports `No such module 'PlayingCard'`.\n\nWhen you run the swift build command, the Package Manager downloads all of the dependencies, compiles them, and links them to the package module based on the Package.swift manifest.\nYou can see the downloaded sources in the `.build/checkouts` directory at the root of your project, and intermediate build products in the `.build` directory at the root of your project.\n\nYou also need to include the dependency on the target where you want to use the library.\nUse the command `add-target-dependency` to add the dependency to the target in this package.\n\n```bash\nswift package add-target-dependency PlayingCard DeckOfPlayingCards --package example-package-playingcard\n```\n\nThis allows DeckOfPlayingCards to access the public members of its dependent modules with import statements.\nThe above command updates the `Package.swift` manifest so that the DeckOfPlayingCards target now references the dependency:\n\n```swift\n.target(\n    name: \"DeckOfPlayingCards\",\n    dependencies: [\n        .target(name: \"PlayingCard\"),\n    ]\n),\n```\n \nWith this update in place, when you run `swift build` the package compiles without warnings.\n\n### Implement the library\n\nThe template provides an empty file for the source for your package. Remove the content, add `import PlayingCard`, and your implementation.\nThe following code provides an example implementation:\n\n```swift\nimport PlayingCard\n\n/// A model for shuffling and dealing a deck of playing cards.\n///\n/// The playing card deck consists of 52 individual cards in four suites: spades, hearts, diamonds, and clubs.\n/// There are 13 ranks from two to ten, then jack, queen, king, and ace.\npublic struct Deck: Equatable {\n  fileprivate var cards: [PlayingCard]\n\n  /// Returns a deck of playing cards.\n  public static func standard52CardDeck() -> Deck {\n    var cards: [PlayingCard] = []\n    for rank in Rank.allCases {\n      for suit in Suit.allCases {\n        cards.append(PlayingCard(rank: rank, suit: suit))\n      }\n    }\n\n    return Deck(cards)\n  }\n\n  /// Creates a deck of playing cards.\n  public init(_ cards: [PlayingCard]) {\n    self.cards = cards\n  }\n\n  /// Randomly shuffles a deck of playing cards.\n  public mutating func shuffle() {\n    cards.shuffle()\n  }\n\n  /// Deals a card from the deck.\n  ///\n  /// The function returns the last card in the deck.\n  public mutating func deal() -> PlayingCard? {\n    guard !cards.isEmpty else { return nil }\n\n    return cards.removeLast()\n  }\n\n  /// The number of remaining cards in the deck.\n  public var count: Int {\n    cards.count\n  }\n}\n\n// MARK: - ExpressibleByArrayLiteral\n\nextension Deck: ExpressibleByArrayLiteral {\n  public init(arrayLiteral elements: PlayingCard...) {\n    self.init(elements)\n  }\n}\n```\n\nUse `swift build` to build the package, and `swift test` to run all the tests associated with the package.\nThe default template also includes the structure that uses [swift-testing](https://swiftpackageindex.com/swiftlang/swift-testing/documentation/testing) by default, including an empty but functional single test:\n\n```bash\n[1/1] Planning build\nBuilding for debugging...\n[10/10] Linking DeckOfPlayingCardsPackageTests\nBuild complete! (2.68s)\nTest Suite 'All tests' started at 2025-10-09 13:12:08.094.\nTest Suite 'All tests' passed at 2025-10-09 13:12:08.095.\n     Executed 0 tests, with 0 failures (0 unexpected) in 0.000 (0.001) seconds\n◇ Test run started.\n↳ Testing Library Version: 1400\n↳ Target Platform: arm64e-apple-macos14.0\n◇ Test example() started.\n✔ Test example() passed after 0.001 seconds.\n✔ Test run with 1 test in 0 suites passed after 0.001 seconds.\n```\n\n### Add tests for your package\n\nExtend the tests to work with the code in your library. Update the contents of `Tests/DeckOfPlayingCardsTests/DeckOfPlayingCardsTests.swift`:\n\n```swift\nimport DeckOfPlayingCards\nimport PlayingCard\nimport Testing\n\nstruct DeckTests {\n  @Test\n  func standard52CardDeck() {\n    var countByPlayingCard: [PlayingCard: Int] = [:]\n\n    var deck = Deck.standard52CardDeck()\n    while let playingCard = deck.deal() {\n      countByPlayingCard[playingCard, default: 0] += 1\n    }\n\n    #expect(countByPlayingCard.count == 52)\n    #expect(countByPlayingCard.values.allSatisfy({ $0 == 1 }))\n\n    for rank in Rank.allCases {\n      for suit in Suit.allCases {\n        let playingCard = PlayingCard(rank: rank, suit: suit)\n        #expect(countByPlayingCard[playingCard] == 1)\n      }\n    }\n  }\n\n  @Test\n  func deal() {\n    let playingCard = PlayingCard(rank: .ace, suit: .clubs)\n    var deck: Deck = [playingCard]\n\n    #expect(deck.deal() == playingCard)\n    #expect(deck.deal() == nil)\n  }\n\n  @Test\n  func countEmptyDeckHasZeroCards() {\n    let deck = Deck()\n    //XCTAssertEqual(deck.count, 0)\n    #expect(deck.count == 0)\n  }\n\n  @Test\n  func countStandard52CardDeckHas52Cards() {\n    let deck = Deck.standard52CardDeck()\n\n    #expect(deck.count == 52)\n  }\n\n  @Test\n  func countDealingDecreasesCountByOne() throws {\n    var deck = Deck([\n      PlayingCard(rank: .ace, suit: .spades), PlayingCard(rank: .queen, suit: .hearts),\n    ])\n\n    #expect(deck.count == 2)\n    try #require(deck.deal() != nil)\n    #expect(deck.count == 1)\n  }\n}\n```\n\nThen when you run the tests again, you see each of the tests and their results:\n\n```bash\nBuilding for debugging...\n[6/6] Linking DeckOfPlayingCardsPackageTests\nBuild complete! (0.44s)\nTest Suite 'All tests' started at 2025-10-09 13:16:44.052.\nTest Suite 'All tests' passed at 2025-10-09 13:16:44.052.\n     Executed 0 tests, with 0 failures (0 unexpected) in 0.000 (0.001) seconds\n◇ Test run started.\n↳ Testing Library Version: 1400\n↳ Target Platform: arm64e-apple-macos14.0\n◇ Suite DeckTests started.\n◇ Test deal() started.\n◇ Test countStandard52CardDeckHas52Cards() started.\n◇ Test countEmptyDeckHasZeroCards() started.\n◇ Test standard52CardDeck() started.\n◇ Test countDealingDecreasesCountByOne() started.\n✔ Test countDealingDecreasesCountByOne() passed after 0.001 seconds.\n✔ Test deal() passed after 0.001 seconds.\n✔ Test countStandard52CardDeckHas52Cards() passed after 0.001 seconds.\n✔ Test countEmptyDeckHasZeroCards() passed after 0.001 seconds.\n✔ Test standard52CardDeck() passed after 0.001 seconds.\n✔ Suite DeckTests passed after 0.001 seconds.\n✔ Test run with 5 tests in 1 suite passed after 0.001 seconds.\n```\n\n> The complete code for the DeckOfPlayingCards example package can be found at [https://github.com/apple/example-package-deckofplayingcards](https://github.com/apple/example-package-deckofplayingcards).\n\n### Share your package\n\nYou can use this package from other Swift packages locally, or share the package through a git hosting provider.\nWhen you want to release your own package, create a git tag that matches the major, minor, and patch versions of a semantic version and push the tag to your git hosting provider.\nFor example, to tag the package with the semantic version `0.1`, which indicates that it's an initial minor release, use the tag `0.1.0`.\n\nFor more information about sharing packages, see [Releasing and publishing a Swift package](https://docs.swift.org/swiftpm/documentation/packagemanagerdocs/releasingpublishingapackage).\n\n### Resolving transitive dependencies\n\nThe Package Manager resolves dependencies for the package you're using and all of its transitive dependencies.\nAnother example package, `Dealer`, illustrates how this works by using the example of the package this guide created.\nYou can explore the example package online at [https://github.com/swiftlang/example-package-dealer/](https://github.com/swiftlang/example-package-dealer/), or download it locally to explore:\n\n```bash\ngit clone https://github.com/swiftlang/example-package-dealer.git\ncd example-package-dealer\n```\n\nThe dealer package includes an additional dependency to [Swift Argument Parser](https://github.com/apple/swift-argument-parser), a package that helps parse arguments for command-line applications.\n\n\nTo see the package resolution and choices, run the command `swift package resolve`.\n\n```bash\nFetching https://github.com/swiftlang/example-package-deckofplayingcards.git\nFetching https://github.com/apple/swift-argument-parser.git from cache\nFetched https://github.com/swiftlang/example-package-deckofplayingcards.git from cache (0.41s)\nFetched https://github.com/apple/swift-argument-parser.git from cache (0.58s)\nComputing version for https://github.com/swiftlang/example-package-deckofplayingcards.git\nComputed https://github.com/swiftlang/example-package-deckofplayingcards.git at 4.0.0 (0.94s)\nFetching https://github.com/apple/example-package-playingcard.git from cache\nFetched https://github.com/apple/example-package-playingcard.git from cache (0.30s)\nComputing version for https://github.com/apple/example-package-playingcard.git\nComputed https://github.com/apple/example-package-playingcard.git at 4.0.0 (0.66s)\nComputing version for https://github.com/apple/swift-argument-parser.git\nComputed https://github.com/apple/swift-argument-parser.git at 1.6.1 (0.39s)\nCreating working copy for https://github.com/apple/swift-argument-parser.git\nWorking copy of https://github.com/apple/swift-argument-parser.git resolved at 1.6.1\nCreating working copy for https://github.com/apple/example-package-playingcard.git\nWorking copy of https://github.com/apple/example-package-playingcard.git resolved at 4.0.0\nCreating working copy for https://github.com/swiftlang/example-package-deckofplayingcards.git\nWorking copy of https://github.com/swiftlang/example-package-deckofplayingcards.git resolved at 4.0.0\n```\n\nThis process happens automatically when you run `swift build` or `swift test`, making the dependencies available for your project.\nAs with the previous package, you can build this package with `swift build`, and run and see the tests for the package using the command `swift test`.\n\nAs the dealer package provides a command-line executable, you can also run the executable built by the package using `swift run`:\n\n```bash\n[1/1] Planning build\nBuilding for debugging...\n[1/1] Write swift-version-2C315BDEC41BFF30.txt\nBuild of product 'dealer' complete! (0.13s)\nError: Missing expected argument '<count> ...'\n\nOVERVIEW: Shuffles a deck of playing cards and deals a number of cards.\n\nFor each count argument, prints a line of tab-delimited cards to stdout,\nor if there aren't enough cards remaining,\nprints \"Not enough cards\" to stderr and exits with a nonzero status.\n\nUSAGE: dealer <count> ...\n\nARGUMENTS:\n  <count>                 The number of cards to deal at a time.\n\nOPTIONS:\n  -h, --help              Show help information.\n```\n\nSpecify the name of the executable along with any required arguments to try it out, for example `swift run dealer 5`:\n\n```bash\nBuilding for debugging...\n[1/1] Write swift-version-2C315BDEC41BFF30.txt\nBuild of product 'dealer' complete! (0.07s)\n♢ J    ♢ 3    ♢ 7    ♣︎ 5    ♡ 7\n```\n\nThe build product from the package is also available in the `.build` directory by default, where you can also execute the tool directly.\nFor example, the debug build (the default) for the dealer package is available at `.build/debug/dealer`.\nYou can invoke that from the terminal: `.build/debug/dealer 5`\n\n```bash\n♠︎ 6    ♡ 4    ♣︎ 4    ♡ A    ♡ K\n```\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/IntroducingPackages.md",
    "content": "# Introducing Packages\n\nLearn to create and use a Swift package.\n\n## Overview\n\nA package consists of a `Package.swift` manifest file along with source files, resources, and other assets. \nThe manifest file, or package manifest, defines the package's name and its contents using the [PackageDescription](https://developer.apple.com/documentation/packagedescription) module.\n\nEach package declares [Products](https://docs.swift.org/swiftpm/documentation/packagedescription/product), a list of what the package produces.\nTypes of products include libraries, executables, and plugins:\n\n- A library defines one or more modules that can be imported by other code.\n- An executable is a program that can be run by the operating system.\n- A plugin is executable code that the Swift Package Manager may use to provide additional commands or build capabilities.\n\nA package may declare [Dependencies](https://docs.swift.org/swiftpm/documentation/packagedescription/package/dependency), that provide products from other Swift packages.\nA dependency may also be defined to a system library or binary (non-source) artifact.\n\nEach product is made up of one or more [Targets](https://docs.swift.org/swiftpm/documentation/packagedescription/target), the basic building block of a Swift package.\nEach target specifies an module, may declare one or more dependencies on other targets within the same package and on products vended by the package’s dependencies.\nA target may define a library, a test suite, an executable, an macro, a binary file, and so on.\n\n### About Modules\n\nA Swift package organizes code into _modules_, a unit of code distribution.\nA module specifies a namespace and enforces access controls on which parts of the code can be used outside of that module.\nEach target you define in a Swift package is a module.\n\nWhen you expose a library from a package, you expose the public API from your targets that make up that library for other packages to use.\nWhen you import a library in Swift, you're importing the modules that make up that library to use from your code, regardless of what language was used to create that module.\nA Swift package can also host C, C++, or Objective-C code as modules.\nLike Swift, these are also units of code distribution, but unlike Swift you expose the API that by hand-authoring a module-defining file (`module.modulemap`) that references a header or collection of headers with the API to expose.\n\nA program may have all of its code in a single module, or it may import other modules as _dependencies_.\nAside from the handful of system-provided modules, such as Darwin on macOS or Glibc on Linux, most dependencies require code to be downloaded and built in order to be used.\n\nExtracting code that solves a particular problem into a separate module allows for that code to be reused in other situations. \nFor example, a module that provides functionality for making network requests could be shared between a photo sharing app and a program that displays the weather forecast. \nAnd if a new module comes along that does a better job, it can be swapped in easily, with minimal change. \nBy embracing modularity, you can focus on the interesting aspects of the problem at hand, rather than getting bogged down solving problems you encounter along the way.\n\nAs a rule of thumb: more modules are probably better than fewer modules. \nThe package manager is designed to make creating both packages and apps with multiple modules as easy as possible.\n\n### About Dependencies\n\nModern development is accelerated by the use of external dependencies (for better and worse). \nThis is great for allowing you to get more done in less time, but adding dependencies to a project has an associated coordination cost.\n\nIn addition to downloading and building the source code for a dependency, that dependency's own dependencies must be downloaded and built as well, and so on, until the entire dependency graph is satisfied. \nTo complicate matters further, a dependency may specify version requirements, which may have to be reconciled with the version requirements of other modules with the same dependency.\n\nThe role of the package manager is to automate the process of downloading and building all of the dependencies for a project, and minimize the coordination costs associated with code reuse.\nA good package manager should be designed from the start to minimize the risk of failing to resolve dependencies, and where this is not possible, to mitigate it and provide tooling so that the user can solve the scenario with a minimum of trouble.\nRead <doc:AddingDependencies> for more information on adding dependencies, and <doc:ResolvingPackageVersions> for how the package manager resolves and records dependencies.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/ModuleAliasing.md",
    "content": "# Module Aliasing\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.7\")\n}\n\nCreate aliased names for modules to avoid collisions between targets in your package or its dependencies.\n\n## Overview\n\nAs you add dependencies to your package, a name collision can occur among modules from different packages.\nModule names such as `Logging` or `Utils` are common examples.\nIn order to resolve the collision, package manager, **from Swift 5.7 or later**, provides the parameter `moduleAliases` when defining dependencies for targets.\nYou define new unique names for the modules that would otherwise conflict, without requiring any source code changes.\n\nNote the following additional requirements:\n* A module being aliased needs to be a pure Swift module only: no ObjC/C/C++/Asm are supported due to a likely symbol collision. Similarly, use of `@objc(name)` should be avoided. \n* A module being aliased cannot be a prebuilt binary due to the impact on mangling and serialization, i.e. source-based only.\n* A module being aliased should not be passed to a runtime call such as `NSClassFromString(...)` that converts (directly or indirectly) String to a type in a module since such call will fail.\n* If a target mapped to a module being aliased contains resources, they should be asset catalogs, localized strings, or resources that do not require explicit module names.\n* If a product that a module being aliased belongs to has a conflicting name with another product, at most one of the products can be a non-automatic library type.\n\n\n### How to Use\n\nModule aliases are defined as a dictionary parameter in a target's dependencies where the key is the original module name in conflict and the value is a user-defined new unique name:\n\n```swift\n    targets: [ \n        .target(\n            name: \"MyTarget\",\n            dependencies: [ \n                .product(\n                    name: \"Utils\",\n                    package: \"MyPackage\",\n                    moduleAliases: [\"Utils\": \"MyPackageUtils\"]\n                )\n            ]\n        )\n    ]\n```\n\nThis will rename the `Utils` module in the `MyPackage` package to the new user-defined unique name, in this case `MyPackageUtils`; the name of the binary will be `MyPackageUtils.swiftmodule`. No source or manifest changes are required by the dependency package.\n\nTo use the aliased module your root package can use the new unique name, i.e. `import MyPackageUtils`, and make it clear that it is importing the utilities module from `MyPackage`.\n\nConsider the following example to go over how module aliasing can be used in more detail.\n\n#### Example\n\nThe following example of a package `App` imports the modules `Utils` and `Logging` from a package `swift-draw`.\nIt wants to add another package dependency `swift-game` and imports the modules `Utils` and `Game` vended from the package. The `Game` module imports `Logging` from the same package.\n\n```\n App\n   |— Module Utils (from package ‘swift-draw’)\n   |— Module Logging (from package ‘swift-draw’)\n   |— Module Utils (from package ‘swift-game’)\n   |— Module Game (from package ‘swift-game’)\n        |— Module Logging (from package ‘swift-game’)\n```\n\nPackage manifest `swift-game`\n```\n{\n    name: \"swift-game\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n        .library(name: \"Game\", targets: [\"Game\"]),\n    ],\n    targets: [\n        .target(name: \"Game\", dependencies: [\"Logging\"]),\n        .target(name: \"Utils\", dependencies: []),\n        .target(name: \"Logging\", dependencies: [])\n    ]\n}\n```\n\nPackage manifest `swift-draw`\n```\n{\n    name: \"swift-draw\",\n    products: [\n        .library(name: \"Utils\", targets: [\"Utils\"]),\n        .library(name: \"Logging\", targets: [\"Logging\"]),\n    ],\n    targets: [\n        .target(name: \"Utils\", dependencies: []),\n        .target(name: \"Logging\", dependencies: []),\n    ]\n}\n```\n\n##### Analyzing the conflicts \n\n###### Utils modules\n\nBoth `swift-draw` and `swift-game` vend modules with the same name `Utils`, thus causing a conflict. To resolve the collision, a new parameter `moduleAliases` can now be used to disambiguate them.\n\nPackage manifest `App`\n```\n    targets: [\n        .executableTarget(\n            name: \"App\",\n            dependencies: [\n                .product(name: \"Utils\",\n                         package: \"swift-draw\"),\n                .product(name: \"Utils\",\n                         package: \"swift-game\",\n                         moduleAliases: [\"Utils\": \"SwiftGameUtils\"]),\n            ])\n    ]\n```\n\nThis will rename the `Utils` module in package `swift-game` as `SwiftGameUtils`; the name of the binary will be `SwiftGameUtils.swiftmodule`.\n\nTo use the aliased module, `App` can reference the new package-qualified name, i.e. `import SwiftGameUtils`. Its existing `import Utils` statement will continue to reference the `Utils` module from package `swift-draw`, as expected.\n\nNote that the dependency product names are duplicate, i.e. both have the same name `Utils`, which is by default not allowed.\nHowever, this is allowed when module aliasing is used as long as no files with the same product name are created.\nThis means they must all be automatic library types, or at most one of them can be a static library, dylib, an executable, or any other type that creates a file or a directory with the product name.\n\n###### Transitive Logging modules\n\nSimilar to the prior conflict with `Utils`, both the `swift-draw` and `swift-game` packages contain modules with the same name `Logging`, thus causing a conflict.\nAlthough `App` does not directly import `Logging` from `swift-game`, the conflicting module still needs to be disambiguated.\n\nWe can use `moduleAliases` again, as follows.\n\nPackage manifest `App`\n```\n    targets: [\n        .executableTarget(\n            name: \"App\",\n            dependencies: [\n                // Utils module aliasing:\n                .product(name: \"Utils\",\n                         package: \"swift-draw\"),\n                .product(name: \"Utils\",\n                         package: \"swift-game\",\n                         moduleAliases: [\"Utils\": \"SwiftGameUtils\"]),\n                // Logging module aliasing:\n                .product(name: \"Logging\",\n                         package: \"swift-draw\"),\n                .product(name: \"Game\",\n                         package: \"swift-game\",\n                         moduleAliases: [\"Logging\": \"SwiftGameLogging\"]),\n            ])\n    ]\n```\n\nThe `Logging` module from `swift-game` is renamed as `SwiftGameLogging`, and all the references to `Logging` in source files of `Game` are compiled as `SwiftGameLogging`. Similar to before, no source or manifest changes are required by the `swift-game` package.\n\nIf more aliases need to be defined, they can be added with a comma delimiter, per below. \n\n```\n    moduleAliases: [\"Utils\": \"SwiftGameUtils\", \"Logging\": \"SwiftGameLogging\"]),\n```\n\n### Override Module Aliases\n\nIf module alias values defined upstream are conflicting downstream, they can be overridden by chaining; add an entry to the `moduleAliases` parameter downstream using the conflicting alias value as a key and provide a unique value. Since the package identifier is unique to the package, using it as the prefix for the new module alias as a convention should help to prevent more collisions since it can be a generally agreed unique name for the module.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageAddDependency.md",
    "content": "# swift package add-dependency\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nAdd a package dependency to the manifest.\n\n```\npackage add-dependency <dependency>\n  [--package-path=<package-path>] [--cache-path=<cache-path>]\n  [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--exact=<exact>]\n  [--revision=<revision>] [--branch=<branch>] [--from=<from>]\n  [--up-to-next-minor-from=<up-to-next-minor-from>]\n  [--to=<to>] [--type=<type>] [--version] [--help]\n```\n\n- term **dependency**:\n\n*The URL or directory of the package to add.*\n\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--exact=\\<exact\\>**:\n\n*The exact package version to depend on.*\n\n\n- term **--revision=\\<revision\\>**:\n\n*The specific package revision to depend on.*\n\n\n- term **--branch=\\<branch\\>**:\n\n*The branch of the package to depend on.*\n\n\n- term **--from=\\<from\\>**:\n\n*The package version to depend on (up to the next major version).*\n\n\n- term **--up-to-next-minor-from=\\<up-to-next-minor-from\\>**:\n\n*The package version to depend on (up to the next minor version).*\n\n\n- term **--to=\\<to\\>**:\n\n*Specify upper bound on the package version range (exclusive).*\n\n\n- term **--type=\\<type\\>**:\n\n*Specify dependency type.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageAddProduct.md",
    "content": "# swift package add-product\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nAdd a new product to the manifest.\n\n```\npackage add-product [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] <name> [--type=<type>]\n  [--targets=<targets>...] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **name**:\n\n*The name of the new product.*\n\n\n- term **--type=\\<type\\>**:\n\n*The type of target to add.*\n\n\n- term **--targets=\\<targets\\>**:\n\n*A list of targets that are part of this product.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageAddSetting.md",
    "content": "# swift package add-setting\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nAdd a new setting to the manifest.\n\n```\npackage add-setting [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] --target=<target>\n  --swift=<swift>... [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--target=\\<target\\>**:\n\n*The target to add the setting to.*\n\n\n- term **--swift=\\<swift\\>**:\n\n*The Swift language setting(s) to add. Supported settings: experimentalFeature, upcomingFeature, languageMode, strictMemorySafety.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageAddTarget.md",
    "content": "# swift package add-target\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nAdd a new target to the manifest.\n\n```\npackage add-target [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] <name> [--type=<type>]\n  [--dependencies=<dependencies>...] [--url=<url>]\n  [--path=<path>] [--checksum=<checksum>]\n  [--testing-library=<testing-library>] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **name**:\n\n*The name of the new target.*\n\n\n- term **--type=\\<type\\>**:\n\n*The type of target to add.*\n\n\n- term **--dependencies=\\<dependencies\\>**:\n\n*A list of target dependency names.*\n\n\n- term **--url=\\<url\\>**:\n\n*The URL for a remote binary target.*\n\n\n- term **--path=\\<path\\>**:\n\n*The path to a local binary target.*\n\n\n- term **--checksum=\\<checksum\\>**:\n\n*The checksum for a remote binary target.*\n\n\n- term **--testing-library=\\<testing-library\\>**:\n\n*The testing library to use when generating test targets, which can be one of 'xctest', 'swift-testing', or 'none'.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageAddTargetDependency.md",
    "content": "# swift package add-target-dependency\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nAdd a new target dependency to the manifest.\n\n```\npackage add-target-dependency [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] <dependency-name> <target-name>\n  [--package=<package>] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **dependency-name**:\n\n*The name of the new dependency.*\n\n\n- term **target-name**:\n\n*The name of the target to update.*\n\n\n- term **--package=\\<package\\>**:\n\n*The package in which the dependency resides.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageArchiveSource.md",
    "content": "# swift package archive-source\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nCreate a source archive for the package.\n\n```\npackage archive-source [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--output=<output>] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--output=\\<output\\>**:\n\n*The absolute or relative path for the generated source archive.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageClean.md",
    "content": "# swift package clean\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nDelete build artifacts.\n\n```\npackage clean [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageCompletionTool.md",
    "content": "# swift package completion-tool\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\n\nCommand to generate shell completions.\n\n```\npackage completion-tool [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] <mode> [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **mode**:\n\n*Type of completions to list.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageComputeChecksum.md",
    "content": "# swift package compute-checksum\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nCompute the checksum for a binary artifact.\n\n```\npackage compute-checksum [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] <path> [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **path**:\n\n*The absolute or relative path to the binary artifact.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageConfigGetMirror.md",
    "content": "# swift package config get-mirror\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nPrint mirror configuration for the given package dependency.\n\n```\npackage config get-mirror [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--original=<original>] [--version]\n  [--help]```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--original=\\<original\\>**:\n\n*The original url or identity.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageConfigSetMirror.md",
    "content": "# swift package config set-mirror\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nSet a mirror for a dependency.\n\n```\npackage config set-mirror [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--original=<original>]\n  [--mirror=<mirror>] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--original=\\<original\\>**:\n\n*The original url or identity.*\n\n\n- term **--mirror=\\<mirror\\>**:\n\n*The mirror url or identity.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageConfigUnsetMirror.md",
    "content": "# swift package config unset-mirror\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nRemove an existing mirror.\n\n```\npackage config unset-mirror [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--original=<original>]\n  [--mirror=<mirror>] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--original=\\<original\\>**:\n\n*The original url or identity.*\n\n\n- term **--mirror=\\<mirror\\>**:\n\n*The mirror url or identity.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageDescribe.md",
    "content": "# swift package describe\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nDescribe the current package.\n\n```\npackage describe [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--type=<type>] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--type=\\<type\\>**:\n\n*Set the output format.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageDiagnoseAPIBreakingChange.md",
    "content": "# swift package diagnose-api-breaking-changes\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\n\nDiagnose API-breaking changes to Swift modules in a package.\n\n```\npackage diagnose-api-breaking-changes\n  [--package-path=<package-path>] [--cache-path=<cache-path>]\n  [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath]\n  [--breakage-allowlist-path=<breakage-allowlist-path>]\n  <treeish> [--products=<products>...]\n  [--targets=<targets>...] [--traits=<traits>]\n  [--enable-all-traits] [--disable-default-traits]\n  [--baseline-dir=<baseline-dir>] [--regenerate-baseline]\n  [--version] [--help]\n```\n\nThe diagnose-api-breaking-changes command can be used to compare the Swift API of a package to a baseline revision, diagnosing any breaking changes which have been introduced. By default, it compares every Swift module from the baseline revision which is part of a library product. For packages with many targets, this behavior may be undesirable as the comparison can be slow. The `--products` and `--targets` options may be used to restrict the scope of the comparison.\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--breakage-allowlist-path=\\<breakage-allowlist-path\\>**:\n\n*The path to a text file containing breaking changes which should be ignored by the API comparison. Each ignored breaking change in the file should appear on its own line and contain the exact message to be ignored (e.g. 'API breakage: func foo() has been removed').*\n\n\n- term **treeish**:\n\n*The baseline treeish to compare to (for example, a commit hash, branch name, tag, and so on).*\n\n\n- term **--products=\\<products\\>**:\n\n*One or more products to include in the API comparison. If present, only the specified products (and any targets specified using `--targets`) will be compared.*\n\n\n- term **--targets=\\<targets\\>**:\n\n*One or more targets to include in the API comparison. If present, only the specified targets (and any products specified using `--products`) will be compared.*\n\n\n- term **--traits=\\<traits\\>**:\n\n*Enables the passed traits of the package. Multiple traits can be specified by providing a comma separated list e.g. `--traits Trait1,Trait2`. When enabling specific traits the defaults traits need to explictily enabled as well by passing `defaults` to this command.*\n\n\n- term **--enable-all-traits**:\n\n*Enables all traits of the package.*\n\n\n- term **--disable-default-traits**:\n\n*Disables all default traits of the package.*\n\n\n- term **--baseline-dir=\\<baseline-dir\\>**:\n\n*The path to a directory used to store API baseline files. If unspecified, a temporary directory will be used.*\n\n\n- term **--regenerate-baseline**:\n\n*Regenerate the API baseline, even if an existing one is available.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageDumpPackage.md",
    "content": "# swift package dump-package\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nPrint parsed Package.swift as JSON.\n\n```\npackage dump-package [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageDumpSymbolGraph.md",
    "content": "# swift package dump-symbol-graph\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nDump symbol graphs.\n\n```\npackage dump-symbol-graph [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--pretty-print]\n  [--skip-synthesized-members]\n  [--minimum-access-level=<minimum-access-level>]\n  [--skip-inherited-docs] [--include-spi-symbols]\n  [--emit-extension-block-symbols]\n  [--omit-extension-block-symbols] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--pretty-print**:\n\n*Pretty-print the output JSON.*\n\n\n- term **--skip-synthesized-members**:\n\n*Skip members inherited through classes or default implementations.*\n\n\n- term **--minimum-access-level=\\<minimum-access-level\\>**:\n\n*Include symbols with this access level or more. Possible values: private | fileprivate | internal | package | public | open.*\n\n\n- term **--skip-inherited-docs**:\n\n*Skip emitting doc comments for members inherited through classes or default implementations.*\n\n\n- term **--include-spi-symbols**:\n\n*Add symbols with SPI information to the symbol graph.*\n\n\n- term **--emit-extension-block-symbols|omit-extension-block-symbols**:\n\n*Emit extension block symbols for extensions to external types or directly associate members and conformances with the extended nominal.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageEdit.md",
    "content": "# swift package edit\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nPut a package in editable mode.\n\n```\npackage edit [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--revision=<revision>]\n  [--branch=<branch>] [--path=<path>] <package-identity>\n  [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--revision=\\<revision\\>**:\n\n*The revision to edit.*\n\n\n- term **--branch=\\<branch\\>**:\n\n*The branch to create.*\n\n\n- term **--path=\\<path\\>**:\n\n*Create or use the checkout at this path.*\n\n\n- term **package-identity**:\n\n*The identity of the package to edit.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageExperimentalInstall.md",
    "content": "# swift package experimental-install\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nOffers the ability to install executable products of the current package.\n\n```\npackage experimental-install [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--product=<product>] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--product=\\<product\\>**:\n\n*The name of the executable product to install.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageExperimentalUninstall.md",
    "content": "# swift package experimental-uninstall\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nOffers the ability to uninstall executable products previously installed by `swift package experimental-install`.\n\n```\npackage experimental-uninstall\n  [--package-path=<package-path>] [--cache-path=<cache-path>]\n  [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] <name> [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **name**:\n\n*Name of the executable to uninstall.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageGenerateSBOM.md",
    "content": "# swift.package.generate-sbom\n\nGenerate a Software Bill of Materials (SBOM).\n\n```\npackage generate-sbom [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching] [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts] [--disable-experimental-prebuilts]\n  [--verbose] [--very-verbose|vv] [--quiet] [--color-diagnostics] [--no-color-diagnostics]\n  [--disable-sandbox]\n  [--netrc] [--enable-netrc] [--disable-netrc] [--netrc-file=<netrc-file>]\n  [--enable-keychain] [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation] [--disable-signature-validation]\n  [--enable-prefetching] [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update]\n  [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>]\n  [--=<Xcc>...] [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>]\n  [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>]\n  [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store] [--disable-index-store]\n  [--enable-parseable-module-interfaces]\n  [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>]\n  [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath]\n  [--traits=<traits>] [--enable-all-traits] [--disable-default-traits]\n  [--product=<product>]\n  [--sbom-spec=<sbom-spec>...]\n  [--sbom-output-dir=<sbom-output-dir>]\n  [--sbom-filter=<sbom-filter>]\n  [--sbom-warning-only]\n  [--version]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--disable-dependency-cache**:\n\n*Do not use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching**:\n\n\n- term **--disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts**:\n\n*Use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--disable-experimental-prebuilts**:\n\n*Do not use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics**:\n\n*Enables color diagnostics when printing to a TTY.\nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--no-color-diagnostics**:\n\n*Disables color diagnostics when printing to a TTY.\nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--disable-netrc**:\n\n*Do not load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--disable-keychain**:\n\n*Do not search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--disable-signature-validation**:\n\n*Do not validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching**:\n\n\n- term **--disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior.*\n\n\n- term **--auto-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n*Specify the build system to use.*\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--traits=\\<traits\\>**:\n\n*Enables the passed traits of the package. Multiple traits can be specified by providing a comma separated list, for example, `--traits Trait1,Trait2`. When enabling specific traits the default traits also need to be explictily enabled as well by passing `defaults` to this command.*\n\n\n- term **--enable-all-traits**:\n\n*Enables all traits of the package.*\n\n\n- term **--disable-default-traits**:\n\n*Disables all default traits of the package.*\n\n\n- term **--product=\\<product\\>**:\n\n*The product to generate an SBOM for.*\n\n\n- term **--sbom-spec=\\<sbom-spec\\>**:\n\n*Set the SBOM specification(s) and generate SBOM(s).*\n\n\n- term **--sbom-output-dir=\\<sbom-output-dir\\>**:\n\n*The absolute or relative directory path to generate the SBOM(s) in. Must be used with --sbom-spec. (default: <build_output>/sboms).*\n\n\n- term **--sbom-filter=\\<sbom-filter\\>**:\n\n*Filter the SBOM components and dependencies by products and/or packages. Must be used with --sbom-spec.*\n\n\n- term **--sbom-warning-only**:\n\n*Treat SBOM generation errors as warnings. Must be used with --sbom-spec. (default: false).*\n\n\n- term **--version**:\n\n*Show the version.*"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageInit.md",
    "content": "# swift package init\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nInitialize a new package.\n\n```\npackage init [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--type=<type>] [--enable-xctest]\n  [--disable-xctest] [--enable-swift-testing]\n  [--disable-swift-testing] [--name=<name>] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--type=\\<type\\>**:\n\n*Package type:*\n\nlibrary           - A package with a library.\nexecutable        - A package with an executable.\ntool              - A package with an executable that uses\n                    Swift Argument Parser. Use this template if you\n                    plan to have a rich set of command-line arguments.\nbuild-tool-plugin - A package that vends a build tool plugin.\ncommand-plugin    - A package that vends a command plugin.\nmacro             - A package that vends a macro.\nempty             - An empty package with a Package.swift manifest.\n\n\n- term **--enable-xctest|disable-xctest**:\n\n*Enable support for XCTest.*\n\n\n- term **--enable-swift-testing|disable-swift-testing**:\n\n*Enable support for Swift Testing.*\n\n\n- term **--name=\\<name\\>**:\n\n*Provide custom package name.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageMigrate.md",
    "content": "# swift package migrate\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.2\")\n}\n\n\nMigrate a package or its individual targets to use the given set of features.\n\n```\npackage migrate [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--target=<target>]\n  --to-feature=<to-feature> [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--targets=\\<targets\\>**:\n\n*The targets to migrate to specified set of features.*\n\n\n- term **--to-feature=\\<to-feature\\>**:\n\n*The Swift language upcoming/experimental feature to migrate to.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackagePlugin.md",
    "content": "# swift package plugin\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.6\")\n}\n\n\nInvoke a command plugin or perform other actions on command plugins.\n\n```\npackage plugin [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--list]\n  [--allow-writing-to-package-directory]\n  [--allow-writing-to-directory=<allow-writing-to-directory>...]\n  [--allow-network-connections=<allow-network-connections>]\n  [--package=<package>] [<command>] [<arguments>...]\n  [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--list**:\n\n*List the available command plugins.*\n\n\n- term **--allow-writing-to-package-directory**:\n\n*Allow the plugin to write to the package directory.*\n\n\n- term **--allow-writing-to-directory=\\<allow-writing-to-directory\\>**:\n\n*Allow the plugin to write to an additional directory.*\n\n\n- term **--allow-network-connections=\\<allow-network-connections\\>**:\n\n\n- term **--package=\\<package\\>**:\n\n*Limit available plugins to a single package with the given identity.*\n\n\n- term **command**:\n\n*Verb of the command plugin to invoke.*\n\n\n- term **arguments**:\n\n*Arguments to pass to the command plugin.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackagePurgeCache.md",
    "content": "# swift package purge-cache\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nPurge the global repository cache.\n\n```\npackage purge-cache [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageReset.md",
    "content": "# swift package reset\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nReset the complete cache/build directory.\n\n```\npackage reset [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageResolve.md",
    "content": "# swift package resolve\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nResolve package dependencies.\n\n```\npackage resolve [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] --version=<version>\n  [--branch=<branch>] [--revision=<revision>]\n  [<package-name>] [--traits=<traits>] [--enable-all-traits]\n  [--disable-default-traits] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version=\\<version\\>**:\n\n*The version to resolve at.*\n\n\n- term **--branch=\\<branch\\>**:\n\n*The branch to resolve at.*\n\n\n- term **--revision=\\<revision\\>**:\n\n*The revision to resolve at.*\n\n\n- term **package-name**:\n\n*The name of the package to resolve.*\n\n\n- term **--traits=\\<traits\\>**:\n\n*Enables the passed traits of the package. Multiple traits can be specified by providing a comma separated list e.g. `--traits Trait1,Trait2`. When enabling specific traits the defaults traits need to explictily enabled as well by passing `defaults` to this command.*\n\n\n- term **--enable-all-traits**:\n\n*Enables all traits of the package.*\n\n\n- term **--disable-default-traits**:\n\n*Disables all default traits of the package.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageShowDependencies.md",
    "content": "# swift package show-dependencies\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nPrint the resolved dependency graph.\n\n```\npackage show-dependencies [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--format=<format>]\n  [--output-path=<output-path>] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--format=\\<format\\>**:\n\n*Set the output format.*\n\n\n- term **--output-path=\\<output-path\\>**:\n\n*The absolute or relative path to output the resolved dependency graph.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageShowExecutables.md",
    "content": "# swift package show-executables\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nList the available executables from this package.\n\n```\npackage show-executables [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--format=<format>] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--format=\\<format\\>**:\n\n*Set the output format.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageShowTraits.md",
    "content": "# swift package show-traits\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.3\")\n}\n\nList the available traits for a package.\n\n```\npackage show-traits [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--format=<format>] [--package-id=<packageId>] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--format=\\<format\\>**:\n\n*Set the output format. Available formats: flatlist (default), json*\n\n\n- term **--package-id=\\<packageId\\>**:\n\n*Select a package to display the traits. Default is the current root package.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageToolsVersion.md",
    "content": "# swift package tools-version\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nManipulate tools version of the current package.\n\n```\npackage tools-version [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--set-current] [--set=<set>]\n  [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--set-current**:\n\n*Set tools version of package to the current tools version in use.*\n\n\n- term **--set=\\<set\\>**:\n\n*Set tools version of package to the given value.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageUnedit.md",
    "content": "# swift package unedit\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nRemove a package from editable mode.\n\n```\npackage unedit [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--force] <package-identity>\n  [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--force**:\n\n*Unedit the package even if it has uncommitted and unpushed changes.*\n\n\n- term **package-identity**:\n\n*The identity of the package to unedit.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Package/PackageUpdate.md",
    "content": "# swift package update\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\nUpdate package dependencies.\n\n```\npackage update [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--dry-run] [<packages>...]\n  [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--dry-run**:\n\n*Display the list of dependencies that can be updated.*\n\n\n- term **packages**:\n\n*The packages to update.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageCollections/PackageCollectionAdd.md",
    "content": "# swift package-collection add\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.5\")\n}\n\nAdd a new collection.\n\n## Overview\n\nThis subcommand adds a package collection hosted on the web (HTTPS required):\n\n```bash\n$ swift package-collection add https://www.example.com/packages.json\nAdded \"Sample Package Collection\" to your package collections.\n```\n\nOr found in the local file system:\n\n```bash\n$ swift package-collection add file:///absolute/path/to/packages.json\nAdded \"Sample Package Collection\" to your package collections.\n```\n\nThe optional `order` hint can be used to order collections and may potentially influence ranking in search results:\n\n```bash\n$ swift package-collection add https://www.example.com/packages.json [--order N]\nAdded \"Sample Package Collection\" to your package collections.\n```\n\n### Signed package collections\n\nPublishers of a package collection may [sign a collection to protect its contents](<doc:PackageCollections#Protecting-package-collections>). \nThe package manager will check if a signed collection's signature is valid before importing it. \nIf the validation check fails, the package manager returns an error:\n\n```bash\n$ swift package-collection add https://www.example.com/bad-packages.json\nThe collection's signature is invalid. If you would like to continue please rerun command with '--skip-signature-check'.\n```\n\nUsers may continue adding the collection despite the error or preemptively skip the signature check on a package collection by passing the `--skip-signature-check` flag:\n\n```bash\n$ swift package-collection add https://www.example.com/packages.json --skip-signature-check\n```\n\nFor package collections hosted on the web, publishers may ask the package manager to [enforce the signature requirement](<doc:PackageSecurity#Trusted-root-certificates>). \nIf a package collection is expected to be signed but it isn't, users will see the following error message:\n\n```bash\n$ swift package-collection add https://www.example.com/bad-packages.json\nThe collection is missing required signature, which means it might have been compromised.\n```\n\nUsers should NOT add the package collection in this case.\n\nFor more details on signature validation, see <doc:PackageSecurity#Signed-package-collections>.\n\n##### Trusted root certificates\n\nThe package manager [validates the certificate](<doc:PackageSecurity#Trusted-root-certificates>) of a signed collection as a part of its signature validation to make sure that the root certificate is trusted.\n\n```bash\n$ swift package-collection add https://www.example.com/packages.json\nThe collection's signature cannot be verified due to missing configuration.\n```\n\nUsers can explicitly specify they trust a publisher and any collections they publish, by obtaining that publisher's root certificate and saving it to `~/.swiftpm/config/trust-root-certs`. The \nroot certificates must be DER-encoded. Since the package manager trusts all certificate chains under a root, depending on what roots are installed, some publishers may already be trusted implicitly and users don't need to explicitly specify each one. \n\n#### Unsigned package collections\n\nUsers will get an error when trying to add an unsigned package collection:\n\n```bash\n$ swift package-collection add https://www.example.com/packages.json\nThe collection is not signed. If you would still like to add it please rerun 'add' with '--trust-unsigned'.\n```\n\nTo continue, users must confirm their trust by passing the `--trust-unsigned` flag:\n\n```bash\n$ swift package-collection add https://www.example.com/packages.json --trust-unsigned\n```\n\nThe `--skip-signature-check` flag has no effects on unsigned collections.\n\n\n## Usage\n\n```\npackage-collection add <collection-url> [--order=<order>]\n  [--trust-unsigned] [--skip-signature-check]\n  [--package-path=<package-path>] [--cache-path=<cache-path>]\n  [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **collection-url**:\n\n*URL of the collection to add.*\n\n\n- term **--order=\\<order\\>**:\n\n*Sort order for the added collection.*\n\n\n- term **--trust-unsigned**:\n\n*Trust the collection even if it is unsigned.*\n\n\n- term **--skip-signature-check**:\n\n*Skip signature check if the collection is signed.*\n\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageCollections/PackageCollectionDescribe.md",
    "content": "# swift package-collection describe\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.5\")\n}\n\nGet metadata for a collection or a package included in an imported collection.\n\n## Overview\n\nThis subcommand shows metadata for a collection or a package included in an imported collection. The result can optionally be returned as JSON using `--json` for\nintegration into other tools.\n\n### Metadata and packages of a collection\n\n`describe` can be used for both collections that have been previously added to the list of the user's configured collections, as well as to preview any other collections.\n\n```bash\n$ swift package-collection describe [--json] https://www.example.com/packages.json\nName: Sample Package Collection\nSource: https://www.example.com/packages.json\nDescription: ...\nKeywords: best, packages\nCreated At: 2020-05-30 12:33\nPackages:\n    https://github.com/jpsim/yams\n    ...\n```\n\n#### Signed package collections\n\nIf a collection is signed, SwiftPM will check that the signature is valid before showing a preview.\n\n```bash\n$ swift package-collection describe https://www.example.com/bad-packages.json\nThe collection's signature is invalid. If you would like to continue please rerun command with '--skip-signature-check'.\n```\n\nUsers may continue previewing the collection despite the error or preemptively skip the signature check on a package collection by passing the `--skip-signature-check` flag:\n\n```bash\n$ swift package-collection describe https://www.example.com/packages.json --skip-signature-check\n```\n\n### Metadata of a package\n\n`describe` can also show the metadata of a package included in an imported collection:\n\n```bash\n$ swift package-collection describe [--json] https://github.com/jpsim/yams\nDescription: A sweet and swifty YAML parser built on LibYAML.\nAvailable Versions: 4.0.0, 3.0.0, ...\nStars: 14\nReadme: https://github.com/jpsim/Yams/blob/main/README.md\nAuthors: @norio-nomura, @jpsim\n--------------------------------------------------------------\nLatest Version: 4.0.0\nPackage Name: Yams\nModules: Yams, CYaml\nSupported Platforms: iOS, macOS, Linux, tvOS, watchOS\nSupported Swift Versions: 5.3, 5.2, 5.1, 5.0\nLicense: MIT\n```\n\n### Metadata of a package version\n\nUser may view additional metadata for a package version by passing `--version`:\n\n```bash\n$ swift package-collection describe [--json] --version 4.0.0 https://github.com/jpsim/yams\nPackage Name: Yams\nVersion: 4.0.0\nModules: Yams, CYaml\nSupported Platforms: iOS, macOS, Linux, tvOS, watchOS\nSupported Swift Versions: 5.3, 5.2, 5.1, 5.0\nLicense: MIT\n```\n\n## Usage\n\n```\npackage-collection describe [--json] <package-url>\n  [--version=<version>] [--skip-signature-check]\n  [--package-path=<package-path>] [--cache-path=<cache-path>]\n  [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--json**:\n\n*Output as JSON*\n\n\n- term **package-url**:\n\n*URL of the package or collection to get information for.*\n\n\n- term **--version=\\<version\\>**:\n\n*Version of the package to get information for.*\n\n\n- term **--skip-signature-check**:\n\n*Skip signature check if the collection is signed.*\n\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY.\nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageCollections/PackageCollectionList.md",
    "content": "# swift package-collection list\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.5\")\n}\n\nList configured collections.\n\n## Overview\n\nThis subcommand lists all collections that are configured by the user:\n\n```bash\n$ swift package-collection list [--json]\nSample Package Collection - https://example.com/packages.json\n...\n```\n\nThe result can optionally be returned as JSON using `--json` for integration into other tools.\n\n## Usage\n\n```\npackage-collection list [--json]\n  [--package-path=<package-path>] [--cache-path=<cache-path>]\n  [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--json**:\n\n*Output as JSON*\n\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageCollections/PackageCollectionRefresh.md",
    "content": "# swift package-collection refresh\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.5\")\n}\n\nRefresh configured collections.\n\n## Overview\n\nThis subcommand refreshes any cached data manually:\n\n```bash\n$ swift package-collection refresh\nRefreshed 5 configured package collections.\n```\n\nSwiftPM will also automatically refresh data under various conditions, but some queries such as search will rely on locally cached data.\n\n\n## Usage\n\n```\npackage-collection refresh [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageCollections/PackageCollectionRemove.md",
    "content": "# swift package-collection remove\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.5\")\n}\n\nRemove a configured collection.\n\n## Overview\n\nThis subcommand removes a collection from the user's list of configured collections:\n\n```bash\n$ swift package-collection remove https://www.example.com/packages.json\nRemoved \"Sample Package Collection\" from your package collections.\n```\n\n## Usage\n\n```\npackage-collection remove <collection-url>\n  [--package-path=<package-path>] [--cache-path=<cache-path>]\n  [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **collection-url**:\n\n*URL of the collection to remove.*\n\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageCollections/PackageCollectionSearch.md",
    "content": "# swift package-collection search\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.5\")\n}\n\nSearch for packages by keywords or module names.\n\n## Overview\n\nThis subcommand searches for packages by keywords or module names within imported collections. The result can optionally be returned as JSON using `--json` for\nintegration into other tools.\n\n### String-based search\n\nThe search command does a string-based search when using the `--keywords` option and returns the list of packages that matches the query:\n\n```bash\n$ swift package-collection search [--json] --keywords yaml\nhttps://github.com/jpsim/yams: A sweet and swifty YAML parser built on LibYAML.\n...\n```\n\n### Module-based search\n\nThe search command does a search for a specific module name when using the `--module` option:\n\n```bash\n$ swift package-collection search [--json] --module yams\nPackage Name: Yams\nLatest Version: 4.0.0\nDescription: A sweet and swifty YAML parser built on LibYAML.\n--------------------------------------------------------------\n...\n```\n\n## Usage\n\n```\npackage-collection search [--json] --keywords --module\n  <search-query> [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--json**:\n\n*Output as JSON*\n\n\n- term **--keywords|module**:\n\n*Pick the method for searching.*\n\n\n- term **search-query**:\n\n*The search query.*\n\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageCollections.md",
    "content": "# Package Collections\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.5\")\n}\n\nLearn to create, publish and use Swift package collections.\n\n## Overview\n\nPackage collections, introduced by [SE-0291](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0291-package-collections.md), are curated lists of packages and associated metadata that you can import to make discovery of existing packages easier. \n\nEducators and community influencers can publish package collections to go along with course materials or blog posts, making it easier for their readers to use packages for the first time, or choosing which packages to use for a particular task. \nEnterprises may use collections to provide a trusted set of packages, or a collection of packages consistently used by a team.\nYou can author a package collection as a static JSON document and publish it to the web or distribute it on a local file system.\n\n### Using the package-collection CLI\n\nWith the `swift package-collection` command-line interface, SwiftPM users can subscribe to package collections. \nContents of imported package \ncollections are accessible to any clients of [libSwiftPM](<doc:SwiftPMAsALibrary>).\n\n`swift package-collection` has the following subcommands:\n- [`add`](<doc:PackageCollectionAdd>): Add a new collection\n- [`describe`](<doc:PackageCollectionDescribe>): Get metadata for a collection or a package included in an imported collection\n- [`list`](<doc:PackageCollectionList>): List configured collections\n- [`refresh`](<doc:PackageCollectionRefresh>): Refresh configured collections\n- [`remove`](<doc:PackageCollectionRemove>): Remove a configured collection\n- [`search`](<doc:PackageCollectionSearch>): Search for packages by keywords or module names within imported collections\n\n### Creating Package Collections\n\nA package collection is a JSON document that contains a list of packages and metadata per package.\n\nPackage collections can be created and published by anyone. The [swift-package-collection-generator](https://github.com/apple/swift-package-collection-generator) project provides tooling \nintended for package collection publishers:\n- [`package-collection-generate`](https://github.com/apple/swift-package-collection-generator/tree/main/Sources/PackageCollectionGenerator): Generate a package collection given a list of package URLs\n- [`package-collection-sign`](https://github.com/apple/swift-package-collection-generator/tree/main/Sources/PackageCollectionSigner): Sign a package collection\n- [`package-collection-validate`](https://github.com/apple/swift-package-collection-generator/tree/main/Sources/PackageCollectionValidator): Perform basic validations on a package collection\n- [`package-collection-diff`](https://github.com/apple/swift-package-collection-generator/tree/main/Sources/PackageCollectionDiff): Compare two package collections to see if their contents are different \n\nAll package collections must adhere to the [collection data format](<doc:Input-Format>) for SwiftPM to be able to consume them.\nThe recommended way to create package collections is to use [`package-collection-generate`](https://github.com/apple/swift-package-collection-generator/tree/main/Sources/PackageCollectionGenerator).\nFor custom implementations, the data models are available through the [`PackageCollectionsModel` module](https://github.com/swiftlang/swift-package-manager/tree/main/Sources/PackageCollectionsModel).\n\n#### Input Format\n\nTo begin, define the top-level metadata about the collection:\n\n* `name`: The name of the package collection, for display purposes only.\n* `overview`: A description of the package collection. **Optional.**\n* `keywords`: An array of keywords that the collection is associated with. **Optional.**\n* `formatVersion`: The version of the format to which the collection conforms. Currently, `1.0` is the only allowed value.\n* `revision`: The revision number of this package collection. **Optional.**\n* `generatedAt`: The ISO 8601-formatted datetime string when the package collection was generated.\n* `generatedBy`: The author of this package collection. **Optional.**\n    * `name`: The author name.\n* `packages`: A non-empty array of package objects.\n\n### Add packages to the collection\n\nEach item in the `packages` array is a package object with the following properties:\n\n* `url`: The URL of the package. Currently only Git repository URLs are supported. URL should be HTTPS and may contain `.git` suffix.\n* `identity`: The [identity](<doc:RegistryServerSpecification#3.6.-Package-identification>) of the package if published to a registry. **Optional.**\n* `summary`: A description of the package. **Optional.**\n* `keywords`: An array of keywords that the package is associated with. **Optional.**\n* `readmeURL`: The URL of the package's README. **Optional.**\n* `license`: The package's *current* license information. **Optional.**\n    * `url`: The URL of the license file.\n    * `name`: License name. [SPDX identifier](https://spdx.org/licenses/) (e.g., `Apache-2.0`, `MIT`, etc.) preferred. Omit if unknown. **Optional.**\n* `versions`: An array of version objects representing the most recent and/or relevant releases of the package.\n\n### Add versions to a package\n\nA version object has metadata extracted from `Package.swift` and optionally additional metadata from other sources:\n\n* `version`: The semantic version string.\n* `summary`: A description of the package version. **Optional.**\n* `manifests`: A non-empty map of manifests by Swift tools version. The keys are (semantic) tools version (more on this below), while the values are:\n    * `toolsVersion`: The Swift tools version specified in the manifest.\n    * `packageName`: The name of the package.\n    * `targets`: An array of the package version's targets.\n        * `name`: The target name.\n        * `moduleName`: The module name if this target can be imported as a module. **Optional.**\n    * `products`: An array of the package version's products.\n        * `name`: The product name.\n        * `type`: The product type. This must have the same JSON representation as SwiftPM's `PackageModel.ProductType`.\n        * `target`: An array of the product’s targets.\n    * `minimumPlatformVersions`: An array of the package version’s supported platforms specified in `Package.swift`. **Optional.** \n\n```json\n{\n  \"5.2\": {\n    \"toolsVersion\": \"5.2\",\n    \"packageName\": \"MyPackage\",\n    \"targets\": [\n      {\n        \"name\": \"MyTarget\",\n        \"moduleName\": \"MyTarget\"\n      }\n    ],\n    \"products\": [\n      {\n        \"name\": \"MyProduct\",\n        \"type\": {\n          \"library\": [\"automatic\"]\n        },\n        \"targets\": [\"MyTarget\"]\n      }\n    ],\n    \"minimumPlatformVersions\": [\n      {\n        \"name\": \"macOS\",\n        \"version\": \"10.15\"\n      }\n    ]\n  }\n}\n```\n\n* `defaultToolsVersion`: The Swift tools version of the default manifest. The `manifests` map must contain this in its keys. \n* `verifiedCompatibility`: An array of compatible platforms and Swift versions that has been tested and verified for. Valid platform names include `macOS`, `iOS`, `tvOS`, `watchOS`, `Linux`, `Android`, and `Windows`. Swift version should be semantic version string and as specific as possible. **Optional.**\n\n```json\n{\n  \"platform\": {\n    \"name\": \"macOS\"\n  },\n  \"swiftVersion\": \"5.3.2\"\n}\n```\n\n* `license`: The package version's license. **Optional.**\n    * `url`: The URL of the license file.\n    * `name`: License name. [SPDX identifier](https://spdx.org/licenses/) (e.g., `Apache-2.0`, `MIT`, etc.) preferred. Omit if unknown. **Optional.**\n* `author`: The package version's author. **Optional.**\n    * `name`: The author of the package version.\n* `signer`: The signer of the package version. **Optional.** Refer to the [documentation](<doc:PackageSecurity#Package-signing>) on package signing for details.\n    * `type`: The signer type. Currently the only valid value is `ADP` (Apple Developer Program).\n    * `commonName`: The common name of the signing certificate's subject.\n    * `organizationalUnitName`: The organizational unit name of the signing certificate's subject.\n    * `organizationName`: The organization name of the signing certificate's subject.           \n* `createdAt`: The ISO 8601-formatted datetime string when the package version was created. **Optional.**\n\n### Version-specific manifests\n\nPackage collection generators should include data from the \"default\" manifest `Package.swift` as well as [version-specific manifest(s)](<doc:SwiftVersionSpecificPackaging#Version-specific-Manifest-Selection>)\n\nThe keys of the `manifests` map are Swift tools (semantic) versions:\n* For `Package.swift`, the tools version specified in `Package.swift` should be used.\n* For version-specific manifests, the tools version specified in the filename should be used. For example, for `Package@swift-4.2.swift` it would be `4.2`. The tools version in the manifest must match that in the filename. \n\n### Version-specific tags\n\n[Version-specific tags](<doc:SwiftVersionSpecificPackaging#Version-specific-tags-when-resolving-remote-dependencies>) are not supported by package collections.\n\n### Configuration File\n\nConfiguration that pertains to package collections are stored in the file `~/.swiftpm/config/collections.json`. \nIt keeps track of user's list of configured collections and preferences such as those set by the `--trust-unsigned` and `--skip-signature-check` flags in the [`package-collection add` command](<doc:PackageCollectionAdd>). \n\n> Note: This file is managed through Swift Package Manager commands and users are not expected to edit it by hand.\n\n## Example\n\n```json\n{\n  \"name\": \"Sample Package Collection\",\n  \"overview\": \"This is a sample package collection listing made-up packages.\",\n  \"keywords\": [\"sample package collection\"],\n  \"formatVersion\": \"1.0\",\n  \"revision\": 3,\n  \"generatedAt\": \"2020-10-22T06:03:52Z\",\n  \"packages\": [\n    {\n      \"url\": \"https://www.example.com/repos/RepoOne.git\",\n      \"summary\": \"Package One\",\n      \"readmeURL\": \"https://www.example.com/repos/RepoOne/README\",\n      \"license\": {\n        \"name\": \"Apache-2.0\",\n        \"url\": \"https://www.example.com/repos/RepoOne/LICENSE\"\n      },\n      \"versions\": [\n        {\n          \"version\": \"0.1.0\",\n          \"summary\": \"Fixed a few bugs\",\n          \"manifests\": {\n            \"5.1\": {\n              \"toolsVersion\": \"5.1\",\n              \"packageName\": \"PackageOne\",\n              \"targets\": [\n                {\n                  \"name\": \"Foo\",\n                  \"moduleName\": \"Foo\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Foo\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Foo\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.1\",\n          \"verifiedCompatibility\": [\n            {\n              \"platform\": { \"name\": \"macOS\" },\n              \"swiftVersion\": \"5.1\"\n            },\n            {\n              \"platform\": { \"name\": \"iOS\" },\n              \"swiftVersion\": \"5.1\"\n            },\n            {\n              \"platform\": { \"name\": \"Linux\" },\n              \"swiftVersion\": \"5.1\"\n            }\n          ],\n          \"license\": {\n            \"name\": \"Apache-2.0\",\n            \"url\": \"https://www.example.com/repos/RepoOne/LICENSE\"\n          },\n          \"createdAt\": \"2020-10-21T09:25:36Z\"\n        }\n      ]\n    },\n    {\n      \"url\": \"https://www.example.com/repos/RepoTwo.git\",\n      \"summary\": \"Package Two\",\n      \"readmeURL\": \"https://www.example.com/repos/RepoTwo/README\",\n      \"versions\": [\n        {\n          \"version\": \"2.1.0\",\n          \"manifests\": {\n            \"5.2\": {\n              \"toolsVersion\": \"5.2\",\n              \"packageName\": \"PackageTwo\",\n              \"targets\": [\n                {\n                  \"name\": \"Bar\",\n                  \"moduleName\": \"Bar\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Bar\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Bar\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.2\"\n        },\n        {\n          \"version\": \"1.8.3\",\n          \"manifests\": {\n            \"5.0\": {\n              \"toolsVersion\": \"5.0\",\n              \"packageName\": \"PackageTwo\",\n              \"targets\": [\n                {\n                  \"name\": \"Bar\",\n                  \"moduleName\": \"Bar\"\n                }\n              ],\n              \"products\": [\n                {\n                  \"name\": \"Bar\",\n                  \"type\": {\n                    \"library\": [\"automatic\"]\n                  },\n                  \"targets\": [\"Bar\"]\n                }\n              ]\n            }\n          },\n          \"defaultToolsVersion\": \"5.0\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n## Protecting package collections\n\n### Signing a collection\n\n[Sign package collections](<doc:PackageSecurity#Signed-package-collections>) to establish authenticity and protect their integrity. \nDoing this is optional. \nUsers will be prompted for confirmation before they can add an [unsigned collection](<doc:PackageCollectionAdd#Unsigned-package-collections>).\nThe signing certificate you use to sign a package collection must meet a list of [requirements](<doc:PackageSecurity#Requirements-on-signing-certificate>). If these requirements are not met, the package manager returns an error.\n\nFor more details on the security features Package manager implements, see <doc:PackageSecurity>.\n\n### Security risks\n\nWhile signing can provide some degree of protection on package collections and reduce the risks of their contents being modified by malicious actors, it doesn't prevent the following attack vectors:\n- **Signature stripping**: This involves attackers removing signature from a signed collection, causing it to be downloaded as an unsigned collection and bypassing signature check. In this case, publishers should make it known that the collection is signed, and SwiftPM users should abort the `add` operation when the \"unsigned\" warning appears on a supposedly signed collection.\n- **Signature replacement**: Attackers may modify a collection then re-sign it using a different certificate, either pretend to be the same entity or as some other entity, and SwiftPM will accept it as long as the [signature is valid](<doc:PackageCollectionAdd#Signed-package-collections>).\n\nTo defend against these attacks, package manager has certificate-pinning configuration that allows collection publishers to:\n- Require signature check on their collections — this defends against \"signature stripping\".\n- Restrict what certificate can be used for signing — this defends against \"signature replacement\".\n\nThe process for collection publishers to define their certificate-pinning configuration is as follows:\n1. Edit [`PackageCollectionSourceCertificatePolicy`](https://github.com/swiftlang/swift-package-manager/blob/main/Sources/PackageCollections/PackageCollections%2BCertificatePolicy.swift) and add an entry to the `defaultSourceCertPolicies` dictionary:\n\n```swift\nprivate static let defaultSourceCertPolicies: [String: CertificatePolicyConfig] = [\n    // The key should be the \"host\" component of the package collection URL.\n    // This would require all package collections hosted on this domain to be signed.\n    \"www.example.com\": CertificatePolicyConfig(\n        // The signing certificate must have this subject user ID\n        certPolicyKey: CertificatePolicyKey.default(subjectUserID: \"exampleUserID\"),\n        /*\n         To compute base64-encoded string of a certificate:\n         let certificateURL = URL(fileURLWithPath: <path to DER-encoded root certificate file>)\n         let certificateData = try Data(contentsOf: certificateURL)\n         let base64EncoodedCertificate = certificateData.base64EncodedString()\n         */\n        base64EncodedRootCerts: [\"<base64-encoded root certificate>\"]\n    )\n]\n```\n\n2. Open a pull request for review. The requestor must be able to provide proof of their identity and ownership on the domain:\n    - The requestor must provide the actual certificate files (DER-encoded). The SwiftPM team will verify that the certificate chain is valid and the values provided in the PR are correct.\n    - The requestor must add a TXT record referencing the pull request. The SwiftPM team will run `dig -t txt <DOMAIN>` to verify. This would act as proof of domain ownership.\n3. After the changes are accepted, they will take effect in the next SwiftPM release.\n\nSince certificate-pinning configuration is associated with web domains, it can only be applied to signed collections hosted on the web (i.e., URL begins with  `https://`) and does \nnot cover those found on local file system (i.e., URL begins with `file://`). \n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageRegistry/PackageRegistryLogin.md",
    "content": "# swift package-registry login\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.9\")\n}\n\nLog in to a registry.\n\n## Overview\n\nThe package manager verifies the credentials using the registry service's login API.\nIf it returns a successful response, the credentials are persisted to the operating system's credential store (for example, Keychain in macOS). On non-macOS platforms, or if the `--netrc` flag is provided, the credentials are persisted to the user-level .netrc (which by default is located at `~/.netrc`).\nThe user-level configuration file located at ~/.swiftpm/configuration/registries.json is also updated.\n\nThe `url` should be the registry's base URL (for example, `https://example-registry.com`).\nIf the location of the login API endpoint is not `/login` (for example, `https://example-registry.com/api/v1/login`), provide the full URL.\n\nThe URL must be HTTPS.\n\nThe table below shows the supported authentication types and their required option(s):\n\n| Authentication Method   | Required Option(s)        |\n| ----------------------- | ------------------------- |\n| Basic                   |  --username, --password   |\n| Token                   |  --token                  |\n\nThe tool analyzes the provided options to determine the authentication type and prompt (that is, interactive mode) for the password/token if it is missing.\nFor example, if only `--username` is present, the tool assumes basic authentication and prompts for the password.\n\nFor non-interactive mode, provide the `--password` or `--token` option as required or make sure the secret is present in credential storage.\n\nIf the operating system's credential store is not supported, the tool prompts the user for confirmation before writing credentials to the less secure netrc file.\nUse `--no-confirm` to disable this confirmation.\n\nTo force usage of netrc file instead of the operating system's credential store, pass the `--netrc` flag.\n\n### Example: basic authentication (macOS, interactive)\n\n```bash\n> swift package-registry login https://example-registry.com \\\n    --username jappleseed\nEnter password for 'jappleseed':\n\nLogin successful.\nCredentials have been saved to the operating system's secure credential store.\n```\n\nAn entry for `example-registry.com` is added to Keychain.\n\nPackage manager updated `registries.json` to indicate that `example-registry.com` requires basic authentication:\n\n{\n  \"authentication\": {\n    \"example-registry.com\": {\n      \"type\": \"basic\"\n    },\n    ...\n  },\n  ...\n}\n\n### Example: basic authentication (operating system's credential store not supported, interactive)\n\n```bash\n> swift package-registry login https://example-registry.com \\\n    --username jappleseed\nEnter password for 'jappleseed':\n\nLogin successful.\n\nWARNING: Secure credential store is not supported on this platform.\nYour credentials will be written out to netrc file.\nContinue? (Yes/No): Yes\n\nCredentials have been saved to netrc file.\n```\nAn entry for `example-registry.com` is added to the netrc file:\n\n```bash\nmachine example-registry.com\nlogin jappleseed\npassword alpine\n```\n\nPackage manager updates `registries.json` to indicate that example-registry.com requires basic authentication:\n\n```json\n{\n  \"authentication\": {\n    \"example-registry.com\": {\n      \"type\": \"basic\"\n    },\n    ...\n  },\n  ...\n}\n```\n\n### Example: basic authentication (use netrc file instead of operating system's credential store, interactive)\n\n```bash\n> swift package-registry login https://example-registry.com \\\n    --username jappleseed\n    --netrc\nEnter password for 'jappleseed':\n\nLogin successful.\n\nWARNING: You choose to use netrc file instead of the operating system's secure credential store. \nYour credentials will be written out to netrc file.\nContinue? (Yes/No): Yes\n\nCredentials have been saved to netrc file.\n```\n\nAn entry for `example-registry.com` is added to the netrc file:\n\n```bash\nmachine example-registry.com\nlogin jappleseed\npassword alpine\n```\n\nPackage manager updates `registries.json` to indicate that `example-registry.com` requires basic authentication:\n\n```json\n{\n  \"authentication\": {\n    \"example-registry.com\": {\n      \"type\": \"basic\"\n    },\n    ...\n  },\n  ...\n}\n```\n\n### Example: basic authentication (operating system's credential store not supported, non-interactive)\n\n```bash\n> swift package-registry login https://example-registry.com \\\n    --username jappleseed \\\n    --password alpine \\\n    --no-confirm\n    \nLogin successful.\nCredentials have been saved to netrc file.\n```\n\nAn entry for `example-registry.com` is added to the netrc file:\n\n```bash\nmachine example-registry.com\nlogin jappleseed\npassword alpine\n```\nPackage manager updates `registries.json` to indicate that `example-registry.com` requires basic authentication:\n\n```json\n{\n  \"authentication\": {\n    \"example-registry.com\": {\n      \"type\": \"basic\"\n    },\n    ...\n  },\n  ...\n}\n```\n\n### Example: basic authentication (operating system's credential store not supported, non-interactive, non-default login URL)\n\n```bash\n> swift package-registry login https://example-registry.com/api/v1/login \\\n    --username jappleseed \\\n    --password alpine \\\n    --no-confirm\n    \nLogin successful.\nCredentials have been saved to netrc file.\n```\nAn entry for `example-registry.com` is added to the netrc file:\n\n```bash\nmachine example-registry.com\nlogin jappleseed\npassword alpine\n```\nPackage manager updates `registries.json` to indicate that `example-registry.com` requires basic authentication:\n\n```json\n{\n  \"authentication\": {\n    \"example-registry.com\": {\n      \"type\": \"basic\",\n      \"loginAPIPath\": \"/api/v1/login\"\n    },\n    ...\n  },\n  ...\n}\n```\n\n### Example: token authentication\n\n```bash\n> swift package-registry login https://example-registry.com \\\n    --token jappleseedstoken\n```\nAn entry for `example-registry.com` is added to the operating system's credential store if supported, or the user-level netrc file otherwise:\n\n```bash\nmachine example-registry.com\nlogin token\npassword jappleseedstoken\n```\nPackage manager updates `registries.json` to indicate that `example-registry.com` requires token authentication:\n\n```json\n{\n  \"authentication\": {\n    \"example-registry.com\": {\n      \"type\": \"token\"\n    },\n    ...\n  },\n  ...\n}\n```\n\n### Usage\n\n```\npackage-registry login [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [<url>] [--username=<username>]\n  [--password=<password>] [--token=<token>]\n  [--token-file=<token-file>] [--no-confirm] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **url**:\n\n*The registry URL.*\n\n\n- term **--username=\\<username\\>**:\n\n*The username for the registry.*\n\n\n- term **--password=\\<password\\>**:\n\n*The password for the registry.*\n\n\n- term **--token=\\<token\\>**:\n\n*The access token for the registry.*\n\n\n- term **--token-file=\\<token-file\\>**:\n\n*Path to the file containing access token.*\n\n\n- term **--no-confirm**:\n\n*Allow writing to netrc file without confirmation.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageRegistry/PackageRegistryLogout.md",
    "content": "# swift package-registry logout\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.9\")\n}\n\nLog out from a registry.\n\n## Overview\n\nPackage manager removes credentials from the operating system's credential store if supported, and the user-level configuration file (`registries.json`).\n\nTo avoid accidental removal of sensitive data, the `netrc` file needs to be updated manually by the user.\n\n### Changes to registry configuration\n\nThe `authentication` key in the user-level `registries.json` file by default is located at `~/.swiftpm/configuration/registries.json`. Any package registry that requires authentication must have a corresponding entry in this dictionary.\n\n```json\n{\n  \"registries\": {\n    \"[default]\": {\n      \"url\": \"https://example-registry.com\"\n    }\n  },\n  \"authentication\": {\n    \"example-registry.com\": {\n      \"type\": <AUTHENTICATION_TYPE>, // One of: \"basic\", \"token\"\n      \"loginAPIPath\": <LOGIN_API_PATH> // Optional. Overrides the default API path (i.e., /login).\n    }\n  },\n  \"version\": 1\n}\n```\n\n`type` must be one of the following:\n\n- `basic`: username and password\n- `token`: access token\n\nSpecify credentials in the native credential store of the operating system if supported, otherwise in the user-level netrc file.\n\nSee [credential storage](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0378-package-registry-auth.md#credential-storage) for more details on configuring credentials for each authentication type.\n\n### Usage\n\n```\npackage-registry logout [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [<url>] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **url**:\n\n*The registry URL*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageRegistry/PackageRegistryPublish.md",
    "content": "# swift package-registry publish\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.9\")\n}\n\nPublish to a registry.\n\n## Overview\n\nThis command creates a source archive for the package release, optionally signs it, and finally [publishes the package release](<doc:RegistryServerSpecification#4.6.-Create-a-package-release>) to the registry.\n\nIf authentication is required for package publication, package authors should [configure registry login](<doc:UsingSwiftPackageRegistry#Registry-authentication>) before running `publish`.\n\n### Publisher TOFU\n\nSome certificates allow the package manager to extract additional information about the signing identity. For packages signed with these certificates, package manager performs publisher TOFU (trust-on-first-use) to ensure the signer remains the same across all versions of the package. \n\nThe `--resolver-signing-entity-checking` option controls whether a publisher mismatch should result in a warning (`warn`) or error (`strict`). Data used by publisher TOFU is saved to `~/.swiftpm/security/signing-entities/`.\n\nFor more details on trust-on-first-use, see <doc:PackageSecurity#Trust-on-First-Use>.\n\n#### Package release metadata\n\nPackage authors can specify a custom location of the package release metadata file by setting the `--metadata-path` option of the `publish` subcommand.\nOtherwise, package manager looks for a file named `package-metadata.json` in the package directory.\n\nContents of the metadata file must conform to the [JSON schema](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md#package-release-metadata-standards) defined in SE-0391.\n\nRefer to the [registry specification](<doc:RegistryServerSpecification#4.2.2.-Package-release-metadata-standards>) for any additional requirements.\n\n#### Package signing\n \nIf a registry requires signing, package authors need to sign the package release by either setting the `signing-identity` (for reading from operating system's identity store such as Keychain in macOS), or `private-key-path` and `cert-chain-paths` (for reading from files) options of the `publish` subcommand. \nThis allows Package manager to locate the signing key and certificate.\n\nFor more information on package signing, see <doc:PackageSecurity#Signed-packages-from-a-registry>. \n\n### Usage\n\n```\npackage-registry publish [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] <package-id> <package-version>\n  [--url|registry-url=<url>]\n  [--scratch-directory=<scratch-directory>]\n  [--metadata-path=<metadata-path>]\n  [--signing-identity=<signing-identity>]\n  [--private-key-path=<private-key-path>]\n  [--cert-chain-paths=<cert-chain-paths>...]\n  [--allow-insecure-http] [--dry-run] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **package-id**:\n\n*The package identifier.*\n\n\n- term **package-version**:\n\n*The package release version being created.*\n\n\n- term **--url|registry-url=\\<url\\>**:\n\n*The registry URL.*\n\n\n- term **--scratch-directory=\\<scratch-directory\\>**:\n\n*The path of the directory where working file(s) will be written.*\n\n\n- term **--metadata-path=\\<metadata-path\\>**:\n\n*The path to the package metadata JSON file if it is not 'package-metadata.json' in the package directory.*\n\n\n- term **--signing-identity=\\<signing-identity\\>**:\n\n*The label of the signing identity to be retrieved from the system's identity store if supported.*\n\n\n- term **--private-key-path=\\<private-key-path\\>**:\n\n*The path to the certificate's PKCS#8 private key (DER-encoded).*\n\n\n- term **--cert-chain-paths=\\<cert-chain-paths\\>**:\n\n*Path(s) to the signing certificate (DER-encoded) and optionally the rest of the certificate chain. Certificates should be ordered with the leaf first and the root last.*\n\n\n- term **--allow-insecure-http**:\n\n*Allow using a non-HTTPS registry URL.*\n\n\n- term **--dry-run**:\n\n*Dry run only; prepare the archive and sign it but do not publish to the registry.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageRegistry/PackageRegistrySet.md",
    "content": "# swift package-registry set\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.9\")\n}\n\nSet a custom registry.\n\n## Overview\n\nUse this subcommand to assign a registry at project or user-level.\n\n### Project-level\n\n```bash\n$ swift package-registry set https://packages.example.com \n```\n\nAt the project level, package manager uses the registry for packages within the project with the registry settings stored in `.swiftpm/configuration/registries.json`.\n\n### User-level\n\nWhen you pass the `--global` option, the package manager sets the registry at the user-level:\n\n```bash\n$ swift package-registry set --global https://global.example.com \n```\n\nAt the user level, the package manager uses the registry for all projects for that user with the registry settings stored in `~/.swiftpm/configuration/registries.json`.\n\n\n### Registry settings\n\nAn example of the `registries.json` that would result from the user-level setting from above would look something like:\n\n```json\n{\n  \"registries\" : {\n    \"[default]\" : {\n      \"url\": \"https://global.example.com\"\n    }   \n  },\n  \"version\" : 1\n}\n```\n\nThe JSON key `[default]` means that the registry at `https://global.example.com` is \"unscoped\" and will be applied when there is no registry association found for a given scope. \n\n### Setting a scope\n\nTo set a specific scope:\n\n```bash\n# project-level\n$ swift package-registry set --scope foo https://local.example.com\n\n# user-level\n$ swift package-registry set --scope foo --global https://global.example.com  \n```\n\n### Removing a registry\n\nTo remove a registry assignment, use the [`swift package-registry unset` subcommand](<doc:PackageRegistryUnset>).\n\n\n### Usage\n\n```\npackage-registry set [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--global] [--scope=<scope>]\n  [--allow-insecure-http] <url> [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--global**:\n\n*Apply settings to all projects for this user.*\n\n\n- term **--scope=\\<scope\\>**:\n\n*Associate the registry with a given scope.*\n\n\n- term **--allow-insecure-http**:\n\n*Allow using a non-HTTPS registry URL.*\n\n\n- term **url**:\n\n*The registry URL.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageRegistry/PackageRegistryUnset.md",
    "content": "# swift package-registry unset\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.9\")\n}\n\nRemove a configured registry.\n\n### Usage\n\n```\npackage-registry unset [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache] [--disable-dependency-cache]\n  [--enable-build-manifest-caching]\n  [--disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts]\n  [--disable-experimental-prebuilts] [--verbose]\n  [--very-verbose|vv] [--quiet] [--color-diagnostics]\n  [--no-color-diagnostics] [--disable-sandbox] [--netrc]\n  [--enable-netrc] [--disable-netrc]\n  [--netrc-file=<netrc-file>] [--enable-keychain]\n  [--disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation]\n  [--disable-signature-validation] [--enable-prefetching]\n  [--disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store] [--enable-index-store]\n  [--disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip] [--disable-dead-strip]\n  [--disable-local-rpath] [--global] [--scope=<scope>]\n  [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--global**:\n\n*Apply settings to all projects for this user.*\n\n\n- term **--scope=\\<scope\\>**:\n\n*Associate the registry with a given scope.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/PackageSecurity.md",
    "content": "# Package Security\n\nLearn about the security features that the package manager implements.\n\n## Trust on First Use\n\nThe package manager records **fingerprints** of downloaded package versions so that\nit can perform [trust-on-first-use](https://en.wikipedia.org/wiki/Trust_on_first_use)\n(TOFU). \nThat is, when a package version is downloaded for the first time, the package manager trusts that \nit has downloaded the correct contents and requires subsequent downloads of the same \npackage version to have the same fingerprint. \nIf the fingerprint changes, it might be an indicator that the package has been\ncompromised and the package manager either warns or returns an error.\n\nDepending on where a package version is downloaded from, a different value is\nused as its fingerprint:\n                             \n| Package Version Origin | Fingerprint |\n| ---------------------- | ----------- |\n| Git repository         | Git hash of the revision |\n| Package registry       | Checksum of the source archive |\n\nThe package manager keeps version fingerprints for each package in a single file\nunder the `~/.swiftpm/security/fingerprints` directory.\n  - For a Git repository package, the fingerprint filename takes the form of `{PACKAGE_NAME}-{REPOSITORY_URL_HASH}.json` (such as `LinkedList-5ddbcf15.json`).\n  - For a registry package, the fingerprint filename takes the form of `{PACKAGE_ID}.json` (such as `mona.LinkedList.json`).\n\nFor packages retrieved from a registry, the package manager expects all registries to provide consistent fingerprints for packages they host.\nIf the archive is downloaded for the first time, the package manager [fetches metadata of the package release](<doc:RegistryServerSpecification#4.2.-Fetch-information-about-a-package-release>) to obtain the expected checksum.\nOtherwise, the package manager compares the checksum with that in local storage (`~/.swiftpm/security/fingerprints/`), saved from previous download.\n\nIf registries have conflicting fingerprints, the package manager reports an error.\nYou can reduce the error to a warning by setting the [build](<doc:SwiftBuild>) option `--resolver-fingerprint-checking` to `warn` (default is `strict`).\n\n### Package signing\n\n#### Signed packages from a registry\n\nA registry may support or require signing.\nTo sign a package release, package authors set either the `signing-identity` (for reading from operating system's identity store such as Keychain in macOS), or `private-key-path` and `cert-chain-paths` (for reading from files) options of the [`swift package-registry publish`](<doc:PackageRegistryPublish>) subcommand so the package manager can locate the signing key and certificate.\n\nIf the certificate chain's root and intermediates are known by the package manager, the package author would only needs to provide the leaf signing certificate in `cert-chain-paths`. \n\nOtherwise, the package author should be provide the entire certificate chain as `cert-chain-paths` so that all of the certificates are included in the signature, making it possible for the package manager to reconstruct the certificate chain for validation later. \nThis is applicable to `signing-identity` as well. That is, you can use `signing-identity` in combination with `cert-chain-paths` to provide the entire certificate chain.\n\nIf the root of the signing certificate is not in the package manager's default trust store, the package author is responsible for telling package users to include the root certificate in their local [trust roots](<doc:PackageSecurity#Trusted-vs.-untrusted-certificate>) directory, otherwise [signature validation](<doc:Validating-signed-packages>) may fail upon download because the signing certificate is not trusted.\n\nFor more information on signed registry packages, see <doc:UsingSwiftPackageRegistry#Publishing-to-Registry>.\n\n##### Validating signed packages\n\nThe package manager determines if a downloaded archive is signed by checking for presence of the `X-Swift-Package-Signature-Format` and `X-Swift-Package-Signature` headers in the HTTP response.\n\nIt then performs a series of validations based on user's [security configuration](<doc:UsingSwiftPackageRegistry#Security-configuration>).\n- If the archive is unsigned, the package manager will error/prompt/warn/allow based on the `signing.onUnsigned` configuration. \n- If the archive is signed, the package manage validates the signature and the signing certificate chain.\n\n###### Trusted vs. untrusted certificate\n\nA certificate is trusted if it is chained to any root in the package manager's trust store, which consists of:\n- The package manager's default trust store, if `signing.includeDefaultTrustedRootCertificates` is `true`.\n- Custom root(s) in the configured trusted roots directory at `signing.trustedRootCertificatesPath`. Certificates must be DER-encoded.\n\nOtherwise, a certificate is untrusted and handled according to the `signing.onUntrustedCertificate` configuration. \nIf a user opts to continue with the untrusted certificate, the package manager proceeds as if it were an unsigned package.\n\n###### Certificate policies\n\nThe package manager requires all certificates used for package signing to have the \"code signing\" extended key usage extension. They must also satisfy the core policies from [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280), as implemented by [swift-certificates](https://github.com/apple/swift-certificates). \n\nUsers can configure certificate expiry and revocation check through the `signing.validationChecks.certificateExpiration` and `signing.validationChecks.certificateRevocation` configuration, respectively. Note that revocation check implicitly requires expiry check.\n   \nAn invalid signing certificate would result in the package manager rejecting the archive when downloading from a registry, or the package collection.\n\n#### Signed package collections\n\nPackage collection publishers may [sign a collection to protect its contents](<doc:PackageCollections#Protecting-package-collections>) from tampering. \nIf a collection is signed, the package manager checks that the signature is valid before importing it; or returns an error if any of these fails:\n- The file's contents, signature excluded, must match what was used to generate the signature. \nIn other words, this checks to see if the collection was altered after it was signed.\n- The signing certificate must meet all the [requirements](<doc:#Requirements-on-signing-certificate>).\n\nSince signing a package collection is optional, the package manager prompts users for confirmation before they can add an [unsigned collection](<doc:PackageCollectionAdd#Unsigned-package-collections>).\n\n [`package-collection-sign`](https://github.com/apple/swift-package-collection-generator/tree/main/Sources/PackageCollectionSigner) helps publishers sign their package collections. \n To generate a signature you need to provide:\n - The package collection file to be signed.\n - A DER-encoded code signing certificate.\n - The PEM-encoded certificate's private key.\n - The certificate's chain in its entirety.\n\n A signed package collection has an extra `signature` object:\n\n ```json\n {\n   ...,\n   \"signature\": {\n     \"signature\": \"<SIGNATURE>\",\n     \"certificate\": {\n       \"subject\": {\n         \"commonName\": \"Jane Doe\",\n         ...\n       },\n       \"issuer\": {\n         \"commonName\": \"Sample CA\",\n         ...\n       }\n     }\n   }\n }\n ```\n\n - The package manager uses the signature string (represented by `\"<SIGNATURE>\"`) is used to verify the contents of the collection file haven't been tampered with after it was signed. The package manager signs the collection when a user [adds the collection](<doc:PackageCollectionAdd>) to their configured list of collections. It includes the certificate's public key and chain.\n - `certificate` contains details extracted from the signing certificate. `subject.commonName` should be consistent with the name of the publisher so that it's recognizable by users. The root of the certificate must be [installed and trusted on users' machines](<doc:PackageCollectionAdd#Trusted-root-certificates>).\n\nFor more information on adding signed package collections, see <doc:PackageCollectionAdd#Signed-package-collections>. \n\n###### Requirements on signing certificate\n\nCertificates used for signing package collections must meet the following requirements, which are checked and enforced during signature generation (publishers) and verification (Swift Package Manager users):\n- The timestamp at which signing/verification is done must fall within the signing certificate's validity period.\n- The certificate's \"Extended Key Usage\" extension must include \"Code Signing\".\n- The certificate must use either 256-bit EC (recommended for enhanced security) or 2048-bit RSA key.\n- The certificate must not be revoked. The certificate authority must support OCSP, which means the certificate must have the \"Certificate Authority Information Access\" extension that includes OCSP as a method, specifying the responder's URL.\n- The certificate chain is valid and root certificate must be trusted.\n\nNon-expired, non-revoked Swift Package Collection certificates from [developer.apple.com](https://developer.apple.com) satisfy all of the criteria above.\n\n###### Trusted root certificates\n\nSince generating a collection signature requires a certificate, part of the signature check involves validating the certificate and its chain and making sure that the root certificate is trusted.\n\nOn Apple platforms, all root certificates that come preinstalled with the OS are automatically trusted.\nUsers may include additional certificates to trust by placing them in the `~/.swiftpm/config/trust-root-certs` directory. \n\nOn non-Apple platforms, there are no trusted root certificates by default other than those shipped with the [certificate-pinning configuration](<doc:PackageCollections#Protecting-package-collections>).\nOnly those found in `~/.swiftpm/config/trust-root-certs` are trusted.\nThis means that the signature check will always fail unless the `trust-root-certs` directory is set up.\n\nUsers can explicitly specify they trust a publisher and any collections they publish, by obtaining that publisher's root certificate and saving it to `~/.swiftpm/config/trust-root-certs`.\nThe root certificates must be DER-encoded.\nSince the package manager trusts all certificate chains under a root, depending on what roots are installed, some publishers may already be trusted implicitly and users don't need to explicitly specify each one. \n\nWith the `package-collection-sign` tool, the root certificate provided as input for signing a collection is automatically trusted. \nWhen a package manager user tries to add the collection, however, the root certificate must either be preinstalled with the OS (Apple platforms only) or found in the `~/.swiftpm/config/trust-root-certs` directory (all platforms) or shipped with the [certificate-pinning configuration](<doc:PackageCollections#Protecting-package-collections>), otherwise the [signature check](<doc:PackageCollectionAdd#Signed-package-collections>) fails. Collection publishers should make the DER-encoded root certificate(s) that they use downloadable so that users can adjust their setup if needed.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Plugins/EnableBuildPlugin.md",
    "content": "# Enable a build plugin\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.6\")\n}\n\nExtend the package manager with a build plugin from another package.\n\n## Overview\n\nA package plugin is available to the package that defines it, and if there is a corresponding plugin product, it is also available to any other package that has a direct dependency on the package that defines it.\n\n### Add a dependency\n\nTo use a plugin defined in another package, add a package dependency on the package that defines the plugin.\nFor example, to use the [swift-openapi-generator](https://github.com/apple/swift-openapi-generator), add\nthe following dependency:\n\n```swift\nlet package = Package(\n    // name, platforms, products, etc.\n    dependencies: [\n        // other dependencies\n        .package(url: \"https://github.com/apple/swift-openapi-generator\",\n                 from: \"1.0.0\"),\n    ],\n    targets: [\n        // targets\n    ]\n)\n```\n\n\nThis plugin can generate models and stubs for clients and servers from an OpenAPI definition file.\n\n### Identify the targets to enable\n\nAdd the plugin to each target to which it should apply.\nFor example, the following example enables the OpenAPI generator plugin on the executable target:\n\n```swift\nlet package = Package(\n    name: \"Example\",\n    dependencies: [\n        .package(url: \"https://github.com/apple/swift-openapi-generator\",\n                 from: \"1.0.0\"),\n    ],\n    targets: [\n        .executableTarget(\n            name: \"MyExample\",\n            plugins: [\n                .plugin(name: \"OpenAPIGenerator\", \n                        package: \"swift-openapi-generator\")\n            ]\n        )\n    ]\n)\n```\nWhen package manager builds the executable target, it calls the plugin and passes it a simplified version of the package model for the target to which it is applied.\nAny build commands returned by the plugin are be incorporated into the build graph and run at the appropriate time during the build.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Plugins/EnableCommandPlugin.md",
    "content": "# Enable a command plugin\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.6\")\n}\n\nExtend package manager commands with a command plugin from another package.\n\n## Overview\n\nTo get access to a plugin from another package, add a dependency on the package that provides the plugin.\nThis lets the package access any plugins from the dependency.\n\n### Add a dependency\n\nFor example, to enable the plugins from [swift-docc-plugin](https://github.com/swiftlang/swift-docc-plugin), add it as a dependency:\n\n```swift\nlet package = Package(\n    // name, platforms, products, etc.\n    dependencies: [\n        // other dependencies\n        .package(url: \"https://github.com/swiftlang/swift-docc-plugin\",\n                 from: \"1.0.0\"),\n    ],\n    targets: [\n        // targets\n    ]\n)\n```\n\n### View available plugins\n\nRun `swift package plugin --list` to see available plugins.\nFor full documentation on the plugin command, see <doc:PackagePlugin>.\n\nInvoke an available plugin using `swift package` followed by the plugin, and provide any parameters or options required.\nFor example, the following command invokes the `generate-documentation` command from [swift-docc-plugin](https://github.com/swiftlang/swift-docc-plugin).\n\n```bash\nswift package generate-documentation\n```\n\n### Pass arguments and flags to the plugin\n\nPackage manager passes all command line arguments and flags after the invocation verb to the plugin.\n\nFor example, if your package has multiple targets you may want to specify a single target with the parameter: `--target`.\nAn updated example that previews the hypothetical target `MyTarget`:\n\n```bash\nswift package generate-documentation --target MyTarget\n```\n\n### Exempting sandbox constraints\n\nCommand plugins that need to write to the file system cause package manager to ask the user for approval if `swift package` is invoked from a console, or deny the request if it is not.\nPass the flag `--allow-writing-to-package-directory` to the `swift package` invocation to allow the request without questions — this is particularly useful in a Continuous Integration environment.\n\nSimilarly, use the `--allow-network-connections` flag to allow network connections without showing a prompt.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Plugins/WritingBuildToolPlugin.md",
    "content": "# Writing a build tool plugin\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.6\")\n}\n\nCreate a build tool to process or generate files.\n\n## Overview\n\nThe first step when writing a package plugin is to decide what kind of plugin you need.\nImplement a build tool plugin to generate source files that should be part of a build, or to perform other actions at the start of every build.\nBuild tool plugins are invoked before a package is built in order to construct command invocations to run as part of the build.\n\nA build tool plugin can provide two kinds of commands:\n\n- term prebuild commands: commands that package manager runs before the build starts. Prebuild commands can generate an arbitrary number of output files with names that can't be predicted before running the command.\n- term build commands: commands that package manager incorporates into the build system's dependency graph and runs at the appropriate time during the build based on the existence and timestamps of their predefined inputs and outputs.\n\n> Note: If your goal is to provide an action that you can perform at any time and is not associated with a build, implement a command plugin.\n> See <doc:WritingCommandPlugin> for details about creating a command plugin.\n\nWith both prebuild and build commands, it is important to note that the build tool plugin doesn't do the work, rather it constructs the commands that the build runs later, and it is those commands that perform the work.\nThe plugin can be quite small, and is often concerned with forming the command line for the build command that does the actual work.\n\nA build tool plugin is available to the package that defines it, and if there is a corresponding plugin product, it is also available to any other package that has a direct dependency on the package.\n\n### Build commands\n\nPrefer to create a build command over a prebuild command when the paths of all of the inputs and outputs are known before the command runs.\nBuild tool commands are more efficient because they provide the build system the information needed to efficiently decide when the build should invoke them.\n\nAn example is a source translation tool that generates one output file (with a predictable name) for each input file.\nOther examples include when the build command controls the names of the outputs without having to first run the tool.\nIn these cases the build system runs the commands only when some of the expected outputs are missing, or when the inputs have changed after the last time the command ran.\nBuild commands don't require a one-to-one correspondence between inputs and outputs; it is free to choose how many (if any) output files to create by examining the input target.\n\n### Prebuild commands\n\nCreate a prebuild command only when the names of the output aren't known until the tool is run.\nThis is the case if the _contents_ of the input files (opposed to the input file names) determines the number and names of the output files, such as generating code based on the input of a configuration file.\nThe build system runs prebuild commands run before every build.\nThey should therefore do their own caching to minimize the work needed to avoid slowing down incremental builds.\n\n### Declaring a build tool plugin in the package manifest\n\nDeclare a build tool plugin in the package manifest.\nThis is done using a `pluginTarget` entry in the `targets` section of the package.\nAdd a corresponding `plugin` entry the products section to make the plugin available to other packages.   \n\nThe following example illustrates defining a build tool named \"MyBuildToolPlugin\" that depends on the product `SomeTool`, and can be used from other packages:\n\n```swift\nimport PackageDescription\n\nlet package = Package(\n    name: \"MyPluginPackage\",\n    products: [\n        .plugin(\n            name: \"MyBuildToolPlugin\",\n            targets: [\n                \"MyBuildToolPlugin\"\n            ]\n        )\n    ],\n    dependencies: [\n        .package(\n            url: \"https://github.com/example/sometool\",\n            from: \"0.1.0\"\n        )\n    ],\n    targets: [\n        .plugin(\n            name: \"MyBuildToolPlugin\",\n            capability: .buildTool(),\n            dependencies: [\n                .product(name: \"SomeTool\", package: \"sometool\"),\n            ]\n        )\n    ]\n)\n```\n\nThe [plugin target](https://developer.apple.com/documentation/packagedescription/target/plugin(name:capability:dependencies:path:exclude:sources:)) declares the name and capability of the plugin, along with its dependencies.\nThe capability of `.buildTool()` is the declaration that this defines a build tool plugin.\nThe capability also indicates the entry point the plugin is expected to implement.\n\nWhen you declare a `plugin` product, that makes the plugin visible to other packages that have a dependency on the package.\nThe name of the plugin doesn't have to match the name of the product, but they are often the same in order to avoid confusion.\nOnly list the name of the plugin the target provides.\nIf you only use the build tool plugin within the package, you don't need to declare a `plugin` product.\n\n### Build tool target dependencies\n\nThe dependencies specify the command line tools available for use in commands constructed by the plugin.\nEach dependency can be either an `executableTarget` or a `binaryTarget` target in the same package, or can be an `executable` product in another package.\nIn the example above, the plugin depends on the hypothetical _SomeTool_ product in the _sometool_ package on which the package that defines the plugin has a dependency.\nNote that this does not necessarily mean that _SomeTool_ will have been built when the plugin is invoked. It means that the plugin can look up the path at which the tool will exist at the time any commands constructed by the plugin are run.\n\nExecutable dependencies are built for the host platform as part of the build, while binary dependencies are references to `artifactbundle` archives that contains prebuilt binaries (see [SE-305](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0305-swiftpm-binary-target-improvements.md)).\nBinary targets are often used when the tool is built using a different build system than package manager, or when building it on demand is prohibitively expensive or requires a special build environment.\n\n### Implementing the build tool plugin script\n\nBy default, Swift Package Manager looks for the implementation of a declared plugin in a subdirectory of the `Plugins` directory named with the same name as the plugin target.\nThis can be overridden using the `path` parameter in the target declaration.\n\nA plugin consists of one or more Swift source files.\nConform the main entry point of the build tool plugin script to the `BuildToolPlugin` protocol.\n\nSimilar to how a package manifest imports the *PackageDescription* module provided by package manager, a package plugin imports the *PackagePlugin* module. \nThe *PackagePlugin* module contains the API through which the plugin receives information from package manager and communicates results back to it.\nThe plugin script can import *Foundation* and other standard libraries, but it cannot import other libraries.\n\nThe following example returns an instance of `buildCommand`, so the package manager incorporates it into the build system's command graph.\nThe build system runs it if any of the output files are missing, or if the contents of any of the input files have changed since the last time the command ran.\n\n```swift\nimport PackagePlugin\n\n@main\nstruct MyPlugin: BuildToolPlugin {\n    \n  func createBuildCommands(context: PluginContext, \n                           target: Target) throws -> [Command] {\n    // This plugin only runs for package targets that can have source files.\n    guard let sourceFiles = target.sourceModule?.sourceFiles else { return [] }\n\n    // Find the code generator tool to run (replace this with the actual one).\n    let generatorTool = try context.tool(named: \"my-code-generator\")\n\n    // Construct a build command for each source file with a particular suffix.\n    return sourceFiles.map(\\.url).compactMap {\n        createBuildCommand(for: $0, in: context.pluginWorkDirectoryURL, with: generatorTool.url)\n    }\n  }\n\n  func createBuildCommand(for inputPath: URL,\n                          in outputDirectoryPath: URL,\n                          with generatorToolPath: URL) -> Command? {\n    // Skip any file that doesn't have the extension we're looking for\n    // (replace this with the actual one).\n    guard inputPath.pathExtension == \"my-input-suffix\" else { return .none }\n\n    // Return a command that will run during the build to generate the output file.\n    let inputName = inputPath.lastPathComponent\n    let outputName = inputPath.deletingPathExtension().lastPathComponent + \".swift\"\n    let outputPath = outputDirectoryPath.appendingPathComponent(outputName)\n    return .buildCommand(\n        displayName: \"Generating \\(outputName) from \\(inputName)\",\n        executable: generatorToolPath,\n        arguments: [\"\\(inputPath)\", \"-o\", \"\\(outputPath)\"],\n        inputFiles: [inputPath],\n        outputFiles: [outputPath]\n    )\n  }\n}\n```\n\nBuild tool plugins are always applied to a target, which is provided as a parameter.\nOnly source module targets have source files, so a plugin that iterates over source files commonly tests that the target it was provided conforms to `SourceModuleTarget`.\n\nA build tool plugin can also return commands of the type `prebuildCommand`.\nThese run before the build starts and can populate a directory with output files whose names are not known until the command runs:\n\n```swift\nimport PackagePlugin\nimport Foundation\n\n@main\nstruct MyBuildToolPlugin: BuildToolPlugin {\n    \n  func createBuildCommands(context: PluginContext, \n                           target: Target) throws -> [Command] {\n\n    // This example configures `sometool` to write to a \n    // \"GeneratedFiles\" directory in the plugin work directory \n    // (which is unique for each plugin and target).\n    let outputDir = context.pluginWorkDirectoryURL\n        .appendingPathComponent(\"GeneratedFiles\")\n    try FileManager.default.createDirectory(\n        at: outputDir,\n        withIntermediateDirectories: true)\n\n    // Return a command to run `sometool` as a prebuild command. \n    // It runs before every build and generates source files \n    // into an output directory provided by the build context.\n    return [.prebuildCommand(\n            displayName: \"Running SomeTool\",\n            executable: try context.tool(named: \"SomeTool\").path,\n            arguments: [ \"--verbose\", \"--outdir\", outputDir ],\n            outputFilesDirectory: outputDir)\n    ]\n  }\n}\n```\n\nIn the case of prebuild commands, any dependencies must be binary targets, since these commands run before the build starts.\n\nA build tool plugin can return a combination of build tool commands and prebuild commands.\nAfter the plugin runs, the build system incorporates the build commands it provides into the build graph.\nThis may result in changes that require commands to run during the subsequent build.\n\nThe build system runs prebuild commands after the plugin runs, but before the build starts. \nAny files that are in the prebuild command's declared `outputFilesDirectory` are evaluated as if they had been source files in the target.\nThe prebuild command should add or remove files in this directory to reflect the results of having run the command.\n\nThe package manager supports generated Swift source files and resources as outputs, but it does not support non-Swift source files.\nAny generated resources are processed as if they had been declared in the manifest with the `.process()` rule.\nThe intent is to eventually support any type of file that you could include as a source file in the target, and to let the plugin provide greater control over the downstream processing of generated files.\n\n### Diagnostics\n\nPlugin entry points are marked `throws`, and any errors thrown from the entry point cause the build system to mark the plugin invocation as failed.\nPackage manager presents the thrown error to the user, which should include a clear description of what went wrong.\n\nAdditionally, plugins can use the `Diagnostics` API in PackagePlugin to emit warnings and errors.\nThese optionally include references to file paths and line numbers in those files.\n\n### Debugging and Testing\n\nPackage manager doesn't currently have any specific support for debugging and testing plugins.\nMany plugins act as adapters that construct command lines for invoking the tools that do the real work.\nIn the cases in which there is non-trivial code in a plugin, a good approach is to factor out that code into separate source files that can be included in unit tests using symbolic links with relative paths.\n\n### Xcode Extensions to the PackagePlugin API\n\nWhen you invoke a plugin in Apple’s Xcode IDE, the plugins have access to a library module provided by Xcode called *XcodeProjectPlugin*. \nThis module extends the *PackagePlugin* APIs to let plugins work on Xcode targets in addition to packages.\n\nIn order to write a plugin that works with packages in every environment, and that conditionally works with Xcode projects when run in Xcode, the plugin should conditionally import the *XcodeProjectPlugin* module when it is available.\nFor example:\n\n```swift\n#if canImport(XcodeProjectPlugin)\nimport XcodeProjectPlugin\n\nextension MyCommandPlugin: XcodeCommandPlugin {\n\n  // Entry point for creating build commands for targets in Xcode projects.\n  func createBuildCommands(context: XcodePluginContext,\n                           target: XcodeTarget) throws -> [Command] {\n    // Find the code generator tool to run (replace this with the actual one).\n    let generatorTool = try context.tool(named: \"my-code-generator\")\n\n    // Construct a build command for each source file with a particular suffix.\n    return target.inputFiles.map(\\.url).compactMap {\n        createBuildCommand(for: $0,\n                           in: context.pluginWorkDirectoryURL,\n                           with: generatorTool.url)\n    }\n  }\n}\n#endif\n```\n\nThe `XcodePluginContext` input structure is similar to the `PluginContext` structure, except that it provides access to an Xcode project. \nThe Xcode project uses Xcode naming and semantics for the project model, which is somewhat different from that of package manager.\nSome of the underlying types, such as `FileList`, or `Path`, are the same for `PackagePlugin` and `XcodeProjectPlugin`.\n\nIf any targets are chosen in the Xcode user interface, Xcode passes their names as `--target` arguments to the plugin.\n\nOther IDEs or custom environments that use the package manager could similarly provide modules that define new entry points and extend the functionality of the core `PackagePlugin` APIs.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Plugins/WritingCommandPlugin.md",
    "content": "# Writing a command plugin\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.6\")\n}\n\nCreate a command plugin to provide commands that extend the package manager.\n\n## Overview\n\nThe first step when writing a package plugin is to decide what kind of plugin you need.  \n\nImplement a command plugin to provide actions that users can perform at any time and that are not associated with a build.\n\n> Note: If your goal is to generate source files that should be part of a build, or to perform other actions at the start of every build, implement a build tool plugin.\n> See <doc:WritingBuildToolPlugin> for details about creating a build tool plugin.\n\nCommand plugins are invoked at will by the user, by invoking `swift` `package` `<command>` `<arguments>`.\nThey are unrelated to the build graph, and often perform their work by invoking to command line tools as subprocesses.\n\nCommand plugins are declared in a similar way to build tool plugins, except that they declare a `.command()` capability and implement a different entry point in the plugin script.\n\nA command plugin specifies the semantic intent of the command — this might be one of the predefined intents such as “documentation generation” or “source code formatting”, or it might be a custom intent with a specialized verb that can be passed to the `swift` `package` command.\nA command plugin can also specify any special permissions it needs, such as the permission to modify the files under the package directory.\n\nThe command's intent declaration provides a way of grouping command plugins by their functional categories, so that package manager — or an IDE that supports package manager packages — can show the commands that are available for a particular purpose.\nFor example, this approach supports having different command plugins for generating documentation for a package, while still allowing those different commands to be grouped and discovered by intent.\n\nA plugin is available to the package that defines it, and if there is a corresponding plugin product, it is also available to any other package that has a direct dependency on the package.\n\n### Declaring a command plugin in the package manifest\n\nThe manifest of a package that declares a command plugin might look like:\n\n```swift\nimport PackageDescription\n\nlet package = Package(\n  name: \"MyPluginPackage\",\n  products: [\n    .plugin(\n      name: \"MyCommandPlugin\",\n      targets: [\n        \"MyCommandPlugin\"\n      ]\n    )\n  ],\n  dependencies: [\n    .package(\n      url: \"https://github.com/example/sometool\",\n      from: \"0.1.0\"\n    )\n  ],\n  targets: [\n    .plugin(\n      name: \"MyCommandPlugin\",\n      capability: .command(\n        intent: .sourceCodeFormatting(),\n        permissions: [\n          .writeToPackageDirectory(reason: \"This command reformats source files\")\n        ]\n      ),\n      dependencies: [\n        .product(name: \"SomeTool\", package: \"sometool\"),\n      ]\n    )\n  ]\n)\n```\n\nIn the above example, the plugin declares its purpose is source code formatting, and that it needs permission to modify files in the package directory.\nThe package manager runs plugins in a sandbox that prevents network access and most file system access.\nPackage manager allows additional permissions to allow network access or file system acess when you declare them after it receives approval from the user.\n\n### Implementing the command plugin script\n\nThe source that implements command plugins should be located under the `Plugins` subdirectory in the package.\nConform the entry point of the plugin to the `CommandPlugin` protocol:\n\n```swift\nimport PackagePlugin\nimport Foundation\n\n@main\nstruct MyCommandPlugin: CommandPlugin {\n  func performCommand(\n    context: PluginContext,\n    arguments: [String]\n  ) throws {\n    // To invoke `sometool` to format code, start by locating it.\n    let sometool = try context.tool(named: \"sometool\")\n\n    // By convention, use a configuration file in the root \n    // directory of the package. This allows package owners to \n    // commit their format settings to their repository.\n    let configFile = context\n      .package\n      .directory\n      .appending(\".sometoolconfig\")\n\n    // Extract the target arguments (if there are none, assume all).\n    var argExtractor = ArgumentExtractor(arguments)\n    let targetNames = argExtractor.extractOption(named: \"target\")\n    let targets = targetNames.isEmpty\n      ? context.package.targets\n      : try context.package.targets(named: targetNames)\n\n    // Iterate over the provided targets to format.\n    for target in targets {\n      // Skip any type of target that doesn't have \n      // source files.\n      // Note: This could instead emit a warning or error.\n      guard let target = target.sourceModule else { continue }\n\n      // Invoke `sometool` on the target directory, passing \n      // a configuration file from the package directory.\n      let sometoolExec = URL(fileURLWithPath: sometool.path.string)\n      let sometoolArgs = [\n        \"--config\",\n        \"\\(configFile)\",\n        \"--cache\", \n        \"\\(context.pluginWorkDirectory.appending(\"cache-dir\"))\",\n        \"\\(target.directory)\"\n      ]\n      let process = try Process.run(sometoolExec, \n                                    arguments: sometoolArgs)\n      process.waitUntilExit()\n\n      // Check whether the subprocess invocation was successful.\n      if process.terminationReason == .exit \n        && process.terminationStatus == 0\n      {\n        print(\"Formatted the source code in \\(target.directory).\")\n      } else {\n        let problem = \"\\(process.terminationReason):\\(process.terminationStatus)\"\n        Diagnostics.error(\"Formatting invocation failed: \\(problem)\")\n      }\n    }\n  }\n}\n```\n\nUnlike build tool plugins, which apply to a single package target, a command plugin does not necessarily operate on just a single target.\nThe `context` parameter provides access to the inputs, including to a distilled version of the package graph rooted at the package to which the command plugin is applied.\n\nCommand plugins can accept arguments, which you use to control options for the plugin's actions or further narrow down what the plugin operates on.\nThis example uses the convention of passing `--target` to limit the scope of the plugin to a set of targets in the package.\n\nPlugins can only use standard system libraries, not those from other packages such as `SwiftArgumentParser`.\nConsequently, the plugin example uses the built-in `ArgumentExtractor` helper in the *PackagePlugin* module to extract the argument.\n\n### Diagnostics\n\nPlugin entry points are marked `throws`, and any errors thrown from the entry point causes the plugin invocation to be marked as having failed.\nThe thrown error is presented to the user, and should include a clear description of what went wrong.\n\nAdditionally, plugins can use the `Diagnostics` API in PackagePlugin to emit warnings and errors that optionally include references to file paths and line numbers in those files.\n\n### Debugging and Testing\n\nPackage manager doesn't currently have any specific support for debugging and testing plugins.\nMany plugins act as adapters that construct command lines for invoking the tools that do the real work.\nIn the cases in which there is non-trivial code in a plugin, a good approach is to factor out that code into separate source files that can be included in unit tests using symbolic links with relative paths.\n\n### Xcode Extensions to the PackagePlugin API\n\nWhen you invoke a plugin in Apple’s Xcode IDE, the plugins has access to a library module provided by Xcode called *XcodeProjectPlugin*. \nThis module extends the *PackagePlugin* APIs to let plugins work on Xcode targets in addition to packages.\n\nIn order to write a plugin that works with packages in every environment, and that conditionally works with Xcode projects when run in Xcode, the plugin should conditionally import the *XcodeProjectPlugin* module when it is available.\nFor example:\n\n```swift\nimport PackagePlugin\n\n@main\nstruct MyCommandPlugin: CommandPlugin {\n    /// This entry point is called when operating on a Swift package.\n    func performCommand(context: PluginContext,\n                        arguments: [String]) throws {\n        debugPrint(context)\n    }\n}\n\n#if canImport(XcodeProjectPlugin)\nimport XcodeProjectPlugin\n\nextension MyCommandPlugin: XcodeCommandPlugin {\n    /// This entry point is called when operating on an Xcode project.\n    func performCommand(context: XcodePluginContext, \n                        arguments: [String]) throws {\n        debugPrint(context)\n    }\n}\n#endif\n```\n\nThe `XcodePluginContext` input structure is similar to the `PluginContext` structure, except that it provides access to an Xcode project. \nThe Xcode project uses Xcode naming and semantics for the project model, which is somewhat different from that of package manager.\nSome of the underlying types, such as `FileList`, or `Path`, are the same for `PackagePlugin` and `XcodeProjectPlugin`.\n\nIf any targets are chosen in the Xcode user interface, Xcode passes their names as `--target` arguments to the plugin.\n\nOther IDEs or custom environments that use the package manager could similarly provide modules that define new entry points and extend the functionality of the core `PackagePlugin` APIs.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/Plugins.md",
    "content": "# Plugins\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.6\")\n}\n\nExtend package manager functionality with build or command plugins.  \n\n## Overview\n\nSome of Swift Package Manager's functionality can be extended through _plugins_.\nWrite package plugins using the `PackagePlugin` API provided by the Swift Package Manager. <!-- link to docs needed -->\nThis is similar to how the package manifest is implemented — as Swift code that runs as needed in order to produce the information package manager needs.\n\nPackage manager defines two extension points for plugins:\n\n- term Build Plugin: Custom build tool tasks that provide commands to run before or during the build.\n  See <doc:EnableBuildPlugin> to see how to add an existing build plugin, or <doc:WritingBuildToolPlugin> to write your own.\n\n- term Command Plugin: Custom commands that you run using the `swift package` command line interface.\n  See <doc:EnableCommandPlugin> to see how to add an existing command plugin, or <doc:WritingCommandPlugin> to write your own.\n\n### Plugin Capabilities\n\nPlugins have access to a representation of the package model.\nCommand plugins can also invoke services provided by package manager to build and test products and targets defined in the package to which the plugin is applied.\n\nEvery plugin runs as a separate process from the package manager. \nOn platforms that support sandboxing, package manager wraps the plugin in a sandbox that prevents network access and attempts to write to arbitrary locations in the file system.\nAll plugins can write to a temporary directory.\n\nCustom command plugins that need to modify the package source code can specify this requirement.\nIf the user approves, package manager grants write access to the package directory.\nBuild tool plugins can't modify the package source code.\n\n### Creating Plugins\n\nWhen creating a plugin, represent a plugin in the package manifest as a target of the `pluginTarget` type.\nIf it should be available to other packages, also include a corresponding `pluginProduct` target.\nSource code for a plugin is normally located in a directory under the `Plugins` directory in the package, but this can be customized.\n\nA plugin declares which extension point it implements by defining the plugin's _capability_.\nThis determines the entry point through which package manager will call it, and determines which actions the plugin can perform.\n\n### References\n\n- \"Meet Swift Package plugins\" [WWDC22 session](https://developer.apple.com/videos/play/wwdc2022-110359)\n- \"Create Swift Package plugins\" [WWDC22 session](https://developer.apple.com/videos/play/wwdc2022-110401)\n\n## Topics\n\n### Enabling Plugins\n\n- <doc:EnableCommandPlugin>\n- <doc:EnableBuildPlugin>\n\n### Writing Plugins\n\n- <doc:WritingCommandPlugin>\n- <doc:WritingBuildToolPlugin>\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/RegistryServerSpecification.md",
    "content": "# Swift Package Registry Service Specification\n\nLearn about the specification for SwiftPM's registry service.\n\n### 1. Notations\n\nThe following terminology and conventions are used in this document.\n\nThe key words \"MUST\", \"MUST NOT\", \"REQUIRED\", \"SHALL\", \"SHALL NOT\",\n\"SHOULD\", \"SHOULD NOT\", \"RECOMMENDED\", \"MAY\", and \"OPTIONAL\"\nin this document are to be interpreted as described in [RFC 2119].\n\nThis specification uses the Augmented Backus-Naur Form (ABNF) notation\nas described in [RFC 5234]\nand Unicode regular expression syntax\nas described in [Unicode Technical Standard #18][UAX18].\n\nAPI endpoints that accept parameters in their path\nare expressed by Uniform Resource Identifier (URI) templates,\nas described in [RFC 6570].\n\n### 2. Definitions\n\nThe following terms, as used in this document, have the meanings indicated.\n\n- _Package_:\n  A named collection of Swift source code\n  that is organized into one or more modules\n  according to a `Package.swift` manifest file.\n- _Scope_:\n  A logical grouping of related packages assigned by a package registry.\n- _Release_:\n  The state of a package after applying a particular set of changes\n  that is uniquely identified by an assigned version number.\n- _Version Number_:\n  An identifier for a package release\n  in accordance with the [Semantic Versioning Specification (SemVer)][SemVer].\n- _Precedence_:\n  The ordering of version numbers relative to each other\n  as defined by the [Semantic Versioning Specification (SemVer)][SemVer].\n\n### 3. Conventions\n\nThis document uses the following conventions\nin its description of client-server interactions.\n\n#### 3.1. Application layer protocols\n\nA client and server MUST communicate over a secured connection\nusing Transport Layer Security (TLS) with the `https` URI scheme.\n\nThe use of HTTP 1.1 in examples is non-normative.\nA client and server MAY communicate according to this specification\nusing any version of the HTTP protocol.\n\n#### 3.2. Authentication\n\nA server MAY require authentication\nfor client requests to access information about packages and package releases.\n\nA server SHOULD respond with a status code of `401` (Unauthorized)\nif a client sends a request to an endpoint that requires authentication\nwithout providing credentials.\nA server MAY respond with a status code of `404` (Not Found) or `403` (Forbidden)\nwhen a client provides valid credentials\nbut isn't authorized to access the requested resource.\n\nA server MAY use any authentication model of its choosing.\nHowever, the use of a scoped, revocable authorization framework\nlike [OAuth 2.0][RFC 6749] is RECOMMENDED.\n\n#### 3.3. Error handling\n\nA server MUST communicate any errors to the client\nusing \"problem details\" objects,\nas described by [RFC 7807].\nFor example,\na client sends a request for a nonexistent release of a package\nand receives the following response:\n\n```http\nHTTP/1.1 404\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"release not found\"\n}\n```\n\n#### 3.4. Rate limiting\n\nA server MAY limit the number of requests made by a client\nby responding with a status code of `429` (Too Many Requests).\n\n```http\nHTTP/1.1 429\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\nRetry-After: 60\n\n{\n   \"detail\": \"try again in 60 seconds\"\n}\n```\n\nA client SHOULD follow the guidance of any\n`Retry-After` header values provided in responses\nto prevent overwhelming a server with retry requests.\nIt is RECOMMENDED for clients to introduce random jitter in their retry logic\nto avoid a [thundering herd effect].\n\n#### 3.5. API versioning\n\nPackage registry APIs are versioned.\n\nAPI version numbers are designated by decimal integers.\nThe accepted version of this proposal constitutes the initial version, `1`.\nSubsequent revisions SHOULD be numbered sequentially\n(`2`, `3`, and so on).\n\nAPI version numbers SHOULD follow\nSemantic Versioning conventions for major releases.\nNon-breaking changes, such as\nadding new endpoints,\nadding new optional parameters to existing endpoints,\nor adding new information to existing endpoints in a backward-compatible way,\nSHOULD NOT require a new version.\nBreaking changes, such as\nremoving or changing an existing endpoint\nin a backward-incompatible way,\nMUST correspond to a new version.\n\nA client SHOULD set the `Accept` header field\nto specify the API version of a request.\n\n```http\nGET /mona/LinkedList/list HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+json\n```\n\nValid `Accept` header field values are described by the following rules:\n\n```abnf\n    version     = \"1\"       ; The API version\n    mediatype   = \"json\" /  ; JSON (default media type)\n                  \"zip\"  /  ; Zip archives, used for package releases\n                  \"swift\"   ; Swift file, used for package manifest\n    accept      = \"application/vnd.swift.registry\" [\".v\" version] [\"+\" mediatype]\n```\n\nA server MUST set the `Content-Type` header field\nwith the corresponding content type of the response.\n\nA server MUST set the `Content-Version` header field\nwith the API version number of the response, unless\nexplicitly stated otherwise.\n\n```http\nHTTP/1.1 200 OK\nContent-Type: application/json\nContent-Version: 1\n```\n\nIf a client sends a request without an `Accept` header,\na server MAY either respond with a status code of `400 Bad Request` or\nprocess the request using an API version that it chooses,\nmaking sure to set the `Content-Type` and `Content-Version` headers accordingly.\n\nIf a client sends a request with an `Accept` header\nthat specifies an unknown or invalid API version,\na server SHOULD respond with a status code of `400` (Bad Request).\n\n```http\nHTTP/1.1 400 Bad Request\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"invalid API version\"\n}\n```\n\nIf a client sends a request with an `Accept` header\nthat specifies a valid but unsupported API version,\na server SHOULD respond with a status code of `415` (Unsupported Media Type).\n\n```http\nHTTP/1.1 415 Unsupported Media Type\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"unsupported API version\"\n}\n```\n\n#### 3.6. Package identification\n\nA package may declare external packages as dependencies in its manifest.\nEach package dependency may specify a requirement\non which versions are allowed.\n\nAn external package dependency may itself have\none or more external package dependencies,\nknown as <dfn>transitive dependencies</dfn>.\nWhen multiple packages have dependencies in common,\nSwift Package Manager determines which version of that package should be used\n(if any exist that satisfy all specified requirements)\nin a process called <dfn>package resolution</dfn>.\n\nEach external package is uniquely identified\nby a scoped identifier in the form `scope.package-name`.\n\n##### 3.6.1 Package scope\n\nA *scope* provides a namespace for related packages within a package registry.\nA package scope consists of alphanumeric characters and hyphens.\nHyphens may not occur at the beginning or end,\nnor consecutively within a scope.\nThe maximum length of a package scope is 39 characters.\nA valid package scope matches the following regular expression pattern:\n\n```regexp\n\\A[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}\\z\n```\n\nPackage scopes are case-insensitive\n(for example, `mona` ≍ `MONA`).\n\n##### 3.6.2. Package name\n\nA package's *name* uniquely identifies a package in a scope.\nA package name consists of alphanumeric characters, underscores, and hyphens.\nHyphens and underscores may not occur at the beginning or end,\nnor consecutively within a name.\nThe maximum length of a package name is 100 characters.\nA valid package name matches the following regular expression pattern:\n\n```regexp\n\\A[a-zA-Z0-9](?:[a-zA-Z0-9]|[-_](?=[a-zA-Z0-9])){0,99}\\z\n```\n\nPackage names are case-insensitive\n(for example, `LinkedList` ≍ `LINKEDLIST`).\n\n### 4. Endpoints\n\nA server MUST respond to the following endpoints:\n\n| Link                 | Method | Path                                                      | Description                                       |\n| -------------------- | ------ | --------------------------------------------------------- | ------------------------------------------------- |\n| [\\[1\\]](<doc:#4.1.-List-package-releases>) | `GET`  | `/{scope}/{name}`                                         | List package releases                             |\n| [\\[2\\]](<doc:#4.2.-Fetch-information-about-a-package-release>) | `GET`  | `/{scope}/{name}/{version}`                               | Fetch metadata for a package release              |\n| [\\[3\\]](<doc:#4.3.-Fetch-manifest-for-a-package-release>) | `GET`  | `/{scope}/{name}/{version}/Package.swift{?swift-version}` | Fetch manifest for a package release              |\n| [\\[4\\]](<doc:#4.4.-Download-source-archive>) | `GET`  | `/{scope}/{name}/{version}.zip`                           | Download source archive for a package release     |\n| [\\[5\\]](<doc:#4.5.-Lookup-package-identifiers-registered-for-a-URL>) | `GET`  | `/identifiers{?url}`                                      | Lookup package identifiers registered for a URL   |\n| [\\[6\\]](<doc:#4.6.-Create-a-package-release>) | `PUT`  | `/{scope}/{name}/{version}`                               | Create a package release                          |\n\nA server SHOULD also respond to `HEAD` requests\nfor each of the specified endpoints.\n\nA client MAY send an `OPTIONS` request with an asterisk (`*`)\nto determine the permitted communication options for the server.\nA server MAY respond with a `Link` header containing\nan entry for the `service-doc` relation type\nwith a link to this document, and\nan entry for the `service-desc` relation type\nwith a link to the OpenAPI specification.\n\n* * *\n\n<a name=\"endpoint-1\"></a>\n\n#### 4.1. List package releases\n\nA client MAY send a `GET` request\nfor a URI matching the expression `/{scope}/{name}`\nto retrieve a list of the available releases for a particular package.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+json`\nand MAY append the `.json` extension to the requested URI.\n\n```http\nGET /mona/LinkedList HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+json\n```\n\nIf a package is found at the requested location,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `application/json`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\nA server SHOULD respond with a JSON document\ncontaining the releases for the requested package.\n\n```http\nHTTP/1.1 200 OK\nContent-Type: application/json\nContent-Version: 1\nContent-Length: 508\nLink: <https://github.com/mona/LinkedList>; rel=\"canonical\",\n      <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n      <https://packages.example.com/mona/LinkedList/1.1.1>; rel=\"latest-version\",\n      <https://github.com/sponsors/mona>; rel=\"payment\"\n\n{\n    \"releases\": {\n        \"1.1.1\": {\n            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.1\"\n        },\n        \"1.1.0\": {\n            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.0\",\n            \"problem\": {\n                \"status\": 410,\n                \"title\": \"Gone\",\n                \"detail\": \"this release was removed from the registry\"\n            }\n        },\n        \"1.0.0\": {\n            \"url\": \"https://packages.example.com/mona/LinkedList/1.0.0\"\n        }\n    }\n}\n```\n\nThe response body MUST contain a JSON object\nnested at a top-level `releases` key,\nwhose keys are version numbers for releases and\nwhose values are objects containing the following fields:\n\n| Key       | Type   | Description                           | Requirement Level |\n| --------- | ------ | ------------------------------------- | ----------------- |\n| `url`     | String | The location of the release resource. | OPTIONAL          |\n| `problem` | Object | A [problem details][RFC 7807] object. | OPTIONAL          |\n\nA server MAY specify a URL for a release using the `url` key.\nA client SHOULD locate a release using the value of the `url` key, if one is provided.\nOtherwise, the client SHOULD locate a release\nby expanding the URI Template `/{scope}/{name}/{version}` on the originating host.\n\nA server SHOULD communicate the unavailability of a package release\nusing a [\"problem details\"][RFC 7807] object.\nA client SHOULD consider any releases with an associated `problem`\nto be unavailable for the purposes of package resolution.\n\nA server SHOULD respond with\na link to the highest precedence published release of the package if one exists,\nusing a `Link` header field with a `latest-version` relation.\n\nA server SHOULD list releases in order of precedence,\nstarting with the highest precedence version.\nHowever, a client SHOULD NOT assume\nany specific ordering of versions in a response.\n\nA server MAY include a `Link` entry\nwith the `canonical` relation type\nthat locates the source repository of the package.\n\nA server MAY include one or more `Link` entries\nwith the `alternate` relation type\nfor other source repository locations.\n\nA server MAY paginate results by responding with\na `Link` header field that includes any of the following relations:\n\n| Name    | Description                             |\n| ------- | --------------------------------------- |\n| `next`  | The immediate next page of results.     |\n| `last`  | The last page of results.               |\n| `first` | The first page of results.              |\n| `prev`  | The immediate previous page of results. |\n\nFor example,\nthe `Link` header field in a response for the third page of paginated results:\n\n```http\nLink: <https://packages.example.com/mona/HashMap/5.0.3>; rel=\"latest-version\",\n      <https://packages.example.com/mona/HashMap?page=1>; rel=\"first\",\n      <https://packages.example.com/mona/HashMap?page=2>; rel=\"previous\",\n      <https://packages.example.com/mona/HashMap?page=4>; rel=\"next\",\n      <https://packages.example.com/mona/HashMap?page=10>; rel=\"last\"\n```\n\nA server MAY respond with additional `Link` entries,\nsuch as one with a `payment` relation for sponsoring a package maintainer.\n\n<a name=\"endpoint-2\"></a>\n\n#### 4.2. Fetch information about a package release\n\nA client MAY send a `GET` request\nfor a URI matching the expression `/{scope}/{name}/{version}`\nto retrieve information about a release.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+json`,\nand MAY append the `.json` extension to the requested URI.\n\n```http\nGET /mona/LinkedList/1.1.1 HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+json\n```\n\nIf a release is found at the requested location,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `application/json`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\n```http\nHTTP/1.1 200 OK\nContent-Version: 1\nContent-Type: application/json\nContent-Length: 720\nLink: <https://packages.example.com/mona/LinkedList/1.1.1>; rel=\"latest-version\",\n      <https://packages.example.com/mona/LinkedList/1.0.0>; rel=\"predecessor-version\"\n{\n  \"id\": \"mona.LinkedList\",\n  \"version\": \"1.1.1\",\n  \"resources\": [\n    {\n      \"name\": \"source-archive\",\n      \"type\": \"application/zip\",\n      \"checksum\": \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\",\n      \"signing\": {\n        \"signatureBase64Encoded\": \"l1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\",\n        \"signatureFormat\": \"cms-1.0.0\"\n      }\n    }\n  ],\n  \"metadata\": { ... },\n  \"publishedAt\": \"2023-02-16T04:00:00.000Z\"\n}\n```\n\nThe response body SHOULD contain a JSON object containing the following fields:\n\n| Key           | Type   | Description                               | Required |\n| ------------- | ------ | ----------------------------------------- | :------: |\n| `id`          | String | The namespaced package identifier.        | ✓ |\n| `version`     | String | The package release version number.       | ✓ |\n| `resources`   | Array  | The resources available for the release.  | ✓ |\n| `metadata`    | Object | Additional information about the release. | ✓ |\n| `publishedAt` | String | The [ISO 8601]-formatted datetime string of when the package release was published, as recorded by the registry. See related [`originalPublicationTime`](<doc:#Appendix-B---Package-Release-Metadata-JSON-Schema>) in `metadata`. | |\n\nA server SHOULD respond with a `Link` header containing the following entries:\n\n| Relation              | Description                                                                          |\n| --------------------- | ------------------------------------------------------------------------------------ |\n| `latest-version`      | The highest precedence published release of the package                              |\n| `successor-version`   | The next published release of the package ordered by precedence, if one exists       |\n| `predecessor-version` | The previously published release of the package ordered by precedence, if one exists |\n\nA link with the `latest-version` relation\nMAY correspond to the requested release.\n\n##### 4.2.1. Package release resources\n\nEach element in the `resources` array is a JSON object with the following keys:\n\n| Key        | Type    | Description                                                                |\n| ---------- | ------- | -------------------------------------------------------------------------- |\n| `name`     | String  | The name of the resource.                                                  |\n| `type`     | String  | The content type of the resource.                                          |\n| `checksum` | String  | A hexadecimal representation of the SHA256 digest for the resource.        |\n| `signing`  | Object  | Information about the signature. Required only if the resource is signed.  |\n\nThe `signing` JSON object contains these keys:\n\n| Key                      | Type    | Description                                       |\n| ------------------------ | ------- | ------------------------------------------------- |\n| `signatureBase64Encoded` | String  | The resource's signature, base64 encoded.         |\n| `signatureFormat`        | String  | The signature format. (e.g., `cms-1.0.0`)         |\n\nA resource object SHOULD have one of the following combinations of\n`name` and `type` values:\n\n| Name               | Content Type      | Description                        |\n| ------------------ | ----------------- | ---------------------------------- |\n| `source-archive`   | `application/zip` | An archive of package sources.     |\n\nA release MUST NOT have more than a single resource object\nwith a given combination of `name` and `type` values.\n\n##### 4.2.2. Package release metadata standards\n\n [Appendix B](<doc:#Appendix-B---Package-Release-Metadata-JSON-Schema>)\n defines the JSON schema for package release metadata that\n gets submitted as part of the [\"create a package release\"](<doc:#4.6.-Create-a-package-release>)\n request. A server MAY allow and/or populate additional metadata by\n expanding the schema. The `metadata` key in the\n [\"fetch information about a package release\"](<doc:#4.2.-Fetch-information-about-a-package-release>) API response\n will hold the user-provided as well as the server populated metadata.\n\n <a name=\"endpoint-3\"></a>\n\n#### 4.3. Fetch manifest for a package release\n\nA client MAY send a `GET` request for a URI matching the expression\n`/{scope}/{name}/{version}/Package.swift`\nto retrieve the package manifest for a release.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+swift`.\n\n```http\nGET /mona/LinkedList/1.1.1/Package.swift HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+swift\n```\n\nIf a release is found at the requested location,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `text/x-swift`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\n```http\nHTTP/1.1 200 OK\nCache-Control: public, immutable\nContent-Type: text/x-swift\nContent-Disposition: attachment; filename=\"Package.swift\"\nContent-Length: 361\nContent-Version: 1\nLink: <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4>; rel=\"alternate\"; filename=\"Package@swift-4.swift\"; swift-tools-version=\"4.0\",\n      <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4.2>; rel=\"alternate\"; filename=\"Package@swift-4.2.swift\"; swift-tools-version=\"4.2\"\n\n// swift-tools-version:5.0\nimport PackageDescription\n\nlet package = Package(\n    name: \"LinkedList\",\n    products: [\n        .library(name: \"LinkedList\", targets: [\"LinkedList\"])\n    ],\n    targets: [\n        .target(name: \"LinkedList\"),\n        .testTarget(name: \"LinkedListTests\", dependencies: [\"LinkedList\"]),\n    ],\n    swiftLanguageVersions: [.v4, .v5]\n)\n```\n\nA server SHOULD respond with a `Content-Length` header\nset to the size of the manifest in bytes.\n\nA server SHOULD respond with a `Content-Disposition` header\nset to `attachment` with a `filename` parameter equal to\nthe name of the manifest file\n(for example, \"Package.swift\").\n\nA server MAY omit the `Content-Version` header\nsince the response content (i.e., the manifest) SHOULD NOT\nchange across different API versions.\n\nIt is RECOMMENDED for clients and servers to support\ncaching as described by [RFC 7234].\n\nA server MUST include a `Link` header field\nwith a value for each version-specific package manifest file\nin the release's source archive,\nwhose filename matches the following regular expression pattern:\n\n```regexp\n\\APackage@swift-(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?.swift\\z\n```\n\nEach link value SHOULD have the `alternate` relation type,\na `filename` attribute set to the version-specific package manifest filename\n(for example, `Package@swift-4.swift`), and\na `swift-tools-version` attribute set to the [Swift tools version]\nspecified by the package manifest file\n(for example, `4.0` for a manifest beginning with the comment\n`// swift-tools-version:4.0`).\n\n##### 4.3.1. swift-version query parameter\n\nA client MAY specify a `swift-version` query parameter\nto request a manifest for a particular version of Swift.\n\n```http\nGET /mona/LinkedList/1.1.1/Package.swift?swift-version=4.2 HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+swift\n```\n\nIf the package includes a file named\n`Package@swift-{swift-version}.swift`,\nthe server SHOULD respond with a status code of `200` (OK)\nand the content of that file in the response body.\n\n```http\nHTTP/1.1 200 OK\nCache-Control: public, immutable\nContent-Type: text/x-swift\nContent-Disposition: attachment; filename=\"Package@swift-4.2.swift\"\nContent-Length: 361\nContent-Version: 1\n\n// swift-tools-version:4.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"LinkedList\",\n    products: [\n        .library(name: \"LinkedList\", targets: [\"LinkedList\"])\n    ],\n    targets: [\n        .target(name: \"LinkedList\"),\n        .testTarget(name: \"LinkedListTests\", dependencies: [\"LinkedList\"]),\n    ],\n    swiftLanguageVersions: [.v3, .v4]\n)\n```\n\nOtherwise,\nthe server SHOULD respond with a status code of `303` (See Other)\nand redirect to the unqualified `Package.swift` resource.\n\n```http\nHTTP/1.1 303 See Other\nContent-Version: 1\nLocation: https://packages.example.com/mona/LinkedList/1.1.1/Package.swift\n```\n\n<a name=\"endpoint-4\"></a>\n\n#### 4.4. Download source archive\n\nA client MAY send a `GET` request\nfor a URI matching the expression `/{scope}/{name}/{version}.zip`\nto retrieve a release's source archive.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+zip`\nand MUST append the `.zip` extension to the requested path.\n\n```http\nGET /mona/LinkedList/1.1.1.zip HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+zip\n```\n\nIf a release is found at the requested location,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `application/zip`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\n```http\nHTTP/1.1 200 OK\nAccept-Ranges: bytes\nCache-Control: public, immutable\nContent-Type: application/zip\nContent-Disposition: attachment; filename=\"LinkedList-1.1.1.zip\"\nContent-Length: 2048\nContent-Version: 1\nDigest: sha-256=oqxUzyX7wa0AKPA/CqS5aDO4O7BaFOUQiSuyfepNyBI=\nLink: <https://mirror-japanwest.example.com/mona-LinkedList-1.1.1.zip>; rel=duplicate; geo=jp; pri=10; type=\"application/zip\"\nX-Swift-Package-Signature-Format: cms-1.0.0\nX-Swift-Package-Signature: l1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\n```\n\nA server MUST respond with a `Content-Length` header\nset to the size of the archive in bytes.\nA client SHOULD terminate any requests whose response exceeds\nthe expected content length.\n\nA server MAY respond with a `Digest` header\ncontaining a cryptographic digest of the source archive.\n\nA server SHOULD respond with a `Content-Disposition` header\nset to `attachment` with a `filename` parameter equal to the name of the package\nfollowed by a hyphen (`-`), the version number, and file extension\n(for example, \"LinkedList-1.1.1.zip\").\n\nA server MAY omit the `Content-Version` header\nsince the response content (i.e., the source archive) SHOULD NOT\nchange across different API versions.\n\nIt is RECOMMENDED for clients and servers to support\nrange requests as described by [RFC 7233]\nand caching as described by [RFC 7234].\n\nIf a release is signed, a server MUST include\n`X-Swift-Package-Signature-Format` and `X-Swift-Package-Signature`\nheaders in the response.\n\n##### 4.4.1. Integrity verification\n\nA client MUST verify the integrity of a downloaded source archive using\nthe `checksum` value for the associated `source-archive` resource\nin the response to `GET /{scope}/{name}/{version}`,\nas described in [4.2.1](<doc:#4.2.1.-Package-release-resources>).\n\nA client SHOULD also verify the integrity using any values\nprovided in the `Digest` header of the source archive response\n(for using the command\n`shasum -b -a 256 LinkedList-1.1.1.zip | cut -f1 | xxd -r -p | base64`).\n\n##### 4.4.2. Download locations\n\nA server MAY specify mirrors or multiple download locations\nusing `Link` header fields\nwith a `duplicate` relation,\nas described by [RFC 6249].\nA client MAY use this information\nto determine its preferred strategy for downloading.\n\nA server MAY respond with a status code of `303` (See Other)\nto redirect the client to download the source archive from another host.\nThe client MUST NOT follow redirects that downgrade to an insecure connection.\nThe client SHOULD limit the number of redirects to prevent a redirect loop.\n\nFor example,\na server redirects the client to download from\na content delivery network (CDN) using a signed URL:\n\n```http\nHTTP/1.1 303 See Other\nLocation: https://example.cdn.com/LinkedList-1.1.1.zip?key=XXXXXXXXXXXXXXXXX\n```\n\n```http\nGET /LinkedList-1.1.1.zip?key=XXXXXXXXXXXXXXXXX HTTP/1.1\nHost: example.cdn.com\nAccept: application/vnd.swift.registry.v1+zip\n```\n\n```http\nHTTP/1.1 200 OK\nAccept-Ranges: bytes\nCache-Control: public, immutable\nContent-Type: application/zip\nContent-Disposition: attachment; filename=\"LinkedList-1.1.1.zip\"\nContent-Length: 2048\nContent-Version: 1\nDigest: sha-256=a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\n```\n\n##### 4.4.3. Signature validation\n\nA client MUST validate the signature of a signed archive\naccording to the signature format and configuration. Signing\ninformation can alternatively be found in the associated\n`source-archive` resource in the response to `GET /{scope}/{name}/{version}`,\nas described in [4.2.1](<doc:#4.2.1.-Package-release-resources>).\n\n<a name=\"endpoint-5\"></a>\n\n#### 4.5. Lookup package identifiers registered for a URL\n\nA client MAY send a `GET` request\nfor a URI matching the expression `/identifiers?url={url}`\nto retrieve package identifiers associated with a particular URL.\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+json`.\n\n```http\nGET /identifiers?url=https://github.com/mona/LinkedList HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1\n```\n\nA client MUST provide a URL for the `url` query parameter.\nWhen no `url` parameter is specified,\na server SHOULD respond with a status code of `400` (Bad Request).\n\nIf one or more package identifiers are associated with the specified URL,\na server SHOULD respond with a status code of `200` (OK)\nand the `Content-Type` header `application/json`.\nOtherwise, a server SHOULD respond with a status code of `404` (Not Found).\n\nA server SHOULD respond with a JSON document\ncontaining the package identifiers for the specified URL.\n\n```http\nHTTP/1.1 200 OK\nContent-Type: application/json\nContent-Version: 1\n\n{\n    \"identifiers\": [\n      \"mona.LinkedList\"\n    ]\n}\n```\n\nThe response body MUST contain an array of package identifier strings\nnested at a top-level `identifiers` key.\n\nIt is RECOMMENDED for clients and servers to support\ncaching as described by [RFC 7234].\n\n##### 4.5.1 URL to package identifier mappings\n\nAs part of the [package release metadata](<doc:#4.2.2.-Package-release-metadata-standards>) JSON object, the `repositoryURLs` array can be used to specify URLs associated with a package identifier.\nThis is one way through which a server can obtain URL to package identifier mappings for this API.\n\nA server MAY choose other mechanism(s) for package authors to specify these mappings.\n\nA server SHOULD validate the package author's ownership claim on the corresponding repository.\n\n<a name=\"endpoint-6\"></a>\n\n#### 4.6. Create a package release\n\nA client MAY send a `PUT` request\nfor a URI matching the expression\n`/{scope}/{name}/{version}`\nto publish a release of a package.\nA client MUST provide a body encoded as multipart form data\nwith the following sections:\n\n| Key                        | Content-Type               | Description                               | Requirement Level |\n| -------------------------- | -------------------------- | ----------------------------------------- | ----------------- |\n| `source-archive`           | `application/zip`          | The source archive of the package.        | REQUIRED          |\n| `source-archive-signature` | `application/octet-stream` | The signature of the source archive.      | OPTIONAL          |\n| `metadata`                 | `application/json`         | Additional information about the release. | OPTIONAL          |\n| `metadata-signature`       | `application/octet-stream` | The signature of the metadata.            | OPTIONAL          |\n\nA client MUST set a `Content-Type` header with the value\n`multipart/form-data`. `boundary` can be any string.\n\nA client MAY use any valid value (e.g., `binary`) for the\n`Content-Transfer-Encoding` header.\n\nA client SHOULD set the `Content-Length` header with\nthe total size of the body in bytes.\n\nA client SHOULD set the `Accept` header with the value\n`application/vnd.swift.registry.v1+json`.\n\nA client MUST set a `X-Swift-Package-Signature-Format` header\nwith the signature format if the source archive is signed.\n\n```http\nPUT /mona/LinkedList/1.1.1 HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1+json\nContent-Type: multipart/form-data;boundary=\"boundary\"\nContent-Length: 336\nExpect: 100-continue\nX-Swift-Package-Signature-Format: cms-1.0.0\n\n--boundary\nContent-Disposition: form-data; name=\"source-archive\"\nContent-Type: application/zip\nContent-Length: 32\nContent-Transfer-Encoding: base64\n\ngHUFBgAAAAAAAAAAAAAAAAAAAAAAAA==\n\n--boundary\nContent-Disposition: form-data; name=\"source-archive-signature\"\nContent-Type: application/octet-stream\nContent-Length: 88\nContent-Transfer-Encoding: base64\n\nl1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\n\n--boundary\nContent-Disposition: form-data; name=\"metadata\"\nContent-Type: application/json\nContent-Transfer-Encoding: quoted-printable\nContent-Length: 3\n\n{ \"repositoryURLs\": [] }\n\n--boundary\nContent-Disposition: form-data; name=\"metadata-signature\"\nContent-Type: application/octet-stream\nContent-Length: 88\nContent-Transfer-Encoding: base64\n\nM6TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\n\n```\n\nA server SHOULD require a client to perform authentication\nfor any requests to create a package release.\nUse of multi-factor authentication is RECOMMENDED.\n\nA client MAY publish releases in any order.\nFor example,\nif a package has existing `1.0.0` and `2.0.0` releases,\na client MAY publish a new `1.0.1` or `1.1.0` release.\n\nOnce a release has been published,\nany resources associated with that release,\nincluding its source archive,\nMUST NOT change.\n\nIf a release already exists for a package at the specified version,\nthe server SHOULD respond with a status code of `409` (Conflict).\n\n```http\nHTTP/1.1 409 Conflict\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"a release with version 1.0.0 already exists\"\n}\n```\n\nIt is RECOMMENDED that a server institute policies\nfor publishing new releases of a package\nafter a scope is transferred to a new owner.\nFor example,\nthe next release of an existing package is published with a new major version,\nor only after a period of 45 days after transfer.\n\nIf the client provides an `Expect` header,\na server SHOULD check that the request can succeed\nbefore responding with a status code of `100 (Continue)`.\nA server that doesn't support expectations\nSHOULD respond with a status code of `417 (Expectation Failed)`.\nIn response,\na client MAY remove the `Expect` header and retry the request.\n\n```http\nHTTP/1.1 417 (Expectation Failed)\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"expectations aren't supported\"\n}\n```\n\nSupport for this endpoint is OPTIONAL.\nA server SHOULD indicate that publishing isn't supported\nby responding with a status code of `405` (Method Not Allowed).\n\n```http\nHTTP/1.1 405 (Method Not Allowed)\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"publishing isn't supported\"\n}\n```\n\nA server MAY respond either synchronously or asynchronously.\nFor more information,\nsee [4.6.3](<doc:#4.6.3.-Synchronous-and-asynchronous-publication>).\n\n##### 4.6.1. Source archive\n\nA client MUST include a multipart section named `source-archive`\ncontaining the source archive for a release.\nA client SHOULD set a `Content-Type` header with the value `application/zip`\nand a `Content-Length` header with the size of the Zip archive in bytes.\n\n```http\n--boundary\nContent-Disposition: form-data; name=\"source-archive\"\nContent-Type: application/zip\nContent-Length: 32\nContent-Transfer-Encoding: base64\n\ngHUFBgAAAAAAAAAAAAAAAAAAAAAAAA==\n```\n\nA client SHOULD use the `swift package archive-source` tool\nto create a source archive for the release.\n\nA server MAY analyze a package to\nassess its viability,\nperform security testing,\nor otherwise evaluate software quality.\nA server MAY refuse to publish a package release for any reason\nby responding with a status code of `422` (Unprocessable Entity).\n\n```http\nHTTP/1.1 422 Unprocessable Entity\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"package doesn't contain a valid manifest (Package.swift) file\"\n}\n```\n\nA server SHOULD use the `swift package compute-checksum` tool to compute the checksum that's provided in response to a client's subsequent request to [download the source archive](<doc:#4.4.-Download-source-archive>) for the release.\n\n##### 4.6.2. Package release metadata\n\nA client MAY include a multipart section named `metadata`\ncontaining additional information about the release.\nA client SHOULD set a `Content-Type` header with the value `application/json`\nand a `Content-Length` header with the size of the JSON document in bytes.\nThe package release metadata MUST be based on the [JSON schema](<doc:#Appendix-B---Package-Release-Metadata-JSON-Schema>),\nas discussed in [4.2.2](<doc:#4.2.2.-Package-release-metadata-standards>).\n\n```http\n--boundary\nContent-Disposition: form-data; name=\"metadata\"\nContent-Type: application/json\nContent-Length: 226\nContent-Transfer-Encoding: quoted-printable\n\n{\n  \"description\": \"One thing links to another.\",\n  \"repositoryURLs\": [\"https://github.com/mona/LinkedList\"],\n  \"licenseURL\": \"https://www.apache.org/licenses/LICENSE-2.0\",\n  \"author\": {\n      \"name\": \"Mona Lisa Octocat\"\n  }\n}\n\n```\n\nA server MAY allow and/or populate additional metadata for a release.\n\nA server MAY make any properties in the [JSON schema](<doc:#Appendix-B---Package-Release-Metadata-JSON-Schema>)\nand additional metadata it defines required.\n\nIf a client provides an invalid JSON document,\nthe server SHOULD respond with a status code of\n`422` (Unprocessable Entity) or `413` (Payload Too Large)\nand MAY communicate validation error details in the response body.\n\n```http\nHTTP/1.1 422 Unprocessable Entity\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\n\n{\n   \"detail\": \"invalid JSON provided for release metadata\"\n}\n```\n\n##### 4.6.3. Synchronous and asynchronous publication\n\nA server MAY respond to a request to publish a new package release\neither synchronously or asynchronously.\n\nA client MAY indicate their preference for asynchronous processing\nwith a `Prefer` header field containing the token `respond-async`\nand an optional `wait` preference,\nas described by [RFC 7240].\n\n```http\nPUT /mona/LinkedList/1.1.1 HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1\nPrefer: respond-async, wait=300\n```\n\n###### 4.6.3.1. Synchronous publication\n\nIf processing is done synchronously,\nthe server MUST respond with a status code of `201` (Created)\nto indicate that the package release was published.\nThis response SHOULD also contain\na `Location` header with a URL to the new release.\n\n```http\nHTTP/1.1 201 Created\nContent-Version: 1\nLocation: https://packages.example.com/github.com/mona/LinkedList/1.1.1\n```\n\nA client MAY set a timeout to guarantee a timely response to each request.\n\n###### 4.6.3.2. Asynchronous publication\n\nIf processing is done asynchronously,\nthe server MUST respond with a status code of `202` (Accepted)\nto acknowledge that the request is being processed.\nThis response MUST contain a `Location` header\nwith a URL that the client can poll for progress updates\nand SHOULD contain a `Retry-After` header\nwith an estimate of when processing is expected to finish.\nA server MAY locate the status resource endpoint at a URI of its choosing.\nHowever,\nthe use of a non-sequential, randomly-generated identifier is RECOMMENDED.\n\n```http\nHTTP/1.1 202 Accepted\nContent-Version: 1\nLocation: https://packages.example.com/submissions/90D8CC77-A576-47AE-A531-D6402C4E33BC\nRetry-After: 120\n```\n\nA client MAY send a `GET` request\nto the location provided by the server in response to a publish request\nto see the current status of that process.\n\n```http\nGET /submissions/90D8CC77-A576-47AE-A531-D6402C4E33BC HTTP/1.1\nHost: packages.example.com\nAccept: application/vnd.swift.registry.v1\n```\n\nIf the asynchronous publish request is still processing,\nthe server SHOULD respond with a status code of `202` (Accepted) and\na `Retry-After` header with an estimate of when processing should finish.\nA server MAY include additional details in the response body.\n\n```http\nHTTP/1.1 202 Accepted\nContent-Version: 1\nContent-Type: application/json\nRetry-After: 120\n\n{\n  \"status\": \"Processing (2/3 steps complete)\",\n  \"steps\": {\n    {\"name\": \"Validate metadata\", \"status\": \"complete\"},\n    {\"name\": \"Verify package manifest\", \"status\": \"complete\"},\n    {\"name\": \"Scan for vulnerabilities\", \"status\": \"pending\"}\n  }\n}\n```\n\nIf the asynchronous publish request is finished processing successfully,\nthe server SHOULD respond with a status code of `301` (Moved Permanently)\nand a `Location` header with a URL to the package release.\n\n```http\nHTTP/1.1 301 Moved Permanently\nContent-Version: 1\nLocation: https://packages.example.com/mona/LinkedList/1.1.1\n```\n\nIf the asynchronous publish request failed,\nthe server SHOULD respond with an appropriate client error status code (`4xx`).\n\n```http\nHTTP/1.1 400 Bad Request\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\nLocation: https://packages.example.com/submissions/90D8CC77-A576-47AE-A531-D6402C4E33BC\n\n{\n   \"detail\": \"invalid package\"\n}\n```\n\nA client MAY send a `DELETE` request\nto the location provided by the server in response to a publish request\nto cancel that process.\n\nIf a request to publish a new package release were to fail,\na server MUST communicate that failure in the same way\nif sending an immediate response\nas it would if responding to a client polling for status.\n\nIf a client makes a request to publish a package release\nto a server that is asynchronously processing a request to publish that release,\nthe server MUST respond with a status code of `409` (Conflict)\n\n```http\nHTTP/1.1 409 Conflict\nContent-Version: 1\nContent-Type: application/problem+json\nContent-Language: en\nLocation: https://packages.example.com/submissions/90D8CC77-A576-47AE-A531-D6402C4E33BC\n\n{\n   \"detail\": \"already processing a request to publish this package version\"\n}\n```\n\nIf a client makes a request to publish a package release\nto a server that finished processing a failed request to publish that release,\nthe server SHOULD try publishing that release again.\nA server MAY refuse to fulfill a subsequent request to publish a package release\nby responding with a status code of `409` (Conflict).\n\n### 5. Normative References\n\n* [RFC 2119]: Key words for use in RFCs to Indicate Requirement Levels\n* [RFC 3230]: Instance Digests in HTTP\n* [RFC 3986]: Uniform Resource Identifier (URI): Generic Syntax\n* [RFC 3987]: Internationalized Resource Identifiers (IRIs)\n* [RFC 5234]: Augmented BNF for Syntax Specifications: ABNF\n* [RFC 5843]: Additional Hash Algorithms for HTTP Instance Digests\n* [RFC 6249]: Metalink/HTTP: Mirrors and Hashes\n* [RFC 6570]: URI Template\n* [RFC 7159]: The JavaScript Object Notation (JSON) Data Interchange Format\n* [RFC 7230]: Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing\n* [RFC 7231]: Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content\n* [RFC 7233]: Hypertext Transfer Protocol (HTTP/1.1): Range Requests\n* [RFC 7234]: Hypertext Transfer Protocol (HTTP/1.1): Caching\n* [RFC 7240]: Prefer Header for HTTP\n* [RFC 7578]: Returning Values from Forms: multipart/form-data\n* [RFC 7807]: Problem Details for HTTP APIs\n* [RFC 8288]: Web Linking\n* [SemVer]: Semantic Versioning\n\n### 6. Informative References\n\n* [BCP 13] Media Type Specifications and Registration Procedures\n* [RFC 6749]: The OAuth 2.0 Authorization Framework\n* [RFC 8446]: The Transport Layer Security (TLS) Protocol Version 1.3\n* [RFC 8631]: Link Relation Types for Web Services\n* [JSON-LD]: A JSON-based Serialization for Linked Data\n* [Schema.org]: A shared vocabulary for structured data.\n* [OAS]: OpenAPI Specification\n\n### Appendix A - OpenAPI Document\n\nThe following [OpenAPI (v3) specification][OAS] is non-normative,\nand is provided for the convenience of\ndevelopers interested in building their own package registry.\n\nSee [registry.openapi.yaml](./registry.openapi.yaml).\n\n### Appendix B - Package Release Metadata JSON Schema\n\nThe `metadata` section of the [create package release request](<doc:#4.6.-Create-a-package-release>)\nmust be a JSON object of type [`PackageRelease`](<doc:#PackageRelease-type>), as defined in the\nJSON schema below.\n\n<details>\n\n<summary>Expand to view <a href=\"https://json-schema.org/specification.html\">JSON schema</a></summary>\n\n```json\n{\n  \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n  \"$id\": \"https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/PackageRegistry/Registry.md\",\n  \"title\": \"Package Release Metadata\",\n  \"description\": \"Metadata of a package release.\",\n  \"type\": \"object\",\n  \"properties\": {\n    \"author\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"name\": {\n          \"type\": \"string\",\n          \"description\": \"Name of the author.\"\n        },\n        \"email\": {\n          \"type\": \"string\",\n          \"format\": \"email\",\n          \"description\": \"Email address of the author.\"\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"description\": \"A description of the author.\"\n        },\n        \"organization\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"name\": {\n              \"type\": \"string\",\n              \"description\": \"Name of the organization.\"\n            },\n            \"email\": {\n              \"type\": \"string\",\n              \"format\": \"email\",\n              \"description\": \"Email address of the organization.\"\n            },\n            \"description\": {\n              \"type\": \"string\",\n              \"description\": \"A description of the organization.\"\n            },\n            \"url\": {\n              \"type\": \"string\",\n              \"format\": \"uri\",\n              \"description\": \"URL of the organization.\"\n            },\n          },\n          \"required\": [\"name\"]\n        },\n        \"url\": {\n          \"type\": \"string\",\n          \"format\": \"uri\",\n          \"description\": \"URL of the author.\"\n        },\n      },\n      \"required\": [\"name\"]\n    },\n    \"description\": {\n      \"type\": \"string\",\n      \"description\": \"A description of the package release.\"\n    },\n    \"licenseURL\": {\n      \"type\": \"string\",\n      \"format\": \"uri\",\n      \"description\": \"URL of the package release's license document.\"\n    },\n    \"originalPublicationTime\": {\n      \"type\": \"string\",\n      \"format\": \"date-time\",\n      \"description\": \"Original publication time of the package release in ISO 8601 format.\"\n    },\n    \"readmeURL\": {\n      \"type\": \"string\",\n      \"format\": \"uri\",\n      \"description\": \"URL of the README specifically for the package release or broadly for the package.\"\n    },\n    \"repositoryURLs\": {\n      \"type\": \"array\",\n      \"description\": \"Code repository URL(s) of the package release.\",\n      \"items\": {\n        \"type\": \"string\",\n        \"description\": \"Code repository URL.\"\n      }\n    }\n  }\n}\n```\n\n</details>\n\n###### PackageRelease type\n\n| Property                  | Type                | Description                                      | Required |\n| ------------------------- | :-----------------: | ------------------------------------------------ | :------: |\n| `author`                  | [Author](<doc:#Author-type>) | Author of the package release. | |\n| `description`             | String | A description of the package release. | |\n| `licenseURL`              | String | URL of the package release's license document. | |\n| `originalPublicationTime` | String | Original publication time of the package release in [ISO 8601] format. This can be set if the package release was previously published elsewhere.<br>A registry should record the publication time independently and include it as `publishedAt` in the [package release metadata response](<doc:#4.2.-Fetch-information-about-a-package-release>). <br>In case both `originalPublicationTime` and `publishedAt` are set, `originalPublicationTime` should be used. | |\n| `readmeURL`       | String | URL of the README specifically for the package release or broadly for the package. | |\n| `repositoryURLs`  | Array | Code repository URL(s) of the package. It is recommended to include all URL variations (e.g., SSH, HTTPS) for the same repository. This can be an empty array if the package does not have source control representation.<br/>Setting this property is one way through which a registry can obtain repository URL to package identifier mappings for the [\"lookup package identifiers registered for a URL\" API](<doc:#4.5.-Lookup-package-identifiers-registered-for-a-URL>). A registry may choose other mechanism(s) for package authors to specify such mappings. | |\n\n###### Author type\n\n| Property          | Type                | Description                                      | Required |\n| ----------------- | :-----------------: | ------------------------------------------------ | :------: |\n| `name`            | String | Name of the author. | ✓ |\n| `email`           | String | Email address of the author. | |\n| `description`     | String | A description of the author. | |\n| `organization`    | [Organization](<doc:#Organization-type>) | Organization that the author belongs to. | |\n| `url`             | String | URL of the author. | |\n\n###### Organization type\n\n| Property          | Type                | Description                                      | Required |\n| ----------------- | :-----------------: | ------------------------------------------------ | :------: |\n| `name`            | String | Name of the organization. | ✓ |\n| `email`           | String | Email address of the organization. | |\n| `description`     | String | A description of the organization. | |\n| `url`             | String | URL of the organization. | |\n\n[UAX18]: https://unicode.org/reports/tr18/\n[BCP 13]: https://tools.ietf.org/html/rfc6838 \"Media Type Specifications and Registration Procedures\"\n[RFC 2119]: https://tools.ietf.org/html/rfc2119 \"Key words for use in RFCs to Indicate Requirement Levels\"\n[RFC 3230]: https://tools.ietf.org/html/rfc5843 \"Instance Digests in HTTP\"\n[RFC 3986]: https://tools.ietf.org/html/rfc3986 \"Uniform Resource Identifier (URI): Generic Syntax\"\n[RFC 3987]: https://tools.ietf.org/html/rfc3987 \"Internationalized Resource Identifiers (IRIs)\"\n[RFC 5234]: https://tools.ietf.org/html/rfc5234 \"Augmented BNF for Syntax Specifications: ABNF\"\n[RFC 5843]: https://tools.ietf.org/html/rfc5843 \"Additional Hash Algorithms for HTTP Instance Digests\"\n[RFC 6249]: https://tools.ietf.org/html/rfc6249 \"Metalink/HTTP: Mirrors and Hashes\"\n[RFC 6570]: https://tools.ietf.org/html/rfc6570 \"URI Template\"\n[RFC 6749]: https://tools.ietf.org/html/rfc6749 \"The OAuth 2.0 Authorization Framework\"\n[RFC 7159]: https://tools.ietf.org/html/rfc7159 \"The JavaScript Object Notation (JSON) Data Interchange Format\"\n[RFC 7230]: https://tools.ietf.org/html/rfc7230 \"Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing\"\n[RFC 7231]: https://tools.ietf.org/html/rfc7231 \"Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content\"\n[RFC 7233]: https://tools.ietf.org/html/rfc7233 \"Hypertext Transfer Protocol (HTTP/1.1): Range Requests\"\n[RFC 7234]: https://tools.ietf.org/html/rfc7234 \"Hypertext Transfer Protocol (HTTP/1.1): Caching\"\n[RFC 7240]: https://tools.ietf.org/html/rfc7240 \"Prefer Header for HTTP\"\n[RFC 7578]: https://tools.ietf.org/html/rfc7578 \"Returning Values from Forms: multipart/form-data\"\n[RFC 7807]: https://tools.ietf.org/html/rfc7807 \"Problem Details for HTTP APIs\"\n[RFC 8288]: https://tools.ietf.org/html/rfc8288 \"Web Linking\"\n[RFC 8446]: https://tools.ietf.org/html/rfc8446 \"The Transport Layer Security (TLS) Protocol Version 1.3\"\n[RFC 8631]: https://tools.ietf.org/html/rfc8631 \"Link Relation Types for Web Services\"\n[IANA Link Relations]: https://www.iana.org/assignments/link-relations/link-relations.xhtml\n[JSON-LD]: https://w3c.github.io/json-ld-syntax/ \"JSON-LD 1.1: A JSON-based Serialization for Linked Data\"\n[SemVer]: https://semver.org/ \"Semantic Versioning\"\n[Schema.org]: https://schema.org/\n[SoftwareSourceCode]: https://schema.org/SoftwareSourceCode\n[DUST]: https://doi.org/10.1145/1462148.1462151 \"Bar-Yossef, Ziv, et al. Do Not Crawl in the DUST: Different URLs with Similar Text. Association for Computing Machinery, 17 Jan. 2009. January 2009\"\n[OAS]: https://swagger.io/specification/ \"OpenAPI Specification\"\n[GitHub / Swift Package Management Service]: https://forums.swift.org/t/github-swift-package-management-service/30406\n[RubyGems]: https://rubygems.org \"RubyGems: The Ruby community’s gem hosting service\"\n[PyPI]: https://pypi.org \"PyPI: The Python Package Index\"\n[npm]: https://www.npmjs.com \"The npm Registry\"\n[crates.io]: https://crates.io \"crates.io: The Rust community’s crate registry\"\n[CocoaPods]: https://cocoapods.org \"A dependency manager for Swift and Objective-C Cocoa projects\"\n[thundering herd effect]: https://en.wikipedia.org/wiki/Thundering_herd_problem \"Thundering herd problem\"\n[offline cache]: https://yarnpkg.com/features/offline-cache \"Offline Cache | Yarn - Package Manager\"\n[XCFramework]: https://developer.apple.com/videos/play/wwdc2019/416/ \"WWDC 2019 Session 416: Binary Frameworks in Swift\"\n[SE-0272]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0272-swiftpm-binary-dependencies.md \"Package Manager Binary Dependencies\"\n[Swift tools version]: https://github.com/swiftlang/swift-package-manager/blob/9b9bed7eaf0f38eeccd0d8ca06ae08f6689d1c3f/Documentation/Usage.md#swift-tools-version-specification \"Swift Tools Version Specification\"\n[ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html \"ISO 8601 Date and Time Format\"\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/ReleasingPublishingAPackage.md",
    "content": "# Releasing and publishing a Swift package\n\nShare a specific version of your package.\n\n## Overview\n\nSwift Package Manager expects a package to be remotely shared as a single Git repository, with a tag that conforms to a full semantic version, and a `Package.swift` manifest in the root of the repository.\n\n<!-- TODO: need a reference to sharing a dependency through a swift registry -->\n\nTo publish a package that is hosted in a Git repository, create and push a semantic version tag.\nSwift package manager expects the tag to be a full semantic version, that includes major, minor, and patch versions in the tag.\n\nThe following commands illustrate adding a tag `1.0.0` and pushing those tags to the remote repository:\n\n```bash\n$ git tag 1.0.0\n$ git push origin --tags\n```\n\n> Warning: A tag in the form of `1.0` isn't recognized by Swift Package Manager as a complete semantic version.\n> Include all three integers reflecting the major, minor, and patch version information.\n\nWith the tag in place, other packages can depend on the package you tagged through your source repository.\nAn example of a published package can be found at [github.com/apple/example-package-playingcard](https://github.com/apple/example-package-playingcard/) with multiple releases available.\n\nTo read more about adding a dependency to your package, read <doc:AddingDependencies>.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/ResolvingPackageVersions.md",
    "content": "# Resolving and updating dependencies\n\nCoordinate and constrain dependencies for your package.\n\n## Overview\n\nThe package manager records the result of dependency resolution in a file named `Package.resolved` at the top-level of the package.\nWhen this file is present and you are resolving dependencies for the top-level (leaf) package of a dependency tree, the package manager uses the `Package.resolved` file as a cache of versions of the dependencies.\nThe Package.resolved file does not pin dependency versions for packages used as libraries, or are otherwise included as a dependency for another Swift project.\nIf the package is being resolved as a dependency from another package, its own `Package.resolved` file is ignored during that resolution.\n\nMost SwiftPM commands implicitly invoke dependency resolution before running, and cancel with an error if dependencies cannot be resolved.\n\n### Resolving Dependencies\n\nRun <doc:PackageResolve> to resolve the dependencies, taking into account the current version constraints in the `Package.swift` manifest and a `Package.resolved` resolved versions file.\nFor packages with a `Package.resolved` file, the `resolve` command resolves to those versions as long as they are still eligible.\nIf you want to explicitly use the dependencies written into `Package.resolved`, use the `--force-resolved-versions` when invoking `swift resolve`.\nFor example, to force the dependencies to align with the versions defined in `Package.resolved`, use:\n\n```bash\nswift package resolve --force-resolved-versions\n```\n\nIf the resolved version's file changes (for example, because a teammate shared an update through source control), the next `resolve` command attempts to update the package dependencies to match that file.\nIn most cases, the resolve command performs no changes unless the `Package.swift` manifest or `Package.resolved` file has changed.\n\n### Updating the dependencies\n\nRun <doc:PackageUpdate> to update a package's dependencies to the latest eligible versions, which also updates the `Package.resolved` file.\n\n### Coordinating versions of dependencies for your package\n\nYou can use `Package.resolved` to coordinate the versions of dependencies it uses for a leaf Swift project - one that isn't being used as a dependency.\nFor example, you can keep a `Package.resolved` file in source control, or resolve it locally and pass it to a container image build process, in order to ensure another build uses the same versions of dependencies.\n\nThe `Package.resolved` only helps to resolve dependencies to the specific versions it defines for leaf projects.\nIt does not provide any dependency pinning for libraries or packages that are used as dependencies for other Swift projects.\nFor example, if your package presents a library and has `Package.resolved` checked in, those versions are ignored by the package that depends on your library, and the latest eligible versions are chosen.\nFor more information on constraining dependency versions, see <doc:AddingDependencies>.\n\nIf a `Package.resolved` doesn't exist, each user or build system separately resolves dependency versions, only updating when they run <doc:PackageUpdate>, and new users start with the latest eligible version of each dependency.\nIf the `Package.resolved` file does exist, any command that requires dependencies (for example, <doc:SwiftBuild> or <doc:SwiftRun>) attempts to resolve the versions of dependencies recorded in the file.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SDK/SDKConfigurationReset.md",
    "content": "# swift sdk configuration reset\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.1\")\n}\n\nResets configuration properties currently applied to a given Swift SDK and target triple. If no specific property is specified, all of them are reset for the Swift SDK.\n\n```\nsdk configuration reset [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...] [--sdk-root-path]\n  [--swift-resources-path] [--swift-static-resources-path]\n  [--include-search-path] [--library-search-path]\n  [--toolset-path] <sdk-id> <target-triple> [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--sdk-root-path**:\n\n*Reset custom configuration for a path to a directory containing the SDK root.*\n\n\n- term **--swift-resources-path**:\n\n*Reset custom configuration for a path to a directory containing Swift resources for dynamic linking.*\n\n\n- term **--swift-static-resources-path**:\n\n*Reset custom configuration for a path to a directory containing Swift resources for static linking.*\n\n\n- term **--include-search-path**:\n\n*Reset custom configuration for a path to a directory containing headers.*\n\n\n- term **--library-search-path**:\n\n*Reset custom configuration for a path to a directory containing libraries.*\n\n\n- term **--toolset-path**:\n\n*Reset custom configuration for a path to a toolset file.*\n\n\n- term **sdk-id**:\n\n*An identifier of an already installed Swift SDK. Use the `list` subcommand to see all available identifiers.*\n\n\n- term **target-triple**:\n\n*A target triple of the Swift SDK specified by `sdk-id` identifier string.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SDK/SDKConfigurationSet.md",
    "content": "# swift sdk configuration set\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.1\")\n}\n\nSets configuration options for installed Swift SDKs.\n\n```\nsdk configuration set [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--sdk-root-path=<sdk-root-path>]\n  [--swift-resources-path=<swift-resources-path>]\n  [--swift-static-resources-path=<swift-static-resources-path>]\n  [--include-search-path=<include-search-path>...]\n  [--library-search-path=<library-search-path>...]\n  [--toolset-path=<toolset-path>...] <sdk-id> <target-triple>\n  [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--sdk-root-path=\\<sdk-root-path\\>**:\n\n*A path to a directory containing the SDK root.*\n\n\n- term **--swift-resources-path=\\<swift-resources-path\\>**:\n\n*A path to a directory containing Swift resources for dynamic linking.*\n\n\n- term **--swift-static-resources-path=\\<swift-static-resources-path\\>**:\n\n*A path to a directory containing Swift resources for static linking.*\n\n\n- term **--include-search-path=\\<include-search-path\\>**:\n\n*A path to a directory containing headers. Multiple paths can be specified by providing this option multiple times to the command.*\n\n\n- term **--library-search-path=\\<library-search-path\\>**:\n\n*\"A path to a directory containing libraries. Multiple paths can be specified by providing this option multiple times to the command.*\n\n\n- term **--toolset-path=\\<toolset-path\\>**:\n\n*\"A path to a toolset file. Multiple paths can be specified by providing this option multiple times to the command.*\n\n\n- term **sdk-id**:\n\n*An identifier of an already installed Swift SDK. Use the `list` subcommand to see all available identifiers.*\n\n\n- term **target-triple**:\n\n*The target triple of the Swift SDK to configure.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SDK/SDKConfigurationShow.md",
    "content": "# swift sdk configuration show\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.1\")\n}\n\nPrints all configuration properties currently applied to a given Swift SDK and target triple.\n\n```\nsdk configuration show [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...] <sdk-id>\n  <target-triple> [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **sdk-id**:\n\n*An identifier of an already installed Swift SDK. Use the `list` subcommand to see all available identifiers.*\n\n\n- term **target-triple**:\n\n*The target triple of the Swift SDK to configure.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SDK/SDKConfigure.md",
    "content": "# swift sdk configure\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.1\")\n}\n\nManages configuration options for installed Swift SDKs.\n\n```\nsdk configure [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--sdk-root-path=<sdk-root-path>]\n  [--swift-resources-path=<swift-resources-path>]\n  [--swift-static-resources-path=<swift-static-resources-path>]\n  [--include-search-path=<include-search-path>...]\n  [--library-search-path=<library-search-path>...]\n  [--toolset-path=<toolset-path>...] [--reset]\n  [--show-configuration] <sdk-id> [target-triple...] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--sdk-root-path=\\<sdk-root-path\\>**:\n\n*A path to a directory containing the SDK root.*\n\n\n- term **--swift-resources-path=\\<swift-resources-path\\>**:\n\n*A path to a directory containing Swift resources for dynamic linking.*\n\n\n- term **--swift-static-resources-path=\\<swift-static-resources-path\\>**:\n\n*A path to a directory containing Swift resources for static linking.*\n\n\n- term **--include-search-path=\\<include-search-path\\>**:\n\n*A path to a directory containing headers. Multiple paths can be specified by providing this option multiple times to the command.*\n\n\n- term **--library-search-path=\\<library-search-path\\>**:\n\n*\"A path to a directory containing libraries. Multiple paths can be specified by providing this option multiple times to the command.*\n\n\n- term **--toolset-path=\\<toolset-path\\>**:\n\n*\"A path to a toolset file. Multiple paths can be specified by providing this option multiple times to the command.*\n\n\n- term **--reset**:\n\n*Resets configuration properties currently applied to a given Swift SDK and target triple. If no specific property is specified, all of them are reset for the Swift SDK.*\n\n\n- term **--show-configuration**:\n\n*Prints all configuration properties currently applied to a given Swift SDK and target triple.*\n\n\n- term **sdk-id**:\n\n*An identifier of an already installed Swift SDK. Use the `list` subcommand to see all available identifiers.*\n\n\n- term **target-triple**:\n\n*The target triple of the Swift SDK to configure.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SDK/SDKInstall.md",
    "content": "# swift sdk install\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.1\")\n}\n\nInstalls a given Swift SDK bundle to a location discoverable by SwiftPM.\n\nIf the artifact bundle is at a remote location, it's downloaded to local filesystem first.\n\n```\nsdk install [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  <bundle-path-or-url> [--checksum=<checksum>]\n  [--color-diagnostics] [--no-color-diagnostics] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **bundle-path-or-url**:\n\n*A local filesystem path or a URL of a Swift SDK bundle to install.*\n\n\n- term **--checksum=\\<checksum\\>**:\n\n*The checksum of the bundle generated with `swift package compute-checksum`.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SDK/SDKList.md",
    "content": "# swift sdk list\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.1\")\n}\n\nPrint a list of IDs of available Swift SDKs available on the filesystem.\n\n```\nsdk list [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...] [--version]\n  [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SDK/SDKRemove.md",
    "content": "# swift sdk remove\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.1\")\n}\n\nRemoves a previously installed Swift SDK bundle from the filesystem.\n\n```\nsdk remove [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  <sdk-id-or-bundle-name> [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **sdk-id-or-bundle-name**:\n\n*Name of the Swift SDK bundle or ID of the Swift SDK to remove from the filesystem.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SettingSwiftToolsVersion.md",
    "content": "# Setting the Swift tools version\n\nDefine the minimum version of the swift compiler required for your package.\n\n## Overview\n\nThe tools version declares the minimum version of the Swift compiler required to\nuse the package, as well as how parse the `Package.swift` manifest.\nWhen you create a new package using <doc:PackageInit>, the minimum version is set automatically to the current version.\nThe version is specified on the first line of the manifest with the comment `// swift-tools-version:` and the version for the Swift compiler.\nThe version is a semantic version, with the exception that a patch version is inferred to be `0` if you don't specify it.\n\nFor example, the following line asserts the package requires the Swift compiler version 6.1 or later:\n\n```swift\n// swift-tools-version:6.1\n```\n\n### Resolving dependencies with different tools versions\n\nWhen resolving package dependencies, if the tools version of a dependency is greater than the version in use, that version of the dependency is ineligible and dependency resolution continues with evaluating the next-best version.\n\nIf no tools version of a dependency, which otherwise meets the package version requirements, supports the version of the Swift tools in use, the package manager presents a dependency resolution error.\nFor more information on providing package manifests for specific Swift versions, see <doc:SwiftVersionSpecificPackaging>.\n\n### Adjusting the tools version.\n\nEdit the `Package.swift` to adjust the version, or use <doc:PackageToolsVersion> to report or set the the tools version.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftBuild.md",
    "content": "# swift build\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\n<!-- Generated by swift-argument-parser -->\n\nBuild sources into binary products.\n\n```\nbuild [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache|disable-dependency-cache]\n  [--enable-build-manifest-caching|disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts|disable-experimental-prebuilts]\n  [--verbose] [--very-verbose|vv] [--quiet]\n  [--color-diagnostics|no-color-diagnostics]\n  [--disable-sandbox] [--netrc]\n  [--enable-netrc|disable-netrc] [--netrc-file=<netrc-file>]\n  [--enable-keychain|disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation|disable-signature-validation]\n  [--enable-prefetching|disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm] \n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>]\n  [--toolchain=<toolchain>] [--swift-sdk=<swift-sdk>]\n  [--sanitize=<sanitize>...]\n  [--auto-index-store|enable-index-store|disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip|disable-dead-strip]\n  [--disable-local-rpath] [--build-tests]\n  [--enable-code-coverage|disable-code-coverage]\n  [--show-bin-path] [--print-manifest-job-graph]\n  [--print-pif-manifest-graph] [--target=<target>]\n  [--product=<product>] [--enable-xctest|disable-xctest]\n  [--enable-swift-testing|disable-swift-testing]\n  [--traits=<traits>] [--enable-all-traits]\n  [--disable-default-traits]\n  [--static-swift-stdlib|no-static-swift-stdlib]\n  [--sbom-spec=<sbom-spec>...] [--sbom-output-dir=<sbom-output-dir>]\n  [--sbom-filter=<sbom-filter>] [--sbom-warning-only]\n  [--version] [--help]\n```\n\nSEE ALSO: <doc:SwiftRun>, <doc:SwiftPackageCommands>, <doc:SwiftTest>\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--build-tests**:\n\n*Build both source and test targets.*\n\n\n- term **--enable-code-coverage|disable-code-coverage**:\n\n*Enable code coverage.*\n\n\n- term **--show-bin-path**:\n\n*Print the binary output path.*\n\n\n- term **--print-manifest-job-graph**:\n\n*Write the command graph for the build manifest as a Graphviz file.*\n\n\n- term **--print-pif-manifest-graph**:\n\n*Write the PIF JSON sent to Swift Build as a Graphviz file.*\n\n\n- term **--target=\\<target\\>**:\n\n*Build the specified target.*\n\n\n- term **--product=\\<product\\>**:\n\n*Build the specified product.*\n\n\n- term **--enable-xctest|disable-xctest**:\n\n*Enable support for XCTest.*\n\n\n- term **--enable-swift-testing|disable-swift-testing**:\n\n*Enable support for Swift Testing.*\n\n\n- term **--traits=\\<traits\\>**:\n\n*Enables the passed traits of the package. Multiple traits can be specified by providing a comma separated list e.g. `--traits Trait1,Trait2`. When enabling specific traits the defaults traits need to explictily enabled as well by passing `defaults` to this command.*\n\n\n- term **--enable-all-traits**:\n\n*Enables all traits of the package.*\n\n\n- term **--disable-default-traits**:\n\n*Disables all default traits of the package.*\n\n\n- term **--static-swift-stdlib|no-static-swift-stdlib**:\n\n*Link Swift stdlib statically.*\n\n- term **--sbom-spec=\\<sbom-spec\\>**:\n\n*Set the SBOM specification(s) and generate SBOM(s).*\n\n\n- term **--sbom-output-dir=\\<sbom-output-dir\\>**:\n\n*The absolute or relative directory path to generate the SBOM(s) in. Must be used with --sbom-spec. (default: <scratch_path>/sboms).*\n\n\n- term **--sbom-filter=\\<sbom-filter\\>**:\n\n*Filter the SBOM components and dependencies by products and/or packages. Must be used with --sbom-spec.*\n\n\n- term **--sbom-warning-only**:\n\n*Treat SBOM generation errors as warnings. Must be used with --sbom-spec. (default: false).*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n## build.help\n\nShow subcommand help information.\n\n```\nbuild help [<subcommands>...] \n```\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftBuildPreview.md",
    "content": "# [6.3] Preview the Swift Build System Integration\n\nUnderstand, use, and preview the next-generation build system for Package Manager.\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"6.3\")\n}\n\n## Overview\n\nSwift Package Manager is previewing a new build system [Swift Build](https://github.com/swiftlang/swift-build) as a replacement for the current native build system. This document outlines the current state of the preview, key differences, and known issues.\n\n\nWe encourage you to [try](#How-to-use-the-Swift-Build-build-system) the new build system in your project and [report any issues](#Reporting-issues) you encounter.\n\nFor more information about the migration to Swift Build, see [this forum post](https://forums.swift.org/t/evolving-swiftpm-builds-with-swift-build/77596).\n\n## Migration plan\n\nThe Swift Build integration follows these phases:\n\n1. **Preview Phase** (Current) - Testing and feedback collection\n2. **Feature Parity** - Address remaining gaps and platform issues\n3. **Default Migration** - Transition to Swift Build as default\n4. **Legacy Build System Deprecation** - Phase out `native` and `xcode` build systems\n\n## How to use the Swift Build build system\n\nTo participate in the preview, run your Swift Package Manager commands with the `--build-system swiftbuild` flag:\n\n```bash\nswift build --build-system swiftbuild\nswift test --build-system swiftbuild\nswift run --build-system swiftbuild\n```\n\n## Key improvements and differences\n\n\n- **`--static-swift-stdlib`**: Stricter validation (errors instead of silently ignoring)\n  - The native build system silently ignored this option on some platforms; Swift Build now produces an error.\n  - The Swift Build build system will generate an error on Windows until static libraries are supported. See [Upcoming changes to Windows Swift SDKs](https://forums.swift.org/t/upcoming-changes-to-windows-swift-sdks/81313).\n\n### Detailed differences\n\n#### Resource support parity with xcodebuild\n- When targeting Apple platforms using `--build-system swiftbuild`, SwiftPM now consistently applies the same set of resource rules as xcodebuild when a package contains resource types like asset catalogs, storyboards, Metal sources, etc.\n\n#### Swift Driver integration\n- The `--use-integrated-swift-driver` command-line option is considered deprecated. `--build-system swiftbuild` always uses the library-based Swift driver.\n- On supported platforms, `--build-system swiftbuild` will make use of explicitly-built Clang and Swift modules.\n\n#### Enhanced diagnostics\n- Logging and diagnostic differences between native and Swift Build build systems\n\n#### Other\n\n- When targeting Apple platforms, `--build-system swiftbuild` supports building universal binaries. Example invocation: `swift build --build-system swiftbuild --arch arm64 --arch x86_64`\n- The Swift Build build system outputs build artifacts to a different location.  Use the `swift build --show-bin-path <other build arguments>` to determine the build output location.\n\n## Known issues\n\n\n### Windows platform\n- Swift Build does not support CodeView debug information format.\n  - **Tracking**: [swiftlang/swift-package-manager#9302](https://github.com/swiftlang/swift-package-manager/issues/9302)\n  - **Impact**: Limited debugging capabilities on Windows.\n\n### Linux platform\n- Coverage reporting issues on some Linux platforms\n  - **Tracking**: [swiftlang/swift-package-manager#9600](https://github.com/swiftlang/swift-package-manager/issues/9600)\n\n### Feature gaps\n\n- The `swift run --repl` command may fail to import some modules.\n  - **Tracking**: [swiftlang/swift-package-manager#8846](https://github.com/swiftlang/swift-package-manager/issues/8846)\n\n- Swift Build does not provide sanitizer support for `scudo` and `fuzzer`.\n  - **Tracking**: [swiftlang/swift-package-manager#9448](https://github.com/swiftlang/swift-package-manager/issues/9448)\n  - **Impact**: Limited testing and debugging capabilities.\n\n- Swift Build does not support the `--enable-parseable-module-interfaces` option.\n  - **Tracking**: [swiftlang/swift-package-manager#9324](https://github.com/swiftlang/swift-package-manager/issues/9324)\n\n- Test execution with coverage may fail on certain platforms.\n  - **Tracking**: [swiftlang/swift-package-manager#9588](https://github.com/swiftlang/swift-package-manager/issues/9588)\n\n- Swift SDK's and toolset.json files aren't working for the most part. The webassembly SDK is ready to use.\n  - **Tracking**: [swiftlang/swift-package-manager#9346](https://github.com/swiftlang/swift-package-manager/issues/9346)\n\n- Swift Build does not support test targets depending on other test targets.\n  - **Workaround**: Create a non-test target for the test target to depend on.\n  - **Tracking**: [swiftlang/swift-package-manager#9458](https://github.com/swiftlang/swift-package-manager/issues/9458)\n\n- Expected `native` build failure in `release` configuration may not fail with Swift Build\n  - **Tracking**: [swiftlang/swift-package-manager#8984](https://github.com/swiftlang/swift-package-manager/issues/8984)\n\n- Swift Build does not support the `--explicit-target-dependency-import-check` flag.\n  - **Tracking**: [swiftlang/swift-package-manager#9620](https://github.com/swiftlang/swift-package-manager/issues/9620)\n\n- Swift Build does not pass environment variables to plugin tools.\n  - **Tracking**: [swiftlang/swift-package-manager#9122](https://github.com/swiftlang/swift-package-manager/issues/9122)\n\n- Swift Build does not support overlapping executable product names and library product names (case-insensitive).\n  - **Tracking**: [swiftlang/swift-package-manager#9184](https://github.com/swiftlang/swift-package-manager/issues/9184)\n\n## Reporting issues\n\nPlease follow these steps when reporting issues:\n\n1. Review the [known issues](#Known-issues) listed above to ensure your issue has not already been identified.\n2. If your issue is not listed, [submit a new issue](https://github.com/swiftlang/swift-package-manager/issues) on GitHub.\n3. Include the following information in your report:\n   - The exact command that failed\n   - Complete error output\n   - System information (operating system, Swift version, etc.)\n   - Whether the same command works with the native build system\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftPMAsALibrary.md",
    "content": "# Swift Package Manager as a library\n\nInclude Swift Package Manager as a dependency in your Swift package.\n\n## Overview\n\n> Warning: **The libSwiftPM API is _unstable_ and may change at any time.**\n\nSwift Package Manager has a library based architecture and the top-level library product is called `libSwiftPM`.\nOther packages can add SwiftPM as a package dependency and create powerful custom build tools on top of `libSwiftPM`.\n\nA subset of `libSwiftPM` that includes only the data model (without the package manager's build system) is available as `libSwiftPMDataModel`.\nAny one client should depend on one or the other, but not both.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftPackageCollectionCommands.md",
    "content": "# swift package-collection\n\nInteract with package collections.\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\n## Overview\n\nOverview of package manager commands here...\n\n<!-- reference content for the CLI commands `swift package ...` -->\n\n## Topics \n\n### Adding a package collection\n- <doc:PackageCollectionAdd>\n\n### Finding package collections\n- <doc:PackageCollectionSearch>\n\n### Updating package collection\n- <doc:PackageCollectionRefresh>\n\n### Inspecting package collections\n- <doc:PackageCollectionList>\n- <doc:PackageCollectionDescribe>\n\n### Removing a package collection\n- <doc:PackageCollectionRemove>\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftPackageCommands.md",
    "content": "# swift package\n\nSubcommands to update and inspect your Swift package.\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\n## Overview\n\nOverview of package manager commands here...\n\n<!-- reference content for the CLI commands `swift package ...` -->\n\n## Topics \n\n### Creating packages\n- <doc:PackageInit>\n\n### Updating and resolving dependencies\n- <doc:PackageUpdate>\n- <doc:PackageResolve>\n\n### Editing packages\n- <doc:PackageAddDependency>\n- <doc:PackageAddProduct>\n- <doc:PackageAddTarget>\n- <doc:PackageAddTargetDependency>\n- <doc:PackageAddSetting>\n- <doc:PackageEdit>\n- <doc:PackageUnedit>\n- <doc:PackageMigrate>\n\n### Using package manager plugins\n- <doc:PackagePlugin>\n- <doc:PackageDiagnoseAPIBreakingChange>\n<!-- ref to swift-format -->\n<!-- ref to swift-docc-plugin -->\n\n### Inspecting packages\n- <doc:PackageDescribe>\n- <doc:PackageShowDependencies>\n- <doc:PackageShowExecutables>\n- <doc:PackageShowTraits>\n- <doc:PackageToolsVersion>\n- <doc:PackageDumpPackage>\n- <doc:PackageDumpSymbolGraph>\n\n### Cleaning builds and caches\n- <doc:PackageClean>\n- <doc:PackageReset>\n- <doc:PackagePurgeCache>\n\n### Archiving packages\n- <doc:PackageArchiveSource>\n- <doc:PackageComputeChecksum>\n\n### Integrating Package Manager into your shell\n- <doc:PackageCompletionTool>\n\n### Configuring Mirrors\n- <doc:PackageConfigSetMirror>\n- <doc:PackageConfigUnsetMirror>\n- <doc:PackageConfigGetMirror>\n\n### Generating SBOMs\n- <doc:PackageGenerateSBOM>\n\n### Experimental commands\n- <doc:PackageExperimentalInstall>\n- <doc:PackageExperimentalUninstall>\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftPackageRegistryCommands.md",
    "content": "# swift package-registry\n\nInteract with package registry and manage related configuration.\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"5.9\")\n}\n\n## Overview\n\nOverview of package manager commands here...\n\n<!-- reference content for the CLI commands `swift package-registry ...` -->\n\n## Topics \n\n### Adding and Removing Registries\n- <doc:PackageRegistrySet>\n- <doc:PackageRegistryUnset>\n\n### Accessing Registries\n- <doc:PackageRegistryLogin>\n- <doc:PackageRegistryPublish>\n- <doc:PackageRegistryLogout>\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftRun.md",
    "content": "# swift run\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\n<!-- Generated by swift-argument-parser -->\n\nBuild and run an executable product.\n\n```\nrun [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache|disable-dependency-cache]\n  [--enable-build-manifest-caching|disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts|disable-experimental-prebuilts]\n  [--verbose] [--very-verbose|vv] [--quiet]\n  [--color-diagnostics|no-color-diagnostics]\n  [--disable-sandbox] [--netrc]\n  [--enable-netrc|disable-netrc] [--netrc-file=<netrc-file>]\n  [--enable-keychain|disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation|disable-signature-validation]\n  [--enable-prefetching|disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]\n  [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...]\n  [--auto-index-store|enable-index-store|disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip|disable-dead-strip]\n  [--disable-local-rpath] [--repl] [--debugger] [--run]\n  [--skip-build] [--build-tests] [<executable>]\n  [--traits=<traits>] [--enable-all-traits]\n  [--disable-default-traits] [<arguments>...] [--version]\n  [--help]\n```\n\nSEE ALSO: <doc:SwiftBuild>, <doc:SwiftPackageCommands>, <doc:SwiftTest>\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--repl**:\n\n*Launch Swift REPL for the package.*\n\n\n- term **--debugger**:\n\n*Launch the executable in a debugger session.*\n\n\n- term **--run**:\n\n*Launch the executable with the provided arguments.*\n\n\n- term **--skip-build**:\n\n*Skip building the executable product.*\n\n\n- term **--build-tests**:\n\n*Build both source and test targets.*\n\n\n- term **executable**:\n\n*The executable to run.*\n\n\n- term **--traits=\\<traits\\>**:\n\n*Enables the passed traits of the package. Multiple traits can be specified by providing a comma separated list e.g. `--traits Trait1,Trait2`. When enabling specific traits the defaults traits need to explictily enabled as well by passing `defaults` to this command.*\n\n\n- term **--enable-all-traits**:\n\n*Enables all traits of the package.*\n\n\n- term **--disable-default-traits**:\n\n*Disables all default traits of the package.*\n\n\n- term **arguments**:\n\n*The arguments to pass to the executable.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n## run.help\n\nShow subcommand help information.\n\n```\nrun help [<subcommands>...] \n```\n\n- term **subcommands:**\n\n\n\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftSDKCommands.md",
    "content": "# swift sdk\n\nPerform operations on Swift SDKs.\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n    @Available(\"Swift\", introduced: \"6.1\")\n}\n\n## Overview\n\nBy default, Swift Package Manager compiles code for the host platform on which you run it.\nSwift 6.1 introduced SDKs (through\n[SE-0387](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0387-cross-compilation-destinations.md))\nto support cross-compilation.\n\nSDKs are tightly coupled with the toolchain used to create them.\nSupported SDKs are distributed by the Swift project with links on the [installation page](https://www.swift.org/install/) for macOS and Linux, and included in the distribution for Windows.\n\nAdditionally, the Swift project provides the tooling repository [swift-sdk-generator](https://github.com/swiftlang/swift-sdk-generator) that you can use to create a custom SDK for your preferred platform.\n\n## Topics \n\n### Installing an SDK\n- <doc:SDKInstall>\n\n### Listing SDKs\n- <doc:SDKList>\n\n### Removing an SDK\n- <doc:SDKRemove>\n\n### Configuring an SDK\n- <doc:SDKConfigure>\n\n### Deprecated Commands\n- <doc:SDKConfigurationSet>\n- <doc:SDKConfigurationShow>\n- <doc:SDKConfigurationReset>\n\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftTest.md",
    "content": "# swift test\n\n@Metadata {\n    @PageImage(purpose: icon, source: command-icon)\n}\n\n<!-- Generated by swift-argument-parser -->\n\nBuild and run tests.\n\n```\ntest [--package-path=<package-path>]\n  [--cache-path=<cache-path>] [--config-path=<config-path>]\n  [--security-path=<security-path>]\n  [--scratch-path=<scratch-path>]\n  [--swift-sdks-path=<swift-sdks-path>]\n  [--toolset=<toolset>...]\n  [--pkg-config-path=<pkg-config-path>...]\n  [--enable-dependency-cache|disable-dependency-cache]\n  [--enable-build-manifest-caching|disable-build-manifest-caching]\n  [--manifest-cache=<manifest-cache>]\n  [--enable-experimental-prebuilts|disable-experimental-prebuilts]\n  [--verbose] [--very-verbose|vv] [--quiet]\n  [--color-diagnostics|no-color-diagnostics]\n  [--disable-sandbox] [--netrc] \n  [--enable-netrc|disable-netrc] [--netrc-file=<netrc-file>]\n  [--enable-keychain|disable-keychain]\n  [--resolver-fingerprint-checking=<resolver-fingerprint-checking>]\n  [--resolver-signing-entity-checking=<resolver-signing-entity-checking>]\n  [--enable-signature-validation|disable-signature-validation]\n  [--enable-prefetching|disable-prefetching]\n  [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file]\n  [--skip-update] [--disable-scm-to-registry-transformation]\n  [--use-registry-identity-for-scm]\n  [--replace-scm-with-registry]\n  [--default-registry-url=<default-registry-url>]\n  [--configuration=<configuration>] [--=<Xcc>...]\n  [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]\n  [--triple=<triple>] [--sdk=<sdk>]\n  [--toolchain=<toolchain>] [--swift-sdk=<swift-sdk>]\n  [--sanitize=<sanitize>...]\n  [--auto-index-store|enable-index-store|disable-index-store]\n  [--enable-parseable-module-interfaces] [--jobs=<jobs>]\n  [--use-integrated-swift-driver]\n  [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>]\n  [--build-system=<build-system>] [--=<debug-info-format>]\n  [--enable-dead-strip|disable-dead-strip]\n  [--disable-local-rpath] [--skip-build]\n  [--enable-xctest|disable-xctest]\n  [--enable-swift-testing|disable-swift-testing]\n  [--attachments-path=<attachments-path>]\n  [--parallel|no-parallel] [--num-workers=<num-workers>]\n  [--list-tests]\n  [--show-codecov-path|show-code-coverage-path|show-coverage-path]\n  [--specifier=<specifier>] [--filter=<filter>...]\n  [--skip=<skip>...] [--xunit-output=<xunit-output>]\n  [--enable-testable-imports|disable-testable-imports]\n  [--enable-code-coverage|disable-code-coverage]\n  [--traits=<traits>] [--enable-all-traits]\n  [--disable-default-traits] [--version] [--help]\n```\n\nSEE ALSO: <doc:SwiftBuild>, <doc:SwiftRun>, <doc:SwiftPackageCommands>\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--skip-build**:\n\n*Skip building the test target.*\n\n\n- term **--enable-xctest|disable-xctest**:\n\n*Enable support for XCTest.*\n\n\n- term **--enable-swift-testing|disable-swift-testing**:\n\n*Enable support for Swift Testing.*\n\n\n- term **--attachments-path=\\<attachments-path\\>**:\n\n*Path where attachments should be written (Swift Testing only). This path must be an existing directory the current user can write to. If not specified, any attachments created during testing are discarded.*\n\n\n- term **--parallel|no-parallel**:\n\n*Run the tests in parallel.*\n\n\n- term **--num-workers=\\<num-workers\\>**:\n\n*Number of tests to execute in parallel.*\n\n\n- term **--list-tests**:\n\n*Lists test methods in specifier format.*\n\n\n- term **--show-codecov-path|show-code-coverage-path|show-coverage-path**:\n\n*Print the path of the exported code coverage JSON file.*\n\n\n- term **--specifier=\\<specifier\\>**:\n\n\n- term **--filter=\\<filter\\>**:\n\n*Run test cases that match a regular expression, Format: '<test-target>.<test-case>' or '<test-target>.<test-case>/<test>'.*\n\n\n- term **--skip=\\<skip\\>**:\n\n*Skip test cases that match a regular expression, Example: '--skip PerformanceTests'.*\n\n\n- term **--xunit-output=\\<xunit-output\\>**:\n\n*Path where the xUnit xml file should be generated.*\n\n\n- term **--enable-testable-imports|disable-testable-imports**:\n\n*Enable or disable testable imports. Enabled by default.*\n\n\n- term **--enable-code-coverage|disable-code-coverage**:\n\n*Enable code coverage.*\n\n\n- term **--traits=\\<traits\\>**:\n\n*Enables the passed traits of the package. Multiple traits can be specified by providing a comma separated list e.g. `--traits Trait1,Trait2`. When enabling specific traits the defaults traits need to explictily enabled as well by passing `defaults` to this command.*\n\n\n- term **--enable-all-traits**:\n\n*Enables all traits of the package.*\n\n\n- term **--disable-default-traits**:\n\n*Disables all default traits of the package.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n## swift.test.list\n\nLists test methods in specifier format\n\n```\ntest list [--package-path=<package-path>] [--cache-path=<cache-path>] [--config-path=<config-path>] [--security-path=<security-path>] [--scratch-path=<scratch-path>]     [--swift-sdks-path=<swift-sdks-path>] [--toolset=<toolset>...] [--pkg-config-path=<pkg-config-path>...]   [--enable-dependency-cache|disable-dependency-cache]  [--enable-build-manifest-caching|disable-build-manifest-caching] [--manifest-cache=<manifest-cache>] [--enable-experimental-prebuilts|disable-experimental-prebuilts] [--verbose] [--very-verbose|vv] [--quiet] [--color-diagnostics|no-color-diagnostics] [--disable-sandbox] [--netrc] [--enable-netrc|disable-netrc] [--netrc-file=<netrc-file>] [--enable-keychain|disable-keychain] [--resolver-fingerprint-checking=<resolver-fingerprint-checking>] [--resolver-signing-entity-checking=<resolver-signing-entity-checking>] [--enable-signature-validation|disable-signature-validation] [--enable-prefetching|disable-prefetching] [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file] [--skip-update] [--disable-scm-to-registry-transformation] [--use-registry-identity-for-scm] [--replace-scm-with-registry]  [--default-registry-url=<default-registry-url>] [--configuration=<configuration>] [--=<Xcc>...] [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]    [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]   [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...] [--auto-index-store|enable-index-store|disable-index-store]   [--enable-parseable-module-interfaces] [--jobs=<jobs>] [--use-integrated-swift-driver] [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>] [--build-system=<build-system>] [--=<debug-info-format>]      [--enable-dead-strip|disable-dead-strip] [--disable-local-rpath] [--skip-build]  [--enable-xctest|disable-xctest] [--enable-swift-testing|disable-swift-testing]         [--attachments-path=<attachments-path>] [--traits=<traits>] [--enable-all-traits] [--disable-default-traits]  [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--skip-build**:\n\n*Skip building the test target.*\n\n\n- term **--enable-xctest|disable-xctest**:\n\n*Enable support for XCTest.*\n\n\n- term **--enable-swift-testing|disable-swift-testing**:\n\n*Enable support for Swift Testing.*\n\n\n- term **--attachments-path=\\<attachments-path\\>**:\n\n*Path where attachments should be written (Swift Testing only). This path must be an existing directory the current user can write to. If not specified, any attachments created during testing are discarded.*\n\n\n- term **--traits=\\<traits\\>**:\n\n*Enables the passed traits of the package. Multiple traits can be specified by providing a comma separated list e.g. `--traits Trait1,Trait2`. When enabling specific traits the defaults traits need to explictily enabled as well by passing `defaults` to this command.*\n\n\n- term **--enable-all-traits**:\n\n*Enables all traits of the package.*\n\n\n- term **--disable-default-traits**:\n\n*Disables all default traits of the package.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n\n\n\n\n## swift.test.last\n\n```\ntest last [--package-path=<package-path>] [--cache-path=<cache-path>] [--config-path=<config-path>] [--security-path=<security-path>] [--scratch-path=<scratch-path>]     [--swift-sdks-path=<swift-sdks-path>] [--toolset=<toolset>...] [--pkg-config-path=<pkg-config-path>...]   [--enable-dependency-cache|disable-dependency-cache]  [--enable-build-manifest-caching|disable-build-manifest-caching] [--manifest-cache=<manifest-cache>] [--enable-experimental-prebuilts|disable-experimental-prebuilts] [--verbose] [--very-verbose|vv] [--quiet] [--color-diagnostics|no-color-diagnostics] [--disable-sandbox] [--netrc] [--enable-netrc|disable-netrc] [--netrc-file=<netrc-file>] [--enable-keychain|disable-keychain] [--resolver-fingerprint-checking=<resolver-fingerprint-checking>] [--resolver-signing-entity-checking=<resolver-signing-entity-checking>] [--enable-signature-validation|disable-signature-validation] [--enable-prefetching|disable-prefetching] [--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file] [--skip-update] [--disable-scm-to-registry-transformation] [--use-registry-identity-for-scm] [--replace-scm-with-registry]  [--default-registry-url=<default-registry-url>] [--configuration=<configuration>] [--=<Xcc>...] [--=<Xswiftc>...] [--=<Xlinker>...] [--=<Xcxx>...]    [--triple=<triple>] [--sdk=<sdk>] [--toolchain=<toolchain>]   [--swift-sdk=<swift-sdk>] [--sanitize=<sanitize>...] [--auto-index-store|enable-index-store|disable-index-store]   [--enable-parseable-module-interfaces] [--jobs=<jobs>] [--use-integrated-swift-driver] [--explicit-target-dependency-import-check=<explicit-target-dependency-import-check>] [--build-system=<build-system>] [--=<debug-info-format>]      [--enable-dead-strip|disable-dead-strip] [--disable-local-rpath] [--version] [--help]\n```\n\n- term **--package-path=\\<package-path\\>**:\n\n*Specify the package path to operate on (default current directory). This changes the working directory before any other operation.*\n\n\n- term **--cache-path=\\<cache-path\\>**:\n\n*Specify the shared cache directory path.*\n\n\n- term **--config-path=\\<config-path\\>**:\n\n*Specify the shared configuration directory path.*\n\n\n- term **--security-path=\\<security-path\\>**:\n\n*Specify the shared security directory path.*\n\n\n- term **--scratch-path=\\<scratch-path\\>**:\n\n*Specify a custom scratch directory path. (default .build)*\n\n\n- term **--swift-sdks-path=\\<swift-sdks-path\\>**:\n\n*Path to the directory containing installed Swift SDKs.*\n\n\n- term **--toolset=\\<toolset\\>**:\n\n*Specify a toolset JSON file to use when building for the target platform. Use the option multiple times to specify more than one toolset. Toolsets will be merged in the order they're specified into a single final toolset for the current build.*\n\n\n- term **--pkg-config-path=\\<pkg-config-path\\>**:\n\n*Specify alternative path to search for pkg-config `.pc` files. Use the option multiple times to\nspecify more than one path.*\n\n\n- term **--enable-dependency-cache|disable-dependency-cache**:\n\n*Use a shared cache when fetching dependencies.*\n\n\n- term **--enable-build-manifest-caching|disable-build-manifest-caching**:\n\n\n- term **--manifest-cache=\\<manifest-cache\\>**:\n\n*Caching mode of Package.swift manifests. Valid values are: (shared: shared cache, local: package's build directory, none: disabled)*\n\n\n- term **--enable-experimental-prebuilts|disable-experimental-prebuilts**:\n\n*Whether to use prebuilt swift-syntax libraries for macros.*\n\n\n- term **--verbose**:\n\n*Increase verbosity to include informational output.*\n\n\n- term **--very-verbose|vv**:\n\n*Increase verbosity to include debug output.*\n\n\n- term **--quiet**:\n\n*Decrease verbosity to only include error output.*\n\n\n- term **--color-diagnostics|no-color-diagnostics**:\n\n*Enables or disables color diagnostics when printing to a TTY. \nBy default, color diagnostics are enabled when connected to a TTY and disabled otherwise.*\n\n\n- term **--disable-sandbox**:\n\n*Disable using the sandbox when executing subprocesses.*\n\n\n- term **--netrc**:\n\n*Use netrc file even in cases where other credential stores are preferred.*\n\n\n- term **--enable-netrc|disable-netrc**:\n\n*Load credentials from a netrc file.*\n\n\n- term **--netrc-file=\\<netrc-file\\>**:\n\n*Specify the netrc file path.*\n\n\n- term **--enable-keychain|disable-keychain**:\n\n*Search credentials in macOS keychain.*\n\n\n- term **--resolver-fingerprint-checking=\\<resolver-fingerprint-checking\\>**:\n\n\n- term **--resolver-signing-entity-checking=\\<resolver-signing-entity-checking\\>**:\n\n\n- term **--enable-signature-validation|disable-signature-validation**:\n\n*Validate signature of a signed package release downloaded from registry.*\n\n\n- term **--enable-prefetching|disable-prefetching**:\n\n\n- term **--force-resolved-versions|disable-automatic-resolution|only-use-versions-from-resolved-file**:\n\n*Only use versions from the Package.resolved file and fail resolution if it is out-of-date.*\n\n\n- term **--skip-update**:\n\n*Skip updating dependencies from their remote during a resolution.*\n\n\n- term **--disable-scm-to-registry-transformation**:\n\n*Disable source control to registry transformation.*\n\n\n- term **--use-registry-identity-for-scm**:\n\n*Look up source control dependencies in the registry and use their registry identity when possible to help deduplicate across the two origins.*\n\n\n- term **--replace-scm-with-registry**:\n\n*Look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible.*\n\n\n- term **--default-registry-url=\\<default-registry-url\\>**:\n\n*Default registry URL to use, instead of the registries.json configuration file.*\n\n\n- term **--configuration=\\<configuration\\>**:\n\n*Build with configuration*\n\n\n- term **--=\\<Xcc\\>**:\n\n*Pass flag through to all C compiler invocations.*\n\n\n- term **--=\\<Xswiftc\\>**:\n\n*Pass flag through to all Swift compiler invocations.*\n\n\n- term **--=\\<Xlinker\\>**:\n\n*Pass flag through to all linker invocations.*\n\n\n- term **--=\\<Xcxx\\>**:\n\n*Pass flag through to all C++ compiler invocations.*\n\n\n- term **--triple=\\<triple\\>**:\n\n\n- term **--sdk=\\<sdk\\>**:\n\n\n- term **--toolchain=\\<toolchain\\>**:\n\n\n- term **--swift-sdk=\\<swift-sdk\\>**:\n\n*Filter for selecting a specific Swift SDK to build with.*\n\n\n- term **--sanitize=\\<sanitize\\>**:\n\n*Turn on runtime checks for erroneous behavior, possible values: address, thread, undefined, scudo.*\n\n\n- term **--auto-index-store|enable-index-store|disable-index-store**:\n\n*Enable or disable indexing-while-building feature.*\n\n\n- term **--enable-parseable-module-interfaces**:\n\n\n- term **--jobs=\\<jobs\\>**:\n\n*The number of jobs to spawn in parallel during the build process.*\n\n\n- term **--use-integrated-swift-driver**:\n\n\n- term **--explicit-target-dependency-import-check=\\<explicit-target-dependency-import-check\\>**:\n\n*A flag that indicates this build should check whether targets only import their explicitly-declared dependencies.*\n\n\n- term **--build-system=\\<build-system\\>**:\n\n\n- term **--=\\<debug-info-format\\>**:\n\n*The Debug Information Format to use.*\n\n\n- term **--enable-dead-strip|disable-dead-strip**:\n\n*Disable/enable dead code stripping by the linker.*\n\n\n- term **--disable-local-rpath**:\n\n*Disable adding $ORIGIN/@loader_path to the rpath by default.*\n\n\n- term **--version**:\n\n*Show the version.*\n\n\n- term **--help**:\n\n*Show help information.*\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/SwiftVersionSpecificPackaging.md",
    "content": "# Packaging based on the version of Swift\n\nProvide a package manifest for a specific version of Swift.\n\n## Overview\n\nThe package manager supports packages that work with a variety of versions, both the versions of the language and versions of the Swift toolchain, which provides the package manager.\n\nFor language-specific version checks, use the language-specific version checks available in the source code.\nHowever, in some circumstances, this may become unmanageable, specifically when the package manifest cannot be version-agnostic.\nAn example being when you adopt new features in the package manifest that aren't present in older versions.\n\nThe package manager supports a mechanism to allow version-specific manifests to be used alongside a current manifest to support older versions of Swift.\n\n### Version-specific Manifest Selection\n\nThe package manager looks for a version-specific marked manifest version when loading the particular version of a package, by searching for a manifest in the form of `Package@swift-6.swift`.\nThe version is a loosely specified semantic version, resolving in the following order of preference:\n\n1. `MAJOR.MINOR.PATCH` (for example, `Package@swift-6.1.1`)\n2. `MAJOR.MINOR` (for example, `Package@swift-6.1`)\n3. `MAJOR` (for example, `Package@swift-6`)\n\nUse this feature to maintain compatibility with multiple Swift project versions with a substantively different manifest file for this to be viable (for example, due to changes in the manifest API).\n\nIn case the current Swift version doesn't match any version-specific manifest, the package manager picks the manifest with the most compatible tools version.\nFor example, if there are three manifests:\n\n- `Package.swift` (tools version 6.0)\n- `Package@swift-5.10.swift` (tools version 5.10)\n- `Package@swift-5.9.swift` (tools version 5.9)\n\nThe package manager picks `Package.swift` on Swift 6 and above, because its tools version is most compatible with future versions of the package manager.\nWhen using Swift 5.10, it picks `Package@swift-5.10.swift`.\nOtherwise, when using Swift 5.9, it picks `Package@swift-5.9.swift`, and this is the minimum tools version this package may be used with.\n\nA package may have versioned manifest files which specify newer tools versions than its unversioned `Package.swift` file.\nIn this scenario, the package manager uses the manifest corresponding to the newest-compatible tools version.\n\n> Note: Support for having a versioned manifest file with a _newer_ tools version was required when the feature was first introduced because prior versions of the package manager were not aware of the concept and only knew to look for the unversioned `Package.swift`. This is still supported, but there have been many Swift releases since the feature was introduced. It is a best practice to have `Package.swift` declare the newest-supported tools version and for versioned manifest files to only specify older versions.\n\n### Version-specific tags when resolving remote dependencies\n\nThe tags that define package versions can _optionally_ be suffixed with a marker in the form of `@swift-3`.\nWhen the package manager is determining the available tags for a repository, _if_ a version-specific marker is available which matches the current tool version, then it *only* considers the versions which have the version-specific marker.\nConversely, version-specific tags are ignored by any non-matching tool version.\n\nFor example, suppose the package `PlayingCard` has the tags `1.0.0`, `1.2.0@swift-5`, and `1.3.0`.\nIf the package manager is from version 5.0 of the Swift toolchain and evaluates the available versions for the package, it only considers version `1.2.0`.\nIn the same scenario, using Swift 6 or later only attempts to resolve against versions `1.0.0` and `1.3.0`.\n\nThis feature is intended for use in the following scenarios:\n\n1. A package wishes to maintain support for Swift 3.0 in older versions, but newer versions of the package require Swift 4.0 for the manifest to be readable.\n   Since Swift 3.0 will not know to ignore those versions, it would fail when performing dependency resolution on the package if no action is taken.\n   In this case, the author can re-tag the last versions which supported Swift 3.0 appropriately.\n\n2. A package wishes to maintain dual support for Swift 3.0 and Swift 4.0 at the same version numbers, but this requires substantial differences in the code.\n   In this case, the author can maintain parallel tag sets for both versions.\n\nIt is *not* expected that the packages would ever use this feature unless absolutely necessary to support existing clients.\nSpecifically, packages *should not* adopt this syntax for tagging versions supporting the _latest released_ Swift version.\nThe package manager supports looking for any of the following marked tags, in order of preference:\n\n1. `MAJOR.MINOR.PATCH` (e.g., `1.2.0@swift-3.1.2`)\n2. `MAJOR.MINOR` (e.g., `1.2.0@swift-3.1`)\n3. `MAJOR` (e.g., `1.2.0@swift-3`)\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/UsingBuildConfigurations.md",
    "content": "# Using build configurations\n\nControl the build configuration for your app or package.\n\n## Overview\n\nPackage manager supports two general build configurations: Debug (default) and Release.\n\n### Debug\n\nBy default, running `swift build` builds the package using its debug configuration.\nAlternatively, you can use `swift build -c debug`.\nPackage manager locates the build artifacts in a directory called `debug` under the `.build` folder.\nWhen building in the debug configuration, a Swift target uses the following Swift compiler flags:\n\n* `-Onone`: Compile without any optimization.\n* `-g`: Generate debug information.\n* `-enable-testing`: Enable the Swift compiler's testability feature.\n\nA C language target in the debug configuration uses the following flags:\n\n* `-O0`: Compile without any optimization.\n* `-g`: Generate debug information.\n\n### Release\n\nTo build in release mode, type `swift build -c release`. \nPackage manager locates the build artifacts in a directory called `release` under the `.build` folder. \nWhen building in the release configuration, a Swift target uses the following Swift compiler flags:\n\n* `-O`: Compile with optimizations.\n* `-whole-module-optimization`: Optimize input files (per module) together\n  instead of individually.\n\nA C language target in the release configuration uses the following flags:\n\n* `-O2`: Compile with optimizations.\n\n### Additional Flags\n\nYou can pass additional flags to the C, C++, or Swift compilers in three different ways:\n\n* Command-line flags passed to these tools: flags like `-Xcc` (for the C compiler) or `-Xswiftc` (for the Swift compiler) pass relevant flags for all targets in the manifest.\n\n* Target-specific flags in the manifest: use options like `cSettings` or `swiftSettings` for fine-grained control of compilation flags for particular targets.\n\n* A destination JSON file: once you have a set of working command-line flags to apply to all targets, collect them in a JSON file and pass them in through `extra-cc-flags` and `extra-swiftc-flags` with `--destination example.json`. \n\nOne difference is that C flags passed on the `-Xcc` command-line or using a manifest's `cSettings`\nare supplied to the Swift compiler tool for convenience, but `extra-cc-flags` aren't.\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/UsingShellCompletion.md",
    "content": "# Using shell completion scripts\n\nCustomize your shell to automatically complete swift package commands.\n\n## Overview\n\nPackage manager ships with completion scripts for Bash, Zsh, and Fish.\nGenerate completion lists for your shell in order to use it.\n\n### Bash\n\nUse the following commands to install the Bash completions to `~/.swift-package-complete.bash` and automatically load them using your `~/.bash_profile` file.\n\n```bash\nswift package completion-tool generate-bash-script > ~/.swift-package-complete.bash\necho -e \"source ~/.swift-package-complete.bash\\n\" >> ~/.bash_profile\nsource ~/.swift-package-complete.bash\n```\n\nAlternatively, add the following commands to your `~/.bash_profile` file to directly load completions:\n\n```bash\n# Source Swift completion\nif [ -n \"`which swift`\" ]; then\n    eval \"`swift package completion-tool generate-bash-script`\"\nfi\n```\n\n### Zsh\n\nUse the following commands to install the Zsh completions to `~/.zsh/_swift`.\nYou can chose a different folder, but the filename should be `_swift`.\nThis will also add `~/.zsh` to your `$fpath` using your `~/.zshrc` file.\n\n```bash\nmkdir ~/.zsh\nswift package completion-tool generate-zsh-script > ~/.zsh/_swift\necho -e \"fpath=(~/.zsh \\$fpath)\\n\" >> ~/.zshrc\ncompinit\n```\n"
  },
  {
    "path": "Sources/PackageManagerDocs/Documentation.docc/UsingSwiftPackageRegistry.md",
    "content": "# Using a package registry\n\nConfigure and use a package registry for Swift Package Manager.\n\n## Overview\n\nSwift Package Manager supports downloading dependencies from any package registry that implements \n[SE-0292](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0292-package-registry-service.md)\nand the corresponding [service specification](<doc:RegistryServerSpecification>).\n\nIn a registry, packages are identified by [package identifier](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0292-package-registry-service.md#package-identity)\nin the form of `scope.package-name`.\n\n### Configuring a registry\n\nA registry can be configured in Swift Package Manager at two levels:\n - Project: the registry will be used for packages within the project. Settings are stored in `.swiftpm/configuration/registries.json`.\n - User: the registry will be used for all projects for the user. Settings are stored in `~/.swiftpm/configuration/registries.json`.\n\nOne could use the [`swift package-registry set` subcommand](<doc:PackageRegistrySet>) to assign a registry URL:\n\n```bash\n$ swift package-registry set https://packages.example.com \n```\n\nThe above sets registry to `https://packages.example.com` at project level. Pass \nthe `--global` option to set registry at user level:\n\n```bash\n$ swift package-registry set --global https://packages.example.com \n```\n\nThe resulting `registries.json` would look something like:\n\n```json\n{\n  \"registries\" : {\n    \"[default]\" : {\n      \"url\": \"https://packages.example.com\"\n    }   \n  },\n  \"version\" : 1\n}\n```\n\nThe JSON key `[default]` means that the registry at `https://packages.example.com` is \"unscoped\" and will be applied when there is no registry association found for a given scope. \n\nIn this example, `https://packages.example.com` will be applied to all scopes.\n\n### Adding a registry package dependency\n\nA registry package dependency is declared in `Package.swift` using the package identifier.\nFor example: \n\n```swift\ndependencies: [\n    .package(id: \"mona.LinkedList\", .upToNextMajor(from: \"1.0.0\")),\n],\n```\n\nPackage manager will query the registry mapped to a package's scope to resolve and download the appropriate release version.\n\n### Registry authentication\n\nIf a registry requires authentication, it can be set up by using the [`swift package-registry login`](<doc:PackageRegistryLogin>) subcommand introduced by [SE-0378](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0378-package-registry-auth.md#new-login-subcommand).\n\nCurrently, basic and token authentication are supported.\n\nProvide the credentials either by setting the corresponding options (i.e., one of username/password or access token) or when prompted:\n\n```bash\n$ swift package-registry login https://packages.example.com\n```\n\nPackage manager will save the credentials to the operating system's credential store (e.g., Keychain in macOS) or netrc file (which by default is located at `~/.netrc`) and apply them automatically when making registry API requests.\n\n### Dependency Resolution Using Registry\n\nResolving a registry dependency involves these steps:\n1. Fetch a package's available versions by calling the [list package releases](<doc:RegistryServerSpecification#4.1.-List-package-releases>) API.\n2. Compute the dependency graph by [fetching manifest(s) for a package release](<doc:RegistryServerSpecification#4.3.-Fetch-manifest-for-a-package-release>).\n3. Pinpoint the package version to use.\n\nFor more information on resolving dependencies, see <doc:ResolvingPackageVersions>. \n\n#### Using registry for source control dependencies\n\nHere is an example of a source control dependency:\n\n```swift\ndependencies: [\n    .package(url: \"https://github.com/mona/LinkedList\", .upToNextMajor(from: \"1.0.0\")),\n],\n```\n\nRegistry can be used for source control dependencies as well. \nThis is particularly useful when there is a \"mixed\" graph (i.e., a dependency graph that has both source control and registry dependencies).\nPackage manager considers packages with different origins to be different, so if a package is referenced as both a registry (e.g., `mona.LinkedList`) and source control (e.g., `https://github.com/mona/LinkedList`) dependency, they are considered different even though they are the same package, and would result in symbol clashes.\n\nSwift Package Manager can deduplicate packages by performing a [lookup on the source control URL](<doc:RegistryServerSpecification#4.5.-Lookup-package-identifiers-registered-for-a-URL>) (e.g., `https://github.com/mona/LinkedList`) to see if it is associated with any package identifier (e.g., `mona.LinkedList`).\n\nOne can control if/how Package manager should use registry in conjunction with source control dependencies by setting one of these flags:\n- `--disable-scm-to-registry-transformation` (default): Swift Package Manager will not transform source control dependency to registry dependency. Source control dependency will be downloaded from its corresponding URL, while registry dependency will be resolved and downloaded using the configured registry (if any).\n- `--use-registry-identity-for-scm`: Swift Package Manager will look up source control dependencies in the registry and use their registry identity whenever possible to help deduplicate packages across the two origins. In other words, suppose `mona.LinkedList` is the package identifier for `https://github.com/mona/LinkedList`, then Package manager will treat both references in the dependency graph as the same package. \n- `--replace-scm-with-registry`: Swift Package Manager will look up source control dependencies in the registry and use the registry to retrieve them instead of source control when possible. In other words, Package manager will attempt to download a source control dependency from the registry first, and fall back to cloning the source repository if the dependency is not found in the registry.\n\n### Dependency Download From Registry\n\nAfter a registry dependency is resolved, Swift Package Manager can [download source archive](<doc:RegistryServerSpecification#4.4.-Download-source-archive>) of the computed package version from the registry.\n\n#### Package security\n\nAs a security feature, Swift Package Manager performs checksum TOFU ([trust-on-first-use](https://en.wikipedia.org/wiki/Trust_on_first_use)) on the downloaded source archive. See <doc:PackageSecurity> for more information about Package manager's use of trust-on-first-use.\n\n#### Validating signed packages\n\n [SE-0391](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md#package-signing) adds package signing support to Swift Package Manager.\nPackage manager determines if a downloaded archive is signed by checking for presence of the `X-Swift-Package-Signature-Format` and `X-Swift-Package-Signature` headers in the HTTP response.\n\n Swift Package Manager then performs a series of validations based on user's [security configuration](<doc:#Security-configuration>).\n\nFor more information on Package manager's registry security features, see <doc:PackageSecurity#Signed-packages-from-a-registry>.\n\n### Publishing to Registry\n\n [`swift package-registry publish`](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md#new-package-registry-publish-subcommand) is an all-in-one command for publishing a package release to registry. \n\n#### Package signing\n\nRegistries can optionally require signing.\nFor more details on signed registry packages, see <doc:PackageSecurity#Signed-packages-from-a-registry>.\n\n##### Signature formats\n\n| Signature Format | Specification |\n| ---------------- | ------------- |\n| `cms-1.0.0`      | [SE-391](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0391-package-registry-publish.md#package-signature-format-cms-100) |\n\nSince there is only one supported signature format, all signatures produced by Swift Package Manager are in `cms-1.0.0`.\n\n##### Signed contents\n\n###### Source archive\n\nThe signature is detached and sent as part of the HTTP request to the publish API. It is included in the source archive download response as HTTP headers, and is part of the package release metadata.\n\n###### Package release metadata\n\nThe signature is detached and sent as part of the HTTP request to the publish API.\nThe current API specification does not include an endpoint for fetching this metadata in its original form.\n\nFor more details, refer to the [registry specification](<doc:RegistryServerSpecification#4.2.2.-Package-release-metadata-standards>).\n\n###### Package manifest(s)\n\n`Package.swift` and version-specific manifests are individually signed.\nThe signature is embedded in the corresponding manifest file.\nThe source archive is generated and signed **after** manifest signing. \n\n```swift\n// swift-tools-version: 5.7\n\nimport PackageDescription\nlet package = Package(\n    name: \"library\",\n    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n    targets: [ .target(name: \"library\") ]\n)\n\n// signature: cms-1.0.0;l1TdTeIuGdNsO1FQ0ptD64F5nSSOsQ5WzhM6/7KsHRuLHfTsggnyIWr0DxMcBj5F40zfplwntXAgS0ynlqvlFw==\n```\n\nWhen a manifest is fetched from the registry, Swift Package Manager checks if the containing source archive is signed by fetching the package release metadata.\nIt is a failure if the source archive is signed but the manifest is not.\nPackage manager will extract and parse signature from the manifest then validate it similar to what is done for [source archive signature](<doc:Validating-signed-packages>).\n\nPackage manager performs publisher TOFU to ensure it remains consistent for the package. \nThis implies the signer of manifests and source archive must be the same.\n\nTo reduce the amount of logging and thus noise, diagnostics related to manifest signature validation are set to DEBUG level. \nOnly when user chooses the `prompt` option for unsigned packages or packages signed with an untrusted certificate would Package manager behave like source archive validation.  \n\n### Swift Package Manager Registry Configuration\n\n#### Registry-to-scope mappings\n\nWhen resolving or downloading registry packages, Package manager looks at the registry-to-scope mappings in project and user-level configuration to determine which registry is assigned for a package's scope.\n\nFor example, given the following configuration files:\n\n```json\n// User-level configuration (~/.swiftpm/configuration/registries.json)\n{\n  \"registries\": {\n    \"[default]\": {\n      \"url\": \"https://global.example.com\"\n    },\n    \"foo\": {\n      \"url\": \"https://global.example.com\"\n    },\n  },\n  \"version\": 1\n}\n\n// Local configuration (.swiftpm/configuration/registries.json)\n{\n  \"registries\": {\n    \"foo\": {\n      \"url\": \"https://local.example.com\"\n    }\n  },\n  \"version\": 1\n}\n```\n\n- For package `foo.LinkedList`, the registry at `https://local.example.com` is used. (Local configuration has higher precedence than user-level configuration.)\n- For package `bar.LinkedList`, the registry at `https://global.example.com` is used. (No mapping for scope `bar` is found, so `[default]` is used.)\n  \n#### Security configuration\n\nRegistry security configurations are specified in the user-level `registries.json` (`~/.swiftpm/configuration/registries.json`):\n\n```json\n{\n  \"security\": {\n    \"default\": {\n      \"signing\": {\n        \"onUnsigned\": \"prompt\", // One of: \"error\", \"prompt\", \"warn\", \"silentAllow\"\n        \"onUntrustedCertificate\": \"prompt\", // One of: \"error\", \"prompt\", \"warn\", \"silentAllow\"\n        \"trustedRootCertificatesPath\": \"~/.swiftpm/security/trusted-root-certs/\",\n        \"includeDefaultTrustedRootCertificates\": true,\n        \"validationChecks\": {\n          \"certificateExpiration\": \"disabled\", // One of: \"enabled\", \"disabled\"\n          \"certificateRevocation\": \"disabled\"  // One of: \"strict\", \"allowSoftFail\", \"disabled\"\n        }\n      }\n    },\n    \"registryOverrides\": {\n      // The example shows all configuration overridable at registry level\n      \"packages.example.com\": {\n        \"signing\": {\n          \"onUnsigned\": \"warn\",\n          \"onUntrustedCertificate\": \"warn\",\n          \"trustedRootCertificatesPath\": <STRING>,\n          \"includeDefaultTrustedRootCertificates\": <BOOL>,\n          \"validationChecks\": {\n            \"certificateExpiration\": \"enabled\",\n            \"certificateRevocation\": \"allowSoftFail\"\n          }\n        }\n      }\n    },\n    \"scopeOverrides\": {\n      // The example shows all configuration overridable at scope level\n      \"mona\": {\n        \"signing\": {\n          \"trustedRootCertificatesPath\": <STRING>,\n          \"includeDefaultTrustedRootCertificates\": <BOOL>\n        }\n      }\n    },\n    \"packageOverrides\": {\n      // The example shows all configuration overridable at package level\n      \"mona.LinkedList\": {\n        \"signing\": {\n          \"trustedRootCertificatesPath\": <STRING>,\n          \"includeDefaultTrustedRootCertificates\": <BOOL>\n        }\n      }\n    }\n  },\n  ...\n}\n```\n\nThere are multiple levels of overrides.\nA configuration for a package is computed using values from the following (in descending precedence):\n1. `packageOverrides` (if any)\n1. `scopeOverrides` (if any)\n1. `registryOverrides` (if any)\n1. `default`\n\nThe `default` JSON object in the example above contains all configurable security options and their default value when there is no override.\n\n- `signing.onUnsigned`: Indicates how Package manager will handle an unsigned package.\n\n  | Option        | Description                                               |\n  | ------------- | --------------------------------------------------------- |\n  | `error`       | Package manager will reject the package and fail the build. |\n  | `prompt`      | Package manager will prompt user to see if the unsigned package should be allowed. <ul><li>If no, Package manager will reject the package and fail the build.</li><li>If yes and the package has never been downloaded, its checksum will be stored for [checksum TOFU](<doc:PackageSecurity#Trust-on-First-Use>). Otherwise, if the package has been downloaded before, its checksum must match the previous value or else Package manager will reject the package and fail the build.</li></ul> Package manager will record user's response to prevent repetitive prompting. |\n  | `warn`        | Package manager will not prompt user but will emit a warning before proceeding. |\n  | `silentAllow` | Package manager will allow the unsigned package without prompting user or emitting warning. |\n\n- `signing.onUntrustedCertificate`: Indicates how Package manager will handle a package signed with an [untrusted certificate](<doc:PackageSecurity#Trusted-vs-untrusted-certificate>).\n\n  | Option        | Description                                               |\n  | ------------- | --------------------------------------------------------- |\n  | `error`       | Package manager will reject the package and fail the build. |\n  | `prompt`      | Package manager will prompt user to see if the package signed with an untrusted certificate should be allowed. <ul><li>If no, Package manager will reject the package and fail the build.</li><li>If yes, Package manager will proceed with the package as if it were an unsigned package.</li></ul> Package manager will record user's response to prevent repetitive prompting. |\n  | `warn`        | Package manager will not prompt user but will emit a warning before proceeding. |\n  | `silentAllow` | Package manager will allow the package signed with an untrusted certificate without prompting user or emitting warning. |\n\n- `signing.trustedRootCertificatesPath`: Absolute path to the directory containing custom trusted roots. Package manager will include these roots in its [trust store](<doc:PackageSecurity#Trusted-vs-untrusted-certificate>), and certificates used for package signing must chain to roots found in this store. This configuration allows override at the package, scope, and registry levels.\n- `signing.includeDefaultTrustedRootCertificates`: Indicates if Package manager should include default trusted roots in its [trust store](<doc:PackageSecurity#Trusted-vs-untrusted-certificate>). This configuration allows override at the package, scope, and registry levels.\n- `signing.validationChecks`: Validation check settings for the package signature.\n\n  | Validation               | Description                                               |\n  | ------------------------ | --------------------------------------------------------------- |\n  | `certificateExpiration`  | <ul><li>`enabled`: Package manager will check that the current timestamp when downloading falls within the signing certificate's validity period. If it doesn't, Package manager will reject the package and fail the build.</li><li>`disabled`: Package manager will not perform this check.</li></ul> |\n  | `certificateRevocation`  | With the exception of `disabled`, Package manager will check revocation status of the signing certificate. Currently, Package manager only supports revocation check done through [OCSP](https://www.rfc-editor.org/rfc/rfc6960).<ul><li>`strict`: Revocation check must complete successfully and the certificate must be in good status. Package manager will reject the package and fail the build if the revocation status is revoked or unknown (including revocation check not supported or failed).</li><li>`allowSoftFail`: Package manager will reject the package and fail the build iff the certificate has been revoked. Package manager will allow the certificate's revocation status to be unknown (including revocation check not supported or failed).</li><li>`disabled`: Package manager will not perform this check.</li></ul> |\n"
  },
  {
    "path": "Sources/PackageManagerDocs/EmptyFile.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This is an empty placeholder swift file for the documentation target.\n\n// You can preview the documentation here by running the following command:\n// swift package --disable-sandbox preview-documentation --target PackageManagerDocs\n"
  },
  {
    "path": "Sources/PackageManagerDocs/README.md",
    "content": "Manually generated the docc content stubs using the swift argument parser tool `generate-docc-reference-tool`:\n\nThe `generate-docc-reference` doesn't work for automatically creating all these because of a quirk in swift-package-manager, which is a driver\nexecutable and expects to be called with different names. The heurstics in swift-argument-parser's generation tool don't accomodate this use case.\n\n```bash\nswift build -c release\n.build/debug/generate-docc-reference-tool .build/release/swift-test -o Sources/PackageManagerDocs/Documentation.docc --style docc\n.build/debug/generate-docc-reference-tool .build/release/swift-bootstrap -o Sources/PackageManagerDocs/Documentation.docc --style docc\n.build/debug/generate-docc-reference-tool .build/release/swift-sdk -o Sources/PackageManagerDocs/Documentation.docc --style docc\n.build/debug/generate-docc-reference-tool .build/release/swift-run -o Sources/PackageManagerDocs/Documentation.docc --style docc\n.build/debug/generate-docc-reference-tool .build/release/swift-package -o Sources/PackageManagerDocs/Documentation.docc --style docc\n.build/debug/generate-docc-reference-tool .build/release/swift-package-registry -o Sources/PackageManagerDocs/Documentation.docc --style docc\n.build/debug/generate-docc-reference-tool .build/release/swift-package-collection -o Sources/PackageManagerDocs/Documentation.docc --style docc\n.build/debug/generate-docc-reference-tool .build/release/swift-build -o Sources/PackageManagerDocs/Documentation.docc --style docc\n.build/debug/generate-docc-reference-tool .build/release/swift-build-prebuilts -o Sources/PackageManagerDocs/Documentation.docc --style docc\n```\n\nAs of May 2025, the generation tool generates a single large markdown file in DocC format, which we then split up manually into small pieces\nfor the CLI content.\n\nUse the following command to preview documentation changes for this target:\n\n```bash\nswift package --disable-sandbox preview-documentation --target PackageManagerDocs\n```\n"
  },
  {
    "path": "Sources/PackageMetadata/PackageMetadata.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport PackageCollections\nimport PackageModel\nimport PackageRegistry\nimport PackageSigning\nimport SourceControl\n\nimport struct Foundation.Date\nimport struct Foundation.URL\n\nimport struct TSCUtility.Version\n\npublic struct Package {\n    public enum Source {\n        case indexAndCollections(collections: [PackageCollectionsModel.CollectionIdentifier], indexes: [URL])\n        case registry(url: URL)\n        case sourceControl(url: SourceControlURL)\n    }\n\n    public struct Resource: Sendable {\n        public let name: String\n        public let type: String\n        public let checksum: String?\n        public let signing: Signing?\n        public let signingEntity: RegistryReleaseMetadata.SigningEntity?\n    }\n\n    public struct Signing: Sendable {\n        public let signatureBase64Encoded: String\n        public let signatureFormat: String\n    }\n\n    public struct Author: Sendable {\n        public let name: String\n        public let email: String?\n        public let description: String?\n        public let organization: Organization?\n        public let url: URL?\n    }\n\n    public struct Organization: Sendable {\n        public let name: String\n        public let email: String?\n        public let description: String?\n        public let url: URL?\n    }\n\n    public let identity: PackageIdentity\n    public let location: String?\n    public let branches: [String]\n    public let versions: [Version]\n    public let source: Source\n\n    // Per version metadata based on the latest version that we include here for convenience.\n    public let licenseURL: URL?\n    public let readmeURL: URL?\n    public let repositoryURLs: [SourceControlURL]?\n    public let resources: [Resource]\n    public let author: Author?\n    public let description: String?\n    public let publishedAt: Date?\n    public let signingEntity: SigningEntity?\n    public let latestVersion: Version?\n\n    fileprivate init(\n        identity: PackageIdentity,\n        location: String? = nil,\n        branches: [String] = [],\n        versions: [Version],\n        licenseURL: URL? = nil,\n        readmeURL: URL? = nil,\n        repositoryURLs: [SourceControlURL]? = nil,\n        resources: [Resource] = [],\n        author: Author? = nil,\n        description: String? = nil,\n        publishedAt: Date? = nil,\n        signingEntity: SigningEntity? = nil,\n        latestVersion: Version? = nil,\n        source: Source\n    ) {\n        self.identity = identity\n        self.location = location\n        self.branches = branches\n        self.versions = versions\n        self.licenseURL = licenseURL\n        self.readmeURL = readmeURL\n        self.repositoryURLs = repositoryURLs\n        self.resources = resources\n        self.author = author\n        self.description = description\n        self.publishedAt = publishedAt\n        self.signingEntity = signingEntity\n        self.latestVersion = latestVersion\n        self.source = source\n    }\n}\n\npublic struct PackageSearchClient {\n    private let fileSystem: FileSystem\n    private let registryClient: RegistryClient\n    private let indexAndCollections: PackageIndexAndCollections\n    private let observabilityScope: ObservabilityScope\n\n    public init(\n        registryClient: RegistryClient,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.registryClient = registryClient\n        self.indexAndCollections = PackageIndexAndCollections(\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n    }\n\n    var repositoryProvider: RepositoryProvider {\n        GitRepositoryProvider()\n    }\n\n    // FIXME: This matches the current implementation, but we may want be smarter about it?\n    private func guessReadMeURL(baseURL: SourceControlURL, defaultBranch: String) -> URL? {\n        if let baseURL = baseURL.url {\n            return guessReadMeURL(baseURL: baseURL, defaultBranch: defaultBranch)\n        } else {\n            return nil\n        }\n    }\n\n    private func guessReadMeURL(baseURL: URL, defaultBranch: String) -> URL {\n        baseURL.appendingPathComponent(\"raw\").appendingPathComponent(defaultBranch).appendingPathComponent(\"README.md\")\n    }\n\n\n\n    private func guessReadMeURL(alternateLocations: [SourceControlURL]?) -> URL? {\n        if let alternateURL = alternateLocations?.first {\n            // FIXME: This is pretty crude, we should let the registry metadata provide the value instead.\n            return guessReadMeURL(baseURL: alternateURL, defaultBranch: \"main\")\n        }\n        return nil\n    }\n\n    private struct Metadata {\n        public let licenseURL: URL?\n        public let readmeURL: URL?\n        public let repositoryURLs: [SourceControlURL]?\n        public let resources: [Package.Resource]\n        public let author: Package.Author?\n        public let description: String?\n        public let publishedAt: Date?\n        public let signingEntity: SigningEntity?\n    }\n\n    private func getVersionMetadata(\n        package: PackageIdentity,\n        version: Version\n    ) async throws -> Metadata {\n        let metadata = try await self.registryClient.getPackageVersionMetadata(\n            package: package,\n            version: version,\n            fileSystem: self.fileSystem,\n            observabilityScope: observabilityScope\n        )\n\n        return Metadata(\n            licenseURL: metadata.licenseURL,\n            readmeURL: metadata.readmeURL,\n            repositoryURLs: metadata.repositoryURLs,\n            resources: metadata.resources.map { .init($0) },\n            author: metadata.author.map { .init($0) },\n            description: metadata.description,\n            publishedAt: metadata.publishedAt,\n            signingEntity: metadata.sourceArchive?.signingEntity\n        )\n    }\n\n    public func findPackages(\n        _ query: String\n    ) async throws -> [Package] {\n        let identity = PackageIdentity.plain(query)\n\n        // Search the package index and collections for a search term.\n        let search = { (error: Error?) async throws -> [Package] in\n            let result = try await self.indexAndCollections.findPackages(query)\n            let packages = result.items.map {\n                let versions = $0.package.versions.sorted(by: >)\n                let latestVersion = versions.first\n\n                return Package(\n                    identity: $0.package.identity,\n                    location: $0.package.location,\n                    versions: $0.package.versions.map(\\.version),\n                    licenseURL: $0.package.license?.url,\n                    readmeURL: $0.package.readmeURL,\n                    repositoryURLs: nil,\n                    resources: [],\n                    author: latestVersion?.author.map { .init($0) },\n                    description: latestVersion?.summary,\n                    publishedAt: latestVersion?.createdAt,\n                    signingEntity: latestVersion?.signer.map { SigningEntity(signer: $0) },\n                    latestVersion: latestVersion?.version,\n                    // this only makes sense in connection with providing versioned metadata\n                    source: .indexAndCollections(collections: $0.collections, indexes: $0.indexes)\n                )\n            }\n            if packages.isEmpty, let error {\n                // If the search result is empty and we had a previous error, emit it now.\n                throw error\n            }\n            return packages\n        }\n\n        // Interpret the given search term as a URL and fetch the corresponding Git repository to\n        // determine the available version tags and branches. If the search term cannot be interpreted\n        // as a URL or there are any errors during the process, we fall back to searching the configured\n        // index or package collections.\n        let fetchStandalonePackageByURL = { (error: Error?) async throws -> [Package] in\n            let url = SourceControlURL(query)\n            do {\n                return try await withTemporaryDirectory(removeTreeOnDeinit: true) { (tempDir: AbsolutePath) in\n                    let tempPath = tempDir.appending(component: url.lastPathComponent)\n                    let repositorySpecifier = RepositorySpecifier(url: url)\n                    try await self.repositoryProvider.fetch(\n                        repository: repositorySpecifier,\n                        to: tempPath,\n                        progressHandler: nil\n                    )\n                    guard try self.repositoryProvider.isValidDirectory(tempPath), let repository = try await self.repositoryProvider.open(\n                        repository: repositorySpecifier,\n                        at: tempPath\n                    ) as? GitRepository else {\n                        return []\n                    }\n\n                    let branches = try repository.getBranches()\n                    let versions = try repository.getTags().compactMap { Version($0) }\n                    let package = Package(\n                        identity: .init(url: url),\n                        location: url.absoluteString,\n                        branches: branches,\n                        versions: versions,\n                        licenseURL: nil,\n                        readmeURL: self.guessReadMeURL(\n                            baseURL: url,\n                            defaultBranch: try repository.getDefaultBranch()\n                        ),\n                        repositoryURLs: nil,\n                        resources: [],\n                        author: nil,\n                        description: nil,\n                        publishedAt: nil,\n                        signingEntity: nil,\n                        latestVersion: nil,\n                        // this only makes sense in connection with providing versioned metadata\n                        source: .sourceControl(url: url)\n                    )\n                    return [package]\n                }\n            } catch {\n                return try await search(error)\n            }\n        }\n\n        // If the given search term can be interpreted as a registry identity, try to get\n        // package metadata for it from the configured registry. If there are any errors\n        // or the search term does not work as a registry identity, we will fall back on\n        // `fetchStandalonePackageByURL`.\n        guard identity.isRegistry else {\n            return try await fetchStandalonePackageByURL(nil)\n        }\n        let metadata: RegistryClient.PackageMetadata\n        do {\n            metadata = try await self.registryClient.getPackageMetadata(\n                package: identity,\n                observabilityScope: observabilityScope\n            )\n        } catch {\n            return try await fetchStandalonePackageByURL(error)\n        }\n\n        let versions = metadata.versions.sorted(by: >)\n\n        // See if the latest package version has readmeURL set\n        guard let version = versions.first else {\n            let readmeURL: URL? = self.guessReadMeURL(alternateLocations: metadata.alternateLocations)\n            return [Package(\n                identity: identity,\n                versions: versions,\n                readmeURL: readmeURL,\n                // this only makes sense in connection with providing versioned metadata\n                source: .registry(url: metadata.registry.url)\n            )]\n        }\n\n        let versionMetadata = try? await self.getVersionMetadata(package: identity, version: version)\n        return [Package(\n            identity: identity,\n            versions: versions,\n            licenseURL: versionMetadata?.licenseURL,\n            readmeURL: versionMetadata?.readmeURL,\n            repositoryURLs: versionMetadata?.repositoryURLs,\n            resources: versionMetadata?.resources ?? [],\n            author: versionMetadata?.author,\n            description: versionMetadata?.description,\n            publishedAt: versionMetadata?.publishedAt,\n            signingEntity: versionMetadata?.signingEntity,\n            latestVersion: version,\n            source: .registry(url: metadata.registry.url)\n        )]\n    }\n\n    public func lookupIdentities(\n        scmURL: SourceControlURL,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @Sendable @escaping (Result<Set<PackageIdentity>, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await registryClient.lookupIdentities(\n                scmURL: scmURL,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    public func lookupSCMURLs(\n        package: PackageIdentity,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @Sendable @escaping (Result<Set<SourceControlURL>, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            let metadata = try await registryClient.getPackageMetadata(\n                package: package,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n            let alternateLocations = metadata.alternateLocations\n            return Set(alternateLocations)\n        }\n    }\n}\n\nextension Package.Signing {\n    fileprivate init(_ signing: RegistryClient.PackageVersionMetadata.Signing) {\n        self.init(\n            signatureBase64Encoded: signing.signatureBase64Encoded,\n            signatureFormat: signing.signatureFormat\n        )\n    }\n}\n\nextension RegistryReleaseMetadata.SigningEntity {\n    fileprivate init(_ entity: SigningEntity) {\n        switch entity {\n        case .recognized(let type, let name, let organizationalUnit, let organization):\n            self = .recognized(type: type.rawValue, commonName: name, organization: organization, identity: organizationalUnit)\n        case .unrecognized(let name, _, let organization):\n            self = .unrecognized(commonName: name, organization: organization)\n        }\n    }\n}\n\nextension Package.Resource {\n    fileprivate init(_ resource: RegistryClient.PackageVersionMetadata.Resource) {\n        self.init(\n            name: resource.name,\n            type: resource.type,\n            checksum: resource.checksum,\n            signing: resource.signing.map { .init($0) },\n            signingEntity: resource.signingEntity.map { .init($0) }\n        )\n    }\n}\n\nextension Package.Author {\n    fileprivate init(_ author: RegistryClient.PackageVersionMetadata.Author) {\n        self.init(\n            name: author.name,\n            email: author.email,\n            description: author.description,\n            organization: author.organization.map { .init($0) },\n            url: author.url\n        )\n    }\n\n    fileprivate init(_ author: PackageCollectionsModel.Package.Author) {\n        self.init(\n            name: author.username,\n            email: nil,\n            description: nil,\n            organization: nil,\n            url: author.url\n        )\n    }\n}\n\nextension Package.Organization {\n    fileprivate init(_ organization: RegistryClient.PackageVersionMetadata.Organization) {\n        self.init(\n            name: organization.name,\n            email: organization.email,\n            description: organization.description,\n            url: organization.url\n        )\n    }\n}\n\nextension SigningEntity {\n    fileprivate init(signer: PackageCollectionsModel.Signer) {\n        // All package collection signers are \"recognized\"\n        self = .recognized(\n            type: .init(signer.type),\n            name: signer.commonName,\n            organizationalUnit: signer.organizationalUnitName,\n            organization: signer.organizationName\n        )\n    }\n}\n\nextension SigningEntityType {\n    fileprivate init(_ type: PackageCollectionsModel.SignerType) {\n        switch type {\n        case .adp:\n            self = .adp\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/ArtifactsArchiveMetadata.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport struct TSCBasic.StringError\nimport struct TSCUtility.Version\n\npublic let artifactBundleExtension = \"artifactbundle\"\n\npublic struct ArtifactsArchiveMetadata: Equatable {\n    public let schemaVersion: String\n    public let artifacts: [String: Artifact]\n\n    public init(schemaVersion: String, artifacts: [String: Artifact]) {\n        self.schemaVersion = schemaVersion\n        self.artifacts = artifacts\n    }\n\n    public struct Artifact: Equatable {\n        public let type: ArtifactType\n        public let version: String\n        public let variants: [Variant]\n\n        public init(type: ArtifactsArchiveMetadata.ArtifactType, version: String, variants: [Variant]) {\n            self.type = type\n            self.version = version\n            self.variants = variants\n        }\n    }\n\n    // In the future we are likely to extend the ArtifactsArchive file format to carry other types of artifacts beyond\n    // executables, static libraries, and Swift SDKs. Additional fields may be required to support these new artifact\n    // types e.g. swift interface files for Swift libraries. This can also support resource-only artifacts as well. For example,\n    // 3D models along with associated textures, or fonts, etc.\n    public enum ArtifactType: String, RawRepresentable, Decodable {\n        case executable\n        case staticLibrary\n        case swiftSDK\n        // Experimental support for Windows DLLs\n        case experimentalWindowsDLL\n\n        // Can't be marked as formally deprecated as we still need to use this value for warning users.\n        case crossCompilationDestination\n    }\n\n    public struct Variant: Equatable {\n        public let path: RelativePath\n        public let supportedTriples: [Triple]?\n        public let staticLibraryMetadata: StaticLibraryMetadata?\n\n        public init(path: RelativePath, supportedTriples: [Triple]?, staticLibraryMetadata: StaticLibraryMetadata? = nil) {\n            self.path = path\n            self.supportedTriples = supportedTriples\n            self.staticLibraryMetadata = staticLibraryMetadata\n        }\n    }\n\n    public struct StaticLibraryMetadata: Equatable, Decodable {\n        public let headerPaths: [RelativePath]\n        public let moduleMapPath: RelativePath?\n    }\n}\n\nextension ArtifactsArchiveMetadata {\n    public static func parse(fileSystem: FileSystem, rootPath: AbsolutePath) throws -> ArtifactsArchiveMetadata {\n        let path = rootPath.appending(\"info.json\")\n        guard fileSystem.exists(path) else {\n            throw StringError(\"ArtifactsArchive info.json not found at '\\(rootPath)'\")\n        }\n\n        do {\n            let data: Data = try fileSystem.readFileContents(path)\n            let decoder = JSONDecoder.makeWithDefaults()\n            let decodedMetadata = try decoder.decode(ArtifactsArchiveMetadata.self, from: data)\n            let version = try Version(\n                versionString: decodedMetadata.schemaVersion,\n                usesLenientParsing: true\n            )\n\n            switch (version.major, version.minor) {\n            case (1, 2), (1, 1), (1, 0):\n                return decodedMetadata\n            default:\n                throw StringError(\n                    \"invalid `schemaVersion` of bundle manifest at `\\(path)`: \\(decodedMetadata.schemaVersion)\"\n                )\n            }\n        } catch {\n            throw StringError(\n                \"failed parsing ArtifactsArchive info.json at '\\(path)': \\(error.interpolationDescription)\"\n            )\n        }\n    }\n}\n\nextension ArtifactsArchiveMetadata: Decodable {\n    enum CodingKeys: String, CodingKey {\n        case schemaVersion\n        case artifacts\n    }\n}\n\nextension ArtifactsArchiveMetadata.Artifact: Decodable {\n    enum CodingKeys: String, CodingKey {\n        case type\n        case version\n        case variants\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        self.type = try container.decode(ArtifactsArchiveMetadata.ArtifactType.self, forKey: .type)\n        self.version = try container.decode(String.self, forKey: .version)\n        self.variants = try container.decode([ArtifactsArchiveMetadata.Variant].self, forKey: .variants)\n    }\n}\n\nextension ArtifactsArchiveMetadata.Variant: Decodable {\n    enum CodingKeys: String, CodingKey {\n        case path\n        case supportedTriples\n        case staticLibraryMetadata\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        self.supportedTriples = try container.decodeIfPresent([String].self, forKey: .supportedTriples)?.map { try Triple($0) }\n        self.path = try RelativePath(validating: container.decode(String.self, forKey: .path))\n        self.staticLibraryMetadata = try container.decodeIfPresent(\n            ArtifactsArchiveMetadata.StaticLibraryMetadata.self,\n            forKey: .staticLibraryMetadata\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/BuildConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The configuration of the build environment.\npublic enum BuildConfiguration: String, CaseIterable, Encodable, Sendable {\n    case debug\n    case release\n\n    public var dirname: String {\n        switch self {\n            case .debug: return \"debug\"\n            case .release: return \"release\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/BuildEnvironment.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A build environment with which to evaluate conditions.\npublic struct BuildEnvironment {\n    public let platform: Platform\n    public let configuration: BuildConfiguration?\n\n    public init(platform: Platform, configuration: BuildConfiguration? = nil) {\n        self.platform = platform\n        self.configuration = configuration\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/BuildFlags.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct BuildFlag: Hashable, Sendable, Encodable {\n    public var value: String\n\n    /// Describes the origin of this flag, for example if it was sourced from a Swift SDK, or added as a builtin option by SwiftPM.\n    public var source: Source?\n\n    public init(value: String, source: Source?) {\n        self.value = value\n        self.source = source\n    }\n\n    public enum Source: Sendable, Hashable, Codable {\n        case defaultSwiftTestingSearchPath\n        case defaultWindowsSettings\n        case swiftSDK\n        case toolset\n        case debugging\n        case plugin\n        case commandLineOptions\n    }\n}\n\nextension [BuildFlag] {\n    public var rawFlags: [String] {\n        return self.map(\\.value)\n    }\n}\n\nextension [String] {\n    public func constructBuildFlags(source: BuildFlag.Source?) -> [BuildFlag] {\n        return self.map {\n            BuildFlag(value: $0, source: source)\n        }\n    }\n}\n\n/// Build-tool independent flags.\npublic struct BuildFlags: Equatable, Encodable {\n    /// Flags to pass to the C compiler.\n    public var cCompilerFlags: [BuildFlag]\n\n    /// Flags to pass to the C++ compiler.\n    public var cxxCompilerFlags: [BuildFlag]\n\n    /// Flags to pass to the Swift compiler.\n    public var swiftCompilerFlags: [BuildFlag]\n\n    /// Flags to pass to the linker.\n    public var linkerFlags: [BuildFlag]\n\n    /// Flags to pass to xcbuild.\n    public var xcbuildFlags: [String]?\n\n    public init(\n        cCompilerFlags: [BuildFlag] = [],\n        cxxCompilerFlags: [BuildFlag] = [],\n        swiftCompilerFlags: [BuildFlag] = [],\n        linkerFlags: [BuildFlag] = [],\n        xcbuildFlags: [String] = []\n    ) {\n        self.cCompilerFlags = cCompilerFlags\n        self.cxxCompilerFlags = cxxCompilerFlags\n        self.swiftCompilerFlags = swiftCompilerFlags\n        self.linkerFlags = linkerFlags\n        self.xcbuildFlags = xcbuildFlags\n    }\n\n    // Kept to allow callers time to migrate to the new initializer.\n    @available(*, deprecated, message: \"Use the overload which accepts compiler flags as [BuildFlag] instead\")\n    public init(\n        cCompilerFlags: [String],\n        cxxCompilerFlags: [String],\n        swiftCompilerFlags: [String],\n        linkerFlags: [String],\n        xcbuildFlags: [String] = []\n    ) {\n        self.cCompilerFlags = cCompilerFlags.constructBuildFlags(source: nil)\n        self.cxxCompilerFlags = cxxCompilerFlags.constructBuildFlags(source: nil)\n        self.swiftCompilerFlags = swiftCompilerFlags.constructBuildFlags(source: nil)\n        self.linkerFlags = linkerFlags.constructBuildFlags(source: nil)\n        self.xcbuildFlags = xcbuildFlags\n    }\n\n    public mutating func merging(_ flags: BuildFlags) -> Self {\n        self.cCompilerFlags.insert(contentsOf: flags.cCompilerFlags, at: 0)\n        self.cxxCompilerFlags.insert(contentsOf: flags.cxxCompilerFlags, at: 0)\n        self.swiftCompilerFlags.insert(contentsOf: flags.swiftCompilerFlags, at: 0)\n        self.linkerFlags.insert(contentsOf: flags.linkerFlags, at: 0)\n        if self.xcbuildFlags != nil || flags.xcbuildFlags != nil {\n            self.xcbuildFlags = (self.xcbuildFlags ?? []) + (flags.xcbuildFlags ?? [])\n        }\n        return self\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/BuildSettings.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Namespace for build settings.\npublic enum BuildSettings {\n    /// Build settings declarations.\n    public struct Declaration: Hashable {\n        // Swift.\n        public static let SWIFT_ACTIVE_COMPILATION_CONDITIONS: Declaration =\n            .init(\"SWIFT_ACTIVE_COMPILATION_CONDITIONS\")\n        public static let OTHER_SWIFT_FLAGS: Declaration = .init(\"OTHER_SWIFT_FLAGS\")\n        public static let SWIFT_VERSION: Declaration = .init(\"SWIFT_VERSION\")\n\n        // C family.\n        public static let GCC_PREPROCESSOR_DEFINITIONS: Declaration = .init(\"GCC_PREPROCESSOR_DEFINITIONS\")\n        public static let HEADER_SEARCH_PATHS: Declaration = .init(\"HEADER_SEARCH_PATHS\")\n        public static let OTHER_CFLAGS: Declaration = .init(\"OTHER_CFLAGS\")\n        public static let OTHER_CPLUSPLUSFLAGS: Declaration = .init(\"OTHER_CPLUSPLUSFLAGS\")\n\n        // Linker.\n        public static let OTHER_LDFLAGS: Declaration = .init(\"OTHER_LDFLAGS\")\n        public static let LINK_LIBRARIES: Declaration = .init(\"LINK_LIBRARIES\")\n        public static let LINK_FRAMEWORKS: Declaration = .init(\"LINK_FRAMEWORKS\")\n\n        // Prebuilts settings.\n        public static let PREBUILT_INCLUDE_PATHS: Declaration = .init(\"PREBUILT_INCLUDE_PATHS\")\n        public static let PREBUILT_LIBRARY_PATHS: Declaration = .init(\"PREBUILT_LIBRARY_PATHS\")\n        public static let PREBUILT_LIBRARIES: Declaration = .init(\"PREBUILT_LIBRARIES\")\n\n        /// The declaration name.\n        public let name: String\n\n        private init(_ name: String) {\n            self.name = name\n        }\n    }\n\n    /// An individual build setting assignment.\n    public struct Assignment: Equatable, Hashable {\n        /// The assignment value.\n        public var values: [String]\n\n        public var conditions: [PackageCondition]\n\n        /// Indicates whether this assignment represents a default\n        /// that should be used only if no other assignments match.\n        public let `default`: Bool\n\n        public init(default: Bool = false) {\n            self.conditions = []\n            self.values = []\n            self.default = `default`\n        }\n\n        public init(values: [String] = [], conditions: [PackageCondition] = []) {\n            self.values = values\n            self.default = false // TODO(franz): Check again\n            self.conditions = conditions\n        }\n    }\n\n    /// Build setting assignment table which maps a build setting to a list of assignments.\n    public struct AssignmentTable {\n        public private(set) var assignments: [Declaration: [Assignment]]\n\n        public init() {\n            self.assignments = [:]\n        }\n\n        /// Add the given assignment to the table.\n        public mutating func add(_ assignment: Assignment, for decl: Declaration) {\n            // FIXME: We should check for duplicate assignments.\n            self.assignments[decl, default: []].append(assignment)\n        }\n    }\n\n    /// Provides a view onto assignment table with a given set of bound parameters.\n    ///\n    /// This class can be used to get the assignments matching the bound parameters.\n    public struct Scope {\n        /// The assignment table.\n        public let table: AssignmentTable\n\n        /// The build environment.\n        public let environment: BuildEnvironment\n\n        public init(_ table: AssignmentTable, environment: BuildEnvironment) {\n            self.table = table\n            self.environment = environment\n        }\n\n        /// Evaluate the given declaration and return the values matching the bound parameters.\n        public func evaluate(_ decl: Declaration) -> [String] {\n            // Return nil if there is no entry for this declaration.\n            guard let assignments = table.assignments[decl] else {\n                return []\n            }\n\n            // Add values from each assignment if it satisfies the build environment.\n            let allViableAssignments = assignments\n                .lazy\n                .filter { $0.conditions.allSatisfy { $0.satisfies(self.environment) } }\n\n            let nonDefaultAssignments = allViableAssignments.filter { !$0.default }\n\n            // If there are no non-default assignments, let's fallback to defaults.\n            if nonDefaultAssignments.isEmpty {\n                return allViableAssignments.filter(\\.default).flatMap(\\.values)\n            }\n\n            return nonDefaultAssignments.flatMap(\\.values)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageModel\n  ArtifactsArchiveMetadata.swift\n  BuildConfiguration.swift\n  BuildEnvironment.swift\n  BuildFlags.swift\n  BuildSettings.swift\n  DependencyMapper.swift\n  Diagnostics.swift\n  EnabledTrait.swift\n  IdentityResolver.swift\n  InstalledSwiftPMConfiguration.swift\n  Manifest/Manifest.swift\n  Manifest/Manifest+Traits.swift\n  Manifest/TraitConfiguration.swift\n  Manifest/PackageConditionDescription.swift\n  Manifest/PackageDependencyDescription.swift\n  Manifest/PlatformDescription.swift\n  Manifest/ProductDescription.swift\n  Manifest/SystemPackageProviderDescription.swift\n  Manifest/TargetBuildSettingDescription.swift\n  Manifest/TargetDescription.swift\n  Manifest/TraitDescription.swift\n  ManifestSourceGeneration.swift\n  MinimumDeploymentTarget.swift\n  Module/BinaryModule.swift\n  Module/ClangModule.swift\n  Module/PluginModule.swift\n  Module/SwiftModule.swift\n  Module/SystemLibraryModule.swift\n  Module/Module.swift\n  ModuleMapType.swift\n  PackageModel.swift\n  PackageIdentity.swift\n  PackageReference.swift\n  Platform.swift\n  PlatformRegistry.swift\n  PrebuiltLibrary.swift\n  Product.swift\n  Registry.swift\n  RegistryReleaseMetadata.swift\n  Resource.swift\n  Sanitizers.swift\n  Snippets/Model/Snippet.swift\n  Snippets/Model/SnippetGroup.swift\n  Snippets/Parsing/PlainTextSnippetExtractor.swift\n  Sources.swift\n  SupportedLanguageExtension.swift\n  SwiftLanguageVersion.swift\n  SwiftSDKs/SwiftSDK.swift\n  SwiftSDKs/SwiftSDKConfigurationStore.swift\n  SwiftSDKs/SwiftSDKBundle.swift\n  SwiftSDKs/SwiftSDKBundleStore.swift\n  Toolchain.swift\n  ToolchainConfiguration.swift\n  Toolchain+SupportedFeatures.swift\n  Toolset.swift\n  ToolsVersion.swift\n  ToolsVersionSpecificationGeneration.swift\n  UserToolchain.swift\n  WindowsToolchainInfo.swift)\ntarget_link_libraries(PackageModel PUBLIC\n  TSCBasic\n  TSCUtility\n  Basics)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageModel PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS PackageModel\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS PackageModel)\n"
  },
  {
    "path": "Sources/PackageModel/DependencyMapper.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport enum TSCBasic.PathValidationError\nimport struct TSCUtility.Version\n\npublic protocol DependencyMapper {\n    func mappedDependency(_ dependency: MappablePackageDependency, fileSystem: FileSystem) throws -> PackageDependency\n}\n\n/// a utility for applying mirrors base mapping\npublic struct DefaultDependencyMapper: DependencyMapper {\n    let identityResolver: IdentityResolver\n\n    public init(\n        identityResolver: IdentityResolver\n    ) {\n        self.identityResolver = identityResolver\n    }\n\n    public func mappedDependency(_ dependency: MappablePackageDependency, fileSystem: FileSystem) throws -> PackageDependency {\n        // clean up variants of path based dependencies\n        let dependencyLocationString = try self.normalizeDependencyLocation(\n            dependency: dependency,\n            parentPackagePath: dependency.parentPackagePath,\n            fileSystem: fileSystem\n        ) ?? dependency.locationString\n\n        // location mapping (aka mirrors) if any\n        let mappedLocationString = self.identityResolver.mappedLocation(for: dependencyLocationString)\n\n        if mappedLocationString == dependencyLocationString {\n            // no mapping done, return based on the cleaned up location string\n            return try .init(dependency, newLocationString: mappedLocationString)\n        } else if PackageIdentity.plain(mappedLocationString).isRegistry {\n            // mapped to registry\n            return .registry(\n                identity: .plain(mappedLocationString),\n                requirement: try dependency.registryRequirement(for: mappedLocationString),\n                productFilter: dependency.productFilter,\n                traits: dependency.traits\n            )\n        } else if parseScheme(mappedLocationString) != nil {\n            // mapped to a URL, we assume a remote SCM location\n            let url = SourceControlURL(mappedLocationString)\n            let identity = try self.identityResolver.resolveIdentity(for: url)\n            return .remoteSourceControl(\n                identity: identity,\n                nameForTargetDependencyResolutionOnly: dependency.nameForTargetDependencyResolutionOnly,\n                url: url,\n                requirement: try dependency.sourceControlRequirement(for: mappedLocationString),\n                productFilter: dependency.productFilter,\n                traits: dependency.traits\n            )\n\n        } else {\n            // mapped to a path, we assume a local SCM location\n            let localPath = try AbsolutePath(validating: mappedLocationString)\n            let identity = try self.identityResolver.resolveIdentity(for: localPath)\n            return .localSourceControl(\n                identity: identity,\n                nameForTargetDependencyResolutionOnly: dependency.nameForTargetDependencyResolutionOnly,\n                path: localPath,\n                requirement: try dependency.sourceControlRequirement(for: mappedLocationString),\n                productFilter: dependency.productFilter,\n                traits: dependency.traits\n            )\n        }\n    }\n\n    private static let filePrefix = \"file://\"\n\n    private func normalizeDependencyLocation(\n        dependency: MappablePackageDependency,\n        parentPackagePath: AbsolutePath,\n        fileSystem: FileSystem\n    ) throws -> String? {\n        switch dependency.kind {\n        // nothing to normalize\n        case .registry:\n            return .none\n        // location may be a relative path so we need to normalize it\n        case .fileSystem, .sourceControl:\n            let dependencyLocation = dependency.locationString\n            switch parseScheme(dependencyLocation) {\n            // if the location has no scheme, we treat it as a path (either absolute or relative).\n            case .none:\n                // if the dependency URL starts with '~/', try to expand it.\n                if dependencyLocation.hasPrefix(\"~/\") {\n                    return try AbsolutePath(validating: String(dependencyLocation.dropFirst(2)), relativeTo: fileSystem.homeDirectory).pathString\n                }\n\n                // check if already absolute path\n                if let path = try? AbsolutePath(validating: dependencyLocation) {\n                    return path.pathString\n                }\n\n                // otherwise treat as relative path to the parent package\n                return try AbsolutePath(validating: dependencyLocation, relativeTo: parentPackagePath).pathString\n            // SwiftPM can't handle file locations with file:// scheme so we need to\n            // strip that. We need to design a Location data structure for SwiftPM.\n            case .some(\"file\"):\n                let location = String(dependencyLocation.dropFirst(Self.filePrefix.count))\n                let hostnameComponent = location.prefix(while: { $0 != \"/\" })\n                guard hostnameComponent.isEmpty else {\n                  if hostnameComponent == \"..\" {\n                      throw DependencyMappingError.invalidFileURL(\"file:// URLs cannot be relative, did you mean to use '.package(path:)'?\")\n                  }\n                  throw DependencyMappingError.invalidFileURL(\"file:// URLs with hostnames are not supported, are you missing a '/'?\")\n                }\n                return try AbsolutePath(validating: location).pathString\n            // if the location has a scheme, assume a URL and nothing to normalize\n            case .some(_):\n                return .none\n            }\n        }\n    }\n}\n\n// trivial representation for mapping\npublic struct MappablePackageDependency {\n    public let parentPackagePath: AbsolutePath\n    public let kind: Kind\n    public let productFilter: ProductFilter\n    package let traits: Set<PackageDependency.Trait>?\n\n    package init(\n        parentPackagePath: AbsolutePath,\n        kind: Kind,\n        productFilter: ProductFilter,\n        traits: Set<PackageDependency.Trait>?\n    ) {\n        self.parentPackagePath = parentPackagePath\n        self.kind = kind\n        self.productFilter = productFilter\n        self.traits = traits\n    }\n\n    public init(\n        parentPackagePath: AbsolutePath,\n        kind: Kind,\n        productFilter: ProductFilter\n    ) {\n        self.init(\n            parentPackagePath: parentPackagePath,\n            kind: kind,\n            productFilter: productFilter,\n            traits: nil\n        )\n    }\n\n    public enum Kind {\n        case fileSystem(name: String?, path: String)\n        case sourceControl(name: String?, location: String, requirement: PackageDependency.SourceControl.Requirement)\n        case registry(id: String, requirement: PackageDependency.Registry.Requirement)\n    }\n\n    public enum Requirement {\n        case exact(Version)\n        case range(Range<Version>)\n        case revision(String)\n        case branch(String)\n    }\n}\n\nextension MappablePackageDependency {\n    public init(_ seed: PackageDependency, parentPackagePath: AbsolutePath) {\n        switch seed {\n        case .fileSystem(let settings):\n            self.init(\n                parentPackagePath: parentPackagePath,\n                kind: .fileSystem(\n                    name: settings.nameForTargetDependencyResolutionOnly,\n                    path: settings.path.pathString\n                ),\n                productFilter: settings.productFilter,\n                traits: settings.traits\n            )\n        case .sourceControl(let settings):\n            let locationString: String\n            switch settings.location {\n            case .local(let path):\n                locationString = path.pathString\n            case .remote(let url):\n                locationString = url.absoluteString\n            }\n            self.init(\n                parentPackagePath: parentPackagePath,\n                kind: .sourceControl(\n                    name: settings.nameForTargetDependencyResolutionOnly,\n                    location: locationString,\n                    requirement: settings.requirement\n                ),\n                productFilter: settings.productFilter,\n                traits: settings.traits\n            )\n        case .registry(let settings):\n            self.init(\n                parentPackagePath: parentPackagePath,\n                kind: .registry(\n                    id: settings.identity.description,\n                    requirement: settings.requirement\n                ),\n                productFilter: settings.productFilter,\n                traits: settings.traits\n            )\n        }\n    }\n}\n\nextension MappablePackageDependency {\n    fileprivate var locationString: String {\n        switch self.kind {\n        case .fileSystem(_, let path):\n            return path\n        case .sourceControl(_, let location, _):\n            return location\n        case .registry(let id, _):\n            return id\n        }\n    }\n\n    fileprivate var nameForTargetDependencyResolutionOnly: String? {\n        switch self.kind {\n        case .fileSystem(let name, _):\n            return name\n        case .sourceControl(let name, _, _):\n            return name\n        case .registry:\n            return .none\n        }\n    }\n\n    fileprivate func sourceControlRequirement(for location: String) throws -> PackageDependency.SourceControl.Requirement {\n        switch self.kind {\n        case .fileSystem(_, let path):\n            throw DependencyMappingError.invalidMapping(\"mapping of file system dependency (\\(path)) to source control (\\(location)) is invalid\")\n        case .sourceControl(_, _, let requirement):\n            return requirement\n        case .registry(_, let requirement):\n            return .init(requirement)\n        }\n    }\n\n    fileprivate func registryRequirement(for identity: String) throws -> PackageDependency.Registry.Requirement {\n        switch self.kind {\n        case .fileSystem(_, let path):\n            throw DependencyMappingError.invalidMapping(\"mapping of file system dependency (\\(path)) to registry (\\(identity)) is invalid\")\n        case .sourceControl(_, let location, let requirement):\n            return try .init(requirement, from: location, to: identity)\n        case .registry(_, let requirement):\n            return requirement\n        }\n    }\n}\n\nfileprivate extension PackageDependency.Registry.Requirement {\n    init(_ requirement: PackageDependency.SourceControl.Requirement, from location: String, to identity: String) throws {\n        switch requirement {\n        case .branch, .revision:\n            throw DependencyMappingError.invalidMapping(\"mapping of source control (\\(location)) to registry (\\(identity)) is invalid due to requirement information mismatch: cannot map branch or revision based dependencies to registry.\")\n        case .exact(let value):\n            self = .exact(value)\n        case .range(let value):\n            self = .range(value)\n        }\n    }\n}\n\nfileprivate extension PackageDependency.SourceControl.Requirement {\n    init(_ requirement: PackageDependency.Registry.Requirement) {\n        switch requirement {\n        case .exact(let value):\n            self = .exact(value)\n        case .range(let value):\n            self = .range(value)\n        }\n    }\n}\n\nextension PackageDependency {\n    init(_ seed: MappablePackageDependency, newLocationString: String) throws {\n        switch seed.kind {\n        case .fileSystem(let name, _):\n            let path = try AbsolutePath(validating: newLocationString)\n            self = .fileSystem(\n                identity: .init(path: path),\n                nameForTargetDependencyResolutionOnly: name,\n                path: path,\n                productFilter: seed.productFilter,\n                traits: seed.traits\n            )\n        case .sourceControl(let name, _, let requirement):\n            let identity: PackageIdentity\n            let location: SourceControl.Location\n            if parseScheme(newLocationString) != nil {\n                identity = .init(urlString: newLocationString)\n                location = .remote(.init(newLocationString))\n            } else {\n                let path = try AbsolutePath(validating: newLocationString)\n                identity = .init(path: path)\n                location = .local(path)\n            }\n            self = .sourceControl(\n                identity: identity,\n                nameForTargetDependencyResolutionOnly: name,\n                location: location,\n                requirement: requirement,\n                productFilter: seed.productFilter,\n                traits: seed.traits\n            )\n        case .registry(let id, let requirement):\n            self = .registry(\n                identity: .plain(id),\n                requirement: requirement,\n                productFilter: seed.productFilter,\n                traits: seed.traits\n            )\n        }\n    }\n}\n\nprivate enum DependencyMappingError: Swift.Error, CustomStringConvertible {\n    case invalidFileURL(_ message: String)\n    case invalidMapping(_ message: String)\n\n    var description: String {\n        switch self {\n        case .invalidFileURL(let message): return message\n        case .invalidMapping(let message): return message\n        }\n    }\n}\n\n/// Parses the URL type of a git repository\n/// e.g. https://github.com/apple/swift returns \"https\"\n/// e.g. git@github.com:apple/swift returns \"git\"\n///\n/// This is *not* a generic URI scheme parser!\nprivate func parseScheme(_ location: String) -> String? {\n    func prefixOfSplitBy(_ delimiter: String) -> String? {\n        let (head, tail) = location.spm_split(around: delimiter)\n        if tail == nil {\n            //not found\n            return nil\n        } else {\n            //found, return head\n            //lowercase the \"scheme\", as specified by the URI RFC (just in case)\n            return head.lowercased()\n        }\n    }\n\n    for delim in [\"://\", \"@\"] {\n        if let found = prefixOfSplitBy(delim), !found.contains(\"/\") {\n            return found\n        }\n    }\n\n    return nil\n}\n"
  },
  {
    "path": "Sources/PackageModel/Diagnostics.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// The diagnostic triggered when the package has a newer tools version than the installed tools.\npublic struct RequireNewerTools: Error, CustomStringConvertible {\n    /// The identity of the package.\n    public let packageIdentity: PackageIdentity\n\n    /// The version of the package.\n    public let packageVersion: String?\n\n    /// The installed tools version.\n    public let installedToolsVersion: ToolsVersion\n\n    /// The tools version of the package.\n    public let packageToolsVersion: ToolsVersion\n\n    public init(\n        packageIdentity: PackageIdentity,\n        packageVersion: String? = nil,\n        installedToolsVersion: ToolsVersion,\n        packageToolsVersion: ToolsVersion\n    ) {\n        self.packageIdentity = packageIdentity\n        self.packageVersion = packageVersion\n        self.installedToolsVersion = installedToolsVersion\n        self.packageToolsVersion = packageToolsVersion\n    }\n\n    public var description: String {\n        var text = \"package '\\(self.packageIdentity)'\"\n        if let packageVersion {\n            text += \" @ \\(packageVersion)\"\n        }\n        text += \" is using Swift tools version \\(packageToolsVersion.description) but the installed version is \\(installedToolsVersion.description)\"\n        return text\n    }\n}\n\n/// The diagnostic triggered when the package has an unsupported tools version.\npublic struct UnsupportedToolsVersion: Error, CustomStringConvertible {\n    /// The identity of the package.\n    public let packageIdentity: PackageIdentity\n\n    /// The version of the package.\n    public let packageVersion: String?\n\n    /// The current tools version support by the tools.\n    public let currentToolsVersion: ToolsVersion\n\n    /// The tools version of the package.\n    public let packageToolsVersion: ToolsVersion\n\n    fileprivate var hintString: String {\n        return \"consider using '\\(currentToolsVersion.specification(roundedTo: .minor))' to specify the current tools version\"\n    }\n\n    public init(\n        packageIdentity: PackageIdentity,\n        packageVersion: String? = nil,\n        currentToolsVersion: ToolsVersion,\n        packageToolsVersion: ToolsVersion\n    ) {\n        self.packageIdentity = packageIdentity\n        self.packageVersion = packageVersion\n        self.currentToolsVersion = currentToolsVersion\n        self.packageToolsVersion = packageToolsVersion\n    }\n\n    public var description: String {\n        var text = \"package '\\(self.packageIdentity)'\"\n        if let packageVersion {\n            text += \" @ \\(packageVersion)\"\n        }\n        text += \" is using Swift tools version \\(packageToolsVersion.description) which is no longer supported; \\(hintString)\"\n        return text\n    }\n}\n\npublic struct InvalidToolchainDiagnostic: Error, CustomStringConvertible {\n    public let error: String\n\n    public init(_ error: String) {\n        self.error = error\n    }\n\n    public var description: String {\n        \"toolchain is invalid: \\(error)\"\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/EnabledTrait.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n// MARK: - EnabledTraitsMap\n\n/// A wrapper struct for a dictionary that stores the transitively enabled traits for each package.\n/// This struct implicitly omits adding `default` traits to its storage, and returns `nil` if it\n/// there is no existing entry for a given package, since if there are no explicitly enabled traits\n/// set by anything else a package will then default to its `default` traits, if they exist.\n///\n/// ## Union Behavior\n/// When setting traits via the subscript setter (e.g., `map[packageId] = [\"trait1\", \"trait2\"]`),\n/// the new traits are **unified** with any existing traits for that package, rather than\n/// replacing them. This means multiple assignments to the same package will accumulate\n/// all traits into a union. If the same trait name is set multiple times with different setters, the\n/// setters are merged together.\n///\n/// Example:\n/// ```swift\n/// var traits = EnabledTraitsMap()\n/// traits[packageId] = [\"Apple\", \"Banana\"]\n/// traits[packageId] = [\"Coffee\", \"Chocolate\"]\n///\n/// // traits[packageId] now contains all four traits:\n/// print(traits[packageId])\n/// // Output: [\"Apple\", \"Banana\", \"Coffee\", \"Chocolate\"]\n/// ```\n///\n/// ## Disablers\n/// When a package or trait configuration explicitly sets an empty trait set (`[]`) for another package,\n/// this is tracked as a \"disabler\" to record the intent to disable default traits. Disablers coexist\n/// with the unified trait system—a package can have both recorded disablers AND explicitly enabled\n/// traits. This allows the system to distinguish between \"no traits specified\" versus \"default traits\n/// explicitly disabled but other traits may be enabled by different parents.\"\n///\n/// Only packages (via `Setter.package`) and trait configurations (via `Setter.traitConfiguration`)\n/// can disable default traits. Traits themselves cannot disable other packages' default traits.\n///\n/// Example:\n/// ```swift\n/// var traits = EnabledTraitsMap()\n/// let dependencyId = PackageIdentity(stringLiteral: \"MyDependency\")\n/// let parent1 = PackageIdentity(stringLiteral: \"Parent1\")\n/// let parent2 = PackageIdentity(stringLiteral: \"Parent2\")\n///\n/// // Parent1 explicitly disables default traits\n/// traits[dependencyId] = EnabledTraits([], setBy: .package(.init(identity: parent1)))\n///\n/// // Parent2 enables specific traits for the same dependency\n/// traits[dependencyId] = EnabledTraits([\"MyTrait\"], setBy: .package(.init(identity: parent2)))\n///\n/// // Query disablers to see who disabled defaults\n/// print(traits[disablersFor: dependencyId])  // Contains .package(Parent1)\n///\n/// // The dependency has \"MyTrait\" trait enabled (unified from Parent2)\n/// print(traits[dependencyId])  // Output: [\"MyTrait\"]\n/// ```\n///\n/// ## Default Setters\n/// When a parent package or trait configuration explicitly requests  the`default` trait (or leaves the set of\n/// traits unspecified), those setters are tracked separately. Query these using the `defaultSettersFor` subscript.\npublic struct EnabledTraitsMap {\n    public typealias Key = PackageIdentity\n    public typealias Value = EnabledTraits\n\n    private struct Storage {\n        /// Storage for explicitly enabled traits per package. Omits packages with only the \"default\" trait.\n        var traits: [PackageIdentity: EnabledTraits] = [:]\n\n        /// Tracks setters that explicitly disabled default traits (via []) for each package.\n        var _disablers: [PackageIdentity: Set<EnabledTrait.Setter>] = [:]\n\n        /// Tracks setters that requested default traits for each package.\n        /// This is used when a parent doesn't specify traits, meaning it wants the dependency to use its defaults,\n        /// or when the `default` trait is explicitly requested.\n        var _defaultSetters: [PackageIdentity: Set<EnabledTrait.Setter>] = [:]\n\n        init() { }\n\n        init(_ traits: [PackageIdentity: EnabledTraits]) {\n            self.traits = traits\n        }\n    }\n\n    private var storage = ThreadSafeBox(Storage())\n\n    public init() { }\n\n    public subscript(key: String) -> EnabledTraits {\n        get { self[PackageIdentity(key)] }\n        set { self[PackageIdentity(key)] = newValue }\n    }\n\n    public subscript(key: PackageIdentity) -> EnabledTraits {\n        get { storage.get().traits[key] ?? [\"default\"] }\n        set {\n            storage.mutate { (state: Storage) -> Storage in\n                var state = state\n\n                // Omit adding \"default\" explicitly, since the map returns \"default\"\n                // if there are no explicit traits enabled. This will allow us to check\n                // for nil entries in the stored dictionary, which tells us whether\n                // traits have been explicitly enabled or not.\n                //\n                // However, if \"default\" is explicitly set by a parent (has setters),\n                // track it in the `defaultSetters` property.\n                guard !(newValue == .defaults && !newValue.isExplicitlySetDefault) else {\n                    return state\n                }\n\n                // Track default setters\n                if newValue.isExplicitlySetDefault {\n                    if let defaultSetter = newValue.first?.setters.first {\n                        state._defaultSetters[key, default: []].insert(defaultSetter)\n                    }\n                    if state.traits[key] == [] {\n                        state.traits[key] = nil\n                    }\n                    return state\n                }\n\n                // Track disablers\n                if newValue.isEmpty, let disabler = newValue.disabledBy {\n                    state._disablers[key, default: []].insert(disabler)\n                }\n\n                // Union or create; the set of enabled traits is strictly additive.\n                if state.traits[key] == nil {\n                    state.traits[key] = newValue\n                } else {\n                    state.traits[key]?.formUnion(newValue)\n                }\n\n                return state\n            }\n        }\n    }\n\n    /// Returns the set of setters that explicitly disabled default traits for a package.\n    ///\n    /// When a parent package or trait configuration sets an empty trait array (`[]`) for a package,\n    /// that setter is tracked as a \"disabler\" to record the intent to disable default traits.\n    ///\n    /// - Parameter key: The package identity to query.\n    /// - Returns: The set of setters that disabled default traits, or `nil` if no disablers exist.\n    public subscript(disablersFor key: PackageIdentity) -> Set<EnabledTrait.Setter>? {\n        storage.get()._disablers[key]\n    }\n\n    /// Returns the set of setters that explicitly disabled default traits for a package identified by a string.\n    ///\n    /// This is a convenience subscript that converts the string key to a `PackageIdentity`.\n    ///\n    /// - Parameter key: The package identity string to query.\n    /// - Returns: The set of setters that disabled default traits, or `nil` if no disablers exist.\n    public subscript(disablersFor key: String) -> Set<EnabledTrait.Setter>? {\n        self[disablersFor: .init(key)]\n    }\n\n    /// Returns the set of setters that requested default traits for a package.\n    ///\n    /// When a parent package or trait configuration sets default traits or leaves\n    /// traits unspecified, those setters are tracked.\n    ///\n    /// - Parameter key: The package identity to query.\n    /// - Returns: The set of setters that requested default traits, or `nil` if no default setters exist.\n    public subscript(defaultSettersFor key: PackageIdentity) -> Set<EnabledTrait.Setter>? {\n        storage.get()._defaultSetters[key]\n    }\n\n    /// Returns the set of setters that requested default traits for a package identified by a string.\n    ///\n    /// This is a convenience subscript that converts the string key to a `PackageIdentity`.\n    ///\n    /// - Parameter key: The package identity string to query.\n    /// - Returns: The set of setters that requested default traits, or `nil` if no default setters exist.\n    public subscript(defaultSettersFor key: String) -> Set<EnabledTrait.Setter>? {\n        self[defaultSettersFor: .init(key)]\n    }\n\n    /// Returns a list of traits that were explicitly enabled for a given package.\n    ///\n    /// - Parameter key: The package identity to query.\n    /// - Returns: The explicitly enabled traits, or `nil` if no traits were explicitly set (meaning the package uses defaults).\n    public subscript(explicitlyEnabledTraitsFor key: PackageIdentity) -> EnabledTraits? {\n        storage.get().traits[key]\n    }\n\n    /// Returns a list of traits that were explicitly enabled for a given package.\n    ///\n    /// This is a convenience subscript that converts the string key to a `PackageIdentity`.\n    ///\n    /// - Parameter key: The package identity string to query.\n    /// - Returns: The explicitly enabled traits, or `nil` if no traits were explicitly set (meaning the package uses defaults).\n    public subscript(explicitlyEnabledTraitsFor key: String) -> EnabledTraits? {\n        self[explicitlyEnabledTraitsFor: .init(key)]\n    }\n\n    /// Returns a dictionary literal representation of the enabled traits map.\n    public var dictionaryLiteral: [PackageIdentity: EnabledTraits] {\n        return storage.get().traits\n    }\n}\n\n// MARK: EnabledTraitsMap + ExpressibleByDictionaryLiteral\nextension EnabledTraitsMap: ExpressibleByDictionaryLiteral {\n    public init(dictionaryLiteral elements: (Key, Value)...) {\n        for (key, value) in elements {\n            self[key] = value\n        }\n    }\n\n    public init(_ dictionary: [String: Value]) {\n        let mappedDictionary = dictionary.reduce(into: [Key: Value]()) { result, element in\n            result[PackageIdentity(element.key)] = element.value\n        }\n\n        self.storage = .init(.init(mappedDictionary))\n    }\n\n    public init(_ dictionary: [Key: Value]) {\n        self.storage = .init(.init(dictionary))\n    }\n}\n\n// MARK: - EnabledTrait\n\n/// A structure representing a trait that is enabled. The package in which this is enabled on is identified in\n/// the EnabledTraitsMap.\n///\n/// An enabled trait is a trait that is either explicitly enabled by a user-passed trait configuration from the command line,\n/// a parent package that has defined enabled traits for its dependency package, or transitively by another trait (including the default case).\n///\n/// An `EnabledTrait` is differentiated by its `name`, and all other data stored in this struct is treated as metadata for\n/// convenience. When unifying two `EnabledTrait`s, it will combine the list of setters if the `name`s match.\n///\npublic struct EnabledTrait: Identifiable {\n    /// Convenience typealias for a list of `Setter`\n    public typealias Setters = Set<Setter>\n\n    /// The identifier for the trait.\n    public var id: String { name }\n\n    /// The name of the trait.\n    public let name: String\n\n    /// The list of setters who have enabled this trait.\n    public var setters: Setters = []\n\n    public init(name: String, setBy: Setter) {\n        self.name = name\n        self.setters = [setBy]\n    }\n\n    public init(name: String, setBy: [Setter]) {\n        self.name = name\n        self.setters = Set(setBy)\n    }\n\n    /// The packages that have enabled this trait.\n    public var parentPackages: [Manifest.PackageIdentifier] {\n        setters.compactMap(\\.parentPackage)\n    }\n\n    /// Returns true if this trait is the \"default\" trait.\n    public var isDefault: Bool {\n        name == \"default\"\n    }\n\n    /// Returns true if this trait was enabled by the \"default\" trait (via `Setter.trait(\"default\")`).\n    /// This is distinct from `isDefault`, which checks if this trait's name is \"default\".\n    public var isSetByDefault: Bool {\n        self.setters.contains(where: { $0 == .default })\n    }\n\n    /// Returns a new `EnabledTrait` that contains a merged list of `Setters` from\n    /// `self` and the `otherTrait`, only if the traits are equal. Otherwise, returns nil.\n    /// - Parameter otherTrait: The trait to merge in.\n    public func unify(_ otherTrait: EnabledTrait) -> EnabledTrait? {\n        guard self.name == otherTrait.name else {\n            return nil\n        }\n\n        var updatedTrait = self\n        updatedTrait.setters = setters.union(otherTrait.setters)\n        return updatedTrait\n    }\n}\n\n// MARK: EnabledTrait.Setter\n\nextension EnabledTrait {\n    /// An enumeration that describes how a given trait was set as enabled.\n    public enum Setter: Hashable, CustomStringConvertible {\n        case traitConfiguration\n        case package(Manifest.PackageIdentifier)\n        case trait(String)\n\n        public var description: String {\n            switch self {\n            case .traitConfiguration:\n                \"command-line trait configuration\"\n            case .package(let parent):\n                \"package \\(parent.description)\"\n            case .trait(let trait):\n                \"trait \\(trait)\"\n            }\n        }\n\n        /// The identifier of the parent package that defined this trait, if any.\n        public var parentPackage: Manifest.PackageIdentifier? {\n            switch self {\n            case .package(let id):\n                return id\n            case .traitConfiguration, .trait:\n                return nil\n            }\n        }\n\n        public var parentTrait: String? {\n            switch self {\n            case .trait(let trait):\n                return trait\n            case .traitConfiguration, .package:\n                return nil\n            }\n        }\n\n        public static var `default`: Self {\n            .trait(\"default\")\n        }\n    }\n}\n\n// MARK: EnabledTrait + Equatable\n\nextension EnabledTrait: Equatable {\n    // When comparing two `EnabledTraits`, if the names are the same then\n    // we know that these two objects are referring to the same trait of a package.\n    // In this case, the two objects should be combined into one.\n    public static func ==(lhs: EnabledTrait, rhs: EnabledTrait) -> Bool {\n        return lhs.name == rhs.name\n    }\n\n    public static func ==(lhs: EnabledTrait, rhs: String) -> Bool {\n        return lhs.name == rhs\n    }\n\n    public static func ==(lhs: String, rhs: EnabledTrait) -> Bool {\n        return lhs == rhs.name\n    }\n}\n\n// MARK: EnabledTrait + Comparable\n\nextension EnabledTrait: Comparable {\n    public static func <(lhs: EnabledTrait, rhs: EnabledTrait) -> Bool {\n        return lhs.name < rhs.name\n    }\n}\n\n// MARK: EnabledTrait + CustomStringConvertible\n\nextension EnabledTrait: CustomStringConvertible {\n    public var description: String {\n        name\n    }\n}\n\n// MARK: EnabledTrait + ExpressibleByStringLiteral\n\nextension EnabledTrait: ExpressibleByStringLiteral {\n    public init(stringLiteral value: String) {\n        self.name = value\n    }\n}\n\n// MARK: - EnabledTraits\n\n/// A collection wrapper around a set of `EnabledTrait` instances that provides specialized behavior\n/// for trait management. This struct ensures that traits with the same name are automatically unified\n/// by merging their setters when inserted, maintaining a single entry per unique trait name. It provides\n/// convenient set operations like union and intersection, along with collection protocol conformance for\n/// easy iteration and manipulation of enabled traits.\n///\n/// ## Disabling All Traits\n/// An `EnabledTraits` instance can represent a \"disabled\" state when created with an empty collection\n/// and a `Setter`. In this case, the `disabledBy` property returns the setter that disabled default traits,\n/// allowing callers to track which parent package or configuration explicitly disabled default traits for a package.\npublic struct EnabledTraits: Hashable {\n    public typealias Element = EnabledTrait\n    public typealias Index = IdentifiableSet<Element>.Index\n\n    /// Storage of enabled traits.\n    private var _traits: IdentifiableSet<EnabledTrait> = []\n\n    /// This should only ever be set in the case where a parent\n    /// disables all traits, and an empty set of traits is passed.\n    private var _disableAllTraitsSetter: EnabledTrait.Setter? = nil\n\n    /// Returns the setter that disabled all traits for a package, if any.\n    /// This value is set when `EnabledTraits` is initialized with an empty collection,\n    /// indicating that a parent explicitly disabled all traits rather than leaving them\n    /// unset.\n    public var disabledBy: EnabledTrait.Setter? {\n        _disableAllTraitsSetter\n    }\n\n    public var areDefaultsEnabled: Bool {\n        return !_traits.filter(\\.isDefault).isEmpty || !_traits.filter(\\.isSetByDefault).isEmpty\n    }\n\n    /// Returns true if this represents an explicitly-set \"default\" trait (with setters),\n    /// as opposed to the sentinel `.defaults` value (no setters).\n    /// This is used to distinguish when a parent package enables default traits\n    /// either explicitly or when no traits have been specified for a package dependency\n    /// at all.\n    public var isExplicitlySetDefault: Bool {\n        // Check if this equals .defaults (only contains \"default\" trait) AND has explicit setters\n        return self == .defaults && _traits.contains(where: { !$0.setters.isEmpty })\n    }\n\n    public static var defaults: EnabledTraits {\n        [\"default\"]\n    }\n\n    public init(_ enabledTraits: EnabledTraits) {\n        self._traits = enabledTraits._traits\n    }\n\n    private init(_ disabler: EnabledTrait.Setter) {\n        self._disableAllTraitsSetter = disabler\n    }\n\n    public init<C: Collection>(_ traits: C, setBy setter: EnabledTrait.Setter) where C.Element == String {\n        guard !traits.isEmpty else {\n            self.init(setter)\n            return\n        }\n        let enabledTraits = traits.map({ EnabledTrait(name: $0, setBy: setter) })\n        self.init(enabledTraits)\n    }\n\n    private init<C: Collection>(_ traits: C) where C.Element == EnabledTrait {\n        self._traits = IdentifiableSet(traits)\n    }\n\n    public static func ==(_ lhs: EnabledTraits, _ rhs: EnabledTraits) -> Bool {\n        lhs._traits.names == rhs._traits.names\n    }\n}\n\n// MARK: EnabledTraits + ExpressibleByArrayLiteral\n\nextension EnabledTraits: ExpressibleByArrayLiteral {\n    public init(arrayLiteral elements: Element...) {\n        for element in elements {\n            _traits.insert(element)\n        }\n    }\n}\n\n// MARK: EnabledTraits + Collection\n\nextension EnabledTraits: Collection {\n    public var startIndex: Index {\n        return _traits.startIndex\n    }\n\n    public var endIndex: Index {\n        return _traits.endIndex\n    }\n\n    public func index(after i: Index) -> Index {\n        return _traits.index(after: i)\n    }\n\n    public subscript(position: Index) -> Element {\n        return _traits[position]\n    }\n\n    public mutating func insert(_ newMember: Element) {\n        _traits.insert(newMember)\n    }\n\n    public mutating func remove(_ member: Element) -> Element? {\n        return _traits.remove(member)\n    }\n\n    public func contains(_ member: Element) -> Bool {\n        return _traits.contains(member)\n    }\n\n    public func intersection<C: Collection>(_ other: C) -> EnabledTraits where C.Element == String {\n        self.intersection(other.map(\\.asEnabledTrait))\n    }\n\n    public func intersection<C: Collection>(_ other: C) -> EnabledTraits where C.Element == Self.Element {\n        let otherSet = IdentifiableSet(other.map({ $0 }))\n        let intersection = self._traits.intersection(otherSet)\n        return EnabledTraits(intersection)\n    }\n\n    public func union<C: Collection>(_ other: C) -> EnabledTraits where C.Element == Self.Element {\n        let unionedTraits = _traits.union(other)\n        return EnabledTraits(unionedTraits)\n    }\n\n    public mutating func formUnion(_ other: EnabledTraits) {\n        self._traits = self.union(other)._traits\n    }\n\n    public mutating func formUnion<C: Collection>(_ other: C) where C.Element == Self.Element {\n        self.formUnion(.init(other))\n    }\n\n    public func map(_ transform: (Self.Element) throws -> Self.Element) rethrows -> EnabledTraits {\n        let transformedTraits = try _traits.map(transform)\n        return EnabledTraits(transformedTraits)\n    }\n\n    public func flatMap(_ transform: (Self.Element) throws -> EnabledTraits) rethrows -> EnabledTraits {\n        let transformedTraits = try _traits.flatMap(transform)\n        return EnabledTraits(transformedTraits)\n    }\n\n    public static func ==<C: Collection>(_ lhs: EnabledTraits, _ rhs: C) -> Bool where C.Element == Element {\n        lhs._traits.names == rhs.names\n    }\n\n    public static func ==<C: Collection>(_ lhs: C, _ rhs: EnabledTraits) -> Bool where C.Element == Element {\n        lhs.names == rhs._traits.names\n    }\n}\n\n// MARK: - EnabledTraitConvertible\n\n/// Represents a type that can be converted into an `EnabledTrait`.\n/// This protocol enables conversion between string-like types and `EnabledTrait` instances,\n/// allowing for more flexible APIs that can accept either strings or traits interchangeably.\npackage protocol EnabledTraitConvertible: Equatable {\n    var asEnabledTrait: EnabledTrait { get }\n}\n\n// MARK: String + EnabledTraitConvertible\n\nextension String: EnabledTraitConvertible {\n    package var asEnabledTrait: EnabledTrait {\n        .init(stringLiteral: self)\n    }\n}\n\n// MARK: - Collection + EnabledTrait\n\nextension Collection where Element == EnabledTrait {\n    public var names: Set<String> {\n        Set<String>(self.map(\\.name))\n    }\n\n    public func contains(_ trait: String) -> Bool {\n        return self.map(\\.name).contains(trait)\n    }\n\n    public func contains(_ trait: Element) -> Bool {\n        return self.contains(trait.description)\n    }\n\n    public func joined(separator: String = \"\") -> String {\n        names.joined(separator: separator)\n    }\n}\n\n\n// MARK: - IdentifiableSet + EnabledTrait\n\nextension IdentifiableSet where Element == EnabledTrait {\n    private mutating func insertTrait(_ member: Element) {\n        if let oldElement = self.remove(member), let newElement = oldElement.unify(member) {\n            insert(newElement)\n        } else {\n            insert(member)\n        }\n    }\n\n    package func union<C: Collection>(_ other: C) -> IdentifiableSet<Element> where C.Element == Element {\n        var updatedContents = self\n        for element in other {\n            updatedContents.insertTrait(element)\n        }\n        return updatedContents\n    }\n}\n\n"
  },
  {
    "path": "Sources/PackageModel/IdentityResolver.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n// TODO: refactor this when adding registry support\npublic protocol IdentityResolver {\n    func resolveIdentity(for packageKind: PackageReference.Kind) throws -> PackageIdentity\n    func resolveIdentity(for url: SourceControlURL) throws -> PackageIdentity\n    func resolveIdentity(for path: AbsolutePath) throws -> PackageIdentity\n    func mappedLocation(for location: String) -> String\n    func mappedIdentity(for identity: PackageIdentity) throws -> PackageIdentity\n}\n\npublic struct DefaultIdentityResolver: IdentityResolver {\n    let locationMapper: (String) -> String\n    let identityMapper: (PackageIdentity) throws -> PackageIdentity\n\n    public init(\n        locationMapper: @escaping (String) -> String = { $0 },\n        identityMapper: @escaping (PackageIdentity) throws -> PackageIdentity = { $0 }\n    ) {\n        self.locationMapper = locationMapper\n        self.identityMapper = identityMapper\n    }\n\n    public func resolveIdentity(for packageKind: PackageReference.Kind) throws -> PackageIdentity {\n        switch packageKind {\n        case .root(let path):\n            return try self.resolveIdentity(for: path)\n        case .fileSystem(let path):\n            return try self.resolveIdentity(for: path)\n        case .localSourceControl(let path):\n            return try self.resolveIdentity(for: path)\n        case .remoteSourceControl(let url):\n            return try self.resolveIdentity(for: url)\n        case .registry(let identity):\n            return identity\n        }\n    }\n\n    public func resolveIdentity(for url: SourceControlURL) throws -> PackageIdentity {\n        let location = self.mappedLocation(for: url.absoluteString)\n        if let path = try? AbsolutePath(validating: location) {\n            return PackageIdentity(path: path)\n        } else {\n            return PackageIdentity(url: SourceControlURL(location))\n        }\n    }\n\n    public func resolveIdentity(for path: AbsolutePath) throws -> PackageIdentity {\n        let location = self.mappedLocation(for: path.pathString)\n        if let path = try? AbsolutePath(validating: location) {\n            return PackageIdentity(path: path)\n        } else {\n            return PackageIdentity(url: SourceControlURL(location))\n        }\n    }\n\n    public func mappedLocation(for location: String) -> String {\n        self.locationMapper(location)\n    }\n\n    public func mappedIdentity(for identity: PackageIdentity) throws -> PackageIdentity {\n        try self.identityMapper(identity)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/InstalledSwiftPMConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct InstalledSwiftPMConfiguration {\n    public struct Version: Codable, CustomStringConvertible {\n        let major: Int\n        let minor: Int\n        let patch: Int\n        let prereleaseIdentifier: String?\n\n        public init(major: Int, minor: Int, patch: Int, prereleaseIdentifier: String? = nil) {\n            self.major = major\n            self.minor = minor\n            self.patch = patch\n            self.prereleaseIdentifier = prereleaseIdentifier\n        }\n\n        public var description: String {\n            return \"\\(major).\\(minor).\\(patch)\\(prereleaseIdentifier.map { \"-\\($0)\" } ?? \"\")\"\n        }\n    }\n\n    let version: Int\n    public let swiftSyntaxVersionForMacroTemplate: Version\n    public let swiftTestingVersionForTestTemplate: Version\n\n    public static var `default`: InstalledSwiftPMConfiguration {\n        return .init(\n            version: 0,\n            swiftSyntaxVersionForMacroTemplate: .init(\n                major: 603,\n                minor: 0,\n                patch: 0,\n                prereleaseIdentifier: \"latest\"\n            ),\n            swiftTestingVersionForTestTemplate: defaultSwiftTestingVersionForTestTemplate\n        )\n    }\n\n    private static var defaultSwiftTestingVersionForTestTemplate: Version {\n        .init(\n            major: 0,\n            minor: 8,\n            patch: 0,\n            prereleaseIdentifier: nil\n        )\n    }\n}\n\nextension InstalledSwiftPMConfiguration: Codable {\n    enum CodingKeys: CodingKey {\n        case version\n        case swiftSyntaxVersionForMacroTemplate\n        case swiftTestingVersionForTestTemplate\n    }\n\n    public init(from decoder: any Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n\n        self.version = try container.decode(\n            Int.self,\n            forKey: CodingKeys.version\n        )\n        self.swiftSyntaxVersionForMacroTemplate = try container.decode(\n            Version.self,\n            forKey: CodingKeys.swiftSyntaxVersionForMacroTemplate\n        )\n        self.swiftTestingVersionForTestTemplate = try container.decodeIfPresent(\n            Version.self,\n            forKey: CodingKeys.swiftTestingVersionForTestTemplate\n        ) ?? InstalledSwiftPMConfiguration.defaultSwiftTestingVersionForTestTemplate\n    }\n\n    public func encode(to encoder: any Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n\n        try container.encode(self.version, forKey: CodingKeys.version)\n        try container.encode(\n            self.swiftSyntaxVersionForMacroTemplate,\n            forKey: CodingKeys.swiftSyntaxVersionForMacroTemplate\n        )\n        try container.encode(\n            self.swiftTestingVersionForTestTemplate,\n            forKey: CodingKeys.swiftTestingVersionForTestTemplate\n        )\n  }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/Manifest+Traits.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n// MARK: - Traits Validation\n\n/// Validator methods that check the correctness of traits and their support as defined in the manifest.\nextension Manifest {\n    /// Struct that contains information about a package's identity, as well as its name.\n    public struct PackageIdentifier: Hashable, CustomStringConvertible, Comparable, ExpressibleByStringLiteral {\n        public var identity: String\n        public var name: String?\n\n        public init(identity: PackageIdentity, name: String? = nil) {\n            self.init(identity: identity.description, name: name)\n        }\n\n        public init(identity: String, name: String? = nil) {\n            self.identity = identity\n            self.name = name\n        }\n\n        public init(_ parent: Manifest) {\n            self.identity = parent.packageIdentity.description\n            self.name = parent.displayName\n        }\n\n        public init(stringLiteral string: String) {\n            self.identity = string\n        }\n\n        public var description: String {\n            var result = \"'\\(identity)'\"\n            if let name {\n                result.append(\" (\\(name))\")\n            }\n            return result\n        }\n\n        public static func < (lhs: Manifest.PackageIdentifier, rhs: Manifest.PackageIdentifier) -> Bool {\n            lhs.identity < rhs.identity\n        }\n    }\n\n    /// Determines whether traits are supported for this Manifest.\n    public var supportsTraits: Bool {\n        !self.traits.isEmpty\n    }\n\n    /// Validates a trait by checking that it is defined in the manifest; if not, an error is thrown.\n    private func validateTrait(_ trait: TraitDescription) throws {\n        guard !trait.isDefault else {\n            if !supportsTraits {\n                throw TraitError.invalidTrait(\n                    package: .init(self),\n                    trait: .init(stringLiteral: trait.name),\n                    availableTraits: traits.map({ $0.name })\n                )\n            }\n\n            return\n        }\n\n        try self.validateTrait(EnabledTrait(stringLiteral: trait.name))\n    }\n\n    /// Validates a trait by checking that it is defined in the manifest; if not, an error is thrown.\n    private func validateTrait(_ trait: EnabledTrait) throws {\n        guard !trait.isDefault else {\n            if !supportsTraits {\n                throw TraitError.invalidTrait(\n                    package: .init(self),\n                    trait: trait,\n                    availableTraits: traits.map({ $0.name })\n                )\n            }\n\n            return\n        }\n\n        // Check if the passed trait is a valid trait.\n        if self.traits.first(where: { $0.name == trait.name }) == nil {\n            throw TraitError.invalidTrait(\n                package: .init(self),\n                trait: trait,\n                availableTraits: self.traits.map({ $0.name })\n            )\n        }\n    }\n\n    /// Validates a set of traits that is intended to be enabled for the manifest; if there are any discrepencies in the\n    /// set of enabled traits and whether the manifest defines these traits (or if it defines any traits at all), then an\n    /// error indicating the issue will be thrown.\n    private func validateEnabledTraits(_ explicitlyEnabledTraits: EnabledTraits) throws {\n        guard supportsTraits else {\n            if explicitlyEnabledTraits != [\"default\"] {\n                throw TraitError.traitsNotSupported(\n                    package: .init(self),\n                    explicitlyEnabledTraits: explicitlyEnabledTraits\n                )\n            }\n\n            return\n        }\n\n        let enabledTraits = explicitlyEnabledTraits\n\n        // Validate each trait to assure it's defined in the current package.\n        for trait in enabledTraits {\n           try validateTrait(trait)\n        }\n\n        let areDefaultsEnabled = enabledTraits.contains(\"default\")\n\n        // Ensure that disabling default traits is disallowed for packages that don't define any traits.\n        if !areDefaultsEnabled && !self.supportsTraits {\n            // We throw an error when default traits are disabled for a package without any traits\n            // This allows packages to initially move new API behind traits once.\n            throw TraitError.traitsNotSupported(\n                package: .init(self),\n                explicitlyEnabledTraits: enabledTraits\n            )\n        }\n    }\n\n    private func validateTraitConfiguration(_ traitConfiguration: TraitConfiguration) throws {\n        guard supportsTraits else {\n            switch traitConfiguration {\n            case .disableAllTraits:\n                throw TraitError.traitsNotSupported(\n                    package: .init(self),\n                    explicitlyEnabledTraits: .init([], setBy: .traitConfiguration)\n                )\n            case .enabledTraits(let traits):\n                throw TraitError.traitsNotSupported(\n                    package: .init(self),\n                    explicitlyEnabledTraits: EnabledTraits(traits, setBy: .traitConfiguration)\n                )\n            case .enableAllTraits, .default:\n                return\n            }\n        }\n\n        // Get the enabled traits; if the trait configuration's `.enabledTraits` returns nil,\n        // we know that it's the `.enableAllTraits` case, since the config does not store\n        // all the defined traits of the manifest itself.\n        let enabledTraits: EnabledTraits = traitConfiguration.enabledTraits ?? EnabledTraits(self.traits.map(\\.name), setBy: .traitConfiguration)\n\n        try validateEnabledTraits(enabledTraits)\n    }\n}\n\n\n// MARK: - Traits\n\n/// Helper methods to calculate states of the manifest and its dependencies when given a set of enabled traits.\nextension Manifest {\n    /// The default traits as defined in this package as the root.\n    public var defaultTraits: Set<String>? {\n        // First, guard against whether this package actually has traits.\n        guard self.supportsTraits else { return nil }\n        return Set(self.traits.filter(\\.isDefault).flatMap(\\.enabledTraits))\n    }\n\n    /// A map of trait names to the trait description.\n    public var traitsMap: [String: TraitDescription] {\n        self.traits.reduce(into: [String: TraitDescription]()) { traitsMap, trait in\n            traitsMap[trait.name] = trait\n        }\n    }\n\n    /// Calculates the set of all transitive traits that are enabled for this manifest using the passed trait configuration.\n    /// Since a trait configuration is only used for root packages, this method is intended for use with root packages only.\n    public func enabledTraits(using traitConfiguration: TraitConfiguration) throws -> EnabledTraits {\n        // If this manifest does not support traits, but the passed configuration either\n        // disables default traits or enables non-default traits (i.e. traits that would\n        // not exist for this manifest) then we must throw an error.\n        try validateTraitConfiguration(traitConfiguration)\n        guard supportsTraits, packageKind.isRoot else {\n            return [\"default\"]\n        }\n\n        var enabledTraits: EnabledTraits = []\n\n        switch traitConfiguration {\n        case .enableAllTraits:\n            enabledTraits = EnabledTraits(traits.map(\\.name), setBy: .traitConfiguration)\n        case .default:\n            if let defaultTraits = defaultTraits {\n                enabledTraits = EnabledTraits(defaultTraits, setBy: .default)\n            }\n        case .disableAllTraits:\n            return []\n        case .enabledTraits(let explicitlyEnabledTraits):\n            enabledTraits = EnabledTraits(explicitlyEnabledTraits, setBy: .traitConfiguration)\n        }\n\n        if let allEnabledTraits = try? self.enabledTraits(using: enabledTraits) {\n            enabledTraits = allEnabledTraits\n        }\n\n        return enabledTraits\n    }\n\n    /// Calculates the set of all transitive traits that are enabled for this manifest using the passed set of\n    /// explicitly enabled traits, and the parent package that defines the enabled traits for this package.\n    /// This method is intended for use with non-root packages.\n    public func enabledTraits(using explicitlyEnabledTraits: EnabledTraits = [\"default\"]) throws -> EnabledTraits {\n        // If this manifest does not support traits, but the passed configuration either\n        // disables default traits or enables non-default traits (i.e. traits that would\n        // not exist for this manifest) then we must throw an error.\n        try validateEnabledTraits(explicitlyEnabledTraits)\n        guard supportsTraits else {\n            return [\"default\"]\n        }\n\n        var enabledTraits: EnabledTraits = []\n\n        if let allEnabledTraits = try? calculateAllEnabledTraits(explicitlyEnabledTraits: explicitlyEnabledTraits) {\n            enabledTraits = allEnabledTraits\n        }\n\n        return enabledTraits\n    }\n\n    /// Determines if a trait is enabled with a given set of enabled traits.\n    public func isTraitEnabled(_ trait: TraitDescription, _ enabledTraits: EnabledTraits) throws -> Bool {\n        // First, check that the queried trait is valid.\n        try validateTrait(trait)\n        // Then, check that the list of enabled traits is valid.\n        try validateEnabledTraits(enabledTraits)\n\n        // Special case for dealing with whether a default trait is enabled.\n        guard !trait.isDefault else {\n            // Check that the manifest defines default traits; if so,\n            // determine whether the default traits are enabled.\n            if self.traits.contains(where: \\.isDefault) {\n                return enabledTraits.areDefaultsEnabled\n            }\n\n            // If manifest does not define default traits, then throw an invalid trait error.\n            throw TraitError.invalidTrait(\n                package: .init(self),\n                trait: EnabledTrait(stringLiteral: trait.name),\n                availableTraits: self.traits.map(\\.name)\n            )\n        }\n\n        guard supportsTraits else {\n            // If the above checks pass without throwing an error, then we simply return false\n            // if the manifest does not support traits.\n            return false\n        }\n\n        // Compute all transitively enabled traits.\n        let allEnabledTraits = try calculateAllEnabledTraits(explicitlyEnabledTraits: enabledTraits)\n\n        return allEnabledTraits.contains(trait.name)\n    }\n\n    /// Calculates and returns a set of all enabled traits, beginning with a set of explicitly enabled traits (which can either be the default traits of a manifest, or a configuration of enabled traits determined from a user-generated trait configuration) and determines which traits are transitively enabled.\n    private func calculateAllEnabledTraits(explicitlyEnabledTraits: EnabledTraits) throws -> EnabledTraits {\n        try validateEnabledTraits(explicitlyEnabledTraits)\n        // This the point where we flatten the enabled traits and resolve the recursive traits\n        var enabledTraits = explicitlyEnabledTraits\n        let areDefaultsEnabled = enabledTraits.remove(\"default\") != nil\n\n        // We have to enable all default traits if no traits are enabled or the defaults are explicitly enabled\n        if explicitlyEnabledTraits == [\"default\"] || areDefaultsEnabled {\n            if let defaultTraits {\n                let transitiveDefaultTraits = EnabledTraits(\n                    defaultTraits,\n                    setBy: .default\n                )\n                enabledTraits.formUnion(transitiveDefaultTraits)\n            }\n        }\n\n        // Initialize before loop to avoid recalculations of computed property\n        let traitsMap = traitsMap\n\n        // Iteratively flatten transitively enabled traits; stop when all transitive traits have been found.\n        while true {\n            // We are going to calculate which traits are actually enabled for a node here. To do this\n            // we have to check if default traits should be used and then flatten all the enabled traits.\n            let transitivelyEnabledTraits = try enabledTraits.flatMap { trait in\n                guard let traitDescription = traitsMap[trait.name] else {\n                    throw TraitError.invalidTrait(\n                        package: .init(self),\n                        trait: trait\n                    )\n                }\n                return EnabledTraits(\n                    traitDescription.enabledTraits,\n                    setBy: .trait(traitDescription.name)\n                )\n            }\n\n\n            let appendedList = enabledTraits.union(transitivelyEnabledTraits)\n            if appendedList.count == enabledTraits.count {\n                break\n            } else {\n                enabledTraits = appendedList\n            }\n        }\n\n        return enabledTraits\n    }\n\n    /// Computes the dependencies that are in use per target in this manifest.\n    private func usedTargetDependencies(withTraits enabledTraits: EnabledTraits) throws -> [String: Set<TargetDescription.Dependency>] {\n        let enabledTraits = try calculateAllEnabledTraits(explicitlyEnabledTraits: enabledTraits)\n        return self.targets.reduce(into: [String: Set<TargetDescription.Dependency>]()) { depMap, target in\n            let nonTraitDeps = target.dependencies.filter {\n                $0.condition?.traits?.isEmpty ?? true\n            }\n\n            let traitGuardedDeps = target.dependencies.filter { dep in\n                let traits = dep.condition?.traits ?? []\n\n                // For each trait that is a condition on this target dependency, assure that\n                // at least one is enabled in the manifest.\n                return !traits.intersection(enabledTraits.names).isEmpty\n            }\n\n            let deps = nonTraitDeps + traitGuardedDeps\n            depMap[target.name] = Set(deps)\n        }\n    }\n\n    /// Computes the set of package dependencies that are used by targets of this manifest.\n    public func usedDependencies(withTraits enabledTraits: EnabledTraits) throws -> (knownPackage: Set<String>, unknownPackage: Set<String>) {\n        let deps = try self.usedTargetDependencies(withTraits: enabledTraits)\n        .values\n        .flatMap { $0 }\n        .compactMap(\\.package)\n\n        var known: Set<String> = []\n        var unknown: Set<String> = []\n\n        for item in deps {\n            if let dep = self.packageDependency(referencedBy: item) {\n                known.insert(dep.identity.description)\n            } else if self.targetMap[item] == nil {\n                // Marking this dependency as tentatively used, given that we cannot find the package ref at this stage.\n                unknown.insert(item)\n            }\n        }\n\n        return (knownPackage: known, unknownPackage: unknown)\n    }\n\n    /// Computes the list of target dependencies per target that are guarded by traits.\n    /// A target dependency is considered potentially trait-guarded if it defines a condition wherein there exists a\n    /// list of traits.\n    /// - Parameters:\n    ///    - lowercasedKeys: A flag that determines whether the keys in the resulting dictionary are lowercased.\n    /// - Returns: A dictionary that maps the name of a `TargetDescription` to a list of its dependencies that are\n    /// guarded by traits.\n    public func traitGuardedTargetDependencies(\n        lowercasedKeys: Bool = false\n    ) -> [String: [TargetDescription.Dependency]] {\n        self.targets.reduce(into: [String: [TargetDescription.Dependency]]()) { depMap, target in\n            let traitGuardedTargetDependencies = traitGuardedTargetDependencies(\n                for: target\n            )\n\n            traitGuardedTargetDependencies.forEach {\n                guard let package = lowercasedKeys ? $0.key.package?.lowercased() : $0.key.package else { return }\n                depMap[package, default: []].append($0.key)\n            }\n        }\n    }\n\n    /// Computes the list of target dependencies that are guarded by traits for given target.\n    /// A target dependency is considered potentially trait-guarded if it defines a condition wherein there exists a\n    /// list of traits.\n    /// - Parameters:\n    ///    - target: A `TargetDescription` for which the trait-guarded target dependencies are calculated.\n    /// - Returns: A dictionary that maps each trait-guarded `TargetDescription.Dependency` of the given\n    /// `TargetDescription` to the list of traits that guard it.\n    public func traitGuardedTargetDependencies(for target: TargetDescription)\n        -> [TargetDescription.Dependency: Set<String>]\n    {\n        target.dependencies.filter {\n            !($0.condition?.traits?.isEmpty ?? true)\n        }.reduce(into: [TargetDescription.Dependency: Set<String>]()) { depMap, dep in\n            depMap[dep, default: []].formUnion(dep.condition?.traits ?? [])\n        }\n    }\n\n    /// Determines whether a target dependency is enabled given a set of enabled traits for this manifest.\n    public func isTargetDependencyEnabled(\n        target: String,\n        _ dependency: TargetDescription.Dependency,\n        enabledTraits: EnabledTraits,\n    ) throws -> Bool {\n        guard self.supportsTraits else { return true }\n        guard let target = self.targetMap[target] else { return false }\n        guard target.dependencies.contains(where: { $0 == dependency }) else {\n            throw InternalError(\n                \"target dependency \\(dependency.name) not found for target \\(target.name) in package \\(self.displayName)\"\n            )\n        }\n\n        let traitsToEnable = self.traitGuardedTargetDependencies(for: target)[dependency] ?? []\n\n        // Check if any of the traits guarding this dependency is enabled;\n        // if so, the condition is met and the target dependency is considered\n        // to be in an enabled state.\n        let isEnabled = try traitsToEnable.contains(where: { try self.isTraitEnabled(\n            .init(stringLiteral: $0),\n            enabledTraits,\n        ) })\n\n        return traitsToEnable.isEmpty || isEnabled\n    }\n\n    /// Determines whether a given package dependency is used by this manifest given a set of enabled traits.\n    public func isPackageDependencyUsed(_ dependency: PackageDependency, enabledTraits: EnabledTraits) throws -> Bool {\n        if self.pruneDependencies {\n            let usedDependencies = try self.usedDependencies(withTraits: enabledTraits)\n            let foundKnownPackage = usedDependencies.knownPackage.contains(where: {\n                $0.caseInsensitiveCompare(dependency.identity.description) == .orderedSame\n            })\n\n            // if there is a target dependency referenced by name and the package it originates from is unknown, default to\n            // tentatively marking the package dependency as used. to be resolved later on.\n            return foundKnownPackage || (!foundKnownPackage && !usedDependencies.unknownPackage.isEmpty)\n        } else {\n            return try !isPackageDependencyTraitGuarded(dependency, enabledTraits: enabledTraits)\n        }\n    }\n\n    /// Given a set of enabled traits, determine whether a package dependecy of this manifest is\n    /// guarded by traits.\n    private func isPackageDependencyTraitGuarded(_ dependency: PackageDependency, enabledTraits: EnabledTraits) throws -> Bool {\n        try validateEnabledTraits(enabledTraits)\n\n        let targetDependenciesForPackageDependency = self.targets.flatMap({ $0.dependencies })\n            .filter({\n            $0.package?.caseInsensitiveCompare(dependency.identity.description) == .orderedSame\n        })\n\n        // Determine whether the current set of enabled traits still gate the package dependency\n        // across targets.\n        let isTraitGuarded = targetDependenciesForPackageDependency.isEmpty ? false : targetDependenciesForPackageDependency.filter({ $0.condition?.traits != nil }).allSatisfy({ self.isTargetDependencyTraitGuarded($0, enabledTraits: enabledTraits)\n        })\n\n        // Since we only omit a package dependency that is only guarded by traits, determine\n        // whether this dependency is used elsewhere without traits.\n        let isUsedWithoutTraitGuarding = !targetDependenciesForPackageDependency.filter({ $0.condition?.traits == nil }).isEmpty\n\n        return !isUsedWithoutTraitGuarding && isTraitGuarded\n    }\n\n    private func isTargetDependencyTraitGuarded(\n        _ dependency: TargetDescription.Dependency,\n        enabledTraits: EnabledTraits\n    ) -> Bool {\n        guard let condition = dependency.condition, let traits = condition.traits else { return false }\n\n        return enabledTraits.intersection(traits).isEmpty\n    }\n}\n\n// MARK: - Trait Error\n\npublic enum TraitError: Swift.Error {\n    /// Indicates that an invalid trait was enabled.\n    case invalidTrait(\n        package: Manifest.PackageIdentifier,\n        trait: EnabledTrait,\n        availableTraits: [String] = []\n    )\n\n    /// Indicates that the manifest does not support traits, yet a method was called with a configuration of enabled\n    /// traits.\n    case traitsNotSupported(\n        package: Manifest.PackageIdentifier,\n        explicitlyEnabledTraits: EnabledTraits\n    )\n}\n\nextension TraitError: CustomStringConvertible {\n    private func generateSetterDescription(_ setters: EnabledTrait.Setters) -> String {\n        guard !setters.isEmpty else {\n            return \"\"\n        }\n\n        var result: String = \" enabled by\"\n        if setters.count == 1, let setter = setters.first {\n            result += \" \\(setter.description)\"\n        } else {\n            let parentPackages = setters.compactMap(\\.parentPackage).sorted()\n            let parentTraits = setters.compactMap(\\.parentTrait).sorted()\n            let traitConfiguration = setters.filter({ $0 == .traitConfiguration }).map(\\.description)\n\n            if !parentPackages.isEmpty {\n                result += \" parent package\"\n                result += parentPackages.count == 1 ? \" \" : \"s \"\n                result += parentPackages.map(\\.description).joined(separator: \", \")\n                result += !parentTraits.isEmpty || !traitConfiguration.isEmpty ? \";\" : \"\"\n            }\n            if !parentTraits.isEmpty {\n                result += \" trait\"\n                result += parentTraits.count == 1 ? \" \" : \"s \"\n                result += parentTraits.map(\\.description).joined(separator: \", \")\n                result += !traitConfiguration.isEmpty ? \";\" : \"\"\n            }\n            if !traitConfiguration.isEmpty {\n                result += \" a custom trait configuration declared for the root\"\n            }\n        }\n\n        return result\n    }\n\n    public var description: String {\n        switch self {\n        case .invalidTrait(let package, let trait, var availableTraits):\n            availableTraits = availableTraits.sorted()\n            var errorMsg = \"Trait '\\(trait)'\"\n            errorMsg += generateSetterDescription(trait.setters)\n            errorMsg += \" is not declared by package \\(package).\"\n            if availableTraits.isEmpty {\n                errorMsg += \" There are no available traits declared by this package.\"\n            } else {\n                errorMsg +=\n                    \" The available traits declared by this package are: \\(availableTraits.joined(separator: \", \")).\"\n            }\n            return errorMsg\n        case .traitsNotSupported(let package, let explicitlyEnabledTraits):\n            let parentPackages = Set(explicitlyEnabledTraits.compactMap(\\.parentPackages).flatMap({ $0 }))\n            let parent: Manifest.PackageIdentifier? = parentPackages.count == 1 ? parentPackages.first : nil\n            if explicitlyEnabledTraits.isEmpty {\n                if let parent = explicitlyEnabledTraits.disabledBy {\n                    return \"\"\"\n            Disabled default traits by \\(parent.description) on package \\(package) that declares no traits. This is prohibited to allow packages to adopt traits initially without causing an API break.\n            \"\"\"\n                } else {\n                    return \"\"\"\n            Disabled default traits on package \\(package) that declares no traits. This is prohibited to allow packages to adopt traits initially without causing an API break.\n            \"\"\"\n                }\n            } else {\n                if let parent {\n                    return \"\"\"\n                Package \\(parent) enables traits [\\(explicitlyEnabledTraits.joined(separator: \", \"))] on package \\(package) that declares no traits.\n                \"\"\"\n                } else {\n                    return \"\"\"\n                Traits [\\(explicitlyEnabledTraits.joined(separator: \", \"))] have been enabled on package \\(package) that declares no traits.\n                \"\"\"\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/Manifest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\nimport func TSCBasic.transitiveClosure\n\nimport struct TSCUtility.Version\n\n/// This contains the declarative specification loaded from package manifest\n/// files, and the tools for working with the manifest.\npublic final class Manifest: Sendable {\n    /// The standard filename for the manifest.\n    public static let filename = basename + \".swift\"\n\n    /// The standard basename for the manifest.\n    public static let basename = \"Package\"\n\n    /// The name of the package as it appears in the manifest\n    /// FIXME: deprecate this, there is no value in this once we have real package identifiers\n    public let displayName: String\n\n    /// The package identity.\n    public let packageIdentity: PackageIdentity\n\n    // FIXME: deprecate this, this is not part of the manifest information, we just use it as a container for this data\n    // FIXME: This doesn't belong here, we want the Manifest to be purely tied\n    // to the repository state, it shouldn't matter where it is.\n    //\n    /// The path of the manifest file.\n    // @available(*, deprecated)\n    public let path: AbsolutePath\n\n    // FIXME: deprecate this, this is not part of the manifest information, we just use it as a container for this data\n    // FIXME: This doesn't belong here, we want the Manifest to be purely tied\n    // to the repository state, it shouldn't matter where it is.\n    //\n    /// The repository URL the manifest was loaded from.\n    public let packageLocation: String\n\n    /// The canonical repository URL the manifest was loaded from.\n    public var canonicalPackageLocation: CanonicalPackageLocation {\n        CanonicalPackageLocation(self.packageLocation)\n    }\n\n    /// Whether kind of package this manifest is from.\n    public let packageKind: PackageReference.Kind\n\n    /// The version this package was loaded from, if known.\n    public let version: Version?\n\n    /// The revision this package was loaded from, if known.\n    public let revision: String?\n\n    /// The tools version declared in the manifest.\n    public let toolsVersion: ToolsVersion\n\n    /// The default localization for resources.\n    public let defaultLocalization: String?\n\n    /// The declared platforms in the manifest.\n    public let platforms: [PlatformDescription]\n\n    /// The declared package dependencies.\n    public let dependencies: [PackageDependency]\n\n    /// The targets declared in the manifest.\n    public let targets: [TargetDescription]\n\n    /// The targets declared in the manifest, keyed by their name.\n    public let targetMap: [String: TargetDescription]\n\n    /// The products declared in the manifest.\n    public let products: [ProductDescription]\n\n    /// The set of traits of this package.\n    public let traits: Set<TraitDescription>\n\n    /// The C language standard flag.\n    public let cLanguageStandard: String?\n\n    /// The C++ language standard flag.\n    public let cxxLanguageStandard: String?\n\n    /// The supported Swift language versions of the package.\n    public let swiftLanguageVersions: [SwiftLanguageVersion]?\n\n    /// The pkg-config name of a system package.\n    public let pkgConfig: String?\n\n    /// The system package providers of a system package.\n    public let providers: [SystemPackageProviderDescription]?\n\n    /// Targets required for building particular product filters.\n    private let _requiredTargets = ThreadSafeKeyValueStore<ProductFilter, [TargetDescription]>()\n\n    /// Dependencies required for building particular product filters.\n    private let _requiredDependencies = ThreadSafeKeyValueStore<ProductFilter, [PackageDependency]>()\n\n    public let pruneDependencies: Bool\n\n    public init(\n        displayName: String,\n        packageIdentity: PackageIdentity,\n        path: AbsolutePath,\n        packageKind: PackageReference.Kind,\n        packageLocation: String,\n        defaultLocalization: String?,\n        platforms: [PlatformDescription],\n        version: TSCUtility.Version?,\n        revision: String?,\n        toolsVersion: ToolsVersion,\n        pkgConfig: String?,\n        providers: [SystemPackageProviderDescription]?,\n        cLanguageStandard: String?,\n        cxxLanguageStandard: String?,\n        swiftLanguageVersions: [SwiftLanguageVersion]?,\n        dependencies: [PackageDependency] = [],\n        products: [ProductDescription] = [],\n        targets: [TargetDescription] = [],\n        traits: Set<TraitDescription>,\n        pruneDependencies: Bool = false\n    ) {\n        self.displayName = displayName\n        self.packageIdentity = packageIdentity\n        self.path = path\n        self.packageKind = packageKind\n        self.packageLocation = packageLocation\n        self.defaultLocalization = defaultLocalization\n        self.platforms = platforms\n        self.version = version\n        self.revision = revision\n        self.toolsVersion = toolsVersion\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.cLanguageStandard = cLanguageStandard\n        self.cxxLanguageStandard = cxxLanguageStandard\n        self.swiftLanguageVersions = swiftLanguageVersions\n        self.dependencies = dependencies\n        self.products = products\n        self.targets = targets\n        self.targetMap = Dictionary(targets.lazy.map { ($0.name, $0) }, uniquingKeysWith: { $1 })\n        self.traits = traits\n        self.pruneDependencies = pruneDependencies\n    }\n\n    /// Returns the targets required for a particular product filter.\n    public func targetsRequired(for productFilter: ProductFilter) -> [TargetDescription] {\n        #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n        // If we have already calculated it, returned the cached value.\n        if let targets = _requiredTargets[productFilter] {\n            return targets\n        } else {\n            let targets: [TargetDescription]\n            switch productFilter {\n            case .everything:\n                return self.targets\n            case .specific(let productFilter):\n                let products = self.products.filter { productFilter.contains($0.name) }\n                targets = self.targetsRequired(for: products)\n            }\n\n            self._requiredTargets[productFilter] = targets\n            return targets\n        }\n        #else\n        // using .nothing as cache key while ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION is false\n        if let targets = self._requiredTargets[.nothing] {\n            return targets\n        } else {\n            let targets = self.packageKind.isRoot ? self.targets : self.targetsRequired(for: self.products)\n            // using .nothing as cache key while ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION is false\n            self._requiredTargets[.nothing] = targets\n            return targets\n        }\n        #endif\n    }\n\n    /// Returns a list of dependencies that are being guarded by unenabled traits, given a set of enabled traits.\n    ///\n    /// If a trait that is guarding a dependency is enabled (and is reflected in the `enabledTraits` parameter) and\n    /// results in that dependency being used, then that dependency is not considered trait-guarded.\n    ///\n    /// For example:\n    ///\n    /// Consider a package dependency `Bar` that is present in the manifest, and the manifest defines the following\n    /// target:\n    /// `TargetDescription(name: \"Baz\", dependencies: [.product(name: \"Bar\", condition: .init(traits: [\"Trait1\"]))])`\n    ///\n    /// If we set the `enabledTraits` to be `[\"Trait1\"]`, then the list of dependencies guarded by traits would be `[]`.\n    /// Otherwise, if `enabledTraits` were `nil`, then the dependencies guarded by traits would be `[\"Bar\"]`.\n    public func dependenciesTraitGuarded(withEnabledTraits enabledTraits: EnabledTraits) -> [PackageDependency] {\n        guard supportsTraits else {\n            return []\n        }\n\n        let traitGuardedDeps = self.traitGuardedTargetDependencies(lowercasedKeys: true)\n        let explicitlyEnabledTraits = try? self.enabledTraits(using: enabledTraits)\n\n        guard self.toolsVersion >= .v5_2 && !self.packageKind.isRoot else {\n            let deps = self.dependencies.filter {\n                var result = false\n                for guardedTargetDeps in traitGuardedDeps[$0.identity.description] ?? [] {\n                    if let guardTraits = guardedTargetDeps.condition?.traits, !guardTraits.isEmpty,\n                       let explicitlyEnabledTraits\n                    {\n                        result = result || !guardTraits.allSatisfy { explicitlyEnabledTraits.contains($0) }\n                    }\n                }\n\n                return result\n            }\n            return deps\n        }\n\n        if let dependencies = self._requiredDependencies[.nothing] {\n            let deps = dependencies.filter {\n                var result = false\n                for guardedTargetDeps in traitGuardedDeps[$0.identity.description] ?? [] {\n                    if let guardTraits = guardedTargetDeps.condition?.traits, !guardTraits.isEmpty,\n                       let explicitlyEnabledTraits\n                    {\n                        result = result || !guardTraits.allSatisfy { explicitlyEnabledTraits.contains($0) }\n                    }\n                }\n\n                return result\n            }\n            return deps\n        } else {\n            var guardedDependencies: Set<PackageIdentity> = []\n            for target in self.targetsRequired(for: self.products) {\n                let traitGuardedTargetDeps = traitGuardedTargetDependencies(for: target)\n\n                for targetDependency in target.dependencies {\n                    guard let dependency = self.packageDependency(referencedBy: targetDependency),\n                          let guardingTraits = traitGuardedTargetDeps[targetDependency]\n                    else {\n                        continue\n                    }\n\n                    if guardingTraits.intersection(enabledTraits.names) != guardingTraits\n                    {\n                        guardedDependencies.insert(dependency.identity)\n                    }\n                }\n\n                // Since plugins cannot specify traits as a guarding condition, we can skip them.\n            }\n\n            let dependencies = self.dependencies.filter { guardedDependencies.contains($0.identity) }\n            return dependencies\n        }\n    }\n\n    /// Returns the package dependencies required for a particular products filter and trait configuration.\n    public func dependenciesRequired(\n        for productFilter: ProductFilter,\n        _ enabledTraits: EnabledTraits = [\"default\"]\n    ) throws -> [PackageDependency] {\n        #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n        // If we have already calculated it, returned the cached value.\n        if let dependencies = self._requiredDependencies[productFilter] {\n            return dependencies\n        } else {\n            let targets = self.targetsRequired(for: productFilter)\n            let dependencies = self.dependenciesRequired(\n                for: targets,\n                keepUnused: productFilter == .everything,\n                traitConfiguration\n            )\n            self._requiredDependencies[productFilter] = dependencies\n            return dependencies\n        }\n        #else\n\n        guard self.toolsVersion >= .v5_2 && !self.packageKind.isRoot else {\n            var dependencies = self.dependencies\n                dependencies = try dependencies.filter({\n                    let isUsed = try self.isPackageDependencyUsed($0, enabledTraits: enabledTraits)\n                    return isUsed\n                })\n            return dependencies\n        }\n\n        // using .nothing as cache key while ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION is false\n        if var dependencies = self._requiredDependencies[.nothing] {\n                dependencies = try dependencies.filter({\n                    return try self.isPackageDependencyUsed($0, enabledTraits: enabledTraits)\n                })\n            return dependencies\n        } else {\n            var requiredDependencies: Set<PackageIdentity> = []\n            for target in self.targetsRequired(for: self.products) {\n                for targetDependency in target.dependencies {\n                    guard try self.isTargetDependencyEnabled(\n                        target: target.name,\n                        targetDependency,\n                        enabledTraits: enabledTraits\n                    ) else { continue }\n                    if let dependency = self.packageDependency(referencedBy: targetDependency) {\n                        requiredDependencies.insert(dependency.identity)\n                    }\n                }\n\n                target.pluginUsages?.forEach {\n                    if let dependency = self.packageDependency(referencedBy: $0) {\n                        requiredDependencies.insert(dependency.identity)\n                    }\n                }\n            }\n\n            let dependencies = self.dependencies.filter { requiredDependencies.contains($0.identity) }\n            // using .nothing as cache key while ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION is false\n            self._requiredDependencies[.nothing] = dependencies\n            return dependencies\n        }\n        #endif\n    }\n\n    /// Returns the targets required for building the provided products.\n    public func targetsRequired(for products: [ProductDescription]) -> [TargetDescription] {\n        let productsByName = Dictionary(products.map { ($0.name, $0) }, uniquingKeysWith: { $1 })\n        let targetsByName = Dictionary(targets.map { ($0.name, $0) }, uniquingKeysWith: { $1 })\n        let productTargetNames = products.flatMap(\\.targets)\n\n        let dependentTargetNames = transitiveClosure(productTargetNames, successors: { targetName in\n\n            if let target = targetsByName[targetName] {\n                let dependencies: [String] = target.dependencies.compactMap { dependency in\n                    switch dependency {\n                    case .target(let name, _),\n                         .byName(let name, _):\n                        targetsByName.keys.contains(name) ? name : nil\n                    default:\n                        nil\n                    }\n                }\n\n                let plugins: [String] = target.pluginUsages?.compactMap { pluginUsage in\n                    switch pluginUsage {\n                    case .plugin(name: let name, package: nil):\n                        if targetsByName.keys.contains(name) {\n                            name\n                        } else if let targetName = productsByName[name]?.targets.first {\n                            targetName\n                        } else {\n                            nil\n                        }\n                    default:\n                        nil\n                    }\n                } ?? []\n\n                return dependencies + plugins\n            }\n\n            return []\n\n        })\n\n        let requiredTargetNames = Set(productTargetNames).union(dependentTargetNames)\n        let requiredTargets = requiredTargetNames.compactMap { targetsByName[$0] }\n        return requiredTargets\n    }\n\n    /// Returns the package dependencies required for building the provided targets.\n    ///\n    /// The returned dependencies have their particular product filters registered. (To determine product filters\n    /// without removing any dependencies from the list, specify `keepUnused: true`.)\n    private func dependenciesRequired(\n        for targets: [TargetDescription],\n        keepUnused: Bool = false\n    ) -> [PackageDependency] {\n        var registry: (known: [PackageIdentity: ProductFilter], unknown: Set<String>) = ([:], [])\n        let availablePackages = Set(self.dependencies.lazy.map(\\.identity))\n\n        for target in targets {\n            for targetDependency in target.dependencies {\n                self.register(\n                    targetDependency: targetDependency,\n                    registry: &registry,\n                    availablePackages: availablePackages\n                )\n            }\n            for requiredPlugIn in target.pluginUsages ?? [] {\n                self.register(requiredPlugIn: requiredPlugIn, registry: &registry, availablePackages: availablePackages)\n            }\n        }\n\n        // Products whose package could not be determined are marked as needed on every dependency.\n        // (This way none of them filters such a product out.)\n        var associations = registry.known\n        let unknown = registry.unknown\n        if !registry.unknown.isEmpty {\n            for package in availablePackages {\n                associations[package, default: .nothing].formUnion(.specific(unknown))\n            }\n        }\n\n        return self.dependencies.compactMap { dependency in\n            if let filter = associations[dependency.identity] {\n                dependency.filtered(by: filter)\n            } else if keepUnused {\n                // Register that while the dependency was kept, no products are needed.\n                dependency.filtered(by: .nothing)\n            } else {\n                // Dependencies known to not have any relevant products are discarded.\n                nil\n            }\n        }\n    }\n\n    /// Finds the package dependency referenced by the specified target dependency.\n    /// - Returns: Returns `nil` if the dependency is a target dependency, if it is a product dependency but has no\n    /// package name (for tools versions less than 5.2), or if there were no dependencies with the provided name.\n    public func packageDependency(\n        referencedBy targetDependency: TargetDescription.Dependency\n    ) -> PackageDependency? {\n        let packageName: String\n\n        switch targetDependency {\n        case .product(_, package: let name?, _, _),\n             .byName(name: let name, _):\n            packageName = name\n        default:\n            return nil\n        }\n\n        return self.packageDependency(referencedBy: packageName)\n    }\n\n    /// Finds the package dependency referenced by the specified plugin usage.\n    /// - Returns: Returns `nil` if  the used plugin is from the same package or if the package the used plugin is from\n    /// cannot be found.\n    public func packageDependency(\n        referencedBy pluginUsage: TargetDescription.PluginUsage\n    ) -> PackageDependency? {\n        switch pluginUsage {\n        case .plugin(_, .some(let package)):\n            self.packageDependency(referencedBy: package)\n        default:\n            nil\n        }\n    }\n\n    internal func packageDependency(\n        referencedBy packageName: String\n    ) -> PackageDependency? {\n        self.dependencies.first(where: {\n            // rdar://80594761 make sure validation is case insensitive\n            $0.nameForModuleDependencyResolutionOnly.lowercased() == packageName.lowercased()\n        })\n    }\n\n    /// Returns the package identity referred to by a target dependency string.\n    ///\n    /// This first checks if any declared package names (from 5.2) match.\n    /// If none is found, it is assumed that the string is the package identity itself\n    /// (although it may actually be a dangling reference diagnosed later).\n    private func packageIdentity(referencedBy packageName: String) -> PackageIdentity {\n        self.packageDependency(referencedBy: packageName)?.identity\n            ?? .plain(packageName)\n    }\n\n    /// Registers a required product with a particular dependency if possible, or registers it as unknown.\n    ///\n    /// - Parameters:\n    ///   - targetDependency: The target dependency to register.\n    ///   - registry: The registry in which to record the association.\n    ///   - availablePackages: The set of available packages.\n    private func register(\n        targetDependency: TargetDescription.Dependency,\n        registry: inout (known: [PackageIdentity: ProductFilter], unknown: Set<String>),\n        availablePackages: Set<PackageIdentity>\n    ) {\n        switch targetDependency {\n        case .target:\n            break\n        case .product(let product, let package, _, _):\n            if let package { // ≥ 5.2\n                if !self.register(\n                    product: product,\n                    inPackage: self.packageIdentity(referencedBy: package),\n                    registry: &registry.known,\n                    availablePackages: availablePackages\n                ) {\n                    // This is an invalid manifest condition diagnosed later. (No such package.)\n                    // Treating it as unknown gracefully allows resolution to continue for now.\n                    registry.unknown.insert(product)\n                }\n            } else { // < 5.2\n                registry.unknown.insert(product)\n            }\n        case .byName(let product, _):\n            if self.toolsVersion < .v5_2 {\n                // A by‐name entry might be a product from anywhere.\n                if self.targets.contains(where: { $0.name == product }) {\n                    // Save the resolver some effort if it is known to only be a target anyway.\n                    break\n                } else {\n                    registry.unknown.insert(product)\n                }\n            } else { // ≥ 5.2\n                // If a by‐name entry is a product, it must be in a package of the same name.\n                if !self.register(\n                    product: product,\n                    inPackage: self.packageIdentity(referencedBy: product),\n                    registry: &registry.known,\n                    availablePackages: availablePackages\n                ) {\n                    // If it doesn’t match a package, it should be a target, not a product.\n                    if self.targets.contains(where: { $0.name == product }) {\n                        break\n                    } else {\n                        // But in case the user is trying to reference a product,\n                        // we still need to pass on the invalid reference\n                        // so that the resolver fetches all dependencies\n                        // in order to provide the diagnostic pass with the information it needs.\n                        registry.unknown.insert(product)\n                    }\n                }\n            }\n        }\n    }\n\n    /// Registers a required plug‐in with a particular dependency if possible, or registers it as unknown.\n    ///\n    /// - Parameters:\n    ///   - requiredPlugIn: The plug‐in to register.\n    ///   - registry: The registry in which to record the association.\n    ///   - availablePackages: The set of available packages.\n    private func register(\n        requiredPlugIn: TargetDescription.PluginUsage,\n        registry: inout (known: [PackageIdentity: ProductFilter], unknown: Set<String>),\n        availablePackages: Set<PackageIdentity>\n    ) {\n        switch requiredPlugIn {\n        case .plugin(let name, let package):\n            if let package {\n                if !self.register(\n                    product: name,\n                    inPackage: self.packageIdentity(referencedBy: package),\n                    registry: &registry.known,\n                    availablePackages: availablePackages\n                ) {\n                    // Invalid, diagnosed later; see the dependency version of this method.\n                    registry.unknown.insert(name)\n                }\n            } else {\n                // The plug‐in is in the same package.\n                break\n            }\n        }\n    }\n\n    /// Registers a required product with a particular dependency if possible.\n    ///\n    /// - Parameters:\n    ///   - product: The product to try registering.\n    ///   - package: The package to try associating it with.\n    ///   - registry: The registry in which to record the association.\n    ///   - availablePackages: The set of available packages.\n    ///\n    /// - Returns: `true` if the particular dependency was found and the product was registered; `false` if no matching\n    /// dependency was found and the product has not yet been handled.\n    private func register(\n        product: String,\n        inPackage package: PackageIdentity,\n        registry: inout [PackageIdentity: ProductFilter],\n        availablePackages: Set<PackageIdentity>\n    ) -> Bool {\n        if let existing = registry[package] {\n            registry[package] = existing.union(.specific([product]))\n            return true\n        } else if availablePackages.contains(package) {\n            registry[package] = .specific([product])\n            return true\n        } else {\n            return false\n        }\n    }\n\n    /// Returns a list of target descriptions whose root source directory is the same as that for the given type.\n    public func targetsWithCommonSourceRoot(type: TargetDescription.TargetKind) -> [TargetDescription] {\n        switch type {\n        case .test:\n            self.targets.filter { $0.type == .test }\n        case .plugin:\n            self.targets.filter { $0.type == .plugin }\n        default:\n            self.targets.filter { $0.type != .test && $0.type != .plugin }\n        }\n    }\n\n    /// Returns true if the tools version is >= 5.9 and the number of targets with a common source root is 1.\n    public func shouldSuggestRelaxedSourceDir(type: TargetDescription.TargetKind) -> Bool {\n        guard self.toolsVersion >= .v5_9 else {\n            return false\n        }\n        return self.targetsWithCommonSourceRoot(type: type).count == 1\n    }\n}\n\nextension Manifest: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n\n    public static func == (lhs: Manifest, rhs: Manifest) -> Bool {\n        ObjectIdentifier(lhs) == ObjectIdentifier(rhs)\n    }\n}\n\nextension Manifest: CustomStringConvertible {\n    public var description: String {\n        \"<Manifest: \\(self.displayName)>\"\n    }\n}\n\nextension Manifest: Encodable {\n    private enum CodingKeys: CodingKey {\n        case name, path, url, version, targetMap, toolsVersion,\n             pkgConfig, providers, cLanguageStandard, cxxLanguageStandard, swiftLanguageVersions,\n             dependencies, products, targets, traits, platforms, packageKind, revision,\n             defaultLocalization\n    }\n\n    /// Coding user info key for dump-package command.\n    ///\n    /// Presence of this key will hide some keys when encoding the Manifest object.\n    public static let dumpPackageKey: CodingUserInfoKey = .init(rawValue: \"dumpPackage\")!\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        try container.encode(self.displayName, forKey: .name)\n\n        // Hide the keys that users shouldn't see when\n        // we're encoding for the dump-package command.\n        if encoder.userInfo[Manifest.dumpPackageKey] == nil {\n            try container.encode(self.path, forKey: .path)\n            try container.encode(self.packageLocation, forKey: .url)\n            try container.encode(self.version, forKey: .version)\n            try container.encode(self.targetMap, forKey: .targetMap)\n        }\n\n        try container.encode(self.toolsVersion, forKey: .toolsVersion)\n        try container.encode(self.defaultLocalization, forKey: .defaultLocalization)\n        try container.encode(self.pkgConfig, forKey: .pkgConfig)\n        try container.encode(self.providers, forKey: .providers)\n        try container.encode(self.cLanguageStandard, forKey: .cLanguageStandard)\n        try container.encode(self.cxxLanguageStandard, forKey: .cxxLanguageStandard)\n        try container.encode(self.swiftLanguageVersions, forKey: .swiftLanguageVersions)\n        try container.encode(self.dependencies, forKey: .dependencies)\n        try container.encode(self.products, forKey: .products)\n        try container.encode(self.targets, forKey: .targets)\n        try container.encode(self.traits, forKey: .traits)\n        try container.encode(self.platforms, forKey: .platforms)\n        try container.encode(self.packageKind, forKey: .packageKind)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/PackageConditionDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Represents a manifest condition.\npublic struct PackageConditionDescription: Codable, Hashable, Sendable {\n    public let platformNames: [String]\n    public let config: String?\n    public let traits: Set<String>?\n\n    public init(platformNames: [String] = [], config: String? = nil, traits: Set<String>? = nil) {\n        assert(!(platformNames.isEmpty && config == nil && traits == nil))\n        self.platformNames = platformNames\n        self.config = config\n        self.traits = traits\n    }\n}\n\n/// One of possible conditions used in package manifests to restrict modules from being built for certain platforms or\n/// build configurations.\npublic enum PackageCondition: Hashable, Sendable {\n    case platforms(PlatformsCondition)\n    case configuration(ConfigurationCondition)\n    case traits(TraitCondition)\n\n    public func satisfies(_ environment: BuildEnvironment) -> Bool {\n        switch self {\n        case .configuration(let configuration):\n            return configuration.satisfies(environment)\n        case .platforms(let platforms):\n            return platforms.satisfies(environment)\n        case .traits(let traits):\n            return traits.satisfies(environment)\n        }\n    }\n\n    public var platformsCondition: PlatformsCondition? {\n        guard case let .platforms(platformsCondition) = self else {\n            return nil\n        }\n\n        return platformsCondition\n    }\n\n    public var configurationCondition: ConfigurationCondition? {\n        guard case let .configuration(configurationCondition) = self else {\n            return nil\n        }\n\n        return configurationCondition\n    }\n\n    public var traitCondition: TraitCondition? {\n        guard case let .traits(traitCondition) = self else {\n            return nil\n        }\n\n        return traitCondition\n    }\n\n    public init(platforms: [Platform]) {\n        self = .platforms(.init(platforms: platforms))\n    }\n\n    public init(configuration: BuildConfiguration) {\n        self = .configuration(.init(configuration: configuration))\n    }\n}\n\n/// Platforms condition implies that an assignment is valid on these platforms.\npublic struct PlatformsCondition: Hashable, Sendable {\n    public let platforms: [Platform]\n\n    public init(platforms: [Platform]) {\n        assert(!platforms.isEmpty, \"List of platforms should not be empty\")\n        self.platforms = platforms\n    }\n\n    public func satisfies(_ environment: BuildEnvironment) -> Bool {\n        platforms.contains(environment.platform)\n    }\n}\n\n/// A mini version of target platform constraints that will eventually be user specifiable..\n/// For now used to mark modules host only that are only accessed by macros and plugins.\npublic enum PlatformConstraint {\n    case all\n    case host\n}\n\n/// A configuration condition implies that an assignment is valid on\n/// a particular build configuration.\npublic struct ConfigurationCondition: Hashable, Sendable {\n    public let configuration: BuildConfiguration\n\n    public init(configuration: BuildConfiguration) {\n        self.configuration = configuration\n    }\n\n    public func satisfies(_ environment: BuildEnvironment) -> Bool {\n        if environment.configuration == nil {\n            return true\n        } else {\n            return configuration == environment.configuration\n        }\n    }\n}\n\n\n/// A configuration condition implies that an assignment is valid on\n/// a particular build configuration.\npublic struct TraitCondition: Hashable, Sendable {\n    public let traits: Set<String>\n\n    public init(traits: Set<String>) {\n        self.traits = traits\n    }\n\n    public func satisfies(_ environment: BuildEnvironment) -> Bool {\n        return true\n    }\n}\n\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/PackageDependencyDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Basics\n\nimport struct TSCBasic.CodableRange\n\nimport struct TSCUtility.Version\n\n/// Represents a package dependency.\npublic enum PackageDependency: Equatable, Hashable, Sendable {\n    /// A struct representing an enabled trait of a dependency.\n    public struct Trait: Hashable, Sendable, Codable, ExpressibleByStringLiteral {\n        /// A condition that limits the application of a dependencies trait.\n        package struct Condition: Hashable, Sendable, Codable {\n            /// The set of traits of this package that enable the dependency's trait.\n            package let traits: Set<String>?\n\n            public init(traits: Set<String>?) {\n                self.traits = traits\n            }\n\n            public func isSatisfied(by enabledTraits: Set<String>) -> Bool {\n                // If there are no traits in this condition, default to true.\n                guard let traits else { return true }\n                return !traits.intersection(enabledTraits).isEmpty\n            }\n        }\n\n        /// The name of the enabled trait.\n        package var name: String\n\n        /// The condition under which the trait is enabled.\n        package var condition: Condition?\n\n        /// Initializes a new enabled trait.\n        ///\n        /// - Parameters:\n        ///   - name: The name of the enabled trait.\n        ///   - condition: The condition under which the trait is enabled.\n        package init(\n            name: String,\n            condition: Condition? = nil\n        ) {\n            self.name = name\n            self.condition = condition\n        }\n\n        public init(stringLiteral value: StringLiteralType) {\n            self.init(name: value)\n        }\n\n        /// Initializes a new enabled trait.\n        ///\n        /// - Parameters:\n        ///   - name: The name of the enabled trait.\n        ///   - condition: The condition under which the trait is enabled.\n        package static func trait(\n            name: String,\n            condition: Condition? = nil\n        ) -> Trait {\n            self.init(\n                name: name,\n                condition: condition\n            )\n        }\n\n        // represents `.defaults`\n        public var isDefaultsCase: Bool {\n            name == \"default\" && condition == nil\n        }\n\n        /// Determines whether this trait's condition would be met by a set of enabled traits,\n        /// therefore enabling this trait.\n        /// Defaults to true if there is no condition to be satisfied.\n        ///\n        /// - Parameters:\n        /// - traits: A list of enabled traits.\n        public func isEnabled(by traits: EnabledTraits) -> Bool {\n            guard let condition else { return true }\n\n            return condition.isSatisfied(by: traits.names)\n        }\n    }\n\n    case fileSystem(FileSystem)\n    case sourceControl(SourceControl)\n    case registry(Registry)\n    \n    public struct FileSystem: Equatable, Hashable, Encodable, Sendable {\n        public let identity: PackageIdentity\n        public let nameForTargetDependencyResolutionOnly: String?\n        public let path: AbsolutePath\n        public let productFilter: ProductFilter\n        package let traits: Set<Trait>?\n    }\n\n    public struct SourceControl: Equatable, Hashable, Encodable, Sendable {\n        public let identity: PackageIdentity\n        public let nameForTargetDependencyResolutionOnly: String?\n        public let location: Location\n        public let requirement: Requirement\n        public let productFilter: ProductFilter\n        package let traits: Set<Trait>?\n\n        public enum Requirement: Equatable, Hashable, Sendable {\n            case exact(Version)\n            case range(Range<Version>)\n            case revision(String)\n            case branch(String)\n        }\n\n        public enum Location: Equatable, Hashable, Sendable {\n            case local(AbsolutePath)\n            case remote(SourceControlURL)\n        }\n    }\n\n    public struct Registry: Equatable, Hashable, Encodable, Sendable {\n        public let identity: PackageIdentity\n        public let requirement: Requirement\n        public let productFilter: ProductFilter\n        package let traits: Set<Trait>?\n\n        /// The dependency requirement.\n        public enum Requirement: Equatable, Hashable, Sendable {\n            case exact(Version)\n            case range(Range<Version>)\n        }\n    }\n\n    /// Describes the traits that are enabled for this package, and overrides this dependency's manifest's\n    /// default traits.\n    package var traits: Set<Trait>? {\n        switch self {\n        case .fileSystem(let settings):\n            return settings.traits\n        case .sourceControl(let settings):\n            return settings.traits\n        case .registry(let settings):\n            return settings.traits\n        }\n    }\n\n    public var identity: PackageIdentity {\n        switch self {\n        case .fileSystem(let settings):\n            return settings.identity\n        case .sourceControl(let settings):\n            return settings.identity\n        case .registry(let settings):\n            return settings.identity\n        }\n    }\n\n    // FIXME: we should simplify target based dependencies such that this is no longer required\n    // A name to be used *only* for target dependencies resolution\n    public var nameForModuleDependencyResolutionOnly: String {\n        switch self {\n        case .fileSystem(let settings):\n            return settings.nameForTargetDependencyResolutionOnly ?? PackageIdentityParser.computeDefaultName(fromPath: settings.path)\n        case .sourceControl(let settings):\n            switch settings.location {\n            case .local(let path):\n                return settings.nameForTargetDependencyResolutionOnly ?? PackageIdentityParser.computeDefaultName(fromPath: path)\n            case .remote(let url):\n                return settings.nameForTargetDependencyResolutionOnly ?? PackageIdentityParser.computeDefaultName(fromURL: url)\n            }\n        case .registry:\n            return self.identity.description.lowercased()\n        }\n    }\n\n    // FIXME: we should simplify target based dependencies such that this is no longer required\n    // A name to be used *only* for target dependencies resolution\n    public var explicitNameForModuleDependencyResolutionOnly: String? {\n        switch self {\n        case .fileSystem(let settings):\n            return settings.nameForTargetDependencyResolutionOnly\n        case .sourceControl(let settings):\n            return settings.nameForTargetDependencyResolutionOnly\n        case .registry:\n            return nil\n        }\n    }\n\n    public var productFilter: ProductFilter {\n        switch self {\n        case .fileSystem(let settings):\n            return settings.productFilter\n        case .sourceControl(let settings):\n            return settings.productFilter\n        case .registry(let settings):\n            return settings.productFilter\n        }\n    }\n\n    public func filtered(by productFilter: ProductFilter) -> Self {\n        switch self {\n        case .fileSystem(let settings):\n            return .fileSystem(\n                identity: settings.identity,\n                nameForTargetDependencyResolutionOnly: settings.nameForTargetDependencyResolutionOnly,\n                path: settings.path,\n                productFilter: productFilter,\n                traits: settings.traits\n            )\n        case .sourceControl(let settings):\n            return .sourceControl(\n                identity: settings.identity,\n                nameForTargetDependencyResolutionOnly: settings.nameForTargetDependencyResolutionOnly,\n                location: settings.location,\n                requirement: settings.requirement,\n                productFilter: productFilter,\n                traits: settings.traits\n            )\n        case .registry(let settings):\n            return .registry(\n                identity: settings.identity,\n                requirement: settings.requirement,\n                productFilter: productFilter,\n                traits: settings.traits\n            )\n        }\n    }\n\n    public static func fileSystem(\n        identity: PackageIdentity,\n        nameForTargetDependencyResolutionOnly: String?,\n        path: AbsolutePath,\n        productFilter: ProductFilter\n    ) -> Self {\n        .fileSystem(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: nameForTargetDependencyResolutionOnly,\n            path: path,\n            productFilter: productFilter,\n            traits: nil\n        )\n    }\n\n    public static func fileSystem(\n        identity: PackageIdentity,\n        nameForTargetDependencyResolutionOnly: String?,\n        path: AbsolutePath,\n        productFilter: ProductFilter,\n        traits: Set<Trait>?\n    ) -> Self {\n        .fileSystem(\n            .init(\n                identity: identity,\n                nameForTargetDependencyResolutionOnly: nameForTargetDependencyResolutionOnly,\n                path: path,\n                productFilter: productFilter,\n                traits: traits\n            )\n        )\n    }\n\n    public static func localSourceControl(\n        identity: PackageIdentity,\n        nameForTargetDependencyResolutionOnly: String?,\n        path: AbsolutePath,\n        requirement: SourceControl.Requirement,\n        productFilter: ProductFilter\n    ) -> Self {\n        .localSourceControl(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: nameForTargetDependencyResolutionOnly,\n            path: path,\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: nil\n        )\n    }\n\n    public static func localSourceControl(\n        identity: PackageIdentity,\n        nameForTargetDependencyResolutionOnly: String?,\n        path: AbsolutePath,\n        requirement: SourceControl.Requirement,\n        productFilter: ProductFilter,\n        traits: Set<Trait>?\n    ) -> Self {\n        .sourceControl(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: nameForTargetDependencyResolutionOnly,\n            location: .local(path),\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: traits\n        )\n    }\n    \n    public static func remoteSourceControl(\n        identity: PackageIdentity,\n        nameForTargetDependencyResolutionOnly: String?,\n        url: SourceControlURL,\n        requirement: SourceControl.Requirement,\n        productFilter: ProductFilter\n    ) -> Self {\n        .remoteSourceControl(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: nameForTargetDependencyResolutionOnly,\n            url: url,\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: nil\n        )\n    }\n\n    public static func remoteSourceControl(\n        identity: PackageIdentity,\n        nameForTargetDependencyResolutionOnly: String?,\n        url: SourceControlURL,\n        requirement: SourceControl.Requirement,\n        productFilter: ProductFilter,\n        traits: Set<Trait>?\n    ) -> Self {\n        .sourceControl(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: nameForTargetDependencyResolutionOnly,\n            location: .remote(url),\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: traits\n        )\n    }\n\n    public static func sourceControl(\n        identity: PackageIdentity,\n        nameForTargetDependencyResolutionOnly: String?,\n        location: SourceControl.Location,\n        requirement: SourceControl.Requirement,\n        productFilter: ProductFilter\n    ) -> Self {\n        .sourceControl(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: nameForTargetDependencyResolutionOnly,\n            location: location,\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: nil\n        )\n    }\n\n    public static func sourceControl(\n        identity: PackageIdentity,\n        nameForTargetDependencyResolutionOnly: String?,\n        location: SourceControl.Location,\n        requirement: SourceControl.Requirement,\n        productFilter: ProductFilter,\n        traits: Set<Trait>?\n    ) -> Self {\n        .sourceControl(\n            .init(\n                identity: identity,\n                nameForTargetDependencyResolutionOnly: nameForTargetDependencyResolutionOnly,\n                location: location,\n                requirement: requirement,\n                productFilter: productFilter,\n                traits: traits\n            )\n        )\n    }\n\n    public static func registry(\n        identity: PackageIdentity,\n        requirement: Registry.Requirement,\n        productFilter: ProductFilter\n    ) -> Self {\n        .registry(\n            identity: identity,\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: nil\n        )\n    }\n\n    public static func registry(\n        identity: PackageIdentity,\n        requirement: Registry.Requirement,\n        productFilter: ProductFilter,\n        traits: Set<Trait>?\n    ) -> Self {\n        .registry(\n            .init(\n                identity: identity,\n                requirement: requirement,\n                productFilter: productFilter,\n                traits: traits\n            )\n        )\n    }\n}\n\nextension Range {\n    public static func upToNextMajor(from version: Version) -> Range<Bound> where Bound == Version {\n        return version ..< Version(version.major + 1, 0, 0)\n    }\n\n    public static func upToNextMinor(from version: Version) -> Range<Bound> where Bound == Version {\n        return version ..< Version(version.major, version.minor + 1, 0)\n    }\n}\n\nextension PackageDependency: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .fileSystem(let data):\n            return \"fileSystem[\\(data)]\"\n        case .sourceControl(let data):\n            return \"sourceControl[\\(data)]\"\n        case .registry(let data):\n            return \"registry[\\(data)]\"\n        }\n    }\n}\n\nextension PackageDependency.SourceControl.Requirement: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .exact(let version):\n            return version.description\n        case .range(let range):\n            return range.description\n        case .revision(let revision):\n            return \"revision[\\(revision)]\"\n        case .branch(let branch):\n            return \"branch[\\(branch)]\"\n        }\n    }\n}\n\nextension PackageDependency.Registry.Requirement: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .exact(let version):\n            return version.description\n        case .range(let range):\n            return range.description\n        }\n    }\n}\n\nextension PackageDependency: Encodable {\n    private enum CodingKeys: String, CodingKey {\n        case local, fileSystem, scm, sourceControl, registry\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .fileSystem(let settings):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .fileSystem)\n            try unkeyedContainer.encode(settings)\n        case .sourceControl(let settings):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .sourceControl)\n            try unkeyedContainer.encode(settings)\n        case .registry(let settings):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .registry)\n            try unkeyedContainer.encode(settings)\n        }\n    }\n}\n\nextension PackageDependency.SourceControl.Requirement: Encodable {\n    private enum CodingKeys: String, CodingKey {\n        case exact, range, revision, branch\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case let .exact(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .exact)\n            try unkeyedContainer.encode(a1)\n        case let .range(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .range)\n            try unkeyedContainer.encode(CodableRange(a1))\n        case let .revision(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .revision)\n            try unkeyedContainer.encode(a1)\n        case let .branch(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .branch)\n            try unkeyedContainer.encode(a1)\n        }\n    }\n}\n\nextension PackageDependency.SourceControl.Location: Encodable {\n    private enum CodingKeys: String, CodingKey {\n        case local, remote\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .local(let path):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .local)\n            try unkeyedContainer.encode(path)\n        case .remote(let url):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .remote)\n            try unkeyedContainer.encode(url)\n        }\n    }\n}\n\nextension PackageDependency.Registry.Requirement: Encodable {\n    private enum CodingKeys: String, CodingKey {\n        case exact, range\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case let .exact(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .exact)\n            try unkeyedContainer.encode(a1)\n        case let .range(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .range)\n            try unkeyedContainer.encode(CodableRange(a1))\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/PlatformDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct PlatformDescription: Codable, Hashable, Sendable {\n    public let platformName: String\n    public let version: String\n    public let options: [String]\n\n    public init(name: String, version: String, options: [String] = []) {\n        self.platformName = name\n        self.version = version\n        self.options = options\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/ProductDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// The product description\npublic struct ProductDescription: Hashable, Codable, Sendable {\n\n    /// The name of the product.\n    public let name: String\n\n    /// The targets in the product.\n    public let targets: [String]\n\n    /// The type of product.\n    public let type: ProductType\n\n    /// The product-specific settings declared for this product.\n    public let settings: [ProductSetting]\n\n    public init(\n        name: String,\n        type: ProductType,\n        targets: [String],\n        settings: [ProductSetting] = []\n    ) throws {\n        guard type != .test else {\n            throw InternalError(\"Declaring test products isn't supported: \\(name):\\(targets)\")\n        }\n        self.name = name\n        self.type = type\n        self.targets = targets\n        self.settings = settings\n    }\n}\n\n/// A particular setting to apply to a product. Some may be specific to certain platforms.\npublic enum ProductSetting: Equatable, Codable, Sendable, Hashable {\n    case bundleIdentifier(String)\n    case teamIdentifier(String)\n    case displayVersion(String)\n    case bundleVersion(String)\n    case iOSAppInfo(IOSAppInfo)\n\n    public struct IOSAppInfo: Equatable, Codable, Sendable, Hashable {\n        public var appIcon: AppIcon?\n        public var accentColor: AccentColor?\n        public var supportedDeviceFamilies: [DeviceFamily]\n        public var supportedInterfaceOrientations: [InterfaceOrientation]\n        public var capabilities: [Capability]\n        public var appCategory: AppCategory?\n        public var additionalInfoPlistContentFilePath: String?\n\n        public enum DeviceFamily: String, Equatable, Codable, Sendable, Hashable {\n            case pad\n            case phone\n            case mac\n        }\n        \n        public struct DeviceFamilyCondition: Equatable, Codable, Sendable, Hashable {\n            public let deviceFamilies: [DeviceFamily]\n            public init(deviceFamilies: [DeviceFamily]) {\n                self.deviceFamilies = deviceFamilies\n            }\n        }\n\n        public enum InterfaceOrientation: Equatable, Codable, Sendable, Hashable {\n            case portrait(condition: DeviceFamilyCondition?)\n            case portraitUpsideDown(condition: DeviceFamilyCondition?)\n            case landscapeRight(condition: DeviceFamilyCondition?)\n            case landscapeLeft(condition: DeviceFamilyCondition?)\n        }\n        \n        public enum AppIcon: Equatable, Codable, Sendable, Hashable {\n            public struct PlaceholderIcon: Equatable, Codable, Sendable, Hashable {\n                public var rawValue: String\n\n                public init(rawValue: String) {\n                    self.rawValue = rawValue\n                }\n            }\n\n            case placeholder(icon: PlaceholderIcon)\n            case asset(name: String)\n        }\n\n        public enum AccentColor: Equatable, Codable, Sendable, Hashable {\n            public struct PresetColor: Equatable, Codable, Sendable, Hashable {\n                public var rawValue: String\n\n                public init(rawValue: String) {\n                    self.rawValue = rawValue\n                }\n            }\n\n            case presetColor(presetColor: PresetColor)\n            case asset(name: String)\n        }\n\n        public struct Capability: Equatable, Codable, Sendable, Hashable {\n            public var purpose: String\n            public var purposeString: String?\n            public var appTransportSecurityConfiguration: AppTransportSecurityConfiguration?\n            public var bonjourServiceTypes: [String]?\n            public var fileAccessLocation: String?\n            public var fileAccessMode: String?\n            public var condition: DeviceFamilyCondition?\n            \n            public init(\n                purpose: String,\n                purposeString: String? = nil,\n                appTransportSecurityConfiguration: AppTransportSecurityConfiguration? = nil,\n                bonjourServiceTypes: [String]? = nil,\n                fileAccessLocation: String? = nil,\n                fileAccessMode: String? = nil,\n                condition: DeviceFamilyCondition?\n            ) {\n                self.purpose = purpose\n                self.purposeString = purposeString\n                self.appTransportSecurityConfiguration = appTransportSecurityConfiguration\n                self.bonjourServiceTypes = bonjourServiceTypes\n                self.fileAccessLocation = fileAccessLocation\n                self.fileAccessMode = fileAccessMode\n                self.condition = condition\n            }\n        }\n        \n        public struct AppTransportSecurityConfiguration: Equatable, Codable, Sendable, Hashable {\n            public var allowsArbitraryLoadsInWebContent: Bool? = nil\n            public var allowsArbitraryLoadsForMedia: Bool? = nil\n            public var allowsLocalNetworking: Bool? = nil\n            public var exceptionDomains: [ExceptionDomain]? = nil\n            public var pinnedDomains: [PinnedDomain]? = nil\n\n            public struct ExceptionDomain: Equatable, Codable, Sendable, Hashable {\n                public var domainName: String\n                public var includesSubdomains: Bool? = nil\n                public var exceptionAllowsInsecureHTTPLoads: Bool? = nil\n                public var exceptionMinimumTLSVersion: String? = nil\n                public var exceptionRequiresForwardSecrecy: Bool? = nil\n                public var requiresCertificateTransparency: Bool? = nil\n                \n                public init(\n                    domainName: String,\n                    includesSubdomains: Bool?,\n                    exceptionAllowsInsecureHTTPLoads: Bool?,\n                    exceptionMinimumTLSVersion: String?,\n                    exceptionRequiresForwardSecrecy: Bool?,\n                    requiresCertificateTransparency: Bool?\n                ) {\n                    self.domainName = domainName\n                    self.includesSubdomains = includesSubdomains\n                    self.exceptionAllowsInsecureHTTPLoads = exceptionAllowsInsecureHTTPLoads\n                    self.exceptionMinimumTLSVersion = exceptionMinimumTLSVersion\n                    self.exceptionRequiresForwardSecrecy = exceptionRequiresForwardSecrecy\n                    self.requiresCertificateTransparency = requiresCertificateTransparency\n                }\n            }\n            \n            public struct PinnedDomain: Equatable, Codable, Sendable, Hashable {\n                public var domainName: String\n                public var includesSubdomains : Bool? = nil\n                public var pinnedCAIdentities : [[String: String]]? = nil\n                public var pinnedLeafIdentities : [[String: String]]? = nil\n                \n                public init(\n                    domainName: String,\n                    includesSubdomains: Bool?,\n                    pinnedCAIdentities : [[String: String]]? ,\n                    pinnedLeafIdentities : [[String: String]]?\n                ) {\n                    self.domainName = domainName\n                    self.includesSubdomains = includesSubdomains\n                    self.pinnedCAIdentities = pinnedCAIdentities\n                    self.pinnedLeafIdentities = pinnedLeafIdentities\n                }\n            }\n\n            public init(\n                allowsArbitraryLoadsInWebContent: Bool?,\n                allowsArbitraryLoadsForMedia: Bool?,\n                allowsLocalNetworking: Bool?,\n                exceptionDomains: [ExceptionDomain]?,\n                pinnedDomains: [PinnedDomain]?\n            ) {\n                self.allowsArbitraryLoadsInWebContent = allowsArbitraryLoadsInWebContent\n                self.allowsArbitraryLoadsForMedia = allowsArbitraryLoadsForMedia\n                self.allowsLocalNetworking = allowsLocalNetworking\n                self.exceptionDomains = exceptionDomains\n                self.pinnedDomains = pinnedDomains\n            }\n        }\n        \n        public struct AppCategory: Equatable, Codable, Sendable, Hashable {\n            public var rawValue: String\n\n            public init(rawValue: String) {\n                self.rawValue = rawValue\n            }\n        }\n\n        public init(\n            appIcon: AppIcon?,\n            accentColor: AccentColor?,\n            supportedDeviceFamilies: [DeviceFamily],\n            supportedInterfaceOrientations: [InterfaceOrientation],\n            capabilities: [Capability],\n            appCategory: AppCategory?,\n            additionalInfoPlistContentFilePath: String?\n        ) {\n            self.appIcon = appIcon\n            self.accentColor = accentColor\n            self.supportedDeviceFamilies = supportedDeviceFamilies\n            self.supportedInterfaceOrientations = supportedInterfaceOrientations\n            self.capabilities = capabilities\n            self.appCategory = appCategory\n            self.additionalInfoPlistContentFilePath = additionalInfoPlistContentFilePath\n        }\n    }\n}\n\n\nextension ProductSetting {\n    private enum CodingKeys: String, CodingKey {\n        case bundleIdentifier\n        case teamIdentifier\n        case displayVersion\n        case bundleVersion\n        case iOSAppInfo\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case let .bundleIdentifier(value):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .bundleIdentifier)\n            try unkeyedContainer.encode(value)\n        case let .teamIdentifier(value):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .teamIdentifier)\n            try unkeyedContainer.encode(value)\n        case let .displayVersion(value):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .displayVersion)\n            try unkeyedContainer.encode(value)\n        case let .bundleVersion(value):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .bundleVersion)\n            try unkeyedContainer.encode(value)\n        case let .iOSAppInfo(value):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .iOSAppInfo)\n            try unkeyedContainer.encode(value)\n        }\n    }\n\n    public init(from decoder: Decoder) throws {\n        let values = try decoder.container(keyedBy: CodingKeys.self)\n        guard let key = values.allKeys.first(where: values.contains) else {\n            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: \"Did not find a matching key\"))\n        }\n        switch key {\n        case .bundleIdentifier:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let value = try unkeyedValues.decode(String.self)\n            self = .bundleIdentifier(value)\n        case .teamIdentifier:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let value = try unkeyedValues.decode(String.self)\n            self = .teamIdentifier(value)\n        case .displayVersion:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let value = try unkeyedValues.decode(String.self)\n            self = .displayVersion(value)\n        case .bundleVersion:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let value = try unkeyedValues.decode(String.self)\n            self = .bundleVersion(value)\n        case .iOSAppInfo:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let value = try unkeyedValues.decode(IOSAppInfo.self)\n            self = .iOSAppInfo(value)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/SystemPackageProviderDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Represents system package providers.\npublic enum SystemPackageProviderDescription: Hashable, Codable, Sendable {\n    case brew([String])\n    case apt([String])\n    case yum([String])\n    case nuget([String])\n    case pkg([String])\n}\n\nextension SystemPackageProviderDescription {\n    private enum CodingKeys: String, CodingKey {\n        case brew, apt, yum, nuget, pkg\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case let .brew(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .brew)\n            try unkeyedContainer.encode(a1)\n        case let .apt(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .apt)\n            try unkeyedContainer.encode(a1)\n        case let .yum(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .yum)\n            try unkeyedContainer.encode(a1)\n        case let .nuget(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .nuget)\n            try unkeyedContainer.encode(a1)\n        case let .pkg(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .pkg)\n            try unkeyedContainer.encode(a1)\n        }\n    }\n\n    public init(from decoder: Decoder) throws {\n        let values = try decoder.container(keyedBy: CodingKeys.self)\n        guard let key = values.allKeys.first(where: values.contains) else {\n            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: \"Did not find a matching key\"))\n        }\n        switch key {\n        case .brew:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode([String].self)\n            self = .brew(a1)\n        case .apt:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode([String].self)\n            self = .apt(a1)\n        case .yum:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode([String].self)\n            self = .yum(a1)\n        case .nuget:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode([String].self)\n            self = .nuget(a1)\n        case .pkg:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode([String].self)\n            self = .pkg(a1)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/TargetBuildSettingDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A namespace for target-specific build settings.\npublic enum TargetBuildSettingDescription {\n    /// The tool for which a build setting is declared.\n    public enum Tool: String, Codable, Hashable, CaseIterable, Sendable {\n        case c\n        case cxx\n        case swift\n        case linker\n    }\n\n    public enum InteroperabilityMode: String, Codable, Hashable, Sendable {\n        case C\n        case Cxx\n    }\n\n    /// The level at which a compiler warning should be treated.\n    public enum WarningLevel: String, Codable, Hashable, Sendable {\n        case warning\n        case error\n    }\n\n    public enum DefaultIsolation: String, Codable, Hashable, Sendable {\n        case MainActor\n        case nonisolated\n    }\n\n    /// The kind of the build setting, with associate configuration\n    public enum Kind: Codable, Hashable, Sendable {\n        case headerSearchPath(String)\n        case define(String)\n        case linkedLibrary(String)\n        case linkedFramework(String)\n\n        case interoperabilityMode(InteroperabilityMode)\n\n        case enableUpcomingFeature(String)\n        case enableExperimentalFeature(String)\n        case strictMemorySafety\n\n        case unsafeFlags([String])\n\n        case swiftLanguageMode(SwiftLanguageVersion)\n\n        case treatAllWarnings(WarningLevel)\n        case treatWarning(String, WarningLevel)\n        case enableWarning(String)\n        case disableWarning(String)\n\n        case defaultIsolation(DefaultIsolation)\n\n        public var isUnsafeFlags: Bool {\n            switch self {\n            case .unsafeFlags(let flags):\n                // If `.unsafeFlags` is used, but doesn't specify any flags, we treat it the same way as not specifying it.\n                return !flags.isEmpty\n            case .headerSearchPath, .define, .linkedLibrary, .linkedFramework, .interoperabilityMode,\n                 .enableUpcomingFeature, .enableExperimentalFeature, .strictMemorySafety, .swiftLanguageMode,\n                 .treatAllWarnings, .treatWarning, .enableWarning, .disableWarning, .defaultIsolation:\n                return false\n            }\n        }\n    }\n\n    /// An individual build setting.\n    public struct Setting: Codable, Hashable, Sendable {\n        /// The tool associated with this setting.\n        public let tool: Tool\n\n        /// The kind of the setting.\n        public let kind: Kind\n\n        /// The condition at which the setting should be applied.\n        public let condition: PackageConditionDescription?\n\n        public init(\n            tool: Tool,\n            kind: Kind,\n            condition: PackageConditionDescription? = .none\n        ) {\n            self.tool = tool\n            self.kind = kind\n            self.condition = condition\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/TargetDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The description of an individual module.\npublic struct TargetDescription: Hashable, Encodable, Sendable {\n    @available(*, deprecated, renamed: \"TargetKind\")\n    public typealias TargetType = TargetKind\n\n    /// The target kind.\n    public enum TargetKind: String, Hashable, Encodable, Sendable {\n        case regular\n        case executable\n        case test\n        case system\n        case binary\n        case plugin\n        case `macro`\n    }\n\n    /// Represents a target's dependency on another entity.\n    public enum Dependency: Hashable, Sendable {\n        case target(name: String, condition: PackageConditionDescription?)\n        case product(name: String, package: String?, moduleAliases: [String: String]? = nil, condition: PackageConditionDescription?)\n        case byName(name: String, condition: PackageConditionDescription?)\n\n        public var condition: PackageConditionDescription? {\n            switch self {\n            case .target(_, let condition):\n                return condition\n            case .product(_, _, _, let condition):\n                return condition\n            case .byName(_, let condition):\n                return condition\n            }\n        }\n\n        public var name: String {\n            switch self {\n            case .target(let name, _):\n                return name\n            case .product(let name, _, _, _):\n                return name\n            case .byName(let name, _):\n                return name\n            }\n        }\n\n        public var package: String? {\n            switch self {\n            case .product(_, let name?, _, _),\n                  .byName(let name, _): // Note: byName can either refer to a product or target dependency\n                return name\n            default:\n                return nil\n            }\n        }\n\n        public static func target(name: String) -> Dependency {\n            return .target(name: name, condition: nil)\n        }\n\n        public static func product(name: String, package: String? = nil, moduleAliases: [String: String]? = nil) -> Dependency {\n            return .product(name: name, package: package, moduleAliases: moduleAliases, condition: nil)\n        }\n    }\n\n    public struct Resource: Encodable, Hashable, Sendable {\n        public enum Rule: Encodable, Hashable, Sendable {\n            case process(localization: Localization?)\n            case copy\n            case embedInCode\n        }\n\n        public enum Localization: String, Encodable, Sendable {\n            case `default`\n            case base\n        }\n\n        /// The rule for the resource.\n        public let rule: Rule\n\n        /// The path of the resource.\n        public let path: String\n\n        public init(rule: Rule, path: String) {\n            self.rule = rule\n            self.path = path\n        }\n    }\n\n    /// The name of the target.\n    public let name: String\n\n    /// If true, access to package declarations from other targets is allowed.\n    /// APIs is not allowed from outside.\n    public let packageAccess: Bool\n\n    /// The custom path of the target.\n    public let path: String?\n\n    /// The url of the binary target artifact.\n    public let url: String?\n\n    /// The custom sources of the target.\n    public let sources: [String]?\n\n    /// The explicitly declared resources of the target.\n    public let resources: [Resource]\n\n    /// The exclude patterns.\n    public let exclude: [String]\n\n    // FIXME: Remote this.\n    //\n    /// Returns true if the target type is test.\n    public var isTest: Bool {\n        return type == .test\n    }\n\n    /// The declared target dependencies.\n    public package(set) var dependencies: [Dependency]\n\n    /// The custom public headers path.\n    public let publicHeadersPath: String?\n\n    /// The type of target.\n    public let type: TargetKind\n\n    /// The pkg-config name of a system library target.\n    public let pkgConfig: String?\n\n    /// The providers of a system library target.\n    public let providers: [SystemPackageProviderDescription]?\n\n    /// The declared capability for a package plugin target.\n    public let pluginCapability: PluginCapability?\n\n    /// Represents the declared capability of a package plugin.\n    public enum PluginCapability: Hashable, Sendable {\n        case buildTool\n        case command(intent: PluginCommandIntent, permissions: [PluginPermission])\n    }\n\n    public enum PluginCommandIntent: Hashable, Codable, Sendable {\n        case documentationGeneration\n        case sourceCodeFormatting\n        case custom(verb: String, description: String)\n    }\n\n    public enum PluginNetworkPermissionScope: Hashable, Codable, Sendable {\n        case none\n        case local(ports: [Int])\n        case all(ports: [Int])\n        case docker\n        case unixDomainSocket\n\n        public init?(_ scopeString: String, ports: [Int]) {\n            switch scopeString {\n            case \"none\": self = .none\n            case \"local\": self = .local(ports: ports)\n            case \"all\": self = .all(ports: ports)\n            case \"docker\": self = .docker\n            case \"unix-socket\": self = .unixDomainSocket\n            default: return nil\n            }\n        }\n    }\n\n    public enum PluginPermission: Hashable, Codable, Sendable {\n        case allowNetworkConnections(scope: PluginNetworkPermissionScope, reason: String)\n        case writeToPackageDirectory(reason: String)\n    }\n\n    /// The target-specific build settings declared in this target.\n    public let settings: [TargetBuildSettingDescription.Setting]\n\n    /// The binary target checksum.\n    public let checksum: String?\n\n    /// The usages of package plugins by the target.\n    public let pluginUsages: [PluginUsage]?\n\n    /// Represents a target's usage of a plugin target or product.\n    public enum PluginUsage: Hashable, Sendable {\n        case plugin(name: String, package: String?)\n    }\n\n    public init(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        url: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource] = [],\n        publicHeadersPath: String? = nil,\n        type: TargetKind = .regular,\n        packageAccess: Bool = true,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProviderDescription]? = nil,\n        pluginCapability: PluginCapability? = nil,\n        settings: [TargetBuildSettingDescription.Setting] = [],\n        checksum: String? = nil,\n        pluginUsages: [PluginUsage]? = nil\n    ) throws {\n        let targetType = String(describing: type)\n        switch type {\n        case .regular, .executable, .test:\n            if url != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"url\",\n                value: url ?? \"<nil>\"\n            ) }\n            if pkgConfig != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pkgConfig\",\n                value: pkgConfig ?? \"<nil>\"\n            ) }\n            if providers != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"providers\",\n                value: String(describing: providers!)\n            ) }\n            if pluginCapability != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pluginCapability\",\n                value: String(describing: pluginCapability!)\n            ) }\n            if checksum != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"checksum\",\n                value: checksum ?? \"<nil>\"\n            ) }\n        case .system:\n            if !dependencies.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"dependencies\",\n                value: String(describing: dependencies)\n            ) }\n            if !exclude.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"exclude\",\n                value: String(describing: exclude)\n            ) }\n            if sources != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"sources\",\n                value: String(describing: sources!)\n            ) }\n            if !resources.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"resources\",\n                value: String(describing: resources)\n            ) }\n            if publicHeadersPath != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"publicHeadersPath\",\n                value: publicHeadersPath ?? \"<nil>\"\n            ) }\n            if pluginCapability != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pluginCapability\",\n                value: String(describing: pluginCapability!)\n            ) }\n            if !settings.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"settings\",\n                value: String(describing: settings)\n            ) }\n            if checksum != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"checksum\",\n                value: checksum ?? \"<nil>\"\n            ) }\n            if pluginUsages != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pluginUsages\",\n                value: String(describing: pluginUsages!)\n            ) }\n        case .binary:\n            if path == nil && url == nil { throw Error.binaryTargetRequiresEitherPathOrURL(targetName: name) }\n            if !dependencies.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"dependencies\",\n                value: String(describing: dependencies)\n            ) }\n            if !exclude.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"exclude\",\n                value: String(describing: exclude)\n            ) }\n            if sources != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"sources\",\n                value: String(describing: sources!)\n            ) }\n            if !resources.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"resources\",\n                value: String(describing: resources)\n            ) }\n            if publicHeadersPath != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"publicHeadersPath\",\n                value: publicHeadersPath ?? \"<nil>\"\n            ) }\n            if pkgConfig != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pkgConfig\",\n                value: pkgConfig ?? \"<nil>\"\n            ) }\n            if providers != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"providers\",\n                value: String(describing: providers!)\n            ) }\n            if pluginCapability != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pluginCapability\",\n                value: String(describing: pluginCapability!)\n            ) }\n            if !settings.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"settings\",\n                value: String(describing: settings)\n            ) }\n            if pluginUsages != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pluginUsages\",\n                value: String(describing: pluginUsages!)\n            ) }\n        case .plugin:\n            if pluginCapability == nil { throw Error.pluginTargetRequiresPluginCapability(targetName: name) }\n            if url != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"url\",\n                value: url ?? \"<nil>\"\n            ) }\n            if !resources.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"resources\",\n                value: String(describing: resources)\n            ) }\n            if publicHeadersPath != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"publicHeadersPath\",\n                value: publicHeadersPath ?? \"<nil>\"\n            ) }\n            if pkgConfig != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pkgConfig\",\n                value: pkgConfig ?? \"<nil>\"\n            ) }\n            if providers != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"providers\",\n                value: String(describing: providers!)\n            ) }\n            if !settings.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"settings\",\n                value: String(describing: settings)\n            ) }\n            if pluginUsages != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pluginUsages\",\n                value: String(describing: pluginUsages!)\n            ) }\n        case .macro:\n            if url != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"url\",\n                value: url ?? \"<nil>\"\n            ) }\n            if !resources.isEmpty { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"resources\",\n                value: String(describing: resources)\n            ) }\n            if publicHeadersPath != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"publicHeadersPath\",\n                value: publicHeadersPath ?? \"<nil>\"\n            ) }\n            if pkgConfig != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pkgConfig\",\n                value: pkgConfig ?? \"<nil>\"\n            ) }\n            if providers != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"providers\",\n                value: String(describing: providers!)\n            ) }\n            if pluginCapability != nil { throw Error.disallowedPropertyInTarget(\n                targetName: name,\n                targetType: targetType,\n                propertyName: \"pluginCapability\",\n                value: String(describing: pluginCapability!)\n            ) }\n        }\n\n        self.name = name\n        self.dependencies = dependencies\n        self.path = path\n        self.url = url\n        self.publicHeadersPath = publicHeadersPath\n        self.sources = sources\n        self.exclude = exclude\n        self.resources = resources\n        self.type = type\n        self.packageAccess = packageAccess\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.pluginCapability = pluginCapability\n        self.settings = settings\n        self.checksum = checksum\n        self.pluginUsages = pluginUsages\n    }\n}\n\nextension TargetDescription.Dependency: Codable {\n    private enum CodingKeys: String, CodingKey {\n        case target, product, byName\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case let .target(a1, a2):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .target)\n            try unkeyedContainer.encode(a1)\n            try unkeyedContainer.encode(a2)\n        case let .product(a1, a2, a3, a4):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .product)\n            try unkeyedContainer.encode(a1)\n            try unkeyedContainer.encode(a2)\n            try unkeyedContainer.encode(a3)\n            try unkeyedContainer.encode(a4)\n        case let .byName(a1, a2):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .byName)\n            try unkeyedContainer.encode(a1)\n            try unkeyedContainer.encode(a2)\n        }\n    }\n\n    public init(from decoder: Decoder) throws {\n        let values = try decoder.container(keyedBy: CodingKeys.self)\n        guard let key = values.allKeys.first(where: values.contains) else {\n            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: \"Did not find a matching key\"))\n        }\n        switch key {\n        case .target:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode(String.self)\n            let a2 = try unkeyedValues.decodeIfPresent(PackageConditionDescription.self)\n            self = .target(name: a1, condition: a2)\n        case .product:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode(String.self)\n            let a2 = try unkeyedValues.decodeIfPresent(String.self)\n            let a3 = try unkeyedValues.decode([String: String].self)\n            let a4 = try unkeyedValues.decodeIfPresent(PackageConditionDescription.self)\n            self = .product(name: a1, package: a2, moduleAliases: a3, condition: a4)\n        case .byName:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode(String.self)\n            let a2 = try unkeyedValues.decodeIfPresent(PackageConditionDescription.self)\n            self = .byName(name: a1, condition: a2)\n        }\n    }\n}\n\nextension TargetDescription.Dependency: ExpressibleByStringLiteral {\n    public init(stringLiteral value: String) {\n        self = .byName(name: value, condition: nil)\n    }\n}\n\nextension TargetDescription.PluginCapability: Codable {\n    private enum CodingKeys: CodingKey {\n        case buildTool, command\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .buildTool:\n            try container.encodeNil(forKey: .buildTool)\n        case .command(let a1, let a2):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .command)\n            try unkeyedContainer.encode(a1)\n            try unkeyedContainer.encode(a2)\n        }\n    }\n\n    public init(from decoder: Decoder) throws {\n        let values = try decoder.container(keyedBy: CodingKeys.self)\n        guard let key = values.allKeys.first(where: values.contains) else {\n            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: \"Did not find a matching key\"))\n        }\n        switch key {\n        case .buildTool:\n            self = .buildTool\n        case .command:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode(TargetDescription.PluginCommandIntent.self)\n            let a2 = try unkeyedValues.decode([TargetDescription.PluginPermission].self)\n            self = .command(intent: a1, permissions: a2)\n        }\n    }\n}\n\nextension TargetDescription.PluginUsage: Codable {\n    private enum CodingKeys: String, CodingKey {\n        case plugin\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case let .plugin(name, package):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .plugin)\n            try unkeyedContainer.encode(name)\n            try unkeyedContainer.encode(package)\n        }\n    }\n\n    public init(from decoder: Decoder) throws {\n        let values = try decoder.container(keyedBy: CodingKeys.self)\n        guard let key = values.allKeys.first(where: values.contains) else {\n            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: \"Did not find a matching key\"))\n        }\n        switch key {\n        case .plugin:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let name = try unkeyedValues.decode(String.self)\n            let package = try unkeyedValues.decodeIfPresent(String.self)\n            self = .plugin(name: name, package: package)\n        }\n    }\n}\n\nimport protocol Foundation.LocalizedError\n\nprivate enum Error: LocalizedError, Equatable {\n    case binaryTargetRequiresEitherPathOrURL(targetName: String)\n    case pluginTargetRequiresPluginCapability(targetName: String)\n    case disallowedPropertyInTarget(targetName: String, targetType: String, propertyName: String, value: String)\n\n    var errorDescription: String? {\n        switch self {\n        case .binaryTargetRequiresEitherPathOrURL(let targetName):\n            \"binary target '\\(targetName)' must define either path or URL for its artifacts\"\n        case .pluginTargetRequiresPluginCapability(let targetName):\n            \"plugin target '\\(targetName)' must define a plugin capability\"\n        case .disallowedPropertyInTarget(let targetName, let targetType, let propertyName, let value):\n            \"target '\\(targetName)' is assigned a property '\\(propertyName)' which is not accepted \" +\n            \"for the \\(targetType) target type. The current property value has \" +\n            \"the following representation: \\(value).\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/TraitConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The trait configuration.\npublic enum TraitConfiguration: Codable, Hashable {\n    case enableAllTraits\n    case disableAllTraits\n    case enabledTraits(Set<String>)\n    case `default`\n\n    public init(\n        enabledTraits: Set<String>? = nil,\n        enableAllTraits: Bool = false\n    ) {\n        // If all traits are enabled, then no other checks are necessary.\n        guard !enableAllTraits else {\n            self = .enableAllTraits\n            return\n        }\n\n        // There can be two possible cases here:\n        //  - The set of enabled traits is empty, which means that no traits are enabled.\n        //  - The set of enabled traits is not empty and specifies which traits are enabled.\n        if let enabledTraits {\n            if enabledTraits.isEmpty {\n                self = .disableAllTraits\n            } else {\n                self = .enabledTraits(enabledTraits)\n            }\n        } else {\n            // Since enableAllTraits isn't enabled and there isn't a set of enabled traits,\n            // there is no configuration passed by the user.\n            self = .default\n        }\n    }\n\n    /// The set of enabled traits, if available.\n    public var enabledTraits: EnabledTraits? {\n        switch self {\n        case .default:\n            EnabledTraits.defaults\n        case .enabledTraits(let traits):\n            EnabledTraits(traits, setBy: .traitConfiguration)\n        case .disableAllTraits:\n            []\n        case .enableAllTraits:\n            nil\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Manifest/TraitDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npublic struct TraitDescription: Sendable, Hashable, Codable, ExpressibleByStringLiteral {\n    /// The trait's canonical name.\n    ///\n    /// This is used when enabling the trait or when referring to it from other modifiers in the manifest.\n    public var name: String\n\n    /// The trait's description.\n    public var description: String?\n\n    /// A set of other traits of this package that this trait enables.\n    public var enabledTraits: Set<String>\n\n    /// Initializes a new trait.\n    ///\n    /// - Parameters:\n    ///   - name: The trait's canonical name.\n    ///   - description: The trait's description.\n    ///   - enabledTraits: A set of other traits of this package that this trait enables.\n    public init(\n        name: String,\n        description: String? = nil,\n        enabledTraits: Set<String> = []\n    ) {\n        self.name = name\n        self.description = description\n        self.enabledTraits = enabledTraits\n    }\n\n    public init(stringLiteral value: StringLiteralType) {\n        self.init(name: value)\n    }\n}\n\nextension TraitDescription {\n    public var isDefault: Bool {\n        self.name == \"default\"\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/ManifestSourceGeneration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n/// Extensions on Manifest for generating source code expressing its contents\n/// in canonical declarative form.  Note that this bakes in the results of any\n/// algorithmically generated manifest content, so it is not suitable for the\n/// mechanical editing of package manifests.  Rather, it is intended for such\n/// tasks as manifest creation as part of package instantiation, etc.\nextension Manifest {\n    \n    /// Generates and returns a string containing the contents of the manifest\n    /// in canonical declarative form.\n    /// \n    /// - Parameters:\n    ///   - packageDirectory: Directory of the manifest's package (for purposes of making strings relative).\n    ///   - toolsVersionHeaderComment: Optional string to add to the `swift-tools-version` header (it will be ignored).\n    ///   - additionalImportModuleNames: Names of any modules to import besides PackageDescription (would commonly contain custom product type definitions).\n    ///   - customProductTypeSourceGenerator: Closure that will be called once for each custom product type in the manifest; it should return a SourceCodeFragment for the product type.\n    /// \n    /// Returns: a string containing the full source code for the manifest.\n    public func generateManifestFileContents(\n        packageDirectory: AbsolutePath,\n        toolsVersionHeaderComment: String? = .none,\n        additionalImportModuleNames: [String] = [],\n        customProductTypeSourceGenerator: ManifestCustomProductTypeSourceGenerator? = .none,\n        overridingToolsVersion: ToolsVersion? = nil\n    ) rethrows -> String {\n        let toolsVersion = overridingToolsVersion ?? self.toolsVersion\n        \n        // Generate the source code fragment for the top level of the package\n        // expression.\n        let packageExprFragment = try SourceCodeFragment(\n            from: self,\n            packageDirectory: packageDirectory,\n            customProductTypeSourceGenerator: customProductTypeSourceGenerator,\n            toolsVersion: toolsVersion)\n        \n        // Generate the source code from the module names and code fragment.\n        // We only write out the major and minor (not patch) versions of the\n        // tools version, since the patch version doesn't change semantics.\n        // We leave out the spacer if the tools version doesn't support it.\n        let toolsVersionSuffix = \"\\(toolsVersionHeaderComment.map{ \"; \\($0)\" } ?? \"\")\"\n        return \"\"\"\n            \\(toolsVersion.specification(roundedTo: .minor))\\(toolsVersionSuffix)\n            import PackageDescription\n            \\(additionalImportModuleNames.map{ \"import \\($0)\\n\" }.joined())\n            let package = \\(packageExprFragment.generateSourceCode())\n            \"\"\"\n    }\n}\n\n/// Constructs and returns a SourceCodeFragment that represents the instantiation of a custom product type with the specified identifier and having the given serialized parameters (the contents of whom are a private matter between the serialized form in PackageDescription and the client). The generated source code should, if evaluated as a part of a package manifest, result in the same serialized parameters.\npublic typealias ManifestCustomProductTypeSourceGenerator = (ProductDescription) throws -> SourceCodeFragment?\n\n\n/// Convenience initializers for package manifest structures.\nfileprivate extension SourceCodeFragment {\n\n    /// Instantiates a SourceCodeFragment to represent an entire manifest.\n    init(\n        from manifest: Manifest,\n        packageDirectory: AbsolutePath,\n        customProductTypeSourceGenerator: ManifestCustomProductTypeSourceGenerator?,\n        toolsVersion: ToolsVersion\n    ) rethrows {\n        var params: [SourceCodeFragment] = []\n        \n        params.append(SourceCodeFragment(key: \"name\", string: manifest.displayName))\n        \n        if let defaultLoc = manifest.defaultLocalization {\n            params.append(SourceCodeFragment(key: \"defaultLocalization\", string: defaultLoc))\n        }\n        \n        if !manifest.platforms.isEmpty {\n            let nodes = manifest.platforms.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"platforms\", subnodes: nodes))\n        }\n        \n        if let pkgConfig = manifest.pkgConfig {\n            params.append(SourceCodeFragment(key: \"pkgConfig\", string: pkgConfig))\n        }\n        \n        if let systemPackageProviders = manifest.providers, !systemPackageProviders.isEmpty {\n            let nodes = systemPackageProviders.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"providers\", subnodes: nodes))\n        }\n\n        if !manifest.products.isEmpty {\n            let nodes = try manifest.products.map{ try SourceCodeFragment(from: $0, customProductTypeSourceGenerator: customProductTypeSourceGenerator, toolsVersion: toolsVersion) }\n            params.append(SourceCodeFragment(key: \"products\", subnodes: nodes))\n        }\n\n        if !manifest.traits.isEmpty {\n            let nodes = manifest.traits.map { SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"traits\", subnodes: nodes))\n        }\n\n        if !manifest.dependencies.isEmpty {\n            let nodes = manifest.dependencies.map{ SourceCodeFragment(from: $0, pathAnchor: packageDirectory) }\n            params.append(SourceCodeFragment(key: \"dependencies\", subnodes: nodes))\n        }\n\n        if !manifest.targets.isEmpty {\n            let nodes = manifest.targets.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"targets\", subnodes: nodes))\n        }\n        \n        if let swiftLanguageVersions = manifest.swiftLanguageVersions {\n            let nodes = swiftLanguageVersions.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"swiftLanguageVersions\", subnodes: nodes, multiline: false))\n        }\n\n        if let cLanguageStandard = manifest.cLanguageStandard {\n            // NOTE: This could be cleaned up to use the nicer accessors.\n            let node = SourceCodeFragment(\"CLanguageStandard\", delimiters: .parentheses, multiline: false, subnodes: [SourceCodeFragment(key: \"rawValue\", string: cLanguageStandard)])\n            params.append(SourceCodeFragment(key: \"cLanguageStandard\", subnode: node))\n        }\n\n        if let cxxLanguageStandard = manifest.cxxLanguageStandard {\n            // NOTE: This could be cleaned up to use the nicer accessors.\n            let node = SourceCodeFragment(\"CXXLanguageStandard\", delimiters: .parentheses, multiline: false, subnodes: [SourceCodeFragment(key: \"rawValue\", string: cxxLanguageStandard)])\n            params.append(SourceCodeFragment(key: \"cxxLanguageStandard\", subnode: node))\n        }\n\n        self.init(\"Package\", delimiters: .parentheses, subnodes: params)\n    }\n    \n    /// Instantiates a SourceCodeFragment to represent a single platform.\n    init(from platform: PlatformDescription) {\n        // NOTE: This could be cleaned up to use the nicer version accessors.\n        switch platform.platformName {\n        case \"macos\":\n            self.init(enum: \"macOS\", string: platform.version)\n        case \"maccatalyst\":\n            self.init(enum: \"macCatalyst\", string: platform.version)\n        case \"ios\":\n            self.init(enum: \"iOS\", string: platform.version)\n        case \"tvos\":\n            self.init(enum: \"tvOS\", string: platform.version)\n        case \"watchos\":\n            self.init(enum: \"watchOS\", string: platform.version)\n        case \"visionos\":\n            self.init(enum: \"visionOS\", string: platform.version)\n        case \"driverkit\":\n            self.init(enum: \"driverKit\", string: platform.version)\n        default:\n            self.init(enum: \"custom\", subnodes: [ .init(string: platform.platformName), .init(key: \"versionString\", string: platform.version) ])\n        }\n    }\n    \n    /// Instantiates a SourceCodeFragment to represent a single package dependency.\n    init(from dependency: PackageDependency, pathAnchor: AbsolutePath) {\n        var params: [SourceCodeFragment] = []\n        if let explicitName = dependency.explicitNameForModuleDependencyResolutionOnly {\n            params.append(SourceCodeFragment(key: \"name\", string: explicitName))\n        }\n        switch dependency {\n        case .fileSystem(let settings):\n            let relPath = settings.path.relative(to: pathAnchor)\n            params.append(SourceCodeFragment(key: \"path\", string: relPath.pathString))\n        case .sourceControl(let settings):\n            switch settings.location {\n            case .local(let absPath):\n                let relPath = absPath.relative(to: pathAnchor)\n                params.append(SourceCodeFragment(key: \"url\", string: relPath.pathString))\n            case .remote(let url):\n                params.append(SourceCodeFragment(key: \"url\", string: url.absoluteString))\n            }\n            switch settings.requirement {\n            case .exact(let version):\n                params.append(SourceCodeFragment(enum: \"exact\", string: \"\\(version)\"))\n            case .range(let range):\n                params.append(SourceCodeFragment(\"\\\"\\(range.lowerBound)\\\"..<\\\"\\(range.upperBound)\\\"\"))\n            case .revision(let revision):\n                params.append(SourceCodeFragment(enum: \"revision\", string: revision))\n            case .branch(let branch):\n                params.append(SourceCodeFragment(enum: \"branch\", string: branch))\n            }\n        case .registry(let settings):\n            params.append(SourceCodeFragment(key: \"identity\", string: settings.identity.description))\n            switch settings.requirement {\n            case .exact(let version):\n                params.append(SourceCodeFragment(enum: \"exact\", string: \"\\(version)\"))\n            case .range(let range):\n                params.append(SourceCodeFragment(\"\\\"\\(range.lowerBound)\\\"..<\\\"\\(range.upperBound)\\\"\"))\n            }\n        }\n\n        if let traits = dependency.traits {\n            // If only `.defaults` is specified, do not output `traits:` .\n            // This is because `traits:` is not available in toolchains earlier than 6.1.\n            let isDefault = traits.count == 1 &&\n                traits.allSatisfy(\\.isDefaultsCase)\n\n            if !isDefault {\n                let traits = traits.sorted { a, b in\n                    PackageDependency.Trait.precedes(a, b)\n                }\n                params.append(\n                    SourceCodeFragment(\n                        key: \"traits\",\n                        subnodes: traits.map { SourceCodeFragment(from: $0) }\n                    )\n                )\n            }\n        }\n\n        self.init(enum: \"package\", subnodes: params)\n    }\n\n    init(from trait: PackageDependency.Trait) {\n        if trait.isDefaultsCase {\n            self.init(enum: \"defaults\")\n            return\n        }\n\n        guard let condition = trait.condition else {\n            self.init(string: trait.name)\n            return\n        }\n\n        let conditionNode = SourceCodeFragment(\n            key: \"condition\",\n            subnode: SourceCodeFragment(from: condition)\n        )\n\n        self.init(enum: \"trait\", subnodes: [\n            SourceCodeFragment(key: \"name\", string: trait.name),\n            conditionNode\n        ])\n    }\n\n    init(from condition: PackageDependency.Trait.Condition) {\n        var params: [SourceCodeFragment] = []\n\n        if let trait = condition.traits {\n            params.append(\n                SourceCodeFragment(\n                    key: \"traits\",\n                    subnodes: trait.sorted().map {\n                        SourceCodeFragment(string: $0)\n                    }\n                )\n            )\n        }\n\n        self.init(enum: \"when\", subnodes: params)\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single product. If there's a custom product generator, it gets\n    /// a chance to generate the source code fragments before checking the default types.\n    init(from product: ProductDescription, customProductTypeSourceGenerator: ManifestCustomProductTypeSourceGenerator?, toolsVersion: ToolsVersion) rethrows {\n        // Use a custom source code fragment if we have a custom generator and it returns a value.\n        if let customSubnode = try customProductTypeSourceGenerator?(product) {\n            self = customSubnode\n        }\n        // Otherwise we use the default behavior.\n        else {\n            var params: [SourceCodeFragment] = []\n            params.append(SourceCodeFragment(key: \"name\", string: product.name))\n            if !product.targets.isEmpty && !product.type.isLibrary {\n                params.append(SourceCodeFragment(key: \"targets\", strings: product.targets))\n            }\n            switch product.type {\n            case .library(let type):\n                if type != .automatic {\n                    params.append(SourceCodeFragment(key: \"type\", enum: type.rawValue))\n                }\n                if !product.targets.isEmpty {\n                    params.append(SourceCodeFragment(key: \"targets\", strings: product.targets))\n                }\n                self.init(enum: \"library\", subnodes: params, multiline: true)\n            case .executable:\n                // For iOSApplication targets, we temporarily do something special\n                // This will be generalized once we are sure of how it should look.\n                let isIOSApp = product.settings.contains(where: {\n                    // iOS apps are currently identifier by an iOSAppInfo product\n                    // setting.\n                    if case .iOSAppInfo(_) = $0 {\n                        return true\n                    }\n                    return false\n                })\n                if isIOSApp {\n                    // Create a parameter for each of the product settings.\n                    for setting in product.settings {\n                        let subnode = SourceCodeFragment(from: setting, toolsVersion: toolsVersion)\n                        switch setting {\n                        case .iOSAppInfo(_):\n                            // For the app info only, we hoist the subnodes of the\n                            // initializer out to the top level, since that is the\n                            // form of the instantiator function.\n                            params.append(contentsOf: subnode.subnodes?.first?.subnodes ?? [])\n                        default:\n                            // Other product settings are just added as they are.\n                            params.append(subnode)\n                        }\n                    }\n                    self.init(enum: \"iOSApplication\", subnodes: params, multiline: true)\n                }\n                else {\n                    self.init(enum: \"executable\", subnodes: params, multiline: true)\n                }\n            case .snippet:\n                self.init(enum: \"sample\", subnodes: params, multiline: true)\n            case .plugin:\n                self.init(enum: \"plugin\", subnodes: params, multiline: true)\n            case .test:\n                self.init(enum: \"test\", subnodes: params, multiline: true)\n            case .macro:\n                self.init(enum: \"macro\", subnodes: params, multiline: true)\n            }\n        }\n    }\n\n    init(from trait: TraitDescription) {\n        let enabledTraitsNode = SourceCodeFragment(\n            key: \"enabledTraits\",\n            subnodes: trait.enabledTraits.sorted().map {\n                SourceCodeFragment(string: $0)\n            }\n        )\n\n        if trait.isDefault {\n            self.init(enum: \"default\", subnodes: [enabledTraitsNode])\n            return\n        }\n\n        if trait.description == nil, trait.enabledTraits.isEmpty {\n            self.init(string: trait.name)\n            return\n        }\n\n        var params: [SourceCodeFragment] = [\n            SourceCodeFragment(key: \"name\", string: trait.name)\n        ]\n\n        if let description = trait.description {\n            params.append(\n                SourceCodeFragment(key: \"description\", string: description)\n            )\n        }\n\n        if !trait.enabledTraits.isEmpty {\n            params.append(enabledTraitsNode)\n        }\n\n        self.init(enum: \"trait\", subnodes: params)\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single target.\n    init(from target: TargetDescription) {\n        var params: [SourceCodeFragment] = []\n\n        params.append(SourceCodeFragment(key: \"name\", string: target.name))\n        \n        if let pluginCapability = target.pluginCapability {\n            let node = SourceCodeFragment(from: pluginCapability)\n            params.append(SourceCodeFragment(key: \"capability\", subnode: node))\n        }\n\n        if !target.dependencies.isEmpty {\n            let nodes = target.dependencies.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"dependencies\", subnodes: nodes))\n        }\n\n        if let path = target.path {\n            params.append(SourceCodeFragment(key: \"path\", string: path))\n        }\n\n        if let url = target.url {\n            params.append(SourceCodeFragment(key: \"url\", string: url))\n        }\n\n        if !target.exclude.isEmpty {\n            params.append(SourceCodeFragment(key: \"exclude\", strings: target.exclude))\n        }\n\n        if let sources = target.sources, !sources.isEmpty {\n            params.append(SourceCodeFragment(key: \"sources\", strings: sources))\n        }\n\n        if !target.resources.isEmpty {\n            let nodes = target.resources.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"resources\", subnodes: nodes))\n        }\n\n        if let publicHeadersPath = target.publicHeadersPath {\n            params.append(SourceCodeFragment(key: \"publicHeadersPath\", string: publicHeadersPath))\n        }\n\n        if let pkgConfig = target.pkgConfig {\n            params.append(SourceCodeFragment(key: \"pkgConfig\", string: pkgConfig))\n        }\n        \n        if let systemPackageProviders = target.providers, !systemPackageProviders.isEmpty {\n            let nodes = systemPackageProviders.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"providers\", subnodes: nodes))\n        }\n\n        let cSettings = target.settings.filter{ $0.tool == .c }\n        if !cSettings.isEmpty {\n            let nodes = cSettings.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"cSettings\", subnodes: nodes))\n        }\n\n        let cxxSettings = target.settings.filter{ $0.tool == .cxx }\n        if !cxxSettings.isEmpty {\n            let nodes = cxxSettings.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"cxxSettings\", subnodes: nodes))\n        }\n\n        let swiftSettings = target.settings.filter{ $0.tool == .swift }\n        if !swiftSettings.isEmpty {\n            let nodes = swiftSettings.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"swiftSettings\", subnodes: nodes))\n        }\n\n        let linkerSettings = target.settings.filter{ $0.tool == .linker }\n        if !linkerSettings.isEmpty {\n            let nodes = linkerSettings.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"linkerSettings\", subnodes: nodes))\n        }\n\n        if let checksum = target.checksum {\n            params.append(SourceCodeFragment(key: \"checksum\", string: checksum))\n        }\n        \n        switch target.type {\n        case .regular:\n            self.init(enum: \"target\", subnodes: params, multiline: true)\n        case .executable:\n            self.init(enum: \"executableTarget\", subnodes: params, multiline: true)\n        case .test:\n            self.init(enum: \"testTarget\", subnodes: params, multiline: true)\n        case .system:\n            self.init(enum: \"systemLibrary\", subnodes: params, multiline: true)\n        case .binary:\n            self.init(enum: \"binaryTarget\", subnodes: params, multiline: true)\n        case .plugin:\n            self.init(enum: \"plugin\", subnodes: params, multiline: true)\n        case .macro:\n            self.init(enum: \"macro\", subnodes: params, multiline: true)\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single target dependency.\n    init(from dependency: TargetDescription.Dependency) {\n        var params: [SourceCodeFragment] = []\n\n        switch dependency {\n        case .target(name: let name, condition: let condition):\n            params.append(SourceCodeFragment(key: \"name\", string: name))\n            if let condition {\n                params.append(SourceCodeFragment(key: \"condition\", subnode: SourceCodeFragment(from: condition)))\n            }\n            self.init(enum: \"target\", subnodes: params)\n            \n        case .product(name: let name, package: let packageName, moduleAliases: let aliases, condition: let condition):\n            params.append(SourceCodeFragment(key: \"name\", string: name))\n            if let packageName {\n                params.append(SourceCodeFragment(key: \"package\", string: packageName))\n            }\n            if let aliases {\n                let vals = aliases.map { SourceCodeFragment(key: $0.key.quotedForPackageManifest, string: $0.value) }\n                params.append(SourceCodeFragment(key: \"moduleAliases\", subnodes: vals))\n            }\n            if let condition {\n                params.append(SourceCodeFragment(key: \"condition\", subnode: SourceCodeFragment(from: condition)))\n            }\n            self.init(enum: \"product\", subnodes: params)\n            \n        case .byName(name: let name, condition: let condition):\n            if let condition {\n                params.append(SourceCodeFragment(key: \"name\", string: name))\n                params.append(SourceCodeFragment(key: \"condition\", subnode: SourceCodeFragment(from: condition)))\n                self.init(enum: \"byName\", subnodes: params)\n            }\n            else {\n                self.init(name.quotedForPackageManifest)\n            }\n        }\n    }\n    \n    /// Instantiates a SourceCodeFragment to represent a single package condition.\n    init(from condition: PackageConditionDescription) {\n        var params: [SourceCodeFragment] = []\n        let platformNodes: [SourceCodeFragment] = condition.platformNames.map { platformName in\n            switch platformName {\n            case \"macos\": return SourceCodeFragment(enum: \"macOS\")\n            case \"maccatalyst\": return SourceCodeFragment(enum: \"macCatalyst\")\n            case \"ios\": return SourceCodeFragment(enum: \"iOS\")\n            case \"tvos\": return SourceCodeFragment(enum: \"tvOS\")\n            case \"watchos\": return SourceCodeFragment(enum: \"watchOS\")\n            case \"visionos\": return SourceCodeFragment(enum: \"visionOS\")\n            case \"driverkit\": return SourceCodeFragment(enum: \"driverKit\")\n\n            // Among known cases, those not requiring capitalization changes\n            case \"linux\", \"windows\", \"android\", \"wasi\", \"openbsd\":\n                return SourceCodeFragment(enum: platformName)\n\n            // Known cases but not yet available\n            case \"freebsd\": fallthrough\n            default:\n                // For unknown cases, output using custom notation\n                return SourceCodeFragment(\n                    enum: \"custom\",\n                    subnodes: [.init(string: platformName)]\n                )\n            }\n        }\n        if !platformNodes.isEmpty {\n            params.append(SourceCodeFragment(key: \"platforms\", subnodes: platformNodes, multiline: false))\n        }\n        if let configName = condition.config {\n            params.append(SourceCodeFragment(key: \"configuration\", enum: configName))\n        }\n        if let traits = condition.traits {\n            params.append(\n                SourceCodeFragment(key: \"traits\", subnodes: traits.sorted().map { trait in\n                    SourceCodeFragment(string: trait)\n                })\n            )\n        }\n        self.init(enum: \"when\", subnodes: params)\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single Swift language version.\n    init(from version: SwiftLanguageVersion) {\n        switch version {\n        case .v3:\n            self.init(enum: \"v3\")\n        case .v4:\n            self.init(enum: \"v4\")\n        case .v4_2:\n            self.init(enum: \"v4_2\")\n        case .v5:\n            self.init(enum: \"v5\")\n        default:\n            self.init(enum: \"version\", subnodes: [SourceCodeFragment(string: version.rawValue)])\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single system package provider.\n    init(from systemPackageProvider: SystemPackageProviderDescription) {\n        switch systemPackageProvider {\n        case .brew(let names):\n            let params = [SourceCodeFragment(strings: names)]\n            self.init(enum: \"brew\", subnodes: params)\n        case .apt(let names):\n            let params = [SourceCodeFragment(strings: names)]\n            self.init(enum: \"apt\", subnodes: params)\n        case .yum(let names):\n            let params = [SourceCodeFragment(strings: names)]\n            self.init(enum: \"yum\", subnodes: params)\n        case .nuget(let names):\n            let params = [SourceCodeFragment(strings: names)]\n            self.init(enum: \"nuget\", subnodes: params)\n        case .pkg(let names):\n            let params = [SourceCodeFragment(strings: names)]\n            self.init(enum: \"pkg\", subnodes: params)\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single system package provider.\n    init(from resource: TargetDescription.Resource) {\n        var params: [SourceCodeFragment] = []\n        params.append(SourceCodeFragment(string: resource.path))\n        switch resource.rule {\n        case .process(let localization):\n            if let localization {\n                params.append(SourceCodeFragment(key: \"localization\", enum: localization.rawValue))\n            }\n            self.init(enum: \"process\", subnodes: params)\n        case .copy:\n            self.init(enum: \"copy\", subnodes: params)\n        case .embedInCode:\n            self.init(enum: \"embedInCode\", subnodes: params)\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single plugin capability.\n    init(from capability: TargetDescription.PluginCapability) {\n        switch capability {\n        case .buildTool:\n            self.init(enum: \"buildTool\", subnodes: [])\n        case .command(let intent, let permissions):\n            var params: [SourceCodeFragment] = []\n            params.append(SourceCodeFragment(key: \"intent\", subnode: .init(from: intent)))\n            if !permissions.isEmpty {\n                params.append(SourceCodeFragment(key: \"permissions\", subnodes: permissions.map{ .init(from: $0) }))\n            }\n            self.init(enum: \"command\", subnodes: params)\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single plugin command intent.\n    init(from intent: TargetDescription.PluginCommandIntent) {\n        switch intent {\n        case .documentationGeneration:\n            self.init(enum: \"documentationGeneration\", subnodes: [])\n        case .sourceCodeFormatting:\n            self.init(enum: \"sourceCodeFormatting\", subnodes: [])\n        case .custom(let verb, let description):\n            let params = [\n                SourceCodeFragment(key: \"verb\", string: verb),\n                SourceCodeFragment(key: \"description\", string: description)\n            ]\n            self.init(enum: \"custom\", subnodes: params)\n        }\n    }\n\n    init(from networkPermissionScope: TargetDescription.PluginNetworkPermissionScope) {\n        switch networkPermissionScope {\n        case .none:\n            self.init(enum: \"none\")\n        case .local(let ports):\n            let ports = SourceCodeFragment(key: \"ports\", subnodes: ports.map { SourceCodeFragment(\"\\($0)\") })\n            self.init(enum: \"local\", subnodes: [ports])\n        case .all(let ports):\n            let ports = SourceCodeFragment(key: \"ports\", subnodes: ports.map { SourceCodeFragment(\"\\($0)\") })\n            self.init(enum: \"all\", subnodes: [ports])\n        case .docker:\n            self.init(enum: \"docker\")\n        case .unixDomainSocket:\n            self.init(enum: \"unixDomainSocket\")\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single plugin permission.\n    init(from permission: TargetDescription.PluginPermission) {\n        switch permission {\n        case .allowNetworkConnections(let scope, let reason):\n            let scope = SourceCodeFragment(key: \"scope\", subnode: .init(from: scope))\n            let reason = SourceCodeFragment(key: \"reason\", string: reason)\n            self.init(enum: \"allowNetworkConnections\", subnodes: [scope, reason])\n        case .writeToPackageDirectory(let reason):\n            let param = SourceCodeFragment(key: \"reason\", string: reason)\n            self.init(enum: \"writeToPackageDirectory\", subnodes: [param])\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment to represent a single target build setting.\n    init(from setting: TargetBuildSettingDescription.Setting) {\n        var params: [SourceCodeFragment] = []\n\n        switch setting.kind {\n        case .headerSearchPath(let value), .linkedLibrary(let value), .linkedFramework(let value), .enableUpcomingFeature(let value), .enableExperimentalFeature(let value):\n            params.append(SourceCodeFragment(string: value))\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .strictMemorySafety:\n          self.init(enum: setting.kind.name, subnodes: [])\n        case .define(let value):\n            let parts = value.split(separator: \"=\", maxSplits: 1)\n            assert(parts.count == 1 || parts.count == 2)\n            params.append(SourceCodeFragment(string: String(parts[0])))\n            if parts.count == 2 {\n                params.append(SourceCodeFragment(key: \"to\", string: String(parts[1])))\n            }\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .interoperabilityMode(let lang):\n            params.append(SourceCodeFragment(enum: lang.rawValue))\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .unsafeFlags(let values):\n            params.append(SourceCodeFragment(strings: values))\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .swiftLanguageMode(let version):\n            params.append(SourceCodeFragment(from: version))\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .treatAllWarnings(let level):\n            params.append(SourceCodeFragment(key: \"as\", enum: level.rawValue))\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .treatWarning(let name, let level):\n            params.append(SourceCodeFragment(string: name))\n            params.append(SourceCodeFragment(key: \"as\", enum: level.rawValue))\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .enableWarning(let name):\n            params.append(SourceCodeFragment(string: name))\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .disableWarning(let name):\n            params.append(SourceCodeFragment(string: name))\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        case .defaultIsolation(let isolation):\n            switch isolation {\n            case .MainActor:\n                params.append(SourceCodeFragment(\"MainActor.self\"))\n            case .nonisolated:\n                params.append(SourceCodeFragment(\"nil\"))\n            }\n            if let condition = setting.condition {\n                params.append(SourceCodeFragment(from: condition))\n            }\n            self.init(enum: setting.kind.name, subnodes: params)\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.\n    init(from productSetting: ProductSetting, toolsVersion: ToolsVersion) {\n        switch productSetting {\n        case .bundleIdentifier(let value):\n            self.init(key: \"bundleIdentifier\", string: value)\n        case .teamIdentifier(let value):\n            self.init(key: \"teamIdentifier\", string: value)\n        case .displayVersion(let value):\n            self.init(key: \"displayVersion\", string: value)\n        case .bundleVersion(let value):\n            self.init(key: \"bundleVersion\", string: value)\n        case .iOSAppInfo(let value):\n            self.init(key: \"iOSAppInfo\", subnode: SourceCodeFragment(from: value, toolsVersion: toolsVersion))\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.\n    init(from appInfo: ProductSetting.IOSAppInfo, toolsVersion: ToolsVersion) {\n        var params: [SourceCodeFragment] = []\n        if let appIcon = appInfo.appIcon {\n            switch appIcon {\n            case let .placeholder(icon):\n                params.append(SourceCodeFragment(key: \"appIcon\", enum: \"placeholder\", subnodes: [SourceCodeFragment(from: icon)]))\n            case let .asset(name):\n                if toolsVersion < .v5_6 {\n                    params.append(SourceCodeFragment(key: \"iconAssetName\", string: \"\\(name)\"))\n                }\n                else {\n                    params.append(SourceCodeFragment(key: \"appIcon\", enum: \"asset\", string: \"\\(name)\"))\n                }\n            }\n        }\n        if let accentColor = appInfo.accentColor {\n            switch accentColor {\n            case let .presetColor(presetColor):\n                params.append(SourceCodeFragment(key: \"accentColor\", enum: \"presetColor\", subnodes: [SourceCodeFragment(from: presetColor)]))\n            case let .asset(name):\n                if toolsVersion < .v5_6 {\n                    params.append(SourceCodeFragment(key: \"accentColorAssetName\", string: \"\\(name)\"))\n                }\n                else {\n                    params.append(SourceCodeFragment(key: \"accentColor\", enum: \"asset\", string: \"\\(name)\"))\n                }\n            }\n        }\n        params.append(SourceCodeFragment(key: \"supportedDeviceFamilies\", subnodes: appInfo.supportedDeviceFamilies.map{\n            SourceCodeFragment(from: $0)\n        }))\n        params.append(SourceCodeFragment(key: \"supportedInterfaceOrientations\", subnodes: appInfo.supportedInterfaceOrientations.map{ SourceCodeFragment(from: $0)\n        }))\n        if !appInfo.capabilities.isEmpty {\n            params.append(SourceCodeFragment(key: \"capabilities\", subnodes: appInfo.capabilities.map{ SourceCodeFragment(from: $0) }))\n        }\n        if let appCategory = appInfo.appCategory {\n            params.append(SourceCodeFragment(subnode: SourceCodeFragment(from: appCategory)))\n        }\n        if let additionalInfoPlistContentFilePath = appInfo.additionalInfoPlistContentFilePath {\n            params.append(SourceCodeFragment(key: \"additionalInfoPlistContentFilePath\", string: additionalInfoPlistContentFilePath))\n        }\n        self.init(enum: \"init\", subnodes: params, multiline: true)\n    }\n    \n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.AppIcon.PlaceholderIcon.\n    init(from placeholderIcon: ProductSetting.IOSAppInfo.AppIcon.PlaceholderIcon) {\n        self.init(key: \"icon\", enum: placeholderIcon.rawValue)\n    }\n    \n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.AccentColor.PresetColor.\n    init(from presetColor: ProductSetting.IOSAppInfo.AccentColor.PresetColor) {\n        self.init(enum: presetColor.rawValue)\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.DeviceFamily.\n    init(from deviceFamily: ProductSetting.IOSAppInfo.DeviceFamily) {\n        self.init(enum: deviceFamily.rawValue)\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.DeviceFamilyCondition.\n    init(from deviceFamilyCondition: ProductSetting.IOSAppInfo.DeviceFamilyCondition) {\n        let deviceFamilyNodes = deviceFamilyCondition.deviceFamilies.map{ SourceCodeFragment(from: $0) }\n        let deviceFamiliesList = SourceCodeFragment(key: \"deviceFamilies\", subnodes: deviceFamilyNodes, multiline: false)\n        self.init(enum: \"when\", subnodes: [deviceFamiliesList])\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.InterfaceOrientation.\n    init(from orientation: ProductSetting.IOSAppInfo.InterfaceOrientation) {\n        switch orientation {\n        case .portrait(let condition):\n            self.init(enum: \"portrait\", subnodes: condition.map{ [SourceCodeFragment(from: $0)] })\n        case .portraitUpsideDown(let condition):\n            self.init(enum: \"portraitUpsideDown\", subnodes: condition.map{ [SourceCodeFragment(from: $0)] })\n        case .landscapeLeft(let condition):\n            self.init(enum: \"landscapeLeft\", subnodes: condition.map{ [SourceCodeFragment(from: $0)] })\n        case .landscapeRight(let condition):\n            self.init(enum: \"landscapeRight\", subnodes: condition.map{ [SourceCodeFragment(from: $0)] })\n        }\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.Capability.\n    init(from capability: ProductSetting.IOSAppInfo.Capability) {\n        var params: [SourceCodeFragment] = []\n        if let purposeString = capability.purposeString {\n            params.append(SourceCodeFragment(key: \"purposeString\", string: purposeString))\n        }\n        if let configuration = capability.appTransportSecurityConfiguration {\n            params.append(SourceCodeFragment(key: \"configuration\", subnode: .init(from: configuration)))\n        }\n        if let bonjourServiceTypes = capability.bonjourServiceTypes {\n            params.append(SourceCodeFragment(key: \"bonjourServiceTypes\", strings: bonjourServiceTypes))\n        }\n        if let fileAccessLocation = capability.fileAccessLocation {\n            params.append(SourceCodeFragment(enum: fileAccessLocation))\n        }\n        if let fileAccessMode = capability.fileAccessMode {\n            params.append(SourceCodeFragment(key: \"mode\", enum: fileAccessMode))\n        }\n\n        if let condition = capability.condition {\n            params.append(SourceCodeFragment(from: condition))\n        }\n        self.init(enum: capability.purpose, subnodes: params)\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.\n    init(from configuration: ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration) {\n        var params: [SourceCodeFragment] = []\n        if let allowsArbitraryLoadsInWebContent = configuration.allowsArbitraryLoadsInWebContent {\n            params.append(SourceCodeFragment(key: \"allowsArbitraryLoadsInWebContent\", boolean: allowsArbitraryLoadsInWebContent))\n        }\n        if let allowsArbitraryLoadsForMedia = configuration.allowsArbitraryLoadsForMedia {\n            params.append(SourceCodeFragment(key: \"allowsArbitraryLoadsForMedia\", boolean: allowsArbitraryLoadsForMedia))\n        }\n        if let allowsLocalNetworking = configuration.allowsLocalNetworking {\n            params.append(SourceCodeFragment(key: \"allowsLocalNetworking\", boolean: allowsLocalNetworking))\n        }\n        if let exceptionDomains = configuration.exceptionDomains {\n            let subnodes = exceptionDomains.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"exceptionDomains\", subnodes: subnodes))\n        }\n        if let pinnedDomains = configuration.pinnedDomains {\n            let subnodes = pinnedDomains.map{ SourceCodeFragment(from: $0) }\n            params.append(SourceCodeFragment(key: \"pinnedDomains\", subnodes: subnodes))\n        }\n        self.init(enum: \"init\", subnodes: params, multiline: true)\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.ExceptionDomain.\n    init(from domain: ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.ExceptionDomain) {\n        var params: [SourceCodeFragment] = []\n        params.append(SourceCodeFragment(key: \"domainName\", string: domain.domainName))\n        if let includesSubdomains = domain.includesSubdomains {\n            params.append(SourceCodeFragment(key: \"includesSubdomains\", boolean: includesSubdomains))\n        }\n        if let exceptionAllowsInsecureHTTPLoads = domain.exceptionAllowsInsecureHTTPLoads {\n            params.append(SourceCodeFragment(key: \"exceptionAllowsInsecureHTTPLoads\", boolean: exceptionAllowsInsecureHTTPLoads))\n        }\n        if let exceptionMinimumTLSVersion = domain.exceptionMinimumTLSVersion {\n            params.append(SourceCodeFragment(key: \"exceptionMinimumTLSVersion\", string: exceptionMinimumTLSVersion))\n        }\n        if let exceptionRequiresForwardSecrecy = domain.exceptionRequiresForwardSecrecy {\n            params.append(SourceCodeFragment(key: \"exceptionRequiresForwardSecrecy\", boolean: exceptionRequiresForwardSecrecy))\n        }\n        if let requiresCertificateTransparency = domain.requiresCertificateTransparency {\n            params.append(SourceCodeFragment(key: \"requiresCertificateTransparency\", boolean: requiresCertificateTransparency))\n        }\n        self.init(enum: \"init\", subnodes: params, multiline: true)\n    }\n\n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.ExceptionDomain.\n    init(from domain: ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.PinnedDomain) {\n        var params: [SourceCodeFragment] = []\n        params.append(SourceCodeFragment(key: \"domainName\", string: domain.domainName))\n        if let includesSubdomains = domain.includesSubdomains {\n            params.append(SourceCodeFragment(key: \"includesSubdomains\", boolean: includesSubdomains))\n        }\n        if let pinnedCAIdentities = domain.pinnedCAIdentities {\n            let subnodes = pinnedCAIdentities.map{ SourceCodeFragment(stringPairs: $0.sorted{ $0.key < $1.key }.map{ ($0.key, $0.value) }) }\n            params.append(SourceCodeFragment(key: \"pinnedCAIdentities\", subnodes: subnodes))\n        }\n        if let pinnedLeafIdentities = domain.pinnedLeafIdentities {\n            let subnodes = pinnedLeafIdentities.map{ SourceCodeFragment(stringPairs: $0.sorted{ $0.key < $1.key }.map{ ($0.key, $0.value) }) }\n            params.append(SourceCodeFragment(key: \"pinnedLeafIdentities\", subnodes: subnodes))\n        }\n        self.init(enum: \"init\", subnodes: params, multiline: true)\n    }\n    \n    /// Instantiates a SourceCodeFragment from a single ProductSetting.IOSAppInfo.AppCategory.\n    init(from appCategory: ProductSetting.IOSAppInfo.AppCategory) {\n        switch appCategory.rawValue {\n        case \"public.app-category.action-games\":\n            self.init(key: \"appCategory\", enum: \"actionGames\")\n        case \"public.app-category.adventure-games\":\n            self.init(key: \"appCategory\", enum: \"adventureGames\")\n        case \"public.app-category.arcade-games\":\n            self.init(key: \"appCategory\", enum: \"arcadeGames\")\n        case \"public.app-category.board-games\":\n            self.init(key: \"appCategory\", enum: \"boardGames\")\n        case \"public.app-category.business\":\n            self.init(key: \"appCategory\", enum: \"business\")\n        case \"public.app-category.card-games\":\n            self.init(key: \"appCategory\", enum: \"cardGames\")\n        case \"public.app-category.casino-games\":\n            self.init(key: \"appCategory\", enum: \"casinoGames\")\n        case \"public.app-category.developer-tools\":\n            self.init(key: \"appCategory\", enum: \"developerTools\")\n        case \"public.app-category.dice-games\":\n            self.init(key: \"appCategory\", enum: \"diceGames\")\n        case \"public.app-category.education\":\n            self.init(key: \"appCategory\", enum: \"education\")\n        case \"public.app-category.educational-games\":\n            self.init(key: \"appCategory\", enum: \"educationalGames\")\n        case \"public.app-category.entertainment\":\n            self.init(key: \"appCategory\", enum: \"entertainment\")\n        case \"public.app-category.family-games\":\n            self.init(key: \"appCategory\", enum: \"familyGames\")\n        case \"public.app-category.finance\":\n            self.init(key: \"appCategory\", enum: \"finance\")\n        case \"public.app-category.games\":\n            self.init(key: \"appCategory\", enum: \"games\")\n        case \"public.app-category.graphics-design\":\n            self.init(key: \"appCategory\", enum: \"graphicsDesign\")\n        case \"public.app-category.healthcare-fitness\":\n            self.init(key: \"appCategory\", enum: \"healthcareFitness\")\n        case \"public.app-category.kids-games\":\n            self.init(key: \"appCategory\", enum: \"kidsGames\")\n        case \"public.app-category.lifestyle\":\n            self.init(key: \"appCategory\", enum: \"lifestyle\")\n        case \"public.app-category.medical\":\n            self.init(key: \"appCategory\", enum: \"medical\")\n        case \"public.app-category.music\":\n            self.init(key: \"appCategory\", enum: \"music\")\n        case \"public.app-category.music-games\":\n            self.init(key: \"appCategory\", enum: \"musicGames\")\n        case \"public.app-category.news\":\n            self.init(key: \"appCategory\", enum: \"news\")\n        case \"public.app-category.photography\":\n            self.init(key: \"appCategory\", enum: \"photography\")\n        case \"public.app-category.productivity\":\n            self.init(key: \"appCategory\", enum: \"productivity\")\n        case \"public.app-category.puzzle-games\":\n            self.init(key: \"appCategory\", enum: \"puzzleGames\")\n        case \"public.app-category.racing-games\":\n            self.init(key: \"appCategory\", enum: \"racingGames\")\n        case \"public.app-category.reference\":\n            self.init(key: \"appCategory\", enum: \"reference\")\n        case \"public.app-category.role-playing-games\":\n            self.init(key: \"appCategory\", enum: \"rolePlayingGames\")\n        case \"public.app-category.simulation-games\":\n            self.init(key: \"appCategory\", enum: \"simulationGames\")\n        case \"public.app-category.social-networking\":\n            self.init(key: \"appCategory\", enum: \"socialNetworking\")\n        case \"public.app-category.sports\":\n            self.init(key: \"appCategory\", enum: \"sports\")\n        case \"public.app-category.sports-games\":\n            self.init(key: \"appCategory\", enum: \"sportsGames\")\n        case \"public.app-category.strategy-games\":\n            self.init(key: \"appCategory\", enum: \"strategyGames\")\n        case \"public.app-category.travel\":\n            self.init(key: \"appCategory\", enum: \"travel\")\n        case \"public.app-category.trivia-games\":\n            self.init(key: \"appCategory\", enum: \"triviaGames\")\n        case \"public.app-category.utilities\":\n            self.init(key: \"appCategory\", enum: \"utilities\")\n        case \"public.app-category.video\":\n            self.init(key: \"appCategory\", enum: \"video\")\n        case \"public.app-category.weather\":\n            self.init(key: \"appCategory\", enum: \"weather\")\n        case \"public.app-category.word-games\":\n            self.init(key: \"appCategory\", enum: \"wordGames\")\n        default:\n            self.init(key: \"appCategory\", string: appCategory.rawValue)\n        }\n    }\n}\n\n\n/// Convenience initializers for key-value pairs of simple types.  These make\n/// the logic above much simpler.\npublic extension SourceCodeFragment {\n    \n    /// Initializes a SourceCodeFragment for a boolean in a generated manifest.\n    init(key: String? = nil, boolean: Bool) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        self.init(prefix + (boolean ? \"true\" : \"false\"))\n    }\n\n    /// Initializes a SourceCodeFragment for an integer in a generated manifest.\n    init(key: String? = nil, integer: Int) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        self.init(prefix + \"\\(integer)\")\n    }\n\n    /// Initializes a SourceCodeFragment for a quoted string in a generated manifest.\n    init(key: String? = nil, string: String) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        self.init(prefix + string.quotedForPackageManifest)\n    }\n\n    /// Initializes a SourceCodeFragment for an enum in a generated manifest.\n    init(key: String? = nil, enum: String, string: String) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        let subnode = SourceCodeFragment(string: string)\n        self.init(prefix + \".\" + `enum`, delimiters: .parentheses, multiline: false, subnodes: [subnode])\n    }\n\n    /// Initializes a SourceCodeFragment for an enum in a generated manifest.\n    init(key: String? = nil, enum: String, strings: [String]) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        let subnodes = strings.map{ SourceCodeFragment($0.quotedForPackageManifest) }\n        self.init(prefix + \".\" + `enum`, delimiters: .parentheses, multiline: false, subnodes: subnodes)\n    }\n\n    /// Initializes a SourceCodeFragment for an enum in a generated manifest.\n    init(key: String? = nil, enum: String, subnodes: [SourceCodeFragment]? = nil, multiline: Bool = false) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        self.init(prefix + \".\" + `enum`, delimiters: .parentheses, multiline: multiline, subnodes: subnodes)\n    }\n\n    /// Initializes a SourceCodeFragment for a string list in a generated manifest.\n    init(key: String? = nil, strings: [String], multiline: Bool = false) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        let subnodes = strings.map{ SourceCodeFragment($0.quotedForPackageManifest) }\n        self.init(prefix, delimiters: .brackets, multiline: multiline, subnodes: subnodes)\n    }\n\n    /// Initializes a SourceCodeFragment for a string map in a generated manifest.\n    init(key: String? = nil, stringPairs: [(String, String)], multiline: Bool = false) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        let subnodes = stringPairs.isEmpty ? [SourceCodeFragment(\":\")] : stringPairs.map{ SourceCodeFragment($0.quotedForPackageManifest + \": \" + $1.quotedForPackageManifest) }\n        self.init(prefix, delimiters: .brackets, multiline: multiline, subnodes: subnodes)\n    }\n\n    /// Initializes a SourceCodeFragment for a node in a generated manifest.\n    init(key: String? = nil, subnode: SourceCodeFragment) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        self.init(prefix, delimiters: .none, multiline: false, subnodes: [subnode])\n    }\n\n    /// Initializes a SourceCodeFragment for a list of nodes in a generated manifest.\n    init(key: String? = nil, subnodes: [SourceCodeFragment], multiline: Bool = true) {\n        let prefix = key.map{ $0 + \": \" } ?? \"\"\n        self.init(prefix, delimiters: .brackets, multiline: multiline, subnodes: subnodes)\n    }\n}\n\n\n/// Helper type to emit source code.  Represents one node of source code, as an\n/// arbitrary string followed by an optional child list, optionally enclosed in\n/// a pair of delimiters.\n///\n/// The source code generation works by creating SourceCodeFragments, and then\n/// rendering them into string form with appropriate formatting.\npublic struct SourceCodeFragment {\n    /// A literal prefix to emit at the start of the source code fragment.\n    var literal: String\n    \n    /// The type of delimiters to use around the subfragments (if any).\n    var delimiters: Delimiters\n    \n    /// Whether or not to emit newlines before the subfragments (if any).\n    var multiline: Bool\n    \n    /// Any subfragments; no delimiters are emitted if none.\n    var subnodes: [SourceCodeFragment]?\n    \n    /// Type of delimiters to emit around any subfragments.\n    public enum Delimiters {\n        case none\n        case brackets\n        case parentheses\n    }\n    \n    public init(_ literal: String, delimiters: Delimiters = .none,\n         multiline: Bool = true, subnodes: [SourceCodeFragment]? = nil) {\n        self.literal = literal\n        self.delimiters = delimiters\n        self.multiline = multiline\n        self.subnodes = subnodes\n    }\n    \n    func generateSourceCode(indent: String = \"\") -> String {\n        var string = literal\n        if let subnodes {\n            switch delimiters {\n            case .none: break\n            case .brackets: string.append(\"[\")\n            case .parentheses: string.append(\"(\")\n            }\n            if multiline { string.append(\"\\n\") }\n            let subindent = indent + (multiline ? \"    \" : \"\")\n            for (idx, subnode) in subnodes.enumerated() {\n                if multiline { string.append(subindent) }\n                string.append(subnode.generateSourceCode(indent: subindent))\n                if idx < subnodes.count-1 {\n                    string.append(multiline ? \",\\n\" : \", \")\n                }\n            }\n            if multiline {\n                string.append(\"\\n\")\n                string.append(indent)\n            }\n            switch delimiters {\n            case .none: break\n            case .brackets: string.append(\"]\")\n            case .parentheses: string.append(\")\")\n            }\n        }\n        return string\n    }\n}\n\nextension Optional {\n    fileprivate static func precedes(\n        _ a: Wrapped?, _ b: Wrapped?,\n        compareWrapped: (Wrapped, Wrapped) -> Bool\n    ) -> Bool {\n        switch (a, b) {\n        case (.none, .none): return false\n        case (.none, .some): return true\n        case (.some, .none): return false\n        case (.some(let a), .some(let b)):\n            return compareWrapped(a, b)\n        }\n    }\n}\n\nextension PackageDependency.Trait {\n    fileprivate static func precedes(_ a: PackageDependency.Trait, _ b: PackageDependency.Trait) -> Bool {\n        if a.name != b.name { return a.name < b.name }\n\n        if a.condition != b.condition {\n            return Optional.precedes(a.condition, b.condition) { a, b in\n                PackageDependency.Trait.Condition.precedes(a, b)\n            }\n        }\n\n        return false\n    }\n}\n\nextension PackageDependency.Trait.Condition {\n    fileprivate static func precedes(_ a: PackageDependency.Trait.Condition, _ b: PackageDependency.Trait.Condition) -> Bool {\n        if a.traits != b.traits {\n            return Optional.precedes(a.traits, b.traits) { a, b in\n                a.sorted().lexicographicallyPrecedes(b.sorted())\n            }\n        }\n\n        return false\n    }\n}\n\nextension TargetBuildSettingDescription.Kind {\n    fileprivate var name: String {\n        switch self {\n        case .headerSearchPath:\n            return \"headerSearchPath\"\n        case .define:\n            return \"define\"\n        case .linkedLibrary:\n            return \"linkedLibrary\"\n        case .linkedFramework:\n            return \"linkedFramework\"\n        case .unsafeFlags:\n            return \"unsafeFlags\"\n        case .interoperabilityMode:\n            return \"interoperabilityMode\"\n        case .enableUpcomingFeature:\n            return \"enableUpcomingFeature\"\n        case .enableExperimentalFeature:\n            return \"enableExperimentalFeature\"\n        case .strictMemorySafety:\n            return \"strictMemorySafety\"\n        case .swiftLanguageMode:\n            return \"swiftLanguageMode\"\n        case .treatAllWarnings:\n            return \"treatAllWarnings\"\n        case .treatWarning:\n            return \"treatWarning\"\n        case .enableWarning:\n            return \"enableWarning\"\n        case .disableWarning:\n            return \"disableWarning\"\n        case .defaultIsolation:\n            return \"defaultIsolation\"\n        }\n    }\n}\n\nextension String {\n    fileprivate var quotedForPackageManifest: String {\n        return \"\\\"\" + self\n            .replacing(\"\\\\\", with: \"\\\\\\\\\")\n            .replacing(\"\\\"\", with: \"\\\\\\\"\")\n            + \"\\\"\"\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/MinimumDeploymentTarget.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport TSCUtility\n\nimport class Basics.AsyncProcess\n\npublic struct MinimumDeploymentTarget {\n    private struct MinimumDeploymentTargetKey: Hashable {\n        let binaryPath: Basics.AbsolutePath\n        let platform: PackageModel.Platform\n    }\n\n    private let minimumDeploymentTargets = ThreadSafeKeyValueStore<MinimumDeploymentTargetKey,PlatformVersion>()\n    private let xcTestMinimumDeploymentTargets = ThreadSafeKeyValueStore<PackageModel.Platform,PlatformVersion>()\n\n    public static let `default`: MinimumDeploymentTarget = .init()\n\n    private init() {\n    }\n\n    public func computeMinimumDeploymentTarget(of binaryPath: Basics.AbsolutePath, platform: PackageModel.Platform) throws -> PlatformVersion {\n        try self.minimumDeploymentTargets.memoize(MinimumDeploymentTargetKey(binaryPath: binaryPath, platform: platform)) {\n            return try Self.computeMinimumDeploymentTarget(of: binaryPath, platform: platform) ?? platform.oldestSupportedVersion\n        }\n    }\n\n    public func computeXCTestMinimumDeploymentTarget(for platform: PackageModel.Platform) -> PlatformVersion {\n        self.xcTestMinimumDeploymentTargets.memoize(platform) {\n            return Self.computeXCTestMinimumDeploymentTarget(for: platform)\n        }\n    }\n\n    static func computeMinimumDeploymentTarget(of binaryPath: Basics.AbsolutePath, platform: PackageModel.Platform) throws -> PlatformVersion? {\n        guard let (_, platformName) = platform.sdkNameAndPlatform else {\n            return nil\n        }\n\n        let runResult = try AsyncProcess.popen(arguments: [\"/usr/bin/xcrun\", \"vtool\", \"-show-build\", binaryPath.pathString])\n        var lines = try runResult.utf8Output().components(separatedBy: \"\\n\")\n        while !lines.isEmpty {\n            let first = lines.removeFirst()\n            if first.contains(\"platform \\(platformName)\"), let line = lines.first, line.contains(\"minos\") {\n                return line.components(separatedBy: \" \").last.map(PlatformVersion.init(stringLiteral:))\n            }\n        }\n        return nil\n    }\n\n    /// Temporary hard-coded minimum deployment targets for test targets.\n    static func absoluteXCTestMinimumDeploymentTarget(platform: PackageModel.Platform) -> PlatformVersion? {\n        if platform == .macOS {\n            return PlatformVersion(\"14.0\")\n        }\n        return nil\n    }\n\n    static func computeXCTestMinimumDeploymentTarget(with runResult: AsyncProcessResult, platform: PackageModel.Platform) throws -> PlatformVersion? {\n        guard let output = try runResult.utf8Output().spm_chuzzle() else { return nil }\n        let sdkPath = try Basics.AbsolutePath(validating: output)\n        let xcTestPath = try Basics.AbsolutePath(validating: \"Developer/Library/Frameworks/XCTest.framework/XCTest\", relativeTo: sdkPath)\n        let swiftTestingPath = try Basics.AbsolutePath(validating: \"Developer/Library/Frameworks/Testing.framework/Testing\", relativeTo: sdkPath)\n        let targets = [\n            try computeMinimumDeploymentTarget(of: xcTestPath, platform: platform),\n            try computeMinimumDeploymentTarget(of: swiftTestingPath, platform: platform),\n            absoluteXCTestMinimumDeploymentTarget(platform: platform),\n        ]\n        return targets.compactMap(\\.self).max()\n    }\n\n    static func computeXCTestMinimumDeploymentTarget(for platform: PackageModel.Platform) -> PlatformVersion {\n        guard let (sdkName, _) = platform.sdkNameAndPlatform else {\n            return platform.oldestSupportedVersion\n        }\n\n        // On macOS, we are determining the deployment target by looking at the XCTest and Swift Testing binaries.\n        #if os(macOS)\n        do {\n            let runResult = try AsyncProcess.popen(arguments: [\"/usr/bin/xcrun\", \"--sdk\", sdkName, \"--show-sdk-platform-path\"])\n\n            if let version = try computeXCTestMinimumDeploymentTarget(with: runResult, platform: platform) {\n                return version\n            }\n        } catch { } // we do not treat this a fatal and instead use the fallback minimum deployment target\n        #endif\n\n        return platform.oldestSupportedVersion\n    }\n}\n\nprivate extension PackageModel.Platform {\n    var sdkNameAndPlatform: (String, String)? {\n        switch self {\n        case .macOS:\n            return (\"macosx\", \"MACOS\")\n        case .macCatalyst:\n            return (\"macosx\", \"MACCATALYST\")\n        case .iOS:\n            return (\"iphoneos\", \"IOS\")\n        case .tvOS:\n            return (\"appletvos\", \"TVOS\")\n        case .watchOS:\n            return (\"watchos\", \"WATCHOS\")\n        case .visionOS:\n            return (\"xros\", \"XROS\")\n        case .driverKit:\n            return nil // DriverKit does not support XCTest.\n        default:\n            return nil\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Module/BinaryModule.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\n\n@available(*, deprecated, renamed: \"BinaryModule\")\npublic typealias BinaryTarget = BinaryModule\n\npublic final class BinaryModule: Module {\n    /// Description of the module type used in `swift package describe` output. Preserved for backwards compatibility.\n    public override class var typeDescription: String { \"BinaryTarget\" }\n\n    /// The kind of binary artifact.\n    public let kind: Kind\n    \n    /// The original source of the binary artifact.\n    public let origin: Origin\n\n    /// The binary artifact path.\n    public var artifactPath: AbsolutePath {\n        return self.sources.root\n    }\n\n    public init(\n        name: String,\n        kind: Kind,\n        path: AbsolutePath,\n        origin: Origin\n    ) {\n        self.origin = origin\n        self.kind = kind\n        let sources = Sources(paths: [], root: path)\n        super.init(\n            name: name,\n            type: .binary,\n            path: .root,\n            sources: sources,\n            dependencies: [],\n            packageAccess: false,\n            buildSettings: .init(),\n            buildSettingsDescription: [],\n            pluginUsages: [],\n            usesUnsafeFlags: false,\n            implicit: false\n        )\n    }\n\n    public enum Kind: CaseIterable {\n        public static var allCases: [BinaryModule.Kind] {\n            [.xcframework, .artifactsArchive(types: []), .unknown]\n        }\n        case xcframework\n\n        /// Artifact bundles containing static libraries.\n        case artifactsArchive(types: [ArtifactsArchiveMetadata.ArtifactType])\n\n        case unknown // for non-downloaded artifacts\n\n        public var fileExtension: String {\n            switch self {\n            case .xcframework:\n                return \"xcframework\"\n            case .artifactsArchive:\n                return \"artifactbundle\"\n            case .unknown:\n                return \"unknown\"\n            }\n        }\n\n        public var isUnknown: Bool {\n            switch self {\n            case .xcframework, .artifactsArchive:\n                return false\n            case .unknown:\n                return true\n            }\n        }\n    }\n\n    public var containsExecutable: Bool {\n        switch self.kind {\n        case .xcframework:\n            return false\n        case .artifactsArchive(let types):\n            return types.contains(.executable)\n        case .unknown:\n            return false\n        }\n    }\n\n    public enum Origin: Equatable {\n\n        /// Represents an artifact that was downloaded from a remote URL.\n        case remote(url: String)\n\n        /// Represents an artifact that was available locally.\n        case local\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Module/ClangModule.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport struct Basics.StringError\nimport TSCBasic\n\n@available(*, deprecated, renamed: \"ClangModule\")\npublic typealias ClangTarget = ClangModule\n\npublic final class ClangModule: Module {\n    /// Description of the module type used in `swift package describe` output. Preserved for backwards compatibility.\n    public override class var typeDescription: String { \"ClangTarget\" }\n\n    /// The default public include directory component.\n    public static let defaultPublicHeadersComponent = \"include\"\n\n    /// The path to include directory.\n    public let includeDir: Basics.AbsolutePath\n\n    /// The target's module map type, which determines whether this target vends a custom module map, a generated module map, or no module map at all.\n    public let moduleMapType: ModuleMapType\n\n    /// The headers present in the target.\n    ///\n    /// Note that this contains both public and non-public headers.\n    public let headers: [Basics.AbsolutePath]\n\n    /// True if this is a C++ target.\n    public let isCXX: Bool\n\n    /// The C language standard flag.\n    public let cLanguageStandard: String?\n\n    /// The C++ language standard flag.\n    public let cxxLanguageStandard: String?\n\n    public init(\n        name: String,\n        potentialBundleName: String? = nil,\n        cLanguageStandard: String?,\n        cxxLanguageStandard: String?,\n        includeDir: Basics.AbsolutePath,\n        moduleMapType: ModuleMapType,\n        headers: [Basics.AbsolutePath] = [],\n        type: Kind,\n        path: Basics.AbsolutePath,\n        sources: Sources,\n        resources: [Resource] = [],\n        ignored: [Basics.AbsolutePath] = [],\n        others: [Basics.AbsolutePath] = [],\n        dependencies: [Module.Dependency] = [],\n        buildSettings: BuildSettings.AssignmentTable = .init(),\n        buildSettingsDescription: [TargetBuildSettingDescription.Setting] = [],\n        usesUnsafeFlags: Bool,\n        implicit: Bool\n    ) throws {\n        guard includeDir.isDescendantOfOrEqual(to: sources.root) else {\n            throw StringError(\"\\(includeDir) should be contained in the source root \\(sources.root)\")\n        }\n        self.isCXX = sources.containsCXXFiles\n        self.cLanguageStandard = cLanguageStandard\n        self.cxxLanguageStandard = cxxLanguageStandard\n        self.includeDir = includeDir\n        self.moduleMapType = moduleMapType\n        self.headers = headers\n        super.init(\n            name: name,\n            potentialBundleName: potentialBundleName,\n            type: type,\n            path: path,\n            sources: sources,\n            resources: resources,\n            ignored: ignored,\n            others: others,\n            dependencies: dependencies,\n            packageAccess: false,\n            buildSettings: buildSettings,\n            buildSettingsDescription: buildSettingsDescription,\n            pluginUsages: [],\n            usesUnsafeFlags: usesUnsafeFlags,\n            implicit: implicit\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Module/Module.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport TSCUtility\n\n@available(*, deprecated, renamed: \"Module\")\npublic typealias Target = Module\n\npublic class Module {\n    /// Description of the module type used in `swift package describe` output. Preserved for backwards compatibility.\n    public class var typeDescription: String { fatalError(\"implement in a subclass\") }\n    /// The module kind.\n    public enum Kind: String {\n        case executable\n        case library\n        case systemModule = \"system-target\"\n        case test\n        case binary\n        case plugin\n        case snippet\n        case `macro`\n    }\n\n    /// A reference to a product from a module dependency.\n    public struct ProductReference {\n        /// The name of the product dependency.\n        public let name: String\n\n        /// The name of the package containing the product.\n        public let package: String?\n\n        /// Module aliases for targets of this product dependency. The key is an\n        /// original target name and the value is a new unique name that also\n        /// becomes the name of its .swiftmodule binary.\n        public let moduleAliases: [String: String]?\n\n        /// Fully qualified name for this product dependency: package ID + name of the product\n        public var identity: String {\n            if let package {\n                return package.lowercased() + \"_\" + name\n            } else {\n                // this is hit only if this product is referenced `.byName(name)`\n                // which assumes the name of this product, its package, and its module\n                // all have the same name\n                return name.lowercased() + \"_\" + name\n            }\n        }\n\n        /// Creates a product reference instance.\n        public init(name: String, package: String?, moduleAliases: [String: String]? = nil) {\n            self.name = name\n            self.package = package\n            self.moduleAliases = moduleAliases\n        }\n    }\n\n    /// A module dependency to a module or product.\n    public enum Dependency {\n        /// A dependency referencing another target, with conditions.\n        case module(_ target: Module, conditions: [PackageCondition])\n\n        /// A dependency referencing a product, with conditions.\n        case product(_ product: ProductReference, conditions: [PackageCondition])\n\n\n        @available(*, deprecated, renamed: \"module\")\n        public var target: Module? { self.module }\n\n        /// The module if the dependency is a target dependency.\n        public var module: Module? {\n            if case .module(let target, _) = self {\n                return target\n            } else {\n                return nil\n            }\n        }\n\n        /// The product reference if the dependency is a product dependency.\n        public var product: ProductReference? {\n            if case .product(let product, _) = self {\n                return product\n            } else {\n                return nil\n            }\n        }\n\n        /// The dependency conditions.\n        public var conditions: [PackageCondition] {\n            switch self {\n            case .module(_, let conditions):\n                return conditions\n            case .product(_, let conditions):\n                return conditions\n            }\n        }\n\n        /// The name of the target or product of the dependency.\n        public var name: String {\n            switch self {\n            case .module(let target, _):\n                return target.name\n            case .product(let product, _):\n                return product.name\n            }\n        }\n    }\n\n    /// A usage of a plugin module or product. Implemented as a dependency\n    /// for now and added to the `dependencies` array, since they currently\n    /// have exactly the same characteristics and to avoid duplicating the\n    /// implementation for now.\n    public typealias PluginUsage = Dependency\n\n    /// The name of the module.\n    ///\n    /// NOTE: This name is not the language-level module (i.e., the importable\n    /// name) name in many cases, instead use ``Target/c99name`` if you need uniqueness.\n    public private(set) var name: String\n\n    /// Module aliases needed to build this module. The key is an original name of a\n    /// dependent module and the value is a new unique name mapped to the name\n    /// of its .swiftmodule binary.\n    public private(set) var moduleAliases: [String: String]?\n    /// Used to store pre-chained / pre-overriden module aliases\n    public private(set) var prechainModuleAliases: [String: String]?\n    /// Used to store aliases that should be referenced directly in source code\n    public private(set) var directRefAliases: [String: [String]]?\n\n    /// Add module aliases (if applicable) for dependencies of this module.\n    ///\n    /// For example, adding an alias `Bar` for a module name `Foo` will result in\n    /// compiling references to `Foo` in source code of this module as `Bar.swiftmodule`.\n    /// If the name argument `Foo` is the same as this module's name, this module will be\n    /// renamed as `Bar` and the resulting binary will be `Bar.swiftmodule`.\n    ///\n    /// - Parameters:\n    ///   - name: The original name of a dependent module or this module\n    ///   - alias: A new unique name mapped to the resulting binary name\n    public func addModuleAlias(for name: String, as alias: String) {\n        if moduleAliases == nil {\n            moduleAliases = [name: alias]\n        } else {\n            moduleAliases?[name] = alias\n        }\n    }\n\n    public func removeModuleAlias(for name: String) {\n        moduleAliases?.removeValue(forKey: name)\n        if moduleAliases?.isEmpty ?? false {\n            moduleAliases = nil\n        }\n    }\n\n    public func addPrechainModuleAlias(for name: String, as alias: String) {\n        if prechainModuleAliases == nil {\n            prechainModuleAliases = [name: alias]\n        } else {\n            prechainModuleAliases?[name] = alias\n        }\n    }\n    public func addDirectRefAliases(for name: String, as aliases: [String]) {\n        if directRefAliases == nil {\n            directRefAliases = [name: aliases]\n        } else {\n            directRefAliases?[name] = aliases\n        }\n    }\n\n    @discardableResult\n    public func applyAlias() -> Bool {\n        // If there's an alias for this module, rename\n        if let alias = moduleAliases?[name] {\n            self.name = alias\n            self.c99name = alias.spm_mangledToC99ExtendedIdentifier()\n            return true\n        }\n        return false\n    }\n\n    /// The dependencies of this module.\n    public let dependencies: [Dependency]\n\n    /// The language-level module name.\n    public private(set) var c99name: String\n\n    /// The bundle name, if one is being generated.\n    public var bundleName: String? {\n        return resources.isEmpty ? nil : potentialBundleName\n    }\n    public let potentialBundleName: String?\n\n    /// Suffix that's expected for test targets.\n    public static let testModuleNameSuffix = \"Tests\"\n\n    /// The kind of module.\n    public let type: Kind\n\n    /// If true, access to package declarations from other modules is allowed.\n    public let packageAccess: Bool\n\n    /// The path of the module.\n    public let path: AbsolutePath\n\n    /// The sources for the module.\n    public let sources: Sources\n\n    /// The resource files in the module.\n    public let resources: [Resource]\n\n    /// Files in the target that were marked as ignored.\n    public let ignored: [AbsolutePath]\n\n    /// Other kinds of files in the module.\n    public let others: [AbsolutePath]\n\n    /// The build settings assignments of this module.\n    public package(set) var buildSettings: BuildSettings.AssignmentTable\n\n    @_spi(SwiftPMInternal)\n    public let buildSettingsDescription: [TargetBuildSettingDescription.Setting]\n\n    /// The usages of package plugins by this module.\n    public let pluginUsages: [PluginUsage]\n\n    /// Whether or not this target uses any custom unsafe flags.\n    public let usesUnsafeFlags: Bool\n\n    /// Whether this module comes from a declaration in the manifest file\n    /// or was synthesized (i.e. some test modules are synthesized).\n    public let implicit: Bool\n\n    init(\n        name: String,\n        potentialBundleName: String? = nil,\n        type: Kind,\n        path: AbsolutePath,\n        sources: Sources,\n        resources: [Resource] = [],\n        ignored: [AbsolutePath] = [],\n        others: [AbsolutePath] = [],\n        dependencies: [Module.Dependency],\n        packageAccess: Bool,\n        buildSettings: BuildSettings.AssignmentTable,\n        buildSettingsDescription: [TargetBuildSettingDescription.Setting],\n        pluginUsages: [PluginUsage],\n        usesUnsafeFlags: Bool,\n        implicit: Bool\n    ) {\n        self.name = name\n        self.potentialBundleName = potentialBundleName\n        self.type = type\n        self.path = path\n        self.sources = sources\n        self.resources = resources\n        self.ignored = ignored\n        self.others = others\n        self.dependencies = dependencies\n        self.c99name = self.name.spm_mangledToC99ExtendedIdentifier()\n        self.packageAccess = packageAccess\n        self.buildSettings = buildSettings\n        self.buildSettingsDescription = buildSettingsDescription\n        self.pluginUsages = pluginUsages\n        self.usesUnsafeFlags = usesUnsafeFlags\n        self.implicit = implicit\n    }\n}\n\nextension Module: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n\n    public static func == (lhs: Module, rhs: Module) -> Bool {\n        ObjectIdentifier(lhs) == ObjectIdentifier(rhs)\n    }\n}\n\nextension Module: Comparable {\n    public static func < (lhs: Module, rhs: Module) -> Bool {\n        return lhs.name < rhs.name\n    }\n}\n\nextension Module: CustomStringConvertible {\n    public var description: String {\n        return \"<\\(Swift.type(of: self)): \\(name)>\"\n    }\n}\n\npublic extension Sequence where Iterator.Element == Module {\n    var executables: [Module] {\n        return filter {\n            switch $0.type {\n            case .binary:\n                return ($0 as? BinaryModule)?.containsExecutable == true\n            case .executable, .snippet, .macro:\n                return true\n            default:\n                return false\n            }\n        }\n    }\n}\n\nextension [TargetBuildSettingDescription.Setting] {\n    @_spi(SwiftPMInternal)\n    public var swiftSettings: Self {\n        self.filter { $0.tool == .swift }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Module/PluginModule.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n@available(*, deprecated, renamed: \"PluginModule\")\npublic typealias PluginTarget = PluginModule\n\npublic final class PluginModule: Module {\n    /// Description of the module type used in `swift package describe` output. Preserved for backwards compatibility.\n    public override class var typeDescription: String { \"PluginTarget\" }\n\n    /// Declared capability of the plugin.\n    public let capability: PluginCapability\n\n    /// API version to use for PackagePlugin API availability.\n    public let apiVersion: ToolsVersion\n\n    public init(\n        name: String,\n        sources: Sources,\n        apiVersion: ToolsVersion,\n        pluginCapability: PluginCapability,\n        dependencies: [Module.Dependency] = [],\n        packageAccess: Bool\n    ) {\n        self.capability = pluginCapability\n        self.apiVersion = apiVersion\n        super.init(\n            name: name,\n            type: .plugin,\n            path: .root,\n            sources: sources,\n            dependencies: dependencies,\n            packageAccess: packageAccess,\n            buildSettings: .init(),\n            buildSettingsDescription: [],\n            pluginUsages: [],\n            usesUnsafeFlags: false,\n            implicit: false\n        )\n    }\n}\n\npublic enum PluginCapability: Hashable {\n    case buildTool\n    case command(intent: PluginCommandIntent, permissions: [PluginPermission])\n\n    public init(from desc: TargetDescription.PluginCapability) {\n        switch desc {\n        case .buildTool:\n            self = .buildTool\n        case .command(let intent, let permissions):\n            self = .command(intent: .init(from: intent), permissions: permissions.map{ .init(from: $0) })\n        }\n    }\n}\n\npublic enum PluginCommandIntent: Hashable {\n    case documentationGeneration\n    case sourceCodeFormatting\n    case custom(verb: String, description: String)\n\n    public init(from desc: TargetDescription.PluginCommandIntent) {\n        switch desc {\n        case .documentationGeneration:\n            self = .documentationGeneration\n        case .sourceCodeFormatting:\n            self = .sourceCodeFormatting\n        case .custom(let verb, let description):\n            self = .custom(verb: verb, description: description)\n        }\n    }\n}\n\npublic enum PluginNetworkPermissionScope: Hashable {\n    case none\n    case local(ports: [Int])\n    case all(ports: [Int])\n    case docker\n    case unixDomainSocket\n\n    init(_ scope: TargetDescription.PluginNetworkPermissionScope) {\n        switch scope {\n        case .none: self = .none\n        case .local(let ports): self = .local(ports: ports)\n        case .all(let ports): self = .all(ports: ports)\n        case .docker: self = .docker\n        case .unixDomainSocket: self = .unixDomainSocket\n        }\n    }\n\n    public var label: String {\n        switch self {\n        case .all: return \"all\"\n        case .local: return \"local\"\n        case .none: return \"none\"\n        case .docker: return \"docker unix domain socket\"\n        case .unixDomainSocket: return \"unix domain socket\"\n        }\n    }\n\n    public var ports: [Int] {\n        switch self {\n        case .all(let ports): return ports\n        case .local(let ports): return ports\n        case .none, .docker, .unixDomainSocket: return []\n        }\n    }\n}\n\npublic enum PluginPermission: Hashable {\n    case allowNetworkConnections(scope: PluginNetworkPermissionScope, reason: String)\n    case writeToPackageDirectory(reason: String)\n\n    public init(from desc: TargetDescription.PluginPermission) {\n        switch desc {\n        case .allowNetworkConnections(let scope, let reason):\n            self = .allowNetworkConnections(scope: .init(scope), reason: reason)\n        case .writeToPackageDirectory(let reason):\n            self = .writeToPackageDirectory(reason: reason)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Module/SwiftModule.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport struct Basics.SwiftVersion\n\n@available(*, deprecated, renamed: \"SwiftModule\")\npublic typealias SwiftTarget = SwiftModule\n\npublic final class SwiftModule: Module {\n    /// Description of the module type used in `swift package describe` output. Preserved for backwards compatibility.\n    public override class var typeDescription: String { \"SwiftTarget\" }\n\n    /// The default name for the test entry point file located in a package.\n    public static let defaultTestEntryPointName = \"XCTMain.swift\"\n\n    /// The list of all supported names for the test entry point file located in a package.\n    public static var testEntryPointNames: [String] {\n        [defaultTestEntryPointName, \"LinuxMain.swift\"]\n    }\n\n    public init(\n        name: String,\n        dependencies: [Module.Dependency],\n        packageAccess: Bool,\n        testDiscoverySrc: Sources,\n        buildSettings: BuildSettings.AssignmentTable = .init(),\n        implicit: Bool) {\n        self.declaredSwiftVersions = []\n\n        super.init(\n            name: name,\n            type: .library,\n            path: .root,\n            sources: testDiscoverySrc,\n            dependencies: dependencies,\n            packageAccess: packageAccess,\n            buildSettings: buildSettings,\n            buildSettingsDescription: [],\n            pluginUsages: [],\n            usesUnsafeFlags: false,\n            implicit: implicit\n        )\n    }\n\n    /// The list of swift versions declared by the manifest.\n    public let declaredSwiftVersions: [SwiftLanguageVersion]\n\n    public init(\n        name: String,\n        potentialBundleName: String? = nil,\n        type: Kind,\n        path: AbsolutePath,\n        sources: Sources,\n        resources: [Resource] = [],\n        ignored: [AbsolutePath] = [],\n        others: [AbsolutePath] = [],\n        dependencies: [Module.Dependency] = [],\n        packageAccess: Bool,\n        declaredSwiftVersions: [SwiftLanguageVersion] = [],\n        buildSettings: BuildSettings.AssignmentTable = .init(),\n        buildSettingsDescription: [TargetBuildSettingDescription.Setting] = [],\n        pluginUsages: [PluginUsage] = [],\n        usesUnsafeFlags: Bool,\n        implicit: Bool\n    ) {\n        self.declaredSwiftVersions = declaredSwiftVersions\n        super.init(\n            name: name,\n            potentialBundleName: potentialBundleName,\n            type: type,\n            path: path,\n            sources: sources,\n            resources: resources,\n            ignored: ignored,\n            others: others,\n            dependencies: dependencies,\n            packageAccess: packageAccess,\n            buildSettings: buildSettings,\n            buildSettingsDescription: buildSettingsDescription,\n            pluginUsages: pluginUsages,\n            usesUnsafeFlags: usesUnsafeFlags,\n            implicit: implicit\n        )\n    }\n\n    /// Create an executable Swift target from test entry point file.\n    public init(\n        name: String,\n        dependencies: [Module.Dependency],\n        packageAccess: Bool,\n        testEntryPointPath: AbsolutePath\n    ) {\n        // Look for the first swift test target and use the same swift version\n        // for linux main target. This will need to change if we move to a model\n        // where we allow per target swift language version build settings.\n        let swiftTestTarget = dependencies.first {\n            guard case .module(let target as SwiftModule, _) = $0 else { return false }\n            return target.type == .test\n        }.flatMap { $0.module as? SwiftModule }\n\n        // We need to select the latest Swift language version that can\n        // satisfy the current tools version but there is not a good way to\n        // do that currently.\n        var buildSettings: BuildSettings.AssignmentTable = .init()\n        do {\n            let toolsSwiftVersion = swiftTestTarget?.buildSettings.assignments[.SWIFT_VERSION]?\n                .filter(\\.default)\n                .filter(\\.conditions.isEmpty)\n                .flatMap(\\.values)\n\n            var versionAssignment = BuildSettings.Assignment()\n            versionAssignment.values = toolsSwiftVersion ?? [String(SwiftVersion.current.major)]\n\n            buildSettings.add(versionAssignment, for: .SWIFT_VERSION)\n        }\n\n        self.declaredSwiftVersions = []\n        let sources = Sources(paths: [testEntryPointPath], root: testEntryPointPath.parentDirectory)\n\n        super.init(\n            name: name,\n            type: .executable,\n            path: .root,\n            sources: sources,\n            dependencies: dependencies,\n            packageAccess: packageAccess,\n            buildSettings: buildSettings,\n            buildSettingsDescription: [],\n            pluginUsages: [],\n            usesUnsafeFlags: false,\n            implicit: true\n        )\n    }\n\n    public var supportsTestableExecutablesFeature: Bool {\n        // Exclude macros from testable executables if they are built as dylibs.\n        #if BUILD_MACROS_AS_DYLIBS\n        return type == .executable || type == .snippet\n        #else\n        return type == .executable || type == .macro || type == .snippet\n        #endif\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Module/SystemLibraryModule.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\n\n@available(*, deprecated, renamed: \"SystemLibraryModule\")\npublic typealias SystemLibraryTarget = SystemLibraryModule\n\npublic final class SystemLibraryModule: Module {\n    /// Description of the module type used in `swift package describe` output. Preserved for backwards compatibility.\n    public override class var typeDescription: String { \"SystemLibraryTarget\" }\n\n    /// The name of pkgConfig file, if any.\n    public let pkgConfig: String?\n\n    /// List of system package providers, if any.\n    public let providers: [SystemPackageProviderDescription]?\n\n    public init(\n        name: String,\n        path: AbsolutePath,\n        isImplicit: Bool = true,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProviderDescription]? = nil\n    ) {\n        let sources = Sources(paths: [], root: path)\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        super.init(\n            name: name,\n            type: .systemModule,\n            path: sources.root,\n            sources: sources,\n            dependencies: [],\n            packageAccess: false,\n            buildSettings: .init(),\n            buildSettingsDescription: [],\n            pluginUsages: [],\n            usesUnsafeFlags: false,\n            implicit: isImplicit\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/ModuleMapType.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// A type of module map layout.  Contains all the information needed to generate or use a module map for a target that can have C-style headers.\npublic enum ModuleMapType: Equatable {\n    /// No module map file.\n    case none\n    /// A custom module map file.\n    case custom(AbsolutePath)\n    /// An umbrella header included by a generated module map file.\n    case umbrellaHeader(AbsolutePath)\n    /// An umbrella directory included by a generated module map file.\n    case umbrellaDirectory(AbsolutePath)\n}\n\nextension ModuleMapType: Codable {\n    private enum CodingKeys: String, CodingKey {\n        case none, custom, umbrellaHeader, umbrellaDirectory\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        if let path = try container.decodeIfPresent(AbsolutePath.self, forKey: .custom) {\n            self = .custom(path)\n        }\n        else if let path = try container.decodeIfPresent(AbsolutePath.self, forKey: .umbrellaHeader) {\n            self = .umbrellaHeader(path)\n        }\n        else if let path = try container.decodeIfPresent(AbsolutePath.self, forKey: .umbrellaDirectory) {\n            self = .umbrellaDirectory(path)\n        }\n        else {\n            self = .none\n        }\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .none:\n            break\n        case .custom(let path):\n            try container.encode(path, forKey: .custom)\n        case .umbrellaHeader(let path):\n            try container.encode(path, forKey: .umbrellaHeader)\n        case .umbrellaDirectory(let path):\n            try container.encode(path, forKey: .umbrellaDirectory)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/PackageIdentity.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport TSCBasic\n\n/// The canonical identifier for a package, based on its source location.\npublic struct PackageIdentity: CustomStringConvertible, Sendable {\n    /// A textual representation of this instance.\n    public let description: String\n\n    /// Creates a package identity from a string.\n    /// - Parameter value: A string used to identify a package.\n    init(_ value: String) {\n        self.description = value\n    }\n\n    /// Creates a package identity from a URL.\n    /// - Parameter url: The package's URL.\n    public init(url: SourceControlURL) {\n        self.init(urlString: url.absoluteString)\n    }\n\n    /// Creates a package identity from a URL.\n    /// - Parameter urlString: The package's URL.\n    // FIXME: deprecate this\n    public init(urlString: String) {\n        self.description = PackageIdentityParser(urlString).description\n    }\n\n    /// Creates a package identity from a file path.\n    /// - Parameter path: An absolute path to the package.\n    public init(path: Basics.AbsolutePath) {\n        self.description = PackageIdentityParser(path.pathString).description\n    }\n\n    /// Creates a plain package identity for a root package\n    /// - Parameter value: A string used to identify a package, will be used unmodified\n    public static func plain(_ value: String) -> PackageIdentity {\n        PackageIdentity(value)\n    }\n\n    @available(*, deprecated, message: \"use .registry instead\")\n    public var scopeAndName: (scope: Scope, name: Name)? {\n        self.registry.flatMap { (scope: $0.scope, name: $0.name) }\n    }\n\n    public var registry: RegistryIdentity? {\n        let components = self.description.split(separator: \".\", maxSplits: 1, omittingEmptySubsequences: true)\n        guard components.count == 2,\n              let scope = Scope(components.first),\n              let name = Name(components.last)\n        else {\n            return .none\n        }\n\n        return RegistryIdentity(\n            scope: scope,\n            name: name,\n            underlying: self\n        )\n    }\n\n    public var isRegistry: Bool {\n        self.registry != nil\n    }\n\n    public struct RegistryIdentity: Hashable, CustomStringConvertible, Sendable {\n        public let scope: PackageIdentity.Scope\n        public let name: PackageIdentity.Name\n        public let underlying: PackageIdentity\n\n        public var description: String {\n            self.underlying.description\n        }\n    }\n}\n\nextension PackageIdentity: Equatable, Comparable {\n    private func compare(to other: PackageIdentity) -> ComparisonResult {\n        self.description.caseInsensitiveCompare(other.description)\n    }\n\n    public static func == (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {\n        lhs.compare(to: rhs) == .orderedSame\n    }\n\n    public static func < (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {\n        lhs.compare(to: rhs) == .orderedAscending\n    }\n\n    public static func > (lhs: PackageIdentity, rhs: PackageIdentity) -> Bool {\n        lhs.compare(to: rhs) == .orderedDescending\n    }\n}\n\nextension PackageIdentity: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(self.description.lowercased())\n    }\n}\n\nextension PackageIdentity: Codable {\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.singleValueContainer()\n        let description = try container.decode(String.self)\n        self.init(description)\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.singleValueContainer()\n        try container.encode(self.description)\n    }\n}\n\n// MARK: -\n\nextension PackageIdentity {\n    /// Provides a namespace for related packages within a package registry.\n    public struct Scope: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral,\n        Sendable\n    {\n        public let description: String\n\n        public init(validating description: String) throws {\n            guard !description.isEmpty else {\n                throw StringError(\"The minimum length of a package scope is 1 character.\")\n            }\n\n            guard description.count <= 39 else {\n                throw StringError(\"The maximum length of a package scope is 39 characters.\")\n            }\n\n            for (index, character) in zip(description.indices, description) {\n                guard character.isASCII,\n                      character.isLetter ||\n                      character.isNumber ||\n                      character == \"-\"\n                else {\n                    throw StringError(\"A package scope consists of alphanumeric characters and hyphens.\")\n                }\n\n                if character.isPunctuation {\n                    switch (index, description.index(after: index)) {\n                    case (description.startIndex, _):\n                        throw StringError(\"Hyphens may not occur at the beginning of a scope.\")\n                    case (_, description.endIndex):\n                        throw StringError(\"Hyphens may not occur at the end of a scope.\")\n                    case (_, let nextIndex) where description[nextIndex].isPunctuation:\n                        throw StringError(\"Hyphens may not occur consecutively within a scope.\")\n                    default:\n                        continue\n                    }\n                }\n            }\n\n            self.description = description\n        }\n\n        public init?(_ description: String) {\n            guard let scope = try? Scope(validating: description) else { return nil }\n            self = scope\n        }\n\n        fileprivate init?(_ substring: String.SubSequence?) {\n            guard let substring else { return nil }\n            self.init(String(substring))\n        }\n\n        // MARK: - Equatable & Comparable\n\n        private func compare(to other: Scope) -> ComparisonResult {\n            // Package scopes are case-insensitive (for example, `mona` ≍ `MONA`).\n            self.description.caseInsensitiveCompare(other.description)\n        }\n\n        public static func == (lhs: Scope, rhs: Scope) -> Bool {\n            lhs.compare(to: rhs) == .orderedSame\n        }\n\n        public static func < (lhs: Scope, rhs: Scope) -> Bool {\n            lhs.compare(to: rhs) == .orderedAscending\n        }\n\n        public static func > (lhs: Scope, rhs: Scope) -> Bool {\n            lhs.compare(to: rhs) == .orderedDescending\n        }\n\n        // MARK: - Hashable\n\n        public func hash(into hasher: inout Hasher) {\n            hasher.combine(self.description.lowercased())\n        }\n\n        // MARK: - ExpressibleByStringLiteral\n\n        public init(stringLiteral value: StringLiteralType) {\n            try! self.init(validating: value)\n        }\n    }\n\n    /// Uniquely identifies a package in a scope\n    public struct Name: LosslessStringConvertible, Hashable, Equatable, Comparable, ExpressibleByStringLiteral,\n        Sendable\n    {\n        public let description: String\n\n        public init(validating description: String) throws {\n            guard !description.isEmpty else {\n                throw StringError(\"The minimum length of a package name is 1 character.\")\n            }\n\n            guard description.count <= 100 else {\n                throw StringError(\"The maximum length of a package name is 100 characters.\")\n            }\n\n            for (index, character) in zip(description.indices, description) {\n                guard character.isASCII,\n                      character.isLetter ||\n                      character.isNumber ||\n                      character == \"-\" ||\n                      character == \"_\"\n                else {\n                    throw StringError(\"A package name consists of alphanumeric characters, underscores, and hyphens.\")\n                }\n\n                if character.isPunctuation {\n                    switch (index, description.index(after: index)) {\n                    case (description.startIndex, _):\n                        throw StringError(\"Hyphens and underscores may not occur at the beginning of a name.\")\n                    case (_, description.endIndex):\n                        throw StringError(\"Hyphens and underscores may not occur at the end of a name.\")\n                    case (_, let nextIndex) where description[nextIndex].isPunctuation:\n                        throw StringError(\"Hyphens and underscores may not occur consecutively within a name.\")\n                    default:\n                        continue\n                    }\n                }\n            }\n\n            self.description = description\n        }\n\n        public init?(_ description: String) {\n            guard let name = try? Name(validating: description) else { return nil }\n            self = name\n        }\n\n        fileprivate init?(_ substring: String.SubSequence?) {\n            guard let substring else { return nil }\n            self.init(String(substring))\n        }\n\n        // MARK: - Equatable & Comparable\n\n        private func compare(to other: Name) -> ComparisonResult {\n            // Package scopes are case-insensitive (for example, `LinkedList` ≍ `LINKEDLIST`).\n            self.description.caseInsensitiveCompare(other.description)\n        }\n\n        public static func == (lhs: Name, rhs: Name) -> Bool {\n            lhs.compare(to: rhs) == .orderedSame\n        }\n\n        public static func < (lhs: Name, rhs: Name) -> Bool {\n            lhs.compare(to: rhs) == .orderedAscending\n        }\n\n        public static func > (lhs: Name, rhs: Name) -> Bool {\n            lhs.compare(to: rhs) == .orderedDescending\n        }\n\n        // MARK: - Hashable\n\n        public func hash(into hasher: inout Hasher) {\n            hasher.combine(self.description.lowercased())\n        }\n\n        // MARK: - ExpressibleByStringLiteral\n\n        public init(stringLiteral value: StringLiteralType) {\n            try! self.init(validating: value)\n        }\n    }\n}\n\n// MARK: -\n\nstruct PackageIdentityParser {\n    /// A textual representation of this instance.\n    public let description: String\n\n    /// Instantiates an instance of the conforming type from a string representation.\n    public init(_ string: String) {\n        self.description = Self.computeDefaultName(fromLocation: string).lowercased()\n    }\n\n    /// Compute the default name of a package given its URL.\n    public static func computeDefaultName(fromURL url: SourceControlURL) -> String {\n        Self.computeDefaultName(fromLocation: url.absoluteString)\n    }\n\n    /// Compute the default name of a package given its path.\n    public static func computeDefaultName(fromPath path: Basics.AbsolutePath) -> String {\n        Self.computeDefaultName(fromLocation: path.pathString)\n    }\n\n    /// Compute the default name of a package given its location.\n    public static func computeDefaultName(fromLocation url: String) -> String {\n        #if os(Windows)\n        let isSeparator: (Character) -> Bool = { $0 == \"/\" || $0 == \"\\\\\" }\n        #else\n        let isSeparator: (Character) -> Bool = { $0 == \"/\" }\n        #endif\n\n        // Get the last path component of the URL.\n        // Drop the last character in case it's a trailing slash.\n        var endIndex = url.endIndex\n        if let lastCharacter = url.last, isSeparator(lastCharacter) {\n            endIndex = url.index(before: endIndex)\n        }\n\n        let separatorIndex = url[..<endIndex].lastIndex(where: isSeparator)\n        let startIndex = separatorIndex.map { url.index(after: $0) } ?? url.startIndex\n        var lastComponent = url[startIndex ..< endIndex]\n\n        // Strip `.git` suffix if present.\n        if lastComponent.hasSuffix(\".git\") {\n            lastComponent = lastComponent.dropLast(4)\n        }\n\n        return String(lastComponent)\n    }\n}\n\n/// A canonicalized package location.\n///\n/// A package may declare external packages as dependencies in its manifest.\n/// Each external package is uniquely identified by the location of its source code.\n///\n/// An external package dependency may itself have one or more external package dependencies,\n/// known as _transitive dependencies_.\n/// When multiple packages have dependencies in common,\n/// Swift Package Manager determines which version of that package should be used\n/// (if any exist that satisfy all specified requirements)\n/// in a process called package resolution.\n///\n/// External package dependencies are located by a URL\n/// (which may be an implicit `file://` URL in the form of a file path).\n/// For the purposes of package resolution,\n/// package URLs are case-insensitive (mona ≍ MONA)\n/// and normalization-insensitive (n + ◌̃ ≍ ñ).\n/// Swift Package Manager takes additional steps to canonicalize URLs\n/// to resolve insignificant differences between URLs.\n/// For example,\n/// the URLs `https://example.com/Mona/LinkedList` and `git@example.com:mona/linkedlist`\n/// are equivalent, in that they both resolve to the same source code repository,\n/// despite having different scheme, authority, and path components.\n///\n/// The `PackageIdentity` type canonicalizes package locations by\n/// performing the following operations:\n///\n/// * Removing the scheme component, if present\n///   ```\n///   https://example.com/mona/LinkedList → example.com/mona/LinkedList\n///   ```\n/// * Removing the userinfo component (preceded by `@`), if present:\n///   ```\n///   git@example.com/mona/LinkedList → example.com/mona/LinkedList\n///   ```\n/// * Removing the port subcomponent, if present:\n///   ```\n///   example.com:443/mona/LinkedList → example.com/mona/LinkedList\n///   ```\n/// * Replacing the colon (`:`) preceding the path component in \"`scp`-style\" URLs:\n///   ```\n///   git@example.com:mona/LinkedList.git → example.com/mona/LinkedList\n///   ```\n/// * Expanding the tilde (`~`) to the provided user, if applicable:\n///   ```\n///   ssh://mona@example.com/~/LinkedList.git → example.com/~mona/LinkedList\n///   ```\n/// * Removing percent-encoding from the path component, if applicable:\n///   ```\n///   example.com/mona/%F0%9F%94%97List → example.com/mona/🔗List\n///   ```\n/// * Removing the `.git` file extension from the path component, if present:\n///   ```\n///   example.com/mona/LinkedList.git → example.com/mona/LinkedList\n///   ```\n/// * Removing the trailing slash (`/`) in the path component, if present:\n///   ```\n///   example.com/mona/LinkedList/ → example.com/mona/LinkedList\n///   ```\n/// * Removing the fragment component (preceded by `#`), if present:\n///   ```\n///   example.com/mona/LinkedList#installation → example.com/mona/LinkedList\n///   ```\n/// * Removing the query component (preceded by `?`), if present:\n///   ```\n///   example.com/mona/LinkedList?utm_source=forums.swift.org → example.com/mona/LinkedList\n///   ```\n/// * Adding a leading slash (`/`) for `file://` URLs and absolute file paths:\n///   ```\n///   file:///Users/mona/LinkedList → /Users/mona/LinkedList\n///   ```\npublic struct CanonicalPackageLocation: Equatable, CustomStringConvertible, Hashable {\n    /// A textual representation of this instance.\n    public let description: String\n\n    /// Instantiates an instance of the conforming type from a string representation.\n    public init(_ string: String) {\n        self.description = computeCanonicalLocation(string).description\n    }\n}\n\n/// Similar to `CanonicalPackageLocation` but differentiates based on the scheme.\npublic struct CanonicalPackageURL: Equatable, CustomStringConvertible {\n    public let description: String\n    public let scheme: String?\n\n    public init(_ string: String) {\n        let location = computeCanonicalLocation(string)\n        self.description = location.description\n        self.scheme = location.scheme\n    }\n}\n\nprivate func computeCanonicalLocation(_ string: String) -> (description: String, scheme: String?) {\n    var description = string.precomposedStringWithCanonicalMapping.lowercased()\n\n    // Remove the scheme component, if present.\n    let detectedScheme = description.dropSchemeComponentPrefixIfPresent()\n    var scheme = detectedScheme\n\n    // Remove the userinfo subcomponent (user / password), if present.\n    if case (let user, _)? = description.dropUserinfoSubcomponentPrefixIfPresent() {\n        // If a user was provided, perform tilde expansion, if applicable.\n        description.replaceFirstOccurrenceIfPresent(of: \"/~/\", with: \"/~\\(user)/\")\n\n        if user == \"git\", scheme == nil {\n            scheme = \"ssh\"\n        }\n    }\n\n    // Remove the port subcomponent, if present.\n    description.removePortComponentIfPresent()\n\n    // Remove the fragment component, if present.\n    description.removeFragmentComponentIfPresent()\n\n    // Remove the query component, if present.\n    description.removeQueryComponentIfPresent()\n\n    // Accommodate \"`scp`-style\" SSH URLs\n    if detectedScheme == nil || detectedScheme == \"ssh\" {\n        description.replaceFirstOccurrenceIfPresent(of: \":\", before: description.firstIndex(of: \"/\"), with: \"/\")\n    }\n\n    // Split the remaining string into path components,\n    // filtering out empty path components and removing valid percent encodings.\n    var components = description.split(omittingEmptySubsequences: true, whereSeparator: isSeparator)\n        .compactMap { $0.removingPercentEncoding ?? String($0) }\n\n    // Remove the `.git` suffix from the last path component.\n    var lastPathComponent = components.popLast() ?? \"\"\n    lastPathComponent.removeSuffixIfPresent(\".git\")\n    components.append(lastPathComponent)\n\n    description = components.joined(separator: \"/\")\n\n    // Prepend a leading slash for file URLs and paths\n    if detectedScheme == \"file\" || string.first.flatMap(isSeparator) ?? false {\n        scheme = \"file\"\n        description.insert(\"/\", at: description.startIndex)\n    }\n\n    return (description, scheme)\n}\n\n#if os(Windows)\nfileprivate let isSeparator: (Character) -> Bool = { $0 == \"/\" || $0 == \"\\\\\" }\n#else\nfileprivate let isSeparator: (Character) -> Bool = { $0 == \"/\" }\n#endif\n\nextension Character {\n    fileprivate var isDigit: Bool {\n        switch self {\n        case \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\":\n            return true\n        default:\n            return false\n        }\n    }\n\n    fileprivate var isAllowedInURLScheme: Bool {\n        isLetter || self.isDigit || self == \"+\" || self == \"-\" || self == \".\"\n    }\n}\n\nextension String {\n    @discardableResult\n    private mutating func removePrefixIfPresent<T: StringProtocol>(_ prefix: T) -> Bool {\n        guard hasPrefix(prefix) else { return false }\n        removeFirst(prefix.count)\n        return true\n    }\n\n    @discardableResult\n    fileprivate mutating func removeSuffixIfPresent<T: StringProtocol>(_ suffix: T) -> Bool {\n        guard hasSuffix(suffix) else { return false }\n        removeLast(suffix.count)\n        return true\n    }\n\n    @discardableResult\n    fileprivate mutating func dropSchemeComponentPrefixIfPresent() -> String? {\n        if let rangeOfDelimiter = range(of: \"://\"),\n           self[startIndex].isLetter,\n           self[..<rangeOfDelimiter.lowerBound].allSatisfy(\\.isAllowedInURLScheme)\n        {\n            defer { self.removeSubrange(..<rangeOfDelimiter.upperBound) }\n\n            return String(self[..<rangeOfDelimiter.lowerBound])\n        }\n\n        return nil\n    }\n\n    @discardableResult\n    fileprivate mutating func dropUserinfoSubcomponentPrefixIfPresent() -> (user: String, password: String?)? {\n        if let indexOfAtSign = firstIndex(of: \"@\"),\n           let indexOfFirstPathComponent = firstIndex(where: isSeparator),\n           indexOfAtSign < indexOfFirstPathComponent\n        {\n            defer { self.removeSubrange(...indexOfAtSign) }\n\n            let userinfo = self[..<indexOfAtSign]\n            var components = userinfo.split(separator: \":\", maxSplits: 2, omittingEmptySubsequences: false)\n            guard components.count > 0 else { return nil }\n            let user = String(components.removeFirst())\n            let password = components.last.map(String.init)\n\n            return (user, password)\n        }\n\n        return nil\n    }\n\n    @discardableResult\n    fileprivate mutating func removePortComponentIfPresent() -> Bool {\n        if let indexOfFirstPathComponent = firstIndex(where: isSeparator),\n           let startIndexOfPort = firstIndex(of: \":\"),\n           startIndexOfPort < endIndex,\n           let endIndexOfPort = self[index(after: startIndexOfPort)...].lastIndex(where: { $0.isDigit }),\n           endIndexOfPort <= indexOfFirstPathComponent\n        {\n            self.removeSubrange(startIndexOfPort ... endIndexOfPort)\n            return true\n        }\n\n        return false\n    }\n\n    @discardableResult\n    fileprivate mutating func removeFragmentComponentIfPresent() -> Bool {\n        if let index = firstIndex(of: \"#\") {\n            self.removeSubrange(index...)\n        }\n\n        return false\n    }\n\n    @discardableResult\n    fileprivate mutating func removeQueryComponentIfPresent() -> Bool {\n        if let index = firstIndex(of: \"?\") {\n            self.removeSubrange(index...)\n        }\n\n        return false\n    }\n\n    @discardableResult\n    fileprivate mutating func replaceFirstOccurrenceIfPresent<T: StringProtocol, U: StringProtocol>(\n        of string: T,\n        before index: Index? = nil,\n        with replacement: U\n    ) -> Bool {\n        guard let range = range(of: string) else { return false }\n\n        if let index, range.lowerBound >= index {\n            return false\n        }\n\n        self.replaceSubrange(range, with: replacement)\n        return true\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/PackageModel.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport struct Foundation.URL\n\nimport enum TSCUtility.PackageLocation\nimport struct TSCUtility.Version\n\n/// The basic package representation.\n///\n/// The package manager conceptually works with five different kinds of\n/// packages, of which this is only one:\n///\n/// 1. Informally, the repository containing a package can be thought of in some\n/// sense as the \"package\". However, this isn't accurate, because the actual\n/// Package is derived from its manifest, a Package only actually exists at a\n/// particular repository revision (typically a tag). We also may eventually\n/// want to support multiple packages within a single repository.\n///\n/// 2. The `PackageDescription.Package` as defined inside a manifest is a\n/// declarative specification for (part of) the package but not the object that\n/// the package manager itself is typically working with internally. Rather,\n/// that specification is primarily used to load the package (see the\n/// `PackageLoading` target).\n///\n/// 3. A loaded `PackageModel.Manifest` is an abstract representation of a\n/// package, and is used during package dependency resolution. It contains the\n/// loaded PackageDescription and information necessary for dependency\n/// resolution, but nothing else.\n///\n/// 4. A loaded `PackageModel.Package` which has had dependencies loaded and\n/// resolved. This is the result after `Get.get()`.\n///\n/// 5. A loaded package, as in #4, for which the targets have also been\n/// loaded. There is not currently a data structure for this, but it is the\n/// result after `PackageLoading.transmute()`.\npublic final class Package {\n    /// The identity of the package.\n    public let identity: PackageIdentity\n\n    /// The manifest describing the package.\n    public let manifest: Manifest\n\n    /// The local path of the package.\n    public let path: AbsolutePath\n\n    /// The targets contained in the package.\n    public var modules: [Module]\n\n    /// The products produced by the package.\n    public let products: [Product]\n\n    // The directory containing the targets which did not explicitly specify\n    // their path. If all targets are explicit, this is the preferred path for\n    // future targets.\n    public let targetSearchPath: AbsolutePath\n\n    // The directory containing the test targets which did not explicitly specify\n    // their path. If all test targets are explicit, this is the preferred path\n    // for future test targets.\n    public let testTargetSearchPath: AbsolutePath\n\n    public init(\n        identity: PackageIdentity,\n        manifest: Manifest,\n        path: AbsolutePath,\n        targets: [Module],\n        products: [Product],\n        targetSearchPath: AbsolutePath,\n        testTargetSearchPath: AbsolutePath\n    ) {\n        self.identity = identity\n        self.manifest = manifest\n        self.path = path\n        self.modules = targets\n        self.products = products\n        self.targetSearchPath = targetSearchPath\n        self.testTargetSearchPath = testTargetSearchPath\n    }\n\n    public enum Error: Swift.Error, Equatable {\n        case noManifest(at: AbsolutePath, version: Version?)\n    }\n}\n\nextension Package: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n\n    public static func == (lhs: Package, rhs: Package) -> Bool {\n        ObjectIdentifier(lhs) == ObjectIdentifier(rhs)\n    }\n}\n\nextension Package {\n    public var diagnosticsMetadata: ObservabilityMetadata {\n        return .packageMetadata(identity: self.identity, kind: self.manifest.packageKind)\n    }\n}\n\nextension Package: CustomStringConvertible {\n    public var description: String {\n        return self.identity.description\n    }\n}\n\nextension Package.Error: CustomStringConvertible {\n   public var description: String {\n        switch self {\n        case .noManifest(let path, let version):\n            var string = \"\\(path) has no Package.swift manifest\"\n            if let version {\n                string += \" for version \\(version)\"\n            }\n            return string\n        }\n    }\n}\n\nextension Manifest {\n    public var disambiguateByProductIDs: Bool {\n        return self.toolsVersion >= .v5_8\n    }\n    public var usePackageNameFlag: Bool {\n        return self.toolsVersion >= .v5_9\n    }\n}\n\nextension ObservabilityMetadata {\n    public static func packageMetadata(identity: PackageIdentity, kind: PackageReference.Kind) -> Self {\n        var metadata = ObservabilityMetadata()\n        metadata.packageIdentity = identity\n        metadata.packageKind = kind\n        return metadata\n    }\n}\n\nextension ObservabilityMetadata {\n    public var packageIdentity: PackageIdentity? {\n        get {\n            self[PackageIdentityKey.self]\n        }\n        set {\n            self[PackageIdentityKey.self] = newValue\n        }\n    }\n\n    enum PackageIdentityKey: Key {\n        typealias Value = PackageIdentity\n    }\n}\n\n/*\nextension ObservabilityMetadata {\n    public var packageLocation: String? {\n        get {\n            self[PackageLocationKey.self]\n        }\n        set {\n            self[PackageLocationKey.self] = newValue\n        }\n    }\n\n    enum PackageLocationKey: Key {\n        typealias Value = String\n    }\n}*/\n\nextension ObservabilityMetadata {\n    public var packageKind: PackageReference.Kind? {\n        get {\n            self[PackageKindKey.self]\n        }\n        set {\n            self[PackageKindKey.self] = newValue\n        }\n    }\n\n    enum PackageKindKey: Key {\n        typealias Value = PackageReference.Kind\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/PackageReference.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n/// A package reference.\n///\n/// This represents a reference to a package containing its identity and location.\npublic struct PackageReference {\n    /// The kind of package reference.\n    public enum Kind: Hashable, CustomStringConvertible, Sendable {\n        /// A root package.\n        case root(AbsolutePath)\n\n        /// A non-root local package.\n        case fileSystem(AbsolutePath)\n\n        /// A local source package.\n        case localSourceControl(AbsolutePath)\n\n        /// A remote source package.\n        case remoteSourceControl(SourceControlURL)\n\n        /// A package from  a registry.\n        case registry(PackageIdentity)\n\n        // FIXME: we should not need this once we migrate off URLs\n        //@available(*, deprecated)\n        public var locationString: String {\n            switch self {\n            case .root(let path):\n                return path.pathString\n            case .fileSystem(let path):\n                return path.pathString\n            case .localSourceControl(let path):\n                return path.pathString\n            case .remoteSourceControl(let url):\n                return url.absoluteString\n            case .registry(let identity):\n                // FIXME: this is a placeholder\n                return identity.description\n            }\n        }\n\n        // FIXME: we should not need this once we migrate off URLs\n        //@available(*, deprecated)\n        public var canonicalLocation: CanonicalPackageLocation {\n            return CanonicalPackageLocation(self.locationString)\n        }\n\n        public var description: String {\n            switch self {\n            case .root(let path):\n                return \"root \\(path)\"\n            case .fileSystem(let path):\n                return \"fileSystem \\(path)\"\n            case .localSourceControl(let path):\n                return \"localSourceControl \\(path)\"\n            case .remoteSourceControl(let url):\n                return \"remoteSourceControl \\(url)\"\n            case .registry(let identity):\n                return \"registry \\(identity)\"\n            }\n        }\n\n        // FIXME: ideally this would not be required and we can check on the enum directly\n        public var isRoot: Bool {\n            if case .root = self {\n                return true\n            } else {\n                return false\n            }\n        }\n\n        public var isRemote: Bool {\n            switch self {\n            case .registry, .remoteSourceControl, .localSourceControl:\n                return true\n            case .root, .fileSystem:\n                return false\n            }\n        }\n    }\n\n    /// The identity of the package.\n    public let identity: PackageIdentity\n\n    /// The name of the package, if available.\n    // soft deprecated 11/21\n    public private(set) var deprecatedName: String\n\n    /// The location of the package.\n    ///\n    /// This could be a remote repository, local repository or local package.\n    // FIXME: we should not need this once we migrate off URLs\n    //@available(*, deprecated)\n    public var locationString: String {\n        self.kind.locationString\n    }\n\n    // FIXME: we should not need this once we migrate off URLs\n    //@available(*, deprecated)\n    public var canonicalLocation: CanonicalPackageLocation {\n        self.kind.canonicalLocation\n    }\n\n    /// The kind of package: root, local, or remote.\n    public let kind: Kind\n\n    /// Create a package reference given its identity and kind.\n    public init(identity: PackageIdentity, kind: Kind, name: String? = nil) {\n        self.identity = identity\n        self.kind = kind\n        switch kind {\n        case .root(let path):\n            self.deprecatedName = name ?? PackageIdentityParser.computeDefaultName(fromPath: path)\n        case .fileSystem(let path):\n            self.deprecatedName = name ?? PackageIdentityParser.computeDefaultName(fromPath: path)\n        case .localSourceControl(let path):\n            self.deprecatedName = name ?? PackageIdentityParser.computeDefaultName(fromPath: path)\n        case .remoteSourceControl(let url):\n            self.deprecatedName = name ?? PackageIdentityParser.computeDefaultName(fromURL: url)\n        case .registry(let identity):\n            // FIXME: this is a placeholder\n            self.deprecatedName = name ?? identity.description\n        }\n    }\n\n    /// Create a new package reference object with the given name.\n    public func withName(_ newName: String) -> PackageReference {\n        return PackageReference(identity: self.identity, kind: self.kind, name: newName)\n    }\n\n    public static func root(identity: PackageIdentity, path: AbsolutePath) -> PackageReference {\n        PackageReference(identity: identity, kind: .root(path))\n    }\n\n    public static func fileSystem(identity: PackageIdentity, path: AbsolutePath) -> PackageReference {\n        PackageReference(identity: identity, kind: .fileSystem(path))\n    }\n\n    public static func localSourceControl(identity: PackageIdentity, path: AbsolutePath) -> PackageReference {\n        PackageReference(identity: identity, kind: .localSourceControl(path))\n    }\n\n    public static func remoteSourceControl(identity: PackageIdentity, url: SourceControlURL) -> PackageReference {\n        PackageReference(identity: identity, kind: .remoteSourceControl(url))\n    }\n\n    public static func registry(identity: PackageIdentity) -> PackageReference {\n        PackageReference(identity: identity, kind: .registry(identity))\n    }\n}\n\nextension PackageReference: Equatable {\n    // TODO: consider location as well?\n    public static func ==(lhs: PackageReference, rhs: PackageReference) -> Bool {\n        return lhs.identity == rhs.identity\n    }\n\n    // TODO: consider rolling into Equatable\n    public func equalsIncludingLocation(_ other: PackageReference) -> Bool {\n        if self.identity != other.identity {\n            return false\n        }\n        if self.canonicalLocation != other.canonicalLocation {\n            return false\n        }\n        switch (self.kind, other.kind) {\n        case (.remoteSourceControl(let lurl), .remoteSourceControl(let rurl)):\n            return lurl.canonicalURL == rurl.canonicalURL\n        default:\n            return true\n        }\n    }\n}\n\nextension SourceControlURL {\n    var canonicalURL: CanonicalPackageURL {\n        CanonicalPackageURL(self.absoluteString)\n    }\n}\n\nextension PackageReference: Hashable {\n    // TODO: consider location as well?\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(self.identity)\n    }\n}\n\nextension PackageReference {\n    public var diagnosticsMetadata: ObservabilityMetadata {\n        return .packageMetadata(identity: self.identity, kind: self.kind)\n    }\n}\n\nextension PackageReference: CustomStringConvertible {\n    public var description: String {\n        return \"\\(self.identity) \\(self.kind)\"\n    }\n}\n\nextension PackageReference.Kind: Encodable {\n    private enum CodingKeys: String, CodingKey {\n        case root, fileSystem, localSourceControl, remoteSourceControl, registry\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .root(let path):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .root)\n            try unkeyedContainer.encode(path)\n        case .fileSystem(let path):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .fileSystem)\n            try unkeyedContainer.encode(path)\n        case .localSourceControl(let path):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .localSourceControl)\n            try unkeyedContainer.encode(path)\n        case .remoteSourceControl(let url):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .remoteSourceControl)\n            try unkeyedContainer.encode(url)\n        case .registry:\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .registry)\n            try unkeyedContainer.encode(self.isRoot)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Platform.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCUtility.Version\n\n/// Represents a platform.\npublic struct Platform: Equatable, Hashable, Codable, Sendable {\n    /// The name of the platform.\n    public let name: String\n\n    /// The oldest supported deployment version by this platform.\n    ///\n    /// We currently hardcode this value but we should load it from the\n    /// SDK's plist file. This value is always present for Apple platforms.\n    public let oldestSupportedVersion: PlatformVersion\n\n    /// Create a platform.\n    private init(name: String, oldestSupportedVersion: PlatformVersion) {\n        self.name = name\n        self.oldestSupportedVersion = oldestSupportedVersion\n    }\n\n    public static func custom(name: String, oldestSupportedVersion: String) -> Platform {\n        return Platform(name: name, oldestSupportedVersion: PlatformVersion(oldestSupportedVersion))\n    }\n\n    public static func custom(name: String, oldestSupportedVersion: PlatformVersion) -> Platform {\n        return Platform(name: name, oldestSupportedVersion: oldestSupportedVersion)\n    }\n\n    public static let macOS: Platform = Platform(name: \"macos\", oldestSupportedVersion: \"10.13\")\n    public static let macCatalyst: Platform = Platform(name: \"maccatalyst\", oldestSupportedVersion: \"13.0\")\n    public static let iOS: Platform = Platform(name: \"ios\", oldestSupportedVersion: \"12.0\")\n    public static let tvOS: Platform = Platform(name: \"tvos\", oldestSupportedVersion: \"12.0\")\n    public static let watchOS: Platform = Platform(name: \"watchos\", oldestSupportedVersion: \"4.0\")\n    public static let visionOS: Platform = Platform(name: \"visionos\", oldestSupportedVersion: \"1.0\")\n    public static let driverKit: Platform = Platform(name: \"driverkit\", oldestSupportedVersion: \"19.0\")\n    public static let linux: Platform = Platform(name: \"linux\", oldestSupportedVersion: .unknown)\n    public static let android: Platform = Platform(name: \"android\", oldestSupportedVersion: .unknown)\n    public static let windows: Platform = Platform(name: \"windows\", oldestSupportedVersion: .unknown)\n    public static let wasi: Platform = Platform(name: \"wasi\", oldestSupportedVersion: .unknown)\n    public static let openbsd: Platform = Platform(name: \"openbsd\", oldestSupportedVersion: .unknown)\n    public static let freebsd: Platform = Platform(name: \"freebsd\", oldestSupportedVersion: .unknown)\n\n\n}\n\n/// Represents a platform supported by a target.\npublic struct SupportedPlatform: Hashable, Codable, Sendable {\n    /// The platform.\n    public let platform: Platform\n\n    /// The minimum required version for this platform.\n    public let version: PlatformVersion\n\n    /// The options declared by the platform.\n    public let options: [String]\n\n    public init(platform: Platform, version: PlatformVersion, options: [String] = []) {\n        self.platform = platform\n        self.version = version\n        self.options = options\n    }\n}\n\n/// Represents a platform version.\npublic struct PlatformVersion: Equatable, Hashable, Codable, Sendable {\n    // FIXME: this should be optional\n    /// The unknown platform version.\n    public static let unknown: PlatformVersion = .init(\"0.0.0\")\n\n    /// The underlying version storage.\n    private let version: Version\n\n    /// The string representation of the version.\n    public var versionString: String {\n        var str = \"\\(version.major).\\(version.minor)\"\n        if version.patch != 0 {\n            str += \".\\(version.patch)\"\n        }\n        return str\n    }\n\n    public var major: Int { version.major }\n    public var minor: Int { version.minor }\n    public var patch: Int { version.patch }\n\n    /// Create a platform version given a string.\n    ///\n    /// The platform version is expected to be in format: X.X.X\n    public init(_ version: String) {\n        let components = version.split(separator: \".\").compactMap({ Int($0) })\n        assert(!components.isEmpty && components.count <= 3, version)\n        switch components.count {\n        case 1:\n            self.version = Version(components[0], 0, 0)\n        case 2:\n            self.version = Version(components[0], components[1], 0)\n        case 3:\n            self.version = Version(components[0], components[1], components[2])\n        default:\n            fatalError(\"Unexpected number of components \\(components)\")\n        }\n    }\n}\n\nextension PlatformVersion: Comparable {\n    public static func < (lhs: PlatformVersion, rhs: PlatformVersion) -> Bool {\n        return lhs.version < rhs.version\n    }\n}\n\nextension PlatformVersion: ExpressibleByStringLiteral {\n    public init(stringLiteral value: String) {\n        self.init(value)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/PlatformRegistry.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A registry for available platforms.\npublic struct PlatformRegistry {\n    /// The current registry is hardcoded and static so we can just use\n    /// a singleton for now.\n    public static let `default`: PlatformRegistry = .init()\n\n    /// The list of known platforms.\n    public let knownPlatforms: [Platform]\n\n    /// The mapping of platforms to their name.\n    public let platformByName: [String: Platform]\n\n    /// Create a registry with the given list of platforms.\n    init(platforms: [Platform] = PlatformRegistry._knownPlatforms) {\n        self.knownPlatforms = platforms\n        self.platformByName = Dictionary(uniqueKeysWithValues: knownPlatforms.map({ ($0.name, $0) }))\n    }\n\n    /// The static list of known platforms.\n    private static var _knownPlatforms: [Platform] {\n        [\n            .android,\n            .driverKit,\n            .iOS,\n            .linux,\n            .macOS,\n            .macCatalyst,\n            .openbsd,\n            .freebsd,\n            .tvOS,\n            .visionOS,\n            .wasi,\n            .watchOS,\n            .windows,\n        ]\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/PrebuiltLibrary.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2026 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Basics\n\n/// A structure representing a prebuilt library to be used instead of a source dependency\npublic struct PrebuiltLibrary {\n    /// The package identity.\n    public let identity: PackageIdentity\n\n    /// The name of the binary target the artifact corresponds to.\n    public let libraryName: String\n\n    /// The path to the extracted prebuilt artifacts\n    public let path: AbsolutePath\n\n    /// The path to the checked out source\n    public let checkoutPath: AbsolutePath?\n\n    /// The products in the library\n    public let products: [String]\n\n    /// The include path relative to the checkouts dir\n    public let includePath: [RelativePath]?\n\n    /// The C modules that need their includes directory added to the include path\n    public let cModules: [String]\n\n    public init(\n        identity: PackageIdentity,\n        libraryName: String,\n        path: AbsolutePath,\n        checkoutPath: AbsolutePath?,\n        products: [String],\n        includePath: [RelativePath]? = nil,\n        cModules: [String] = []\n    ) {\n        self.identity = identity\n        self.libraryName = libraryName\n        self.path = path\n        self.checkoutPath = checkoutPath\n        self.products = products\n        self.includePath = includePath\n        self.cModules = cModules\n    }\n}\n\npublic enum PrebuiltsPlatform: String, Codable {\n    case macos_universal\n    case windows_aarch64\n    case windows_x86_64\n    case ubuntu_noble_aarch64\n    case ubuntu_noble_x86_64\n    case ubuntu_jammy_aarch64\n    case ubuntu_jammy_x86_64\n    case ubuntu_focal_aarch64\n    case ubuntu_focal_x86_64\n    case fedora_39_aarch64\n    case fedora_39_x86_64\n    case amazonlinux2_aarch64\n    case amazonlinux2_x86_64\n    case rhel_ubi9_aarch64\n    case rhel_ubi9_x86_64\n    case debian_12_aarch64\n    case debian_12_x86_64\n\n    public enum Arch: String, CaseIterable {\n        case x86_64\n        case aarch64\n    }\n\n    public enum OS {\n        case macos\n        case windows\n        case linux\n    }\n\n    public var arch: Arch? {\n        switch self {\n        case .windows_aarch64,\n            .ubuntu_noble_aarch64, .ubuntu_jammy_aarch64, .ubuntu_focal_aarch64,\n            .fedora_39_aarch64,\n            .amazonlinux2_aarch64,\n            .rhel_ubi9_aarch64,\n            .debian_12_aarch64:\n            return .aarch64\n        case .windows_x86_64,\n            .ubuntu_noble_x86_64, .ubuntu_jammy_x86_64, .ubuntu_focal_x86_64,\n            .fedora_39_x86_64,\n            .amazonlinux2_x86_64,\n            .rhel_ubi9_x86_64,\n            .debian_12_x86_64:\n            return .x86_64\n        case .macos_universal:\n            return nil\n        }\n    }\n\n    public var os: OS {\n        switch self {\n        case .macos_universal:\n            return .macos\n        case .windows_aarch64, .windows_x86_64:\n            return .windows\n        case .ubuntu_noble_aarch64, .ubuntu_noble_x86_64,\n            .ubuntu_jammy_aarch64, .ubuntu_jammy_x86_64,\n            .ubuntu_focal_aarch64, .ubuntu_focal_x86_64,\n            .fedora_39_aarch64, .fedora_39_x86_64,\n            .amazonlinux2_aarch64, .amazonlinux2_x86_64,\n            .rhel_ubi9_aarch64, .rhel_ubi9_x86_64,\n            .debian_12_aarch64, .debian_12_x86_64:\n            return .linux\n        }\n    }\n\n    public enum PrebuiltNameError: Error {\n        case missingSwiftVersion\n        case missingSDKName\n    }\n\n    public func prebuiltName(hostToolchain: UserToolchain) throws -> String {\n        guard let swiftVersion = hostToolchain.swiftCompilerVersion else {\n            throw PrebuiltNameError.missingSwiftVersion\n        }\n\n        switch os {\n        case .macos:\n            if swiftVersion.hasPrefix(\"swiftlang-\") {\n                // Denotes an Xcode toochain, need the SDK name as well\n                guard let sdkName = try hostToolchain.swiftSDK.loadSettings()?.CanonicalName else {\n                    throw PrebuiltNameError.missingSDKName\n                }\n                // The SDK name identifies the platform\n                return \"\\(swiftVersion)-\\(sdkName)\"\n            } else {\n                fallthrough\n            }\n        default:\n            return \"\\(swiftVersion)-\\(self)\"\n        }\n    }\n\n    /// Determine host platform based on compilation target\n    public static var hostPlatform: Self? {\n        let arch: Arch?\n#if arch(arm64)\n        arch = .aarch64\n#elseif arch(x86_64)\n        arch = .x86_64\n#else\n        arch = nil\n#endif\n        guard let arch else {\n            return nil\n        }\n\n#if os(macOS)\n        return .macos_universal\n#elseif os(Windows)\n        switch arch {\n        case .aarch64:\n            return .windows_aarch64\n        case .x86_64:\n            return .windows_x86_64\n        }\n#elseif os(Linux)\n        // Load up the os-release file into a dictionary\n        guard let osData = try? String(contentsOfFile: \"/etc/os-release\", encoding: .utf8)\n        else {\n            return nil\n        }\n        let osLines = osData.split(separator: \"\\n\")\n        let osDict = osLines.reduce(into: [Substring: String]()) {\n            (dict, line) in\n            let parts = line.split(separator: \"=\", maxSplits: 2)\n            dict[parts[0]] = parts[1...].joined(separator: \"=\").trimmingCharacters(in: [\"\\\"\"])\n        }\n\n        switch osDict[\"ID\"] {\n        case \"ubuntu\":\n            switch osDict[\"VERSION_CODENAME\"] {\n            case \"noble\":\n                switch arch {\n                case .aarch64:\n                    return .ubuntu_noble_aarch64\n                case .x86_64:\n                    return .ubuntu_noble_x86_64\n                }\n            case \"jammy\":\n                switch arch {\n                case .aarch64:\n                    return .ubuntu_jammy_aarch64\n                case .x86_64:\n                    return .ubuntu_jammy_x86_64\n                }\n            case \"focal\":\n                switch arch {\n                case .aarch64:\n                    return .ubuntu_focal_aarch64\n                case .x86_64:\n                    return .ubuntu_focal_x86_64\n                }\n            default:\n                return nil\n            }\n        case \"fedora\":\n            switch osDict[\"VERSION_ID\"] {\n            case \"39\", \"41\":\n                switch arch {\n                case .aarch64:\n                    return .fedora_39_aarch64\n                case .x86_64:\n                    return .fedora_39_x86_64\n                }\n            default:\n                return nil\n            }\n        case \"amzn\":\n            switch osDict[\"VERSION_ID\"] {\n            case \"2\":\n                switch arch {\n                case .aarch64:\n                    return .amazonlinux2_aarch64\n                case .x86_64:\n                    return .amazonlinux2_x86_64\n                }\n            default:\n                return nil\n            }\n        case \"rhel\":\n            guard let version = osDict[\"VERSION_ID\"] else {\n                return nil\n            }\n            switch version.split(separator: \".\")[0] {\n            case \"9\":\n                switch arch {\n                case .aarch64:\n                    return .rhel_ubi9_aarch64\n                case .x86_64:\n                    return .rhel_ubi9_x86_64\n                }\n            default:\n                return nil\n            }\n        case \"debian\":\n            switch osDict[\"VERSION_ID\"] {\n            case \"12\":\n                switch arch {\n                case .aarch64:\n                    return .debian_12_aarch64\n                case .x86_64:\n                    return .debian_12_x86_64\n                }\n            default:\n                return nil\n            }\n        default:\n            return nil\n        }\n#else\n        return nil\n#endif\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Product.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\npublic class Product: Identifiable {\n    /// The name of the product.\n    public let name: String\n\n    public var id: String { name }\n\n    /// Fully qualified name for this product: package ID + name of this product\n    public let identity: String\n\n    /// The type of product to create.\n    public let type: ProductType\n\n    /// The list of targets to combine to form the product.\n    ///\n    /// This is never empty, and is only the targets which are required to be in\n    /// the product, but not necessarily their transitive dependencies.\n    public var modules: [Module]\n\n    /// The path to test entry point file.\n    public let testEntryPointPath: AbsolutePath?\n\n    /// Was this product implicitly created\n    public let isImplicit: Bool\n\n    /// The suffix for REPL product name.\n    public static let replProductSuffix: String = \"__REPL\"\n\n    public init(\n        package: PackageIdentity,\n        name: String,\n        type: ProductType,\n        modules: [Module],\n        testEntryPointPath: AbsolutePath? = nil,\n        isImplicit: Bool = false\n    ) throws {\n        guard !modules.isEmpty else {\n            throw InternalError(\"Targets cannot be empty\")\n        }\n        if type == .executable {\n            guard modules.executables.count == 1 else {\n                throw InternalError(\"Executable products should have exactly one executable target.\")\n            }\n        }\n        if testEntryPointPath != nil {\n            guard type == .test else {\n                throw InternalError(\"Test entry point path should only be set on test products\")\n            }\n        }\n        self.name = name\n        self.type = type\n        self.identity = package.description.lowercased() + \"_\" + name\n        self.modules = modules\n        self.testEntryPointPath = testEntryPointPath\n        self.isImplicit = isImplicit\n    }\n}\n\nextension Product: Hashable {\n    public func hash(into hasher: inout Hasher) {\n        hasher.combine(ObjectIdentifier(self))\n    }\n\n    public static func == (lhs: Product, rhs: Product) -> Bool {\n        ObjectIdentifier(lhs) == ObjectIdentifier(rhs)\n    }\n}\n\nextension Product: Comparable {\n    public static func < (lhs: Product, rhs: Product) -> Bool {\n        lhs.name < rhs.name\n    }\n}\n\n/// The type of product.\npublic enum ProductType: Equatable, Hashable, Sendable {\n\n    /// The type of library.\n    public enum LibraryType: String, Codable, Sendable {\n\n        /// Static library.\n        case `static`\n\n        /// Dynamic library.\n        case `dynamic`\n\n        /// The type of library is unspecified and should be decided by package manager.\n        case automatic\n    }\n\n    /// A library product.\n    case library(LibraryType)\n\n    /// An executable product.\n    case executable\n\n    /// An executable code snippet.\n    case snippet\n\n    /// An plugin product.\n    case plugin\n\n    /// A test product.\n    case test\n\n    /// A macro product.\n    case `macro`\n\n    public var isLibrary: Bool {\n        guard case .library = self else { return false }\n        return true\n    }\n}\n\n\n/// The products requested of a package.\n///\n/// Any product which matches the filter will be used for dependency resolution, whereas unrequested products will be ignored.\n///\n/// Requested products need not actually exist in the package. Under certain circumstances, the resolver may request names whose package of origin are unknown. The intended package will recognize and fulfill the request; packages that do not know what it is will simply ignore it.\npublic enum ProductFilter: Equatable, Hashable, Sendable {\n\n    /// All products, targets, and tests are requested.\n    ///\n    /// This is used for root packages.\n    case everything\n\n    /// A set of specific products requested by one or more client packages.\n    case specific(Set<String>)\n\n    /// No products, targets, or tests are requested.\n    public static var nothing: ProductFilter { .specific([]) }\n\n    public func union(_ other: ProductFilter) -> ProductFilter {\n        switch self {\n        case .everything:\n            return .everything\n        case .specific(let set):\n            switch other {\n            case .everything:\n                return .everything\n            case .specific(let otherSet):\n                return .specific(set.union(otherSet))\n            }\n        }\n    }\n\n    public mutating func formUnion(_ other: ProductFilter) {\n        self = self.union(other)\n    }\n\n    public func contains(_ product: String) -> Bool {\n        switch self {\n        case .everything:\n            return true\n        case .specific(let set):\n            return set.contains(product)\n        }\n    }\n\n    public func merge(_ other: ProductFilter) -> ProductFilter {\n        switch (self, other) {\n        case (.everything, _):\n            return .everything\n        case (_, .everything):\n            return .everything\n        case (.specific(let mine), .specific(let other)):\n            return .specific(mine.union(other))\n        }\n    }\n}\n\n\n// MARK: - CustomStringConvertible\n\nextension Product: CustomStringConvertible {\n    public var description: String {\n        return \"<Product: \\(name)>\"\n    }\n}\n\nextension ProductType: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .executable:\n            return \"executable\"\n        case .snippet:\n            return \"snippet\"\n        case .test:\n            return \"test\"\n        case .library(let type):\n            switch type {\n            case .automatic:\n                return \"library\"\n            case .dynamic:\n                return \"dynamic library\"\n            case .static:\n                return \"static library\"\n            }\n        case .plugin:\n            return \"plugin\"\n        case .macro:\n            return \"macro\"\n        }\n    }\n}\n\nextension ProductFilter: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .everything:\n            return \"[everything]\"\n        case .specific(let set):\n            return \"[\\(set.sorted().joined(separator: \", \"))]\"\n        }\n    }\n}\n\n// MARK: - Codable\n\nextension ProductType: Codable {\n    private enum CodingKeys: String, CodingKey {\n        case library, executable, snippet, plugin, test, `macro`\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case let .library(a1):\n            var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .library)\n            try unkeyedContainer.encode(a1)\n        case .executable:\n            try container.encodeNil(forKey: .executable)\n        case .snippet:\n            try container.encodeNil(forKey: .snippet)\n        case .plugin:\n            try container.encodeNil(forKey: .plugin)\n        case .test:\n            try container.encodeNil(forKey: .test)\n        case .macro:\n            try container.encodeNil(forKey: .macro)\n        }\n    }\n\n    public init(from decoder: Decoder) throws {\n        let values = try decoder.container(keyedBy: CodingKeys.self)\n        guard let key = values.allKeys.first(where: values.contains) else {\n            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: \"Did not find a matching key\"))\n        }\n        switch key {\n        case .library:\n            var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)\n            let a1 = try unkeyedValues.decode(ProductType.LibraryType.self)\n            self = .library(a1)\n        case .test:\n            self = .test\n        case .executable:\n            self = .executable\n        case .snippet:\n            self = .snippet\n        case .plugin:\n            self = .plugin\n        case .macro:\n            self = .macro\n        }\n    }\n}\n\nextension ProductFilter: Codable {\n    public func encode(to encoder: Encoder) throws {\n        let optionalSet: Set<String>?\n        switch self {\n        case .everything:\n            optionalSet = nil\n        case .specific(let set):\n            optionalSet = set\n        }\n        var container = encoder.singleValueContainer()\n        try container.encode(optionalSet?.sorted())\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.singleValueContainer()\n        if container.decodeNil() {\n            self = .everything\n        } else {\n            self = .specific(Set(try container.decode([String].self)))\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/README.md",
    "content": "# PackageModel Library\n\nThis library defines the model objects for describing Packages.\n\nThe intent of this library is that these should be pure model objects and\ncontain a complete specification of a single local package. The convention\nsystem is encoded in the model via the\n[`PackageLoading`](../PackageLoading/README.md) library, and then the individual\npackages are combined into a cohesive\n[`PackageGraph`](../PackageGraph/README.md) for the high-level operations.\n\nNOTE: This library contains types which shadows definitions from the\n[`PackageDescription`](../PackageDescription/README.md) library, but they are\nfundamentally different -- those model objects describe the model of the package\n*manifest* itself, not the overall package.\n"
  },
  {
    "path": "Sources/PackageModel/Registry.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport struct Foundation.URL\n\npublic struct Registry: Hashable, CustomStringConvertible, Sendable {\n    public var url: URL\n    public var supportsAvailability: Bool\n\n    public init(url: URL, supportsAvailability: Bool) {\n        self.url = url\n        self.supportsAvailability = supportsAvailability\n    }\n\n    public var description: String {\n        self.url.absoluteString\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/RegistryReleaseMetadata.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.SourceControlURL\nimport struct Foundation.URL\nimport struct TSCUtility.Version\n\n\npublic struct RegistryReleaseMetadata: Hashable {\n    public let source: Source\n    public let metadata: Metadata\n    public let signature: RegistrySignature?\n\n    public init(\n        source: RegistryReleaseMetadata.Source,\n        metadata: RegistryReleaseMetadata.Metadata,\n        signature: RegistrySignature?\n    ) {\n        self.source = source\n        self.metadata = metadata\n        self.signature = signature\n    }\n\n    /// Metadata of the given release, provided by the registry.\n    public struct Metadata: Hashable {\n        public let author: Author?\n        public let description: String?\n        public let licenseURL: URL?\n        public let readmeURL: URL?\n        public let scmRepositoryURLs: [SourceControlURL]?\n\n        public init(\n            author: RegistryReleaseMetadata.Metadata.Author? = nil,\n            description: String? = nil,\n            licenseURL: URL? = nil,\n            readmeURL: URL? = nil,\n            scmRepositoryURLs: [SourceControlURL]?\n        ) {\n            self.author = author\n            self.description = description\n            self.licenseURL = licenseURL\n            self.readmeURL = readmeURL\n            self.scmRepositoryURLs = scmRepositoryURLs\n        }\n\n        public struct Author: Hashable {\n            public let name: String\n            public let emailAddress: String?\n            public let description: String?\n            public let url: URL?\n            public let organization: Organization?\n\n            public init(\n                name: String,\n                emailAddress: String? = nil,\n                description: String? = nil,\n                url: URL? = nil,\n                organization: RegistryReleaseMetadata.Metadata.Organization?\n            ) {\n                self.name = name\n                self.emailAddress = emailAddress\n                self.description = description\n                self.url = url\n                self.organization = organization\n            }\n        }\n\n        public struct Organization: Hashable {\n            public let name: String\n            public let emailAddress: String?\n            public let description: String?\n            public let url: URL?\n\n            public init(name: String, emailAddress: String? = nil, description: String? = nil, url: URL? = nil) {\n                self.name = name\n                self.emailAddress = emailAddress\n                self.description = description\n                self.url = url\n            }\n        }\n    }\n\n    /// Information from the signing certificate.\n    public struct RegistrySignature: Hashable, Codable {\n        public let signedBy: SigningEntity?\n        public let format: String\n        public let value: [UInt8]\n\n        public init(\n            signedBy: SigningEntity?,\n            format: String,\n            value: [UInt8]\n        ) {\n            self.signedBy = signedBy\n            self.format = format\n            self.value = value\n        }\n    }\n\n    public enum SigningEntity: Codable, Hashable, Sendable {\n        case recognized(type: String, commonName: String?, organization: String?, identity: String?)\n        case unrecognized(commonName: String?, organization: String?)\n    }\n    \n    /// Information about the source of the release.\n    public enum Source: Hashable {\n        case registry(URL)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Resource.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// An individual resource file and its corresponding rule.\npublic struct Resource: Codable, Equatable {\n    public static let localizationDirectoryExtension = \"lproj\"\n\n    /// The rule associated with this resource.\n    public let rule: Rule\n\n    /// The path of the resource file.\n    public let path: AbsolutePath\n\n    /// The relative location of the resource in the resource bundle.\n    public var destination: RelativePath {\n        get throws {\n            switch self.rule {\n            case .process(.some(let localization)):\n                return try RelativePath(validating: \"\\(localization).\\(Self.localizationDirectoryExtension)/\\(path.basename)\")\n            default:\n                return try RelativePath(validating: path.basename)\n            }\n        }\n    }\n\n    public init(rule: Rule, path: AbsolutePath) {\n        var rule = rule\n        if case .process(.some(let localization)) = rule, localization != \"Base\" {\n            rule  = .process(localization: localization.lowercased())\n        }\n        self.rule = rule\n        self.path = path\n    }\n\n    public enum Rule: Codable, Equatable {\n        case process(localization: String?)\n        case copy\n        case embedInCode\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Sanitizers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Available runtime sanitizers.\npublic enum Sanitizer: String, Encodable, CaseIterable {\n    case address\n    case thread\n    case undefined\n    case scudo\n    case fuzzer\n\n    /// Return an established short name for a sanitizer, e.g. \"asan\".\n    public var shortName: String {\n        switch self {\n            case .address: return \"asan\"\n            case .thread: return \"tsan\"\n            case .undefined: return \"ubsan\"\n            case .scudo: return \"scudo\"\n            case .fuzzer: return \"fuzzer\"\n        }\n    }\n}\n\n/// A set of enabled runtime sanitizers.\npublic struct EnabledSanitizers: Encodable {\n    /// A set of enabled sanitizers.\n    public let sanitizers: Set<Sanitizer>\n\n    public init(_ sanitizers: Set<Sanitizer> = []) {\n        // FIXME: We need to throw from here if given sanitizers can't be\n        // enabled.  For e.g., it is illegal to enable thread and address\n        // sanitizers together.\n        self.sanitizers = sanitizers\n    }\n\n    /// Sanitization flags for the C family compiler (C/C++).\n    public func compileCFlags() -> [String] {\n        return sanitizers.map({ \"-fsanitize=\\($0.rawValue)\" })\n    }\n\n    /// Sanitization flags for the Swift compiler.\n    public func compileSwiftFlags() -> [String] {\n        return sanitizers.map({ \"-sanitize=\\($0.rawValue)\" })\n    }\n\n    /// Sanitization flags for the Swift linker and compiler are the same so far.\n    public func linkSwiftFlags() -> [String] {\n        return compileSwiftFlags()\n    }\n\n    public var isEmpty: Bool {\n        return sanitizers.isEmpty\n    }\n\n    enum CodingKeys: String, CodingKey {\n        case sanitizers\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        try container.encode(sanitizers.sorted{ $0.rawValue < $1.rawValue }, forKey: .sanitizers)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Snippets/Model/Snippet.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\npublic struct Snippet {\n    public var path: AbsolutePath\n    public var explanation: String\n    public var presentationCode: String\n    public var groupName: String? = nil\n\n    public var name: String {\n        path.basenameWithoutExt\n    }\n\n    init(parsing source: String, path: AbsolutePath) {\n        let extractor = PlainTextSnippetExtractor(source: source)\n        self.path = path\n        self.explanation = extractor.explanation\n        self.presentationCode = extractor.presentationCode\n    }\n\n    public init(parsing file: AbsolutePath) throws {\n        let source = try String(contentsOf: file.asURL)\n        self.init(parsing: source, path: file)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Snippets/Model/SnippetGroup.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\npublic struct SnippetGroup {\n    public var name: String\n    public var baseDirectory: AbsolutePath\n    public var snippets: [Snippet]\n    public var explanation: String\n\n    public init(name: String, baseDirectory: AbsolutePath, snippets: [Snippet], explanation: String) {\n        self.name = name\n        self.baseDirectory = baseDirectory\n        self.snippets = snippets\n        self.explanation = explanation\n        for index in self.snippets.indices {\n            self.snippets[index].groupName = baseDirectory.basename\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Snippets/Parsing/PlainTextSnippetExtractor.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nfileprivate enum SnippetVisibility {\n    case shown\n    case hidden\n}\n\nfileprivate extension StringProtocol {\n    /// If the string is a line comment, attempt to parse\n    /// a ``SnippetVisibility`` with `mark: show` or `mark: hide`.\n    var parsedVisibilityMark: SnippetVisibility? {\n        guard var comment = parsedLineCommentText else {\n            return nil\n        }\n\n        comment = comment.drop { $0.isWhitespace }\n\n        if comment.lowercased().starts(with: \"mark: show\") {\n            return SnippetVisibility.shown\n        } else if comment.lowercased().starts(with: \"mark: hide\") {\n            return SnippetVisibility.hidden\n        } else {\n            return nil\n        }\n    }\n\n    /// If the string is a line comment starting with `\"//\"`, return the\n    /// contents with the comment marker stripped.\n    var parsedLineCommentText: Self.SubSequence? {\n        var trimmed = self.drop { $0.isWhitespace }\n        guard trimmed.starts(with: \"//\") else {\n            return nil\n        }\n        trimmed.removeFirst(2)\n        return trimmed\n    }\n\n    var isEmptyOrWhiteSpace: Bool {\n        return self.isEmpty || self.allSatisfy { $0.isWhitespace }\n    }\n}\n\nfileprivate extension String {\n    mutating func removeLeadingAndTrailingNewlines() {\n        while self.starts(with: \"\\n\") {\n            self.removeFirst(1)\n        }\n        while self.suffix(1) == \"\\n\" {\n            self.removeLast(1)\n        }\n    }\n\n    /// Returns a re-indented string with the most indentation removed\n    /// without changing the relative indentation between lines. This is\n    /// useful for re-indenting some inner part of a block of nested code.\n    mutating func trimExtraIndentation() {\n        var lines = self.split(separator: \"\\n\", maxSplits: Int.max,\n                               omittingEmptySubsequences: false)\n        lines = Array(lines\n                        .drop(while: { $0.isEmptyOrWhiteSpace })\n                        .reversed()\n                        .drop(while: { $0.isEmptyOrWhiteSpace })\n                        .reversed())\n\n        let minimumIndentation = lines.map {\n            guard !$0.isEmpty else {\n                return Int.max\n            }\n            return $0.prefix { $0 == \" \" }.count\n        }.min() ?? 0\n\n        guard minimumIndentation > 0 else {\n            return\n        }\n\n        self = lines.map { $0.dropFirst(minimumIndentation) }\n            .joined(separator: \"\\n\")\n    }\n}\n\n/// Extracts a ``Snippet`` structure from Swift source code.\n///\n/// - todo: In order to support different styles of comments, it might be\n///   better to adopt SwiftSyntax if possible in the future.\nstruct PlainTextSnippetExtractor {\n    var source: String\n    var explanation = \"\"\n    var presentationCode = \"\"\n    private var currentVisibility = SnippetVisibility.shown\n\n    init(source: String) {\n        self.source = source\n        let lines = source.split(separator: \"\\n\", omittingEmptySubsequences: false)\n\n        var lastExplanationLine = \"...\"\n        var lastPresentationCodeLine = \"...\"\n\n        for line in lines {\n            if let visibility = line.parsedVisibilityMark {\n                self.currentVisibility = visibility\n                continue\n            }\n\n            guard case .shown = currentVisibility else {\n                continue\n            }\n\n            if var comment = line.parsedLineCommentText,\n               comment.starts(with: \"!\") {\n                comment.removeFirst(1)\n                comment = comment.drop { $0.isWhitespace }\n                if lastExplanationLine.isEmptyOrWhiteSpace && comment.isEmptyOrWhiteSpace {\n                    continue\n                }\n                print(comment, to: &explanation)\n                lastExplanationLine = String(comment)\n            } else {\n                if lastPresentationCodeLine.isEmptyOrWhiteSpace && line.isEmptyOrWhiteSpace {\n                    continue\n                }\n                print(line, to: &presentationCode)\n                lastPresentationCodeLine = String(line)\n            }\n        }\n        self.explanation\n            .removeLeadingAndTrailingNewlines()\n\n        self.presentationCode\n            .removeLeadingAndTrailingNewlines()\n        \n        self.presentationCode\n            .trimExtraIndentation()\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Sources.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// A grouping of related source files.\npublic struct Sources: Codable {\n    /// The root of the sources.\n    public let root: AbsolutePath\n\n    /// The subpaths within the root.\n    public var relativePaths: [RelativePath]\n\n    /// The list of absolute paths of all files.\n    public var paths: [AbsolutePath] {\n        return relativePaths.map({ root.appending($0) })\n    }\n\n    public init(paths: [AbsolutePath], root: AbsolutePath) {\n        let relativePaths = paths.map({ $0.relative(to: root) })\n        self.relativePaths = relativePaths.sorted(by: { $0.pathString < $1.pathString })\n        self.root = root\n    }\n\n    /// Returns true if the sources contain C++ files.\n    public var containsCXXFiles: Bool {\n        return paths.contains(where: {\n            guard let ext = $0.extension else {\n                return false\n            }\n            return SupportedLanguageExtension.cppExtensions.contains(ext)\n        })\n    }\n\n    /// Returns true if the sources contain C++ files.\n    public var containsObjcFiles: Bool {\n        return paths.contains(where: {\n            guard let ext = $0.extension else {\n                return false\n            }\n            return ext == SupportedLanguageExtension.m.rawValue || ext == SupportedLanguageExtension.mm.rawValue\n        })\n    }\n\n    public var containsNonSwiftFiles: Bool {\n        return paths.contains(where: {\n            guard let ext = $0.extension else {\n                return false\n            }\n            return !SupportedLanguageExtension.swiftExtensions.contains(ext)\n        })\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/SupportedLanguageExtension.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// An enum representing supported source file extensions.\npublic enum SupportedLanguageExtension: String {\n    /// Swift\n    case swift\n    /// C\n    case c\n    /// Objective C\n    case m\n    /// Objective-C++\n    case mm\n    /// C++\n    case cc\n    case cpp\n    case cxx\n    /// Assembly\n    case s\n    case S\n\n    /// Returns a set of valid swift extensions.\n    public static var swiftExtensions: Set<String> = {\n        SupportedLanguageExtension.stringSet(swift)\n    }()\n\n    /// Returns a set of valid c extensions.\n    public static var cExtensions: Set<String> = {\n        SupportedLanguageExtension.stringSet(c, m)\n    }()\n\n    /// Returns a set of valid cpp extensions.\n    public static var cppExtensions: Set<String> = {\n        SupportedLanguageExtension.stringSet(mm, cc, cpp, cxx)\n    }()\n\n    /// Returns a set of valid assembly file extensions.\n    public static var assemblyExtensions: Set<String> = {\n        SupportedLanguageExtension.stringSet(.s, .S)\n    }()\n\n    /// Returns a set of valid extensions in clang targets.\n    public static func clangTargetExtensions(toolsVersion: ToolsVersion) -> Set<String> {\n        var validExts = cExtensions.union(cppExtensions)\n        if toolsVersion >= .v5 {\n            validExts.formUnion(assemblyExtensions)\n        }\n        return validExts\n    }\n\n    /// Returns a set of all file extensions we support.\n    public static func validExtensions(toolsVersion: ToolsVersion) -> Set<String> {\n        return swiftExtensions.union(clangTargetExtensions(toolsVersion: toolsVersion))\n    }\n\n    /// Converts array of LanguageExtension into a string set representation.\n    ///\n    /// - Parameters:\n    ///     - extensions: Array of LanguageExtension to be converted to string set.\n    ///\n    /// - Returns: Set of strings.\n    private static func stringSet(_ extensions: SupportedLanguageExtension...) -> Set<String> {\n        return Set(extensions.map({ $0.rawValue }))\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/SwiftLanguageVersion.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport struct TSCBasic.RegEx\n\nimport struct TSCUtility.Version\n\n/// Represents a Swift language version.\npublic struct SwiftLanguageVersion: Hashable, Sendable {\n\n    /// Swift language version 3.\n    public static let v3 = SwiftLanguageVersion(uncheckedString: \"3\")\n\n    /// Swift language version 4.\n    public static let v4 = SwiftLanguageVersion(uncheckedString: \"4\")\n\n    /// Swift language version 4.2.\n    public static let v4_2 = SwiftLanguageVersion(uncheckedString: \"4.2\")\n\n    /// Swift language version 5.\n    public static let v5 = SwiftLanguageVersion(uncheckedString: \"5\")\n\n    /// Swift language version 6.\n    public static let v6 = SwiftLanguageVersion(uncheckedString: \"6\")\n\n    /// The list of known Swift language versions.\n    public static let knownSwiftLanguageVersions = [\n        v3, v4, v4_2, v5, v6\n    ]\n\n    /// The list of supported Swift language versions for this toolchain.\n    public static let supportedSwiftLanguageVersions = [\n        v4, v4_2, v5, v6\n    ]\n\n    /// The raw value of the language version.\n    //\n    // This should be passed as a value to Swift compiler's -swift-version flag.\n    public let rawValue: String\n\n    /// The underlying backing store.\n    private let _version: Version\n\n    /// The major version number.\n    public var major: Int {\n        return _version.major\n    }\n\n    /// The minor version number.\n    public var minor: Int {\n        return _version.minor\n    }\n\n    /// The patch version number.\n    public var patch: Int {\n        return _version.patch\n    }\n\n    /// Regex for parsing the Swift language version.\n    private static let regex = try! RegEx(pattern: #\"^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$\"#)\n\n    /// Create an instance of Swift language version from the given string.\n    ///\n    // The Swift language version is not officially fixed but we require it to\n    // be a valid SemVer-like string.\n    public init?(string: String) {\n        let parsedVersion = SwiftLanguageVersion.regex.matchGroups(in: string)\n        guard parsedVersion.count == 1, parsedVersion[0].count == 3 else {\n            return nil\n        }\n        let major = Int(parsedVersion[0][0])!\n        let minor = parsedVersion[0][1].isEmpty ? 0 : Int(parsedVersion[0][1])!\n        let patch = parsedVersion[0][2].isEmpty ? 0 : Int(parsedVersion[0][2])!\n\n        self.rawValue = string\n        self._version = Version(major, minor, patch)\n    }\n\n    /// Create an instance assuming the string is valid.\n    private init(uncheckedString string: String) {\n        self.init(string: string)!\n    }\n}\n\nextension SwiftLanguageVersion: CustomStringConvertible {\n    public var description: String {\n        return rawValue\n    }\n}\n\nextension SwiftLanguageVersion: Equatable {\n    public static func == (lhs: SwiftLanguageVersion, rhs: SwiftLanguageVersion) -> Bool {\n        return lhs._version == rhs._version\n    }\n}\n\nextension SwiftLanguageVersion: Comparable {\n    public static func < (lhs: SwiftLanguageVersion, rhs: SwiftLanguageVersion) -> Bool {\n        return lhs._version < rhs._version\n    }\n}\n\n// MARK: - Compare with ToolsVersion\n\nextension SwiftLanguageVersion {\n    public static func == (lhs: SwiftLanguageVersion, rhs: ToolsVersion) -> Bool {\n        return (lhs.major, lhs.minor, lhs.patch) == (rhs.major, rhs.minor, rhs.patch)\n    }\n\n    public static func < (lhs: SwiftLanguageVersion, rhs: ToolsVersion) -> Bool {\n        return (lhs.major, lhs.minor, lhs.patch) < (rhs.major, rhs.minor, rhs.patch)\n    }\n\n    public static func <= (lhs: SwiftLanguageVersion, rhs: ToolsVersion) -> Bool {\n        return (lhs < rhs) || (lhs == rhs)\n    }\n}\n\nextension SwiftLanguageVersion: Codable {\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.singleValueContainer()\n        try container.encode(rawValue)\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.singleValueContainer()\n        let rawValue = try container.decode(String.self)\n        self.init(uncheckedString: rawValue)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/SwiftSDKs/SwiftSDK.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport TSCBasic\n\nimport class Basics.AsyncProcess\n\nimport struct TSCUtility.Version\n\n/// Errors related to Swift SDKs.\npublic enum SwiftSDKError: Swift.Error {\n    /// A bundle archive should contain at least one directory with the `.artifactbundle` extension.\n    case invalidBundleArchive(Basics.AbsolutePath)\n\n    /// A passed argument is neither a valid file system path nor a URL.\n    case invalidPathOrURL(String)\n\n    ///  Bundles installed from remote URLs require a checksum to be provided.\n    case checksumNotProvided(URL)\n\n    /// Computed archive checksum does not match the provided checksum.\n    case checksumInvalid(computed: String, provided: String)\n\n    /// Couldn't find the Xcode installation.\n    case invalidInstallation(String)\n\n    /// The schema version is invalid.\n    case invalidSchemaVersion\n\n    /// Name of the Swift SDK bundle is not valid.\n    case invalidBundleName(String)\n\n    /// No valid Swift SDKs were decoded from a metadata file.\n    case noSwiftSDKDecoded(Basics.AbsolutePath)\n\n    /// Path used for storing Swift SDK configuration data is not a directory.\n    case pathIsNotDirectory(Basics.AbsolutePath)\n\n    /// Swift SDK metadata couldn't be serialized with the latest serialization schema, potentially because it\n    /// was deseriali\u0005zed from an earlier incompatible schema version or initialized manually with properties\n    /// required for initialization missing.\n    case unserializableMetadata\n\n    /// No configuration values are available for this Swift SDK and target triple.\n    case swiftSDKNotFound(artifactID: String, hostTriple: Triple, targetTriple: Triple?)\n\n    /// A Swift SDK bundle with this name is already installed, can't install a new bundle with the same name.\n    case swiftSDKBundleAlreadyInstalled(bundleName: String)\n\n    /// A Swift SDK with this artifact ID is already installed. Can't install a new bundle with this artifact,\n    /// installed artifact IDs are expected to be unique.\n    case swiftSDKArtifactAlreadyInstalled(installedBundleName: String, newBundleName: String, artifactID: String)\n\n    #if os(macOS)\n    /// Quarantine attribute should be removed by the `xattr` command from an installed bundle.\n    case quarantineAttributePresent(bundlePath: Basics.AbsolutePath)\n    #endif\n}\n\nextension SwiftSDKError: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case let .checksumInvalid(computed, provided):\n            return \"\"\"\n            Computed archive checksum `\\(computed)` does not match the provided checksum `\\(provided)`.\n            \"\"\"\n\n        case .checksumNotProvided(let url):\n            return \"\"\"\n            Bundles installed from remote URLs (`\\(url)`) require their checksum passed via `--checksum` option.\n            The distributor of the bundle must compute it with the `swift package compute-checksum` \\\n            command and provide it with their Swift SDK installation instructions.\n            \"\"\"\n        case .invalidBundleArchive(let archivePath):\n            return \"\"\"\n            Swift SDK archive at `\\(archivePath)` does not contain at least one directory with the \\\n            `.artifactbundle` extension.\n            \"\"\"\n        case .invalidPathOrURL(let argument):\n            return \"`\\(argument)` is neither a valid filesystem path nor a URL.\"\n        case .invalidSchemaVersion:\n            return \"unsupported Swift SDK file schema version\"\n        case .invalidInstallation(let problem):\n            return problem\n        case .invalidBundleName(let name):\n            return \"\"\"\n            invalid bundle name `\\(name)`, unpacked Swift SDK bundles are expected to have `.artifactbundle` extension\n            \"\"\"\n        case .noSwiftSDKDecoded(let path):\n            return \"no valid Swift SDKs were decoded from a metadata file at path `\\(path)`\"\n        case .pathIsNotDirectory(let path):\n            return \"path expected to be a directory is not a directory or doesn't exist: `\\(path)`\"\n        case .unserializableMetadata:\n            return \"\"\"\n            Swift SDK configuration couldn't be serialized with the latest serialization schema, potentially because \\\n            it was deserialized from an earlier incompatible schema version or initialized manually with missing \\\n            properties required for initialization\n            \"\"\"\n        case .swiftSDKNotFound(let artifactID, let hostTriple, let targetTriple):\n            if let targetTriple {\n                return \"\"\"\n                Swift SDK with ID `\\(artifactID)`, host triple \\(hostTriple), and target triple \\(targetTriple) is not \\\n                currently installed.\n                \"\"\"\n            } else {\n                return \"\"\"\n                Swift SDK with ID `\\(artifactID)` is not currently installed.\n                \"\"\"\n            }\n        case .swiftSDKBundleAlreadyInstalled(let bundleName):\n            return \"\"\"\n            Swift SDK bundle with name `\\(bundleName)` is already installed. Can't install a new bundle \\\n            with the same name.\n            \"\"\"\n        case .swiftSDKArtifactAlreadyInstalled(let installedBundleName, let newBundleName, let artifactID):\n            return \"\"\"\n            A Swift SDK with artifact ID `\\(artifactID)` is already included in an installed bundle with name \\\n            `\\(installedBundleName)`. Can't install a new bundle `\\(newBundleName)` with this artifact, artifact IDs \\\n            are expected to be unique across all installed Swift SDK bundles.\n            \"\"\"\n        #if os(macOS)\n        case .quarantineAttributePresent(let bundlePath):\n            return \"\"\"\n            Quarantine attribute is present on a Swift SDK bundle at path `\\(bundlePath)`. If you're certain that the \\\n            bundle was downloaded from a trusted source, you can remove the attribute with this command:\n\n            xattr -d -r -s com.apple.quarantine \"\\(bundlePath)\"\n\n            and try to install this bundle again.\n            \"\"\"\n        #endif\n        }\n    }\n}\n\n@available(*, deprecated, renamed: \"SwiftSDK\")\npublic typealias Destination = SwiftSDK\n\n/// Swift SDK model type which has information about everything that's required to build a SwiftPM package for a certain\n/// platform.\npublic struct SwiftSDK: Equatable {\n    /// The clang/LLVM triple describing the target OS and architecture.\n    ///\n    /// The triple has the general format <arch><sub>-<vendor>-<sys>-<abi>, where:\n    ///  - arch = x86_64, i386, arm, thumb, mips, etc.\n    ///  - sub = for ex. on ARM: v5, v6m, v7a, v7m, etc.\n    ///  - vendor = pc, apple, nvidia, ibm, etc.\n    ///  - sys = none, linux, win32, darwin, cuda, etc.\n    ///  - abi = eabi, gnu, android, macho, elf, etc.\n    ///\n    /// for more information see //https://clang.llvm.org/docs/CrossCompilation.html\n    public var targetTriple: Triple?\n\n    /// The clang/LLVM triple describing the host platform that supports this Swift SDK.\n    public let hostTriple: Triple?\n\n    // FIXME: this needs to be implemented with either multiple Swift SDKs or making ``SwiftSDK/targetTriple`` an array.\n    /// The architectures to build for. We build for host architecture if this is empty.\n    public var architectures: [String]? = nil\n\n    /// Whether or not the receiver supports testing.\n    @available(*, deprecated, message: \"Use `xctestSupport` instead\")\n    public var supportsTesting: Bool {\n        if case .supported = xctestSupport {\n            return true\n        }\n        return false\n    }\n\n    /// Whether or not the receiver supports testing using XCTest.\n    @_spi(SwiftPMInternal)\n    public enum XCTestSupport: Sendable, Equatable {\n        /// XCTest is supported.\n        case supported\n\n        /// XCTest is not supported.\n        ///\n        /// - Parameters:\n        ///     - reason: A string explaining why XCTest is not supported. If\n        ///         `nil`, no additional information is available.\n        case unsupported(reason: String?)\n    }\n\n    /// Whether or not the receiver supports using XCTest.\n    @_spi(SwiftPMInternal)\n    public let xctestSupport: XCTestSupport\n\n    /// Root directory path of the SDK used to compile for the target triple.\n    @available(*, deprecated, message: \"use `pathsConfiguration.sdkRootPath` instead\")\n    public var sdk: Basics.AbsolutePath? {\n        get {\n            sdkRootDir\n        }\n        set {\n            sdkRootDir = newValue\n        }\n    }\n\n    /// Root directory path of the SDK used to compile for the target triple.\n    @available(*, deprecated, message: \"use `pathsConfiguration.sdkRootPath` instead\")\n    public var sdkRootDir: Basics.AbsolutePath? {\n        get {\n            pathsConfiguration.sdkRootPath\n        }\n        set {\n            pathsConfiguration.sdkRootPath = newValue\n        }\n    }\n\n    /// Path to a directory containing the toolchain (compilers/linker) to be used for the compilation.\n    @available(*, deprecated, message: \"use `toolset.rootPaths` instead\")\n    public var binDir: Basics.AbsolutePath {\n        toolchainBinDir\n    }\n\n    /// Path to a directory containing the toolchain (compilers/linker) to be used for the compilation.\n    @available(*, deprecated, message: \"use `toolset.rootPaths` instead\")\n    public var toolchainBinDir: Basics.AbsolutePath {\n        toolset.rootPaths[0]\n    }\n\n    /// Additional flags to be passed to the C compiler.\n    @available(*, deprecated, message: \"use `toolset` and its properties instead\")\n    public var extraCCFlags: [String] {\n        extraFlags.cCompilerFlags.rawFlags\n    }\n\n    /// Additional flags to be passed to the Swift compiler.\n    @available(*, deprecated, message: \"use `toolset` and its properties instead\")\n    public var extraSwiftCFlags: [String] {\n        extraFlags.swiftCompilerFlags.rawFlags\n    }\n\n    /// Additional flags to be passed to the C++ compiler.\n    @available(*, deprecated, message: \"use `toolset` and its properties instead\")\n    public var extraCPPFlags: [String] {\n        extraFlags.cxxCompilerFlags.rawFlags\n    }\n\n    /// Additional flags to be passed to the build tools.\n    @available(*, deprecated, message: \"use `toolset` and its properties instead\")\n    public var extraFlags: BuildFlags {\n        return .init(\n            cCompilerFlags: (toolset.knownTools[.cCompiler]?.extraCLIOptions ?? []).constructBuildFlags(source: .toolset),\n            cxxCompilerFlags: (toolset.knownTools[.cxxCompiler]?.extraCLIOptions ?? []).constructBuildFlags(source: .toolset),\n            swiftCompilerFlags: (toolset.knownTools[.swiftCompiler]?.extraCLIOptions ?? []).constructBuildFlags(source: .toolset),\n            linkerFlags: (toolset.knownTools[.linker]?.extraCLIOptions ?? []).constructBuildFlags(source: .toolset),\n            xcbuildFlags: toolset.knownTools[.xcbuild]?.extraCLIOptions ?? []\n        )\n    }\n\n    /// Set of tools and their properties used for building code for the target triple. While a serialized Swift SDK\n    /// metadata may specify multiple toolset files, these files are consolidated into a single ``Toolset`` value during\n    /// deserialization.\n    public private(set) var toolset: Toolset\n\n    public private(set) var swiftSDKManifest: Basics.AbsolutePath?\n\n    public func loadSettings() throws -> SDKSettings? {\n        guard let sdkSettingsFile = pathsConfiguration.sdkRootPath?.appending(\"SDKSettings.json\") else {\n            return nil\n        }\n        return try JSONDecoder().decode(SDKSettings.self, from: Data(contentsOf: sdkSettingsFile.asURL))\n    }\n\n    /// The paths associated with a Swift SDK. The Path type can be a `String`\n    /// to encapsulate the arguments for the `SwiftSDKConfigurationStore.configure`\n    /// function, or can be a fully-realized `AbsolutePath` when deserialized from a configuration.\n    public struct PathsConfiguration<Path: Equatable>: Equatable {\n        public init(\n            sdkRootPath: Path? = nil,\n            swiftResourcesPath: Path? = nil,\n            swiftStaticResourcesPath: Path? = nil,\n            includeSearchPaths: [Path]? = nil,\n            librarySearchPaths: [Path]? = nil,\n            toolsetPaths: [Path]? = nil\n        ) {\n            self.sdkRootPath = sdkRootPath\n            self.swiftResourcesPath = swiftResourcesPath\n            self.swiftStaticResourcesPath = swiftStaticResourcesPath\n            self.includeSearchPaths = includeSearchPaths\n            self.librarySearchPaths = librarySearchPaths\n            self.toolsetPaths = toolsetPaths\n        }\n\n        /// Root directory path of the SDK used to compile for the target triple.\n        public var sdkRootPath: Path?\n\n        /// Path containing Swift resources for dynamic linking.\n        public var swiftResourcesPath: Path?\n\n        /// Path containing Swift resources for static linking.\n        public var swiftStaticResourcesPath: Path?\n\n        /// Array of paths containing headers.\n        public var includeSearchPaths: [Path]?\n\n        /// Array of paths containing libraries.\n        public var librarySearchPaths: [Path]?\n\n        /// Array of paths containing toolset files.\n        public var toolsetPaths: [Path]?\n\n        /// Initialize paths configuration from values deserialized using v3 schema.\n        /// - Parameters:\n        ///   - properties: properties of the Swift SDK for the given triple.\n        ///   - swiftSDKDirectory: directory used for converting relative paths in `properties` to absolute paths.\n        fileprivate init(\n            _ properties: SerializedDestinationV3.TripleProperties,\n            swiftSDKDirectory: Basics.AbsolutePath? = nil\n        ) throws where Path == Basics.AbsolutePath {\n            self.init(\n                sdkRootPath: try AbsolutePath(validating: properties.sdkRootPath, relativeTo: swiftSDKDirectory),\n                swiftResourcesPath: try properties.swiftResourcesPath.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                swiftStaticResourcesPath: try properties.swiftStaticResourcesPath.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                includeSearchPaths: try properties.includeSearchPaths?.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                librarySearchPaths: try properties.librarySearchPaths?.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                toolsetPaths: try properties.toolsetPaths?.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                }\n            )\n        }\n\n        /// Initialize paths configuration from values deserialized using v4 schema.\n        /// - Parameters:\n        ///   - properties: properties of a Swift SDK for the given triple.\n        ///   - swiftSDKDirectory: directory used for converting relative paths in `properties` to absolute paths.\n        fileprivate init(\n            _ properties: SwiftSDKMetadataV4.TripleProperties,\n            swiftSDKDirectory: Basics.AbsolutePath? = nil\n        ) throws where Path == Basics.AbsolutePath {\n            self.init(\n                sdkRootPath: try properties.sdkRootPath.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                swiftResourcesPath: try properties.swiftResourcesPath.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                swiftStaticResourcesPath: try properties.swiftStaticResourcesPath.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                includeSearchPaths: try properties.includeSearchPaths?.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                librarySearchPaths: try properties.librarySearchPaths?.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                },\n                toolsetPaths: try properties.toolsetPaths?.map {\n                    try AbsolutePath(validating: $0, relativeTo: swiftSDKDirectory)\n                }\n            )\n        }\n\n        public mutating func merge(with newConfiguration: Self) {\n            if let sdkRootPath = newConfiguration.sdkRootPath {\n                self.sdkRootPath = sdkRootPath\n            }\n\n            if let swiftResourcesPath = newConfiguration.swiftResourcesPath {\n                self.swiftResourcesPath = swiftResourcesPath\n            }\n\n            if let swiftStaticResourcesPath = newConfiguration.swiftStaticResourcesPath {\n                self.swiftStaticResourcesPath = swiftStaticResourcesPath\n            }\n\n            if let includeSearchPaths = newConfiguration.includeSearchPaths {\n                self.includeSearchPaths = includeSearchPaths\n            }\n\n            if let librarySearchPaths = newConfiguration.librarySearchPaths {\n                self.librarySearchPaths = librarySearchPaths\n            }\n\n            if let toolsetPaths = newConfiguration.toolsetPaths {\n                self.toolsetPaths = toolsetPaths\n            }\n        }\n\n        mutating func merge(\n            with newConfiguration: PathsConfiguration<String>,\n            relativeTo basePath: Path?\n        ) throws -> [String] where Path == Basics.AbsolutePath {\n            var updatedProperties: [String] = []\n            if let sdkRootPath = newConfiguration.sdkRootPath {\n                self.sdkRootPath = try AbsolutePath(validating: sdkRootPath, relativeTo: basePath)\n                updatedProperties.append(\"sdkRootPath\")\n            }\n\n            if let swiftResourcesPath = newConfiguration.swiftResourcesPath {\n                self.swiftResourcesPath = try AbsolutePath(validating: swiftResourcesPath, relativeTo: basePath)\n                updatedProperties.append(\"swiftResourcesPath\")\n            }\n\n            if let swiftStaticResourcesPath = newConfiguration.swiftStaticResourcesPath {\n                self.swiftResourcesPath = try AbsolutePath(validating: swiftStaticResourcesPath, relativeTo: basePath)\n                updatedProperties.append(\"swiftStaticResourcesPath\")\n            }\n\n            if let includeSearchPaths = newConfiguration.includeSearchPaths, !includeSearchPaths.isEmpty {\n                self.includeSearchPaths = try includeSearchPaths.map { try AbsolutePath(validating: $0, relativeTo: basePath) }\n                updatedProperties.append(\"includeSearchPath\")\n            }\n\n            if let librarySearchPaths = newConfiguration.librarySearchPaths, !librarySearchPaths.isEmpty {\n                self.librarySearchPaths = try librarySearchPaths.map { try AbsolutePath(validating: $0, relativeTo: basePath) }\n                updatedProperties.append(\"librarySearchPath\")\n            }\n\n            if let toolsetPaths = newConfiguration.toolsetPaths, !toolsetPaths.isEmpty {\n                self.toolsetPaths = try toolsetPaths.map { try AbsolutePath(validating: $0, relativeTo: basePath) }\n                updatedProperties.append(\"toolsetPath\")\n            }\n\n            return updatedProperties\n        }\n    }\n\n    /// Configuration of file system paths used by this Swift SDK when building.\n    public var pathsConfiguration: PathsConfiguration<Basics.AbsolutePath>\n\n    /// Creates a Swift SDK with the specified properties.\n    @available(*, deprecated, message: \"use `init(targetTriple:sdkRootDir:toolset:)` instead\")\n    public init(\n        target: Triple? = nil,\n        sdk: Basics.AbsolutePath?,\n        binDir: Basics.AbsolutePath,\n        extraCCFlags: [String] = [],\n        extraSwiftCFlags: [String] = [],\n        extraCPPFlags: [String] = []\n    ) {\n        self.init(\n            targetTriple: target,\n            sdkRootDir: sdk,\n            toolchainBinDir: binDir,\n            extraFlags: BuildFlags(\n                cCompilerFlags: extraCCFlags.constructBuildFlags(source: .swiftSDK),\n                cxxCompilerFlags: extraCPPFlags.constructBuildFlags(source: .swiftSDK),\n                swiftCompilerFlags: extraSwiftCFlags.constructBuildFlags(source: .swiftSDK)\n            )\n        )\n    }\n\n    /// Creates a Swift SDK with the specified properties.\n    @available(*, deprecated, message: \"use `init(hostTriple:targetTriple:toolset:pathsConfiguration:)` instead\")\n    public init(\n        hostTriple: Triple? = nil,\n        targetTriple: Triple? = nil,\n        sdkRootDir: Basics.AbsolutePath?,\n        toolchainBinDir: Basics.AbsolutePath,\n        extraFlags: BuildFlags = BuildFlags()\n    ) {\n        self.init(\n            hostTriple: hostTriple,\n            targetTriple: targetTriple,\n            toolset: Toolset(toolchainBinDir: toolchainBinDir, buildFlags: extraFlags),\n            pathsConfiguration: .init(sdkRootPath: sdkRootDir)\n        )\n    }\n\n    /// Creates a Swift SDK with the specified properties.\n    @available(*, deprecated, message: \"use `init(hostTriple:targetTriple:toolset:pathsConfiguration:xctestSupport:)` instead\")\n    public init(\n        hostTriple: Triple? = nil,\n        targetTriple: Triple? = nil,\n        toolset: Toolset,\n        pathsConfiguration: PathsConfiguration<Basics.AbsolutePath>,\n        supportsTesting: Bool\n    ) {\n        let xctestSupport: XCTestSupport\n        if supportsTesting {\n            xctestSupport = .supported\n        } else {\n            xctestSupport = .unsupported(reason: nil)\n        }\n\n        self.init(\n            hostTriple: hostTriple,\n            targetTriple: targetTriple,\n            toolset: toolset,\n            pathsConfiguration: pathsConfiguration,\n            xctestSupport: xctestSupport\n        )\n    }\n\n    /// Creates a Swift SDK with the specified properties.\n    @_spi(SwiftPMInternal)\n    public init(\n        hostTriple: Triple? = nil,\n        targetTriple: Triple? = nil,\n        toolset: Toolset,\n        swiftSDKManifest: Basics.AbsolutePath? = nil,\n        pathsConfiguration: PathsConfiguration<Basics.AbsolutePath>,\n        xctestSupport: XCTestSupport = .supported\n    ) {\n        self.hostTriple = hostTriple\n        self.targetTriple = targetTriple\n        self.toolset = toolset\n        self.swiftSDKManifest = swiftSDKManifest\n        self.pathsConfiguration = pathsConfiguration\n        self.xctestSupport = xctestSupport\n    }\n\n    /// Returns the bin directory for the host.\n    private static func hostBinDir(\n        fileSystem: FileSystem\n    ) throws -> Basics.AbsolutePath {\n        guard let cwd = fileSystem.currentWorkingDirectory else {\n            return try AbsolutePath(validating: CommandLine.arguments[0]).parentDirectory\n        }\n        return try AbsolutePath(validating: CommandLine.arguments[0], relativeTo: cwd).parentDirectory\n    }\n\n    /// The Swift SDK describing the host platform.\n    @available(*, deprecated, renamed: \"hostSwiftSDK\")\n    public static func hostDestination(\n        _ binDir: Basics.AbsolutePath? = nil,\n        originalWorkingDirectory: Basics.AbsolutePath? = nil,\n        environment: Environment\n    ) throws -> SwiftSDK {\n        try self.hostSwiftSDK(binDir, environment: environment)\n    }\n\n    /// The Swift SDK for the host platform.\n    public static func hostSwiftSDK(\n        _ binDir: Basics.AbsolutePath? = nil,\n        environment: Environment = .current,\n        observabilityScope: ObservabilityScope? = nil,\n        fileSystem: any FileSystem = Basics.localFileSystem\n    ) throws -> SwiftSDK {\n        try self.systemSwiftSDK(\n            binDir,\n            environment: environment,\n            observabilityScope: observabilityScope,\n            fileSystem: fileSystem\n        )\n    }\n\n    /// A default Swift SDK on the host.\n    ///\n    /// Equivalent to `hostSwiftSDK`, except on macOS, where passing a non-nil `darwinPlatformOverride`\n    /// will result in the SDK for the corresponding Darwin platform.\n    private static func systemSwiftSDK(\n        _ binDir: Basics.AbsolutePath? = nil,\n        environment: Environment = .current,\n        observabilityScope: ObservabilityScope? = nil,\n        fileSystem: any FileSystem = Basics.localFileSystem,\n        darwinPlatformOverride: DarwinPlatform? = nil\n    ) throws -> SwiftSDK {\n        // Select the correct binDir.\n        if environment[\"SWIFTPM_CUSTOM_BINDIR\"] != nil {\n            print(\"SWIFTPM_CUSTOM_BINDIR was deprecated in favor of SWIFTPM_CUSTOM_BIN_DIR\")\n        }\n        let customBinDir = (environment[\"SWIFTPM_CUSTOM_BIN_DIR\"] ?? environment[\"SWIFTPM_CUSTOM_BINDIR\"])\n            .flatMap { try? Basics.AbsolutePath(validating: $0) }\n        let binDir = try customBinDir ?? binDir ?? SwiftSDK.hostBinDir(fileSystem: fileSystem)\n\n        let sdkPath: Basics.AbsolutePath?\n        #if os(macOS)\n        let darwinPlatform = darwinPlatformOverride ?? .macOS\n        // Get the SDK.\n        if let value = environment[\"SDKROOT\"] {\n            sdkPath = try AbsolutePath(validating: value)\n        } else if let value = environment[EnvironmentKey(\"SWIFTPM_SDKROOT_\\(darwinPlatform.xcrunName)\")] {\n            sdkPath = try AbsolutePath(validating: value)\n        } else {\n            // No value in env, so search for it.\n            let sdkPathStr = try AsyncProcess.checkNonZeroExit(\n                arguments: [\"/usr/bin/xcrun\", \"--sdk\", darwinPlatform.xcrunName, \"--show-sdk-path\"],\n                environment: environment\n            ).spm_chomp()\n            guard !sdkPathStr.isEmpty else {\n                throw SwiftSDKError.invalidInstallation(\"default SDK not found\")\n            }\n            sdkPath = try AbsolutePath(validating: sdkPathStr)\n        }\n        #else\n        sdkPath = nil\n        #endif\n\n        // Compute common arguments for clang and swift.\n        let xctestSupport: XCTestSupport\n        var extraCCFlags: [String] = []\n        var extraSwiftCFlags: [String] = []\n        #if os(macOS)\n        do {\n            let sdkPaths = try SwiftSDK.sdkPlatformPaths(for: darwinPlatform, environment: environment)\n            extraCCFlags.append(contentsOf: sdkPaths.buildTimeFrameworkSearchPaths.flatMap { [\"-F\", $0.pathString] })\n            extraSwiftCFlags.append(contentsOf: sdkPaths.buildTimeFrameworkSearchPaths.flatMap { [\"-F\", $0.pathString] })\n            extraSwiftCFlags.append(contentsOf: sdkPaths.buildTimeLibrarySearchPaths.flatMap { [\"-I\", $0.pathString] })\n            extraSwiftCFlags.append(contentsOf: sdkPaths.buildTimeLibrarySearchPaths.flatMap { [\"-L\", $0.pathString] })\n            xctestSupport = .supported\n        } catch {\n            xctestSupport = .unsupported(reason: String(describing: error))\n        }\n        #else\n        xctestSupport = .supported\n        #endif\n\n        #if !os(Windows)\n        extraCCFlags += [\"-fPIC\"]\n        #endif\n\n        return SwiftSDK(\n            toolset: .init(\n                knownTools: [\n                    .cCompiler: .init(extraCLIOptions: extraCCFlags),\n                    .swiftCompiler: .init(extraCLIOptions: extraSwiftCFlags),\n                ],\n                rootPaths: [binDir]\n            ),\n            pathsConfiguration: .init(sdkRootPath: sdkPath),\n            xctestSupport: xctestSupport\n        )\n    }\n\n    /// Auxiliary platform frameworks and libraries.\n    ///\n    /// The referenced directories may contain, for example, test support utilities.\n    ///\n    /// - SeeAlso: ``sdkPlatformPaths(for:environment:)``\n    public struct PlatformPaths {\n        /// Paths of directories containing auxiliary platform frameworks which\n        /// should be included as framework search paths at build time.\n        public var buildTimeFrameworkSearchPaths: [Basics.AbsolutePath]\n\n        /// Paths of directories containing auxiliary platform libraries which\n        /// should be included as library search paths at build time.\n        public var buildTimeLibrarySearchPaths: [Basics.AbsolutePath]\n\n        /// Paths of directories containing auxiliary platform frameworks which\n        /// should be included as framework search paths at runtime.\n        public var runtimeFrameworkSearchPaths: [Basics.AbsolutePath]\n\n        /// Paths of directories containing auxiliary platform libraries which\n        /// should be included as library search paths at runtime.\n        public var runtimeLibrarySearchPaths: [Basics.AbsolutePath]\n    }\n\n    /// Returns `macosx` sdk platform framework path.\n    @available(*, deprecated, message: \"use sdkPlatformPaths(for:) instead\")\n    public static func sdkPlatformFrameworkPaths(\n        environment: Environment = .current\n    ) throws -> (fwk: Basics.AbsolutePath, lib: Basics.AbsolutePath) {\n        let paths = try sdkPlatformPaths(for: .macOS, environment: environment)\n        guard let frameworkPath = paths.buildTimeFrameworkSearchPaths.first else {\n            throw StringError(\"could not determine SDK platform framework path\")\n        }\n        guard let libraryPath = paths.buildTimeLibrarySearchPaths.first else {\n            throw StringError(\"could not determine SDK platform library path\")\n        }\n        return (fwk: frameworkPath, lib: libraryPath)\n    }\n\n    /// Returns ``SwiftSDK/PlatformPaths`` for the provided Darwin platform.\n    public static func sdkPlatformPaths(\n        for darwinPlatform: DarwinPlatform,\n        environment: Environment = .current\n    ) throws -> PlatformPaths {\n        let sdkPlatformFrameworkPath = try _sdkPlatformFrameworkPathCache.memoize(darwinPlatform) {\n            // Compute the platform path.\n            let platformPath = try environment[\n                EnvironmentKey(\"SWIFTPM_PLATFORM_PATH_\\(darwinPlatform.xcrunName)\")\n            ] ?? AsyncProcess.checkNonZeroExit(\n                arguments: [\"/usr/bin/xcrun\", \"--sdk\", darwinPlatform.xcrunName, \"--show-sdk-platform-path\"],\n                environment: environment\n            ).spm_chomp()\n\n            guard !platformPath.isEmpty else {\n                throw StringError(\"could not determine SDK platform path\")\n            }\n\n            // For testing frameworks.\n            let frameworksPath = try Basics.AbsolutePath(validating: platformPath).appending(\n                components: \"Developer\", \"Library\", \"Frameworks\"\n            )\n            let privateFrameworksPath = try Basics.AbsolutePath(validating: platformPath).appending(\n                components: \"Developer\", \"Library\", \"PrivateFrameworks\"\n            )\n\n            // For testing libraries.\n            let librariesPath = try Basics.AbsolutePath(validating: platformPath).appending(\n                components: \"Developer\", \"usr\", \"lib\"\n            )\n\n            let sdkPlatformFrameworkPath = PlatformPaths(\n                buildTimeFrameworkSearchPaths: [frameworksPath /* omit privateFrameworksPath */],\n                buildTimeLibrarySearchPaths: [librariesPath],\n                runtimeFrameworkSearchPaths: [frameworksPath, privateFrameworksPath],\n                runtimeLibrarySearchPaths: [librariesPath]\n            )\n            return sdkPlatformFrameworkPath\n        }\n        return sdkPlatformFrameworkPath\n    }\n\n    /// Cache storage for sdk platform paths.\n    private static let _sdkPlatformFrameworkPathCache = ThreadSafeKeyValueStore<DarwinPlatform, PlatformPaths>()\n\n    /// Returns a default Swift SDK for a given target environment\n    @available(*, deprecated, renamed: \"defaultSwiftSDK\")\n    public static func defaultDestination(for triple: Triple, host: SwiftSDK) -> SwiftSDK? {\n        defaultSwiftSDK(for: triple, hostSDK: host)\n    }\n\n    /// Returns a default Swift SDK of a given target environment.\n    public static func defaultSwiftSDK(\n        for targetTriple: Triple,\n        hostSDK: SwiftSDK,\n        environment: Environment = .current\n    ) -> SwiftSDK? {\n        #if os(macOS)\n        if let darwinPlatform = targetTriple.darwinPlatform {\n            // the Darwin SDKs are trivially available on macOS\n            var sdk = try? self.systemSwiftSDK(\n                hostSDK.toolset.rootPaths.first,\n                environment: environment,\n                darwinPlatformOverride: darwinPlatform\n            )\n            sdk?.targetTriple = targetTriple\n            return sdk\n        }\n        #endif\n\n        return nil\n    }\n\n    /// Computes the target Swift SDK for the given options.\n    public static func deriveTargetSwiftSDK(\n      hostSwiftSDK: SwiftSDK,\n      hostTriple: Triple,\n      customToolsets: [Basics.AbsolutePath] = [],\n      customCompileDestination: Basics.AbsolutePath? = nil,\n      customCompileTriple: Triple? = nil,\n      customCompileToolchain: Basics.AbsolutePath? = nil,\n      customCompileSDK: Basics.AbsolutePath? = nil,\n      swiftSDKSelector: String? = nil,\n      architectures: [String] = [],\n      store: SwiftSDKBundleStore,\n      observabilityScope: ObservabilityScope,\n      fileSystem: FileSystem\n    ) throws -> SwiftSDK {\n        var swiftSDK: SwiftSDK\n        var isBasedOnHostSDK: Bool = false\n\n        // Create custom toolchain if present.\n        if let customDestination = customCompileDestination {\n            let swiftSDKs = try SwiftSDK.decode(\n                fromFile: customDestination,\n                hostToolchainBinDir: store.hostToolchainBinDir,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n            if swiftSDKs.count == 1 {\n                swiftSDK = swiftSDKs[0]\n            } else if swiftSDKs.count > 1,\n                      let triple = customCompileTriple,\n                      let matchingSDK = swiftSDKs.first(where: { $0.targetTriple == triple })\n            {\n                swiftSDK = matchingSDK\n            } else {\n                throw SwiftSDKError.noSwiftSDKDecoded(customDestination)\n            }\n        } else if let targetTriple = customCompileTriple,\n                  let targetSwiftSDK = SwiftSDK.defaultSwiftSDK(for: targetTriple, hostSDK: hostSwiftSDK)\n        {\n            swiftSDK = targetSwiftSDK\n        } else if let swiftSDKSelector {\n            do {\n                swiftSDK = try store.selectBundle(matching: swiftSDKSelector, hostTriple: hostTriple)\n            } catch {\n                // If a user-installed bundle for the selector doesn't exist, check if the\n                // selector is recognized as a default SDK.\n                if let targetTriple = try? Triple(swiftSDKSelector),\n                   let defaultSDK = SwiftSDK.defaultSwiftSDK(for: targetTriple, hostSDK: hostSwiftSDK) {\n                    swiftSDK = defaultSDK\n                } else {\n                    throw error\n                }\n            }\n        } else {\n            // Otherwise use the host toolchain.\n            swiftSDK = hostSwiftSDK\n            isBasedOnHostSDK = true\n        }\n\n        if !customToolsets.isEmpty {\n            for toolsetPath in customToolsets {\n                let toolset = try Toolset(from: toolsetPath, at: fileSystem, observabilityScope)\n                swiftSDK.toolset.merge(with: toolset)\n            }\n        }\n\n        // Apply any manual overrides.\n        if let triple = customCompileTriple {\n            swiftSDK.targetTriple = triple\n\n            if isBasedOnHostSDK && customToolsets.isEmpty {\n                // Don't pick up extraCLIOptions for a custom triple, since those are only valid for the host triple.\n                for tool in swiftSDK.toolset.knownTools.keys {\n                    swiftSDK.toolset.knownTools[tool]?.extraCLIOptions = []\n                }\n            }\n        }\n\n        if let binDir = customCompileToolchain {\n            if !fileSystem.exists(binDir) {\n                observabilityScope.emit(\n                    warning: \"\"\"\n                        Toolchain directory specified through a command-line option doesn't exist and is ignored: `\\(\n                            binDir\n                        )`\n                        \"\"\"\n                )\n            }\n\n            // `--tooolchain` should override existing anything in the SDK and search paths.\n            swiftSDK.prepend(toolsetRootPath: binDir.appending(components: \"usr\", \"bin\"))\n        }\n        if let sdk = customCompileSDK {\n            swiftSDK.pathsConfiguration.sdkRootPath = sdk\n        }\n        swiftSDK.architectures = architectures.isEmpty ? nil : architectures\n\n        if !isBasedOnHostSDK {\n            // Append the host toolchain's toolset paths at the end for the case the target Swift SDK\n            // doesn't have some of the tools (e.g. swift-frontend might be shared between the host and\n            // target Swift SDKs).\n            let rootPaths = Set(swiftSDK.toolset.rootPaths)\n            for rootPath in hostSwiftSDK.toolset.rootPaths where !rootPaths.contains(rootPath) {\n                swiftSDK.append(toolsetRootPath: rootPath)\n            }\n        }\n\n        return swiftSDK\n    }\n\n    /// Propagates toolchain and SDK paths known to the Swift SDK to `swiftc` CLI options.\n    public mutating func applyPathCLIOptions() {\n        var properties = self.toolset.knownTools[.swiftCompiler] ?? .init(extraCLIOptions: [])\n        properties.extraCLIOptions.append(contentsOf: self.toolset.rootPaths.flatMap { [\"-tools-directory\", $0.pathString] })\n\n        if let sdkDirPath = self.pathsConfiguration.sdkRootPath?.pathString {\n            properties.extraCLIOptions.append(contentsOf: [\"-sdk\", sdkDirPath])\n        }\n\n        self.toolset.knownTools[.swiftCompiler] = properties\n    }\n\n    /// Prepends a path to the array of toolset root paths.\n    ///\n    /// Note: Use this operation if you want new root path to take priority over existing paths.\n    ///\n    /// - Parameter toolsetRootPath: new path to add to Swift SDK's toolset.\n    public mutating func prepend(toolsetRootPath path: Basics.AbsolutePath) {\n        self.toolset.rootPaths.insert(path, at: 0)\n    }\n\n    /// Appends a path to the array of toolset root paths.\n    ///\n    /// Note: The paths are evaluated in insertion order which means that newly added path would\n    /// have a lower priority vs. existing paths.\n    ///\n    /// - Parameter toolsetRootPath: new path to add to Swift SDK's toolset.\n    public mutating func append(toolsetRootPath: Basics.AbsolutePath) {\n        self.toolset.rootPaths.append(toolsetRootPath)\n    }\n}\n\nextension SwiftSDK {\n    /// Load a ``SwiftSDK`` description from a JSON representation from disk.\n    public static func decode(\n        fromFile path: Basics.AbsolutePath,\n        hostToolchainBinDir: Basics.AbsolutePath,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws -> [SwiftSDK] {\n        let decoder = JSONDecoder.makeWithDefaults()\n        do {\n            let version = try decoder.decode(path: path, fileSystem: fileSystem, as: SemanticVersionInfo.self)\n            return try Self.decode(\n                semanticVersion: version,\n                fromFile: path,\n                hostToolchainBinDir: hostToolchainBinDir,\n                fileSystem: fileSystem,\n                decoder: decoder,\n                observabilityScope: observabilityScope\n            )\n        } catch DecodingError.keyNotFound {\n            let version = try decoder.decode(path: path, fileSystem: fileSystem, as: VersionInfo.self)\n            return try [SwiftSDK(legacy: version, fromFile: path, fileSystem: fileSystem, decoder: decoder)]\n        }\n    }\n\n    /// Load a ``SwiftSDK`` description from a semantically versioned JSON representation from disk.\n    private static func decode(\n        semanticVersion: SemanticVersionInfo,\n        fromFile path: Basics.AbsolutePath,\n        hostToolchainBinDir: Basics.AbsolutePath,\n        fileSystem: FileSystem,\n        decoder: JSONDecoder,\n        observabilityScope: ObservabilityScope\n    ) throws -> [SwiftSDK] {\n        let wasmKitProperties = Toolset.ToolProperties(\n            path: hostToolchainBinDir.appending(\"wasmkit\"),\n            extraCLIOptions: [\"run\", \"--dir\", \".\"]\n        )\n\n        switch semanticVersion.schemaVersion {\n        case Version(3, 0, 0):\n            let swiftSDKs = try decoder.decode(path: path, fileSystem: fileSystem, as: SerializedDestinationV3.self)\n            let swiftSDKDirectory = path.parentDirectory\n\n            return try swiftSDKs.runTimeTriples.map { triple, properties in\n                let triple = try Triple(triple)\n\n                let pathStrings = properties.toolsetPaths ?? []\n                let defaultTools: [Toolset.KnownTool: Toolset.ToolProperties] = if triple.isWasm {\n                    [.debugger: wasmKitProperties, .testRunner: wasmKitProperties]\n                } else {\n                    [:]\n                }\n                let toolset = try pathStrings.reduce(into: Toolset(knownTools: defaultTools, rootPaths: [])) {\n                    try $0.merge(\n                        with: Toolset(\n                            from: .init(validating: $1, relativeTo: swiftSDKDirectory),\n                            at: fileSystem,\n                            observabilityScope\n                        )\n                    )\n                }\n\n                return try SwiftSDK(\n                    targetTriple: triple,\n                    properties: properties,\n                    toolset: toolset,\n                    swiftSDKDirectory: swiftSDKDirectory,\n                    swiftSDKManifest: path,\n                )\n            }\n\n        case Version(4, 0, 0):\n            let swiftSDKs = try decoder.decode(path: path, fileSystem: fileSystem, as: SwiftSDKMetadataV4.self)\n            let swiftSDKDirectory = path.parentDirectory\n\n            return try swiftSDKs.targetTriples.map { triple, properties in\n                let triple = try Triple(triple)\n\n                let defaultTools: [Toolset.KnownTool: Toolset.ToolProperties] = if triple.isWasm {\n                    [.debugger: wasmKitProperties, .testRunner: wasmKitProperties]\n                } else {\n                    [:]\n                }\n                let pathStrings = properties.toolsetPaths ?? []\n                let toolset = try pathStrings.reduce(into: Toolset(knownTools: defaultTools, rootPaths: [])) {\n                    try $0.merge(\n                        with: Toolset(\n                            from: .init(validating: $1, relativeTo: swiftSDKDirectory),\n                            at: fileSystem,\n                            observabilityScope\n                        )\n                    )\n                }\n\n                return try SwiftSDK(\n                    targetTriple: triple,\n                    properties: properties,\n                    toolset: toolset,\n                    swiftSDKDirectory: swiftSDKDirectory,\n                    swiftSDKManifest: path,\n                )\n            }\n        default:\n            throw SwiftSDKError.invalidSchemaVersion\n        }\n    }\n\n    /// Initialize new Swift SDK from values deserialized using v4 schema.\n    /// - Parameters:\n    ///   - targetTriple: triple of the machine running code built with this Swift SDK.\n    ///   - properties: properties of the Swift SDK for the given triple.\n    ///   - toolset: combined toolset used by this Swift SDK.\n    ///   - swiftSDKDirectory: directory used for converting relative paths in `properties` to absolute paths.\n    init(\n        targetTriple: Triple,\n        properties: SwiftSDKMetadataV4.TripleProperties,\n        toolset: Toolset = .init(),\n        swiftSDKDirectory: Basics.AbsolutePath? = nil,\n        swiftSDKManifest: Basics.AbsolutePath? = nil,\n    ) throws {\n        self.init(\n            targetTriple: targetTriple,\n            toolset: toolset,\n            swiftSDKManifest: swiftSDKManifest,\n            pathsConfiguration: try .init(properties, swiftSDKDirectory: swiftSDKDirectory)\n        )\n    }\n\n    /// Initialize new Swift SDK from values deserialized using the v3 schema.\n    /// - Parameters:\n    ///   - targetTriple: triple of the machine running code built with this Swift SDK.\n    ///   - properties: properties of the destination for the given triple.\n    ///   - toolset: combined toolset used by this destination.\n    ///   - swiftSDKDirectory: directory used for converting relative paths in `properties` to absolute paths.\n    private init(\n        targetTriple: Triple,\n        properties: SerializedDestinationV3.TripleProperties,\n        toolset: Toolset = .init(),\n        swiftSDKDirectory: Basics.AbsolutePath? = nil,\n        swiftSDKManifest: Basics.AbsolutePath? = nil,\n    ) throws {\n        self.init(\n            targetTriple: targetTriple,\n            toolset: toolset,\n            swiftSDKManifest: swiftSDKManifest,\n            pathsConfiguration: try .init(properties, swiftSDKDirectory: swiftSDKDirectory)\n        )\n    }\n\n    /// Load a ``SwiftSDK`` description from a legacy JSON representation from disk.\n    private init(\n        legacy version: VersionInfo,\n        fromFile path: Basics.AbsolutePath,\n        fileSystem: FileSystem,\n        decoder: JSONDecoder\n    ) throws {\n        // Check schema version.\n        switch version.version {\n        case 1:\n            let serializedMetadata = try decoder.decode(\n                path: path,\n                fileSystem: fileSystem,\n                as: SerializedDestinationV1.self\n            )\n            try self.init(\n                targetTriple: serializedMetadata.target.map { try Triple($0) },\n                toolset: .init(\n                    toolchainBinDir: serializedMetadata.binDir,\n                    buildFlags: .init(\n                        cCompilerFlags: serializedMetadata.extraCCFlags.constructBuildFlags(source: .swiftSDK),\n                        cxxCompilerFlags: serializedMetadata.extraCPPFlags.constructBuildFlags(source: .swiftSDK),\n                        swiftCompilerFlags: serializedMetadata.extraSwiftCFlags.constructBuildFlags(source: .swiftSDK)\n                    )\n                ),\n                pathsConfiguration: .init(sdkRootPath: serializedMetadata.sdk)\n            )\n        case 2:\n            let serializedMetadata = try decoder.decode(path: path, fileSystem: fileSystem, as: SerializedDestinationV2.self)\n            let swiftSDKDirectory = path.parentDirectory\n\n            try self.init(\n                hostTriple: serializedMetadata.hostTriples.map(Triple.init).first,\n                targetTriple: serializedMetadata.targetTriples.map(Triple.init).first,\n                toolset: .init(\n                    toolchainBinDir: AbsolutePath(\n                        validating: serializedMetadata.toolchainBinDir,\n                        relativeTo: swiftSDKDirectory\n                    ),\n                    buildFlags: .init(\n                        cCompilerFlags: serializedMetadata.extraCCFlags.constructBuildFlags(source: .swiftSDK),\n                        cxxCompilerFlags: serializedMetadata.extraCXXFlags.constructBuildFlags(source: .swiftSDK),\n                        swiftCompilerFlags: serializedMetadata.extraSwiftCFlags.constructBuildFlags(source: .swiftSDK),\n                        linkerFlags: serializedMetadata.extraLinkerFlags.constructBuildFlags(source: .swiftSDK)\n                    )\n                ),\n                pathsConfiguration: .init(\n                    sdkRootPath: AbsolutePath(validating: serializedMetadata.sdkRootDir, relativeTo: swiftSDKDirectory)\n                )\n            )\n        default:\n            throw SwiftSDKError.invalidSchemaVersion\n        }\n    }\n\n    /// Encodes a Swift SDK into its serialized form, which is a pair of its run time triple and paths configuration.\n    /// Returns a pair that can be used to reconstruct a `SerializedDestinationV3` value for storage. `nil` if\n    /// required configuration properties aren't available on `self`, which can happen if `Swift SDK` was decoded\n    /// from different schema versions or constructed manually without providing valid values for such properties.\n    var serialized: (Triple, SerializedDestinationV3.TripleProperties) {\n        get throws {\n            guard let targetTriple = self.targetTriple, let sdkRootDir = self.pathsConfiguration.sdkRootPath else {\n                throw SwiftSDKError.unserializableMetadata\n            }\n\n            return (\n                targetTriple,\n                .init(\n                    sdkRootPath: sdkRootDir.pathString,\n                    swiftResourcesPath: self.pathsConfiguration.swiftResourcesPath?.pathString,\n                    swiftStaticResourcesPath: self.pathsConfiguration.swiftStaticResourcesPath?.pathString,\n                    includeSearchPaths: self.pathsConfiguration.includeSearchPaths?.map(\\.pathString),\n                    librarySearchPaths: self.pathsConfiguration.librarySearchPaths?.map(\\.pathString),\n                    toolsetPaths: self.pathsConfiguration.toolsetPaths?.map(\\.pathString)\n                )\n            )\n        }\n    }\n}\n\nextension DarwinPlatform {\n    /// The name xcrun uses to identify this platform.\n    fileprivate var xcrunName: String {\n        switch self {\n        case .iOS(.catalyst):\n            return \"macosx\"\n        default:\n            return platformName\n        }\n    }\n}\n\n/// Integer version of the schema of `destination.json` files used for cross-compilation.\nprivate struct VersionInfo: Codable {\n    let version: Int\n}\n\n/// Semantic version of the schema of `destination.json` files used for cross-compilation.\nprivate struct SemanticVersionInfo: Decodable {\n    let schemaVersion: Version\n\n    enum CodingKeys: String, CodingKey {\n        case schemaVersion\n    }\n\n    init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        let versionString = try container.decode(String.self, forKey: .schemaVersion)\n        self.schemaVersion = try Version(versionString: versionString, usesLenientParsing: true)\n    }\n}\n\n/// Represents v1 schema of `destination.json` files used for cross-compilation.\nprivate struct SerializedDestinationV1: Codable {\n    let target: String?\n    let sdk: Basics.AbsolutePath?\n    let binDir: Basics.AbsolutePath\n    let extraCCFlags: [String]\n    let extraSwiftCFlags: [String]\n    let extraCPPFlags: [String]\n\n    enum CodingKeys: String, CodingKey {\n        case target\n        case sdk\n        case binDir = \"toolchain-bin-dir\"\n        case extraCCFlags = \"extra-cc-flags\"\n        case extraSwiftCFlags = \"extra-swiftc-flags\"\n        case extraCPPFlags = \"extra-cpp-flags\"\n    }\n}\n\n/// Represents v2 schema of `destination.json` files used for cross-compilation.\nprivate struct SerializedDestinationV2: Codable {\n    let sdkRootDir: String\n    let toolchainBinDir: String\n    let hostTriples: [String]\n    let targetTriples: [String]\n    let extraCCFlags: [String]\n    let extraSwiftCFlags: [String]\n    let extraCXXFlags: [String]\n    let extraLinkerFlags: [String]\n}\n\n/// Represents v3 schema of `destination.json` files used for cross-compilation.\nstruct SerializedDestinationV3: Decodable {\n    struct TripleProperties: Codable {\n        /// Path relative to `destination.json` containing SDK root.\n        var sdkRootPath: String\n\n        /// Path relative to `destination.json` containing Swift resources for dynamic linking.\n        var swiftResourcesPath: String?\n\n        /// Path relative to `destination.json` containing Swift resources for static linking.\n        var swiftStaticResourcesPath: String?\n\n        /// Array of paths relative to `destination.json` containing headers.\n        var includeSearchPaths: [String]?\n\n        /// Array of paths relative to `destination.json` containing libraries.\n        var librarySearchPaths: [String]?\n\n        /// Array of paths relative to `destination.json` containing toolset files.\n        var toolsetPaths: [String]?\n    }\n\n    /// Mapping of triple strings to corresponding properties of such run-time triple.\n    let runTimeTriples: [String: TripleProperties]\n}\n\n/// Represents v4 schema of `swift-sdk.json` (previously `destination.json`) files used for cross-compilation.\nstruct SwiftSDKMetadataV4: Decodable {\n    struct TripleProperties: Codable {\n        /// Path relative to `swift-sdk.json` containing SDK root.\n        var sdkRootPath: String?\n\n        /// Path relative to `swift-sdk.json` containing Swift resources for dynamic linking.\n        var swiftResourcesPath: String?\n\n        /// Path relative to `swift-sdk.json` containing Swift resources for static linking.\n        var swiftStaticResourcesPath: String?\n\n        /// Array of paths relative to `swift-sdk.json` containing headers.\n        var includeSearchPaths: [String]?\n\n        /// Array of paths relative to `swift-sdk.json` containing libraries.\n        var librarySearchPaths: [String]?\n\n        /// Array of paths relative to `swift-sdk.json` containing toolset files.\n        var toolsetPaths: [String]?\n    }\n\n    /// Mapping of triple strings to corresponding properties of such target triple.\n    let targetTriples: [String: TripleProperties]\n}\n\nextension Optional where Wrapped == Basics.AbsolutePath {\n    fileprivate var configurationString: String {\n        self?.pathString ?? \"not set\"\n    }\n}\n\nextension Optional where Wrapped == [Basics.AbsolutePath] {\n    fileprivate var configurationString: String {\n        self?.map(\\.pathString).description ?? \"not set\"\n    }\n}\n\nextension SwiftSDK.PathsConfiguration: CustomStringConvertible where Path == Basics.AbsolutePath {\n    public var description: String {\n        \"\"\"\n        sdkRootPath: \\(sdkRootPath.configurationString)\n        swiftResourcesPath: \\(swiftResourcesPath.configurationString)\n        swiftStaticResourcesPath: \\(swiftStaticResourcesPath.configurationString)\n        includeSearchPaths: \\(includeSearchPaths.configurationString)\n        librarySearchPaths: \\(librarySearchPaths.configurationString)\n        toolsetPaths: \\(toolsetPaths.configurationString)\n        \"\"\"\n    }\n}\n\nextension Basics.AbsolutePath {\n    fileprivate init(validating string: String, relativeTo basePath: Basics.AbsolutePath?) throws {\n        if let basePath {\n            try self.init(validating: string, relativeTo: basePath)\n        } else {\n            try self.init(validating: string)\n        }\n    }\n}\n\n// TODO: Move anything to do with the SDKSettings here\npublic struct SDKSettings: Codable {\n    public let CanonicalName: String\n}\n"
  },
  {
    "path": "Sources/PackageModel/SwiftSDKs/SwiftSDKBundle.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nimport struct Foundation.URL\nimport protocol TSCBasic.FileSystem\nimport struct TSCBasic.RegEx\n\n/// Represents an `.artifactbundle` on the filesystem that contains a Swift SDK.\npublic struct SwiftSDKBundle {\n    public struct Variant: Equatable {\n        let metadata: ArtifactsArchiveMetadata.Variant\n        let swiftSDKs: [SwiftSDK]\n    }\n\n    // Path to the bundle root directory.\n    public let path: AbsolutePath\n\n    /// Mapping of artifact IDs to variants available for a corresponding artifact.\n    public internal(set) var artifacts = [String: [Variant]]()\n\n    /// Name of the Swift SDK bundle that can be used to distinguish it from other bundles.\n    public var name: String { path.basename }\n}\n\nextension SwiftSDKBundle.Variant {\n    /// Whether the given host triple is supported by this SDK variant\n    internal func isSupporting(hostTriple: Triple) -> Bool {\n        guard let supportedTriples = metadata.supportedTriples else {\n            // No supportedTriples means the SDK can be universally usable\n            return true\n        }\n        return supportedTriples.contains(where: { variantTriple in\n            hostTriple.isRuntimeCompatible(with: variantTriple)\n        })\n    }\n}\n\nextension [SwiftSDKBundle] {\n    /// Select a Swift SDK with a given artifact ID from a `self` array of available Swift SDKs.\n    /// - Parameters:\n    ///   - id: artifact ID of the Swift SDK to look up.\n    ///   - hostTriple: triple of the machine on which the Swift SDK is building.\n    ///   - targetTriple: triple of the machine for which the Swift SDK is building.\n    /// - Returns: ``SwiftSDK`` value with a given artifact ID, `nil` if none found.\n    public func selectSwiftSDK(id: String, hostTriple: Triple?, targetTriple: Triple) -> SwiftSDK? {\n        for bundle in self {\n            for (artifactID, variants) in bundle.artifacts {\n                guard artifactID == id else {\n                    continue\n                }\n\n                for variant in variants {\n                    if let hostTriple {\n                        guard variant.isSupporting(hostTriple: hostTriple) else {\n                            continue\n                        }\n                    }\n\n                    return variant.swiftSDKs.first { $0.targetTriple == targetTriple }\n                }\n            }\n        }\n\n        return nil\n    }\n\n    /// Select Swift SDKs matching a given selector and host triple from a `self` array of available Swift SDKs.\n    /// - Parameters:\n    ///   - selector: either an artifact ID or target triple to filter with.\n    ///   - hostTriple: triple of the host building with these Swift SDKs.\n    ///   - observabilityScope: observability scope to log warnings about multiple matches.\n    /// - Returns: ``SwiftSDK`` value matching `query` either by artifact ID or target triple, `nil` if none found.\n    func selectSwiftSDK(\n        matching selector: String,\n        hostTriple: Triple,\n        observabilityScope: ObservabilityScope\n    ) -> SwiftSDK? {\n        var matchedByID: (path: AbsolutePath, variant: SwiftSDKBundle.Variant, swiftSDK: SwiftSDK)?\n        var matchedByTriple: (path: AbsolutePath, variant: SwiftSDKBundle.Variant, swiftSDK: SwiftSDK)?\n\n        for bundle in self {\n            for (artifactID, variants) in bundle.artifacts {\n                for variant in variants {\n                    guard variant.isSupporting(hostTriple: hostTriple) else { continue }\n\n                    for swiftSDK in variant.swiftSDKs {\n                        if artifactID == selector {\n                            if let matchedByID {\n                                observabilityScope.emit(\n                                    warning:\n                                    \"\"\"\n                                    multiple Swift SDKs match ID `\\(artifactID)` and host triple \\(\n                                        hostTriple.tripleString\n                                    ), selected one at \\(\n                                        matchedByID.path.appending(matchedByID.variant.metadata.path)\n                                    )\n                                    \"\"\"\n                                )\n                            } else {\n                                matchedByID = (bundle.path, variant, swiftSDK)\n                            }\n                        }\n\n                        if swiftSDK.targetTriple?.tripleString == selector {\n                            if let matchedByTriple {\n                                observabilityScope.emit(\n                                    warning:\n                                    \"\"\"\n                                    multiple Swift SDKs match target triple `\\(selector)` and host triple \\(\n                                        hostTriple.tripleString\n                                    ), selected one at \\(\n                                        matchedByTriple.path.appending(matchedByTriple.variant.metadata.path)\n                                    )\n                                    \"\"\"\n                                )\n                            } else {\n                                matchedByTriple = (bundle.path, variant, swiftSDK)\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        if let matchedByID, let matchedByTriple, matchedByID != matchedByTriple {\n            observabilityScope.emit(\n                warning:\n                \"\"\"\n                multiple Swift SDKs match the query `\\(selector)` and host triple \\(\n                    hostTriple.tripleString\n                ), selected one at \\(matchedByID.path.appending(matchedByID.variant.metadata.path))\n                \"\"\"\n            )\n        }\n\n        return matchedByID?.swiftSDK ?? matchedByTriple?.swiftSDK\n    }\n\n    public var sortedArtifactIDs: [String] {\n        self.flatMap(\\.artifacts.keys).sorted()\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/SwiftSDKs/SwiftSDKBundleStore.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// FIXME: can't write `import actor Basics.HTTPClient`, importing the whole module because of that :(\n@_spi(SwiftPMInternal)\nimport Basics\nimport struct Foundation.URL\nimport protocol TSCBasic.FileSystem\nimport struct TSCBasic.RegEx\nimport protocol TSCUtility.ProgressAnimationProtocol\n\npublic final class SwiftSDKBundleStore {\n    public enum Output: Equatable, CustomStringConvertible {\n        case downloadStarted(URL)\n        case downloadFinishedSuccessfully(URL)\n        case verifyingChecksum\n        case checksumValid\n        case unpackingArchive(bundlePathOrURL: String)\n        case installationSuccessful(bundlePathOrURL: String, bundleName: String)\n\n        public var description: String {\n            switch self {\n            case let .downloadStarted(url):\n                return \"Downloading a Swift SDK bundle archive from `\\(url)`...\"\n            case let .downloadFinishedSuccessfully(url):\n                return \"Swift SDK bundle archive successfully downloaded from `\\(url)`.\"\n            case .verifyingChecksum:\n                return \"Verifying if checksum of the downloaded archive is valid...\"\n            case .checksumValid:\n                return \"Downloaded archive has a valid checksum.\"\n            case let .installationSuccessful(bundlePathOrURL, bundleName):\n                return \"Swift SDK bundle at `\\(bundlePathOrURL)` successfully installed as \\(bundleName).\"\n            case let .unpackingArchive(bundlePathOrURL):\n                return \"Swift SDK bundle at `\\(bundlePathOrURL)` is assumed to be an archive, unpacking...\"\n            }\n        }\n    }\n\n    enum Error: Swift.Error, CustomStringConvertible {\n        case noMatchingSwiftSDK(selector: String, hostTriple: Triple)\n\n        var description: String {\n            switch self {\n            case let .noMatchingSwiftSDK(selector, hostTriple):\n                return \"\"\"\n                No Swift SDK found matching query `\\(selector)` and host triple \\\n                `\\(hostTriple.tripleString)`. Use `swift sdk list` command to see \\\n                available Swift SDKs.\n                \"\"\"\n            }\n        }\n    }\n\n    /// Directory in which Swift SDKs bundles are stored.\n    let swiftSDKsDirectory: AbsolutePath\n\n    /// `usr/bin` directory of the \"root\" toolchain that includes this currently running SwiftPM instance.\n    let hostToolchainBinDir: AbsolutePath\n\n    /// File system instance used for reading from and writing to SDK bundles stored on it.\n    let fileSystem: any FileSystem\n\n    /// Observability scope used for logging.\n    let observabilityScope: ObservabilityScope\n\n    /// Closure invoked for output produced by this store during its operation.\n    private let outputHandler: (Output) -> Void\n\n    /// Progress animation used for downloading SDK bundles.\n    private let downloadProgressAnimation: ProgressAnimationProtocol?\n\n    public init(\n        swiftSDKsDirectory: AbsolutePath,\n        hostToolchainBinDir: AbsolutePath,\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope,\n        outputHandler: @escaping (Output) -> Void,\n        downloadProgressAnimation: ProgressAnimationProtocol? = nil\n    ) {\n        self.swiftSDKsDirectory = swiftSDKsDirectory\n        self.hostToolchainBinDir = hostToolchainBinDir\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n        self.outputHandler = outputHandler\n        self.downloadProgressAnimation = downloadProgressAnimation\n    }\n\n    /// An array of valid Swift SDK bundles stored in ``SwiftSDKBundleStore//swiftSDKsDirectory``.\n    public var allValidBundles: [SwiftSDKBundle] {\n        get throws {\n            // Get absolute paths to available Swift SDK bundles.\n            try self.fileSystem.getDirectoryContents(swiftSDKsDirectory).filter {\n                $0.hasSuffix(BinaryModule.Kind.artifactsArchive(types: []).fileExtension)\n            }.map {\n                self.swiftSDKsDirectory.appending(components: [$0])\n            }.compactMap {\n                do {\n                    // Enumerate available bundles and parse manifests for each of them, then validate supplied\n                    // Swift SDKs.\n                    return try self.parseAndValidate(bundlePath: $0)\n                } catch {\n                    observabilityScope.emit(\n                        warning: \"Couldn't parse `info.json` manifest of a Swift SDK bundle at \\($0)\",\n                        underlyingError: error\n                    )\n                    return nil\n                }\n            }\n        }\n    }\n\n    /// Select a Swift SDK matching a given query and host triple from all Swift SDKs available in\n    /// ``SwiftSDKBundleStore//swiftSDKsDirectory``.\n    /// - Parameters:\n    ///   - query: either an artifact ID or target triple to filter with.\n    ///   - hostTriple: triple of the host building with these Swift SDKs.\n    /// - Returns: ``SwiftSDK`` value matching `query` either by artifact ID or target triple, `nil` if none found.\n    public func selectBundle(\n        matching selector: String,\n        hostTriple: Triple\n    ) throws -> SwiftSDK {\n        let validBundles = try self.allValidBundles\n\n        guard !validBundles.isEmpty else {\n            throw StringError(\n                \"No valid Swift SDK bundles found at \\(self.swiftSDKsDirectory).\"\n            )\n        }\n\n        guard var selectedSwiftSDKs = validBundles.selectSwiftSDK(\n            matching: selector,\n            hostTriple: hostTriple,\n            observabilityScope: self.observabilityScope\n        ) else {\n            throw Error.noMatchingSwiftSDK(selector: selector, hostTriple: hostTriple)\n        }\n\n        selectedSwiftSDKs.applyPathCLIOptions()\n\n        return selectedSwiftSDKs\n    }\n\n    /// Installs a Swift SDK bundle from a given path or URL to ``SwiftSDKBundleStore//swiftSDKsDirectory``.\n    /// - Parameters:\n    ///   - bundlePathOrURL: A string passed on the command line, which is either an absolute or relative to a current\n    ///   working directory path, or a URL to a Swift SDK artifact bundle.\n    ///   - archiver: Archiver instance to use for extracting bundle archives.\n    public func install(\n        bundlePathOrURL: String,\n        checksum: String? = nil,\n        _ archiver: any Archiver,\n        _ httpClient: HTTPClient = .init(),\n        hasher: ((_ archivePath: AbsolutePath) throws -> String)? = nil\n    ) async throws {\n        let bundleName = try await withTemporaryDirectory(fileSystem: self.fileSystem, removeTreeOnDeinit: true) { temporaryDirectory in\n            let bundlePath: AbsolutePath\n\n            if\n                let bundleURL = URL(string: bundlePathOrURL),\n                let scheme = bundleURL.scheme,\n                scheme == \"http\" || scheme == \"https\"\n            {\n                guard let checksum, let hasher else {\n                    throw SwiftSDKError.checksumNotProvided(bundleURL)\n                }\n\n                let bundleName: String\n                let fileNameComponent = bundleURL.lastPathComponent\n                if archiver.isFileSupported(fileNameComponent) {\n                    bundleName = fileNameComponent\n                } else {\n                    // Assume that the bundle is a tarball if it doesn't have a recognized extension.\n                    bundleName = \"bundle.tar.gz\"\n                }\n                let downloadedBundlePath = temporaryDirectory.appending(component: bundleName)\n\n                var request = HTTPClientRequest.download(\n                    url: bundleURL,\n                    fileSystem: self.fileSystem,\n                    destination: downloadedBundlePath\n                )\n                request.options.validResponseCodes = [200]\n\n                self.outputHandler(.downloadStarted(bundleURL))\n\n                _ = try await httpClient.execute(\n                    request,\n                    observabilityScope: self.observabilityScope,\n                    progress: { step, total in\n                        guard let progressAnimation = self.downloadProgressAnimation else {\n                            return\n                        }\n                        let step = step > Int.max ? Int.max : Int(step)\n                        let total = total.map { $0 > Int.max ? Int.max : Int($0) } ?? step\n                        progressAnimation.update(\n                          step: step,\n                          total: total,\n                          text: \"Downloading \\(bundleURL.lastPathComponent)\"\n                        )\n                    }\n                )\n                self.downloadProgressAnimation?.complete(success: true)\n\n                self.outputHandler(.downloadFinishedSuccessfully(bundleURL))\n\n                self.outputHandler(.verifyingChecksum)\n                let computedChecksum = try hasher(downloadedBundlePath)\n                guard computedChecksum == checksum else {\n                    throw SwiftSDKError.checksumInvalid(computed: computedChecksum, provided: checksum)\n                }\n                self.outputHandler(.checksumValid)\n\n                bundlePath = downloadedBundlePath\n            } else if\n                let cwd: AbsolutePath = self.fileSystem.currentWorkingDirectory,\n                let originalBundlePath = try? AbsolutePath(validating: bundlePathOrURL, relativeTo: cwd)\n            {\n                bundlePath = originalBundlePath\n            } else {\n                throw SwiftSDKError.invalidPathOrURL(bundlePathOrURL)\n            }\n\n            return try await self.installIfValid(\n                bundlePathOrURL: bundlePathOrURL,\n                validatedBundlePath: bundlePath,\n                temporaryDirectory: temporaryDirectory,\n                archiver: archiver\n            )\n        }.value\n\n        self.outputHandler(.installationSuccessful(bundlePathOrURL: bundlePathOrURL, bundleName: bundleName))\n    }\n\n    /// Unpacks a Swift SDK bundle if it has an archive extension in its filename.\n    /// - Parameters:\n    ///   - bundlePath: Absolute path to a Swift SDK bundle to unpack if needed.\n    ///   - temporaryDirectory: Absolute path to a temporary directory in which the bundle can be unpacked if needed.\n    ///   - archiver: Archiver instance to use for extracting bundle archives.\n    /// - Returns: Path to an unpacked Swift SDK bundle if unpacking is needed, value of `bundlePath` is returned\n    /// otherwise.\n    private func unpackIfNeeded(\n        bundlePathOrURL: String,\n        validatedBundlePath bundlePath: AbsolutePath,\n        temporaryDirectory: AbsolutePath,\n        _ archiver: any Archiver\n    ) async throws -> AbsolutePath {\n        // If there's no archive extension on the bundle name, assuming it's not archived and returning the same path.\n        guard !bundlePath.pathString.hasSuffix(\".\\(artifactBundleExtension)\") else {\n            return bundlePath\n        }\n\n        self.outputHandler(.unpackingArchive(bundlePathOrURL: bundlePathOrURL))\n        let extractionResultsDirectory = temporaryDirectory.appending(\"extraction-results\")\n        try self.fileSystem.createDirectory(extractionResultsDirectory)\n\n        try await archiver.extract(from: bundlePath, to: extractionResultsDirectory)\n\n        guard let bundleName = try fileSystem.getDirectoryContents(extractionResultsDirectory).first(where: {\n            $0.hasSuffix(\".\\(artifactBundleExtension)\") &&\n                fileSystem.isDirectory(extractionResultsDirectory.appending($0))\n        }) else {\n            throw SwiftSDKError.invalidBundleArchive(bundlePath)\n        }\n\n        let installedBundlePath = swiftSDKsDirectory.appending(component: bundleName)\n        guard !self.fileSystem.exists(installedBundlePath) else {\n            throw SwiftSDKError.swiftSDKBundleAlreadyInstalled(bundleName: bundleName)\n        }\n\n        return extractionResultsDirectory.appending(component: bundleName)\n    }\n\n    /// Installs an unpacked Swift SDK bundle to a Swift SDK installation directory.\n    /// - Parameters:\n    ///   - bundlePath: absolute path to an unpacked Swift SDK bundle directory.\n    ///   - temporaryDirectory: Temporary directory to use if the bundle is an archive that needs extracting.\n    ///   - archiver: Archiver instance to use for extracting bundle archives.\n    /// - Returns: Name of the bundle installed.\n    private func installIfValid(\n        bundlePathOrURL: String,\n        validatedBundlePath: AbsolutePath,\n        temporaryDirectory: AbsolutePath,\n        archiver: any Archiver\n    ) async throws -> String {\n        #if os(macOS)\n        // Check the quarantine attribute on bundles downloaded manually in the browser.\n        guard !self.fileSystem.hasAttribute(.quarantine, validatedBundlePath) else {\n            throw SwiftSDKError.quarantineAttributePresent(bundlePath: validatedBundlePath)\n        }\n        #endif\n\n        let unpackedBundlePath = try await self.unpackIfNeeded(\n            bundlePathOrURL: bundlePathOrURL,\n            validatedBundlePath: validatedBundlePath,\n            temporaryDirectory: temporaryDirectory,\n            archiver\n        )\n\n        guard\n            self.fileSystem.isDirectory(unpackedBundlePath),\n            let bundleName = unpackedBundlePath.components.last\n        else {\n            throw SwiftSDKError.pathIsNotDirectory(validatedBundlePath)\n        }\n\n        let installedBundlePath = self.swiftSDKsDirectory.appending(component: bundleName)\n\n        let validatedBundle = try self.parseAndValidate(bundlePath: unpackedBundlePath)\n        let newArtifactIDs = validatedBundle.artifacts.keys\n\n        let installedBundles = try self.allValidBundles\n\n        for installedBundle in installedBundles {\n            for artifactID in installedBundle.artifacts.keys {\n                guard !newArtifactIDs.contains(artifactID) else {\n                    throw SwiftSDKError.swiftSDKArtifactAlreadyInstalled(\n                        installedBundleName: installedBundle.name,\n                        newBundleName: validatedBundle.name,\n                        artifactID: artifactID\n                    )\n                }\n            }\n        }\n\n        try self.fileSystem.copy(from: unpackedBundlePath, to: installedBundlePath)\n\n        return bundleName\n    }\n\n    /// Parses metadata of an `.artifactbundle` and validates it as a bundle containing\n    /// cross-compilation Swift SDKs.\n    /// - Parameters:\n    ///   - bundlePath: path to the bundle root directory.\n    /// - Returns: Validated ``SwiftSDKBundle`` containing validated ``SwiftSDK`` values for\n    /// each artifact and its variants.\n    private func parseAndValidate(bundlePath: AbsolutePath) throws -> SwiftSDKBundle {\n        let parsedManifest = try ArtifactsArchiveMetadata.parse(\n            fileSystem: self.fileSystem,\n            rootPath: bundlePath\n        )\n\n        return try self.validateSwiftSDKBundle(\n            bundlePath: bundlePath,\n            bundleManifest: parsedManifest\n        )\n    }\n\n    private func validateSwiftSDKBundle(\n        bundlePath: AbsolutePath,\n        bundleManifest: ArtifactsArchiveMetadata\n    ) throws -> SwiftSDKBundle {\n        var result = SwiftSDKBundle(path: bundlePath)\n\n        for (artifactID, artifactMetadata) in bundleManifest.artifacts {\n            if artifactMetadata.type == .crossCompilationDestination {\n                self.observabilityScope.emit(\n                    warning: \"\"\"\n                    `crossCompilationDestination` bundle metadata value used for `\\(artifactID)` is deprecated, \\\n                    use `swiftSDK` instead.\n                    \"\"\"\n                )\n            } else {\n                guard artifactMetadata.type == .swiftSDK else { continue }\n            }\n\n            var variants = [SwiftSDKBundle.Variant]()\n\n            for variantMetadata in artifactMetadata.variants {\n                var variantConfigurationPath = bundlePath\n                    .appending(variantMetadata.path)\n\n                if variantConfigurationPath.extension != \".json\" &&\n                        self.fileSystem.isDirectory(variantConfigurationPath) {\n                    variantConfigurationPath = variantConfigurationPath.appending(\"swift-sdk.json\")\n                }\n\n                guard self.fileSystem.exists(variantConfigurationPath) else {\n                    self.observabilityScope.emit(\n                        .warning(\n                            \"\"\"\n                            Swift SDK metadata file not found at \\(\n                                variantConfigurationPath\n                            ) for a variant of artifact \\(artifactID)\n                            \"\"\"\n                        )\n                    )\n\n                    continue\n                }\n\n                do {\n                    let swiftSDKs = try SwiftSDK.decode(\n                        fromFile: variantConfigurationPath,\n                        hostToolchainBinDir: self.hostToolchainBinDir,\n                        fileSystem: fileSystem,\n                        observabilityScope: observabilityScope\n                    )\n\n                    variants.append(.init(metadata: variantMetadata, swiftSDKs: swiftSDKs))\n                } catch {\n                    observabilityScope.emit(\n                        warning: \"Couldn't parse Swift SDK artifact metadata at \\(variantConfigurationPath)\",\n                        underlyingError: error\n                    )\n                }\n            }\n\n            result.artifacts[artifactID] = variants\n        }\n\n        return result\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/SwiftSDKs/SwiftSDKConfigurationStore.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nimport class Foundation.JSONDecoder\nimport class Foundation.JSONEncoder\n\n/// Storage for configuration properties of Swift SDKs.\npublic final class SwiftSDKConfigurationStore {\n    /// Triple of the machine on which SwiftPM is running.\n    private let hostTriple: Triple\n\n    /// Path to the directory in which Swift SDKs and their configuration are stored. Usually\n    /// `~/.swiftpm/swift-sdks` or a directory to which `~/.swiftpm/swift-sdks` symlinks to.\n    private let swiftSDKsDirectoryPath: AbsolutePath\n\n    /// Path to the directory in which Swift SDK configuration files are stored.\n    private let configurationDirectoryPath: AbsolutePath\n\n    /// File system that stores Swift SDK configuration and contains\n    /// ``SwiftSDKConfigurationStore//configurationDirectoryPath``.\n    private let fileSystem: FileSystem\n\n    // An observability scope on which warnings can be reported if any appear.\n    private let swiftSDKBundleStore: SwiftSDKBundleStore\n\n    /// Encoder used for encoding updated configuration to be written to ``SwiftSDKConfigurationStore//fileSystem``.\n    private let encoder: JSONEncoder\n\n    /// Encoder used for reading existing configuration from  ``SwiftSDKConfigurationStore//fileSystem``.\n    private let decoder: JSONDecoder\n\n    /// Initializes a store for configuring Swift SDKs.\n    /// - Parameters:\n    ///   - hostTriple: Triple of the machine on which SwiftPM is running.\n    ///   - swiftSDKsDirectoryPath: Path to the directory in which Swift SDKs and their configuration are\n    ///   stored. Usually `~/.swiftpm/swift-sdks` or a directory to which `~/.swiftpm/swift-sdks` symlinks to.\n    ///   If this directory doesn't exist, an error will be thrown.\n    ///   - fileSystem: file system on which `swiftSDKsDirectoryPath` exists.\n    ///   - observabilityScope: an observability scope on which warnings can be reported if any appear.\n    public init(\n        hostTimeTriple: Triple,\n        swiftSDKBundleStore: SwiftSDKBundleStore\n    ) throws {\n        let configurationDirectoryPath = swiftSDKBundleStore.swiftSDKsDirectory.appending(component: \"configuration\")\n\n        let fileSystem = swiftSDKBundleStore.fileSystem\n        if fileSystem.exists(configurationDirectoryPath) {\n            guard fileSystem.isDirectory(configurationDirectoryPath) else {\n                throw SwiftSDKError.pathIsNotDirectory(configurationDirectoryPath)\n            }\n        } else {\n            try fileSystem.createDirectory(configurationDirectoryPath)\n        }\n\n        self.hostTriple = hostTimeTriple\n        self.swiftSDKsDirectoryPath = swiftSDKBundleStore.swiftSDKsDirectory\n        self.configurationDirectoryPath = configurationDirectoryPath\n        self.fileSystem = fileSystem\n        self.swiftSDKBundleStore = swiftSDKBundleStore\n        self.encoder = JSONEncoder.makeWithDefaults(prettified: true)\n        self.decoder = JSONDecoder.makeWithDefaults()\n    }\n\n    public func updateConfiguration(\n        sdkID: String,\n        swiftSDK: SwiftSDK\n    ) throws {\n        let (targetTriple, properties) = try swiftSDK.serialized\n\n        let configurationPath = configurationDirectoryPath.appending(\n            component: \"\\(sdkID)_\\(targetTriple).json\"\n        )\n\n        try encoder.encode(path: configurationPath, fileSystem: fileSystem, properties)\n    }\n\n    private func swiftSDKs(for id: String) throws -> [SwiftSDK] {\n        for bundle in try self.swiftSDKBundleStore.allValidBundles {\n            for (artifactID, variants) in bundle.artifacts {\n                guard artifactID == id else {\n                    continue\n                }\n\n                for variant in variants {\n                    return variant.swiftSDKs\n                }\n            }\n        }\n\n        return []\n    }\n\n    public func readConfiguration(\n        sdkID: String,\n        targetTriple: Triple\n    ) throws -> SwiftSDK? {\n        let configurationPath = configurationDirectoryPath.appending(\n            component: \"\\(sdkID)_\\(targetTriple.tripleString).json\"\n        )\n\n        let swiftSDKs = try self.swiftSDKBundleStore.allValidBundles\n\n        guard var swiftSDK = swiftSDKs.selectSwiftSDK(\n            id: sdkID,\n            hostTriple: nil,\n            targetTriple: targetTriple\n        ) else {\n            return nil\n        }\n\n        if fileSystem.isFile(configurationPath) {\n            let properties = try decoder.decode(\n                path: configurationPath,\n                fileSystem: fileSystem,\n                as: SwiftSDKMetadataV4.TripleProperties.self\n            )\n\n            swiftSDK.pathsConfiguration.merge(\n                with: try SwiftSDK(\n                    targetTriple: targetTriple,\n                    properties: properties\n                ).pathsConfiguration\n            )\n        }\n\n        return swiftSDK\n    }\n\n    /// Resets configuration for identified target triple.\n    /// - Parameters:\n    ///   - sdkID: ID of the Swift SDK to operate on.\n    ///   - tripleString: run-time triple for which the properties should be reset.\n    /// - Returns: `true` if custom configuration was successfully removed, `false` if no custom configuration existed.\n    public func resetConfiguration(\n        sdkID: String,\n        targetTriple triple: Triple\n    ) throws -> Bool {\n        let configurationPath = configurationDirectoryPath.appending(\n            component: \"\\(sdkID)_\\(triple.tripleString).json\"\n        )\n\n        guard fileSystem.isFile(configurationPath) else {\n            return false\n        }\n\n        try fileSystem.removeFileTree(configurationPath)\n        return true\n    }\n\n    /// Configures the specified Swift SDK and identified target triple with the configuration parameter.\n    /// - Parameters:\n    ///   - sdkID: ID of the Swift SDK to operate on.\n    ///   - tripleString: run-time triple for which the properties should be configured, or nil to configure all triples for the Swift SDK\n    ///   - showConfiguration: if true, simply print the current configuration for the target triple(s)\n    ///   - resetConfiguration: if true, reset the configuration for the target triple(s)\n    ///   - config: the configuration parameters to set for for the target triple(s)\n    /// - Returns: `true` if custom configuration was successful, `false` if no configuration was performed.\n    package func configure(\n        sdkID: String,\n        targetTriple: String?,\n        showConfiguration: Bool,\n        resetConfiguration: Bool,\n        config: SwiftSDK.PathsConfiguration<String>\n    ) throws -> Bool {\n        let targetTriples: [Triple]\n        if let targetTriple = targetTriple {\n            targetTriples = try [Triple(targetTriple)]\n        } else {\n            // when `targetTriple` is unspecified, configure every triple for the SDK\n            let validBundles = try self.swiftSDKs(for: sdkID)\n            targetTriples = validBundles.compactMap(\\.targetTriple)\n            if targetTriples.isEmpty {\n                throw SwiftSDKError.swiftSDKNotFound(\n                    artifactID: sdkID,\n                    hostTriple: hostTriple,\n                    targetTriple: nil\n                )\n            }\n        }\n\n        for targetTriple in targetTriples {\n            guard let swiftSDK = try self.readConfiguration(\n                sdkID: sdkID,\n                targetTriple: targetTriple\n            ) else {\n                throw SwiftSDKError.swiftSDKNotFound(\n                    artifactID: sdkID,\n                    hostTriple: hostTriple,\n                    targetTriple: targetTriple\n                )\n            }\n\n            if showConfiguration {\n                print(swiftSDK.pathsConfiguration)\n                continue\n            }\n\n            if resetConfiguration {\n                if try !self.resetConfiguration(sdkID: sdkID, targetTriple: targetTriple) {\n                    swiftSDKBundleStore.observabilityScope.emit(\n                        warning: \"No configuration for Swift SDK `\\(sdkID)`\"\n                    )\n                } else {\n                    swiftSDKBundleStore.observabilityScope.emit(\n                        info: \"\"\"\n                        All configuration properties of Swift SDK `\\(sdkID)` for target triple \\\n                        `\\(targetTriple)` were successfully reset.\n                        \"\"\"\n                    )\n                }\n            } else {\n                var configuration = swiftSDK.pathsConfiguration\n                let updatedProperties = try configuration.merge(with: config, relativeTo: fileSystem.currentWorkingDirectory)\n\n                guard !updatedProperties.isEmpty else {\n                    swiftSDKBundleStore.observabilityScope.emit(\n                        error: \"\"\"\n                        No properties of Swift SDK `\\(sdkID)` for target triple `\\(targetTriple)` were updated \\\n                        since none were specified. Pass `--help` flag to see the list of all available properties.\n                        \"\"\"\n                    )\n                    return false\n                }\n\n                var swiftSDK = swiftSDK\n                swiftSDK.pathsConfiguration = configuration\n                swiftSDK.targetTriple = targetTriple\n                try self.updateConfiguration(sdkID: sdkID, swiftSDK: swiftSDK)\n\n                swiftSDKBundleStore.observabilityScope.emit(\n                    info: \"\"\"\n                    These properties of Swift SDK `\\(sdkID)` for target triple \\\n                    `\\(targetTriple)` were successfully updated: \\(updatedProperties.joined(separator: \", \")).\n                    \"\"\"\n                )\n            }\n\n            if swiftSDKBundleStore.observabilityScope.errorsReported {\n                return false\n            }\n        }\n\n        return true\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Toolchain+SupportedFeatures.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nimport enum TSCBasic.JSON\nimport protocol TSCBasic.JSONMappable\nimport TSCUtility\n\npublic enum SwiftCompilerFeature {\n    case optional(name: String, migratable: Bool, categories: [String], flagName: String)\n    case upcoming(name: String, migratable: Bool, categories: [String], enabledIn: SwiftLanguageVersion?)\n    case experimental(name: String, migratable: Bool, categories: [String])\n\n    public var optional: Bool {\n        switch self {\n        case .optional: true\n        case .upcoming, .experimental: false\n        }\n    }\n    public var upcoming: Bool {\n        switch self {\n        case .upcoming: true\n        case .optional, .experimental: false\n        }\n    }\n\n    public var experimental: Bool {\n        switch self {\n        case .optional, .upcoming: false\n        case .experimental: true\n        }\n    }\n\n    public var name: String {\n        switch self {\n        case .optional(name: let name, migratable: _, categories: _, flagName: _),\n                .upcoming(name: let name, migratable: _, categories: _, enabledIn: _),\n                .experimental(name: let name, migratable: _, categories: _):\n            name\n        }\n    }\n\n    public var migratable: Bool {\n        switch self {\n        case .optional(name: _, migratable: let migratable, categories: _, flagName: _),\n             .upcoming(name: _, migratable: let migratable, categories: _, enabledIn: _),\n             .experimental(name: _, migratable: let migratable, categories: _):\n            migratable\n        }\n    }\n\n    public var categories: [String] {\n        switch self {\n        case .optional(name: _, migratable: _, categories: let categories, flagName: _),\n             .upcoming(name: _, migratable: _, categories: let categories, enabledIn: _),\n             .experimental(name: _, migratable: _, categories: let categories):\n            categories\n        }\n    }\n}\n\nextension Toolchain {\n    public var supportsSupportedFeatures: Bool {\n        guard let features = try? swiftCompilerSupportedFeatures else {\n            return false\n        }\n        return !features.isEmpty\n    }\n\n    public var swiftCompilerSupportedFeatures: [SwiftCompilerFeature] {\n        get throws {\n            let compilerOutput: String\n            do {\n                let result = try AsyncProcess.popen(args: swiftCompilerPath.pathString, \"-print-supported-features\")\n                compilerOutput = try result.utf8Output().spm_chomp()\n            } catch {\n                throw InternalError(\"Failed to get supported features info (\\(error.interpolationDescription))\")\n            }\n\n            if compilerOutput.isEmpty {\n                return []\n            }\n\n            let parsedSupportedFeatures: JSON\n            do {\n                parsedSupportedFeatures = try JSON(string: compilerOutput)\n            } catch {\n                throw InternalError(\n                    \"Failed to parse supported features info (\\(error.interpolationDescription)).\\nRaw compiler output: \\(compilerOutput)\"\n                )\n            }\n\n            let features: JSON = try parsedSupportedFeatures.get(\"features\")\n\n            let optionalFeatures = (try? features.getArray(\"optional\")) ?? []\n\n            let optional: [SwiftCompilerFeature] = try optionalFeatures.map { json in\n                let name: String = try json.get(\"name\")\n                let categories: [String]? = try json.getArrayIfAvailable(\"categories\")\n                let migratable: Bool? = json.get(\"migratable\")\n                let flagName: String = try json.get(\"flag_name\")\n\n                return .optional(\n                    name: name,\n                    migratable: migratable ?? false,\n                    categories: categories ?? [name],\n                    flagName: flagName\n                )\n            }\n\n            let upcoming: [SwiftCompilerFeature] = try features.getArray(\"upcoming\").map {\n                let name: String = try $0.get(\"name\")\n                let categories: [String]? = try $0.getArrayIfAvailable(\"categories\")\n                let migratable: Bool? = $0.get(\"migratable\")\n\n                let mode: SwiftLanguageVersion?\n                decodeMode: do {\n                    // Try to decode a string or integer, but do not expect a\n                    // language mode to always be present.\n                    let versionString: String\n                    switch try? $0.getJSON(\"enabled_in\") {\n                    case let .int(int):\n                        versionString = String(int)\n                    case let .string(string):\n                        versionString = string\n                    default:\n                        mode = nil\n                        break decodeMode\n                    }\n\n                    mode = SwiftLanguageVersion(string: versionString)\n                    if mode == nil {\n                        throw InternalError(\"Unknown swift language mode: \\(versionString)\")\n                    }\n                }\n\n                return .upcoming(\n                    name: name,\n                    migratable: migratable ?? false,\n                    categories: categories ?? [name],\n                    enabledIn: mode\n                )\n            }\n\n            let experimental: [SwiftCompilerFeature] = try features.getArray(\"experimental\").map {\n                let name: String = try $0.get(\"name\")\n                let categories: [String]? = try $0.getArrayIfAvailable(\"categories\")\n                let migratable: Bool? = $0.get(\"migratable\")\n\n                return .experimental(\n                    name: name,\n                    migratable: migratable ?? false,\n                    categories: categories ?? [name]\n                )\n            }\n\n            return optional + upcoming + experimental\n        }\n    }\n}\n\nfileprivate extension JSON {\n    func getArrayIfAvailable<T: JSONMappable>(_ key: String) throws -> [T]? {\n        do {\n            return try get(key)\n        } catch MapError.missingKey(key) {\n            return nil\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Toolchain.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\npublic protocol Toolchain {\n    /// Path of the librarian.\n    var librarianPath: AbsolutePath { get }\n\n    /// Path of the `swiftc` compiler.\n    var swiftCompilerPath: AbsolutePath { get }\n\n    /// Path to `lib/swift`\n    var swiftResourcesPath: AbsolutePath? { get }\n\n    /// Path to `lib/swift_static`\n    var swiftStaticResourcesPath: AbsolutePath? { get }\n\n    /// Path containing the macOS Swift stdlib.\n    var macosSwiftStdlib: AbsolutePath { get throws }\n\n    /// An array of paths to search for headers and modules at compile time.\n    var includeSearchPaths: [AbsolutePath] { get }\n\n    /// An array of paths to search for libraries at link time.\n    var librarySearchPaths: [AbsolutePath] { get }\n\n    /// An array of paths to use with binaries produced by this toolchain at run time.\n    var runtimeLibraryPaths: [AbsolutePath] { get }\n\n    /// Configuration from the used toolchain.\n    var installedSwiftPMConfiguration: InstalledSwiftPMConfiguration { get }\n\n    /// The root path to the Swift SDK used by this toolchain.\n    var sdkRootPath: AbsolutePath? { get }\n\n    /// The manifest and library locations used by this toolchain.\n    var swiftPMLibrariesLocation: ToolchainConfiguration.SwiftPMLibrariesLocation { get }\n\n    /// Path to the Metal toolchain if available.\n    var metalToolchainPath: AbsolutePath? { get }\n\n    // Metal toolchain ID if available.\n    var metalToolchainId: String? { get }\n\n    /// Path of the `clang` compiler.\n    func getClangCompiler() throws -> AbsolutePath\n\n    // FIXME: This is a temporary API until index store is widely available in\n    // the OSS clang compiler. This API should not used for any other purpose.\n    /// Returns true if clang compiler's vendor is Apple and nil if unknown.\n    func _isClangCompilerVendorApple() throws -> Bool?\n    \n    /// Additional flags to be passed to the build tools.\n    var extraFlags: BuildFlags { get }\n\n    /// Additional flags to be passed to the C compiler.\n    @available(*, deprecated, message: \"use extraFlags.cCompilerFlags instead\")\n    var extraCCFlags: [String] { get }\n\n    /// Additional flags to be passed to the Swift compiler.\n    @available(*, deprecated, message: \"use extraFlags.swiftCompilerFlags instead\")\n    var extraSwiftCFlags: [String] { get }\n\n    /// Additional flags to be passed to the C++ compiler.\n    @available(*, deprecated, message: \"use extraFlags.cxxCompilerFlags instead\")\n    var extraCPPFlags: [String] { get }\n\n    var swiftSDK: SwiftSDK { get }\n}\n\nextension Toolchain {\n    public func _isClangCompilerVendorApple() throws -> Bool? {\n        return nil\n    }\n\n    public var hostLibDir: AbsolutePath {\n        get throws {\n            try Self.toolchainLibDir(swiftCompilerPath: self.swiftCompilerPath).appending(\n                components: [\"swift\", \"host\"]\n            )\n        }\n    }\n\n    public var macosSwiftStdlib: AbsolutePath {\n        get throws {\n            try Self.toolchainLibDir(swiftCompilerPath: self.swiftCompilerPath).appending(\n                components: [\"swift\", \"macosx\"]\n            )\n        }\n    }\n\n    /// Toolchain path that's given to Swift Build to determine whether the compiler needs to be overridden.\n    public var toolchainDir: AbsolutePath {\n        get throws {\n            let compilerPath = try resolveSymlinks(swiftCompilerPath)\n            let os = ProcessInfo.hostOperatingSystem\n            switch os {\n            case .windows, .macOS, .linux, .android:\n                return compilerPath\n                    .parentDirectory // bin\n                    .parentDirectory // usr\n                    .parentDirectory // <toolchain>\n            case .freebsd, .openbsd:\n                return compilerPath\n                    .parentDirectory // bin\n                    .parentDirectory // local\n                    .parentDirectory // usr\n                    .parentDirectory // <toolchain>\n            case .unknown:\n                throw UnknownToolchainLayout(os: os)\n            }\n        }\n    }\n\n    public var toolchainLibDir: AbsolutePath {\n        get throws {\n            // FIXME: Not sure if it's better to base this off of Swift compiler or our own binary.\n            try Self.toolchainLibDir(swiftCompilerPath: self.swiftCompilerPath)\n        }\n    }\n\n    /// Returns the appropriate Swift resources directory path.\n    ///\n    /// - Parameter static: Controls whether to use the static or dynamic\n    /// resources directory.\n    public func swiftResourcesPath(isStatic: Bool) -> AbsolutePath? {\n        isStatic ? swiftStaticResourcesPath : swiftResourcesPath\n    }\n\n    public var extraCCFlags: [String] {\n        extraFlags.cCompilerFlags.rawFlags\n    }\n\n    public var extraCPPFlags: [String] {\n        extraFlags.cxxCompilerFlags.rawFlags\n    }\n    \n    public var extraSwiftCFlags: [String] {\n        extraFlags.swiftCompilerFlags.rawFlags\n    }\n\n    package static func toolchainLibDir(swiftCompilerPath: AbsolutePath) throws -> AbsolutePath {\n        try AbsolutePath(validating: \"../../lib\", relativeTo: resolveSymlinks(swiftCompilerPath))\n    }\n}\n\nstruct UnknownToolchainLayout: Error, CustomStringConvertible {\n    let os: OperatingSystem\n    var description: String {\n        \"Unknown toolchain layout for host operating system: \\(os)\"\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/ToolchainConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// Toolchain configuration required for evaluation of swift code such as the manifests or plugins\n///\n/// These requirements are abstracted out to make it easier to add support for\n/// using the package manager with alternate toolchains in the future.\npublic struct ToolchainConfiguration {\n    /// The path of the librarian.\n    public var librarianPath: AbsolutePath\n\n    /// The path of the swift compiler.\n    public var swiftCompilerPath: AbsolutePath\n\n    /// Extra arguments to pass the Swift compiler (defaults to the empty string).\n    public var swiftCompilerFlags: [String]\n\n    /// Environment to pass to the Swift compiler (defaults to the inherited environment).\n    public var swiftCompilerEnvironment: Environment\n\n    /// SwiftPM library paths.\n    public var swiftPMLibrariesLocation: SwiftPMLibrariesLocation\n\n    /// The path to SDK root.\n    ///\n    /// If provided, it will be passed to the swift interpreter.\n    public var sdkRootPath: AbsolutePath?\n\n    /// Path to the XCTest utility.\n    ///\n    /// This is optional for example on macOS w/o Xcode.\n    public var xctestPath: AbsolutePath?\n\n    /// Path to the swift-testing utility.\n    /// Currently computed only for Windows.\n    public var swiftTestingPath: AbsolutePath?\n\n    /// Path to the Metal toolchain.\n    /// This is optional and only available on Darwin platforms.\n    public var metalToolchainPath: AbsolutePath?\n\n    /// Metal toolchain identifier\n    /// This is optional and only available on Darwin platforms.\n    public var metalToolchainId: String?\n\n    /// Creates the set of manifest resources associated with a `swiftc` executable.\n    ///\n    /// - Parameters:\n    ///     - librarianPath: The absolute path to the librarian\n    ///     - swiftCompilerPath: The absolute path of the associated swift compiler executable (`swiftc`).\n    ///     - swiftCompilerFlags: Extra flags to pass to the Swift compiler.\n    ///     - swiftCompilerEnvironment: Environment variables to pass to the Swift compiler.\n    ///     - swiftPMLibrariesRootPath: Custom path for SwiftPM libraries. Computed based on the compiler path by default.\n    ///     - sdkRootPath: Optional path to SDK root.\n    ///     - xctestPath: Optional path to XCTest.\n    ///     - swiftTestingPath: Optional path to swift-testing.\n    ///     - metalToolchainPath: Optional path to Metal toolchain.\n    public init(\n        librarianPath: AbsolutePath,\n        swiftCompilerPath: AbsolutePath,\n        swiftCompilerFlags: [String] = [],\n        swiftCompilerEnvironment: Environment = .current,\n        swiftPMLibrariesLocation: SwiftPMLibrariesLocation? = nil,\n        sdkRootPath: AbsolutePath? = nil,\n        xctestPath: AbsolutePath? = nil,\n        swiftTestingPath: AbsolutePath? = nil,\n        metalToolchainPath: AbsolutePath? = nil,\n        metalToolchainId: String? = nil\n    ) {\n        let swiftPMLibrariesLocation = swiftPMLibrariesLocation ?? {\n            return .init(swiftCompilerPath: swiftCompilerPath)\n        }()\n\n        self.librarianPath = librarianPath\n        self.swiftCompilerPath = swiftCompilerPath\n        self.swiftCompilerFlags = swiftCompilerFlags\n        self.swiftCompilerEnvironment = swiftCompilerEnvironment\n        self.swiftPMLibrariesLocation = swiftPMLibrariesLocation\n        self.sdkRootPath = sdkRootPath\n        self.xctestPath = xctestPath\n        self.swiftTestingPath = swiftTestingPath\n        self.metalToolchainPath = metalToolchainPath\n        self.metalToolchainId = metalToolchainId\n    }\n}\n\nextension ToolchainConfiguration {\n    public struct SwiftPMLibrariesLocation {\n        public var manifestLibraryPath: AbsolutePath\n        public var manifestModulesPath: AbsolutePath\n        public var pluginLibraryPath: AbsolutePath\n        public var pluginModulesPath: AbsolutePath\n\n        public init(\n            manifestLibraryPath: AbsolutePath,\n            manifestModulesPath: AbsolutePath? = nil,\n            manifestLibraryMinimumDeploymentTarget: PlatformVersion? = nil,\n            pluginLibraryPath: AbsolutePath,\n            pluginModulesPath: AbsolutePath? = nil,\n            pluginLibraryMinimumDeploymentTarget: PlatformVersion? = nil\n        ) {\n            #if os(macOS)\n            if let manifestLibraryMinimumDeploymentTarget {\n                self.manifestLibraryMinimumDeploymentTarget = manifestLibraryMinimumDeploymentTarget\n            } else if let manifestLibraryMinimumDeploymentTarget = try? MinimumDeploymentTarget.default.computeMinimumDeploymentTarget(of: Self.macOSManifestLibraryPath(for: manifestLibraryPath), platform: .macOS) {\n                self.manifestLibraryMinimumDeploymentTarget = manifestLibraryMinimumDeploymentTarget\n            } else {\n                self.manifestLibraryMinimumDeploymentTarget = nil\n            }\n\n            if let pluginLibraryMinimumDeploymentTarget {\n                self.pluginLibraryMinimumDeploymentTarget = pluginLibraryMinimumDeploymentTarget\n            } else if let pluginLibraryMinimumDeploymentTarget = try? MinimumDeploymentTarget.default.computeMinimumDeploymentTarget(of: Self.macOSPluginLibraryPath(for: pluginLibraryPath), platform: .macOS) {\n                self.pluginLibraryMinimumDeploymentTarget = pluginLibraryMinimumDeploymentTarget\n            } else {\n                self.pluginLibraryMinimumDeploymentTarget = nil\n            }\n            #else\n            precondition(manifestLibraryMinimumDeploymentTarget == nil && pluginLibraryMinimumDeploymentTarget == nil, \"deployment targets can only be specified on macOS\")\n            #endif\n\n            self.manifestLibraryPath = manifestLibraryPath\n            if let manifestModulesPath {\n                self.manifestModulesPath = manifestModulesPath\n            } else {\n                self.manifestModulesPath = manifestLibraryPath\n            }\n\n            self.pluginLibraryPath = pluginLibraryPath\n            if let pluginModulesPath {\n                self.pluginModulesPath = pluginModulesPath\n            } else {\n                self.pluginModulesPath = pluginLibraryPath\n            }\n        }\n\n        public init(root: AbsolutePath, manifestLibraryMinimumDeploymentTarget: PlatformVersion? = nil, pluginLibraryMinimumDeploymentTarget: PlatformVersion? = nil) {\n            self.init(\n                manifestLibraryPath: root.appending(\"ManifestAPI\"),\n                manifestLibraryMinimumDeploymentTarget: manifestLibraryMinimumDeploymentTarget,\n                pluginLibraryPath: root.appending(\"PluginAPI\"),\n                pluginLibraryMinimumDeploymentTarget: pluginLibraryMinimumDeploymentTarget\n            )\n        }\n\n        public init(swiftCompilerPath: AbsolutePath, manifestLibraryMinimumDeploymentTarget: PlatformVersion? = nil, pluginLibraryMinimumDeploymentTarget: PlatformVersion? = nil) {\n            let rootPath = swiftCompilerPath.parentDirectory.parentDirectory.appending(components: \"lib\", \"swift\", \"pm\")\n            self.init(root: rootPath,\n                      manifestLibraryMinimumDeploymentTarget: manifestLibraryMinimumDeploymentTarget,\n                      pluginLibraryMinimumDeploymentTarget: pluginLibraryMinimumDeploymentTarget)\n        }\n\n#if os(macOS)\n        public var manifestLibraryMinimumDeploymentTarget: PlatformVersion?\n        public var pluginLibraryMinimumDeploymentTarget: PlatformVersion?\n\n        private static func macOSManifestLibraryPath(for manifestAPI: AbsolutePath) -> AbsolutePath {\n            if manifestAPI.extension == \"framework\" {\n                return manifestAPI.appending(\"PackageDescription\")\n            } else {\n                // note: this is not correct for all platforms, but we only actually use it on macOS.\n                return manifestAPI.appending(\"libPackageDescription.dylib\")\n            }\n        }\n\n        public var macOSManifestLibraryPath: AbsolutePath {\n            return Self.macOSManifestLibraryPath(for: manifestLibraryPath)\n        }\n\n        private static func macOSPluginLibraryPath(for pluginAPI: AbsolutePath) -> AbsolutePath {\n            // if runtimePath is set to \"PackageFrameworks\" that means we could be developing SwiftPM in Xcode\n            // which produces a framework for dynamic package products.\n            if pluginAPI.extension == \"framework\" {\n                return pluginAPI.appending(\"PackagePlugin\")\n            } else {\n                // note: this is not correct for all platforms, but we only actually use it on macOS.\n                return pluginAPI.appending(\"libPackagePlugin.dylib\")\n            }\n        }\n\n        public var macOSPluginLibraryPath: AbsolutePath {\n            return Self.macOSPluginLibraryPath(for: pluginLibraryPath)\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/ToolsVersion.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\nimport struct TSCUtility.Version\n\n/// Tools version represents version of the Swift toolchain.\npublic struct ToolsVersion: Equatable, Hashable, Codable, Sendable {\n\n    public static let v3 = ToolsVersion(version: \"3.1.0\")\n    public static let v4 = ToolsVersion(version: \"4.0.0\")\n    public static let v4_2 = ToolsVersion(version: \"4.2.0\")\n    public static let v5 = ToolsVersion(version: \"5.0.0\")\n    public static let v5_2 = ToolsVersion(version: \"5.2.0\")\n    public static let v5_3 = ToolsVersion(version: \"5.3.0\")\n    public static let v5_4 = ToolsVersion(version: \"5.4.0\")\n    public static let v5_5 = ToolsVersion(version: \"5.5.0\")\n    public static let v5_6 = ToolsVersion(version: \"5.6.0\")\n    public static let v5_7 = ToolsVersion(version: \"5.7.0\")\n    public static let v5_8 = ToolsVersion(version: \"5.8.0\")\n    public static let v5_9 = ToolsVersion(version: \"5.9.0\")\n    public static let v5_10 = ToolsVersion(version: \"5.10.0\")\n    public static let v6_0 = ToolsVersion(version: \"6.0.0\")\n    public static let v6_1 = ToolsVersion(version: \"6.1.0\")\n    public static let v6_2 = ToolsVersion(version: \"6.2.0\")\n    public static let v6_3 = ToolsVersion(version: \"6.3.0\")\n    public static let vNext = ToolsVersion(version: \"999.0.0\")\n\n    /// The current tools version in use.\n    public static let current = ToolsVersion(string:\n        \"\\(SwiftVersion.current.major).\" +\n        \"\\(SwiftVersion.current.minor).\" +\n        \"\\(SwiftVersion.current.patch)\")!\n\n    /// The minimum tools version that is required by the package manager.\n    public static let minimumRequired: ToolsVersion = .v4\n\n    /// Regex pattern to parse tools version. The format is SemVer 2.0 with an\n    /// addition that specifying the patch version is optional.\n    static let toolsVersionRegex = try! NSRegularExpression(\n        pattern: #\"\"\"\n                 ^\n                 (\\d+)\\.(\\d+)(?:\\.(\\d+))?\n                 (\n                     \\-[A-Za-z\\d]+(?:\\.[A-Za-z\\d]+)*\n                 )?\n                 (\n                     \\+[A-Za-z\\d]+(?:\\.[A-Za-z\\d]+)*\n                 )?\n                 $\n                 \"\"\"#,\n        options: [.allowCommentsAndWhitespace]\n    )\n\n    /// The major version number.\n    public var major: Int {\n        return _version.major\n    }\n\n    /// The minor version number.\n    public var minor: Int {\n        return _version.minor\n    }\n\n    /// The patch version number.\n    public var patch: Int {\n        return _version.patch\n    }\n\n    /// Returns the tools version with zeroed patch number.\n    public var zeroedPatch: ToolsVersion {\n        return ToolsVersion(version: Version(major, minor, 0))\n    }\n\n    /// The underlying backing store.\n    fileprivate let _version: Version\n\n    /// Experimental features\n    public enum ExperimentalFeature: String, Sendable, Codable {\n        case experimentalCGen\n    }\n    public let experimentalFeatures: Set<ExperimentalFeature>\n\n    /// Helpers for experimental\n    public var experimentalCGen: Bool {\n        self >= .v6_3 && experimentalFeatures.contains(.experimentalCGen)\n    }\n\n    /// Create an instance of tools version from a given string.\n    public init?(string: String, experimentalFeatures: Set<ExperimentalFeature> = []) {\n        guard let match = ToolsVersion.toolsVersionRegex.firstMatch(\n            in: string, options: [], range: NSRange(location: 0, length: string.count)) else {\n            return nil\n        }\n        // The regex succeeded, compute individual components.\n        assert(match.numberOfRanges == 6)\n        let string = NSString(string: string)\n        let major = Int(string.substring(with: match.range(at: 1)))!\n        let minor = Int(string.substring(with: match.range(at: 2)))!\n        let patchRange = match.range(at: 3)\n        let patch = patchRange.location != NSNotFound ? Int(string.substring(with: patchRange))! : 0\n        // We ignore storing pre-release and build identifiers for now.\n        _version = Version(major, minor, patch)\n        self.experimentalFeatures = experimentalFeatures\n    }\n\n    /// Create instance of tools version from a given version.\n    ///\n    /// - precondition: prereleaseIdentifiers and buildMetadataIdentifier should not be present.\n    public init(version: Version) {\n        _version = version\n        experimentalFeatures = []\n    }\n\n    /// Override equality to ignore experimental features\n    public static func == (lhs: ToolsVersion, rhs: ToolsVersion) -> Bool {\n        lhs._version == rhs._version\n    }\n\n    private enum ValidationResult {\n        case valid\n        case unsupportedToolsVersion\n        case requireNewerTools\n    }\n\n    private func _validateToolsVersion(_ currentToolsVersion: ToolsVersion) -> ValidationResult {\n        // We don't want to throw any error when using the special vNext version.\n        if SwiftVersion.current.isDevelopment && self == .vNext {\n            return .valid\n        }\n\n        // Make sure the package has the right minimum tools version.\n        guard self >= .minimumRequired else {\n            return .unsupportedToolsVersion\n        }\n\n        // Make sure the package isn't newer than the current tools version.\n        guard currentToolsVersion >= self else {\n            return .requireNewerTools\n        }\n\n        return .valid\n    }\n\n    /// Returns true if the tools version is valid and can be used by this\n    /// version of the package manager.\n    public func validateToolsVersion(_ currentToolsVersion: ToolsVersion) -> Bool {\n        return self._validateToolsVersion(currentToolsVersion) == .valid\n    }\n\n    public func validateToolsVersion(\n        _ currentToolsVersion: ToolsVersion,\n        packageIdentity: PackageIdentity,\n        packageVersion: String? = .none\n    ) throws {\n        switch self._validateToolsVersion(currentToolsVersion) {\n        case .valid:\n            break\n        case .unsupportedToolsVersion:\n            throw UnsupportedToolsVersion(\n                packageIdentity: packageIdentity,\n                packageVersion: packageVersion,\n                currentToolsVersion: currentToolsVersion,\n                packageToolsVersion: self\n            )\n        case .requireNewerTools:\n            throw RequireNewerTools(\n                packageIdentity: packageIdentity,\n                packageVersion: packageVersion,\n                installedToolsVersion: currentToolsVersion,\n                packageToolsVersion: self\n            )\n        }\n    }\n\n    /// The subpath to the PackageDescription runtime library.\n    public var runtimeSubpath: RelativePath {\n        if self < .v4_2 {\n            return try! RelativePath(validating: \"4\") // try! safe\n        }\n        return try! RelativePath(validating: \"4_2\") // try! safe\n    }\n\n    /// The swift language version based on this tools version.\n    public var swiftLanguageVersion: SwiftLanguageVersion {\n        switch major {\n        case 4:\n            // If the tools version is less than 4.2, use language version 4.\n            if minor < 2 {\n                return .v4\n            }\n\n            // Otherwise, use 4.2\n            return .v4_2\n        case 5:\n            return .v5\n        default:\n            // Anything above 5 major version uses version 6.\n            return .v6\n        }\n    }\n}\n\nextension ToolsVersion {\n    /// The list of version specific identifiers to search when attempting to\n    /// load version specific package or version information, in order of\n    /// preference.\n    public var versionSpecificKeys: [String] {\n        return [\n            \"@swift-\\(self.major).\\(self.minor).\\(self.patch)\",\n            \"@swift-\\(self.major).\\(self.minor)\",\n            \"@swift-\\(self.major)\",\n        ]\n    }\n}\n\nextension ToolsVersion: CustomStringConvertible {\n    public var description: String {\n        return self._version.description\n    }\n}\n\nextension ToolsVersion: Comparable {\n    public static func < (lhs: ToolsVersion, rhs: ToolsVersion) -> Bool {\n        return lhs._version < rhs._version\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/ToolsVersionSpecificationGeneration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// -----------------------------------------------------------------------------\n///\n/// This file contains an extension to `ToolsVersion` that implements the generation of a Swift tools version specification from a `ToolsVersion` instance.\n///\n// -----------------------------------------------------------------------------\n\nextension ToolsVersion {\n    // TODO: Add options for whitespace styles.\n    /// Returns a Swift tools version specification specifying the version to the given precision.\n    /// - Parameter leastSignificantVersion: The precision to which the version specifier follows the version.\n    /// - Returns: A  Swift tools version specification specifying the version to the given precision.\n    public func specification(roundedTo leastSignificantVersion: LeastSignificantVersion = .automatic) -> String {\n        var versionSpecifier = \"\\(major).\\(minor)\"\n        switch leastSignificantVersion {\n        case .automatic:\n            // If the patch version is not zero, then it's included in the Swift tools version specification.\n            if patch != 0 { fallthrough }\n        case .patch:\n            versionSpecifier = \"\\(versionSpecifier).\\(patch)\"\n        case .minor:\n            break\n        }\n        return \"// swift-tools-version:\\(self < .v5_4 ? \"\" : \" \")\\(versionSpecifier)\"\n    }\n\n    /// The least significant version to round to.\n    public enum LeastSignificantVersion {\n        /// The patch version is the least significant if and only if it's not zero. Otherwise, the minor version is the least significant.\n        case automatic\n        /// The minor version is the least significant.\n        case minor\n        /// The patch version is the least significant.\n        case patch\n        // Although `ToolsVersion` uses `Version` as its backing store, it discards all pre-release and build metadata.\n        // The versioning information ends at the patch version.\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/Toolset.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\nimport struct TSCBasic.StringError\nimport struct TSCUtility.Version\n\n/// A set of paths and flags for tools used for building Swift packages. This type unifies pre-existing assorted ways\n/// to specify these properties across SwiftPM codebase.\npublic struct Toolset: Equatable {\n    /// Tools currently known and used by SwiftPM.\n    public enum KnownTool: String, Hashable, CaseIterable {\n        case swiftCompiler\n        case cCompiler\n        case cxxCompiler\n        case linker\n        case librarian\n        case debugger\n        case testRunner\n        case xcbuild\n    }\n\n    /// Properties of a known tool in a ``Toolset``.\n    public struct ToolProperties: Equatable {\n        /// Absolute path to the tool on the filesystem. If absent, implies a default tool is used.\n        public internal(set) var path: AbsolutePath?\n\n        /// Command-line options to be passed to the tool when it's invoked.\n        public internal(set) var extraCLIOptions: [String]\n    }\n\n    /// A dictionary of known tools in this toolset.\n    public internal(set) var knownTools: [KnownTool: ToolProperties] = [:]\n\n    /// An array of paths specified as `rootPath` in toolset files from which this toolset was formed. May be used\n    /// for locating tools that aren't currently listed in ``Toolset/KnownTool``.\n    public internal(set) var rootPaths: [AbsolutePath] = []\n}\n\nextension Toolset.ToolProperties {\n    init(path: AbsolutePath) {\n        self.init(path: path, extraCLIOptions: [])\n    }\n}\n\nextension Toolset {\n    /// Initialize a toolset from an encoded file on a file system.\n    /// - Parameters:\n    ///   - path: absolute path on the `fileSystem`.\n    ///   - fileSystem: file system from which the toolset should be read.\n    ///   - observabilityScope: an instance of `ObservabilityScope` to log warnings about unknown or invalid tools.\n    public init(\n        from toolsetPath: AbsolutePath,\n        at fileSystem: FileSystem,\n        _ observabilityScope: ObservabilityScope\n    ) throws {\n        let decoder = JSONDecoder()\n\n        let decoded: DecodedToolset\n        do {\n            decoded = try decoder.decode(path: toolsetPath, fileSystem: fileSystem, as: DecodedToolset.self)\n        } catch {\n            // Throw a more detailed warning that includes the location of the toolset file we couldn't parse.\n            throw StringError(\"Couldn't parse toolset configuration at `\\(toolsetPath)`: \\(error.interpolationDescription)\")\n        }\n\n        guard decoded.schemaVersion == Version(1, 0, 0) else {\n            throw StringError(\n                \"Unsupported `schemaVersion` \\(decoded.schemaVersion) in toolset configuration at `\\(toolsetPath)`\"\n            )\n        }\n\n        let rootPaths = try decoded.rootPath.map {\n            [try AbsolutePath(validating: $0, relativeTo: toolsetPath.parentDirectory)]\n        } ?? []\n\n        var knownTools = [KnownTool: ToolProperties]()\n        var hasEmptyToolConfiguration = false\n        for (tool, properties) in decoded.tools {\n            guard let knownTool = KnownTool(rawValue: tool) else {\n                observabilityScope.emit(warning: \"Unknown tool `\\(tool)` in toolset configuration at `\\(toolsetPath)`\")\n                continue\n            }\n\n            let toolPath: AbsolutePath?\n            if let path = properties.path {\n                if let absolutePath = try? AbsolutePath(validating: path) {\n                    toolPath = absolutePath\n                } else {\n                    let rootPath = rootPaths.first ?? toolsetPath.parentDirectory\n                    toolPath = rootPath.appending(path)\n                }\n            } else {\n                toolPath = nil\n            }\n\n            guard toolPath != nil || !(properties.extraCLIOptions?.isEmpty ?? true) else {\n                // don't keep track of a tool with no path and CLI options specified.\n                observabilityScope.emit(\n                    error:\n                    \"\"\"\n                    Tool `\\(knownTool.rawValue) in toolset configuration at `\\(toolsetPath)` has neither `path` nor \\\n                    `extraCLIOptions` properties specified with valid values, skipping it.\n                    \"\"\"\n                )\n                hasEmptyToolConfiguration = true\n                continue\n            }\n\n            knownTools[knownTool] = ToolProperties(\n                path: toolPath,\n                extraCLIOptions: properties.extraCLIOptions ?? []\n            )\n        }\n\n        guard !hasEmptyToolConfiguration else {\n            throw StringError(\"Toolset configuration at `\\(toolsetPath)` has at least one tool with no properties.\")\n        }\n\n        self.init(knownTools: knownTools, rootPaths: rootPaths)\n    }\n\n    /// Merges toolsets together into a single configuration. Tools passed in a new toolset will shadow tools with\n    /// same names from previous toolsets. When no `path` is specified for a new tool, its `extraCLIOptions` are\n    /// appended to `extraCLIOptions` of a tool from a previous toolset, which allows augmenting existing tools instead\n    /// of replacing them.\n    /// - Parameter newToolset: new toolset to merge into the existing `self` toolset.\n    public mutating func merge(with newToolset: Toolset) {\n        self.rootPaths.insert(contentsOf: newToolset.rootPaths, at: 0)\n\n        for (newTool, newProperties) in newToolset.knownTools {\n            if newProperties.path != nil {\n                // if `newTool` has `path` specified, it overrides the existing tool completely.\n                knownTools[newTool] = newProperties\n            } else if !newProperties.extraCLIOptions.isEmpty {\n                // if `newTool` has no `path` specified, `newExtraCLIOptions` are appended to the existing tool.\n                if var existingTool = knownTools[newTool] {\n                    // either update the existing tool and store it back...\n                    existingTool.extraCLIOptions.append(contentsOf: newProperties.extraCLIOptions)\n                    knownTools[newTool] = existingTool\n                } else {\n                    // ...or store a new tool if no existing tool is found.\n                    knownTools[newTool] = newProperties\n                }\n            }\n        }\n    }\n\n    /// Initialize a new ad-hoc toolset that wasn't previously serialized, but created in memory.\n    /// - Parameters:\n    ///   - toolchainBinDir: absolute path to the toolchain binaries directory, which are used in this toolset.\n    ///   - buildFlags: flags provided to each tool as CLI options.\n    public init(toolchainBinDir: AbsolutePath, buildFlags: BuildFlags = .init()) {\n        self.rootPaths = [toolchainBinDir]\n        self.knownTools = [\n            .cCompiler: .init(extraCLIOptions: buildFlags.cCompilerFlags.rawFlags),\n            .cxxCompiler: .init(extraCLIOptions: buildFlags.cxxCompilerFlags.rawFlags),\n            .swiftCompiler: .init(extraCLIOptions: buildFlags.swiftCompilerFlags.rawFlags),\n            .linker: .init(extraCLIOptions: buildFlags.linkerFlags.rawFlags),\n            .xcbuild: .init(extraCLIOptions: buildFlags.xcbuildFlags ?? []),\n        ]\n    }\n}\n\n/// A raw decoding of toolset configuration stored on disk.\nprivate struct DecodedToolset {\n    /// Version of a toolset schema used for decoding a toolset file.\n    let schemaVersion: Version\n\n    /// Root path of the toolset, if present. When filling in ``Toolset.ToolProperties/path``, if a raw path string in\n    /// ``DecodedToolset`` is inferred to be relative, it's resolved as absolute path relatively to `rootPath`.\n    let rootPath: String?\n\n    /// Dictionary of raw tools that haven't been validated yet to match ``Toolset.KnownTool``.\n    var tools: [String: ToolProperties]\n\n    /// Properties of a tool in a ``DecodedToolset``.\n    public struct ToolProperties {\n        /// Either a relative or an absolute path to the tool on the filesystem.\n        let path: String?\n\n        /// Command-line options to be passed to the tool when it's invoked.\n        let extraCLIOptions: [String]?\n    }\n}\n\nextension DecodedToolset.ToolProperties: Decodable {}\n\nextension DecodedToolset: Decodable {\n    /// Custom decoding keys that allow decoding tools with arbitrary names,\n    enum CodingKeys: Equatable {\n        case schemaVersion\n        case rootPath\n        case tool(String)\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n\n        self.schemaVersion = try Version(\n            versionString: container.decode(String.self, forKey: .schemaVersion),\n            usesLenientParsing: true\n        )\n        self.rootPath = try container.decodeIfPresent(String.self, forKey: .rootPath)\n\n        self.tools = [String: DecodedToolset.ToolProperties]()\n        for key in container.allKeys {\n            switch key {\n            case .rootPath, .schemaVersion:\n                // These keys were already decoded before entering this loop, skipping.\n                continue\n            case .tool(let tool):\n                self.tools[tool] = try container.decode(DecodedToolset.ToolProperties.self, forKey: key)\n            }\n        }\n    }\n}\n\n/// Custom `CodingKey` implementation for `DecodedToolset`, which allows us to resiliently decode unknown tools and emit\n/// multiple diagnostic messages about them separately from the decoding process, instead of emitting a single error\n/// that will disrupt whole decoding at once.\nextension DecodedToolset.CodingKeys: CodingKey {\n    var stringValue: String {\n        switch self {\n        case .schemaVersion:\n            return \"schemaVersion\"\n        case .rootPath:\n            return \"rootPath\"\n        case .tool(let toolName):\n            return toolName\n        }\n    }\n\n    init?(stringValue: String) {\n        switch stringValue {\n        case \"schemaVersion\":\n            self = .schemaVersion\n        case \"rootPath\":\n            self = .rootPath\n        default:\n            self = .tool(stringValue)\n        }\n    }\n\n    var intValue: Int? { nil }\n\n    init?(intValue: Int) {\n        nil\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/UserToolchain.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport TSCUtility\nimport enum TSCBasic.JSON\n\nimport class Basics.AsyncProcess\n\n#if os(Windows)\nprivate let hostExecutableSuffix = \".exe\"\n#else\nprivate let hostExecutableSuffix = \"\"\n#endif\n\n// FIXME: This is messy and needs a redesign.\npublic final class UserToolchain: Toolchain {\n    public typealias SwiftCompilers = (compile: AbsolutePath, manifest: AbsolutePath)\n\n    /// The toolchain configuration.\n    private let configuration: ToolchainConfiguration\n\n    /// Path of the librarian.\n    public let librarianPath: AbsolutePath\n\n    /// Path of the `swiftc` compiler.\n    public let swiftCompilerPath: AbsolutePath\n\n    /// An array of paths to search for headers and modules at compile time.\n    public let includeSearchPaths: [AbsolutePath]\n\n    /// An array of paths to search for libraries at link time.\n    public let librarySearchPaths: [AbsolutePath]\n\n    /// Thread-safe cached runtime library paths\n    private let _runtimeLibraryPaths = ThreadSafeBox<[AbsolutePath]?>()\n\n    /// An array of paths to use with binaries produced by this toolchain at run time.\n    public var runtimeLibraryPaths: [AbsolutePath] {\n        return _runtimeLibraryPaths.memoize {\n            guard let targetInfo = self.targetInfo else {\n                return []\n            }\n            return (try? Self.computeRuntimeLibraryPaths(targetInfo: targetInfo)) ?? []\n        }\n    }\n\n    /// Path containing Swift resources for dynamic linking.\n    public var swiftResourcesPath: AbsolutePath? {\n        swiftSDK.pathsConfiguration.swiftResourcesPath\n    }\n\n    /// Path containing Swift resources for static linking.\n    public var swiftStaticResourcesPath: AbsolutePath? {\n        swiftSDK.pathsConfiguration.swiftStaticResourcesPath\n    }\n\n    /// Additional flags to be passed to the build tools.\n    public var extraFlags: BuildFlags\n\n    /// Path of the `swift` interpreter.\n    public var swiftInterpreterPath: AbsolutePath {\n        self.swiftCompilerPath.parentDirectory.appending(\"swift\" + hostExecutableSuffix)\n    }\n\n    private let fileSystem: any FileSystem\n\n    /// The compilation destination object.\n    @available(*, deprecated, renamed: \"swiftSDK\")\n    public var destination: SwiftSDK { swiftSDK }\n\n    /// The Swift SDK used by this toolchain.\n    public let swiftSDK: SwiftSDK\n\n    /// The target triple that should be used for compilation.\n    @available(*, deprecated, renamed: \"targetTriple\")\n    public var triple: Basics.Triple { targetTriple }\n\n    public let targetTriple: Basics.Triple\n\n    private let _targetInfo: JSON?\n\n    /// Thread-safe cached target info that allows for lazy instantiation\n    private let _cachedTargetInfo = ThreadSafeBox<JSON?>()\n\n    private var targetInfo: JSON? {\n        return _cachedTargetInfo.memoizeOptional {\n            // Only call out to the swift compiler to fetch the target info when necessary\n            return try? _targetInfo ?? Self.getTargetInfo(swiftCompiler: swiftCompilerPath)\n        }\n    }\n\n    /// Thread-safe cached swift compiler version that allows for lazy instantiation\n    private let _swiftCompilerVersion = ThreadSafeBox<String?>()\n\n    // A version string that can be used to identify the swift compiler version\n    public var swiftCompilerVersion: String? {\n        return _swiftCompilerVersion.memoizeOptional {\n            guard let targetInfo = self.targetInfo else {\n                return nil\n            }\n            return Self.computeSwiftCompilerVersion(targetInfo: targetInfo)\n        }\n    }\n\n    /// The list of CPU architectures to build for.\n    public let architectures: [String]?\n\n    /// Search paths from the PATH environment variable.\n    let envSearchPaths: [AbsolutePath]\n\n    /// Only use search paths, do not fall back to `xcrun`.\n    let useXcrun: Bool\n\n    private var _clangCompiler: AbsolutePath?\n\n    private let environment: Environment\n\n    public let installedSwiftPMConfiguration: InstalledSwiftPMConfiguration\n\n    /// Returns the runtime library for the given sanitizer.\n    public func runtimeLibrary(for sanitizer: Sanitizer) throws -> AbsolutePath {\n        // FIXME: This is only for SwiftPM development time support. It is OK\n        // for now but we shouldn't need to resolve the symlink.  We need to lay\n        // down symlinks to runtimes in our fake toolchain as part of the\n        // bootstrap script.\n        let swiftCompiler = try resolveSymlinks(self.swiftCompilerPath)\n\n        let runtime = try swiftCompiler.appending(\n            RelativePath(validating: \"../../lib/swift/clang/lib/darwin/libclang_rt.\\(sanitizer.shortName)_osx_dynamic.dylib\")\n        )\n\n        // Ensure that the runtime is present.\n        guard fileSystem.exists(runtime) else {\n            throw InvalidToolchainDiagnostic(\"Missing runtime for \\(sanitizer) sanitizer\")\n        }\n\n        return runtime\n    }\n\n    // MARK: - private utilities\n\n    private static func lookup(\n        variable: String,\n        searchPaths: [AbsolutePath],\n        environment: Environment\n    ) -> AbsolutePath? {\n        lookupExecutablePath(filename: environment[.init(variable)], searchPaths: searchPaths)\n    }\n\n    private static func getTool(\n        _ name: String,\n        binDirectories: [AbsolutePath],\n        fileSystem: any FileSystem\n    ) throws -> AbsolutePath {\n        let executableName = \"\\(name)\\(hostExecutableSuffix)\"\n        var toolPath: AbsolutePath?\n\n        for dir in binDirectories {\n            let path = dir.appending(component: executableName)\n            guard fileSystem.isExecutableFile(path) else {\n                continue\n            }\n            toolPath = path\n            // Take the first match.\n            break\n        }\n\n        guard let toolPath else {\n            throw InvalidToolchainDiagnostic(\"could not find CLI tool `\\(name)` at any of these directories: \\(binDirectories)\")\n        }\n        return toolPath\n    }\n\n    private static func findTool(\n        _ name: String,\n        envSearchPaths: [AbsolutePath],\n        useXcrun: Bool,\n        fileSystem: any FileSystem\n    ) throws -> AbsolutePath {\n        if useXcrun {\n            #if os(macOS)\n            let foundPath = try AsyncProcess.checkNonZeroExit(arguments: [\"/usr/bin/xcrun\", \"--find\", name])\n                .spm_chomp()\n            return try AbsolutePath(validating: foundPath)\n            #endif\n        }\n\n        return try getTool(name, binDirectories: envSearchPaths, fileSystem: fileSystem)\n    }\n\n    private static func getTargetInfo(swiftCompiler: AbsolutePath) throws -> JSON {\n        // Call the compiler to get the target info JSON.\n        let result: AsyncProcessResult\n        let compilerOutput: String\n        let compilerStderr: String\n        do {\n            result = try AsyncProcess.popen(args: swiftCompiler.pathString, \"-print-target-info\")\n            compilerOutput = try result.utf8Output().spm_chomp()\n            compilerStderr = try result.utf8stderrOutput().spm_chomp()\n        } catch {\n            throw InternalError(\n                \"Failed to load target info (\\(error.interpolationDescription))\"\n            )\n        }\n        // Parse the compiler's JSON output.\n        do {\n            return try JSON(string: compilerOutput)\n        } catch {\n            throw InternalError(\n                \"Failed to parse target info (\\(error.interpolationDescription)).\\nCompiler exited with staus \\(result.exitStatus).\\nRaw compiler stdout: \\(compilerOutput)\\nRaw compiler stderr: \\(compilerStderr)\"\n            )\n        }\n    }\n\n    private static func getHostTriple(targetInfo: JSON, versioned: Bool) throws -> Basics.Triple {\n        // Get the triple string from the target info.\n        let tripleString: String\n        do {\n            tripleString = try targetInfo.get(\"target\").get(versioned ? \"triple\" : \"unversionedTriple\")\n        } catch {\n            throw InternalError(\n                \"Target info does not contain a triple string (\\(error.interpolationDescription)).\\nTarget info: \\(targetInfo)\"\n            )\n        }\n\n        // Parse the triple string.\n        do {\n            return try Triple(tripleString)\n        } catch {\n            throw InternalError(\n                \"Failed to parse triple string (\\(error.interpolationDescription)).\\nTriple string: \\(tripleString)\"\n            )\n        }\n    }\n\n    private static func computeRuntimeLibraryPaths(targetInfo: JSON) throws -> [AbsolutePath] {\n        var libraryPaths: [AbsolutePath] = []\n\n        for runtimeLibPath in (try? (try? targetInfo.get(\"paths\"))?.getArray(\"runtimeLibraryPaths\")) ?? [] {\n            guard case .string(let value) = runtimeLibPath else {\n                continue\n            }\n\n            guard let path = try? AbsolutePath(validating: value) else {\n                continue\n            }\n\n            libraryPaths.append(path)\n        }\n\n        return libraryPaths\n    }\n\n    private static func computeSwiftCompilerVersion(targetInfo: JSON) -> String? {\n        // Use the new swiftCompilerTag if it's there\n        if let swiftCompilerTag: String = targetInfo.get(\"swiftCompilerTag\") {\n            return swiftCompilerTag\n        }\n\n        // Default to the swift portion of the compilerVersion\n        let compilerVersion: String\n        do {\n            compilerVersion = try targetInfo.get(\"compilerVersion\")\n        } catch {\n            return nil\n        }\n\n        // Extract the swift version using regex from the description if available\n        do {\n            let regex = try Regex(#\"\\((swift(lang)?-[^ )]*)\"#)\n            if let match = try regex.firstMatch(in: compilerVersion), match.count > 1, let substring = match[1].substring {\n                return String(substring)\n            }\n\n            let regex2 = try Regex(#\"\\(.*Swift (.*)[ )]\"#)\n            if let match2 = try regex2.firstMatch(in: compilerVersion), match2.count > 1, let substring = match2[1].substring {\n                return \"swift-\\(substring)\"\n            } else {\n                return nil\n            }\n        } catch {\n            return nil\n        }\n    }\n\n    // MARK: - public API\n\n    public static func determineLibrarian(\n        triple: Basics.Triple,\n        binDirectories: [AbsolutePath],\n        useXcrun: Bool,\n        environment: Environment,\n        searchPaths: [AbsolutePath],\n        extraSwiftFlags: [String],\n        fileSystem: any FileSystem\n    ) throws -> AbsolutePath {\n        let variable: String = triple.isApple() ? \"LIBTOOL\" : \"AR\"\n        let tool: String = {\n            if triple.isApple() { return \"libtool\" }\n            if triple.isWindows() {\n                if let librarian: AbsolutePath =\n                    UserToolchain.lookup(\n                        variable: \"AR\",\n                        searchPaths: searchPaths,\n                        environment: environment\n                    )\n                {\n                    return librarian.basename\n                }\n                // TODO(5719) handle `-Xmanifest` vs `-Xswiftc`\n                // `-use-ld=` is always joined in Swift.\n                if let ld = extraSwiftFlags.first(where: { $0.starts(with: \"-use-ld=\") }) {\n                    let linker = String(ld.split(separator: \"=\").last!)\n                    return linker == \"lld\" ? \"lld-link\" : linker\n                }\n                return \"link\"\n            }\n            return \"llvm-ar\"\n        }()\n\n        if let librarian = UserToolchain.lookup(\n            variable: variable,\n            searchPaths: searchPaths,\n            environment: environment\n        ) {\n            if fileSystem.isExecutableFile(librarian) {\n                return librarian\n            }\n        }\n\n        if let librarian = try? UserToolchain.getTool(tool, binDirectories: binDirectories, fileSystem: fileSystem) {\n            return librarian\n        }\n        if triple.isApple() || triple.isWindows() {\n            return try UserToolchain.findTool(tool, envSearchPaths: searchPaths, useXcrun: useXcrun, fileSystem: fileSystem)\n        } else {\n            if let librarian = try? UserToolchain.findTool(tool, envSearchPaths: searchPaths, useXcrun: false, fileSystem: fileSystem) {\n                return librarian\n            }\n            // Fall back to looking for binutils `ar` if `llvm-ar` can't be found.\n            if let librarian = try? UserToolchain.getTool(\"ar\", binDirectories: binDirectories, fileSystem: fileSystem) {\n                return librarian\n            }\n            return try UserToolchain.findTool(\"ar\", envSearchPaths: searchPaths, useXcrun: false, fileSystem: fileSystem)\n        }\n    }\n\n    /// Determines the Swift compiler paths for compilation and manifest parsing.\n    public static func determineSwiftCompilers(\n        binDirectories: [AbsolutePath],\n        useXcrun: Bool,\n        environment: Environment,\n        searchPaths: [AbsolutePath],\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope? = nil\n    ) throws -> SwiftCompilers {\n        func validateCompiler(at path: AbsolutePath?) throws {\n            guard let path else { return }\n            guard fileSystem.isExecutableFile(path) else {\n                throw InvalidToolchainDiagnostic(\n                    \"could not find the `swiftc\\(hostExecutableSuffix)` at expected path \\(path)\"\n                )\n            }\n        }\n\n        let lookup = { UserToolchain.lookup(variable: $0, searchPaths: searchPaths, environment: environment) }\n\n        // Warn if SWIFT_EXEC or SWIFT_EXEC_MANIFEST is set but points to a non-existent or non-executable path\n        func warnIfInvalid(envVar: String, value: String, resolved: AbsolutePath?) {\n            guard resolved == nil else { return }\n\n            let message: String\n            if let absolutePath = try? AbsolutePath(validating: value) {\n                if fileSystem.exists(absolutePath) {\n                    message = \"\\(envVar) is set to '\\(value)' which exists but is not executable; ignoring\"\n                } else {\n                    message = \"\\(envVar) is set to '\\(value)' but the file does not exist; ignoring\"\n                }\n            } else {\n                message = \"\\(envVar) is set to '\\(value)' but no executable was found in search paths; ignoring\"\n            }\n\n            observabilityScope?.emit(warning: message)\n        }\n\n        // Get overrides.\n        let SWIFT_EXEC_MANIFEST = lookup(\"SWIFT_EXEC_MANIFEST\")\n        let SWIFT_EXEC = lookup(\"SWIFT_EXEC\")\n\n        // Emit warnings if environment variables are set but lookup failed\n        if let swiftExecValue = environment[\"SWIFT_EXEC\"], !swiftExecValue.isEmpty {\n            warnIfInvalid(envVar: \"SWIFT_EXEC\", value: swiftExecValue, resolved: SWIFT_EXEC)\n        }\n        if let swiftExecManifestValue = environment[\"SWIFT_EXEC_MANIFEST\"], !swiftExecManifestValue.isEmpty {\n            warnIfInvalid(envVar: \"SWIFT_EXEC_MANIFEST\", value: swiftExecManifestValue, resolved: SWIFT_EXEC_MANIFEST)\n        }\n\n        // Validate the overrides.\n        try validateCompiler(at: SWIFT_EXEC)\n        try validateCompiler(at: SWIFT_EXEC_MANIFEST)\n\n        // We require there is at least one valid swift compiler, either in the\n        // bin dir or SWIFT_EXEC.\n        let resolvedBinDirCompiler: AbsolutePath\n        if let SWIFT_EXEC {\n            resolvedBinDirCompiler = SWIFT_EXEC\n        } else if let binDirCompiler = try? UserToolchain.getTool(\"swiftc\", binDirectories: binDirectories, fileSystem: fileSystem) {\n            resolvedBinDirCompiler = binDirCompiler\n        } else {\n            // Try to lookup swift compiler on the system which is possible when\n            // we're built outside of the Swift toolchain.\n            resolvedBinDirCompiler = try UserToolchain.findTool(\n                \"swiftc\",\n                envSearchPaths: searchPaths,\n                useXcrun: useXcrun,\n                fileSystem: fileSystem\n            )\n        }\n\n        // The compiler for compilation tasks is SWIFT_EXEC or the bin dir compiler.\n        // The compiler for manifest is either SWIFT_EXEC_MANIFEST or the bin dir compiler.\n        return (compile: SWIFT_EXEC ?? resolvedBinDirCompiler, manifest: SWIFT_EXEC_MANIFEST ?? resolvedBinDirCompiler)\n    }\n\n    /// Returns the path to clang compiler tool.\n    public func getClangCompiler() throws -> AbsolutePath {\n        // Check if we already computed.\n        if let clang = self._clangCompiler {\n            return clang\n        }\n\n        // Check in the environment variable first.\n        if let toolPath = UserToolchain.lookup(\n            variable: \"CC\",\n            searchPaths: self.envSearchPaths,\n            environment: environment\n        ) {\n            self._clangCompiler = toolPath\n            return toolPath\n        }\n\n        // Then, check the toolchain.\n        if let toolPath = try? UserToolchain.getTool(\n            \"clang\",\n            binDirectories: self.swiftSDK.toolset.rootPaths,\n            fileSystem: self.fileSystem\n        ) {\n            self._clangCompiler = toolPath\n            return toolPath\n        }\n\n        // Otherwise, lookup it up on the system.\n        let toolPath = try UserToolchain.findTool(\n            \"clang\",\n            envSearchPaths: self.envSearchPaths,\n            useXcrun: useXcrun,\n            fileSystem: self.fileSystem\n        )\n        self._clangCompiler = toolPath\n        return toolPath\n    }\n\n    public func _isClangCompilerVendorApple() throws -> Bool? {\n        // Assume the vendor is Apple on macOS.\n        // FIXME: This might not be the best way to determine this.\n        #if os(macOS)\n        return true\n        #else\n        return false\n        #endif\n    }\n\n    /// Returns the path to lldb.\n    public func getLLDB() throws -> AbsolutePath {\n        // Look for LLDB next to the compiler first.\n        if let lldbPath = try? UserToolchain.getTool(\n            \"lldb\",\n            binDirectories: [self.swiftCompilerPath.parentDirectory],\n            fileSystem: self.fileSystem\n        ) {\n            return lldbPath\n        }\n        // If that fails, fall back to xcrun, PATH, etc.\n        return try UserToolchain.findTool(\n            \"lldb\",\n            envSearchPaths: self.envSearchPaths,\n            useXcrun: useXcrun,\n            fileSystem: self.fileSystem\n        )\n    }\n\n    /// Returns the path to llvm-cov tool.\n    public func getLLVMCov() throws -> AbsolutePath {\n        try UserToolchain.getTool(\n            \"llvm-cov\",\n            binDirectories: [self.swiftCompilerPath.parentDirectory],\n            fileSystem: self.fileSystem\n        )\n    }\n\n    /// Returns the path to llvm-prof tool.\n    public func getLLVMProf() throws -> AbsolutePath {\n        try UserToolchain.getTool(\n            \"llvm-profdata\",\n            binDirectories: [self.swiftCompilerPath.parentDirectory],\n            fileSystem: self.fileSystem\n        )\n    }\n\n    /// Returns the path to llvm-objdump tool.\n    package func getLLVMObjdump() throws -> AbsolutePath {\n        try UserToolchain.getTool(\n            \"llvm-objdump\",\n            binDirectories: [self.swiftCompilerPath.parentDirectory],\n            fileSystem: self.fileSystem\n        )\n    }\n\n    public func getSwiftAPIDigester() throws -> AbsolutePath {\n        if let envValue = UserToolchain.lookup(\n            variable: \"SWIFT_API_DIGESTER\",\n            searchPaths: self.envSearchPaths,\n            environment: environment\n        ) {\n            return envValue\n        }\n        return try UserToolchain.getTool(\n            \"swift-api-digester\",\n            binDirectories: [self.swiftCompilerPath.parentDirectory],\n            fileSystem: self.fileSystem\n\n        )\n    }\n\n    public func getSymbolGraphExtract() throws -> AbsolutePath {\n        if let envValue = UserToolchain.lookup(\n            variable: \"SWIFT_SYMBOLGRAPH_EXTRACT\",\n            searchPaths: self.envSearchPaths,\n            environment: environment\n        ) {\n            return envValue\n        }\n        return try UserToolchain.getTool(\n            \"swift-symbolgraph-extract\",\n            binDirectories: [self.swiftCompilerPath.parentDirectory],\n            fileSystem: self.fileSystem\n        )\n    }\n\n#if os(macOS)\n    public func getSwiftTestingHelper() throws -> AbsolutePath {\n        // The helper would be located in `.build/<config>` directory when\n        // SwiftPM is built locally and `usr/libexec/swift/pm` directory in\n        // an installed version.\n        let binDirectories = self.swiftSDK.toolset.rootPaths +\n            self.swiftSDK.toolset.rootPaths.map {\n                $0.parentDirectory.appending(components: [\"libexec\", \"swift\", \"pm\"])\n            }\n\n        return try UserToolchain.getTool(\n            \"swiftpm-testing-helper\",\n            binDirectories: binDirectories,\n            fileSystem: self.fileSystem\n        )\n    }\n#endif\n\n    internal static func deriveSwiftCFlags(\n        triple: Basics.Triple,\n        swiftSDK: SwiftSDK,\n        environment: Environment,\n        fileSystem: any FileSystem\n    ) throws -> [BuildFlag] {\n        var swiftCompilerFlags = (swiftSDK.toolset.knownTools[.swiftCompiler]?.extraCLIOptions ?? []).map { BuildFlag(value: $0, source: .toolset)}\n\n        if let linker = swiftSDK.toolset.knownTools[.linker]?.path {\n            swiftCompilerFlags += [BuildFlag(value: \"-ld-path=\\(linker)\", source: .toolset)]\n        }\n\n        guard let sdkDir = swiftSDK.pathsConfiguration.sdkRootPath else {\n            if triple.isWindows() {\n                // Windows uses a variable named SDKROOT to determine the root of\n                // the SDK.  This is not the same value as the SDKROOT parameter\n                // in Xcode, however, the value represents a similar concept.\n                if let sdkroot = environment.windowsSDKRoot {\n                    var runtime: [BuildFlag] = []\n                    var xctest: [BuildFlag] = []\n                    var swiftTesting: [BuildFlag] = []\n                    var extraSwiftCFlags: [BuildFlag] = []\n\n                    if let settings = WindowsSDKSettings(\n                        reading: sdkroot.appending(\"SDKSettings.plist\"),\n                        observabilityScope: nil,\n                        filesystem: fileSystem\n                    ) {\n                        switch settings.defaults.runtime {\n                        case .multithreadedDebugDLL:\n                            runtime = [\"-libc\", \"MDd\"].map {\n                                BuildFlag(value: $0, source: .defaultWindowsSettings)\n                            }\n                        case .multithreadedDLL:\n                            runtime = [\"-libc\", \"MD\"].map {\n                                BuildFlag(value: $0, source: .defaultWindowsSettings)\n                            }\n                        case .multithreadedDebug:\n                            runtime = [\"-libc\", \"MTd\"].map {\n                                BuildFlag(value: $0, source: .defaultWindowsSettings)\n                            }\n                        case .multithreaded:\n                            runtime = [\"-libc\", \"MT\"].map {\n                                BuildFlag(value: $0, source: .defaultWindowsSettings)\n                            }\n                        }\n                    }\n\n                    // The layout of the SDK is as follows:\n                    //\n                    // Library/Developer/Platforms/[PLATFORM].platform/Developer/Library/<Project>-[VERSION]/...\n                    // Library/Developer/Platforms/[PLATFORM].platform/Developer/SDKs/[PLATFORM].sdk/...\n                    //\n                    // SDKROOT points to [PLATFORM].sdk\n                    let platform = sdkroot.parentDirectory.parentDirectory.parentDirectory\n\n                    if let info = WindowsPlatformInfo(\n                        reading: platform.appending(\"Info.plist\"),\n                        observabilityScope: nil,\n                        filesystem: fileSystem\n                    ) {\n                        let XCTestInstallation: AbsolutePath =\n                            platform.appending(\"Developer\")\n                                .appending(\"Library\")\n                                .appending(\"XCTest-\\(info.defaults.xctestVersion)\")\n\n                        xctest = try [\n                            \"-I\",\n                            AbsolutePath(\n                                validating: \"usr/lib/swift/windows\",\n                                relativeTo: XCTestInstallation\n                            ).pathString,\n                            // Migration Path\n                            //\n                            // Older Swift (<=5.7) installations placed the\n                            // XCTest Swift module into the architecture\n                            // specified directory.  This was in order to match\n                            // the SDK setup.  However, the toolchain finally\n                            // gained the ability to consult the architecture\n                            // independent directory for Swift modules, allowing\n                            // the merged swiftmodules.  XCTest followed suit.\n                            \"-I\",\n                            AbsolutePath(\n                                validating: \"usr/lib/swift/windows/\\(triple.archName)\",\n                                relativeTo: XCTestInstallation\n                            ).pathString,\n                            \"-L\",\n                            AbsolutePath(\n                                validating: \"usr/lib/swift/windows/\\(triple.archName)\",\n                                relativeTo: XCTestInstallation\n                            ).pathString,\n                        ].map { BuildFlag(value: $0, source: .defaultWindowsSettings) }\n\n                        // Migration Path\n                        //\n                        // In order to support multiple parallel installations\n                        // of an SDK, we need to ensure that we can have all the\n                        // architecture variant libraries available.  Prior to\n                        // this getting enabled (~5.7), we always had a singular\n                        // installed SDK.  Prefer the new variant which has an\n                        // architecture subdirectory in `bin` if available.\n                        let implib = try AbsolutePath(\n                            validating: \"usr/lib/swift/windows/XCTest.lib\",\n                            relativeTo: XCTestInstallation\n                        )\n                        if fileSystem.exists(implib) {\n                            xctest.append(contentsOf: [\"-L\", implib.parentDirectory.pathString].map {\n                                BuildFlag(value: $0, source: .defaultWindowsSettings)\n                            })\n                        }\n\n                        if let swiftTestingVersion = info.defaults.swiftTestingVersion {\n                            let swiftTestingInstallation: AbsolutePath =\n                                platform.appending(\"Developer\")\n                                    .appending(\"Library\")\n                                    .appending(\"Testing-\\(swiftTestingVersion)\")\n\n                            swiftTesting = try [\n                                \"-I\",\n                                AbsolutePath(\n                                    validating: \"usr/lib/swift/windows\",\n                                    relativeTo: swiftTestingInstallation\n                                ).pathString,\n                                \"-L\",\n                                AbsolutePath(\n                                    validating: \"usr/lib/swift/windows/\\(triple.archName)\",\n                                    relativeTo: swiftTestingInstallation\n                                ).pathString\n                            ].map { BuildFlag(value: $0, source: .defaultWindowsSettings) }\n                        }\n\n                        extraSwiftCFlags = (info.defaults.extraSwiftCFlags ?? []).map {\n                            BuildFlag(value: $0, source: .defaultWindowsSettings)\n                        }\n                    }\n\n                    return ([\"-sdk\", sdkroot.pathString].map { BuildFlag(value: $0, source: .swiftSDK) } + runtime + xctest + swiftTesting + extraSwiftCFlags)\n                }\n            }\n\n            return swiftCompilerFlags\n        }\n\n        return (\n            triple.isDarwin() || triple.isAndroid() || triple.isWASI() || triple.isWindows()\n                ? [\"-sdk\", sdkDir.pathString].map { BuildFlag(value: $0, source: .swiftSDK) }\n                : []\n        ) + swiftCompilerFlags\n    }\n\n    // MARK: - initializer\n\n    public enum SearchStrategy {\n        case `default`\n        case custom(searchPaths: [AbsolutePath], useXcrun: Bool = true)\n    }\n\n    @available(*, deprecated, message: \"use init(swiftSDK:environment:searchStrategy:customLibrariesLocation) instead\")\n    public convenience init(\n        destination: SwiftSDK,\n        environment: Environment = .current,\n        searchStrategy: SearchStrategy = .default,\n        customLibrariesLocation: ToolchainConfiguration.SwiftPMLibrariesLocation? = nil\n    ) throws {\n        try self.init(\n            swiftSDK: destination,\n            environment: environment,\n            searchStrategy: searchStrategy,\n            customLibrariesLocation: customLibrariesLocation,\n            fileSystem: localFileSystem\n        )\n    }\n\n    public init(\n        swiftSDK: SwiftSDK,\n        environment: Environment = .current,\n        searchStrategy: SearchStrategy = .default,\n        customTargetInfo: JSON? = nil,\n        customLibrariesLocation: ToolchainConfiguration.SwiftPMLibrariesLocation? = nil,\n        customInstalledSwiftPMConfiguration: InstalledSwiftPMConfiguration? = nil,\n        observabilityScope: ObservabilityScope? = nil,\n        fileSystem: any FileSystem = localFileSystem\n    ) throws {\n        self.swiftSDK = swiftSDK\n        self.environment = environment\n\n        switch searchStrategy {\n        case .default:\n            // Get the search paths from PATH.\n            self.envSearchPaths = getEnvSearchPaths(\n                pathString: environment[.path],\n                currentWorkingDirectory: fileSystem.currentWorkingDirectory\n            )\n            self.useXcrun = !(fileSystem is InMemoryFileSystem)\n        case .custom(let searchPaths, let useXcrun):\n            self.envSearchPaths = searchPaths\n            self.useXcrun = useXcrun\n        }\n\n        let swiftCompilers = try UserToolchain.determineSwiftCompilers(\n            binDirectories: swiftSDK.toolset.rootPaths,\n            useXcrun: self.useXcrun,\n            environment: environment,\n            searchPaths: self.envSearchPaths,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n        self.swiftCompilerPath = swiftCompilers.compile\n        self.architectures = swiftSDK.architectures\n\n        if let customInstalledSwiftPMConfiguration {\n            self.installedSwiftPMConfiguration = customInstalledSwiftPMConfiguration\n        } else {\n            let path = swiftCompilerPath.parentDirectory.parentDirectory.appending(components: [\n                \"share\", \"pm\", \"config.json\",\n            ])\n            self.installedSwiftPMConfiguration = try Self.loadJSONResource(\n                config: path,\n                type: InstalledSwiftPMConfiguration.self,\n                default: InstalledSwiftPMConfiguration.default)\n        }\n\n        var triple: Basics.Triple\n        if let targetTriple = swiftSDK.targetTriple {\n            self._targetInfo = nil\n            triple = targetTriple\n        } else {\n            // targetInfo from the compiler\n            let targetInfo = try customTargetInfo ?? Self.getTargetInfo(swiftCompiler: swiftCompilers.compile)\n            self._targetInfo = targetInfo\n            triple = try Self.getHostTriple(targetInfo: targetInfo, versioned: false)\n            if !triple.isDarwin() {\n                triple = try Self.getHostTriple(targetInfo: targetInfo, versioned: true)\n            }\n        }\n\n        // Change the triple to the specified arch if there's exactly one of them.\n        // The Triple property is only looked at by the native build system currently.\n        if let architectures = self.architectures, architectures.count == 1 {\n            let components = triple.tripleString.drop(while: { $0 != \"-\" })\n            triple = try Triple(architectures[0] + components)\n        }\n\n        self.targetTriple = triple\n\n        var swiftCompilerFlags: [BuildFlag] = []\n        var extraLinkerFlags: [BuildFlag] = []\n\n        let swiftTestingPath: AbsolutePath? = try Self.deriveSwiftTestingPath(\n            derivedSwiftCompiler: swiftCompilers.compile,\n            swiftSDK: self.swiftSDK,\n            triple: triple,\n            environment: environment,\n            fileSystem: fileSystem\n        )\n\n        var swiftTestingFlags: [String] = []\n        if triple.isMacOSX, let swiftTestingPath {\n            // Swift Testing is a framework (e.g. from CommandLineTools) so use -F.\n            if swiftTestingPath.extension == \"framework\" {\n                swiftTestingFlags += [\"-F\", swiftTestingPath.pathString]\n\n            // Otherwise Swift Testing is assumed to be a swiftmodule + library, so use -I and -L.\n            } else {\n                swiftTestingFlags += [\n                    \"-I\", swiftTestingPath.pathString,\n                    \"-L\", swiftTestingPath.pathString,\n                ]\n            }\n        }\n\n        // Specify the plugin path for Swift Testing's macro plugin if such a\n        // path exists in this toolchain.\n        if let swiftTestingPluginPath = Self.deriveSwiftTestingPluginPath(\n            derivedSwiftCompiler: swiftCompilers.compile,\n            fileSystem: fileSystem\n        ) {\n            swiftTestingFlags += [\"-plugin-path\", swiftTestingPluginPath.pathString]\n        }\n\n        swiftCompilerFlags.append(contentsOf: swiftTestingFlags.map {\n            BuildFlag(value: $0, source: .defaultSwiftTestingSearchPath)\n        })\n\n        swiftCompilerFlags += try Self.deriveSwiftCFlags(\n            triple: triple,\n            swiftSDK: swiftSDK,\n            environment: environment,\n            fileSystem: fileSystem\n        )\n\n        extraLinkerFlags += (swiftSDK.toolset.knownTools[.linker]?.extraCLIOptions ?? []).constructBuildFlags(source: .toolset)\n\n        self.extraFlags = BuildFlags(\n            cCompilerFlags: (swiftSDK.toolset.knownTools[.cCompiler]?.extraCLIOptions ?? []).constructBuildFlags(source: .toolset),\n            cxxCompilerFlags: (swiftSDK.toolset.knownTools[.cxxCompiler]?.extraCLIOptions ?? []).constructBuildFlags(source: .toolset),\n            swiftCompilerFlags: swiftCompilerFlags,\n            linkerFlags: extraLinkerFlags,\n            xcbuildFlags: swiftSDK.toolset.knownTools[.xcbuild]?.extraCLIOptions ?? [])\n\n        self.includeSearchPaths = swiftSDK.pathsConfiguration.includeSearchPaths ?? []\n        self.librarySearchPaths = swiftSDK.pathsConfiguration.includeSearchPaths ?? []\n\n        self.librarianPath = try swiftSDK.toolset.knownTools[.librarian]?.path ?? UserToolchain.determineLibrarian(\n            triple: triple,\n            binDirectories: swiftSDK.toolset.rootPaths,\n            useXcrun: useXcrun,\n            environment: environment,\n            searchPaths: envSearchPaths,\n            extraSwiftFlags: self.extraFlags.swiftCompilerFlags.rawFlags,\n            fileSystem: fileSystem\n        )\n\n        if let sdkDir = swiftSDK.pathsConfiguration.sdkRootPath {\n            let sysrootFlags = [triple.isDarwin() ? \"-isysroot\" : \"--sysroot\", sdkDir.pathString]\n            self.extraFlags.cCompilerFlags.insert(contentsOf: sysrootFlags.constructBuildFlags(source: .swiftSDK), at: 0)\n        }\n\n        if triple.isWindows() {\n            if let root = environment.windowsSDKRoot {\n                if let settings = WindowsSDKSettings(\n                    reading: root.appending(\"SDKSettings.plist\"),\n                    observabilityScope: nil,\n                    filesystem: fileSystem\n                ) {\n                    switch settings.defaults.runtime {\n                    case .multithreadedDebugDLL:\n                        // Defines _DEBUG, _MT, and _DLL\n                        // Linker uses MSVCRTD.lib\n                        self.extraFlags.cCompilerFlags += [\n                            \"-D_DEBUG\",\n                            \"-D_MT\",\n                            \"-D_DLL\",\n                            \"-Xclang\",\n                            \"--dependent-lib=msvcrtd\",\n                        ].constructBuildFlags(source: .defaultWindowsSettings)\n\n                    case .multithreadedDLL:\n                        // Defines _MT, and _DLL\n                        // Linker uses MSVCRT.lib\n                        self.extraFlags.cCompilerFlags += [\"-D_MT\", \"-D_DLL\", \"-Xclang\", \"--dependent-lib=msvcrt\"].constructBuildFlags(source: .defaultWindowsSettings)\n\n                    case .multithreadedDebug:\n                        // Defines _DEBUG, and _MT\n                        // Linker uses LIBCMTD.lib\n                        self.extraFlags.cCompilerFlags += [\"-D_DEBUG\", \"-D_MT\", \"-Xclang\", \"--dependent-lib=libcmtd\"].constructBuildFlags(source: .defaultWindowsSettings)\n\n                    case .multithreaded:\n                        // Defines _MT\n                        // Linker uses LIBCMT.lib\n                        self.extraFlags.cCompilerFlags += [\"-D_MT\", \"-Xclang\", \"--dependent-lib=libcmt\"].constructBuildFlags(source: .defaultWindowsSettings)\n                    }\n                }\n            }\n        }\n\n        let swiftPMLibrariesLocation = try customLibrariesLocation ?? Self.deriveSwiftPMLibrariesLocation(\n            swiftCompilerPath: swiftCompilerPath,\n            swiftSDK: swiftSDK,\n            environment: environment,\n            fileSystem: fileSystem\n        )\n\n        let xctestPath: AbsolutePath?\n        if case .custom(_, let useXcrun) = searchStrategy, !useXcrun {\n            xctestPath = nil\n        } else {\n            xctestPath = try Self.deriveXCTestPath(\n                swiftSDK: self.swiftSDK,\n                triple: triple,\n                environment: environment,\n                fileSystem: fileSystem\n            )\n        }\n\n        let metalToolchain = try? Self.deriveMetalToolchainPath(fileSystem: fileSystem, triple: triple, environment: environment)\n\n        self.configuration = .init(\n            librarianPath: librarianPath,\n            swiftCompilerPath: swiftCompilers.manifest,\n            swiftCompilerFlags: self.extraFlags.swiftCompilerFlags.rawFlags,\n            swiftCompilerEnvironment: environment,\n            swiftPMLibrariesLocation: swiftPMLibrariesLocation,\n            sdkRootPath: self.swiftSDK.pathsConfiguration.sdkRootPath,\n            xctestPath: xctestPath,\n            swiftTestingPath: swiftTestingPath,\n            metalToolchainPath: metalToolchain?.path,\n            metalToolchainId: metalToolchain?.identifier\n        )\n\n        self.fileSystem = fileSystem\n    }\n\n    private static func deriveSwiftPMLibrariesLocation(\n        swiftCompilerPath: AbsolutePath,\n        swiftSDK: SwiftSDK,\n        environment: Environment,\n        fileSystem: any FileSystem\n    ) throws -> ToolchainConfiguration.SwiftPMLibrariesLocation? {\n        // Look for an override in the env.\n        if let pathEnvVariable = environment[\"SWIFTPM_CUSTOM_LIBS_DIR\"] ?? environment[\"SWIFTPM_PD_LIBS\"] {\n            if environment[\"SWIFTPM_PD_LIBS\"] != nil {\n                print(\"SWIFTPM_PD_LIBS was deprecated in favor of SWIFTPM_CUSTOM_LIBS_DIR\")\n            }\n            // We pick the first path which exists in an environment variable\n            // delimited by the platform specific string separator.\n            #if os(Windows)\n            let separator: Character = \";\"\n            #else\n            let separator: Character = \":\"\n            #endif\n            let paths = pathEnvVariable.split(separator: separator).map(String.init)\n            for pathString in paths {\n                if let path = try? AbsolutePath(validating: pathString), fileSystem.exists(path) {\n                    // we found the custom one\n                    return .init(root: path)\n                }\n            }\n\n            // fail if custom one specified but not found\n            throw InternalError(\n                \"Couldn't find the custom libraries location defined by SWIFTPM_CUSTOM_LIBS_DIR / SWIFTPM_PD_LIBS: \\(pathEnvVariable)\"\n            )\n        }\n\n        // FIXME: the following logic is pretty fragile, but has always been this way\n        // an alternative cloud be to force explicit locations to always be set explicitly when running in Xcode/SwiftPM\n        // debug and assert if not set but we detect that we are in this mode\n\n        for applicationPath in swiftSDK.toolset.rootPaths {\n            // this is the normal case when using the toolchain\n            let librariesPath = applicationPath.parentDirectory.appending(components: \"lib\", \"swift\", \"pm\")\n            if fileSystem.exists(librariesPath) {\n                return .init(root: librariesPath)\n            }\n\n            // this tests if we are debugging / testing SwiftPM with Xcode\n            let manifestFrameworksPath = applicationPath.appending(\n                components: \"PackageFrameworks\",\n                \"PackageDescription.framework\"\n            )\n            let pluginFrameworksPath = applicationPath.appending(components: \"PackageFrameworks\", \"PackagePlugin.framework\")\n            if fileSystem.exists(manifestFrameworksPath), fileSystem.exists(pluginFrameworksPath) {\n                return .init(\n                    manifestLibraryPath: manifestFrameworksPath,\n                    pluginLibraryPath: pluginFrameworksPath\n                )\n            }\n\n            // this tests if we are debugging / testing SwiftPM with SwiftPM\n            if localFileSystem.exists(applicationPath.appending(\"swift-package\")) {\n                // Newer versions of SwiftPM will emit modules to a \"Modules\" subdirectory, but we're also staying compatible with older versions for development.\n                let modulesPath: AbsolutePath\n                if localFileSystem.exists(applicationPath.appending(\"Modules\")) {\n                    modulesPath = applicationPath.appending(\"Modules\")\n                } else {\n                    modulesPath = applicationPath\n                }\n\n                return .init(\n                    manifestLibraryPath: applicationPath,\n                    manifestModulesPath: modulesPath,\n                    pluginLibraryPath: applicationPath,\n                    pluginModulesPath: modulesPath\n                )\n            }\n        }\n\n        // we are using a SwiftPM outside a toolchain, use the compiler path to compute the location\n        return .init(swiftCompilerPath: swiftCompilerPath)\n    }\n\n    private static func derivePluginServerPath(triple: Basics.Triple) throws -> AbsolutePath? {\n        if triple.isDarwin() {\n            let pluginServerPathFindArgs = [\"/usr/bin/xcrun\", \"--find\", \"swift-plugin-server\"]\n            if let path = try? AsyncProcess.checkNonZeroExit(arguments: pluginServerPathFindArgs, environment: [:])\n                .spm_chomp() {\n                return try AbsolutePath(validating: path)\n            }\n        }\n        return .none\n    }\n\n    private static func getWindowsPlatformInfo(\n        swiftSDK: SwiftSDK,\n        environment: Environment,\n        fileSystem: any FileSystem\n    ) -> (AbsolutePath, WindowsPlatformInfo)? {\n        let sdkRoot: AbsolutePath? = if let sdkDir = swiftSDK.pathsConfiguration.sdkRootPath {\n            sdkDir\n        } else if let sdkDir = environment.windowsSDKRoot {\n            sdkDir\n        } else {\n            nil\n        }\n\n        guard let sdkRoot else {\n            return nil\n        }\n\n        // The layout of the SDK is as follows:\n        //\n        // Library/Developer/Platforms/[PLATFORM].platform/Developer/Library/<Project>-[VERSION]/...\n        // Library/Developer/Platforms/[PLATFORM].platform/Developer/SDKs/[PLATFORM].sdk/...\n        //\n        // SDKROOT points to [PLATFORM].sdk\n        let platform = sdkRoot.parentDirectory.parentDirectory.parentDirectory\n\n        guard let info = WindowsPlatformInfo(\n            reading: platform.appending(\"Info.plist\"),\n            observabilityScope: nil,\n            filesystem: fileSystem\n        ) else {\n            return nil\n        }\n\n        return (platform, info)\n    }\n\n    private static func deriveMetalToolchainPath(\n        fileSystem: FileSystem,\n        triple: Basics.Triple,\n        environment: Environment\n    ) throws -> (path: AbsolutePath, identifier: String)? {\n        guard triple.isDarwin() else {\n            return nil\n        }\n\n        let xcrunCmd = [\"/usr/bin/xcrun\", \"--find\", \"metal\"]\n        guard let output = try? AsyncProcess.checkNonZeroExit(arguments: xcrunCmd, environment: environment).spm_chomp() else {\n            return nil\n        }\n\n        guard let metalPath = try? AbsolutePath(validating: output) else {\n            return nil\n        }\n\n        guard let toolchainPath: AbsolutePath = {\n            var currentPath = metalPath\n            while currentPath != currentPath.parentDirectory {\n                if currentPath.basename == \"Metal.xctoolchain\" {\n                    return currentPath\n                }\n                currentPath = currentPath.parentDirectory\n            }\n            return nil\n        }() else {\n            return nil\n        }\n\n        let toolchainInfoPlist = toolchainPath.appending(component: \"ToolchainInfo.plist\")\n\n        struct MetalToolchainInfo: Decodable {\n            let Identifier: String\n        }\n\n        let toolchainIdentifier: String\n        do {\n            let data: Data = try fileSystem.readFileContents(toolchainInfoPlist)\n            let info = try PropertyListDecoder().decode(MetalToolchainInfo.self, from: data)\n            toolchainIdentifier = info.Identifier\n        } catch {\n            return nil\n        }\n\n        return (path: toolchainPath.parentDirectory, identifier: toolchainIdentifier)\n    }\n\n    // TODO: We should have some general utility to find tools.\n    private static func deriveXCTestPath(\n        swiftSDK: SwiftSDK,\n        triple: Basics.Triple,\n        environment: Environment,\n        fileSystem: any FileSystem\n    ) throws -> AbsolutePath? {\n        if triple.isDarwin() {\n            // XCTest is optional on macOS, for example when Xcode is not installed\n            let xctestFindArgs = [\"/usr/bin/xcrun\", \"--sdk\", \"macosx\", \"--find\", \"xctest\"]\n            if let path = try? AsyncProcess.checkNonZeroExit(arguments: xctestFindArgs, environment: environment)\n                .spm_chomp()\n            {\n                return try AbsolutePath(validating: path)\n            }\n        } else if triple.isWindows() {\n            if let (platform, info) = getWindowsPlatformInfo(\n                swiftSDK: swiftSDK,\n                environment: environment,\n                fileSystem: fileSystem\n            ) {\n                let xctest: AbsolutePath =\n                    platform.appending(\"Developer\")\n                        .appending(\"Library\")\n                        .appending(\"XCTest-\\(info.defaults.xctestVersion)\")\n\n                // Migration Path\n                //\n                // In order to support multiple parallel installations of an\n                // SDK, we need to ensure that we can have all the architecture\n                // variant libraries available.  Prior to this getting enabled\n                // (~5.7), we always had a singular installed SDK.  Prefer the\n                // new variant which has an architecture subdirectory in `bin`\n                // if available.\n                switch triple.arch {\n                case .x86_64: // amd64 x86_64 x86_64h\n                    let path: AbsolutePath =\n                        xctest.appending(\"usr\")\n                            .appending(\"bin64\")\n                    if fileSystem.exists(path) {\n                        return path\n                    }\n\n                case .x86: // i386 i486 i586 i686 i786 i886 i986\n                    let path: AbsolutePath =\n                        xctest.appending(\"usr\")\n                            .appending(\"bin32\")\n                    if fileSystem.exists(path) {\n                        return path\n                    }\n\n                case .arm: // armv7 and many more\n                    let path: AbsolutePath =\n                        xctest.appending(\"usr\")\n                            .appending(\"bin32a\")\n                    if fileSystem.exists(path) {\n                        return path\n                    }\n\n                case .aarch64: // aarch6 arm64\n                    let path: AbsolutePath =\n                        xctest.appending(\"usr\")\n                            .appending(\"bin64a\")\n                    if fileSystem.exists(path) {\n                        return path\n                    }\n\n                default:\n                    // Fallback to the old-style layout.  We should really\n                    // report an error in this case - this architecture is\n                    // unavailable.\n                    break\n                }\n\n                // Assume that we are in the old-style layout.\n                return xctest.appending(\"usr\")\n                    .appending(\"bin\")\n            }\n        }\n        return nil\n    }\n\n    /// Find the swift-testing path if it is within a path that will need extra search paths.\n    private static func deriveSwiftTestingPath(\n        derivedSwiftCompiler: Basics.AbsolutePath,\n        swiftSDK: SwiftSDK,\n        triple: Basics.Triple,\n        environment: Environment,\n        fileSystem: any FileSystem\n    ) throws -> AbsolutePath? {\n        if triple.isDarwin() {\n            // If this is CommandLineTools all we need to add is a frameworks path.\n            if let frameworksPath = try? AbsolutePath(\n                validating: \"../../Library/Developer/Frameworks\",\n                relativeTo: resolveSymlinks(derivedSwiftCompiler).parentDirectory\n            ), fileSystem.exists(frameworksPath.appending(\"Testing.framework\")) {\n                return frameworksPath\n            }\n\n            guard let toolchainLibDir = try? toolchainLibDir(swiftCompilerPath: derivedSwiftCompiler) else {\n                return nil\n            }\n\n            let testingLibDir = toolchainLibDir.appending(components: [\"swift\", \"macosx\", \"testing\"])\n            if fileSystem.exists(testingLibDir) {\n                return testingLibDir\n            }\n        } else if triple.isWindows() {\n            guard let (platform, info) = getWindowsPlatformInfo(\n                swiftSDK: swiftSDK,\n                environment: environment,\n                fileSystem: fileSystem\n            ) else {\n                return nil\n            }\n\n            guard let swiftTestingVersion = info.defaults.swiftTestingVersion else {\n                return nil\n            }\n\n            let swiftTesting: AbsolutePath =\n                platform.appending(\"Developer\")\n                    .appending(\"Library\")\n                    .appending(\"Testing-\\(swiftTestingVersion)\")\n\n            let binPath: AbsolutePath? = switch triple.arch {\n            case .x86_64: // amd64 x86_64 x86_64h\n                swiftTesting.appending(\"usr\")\n                    .appending(\"bin64\")\n            case .x86: // i386 i486 i586 i686 i786 i886 i986\n                swiftTesting.appending(\"usr\")\n                    .appending(\"bin32\")\n            case .arm: // armv7 and many more\n                swiftTesting.appending(\"usr\")\n                    .appending(\"bin32a\")\n            case .aarch64: // aarch6 arm64\n                swiftTesting.appending(\"usr\")\n                    .appending(\"bin64a\")\n            default:\n                nil\n            }\n\n            if let path = binPath, fileSystem.exists(path) {\n                return path\n            }\n        }\n\n        return nil\n    }\n\n    /// Derive the plugin path needed to locate the Swift Testing macro plugin,\n    /// if such a path exists in the toolchain of the specified compiler.\n    ///\n    /// - Parameters:\n    ///   - derivedSwiftCompiler: The derived path of the Swift compiler to use\n    ///       when deriving the Swift Testing plugin path.\n    ///   - fileSystem: The file system instance to use when validating the path\n    ///       to return.\n    ///\n    /// - Returns: A path to the directory containing Swift Testing's macro\n    ///     plugin, or `nil` if the path does not exist or cannot be determined.\n    ///\n    /// The path returned is a directory containing a library, suitable for\n    /// passing to a client compiler via the `-plugin-path` flag.\n    private static func deriveSwiftTestingPluginPath(\n        derivedSwiftCompiler: Basics.AbsolutePath,\n        fileSystem: any FileSystem\n    ) -> AbsolutePath? {\n        guard let toolchainLibDir = try? toolchainLibDir(swiftCompilerPath: derivedSwiftCompiler) else {\n            return nil\n        }\n\n        if let pluginsPath = try? AbsolutePath(validating: \"swift/host/plugins/testing\", relativeTo: toolchainLibDir), fileSystem.exists(pluginsPath) {\n            return pluginsPath\n        }\n\n        return nil\n    }\n\n    public var sdkRootPath: AbsolutePath? {\n        configuration.sdkRootPath\n    }\n\n    public var metalToolchainPath: AbsolutePath? {\n        configuration.metalToolchainPath\n    }\n\n    public var metalToolchainId: String? {\n        configuration.metalToolchainId\n    }\n\n    public var swiftCompilerEnvironment: Environment {\n        configuration.swiftCompilerEnvironment\n    }\n\n    public var swiftCompilerFlags: [String] {\n        configuration.swiftCompilerFlags\n    }\n\n    public var swiftCompilerPathForManifests: AbsolutePath {\n        configuration.swiftCompilerPath\n    }\n\n    public var swiftPMLibrariesLocation: ToolchainConfiguration.SwiftPMLibrariesLocation {\n        configuration.swiftPMLibrariesLocation\n    }\n\n    public var xctestPath: AbsolutePath? {\n        configuration.xctestPath\n    }\n\n    public var swiftTestingPath: AbsolutePath? {\n        configuration.swiftTestingPath\n    }\n\n    private static func loadJSONResource<T: Decodable>(\n        config: AbsolutePath, type: T.Type, `default`: T\n    )\n        throws -> T\n    {\n        if localFileSystem.exists(config) {\n            return try JSONDecoder.makeWithDefaults().decode(\n                path: config,\n                fileSystem: localFileSystem,\n                as: type)\n        }\n\n        return `default`\n    }\n}\n\nextension Environment {\n    fileprivate var windowsSDKRoot: AbsolutePath? {\n        if let SDKROOT = self[\"SDKROOT\"], let sdkDir = try? AbsolutePath(validating: SDKROOT) {\n            return sdkDir\n        }\n        return nil\n    }\n}\n"
  },
  {
    "path": "Sources/PackageModel/WindowsToolchainInfo.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\npublic struct WindowsSDKSettings {\n    public struct DefaultProperties {\n        public enum Runtime: String, Decodable {\n        /// MultiThreadedDebugDLL\n        /// Use the debug variant of the C runtime with shared linking.\n        case multithreadedDebugDLL = \"MDd\"\n\n        /// MultiThreadedDLL\n        /// Use the release variant of the C runtime with shared linking.\n        case multithreadedDLL = \"MD\"\n\n        /// MultiThreadedDebug\n        /// Use the debug variant of the C runtime with static linking.\n        case multithreadedDebug = \"MTd\"\n\n        /// MultiThreaded\n        /// Use the release variant of the C runtime with static linking.\n        case multithreaded = \"MT\"\n        }\n\n        /// DEFAULT_USE_RUNTIME - specifies the C runtime variant to use\n        public let runtime: Runtime\n    }\n\n    public let defaults: DefaultProperties\n}\n\nextension WindowsSDKSettings.DefaultProperties: Decodable {\n    enum CodingKeys: String, CodingKey {\n    case runtime = \"DEFAULT_USE_RUNTIME\"\n    }\n}\n\nextension WindowsSDKSettings: Decodable {\n    enum CodingKeys: String, CodingKey {\n    case defaults = \"DefaultProperties\"\n    }\n}\n\nextension WindowsSDKSettings {\n    public init?(reading path: AbsolutePath, observabilityScope: ObservabilityScope?, filesystem: FileSystem) {\n        guard filesystem.exists(path) else {\n            observabilityScope?.emit(error: \"missing SDKSettings.plist at '\\(path)'\")\n            return nil\n        }\n\n        do {\n            let data: Data = try filesystem.readFileContents(path)\n            self = try PropertyListDecoder().decode(WindowsSDKSettings.self, from: data)\n        } catch {\n            observabilityScope?.emit(\n                error: \"failed to load SDKSettings.plist at '\\(path)'\",\n                underlyingError: error\n            )\n            return nil\n        }\n    }\n}\n\npublic struct WindowsPlatformInfo {\n    public struct DefaultProperties {\n        /// XCTEST_VERSION\n        /// specifies the version string of the bundled XCTest.\n        public let xctestVersion: String\n\n        /// SWIFT_TESTING_VERSION\n        /// specifies the version string of the bundled swift-testing.\n        public let swiftTestingVersion: String?\n\n        /// SWIFTC_FLAGS\n        /// Specifies extra flags to pass to swiftc from Swift Package Manager.\n        public let extraSwiftCFlags: [String]?\n    }\n\n    public let defaults: DefaultProperties\n}\n\nextension WindowsPlatformInfo.DefaultProperties: Decodable {\n    enum CodingKeys: String, CodingKey {\n    case xctestVersion = \"XCTEST_VERSION\"\n    case swiftTestingVersion = \"SWIFT_TESTING_VERSION\"\n    case extraSwiftCFlags = \"SWIFTC_FLAGS\"\n    }\n}\n\nextension WindowsPlatformInfo: Decodable {\n    enum CodingKeys: String, CodingKey {\n    case defaults = \"DefaultProperties\"\n    }\n}\n\nextension WindowsPlatformInfo {\n    public init?(reading path: AbsolutePath, observabilityScope: ObservabilityScope?, filesystem: FileSystem) {\n        guard filesystem.exists(path) else {\n            observabilityScope?.emit(error: \"missing Info.plist at '\\(path)'\")\n            return nil\n        }\n\n        do {\n            let data: Data = try filesystem.readFileContents(path)\n            self = try PropertyListDecoder().decode(WindowsPlatformInfo.self, from: data)\n        } catch {\n            observabilityScope?.emit(\n                error: \"failed to load Info.plist at '\\(path)'\",\n                underlyingError: error\n            )\n            return nil\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistry/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageRegistry STATIC\n  ChecksumTOFU.swift  \n  RegistryConfiguration.swift\n  RegistryClient.swift\n  RegistryDownloadsManager.swift\n  SignatureValidation.swift\n  SigningEntityTOFU.swift)\ntarget_link_libraries(PackageRegistry PUBLIC\n  Basics\n  PackageFingerprint\n  PackageLoading\n  PackageModel\n  PackageSigning\n  TSCBasic\n  TSCUtility)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageRegistry PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n"
  },
  {
    "path": "Sources/PackageRegistry/ChecksumTOFU.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Dispatch\n\nimport Basics\nimport PackageFingerprint\nimport PackageModel\nimport Foundation\n\nimport struct TSCUtility.Version\n\nstruct PackageVersionChecksumTOFU {\n    private let fingerprintStorage: PackageFingerprintStorage?\n    private let fingerprintCheckingMode: FingerprintCheckingMode\n    private let versionMetadataProvider: (PackageIdentity.RegistryIdentity, Version) async throws -> RegistryClient\n        .PackageVersionMetadata\n\n    init(\n        fingerprintStorage: PackageFingerprintStorage?,\n        fingerprintCheckingMode: FingerprintCheckingMode,\n        versionMetadataProvider: @escaping (PackageIdentity.RegistryIdentity, Version) async throws -> RegistryClient\n            .PackageVersionMetadata\n    ) {\n        self.fingerprintStorage = fingerprintStorage\n        self.fingerprintCheckingMode = fingerprintCheckingMode\n        self.versionMetadataProvider = versionMetadataProvider\n    }\n\n    // MARK: - source archive\n    func validateSourceArchive(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        checksum: String,\n        timeout: DispatchTimeInterval?,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        let expectedChecksum = try await self.getExpectedChecksum(\n            registry: registry,\n            package: package,\n            version: version,\n            timeout: timeout,\n            observabilityScope: observabilityScope\n        )\n\n        if checksum != expectedChecksum {\n            switch self.fingerprintCheckingMode {\n            case .strict:\n                throw RegistryError.invalidChecksum(expected: expectedChecksum, actual: checksum)\n            case .warn:\n                observabilityScope\n                    .emit(\n                        warning: \"the checksum \\(checksum) for source archive of \\(package) \\(version) does not match previously recorded value \\(expectedChecksum)\"\n                    )\n            }\n        }\n    }\n\n    @available(*, noasync, message: \"Use the async alternative\")\n    func validateSourceArchive(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        checksum: String,\n        timeout: DispatchTimeInterval?,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<Void, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.validateSourceArchive(\n                registry: registry,\n                package: package,\n                version: version,\n                checksum: checksum,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    private func getExpectedChecksum(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        timeout: DispatchTimeInterval?,\n        observabilityScope: ObservabilityScope\n    ) async throws -> String {\n        // We either use a previously recorded checksum, or fetch it from the registry.\n        if let savedChecksum = try? self.readFromStorage(package: package, version: version, contentType: .sourceCode, observabilityScope: observabilityScope) {\n            return savedChecksum\n        }\n\n        // Try fetching checksum from registry if:\n        //   - No storage available\n        //   - Checksum not found in storage\n        //   - Reading from storage resulted in error\n        var checksum: String\n        do {\n            let versionMetadata = try await self.versionMetadataProvider(package, version)\n            guard let sourceArchiveResource = versionMetadata.sourceArchive else {\n                throw RegistryError.missingSourceArchive\n            }\n            guard let archiveChecksum = sourceArchiveResource.checksum else {\n                throw RegistryError.sourceArchiveMissingChecksum(\n                    registry: registry,\n                    package: package.underlying,\n                    version: version\n                )\n            }\n            checksum = archiveChecksum\n        } catch {\n            throw RegistryError.failedRetrievingReleaseChecksum(\n                registry: registry,\n                package: package.underlying,\n                version: version,\n                error: error\n            )\n        }\n        try self.writeToStorage(\n            registry: registry,\n            package: package,\n            version: version,\n            checksum: checksum,\n            contentType: .sourceCode,\n            observabilityScope: observabilityScope\n        )\n        return checksum\n    }\n\n    func validateManifest(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        toolsVersion: ToolsVersion?,\n        checksum: String,\n        timeout: DispatchTimeInterval?,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        let contentType = Fingerprint.ContentType.manifest(toolsVersion)\n\n        guard let expectedChecksum = try? self.readFromStorage(\n            package: package,\n            version: version,\n            contentType: .manifest(toolsVersion),\n            observabilityScope: observabilityScope\n        ) else {\n            return try self.writeToStorage(\n                registry: registry,\n                package: package,\n                version: version,\n                checksum: checksum,\n                contentType: .manifest(toolsVersion),\n                observabilityScope: observabilityScope\n            )\n        }\n        // Previously recorded checksum\n        if checksum != expectedChecksum {\n            switch self.fingerprintCheckingMode {\n            case .strict:\n                throw RegistryError.invalidChecksum(expected: expectedChecksum, actual: checksum)\n            case .warn:\n                observabilityScope\n                    .emit(\n                        warning: \"the checksum \\(checksum) for \\(contentType) of \\(package) \\(version) does not match previously recorded value \\(expectedChecksum)\"\n                    )\n            }\n        }\n    }\n\n    // MARK: - storage helpers\n\n    private func readFromStorage(\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        contentType: Fingerprint.ContentType,\n        observabilityScope: ObservabilityScope\n    ) throws -> String? {\n        guard let fingerprintStorage else {\n            return nil\n        }\n\n        do {\n            return try fingerprintStorage.get(\n                package: package.underlying,\n                version: version,\n                kind: .registry,\n                contentType: contentType,\n                observabilityScope: observabilityScope\n            ).value\n        } catch PackageFingerprintStorageError.notFound {\n            return nil\n        } catch {\n            observabilityScope\n                .emit(\n                    error: \"failed to get registry fingerprint for \\(contentType) of \\(package) \\(version) from storage\",\n                    underlyingError: error\n                )\n            throw error\n        }\n    }\n\n    private func writeToStorage(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        checksum: String,\n        contentType: Fingerprint.ContentType,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        guard let fingerprintStorage else {\n            return\n        }\n\n        let fingerprint = Fingerprint(origin: .registry(registry.url), value: checksum, contentType: contentType)\n        do {\n            try fingerprintStorage.put(\n                package: package.underlying,\n                version: version,\n                fingerprint: fingerprint,\n                observabilityScope: observabilityScope\n            )\n        } catch PackageFingerprintStorageError.conflict(_, let existing){\n            switch self.fingerprintCheckingMode {\n            case .strict:\n                throw RegistryError.checksumChanged(latest: checksum, previous: existing.value)\n            case .warn:\n                observabilityScope\n                    .emit(\n                        warning: \"the checksum \\(checksum) for \\(contentType) of \\(package) \\(version) from \\(registry.url.absoluteString) does not match previously recorded value \\(existing.value) from \\(String(describing: existing.origin.url?.absoluteString))\"\n                    )\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistry/RegistryClient.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport Foundation\nimport PackageFingerprint\nimport PackageLoading\nimport PackageModel\nimport PackageSigning\n\nimport protocol TSCBasic.HashAlgorithm\n\nimport struct TSCUtility.Version\n\npublic protocol RegistryClientDelegate {\n    func onUnsigned(registry: Registry, package: PackageIdentity, version: Version, completion: (Bool) -> Void)\n    func onUntrusted(registry: Registry, package: PackageIdentity, version: Version, completion: (Bool) -> Void)\n}\n\n/// Package registry client.\n/// API specification: https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/PackageRegistry/Registry.md\npublic final class RegistryClient: AsyncCancellable {\n    public typealias Delegate = RegistryClientDelegate\n\n    private static let apiVersion: APIVersion = .v1\n    private static let availabilityCacheTTL: DispatchTimeInterval = .seconds(5 * 60)\n    private static let metadataCacheTTL: DispatchTimeInterval = .seconds(60 * 60)\n\n    private var configuration: RegistryConfiguration\n    private let archiverProvider: (FileSystem) -> Archiver\n    private let httpClient: HTTPClient\n    private let authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?\n    private let fingerprintStorage: PackageFingerprintStorage?\n    private let fingerprintCheckingMode: FingerprintCheckingMode\n    private let skipSignatureValidation: Bool\n    private let signingEntityStorage: PackageSigningEntityStorage?\n    private let signingEntityCheckingMode: SigningEntityCheckingMode\n    private let jsonDecoder: JSONDecoder\n    private let delegate: Delegate?\n    private let checksumAlgorithm: HashAlgorithm\n\n    private let availabilityCache = ThreadSafeKeyValueStore<\n        URL,\n        (status: Result<AvailabilityStatus, Error>, expires: DispatchTime)\n    >()\n\n    private let metadataCache = ThreadSafeKeyValueStore<\n        MetadataCacheKey,\n        (metadata: Serialization.VersionMetadata, expires: DispatchTime)\n    >()\n\n    public init(\n        configuration: RegistryConfiguration,\n        fingerprintStorage: PackageFingerprintStorage?,\n        fingerprintCheckingMode: FingerprintCheckingMode,\n        skipSignatureValidation: Bool,\n        signingEntityStorage: PackageSigningEntityStorage?,\n        signingEntityCheckingMode: SigningEntityCheckingMode,\n        authorizationProvider: AuthorizationProvider? = .none,\n        customHTTPClient: HTTPClient? = .none,\n        customArchiverProvider: ((FileSystem) -> Archiver)? = .none,\n        delegate: Delegate?,\n        checksumAlgorithm: HashAlgorithm\n    ) {\n        self.configuration = configuration\n\n        if let authorizationProvider {\n            self.authorizationProvider = { url in\n                guard let registryAuthentication = try? configuration.authentication(for: url) else {\n                    return .none\n                }\n                guard let (user, password) = authorizationProvider.authentication(for: url) else {\n                    return .none\n                }\n\n                switch registryAuthentication.type {\n                case .basic:\n                    let authorizationString = \"\\(user):\\(password)\"\n                    let authorizationData = Data(authorizationString.utf8)\n                    return \"Basic \\(authorizationData.base64EncodedString())\"\n                case .token: // `user` value is irrelevant in this case\n                    return \"Bearer \\(password)\"\n                }\n            }\n        } else {\n            self.authorizationProvider = .none\n        }\n\n        self.httpClient = customHTTPClient ?? HTTPClient()\n        self.archiverProvider = customArchiverProvider ?? { fileSystem in ZipArchiver(fileSystem: fileSystem) }\n        self.fingerprintStorage = fingerprintStorage\n        self.fingerprintCheckingMode = fingerprintCheckingMode\n        self.skipSignatureValidation = skipSignatureValidation\n        self.signingEntityStorage = signingEntityStorage\n        self.signingEntityCheckingMode = signingEntityCheckingMode\n        self.jsonDecoder = JSONDecoder.makeWithDefaults()\n        self.delegate = delegate\n        self.checksumAlgorithm = checksumAlgorithm\n    }\n\n    public var explicitlyConfigured: Bool {\n        self.configuration.explicitlyConfigured\n    }\n\n    // not thread safe\n    // marked public for cross module visibility\n    public var defaultRegistry: Registry? {\n        get {\n            self.configuration.defaultRegistry\n        }\n        set {\n            self.configuration.defaultRegistry = newValue\n        }\n    }\n\n    /// Cancel any outstanding requests\n    public func cancel(deadline: DispatchTime) async throws {\n        await self.httpClient.cancel(deadline: deadline)\n    }\n\n    public func changeSigningEntityFromVersion(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.signingEntityStorage?.changeSigningEntityFromVersion(\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            origin: origin,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    public func getPackageMetadata(\n        package: PackageIdentity,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope\n    ) async throws -> PackageMetadata {\n        let (registryIdentity, registry) = try self.unwrapRegistry(from: package)\n\n        try await withAvailabilityCheck(\n            registry: registry,\n            observabilityScope: observabilityScope\n        )\n\n        guard var components = URLComponents(url: registry.url, resolvingAgainstBaseURL: true) else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n        components.appendPathComponents(\"\\(registryIdentity.scope)\", \"\\(registryIdentity.name)\")\n        guard let url = components.url else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        // If the responses are paginated then iterate until we've exasuasted all the pages and have a full versions list.\n        func iterateResponses(url: URL, existingMetadata: PackageMetadata) async throws -> PackageMetadata {\n            try Task.checkCancellation()\n\n            let metadata = try await self._getIndividualPackageMetadata(\n                url: url,\n                registry: registry,\n                package: registryIdentity,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n\n            let mergedMetadata = PackageMetadata(\n                registry: registry,\n                versions: existingMetadata.versions + metadata.versions,\n                alternateLocations: existingMetadata.alternateLocations.count > 0\n                    ? existingMetadata.alternateLocations\n                    : metadata.alternateLocations,\n                nextPage: metadata.nextPage\n            )\n            if let nextPage = mergedMetadata.nextPage?.url {\n                return try await iterateResponses(\n                    url: nextPage,\n                    existingMetadata: mergedMetadata\n                )\n            } else {\n                return PackageMetadata(\n                    registry: registry,\n                    versions: mergedMetadata.versions.sorted(by: >),\n                    alternateLocations: mergedMetadata.alternateLocations,\n                    nextPage: mergedMetadata.nextPage\n                )\n            }\n        }\n\n        return try await iterateResponses(\n            url: url,\n            existingMetadata: PackageMetadata(\n                registry: registry,\n                versions: [],\n                alternateLocations: [],\n                nextPage: nil\n            )\n        )\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    public func getPackageMetadata(\n        package: PackageIdentity,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<PackageMetadata, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.getPackageMetadata(\n                package: package,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    private func _getIndividualPackageMetadata(\n        url: URL,\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        timeout: DispatchTimeInterval?,\n        observabilityScope: ObservabilityScope\n    ) async throws -> PackageMetadata {\n        let start = DispatchTime.now()\n        observabilityScope.emit(info: \"retrieving \\(package) metadata from \\(url)\")\n\n        let response: HTTPClient.Response\n        do {\n            response = try await self.httpClient.get(\n                url,\n                headers: [\"Accept\": self.acceptHeader(mediaType: .json)],\n                options: self.defaultRequestOptions(timeout: timeout)\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.failedRetrievingReleases(registry: registry, package: package.underlying, error: error)\n        }\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(url): \\(response.statusCode) in \\(start.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        switch response.statusCode {\n        case 200:\n            let packageMetadata = try response.parseJSON(\n                Serialization.PackageMetadata.self,\n                decoder: self.jsonDecoder\n            )\n\n            let versions = packageMetadata.releases.filter { $0.value.problem == nil }\n                .compactMap { Version($0.key) }\n\n            let alternateLocations = response.headers.parseAlternativeLocationLinks()\n            let paginationLinks = response.headers.parsePaginationLinks()\n\n            return PackageMetadata(\n                registry: registry,\n                versions: versions,\n                alternateLocations: alternateLocations.map(\\.url),\n                nextPage: paginationLinks.first { $0.kind == .next }?.url\n            )\n        case 404:\n            throw RegistryError.failedRetrievingReleases(\n                registry: registry,\n                package: package.underlying,\n                error: RegistryError.packageNotFound\n            )\n        default:\n            throw RegistryError.failedRetrievingReleases(\n                registry: registry,\n                package: package.underlying,\n                error: self.unexpectedStatusError(response, expectedStatus: [200, 404])\n            )\n        }\n    }\n\n    public func getPackageVersionMetadata(\n        package: PackageIdentity,\n        version: Version,\n        timeout: DispatchTimeInterval? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> PackageVersionMetadata {\n        let (package, registry) = try self.unwrapRegistry(from: package)\n\n        try await withAvailabilityCheck(\n            registry: registry,\n            observabilityScope: observabilityScope\n        )\n\n        let versionMetadata = try await self._getRawPackageVersionMetadata(\n            registry: registry,\n            package: package,\n            version: version,\n            timeout: timeout,\n            observabilityScope: observabilityScope\n        )\n\n        var resourceSigning: [(resource: RegistryClient.Serialization.VersionMetadata.Resource, signingEntity: SigningEntity?)] = []\n        for resource in versionMetadata.resources {\n            guard let signing = resource.signing,\n                  let signatureData = Data(base64Encoded: signing.signatureBase64Encoded),\n                  let signatureFormat = SignatureFormat(rawValue: signing.signatureFormat) else {\n                resourceSigning.append((resource, nil))\n                continue\n            }\n            let configuration = self.configuration.signing(for: package, registry: registry)\n            let result = try? await SignatureValidation.extractSigningEntity(\n                signature: [UInt8](signatureData),\n                signatureFormat: signatureFormat,\n                configuration: configuration,\n                fileSystem: fileSystem\n            )\n            resourceSigning.append((resource, result))\n        }\n\n        let packageVersionMetadata = PackageVersionMetadata(\n            registry: registry,\n            licenseURL: versionMetadata.metadata?.licenseURL.flatMap { URL(string: $0) },\n            readmeURL: versionMetadata.metadata?.readmeURL.flatMap { URL(string: $0) },\n            repositoryURLs: versionMetadata.metadata?.repositoryURLs?.compactMap { SourceControlURL($0) },\n            resources: resourceSigning.map {\n                .init(\n                    name: $0.resource.name,\n                    type: $0.resource.type,\n                    checksum: $0.resource.checksum,\n                    signing: $0.resource.signing.flatMap {\n                        PackageVersionMetadata.Signing(\n                            signatureBase64Encoded: $0.signatureBase64Encoded,\n                            signatureFormat: $0.signatureFormat\n                        )\n                    },\n                    signingEntity: $0.signingEntity\n                )\n            },\n            author: versionMetadata.metadata?.author.map {\n                .init(\n                    name: $0.name,\n                    email: $0.email,\n                    description: $0.description,\n                    organization: $0.organization.map {\n                        .init(\n                            name: $0.name,\n                            email: $0.email,\n                            description: $0.description,\n                            url: $0.url.flatMap { URL(string: $0) }\n                        )\n                    },\n                    url: $0.url.flatMap { URL(string: $0) }\n                )\n            },\n            description: versionMetadata.metadata?.description,\n            publishedAt: versionMetadata.metadata?.originalPublicationTime ?? versionMetadata.publishedAt\n        )\n\n        return packageVersionMetadata\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    public func getPackageVersionMetadata(\n        package: PackageIdentity,\n        version: Version,\n        timeout: DispatchTimeInterval? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<PackageVersionMetadata, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.getPackageVersionMetadata(\n                package: package,\n                version: version,\n                timeout: timeout,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    private func _getRawPackageVersionMetadata(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        timeout: DispatchTimeInterval?,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Serialization.VersionMetadata {\n        let cacheKey = MetadataCacheKey(registry: registry, package: package, version: version)\n        if let cached = self.metadataCache[cacheKey], cached.expires > .now() {\n            return cached.metadata\n        }\n\n        guard var components = URLComponents(url: registry.url, resolvingAgainstBaseURL: true) else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        components.appendPathComponents(\"\\(package.scope)\", \"\\(package.name)\", \"\\(version)\")\n        guard let url = components.url else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        let start = DispatchTime.now()\n        observabilityScope.emit(info: \"retrieving \\(package) \\(version) metadata from \\(url)\")\n\n        let response: HTTPClient.Response\n        do {\n            response = try await self.httpClient.get(\n                url,\n                headers: [\"Accept\": self.acceptHeader(mediaType: .json)],\n                options: self.defaultRequestOptions(timeout: timeout)\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.failedRetrievingReleaseInfo(\n                registry: registry,\n                package: package.underlying,\n                version: version,\n                error: error\n            )\n        }\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(url): \\(response.statusCode) in \\(start.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        switch response.statusCode {\n        case 200:\n            let metadata = try response.parseJSON(\n                Serialization.VersionMetadata.self,\n                decoder: self.jsonDecoder\n            )\n            self.metadataCache[cacheKey] = (metadata: metadata, expires: .now() + Self.metadataCacheTTL)\n            return metadata\n        case 404:\n            throw RegistryError.failedRetrievingReleaseInfo(\n                registry: registry,\n                package: package.underlying,\n                version: version,\n                error: RegistryError.packageVersionNotFound\n            )\n        default:\n            throw RegistryError.failedRetrievingReleaseInfo(\n                registry: registry,\n                package: package.underlying,\n                version: version,\n                error: self.unexpectedStatusError(response, expectedStatus: [200, 404])\n            )\n        }\n    }\n\n    public func getAvailableManifests(\n        package: PackageIdentity,\n        version: Version,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope\n    ) async throws -> [String: (toolsVersion: ToolsVersion, content: String?)]{\n        let (registryIdentity, registry) = try self.unwrapRegistry(from: package)\n\n        try await withAvailabilityCheck(\n            registry: registry,\n            observabilityScope: observabilityScope\n        )\n\n        // first get the release metadata to see if archive is signed (therefore manifest is also signed)\n        let versionMetadata = try await self.getPackageVersionMetadata(\n            package: package,\n            version: version,\n            timeout: timeout,\n            fileSystem: localFileSystem,\n            observabilityScope: observabilityScope\n        )\n        guard var components = URLComponents(url: registry.url, resolvingAgainstBaseURL: true) else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        components.appendPathComponents(\n            \"\\(registryIdentity.scope)\",\n            \"\\(registryIdentity.name)\",\n            \"\\(version)\",\n            Manifest.filename\n        )\n\n        guard let url = components.url else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        let start = DispatchTime.now()\n        observabilityScope.emit(info: \"retrieving available manifests for \\(package) \\(version) from \\(url)\")\n\n        let response: LegacyHTTPClient.Response\n        do {\n            response = try await self.httpClient.get(\n                url,\n                headers: [\"Accept\": self.acceptHeader(mediaType: .swift)],\n                options: self.defaultRequestOptions(timeout: timeout)\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.failedRetrievingManifest(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: error\n            )\n        }\n\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(url): \\(response.statusCode) in \\(start.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        // signature validation helper\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: self.skipSignatureValidation,\n            signingEntityStorage: self.signingEntityStorage,\n            signingEntityCheckingMode: self.signingEntityCheckingMode,\n            versionMetadataProvider: { _, _ in versionMetadata },\n            delegate: RegistryClientSignatureValidationDelegate(underlying: self.delegate)\n        )\n\n        // checksum TOFU validation helper\n        let checksumTOFU = PackageVersionChecksumTOFU(\n            fingerprintStorage: self.fingerprintStorage,\n            fingerprintCheckingMode: self.fingerprintCheckingMode,\n            versionMetadataProvider: { _, _ in versionMetadata }\n        )\n\n        switch response.statusCode {\n        case 200:\n            try response.validateAPIVersion()\n            try response.validateContentType(.swift)\n\n            guard let data = response.body else {\n                throw RegistryError.invalidResponse\n            }\n            let manifestContent = String(decoding: data, as: UTF8.self)\n\n            let _ = try await signatureValidation.validate(\n                registry: registry,\n                package: registryIdentity,\n                version: version,\n                toolsVersion: .none,\n                manifestContent: manifestContent,\n                configuration: self.configuration.signing(for: registryIdentity, registry: registry),\n                timeout: timeout,\n                fileSystem: localFileSystem,\n                observabilityScope: observabilityScope\n            )\n\n            // TODO: expose Data based API on checksumAlgorithm\n            let actualChecksum = self.checksumAlgorithm.hash(.init(data))\n                .hexadecimalRepresentation\n\n            do {\n                try checksumTOFU.validateManifest(\n                    registry: registry,\n                    package: registryIdentity,\n                    version: version,\n                    toolsVersion: .none,\n                    checksum: actualChecksum,\n                    timeout: timeout,\n                    observabilityScope: observabilityScope\n                )\n                do {\n                    var result = [String: (toolsVersion: ToolsVersion, content: String?)]()\n                    let toolsVersion = try ToolsVersionParser.parse(utf8String: manifestContent)\n                    result[Manifest.filename] = (\n                        toolsVersion: toolsVersion,\n                        content: manifestContent\n                    )\n\n                    let alternativeManifests = try response.headers.parseManifestLinks()\n                    for alternativeManifest in alternativeManifests {\n                        result[alternativeManifest.filename] = (\n                            toolsVersion: alternativeManifest.toolsVersion,\n                            content: .none\n                        )\n                    }\n                    return result\n                } catch {\n                    throw RegistryError.failedRetrievingManifest(\n                        registry: registry,\n                        package: registryIdentity.underlying,\n                        version: version,\n                        error: error\n                    )\n                }\n            }\n        case 404:\n            throw RegistryError.failedRetrievingManifest(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: RegistryError.packageVersionNotFound\n            )\n        default:\n            throw RegistryError.failedRetrievingManifest(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: self.unexpectedStatusError(response, expectedStatus: [200, 404])\n            )\n        }\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    public func getAvailableManifests(\n        package: PackageIdentity,\n        version: Version,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<[String: (toolsVersion: ToolsVersion, content: String?)], Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.getAvailableManifests(\n                package: package,\n                version: version,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    public func getManifestContent(\n        package: PackageIdentity,\n        version: Version,\n        customToolsVersion: ToolsVersion?,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope\n    ) async throws -> String {\n        let (registryIdentity, registry) = try self.unwrapRegistry(from: package)\n\n        try await withAvailabilityCheck(\n            registry: registry,\n            observabilityScope: observabilityScope\n        )\n\n        // first get the release metadata to see if archive is signed (therefore manifest is also signed)\n        let versionMetadata = try await self.getPackageVersionMetadata(\n            package: package,\n            version: version,\n            timeout: timeout,\n            fileSystem: localFileSystem,\n            observabilityScope: observabilityScope\n        )\n        guard var components = URLComponents(url: registry.url, resolvingAgainstBaseURL: true) else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n        components.appendPathComponents(\n            \"\\(registryIdentity.scope)\",\n            \"\\(registryIdentity.name)\",\n            \"\\(version)\",\n            Manifest.filename\n        )\n\n        if let toolsVersion = customToolsVersion {\n            components.queryItems = [\n                URLQueryItem(name: \"swift-version\", value: toolsVersion.description),\n            ]\n        }\n\n        guard let url = components.url else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        let start = DispatchTime.now()\n        observabilityScope.emit(info: \"retrieving \\(package) \\(version) manifest from \\(url)\")\n\n        let response: HTTPClient.Response\n        do {\n            response = try await self.httpClient.get(\n                url,\n                headers: [\"Accept\": self.acceptHeader(mediaType: .swift)],\n                options: self.defaultRequestOptions(timeout: timeout)\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.failedRetrievingManifest(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: error\n            )\n        }\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(url): \\(response.statusCode) in \\(start.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        // signature validation helper\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: self.skipSignatureValidation,\n            signingEntityStorage: self.signingEntityStorage,\n            signingEntityCheckingMode: self.signingEntityCheckingMode,\n            versionMetadataProvider: { _, _ in versionMetadata },\n            delegate: RegistryClientSignatureValidationDelegate(underlying: self.delegate)\n        )\n\n        // checksum TOFU validation helper\n        let checksumTOFU = PackageVersionChecksumTOFU(\n            fingerprintStorage: self.fingerprintStorage,\n            fingerprintCheckingMode: self.fingerprintCheckingMode,\n            versionMetadataProvider: { _, _ in versionMetadata }\n        )\n\n        switch response.statusCode {\n        case 200:\n            try response.validateAPIVersion(isOptional: true)\n            try response.validateContentType(.swift)\n\n            guard let data = response.body else {\n                throw RegistryError.invalidResponse\n            }\n            let manifestContent = String(decoding: data, as: UTF8.self)\n\n            let _ = try await signatureValidation.validate(\n                registry: registry,\n                package: registryIdentity,\n                version: version,\n                toolsVersion: customToolsVersion,\n                manifestContent: manifestContent,\n                configuration: self.configuration.signing(for: registryIdentity, registry: registry),\n                timeout: timeout,\n                fileSystem: localFileSystem,\n                observabilityScope: observabilityScope\n            )\n\n            // TODO: expose Data based API on checksumAlgorithm\n            let actualChecksum = self.checksumAlgorithm.hash(.init(data))\n                .hexadecimalRepresentation\n\n            try checksumTOFU.validateManifest(\n                registry: registry,\n                package: registryIdentity,\n                version: version,\n                toolsVersion: customToolsVersion,\n                checksum: actualChecksum,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n\n            return manifestContent\n        case 404:\n            throw RegistryError.failedRetrievingManifest(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: RegistryError.packageVersionNotFound\n            )\n        default:\n            throw RegistryError.failedRetrievingManifest(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: self.unexpectedStatusError(response, expectedStatus: [200, 404])\n            )\n        }\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    public func getManifestContent(\n        package: PackageIdentity,\n        version: Version,\n        customToolsVersion: ToolsVersion?,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<String, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.getManifestContent(\n                package: package,\n                version: version,\n                customToolsVersion: customToolsVersion,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    public func downloadSourceArchive(\n        package: PackageIdentity,\n        version: Version,\n        destinationPath: AbsolutePath,\n        progressHandler: (@Sendable (_ bytesReceived: Int64, _ totalBytes: Int64?) -> Void)?,\n        timeout: DispatchTimeInterval? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        let (registryIdentity, registry) = try self.unwrapRegistry(from: package)\n\n        try await withAvailabilityCheck(\n            registry: registry,\n            observabilityScope: observabilityScope\n        )\n\n        // first get the release metadata\n        // TODO: this should be included in the archive to save the extra HTTP call\n        let versionMetadata = try await self.getPackageVersionMetadata(\n            package: package,\n            version: version,\n            timeout: timeout,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n        // download archive\n        guard var components = URLComponents(url: registry.url, resolvingAgainstBaseURL: true) else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n        components.appendPathComponents(\"\\(registryIdentity.scope)\", \"\\(registryIdentity.name)\", \"\\(version).zip\")\n\n        guard let url = components.url else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        // prepare target download locations\n        let downloadPath = destinationPath.appending(extension: \"zip\")\n        // prepare directories\n        if !fileSystem.exists(downloadPath.parentDirectory) {\n            try fileSystem.createDirectory(downloadPath.parentDirectory, recursive: true)\n        }\n\n        // clear out download path if exists\n        try fileSystem.removeFileTree(downloadPath)\n        // validate that the destination does not already exist\n        guard !fileSystem.exists(destinationPath) else {\n            throw RegistryError.pathAlreadyExists(destinationPath)\n        }\n\n        // signature validation helper\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: self.skipSignatureValidation,\n            signingEntityStorage: self.signingEntityStorage,\n            signingEntityCheckingMode: self.signingEntityCheckingMode,\n            versionMetadataProvider: { _, _ in versionMetadata },\n            delegate: RegistryClientSignatureValidationDelegate(underlying: self.delegate)\n        )\n\n        // checksum TOFU validation helper\n        let checksumTOFU = PackageVersionChecksumTOFU(\n            fingerprintStorage: self.fingerprintStorage,\n            fingerprintCheckingMode: self.fingerprintCheckingMode,\n            versionMetadataProvider: { _, _ in versionMetadata }\n        )\n\n        let downloadStart = DispatchTime.now()\n        observabilityScope.emit(info: \"downloading \\(package) \\(version) source archive from \\(url)\")\n\n        let response: HTTPClient.Response\n        do {\n            response = try await self.httpClient.download(\n                url,\n                headers: [\"Accept\": self.acceptHeader(mediaType: .zip)],\n                options: self.defaultRequestOptions(timeout: timeout),\n                progressHandler: progressHandler,\n                fileSystem: fileSystem,\n                destination: downloadPath\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.failedDownloadingSourceArchive(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: error\n            )\n        }\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(url): \\(response.statusCode) in \\(downloadStart.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        switch response.statusCode {\n        case 200:\n            try response.validateAPIVersion(isOptional: true)\n            try response.validateContentType(.zip)\n\n            let archiveContent: Data = try fileSystem.readFileContents(downloadPath)\n            // TODO: expose Data based API on checksumAlgorithm\n            let actualChecksum = self.checksumAlgorithm.hash(.init(archiveContent))\n                .hexadecimalRepresentation\n\n            observabilityScope\n                .emit(\n                    debug: \"performing TOFU checks on \\(package) \\(version) source archive (checksum: '\\(actualChecksum)'\"\n                )\n            let signingEntity = try await signatureValidation.validate(\n                registry: registry,\n                package: registryIdentity,\n                version: version,\n                content: archiveContent,\n                configuration: self.configuration.signing(for: registryIdentity, registry: registry),\n                timeout: timeout,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n\n            try await checksumTOFU.validateSourceArchive(\n                registry: registry,\n                package: registryIdentity,\n                version: version,\n                checksum: actualChecksum,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n\n            do {\n                // validate that the destination does not already exist\n                // (again, as this is async)\n                guard !fileSystem.exists(destinationPath) else {\n                    throw RegistryError.pathAlreadyExists(destinationPath)\n                }\n                try fileSystem.createDirectory(\n                    destinationPath,\n                    recursive: true\n                )\n                // extract the content\n                let extractStart = DispatchTime.now()\n                observabilityScope\n                    .emit(\n                        debug: \"extracting \\(package) \\(version) source archive to '\\(destinationPath)'\"\n                    )\n                let archiver = self.archiverProvider(fileSystem)\n                // TODO: Bail if archive contains relative paths or overlapping files\n                do {\n                    try await archiver.extract(from: downloadPath, to: destinationPath)\n                    defer {\n                        try? fileSystem.removeFileTree(downloadPath)\n                    }\n                    observabilityScope\n                        .emit(\n                            debug: \"extracted \\(package) \\(version) source archive to '\\(destinationPath)' in \\(extractStart.distance(to: .now()).descriptionInSeconds)\"\n                        )\n\n                    // strip first level component\n                    try fileSystem.stripFirstLevel(of: destinationPath)\n\n                    // write down copy of version metadata\n                    let registryMetadataPath = destinationPath.appending(component: RegistryReleaseMetadataStorage.fileName)\n                    observabilityScope\n                        .emit(\n                            debug: \"saving \\(package) \\(version) metadata to '\\(registryMetadataPath)'\"\n                        )\n\n                    try RegistryReleaseMetadataStorage.save(\n                        metadata: versionMetadata,\n                        signingEntity: signingEntity,\n                        to: registryMetadataPath,\n                        fileSystem: fileSystem\n                    )\n                } catch {\n                    throw StringError(\n                        \"failed extracting '\\(downloadPath)' to '\\(destinationPath)': \\(error.interpolationDescription)\"\n                    )\n                }\n            } catch {\n                throw RegistryError.failedDownloadingSourceArchive(\n                    registry: registry,\n                    package: registryIdentity.underlying,\n                    version: version,\n                    error: error\n                )\n            }\n        case 404:\n            throw RegistryError.failedDownloadingSourceArchive(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: RegistryError.packageVersionNotFound\n            )\n        default:\n            throw RegistryError.failedDownloadingSourceArchive(\n                registry: registry,\n                package: registryIdentity.underlying,\n                version: version,\n                error: self.unexpectedStatusError(response, expectedStatus: [200, 404])\n            )\n        }\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    public func downloadSourceArchive(\n        package: PackageIdentity,\n        version: Version,\n        destinationPath: AbsolutePath,\n        progressHandler: (@Sendable (_ bytesReceived: Int64, _ totalBytes: Int64?) -> Void)?,\n        timeout: DispatchTimeInterval? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<Void, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.downloadSourceArchive(\n                package: package,\n                version: version,\n                destinationPath: destinationPath,\n                progressHandler: progressHandler,\n                timeout: timeout,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    public func lookupIdentities(\n        scmURL: SourceControlURL,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Set<PackageIdentity> {\n        guard let registry = self.configuration.defaultRegistry else {\n            throw RegistryError.registryNotConfigured(scope: nil)\n        }\n\n        try await withAvailabilityCheck(\n            registry: registry,\n            observabilityScope: observabilityScope\n        )\n\n        guard var components = URLComponents(url: registry.url, resolvingAgainstBaseURL: true) else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n        components.appendPathComponents(\"identifiers\")\n\n        components.queryItems = [\n            URLQueryItem(name: \"url\", value: scmURL.absoluteString),\n        ]\n\n        guard let url = components.url else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        let start = DispatchTime.now()\n        observabilityScope.emit(info: \"looking up identity for \\(scmURL) from \\(url)\")\n\n        let response: HTTPClient.Response\n        do {\n            response = try await self.httpClient.get(\n                url,\n                headers: [\"Accept\": self.acceptHeader(mediaType: .json)],\n                options: self.defaultRequestOptions(timeout: timeout)\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.failedIdentityLookup(registry: registry, scmURL: scmURL, error: error)\n        }\n\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(url): \\(response.statusCode) in \\(start.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        switch response.statusCode {\n        case 200:\n            let packageIdentities = try response.parseJSON(\n                Serialization.PackageIdentifiers.self,\n                decoder: self.jsonDecoder\n            )\n            observabilityScope.emit(debug: \"matched identities for \\(scmURL): \\(packageIdentities)\")\n            return Set(packageIdentities.identifiers.map(PackageIdentity.plain))\n        case 404:\n            // 404 is valid, no identities mapped\n            return []\n        default:\n            throw RegistryError.failedIdentityLookup(\n                registry: registry,\n                scmURL: scmURL,\n                error: self.unexpectedStatusError(response, expectedStatus: [200, 404])\n            )\n        }\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    public func lookupIdentities(\n        scmURL: SourceControlURL,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<Set<PackageIdentity>, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.lookupIdentities(\n                scmURL: scmURL,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    public func login(\n        loginURL: URL,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        let start = DispatchTime.now()\n        observabilityScope.emit(info: \"logging-in into \\(loginURL)\")\n\n        let response: LegacyHTTPClient.Response\n        do {\n            response = try await self.httpClient.post(\n                loginURL,\n                body: nil,\n                options: self.defaultRequestOptions(timeout: timeout)\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.loginFailed(url: loginURL, error: error)\n        }\n\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(loginURL): \\(response.statusCode) in \\(start.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        switch response.statusCode {\n        case 200:\n            return\n        default:\n            throw RegistryError.loginFailed(url: loginURL, error: self.unexpectedStatusError(response, expectedStatus: [200]))\n        }\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    public func login(\n        loginURL: URL,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<Void, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.login(\n                loginURL: loginURL,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    public func publish(\n        registryURL: URL,\n        packageIdentity: PackageIdentity,\n        packageVersion: Version,\n        packageArchive: AbsolutePath,\n        packageMetadata: AbsolutePath?,\n        signature: [UInt8]?,\n        metadataSignature: [UInt8]?,\n        signatureFormat: SignatureFormat?,\n        timeout: DispatchTimeInterval? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<PublishResult, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.publish(\n                registryURL: registryURL,\n                packageIdentity: packageIdentity,\n                packageVersion: packageVersion,\n                packageArchive: packageArchive,\n                packageMetadata: packageMetadata,\n                signature: signature,\n                metadataSignature: metadataSignature,\n                signatureFormat: signatureFormat,\n                timeout: timeout,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    public func publish(\n        registryURL: URL,\n        packageIdentity: PackageIdentity,\n        packageVersion: Version,\n        packageArchive: AbsolutePath,\n        packageMetadata: AbsolutePath?,\n        signature: [UInt8]?,\n        metadataSignature: [UInt8]?,\n        signatureFormat: SignatureFormat?,\n        timeout: DispatchTimeInterval? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> PublishResult {\n        guard let registryIdentity = packageIdentity.registry else {\n            throw RegistryError.invalidPackageIdentity(packageIdentity)\n        }\n        guard var components = URLComponents(url: registryURL, resolvingAgainstBaseURL: true) else {\n            throw RegistryError.invalidURL(registryURL)\n        }\n        components.appendPathComponents(registryIdentity.scope.description)\n        components.appendPathComponents(registryIdentity.name.description)\n        components.appendPathComponents(packageVersion.description)\n\n        guard let url = components.url else {\n            throw RegistryError.invalidURL(registryURL)\n        }\n\n        // TODO: don't load the entire file in memory\n        guard let packageArchiveContent: Data = try? fileSystem.readFileContents(packageArchive) else {\n            throw RegistryError.failedLoadingPackageArchive(packageArchive)\n        }\n        var metadataContent: String? = .none\n        if let packageMetadata {\n            do {\n                metadataContent = try fileSystem.readFileContents(packageMetadata)\n            } catch {\n                throw RegistryError.failedLoadingPackageMetadata(packageMetadata)\n            }\n        }\n\n        // TODO: add generic support for upload requests in Basics\n        let boundary = UUID().uuidString\n        var body = Data()\n\n        // archive field\n        body.append(contentsOf: \"\"\"\n        --\\(boundary)\\r\n        Content-Disposition: form-data; name=\\\"source-archive\\\"\\r\n        Content-Type: application/zip\\r\n        Content-Transfer-Encoding: binary\\r\n        \\r\\n\n        \"\"\".utf8)\n        body.append(packageArchiveContent)\n\n        if let signature {\n            guard signatureFormat != nil else {\n                throw RegistryError.missingSignatureFormat\n            }\n\n            body.append(contentsOf: \"\"\"\n            \\r\n            --\\(boundary)\\r\n            Content-Disposition: form-data; name=\\\"source-archive-signature\\\"\\r\n            Content-Type: application/octet-stream\\r\n            Content-Transfer-Encoding: binary\\r\n            \\r\\n\n            \"\"\".utf8)\n            body.append(contentsOf: signature)\n        }\n\n        // metadata field\n        if let metadataContent {\n            body.append(contentsOf: \"\"\"\n            \\r\n            --\\(boundary)\\r\n            Content-Disposition: form-data; name=\\\"metadata\\\"\\r\n            Content-Type: application/json\\r\n            Content-Transfer-Encoding: quoted-printable\\r\n            \\r\n            \\(metadataContent)\n            \"\"\".utf8)\n\n            if signature != nil {\n                guard metadataSignature != nil else {\n                    throw RegistryError.invalidSignature(reason: \"both archive and metadata must be signed\")\n                }\n            }\n\n            if let metadataSignature {\n                guard signature != nil else {\n                    throw RegistryError.invalidSignature(reason: \"both archive and metadata must be signed\")\n                }\n                guard signatureFormat != nil else {\n                    throw RegistryError.missingSignatureFormat\n                }\n\n                body.append(contentsOf: \"\"\"\n                \\r\n                --\\(boundary)\\r\n                Content-Disposition: form-data; name=\\\"metadata-signature\\\"\\r\n                Content-Type: application/octet-stream\\r\n                Content-Transfer-Encoding: binary\\r\n                \\r\\n\n                \"\"\".utf8)\n                body.append(contentsOf: metadataSignature)\n            }\n        }\n\n        // footer\n        body.append(contentsOf: \"\\r\\n--\\(boundary)--\\r\\n\".utf8)\n\n        var headers = HTTPClientHeaders()\n        headers.add(HTTPClientHeaders.Item(name: \"Content-Type\", value: \"multipart/form-data;boundary=\\\"\\(boundary)\\\"\"))\n        headers.add(HTTPClientHeaders.Item(name: \"Accept\", value: self.acceptHeader(mediaType: .json)))\n        headers.add(HTTPClientHeaders.Item(name: \"Expect\", value: \"100-continue\"))\n        headers.add(HTTPClientHeaders.Item(name: \"Prefer\", value: \"respond-async\"))\n\n        if signature != nil, let signatureFormat {\n            headers.add(HTTPClientHeaders.Item(name: \"X-Swift-Package-Signature-Format\", value: signatureFormat.rawValue))\n        }\n\n        let start = DispatchTime.now()\n        observabilityScope.emit(info: \"publishing \\(packageIdentity) \\(packageVersion) to \\(url)\")\n\n        let response: HTTPClient.Response\n        do {\n            response = try await self.httpClient.put(\n                url,\n                body: body,\n                headers: headers,\n                options: self.defaultRequestOptions(timeout: timeout)\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.failedPublishing(error)\n        }\n\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(url): \\(response.statusCode) in \\(start.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        switch response.statusCode {\n        case 201:\n            try response.validateAPIVersion()\n            let location = response.headers.get(\"Location\").first.flatMap { URL(string: $0) }\n            return PublishResult.published(location)\n        case 202:\n            try response.validateAPIVersion()\n\n            guard let location = (response.headers.get(\"Location\").first.flatMap { URL(string: $0) }) else {\n                throw RegistryError.missingPublishingLocation\n            }\n            let retryAfter = response.headers.get(\"Retry-After\").first.flatMap { Int($0) }\n            return PublishResult.processing(statusURL: location, retryAfter: retryAfter)\n        default:\n            throw RegistryError.failedPublishing(self.unexpectedStatusError(response, expectedStatus: [201, 202]))\n        }\n    }\n\n    @available(*, deprecated, message: \"Use the async alternative\")\n    func checkAvailability(\n        registry: Registry,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<AvailabilityStatus, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.checkAvailability(\n                registry: registry,\n                timeout: timeout,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    // marked internal for testing\n    func checkAvailability(\n        registry: Registry,\n        timeout: DispatchTimeInterval? = .none,\n        observabilityScope: ObservabilityScope\n    ) async throws -> AvailabilityStatus {\n        guard registry.supportsAvailability else {\n            throw StringError(\"registry \\(registry.url) does not support availability checks.\")\n        }\n\n        guard var components = URLComponents(url: registry.url, resolvingAgainstBaseURL: true) else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n        components.appendPathComponents(\"availability\")\n\n        guard let url = components.url else {\n            throw RegistryError.invalidURL(registry.url)\n        }\n\n        let start = DispatchTime.now()\n        observabilityScope.emit(info: \"checking availability of \\(registry.url) using \\(url)\")\n\n        let response: HTTPClient.Response\n        do {\n            response = try await self.httpClient.get(\n                url,\n                options: self.defaultRequestOptions(timeout: timeout)\n            )\n        } catch let error where !(error is _Concurrency.CancellationError) {\n            throw RegistryError.availabilityCheckFailed(registry: registry, error: error)\n        }\n\n        observabilityScope\n            .emit(\n                debug: \"server response for \\(url): \\(response.statusCode) in \\(start.distance(to: .now()).descriptionInSeconds)\"\n            )\n\n        switch response.statusCode {\n        case 200:\n            return .available\n        case let value where AvailabilityStatus.unavailableStatusCodes.contains(value):\n            return .unavailable\n        default:\n            if let error = try? response.parseError(decoder: self.jsonDecoder) {\n                return .error(error.detail)\n            }\n            return .error(\"unknown server error (\\(response.statusCode))\")\n        }\n    }\n\n    // If the registry is available, the function returns, otherwise an error\n    // explaining why the registry is unavailable is thrown.\n    func withAvailabilityCheck(\n        registry: Registry,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        if !registry.supportsAvailability {\n            return\n        }\n\n        let availabilityHandler: (Result<AvailabilityStatus, Error>) throws -> Void = { result in\n            switch result {\n            case .success(let status):\n                switch status {\n                case .available: return\n                case .unavailable: throw RegistryError.registryNotAvailable(registry)\n                case .error(let error): throw StringError(error)\n                }\n            case .failure(let error):\n                throw error\n            }\n        }\n\n        if let cached = self.availabilityCache[registry.url], cached.expires > .now() {\n            return try availabilityHandler(cached.status)\n        }\n\n        let result = await Result(catching: {\n            try await self.checkAvailability(\n                registry: registry,\n                observabilityScope: observabilityScope\n            )\n        })\n\n        self.availabilityCache[registry.url] = (status: result, expires: .now() + Self.availabilityCacheTTL)\n        return try availabilityHandler(result)\n    }\n\n    private func unwrapRegistry(from package: PackageIdentity) throws -> (PackageIdentity.RegistryIdentity, Registry) {\n        guard let registryIdentity = package.registry else {\n            throw RegistryError.invalidPackageIdentity(package)\n        }\n\n        guard let registry = self.configuration.registry(for: registryIdentity.scope) else {\n            throw RegistryError.registryNotConfigured(scope: registryIdentity.scope)\n        }\n\n        return (registryIdentity, registry)\n    }\n\n    private func unexpectedStatusError(\n        _ response: HTTPClientResponse,\n        expectedStatus: [Int]\n    ) -> Error {\n        if let error = try? response.parseError(decoder: self.jsonDecoder) {\n            return RegistryError.serverError(code: response.statusCode, details: error.detail)\n        }\n\n        switch response.statusCode {\n        case 401:\n            return RegistryError.unauthorized\n        case 403:\n            return RegistryError.forbidden\n        case 400...499:\n            return RegistryError.clientError(\n                code: response.statusCode,\n                details: response.body.map { String(decoding: $0, as: UTF8.self) } ?? \"\"\n            )\n        case 501:\n            return RegistryError.authenticationMethodNotSupported\n        case 500...599:\n            return RegistryError.serverError(\n                code: response.statusCode,\n                details: response.body.map { String(decoding: $0, as: UTF8.self) } ?? \"\"\n            )\n        default:\n            return RegistryError.invalidResponseStatus(expected: expectedStatus, actual: response.statusCode)\n        }\n    }\n\n    private func defaultRequestOptions(\n        timeout: DispatchTimeInterval? = .none\n    ) -> HTTPClient.Request.Options {\n        var options = HTTPClient.Request.Options()\n        options.timeout = timeout\n        options.authorizationProvider = self.authorizationProvider\n        return options\n    }\n\n    private struct MetadataCacheKey: Hashable {\n        let registry: Registry\n        let package: PackageIdentity.RegistryIdentity\n        let version: Version\n    }\n}\n\npublic enum RegistryError: Error, CustomStringConvertible {\n    case registryNotConfigured(scope: PackageIdentity.Scope?)\n    case invalidPackageIdentity(PackageIdentity)\n    case invalidURL(URL)\n    case invalidResponseStatus(expected: [Int], actual: Int)\n    case invalidContentVersion(expected: String, actual: String?)\n    case invalidContentType(expected: String, actual: String?)\n    case invalidResponse\n    case missingSourceArchive\n    case invalidSourceArchive\n    case unsupportedHashAlgorithm(String)\n    case failedToComputeChecksum(Error)\n    case checksumChanged(latest: String, previous: String)\n    case invalidChecksum(expected: String, actual: String)\n    case pathAlreadyExists(AbsolutePath)\n    case failedRetrievingReleases(registry: Registry, package: PackageIdentity, error: Error)\n    case failedRetrievingReleaseInfo(registry: Registry, package: PackageIdentity, version: Version, error: Error)\n    case failedRetrievingReleaseChecksum(registry: Registry, package: PackageIdentity, version: Version, error: Error)\n    case failedRetrievingManifest(registry: Registry, package: PackageIdentity, version: Version, error: Error)\n    case failedDownloadingSourceArchive(registry: Registry, package: PackageIdentity, version: Version, error: Error)\n    case failedIdentityLookup(registry: Registry, scmURL: SourceControlURL, error: Error)\n    case failedLoadingPackageArchive(AbsolutePath)\n    case failedLoadingPackageMetadata(AbsolutePath)\n    case failedPublishing(Error)\n    case missingPublishingLocation\n    case serverError(code: Int, details: String)\n    case clientError(code: Int, details: String)\n    case unauthorized\n    case authenticationMethodNotSupported\n    case forbidden\n    case loginFailed(url: URL, error: Error)\n    case availabilityCheckFailed(registry: Registry, error: Error)\n    case registryNotAvailable(Registry)\n    case packageNotFound\n    case packageVersionNotFound\n    case sourceArchiveMissingChecksum(registry: Registry, package: PackageIdentity, version: Version)\n    case sourceArchiveNotSigned(registry: Registry, package: PackageIdentity, version: Version)\n    case failedLoadingSignature\n    case failedRetrievingSourceArchiveSignature(\n        registry: Registry,\n        package: PackageIdentity,\n        version: Version,\n        error: Error\n    )\n    case manifestNotSigned(registry: Registry, package: PackageIdentity, version: Version, toolsVersion: ToolsVersion?)\n    case missingConfiguration(details: String)\n    case badConfiguration(details: String)\n    case missingSignatureFormat\n    case unknownSignatureFormat(String)\n    case invalidSignature(reason: String)\n    case invalidSigningCertificate(reason: String)\n    case signerNotTrusted(PackageIdentity, SigningEntity)\n    case failedToValidateSignature(Error)\n    case signingEntityForReleaseChanged(\n        registry: Registry,\n        package: PackageIdentity,\n        version: Version,\n        latest: SigningEntity?,\n        previous: SigningEntity\n    )\n    case signingEntityForPackageChanged(\n        registry: Registry,\n        package: PackageIdentity,\n        version: Version,\n        latest: SigningEntity?,\n        previous: SigningEntity,\n        previousVersion: Version\n    )\n\n    public var description: String {\n        switch self {\n        case .registryNotConfigured(let scope):\n            if let scope {\n                return \"no registry configured for '\\(scope)' scope\"\n            } else {\n                return \"no registry configured'\"\n            }\n        case .invalidPackageIdentity(let packageIdentity):\n            return \"invalid package identifier '\\(packageIdentity)'\"\n        case .invalidURL(let url):\n            return \"invalid URL '\\(url)'\"\n        case .invalidResponseStatus(let expected, let actual):\n            return \"invalid registry response status '\\(actual)', expected '\\(expected)'\"\n        case .invalidContentVersion(let expected, let actual):\n            return \"invalid registry response content version '\\(actual ?? \"\")', expected '\\(expected)'\"\n        case .invalidContentType(let expected, let actual):\n            return \"invalid registry response content type '\\(actual ?? \"\")', expected '\\(expected)'\"\n        case .invalidResponse:\n            return \"invalid registry response\"\n        case .missingSourceArchive:\n            return \"missing registry source archive\"\n        case .invalidSourceArchive:\n            return \"invalid registry source archive\"\n        case .unsupportedHashAlgorithm(let algorithm):\n            return \"unsupported hash algorithm '\\(algorithm)'\"\n        case .failedToComputeChecksum(let error):\n            return \"failed computing registry source archive checksum: \\(error.interpolationDescription)\"\n        case .checksumChanged(let latest, let previous):\n            return \"the latest checksum '\\(latest)' is different from the previously recorded value '\\(previous)'\"\n        case .invalidChecksum(let expected, let actual):\n            return \"invalid registry source archive checksum '\\(actual)', expected '\\(expected)'\"\n        case .pathAlreadyExists(let path):\n            return \"path already exists '\\(path)'\"\n        case .failedRetrievingReleases(let registry, let packageIdentity, let error):\n            return \"failed fetching \\(packageIdentity) releases list from \\(registry): \\(error.interpolationDescription)\"\n        case .failedRetrievingReleaseInfo(let registry, let packageIdentity, let version, let error):\n            return \"failed fetching \\(packageIdentity) version \\(version) release information from \\(registry): \\(error.interpolationDescription)\"\n        case .failedRetrievingReleaseChecksum(let registry, let packageIdentity, let version, let error):\n            return \"failed fetching \\(packageIdentity) version \\(version) release checksum from \\(registry): \\(error.interpolationDescription)\"\n        case .failedRetrievingManifest(let registry, let packageIdentity, let version, let error):\n            return \"failed retrieving \\(packageIdentity) version \\(version) manifest from \\(registry): \\(error.interpolationDescription)\"\n        case .failedDownloadingSourceArchive(let registry, let packageIdentity, let version, let error):\n            return \"failed downloading \\(packageIdentity) version \\(version) source archive from \\(registry): \\(error.interpolationDescription)\"\n        case .failedIdentityLookup(let registry, let scmURL, let error):\n            return \"failed looking up identity for \\(scmURL) on \\(registry): \\(error.interpolationDescription)\"\n        case .failedLoadingPackageArchive(let path):\n            return \"failed loading package archive at '\\(path)' for publishing\"\n        case .failedLoadingPackageMetadata(let path):\n            return \"failed loading package metadata at '\\(path)' for publishing\"\n        case .failedPublishing(let error):\n            return \"failed publishing: \\(error.interpolationDescription)\"\n        case .missingPublishingLocation:\n            return \"response missing registry source archive\"\n        case .serverError(let code, let details):\n            return \"server error \\(code): \\(details)\"\n        case .clientError(let code, let details):\n            return \"client error \\(code): \\(details)\"\n        case .unauthorized:\n            return \"missing or invalid authentication credentials\"\n        case .authenticationMethodNotSupported:\n            return \"authentication method not supported\"\n        case .forbidden:\n            return \"forbidden\"\n        case .availabilityCheckFailed(let registry, let error):\n            return \"failed checking availability of registry at '\\(registry.url)': \\(error.interpolationDescription)\"\n        case .registryNotAvailable(let registry):\n            return \"registry at '\\(registry.url)' is not available at this time, please try again later\"\n        case .packageNotFound:\n            return \"package not found on registry\"\n        case .packageVersionNotFound:\n            return \"package version not found on registry\"\n        case .sourceArchiveMissingChecksum(let registry, let packageIdentity, let version):\n            return \"\\(packageIdentity) version \\(version) source archive from \\(registry) has no checksum\"\n        case .sourceArchiveNotSigned(let registry, let packageIdentity, let version):\n            return \"\\(packageIdentity) version \\(version) source archive from \\(registry) is not signed\"\n        case .failedLoadingSignature:\n            return \"failed loading signature for validation\"\n        case .failedRetrievingSourceArchiveSignature(let registry, let packageIdentity, let version, let error):\n            return \"failed retrieving '\\(packageIdentity)' version \\(version) source archive signature from '\\(registry)': \\(error.interpolationDescription)\"\n        case .manifestNotSigned(let registry, let packageIdentity, let version, let toolsVersion):\n            return \"manifest for \\(packageIdentity) version \\(version) tools version \\(toolsVersion.map { \"\\($0)\" } ?? \"unspecified\") from \\(registry) is not signed\"\n        case .missingConfiguration(let details):\n            return \"unable to proceed because of missing configuration: \\(details)\"\n        case .badConfiguration(let details):\n            return \"unable to proceed because of bad configuration: \\(details)\"\n        case .missingSignatureFormat:\n            return \"missing signature format\"\n        case .unknownSignatureFormat(let format):\n            return \"unknown signature format: \\(format)\"\n        case .invalidSignature(let reason):\n            return \"signature is invalid: \\(reason)\"\n        case .invalidSigningCertificate(let reason):\n            return \"the signing certificate is invalid: \\(reason)\"\n        case .signerNotTrusted(_, let signingEntity):\n            return \"the signer \\(signingEntity) is not trusted\"\n        case .failedToValidateSignature(let error):\n            return \"failed to validate signature: \\(error.interpolationDescription)\"\n        case .signingEntityForReleaseChanged(let registry, let package, let version, let latest, let previous):\n            return \"the signing entity '\\(String(describing: latest))' from \\(registry) for \\(package) version \\(version) is different from the previously recorded value '\\(previous)'\"\n        case .signingEntityForPackageChanged(\n            let registry,\n            let package,\n            let version,\n            let latest,\n            let previous,\n            let previousVersion\n        ):\n            return \"the signing entity '\\(String(describing: latest))' from \\(registry) for \\(package) version \\(version) is different from the previously recorded value '\\(previous)' for version \\(previousVersion)\"\n        case .loginFailed(let url, let error):\n            return \"registry login using \\(url) failed: \\(error.interpolationDescription)\"\n        }\n    }\n}\n\nextension RegistryClient {\n    fileprivate enum APIVersion: String {\n        case v1 = \"1\"\n    }\n}\n\nextension RegistryClient {\n    fileprivate enum MediaType: String {\n        case json\n        case swift\n        case zip\n    }\n\n    fileprivate enum ContentType: String, CaseIterable {\n        case json = \"application/json\"\n        case swift = \"text/x-swift\"\n        case zip = \"application/zip\"\n        case error = \"application/problem+json\"\n    }\n\n    private func acceptHeader(mediaType: MediaType) -> String {\n        \"application/vnd.swift.registry.v\\(Self.apiVersion.rawValue)+\\(mediaType)\"\n    }\n}\n\nextension RegistryClient {\n    public struct PackageMetadata {\n        public let registry: Registry\n        public let versions: [Version]\n        public let alternateLocations: [SourceControlURL]\n        public let nextPage: SourceControlURL?\n    }\n\n    public struct PackageVersionMetadata: Sendable {\n        public let registry: Registry\n        public let licenseURL: URL?\n        public let readmeURL: URL?\n        public let repositoryURLs: [SourceControlURL]?\n        public let resources: [Resource]\n        public let author: Author?\n        public let description: String?\n        public let publishedAt: Date?\n\n        public var sourceArchive: Resource? {\n            self.resources.first(where: { $0.name == \"source-archive\" })\n        }\n\n        public struct Resource: Sendable {\n            public let name: String\n            public let type: String\n            public let checksum: String?\n            public let signing: Signing?\n            public let signingEntity: SigningEntity?\n\n            public init(\n                name: String,\n                type: String,\n                checksum: String?,\n                signing: Signing?,\n                signingEntity: SigningEntity?\n            ) {\n                self.name = name\n                self.type = type\n                self.checksum = checksum\n                self.signing = signing\n                self.signingEntity = signingEntity\n            }\n        }\n\n        public struct Signing: Sendable {\n            public let signatureBase64Encoded: String\n            public let signatureFormat: String\n        }\n\n        public struct Author: Sendable {\n            public let name: String\n            public let email: String?\n            public let description: String?\n            public let organization: Organization?\n            public let url: URL?\n        }\n\n        public struct Organization: Sendable {\n            public let name: String\n            public let email: String?\n            public let description: String?\n            public let url: URL?\n        }\n    }\n}\n\nextension RegistryClient {\n    fileprivate struct AlternativeLocationLink {\n        let url: SourceControlURL\n        let kind: Kind\n\n        enum Kind: String {\n            case canonical\n            case alternate\n        }\n    }\n\n    fileprivate struct NextLocationLink {\n        let url: SourceControlURL\n        let kind: Kind\n\n        enum Kind: String {\n            // Currently we only care about `next` for pagination, but there are several other values:\n            // https://github.com/swiftlang/swift-package-manager/blob/0340bb12a56f9696b3966ad82c2aee1594135377/Documentation/PackageRegistry/Registry.md?plain=1#L403-L411\n            case next\n        }\n    }\n}\n\nextension RegistryClient {\n    fileprivate struct ManifestLink {\n        let url: URL\n        let filename: String\n        let toolsVersion: ToolsVersion\n    }\n}\n\nextension RegistryClient {\n    public enum PublishResult: Equatable {\n        case published(URL?)\n        case processing(statusURL: URL, retryAfter: Int?)\n    }\n}\n\nextension RegistryClient {\n    public enum AvailabilityStatus: Equatable {\n        case available\n        case unavailable\n        case error(String)\n\n        // marked internal for testing\n        static var unavailableStatusCodes = [404, 501]\n    }\n}\n\nextension RegistryClient {\n    struct ServerError: Decodable {\n        let detail: String\n    }\n\n    struct RatelimitError {\n        let retryAfter: Int\n    }\n}\n\nextension HTTPClientResponse {\n    fileprivate func parseJSON<T>(_ type: T.Type, decoder: JSONDecoder) throws -> T where T: Decodable {\n        try self.validateAPIVersion()\n        try self.validateContentType(.json)\n\n        guard let data = self.body else {\n            throw RegistryError.invalidResponse\n        }\n\n        return try decoder.decode(type, from: data)\n    }\n\n    fileprivate func parseError(\n        decoder: JSONDecoder\n    ) throws -> RegistryClient.ServerError {\n        try self.validateAPIVersion()\n        try self.validateContentType(.error)\n\n        guard let data = self.body else {\n            throw RegistryError.invalidResponse\n        }\n\n        return try decoder.decode(RegistryClient.ServerError.self, from: data)\n    }\n}\n\nextension HTTPClientResponse {\n    private func validateStatusCode(_ expectedStatusCodes: [Int]) throws {\n        guard expectedStatusCodes.contains(self.statusCode) else {\n            throw RegistryError.invalidResponseStatus(expected: expectedStatusCodes, actual: self.statusCode)\n        }\n    }\n\n    fileprivate func validateAPIVersion(\n        _ expectedVersion: RegistryClient.APIVersion = .v1,\n        isOptional: Bool = false\n    ) throws {\n        let apiVersion = self.apiVersion\n\n        if isOptional, apiVersion == nil {\n            return\n        }\n\n        // Check API version as long as `Content-Version` is set\n        guard apiVersion == expectedVersion else {\n            throw RegistryError.invalidContentVersion(\n                expected: expectedVersion.rawValue,\n                actual: self.apiVersion?.rawValue\n            )\n        }\n    }\n\n    fileprivate func validateContentType(_ expectedContentType: RegistryClient.ContentType) throws {\n        guard self.contentType == expectedContentType else {\n            throw RegistryError.invalidContentType(\n                expected: expectedContentType.rawValue,\n                actual: self.contentType?.rawValue\n            )\n        }\n    }\n\n    fileprivate var apiVersion: RegistryClient.APIVersion? {\n        self.headers.get(\"Content-Version\").first.flatMap { headerValue in\n            RegistryClient.APIVersion(rawValue: headerValue)\n        }\n    }\n\n    private var contentType: RegistryClient.ContentType? {\n        self.headers.get(\"Content-Type\").first.flatMap { headerValue in\n            if let contentType = RegistryClient.ContentType(rawValue: headerValue) {\n                return contentType\n            }\n            if let contentType = RegistryClient.ContentType.allCases.first(where: {\n                headerValue.hasPrefix($0.rawValue + \";\")\n            }) {\n                return contentType\n            }\n            return nil\n        }\n    }\n}\n\nextension HTTPClientHeaders {\n    fileprivate func parseLink<T>(_ factory: (String) throws -> T?) rethrows -> [T] {\n        return try self.get(\"Link\").map { header -> [T] in\n            let linkLines = header.split(separator: \",\").map(String.init).map { $0.spm_chuzzle() ?? $0 }\n            return try linkLines.compactMap { linkLine in\n                try factory(linkLine)\n            }\n        }.flatMap { $0 }\n    }\n\n    fileprivate func parseLocationLine<T>(_ value: String, _ factory: (String, String) -> T?) -> T? {\n        let fields = value.split(separator: \";\")\n            .map(String.init)\n            .map { $0.spm_chuzzle() ?? $0 }\n\n        guard fields.count == 2 else {\n            return nil\n        }\n\n        guard let link = fields.first(where: { $0.hasPrefix(\"<\") }).map({ String($0.dropFirst().dropLast()) })\n        else {\n            return nil\n        }\n\n        guard let rel = fields.first(where: { $0.hasPrefix(\"rel=\") }).flatMap({ parseLinkFieldValue($0) })\n        else {\n            return nil\n        }\n\n        return factory(link, rel)\n    }\n}\n\nextension HTTPClientHeaders {\n    /*\n    https://github.com/swiftlang/swift-package-manager/blob/0340bb12a56f9696b3966ad82c2aee1594135377/Documentation/PackageRegistry/Registry.md?plain=1#L395C1-L401C39\n    <https://github.com/mona/LinkedList>; rel=\"canonical\",\n    <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n    */\n    fileprivate func parseAlternativeLocationLinks() -> [RegistryClient.AlternativeLocationLink] {\n        self.parseLink(self.parseAlternativeLocationLine(_:))\n    }\n\n    private func parseAlternativeLocationLine(_ value: String) -> RegistryClient.AlternativeLocationLink? {\n        return parseLocationLine(value) { link, rel in\n            guard let kind = RegistryClient.AlternativeLocationLink.Kind(rawValue: rel) else {\n                return nil\n            }\n\n            return RegistryClient.AlternativeLocationLink(\n                url: SourceControlURL(link),\n                kind: kind\n            )\n        }\n    }\n}\n\nextension HTTPClientHeaders {\n    /*\n    https://github.com/swiftlang/swift-package-manager/blob/0340bb12a56f9696b3966ad82c2aee1594135377/Documentation/PackageRegistry/Registry.md?plain=1#L403-L411\n    <https://github.com/mona/LinkedList?page=2>; rel=\"next\",\n    <ssh://git@github.com:mona/LinkedList.git?page=40>; rel=\"last\",\n    */\n    fileprivate func parsePaginationLinks() -> [RegistryClient.NextLocationLink] {\n        self.parseLink(self.parsePaginationLine(_:))\n    }\n\n    private func parsePaginationLine(_ value: String) -> RegistryClient.NextLocationLink? {\n        return parseLocationLine(value) { link, rel in\n            guard let kind = RegistryClient.NextLocationLink.Kind(rawValue: rel) else {\n                return nil\n            }\n\n            return RegistryClient.NextLocationLink(\n                url: SourceControlURL(link),\n                kind: kind\n            )\n        }\n    }\n}\n\nextension HTTPClientHeaders {\n    /*\n     <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4>; rel=\"alternate\"; filename=\"Package@swift-4.swift\"; swift-tools-version=\"4.0\"\n     */\n    fileprivate func parseManifestLinks() throws -> [RegistryClient.ManifestLink] {\n        try self.parseLink(self.parseManifestLinkLine(_:))\n    }\n\n    private func parseManifestLinkLine(_ value: String) throws -> RegistryClient.ManifestLink? {\n        let fields = value.split(separator: \";\")\n            .map(String.init)\n            .map { $0.spm_chuzzle() ?? $0 }\n\n        guard fields.count == 4 else {\n            return nil\n        }\n\n        guard let link = fields.first(where: { $0.hasPrefix(\"<\") }).map({ String($0.dropFirst().dropLast()) }),\n              let url = URL(string: link)\n        else {\n            return nil\n        }\n\n        guard let rel = fields.first(where: { $0.hasPrefix(\"rel=\") }).flatMap({ parseLinkFieldValue($0) }),\n              rel == \"alternate\"\n        else {\n            return nil\n        }\n\n        guard let filename = fields.first(where: { $0.hasPrefix(\"filename=\") }).flatMap({ parseLinkFieldValue($0) })\n        else {\n            return nil\n        }\n\n        guard let toolsVersion = fields.first(where: { $0.hasPrefix(\"swift-tools-version=\") })\n            .flatMap({ parseLinkFieldValue($0) })\n        else {\n            return nil\n        }\n\n        guard let toolsVersion = ToolsVersion(string: toolsVersion) else {\n            throw StringError(\"Invalid tools version in alternate manifest link '\\(value)'\")\n        }\n\n        return RegistryClient.ManifestLink(\n            url: url,\n            filename: filename,\n            toolsVersion: toolsVersion\n        )\n    }\n}\n\nextension HTTPClientHeaders {\n    private func parseLinkFieldValue(_ field: String) -> String? {\n        let parts = field.split(separator: \"=\")\n            .map(String.init)\n            .map { $0.spm_chuzzle() ?? $0 }\n\n        guard parts.count == 2 else {\n            return nil\n        }\n\n        return parts[1].replacing(\"\\\"\", with: \"\")\n    }\n}\n\n// MARK: - Serialization\n\nextension RegistryClient {\n    // marked public for testing (cross module visibility)\n    public enum Serialization {\n        // marked public for testing (cross module visibility)\n        public struct PackageMetadata: Codable {\n            public let releases: [String: Release]\n\n            public init(releases: [String: Release]) {\n                self.releases = releases\n            }\n\n            public struct Release: Codable {\n                public var url: String?\n                public var problem: Problem?\n\n                public init(url: String?, problem: Problem? = .none) {\n                    self.url = url\n                    self.problem = problem\n                }\n            }\n\n            public struct Problem: Codable {\n                public var status: Int?\n                public var title: String?\n                public var detail: String\n\n                public init(status: Int, title: String, detail: String) {\n                    self.status = status\n                    self.title = title\n                    self.detail = detail\n                }\n            }\n        }\n\n        // marked public for testing (cross module visibility)\n        public struct VersionMetadata: Codable {\n            public let id: String\n            public let version: String\n            public let resources: [Resource]\n            public let metadata: AdditionalMetadata?\n            public let publishedAt: Date?\n\n            var sourceArchive: Resource? {\n                self.resources.first(where: { $0.name == \"source-archive\" })\n            }\n\n            public init(\n                id: String,\n                version: String,\n                resources: [Resource],\n                metadata: AdditionalMetadata?,\n                publishedAt: Date?\n            ) {\n                self.id = id\n                self.version = version\n                self.resources = resources\n                self.metadata = metadata\n                self.publishedAt = publishedAt\n            }\n\n            public struct Resource: Codable {\n                public let name: String\n                public let type: String\n                public let checksum: String?\n                public let signing: Signing?\n\n                public init(name: String, type: String, checksum: String, signing: Signing?) {\n                    self.name = name\n                    self.type = type\n                    self.checksum = checksum\n                    self.signing = signing\n                }\n            }\n\n            public struct Signing: Codable {\n                public let signatureBase64Encoded: String\n                public let signatureFormat: String\n            }\n\n            public struct AdditionalMetadata: Codable {\n                public let author: Author?\n                public let description: String?\n                public let licenseURL: String?\n                public let readmeURL: String?\n                public let repositoryURLs: [String]?\n                public let originalPublicationTime: Date?\n\n                public init(\n                    author: Author? = nil,\n                    description: String,\n                    licenseURL: String? = nil,\n                    readmeURL: String? = nil,\n                    repositoryURLs: [String]? = nil,\n                    originalPublicationTime: Date? = nil\n                ) {\n                    self.author = author\n                    self.description = description\n                    self.licenseURL = licenseURL\n                    self.readmeURL = readmeURL\n                    self.repositoryURLs = repositoryURLs\n                    self.originalPublicationTime = originalPublicationTime\n                }\n            }\n\n            public struct Author: Codable {\n                public let name: String\n                public let email: String?\n                public let description: String?\n                public let organization: Organization?\n                public let url: String?\n            }\n\n            public struct Organization: Codable {\n                public let name: String\n                public let email: String?\n                public let description: String?\n                public let url: String?\n            }\n        }\n\n        // marked public for testing (cross module visibility)\n        public struct PackageIdentifiers: Codable {\n            public let identifiers: [String]\n\n            public init(identifiers: [String]) {\n                self.identifiers = identifiers\n            }\n        }\n    }\n}\n\n// MARK: - RegistryReleaseMetadata serialization helpers\n\nextension RegistryReleaseMetadataStorage {\n    fileprivate static func save(\n        metadata: RegistryClient.PackageVersionMetadata,\n        signingEntity: SigningEntity?,\n        to path: AbsolutePath,\n        fileSystem: FileSystem\n    ) throws {\n        let registryMetadata = try RegistryReleaseMetadata(\n            metadata: metadata,\n            signingEntity: signingEntity\n        )\n        try self.save(registryMetadata, to: path, fileSystem: fileSystem)\n    }\n}\n\nextension RegistryReleaseMetadata {\n    fileprivate init(\n        metadata: RegistryClient.PackageVersionMetadata,\n        signingEntity: PackageSigning.SigningEntity?\n    ) throws {\n        self.init(\n            source: .registry(metadata.registry.url),\n            metadata: .init(\n                author: metadata.author.flatMap {\n                    .init(\n                        name: $0.name,\n                        emailAddress: $0.email,\n                        description: $0.description,\n                        url: $0.url,\n                        organization: $0.organization.flatMap {\n                            .init(\n                                name: $0.name,\n                                emailAddress: $0.email,\n                                description: $0.description,\n                                url: $0.url\n                            )\n                        }\n                    )\n                },\n                description: metadata.description,\n                licenseURL: metadata.licenseURL,\n                readmeURL: metadata.readmeURL,\n                scmRepositoryURLs: metadata.repositoryURLs\n            ),\n            signature: try metadata.sourceArchive?.signing.flatMap {\n                guard let signatureData = Data(base64Encoded: $0.signatureBase64Encoded) else {\n                    throw StringError(\"invalid based64 encoded signature\")\n                }\n                return RegistrySignature(\n                    signedBy: signingEntity.flatMap {\n                        switch $0 {\n                        case .recognized(let type, let name, let organizationalUnit, let organization):\n                            return .recognized(\n                                type: type.rawValue,\n                                commonName: name,\n                                organization: organization,\n                                identity: organizationalUnit\n                            )\n                        case .unrecognized(let name, _, let organization):\n                            return .unrecognized(commonName: name, organization: organization)\n                        }\n                    },\n                    format: $0.signatureFormat,\n                    value: Array(signatureData)\n                )\n            }\n        )\n    }\n}\n\nprivate struct RegistryClientSignatureValidationDelegate: SignatureValidation.Delegate {\n    let underlying: RegistryClient.Delegate?\n\n    private let onUnsignedResponseCache = ThreadSafeKeyValueStore<ResponseCacheKey, Bool>()\n    private let onUntrustedResponseCache = ThreadSafeKeyValueStore<ResponseCacheKey, Bool>()\n\n    func onUnsigned(\n        registry: Registry,\n        package: PackageModel.PackageIdentity,\n        version: TSCUtility.Version,\n        completion: (Bool) -> Void\n    ) {\n        let responseCacheKey = ResponseCacheKey(registry: registry, package: package, version: version)\n        if let cachedResponse = self.onUnsignedResponseCache[responseCacheKey] {\n            return completion(cachedResponse)\n        }\n\n        if let underlying {\n            underlying.onUnsigned(\n                registry: registry,\n                package: package,\n                version: version\n            ) { response in\n                self.onUnsignedResponseCache[responseCacheKey] = response\n                completion(response)\n            }\n        } else {\n            // true == continue resolution\n            // false == stop dependency resolution\n            completion(false)\n        }\n    }\n\n    func onUntrusted(\n        registry: Registry,\n        package: PackageModel.PackageIdentity,\n        version: TSCUtility.Version,\n        completion: (Bool) -> Void\n    ) {\n        let responseCacheKey = ResponseCacheKey(registry: registry, package: package, version: version)\n        if let cachedResponse = self.onUntrustedResponseCache[responseCacheKey] {\n            return completion(cachedResponse)\n        }\n\n        if let underlying {\n            underlying.onUntrusted(\n                registry: registry,\n                package: package,\n                version: version\n            ) { response in\n                self.onUntrustedResponseCache[responseCacheKey] = response\n                completion(response)\n            }\n        } else {\n            // true == continue resolution\n            // false == stop dependency resolution\n            completion(false)\n        }\n    }\n\n    private struct ResponseCacheKey: Hashable {\n        let registry: Registry\n        let package: PackageModel.PackageIdentity\n        let version: TSCUtility.Version\n    }\n}\n\n// MARK: - Utilities\n\nextension URLComponents {\n    fileprivate mutating func appendPathComponents(_ components: String...) {\n        path += (path.last == \"/\" ? \"\" : \"/\") + components.joined(separator: \"/\")\n    }\n}\n\nextension Result {\n    fileprivate init(catching body: () async throws(Failure) -> Success) async {\n        do {\n            self = .success(try await body())\n        } catch {\n            self = .failure(error)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistry/RegistryConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\n\npublic struct RegistryConfiguration: Hashable {\n    static func authenticationStorageKey(for registryURL: URL) throws -> String {\n        guard let host = registryURL.host?.lowercased() else {\n            throw RegistryError.invalidURL(registryURL)\n        }\n\n        return [host, registryURL.port?.description].compactMap { $0 }.joined(separator: \":\")\n    }\n\n    public enum Version: Int, Codable {\n        case v1 = 1\n    }\n\n    public static let version: Version = .v1\n\n    public var defaultRegistry: Registry?\n    public var scopedRegistries: [PackageIdentity.Scope: Registry]\n    public var registryAuthentication: [String: Authentication]\n    public var security: Security?\n\n    public init() {\n        self.defaultRegistry = .none\n        self.scopedRegistries = [:]\n        self.registryAuthentication = [:]\n        self.security = .none\n    }\n\n    public mutating func merge(_ other: RegistryConfiguration) {\n        if let defaultRegistry = other.defaultRegistry {\n            self.defaultRegistry = defaultRegistry\n        }\n\n        for (scope, registry) in other.scopedRegistries {\n            self.scopedRegistries[scope] = registry\n        }\n\n        for (registry, authentication) in other.registryAuthentication {\n            self.registryAuthentication[registry] = authentication\n        }\n\n        if let security = other.security {\n            self.security = security\n        }\n    }\n\n    public func registry(for package: PackageIdentity) -> Registry? {\n        guard let registryIdentity = package.registry else {\n            return .none\n        }\n        return self.registry(for: registryIdentity.scope)\n    }\n\n    public func registry(for scope: PackageIdentity.Scope) -> Registry? {\n        self.scopedRegistries[scope] ?? self.defaultRegistry\n    }\n\n    public var explicitlyConfigured: Bool {\n        self.defaultRegistry != nil || !self.scopedRegistries.isEmpty\n    }\n\n    public func authentication(for registryURL: URL) throws -> Authentication? {\n        let key = try Self.authenticationStorageKey(for: registryURL)\n        return self.registryAuthentication[key]\n    }\n\n    public mutating func add(authentication: Authentication, for registryURL: URL) throws {\n        let key = try Self.authenticationStorageKey(for: registryURL)\n        self.registryAuthentication[key] = authentication\n    }\n\n    public mutating func removeAuthentication(for registryURL: URL) {\n        guard let key = try? Self.authenticationStorageKey(for: registryURL) else { return }\n        self.registryAuthentication.removeValue(forKey: key)\n    }\n\n    public func signing(for package: PackageIdentity.RegistryIdentity, registry: Registry) -> Security.Signing {\n        let global = self.security?.default.signing\n        let registryOverrides = registry.url.host.flatMap { host in self.security?.registryOverrides[host]?.signing }\n        let scopeOverrides = self.security?.scopeOverrides[package.scope]?.signing\n        let packageOverrides = self.security?.packageOverrides[package]?.signing\n\n        var signing = Security.Signing.default\n        if let global {\n            signing.merge(global)\n        }\n        if let registryOverrides {\n            signing.merge(registryOverrides)\n        }\n        if let scopeOverrides {\n            signing.merge(scopeOverrides)\n        }\n        if let packageOverrides {\n            signing.merge(packageOverrides)\n        }\n\n        return signing\n    }\n}\n\nextension RegistryConfiguration {\n    public struct Authentication: Hashable, Codable {\n        public var type: AuthenticationType\n        public var loginAPIPath: String?\n\n        public init(type: AuthenticationType, loginAPIPath: String? = nil) {\n            self.type = type\n            self.loginAPIPath = loginAPIPath\n        }\n    }\n\n    public enum AuthenticationType: String, Hashable, Codable {\n        case basic\n        case token\n    }\n}\n\nextension RegistryConfiguration {\n    public struct Security: Hashable {\n        public var `default`: Global\n        public var registryOverrides: [String: RegistryOverride]\n        public var scopeOverrides: [PackageIdentity.Scope: ScopePackageOverride]\n        public var packageOverrides: [PackageIdentity.RegistryIdentity: ScopePackageOverride]\n\n        public init() {\n            self.default = Global()\n            self.registryOverrides = [:]\n            self.scopeOverrides = [:]\n            self.packageOverrides = [:]\n        }\n\n        // for testing\n        init(\n            default: Global,\n            registryOverrides: [String: RegistryOverride] = [:],\n            scopeOverrides: [PackageIdentity.Scope: ScopePackageOverride] = [:],\n            packageOverrides: [PackageIdentity.RegistryIdentity: ScopePackageOverride] = [:]\n        ) {\n            self.default = `default`\n            self.registryOverrides = registryOverrides\n            self.scopeOverrides = scopeOverrides\n            self.packageOverrides = packageOverrides\n        }\n\n        public struct Global: Hashable, Codable {\n            public var signing: Signing?\n\n            public init() {\n                self.signing = nil\n            }\n\n            // for testing\n            init(signing: Signing) {\n                self.signing = signing\n            }\n        }\n\n        public struct RegistryOverride: Hashable, Codable {\n            public var signing: Signing?\n\n            public init() {\n                self.signing = nil\n            }\n        }\n\n        public struct Signing: Hashable, Codable {\n            static let `default`: Signing = {\n                var signing = Signing()\n                signing.onUnsigned = .warn\n                signing.onUntrustedCertificate = .warn\n                signing.trustedRootCertificatesPath = nil\n                signing.includeDefaultTrustedRootCertificates = true\n\n                var validationChecks = Signing.ValidationChecks()\n                validationChecks.certificateExpiration = .disabled\n                validationChecks.certificateRevocation = .disabled\n                signing.validationChecks = validationChecks\n\n                return signing\n            }()\n\n            public var onUnsigned: OnUnsignedAction?\n            public var onUntrustedCertificate: OnUntrustedCertificateAction?\n            public var trustedRootCertificatesPath: String?\n            public var includeDefaultTrustedRootCertificates: Bool?\n            public var validationChecks: ValidationChecks?\n\n            public init() {\n                self.onUnsigned = nil\n                self.onUntrustedCertificate = nil\n                self.trustedRootCertificatesPath = nil\n                self.includeDefaultTrustedRootCertificates = nil\n                self.validationChecks = nil\n            }\n\n            mutating func merge(_ other: Signing) {\n                if let onUnsigned = other.onUnsigned {\n                    self.onUnsigned = onUnsigned\n                }\n                if let onUntrustedCertificate = other.onUntrustedCertificate {\n                    self.onUntrustedCertificate = onUntrustedCertificate\n                }\n                if let trustedRootCertificatesPath = other.trustedRootCertificatesPath {\n                    self.trustedRootCertificatesPath = trustedRootCertificatesPath\n                }\n                if let includeDefaultTrustedRootCertificates = other.includeDefaultTrustedRootCertificates {\n                    self.includeDefaultTrustedRootCertificates = includeDefaultTrustedRootCertificates\n                }\n                if let validationChecks = other.validationChecks {\n                    self.validationChecks?.merge(validationChecks)\n                }\n            }\n\n            mutating func merge(_ other: ScopePackageOverride.Signing) {\n                if let trustedRootCertificatesPath = other.trustedRootCertificatesPath {\n                    self.trustedRootCertificatesPath = trustedRootCertificatesPath\n                }\n                if let includeDefaultTrustedRootCertificates = other.includeDefaultTrustedRootCertificates {\n                    self.includeDefaultTrustedRootCertificates = includeDefaultTrustedRootCertificates\n                }\n            }\n\n            public enum OnUnsignedAction: String, Hashable, Codable {\n                case prompt\n                case error\n                case warn\n                case silentAllow\n            }\n\n            public enum OnUntrustedCertificateAction: String, Hashable, Codable {\n                case prompt\n                case error\n                case warn\n                case silentAllow\n            }\n\n            public struct ValidationChecks: Hashable, Codable {\n                public var certificateExpiration: CertificateExpirationCheck?\n                public var certificateRevocation: CertificateRevocationCheck?\n\n                public init() {\n                    self.certificateExpiration = nil\n                    self.certificateRevocation = nil\n                }\n\n                mutating func merge(_ other: ValidationChecks) {\n                    if let certificateExpiration = other.certificateExpiration {\n                        self.certificateExpiration = certificateExpiration\n                    }\n                    if let certificateRevocation = other.certificateRevocation {\n                        self.certificateRevocation = certificateRevocation\n                    }\n                }\n\n                public enum CertificateExpirationCheck: String, Hashable, Codable {\n                    case enabled\n                    case disabled\n                }\n\n                public enum CertificateRevocationCheck: String, Hashable, Codable {\n                    case strict\n                    case allowSoftFail\n                    case disabled\n                }\n            }\n        }\n\n        public struct ScopePackageOverride: Hashable, Codable {\n            public var signing: Signing?\n\n            public init() {\n                self.signing = nil\n            }\n\n            public struct Signing: Hashable, Codable {\n                public var trustedRootCertificatesPath: String?\n                public var includeDefaultTrustedRootCertificates: Bool?\n\n                public init() {\n                    self.trustedRootCertificatesPath = nil\n                    self.includeDefaultTrustedRootCertificates = nil\n                }\n\n                mutating func merge(_ other: Signing) {\n                    if let trustedRootCertificatesPath = other.trustedRootCertificatesPath {\n                        self.trustedRootCertificatesPath = trustedRootCertificatesPath\n                    }\n                    if let includeDefaultTrustedRootCertificates = other.includeDefaultTrustedRootCertificates {\n                        self.includeDefaultTrustedRootCertificates = includeDefaultTrustedRootCertificates\n                    }\n                }\n            }\n        }\n    }\n}\n\n// MARK: - Codable\n\nextension RegistryConfiguration: Codable {\n    private enum CodingKeys: String, CodingKey {\n        case registries\n        case authentication\n        case security\n        case version\n    }\n\n    fileprivate struct ScopeCodingKey: CodingKey, Hashable {\n        static let `default` = ScopeCodingKey(stringValue: \"[default]\")\n\n        var stringValue: String\n        var intValue: Int? { nil }\n\n        init(stringValue: String) {\n            self.stringValue = stringValue\n        }\n\n        init?(intValue: Int) {\n            nil\n        }\n    }\n\n    fileprivate struct PackageCodingKey: CodingKey, Hashable {\n        var stringValue: String\n        var intValue: Int? { nil }\n\n        init(stringValue: String) {\n            self.stringValue = stringValue\n        }\n\n        init?(intValue: Int) {\n            nil\n        }\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n\n        let version = try container.decode(Version.RawValue.self, forKey: .version)\n        switch Version(rawValue: version) {\n        case .v1:\n            let nestedContainer = try container.nestedContainer(keyedBy: ScopeCodingKey.self, forKey: .registries)\n\n            self.defaultRegistry = try nestedContainer.decodeIfPresent(Registry.self, forKey: .default)\n\n            var scopedRegistries: [PackageIdentity.Scope: Registry] = [:]\n            for key in nestedContainer.allKeys where key != .default {\n                let scope = try PackageIdentity.Scope(validating: key.stringValue)\n                scopedRegistries[scope] = try nestedContainer.decode(Registry.self, forKey: key)\n            }\n            self.scopedRegistries = scopedRegistries\n\n            self.registryAuthentication = try container.decodeIfPresent(\n                [String: Authentication].self,\n                forKey: .authentication\n            ) ?? [:]\n            self.security = try container.decodeIfPresent(Security.self, forKey: .security) ?? nil\n        case nil:\n            throw DecodingError.dataCorruptedError(\n                forKey: .version,\n                in: container,\n                debugDescription: \"invalid version: \\(version)\"\n            )\n        }\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n\n        try container.encode(Self.version, forKey: .version)\n\n        var registriesContainer = container.nestedContainer(keyedBy: ScopeCodingKey.self, forKey: .registries)\n\n        try registriesContainer.encodeIfPresent(self.defaultRegistry, forKey: .default)\n\n        for (scope, registry) in self.scopedRegistries {\n            let key = ScopeCodingKey(stringValue: scope.description)\n            try registriesContainer.encode(registry, forKey: key)\n        }\n\n        try container.encode(self.registryAuthentication, forKey: .authentication)\n        try container.encodeIfPresent(self.security, forKey: .security)\n    }\n}\n\nextension PackageModel.Registry: Codable {\n    private enum CodingKeys: String, CodingKey {\n        case url\n        case supportsAvailability\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        try self.init(\n            url: container.decode(URL.self, forKey: .url),\n            supportsAvailability: container.decodeIfPresent(Bool.self, forKey: .supportsAvailability) ?? false\n        )\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        try container.encode(self.url, forKey: .url)\n        try container.encode(self.supportsAvailability, forKey: .supportsAvailability)\n    }\n}\n\nextension RegistryConfiguration.Security: Codable {\n    private enum CodingKeys: String, CodingKey {\n        case `default`\n        case registryOverrides\n        case scopeOverrides\n        case packageOverrides\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n\n        self.default = try container.decodeIfPresent(Global.self, forKey: .default) ?? Global()\n        self.registryOverrides = try container.decodeIfPresent(\n            [String: RegistryOverride].self,\n            forKey: .registryOverrides\n        ) ?? [:]\n\n        let scopeOverridesContainer = try container.decodeIfPresent(\n            [String: ScopePackageOverride].self,\n            forKey: .scopeOverrides\n        ) ?? [:]\n        var scopeOverrides: [PackageIdentity.Scope: ScopePackageOverride] = [:]\n        for (key, scopeOverride) in scopeOverridesContainer {\n            let scope = try PackageIdentity.Scope(validating: key)\n            scopeOverrides[scope] = scopeOverride\n        }\n        self.scopeOverrides = scopeOverrides\n\n        let packageOverridesContainer = try container.decodeIfPresent(\n            [String: ScopePackageOverride].self,\n            forKey: .packageOverrides\n        ) ?? [:]\n        var packageOverrides: [PackageIdentity.RegistryIdentity: ScopePackageOverride] = [:]\n        for (key, packageOverride) in packageOverridesContainer {\n            guard let packageIdentity = PackageIdentity.plain(key).registry else {\n                throw DecodingError.dataCorruptedError(\n                    forKey: .packageOverrides,\n                    in: container,\n                    debugDescription: \"invalid package identifier: '\\(key)'\"\n                )\n            }\n            packageOverrides[packageIdentity] = packageOverride\n        }\n        self.packageOverrides = packageOverrides\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n\n        try container.encode(self.default, forKey: .default)\n        try container.encode(self.registryOverrides, forKey: .registryOverrides)\n\n        var scopeOverridesContainer = container.nestedContainer(\n            keyedBy: RegistryConfiguration.ScopeCodingKey.self,\n            forKey: .scopeOverrides\n        )\n        for (scope, scopeOverride) in self.scopeOverrides {\n            let key = RegistryConfiguration.ScopeCodingKey(stringValue: scope.description)\n            try scopeOverridesContainer.encode(scopeOverride, forKey: key)\n        }\n\n        var packageOverridesContainer = container.nestedContainer(\n            keyedBy: RegistryConfiguration.PackageCodingKey.self,\n            forKey: .packageOverrides\n        )\n        for (packageIdentity, packageOverride) in self.packageOverrides {\n            let key = RegistryConfiguration.PackageCodingKey(stringValue: packageIdentity.description)\n            try packageOverridesContainer.encode(packageOverride, forKey: key)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistry/RegistryDownloadsManager.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport Foundation\nimport PackageLoading\nimport PackageModel\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\npublic class RegistryDownloadsManager: AsyncCancellable {\n    public typealias Delegate = RegistryDownloadsManagerDelegate\n\n    private let fileSystem: FileSystem\n    private let path: Basics.AbsolutePath\n    private let cachePath: Basics.AbsolutePath?\n    private let registryClient: RegistryClient\n    private let delegate: RegistryDownloadManagerDelegateProxy?\n\n    struct PackageLookup: Hashable {\n        let package: PackageIdentity\n        let version: Version\n    }\n\n    private var pendingLookups = [PackageLookup: Task<Basics.AbsolutePath, Error>]()\n    private var pendingLookupsLock = NSLock()\n\n    public init(\n        fileSystem: FileSystem,\n        path: Basics.AbsolutePath,\n        cachePath: Basics.AbsolutePath?,\n        registryClient: RegistryClient,\n        delegate: Delegate?\n    ) {\n        self.fileSystem = fileSystem\n        self.path = path\n        self.cachePath = cachePath\n        self.registryClient = registryClient\n        self.delegate = RegistryDownloadManagerDelegateProxy(delegate)\n    }\n\n    public func lookup(\n        package: PackageIdentity,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Basics.AbsolutePath {\n        let packageRelativePath: Basics.RelativePath\n        let packagePath: Basics.AbsolutePath\n\n        packageRelativePath = try package.downloadPath(version: version)\n        packagePath = self.path.appending(packageRelativePath)\n\n        // TODO: we can do some finger-print checking to improve the validation\n        // already exists and valid, we can exit early\n        if try self.fileSystem.validPackageDirectory(packagePath) {\n            return packagePath\n        }\n\n        let lookupId = PackageLookup(package: package, version: version)\n        let task = await withCheckedContinuation { continuation in\n            self.pendingLookupsLock.lock()\n            defer { self.pendingLookupsLock.unlock() }\n\n            // Check if we've already resolved/are in the process of resolving for this package.\n            if let inFlight = self.pendingLookups[lookupId] {\n                continuation.resume(returning: inFlight)\n            } else {\n                let lookupTask = Task {\n                    // inform delegate that we are starting to fetch\n                    // calculate if cached (for delegate call) outside queue as it may change while queue is processing\n                    let isCached = self.cachePath.map { self.fileSystem.exists($0.appending(packageRelativePath)) } ?? false\n                    Task {\n                        let details = FetchDetails(fromCache: isCached, updatedCache: false)\n                        await delegate?.willFetch(package: package, version: version, fetchDetails: details)\n                    }\n\n                    // make sure destination is free.\n                    try? self.fileSystem.removeFileTree(packagePath)\n\n                    let start = DispatchTime.now()\n                    do {\n                        let result = try await self.downloadAndPopulateCache(\n                            package: package,\n                            version: version,\n                            packagePath: packagePath,\n                            observabilityScope: observabilityScope\n                        )\n                        // inform delegate that we finished to fetch\n                        let duration = start.distance(to: .now())\n                        Task {\n                            await delegate?.didFetch(package: package, version: version, result: .success(result), duration: duration)\n                        }\n                    } catch {\n                        let duration = start.distance(to: .now())\n                        Task {\n                            await delegate?.didFetch(package: package, version: version, result: .failure(error), duration: duration)\n                        }\n                        throw error\n                    }\n                    return packagePath\n                }\n\n                self.pendingLookups[lookupId] = lookupTask\n                continuation.resume(returning: lookupTask)\n            }\n        }\n        return try await task.value\n    }\n\n    @available(*, noasync, message: \"Use the async alternative\")\n    public func lookup(\n        package: PackageIdentity,\n        version: Version,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<Basics.AbsolutePath, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.lookup(\n                package: package,\n                version: version,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    /// Cancel any outstanding requests\n    public func cancel(deadline: DispatchTime) async throws {\n        try await self.registryClient.cancel(deadline: deadline)\n    }\n\n    private func downloadAndPopulateCache(\n        package: PackageIdentity,\n        version: Version,\n        packagePath: Basics.AbsolutePath,\n        observabilityScope: ObservabilityScope\n    ) async throws -> FetchDetails {\n        if let cachePath {\n            do {\n                let relativePath = try package.downloadPath(version: version)\n                let cachedPackagePath = cachePath.appending(relativePath)\n\n                try self.initializeCacheIfNeeded(cachePath: cachePath)\n\n                return try await self.fileSystem.withLock(on: cachedPackagePath, type: .exclusive) {\n                    // download the package into the cache unless already exists\n                    if try self.fileSystem.validPackageDirectory(cachedPackagePath) {\n                        // extra validation to defend from racy edge cases\n                        if self.fileSystem.exists(packagePath) {\n                            throw StringError(\"\\(packagePath) already exists unexpectedly\")\n                        }\n                        // copy the package from the cache into the package path.\n                        try self.fileSystem.createDirectory(packagePath.parentDirectory, recursive: true)\n                        try self.fileSystem.copy(from: cachedPackagePath, to: packagePath)\n                        return FetchDetails(fromCache: true, updatedCache: false)\n                    } else {\n                        do {\n                            // it is possible that we already created the directory before from failed attempts, so clear leftover data if present.\n                            try? self.fileSystem.removeFileTree(cachedPackagePath)\n                            // download the package from the registry\n                            let _ = try await self.registryClient.downloadSourceArchive(\n                                package: package,\n                                version: version,\n                                destinationPath: cachedPackagePath,\n                                progressHandler: updateDownloadProgress,\n                                fileSystem: self.fileSystem,\n                                observabilityScope: observabilityScope\n                            )\n\n                            // extra validation to defend from racy edge cases\n                            if self.fileSystem.exists(packagePath) {\n                                throw StringError(\"\\(packagePath) already exists unexpectedly\")\n                            }\n                            // copy the package from the cache into the package path.\n                            try self.fileSystem.createDirectory(packagePath.parentDirectory, recursive: true)\n                            try self.fileSystem.copy(from: cachedPackagePath, to: packagePath)\n                            return FetchDetails(fromCache: true, updatedCache: true)\n                        } catch {\n                            // Wrap this error to do a straight rethrow instead of handling it as if\n                            // the download should be made without populating the cache.\n                            throw DownloadError.passthrough(error)\n                        }\n                    }\n                }\n            } catch DownloadError.passthrough(let underlyingError) {\n                throw underlyingError\n            } catch {\n                // download without populating the cache in the case of an error.\n                observabilityScope.emit(\n                    warning: \"skipping cache due to an error\",\n                    underlyingError: error\n                )\n                // it is possible that we already created the directory from failed attempts, so clear leftover data if present.\n                try? self.fileSystem.removeFileTree(packagePath)\n                let _ = try await self.registryClient.downloadSourceArchive(\n                    package: package,\n                    version: version,\n                    destinationPath: packagePath,\n                    progressHandler: updateDownloadProgress,\n                    fileSystem: self.fileSystem,\n                    observabilityScope: observabilityScope\n                )\n                return FetchDetails(fromCache: false, updatedCache: false)\n            }\n        } else {\n            // it is possible that we already created the directory from failed attempts, so clear leftover data if present.\n            try? self.fileSystem.removeFileTree(packagePath)\n\n            // download without populating the cache when no `cachePath` is set.\n            let _ = try await self.registryClient.downloadSourceArchive(\n                package: package,\n                version: version,\n                destinationPath: packagePath,\n                progressHandler: updateDownloadProgress,\n                fileSystem: self.fileSystem,\n                observabilityScope: observabilityScope\n            )\n            return FetchDetails(fromCache: false, updatedCache: false)\n        }\n\n        // utility to update progress\n\n        @Sendable func updateDownloadProgress(downloaded: Int64, total: Int64?) {\n            Task {\n                await delegate?.fetching(\n                    package: package,\n                    version: version,\n                    bytesDownloaded: downloaded,\n                    totalBytesToDownload: total\n                )\n            }\n        }\n\n        enum DownloadError: Error {\n            case passthrough(Error)\n        }\n    }\n\n    public func remove(package: PackageIdentity) throws {\n        let relativePath = try package.downloadPath()\n        let packagesPath = self.path.appending(relativePath)\n        self.pendingLookups.removeValue(forPackage: package)\n        try self.fileSystem.removeFileTree(packagesPath)\n    }\n\n    public func reset(observabilityScope: ObservabilityScope) {\n        do {\n            try self.fileSystem.removeFileTree(self.path)\n        } catch {\n            observabilityScope.emit(\n                error: \"Error resetting registry downloads at '\\(self.path)'\",\n                underlyingError: error\n            )\n        }\n    }\n\n    public func purgeCache(observabilityScope: ObservabilityScope) {\n        guard let cachePath else {\n            return\n        }\n\n        guard self.fileSystem.exists(cachePath) else {\n            return\n        }\n\n        observabilityScope.emit(info: \"Purging registry cache at '\\(cachePath)'\")\n\n        do {\n            try self.fileSystem.withLock(on: cachePath, type: .exclusive) {\n                let cachedPackages = try self.fileSystem.getDirectoryContents(cachePath)\n                for packagePath in cachedPackages {\n                    let pathToDelete = cachePath.appending(component: packagePath)\n                    do {\n                        try self.fileSystem.removeFileTree(pathToDelete)\n                    } catch {\n                        observabilityScope.emit(\n                            error: \"Error removing cached package at '\\(pathToDelete)'\",\n                            underlyingError: error\n                        )\n                    }\n                }\n            }\n        } catch {\n            observabilityScope.emit(\n                error: \"Error purging registry downloads cache at '\\(cachePath)'\",\n                underlyingError: error\n            )\n        }\n    }\n\n    private func initializeCacheIfNeeded(cachePath: Basics.AbsolutePath) throws {\n        if !self.fileSystem.exists(cachePath) {\n            try self.fileSystem.createDirectory(cachePath, recursive: true)\n        }\n    }\n}\n\n/// Delegate to notify clients about actions being performed by RegistryManager.\npublic protocol RegistryDownloadsManagerDelegate: Sendable {\n    /// Called when a package is about to be fetched.\n    func willFetch(package: PackageIdentity, version: Version, fetchDetails: RegistryDownloadsManager.FetchDetails)\n\n    /// Called when a package has finished fetching.\n    func didFetch(\n        package: PackageIdentity,\n        version: Version,\n        result: Result<RegistryDownloadsManager.FetchDetails, Error>,\n        duration: DispatchTimeInterval\n    )\n\n    /// Called every time the progress of a repository fetch operation updates.\n    func fetching(package: PackageIdentity, version: Version, bytesDownloaded: Int64, totalBytesToDownload: Int64?)\n}\n\nactor RegistryDownloadManagerDelegateProxy {\n    private let delegate: RegistryDownloadsManagerDelegate\n\n    init?(_ delegate: RegistryDownloadsManagerDelegate?) {\n        guard let delegate else {\n            return nil\n        }\n        self.delegate = delegate\n    }\n\n    func willFetch(package: PackageIdentity, version: Version, fetchDetails: RegistryDownloadsManager.FetchDetails) {\n        self.delegate.willFetch(package: package, version: version, fetchDetails: fetchDetails)\n    }\n\n    func didFetch(\n        package: PackageIdentity,\n        version: Version,\n        result: Result<RegistryDownloadsManager.FetchDetails, Error>,\n        duration: DispatchTimeInterval\n    ) {\n        self.delegate.didFetch(package: package, version: version, result: result, duration: duration)\n    }\n\n    func fetching(package: PackageIdentity, version: Version, bytesDownloaded: Int64, totalBytesToDownload: Int64?) {\n        self.delegate.fetching(package: package, version: version, bytesDownloaded: bytesDownloaded, totalBytesToDownload: totalBytesToDownload)\n    }\n}\n\nextension Dictionary where Key == RegistryDownloadsManager.PackageLookup {\n    fileprivate mutating func removeValue(forPackage package: PackageIdentity) {\n        self.keys\n            .filter { $0.package == package }\n            .forEach { self.removeValue(forKey: $0) }\n    }\n}\n\nextension RegistryDownloadsManager {\n    /// Additional information about a fetch\n    public struct FetchDetails: Equatable, Sendable {\n        /// Indicates if the repository was fetched from the cache or from the remote.\n        public let fromCache: Bool\n        /// Indicates whether the repository was already present in the cache and updated or if a clean fetch was performed.\n        public let updatedCache: Bool\n    }\n}\n\nextension FileSystem {\n    func validPackageDirectory(_ path: Basics.AbsolutePath) throws -> Bool {\n        if !self.exists(path) {\n            return false\n        }\n        return try self.getDirectoryContents(path).contains(Manifest.filename)\n    }\n}\n\nextension PackageIdentity {\n    internal func downloadPath() throws -> Basics.RelativePath {\n        guard let registryIdentity = self.registry else {\n            throw StringError(\"invalid package identifier \\(self), expected registry scope and name\")\n        }\n        return try RelativePath(validating: registryIdentity.scope.description).appending(component: registryIdentity.name.description)\n    }\n\n    internal func downloadPath(version: Version) throws -> Basics.RelativePath {\n        try self.downloadPath().appending(component: version.description)\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistry/SignatureValidation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Dispatch\nimport struct Foundation.Data\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport PackageSigning\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\nprotocol SignatureValidationDelegate {\n    func onUnsigned(registry: Registry, package: PackageIdentity, version: Version, completion: (Bool) -> Void)\n    func onUntrusted(registry: Registry, package: PackageIdentity, version: Version, completion: (Bool) -> Void)\n}\n\nstruct SignatureValidation {\n    typealias Delegate = SignatureValidationDelegate\n\n    private let skipSignatureValidation: Bool\n    private let signingEntityTOFU: PackageSigningEntityTOFU\n    private let versionMetadataProvider: (PackageIdentity.RegistryIdentity, Version) async throws -> RegistryClient\n        .PackageVersionMetadata\n    private let delegate: Delegate\n\n    private enum ValidationError: Error {\n        case passthrough(Error)\n    }\n\n    init(\n        skipSignatureValidation: Bool,\n        signingEntityStorage: PackageSigningEntityStorage?,\n        signingEntityCheckingMode: SigningEntityCheckingMode,\n        versionMetadataProvider: @escaping (PackageIdentity.RegistryIdentity, Version) async throws -> RegistryClient\n            .PackageVersionMetadata,\n        delegate: Delegate\n    ) {\n        self.skipSignatureValidation = skipSignatureValidation\n        self.signingEntityTOFU = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n        self.versionMetadataProvider = versionMetadataProvider\n        self.delegate = delegate\n    }\n\n    // MARK: - source archive\n    func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        content: Data,\n        configuration: RegistryConfiguration.Security.Signing,\n        timeout: DispatchTimeInterval?,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SigningEntity? {\n        guard !self.skipSignatureValidation else {\n            return .none\n        }\n\n        let signingEntity = try await self.getAndValidateSourceArchiveSignature(\n            registry: registry,\n            package: package,\n            version: version,\n            content: content,\n            configuration: configuration,\n            timeout: timeout,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n        // Always do signing entity TOFU check at the end,\n        // whether the package is signed or not.\n        let _ = try await self.signingEntityTOFU.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            observabilityScope: observabilityScope\n        )\n        return signingEntity;\n    }\n\n    @available(*, noasync, message: \"Use the async alternative\")\n    func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        content: Data,\n        configuration: RegistryConfiguration.Security.Signing,\n        timeout: DispatchTimeInterval?,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<SigningEntity?, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                content: content,\n                configuration: configuration,\n                timeout: timeout,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    private func getAndValidateSourceArchiveSignature(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        content: Data,\n        configuration: RegistryConfiguration.Security.Signing,\n        timeout: DispatchTimeInterval?,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SigningEntity? {\n        do {\n            let versionMetadata = try await self.versionMetadataProvider(package, version)\n\n            guard let sourceArchiveResource = versionMetadata.sourceArchive else {\n                throw RegistryError.missingSourceArchive\n            }\n            guard let signatureBase64Encoded = sourceArchiveResource.signing?.signatureBase64Encoded else {\n                throw RegistryError.sourceArchiveNotSigned(\n                    registry: registry,\n                    package: package.underlying,\n                    version: version\n                )\n            }\n\n            guard let signatureData = Data(base64Encoded: signatureBase64Encoded) else {\n                throw RegistryError.failedLoadingSignature\n            }\n            guard let signatureFormatString = sourceArchiveResource.signing?.signatureFormat else {\n                throw RegistryError.missingSignatureFormat\n            }\n            guard let signatureFormat = SignatureFormat(rawValue: signatureFormatString) else {\n                throw RegistryError.unknownSignatureFormat(signatureFormatString)\n            }\n\n            do {\n                return try await self.validateSourceArchiveSignature(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    signature: Array(signatureData),\n                    signatureFormat: signatureFormat,\n                    content: Array(content),\n                    configuration: configuration,\n                    fileSystem: fileSystem,\n                    observabilityScope: observabilityScope\n                )\n            } catch {\n                throw ValidationError.passthrough(error)\n            }\n        } catch RegistryError.sourceArchiveNotSigned {\n            observabilityScope.emit(\n                info: \"\\(package) \\(version) from \\(registry) is unsigned\",\n                metadata: .registryPackageMetadata(identity: package)\n            )\n            guard let onUnsigned = configuration.onUnsigned else {\n                throw RegistryError.missingConfiguration(details: \"security.signing.onUnsigned\")\n            }\n\n            let sourceArchiveNotSignedError = RegistryError.sourceArchiveNotSigned(\n                registry: registry,\n                package: package.underlying,\n                version: version\n            )\n\n            switch onUnsigned {\n            case .prompt:\n                return try await withCheckedThrowingContinuation { continuation in\n                    self.delegate\n                        .onUnsigned(registry: registry, package: package.underlying, version: version) { `continue` in\n                            if `continue` {\n                                continuation.resume(returning: .none)\n                            } else {\n                                continuation.resume(throwing: sourceArchiveNotSignedError)\n                            }\n                        }\n                }\n            case .error:\n                throw sourceArchiveNotSignedError\n            case .warn:\n                observabilityScope.emit(\n                    warning: \"\\(sourceArchiveNotSignedError)\",\n                    metadata: .registryPackageMetadata(identity: package)\n                )\n                return .none\n            case .silentAllow:\n                // Continue without logging\n                return .none\n            }\n        } catch RegistryError.failedRetrievingReleaseInfo(_, _, _, let error) {\n            throw RegistryError.failedRetrievingSourceArchiveSignature(\n                registry: registry,\n                package: package.underlying,\n                version: version,\n                error: error\n            )\n        } catch ValidationError.passthrough(let underlyingError) {\n            throw underlyingError\n        } catch {\n            throw RegistryError.failedRetrievingSourceArchiveSignature(\n                registry: registry,\n                package: package.underlying,\n                version: version,\n                error: error\n            )\n        }\n    }\n\n    private func validateSourceArchiveSignature(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        signature: [UInt8],\n        signatureFormat: SignatureFormat,\n        content: [UInt8],\n        configuration: RegistryConfiguration.Security.Signing,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SigningEntity? {\n        do {\n            let signatureStatus = try await SignatureProvider.status(\n                signature: signature,\n                content: content,\n                format: signatureFormat,\n                verifierConfiguration: try VerifierConfiguration.from(configuration, fileSystem: fileSystem),\n                observabilityScope: observabilityScope\n            )\n\n            switch signatureStatus {\n            case .valid(let signingEntity):\n                observabilityScope\n                    .emit(\n                        info: \"\\(package) \\(version) from \\(registry) is signed with a valid entity '\\(signingEntity)'\"\n                    )\n                return signingEntity\n            case .invalid(let reason):\n                throw ValidationError.passthrough(RegistryError.invalidSignature(reason: reason))\n            case .certificateInvalid(let reason):\n                throw ValidationError.passthrough(RegistryError.invalidSigningCertificate(reason: reason))\n            case .certificateNotTrusted(let signingEntity):\n                observabilityScope\n                    .emit(\n                        info: \"\\(package) \\(version) from \\(registry) signing entity '\\(signingEntity)' is untrusted\",\n                        metadata: .registryPackageMetadata(identity: package)\n                    )\n\n                guard let onUntrusted = configuration.onUntrustedCertificate else {\n                    throw ValidationError.passthrough(\n                        RegistryError.missingConfiguration(details: \"security.signing.onUntrustedCertificate\")\n                    )\n                }\n\n                let signerNotTrustedError = ValidationError.passthrough(\n                    RegistryError.signerNotTrusted(package.underlying, signingEntity)\n                )\n\n                switch onUntrusted {\n                case .prompt:\n                    return try await withCheckedThrowingContinuation { continuation in\n                        self.delegate\n                            .onUntrusted(\n                                registry: registry,\n                                package: package.underlying,\n                                version: version\n                            ) { `continue` in\n                                if `continue` {\n                                    continuation.resume(returning: .none)\n                                } else {\n                                    continuation.resume(throwing: signerNotTrustedError)\n                                }\n                            }\n                    }\n                case .error:\n                    throw signerNotTrustedError\n                case .warn:\n                    observabilityScope.emit(\n                        warning: \"\\(signerNotTrustedError)\",\n                        metadata: .registryPackageMetadata(identity: package)\n                    )\n                    return .none\n                case .silentAllow:\n                    // Continue without logging\n                    return .none\n                }\n            }\n        } catch ValidationError.passthrough(let underlyingError) {\n            throw underlyingError\n        } catch {\n            throw RegistryError.failedToValidateSignature(error)\n        }\n    }\n\n    // MARK: - manifests\n    func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        toolsVersion: ToolsVersion?,\n        manifestContent: String,\n        configuration: RegistryConfiguration.Security.Signing,\n        timeout: DispatchTimeInterval?,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SigningEntity? {\n        guard !self.skipSignatureValidation else {\n            return .none\n        }\n\n        let signingEntity = try await self.getAndValidateManifestSignature(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: toolsVersion,\n            manifestContent: manifestContent,\n            configuration: configuration,\n            timeout: timeout,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n\n        let _ = try await self.signingEntityTOFU.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            observabilityScope: observabilityScope\n        )\n        return signingEntity;\n    }\n\n\n    @available(*, noasync, message: \"Use the async alternative\")\n    func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        toolsVersion: ToolsVersion?,\n        manifestContent: String,\n        configuration: RegistryConfiguration.Security.Signing,\n        timeout: DispatchTimeInterval?,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<SigningEntity?, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            try await self.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: toolsVersion,\n                manifestContent: manifestContent,\n                configuration: configuration,\n                timeout: timeout,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    private func getAndValidateManifestSignature(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        toolsVersion: ToolsVersion?,\n        manifestContent: String,\n        configuration: RegistryConfiguration.Security.Signing,\n        timeout: DispatchTimeInterval?,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SigningEntity? {\n        let manifestName = toolsVersion.map { \"Package@swift-\\($0).swift\" } ?? Manifest.filename\n        do {\n            let versionMetadata = try await self.versionMetadataProvider(package, version)\n\n            guard let sourceArchiveResource = versionMetadata.sourceArchive else {\n                observabilityScope\n                    .emit(\n                        debug: \"cannot determine if \\(manifestName) should be signed because source archive for \\(package) \\(version) is not found in \\(registry)\",\n                        metadata: .registryPackageMetadata(identity: package)\n                    )\n                return .none\n            }\n            guard sourceArchiveResource.signing?.signatureBase64Encoded != nil else {\n                throw RegistryError.sourceArchiveNotSigned(\n                    registry: registry,\n                    package: package.underlying,\n                    version: version\n                )\n            }\n\n            // source archive is signed, so the manifest must also be signed\n            guard let manifestSignature = try ManifestSignatureParser.parse(utf8String: manifestContent) else {\n                throw ValidationError.passthrough(RegistryError.manifestNotSigned(\n                    registry: registry,\n                    package: package.underlying,\n                    version: version,\n                    toolsVersion: toolsVersion\n                ))\n            }\n\n            guard let signatureFormat = SignatureFormat(rawValue: manifestSignature.signatureFormat) else {\n                throw ValidationError.passthrough(RegistryError.unknownSignatureFormat(manifestSignature.signatureFormat))\n            }\n\n            do {\n                return try await self.validateManifestSignature(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    manifestName: manifestName,\n                    signature: manifestSignature.signature,\n                    signatureFormat: signatureFormat,\n                    content: manifestSignature.contents,\n                    configuration: configuration,\n                    fileSystem: fileSystem,\n                    observabilityScope: observabilityScope\n                )\n            } catch {\n                throw ValidationError.passthrough(error)\n            }\n        } catch ValidationError.passthrough(let underlyingError) {\n            throw underlyingError\n        } catch RegistryError.sourceArchiveNotSigned {\n            observabilityScope.emit(\n                debug: \"\\(manifestName) is not signed because source archive for \\(package) \\(version) from \\(registry) is not signed\",\n                metadata: .registryPackageMetadata(identity: package)\n            )\n            guard let onUnsigned = configuration.onUnsigned else {\n                throw RegistryError.missingConfiguration(details: \"security.signing.onUnsigned\")\n            }\n\n            let sourceArchiveNotSignedError = RegistryError.sourceArchiveNotSigned(\n                registry: registry,\n                package: package.underlying,\n                version: version\n            )\n\n            // Prompt if configured, otherwise just continue (this differs\n            // from source archive to minimize duplicate loggings).\n            switch onUnsigned {\n            case .prompt:\n                return try await withCheckedThrowingContinuation { continuation in\n                    self.delegate\n                        .onUnsigned(registry: registry, package: package.underlying, version: version) { `continue` in\n                            if `continue` {\n                                continuation.resume(returning: .none)\n                            } else {\n                                continuation.resume(throwing: sourceArchiveNotSignedError)\n                            }\n                        }\n                }\n            default:\n                return .none\n            }\n        } catch ManifestSignatureParser.Error.malformedManifestSignature {\n            throw RegistryError.invalidSignature(reason: \"manifest signature is malformed\")\n        } catch {\n            observabilityScope\n                .emit(\n                    debug: \"cannot determine if \\(manifestName) should be signed because retrieval of source archive signature for \\(package) \\(version) from \\(registry) failed\",\n                    metadata: .registryPackageMetadata(identity: package),\n                    underlyingError: error\n                )\n            return .none\n        }\n    }\n\n    private func validateManifestSignature(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        manifestName: String,\n        signature: [UInt8],\n        signatureFormat: SignatureFormat,\n        content: [UInt8],\n        configuration: RegistryConfiguration.Security.Signing,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SigningEntity? {\n        do {\n            let signatureStatus = try await SignatureProvider.status(\n                signature: signature,\n                content: content,\n                format: signatureFormat,\n                verifierConfiguration: try VerifierConfiguration.from(configuration, fileSystem: fileSystem),\n                observabilityScope: observabilityScope\n            )\n\n            switch signatureStatus {\n            case .valid(let signingEntity):\n                observabilityScope\n                    .emit(\n                        info: \"\\(package) \\(version) \\(manifestName) from \\(registry) is signed with a valid entity '\\(signingEntity)'\"\n                    )\n                return signingEntity\n            case .invalid(let reason):\n                throw ValidationError.passthrough(RegistryError.invalidSignature(reason: reason))\n            case .certificateInvalid(let reason):\n                throw ValidationError.passthrough(RegistryError.invalidSigningCertificate(reason: reason))\n            case .certificateNotTrusted(let signingEntity):\n                observabilityScope\n                    .emit(\n                        debug: \"the signer '\\(signingEntity)' of \\(package) \\(version) \\(manifestName) from \\(registry) is not trusted\",\n                        metadata: .registryPackageMetadata(identity: package)\n                    )\n\n                guard let onUntrusted = configuration.onUntrustedCertificate else {\n                    throw RegistryError.missingConfiguration(details: \"security.signing.onUntrustedCertificate\")\n                }\n\n                let signerNotTrustedError = ValidationError.passthrough(\n                    RegistryError.signerNotTrusted(package.underlying, signingEntity)\n                )\n\n                // Prompt if configured, otherwise just continue (this differs\n                // from source archive to minimize duplicate loggings).\n                switch onUntrusted {\n                case .prompt:\n                    return try await withCheckedThrowingContinuation { continuation in\n                        self.delegate\n                            .onUntrusted(\n                                registry: registry,\n                                package: package.underlying,\n                                version: version\n                            ) { `continue` in\n                                if `continue` {\n                                    continuation.resume(returning: .none)\n                                } else {\n                                    continuation.resume(throwing: signerNotTrustedError)\n                                }\n                            }\n                    }\n                default:\n                    return .none\n                }\n            }\n        } catch ValidationError.passthrough(let underlyingError) {\n            throw underlyingError\n        } catch {\n            throw RegistryError.failedToValidateSignature(error)\n        }\n    }\n\n    // MARK: - signing entity\n\n    static func extractSigningEntity(\n        signature: [UInt8],\n        signatureFormat: SignatureFormat,\n        configuration: RegistryConfiguration.Security.Signing,\n        fileSystem: FileSystem\n    ) async throws -> SigningEntity? {\n        let verifierConfiguration = try VerifierConfiguration.from(configuration, fileSystem: fileSystem)\n        let signingEntity = try await SignatureProvider.extractSigningEntity(\n            signature: signature,\n            format: signatureFormat,\n            verifierConfiguration: verifierConfiguration\n        )\n        return signingEntity\n    }\n}\n\nextension VerifierConfiguration {\n    fileprivate static func from(\n        _ configuration: RegistryConfiguration.Security.Signing,\n        fileSystem: FileSystem\n    ) throws -> VerifierConfiguration {\n        var verifierConfiguration = VerifierConfiguration()\n\n        // Load trusted roots from configured directory\n        if let trustedRootsDirectoryPath = configuration.trustedRootCertificatesPath {\n            let trustedRootsDirectory: Basics.AbsolutePath\n            do {\n                trustedRootsDirectory = try AbsolutePath(validating: trustedRootsDirectoryPath)\n            } catch {\n                throw RegistryError.badConfiguration(details: \"\\(trustedRootsDirectoryPath) is invalid: \\(error.interpolationDescription)\")\n            }\n\n            guard fileSystem.isDirectory(trustedRootsDirectory) else {\n                throw RegistryError.badConfiguration(details: \"\\(trustedRootsDirectoryPath) is not a directory\")\n            }\n\n            do {\n                let trustedRoots = try fileSystem.getDirectoryContents(trustedRootsDirectory).map {\n                    let trustRootPath = trustedRootsDirectory.appending(component: $0)\n                    return try fileSystem.readFileContents(trustRootPath).contents\n                }\n                verifierConfiguration.trustedRoots = trustedRoots\n            } catch {\n                throw RegistryError.badConfiguration(details: \"failed to load trust roots: \\(error.interpolationDescription)\")\n            }\n        }\n\n        // Should default trust store be included?\n        if let includeDefaultTrustedRoots = configuration.includeDefaultTrustedRootCertificates {\n            verifierConfiguration.includeDefaultTrustStore = includeDefaultTrustedRoots\n        }\n\n        if let validationChecks = configuration.validationChecks {\n            // Check certificate expiry\n            if let certificateExpiration = validationChecks.certificateExpiration {\n                switch certificateExpiration {\n                case .enabled:\n                    verifierConfiguration.certificateExpiration = .enabled(validationTime: .none)\n                case .disabled:\n                    verifierConfiguration.certificateExpiration = .disabled\n                }\n            }\n            // Check certificate revocation status\n            if let certificateRevocation = validationChecks.certificateRevocation {\n                switch certificateRevocation {\n                case .strict:\n                    verifierConfiguration.certificateRevocation = .strict(validationTime: .none)\n                case .allowSoftFail:\n                    verifierConfiguration.certificateRevocation = .allowSoftFail(validationTime: .none)\n                case .disabled:\n                    verifierConfiguration.certificateRevocation = .disabled\n                }\n            }\n        }\n\n        return verifierConfiguration\n    }\n}\n\nextension ObservabilityMetadata {\n    public static func registryPackageMetadata(identity: PackageIdentity.RegistryIdentity) -> Self {\n        var metadata = ObservabilityMetadata()\n        metadata.packageIdentity = identity.underlying\n        metadata.packageKind = .registry(identity.underlying)\n        return metadata\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistry/SigningEntityTOFU.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Dispatch\n\nimport Basics\nimport PackageModel\nimport PackageSigning\n\nimport struct TSCUtility.Version\n\nstruct PackageSigningEntityTOFU {\n    private let signingEntityStorage: PackageSigningEntityStorage?\n    private let signingEntityCheckingMode: SigningEntityCheckingMode\n\n    init(\n        signingEntityStorage: PackageSigningEntityStorage?,\n        signingEntityCheckingMode: SigningEntityCheckingMode\n    ) {\n        self.signingEntityStorage = signingEntityStorage\n        self.signingEntityCheckingMode = signingEntityCheckingMode\n    }\n\n    func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        signingEntity: SigningEntity?,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        guard let signingEntityStorage else {\n            return\n        }\n\n        let packageSigners: PackageSigners\n        do {\n            packageSigners = try signingEntityStorage.get(package: package.underlying, observabilityScope: observabilityScope)\n        } catch {\n            observabilityScope.emit(\n                error: \"Failed to get signing entity for \\(package) from storage\",\n                underlyingError: error\n            )\n            throw error\n        }\n\n        let shouldWrite = try await self.validateSigningEntity(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            packageSigners: packageSigners,\n            observabilityScope: observabilityScope\n        )\n\n        // We only use certain type(s) of signing entity for TOFU\n        guard shouldWrite, let signingEntity = signingEntity, case .recognized = signingEntity else {\n            return\n        }\n\n        try self.writeToStorage(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    @available(*, noasync, message: \"Use the async alternative\")\n    func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        signingEntity: SigningEntity?,\n        observabilityScope: ObservabilityScope,\n        completion: @escaping @Sendable (Result<Void, Error>) -> Void\n    ) {\n        DispatchQueue.sharedConcurrent.asyncResult(completion) {\n            try await self.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                signingEntity: signingEntity,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    private func validateSigningEntity(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        signingEntity: SigningEntity?,\n        packageSigners: PackageSigners,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Bool {\n        // Package is never signed.\n        // If signingEntity is nil, it means package remains unsigned, which is OK. (none -> none)\n        // Otherwise, package has gained a signer, which is also OK. (none -> some)\n        if packageSigners.isEmpty {\n            return true\n        }\n\n        // If we get to this point, it means we have seen a signed version of the package.\n        let signingEntitiesForVersion = packageSigners.signingEntities(of: version)\n\n        // We recorded the version's signer(s) previously\n        if !signingEntitiesForVersion.isEmpty {\n            guard let signingEntityToCheck = signingEntity,\n                  signingEntitiesForVersion.contains(signingEntityToCheck)\n            else {\n                // The given signer is nil or different\n                // TODO: This could indicate a legitimate change\n                //   - If signingEntity is nil, it could mean the package author has stopped signing the package.\n                //   - If signingEntity is non-nil, it could mean the package has changed ownership and the new owner\n                //     is re-signing all of the package versions.\n                try self.handleSigningEntityForPackageVersionChanged(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    latest: signingEntity,\n                    existing: signingEntitiesForVersion.first!, // !-safe since signingEntitiesForVersion is non-empty\n                    observabilityScope: observabilityScope\n                )\n                return false\n            }\n            // Signer remains the same for the version\n            return false\n        }\n\n        // Check signer(s) of other version(s)\n        switch signingEntity {\n        // Is the package changing from one signer to another?\n        case .some(let signingEntity):\n            // Does the package have an expected signer?\n            if let expectedSigner = packageSigners.expectedSigner,\n               version >= expectedSigner.fromVersion\n            {\n                // Signer is as expected\n                if signingEntity == expectedSigner.signingEntity {\n                    return true\n                }\n                // If the signer is different from expected but has been seen before,\n                // we allow versions before its highest known version to be signed\n                // by this signer. This is to handle the case where a signer was recorded\n                // before expectedSigner is set, and it had signed a version newer than\n                // expectedSigner.fromVersion. For example, if signer A is recorded to have\n                // signed v2.0 and later expectedSigner is set to signer B with fromVersion\n                // set to v1.5, then it should not be a TOFU failure if we see signer A\n                // for v1.9.\n                if let knownSigner = packageSigners.signers[signingEntity],\n                   let highestKnownVersion = knownSigner.versions.sorted(by: >).first,\n                   version < highestKnownVersion\n                {\n                    return true\n                }\n                // Different signer than expected\n                try self.handleSigningEntityForPackageChanged(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    latest: signingEntity,\n                    existing: expectedSigner.signingEntity,\n                    existingVersion: expectedSigner.fromVersion,\n                    observabilityScope: observabilityScope\n                )\n                return false\n            } else {\n                // There might be other signers, but if we have seen this signer before, allow it.\n                if packageSigners.signers[signingEntity] != nil {\n                    return true\n                }\n\n                let otherSigningEntities = packageSigners.signers.keys.filter { $0 != signingEntity }\n                for otherSigningEntity in otherSigningEntities {\n                    // We have not seen this signer before, and there is at least one other signer already.\n                    // TODO: This could indicate a legitimate change in package ownership\n                    if let existingVersion = packageSigners.signers[otherSigningEntity]?.versions.sorted(by: >).first {\n                        try self.handleSigningEntityForPackageChanged(\n                            registry: registry,\n                            package: package,\n                            version: version,\n                            latest: signingEntity,\n                            existing: otherSigningEntity,\n                            existingVersion: existingVersion,\n                            observabilityScope: observabilityScope\n                        )\n                        return false\n                    }\n                }\n\n                // Package doesn't have any other signer besides the given one, which is good.\n                return true\n            }\n        // Or is the package going from having a signer to .none?\n        case .none:\n            let versionSigningEntities = packageSigners.versionSigningEntities\n            // If the given version is semantically newer than any signed version,\n            // then it must be signed. (i.e., when a package starts being signed\n            // at a version, then all future versions must be signed.)\n            // TODO: We might want to allow package becoming unsigned\n            //\n            // Here we try to handle the scenario where there is more than\n            // one major version branch, and signing didn't start from the beginning\n            // for both of them. For example, suppose a project has 1.x and 2.x active\n            // major versions, and signing starts at 1.2.0 and 2.2.0. The first version\n            // that SwiftPM downloads is 1.5.0, which is signed and signer gets recorded.\n            //   - When unsigned v1.1.0 is downloaded, we don't fail because it's\n            //     an older version (i.e., < 1.5.0) and we allow it to be unsigned.\n            //   - When unsigned v1.6.0 is downloaded, we fail because it's\n            //     a newer version (i.e., < 1.5.0) and we assume it to be signed.\n            //   - When unsigned v2.0.0 is downloaded, we don't fail because we haven't\n            //     seen a signed 2.x release yet, so we assume 2.x releases are not signed.\n            //     (this might be controversial)\n            let olderSignedVersions = versionSigningEntities.keys\n                .filter { $0.major == version.major && $0 < version }\n                .sorted(by: >)\n            for olderSignedVersion in olderSignedVersions {\n                if let olderVersionSigner = versionSigningEntities[olderSignedVersion]?.first {\n                    try self.handleSigningEntityForPackageChanged(\n                        registry: registry,\n                        package: package,\n                        version: version,\n                        latest: signingEntity,\n                        existing: olderVersionSigner,\n                        existingVersion: olderSignedVersion,\n                        observabilityScope: observabilityScope\n                    )\n                    return false\n                }\n            }\n            // Assume the given version is an older version before package started getting signed\n            return false\n        }\n    }\n\n    private func writeToStorage(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        guard let signingEntityStorage else {\n            return\n        }\n\n        do {\n            try signingEntityStorage.put(\n                package: package.underlying,\n                version: version,\n                signingEntity: signingEntity,\n                origin: .registry(registry.url),\n                observabilityScope: observabilityScope\n            )\n        } catch PackageSigningEntityStorageError.conflict(_, _, _, let existing) {\n            try self.handleSigningEntityForPackageVersionChanged(\n                registry: registry,\n                package: package,\n                version: version,\n                latest: signingEntity,\n                existing: existing,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    private func handleSigningEntityForPackageVersionChanged(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        latest: SigningEntity?,\n        existing: SigningEntity,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        switch self.signingEntityCheckingMode {\n        case .strict:\n            throw RegistryError.signingEntityForReleaseChanged(\n                registry: registry,\n                package: package.underlying,\n                version: version,\n                latest: latest,\n                previous: existing\n            )\n        case .warn:\n            observabilityScope\n                .emit(\n                    warning: \"the signing entity '\\(String(describing: latest))' from \\(registry) for \\(package) version \\(version) is different from the previously recorded value '\\(existing)'\"\n                )\n        }\n    }\n\n    private func handleSigningEntityForPackageChanged(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        latest: SigningEntity?,\n        existing: SigningEntity,\n        existingVersion: Version,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        switch self.signingEntityCheckingMode {\n        case .strict:\n            throw RegistryError.signingEntityForPackageChanged(\n                registry: registry,\n                package: package.underlying,\n                version: version,\n                latest: latest,\n                previous: existing,\n                previousVersion: existingVersion\n            )\n        case .warn:\n            observabilityScope\n                .emit(\n                    warning: \"the signing entity '\\(String(describing: latest))' from \\(registry) for \\(package) version \\(version) is different from the previously recorded value '\\(existing)' for version \\(existingVersion)\"\n                )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistryCommand/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageRegistryCommand\n  PackageRegistryCommand+Auth.swift\n  PackageRegistryCommand+Publish.swift\n  PackageRegistryCommand.swift)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageRegistryCommand PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\ntarget_link_libraries(PackageRegistryCommand PUBLIC\n  Basics\n  Commands\n  CoreCommands\n  PackageFingerprint\n  PackageModel\n  PackageRegistry\n  PackageSigning\n  Workspace\n  ArgumentParser\n  TSCBasic\n  TSCUtility\n  X509)\nif(NOT APPLE)\n  if(Foundation_FOUND)\n    target_link_directories(PackageRegistryCommand PRIVATE\n      $<TARGET_LINKER_FILE_DIR:Fooundation>)\n  endif()\nendif()\n\ninstall(TARGETS PackageRegistryCommand\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/PackageRegistryCommand/PackageRegistryCommand+Auth.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport Commands\nimport CoreCommands\nimport Foundation\nimport PackageFingerprint\nimport PackageModel\nimport PackageRegistry\nimport PackageSigning\nimport Workspace\n\nimport struct TSCBasic.SHA256\n\n#if os(Windows)\nimport WinSDK\n\nprivate func readpassword(_ prompt: String) throws -> String {\n    enum StaticStorage {\n        static var buffer: UnsafeMutableBufferPointer<CChar> =\n            .allocate(capacity: PackageRegistryCommand.Login.passwordBufferSize)\n    }\n\n    let hStdIn: HANDLE = GetStdHandle(STD_INPUT_HANDLE)\n    if hStdIn == INVALID_HANDLE_VALUE {\n        throw StringError(\"unable to read input: GetStdHandle returns INVALID_HANDLE_VALUE\")\n    }\n\n    var dwMode: DWORD = 0\n    guard GetConsoleMode(hStdIn, &dwMode) else {\n        throw StringError(\"unable to read input: GetConsoleMode failed\")\n    }\n\n    print(prompt, terminator: \"\")\n\n    guard SetConsoleMode(hStdIn, DWORD(ENABLE_LINE_INPUT)) else {\n        throw StringError(\"unable to read input: SetConsoleMode failed\")\n    }\n    defer { SetConsoleMode(hStdIn, dwMode) }\n\n    var dwNumberOfCharsRead: DWORD = 0\n    _ = ReadConsoleA(\n        hStdIn,\n        StaticStorage.buffer.baseAddress,\n        DWORD(StaticStorage.buffer.count),\n        &dwNumberOfCharsRead,\n        nil\n    )\n\n    let password = String(cString: UnsafePointer<CChar>(StaticStorage.buffer.baseAddress!))\n    guard password.count <= PackageRegistryCommand.Login.maxPasswordLength else {\n        throw PackageRegistryCommand.ValidationError\n            .credentialLengthLimitExceeded(PackageRegistryCommand.Login.maxPasswordLength)\n    }\n    return password\n}\n#else\n#if canImport(Android)\nimport Android\n#endif\n\nprivate func readpassword(_ prompt: String) throws -> String {\n    let password: String\n\n    #if canImport(Darwin)\n    var buffer = [CChar](repeating: 0, count: PackageRegistryCommand.Login.passwordBufferSize)\n    password = try withExtendedLifetime(buffer) {\n        guard let passwordPtr = readpassphrase(prompt, &buffer, buffer.count, 0) else {\n            throw StringError(\"unable to read input\")\n        }\n\n        return String(cString: passwordPtr)\n    }\n    #elseif canImport(Android)\n    throw StringError(\"unable to read input - not implemented on this platform\")\n    #else\n    // GNU C implementation of getpass has no limit on the password length\n    // (https://man7.org/linux/man-pages/man3/getpass.3.html)\n    password = String(cString: getpass(prompt))\n    #endif\n\n    guard password.count <= PackageRegistryCommand.Login.maxPasswordLength else {\n        throw PackageRegistryCommand.ValidationError\n            .credentialLengthLimitExceeded(PackageRegistryCommand.Login.maxPasswordLength)\n    }\n    return password\n}\n#endif\n\nextension PackageRegistryCommand {\n    struct Login: AsyncSwiftCommand {\n\n        static func loginURL(from registryURL: URL, loginAPIPath: String?) throws -> URL {\n            // Login URL must be HTTPS\n            var loginURLComponents = URLComponents(url: registryURL, resolvingAgainstBaseURL: true)\n            loginURLComponents?.scheme = \"https\"\n            loginURLComponents?.path = loginAPIPath ?? \"/login\"\n\n            guard let loginURL = loginURLComponents?.url else {\n                throw ValidationError.invalidURL(registryURL)\n            }\n\n            return loginURL\n        }\n\n        static let configuration = CommandConfiguration(\n            abstract: \"Log in to a registry.\"\n        )\n\n        static let maxPasswordLength = 512\n        // Define a larger buffer size so we read more than allowed, and\n        // this way we can tell if the entered password is over the length\n        // limit. One space is for \\0, another is for the \"overflowing\" char.\n        static let passwordBufferSize = Self.maxPasswordLength + 2\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Argument(help: \"The registry URL.\")\n        var url: URL?\n\n        var registryURL: URL? {\n            self.url\n        }\n\n        @Option(help: \"The username for the registry.\")\n        var username: String?\n\n        @Option(help: \"The password for the registry.\")\n        var password: String?\n\n        @Option(help: \"The access token for the registry.\")\n        var token: String?\n\n        @Option(\n            name: .customLong(\"token-file\"),\n            help: \"Path to the file containing access token.\"\n        )\n        var tokenFilePath: AbsolutePath?\n\n        @Flag(help: \"Write to the netrc file without asking for confirmation.\")\n        var noConfirm: Bool = false\n\n        private static let PLACEHOLDER_TOKEN_USER = \"token\"\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            // We need to be able to read/write credentials\n            // Make sure credentials store is available before proceeding\n            let authorizationProvider: AuthorizationProvider?\n            do {\n                authorizationProvider = try swiftCommandState.getRegistryAuthorizationProvider()\n            } catch {\n                throw ValidationError.invalidCredentialStore(error)\n            }\n\n            guard let authorizationProvider else {\n                throw ValidationError.unknownCredentialStore\n            }\n\n            // Auth config is in user-level registries config only\n            let configuration = try getRegistriesConfig(swiftCommandState, global: true)\n\n            // compute and validate registry URL\n            guard let registryURL = self.registryURL ?? configuration.configuration.defaultRegistry?.url else {\n                throw ValidationError.unknownRegistry\n            }\n\n            try registryURL.validateRegistryURL()\n\n            let authenticationType: RegistryConfiguration.AuthenticationType\n            let storeUsername: String\n            let storePassword: String\n            var saveChanges = true\n\n            if let username {\n                authenticationType = .basic\n\n                storeUsername = username\n                if let password {\n                    // User provided password\n                    storePassword = password\n                } else if let stored = authorizationProvider.authentication(for: registryURL),\n                          stored.user == storeUsername\n                {\n                    // Password found in credential store\n                    storePassword = stored.password\n                    saveChanges = false\n                } else {\n                    // Prompt user for password\n                    storePassword = try readpassword(\"Enter password for '\\(storeUsername)': \")\n                }\n            } else {\n                authenticationType = .token\n\n                // All token auth accounts have the same placeholder value\n                storeUsername = Self.PLACEHOLDER_TOKEN_USER\n                if let token {\n                    // User provided token\n                    storePassword = token\n                } else if let tokenFilePath {\n                    print(\"Reading access token from \\(tokenFilePath).\")\n                    storePassword = try localFileSystem.readFileContents(tokenFilePath)\n                        .trimmingCharacters(in: .whitespacesAndNewlines)\n                } else if let stored = authorizationProvider.authentication(for: registryURL),\n                          stored.user == storeUsername\n                {\n                    // Token found in credential store\n                    storePassword = stored.password\n                    saveChanges = false\n                } else {\n                    // Prompt user for token\n                    storePassword = try readpassword(\"Enter access token: \")\n                }\n            }\n\n            let authorizationWriter = authorizationProvider as? AuthorizationWriter\n            if saveChanges, authorizationWriter == nil {\n                throw StringError(\"Credential store must be writable\")\n            }\n\n            // Save in cache so we can try the credentials and persist to storage only if login succeeds\n            try await authorizationWriter?.addOrUpdate(\n                for: registryURL,\n                user: storeUsername,\n                password: storePassword,\n                persist: false\n            )\n\n            // `url` can either be base URL of the registry, in which case the login API\n            // is assumed to be at /login, or the full URL of the login API.\n            var loginAPIPath: String?\n            if !registryURL.path.isEmpty, registryURL.path != \"/\" {\n                loginAPIPath = registryURL.path\n            }\n\n            let loginURL = try Self.loginURL(from: registryURL, loginAPIPath: loginAPIPath)\n\n\n            // Build a RegistryConfiguration with the given authentication settings\n            var registryConfiguration = configuration.configuration\n            try registryConfiguration.add(authentication: .init(type: authenticationType, loginAPIPath: loginAPIPath), for: registryURL)\n\n            // Build a RegistryClient to test login credentials (fingerprints don't matter in this case)\n            let registryClient = RegistryClient(\n                configuration: registryConfiguration,\n                fingerprintStorage: .none,\n                fingerprintCheckingMode: .strict,\n                skipSignatureValidation: false,\n                signingEntityStorage: .none,\n                signingEntityCheckingMode: .strict,\n                authorizationProvider: authorizationProvider,\n                delegate: .none,\n                checksumAlgorithm: SHA256()\n            )\n\n            // Try logging in\n            try await registryClient.login(\n                loginURL: loginURL,\n                timeout: .seconds(5),\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n\n            print(\"Login successful.\")\n\n            // Login successful. Persist credentials to storage.\n\n            let osStore = !(authorizationWriter is NetrcAuthorizationProvider)\n\n            // Prompt if writing to netrc file and --no-confirm is not set\n            if saveChanges, !osStore, !self.noConfirm {\n                if self.globalOptions.security.forceNetrc {\n                    print(\"\"\"\n\n                    WARNING: You choose to use netrc file instead of the operating system's secure credential store.\n                    Your credentials will be written out to netrc file.\n                    \"\"\")\n                } else {\n                    print(\"\"\"\n\n                    WARNING: Secure credential store is not supported on this platform.\n                    Your credentials will be written out to netrc file.\n                    \"\"\")\n                }\n                print(\"Continue? (Yes/No): \")\n                guard readLine(strippingNewline: true)?.lowercased() == \"yes\" else {\n                    print(\"Credentials not saved. Exiting...\")\n                    return\n                }\n            }\n\n            if saveChanges {\n                try await authorizationWriter?.addOrUpdate(\n                    for: registryURL,\n                    user: storeUsername,\n                    password: storePassword,\n                    persist: true\n                )\n\n                if osStore {\n                    print(\"\\nCredentials have been saved to the operating system's secure credential store.\")\n                } else {\n                    print(\"\\nCredentials have been saved to netrc file.\")\n                }\n            }\n\n            // Update user-level registry configuration file\n            let update: (inout RegistryConfiguration) throws -> Void = { configuration in\n                try configuration.add(authentication: .init(type: authenticationType, loginAPIPath: loginAPIPath), for: registryURL)\n            }\n            try configuration.updateShared(with: update)\n\n            print(\"Registry configuration updated.\")\n        }\n    }\n\n    struct Logout: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Log out from a registry.\"\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Argument(help: \"The registry URL.\")\n        var url: URL?\n\n        var registryURL: URL? {\n            self.url\n        }\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            // Auth config is in user-level registries config only\n            let configuration = try getRegistriesConfig(swiftCommandState, global: true)\n\n            // compute and validate registry URL\n            guard let registryURL = self.registryURL ?? configuration.configuration.defaultRegistry?.url else {\n                throw ValidationError.unknownRegistry\n            }\n\n            try registryURL.validateRegistryURL()\n\n            // We need to be able to read/write credentials\n            guard let authorizationProvider = try swiftCommandState.getRegistryAuthorizationProvider() else {\n                throw ValidationError.unknownCredentialStore\n            }\n\n            let authorizationWriter = authorizationProvider as? AuthorizationWriter\n            let osStore = !(authorizationWriter is NetrcAuthorizationProvider)\n\n            // Only OS credential store supports deletion\n            if osStore {\n                try await authorizationWriter?.remove(for: registryURL)\n                print(\"Credentials have been removed from operating system's secure credential store.\")\n            } else {\n                print(\"netrc file not updated. Please remove credentials from the file manually.\")\n            }\n\n            // Update user-level registry configuration file\n            let update: (inout RegistryConfiguration) throws -> Void = { configuration in\n                configuration.removeAuthentication(for: registryURL)\n            }\n            try configuration.updateShared(with: update)\n\n            print(\"Registry configuration updated.\")\n            print(\"Logout successful.\")\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistryCommand/PackageRegistryCommand+Publish.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport Commands\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport PackageFingerprint\nimport PackageRegistry\nimport PackageSigning\nimport Workspace\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import X509 // FIXME: need this import or else SwiftSigningIdentity initializer fails\n#else\nimport X509\n#endif\n\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.RegEx\nimport struct TSCBasic.SHA256\n\nimport struct TSCUtility.Version\n\nextension PackageRegistryCommand {\n    struct Publish: AsyncSwiftCommand {\n        static let metadataFilename = \"package-metadata.json\"\n\n        static let configuration = CommandConfiguration(\n            abstract: \"Publish to a registry.\"\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Argument(help: .init(\"The package identifier.\", valueName: \"package-id\"))\n        var packageIdentity: PackageIdentity\n\n        @Argument(help: .init(\"The package release version being created.\", valueName: \"package-version\"))\n        var packageVersion: Version\n\n        @Option(name: [.customLong(\"url\"), .customLong(\"registry-url\")], help: \"The registry URL.\")\n        var registryURL: URL?\n\n        @Option(\n            name: .customLong(\"scratch-directory\"),\n            help: \"The path to the directory for working files.\"\n        )\n        var customWorkingDirectory: AbsolutePath?\n\n        @Option(\n            name: .customLong(\"metadata-path\"),\n            help: \"The path to the package metadata JSON file if it is not '\\(Self.metadataFilename)' in the package directory.\"\n        )\n        var customMetadataPath: AbsolutePath?\n\n        @Option(help: .hidden) // help: \"Signature format identifier. Defaults to 'cms-1.0.0'.\n        var signatureFormat: SignatureFormat = .cms_1_0_0\n\n        @Option(\n            help: \"The label of the signing identity to be retrieved from the system's identity store if supported.\"\n        )\n        var signingIdentity: String?\n\n        @Option(help: \"The path to the certificate's PKCS#8 private key (DER-encoded).\")\n        var privateKeyPath: AbsolutePath?\n\n        @Option(\n            name: .customLong(\"cert-chain-paths\"),\n            parsing: .upToNextOption,\n            help: \"Path(s) to the signing certificate (DER-encoded) and optionally the rest of the certificate chain. Certificates should be ordered with the leaf first and the root last.\"\n        )\n        var certificateChainPaths: [AbsolutePath] = []\n\n        @Flag(name: .customLong(\"allow-insecure-http\"), help: \"Use a non-HTTPS registry URL.\")\n        var allowInsecureHTTP: Bool = false\n\n        @Flag(help: \"Prepare and sign the archive without publishing it to the registry.\")\n        var dryRun: Bool = false\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            // Require both local and user-level registries config\n            let configuration = try getRegistriesConfig(swiftCommandState, global: false).configuration\n\n            // validate package location\n            let packageDirectory = try self.globalOptions.locations.packageDirectory ?? swiftCommandState.getPackageRoot()\n            guard localFileSystem.isDirectory(packageDirectory) else {\n                throw StringError(\"No package found at '\\(packageDirectory)'.\")\n            }\n\n            // validate package identity\n            guard let registryIdentity = self.packageIdentity.registry else {\n                throw ValidationError.invalidPackageIdentity(self.packageIdentity)\n            }\n\n            // compute and validate registry URL\n            let registryURL = self.registryURL ?? configuration.registry(for: registryIdentity.scope)?.url\n            guard let registryURL else {\n                throw ValidationError.unknownRegistry\n            }\n\n            let allowHTTP = try self.allowInsecureHTTP && (configuration.authentication(for: registryURL) == nil)\n            try registryURL.validateRegistryURL(allowHTTP: allowHTTP)\n\n            // validate working directory path\n            if let customWorkingDirectory {\n                guard localFileSystem.isDirectory(customWorkingDirectory) else {\n                    throw StringError(\"Directory not found at '\\(customWorkingDirectory)'.\")\n                }\n            }\n\n            let workingDirectory = self.customWorkingDirectory ?? Workspace.DefaultLocations\n                .scratchDirectory(forRootPackage: packageDirectory).appending(components: [\"registry\", \"publish\"])\n            if localFileSystem.exists(workingDirectory) {\n                try localFileSystem.removeFileTree(workingDirectory)\n            }\n            // Make sure the working directory exists\n            try localFileSystem.createDirectory(workingDirectory, recursive: true)\n\n            // validate custom metadata path\n            let defaultMetadataPath = packageDirectory.appending(component: Self.metadataFilename)\n            var metadataLocation: MetadataLocation? = .none\n            if let customMetadataPath {\n                guard localFileSystem.exists(customMetadataPath) else {\n                    throw StringError(\"Metadata file not found at '\\(customMetadataPath)'.\")\n                }\n                metadataLocation = .external(customMetadataPath)\n            } else if localFileSystem.exists(defaultMetadataPath) {\n                metadataLocation = .sourceTree(defaultMetadataPath)\n            }\n\n            guard let authorizationProvider = try swiftCommandState.getRegistryAuthorizationProvider() else {\n                throw ValidationError.unknownCredentialStore\n            }\n\n            let registryClient = RegistryClient(\n                configuration: configuration,\n                fingerprintStorage: .none,\n                fingerprintCheckingMode: .strict,\n                skipSignatureValidation: false,\n                signingEntityStorage: .none,\n                signingEntityCheckingMode: .strict,\n                authorizationProvider: authorizationProvider,\n                delegate: .none,\n                checksumAlgorithm: SHA256()\n            )\n\n            // step 1: publishing configuration\n            let signingRequired = self.signingIdentity != nil || self.privateKeyPath != nil || !self\n                .certificateChainPaths.isEmpty\n\n            let archivePath: AbsolutePath\n            var archiveSignature: [UInt8]? = .none\n            var metadataSignature: [UInt8]? = .none\n            if signingRequired {\n                // step 2: generate source archive (includes signed manifests) for the package release\n                // step 3: sign source archive and metadata\n                let signingMode = try PackageArchiveSigner.computeSigningMode(\n                    signingIdentity: self.signingIdentity,\n                    privateKeyPath: self.privateKeyPath,\n                    certificateChainPaths: self.certificateChainPaths\n                )\n\n                let result = try await PackageArchiveSigner.prepareArchiveAndSign(\n                    packageIdentity: packageIdentity,\n                    packageVersion: packageVersion,\n                    packageDirectory: packageDirectory,\n                    metadataPath: metadataLocation?.path,\n                    workingDirectory: workingDirectory,\n                    mode: signingMode,\n                    signatureFormat: self.signatureFormat,\n                    cancellator: swiftCommandState.cancellator,\n                    fileSystem: localFileSystem,\n                    observabilityScope: swiftCommandState.observabilityScope\n                )\n                archivePath = result.archive.path\n                archiveSignature = result.archive.signature\n                metadataSignature = result.metadata?.signature\n            } else {\n                // step 2: generate source archive for the package release\n                // step 3: signing not required\n                swiftCommandState.observabilityScope.emit(info: \"archiving the source at '\\(packageDirectory)'\")\n                archivePath = try await PackageArchiver.archive(\n                    packageIdentity: self.packageIdentity,\n                    packageVersion: self.packageVersion,\n                    packageDirectory: packageDirectory,\n                    workingDirectory: workingDirectory,\n                    workingFilesToCopy: [],\n                    cancellator: swiftCommandState.cancellator,\n                    observabilityScope: swiftCommandState.observabilityScope\n                )\n            }\n\n            // step 4: publish the package if not dry-run\n            guard !self.dryRun else {\n                print(\n                    \"\\(packageIdentity)@\\(packageVersion) was successfully prepared for publishing but was not published due to dry run flag. Artifacts available at '\\(workingDirectory)'.\"\n                )\n                return\n            }\n\n            swiftCommandState.observabilityScope\n                .emit(info: \"publishing \\(self.packageIdentity) archive at '\\(archivePath)' to \\(registryURL)\")\n            let result = try await registryClient.publish(\n                registryURL: registryURL,\n                packageIdentity: self.packageIdentity,\n                packageVersion: self.packageVersion,\n                packageArchive: archivePath,\n                packageMetadata: metadataLocation?.path,\n                signature: archiveSignature,\n                metadataSignature: metadataSignature,\n                signatureFormat: self.signatureFormat,\n                fileSystem: localFileSystem,\n                observabilityScope: swiftCommandState.observabilityScope\n            )\n\n            switch result {\n            case .published(.none):\n                print(\"\\(packageIdentity) version \\(packageVersion) was successfully published to \\(registryURL)\")\n            case .published(.some(let location)):\n                print(\n                    \"\\(packageIdentity) version \\(packageVersion) was successfully published to \\(registryURL) and is available at '\\(location)'\"\n                )\n            case .processing(let statusURL, _):\n                print(\n                    \"\\(packageIdentity) version \\(packageVersion) was successfully submitted to \\(registryURL) and is being processed. Publishing status is available at '\\(statusURL)'.\"\n                )\n            }\n        }\n    }\n}\n\nextension SignatureFormat {\n    public init?(argument: String) {\n        self.init(rawValue: argument.lowercased())\n    }\n}\n\nextension SignatureFormat: ExpressibleByArgument {}\n\nenum MetadataLocation {\n    case sourceTree(AbsolutePath)\n    case external(AbsolutePath)\n\n    var path: AbsolutePath {\n        switch self {\n        case .sourceTree(let path):\n            return path\n        case .external(let path):\n            return path\n        }\n    }\n}\n\n// MARK: - Helpers\n\nenum PackageArchiveSigner {\n    static func computeSigningMode(\n        signingIdentity: String?,\n        privateKeyPath: AbsolutePath?,\n        certificateChainPaths: [AbsolutePath]\n    ) throws -> SigningMode {\n        let signingMode: PackageArchiveSigner.SigningMode\n        switch (signingIdentity, certificateChainPaths, privateKeyPath) {\n        case (.none, let certChainPaths, .none) where !certChainPaths.isEmpty:\n            throw StringError(\n                \"Both 'private-key-path' and 'cert-chain-paths' are required when one of them is set.\"\n            )\n        case (.none, let certChainPaths, .some) where certChainPaths.isEmpty:\n            throw StringError(\n                \"Both 'private-key-path' and 'cert-chain-paths' are required when one of them is set.\"\n            )\n        case (.none, let certChainPaths, .some(let privateKeyPath)) where !certChainPaths.isEmpty:\n            let certificate = certChainPaths[0]\n            let intermediateCertificates = certChainPaths.count > 1 ? Array(certChainPaths[1...]) : []\n            signingMode = .certificate(\n                certificate: certificate,\n                intermediateCertificates: intermediateCertificates,\n                privateKey: privateKeyPath\n            )\n        case (.some(let signingStoreLabel), let certChainPaths, .none) where certChainPaths.isEmpty:\n            signingMode = .identityStore(label: signingStoreLabel, intermediateCertificates: certChainPaths)\n        default:\n            throw StringError(\n                \"Either 'signing-identity' or 'private-key-path' (together with 'cert-chain-paths') must be provided.\"\n            )\n        }\n        return signingMode\n    }\n\n    static func prepareArchiveAndSign(\n        packageIdentity: PackageIdentity,\n        packageVersion: Version,\n        packageDirectory: AbsolutePath,\n        metadataPath: AbsolutePath?,\n        workingDirectory: AbsolutePath,\n        mode: SigningMode,\n        signatureFormat: SignatureFormat,\n        cancellator: Cancellator?,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> ArchiveAndSignResult {\n        // signing identity\n        let (signingIdentity, intermediateCertificates) = try Self.signingIdentityAndIntermediateCertificates(\n            mode: mode,\n            signatureFormat: signatureFormat,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n\n        // sign package manifest(s)\n        let manifests = try Self.findManifests(packageDirectory: packageDirectory)\n        try manifests.forEach {\n            observabilityScope.emit(info: \"signing \\($0)\")\n            let signedManifestPath = workingDirectory.appending($0)\n\n            var manifest = try fileSystem.readFileContents(packageDirectory.appending($0)).contents\n            let signature = try SignatureProvider.sign(\n                content: manifest,\n                identity: signingIdentity,\n                intermediateCertificates: intermediateCertificates,\n                format: signatureFormat,\n                observabilityScope: observabilityScope\n            )\n            manifest\n                .append(\n                    contentsOf: Array(\n                        \"\\n// signature: \\(signatureFormat.rawValue);\\(Data(signature).base64EncodedString())\"\n                            .utf8\n                    )\n                )\n            try fileSystem.writeFileContents(signedManifestPath, bytes: .init(manifest))\n        }\n\n        // create the archive\n        observabilityScope.emit(info: \"archiving the source at '\\(packageDirectory)'\")\n        let archivePath = try await PackageArchiver.archive(\n            packageIdentity: packageIdentity,\n            packageVersion: packageVersion,\n            packageDirectory: packageDirectory,\n            workingDirectory: workingDirectory,\n            workingFilesToCopy: manifests,\n            cancellator: cancellator,\n            observabilityScope: observabilityScope\n        )\n        let archive = try localFileSystem.readFileContents(archivePath).contents\n\n        // sign the archive\n        observabilityScope.emit(info: \"signing the archive at '\\(archivePath)'\")\n        let archiveSignature = try SignatureProvider.sign(\n            content: archive,\n            identity: signingIdentity,\n            intermediateCertificates: intermediateCertificates,\n            format: signatureFormat,\n            observabilityScope: observabilityScope\n        )\n        let archiveSignaturePath = workingDirectory.appending(\"\\(packageIdentity)-\\(packageVersion).sig\")\n        try fileSystem.writeFileContents(archiveSignaturePath, bytes: .init(archiveSignature))\n\n        var signedMetadata: SignedItem? = .none\n        if let metadataPath {\n            observabilityScope.emit(info: \"signing metadata at '\\(metadataPath)'\")\n            let metadata = try localFileSystem.readFileContents(metadataPath).contents\n            let metadataSignature = try SignatureProvider.sign(\n                content: metadata,\n                identity: signingIdentity,\n                intermediateCertificates: intermediateCertificates,\n                format: signatureFormat,\n                observabilityScope: observabilityScope\n            )\n            let metadataSignaturePath = workingDirectory.appending(\"\\(packageIdentity)-\\(packageVersion)-metadata.sig\")\n            try fileSystem.writeFileContents(metadataSignaturePath, bytes: .init(metadataSignature))\n            signedMetadata = .init(path: metadataPath, signature: metadataSignature)\n        }\n\n        return ArchiveAndSignResult(\n            archive: .init(path: archivePath, signature: archiveSignature),\n            signedManifests: manifests,\n            metadata: signedMetadata\n        )\n    }\n\n    private static func signingIdentityAndIntermediateCertificates(\n        mode: SigningMode,\n        signatureFormat: SignatureFormat,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws -> (SigningIdentity, [[UInt8]]) {\n        let signingIdentity: SigningIdentity\n        let intermediateCertificates: [[UInt8]]\n        switch mode {\n        case .identityStore(let label, let intermediateCertPaths):\n            let signingIdentityStore = SigningIdentityStore(observabilityScope: observabilityScope)\n            let matches = signingIdentityStore.find(by: label)\n            guard let identity = matches.first else {\n                throw StringError(\"'\\(label)' not found in the system identity store.\")\n            }\n            // TODO: let user choose if there is more than one match?\n            signingIdentity = identity\n            intermediateCertificates = try intermediateCertPaths.map { try fileSystem.readFileContents($0).contents }\n        case .certificate(let certPath, let intermediateCertPaths, let privateKeyPath):\n            let certificate = try fileSystem.readFileContents(certPath).contents\n            let privateKey = try fileSystem.readFileContents(privateKeyPath).contents\n            signingIdentity = try SwiftSigningIdentity(\n                derEncodedCertificate: certificate,\n                derEncodedPrivateKey: privateKey,\n                privateKeyType: signatureFormat.signingKeyType\n            )\n            intermediateCertificates = try intermediateCertPaths.map { try fileSystem.readFileContents($0).contents }\n        }\n        return (signingIdentity, intermediateCertificates)\n    }\n\n    private static func findManifests(packageDirectory: AbsolutePath) throws -> [String] {\n        let packageContents = try localFileSystem.getDirectoryContents(packageDirectory)\n\n        var manifests: [String] = []\n\n        let manifestPath = packageDirectory.appending(Manifest.filename)\n        guard localFileSystem.exists(manifestPath) else {\n            throw StringError(\"No \\(Manifest.filename) found at \\(packageDirectory).\")\n        }\n        manifests.append(Manifest.filename)\n\n        let regex = try RegEx(pattern: #\"^Package@swift-(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?.swift$\"#)\n        let versionSpecificManifests: [String] = packageContents.filter { file in\n            let matchGroups = regex.matchGroups(in: file)\n            return !matchGroups.isEmpty\n        }\n        manifests.append(contentsOf: versionSpecificManifests)\n\n        return manifests\n    }\n\n    enum SigningMode {\n        case identityStore(label: String, intermediateCertificates: [AbsolutePath])\n        case certificate(certificate: AbsolutePath, intermediateCertificates: [AbsolutePath], privateKey: AbsolutePath)\n    }\n\n    struct ArchiveAndSignResult {\n        let archive: SignedItem\n        let signedManifests: [String]\n        let metadata: SignedItem?\n    }\n\n    struct SignedItem {\n        let path: AbsolutePath\n        let signature: [UInt8]\n    }\n}\n\nenum PackageArchiver {\n    static func archive(\n        packageIdentity: PackageIdentity,\n        packageVersion: Version,\n        packageDirectory: AbsolutePath,\n        workingDirectory: AbsolutePath,\n        workingFilesToCopy: [String],\n        cancellator: Cancellator?,\n        observabilityScope: ObservabilityScope\n    ) async throws -> AbsolutePath {\n        let archivePath = workingDirectory.appending(\"\\(packageIdentity)-\\(packageVersion).zip\")\n\n        // create temp location for sources\n        let sourceDirectory = workingDirectory.appending(components: \"source\", \"\\(packageIdentity)\")\n        try localFileSystem.createDirectory(sourceDirectory, recursive: true)\n\n        // TODO: filter other unnecessary files, and/or .swiftpmignore file\n        let ignoredContent = [\".build\", \".git\", \".gitignore\", \".swiftpm\"]\n        let packageContent = try localFileSystem.getDirectoryContents(packageDirectory)\n        for item in (packageContent.filter { !ignoredContent.contains($0) }) {\n            try localFileSystem.copy(\n                from: packageDirectory.appending(component: item),\n                to: sourceDirectory.appending(component: item)\n            )\n        }\n\n        for item in workingFilesToCopy {\n            let replacementPath = workingDirectory.appending(item)\n            let replacement = try localFileSystem.readFileContents(replacementPath)\n\n            let toBeReplacedPath = sourceDirectory.appending(item)\n\n            observabilityScope.emit(info: \"replacing '\\(toBeReplacedPath)' with '\\(replacementPath)'\")\n            try localFileSystem.writeFileContents(toBeReplacedPath, bytes: replacement)\n        }\n\n        try await SwiftPackageCommand.archiveSource(\n            at: sourceDirectory,\n            to: archivePath,\n            fileSystem: localFileSystem,\n            cancellator: cancellator\n        )\n\n        return archivePath\n    }\n}\n"
  },
  {
    "path": "Sources/PackageRegistryCommand/PackageRegistryCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport Commands\nimport CoreCommands\nimport Foundation\nimport PackageModel\nimport PackageRegistry\nimport Workspace\n\npublic struct PackageRegistryCommand: AsyncParsableCommand {\n    public static var configuration = CommandConfiguration(\n        commandName: \"package-registry\",\n        _superCommandName: \"swift\",\n        abstract: \"Interact with package registry and manage related configuration.\",\n        discussion: \"SEE ALSO: swift package\",\n        version: SwiftVersion.current.completeDisplayString,\n        subcommands: [\n            Set.self,\n            Unset.self,\n            Login.self,\n            Logout.self,\n            Publish.self,\n        ],\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    @OptionGroup()\n    var globalOptions: GlobalOptions\n\n    public init() {}\n\n    struct Set: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Set a custom registry.\"\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Flag(help: \"Apply settings to all projects for this user.\")\n        var global: Bool = false\n\n        @Option(help: \"Associate the registry with a given scope.\")\n        var scope: String?\n\n        @Flag(name: .customLong(\"allow-insecure-http\"), help: \"Use a non-HTTPS registry URL.\")\n        var allowInsecureHTTP: Bool = false\n\n        @Argument(help: \"The registry URL.\")\n        var url: URL\n\n        var registryURL: URL {\n            self.url\n        }\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            try self.registryURL.validateRegistryURL(allowHTTP: self.allowInsecureHTTP)\n\n            let scope = try scope.map(PackageIdentity.Scope.init(validating:))\n\n            let set: (inout RegistryConfiguration) throws -> Void = { configuration in\n                let registry = Registry(url: self.registryURL, supportsAvailability: false)\n                if let scope {\n                    configuration.scopedRegistries[scope] = registry\n                } else {\n                    configuration.defaultRegistry = registry\n                }\n            }\n\n            let configuration = try getRegistriesConfig(swiftCommandState, global: self.global)\n            if self.global {\n                try configuration.updateShared(with: set)\n            } else {\n                try configuration.updateLocal(with: set)\n            }\n        }\n    }\n\n    struct Unset: AsyncSwiftCommand {\n        static let configuration = CommandConfiguration(\n            abstract: \"Remove a configured registry.\"\n        )\n\n        @OptionGroup(visibility: .hidden)\n        var globalOptions: GlobalOptions\n\n        @Flag(help: \"Apply settings to all projects for this user.\")\n        var global: Bool = false\n\n        @Option(help: \"Associate the registry with a given scope.\")\n        var scope: String?\n\n        func run(_ swiftCommandState: SwiftCommandState) async throws {\n            let scope = try scope.map(PackageIdentity.Scope.init(validating:))\n\n            let unset: (inout RegistryConfiguration) throws -> Void = { configuration in\n                if let scope {\n                    guard let _ = configuration.scopedRegistries[scope] else {\n                        throw ConfigurationError.missingScope(scope)\n                    }\n                    configuration.scopedRegistries.removeValue(forKey: scope)\n                } else {\n                    guard let _ = configuration.defaultRegistry else {\n                        throw ConfigurationError.missingScope()\n                    }\n                    configuration.defaultRegistry = nil\n                }\n            }\n\n            let configuration = try getRegistriesConfig(swiftCommandState, global: self.global)\n            if self.global {\n                try configuration.updateShared(with: unset)\n            } else {\n                try configuration.updateLocal(with: unset)\n            }\n        }\n    }\n\n    // common utility\n\n    enum ConfigurationError: Swift.Error {\n        case missingScope(PackageIdentity.Scope? = nil)\n    }\n\n    enum ValidationError: Swift.Error {\n        case invalidURL(URL)\n        case invalidPackageIdentity(PackageIdentity)\n        case unknownRegistry\n        case unknownCredentialStore\n        case invalidCredentialStore(Error)\n        case credentialLengthLimitExceeded(Int)\n    }\n\n    static func getRegistriesConfig(_ swiftCommandState: SwiftCommandState, global: Bool) throws -> Workspace.Configuration.Registries {\n        if global {\n            let sharedRegistriesFile = Workspace.DefaultLocations.registriesConfigurationFile(\n                at: swiftCommandState.sharedConfigurationDirectory\n            )\n            // Workspace not needed when working with user-level registries config\n            return try .init(\n                fileSystem: swiftCommandState.fileSystem,\n                localRegistriesFile: .none,\n                sharedRegistriesFile: sharedRegistriesFile\n            )\n        } else {\n            let workspace = try swiftCommandState.getActiveWorkspace()\n            return try .init(\n                fileSystem: swiftCommandState.fileSystem,\n                localRegistriesFile: workspace.location.localRegistriesConfigurationFile,\n                sharedRegistriesFile: workspace.location.sharedRegistriesConfigurationFile\n            )\n        }\n    }\n}\n\nextension URL {\n    func validateRegistryURL(allowHTTP: Bool = false) throws {\n        guard self.scheme == \"https\" || (self.scheme == \"http\" && allowHTTP) else {\n            throw PackageRegistryCommand.ValidationError.invalidURL(self)\n        }\n    }\n}\n\nextension PackageRegistryCommand.ConfigurationError: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .missingScope(let scope?):\n            return \"No existing entry for scope: \\(scope)\"\n        case .missingScope:\n            return \"No existing entry for default scope\"\n        }\n    }\n}\n\nextension PackageRegistryCommand.ValidationError: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .invalidURL(let url):\n            return \"invalid URL: \\(url)\"\n        case .invalidPackageIdentity(let identity):\n            return \"invalid package identifier '\\(identity)'\"\n        case .unknownRegistry:\n            return \"unknown registry, is one configured?\"\n        case .unknownCredentialStore:\n            return \"no credential store available\"\n        case .invalidCredentialStore(let error):\n            return \"credential store is invalid: \\(error.interpolationDescription)\"\n        case .credentialLengthLimitExceeded(let limit):\n            return \"password or access token must be \\(limit) characters or less\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageSigning/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageSigning STATIC\n  embedded_resources.swift\n  CertificateStores.swift\n  SigningEntity/FilePackageSigningEntityStorage.swift\n  SigningEntity/PackageSigningEntityStorage.swift\n  SigningEntity/SigningEntity.swift\n  SignatureProvider.swift\n  SigningIdentity.swift\n  VerifierPolicies.swift\n  X509Extensions.swift)\ntarget_link_libraries(PackageSigning PUBLIC\n  $<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>\n  Basics\n  Crypto\n  PackageModel\n  TSCBasic\n  TSCUtility\n  X509)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(PackageSigning PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS PackageSigning)\n"
  },
  {
    "path": "Sources/PackageSigning/CertificateStores.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import X509\n@_implementationOnly import SwiftASN1\n#else\nimport X509\nimport SwiftASN1\n#endif\n\nenum Certificates {\n    static let appleRootsRaw = [\n        PackageResources.AppleComputerRootCertificate_cer,\n        PackageResources.AppleIncRootCertificate_cer,\n        PackageResources.AppleRootCA_G2_cer,\n        PackageResources.AppleRootCA_G3_cer,\n    ]\n\n    static let appleRoots = Self.appleRootsRaw.compactMap {\n        try? Certificate(derEncoded: $0)\n    }\n\n    static let wwdrIntermediatesRaw = [\n        PackageResources.AppleWWDRCAG2_cer,\n        PackageResources.AppleWWDRCAG3_cer,\n        PackageResources.AppleWWDRCAG4_cer,\n        PackageResources.AppleWWDRCAG5_cer,\n        PackageResources.AppleWWDRCAG6_cer,\n        PackageResources.AppleWWDRCAG7_cer,\n        PackageResources.AppleWWDRCAG8_cer,\n    ]\n\n    static let wwdrIntermediates = Self.wwdrIntermediatesRaw.compactMap {\n        try? Certificate(derEncoded: $0)\n    }\n}\n\nenum CertificateStores {\n    static let defaultTrustRoots = Certificates.appleRoots\n}\n"
  },
  {
    "path": "Sources/PackageSigning/SignatureProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.Data\nimport struct Foundation.Date\n\n#if USE_IMPL_ONLY_IMPORTS\n#if canImport(Security)\n@_implementationOnly import Security\n#endif\n\n@_implementationOnly import SwiftASN1\n@_implementationOnly @_spi(CMS) import X509\n#else\n#if canImport(Security)\nimport Security\n#endif\n\nimport SwiftASN1\n@_spi(CMS) import X509\n#endif\n\nimport Basics\n\n// MARK: - Public signature API\n\npublic enum SignatureProvider {\n    public static func sign(\n        content: [UInt8],\n        identity: SigningIdentity,\n        intermediateCertificates: [[UInt8]],\n        format: SignatureFormat,\n        observabilityScope: ObservabilityScope\n    ) throws -> [UInt8] {\n        let provider = format.provider\n        return try provider.sign(\n            content: content,\n            identity: identity,\n            intermediateCertificates: intermediateCertificates,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    public static func status(\n        signature: [UInt8],\n        content: [UInt8],\n        format: SignatureFormat,\n        verifierConfiguration: VerifierConfiguration,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SignatureStatus {\n        let provider = format.provider\n        return try await provider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    public static func extractSigningEntity(\n        signature: [UInt8],\n        format: SignatureFormat,\n        verifierConfiguration: VerifierConfiguration\n    ) async throws -> SigningEntity {\n        let provider = format.provider\n        return try await provider.extractSigningEntity(\n            signature: signature,\n            format: format,\n            verifierConfiguration: verifierConfiguration\n        )\n    }\n}\n\npublic struct VerifierConfiguration {\n    public var trustedRoots: [[UInt8]]\n    public var includeDefaultTrustStore: Bool\n    public var certificateExpiration: CertificateExpiration\n    public var certificateRevocation: CertificateRevocation\n\n    // for testing\n    init(\n        trustedRoots: [[UInt8]],\n        includeDefaultTrustStore: Bool,\n        certificateExpiration: CertificateExpiration,\n        certificateRevocation: CertificateRevocation\n    ) {\n        self.trustedRoots = trustedRoots\n        self.includeDefaultTrustStore = includeDefaultTrustStore\n        self.certificateExpiration = certificateExpiration\n        self.certificateRevocation = certificateRevocation\n    }\n\n    public init() {\n        self.trustedRoots = []\n        self.includeDefaultTrustStore = true\n        self.certificateExpiration = .disabled\n        self.certificateRevocation = .disabled\n    }\n\n    public enum CertificateExpiration {\n        case enabled(validationTime: Date?)\n        case disabled\n    }\n\n    public enum CertificateRevocation {\n        case strict(validationTime: Date?)\n        case allowSoftFail(validationTime: Date?)\n        case disabled\n    }\n}\n\npublic enum SignatureStatus: Equatable {\n    case valid(SigningEntity)\n    case invalid(String)\n    case certificateInvalid(String)\n    case certificateNotTrusted(SigningEntity)\n}\n\npublic enum SigningError: Error {\n    case signingFailed(String)\n    case keyDoesNotSupportSignatureAlgorithm\n    case signingIdentityNotSupported\n    case unableToValidateSignature(String)\n    case invalidSignature(String)\n    case certificateInvalid(String)\n    case certificateNotTrusted(SigningEntity)\n}\n\n// MARK: - Signature formats and providers\n\npublic enum SignatureFormat: String {\n    case cms_1_0_0 = \"cms-1.0.0\"\n\n    public var signingKeyType: SigningKeyType {\n        switch self {\n        case .cms_1_0_0:\n            return .p256\n        }\n    }\n\n    var provider: SignatureProviderProtocol {\n        switch self {\n        case .cms_1_0_0:\n            return CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n        }\n    }\n}\n\npublic enum SigningKeyType {\n    case p256\n    // RSA support is internal/testing only, thus not included\n}\n\nenum SignatureAlgorithm {\n    case ecdsaP256\n    case rsa\n\n    var certificateSignatureAlgorithm: Certificate.SignatureAlgorithm {\n        switch self {\n        case .ecdsaP256:\n            return .ecdsaWithSHA256\n        case .rsa:\n            return .sha256WithRSAEncryption\n        }\n    }\n}\n\nprotocol SignatureProviderProtocol {\n    func sign(\n        content: [UInt8],\n        identity: SigningIdentity,\n        intermediateCertificates: [[UInt8]],\n        observabilityScope: ObservabilityScope\n    ) throws -> [UInt8]\n\n    func status(\n        signature: [UInt8],\n        content: [UInt8],\n        verifierConfiguration: VerifierConfiguration,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SignatureStatus\n\n    func extractSigningEntity(\n        signature: [UInt8],\n        format: SignatureFormat,\n        verifierConfiguration: VerifierConfiguration\n    ) async throws -> SigningEntity\n}\n\n// MARK: - CMS signature provider\n\nstruct CMSSignatureProvider: SignatureProviderProtocol {\n    let signatureAlgorithm: SignatureAlgorithm\n    let httpClient: HTTPClient\n\n    init(\n        signatureAlgorithm: SignatureAlgorithm,\n        customHTTPClient: HTTPClient? = .none\n    ) {\n        self.signatureAlgorithm = signatureAlgorithm\n        self.httpClient = customHTTPClient ?? HTTPClient()\n    }\n\n    func sign(\n        content: [UInt8],\n        identity: SigningIdentity,\n        intermediateCertificates: [[UInt8]],\n        observabilityScope: ObservabilityScope\n    ) throws -> [UInt8] {\n        #if canImport(Security)\n        if CFGetTypeID(identity as CFTypeRef) == SecIdentityGetTypeID() {\n            let secIdentity = identity as! SecIdentity // !-safe because we ensure type above\n\n            var privateKey: SecKey?\n            let keyStatus = SecIdentityCopyPrivateKey(secIdentity, &privateKey)\n            guard keyStatus == errSecSuccess, let privateKey else {\n                throw SigningError.signingFailed(\"unable to get private key from SecIdentity: status \\(keyStatus)\")\n            }\n\n            let signature = try privateKey.sign(content: content, algorithm: self.signatureAlgorithm)\n\n            do {\n                let intermediateCertificates = try intermediateCertificates.map { try Certificate($0) }\n\n                return try CMS.sign(\n                    signatureBytes: ASN1OctetString(contentBytes: ArraySlice(signature)),\n                    signatureAlgorithm: self.signatureAlgorithm.certificateSignatureAlgorithm,\n                    additionalIntermediateCertificates: intermediateCertificates,\n                    certificate: try Certificate(secIdentity: secIdentity)\n                )\n            } catch {\n                throw SigningError.signingFailed(\"\\(error.interpolationDescription)\")\n            }\n        }\n        #endif\n\n        guard let swiftSigningIdentity = identity as? SwiftSigningIdentity else {\n            throw SigningError.signingIdentityNotSupported\n        }\n\n        do {\n            let intermediateCertificates = try intermediateCertificates.map { try Certificate($0) }\n\n            return try CMS.sign(\n                content,\n                signatureAlgorithm: self.signatureAlgorithm.certificateSignatureAlgorithm,\n                additionalIntermediateCertificates: intermediateCertificates,\n                certificate: swiftSigningIdentity.certificate,\n                privateKey: swiftSigningIdentity.privateKey\n            )\n        } catch let error as CertificateError where error.code == .unsupportedSignatureAlgorithm {\n            throw SigningError.keyDoesNotSupportSignatureAlgorithm\n        } catch {\n            throw SigningError.signingFailed(\"\\(error.interpolationDescription)\")\n        }\n    }\n\n    func status(\n        signature: [UInt8],\n        content: [UInt8],\n        verifierConfiguration: VerifierConfiguration,\n        observabilityScope: ObservabilityScope\n    ) async throws -> SignatureStatus {\n        do {\n            var trustRoots: [Certificate] = []\n            if verifierConfiguration.includeDefaultTrustStore {\n                trustRoots.append(contentsOf: CertificateStores.defaultTrustRoots)\n            }\n            trustRoots.append(contentsOf: try verifierConfiguration.trustedRoots.map { try Certificate($0) })\n\n            let result = await CMS.isValidSignature(\n                dataBytes: content,\n                signatureBytes: signature,\n                // The intermediates supplied here will be combined with those\n                // included in the signature to build cert chain for validation.\n                //\n                // Those who use ADP certs for signing are not required to provide\n                // the entire cert chain, thus we must supply WWDR intermediates\n                // here so that the chain can be constructed during validation.\n                // Whether the signing cert is trusted still depends on whether\n                // the WWDR roots are in the trust store or not, which by default\n                // they are but user may disable that through configuration.\n                additionalIntermediateCertificates: Certificates.wwdrIntermediates,\n                trustRoots: CertificateStore(trustRoots)\n            ) {\n                self.buildPolicySet(configuration: verifierConfiguration, httpClient: self.httpClient)\n            }\n            \n\n            switch result {\n            case .success(let valid):\n                let signingEntity = SigningEntity.from(certificate: valid.signer)\n                return .valid(signingEntity)\n            case .failure(CMS.VerificationError.unableToValidateSigner(let failure)):\n                if failure.validationFailures.isEmpty {\n                    let signingEntity = SigningEntity.from(certificate: failure.signer)\n                    return .certificateNotTrusted(signingEntity)\n                } else {\n                    observabilityScope\n                        .emit(\n                            info: \"cannot validate certificate chain. Validation failures: \\(failure.validationFailures)\"\n                        )\n                    return .certificateInvalid(\"failures: \\(failure.validationFailures.map(\\.policyFailureReason))\")\n                }\n            case .failure(CMS.VerificationError.invalidCMSBlock(let error)):\n                return .invalid(error.reason)\n            case .failure(let error):\n                return .invalid(\"\\(error.interpolationDescription)\")\n            }\n        } catch {\n            throw SigningError.unableToValidateSignature(\"\\(error.interpolationDescription)\")\n        }\n    }\n\n    func extractSigningEntity(\n        signature: [UInt8],\n        format: SignatureFormat,\n        verifierConfiguration: VerifierConfiguration\n    ) async throws -> SigningEntity {\n        switch format {\n        case .cms_1_0_0:\n            do {\n                let cmsSignature = try CMSSignature(derEncoded: signature)\n                let signers = try cmsSignature.signers\n                guard signers.count == 1, let signer = signers.first else {\n                    throw SigningError.invalidSignature(\"expected 1 signer but got \\(signers.count)\")\n                }\n\n                let signingCertificate = signer.certificate\n\n                var trustRoots: [Certificate] = []\n                if verifierConfiguration.includeDefaultTrustStore {\n                    trustRoots.append(contentsOf: CertificateStores.defaultTrustRoots)\n                }\n                trustRoots.append(contentsOf: try verifierConfiguration.trustedRoots.map { try Certificate($0) })\n\n                // Verifier uses these to build cert chain for validation\n                // (see also notes in `status` method)\n                var untrustedIntermediates: [Certificate] = []\n                // WWDR intermediates are not required when signing with ADP certs,\n                // (i.e., these intermediates may not be in the signature), hence\n                // we include them here to ensure Verifier can build cert chain.\n                untrustedIntermediates.append(contentsOf: Certificates.wwdrIntermediates)\n                // For self-signed certificate, the signature should include intermediate(s).\n                untrustedIntermediates.append(contentsOf: cmsSignature.certificates)\n\n                var verifier = Verifier(rootCertificates: CertificateStore(trustRoots)) {\n                    self.buildPolicySet(configuration: verifierConfiguration, httpClient: self.httpClient)\n                }\n                let result = await verifier.validate(\n                    leafCertificate: signingCertificate,\n                    intermediates: CertificateStore(untrustedIntermediates)\n                )\n\n                switch result {\n                case .validCertificate:\n                    return SigningEntity.from(certificate: signingCertificate)\n                case .couldNotValidate(let validationFailures):\n                    if validationFailures.isEmpty {\n                        let signingEntity = SigningEntity.from(certificate: signingCertificate)\n                        throw SigningError.certificateNotTrusted(signingEntity)\n                    } else {\n                        throw SigningError\n                            .certificateInvalid(\"failures: \\(validationFailures.map(\\.policyFailureReason))\")\n                    }\n                }\n            } catch let error as SigningError {\n                throw error\n            } catch {\n                throw SigningError.invalidSignature(\"\\(error.interpolationDescription)\")\n            }\n        }\n    }\n}\n\n#if canImport(Security)\nextension SecKey {\n    func sign(content: [UInt8], algorithm: SignatureAlgorithm) throws -> [UInt8] {\n        let secKeyAlgorithm: SecKeyAlgorithm\n        switch algorithm {\n        case .ecdsaP256:\n            secKeyAlgorithm = .ecdsaSignatureMessageX962SHA256\n        case .rsa:\n            secKeyAlgorithm = .rsaSignatureMessagePKCS1v15SHA256\n        }\n\n        guard SecKeyIsAlgorithmSupported(self, .sign, secKeyAlgorithm) else {\n            throw SigningError.keyDoesNotSupportSignatureAlgorithm\n        }\n\n        var error: Unmanaged<CFError>?\n        guard let signatureData = SecKeyCreateSignature(\n            self,\n            secKeyAlgorithm,\n            Data(content) as CFData,\n            &error\n        ) as Data? else {\n            if let error = error?.takeRetainedValue() as Error? {\n                throw SigningError.signingFailed(\"\\(error.interpolationDescription)\")\n            }\n            throw SigningError.signingFailed(\"Failed to sign with SecKey\")\n        }\n        return Array(signatureData)\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/PackageSigning/SigningEntity/FilePackageSigningEntityStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport Foundation\nimport PackageModel\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\npublic struct FilePackageSigningEntityStorage: PackageSigningEntityStorage {\n    let fileSystem: FileSystem\n    let directoryPath: Basics.AbsolutePath\n\n    private let encoder: JSONEncoder\n    private let decoder: JSONDecoder\n\n    public init(fileSystem: FileSystem, directoryPath: Basics.AbsolutePath) {\n        self.fileSystem = fileSystem\n        self.directoryPath = directoryPath\n\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n    }\n\n    public func get(\n        package: PackageIdentity,\n        observabilityScope: ObservabilityScope\n    ) throws -> PackageSigners {\n        try self.withLock {\n            try self.loadFromDisk(package: package)\n        }\n    }\n\n    public func put(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.withLock {\n            var packageSigners = try self.loadFromDisk(package: package)\n\n            let otherSigningEntities = packageSigners.signingEntities(of: version).filter { $0 != signingEntity }\n            // Error if we try to write a different signing entity for a version\n            guard otherSigningEntities.isEmpty else {\n                throw PackageSigningEntityStorageError.conflict(\n                    package: package,\n                    version: version,\n                    given: signingEntity,\n                    existing: otherSigningEntities.first! // !-safe because otherSigningEntities is not empty\n                )\n            }\n\n            try self.add(\n                packageSigners: &packageSigners,\n                signingEntity: signingEntity,\n                origin: origin,\n                version: version\n            )\n            try self.saveToDisk(package: package, packageSigners: packageSigners)\n        }\n    }\n\n    public func add(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.withLock {\n            var packageSigners = try self.loadFromDisk(package: package)\n            try self.add(\n                packageSigners: &packageSigners,\n                signingEntity: signingEntity,\n                origin: origin,\n                version: version\n            )\n            try self.saveToDisk(package: package, packageSigners: packageSigners)\n        }\n    }\n\n    public func changeSigningEntityFromVersion(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.withLock {\n            var packageSigners = try self.loadFromDisk(package: package)\n            packageSigners.expectedSigner = (signingEntity: signingEntity, fromVersion: version)\n            try self.add(\n                packageSigners: &packageSigners,\n                signingEntity: signingEntity,\n                origin: origin,\n                version: version\n            )\n            try self.saveToDisk(package: package, packageSigners: packageSigners)\n        }\n    }\n\n    public func changeSigningEntityForAllVersions(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.withLock {\n            var packageSigners = try self.loadFromDisk(package: package)\n            packageSigners.expectedSigner = (signingEntity: signingEntity, fromVersion: version)\n            // Delete all other signers\n            packageSigners.signers = packageSigners.signers.filter { $0.key == signingEntity }\n            try self.add(\n                packageSigners: &packageSigners,\n                signingEntity: signingEntity,\n                origin: origin,\n                version: version\n            )\n            try self.saveToDisk(package: package, packageSigners: packageSigners)\n        }\n    }\n\n    private func add(\n        packageSigners: inout PackageSigners,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        version: Version\n    ) throws {\n        guard case .recognized = signingEntity else {\n            throw PackageSigningEntityStorageError.unrecognizedSigningEntity(signingEntity)\n        }\n\n        if var existingSigner = packageSigners.signers.removeValue(forKey: signingEntity) {\n            existingSigner.origins.insert(origin)\n            existingSigner.versions.insert(version)\n            packageSigners.signers[signingEntity] = existingSigner\n        } else {\n            let signer = PackageSigner(\n                signingEntity: signingEntity,\n                origins: [origin],\n                versions: [version]\n            )\n            packageSigners.signers[signingEntity] = signer\n        }\n    }\n\n    private func loadFromDisk(package: PackageIdentity) throws -> PackageSigners {\n        let path = self.directoryPath.appending(component: package.signedVersionsFilename)\n\n        guard self.fileSystem.exists(path) else {\n            return .init()\n        }\n\n        let data: Data = try fileSystem.readFileContents(path)\n        guard data.count > 0 else {\n            return .init()\n        }\n\n        let container = try self.decoder.decode(StorageModel.Container.self, from: data)\n        return try container.packageSigners()\n    }\n\n    private func saveToDisk(package: PackageIdentity, packageSigners: PackageSigners) throws {\n        if !self.fileSystem.exists(self.directoryPath) {\n            try self.fileSystem.createDirectory(self.directoryPath, recursive: true)\n        }\n\n        let container = try StorageModel.Container(packageSigners)\n        let buffer = try encoder.encode(container)\n\n        let path = self.directoryPath.appending(component: package.signedVersionsFilename)\n        try self.fileSystem.writeFileContents(path, data: buffer)\n    }\n\n    private func withLock<T>(_ body: () throws -> T) throws -> T {\n        if !self.fileSystem.exists(self.directoryPath) {\n            try self.fileSystem.createDirectory(self.directoryPath, recursive: true)\n        }\n        return try self.fileSystem.withLock(on: self.directoryPath, type: .exclusive, body)\n    }\n\n    private func makeAsync<T>(\n        _ closure: @escaping (Result<T, Error>) -> Void,\n        on queue: DispatchQueue\n    ) -> (Result<T, Error>) -> Void {\n        { result in queue.async { closure(result) } }\n    }\n}\n\nprivate enum StorageModel {\n    struct Container: Codable {\n        let expectedSigner: ExpectedSigner?\n        let signers: [PackageSigner]\n\n        init(_ packageSigners: PackageSigners) throws {\n            self.expectedSigner = packageSigners.expectedSigner.map {\n                ExpectedSigner(signingEntity: $0.signingEntity, fromVersion: $0.fromVersion)\n            }\n            self.signers = Array(packageSigners.signers.values)\n        }\n\n        func packageSigners() throws -> PackageSigners {\n            let signers = try Dictionary(throwingUniqueKeysWithValues: self.signers.map {\n                ($0.signingEntity, $0)\n            })\n            return PackageSigners(\n                expectedSigner: self.expectedSigner.map { ($0.signingEntity, $0.fromVersion) },\n                signers: signers\n            )\n        }\n    }\n\n    struct ExpectedSigner: Codable {\n        let signingEntity: SigningEntity\n        let fromVersion: Version\n    }\n}\n\nextension PackageIdentity {\n    var signedVersionsFilename: String {\n        \"\\(self.description).json\"\n    }\n}\n"
  },
  {
    "path": "Sources/PackageSigning/SigningEntity/PackageSigningEntityStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.URL\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport PackageModel\n\nimport struct TSCUtility.Version\n\npublic protocol PackageSigningEntityStorage {\n    /// For a given package, return the signing entities and the package versions that each of them signed.\n    func get(\n        package: PackageIdentity,\n        observabilityScope: ObservabilityScope\n    ) throws -> PackageSigners\n\n    /// Record signer for a given package version.\n    ///\n    /// This throws `PackageSigningEntityStorageError.conflict` if `signingEntity`\n    /// of the package version is different from that in storage.\n    func put(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws\n\n    /// Add signer for a given package version.\n    ///\n    /// If the package version already has other `SigningEntity`s in storage, this\n    /// API **adds** `signingEntity` to the package version's signers rather than\n    /// throwing an error.\n    func add(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws\n\n    /// Make `signingEntity` the package's expected signer starting from the given version.\n    func changeSigningEntityFromVersion(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws\n\n    /// Make `signingEntity` the only signer for a given package.\n    ///\n    /// This API deletes all other existing signers from storage, therefore making\n    /// `signingEntity` the package's sole signer.\n    func changeSigningEntityForAllVersions(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws\n}\n\n// MARK: - Models\n\nextension SigningEntity {\n    public enum Origin: Hashable, Codable, CustomStringConvertible {\n        case registry(URL)\n\n        public var url: URL {\n            switch self {\n            case .registry(let url):\n                return url\n            }\n        }\n\n        public var description: String {\n            switch self {\n            case .registry(let url):\n                return \"registry(\\(url))\"\n            }\n        }\n    }\n}\n\npublic struct PackageSigner: Codable {\n    public let signingEntity: SigningEntity\n    public internal(set) var origins: Set<SigningEntity.Origin>\n    public internal(set) var versions: Set<Version>\n\n    public init(\n        signingEntity: SigningEntity,\n        origins: Set<SigningEntity.Origin>,\n        versions: Set<Version>\n    ) {\n        self.signingEntity = signingEntity\n        self.origins = origins\n        self.versions = versions\n    }\n}\n\npublic struct PackageSigners {\n    public internal(set) var expectedSigner: (signingEntity: SigningEntity, fromVersion: Version)?\n    public internal(set) var signers: [SigningEntity: PackageSigner]\n\n    public init(\n        expectedSigner: (signingEntity: SigningEntity, fromVersion: Version)? = .none,\n        signers: [SigningEntity: PackageSigner] = [:]\n    ) {\n        self.expectedSigner = expectedSigner\n        self.signers = signers\n    }\n\n    public var isEmpty: Bool {\n        self.signers.isEmpty\n    }\n\n    public var versionSigningEntities: [Version: Set<SigningEntity>] {\n        var versionSigningEntities = [Version: Set<SigningEntity>]()\n        for (signingEntity, versions) in self.signers.map({ ($0.key, $0.value.versions) }) {\n            versions.forEach { version in\n                var signingEntities: Set<SigningEntity> = versionSigningEntities.removeValue(forKey: version) ?? []\n                signingEntities.insert(signingEntity)\n                versionSigningEntities[version] = signingEntities\n            }\n        }\n        return versionSigningEntities\n    }\n\n    public func signingEntities(of version: Version) -> Set<SigningEntity> {\n        Set(self.signers.values.filter { $0.versions.contains(version) }.map(\\.signingEntity))\n    }\n}\n\n// MARK: - Errors\n\npublic enum PackageSigningEntityStorageError: Error, Equatable, CustomStringConvertible {\n    case conflict(package: PackageIdentity, version: Version, given: SigningEntity, existing: SigningEntity)\n    case unrecognizedSigningEntity(SigningEntity)\n\n    public var description: String {\n        switch self {\n        case .conflict(let package, let version, let given, let existing):\n            return \"\\(package) version \\(version) was previously signed by '\\(existing)', which is different from '\\(given)'.\"\n        case .unrecognizedSigningEntity(let signingEntity):\n            return \"'\\(signingEntity)' is not recognized and therefore will not be saved.\"\n        }\n    }\n}\n\npublic enum SigningEntityCheckingMode: String {\n    case strict\n    case warn\n}\n"
  },
  {
    "path": "Sources/PackageSigning/SigningEntity/SigningEntity.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftASN1\n@_implementationOnly import X509\n#else\nimport SwiftASN1\nimport X509\n#endif\n\n// MARK: - SigningEntity is the entity that generated the signature\n\npublic enum SigningEntity: Hashable, Codable, CustomStringConvertible, Sendable {\n    case recognized(type: SigningEntityType, name: String, organizationalUnit: String, organization: String)\n    case unrecognized(name: String?, organizationalUnit: String?, organization: String?)\n\n    static func from(certificate: Certificate) -> SigningEntity {\n        let name = certificate.subject.commonName\n        let organizationalUnit = certificate.subject.organizationalUnitName\n        let organization = certificate.subject.organizationName\n\n        if let type = certificate.signingEntityType,\n           let name = name,\n           let organizationalUnit = organizationalUnit,\n           let organization = organization {\n            return .recognized(\n                type: type,\n                name: name,\n                organizationalUnit: organizationalUnit,\n                organization: organization\n            )\n        } else {\n            return .unrecognized(\n                name: name,\n                organizationalUnit: organizationalUnit,\n                organization: organization\n            )\n        }\n    }\n\n    public static func == (lhs: SigningEntity, rhs: SigningEntity) -> Bool {\n        switch (lhs, rhs) {\n        case (\n            .recognized(let lhsType, let lhsName, let lhsOrgUnit, let lhsOrg),\n            .recognized(let rhsType, let rhsName, let rhsOrgUnit, let rhsOrg)\n        ):\n            // For ADP type, only team ID (org unit) needs to match\n            if lhsType == .adp, rhsType == .adp {\n                return lhsOrgUnit == rhsOrgUnit\n            }\n            return lhsType == rhsType && lhsName == rhsName && lhsOrgUnit == rhsOrgUnit && lhsOrg == rhsOrg\n        case (\n            .unrecognized(let lhsName, let lhsOrgUnit, let lhsOrg),\n            .unrecognized(let rhsName, let rhsOrgUnit, let rhsOrg)\n        ):\n            return lhsName == rhsName && lhsOrgUnit == rhsOrgUnit && lhsOrg == rhsOrg\n        default:\n            return false\n        }\n    }\n\n    public var description: String {\n        switch self {\n        case .recognized(let type, let name, let organizationalUnit, let organization):\n            return \"SigningEntity[type=\\(type), name=\\(name), organizationalUnit=\\(organizationalUnit), organization=\\(organization)]\"\n        case .unrecognized(let name, let organizationalUnit, let organization):\n            return \"SigningEntity[name=\\(String(describing: name)), organizationalUnit=\\(String(describing: organizationalUnit)), organization=\\(String(describing: organization))]\"\n        }\n    }\n}\n\n// MARK: - SigningEntity types that SwiftPM recognizes\n\npublic enum SigningEntityType: String, Hashable, Codable, Sendable {\n    case adp // Apple Developer Program\n}\n\nextension ASN1ObjectIdentifier.NameAttributes {\n    static let adpSwiftPackageMarker: ASN1ObjectIdentifier = [1, 2, 840, 113_635, 100, 6, 1, 35]\n}\n\nextension Certificate {\n    var signingEntityType: SigningEntityType? {\n        if self.hasExtension(oid: ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageMarker),\n           Certificates.wwdrIntermediates\n           .first(where: { $0.subject == self.issuer && $0.publicKey.isValidSignature(self.signature, for: self) }) !=\n           nil\n        {\n            return .adp\n        }\n        return .none\n    }\n}\n"
  },
  {
    "path": "Sources/PackageSigning/SigningIdentity.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n#if canImport(Security)\n@_implementationOnly import Security\n#endif\n\n@_implementationOnly import Crypto\n@_implementationOnly import X509\n#else\n#if canImport(Security)\nimport Security\n#endif\n\nimport Crypto\nimport X509\n#endif\n\nimport Basics\nimport TSCBasic\n\npublic protocol SigningIdentity {}\n\n// MARK: - SecIdentity conformance to SigningIdentity\n\n#if canImport(Security)\nextension SecIdentity: SigningIdentity {}\n#endif\n\n// MARK: - SwiftSigningIdentity is created using raw private key and certificate bytes\n\npublic struct SwiftSigningIdentity: SigningIdentity {\n    let certificate: Certificate\n    let privateKey: Certificate.PrivateKey\n\n    // for testing\n    init(certificate: Certificate, privateKey: Certificate.PrivateKey) {\n        self.certificate = certificate\n        self.privateKey = privateKey\n    }\n\n    public init(\n        derEncodedCertificate certificate: [UInt8],\n        derEncodedPrivateKey privateKey: [UInt8],\n        privateKeyType: SigningKeyType\n    ) throws {\n        do {\n            self.certificate = try Certificate(certificate)\n        } catch {\n            throw StringError(\"Invalid certificate: \\(error.interpolationDescription)\")\n        }\n\n        do {\n            switch privateKeyType {\n            case .p256:\n                self.privateKey = try Certificate.PrivateKey(P256.Signing.PrivateKey(derRepresentation: privateKey))\n            }\n        } catch let error as StringError {\n            throw error\n        } catch {\n            throw StringError(\"Invalid key: \\(error.interpolationDescription)\")\n        }\n    }\n}\n\n// MARK: - SigningIdentity store\n\npublic struct SigningIdentityStore {\n    private let observabilityScope: ObservabilityScope\n\n    public init(observabilityScope: ObservabilityScope) {\n        self.observabilityScope = observabilityScope\n    }\n\n    public func find(by label: String) -> [SigningIdentity] {\n        #if os(macOS)\n        // Find in Keychain\n        let query: [String: Any] = [\n            // Use kSecClassCertificate instead of kSecClassIdentity because the latter\n            // seems to always return all results, whether matching given label or not.\n            kSecClass as String: kSecClassCertificate,\n            kSecReturnRef as String: true,\n            kSecAttrLabel as String: label,\n            // TODO: too restrictive to require kSecAttrCanSign == true?\n//            kSecAttrCanSign as String: true,\n            kSecMatchLimit as String: kSecMatchLimitAll,\n        ]\n\n        var result: CFTypeRef?\n        let status = SecItemCopyMatching(query as CFDictionary, &result)\n        guard status == errSecSuccess else {\n            self.observabilityScope.emit(warning: \"Failed to search for '\\(label)' in Keychain: status \\(status)\")\n            return []\n        }\n\n        let certificates = result as? [SecCertificate] ?? []\n        return certificates.compactMap { secCertificate in\n            var identity: SecIdentity?\n            let status = SecIdentityCreateWithCertificate(nil, secCertificate, &identity)\n            guard status == errSecSuccess, let identity else {\n                self.observabilityScope\n                    .emit(\n                        warning: \"Failed to create SecIdentity from SecCertificate[\\(secCertificate)]: status \\(status)\"\n                    )\n                return nil\n            }\n            return identity\n        }\n        #else\n        // No identity store support on other platforms\n        return []\n        #endif\n    }\n}\n"
  },
  {
    "path": "Sources/PackageSigning/VerifierPolicies.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Dispatch\nimport struct Foundation.Data\nimport struct Foundation.Date\nimport struct Foundation.URL\n\nimport Basics\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftASN1\n@_implementationOnly @_spi(DisableValidityCheck) import X509\n#else\nimport SwiftASN1\n@_spi(DisableValidityCheck) import X509\n#endif\n\nextension SignatureProviderProtocol {\n    @PolicyBuilder\n    func buildPolicySet(configuration: VerifierConfiguration, httpClient: HTTPClient) -> some VerifierPolicy {\n        _CodeSigningPolicy()\n        _ADPCertificatePolicy()\n\n        let now = Date()\n        switch (configuration.certificateExpiration, configuration.certificateRevocation) {\n        case (.enabled(let expiryValidationTime), .strict(let revocationValidationTime)):\n            RFC5280Policy(validationTime: expiryValidationTime ?? now)\n            _OCSPVerifierPolicy(\n                failureMode: .hard,\n                httpClient: httpClient,\n                validationTime: revocationValidationTime ?? now\n            )\n        case (.enabled(let expiryValidationTime), .allowSoftFail(let revocationValidationTime)):\n            RFC5280Policy(validationTime: expiryValidationTime ?? now)\n            _OCSPVerifierPolicy(\n                failureMode: .soft,\n                httpClient: httpClient,\n                validationTime: revocationValidationTime ?? now\n            )\n        case (.enabled(let expiryValidationTime), .disabled):\n            RFC5280Policy(validationTime: expiryValidationTime ?? now)\n        case (.disabled, .strict(let revocationValidationTime)):\n            // Always do expiry check (and before) if revocation check is enabled\n            RFC5280Policy(validationTime: revocationValidationTime ?? now)\n            _OCSPVerifierPolicy(\n                failureMode: .hard,\n                httpClient: httpClient,\n                validationTime: revocationValidationTime ?? now\n            )\n        case (.disabled, .allowSoftFail(let revocationValidationTime)):\n            // Always do expiry check (and before) if revocation check is enabled\n            RFC5280Policy(validationTime: revocationValidationTime ?? now)\n            _OCSPVerifierPolicy(\n                failureMode: .soft,\n                httpClient: httpClient,\n                validationTime: revocationValidationTime ?? now\n            )\n        case (.disabled, .disabled):\n            // We should still do basic certificate validations even if expiry check is disabled\n            RFC5280Policy.withValidityCheckDisabled()\n        }\n    }\n}\n\n/// Policy for code signing certificates.\nstruct _CodeSigningPolicy: VerifierPolicy {\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = [\n        ASN1ObjectIdentifier.X509ExtensionID.keyUsage,\n        ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage,\n    ]\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        let isCodeSigning = (\n            try? chain.leaf.extensions.extendedKeyUsage?.contains(ExtendedKeyUsage.Usage.codeSigning)\n        ) ??\n            false\n        guard isCodeSigning else {\n            return .failsToMeetPolicy(reason: \"Certificate \\(chain.leaf) does not have code signing extended key usage\")\n        }\n        return .meetsPolicy\n    }\n}\n\n/// Policy for ADP certificates.\nstruct _ADPCertificatePolicy: VerifierPolicy {\n    /// Include custom marker extensions (which can be critical) so they would not\n    /// be considered unhandled and cause certificate chain validation to fail.\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = Self.swiftPackageMarkers\n        + Self.developmentMarkers\n\n    // Marker extensions for Swift Package certificate\n    private static let swiftPackageMarkers: [ASN1ObjectIdentifier] = [\n        // This is not a critical extension but including it just in case\n        ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageMarker,\n    ]\n\n    // Marker extensions for Development certificate (included for testing)\n    private static let developmentMarkers: [ASN1ObjectIdentifier] = [\n        [1, 2, 840, 113_635, 100, 6, 1, 2],\n        [1, 2, 840, 113_635, 100, 6, 1, 12],\n    ]\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        // Not policing anything here. This policy is mainly for\n        // listing marker extensions to prevent chain validation\n        // from failing prematurely.\n        .meetsPolicy\n    }\n}\n\nstruct _OCSPVerifierPolicy: VerifierPolicy {\n    private static let cacheTTL: DispatchTimeInterval = .seconds(5 * 60)\n    private let cache = ThreadSafeKeyValueStore<\n        UnverifiedCertificateChain,\n        (result: PolicyEvaluationResult, expires: DispatchTime)\n    >()\n\n    private var underlying: OCSPVerifierPolicy<_OCSPRequester>\n\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []\n\n    /// Initializes an `_OCSPVerifierPolicy` that caches its results.\n    ///\n    /// - Parameters:\n    ///     - failureMode: `OCSPFailureMode` that defines policy failure in event of failure.\n    ///                 Possible values are `hard` (OCSP request failure and unknown status\n    ///                 not allowed) or `soft` (OCSP request failure and unknown status allowed).\n    ///     - httpClient: `HTTPClient` that backs`_OCSPRequester` for making OCSP requests.\n    ///     - validationTime: The time used to decide if the OCSP request is relatively recent. It is\n    ///                   considered a failure if the request is too old.\n    init(failureMode: OCSPFailureMode, httpClient: HTTPClient, validationTime: Date) {\n        self.underlying = OCSPVerifierPolicy(\n            failureMode: failureMode,\n            requester: _OCSPRequester(httpClient: httpClient),\n            validationTime: validationTime\n        )\n    }\n\n    mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        // Look for cached result\n        if let cached = self.cache[chain], cached.expires < .now() {\n            return cached.result\n        }\n\n        // This makes HTTP requests\n        let result = await self.underlying.chainMeetsPolicyRequirements(chain: chain)\n\n        // Save result to cache\n        self.cache[chain] = (result: result, expires: .now() + Self.cacheTTL)\n        return result\n    }\n}\n\nprivate struct _OCSPRequester: OCSPRequester {\n    let httpClient: HTTPClient\n\n    func query(request: [UInt8], uri: String) async -> OCSPRequesterQueryResult {\n        guard let url = URL(string: uri), let host = url.host else {\n            return .terminalError(SwiftOCSPRequesterError.invalidURL(uri))\n        }\n\n        do {\n            let response = try await self.httpClient.post(\n                url,\n                body: Data(request),\n                headers: [\n                    \"Content-Type\": \"application/ocsp-request\",\n                    \"Host\": host,\n                ]\n            )\n\n            guard response.statusCode == 200 else {\n                throw SwiftOCSPRequesterError.invalidResponse(statusCode: response.statusCode)\n            }\n            guard let responseBody = response.body else {\n                throw SwiftOCSPRequesterError.emptyResponse\n            }\n            return .response(Array(responseBody))\n        } catch {\n            return .nonTerminalError(error)\n        }\n    }\n}\n\nenum SwiftOCSPRequesterError: Error {\n    case invalidURL(String)\n    case emptyResponse\n    case invalidResponse(statusCode: Int)\n}\n"
  },
  {
    "path": "Sources/PackageSigning/X509Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Foundation.Data\n\n#if USE_IMPL_ONLY_IMPORTS\n#if canImport(Security)\n@_implementationOnly import Security\n#endif\n\n@_implementationOnly import SwiftASN1\n@_implementationOnly import X509\n#else\n#if canImport(Security)\nimport Security\n#endif\n\nimport SwiftASN1\nimport X509\n#endif\n\nimport Basics\nimport TSCBasic\n\n#if canImport(Security)\nextension Certificate {\n    init(secCertificate: SecCertificate) throws {\n        let data = SecCertificateCopyData(secCertificate) as Data\n        self = try Certificate(Array(data))\n    }\n\n    init(secIdentity: SecIdentity) throws {\n        var secCertificate: SecCertificate?\n        let status = SecIdentityCopyCertificate(secIdentity, &secCertificate)\n        guard status == errSecSuccess, let secCertificate else {\n            throw StringError(\"failed to get certificate from SecIdentity: status \\(status)\")\n        }\n        self = try Certificate(secCertificate: secCertificate)\n    }\n}\n#endif\n\nextension Certificate {\n    func hasExtension(oid: ASN1ObjectIdentifier) -> Bool {\n        self.extensions[oid: oid] != nil\n    }\n}\n\nextension DistinguishedName {\n    var commonName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.commonName)\n    }\n\n    var organizationalUnitName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.organizationalUnitName)\n    }\n\n    var organizationName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.organizationName)\n    }\n\n    private func stringAttribute(oid: ASN1ObjectIdentifier) -> String? {\n        for relativeDistinguishedName in self {\n            for attribute in relativeDistinguishedName where attribute.type == oid {\n                return attribute.value.description\n            }\n        }\n        return nil\n    }\n}\n\n// MARK: - Certificate cache\n\nextension Certificate {\n    private static let cache = ThreadSafeKeyValueStore<[UInt8], Certificate>()\n\n    init(_ bytes: [UInt8]) throws {\n        if let cached = Self.cache[bytes] {\n            self = cached\n        } else {\n            let certificate = try Certificate(derEncoded: bytes)\n            Self.cache[bytes] = certificate\n            self = certificate\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/PackageSigning/embedded_resources.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nstruct PackageResources {\nstatic let AppleWWDRCAG2_cer: [UInt8] = [48,130,2,247,48,130,2,124,160,3,2,1,2,2,8,111,239,216,245,233,163,167,238,48,10,6,8,42,134,72,206,61,4,3,2,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,53,48,54,50,51,52,51,50,52,90,23,13,50,57,48,53,48,54,50,51,52,51,50,52,90,48,129,128,49,52,48,50,6,3,85,4,3,12,43,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,221,240,183,6,75,207,221,115,4,19,196,67,137,3,147,128,251,94,246,116,173,66,97,82,88,2,38,83,25,200,99,34,7,9,82,97,202,196,217,87,239,109,38,104,139,116,145,140,196,249,128,104,40,252,9,104,240,16,218,233,208,46,201,26,163,129,247,48,129,244,48,70,6,8,43,6,1,5,5,7,1,1,4,58,48,56,48,54,6,8,43,6,1,5,5,7,48,1,134,42,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,52,45,97,112,112,108,101,114,111,111,116,99,97,103,51,48,29,6,3,85,29,14,4,22,4,20,132,182,132,204,58,134,98,114,22,89,148,232,26,163,189,72,223,58,223,11,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,31,6,3,85,29,35,4,24,48,22,128,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,55,6,3,85,29,31,4,48,48,46,48,44,160,42,160,40,134,38,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,114,111,111,116,99,97,103,51,46,99,114,108,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,15,4,2,5,0,48,10,6,8,42,134,72,206,61,4,3,2,3,105,0,48,102,2,49,0,217,177,199,49,198,35,246,79,77,208,217,71,197,125,24,105,17,135,113,39,211,104,173,224,155,101,154,190,108,223,63,70,166,144,9,190,110,161,59,44,176,81,137,65,60,135,210,191,2,49,0,252,100,82,137,75,60,93,191,107,28,194,137,152,47,114,174,181,155,170,26,11,35,84,119,84,232,21,67,162,197,18,218,151,80,115,124,94,208,110,178,92,98,80,215,81,241,58,90]\nstatic let AppleWWDRCAG3_cer: [UInt8] = [48,130,4,81,48,130,3,57,160,3,2,1,2,2,16,124,175,105,10,37,183,57,254,123,155,68,122,193,120,197,238,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,48,50,49,57,49,56,49,51,52,55,90,23,13,51,48,48,50,50,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,51,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,216,245,137,252,168,89,11,135,199,76,145,46,45,86,144,211,120,29,164,48,233,165,72,239,11,67,191,45,132,251,36,93,69,27,229,235,89,54,18,92,84,100,158,108,98,45,180,198,151,202,204,60,246,214,6,145,252,229,2,166,28,106,180,121,213,103,203,172,233,63,7,17,225,132,188,71,29,102,142,57,162,232,180,73,237,58,210,225,16,96,122,142,147,140,202,192,218,12,192,131,208,227,249,145,214,167,140,200,193,115,226,174,70,209,98,157,146,168,144,96,55,125,104,150,205,141,224,252,155,250,120,187,227,123,175,45,23,221,91,254,128,89,35,117,23,184,18,193,237,27,229,52,206,254,34,181,158,73,176,229,85,191,143,132,162,60,168,186,197,134,149,22,228,0,201,159,3,208,204,179,58,22,123,214,5,92,157,235,71,174,13,181,45,140,14,105,77,64,208,75,76,59,4,158,141,33,177,172,46,67,84,48,206,193,138,134,148,152,75,223,106,13,63,254,251,28,174,151,23,194,120,10,48,224,95,31,84,59,73,183,37,0,26,55,130,210,86,151,165,82,73,124,96,56,155,239,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,9,254,192,21,144,249,175,100,10,146,18,185,38,40,99,12,151,236,167,178,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,173,101,19,232,246,224,129,119,68,2,71,66,190,95,165,57,32,234,98,169,253,197,144,201,115,19,213,158,155,208,170,15,141,141,203,237,1,207,108,40,64,91,199,85,36,65,248,252,207,193,181,35,233,220,236,241,111,202,128,29,119,194,196,97,73,37,103,175,15,202,57,37,173,211,227,122,204,51,40,13,14,46,161,87,64,115,250,230,92,174,6,81,41,237,227,133,12,79,97,220,50,22,139,119,208,68,202,93,114,3,49,70,156,174,155,64,26,250,244,224,211,62,250,47,140,102,159,151,196,84,89,239,210,72,244,7,153,73,96,89,25,199,221,148,209,192,193,108,127,120,33,239,12,235,59,108,153,130,75,82,96,56,181,57,130,109,236,82,49,83,190,15,145,76,73,73,116,143,166,81,203,132,71,78,29,117,39,110,189,249,210,92,243,127,194,108,11,9,54,226,100,228,194,55,3,20,25,213,234,106,148,170,169,219,254,246,154,8,103,139,239,43,184,170,23,73,131,175,207,203,188,233,207,234,149,113,176,180,69,162,204,229,135,170,10,195,65,58,121,92,218,80,52,157,149,59]\nstatic let AppleWWDRCAG5_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,59,126,128,10,238,211,2,161,230,236,219,151,217,202,172,40,156,241,105,148,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,49,50,49,54,49,57,51,56,53,54,90,23,13,51,48,49,50,49,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,53,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,159,93,218,31,251,250,188,208,75,34,60,199,214,38,250,23,247,244,159,30,62,100,17,102,154,239,94,190,171,52,189,170,44,33,110,214,30,148,33,133,44,116,193,14,16,97,170,60,99,74,126,74,227,200,117,214,207,194,156,8,72,123,106,185,41,177,201,102,253,200,138,22,209,178,4,60,130,186,128,108,226,255,10,114,235,172,254,59,111,72,190,158,139,17,77,149,125,178,123,144,47,2,28,78,252,73,190,215,111,181,79,190,120,198,218,222,178,205,201,217,102,17,59,90,233,9,69,115,137,80,212,78,226,104,5,126,218,117,156,75,1,174,218,227,207,109,116,77,222,83,208,213,26,56,130,58,208,157,227,93,41,123,177,129,234,41,39,11,251,96,124,134,18,251,240,98,79,6,231,76,209,31,217,109,158,237,115,218,120,33,13,157,112,217,70,87,144,95,103,132,193,115,119,10,168,98,98,182,174,112,134,187,117,35,137,173,121,246,230,164,212,253,131,38,50,10,59,36,146,91,32,161,156,209,47,128,24,155,221,60,11,231,181,253,236,128,87,15,23,158,63,43,135,39,187,247,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,25,139,151,141,74,91,97,120,87,244,165,92,53,18,138,57,8,227,176,117,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,90,196,53,162,217,230,10,158,82,162,0,130,34,119,205,114,47,144,249,34,175,20,37,204,170,10,66,96,146,194,189,117,29,235,76,202,21,229,126,107,64,16,94,251,91,69,116,13,240,122,125,136,145,206,222,99,139,66,137,210,24,223,65,179,88,158,6,8,135,72,221,64,175,35,213,237,235,44,96,229,235,164,127,28,233,156,131,214,148,95,76,98,57,138,78,174,19,141,125,67,184,220,94,172,190,24,64,242,230,15,44,93,19,147,241,123,101,168,194,104,72,222,255,180,150,155,12,251,50,54,158,158,13,149,95,56,10,139,150,210,18,108,183,139,11,142,215,62,236,111,1,170,206,77,69,96,219,132,113,102,98,229,25,101,48,205,138,255,69,83,251,110,251,136,119,67,195,72,99,249,247,81,179,114,94,121,226,86,207,188,187,132,185,56,90,120,174,17,72,82,187,13,53,139,148,222,204,116,154,104,245,73,96,148,172,242,168,179,21,134,144,208,204,48,67,134,211,229,112,2,81,180,129,192,168,151,212,234,234,176,140,9,64,239,56,147,178,205,34,3,235,103,67,101,200,69]\nstatic let AppleRootCA_G2_cer: [UInt8] = [48,130,5,146,48,130,3,122,160,3,2,1,2,2,8,1,224,229,181,131,103,163,224,48,13,6,9,42,134,72,134,247,13,1,1,12,5,0,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,52,51,48,49,56,49,48,48,57,90,23,13,51,57,48,52,51,48,49,56,49,48,48,57,90,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,2,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,2,15,0,48,130,2,10,2,130,2,1,0,216,17,18,72,72,218,41,138,73,197,28,199,236,110,51,109,254,77,251,224,28,222,172,94,226,54,167,36,249,127,80,107,76,206,185,48,84,39,229,179,214,237,37,230,48,182,5,55,94,20,34,17,197,232,170,27,210,251,178,210,9,149,56,164,239,42,73,140,93,62,113,102,3,56,251,22,245,133,136,228,90,146,12,4,50,242,200,64,251,82,95,159,246,192,241,227,186,69,160,80,213,18,139,242,221,222,145,134,35,240,245,182,114,46,1,218,11,246,46,57,8,95,25,161,99,65,11,28,167,148,193,134,196,83,47,118,246,10,215,12,209,131,63,26,83,25,243,87,213,39,127,252,19,184,248,146,141,252,211,40,67,60,181,104,0,37,93,39,98,211,221,85,221,68,32,144,131,53,147,197,191,184,25,251,107,227,220,8,66,230,175,109,250,158,64,202,78,133,133,120,73,177,215,195,193,48,57,50,171,126,95,170,211,139,111,159,45,26,33,104,112,103,179,163,241,152,65,109,145,124,248,215,219,168,231,95,33,26,140,51,191,49,116,183,184,209,244,224,34,244,191,114,52,223,247,129,77,113,125,81,161,226,179,240,211,40,22,115,111,205,204,173,55,125,78,235,173,64,225,63,129,253,247,61,10,62,162,241,189,49,150,41,89,220,194,25,128,140,91,116,198,44,211,16,83,38,29,20,79,196,212,129,102,60,135,103,51,39,20,8,233,180,119,132,52,82,143,137,248,104,152,23,191,195,187,170,19,147,31,93,84,47,168,199,124,251,13,20,190,21,61,36,52,242,154,220,117,65,102,34,180,1,214,11,175,144,158,12,234,98,248,155,89,60,8,226,150,52,228,99,222,188,55,212,235,12,136,3,67,11,80,175,160,52,221,80,77,21,251,90,36,216,12,250,12,99,158,31,3,177,225,238,225,170,67,244,102,101,40,55,2,49,239,1,199,30,209,204,159,109,202,84,58,64,219,206,207,79,70,139,74,101,154,106,198,104,108,215,204,153,27,71,176,114,195,119,143,196,247,97,156,116,31,206,253,107,161,194,156,148,130,171,148,162,231,189,27,186,185,112,57,149,23,197,41,243,57,88,52,245,196,164,198,123,96,185,102,67,80,63,110,97,252,14,249,134,170,96,12,67,75,149,2,3,1,0,1,163,66,48,64,48,29,6,3,85,29,14,4,22,4,20,196,153,19,108,24,3,194,123,192,163,160,13,127,114,128,122,28,119,38,141,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,13,6,9,42,134,72,134,247,13,1,1,12,5,0,3,130,2,1,0,81,166,243,226,244,184,61,147,191,45,206,15,187,91,225,85,20,78,78,209,229,206,121,93,129,127,254,182,240,135,51,248,239,148,229,126,220,106,121,167,28,190,240,148,183,166,209,48,156,200,13,10,117,158,125,146,149,126,24,157,126,194,113,105,124,20,234,207,131,14,228,20,66,158,116,14,16,205,171,26,186,17,97,129,120,216,241,181,69,64,120,171,168,192,206,251,125,99,55,104,246,231,251,175,198,195,75,236,31,54,38,19,84,134,148,114,178,234,2,237,139,109,228,12,166,144,192,87,117,207,140,66,125,92,230,49,125,243,201,178,146,105,70,14,136,248,227,45,66,178,56,168,166,25,141,241,159,205,238,106,101,188,26,176,37,189,167,41,253,244,62,162,117,73,191,158,219,201,247,167,30,99,153,225,92,70,255,146,5,140,250,30,32,249,134,148,86,37,229,180,87,56,157,235,136,100,20,33,73,33,57,191,98,102,169,177,162,202,111,63,33,96,197,137,212,69,54,200,152,124,189,246,254,153,73,128,59,44,210,166,167,136,3,4,49,25,183,182,58,97,69,250,201,242,35,200,99,115,191,86,137,49,176,217,124,98,167,123,21,168,136,138,171,56,64,194,204,18,255,21,227,240,55,223,55,114,203,204,152,230,191,162,188,250,38,138,113,86,215,231,36,27,72,68,62,158,252,159,201,204,26,236,67,60,1,188,52,120,200,105,245,198,230,86,236,6,9,54,144,235,20,74,27,94,201,136,35,218,3,48,145,11,184,54,62,249,231,181,40,111,190,63,236,60,143,101,29,229,192,30,135,164,170,186,152,253,146,227,108,38,119,221,6,180,100,6,135,244,78,214,186,74,170,22,168,244,5,103,102,150,186,226,85,121,195,44,93,73,143,128,73,43,138,18,199,118,128,81,223,186,189,101,93,62,55,71,99,49,233,229,244,197,63,75,173,4,138,122,113,44,175,9,67,55,15,168,227,50,79,244,69,182,109,151,54,236,132,245,10,1,234,23,187,133,141,66,147,112,195,80,229,20,139,191,63,195,65,15,221,34,4,35,8,138,186,109,113,68,171,115,9,58,201,249,82,128,9,223,186,233,230,22,202,46,46,76,178,211,220,229,4,84,178,212,52,128,50,181,188,15,23,225]\nstatic let AppleComputerRootCertificate_cer: [UInt8] = [48,130,5,186,48,130,4,162,160,3,2,1,2,2,1,1,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,129,134,49,11,48,9,6,3,85,4,6,19,2,85,83,49,29,48,27,6,3,85,4,10,19,20,65,112,112,108,101,32,67,111,109,112,117,116,101,114,44,32,73,110,99,46,49,45,48,43,6,3,85,4,11,19,36,65,112,112,108,101,32,67,111,109,112,117,116,101,114,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,49,41,48,39,6,3,85,4,3,19,32,65,112,112,108,101,32,82,111,111,116,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,48,30,23,13,48,53,48,50,49,48,48,48,49,56,49,52,90,23,13,50,53,48,50,49,48,48,48,49,56,49,52,90,48,129,134,49,11,48,9,6,3,85,4,6,19,2,85,83,49,29,48,27,6,3,85,4,10,19,20,65,112,112,108,101,32,67,111,109,112,117,116,101,114,44,32,73,110,99,46,49,45,48,43,6,3,85,4,11,19,36,65,112,112,108,101,32,67,111,109,112,117,116,101,114,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,49,41,48,39,6,3,85,4,3,19,32,65,112,112,108,101,32,82,111,111,116,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,228,145,169,9,31,145,219,30,71,80,235,5,237,94,121,132,45,235,54,162,87,76,85,236,139,25,137,222,249,75,108,245,7,171,34,48,2,232,24,62,248,80,9,211,127,65,168,152,249,209,202,102,156,36,107,17,208,163,187,228,27,42,195,31,149,158,122,12,164,71,139,91,212,22,55,51,203,196,15,77,206,20,105,209,201,25,114,245,93,14,213,127,95,155,242,37,3,186,85,143,77,93,13,241,100,53,35,21,75,21,89,29,179,148,247,246,156,158,207,80,186,193,88,80,103,143,8,180,32,247,203,172,44,32,111,112,182,63,1,48,140,183,67,207,15,157,61,243,43,73,40,26,200,254,206,181,185,14,217,94,28,214,203,61,181,58,173,244,15,14,0,146,11,177,33,22,46,116,213,60,13,219,98,22,171,163,113,146,71,83,85,193,175,47,65,179,248,251,227,112,205,230,163,76,69,126,31,76,107,80,150,65,137,196,116,98,11,16,131,65,135,51,138,129,177,48,88,236,90,4,50,140,104,179,143,29,222,101,115,255,103,94,101,188,73,216,118,159,51,20,101,161,119,148,201,45,2,3,1,0,1,163,130,2,47,48,130,2,43,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,29,6,3,85,29,14,4,22,4,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,130,1,41,6,3,85,29,32,4,130,1,32,48,130,1,28,48,130,1,24,6,9,42,134,72,134,247,99,100,5,1,48,130,1,9,48,65,6,8,43,6,1,5,5,7,2,1,22,53,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,116,101,114,109,115,46,104,116,109,108,48,129,195,6,8,43,6,1,5,5,7,2,2,48,129,182,26,129,179,82,101,108,105,97,110,99,101,32,111,110,32,116,104,105,115,32,99,101,114,116,105,102,105,99,97,116,101,32,98,121,32,97,110,121,32,112,97,114,116,121,32,97,115,115,117,109,101,115,32,97,99,99,101,112,116,97,110,99,101,32,111,102,32,116,104,101,32,116,104,101,110,32,97,112,112,108,105,99,97,98,108,101,32,115,116,97,110,100,97,114,100,32,116,101,114,109,115,32,97,110,100,32,99,111,110,100,105,116,105,111,110,115,32,111,102,32,117,115,101,44,32,99,101,114,116,105,102,105,99,97,116,101,32,112,111,108,105,99,121,32,97,110,100,32,99,101,114,116,105,102,105,99,97,116,105,111,110,32,112,114,97,99,116,105,99,101,32,115,116,97,116,101,109,101,110,116,115,46,48,68,6,3,85,29,31,4,61,48,59,48,57,160,55,160,53,134,51,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,114,111,111,116,46,99,114,108,48,85,6,8,43,6,1,5,5,7,1,1,4,73,48,71,48,69,6,8,43,6,1,5,5,7,48,2,134,57,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,99,97,115,105,103,110,101,114,115,46,104,116,109,108,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,157,218,45,40,88,47,125,118,4,185,4,211,62,206,183,102,99,78,143,47,212,254,75,173,114,189,163,57,198,82,77,5,152,82,245,137,81,1,36,121,190,26,50,247,229,68,139,75,68,7,57,130,214,90,202,180,32,94,217,174,21,93,29,140,29,50,191,56,49,98,72,93,199,225,144,177,248,36,64,248,95,88,155,81,93,87,157,193,229,255,60,204,114,33,110,196,233,233,161,119,215,44,23,38,195,63,235,154,232,11,3,186,233,179,74,114,235,51,9,91,173,230,98,49,106,232,175,47,213,175,30,87,118,143,127,55,45,46,2,92,221,99,201,242,113,184,38,64,223,21,141,117,68,63,121,189,230,29,153,225,67,44,62,173,111,190,185,164,254,14,53,25,81,99,177,195,222,181,146,62,81,120,1,115,138,164,35,202,164,136,241,30,92,31,65,22,45,126,149,10,170,233,137,65,152,27,26,221,203,32,191,71,94,12,38,197,85,53,77,198,48,139,153,103,20,199,9,31,186,71,199,218,1,9,135,36,66,149,189,19,96,25,10,239,234,127,14,110,205,193,68,67,58,74,213,227]\nstatic let AppleWWDRCAG7_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,52,24,88,255,1,254,6,63,142,241,159,31,233,60,1,180,193,70,255,201,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,50,49,49,49,55,50,48,52,48,53,51,90,23,13,50,51,49,49,49,55,50,48,52,48,53,50,90,48,117,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,11,12,2,71,55,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,172,174,209,211,182,138,177,27,40,149,173,222,81,81,76,63,51,225,78,92,175,179,252,2,210,101,79,42,212,116,104,140,117,23,101,207,40,228,72,9,152,113,82,50,44,22,78,120,142,146,86,100,169,221,139,205,226,212,199,59,162,18,69,55,2,25,98,100,47,127,97,198,211,89,34,191,171,249,20,163,237,182,158,153,186,47,241,177,220,48,66,79,182,182,178,198,116,170,98,86,187,237,68,54,15,209,229,32,116,147,87,58,93,158,220,1,252,120,111,105,22,53,195,110,1,194,158,114,212,113,54,177,118,9,122,190,13,42,151,241,176,94,11,27,18,173,43,171,7,223,99,45,245,136,233,50,18,162,85,88,67,118,60,61,23,128,31,41,219,177,169,159,171,150,5,157,21,220,221,219,78,15,231,19,124,90,43,46,2,65,246,238,122,106,182,115,96,247,151,25,20,139,149,51,56,147,218,0,37,54,174,85,90,124,159,249,244,98,4,7,116,233,29,167,149,87,35,172,43,36,218,100,79,40,114,233,150,176,8,60,136,27,20,99,67,215,137,174,152,193,242,45,142,227,81,37,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,93,66,16,108,27,187,199,82,151,78,68,189,19,39,185,58,18,119,131,43,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,82,163,8,41,19,101,183,181,31,230,52,3,237,246,24,119,188,61,202,39,181,112,236,236,108,51,75,246,153,37,148,7,158,33,51,3,106,245,125,10,46,43,223,8,169,130,222,74,127,225,231,11,75,5,184,39,152,73,221,193,12,134,215,129,100,174,130,156,196,69,241,234,143,28,34,48,227,162,37,97,68,137,254,133,122,86,240,114,146,124,12,68,84,36,183,181,164,159,38,240,50,249,87,157,106,121,108,64,237,15,52,6,6,66,255,216,14,49,101,109,230,46,1,217,6,191,197,202,13,174,71,212,5,23,136,60,233,156,228,25,100,109,138,148,173,17,220,1,246,229,120,175,173,232,112,215,13,93,129,62,70,42,44,174,36,161,199,210,224,125,191,29,245,54,107,197,222,169,10,154,128,177,17,94,178,100,126,179,193,87,204,194,108,89,153,183,244,176,221,49,218,72,214,106,129,238,178,139,80,53,22,230,231,92,113,98,110,176,242,81,226,168,109,248,42,203,104,115,198,166,196,26,67,73,1,62,169,169,0,138,134,108,131,136,210,92,112,87,122,218,248,118,204,25,213,176]\nstatic let AppleIncRootCertificate_cer: [UInt8] = [48,130,4,187,48,130,3,163,160,3,2,1,2,2,1,2,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,48,54,48,52,50,53,50,49,52,48,51,54,90,23,13,51,53,48,50,48,57,50,49,52,48,51,54,90,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,228,145,169,9,31,145,219,30,71,80,235,5,237,94,121,132,45,235,54,162,87,76,85,236,139,25,137,222,249,75,108,245,7,171,34,48,2,232,24,62,248,80,9,211,127,65,168,152,249,209,202,102,156,36,107,17,208,163,187,228,27,42,195,31,149,158,122,12,164,71,139,91,212,22,55,51,203,196,15,77,206,20,105,209,201,25,114,245,93,14,213,127,95,155,242,37,3,186,85,143,77,93,13,241,100,53,35,21,75,21,89,29,179,148,247,246,156,158,207,80,186,193,88,80,103,143,8,180,32,247,203,172,44,32,111,112,182,63,1,48,140,183,67,207,15,157,61,243,43,73,40,26,200,254,206,181,185,14,217,94,28,214,203,61,181,58,173,244,15,14,0,146,11,177,33,22,46,116,213,60,13,219,98,22,171,163,113,146,71,83,85,193,175,47,65,179,248,251,227,112,205,230,163,76,69,126,31,76,107,80,150,65,137,196,116,98,11,16,131,65,135,51,138,129,177,48,88,236,90,4,50,140,104,179,143,29,222,101,115,255,103,94,101,188,73,216,118,159,51,20,101,161,119,148,201,45,2,3,1,0,1,163,130,1,122,48,130,1,118,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,29,6,3,85,29,14,4,22,4,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,130,1,17,6,3,85,29,32,4,130,1,8,48,130,1,4,48,130,1,0,6,9,42,134,72,134,247,99,100,5,1,48,129,242,48,42,6,8,43,6,1,5,5,7,2,1,22,30,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,99,97,47,48,129,195,6,8,43,6,1,5,5,7,2,2,48,129,182,26,129,179,82,101,108,105,97,110,99,101,32,111,110,32,116,104,105,115,32,99,101,114,116,105,102,105,99,97,116,101,32,98,121,32,97,110,121,32,112,97,114,116,121,32,97,115,115,117,109,101,115,32,97,99,99,101,112,116,97,110,99,101,32,111,102,32,116,104,101,32,116,104,101,110,32,97,112,112,108,105,99,97,98,108,101,32,115,116,97,110,100,97,114,100,32,116,101,114,109,115,32,97,110,100,32,99,111,110,100,105,116,105,111,110,115,32,111,102,32,117,115,101,44,32,99,101,114,116,105,102,105,99,97,116,101,32,112,111,108,105,99,121,32,97,110,100,32,99,101,114,116,105,102,105,99,97,116,105,111,110,32,112,114,97,99,116,105,99,101,32,115,116,97,116,101,109,101,110,116,115,46,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,92,54,153,76,45,120,183,237,140,155,220,243,119,155,242,118,210,119,48,79,193,31,133,131,133,27,153,61,71,55,242,169,155,64,142,44,212,177,144,18,216,190,244,115,155,238,210,100,15,203,121,79,52,216,162,62,249,120,255,107,200,7,236,125,57,131,139,83,32,211,56,196,177,191,154,79,10,107,255,43,252,89,167,5,9,124,23,64,86,17,30,116,211,183,139,35,59,71,163,213,111,36,226,235,209,183,112,223,15,69,225,39,202,241,109,120,237,231,181,23,23,168,220,126,34,53,202,37,213,217,15,214,107,212,162,36,35,17,247,161,172,143,115,129,96,198,27,91,9,47,146,178,248,68,72,240,96,56,158,21,245,61,38,103,32,138,51,106,247,13,130,207,222,235,163,47,249,83,106,91,100,192,99,51,119,247,58,7,44,86,235,218,15,33,14,218,186,115,25,79,181,217,54,127,193,135,85,217,167,153,185,50,66,251,216,213,113,158,126,161,82,183,27,189,147,66,36,18,42,199,15,29,182,77,156,94,99,200,75,128,23,80,170,138,213,218,228,252,208,9,7,55,176,117,117,33]\nstatic let AppleWWDRCAG4_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,19,220,119,149,82,113,229,61,198,50,232,204,255,229,33,243,204,197,206,210,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,49,50,49,54,49,57,51,54,48,52,90,23,13,51,48,49,50,49,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,52,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,208,31,120,170,122,39,50,176,70,95,231,23,118,216,160,157,14,41,142,173,61,50,165,196,107,55,201,228,65,145,106,183,121,113,93,12,52,4,96,117,247,174,67,143,71,196,134,30,8,232,191,214,57,82,47,30,103,252,113,241,130,109,60,126,6,82,118,157,44,188,213,67,233,177,180,188,64,58,120,81,93,81,161,37,225,190,108,145,157,107,33,89,24,65,213,15,141,109,65,42,57,74,33,224,144,159,78,19,79,208,140,154,50,184,215,106,146,30,37,106,164,50,206,34,25,133,5,96,220,2,74,242,90,235,119,121,2,125,192,151,84,108,146,142,118,1,230,70,143,229,230,42,251,162,176,173,24,173,109,51,133,56,35,139,234,138,150,237,159,174,102,79,163,12,64,39,109,149,208,98,136,217,67,41,39,253,237,164,191,83,46,144,21,101,60,217,46,98,100,51,29,108,106,221,142,33,170,164,95,21,198,48,237,95,230,140,54,146,148,183,220,57,2,0,251,100,140,212,12,129,242,63,213,52,151,135,117,38,194,111,174,3,99,33,12,123,212,27,177,98,197,2,156,189,253,175,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,91,217,250,29,231,154,26,11,163,153,118,34,80,134,62,145,200,91,119,168,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,63,86,61,158,229,182,195,121,230,69,32,104,189,191,115,139,44,18,158,2,227,174,128,34,140,4,30,195,82,200,112,128,168,251,206,167,176,213,66,68,130,3,130,79,6,252,59,73,20,251,216,116,82,133,175,167,157,33,231,1,18,3,159,205,64,88,208,1,215,191,50,131,43,83,88,40,60,238,156,159,84,118,61,100,39,198,126,141,29,56,77,45,174,129,230,185,165,184,156,137,148,247,159,199,135,165,81,102,52,27,57,113,57,36,227,135,103,239,165,177,104,123,140,238,61,247,174,182,123,226,210,255,223,97,198,106,117,73,149,34,68,168,4,252,148,184,11,46,57,17,73,18,209,229,129,234,89,0,79,91,60,90,54,218,122,34,115,9,9,105,205,192,124,234,226,36,254,152,68,184,248,239,178,113,63,26,93,212,93,126,51,77,156,29,36,190,0,240,144,3,88,153,65,61,49,90,98,64,175,57,168,81,67,146,171,4,168,156,194,77,177,75,210,171,124,74,95,235,157,59,188,79,136,64,6,19,255,144,23,138,8,71,41,232,98,152,41,165,79,17,5,105,58,207,242,159]\nstatic let AppleWWDRCAG6_cer: [UInt8] = [48,130,3,22,48,130,2,156,160,3,2,1,2,2,20,34,193,161,71,10,116,115,105,239,83,134,18,201,198,159,61,56,243,108,215,48,10,6,8,42,134,72,206,61,4,3,3,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,50,49,48,51,49,55,50,48,51,55,49,48,90,23,13,51,54,48,51,49,57,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,54,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,118,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,3,98,0,4,110,196,10,11,222,15,174,85,166,101,121,215,130,220,115,117,82,75,241,61,18,25,137,224,13,17,169,158,9,247,55,163,211,240,147,4,111,177,67,139,134,193,152,248,66,157,157,255,178,174,143,23,247,6,112,165,214,176,190,111,58,215,145,135,34,120,231,29,192,72,254,220,56,31,154,106,143,116,125,202,113,74,255,196,100,86,231,136,6,205,129,145,161,34,26,72,163,129,250,48,129,247,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,70,6,8,43,6,1,5,5,7,1,1,4,58,48,56,48,54,6,8,43,6,1,5,5,7,48,1,134,42,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,103,51,48,55,6,3,85,29,31,4,48,48,46,48,44,160,42,160,40,134,38,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,114,111,111,116,99,97,103,51,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,63,47,148,35,81,211,80,201,154,40,61,237,176,124,229,207,165,144,98,153,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,10,6,8,42,134,72,206,61,4,3,3,3,104,0,48,101,2,48,64,94,20,170,228,140,138,162,3,2,62,220,56,247,64,90,7,174,251,9,161,6,37,123,159,64,31,196,169,145,157,232,36,163,136,43,78,158,227,19,109,117,87,155,28,92,197,249,2,49,0,211,72,252,90,173,149,239,54,185,49,83,116,228,80,194,55,223,44,239,21,85,81,79,140,49,88,144,189,247,131,172,117,198,120,249,17,141,177,128,242,71,152,38,118,189,39,12,104]\nstatic let AppleWWDRCAG8_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,84,181,11,175,121,13,141,127,140,175,104,76,86,47,80,105,10,26,186,95,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,51,48,54,50,48,50,51,51,55,49,53,90,23,13,50,53,48,49,50,52,48,48,48,48,48,48,90,48,117,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,11,12,2,71,56,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,208,64,16,212,8,249,82,33,99,79,60,104,247,212,156,130,2,140,131,104,188,183,141,127,136,231,66,77,44,239,34,165,194,137,222,189,12,215,77,97,80,45,57,228,48,115,165,210,213,104,154,51,242,239,217,42,173,46,31,3,186,248,165,241,66,11,87,46,70,198,208,88,211,112,95,247,178,55,239,106,31,62,191,137,57,194,173,254,245,5,251,88,150,49,200,135,44,213,35,186,117,176,44,245,171,160,186,242,32,12,76,235,36,99,105,233,34,64,240,142,88,91,222,100,123,137,27,81,18,4,224,23,178,89,205,223,241,231,206,175,44,50,232,105,193,208,8,126,29,162,71,115,209,75,59,253,185,133,220,71,167,40,130,121,41,72,137,2,40,226,193,236,44,31,91,134,252,216,182,203,113,192,115,1,75,252,5,17,17,108,1,3,52,90,246,129,194,94,31,124,20,14,222,63,107,33,203,79,245,215,97,230,132,3,146,188,231,37,41,158,205,91,12,193,219,227,196,58,217,118,87,172,47,56,20,25,200,183,177,162,85,79,95,78,142,25,89,169,218,253,114,218,176,4,33,5,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,181,189,188,128,196,12,227,56,164,244,183,173,35,179,239,68,206,185,90,133,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,76,179,235,122,57,148,74,149,102,250,22,49,234,13,138,143,93,66,56,198,7,205,232,201,34,172,252,8,66,126,95,147,95,49,42,168,34,193,118,25,43,238,174,114,233,189,86,207,73,36,146,8,247,205,25,117,195,249,26,39,13,14,220,41,141,63,182,219,165,79,76,114,196,96,145,137,17,126,36,149,67,34,96,103,188,223,255,171,229,60,22,23,157,130,20,78,157,244,117,254,80,185,173,5,178,184,121,246,149,214,16,229,246,83,244,207,35,230,119,15,236,184,75,105,248,226,158,2,49,217,142,217,202,190,99,94,95,225,160,105,206,193,205,110,73,163,120,97,175,57,60,106,75,10,52,37,100,213,48,181,60,171,221,17,129,57,113,232,192,195,88,128,17,16,26,17,210,194,188,89,240,138,217,53,115,192,230,109,228,201,125,98,20,62,130,2,169,16,105,55,121,97,111,240,70,148,62,53,245,171,172,99,208,216,94,89,87,105,209,184,75,110,93,212,95,19,156,112,78,37,17,220,36,44,30,22,158,150,90,4,237,69,238,58,238,103,93,143,195,134,176,245,76,31,104,16]\nstatic let AppleRootCA_G3_cer: [UInt8] = [48,130,2,67,48,130,1,201,160,3,2,1,2,2,8,45,197,252,136,210,197,75,149,48,10,6,8,42,134,72,206,61,4,3,3,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,52,51,48,49,56,49,57,48,54,90,23,13,51,57,48,52,51,48,49,56,49,57,48,54,90,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,118,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,3,98,0,4,152,233,47,61,64,114,164,237,147,34,114,129,19,28,221,16,149,241,197,163,78,113,220,20,22,217,14,229,166,5,42,119,100,123,95,78,56,211,187,28,68,181,127,245,31,182,50,98,93,201,233,132,91,79,48,79,17,90,0,253,88,88,12,165,245,15,44,77,7,71,19,117,218,151,151,151,111,49,92,237,43,157,123,32,59,216,185,84,217,94,153,164,58,81,10,49,163,66,48,64,48,29,6,3,85,29,14,4,22,4,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,10,6,8,42,134,72,206,61,4,3,3,3,104,0,48,101,2,49,0,131,233,193,196,22,94,26,93,52,24,217,237,239,244,108,14,0,70,75,184,223,178,70,17,197,15,253,230,122,140,161,166,107,206,194,3,212,156,245,147,198,116,184,106,223,170,35,21,2,48,109,102,138,16,202,212,13,212,79,205,141,67,62,180,138,99,165,51,110,227,109,218,23,183,100,31,200,83,38,249,136,98,116,57,11,23,91,203,81,168,12,232,24,3,231,162,178,40]\n}\n"
  },
  {
    "path": "Sources/QueryEngine/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(QueryEngine\n  CacheKey.swift\n  FileCacheRecord.swift\n  Query.swift\n  QueryEngine.swift)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(QueryEngine PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\ntarget_link_libraries(QueryEngine PUBLIC\n  _AsyncFileSystem\n  Basics\n  Crypto\n  SwiftSystem::SystemPackage)\nif(NOT APPLE)\n  if(Foundation_FOUND)\n    target_link_directories(QueryEngine PRIVATE\n      $<TARGET_LINKER_FILE_DIR:Foundation>)\n  endif()\nendif()\n\ninstall(TARGETS QueryEngine\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/QueryEngine/CacheKey.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_exported import protocol Crypto.HashFunction\nimport struct Foundation.URL\npackage import struct SystemPackage.FilePath\n\n/// Indicates that values of a conforming type can be hashed with an arbitrary hashing function. Unlike `Hashable`,\n/// this protocol doesn't utilize random seed values and produces consistent hash values across process launches.\npublic protocol CacheKey: Encodable {}\n\n/// Types that cannot be decomposed more to be hashed\nprotocol LeafCacheKey: CacheKey {\n  func hash(with hashFunction: inout some HashFunction)\n}\n\nextension Bool: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    hashFunction.update(data: self ? [1] : [0])\n  }\n}\n\nextension Int: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension Int8: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension Int16: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension Int32: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension Int64: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension UInt: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension UInt8: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension UInt16: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension UInt32: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension UInt64: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension Float: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension Double: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    withUnsafeBytes(of: self) {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension String: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    var t = String(reflecting: Self.self)\n    t.withUTF8 {\n      hashFunction.update(data: $0)\n    }\n    var x = self\n    x.withUTF8 {\n      hashFunction.update(data: $0)\n    }\n  }\n}\n\nextension FilePath: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    self.string.hash(with: &hashFunction)\n  }\n}\n\nextension FilePath.Component: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    self.string.hash(with: &hashFunction)\n  }\n}\n\nextension URL: LeafCacheKey {\n  func hash(with hashFunction: inout some HashFunction) {\n    String(reflecting: Self.self).hash(with: &hashFunction)\n    self.description.hash(with: &hashFunction)\n  }\n}\n"
  },
  {
    "path": "Sources/QueryEngine/FileCacheRecord.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct _AsyncFileSystem.OpenReadableFile\n\n// FIXME: need a new swift-system tag to remove `@preconcurrency`\n@preconcurrency package import struct SystemPackage.FilePath\n\npackage struct FileCacheRecord: Sendable {\n    package let path: FilePath\n    package let hash: String\n}\n\nextension FileCacheRecord: Codable {\n    enum CodingKeys: CodingKey {\n        case path\n        case hash\n    }\n\n    // FIXME: `Codable` on `FilePath` is broken, thus all `Codable` types with `FilePath` properties need a custom impl.\n    package init(from decoder: any Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        self.path = try FilePath(container.decode(String.self, forKey: .path))\n        self.hash = try container.decode(String.self, forKey: .hash)\n    }\n\n    package func encode(to encoder: any Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        try container.encode(self.path.string, forKey: .path)\n        try container.encode(self.hash, forKey: .hash)\n    }\n}\n\nextension OpenReadableFile {\n    func hash(with hashFunction: inout some HashFunction) async throws {\n        let stream = try await self.read()\n\n        for try await bytes in stream {\n            hashFunction.update(data: bytes)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/QueryEngine/Query.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npackage import struct SystemPackage.FilePath\n\npackage protocol Query: Sendable {\n    associatedtype Key: CacheKey\n    var cacheKey: Key { get }\n    func run(engine: QueryEngine) async throws -> FilePath\n}\n\npackage protocol CachingQuery: Query, CacheKey where Self.Key == Self {}\nextension CachingQuery {\n    package var cacheKey: Key { self }\n}\n\n// SwiftPM has to be built with Swift 5.8 on CI and also needs to support CMake for bootstrapping on Windows.\n// This means we can't implement persistable hashing with macros (unavailable in Swift 5.8 and additional effort to\n// set up with CMake when Swift 5.9 is available for all CI jobs) and have to stick to `Encodable` for now.\nfinal class HashEncoder<Hash: HashFunction>: Encoder {\n    enum Error: Swift.Error {\n        case noCacheKeyConformance(Encodable.Type)\n    }\n\n    var codingPath: [any CodingKey]\n\n    var userInfo: [CodingUserInfoKey: Any]\n\n    func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {\n        .init(KeyedContainer(encoder: self))\n    }\n\n    func unkeyedContainer() -> any UnkeyedEncodingContainer {\n        self\n    }\n\n    func singleValueContainer() -> any SingleValueEncodingContainer {\n        self\n    }\n\n    init() {\n        self.hashFunction = Hash()\n        self.codingPath = []\n        self.userInfo = [:]\n    }\n\n    fileprivate var hashFunction = Hash()\n\n    func finalize() -> Hash.Digest {\n        self.hashFunction.finalize()\n    }\n}\n\nextension HashEncoder: SingleValueEncodingContainer {\n    func encodeNil() throws {\n        // FIXME: this doesn't encode the name of the underlying optional type,\n        // but `Encoder` protocol is limited and can't provide this for us.\n        var str = \"nil\"\n        str.withUTF8 {\n            self.hashFunction.update(data: $0)\n        }\n    }\n\n    func encode(_ value: Bool) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: String) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: Double) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: Float) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: Int) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: Int8) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: Int16) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: Int32) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: Int64) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: UInt) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: UInt8) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: UInt16) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: UInt32) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode(_ value: UInt64) throws {\n        value.hash(with: &self.hashFunction)\n    }\n\n    func encode<T>(_ value: T) throws where T: Encodable {\n        if let leaf = value as? LeafCacheKey {\n            leaf.hash(with: &self.hashFunction)\n            return\n        }\n\n        guard value is CacheKey else {\n            throw Error.noCacheKeyConformance(T.self)\n        }\n\n        try String(describing: T.self).encode(to: self)\n        try value.encode(to: self)\n    }\n}\n\nextension HashEncoder: UnkeyedEncodingContainer {\n    var count: Int {\n        0\n    }\n\n    func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey>\n    where NestedKey: CodingKey {\n        KeyedEncodingContainer(KeyedContainer(encoder: self))\n    }\n\n    func nestedUnkeyedContainer() -> any UnkeyedEncodingContainer {\n        self\n    }\n\n    func superEncoder() -> any Encoder {\n        fatalError(\"\\(#file):\\(#line) - Illegal call of function \\(#function)\")\n    }\n}\n\nextension HashEncoder {\n    struct KeyedContainer<K: CodingKey>: KeyedEncodingContainerProtocol {\n        var encoder: HashEncoder\n        var codingPath: [any CodingKey] { self.encoder.codingPath }\n\n        mutating func encodeNil(forKey key: K) throws {\n            // FIXME: this doesn't encode the name of the underlying optional type,\n            // but `Encoder` protocol is limited and can't provide this for us.\n            var str = \"nil\"\n            str.withUTF8 {\n                self.encoder.hashFunction.update(data: $0)\n            }\n        }\n\n        mutating func encode(_ value: Bool, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: String, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: Double, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: Float, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: Int, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: Int8, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: Int16, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: Int32, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: Int64, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: UInt, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: UInt8, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: UInt16, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: UInt32, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode(_ value: UInt64, forKey key: K) throws {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            value.hash(with: &self.encoder.hashFunction)\n        }\n\n        mutating func encode<T>(_ value: T, forKey key: K) throws where T: Encodable {\n            if let leaf = value as? LeafCacheKey {\n                leaf.hash(with: &self.encoder.hashFunction)\n                return\n            }\n            guard value is CacheKey else {\n                throw Error.noCacheKeyConformance(T.self)\n            }\n\n            try String(reflecting: T.self).encode(to: self.encoder)\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            try value.encode(to: self.encoder)\n        }\n\n        mutating func nestedContainer<NestedKey>(\n            keyedBy keyType: NestedKey.Type,\n            forKey key: K\n        ) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            return self.encoder.nestedContainer(keyedBy: keyType)\n        }\n\n        mutating func nestedUnkeyedContainer(forKey key: K) -> any UnkeyedEncodingContainer {\n            key.stringValue.hash(with: &self.encoder.hashFunction)\n            return self.encoder\n        }\n\n        mutating func superEncoder() -> any Encoder {\n            fatalError(\"\\(#file):\\(#line) - Illegal call of function \\(#function)\")\n        }\n\n        mutating func superEncoder(forKey key: K) -> any Encoder {\n            fatalError(\"\\(#file):\\(#line) - Illegal call of function \\(#function)\")\n        }\n\n        typealias Key = K\n    }\n}\n"
  },
  {
    "path": "Sources/QueryEngine/QueryEngine.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _AsyncFileSystem\nimport Basics\nimport Crypto\n\npackage func withQueryEngine(\n    _ fileSystem: some AsyncFileSystem,\n    _ observabilityScope: ObservabilityScope,\n    cacheLocation: SQLite.Location,\n    _ body: @Sendable (QueryEngine) async throws -> Void\n) async throws {\n    let engine = QueryEngine(\n        fileSystem,\n        observabilityScope,\n        cacheLocation: cacheLocation\n    )\n\n    try await withAsyncThrowing {\n        try await body(engine)\n    } defer: {\n        try await engine.shutDown()\n    }\n}\n\n/// Cacheable computations engine. Currently the engine makes an assumption that computations produce same results for\n/// the same query values and write results to a single file path.\npackage actor QueryEngine {\n    private(set) var cacheHits = 0\n    private(set) var cacheMisses = 0\n\n    package let fileSystem: any AsyncFileSystem\n    package let httpClient = HTTPClient()\n    package let observabilityScope: ObservabilityScope\n    private let resultsCache: SQLiteBackedCache<FileCacheRecord>\n    private var isShutDown = false\n\n    /// Creates a new instance of the ``QueryEngine`` actor. Requires an explicit call\n    /// to ``QueryEngine//shutdown`` before the instance is deinitialized. The recommended approach to resource\n    /// management is to place `engine.shutDown()` when the engine is no longer used, but is not deinitialized yet.\n    /// - Parameter fileSystem: Implementation of a file system this engine should use.\n    /// - Parameter cacheLocation: Location of cache storage used by the engine.\n    /// - Parameter logger: Logger to use during queries execution.\n    init(\n        _ fileSystem: any AsyncFileSystem,\n        _ observabilityScope: ObservabilityScope,\n        cacheLocation: SQLite.Location\n    ) {\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n        self.resultsCache = SQLiteBackedCache(tableName: \"cache_table\", location: cacheLocation)\n    }\n\n    package func shutDown() async throws {\n        precondition(!self.isShutDown, \"`QueryEngine/shutDown` should be called only once\")\n        try self.resultsCache.close()\n\n        self.isShutDown = true\n    }\n\n    deinit {\n        let isShutDown = self.isShutDown\n        precondition(\n            isShutDown,\n            \"`QueryEngine/shutDown` should be called explicitly on instances of `Engine` before deinitialization\"\n        )\n    }\n\n    /// Executes a given query if no cached result of it is available. Otherwise fetches the result from engine's cache.\n    /// - Parameter query: A query value to execute.\n    /// - Returns: A file path to query's result recorded in a file.\n    package subscript(_ query: some Query) -> FileCacheRecord {\n        get async throws {\n            let hashEncoder = HashEncoder<SHA512>()\n            try hashEncoder.encode(query.cacheKey)\n            let key = hashEncoder.finalize()\n\n            if let fileRecord = try resultsCache.get(blobKey: key) {\n\n                let fileHash = try await self.fileSystem.withOpenReadableFile(fileRecord.path) {\n                    var hashFunction = SHA512()\n                    try await $0.hash(with: &hashFunction)\n                    return hashFunction.finalize().description\n                }\n\n                if fileHash == fileRecord.hash {\n                    self.cacheHits += 1\n                    return fileRecord\n                }\n            }\n\n            self.cacheMisses += 1\n            let resultPath = try await query.run(engine: self)\n\n            let resultHash = try await self.fileSystem.withOpenReadableFile(resultPath) {\n                var hashFunction = SHA512()\n                try await $0.hash(with: &hashFunction)\n                return hashFunction.finalize().description\n            }\n            let result = FileCacheRecord(path: resultPath, hash: resultHash)\n\n            // FIXME: update `SQLiteBackedCache` to store `resultHash` directly instead of relying on string conversions\n            try self.resultsCache.put(blobKey: key, value: result)\n\n            return result\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\ncmake_minimum_required(VERSION 3.29)\n\nif(POLICY CMP0157 AND CMAKE_Swift_COMPILER_USE_OLD_DRIVER)\n  cmake_policy(SET CMP0157 OLD)\nendif()\n\nproject(SwiftPMRuntime\n  LANGUAGES Swift)\n\n# TODO(compnerd) C is being enabled as a workaround for `GNUInstallDirs` not\n# being aware of Swift-only projects. Remove this once that is updated and we\n# have updated to a newer CMake minimum version.\nenable_language(C)\ninclude(GNUInstallDirs)\n\nset(CMAKE_INSTALL_NAME_DIR \"@rpath\")\nset(CMAKE_INSTALL_RPATH \"$ORIGIN/../../$<LOWER_CASE:${CMAKE_SYSTEM_NAME}>\")\nset(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreadedDLL)\nset(CMAKE_POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS})\nset(CMAKE_Swift_LANGUAGE_VERSION 5)\nset(CMAKE_Swift_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY MultiThreadedDLL)\n\nset(SwiftPMRuntime_ENABLE_LIBRARY_EVOLUTION YES)\nadd_compile_options(-enable-library-evolution)\n\nadd_compile_options(-package-description-version 999.0)\n\nlist(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)\ninclude(PlatformInfo)\ninclude(EmitSwiftInterface)\ninclude(InstallSwiftInterface)\n\nadd_subdirectory(PackageDescription)\nadd_subdirectory(CompilerPluginSupport)\nadd_subdirectory(PackagePlugin)\n"
  },
  {
    "path": "Sources/Runtimes/CompilerPluginSupport/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2023-2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(CompilerPluginSupport\n  TargetExtensions.swift)\ntarget_link_libraries(CompilerPluginSupport PRIVATE\n  PackageDescription)\n\nif(APPLE)\n  target_link_options(CompilerPluginSupport PRIVATE\n    \"SHELL:-Xlinker -install_name -Xlinker @rpath/CompilerPluginSupport.dylib\")\nelse()\n  target_link_libraries(CompilerPluginSupport PRIVATE\n    Foundation)\nendif()\n\ninstall(TARGETS CompilerPluginSupport\n  DESTINATION ${CMAKE_INSTALL_LIBDIR}/swift/pm/ManifestAPI)\n\nset(SwiftPMRuntime_INSTALL_SWIFTMODULEDIR\n  ${CMAKE_INSTALL_LIBDIR}/swift/pm/ManifestAPI)\nemit_swift_interface(CompilerPluginSupport)\ninstall_swift_interface(CompilerPluginSupport)\n"
  },
  {
    "path": "Sources/Runtimes/CompilerPluginSupport/TargetExtensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(PackageDescriptionInternal) import PackageDescription\n\npublic extension Target {\n    @available(_PackageDescription, introduced: 5.9)\n    static func macro(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        packageAccess: Bool = true,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil,\n        plugins: [PluginUsage]? = nil\n    ) -> Target {\n        return Target(name: name,\n                      dependencies: dependencies,\n                      path: path,\n                      exclude: exclude,\n                      sources: sources,\n                      publicHeadersPath: nil,\n                      type: .macro,\n                      packageAccess: packageAccess,\n                      swiftSettings: swiftSettings,\n                      linkerSettings: linkerSettings,\n                      plugins: plugins)\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/BuildSettings.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\n\n/// The build configuration, such as debug or release.\npublic struct BuildConfiguration: Sendable {\n    /// The configuration of the build. Valid values are `debug` and `release`.\n    let config: String\n\n    private init(_ config: String) {\n        self.config = config\n    }\n\n    /// The debug build configuration.\n    public static let debug: BuildConfiguration = BuildConfiguration(\"debug\")\n\n    /// The release build configuration.\n    public static let release: BuildConfiguration = BuildConfiguration(\"release\")\n}\n\n/// A condition that limits the application of a build setting.\n///\n/// By default, build settings are applicable for all platforms and build\n/// configurations. Use the `.when` modifier to define a build setting for a\n/// specific condition. Invalid usage of `.when` emits an error during manifest\n/// parsing. For example, it's invalid to specify a `.when` condition with both\n/// parameters as `nil`.\n///\n/// The following example shows how to use build setting conditions with various\n/// APIs:\n///\n/// ```swift\n/// ...\n/// .target(\n///     name: \"MyTool\",\n///     dependencies: [\"Utility\"],\n///     cSettings: [\n///         .headerSearchPath(\"path/relative/to/my/target\"),\n///         .define(\"DISABLE_SOMETHING\", .when(platforms: [.iOS], configuration: .release)),\n///     ],\n///     swiftSettings: [\n///         .define(\"ENABLE_SOMETHING\", .when(configuration: .release)),\n///     ],\n///     linkerSettings: [\n///         .linkLibrary(\"openssl\", .when(platforms: [.linux])),\n///     ]\n/// ),\n/// ```\npublic struct BuildSettingCondition: Sendable {\n    /// The applicable platforms for this build setting condition.\n    let platforms: [Platform]?\n    /// The applicable build configuration for this build setting condition.\n    let config: BuildConfiguration?\n    /// The applicable traits for this build setting condition.\n    let traits: Set<String>?\n\n    private init(platforms: [Platform]?, config: BuildConfiguration?, traits: Set<String>?) {\n        self.platforms = platforms\n        self.config = config\n        self.traits = traits\n    }\n\n    @available(_PackageDescription, deprecated: 5.7)\n    public static func when(\n        platforms: [Platform]? = nil,\n        configuration: BuildConfiguration? = nil\n    ) -> BuildSettingCondition {\n        precondition(!(platforms == nil && configuration == nil))\n        return BuildSettingCondition(platforms: platforms, config: configuration, traits: nil)\n    }\n\n    /// Creates a build setting condition.\n    ///\n    /// - Parameters:\n    ///   - platforms: The applicable platforms for this build setting condition.\n    ///   - configuration: The applicable build configuration for this build setting condition.\n    ///   - traits: The applicable traits for this build setting condition.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func when(\n        platforms: [Platform]? = nil,\n        configuration: BuildConfiguration? = nil,\n        traits: Set<String>? = nil\n    ) -> BuildSettingCondition {\n        precondition(!(platforms == nil && configuration == nil && traits == nil))\n        return BuildSettingCondition(platforms: platforms, config: configuration, traits: traits)\n    }\n\n    /// Creates a build setting condition.\n    ///\n    /// - Parameters:\n    ///   - platforms: The applicable platforms for this build setting condition.\n    ///   - configuration: The applicable build configuration for this build setting condition.\n    @available(_PackageDescription, introduced: 5.7)\n    public static func when(platforms: [Platform], configuration: BuildConfiguration) -> BuildSettingCondition {\n        BuildSettingCondition(platforms: platforms, config: configuration, traits: nil)\n    }\n\n    /// Creates a build setting condition.\n    ///\n    /// - Parameter platforms: The applicable platforms for this build setting condition.\n    @available(_PackageDescription, introduced: 5.7)\n    public static func when(platforms: [Platform]) -> BuildSettingCondition {\n        BuildSettingCondition(platforms: platforms, config: .none, traits: nil)\n    }\n\n    /// Creates a build setting condition.\n    ///\n    /// - Parameter configuration: The applicable build configuration for this build setting condition.\n    @available(_PackageDescription, introduced: 5.7)\n    public static func when(configuration: BuildConfiguration) -> BuildSettingCondition {\n        BuildSettingCondition(platforms: .none, config: configuration, traits: nil)\n    }\n}\n\n/// The underlying build setting data.\nstruct BuildSettingData {\n\n    /// The name of the build setting.\n    let name: String\n\n    /// The value of the build setting.\n    let value: [String]\n\n    /// A condition that restricts the application of the build setting.\n    let condition: BuildSettingCondition?\n}\n\n/// A C language build setting.\npublic struct CSetting: Sendable {\n    /// The abstract build setting data.\n    let data: BuildSettingData\n\n    private init(name: String, value: [String], condition: BuildSettingCondition?) {\n        self.data = BuildSettingData(name: name, value: value, condition: condition)\n    }\n\n    /// Provides a header search path relative to the target's directory.\n    ///\n    /// Use this setting to add a search path for headers within your target.\n    /// You can't use absolute paths and you can't use this setting to provide\n    /// headers that are visible to other targets.\n    ///\n    /// The path must be a directory inside the package.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - path: The path of the directory that contains the headers. The path is relative to the target's directory.\n    ///   - condition: A condition that restricts the use of the build setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func headerSearchPath(_ path: String, _ condition: BuildSettingCondition? = nil) -> CSetting {\n        return CSetting(name: \"headerSearchPath\", value: [path], condition: condition)\n    }\n\n    /// Defines a value for a macro.\n    ///\n    /// If you don't specify a value, the macro's default value is 1.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the macro.\n    ///   - value: The value of the macro.\n    ///   - condition: A condition that restricts the use of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func define(_ name: String, to value: String? = nil, _ condition: BuildSettingCondition? = nil) -> CSetting {\n        var settingValue = name\n        if let value {\n            settingValue += \"=\" + value\n        }\n        return CSetting(name: \"define\", value: [settingValue], condition: condition)\n    }\n\n    /// Sets unsafe flags to pass arbitrary command-line flags to the\n    /// corresponding build tool.\n    ///\n    /// As the usage of the word “unsafe” implies, Swift Package Manager can't safely determine\n    /// if the build flags have any negative side effect on the build since\n    /// certain flags can change the behavior of how it performs a build.\n    ///\n    /// As some build flags can be exploited for unsupported or malicious\n    /// behavior, the use of unsafe flags makes the products containing this\n    /// target ineligible for use by other packages.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - flags: The unsafe flags to set.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func unsafeFlags(_ flags: [String], _ condition: BuildSettingCondition? = nil) -> CSetting {\n        return CSetting(name: \"unsafeFlags\", value: flags, condition: condition)\n    }\n    \n    /// Controls how all C compiler warnings are treated during compilation.\n    ///\n    /// Use this setting to specify whether all warnings should be treated as warnings (default behavior)\n    /// or as errors. This is equivalent to passing `-Werror` or `-Wno-error`\n    /// to the C compiler.\n    ///\n    /// This setting applies to all warnings emitted by the C compiler. To control specific\n    /// warnings individually, use `treatWarning(name:as:_:)` instead.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - level: The treatment level for all warnings (`.warning` or `.error`).\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func treatAllWarnings(\n      as level: WarningLevel,\n      _ condition: BuildSettingCondition? = nil\n    ) -> CSetting {\n        return CSetting(\n            name: \"treatAllWarnings\", value: [level.rawValue], condition: condition)\n    }\n\n    /// Controls how a specific C compiler warning is treated during compilation.\n    ///\n    /// Use this setting to specify whether a particular warning should be treated as a warning\n    /// (default behavior) or as an error. This is equivalent to passing `-Werror=` or `-Wno-error=`\n    /// followed by the warning name to the C compiler.\n    ///\n    /// This setting allows for fine-grained control over individual warnings. To control all\n    /// warnings at once, use `treatAllWarnings(as:_:)` instead.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the specific warning to control.\n    ///   - level: The treatment level for the warning (`.warning` or `.error`).\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func treatWarning(\n      _ name: String,\n      as level: WarningLevel,\n      _ condition: BuildSettingCondition? = nil\n    ) -> CSetting {\n        return CSetting(\n            name: \"treatWarning\", value: [name, level.rawValue], condition: condition)\n    }\n\n    /// Enable a specific C compiler warning group.\n    ///\n    /// Use this setting to enable a specific warning group. This is equivalent to passing\n    /// `-W` followed by the group name to the C compiler.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the warning group to enable.\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func enableWarning(\n      _ name: String,\n      _ condition: BuildSettingCondition? = nil\n    ) -> CSetting {\n        return CSetting(\n            name: \"enableWarning\", value: [name], condition: condition)\n    }\n\n    /// Disable a specific C compiler warning group.\n    ///\n    /// Use this setting to disable a specific warning group. This is equivalent to passing\n    /// `-Wno-` followed by the group name to the C compiler.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the warning group to disable.\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func disableWarning(\n      _ name: String,\n      _ condition: BuildSettingCondition? = nil\n    ) -> CSetting {\n        return CSetting(\n            name: \"disableWarning\", value: [name], condition: condition)\n    }\n}\n\n/// A CXX-language build setting.\npublic struct CXXSetting: Sendable {\n    /// The data store for the CXX build setting.\n    let data: BuildSettingData\n\n    private init(name: String, value: [String], condition: BuildSettingCondition?) {\n        self.data = BuildSettingData(name: name, value: value, condition: condition)\n    }\n\n    /// Provides a header search path relative to the target's directory.\n    ///\n    /// Use this setting to add a search path for headers within your target.\n    /// You can't use absolute paths and you can't use this setting to provide\n    /// headers that are visible to other targets.\n    ///\n    /// The path must be a directory inside the package.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - path: The path of the directory that contains the headers. The path is\n    ///   relative to the target's directory.\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func headerSearchPath(_ path: String, _ condition: BuildSettingCondition? = nil) -> CXXSetting {\n        return CXXSetting(name: \"headerSearchPath\", value: [path], condition: condition)\n    }\n\n    /// Defines a value for a macro.\n    ///\n    /// If you don't specify a value, the macro's default value is 1.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the macro.\n    ///   - value: The value of the macro.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func define(_ name: String, to value: String? = nil, _ condition: BuildSettingCondition? = nil) -> CXXSetting {\n        var settingValue = name\n        if let value {\n            settingValue += \"=\" + value\n        }\n        return CXXSetting(name: \"define\", value: [settingValue], condition: condition)\n    }\n\n    /// Sets unsafe flags to pass arbitrary command-line flags to the\n    /// corresponding build tool.\n    ///\n    /// As the usage of the word “unsafe” implies, Swift Package Manager can't safely determine\n    /// if the build flags have any negative side effect on the build since\n    /// certain flags can change the behavior of how it performs a build.\n    ///\n    /// As some build flags can be exploited for unsupported or malicious\n    /// behavior, you can't use products with unsafe build flags as dependencies in another package.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - flags: The unsafe flags to set.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func unsafeFlags(_ flags: [String], _ condition: BuildSettingCondition? = nil) -> CXXSetting {\n        return CXXSetting(name: \"unsafeFlags\", value: flags, condition: condition)\n    }\n    \n    /// Controls how all C++ compiler warnings are treated during compilation.\n    ///\n    /// Use this setting to specify whether all warnings should be treated as warnings (default behavior)\n    /// or as errors. This is equivalent to passing `-Werror` or `-Wno-error`\n    /// to the C++ compiler.\n    ///\n    /// This setting applies to all warnings emitted by the C++ compiler. To control specific\n    /// warnings individually, use `treatWarning(name:as:_:)` instead.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - level: The treatment level for all warnings (`.warning` or `.error`).\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func treatAllWarnings(\n      as level: WarningLevel,\n      _ condition: BuildSettingCondition? = nil\n    ) -> CXXSetting {\n        return CXXSetting(\n            name: \"treatAllWarnings\", value: [level.rawValue], condition: condition)\n    }\n\n    /// Controls how a specific C++ compiler warning is treated during compilation.\n    ///\n    /// Use this setting to specify whether a particular warning should be treated as a warning\n    /// (default behavior) or as an error. This is equivalent to passing `-Werror=` or `-Wno-error=`\n    /// followed by the warning name to the C++ compiler.\n    ///\n    /// This setting allows for fine-grained control over individual warnings. To control all\n    /// warnings at once, use `treatAllWarnings(as:_:)` instead.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the specific warning to control.\n    ///   - level: The treatment level for the warning (`.warning` or `.error`).\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func treatWarning(\n      _ name: String,\n      as level: WarningLevel,\n      _ condition: BuildSettingCondition? = nil\n    ) -> CXXSetting {\n        return CXXSetting(\n            name: \"treatWarning\", value: [name, level.rawValue], condition: condition)\n    }\n\n    /// Enable a specific C++ compiler warning group.\n    ///\n    /// Use this setting to enable a specific warning group. This is equivalent to passing\n    /// `-W` followed by the group name to the C++ compiler.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the warning group to enable.\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func enableWarning(\n      _ name: String,\n      _ condition: BuildSettingCondition? = nil\n    ) -> CXXSetting {\n        return CXXSetting(\n            name: \"enableWarning\", value: [name], condition: condition)\n    }\n\n    /// Disable a specific C++ compiler warning group.\n    ///\n    /// Use this setting to disable a specific warning group. This is equivalent to passing\n    /// `-Wno-` followed by the group name to the C++ compiler.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the warning group to disable.\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func disableWarning(\n      _ name: String,\n      _ condition: BuildSettingCondition? = nil\n    ) -> CXXSetting {\n        return CXXSetting(\n            name: \"disableWarning\", value: [name], condition: condition)\n    }\n}\n\n/// A Swift language build setting.\npublic struct SwiftSetting: Sendable {\n    /// The data store for the Swift build setting.\n    let data: BuildSettingData\n\n    private init(name: String, value: [String], condition: BuildSettingCondition?) {\n        self.data = BuildSettingData(name: name, value: value, condition: condition)\n    }\n\n    /// Defines a compilation condition.\n    ///\n    /// Use compilation conditions to only compile statements if a certain\n    /// condition is true. For example, the Swift compiler will only compile the\n    /// statements inside the `#if` block when `ENABLE_SOMETHING` is defined:\n    ///\n    /// ```swift\n    /// #if ENABLE_SOMETHING\n    ///    ...\n    /// #endif\n    /// ```\n    ///\n    /// Unlike macros in C/C++, compilation conditions don't have an associated\n    /// value.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the macro.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func define(_ name: String, _ condition: BuildSettingCondition? = nil) -> SwiftSetting {\n        return SwiftSetting(name: \"define\", value: [name], condition: condition)\n    }\n\n    /// Set unsafe flags to pass arbitrary command-line flags to the\n    /// corresponding build tool.\n    ///\n    /// As the usage of the word “unsafe” implies, Swift Package Manager can't safely determine\n    /// if the build flags have any negative side effect on the build since\n    /// certain flags can change the behavior of how it performs a build.\n    ///\n    /// As some build flags can be exploited for unsupported or malicious\n    /// behavior, the use of unsafe flags makes the products containing this\n    /// target ineligible for use by other packages.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - flags: The unsafe flags to set.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func unsafeFlags(_ flags: [String], _ condition: BuildSettingCondition? = nil) -> SwiftSetting {\n        return SwiftSetting(name: \"unsafeFlags\", value: flags, condition: condition)\n    }\n\n    /// Enable an upcoming feature with the given name.\n    ///\n    /// An upcoming feature is one that is available in Swift as of a\n    /// certain language version, but isn't available by default in prior\n    /// language modes because it has some impact on source compatibility.\n    ///\n    /// You can add and use multiple upcoming features in a given target\n    /// without affecting its dependencies. Targets will ignore any unknown\n    /// upcoming features.\n    ///\n    /// - Since: First available in PackageDescription 5.8.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the upcoming feature; for example, `ConciseMagicFile`.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.8)\n    public static func enableUpcomingFeature(\n        _ name: String,\n        _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        return SwiftSetting(\n            name: \"enableUpcomingFeature\", value: [name], condition: condition)\n    }\n\n    /// Enable an experimental feature with the given name.\n    ///\n    /// An experimental feature is one that's in development, but\n    /// is not yet available in Swift as a language feature.\n    ///\n    /// You can add and use multiple experimental features in a given target\n    /// without affecting its dependencies. Targets will ignore any  unknown\n    /// experimental features.\n    ///\n    /// - Since: First available in PackageDescription 5.8.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the experimental feature; for example, `VariadicGenerics`.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.8)\n    public static func enableExperimentalFeature(\n        _ name: String,\n        _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        return SwiftSetting(\n            name: \"enableExperimentalFeature\", value: [name], condition: condition)\n    }\n\n    /// Enable strict memory safety checking.\n    ///\n    /// Strict memory safety checking is an opt-in compiler feature that\n    /// identifies any uses of language constructs or APIs that break\n    /// memory safety. Issues are reported as warnings and can generally\n    /// be suppressed by adding annotations (such as `@unsafe` and `unsafe`)\n    /// that acknowledge the presence of unsafe code, making it easier to\n    /// review and audit at a later time.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func strictMemorySafety(\n      _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        return SwiftSetting(\n            name: \"strictMemorySafety\", value: [\"ON\"], condition: condition)\n    }\n\n    /// The interoperability mode\n    public enum InteroperabilityMode: String {\n        /// Emit code compatible with being imported from C and Objective-C.\n        case C\n        /// Emit code compatible with being imported from C++ and Objective-C++.\n        case Cxx\n    }\n\n    /// Enables Swift interoperability with a given language.\n    ///\n    /// This is useful for enabling interoperability between Swift and C++ for\n    /// a given target.\n    ///\n    /// Enabling C++ interoperability mode might alter the way some existing\n    /// C and Objective-C APIs are imported.\n    ///\n    /// - Since: First available in PackageDescription 5.9.\n    ///\n    /// - Parameters:\n    ///   - mode: The interoperability mode, either C-compatible or C++-compatible.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.9)\n    public static func interoperabilityMode(\n      _ mode: InteroperabilityMode,\n      _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        return SwiftSetting(\n          name: \"interoperabilityMode\", value: [mode.rawValue], condition: condition)\n    }\n\n    /// Defines a `-swift-version` to pass  to the\n    /// corresponding build tool.\n    ///\n    /// - Since: First available in PackageDescription 6.0.\n    ///\n    /// - Parameters:\n    ///   - version: The Swift language version to use.\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.0, deprecated: 6.0, renamed: \"swiftLanguageMode(_:_:)\")\n    public static func swiftLanguageVersion(\n      _ version: SwiftVersion,\n      _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        return SwiftSetting(\n            name: \"swiftLanguageMode\", value: [.init(describing: version)], condition: condition)\n    }\n\n    /// Defines a `-language-mode` to pass  to the\n    /// corresponding build tool.\n    ///\n    /// - Since: First available in PackageDescription 6.0.\n    ///\n    /// - Parameters:\n    ///   - mode: The Swift language mode to use.\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.0)\n    public static func swiftLanguageMode(\n      _ mode: SwiftLanguageMode,\n      _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        return SwiftSetting(\n            name: \"swiftLanguageMode\", value: [.init(describing: mode)], condition: condition)\n    }\n\n    /// Controls how all Swift compiler warnings are treated during compilation.\n    ///\n    /// Use this setting to specify whether all warnings should be treated as warnings (default behavior)\n    /// or as errors. This is equivalent to passing `-warnings-as-errors` or `-no-warnings-as-errors`\n    /// to the Swift compiler.\n    ///\n    /// This setting applies to all warnings emitted by the Swift compiler. To control specific\n    /// warnings individually, use `treatWarning(name:as:_:)` instead.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - level: The treatment level for all warnings (`.warning` or `.error`).\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func treatAllWarnings(\n      as level: WarningLevel,\n      _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        return SwiftSetting(\n            name: \"treatAllWarnings\", value: [level.rawValue], condition: condition)\n    }\n\n    /// Controls how a specific Swift compiler warning is treated during compilation.\n    ///\n    /// Use this setting to specify whether a particular warning should be treated as a warning\n    /// (default behavior) or as an error. This is equivalent to passing `-Werror` or `-Wwarning`\n    /// followed by the warning name to the Swift compiler.\n    ///\n    /// This setting allows for fine-grained control over individual warnings. To control all\n    /// warnings at once, use `treatAllWarnings(as:_:)` instead.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the specific warning to control.\n    ///   - level: The treatment level for the warning (`.warning` or `.error`).\n    ///   - condition: A condition that restricts the application of the build setting.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func treatWarning(\n      _ name: String,\n      as level: WarningLevel,\n      _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        return SwiftSetting(\n            name: \"treatWarning\", value: [name, level.rawValue], condition: condition)\n    }\n\n    /// Set the default isolation to the given global actor type.\n    ///\n    /// - Since: First available in PackageDescription 6.2.\n    ///\n    /// - Parameters:\n    ///   - isolation: The type of global actor to use for default actor isolation\n    ///     inference. The only valid arguments are `MainActor.self` and `nil`.\n    ///   - condition: A condition that restricts the application of the build\n    ///     setting.\n    ///\n    /// The compiler defaults to inferring unannotated code as `nonisolated` if unspecified,\n    /// or if the `isolation` parameter is set to `nil`.\n    @available(_PackageDescription, introduced: 6.2)\n    public static func defaultIsolation(\n        _ isolation: MainActor.Type?,\n        _ condition: BuildSettingCondition? = nil\n    ) -> SwiftSetting {\n        let isolationString =\n            if isolation == nil {\n                \"nonisolated\"\n            } else {\n                \"MainActor\"\n            }\n        return SwiftSetting(\n            name: \"defaultIsolation\", value: [isolationString], condition: condition)\n    }\n}\n\n/// A linker build setting.\npublic struct LinkerSetting: Sendable {\n    /// The data store for the Linker setting.\n    let data: BuildSettingData\n\n    private init(name: String, value: [String], condition: BuildSettingCondition?) {\n        self.data = BuildSettingData(name: name, value: value, condition: condition)\n    }\n\n    /// Declares linkage to a system library.\n    ///\n    /// This setting is most useful when the library can't be linked\n    /// automatically, such as C++ based libraries and non-modular libraries.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - library: The library name.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func linkedLibrary(_ library: String, _ condition: BuildSettingCondition? = nil) -> LinkerSetting {\n        return LinkerSetting(name: \"linkedLibrary\", value: [library], condition: condition)\n    }\n\n    /// Declares linkage to a system framework.\n    ///\n    /// This setting is most useful when the framework can't be linked\n    /// automatically, such as C++ based frameworks and non-modular frameworks.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - framework: The framework name.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func linkedFramework(_ framework: String, _ condition: BuildSettingCondition? = nil) -> LinkerSetting {\n        return LinkerSetting(name: \"linkedFramework\", value: [framework], condition: condition)\n    }\n   \n    /// Sets unsafe flags to pass arbitrary command-line flags to the\n    /// corresponding build tool.\n    ///\n    /// As the usage of the word “unsafe” implies, Swift Package Manager can't safely determine\n    /// if the build flags have any negative side effect on the build since\n    /// certain flags can change the behavior of how it performs a build.\n    ///\n    /// As some build flags can be exploited for unsupported or malicious\n    /// behavior, the use of unsafe flags makes the products containing this\n    /// target ineligible for use by other packages.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameters:\n    ///   - flags: The unsafe flags to set.\n    ///   - condition: A condition that restricts the application of the build\n    /// setting.\n    @available(_PackageDescription, introduced: 5.0)\n    public static func unsafeFlags(_ flags: [String], _ condition: BuildSettingCondition? = nil) -> LinkerSetting {\n        return LinkerSetting(name: \"unsafeFlags\", value: flags, condition: condition)\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackageDescription\n  BuildSettings.swift\n  Context.swift\n  ContextModel.swift\n  LanguageStandardSettings.swift\n  PackageDescription.swift\n  PackageDescriptionSerialization.swift\n  PackageDescriptionSerializationConversion.swift\n  PackageDependency.swift\n  PackageDependencyTrait.swift\n  PackageRequirement.swift\n  Product.swift\n  Resource.swift\n  SupportedPlatforms.swift\n  Target.swift\n  Trait.swift\n  Version.swift\n  Version+StringLiteralConvertible.swift\n  WarningLevel.swift)\n\nset_target_properties(PackageDescription PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_BINARY_DIR})\ntarget_compile_definitions(PackageDescription PRIVATE\n  USE_IMPL_ONLY_IMPORTS)\n\nif(APPLE)\n  target_link_options(PackageDescription PRIVATE\n    \"SHELL:-Xlinker -install_name -Xlinker @rpath/libPackageDescription.dylib\")\nelse()\n  target_link_libraries(PackageDescription PRIVATE\n    Foundation)\nendif()\n\ninstall(TARGETS PackageDescription\n    DESTINATION ${CMAKE_INSTALL_LIBDIR}/swift/pm/ManifestAPI)\n\nset(SwiftPMRuntime_INSTALL_SWIFTMODULEDIR\n  ${CMAKE_INSTALL_LIBDIR}/swift/pm/ManifestAPI)\nemit_swift_interface(PackageDescription)\ninstall_swift_interface(PackageDescription)\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/Context.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The context information for a Swift package.\n///\n/// The context encapsulates states that are known when Swift Package Manager interprets the package manifest,\n/// for example the location in the file system where the current package resides.\n@available(_PackageDescription, introduced: 5.6)\npublic struct Context: Sendable {\n    private static let model = try! ContextModel.decode()\n\n    /// The directory that contains `Package.swift`.\n    public static var packageDirectory : String {\n        model.packageDirectory\n    }\n\n    /// Information about the git status of a given package, if available.\n    @available(_PackageDescription, introduced: 6.0)\n    public static var gitInformation: GitInformation? {\n        model.gitInformation.map {\n            GitInformation(\n                currentTag: $0.currentTag,\n                currentCommit: $0.currentCommit,\n                hasUncommittedChanges: $0.hasUncommittedChanges\n            )\n        }\n    }\n\n    /// Snapshot of the system environment variables.\n    public static var environment : [String : String] {\n        model.environment\n    }\n    \n    private init() {\n    }\n}\n\n/// Information about the git status of a given package, if available.\n@available(_PackageDescription, introduced: 6.0)\npublic struct GitInformation: Sendable {\n    /// The version tag currently checked out, if available.\n    public let currentTag: String?\n    /// The commit currently checked out.\n    public let currentCommit: String\n    /// Whether or not there are uncommitted changes in the current repository.\n    public let hasUncommittedChanges: Bool\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/LanguageStandardSettings.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2017-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The supported C language standard you use to compile C sources in the\n/// package.\npublic enum CLanguageStandard: String {\n\n    /// The identifier for the ISO C 1989 language standard.\n    case c89\n\n    /// The identifier for the ISO C 1990 language standard.\n    case c90\n\n    /// The identifier for the ISO C 1999 language standard.\n    case c99\n\n    /// The identifier for the ISO C 2011 language standard.\n    case c11\n\n    /// The identifier for the ISO C 2017 language stadard.\n    @available(_PackageDescription, introduced: 5.4)\n    case c17\n\n    /// The identifier for the ISO C 2017 language standard.\n    @available(_PackageDescription, introduced: 5.4)\n    case c18\n\n    /// The identifier for the ISO C2x draft language standard.\n    @available(_PackageDescription, introduced: 5.4)\n    case c2x\n\n    /// The identifier for the ISO C 1990 language standard with GNU extensions.\n    case gnu89\n\n    /// The identifier for the ISO C 1990 language standard with GNU extensions.\n    case gnu90\n\n    /// The identifier for the ISO C 1999 language standard with GNU extensions.\n    case gnu99\n\n    /// The identifier for the ISO C 2011 language standard with GNU extensions.\n    case gnu11\n\n    /// The identifier for the ISO C 2017 language standard with GNU extensions.\n    @available(_PackageDescription, introduced: 5.4)\n    case gnu17\n\n    /// The identifier for the ISO C 2017 language standard with GNU extensions.\n    @available(_PackageDescription, introduced: 5.4)\n    case gnu18\n\n    /// The identifier for the ISO C2x draft language standard with GNU extensions.\n    @available(_PackageDescription, introduced: 5.4)\n    case gnu2x\n\n    /// The identifier for the ISO C 1990 language standard.\n    case iso9899_1990 = \"iso9899:1990\"\n\n    /// The identifier for the ISO C 1990 language standard with amendment 1.\n    case iso9899_199409 = \"iso9899:199409\"\n\n    /// The identifier for the ISO C 1999 language standard.\n    case iso9899_1999 = \"iso9899:1999\"\n\n    /// The identifier for the ISO C 2011 language standard.\n    case iso9899_2011 = \"iso9899:2011\"\n\n    /// The identifier for the ISO C 2017 language standard.\n    @available(_PackageDescription, introduced: 5.4)\n    case iso9899_2017 = \"iso9899:2017\"\n\n    /// The identifier for the ISO C 2017 language standard.\n    @available(_PackageDescription, introduced: 5.4)\n    case iso9899_2018 = \"iso9899:2018\"\n}\n\n/// The supported C++ language standard you use to compile C++ sources in the\n/// package.\n///\n/// Aliases are available for some C++ language standards. For example,\n/// use `cxx98` or `cxx03` for the \"ISO C++ 1998 with amendments\" standard.\n/// To learn more, see [C++ Support in Clang](https://clang.llvm.org/cxx_status.html).\npublic enum CXXLanguageStandard: String {\n\n    /// The identifier for the ISO C++ 1998 language standard with amendments.\n    case cxx98 = \"c++98\"\n\n    /// The identifier for the ISO C++ 1998 language standard with amendments.\n    case cxx03 = \"c++03\"\n\n    /// The identifier for the ISO C++ 2011 language standard with amendments.\n    case cxx11 = \"c++11\"\n\n    /// The identifier for the ISO C++ 2014 language standard with amendments.\n    case cxx14 = \"c++14\"\n\n    /// The identifier for the ISO C++ 2017 language standard with amendments.\n    @available(_PackageDescription, introduced: 5.4)\n    case cxx17 = \"c++17\"\n\n    /// The identifier for the ISO C++ 2017 language standard with amendments.\n    @available(_PackageDescription, introduced: 4, deprecated: 5.4, renamed: \"cxx17\")\n    case cxx1z = \"c++1z\"\n\n    /// The identifier for the ISO C++ 2020 language standard.\n    @available(_PackageDescription, introduced: 5.4)\n    case cxx20 = \"c++20\"\n\n    /// The identifier for the ISO C++ 2023 draft language standard.\n    @available(_PackageDescription, introduced: 5.6)\n    case cxx2b = \"c++2b\"\n\n    /// The identifier for the ISO C++ 1998 language standard with amendments and GNU extensions.\n    case gnucxx98 = \"gnu++98\"\n\n    /// The identifier for the ISO C++ 1998 language standard with amendments and GNU extensions.\n    case gnucxx03 = \"gnu++03\"\n\n    /// The identifier for the ISO C++ 2011 language standard with amendments and GNU extensions.\n    case gnucxx11 = \"gnu++11\"\n\n    /// The identifier for the ISO C++ 2014 language standard with amendments and GNU extensions.\n    case gnucxx14 = \"gnu++14\"\n\n    /// The identifier for the ISO C++ 2017 language standard with amendments and GNU extensions.\n    @available(_PackageDescription, introduced: 5.4)\n    case gnucxx17 = \"gnu++17\"\n\n    /// The identifier for the ISO C++ 2017 language standard with amendments and GNU extensions.\n    @available(_PackageDescription, introduced: 4, deprecated: 5.4, renamed: \"gnucxx17\")\n    case gnucxx1z = \"gnu++1z\"\n\n    /// The identifier for the ISO C++ 2020 language standard with GNU extensions.\n    @available(_PackageDescription, introduced: 5.4)\n    case gnucxx20 = \"gnu++20\"\n\n    /// The identifier for the ISO C++ 2023 draft language standard with GNU extensions.\n    @available(_PackageDescription, introduced: 5.6)\n    case gnucxx2b = \"gnu++2b\"\n}\n\n/// The Swift language mode used to compile Swift sources in the package\npublic enum SwiftLanguageMode {\n    /// The identifier for the Swift 3 language version.\n    @available(_PackageDescription, introduced: 4, obsoleted: 5)\n    case v3\n\n    /// The identifier for the Swift 4 language version.\n    @available(_PackageDescription, introduced: 4)\n    case v4\n\n    /// The identifier for the Swift 4.2 language version.\n    @available(_PackageDescription, introduced: 4)\n    case v4_2\n\n    /// The identifier for the Swift 5 language version.\n    @available(_PackageDescription, introduced: 5)\n    case v5\n\n    /// The identifier for the Swift 6 language version.\n    @available(_PackageDescription, introduced: 6)\n    case v6\n\n    /// A user-defined value for the Swift version.\n    ///\n    /// The value is passed as-is to the Swift compiler's `-swift-version` flag.\n    case version(String)\n}\n\nextension SwiftLanguageMode: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .v3: \"3\"\n        case .v4: \"4\"\n        case .v4_2: \"4.2\"\n        case .v5: \"5\"\n        case .v6: \"6\"\n        case .version(let version): version\n        }\n    }\n}\n\n/// Type alias to previous name for backward source compatibility\n@available(_PackageDescription, deprecated: 6, renamed:\"SwiftLanguageMode\")\npublic typealias SwiftVersion = SwiftLanguageMode\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDependency.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import Foundation\n#else\nimport Foundation\n#endif\n\nextension Package {\n    /// A package dependency of a Swift package.\n    ///\n    /// A package dependency consists of a Git URL to the source of the package,\n    /// and a requirement for the version of the package.\n    ///\n    /// Swift Package Manager performs a process called _dependency resolution_ to determine\n    /// the exact version of the package dependencies that an app or other Swift\n    /// package can use. The `Package.resolved` file records the results of the\n    /// dependency resolution and lives in the top-level directory of a Swift\n    /// package. If you add the Swift package as a package dependency to an app\n    /// for an Apple platform, you can find the `Package.resolved` file inside\n    /// your `.xcodeproj` or `.xcworkspace`.\n    public class Dependency {\n        /// The type of dependency.\n        @available(_PackageDescription, introduced: 5.6)\n        public enum Kind {\n            /// A dependency located at the given path.\n            /// - Parameters:\n            ///    - name: The name of the dependency.\n            ///    - path: The path to the dependency.\n            case fileSystem(name: String?, path: String)\n            /// A dependency based on a source control requirement.\n            ///  - Parameters:\n            ///    - name: The name of the dependency.\n            ///    - location: The Git URL of the dependency.\n            ///    - requirement: The version-based requirement for a package.\n            case sourceControl(name: String?, location: String, requirement: SourceControlRequirement)\n            /// A dependency based on a registry requirement.\n            /// - Parameters:\n            ///   - id: The package identifier of the dependency.\n            ///   - requirement: The version based requirement for a package.\n            case registry(id: String, requirement: RegistryRequirement)\n        }\n\n        /// A description of the package dependency.\n        @available(_PackageDescription, introduced: 5.6)\n        public let kind: Kind\n\n        /// The dependencies traits configuration.\n        @available(_PackageDescription, introduced: 6.1)\n        public let traits: Set<Trait>\n\n        /// The name of the dependency.\n        ///\n        /// If the `name` is `nil`, Swift Package Manager deduces the dependency's name from its\n        /// package identity or Git URL.\n        @available(_PackageDescription, deprecated: 5.6, message: \"use kind instead\")\n        public var name: String? {\n            get {\n                switch self.kind {\n                case .fileSystem(name: let name, path: _):\n                    return name\n                case .sourceControl(name: let name, location: _, requirement: _):\n                    return name\n                case .registry:\n                    return nil\n                }\n            }\n        }\n\n        /// The Git URL of the package dependency.\n        @available(_PackageDescription, deprecated: 5.6, message: \"use kind instead\")\n        public var url: String? {\n            get {\n                switch self.kind {\n                case .fileSystem(name: _, path: let path):\n                    return path\n                case .sourceControl(name: _, location: let location, requirement: _):\n                    return location\n                case .registry:\n                    return nil\n                }\n            }\n        }\n\n        /// Module aliases for targets in this dependency. The key is an original target name and\n        /// the value is a new unique name mapped to the name of the .swiftmodule binary.\n        internal var moduleAliases: [String: String]?\n\n        /// The dependency requirement of the package dependency.\n        @available(_PackageDescription, deprecated: 5.6, message: \"use kind instead\")\n        public var requirement: Requirement {\n            get {\n                switch self.kind {\n                case .fileSystem:\n                    return .localPackageItem\n                case .sourceControl(name: _, location: _, requirement: let requirement):\n                    switch requirement {\n                    case .branch(let branch):\n                        return .branchItem(branch)\n                    case .exact(let version):\n                        return .exactItem(version)\n                    case .range(let range):\n                        return .rangeItem(range)\n                    case .revision(let revision):\n                        return .revisionItem(revision)\n                    }\n                case .registry(id: _, requirement: let requirement):\n                    switch requirement {\n                    case .exact(let version):\n                        return .exactItem(version)\n                    case .range(let range):\n                        return .rangeItem(range)\n                    }\n                }\n            }\n        }\n\n        /// Initializes and returns a newly allocated requirement with the specified url and requirements.\n        @available(_PackageDescription, deprecated: 5.6)\n        convenience init(\n            name: String?,\n            url: String,\n            requirement: Requirement,\n            traits: Set<Trait>?\n        ) {\n            switch requirement {\n            case .localPackageItem:\n                self.init(name: name, path: url, traits: traits)\n            case .branchItem(let branch):\n                self.init(name: name, location: url, requirement: .branch(branch), traits: traits)\n            case .exactItem(let version):\n                self.init(name: name, location: url, requirement: .exact(version), traits: traits)\n            case .revisionItem(let revision):\n                self.init(name: name, location: url, requirement: .revision(revision), traits: traits)\n            case .rangeItem(let range):\n                self.init(name: name, location: url, requirement: .range(range), traits: traits)\n            }\n        }\n\n        init(kind: Kind, traits: Set<Trait>?) {\n            self.kind = kind\n            self.traits = traits ?? [.defaults]\n        }\n\n        convenience init(\n            name: String?,\n            path: String,\n            traits: Set<Trait>?\n        ) {\n            self.init(\n                kind: .fileSystem(\n                    name: name,\n                    path: path\n                ),\n                traits: traits\n            )\n        }\n\n        convenience init(\n            name: String?,\n            location: String,\n            requirement: SourceControlRequirement,\n            traits: Set<Trait>?\n        ) {\n            self.init(\n                kind: .sourceControl(\n                    name: name,\n                    location: location,\n                    requirement: requirement\n                ),\n                traits: traits\n            )\n        }\n\n        convenience init(\n            id: String,\n            requirement: RegistryRequirement,\n            traits: Set<Trait>?\n        ) {\n            self.init(\n                kind: .registry(\n                    id: id,\n                    requirement: requirement\n                ),\n                traits: traits\n            )\n        }\n    }\n}\n\n// MARK: - file system\n\nextension Package.Dependency {\n    /// Adds a local dependency to a package located at the path you provide.\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// The Swift Package Manager uses the package dependency as-is\n    /// and does not perform any source control access. Local package dependencies\n    /// are especially useful during development of a new package or when working\n    /// on multiple tightly coupled packages.\n    ///\n    /// - Parameter path: The file system path to the package.\n    ///\n    /// - Returns: A package dependency.\n    public static func package(\n        path: String\n    ) -> Package.Dependency {\n        return .init(name: nil, path: path, traits: nil)\n    }\n\n    /// Adds a local dependency to a package located at the path and with an optional set of traits you provide.\n    ///\n    /// The Swift Package Manager uses the package dependency as-is\n    /// and does not perform any source control access. Local package dependencies\n    /// are especially useful during development of a new package or when working\n    /// on multiple tightly coupled packages.\n    ///\n    /// - Parameter path: The file system path to the package.\n    /// - Parameter traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A package dependency.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        path: String,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .init(name: nil, path: path, traits: traits)\n    }\n\n    /// Adds a local dependency to a named package located at the path you provide.\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// Swift Package Manager uses the package dependency as-is and doesn't perform any source\n    /// control access. Local package dependencies are especially useful during\n    /// development of a new package or when working on multiple tightly coupled\n    /// packages.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package.\n    ///   - path: The file system path to the package.\n    ///\n    /// - Returns: A package dependency.\n    @available(_PackageDescription, introduced: 5.2)\n    public static func package(\n        name: String,\n        path: String\n    ) -> Package.Dependency {\n        return .init(name: name, path: path, traits: nil)\n    }\n\n    /// Adds a local dependency to a named package located at the path and with an optional set of traits you provide.\n    ///\n    /// Swift Package Manager uses the package dependency as-is and doesn't perform any source\n    /// control access. Local package dependencies are especially useful during\n    /// development of a new package or when working on multiple tightly coupled\n    /// packages.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package.\n    ///   - path: The file system path to the package.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A package dependency.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        name: String,\n        path: String,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .init(name: name, path: path, traits: traits)\n    }\n}\n\n// MARK: - source control\n\nextension Package.Dependency {\n    /// Adds a remote package dependency with a version requirement, starting with the given minimum version,\n    /// going up to the next major version.\n    ///\n    /// This is the recommended way to specify a remote package dependency.\n    /// It allows you to specify the minimum version you require, allows updates that include bug fixes\n    /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency.\n    /// This approach provides the maximum flexibility on which version to use,\n    /// while making sure you don't update to a version with breaking changes,\n    /// and helps to prevent conflicts in your dependency graph.\n    ///\n    /// The following example allows the Swift Package Manager to select a version\n    /// like a  `1.2.3`, `1.2.4`, or `1.3.0`, but not `2.0.0`.\n    ///\n    ///```swift\n    ///.package(url: \"https://example.com/example-package.git\", from: \"1.2.3\"),\n    ///```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///    - url: The valid Git URL of the package.\n    ///    - version: The minimum version requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    public static func package(\n        url: String,\n        from version: Version\n    ) -> Package.Dependency {\n        return .package(url: url, .upToNextMajor(from: version))\n    }\n\n    /// Adds a remote package dependency with a version requirement, starting with the given minimum version,\n    /// going up to the next major version.\n    ///\n    /// This is the recommended way to specify a remote package dependency.\n    /// It allows you to specify the minimum version you require, allows updates that include bug fixes\n    /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency.\n    /// This approach provides the maximum flexibility on which version to use,\n    /// while making sure you don't update to a version with breaking changes,\n    /// and helps to prevent conflicts in your dependency graph.\n    ///\n    /// The following example allows the Swift Package Manager to select a version\n    /// like a  `1.2.3`, `1.2.4`, or `1.3.0`, but not `2.0.0`.\n    ///\n    ///```swift\n    ///.package(url: \"https://example.com/example-package.git\", from: \"1.2.3\"),\n    ///```\n    ///\n    /// - Parameters:\n    ///    - url: The valid Git URL of the package.\n    ///    - version: The minimum version requirement.\n    ///    - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        url: String,\n        from version: Version,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(url: url, .upToNextMajor(from: version), traits: traits)\n    }\n\n    /// Adds a remote package dependency with a version requirement, starting\n    /// with the given minimum version, going up to the next major version.\n    ///\n    /// This is the recommended way to specify a remote package dependency. It\n    /// allows you to specify the minimum version you require, allows updates\n    /// that include bug fixes and backward-compatible feature updates, but\n    /// requires you to explicitly update to a new major version of the\n    /// dependency. This approach provides the maximum flexibility on which\n    /// version to use, while making sure you don't update to a version with\n    /// breaking changes, and helps to prevent conflicts in your dependency\n    /// graph.\n    ///\n    /// The following example allows the Swift package manager to select a\n    /// version like a `1.2.3`, `1.2.4`, or `1.3.0`, but not `2.0.0`.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", from:\n    /// \"1.2.3\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package or `nil` to deduce the name from  the package's Git URL.\n    ///   - url: The valid Git URL of the package.\n    ///   - version: The minimum version requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.2, deprecated: 5.6, message: \"use package(url:from:) instead\")\n    public static func package(\n        name: String,\n        url: String,\n        from version: Version\n    ) -> Package.Dependency {\n        return .package(name: name, url: url, .upToNextMajor(from: version))\n    }\n\n    /// Adds a remote package dependency with a branch requirement you provide.\n    ///\n    ///```swift\n    /// .package(url: \"https://example.com/example-package.git\", branch: \"main\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - branch: A dependency requirement. See static methods on ``Requirement-swift.enum`` for available options.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func package(\n        url: String,\n        branch: String\n    ) -> Package.Dependency {\n        return .package(url: url, requirement: .branch(branch))\n    }\n\n    /// Adds a remote package dependency with a branch requirement you provide.\n    ///\n    ///```swift\n    /// .package(url: \"https://example.com/example-package.git\", branch: \"main\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - branch: A dependency requirement. See static methods on ``Requirement-swift.enum`` for available options.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        url: String,\n        branch: String,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(url: url, requirement: .branch(branch), traits: traits)\n    }\n\n    /// Adds a remote package dependency with a branch requirement you provide.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", branch: \"main\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - name: The name of the package, or nil to deduce it from the URL.\n    ///   - url: The valid Git URL of the package.\n    ///   - branch: A dependency requirement. See static methods on ``Requirement-swift.enum`` for available options.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.5, deprecated: 5.6, message: \"use package(url:branch:) instead\")\n    public static func package(\n        name: String,\n        url: String,\n        branch: String\n    ) -> Package.Dependency {\n        return .package(name: name, url: url, requirement: .branch(branch))\n    }\n\n    /// Adds a remote package dependency with a specific revision requirement.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", revision: \"aa681bd6c61e22df0fd808044a886fc4a7ed3a65\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - revision: A dependency requirement. See static methods on ``Requirement-swift.enum`` for available options.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func package(\n        url: String,\n        revision: String\n    ) -> Package.Dependency {\n        return .package(url: url, requirement: .revision(revision))\n    }\n\n    /// Adds a remote package dependency with a specific revision requirement.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", revision: \"aa681bd6c61e22df0fd808044a886fc4a7ed3a65\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - revision: A dependency requirement. See static methods on ``Requirement-swift.enum`` for available options.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        url: String,\n        revision: String,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(url: url, requirement: .revision(revision), traits: traits)\n    }\n\n    /// Adds a remote package dependency with a specific revision requirement.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", revision: \"aa681bd6c61e22df0fd808044a886fc4a7ed3a65\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - name: The name of the package, or nil to deduce it from the URL.\n    ///   - url: The valid Git URL of the package.\n    ///   - revision: A dependency requirement. See static methods on ``Requirement-swift.enum`` for available options.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.5, deprecated: 5.6, message: \"use package(url:revision:) instead\")\n    public static func package(\n        name: String,\n        url: String,\n        revision: String\n    ) -> Package.Dependency {\n        return .package(name: name, url: url, requirement: .revision(revision))\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, up to\n    /// but not including a specified maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions `1.2.3`, `1.2.4`, `1.2.5`, but not `1.2.6`.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", \"1.2.3\"..<\"1.2.6\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - range: The custom version range requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    public static func package(\n        url: String,\n        _ range: Range<Version>\n    ) -> Package.Dependency {\n        return .package(name: nil, url: url, requirement: .range(range))\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, up to\n    /// but not including a specified maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions `1.2.3`, `1.2.4`, `1.2.5`, but not `1.2.6`.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", \"1.2.3\"..<\"1.2.6\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - range: The custom version range requirement.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        url: String,\n        _ range: Range<Version>,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(name: nil, url: url, requirement: .range(range), traits: traits)\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, up to\n    /// but not including a specified maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions `1.2.3`, `1.2.4`, `1.2.5`, but not `1.2.6`.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", \"1.2.3\"..<\"1.2.6\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the package, or `nil` to deduce it from the URL.\n    ///   - url: The valid Git URL of the package.\n    ///   - range: The custom version range requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.2, deprecated: 5.6, message: \"use package(url:_:) instead\")\n    public static func package(\n        name: String,\n        url: String,\n        _ range: Range<Version>\n    ) -> Package.Dependency {\n        return .package(name: name, url: url, requirement: .range(range))\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, going\n    /// up to and including a specific maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", \"1.2.3\"...\"1.2.6\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - range: The closed version range requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    public static func package(\n        url: String,\n        _ range: ClosedRange<Version>\n    ) -> Package.Dependency {\n        return .package(name: nil, url: url, closedRange: range)\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, going\n    /// up to and including a specific maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", \"1.2.3\"...\"1.2.6\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - range: The closed version range requirement.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        url: String,\n        _ range: ClosedRange<Version>,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(name: nil, url: url, closedRange: range, traits: traits)\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, going\n    /// up to and including a specific maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", \"1.2.3\"...\"1.2.6\"),\n    /// ```\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions between 1.0.0 and 2.0.0\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", .upToNextMajor(from: \"1.0.0\"),\n    /// ```\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions between 1.0.0 and 1.1.0\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", .upToNextMinor(from: \"1.0.0\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the package, or `nil` to deduce it from the URL.\n    ///   - url: The valid Git URL of the package.\n    ///   - range: The closed version range requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.2, deprecated: 5.6, message: \"use package(url:_:) instead\")\n    public static func package(\n        name: String,\n        url: String,\n        _ range: ClosedRange<Version>\n    ) -> Package.Dependency {\n        return .package(name: name, url: url, closedRange: range)\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, going\n    /// up to and including a specific maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", \"1.2.3\"...\"1.2.6\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the package, or `nil` to deduce it from the URL.\n    ///   - url: The valid Git URL of the package.\n    ///   - range: The closed version range requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    private static func package(\n        name: String?,\n        url: String,\n        closedRange: ClosedRange<Version>\n    ) -> Package.Dependency {\n        // Increase upperbound's patch version by one.\n        let upper = closedRange.upperBound\n        let upperBound = Version(\n            upper.major, upper.minor, upper.patch + 1,\n            prereleaseIdentifiers: upper.prereleaseIdentifiers,\n            buildMetadataIdentifiers: upper.buildMetadataIdentifiers)\n        return .package(name: name, url: url, requirement: .range(closedRange.lowerBound ..< upperBound))\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, going\n    /// up to and including a specific maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", \"1.2.3\"...\"1.2.6\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - name: The name of the package, or `nil` to deduce it from the URL.\n    ///   - url: The valid Git URL of the package.\n    ///   - range: The closed version range requirement.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    private static func package(\n        name: String?,\n        url: String,\n        closedRange: ClosedRange<Version>,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        // Increase upperbound's patch version by one.\n        let upper = closedRange.upperBound\n        let upperBound = Version(\n            upper.major, upper.minor, upper.patch + 1,\n            prereleaseIdentifiers: upper.prereleaseIdentifiers,\n            buildMetadataIdentifiers: upper.buildMetadataIdentifiers)\n        return .package(\n            name: name,\n            url: url,\n            requirement: .range(\n                closedRange.lowerBound ..< upperBound\n            ),\n            traits: traits\n        )\n    }\n\n    /// Adds a remote package dependency that uses an exact version requirement.\n    ///\n    /// Specifying exact version requirements are not recommended as\n    /// they can cause conflicts in your dependency graph when other packages depend on this package.\n    /// As Swift packages follow the semantic versioning convention,\n    /// think about specifying a version range instead.\n    ///\n    /// The following example instructs the Swift Package Manager to use version `1.2.3`.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", exact: \"1.2.3\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - version: The exact version of the dependency for this requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.6)\n    public static func package(\n        url: String,\n        exact version: Version\n    ) -> Package.Dependency {\n        return .package(url: url, requirement: .exact(version))\n    }\n\n    /// Adds a remote package dependency that uses an exact version requirement.\n    ///\n    /// Specifying exact version requirements are not recommended as\n    /// they can cause conflicts in your dependency graph when other packages depend on this package.\n    /// As Swift packages follow the semantic versioning convention,\n    /// think about specifying a version range instead.\n    ///\n    /// The following example instructs the Swift Package Manager to use version `1.2.3`.\n    ///\n    /// ```swift\n    /// .package(url: \"https://example.com/example-package.git\", exact: \"1.2.3\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - version: The exact version of the dependency for this requirement.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        url: String,\n        exact version: Version,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(url: url, requirement: .exact(version), traits: traits)\n    }\n\n    /// Adds a remote package dependency given a version requirement.\n    ///\n    /// - Parameters:\n    ///   - url: The valid Git URL of the package.\n    ///   - requirement: A dependency requirement. See static methods on `Package.Dependency.Requirement` for available options.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, deprecated: 5.6, message: \"use specific requirement APIs instead (e.g. use 'branch:' instead of '.branch')\")\n    public static func package(\n        url: String,\n        _ requirement: Package.Dependency.Requirement\n    ) -> Package.Dependency {\n        return .package(name: nil, url: url, requirement)\n    }\n\n    /// Adds a remote package dependency with a given version requirement.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package or `nil` to deduce the name from the package's Git URL.\n    ///   - url: The valid Git URL of the package.\n    ///   - requirement: A dependency requirement. See static methods on\n    ///     ``Package/Dependency/Requirement-swift.enum`` for available options.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.2, deprecated: 5.6, message: \"use specific requirement APIs instead (e.g. use 'branch:' instead of '.branch')\")\n    public static func package(\n        name: String?,\n        url: String,\n        _ requirement: Package.Dependency.Requirement\n    ) -> Package.Dependency {\n        precondition(!requirement.isLocalPackage, \"Use `.package(path:)` API to declare a local package dependency\")\n        return .init(name: name, url: url, requirement: requirement, traits: nil)\n    }\n\n    // intentionally private to hide enum detail\n    private static func package(\n        name: String? = nil,\n        url: String,\n        requirement: Package.Dependency.SourceControlRequirement\n    ) -> Package.Dependency {\n        return .init(name: name, location: url, requirement: requirement, traits: nil)\n    }\n\n    // intentionally private to hide enum detail\n    private static func package(\n        name: String? = nil,\n        url: String,\n        requirement: Package.Dependency.SourceControlRequirement,\n        traits: Set<Trait>?\n    ) -> Package.Dependency {\n        return .init(name: name, location: url, requirement: requirement, traits: traits)\n    }\n}\n\n// MARK: - registry\n\nextension Package.Dependency {\n    /// Adds a remote package dependency that uses the version requirement, starting with the given minimum version,\n    /// going up to the next major version.\n    ///\n    /// This is the recommended way to specify a remote package dependency.\n    /// It allows you to specify the minimum version you require, allows updates that include bug fixes\n    /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency.\n    /// This approach provides the maximum flexibility on which version to use,\n    /// while making sure you don't update to a version with breaking changes,\n    /// and helps to prevent conflicts in your dependency graph.\n    ///\n    /// The following example allows the Swift Package Manager to select a version\n    /// like a  `1.2.3`, `1.2.4`, or `1.3.0`, but not `2.0.0`.\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", from: \"1.2.3\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - id: The identity of the package.\n    ///   - version: The minimum version requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.7)\n    public static func package(\n        id: String,\n        from version: Version\n    ) -> Package.Dependency {\n        return .package(id: id, .upToNextMajor(from: version))\n    }\n\n    /// Adds a remote package dependency that uses the version requirement, starting with the given minimum version,\n    /// going up to the next major version.\n    ///\n    /// This is the recommended way to specify a remote package dependency.\n    /// It allows you to specify the minimum version you require, allows updates that include bug fixes\n    /// and backward-compatible feature updates, but requires you to explicitly update to a new major version of the dependency.\n    /// This approach provides the maximum flexibility on which version to use,\n    /// while making sure you don't update to a version with breaking changes,\n    /// and helps to prevent conflicts in your dependency graph.\n    ///\n    /// The following example allows the Swift Package Manager to select a version\n    /// like a  `1.2.3`, `1.2.4`, or `1.3.0`, but not `2.0.0`.\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", from: \"1.2.3\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - id: The identity of the package.\n    ///   - version: The minimum version requirement.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        id: String,\n        from version: Version,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(id: id, .upToNextMajor(from: version), traits: traits)\n    }\n\n    /// Adds a remote package dependency with an exact version requirement.\n    ///\n    /// Specifying exact version requirements are not recommended as\n    /// they can cause conflicts in your dependency graph when multiple other packages depend on a package.\n    /// Because Swift packages follow the semantic versioning convention,\n    /// think about specifying a version range instead.\n    ///\n    /// The following example instructs the Swift Package Manager to use version `1.2.3`.\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", exact: \"1.2.3\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - id: The identity of the package.\n    ///   - version: The exact version of the dependency for this requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.7)\n    public static func package(\n        id: String,\n        exact version: Version\n    ) -> Package.Dependency {\n        return .package(id: id, requirement: .exact(version), traits: nil)\n    }\n\n    /// Adds a remote package dependency with an exact version requirement.\n    ///\n    /// Specifying exact version requirements are not recommended as\n    /// they can cause conflicts in your dependency graph when multiple other packages depend on a package.\n    /// Because Swift packages follow the semantic versioning convention,\n    /// think about specifying a version range instead.\n    ///\n    /// The following example instructs the Swift Package Manager to use version `1.2.3`.\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", exact: \"1.2.3\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - id: The identity of the package.\n    ///   - version: The exact version of the dependency for this requirement.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        id: String,\n        exact version: Version,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(id: id, requirement: .exact(version), traits: traits)\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, up to\n    /// but not including a specified maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions `1.2.3`, `1.2.4`, `1.2.5`, but not `1.2.6`.\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", \"1.2.3\"..<\"1.2.6\"),\n    /// ```\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions between 1.0.0 and 2.0.0\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", .upToNextMajor(from: \"1.0.0\"),\n    /// ```\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions between 1.0.0 and 1.1.0\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", .upToNextMinor(from: \"1.0.0\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - id: The identity of the package.\n    ///   - range: The custom version range requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.7)\n    public static func package(\n        id: String,\n        _ range: Range<Version>\n    ) -> Package.Dependency {\n        return .package(id: id, requirement: .range(range), traits: nil)\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, up to\n    /// but not including a specified maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions `1.2.3`, `1.2.4`, `1.2.5`, but not `1.2.6`.\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", \"1.2.3\"..<\"1.2.6\"),\n    /// ```\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions between 1.0.0 and 2.0.0\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", .upToNextMajor(from: \"1.0.0\"),\n    /// ```\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions between 1.0.0 and 1.1.0\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", .upToNextMinor(from: \"1.0.0\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - id: The identity of the package.\n    ///   - range: The custom version range requirement.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        id: String,\n        _ range: Range<Version>,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        return .package(id: id, requirement: .range(range), traits: traits)\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, going\n    /// up to and including a specific maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6.\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", \"1.2.3\"...\"1.2.6\"),\n    /// ```\n    ///\n    /// If the package you depend on defines traits, the package manager uses the dependency with its default set of traits.\n    ///\n    /// - Parameters:\n    ///   - id: The identity of the package.\n    ///   - range: The closed version range requirement.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 5.7)\n    public static func package(\n        id: String,\n        _ range: ClosedRange<Version>\n    ) -> Package.Dependency {\n        // Increase upperbound's patch version by one.\n        let upper = range.upperBound\n        let upperBound = Version(\n            upper.major, upper.minor, upper.patch + 1,\n            prereleaseIdentifiers: upper.prereleaseIdentifiers,\n            buildMetadataIdentifiers: upper.buildMetadataIdentifiers)\n        return .package(id: id, range.lowerBound ..< upperBound)\n    }\n\n    /// Adds a remote package dependency starting with a specific minimum version, going\n    /// up to and including a specific maximum version.\n    ///\n    /// The following example allows the Swift Package Manager to pick\n    /// versions 1.2.3, 1.2.4, 1.2.5, as well as 1.2.6.\n    ///\n    /// ```swift\n    /// .package(id: \"scope.name\", \"1.2.3\"...\"1.2.6\"),\n    /// ```\n    ///\n    /// - Parameters:\n    ///   - id: The identity of the package.\n    ///   - range: The closed version range requirement.\n    ///   - traits: The trait configuration of this dependency. The default value enables the default traits of the package.\n    ///\n    /// - Returns: A `Package.Dependency` instance.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func package(\n        id: String,\n        _ range: ClosedRange<Version>,\n        traits: Set<Trait> = [.defaults]\n    ) -> Package.Dependency {\n        // Increase upperbound's patch version by one.\n        let upper = range.upperBound\n        let upperBound = Version(\n            upper.major, upper.minor, upper.patch + 1,\n            prereleaseIdentifiers: upper.prereleaseIdentifiers,\n            buildMetadataIdentifiers: upper.buildMetadataIdentifiers)\n        return .package(id: id, range.lowerBound ..< upperBound, traits: traits)\n    }\n\n    // intentionally private to hide enum detail\n    private static func package(\n        id: String,\n        requirement: Package.Dependency.RegistryRequirement,\n        traits: Set<Trait>?\n    ) -> Package.Dependency {\n        let pattern = #\"\\A[a-zA-Z\\d](?:[a-zA-Z\\d]|-(?=[a-zA-Z\\d])){0,38}\\.[a-zA-Z0-9](?:[a-zA-Z0-9]|[-_](?=[a-zA-Z0-9])){0,99}\\z\"#\n        if id.range(of: pattern, options: .regularExpression) == nil {\n            errors.append(\"Invalid package identifier: '\\(id)'\")\n        }\n\n        return .init(id: id, requirement: requirement, traits: traits)\n    }\n}\n\n// MARK: - common APIs used by mistake as unavailable to provide better error messages.\n\nextension Package.Dependency {\n    @available(*, unavailable, message: \"use package(url:exact:) instead\")\n    public static func package(url: String, version: Version) -> Package.Dependency {\n        fatalError(\"\\(#file):\\(#line) - Illegal call of deprecated function \\(#function)\")\n    }\n\n    @available(*, unavailable, message: \"use package(url:_:) instead\")\n    public static func package(url: String, range: Range<Version>) -> Package.Dependency {\n        fatalError(\"\\(#file):\\(#line) - Illegal call of deprecated function \\(#function)\")\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDependencyTrait.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension Package.Dependency {\n    /// An enabled trait of a dependency.\n    @available(_PackageDescription, introduced: 6.1)\n    public struct Trait: Hashable, Sendable, ExpressibleByStringLiteral {\n        /// Enables all default traits of the dependency.\n        public static let defaults = Self.init(name: \"default\")\n\n        /// A condition that limits the application of a trait for a dependency.\n        public struct Condition: Hashable, Sendable {\n            /// The set of traits that enable the dependencies trait.\n            let traits: Set<String>?\n\n            /// Creates a package dependency trait condition.\n            ///\n            /// If the depending package enables any of the traits you provide, the package manager enables the dependency to which this condition applies.\n            ///\n            /// - Parameter traits: The set of traits that enable the dependencies trait.\n            public static func when(\n                traits: Set<String>\n            ) -> Self? {\n                return !traits.isEmpty ? Self(traits: traits) : nil\n            }\n        }\n\n        /// The name of the enabled trait.\n        public var name: String\n\n        /// The condition under which the package manager enables the dependency.\n        public var condition: Condition?\n\n        /// Creates a new enabled trait.\n        ///\n        /// - Parameters:\n        ///   - name: The name of the enabled trait.\n        ///   - condition: The condition under which the trait is enabled.\n        public init(\n            name: String,\n            condition: Condition? = nil\n        ) {\n            self.name = name\n            self.condition = condition\n        }\n\n        /// Creates a new enabled trait.\n        ///\n        /// - Parameter value: The name of the enabled trait.\n        public init(stringLiteral value: StringLiteralType) {\n            self.init(name: value)\n        }\n\n        /// Creates a new enabled trait.\n        ///\n        /// - Parameters:\n        ///   - name: The name of the enabled trait.\n        ///   - condition: The condition under which the trait is enabled.\n        public static func trait(\n            name: String,\n            condition: Condition? = nil\n        ) -> Trait {\n            self.init(\n                name: name,\n                condition: condition\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/BuildConfiguration.md",
    "content": "# ``PackageDescription/BuildConfiguration``\n\n## Topics\n\n### Describing Build Configurations\n\n- ``debug``\n- ``release``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/BuildSettingCondition.md",
    "content": "# ``PackageDescription/BuildSettingCondition``\n\n## Topics\n\n### Checking for a Build Condition\n\n- ``when(platforms:)``\n- ``when(configuration:)``\n- ``when(platforms:configuration:)-475co``\n- ``when(platforms:configuration:traits:)``\n- ``when(platforms:configuration:)-2991l``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/CLanguageStandard.md",
    "content": "# ``PackageDescription/CLanguageStandard``\n\n## Topics\n\n### Enumeration Cases\n\n- ``c11``\n- ``c17``\n- ``c18``\n- ``c2x``\n- ``c89``\n- ``c90``\n- ``c99``\n- ``gnu11``\n- ``gnu17``\n- ``gnu18``\n- ``gnu2x``\n- ``gnu89``\n- ``gnu90``\n- ``gnu99``\n- ``iso9899_1990``\n- ``iso9899_199409``\n- ``iso9899_1999``\n- ``iso9899_2011``\n- ``iso9899_2017``\n- ``iso9899_2018``\n\n### Hashing\n\n- ``hash(into:)``\n- ``hashValue``\n\n### Operator Functions\n\n- ``!=(_:_:)``\n\n### Creating a Value\n\n- ``init(rawValue:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/CSetting.md",
    "content": "# ``PackageDescription/CSetting``\n\n## Topics\n\n### Configuring C Settings\n\n- ``define(_:to:_:)``\n- ``headerSearchPath(_:_:)``\n- ``unsafeFlags(_:_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/CXXLanguageStandard.md",
    "content": "# ``PackageDescription/CXXLanguageStandard``\n\n## Topics\n\n### Enumeration Cases\n\n- ``cxx03``\n- ``cxx11``\n- ``cxx14``\n- ``cxx1z``\n- ``cxx98``\n- ``gnucxx03``\n- ``gnucxx11``\n- ``gnucxx14``\n- ``gnucxx1z``\n- ``gnucxx98``\n- ``cxx17``\n- ``cxx20``\n- ``cxx2b``\n- ``gnucxx17``\n- ``gnucxx20``\n- ``gnucxx2b``\n\n### Hashing\n\n- ``hash(into:)``\n- ``hashValue``\n\n### Operator Functions\n\n- ``!=(_:_:)``\n\n### Creating a Value\n\n- ``init(rawValue:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/CXXSetting.md",
    "content": "# ``PackageDescription/CXXSetting``\n\n## Topics\n\n### Configuring CXX Settings\n\n- ``define(_:to:_:)``\n- ``headerSearchPath(_:_:)``\n- ``unsafeFlags(_:_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Dependency-Trait.md",
    "content": "# ``PackageDescription/Package/Dependency/Trait``\n\n## Topics\n\n### Declaring a Dependency Trait\n\n- ``trait(name:condition:)``\n- ``defaults``\n\n### Creating a Dependency Trait\n\n- ``init(name:condition:)``\n- ``init(stringLiteral:)``\n- ``Condition``\n\n### Inspecting a Dependency Trait\n\n- ``name``\n- ``condition``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Dependency.md",
    "content": "# ``PackageDescription/Package/Dependency``\n\n## Topics\n\n### Creating a package dependency from a URL\n\n- ``package(url:from:)``\n- ``package(url:from:traits:)``\n- ``package(url:_:)-2ys47``\n- ``package(url:_:traits:)-(_,Range<Version>,_)``\n- ``package(url:_:)-1r6rc``\n- ``package(url:_:traits:)-(_,ClosedRange<Version>,_)``\n- ``package(url:branch:)``\n- ``package(url:branch:traits:)``\n- ``package(url:revision:)``\n- ``package(url:revision:traits:)``\n- ``package(url:exact:)``\n- ``package(url:exact:traits:)``\n\n### Creating a package dependency from a registry\n\n- ``package(id:from:)``\n- ``package(id:from:traits:)``\n- ``package(id:_:)-(_,Range<Version>)``\n- ``package(id:_:traits:)-(_,Range<Version>,_)``\n- ``package(id:_:)-(_,ClosedRange<Version>)``\n- ``package(id:_:traits:)-(_,ClosedRange<Version>,_)``\n- ``package(id:exact:)``\n- ``package(id:exact:traits:)``\n\n### Creating a local dependency\n\n- ``package(name:path:)``\n- ``package(name:path:traits:)``\n- ``package(path:)``\n- ``package(path:traits:)``\n\n### Declaring Requirements\n\n- ``traits``\n- ``Trait``\n- ``RegistryRequirement``\n- ``SourceControlRequirement``\n\n### Describing a Package Dependency\n\n- ``kind-swift.property``\n- ``Kind``\n- ``Version``\n\n### Deprecated methods\n\n- ``package(name:url:_:)-(String?,_,_)``\n- ``package(name:url:_:)-(_,_,Range<Version>)``\n- ``package(name:url:_:)-(_,_,ClosedRange<Version>)``\n- ``package(name:url:branch:)``\n- ``package(name:url:from:)``\n- ``package(name:url:revision:)``\n- ``package(url:_:)-(_,Package.Dependency.Requirement)``\n- ``name``\n- ``url``\n- ``requirement-swift.property``\n- ``Requirement-swift.enum``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/CLanguageStandard-hash.md",
    "content": "# ``PackageDescription/CLanguageStandard/hash(into:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nHashes the C language standard by feeding the item into the given hasher.\n\n- Parameter hasher: The hasher.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/CLanguageStandard-hashValue.md",
    "content": "# ``PackageDescription/CLanguageStandard/hashValue``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nThe hash value for the C language standard.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/CLanguageStandard-notEqual.md",
    "content": "# ``PackageDescription/CLanguageStandard/!=(_:_:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nReturns a Boolean value indicating whether two values are not equal.\n\n- Parameters:\n  - lhs: A value to compare.\n  - rhs: Another value to compare.\n\nInequality is the inverse of equality. For any values a and b, a != b implies that a == b is false.\n\nThis is the default implementation of the not-equal-to operator (!=) for any type that conforms to Equatable.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/CXXLanguageStandard-hash.md",
    "content": "# ``PackageDescription/CXXLanguageStandard/hash(into:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nHashes the C++ language standard by feeding the item into the given hasher.\n\n- Parameter hasher: The hasher.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/CXXLanguageStandard-hashValue.md",
    "content": "# ``PackageDescription/CXXLanguageStandard/hashValue``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nThe hash value for the C++ language standard.\n\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/CXXLanguageStandard-notEqual.md",
    "content": "# ``PackageDescription/CXXLanguageStandard/!=(_:_:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nReturns a Boolean value indicating whether two values are not equal.\n\n- Parameters:\n  - lhs: A value to compare.\n  - rhs: Another value to compare.\n\nInequality is the inverse of equality. For any values a and b, a != b implies that a == b is false.\n\nThis is the default implementation of the not-equal-to operator (!=) for any type that conforms to Equatable.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/LanguageTag-hash.md",
    "content": "# ``PackageDescription/LanguageTag/hash(into:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nHashes the language tag by feeding the item into the given hasher.\n\n- Parameter hasher: The hasher.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/LanguageTag-hashValue.md",
    "content": "# ``PackageDescription/LanguageTag/hashValue``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nThe hash value for language tag.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/LanguageTag-initRawValue.md",
    "content": "# ``PackageDescription/LanguageTag/init(rawValue:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nCreates a new instance with the specified raw value.\n\n- Parameter rawValue: The raw value to use for the new instance.\n\nIf there is no value of the type that corresponds with the specified raw value, this initializer returns `nil`.\n\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/LanguageTag-notEqual.md",
    "content": "# ``PackageDescription/LanguageTag/!=(_:_:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nReturns a Boolean value indicating whether two values are not equal.\n\n- Parameters:\n  - lhs: A value to compare.\n  - rhs: Another value to compare.\n\nInequality is the inverse of equality. For any values a and b, a != b implies that a == b is false.\n\nThis is the default implementation of the not-equal-to operator (!=) for any type that conforms to Equatable.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/LanguageTag-rawValue.md",
    "content": "# ``PackageDescription/LanguageTag/rawValue``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nThe corresponding value of the raw type.\n\nA new instance initialized with `rawValue` will be equivalent to this instance.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Library-LibraryType-hash.md",
    "content": "# ``PackageDescription/Product/Library/LibraryType/hash(into:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nHashes the essential components of this value by feeding them into the given hasher.\n\nImplement this method to conform to the Hashable protocol. The components used for hashing must be the same as the components compared in your type’s == operator implementation. Call hasher.combine(_:) with each of these components.\n\n> Important:\n> Never call finalize() on hasher. Doing so may become a compile-time error in the future.\n\n- Parameter hasher: The hasher to use when combining the components of this instance.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Library-LibraryType-hashValue.md",
    "content": "# ``PackageDescription/Product/Library/LibraryType/hashValue``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nThe library type’s hash value.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Library-LibraryType-initRawValue.md",
    "content": "# ``PackageDescription/Product/Library/LibraryType/init(rawValue:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nCreates a new instance with the specified raw value.\n\n- Parameter rawValue: The raw value to use for the new instance.\n\nIf there is no value of the type that corresponds with the specified raw value, this initializer returns `nil`.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Library-LibraryType-notEqual.md",
    "content": "# ``PackageDescription/Product/Library/LibraryType/!=(_:_:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nReturns a Boolean value indicating whether two values are not equal.\n\n- Parameters:\n  - lhs: A value to compare.\n  - rhs: Another value to compare.\n\nInequality is the inverse of equality. For any values a and b, `a != b` implies that `a == b` is `false`.\n\nThis is the default implementation of the not-equal-to operator (`!=`) for any type that conforms to `Equatable`.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Library-LibraryType.md",
    "content": "# ``PackageDescription/Product/Library/LibraryType``\n\n## Topics\n\n### Enumeration Cases\n\n- ``dynamic``\n- ``static``\n\n### Hashing\n\n- <doc:/documentation/PackageDescription/Product/Library/LibraryType/hash(into:)>\n- <doc:/documentation/PackageDescription/Product/Library/LibraryType/hashValue>\n\n### Operator Functions\n\n- <doc:/documentation/PackageDescription/Product/Library/LibraryType/!=(_:_:)>\n\n### Creating a Value\n\n- <doc:/documentation/PackageDescription/Product/Library/LibraryType/init(rawValue:)>\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Product-Executable.md",
    "content": "# ``PackageDescription/Product/Executable``\n\n## Topics\n\n### Describing an executable product\n\n- ``targets``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Resource-Localization-hash.md",
    "content": "# ``PackageDescription/Resource/Localization/hash(into:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nHashes the localization by feeding the item into the given hasher.\n\n- Parameter hasher: The hasher.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Resource-Localization-hashValue.md",
    "content": "# ``PackageDescription/Resource/Localization/hashValue``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nThe localization's hash value.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Resource-Localization-notEqual.md",
    "content": "# ``PackageDescription/Resource/Localization/!=(_:_:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nReturns a Boolean value indicating whether two values are not equal.\n\n- Parameters:\n  - lhs: A value to compare.\n  - rhs: Another value to compare.\n\nInequality is the inverse of equality. For any values a and b, `a != b` implies that `a == b` is `false`.\n\nThis is the default implementation of the not-equal-to operator (`!=`) for any type that conforms to `Equatable`.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Target-TargetType-hash.md",
    "content": "# ``PackageDescription/Target/TargetType/hash(into:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nHashes the target type by feeding the item into the given hasher.\n\n- Parameter hasher: The hasher.\n\n\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Target-TargetType-hashValue.md",
    "content": "# ``PackageDescription/Target/TargetType/hashValue``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nThe target type's hash value.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Extensions/Target-TargetType-notEqual.md",
    "content": "# ``PackageDescription/Target/TargetType/!=(_:_:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nReturns a Boolean value indicating whether two values are not equal.\n\n- Parameters:\n  - lhs: A value to compare.\n  - rhs: Another value to compare.\n\nInequality is the inverse of equality. For any values a and b, `a != b` implies that `a == b` is `false`.\n\nThis is the default implementation of the not-equal-to operator (`!=`) for any type that conforms to `Equatable`.\n\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/LanguageTag.md",
    "content": "#  ``PackageDescription/LanguageTag``\n\n## Topics\n\n### Creating a Language Tag\n\n- <doc:/documentation/PackageDescription/LanguageTag/init(extendedGraphemeClusterLiteral:)-36buv>\n- ``init(stringLiteral:)``\n- <doc:/documentation/PackageDescription/LanguageTag/init(unicodeScalarLiteral:)-1j41k>\n- ``init(rawValue:)``\n- ``rawValue-swift.property``\n\n### Describing a Language Tag\n\n- ``description``\n\n### Hashing\n\n- <doc:/documentation/PackageDescription/LanguageTag/hash(into:)>\n- <doc:/documentation/PackageDescription/LanguageTag/hashValue>\n\n### Operator Functions\n\n- <doc:/documentation/PackageDescription/LanguageTag/!=(_:_:)>\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Library.md",
    "content": "# ``PackageDescription/Product/Library``\n\n## Topics\n\n### Describing a Library Product\n\n- ``targets``\n- ``type``\n- ``LibraryType``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/LinkerSetting.md",
    "content": "# ``PackageDescription/LinkerSetting``\n\n## Topics\n\n### Configuring Linker Settings\n\n- ``linkedFramework(_:_:)``\n- ``linkedLibrary(_:_:)``\n- ``unsafeFlags(_:_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Package.md",
    "content": "#  ``PackageDescription/Package``\n\n## Topics\n\n### Creating a Package\n\n- ``Package/init(name:defaultLocalization:platforms:pkgConfig:providers:products:dependencies:targets:swiftLanguageModes:cLanguageStandard:cxxLanguageStandard:)``\n- ``Package/init(name:defaultLocalization:platforms:pkgConfig:providers:products:traits:dependencies:targets:swiftLanguageModes:cLanguageStandard:cxxLanguageStandard:)``\n- ``Package/init(name:platforms:pkgConfig:providers:products:dependencies:targets:swiftLanguageVersions:cLanguageStandard:cxxLanguageStandard:)``\n- ``Package/init(name:pkgConfig:providers:products:dependencies:targets:swiftLanguageVersions:cLanguageStandard:cxxLanguageStandard:)-(_,_,_,_,_,_,[Int]?,_,_)``\n- ``Package/init(name:pkgConfig:providers:products:dependencies:targets:swiftLanguageVersions:cLanguageStandard:cxxLanguageStandard:)-(_,_,_,_,_,_,[SwiftVersion]?,_,_)``\n- ``Package/init(name:defaultLocalization:platforms:pkgConfig:providers:products:dependencies:targets:swiftLanguageVersions:cLanguageStandard:cxxLanguageStandard:)``\n\n### Naming the Package\n\n- ``Package/name``\n\n### Localizing Package Resources\n\n- ``Package/defaultLocalization``\n- ``LanguageTag``\n\n### Configuring Products\n\n- ``Package/products``\n- ``Product``\n\n### Configuring Targets\n\n- ``Package/targets``\n- ``Target``\n\n### Declaring Supported Platforms\n\n- ``Package/platforms``\n- ``SupportedPlatform``\n- ``Platform``\n\n### Configuring System Packages\n\n- ``SystemPackageProvider``\n- ``Package/pkgConfig``\n- ``Package/providers``\n\n### Configuring Traits\n\n- ``Package/traits``\n- ``Trait``\n\n### Declaring Package Dependencies\n\n- ``Package/dependencies``\n- ``Package/Dependency``\n\n### Declaring Supported Languages\n\n- ``SwiftLanguageMode``\n- ``CLanguageStandard``\n- ``CXXLanguageStandard``\n- ``Package/swiftLanguageModes``\n- ``Package/cLanguageStandard``\n- ``Package/cxxLanguageStandard``\n- ``SwiftVersion``\n- ``Package/swiftLanguageVersions``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Platform-notEqual.md",
    "content": "# ``PackageDescription/Platform/!=(_:_:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nReturns a Boolean value indicating whether two values are not equal.\n\n- Parameters:\n  - lhs: A value to compare.\n  - rhs: Another value to compare.\n\nInequality is the inverse of equality. For any values a and b, `a != b` implies that `a == b` is `false`.\n\nThis is the default implementation of the not-equal-to operator (`!=`) for any type that conforms to `Equatable`.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Platform.md",
    "content": "# ``PackageDescription/Platform``\n\n\n## Topics\n\n### Platforms\n\n- ``iOS``\n- ``macOS``\n- ``tvOS``\n- ``watchOS``\n- ``visionOS``\n- ``macCatalyst``\n- ``driverKit``\n- ``android``\n- ``linux``\n- ``freebsd``\n- ``openbsd``\n- ``wasi``\n- ``windows``\n\n### Type methods\n\n- ``custom(_:)``\n\n### Operator Functions\n\n- ``!=(_:_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Plugin.md",
    "content": "# ``PackageDescription/Product/Plugin``\n\n## Topics\n\n### Describing a plug-in product\n\n- ``targets``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/PluginCapability.md",
    "content": "# ``PackageDescription/Target/PluginCapability-swift.enum``\n\n## Topics\n\n### Creating a Plugin Capability\n\n- ``buildTool()``\n- ``command(intent:permissions:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/PluginCommandIntent.md",
    "content": "# ``PackageDescription/PluginCommandIntent``\n\n## Topics\n\n### Creating a Command Intent\n\n- ``documentationGeneration()``\n- ``sourceCodeFormatting()``\n- ``custom(verb:description:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/PluginPermission.md",
    "content": "# ``PackageDescription/PluginPermission``\n\n## Topics\n\n### Create a permission\n\n- ``allowNetworkConnections(scope:reason:)``\n- ``writeToPackageDirectory(reason:)``\n\n### Allow network connection\n\n- ``PluginNetworkPermissionScope``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/PluginUsage.md",
    "content": "# ``PackageDescription/Target/PluginUsage``\n\n## Topics\n\n### Creating a Plugin Usage\n\n- ``plugin(name:)``\n- ``plugin(name:package:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Product.md",
    "content": "#  ``PackageDescription/Product``\n\n## Topics\n\n### Creating a Library Product\n\n- ``library(name:type:targets:)``\n- ``Library``\n\n### Creating an Executable Product\n\n- ``executable(name:targets:)``\n- ``Executable``\n\n### Creating a Plugin Product\n\n- ``Product/plugin(name:targets:)``\n- ``Plugin``\n\n### Naming the product\n\n- ``name``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Resource-Localization.md",
    "content": "# ``PackageDescription/Resource/Localization``\n\n## Topics\n\n### Enumeration Cases\n\n- ``base``\n- ``default``\n\n### Hashing\n\n- ``hash(into:)``\n- ``hashValue``\n\n### Operator Functions\n\n- ``!=(_:_:)``\n\n### Creating a Value\n\n- ``init(rawValue:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Resource.md",
    "content": "# ``PackageDescription/Resource``\n\n## Topics\n\n### Applying Rules\n\n- ``process(_:localization:)``\n- ``Localization``\n- ``copy(_:)``\n- ``embedInCode(_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/SupportedPlatforms-notEqual.md",
    "content": "# ``PackageDescription/SupportedPlatform/!=(_:_:)``\n\n@Metadata {\n   @DocumentationExtension(mergeBehavior: override)\n}\n\nReturns a Boolean value indicating whether two values are not equal.\n\n- Parameters:\n  - lhs: A value to compare.\n  - rhs: Another value to compare.\n\nInequality is the inverse of equality. For any values a and b, `a != b` implies that `a == b` is `false`.\n\nThis is the default implementation of the not-equal-to operator (`!=`) for any type that conforms to `Equatable`.\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/SupportedPlatforms.md",
    "content": "# ``PackageDescription/SupportedPlatform``\n\n## Topics\n\n### Supporting iOS\n\n- ``iOS(_:)-5pvv5``\n- ``iOS(_:)-83bbf``\n- <doc:/documentation/PackageDescription/Platform/iOS>\n- ``IOSVersion``\n\n### Supporting macOS\n\n- ``macOS(_:)-2wthp``\n- ``macOS(_:)-9771f``\n- <doc:/documentation/PackageDescription/Platform/macOS>\n- ``MacOSVersion``\n\n### Supporting watchOS\n\n- ``watchOS(_:)-t998``\n- ``watchOS(_:)-4lrx0``\n- <doc:/documentation/PackageDescription/Platform/watchOS>\n- ``WatchOSVersion``\n\n### Supporting visionOS\n\n- ``visionOS(_:)-3ip0z``\n- ``visionOS(_:)-6ur2u``\n- <doc:/documentation/PackageDescription/Platform/visionOS>\n- ``VisionOSVersion``\n\n### Supporting tvOS\n\n- ``tvOS(_:)-6931l``\n- ``tvOS(_:)-3k8sy``\n- <doc:/documentation/PackageDescription/Platform/tvOS>\n- ``TVOSVersion``\n\n### Supporting MacCatalyst\n\n- ``macCatalyst(_:)-6bh40``\n- ``macCatalyst(_:)-9wbz``\n- <doc:/documentation/PackageDescription/Platform/macCatalyst>\n- ``MacCatalystVersion``\n\n### Supporting DriverKit\n\n- ``driverKit(_:)-jxlz``\n- ``driverKit(_:)-6evdd``\n- <doc:/documentation/PackageDescription/Platform/driverKit>\n- ``DriverKitVersion``\n\n### Supporting Custom Platforms\n\n- ``custom(_:versionString:)``\n\n### Operator Functions\n\n- ``!=(_:_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/SwiftLanguageMode.md",
    "content": "# ``PackageDescription/SwiftLanguageMode``\n\n## Topics\n\n### Swift Language Modes\n\n- ``v6``\n- ``v5``\n- ``v4_2``\n- ``v4``\n- ``version(_:)``\n- ``v3``\n\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/SwiftSetting.md",
    "content": "# ``PackageDescription/SwiftSetting``\n\n## Topics\n\n### Configuring Swift Settings\n\n- ``define(_:_:)``\n- ``unsafeFlags(_:_:)``\n- ``treatAllWarnings(as:_:)``\n- ``treatWarning(_:as:_:)``\n\n### Configuring Swift Language Mode\n\n- ``swiftLanguageMode(_:_:)``\n\n### Configuring Swift Concurrency\n\n- ``strictMemorySafety(_:)``\n- ``defaultIsolation(_:_:)``\n\n### Configuring Swift Experimental and Upcoming Features\n\n- ``enableExperimentalFeature(_:_:)``\n- ``enableUpcomingFeature(_:_:)``\n\n### Configuring Swift Interoperability\n\n- ``interoperabilityMode(_:_:)``\n- ``InteroperabilityMode``\n\n### Deprecated configurations\n\n- ``swiftLanguageVersion(_:_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/SystemPackageProvider.md",
    "content": "# ``PackageDescription/SystemPackageProvider``\n\n## Topics\n\n### Providing Hints to Users of System Packages\n\n- ``apt(_:)``\n- ``brew(_:)``\n- ``nuget(_:)``\n- ``yum(_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Target-Dependency.md",
    "content": "# ``PackageDescription/Target/Dependency``\n\n## Topics\n\n### Creating a Target Dependency\n\n- ``product(name:package:moduleAliases:condition:)``\n- ``productItem(name:package:moduleAliases:condition:)``\n- ``target(name:condition:)``\n- ``targetItem(name:condition:)``\n- ``byName(name:condition:)``\n- ``byNameItem(name:condition:)``\n- ``TargetDependencyCondition``\n- ``init(stringLiteral:)``\n\n- ``product(name:package:condition:)``\n- ``product(name:package:)-fp0j``\n- ``product(name:package:)-2nako``\n- ``productItem(name:package:condition:)``\n- ``target(name:)``\n- ``byName(name:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Target-TargetDependencyCondition.md",
    "content": "# ``PackageDescription/TargetDependencyCondition``\n\n## Topics\n\n### Creating a Dependency Condition\n\n- ``when(platforms:)-5bxhc``\n- ``when(traits:)``\n- ``when(platforms:traits:)``\n- ``when(platforms:)-4djh6``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Target-TargetType.md",
    "content": "# ``PackageDescription/Target/TargetType``\n\n## Topics\n\n### Enumeration Cases\n\n- ``regular``\n- ``binary``\n- ``system``\n- ``test``\n- ``executable``\n- ``plugin``\n\n### Creating a Value\n\n- ``init(rawValue:)``\n\n### Hashing\n\n- ``hash(into:)``\n- ``hashValue``\n\n### Operator Functions\n\n- ``!=(_:_:)``\n\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Target.md",
    "content": "#  ``PackageDescription/Target``\n\n### Test Libraries Targets\n\nBuilt-in testing libraries, such as Swift Testing and XCTest, are only available for use in certain runtime contexts.\nWhile you can use these within Swift libraries intended for testing, take care so that any such libraries only terminate in test targets, as targets that use Swift Testing or XCTest should never be distributed to end users.\nIncluding testing libraries as a dependency to an executable target, as either a direct or transitive dependency, can cause clients to encounter linking issues.\n\n## Topics\n\n### Naming the Target\n\n- ``name``\n\n### Configuring File Locations\n\n- ``path``\n- ``exclude``\n- ``sources``\n- ``resources``\n- ``Resource``\n- ``publicHeadersPath``\n\n### Creating a Binary Target\n\n- ``binaryTarget(name:path:)``\n- ``binaryTarget(name:url:checksum:)``\n- ``url``\n- ``checksum``\n\n### Creating a System Library Target\n\n- ``systemLibrary(name:path:pkgConfig:providers:)``\n- ``pkgConfig``\n- ``providers``\n\n### Creating an Executable Target\n\n- ``executableTarget(name:dependencies:path:exclude:sources:resources:publicHeadersPath:packageAccess:cSettings:cxxSettings:swiftSettings:linkerSettings:plugins:)``\n- ``executableTarget(name:dependencies:path:exclude:sources:resources:publicHeadersPath:cSettings:cxxSettings:swiftSettings:linkerSettings:plugins:)``\n- ``executableTarget(name:dependencies:path:exclude:sources:resources:publicHeadersPath:cSettings:cxxSettings:swiftSettings:linkerSettings:)``\n\n### Creating a Regular Target\n\n- ``target(name:dependencies:path:exclude:sources:resources:publicHeadersPath:packageAccess:cSettings:cxxSettings:swiftSettings:linkerSettings:plugins:)``\n- ``target(name:dependencies:path:exclude:sources:resources:publicHeadersPath:cSettings:cxxSettings:swiftSettings:linkerSettings:plugins:)``\n- ``target(name:dependencies:path:exclude:sources:resources:publicHeadersPath:cSettings:cxxSettings:swiftSettings:linkerSettings:)``\n- ``target(name:dependencies:path:exclude:sources:publicHeadersPath:cSettings:cxxSettings:swiftSettings:linkerSettings:)``\n- ``target(name:dependencies:path:exclude:sources:publicHeadersPath:)``\n\n### Creating a Test Target\n\n- ``testTarget(name:dependencies:path:exclude:sources:resources:packageAccess:cSettings:cxxSettings:swiftSettings:linkerSettings:plugins:)``\n- ``testTarget(name:dependencies:path:exclude:sources:resources:cSettings:cxxSettings:swiftSettings:linkerSettings:plugins:)``\n- ``testTarget(name:dependencies:path:exclude:sources:resources:cSettings:cxxSettings:swiftSettings:linkerSettings:)``\n- ``testTarget(name:dependencies:path:exclude:sources:cSettings:cxxSettings:swiftSettings:linkerSettings:)``\n- ``testTarget(name:dependencies:path:exclude:sources:)``\n\n### Creating a Plugin Target\n\n- ``plugin(name:capability:dependencies:path:exclude:sources:packageAccess:)``\n- ``pluginCapability-swift.property``\n- ``PluginCapability-swift.enum``\n- ``PluginCommandIntent``\n- ``PluginPermission``\n- ``plugin(name:capability:dependencies:path:exclude:sources:)``\n\n### Declaring a Dependency Target\n\n- ``dependencies``\n- ``Dependency``\n- ``TargetDependencyCondition``\n\n### Configuring the Target\n\n- ``cSettings``\n- ``cxxSettings``\n- ``swiftSettings``\n- ``linkerSettings``\n- ``plugins``\n- ``BuildConfiguration``\n- ``BuildSettingCondition``\n- ``CSetting``\n- ``CXXSetting``\n- ``SwiftSetting``\n- ``LinkerSetting``\n- ``PluginUsage``\n- ``packageAccess``\n\n### Describing the Target Type\n\n- ``isTest``\n- ``type``\n- ``TargetType``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Trait.md",
    "content": "# ``PackageDescription/Trait``\n\n## Topics\n\n### Declaring Traits\n\n- ``trait(name:description:enabledTraits:)``\n- ``default(enabledTraits:)``\n\n### Creating Traits\n\n- ``init(name:description:enabledTraits:)``\n- ``init(stringLiteral:)``\n\n### Inspecting Traits\n\n- ``name``\n- ``description``\n- ``enabledTraits``\n\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Curation/Version.md",
    "content": "# ``PackageDescription/Version``\n\n## Topics\n\n### Creating a new version\n\n- ``init(_:_:_:prereleaseIdentifiers:buildMetadataIdentifiers:)``\n\n### Inspecting a version\n\n- ``major``\n- ``minor``\n- ``patch``\n- ``prereleaseIdentifiers``\n- ``buildMetadataIdentifiers``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n    <key>CFBundleName</key>\n    <string>PackageDescription</string>\n    <key>CFBundleDisplayName</key>\n    <string>PackageDescription</string>\n    <key>CFBundleIdentifier</key>\n    <string>org.swift.swiftpm.packagedescription</string>\n    <key>CFBundleDevelopmentRegion</key>\n    <string>en</string>\n    <key>CFBundleIconFile</key>\n    <string>DocumentationIcon</string>\n    <key>CFBundleIconName</key>\n    <string>DocumentationIcon</string>\n    <key>CFBundlePackageType</key>\n    <string>DOCS</string>\n    <key>CFBundleShortVersionString</key>\n    <string>0.1.0</string>\n    <key>CDDefaultCodeListingLanguage</key>\n    <string>swift</string>\n    <key>CFBundleVersion</key>\n    <string>0.1.0</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.docc/PackageDescription.md",
    "content": "# ``PackageDescription``\n\nCreate reusable code, organize it in a lightweight way, and share it across your projects and with other developers.\n\nSwift packages are reusable components of Swift, Objective-C, Objective-C++, C, or C++ code that developers can use in their projects. They bundle source files, binaries, and resources in a way that’s easy to use in your app’s project. \n\nEach Swift package requires a `Package.swift` file in the main directory of the package — referred to as the package manifest. When you create a Swift package, you use the PackageDescription library in the package manifest to list dependencies, configure localized resources, and set other configuration options.\n\nFor example, the package manifest from the [SlothCreator: Building DocC Documentation in Xcode](https://developer.apple.com/documentation/xcode/slothcreator_building_docc_documentation_in_xcode) sample project below defines the SlothCreator package, with the SlothCreator library in it. It specifies the deployment targets, and that its resources are in the `Resources` folder.\n\n```swift\nimport PackageDescription\n\nlet package = Package(\n    name: \"SlothCreator\",\n    platforms: [\n        .macOS(.v11),\n        .iOS(.v14),\n        .watchOS(.v7),\n        .tvOS(.v13)\n    ],\n    products: [\n        .library(\n            name: \"SlothCreator\",\n            targets: [\"SlothCreator\"]\n        )\n    ],\n    targets: [\n        .target(\n            name: \"SlothCreator\",\n            resources: [\n                .process(\"Resources/\")\n            ]\n        )\n    ]\n)\n```\n\nThe package manifest also allows you to define executable products, as well as plugins that Swift Package Manager can use to build other products in the manifest.\n\nFor more information about adding a package dependency to your app project and creating Swift packages with Xcode, see [Adding Package Dependencies to Your App](https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app), [Creating a Standalone Swift Package with Xcode](https://developer.apple.com/documentation/xcode/creating-a-standalone-swift-package-with-xcode), and [Swift Packages](https://developer.apple.com/documentation/xcode/swift-packages).\n\nSupport for Swift packages in Xcode builds on the open-source Swift Package Manager project. To learn more about the Swift Package Manager, visit [Swift.org](https://www.swift.org/package-manager/) and the Swift Package Manager repository on [GitHub](https://github.com/swiftlang/swift-package-manager).\n\n## Topics\n\n### Creating a Package\n\n- ``Package``\n- ``Context``\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if canImport(ucrt) && canImport(WinSDK)\n@_implementationOnly import ucrt\n@_implementationOnly import struct WinSDK.HANDLE\n#endif\n@_implementationOnly import Foundation\n\n/// The configuration of a Swift package.\n///\n/// Pass configuration options as parameters to your package's initializer\n/// statement to provide the name of the package, its targets, products,\n/// dependencies, and other configuration options.\n///\n/// By convention, you need to define the properties of a package in a single\n/// nested initializer statement. Don't modify it after initialization. The\n/// following package manifest shows the initialization of a simple package\n/// object for the MyLibrary Swift package:\n///\n/// ```swift\n/// // swift-tools-version:5.3\n/// import PackageDescription\n///\n/// let package = Package(\n///     name: \"MyLibrary\",\n///     platforms: [\n///         .macOS(.v10_15),\n///     ],\n///     products: [\n///         .library(name: \"MyLibrary\", targets: [\"MyLibrary\"])\n///     ],\n///     dependencies: [\n///         .package(url: \"https://url/of/another/package/named/utility\", from: \"1.0.0\")\n///     ],\n///     targets: [\n///         .target(name: \"MyLibrary\", dependencies: [\"Utility\"]),\n///         .testTarget(name: \"MyLibraryTests\", dependencies: [\"MyLibrary\"])\n///     ]\n/// )\n/// ```\n///\n/// In Swift tools versions earlier than 5.4, the package manifest must begin with the string `// swift-tools-version:`\n/// followed by a version number specifier. Version 5.4 and later has relaxed the whitespace requirements.\n/// The following code listing shows a few examples of valid declarations of the Swift tools version:\n///\n/// ```swift\n/// // swift-tools-version:3.0.2\n/// // swift-tools-version:3.1\n/// // swift-tools-version:4.0\n/// // swift-tools-version:5.3\n/// // swift-tools-version: 5.6\n/// ```\n///\n/// The Swift tools version declares the version of the `PackageDescription`\n/// library, the minimum version of the Swift tools and Swift language\n/// compatibility version to process the manifest, and the required minimum\n/// version of the Swift tools to use the Swift package. Each version of Swift\n/// can introduce updates to the PackageDescription framework, but the previous\n/// API version is available to packages which declare a prior tools version.\n/// This behavior means you can take advantage of new releases of Swift, the Swift\n/// tools, and the PackageDescription library, without having to update your\n/// package's manifest or losing access to existing packages.\npublic final class Package {\n    /// The name of the Swift package.\n    public var name: String\n\n    /// The list of minimum versions for platforms supported by the package.\n    @available(_PackageDescription, introduced: 5)\n    public var platforms: [SupportedPlatform]?\n\n    /// The default localization for resources.\n    @available(_PackageDescription, introduced: 5.3)\n    public var defaultLocalization: LanguageTag?\n\n    /// The name to use for C modules.\n    ///\n    /// If present, the Swift Package Manager searches for a `<name>.pc` file to\n    /// get the required additional flags for a system target.\n    public var pkgConfig: String?\n\n    /// An array of providers for a system target.\n    public var providers: [SystemPackageProvider]?\n\n    /// The list of targets that are part of this package.\n    public var targets: [Target]\n\n    /// The list of products that this package vends and that clients can use.\n    public var products: [Product]\n\n    /// The set of traits this package provides.\n    @available(_PackageDescription, introduced: 6.1)\n    public var traits: Set<Trait>\n\n    /// The list of package dependencies.\n    public var dependencies: [Dependency]\n\n    /// The list of Swift language modes with which this package is compatible.\n    public var swiftLanguageModes: [SwiftLanguageMode]?\n    \n    /// Legacy property name, accesses value of `swiftLanguageModes`\n    @available(_PackageDescription, deprecated: 6, renamed: \"swiftLanguageModes\")\n    public var swiftLanguageVersions: [SwiftVersion]? {\n        get { swiftLanguageModes }\n        set { swiftLanguageModes = newValue }\n    }\n\n    /// The C language standard to use for all C targets in this package.\n    public var cLanguageStandard: CLanguageStandard?\n\n    /// The C++ language standard to use for all C++ targets in this package.\n    public var cxxLanguageStandard: CXXLanguageStandard?\n\n    /// Initializes a Swift package with configuration options you provide.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package, or `nil`, if you want the Swift Package Manager to deduce the\n    ///           name from the package's Git URL.\n    ///   - pkgConfig: The name to use for C modules. If present, the Swift\n    ///           Package Manager searches for a `<name>.pc` file to get the\n    ///           additional flags required for a system target.\n    ///   - providers: The package providers for a system package.\n    ///   - products: The list of products that this package vends and that clients can use.\n    ///   - dependencies: The list of package dependencies.\n    ///   - targets: The list of targets that are part of this package.\n    ///   - swiftLanguageVersions: The list of Swift versions that this package is compatible with.\n    ///   - cLanguageStandard: The C language standard to use for all C targets in this package.\n    ///   - cxxLanguageStandard: The C++ language standard to use for all C++ targets in this package.\n    @available(_PackageDescription, obsoleted: 4.2)\n    public init(\n        name: String,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProvider]? = nil,\n        products: [Product] = [],\n        dependencies: [Dependency] = [],\n        targets: [Target] = [],\n        swiftLanguageVersions: [Int]? = nil,\n        cLanguageStandard: CLanguageStandard? = nil,\n        cxxLanguageStandard: CXXLanguageStandard? = nil\n    ) {\n        self.name = name\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.products = products\n        self.dependencies = dependencies\n        self.targets = targets\n        self.traits = []\n        self.swiftLanguageModes = swiftLanguageVersions.map{ $0.map{ .version(\"\\($0)\") } }\n        self.cLanguageStandard = cLanguageStandard\n        self.cxxLanguageStandard = cxxLanguageStandard\n        registerExitHandler()\n    }\n\n    /// Initializes a Swift package with configuration options you provide.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package, or `nil`, if you want the Swift Package Manager to deduce the\n    ///           name from the package's Git URL.\n    ///   - pkgConfig: The name to use for C modules. If present, the Swift\n    ///           Package Manager searches for a `<name>.pc` file to get the\n    ///           additional flags required for a system target.\n    ///   - providers: The system package providers that this package uses.\n    ///   - products: The list of products that this package makes available for clients to use.\n    ///   - dependencies: The list of package dependencies.\n    ///   - targets: The list of targets that are part of this package.\n    ///   - swiftLanguageVersions: The list of Swift versions that this package is compatible with.\n    ///   - cLanguageStandard: The C language standard to use for all C targets in this package.\n    ///   - cxxLanguageStandard: The C++ language standard to use for all C++ targets in this package.\n    @available(_PackageDescription, introduced: 4.2, obsoleted: 5)\n    public init(\n        name: String,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProvider]? = nil,\n        products: [Product] = [],\n        dependencies: [Dependency] = [],\n        targets: [Target] = [],\n        swiftLanguageVersions: [SwiftVersion]? = nil,\n        cLanguageStandard: CLanguageStandard? = nil,\n        cxxLanguageStandard: CXXLanguageStandard? = nil\n    ) {\n        self.name = name\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.products = products\n        self.dependencies = dependencies\n        self.targets = targets\n        self.traits = []\n        self.swiftLanguageModes = swiftLanguageVersions\n        self.cLanguageStandard = cLanguageStandard\n        self.cxxLanguageStandard = cxxLanguageStandard\n        registerExitHandler()\n    }\n\n    /// Initializes a Swift package with configuration options you provide.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package, or `nil`, if you want the Swift Package Manager to deduce the\n    ///           name from the package's Git URL.\n    ///   - platforms: The list of supported platforms that have a custom deployment target.\n    ///   - pkgConfig: The name to use for C modules. If present, the Swift\n    ///           Package Manager searches for a `<name>.pc` file to get the\n    ///           additional flags required for a system target.\n    ///   - providers: The system package providers that this package uses.\n    ///   - products: The list of products that this package makes available for clients to use.\n    ///   - dependencies: The list of package dependencies.\n    ///   - targets: The list of targets that are part of this package.\n    ///   - swiftLanguageVersions: The list of Swift versions that this package is compatible with.\n    ///   - cLanguageStandard: The C language standard to use for all C targets in this package.\n    ///   - cxxLanguageStandard: The C++ language standard to use for all C++ targets in this package.\n    @available(_PackageDescription, introduced: 5, obsoleted: 5.3)\n    public init(\n        name: String,\n        platforms: [SupportedPlatform]? = nil,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProvider]? = nil,\n        products: [Product] = [],\n        dependencies: [Dependency] = [],\n        targets: [Target] = [],\n        swiftLanguageVersions: [SwiftVersion]? = nil,\n        cLanguageStandard: CLanguageStandard? = nil,\n        cxxLanguageStandard: CXXLanguageStandard? = nil\n    ) {\n        self.name = name\n        self.platforms = platforms\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.products = products\n        self.dependencies = dependencies\n        self.targets = targets\n        self.traits = []\n        self.swiftLanguageModes = swiftLanguageVersions\n        self.cLanguageStandard = cLanguageStandard\n        self.cxxLanguageStandard = cxxLanguageStandard\n        registerExitHandler()\n    }\n\n    /// Initializes a Swift package with configuration options you provide.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package, or `nil` to use the package's Git URL to deduce the name.\n    ///   - defaultLocalization: The default localization for resources.\n    ///   - platforms: The list of supported platforms with a custom deployment target.\n    ///   - pkgConfig: The name to use for C modules. If present, Swift Package Manager searches for a\n    ///   `<name>.pc` file to get the additional flags required for a system target.\n    ///   - providers: The package providers for a system target.\n    ///   - products: The list of products that this package makes available for clients to use.\n    ///   - dependencies: The list of package dependencies.\n    ///   - targets: The list of targets that are part of this package.\n    ///   - swiftLanguageVersions: The list of Swift versions with which this package is compatible.\n    ///   - cLanguageStandard: The C language standard to use for all C targets in this package.\n    ///   - cxxLanguageStandard: The C++ language standard to use for all C++ targets in this package.\n    @_disfavoredOverload\n    @available(_PackageDescription, introduced: 5.3)\n    @available(_PackageDescription, deprecated: 6, renamed:\"init(name:defaultLocalization:platforms:pkgConfig:providers:products:dependencies:targets:swiftLanguageModes:cLanguageStandard:cxxLanguageStandard:)\")\n    public init(\n        name: String,\n        defaultLocalization: LanguageTag? = nil,\n        platforms: [SupportedPlatform]? = nil,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProvider]? = nil,\n        products: [Product] = [],\n        dependencies: [Dependency] = [],\n        targets: [Target] = [],\n        swiftLanguageVersions: [SwiftVersion]? = nil,\n        cLanguageStandard: CLanguageStandard? = nil,\n        cxxLanguageStandard: CXXLanguageStandard? = nil\n    ) {\n        self.name = name\n        self.defaultLocalization = defaultLocalization\n        self.platforms = platforms\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.products = products\n        self.dependencies = dependencies\n        self.targets = targets\n        self.traits = []\n        self.swiftLanguageModes = swiftLanguageVersions\n        self.cLanguageStandard = cLanguageStandard\n        self.cxxLanguageStandard = cxxLanguageStandard\n        registerExitHandler()\n    }\n    \n    /// Initializes a Swift package with configuration options you provide.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package, or `nil` to use the package's Git URL to deduce the name.\n    ///   - defaultLocalization: The default localization for resources.\n    ///   - platforms: The list of supported platforms with a custom deployment target.\n    ///   - pkgConfig: The name to use for C modules. If present, Swift Package Manager searches for a\n    ///   `<name>.pc` file to get the additional flags required for a system target.\n    ///   - providers: The package providers for a system target.\n    ///   - products: The list of products that this package makes available for clients to use.\n    ///   - dependencies: The list of package dependencies.\n    ///   - targets: The list of targets that are part of this package.\n    ///   - swiftLanguageModes: The list of Swift language modes with which this package is compatible.\n    ///   - cLanguageStandard: The C language standard to use for all C targets in this package.\n    ///   - cxxLanguageStandard: The C++ language standard to use for all C++ targets in this package.\n    @available(_PackageDescription, introduced: 6)\n    public init(\n        name: String,\n        defaultLocalization: LanguageTag? = nil,\n        platforms: [SupportedPlatform]? = nil,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProvider]? = nil,\n        products: [Product] = [],\n        dependencies: [Dependency] = [],\n        targets: [Target] = [],\n        swiftLanguageModes: [SwiftLanguageMode]? = nil,\n        cLanguageStandard: CLanguageStandard? = nil,\n        cxxLanguageStandard: CXXLanguageStandard? = nil\n    ) {\n        self.name = name\n        self.defaultLocalization = defaultLocalization\n        self.platforms = platforms\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.products = products\n        self.dependencies = dependencies\n        self.targets = targets\n        self.traits = []\n        self.swiftLanguageModes = swiftLanguageModes\n        self.cLanguageStandard = cLanguageStandard\n        self.cxxLanguageStandard = cxxLanguageStandard\n        registerExitHandler()\n    }\n\n\n    /// Initializes a Swift package with configuration options you provide.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the Swift package, or `nil` to use the package's Git URL to deduce the name.\n    ///   - defaultLocalization: The default localization for resources.\n    ///   - platforms: The list of supported platforms with a custom deployment target.\n    ///   - pkgConfig: The name to use for C modules. If present, Swift Package Manager searches for a\n    ///   `<name>.pc` file to get the additional flags required for a system target.\n    ///   - providers: The package providers for a system target.\n    ///   - products: The list of products that this package makes available for clients to use.\n    ///   - traits: The set of traits this package provides.\n    ///   - dependencies: The list of package dependencies.\n    ///   - targets: The list of targets that are part of this package.\n    ///   - swiftLanguageModes: The list of Swift language modes with which this package is compatible.\n    ///   - cLanguageStandard: The C language standard to use for all C targets in this package.\n    ///   - cxxLanguageStandard: The C++ language standard to use for all C++ targets in this package.\n    @available(_PackageDescription, introduced: 6.1)\n    public init(\n        name: String,\n        defaultLocalization: LanguageTag? = nil,\n        platforms: [SupportedPlatform]? = nil,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProvider]? = nil,\n        products: [Product] = [],\n        traits: Set<Trait> = [],\n        dependencies: [Dependency] = [],\n        targets: [Target] = [],\n        swiftLanguageModes: [SwiftLanguageMode]? = nil,\n        cLanguageStandard: CLanguageStandard? = nil,\n        cxxLanguageStandard: CXXLanguageStandard? = nil\n    ) {\n        self.name = name\n        self.defaultLocalization = defaultLocalization\n        self.platforms = platforms\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.products = products\n        self.traits = traits\n        self.dependencies = dependencies\n        self.targets = targets\n        self.swiftLanguageModes = swiftLanguageModes\n        self.cLanguageStandard = cLanguageStandard\n        self.cxxLanguageStandard = cxxLanguageStandard\n        registerExitHandler()\n    }\n\n    private func registerExitHandler() {\n        // Add a custom exit handler to cause the package's JSON representation\n        // to be dumped at exit, if requested.  Emitting it to a separate file\n        // descriptor from stdout keeps any of the manifest's stdout output from\n        // interfering with it.\n        //\n        // FIXME: This doesn't belong here, but for now is the mechanism we use\n        // to get the interpreter to dump the package when attempting to load a\n        // manifest.\n        //\n        // Warning:  The `-fileno` flag is a contract between PackageDescription\n        // and libSwiftPM, and since different versions of the two can be used\n        // together, it isn't safe to rename or remove it.\n        //\n        // Note: `-fileno` is not viable on Windows.  Instead, we pass the file\n        // handle through the `-handle` option.\n#if os(Windows)\n        if let index = CommandLine.arguments.firstIndex(of: \"-handle\") {\n            if let handle = Int(CommandLine.arguments[index + 1], radix: 16) {\n                dumpPackageAtExit(self, to: handle)\n            }\n        }\n#else\n        if let optIdx = CommandLine.arguments.firstIndex(of: \"-fileno\") {\n            if let jsonOutputFileDesc = Int32(CommandLine.arguments[optIdx + 1]) {\n                dumpPackageAtExit(self, to: jsonOutputFileDesc)\n            }\n        }\n#endif\n    }\n}\n\n/// A wrapper around an IETF language tag.\n///\n/// To learn more about the IETF worldwide standard for language tags, see\n/// [RFC5646](https://tools.ietf.org/html/rfc5646).\npublic struct LanguageTag: Hashable {\n\n    /// An IETF BCP 47 standard language tag.\n    let tag: String\n\n    /// Creates a language tag from its [IETF BCP 47](https://datatracker.ietf.org/doc/html/rfc5646) string representation.\n    ///\n    /// - Parameter tag: The string representation of an IETF language tag.\n    private init(_ tag: String) {\n        self.tag = tag\n    }\n}\n\nextension LanguageTag: RawRepresentable {\n    public var rawValue: String { tag }\n\n    /// Creates a new instance with the specified raw value.\n    ///\n    /// If there's no value of the type that corresponds with the specified raw\n    /// value, this initializer returns `nil`.\n    ///\n    /// - Parameter rawValue: The raw value to use for the new instance.\n    public init?(rawValue: String) {\n        tag = rawValue\n    }\n}\n\n/// ExpressibleByStringLiteral implementation.\nextension LanguageTag: ExpressibleByStringLiteral {\n    \n    /// Creates an instance initialized to the given value.\n    ///\n    /// - Parameter value: The value of the new instance.\n    public init(stringLiteral value: String) {\n        tag = value\n    }\n\n    /// Creates an instance initialized to the given value.\n    /// - Parameter value: The value of the new instance.\n    public init(extendedGraphemeClusterLiteral value: String) {\n        self.init(stringLiteral: value)\n    }\n\n    /// Creates an instance initialized to the given value.\n    ///\n    /// - Parameter value: The value of the new instance.\n    public init(unicodeScalarLiteral value: String) {\n        self.init(stringLiteral: value)\n    }\n}\n\nextension LanguageTag: CustomStringConvertible {\n\n    /// A textual representation of the language tag.\n    public var description: String { tag }\n}\n\n/// The system package providers that this package uses.\npublic enum SystemPackageProvider {\n\n    /// Packages installable by the HomeBrew package manager.\n    case brewItem([String])\n    /// Packages installable by the apt-get package manager.\n    case aptItem([String])\n    /// Packages installable by the Yellowdog Updated, Modified (YUM) package manager.\n    @available(_PackageDescription, introduced: 5.3)\n    case yumItem([String])\n    /// Packages installable by the NuGet package manager.\n    @available(_PackageDescription, introduced: 999.0)\n    case nugetItem([String])\n\n    /// Creates a system package provider with a list of installable packages\n    /// for people who use the HomeBrew package manager on macOS.\n    ///\n    /// - Parameter packages: The list of package names.\n    ///\n    /// - Returns: A package provider.\n    public static func brew(_ packages: [String]) -> SystemPackageProvider {\n        return .brewItem(packages)\n    }\n\n    /// Creates a system package provider with a list of installable packages\n    /// for users of the apt-get package manager on Ubuntu Linux.\n    ///\n    /// - Parameter packages: The list of package names.\n    ///\n    /// - Returns: A package provider.\n    public static func apt(_ packages: [String]) -> SystemPackageProvider {\n        return .aptItem(packages)\n    }\n\n    /// Creates a system package provider with a list of installable packages\n    /// for users of the yum package manager on Red Hat Enterprise Linux or\n    /// CentOS.\n    ///\n    /// - Parameter packages: The list of package names.\n    ///\n    /// - Returns: A package provider.\n    @available(_PackageDescription, introduced: 5.3)\n    public static func yum(_ packages: [String]) -> SystemPackageProvider {\n        return .yumItem(packages)\n    }\n\n    /// Creates a system package provider with a list of installable packages\n    /// for users of the NuGet package manager on Linux or Windows.\n    ///\n    /// - Parameter packages: The list of package names.\n    ///\n    /// - Returns: A package provider.\n    @available(_PackageDescription, introduced: 999.0)\n    public static func nuget(_ packages: [String]) -> SystemPackageProvider {\n        return .nugetItem(packages)\n    }\n}\n\n// MARK: - Package Dumping\n\nprivate func manifestToJSON(_ package: Package) -> String {\n    struct Output: Codable {\n        let package: Serialization.Package\n        let errors: [String]\n        let version: Int\n    }\n\n    let encoder = JSONEncoder()\n    encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]\n    let data = try! encoder.encode(Output(package: .init(package), errors: errors, version: 2))\n    return String(decoding: data, as: UTF8.self)\n}\n\nvar errors: [String] = []\n\n#if os(Windows)\nprivate var dumpInfo: (package: Package, handle: Int)?\nprivate func dumpPackageAtExit(_ package: Package, to handle: Int) {\n    let dump: @convention(c) () -> Void = {\n        guard let dumpInfo else { return }\n\n        let hFile: HANDLE = HANDLE(bitPattern: dumpInfo.handle)!\n        // NOTE: `_open_osfhandle` transfers ownership of the `HANDLE` to the file\n        // descriptor.  DO NOT invoke `CloseHandle` on `hFile`.\n        let fd: CInt = _open_osfhandle(Int(bitPattern: hFile), _O_APPEND)\n        // NOTE: `_fdopen` transfers ownership of the file descriptor to the\n        // `FILE *`.  DO NOT invoke `_close` on the `fd`.\n        guard let fp = _fdopen(fd, \"w\") else {\n            _close(fd)\n            return\n        }\n        defer { fclose(fp) }\n\n        fputs(manifestToJSON(dumpInfo.package), fp)\n    }\n\n    dumpInfo = (package, handle)\n    atexit(dump)\n}\n#else\nprivate var dumpInfo: (package: Package, fileDesc: Int32)?\nprivate func dumpPackageAtExit(_ package: Package, to fileDesc: Int32) {\n    func dump() {\n        guard let dumpInfo else { return }\n        guard let fd = fdopen(dumpInfo.fileDesc, \"w\") else { return }\n        fputs(manifestToJSON(dumpInfo.package), fd)\n        fclose(fd)\n    }\n    dumpInfo = (package, fileDesc)\n    atexit(dump)\n}\n#endif\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescriptionSerialization.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import Foundation\n#else\nimport Foundation\n#endif\n\nenum Serialization {\n    // MARK: - build settings serialization\n\n    struct BuildConfiguration: Codable {\n        let config: String\n    }\n\n    struct BuildSettingCondition: Codable {\n        let platforms: [Platform]?\n        let config: BuildConfiguration?\n        let traits: Set<String>?\n    }\n\n    struct BuildSettingData: Codable {\n        let name: String\n        let value: [String]\n        let condition: BuildSettingCondition?\n    }\n\n    struct CSetting: Codable {\n        let data: BuildSettingData\n    }\n\n    struct CXXSetting: Codable {\n        let data: BuildSettingData\n    }\n\n    struct SwiftSetting: Codable {\n        let data: BuildSettingData\n    }\n\n    struct LinkerSetting: Codable {\n        let data: BuildSettingData\n    }\n\n    // MARK: - language standards serialization\n\n    enum CLanguageStandard: String, Codable {\n        case c89\n        case c90\n        case c99\n        case c11\n        case c17\n        case c18\n        case c2x\n        case gnu89\n        case gnu90\n        case gnu99\n        case gnu11\n        case gnu17\n        case gnu18\n        case gnu2x\n        case iso9899_1990 = \"iso9899:1990\"\n        case iso9899_199409 = \"iso9899:199409\"\n        case iso9899_1999 = \"iso9899:1999\"\n        case iso9899_2011 = \"iso9899:2011\"\n        case iso9899_2017 = \"iso9899:2017\"\n        case iso9899_2018 = \"iso9899:2018\"\n    }\n\n    enum CXXLanguageStandard: String, Codable {\n        case cxx98 = \"c++98\"\n        case cxx03 = \"c++03\"\n        case cxx11 = \"c++11\"\n        case cxx14 = \"c++14\"\n        case cxx17 = \"c++17\"\n        case cxx1z = \"c++1z\"\n        case cxx20 = \"c++20\"\n        case cxx2b = \"c++2b\"\n        case gnucxx98 = \"gnu++98\"\n        case gnucxx03 = \"gnu++03\"\n        case gnucxx11 = \"gnu++11\"\n        case gnucxx14 = \"gnu++14\"\n        case gnucxx17 = \"gnu++17\"\n        case gnucxx1z = \"gnu++1z\"\n        case gnucxx20 = \"gnu++20\"\n        case gnucxx2b = \"gnu++2b\"\n    }\n\n    enum SwiftVersion: Codable {\n        case v3\n        case v4\n        case v4_2\n        case v5\n        case v6\n        case version(String)\n    }\n\n    // MARK: - version serialization\n\n    struct Version: Codable {\n        let major: Int\n        let minor: Int\n        let patch: Int\n        let prereleaseIdentifiers: [String]\n        let buildMetadataIdentifiers: [String]\n    }\n\n    // MARK: - package dependency serialization\n\n    struct PackageDependency: Codable {\n        struct Trait: Hashable, Codable {\n            struct Condition: Hashable, Codable {\n                let traits: Set<String>?\n            }\n\n            var name: String\n            var condition: Condition?\n        }\n        enum SourceControlRequirement: Codable {\n            case exact(Version)\n            case range(lowerBound: Version, upperBound: Version)\n            case revision(String)\n            case branch(String)\n        }\n\n        enum RegistryRequirement: Codable {\n            case exact(Version)\n            case range(lowerBound: Version, upperBound: Version)\n        }\n\n        enum Kind: Codable {\n            case fileSystem(name: String?, path: String)\n            case sourceControl(name: String?, location: String, requirement: SourceControlRequirement)\n            case registry(id: String, requirement: RegistryRequirement)\n        }\n\n        let kind: Kind\n        let moduleAliases: [String: String]?\n        let traits: Set<Trait>?\n    }\n\n    // MARK: - platforms serialization\n\n    struct Platform: Codable {\n        let name: String\n    }\n\n    struct SupportedPlatform: Codable {\n        let platform: Platform\n        let version: String?\n    }\n\n    // MARK: - target serialization\n\n    enum TargetDependency: Codable {\n        struct Condition: Codable {\n            let platforms: [Platform]?\n            let traits: Set<String>?\n        }\n\n        case target(name: String, condition: Condition?)\n        case product(name: String, package: String?, moduleAliases: [String: String]?, condition: Condition?)\n        case byName(name: String, condition: Condition?)\n    }\n\n    enum TargetType: Codable {\n        case regular\n        case executable\n        case test\n        case system\n        case binary\n        case plugin\n        case `macro`\n    }\n\n    enum PluginCapability: Codable {\n        case buildTool\n        case command(intent: PluginCommandIntent, permissions: [PluginPermission])\n    }\n\n    enum PluginCommandIntent: Codable {\n        case documentationGeneration\n        case sourceCodeFormatting\n        case custom(verb: String, description: String)\n    }\n\n    enum PluginPermission: Codable {\n        case allowNetworkConnections(scope: PluginNetworkPermissionScope, reason: String)\n        case writeToPackageDirectory(reason: String)\n    }\n\n    enum PluginNetworkPermissionScope: Codable {\n        case none\n        case local(ports: [Int])\n        case all(ports: [Int])\n        case docker\n        case unixDomainSocket\n    }\n\n    enum PluginUsage: Codable {\n        case plugin(name: String, package: String?)\n    }\n\n    struct Target: Codable {\n        let name: String\n        let path: String?\n        let url: String?\n        let sources: [String]?\n        let resources: [Resource]?\n        let exclude: [String]\n        let dependencies: [TargetDependency]\n        let publicHeadersPath: String?\n        let type: TargetType\n        let packageAccess: Bool\n        let pkgConfig: String?\n        let providers: [SystemPackageProvider]?\n        let pluginCapability: PluginCapability?\n        let cSettings: [CSetting]?\n        let cxxSettings: [CXXSetting]?\n        let swiftSettings: [SwiftSetting]?\n        let linkerSettings: [LinkerSetting]?\n        let checksum: String?\n        let pluginUsages: [PluginUsage]?\n    }\n\n    // MARK: - resource serialization\n\n    struct Resource: Codable {\n        enum Localization: String, Codable {\n            case `default`\n            case base\n        }\n\n        let rule: String\n        let path: String\n        let localization: Localization?\n    }\n\n    // MARK: - product serialization\n\n    struct Product: Codable {\n        enum ProductType: Codable {\n            enum LibraryType: Codable {\n                case automatic\n                case dynamic\n                case `static`\n            }\n\n            case executable\n            case library(type: LibraryType)\n            case plugin\n        }\n\n        let name: String\n        let targets: [String]\n        let productType: ProductType\n\n        #if ENABLE_APPLE_PRODUCT_TYPES\n        let settings: [ProductSetting]\n        #endif\n    }\n\n    // MARK: - trait serialization\n\n    struct Trait: Hashable, Codable {\n        let name: String\n        let description: String?\n        let enabledTraits: Set<String>\n    }\n\n    // MARK: - package serialization\n\n    struct LanguageTag: Codable {\n        let tag: String\n    }\n\n    enum SystemPackageProvider: Codable {\n        case brew([String])\n        case apt([String])\n        case yum([String])\n        case nuget([String])\n    }\n\n    struct Package: Codable {\n        let name: String\n        let platforms: [SupportedPlatform]?\n        let defaultLocalization: LanguageTag?\n        let pkgConfig: String?\n        let providers: [SystemPackageProvider]?\n        let targets: [Target]\n        let products: [Product]\n        let traits: Set<Trait>?\n        let dependencies: [PackageDependency]\n        let swiftLanguageVersions: [SwiftVersion]?\n        let cLanguageStandard: CLanguageStandard?\n        let cxxLanguageStandard: CXXLanguageStandard?\n    }\n}\n\n#if ENABLE_APPLE_PRODUCT_TYPES\nextension Serialization {\n    enum ProductSetting: Codable {\n        case bundleIdentifier(String)\n        case teamIdentifier(String)\n        case displayVersion(String)\n        case bundleVersion(String)\n        case iOSAppInfo(IOSAppInfo)\n        \n        struct IOSAppInfo: Codable {\n            var appIcon: AppIcon?\n            var accentColor: AccentColor?\n            var supportedDeviceFamilies: [DeviceFamily]\n            var supportedInterfaceOrientations: [InterfaceOrientation]\n            var capabilities: [Capability] = []\n            var appCategory: AppCategory?\n            var additionalInfoPlistContentFilePath: String?\n            \n            enum AccentColor: Codable {\n                struct PresetColor: Codable {\n                    var rawValue: String\n                }\n                \n                case presetColor(PresetColor)\n                case asset(String)\n            }\n            \n            enum AppIcon: Codable {\n                struct PlaceholderIcon: Codable {\n                    var rawValue: String\n                }\n                \n                case placeholder(icon: PlaceholderIcon)\n                case asset(String)\n            }\n            \n            enum DeviceFamily: String, Codable {\n                case phone\n                case pad\n                case mac\n            }\n            \n            struct DeviceFamilyCondition: Codable {\n                var deviceFamilies: [DeviceFamily]\n            }\n            \n            enum InterfaceOrientation: Codable {\n                case portrait(_ condition: DeviceFamilyCondition? = nil)\n                case portraitUpsideDown(_ condition: DeviceFamilyCondition? = nil)\n                case landscapeRight(_ condition: DeviceFamilyCondition? = nil)\n                case landscapeLeft(_ condition: DeviceFamilyCondition? = nil)\n            }\n            \n            enum Capability: Codable {\n                case appTransportSecurity(configuration: AppTransportSecurityConfiguration, _ condition: DeviceFamilyCondition? = nil)\n                case bluetoothAlways(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case calendars(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case camera(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case contacts(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case faceID(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case fileAccess(_ location: FileAccessLocation, mode: FileAccessMode, _ condition: DeviceFamilyCondition? = nil)\n                case incomingNetworkConnections(_ condition: DeviceFamilyCondition? = nil)\n                case localNetwork(purposeString: String, bonjourServiceTypes: [String]? = nil, _ condition: DeviceFamilyCondition? = nil)\n                case locationAlwaysAndWhenInUse(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case locationWhenInUse(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case mediaLibrary(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case microphone(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case motion(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case nearbyInteractionAllowOnce(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case outgoingNetworkConnections(_ condition: DeviceFamilyCondition? = nil)\n                case photoLibrary(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case photoLibraryAdd(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case reminders(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case speechRecognition(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n                case userTracking(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            }\n            \n            struct AppTransportSecurityConfiguration: Codable {\n                var allowsArbitraryLoadsInWebContent: Bool? = nil\n                var allowsArbitraryLoadsForMedia: Bool? = nil\n                var allowsLocalNetworking: Bool? = nil\n                var exceptionDomains: [ExceptionDomain]? = nil\n                var pinnedDomains: [PinnedDomain]? = nil\n                \n                struct ExceptionDomain: Codable {\n                    var domainName: String\n                    var includesSubdomains: Bool? = nil\n                    var exceptionAllowsInsecureHTTPLoads: Bool? = nil\n                    var exceptionMinimumTLSVersion: String? = nil\n                    var exceptionRequiresForwardSecrecy: Bool? = nil\n                    var requiresCertificateTransparency: Bool? = nil\n                }\n                \n                struct PinnedDomain: Codable {\n                    var domainName: String\n                    var includesSubdomains : Bool? = nil\n                    var pinnedCAIdentities : [[String: String]]? = nil\n                    var pinnedLeafIdentities : [[String: String]]? = nil\n                }\n            }\n            \n            enum FileAccessLocation: String, Codable {\n                case userSelectedFiles\n                case downloadsFolder\n                case pictureFolder\n                case musicFolder\n                case moviesFolder\n            }\n            \n            enum FileAccessMode: String, Codable {\n                case readOnly\n                case readWrite\n            }\n            \n            struct AppCategory: Codable {\n                var rawValue: String\n            }\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageDescriptionSerializationConversion.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension Serialization.BuildConfiguration {\n    init(_ configuration: PackageDescription.BuildConfiguration) {\n        self.config = configuration.config\n    }\n}\n\nextension Serialization.BuildSettingCondition {\n    init(_ condition: PackageDescription.BuildSettingCondition) {\n        self.platforms = condition.platforms?.map { .init($0) }\n        self.config = condition.config.map { .init($0) }\n        self.traits = condition.traits\n    }\n}\n\nextension Serialization.BuildSettingData {\n    init(_ settingsData: PackageDescription.BuildSettingData) {\n        self.name = settingsData.name\n        self.value = settingsData.value\n        self.condition = settingsData.condition.map { .init($0) }\n    }\n}\n\nextension Serialization.CSetting {\n    init(_ setting: PackageDescription.CSetting) {\n        self.data = .init(setting.data)\n    }\n}\n\nextension Serialization.CXXSetting {\n    init(_ setting: PackageDescription.CXXSetting) {\n        self.data = .init(setting.data)\n    }\n}\n\nextension Serialization.SwiftSetting {\n    init(_ setting: PackageDescription.SwiftSetting) {\n        self.data = .init(setting.data)\n    }\n}\n\nextension Serialization.LinkerSetting {\n    init(_ setting: PackageDescription.LinkerSetting) {\n        self.data = .init(setting.data)\n    }\n}\n\nextension Serialization.CLanguageStandard {\n    init(_ languageStandard: PackageDescription.CLanguageStandard) {\n        switch languageStandard {\n        case .c89: self = .c89\n        case .c90: self = .c90\n        case .c99: self = .c99\n        case .c11: self = .c11\n        case .c17: self = .c17\n        case .c18: self = .c18\n        case .c2x: self = .c2x\n        case .gnu89: self = .gnu89\n        case .gnu90: self = .gnu90\n        case .gnu99: self = .gnu99\n        case .gnu11: self = .gnu11\n        case .gnu17: self = .gnu17\n        case .gnu18: self = .gnu18\n        case .gnu2x: self = .gnu2x\n        case .iso9899_1990: self = .iso9899_1990\n        case .iso9899_199409: self = .iso9899_199409\n        case .iso9899_1999: self = .iso9899_1999\n        case .iso9899_2011: self = .iso9899_2011\n        case .iso9899_2017: self = .iso9899_2017\n        case .iso9899_2018: self = .iso9899_2018\n        }\n    }\n}\n\nextension Serialization.CXXLanguageStandard {\n    init(_ languageStandard: PackageDescription.CXXLanguageStandard) {\n        switch languageStandard {\n        case .cxx98: self = .cxx98\n        case .cxx03: self = .cxx03\n        case .cxx11: self = .cxx11\n        case .cxx14: self = .cxx14\n        case .cxx17: self = .cxx17\n        case .cxx1z: self = .cxx1z\n        case .cxx20: self = .cxx20\n        case .cxx2b: self = .cxx2b\n        case .gnucxx98: self = .gnucxx98\n        case .gnucxx03: self = .gnucxx03\n        case .gnucxx11: self = .gnucxx11\n        case .gnucxx14: self = .gnucxx14\n        case .gnucxx17: self = .gnucxx17\n        case .gnucxx1z: self = .gnucxx1z\n        case .gnucxx20: self = .gnucxx20\n        case .gnucxx2b: self = .gnucxx2b\n        }\n    }\n}\n\nextension Serialization.SwiftVersion {\n    init(_ swiftVersion: PackageDescription.SwiftLanguageMode) {\n        switch swiftVersion {\n        case .v3: self = .v3\n        case .v4: self = .v4\n        case .v4_2: self = .v4_2\n        case .v5: self = .v5\n        case .v6: self = .v6\n        case .version(let version): self = .version(version)\n        }\n    }\n}\n\nextension Serialization.Version {\n    init(_ version: PackageDescription.Version) {\n        self.major = version.major\n        self.minor = version.minor\n        self.patch = version.patch\n        self.prereleaseIdentifiers = version.prereleaseIdentifiers\n        self.buildMetadataIdentifiers = version.buildMetadataIdentifiers\n    }\n}\n\nextension Serialization.PackageDependency.SourceControlRequirement {\n    init(_ requirement: PackageDescription.Package.Dependency.SourceControlRequirement) {\n        switch requirement {\n        case .range(let range):\n            self = .range(lowerBound: .init(range.lowerBound), upperBound: .init(range.upperBound))\n        case .exact(let version):\n            self = .exact(.init(version))\n        case .revision(let revision):\n            self = .revision(revision)\n        case .branch(let branch):\n            self = .branch(branch)\n        }\n    }\n}\n\nextension Serialization.PackageDependency.RegistryRequirement {\n    init(_ requirement: PackageDescription.Package.Dependency.RegistryRequirement) {\n        switch requirement {\n        case .exact(let version):\n            self = .exact(.init(version))\n        case .range(let range):\n            self = .range(lowerBound: .init(range.lowerBound), upperBound: .init(range.upperBound))\n        }\n    }\n}\n\nextension Serialization.PackageDependency.Kind {\n    init(_ kind: PackageDescription.Package.Dependency.Kind) {\n        switch kind {\n        case .fileSystem(let name, let path):\n            self = .fileSystem(name: name, path: path)\n        case .sourceControl(let name, let location, let requirement):\n            self = .sourceControl(name: name, location: location, requirement: .init(requirement))\n        case .registry(let identity, let requirement):\n            self = .registry(id: identity, requirement: .init(requirement))\n        }\n    }\n}\n\nextension Serialization.PackageDependency {\n    init(_ dependency: PackageDescription.Package.Dependency) {\n        self.kind = .init(dependency.kind)\n        self.moduleAliases = dependency.moduleAliases\n        self.traits = Set(dependency.traits.map { Serialization.PackageDependency.Trait.init($0) })\n    }\n}\n\nextension Serialization.PackageDependency.Trait {\n    init(_ trait: PackageDescription.Package.Dependency.Trait) {\n        self.name = trait.name\n        self.condition = trait.condition.flatMap { .init($0) }\n    }\n}\n\nextension Serialization.PackageDependency.Trait.Condition {\n    init(_ condition: PackageDescription.Package.Dependency.Trait.Condition) {\n        self.traits = condition.traits\n    }\n}\n\nextension Serialization.Platform {\n    init(_ platform: PackageDescription.Platform) {\n        self.name = platform.name\n    }\n}\n\nextension Serialization.SupportedPlatform {\n    init(_ platform: PackageDescription.SupportedPlatform) {\n        self.platform = .init(platform.platform)\n        self.version = platform.version\n    }\n}\n\nextension Serialization.TargetDependency.Condition {\n    init(_ condition: TargetDependencyCondition) {\n        self.platforms = condition.platforms?.map { .init($0) }\n        self.traits = condition.traits\n    }\n}\n\nextension Serialization.TargetDependency {\n    init(_ dependency: PackageDescription.Target.Dependency) {\n        switch dependency {\n        case .targetItem(let name, let condition):\n            self = .target(name: name, condition: condition.map { .init($0) })\n        case .productItem(let name, let package, let moduleAliases, let condition):\n            self = .product(\n                name: name,\n                package: package,\n                moduleAliases: moduleAliases,\n                condition: condition.map { .init($0) }\n            )\n        case .byNameItem(let name, let condition):\n            self = .byName(name: name, condition: condition.map { .init($0) })\n        }\n    }\n}\n\nextension Serialization.TargetType {\n    init(_ type: PackageDescription.Target.TargetType) {\n        switch type {\n        case .regular: self = .regular\n        case .executable: self = .executable\n        case .test: self = .test\n        case .system: self = .system\n        case .binary: self = .binary\n        case .plugin: self = .plugin\n        case .macro: self = .macro\n        }\n    }\n}\n\nextension Serialization.PluginCapability {\n    init(_ capability: PackageDescription.Target.PluginCapability) {\n        switch capability {\n        case .buildTool: self = .buildTool\n        case .command(let intent, let permissions): self = .command(\n                intent: .init(intent),\n                permissions: permissions.map { .init($0) }\n            )\n        }\n    }\n}\n\nextension Serialization.PluginCommandIntent {\n    init(_ intent: PackageDescription.PluginCommandIntent) {\n        switch intent {\n        case .custom(let verb, let description): self = .custom(verb: verb, description: description)\n        case .sourceCodeFormatting: self = .sourceCodeFormatting\n        case .documentationGeneration: self = .documentationGeneration\n        }\n    }\n}\n\nextension Serialization.PluginPermission {\n    init(_ permission: PackageDescription.PluginPermission) {\n        switch permission {\n        case .allowNetworkConnections(let scope, let reason): self = .allowNetworkConnections(\n                scope: .init(scope),\n                reason: reason\n            )\n        case .writeToPackageDirectory(let reason): self = .writeToPackageDirectory(reason: reason)\n        }\n    }\n}\n\nextension Serialization.PluginNetworkPermissionScope {\n    init(_ scope: PackageDescription.PluginNetworkPermissionScope) {\n        switch scope {\n        case .none: self = .none\n        case .local(let ports): self = .local(ports: ports)\n        case .all(let ports): self = .all(ports: ports)\n        case .docker: self = .docker\n        case .unixDomainSocket: self = .unixDomainSocket\n        }\n    }\n}\n\nextension Serialization.PluginUsage {\n    init(_ usage: PackageDescription.Target.PluginUsage) {\n        switch usage {\n        case .plugin(let name, let package): self = .plugin(name: name, package: package)\n        }\n    }\n}\n\nextension Serialization.Target {\n    init(_ target: PackageDescription.Target) {\n        self.name = target.name\n        self.packageAccess = target.packageAccess\n        self.path = target.path\n        self.url = target.url\n        self.sources = target.sources\n        self.resources = target.resources?.map { .init($0) }\n        self.exclude = target.exclude\n        self.dependencies = target.dependencies.map { .init($0) }\n        self.publicHeadersPath = target.publicHeadersPath\n        self.type = .init(target.type)\n        self.pkgConfig = target.pkgConfig\n        self.providers = target.providers?.map { .init($0) }\n        self.pluginCapability = target.pluginCapability.map { .init($0) }\n        self.cSettings = target.cSettings?.map { .init($0) }\n        self.cxxSettings = target.cxxSettings?.map { .init($0) }\n        self.swiftSettings = target.swiftSettings?.map { .init($0) }\n        self.linkerSettings = target.linkerSettings?.map { .init($0) }\n        self.checksum = target.checksum\n        self.pluginUsages = target.plugins?.map { .init($0) }\n    }\n}\n\nextension Serialization.Resource {\n    init(_ resource: PackageDescription.Resource) {\n        self.rule = resource.rule\n        self.path = resource.path\n        self.localization = resource.localization.map { .init($0) }\n    }\n}\n\nextension Serialization.Resource.Localization {\n    init(_ localization: PackageDescription.Resource.Localization) {\n        switch localization {\n        case .base: self = .base\n        case .default: self = .default\n        }\n    }\n}\n\nextension Serialization.Product.ProductType.LibraryType {\n    init(_ type: PackageDescription.Product.Library.LibraryType) {\n        switch type {\n        case .dynamic: self = .dynamic\n        case .static: self = .static\n        }\n    }\n}\n\nextension Serialization.Product {\n    init(_ product: PackageDescription.Product) {\n        if let executable = product as? PackageDescription.Product.Executable {\n            self.init(executable)\n        } else if let library = product as? PackageDescription.Product.Library {\n            self.init(library)\n        } else if let plugin = product as? PackageDescription.Product.Plugin {\n            self.init(plugin)\n        } else {\n            fatalError(\"should not be reached\")\n        }\n    }\n\n    init(_ executable: PackageDescription.Product.Executable) {\n        self.name = executable.name\n        self.targets = executable.targets\n        self.productType = .executable\n        #if ENABLE_APPLE_PRODUCT_TYPES\n        self.settings = executable.settings.map { .init($0) }\n        #endif\n    }\n\n    init(_ library: PackageDescription.Product.Library) {\n        self.name = library.name\n        self.targets = library.targets\n        let libraryType = library.type.map { ProductType.LibraryType($0) } ?? .automatic\n        self.productType = .library(type: libraryType)\n        #if ENABLE_APPLE_PRODUCT_TYPES\n        self.settings = []\n        #endif\n    }\n\n    init(_ plugin: PackageDescription.Product.Plugin) {\n        self.name = plugin.name\n        self.targets = plugin.targets\n        self.productType = .plugin\n        #if ENABLE_APPLE_PRODUCT_TYPES\n        self.settings = []\n        #endif\n    }\n}\n\nextension Serialization.Trait {\n    init(_ trait: PackageDescription.Trait) {\n        self.name = trait.name\n        self.description = trait.description\n        self.enabledTraits = trait.enabledTraits\n    }\n}\n\nextension Serialization.Package {\n    init(_ package: PackageDescription.Package) {\n        self.name = package.name\n        self.platforms = package.platforms?.map { .init($0) }\n        self.defaultLocalization = package.defaultLocalization.map { .init($0) }\n        self.pkgConfig = package.pkgConfig\n        self.providers = package.providers?.map { .init($0) }\n        self.targets = package.targets.map { .init($0) }\n        self.products = package.products.map { .init($0) }\n        self.traits = Set(package.traits.map { Serialization.Trait($0) })\n        self.dependencies = package.dependencies.map { .init($0) }\n        self.swiftLanguageVersions = package.swiftLanguageModes?.map { .init($0) }\n        self.cLanguageStandard = package.cLanguageStandard.map { .init($0) }\n        self.cxxLanguageStandard = package.cxxLanguageStandard.map { .init($0) }\n    }\n}\n\nextension Serialization.LanguageTag {\n    init(_ language: PackageDescription.LanguageTag) {\n        self.tag = language.tag\n    }\n}\n\nextension Serialization.SystemPackageProvider {\n    init(_ provider: PackageDescription.SystemPackageProvider) {\n        switch provider {\n        case .brewItem(let values): self = .brew(values)\n        case .aptItem(let values): self = .apt(values)\n        case .yumItem(let values): self = .yum(values)\n        case .nugetItem(let values): self = .nuget(values)\n        }\n    }\n}\n\n#if ENABLE_APPLE_PRODUCT_TYPES\nextension Serialization.ProductSetting {\n    init(_ setting: PackageDescription.ProductSetting) {\n        switch setting {\n        case .bundleIdentifier(let value):\n            self = .bundleIdentifier(value)\n        case .teamIdentifier(let value):\n            self = .teamIdentifier(value)\n        case .displayVersion(let value):\n            self = .displayVersion(value)\n        case .bundleVersion(let value):\n            self = .bundleVersion(value)\n        case .iOSAppInfo(let appInfo):\n            self = .iOSAppInfo(.init(appInfo))\n        }\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo {\n    init(_ appInfo: PackageDescription.ProductSetting.IOSAppInfo) {\n        self.init(\n            appIcon: appInfo.appIcon.map { .init($0) },\n            accentColor: appInfo.accentColor.map { .init($0) },\n            supportedDeviceFamilies: appInfo.supportedDeviceFamilies.map { .init($0) },\n            supportedInterfaceOrientations: appInfo.supportedInterfaceOrientations.map { .init($0) },\n            capabilities: appInfo.capabilities.map { .init($0) },\n            appCategory: appInfo.appCategory.map { .init($0) },\n            additionalInfoPlistContentFilePath: appInfo.additionalInfoPlistContentFilePath\n        )\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.AccentColor {\n    init(_ color: PackageDescription.ProductSetting.IOSAppInfo.AccentColor) {\n        switch color {\n        case .presetColor(let color):\n            self = .presetColor(.init(color))\n        case .asset(let value):\n            self = .asset(value)\n        }\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.AccentColor.PresetColor {\n    init(_ color: PackageDescription.ProductSetting.IOSAppInfo.AccentColor.PresetColor) {\n        self.rawValue = color.rawValue\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.AppIcon {\n    init(_ icon: PackageDescription.ProductSetting.IOSAppInfo.AppIcon) {\n        switch icon {\n        case .placeholder(icon: let icon):\n            self = .placeholder(icon: .init(icon))\n        case .asset(let value):\n            self = .asset(value)\n        }\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.AppIcon.PlaceholderIcon {\n    init(_ icon: PackageDescription.ProductSetting.IOSAppInfo.AppIcon.PlaceholderIcon) {\n        self.rawValue = icon.rawValue\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.DeviceFamily {\n    init(_ deviceFamily: PackageDescription.ProductSetting.IOSAppInfo.DeviceFamily) {\n        switch deviceFamily {\n        case .phone: self = .phone\n        case .pad: self = .pad\n        case .mac: self = .mac\n        }\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.DeviceFamilyCondition {\n    init(_ condition: PackageDescription.ProductSetting.IOSAppInfo.DeviceFamilyCondition) {\n        self.init(deviceFamilies: condition.deviceFamilies.map { .init($0) })\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.InterfaceOrientation {\n    init(_ interfaceOrientation: PackageDescription.ProductSetting.IOSAppInfo.InterfaceOrientation) {\n        switch interfaceOrientation {\n        case .portrait(let condition):\n            self = .portrait(condition.map { .init($0) })\n        case .portraitUpsideDown(let condition):\n            self = .portraitUpsideDown(condition.map { .init($0) })\n        case .landscapeRight(let condition):\n            self = .landscapeRight(condition.map { .init($0) })\n        case .landscapeLeft(let condition):\n            self = .landscapeLeft(condition.map { .init($0) })\n        }\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.Capability {\n    init(_ capability: PackageDescription.ProductSetting.IOSAppInfo.Capability) {\n        switch capability {\n        case .appTransportSecurity(configuration: let configuration, let condition):\n            self = .appTransportSecurity(configuration: .init(configuration), condition.map { .init($0) })\n        case .bluetoothAlways(purposeString: let purposeString, let condition):\n            self = .bluetoothAlways(purposeString: purposeString, condition.map { .init($0) })\n        case .calendars(purposeString: let purposeString, let condition):\n            self = .calendars(purposeString: purposeString, condition.map { .init($0) })\n        case .camera(purposeString: let purposeString, let condition):\n            self = .camera(purposeString: purposeString, condition.map { .init($0) })\n        case .contacts(purposeString: let purposeString, let condition):\n            self = .contacts(purposeString: purposeString, condition.map { .init($0) })\n        case .faceID(purposeString: let purposeString, let condition):\n            self = .faceID(purposeString: purposeString, condition.map { .init($0) })\n        case .fileAccess(let location, let mode, let condition):\n            self = .fileAccess(.init(location), mode: .init(mode), condition.map { .init($0) })\n        case .incomingNetworkConnections(let condition):\n            self = .incomingNetworkConnections(condition.map { .init($0) })\n        case .localNetwork(purposeString: let purposeString, bonjourServiceTypes: let bonjourServiceTypes, let condition):\n            self = .localNetwork(purposeString: purposeString, bonjourServiceTypes: bonjourServiceTypes, condition.map { .init($0) })\n        case .locationAlwaysAndWhenInUse(purposeString: let purposeString, let condition):\n            self = .locationAlwaysAndWhenInUse(purposeString: purposeString, condition.map { .init($0) })\n        case .locationWhenInUse(purposeString: let purposeString, let condition):\n            self = .locationWhenInUse(purposeString: purposeString, condition.map { .init($0) })\n        case .mediaLibrary(purposeString: let purposeString, let condition):\n            self = .mediaLibrary(purposeString: purposeString, condition.map { .init($0) })\n        case .microphone(purposeString: let purposeString, let condition):\n            self = .microphone(purposeString: purposeString, condition.map { .init($0) })\n        case .motion(purposeString: let purposeString, let condition):\n            self = .motion(purposeString: purposeString, condition.map { .init($0) })\n        case .nearbyInteractionAllowOnce(purposeString: let purposeString, let condition):\n            self = .nearbyInteractionAllowOnce(purposeString: purposeString, condition.map { .init($0) })\n        case .outgoingNetworkConnections(let condition):\n            self = .outgoingNetworkConnections(condition.map { .init($0) })\n        case .photoLibrary(purposeString: let purposeString, let condition):\n            self = .photoLibrary(purposeString: purposeString, condition.map { .init($0) })\n        case .photoLibraryAdd(purposeString: let purposeString, let condition):\n            self = .photoLibraryAdd(purposeString: purposeString, condition.map { .init($0) })\n        case .reminders(purposeString: let purposeString, let condition):\n            self = .reminders(purposeString: purposeString, condition.map { .init($0) })\n        case .speechRecognition(purposeString: let purposeString, let condition):\n            self = .speechRecognition(purposeString: purposeString, condition.map { .init($0) })\n        case .userTracking(purposeString: let purposeString, let condition):\n            self = .userTracking(purposeString: purposeString, condition.map { .init($0) })\n        }\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration {\n    init(_ configuration: PackageDescription.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration) {\n        self.init(\n            allowsArbitraryLoadsInWebContent: configuration.allowsArbitraryLoadsInWebContent,\n            allowsArbitraryLoadsForMedia: configuration.allowsArbitraryLoadsForMedia,\n            allowsLocalNetworking: configuration.allowsLocalNetworking,\n            exceptionDomains: configuration.exceptionDomains?.map { .init($0) },\n            pinnedDomains: configuration.pinnedDomains?.map { .init($0) }\n        )\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.ExceptionDomain {\n    init(_ exceptionDomain: PackageDescription.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.ExceptionDomain) {\n        self.init(\n            domainName: exceptionDomain.domainName,\n            includesSubdomains: exceptionDomain.includesSubdomains,\n            exceptionAllowsInsecureHTTPLoads: exceptionDomain.exceptionAllowsInsecureHTTPLoads,\n            exceptionMinimumTLSVersion: exceptionDomain.exceptionMinimumTLSVersion,\n            exceptionRequiresForwardSecrecy: exceptionDomain.exceptionRequiresForwardSecrecy,\n            requiresCertificateTransparency: exceptionDomain.requiresCertificateTransparency\n        )\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.PinnedDomain {\n    init(_ pinnedDomain: PackageDescription.ProductSetting.IOSAppInfo.AppTransportSecurityConfiguration.PinnedDomain) {\n        self.init(\n            domainName: pinnedDomain.domainName,\n            includesSubdomains: pinnedDomain.includesSubdomains,\n            pinnedCAIdentities: pinnedDomain.pinnedCAIdentities,\n            pinnedLeafIdentities: pinnedDomain.pinnedLeafIdentities\n        )\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.FileAccessLocation {\n    init(_ fileAccessLocation: PackageDescription.ProductSetting.IOSAppInfo.FileAccessLocation) {\n        switch fileAccessLocation {\n        case .userSelectedFiles: self = .userSelectedFiles\n        case .downloadsFolder: self = .downloadsFolder\n        case .pictureFolder: self = .pictureFolder\n        case .musicFolder: self = .musicFolder\n        case .moviesFolder: self = .moviesFolder\n        }\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.FileAccessMode {\n    init(_ fileAccessNode: PackageDescription.ProductSetting.IOSAppInfo.FileAccessMode) {\n        switch fileAccessNode {\n        case .readOnly: self = .readOnly\n        case .readWrite: self = .readWrite\n        }\n    }\n}\n\nextension Serialization.ProductSetting.IOSAppInfo.AppCategory {\n    init(_ appCategory: PackageDescription.ProductSetting.IOSAppInfo.AppCategory) {\n        self.rawValue = appCategory.rawValue\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/PackageRequirement.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension Package.Dependency {\n    /// An enum that represents the requirement for a package dependency.\n    ///\n    /// The dependency requirement can be defined as one of three different\n    /// version requirements:\n    ///\n    /// - term A version-based requirement: Decide whether your project accepts\n    /// updates to a package dependency up to the next major version or up to\n    /// the next minor version. To be more restrictive, select a specific\n    /// version range or an exact version. Major versions tend to have more\n    /// significant changes than minor versions, and may require you to modify\n    /// your code when they update.\n    ///\n    /// The version rule requires Swift packages to conform to semantic\n    /// versioning. To learn more about the semantic versioning standard, visit the\n    /// [Semantic Versioning 2.0.0](https://semver.org) website.\n    ///\n    /// Selecting the version requirement is the recommended way to add a\n    /// package dependency. It allows you to create a balance between\n    /// restricting changes and obtaining improvements and features. - term A\n    /// branch-based requirement: Select the name of the branch for your package\n    /// dependency to follow. Use branch-based dependencies when you're\n    /// developing multiple packages in tandem or when you don't want to publish\n    /// versions of your package dependencies.\n    ///\n    /// Note that packages which use branch-based dependency requirements can't\n    /// be added as dependencies to packages that use version-based dependency\n    /// requirements; you should remove branch-based dependency requirements\n    /// before publishing a version of your package. - term A commit-based\n    /// requirement: Select the commit hash for your package dependency to\n    /// follow.\n    ///\n    /// Choosing this option isn't recommended, and should be limited to\n    /// exceptional cases. While pinning your package dependency to a specific\n    /// commit ensures that the package dependency doesn't change and your code\n    /// remains stable, you don't receive any updates at all. If you worry about\n    /// the stability of a remote package, consider one of the more restrictive\n    /// options of the version-based requirement.\n    ///\n    /// Note that packages which use commit-based dependency requirements can't\n    /// be added as dependencies to packages that use version-based dependency\n    /// requirements; you should remove commit-based dependency requirements\n    /// before publishing a version of your package.\n    @available(_PackageDescription, deprecated: 5.6)\n    public enum Requirement {\n        case exactItem(Version)\n        case rangeItem(Range<Version>)\n        case revisionItem(String)\n        case branchItem(String)\n        case localPackageItem\n\n        var isLocalPackage: Bool {\n            if case .localPackageItem = self { return true }\n            return false\n        }\n    }\n}\n\n@available(_PackageDescription, deprecated: 5.6)\nextension Package.Dependency.Requirement {\n    /// Returns a requirement for the given exact version.\n    ///\n    /// Specifying exact version requirements are not recommended as they can\n    /// cause conflicts in your dependency graph when multiple other packages\n    /// depend on a package. As Swift packages follow the semantic versioning\n    /// convention, think about specifying a version range instead.\n    ///\n    /// The following example defines a version requirement that requires\n    /// version 1.2.3 of a package.\n    ///\n    /// ```swift\n    /// .exact(“1.2.3”)\n    /// ```\n    ///\n    /// - Parameter version: The exact version of the dependency for this requirement.\n    @available(_PackageDescription, deprecated: 5.6)\n    public static func exact(_ version: Version) -> Package.Dependency.Requirement {\n        return .exactItem(version)\n    }\n\n    /// Returns a requirement for a source control revision such as the hash of\n    /// a commit.\n    ///\n    /// Note that packages that use commit-based dependency requirements can't\n    /// be depended upon by packages that use version-based dependency\n    /// requirements; you should remove commit-based dependency requirements\n    /// before publishing a version of your package.\n    ///\n    /// The following example defines a version requirement for a specific\n    /// commit hash.\n    ///\n    ///```swift\n    /// .revision(“e74b07278b926c9ec6f9643455ea00d1ce04a021”)\n    /// ```\n    ///\n    /// - Parameter ref: The Git revision, usually a commit hash.\n    @available(_PackageDescription, deprecated: 5.6)\n    public static func revision(_ ref: String) -> Package.Dependency.Requirement {\n        return .revisionItem(ref)\n    }\n\n    /// Returns a requirement for a source control branch.\n    ///\n    /// Note that packages that use branch-based dependency requirements can't\n    /// be depended upon by packages that use version-based dependency\n    /// requirements; you should remove branch-based dependency requirements\n    /// before publishing a version of your package.\n    ///\n    /// The following example defines a version requirement that accepts any\n    /// change in the develop branch.\n    ///\n    ///```swift\n    /// .branch(“develop”)\n    /// ```\n    ///\n    /// - Parameter name: The name of the branch.\n    @available(_PackageDescription, deprecated: 5.6)\n    public static func branch(_ name: String) -> Package.Dependency.Requirement {\n        return .branchItem(name)\n    }\n}\n\n// MARK: - SourceControlRequirement\n\nextension Package.Dependency {\n    /// An enum that represents the requirement for a package dependency.\n    ///\n    /// The dependency requirement can be defined as one of three different version requirements:\n    ///\n    /// **A version-based requirement.**\n    ///\n    /// Decide whether your project accepts updates to a package dependency up\n    /// to the next major version or up to the next minor version. To be more\n    /// restrictive, select a specific version range or an exact version.\n    /// Major versions tend to have more significant changes than minor\n    /// versions, and may require you to modify your code when they update.\n    /// The version rule requires Swift packages to conform to semantic\n    /// versioning. To learn more about the semantic versioning standard,\n    /// see the [Semantic Versioning 2.0.0](https://semver.org) website.\n    ///\n    /// Selecting the version requirement is the recommended way to add a package dependency. It allows you to create a balance between restricting changes and obtaining improvements and features.\n    ///\n    /// **A branch-based requirement**\n    ///\n    /// Select the name of the branch for your package dependency to follow.\n    /// Use branch-based dependencies when you're developing multiple packages\n    /// in tandem or when you don't want to publish versions of your package dependencies.\n    ///\n    /// Note that packages which use branch-based dependency requirements\n    /// can't be added as dependencies to packages that use version-based dependency\n    /// requirements; you should remove branch-based dependency requirements\n    /// before publishing a version of your package.\n    ///\n    /// **A commit-based requirement**\n    ///\n    /// Select the commit hash for your package dependency to follow.\n    /// Choosing this option isn't recommended, and should be limited to\n    /// exceptional cases. While pinning your package dependency to a specific\n    /// commit ensures that the package dependency doesn't change and your\n    /// code remains stable, you don't receive any updates at all. If you worry about\n    /// the stability of a remote package, consider one of the more\n    /// restrictive options of the version-based requirement.\n    ///\n    /// Note that packages which use commit-based dependency requirements\n    /// can't be added as dependencies to packages that use version-based\n    /// dependency requirements; you should remove commit-based dependency\n    /// requirements before publishing a version of your package.\n    @available(_PackageDescription, introduced: 5.6)\n    public enum SourceControlRequirement {\n        /// An exact version based requirement.\n        case exact(Version)\n        /// A requirement based on a range of versions.\n        case range(Range<Version>)\n        /// A commit based requirement.\n        case revision(String)\n        /// A branch based requirement.\n        case branch(String)\n    }\n}\n\n// MARK: - RegistryRequirement\n\nextension Package.Dependency {\n    /// An enum that represents the requirement for a package dependency.\n    ///\n    /// Decide whether your project accepts updates to a package dependency up\n    /// to the next major version or up to the next minor version. To be more\n    /// restrictive, select a specific version range or an exact version.\n    /// Major versions tend to have more significant changes than minor\n    /// versions, and may require you to modify your code when they update.\n    /// The version rule requires Swift packages to conform to semantic\n    /// versioning. To learn more about the semantic versioning standard,\n    /// visit the [Semantic Versioning 2.0.0](https://semver.org) website.\n    @available(_PackageDescription, introduced: 999)\n    public enum RegistryRequirement {\n        /// A requirement based on an exact version.\n        case exact(Version)\n        /// A requirement based on a range of versions.\n        case range(Range<Version>)\n    }\n}\n\nextension Range {\n    /// Returns a requirement for a version range, starting at the given minimum\n    /// version and going up to the next major version. This is the recommended version requirement.\n    ///\n    /// - Parameter version: The minimum version for the version range.\n    public static func upToNextMajor(from version: Version) -> Range<Bound> where Bound == Version {\n        return version ..< Version(version.major + 1, 0, 0)\n    }\n\n\n    /// Returns a requirement for a version range, starting at the given minimum\n    /// version and going up to the next minor version.\n    ///\n    /// - Parameter version: The minimum version for the version range.\n    public static func upToNextMinor(from version: Version) -> Range<Bound> where Bound == Version {\n        return version ..< Version(version.major, version.minor + 1, 0)\n    }\n}\n\n@available(_PackageDescription, deprecated: 5.6)\nextension Package.Dependency.Requirement {\n    /// A source control requirement bounded to the given version's major version number.\n    ///\n    /// Returns a requirement for a version range, starting at the given minimum\n    /// version and going up to but not including the next major version. This is the recommended\n    /// version requirement.\n    ///\n    /// - Parameter version: The minimum version for the version range.\n    ///\n    /// - Returns: A source control requirement instance.\n    @_disfavoredOverload\n    public static func upToNextMajor(from version: Version) -> Self {\n        return .rangeItem(.upToNextMajor(from: version))\n    }\n    /// A source control requirement bounded to the given version's minor version number.\n    ///\n    /// Returns a requirement for a version range, starting at the given minimum\n    /// version and going up to but not including the next minor version.\n    ///\n    /// - Parameter version: The minimum version for the version range.\n    ///\n    /// - Returns: A source control requirement instance.\n    @_disfavoredOverload\n    public static func upToNextMinor(from version: Version) -> Self {\n        return .rangeItem(.upToNextMinor(from: version))\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/Product.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The object that defines a package product.\n///\n/// A package product defines an externally visible build artifact that's\n/// available to clients of a package. Swift Package Manager assembles the product from the\n/// build artifacts of one or more of the package's targets. A package product\n/// can be one of three types:\n///\n/// - term Library: Use a _library product_ to vend library targets. This makes\n/// a target's public APIs available to clients that integrate the Swift\n/// package.\n/// - term Executable: Use an _executable product_ to vend an\n/// executable target. Use this only if you want to make the executable\n/// available to clients.\n/// - term Plugin: Use a _plugin product_ to vend plugin targets. This makes\n/// the plugin available to clients that integrate the Swift package.\n///\n/// The following example shows a package manifest for a library called “Paper”\n/// that defines multiple products:\n///\n/// ```swift\n/// let package = Package(\n///     name: \"Paper\",\n///     products: [\n///         .executable(name: \"tool\", targets: [\"tool\"]),\n///         .library(name: \"Paper\", targets: [\"Paper\"]),\n///         .library(name: \"PaperStatic\", type: .static, targets: [\"Paper\"]),\n///         .library(name: \"PaperDynamic\", type: .dynamic, targets: [\"Paper\"]),\n///     ],\n///     dependencies: [\n///         .package(url: \"http://example.com.com/ExamplePackage/ExamplePackage\", from: \"1.2.3\"),\n///         .package(url: \"http://some/other/lib\", .exact(\"1.2.3\")),\n///     ],\n///     targets: [\n///         .executableTarget(\n///             name: \"tool\",\n///             dependencies: [\n///                 \"Paper\",\n///                 \"ExamplePackage\"\n///             ]),\n///         .target(\n///             name: \"Paper\",\n///             dependencies: [\n///                 \"Basic\",\n///                 .target(name: \"Utility\"),\n///                 .product(name: \"AnotherExamplePackage\"),\n///             ])\n///     ]\n/// )\n/// ```\npublic class Product {\n    /// The name of the package product.\n    public let name: String\n\n    init(name: String) {\n        self.name = name\n    }\n\n    /// The executable product of a Swift package.\n    public final class Executable: Product, @unchecked Sendable {\n        /// The names of the targets in this product.\n        public let targets: [String]\n        \n        /// Any specific product settings that apply to this product.\n        @_spi(PackageProductSettings)\n        public let settings: [ProductSetting]\n\n        init(name: String, targets: [String], settings: [ProductSetting]) {\n            self.targets = targets\n            self.settings = settings\n            super.init(name: name)\n        }\n    }\n\n    /// The library product of a Swift package.\n    public final class Library: Product, @unchecked Sendable {\n        /// The different types of a library product.\n        public enum LibraryType: String {\n            /// A statically linked library.\n            case `static`\n            /// A dynamically linked library.\n            case `dynamic`\n        }\n\n        /// The names of the targets in this product.\n        public let targets: [String]\n\n        /// The type of the library.\n        ///\n        /// If the type is unspecified, the Swift Package Manager automatically chooses a type\n        /// based on the client's preference.\n        public let type: LibraryType?\n\n        init(name: String, type: LibraryType? = nil, targets: [String]) {\n            self.type = type\n            self.targets = targets\n            super.init(name: name)\n        }\n    }\n\n    /// The plug-in product of a Swift package.\n    public final class Plugin: Product, @unchecked Sendable {\n        /// The name of the plug-in target to vend as a product.\n        public let targets: [String]\n\n        init(name: String, targets: [String]) {\n            self.targets = targets\n            super.init(name: name)\n        }\n    }\n\n    /// Creates a library product to allow clients that declare a dependency on\n    /// this package to use the package's functionality.\n    ///\n    /// A library's product can be either statically or dynamically linked. It's recommended\n    /// that you don't explicitly declare the type of library, so Swift Package Manager can\n    /// choose between static or dynamic linking based on the preference of the\n    /// package's consumer.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the library product.\n    ///   - type: The optional type of the library that's used to determine how to\n    ///     link to the library. Leave this parameter so\n    ///     Swift Package Manager can choose between static or dynamic linking (recommended). If you\n    ///     don't support both linkage types, use\n    ///     ``Product/Library/LibraryType/static`` or\n    ///     ``Product/Library/LibraryType/dynamic`` for this parameter.\n    ///   - targets: The targets that are bundled into a library product.\n    ///\n    /// - Returns: A `Product` instance.\n    public static func library(\n        name: String,\n        type: Library.LibraryType? = nil,\n        targets: [String]\n    ) -> Product {\n        return Library(name: name, type: type, targets: targets)\n    }\n\n    /// Creates an executable package product.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the executable product.\n    ///   - targets: The targets to bundle into an executable product.\n    /// - Returns: A `Product` instance.\n    public static func executable(\n        name: String,\n        targets: [String]\n    ) -> Product {\n        return Executable(name: name, targets: targets, settings: [])\n    }\n\n    @_spi(PackageProductSettings)\n    public static func executable(\n        name: String,\n        targets: [String],\n        settings: [ProductSetting]\n    ) -> Product {\n        return Executable(name: name, targets: targets, settings: settings)\n    }\n\n    /// Defines a product that vends a package plugin target for use by clients of the package.\n    ///\n    /// It is not necessary to define a product for a plugin that\n    /// is only used within the same package where you define it. All the targets\n    /// listed must be plugin targets in the same package as the product. Swift Package Manager\n    /// will apply them to any client targets of the product in the order\n    /// they are listed.\n    /// - Parameters:\n    ///   - name: The name of the plugin product.\n    ///   - targets: The plugin targets to vend as a product.\n    /// - Returns: A `Product` instance.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func plugin(\n        name: String,\n        targets: [String]\n    ) -> Product {\n        return Plugin(name: name, targets: targets)\n    }\n}\n\n\n/// A particular setting to apply to a product. Some may be specific to certain platforms.\n#if ENABLE_APPLE_PRODUCT_TYPES\npublic enum ProductSetting: Equatable {\n    case bundleIdentifier(String)\n    case teamIdentifier(String)\n    case displayVersion(String)\n    case bundleVersion(String)\n    case iOSAppInfo(IOSAppInfo)\n\n    public struct IOSAppInfo: Equatable {\n        var appIcon: AppIcon?\n        var accentColor: AccentColor?\n        var supportedDeviceFamilies: [DeviceFamily]\n        var supportedInterfaceOrientations: [InterfaceOrientation]\n        var capabilities: [Capability] = []\n        var appCategory: AppCategory?\n        var additionalInfoPlistContentFilePath: String?\n\n        // Represents the configuration of the app's accent color.\n        public enum AccentColor: Equatable {\n            public struct PresetColor: Equatable {\n                public var rawValue: String\n\n                public init(rawValue: String) {\n                    self.rawValue = rawValue\n                }\n            }\n            // Predefined color.\n            case presetColor(PresetColor)\n            // Named asset in an asset catalog.\n            case asset(String)\n        }\n\n        // Represents the configuration of the app's app icon.\n        public enum AppIcon: Equatable {\n            public struct PlaceholderIcon: Equatable {\n                public var rawValue: String\n\n                public init(rawValue: String) {\n                    self.rawValue = rawValue\n                }\n            }\n            // Placeholder app icon using the app's accent color and specified icon.\n            case placeholder(icon: PlaceholderIcon)\n            // Named asset in an asset catalog.\n            case asset(String)\n        }\n        \n        /// Represents a family of device types that an application can support.\n        public enum DeviceFamily: String, Equatable {\n            case phone\n            case pad\n            case mac\n        }\n        \n        /// Represents a condition on a particular device family.\n        public struct DeviceFamilyCondition: Equatable {\n            public var deviceFamilies: [DeviceFamily]\n            \n            public init(deviceFamilies: [DeviceFamily]) {\n                self.deviceFamilies = deviceFamilies\n            }\n            public static func when(deviceFamilies: [DeviceFamily]) -> DeviceFamilyCondition {\n                return DeviceFamilyCondition(deviceFamilies: deviceFamilies)\n            }\n        }\n        \n        /// Represents a supported device interface orientation.\n        public enum InterfaceOrientation: Equatable {\n            case portrait(_ condition: DeviceFamilyCondition? = nil)\n            case portraitUpsideDown(_ condition: DeviceFamilyCondition? = nil)\n            case landscapeRight(_ condition: DeviceFamilyCondition? = nil)\n            case landscapeLeft(_ condition: DeviceFamilyCondition? = nil)\n\n            public static var portrait: Self { portrait(nil) }\n            public static var portraitUpsideDown: Self { portraitUpsideDown(nil) }\n            public static var landscapeRight: Self { landscapeRight(nil) }\n            public static var landscapeLeft: Self { landscapeLeft(nil) }\n        }\n        \n        /// A capability required by the device.\n        public enum Capability: Equatable {\n            case appTransportSecurity(configuration: AppTransportSecurityConfiguration, _ condition: DeviceFamilyCondition? = nil)\n            case bluetoothAlways(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case calendars(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case camera(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case contacts(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case faceID(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case fileAccess(_ location: FileAccessLocation, mode: FileAccessMode, _ condition: DeviceFamilyCondition? = nil)\n            case incomingNetworkConnections(_ condition: DeviceFamilyCondition? = nil)\n            case localNetwork(purposeString: String, bonjourServiceTypes: [String]? = nil, _ condition: DeviceFamilyCondition? = nil)\n            case locationAlwaysAndWhenInUse(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case locationWhenInUse(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case mediaLibrary(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case microphone(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case motion(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case nearbyInteractionAllowOnce(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case outgoingNetworkConnections(_ condition: DeviceFamilyCondition? = nil)\n            case photoLibrary(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case photoLibraryAdd(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case reminders(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case speechRecognition(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n            case userTracking(purposeString: String, _ condition: DeviceFamilyCondition? = nil)\n        }\n        \n        public struct AppTransportSecurityConfiguration: Equatable {\n            public var allowsArbitraryLoadsInWebContent: Bool? = nil\n            public var allowsArbitraryLoadsForMedia: Bool? = nil\n            public var allowsLocalNetworking: Bool? = nil\n            public var exceptionDomains: [ExceptionDomain]? = nil\n            public var pinnedDomains: [PinnedDomain]? = nil\n\n            public struct ExceptionDomain: Equatable {\n                public var domainName: String\n                public var includesSubdomains: Bool? = nil\n                public var exceptionAllowsInsecureHTTPLoads: Bool? = nil\n                public var exceptionMinimumTLSVersion: String? = nil\n                public var exceptionRequiresForwardSecrecy: Bool? = nil\n                public var requiresCertificateTransparency: Bool? = nil\n\n                public init(\n                    domainName: String,\n                    includesSubdomains: Bool? = nil,\n                    exceptionAllowsInsecureHTTPLoads: Bool? = nil,\n                    exceptionMinimumTLSVersion: String? = nil,\n                    exceptionRequiresForwardSecrecy: Bool? = nil,\n                    requiresCertificateTransparency: Bool? = nil\n                ) {\n                    self.domainName = domainName\n                    self.includesSubdomains = includesSubdomains\n                    self.exceptionAllowsInsecureHTTPLoads = exceptionAllowsInsecureHTTPLoads\n                    self.exceptionMinimumTLSVersion = exceptionMinimumTLSVersion\n                    self.exceptionRequiresForwardSecrecy = exceptionRequiresForwardSecrecy\n                    self.requiresCertificateTransparency = requiresCertificateTransparency\n                }\n            }\n            \n            public struct PinnedDomain: Equatable {\n                public var domainName: String\n                public var includesSubdomains : Bool? = nil\n                public var pinnedCAIdentities : [[String: String]]? = nil\n                public var pinnedLeafIdentities : [[String: String]]? = nil\n                \n                public init(\n                    domainName: String,\n                    includesSubdomains: Bool? = nil,\n                    pinnedCAIdentities: [[String: String]]? = nil,\n                    pinnedLeafIdentities: [[String: String]]? = nil\n                ) {\n                    self.domainName = domainName\n                    self.includesSubdomains = includesSubdomains\n                    self.pinnedCAIdentities = pinnedCAIdentities\n                    self.pinnedLeafIdentities = pinnedLeafIdentities\n                }\n            }\n            \n            public init(\n                allowsArbitraryLoadsInWebContent: Bool? = nil,\n                allowsArbitraryLoadsForMedia: Bool? = nil,\n                allowsLocalNetworking: Bool? = nil,\n                exceptionDomains: [ExceptionDomain]? = nil,\n                pinnedDomains: [PinnedDomain]? = nil\n            ) {\n                self.allowsArbitraryLoadsInWebContent = allowsArbitraryLoadsInWebContent\n                self.allowsArbitraryLoadsForMedia = allowsArbitraryLoadsForMedia\n                self.allowsLocalNetworking = allowsLocalNetworking\n                self.exceptionDomains = exceptionDomains\n                self.pinnedDomains = pinnedDomains\n            }\n        }\n\n        public enum FileAccessLocation: Equatable {\n            case userSelectedFiles\n            case downloadsFolder\n            case pictureFolder\n            case musicFolder\n            case moviesFolder\n\n            var identifier: String {\n                switch self {\n                case .userSelectedFiles:\n                    return \"userSelectedFiles\"\n                case .downloadsFolder:\n                    return \"downloadsFolder\"\n                case .pictureFolder:\n                    return \"pictureFolder\"\n                case .musicFolder:\n                    return \"musicFolder\"\n                case .moviesFolder:\n                    return \"moviesFolder\"\n                }\n            }\n        }\n\n        public enum FileAccessMode: Equatable {\n            case readOnly\n            case readWrite\n\n            var identifier: String {\n                switch self {\n                case .readOnly: return \"readOnly\"\n                case .readWrite: return \"readWrite\"\n                }\n            }\n        }\n        \n        public struct AppCategory: Equatable, ExpressibleByStringLiteral {\n            public var rawValue: String\n\n            public init(rawValue: String) {\n                self.rawValue = rawValue\n            }\n\n            public init(stringLiteral value: StringLiteralType) {\n                self.init(rawValue: value)\n            }\n        }\n\n        public init(\n            appIcon: AppIcon?,\n            accentColor: AccentColor?,\n            supportedDeviceFamilies: [DeviceFamily],\n            supportedInterfaceOrientations: [InterfaceOrientation],\n            capabilities: [Capability],\n            appCategory: AppCategory?,\n            additionalInfoPlistContentFilePath: String?\n        ) {\n            self.appIcon = appIcon\n            self.accentColor = accentColor\n            self.supportedDeviceFamilies = supportedDeviceFamilies\n            self.supportedInterfaceOrientations = supportedInterfaceOrientations\n            self.capabilities = capabilities\n            self.appCategory = appCategory\n            self.additionalInfoPlistContentFilePath = additionalInfoPlistContentFilePath\n        }\n    }\n}\n#else\n// This has to be defined at least as SPI because some of the methods that are\n// SPI use it, but it doesn't contain anything when Apple product types aren't\n// enabled.\n@_spi(PackageProductSettings)\npublic enum ProductSetting: Equatable { }\n#endif\n\n#if ENABLE_APPLE_PRODUCT_TYPES\nextension ProductSetting.IOSAppInfo.AccentColor.PresetColor {\n    public static var blue: Self { .init(rawValue: \"blue\") }\n    public static var brown: Self { .init(rawValue: \"brown\") }\n    public static var cyan: Self { .init(rawValue: \"cyan\") }\n    public static var green: Self { .init(rawValue: \"green\") }\n    public static var indigo: Self { .init(rawValue: \"indigo\") }\n    public static var mint: Self { .init(rawValue: \"mint\") }\n    public static var orange: Self { .init(rawValue: \"orange\") }\n    public static var pink: Self { .init(rawValue: \"pink\") }\n    public static var purple: Self { .init(rawValue: \"purple\") }\n    public static var red: Self { .init(rawValue: \"red\") }\n    public static var teal: Self { .init(rawValue: \"teal\") }\n    public static var yellow: Self { .init(rawValue: \"yellow\") }\n}\n\nextension ProductSetting.IOSAppInfo.AppIcon.PlaceholderIcon {\n    public static var bandage: Self { .init(rawValue: \"bandage\")}\n    public static var barChart: Self { .init(rawValue: \"barChart\")}\n    public static var beachball: Self { .init(rawValue: \"beachball\")}\n    public static var bicycle: Self { .init(rawValue: \"bicycle\")}\n    public static var binoculars: Self { .init(rawValue: \"binoculars\")}\n    public static var bird: Self { .init(rawValue: \"bird\") }\n    public static var boat: Self { .init(rawValue: \"boat\")}\n    public static var bowl: Self { .init(rawValue: \"bowl\")}\n    public static var box: Self { .init(rawValue: \"box\")}\n    public static var bunny: Self { .init(rawValue: \"bunny\")}\n    public static var butterfly: Self { .init(rawValue: \"butterfly\")}\n    public static var calculator: Self { .init(rawValue: \"calculator\")}\n    public static var calendar: Self { .init(rawValue: \"calendar\")}\n    public static var camera: Self { .init(rawValue: \"camera\")}\n    public static var car: Self { .init(rawValue: \"car\")}\n    public static var carrot: Self { .init(rawValue: \"carrot\")}\n    public static var cat: Self { .init(rawValue: \"cat\")}\n    public static var chatMessage: Self { .init(rawValue: \"chatMessage\")}\n    public static var checkmark: Self { .init(rawValue: \"checkmark\")}\n    public static var clock: Self { .init(rawValue: \"clock\")}\n    public static var cloud: Self { .init(rawValue: \"cloud\")}\n    public static var coffee: Self { .init(rawValue: \"coffee\")}\n    public static var coins: Self { .init(rawValue: \"coins\")}\n    public static var dog: Self { .init(rawValue: \"dog\")}\n    public static var earth: Self { .init(rawValue: \"earth\")}\n    public static var flower: Self { .init(rawValue: \"flower\")}\n    public static var gamepad: Self { .init(rawValue: \"gamepad\")}\n    public static var gift: Self { .init(rawValue: \"gift\")}\n    public static var heart: Self { .init(rawValue: \"heart\")}\n    public static var images: Self { .init(rawValue: \"images\")}\n    public static var leaf: Self { .init(rawValue: \"leaf\")}\n    public static var lightningBolt: Self { .init(rawValue: \"lightningBolt\")}\n    public static var location: Self { .init(rawValue: \"location\")}\n    public static var magicWand: Self { .init(rawValue: \"magicWand\")}\n    public static var map: Self { .init(rawValue: \"map\")}\n    public static var mic: Self { .init(rawValue: \"mic\")}\n    public static var moon: Self { .init(rawValue: \"moon\")}\n    public static var movieReel: Self { .init(rawValue: \"movieReel\")}\n    public static var note: Self { .init(rawValue: \"note\")}\n    public static var openBook: Self { .init(rawValue: \"openBook\")}\n    public static var palette: Self { .init(rawValue: \"palette\")}\n    public static var paper: Self { .init(rawValue: \"paper\")}\n    public static var pencil: Self { .init(rawValue: \"pencil\")}\n    public static var plane: Self { .init(rawValue: \"plane\")}\n    public static var rocket: Self { .init(rawValue: \"rocket\")}\n    public static var running: Self { .init(rawValue: \"running\")}\n    public static var sandwich: Self { .init(rawValue: \"sandwich\")}\n    public static var smiley: Self { .init(rawValue: \"smiley\")}\n    public static var sparkle: Self { .init(rawValue: \"sparkle\")}\n    public static var star: Self { .init(rawValue: \"star\")}\n    public static var sun: Self { .init(rawValue: \"sun\")}\n    public static var tv: Self { .init(rawValue: \"tv\")}\n    public static var twoPeople: Self { .init(rawValue: \"twoPeople\")}\n    public static var weights: Self { .init(rawValue: \"weights\")}\n}\n\nextension ProductSetting.IOSAppInfo.AppCategory {\n    public static var books: Self { .init(rawValue: \"public.app-category.books\") }\n    public static var business: Self { .init(rawValue: \"public.app-category.business\") }\n    public static var developerTools: Self { .init(rawValue: \"public.app-category.developer-tools\") }\n    public static var education: Self { .init(rawValue: \"public.app-category.education\") }\n    public static var entertainment: Self { .init(rawValue: \"public.app-category.entertainment\") }\n    public static var finance: Self { .init(rawValue: \"public.app-category.finance\") }\n    public static var foodAndDrink: Self { .init(rawValue: \"public.app-category.food-and-drink\") }\n    public static var graphicsDesign: Self { .init(rawValue: \"public.app-category.graphics-design\") }\n    public static var healthcareFitness: Self { .init(rawValue: \"public.app-category.healthcare-fitness\") }\n    public static var lifestyle: Self { .init(rawValue: \"public.app-category.lifestyle\") }\n    public static var magazinesAndNewspapers: Self { .init(rawValue: \"public.app-category.magazines-and-newspapers\") }\n    public static var medical: Self { .init(rawValue: \"public.app-category.medical\") }\n    public static var music: Self { .init(rawValue: \"public.app-category.music\") }\n    public static var navigation: Self { .init(rawValue: \"public.app-category.navigation\") }\n    public static var news: Self { .init(rawValue: \"public.app-category.news\") }\n    public static var photography: Self { .init(rawValue: \"public.app-category.photography\") }\n    public static var productivity: Self { .init(rawValue: \"public.app-category.productivity\") }\n    public static var reference: Self { .init(rawValue: \"public.app-category.reference\") }\n    public static var shopping: Self { .init(rawValue: \"public.app-category.shopping\") }\n    public static var socialNetworking: Self { .init(rawValue: \"public.app-category.social-networking\") }\n    public static var sports: Self { .init(rawValue: \"public.app-category.sports\") }\n    public static var travel: Self { .init(rawValue: \"public.app-category.travel\") }\n    public static var utilities: Self { .init(rawValue: \"public.app-category.utilities\") }\n    public static var video: Self { .init(rawValue: \"public.app-category.video\") }\n    public static var weather: Self { .init(rawValue: \"public.app-category.weather\") }\n\n    // Games\n    public static var games: Self { .init(rawValue: \"public.app-category.games\") }\n    // Games subcategories\n    public static var actionGames: Self { .init(rawValue: \"public.app-category.action-games\") }\n    public static var adventureGames: Self { .init(rawValue: \"public.app-category.adventure-games\") }\n    public static var arcadeGames: Self { .init(rawValue: \"public.app-category.arcade-games\") }\n    public static var boardGames: Self { .init(rawValue: \"public.app-category.board-games\") }\n    public static var cardGames: Self { .init(rawValue: \"public.app-category.card-games\") }\n    public static var casinoGames: Self { .init(rawValue: \"public.app-category.casino-games\") }\n    public static var diceGames: Self { .init(rawValue: \"public.app-category.dice-games\") }\n    public static var educationalGames: Self { .init(rawValue: \"public.app-category.educational-games\") }\n    public static var familyGames: Self { .init(rawValue: \"public.app-category.family-games\") }\n    public static var kidsGames: Self { .init(rawValue: \"public.app-category.kids-games\") }\n    public static var musicGames: Self { .init(rawValue: \"public.app-category.music-games\") }\n    public static var puzzleGames: Self { .init(rawValue: \"public.app-category.puzzle-games\") }\n    public static var racingGames: Self { .init(rawValue: \"public.app-category.racing-games\") }\n    public static var rolePlayingGames: Self { .init(rawValue: \"public.app-category.role-playing-games\") }\n    public static var simulationGames: Self { .init(rawValue: \"public.app-category.simulation-games\") }\n    public static var sportsGames: Self { .init(rawValue: \"public.app-category.sports-games\") }\n    public static var strategyGames: Self { .init(rawValue: \"public.app-category.strategy-games\") }\n    public static var triviaGames: Self { .init(rawValue: \"public.app-category.trivia-games\") }\n    public static var wordGames: Self { .init(rawValue: \"public.app-category.word-games\") }\n}\n#endif\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/Resource.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A resource to bundle with the Swift package.\n///\n/// If a Swift package declares a Swift tools version of 5.3 or later, it can\n/// include resource files. Similar to source code, Swift Package Manager scopes resources to a\n/// target, so you must put them into the folder that corresponds to the target\n/// they belong to. For example, any resources for the `MyLibrary` target must\n/// reside in `Sources/MyLibrary`. Use subdirectories to organize your resource\n/// files in a way that simplifies file identification and management. For\n/// example, put all resource files into a directory named `Resources`, so they\n/// reside at `Sources/MyLibrary/Resources`.\n///\n/// By default, Swift Package Manager handles common resources types for Apple platforms\n/// automatically. For example, you don't need to declare XIB files,\n/// storyboards, Core Data file types, and asset catalogs as resources in your\n/// package manifest. However, you must explicitly declare other file types — for\n/// example, image files — as resources using the\n/// ``Resource/process(_:localization:)`` or ``Resource/copy(_:)`` rules.\n/// Alternatively, exclude resource files from a target by passing them to the\n/// target initializer's ``Target/exclude`` parameter.\n///\n/// To learn more about package resources, see [Bundling resources as a Swift Package](https://developer.apple.com/documentation/xcode/bundling-resources-with-a-swift-package).\n@available(_PackageDescription, introduced: 5.3)\npublic struct Resource: Sendable {\n\n    /// Defines the explicit type of localization for resources.\n    public enum Localization: String, Sendable {\n\n        /// A constant that represents default localization.\n        case `default`\n\n        /// A constant that represents base internationalization.\n        case base\n    }\n\n    /// The rule for the resource.\n    let rule: String\n\t\n    /// The path of the resource.\n    let path: String\n\n    /// The explicit type of localization for the resource.\n    let localization: Localization?\n\n    private init(rule: String, path: String, localization: Localization?) {\n        self.rule = rule\n        self.path = path\n        self.localization = localization\n    }\n\n    /// Applies a platform-specific rules to the resource at the given path.\n    ///\n    /// Use the `process` rule to process resources at the given path according\n    /// to the platform Swift Package Manager builds the target for. For example, Swift Package Manager may\n    /// optimize image files for platforms that support such optimizations. If\n    /// no optimization is available for a file type, Swift Package Manager copies the file.\n    ///\n    /// If the given path represents a directory, Swift Package Manager applies the process rule\n    /// recursively to each file in the directory.\n    ///\n    /// If possible, use this rule instead of ``Resource/copy(_:)``.\n    ///\n    /// - Parameters:\n    ///   - path: The path for a resource.\n    ///   - localization: The explicit localization type for the resource.\n    /// - Returns: A `Resource` instance.\n    public static func process(_ path: String, localization: Localization? = nil) -> Resource {\n        return Resource(rule: \"process\", path: path, localization: localization)\n    }\n\n    /// Applies the copy rule to a resource at the given path.\n    ///\n    /// If possible, use ``Resource/process(_:localization:)`` and automatically\n    /// apply optimizations to resources.\n    ///\n    /// If your resources must remain untouched or must retain a specific folder\n    /// structure, use the `copy` rule. It copies resources at the given `path`,\n    /// as is, to the top level in the package's resource bundle. If the given\n    /// path represents a directory, Swift Package Manager preserves its structure.\n    ///\n    /// - Parameter path: The path for a resource.\n    /// - Returns: A `Resource` instance.\n    public static func copy(_ path: String) -> Resource {\n        return Resource(rule: \"copy\", path: path, localization: nil)\n    }\n\n    /// Applies the embed rule to a resource at the given path.\n    ///\n    /// Use the embed rule to embed the bytes that represent the contents of a resource into executable code.\n    /// For example,  if you embed the file `identifier.txt` that has the contents:\n    /// ```\n    /// Hello Swift\n    /// ```\n    ///\n    /// Package manager generates a PackageResources class with each embedded resource as a static property based on the name of the resource.\n    /// For the example above, the code generated by Package Manager is equivalent to the following source:\n    /// ```\n    /// struct PackageResources {\n    ///     static let identifier_txt: [UInt8] = [72,101,108,108,111,32,83,119,105,102,116,10]\n    /// }\n    /// ```\n    ///\n    /// - Parameter path: The path for a resource.\n    /// - Returns: A `Resource` instance.\n    @available(_PackageDescription, introduced: 5.9)\n    public static func embedInCode(_ path: String) -> Resource {\n        return Resource(rule: \"embedInCode\", path: path, localization: nil)\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/SupportedPlatforms.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A platform supported by Swift Package Manager.\npublic struct Platform: Equatable, Sendable {\n\n    /// The name of the platform.\n    let name: String\n\n    private init(name: String) {\n        self.name = name\n    }\n\n    /// Creates a custom platform.\n    ///\n    /// Use this function if none of the predefined platform names match the platform you are targeting.\n    /// - Parameter platformName: The name of the platform.\n    /// - Returns: A `Platform` instance.\n    @available(_PackageDescription, introduced: 5.6)\n    public static func custom(_ platformName: String) -> Platform {\n        return Platform(name: platformName)\n    }\n\n    /// The macOS platform.\n    public static let macOS: Platform = Platform(name: \"macos\")\n\n    /// The Mac Catalyst platform.\n    public static let macCatalyst: Platform = Platform(name: \"maccatalyst\")\n\n    /// The iOS platform.\n    public static let iOS: Platform = Platform(name: \"ios\")\n\n    /// The tvOS platform.\n    public static let tvOS: Platform = Platform(name: \"tvos\")\n\n    /// The watchOS platform.\n    public static let watchOS: Platform = Platform(name: \"watchos\")\n\n    /// The visionOS platform.\n    public static let visionOS: Platform = Platform(name: \"visionos\")\n\n    /// The DriverKit platform\n    public static let driverKit: Platform = Platform(name: \"driverkit\")\n\n    /// The Linux platform.\n    public static let linux: Platform = Platform(name: \"linux\")\n\n    /// The Windows platform.\n    @available(_PackageDescription, introduced: 5.2)\n    public static let windows: Platform = Platform(name: \"windows\")\n\n    /// The Android platform.\n    @available(_PackageDescription, introduced: 5.2)\n    public static let android: Platform = Platform(name: \"android\")\n\n    /// The WebAssembly System Interface platform.\n    @available(_PackageDescription, introduced: 5.3)\n    public static let wasi: Platform = Platform(name: \"wasi\")\n\n    /// The OpenBSD platform.\n    @available(_PackageDescription, introduced: 5.8)\n    public static let openbsd: Platform = Platform(name: \"openbsd\")\n\n    /// The FreeBSD platform.\n    @available(_PackageDescription, introduced: 999.0)\n    public static let freebsd: Platform = Platform(name: \"freebsd\")\n}\n\n/// A platform that the Swift package supports.\n///\n/// By default, Swift Package Manager assigns a predefined minimum deployment version for each\n/// supported platforms unless you configure supported platforms using the\n/// `platforms` API. This predefined deployment version is the oldest deployment\n/// target version that the installed SDK supports for a given platform. One\n/// exception to this rule is macOS, for which the minimum deployment target\n/// version starts from 10.10. Packages can choose to configure the minimum\n/// deployment target version for a platform by using the APIs defined in this\n/// struct. Swift Package Manager emits appropriate errors when an invalid value is provided for\n/// supported platforms, such as an empty array, multiple declarations for the\n/// same platform, or an invalid version specification.\n///\n/// Swift Package Manager emits an error if a dependency isn't compatible with the top-level\n/// package's deployment version. The deployment target of a package's\n/// dependencies must be lower than or equal to the top-level package's\n/// deployment target version for a particular platform.\npublic struct SupportedPlatform: Equatable, Sendable {\n\n    /// The platform.\n    let platform: Platform\n\n    /// The platform version.\n    let version: String?\n\n    /// Creates supported platform instance.\n    init(platform: Platform, version: String? = nil) {\n        self.platform = platform\n        self.version = version\n    }\n\n    /// Configures the minimum deployment target version for the macOS platform.\n    ///\n    /// - Since: First available in PackageDescription 5.0\n    ///\n    /// - Parameter version: The minimum deployment target that the package supports.\n    public static func macOS(_ version: SupportedPlatform.MacOSVersion) -> SupportedPlatform {\n        return SupportedPlatform(platform: .macOS, version: version.version)\n    }\n\n    /// Configures the minimum deployment target version for the macOS platform\n    /// using a version string.\n    ///\n    /// The version string must be a series of two or three dot-separated\n    /// integers, such as `10.10` or `10.10.1`.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameter versionString: The minimum deployment target as a string\n    ///     representation of two or three dot-separated integers, such as\n    ///     `10.10.1`.\n    /// - Returns: A `SupportedPlatform` instance.\n    public static func macOS(_ versionString: String) -> SupportedPlatform {\n        return SupportedPlatform(platform: .macOS, version: SupportedPlatform.MacOSVersion(string: versionString).version)\n    }\n\n    /// Configures the minimum deployment target version for the Mac Catalyst platform.\n    ///\n    /// - Since: First available in PackageDescription 5.5\n    ///\n    /// - Parameter version: The minimum deployment target that the package supports.\n    /// - Returns: A `SupportedPlatform` instance.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func macCatalyst(_ version: SupportedPlatform.MacCatalystVersion) -> SupportedPlatform {\n        return SupportedPlatform(platform: .macCatalyst, version: version.version)\n    }\n\n    /// Configures the minimum deployment target version for the Mac Catalyst platform\n    /// using a version string.\n    ///\n    /// The version string must be a series of two or three dot-separated integers, such as `13.0` or `13.0.1`.\n    ///\n    /// - Since: First available in PackageDescription 5.5\n    ///\n    /// - Parameter versionString: The minimum deployment target as a string representation of two or three dot-separated integers, such as `13.0.1`.\n    /// - Returns: A `SupportedPlatform` instance.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func macCatalyst(_ versionString: String) -> SupportedPlatform {\n        return SupportedPlatform(platform: .macCatalyst, version: SupportedPlatform.MacCatalystVersion(string: versionString).version)\n    }\n\n    /// Configures the minimum deployment target version for the iOS platform.\n    ///\n    /// - Since: First available in PackageDescription 5.0.\n    ///\n    /// - Parameter version: The minimum deployment target that the package supports.\n    /// - Returns: A `SupportedPlatform` instance.\n    public static func iOS(_ version: SupportedPlatform.IOSVersion) -> SupportedPlatform {\n        return SupportedPlatform(platform: .iOS, version: version.version)\n    }\n\n    /// Configures the minimum deployment target version for the iOS platform\n    /// using a custom version string.\n    ///\n    /// The version string must be a series of two or three dot-separated\n    /// integers, such as `8.0` or `8.0.1`.\n    ///\n    /// - Since: First available in PackageDescription 5.0\n    ///\n    /// - Parameter versionString: The minimum deployment target as a string\n    ///     representation of two or three dot-separated integers, such as `8.0.1`.\n    /// - Returns: A `SupportedPlatform` instance.\n    public static func iOS(_ versionString: String) -> SupportedPlatform {\n        return SupportedPlatform(platform: .iOS, version: SupportedPlatform.IOSVersion(string: versionString).version)\n    }\n\n    /// Configures the minimum deployment target version for the tvOS platform.\n    ///\n    /// - Since: First available in PackageDescription 5.0\n    ///\n    /// - Parameter version: The minimum deployment target that the package supports.\n    /// - Returns: A `SupportedPlatform` instance.\n    public static func tvOS(_ version: SupportedPlatform.TVOSVersion) -> SupportedPlatform {\n        return SupportedPlatform(platform: .tvOS, version: version.version)\n    }\n\n    /// Configures the minimum deployment target version for the tvOS platform\n    /// using a custom version string.\n    ///\n    /// The version string must be a series of two or three dot-separated\n    /// integers,such as `9.0` or `9.0.1`.\n    ///\n    /// - Since: First available in PackageDescription 5.0\n    ///\n    /// - Parameter versionString: The minimum deployment target as a string\n    ///     representation of two or three dot-separated integers, such as `9.0.1`.\n    /// - Returns: A `SupportedPlatform` instance.\n    public static func tvOS(_ versionString: String) -> SupportedPlatform {\n        return SupportedPlatform(platform: .tvOS, version: SupportedPlatform.TVOSVersion(string: versionString).version)\n    }\n\n    /// Configure the minimum deployment target version for the watchOS\n    /// platform.\n    ///\n    /// - Since: First available in PackageDescription 5.0\n    ///\n    /// - Parameter version: The minimum deployment target that the package supports.\n    /// - Returns: A `SupportedPlatform` instance.\n    public static func watchOS(_ version: SupportedPlatform.WatchOSVersion) -> SupportedPlatform {\n        return SupportedPlatform(platform: .watchOS, version: version.version)\n    }\n\n    /// Configure the minimum deployment target version for the watchOS\n    /// platform using a custom version string.\n    ///\n    /// The version string must be a series of two or three dot-separated integers, such as `2.0` or `2.0.1`.\n    ///\n    /// - Since: First available in PackageDescription 5.0\n    ///\n    /// - Parameter versionString: The minimum deployment target as a string\n    ///     representation of two or three dot-separated integers, such as `2.0.1`.\n    /// - Returns: A `SupportedPlatform` instance.\n    public static func watchOS(_ versionString: String) -> SupportedPlatform {\n        return SupportedPlatform(platform: .watchOS, version: SupportedPlatform.WatchOSVersion(string: versionString).version)\n    }\n\n    /// Configure the minimum deployment target version for the visionOS\n    /// platform.\n    ///\n    /// - Since: First available in PackageDescription 5.9\n    ///\n    /// - Parameter version: The minimum deployment target that the package supports.\n    /// - Returns: A `SupportedPlatform` instance.\n    @available(_PackageDescription, introduced: 5.9)\n    public static func visionOS(_ version: SupportedPlatform.VisionOSVersion) -> SupportedPlatform {\n        return SupportedPlatform(platform: .visionOS, version: version.version)\n    }\n\n    /// Configure the minimum deployment target version for the visionOS\n    /// platform using a custom version string.\n    ///\n    /// The version string must be a series of two or three dot-separated integers, such as `1.0` or `1.0.0`.\n    ///\n    /// - Since: First available in PackageDescription 5.9\n    ///\n    /// - Parameter versionString: The minimum deployment target as a string\n    ///     representation of two or three dot-separated integers, such as `1.0.0`.\n    /// - Returns: A `SupportedPlatform` instance.\n    @available(_PackageDescription, introduced: 5.9)\n    public static func visionOS(_ versionString: String) -> SupportedPlatform {\n        return SupportedPlatform(platform: .visionOS, version: SupportedPlatform.VisionOSVersion(string: versionString).version)\n    }\n\n    /// Configures the minimum deployment target version for the DriverKit platform.\n    ///\n    /// - Parameter version: The minimum deployment target that the package supports.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func driverKit(_ version: SupportedPlatform.DriverKitVersion) -> SupportedPlatform {\n        return SupportedPlatform(platform: .driverKit, version: version.version)\n    }\n\n    /// Configures the minimum deployment target version for the DriverKit platform\n    /// using a custom version string.\n    ///\n    /// - Parameter versionString: The minimum deployment target as a string representation of two or three dot-separated integers, such as `19.0.1`.\n    /// - Returns: A `SupportedPlatform` instance.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func driverKit(_ versionString: String) -> SupportedPlatform {\n        return SupportedPlatform(platform: .driverKit, version: SupportedPlatform.DriverKitVersion(string: versionString).version)\n    }\n\n    /// Configures the minimum deployment target version for custom platforms.\n    ///\n    /// - Since: First available in PackageDescription 5.6\n    ///\n    /// - Parameters:\n    ///   - platformName: The name of the platform.\n    ///   - versionString: The minimum deployment target as a string representation of two or three dot-separated integers, such as `19.0.1`.\n    /// - Returns: A `SupportedPlatform` instance.\n    @available(_PackageDescription, introduced: 5.6)\n    public static func custom(_ platformName: String,  versionString: String) -> SupportedPlatform {\n        do {\n            try CustomPlatformVersion.validateVersion(versionString)\n        } catch {\n            errors.append(\"\\(error)\")\n        }\n        return SupportedPlatform(platform: .custom(platformName), version: versionString)\n    }\n}\n\n/// An extension to the SupportedPlatform struct that defines major platform versions.\nextension SupportedPlatform {\n\n    /// The supported macOS version.\n    public struct MacOSVersion: AppleOSVersion {\n        fileprivate static let name = \"macOS\"\n        fileprivate static let minimumMajorVersion = 10\n\n        /// The underlying version representation.\n        let version: String\n\n        fileprivate init(uncheckedVersion version: String) {\n            self.version = version\n        }\n\n        /// The value that represents macOS 10.10.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"macOS 10.13 is the oldest supported version\")\n        public static let v10_10: MacOSVersion = .init(string: \"10.10\")\n\n        /// The value that represents macOS 10.11.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"macOS 10.13 is the oldest supported version\")\n        public static let v10_11: MacOSVersion = .init(string: \"10.11\")\n\n        /// The value that represents macOS 10.12.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"macOS 10.13 is the oldest supported version\")\n        public static let v10_12: MacOSVersion = .init(string: \"10.12\")\n\n        /// The value that represents macOS 10.13.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0)\n        public static let v10_13: MacOSVersion = .init(string: \"10.13\")\n\n        /// The value that represents macOS 10.14.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0)\n        public static let v10_14: MacOSVersion = .init(string: \"10.14\")\n\n        /// The value that represents macOS 10.15.\n        ///\n        /// - Since: First available in PackageDescription 5.1.\n        @available(_PackageDescription, introduced: 5.1)\n        public static let v10_15: MacOSVersion = .init(string: \"10.15\")\n\n        /// The value that represents macOS 10.16, which has been\n        /// replaced by the value for macOS 11.0.\n        ///\n        /// - Since: First available in PackageDescription 5.3.\n        @available(*, unavailable, renamed: \"v11\")\n        @available(_PackageDescription, introduced: 5.3)\n        public static let v10_16: MacOSVersion = .init(string: \"11.0\")\n\n        /// The value that represents macOS 11.0.\n        /// - Since: First available in PackageDescription 5.3.\n        @available(_PackageDescription, introduced: 5.3)\n        public static let v11: MacOSVersion = .init(string: \"11.0\")\n\n        /// The value that represents macOS 12.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v12: MacOSVersion = .init(string: \"12.0\")\n\n        /// The value that represents macOS 13.0.\n        ///\n        /// - Since: First available in PackageDescription 5.7.\n        @available(_PackageDescription, introduced: 5.7)\n        public static let v13: MacOSVersion = .init(string: \"13.0\")\n\n        /// The value that represents macOS 14.0.\n        ///\n        /// - Since: First available in PackageDescription 5.9.\n        @available(_PackageDescription, introduced: 5.9)\n        public static let v14: MacOSVersion = .init(string: \"14.0\")\n\n        /// The value that represents macOS 15.0.\n        ///\n        /// - Since: First available in PackageDescription 6.0.\n        @available(_PackageDescription, introduced: 6.0)\n        public static let v15: MacOSVersion = .init(string: \"15.0\")\n\n        /// The value that represents macOS 16.0, which has been\n        /// replaced by the value for macOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(*, unavailable, renamed: \"v26\")\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v16: MacOSVersion = .init(string: \"16.0\")\n\n        /// The value that represents macOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v26: MacOSVersion = .init(string: \"26.0\")\n    }\n\n    /// The supported tvOS version.\n    public struct TVOSVersion: AppleOSVersion {\n        fileprivate static let name = \"tvOS\"\n        fileprivate static let minimumMajorVersion = 9\n\n        /// The underlying version representation.\n        let version: String\n\n        fileprivate init(uncheckedVersion version: String) {\n            self.version = version\n        }\n\n        /// The value that represents tvOS 9.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"tvOS 12.0 is the oldest supported version\")\n        public static let v9: TVOSVersion = .init(string: \"9.0\")\n\n        /// The value that represents tvOS 10.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"tvOS 12.0 is the oldest supported version\")\n        public static let v10: TVOSVersion = .init(string: \"10.0\")\n\n        /// The value that represents tvOS 11.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.9, message: \"tvOS 12.0 is the oldest supported version\")\n        public static let v11: TVOSVersion = .init(string: \"11.0\")\n\n        /// The value that represents tvOS 12.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0)\n        public static let v12: TVOSVersion = .init(string: \"12.0\")\n\n        /// The value that represents tvOS 13.0.\n        ///\n        /// - Since: First available in PackageDescription 5.1.\n        @available(_PackageDescription, introduced: 5.1)\n        public static let v13: TVOSVersion = .init(string: \"13.0\")\n\n        /// The value that represents tvOS 14.0.\n        ///\n        /// - Since: First available in PackageDescription 5.3.\n        @available(_PackageDescription, introduced: 5.3)\n        public static let v14: TVOSVersion = .init(string: \"14.0\")\n\n        /// The value that represents tvOS 15.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v15: TVOSVersion = .init(string: \"15.0\")\n\n        /// The value that represents tvOS 16.0.\n        ///\n        /// - Since: First available in PackageDescription 5.7.\n        @available(_PackageDescription, introduced: 5.7)\n        public static let v16: TVOSVersion = .init(string: \"16.0\")\n\n        /// The value that represents tvOS 17.0.\n        ///\n        /// - Since: First available in PackageDescription 5.9.\n        @available(_PackageDescription, introduced: 5.9)\n        public static let v17: TVOSVersion = .init(string: \"17.0\")\n\n        /// The value that represents tvOS 18.0.\n        ///\n        /// - Since: First available in PackageDescription 6.0.\n        @available(_PackageDescription, introduced: 6.0)\n        public static let v18: TVOSVersion = .init(string: \"18.0\")\n\n        /// The value that represents tvOS 19.0, which has been\n        /// replaced by the value for tvOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(*, unavailable, renamed: \"v26\")\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v19: TVOSVersion = .init(string: \"19.0\")\n\n        /// The value that represents tvOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v26: TVOSVersion = .init(string: \"26.0\")\n    }\n\n    /// The supported Mac Catalyst version.\n    public struct MacCatalystVersion: AppleOSVersion {\n        fileprivate static let name = \"macCatalyst\"\n        fileprivate static let minimumMajorVersion = 13\n\n        /// The underlying version representation.\n        let version: String\n\n        fileprivate init(uncheckedVersion version: String) {\n            self.version = version\n        }\n\n        /// The value that represents Mac Catalyst 13.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v13: MacCatalystVersion = .init(string: \"13.0\")\n\n        /// The value that represents Mac Catalyst 14.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v14: MacCatalystVersion = .init(string: \"14.0\")\n\n        /// The value that represents Mac Catalyst 15.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v15: MacCatalystVersion = .init(string: \"15.0\")\n\n        /// The value that represents Mac Catalyst 16.0.\n        ///\n        /// - Since: First available in PackageDescription 5.7.\n        @available(_PackageDescription, introduced: 5.7)\n        public static let v16: MacCatalystVersion = .init(string: \"16.0\")\n\n        /// The value that represents Mac Catalyst 17.0.\n        ///\n        /// - Since: First available in PackageDescription 5.9.\n        @available(_PackageDescription, introduced: 5.9)\n        public static let v17: MacCatalystVersion = .init(string: \"17.0\")\n\n        /// The value that represents Mac Catalyst 18.0.\n        ///\n        /// - Since: First available in PackageDescription 6.0.\n        @available(_PackageDescription, introduced: 6.0)\n        public static let v18: MacCatalystVersion = .init(string: \"18.0\")\n\n        /// The value that represents Mac Catalyst 19.0, which has been\n        /// replaced by the value for Mac Catalyst 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(*, unavailable, renamed: \"v26\")\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v19: MacCatalystVersion = .init(string: \"19.0\")\n\n        /// The value that represents Mac Catalyst 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v26: MacCatalystVersion = .init(string: \"26.0\")\n    }\n\n    /// The supported iOS version.\n    public struct IOSVersion: AppleOSVersion {\n        fileprivate static let name = \"iOS\"\n        fileprivate static let minimumMajorVersion = 2\n\n        /// The underlying version representation.\n        let version: String\n\n        fileprivate init(uncheckedVersion version: String) {\n            self.version = version\n        }\n\n        /// The value that represents iOS 8.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"iOS 12.0 is the oldest supported version\")\n        public static let v8: IOSVersion = .init(string: \"8.0\")\n\n        /// The value that represents iOS 9.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"iOS 12.0 is the oldest supported version\")\n        public static let v9: IOSVersion = .init(string: \"9.0\")\n\n        /// The value that represents iOS 10.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"iOS 12.0 is the oldest supported version\")\n        public static let v10: IOSVersion = .init(string: \"10.0\")\n\n        /// The value that represents iOS 11.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.9, message: \"iOS 12.0 is the oldest supported version\")\n        public static let v11: IOSVersion = .init(string: \"11.0\")\n\n        /// The value that represents iOS 12.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0)\n        public static let v12: IOSVersion = .init(string: \"12.0\")\n\n        /// The value that represents iOS 13.0.\n        ///\n        /// - Since: First available in PackageDescription 5.1.\n        @available(_PackageDescription, introduced: 5.1)\n        public static let v13: IOSVersion = .init(string: \"13.0\")\n\n        /// The value that represents iOS 14.0.\n        ///\n        /// - Since: First available in PackageDescription 5.3.\n        @available(_PackageDescription, introduced: 5.3)\n        public static let v14: IOSVersion = .init(string: \"14.0\")\n\n        /// The value that represents iOS 15.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v15: IOSVersion = .init(string: \"15.0\")\n\n        /// The value that represents iOS 16.0.\n        ///\n        /// - Since: First available in PackageDescription 5.7.\n        @available(_PackageDescription, introduced: 5.7)\n        public static let v16: IOSVersion = .init(string: \"16.0\")\n\n        /// The value that represents iOS 17.0.\n        ///\n        /// - Since: First available in PackageDescription 5.9.\n        @available(_PackageDescription, introduced: 5.9)\n        public static let v17: IOSVersion = .init(string: \"17.0\")\n\n        /// The value that represents iOS 18.0.\n        ///\n        /// - Since: First available in PackageDescription 6.0.\n        @available(_PackageDescription, introduced: 6.0)\n        public static let v18: IOSVersion = .init(string: \"18.0\")\n\n        /// The value that represents iOS 19.0, which has been\n        /// replaced by the value for iOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(*, unavailable, renamed: \"v26\")\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v19: IOSVersion = .init(string: \"19.0\")\n\n        /// The value that represents iOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v26: IOSVersion = .init(string: \"26.0\")\n    }\n\n    /// The supported watchOS version.\n    public struct WatchOSVersion: AppleOSVersion {\n        fileprivate static let name = \"watchOS\"\n        fileprivate static let minimumMajorVersion = 2\n\n        /// The underlying version representation.\n        let version: String\n\n        fileprivate init(uncheckedVersion version: String) {\n            self.version = version\n        }\n\n        /// The value that represents watchOS 2.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"watchOS 4.0 is the oldest supported version\")\n        public static let v2: WatchOSVersion = .init(string: \"2.0\")\n\n        /// The value that represents watchOS 3.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0, deprecated: 5.7, message: \"watchOS 4.0 is the oldest supported version\")\n        public static let v3: WatchOSVersion = .init(string: \"3.0\")\n\n        /// The value that represents watchOS 4.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0)\n        public static let v4: WatchOSVersion = .init(string: \"4.0\")\n\n        /// The value that represents watchOS 5.0.\n        ///\n        /// - Since: First available in PackageDescription 5.0.\n        @available(_PackageDescription, introduced: 5.0)\n        public static let v5: WatchOSVersion = .init(string: \"5.0\")\n\n        /// The value that represents watchOS 6.0.\n        ///\n        /// - Since: First available in PackageDescription 5.1.\n        @available(_PackageDescription, introduced: 5.1)\n        public static let v6: WatchOSVersion = .init(string: \"6.0\")\n\n        /// The value that represents watchOS 7.0.\n        ///\n        /// - Since: First available in PackageDescription 5.3.\n        @available(_PackageDescription, introduced: 5.3)\n        public static let v7: WatchOSVersion = .init(string: \"7.0\")\n\n        /// The value that represents watchOS 8.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v8: WatchOSVersion = .init(string: \"8.0\")\n\n        /// The value that represents watchOS 9.0.\n        ///\n        /// - Since: First available in PackageDescription 5.7.\n        @available(_PackageDescription, introduced: 5.7)\n        public static let v9: WatchOSVersion = .init(string: \"9.0\")\n\n        /// The value that represents watchOS 10.0.\n        ///\n        /// - Since: First available in PackageDescription 5.9.\n        @available(_PackageDescription, introduced: 5.9)\n        public static let v10: WatchOSVersion = .init(string: \"10.0\")\n\n        /// The value that represents watchOS 11.0.\n        ///\n        /// - Since: First available in PackageDescription 6.0.\n        @available(_PackageDescription, introduced: 6.0)\n        public static let v11: WatchOSVersion = .init(string: \"11.0\")\n\n        /// The value that represents watchOS 12.0, which has been\n        /// replaced by the value for watchOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(*, unavailable, renamed: \"v26\")\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v12: WatchOSVersion = .init(string: \"12.0\")\n\n        /// The value that represents watchOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v26: WatchOSVersion = .init(string: \"26.0\")\n    }\n\n    /// The supported visionOS version.\n    public struct VisionOSVersion: AppleOSVersion {\n        fileprivate static let name = \"visionOS\"\n        fileprivate static let minimumMajorVersion = 1\n\n        /// The underlying version representation.\n        let version: String\n\n        fileprivate init(uncheckedVersion version: String) {\n            self.version = version\n        }\n\n        /// The value that represents visionOS 1.0.\n        ///\n        /// - Since: First available in PackageDescription 5.9.\n        @available(_PackageDescription, introduced: 5.9)\n        public static let v1: VisionOSVersion = .init(string: \"1.0\")\n\n        /// The value that represents visionOS 2.0.\n        ///\n        /// - Since: First available in PackageDescription 6.0.\n        @available(_PackageDescription, introduced: 6.0)\n        public static let v2: VisionOSVersion = .init(string: \"2.0\")\n\n        /// The value that represents visionOS 3.0, which has been\n        /// replaced by the value for visionOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(*, unavailable, renamed: \"v26\")\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v3: VisionOSVersion = .init(string: \"3.0\")\n\n        /// The value that represents visionOS 26.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v26: VisionOSVersion = .init(string: \"26.0\")\n    }\n\n    /// The supported DriverKit version.\n    public struct DriverKitVersion: AppleOSVersion {\n        fileprivate static let name = \"DriverKit\"\n        fileprivate static let minimumMajorVersion = 19\n\n        /// The underlying version representation.\n        let version: String\n\n        fileprivate init(uncheckedVersion version: String) {\n            self.version = version\n        }\n\n        /// The value that represents DriverKit 19.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v19: DriverKitVersion = .init(string: \"19.0\")\n\n        /// The value that represents DriverKit 20.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v20: DriverKitVersion = .init(string: \"20.0\")\n\n        /// The value that represents DriverKit 21.0.\n        ///\n        /// - Since: First available in PackageDescription 5.5.\n        @available(_PackageDescription, introduced: 5.5)\n        public static let v21: DriverKitVersion = .init(string: \"21.0\")\n\n        /// The value that represents DriverKit 22.0.\n        ///\n        /// - Since: First available in PackageDescription 5.7.\n        @available(_PackageDescription, introduced: 5.7)\n        public static let v22: DriverKitVersion = .init(string: \"22.0\")\n\n        /// The value that represents DriverKit 23.0.\n        ///\n        /// - Since: First available in PackageDescription 5.9.\n        @available(_PackageDescription, introduced: 5.9)\n        public static let v23: DriverKitVersion = .init(string: \"23.0\")\n\n        /// The value that represents DriverKit 24.0.\n        ///\n        /// - Since: First available in PackageDescription 6.0.\n        @available(_PackageDescription, introduced: 6.0)\n        public static let v24: DriverKitVersion = .init(string: \"24.0\")\n\n        /// The value that represents DriverKit 25.0.\n        ///\n        /// - Since: First available in PackageDescription 6.2.\n        @available(_PackageDescription, introduced: 6.2)\n        public static let v25: DriverKitVersion = .init(string: \"25.0\")\n    }\n\n    /// A supported custom platform version.\n    public struct CustomPlatformVersion: AppleOSVersion {\n        /// The name of the custom platform.\n        static var name: String = \"custom platform\"\n        /// The minimum valid major version number.\n        static var minimumMajorVersion = 0\n\n        fileprivate init(uncheckedVersion version: String) {\n        }\n    }\n}\n\nfileprivate protocol AppleOSVersion: Sendable {\n    static var name: String { get }\n    static var minimumMajorVersion: Int { get }\n    init(uncheckedVersion: String)\n}\n\nstruct StringError: Error, CustomStringConvertible {\n    var error: String\n\n    init(_ error: String) {\n        self.error = error\n    }\n\n    var description: String { error }\n}\n\nfileprivate extension AppleOSVersion {\n\n    static func validateVersion(_ string: String) throws {\n        let components = string.split(separator: \".\", omittingEmptySubsequences: false)\n\n        func error(_ error: String) throws {\n            throw StringError(\"invalid \\(Self.name) version \\(string); \\(error)\")\n        }\n\n        for (idx, component) in components.enumerated() {\n            if component.isEmpty {\n                try error(\"found an empty component\")\n            }\n\n            if idx < 2 {\n                if UInt(component) == nil {\n                    try error(\"\\(component) should be a positive integer\")\n                }\n            }\n        }\n\n        if (UInt(components[0]) ?? 0) < Self.minimumMajorVersion {\n            try error(\"the minimum major version should be \\(Self.minimumMajorVersion)\")\n        }\n    }\n\n    init(string: String) {\n        do {\n            try Self.validateVersion(string)\n        } catch {\n            errors.append(\"\\(error)\")\n        }\n\n        self.init(uncheckedVersion: string)\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/Target.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_implementationOnly import Foundation\n\n/// The basic building block of a Swift package.\n///\n/// Each target contains a set of source files that Swift Package Manager compiles into a module\n/// or test suite. You can vend targets to other packages by defining products\n/// that include the targets.\n///\n/// A target may depend on other targets within the same package and on products\n/// vended by the package's dependencies.\npublic final class Target {\n\n    /// The different types of a target.\n    public enum TargetType: String {\n        /// A target that contains code for the Swift package's functionality.\n        case regular\n        /// A target that contains code for an executable's main module.\n        case executable\n        /// A target that contains tests for the Swift package's other targets.\n        case test\n        /// A target that adapts a library on the system to work with Swift\n        /// packages.\n        case system\n        /// A target that references a binary artifact.\n        case binary\n        /// A target that provides a package plug-in.\n        case plugin\n        /// A target that provides a Swift macro.\n        case `macro`\n    }\n\n    /// The different types of a target's dependency on another entity.\n    public enum Dependency: Sendable {\n        /// A dependency on a target.\n        ///\n        ///  - Parameters:\n        ///    - name: The name of the target.\n        ///    - condition: A condition that limits the application of the target dependency. For example, only apply a dependency for a specific platform.\n        case targetItem(name: String, condition: TargetDependencyCondition?)\n        /// A dependency on a product.\n        ///\n        /// - Parameters:\n        ///    - name: The name of the product.\n        ///    - package: The name of the package.\n        ///    - moduleAlias: The module aliases for targets in the product.\n        ///    - condition: A condition that limits the application of the target dependency. For example, only apply a dependency for a specific platform.\n        case productItem(name: String, package: String?, moduleAliases: [String: String]?, condition: TargetDependencyCondition?)\n        /// A by-name dependency on either a target or a product.\n        ///\n        /// - Parameters:\n        ///   - name: The name of the dependency, either a target or a product.\n        ///   - condition: A condition that limits the application of the target\n        ///     dependency. For example, only apply a dependency for a specific\n        ///     platform.\n        case byNameItem(name: String, condition: TargetDependencyCondition?)\n    }\n\n    /// The name of the target.\n    public var name: String\n\n    /// The path of the target, relative to the package root.\n    ///\n    /// If the path is `nil`, Swift Package Manager looks for a target's source files at\n    /// predefined search paths and in a subdirectory with the target's name.\n    ///\n    /// The predefined search paths are the following directories under the\n    /// package root:\n    ///\n    /// - `Sources`, `Source`, `src`, and `srcs` for regular targets\n    /// - `Tests`, `Sources`, `Source`, `src`, and `srcs` for test targets\n    ///\n    /// For example, Swift Package Manager looks for source files inside the\n    /// `[PackageRoot]/Sources/[TargetName]` directory.\n    ///\n    /// Don't escape the package root; that is, values like `../Foo` or `/Foo`\n    /// are invalid.\n    public var path: String?\n\n    /// The URL of a binary target.\n    ///\n    /// The URL points to an archive file that contains the referenced binary\n    /// artifact at its root.\n    ///\n    /// Binary targets are only available on Apple platforms.\n    @available(_PackageDescription, introduced: 5.3)\n    public var url: String?\n\n    /// The source files in this target.\n    ///\n    /// If this property is `nil`, Swift Package Manager includes all valid source files in the\n    /// target's path and treats specified paths as relative to the target's\n    /// path.\n    ///\n    /// A path can be a path to a directory or an individual source file. In\n    /// case of a directory, Swift Package Manager searches for valid source files recursively\n    /// inside it.\n    public var sources: [String]?\n\n    /// The explicit list of resource files in the target.\n    @available(_PackageDescription, introduced: 5.3)\n    public var resources: [Resource]?\n\n    /// The paths to source and resource files that you don't want to include in the target.\n    ///\n    /// Excluded paths are relative to the target path. This property has\n    /// precedence over the `sources` and `resources` properties.\n    public var exclude: [String]\n\n    /// A Boolean value that indicates whether this is a test target.\n    public var isTest: Bool {\n        return type == .test\n    }\n\n    /// The target's dependencies on other entities inside or outside the package.\n    public var dependencies: [Dependency]\n\n    /// The path to the directory that contains public headers of a C-family target.\n    ///\n    /// If this is `nil`, the directory is set to `include`.\n    public var publicHeadersPath: String?\n\n    /// The type of the target.\n    public let type: TargetType\n\n    /// If true, access to package declarations from other targets in the package is allowed.\n    public let packageAccess: Bool\n\n    /// The name of the package configuration file, without extension, for the system library target.\n    ///\n    /// If present, the Swift Package Manager tries every package configuration\n    /// name separated by a space to search for the `<name>.pc` file\n    /// to get the additional flags needed for the system library target.\n    public let pkgConfig: String?\n\n    /// The providers array for a system library target.\n    public let providers: [SystemPackageProvider]?\n\n    /// The capability provided by a package plug-in target.\n    @available(_PackageDescription, introduced: 5.5)\n    public var pluginCapability: PluginCapability?\n\n    /// The different types of capability that a plug-in can provide.\n    ///\n    /// In this version of SwiftPM, only build tool and command plug-ins are supported;\n    /// this enumeration will be extended as new plug-in capabilities are added.\n    public enum PluginCapability {\n        /// Specifies that the plug-in provides a build tool capability.\n        ///\n        /// The plug-in to apply to each target that uses it, and creates commands\n        /// that run before or during the build of the target.\n        @available(_PackageDescription, introduced: 5.5)\n        case buildTool\n\n        /// Specifies that the plug-in provides a user command capability.\n        ///\n        ///- Parameters:\n        ///   - intent: The semantic intent of the plug-in; either one of the predefined intents,\n        ///     or a custom intent.\n        ///   - permissions: Any permissions needed by the command plug-in. This affects what the\n        ///     sandbox in which the plug-in is run allows. Some permissions may require\n        ///     user approval.\n        ///\n        /// Plug-ins that specify a `command` capability define commands that can run\n        /// using the SwiftPM command line interface, or in an IDE that supports\n        /// Swift packages. You can invoke the command manually on one or more targets in a package.\n        ///\n        ///```swift\n        ///swift package <verb>\n        ///```\n        ///\n        /// The package can specify the _verb_ used to invoke the command.\n        @available(_PackageDescription, introduced: 5.6)\n        case command(intent: PluginCommandIntent, permissions: [PluginPermission] = [])\n    }\n\n    /// The target's C build settings.\n    @available(_PackageDescription, introduced: 5)\n    public var cSettings: [CSetting]?\n\n    /// The target's C++ build settings.\n    @available(_PackageDescription, introduced: 5)\n    public var cxxSettings: [CXXSetting]?\n\n    /// The target's Swift build settings.\n    @available(_PackageDescription, introduced: 5)\n    public var swiftSettings: [SwiftSetting]?\n\n    /// The target's linker settings.\n    @available(_PackageDescription, introduced: 5)\n    public var linkerSettings: [LinkerSetting]?\n \n    /// The checksum for the archive file that contains the referenced binary\n    /// artifact.\n    ///\n    /// If you make a remote binary framework available as a Swift package,\n    /// declare a remote, or _URL-based_, binary target in your package manifest\n    /// with ``Target/binaryTarget(name:url:checksum:)``. Always run `swift\n    /// package compute-checksum path/to/MyFramework.zip` at the command line to\n    /// make sure you create a correct SHA256 checksum.\n    ///\n    /// For more information, see [Distributing binary frameworks as Swift packages](https://developer.apple.com/documentation/xcode/distributing-binary-frameworks-as-swift-packages).\n    @available(_PackageDescription, introduced: 5.3)\n    public var checksum: String?\n\n    /// The uses of package plug-ins by the target.\n    @available(_PackageDescription, introduced: 5.5)\n    public var plugins: [PluginUsage]?\n    \n    /// A plug-in used in a target.\n    @available(_PackageDescription, introduced: 5.5)\n    public enum PluginUsage {\n        /// Specifies the use of a plug-in product in a package dependency.\n        ///\n        /// - Parameters:\n        ///   - name: The name of the plug-in target.\n        ///   - package: The name of the package that defines the plug-in target.\n        case plugin(name: String, package: String?)\n    }\n\n    /// Construct a target.\n    @_spi(PackageDescriptionInternal)\n    public init(\n        name: String,\n        dependencies: [Dependency],\n        path: String?,\n        url: String? = nil,\n        exclude: [String],\n        sources: [String]?,\n        resources: [Resource]? = nil,\n        publicHeadersPath: String?,\n        type: TargetType,\n        packageAccess: Bool,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProvider]? = nil,\n        pluginCapability: PluginCapability? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil,\n        checksum: String? = nil,\n        plugins: [PluginUsage]? = nil\n    ) {\n        self.name = name\n        self.dependencies = dependencies\n        self.path = path\n        self.url = url\n        self.publicHeadersPath = publicHeadersPath\n        self.sources = sources\n        self.resources = resources\n        self.exclude = exclude\n        self.type = type\n        self.packageAccess = packageAccess\n        self.pkgConfig = pkgConfig\n        self.providers = providers\n        self.pluginCapability = pluginCapability\n        self.cSettings = cSettings\n        self.cxxSettings = cxxSettings\n        self.swiftSettings = swiftSettings\n        self.linkerSettings = linkerSettings\n        self.checksum = checksum\n        self.plugins = plugins\n\n        switch type {\n        case .regular, .executable, .test:\n            precondition(\n                url == nil &&\n                pkgConfig == nil &&\n                providers == nil &&\n                pluginCapability == nil &&\n                checksum == nil\n            )\n        case .system:\n            precondition(\n                url == nil &&\n                dependencies.isEmpty &&\n                exclude.isEmpty &&\n                sources == nil &&\n                resources == nil &&\n                publicHeadersPath == nil &&\n                pluginCapability == nil &&\n                cSettings == nil &&\n                cxxSettings == nil &&\n                swiftSettings == nil &&\n                linkerSettings == nil &&\n                checksum == nil &&\n                plugins == nil\n            )\n        case .binary:\n            precondition(\n                dependencies.isEmpty &&\n                exclude.isEmpty &&\n                sources == nil &&\n                resources == nil &&\n                publicHeadersPath == nil &&\n                pkgConfig == nil &&\n                providers == nil &&\n                pluginCapability == nil &&\n                cSettings == nil &&\n                cxxSettings == nil &&\n                swiftSettings == nil &&\n                linkerSettings == nil &&\n                plugins == nil\n            )\n        case .plugin:\n            precondition(\n                url == nil &&\n                resources == nil &&\n                publicHeadersPath == nil &&\n                pkgConfig == nil &&\n                providers == nil &&\n                pluginCapability != nil &&\n                cSettings == nil &&\n                cxxSettings == nil &&\n                swiftSettings == nil &&\n                linkerSettings == nil &&\n                plugins == nil\n            )\n        case .macro:\n            precondition(\n                url == nil &&\n                resources == nil &&\n                publicHeadersPath == nil &&\n                pkgConfig == nil &&\n                providers == nil &&\n                pluginCapability == nil &&\n                cSettings == nil &&\n                cxxSettings == nil\n            )\n        }\n    }\n\n    /// Creates a library or executable target.\n    ///\n    /// A target can contain either Swift or C-family source files, but not both. The Swift Package Manager\n    /// considers a target to be an executable target if its directory contains a `main.swift`, `main.m`, `main.c`,\n    /// or `main.cpp` file. The Swift Package Manager considers all other targets to be library targets.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - publicHeadersPath: The directory containing public headers of a C-family library target.\n    @available(_PackageDescription, introduced: 4, obsoleted: 5)\n    public static func target(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        publicHeadersPath: String? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            publicHeadersPath: publicHeadersPath,\n            type: .regular,\n            packageAccess: false\n        )\n    }\n\n    /// Creates a library or executable target.\n    ///\n    /// A target can contain either Swift or C-family source files, but not both. The Swift Package Manager\n    /// considers a target to be an executable target if its directory contains a `main.swift`, `main.m`, `main.c`,\n    /// or `main.cpp` file. The Swift Package Manager considers all other targets to be library targets.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       Paths are relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - publicHeadersPath: The directory containing public headers of a C-family library target.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    @available(_PackageDescription, introduced: 5, obsoleted: 5.3)\n    public static func target(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        publicHeadersPath: String? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            publicHeadersPath: publicHeadersPath,\n            type: .regular,\n            packageAccess: false,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings\n        )\n    }\n\n    /// Creates a regular target.\n    ///\n    /// A target can contain either Swift or C-family source files, but not both. It contains code that is built as\n    /// a regular module that can be included in a library or executable product, but that cannot itself be used as\n    /// the main target of an executable product.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - publicHeadersPath: The directory containing public headers of a C-family library target.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    @available(_PackageDescription, introduced: 5.3, obsoleted: 5.5)\n    public static func target(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        publicHeadersPath: String? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: publicHeadersPath,\n            type: .regular,\n            packageAccess: false,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings\n        )\n    }\n\n    /// Creates a regular target.\n    ///\n    /// A target can contain either Swift or C-family source files, but not both. It contains code that is built as\n    /// a regular module that can be included in a library or executable product, but that cannot itself be used as\n    /// the main target of an executable product.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - publicHeadersPath: The directory containing public headers of a C-family library target.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    ///   - plugins: The plug-ins used by this target.\n    @available(_PackageDescription, introduced: 5.5, obsoleted: 5.9)\n    public static func target(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        publicHeadersPath: String? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil,\n        plugins: [PluginUsage]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: publicHeadersPath,\n            type: .regular,\n            packageAccess: false,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings,\n            plugins: plugins\n        )\n    }\n\n    /// Creates a regular target.\n    ///\n    /// A target can contain either Swift or C-family source files, but not both. It contains code that is built as\n    /// a regular module for inclusion in a library or executable product, but that cannot itself be used as\n    /// the main target of an executable product.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - publicHeadersPath: The directory that contains public headers of a C-family library target.\n    ///   - packageAccess: Allows package symbols from other targets in the package.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    ///   - plugins: The plug-ins used by this target\n    @available(_PackageDescription, introduced: 5.9)\n    public static func target(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        publicHeadersPath: String? = nil,\n        packageAccess: Bool = true,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil,\n        plugins: [PluginUsage]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: publicHeadersPath,\n            type: .regular,\n            packageAccess: packageAccess,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings,\n            plugins: plugins\n        )\n    }\n\n    /// Creates an executable target.\n    ///\n    /// An executable target can contain either Swift or C-family source files, but not both. It contains code that\n    /// is built as an executable module that can be used as the main target of an executable product. The target\n    /// is expected to either have a source file named `main.swift`, `main.m`, `main.c`, or `main.cpp`, or a source\n    /// file that contains the `@main` keyword.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - publicHeadersPath: The directory containing public headers of a C-family library target.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    @available(_PackageDescription, introduced: 5.4, obsoleted: 5.5)\n    public static func executableTarget(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        publicHeadersPath: String? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: publicHeadersPath,\n            type: .executable,\n            packageAccess: false,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings\n        )\n    }\n\n    /// Creates an executable target.\n    ///\n    /// An executable target can contain either Swift or C-family source files, but not both. It contains code that\n    /// is built as an executable module that can be used as the main target of an executable product. The target\n    /// is expected to either have a source file named `main.swift`, `main.m`, `main.c`, or `main.cpp`, or a source\n    /// file that contains the `@main` keyword.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - publicHeadersPath: The directory containing public headers of a C-family library target.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    ///   - plugins: The plug-ins used by this target.\n    @available(_PackageDescription, introduced: 5.5, obsoleted: 5.9)\n    public static func executableTarget(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        publicHeadersPath: String? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil,\n        plugins: [PluginUsage]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: publicHeadersPath,\n            type: .executable,\n            packageAccess: false,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings,\n            plugins: plugins\n        )\n    }\n    /// Creates an executable target.\n    ///\n    /// An executable target can contain either Swift or C-family source files, but not both. It contains code that\n    /// is built as an executable module for use as the main target of an executable product. The target\n    /// is expected to either have a source file named `main.swift`, `main.m`, `main.c`, or `main.cpp`, or a source\n    /// file that contains the `@main` keyword.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - publicHeadersPath: The directory that contains public headers of a C-family library target.\n    ///   - packageAccess: Allows package symbols from other targets in the package.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    ///   - plugins: The plug-ins used by this target\n    @available(_PackageDescription, introduced: 5.9)\n    public static func executableTarget(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        publicHeadersPath: String? = nil,\n        packageAccess: Bool = true,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil,\n        plugins: [PluginUsage]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: publicHeadersPath,\n            type: .executable,\n            packageAccess: packageAccess,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings,\n            plugins: plugins\n        )\n    }\n\n    /// Creates a test target.\n    ///\n    /// Write test targets using the XCTest testing framework.\n    /// Test targets generally declare a dependency on the targets they test.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    @available(_PackageDescription, introduced: 4, obsoleted: 5)\n    public static func testTarget(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            publicHeadersPath: nil,\n            type: .test,\n            packageAccess: false\n        )\n    }\n\n    /// Creates a test target.\n    ///\n    /// Write test targets using the XCTest testing framework.\n    /// Test targets generally declare a dependency on the targets they test.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    @available(_PackageDescription, introduced: 5, obsoleted: 5.3)\n    public static func testTarget(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            publicHeadersPath: nil,\n            type: .test,\n            packageAccess: false,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings\n        )\n    }\n\n    /// Creates a test target.\n    ///\n    /// Write test targets using the XCTest testing framework.\n    /// Test targets generally declare a dependency on the targets they test.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    @available(_PackageDescription, introduced: 5.3, obsoleted: 5.5)\n    public static func testTarget(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: nil,\n            type: .test,\n            packageAccess: false,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings\n        )\n    }\n\n    /// Creates a test target.\n    ///\n    /// Write test targets using the XCTest testing framework.\n    /// Test targets generally declare a dependency on the targets they test.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, the Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that the Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       the Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    ///   - plugins: The plug-ins used by this target.\n    @available(_PackageDescription, introduced: 5.5, obsoleted: 5.9)\n    public static func testTarget(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil,\n        plugins: [PluginUsage]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: nil,\n            type: .test,\n            packageAccess: false,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings,\n            plugins: plugins\n        )\n    }\n\n    /// Creates a test target.\n    ///\n    /// Write test targets using the XCTest testing framework.\n    /// Test targets generally declare a dependency on the targets they test.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - dependencies: The dependencies of the target. A dependency can be another target in the package or a product from a package dependency.\n    ///   - path: The custom path for the target. By default, Swift Package Manager requires a target's sources to reside at predefined search paths;\n    ///       for example, `[PackageRoot]/Sources/[TargetName]`.\n    ///       Don't escape the package root; for example, values like `../Foo` or `/Foo` are invalid.\n    ///   - exclude: A list of paths to files or directories that Swift Package Manager shouldn't consider to be source or resource files.\n    ///       A path is relative to the target's directory.\n    ///       This parameter has precedence over the ``sources`` parameter.\n    ///   - sources: An explicit list of source files. If you provide a path to a directory,\n    ///       Swift Package Manager searches for valid source files recursively.\n    ///   - resources: An explicit list of resources files.\n    ///   - packageAccess: Allows access to package symbols from other targets in the package.\n    ///   - cSettings: The C settings for this target.\n    ///   - cxxSettings: The C++ settings for this target.\n    ///   - swiftSettings: The Swift settings for this target.\n    ///   - linkerSettings: The linker settings for this target.\n    ///   - plugins: The plug-ins used by this target.\n    @available(_PackageDescription, introduced: 5.9)\n    public static func testTarget(\n        name: String,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        resources: [Resource]? = nil,\n        packageAccess: Bool = true,\n        cSettings: [CSetting]? = nil,\n        cxxSettings: [CXXSetting]? = nil,\n        swiftSettings: [SwiftSetting]? = nil,\n        linkerSettings: [LinkerSetting]? = nil,\n        plugins: [PluginUsage]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            resources: resources,\n            publicHeadersPath: nil,\n            type: .test,\n            packageAccess: packageAccess,\n            cSettings: cSettings,\n            cxxSettings: cxxSettings,\n            swiftSettings: swiftSettings,\n            linkerSettings: linkerSettings,\n            plugins: plugins\n        )\n    }\n\n    /// Creates a system library target.\n    ///\n    /// Use system library targets to adapt a library installed on the system to\n    /// work with Swift packages. Such libraries are generally installed by\n    /// system package managers (such as Homebrew and apt-get) and exposed to\n    /// Swift packages by providing a `modulemap` file along with other metadata\n    /// such as the library's `pkgConfig` name.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - path: The custom path for the target. By default, a targets sources\n    ///     are expected to be located in the predefined search paths, such as\n    ///     `[PackageRoot]/Sources/[TargetName]`. Do not escape the package root;\n    ///     that is, values like `../Foo` or `/Foo` are invalid.\n    ///   - pkgConfig: The name of the `pkg-config` file for this system library.\n    ///   - providers: The providers for this system library.\n    public static func systemLibrary(\n        name: String,\n        path: String? = nil,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProvider]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: [],\n            path: path,\n            exclude: [],\n            sources: nil,\n            publicHeadersPath: nil,\n            type: .system,\n            packageAccess: false,\n            pkgConfig: pkgConfig,\n            providers: providers)\n    }\n\n    /// Creates a binary target that references a remote artifact.\n    ///\n    /// Binary targets are only available on Apple platforms.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - url: The URL to the binary artifact. This URL must point to an archive\n    ///     file that contains a binary artifact in its root directory.\n    ///   - checksum: The checksum of the archive file that contains the binary\n    ///     artifact.\n    @available(_PackageDescription, introduced: 5.3)\n    public static func binaryTarget(\n        name: String,\n        url: String,\n        checksum: String\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: [],\n            path: nil,\n            url: url,\n            exclude: [],\n            sources: nil,\n            publicHeadersPath: nil,\n            type: .binary,\n            packageAccess: false,\n            checksum: checksum)\n    }\n\n    /// Creates a binary target that references an artifact on disk.\n    ///\n    /// Binary targets are only available on Apple platforms.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - path: The path to the binary artifact. This path can point directly to\n    ///     a binary artifact or to an archive file that contains the binary\n    ///     artifact at its root.\n    @available(_PackageDescription, introduced: 5.3)\n    public static func binaryTarget(\n        name: String,\n        path: String\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: [],\n            path: path,\n            exclude: [],\n            sources: nil,\n            publicHeadersPath: nil,\n            type: .binary,\n            packageAccess: false)\n    }\n    \n    /// Defines a new package plugin target.\n    ///\n    /// A plugin target provides custom build commands to SwiftPM (and to\n    /// any IDEs based on libSwiftPM).\n    ///\n    /// The capability determines what kind of build commands it can add. Besides\n    /// determining at what point in the build those commands run, the capability\n    /// determines the context that is available to the plugin and the kinds of\n    /// commands it can create.\n    ///\n    /// In the initial version of this proposal, three capabilities are provided:\n    /// prebuild, build tool, and postbuild. See the declaration of each capability\n    /// under ``PluginCapability-swift.enum`` for more information.\n    ///\n    /// The package plugin itself is implemented using a Swift script that is\n    /// invoked for each target that uses it. The script is invoked after the\n    /// package graph has been resolved, but before the build system creates its\n    /// dependency graph. It is also invoked after changes to the target or the\n    /// build parameters.\n    ///\n    /// Note that the role of the package plugin is only to define the commands\n    /// that will run before, during, or after the build. It does not itself run\n    /// those commands. The commands are defined in an IDE-neutral way, and are\n    /// run as appropriate by the build system that builds the package. The extension\n    /// itself is only a procedural way of generating commands and their input\n    /// and output dependencies.\n    ///\n    /// The package plugin may specify the executable targets or binary targets\n    /// that provide the build tools that will be used by the generated commands\n    /// during the build. In the initial implementation, prebuild actions can only\n    /// depend on binary targets. Build tool and postbuild plugins can depend\n    /// on executables as well as binary targets. This is due to how\n    /// Swift Package Manager constructs its build plan.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the plugin target.\n    ///   - capability: The type of capability the plugin target provides.\n    ///   - dependencies: The plugin target's dependencies.\n    ///   - path: The path of the plugin target, relative to the package root.\n    ///   - exclude: The paths to source and resource files that you want to exclude from the plug-in target.\n    ///   - sources: The source files in the plug-in target.\n    /// - Returns: A `Target` instance.\n    @available(_PackageDescription, introduced: 5.5, obsoleted: 5.9)\n    public static func plugin(\n        name: String,\n        capability: PluginCapability,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            publicHeadersPath: nil,\n            type: .plugin,\n            packageAccess: false,\n            pluginCapability: capability)\n    }\n\n    /// Defines a new package plug-in target.\n    ///\n    /// A plug-in target provides custom build commands to SwiftPM (and to\n    /// any IDEs based on libSwiftPM).\n    ///\n    /// The capability determines what kind of build commands it can add. Besides\n    /// determining at what point in the build those commands run, the capability\n    /// determines the context that is available to the plug-in and the kinds of\n    /// commands it can create.\n    ///\n    /// In the initial version of this proposal, three capabilities are provided:\n    /// prebuild, build tool, and postbuild. For more information, see the declaration of each capability\n    /// under ``PluginCapability-swift.enum``.\n    ///\n    /// The package plug-in itself is implemented using a Swift script that is\n    /// invoked for each target that uses it. The script is invoked after the\n    /// package graph has been resolved, but before the build system creates its\n    /// dependency graph. It's also invoked after changes to the target or the\n    /// build parameters.\n    ///\n    /// Note that the role of the package plug-in is only to define the commands\n    /// that run before, during, or after the build. It doesn't run\n    /// those commands itself. The commands are defined in an IDE-neutral way, and are\n    /// run as appropriate by the build system that builds the package. The extension\n    /// itself is only a procedural way of generating commands and their input\n    /// and output dependencies.\n    ///\n    /// The package plug-in may specify the executable or binary targets\n    /// that provide the build tools used by the generated commands\n    /// during the build. In the initial implementation, prebuild actions can only\n    /// depend on binary targets. Build tool and postbuild plug-ins can depend\n    /// on executables as well as binary targets. This is due to how\n    /// Swift Package Manager constructs its build plan.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the plug-in target.\n    ///   - capability: The type of capability the plug-in target provides.\n    ///   - dependencies: The plug-in target's dependencies.\n    ///   - path: The path of the plug-in target relative to the package root.\n    ///   - exclude: The paths to source and resource files that you want to exclude from the plug-in target.\n    ///   - sources: The source files in the plug-in target.\n    ///   - packageAccess: Allows access to package symbols from other targets in the package.\n    /// - Returns: A `Target` instance.\n    @available(_PackageDescription, introduced: 5.9)\n    public static func plugin(\n        name: String,\n        capability: PluginCapability,\n        dependencies: [Dependency] = [],\n        path: String? = nil,\n        exclude: [String] = [],\n        sources: [String]? = nil,\n        packageAccess: Bool = true\n    ) -> Target {\n        return Target(\n            name: name,\n            dependencies: dependencies,\n            path: path,\n            exclude: exclude,\n            sources: sources,\n            publicHeadersPath: nil,\n            type: .plugin,\n            packageAccess: packageAccess,\n            pluginCapability: capability)\n    }\n}\n\nextension Target.Dependency {\n    @available(_PackageDescription, obsoleted: 5.7, message: \"use .product(name:package:condition) instead.\")\n    public static func productItem(name: String, package: String? = nil, condition: TargetDependencyCondition? = nil) -> Target.Dependency {\n        return .productItem(name: name, package: package, moduleAliases: nil, condition: nil)\n    }\n\n    /// Creates a dependency on a target in the same package.\n    ///\n    /// - Parameter name: The name of the target.\n    /// - Returns: A `Target.Dependency` instance.\n    @available(_PackageDescription, obsoleted: 5.3)\n    public static func target(name: String) -> Target.Dependency {\n        return .targetItem(name: name, condition: nil)\n    }\n\n    /// Creates a dependency on a product from a package dependency.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the product.\n    ///   - package: The name of the package.\n    /// - Returns: A `Target.Dependency` instance.\n@available(_PackageDescription, obsoleted: 5.2, message: \"the 'package' argument is mandatory as of tools version 5.2\")\n    public static func product(name: String, package: String? = nil) -> Target.Dependency {\n        return .productItem(name: name, package: package, moduleAliases: nil, condition: nil)\n    }\n\n    /// Creates a dependency that resolves to either a target or a product with the specified name.\n    ///\n    /// - Parameter name: The name of the dependency, either a target or a product.\n    /// - Returns: A `Target.Dependency` instance.\n    /// The Swift Package Manager creates the by-name dependency after it has loaded the package graph.\n@available(_PackageDescription, obsoleted: 5.3)\n    public static func byName(name: String) -> Target.Dependency {\n        return .byNameItem(name: name, condition: nil)\n    }\n\n    /// Creates a dependency on a product from a package dependency.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the product.\n    ///   - package: The name of the package.\n    /// - Returns: A `Target.Dependency` instance.\n@available(_PackageDescription, introduced: 5.2, obsoleted: 5.3)\n    public static func product(\n        name: String,\n        package: String\n    ) -> Target.Dependency {\n        return .productItem(name: name, package: package, moduleAliases: nil, condition: nil)\n    }\n\n    /// Creates a dependency on a target in the same package.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the target.\n    ///   - condition: A condition that limits the application of the target\n    ///     dependency. For example, only apply a dependency for a specific\n    ///     platform.\n    /// - Returns: A `Target.Dependency` instance.\n@available(_PackageDescription, introduced: 5.3)\n    public static func target(name: String, condition: TargetDependencyCondition? = nil) -> Target.Dependency {\n        return .targetItem(name: name, condition: condition)\n    }\n\n    /// Creates a target dependency on a product from a package dependency.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the product.\n    ///   - package: The name of the package.\n    ///   - condition: A condition that limits the application of the target\n    ///     dependency. For example, only apply a dependency for a specific\n    ///     platform.\n    /// - Returns: A `Target.Dependency` instance.\n@_disfavoredOverload\n    @available(_PackageDescription, introduced: 5.3, obsoleted: 5.7)\n    public static func product(\n        name: String,\n        package: String,\n        condition: TargetDependencyCondition? = nil\n    ) -> Target.Dependency {\n        return .productItem(name: name, package: package, moduleAliases: nil, condition: condition)\n    }\n\n    /// Creates a target dependency on a product from a package dependency.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the product.\n    ///   - package: The name of the package.\n    ///   - moduleAliases: The module aliases for targets in the product.\n    ///   - condition: A condition that limits the application of the target dependency. For example, only apply a\n    ///       dependency for a specific platform.\n    /// - Returns: A `Target.Dependency` instance.\n@available(_PackageDescription, introduced: 5.7)\n    public static func product(\n      name: String,\n      package: String,\n      moduleAliases: [String: String]? = nil,\n      condition: TargetDependencyCondition? = nil\n    ) -> Target.Dependency {\n        return .productItem(name: name, package: package, moduleAliases: moduleAliases, condition: condition)\n    }\n\n    /// Creates a dependency that resolves to either a target or a product with\n    /// the specified name.\n    ///\n    /// Swift Package Manager creates the by-name dependency after it has loaded the package\n    /// graph.\n    ///\n    /// - Parameters:\n    ///   - name: The name of the dependency, either a target or a product.\n    ///   - condition: A condition that limits the application of the target\n    ///     dependency. For example, only apply a dependency for a specific\n    ///     platform.\n    /// - Returns: A `Target.Dependency` instance.\n@available(_PackageDescription, introduced: 5.3)\n    public static func byName(name: String, condition: TargetDependencyCondition? = nil) -> Target.Dependency {\n        return .byNameItem(name: name, condition: condition)\n    }\n}\n\n/// A condition that limits the application of a target's dependency.\npublic struct TargetDependencyCondition: Sendable {\n    let platforms: [Platform]?\n    let traits: Set<String>?\n\n    private init(platforms: [Platform]?, traits: Set<String>?) {\n        self.platforms = platforms\n        self.traits = traits\n    }\n\n    /// Creates a target dependency condition.\n    ///\n    /// - Parameter platforms: The applicable platforms for this target dependency condition.\n    @_disfavoredOverload\n    @available(_PackageDescription, obsoleted: 5.7, message: \"using .when with nil platforms is obsolete\")\n    public static func when(\n        platforms: [Platform]? = nil\n    ) -> TargetDependencyCondition {\n        // FIXME: This should be an error, not a precondition.\n        precondition(!(platforms == nil))\n        return TargetDependencyCondition(platforms: platforms, traits: nil)\n    }\n\n    /// Creates a target dependency condition.\n    ///\n    /// - Parameter platforms: The applicable platforms for this target dependency condition.\n    @available(_PackageDescription, introduced: 5.7)\n    public static func when(\n        platforms: [Platform]\n    ) -> TargetDependencyCondition? {\n        return !platforms.isEmpty ? TargetDependencyCondition(platforms: platforms, traits: nil) : .none\n    }\n\n    /// Creates a target dependency condition.\n    ///\n    /// - Parameter platforms: The applicable platforms for this target dependency condition.\n    /// - Parameter traits: The applicable traits for this target dependency condition.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func when(\n        platforms: [Platform],\n        traits: Set<String>\n    ) -> TargetDependencyCondition? {\n        return TargetDependencyCondition(platforms: platforms, traits: traits)\n    }\n\n    /// Creates a target dependency condition.\n    ///\n    /// - Parameter traits: The applicable traits for this target dependency condition.\n    @available(_PackageDescription, introduced: 6.1)\n    public static func when(\n        traits: Set<String>\n    ) -> TargetDependencyCondition? {\n        return TargetDependencyCondition(platforms: nil, traits: traits)\n    }\n}\n\nextension Target.PluginCapability {\n    \n    /// The plug-in is a build tool.\n    ///\n    /// The plug-in to apply to each target that uses it, and creates commands\n    /// that run before or during the build of the target.\n    ///\n    ///  - Returns: A plug-in capability that defines a build tool.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func buildTool() -> Target.PluginCapability {\n        return .buildTool\n    }\n}\n\n/// The intended use case of the command plug-in.\n@available(_PackageDescription, introduced: 5.6)\npublic enum PluginCommandIntent {\n    /// The plug-in generates documentation.\n    ///\n    /// The command used to generate documentation, either by parsing the\n    /// package contents directly or by using the build system support for generating\n    /// symbol graphs. Invoked by a `generate-documentation` verb to `swift package`.\n    case documentationGeneration\n\n    /// The plug-in formats source code.\n    ///\n    /// The command used to modify the source code in the package based\n    /// on a set of rules. Invoked by a `format-source-code` verb to `swift package`.\n    case sourceCodeFormatting\n\n    /// A custom command plug-in intent.\n    ///\n    ///  Use this case when none of the predefined cases fulfill the role of the plug-in.\n    ///  - Parameters:\n    ///    - verb: The invocation verb of the plug-in.\n    ///    - description: A human readable description of the plug-in's role.\n    case custom(verb: String, description: String)\n}\n\n@available(_PackageDescription, introduced: 5.6)\npublic extension PluginCommandIntent {\n    /// The plugin generates documentation.\n    ///\n    /// The intent of the command is to generate documentation, either by parsing the\n    /// package contents directly or by using the build system support for generating\n    /// symbol graphs. Invoked by a `generate-documentation` verb to `swift package`.\n    ///\n    ///  - Returns: A `PluginCommandIntent` instance.\n    static func documentationGeneration() -> PluginCommandIntent {\n        return documentationGeneration\n    }\n\n    /// The plug-in formats source code.\n    ///\n    /// The intent of the command is to modify the source code in the package based\n    /// on a set of rules. Invoked by a `format-source-code` verb to `swift package`.\n    ///\n    /// - Returns: A `PluginCommandIntent` instance.\n    static func sourceCodeFormatting() -> PluginCommandIntent {\n        return sourceCodeFormatting\n    }\n}\n\n/// The type of permission a plug-in requires.\n///\n/// Supported types are ``allowNetworkConnections(scope:reason:)`` and ``writeToPackageDirectory(reason:)``.\n@available(_PackageDescription, introduced: 5.6)\npublic enum PluginPermission {\n    /// Create a permission to make network connections.\n    ///\n    /// The command plug-in requires permission to make network connections. The `reason` string is shown\n    /// to the user at the time of request for approval, explaining why the plug-in is requesting access.\n    ///   - Parameter scope: The scope of the permission.\n    ///   - Parameter reason: A reason why the permission is needed. This is shown to the user when permission is sought.\n    @available(_PackageDescription, introduced: 5.9)\n    case allowNetworkConnections(scope: PluginNetworkPermissionScope, reason: String)\n\n    /// Create a permission to modify files in the package's directory.\n    ///\n    /// The command plug-in requires permission to modify the files under the package\n    /// directory. The `reason` string is shown to the user at the time of request\n    /// for approval, explaining why the plug-in requests access.\n    ///   - Parameter reason: A reason why the permission is needed. This is shown to the user when permission is sought.\n    case writeToPackageDirectory(reason: String)\n}\n\n/// The scope of a network permission.\n///\n/// The scope can be none, local connections only, or all connections.\n@available(_PackageDescription, introduced: 5.9)\npublic enum PluginNetworkPermissionScope {\n    /// Do not allow network access.\n    case none\n    /// Allow local network connections; can be limited to a list of allowed ports.\n    case local(ports: [Int] = [])\n    /// Allow local and outgoing network connections; can be limited to a list of allowed ports.\n    case all(ports: [Int] = [])\n    /// Allow connections to Docker through UNIX domain sockets.\n    case docker\n    /// Allow connections to any UNIX domain socket.\n    case unixDomainSocket\n\n    /// Allow local and outgoing network connections, limited to a range of allowed ports.\n    public static func all(ports: Range<Int>) -> PluginNetworkPermissionScope {\n        return .all(ports: Array(ports))\n    }\n\n    /// Allow local network connections, limited to a range of allowed ports.\n    public static func local(ports: Range<Int>) -> PluginNetworkPermissionScope {\n        return .local(ports: Array(ports))\n    }\n}\n\nextension Target.PluginUsage {\n    /// Specifies use of a plugin target in the same package.\n    ///\n    /// - Parameter name: The name of the plugin target.\n    /// - Returns: A `PluginUsage` instance.\n    @available(_PackageDescription, introduced: 5.5)\n    public static func plugin(name: String) -> Target.PluginUsage {\n        return .plugin(name: name, package: nil)\n    }\n}\n\n\n// MARK: ExpressibleByStringLiteral\n\n/// `ExpressibleByStringLiteral` conformance.\n///\nextension Target.Dependency: ExpressibleByStringLiteral {\n\n    /// Creates a target dependency instance with the given value.\n    ///\n    /// - Parameter value: A string literal.\n    public init(stringLiteral value: String) {\n        self = .byNameItem(name: value, condition: nil)\n    }\n}\n\n/// `ExpressibleByStringLiteral` conformance.\n///\nextension Target.PluginUsage: ExpressibleByStringLiteral {\n\n    /// Specifies use of a plugin target in the same package.\n    ///\n    /// - Parameter value: A string literal.\n    public init(stringLiteral value: String) {\n        self = .plugin(name: value, package: nil)\n    }\n}\n\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/Trait.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A package trait.\n///\n/// A trait is a package feature that expresses conditional compilation and potentially optional dependencies.\n/// It is typically used to expose additional or extended API for the package.\n///\n/// When you define a trait on a package, the package manager uses the name of that trait as a conditional block for the package's code.\n/// Use the conditional block to enable imports or code paths for that trait.\n/// For example, a trait with the canonical name `MyTrait` allows you to use the name as a conditional block:\n///\n/// ```swift\n/// #if MyTrait\n/// // additional imports or APIs that MyTrait enables\n/// #endif // MyTrait\n/// ```\n///\n/// - Important: Traits must be strictly additive. Enabling a trait **must not** remove API.\n///\n/// If your conditional code requires a dependency that you want to enable only when the trait is enabled,\n/// add a conditional declaration to the target dependencies,\n/// then include the import statement within the conditional block.\n/// The following example illustrates enabling the dependency `MyDependency` when the trait `Trait1` is enabled:\n///\n/// ```swift\n/// targets: [\n///    .target(\n///        name: \"MyTarget\",\n///        dependencies: [\n///            .product(\n///                name: \"MyAPI\",\n///                package: \"MyDependency\",\n///                condition: .when(traits: [\"Trait1\"])\n///            )\n///        ]\n///    ),\n/// ]\n/// ```\n///\n/// Coordinate a declaration like the example above with code that imports the dependency in a conditional block:\n///\n/// ```swift\n/// #if Trait1\n/// import MyAPI\n/// #endif // Trait1\n/// ```\n@available(_PackageDescription, introduced: 6.1)\npublic struct Trait: Hashable, ExpressibleByStringLiteral {\n    /// Declares the default traits for this package.\n    public static func `default`(enabledTraits: Set<String>) -> Self {\n        .init(\n            name: \"default\",\n            description: \"The default traits of this package.\",\n            enabledTraits: enabledTraits\n        )\n    }\n\n    /// The trait's canonical name.\n    ///\n    /// Use the trait's name to enable the trait or when referring to it from other modifiers in the manifest.\n    /// The trait's name also defines the conditional block that the compiler supports when the trait is active.\n    ///\n    /// The following rules are enforced on trait names:\n    /// - The first character must be a [Unicode XID start character](https://unicode.org/reports/tr31/#Figure_Code_Point_Categories_for_Identifier_Parsing)\n    /// (most letters), a digit, or `_`.\n    /// - Subsequent characters must be a [Unicode XID continue character](https://unicode.org/reports/tr31/#Figure_Code_Point_Categories_for_Identifier_Parsing)\n    /// (a digit, `_`, or most letters), `-`, or `+`.\n    /// - The names `default` and `defaults` (in any letter casing combination) aren't allowed as trait names to avoid confusion with default traits.\n    public var name: String\n\n    /// The trait's description.\n    ///\n    /// Use the description to explain the additional functionality that the trait enables.\n    public var description: String?\n\n    /// A set of other traits of this package that this trait enables.\n    public var enabledTraits: Set<String>\n\n    /// Creates a trait with a name, a description, and set of additional traits it enables.\n    ///\n    /// - Parameters:\n    ///   - name: The trait's canonical name.\n    ///   - description: The trait's description.\n    ///   - enabledTraits: A set of other traits of this package that this trait enables.\n    public init(\n        name: String,\n        description: String? = nil,\n        enabledTraits: Set<String> = []\n    ) {\n        self.name = name\n        self.description = description\n        self.enabledTraits = enabledTraits\n    }\n\n    /// Creates a trait with the name you provide.\n    /// - Parameter value: The trait's canonical name.\n    public init(stringLiteral value: StringLiteralType) {\n        self.init(name: value)\n    }\n\n    /// Creates a trait with a name, a description, and set of additional traits it enables.\n    ///\n    /// - Parameters:\n    ///   - name: The trait's canonical name.\n    ///   - description: The trait's description.\n    ///   - enabledTraits: A set of other traits of this package that this trait enables.\n    public static func trait(\n        name: String,\n        description: String? = nil,\n        enabledTraits: Set<String> = []\n    ) -> Trait {\n        .init(\n            name: name,\n            description: description,\n            enabledTraits: enabledTraits\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/Version+StringLiteralConvertible.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension Version: ExpressibleByStringLiteral {\n    /// Initializes a version struct with the provided string literal.\n    ///\n    /// - Parameter value: A string literal to use for creating a new version struct.\n    public init(stringLiteral value: String) {\n        if let version = Version(value) {\n            self = version\n        } else {\n            // If version can't be initialized using the string literal, report\n            // the error and initialize with a dummy value. This is done to\n            // report error to the invoking tool (like swift build) gracefully\n            // rather than just crashing.\n            errors.append(\"Invalid semantic version string '\\(value)'\")\n            self.init(0, 0, 0)\n        }\n    }\n\n    /// Initializes a version struct with the provided extended grapheme cluster.\n    ///\n    /// - Parameter value: An extended grapheme cluster to use for creating a new\n    ///   version struct.\n    public init(extendedGraphemeClusterLiteral value: String) {\n        self.init(stringLiteral: value)\n    }\n\n    /// Initializes a version struct with the provided Unicode string.\n    ///\n    /// - Parameter value: A Unicode string to use for creating a new version struct.\n    public init(unicodeScalarLiteral value: String) {\n        self.init(stringLiteral: value)\n    }\n}\n\nextension Version: LosslessStringConvertible {\n    /// Initializes a version struct with the provided version string.\n    /// - Parameter versionString: A version string to use for creating a new version struct.\n    public init?(_ versionString: String) {\n        // SemVer 2.0.0 allows only ASCII alphanumerical characters and \"-\" in the version string, except for \".\" and \"+\" as delimiters. (\"-\" is used as a delimiter between the version core and pre-release identifiers, but it's allowed within pre-release and metadata identifiers as well.)\n        // Alphanumerics check will come later, after each identifier is split out (i.e. after the delimiters are removed).\n        guard versionString.allSatisfy(\\.isASCII) else { return nil }\n\n        let metadataDelimiterIndex = versionString.firstIndex(of: \"+\")\n        // SemVer 2.0.0 requires that pre-release identifiers come before build metadata identifiers\n        let prereleaseDelimiterIndex = versionString[..<(metadataDelimiterIndex ?? versionString.endIndex)].firstIndex(of: \"-\")\n\n        let versionCore = versionString[..<(prereleaseDelimiterIndex ?? metadataDelimiterIndex ?? versionString.endIndex)]\n        let versionCoreIdentifiers = versionCore.split(separator: \".\", omittingEmptySubsequences: false)\n\n        guard\n            versionCoreIdentifiers.count == 3,\n            // Major, minor, and patch versions must be ASCII numbers, according to the semantic versioning standard.\n            // Converting each identifier from a substring to an integer doubles as checking if the identifiers have non-numeric characters.\n                let major = Int(versionCoreIdentifiers[0]),\n            let minor = Int(versionCoreIdentifiers[1]),\n            let patch = Int(versionCoreIdentifiers[2])\n        else { return nil }\n\n        self.major = major\n        self.minor = minor\n        self.patch = patch\n\n        if let prereleaseDelimiterIndex {\n            let prereleaseStartIndex = versionString.index(after: prereleaseDelimiterIndex)\n            let prereleaseIdentifiers = versionString[prereleaseStartIndex..<(metadataDelimiterIndex ?? versionString.endIndex)].split(separator: \".\", omittingEmptySubsequences: false)\n            guard prereleaseIdentifiers.allSatisfy({ $0.allSatisfy({ $0.isLetter || $0.isNumber || $0 == \"-\" })}) else { return nil }\n            self.prereleaseIdentifiers = prereleaseIdentifiers.map { String($0) }\n        } else {\n            self.prereleaseIdentifiers = []\n        }\n\n        if let metadataDelimiterIndex {\n            let metadataStartIndex = versionString.index(after: metadataDelimiterIndex)\n            let buildMetadataIdentifiers = versionString[metadataStartIndex...].split(separator: \".\", omittingEmptySubsequences: false)\n            guard buildMetadataIdentifiers.allSatisfy({ $0.allSatisfy({ $0.isLetter || $0.isNumber || $0 == \"-\" })}) else { return nil }\n            self.buildMetadataIdentifiers = buildMetadataIdentifiers.map { String($0) }\n        } else {\n            self.buildMetadataIdentifiers = []\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/Version.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A version according to the semantic versioning specification.\n///\n/// A package version consists of three integers separated by periods, for example `1.0.0`. It must conform to the semantic versioning standard in order to ensure\n/// that your package behaves in a predictable manner once developers update their\n/// package dependency to a newer version. To achieve predictability, the semantic versioning specification proposes a set of rules and\n/// requirements that dictate how version numbers are assigned and incremented. To learn more about the semantic versioning specification, visit\n/// [Semantic Versioning 2.0.0](https://semver.org).\n///\n/// - term The major version: The first digit of a version, or _major version_,\n/// signifies breaking changes to the API that require updates to existing\n/// clients. For example, the semantic versioning specification considers\n/// renaming an existing type, removing a method, or changing a method's\n/// signature breaking changes. This also includes any backward-incompatible bug\n/// fixes or behavioral changes of the existing API.\n///\n/// - term The minor version:\n/// Update the second digit of a version, or _minor version_, if you add\n/// functionality in a backward-compatible manner. For example, the semantic\n/// versioning specification considers adding a new method or type without\n/// changing any other API to be backward-compatible.\n///\n/// - term The patch version:\n/// Increase the third digit of a version, or _patch version_, if you're making\n/// a backward-compatible bug fix. This allows clients to benefit from bugfixes\n/// to your package without incurring any maintenance burden.\npublic struct Version: Sendable {\n\n    /// The major version according to the semantic versioning standard.\n    public let major: Int\n\n    /// The minor version according to the semantic versioning standard.\n    public let minor: Int\n\n    /// The patch version according to the semantic versioning standard.\n    public let patch: Int\n\n    /// The pre-release identifier according to the semantic versioning standard, such as `-beta.1`.\n    public let prereleaseIdentifiers: [String]\n\n    /// The build metadata of this version according to the semantic versioning standard, such as a commit hash.\n    public let buildMetadataIdentifiers: [String]\n\n    /// Initializes a version struct with the provided components of a semantic version.\n    ///\n    /// - Parameters:\n    ///   - major: The major version number.\n    ///   - minor: The minor version number.\n    ///   - patch: The patch version number.\n    ///   - prereleaseIdentifiers: The pre-release identifier.\n    ///   - buildMetadataIdentifiers: Build metadata that identifies a build.\n    ///\n    /// - Precondition: `major >= 0 && minor >= 0 && patch >= 0`.\n    /// - Precondition: `prereleaseIdentifiers` can contain only ASCII alpha-numeric characters and \"-\".\n    /// - Precondition: `buildMetadataIdentifiers` can contain only ASCII alpha-numeric characters and \"-\".\n    public init(\n        _ major: Int,\n        _ minor: Int,\n        _ patch: Int,\n        prereleaseIdentifiers: [String] = [],\n        buildMetadataIdentifiers: [String] = []\n    ) {\n        precondition(major >= 0 && minor >= 0 && patch >= 0, \"Negative versioning is invalid.\")\n        precondition(\n            prereleaseIdentifiers.allSatisfy {\n                $0.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == \"-\") }\n            },\n            #\"Pre-release identifiers can contain only ASCII alpha-numeric characters and \"-\".\"#\n        )\n        precondition(\n            buildMetadataIdentifiers.allSatisfy {\n                $0.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == \"-\") }\n            },\n            #\"Build metadata identifiers can contain only ASCII alpha-numeric characters and \"-\".\"#\n        )\n        self.major = major\n        self.minor = minor\n        self.patch = patch\n        self.prereleaseIdentifiers = prereleaseIdentifiers\n        self.buildMetadataIdentifiers = buildMetadataIdentifiers\n    }\n}\n\nextension Version: Comparable {\n    // Although `Comparable` inherits from `Equatable`, it does not provide a new default implementation of `==`, but instead uses `Equatable`'s default synthesised implementation. The compiler-synthesised `==`` is composed of [member-wise comparisons](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0185-synthesize-equatable-hashable.md#implementation-details), which leads to a false `false` when 2 semantic versions differ by only their build metadata identifiers, contradicting SemVer 2.0.0's [comparison rules](https://semver.org/#spec-item-10).\n    \n    /// Returns a Boolean value indicating whether two values are equal.\n    ///\n    /// Equality is the inverse of inequality. For any values `a` and `b`, `a ==\n    /// b` implies that `a != b` is `false`.\n    ///\n    /// - Parameters:\n    ///   - lhs: A value to compare.\n    ///   - rhs: Another value to compare.\n    ///\n    /// - Returns: A boolean value indicating the result of the equality test.\n    @inlinable\n    public static func == (lhs: Version, rhs: Version) -> Bool {\n        !(lhs < rhs) && !(lhs > rhs)\n    }\n    \n    /// Returns a Boolean value indicating whether the value of the first\n    /// argument is less than that of the second argument.\n    ///\n    /// The precedence is determined according to rules described in the [Semantic Versioning 2.0.0](https://semver.org) standard, paragraph 11.\n    ///\n    /// - Parameters:\n    ///   - lhs: A value to compare.\n    ///   - rhs: Another value to compare.\n    public static func < (lhs: Version, rhs: Version) -> Bool {\n        let lhsComparators = [lhs.major, lhs.minor, lhs.patch]\n        let rhsComparators = [rhs.major, rhs.minor, rhs.patch]\n\n        if lhsComparators != rhsComparators {\n            return lhsComparators.lexicographicallyPrecedes(rhsComparators)\n        }\n\n        guard lhs.prereleaseIdentifiers.count > 0 else {\n            return false // Non-prerelease lhs >= potentially prerelease rhs\n        }\n\n        guard rhs.prereleaseIdentifiers.count > 0 else {\n            return true // Prerelease lhs < non-prerelease rhs\n        }\n\n        for (lhsPrereleaseIdentifier, rhsPrereleaseIdentifier) in zip(lhs.prereleaseIdentifiers, rhs.prereleaseIdentifiers) {\n            if lhsPrereleaseIdentifier == rhsPrereleaseIdentifier {\n                continue\n            }\n\n            // Check if either of the 2 pre-release identifiers is numeric.\n            let lhsNumericPrereleaseIdentifier = Int(lhsPrereleaseIdentifier)\n            let rhsNumericPrereleaseIdentifier = Int(rhsPrereleaseIdentifier)\n\n            if let lhsNumericPrereleaseIdentifier,\n               let rhsNumericPrereleaseIdentifier = rhsNumericPrereleaseIdentifier {\n                return lhsNumericPrereleaseIdentifier < rhsNumericPrereleaseIdentifier\n            } else if lhsNumericPrereleaseIdentifier != nil {\n                return true // numeric pre-release < non-numeric pre-release\n            } else if rhsNumericPrereleaseIdentifier != nil {\n                return false // non-numeric pre-release > numeric pre-release\n            } else {\n                return lhsPrereleaseIdentifier < rhsPrereleaseIdentifier\n            }\n        }\n\n        return lhs.prereleaseIdentifiers.count < rhs.prereleaseIdentifiers.count\n    }\n}\n\nextension Version: CustomStringConvertible {\n    /// A textual description of the version object.\n    public var description: String {\n        var base = \"\\(major).\\(minor).\\(patch)\"\n        if !prereleaseIdentifiers.isEmpty {\n            base += \"-\" + prereleaseIdentifiers.joined(separator: \".\")\n        }\n        if !buildMetadataIdentifiers.isEmpty {\n            base += \"+\" + buildMetadataIdentifiers.joined(separator: \".\")\n        }\n        return base\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackageDescription/WarningLevel.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// The level at which a compiler warning should be treated.\n///\n/// This enum is used with the `SwiftSetting.treatAllWarnings(as:_:)` and\n/// `SwiftSetting.treatWarning(name:as:_:)` methods to control how warnings\n/// are handled during compilation.\n@available(_PackageDescription, introduced: 6.2)\npublic enum WarningLevel: String {\n    /// Treat as a warning.\n    ///\n    /// Warnings will be displayed during compilation but will not cause the build to fail.\n    case warning\n\n    /// Treat as an error.\n    ///\n    /// Warnings will be elevated to errors, causing the build to fail if any such warnings occur.\n    case error\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/ArgumentExtractor.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A rudimentary helper for extracting options and flags from a list of strings that represent command line arguments.\n///\n/// Create the extractor with the full command line arguments provided, then extract all known\n/// options and flags, which leaves the positional arguments.\n///\n/// This does not handle the case where positional arguments (or optional argument values) have the same\n/// name as an option or a flag. It only handles the long form of options, not short forms, for example: `--<name>`, not `-n`.\n/// It respects an argument that consists of two hyphens (`--`) as an indication that all remaining arguments are positional.\npublic struct ArgumentExtractor {\n    private var args: [String]\n    private let literals: [String]\n\n    /// Creates an argument extractor with a list of strings from which to extract flags and options.\n    ///\n    /// If the list contains `--`, any arguments that follow it are considered positional arguments.\n    public init(_ arguments: [String]) {\n        // Split the array on the first `--`, if there is one. Everything after that is a literal.\n        let parts = arguments.split(separator: \"--\", maxSplits: 1, omittingEmptySubsequences: false)\n        self.args = Array(parts[0])\n        self.literals = Array(parts.count == 2 ? parts[1] : [])\n    }\n\n    /// Extracts options of the form `--<name> <value>` or `--<name>=<value>` from the remaining arguments and returns the extracted values.\n    public mutating func extractOption(named name: String) -> [String] {\n        var values: [String] = []\n        var idx = 0\n        while idx < args.count {\n            var arg = args[idx]\n            if arg == \"--\\(name)\" {\n                args.remove(at: idx)\n                if idx < args.count {\n                    let val = args[idx]\n                    values.append(val)\n                    args.remove(at: idx)\n                }\n            }\n            else if arg.starts(with: \"--\\(name)=\") {\n                arg.removeFirst(2 + name.count + 1)\n                values.append(arg)\n                args.remove(at: idx)\n            }\n            else {\n                idx += 1\n            }\n        }\n        return values\n    }\n\n    /// Extracts flags of the form `--<name>` from the remaining arguments, and returns the count.\n    public mutating func extractFlag(named name: String) -> Int {\n        var count = 0\n        var idx = 0\n        while idx < args.count {\n            let arg = args[idx]\n            if arg == \"--\\(name)\" {\n                args.remove(at: idx)\n                count += 1\n            }\n            else {\n                idx += 1\n            }\n        }\n        return count\n    }\n\n    /// Returns any unextracted flags or options.\n    ///\n    /// This is based strictly on whether remaining arguments have a `--` prefix.\n    public var unextractedOptionsOrFlags: [String] {\n        return args.filter{ $0.hasPrefix(\"--\") }\n    }\n\n    /// Returns all remaining arguments.\n    ///\n    /// The returned values include any positional arguments after the first `--`, if there is one.\n    public var remainingArguments: [String] {\n        return args + literals\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021-2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(PackagePlugin\n  ArgumentExtractor.swift\n  Command.swift\n  Context.swift\n  Diagnostics.swift\n  Errors.swift\n  PackageManagerProxy.swift\n  PackageModel.swift\n  Path.swift\n  Plugin.swift\n  PluginContextDeserializer.swift\n  PluginMessages.swift\n  Protocols.swift\n  Utilities.swift)\n\nif(APPLE)\n  target_link_options(PackagePlugin PRIVATE\n    \"SHELL:-Xlinker -install_name -Xlinker @rpath/libPackagePlugin.dylib\")\nelse()\n  target_link_libraries(PackagePlugin PRIVATE\n    Foundation)\nendif()\n\ninstall(TARGETS PackagePlugin\n  DESTINATION ${CMAKE_INSTALL_LIBDIR}/swift/pm/PluginAPI)\n\nset(SwiftPMRuntime_INSTALL_SWIFTMODULEDIR\n  ${CMAKE_INSTALL_LIBDIR}/swift/pm/PluginAPI)\nemit_swift_interface(PackagePlugin)\ninstall_swift_interface(PackagePlugin)\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Command.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A command to run during the build.\n///\n/// A command includes the executable, command lines, environment variables, initial working directory, and so on.\n/// All paths should be based on the ones that SwiftPM passes to the plugin in the target build context.\npublic enum Command {\n    /// Returns a command that runs when any of its output files are needed by\n    /// the build and are out-of-date.\n    ///\n    /// An output file is out-of-date if it doesn't exist, or if any input files\n    /// have changed since the command was last run.\n    ///\n    /// - Note: the paths in the list of output files may depend on the list of\n    ///   input file paths, but **must not** depend on reading the contents of\n    ///   any input files. Use a `prebuildCommand`if the functionality of your plugin\n    ///   requires you to read the contents of an input file.\n    ///\n    /// - parameters:\n    ///   - displayName: An optional string to show in build logs and other\n    ///     status areas.\n    ///   - executable: The absolute path to the executable to invoke.\n    ///   - arguments: The command-line arguments for the executable.\n    ///   - environment: Any environment variable assignments visible to the\n    ///     executable.\n    ///   - inputFiles: A list of files on which the contents of output files may depend.\n    ///     Any paths passed as `arguments` should typically be passed here as\n    ///     well.\n    ///   - outputFiles: A list of files to be generated or updated by the executable.\n    ///     Any files recognizable by their extension as source files\n    ///     (for example, `.swift`) are compiled into the target for which this command\n    ///     was generated as if in its source directory; other files are treated\n    ///     as resources as if explicitly listed in `Package.swift` using\n    ///     `.process(...)`.\n    @available(_PackageDescription, introduced: 6.0)\n    case buildCommand(\n        displayName: String?,\n        executable: URL,\n        arguments: [String],\n        environment: [String: String] = [:],\n        inputFiles: [URL] = [],\n        outputFiles: [URL] = []\n    )\n\n    /// Returns a command that runs unconditionally before every build.\n    ///\n    /// Prebuild commands can have a significant performance impact\n    /// and should only be used when there would be no way to know the\n    /// list of output file paths without first reading the contents\n    /// of one or more input files. Typically there is no way to\n    /// determine this list without first running the command, so\n    /// instead of encoding that list, the caller supplies an\n    /// `outputFilesDirectory` parameter, and all files in that\n    /// directory after the command runs are treated as the output files\n    /// of the plugin.\n    ///\n    /// - parameters:\n    ///   - displayName: An optional string to show in build logs and other\n    ///     status areas.\n    ///   - executable: The absolute path to the executable to invoke.\n    ///   - arguments: The command-line arguments for the executable.\n    ///   - environment: Any environment variable assignments visible to the executable.\n    ///   - outputFilesDirectory: A directory into which the command writes its\n    ///     output files.  The package manager compiles any files there recognizable by\n    ///     their extension as source files (for example, `.swift`) into the target for which\n    ///     this command was generated as if in its source directory; other\n    ///     files are treated as resources as if explicitly listed in\n    ///     `Package.swift` using `.process(...)`.\n    @available(_PackageDescription, introduced: 6.0)\n    case prebuildCommand(\n        displayName: String?,\n        executable: URL,\n        arguments: [String],\n        environment: [String: String] = [:],\n        outputFilesDirectory: URL\n    )\n}\n\nextension Command {\n    /// Returns a command that runs when any of its output files are needed by\n    /// the build and are out-of-date.\n    ///\n    /// An output file is out-of-date if it doesn't exist, or if any input files\n    /// have changed since the command was last run.\n    ///\n    /// - Note: the paths in the list of output files may depend on the list of\n    ///   input file paths, but **must not** depend on reading the contents of\n    ///   any input files. Such cases must be handled using a `prebuildCommand`.\n    ///\n    /// - parameters:\n    ///   - displayName: An optional string to show in build logs and other\n    ///     status areas.\n    ///   - executable: The absolute path to the executable to invoke.\n    ///   - arguments: Command-line arguments for the executable.\n    ///   - environment: Environment variable assignments visible to the\n    ///     executable.\n    ///   - inputFiles: Files on which the contents of output files may depend.\n    ///     Any paths passed as `arguments` should typically be passed here as\n    ///     well.\n    ///   - outputFiles: The files that the plugin generates or updates using the executable.\n    ///     The package manager compiles any files recognizable by their extension as source files\n    ///     (e.g. `.swift`) into the target for which this command\n    ///     was generated as if in its source directory; other files are treated\n    ///     as resources as if explicitly listed in `Package.swift` using\n    ///     `.process(...)`.\n    ///\n    /// @DeprecationSummary {\n    ///    Use ``buildCommand(displayName:executable:arguments:environment:inputFiles:outputFiles:)-swift.enum.case`` instead.\n    /// }\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public static func buildCommand(\n        displayName: String?,\n        executable: Path,\n        arguments: [CustomStringConvertible],\n        environment: [String: CustomStringConvertible] = [:],\n        inputFiles: [Path] = [],\n        outputFiles: [Path] = []\n    ) -> Command {\n        self.buildCommand(\n            displayName: displayName,\n            executable: URL(fileURLWithPath: executable.stringValue),\n            arguments: arguments.map(\\.description),\n            environment: environment.mapValues { $0.description },\n            inputFiles: inputFiles.map { URL(fileURLWithPath: $0.stringValue) },\n            outputFiles: outputFiles.map { URL(fileURLWithPath: $0.stringValue) }\n        )\n    }\n\n    /// Returns a command that runs when any of its output files are needed\n    /// by the build and are out-of-date.\n    ///\n    /// An output file is out-of-date if it doesn't exist, or if any input\n    /// files have changed since the command was last run.\n    ///\n    /// - Note: the paths in the list of output files may depend on the list\n    ///   of input file paths, but **must not** depend on reading the contents\n    ///   of any input files. Use a `prebuildCommand`if the functionality of your plugin\n    ///   requires you to read the contents of an input file.\n    ///\n    /// - parameters:\n    ///   - displayName: An optional string to show in build logs and other\n    ///     status areas.\n    ///   - executable: The absolute path to the executable to invoke.\n    ///   - arguments: The command-line arguments for the executable.\n    ///   - environment: Any environment variable assignments visible to the executable.\n    ///   - workingDirectory: Optional initial working directory when the executable\n    ///     runs.\n    ///   - inputFiles: A list of files on which the contents of output files may depend.\n    ///     Any paths passed as `arguments` should typically be passed here as well.\n    ///   - outputFiles: A list of files to be generated or updated by the executable.\n    ///     Any files recognizable by their extension as source files\n    ///     (for example, `.swift`) are compiled into the target for which this command\n    ///     was generated as if in its source directory; other files are treated\n    ///     as resources as if explicitly listed in `Package.swift` using\n    ///     `.process(...)`.\n    @available(*, unavailable, message: \"specifying the initial working directory for a command is not supported\")\n    public static func buildCommand(\n        displayName: String?,\n        executable: Path,\n        arguments: [CustomStringConvertible],\n        environment: [String: CustomStringConvertible] = [:],\n        workingDirectory: Path? = .none,\n        inputFiles: [Path] = [],\n        outputFiles: [Path] = []\n    ) -> Command {\n        self.buildCommand(\n            displayName: displayName,\n            executable: URL(fileURLWithPath: executable.stringValue),\n            arguments: arguments.map(\\.description),\n            environment: environment.mapValues { $0.description },\n            inputFiles: inputFiles.map { URL(fileURLWithPath: $0.stringValue) },\n            outputFiles: outputFiles.map { URL(fileURLWithPath: $0.stringValue) }\n        )\n    }\n\n    /// Returns a command that runs unconditionally before every build.\n    ///\n    /// Prebuild commands can have a significant performance impact\n    /// and should only be used when there would be no way to know the\n    /// list of output file paths without first reading the contents\n    /// of one or more input files. Typically there is no way to\n    /// determine this list without first running the command, so\n    /// instead of encoding that list, the caller supplies an\n    /// `outputFilesDirectory` parameter, and all files in that\n    /// directory after the command runs are treated as output files.\n    ///\n    /// - parameters:\n    ///   - displayName: An optional string to show in build logs and other\n    ///     status areas.\n    ///   - executable: The absolute path to the executable to invoke.\n    ///   - arguments: The command-line arguments for the executable.\n    ///   - environment: Any environment variable assignments visible to the executable.\n    ///   - outputFilesDirectory: A directory into which the command writes its\n    ///     output files.  Any files there recognizable by their extension as\n    ///     source files (for example, `.swift`) are compiled into the target for which\n    ///     this command was generated as if in its source directory; other\n    ///     files are treated as resources as if explicitly listed in\n    ///     `Package.swift` using `.process(...)`.\n    /// @DeprecationSummary {\n    ///   Use ``prebuildCommand(displayName:executable:arguments:environment:outputFilesDirectory:)-swift.enum.case`` instead.\n    /// }\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public static func prebuildCommand(\n        displayName: String?,\n        executable: Path,\n        arguments: [CustomStringConvertible],\n        environment: [String: CustomStringConvertible] = [:],\n        outputFilesDirectory: Path\n    ) -> Command {\n        self.prebuildCommand(\n            displayName: displayName,\n            executable: URL(fileURLWithPath: executable.stringValue),\n            arguments: arguments.map(\\.description),\n            environment: environment.mapValues { $0.description },\n            outputFilesDirectory: URL(fileURLWithPath: outputFilesDirectory.stringValue)\n        )\n    }\n\n    /// Returns a command that runs unconditionally before every build.\n    ///\n    /// Because prebuild commands are run on every build, they can have a\n    /// significant performance impact and should only be used when there\n    /// would be no way to know the list of output file paths without first\n    /// reading the contents of one or more input files. Typically there is\n    /// no way to determine this list without first running the command, so\n    /// instead of encoding that list, the caller supplies an\n    /// `outputFilesDirectory` parameter, and all files in that directory\n    /// after the command runs are treated as output files.\n    ///\n    /// - parameters:\n    ///   - displayName: An optional string to show in build logs and other\n    ///     status areas.\n    ///   - executable: The absolute path to the executable to invoke.\n    ///   - arguments: The command-line arguments for the executable.\n    ///   - environment: Any environment variable assignments visible to the executable.\n    ///   - workingDirectory: Optional initial working directory when the executable\n    ///     runs.\n    ///   - outputFilesDirectory: A directory into which the command writes its\n    ///     output files.  Any files there recognizable by their extension as\n    ///     source files (for example, `.swift`) are compiled into the target for which\n    ///     this command was generated as if in its source directory; other\n    ///     files are treated as resources as if explicitly listed in\n    ///     `Package.swift` using `.process(...)`.\n    @available(*, unavailable, message: \"specifying the initial working directory for a command is not supported\")\n    public static func prebuildCommand(\n        displayName: String?,\n        executable: Path,\n        arguments: [CustomStringConvertible],\n        environment: [String: CustomStringConvertible] = [:],\n        workingDirectory: Path? = .none,\n        outputFilesDirectory: Path\n    ) -> Command {\n        self.prebuildCommand(\n            displayName: displayName,\n            executable: URL(fileURLWithPath: executable.stringValue),\n            arguments: arguments.map(\\.description),\n            environment: environment.mapValues { $0.description },\n            outputFilesDirectory: URL(fileURLWithPath: outputFilesDirectory.stringValue)\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Context.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A collection of information about the package on which the package manager invokes the  plugin,\n/// as well as contextual information based on the plugin's intent and requirements.\npublic struct PluginContext {\n    /// Information about the package the plugin works on.\n    public let package: Package\n\n    /// The path of a writable directory into which the plugin or the build\n    /// commands can write files.\n    ///\n    /// This could include\n    /// generated source files to processed further, as well as\n    /// any caches used by the build tool or the plugin.\n    /// The plugin is in complete control of what is written under this directory,\n    /// and the package manager preserves the contents between builds.\n    ///\n    /// A plugin may create a separate subdirectory\n    /// for each command it creates, with the command configured to\n    /// write its output to that directory. The plugin may also create other\n    /// directories for cache files and other file system content that either\n    /// it or the command will need.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"pluginWorkDirectoryURL\")\n    public let pluginWorkDirectory: Path\n\n    /// The URL of a writable directory into which the plugin or the build\n    /// commands it constructs can write anything it wants.\n    ///\n    /// This could include\n    /// generated source files to processed further, as well as\n    /// any caches used by the build tool or the plugin.\n    /// The plugin is in complete control of what is written under this directory,\n    /// and the package manager preserves the contents between builds.\n    ///\n    /// A plugin may create a separate subdirectory\n    /// for each command it creates, with the command configured to\n    /// write its output to that directory. The plugin may also create other\n    /// directories for cache files and other file system content that either\n    /// it or the command will need.\n    @available(_PackageDescription, introduced: 6.0)\n    public let pluginWorkDirectoryURL: URL\n\n    /// Looks up and returns the path of a named command line executable.\n    /// \n    /// The executable must be provided by an executable target or binary\n    /// target on which the package plugin target depends. This function throws\n    /// an error if the tool cannot be found. The lookup is case sensitive.\n    /// - Parameter name: The name of the executable to find.\n    public func tool(named name: String) throws -> Tool {\n        if let tool = self.accessibleTools[name] {\n            // For PluginAccessibleTool.builtTool, the triples value is not saved, thus\n            // the value is always nil; this is intentional since if we are able to\n            // build the tool, it is by definition supporting the target platform.\n            // For PluginAccessibleTool.vendedTool, only supported triples are saved,\n            // so empty triples means the tool is not supported on the target platform.\n            if let triples = tool.triples, triples.isEmpty {\n                throw PluginContextError.toolNotSupportedOnTargetPlatform(name: name)\n            }\n            return try Tool(name: name, path: Path(url: tool.path), url: tool.path)\n        } else {\n            for dir in self.toolSearchDirectoryURLs {\n                #if os(Windows)\n                let hostExecutableSuffix = \".exe\"\n                #else\n                let hostExecutableSuffix = \"\"\n                #endif\n                let pathURL = dir.appendingPathComponent(name + hostExecutableSuffix)\n                let path = try Path(url: pathURL)\n                if FileManager.default.isExecutableFile(atPath: path.stringValue) {\n                    return Tool(name: name, path: path, url: pathURL)\n                }\n            }\n        }\n        throw PluginContextError.toolNotFound(name: name)\n    }\n\n    /// A map from tool names to their paths and triples.\n    ///\n    /// This is not directly available to the plugin, but is used by  ``tool(named:)``.\n    let accessibleTools: [String: (path: URL, triples: [String]?)]\n\n    /// The paths of directories in which to search for tools that aren't in\n    /// the `toolNamesToPaths` map.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"toolSearchDirectoryURLs\")\n    let toolSearchDirectories: [Path]\n\n    /// The paths of directories in which to search for tools that aren't in\n    /// the `toolNamesToPaths` map.\n    @available(_PackageDescription, introduced: 6.0)\n    let toolSearchDirectoryURLs: [URL]\n\n    /// Information about a particular tool that is available to a plugin.\n    public struct Tool {\n        /// The name of the tool, suitable for display purposes.\n        public let name: String\n\n        /// The path of the tool in the file system.\n        @available(_PackageDescription, deprecated: 6.0, renamed: \"url\")\n        public var path: Path {\n            get { _path }\n        }\n\n        /// The file URL of the tool in the file system.\n        @available(_PackageDescription, introduced: 6.0)\n        public let url: URL\n\n        private let _path: Path\n\n        @_spi(PackagePluginInternal) public init(name: String, path: Path, url: URL) {\n            self.name = name\n            self.url = url\n            self._path = path\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Diagnostics.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Emits errors, warnings, and remarks to show as a result of running the\n/// plugin.\n///\n/// After emitting one or more errors, a plugin should return a\n/// non-zero exit code.\npublic struct Diagnostics {\n\n    /// The severity of the diagnostic.\n    public enum Severity: String, Encodable {\n        case error, warning, remark\n    }\n    \n    /// Emits an error with a specified severity and message, and optional file path and line number.\n    /// - Parameters:\n    ///   - severity: The severity of the diagnostic.\n    ///   - description: The description of the diagnostic.\n    ///   - file: The file responsible for the diagnostic, that defaults to `#file`.\n    ///   - line: The line responsible for the diagnostic, that defaults to `#line`.\n    public static func emit(_ severity: Severity, _ description: String, file: String? = #file, line: Int? = #line) {\n        let message: PluginToHostMessage\n        switch severity {\n        case .error:\n            message = .emitDiagnostic(severity: .error, message: description, file: file, line: line)\n        case .warning:\n            message = .emitDiagnostic(severity: .warning, message: description, file: file, line: line)\n        case .remark:\n            message = .emitDiagnostic(severity: .remark, message: description, file: file, line: line)\n        }\n        // FIXME: Handle problems sending the message.\n        try? pluginHostConnection.sendMessage(message)\n    }\n\n    /// Emits an error with the message you specify.\n    /// - Parameters:\n    ///   - message: The description of the error.\n    ///   - file: The file responsible for the diagnostic, that defaults to `#file`.\n    ///   - line: The line responsible for the diagnostic, that defaults to `#line`.\n    public static func error(_ message: String, file: String? = #file, line: Int? = #line) {\n        self.emit(.error, message, file: file, line: line)\n    }\n\n    /// Emits a warning with the message you specify.\n    /// - Parameters:\n    ///   - message: The description of the warning.\n    ///   - file: The file responsible for the diagnostic, that defaults to `#file`.\n    ///   - line: The line responsible for the diagnostic, that defaults to `#line`.\n    public static func warning(_ message: String, file: String? = #file, line: Int? = #line) {\n        self.emit(.warning, message, file: file, line: line)\n    }\n\n    /// Emits a remark with the message you specify.\n    /// - Parameters:\n    ///   - message: The description of the remark.\n    ///   - file: The file responsible for the diagnostic, that defaults to `#file`.\n    ///   - line: The line responsible for the diagnostic, that defaults to `#line`.\n    public static func remark(_ message: String, file: String? = #file, line: Int? = #line) {\n        self.emit(.remark, message, file: file, line: line)\n    }\n\n    /// Emits a progress message.\n    /// - Parameter message: The description of the progress.\n    public static func progress(_ message: String) {\n        try? pluginHostConnection.sendMessage(.emitProgress(message: message))\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/ArgumentExtractor.md",
    "content": "# ``PackagePlugin/ArgumentExtractor``\n\n## Topics\n\n### Creating an Argument Extractor\n\n- ``init(_:)``\n\n### Inspecting Arguments\n\n- ``remainingArguments``\n- ``unextractedOptionsOrFlags``\n\n### Extracting Arguments\n\n- ``extractFlag(named:)``\n- ``extractOption(named:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/BinaryArtifactTarget.md",
    "content": "# ``PackagePlugin/BinaryArtifactTarget``\n\n## Topics\n\n### Inspecting the Target\n\n- ``id``\n- ``name``\n- ``kind-swift.property``\n- ``origin-swift.property``\n- ``artifactURL``\n- ``dependencies``\n- ``directoryURL``\n- ``Kind-swift.enum``\n- ``Origin-swift.enum``\n\n- ``artifact``\n- ``directory``\n\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/BuildToolPlugin.md",
    "content": "# ``PackagePlugin/BuildToolPlugin``\n\n## Topics\n\n### Creating a Build Tool Plugin\n\n- ``createBuildCommands(context:target:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/ClangSourceModuleTarget.md",
    "content": "# ``PackagePlugin/ClangSourceModuleTarget``\n\n## Topics\n\n### Inspecting a Clang Source Module Target\n\n- ``id``\n- ``name``\n- ``kind``\n- ``moduleName``\n- ``directoryURL``\n- ``dependencies``\n- ``headerSearchPaths``\n- ``preprocessorDefinitions``\n- ``directory``\n- ``publicHeadersDirectory``\n- ``publicHeadersDirectoryURL``\n\n### Source Files\n\n- ``sourceFiles``\n- ``sourceFiles(withSuffix:)``\n\n### Plugin Sources and Resources\n\n- ``pluginGeneratedSources``\n- ``pluginGeneratedResources``\n\n### Linked Library and Frameworks\n\n- ``linkedLibraries``\n- ``linkedFrameworks``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/Command.md",
    "content": "# ``PackagePlugin/Command``\n\n## Topics\n\n### Types of Build Commands\n\n- ``buildCommand(displayName:executable:arguments:environment:inputFiles:outputFiles:)-swift.enum.case``\n- ``prebuildCommand(displayName:executable:arguments:environment:outputFilesDirectory:)-swift.enum.case``\n- ``buildCommand(displayName:executable:arguments:environment:inputFiles:outputFiles:)-swift.type.method``\n- ``prebuildCommand(displayName:executable:arguments:environment:outputFilesDirectory:)-swift.type.method``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/CommandPlugin.md",
    "content": "# ``PackagePlugin/CommandPlugin``\n\n## Topics\n\n### Creating a Command Plugin\n\n- ``performCommand(context:arguments:)``\n\n### Accessing the Package Manager\n\n- ``packageManager-4z02h``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/Diagnostics.md",
    "content": "# ``PackagePlugin/Diagnostics``\n\n## Topics\n\n### Emitting Errors and Diagnostics\n\n- ``progress(_:)``\n- ``error(_:file:line:)``\n- ``warning(_:file:line:)``\n- ``remark(_:file:line:)``\n- ``emit(_:_:file:line:)``\n- ``Severity``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/ExecutableProduct.md",
    "content": "# ``PackagePlugin/ExecutableProduct``\n\n## Topics\n\n### Inspecting an Executable Target\n\n- ``id``\n- ``name``\n- ``mainTarget``\n- ``targets``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/File.md",
    "content": "# ``PackagePlugin/File``\n\n## Topics\n\n### Inspecting the File\n\n- ``type``\n- ``url``\n- ``path``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/FileList.md",
    "content": "# ``PackagePlugin/FileList``\n\n## Topics\n\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/FileType.md",
    "content": "# ``PackagePlugin/FileType``\n\n## Topics\n\n### Types of Files\n\n- ``source``\n- ``header``\n- ``resource``\n- ``unknown``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/LibraryProduct.md",
    "content": "# ``PackagePlugin/LibraryProduct``\n\n## Topics\n\n### Inspecting a Library Product\n\n- ``id``\n- ``name``\n- ``kind-swift.property``\n- ``targets``\n- ``Kind-swift.enum``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/LibraryProduct_Kind.md",
    "content": "# ``PackagePlugin/LibraryProduct/Kind-swift.enum``\n\n## Topics\n\n### Kinds of Library Targets\n\n- ``automatic``\n- ``dynamic``\n- ``static``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/ModuleKind.md",
    "content": "# ``PackagePlugin/ModuleKind``\n\n## Topics\n\n### Kinds of Modules\n\n- ``executable``\n- ``test``\n- ``generic``\n- ``macro``\n- ``snippet``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/Package.md",
    "content": "# ``PackagePlugin/Package``\n\n## Topics\n\n### Inspecting Packages\n\n- ``id``\n- ``displayName``\n- ``toolsVersion``\n- ``directoryURL``\n- ``origin``\n- ``dependencies``\n- ``sourceModules``\n- ``ID``\n- ``directory``\n\n### Inspecting Package Targets\n\n- ``targets``\n- ``targets(named:)``\n- ``targets(ofType:)``\n\n### Inspecting Package Products\n\n- ``products``\n- ``products(named:)``\n- ``products(ofType:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageDependency.md",
    "content": "# ``PackagePlugin/PackageDependency``\n\n## Topics\n\n### Inspecting a Package Dependency\n\n- ``package``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager.md",
    "content": "# ``PackagePlugin/PackageManager``\n\n## Topics\n\n### Building a Package\n\n- ``build(_:parameters:)``\n- ``BuildSubset``\n- ``BuildParameters``\n- ``BuildResult``\n- ``BuildConfiguration``\n- ``BuildLogVerbosity``\n\n### Testing a Package\n\n- ``test(_:parameters:)``\n- ``TestSubset``\n- ``TestParameters``\n- ``TestResult``\n\n### Retrieving Symbols for a Package\n\n- ``getSymbolGraph(for:options:)``\n- ``SymbolGraphOptions``\n- ``SymbolGraphResult``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManagerProxyError.md",
    "content": "# ``PackagePlugin/PackageManagerProxyError``\n\n## Topics\n\n### Types of Proxy Errors from Package Manager\n\n- ``unimplemented(_:)``\n- ``unspecified(_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_BuildConfiguration.md",
    "content": "# ``PackagePlugin/PackageManager/BuildConfiguration``\n\n## Topics\n\n### Build Configurations\n\n- ``inherit``\n- ``debug``\n- ``release``\n\n### Creating a Build Configuration\n\n- ``init(rawValue:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_BuildLogVerbosity.md",
    "content": "# ``PackagePlugin/PackageManager/BuildLogVerbosity``\n\n## Topics\n\n### Verbosity Levels\n\n- ``concise``\n- ``debug``\n- ``verbose``\n\n### Creating a Verbosity Level\n\n- ``init(rawValue:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_BuildParameters.md",
    "content": "# ``PackagePlugin/PackageManager/BuildParameters``\n\n## Topics\n\n### Creating Build Parameters\n\n- ``init(configuration:logging:echoLogs:)``\n- ``BuildConfiguration``\n- ``BuildLogVerbosity``\n\n### Inspecting Build Parameters\n\n- ``configuration``\n- ``logging``\n- ``echoLogs``\n- ``otherCFlags``\n- ``otherCxxFlags``\n- ``otherLinkerFlags``\n- ``otherSwiftcFlags``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_BuildResult.md",
    "content": "# ``PackagePlugin/PackageManager/BuildResult``\n\n## Topics\n\n### Inspecting a Build Result\n\n- ``builtArtifacts``\n- ``logText``\n- ``succeeded``\n- ``BuiltArtifact``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_BuildResult_BuiltArtifact.md",
    "content": "# ``PackagePlugin/PackageManager/BuildResult/BuiltArtifact``\n\n## Topics\n\n### Inspecting a Build Artifact\n\n- ``kind-swift.property``\n- ``url``\n- ``Kind-swift.enum``\n- ``path``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_BuildSubset.md",
    "content": "# ``PackagePlugin/PackageManager/BuildSubset``\n\n## Topics\n\n### Subsets of the Package\n\n- ``product(_:)``\n- ``target(_:)``\n- ``all(includingTests:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_SymbolGraphOptions.md",
    "content": "# ``PackagePlugin/PackageManager/SymbolGraphOptions``\n\n## Topics\n\n### Creating Symbol Graph Options\n\n- ``init(minimumAccessLevel:includeSynthesized:includeSPI:emitExtensionBlocks:)``\n\n### Inspecting Symbol Graph Options\n\n- ``emitExtensionBlocks``\n- ``includeSPI``\n- ``includeSynthesized``\n- ``minimumAccessLevel``\n- ``AccessLevel``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_SymbolGraphOptions_AccessLevel.md",
    "content": "# ``PackagePlugin/PackageManager/SymbolGraphOptions/AccessLevel``\n\n## Topics\n\n### Access Levels\n\n- ``public``\n- ``package``\n- ``open``\n- ``internal``\n- ``private``\n- ``fileprivate``\n\n### Creating an Access Level\n\n- ``init(rawValue:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_SymbolGraphResult.md",
    "content": "# ``PackagePlugin/PackageManager/SymbolGraphResult``\n\n## Topics\n\n### Inspecting Symbol Graph Results\n\n- ``directoryURL``\n- ``directoryPath``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_TestParameters.md",
    "content": "# ``PackagePlugin/PackageManager/TestParameters``\n\n## Topics\n\n### Creating Test Parameters\n\n- ``init(enableCodeCoverage:)``\n\n### Inspecting Test Parameters\n\n- ``enableCodeCoverage``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_TestResult.md",
    "content": "# ``PackagePlugin/PackageManager/TestResult``\n\n## Topics\n\n### Inspecting Test Results\n\n- ``succeeded``\n- ``testTargets``\n- ``codeCoverageDataFileURL``\n- ``TestTarget``\n- ``codeCoverageDataFile``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_TestResult_TestTarget.md",
    "content": "# ``PackagePlugin/PackageManager/TestResult/TestTarget``\n\n## Topics\n\n### Inspecting a Test Target\n\n- ``name``\n- ``testCases``\n- ``TestCase``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_TestResult_TestTarget_TestCase.md",
    "content": "# ``PackagePlugin/PackageManager/TestResult/TestTarget/TestCase``\n\n## Topics\n\n### Inspecting a Test Case\n\n- ``name``\n- ``tests``\n- ``Test``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_TestResult_TestTarget_TestCase_Test.md",
    "content": "# ``PackagePlugin/PackageManager/TestResult/TestTarget/TestCase/Test``\n\n## Topics\n\n### Inspecting a Test in a Test Case\n\n- ``name``\n- ``result-swift.property``\n- ``duration``\n- ``Result-swift.enum``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_TestResult_TestTarget_TestCase_Test_Result.md",
    "content": "# ``PackagePlugin/PackageManager/TestResult/TestTarget/TestCase/Test/Result-swift.enum``\n\n## Topics\n\n### Test Results\n\n- ``succeeded``\n- ``skipped``\n- ``failed``\n\n### Creating a Test Result\n\n- ``init(rawValue:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageManager_TestSubset.md",
    "content": "# ``PackagePlugin/PackageManager/TestSubset``\n\n## Topics\n\n### Subsets of Tests\n\n- ``all``\n- ``filtered(_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PackageOrigin.md",
    "content": "# ``PackagePlugin/PackageOrigin``\n\n## Topics\n\n### Package Origins\n\n- ``repository(url:displayVersion:scmRevision:)``\n- ``registry(identity:displayVersion:)``\n- ``local(path:)``\n- ``root``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/Path.md",
    "content": "# ``PackagePlugin/Path``\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.6\", deprecated: \"6.0\")\n}\n\n## Topics\n\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PathList.md",
    "content": "# ``PackagePlugin/PathList``\n\n@Metadata {\n    @Available(\"Swift\", introduced: \"5.6\", deprecated: \"6.0\")\n}\n\n## Topics\n\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/Plugin.md",
    "content": "# ``PackagePlugin/Plugin``\n\n## Topics\n\n### Creating a plugin\n\n- ``init()``\n\n### Invoking a plugin\n\n- ``main()``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PluginContext.md",
    "content": "# ``PackagePlugin/PluginContext``\n\n## Topics\n\n### Inspecting the Context\n\n- ``pluginWorkDirectoryURL``\n- ``tool(named:)``\n- ``package``\n- ``Tool``\n- ``pluginWorkDirectory``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PluginContextError.md",
    "content": "# ``PackagePlugin/PluginContextError``\n\n## Topics\n\n### Errors from the Plugin Context\n\n- ``productNotFound(name:package:)``\n- ``targetNotFound(name:package:)``\n- ``toolNotFound(name:)``\n- ``toolNotSupportedOnTargetPlatform(name:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/PluginDeserializationError.md",
    "content": "# ``PackagePlugin/PluginDeserializationError``\n\n## Topics\n\n### Errors while deserializing\n\n- ``missingBuildToolPluginProtocolConformance(protocolName:)``\n- ``missingCommandPluginProtocolConformance(protocolName:)``\n- ``missingXcodeProjectPluginSupport``\n- ``malformedInputJSON(_:)``\n- ``internalError(_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/Product.md",
    "content": "# ``PackagePlugin/Product``\n\n## Topics\n\n### Inspecting a Package Product\n\n- ``id-swift.property``\n- ``name``\n- ``sourceModules``\n- ``targets``\n- ``ID-swift.typealias``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/SourceModuleTarget.md",
    "content": "# ``PackagePlugin/SourceModuleTarget``\n\n## Topics\n\n### Inspecting a Source Module Target\n\n- ``moduleName``\n- ``kind``\n- ``linkedLibraries``\n- ``linkedFrameworks``\n- ``pluginGeneratedSources``\n- ``pluginGeneratedResources``\n- ``sourceFiles``\n- ``sourceFiles(withSuffix:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/SwiftSourceModuleTarget.md",
    "content": "# ``PackagePlugin/SwiftSourceModuleTarget``\n\n## Topics\n\n### Inspecting a Swift Source Module Target\n\n- ``id``\n- ``name``\n- ``kind``\n- ``moduleName``\n- ``directoryURL``\n- ``dependencies``\n- ``compilationConditions``\n- ``directory``\n\n### Source Files\n\n- ``sourceFiles``\n- ``sourceFiles(withSuffix:)``\n\n### Plugin Sources and Resources\n\n- ``pluginGeneratedSources``\n- ``pluginGeneratedResources``\n\n### Linked Library and Frameworks\n\n- ``linkedLibraries``\n- ``linkedFrameworks``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/SystemLibraryTarget.md",
    "content": "# ``PackagePlugin/SystemLibraryTarget``\n\n## Topics\n\n### Inspecting the System Library Target\n\n- ``id``\n- ``name``\n- ``pkgConfig``\n- ``dependencies``\n- ``compilerFlags``\n- ``linkerFlags``\n- ``directoryURL``\n- ``directory``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/Target.md",
    "content": "# ``PackagePlugin/Target``\n\n## Topics\n\n### Inspecting a target\n\n- ``id-swift.property``\n- ``name``\n- ``directoryURL``\n- ``sourceModule``\n- ``dependencies``\n- ``recursiveTargetDependencies``\n- ``ID-swift.typealias``\n- ``directory``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/TargetDependency.md",
    "content": "# ``PackagePlugin/TargetDependency``\n\n## Topics\n\n### Target Dependencies\n\n- ``product(_:)``\n- ``target(_:)``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Curation/ToolsVersion.md",
    "content": "# ``PackagePlugin/ToolsVersion``\n\n## Topics\n\n### Tools Version Components\n\n- ``major``\n- ``minor``\n- ``patch``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Documentation.md",
    "content": "# ``PackagePlugin``\n\nCreate plugins that extend the Swift Package Manager.\n\n<!-- swift package --disable-sandbox preview-documentation --target PackagePlugin -->\n## Overview\n\nBuild tool plugins generate source files as part of a build, or perform other actions at the start of every build.\nThe package manager invokes build tool plugins before a package is built in order to construct command invocations to run as part of the build.\nCommand plugins provide actions that users can perform at any time and aren't associated with a build.\n\nRead [Writing a build tool plugin](https://docs.swift.org/swiftpm/documentation/packagemanagerdocs/WritingBuildToolPlugin) to learn how to create build tool plugins, or [Writing a command plugin](https://docs.swift.org/swiftpm/documentation/packagemanagerdocs/WritingCommandPlugin) to learn how to create command plugins.\n\n## Topics\n\n### Implementing Command Plugins\n\n- ``CommandPlugin``\n- ``PluginContext``\n- ``Plugin``\n\n### Extracting Arguments\n\n- ``ArgumentExtractor``\n\n### Implementing Build Plugins\n\n- ``BuildToolPlugin``\n- ``PluginContext``\n- ``Target``\n- ``Command``\n\n### Interacting with Package Manager\n\n- ``PackageManager``\n- ``PackageManagerProxyError``\n\n### Inspecting the Package Representation\n\n- ``Package``\n- ``ToolsVersion``\n- ``PackageOrigin``\n- ``PackageDependency``\n- ``Product``\n- ``ExecutableProduct``\n- ``LibraryProduct``\n\n### Inspecting Package Targets\n\n- ``Target``\n- ``TargetDependency``\n- ``SourceModuleTarget``\n- ``ModuleKind``\n- ``SwiftSourceModuleTarget``\n- ``ClangSourceModuleTarget``\n- ``BinaryArtifactTarget``\n- ``SystemLibraryTarget``\n\n### Inspecting Package Files\n\n- ``FileList``\n- ``File``\n- ``FileType``\n\n- ``Path``\n- ``PathList``\n\n### Plugin Diagnostics and Errors\n\n- ``Diagnostics``\n- ``PluginContextError``\n- ``PluginDeserializationError``\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Documentation.docc/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleName</key>\n\t<string>PackagePlugin</string>\n\t<key>CFBundleDisplayName</key>\n\t<string>PackagePlugin</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>org.swift.swiftpm.packageplugin</string>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleIconFile</key>\n\t<string>DocumentationIcon</string>\n\t<key>CFBundleIconName</key>\n\t<string>DocumentationIcon</string>\n\t<key>CFBundlePackageType</key>\n\t<string>DOCS</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>0.1.0</string>\n\t<key>CDDefaultCodeListingLanguage</key>\n\t<string>swift</string>\n\t<key>CFBundleVersion</key>\n\t<string>0.1.0</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Errors.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Errors thrown while a plugin operates.\npublic enum PluginContextError: Error {\n    /// Could not find a tool with the given name.\n    ///\n    /// This could be either because\n    /// it doesn't exist, or because the plugin doesn't have a dependency on it.\n    case toolNotFound(name: String)\n\n    /// The tool is not supported on the target platform\n    case toolNotSupportedOnTargetPlatform(name: String)\n\n    /// Could not find a target with the given name.\n    case targetNotFound(name: String, package: Package)\n\n    /// Could not find a product with the given name.\n    case productNotFound(name: String, package: Package)\n}\n\nextension PluginContextError: CustomStringConvertible {\n    /// The string representation of the error.\n    public var description: String {\n        switch self {\n        case .toolNotFound(let name):\n            return \"Plugin does not have access to a tool named ‘\\(name)’\"\n        case .toolNotSupportedOnTargetPlatform(let name):\n            return \"Tool ‘\\(name)’ is not supported on the target platform\"\n        case .targetNotFound(let name, let package):\n            return \"Package ‘\\(package.displayName)’ has no target named ‘\\(name)’\"\n        case .productNotFound(let name, let package):\n            return \"Package ‘\\(package.displayName)’ has no product named ‘\\(name)’\"\n        }\n    }\n}\n\n/// Errors thrown while loading a plugin.\npublic enum PluginDeserializationError: Error {\n    /// The input JSON is malformed in some way; the message provides more details.\n    case malformedInputJSON(_ message: String)\n    /// The plugin doesn't support Xcode\n    ///\n    /// Typically, it doesn't link against XcodeProjectPlugin.\n    case missingXcodeProjectPluginSupport\n    /// The plugin doesn't conform to the BuildToolPlugin protocol.\n    case missingBuildToolPluginProtocolConformance(protocolName: String)\n    /// The plugin doesn't conform to the CommandPlugin protocol.\n    case missingCommandPluginProtocolConformance(protocolName: String)\n    /// An internal error of some kind; the message provides more details.\n    case internalError(_ message: String)\n}\n\nextension PluginDeserializationError: CustomStringConvertible {\n    /// The string representation of the error.\n    public var description: String {\n        switch self {\n        case .malformedInputJSON(let message):\n            return \"Malformed input JSON: \\(message)\"\n        case .missingXcodeProjectPluginSupport:\n            return \"Plugin doesn't support Xcode projects (it doesn't use the XcodeProjectPlugin library)\"\n        case .missingBuildToolPluginProtocolConformance(let protocolName):\n            return \"Plugin is declared with the `buildTool` capability, but doesn't conform to the `\\(protocolName)` protocol\"\n        case .missingCommandPluginProtocolConformance(let protocolName):\n            return \"Plugin is declared with the `command` capability, but doesn't conform to the `\\(protocolName)` protocol\"\n        case .internalError(let message):\n            return \"Internal error: \\(message)\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/PackageManagerProxy.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// Provides specialized information and services from the Swift Package Manager\n/// or an IDE that supports Swift packages.\n///\n/// Different plugin hosts implement the functionality in whatever way is appropriate for them,\n/// but are expected to preserve the semantics described by this API.\npublic struct PackageManager {\n    /// Performs a build of all, or a subset, of products and targets in a package.\n    ///\n    /// Return any errors encountered during the build in the build result,\n    /// as well as the log of the build commands that it runs. This method throws an\n    /// error if the input parameters are invalid, or in case the build can't be\n    /// started.\n    ///\n    /// The Swift package manager command line interface or any IDE that supports\n    /// packages may show the progress of the build as it happens.\n    /// - Parameters:\n    ///   - subset: The subset of targets to build.\n    ///   - parameters: The build parameters to apply.\n    /// - Returns: The build results.\n    public func build(\n        _ subset: BuildSubset,\n        parameters: BuildParameters\n    ) throws -> BuildResult {\n        // Ask the plugin host to build the specified products and targets, and wait for a response.\n        // FIXME: We'll want to make this asynchronous when there is back deployment support for it.\n        try sendMessageAndWaitForReply(.buildOperationRequest(subset: .init(subset), parameters: .init(parameters))) {\n            guard case .buildOperationResponse(let result) = $0 else { return nil }\n            return .init(result)\n        }\n    }\n\n    /// Specifies a subset of package products and targets to build.\n    public enum BuildSubset {\n        /// Represents the subset consisting of all products and of either all\n        /// targets or, if `includingTests` is false, non-test targets.\n        case all(includingTests: Bool)\n\n        /// Represents the product with the specified name.\n        case product(String)\n\n        /// Represents the target with the specified name.\n        case target(String)\n    }\n\n    /// Parameters and options to apply during a build.\n    public struct BuildParameters {\n        /// The build configuration to use while building.\n        ///\n        /// Typically whether to build for debug or release.\n        public var configuration: BuildConfiguration\n\n        /// Controls the amount of detail in the log returned in the build result.\n        public var logging: BuildLogVerbosity\n\n        /// A Boolean value that indicates whether to print build logs to the console.\n        public var echoLogs: Bool\n\n        /// Additional flags to pass to all C compiler invocations.\n        public var otherCFlags: [String] = []\n\n        /// Additional flags to pass to all C++ compiler invocations.\n        public var otherCxxFlags: [String] = []\n\n        /// Additional flags to pass to all Swift compiler invocations.\n        public var otherSwiftcFlags: [String] = []\n\n        /// Additional flags to pass to all linker invocations.\n        public var otherLinkerFlags: [String] = []\n\n        /// Creates a new sert of build parameters.\n        /// - Parameters:\n        ///   - configuration: The build configuration to use.\n        ///   - logging: The level of detail to include in the build logs returned in the build result.\n        ///   - echoLogs: Whether to print build logs to the console.\n        public init(\n            configuration: BuildConfiguration = .debug,\n            logging: BuildLogVerbosity = .concise,\n            echoLogs: Bool = false\n        ) {\n            self.configuration = configuration\n            self.logging = logging\n            self.echoLogs = echoLogs\n        }\n    }\n\n    /// The configuration to use for the build.\n    ///\n    /// The configuration affects optimization and generation of debug symbols.\n    public enum BuildConfiguration: String {\n        case debug, release, inherit\n    }\n\n    /// The amount of detail to include in a build log.\n    public enum BuildLogVerbosity: String {\n        case concise, verbose, debug\n    }\n\n    /// The results of running a build.\n    public struct BuildResult {\n        /// A Boolean value that indicates whether the build succeeded or failed.\n        public var succeeded: Bool\n\n        /// The log output.\n        ///\n        /// The verbatim text in the initial proposal.\n        public var logText: String\n\n        /// The artifacts built from the products in the package.\n        ///\n        /// Intermediates such as object files produced from individual targets aren't listed.\n        public var builtArtifacts: [BuiltArtifact]\n\n        /// The single artifact produced during a build.\n        public struct BuiltArtifact {\n            /// Full path of the built artifact in the local file system.\n            @available(_PackageDescription, deprecated: 6.0, renamed: \"url\")\n            public var path: Path {\n                try! Path(url: self.url)\n            }\n\n            /// The file URL of the built artifact in the local file system.\n            @available(_PackageDescription, introduced: 6.0)\n            public var url: URL\n\n            /// The kind of artifact built.\n            public var kind: Kind\n\n            /// The kind of artifact built.\n            ///\n            /// The specific file formats may vary from platform to platform.\n            /// For example, on macOS  a dynamic library may in fact be built as a framework.\n            public enum Kind: String {\n                case executable, dynamicLibrary, staticLibrary\n            }\n        }\n    }\n\n    /// Runs all, or a specified subset, of the unit tests of the package, after\n    /// an incremental build if necessary.\n    /// \n    /// The is functionally the same as `swift test` on the command line.\n    /// \n    /// The returned test result includes any test failures. This method throws an\n    /// error if the input parameters are invalid, or if the test cannot be\n    /// started.\n    /// \n    /// The Swift package manager command-line interface, or any IDE,\n    /// may show the progress of the tests as they happen.\n    /// - Parameters:\n    ///   - subset: The subset of tests to run.\n    ///   - parameters: The test parameters to apply.\n    /// - Returns: The test results.\n    public func test(\n        _ subset: TestSubset,\n        parameters: TestParameters\n    ) throws -> TestResult {\n        // Ask the plugin host to run the specified tests, and wait for a response.\n        // FIXME: We'll want to make this asynchronous when there is back deployment support for it.\n        try sendMessageAndWaitForReply(.testOperationRequest(subset: .init(subset), parameters: .init(parameters))) {\n            guard case .testOperationResponse(let result) = $0 else { return nil }\n            return .init(result)\n        }\n    }\n\n    /// Specifies which tests to run.\n    public enum TestSubset {\n        /// All tests in the package.\n        case all\n\n        /// One or more tests filtered by regular expression.\n        /// Use the format `<test-target>.<test-case>` or\n        /// `<test-target>.<test-case>/<test>`.\n        ///\n        /// This is the same as the `--filter` option of `swift test`.\n        case filtered([String])\n    }\n\n    /// Parameters that control how tests are run.\n    public struct TestParameters {\n        /// Whether to collect code coverage information while running tests.\n        public var enableCodeCoverage: Bool\n        \n        /// Creates a new set of test parameters.\n        /// - Parameter enableCodeCoverage: Whether to collect code coverage information while running tests.\n        public init(enableCodeCoverage: Bool = false) {\n            self.enableCodeCoverage = enableCodeCoverage\n        }\n    }\n\n    /// The result of running tests.\n    public struct TestResult {\n        /// A Boolean value that indicates whether the test run succeeded.\n        public var succeeded: Bool\n\n        /// Results for all the test targets run.\n        public var testTargets: [TestTarget]\n\n        /// The path of a generated profile file to provide code corage.\n        ///\n        /// The `.profdata` file is suitable for processing using\n        /// `llvm-cov`, if `enableCodeCoverage` was set in the test parameters.\n        @available(_PackageDescription, deprecated: 6.0, renamed: \"codeCoverageDataFileURL\")\n        public var codeCoverageDataFile: Path? {\n            self.codeCoverageDataFileURL.map { try! Path(url: $0) }\n        }\n\n        /// The file URL of a generated profile file to provide code coverage.\n        ///\n        /// The `.profdata` file is suitable for processing using\n        /// `llvm-cov`, if `enableCodeCoverage` was set in the test parameters.\n        @available(_PackageDescription, introduced: 6.0)\n        public var codeCoverageDataFileURL: URL?\n\n        /// The results of running some or all of the tests in a\n        /// single test target.\n        public struct TestTarget {\n            /// The name of the target.\n            public var name: String\n            /// The test cases included in the target.\n            public var testCases: [TestCase]\n\n            /// The results of running some or all of the tests in\n            /// a single test case.\n            public struct TestCase {\n                /// The name of the test case.\n                public var name: String\n                /// The tests included in the test case.\n                public var tests: [Test]\n\n                /// The results of running a single test.\n                public struct Test {\n                    /// The name of the test.\n                    public var name: String\n                    /// The test result.\n                    public var result: Result\n                    /// The duration of the test.\n                    public var duration: Double\n\n                    /// The result of running a single test.\n                    public enum Result: String {\n                        case succeeded, skipped, failed\n                    }\n                }\n            }\n        }\n    }\n\n    /// Return a directory containing symbol graph files for the given target\n    /// and options.\n    /// \n    /// If the symbol graphs need to be created or updated first, they will be.\n    /// Swift package manager or an IDE may generate these symbol graph files\n    /// in any way it sees fit.\n    /// - Parameters:\n    ///   - target: The target to build or from which to extract symbol graphs.\n    ///   - options: The options to use while building or extracting symbol graphs.\n    /// - Returns: The symbol graphs for the target you specify.\n    public func getSymbolGraph(\n        for target: Target,\n        options: SymbolGraphOptions\n    ) throws -> SymbolGraphResult {\n        // Ask the plugin host for symbol graph information for the target, and wait for a response.\n        // FIXME: We'll want to make this asynchronous when there is back deployment support for it.\n        try sendMessageAndWaitForReply(.symbolGraphRequest(targetName: target.name, options: .init(options))) {\n            guard case .symbolGraphResponse(let result) = $0 else { return nil }\n            return .init(result)\n        }\n    }\n\n    /// Represents options for symbol graph generation.\n    public struct SymbolGraphOptions {\n        /// The minimum access level of symbols to return.\n        ///\n        /// The symbol graph includes symbols at this access level and higher.\n        public var minimumAccessLevel: AccessLevel\n\n        /// The access level for a symbol.\n        public enum AccessLevel: String, CaseIterable {\n            case `private`, `fileprivate`, `internal`, `package`, `public`, open\n        }\n\n        /// A Boolean value that indicates whether to include inherited docs from class or protocol members.\n        public var includeInheritedDocs: Bool\n\n        /// A Boolean value that indicates whether to include synthesized members.\n        public var includeSynthesized: Bool\n\n        /// A Boolean value that indicates whether to include symbols marked as SPI.\n        public var includeSPI: Bool\n\n        /// A Boolean value that indicates whether to emit symbols for extensions to external types.\n        public var emitExtensionBlocks: Bool\n        \n        /// Creates a new set of options for returning the symbol graph for a target.\n        /// - Parameters:\n        ///   - minimumAccessLevel: The minimum access level of symbols to return.\n        ///   - includeInheritedDocs: A Boolean value that indicates whether to include inheirted docs from protocol or class members.\n        ///   - includeSynthesized: A Boolean value that indicates whether to include synthesized members.\n        ///   - includeSPI: A Boolean value that indicates whether to include symbols marked as SPI.\n        ///   - emitExtensionBlocks: A Boolean value that indicates whether to emit symbols for extensions to external types.\n        public init(\n            minimumAccessLevel: AccessLevel = .public,\n            includeInheritedDocs: Bool = true,\n            includeSynthesized: Bool = false,\n            includeSPI: Bool = false,\n            emitExtensionBlocks: Bool = false\n        ) {\n            self.minimumAccessLevel = minimumAccessLevel\n            self.includeInheritedDocs = includeInheritedDocs\n            self.includeSynthesized = includeSynthesized\n            self.includeSPI = includeSPI\n            self.emitExtensionBlocks = emitExtensionBlocks\n        }\n    }\n\n    /// The result of symbol graph generation.\n    public struct SymbolGraphResult {\n        /// The directory that contains the symbol graph files for the target.\n        @available(_PackageDescription, deprecated: 6.0, renamed: \"directoryURL\")\n        public var directoryPath: Path {\n            try! Path(url: self.directoryURL)\n        }\n\n        /// The file URL of the directory that contains the symbol graph files for the target.\n        @available(_PackageDescription, introduced: 6.0)\n        public var directoryURL: URL\n    }\n}\n\nextension PackageManager {\n    /// Private helper function that sends a message to the host and waits for a reply. The reply handler should return\n    /// `nil` for any reply message it doesn't recognize.\n    private func sendMessageAndWaitForReply<T>(\n        _ message: PluginToHostMessage,\n        replyHandler: (HostToPluginMessage) -> T?\n    ) throws -> T {\n        try pluginHostConnection.sendMessage(message)\n        guard let reply = try pluginHostConnection.waitForNextMessage() else {\n            throw PackageManagerProxyError.unspecified(\"internal error: unexpected lack of response message\")\n        }\n        if case .errorResponse(let message) = reply {\n            throw PackageManagerProxyError.unspecified(message)\n        }\n        if let result = replyHandler(reply) {\n            return result\n        }\n        throw PackageManagerProxyError.unspecified(\"internal error: unexpected response message \\(message)\")\n    }\n}\n\n/// Errors from methods using the package manager.\npublic enum PackageManagerProxyError: Error {\n    /// Indicates that the functionality isn't implemented in the plugin host.\n    case unimplemented(_ message: String)\n\n    /// An unspecified other kind of error from the package manager proxy.\n    case unspecified(_ message: String)\n}\n\nextension PluginToHostMessage.BuildSubset {\n    fileprivate init(_ subset: PackageManager.BuildSubset) {\n        switch subset {\n        case .all(let includingTests):\n            self = .all(includingTests: includingTests)\n        case .product(let name):\n            self = .product(name)\n        case .target(let name):\n            self = .target(name)\n        }\n    }\n}\n\nextension PluginToHostMessage.BuildParameters {\n    fileprivate init(_ parameters: PackageManager.BuildParameters) {\n        self.configuration = .init(parameters.configuration)\n        self.logging = .init(parameters.logging)\n        self.echoLogs = parameters.echoLogs\n        self.otherCFlags = parameters.otherCFlags\n        self.otherCxxFlags = parameters.otherCxxFlags\n        self.otherSwiftcFlags = parameters.otherSwiftcFlags\n        self.otherLinkerFlags = parameters.otherLinkerFlags\n    }\n}\n\nextension PluginToHostMessage.BuildParameters.Configuration {\n    fileprivate init(_ configuration: PackageManager.BuildConfiguration) {\n        switch configuration {\n        case .debug:\n            self = .debug\n        case .release:\n            self = .release\n        case .inherit:\n            self = .inherit\n        }\n    }\n}\n\nextension PluginToHostMessage.BuildParameters.LogVerbosity {\n    fileprivate init(_ verbosity: PackageManager.BuildLogVerbosity) {\n        switch verbosity {\n        case .concise:\n            self = .concise\n        case .verbose:\n            self = .verbose\n        case .debug:\n            self = .debug\n        }\n    }\n}\n\nextension PackageManager.BuildResult {\n    fileprivate init(_ result: HostToPluginMessage.BuildResult) {\n        self.succeeded = result.succeeded\n        self.logText = result.logText\n        self.builtArtifacts = result.builtArtifacts.map { .init($0) }\n    }\n}\n\nextension PackageManager.BuildResult.BuiltArtifact {\n    fileprivate init(_ artifact: HostToPluginMessage.BuildResult.BuiltArtifact) {\n        self.kind = .init(artifact.kind)\n        self.url = artifact.path\n    }\n}\n\nextension PackageManager.BuildResult.BuiltArtifact.Kind {\n    fileprivate init(_ kind: HostToPluginMessage.BuildResult.BuiltArtifact.Kind) {\n        switch kind {\n        case .executable:\n            self = .executable\n        case .dynamicLibrary:\n            self = .dynamicLibrary\n        case .staticLibrary:\n            self = .staticLibrary\n        }\n    }\n}\n\nextension PluginToHostMessage.TestSubset {\n    fileprivate init(_ subset: PackageManager.TestSubset) {\n        switch subset {\n        case .all:\n            self = .all\n        case .filtered(let regexes):\n            self = .filtered(regexes)\n        }\n    }\n}\n\nextension PluginToHostMessage.TestParameters {\n    fileprivate init(_ parameters: PackageManager.TestParameters) {\n        self.enableCodeCoverage = parameters.enableCodeCoverage\n    }\n}\n\nextension PackageManager.TestResult {\n    fileprivate init(_ result: HostToPluginMessage.TestResult) {\n        self.succeeded = result.succeeded\n        self.testTargets = result.testTargets.map { .init($0) }\n        self.codeCoverageDataFileURL = result.codeCoverageDataFile.map { URL(fileURLWithPath: $0) }\n    }\n}\n\nextension PackageManager.TestResult.TestTarget {\n    fileprivate init(_ testTarget: HostToPluginMessage.TestResult.TestTarget) {\n        self.name = testTarget.name\n        self.testCases = testTarget.testCases.map { .init($0) }\n    }\n}\n\nextension PackageManager.TestResult.TestTarget.TestCase {\n    fileprivate init(_ testCase: HostToPluginMessage.TestResult.TestTarget.TestCase) {\n        self.name = testCase.name\n        self.tests = testCase.tests.map { .init($0) }\n    }\n}\n\nextension PackageManager.TestResult.TestTarget.TestCase.Test {\n    fileprivate init(_ test: HostToPluginMessage.TestResult.TestTarget.TestCase.Test) {\n        self.name = test.name\n        self.result = .init(test.result)\n        self.duration = test.duration\n    }\n}\n\nextension PackageManager.TestResult.TestTarget.TestCase.Test.Result {\n    fileprivate init(_ result: HostToPluginMessage.TestResult.TestTarget.TestCase.Test.Result) {\n        switch result {\n        case .succeeded:\n            self = .succeeded\n        case .skipped:\n            self = .skipped\n        case .failed:\n            self = .failed\n        }\n    }\n}\n\nextension PluginToHostMessage.SymbolGraphOptions {\n    fileprivate init(_ options: PackageManager.SymbolGraphOptions) {\n        self.minimumAccessLevel = .init(options.minimumAccessLevel)\n        self.includeInheritedDocs = options.includeInheritedDocs\n        self.includeSynthesized = options.includeSynthesized\n        self.includeSPI = options.includeSPI\n        self.emitExtensionBlocks = options.emitExtensionBlocks\n    }\n}\n\nextension PluginToHostMessage.SymbolGraphOptions.AccessLevel {\n    fileprivate init(_ accessLevel: PackageManager.SymbolGraphOptions.AccessLevel) {\n        switch accessLevel {\n        case .private:\n            self = .private\n        case .fileprivate:\n            self = .fileprivate\n        case .internal:\n            self = .internal\n        case .public:\n            self = .public\n        case .package:\n            self = .package\n        case .open:\n            self = .open\n        }\n    }\n}\n\nextension PackageManager.SymbolGraphResult {\n    fileprivate init(_ result: HostToPluginMessage.SymbolGraphResult) {\n        self.directoryURL = result.directoryPath\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/PackageModel.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A single package in a graph of packages.\n///\n/// The package can either be the root package, or a dependency.\npublic struct Package {\n    /// The unique identifier for the package.\n    public let id: ID\n    /// The type that represents a package identifier.\n    public typealias ID = String\n\n    /// The name of the package.\n    ///\n    /// Use the name for display purposes only.\n    public let displayName: String\n\n    /// The absolute path of the package directory in the local file system.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"directoryURL\")\n    public let directory: Path\n\n    /// The file URL of the package directory in the local file system.\n    @available(_PackageDescription, introduced: 6.0)\n    public let directoryURL: URL\n\n    /// The origin of the package.\n    public let origin: PackageOrigin\n\n    /// The tools version specified by the resolved version of the package.\n    /// \n    /// Behavior is often gated on the tools version to make sure older\n    /// packages continue to work as intended.\n    public let toolsVersion: ToolsVersion\n\n    /// Any dependencies on other packages.\n    ///\n    /// The dependencies are included in the same order as\n    /// specified in the package manifest.\n    public let dependencies: [PackageDependency]\n\n    /// Any regular products defined in this package, with the exception of plugin products.\n    ///\n    /// The products are specified in the same order as the package manifest.\n    public let products: [Product]\n\n    /// Any regular targets defined in this packagewith the exception of plugin targets.\n    ///\n    /// The targets are specified in the same order as the package manifest.\n    public let targets: [Target]\n}\n\n/// The origin of a package.\npublic enum PackageOrigin {\n    /// A root package.\n    ///\n    /// The root package is unversioned.\n    case root\n\n    /// A local package, referenced by path.\n    ///\n    /// A local package is unversioned.\n    case local(path: String)\n\n    /// A package from a Git repository, with a URL and with a textual\n    /// description of the resolved version or branch name (for display\n    /// purposes only), and the corresponding SCM revision.\n    ///\n    /// The\n    /// revision is the Git commit hash and may be useful for plugins\n    /// that generates source code that includes version information.\n    case repository(url: String, displayVersion: String, scmRevision: String)\n\n    /// A package from a registry, with an identity and with a textual\n    /// description of the resolved version or branch name (for display\n    /// purposes only).\n    case registry(identity: String, displayVersion: String)\n}\n\n/// A version of Swift package manager on whose semantics a package relies.\npublic struct ToolsVersion {\n    /// The major version.\n    public let major: Int\n\n    /// The minor version.\n    public let minor: Int\n\n    /// The patch version.\n    public let patch: Int\n    \n    @_spi(PackagePluginInternal) public init(major: Int, minor: Int, patch: Int) {\n        self.major = major\n        self.minor = minor\n        self.patch = patch\n    }\n}\n\n/// A resolved dependency of a package.\n///\n/// This is a separate entity in order to make it easier for future versions of the API to\n/// add information about the dependency itself.\npublic struct PackageDependency {\n    /// The package that is a dependency.\n    public let package: Package\n\n    init(package: Package) {\n        self.package = package\n    }\n}\n\n/// A single product defined in a package.\npublic protocol Product {\n    /// Unique identifier for the product.\n    var id: ID { get }\n    /// The type that represents the identifier of a package product.\n    typealias ID = String\n\n    /// The name of the product, as defined in the package manifest.\n    ///\n    /// This name is unique among the products of the package in which it is defined.\n    var name: String { get }\n\n    /// The targets that directly comprise the product, in the order in which\n    /// they are declared in the package manifest.\n    ///\n    /// The product contains the transitive closure of the these targets and their\n    /// dependencies. Some kinds of products have further restrictions on the set of\n    /// targets (for example, an executable product must have one and only one\n    /// target that defines the main entry point for an executable).\n    var targets: [Target] { get }\n}\n\n/// An executable product defined in a package.\npublic struct ExecutableProduct: Product {\n    /// Unique identifier for the product.\n    public let id: ID\n\n    /// The name of the product, as defined in the package manifest.\n    ///\n    /// This name is unique among the products of the package in which it is defined.\n    public let name: String\n\n    /// The targets that directly comprise the product, in the order in which\n    /// they are declared in the package manifest.\n    ///\n    /// The product contains the transitive closure of the these targets and their dependencies.\n    /// For an `ExecutableProduct`, exactly one of the targets in this list must be an\n    /// `ExecutableTarget`.\n    public let targets: [Target]\n\n    /// The target that contains the main entry point of the executable.\n    ///\n    /// Every executable product has exactly one main executable target. This target\n    /// will always be one of the targets in the product's `targets` array.\n    public let mainTarget: Target\n}\n\n/// A library product defined in a package.\npublic struct LibraryProduct: Product {\n    /// Unique identifier for the product.\n    public let id: ID\n\n    /// The name of the product, as defined in the package manifest.\n    ///\n    /// This name is unique among the products of the package in which\n    /// it is defined.\n    public let name: String\n\n    /// The targets that directly comprise the product, in the order in which\n    /// they are declared in the package manifest.\n    ///\n    /// The product contains the transitive closure of the these targets\n    /// and their dependencies.\n    public let targets: [Target]\n\n    /// A value that indicates whether the library is static, dynamic, or automatically determined.\n    public let kind: Kind\n\n    /// The kind of library product.\n    public enum Kind {\n        /// A static library, whose code is copied into its clients.\n        case `static`\n\n        /// Dynamic library, whose code is referenced by its clients.\n        case dynamic\n\n        /// The kind of library produced is unspecified and will be determined\n        /// by the build system based on how the library is used.\n        case automatic\n    }\n}\n\n/// A single target defined in a package.\npublic protocol Target {\n    /// Unique identifier for the target.\n    var id: ID { get }\n    /// The type that represents the ID of the target.\n    typealias ID = String\n\n    /// The name of the target, as defined in the package manifest.\n    ///\n    /// This name is unique among the targets of the package in which it is defined.\n    var name: String { get }\n\n    /// The absolute path of the target directory in the local file system.\n    @available(_PackageDescription, deprecated: 6.1, renamed: \"directoryURL\")\n    var directory: Path { get }\n\n    /// The file URL of the target directory in the local file system.\n    @available(_PackageDescription, introduced: 6.1)\n    var directoryURL: URL { get }\n\n    /// Any other targets on which this target depends, in the same order as\n    /// they are specified in the package manifest.\n    ///\n    /// Conditional dependencies that do not apply are filtered out.\n    var dependencies: [TargetDependency] { get }\n}\n\n/// A dependency of a target on a product or on another target.\npublic enum TargetDependency {\n    /// A dependency on a target in the same package.\n    case target(Target)\n\n    /// A dependency on a product in another package.\n    case product(Product)\n}\n\n/// A target consisting of a source code module.\n///\n/// The module contains either Swift or source files in one of\n/// the C-based languages.\npublic protocol SourceModuleTarget: Target {\n    /// The name of the module produced by the target.\n    ///\n    /// Derived from the target name, though future Swift package manager versions may\n    /// allow this to be customized.\n    var moduleName: String { get }\n\n    /// The kind of module, describing whether it contains unit tests, contains\n    /// the main entry point of an executable, or neither.\n    var kind: ModuleKind { get }\n\n    /// The source files that are associated with this target.\n    ///\n    /// Any files that have been excluded in the manifest are filtered out.\n    var sourceFiles: FileList { get }\n\n    /// Any custom linked libraries required by the module, as specified in the\n    /// package manifest.\n    var linkedLibraries: [String] { get }\n\n    /// Any custom linked frameworks required by the module, as specified in the\n    /// package manifest.\n    var linkedFrameworks: [String] { get }\n\n    /// The file URLs of any sources generated by other plugins applied to the given target before the plugin\n    /// being executed.\n    ///\n    /// Note: Plugins are applied in order of declaration in the package manifest. Generated files are vended to the\n    /// target the current plugin is being applied to, but not necessarily to other targets in the package graph.\n    @available(_PackageDescription, introduced: 6.0)\n    var pluginGeneratedSources: [URL] { get }\n\n    /// The file URLs of any resources generated by other plugins that have been applied to the given target\n    /// before the plugin currently being executed.\n    ///\n    /// Note: Plugins are applied in order of declaration in the package manifest. Generated files are vended to the\n    /// target the current plugin is being applied to, but not necessarily to other targets in the package graph.\n    @available(_PackageDescription, introduced: 6.0)\n    var pluginGeneratedResources: [URL] { get }\n}\n\n/// The kind of module.\npublic enum ModuleKind {\n    /// A module that contains generic code (not a test nor an executable).\n    case generic\n    /// A module that contains code for an executable's main module.\n    case executable\n    /// A module that contains code for a snippet.\n    @available(_PackageDescription, introduced: 5.8)\n    case snippet\n    /// A module that contains unit tests.\n    case test\n    /// A module that contains code for a macro.\n    @available(_PackageDescription, introduced: 5.9)\n    case macro // FIXME: This should really come from `CompilerPluginSupport` somehow, but we lack the infrastructure to allow that currently.\n}\n\n/// A target consisting of a source code module compiled using Swift.\npublic struct SwiftSourceModuleTarget: SourceModuleTarget {\n    /// Unique identifier for the target.\n    public let id: ID\n\n    /// The name of the target, as defined in the package manifest.\n    ///\n    /// This name is unique among the targets of the package in which it is defined.\n    public let name: String\n\n    /// The kind of module, describing whether it contains unit tests, contains\n    /// the main entry point of an executable, or neither.\n    public let kind: ModuleKind\n\n    /// The absolute path of the target directory in the local file system.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"directoryURL\")\n    public let directory: Path\n\n    /// The file URL of the target directory in the local file system.\n    @available(_PackageDescription, introduced: 6.0)\n    public let directoryURL: URL\n\n    /// Any other targets on which this target depends, in the same order as\n    /// specified in the package manifest.\n    ///\n    /// Conditional dependencies that do not apply have already been filtered out.\n    public let dependencies: [TargetDependency]\n\n    /// The name of the module produced by the target.\n    ///\n    /// This is derived from the target name, though future Swift package manager\n    /// versions may allow this to be customized.\n    public let moduleName: String\n\n    /// The source files associated with this target\n    ///\n    /// Any files that have been excluded in the manifest have already been filtered out.\n    public let sourceFiles: FileList\n\n    /// Any custom compilation conditions specified for the Swift target in the\n    /// package manifest.\n    public let compilationConditions: [String]\n\n    /// Any custom linked libraries required by the module, as specified in the\n    /// package manifest.\n    public let linkedLibraries: [String]\n\n    /// Any custom linked frameworks required by the module, as specified in the\n    /// package manifest.\n    public let linkedFrameworks: [String]\n\n    /// The file URLs of any sources generated by other plugins that have been applied\n    /// to the given target before the plugin being executed.\n    @available(_PackageDescription, introduced: 6.0)\n    public let pluginGeneratedSources: [URL]\n\n    /// The file URLS of any resources generated by other plugins that have been applied\n    /// to the given target before the plugin being executed.\n    @available(_PackageDescription, introduced: 6.0)\n    public let pluginGeneratedResources: [URL]\n}\n\n/// A target consisting of a source code module compiled using Clang.\npublic struct ClangSourceModuleTarget: SourceModuleTarget {\n    /// Unique identifier for the target.\n    public let id: ID\n\n    /// The name of the target, as defined in the package manifest.\n    ///\n    /// This name is unique among the targets of the package in which it is defined.\n    public let name: String\n\n    /// The kind of module.\n    ///\n    /// The kind of module describes whether it contains unit tests,\n    /// the main entry point of an executable, or neither.\n    public let kind: ModuleKind\n\n    /// The absolute path of the target directory in the local file system.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"directoryURL\")\n    public let directory: Path\n\n    /// The file URL of the target directory in the local file system.\n    @available(_PackageDescription, introduced: 6.0)\n    public let directoryURL: URL\n\n    /// Any other targets on which this target depends, in the same order as\n    /// specified in the package manifest.\n    ///\n    /// Conditional dependencies that do not apply have already been filtered out.\n    public let dependencies: [TargetDependency]\n\n    /// The name of the module produced by the target.\n    ///\n    /// This is derived from the target name, though future Swift package manager\n    /// versions may allow this to be customized.\n    public let moduleName: String\n\n    /// The source files that are associated with this target.\n    ///\n    /// Any files that have been excluded in the manifest have already been filtered out.\n    public let sourceFiles: FileList\n\n    /// Any preprocessor definitions specified for the Clang target.\n    public let preprocessorDefinitions: [String]\n\n    /// Any custom header search paths specified for the Clang target.\n    public let headerSearchPaths: [String]\n\n    /// The directory containing public C headers, if applicable.\n    ///\n    /// This will only be set for targets that have a directory of a public headers.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"publicHeadersDirectoryURL\")\n    public let publicHeadersDirectory: Path?\n\n    /// The directory containing public C headers, if applicable.\n    ///\n    /// This will only be set for targets that have a directory of a public headers.\n    @available(_PackageDescription, introduced: 6.0)\n    public let publicHeadersDirectoryURL: URL?\n\n    /// Any custom linked libraries required by the module, as specified in the\n    /// package manifest.\n    public let linkedLibraries: [String]\n\n    /// Any custom linked frameworks required by the module, as specified in the\n    /// package manifest.\n    public let linkedFrameworks: [String]\n\n    /// The file URLs of any sources generated by other plugins that have been applied\n    /// to the given target before the plugin currently being executed.\n    @available(_PackageDescription, introduced: 6.0)\n    public let pluginGeneratedSources: [URL]\n\n    /// The file URLs of any resources generated by other plugins that have been applied\n    /// to the given target before the plugin currently being executed.\n    @available(_PackageDescription, introduced: 6.0)\n    public let pluginGeneratedResources: [URL]\n}\n\n/// A target describing an artifact that is distributed as a binary.\n///\n/// For example, a library or executable.\npublic struct BinaryArtifactTarget: Target {\n    /// Unique identifier for the target.\n    public let id: ID\n\n    /// The name of the target, as defined in the package manifest.\n    ///\n    /// This name is unique among the targets of the package in which it is defined.\n    public let name: String\n\n    /// The absolute path of the target directory in the local file system.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"directoryURL\")\n    public let directory: Path\n\n    /// The file URL of the target directory in the local file system.\n    @available(_PackageDescription, introduced: 6.0)\n    public let directoryURL: URL\n\n    /// Any other targets on which this target depends, in the same order as\n    /// specified in the package manifest.\n    ///\n    /// Conditional dependencies that do not apply have already been filtered out.\n    public let dependencies: [TargetDependency]\n\n    /// The kind of binary artifact.\n    public let kind: Kind\n\n    /// The original source of the binary artifact.\n    public let origin: Origin\n\n    /// The path location of the binary artifact in the local file system.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"artifactURL\")\n    public let artifact: Path\n\n    /// The file URL of the location of the binary artifact in the local file system.\n    @available(_PackageDescription, introduced: 6.0)\n    public let artifactURL: URL\n\n    /// A kind of binary artifact.\n    public enum Kind {\n        /// An XCFramework.\n        case xcframework\n        /// An artifact archive.\n        case artifactsArchive\n    }\n\n    /// The original location of a binary artifact.\n    public enum Origin: Equatable {\n        /// An artifact that was available locally.\n        case local\n\n        /// An artifact that was downloaded from a remote URL.\n        case remote(url: String)\n    }\n}\n\n/// A target describing a system library that is expected to be\n/// present on the host system.\npublic struct SystemLibraryTarget: Target {\n    /// Unique identifier for the target.\n    public let id: ID\n\n    /// The name of the target, as defined in the package manifest.\n    ///\n    /// This name is unique among the targets of the package in which it is defined.\n    public var name: String\n\n    /// The absolute path of the target directory in the local file system.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"directoryURL\")\n    public var directory: Path\n\n    /// The file URL of the target directory in the local file system.\n    @available(_PackageDescription, introduced: 6.0)\n    public var directoryURL: URL\n\n    /// Any other targets on which this target depends, in the same order as\n    /// specified in the package manifest.\n    ///\n    /// Conditional dependencies that do not apply have already been filtered out.\n    public var dependencies: [TargetDependency]\n\n    /// The name of the `pkg-config` file, if any, describing the library.\n    public let pkgConfig: String?\n\n    /// Flags from `pkg-config` to pass to Clang and SwiftC.\n    ///\n    /// Flags are passed to using `-Xcc`.\n    public let compilerFlags: [String]\n\n    /// Flags from `pkg-config` to pass to the platform linker.\n    public let linkerFlags: [String]\n}\n\n/// Provides information about a list of files.\n///\n/// The order is not defined but is guaranteed to be stable.\n/// This allows the implementation to be more efficient than a static file list.\npublic struct FileList {\n    private var files: [File]\n\n    @_spi(PackagePluginInternal) public init(_ files: [File]) {\n        self.files = files\n    }\n}\n\nextension FileList: Sequence {\n    public struct Iterator: IteratorProtocol {\n        private var files: ArraySlice<File>\n        fileprivate init(files: ArraySlice<File>) {\n            self.files = files\n        }\n\n        public mutating func next() -> File? {\n            guard let nextInfo = self.files.popFirst() else {\n                return nil\n            }\n            return nextInfo\n        }\n    }\n\n    public func makeIterator() -> Iterator {\n        Iterator(files: ArraySlice(self.files))\n    }\n}\n\n@available(_PackageDescription, introduced: 5.10)\nextension FileList: RandomAccessCollection {\n    public var startIndex: Int { 0 }\n    public var endIndex: Int { self.files.endIndex }\n    public subscript(i: Int) -> File { self.files[i] }\n}\n\n/// Information about a single file in a FileList.\npublic struct File {\n    /// The path of the file.\n    @available(_PackageDescription, deprecated: 6.0, renamed: \"url\")\n    public var path: Path {\n        return try! Path(url: url)\n    }\n\n    /// The URL of the file.\n    @available(_PackageDescription, introduced: 6.0)\n    public let url: URL\n\n    /// The File type, as determined by Swift package manager.\n    public let type: FileType\n\n    @_spi(PackagePluginInternal) public init(url: URL, type: FileType) {\n        self.url = url\n        self.type = type\n    }\n}\n\n/// Information about the type of a file.\n///\n/// Future cases will use availability annotations to make sure existing plugins\n/// continue to work until they increase their required tools version.\npublic enum FileType {\n    /// A source file.\n    case source\n\n    /// A header file.\n    case header\n\n    /// A resource file.\n    ///\n    /// A resource file may be either processed or copied.\n    case resource\n\n    /// A file not covered by any other rule.\n    case unknown\n}\n\n/// Provides information about a list of paths.\n///\n/// The order is not defined but is guaranteed to be stable.\n/// This allows the implementation to be more efficient than a static path list.\npublic struct PathList {\n    private var paths: [URL]\n\n    @_spi(PackagePluginInternal) public init(_ paths: [URL]) {\n        self.paths = paths\n    }\n}\nextension PathList: Sequence {\n    public struct Iterator: IteratorProtocol {\n        private var paths: ArraySlice<Path>\n        fileprivate init(paths: ArraySlice<Path>) {\n            self.paths = paths\n        }\n        mutating public func next() -> Path? {\n            guard let nextInfo = self.paths.popFirst() else {\n                return nil\n            }\n            return nextInfo\n        }\n    }\n    public func makeIterator() -> Iterator {\n        // FIXME: This iterator should be converted to URLs, too, but that doesn't seem to be possible without breaking source compatibility\n        return Iterator(paths: ArraySlice(self.paths.map { try! Path(url: $0) }))\n    }\n}\n\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Path.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A simple representation of a path in the file system.\npublic struct Path: Hashable {\n    private let _string: String\n\n    /// Initializes the path from the contents a string, which should be an\n    /// absolute path in platform representation.\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public init(_ string: String) {\n        self._string = string\n    }\n\n    init(url: URL) throws {\n        self._string = try url.filePath\n    }\n\n    /// A string representation of the path.\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public var string: String {\n        self._string\n    }\n\n    // Note: this avoids duplication warnings for our own code.\n    var stringValue: String {\n        self._string\n    }\n\n    /// The last path component (including any extension).\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public var lastComponent: String {\n        // Check for a special case of the root directory.\n        if self._string == \"/\" {\n            // Root directory, so the basename is a single path separator (the\n            // root directory is special in this regard).\n            return \"/\"\n        }\n        // Find the last path separator.\n        guard let idx = _string.lastIndex(of: \"/\") else {\n            // No path separators, so the basename is the whole string.\n            return self._string\n        }\n        // Otherwise, it's the string from (but not including) the last path\n        // separator.\n        return String(self._string.suffix(from: self._string.index(after: idx)))\n    }\n\n    /// The last path component (without any extension).\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public var stem: String {\n        let filename = self.lastComponent\n        if let ext = self.extension {\n            return String(filename.dropLast(ext.count + 1))\n        } else {\n            return filename\n        }\n    }\n\n    /// The filename extension, if any (without any leading dot).\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public var `extension`: String? {\n        // Find the last path separator, if any.\n        let sIdx = self._string.lastIndex(of: \"/\")\n\n        // Find the start of the basename.\n        let bIdx = (sIdx != nil) ? self._string.index(after: sIdx!) : self._string.startIndex\n\n        // Find the last `.` (if any), starting from the second character of\n        // the basename (a leading `.` does not make the whole path component\n        // a suffix).\n        let fIdx = self._string.index(bIdx, offsetBy: 1, limitedBy: self._string.endIndex) ?? self._string.startIndex\n        if let idx = _string[fIdx...].lastIndex(of: \".\") {\n            // Unless it's just a `.` at the end, we have found a suffix.\n            if self._string.distance(from: idx, to: self._string.endIndex) > 1 {\n                return String(self._string.suffix(from: self._string.index(idx, offsetBy: 1)))\n            }\n        }\n        // If we get this far, there is no suffix.\n        return nil\n    }\n\n    /// The path except for the last path component.\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public func removingLastComponent() -> Path {\n        // Find the last path separator.\n        guard let idx = string.lastIndex(of: \"/\") else {\n            // No path separators, so the directory name is `.`.\n            return Path(\".\")\n        }\n        // Check if it's the only one in the string.\n        if idx == self.string.startIndex {\n            // Just one path separator, so the directory name is `/`.\n            return Path(\"/\")\n        }\n        // Otherwise, it's the string up to (but not including) the last path\n        // separator.\n        return Path(String(self._string.prefix(upTo: idx)))\n    }\n\n    /// The result of appending a subpath, which should be a relative path in\n    /// platform representation.\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public func appending(subpath: String) -> Path {\n        Path(self._string + (self._string.hasSuffix(\"/\") ? \"\" : \"/\") + subpath)\n    }\n\n    /// The result of appending one or more path components.\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public func appending(_ components: [String]) -> Path {\n        self.appending(subpath: components.joined(separator: \"/\"))\n    }\n\n    /// The result of appending one or more path components.\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public func appending(_ components: String...) -> Path {\n        self.appending(components)\n    }\n}\n\nextension Path: CustomStringConvertible {\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public var description: String {\n        self.string\n    }\n}\n\nextension Path: Codable {\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.singleValueContainer()\n        try container.encode(self.string)\n    }\n\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.singleValueContainer()\n        let string = try container.decode(String.self)\n        self.init(string)\n    }\n}\n\nextension String.StringInterpolation {\n    @available(_PackageDescription, deprecated: 6.0, message: \"Use `URL` type instead of `Path`.\")\n    public mutating func appendInterpolation(_ path: Path) {\n        self.appendInterpolation(path.string)\n    }\n}\n\nextension URL {\n    /// Returns the path of the file URL.\n    ///\n    /// This should always be used whenever the file path equivalent of a URL is needed. DO NOT use ``path`` or ``path(percentEncoded:)``, as these deal in terms of the path portion of the URL representation per RFC8089, which on Windows would include a leading slash.\n    ///\n    /// - throws: ``FileURLError`` if the URL does not represent a file or its path is otherwise not representable.\n    fileprivate var filePath: String {\n        get throws {\n            guard isFileURL else {\n                throw FileURLError.notRepresentable(self)\n            }\n            return try withUnsafeFileSystemRepresentation { cString in\n                guard let cString else {\n                    throw FileURLError.notRepresentable(self)\n                }\n                return String(cString: cString)\n            }\n        }\n    }\n}\n\nfileprivate enum FileURLError: Error {\n    case notRepresentable(URL)\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Plugin.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n#if os(Windows)\n@_implementationOnly import ucrt\n@_implementationOnly import WinSDK\n\ninternal func dup(_ fd: CInt) -> CInt {\n    return _dup(fd)\n}\ninternal func dup2(_ fd1: CInt, _ fd2: CInt) -> CInt {\n    return _dup2(fd1, fd2)\n}\ninternal func close(_ fd: CInt) -> CInt {\n    return _close(fd)\n}\ninternal func fileno(_ fh: UnsafeMutablePointer<FILE>?) -> CInt {\n    return _fileno(fh)\n}\n\ninternal func strerror(_ errno: CInt) -> String? {\n    // MSDN indicates that the returned string can have a maximum of 94\n    // characters, so allocate 95 characters.\n    return withUnsafeTemporaryAllocation(of: wchar_t.self, capacity: 95) {\n        let result = _wcserror_s($0.baseAddress, $0.count, errno)\n        guard result == 0, let baseAddress = $0.baseAddress else { return nil }\n        return String(decodingCString: baseAddress, as: UTF16.self)\n    }\n}\n#elseif canImport(Android)\nimport Android\n#endif\n\n//\n// This source file contains the main entry point for all kinds of plugins.\n// A plugin receives messages from the \"plugin host\" (either SwiftPM or some\n// IDE that uses libSwiftPM), and sends back messages in return based on its\n// actions and events. A plugin can also request services from the host.\n//\n// Exactly how the plugin host invokes a plugin is an implementation detail,\n// but the current approach is to compile the Swift source files that make up\n// the plugin into an executable for the host platform, and to then invoke the\n// executable in a sandbox that blocks network access and prevents changes to\n// all except for a few specific file system locations.\n//\n// The host process and the plugin communicate using messages in the form of\n// length-prefixed JSON-encoded Swift enums. The host sends messages to the\n// plugin through its standard-input pipe, and receives messages through the\n// plugin's standard-output pipe. All output received through the plugin's\n// standard-error pipe is considered to be free-form textual console output.\n//\n// Within the plugin process, `stdout` is redirected to `stderr` so that print\n// statements from the plugin are treated as plain-text output, and `stdin` is\n// closed so that any attempts by the plugin logic to read from console result\n// in errors instead of blocking the process. The original `stdin` and `stdout`\n// are duplicated for use as messaging pipes, and are not directly used by the\n// plugin logic.\n//\n// The exit code of the plugin process indicates whether the plugin invocation\n// is considered successful. A failure result should also be accompanied by an\n// emitted error diagnostic, so that errors are understandable by the user.\n//\n// Using standard input and output streams for messaging avoids having to make\n// allowances in the sandbox for other channels of communication, and seems a\n// more portable approach than many of the alternatives. This is all somewhat\n// temporary in any case — in the long term, something like distributed actors\n// or something similar can hopefully replace the custom messaging.\n//\n\nextension Plugin {\n    \n    /// The main entry point of the plugin.\n    ///\n    /// This sets up a communication channel with the plugin host and runs the main message loop.\n    public static func main() async throws {\n        // Duplicate the `stdin` file descriptor, which we will then use for\n        // receiving messages from the plugin host.\n        let inputFD = dup(fileno(stdin))\n        guard inputFD >= 0 else {\n            internalError(\"Could not duplicate `stdin`: \\(describe(errno: errno)).\")\n        }\n        \n        // Having duplicated the original standard-input descriptor, we close\n        // `stdin` so that attempts by the plugin to read console input (which\n        // are usually a mistake) return errors instead of blocking.\n        guard close(fileno(stdin)) >= 0 else {\n            internalError(\"Could not close `stdin`: \\(describe(errno: errno)).\")\n        }\n\n        // Duplicate the `stdout` file descriptor, which we will then use for\n        // sending messages to the plugin host.\n        let outputFD = dup(fileno(stdout))\n        guard outputFD >= 0 else {\n            internalError(\"Could not dup `stdout`: \\(describe(errno: errno)).\")\n        }\n        \n        // Having duplicated the original standard-output descriptor, redirect\n        // `stdout` to `stderr` so that all free-form text output goes there.\n        guard dup2(fileno(stderr), fileno(stdout)) >= 0 else {\n            internalError(\"Could not dup2 `stdout` to `stderr`: \\(describe(errno: errno)).\")\n        }\n        \n        // Turn off full buffering so printed text appears as soon as possible.\n        // Windows is much less forgiving than other platforms.  If line\n        // buffering is enabled, we must provide a buffer and the size of the\n        // buffer.  As a result, on Windows, we completely disable all\n        // buffering, which means that partial writes are possible.\n#if os(Windows)\n        setvbuf(stdout, nil, _IONBF, 0)\n#else\n        setvbuf(stdout, nil, _IOLBF, 0)\n#endif\n\n        // Open a message channel for communicating with the plugin host.\n        pluginHostConnection = PluginHostConnection(\n            inputStream: FileHandle(fileDescriptor: inputFD),\n            outputStream: FileHandle(fileDescriptor: outputFD))\n        \n        // Handle messages from the host until the input stream is closed,\n        // indicating that we're done.\n        while let message = try pluginHostConnection.waitForNextMessage() {\n            do {\n                try await handleMessage(message)\n            }\n            catch {\n                // Emit a diagnostic and indicate failure to the plugin host,\n                // and exit with an error code.\n                Diagnostics.error(String(describing: error))\n                exit(1)\n            }\n        }\n    }\n    \n    /// Handles a single message received from the plugin host.\n    fileprivate static func handleMessage(_ message: HostToPluginMessage) async throws {\n        switch message {\n            \n        case .createBuildToolCommands(let wireInput, let rootPackageId, let targetId, let generatedSources, let generatedResources):\n            // Deserialize the context from the wire input structures. The root\n            // package is the one we'll set the context's `package` property to.\n            let context: PluginContext\n            let target: Target\n            do {\n                var deserializer = PluginContextDeserializer(wireInput)\n                let package = try deserializer.package(for: rootPackageId)\n                let pluginWorkDirectory = try deserializer.url(for: wireInput.pluginWorkDirId)\n                let toolSearchDirectories = try wireInput.toolSearchDirIds.map {\n                    try deserializer.url(for: $0)\n                }\n                let accessibleTools = try wireInput.accessibleTools.mapValues { (tool: HostToPluginMessage.InputContext.Tool) -> (URL, [String]?) in\n                    let path = try deserializer.url(for: tool.path)\n                    return (path, tool.triples)\n                }\n\n                context = try PluginContext(\n                    package: package,\n                    pluginWorkDirectory: Path(url: pluginWorkDirectory),\n                    pluginWorkDirectoryURL: pluginWorkDirectory,\n                    accessibleTools: accessibleTools,\n                    toolSearchDirectories: toolSearchDirectories.map { try Path(url: $0) },\n                    toolSearchDirectoryURLs: toolSearchDirectories)\n\n                let pluginGeneratedSources = try generatedSources.map { try deserializer.url(for: $0) }\n                let pluginGeneratedResources = try generatedResources.map { try deserializer.url(for: $0) }\n                target = try deserializer.target(\n                    for: targetId,\n                    pluginGeneratedSources: pluginGeneratedSources,\n                    pluginGeneratedResources: pluginGeneratedResources\n                )\n            }\n            catch {\n                internalError(\"Couldn’t deserialize input from host: \\(error).\")\n            }\n\n            // Instantiate the plugin. For now there are no parameters, but\n            // this is where we would set them up, most likely as properties\n            // of the plugin instance (similar to how SwiftArgumentParser\n            // allows commands to annotate arguments). It could use property\n            // wrappers to mark up properties in the plugin, and a separate\n            // message could be used to query the plugin for its parameter\n            // definitions.\n            let plugin = self.init()\n\n            // Check that the plugin implements the appropriate protocol\n            // for its declared `.buildTool` capability.\n            guard let plugin = plugin as? BuildToolPlugin else {\n                throw PluginDeserializationError.missingBuildToolPluginProtocolConformance(protocolName: \"BuildToolPlugin\")\n            }\n            \n            // Invoke the plugin to create build commands for the target.\n            let generatedCommands = try await plugin.createBuildCommands(context: context, target: target)\n            \n            // Send each of the generated commands to the host.\n            for command in generatedCommands {\n                switch command {\n\n                case .buildCommand(let displayName, let executable, let arguments, let environment, let inputFiles, let outputFiles):\n                    let command = PluginToHostMessage.CommandConfiguration(\n                        displayName: displayName,\n                        executable: executable,\n                        arguments: arguments,\n                        environment: environment\n                    )\n                    let message = PluginToHostMessage.defineBuildCommand(\n                        configuration: command,\n                        inputFiles: inputFiles,\n                        outputFiles: outputFiles\n                    )\n                    try pluginHostConnection.sendMessage(message)\n\n                case .prebuildCommand(let displayName, let executable, let arguments, let environment, let outputFilesDirectory):\n                    let command = PluginToHostMessage.CommandConfiguration(\n                        displayName: displayName,\n                        executable: executable,\n                        arguments: arguments,\n                        environment: environment\n                    )\n                    let message = PluginToHostMessage.definePrebuildCommand(\n                        configuration: command,\n                        outputFilesDirectory: outputFilesDirectory\n                    )\n                    try pluginHostConnection.sendMessage(message)\n                }\n            }\n            \n            // Exit with a zero exit code to indicate success.\n            exit(0)\n\n        case .createXcodeProjectBuildToolCommands(let wireInput, let rootProjectId, let targetId, let generatedSources, let generatedResources):\n            // Instantiate the plugin (for now without parameters, as described\n            // above).\n            let plugin = self.init()\n\n            // Check that the plugin implements the appropriate protocol\n            // for its declared `.buildTool` capability.\n            guard let plugin = plugin as? BuildToolPlugin else {\n                throw PluginDeserializationError.missingBuildToolPluginProtocolConformance(protocolName: \"BuildToolPlugin\")\n            }\n            \n            // Deserialize the context from the wire input structures, and create a record for us to pass to the XcodeProjectPlugin library.\n            let record: XcodeProjectPluginInvocationRecord\n            do {\n                var deserializer = PluginContextDeserializer(wireInput)\n                let xcodeProject = try deserializer.xcodeProject(for: rootProjectId)\n                let xcodeTarget = try deserializer.xcodeTarget(\n                    for: targetId,\n                    pluginGeneratedSources: try generatedSources.map { try deserializer.url(for: $0) },\n                    pluginGeneratedResources: try generatedResources.map { try deserializer.url(for: $0) }\n                )\n                let pluginWorkDirectory = try deserializer.url(for: wireInput.pluginWorkDirId)\n                let toolSearchDirectories = try wireInput.toolSearchDirIds.map {\n                    try deserializer.url(for: $0)\n                }\n                let accessibleTools = try wireInput.accessibleTools.mapValues { (tool: HostToPluginMessage.InputContext.Tool) -> (URL, [String]?) in\n                    let path = try deserializer.url(for: tool.path)\n                    return (path, tool.triples)\n                }\n                record = XcodeProjectPluginInvocationRecord(\n                    plugin: plugin,\n                    xcodeProject: xcodeProject,\n                    xcodeTarget: xcodeTarget,\n                    pluginWorkDirectory: pluginWorkDirectory,\n                    accessibleTools: accessibleTools,\n                    toolSearchDirectories: toolSearchDirectories)\n            }\n            catch {\n                internalError(\"Couldn’t deserialize input from host: \\(error).\")\n            }\n\n            try callEntryPoint(record, \"call_XcodeProjectPlugin_build_command_creation_entry_point\")\n\n            // Send each of the generated commands to the host.\n            for command in record.generatedCommands {\n                switch command {\n\n                case let .buildCommand(name, exec, args, env, inputs, outputs):\n                    let command = PluginToHostMessage.CommandConfiguration(\n                        displayName: name,\n                        executable: exec,\n                        arguments: args,\n                        environment: env,\n                        workingDirectory: nil)\n                    let message = PluginToHostMessage.defineBuildCommand(\n                        configuration: command,\n                        inputFiles: inputs,\n                        outputFiles: outputs)\n                    try pluginHostConnection.sendMessage(message)\n                    \n                case let .prebuildCommand(name, exec, args, env, outdir):\n                    let command = PluginToHostMessage.CommandConfiguration(\n                        displayName: name,\n                        executable: exec,\n                        arguments: args,\n                        environment: env,\n                        workingDirectory: nil)\n                    let message = PluginToHostMessage.definePrebuildCommand(\n                        configuration: command,\n                        outputFilesDirectory: outdir)\n                    try pluginHostConnection.sendMessage(message)\n                }\n            }\n            \n            // Exit with a zero exit code to indicate success.\n            exit(0)\n\n        case .performCommand(let wireInput, let rootPackageId, let arguments):\n            // Deserialize the context from the wire input structures. The root\n            // package is the one we'll set the context's `package` property to.\n            let context: PluginContext\n            do {\n                var deserializer = PluginContextDeserializer(wireInput)\n                let package = try deserializer.package(for: rootPackageId)\n                let pluginWorkDirectory = try deserializer.url(for: wireInput.pluginWorkDirId)\n                let toolSearchDirectories = try wireInput.toolSearchDirIds.map {\n                    try deserializer.url(for: $0)\n                }\n                let accessibleTools = try wireInput.accessibleTools.mapValues { (tool: HostToPluginMessage.InputContext.Tool) -> (URL, [String]?) in\n                    let path = try deserializer.url(for: tool.path)\n                    return (path, tool.triples)\n                }\n                context = try PluginContext(\n                    package: package,\n                    pluginWorkDirectory: Path(url: pluginWorkDirectory),\n                    pluginWorkDirectoryURL: pluginWorkDirectory,\n                    accessibleTools: accessibleTools,\n                    toolSearchDirectories: toolSearchDirectories.map { try Path(url: $0) },\n                    toolSearchDirectoryURLs: toolSearchDirectories)\n            }\n            catch {\n                internalError(\"Couldn’t deserialize input from host: \\(error).\")\n            }\n\n            // Instantiate the plugin (for now without parameters, as described\n            // above).\n            let plugin = self.init()\n\n            // Check that the plugin implements the appropriate protocol\n            // for its declared `.command` capability.\n            guard let plugin = plugin as? CommandPlugin else {\n                throw PluginDeserializationError.missingCommandPluginProtocolConformance(protocolName: \"CommandPlugin\")\n            }\n            \n            // Invoke the plugin to perform its custom logic.\n            try await plugin.performCommand(context: context, arguments: arguments)\n            \n            // Exit with a zero exit code to indicate success.\n            exit(0)\n\n        case .performXcodeProjectCommand(let wireInput, let rootProjectId, let arguments):\n            // Instantiate the plugin (for now without parameters, as described\n            // above).\n            let plugin = self.init()\n\n            // Check that the plugin implements the appropriate protocol\n            // for its declared `.command` capability.\n            guard let plugin = plugin as? CommandPlugin else {\n                throw PluginDeserializationError.missingCommandPluginProtocolConformance(protocolName: \"CommandPlugin\")\n            }\n            \n            // Deserialize the context from the wire input structures, and create a record for us to pass to the XcodeProjectPlugin library.\n            let record: XcodeProjectPluginInvocationRecord\n            do {\n                var deserializer = PluginContextDeserializer(wireInput)\n                let xcodeProject = try deserializer.xcodeProject(for: rootProjectId)\n                let pluginWorkDirectory = try deserializer.url(for: wireInput.pluginWorkDirId)\n                let toolSearchDirectories = try wireInput.toolSearchDirIds.map {\n                    try deserializer.url(for: $0)\n                }\n                let accessibleTools = try wireInput.accessibleTools.mapValues { (tool: HostToPluginMessage.InputContext.Tool) -> (URL, [String]?) in\n                    let path = try deserializer.url(for: tool.path)\n                    return (path, tool.triples)\n                }\n                record = XcodeProjectPluginInvocationRecord(\n                    plugin: plugin,\n                    xcodeProject: xcodeProject,\n                    pluginWorkDirectory: pluginWorkDirectory,\n                    accessibleTools: accessibleTools,\n                    toolSearchDirectories: toolSearchDirectories,\n                    arguments: arguments)\n            }\n            catch {\n                internalError(\"Couldn’t deserialize input from host: \\(error).\")\n            }\n\n            try callEntryPoint(record, \"call_XcodeProjectPlugin_custom_command_entry_point\")\n\n            // Exit with a zero exit code to indicate success.\n            exit(0)\n\n        default:\n            internalError(\"unexpected top-level message \\(message)\")\n        }\n    }\n\n    // Private function to report internal errors and then exit.\n    fileprivate static func internalError(_ message: String) -> Never {\n        fputs(\"Internal Error: \\(message)\", stderr)\n        exit(1)\n    }\n    \n    // Private function to construct an error message from an `errno` code.\n    fileprivate static func describe(errno: Int32) -> String {\n#if os(Windows)\n        return strerror(errno) ?? String(errno)\n#else\n        if let cStr = strerror(errno) { return String(cString: cStr) }\n        return String(describing: errno)\n#endif\n    }\n}\n\n@_spi(PackagePluginInternal) public class XcodeProjectPluginInvocationRecord {\n    public let plugin: Plugin\n    public let xcodeProject: XcodeProject\n    public let xcodeTarget: XcodeTarget?\n    @available(_PackageDescription, introduced: 5.11)\n    public let pluginWorkDirectoryURL: URL\n    @available(_PackageDescription, introduced: 5.11)\n    public let accessibleToolsByURL: [String: (path: URL, triples: [String]?)]\n    @available(_PackageDescription, introduced: 5.11)\n    public let toolSearchDirectoryURLs: [URL]\n    public let arguments: [String]\n    public var generatedCommands: [Command] = []\n\n    @available(_PackageDescription, deprecated: 5.11)\n    public var pluginWorkDirectory: Path {\n        return try! Path(url: self.pluginWorkDirectoryURL)\n    }\n    @available(_PackageDescription, deprecated: 5.11)\n    public var accessibleTools: [String: (path: Path, triples: [String]?)] {\n        var result = [String: (path: Path, triples: [String]?)]()\n        self.accessibleToolsByURL.forEach {\n            result[$0.key] = (try! Path(url: $0.value.path), $0.value.triples)\n        }\n        return result\n    }\n    @available(_PackageDescription, deprecated: 5.11)\n    public var toolSearchDirectories: [Path] {\n        return self.toolSearchDirectoryURLs.map { try! Path(url: $0) }\n    }\n\n    internal init(\n        plugin: Plugin,\n        xcodeProject: XcodeProject,\n        xcodeTarget: XcodeTarget? = .none,\n        pluginWorkDirectory: URL,\n        accessibleTools: [String: (path: URL, triples: [String]?)],\n        toolSearchDirectories: [URL],\n        arguments: [String] = []\n    ) {\n        self.plugin = plugin\n        self.xcodeProject = xcodeProject\n        self.xcodeTarget = xcodeTarget\n        self.pluginWorkDirectoryURL = pluginWorkDirectory\n        self.accessibleToolsByURL = accessibleTools\n        self.toolSearchDirectoryURLs = toolSearchDirectories\n        self.arguments = arguments\n        self.generatedCommands = []\n    }\n    public struct XcodeProject {\n        public var id: String\n        public var displayName: String\n        @available(_PackageDescription, deprecated: 5.11)\n        public var directoryPath: Path {\n            return try! Path(url: directoryPathURL)\n        }\n        @available(_PackageDescription, introduced: 5.11)\n        public var directoryPathURL: URL\n        public var filePaths: PathList\n        public var targets: [XcodeTarget]\n    }\n    public struct XcodeTarget {\n        public var id: String\n        public var displayName: String\n        public var product: Product?\n        public var inputFiles: FileList\n        public struct Product {\n            public var name: String\n            public var kind: Kind\n            public enum Kind {\n                case application\n                case executable\n                case framework\n                case library\n                case other(String)\n            }\n        }\n\n        /// Paths of any sources generated by other plugins that have been applied to the given target before the plugin currently being executed.\n        @available(_PackageDescription, introduced: 5.11)\n        public let pluginGeneratedSources: [URL]\n\n        /// Paths of any resources generated by other plugins that have been applied to the given target before the plugin currently being executed.\n        @available(_PackageDescription, introduced: 5.11)\n        public let pluginGeneratedResources: [URL]\n    }\n}\n\n/// Message channel for bidirectional communication with the plugin host.\ninternal fileprivate(set) var pluginHostConnection: PluginHostConnection!\n\ntypealias PluginHostConnection = MessageConnection<PluginToHostMessage, HostToPluginMessage>\n\ninternal struct MessageConnection<TX,RX> where TX: Encodable, RX: Decodable {\n    let inputStream: FileHandle\n    let outputStream: FileHandle\n\n    func sendMessage(_ message: TX) throws {\n        // Encode the message as JSON.\n        let payload = try JSONEncoder().encode(message)\n        \n        // Write the header (a 64-bit length field in little endian byte order).\n        var count = UInt64(littleEndian: UInt64(payload.count))\n        let header = Swift.withUnsafeBytes(of: &count) { Data($0) }\n        assert(header.count == 8)\n        try outputStream.write(contentsOf: header)\n\n        // Write the payload.\n        try outputStream.write(contentsOf: payload)\n    }\n    \n    func waitForNextMessage() throws -> RX? {\n        // Read the header (a 64-bit length field in little endian byte order).\n        guard let header = try inputStream.read(upToCount: 8) else { return nil }\n        guard header.count == 8 else {\n            throw PluginMessageError.truncatedHeader\n        }\n        \n        // Decode the count.\n        let count = header.withUnsafeBytes{ $0.loadUnaligned(as: UInt64.self).littleEndian }\n        guard count >= 2 else {\n            throw PluginMessageError.invalidPayloadSize\n        }\n\n        // Read the JSON payload.\n        guard let payload = try inputStream.read(upToCount: Int(count)), payload.count == count else {\n            throw PluginMessageError.truncatedPayload\n        }\n\n        // Decode and return the message.\n        return try JSONDecoder().decode(RX.self, from: payload)\n    }\n\n    enum PluginMessageError: Swift.Error {\n        case truncatedHeader\n        case invalidPayloadSize\n        case truncatedPayload\n    }\n}\n\nfileprivate func callEntryPoint(_ record: XcodeProjectPluginInvocationRecord, _ functionName: String) throws {\n    #if !canImport(Darwin)\n    // Workaround for a compiler crash presumably related to Objective-C bridging on non-Darwin platforms (rdar://130826719&136043295)\n    typealias CallerFuncType = @convention(c) (UnsafeRawPointer) -> Any\n    #else\n    typealias CallerFuncType = @convention(c) (UnsafeRawPointer) -> (any Error)?\n    #endif\n\n    // Find the trampoline for the type of custom command (it's expected to be in the add-on library).\n    guard let callerFunc: CallerFuncType = try Library.lookup(Library.open(), functionName) else {\n        throw PluginDeserializationError.missingXcodeProjectPluginSupport\n    }\n\n    // The caller function is expected to take a pointer to a XcodeProjectPluginInvocationRecord. It is expected to return nil on success or an error on failure, as there is no way of throwing form a C function.\n    let recordPtr = UnsafeRawPointer(Unmanaged.passUnretained(record).toOpaque())\n    #if !canImport(Darwin)\n    // Workaround for a compiler crash presumably related to Objective-C bridging on non-Darwin platforms (rdar://130826719&136043295)\n    /*if let error = callerFunc(recordPtr) as! (any Error)? {\n        throw error\n    }*/\n    fatalError(\"FIXME: Compiler crashes when trying to compile a call to callerFunc\")\n    #else\n    if let error = callerFunc(recordPtr) {\n        throw error\n    }\n    #endif\n}\n\nfileprivate enum Library: Sendable {\n    @_alwaysEmitIntoClient\n    public static func open() throws -> LibraryHandle {\n        #if os(Windows)\n        guard let handle = GetModuleHandleW(nil) else {\n            throw LibraryOpenError(message: \"GetModuleHandleW returned \\(GetLastError())\")\n        }\n        return LibraryHandle(rawValue: handle)\n        #else\n        guard let handle = dlopen(nil, RTLD_NOW | RTLD_LOCAL) else {\n            throw LibraryOpenError(message: String(cString: dlerror()!))\n        }\n        return LibraryHandle(rawValue: handle)\n        #endif\n    }\n\n    public static func lookup<T>(_ handle: LibraryHandle, _ symbol: String) -> T? {\n        #if os(Windows)\n        guard let ptr = GetProcAddress(handle.rawValue, symbol) else { return nil }\n        #else\n        guard let ptr = dlsym(handle.rawValue, symbol) else { return nil }\n        #endif\n        return unsafeBitCast(ptr, to: T.self)\n    }\n}\n\nfileprivate struct LibraryOpenError: Error, CustomStringConvertible, Sendable {\n    public let message: String\n\n    public var description: String {\n        message\n    }\n\n    @usableFromInline\n    internal init(message: String) {\n        self.message = message\n    }\n}\n\nfileprivate struct LibraryHandle: @unchecked Sendable {\n    #if os(Windows)\n    @usableFromInline typealias PlatformHandle = HMODULE\n    #else\n    @usableFromInline typealias PlatformHandle = UnsafeMutableRawPointer\n    #endif\n\n    fileprivate let rawValue: PlatformHandle\n\n    @usableFromInline\n    internal init(rawValue: PlatformHandle) {\n        self.rawValue = rawValue\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/PluginContextDeserializer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\ntypealias WireInput = HostToPluginMessage.InputContext\n\n/// Deserializer for constructing a plugin input from the wire representation\n/// received from SwiftPM, which consists of a set of flat lists of entities,\n/// referenced by array index in all cross-references. The deserialized data\n/// structure forms a directed acyclic graph. This information is provided to\n/// the plugin in the `PluginContext` struct.\ninternal struct PluginContextDeserializer {\n    let wireInput: WireInput\n    var urlsById: [WireInput.URL.Id: URL] = [:]\n    var packagesById: [WireInput.Package.Id: Package] = [:]\n    var productsById: [WireInput.Product.Id: Product] = [:]\n    var targetsById: [WireInput.Target.Id: Target] = [:]\n    var xcodeProjectsById: [WireInput.XcodeProject.Id: XcodeProjectPluginInvocationRecord.XcodeProject] = [:]\n    var xcodeTargetsById: [WireInput.XcodeTarget.Id: XcodeProjectPluginInvocationRecord.XcodeTarget] = [:]\n    \n    /// Initializes the deserializer with the given wire input.\n    init(_ input: WireInput) {\n        self.wireInput = input\n    }\n    \n    /// Returns the `URL` that corresponds to the given ID (a small integer),\n    /// or throws an error if the ID is invalid. The URL is deserialized on-\n    /// demand if it hasn't already been deserialized.\n    mutating func url(for id: WireInput.URL.Id) throws -> URL {\n        if let path = urlsById[id] { return path }\n        guard id < wireInput.paths.count else {\n            throw PluginDeserializationError.malformedInputJSON(\"invalid URL id (\\(id))\")\n        }\n        \n        // Compose a path based on an optional base path and a subpath.\n        let wirePath = wireInput.paths[id]\n        let basePath = try wireInput.paths[id].baseURLId.map{ try self.url(for: $0) }\n        let path: URL\n        if let basePath {\n            path = basePath.appendingPathComponent(wirePath.subpath)\n        } else {\n            #if os(Windows)\n            // Windows does not have a single root path like UNIX, if this component has no base path, it IS the root and should not be joined with anything\n            path = URL(fileURLWithPath: wirePath.subpath)\n            #else\n            path = URL(fileURLWithPath: \"/\").appendingPathComponent(wirePath.subpath)\n            #endif\n        }\n\n        // Store it for the next look up.\n        urlsById[id] = path\n        return path\n    }\n\n    /// Returns the `Target` that corresponds to the given ID (a small integer),\n    /// or throws an error if the ID is invalid. The module is deserialized on-\n    /// demand if it hasn't already been deserialized.\n    mutating func target(for id: WireInput.Target.Id, pluginGeneratedSources: [URL] = [], pluginGeneratedResources: [URL] = []) throws -> Target {\n        if let target = targetsById[id],\n           target.sourceModule?.pluginGeneratedSources.count == pluginGeneratedSources.count,\n           target.sourceModule?.pluginGeneratedResources.count == pluginGeneratedResources.count {\n            return target\n        }\n        guard id < wireInput.targets.count else {\n            throw PluginDeserializationError.malformedInputJSON(\"invalid target id (\\(id))\")\n        }\n\n        let wireTarget = wireInput.targets[id]\n        let dependencies: [TargetDependency] = try wireTarget.dependencies.map {\n            switch $0 {\n            case .target(let targetId):\n                let target = try self.target(for: targetId)\n                return .target(target)\n            case .product(let productId):\n                let product = try self.product(for: productId)\n                return .product(product)\n            }\n        }\n        let directory = try self.url(for: wireTarget.directoryId)\n        let target: Target\n        switch wireTarget.info {\n        \n        case let .swiftSourceModuleInfo(moduleName, kind, sourceFiles, compilationConditions, linkedLibraries, linkedFrameworks):\n            let sourceFiles = FileList(try sourceFiles.map {\n                let path = try self.url(for: $0.basePathId).appendingPathComponent($0.name)\n                let type: FileType\n                switch $0.type {\n                case .source:\n                    type = .source\n                case .header:\n                    type = .header\n                case .resource:\n                    type = .resource\n                case .unknown:\n                    type = .unknown\n                }\n                return File(url: path, type: type)\n            })\n            target = try SwiftSourceModuleTarget(\n                id: String(id),\n                name: wireTarget.name,\n                kind: .init(kind),\n                directory: Path(url: directory),\n                directoryURL: directory,\n                dependencies: dependencies,\n                moduleName: moduleName,\n                sourceFiles: sourceFiles,\n                compilationConditions: compilationConditions,\n                linkedLibraries: linkedLibraries,\n                linkedFrameworks: linkedFrameworks,\n                pluginGeneratedSources: pluginGeneratedSources,\n                pluginGeneratedResources: pluginGeneratedResources\n            )\n\n        case let .clangSourceModuleInfo(moduleName, kind, sourceFiles, preprocessorDefinitions, headerSearchPaths, publicHeadersDirId, linkedLibraries, linkedFrameworks):\n            let publicHeadersDir = try publicHeadersDirId.map { try self.url(for: $0) }\n            let sourceFiles = FileList(try sourceFiles.map {\n                let path = try self.url(for: $0.basePathId).appendingPathComponent($0.name)\n                let type: FileType\n                switch $0.type {\n                case .source:\n                    type = .source\n                case .header:\n                    type = .header\n                case .resource:\n                    type = .resource\n                case .unknown:\n                    type = .unknown\n                }\n                return File(url: path, type: type)\n            })\n            target = try ClangSourceModuleTarget(\n                id: String(id),\n                name: wireTarget.name,\n                kind: .init(kind),\n                directory: Path(url: directory),\n                directoryURL: directory,\n                dependencies: dependencies,\n                moduleName: moduleName,\n                sourceFiles: sourceFiles,\n                preprocessorDefinitions: preprocessorDefinitions,\n                headerSearchPaths: headerSearchPaths,\n                publicHeadersDirectory: publicHeadersDir.map { try .init(url: $0) },\n                publicHeadersDirectoryURL: publicHeadersDir,\n                linkedLibraries: linkedLibraries,\n                linkedFrameworks: linkedFrameworks,\n                pluginGeneratedSources: pluginGeneratedSources,\n                pluginGeneratedResources: pluginGeneratedResources\n            )\n\n        case let .binaryArtifactInfo(kind, origin, artifactId):\n            let artifact = try self.url(for: artifactId)\n            let artifactKind: BinaryArtifactTarget.Kind\n            switch kind {\n            case .artifactsArchive:\n                artifactKind = .artifactsArchive\n            case .xcframework:\n                artifactKind = .xcframework\n            }\n            let artifactOrigin: BinaryArtifactTarget.Origin\n            switch origin {\n            case .local:\n                artifactOrigin = .local\n            case .remote(let url):\n                artifactOrigin = .remote(url: url)\n            }\n            target = try BinaryArtifactTarget(\n                id: String(id),\n                name: wireTarget.name,\n                directory: Path(url: directory),\n                directoryURL: directory,\n                dependencies: dependencies,\n                kind: artifactKind,\n                origin: artifactOrigin,\n                artifact: Path(url: artifact),\n                artifactURL: artifact)\n\n        case let .systemLibraryInfo(pkgConfig, compilerFlags, linkerFlags):\n            target = try SystemLibraryTarget(\n                id: String(id),\n                name: wireTarget.name,\n                directory: Path(url: directory),\n                directoryURL: directory,\n                dependencies: dependencies,\n                pkgConfig: pkgConfig,\n                compilerFlags: compilerFlags,\n                linkerFlags: linkerFlags)\n        }\n        \n        targetsById[id] = target\n        return target\n    }\n\n    /// Returns the `Product` that corresponds to the given ID (a small integer),\n    /// or throws an error if the ID is invalid. The product is deserialized on-\n    /// demand if it hasn't already been deserialized.\n    mutating func product(for id: WireInput.Product.Id) throws -> Product {\n        if let product = productsById[id] { return product }\n        guard id < wireInput.products.count else {\n            throw PluginDeserializationError.malformedInputJSON(\"invalid product id (\\(id))\")\n        }\n\n        let wireProduct = wireInput.products[id]\n        let targets: [Target] = try wireProduct.targetIds.map{ try self.target(for: $0) }\n        let product: Product\n        switch wireProduct.info {\n\n        case .executable(let mainTargetId):\n            let mainTarget = try self.target(for: mainTargetId)\n            product = ExecutableProduct(\n                id: String(id),\n                name: wireProduct.name,\n                targets: targets,\n                mainTarget: mainTarget)\n\n        case .library(let type):\n            let libraryKind: LibraryProduct.Kind\n            switch type {\n            case .static:\n                libraryKind = .static\n            case .dynamic:\n                libraryKind = .dynamic\n            case .automatic:\n                libraryKind = .automatic\n            }\n            product = LibraryProduct(\n                id: String(id),\n                name: wireProduct.name,\n                targets: targets,\n                kind: libraryKind)\n        }\n        \n        productsById[id] = product\n        return product\n    }\n\n    /// Returns the `Package` that corresponds to the given ID (a small integer),\n    /// or throws an error if the ID is invalid. The package is deserialized on-\n    /// demand if it hasn't already been deserialized.\n    mutating func package(for id: WireInput.Product.Id) throws -> Package {\n        if let package = packagesById[id] { return package }\n        guard id < wireInput.packages.count else {\n            throw PluginDeserializationError.malformedInputJSON(\"invalid package id (\\(id))\") }\n        \n        let wirePackage = wireInput.packages[id]\n        let directory = try self.url(for: wirePackage.directoryId)\n        let toolsVersion = ToolsVersion(\n            major: wirePackage.toolsVersion.major,\n            minor: wirePackage.toolsVersion.minor,\n            patch: wirePackage.toolsVersion.patch)\n        let dependencies: [PackageDependency] = try wirePackage.dependencies.map {\n            .init(package: try self.package(for: $0.packageId))\n        }\n        let products = try wirePackage.productIds.map { try self.product(for: $0) }\n        let targets = try wirePackage.targetIds.map { try self.target(for: $0) }\n        let origin: PackageOrigin = switch wirePackage.origin {\n            case .root:\n                .root\n            case .local(let pathId):\n                try .local(path: url(for: pathId).path)\n            case .repository(let url, let displayVersion, let scmRevision):\n                .repository(url: url, displayVersion: displayVersion, scmRevision: scmRevision)\n            case .registry(let identity, let displayVersion):\n                .registry(identity: identity, displayVersion: displayVersion)\n        }\n        let package = try Package(\n            id: wirePackage.identity,\n            displayName: wirePackage.displayName,\n            directory: Path(url: directory),\n            directoryURL: directory,\n            origin:  origin,\n            toolsVersion: toolsVersion,\n            dependencies: dependencies,\n            products: products,\n            targets: targets)\n        \n        packagesById[id] = package\n        return package\n    }\n\n    /// Returns the `XcodeTarget` that corresponds to the given ID (a small integer),\n    /// or throws an error if the ID is invalid. The product is deserialized on-\n    /// demand if it hasn't already been deserialized.\n    mutating func xcodeTarget(for id: WireInput.XcodeTarget.Id, pluginGeneratedSources: [URL] = [], pluginGeneratedResources: [URL] = []) throws -> XcodeProjectPluginInvocationRecord.XcodeTarget {\n        if let xcodeTarget = xcodeTargetsById[id],\n           xcodeTarget.pluginGeneratedSources.count == pluginGeneratedSources.count,\n           xcodeTarget.pluginGeneratedResources.count == pluginGeneratedResources.count {\n            return xcodeTarget\n        }\n        guard id < wireInput.xcodeTargets.count else {\n            throw PluginDeserializationError.malformedInputJSON(\"invalid Xcode target id (\\(id))\")\n        }\n\n        let wireXcodeTarget = wireInput.xcodeTargets[id]\n        let product: XcodeProjectPluginInvocationRecord.XcodeTarget.Product? = wireXcodeTarget.product.map {\n            let kind: XcodeProjectPluginInvocationRecord.XcodeTarget.Product.Kind\n            switch $0.kind {\n            case .application:\n                kind = .application\n            case .executable:\n                kind = .executable\n            case .framework:\n                kind = .framework\n            case .library:\n                kind = .library\n            case .other(let ident):\n                kind = .other(ident)\n            }\n            return .init(name: $0.name, kind: kind)\n        }\n        let inputFiles = FileList(try wireXcodeTarget.inputFiles.map {\n            let path = try self.url(for: $0.basePathId).appendingPathComponent($0.name)\n            let type: FileType\n            switch $0.type {\n            case .source:\n                type = .source\n            case .header:\n                type = .header\n            case .resource:\n                type = .resource\n            case .unknown:\n                type = .unknown\n            }\n            return .init(url: path, type: type)\n        })\n        let xcodeTarget = XcodeProjectPluginInvocationRecord.XcodeTarget(\n            id: String(id),\n            displayName: wireXcodeTarget.displayName,\n            product: product,\n            inputFiles: inputFiles,\n            pluginGeneratedSources: pluginGeneratedSources,\n            pluginGeneratedResources: pluginGeneratedResources\n        )\n\n        xcodeTargetsById[id] = xcodeTarget\n        return xcodeTarget\n    }\n\n    /// Returns the `Package` that corresponds to the given ID (a small integer),\n    /// or throws an error if the ID is invalid. The package is deserialized on-\n    /// demand if it hasn't already been deserialized.\n    mutating func xcodeProject(for id: WireInput.XcodeProject.Id) throws -> XcodeProjectPluginInvocationRecord.XcodeProject {\n        if let xcodeProject = xcodeProjectsById[id] { return xcodeProject }\n        guard id < wireInput.xcodeProjects.count else {\n            throw PluginDeserializationError.malformedInputJSON(\"invalid Xcode project id (\\(id))\") }\n        \n        let wireXcodeProject = wireInput.xcodeProjects[id]\n        let directoryPath = try self.url(for: wireXcodeProject.directoryPathId)\n        let filePaths = PathList(try wireXcodeProject.urlIds.map{ try self.url(for: $0) })\n        let targets = try wireXcodeProject.targetIds.map { try self.xcodeTarget(for: $0) }\n        let xcodeProject = XcodeProjectPluginInvocationRecord.XcodeProject(\n            id: String(id),\n            displayName: wireXcodeProject.displayName,\n            directoryPathURL: directoryPath,\n            filePaths: filePaths,\n            targets: targets)\n        \n        xcodeProjectsById[id] = xcodeProject\n        return xcodeProject\n    }\n}\n\nfileprivate extension ModuleKind {\n    init(_ kind: WireInput.Target.TargetInfo.SourceModuleKind) {\n        switch kind {\n        case .generic:\n            self = .generic\n        case .executable:\n            self = .executable\n        case .snippet:\n            self = .snippet\n        case .test:\n            self = .test\n        case .macro:\n            self = .macro\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/PluginMessages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// A message that the host can send to the plugin, including definitions of the corresponding serializable data structures.\nenum HostToPluginMessage: Codable {\n    \n    /// The host requests that the plugin create build commands (corresponding to a `.buildTool` capability) for a target in the package graph.\n    case createBuildToolCommands(\n        context: InputContext,\n        rootPackageId: InputContext.Package.Id,\n        targetId: InputContext.Target.Id,\n        pluginGeneratedSources: [InputContext.URL.Id],\n        pluginGeneratedResources: [InputContext.URL.Id]\n    )\n\n    /// The host requests that the plugin create build commands (corresponding to a `.buildTool` capability) for a target in the package graph.\n    case createXcodeProjectBuildToolCommands(\n        context: InputContext,\n        rootProjectId: InputContext.XcodeProject.Id,\n        targetId: InputContext.XcodeTarget.Id,\n        pluginGeneratedSources: [InputContext.URL.Id],\n        pluginGeneratedResources: [InputContext.URL.Id]\n    )\n\n    /// The host requests that the plugin perform a user command (corresponding to a `.command` capability) on a package in the graph.\n    case performCommand(context: InputContext, rootPackageId: InputContext.Package.Id, arguments: [String])\n\n    /// The host requests that the plugin perform a user command (corresponding to a `.command` capability) on a package in the graph.\n    case performXcodeProjectCommand(context: InputContext, rootProjectId: InputContext.XcodeProject.Id, arguments: [String])\n\n        struct InputContext: Codable {\n            let paths: [URL]\n            let targets: [Target]\n            let products: [Product]\n            let packages: [Package]\n            let xcodeTargets: [XcodeTarget]\n            let xcodeProjects: [XcodeProject]\n            let pluginWorkDirId: URL.Id\n            let toolSearchDirIds: [URL.Id]\n            let accessibleTools: [String: Tool]\n\n            // Wrapper struct for encoding information about a tool that's accessible to the plugin.\n            struct Tool: Codable {\n                let path: URL.Id\n                let triples: [String]?\n            }\n\n            /// A single absolute path in the wire structure, represented as a tuple\n            /// consisting of the ID of the base path and subpath off of that path.\n            /// This avoids repetition of path components in the wire representation.\n            struct URL: Codable {\n                typealias Id = Int\n                let baseURLId: URL.Id?\n                let subpath: String\n            }\n\n            /// A package in the wire structure. All references to other entities are\n            /// their ID numbers.\n            struct Package: Codable {\n                typealias Id = Int\n                let identity: String\n                let displayName: String\n                let directoryId: URL.Id\n                let origin: Origin\n                let toolsVersion: ToolsVersion\n                let dependencies: [Dependency]\n                let productIds: [Product.Id]\n                let targetIds: [Target.Id]\n\n                enum Origin: Codable {\n                    case root\n                    case local(\n                        path: URL.Id)\n                    case repository(\n                        url: String,\n                        displayVersion: String,\n                        scmRevision: String)\n                    case registry(\n                        identity: String,\n                        displayVersion: String)\n                }\n                \n                struct ToolsVersion: Codable {\n                    let major: Int\n                    let minor: Int\n                    let patch: Int\n                }\n\n                /// A dependency on a package in the wire structure. All references to\n                /// other entities are ID numbers.\n                struct Dependency: Codable {\n                    let packageId: Package.Id\n                }\n            }\n\n            /// A product in the wire structure. All references to other entities are\n            /// their ID numbers.\n            struct Product: Codable {\n                typealias Id = Int\n                let name: String\n                let targetIds: [Target.Id]\n                let info: ProductInfo\n\n                /// Information for each type of product in the wire structure. All\n                /// references to other entities are their ID numbers.\n                enum ProductInfo: Codable {\n                    case executable(\n                        mainTargetId: Target.Id)\n                    case library(\n                        kind: LibraryKind)\n\n                    enum LibraryKind: Codable {\n                        case `static`\n                        case `dynamic`\n                        case automatic\n                    }\n                }\n            }\n\n            /// A target in the wire structure. All references to other entities are\n            /// their ID numbers.\n            struct Target: Codable {\n                typealias Id = Int\n                let name: String\n                let directoryId: URL.Id\n                let dependencies: [Dependency]\n                let info: TargetInfo\n\n                /// A dependency on either a target or a product in the wire structure.\n                /// All references to other entities are ID their numbers.\n                enum Dependency: Codable {\n                    case target(\n                        targetId: Target.Id)\n                    case product(\n                        productId: Product.Id)\n                }\n                \n                /// Type-specific information for a target in the wire structure. All\n                /// references to other entities are their ID numbers.\n                enum TargetInfo: Codable {\n                    case swiftSourceModuleInfo(\n                        moduleName: String,\n                        kind: SourceModuleKind,\n                        sourceFiles: [File],\n                        compilationConditions: [String],\n                        linkedLibraries: [String],\n                        linkedFrameworks: [String])\n                    \n                    case clangSourceModuleInfo(\n                        moduleName: String,\n                        kind: SourceModuleKind,\n                        sourceFiles: [File],\n                        preprocessorDefinitions: [String],\n                        headerSearchPaths: [String],\n                        publicHeadersDirId: URL.Id?,\n                        linkedLibraries: [String],\n                        linkedFrameworks: [String])\n                    \n                    case binaryArtifactInfo(\n                        kind: BinaryArtifactKind,\n                        origin: BinaryArtifactOrigin,\n                        artifactId: URL.Id)\n\n                    case systemLibraryInfo(\n                        pkgConfig: String?,\n                        compilerFlags: [String],\n                        linkerFlags: [String])\n\n                    enum SourceModuleKind: String, Codable {\n                        case generic\n                        case executable\n                        case snippet\n                        case test\n                        case macro\n                    }\n\n                    enum BinaryArtifactKind: Codable {\n                        case xcframework\n                        case artifactsArchive\n                    }\n\n                    enum BinaryArtifactOrigin: Codable {\n                        case local\n                        case remote(url: String)\n                    }\n                }\n            }\n            \n            /// A typed file in the wire structure. All references to other entities are\n            /// their ID numbers.\n            struct File: Codable {\n                let basePathId: URL.Id\n                let name: String\n                let type: FileType\n\n                enum FileType: String, Codable {\n                    case source\n                    case header\n                    case resource\n                    case unknown\n                }\n            }\n\n            /// An Xcode project in the wire structure. All references to other entities are their ID numbers.\n            struct XcodeProject: Codable {\n                typealias Id = Int\n                let displayName: String\n                let directoryPathId: URL.Id\n                let dependencies: [Dependency]\n                let urlIds: [URL.Id]\n                let targetIds: [XcodeTarget.Id]\n\n                /// A dependency on a package or project in the wire structure. All references to\n                /// other entities are ID numbers.\n                enum Dependency: Codable {\n                    case package(Package.Id)\n                    case xcodeProject(XcodeProject.Id)\n                }\n            }\n\n            /// A target in the wire structure. All references to other entities are\n            /// their ID numbers.\n            struct XcodeTarget: Codable {\n                typealias Id = Int\n                let displayName: String\n                let product: XcodeProduct?\n                let dependencies: [Dependency]\n                let inputFiles: [File]\n\n                /// A product in the wire structure.\n                struct XcodeProduct: Codable {\n                    let name: String\n                    let kind: Kind\n                    public enum Kind: Codable {\n                        case application\n                        case executable\n                        case framework\n                        case library\n                        case other(String)\n                    }\n                }\n\n                /// A dependency on either a target or a product in the wire structure.\n                /// All references to other entities are ID their numbers.\n                enum Dependency: Codable {\n                    case target(\n                        targetId: XcodeTarget.Id)\n                    case product(\n                        productId: Product.Id)\n                }\n            }\n        }\n    \n    /// A response to a request to run a build operation.\n    case buildOperationResponse(result: BuildResult)\n\n        struct BuildResult: Codable {\n            var succeeded: Bool\n            var logText: String\n            var builtArtifacts: [BuiltArtifact]\n            \n            struct BuiltArtifact: Codable {\n                var path: URL\n                var kind: Kind\n                \n                enum Kind: String, Codable {\n                    case executable\n                    case dynamicLibrary\n                    case staticLibrary\n                }\n            }\n        }\n\n    /// A response to a request to run a test operation.\n    case testOperationResponse(result: TestResult)\n\n        struct TestResult: Codable {\n            var succeeded: Bool\n            var testTargets: [TestTarget]\n            var codeCoverageDataFile: String?\n\n            struct TestTarget: Codable {\n                var name: String\n                var testCases: [TestCase]\n                \n                struct TestCase: Codable {\n                    var name: String\n                    var tests: [Test]\n                                       \n                    struct Test: Codable {\n                        var name: String\n                        var result: Result\n                        var duration: Double\n                        \n                        enum Result: String, Codable {\n                            case succeeded\n                            case skipped\n                            case failed\n                        }\n                    }\n                }\n            }\n        }\n    \n    /// A response to a request for symbol graph information for a target.\n    case symbolGraphResponse(result: SymbolGraphResult)\n    \n        struct SymbolGraphResult: Codable {\n            var directoryPath: URL\n        }\n    \n    /// A response of an error while trying to complete a request.\n    case errorResponse(error: String)\n}\n\n\n/// A message that the plugin can send to the host.\nenum PluginToHostMessage: Codable {\n    \n    /// The plugin emits a diagnostic.\n    case emitDiagnostic(severity: DiagnosticSeverity, message: String, file: String?, line: Int?)\n\n        enum DiagnosticSeverity: String, Codable {\n            case error, warning, remark\n        }\n\n    /// The plugin emits a progress message.\n    case emitProgress(message: String)\n\n    /// The plugin defines a build command.\n    case defineBuildCommand(configuration: CommandConfiguration, inputFiles: [URL], outputFiles: [URL])\n\n    /// The plugin defines a prebuild command.\n    case definePrebuildCommand(configuration: CommandConfiguration, outputFilesDirectory: URL)\n    \n        struct CommandConfiguration: Codable {\n            var version = 2\n            var displayName: String?\n            var executable: URL\n            var arguments: [String]\n            var environment: [String: String]\n            var workingDirectory: URL?\n        }\n    \n    /// The plugin is requesting that a build operation be run.\n    case buildOperationRequest(subset: BuildSubset, parameters: BuildParameters)\n    \n        enum BuildSubset: Codable {\n            case all(includingTests: Bool)\n            case product(String)\n            case target(String)\n        }\n\n        struct BuildParameters: Codable {\n            var configuration: Configuration\n            enum Configuration: String, Codable {\n                case debug, release, inherit\n            }\n            var logging: LogVerbosity\n            enum LogVerbosity: String, Codable {\n                case concise, verbose, debug\n            }\n            var echoLogs: Bool\n            var otherCFlags: [String]\n            var otherCxxFlags: [String]\n            var otherSwiftcFlags: [String]\n            var otherLinkerFlags: [String]\n        }\n\n    /// The plugin is requesting that a test operation be run.\n    case testOperationRequest(subset: TestSubset, parameters: TestParameters)\n\n        enum TestSubset: Codable {\n            case all\n            case filtered([String])\n        }\n\n        struct TestParameters: Codable {\n            var enableCodeCoverage: Bool\n        }\n\n    /// The plugin is requesting symbol graph information for a given target and set of options.\n    case symbolGraphRequest(targetName: String, options: SymbolGraphOptions)\n\n        struct SymbolGraphOptions: Codable {\n            var minimumAccessLevel: AccessLevel\n            enum AccessLevel: String, Codable {\n                case `private`, `fileprivate`, `internal`, `package`, `public`, `open`\n            }\n            var includeInheritedDocs: Bool? = true\n            var includeSynthesized: Bool\n            var includeSPI: Bool\n            var emitExtensionBlocks: Bool\n        }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Protocols.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// A future improvement to the package manager would be to allow use of\n// a plugin to also provide configuration parameters for that plugin.\n// Any proposal that adds such a facility should also add initializers\n// to set those values as plugin properties.\n\n/// A protocol that defines functionality common to all package manger plugins.\n///\n/// For example, the way to instantiate and run a plugin.\npublic protocol Plugin {\n\n\n    /// Instantiates the plugin.\n    ///\n    /// This happens once per invocation of the plugin.\n    /// There is no facility for keeping in-memory state from one invocation to the next.\n    /// Most plugins do not need to implement the initializer.\n    init()\n}\n\n/// The plugin protocol that defines functionality for all plugins having a buildTool capability.\npublic protocol BuildToolPlugin: Plugin {\n    /// Invoked by the package manager to create build commands for a particular target.\n    ///\n    /// The context parameter contains information about the package and its\n    /// dependencies, as well as other environmental inputs.\n    ///\n    /// This function should create and return build commands or prebuild\n    /// commands, configured based on the information in the context. Note\n    /// that the plugin does not directly run those commands.\n    func createBuildCommands(\n        context: PluginContext,\n        target: Target\n    ) async throws -> [Command]\n}\n\n/// The plugin protocol that defines functionality for all plugins that have a command capability.\npublic protocol CommandPlugin: Plugin {\n    /// Invoked by the package manager to perform the custom actions of the command.\n    func performCommand(\n        /// The context in which the plugin is invoked.\n        ///\n        /// This is the same for all kinds of plugins, and provides access to the package graph,\n        /// to cache directories, and so on.\n        context: PluginContext,\n        \n        /// Any literal arguments passed after the verb in the command invocation.\n        arguments: [String]\n    ) async throws\n\n    /// A proxy to the Swift Package Manager or IDE hosting the command plugin,\n    /// through which the plugin can ask for specialized information or actions.\n    var packageManager: PackageManager { get }\n}\n\nextension CommandPlugin {    \n    /// A proxy to the Swift Package Manager or IDE hosting the command plugin,\n    /// through which the plugin can ask for specialized information or actions.\n    public var packageManager: PackageManager {\n        return PackageManager()\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/PackagePlugin/Utilities.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension Package {\n    /// The list of targets matching the given names.\n    ///\n    /// Throws an error if any of the targets cannot be found.\n    public func targets(named targetNames: [String]) throws -> [Target] {\n        return try targetNames.map { name in\n            guard let target = self.targets.first(where: { $0.name == name }) else {\n                throw PluginContextError.targetNotFound(name: name, package: self)\n            }\n            return target\n        }\n    }\n\n    /// The list of products matching the given names.\n    ///\n    /// Throws an error if any of the products cannot be found.\n    public func products(named productNames: [String]) throws -> [Product] {\n        return try productNames.map { name in\n            guard let product = self.products.first(where: { $0.name == name }) else {\n                throw PluginContextError.productNotFound(name: name, package: self)\n            }\n            return product\n        }\n    }\n\n    @available(_PackageDescription, introduced: 5.9)\n    public var sourceModules: [SourceModuleTarget] {\n        return targets.compactMap { $0.sourceModule }\n    }\n}\n\nextension Product {\n    @available(_PackageDescription, introduced: 5.9)\n    public var sourceModules: [SourceModuleTarget] {\n        return targets.compactMap { $0.sourceModule }\n    }\n}\n\nextension Target {\n    /// The transitive closure of all the targets on which the receiver depends.\n    ///\n    /// Package manager orders the results such that every dependency appears before any other target that\n    /// depends on it.\n    ///\n    /// The dependencies are sorted in topological sort order.\n    public var recursiveTargetDependencies: [Target] {\n        // FIXME: We can rewrite this to use a stack instead of recursion.\n        var visited = Set<Target.ID>()\n        func dependencyClosure(for target: Target) -> [Target] {\n            guard visited.insert(target.id).inserted else { return [] }\n            return target.dependencies.flatMap{ dependencyClosure(for: $0) } + [target]\n        }\n        func dependencyClosure(for dependency: TargetDependency) -> [Target] {\n            switch dependency {\n            case .target(let target):\n                return dependencyClosure(for: target)\n            case .product(let product):\n                return product.targets.flatMap{ dependencyClosure(for: $0) }\n            }\n        }\n        return self.dependencies.flatMap{ dependencyClosure(for: $0) }\n    }\n\n    /// Convenience accessor which casts the receiver to`SourceModuleTarget`, if possible.\n    @available(_PackageDescription, introduced: 5.9)\n    public var sourceModule: SourceModuleTarget? {\n        return self as? SourceModuleTarget\n    }\n}\n\nextension Package {\n    /// The products in this package that conform to a specific type.\n    public func products<T: Product>(ofType: T.Type) -> [T] {\n        return self.products.compactMap { $0 as? T }\n    }\n\n    /// The targets in this package that conform to a specific type.\n    public func targets<T: Target>(ofType: T.Type) -> [T] {\n        return self.targets.compactMap { $0 as? T }\n    }\n}\n\nextension SourceModuleTarget {\n    /// A possibly empty list of source files in the target that have the given\n    /// filename suffix.\n    public func sourceFiles(withSuffix suffix: String) -> FileList {\n        return FileList(self.sourceFiles.filter{ $0.url.lastPathComponent.hasSuffix(suffix) })\n    }\n}\n"
  },
  {
    "path": "Sources/Runtimes/cmake/modules/EmitSwiftInterface.cmake",
    "content": "##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2025 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\n# Generate and install swift interface files\n\n# TODO: CMake should learn how to model library evolution and generate this\n#       stuff automatically.\n\n\n# Generate a swift interface file for the target if library evolution is enabled\nfunction(emit_swift_interface target)\n  # Generate the target-variant binary swift module when performing zippered\n  # build\n  # Clean this up once CMake has nested swiftmodules in the build directory:\n  # https://gitlab.kitware.com/cmake/cmake/-/merge_requests/10664\n  # https://cmake.org/cmake/help/git-stage/policy/CMP0195.html\n\n  # We can't expand the Swift_MODULE_NAME target property in a generator\n  # expression or it will fail saying that the target doesn't exist.\n  get_target_property(module_name ${target} Swift_MODULE_NAME)\n  if(NOT module_name)\n    set(module_name ${target})\n  endif()\n  # Account for an existing swiftmodule file\n  # generated with the previous logic\n  if(EXISTS \"${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule\"\n     AND NOT IS_DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule\")\n    message(STATUS \"Removing regular file ${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule to support nested swiftmodule generation\")\n    file(REMOVE \"${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule\")\n  endif()\n  target_compile_options(${target} PRIVATE\n    \"$<$<COMPILE_LANGUAGE:Swift>:SHELL:-emit-module-path ${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule/${${PROJECT_NAME}_MODULE_TRIPLE}.swiftmodule>\")\n  if(${PROJECT_NAME}_VARIANT_MODULE_TRIPLE)\n    target_compile_options(${target} PRIVATE\n      \"$<$<COMPILE_LANGUAGE:Swift>:SHELL:-emit-variant-module-path ${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule/${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.swiftmodule>\")\n  endif()\n  add_custom_command(OUTPUT \"${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule/${${PROJECT_NAME}_MODULE_TRIPLE}.swiftmodule\"\n    DEPENDS ${target})\n  target_sources(${target}\n    INTERFACE\n      $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule/${${PROJECT_NAME}_MODULE_TRIPLE}.swiftmodule>)\n\n  # Generate textual swift interfaces is library-evolution is enabled\n  if(${PROJECT_NAME}_ENABLE_LIBRARY_EVOLUTION)\n    target_compile_options(${target} PRIVATE\n      $<$<COMPILE_LANGUAGE:Swift>:-emit-module-interface-path$<SEMICOLON>${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule/${${PROJECT_NAME}_MODULE_TRIPLE}.swiftinterface>\n      $<$<COMPILE_LANGUAGE:Swift>:-emit-private-module-interface-path$<SEMICOLON>${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule/${${PROJECT_NAME}_MODULE_TRIPLE}.private.swiftinterface>)\n    if(${PROJECT_NAME}_VARIANT_MODULE_TRIPLE)\n      target_compile_options(${target} PRIVATE\n        \"$<$<COMPILE_LANGUAGE:Swift>:SHELL:-emit-variant-module-interface-path ${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule/${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.swiftinterface>\"\n        \"$<$<COMPILE_LANGUAGE:Swift>:SHELL:-emit-variant-private-module-interface-path ${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule/${${PROJECT_NAME}_VARIANT_MODULE_TRIPLE}.private.swiftinterface>\")\n    endif()\n  endif()\nendfunction()\n"
  },
  {
    "path": "Sources/Runtimes/cmake/modules/InstallSwiftInterface.cmake",
    "content": "##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2025 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\n# Install the generated swift interface files for the target.\nfunction(install_swift_interface target)\n  # Swiftmodules are already in the directory structure\n  get_target_property(module_name ${target} Swift_MODULE_NAME)\n  if(NOT module_name)\n    set(module_name ${target})\n  endif()\n\n  install(DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/${module_name}.swiftmodule\"\n    DESTINATION \"${${PROJECT_NAME}_INSTALL_SWIFTMODULEDIR}\"\n    COMPONENT ${PROJECT_NAME}_development)\nendfunction()\n"
  },
  {
    "path": "Sources/Runtimes/cmake/modules/PlatformInfo.cmake",
    "content": "##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2025 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\ninclude_guard(GLOBAL)\n\nif(NOT ${PROJECT_NAME}_SIZEOF_POINTER)\n  set(${PROJECT_NAME}_SIZEOF_POINTER \"${CMAKE_SIZEOF_VOID_P}\" CACHE STRING \"Size of a pointer in bytes\")\n  message(CONFIGURE_LOG \"Stdlib Pointer size: ${CMAKE_SIZEOF_VOID_P}\")\n  mark_as_advanced(${PROJECT_NAME}_SIZEOF_POINTER)\nendif()\n\n# TODO: This logic should migrate to CMake once CMake supports installing swiftmodules\nset(module_triple_command \"${CMAKE_Swift_COMPILER}\" -print-target-info)\nif(CMAKE_Swift_COMPILER_TARGET)\n  list(APPEND module_triple_command -target ${CMAKE_Swift_COMPILER_TARGET})\nendif()\nexecute_process(COMMAND ${module_triple_command} OUTPUT_VARIABLE target_info_json)\nmessage(CONFIGURE_LOG \"Swift target info: ${module_triple_command}\\n\"\n\"${target_info_json}\")\n\nif(NOT ${PROJECT_NAME}_MODULE_TRIPLE)\n  string(JSON module_triple GET \"${target_info_json}\" \"target\" \"moduleTriple\")\n  set(${PROJECT_NAME}_MODULE_TRIPLE \"${module_triple}\" CACHE STRING \"Triple used for installed swift{doc,module,interface} files\")\n  mark_as_advanced(${PROJECT_NAME}_MODULE_TRIPLE)\n\n  message(CONFIGURE_LOG \"Swift module triple: ${module_triple}\")\nendif()\n"
  },
  {
    "path": "Sources/SBOMModel/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SBOMModel STATIC\n  SBOMCreator.swift\n  SBOMError.swift\n  SBOMInput.swift\n  Core/SBOMCommit.swift\n  Core/SBOMComponent.swift\n  Core/SBOMDependencies.swift\n  Core/SBOMDocument.swift\n  Core/SBOMIdentifier.swift\n  Core/SBOMLicense.swift\n  Core/SBOMMetadata.swift\n  Core/SBOMOriginator.swift\n  Core/SBOMPerson.swift\n  Core/SBOMRegistryEntry.swift\n  Core/SBOMRelationship.swift\n  Core/SBOMSpec.swift\n  Core/SBOMTool.swift\n  Core/SBOMVersionRegistry.swift\n  Converter/CycloneDXConverter.swift\n  Converter/SPDXConverter.swift\n  CycloneDX/CycloneDXComponent.swift\n  CycloneDX/CycloneDXConstants.swift\n  CycloneDX/CycloneDXDependency.swift\n  CycloneDX/CycloneDXDocument.swift\n  CycloneDX/CycloneDXExternalReference.swift\n  CycloneDX/CycloneDXLicense.swift\n  CycloneDX/CycloneDXMetadata.swift\n  CycloneDX/CycloneDXPedigree.swift\n  CycloneDX/CycloneDXProperty.swift\n  Encoder/SBOMEncoder.swift\n  Extractor/DependencySourceStrategy.swift\n  Extractor/PURL.swift\n  Extractor/SBOMCache.swift\n  Extractor/SBOMDependenciesExtractor.swift\n  Extractor/SBOMExtractor.swift\n  Extractor/SBOMFilterStrategy.swift\n  Extractor/SBOMGraphsConverter.swift\n  SPDX/SPDXAgent.swift\n  SPDX/SPDXConstants.swift\n  SPDX/SPDXCreationInfo.swift\n  SPDX/SPDXDocument.swift\n  SPDX/SPDXExternalIdentifier.swift\n  SPDX/SPDXGraph.swift\n  SPDX/SPDXLicenseExpression.swift\n  SPDX/SPDXObject.swift\n  SPDX/SPDXPackage.swift\n  SPDX/SPDXRelationship.swift\n  SPDX/SPDXSBOM.swift\n  SPDX/SPDXType.swift\n  Validator/CycloneDXValidator.swift\n  Validator/SBOMValidator.swift\n  Validator/SBOMValidatorProtocol.swift\n  Validator/SPDXValidator.swift)\ntarget_link_libraries(SBOMModel PUBLIC\n  TSCBasic\n  TSCUtility\n  Basics\n  PackageCollections\n  PackageGraph\n  PackageModel\n  SourceControl\n  SwiftBuildSupport\n)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(SBOMModel PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n  "
  },
  {
    "path": "Sources/SBOMModel/Converter/CycloneDXConverter.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\ninternal struct CycloneDXConverter {\n    private init() {}\n\n    private static func convertToScope(from scope: SBOMComponent.Scope) async -> CycloneDXComponent.Scope {\n        switch scope {\n        case .runtime:\n            .required\n        case .optional:\n            .optional\n        case .test:\n            .excluded\n        }\n    }\n\n    private static func convertToCategory(from category: SBOMComponent.Category) async -> CycloneDXComponent\n        .Category\n    {\n        switch category {\n        case .application:\n            .application\n        case .framework:\n            .framework\n        case .library:\n            .library\n        case .file:\n            .file\n        }\n    }\n\n    private static func convertToLicense(from license: SBOMLicense) -> CycloneDXLicense {\n        return CycloneDXLicense(\n            license: CycloneDXLicenseInfo(\n                id: license.name,\n                url: license.url\n            ),\n        )\n    }\n\n    private static func convertToSchema(from spec: SBOMSpec) async throws -> String {\n        switch spec.concreteSpec {\n        case .cyclonedx1:\n            return CycloneDXConstants.cyclonedx1Schema\n        // case .cyclonedx2:\n        //     return CycloneDXConstants.cyclonedx2Schema\n        case .spdx3:\n            throw SBOMGenerationError.unexpectedSpecType(expected: \"cyclonedx\", actual: spec)\n        }\n    }\n\n    internal static func convertToPedigree(from originator: SBOMOriginator) async throws -> CycloneDXPedigree {\n        guard let sbomCommits = originator.commits else {\n            return CycloneDXPedigree(commits: nil)\n        }\n\n        let cyclonedxCommits = sbomCommits.map { sbomCommit in\n            let cyclonedxAuthor: CycloneDXAction? = sbomCommit.authors?.first.map { sbomPerson in\n                CycloneDXAction(\n                    name: sbomPerson.name,\n                    email: sbomPerson.email\n                )\n            }\n\n            return CycloneDXCommit(\n                uid: sbomCommit.sha,\n                url: sbomCommit.repository,\n                author: cyclonedxAuthor,\n            )\n        }\n\n        return CycloneDXPedigree(commits: cyclonedxCommits)\n    }\n\n    internal static func convertToExternalReferences(from originator: SBOMOriginator) async throws -> [CycloneDXExternalReference] {\n        guard let registryEntries = originator.entries else {\n            return []\n        }\n        let externalReferences = registryEntries.compactMap { entry -> CycloneDXExternalReference? in\n            guard let url = entry.url else { return nil }\n            return CycloneDXExternalReference(\n                url: url,\n                refType: .distribution\n            )\n        }\n        return externalReferences\n    }\n\n    internal static func convertToComponent(from comp: SBOMComponent) async throws -> CycloneDXComponent {\n        try await CycloneDXComponent(\n            type: self.convertToCategory(from: comp.category),\n            bomRef: comp.id.value,\n            name: comp.name,\n            version: comp.version.revision,\n            scope: self.convertToScope(from: comp.scope ?? .runtime),\n            purl: comp.purl.description,\n            pedigree: self.convertToPedigree(from: comp.originator),\n            externalReferences: self.convertToExternalReferences(from: comp.originator),\n            properties: [CycloneDXProperty(name: \"swift-entity\", value: comp.entity.rawValue)]\n        )\n    }\n\n    private static func convertToComponent(from tool: SBOMTool) async throws -> CycloneDXComponent {\n        let licenses = tool.licenses?.map { license in\n            convertToLicense(from: license)\n        }\n        \n        return CycloneDXComponent(\n            type: .application,\n            bomRef: tool.id.value,\n            name: tool.name,\n            version: tool.version,\n            scope: .excluded,\n            purl: tool.purl.description,\n            pedigree: nil,\n            licenses: licenses\n        )\n    }\n\n    internal static func convertToDependency(from dep: SBOMRelationship) async throws -> CycloneDXDependency {\n        CycloneDXDependency(\n            ref: dep.parentID.value,\n            dependsOn: dep.childrenID.map(\\.value)\n        )\n    }\n\n    internal static func convertToMetadata(from document: SBOMDocument) async throws -> CycloneDXMetadata {\n        var tools: CycloneDXTools? = nil\n        if let creators = document.metadata.creators, !creators.isEmpty {\n            var toolsComponents: [CycloneDXComponent] = []\n            for creator in creators {\n                let cyclonedxTool = try await convertToComponent(from: creator)\n                toolsComponents.append(cyclonedxTool)\n            }\n            tools = CycloneDXTools(components: toolsComponents)\n        }\n\n        return try await CycloneDXMetadata(\n            timestamp: document.metadata.timestamp,\n            component: self.convertToComponent(from: document.primaryComponent),\n            tools: tools\n        )\n    }\n\n    internal static func convertToDocument(\n        from document: SBOMDocument,\n        spec: SBOMSpec\n    ) async throws -> CycloneDXDocument {\n        guard spec.supportsCycloneDX else {\n            throw SBOMGenerationError.unexpectedSpecType(expected: \"cyclonedx\", actual: spec)\n        }\n\n        var components: [CycloneDXComponent] = []\n        for sbomComp in document.dependencies.components.sorted() {\n            let cyclonedxComp = try await convertToComponent(from: sbomComp)\n            components.append(cyclonedxComp)\n        }\n\n        var dependencies: [CycloneDXDependency] = []\n        if let documentDependencies = document.dependencies.relationships {\n            for sbomDep in documentDependencies.sorted() {\n                let cyclonedxDep = try await convertToDependency(from: sbomDep)\n                dependencies.append(cyclonedxDep)\n            }\n        }\n\n        return try await CycloneDXDocument(\n            schema: self.convertToSchema(from: spec),\n            bomFormat: \"CycloneDX\",\n            specVersion: spec.versionString,\n            serialNumber: document.id.value,\n            version: 1,\n            metadata: self.convertToMetadata(from: document),\n            components: components,\n            dependencies: dependencies\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Converter/SPDXConverter.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\ninternal struct SPDXConverter {\n    private init() {}\n\n    private static func generateSPDXID(_ id: String) -> String {\n        if id.starts(with: \"urn:\") { return id }\n        return \"urn:spdx:\\(id)\"\n    }\n\n    private static func convertToPurpose(from category: SBOMComponent.Category) async -> SPDXPackage.Purpose {\n        switch category {\n        case .application:\n            .application\n        case .framework:\n            .framework\n        case .library:\n            .library\n        case .file:\n            .file\n        }\n    }\n\n    private static func convertToLicenseExpression(from license: SBOMLicense, creationInfoID: String) async -> SPDXLicenseExpression {\n        let id = generateSPDXID(license.name)\n        return SPDXLicenseExpression(\n            id: id,\n            type: SPDXType.LicenseExpression,\n            expression: license.name,\n            creationInfoID: creationInfoID,\n        )\n    }\n    \n\n    internal static func convertToAgent(from metadata: SBOMMetadata?) async -> [any SPDXObject] {\n        guard let metadata,\n              let creators = metadata.creators,\n              !creators.isEmpty\n        else {\n            return []\n        }\n                \n        var agents: [any SPDXObject] = []\n        for creator in creators {\n            let creatorID = self.generateSPDXID(creator.id.value)\n            let toolCreationInfoID = \"\\(creatorID):creationInfo\"\n            let toolCreationInfo = SPDXCreationInfo(\n                id: toolCreationInfoID,\n                type: .CreationInfo,\n                specVersion: creator.version,\n                createdBy: [creatorID],\n                created: \"1970-01-01T00:00:00Z\"\n            )\n            let tool = SPDXAgent(\n                id: creatorID,\n                type: .Agent,\n                name: creator.name,\n                creationInfoID: toolCreationInfoID\n            )\n            if let licenses = creator.licenses {\n                for license in licenses {\n                    let spdxLicense = await convertToLicenseExpression(from: license, creationInfoID: toolCreationInfoID)\n                    let relationship = SPDXRelationship(\n                        id: generateSPDXID(\"\\(creatorID)-hasDeclaredLicense-\\(spdxLicense.id)\"),\n                        type: .Relationship,\n                        category: .hasDeclaredLicense,\n                        creationInfoID: toolCreationInfoID,\n                        parentID: creatorID,\n                        childrenID: [spdxLicense.id]\n                    )\n                    agents.append(relationship)\n                    agents.append(spdxLicense)\n                }\n            }\n            \n            agents.append(toolCreationInfo)\n            agents.append(tool)\n        }\n        return agents\n    }\n\n    internal static func convertToDocument(\n        from document: SBOMDocument,\n        spec: SBOMSpec\n    ) async throws -> [any SPDXObject] {\n        guard let timestamp = document.metadata.timestamp,\n              let creators = document.metadata.creators,\n              !creators.isEmpty\n        else {\n            throw SBOMConverterError.missingRequiredMetadata(\n                message: \"timestamp or creators are missing from SBOM document metadata, required for SPDX format\"\n            )\n        }\n\n        var elements: [any SPDXObject] = []\n\n        let creationInfoID = SPDXConstants.spdxRootCreationInfoID\n\n        let creationInfo = SPDXCreationInfo(\n            id: creationInfoID,\n            type: .CreationInfo,\n            specVersion: spec.versionString,\n            createdBy: creators.map { self.generateSPDXID($0.id.value) },\n            created: timestamp\n        )\n        elements.append(creationInfo)\n\n        let spdxSBOMID = SBOMIdentifier.generate().value\n        let profileConformance = [\"core\", \"software\"]\n\n        let primaryComponentID = self.generateSPDXID(document.primaryComponent.id.value)\n\n        let spdxSBOM = SPDXSBOM(\n            id: spdxSBOMID,\n            type: .SoftwareSBOM,\n            creationInfoID: creationInfoID,\n            profileConformance: profileConformance,\n            rootElementIDs: [primaryComponentID]\n        )\n        elements.append(spdxSBOM)\n\n        let describes = SPDXRelationship(\n            id: generateSPDXID(\"\\(spdxSBOMID)-describes-\\(primaryComponentID)\"),\n            type: .Relationship,\n            category: .describes,\n            creationInfoID: creationInfoID,\n            parentID: spdxSBOMID,\n            childrenID: [primaryComponentID]\n        )\n        elements.append(describes)\n\n        let spdxDocument = SPDXDocument(\n            id: generateSPDXID(document.id.value),\n            type: .SpdxDocument,\n            creationInfoID: creationInfoID,\n            profileConformance: profileConformance,\n            rootElementIDs: [spdxSBOMID]\n        )\n        elements.append(spdxDocument)\n\n        return elements\n    }\n\n    internal static func convertToPackage(from component: SBOMComponent) async throws -> SPDXPackage {\n        await SPDXPackage(\n            id: self.generateSPDXID(component.id.value),\n            type: .SoftwarePackage,\n            purpose: self.convertToPurpose(from: component.category),\n            purl: component.purl.description,\n            name: component.name,\n            version: component.version.revision,\n            creationInfoID: SPDXConstants.spdxRootCreationInfoID,\n            description: component.description,\n            summary: component.entity.rawValue\n        )\n    }\n\n    internal static func convertToExternalIdentifiers(from components: [SBOMComponent]?) async -> [any SPDXObject] {\n        guard let comps = components, !comps.isEmpty else {\n            return []\n        }\n\n        var externalIdentifiers: [any SPDXObject] = []\n\n        var commitToComponents: [String: (repository: String, componentIDs: [String])] = [:]\n        for component in comps.sorted() {\n            let componentID: String = self.generateSPDXID(component.id.value)\n\n            // Handle originator commits\n            if let commits = component.originator.commits {\n                for commit in commits {\n                    if commitToComponents[commit.sha] != nil {\n                        commitToComponents[commit.sha]?.componentIDs.append(componentID)\n                    } else {\n                        commitToComponents[commit.sha] = (repository: commit.repository, componentIDs: [componentID])\n                    }\n                }\n            }\n            // Handle originator registry entries\n            if let entries = component.originator.entries {\n                for entry in entries {\n                    guard let entryURL = entry.url else {\n                        continue\n                    }\n                    let externalIdentifier = SPDXExternalIdentifier(\n                        identifier: generateSPDXID(entryURL.description),\n                        identifierLocator: [entryURL.description],\n                        type: .ExternalIdentifier,\n                        category: .urlScheme\n                    )\n                    externalIdentifiers.append(externalIdentifier)\n                    let relationship = SPDXRelationship(\n                        id: generateSPDXID(\"\\(entry.scope)-\\(entry.name)-\\(entry.version)-availableFrom-\\(componentID)\"),\n                        type: .Relationship,\n                        category: .availableFrom,\n                        creationInfoID: SPDXConstants.spdxRootCreationInfoID,\n                        parentID: componentID,\n                        childrenID: [self.generateSPDXID(entryURL.description)]\n                    )\n                    externalIdentifiers.append(relationship)\n                }\n            }\n        }\n\n        for (commitSHA, commitInfo) in commitToComponents.sorted(by: { $0.key < $1.key }) {\n            let externalIdentifier = SPDXExternalIdentifier(\n                identifier: generateSPDXID(commitSHA),\n                identifierLocator: [commitInfo.repository],\n                type: .ExternalIdentifier,\n                category: .gitoid\n            )\n            externalIdentifiers.append(externalIdentifier)\n            let relationship = SPDXRelationship(\n                id: generateSPDXID(\"\\(commitSHA)-generates\"),\n                type: .Relationship,\n                category: .generates,\n                creationInfoID: SPDXConstants.spdxRootCreationInfoID,\n                parentID: self.generateSPDXID(commitSHA),\n                childrenID: commitInfo.componentIDs.sorted()\n            )\n            externalIdentifiers.append(relationship)\n        }\n\n        // Note: SPDXObject Comparable is a protocol made up of other concrete types, so use a custom sort\n        return externalIdentifiers.sorted { lhs, rhs in\n            if let lhsRel = lhs as? SPDXRelationship, let rhsRel = rhs as? SPDXRelationship {\n                return lhsRel.id < rhsRel.id\n            }\n            if let lhsExt = lhs as? SPDXExternalIdentifier, let rhsExt = rhs as? SPDXExternalIdentifier {\n                return lhsExt.identifier < rhsExt.identifier\n            }\n            if lhs is SPDXExternalIdentifier && rhs is SPDXRelationship { return true }\n            if lhs is SPDXRelationship && rhs is SPDXExternalIdentifier { return false }\n            return false\n        }\n    }\n\n    internal static func convertToRelationships(from dependencies: SBOMDependencies?) async -> [any SPDXObject] {\n        guard let dependencies else {\n            return []\n        }\n\n        var relationships: [any SPDXObject] = []\n        if let sbomRelationships = dependencies.relationships {\n            for dependency in sbomRelationships.sorted() {\n                let parentID = self.generateSPDXID(dependency.parentID.value)\n                let childrenIDs = dependency.childrenID.map { self.generateSPDXID($0.value) }\n\n                let relationship = SPDXRelationship(\n                    id: generateSPDXID(\"\\(dependency.parentID.value)-dependsOn\"),\n                    type: .Relationship,\n                    category: .dependsOn,\n                    creationInfoID: SPDXConstants.spdxRootCreationInfoID,\n                    parentID: parentID,\n                    childrenID: childrenIDs\n                )\n                relationships.append(relationship)\n\n                var optionalDependencies: [String] = []\n                var testDependencies: [String] = []\n                for childID in dependency.childrenID.sorted(by: { $0.value < $1.value }) {\n                    guard let comp = dependencies.components.first(where: { $0.id == childID }) else {\n                        continue\n                    }\n                    let spdxChildID = self.generateSPDXID(childID.value)\n                    switch comp.scope {\n                    case .optional:\n                        optionalDependencies.append(spdxChildID)\n                    case .test:\n                        testDependencies.append(spdxChildID)\n                    default:\n                        break\n                    }\n                }\n                if !optionalDependencies.isEmpty {\n                    let relationship = SPDXRelationship(\n                        id: generateSPDXID(\"\\(dependency.parentID.value)-hasOptionalDependency\"),\n                        type: .Relationship,\n                        category: .hasOptionalDependency,\n                        creationInfoID: SPDXConstants.spdxRootCreationInfoID,\n                        parentID: parentID,\n                        childrenID: optionalDependencies\n                    )\n                    relationships.append(relationship)\n                }\n                if !testDependencies.isEmpty {\n                    let relationship = SPDXRelationship(\n                        id: generateSPDXID(\"\\(dependency.parentID.value)-hasTest\"),\n                        type: .Relationship,\n                        category: .hasTest,\n                        creationInfoID: SPDXConstants.spdxRootCreationInfoID,\n                        parentID: parentID,\n                        childrenID: testDependencies\n                    )\n                    relationships.append(relationship)\n                }\n            }\n        }\n\n        return relationships\n    }\n\n    internal static func convertToGraph(from document: SBOMDocument, spec: SBOMSpec) async throws -> SPDXGraph {\n        guard spec.supportsSPDX else {\n            throw SBOMGenerationError.unexpectedSpecType(expected: \"spdx\", actual: spec)\n        }\n\n        let agents = await convertToAgent(from: document.metadata)\n        let elements = try await convertToDocument(from: document, spec: spec)\n\n        var packages: [any SPDXObject] = []\n        for comp in document.dependencies.components.sorted() {\n            let p = try await convertToPackage(from: comp)\n            packages.append(p)\n        }\n\n        let relationships = await convertToRelationships(from: document.dependencies)\n        let commits = await convertToExternalIdentifiers(from: document.dependencies.components)\n\n        return SPDXGraph(\n            context: SPDXConstants.spdx3Context,\n            graph: agents + elements + packages + relationships + commits\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMCommit.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMCommit: Hashable, Codable, Equatable {\n    internal let sha: String\n    internal let repository: String\n    internal let authors: [SBOMPerson]?\n\n    internal init(\n        sha: String,\n        repository: String,\n        authors: [SBOMPerson]? = nil,\n    ) {\n        self.sha = sha\n        self.repository = repository\n        self.authors = authors\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMComponent.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMComponent: Codable, Equatable, Hashable, Comparable {\n    internal enum Category: String, Codable, Equatable {\n        case application\n        case framework\n        case library\n        case file\n    }\n\n    internal enum Scope: String, Codable, Equatable {\n        case runtime\n        case optional\n        case test\n    }\n    \n    internal enum Entity: String, Codable, Equatable {\n        case product = \"swift-product\"\n        case package = \"swift-package\"\n    }\n\n    // Specifies the commit or registry entry that is used for the version\n    internal struct Version: Codable, Equatable, Hashable {\n        internal let revision: String\n        internal let commit: SBOMCommit?\n        internal let entry: SBOMRegistryEntry?\n\n        internal init(\n            revision: String,\n            commit: SBOMCommit? = nil,\n            entry: SBOMRegistryEntry? = nil\n        ) {\n            self.revision = revision\n            self.commit = commit\n            self.entry = entry\n        }\n    }\n\n    internal let category: Category\n    internal let id: SBOMIdentifier\n    internal let purl: PURL\n    internal let name: String\n    internal let version: Version\n    internal let originator: SBOMOriginator\n    internal let description: String?\n    internal let scope: Scope?\n    internal let components: [SBOMComponent]?\n    internal let entity: Entity\n\n    internal init(\n        category: Category,\n        id: SBOMIdentifier,\n        purl: PURL,\n        name: String,\n        version: Version,\n        originator: SBOMOriginator,\n        description: String? = nil,\n        scope: Scope?,\n        components: [SBOMComponent]? = nil,\n        entity: Entity\n    ) {\n        self.category = category\n        self.id = id\n        self.purl = purl\n        self.name = name\n        self.version = version\n        self.originator = originator\n        self.description = description\n        self.scope = scope\n        self.components = components\n        self.entity = entity\n    }\n    \n    // Comparable implementation for deterministic ordering\n    internal static func < (lhs: SBOMComponent, rhs: SBOMComponent) -> Bool {\n        lhs.id.value < rhs.id.value\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMDependencies.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMDependencies: Codable, Equatable {\n    internal let components: [SBOMComponent]\n    internal let relationships: [SBOMRelationship]?\n\n    internal init(\n        components: [SBOMComponent],\n        relationships: [SBOMRelationship]? = nil\n    ) {\n        self.components = components\n        self.relationships = relationships\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMDocument.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMDocument: Codable, Equatable {\n    internal let id: SBOMIdentifier\n    internal let metadata: SBOMMetadata\n    internal let primaryComponent: SBOMComponent\n    internal let dependencies: SBOMDependencies\n    internal let licenses: [SBOMLicense]?\n\n    internal init(\n        id: SBOMIdentifier,\n        metadata: SBOMMetadata,\n        primaryComponent: SBOMComponent,\n        dependencies: SBOMDependencies,\n        licenses: [SBOMLicense]? = nil\n    ) {\n        self.id = id\n        self.metadata = metadata\n        self.primaryComponent = primaryComponent\n        self.dependencies = dependencies\n        self.licenses = licenses\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMIdentifier.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\ninternal struct SBOMIdentifier: Codable, Equatable, Hashable {\n    internal let value: String\n\n    internal init(value: String) {\n        self.value = value\n    }\n\n    internal static func generate() -> SBOMIdentifier {\n        SBOMIdentifier(value: \"urn:uuid:\\(UUID().uuidString.lowercased())\")\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMLicense.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMLicense: Codable, Equatable {\n    internal let name: String\n    internal let url: String?\n\n    internal init(\n        name: String,\n        url: String?\n    ) {\n        self.name = name\n        self.url = url\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMMetadata.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMMetadata: Codable, Equatable {\n    internal let timestamp: String?\n    internal let creators: [SBOMTool]?\n\n    internal init(\n        timestamp: String?,\n        creators: [SBOMTool]? = nil\n    ) {\n        self.timestamp = timestamp\n        self.creators = creators\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMOriginator.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMOriginator: Codable, Equatable, Hashable {\n    internal let commits: [SBOMCommit]?\n    internal let entries: [SBOMRegistryEntry]?\n\n    internal init(\n        commits: [SBOMCommit]? = nil,\n        entries: [SBOMRegistryEntry]? = nil,\n    ) {\n        self.commits = commits\n        self.entries = entries\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMPerson.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMPerson: Codable, Equatable, Hashable {\n    internal let id: SBOMIdentifier\n    internal let name: String\n    internal let email: String?\n\n    internal init(\n        id: SBOMIdentifier,\n        name: String,\n        email: String?\n    ) {\n        self.id = id\n        self.name = name\n        self.email = email\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMRegistryEntry.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\ninternal struct SBOMRegistryEntry: Hashable, Codable, Equatable {\n    internal let url: URL?\n    internal let scope: String\n    internal let name: String\n    internal let version: String\n\n    internal init(\n        url: URL? = nil,\n        scope: String,\n        name: String,\n        version: String,\n    ) {\n        self.url = url\n        self.scope = scope\n        self.name = name\n        self.version = version\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMRelationship.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMRelationship: Codable, Equatable, Hashable, Comparable {\n    // internal enum Source: String, Codable, Equatable {\n    //     case modules // from ModulesGraph\n    //     case build // from build dependency graph\n    //     case all // appears in all graphs\n    // }\n\n    // internal struct Metadata: Codable, Equatable {\n    //     let source: Source\n\n    //     internal init(\n    //         source: Source,\n    //     ) {\n    //         self.source = source\n    //     }\n    // }\n\n    internal let id: SBOMIdentifier\n    internal let parentID: SBOMIdentifier\n    internal let childrenID: [SBOMIdentifier]\n\n    internal init(\n        id: SBOMIdentifier,\n        parentID: SBOMIdentifier,\n        childrenID: [SBOMIdentifier]\n    ) {\n        self.id = id\n        self.parentID = parentID\n        self.childrenID = childrenID\n    }\n    \n    // Comparable implementation for deterministic ordering\n    internal static func < (lhs: SBOMRelationship, rhs: SBOMRelationship) -> Bool {\n        lhs.id.value < rhs.id.value\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMSpec.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n\n/// SBOM specification types supported by SwiftPM.\n/// All version numbers are managed centrally in `SBOMVersionRegistry`.\n/// \n/// This file only needs to be changed with new major versions like CycloneDX 2 or SPDX 4.\n\n/// Spec is the enum used for the user's CLI arguments\npackage enum Spec: String, Codable, Equatable, CaseIterable, ExpressibleByArgument {\n    /// Latest major version of CycloneDX (currently maps to `cyclonedx1`)\n    case cyclonedx\n    \n    /// Latest major version of SPDX (currently maps to `spdx3`)\n    case spdx\n    \n    /// CycloneDX v1.x - Latest minor version\n    case cyclonedx1\n    \n    /// SPDX v3.x - Latest minor version\n    case spdx3\n    \n    // Future major versions (uncomment when released):\n    //\n    // /// CycloneDX v2.x - Latest minor version\n    // ///\n    // /// Add this case when CycloneDX 2.0 is released.\n    // /// Update `.cyclonedx` to map to this case in `latestSpec`.\n    // case cyclonedx2\n    //\n    // /// SPDX v4.x - Latest minor version\n    // ///\n    // /// Add this case when SPDX 4.0 is released.\n    // /// Update `.spdx` to map to this case in `latestSpec`.\n    // case spdx4\n\n    package var defaultValueDescription: String {\n        let version = SBOMVersionRegistry.getLatestVersion(for: SBOMSpec(spec: self))\n        switch self {\n        case .cyclonedx: return \"Most recent major version of CycloneDX supported by SwiftPM (currently: \\(version))\"\n        case .spdx: return \"Most recent major version of SPDX supported by SwiftPM (currently: \\(version))\"\n        case .cyclonedx1: return \"Most recent minor version of CycloneDX v1 supported by SwiftPM (currently: \\(version))\"\n        case .spdx3: return \"Most recent minor version of SPDX v3 supported by SwiftPM (currently: \\(version))\"\n        // case .cyclonedx2: return \"Most recent minor version of CycloneDX v2 supported by SwiftPM (currently: \\(version))\"\n        // case .spdx4: return \"Most recent minor version of SPDX v4 supported by SwiftPM (currently: \\(version))\"\n        }\n    }\n\n    internal func internalSpec() -> SBOMSpec {\n        SBOMSpec(spec: self)\n    }\n}\n\n/// Internal representation of a concrete SBOM specification.\ninternal struct SBOMSpec: Codable, Equatable, Hashable, Comparable {\n\n    internal enum ConcreteSpec: String, Codable, Equatable, CaseIterable, Comparable {\n        case cyclonedx1\n        case spdx3\n        // case cyclonedx2\n        // case spdx4\n\n        package static func < (lhs: ConcreteSpec, rhs: ConcreteSpec) -> Bool {\n            lhs.rawValue < rhs.rawValue\n        }\n    }\n\n    internal let concreteSpec: ConcreteSpec\n    \n    internal var versionString: String {\n        SBOMVersionRegistry.getLatestVersion(for: self)\n    }\n\n    /// Returns the schema filename (without .json extension) for this spec type\n    internal var schemaFilename: String {\n        switch self.concreteSpec {\n        case .cyclonedx1:\n            CycloneDXConstants.cyclonedx1SchemaFile\n        case .spdx3:\n            SPDXConstants.spdx3SchemaFile\n            // case .cyclonedx2:\n            //     CycloneDXConstants.cyclonedx2SchemaFile\n            // case .spdx4:\n            //     SPDXConstants.spdx4SchemaFile\n        }\n    }\n\n    /// Returns `true` if this spec type supports CycloneDX format.\n    internal var supportsCycloneDX: Bool {\n        switch self.concreteSpec {\n        case .cyclonedx1: // .cyclonedx2\n            true\n        case .spdx3: // .spdx4\n            false\n        }\n    }\n\n    /// Returns `true` if this spec type supports SPDX format.\n    internal var supportsSPDX: Bool {\n        switch self.concreteSpec {\n        case .spdx3: // .spdx4\n            true\n        case .cyclonedx1: // .cyclonedx2\n            false\n        }\n    }\n\n    internal init(spec: Spec) {\n        switch spec {\n            case .cyclonedx, .cyclonedx1:\n                self.concreteSpec = .cyclonedx1\n            case .spdx, .spdx3:\n                self.concreteSpec = .spdx3\n        }\n    }\n\n    internal static func < (lhs: SBOMSpec, rhs: SBOMSpec) -> Bool {\n        lhs.concreteSpec < rhs.concreteSpec\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMTool.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SBOMTool: Codable, Equatable {\n    internal let id: SBOMIdentifier\n    internal let name: String\n    internal let version: String\n    internal let purl: PURL\n    internal let licenses: [SBOMLicense]?\n\n    internal init(\n        id: SBOMIdentifier,\n        name: String,\n        version: String,\n        purl: PURL,\n        licenses: [SBOMLicense]? = nil\n    ) {\n        self.id = id\n        self.name = name\n        self.version = version\n        self.purl = purl\n        self.licenses = licenses\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Core/SBOMVersionRegistry.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Central registry for managing SBOM specification versions.\n///\n/// See `Sources/SBOMModel/README.md` for detailed documentation on version management.\ninternal struct SBOMVersionRegistry {\n    // MARK: - CycloneDX Versions\n    \n    /// Latest minor version of CycloneDX v1.x\n    internal static let cycloneDX1LatestMinor = \"1.7\"\n    \n    // Future major versions (uncomment when released):\n    // internal static let cycloneDX2LatestMinor = \"2.0\"\n    \n    // MARK: - SPDX Versions\n    \n    /// Latest minor version of SPDX v3.x\n    internal static let spdx3LatestMinor = \"3.0.1\"\n    \n    // Future major versions (uncomment when released):\n    // internal static let spdx4LatestMinor = \"4.0\"\n    \n    // MARK: - Version Resolution\n    \n    /// Returns the latest supported version for a given spec type.\n    internal static func getLatestVersion(for spec: SBOMSpec) -> String {\n        switch spec.concreteSpec {\n        case .cyclonedx1:\n            return cycloneDX1LatestMinor\n        case .spdx3:\n            return spdx3LatestMinor\n        // case .cyclonedx2:\n        //     return cycloneDX2LatestMinor\n        // case .spdx4:\n        //     return spdx4LatestMinor\n        }\n    }\n}"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXComponent.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct CycloneDXComponent: Codable, Equatable {\n    internal enum Category: String, Codable, Equatable {\n        case application\n        case framework\n        case library\n        case file\n    }\n\n    internal enum Scope: String, Codable, Equatable {\n        case required\n        case optional\n        case excluded\n    }\n\n    internal let type: Category\n    internal let bomRef: String\n    internal let name: String\n    internal let version: String\n    internal let scope: Scope\n    internal let purl: String\n    internal let components: [CycloneDXComponent]?\n    internal let pedigree: CycloneDXPedigree?\n    internal let externalReferences: [CycloneDXExternalReference]?\n    internal let properties: [CycloneDXProperty]?\n    internal let licenses: [CycloneDXLicense]?\n\n    internal init(\n        type: Category,\n        bomRef: String,\n        name: String,\n        version: String,\n        scope: Scope,\n        purl: String,\n        components: [CycloneDXComponent]? = nil,\n        pedigree: CycloneDXPedigree? = nil,\n        externalReferences: [CycloneDXExternalReference]? = nil,\n        properties: [CycloneDXProperty]? = nil,\n        licenses: [CycloneDXLicense]? = nil\n    ) {\n        self.type = type\n        self.bomRef = bomRef\n        self.name = name\n        self.version = version\n        self.scope = scope\n        self.purl = purl\n        self.components = components\n        self.pedigree = pedigree\n        self.externalReferences = externalReferences\n        self.properties = properties\n        self.licenses = licenses\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case type\n        case bomRef = \"bom-ref\"\n        case name\n        case version\n        case scope\n        case purl\n        case components\n        case pedigree\n        case externalReferences\n        case properties\n        case licenses\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXConstants.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct CycloneDXConstants: Codable, Equatable {\n    /// The latest minor version of CycloneDX v1.x (from SBOMVersionRegistry)\n    internal static var cyclonedx1SpecVersion: String {\n        SBOMVersionRegistry.cycloneDX1LatestMinor\n    }\n    \n    /// The JSON schema URL for CycloneDX v1.x\n    /// This is embedded as a field in the SBOM, and points to an official schema URL on the CycloneDX website\n    internal static var cyclonedx1Schema: String {\n        \"http://cyclonedx.org/schema/bom-\\(cyclonedx1SpecVersion).schema.json\"\n    }\n    \n    /// The schema filename for CycloneDX v1.x (without .json extension) that's bundled as an internal resource with SwiftPM\n    internal static var cyclonedx1SchemaFile: String {\n        \"cyclonedx-\\(cyclonedx1SpecVersion).schema\"\n    }\n    \n    // Future major versions (uncomment when CycloneDX 2.0 is released):\n    // /// The latest minor version of CycloneDX v2.x (from SBOMVersionRegistry)\n    // internal static var cyclonedx2SpecVersion: String {\n    //     SBOMVersionRegistry.cycloneDX2LatestMinor\n    // }\n    //\n    // /// The JSON schema URL for CycloneDX v2.x\n    // internal static var cyclonedx2Schema: String {\n    //     \"http://cyclonedx.org/schema/bom-\\(cyclonedx2SpecVersion).schema.json\"\n    // }\n    //\n    // /// The schema filename for CycloneDX v2.x (without .json extension)\n    // internal static var cyclonedx2SchemaFile: String {\n    //     \"cyclonedx-\\(cyclonedx2SpecVersion).schema\"\n    // }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXDependency.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct CycloneDXDependency: Codable, Equatable {\n    internal let ref: String\n    internal let dependsOn: [String]\n\n    internal init(\n        ref: String,\n        dependsOn: [String]\n    ) {\n        self.ref = ref\n        self.dependsOn = dependsOn\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case ref\n        case dependsOn\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXDocument.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct CycloneDXDocument: Codable, Equatable {\n    internal let schema: String\n    internal let bomFormat: String\n    internal let specVersion: String\n    internal let serialNumber: String\n    internal let version: Int\n    internal let metadata: CycloneDXMetadata\n    internal let components: [CycloneDXComponent]?\n    internal let dependencies: [CycloneDXDependency]?\n\n    internal init(\n        schema: String,\n        bomFormat: String,\n        specVersion: String,\n        serialNumber: String,\n        version: Int,\n        metadata: CycloneDXMetadata,\n        components: [CycloneDXComponent]? = nil,\n        dependencies: [CycloneDXDependency]? = nil\n    ) {\n        self.schema = schema\n        self.bomFormat = bomFormat\n        self.specVersion = specVersion\n        self.serialNumber = serialNumber\n        self.version = version\n        self.metadata = metadata\n        self.components = components\n        self.dependencies = dependencies\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case schema = \"$schema\"\n        case bomFormat\n        case specVersion\n        case serialNumber\n        case version\n        case metadata\n        case components\n        case dependencies\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXExternalReference.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\ninternal struct CycloneDXExternalReference: Codable, Equatable {\n    internal enum RefType: String, Codable, Equatable {\n        case distribution\n    }\n\n    internal let url: URL\n    internal let refType: RefType\n\n    internal init(\n        url: URL,\n        refType: RefType \n    ) {\n        self.url = url\n        self.refType = refType\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case url\n        case refType = \"type\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXLicense.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct CycloneDXLicenseInfo: Codable, Equatable {\n    internal let id: String\n    internal let url: String?\n\n    internal init(\n        id: String,\n        url: String?\n    ) {\n        self.id = id\n        self.url = url\n    }\n}\n\ninternal struct CycloneDXLicense: Codable, Equatable {\n    internal let license: CycloneDXLicenseInfo\n\n    internal init(\n        license: CycloneDXLicenseInfo,\n    ) {\n        self.license = license\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXMetadata.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct CycloneDXTools: Codable, Equatable {\n    internal let components: [CycloneDXComponent]\n\n    internal init(components: [CycloneDXComponent]) {\n        self.components = components\n    }\n}\n\ninternal struct CycloneDXMetadata: Codable, Equatable {\n    internal let timestamp: String?\n    internal let component: CycloneDXComponent\n    internal let tools: CycloneDXTools?\n\n    internal init(\n        timestamp: String?,\n        component: CycloneDXComponent,\n        tools: CycloneDXTools?\n    ) {\n        self.timestamp = timestamp\n        self.component = component\n        self.tools = tools\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXPedigree.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct CycloneDXAction: Codable, Equatable {\n    internal let name: String?\n    internal let email: String?\n\n    internal init(\n        name: String? = nil,\n        email: String? = nil\n    ) {\n        self.name = name\n        self.email = email\n    }\n}\n\ninternal struct CycloneDXCommit: Codable, Equatable {\n    internal let uid: String?\n    internal let url: String?\n    internal let author: CycloneDXAction?\n    internal let message: String?\n\n    internal init(\n        uid: String? = nil,\n        url: String? = nil,\n        author: CycloneDXAction? = nil,\n        message: String? = nil\n    ) {\n        self.uid = uid\n        self.url = url\n        self.author = author\n        self.message = message\n    }\n}\n\ninternal struct CycloneDXPedigree: Codable, Equatable {\n    internal let commits: [CycloneDXCommit]?\n\n    internal init(commits: [CycloneDXCommit]? = nil) {\n        self.commits = commits\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/CycloneDXProperty.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct CycloneDXProperty: Codable, Equatable {\n    internal let name: String\n    internal let value: String\n\n    internal init(\n        name: String,\n        value: String\n    ) {\n        self.name = name\n        self.value = value\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/CycloneDX/Resources/cyclonedx-1.7.schema.json",
    "content": "{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"$id\": \"http://cyclonedx.org/schema/bom-1.7.schema.json\",\n  \"type\": \"object\",\n  \"title\": \"CycloneDX Bill of Materials Standard\",\n  \"$comment\" : \"CycloneDX JSON schema is published under the terms of the Apache License 2.0.\",\n  \"required\": [\n    \"bomFormat\",\n    \"specVersion\"\n  ],\n  \"additionalProperties\": false,\n  \"properties\": {\n    \"$schema\": {\n      \"type\": \"string\"\n    },\n    \"bomFormat\": {\n      \"type\": \"string\",\n      \"title\": \"BOM Format\",\n      \"description\": \"Specifies the format of the BOM. This helps to identify the file as CycloneDX since BOMs do not have a filename convention, nor does JSON schema support namespaces. This value must be \\\"CycloneDX\\\".\",\n      \"enum\": [\n        \"CycloneDX\"\n      ]\n    },\n    \"specVersion\": {\n      \"type\": \"string\",\n      \"title\": \"CycloneDX Specification Version\",\n      \"description\": \"The version of the CycloneDX specification the BOM conforms to.\",\n      \"examples\": [\"1.7\"]\n    },\n    \"serialNumber\": {\n      \"type\": \"string\",\n      \"title\": \"BOM Serial Number\",\n      \"description\": \"Every BOM generated SHOULD have a unique serial number, even if the contents of the BOM have not changed over time. If specified, the serial number must conform to [RFC 4122](https://www.ietf.org/rfc/rfc4122.html). Use of serial numbers is recommended.\",\n      \"examples\": [\"urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79\"],\n      \"pattern\": \"^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\"\n    },\n    \"version\": {\n      \"type\": \"integer\",\n      \"title\": \"BOM Version\",\n      \"description\": \"Whenever an existing BOM is modified, either manually or through automated processes, the version of the BOM SHOULD be incremented by 1. When a system is presented with multiple BOMs with identical serial numbers, the system SHOULD use the most recent version of the BOM. The default version is '1'.\",\n      \"minimum\": 1,\n      \"default\": 1,\n      \"examples\": [1]\n    },\n    \"metadata\": {\n      \"$ref\": \"#/definitions/metadata\",\n      \"title\": \"BOM Metadata\",\n      \"description\": \"Provides additional information about a BOM.\"\n    },\n    \"components\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/component\"},\n      \"uniqueItems\": true,\n      \"title\": \"Components\",\n      \"description\": \"A list of software and hardware components.\"\n    },\n    \"services\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/service\"},\n      \"uniqueItems\": true,\n      \"title\": \"Services\",\n      \"description\": \"A list of services. This may include microservices, function-as-a-service, and other types of network or intra-process services.\"\n    },\n    \"externalReferences\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/externalReference\"},\n      \"title\": \"External References\",\n      \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n    },\n    \"dependencies\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/dependency\"},\n      \"uniqueItems\": true,\n      \"title\": \"Dependencies\",\n      \"description\": \"Provides the ability to document dependency relationships including provided & implemented components.\"\n    },\n    \"compositions\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/compositions\"},\n      \"uniqueItems\": true,\n      \"title\": \"Compositions\",\n      \"description\": \"Compositions describe constituent parts (including components, services, and dependency relationships) and their completeness. The completeness of vulnerabilities expressed in a BOM may also be described.\"\n    },\n    \"vulnerabilities\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/vulnerability\"},\n      \"uniqueItems\": true,\n      \"title\": \"Vulnerabilities\",\n      \"description\": \"Vulnerabilities identified in components or services.\"\n    },\n    \"annotations\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/annotations\"},\n      \"uniqueItems\": true,\n      \"title\": \"Annotations\",\n      \"description\": \"Comments made by people, organizations, or tools about any object with a bom-ref, such as components, services, vulnerabilities, or the BOM itself. Unlike inventory information, annotations may contain opinions or commentary from various stakeholders. Annotations may be inline (with inventory) or externalized via BOM-Link and may optionally be signed.\"\n    },\n    \"formulation\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/formula\"},\n      \"uniqueItems\": true,\n      \"title\": \"Formulation\",\n      \"description\": \"Describes the formulation of any referencable object within the BOM, including components, services, metadata, declarations, or the BOM itself. This may encompass how the object was created, assembled, deployed, tested, certified, or otherwise brought into its present form. Common examples include software build pipelines, deployment processes, AI/ML model training, cryptographic key generation or certification, and third-party audits. Processes are modeled using declared and observed formulas, composed of workflows, tasks, and individual steps.\"\n    },\n    \"declarations\": {\n      \"type\": \"object\",\n      \"title\": \"Declarations\",\n      \"description\": \"The list of declarations which describe the conformance to standards. Each declaration may include attestations, claims, and evidence.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"assessors\": {\n          \"type\": \"array\",\n          \"title\": \"Assessors\",\n          \"description\": \"The list of assessors evaluating claims and determining conformance to requirements and confidence in that assessment.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"title\": \"Assessor\",\n            \"description\": \"The assessor who evaluates claims and determines conformance to requirements and confidence in that assessment.\",\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"bom-ref\": {\n                \"$ref\": \"#/definitions/refType\",\n                \"title\": \"BOM Reference\",\n                \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\"\n              },\n              \"thirdParty\": {\n                \"type\": \"boolean\",\n                \"title\": \"Third Party\",\n                \"description\": \"The boolean indicating if the assessor is outside the organization generating claims. A value of false indicates a self assessor.\"\n              },\n              \"organization\": {\n                \"$ref\": \"#/definitions/organizationalEntity\",\n                \"title\": \"Organization\",\n                \"description\": \"The entity issuing the assessment.\"\n              }\n            }\n          }\n        },\n        \"attestations\": {\n          \"type\": \"array\",\n          \"title\": \"Attestations\",\n          \"description\": \"The list of attestations asserted by an assessor that maps requirements to claims.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"title\": \"Attestation\",\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"summary\":  {\n                \"type\": \"string\",\n                \"title\": \"Summary\",\n                \"description\": \"The short description explaining the main points of the attestation.\"\n              },\n              \"assessor\": {\n                \"$ref\": \"#/definitions/refLinkType\",\n                \"title\": \"Assessor\",\n                \"description\": \"The `bom-ref` to the assessor asserting the attestation.\"\n              },\n              \"map\": {\n                \"type\": \"array\",\n                \"title\": \"Map\",\n                \"description\": \"The grouping of requirements to claims and the attestors declared conformance and confidence thereof.\",\n                \"items\": {\n                  \"type\": \"object\",\n                  \"title\": \"Map\",\n                  \"additionalProperties\": false,\n                  \"properties\": {\n                    \"requirement\": {\n                      \"$ref\": \"#/definitions/refLinkType\",\n                      \"title\": \"Requirement\",\n                      \"description\": \"The `bom-ref` to the requirement being attested to.\"\n                    },\n                    \"claims\": {\n                      \"type\": \"array\",\n                      \"title\": \"Claims\",\n                      \"description\": \"The list of `bom-ref` to the claims being attested to.\",\n                      \"items\": { \"$ref\": \"#/definitions/refLinkType\" }\n                    },\n                    \"counterClaims\": {\n                      \"type\": \"array\",\n                      \"title\": \"Counter Claims\",\n                      \"description\": \"The list of  `bom-ref` to the counter claims being attested to.\",\n                      \"items\": { \"$ref\": \"#/definitions/refLinkType\" }\n                    },\n                    \"conformance\": {\n                      \"type\": \"object\",\n                      \"title\": \"Conformance\",\n                      \"description\": \"The conformance of the claim meeting a requirement.\",\n                      \"additionalProperties\": false,\n                      \"properties\": {\n                        \"score\": {\n                          \"type\": \"number\",\n                          \"minimum\": 0,\n                          \"maximum\": 1,\n                          \"title\": \"Score\",\n                          \"description\": \"The conformance of the claim between and inclusive of 0 and 1, where 1 is 100% conformance.\"\n                        },\n                        \"rationale\": {\n                          \"type\": \"string\",\n                          \"title\": \"Rationale\",\n                          \"description\": \"The rationale for the conformance score.\"\n                        },\n                        \"mitigationStrategies\": {\n                          \"type\": \"array\",\n                          \"title\": \"Mitigation Strategies\",\n                          \"description\": \"The list of  `bom-ref` to the evidence provided describing the mitigation strategies.\",\n                          \"items\": { \"$ref\": \"#/definitions/refLinkType\" }\n                        }\n                      }\n                    },\n                    \"confidence\": {\n                      \"type\": \"object\",\n                      \"title\": \"Confidence\",\n                      \"description\": \"The confidence of the claim meeting the requirement.\",\n                      \"additionalProperties\": false,\n                      \"properties\": {\n                        \"score\": {\n                          \"type\": \"number\",\n                          \"minimum\": 0,\n                          \"maximum\": 1,\n                          \"title\": \"Score\",\n                          \"description\": \"The confidence of the claim between and inclusive of 0 and 1, where 1 is 100% confidence.\"\n                        },\n                        \"rationale\": {\n                          \"type\": \"string\",\n                          \"title\": \"Rationale\",\n                          \"description\": \"The rationale for the confidence score.\"\n                        }\n                      }\n                    }\n                  }\n                }\n              },\n              \"signature\": {\n                \"$ref\": \"#/definitions/signature\",\n                \"title\": \"Signature\",\n                \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n              }\n            }\n          }\n        },\n        \"claims\": {\n          \"type\": \"array\",\n          \"title\": \"Claims\",\n          \"description\": \"The list of claims.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"title\": \"Claim\",\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"bom-ref\": {\n                \"$ref\": \"#/definitions/refType\",\n                \"title\": \"BOM Reference\",\n                \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\"\n              },\n              \"target\": {\n                \"$ref\": \"#/definitions/refLinkType\",\n                \"title\": \"Target\",\n                \"description\": \"The `bom-ref` to a target representing a specific system, application, API, module, team, person, process, business unit, company, etc...  that this claim is being applied to.\"\n              },\n              \"predicate\": {\n                \"type\": \"string\",\n                \"title\": \"Predicate\",\n                \"description\": \"The specific statement or assertion about the target.\"\n              },\n              \"mitigationStrategies\": {\n                \"type\": \"array\",\n                \"title\": \"Mitigation Strategies\",\n                \"description\": \"The list of  `bom-ref` to the evidence provided describing the mitigation strategies. Each mitigation strategy should include an explanation of how any weaknesses in the evidence will be mitigated.\",\n                \"items\": { \"$ref\": \"#/definitions/refLinkType\" }\n              },\n              \"reasoning\": {\n                \"type\": \"string\",\n                \"title\": \"Reasoning\",\n                \"description\": \"The written explanation of why the evidence provided substantiates the claim.\"\n              },\n              \"evidence\": {\n                \"type\": \"array\",\n                \"title\": \"Evidence\",\n                \"description\": \"The list of `bom-ref` to evidence that supports this claim.\",\n                \"items\": { \"$ref\": \"#/definitions/refLinkType\" }\n              },\n              \"counterEvidence\": {\n                \"type\": \"array\",\n                \"title\": \"Counter Evidence\",\n                \"description\": \"The list of `bom-ref` to counterEvidence that supports this claim.\",\n                \"items\": { \"$ref\": \"#/definitions/refLinkType\" }\n              },\n              \"externalReferences\": {\n                \"type\": \"array\",\n                \"items\": {\"$ref\": \"#/definitions/externalReference\"},\n                \"title\": \"External References\",\n                \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n              },\n              \"signature\": {\n                \"$ref\": \"#/definitions/signature\",\n                \"title\": \"Signature\",\n                \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n              }\n            }\n          }\n        },\n        \"evidence\": {\n          \"type\": \"array\",\n          \"title\": \"Evidence\",\n          \"description\": \"The list of evidence\",\n          \"items\": {\n            \"type\": \"object\",\n            \"title\": \"Evidence\",\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"bom-ref\": {\n                \"$ref\": \"#/definitions/refType\",\n                \"title\": \"BOM Reference\",\n                \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\"\n              },\n              \"propertyName\": {\n                \"type\": \"string\",\n                \"title\": \"Property Name\",\n                \"description\": \"The reference to the property name as defined in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy/).\"\n              },\n              \"description\": {\n                \"type\": \"string\",\n                \"title\": \"Description\",\n                \"description\": \"The written description of what this evidence is and how it was created.\"\n              },\n              \"data\": {\n                \"type\": \"array\",\n                \"title\": \"Data\",\n                \"description\": \"The output or analysis that supports claims.\",\n                \"items\": {\n                  \"type\": \"object\",\n                  \"title\": \"Data\",\n                  \"additionalProperties\": false,\n                  \"properties\": {\n                    \"name\": {\n                      \"title\": \"Data Name\",\n                      \"description\": \"The name of the data.\",\n                      \"type\": \"string\"\n                    },\n                    \"contents\": {\n                      \"type\": \"object\",\n                      \"title\": \"Data Contents\",\n                      \"description\": \"The contents or references to the contents of the data being described.\",\n                      \"additionalProperties\": false,\n                      \"properties\": {\n                        \"attachment\": {\n                          \"title\": \"Data Attachment\",\n                          \"description\": \"A way to include textual or encoded data.\",\n                          \"$ref\": \"#/definitions/attachment\"\n                        },\n                        \"url\": {\n                          \"type\": \"string\",\n                          \"title\": \"Data URL\",\n                          \"description\": \"The URL to where the data can be retrieved.\",\n                          \"format\": \"iri-reference\"\n                        }\n                      }\n                    },\n                    \"classification\": {\n                      \"$ref\": \"#/definitions/dataClassification\"\n                    },\n                    \"sensitiveData\": {\n                      \"type\": \"array\",\n                      \"title\": \"Sensitive Data\",\n                      \"description\": \"A description of any sensitive data included.\",\n                      \"items\": {\n                        \"type\": \"string\"\n                      }\n                    },\n                    \"governance\": {\n                      \"title\": \"Data Governance\",\n                      \"$ref\": \"#/definitions/dataGovernance\"\n                    }\n                  }\n                }\n              },\n              \"created\": {\n                \"type\": \"string\",\n                \"format\": \"date-time\",\n                \"title\": \"Created\",\n                \"description\": \"The date and time (timestamp) when the evidence was created.\"\n              },\n              \"expires\": {\n                \"type\": \"string\",\n                \"format\": \"date-time\",\n                \"title\": \"Expires\",\n                \"description\": \"The date and time (timestamp) when the evidence is no longer valid.\"\n              },\n              \"author\": {\n                \"$ref\": \"#/definitions/organizationalContact\",\n                \"title\": \"Author\",\n                \"description\": \"The author of the evidence.\"\n              },\n              \"reviewer\": {\n                \"$ref\": \"#/definitions/organizationalContact\",\n                \"title\": \"Reviewer\",\n                \"description\": \"The reviewer of the evidence.\"\n              },\n              \"signature\": {\n                \"$ref\": \"#/definitions/signature\",\n                \"title\": \"Signature\",\n                \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n              }\n            }\n          }\n        },\n        \"targets\": {\n          \"type\": \"object\",\n          \"title\": \"Targets\",\n          \"description\": \"The list of targets which claims are made against.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"organizations\": {\n              \"type\": \"array\",\n              \"title\": \"Organizations\",\n              \"description\": \"The list of organizations which claims are made against.\",\n              \"items\": {\"$ref\": \"#/definitions/organizationalEntity\"}\n            },\n            \"components\": {\n              \"type\": \"array\",\n              \"title\": \"Components\",\n              \"description\": \"The list of components which claims are made against.\",\n              \"items\": {\"$ref\": \"#/definitions/component\"}\n            },\n            \"services\": {\n              \"type\": \"array\",\n              \"title\": \"Services\",\n              \"description\": \"The list of services which claims are made against.\",\n              \"items\": {\"$ref\": \"#/definitions/service\"}\n            }\n          }\n        },\n        \"affirmation\": {\n          \"type\": \"object\",\n          \"title\": \"Affirmation\",\n          \"description\": \"A concise statement affirmed by an individual regarding all declarations, often used for third-party auditor acceptance or recipient acknowledgment. It includes a list of authorized signatories who assert the validity of the document on behalf of the organization.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"statement\": {\n              \"type\": \"string\",\n              \"title\": \"Statement\",\n              \"description\": \"The brief statement affirmed by an individual regarding all declarations.\\n*- Notes This could be an affirmation of acceptance by a third-party auditor or receiving individual of a file.\",\n              \"examples\": [ \"I certify, to the best of my knowledge, that all information is correct.\" ]\n            },\n            \"signatories\": {\n              \"type\": \"array\",\n              \"title\": \"Signatories\",\n              \"description\": \"The list of signatories authorized on behalf of an organization to assert validity of this document.\",\n              \"items\": {\n                \"type\": \"object\",\n                \"title\": \"Signatory\",\n                \"additionalProperties\": false,\n                \"oneOf\": [\n                  {\n                    \"required\": [\"signature\"]\n                  },\n                  {\n                    \"required\": [\"externalReference\", \"organization\"]\n                  }\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"type\": \"string\",\n                    \"title\": \"Name\",\n                    \"description\": \"The signatory's name.\"\n                  },\n                  \"role\": {\n                    \"type\": \"string\",\n                    \"title\": \"Role\",\n                    \"description\": \"The signatory's role within an organization.\"\n                  },\n                  \"signature\": {\n                    \"$ref\": \"#/definitions/signature\",\n                    \"title\": \"Signature\",\n                    \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n                  },\n                  \"organization\": {\n                    \"$ref\": \"#/definitions/organizationalEntity\",\n                    \"title\": \"Organization\",\n                    \"description\": \"The signatory's organization.\"\n                  },\n                  \"externalReference\": {\n                    \"$ref\": \"#/definitions/externalReference\",\n                    \"title\": \"External Reference\",\n                    \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n                  }\n                }\n              }\n            },\n            \"signature\": {\n              \"$ref\": \"#/definitions/signature\",\n              \"title\": \"Signature\",\n              \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n            }\n          }\n        },\n        \"signature\": {\n          \"$ref\": \"#/definitions/signature\",\n          \"title\": \"Signature\",\n          \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n        }\n      }\n    },\n    \"definitions\": {\n      \"type\": \"object\",\n      \"title\": \"Definitions\",\n      \"description\": \"A collection of reusable objects that are defined and may be used elsewhere in the BOM.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"standards\": {\n          \"type\": \"array\",\n          \"title\": \"Standards\",\n          \"description\": \"The list of standards which may consist of regulations, industry or organizational-specific standards, maturity models, best practices, or any other requirements which can be evaluated against or attested to.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/standard\"\n          }\n        },\n        \"patents\": {\n          \"type\": \"array\",\n          \"title\": \"Patents\",\n          \"description\": \"The list of either individual patents or patent families.\",\n          \"items\": {\n            \"anyOf\": [\n              { \"$ref\": \"#/definitions/patent\" },\n              { \"$ref\": \"#/definitions/patentFamily\" }\n            ]\n          }\n        }\n      }\n    },\n    \"citations\": {\n      \"type\": \"array\",\n      \"items\": {\"$ref\": \"#/definitions/citation\"},\n      \"uniqueItems\": true,\n      \"title\": \"Citations\",\n      \"description\": \"A collection of attributions indicating which entity supplied information for specific fields within the BOM.\"\n    },\n    \"properties\": {\n      \"type\": \"array\",\n      \"title\": \"Properties\",\n      \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n      \"items\": {\n        \"$ref\": \"#/definitions/property\"\n      }\n    },\n    \"signature\": {\n      \"$ref\": \"#/definitions/signature\",\n      \"title\": \"Signature\",\n      \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n    }\n  },\n  \"definitions\": {\n    \"refType\": {\n      \"title\": \"BOM Reference\",\n      \"description\": \"Identifier for referable and therefore interlinkable elements.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\",\n      \"type\": \"string\",\n      \"minLength\": 1,\n      \"$comment\": \"TODO (breaking change): add a format constraint that prevents the value from staring with 'urn:cdx:'\"\n    },\n    \"refLinkType\": {\n      \"title\": \"BOM Reference\",\n      \"description\": \"Descriptor for an element identified by the attribute 'bom-ref' in the same BOM document.\\nIn contrast to `bomLinkElementType`.\",\n      \"$ref\": \"#/definitions/refType\"\n    },\n    \"bomLinkDocumentType\": {\n      \"title\": \"BOM-Link Document\",\n      \"description\": \"Descriptor for another BOM document. See https://cyclonedx.org/capabilities/bomlink/\",\n      \"type\": \"string\",\n      \"format\": \"iri-reference\",\n      \"pattern\": \"^urn:cdx:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[1-9][0-9]*$\",\n      \"$comment\": \"part of the pattern is based on `bom.serialNumber`'s pattern\"\n    },\n    \"bomLinkElementType\": {\n      \"title\": \"BOM-Link Element\",\n      \"description\": \"Descriptor for an element in a BOM document. See https://cyclonedx.org/capabilities/bomlink/\",\n      \"type\": \"string\",\n      \"format\": \"iri-reference\",\n      \"pattern\": \"^urn:cdx:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/[1-9][0-9]*#.+$\",\n      \"$comment\": \"part of the pattern is based on `bom.serialNumber`'s pattern\"\n    },\n    \"bomLink\": {\n      \"title\": \"BOM-Link\",\n      \"anyOf\": [\n        {\n          \"title\": \"BOM-Link Document\",\n          \"$ref\": \"#/definitions/bomLinkDocumentType\"\n        },\n        {\n          \"title\": \"BOM-Link Element\",\n          \"$ref\": \"#/definitions/bomLinkElementType\"\n        }\n      ]\n    },\n    \"metadata\": {\n      \"type\": \"object\",\n      \"title\": \"BOM Metadata\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"timestamp\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Timestamp\",\n          \"description\": \"The date and time (timestamp) when the BOM was created.\"\n        },\n        \"lifecycles\": {\n          \"type\": \"array\",\n          \"title\": \"Lifecycles\",\n          \"description\": \"Lifecycles communicate the stage(s) in which data in the BOM was captured. Different types of data may be available at various phases of a lifecycle, such as the Software Development Lifecycle (SDLC), IT Asset Management (ITAM), and Software Asset Management (SAM). Thus, a BOM may include data specific to or only obtainable in a given lifecycle.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"title\": \"Lifecycle\",\n            \"description\": \"The product lifecycle(s) that this BOM represents.\",\n            \"oneOf\": [\n              {\n                \"title\": \"Pre-Defined Phase\",\n                \"required\": [\"phase\"],\n                \"additionalProperties\": false,\n                \"properties\": {\n                  \"phase\": {\n                    \"type\": \"string\",\n                    \"title\": \"Phase\",\n                    \"description\": \"A pre-defined phase in the product lifecycle.\",\n                    \"enum\": [\n                      \"design\",\n                      \"pre-build\",\n                      \"build\",\n                      \"post-build\",\n                      \"operations\",\n                      \"discovery\",\n                      \"decommission\"\n                    ],\n                    \"meta:enum\": {\n                      \"design\": \"BOM produced early in the development lifecycle containing an inventory of components and services that are proposed or planned to be used. The inventory may need to be procured, retrieved, or resourced prior to use.\",\n                      \"pre-build\": \"BOM consisting of information obtained prior to a build process and may contain source files and development artifacts and manifests. The inventory may need to be resolved and retrieved prior to use.\",\n                      \"build\": \"BOM consisting of information obtained during a build process where component inventory is available for use. The precise versions of resolved components are usually available at this time as well as the provenance of where the components were retrieved from.\",\n                      \"post-build\": \"BOM consisting of information obtained after a build process has completed and the resulting components(s) are available for further analysis. Built components may exist as the result of a CI/CD process, may have been installed or deployed to a system or device, and may need to be retrieved or extracted from the system or device.\",\n                      \"operations\": \"BOM produced that represents inventory that is running and operational. This may include staging or production environments and will generally encompass multiple SBOMs describing the applications and operating system, along with HBOMs describing the hardware that makes up the system. Operations Bill of Materials (OBOM) can provide full-stack inventory of runtime environments, configurations, and additional dependencies.\",\n                      \"discovery\": \"BOM consisting of information observed through network discovery providing point-in-time enumeration of embedded, on-premise, and cloud-native services such as server applications, connected devices, microservices, and serverless functions.\",\n                      \"decommission\": \"BOM containing inventory that will be, or has been retired from operations.\"\n                    }\n                  }\n                }\n              },\n              {\n                \"title\": \"Custom Phase\",\n                \"required\": [\"name\"],\n                \"additionalProperties\": false,\n                \"properties\": {\n                  \"name\": {\n                    \"type\": \"string\",\n                    \"title\": \"Name\",\n                    \"description\": \"The name of the lifecycle phase\"\n                  },\n                  \"description\": {\n                    \"type\": \"string\",\n                    \"title\": \"Description\",\n                    \"description\": \"The description of the lifecycle phase\"\n                  }\n                }\n              }\n            ]\n          }\n        },\n        \"tools\": {\n          \"title\": \"Tools\",\n          \"description\": \"The tool(s) used in the creation, enrichment, and validation of the BOM.\",\n          \"oneOf\": [\n            {\n              \"type\": \"object\",\n              \"title\": \"Tools\",\n              \"description\": \"The tool(s) used in the creation, enrichment, and validation of the BOM.\",\n              \"additionalProperties\": false,\n              \"properties\": {\n                \"components\": {\n                  \"type\": \"array\",\n                  \"items\": {\"$ref\": \"#/definitions/component\"},\n                  \"uniqueItems\": true,\n                  \"title\": \"Components\",\n                  \"description\": \"A list of software and hardware components used as tools.\"\n                },\n                \"services\": {\n                  \"type\": \"array\",\n                  \"items\": {\"$ref\": \"#/definitions/service\"},\n                  \"uniqueItems\": true,\n                  \"title\": \"Services\",\n                  \"description\": \"A list of services used as tools. This may include microservices, function-as-a-service, and other types of network or intra-process services.\"\n                }\n              }\n            },\n            {\n              \"type\": \"array\",\n              \"title\": \"Tools (legacy)\",\n              \"description\": \"[Deprecated]\\nThe tool(s) used in the creation, enrichment, and validation of the BOM.\",\n              \"deprecated\": true,\n              \"items\": {\"$ref\": \"#/definitions/tool\"}\n            }\n          ]\n        },\n        \"manufacturer\": {\n          \"title\": \"BOM Manufacturer\",\n          \"description\": \"The organization that created the BOM.\\nManufacturer is common in BOMs created through automated processes. BOMs created through manual means may have `@.authors` instead.\",\n          \"$ref\": \"#/definitions/organizationalEntity\"\n        },\n        \"authors\": {\n          \"type\": \"array\",\n          \"title\": \"BOM Authors\",\n          \"description\": \"The person(s) who created the BOM.\\nAuthors are common in BOMs created through manual processes. BOMs created through automated means may have `@.manufacturer` instead.\",\n          \"items\": {\"$ref\": \"#/definitions/organizationalContact\"}\n        },\n        \"component\": {\n          \"title\": \"Component\",\n          \"description\": \"The component that the BOM describes.\",\n          \"$ref\": \"#/definitions/component\"\n        },\n        \"manufacture\": {\n          \"deprecated\": true,\n          \"title\": \"Component Manufacture (legacy)\",\n          \"description\": \"[Deprecated] This will be removed in a future version. Use the `@.component.manufacturer` instead.\\nThe organization that manufactured the component that the BOM describes.\",\n          \"$ref\": \"#/definitions/organizationalEntity\"\n        },\n        \"supplier\": {\n          \"title\": \"Supplier\",\n          \"description\": \" The organization that supplied the component that the BOM describes. The supplier may often be the manufacturer, but may also be a distributor or repackager.\",\n          \"$ref\": \"#/definitions/organizationalEntity\"\n        },\n        \"licenses\": {\n          \"title\": \"BOM License(s)\",\n          \"description\": \"The license information for the BOM document.\\nThis may be different from the license(s) of the component(s) that the BOM describes.\",\n          \"$ref\": \"#/definitions/licenseChoice\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\"$ref\": \"#/definitions/property\"}\n        },\n        \"distributionConstraints\": {\n          \"title\": \"Distribution Constraints\",\n          \"description\": \"Conditions and constraints governing the sharing and distribution of the data or components described by this BOM.\",\n          \"type\": \"object\",\n          \"properties\": {\n            \"tlp\": {\n              \"$ref\": \"#/definitions/tlpClassification\",\n              \"description\": \"The Traffic Light Protocol (TLP) classification that controls the sharing and distribution of the data that the BOM describes.\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      }\n    },\n    \"tlpClassification\": {\n      \"title\": \"Traffic Light Protocol (TLP) Classification\",\n      \"description\": \"Traffic Light Protocol (TLP) is a classification system for identifying the potential risk associated with artefact, including whether it is subject to certain types of legal, financial, or technical threats. Refer to [https://www.first.org/tlp/](https://www.first.org/tlp/) for further information.\\nThe default classification is \\\"CLEAR\\\"\",\n      \"type\" : \"string\",\n      \"default\": \"CLEAR\",\n      \"enum\": [\n        \"CLEAR\",\n        \"GREEN\",\n        \"AMBER\",\n        \"AMBER_AND_STRICT\",\n        \"RED\"\n      ],\n      \"meta:enum\": {\n        \"CLEAR\": \"The information is not subject to any restrictions as regards the sharing.\",\n        \"GREEN\": \"The information is subject to limited disclosure, and recipients can share it within their community but not via publicly accessible channels.\",\n        \"AMBER\": \"The information is subject to limited disclosure, and recipients can only share it on a need-to-know basis within their organization and with clients.\",\n        \"AMBER_AND_STRICT\": \"The information is subject to limited disclosure, and recipients can only share it on a need-to-know basis within their organization.\",\n        \"RED\": \"The information is subject to restricted distribution to individual recipients only and must not be shared.\"\n      }\n    },\n    \"tool\": {\n      \"type\": \"object\",\n      \"title\": \"Tool\",\n      \"description\": \"[Deprecated] This will be removed in a future version. Use component or service instead.\\nInformation about the automated or manual tool used\",\n      \"additionalProperties\": false,\n      \"deprecated\": true,\n      \"properties\": {\n        \"vendor\": {\n          \"type\": \"string\",\n          \"title\": \"Tool Vendor\",\n          \"description\": \"The name of the vendor who created the tool\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Tool Name\",\n          \"description\": \"The name of the tool\"\n        },\n        \"version\": {\n          \"$ref\": \"#/definitions/version\",\n          \"title\": \"Tool Version\",\n          \"description\": \"The version of the tool\"\n        },\n        \"hashes\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/hash\"},\n          \"title\": \"Hashes\",\n          \"description\": \"The hashes of the tool (if applicable).\"\n        },\n        \"externalReferences\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/externalReference\"},\n          \"title\": \"External References\",\n          \"description\": \"External references provide a way to document systems, sites, and information that may be relevant, but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n        }\n      }\n    },\n    \"organizationalEntity\": {\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Organization Name\",\n          \"description\": \"The name of the organization\",\n          \"examples\": [\n            \"Example Inc.\"\n          ]\n        },\n        \"address\": {\n          \"$ref\": \"#/definitions/postalAddress\",\n          \"title\": \"Organization Address\",\n          \"description\": \"The physical address (location) of the organization\"\n        },\n        \"url\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\",\n            \"format\": \"iri-reference\"\n          },\n          \"title\": \"Organization URL(s)\",\n          \"description\": \"The URL of the organization. Multiple URLs are allowed.\",\n          \"examples\": [\"https://example.com\"]\n        },\n        \"contact\": {\n          \"type\": \"array\",\n          \"title\": \"Organizational Contact\",\n          \"description\": \"A contact at the organization. Multiple contacts are allowed.\",\n          \"items\": {\"$ref\": \"#/definitions/organizationalContact\"}\n        }\n      }\n    },\n    \"organizationalContact\": {\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"title\": \"Organizational Person\",\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"The name of a contact\",\n          \"examples\": [\"Contact name\"]\n        },\n        \"email\": {\n          \"type\": \"string\",\n          \"format\": \"idn-email\",\n          \"title\": \"Email Address\",\n          \"description\": \"The email address of the contact.\",\n          \"examples\": [\"firstname.lastname@example.com\"]\n        },\n        \"phone\": {\n          \"type\": \"string\",\n          \"title\": \"Phone\",\n          \"description\": \"The phone number of the contact.\",\n          \"examples\": [\"800-555-1212\"]\n        }\n      }\n    },\n    \"component\": {\n      \"type\": \"object\",\n      \"title\": \"Component\",\n      \"required\": [\n        \"type\",\n        \"name\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"type\": {\n          \"type\": \"string\",\n          \"enum\": [\n            \"application\",\n            \"framework\",\n            \"library\",\n            \"container\",\n            \"platform\",\n            \"operating-system\",\n            \"device\",\n            \"device-driver\",\n            \"firmware\",\n            \"file\",\n            \"machine-learning-model\",\n            \"data\",\n            \"cryptographic-asset\"\n          ],\n          \"meta:enum\": {\n            \"application\": \"A software application. Refer to [https://en.wikipedia.org/wiki/Application_software](https://en.wikipedia.org/wiki/Application_software) for information about applications.\",\n            \"framework\": \"A software framework. Refer to [https://en.wikipedia.org/wiki/Software_framework](https://en.wikipedia.org/wiki/Software_framework) for information on how frameworks vary slightly from libraries.\",\n            \"library\": \"A software library. Refer to [https://en.wikipedia.org/wiki/Library_(computing)](https://en.wikipedia.org/wiki/Library_(computing)) for information about libraries. All third-party and open source reusable components will likely be a library. If the library also has key features of a framework, then it should be classified as a framework. If not, or is unknown, then specifying library is recommended.\",\n            \"container\": \"A packaging and/or runtime format, not specific to any particular technology, which isolates software inside the container from software outside of a container through virtualization technology. Refer to [https://en.wikipedia.org/wiki/OS-level_virtualization](https://en.wikipedia.org/wiki/OS-level_virtualization).\",\n            \"platform\": \"A runtime environment that interprets or executes software. This may include runtimes such as those that execute bytecode, just-in-time compilers, interpreters, or low-code/no-code application platforms.\",\n            \"operating-system\": \"A software operating system without regard to deployment model (i.e. installed on physical hardware, virtual machine, image, etc) Refer to [https://en.wikipedia.org/wiki/Operating_system](https://en.wikipedia.org/wiki/Operating_system).\",\n            \"device\": \"A hardware device such as a processor or chip-set. A hardware device containing firmware SHOULD include a component for the physical hardware itself and another component of type 'firmware' or 'operating-system' (whichever is relevant), describing information about the software running on the device. See also the list of [known device properties](https://github.com/CycloneDX/cyclonedx-property-taxonomy/blob/main/cdx/device.md).\",\n            \"device-driver\": \"A special type of software that operates or controls a particular type of device. Refer to [https://en.wikipedia.org/wiki/Device_driver](https://en.wikipedia.org/wiki/Device_driver).\",\n            \"firmware\": \"A special type of software that provides low-level control over a device's hardware. Refer to [https://en.wikipedia.org/wiki/Firmware](https://en.wikipedia.org/wiki/Firmware).\",\n            \"file\": \"A computer file. Refer to [https://en.wikipedia.org/wiki/Computer_file](https://en.wikipedia.org/wiki/Computer_file) for information about files.\",\n            \"machine-learning-model\": \"A model based on training data that can make predictions or decisions without being explicitly programmed to do so.\",\n            \"data\": \"A collection of discrete values that convey information.\",\n            \"cryptographic-asset\": \"A cryptographic asset including algorithms, protocols, certificates, keys, tokens, and secrets.\"\n          },\n          \"title\": \"Component Type\",\n          \"description\": \"Specifies the type of component. For software components, classify as application if no more specific appropriate classification is available or cannot be determined for the component.\",\n          \"examples\": [\"library\"]\n        },\n        \"mime-type\": {\n          \"type\": \"string\",\n          \"title\": \"Mime-Type\",\n          \"description\": \"The mime-type of the component. When used on file components, the mime-type can provide additional context about the kind of file being represented, such as an image, font, or executable. Some library or framework components may also have an associated mime-type.\",\n          \"examples\": [\"image/jpeg\"],\n          \"pattern\": \"^[-+a-z0-9.]+/[-+a-z0-9.]+$\"\n        },\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the component elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"supplier\": {\n          \"title\": \"Component Supplier\",\n          \"description\": \" The organization that supplied the component. The supplier may often be the manufacturer, but may also be a distributor or repackager.\",\n          \"$ref\": \"#/definitions/organizationalEntity\"\n        },\n        \"manufacturer\": {\n          \"title\": \"Component Manufacturer\",\n          \"description\": \"The organization that created the component.\\nManufacturer is common in components created through automated processes. Components created through manual means may have `@.authors` instead.\",\n          \"$ref\": \"#/definitions/organizationalEntity\"\n        },\n        \"authors\" :{\n          \"type\": \"array\",\n          \"title\": \"Component Authors\",\n          \"description\": \"The person(s) who created the component.\\nAuthors are common in components created through manual processes. Components created through automated means may have `@.manufacturer` instead.\",\n          \"items\": {\"$ref\": \"#/definitions/organizationalContact\"}\n        },\n        \"author\": {\n          \"deprecated\": true,\n          \"type\": \"string\",\n          \"title\": \"Component Author (legacy)\",\n          \"description\": \"[Deprecated] This will be removed in a future version. Use `@.authors` or `@.manufacturer` instead.\\nThe person(s) or organization(s) that authored the component\",\n          \"examples\": [\"Acme Inc\"]\n        },\n        \"publisher\": {\n          \"type\": \"string\",\n          \"title\": \"Component Publisher\",\n          \"description\": \"The person(s) or organization(s) that published the component\",\n          \"examples\": [\"Acme Inc\"]\n        },\n        \"group\": {\n          \"type\": \"string\",\n          \"title\": \"Component Group\",\n          \"description\": \"The grouping name or identifier. This will often be a shortened, single name of the company or project that produced the component, or the source package or domain name. Whitespace and special characters should be avoided. Examples include: apache, org.apache.commons, and apache.org.\",\n          \"examples\": [\"com.acme\"]\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Component Name\",\n          \"description\": \"The name of the component. This will often be a shortened, single name of the component. Examples: commons-lang3 and jquery\",\n          \"examples\": [\"tomcat-catalina\"]\n        },\n        \"version\": {\n          \"$ref\": \"#/definitions/version\",\n          \"title\": \"Component Version\",\n          \"description\": \"The component version. The version should ideally comply with semantic versioning but is not enforced.\\nMust be used exclusively, either 'version' or 'versionRange', but not both.\"\n        },\n        \"versionRange\": {\n          \"$ref\": \"#/definitions/versionRange\",\n          \"title\": \"Component Version Range\",\n          \"description\": \"For an external component, this specifies the accepted version range.\\nThe value must adhere to the Package URL Version Range syntax (vers), as defined at <https://github.com/package-url/vers-spec\\nMay only be used if `.isExternal` is set to `true`.\\nMust be used exclusively, either 'version' or 'versionRange', but not both.\"\n        },\n        \"isExternal\": {\n          \"type\": \"boolean\",\n          \"title\": \"Component Is External\",\n          \"description\": \"Determine whether this component is external.\\nAn external component is one that is not part of an assembly, but is expected to be provided by the environment, regardless of the component's `.scope`. This setting can be useful for distinguishing which components are bundled with the product and which can be relied upon to be present in the deployment environment.\\nThis may be set to `true` for runtime components only. For `$.metadata.component`, it must be set to `false`.\",\n          \"default\": false\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"title\": \"Component Description\",\n          \"description\": \"Specifies a description for the component\"\n        },\n        \"scope\": {\n          \"type\": \"string\",\n          \"enum\": [\n            \"required\",\n            \"optional\",\n            \"excluded\"\n          ],\n          \"meta:enum\": {\n            \"required\": \"The component is required for runtime\",\n            \"optional\": \"The component is optional at runtime. Optional components are components that are not capable of being called due to them not being installed or otherwise accessible by any means. Components that are installed but due to configuration or other restrictions are prohibited from being called must be scoped as 'required'.\",\n            \"excluded\": \"Components that are excluded provide the ability to document component usage for test and other non-runtime purposes. Excluded components are not reachable within a call graph at runtime.\"\n          },\n          \"title\": \"Component Scope\",\n          \"description\": \"Specifies the scope of the component. If scope is not specified, 'required' scope SHOULD be assumed by the consumer of the BOM.\",\n          \"default\": \"required\"\n        },\n        \"hashes\": {\n          \"type\": \"array\",\n          \"title\": \"Component Hashes\",\n          \"description\": \"The hashes of the component.\",\n          \"items\": {\"$ref\": \"#/definitions/hash\"}\n        },\n        \"licenses\": {\n          \"$ref\": \"#/definitions/licenseChoice\",\n          \"title\": \"Component License(s)\"\n        },\n        \"copyright\": {\n          \"type\": \"string\",\n          \"title\": \"Component Copyright\",\n          \"description\": \"A copyright notice informing users of the underlying claims to copyright ownership in a published work.\",\n          \"examples\": [\"Acme Inc\"]\n        },\n        \"patentAssertions\": {\n          \"$ref\": \"#/definitions/patentAssertions\",\n          \"title\": \"Component Patent(s)\"\n        },\n        \"cpe\": {\n          \"type\": \"string\",\n          \"title\": \"Common Platform Enumeration (CPE)\",\n          \"description\": \"Asserts the identity of the component using CPE. The CPE must conform to the CPE 2.2 or 2.3 specification. See [https://nvd.nist.gov/products/cpe](https://nvd.nist.gov/products/cpe). Refer to `@.evidence.identity` to optionally provide evidence that substantiates the assertion of the component's identity.\",\n          \"examples\": [\"cpe:2.3:a:acme:component_framework:-:*:*:*:*:*:*:*\"]\n        },\n        \"purl\": {\n          \"type\": \"string\",\n          \"title\": \"Package URL (purl)\",\n          \"description\": \"Asserts the identity of the component using package-url (purl). The purl, if specified, must be valid and conform to the specification defined at: [https://github.com/package-url/purl-spec](https://github.com/package-url/purl-spec). Refer to `@.evidence.identity` to optionally provide evidence that substantiates the assertion of the component's identity.\",\n          \"examples\": [\"pkg:maven/com.acme/tomcat-catalina@9.0.14?packaging=jar\"]\n        },\n        \"omniborId\": {\n          \"type\": \"array\",\n          \"title\": \"OmniBOR Artifact Identifier (gitoid)\",\n          \"description\": \"Asserts the identity of the component using the OmniBOR Artifact ID. The OmniBOR, if specified, must be valid and conform to the specification defined at: [https://www.iana.org/assignments/uri-schemes/prov/gitoid](https://www.iana.org/assignments/uri-schemes/prov/gitoid). Refer to `@.evidence.identity` to optionally provide evidence that substantiates the assertion of the component's identity.\",\n          \"items\": { \"type\": \"string\" },\n          \"examples\": [\n            \"gitoid:blob:sha1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3\",\n            \"gitoid:blob:sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"\n          ]\n        },\n        \"swhid\": {\n          \"type\": \"array\",\n          \"title\": \"Software Heritage Identifier\",\n          \"description\": \"Asserts the identity of the component using the Software Heritage persistent identifier (SWHID). The SWHID, if specified, must be valid and conform to the specification defined at: [https://docs.softwareheritage.org/devel/swh-model/persistent-identifiers.html](https://docs.softwareheritage.org/devel/swh-model/persistent-identifiers.html). Refer to `@.evidence.identity` to optionally provide evidence that substantiates the assertion of the component's identity.\",\n          \"items\": { \"type\": \"string\" },\n          \"examples\": [\"swh:1:cnt:94a9ed024d3859793618152ea559a168bbcbb5e2\"]\n        },\n        \"swid\": {\n          \"$ref\": \"#/definitions/swid\",\n          \"title\": \"SWID Tag\",\n          \"description\": \"Asserts the identity of the component using [ISO-IEC 19770-2 Software Identification (SWID) Tags](https://www.iso.org/standard/65666.html). Refer to `@.evidence.identity` to optionally provide evidence that substantiates the assertion of the component's identity.\"\n        },\n        \"modified\": {\n          \"type\": \"boolean\",\n          \"title\": \"Component Modified From Original\",\n          \"description\": \"[Deprecated] This will be removed in a future version. Use the pedigree element instead to supply information on exactly how the component was modified.\\nA boolean value indicating if the component has been modified from the original. A value of true indicates the component is a derivative of the original. A value of false indicates the component has not been modified from the original.\",\n          \"deprecated\": true\n        },\n        \"pedigree\": {\n          \"type\": \"object\",\n          \"title\": \"Component Pedigree\",\n          \"description\": \"Component pedigree is a way to document complex supply chain scenarios where components are created, distributed, modified, redistributed, combined with other components, etc. Pedigree supports viewing this complex chain from the beginning, the end, or anywhere in the middle. It also provides a way to document variants where the exact relation may not be known.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"ancestors\": {\n              \"type\": \"array\",\n              \"title\": \"Ancestors\",\n              \"description\": \"Describes zero or more components in which a component is derived from. This is commonly used to describe forks from existing projects where the forked version contains a ancestor node containing the original component it was forked from. For example, Component A is the original component. Component B is the component being used and documented in the BOM. However, Component B contains a pedigree node with a single ancestor documenting Component A - the original component from which Component B is derived from.\",\n              \"items\": {\"$ref\": \"#/definitions/component\"}\n            },\n            \"descendants\": {\n              \"type\": \"array\",\n              \"title\": \"Descendants\",\n              \"description\": \"Descendants are the exact opposite of ancestors. This provides a way to document all forks (and their forks) of an original or root component.\",\n              \"items\": {\"$ref\": \"#/definitions/component\"}\n            },\n            \"variants\": {\n              \"type\": \"array\",\n              \"title\": \"Variants\",\n              \"description\": \"Variants describe relations where the relationship between the components is not known. For example, if Component A contains nearly identical code to Component B. They are both related, but it is unclear if one is derived from the other, or if they share a common ancestor.\",\n              \"items\": {\"$ref\": \"#/definitions/component\"}\n            },\n            \"commits\": {\n              \"type\": \"array\",\n              \"title\": \"Commits\",\n              \"description\": \"A list of zero or more commits which provide a trail describing how the component deviates from an ancestor, descendant, or variant.\",\n              \"items\": {\"$ref\": \"#/definitions/commit\"}\n            },\n            \"patches\": {\n              \"type\": \"array\",\n              \"title\": \"Patches\",\n              \"description\": \">A list of zero or more patches describing how the component deviates from an ancestor, descendant, or variant. Patches may be complementary to commits or may be used in place of commits.\",\n              \"items\": {\"$ref\": \"#/definitions/patch\"}\n            },\n            \"notes\": {\n              \"type\": \"string\",\n              \"title\": \"Notes\",\n              \"description\": \"Notes, observations, and other non-structured commentary describing the components pedigree.\"\n            }\n          }\n        },\n        \"externalReferences\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/externalReference\"},\n          \"title\": \"External References\",\n          \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n        },\n        \"components\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/component\"},\n          \"uniqueItems\": true,\n          \"title\": \"Components\",\n          \"description\": \"A list of software and hardware components included in the parent component. This is not a dependency tree. It provides a way to specify a hierarchical representation of component assemblies, similar to system &#8594; subsystem &#8594; parts assembly in physical supply chains.\"\n        },\n        \"evidence\": {\n          \"$ref\": \"#/definitions/componentEvidence\",\n          \"title\": \"Evidence\",\n          \"description\": \"Provides the ability to document evidence collected through various forms of extraction or analysis.\"\n        },\n        \"releaseNotes\": {\n          \"$ref\": \"#/definitions/releaseNotes\",\n          \"title\": \"Release notes\",\n          \"description\": \"Specifies release notes.\"\n        },\n        \"modelCard\": {\n          \"$ref\": \"#/definitions/modelCard\",\n          \"title\": \"AI/ML Model Card\"\n        },\n        \"data\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/componentData\"},\n          \"title\": \"Data\",\n          \"description\": \"This object SHOULD be specified for any component of type `data` and must not be specified for other component types.\"\n        },\n        \"cryptoProperties\": {\n          \"$ref\": \"#/definitions/cryptoProperties\",\n          \"title\": \"Cryptographic Properties\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\"$ref\": \"#/definitions/property\"}\n        },\n        \"tags\": {\n          \"$ref\": \"#/definitions/tags\",\n          \"title\": \"Tags\"\n        },\n        \"signature\": {\n          \"$ref\": \"#/definitions/signature\",\n          \"title\": \"Signature\",\n          \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n        }\n      },\n      \"allOf\": [\n        {\n          \"description\": \"Requirement: ensure that `version` and `versionRange` are not present simultaneously.\",\n          \"not\": {\n            \"required\": [\"version\", \"versionRange\"]\n          }\n        },\n        {\n          \"description\": \"Requirement: 'versionRange' must not be present when 'isExternal' is `false`.\",\n          \"if\": {\n            \"properties\": { \"isExternal\": { \"const\": false } }\n          },\n          \"then\": {\n            \"not\": { \"required\": [\"versionRange\"] }\n          },\n          \"else\": true\n        }\n      ]\n    },\n    \"swid\": {\n      \"type\": \"object\",\n      \"title\": \"SWID Tag\",\n      \"description\": \"Specifies metadata and content for ISO-IEC 19770-2 Software Identification (SWID) Tags.\",\n      \"required\": [\n        \"tagId\",\n        \"name\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"tagId\": {\n          \"type\": \"string\",\n          \"title\": \"Tag ID\",\n          \"description\": \"Maps to the tagId of a SoftwareIdentity.\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"Maps to the name of a SoftwareIdentity.\"\n        },\n        \"version\": {\n          \"type\": \"string\",\n          \"title\": \"Version\",\n          \"default\": \"0.0\",\n          \"description\": \"Maps to the version of a SoftwareIdentity.\"\n        },\n        \"tagVersion\": {\n          \"type\": \"integer\",\n          \"title\": \"Tag Version\",\n          \"default\": 0,\n          \"description\": \"Maps to the tagVersion of a SoftwareIdentity.\"\n        },\n        \"patch\": {\n          \"type\": \"boolean\",\n          \"title\": \"Patch\",\n          \"default\": false,\n          \"description\": \"Maps to the patch of a SoftwareIdentity.\"\n        },\n        \"text\": {\n          \"title\": \"Attachment text\",\n          \"description\": \"Specifies the metadata and content of the SWID tag.\",\n          \"$ref\": \"#/definitions/attachment\"\n        },\n        \"url\": {\n          \"type\": \"string\",\n          \"title\": \"URL\",\n          \"description\": \"The URL to the SWID file.\",\n          \"format\": \"iri-reference\"\n        }\n      }\n    },\n    \"attachment\": {\n      \"type\": \"object\",\n      \"title\": \"Attachment\",\n      \"description\": \"Specifies the metadata and content for an attachment.\",\n      \"required\": [\n        \"content\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"contentType\": {\n          \"type\": \"string\",\n          \"title\": \"Content-Type\",\n          \"description\": \"Specifies the format and nature of the data being attached, helping systems correctly interpret and process the content. Common content type examples include `application/json` for JSON data and `text/plain` for plan text documents.\\n [RFC 2045 section 5.1](https://www.ietf.org/rfc/rfc2045.html#section-5.1) outlines the structure and use of content types. For a comprehensive list of registered content types, refer to the [IANA media types registry](https://www.iana.org/assignments/media-types/media-types.xhtml).\",\n          \"default\": \"text/plain\",\n          \"examples\": [\n            \"text/plain\",\n            \"application/json\",\n            \"image/png\"\n          ]\n        },\n        \"encoding\": {\n          \"type\": \"string\",\n          \"title\": \"Encoding\",\n          \"description\": \"Specifies the encoding the text is represented in.\",\n          \"enum\": [\n            \"base64\"\n          ],\n          \"meta:enum\": {\n            \"base64\": \"Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string.\"\n          }\n        },\n        \"content\": {\n          \"type\": \"string\",\n          \"title\": \"Attachment Text\",\n          \"description\": \"The attachment data. Proactive controls such as input validation and sanitization should be employed to prevent misuse of attachment text.\"\n        }\n      }\n    },\n    \"hash\": {\n      \"type\": \"object\",\n      \"title\": \"Hash\",\n      \"required\": [\n        \"alg\",\n        \"content\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"alg\": {\n          \"$ref\": \"#/definitions/hash-alg\"\n        },\n        \"content\": {\n          \"$ref\": \"#/definitions/hash-content\"\n        }\n      }\n    },\n    \"hash-alg\": {\n      \"type\": \"string\",\n      \"title\": \"Hash Algorithm\",\n      \"description\": \"The algorithm that generated the hash value.\",\n      \"enum\": [\n        \"MD5\",\n        \"SHA-1\",\n        \"SHA-256\",\n        \"SHA-384\",\n        \"SHA-512\",\n        \"SHA3-256\",\n        \"SHA3-384\",\n        \"SHA3-512\",\n        \"BLAKE2b-256\",\n        \"BLAKE2b-384\",\n        \"BLAKE2b-512\",\n        \"BLAKE3\",\n        \"Streebog-256\",\n        \"Streebog-512\"\n      ]\n    },\n    \"hash-content\": {\n      \"type\": \"string\",\n      \"title\": \"Hash Value\",\n      \"description\": \"The value of the hash.\",\n      \"examples\": [\"3942447fac867ae5cdb3229b658f4d48\"],\n      \"pattern\": \"^([a-fA-F0-9]{32}|[a-fA-F0-9]{40}|[a-fA-F0-9]{64}|[a-fA-F0-9]{96}|[a-fA-F0-9]{128})$\"\n    },\n    \"licensing\": {\n      \"type\": \"object\",\n      \"title\": \"Licensing information\",\n      \"description\": \"Licensing details describing the licensor/licensee, license type, renewal and expiration dates, and other important metadata\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"altIds\": {\n          \"type\": \"array\",\n          \"title\": \"Alternate License Identifiers\",\n          \"description\": \"License identifiers that may be used to manage licenses and their lifecycle\",\n          \"items\": {\n            \"type\": \"string\"\n          }\n        },\n        \"licensor\": {\n          \"title\": \"Licensor\",\n          \"description\": \"The individual or organization that grants a license to another individual or organization\",\n          \"type\": \"object\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"organization\": {\n              \"title\": \"Licensor (Organization)\",\n              \"description\": \"The organization that granted the license\",\n              \"$ref\": \"#/definitions/organizationalEntity\"\n            },\n            \"individual\": {\n              \"title\": \"Licensor (Individual)\",\n              \"description\": \"The individual, not associated with an organization, that granted the license\",\n              \"$ref\": \"#/definitions/organizationalContact\"\n            }\n          },\n          \"oneOf\":[\n            {\n              \"required\": [\"organization\"]\n            },\n            {\n              \"required\": [\"individual\"]\n            }\n          ]\n        },\n        \"licensee\": {\n          \"title\": \"Licensee\",\n          \"description\": \"The individual or organization for which a license was granted to\",\n          \"type\": \"object\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"organization\": {\n              \"title\": \"Licensee (Organization)\",\n              \"description\": \"The organization that was granted the license\",\n              \"$ref\": \"#/definitions/organizationalEntity\"\n            },\n            \"individual\": {\n              \"title\": \"Licensee (Individual)\",\n              \"description\": \"The individual, not associated with an organization, that was granted the license\",\n              \"$ref\": \"#/definitions/organizationalContact\"\n            }\n          },\n          \"oneOf\":[\n            {\n              \"required\": [\"organization\"]\n            },\n            {\n              \"required\": [\"individual\"]\n            }\n          ]\n        },\n        \"purchaser\": {\n          \"title\": \"Purchaser\",\n          \"description\": \"The individual or organization that purchased the license\",\n          \"type\": \"object\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"organization\": {\n              \"title\": \"Purchaser (Organization)\",\n              \"description\": \"The organization that purchased the license\",\n              \"$ref\": \"#/definitions/organizationalEntity\"\n            },\n            \"individual\": {\n              \"title\": \"Purchaser (Individual)\",\n              \"description\": \"The individual, not associated with an organization, that purchased the license\",\n              \"$ref\": \"#/definitions/organizationalContact\"\n            }\n          },\n          \"oneOf\":[\n            {\n              \"required\": [\"organization\"]\n            },\n            {\n              \"required\": [\"individual\"]\n            }\n          ]\n        },\n        \"purchaseOrder\": {\n          \"type\": \"string\",\n          \"title\": \"Purchase Order\",\n          \"description\": \"The purchase order identifier the purchaser sent to a supplier or vendor to authorize a purchase\"\n        },\n        \"licenseTypes\": {\n          \"type\": \"array\",\n          \"title\": \"License Type\",\n          \"description\": \"The type of license(s) that was granted to the licensee.\",\n          \"items\": {\n            \"type\": \"string\",\n            \"enum\": [\n              \"academic\",\n              \"appliance\",\n              \"client-access\",\n              \"concurrent-user\",\n              \"core-points\",\n              \"custom-metric\",\n              \"device\",\n              \"evaluation\",\n              \"named-user\",\n              \"node-locked\",\n              \"oem\",\n              \"perpetual\",\n              \"processor-points\",\n              \"subscription\",\n              \"user\",\n              \"other\"\n            ],\n            \"meta:enum\": {\n              \"academic\": \"A license that grants use of software solely for the purpose of education or research.\",\n              \"appliance\": \"A license covering use of software embedded in a specific piece of hardware.\",\n              \"client-access\": \"A Client Access License (CAL) allows client computers to access services provided by server software.\",\n              \"concurrent-user\": \"A Concurrent User license (aka floating license) limits the number of licenses for a software application and licenses are shared among a larger number of users.\",\n              \"core-points\": \"A license where the core of a computer's processor is assigned a specific number of points.\",\n              \"custom-metric\": \"A license for which consumption is measured by non-standard metrics.\",\n              \"device\": \"A license that covers a defined number of installations on computers and other types of devices.\",\n              \"evaluation\": \"A license that grants permission to install and use software for trial purposes.\",\n              \"named-user\": \"A license that grants access to the software to one or more pre-defined users.\",\n              \"node-locked\": \"A license that grants access to the software on one or more pre-defined computers or devices.\",\n              \"oem\": \"An Original Equipment Manufacturer license that is delivered with hardware, cannot be transferred to other hardware, and is valid for the life of the hardware.\",\n              \"perpetual\": \"A license where the software is sold on a one-time basis and the licensee can use a copy of the software indefinitely.\",\n              \"processor-points\": \"A license where each installation consumes points per processor.\",\n              \"subscription\": \"A license where the licensee pays a fee to use the software or service.\",\n              \"user\": \"A license that grants access to the software or service by a specified number of users.\",\n              \"other\": \"Another license type.\"\n            }\n          }\n        },\n        \"lastRenewal\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Last Renewal\",\n          \"description\": \"The timestamp indicating when the license was last renewed. For new purchases, this is often the purchase or acquisition date. For non-perpetual licenses or subscriptions, this is the timestamp of when the license was last renewed.\"\n        },\n        \"expiration\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Expiration\",\n          \"description\": \"The timestamp indicating when the current license expires (if applicable).\"\n        }\n      }\n    },\n    \"license\": {\n      \"type\": \"object\",\n      \"title\": \"License\",\n      \"description\": \"Specifies the details and attributes related to a software license. It can either include a valid SPDX license identifier or a named license, along with additional properties such as license acknowledgment, comprehensive commercial licensing information, and the full text of the license.\",\n      \"oneOf\": [\n        {\n          \"required\": [\"id\"]\n        },\n        {\n          \"required\": [\"name\"]\n        }\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the license elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"id\": {\n          \"$ref\": \"spdx.schema.json\",\n          \"title\": \"License ID (SPDX)\",\n          \"description\": \"A valid SPDX license identifier. If specified, this value must be one of the enumeration of valid SPDX license identifiers defined in the spdx.schema.json (or spdx.xml) subschema which is synchronized with the official SPDX license list.\",\n          \"examples\": [\"Apache-2.0\"]\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"License Name\",\n          \"description\": \"The name of the license. This may include the name of a commercial or proprietary license or an open source license that may not be defined by SPDX.\",\n          \"examples\": [\"Acme Software License\"]\n        },\n        \"acknowledgement\": {\n          \"$ref\": \"#/definitions/licenseAcknowledgementEnumeration\"\n        },\n        \"text\": {\n          \"title\": \"License text\",\n          \"description\": \"A way to include the textual content of a license.\",\n          \"$ref\": \"#/definitions/attachment\"\n        },\n        \"url\": {\n          \"type\": \"string\",\n          \"title\": \"License URL\",\n          \"description\": \"The URL to the license file. If specified, a 'license' externalReference should also be specified for completeness\",\n          \"examples\": [\"https://www.apache.org/licenses/LICENSE-2.0.txt\"],\n          \"format\": \"iri-reference\"\n        },\n        \"licensing\": {\"$ref\": \"#/definitions/licensing\"},\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\"$ref\": \"#/definitions/property\"}\n        }\n      }\n    },\n    \"licenseAcknowledgementEnumeration\": {\n      \"title\": \"License Acknowledgement\",\n      \"description\": \"Declared licenses and concluded licenses represent two different stages in the licensing process within software development. Declared licenses refer to the initial intention of the software authors regarding the licensing terms under which their code is released. On the other hand, concluded licenses are the result of a comprehensive analysis of the project's codebase to identify and confirm the actual licenses of the components used, which may differ from the initially declared licenses. While declared licenses provide an upfront indication of the licensing intentions, concluded licenses offer a more thorough understanding of the actual licensing within a project, facilitating proper compliance and risk management. Observed licenses are defined in `@.evidence.licenses`. Observed licenses form the evidence necessary to substantiate a concluded license.\",\n      \"type\": \"string\",\n      \"enum\": [\n        \"declared\",\n        \"concluded\"\n      ],\n      \"meta:enum\": {\n        \"declared\": \"Declared licenses represent the initial intentions of authors regarding the licensing terms of their code.\",\n        \"concluded\": \"Concluded licenses are verified and confirmed.\"\n      }\n    },\n    \"licenseChoice\": {\n      \"title\": \"License Choice\",\n      \"description\": \"A list of SPDX licenses and/or named licenses and/or SPDX License Expression.\",\n      \"type\": \"array\",\n      \"items\": {\n        \"oneOf\": [\n          {\n            \"type\": \"object\",\n            \"title\": \"License\",\n            \"required\": [\n              \"license\"\n            ],\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"license\": {\n                \"$ref\": \"#/definitions/license\"\n              }\n            }\n          },\n          {\n            \"title\": \"License Expression\",\n            \"description\": \"Specifies the details and attributes related to a software license.\\nIt must be a valid SPDX license expression, along with additional properties such as license acknowledgment.\",\n            \"type\": \"object\",\n            \"additionalProperties\": false,\n            \"required\": [\n              \"expression\"\n            ],\n            \"properties\": {\n              \"expression\": {\n                \"type\": \"string\",\n                \"title\": \"SPDX License Expression\",\n                \"description\": \"A valid SPDX license expression.\\nRefer to https://spdx.org/specifications for syntax requirements.\",\n                \"examples\": [\n                  \"Apache-2.0 AND (MIT OR GPL-2.0-only)\",\n                  \"GPL-3.0-only WITH Classpath-exception-2.0\"\n                ]\n              },\n              \"expressionDetails\": {\n                \"title\": \"Expression Details\",\n                \"description\": \"Details for parts of the `expression`.\",\n                \"type\": \"array\",\n                \"items\": {\n                  \"type\": \"object\",\n                  \"description\": \"This document specifies the details and attributes related to a software license identifier. An SPDX expression may be a compound of license identifiers.\\nThe `license_identifier` property serves as the key that identifies each record. Note that this key is not required to be unique, as the same license identifier could apply to multiple, different but similar license details, texts, etc.\",\n                  \"required\": [\n                    \"licenseIdentifier\"\n                  ],\n                  \"properties\": {\n                    \"licenseIdentifier\": {\n                      \"title\": \"License Identifier\",\n                      \"description\": \"The valid SPDX license identifier. Refer to https://spdx.org/specifications for syntax requirements.\\nThis property serves as the primary key, which uniquely identifies each record.\",\n                      \"type\": \"string\",\n                      \"examples\": [\n                        \"Apache-2.0\",\n                        \"GPL-3.0-only WITH Classpath-exception-2.0\",\n                        \"LicenseRef-my-custom-license\"\n                      ]\n                    },\n                    \"bom-ref\": {\n                      \"$ref\": \"#/definitions/refType\",\n                      \"title\": \"BOM Reference\",\n                      \"description\": \"An identifier which can be used to reference the license elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n                    },\n                    \"text\": {\n                      \"title\": \"License texts\",\n                      \"description\": \"A way to include the textual content of the license.\",\n                      \"$ref\": \"#/definitions/attachment\"\n                    },\n                    \"url\": {\n                      \"type\": \"string\",\n                      \"title\": \"License URL\",\n                      \"description\": \"The URL to the license file. If specified, a 'license' externalReference should also be specified for completeness\",\n                      \"examples\": [\n                        \"https://www.apache.org/licenses/LICENSE-2.0.txt\"\n                      ],\n                      \"format\": \"iri-reference\"\n                    }\n                  },\n                  \"additionalProperties\": false\n                }\n              },\n              \"acknowledgement\": {\n                \"$ref\": \"#/definitions/licenseAcknowledgementEnumeration\"\n              },\n              \"bom-ref\": {\n                \"$ref\": \"#/definitions/refType\",\n                \"title\": \"BOM Reference\",\n                \"description\": \"An identifier which can be used to reference the license elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n              },\n              \"licensing\": {\n                \"$ref\": \"#/definitions/licensing\"\n              },\n              \"properties\": {\n                \"type\": \"array\",\n                \"title\": \"Properties\",\n                \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n                \"items\": {\n                  \"$ref\": \"#/definitions/property\"\n                }\n              }\n            }\n          }\n        ]\n      }\n    },\n    \"commit\": {\n      \"type\": \"object\",\n      \"title\": \"Commit\",\n      \"description\": \"Specifies an individual commit\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"uid\": {\n          \"type\": \"string\",\n          \"title\": \"UID\",\n          \"description\": \"A unique identifier of the commit. This may be version control specific. For example, Subversion uses revision numbers whereas git uses commit hashes.\"\n        },\n        \"url\": {\n          \"type\": \"string\",\n          \"title\": \"URL\",\n          \"description\": \"The URL to the commit. This URL will typically point to a commit in a version control system.\",\n          \"format\": \"iri-reference\"\n        },\n        \"author\": {\n          \"title\": \"Author\",\n          \"description\": \"The author who created the changes in the commit\",\n          \"$ref\": \"#/definitions/identifiableAction\"\n        },\n        \"committer\": {\n          \"title\": \"Committer\",\n          \"description\": \"The person who committed or pushed the commit\",\n          \"$ref\": \"#/definitions/identifiableAction\"\n        },\n        \"message\": {\n          \"type\": \"string\",\n          \"title\": \"Message\",\n          \"description\": \"The text description of the contents of the commit\"\n        }\n      }\n    },\n    \"patch\": {\n      \"type\": \"object\",\n      \"title\": \"Patch\",\n      \"description\": \"Specifies an individual patch\",\n      \"required\": [\n        \"type\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"type\": {\n          \"type\": \"string\",\n          \"enum\": [\n            \"unofficial\",\n            \"monkey\",\n            \"backport\",\n            \"cherry-pick\"\n          ],\n          \"meta:enum\": {\n            \"unofficial\": \"A patch which is not developed by the creators or maintainers of the software being patched. Refer to [https://en.wikipedia.org/wiki/Unofficial_patch](https://en.wikipedia.org/wiki/Unofficial_patch).\",\n            \"monkey\": \"A patch which dynamically modifies runtime behavior. Refer to [https://en.wikipedia.org/wiki/Monkey_patch](https://en.wikipedia.org/wiki/Monkey_patch).\",\n            \"backport\": \"A patch which takes code from a newer version of the software and applies it to older versions of the same software. Refer to [https://en.wikipedia.org/wiki/Backporting](https://en.wikipedia.org/wiki/Backporting).\",\n            \"cherry-pick\": \"A patch created by selectively applying commits from other versions or branches of the same software.\"\n          },\n          \"title\": \"Patch Type\",\n          \"description\": \"Specifies the purpose for the patch including the resolution of defects, security issues, or new behavior or functionality.\"\n        },\n        \"diff\": {\n          \"title\": \"Diff\",\n          \"description\": \"The patch file (or diff) that shows changes. Refer to [https://en.wikipedia.org/wiki/Diff](https://en.wikipedia.org/wiki/Diff)\",\n          \"$ref\": \"#/definitions/diff\"\n        },\n        \"resolves\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/issue\"},\n          \"title\": \"Resolves\",\n          \"description\": \"A collection of issues the patch resolves\"\n        }\n      }\n    },\n    \"diff\": {\n      \"type\": \"object\",\n      \"title\": \"Diff\",\n      \"description\": \"The patch file (or diff) that shows changes. Refer to https://en.wikipedia.org/wiki/Diff\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"text\": {\n          \"title\": \"Diff text\",\n          \"description\": \"Specifies the text of the diff\",\n          \"$ref\": \"#/definitions/attachment\"\n        },\n        \"url\": {\n          \"type\": \"string\",\n          \"title\": \"URL\",\n          \"description\": \"Specifies the URL to the diff\",\n          \"format\": \"iri-reference\"\n        }\n      }\n    },\n    \"issue\": {\n      \"type\": \"object\",\n      \"title\": \"Issue\",\n      \"description\": \"An individual issue that has been resolved.\",\n      \"required\": [\n        \"type\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"type\": {\n          \"type\": \"string\",\n          \"enum\": [\n            \"defect\",\n            \"enhancement\",\n            \"security\"\n          ],\n          \"meta:enum\": {\n            \"defect\": \"A fault, flaw, or bug in software.\",\n            \"enhancement\": \"A new feature or behavior in software.\",\n            \"security\": \"A special type of defect which impacts security.\"\n          },\n          \"title\": \"Issue Type\",\n          \"description\": \"Specifies the type of issue\"\n        },\n        \"id\": {\n          \"type\": \"string\",\n          \"title\": \"Issue ID\",\n          \"description\": \"The identifier of the issue assigned by the source of the issue\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Issue Name\",\n          \"description\": \"The name of the issue\"\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"title\": \"Issue Description\",\n          \"description\": \"A description of the issue\"\n        },\n        \"source\": {\n          \"type\": \"object\",\n          \"title\": \"Source\",\n          \"description\": \"The source of the issue where it is documented\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"name\": {\n              \"type\": \"string\",\n              \"title\": \"Name\",\n              \"description\": \"The name of the source.\",\n              \"examples\": [\n                \"National Vulnerability Database\",\n                \"NVD\",\n                \"Apache\"\n              ]\n            },\n            \"url\": {\n              \"type\": \"string\",\n              \"title\": \"URL\",\n              \"description\": \"The url of the issue documentation as provided by the source\",\n              \"format\": \"iri-reference\"\n            }\n          }\n        },\n        \"references\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\",\n            \"format\": \"iri-reference\"\n          },\n          \"title\": \"References\",\n          \"description\": \"A collection of URL's for reference. Multiple URLs are allowed.\",\n          \"examples\": [\"https://example.com\"]\n        }\n      }\n    },\n    \"identifiableAction\": {\n      \"type\": \"object\",\n      \"title\": \"Identifiable Action\",\n      \"description\": \"Specifies an individual commit\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"timestamp\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Timestamp\",\n          \"description\": \"The timestamp in which the action occurred\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"The name of the individual who performed the action\"\n        },\n        \"email\": {\n          \"type\": \"string\",\n          \"format\": \"idn-email\",\n          \"title\": \"E-mail\",\n          \"description\": \"The email address of the individual who performed the action\"\n        }\n      }\n    },\n    \"externalReference\": {\n      \"type\": \"object\",\n      \"title\": \"External Reference\",\n      \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\",\n      \"required\": [\n        \"url\",\n        \"type\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"url\": {\n          \"anyOf\": [\n            {\n              \"title\": \"URL\",\n              \"type\": \"string\",\n              \"format\": \"iri-reference\"\n            },\n            {\n              \"title\": \"BOM-Link\",\n              \"$ref\": \"#/definitions/bomLink\"\n            }\n          ],\n          \"title\": \"URL\",\n          \"description\": \"The URI (URL or URN) to the external reference. External references are URIs and therefore can accept any URL scheme including https ([RFC-7230](https://www.ietf.org/rfc/rfc7230.txt)), mailto ([RFC-2368](https://www.ietf.org/rfc/rfc2368.txt)), tel ([RFC-3966](https://www.ietf.org/rfc/rfc3966.txt)), and dns ([RFC-4501](https://www.ietf.org/rfc/rfc4501.txt)). External references may also include formally registered URNs such as [CycloneDX BOM-Link](https://cyclonedx.org/capabilities/bomlink/) to reference CycloneDX BOMs or any object within a BOM. BOM-Link transforms applicable external references into relationships that can be expressed in a BOM or across BOMs.\"\n        },\n        \"comment\": {\n          \"type\": \"string\",\n          \"title\": \"Comment\",\n          \"description\": \"A comment describing the external reference\"\n        },\n        \"type\": {\n          \"type\": \"string\",\n          \"title\": \"Type\",\n          \"description\": \"Specifies the type of external reference.\",\n          \"enum\": [\n            \"vcs\",\n            \"issue-tracker\",\n            \"website\",\n            \"advisories\",\n            \"bom\",\n            \"mailing-list\",\n            \"social\",\n            \"chat\",\n            \"documentation\",\n            \"support\",\n            \"source-distribution\",\n            \"distribution\",\n            \"distribution-intake\",\n            \"license\",\n            \"build-meta\",\n            \"build-system\",\n            \"release-notes\",\n            \"security-contact\",\n            \"model-card\",\n            \"log\",\n            \"configuration\",\n            \"evidence\",\n            \"formulation\",\n            \"attestation\",\n            \"threat-model\",\n            \"adversary-model\",\n            \"risk-assessment\",\n            \"vulnerability-assertion\",\n            \"exploitability-statement\",\n            \"pentest-report\",\n            \"static-analysis-report\",\n            \"dynamic-analysis-report\",\n            \"runtime-analysis-report\",\n            \"component-analysis-report\",\n            \"maturity-report\",\n            \"certification-report\",\n            \"codified-infrastructure\",\n            \"quality-metrics\",\n            \"poam\",\n            \"electronic-signature\",\n            \"digital-signature\",\n            \"rfc-9116\",\n            \"patent\",\n            \"patent-family\",\n            \"patent-assertion\",\n            \"citation\",\n            \"other\"\n          ],\n          \"meta:enum\": {\n            \"vcs\": \"Version Control System\",\n            \"issue-tracker\": \"Issue or defect tracking system, or an Application Lifecycle Management (ALM) system\",\n            \"website\": \"Website\",\n            \"advisories\": \"Security advisories\",\n            \"bom\": \"Bill of Materials (SBOM, OBOM, HBOM, SaaSBOM, etc)\",\n            \"mailing-list\": \"Mailing list or discussion group\",\n            \"social\": \"Social media account\",\n            \"chat\": \"Real-time chat platform\",\n            \"documentation\": \"Documentation, guides, or how-to instructions\",\n            \"support\": \"Community or commercial support\",\n            \"source-distribution\": \"The location where the source code distributable can be obtained. This is often an archive format such as zip or tgz. The source-distribution type complements use of the version control (vcs) type.\",\n            \"distribution\": \"Direct or repository download location\",\n            \"distribution-intake\": \"The location where a component was published to. This is often the same as \\\"distribution\\\" but may also include specialized publishing processes that act as an intermediary.\",\n            \"license\": \"The reference to the license file. If a license URL has been defined in the license node, it should also be defined as an external reference for completeness.\",\n            \"build-meta\": \"Build-system specific meta file (i.e. pom.xml, package.json, .nuspec, etc)\",\n            \"build-system\": \"Reference to an automated build system\",\n            \"release-notes\": \"Reference to release notes\",\n            \"security-contact\": \"Specifies a way to contact the maintainer, supplier, or provider in the event of a security incident. Common URIs include links to a disclosure procedure, a mailto (RFC-2368) that specifies an email address, a tel (RFC-3966) that specifies a phone number, or dns (RFC-4501) that specifies the records containing DNS Security TXT.\",\n            \"model-card\": \"A model card describes the intended uses of a machine learning model, potential limitations, biases, ethical considerations, training parameters, datasets used to train the model, performance metrics, and other relevant data useful for ML transparency.\",\n            \"log\": \"A record of events that occurred in a computer system or application, such as problems, errors, or information on current operations.\",\n            \"configuration\": \"Parameters or settings that may be used by other components or services.\",\n            \"evidence\": \"Information used to substantiate a claim.\",\n            \"formulation\": \"Describes the formulation of any referencable object within the BOM, including components, services, metadata, declarations, or the BOM itself.\",\n            \"attestation\": \"Human or machine-readable statements containing facts, evidence, or testimony.\",\n            \"threat-model\": \"An enumeration of identified weaknesses, threats, and countermeasures, dataflow diagram (DFD), attack tree, and other supporting documentation in human-readable or machine-readable format.\",\n            \"adversary-model\": \"The defined assumptions, goals, and capabilities of an adversary.\",\n            \"risk-assessment\": \"Identifies and analyzes the potential of future events that may negatively impact individuals, assets, and/or the environment. Risk assessments may also include judgments on the tolerability of each risk.\",\n            \"vulnerability-assertion\": \"A Vulnerability Disclosure Report (VDR) which asserts the known and previously unknown vulnerabilities that affect a component, service, or product including the analysis and findings describing the impact (or lack of impact) that the reported vulnerability has on a component, service, or product.\",\n            \"exploitability-statement\": \"A Vulnerability Exploitability eXchange (VEX) which asserts the known vulnerabilities that do not affect a product, product family, or organization, and optionally the ones that do. The VEX should include the analysis and findings describing the impact (or lack of impact) that the reported vulnerability has on the product, product family, or organization.\",\n            \"pentest-report\": \"Results from an authorized simulated cyberattack on a component or service, otherwise known as a penetration test.\",\n            \"static-analysis-report\": \"SARIF or proprietary machine or human-readable report for which static analysis has identified code quality, security, and other potential issues with the source code.\",\n            \"dynamic-analysis-report\": \"Dynamic analysis report that has identified issues such as vulnerabilities and misconfigurations.\",\n            \"runtime-analysis-report\": \"Report generated by analyzing the call stack of a running application.\",\n            \"component-analysis-report\": \"Report generated by Software Composition Analysis (SCA), container analysis, or other forms of component analysis.\",\n            \"maturity-report\": \"Report containing a formal assessment of an organization, business unit, or team against a maturity model.\",\n            \"certification-report\": \"Industry, regulatory, or other certification from an accredited (if applicable) certification body.\",\n            \"codified-infrastructure\": \"Code or configuration that defines and provisions virtualized infrastructure, commonly referred to as Infrastructure as Code (IaC).\",\n            \"quality-metrics\": \"Report or system in which quality metrics can be obtained.\",\n            \"poam\": \"Plans of Action and Milestones (POA&M) complement an \\\"attestation\\\" external reference. POA&M is defined by NIST as a \\\"document that identifies tasks needing to be accomplished. It details resources required to accomplish the elements of the plan, any milestones in meeting the tasks and scheduled completion dates for the milestones\\\".\",\n            \"electronic-signature\": \"An e-signature is commonly a scanned representation of a written signature or a stylized script of the person's name.\",\n            \"digital-signature\": \"A signature that leverages cryptography, typically public/private key pairs, which provides strong authenticity verification.\",\n            \"rfc-9116\": \"Document that complies with [RFC 9116](https://www.ietf.org/rfc/rfc9116.html) (A File Format to Aid in Security Vulnerability Disclosure)\",\n            \"patent\": \"References information about patents which may be defined in human-readable documents or in machine-readable formats such as CycloneDX or ST.96. For detailed patent information or to reference the information provided directly by patent offices, it is recommended to leverage standards from the World Intellectual Property Organization (WIPO) such as [ST.96](https://www.wipo.int/standards/en/st96).\",\n            \"patent-family\": \"References information about a patent family which may be defined in human-readable documents or in machine-readable formats such as CycloneDX or ST.96. A patent family is a group of related patent applications or granted patents that cover the same or similar invention. For detailed patent family information or to reference the information provided directly by patent offices, it is recommended to leverage standards from the World Intellectual Property Organization (WIPO) such as [ST.96](https://www.wipo.int/standards/en/st96).\",\n            \"patent-assertion\" : \"References assertions made regarding patents associated with a component or service. Assertions distinguish between ownership, licensing, and other relevant interactions with patents.\",\n            \"citation\": \"A reference to external citations applicable to the object identified by this BOM entry or the BOM itself. When used with a BOM-Link, this allows offloading citations into a separate CycloneDX BOM.\",\n            \"other\": \"Use this if no other types accurately describe the purpose of the external reference.\"\n          }\n        },\n        \"hashes\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/hash\"},\n          \"title\": \"Hashes\",\n          \"description\": \"The hashes of the external reference (if applicable).\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\"$ref\": \"#/definitions/property\"}\n        }\n      }\n    },\n    \"dependency\": {\n      \"type\": \"object\",\n      \"title\": \"Dependency\",\n      \"description\": \"Defines the direct dependencies of a component, service, or the components provided/implemented by a given component. Components or services that do not have their own dependencies must be declared as empty elements within the graph. Components or services that are not represented in the dependency graph may have unknown dependencies. It is recommended that implementations assume this to be opaque and not an indicator of an object being dependency-free. It is recommended to leverage compositions to indicate unknown dependency graphs.\",\n      \"required\": [\n        \"ref\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"ref\": {\n          \"$ref\": \"#/definitions/refLinkType\",\n          \"title\": \"Reference\",\n          \"description\": \"References a component or service by its bom-ref attribute\"\n        },\n        \"dependsOn\": {\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/refLinkType\"\n          },\n          \"title\": \"Depends On\",\n          \"description\": \"The bom-ref identifiers of the components or services that are dependencies of this dependency object.\"\n        },\n        \"provides\": {\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/refLinkType\"\n          },\n          \"title\": \"Provides\",\n          \"description\": \"The bom-ref identifiers of the components or services that define a given specification or standard, which are provided or implemented by this dependency object.\\nFor example, a cryptographic library which implements a cryptographic algorithm. A component which implements another component does not imply that the implementation is in use.\"\n        }\n      }\n    },\n    \"service\": {\n      \"type\": \"object\",\n      \"title\": \"Service\",\n      \"required\": [\n        \"name\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the service elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"provider\": {\n          \"title\": \"Provider\",\n          \"description\": \"The organization that provides the service.\",\n          \"$ref\": \"#/definitions/organizationalEntity\"\n        },\n        \"group\": {\n          \"type\": \"string\",\n          \"title\": \"Service Group\",\n          \"description\": \"The grouping name, namespace, or identifier. This will often be a shortened, single name of the company or project that produced the service or domain name. Whitespace and special characters should be avoided.\",\n          \"examples\": [\"com.acme\"]\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Service Name\",\n          \"description\": \"The name of the service. This will often be a shortened, single name of the service.\",\n          \"examples\": [\"ticker-service\"]\n        },\n        \"version\": {\n          \"$ref\": \"#/definitions/version\",\n          \"title\": \"Service Version\",\n          \"description\": \"The service version.\"\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"title\": \"Service Description\",\n          \"description\": \"Specifies a description for the service\"\n        },\n        \"endpoints\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\",\n            \"format\": \"iri-reference\"\n          },\n          \"title\": \"Endpoints\",\n          \"description\": \"The endpoint URIs of the service. Multiple endpoints are allowed.\",\n          \"examples\": [\"https://example.com/api/v1/ticker\"]\n        },\n        \"authenticated\": {\n          \"type\": \"boolean\",\n          \"title\": \"Authentication Required\",\n          \"description\": \"A boolean value indicating if the service requires authentication. A value of true indicates the service requires authentication prior to use. A value of false indicates the service does not require authentication.\"\n        },\n        \"x-trust-boundary\": {\n          \"type\": \"boolean\",\n          \"title\": \"Crosses Trust Boundary\",\n          \"description\": \"A boolean value indicating if use of the service crosses a trust zone or boundary. A value of true indicates that by using the service, a trust boundary is crossed. A value of false indicates that by using the service, a trust boundary is not crossed.\"\n        },\n        \"trustZone\": {\n          \"type\": \"string\",\n          \"title\": \"Trust Zone\",\n          \"description\": \"The name of the trust zone the service resides in.\"\n        },\n        \"data\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/serviceData\"},\n          \"title\": \"Data\",\n          \"description\": \"Specifies information about the data including the directional flow of data and the data classification.\"\n        },\n        \"licenses\": {\n          \"$ref\": \"#/definitions/licenseChoice\",\n          \"title\": \"Service License(s)\"\n        },\n        \"patentAssertions\": {\n          \"$ref\": \"#/definitions/patentAssertions\",\n          \"title\": \"Service Patent(s)\"\n        },\n        \"externalReferences\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/externalReference\"},\n          \"title\": \"External References\",\n          \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n        },\n        \"services\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/service\"},\n          \"uniqueItems\": true,\n          \"title\": \"Services\",\n          \"description\": \"A list of services included or deployed behind the parent service. This is not a dependency tree. It provides a way to specify a hierarchical representation of service assemblies.\"\n        },\n        \"releaseNotes\": {\n          \"$ref\": \"#/definitions/releaseNotes\",\n          \"title\": \"Release notes\",\n          \"description\": \"Specifies release notes.\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\"$ref\": \"#/definitions/property\"}\n        },\n        \"tags\": {\n          \"$ref\": \"#/definitions/tags\",\n          \"title\": \"Tags\"\n        },\n        \"signature\": {\n          \"$ref\": \"#/definitions/signature\",\n          \"title\": \"Signature\",\n          \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n        }\n      }\n    },\n    \"serviceData\": {\n      \"type\": \"object\",\n      \"title\": \"Hash Objects\",\n      \"required\": [\n        \"flow\",\n        \"classification\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"flow\": {\n          \"$ref\": \"#/definitions/dataFlowDirection\",\n          \"title\": \"Directional Flow\",\n          \"description\": \"Specifies the flow direction of the data. Direction is relative to the service. Inbound flow states that data enters the service. Outbound flow states that data leaves the service. Bi-directional states that data flows both ways and unknown states that the direction is not known.\"\n        },\n        \"classification\": {\n          \"$ref\": \"#/definitions/dataClassification\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"Name for the defined data\",\n          \"examples\": [\n            \"Credit card reporting\"\n          ]\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"title\": \"Description\",\n          \"description\": \"Short description of the data content and usage\",\n          \"examples\": [\n            \"Credit card information being exchanged in between the web app and the database\"\n          ]\n        },\n        \"governance\": {\n          \"title\": \"Data Governance\",\n          \"$ref\": \"#/definitions/dataGovernance\"\n        },\n        \"source\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"anyOf\": [\n              {\n                \"title\": \"URL\",\n                \"type\": \"string\",\n                \"format\": \"iri-reference\"\n              },\n              {\n                \"title\": \"BOM-Link Element\",\n                \"$ref\": \"#/definitions/bomLinkElementType\"\n              }\n            ]\n          },\n          \"title\": \"Source\",\n          \"description\": \"The URI, URL, or BOM-Link of the components or services the data came in from\"\n        },\n        \"destination\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"anyOf\": [\n              {\n                \"title\": \"URL\",\n                \"type\": \"string\",\n                \"format\": \"iri-reference\"\n              },\n              {\n                \"title\": \"BOM-Link Element\",\n                \"$ref\": \"#/definitions/bomLinkElementType\"\n              }\n            ]\n          },\n          \"title\": \"Destination\",\n          \"description\": \"The URI, URL, or BOM-Link of the components or services the data is sent to\"\n        }\n      }\n    },\n    \"dataFlowDirection\": {\n      \"type\": \"string\",\n      \"enum\": [\n        \"inbound\",\n        \"outbound\",\n        \"bi-directional\",\n        \"unknown\"\n      ],\n      \"meta:enum\": {\n        \"inbound\": \"Data that enters a service.\",\n        \"outbound\": \"Data that exits a service.\",\n        \"bi-directional\": \"Data flows in and out of the service.\",\n        \"unknown\": \"The directional flow of data is not known.\"\n      },\n      \"title\": \"Data flow direction\",\n      \"description\": \"Specifies the flow direction of the data. Direction is relative to the service.\"\n    },\n    \"copyright\": {\n      \"type\": \"object\",\n      \"title\": \"Copyright\",\n      \"description\": \"A copyright notice informing users of the underlying claims to copyright ownership in a published work.\",\n      \"required\": [\n        \"text\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"text\": {\n          \"type\": \"string\",\n          \"title\": \"Copyright Text\",\n          \"description\": \"The textual content of the copyright.\"\n        }\n      }\n    },\n    \"componentEvidence\": {\n      \"type\": \"object\",\n      \"title\": \"Evidence\",\n      \"description\": \"Provides the ability to document evidence collected through various forms of extraction or analysis.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"identity\": {\n          \"title\": \"Identity Evidence\",\n          \"description\": \"Evidence that substantiates the identity of a component. The identity may be an object or an array of identity objects. Support for specifying identity as a single object was introduced in CycloneDX v1.5. Arrays were introduced in v1.6. It is recommended that all implementations use arrays, even if only one identity object is specified.\",\n          \"oneOf\" : [\n            {\n              \"type\": \"array\",\n              \"title\": \"Array of Identity Objects\",\n              \"items\": { \"$ref\": \"#/definitions/componentIdentityEvidence\" }\n            },\n            {\n              \"title\": \"A Single Identity Object\",\n              \"description\": \"[Deprecated]\",\n              \"$ref\": \"#/definitions/componentIdentityEvidence\",\n              \"deprecated\": true\n            }\n          ]\n        },\n        \"occurrences\": {\n          \"type\": \"array\",\n          \"title\": \"Occurrences\",\n          \"description\": \"Evidence of individual instances of a component spread across multiple locations.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"required\": [ \"location\" ],\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"bom-ref\": {\n                \"$ref\": \"#/definitions/refType\",\n                \"title\": \"BOM Reference\",\n                \"description\": \"An identifier which can be used to reference the occurrence elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n              },\n              \"location\": {\n                \"type\": \"string\",\n                \"title\": \"Location\",\n                \"description\": \"The location or path to where the component was found.\"\n              },\n              \"line\": {\n                \"type\": \"integer\",\n                \"minimum\": 0,\n                \"title\": \"Line Number\",\n                \"description\": \"The line number where the component was found.\"\n              },\n              \"offset\": {\n                \"type\": \"integer\",\n                \"minimum\": 0,\n                \"title\": \"Offset\",\n                \"description\": \"The offset where the component was found.\"\n              },\n              \"symbol\": {\n                \"type\": \"string\",\n                \"title\": \"Symbol\",\n                \"description\": \"The symbol name that was found associated with the component.\"\n              },\n              \"additionalContext\": {\n                \"type\": \"string\",\n                \"title\": \"Additional Context\",\n                \"description\": \"Any additional context of the detected component (e.g. a code snippet).\"\n              }\n            }\n          }\n        },\n        \"callstack\": {\n          \"type\": \"object\",\n          \"title\": \"Call Stack\",\n          \"description\": \"Evidence of the components use through the callstack.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"frames\": {\n              \"type\": \"array\",\n              \"title\": \"Frames\",\n              \"description\": \"Within a call stack, a frame is a discrete unit that encapsulates an execution context, including local variables, parameters, and the return address. As function calls are made, frames are pushed onto the stack, forming an array-like structure that orchestrates the flow of program execution and manages the sequence of function invocations.\",\n              \"items\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"module\"\n                ],\n                \"additionalProperties\": false,\n                \"properties\": {\n                  \"package\": {\n                    \"title\": \"Package\",\n                    \"description\": \"A package organizes modules into namespaces, providing a unique namespace for each type it contains.\",\n                    \"type\": \"string\"\n                  },\n                  \"module\": {\n                    \"title\": \"Module\",\n                    \"description\": \"A module or class that encloses functions/methods and other code.\",\n                    \"type\": \"string\"\n                  },\n                  \"function\": {\n                    \"title\": \"Function\",\n                    \"description\": \"A block of code designed to perform a particular task.\",\n                    \"type\": \"string\"\n                  },\n                  \"parameters\": {\n                    \"title\": \"Parameters\",\n                    \"description\": \"Arguments that are passed to the module or function.\",\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"type\": \"string\"\n                    }\n                  },\n                  \"line\": {\n                    \"title\": \"Line\",\n                    \"description\": \"The line number the code that is called resides on.\",\n                    \"type\": \"integer\"\n                  },\n                  \"column\": {\n                    \"title\": \"Column\",\n                    \"description\": \"The column the code that is called resides.\",\n                    \"type\": \"integer\"\n                  },\n                  \"fullFilename\": {\n                    \"title\": \"Full Filename\",\n                    \"description\": \"The full path and filename of the module.\",\n                    \"type\": \"string\"\n                  }\n                }\n              }\n            }\n          }\n        },\n        \"licenses\": {\n          \"$ref\": \"#/definitions/licenseChoice\",\n          \"title\": \"License Evidence\"\n        },\n        \"copyright\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/copyright\"},\n          \"title\": \"Copyright Evidence\",\n          \"description\": \"Copyright evidence captures intellectual property assertions, providing evidence of possible ownership and legal protection.\"\n        }\n      }\n    },\n    \"compositions\": {\n      \"type\": \"object\",\n      \"title\": \"Compositions\",\n      \"required\": [\n        \"aggregate\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the composition elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"aggregate\": {\n          \"$ref\": \"#/definitions/aggregateType\",\n          \"title\": \"Aggregate\",\n          \"description\": \"Specifies an aggregate type that describes how complete a relationship is.\"\n        },\n        \"assemblies\": {\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"anyOf\": [\n              {\n                \"title\": \"Ref\",\n                \"$ref\": \"#/definitions/refLinkType\"\n              },\n              {\n                \"title\": \"BOM-Link Element\",\n                \"$ref\": \"#/definitions/bomLinkElementType\"\n              }\n            ]\n          },\n          \"title\": \"BOM references\",\n          \"description\": \"The bom-ref identifiers of the components or services being described. Assemblies refer to nested relationships whereby a constituent part may include other constituent parts. References do not cascade to child parts. References are explicit for the specified constituent part only.\"\n        },\n        \"dependencies\": {\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"title\": \"BOM references\",\n          \"description\": \"The bom-ref identifiers of the components or services being described. Dependencies refer to a relationship whereby an independent constituent part requires another independent constituent part. References do not cascade to transitive dependencies. References are explicit for the specified dependency only.\"\n        },\n        \"vulnerabilities\": {\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"title\": \"BOM references\",\n          \"description\": \"The bom-ref identifiers of the vulnerabilities being described.\"\n        },\n        \"signature\": {\n          \"$ref\": \"#/definitions/signature\",\n          \"title\": \"Signature\",\n          \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n        }\n      }\n    },\n    \"aggregateType\": {\n      \"type\": \"string\",\n      \"default\": \"not_specified\",\n      \"enum\": [\n        \"complete\",\n        \"incomplete\",\n        \"incomplete_first_party_only\",\n        \"incomplete_first_party_proprietary_only\",\n        \"incomplete_first_party_opensource_only\",\n        \"incomplete_third_party_only\",\n        \"incomplete_third_party_proprietary_only\",\n        \"incomplete_third_party_opensource_only\",\n        \"unknown\",\n        \"not_specified\"\n      ],\n      \"meta:enum\": {\n        \"complete\": \"The relationship is complete. No further relationships including constituent components, services, or dependencies are known to exist.\",\n        \"incomplete\": \"The relationship is incomplete. Additional relationships exist and may include constituent components, services, or dependencies.\",\n        \"incomplete_first_party_only\": \"The relationship is incomplete. Only relationships for first-party components, services, or their dependencies are represented.\",\n        \"incomplete_first_party_proprietary_only\": \"The relationship is incomplete. Only relationships for first-party components, services, or their dependencies are represented, limited specifically to those that are proprietary.\",\n        \"incomplete_first_party_opensource_only\": \"The relationship is incomplete. Only relationships for first-party components, services, or their dependencies are represented, limited specifically to those that are opensource.\",\n        \"incomplete_third_party_only\": \"The relationship is incomplete. Only relationships for third-party components, services, or their dependencies are represented.\",\n        \"incomplete_third_party_proprietary_only\": \"The relationship is incomplete. Only relationships for third-party components, services, or their dependencies are represented, limited specifically to those that are proprietary.\",\n        \"incomplete_third_party_opensource_only\": \"The relationship is incomplete. Only relationships for third-party components, services, or their dependencies are represented, limited specifically to those that are opensource.\",\n        \"unknown\": \"The relationship may be complete or incomplete. This usually signifies a 'best-effort' to obtain constituent components, services, or dependencies but the completeness is inconclusive.\",\n        \"not_specified\": \"The relationship completeness is not specified.\"\n      }\n    },\n    \"property\": {\n      \"type\": \"object\",\n      \"title\": \"Lightweight name-value pair\",\n      \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n      \"required\": [\n        \"name\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"The name of the property. Duplicate names are allowed, each potentially having a different value.\"\n        },\n        \"value\": {\n          \"type\": \"string\",\n          \"title\": \"Value\",\n          \"description\": \"The value of the property.\"\n        }\n      }\n    },\n    \"localeType\": {\n      \"type\": \"string\",\n      \"pattern\": \"^([a-z]{2})(-[A-Z]{2})?$\",\n      \"title\": \"Locale\",\n      \"description\": \"Defines a syntax for representing two character language code (ISO-639) followed by an optional two character country code. The language code must be lower case. If the country code is specified, the country code must be upper case. The language code and country code must be separated by a minus sign. Examples: en, en-US, fr, fr-CA\"\n    },\n    \"releaseType\": {\n      \"type\": \"string\",\n      \"examples\": [\n        \"major\",\n        \"minor\",\n        \"patch\",\n        \"pre-release\",\n        \"internal\"\n      ],\n      \"description\": \"The software versioning type. It is recommended that the release type use one of 'major', 'minor', 'patch', 'pre-release', or 'internal'. Representing all possible software release types is not practical, so standardizing on the recommended values, whenever possible, is strongly encouraged.\\n\\n* __major__ = A major release may contain significant changes or may introduce breaking changes.\\n* __minor__ = A minor release, also known as an update, may contain a smaller number of changes than major releases.\\n* __patch__ = Patch releases are typically unplanned and may resolve defects or important security issues.\\n* __pre-release__ = A pre-release may include alpha, beta, or release candidates and typically have limited support. They provide the ability to preview a release prior to its general availability.\\n* __internal__ = Internal releases are not for public consumption and are intended to be used exclusively by the project or manufacturer that produced it.\"\n    },\n    \"note\": {\n      \"type\": \"object\",\n      \"title\": \"Note\",\n      \"description\": \"A note containing the locale and content.\",\n      \"required\": [\n        \"text\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"locale\": {\n          \"$ref\": \"#/definitions/localeType\",\n          \"title\": \"Locale\",\n          \"description\": \"The ISO-639 (or higher) language code and optional ISO-3166 (or higher) country code. Examples include: \\\"en\\\", \\\"en-US\\\", \\\"fr\\\" and \\\"fr-CA\\\"\"\n        },\n        \"text\": {\n          \"title\": \"Release note content\",\n          \"description\": \"Specifies the full content of the release note.\",\n          \"$ref\": \"#/definitions/attachment\"\n        }\n      }\n    },\n    \"releaseNotes\": {\n      \"type\": \"object\",\n      \"title\": \"Release notes\",\n      \"required\": [\n        \"type\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"type\": {\n          \"$ref\": \"#/definitions/releaseType\",\n          \"title\": \"Type\",\n          \"description\": \"The software versioning type the release note describes.\"\n        },\n        \"title\": {\n          \"type\": \"string\",\n          \"title\": \"Title\",\n          \"description\": \"The title of the release.\"\n        },\n        \"featuredImage\": {\n          \"type\": \"string\",\n          \"format\": \"iri-reference\",\n          \"title\": \"Featured image\",\n          \"description\": \"The URL to an image that may be prominently displayed with the release note.\"\n        },\n        \"socialImage\": {\n          \"type\": \"string\",\n          \"format\": \"iri-reference\",\n          \"title\": \"Social image\",\n          \"description\": \"The URL to an image that may be used in messaging on social media platforms.\"\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"title\": \"Description\",\n          \"description\": \"A short description of the release.\"\n        },\n        \"timestamp\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Timestamp\",\n          \"description\": \"The date and time (timestamp) when the release note was created.\"\n        },\n        \"aliases\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"title\": \"Aliases\",\n          \"description\": \"One or more alternate names the release may be referred to. This may include unofficial terms used by development and marketing teams (e.g. code names).\"\n        },\n        \"tags\": {\n          \"$ref\": \"#/definitions/tags\",\n          \"title\": \"Tags\"\n        },\n        \"resolves\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/issue\"},\n          \"title\": \"Resolves\",\n          \"description\": \"A collection of issues that have been resolved.\"\n        },\n        \"notes\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/note\"},\n          \"title\": \"Notes\",\n          \"description\": \"Zero or more release notes containing the locale and content. Multiple note objects may be specified to support release notes in a wide variety of languages.\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\"$ref\": \"#/definitions/property\"}\n        }\n      }\n    },\n    \"advisory\": {\n      \"type\": \"object\",\n      \"title\": \"Advisory\",\n      \"description\": \"Title and location where advisory information can be obtained. An advisory is a notification of a threat to a component, service, or system.\",\n      \"required\": [\"url\"],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"title\": {\n          \"type\": \"string\",\n          \"title\": \"Title\",\n          \"description\": \"A name of the advisory.\"\n        },\n        \"url\": {\n          \"type\": \"string\",\n          \"title\": \"URL\",\n          \"format\": \"iri-reference\",\n          \"description\": \"Location where the advisory can be obtained.\"\n        }\n      }\n    },\n    \"cwe\": {\n      \"type\": \"integer\",\n      \"minimum\": 1,\n      \"title\": \"CWE\",\n      \"description\": \"Integer representation of a Common Weaknesses Enumerations (CWE). For example 399 (of https://cwe.mitre.org/data/definitions/399.html)\"\n    },\n    \"severity\": {\n      \"type\": \"string\",\n      \"title\": \"Severity\",\n      \"description\": \"Textual representation of the severity of the vulnerability adopted by the analysis method. If the analysis method uses values other than what is provided, the user is expected to translate appropriately.\",\n      \"enum\": [\n        \"critical\",\n        \"high\",\n        \"medium\",\n        \"low\",\n        \"info\",\n        \"none\",\n        \"unknown\"\n      ],\n      \"meta:enum\": {\n        \"critical\": \"Critical severity\",\n        \"high\": \"High severity\",\n        \"medium\": \"Medium severity\",\n        \"low\": \"Low severity\",\n        \"info\": \"Informational warning.\",\n        \"none\": \"None\",\n        \"unknown\": \"The severity is not known\"\n      }\n    },\n    \"scoreMethod\": {\n      \"type\": \"string\",\n      \"title\": \"Method\",\n      \"description\": \"Specifies the severity or risk scoring methodology or standard used.\",\n      \"enum\": [\n        \"CVSSv2\",\n        \"CVSSv3\",\n        \"CVSSv31\",\n        \"CVSSv4\",\n        \"OWASP\",\n        \"SSVC\",\n        \"other\"\n      ],\n      \"meta:enum\": {\n        \"CVSSv2\": \"Common Vulnerability Scoring System v2.0\",\n        \"CVSSv3\": \"Common Vulnerability Scoring System v3.0\",\n        \"CVSSv31\": \"Common Vulnerability Scoring System v3.1\",\n        \"CVSSv4\": \"Common Vulnerability Scoring System v4.0\",\n        \"OWASP\": \"OWASP Risk Rating Methodology\",\n        \"SSVC\": \"Stakeholder Specific Vulnerability Categorization\",\n        \"other\": \"Another severity or risk scoring methodology\"\n      }\n    },\n    \"impactAnalysisState\": {\n      \"type\": \"string\",\n      \"title\": \"Impact Analysis State\",\n      \"description\": \"Declares the current state of an occurrence of a vulnerability, after automated or manual analysis.\",\n      \"enum\": [\n        \"resolved\",\n        \"resolved_with_pedigree\",\n        \"exploitable\",\n        \"in_triage\",\n        \"false_positive\",\n        \"not_affected\"\n      ],\n      \"meta:enum\": {\n        \"resolved\": \"The vulnerability has been remediated.\",\n        \"resolved_with_pedigree\": \"The vulnerability has been remediated and evidence of the changes are provided in the affected components pedigree containing verifiable commit history and/or diff(s).\",\n        \"exploitable\": \"The vulnerability may be directly or indirectly exploitable.\",\n        \"in_triage\": \"The vulnerability is being investigated.\",\n        \"false_positive\": \"The vulnerability is not specific to the component or service and was falsely identified or associated.\",\n        \"not_affected\": \"The component or service is not affected by the vulnerability. Justification should be specified for all not_affected cases.\"\n      }\n    },\n    \"impactAnalysisJustification\": {\n      \"type\": \"string\",\n      \"title\": \"Impact Analysis Justification\",\n      \"description\": \"The rationale of why the impact analysis state was asserted.\",\n      \"enum\": [\n        \"code_not_present\",\n        \"code_not_reachable\",\n        \"requires_configuration\",\n        \"requires_dependency\",\n        \"requires_environment\",\n        \"protected_by_compiler\",\n        \"protected_at_runtime\",\n        \"protected_at_perimeter\",\n        \"protected_by_mitigating_control\"\n      ],\n      \"meta:enum\": {\n        \"code_not_present\": \"The code has been removed or tree-shaked.\",\n        \"code_not_reachable\": \"The vulnerable code is not invoked at runtime.\",\n        \"requires_configuration\": \"Exploitability requires a configurable option to be set/unset.\",\n        \"requires_dependency\": \"Exploitability requires a dependency that is not present.\",\n        \"requires_environment\": \"Exploitability requires a certain environment which is not present.\",\n        \"protected_by_compiler\": \"Exploitability requires a compiler flag to be set/unset.\",\n        \"protected_at_runtime\": \"Exploits are prevented at runtime.\",\n        \"protected_at_perimeter\": \"Attacks are blocked at physical, logical, or network perimeter.\",\n        \"protected_by_mitigating_control\": \"Preventative measures have been implemented that reduce the likelihood and/or impact of the vulnerability.\"\n      }\n    },\n    \"rating\": {\n      \"type\": \"object\",\n      \"title\": \"Rating\",\n      \"description\": \"Defines the severity or risk ratings of a vulnerability.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"source\": {\n          \"$ref\": \"#/definitions/vulnerabilitySource\",\n          \"description\": \"The source that calculated the severity or risk rating of the vulnerability.\"\n        },\n        \"score\": {\n          \"type\": \"number\",\n          \"title\": \"Score\",\n          \"description\": \"The numerical score of the rating.\"\n        },\n        \"severity\": {\n          \"$ref\": \"#/definitions/severity\",\n          \"description\": \"Textual representation of the severity that corresponds to the numerical score of the rating.\"\n        },\n        \"method\": {\n          \"$ref\": \"#/definitions/scoreMethod\"\n        },\n        \"vector\": {\n          \"type\": \"string\",\n          \"title\": \"Vector\",\n          \"description\": \"Textual representation of the metric values used to score the vulnerability\"\n        },\n        \"justification\": {\n          \"type\": \"string\",\n          \"title\": \"Justification\",\n          \"description\": \"A reason for rating the vulnerability as it was\"\n        }\n      }\n    },\n    \"vulnerabilitySource\": {\n      \"type\": \"object\",\n      \"title\": \"Source\",\n      \"description\": \"The source of vulnerability information. This is often the organization that published the vulnerability.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"url\": {\n          \"type\": \"string\",\n          \"title\": \"URL\",\n          \"description\": \"The url of the vulnerability documentation as provided by the source.\",\n          \"examples\": [\n            \"https://nvd.nist.gov/vuln/detail/CVE-2021-39182\"\n          ]\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"The name of the source.\",\n          \"examples\": [\n            \"NVD\",\n            \"National Vulnerability Database\",\n            \"OSS Index\",\n            \"VulnDB\",\n            \"GitHub Advisories\"\n          ]\n        }\n      }\n    },\n    \"vulnerability\": {\n      \"type\": \"object\",\n      \"title\": \"Vulnerability\",\n      \"description\": \"Defines a weakness in a component or service that could be exploited or triggered by a threat source.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the vulnerability elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"id\": {\n          \"type\": \"string\",\n          \"title\": \"ID\",\n          \"description\": \"The identifier that uniquely identifies the vulnerability.\",\n          \"examples\": [\n            \"CVE-2021-39182\",\n            \"GHSA-35m5-8cvj-8783\",\n            \"SNYK-PYTHON-ENROCRYPT-1912876\"\n          ]\n        },\n        \"source\": {\n          \"$ref\": \"#/definitions/vulnerabilitySource\",\n          \"description\": \"The source that published the vulnerability.\"\n        },\n        \"references\": {\n          \"type\": \"array\",\n          \"title\": \"References\",\n          \"description\": \"Zero or more pointers to vulnerabilities that are the equivalent of the vulnerability specified. Often times, the same vulnerability may exist in multiple sources of vulnerability intelligence, but have different identifiers. References provide a way to correlate vulnerabilities across multiple sources of vulnerability intelligence.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"id\",\n              \"source\"\n            ],\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"id\": {\n                \"type\": \"string\",\n                \"title\": \"ID\",\n                \"description\": \"An identifier that uniquely identifies the vulnerability.\",\n                \"examples\": [\n                  \"CVE-2021-39182\",\n                  \"GHSA-35m5-8cvj-8783\",\n                  \"SNYK-PYTHON-ENROCRYPT-1912876\"\n                ]\n              },\n              \"source\": {\n                \"$ref\": \"#/definitions/vulnerabilitySource\",\n                \"description\": \"The source that published the vulnerability.\"\n              }\n            }\n          }\n        },\n        \"ratings\": {\n          \"type\": \"array\",\n          \"title\": \"Ratings\",\n          \"description\": \"List of vulnerability ratings\",\n          \"items\": {\n            \"$ref\": \"#/definitions/rating\"\n          }\n        },\n        \"cwes\": {\n          \"type\": \"array\",\n          \"title\": \"CWEs\",\n          \"description\": \"List of Common Weaknesses Enumerations (CWEs) codes that describes this vulnerability.\",\n          \"examples\": [399],\n          \"items\": {\n            \"$ref\": \"#/definitions/cwe\"\n          }\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"title\": \"Description\",\n          \"description\": \"A description of the vulnerability as provided by the source.\"\n        },\n        \"detail\": {\n          \"type\": \"string\",\n          \"title\": \"Details\",\n          \"description\": \"If available, an in-depth description of the vulnerability as provided by the source organization. Details often include information useful in understanding root cause.\"\n        },\n        \"recommendation\": {\n          \"type\": \"string\",\n          \"title\": \"Recommendation\",\n          \"description\": \"Recommendations of how the vulnerability can be remediated or mitigated.\"\n        },\n        \"workaround\": {\n          \"type\": \"string\",\n          \"title\": \"Workarounds\",\n          \"description\": \"A bypass, usually temporary, of the vulnerability that reduces its likelihood and/or impact. Workarounds often involve changes to configuration or deployments.\"\n        },\n        \"proofOfConcept\": {\n          \"type\": \"object\",\n          \"title\": \"Proof of Concept\",\n          \"description\": \"Evidence used to reproduce the vulnerability.\",\n          \"properties\": {\n            \"reproductionSteps\": {\n              \"type\": \"string\",\n              \"title\": \"Steps to Reproduce\",\n              \"description\": \"Precise steps to reproduce the vulnerability.\"\n            },\n            \"environment\": {\n              \"type\": \"string\",\n              \"title\": \"Environment\",\n              \"description\": \"A description of the environment in which reproduction was possible.\"\n            },\n            \"supportingMaterial\": {\n              \"type\": \"array\",\n              \"title\": \"Supporting Material\",\n              \"description\": \"Supporting material that helps in reproducing or understanding how reproduction is possible. This may include screenshots, payloads, and PoC exploit code.\",\n              \"items\": { \"$ref\": \"#/definitions/attachment\" }\n            }\n          }\n        },\n        \"advisories\": {\n          \"type\": \"array\",\n          \"title\": \"Advisories\",\n          \"description\": \"Published advisories of the vulnerability if provided.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/advisory\"\n          }\n        },\n        \"created\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Created\",\n          \"description\": \"The date and time (timestamp) when the vulnerability record was created in the vulnerability database.\"\n        },\n        \"published\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Published\",\n          \"description\": \"The date and time (timestamp) when the vulnerability record was first published.\"\n        },\n        \"updated\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Updated\",\n          \"description\": \"The date and time (timestamp) when the vulnerability record was last updated.\"\n        },\n        \"rejected\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Rejected\",\n          \"description\": \"The date and time (timestamp) when the vulnerability record was rejected (if applicable).\"\n        },\n        \"credits\": {\n          \"type\": \"object\",\n          \"title\": \"Credits\",\n          \"description\": \"Individuals or organizations credited with the discovery of the vulnerability.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"organizations\": {\n              \"type\": \"array\",\n              \"title\": \"Organizations\",\n              \"description\": \"The organizations credited with vulnerability discovery.\",\n              \"items\": {\n                \"$ref\": \"#/definitions/organizationalEntity\"\n              }\n            },\n            \"individuals\": {\n              \"type\": \"array\",\n              \"title\": \"Individuals\",\n              \"description\": \"The individuals, not associated with organizations, that are credited with vulnerability discovery.\",\n              \"items\": {\n                \"$ref\": \"#/definitions/organizationalContact\"\n              }\n            }\n          }\n        },\n        \"tools\": {\n          \"title\": \"Tools\",\n          \"description\": \"The tool(s) used to identify, confirm, or score the vulnerability.\",\n          \"oneOf\": [\n            {\n              \"type\": \"object\",\n              \"title\": \"Tools\",\n              \"description\": \"The tool(s) used to identify, confirm, or score the vulnerability.\",\n              \"additionalProperties\": false,\n              \"properties\": {\n                \"components\": {\n                  \"type\": \"array\",\n                  \"items\": {\"$ref\": \"#/definitions/component\"},\n                  \"uniqueItems\": true,\n                  \"title\": \"Components\",\n                  \"description\": \"A list of software and hardware components used as tools.\"\n                },\n                \"services\": {\n                  \"type\": \"array\",\n                  \"items\": {\"$ref\": \"#/definitions/service\"},\n                  \"uniqueItems\": true,\n                  \"title\": \"Services\",\n                  \"description\": \"A list of services used as tools. This may include microservices, function-as-a-service, and other types of network or intra-process services.\"\n                }\n              }\n            },\n            {\n              \"type\": \"array\",\n              \"title\": \"Tools (legacy)\",\n              \"description\": \"[Deprecated]\\nThe tool(s) used to identify, confirm, or score the vulnerability.\",\n              \"deprecated\": true,\n              \"items\": {\"$ref\": \"#/definitions/tool\"}\n            }\n          ]\n        },\n        \"analysis\": {\n          \"type\": \"object\",\n          \"title\": \"Impact Analysis\",\n          \"description\": \"An assessment of the impact and exploitability of the vulnerability.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"state\": {\n              \"$ref\": \"#/definitions/impactAnalysisState\"\n            },\n            \"justification\": {\n              \"$ref\": \"#/definitions/impactAnalysisJustification\"\n            },\n            \"response\": {\n              \"type\": \"array\",\n              \"title\": \"Response\",\n              \"description\": \"A response to the vulnerability by the manufacturer, supplier, or project responsible for the affected component or service. More than one response is allowed. Responses are strongly encouraged for vulnerabilities where the analysis state is exploitable.\",\n              \"items\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"can_not_fix\",\n                  \"will_not_fix\",\n                  \"update\",\n                  \"rollback\",\n                  \"workaround_available\"\n                ],\n                \"meta:enum\": {\n                  \"can_not_fix\": \"Can not fix\",\n                  \"will_not_fix\": \"Will not fix\",\n                  \"update\": \"Update to a different revision or release\",\n                  \"rollback\": \"Revert to a previous revision or release\",\n                  \"workaround_available\": \"There is a workaround available\"\n                }\n              }\n            },\n            \"detail\": {\n              \"type\": \"string\",\n              \"title\": \"Detail\",\n              \"description\": \"Detailed description of the impact including methods used during assessment. If a vulnerability is not exploitable, this field should include specific details on why the component or service is not impacted by this vulnerability.\"\n            },\n            \"firstIssued\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"First Issued\",\n              \"description\": \"The date and time (timestamp) when the analysis was first issued.\"\n            },\n            \"lastUpdated\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Last Updated\",\n              \"description\": \"The date and time (timestamp) when the analysis was last updated.\"\n            }\n          }\n        },\n        \"affects\": {\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"ref\"\n            ],\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"ref\": {\n                \"anyOf\": [\n                  {\n                    \"title\": \"Ref\",\n                    \"$ref\": \"#/definitions/refLinkType\"\n                  },\n                  {\n                    \"title\": \"BOM-Link Element\",\n                    \"$ref\": \"#/definitions/bomLinkElementType\"\n                  }\n                ],\n                \"title\": \"Reference\",\n                \"description\": \"References a component or service by the objects bom-ref\"\n              },\n              \"versions\": {\n                \"type\": \"array\",\n                \"title\": \"Versions\",\n                \"description\": \"Zero or more individual versions or range of versions.\",\n                \"items\": {\n                  \"type\": \"object\",\n                  \"oneOf\": [\n                    {\n                      \"required\": [\"version\"]\n                    },\n                    {\n                      \"required\": [\"range\"]\n                    }\n                  ],\n                  \"additionalProperties\": false,\n                  \"properties\": {\n                    \"version\": {\n                      \"title\": \"Version\",\n                      \"description\": \"A single version of a component or service.\",\n                      \"$ref\": \"#/definitions/version\"\n                    },\n                    \"range\": {\n                      \"title\": \"Version Range\",\n                      \"description\": \"A version range specified in Package URL Version Range syntax (vers) which is defined at https://github.com/package-url/vers-spec\",\n                      \"$ref\": \"#/definitions/versionRange\"\n                    },\n                    \"status\": {\n                      \"title\": \"Status\",\n                      \"description\": \"The vulnerability status for the version or range of versions.\",\n                      \"$ref\": \"#/definitions/affectedStatus\",\n                      \"default\": \"affected\"\n                    }\n                  }\n                }\n              }\n            }\n          },\n          \"title\": \"Affects\",\n          \"description\": \"The components or services that are affected by the vulnerability.\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"affectedStatus\": {\n      \"description\": \"The vulnerability status of a given version or range of versions of a product. The statuses 'affected' and 'unaffected' indicate that the version is affected or unaffected by the vulnerability. The status 'unknown' indicates that it is unknown or unspecified whether the given version is affected. There can be many reasons for an 'unknown' status, including that an investigation has not been undertaken or that a vendor has not disclosed the status.\",\n      \"type\": \"string\",\n      \"enum\": [\n        \"affected\",\n        \"unaffected\",\n        \"unknown\"\n      ],\n      \"meta:enum\": {\n        \"affected\": \"The version is affected by the vulnerability.\",\n        \"unaffected\": \"The version is not affected by the vulnerability.\",\n        \"unknown\": \"It is unknown (or unspecified) whether the given version is affected.\"\n      }\n    },\n    \"version\": {\n      \"description\": \"A single disjunctive version identifier, for a component or service.\",\n      \"type\": \"string\",\n      \"maxLength\": 1024,\n      \"examples\": [\n        \"9.0.14\",\n        \"v1.33.7\",\n        \"7.0.0-M1\",\n        \"2.0pre1\",\n        \"1.0.0-beta1\",\n        \"0.8.15\"\n      ]\n    },\n    \"versionRange\": {\n      \"description\": \"A version range specified in Package URL Version Range syntax (vers) which is defined at https://github.com/package-url/vers-spec\",\n      \"type\": \"string\",\n      \"minLength\": 1,\n      \"maxLength\": 4096,\n      \"examples\": [\n        \"vers:cargo/9.0.14\",\n        \"vers:npm/1.2.3|>=2.0.0|<5.0.0\",\n        \"vers:pypi/0.0.0|0.0.1|0.0.2|0.0.3|1.0|2.0pre1\",\n        \"vers:tomee/>=1.0.0-beta1|<=1.7.5|>=7.0.0-M1|<=7.0.7|>=7.1.0|<=7.1.2|>=8.0.0-M1|<=8.0.1\",\n        \"vers:gem/>=2.2.0|!= 2.2.1|<2.3.0\"\n      ]\n    },\n    \"range\": {\n      \"deprecated\": true,\n      \"description\": \"Deprecated definition. use definition `versionRange` instead.\",\n      \"$ref\": \"#/definitions/versionRange\"\n    },\n    \"annotations\": {\n      \"type\": \"object\",\n      \"title\": \"Annotations\",\n      \"description\": \"A comment, note, explanation, or similar textual content which provides additional context to the object(s) being annotated.\",\n      \"required\": [\n        \"subjects\",\n        \"annotator\",\n        \"timestamp\",\n        \"text\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the annotation elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"subjects\": {\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"anyOf\": [\n              {\n                \"title\": \"Ref\",\n                \"$ref\": \"#/definitions/refLinkType\"\n              },\n              {\n                \"title\": \"BOM-Link Element\",\n                \"$ref\": \"#/definitions/bomLinkElementType\"\n              }\n            ]\n          },\n          \"title\": \"Subjects\",\n          \"description\": \"The object in the BOM identified by its bom-ref. This is often a component or service, but may be any object type supporting bom-refs.\"\n        },\n        \"annotator\": {\n          \"type\": \"object\",\n          \"title\": \"Annotator\",\n          \"description\": \"The organization, person, component, or service which created the textual content of the annotation.\",\n          \"oneOf\": [\n            {\n              \"required\": [\n                \"organization\"\n              ]\n            },\n            {\n              \"required\": [\n                \"individual\"\n              ]\n            },\n            {\n              \"required\": [\n                \"component\"\n              ]\n            },\n            {\n              \"required\": [\n                \"service\"\n              ]\n            }\n          ],\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"organization\": {\n              \"description\": \"The organization that created the annotation\",\n              \"$ref\": \"#/definitions/organizationalEntity\"\n            },\n            \"individual\": {\n              \"description\": \"The person that created the annotation\",\n              \"$ref\": \"#/definitions/organizationalContact\"\n            },\n            \"component\": {\n              \"description\": \"The tool or component that created the annotation\",\n              \"$ref\": \"#/definitions/component\"\n            },\n            \"service\": {\n              \"description\": \"The service that created the annotation\",\n              \"$ref\": \"#/definitions/service\"\n            }\n          }\n        },\n        \"timestamp\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Timestamp\",\n          \"description\": \"The date and time (timestamp) when the annotation was created.\"\n        },\n        \"text\": {\n          \"type\": \"string\",\n          \"title\": \"Text\",\n          \"description\": \"The textual content of the annotation.\"\n        },\n        \"signature\": {\n          \"$ref\": \"#/definitions/signature\",\n          \"title\": \"Signature\",\n          \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n        }\n      }\n    },\n    \"modelCard\": {\n      \"$comment\": \"Model card support in CycloneDX is derived from TensorFlow Model Card Toolkit released under the Apache 2.0 license and available from https://github.com/tensorflow/model-card-toolkit/blob/main/model_card_toolkit/schema/v0.0.2/model_card.schema.json. In addition, CycloneDX model card support includes portions of VerifyML, also released under the Apache 2.0 license and available from https://github.com/cylynx/verifyml/blob/main/verifyml/model_card_toolkit/schema/v0.0.4/model_card.schema.json.\",\n      \"type\": \"object\",\n      \"title\": \"Model Card\",\n      \"description\": \"A model card describes the intended uses of a machine learning model and potential limitations, including biases and ethical considerations. Model cards typically contain the training parameters, which datasets were used to train the model, performance metrics, and other relevant data useful for ML transparency. This object SHOULD be specified for any component of type `machine-learning-model` and must not be specified for other component types.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the model card elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"modelParameters\": {\n          \"type\": \"object\",\n          \"title\": \"Model Parameters\",\n          \"description\": \"Hyper-parameters for construction of the model.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"approach\": {\n              \"type\": \"object\",\n              \"title\": \"Approach\",\n              \"description\": \"The overall approach to learning used by the model for problem solving.\",\n              \"additionalProperties\": false,\n              \"properties\": {\n                \"type\": {\n                  \"type\": \"string\",\n                  \"title\": \"Learning Type\",\n                  \"description\": \"Learning types describing the learning problem or hybrid learning problem.\",\n                  \"enum\": [\n                    \"supervised\",\n                    \"unsupervised\",\n                    \"reinforcement-learning\",\n                    \"semi-supervised\",\n                    \"self-supervised\"\n                  ],\n                  \"meta:enum\": {\n                    \"supervised\": \"Supervised machine learning involves training an algorithm on labeled data to predict or classify new data based on the patterns learned from the labeled examples.\",\n                    \"unsupervised\": \"Unsupervised machine learning involves training algorithms on unlabeled data to discover patterns, structures, or relationships without explicit guidance, allowing the model to identify inherent structures or clusters within the data.\",\n                    \"reinforcement-learning\": \"Reinforcement learning is a type of machine learning where an agent learns to make decisions by interacting with an environment to maximize cumulative rewards, through trial and error.\",\n                    \"semi-supervised\": \"Semi-supervised machine learning utilizes a combination of labeled and unlabeled data during training to improve model performance, leveraging the benefits of both supervised and unsupervised learning techniques.\",\n                    \"self-supervised\": \"Self-supervised machine learning involves training models to predict parts of the input data from other parts of the same data, without requiring external labels, enabling learning from large amounts of unlabeled data.\"\n                  }\n                }\n              }\n            },\n            \"task\": {\n              \"type\": \"string\",\n              \"title\": \"Task\",\n              \"description\": \"Directly influences the input and/or output. Examples include classification, regression, clustering, etc.\"\n            },\n            \"architectureFamily\": {\n              \"type\": \"string\",\n              \"title\": \"Architecture Family\",\n              \"description\": \"The model architecture family such as transformer network, convolutional neural network, residual neural network, LSTM neural network, etc.\"\n            },\n            \"modelArchitecture\": {\n              \"type\": \"string\",\n              \"title\": \"Model Architecture\",\n              \"description\": \"The specific architecture of the model such as GPT-1, ResNet-50, YOLOv3, etc.\"\n            },\n            \"datasets\": {\n              \"type\": \"array\",\n              \"title\": \"Datasets\",\n              \"description\": \"The datasets used to train and evaluate the model.\",\n              \"items\" : {\n                \"oneOf\" : [\n                  {\n                    \"title\": \"Inline Data Information\",\n                    \"$ref\": \"#/definitions/componentData\"\n                  },\n                  {\n                    \"type\": \"object\",\n                    \"title\": \"Data Reference\",\n                    \"additionalProperties\": false,\n                    \"properties\": {\n                      \"ref\": {\n                        \"anyOf\": [\n                          {\n                            \"title\": \"Ref\",\n                            \"$ref\": \"#/definitions/refLinkType\"\n                          },\n                          {\n                            \"title\": \"BOM-Link Element\",\n                            \"$ref\": \"#/definitions/bomLinkElementType\"\n                          }\n                        ],\n                        \"title\": \"Reference\",\n                        \"type\": \"string\",\n                        \"description\": \"References a data component by the components bom-ref attribute\"\n                      }\n                    }\n                  }\n                ]\n              }\n            },\n            \"inputs\": {\n              \"type\": \"array\",\n              \"title\": \"Inputs\",\n              \"description\": \"The input format(s) of the model\",\n              \"items\": { \"$ref\": \"#/definitions/inputOutputMLParameters\" }\n            },\n            \"outputs\": {\n              \"type\": \"array\",\n              \"title\": \"Outputs\",\n              \"description\": \"The output format(s) from the model\",\n              \"items\": { \"$ref\": \"#/definitions/inputOutputMLParameters\" }\n            }\n          }\n        },\n        \"quantitativeAnalysis\": {\n          \"type\": \"object\",\n          \"title\": \"Quantitative Analysis\",\n          \"description\": \"A quantitative analysis of the model\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"performanceMetrics\": {\n              \"type\": \"array\",\n              \"title\": \"Performance Metrics\",\n              \"description\": \"The model performance metrics being reported. Examples may include accuracy, F1 score, precision, top-3 error rates, MSC, etc.\",\n              \"items\": { \"$ref\": \"#/definitions/performanceMetric\" }\n            },\n            \"graphics\": { \"$ref\": \"#/definitions/graphicsCollection\" }\n          }\n        },\n        \"considerations\": {\n          \"type\": \"object\",\n          \"title\": \"Considerations\",\n          \"description\": \"What considerations should be taken into account regarding the model's construction, training, and application?\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"users\": {\n              \"type\": \"array\",\n              \"title\": \"Users\",\n              \"description\": \"Who are the intended users of the model?\",\n              \"items\": {\n                \"type\": \"string\"\n              }\n            },\n            \"useCases\": {\n              \"type\": \"array\",\n              \"title\": \"Use Cases\",\n              \"description\": \"What are the intended use cases of the model?\",\n              \"items\": {\n                \"type\": \"string\"\n              }\n            },\n            \"technicalLimitations\": {\n              \"type\": \"array\",\n              \"title\": \"Technical Limitations\",\n              \"description\": \"What are the known technical limitations of the model? E.g. What kind(s) of data should the model be expected not to perform well on? What are the factors that might degrade model performance?\",\n              \"items\": {\n                \"type\": \"string\"\n              }\n            },\n            \"performanceTradeoffs\": {\n              \"type\": \"array\",\n              \"title\": \"Performance Tradeoffs\",\n              \"description\": \"What are the known tradeoffs in accuracy/performance of the model?\",\n              \"items\": {\n                \"type\": \"string\"\n              }\n            },\n            \"ethicalConsiderations\": {\n              \"type\": \"array\",\n              \"title\": \"Ethical Considerations\",\n              \"description\": \"What are the ethical risks involved in the application of this model?\",\n              \"items\": { \"$ref\": \"#/definitions/risk\" }\n            },\n            \"environmentalConsiderations\":{\n              \"$ref\": \"#/definitions/environmentalConsiderations\",\n              \"title\": \"Environmental Considerations\",\n              \"description\": \"What are the various environmental impacts the corresponding machine learning model has exhibited across its lifecycle?\"\n            },\n            \"fairnessAssessments\": {\n              \"type\": \"array\",\n              \"title\": \"Fairness Assessments\",\n              \"description\": \"How does the model affect groups at risk of being systematically disadvantaged? What are the harms and benefits to the various affected groups?\",\n              \"items\": {\n                \"$ref\": \"#/definitions/fairnessAssessment\"\n              }\n            }\n          }\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\"$ref\": \"#/definitions/property\"}\n        }\n      }\n    },\n    \"inputOutputMLParameters\": {\n      \"type\": \"object\",\n      \"title\": \"Input and Output Parameters\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"format\": {\n          \"title\": \"Input/Output Format\",\n          \"description\": \"The data format for input/output to the model.\",\n          \"type\": \"string\",\n          \"examples\": [ \"string\", \"image\", \"time-series\"]\n        }\n      }\n    },\n    \"componentData\": {\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"required\": [\n        \"type\"\n      ],\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the dataset elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\"\n        },\n        \"type\": {\n          \"type\": \"string\",\n          \"title\": \"Type of Data\",\n          \"description\": \"The general theme or subject matter of the data being specified.\",\n          \"enum\": [\n            \"source-code\",\n            \"configuration\",\n            \"dataset\",\n            \"definition\",\n            \"other\"\n          ],\n          \"meta:enum\": {\n            \"source-code\": \"Any type of code, code snippet, or data-as-code.\",\n            \"configuration\": \"Parameters or settings that may be used by other components.\",\n            \"dataset\": \"A collection of data.\",\n            \"definition\": \"Data that can be used to create new instances of what the definition defines.\",\n            \"other\": \"Any other type of data that does not fit into existing definitions.\"\n          }\n        },\n        \"name\": {\n          \"title\": \"Dataset Name\",\n          \"description\": \"The name of the dataset.\",\n          \"type\": \"string\"\n        },\n        \"contents\": {\n          \"type\": \"object\",\n          \"title\": \"Data Contents\",\n          \"description\": \"The contents or references to the contents of the data being described.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"attachment\": {\n              \"title\": \"Data Attachment\",\n              \"description\": \"A way to include textual or encoded data.\",\n              \"$ref\": \"#/definitions/attachment\"\n            },\n            \"url\": {\n              \"type\": \"string\",\n              \"title\": \"Data URL\",\n              \"description\": \"The URL to where the data can be retrieved.\",\n              \"format\": \"iri-reference\"\n            },\n            \"properties\": {\n              \"type\": \"array\",\n              \"title\": \"Configuration Properties\",\n              \"description\": \"Provides the ability to document name-value parameters used for configuration.\",\n              \"items\": {\n                \"$ref\": \"#/definitions/property\"\n              }\n            }\n          }\n        },\n        \"classification\": {\n          \"$ref\": \"#/definitions/dataClassification\"\n        },\n        \"sensitiveData\": {\n          \"type\": \"array\",\n          \"title\": \"Sensitive Data\",\n          \"description\": \"A description of any sensitive data in a dataset.\",\n          \"items\": {\n            \"type\": \"string\"\n          }\n        },\n        \"graphics\": { \"$ref\": \"#/definitions/graphicsCollection\" },\n        \"description\": {\n          \"title\": \"Dataset Description\",\n          \"description\": \"A description of the dataset. Can describe size of dataset, whether it's used for source code, training, testing, or validation, etc.\",\n          \"type\": \"string\"\n        },\n        \"governance\": {\n          \"title\": \"Data Governance\",\n          \"$ref\": \"#/definitions/dataGovernance\"\n        }\n      }\n    },\n    \"dataGovernance\": {\n      \"type\": \"object\",\n      \"title\": \"Data Governance\",\n      \"description\": \"Data governance captures information regarding data ownership, stewardship, and custodianship, providing insights into the individuals or entities responsible for managing, overseeing, and safeguarding the data throughout its lifecycle.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"custodians\": {\n          \"type\": \"array\",\n          \"title\": \"Data Custodians\",\n          \"description\": \"Data custodians are responsible for the safe custody, transport, and storage of data.\",\n          \"items\": { \"$ref\": \"#/definitions/dataGovernanceResponsibleParty\" }\n        },\n        \"stewards\": {\n          \"type\": \"array\",\n          \"title\": \"Data Stewards\",\n          \"description\": \"Data stewards are responsible for data content, context, and associated business rules.\",\n          \"items\": { \"$ref\": \"#/definitions/dataGovernanceResponsibleParty\" }\n        },\n        \"owners\": {\n          \"type\": \"array\",\n          \"title\": \"Data Owners\",\n          \"description\": \"Data owners are concerned with risk and appropriate access to data.\",\n          \"items\": { \"$ref\": \"#/definitions/dataGovernanceResponsibleParty\" }\n        }\n      }\n    },\n    \"dataGovernanceResponsibleParty\": {\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"organization\": {\n          \"title\": \"Organization\",\n          \"description\": \"The organization that is responsible for specific data governance role(s).\",\n          \"$ref\": \"#/definitions/organizationalEntity\"\n        },\n        \"contact\": {\n          \"title\": \"Individual\",\n          \"description\": \"The individual that is responsible for specific data governance role(s).\",\n          \"$ref\": \"#/definitions/organizationalContact\"\n        }\n      },\n      \"oneOf\":[\n        {\n          \"required\": [\"organization\"]\n        },\n        {\n          \"required\": [\"contact\"]\n        }\n      ]\n    },\n    \"graphicsCollection\": {\n      \"type\": \"object\",\n      \"title\": \"Graphics Collection\",\n      \"description\": \"A collection of graphics that represent various measurements.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"description\": {\n          \"title\": \"Description\",\n          \"description\": \"A description of this collection of graphics.\",\n          \"type\": \"string\"\n        },\n        \"collection\": {\n          \"title\": \"Collection\",\n          \"description\": \"A collection of graphics.\",\n          \"type\": \"array\",\n          \"items\": { \"$ref\": \"#/definitions/graphic\" }\n        }\n      }\n    },\n    \"graphic\": {\n      \"type\": \"object\",\n      \"title\": \"Graphic\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"The name of the graphic.\",\n          \"type\": \"string\"\n        },\n        \"image\": {\n          \"title\": \"Graphic Image\",\n          \"description\": \"The graphic (vector or raster). Base64 encoding must be specified for binary images.\",\n          \"$ref\": \"#/definitions/attachment\"\n        }\n      }\n    },\n    \"performanceMetric\": {\n      \"type\": \"object\",\n      \"title\": \"Performance Metric\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"type\": {\n          \"title\": \"Type\",\n          \"description\": \"The type of performance metric.\",\n          \"type\": \"string\"\n        },\n        \"value\": {\n          \"title\": \"Value\",\n          \"description\": \"The value of the performance metric.\",\n          \"type\": \"string\"\n        },\n        \"slice\": {\n          \"title\": \"Slice\",\n          \"description\": \"The name of the slice this metric was computed on. By default, assume this metric is not sliced.\",\n          \"type\": \"string\"\n        },\n        \"confidenceInterval\": {\n          \"title\": \"Confidence Interval\",\n          \"description\": \"The confidence interval of the metric.\",\n          \"type\": \"object\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"lowerBound\": {\n              \"title\": \"Lower Bound\",\n              \"description\": \"The lower bound of the confidence interval.\",\n              \"type\": \"string\"\n            },\n            \"upperBound\": {\n              \"title\": \"Upper Bound\",\n              \"description\": \"The upper bound of the confidence interval.\",\n              \"type\": \"string\"\n            }\n          }\n        }\n      }\n    },\n    \"risk\": {\n      \"type\": \"object\",\n      \"title\": \"Risk\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"The name of the risk.\",\n          \"type\": \"string\"\n        },\n        \"mitigationStrategy\": {\n          \"title\": \"Mitigation Strategy\",\n          \"description\": \"Strategy used to address this risk.\",\n          \"type\": \"string\"\n        }\n      }\n    },\n    \"fairnessAssessment\": {\n      \"type\": \"object\",\n      \"title\": \"Fairness Assessment\",\n      \"description\": \"Information about the benefits and harms of the model to an identified at risk group.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"groupAtRisk\": {\n          \"type\": \"string\",\n          \"title\": \"Group at Risk\",\n          \"description\": \"The groups or individuals at risk of being systematically disadvantaged by the model.\"\n        },\n        \"benefits\": {\n          \"type\": \"string\",\n          \"title\": \"Benefits\",\n          \"description\": \"Expected benefits to the identified groups.\"\n        },\n        \"harms\": {\n          \"type\": \"string\",\n          \"title\": \"Harms\",\n          \"description\": \"Expected harms to the identified groups.\"\n        },\n        \"mitigationStrategy\": {\n          \"type\": \"string\",\n          \"title\": \"Mitigation Strategy\",\n          \"description\": \"With respect to the benefits and harms outlined, please describe any mitigation strategy implemented.\"\n        }\n      }\n    },\n    \"dataClassification\": {\n      \"type\": \"string\",\n      \"title\": \"Data Classification\",\n      \"description\": \"Data classification tags data according to its type, sensitivity, and value if altered, stolen, or destroyed.\"\n    },\n    \"environmentalConsiderations\": {\n      \"type\": \"object\",\n      \"title\": \"Environmental Considerations\",\n      \"description\": \"Describes various environmental impact metrics.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"energyConsumptions\": {\n          \"title\": \"Energy Consumptions\",\n          \"description\": \"Describes energy consumption information incurred for one or more component lifecycle activities.\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/energyConsumption\"\n          }\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"energyConsumption\": {\n      \"title\": \"Energy consumption\",\n      \"description\": \"Describes energy consumption information incurred for the specified lifecycle activity.\",\n      \"type\": \"object\",\n      \"required\": [\n        \"activity\",\n        \"energyProviders\",\n        \"activityEnergyCost\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"activity\": {\n          \"type\": \"string\",\n          \"title\": \"Activity\",\n          \"description\": \"The type of activity that is part of a machine learning model development or operational lifecycle.\",\n          \"enum\": [\n            \"design\",\n            \"data-collection\",\n            \"data-preparation\",\n            \"training\",\n            \"fine-tuning\",\n            \"validation\",\n            \"deployment\",\n            \"inference\",\n            \"other\"\n          ],\n          \"meta:enum\": {\n            \"design\": \"A model design including problem framing, goal definition and algorithm selection.\",\n            \"data-collection\": \"Model data acquisition including search, selection and transfer.\",\n            \"data-preparation\": \"Model data preparation including data cleaning, labeling and conversion.\",\n            \"training\": \"Model building, training and generalized tuning.\",\n            \"fine-tuning\": \"Refining a trained model to produce desired outputs for a given problem space.\",\n            \"validation\": \"Model validation including model output evaluation and testing.\",\n            \"deployment\": \"Explicit model deployment to a target hosting infrastructure.\",\n            \"inference\": \"Generating an output response from a hosted model from a set of inputs.\",\n            \"other\": \"A lifecycle activity type whose description does not match currently defined values.\"\n          }\n        },\n        \"energyProviders\": {\n          \"title\": \"Energy Providers\",\n          \"description\": \"The provider(s) of the energy consumed by the associated model development lifecycle activity.\",\n          \"type\": \"array\",\n          \"items\": { \"$ref\": \"#/definitions/energyProvider\" }\n        },\n        \"activityEnergyCost\": {\n          \"title\": \"Activity Energy Cost\",\n          \"description\": \"The total energy cost associated with the model lifecycle activity.\",\n          \"$ref\": \"#/definitions/energyMeasure\"\n        },\n        \"co2CostEquivalent\": {\n          \"title\": \"CO2 Equivalent Cost\",\n          \"description\": \"The CO2 cost (debit) equivalent to the total energy cost.\",\n          \"$ref\": \"#/definitions/co2Measure\"\n        },\n        \"co2CostOffset\": {\n          \"title\": \"CO2 Cost Offset\",\n          \"description\": \"The CO2 offset (credit) for the CO2 equivalent cost.\",\n          \"$ref\": \"#/definitions/co2Measure\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"energyMeasure\": {\n      \"type\": \"object\",\n      \"title\": \"Energy Measure\",\n      \"description\": \"A measure of energy.\",\n      \"required\": [\n        \"value\",\n        \"unit\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"value\": {\n          \"type\": \"number\",\n          \"title\": \"Value\",\n          \"description\": \"Quantity of energy.\"\n        },\n        \"unit\": {\n          \"type\": \"string\",\n          \"enum\": [ \"kWh\" ],\n          \"title\": \"Unit\",\n          \"description\": \"Unit of energy.\",\n          \"meta:enum\": {\n            \"kWh\": \"Kilowatt-hour (kWh) is the energy delivered by one kilowatt (kW) of power for one hour (h).\"\n          }\n        }\n      }\n    },\n    \"co2Measure\": {\n      \"type\": \"object\",\n      \"title\": \"CO2 Measure\",\n      \"description\": \"A measure of carbon dioxide (CO2).\",\n      \"required\": [\n        \"value\",\n        \"unit\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"value\": {\n          \"type\": \"number\",\n          \"title\": \"Value\",\n          \"description\": \"Quantity of carbon dioxide (CO2).\"\n        },\n        \"unit\": {\n          \"type\": \"string\",\n          \"enum\": [ \"tCO2eq\" ],\n          \"title\": \"Unit\",\n          \"description\": \"Unit of carbon dioxide (CO2).\",\n          \"meta:enum\": {\n            \"tCO2eq\": \"Tonnes (t) of carbon dioxide (CO2) equivalent (eq).\"\n          }\n        }\n      }\n    },\n    \"energyProvider\": {\n      \"type\": \"object\",\n      \"title\": \"Energy Provider\",\n      \"description\": \"Describes the physical provider of energy used for model development or operations.\",\n      \"required\": [\n        \"organization\",\n        \"energySource\",\n        \"energyProvided\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the energy provider elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\",\n          \"$ref\": \"#/definitions/refType\"\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"title\": \"Description\",\n          \"description\": \"A description of the energy provider.\"\n        },\n        \"organization\": {\n          \"type\": \"object\",\n          \"title\": \"Organization\",\n          \"description\": \"The organization that provides energy.\",\n          \"$ref\": \"#/definitions/organizationalEntity\"\n        },\n        \"energySource\": {\n          \"type\": \"string\",\n          \"enum\": [\n            \"coal\",\n            \"oil\",\n            \"natural-gas\",\n            \"nuclear\",\n            \"wind\",\n            \"solar\",\n            \"geothermal\",\n            \"hydropower\",\n            \"biofuel\",\n            \"unknown\",\n            \"other\"\n          ],\n          \"meta:enum\": {\n            \"coal\": \"Energy produced by types of coal.\",\n            \"oil\": \"Petroleum products (primarily crude oil and its derivative fuel oils).\",\n            \"natural-gas\": \"Hydrocarbon gas liquids (HGL) that occur as gases at atmospheric pressure and as liquids under higher pressures including Natural gas (C5H12 and heavier), Ethane (C2H6), Propane (C3H8), etc.\",\n            \"nuclear\": \"Energy produced from the cores of atoms (i.e., through nuclear fission or fusion).\",\n            \"wind\": \"Energy produced from moving air.\",\n            \"solar\": \"Energy produced from the sun (i.e., solar radiation).\",\n            \"geothermal\": \"Energy produced from heat within the earth.\",\n            \"hydropower\": \"Energy produced from flowing water.\",\n            \"biofuel\": \"Liquid fuels produced from biomass feedstocks (i.e., organic materials such as plants or animals).\",\n            \"unknown\": \"The energy source is unknown.\",\n            \"other\": \"An energy source that is not listed.\"\n          },\n          \"title\": \"Energy Source\",\n          \"description\": \"The energy source for the energy provider.\"\n        },\n        \"energyProvided\": {\n          \"$ref\": \"#/definitions/energyMeasure\",\n          \"title\": \"Energy Provided\",\n          \"description\": \"The energy provided by the energy source for an associated activity.\"\n        },\n        \"externalReferences\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/externalReference\"},\n          \"title\": \"External References\",\n          \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n        }\n      }\n    },\n    \"postalAddress\": {\n      \"type\": \"object\",\n      \"title\": \"Postal address\",\n      \"description\": \"An address used to identify a contactable location.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the address elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\",\n          \"$ref\": \"#/definitions/refType\"\n        },\n        \"country\": {\n          \"type\": \"string\",\n          \"title\": \"Country\",\n          \"description\": \"The country name or the two-letter ISO 3166-1 country code.\"\n        },\n        \"region\": {\n          \"type\": \"string\",\n          \"title\": \"Region\",\n          \"description\": \"The region or state in the country.\",\n          \"examples\": [ \"Texas\" ]\n        },\n        \"locality\": {\n          \"type\": \"string\",\n          \"title\": \"Locality\",\n          \"description\": \"The locality or city within the country.\",\n          \"examples\": [ \"Austin\" ]\n        },\n        \"postOfficeBoxNumber\": {\n          \"type\": \"string\",\n          \"title\": \"Post Office Box Number\",\n          \"description\": \"The post office box number.\",\n          \"examples\": [ \"901\" ]\n        },\n        \"postalCode\": {\n          \"type\": \"string\",\n          \"title\": \"Postal Code\",\n          \"description\": \"The postal code.\",\n          \"examples\": [ \"78758\" ]\n        },\n        \"streetAddress\": {\n          \"type\": \"string\",\n          \"title\": \"Street Address\",\n          \"description\": \"The street address.\",\n          \"examples\": [ \"100 Main Street\" ]\n        }\n      }\n    },\n    \"formula\": {\n      \"title\": \"Formula\",\n      \"description\": \"Describes workflows and resources that captures rules and other aspects of how the associated BOM component or service was formed.\",\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the formula elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\",\n          \"$ref\": \"#/definitions/refType\"\n        },\n        \"components\": {\n          \"title\": \"Components\",\n          \"description\": \"Transient components that are used in tasks that constitute one or more of this formula's workflows\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/component\"\n          },\n          \"uniqueItems\": true\n        },\n        \"services\": {\n          \"title\": \"Services\",\n          \"description\": \"Transient services that are used in tasks that constitute one or more of this formula's workflows\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/service\"\n          },\n          \"uniqueItems\": true\n        },\n        \"workflows\": {\n          \"title\": \"Workflows\",\n          \"description\": \"List of workflows that can be declared to accomplish specific orchestrated goals and independently triggered.\",\n          \"$comment\": \"Different workflows can be designed to work together to perform end-to-end CI/CD builds and deployments.\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/workflow\"\n          },\n          \"uniqueItems\": true\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"workflow\": {\n      \"title\": \"Workflow\",\n      \"description\": \"A specialized orchestration task.\",\n      \"$comment\": \"Workflow are as task themselves and can trigger other workflow tasks.  These relationships can be modeled in the taskDependencies graph.\",\n      \"type\": \"object\",\n      \"required\": [\n        \"bom-ref\",\n        \"uid\",\n        \"taskTypes\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the workflow elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\",\n          \"$ref\": \"#/definitions/refType\"\n        },\n        \"uid\": {\n          \"title\": \"Unique Identifier (UID)\",\n          \"description\": \"The unique identifier for the resource instance within its deployment context.\",\n          \"type\": \"string\"\n        },\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"The name of the resource instance.\",\n          \"type\": \"string\"\n        },\n        \"description\": {\n          \"title\": \"Description\",\n          \"description\": \"A description of the resource instance.\",\n          \"type\": \"string\"\n        },\n        \"resourceReferences\": {\n          \"title\": \"Resource references\",\n          \"description\": \"References to component or service resources that are used to realize the resource instance.\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/resourceReferenceChoice\"\n          }\n        },\n        \"tasks\": {\n          \"title\": \"Tasks\",\n          \"description\": \"The tasks that comprise the workflow.\",\n          \"$comment\": \"Note that tasks can appear more than once as different instances (by name or UID).\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/task\"\n          }\n        },\n        \"taskDependencies\": {\n          \"title\": \"Task dependency graph\",\n          \"description\": \"The graph of dependencies between tasks within the workflow.\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/dependency\"\n          }\n        },\n        \"taskTypes\": {\n          \"title\": \"Task types\",\n          \"description\": \"Indicates the types of activities performed by the set of workflow tasks.\",\n          \"$comment\": \"Currently, these types reflect common CI/CD actions.\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/taskType\"\n          }\n        },\n        \"trigger\": {\n          \"title\": \"Trigger\",\n          \"description\": \"The trigger that initiated the task.\",\n          \"$ref\": \"#/definitions/trigger\"\n        },\n        \"steps\": {\n          \"title\": \"Steps\",\n          \"description\": \"The sequence of steps for the task.\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/step\"\n          },\n          \"uniqueItems\": true\n        },\n        \"inputs\": {\n          \"title\": \"Inputs\",\n          \"description\": \"Represents resources and data brought into a task at runtime by executor or task commands\",\n          \"examples\": [\"a `configuration` file which was declared as a local `component` or `externalReference`\"],\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/inputType\"\n          },\n          \"uniqueItems\": true\n        },\n        \"outputs\": {\n          \"title\": \"Outputs\",\n          \"description\": \"Represents resources and data output from a task at runtime by executor or task commands\",\n          \"examples\": [\"a log file or metrics data produced by the task\"],\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/outputType\"\n          },\n          \"uniqueItems\": true\n        },\n        \"timeStart\": {\n          \"title\": \"Time start\",\n          \"description\": \"The date and time (timestamp) when the task started.\",\n          \"type\": \"string\",\n          \"format\": \"date-time\"\n        },\n        \"timeEnd\": {\n          \"title\": \"Time end\",\n          \"description\": \"The date and time (timestamp) when the task ended.\",\n          \"type\": \"string\",\n          \"format\": \"date-time\"\n        },\n        \"workspaces\": {\n          \"title\": \"Workspaces\",\n          \"description\": \"A set of named filesystem or data resource shareable by workflow tasks.\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/workspace\"\n          }\n        },\n        \"runtimeTopology\": {\n          \"title\": \"Runtime topology\",\n          \"description\": \"A graph of the component runtime topology for workflow's instance.\",\n          \"$comment\": \"A description of the runtime component and service topology.  This can describe a partial or complete topology used to host and execute the task (e.g., hardware, operating systems, configurations, etc.),\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/dependency\"\n          }\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"task\": {\n      \"title\": \"Task\",\n      \"description\": \"Describes the inputs, sequence of steps and resources used to accomplish a task and its output.\",\n      \"$comment\": \"Tasks are building blocks for constructing assemble CI/CD workflows or pipelines.\",\n      \"type\": \"object\",\n      \"required\": [\n        \"bom-ref\",\n        \"uid\",\n        \"taskTypes\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the task elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\",\n          \"$ref\": \"#/definitions/refType\"\n        },\n        \"uid\": {\n          \"title\": \"Unique Identifier (UID)\",\n          \"description\": \"The unique identifier for the resource instance within its deployment context.\",\n          \"type\": \"string\"\n        },\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"The name of the resource instance.\",\n          \"type\": \"string\"\n        },\n        \"description\": {\n          \"title\": \"Description\",\n          \"description\": \"A description of the resource instance.\",\n          \"type\": \"string\"\n        },\n        \"resourceReferences\": {\n          \"title\": \"Resource references\",\n          \"description\": \"References to component or service resources that are used to realize the resource instance.\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/resourceReferenceChoice\"\n          }\n        },\n        \"taskTypes\": {\n          \"title\": \"Task types\",\n          \"description\": \"Indicates the types of activities performed by the set of workflow tasks.\",\n          \"$comment\": \"Currently, these types reflect common CI/CD actions.\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/taskType\"\n          }\n        },\n        \"trigger\": {\n          \"title\": \"Trigger\",\n          \"description\": \"The trigger that initiated the task.\",\n          \"$ref\": \"#/definitions/trigger\"\n        },\n        \"steps\": {\n          \"title\": \"Steps\",\n          \"description\": \"The sequence of steps for the task.\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/step\"\n          },\n          \"uniqueItems\": true\n        },\n        \"inputs\": {\n          \"title\": \"Inputs\",\n          \"description\": \"Represents resources and data brought into a task at runtime by executor or task commands\",\n          \"examples\": [\"a `configuration` file which was declared as a local `component` or `externalReference`\"],\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/inputType\"\n          },\n          \"uniqueItems\": true\n        },\n        \"outputs\": {\n          \"title\": \"Outputs\",\n          \"description\": \"Represents resources and data output from a task at runtime by executor or task commands\",\n          \"examples\": [\"a log file or metrics data produced by the task\"],\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/outputType\"\n          },\n          \"uniqueItems\": true\n        },\n        \"timeStart\": {\n          \"title\": \"Time start\",\n          \"description\": \"The date and time (timestamp) when the task started.\",\n          \"type\": \"string\",\n          \"format\": \"date-time\"\n        },\n        \"timeEnd\": {\n          \"title\": \"Time end\",\n          \"description\": \"The date and time (timestamp) when the task ended.\",\n          \"type\": \"string\",\n          \"format\": \"date-time\"\n        },\n        \"workspaces\": {\n          \"title\": \"Workspaces\",\n          \"description\": \"A set of named filesystem or data resource shareable by workflow tasks.\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/workspace\"\n          },\n          \"uniqueItems\": true\n        },\n        \"runtimeTopology\": {\n          \"title\": \"Runtime topology\",\n          \"description\": \"A graph of the component runtime topology for task's instance.\",\n          \"$comment\": \"A description of the runtime component and service topology.  This can describe a partial or complete topology used to host and execute the task (e.g., hardware, operating systems, configurations, etc.),\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/dependency\"\n          },\n          \"uniqueItems\": true\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"step\": {\n      \"type\": \"object\",\n      \"description\": \"Executes specific commands or tools in order to accomplish its owning task as part of a sequence.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"A name for the step.\",\n          \"type\": \"string\"\n        },\n        \"description\": {\n          \"title\": \"Description\",\n          \"description\": \"A description of the step.\",\n          \"type\": \"string\"\n        },\n        \"commands\": {\n          \"title\": \"Commands\",\n          \"description\": \"Ordered list of commands or directives for the step\",\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/command\"\n          }\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"command\": {\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"executed\": {\n          \"title\": \"Executed\",\n          \"description\": \"A text representation of the executed command.\",\n          \"type\": \"string\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"workspace\": {\n      \"title\": \"Workspace\",\n      \"description\": \"A named filesystem or data resource shareable by workflow tasks.\",\n      \"type\": \"object\",\n      \"required\": [\n        \"bom-ref\",\n        \"uid\"\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the workspace elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\",\n          \"$ref\": \"#/definitions/refType\"\n        },\n        \"uid\": {\n          \"title\": \"Unique Identifier (UID)\",\n          \"description\": \"The unique identifier for the resource instance within its deployment context.\",\n          \"type\": \"string\"\n        },\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"The name of the resource instance.\",\n          \"type\": \"string\"\n        },\n        \"aliases\": {\n          \"title\": \"Aliases\",\n          \"description\": \"The names for the workspace as referenced by other workflow tasks. Effectively, a name mapping so other tasks can use their own local name in their steps.\",\n          \"type\": \"array\",\n          \"items\": {\"type\": \"string\"}\n        },\n        \"description\": {\n          \"title\": \"Description\",\n          \"description\": \"A description of the resource instance.\",\n          \"type\": \"string\"\n        },\n        \"resourceReferences\": {\n          \"title\": \"Resource references\",\n          \"description\": \"References to component or service resources that are used to realize the resource instance.\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/resourceReferenceChoice\"\n          }\n        },\n        \"accessMode\": {\n          \"title\": \"Access mode\",\n          \"description\": \"Describes the read-write access control for the workspace relative to the owning resource instance.\",\n          \"type\": \"string\",\n          \"enum\": [\n            \"read-only\",\n            \"read-write\",\n            \"read-write-once\",\n            \"write-once\",\n            \"write-only\"\n          ]\n        },\n        \"mountPath\": {\n          \"title\": \"Mount path\",\n          \"description\": \"A path to a location on disk where the workspace will be available to the associated task's steps.\",\n          \"type\": \"string\"\n        },\n        \"managedDataType\": {\n          \"title\": \"Managed data type\",\n          \"description\": \"The name of a domain-specific data type the workspace represents.\",\n          \"$comment\": \"This property is for CI/CD frameworks that are able to provide access to structured, managed data at a more granular level than a filesystem.\",\n          \"examples\": [\"ConfigMap\",\"Secret\"],\n          \"type\": \"string\"\n        },\n        \"volumeRequest\": {\n          \"title\": \"Volume request\",\n          \"description\": \"Identifies the reference to the request for a specific volume type and parameters.\",\n          \"examples\": [\"a kubernetes Persistent Volume Claim (PVC) name\"],\n          \"type\": \"string\"\n        },\n        \"volume\": {\n          \"title\": \"Volume\",\n          \"description\": \"Information about the actual volume instance allocated to the workspace.\",\n          \"$comment\": \"The actual volume allocated may be different than the request.\",\n          \"examples\": [\"see https://kubernetes.io/docs/concepts/storage/persistent-volumes/\"],\n          \"$ref\": \"#/definitions/volume\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"volume\": {\n      \"title\": \"Volume\",\n      \"description\": \"An identifiable, logical unit of data storage tied to a physical device.\",\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"uid\": {\n          \"title\": \"Unique Identifier (UID)\",\n          \"description\": \"The unique identifier for the volume instance within its deployment context.\",\n          \"type\": \"string\"\n        },\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"The name of the volume instance\",\n          \"type\": \"string\"\n        },\n        \"mode\": {\n          \"title\": \"Mode\",\n          \"description\": \"The mode for the volume instance.\",\n          \"type\": \"string\",\n          \"enum\": [\n            \"filesystem\", \"block\"\n          ],\n          \"default\": \"filesystem\"\n        },\n        \"path\": {\n          \"title\": \"Path\",\n          \"description\": \"The underlying path created from the actual volume.\",\n          \"type\": \"string\"\n        },\n        \"sizeAllocated\": {\n          \"title\": \"Size allocated\",\n          \"description\": \"The allocated size of the volume accessible to the associated workspace. This should include the scalar size as well as IEC standard unit in either decimal or binary form.\",\n          \"examples\": [\"10GB\", \"2Ti\", \"1Pi\"],\n          \"type\": \"string\"\n        },\n        \"persistent\": {\n          \"title\": \"Persistent\",\n          \"description\": \"Indicates if the volume persists beyond the life of the resource it is associated with.\",\n          \"type\": \"boolean\"\n        },\n        \"remote\": {\n          \"title\": \"Remote\",\n          \"description\": \"Indicates if the volume is remotely (i.e., network) attached.\",\n          \"type\": \"boolean\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"trigger\": {\n      \"title\": \"Trigger\",\n      \"description\": \"Represents a resource that can conditionally activate (or fire) tasks based upon associated events and their data.\",\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"required\": [\n        \"type\",\n        \"bom-ref\",\n        \"uid\"\n      ],\n      \"properties\": {\n        \"bom-ref\": {\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the trigger elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\\nValue SHOULD not start with the BOM-Link intro 'urn:cdx:' to avoid conflicts with BOM-Links.\",\n          \"$ref\": \"#/definitions/refType\"\n        },\n        \"uid\": {\n          \"title\": \"Unique Identifier (UID)\",\n          \"description\": \"The unique identifier for the resource instance within its deployment context.\",\n          \"type\": \"string\"\n        },\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"The name of the resource instance.\",\n          \"type\": \"string\"\n        },\n        \"description\": {\n          \"title\": \"Description\",\n          \"description\": \"A description of the resource instance.\",\n          \"type\": \"string\"\n        },\n        \"resourceReferences\": {\n          \"title\": \"Resource references\",\n          \"description\": \"References to component or service resources that are used to realize the resource instance.\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/resourceReferenceChoice\"\n          }\n        },\n        \"type\": {\n          \"title\": \"Type\",\n          \"description\": \"The source type of event which caused the trigger to fire.\",\n          \"type\": \"string\",\n          \"enum\": [\n            \"manual\",\n            \"api\",\n            \"webhook\",\n            \"scheduled\"\n          ]\n        },\n        \"event\": {\n          \"title\": \"Event\",\n          \"description\": \"The event data that caused the associated trigger to activate.\",\n          \"$ref\": \"#/definitions/event\"\n        },\n        \"conditions\": {\n          \"type\": \"array\",\n          \"title\": \"Conditions\",\n          \"description\": \"A list of conditions used to determine if a trigger should be activated.\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/condition\"\n          }\n        },\n        \"timeActivated\": {\n          \"title\": \"Time activated\",\n          \"description\": \"The date and time (timestamp) when the trigger was activated.\",\n          \"type\": \"string\",\n          \"format\": \"date-time\"\n        },\n        \"inputs\": {\n          \"title\": \"Inputs\",\n          \"description\": \"Represents resources and data brought into a task at runtime by executor or task commands\",\n          \"examples\": [\"a `configuration` file which was declared as a local `component` or `externalReference`\"],\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/inputType\"\n          },\n          \"uniqueItems\": true\n        },\n        \"outputs\": {\n          \"title\": \"Outputs\",\n          \"description\": \"Represents resources and data output from a task at runtime by executor or task commands\",\n          \"examples\": [\"a log file or metrics data produced by the task\"],\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/outputType\"\n          },\n          \"uniqueItems\": true\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"event\": {\n      \"title\": \"Event\",\n      \"description\": \"Represents something that happened that may trigger a response.\",\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"uid\": {\n          \"title\": \"Unique Identifier (UID)\",\n          \"description\": \"The unique identifier of the event.\",\n          \"type\": \"string\"\n        },\n        \"description\": {\n          \"title\": \"Description\",\n          \"description\": \"A description of the event.\",\n          \"type\": \"string\"\n        },\n        \"timeReceived\": {\n          \"title\": \"Time Received\",\n          \"description\": \"The date and time (timestamp) when the event was received.\",\n          \"type\": \"string\",\n          \"format\": \"date-time\"\n        },\n        \"data\": {\n          \"title\": \"Data\",\n          \"description\": \"Encoding of the raw event data.\",\n          \"$ref\": \"#/definitions/attachment\"\n        },\n        \"source\": {\n          \"title\": \"Source\",\n          \"description\": \"References the component or service that was the source of the event\",\n          \"$ref\": \"#/definitions/resourceReferenceChoice\"\n        },\n        \"target\": {\n          \"title\": \"Target\",\n          \"description\": \"References the component or service that was the target of the event\",\n          \"$ref\": \"#/definitions/resourceReferenceChoice\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"inputType\": {\n      \"title\": \"Input type\",\n      \"description\": \"Type that represents various input data types and formats.\",\n      \"type\": \"object\",\n      \"oneOf\": [\n        {\n          \"required\": [\n            \"resource\"\n          ]\n        },\n        {\n          \"required\": [\n            \"parameters\"\n          ]\n        },\n        {\n          \"required\": [\n            \"environmentVars\"\n          ]\n        },\n        {\n          \"required\": [\n            \"data\"\n          ]\n        }\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"source\": {\n          \"title\": \"Source\",\n          \"description\": \"A reference to the component or service that provided the input to the task (e.g., reference to a service with data flow value of `inbound`)\",\n          \"examples\": [\n            \"source code repository\",\n            \"database\"\n          ],\n          \"$ref\": \"#/definitions/resourceReferenceChoice\"\n        },\n        \"target\": {\n          \"title\": \"Target\",\n          \"description\": \"A reference to the component or service that received or stored the input if not the task itself (e.g., a local, named storage workspace)\",\n          \"examples\": [\n            \"workspace\",\n            \"directory\"\n          ],\n          \"$ref\": \"#/definitions/resourceReferenceChoice\"\n        },\n        \"resource\": {\n          \"title\": \"Resource\",\n          \"description\": \"A reference to an independent resource provided as an input to a task by the workflow runtime.\",\n          \"examples\": [\n            \"a reference to a configuration file in a repository (i.e., a bom-ref)\",\n            \"a reference to a scanning service used in a task (i.e., a bom-ref)\"\n          ],\n          \"$ref\": \"#/definitions/resourceReferenceChoice\"\n        },\n        \"parameters\": {\n          \"title\": \"Parameters\",\n          \"description\": \"Inputs that have the form of parameters with names and values.\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"$ref\": \"#/definitions/parameter\"\n          }\n        },\n        \"environmentVars\": {\n          \"title\": \"Environment variables\",\n          \"description\": \"Inputs that have the form of parameters with names and values.\",\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"oneOf\": [\n              {\n                \"$ref\": \"#/definitions/property\"\n              },\n              {\n                \"type\": \"string\",\n                \"title\": \"String-Based Environment Variables\",\n                \"description\": \"In addition to the more common key–value pair format, some environment variables may consist of a single string without an explicit value assignment. These string-based environment variables typically act as flags or signals to software, indicating that a feature should be enabled, a mode should be activated, or a specific condition is present. Their presence alone conveys meaning.\"\n              }\n            ]\n          }\n        },\n        \"data\": {\n          \"title\": \"Data\",\n          \"description\": \"Inputs that have the form of data.\",\n          \"$ref\": \"#/definitions/attachment\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"outputType\": {\n      \"type\": \"object\",\n      \"oneOf\": [\n        {\n          \"required\": [\n            \"resource\"\n          ]\n        },\n        {\n          \"required\": [\n            \"environmentVars\"\n          ]\n        },\n        {\n          \"required\": [\n            \"data\"\n          ]\n        }\n      ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"type\": {\n          \"title\": \"Type\",\n          \"description\": \"Describes the type of data output.\",\n          \"type\": \"string\",\n          \"enum\": [\n            \"artifact\",\n            \"attestation\",\n            \"log\",\n            \"evidence\",\n            \"metrics\",\n            \"other\"\n          ]\n        },\n        \"source\": {\n          \"title\": \"Source\",\n          \"description\": \"Component or service that generated or provided the output from the task (e.g., a build tool)\",\n          \"$ref\": \"#/definitions/resourceReferenceChoice\"\n        },\n        \"target\": {\n          \"title\": \"Target\",\n          \"description\": \"Component or service that received the output from the task (e.g., reference to an artifactory service with data flow value of `outbound`)\",\n          \"examples\": [\"a log file described as an `externalReference` within its target domain.\"],\n          \"$ref\": \"#/definitions/resourceReferenceChoice\"\n        },\n        \"resource\": {\n          \"title\": \"Resource\",\n          \"description\": \"A reference to an independent resource generated as output by the task.\",\n          \"examples\": [\n            \"configuration file\",\n            \"source code\",\n            \"scanning service\"\n          ],\n          \"$ref\": \"#/definitions/resourceReferenceChoice\"\n        },\n        \"data\": {\n          \"title\": \"Data\",\n          \"description\": \"Outputs that have the form of data.\",\n          \"$ref\": \"#/definitions/attachment\"\n        },\n        \"environmentVars\": {\n          \"title\": \"Environment variables\",\n          \"description\": \"Outputs that have the form of environment variables.\",\n          \"type\": \"array\",\n          \"items\": {\n            \"oneOf\": [\n              {\n                \"$ref\": \"#/definitions/property\"\n              },\n              {\n                \"type\": \"string\",\n                \"title\": \"String-Based Environment Variables\",\n                \"description\": \"In addition to the more common key–value pair format, some environment variables may consist of a single string without an explicit value assignment. These string-based environment variables typically act as flags or signals to software, indicating that a feature should be enabled, a mode should be activated, or a specific condition is present. Their presence alone conveys meaning.\"\n              }\n            ]\n          },\n          \"uniqueItems\": true\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"resourceReferenceChoice\": {\n      \"title\": \"Resource reference choice\",\n      \"description\": \"A reference to a locally defined resource (e.g., a bom-ref) or an externally accessible resource.\",\n      \"$comment\": \"Enables reference to a resource that participates in a workflow; using either internal (bom-ref) or external (externalReference) types.\",\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"ref\": {\n          \"title\": \"BOM Reference\",\n          \"description\": \"References an object by its bom-ref attribute\",\n          \"anyOf\": [\n            {\n              \"title\": \"Ref\",\n              \"$ref\": \"#/definitions/refLinkType\"\n            },\n            {\n              \"title\": \"BOM-Link Element\",\n              \"$ref\": \"#/definitions/bomLinkElementType\"\n            }\n          ]\n        },\n        \"externalReference\": {\n          \"title\": \"External reference\",\n          \"description\": \"Reference to an externally accessible resource.\",\n          \"$ref\": \"#/definitions/externalReference\"\n        }\n      },\n      \"oneOf\": [\n        {\n          \"required\": [\n            \"ref\"\n          ]\n        },\n        {\n          \"required\": [\n            \"externalReference\"\n          ]\n        }\n      ]\n    },\n    \"condition\": {\n      \"title\": \"Condition\",\n      \"description\": \"A condition that was used to determine a trigger should be activated.\",\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"description\": {\n          \"title\": \"Description\",\n          \"description\": \"Describes the set of conditions which cause the trigger to activate.\",\n          \"type\": \"string\"\n        },\n        \"expression\": {\n          \"title\": \"Expression\",\n          \"description\": \"The logical expression that was evaluated that determined the trigger should be fired.\",\n          \"type\": \"string\"\n        },\n        \"properties\": {\n          \"type\": \"array\",\n          \"title\": \"Properties\",\n          \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/property\"\n          }\n        }\n      }\n    },\n    \"taskType\": {\n      \"type\": \"string\",\n      \"enum\": [\n        \"copy\",\n        \"clone\",\n        \"lint\",\n        \"scan\",\n        \"merge\",\n        \"build\",\n        \"test\",\n        \"deliver\",\n        \"deploy\",\n        \"release\",\n        \"clean\",\n        \"other\"\n      ],\n      \"meta:enum\": {\n        \"copy\": \"A task that copies software or data used to accomplish other tasks in the workflow.\",\n        \"clone\": \"A task that clones a software repository into the workflow in order to retrieve its source code or data for use in a build step.\",\n        \"lint\": \"A task that checks source code for programmatic and stylistic errors.\",\n        \"scan\": \"A task that performs a scan against source code, or built or deployed components and services. Scans are typically run to gather or test for security vulnerabilities or policy compliance.\",\n        \"merge\": \"A task that merges changes or fixes into source code prior to a build step in the workflow.\",\n        \"build\": \"A task that builds the source code, dependencies and/or data into an artifact that can be deployed to and executed on target systems.\",\n        \"test\": \"A task that verifies the functionality of a component or service.\",\n        \"deliver\": \"A task that delivers a built artifact to one or more target repositories or storage systems.\",\n        \"deploy\": \"A task that deploys a built artifact for execution on one or more target systems.\",\n        \"release\": \"A task that releases a built, versioned artifact to a target repository or distribution system.\",\n        \"clean\": \"A task that cleans unnecessary tools, build artifacts and/or data from workflow storage.\",\n        \"other\": \"A workflow task that does not match current task type definitions.\"\n      }\n    },\n    \"parameter\": {\n      \"title\": \"Parameter\",\n      \"description\": \"A representation of a functional parameter.\",\n      \"type\": \"object\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"title\": \"Name\",\n          \"description\": \"The name of the parameter.\",\n          \"type\": \"string\"\n        },\n        \"value\": {\n          \"title\": \"Value\",\n          \"description\": \"The value of the parameter.\",\n          \"type\": \"string\"\n        },\n        \"dataType\": {\n          \"title\": \"Data type\",\n          \"description\": \"The data type of the parameter.\",\n          \"type\": \"string\"\n        }\n      }\n    },\n    \"componentIdentityEvidence\": {\n      \"type\": \"object\",\n      \"title\": \"Identity Evidence\",\n      \"description\": \"Evidence that substantiates the identity of a component.\",\n      \"required\": [ \"field\" ],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"field\": {\n          \"type\": \"string\",\n          \"enum\": [\n            \"group\", \"name\", \"version\", \"purl\", \"cpe\", \"omniborId\", \"swhid\", \"swid\", \"hash\"\n          ],\n          \"title\": \"Field\",\n          \"description\": \"The identity field of the component which the evidence describes.\"\n        },\n        \"confidence\": {\n          \"type\": \"number\",\n          \"minimum\": 0,\n          \"maximum\": 1,\n          \"title\": \"Confidence\",\n          \"description\": \"The overall confidence of the evidence from 0 - 1, where 1 is 100% confidence.\"\n        },\n        \"concludedValue\": {\n          \"type\": \"string\",\n          \"title\": \"Concluded Value\",\n          \"description\": \"The value of the field (cpe, purl, etc) that has been concluded based on the aggregate of all methods (if available).\"\n        },\n        \"methods\": {\n          \"type\": \"array\",\n          \"title\": \"Methods\",\n          \"description\": \"The methods used to extract and/or analyze the evidence.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"technique\" ,\n              \"confidence\"\n            ],\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"technique\": {\n                \"title\": \"Technique\",\n                \"description\": \"The technique used in this method of analysis.\",\n                \"type\": \"string\",\n                \"enum\": [\n                  \"source-code-analysis\",\n                  \"binary-analysis\",\n                  \"manifest-analysis\",\n                  \"ast-fingerprint\",\n                  \"hash-comparison\",\n                  \"instrumentation\",\n                  \"dynamic-analysis\",\n                  \"filename\",\n                  \"attestation\",\n                  \"other\"\n                ]\n              },\n              \"confidence\": {\n                \"type\": \"number\",\n                \"minimum\": 0,\n                \"maximum\": 1,\n                \"title\": \"Confidence\",\n                \"description\": \"The confidence of the evidence from 0 - 1, where 1 is 100% confidence. Confidence is specific to the technique used. Each technique of analysis can have independent confidence.\"\n              },\n              \"value\": {\n                \"type\": \"string\",\n                \"title\": \"Value\",\n                \"description\": \"The value or contents of the evidence.\"\n              }\n            }\n          }\n        },\n        \"tools\": {\n          \"type\": \"array\",\n          \"uniqueItems\": true,\n          \"items\": {\n            \"anyOf\": [\n              {\n                \"title\": \"Ref\",\n                \"$ref\": \"#/definitions/refLinkType\"\n              },\n              {\n                \"title\": \"BOM-Link Element\",\n                \"$ref\": \"#/definitions/bomLinkElementType\"\n              }\n            ]\n          },\n          \"title\": \"BOM References\",\n          \"description\": \"The object in the BOM identified by its bom-ref. This is often a component or service but may be any object type supporting bom-refs. Tools used for analysis should already be defined in the BOM, either in the metadata/tools, components, or formulation.\"\n        }\n      }\n    },\n    \"standard\": {\n      \"type\": \"object\",\n      \"title\": \"Standard\",\n      \"description\": \"A standard may consist of regulations, industry or organizational-specific standards, maturity models, best practices, or any other requirements which can be evaluated against or attested to.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\"\n        },\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"The name of the standard. This will often be a shortened, single name of the standard.\"\n        },\n        \"version\": {\n          \"type\": \"string\",\n          \"title\": \"Version\",\n          \"description\": \"The version of the standard.\"\n        },\n        \"description\": {\n          \"type\": \"string\",\n          \"title\": \"Description\",\n          \"description\": \"The description of the standard.\"\n        },\n        \"owner\": {\n          \"type\": \"string\",\n          \"title\": \"Owner\",\n          \"description\": \"The owner of the standard, often the entity responsible for its release.\"\n        },\n        \"requirements\": {\n          \"type\": \"array\",\n          \"title\": \"Requirements\",\n          \"description\": \"The list of requirements comprising the standard.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"title\": \"Requirement\",\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"bom-ref\": {\n                \"$ref\": \"#/definitions/refType\",\n                \"title\": \"BOM Reference\",\n                \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\"\n              },\n              \"identifier\": {\n                \"type\": \"string\",\n                \"title\": \"Identifier\",\n                \"description\": \"The unique identifier used in the standard to identify a specific requirement. This should match what is in the standard and should not be the requirements bom-ref.\"\n              },\n              \"title\": {\n                \"type\": \"string\",\n                \"title\": \"Title\",\n                \"description\": \"The title of the requirement.\"\n              },\n              \"text\": {\n                \"type\": \"string\",\n                \"title\": \"Text\",\n                \"description\": \"The textual content of the requirement.\"\n              },\n              \"descriptions\": {\n                \"type\": \"array\",\n                \"title\": \"Descriptions\",\n                \"description\": \"The supplemental text that provides additional guidance or context to the requirement, but is not directly part of the requirement.\",\n                \"items\": { \"type\":  \"string\" }\n              },\n              \"openCre\": {\n                \"type\": \"array\",\n                \"title\": \"OWASP OpenCRE Identifier(s)\",\n                \"description\": \"The Common Requirements Enumeration (CRE) identifier(s). CRE is a structured and standardized framework for uniting security standards and guidelines. CRE links each section of a resource to a shared topic identifier (a Common Requirement). Through this shared topic link, all resources map to each other. Use of CRE promotes clear and unambiguous communication among stakeholders.\",\n                \"items\": {\n                  \"type\":  \"string\",\n                  \"pattern\": \"^CRE:[0-9]+-[0-9]+$\",\n                  \"examples\": [ \"CRE:764-507\" ]\n                }\n              },\n              \"parent\": {\n                \"$ref\": \"#/definitions/refLinkType\",\n                \"title\": \"Parent BOM Reference\",\n                \"description\": \"The `bom-ref` to a parent requirement. This establishes a hierarchy of requirements. Top-level requirements must not define a parent. Only child requirements should define parents.\"\n              },\n              \"properties\": {\n                \"type\": \"array\",\n                \"title\": \"Properties\",\n                \"description\": \"Provides the ability to document properties in a name-value store. This provides flexibility to include data not officially supported in the standard without having to use additional namespaces or create extensions. Unlike key-value stores, properties support duplicate names, each potentially having different values. Property names of interest to the general public are encouraged to be registered in the [CycloneDX Property Taxonomy](https://github.com/CycloneDX/cyclonedx-property-taxonomy). Formal registration is optional.\",\n                \"items\": {\n                  \"$ref\": \"#/definitions/property\"\n                }\n              },\n              \"externalReferences\": {\n                \"type\": \"array\",\n                \"items\": {\"$ref\": \"#/definitions/externalReference\"},\n                \"title\": \"External References\",\n                \"description\": \"External references provide a way to document systems, sites, and information that may be relevant, but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n              }\n            }\n          }\n        },\n        \"levels\": {\n          \"type\": \"array\",\n          \"title\": \"Levels\",\n          \"description\": \"The list of levels associated with the standard. Some standards have different levels of compliance.\",\n          \"items\": {\n            \"type\": \"object\",\n            \"title\": \"Level\",\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"bom-ref\": {\n                \"$ref\": \"#/definitions/refType\",\n                \"title\": \"BOM Reference\",\n                \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\"\n              },\n              \"identifier\": {\n                \"type\": \"string\",\n                \"title\": \"Identifier\",\n                \"description\": \"The identifier used in the standard to identify a specific level.\"\n              },\n              \"title\": {\n                \"type\": \"string\",\n                \"title\": \"Title\",\n                \"description\": \"The title of the level.\"\n              },\n              \"description\": {\n                \"type\": \"string\",\n                \"title\": \"Description\",\n                \"description\": \"The description of the level.\"\n              },\n              \"requirements\": {\n                \"type\": \"array\",\n                \"title\": \"Requirements\",\n                \"description\": \"The list of requirement `bom-ref`s that comprise the level.\",\n                \"items\": { \"$ref\": \"#/definitions/refLinkType\" }\n              }\n            }\n          }\n        },\n        \"externalReferences\": {\n          \"type\": \"array\",\n          \"items\": {\"$ref\": \"#/definitions/externalReference\"},\n          \"title\": \"External References\",\n          \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\"\n        },\n        \"signature\": {\n          \"$ref\": \"#/definitions/signature\",\n          \"title\": \"Signature\",\n          \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n        }\n      }\n    },\n    \"signature\": {\n      \"$ref\": \"jsf-0.82.schema.json#/definitions/signature\",\n      \"title\": \"Signature\",\n      \"description\": \"Enveloped signature in [JSON Signature Format (JSF)](https://cyberphone.github.io/doc/security/jsf.html).\"\n    },\n    \"cryptoProperties\": {\n      \"type\": \"object\",\n      \"title\": \"Cryptographic Properties\",\n      \"description\": \"Cryptographic assets have properties that uniquely define them and that make them actionable for further reasoning. As an example, it makes a difference if one knows the algorithm family (e.g. AES) or the specific variant or instantiation (e.g. AES-128-GCM). This is because the security level and the algorithm primitive (authenticated encryption) are only defined by the definition of the algorithm variant. The presence of a weak cryptographic algorithm like SHA1 vs. HMAC-SHA1 also makes a difference.\",\n      \"additionalProperties\": false,\n      \"required\": [\n        \"assetType\"\n      ],\n      \"properties\": {\n        \"assetType\": {\n          \"type\": \"string\",\n          \"title\": \"Asset Type\",\n          \"description\": \"Cryptographic assets occur in several forms. Algorithms and protocols are most commonly implemented in specialized cryptographic libraries. They may, however, also be 'hardcoded' in software components. Certificates and related cryptographic material like keys, tokens, secrets or passwords are other cryptographic assets to be modelled.\",\n          \"enum\": [\n            \"algorithm\",\n            \"certificate\",\n            \"protocol\",\n            \"related-crypto-material\"\n          ],\n          \"meta:enum\": {\n            \"algorithm\": \"Mathematical function commonly used for data encryption, authentication, and digital signatures.\",\n            \"certificate\": \"An electronic document that is used to provide the identity or validate a public key.\",\n            \"protocol\": \"A set of rules and guidelines that govern the behavior and communication with each other.\",\n            \"related-crypto-material\": \"Other cryptographic assets related to algorithms, certificates, and protocols such as keys and tokens.\"\n          }\n        },\n        \"algorithmProperties\": {\n          \"type\": \"object\",\n          \"title\": \"Algorithm Properties\",\n          \"description\": \"Additional properties specific to a cryptographic algorithm.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"primitive\": {\n              \"type\": \"string\",\n              \"title\": \"primitive\",\n              \"description\": \"Cryptographic building blocks used in higher-level cryptographic systems and protocols. Primitives represent different cryptographic routines: deterministic random bit generators (drbg, e.g. CTR_DRBG from NIST SP800-90A-r1), message authentication codes (mac, e.g. HMAC-SHA-256), blockciphers (e.g. AES), streamciphers (e.g. Salsa20), signatures (e.g. ECDSA), hash functions (e.g. SHA-256), public-key encryption schemes (pke, e.g. RSA), extended output functions (xof, e.g. SHAKE256), key derivation functions (e.g. pbkdf2), key agreement algorithms (e.g. ECDH), key encapsulation mechanisms (e.g. ML-KEM), authenticated encryption (ae, e.g. AES-GCM) and the combination of multiple algorithms (combiner, e.g. SP800-56Cr2).\",\n              \"enum\": [\n                \"drbg\",\n                \"mac\",\n                \"block-cipher\",\n                \"stream-cipher\",\n                \"signature\",\n                \"hash\",\n                \"pke\",\n                \"xof\",\n                \"kdf\",\n                \"key-agree\",\n                \"kem\",\n                \"ae\",\n                \"combiner\",\n                \"key-wrap\",\n                \"other\",\n                \"unknown\"\n              ],\n              \"meta:enum\": {\n                \"drbg\": \"Deterministic Random Bit Generator (DRBG) is a type of pseudorandom number generator designed to produce a sequence of bits from an initial seed value. DRBGs are commonly used in cryptographic applications where reproducibility of random values is important.\",\n                \"mac\": \"In cryptography, a Message Authentication Code (MAC) is information used for authenticating and integrity-checking a message.\",\n                \"block-cipher\": \"A block cipher is a symmetric key algorithm that operates on fixed-size blocks of data. It encrypts or decrypts the data in block units, providing confidentiality. Block ciphers are widely used in various cryptographic modes and protocols for secure data transmission.\",\n                \"stream-cipher\": \"A stream cipher is a symmetric key cipher where plaintext digits are combined with a pseudorandom cipher digit stream (keystream).\",\n                \"signature\": \"In cryptography, a signature is a digital representation of a message or data that proves its origin, identity, and integrity. Digital signatures are generated using cryptographic algorithms and are widely used for authentication and verification in secure communication.\",\n                \"hash\": \"A hash function is a mathematical algorithm that takes an input (or 'message') and produces a fixed-size string of characters, which is typically a hash value. Hash functions are commonly used in various cryptographic applications, including data integrity verification and password hashing.\",\n                \"pke\": \"Public Key Encryption (PKE) is a type of encryption that uses a pair of public and private keys for secure communication. The public key is used for encryption, while the private key is used for decryption. PKE is a fundamental component of public-key cryptography.\",\n                \"xof\": \"An XOF is an extendable output function that can take arbitrary input and creates a stream of output, up to a limit determined by the size of the internal state of the hash function that underlies the XOF.\",\n                \"kdf\": \"A Key Derivation Function (KDF) derives key material from another source of entropy while preserving the entropy of the input.\",\n                \"key-agree\": \"In cryptography, a key-agreement is a protocol whereby two or more parties agree on a cryptographic key in such a way that both influence the outcome.\",\n                \"kem\": \"A Key Encapsulation Mechanism (KEM) algorithm is a mechanism for transporting random keying material to a recipient using the recipient's public key.\",\n                \"ae\": \"Authenticated Encryption (AE) is a cryptographic process that provides both confidentiality and data integrity. It ensures that the encrypted data has not been tampered with and comes from a legitimate source. AE is commonly used in secure communication protocols.\",\n                \"combiner\": \"A combiner aggregates many candidates for a cryptographic primitive and generates a new candidate for the same primitive.\",\n                \"key-wrap\": \"Key-wrap is a cryptographic technique used to securely encrypt and protect cryptographic keys using algorithms like AES.\",\n                \"other\": \"Another primitive type.\",\n                \"unknown\": \"The primitive is not known.\"\n              }\n            },\n            \"algorithmFamily\": {\n              \"$ref\": \"cryptography-defs.schema.json#/definitions/algorithmFamiliesEnum\",\n              \"title\": \"Algorithm Family\",\n              \"description\": \"A valid algorithm family identifier. If specified, this value must be one of the enumeration of valid algorithm Family identifiers defined in the `cryptography-defs.schema.json` subschema.\",\n              \"examples\": [\"3DES\", \"Blowfish\", \"ECDH\"]\n            },\n            \"parameterSetIdentifier\": {\n              \"type\": \"string\",\n              \"title\": \"Parameter Set Identifier\",\n              \"description\": \"An identifier for the parameter set of the cryptographic algorithm. Examples: in AES128, '128' identifies the key length in bits, in SHA256, '256' identifies the digest length, '128' in SHAKE128 identifies its maximum security level in bits, and 'SHA2-128s' identifies a parameter set used in SLH-DSA (FIPS205).\"\n            },\n            \"curve\": {\n              \"deprecated\": true,\n              \"type\": \"string\",\n              \"title\": \"Elliptic Curve\",\n              \"description\": \"[Deprecated] This will be removed in a future version. Use `@.ellipticCurve` instead.\\nThe specific underlying Elliptic Curve (EC) definition employed which is an indicator of the level of security strength, performance and complexity. Absent an authoritative source of curve names, CycloneDX recommends using curve names as defined at [https://neuromancer.sk/std/](https://neuromancer.sk/std/), the source of which can be found at [https://github.com/J08nY/std-curves](https://github.com/J08nY/std-curves).\"\n            },\n            \"ellipticCurve\": {\n              \"$ref\": \"cryptography-defs.schema.json#/definitions/ellipticCurvesEnum\",\n              \"title\": \"Elliptic Curve\",\n              \"description\": \"The specific underlying Elliptic Curve (EC) definition employed which is an indicator of the level of security strength, performance and complexity. If specified, this value must be one of the enumeration of valid elliptic curves identifiers defined in the `cryptography-defs.schema.json` subschema.\"\n            },\n            \"executionEnvironment\": {\n              \"type\": \"string\",\n              \"title\": \"Execution Environment\",\n              \"description\": \"The target and execution environment in which the algorithm is implemented in.\",\n              \"enum\": [\n                \"software-plain-ram\",\n                \"software-encrypted-ram\",\n                \"software-tee\",\n                \"hardware\",\n                \"other\",\n                \"unknown\"\n              ],\n              \"meta:enum\": {\n                \"software-plain-ram\": \"A software implementation running in plain unencrypted RAM.\",\n                \"software-encrypted-ram\": \"A software implementation running in encrypted RAM.\",\n                \"software-tee\": \"A software implementation running in a trusted execution environment.\",\n                \"hardware\": \"A hardware implementation.\",\n                \"other\": \"Another implementation environment.\",\n                \"unknown\": \"The execution environment is not known.\"\n              }\n            },\n            \"implementationPlatform\": {\n              \"type\": \"string\",\n              \"title\": \"Implementation platform\",\n              \"description\": \"The target platform for which the algorithm is implemented. The implementation can be 'generic', running on any platform or for a specific platform.\",\n              \"enum\": [\n                \"generic\",\n                \"x86_32\",\n                \"x86_64\",\n                \"armv7-a\",\n                \"armv7-m\",\n                \"armv8-a\",\n                \"armv8-m\",\n                \"armv9-a\",\n                \"armv9-m\",\n                \"s390x\",\n                \"ppc64\",\n                \"ppc64le\",\n                \"other\",\n                \"unknown\"\n              ]\n            },\n            \"certificationLevel\": {\n              \"type\": \"array\",\n              \"title\": \"Certification Level\",\n              \"description\": \"The certification that the implementation of the cryptographic algorithm has received, if any. Certifications include revisions and levels of FIPS 140 or Common Criteria of different Extended Assurance Levels (CC-EAL).\",\n              \"items\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"none\",\n                  \"fips140-1-l1\",\n                  \"fips140-1-l2\",\n                  \"fips140-1-l3\",\n                  \"fips140-1-l4\",\n                  \"fips140-2-l1\",\n                  \"fips140-2-l2\",\n                  \"fips140-2-l3\",\n                  \"fips140-2-l4\",\n                  \"fips140-3-l1\",\n                  \"fips140-3-l2\",\n                  \"fips140-3-l3\",\n                  \"fips140-3-l4\",\n                  \"cc-eal1\",\n                  \"cc-eal1+\",\n                  \"cc-eal2\",\n                  \"cc-eal2+\",\n                  \"cc-eal3\",\n                  \"cc-eal3+\",\n                  \"cc-eal4\",\n                  \"cc-eal4+\",\n                  \"cc-eal5\",\n                  \"cc-eal5+\",\n                  \"cc-eal6\",\n                  \"cc-eal6+\",\n                  \"cc-eal7\",\n                  \"cc-eal7+\",\n                  \"other\",\n                  \"unknown\"\n                ],\n                \"meta:enum\": {\n                  \"none\": \"No certification obtained\",\n                  \"fips140-1-l1\": \"FIPS 140-1 Level 1\",\n                  \"fips140-1-l2\": \"FIPS 140-1 Level 2\",\n                  \"fips140-1-l3\": \"FIPS 140-1 Level 3\",\n                  \"fips140-1-l4\": \"FIPS 140-1 Level 4\",\n                  \"fips140-2-l1\": \"FIPS 140-2 Level 1\",\n                  \"fips140-2-l2\": \"FIPS 140-2 Level 2\",\n                  \"fips140-2-l3\": \"FIPS 140-2 Level 3\",\n                  \"fips140-2-l4\": \"FIPS 140-2 Level 4\",\n                  \"fips140-3-l1\": \"FIPS 140-3 Level 1\",\n                  \"fips140-3-l2\": \"FIPS 140-3 Level 2\",\n                  \"fips140-3-l3\": \"FIPS 140-3 Level 3\",\n                  \"fips140-3-l4\": \"FIPS 140-3 Level 4\",\n                  \"cc-eal1\": \"Common Criteria - Evaluation Assurance Level 1\",\n                  \"cc-eal1+\": \"Common Criteria - Evaluation Assurance Level 1 (Augmented)\",\n                  \"cc-eal2\": \"Common Criteria - Evaluation Assurance Level 2\",\n                  \"cc-eal2+\": \"Common Criteria - Evaluation Assurance Level 2 (Augmented)\",\n                  \"cc-eal3\": \"Common Criteria - Evaluation Assurance Level 3\",\n                  \"cc-eal3+\": \"Common Criteria - Evaluation Assurance Level 3 (Augmented)\",\n                  \"cc-eal4\": \"Common Criteria - Evaluation Assurance Level 4\",\n                  \"cc-eal4+\": \"Common Criteria - Evaluation Assurance Level 4 (Augmented)\",\n                  \"cc-eal5\": \"Common Criteria - Evaluation Assurance Level 5\",\n                  \"cc-eal5+\": \"Common Criteria - Evaluation Assurance Level 5 (Augmented)\",\n                  \"cc-eal6\": \"Common Criteria - Evaluation Assurance Level 6\",\n                  \"cc-eal6+\": \"Common Criteria - Evaluation Assurance Level 6 (Augmented)\",\n                  \"cc-eal7\": \"Common Criteria - Evaluation Assurance Level 7\",\n                  \"cc-eal7+\": \"Common Criteria - Evaluation Assurance Level 7 (Augmented)\",\n                  \"other\": \"Another certification\",\n                  \"unknown\": \"The certification level is not known\"\n                }\n              }\n            },\n            \"mode\": {\n              \"type\": \"string\",\n              \"title\": \"Mode\",\n              \"description\": \"The mode of operation in which the cryptographic algorithm (block cipher) is used.\",\n              \"enum\": [\n                \"cbc\",\n                \"ecb\",\n                \"ccm\",\n                \"gcm\",\n                \"cfb\",\n                \"ofb\",\n                \"ctr\",\n                \"other\",\n                \"unknown\"\n              ],\n              \"meta:enum\": {\n                \"cbc\": \"Cipher block chaining\",\n                \"ecb\": \"Electronic codebook\",\n                \"ccm\": \"Counter with cipher block chaining message authentication code\",\n                \"gcm\": \"Galois/counter\",\n                \"cfb\": \"Cipher feedback\",\n                \"ofb\": \"Output feedback\",\n                \"ctr\": \"Counter\",\n                \"other\": \"Another mode of operation\",\n                \"unknown\": \"The mode of operation is not known\"\n              }\n            },\n            \"padding\": {\n              \"type\": \"string\",\n              \"title\": \"Padding\",\n              \"description\": \"The padding scheme that is used for the cryptographic algorithm.\",\n              \"enum\": [\n                \"pkcs5\",\n                \"pkcs7\",\n                \"pkcs1v15\",\n                \"oaep\",\n                \"raw\",\n                \"other\",\n                \"unknown\"\n              ],\n              \"meta:enum\": {\n                \"pkcs5\": \"Public Key Cryptography Standard: Password-Based Cryptography\",\n                \"pkcs7\": \"Public Key Cryptography Standard: Cryptographic Message Syntax\",\n                \"pkcs1v15\": \"Public Key Cryptography Standard: RSA Cryptography v1.5\",\n                \"oaep\": \"Optimal asymmetric encryption padding\",\n                \"raw\": \"Raw\",\n                \"other\": \"Another padding scheme\",\n                \"unknown\": \"The padding scheme is not known\"\n              }\n            },\n            \"cryptoFunctions\": {\n              \"type\": \"array\",\n              \"title\": \"Cryptographic functions\",\n              \"description\": \"The cryptographic functions implemented by the cryptographic algorithm.\",\n              \"items\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"generate\",\n                  \"keygen\",\n                  \"encrypt\",\n                  \"decrypt\",\n                  \"digest\",\n                  \"tag\",\n                  \"keyderive\",\n                  \"sign\",\n                  \"verify\",\n                  \"encapsulate\",\n                  \"decapsulate\",\n                  \"other\",\n                  \"unknown\"\n                ]\n              }\n            },\n            \"classicalSecurityLevel\": {\n              \"type\": \"integer\",\n              \"title\": \"classical security level\",\n              \"description\": \"The classical security level that a cryptographic algorithm provides (in bits).\",\n              \"minimum\": 0\n            },\n            \"nistQuantumSecurityLevel\": {\n              \"type\": \"integer\",\n              \"title\": \"NIST security strength category\",\n              \"description\": \"The NIST security strength category as defined in https://csrc.nist.gov/projects/post-quantum-cryptography/post-quantum-cryptography-standardization/evaluation-criteria/security-(evaluation-criteria). A value of 0 indicates that none of the categories are met.\",\n              \"minimum\": 0,\n              \"maximum\": 6\n            }\n          }\n        },\n        \"certificateProperties\": {\n          \"type\": \"object\",\n          \"title\": \"Certificate Properties\",\n          \"description\": \"Properties for cryptographic assets of asset type 'certificate'\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"serialNumber\": {\n              \"type\": \"string\",\n              \"title\": \"Serial Number\",\n              \"description\": \"The serial number is a unique identifier for the certificate issued by a CA.\"\n            },\n            \"subjectName\": {\n              \"type\": \"string\",\n              \"title\": \"Subject Name\",\n              \"description\": \"The subject name for the certificate\"\n            },\n            \"issuerName\": {\n              \"type\": \"string\",\n              \"title\": \"Issuer Name\",\n              \"description\": \"The issuer name for the certificate\"\n            },\n            \"notValidBefore\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Not Valid Before\",\n              \"description\": \"The date and time according to ISO-8601 standard from which the certificate is valid\"\n            },\n            \"notValidAfter\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Not Valid After\",\n              \"description\": \"The date and time according to ISO-8601 standard from which the certificate is not valid anymore\"\n            },\n            \"signatureAlgorithmRef\": {\n              \"deprecated\": true,\n              \"$ref\": \"#/definitions/refType\",\n              \"title\": \"Algorithm Reference\",\n              \"description\": \"[DEPRECATED] This will be removed in a future version. Use `@.relatedCryptographicAssets` instead.\\nThe bom-ref to signature algorithm used by the certificate\"\n            },\n            \"subjectPublicKeyRef\": {\n              \"deprecated\": true,\n              \"$ref\": \"#/definitions/refType\",\n              \"title\": \"Key reference\",\n              \"description\": \"[DEPRECATED] This will be removed in a future version. Use `@.relatedCryptographicAssets` instead.\\nThe bom-ref to the public key of the subject\"\n            },\n            \"certificateFormat\": {\n              \"type\": \"string\",\n              \"title\": \"Certificate Format\",\n              \"description\": \"The format of the certificate\",\n              \"examples\": [\n                \"X.509\",\n                \"PEM\",\n                \"DER\",\n                \"CVC\"\n              ]\n            },\n            \"certificateExtension\": {\n              \"deprecated\": true,\n              \"type\": \"string\",\n              \"title\": \"Certificate File Extension\",\n              \"description\": \"[DEPRECATED] This will be removed in a future version. Use `@.certificateFileExtension` instead.\\nThe file extension of the certificate\",\n              \"examples\": [\n                \"crt\",\n                \"pem\",\n                \"cer\",\n                \"der\",\n                \"p12\"\n              ]\n            },\n            \"certificateFileExtension\": {\n              \"type\": \"string\",\n              \"title\": \"Certificate File Extension\",\n              \"description\": \"The file extension of the certificate.\",\n              \"examples\": [\n                \"crt\",\n                \"pem\",\n                \"cer\",\n                \"der\",\n                \"p12\"\n              ]\n            },\n            \"fingerprint\": {\n              \"type\": \"object\",\n              \"$ref\": \"#/definitions/hash\",\n              \"title\": \"Certificate Fingerprint\",\n              \"description\": \"The fingerprint is a cryptographic hash of the certificate excluding it's signature.\"\n            },\n            \"certificateState\": {\n              \"type\": \"array\",\n              \"title\": \"Certificate Lifecycle State\",\n              \"description\": \"The certificate lifecycle is a comprehensive process that manages digital certificates from their initial creation to eventual expiration or revocation. It typically involves several stages\",\n              \"items\": {\n                \"type\": \"object\",\n                \"title\": \"State\",\n                \"description\": \"The state of the certificate.\",\n                \"oneOf\": [\n                  {\n                    \"title\": \"Pre-Defined State\",\n                    \"required\": [\n                      \"state\"\n                    ],\n                    \"additionalProperties\": false,\n                    \"properties\": {\n                      \"state\": {\n                        \"type\": \"string\",\n                        \"title\": \"State\",\n                        \"description\": \"A pre-defined state in the certificate lifecycle.\",\n                        \"enum\": [\n                          \"pre-activation\",\n                          \"active\",\n                          \"suspended\",\n                          \"deactivated\",\n                          \"revoked\",\n                          \"destroyed\"\n                        ],\n                        \"meta:enum\": {\n                          \"pre-activation\": \"The certificate has been issued by the issuing certificate authority (CA) but has not been authorized for use.\",\n                          \"active\": \"The certificate may be used to cryptographically protect information, cryptographically process previously protected information, or both.\",\n                          \"deactivated\": \"Certificates in the deactivated state shall not be used to apply cryptographic protection but, in some cases, may be used to process cryptographically protected information.\",\n                          \"suspended\": \"The use of a certificate may be suspended for several possible reasons.\",\n                          \"revoked\": \"A revoked certificate is a digital certificate that has been invalidated by the issuing certificate authority (CA) before its scheduled expiration date.\",\n                          \"destroyed\": \"The certificate has been destroyed.\"\n                        }\n                      },\n                      \"reason\": {\n                        \"type\": \"string\",\n                        \"title\": \"Reason\",\n                        \"description\": \"A reason for the certificate being in this state.\"\n                      }\n                    }\n                  },\n                  {\n                    \"title\": \"Custom State\",\n                    \"required\": [\n                      \"name\"\n                    ],\n                    \"additionalProperties\": false,\n                    \"properties\": {\n                      \"name\": {\n                        \"type\": \"string\",\n                        \"title\": \"State\",\n                        \"description\": \"The name of the certificate lifecycle state.\"\n                      },\n                      \"description\": {\n                        \"type\": \"string\",\n                        \"title\": \"Description\",\n                        \"description\": \"The description of the certificate lifecycle state.\"\n                      },\n                      \"reason\": {\n                        \"type\": \"string\",\n                        \"title\": \"Reason\",\n                        \"description\": \"A reason for the certificate being in this state.\"\n                      }\n                    }\n                  }\n                ]\n              }\n            },\n            \"creationDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Creation Date\",\n              \"description\": \"The date and time (timestamp) when the certificate was created or pre-activated.\"\n            },\n            \"activationDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Activation Date\",\n              \"description\": \"The date and time (timestamp) when the certificate was activated.\"\n            },\n            \"deactivationDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Deactivation Date\",\n              \"description\": \"The date and time (timestamp) when the related certificate was deactivated.\"\n            },\n            \"revocationDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Revocation Date\",\n              \"description\": \"The date and time (timestamp) when the certificate was revoked.\"\n            },\n            \"destructionDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Destruction Date\",\n              \"description\": \"The date and time (timestamp) when the certificate was destroyed.\"\n            },\n            \"certificateExtensions\": {\n              \"type\": \"array\",\n              \"title\": \"Certificate Extensions\",\n              \"description\": \"A certificate extension is a field that provides additional information about the certificate or its use. Extensions are used to convey additional information beyond the standard fields.\",\n              \"items\": {\n                \"type\": \"object\",\n                \"title\": \"Extension\",\n                \"description\": \"\",\n                \"oneOf\": [\n                  {\n                    \"title\": \"Common Extensions\",\n                    \"required\": [\n                      \"commonExtensionName\",\n                      \"commonExtensionValue\"\n                    ],\n                    \"additionalProperties\": false,\n                    \"properties\": {\n                      \"commonExtensionName\": {\n                        \"type\": \"string\",\n                        \"title\": \"name\",\n                        \"description\": \"The name of the extension.\",\n                        \"enum\": [\n                          \"basicConstraints\",\n                          \"keyUsage\",\n                          \"extendedKeyUsage\",\n                          \"subjectAlternativeName\",\n                          \"authorityKeyIdentifier\",\n                          \"subjectKeyIdentifier\",\n                          \"authorityInformationAccess\",\n                          \"certificatePolicies\",\n                          \"crlDistributionPoints\",\n                          \"signedCertificateTimestamp\"\n                        ],\n                        \"meta:enum\": {\n                          \"basicConstraints\": \"Specifies whether a certificate can be used as a CA certificate or not.\",\n                          \"keyUsage\": \"Specifies the allowed uses of the public key in the certificate.\",\n                          \"extendedKeyUsage\": \"Specifies additional purposes for which the public key can be used.\",\n                          \"subjectAlternativeName\": \"Allows inclusion of additional names to identify the entity associated with the certificate.\",\n                          \"authorityKeyIdentifier\": \"Identifies the public key of the CA that issued the certificate.\",\n                          \"subjectKeyIdentifier\": \"Identifies the public key associated with the entity the certificate was issued to.\",\n                          \"authorityInformationAccess\": \"Contains CA issuers and OCSP information.\",\n                          \"certificatePolicies\": \"Defines the policies under which the certificate was issued and can be used.\",\n                          \"crlDistributionPoints\": \"Contains one or more URLs where a Certificate Revocation List (CRL) can be obtained.\",\n                          \"signedCertificateTimestamp\": \"Shows that the certificate has been publicly logged, which helps prevent the issuance of rogue certificates by a CA. Log ID, timestamp and signature as proof.\"\n                        }\n                      },\n                      \"commonExtensionValue\": {\n                        \"type\": \"string\",\n                        \"title\": \"Value\",\n                        \"description\": \"The value of the certificate extension.\"\n                      }\n                    }\n                  },\n                  {\n                    \"title\": \"Custom Extensions\",\n                    \"description\": \"Custom extensions may convey application-specific or vendor-specific data not covered by standard extensions. The structure and semantics of custom extensions are typically defined outside of public standards. CycloneDX leverages properties to support this capability.\",\n                    \"required\": [\n                      \"customExtensionName\"\n                    ],\n                    \"additionalProperties\": false,\n                    \"properties\": {\n                      \"customExtensionName\": {\n                        \"type\": \"string\",\n                        \"title\": \"Name\",\n                        \"description\": \"The name for the custom certificate extension.\"\n                      },\n                      \"customExtensionValue\": {\n                        \"type\": \"string\",\n                        \"title\": \"Value\",\n                        \"description\": \"The description of the custom certificate extension.\"\n                      }\n                    }\n                  }\n                ]\n              }\n            },\n            \"relatedCryptographicAssets\": {\n              \"$ref\": \"#/definitions/relatedCryptographicAssets\",\n              \"title\": \"Related Cryptographic Assets\",\n              \"description\": \"A list of cryptographic assets related to this component.\"\n            }\n          }\n        },\n        \"relatedCryptoMaterialProperties\": {\n          \"type\": \"object\",\n          \"title\": \"Related Cryptographic Material Properties\",\n          \"description\": \"Properties for cryptographic assets of asset type: `related-crypto-material`\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"type\": {\n              \"type\": \"string\",\n              \"title\": \"relatedCryptoMaterialType\",\n              \"description\": \"The type for the related cryptographic material\",\n              \"enum\": [\n                \"private-key\",\n                \"public-key\",\n                \"secret-key\",\n                \"key\",\n                \"ciphertext\",\n                \"signature\",\n                \"digest\",\n                \"initialization-vector\",\n                \"nonce\",\n                \"seed\",\n                \"salt\",\n                \"shared-secret\",\n                \"tag\",\n                \"additional-data\",\n                \"password\",\n                \"credential\",\n                \"token\",\n                \"other\",\n                \"unknown\"\n              ],\n              \"meta:enum\": {\n                \"private-key\": \"The confidential key of a key pair used in asymmetric cryptography.\",\n                \"public-key\": \"The non-confidential key of a key pair used in asymmetric cryptography.\",\n                \"secret-key\": \"A key used to encrypt and decrypt messages in symmetric cryptography.\",\n                \"key\": \"A piece of information, usually an octet string, which, when processed through a cryptographic algorithm, processes cryptographic data.\",\n                \"ciphertext\": \"The result of encryption performed on plaintext using an algorithm (or cipher).\",\n                \"signature\": \"A cryptographic value that is calculated from the data and a key known only by the signer.\",\n                \"digest\": \"The output of the hash function.\",\n                \"initialization-vector\": \"A fixed-size random or pseudo-random value used as an input parameter for cryptographic algorithms.\",\n                \"nonce\": \"A random or pseudo-random number that can only be used once in a cryptographic communication.\",\n                \"seed\": \"The input to a pseudo-random number generator. Different seeds generate different pseudo-random sequences.\",\n                \"salt\": \"A value used in a cryptographic process, usually to ensure that the results of computations for one instance cannot be reused by an attacker.\",\n                \"shared-secret\": \"A piece of data known only to the parties involved, in a secure communication.\",\n                \"tag\": \"A message authentication code (MAC), sometimes known as an authentication tag, is a short piece of information used for authenticating and integrity-checking a message.\",\n                \"additional-data\": \"An unspecified collection of data with relevance to cryptographic activity.\",\n                \"password\": \"A secret word, phrase, or sequence of characters used during authentication or authorization.\",\n                \"credential\": \"Establishes the identity of a party to communication, usually in the form of cryptographic keys or passwords.\",\n                \"token\": \"An object encapsulating a security identity.\",\n                \"other\": \"Another type of cryptographic asset.\",\n                \"unknown\": \"The type of cryptographic asset is not known.\"\n              }\n            },\n            \"id\": {\n              \"type\": \"string\",\n              \"title\": \"ID\",\n              \"description\": \"The unique identifier for the related cryptographic material.\"\n            },\n            \"state\": {\n              \"type\": \"string\",\n              \"title\": \"State\",\n              \"description\": \"The key state as defined by NIST SP 800-57.\",\n              \"enum\": [\n                \"pre-activation\",\n                \"active\",\n                \"suspended\",\n                \"deactivated\",\n                \"compromised\",\n                \"destroyed\"\n              ]\n            },\n            \"algorithmRef\": {\n              \"deprecated\": true,\n              \"$ref\": \"#/definitions/refType\",\n              \"title\": \"Algorithm Reference\",\n              \"description\": \"[DEPRECATED] Use `@.relatedCryptographicAssets` instead.\\nThe bom-ref to the algorithm used to generate the related cryptographic material.\"\n            },\n            \"creationDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Creation Date\",\n              \"description\": \"The date and time (timestamp) when the related cryptographic material was created.\"\n            },\n            \"activationDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Activation Date\",\n              \"description\": \"The date and time (timestamp) when the related cryptographic material was activated.\"\n            },\n            \"updateDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Update Date\",\n              \"description\": \"The date and time (timestamp) when the related cryptographic material was updated.\"\n            },\n            \"expirationDate\": {\n              \"type\": \"string\",\n              \"format\": \"date-time\",\n              \"title\": \"Expiration Date\",\n              \"description\": \"The date and time (timestamp) when the related cryptographic material expires.\"\n            },\n            \"value\": {\n              \"type\": \"string\",\n              \"title\": \"Value\",\n              \"description\": \"The associated value of the cryptographic material.\"\n            },\n            \"size\": {\n              \"type\": \"integer\",\n              \"title\": \"Size\",\n              \"description\": \"The size of the cryptographic asset (in bits).\"\n            },\n            \"format\": {\n              \"type\": \"string\",\n              \"title\": \"Format\",\n              \"description\": \"The format of the related cryptographic material (e.g. P8, PEM, DER).\"\n            },\n            \"securedBy\": {\n              \"$ref\": \"#/definitions/securedBy\",\n              \"title\": \"Secured By\",\n              \"description\": \"The mechanism by which the cryptographic asset is secured by.\"\n            },\n            \"fingerprint\": {\n              \"type\": \"object\",\n              \"$ref\": \"#/definitions/hash\",\n              \"title\": \"Fingerprint\",\n              \"description\": \"The fingerprint is a cryptographic hash of the asset.\"\n            },\n            \"relatedCryptographicAssets\": {\n              \"$ref\": \"#/definitions/relatedCryptographicAssets\",\n              \"title\": \"Related Cryptographic Assets\",\n              \"description\": \"A list of cryptographic assets related to this component.\"\n            }\n          }\n        },\n        \"protocolProperties\": {\n          \"type\": \"object\",\n          \"title\": \"Protocol Properties\",\n          \"description\": \"Properties specific to cryptographic assets of type: `protocol`.\",\n          \"additionalProperties\": false,\n          \"properties\": {\n            \"type\": {\n              \"type\": \"string\",\n              \"title\": \"Type\",\n              \"description\": \"The concrete protocol type.\",\n              \"enum\": [\n                \"tls\",\n                \"ssh\",\n                \"ipsec\",\n                \"ike\",\n                \"sstp\",\n                \"wpa\",\n                \"dtls\",\n                \"quic\",\n                \"eap-aka\",\n                \"eap-aka-prime\",\n                \"prins\",\n                \"5g-aka\",\n                \"other\",\n                \"unknown\"\n              ],\n              \"meta:enum\": {\n                \"tls\": \"Transport Layer Security\",\n                \"ssh\": \"Secure Shell\",\n                \"ipsec\": \"Internet Protocol Security\",\n                \"ike\": \"Internet Key Exchange\",\n                \"sstp\": \"Secure Socket Tunneling Protocol\",\n                \"wpa\": \"Wi-Fi Protected Access\",\n                \"dtls\": \"Datagram Transport Layer Security\",\n                \"quic\": \"Quick UDP Internet Connections\",\n                \"eap-aka\": \"Extensible Authentication Protocol variant\",\n                \"eap-aka-prime\": \"Enhanced version of EAP-AKA\",\n                \"prins\": \"Protection of Inter-Network Signaling\",\n                \"5g-aka\": \"Authentication and Key Agreement for 5G\",\n                \"other\": \"Another protocol type\",\n                \"unknown\": \"The protocol type is not known\"\n              }\n            },\n            \"version\": {\n              \"type\": \"string\",\n              \"title\": \"Protocol Version\",\n              \"description\": \"The version of the protocol.\",\n              \"examples\": [\n                \"1.0\",\n                \"1.2\",\n                \"1.99\"\n              ]\n            },\n            \"cipherSuites\": {\n              \"type\": \"array\",\n              \"title\": \"Cipher Suites\",\n              \"description\": \"A list of cipher suites related to the protocol.\",\n              \"items\": {\n                \"$ref\": \"#/definitions/cipherSuite\",\n                \"title\": \"Cipher Suite\"\n              }\n            },\n            \"ikev2TransformTypes\": {\n              \"type\": \"object\",\n              \"title\": \"IKEv2 Transform Types\",\n              \"description\": \"The IKEv2 transform types supported (types 1-4), defined in [RFC 7296 section 3.3.2](https://www.ietf.org/rfc/rfc7296.html#section-3.3.2), and additional properties.\",\n              \"additionalProperties\": false,\n              \"properties\": {\n                \"encr\": {\n                  \"title\": \"Encryption Algorithms (ENCR)\",\n                  \"description\": \"Transform Type 1: encryption algorithms\",\n                  \"anyOf\": [\n                    {\n                      \"type\": \"array\",\n                      \"title\": \"Encryption Algorithms (ENCR)\",\n                      \"items\": {\n                        \"$ref\": \"#/definitions/ikeV2Enc\",\n                        \"title\": \"Encryption Algorithm (ENCR)\"\n                      }\n                    },\n                    {\n                      \"deprecated\": true,\n                      \"$ref\": \"#/definitions/cryptoRefArray\",\n                      \"title\": \"Encryption Algorithm (ENCR) References\",\n                      \"description\": \"[DEPRECATED] This will be removed in a future version.\\nTransform Type 1: encryption algorithms\"\n                    }\n                  ]\n                },\n                \"prf\": {\n                  \"title\": \"Pseudorandom Functions (PRF)\",\n                  \"description\": \"Transform Type 2: pseudorandom functions\",\n                  \"anyOf\": [\n                    {\n                      \"type\": \"array\",\n                      \"title\": \"Pseudorandom Functions (PRF)\",\n                      \"items\": {\n                        \"$ref\": \"#/definitions/ikeV2Prf\",\n                        \"title\": \"Pseudorandom Function (PRF)\"\n                      }\n                    },\n                    {\n                      \"deprecated\": true,\n                      \"$ref\": \"#/definitions/cryptoRefArray\",\n                      \"description\": \"[DEPRECATED] This will be removed in a future version.\\nTransform Type 2: pseudorandom functions\"\n                    }\n                  ]\n                },\n                \"integ\": {\n                  \"title\": \"Integrity Algorithms (INTEG)\",\n                  \"description\": \"Transform Type 3: integrity algorithms\",\n                  \"anyOf\": [\n                    {\n                      \"type\": \"array\",\n                      \"title\": \"Integrity Algorithms (INTEG)\",\n                      \"items\": {\n                        \"$ref\": \"#/definitions/ikeV2Integ\",\n                        \"title\": \"Integrity Algorithm (INTEG)\"\n                      }\n                    },\n                    {\n                      \"deprecated\": true,\n                      \"$ref\": \"#/definitions/cryptoRefArray\",\n                      \"description\": \"[DEPRECATED] This will be removed in a future version.\\nTransform Type 3: integrity algorithms\"\n                    }\n                  ]\n                },\n                \"ke\": {\n                  \"title\": \"Key Exchange Methods (KE)\",\n                  \"description\": \"Transform Type 4: Key Exchange Method (KE) per [RFC 9370](https://www.ietf.org/rfc/rfc9370.html), formerly called Diffie-Hellman Group (D-H).\",\n                  \"anyOf\": [\n                    {\n                      \"type\": \"array\",\n                      \"title\": \"Key Exchange Methods (KE)\",\n                      \"items\": {\n                        \"$ref\": \"#/definitions/ikeV2Ke\",\n                        \"title\": \"Key Exchange Method (KE)\"\n                      }\n                    },\n                    {\n                      \"deprecated\": true,\n                      \"$ref\": \"#/definitions/cryptoRefArray\",\n                      \"description\": \"[DEPRECATED] This will be removed in a future version.\\nTransform Type 4: Key Exchange Method (KE) per [RFC 9370](https://www.ietf.org/rfc/rfc9370.html), formerly called Diffie-Hellman Group (D-H).\"\n                    }\n                  ]\n                },\n                \"esn\": {\n                  \"type\": \"boolean\",\n                  \"title\": \"Extended Sequence Number (ESN)\",\n                  \"description\": \"Specifies if an Extended Sequence Number (ESN) is used.\"\n                },\n                \"auth\": {\n                  \"title\": \"IKEv2 Authentication methods\",\n                  \"description\": \"IKEv2 Authentication method per [RFC9593](https://www.ietf.org/rfc/rfc9593.html).\",\n                  \"anyOf\": [\n                    {\n                      \"type\": \"array\",\n                      \"title\": \"IKEv2 Authentication Methods\",\n                      \"items\": {\n                        \"$ref\": \"#/definitions/ikeV2Auth\",\n                        \"title\": \"IKEv2 Authentication Method\"\n                      }\n                    },\n                    {\n                      \"deprecated\": true,\n                      \"$ref\": \"#/definitions/cryptoRefArray\",\n                      \"description\": \"[DEPRECATED] This will be removed in a future version.\\nIKEv2 Authentication method\"\n                    }\n                  ]\n                }\n              }\n            },\n            \"cryptoRefArray\": {\n              \"deprecated\": true,\n              \"$ref\": \"#/definitions/cryptoRefArray\",\n              \"title\": \"Cryptographic References\",\n              \"description\": \"[DEPRECATED] Use `@.relatedCryptographicAssets` instead.\\nA list of protocol-related cryptographic assets\"\n            },\n            \"relatedCryptographicAssets\": {\n              \"$ref\": \"#/definitions/relatedCryptographicAssets\",\n              \"title\": \"Related Cryptographic Assets\",\n              \"description\": \"A list of cryptographic assets related to this component.\"\n            }\n          }\n        },\n        \"oid\": {\n          \"type\": \"string\",\n          \"title\": \"OID\",\n          \"description\": \"The object identifier (OID) of the cryptographic asset.\"\n        }\n      }\n    },\n    \"cipherSuite\": {\n      \"type\": \"object\",\n      \"title\": \"Cipher Suite\",\n      \"description\": \"Object representing a cipher suite\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Common Name\",\n          \"description\": \"A common name for the cipher suite.\",\n          \"examples\": [\n            \"TLS_DHE_RSA_WITH_AES_128_CCM\"\n          ]\n        },\n        \"algorithms\": {\n          \"type\": \"array\",\n          \"title\": \"Related Algorithms\",\n          \"description\": \"A list of algorithms related to the cipher suite.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/refType\",\n            \"title\": \"Algorithm reference\",\n            \"description\": \"The bom-ref to algorithm cryptographic asset.\"\n          }\n        },\n        \"identifiers\": {\n          \"type\": \"array\",\n          \"title\": \"Cipher Suite Identifiers\",\n          \"description\": \"A list of common identifiers for the cipher suite.\",\n          \"items\": {\n            \"type\": \"string\",\n            \"title\": \"identifier\",\n            \"description\": \"Cipher suite identifier\",\n            \"examples\": [\n              \"0xC0\",\n              \"0x9E\"\n            ]\n          }\n        },\n        \"tlsGroups\": {\n          \"type\": \"array\",\n          \"title\": \"TLS Groups\",\n          \"description\": \"A list of TLS named groups (formerly known as curves) for this cipher suite. These groups define the parameters for key exchange algorithms like ECDHE.\",\n          \"items\": {\n            \"type\": \"string\",\n            \"title\": \"Group Name\",\n            \"description\": \"The name of the TLS group\",\n            \"examples\": [\n              \"x25519\",\n              \"ffdhe2048\"\n            ]\n          }\n        },\n        \"tlsSignatureSchemes\": {\n          \"type\": \"array\",\n          \"title\": \"TLS Signature Schemes\",\n          \"description\": \"A list of signature schemes supported for cipher suite. These schemes specify the algorithms used for digital signatures in TLS handshakes and certificate verification.\",\n          \"items\": {\n            \"type\": \"string\",\n            \"title\": \"Signature Scheme\",\n            \"description\": \"The name of the TLS signature scheme\",\n            \"examples\": [\n              \"ecdsa_secp256r1_sha256\",\n              \"rsa_pss_rsae_sha256\",\n              \"ed25519\"\n            ]\n          }\n        }\n      }\n    },\n    \"ikeV2Enc\": {\n      \"type\": \"object\",\n      \"title\": \"Encryption Algorithm (ENCR)\",\n      \"description\": \"Object representing an encryption algorithm (ENCR)\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"A name for the encryption method.\",\n          \"examples\": [\n            \"ENCR_AES_GCM_16\"\n          ]\n        },\n        \"keyLength\": {\n          \"type\": \"integer\",\n          \"title\": \"Encryption algorithm key length\",\n          \"description\": \"The key length of the encryption algorithm.\"\n        },\n        \"algorithm\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"Algorithm reference\",\n          \"description\": \"The bom-ref to algorithm cryptographic asset.\"\n        }\n      }\n    },\n    \"ikeV2Prf\": {\n      \"type\": \"object\",\n      \"title\": \"Pseudorandom Function (PRF)\",\n      \"description\": \"Object representing a pseudorandom function (PRF)\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"A name for the pseudorandom function.\",\n          \"examples\": [\n            \"PRF_HMAC_SHA2_256\"\n          ]\n        },\n        \"algorithm\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"Algorithm reference\",\n          \"description\": \"The bom-ref to algorithm cryptographic asset.\"\n        }\n      }\n    },\n    \"ikeV2Integ\": {\n      \"type\": \"object\",\n      \"title\": \"Integrity Algorithm (INTEG)\",\n      \"description\": \"Object representing an integrity algorithm (INTEG)\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"A name for the integrity algorithm.\",\n          \"examples\": [\n            \"AUTH_HMAC_SHA2_256_128\"\n          ]\n        },\n        \"algorithm\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"Algorithm reference\",\n          \"description\": \"The bom-ref to algorithm cryptographic asset.\"\n        }\n      }\n    },\n    \"ikeV2Ke\": {\n      \"type\": \"object\",\n      \"title\": \"Key Exchange Method (KE)\",\n      \"description\": \"Object representing a key exchange method (KE)\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"group\": {\n          \"type\": \"integer\",\n          \"title\": \"Group Identifier\",\n          \"description\": \"A group identifier for the key exchange algorithm.\"\n        },\n        \"algorithm\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"Algorithm reference\",\n          \"description\": \"The bom-ref to algorithm cryptographic asset.\"\n        }\n      }\n    },\n    \"ikeV2Auth\": {\n      \"type\": \"object\",\n      \"title\": \"IKEv2 Authentication method\",\n      \"description\": \"Object representing a IKEv2 Authentication method\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"name\": {\n          \"type\": \"string\",\n          \"title\": \"Name\",\n          \"description\": \"A name for the authentication method.\"\n        },\n        \"algorithm\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"Algorithm reference\",\n          \"description\": \"The bom-ref to algorithm cryptographic asset.\"\n        }\n      }\n    },\n    \"cryptoRefArray\" : {\n      \"deprecated\": true,\n      \"title\": \"Encryption Algorithm (ENCR) Reference Array\",\n      \"description\": \"Deprecated definition.\",\n      \"type\": \"array\",\n      \"items\": {\n        \"$ref\": \"#/definitions/refType\"\n      }\n    },\n    \"relatedCryptographicAssets\": {\n      \"type\": \"array\",\n      \"title\": \"Related Cryptographic Assets\",\n      \"description\": \"A list of cryptographic assets related to this component.\",\n      \"items\": {\n        \"$ref\": \"#/definitions/relatedCryptographicAsset\",\n        \"title\": \"Related Cryptographic Asset\"\n      }\n    },\n    \"relatedCryptographicAsset\": {\n      \"type\": \"object\",\n      \"title\": \"Related Cryptographic Asset\",\n      \"description\": \"A cryptographic assets related to this component.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"type\": {\n          \"type\": \"string\",\n          \"title\": \"Type\",\n          \"description\": \"Specifies the mechanism by which the cryptographic asset is secured by.\",\n          \"examples\": [\n            \"publicKey\",\n            \"privateKey\",\n            \"algorithm\"\n          ]\n        },\n        \"ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"Reference to cryptographic asset\",\n          \"description\": \"The bom-ref to cryptographic asset.\"\n        }\n      }\n    },\n    \"securedBy\": {\n      \"type\": \"object\",\n      \"title\": \"Secured By\",\n      \"description\": \"Specifies the mechanism by which the cryptographic asset is secured by\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"mechanism\": {\n          \"type\": \"string\",\n          \"title\": \"Mechanism\",\n          \"description\": \"Specifies the mechanism by which the cryptographic asset is secured by.\",\n          \"examples\": [\n            \"HSM\",\n            \"TPM\",\n            \"SGX\",\n            \"Software\",\n            \"None\"\n          ]\n        },\n        \"algorithmRef\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"Algorithm Reference\",\n          \"description\": \"The bom-ref to the algorithm.\"\n        }\n      }\n    },\n    \"tags\": {\n      \"type\": \"array\",\n      \"items\": {\n        \"type\": \"string\"\n      },\n      \"title\": \"Tags\",\n      \"description\": \"Textual strings that aid in discovery, search, and retrieval of the associated object. Tags often serve as a way to group or categorize similar or related objects by various attributes.\",\n      \"examples\": [\n        \"json-parser\",\n        \"object-persistence\",\n        \"text-to-image\",\n        \"translation\",\n        \"object-detection\"\n      ]\n    },\n    \"patentFamily\": {\n      \"type\": \"object\",\n      \"title\": \"Patent Family\",\n      \"description\": \"A patent family is a group of related patent applications or granted patents that cover the same or similar invention. These patents are filed in multiple jurisdictions to protect the invention across different regions or countries. A patent family typically includes patents that share a common priority date, originating from the same initial application, and may vary slightly in scope or claims to comply with regional legal frameworks. Fields align with WIPO ST.96 standards where applicable.\",\n      \"required\": [\"familyId\"],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM. \\n\\nFor a patent, it might be a good idea to use a patent number as the BOM reference ID.\"\n        },\n        \"familyId\": {\n          \"type\": \"string\",\n          \"title\": \"Patent Family ID\",\n          \"description\": \"The unique identifier for the patent family, aligned with the `id` attribute in WIPO ST.96 v8.0's `PatentFamilyType`. Refer to [PatentFamilyType in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/PatentFamilyType.xsd).\"\n        },\n        \"priorityApplication\": {\n          \"$ref\": \"#/definitions/priorityApplication\"\n        },\n        \"members\": {\n          \"type\": \"array\",\n          \"title\": \"Family Members\",\n          \"description\": \"A collection of patents or applications that belong to this family, each identified by a `bom-ref` pointing to a patent object defined elsewhere in the BOM.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/refLinkType\",\n            \"title\": \"BOM Reference\",\n            \"description\": \"A `bom-ref` linking to a patent or application object within the BOM.\"\n          }\n        },\n        \"externalReferences\": {\n          \"type\": \"array\",\n          \"title\": \"External References\",\n          \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/externalReference\"\n          }\n        }\n      }\n    },\n    \"patent\": {\n      \"type\": \"object\",\n      \"title\": \"Patent\",\n      \"description\": \"A patent is a legal instrument, granted by an authority, that confers certain rights over an invention for a specified period, contingent on public disclosure and adherence to relevant legal requirements. The summary information in this object is aligned with [WIPO ST.96](https://www.wipo.int/standards/en/st96/) principles where applicable.\",\n      \"required\": [\"patentNumber\", \"jurisdiction\", \"patentLegalStatus\"],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\",\n          \"description\": \"An identifier which can be used to reference the object elsewhere in the BOM. Every `bom-ref` must be unique within the BOM.\"\n        },\n        \"patentNumber\": {\n          \"type\": \"string\",\n          \"pattern\": \"^[A-Za-z0-9][A-Za-z0-9\\\\-/.()\\\\s]{0,28}[A-Za-z0-9]$\",\n          \"title\": \"Patent Number\",\n          \"description\": \"The unique number assigned to the granted patent by the issuing authority. Aligned with `PatentNumber` in WIPO ST.96. Refer to [PatentNumber in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/PatentNumber.xsd).\",\n          \"examples\": [\"US987654321\", \"EP1234567B1\"]\n        },\n        \"applicationNumber\": {\n          \"$ref\": \"#/definitions/patentApplicationNumber\"\n        },\n        \"jurisdiction\": {\n          \"$ref\": \"#/definitions/patentJurisdiction\"\n        },\n        \"priorityApplication\": {\n          \"$ref\": \"#/definitions/priorityApplication\"\n        },\n        \"publicationNumber\": {\n          \"type\": \"string\",\n          \"pattern\": \"^[A-Za-z0-9][A-Za-z0-9\\\\-/.()\\\\s]{0,28}[A-Za-z0-9]$\",\n          \"title\": \"Patent Publication Number\",\n          \"description\": \"This is the number assigned to a patent application once it is published. Patent applications are generally published 18 months after filing (unless an applicant requests non-publication). This number is distinct from the application number. \\n\\nPurpose: Identifies the publicly available version of the application. \\n\\nFormat: Varies by jurisdiction, often similar to application numbers but includes an additional suffix indicating publication. \\n\\nExample:\\n - US: US20240000123A1 (indicates the first publication of application US20240000123) \\n - Europe: EP23123456A1 (first publication of European application EP23123456). \\n\\nWIPO ST.96 v8.0: \\n - Publication Number field: https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/PublicationNumber.xsd\"\n        },\n        \"title\": {\n          \"type\": \"string\",\n          \"title\": \"Patent Title\",\n          \"description\": \"The title of the patent, summarising the invention it protects. Aligned with `InventionTitle` in WIPO ST.96. Refer to [InventionTitle in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/InventionTitle.xsd).\"\n        },\n        \"abstract\": {\n          \"type\": \"string\",\n          \"title\": \"Patent Abstract\",\n          \"description\": \"A brief summary of the invention described in the patent. Aligned with `Abstract` and `P` in WIPO ST.96. Refer to [Abstract in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/Abstract.xsd).\"\n        },\n        \"filingDate\": {\n          \"type\": \"string\",\n          \"format\": \"date\",\n          \"title\": \"Filing Date\",\n          \"description\": \"The date the patent application was filed with the jurisdiction. Aligned with `FilingDate` in WIPO ST.96. Refer to [FilingDate in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/FilingDate.xsd).\"\n        },\n        \"grantDate\": {\n          \"type\": \"string\",\n          \"format\": \"date\",\n          \"title\": \"Grant Date\",\n          \"description\": \"The date the patent was granted by the jurisdiction. Aligned with `GrantDate` in WIPO ST.96. Refer to [GrantDate in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/GrantDate.xsd).\"\n        },\n        \"patentExpirationDate\": {\n          \"type\": \"string\",\n          \"format\": \"date\",\n          \"title\": \"Expiration Date\",\n          \"description\": \"The date the patent expires. Derived from grant or filing date according to jurisdiction-specific rules.\"\n        },\n        \"patentLegalStatus\": {\n          \"type\": \"string\",\n          \"title\": \"Legal Status\",\n          \"description\": \"Indicates the current legal status of the patent or patent application, based on the WIPO ST.27 standard. This status reflects administrative, procedural, or legal events. Values include both active and inactive states and are useful for determining enforceability, procedural history, and maintenance status.\",\n          \"enum\": [\n            \"pending\",\n            \"granted\",\n            \"revoked\",\n            \"expired\",\n            \"lapsed\",\n            \"withdrawn\",\n            \"abandoned\",\n            \"suspended\",\n            \"reinstated\",\n            \"opposed\",\n            \"terminated\",\n            \"invalidated\",\n            \"in-force\"\n          ],\n          \"meta:enum\": {\n            \"pending\": \"The patent application has been filed but not yet examined or granted.\",\n            \"granted\": \"The patent application has been examined and a patent has been issued.\",\n            \"revoked\": \"The patent has been declared invalid through a legal or administrative process.\",\n            \"expired\": \"The patent has reached the end of its enforceable term.\",\n            \"lapsed\": \"The patent is no longer in force due to non-payment of maintenance fees or other requirements.\",\n            \"withdrawn\": \"The patent application was voluntarily withdrawn by the applicant.\",\n            \"abandoned\": \"The patent application was abandoned, often due to lack of action or response.\",\n            \"suspended\": \"Processing of the patent application has been temporarily halted.\",\n            \"reinstated\": \"A previously abandoned or lapsed patent has been reinstated.\",\n            \"opposed\": \"The patent application or granted patent is under formal opposition proceedings.\",\n            \"terminated\": \"The patent or application has been officially terminated.\",\n            \"invalidated\": \"The patent has been invalidated, either in part or in full.\",\n            \"in-force\": \"The granted patent is active and enforceable.\"\n          }\n        },\n        \"patentAssignee\": {\n          \"type\": \"array\",\n          \"title\": \"Patent Assignees\",\n          \"description\": \"A collection of organisations or individuals to whom the patent rights are assigned. This supports joint ownership and allows for flexible representation of both corporate entities and individual inventors.\",\n          \"items\": {\n            \"oneOf\": [\n              {\n                \"title\": \"Person\",\n                \"$ref\": \"#/definitions/organizationalContact\"\n              },\n              {\n                \"title\": \"Organizational Entity\",\n                \"$ref\": \"#/definitions/organizationalEntity\"\n              }\n            ]\n          }\n        },\n        \"externalReferences\": {\n          \"type\": \"array\",\n          \"title\": \"External References\",\n          \"description\": \"External references provide a way to document systems, sites, and information that may be relevant but are not included with the BOM. They may also establish specific relationships within or external to the BOM.\",\n          \"items\": {\n            \"$ref\": \"#/definitions/externalReference\"\n          }\n        }\n      }\n    },\n    \"patentAssertions\": {\n      \"type\": \"array\",\n      \"title\": \"Patent Assertions\",\n      \"description\": \"A list of assertions made regarding patents associated with this component or service. Assertions distinguish between ownership, licensing, and other relevant interactions with patents.\",\n      \"items\": {\n        \"type\": \"object\",\n        \"title\": \"Patent Assertion\",\n        \"description\": \"An assertion linking a patent or patent family to this component or service.\",\n        \"required\": [\"assertionType\", \"asserter\"],\n        \"additionalProperties\": false,\n        \"properties\": {\n          \"bom-ref\": {\n            \"$ref\": \"#/definitions/refType\",\n            \"title\": \"BOM Reference\",\n            \"description\": \"A reference to the patent or patent family object within the BOM. This must match the `bom-ref` of a `patent` or `patentFamily` object.\"\n          },\n          \"assertionType\": {\n            \"type\": \"string\",\n            \"title\": \"Assertion Type\",\n            \"description\": \"The type of assertion being made about the patent or patent family. Examples include ownership, licensing, and standards inclusion.\",\n            \"enum\": [\n              \"ownership\",\n              \"license\",\n              \"third-party-claim\",\n              \"standards-inclusion\",\n              \"prior-art\",\n              \"exclusive-rights\",\n              \"non-assertion\",\n              \"research-or-evaluation\"\n            ],\n            \"meta:enum\": {\n              \"ownership\": \"The manufacturer asserts ownership of the patent or patent family.\",\n              \"license\": \"The manufacturer asserts they have a license to use the patent or patent family.\",\n              \"third-party-claim\": \"A third party has asserted a claim or potential infringement against the manufacturer’s component or service.\",\n              \"standards-inclusion\": \"The patent is part of a standard essential patent (SEP) portfolio relevant to the component or service.\",\n              \"prior-art\": \"The manufacturer asserts the patent or patent family as prior art that invalidates another patent or claim.\",\n              \"exclusive-rights\": \"The manufacturer asserts exclusive rights granted through a licensing agreement.\",\n              \"non-assertion\": \"The manufacturer asserts they will not enforce the patent or patent family against certain uses or users.\",\n              \"research-or-evaluation\": \"The patent or patent family is being used under a research or evaluation license.\"\n            }\n          },\n          \"patentRefs\": {\n            \"type\": \"array\",\n            \"title\": \"Patent References\",\n            \"description\": \"A list of BOM references (`bom-ref`) linking to patents or patent families associated with this assertion.\",\n            \"items\": {\n              \"$ref\": \"#/definitions/refType\"\n            }\n          },\n          \"asserter\": {\n            \"oneOf\": [\n              {\n                \"$ref\": \"#/definitions/organizationalEntity\",\n                \"title\": \"Organizational Entity\"\n              },\n              {\n                \"$ref\": \"#/definitions/organizationalContact\",\n                \"title\": \"Person\"\n              },\n              {\n                \"$ref\": \"#/definitions/refLinkType\",\n                \"title\": \"Reference\",\n                \"description\": \"A reference to a previously defined `organizationalContact` or `organizationalEntity` object in the BOM. The value must be a valid `bom-ref` pointing to one of these objects.\"\n              }\n            ]\n          },\n          \"notes\": {\n            \"type\": \"string\",\n            \"title\": \"Notes\",\n            \"description\": \"Additional notes or clarifications regarding the assertion, if necessary. For example, geographical restrictions, duration, or limitations of a license.\"\n          }\n        }\n      }\n    },\n    \"patentApplicationNumber\": {\n      \"type\": \"string\",\n      \"pattern\": \"^[A-Za-z0-9][A-Za-z0-9\\\\-/.()\\\\s]{0,28}[A-Za-z0-9]$\",\n      \"title\": \"Patent Application Number\",\n      \"description\": \"The unique number assigned to a patent application when it is filed with a patent office. It is used to identify the specific application and track its progress through the examination process. Aligned with `ApplicationNumber` in ST.96. Refer to [ApplicationIdentificationType in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/ApplicationIdentificationType.xsd).\",\n      \"examples\": [\"US20240000123\", \"EP23123456\"]\n    },\n    \"patentJurisdiction\": {\n      \"type\": \"string\",\n      \"title\": \"Jurisdiction\",\n      \"description\": \"The jurisdiction or patent office where the priority application was filed, specified using WIPO ST.3 codes. Aligned with `IPOfficeCode` in ST.96. Refer to [IPOfficeCode in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Common/IPOfficeCode.xsd).\",\n      \"pattern\": \"^[A-Z]{2}$\",\n      \"examples\": [\"US\", \"EP\", \"JP\"]\n    },\n    \"patentFilingDate\": {\n      \"type\": \"string\",\n      \"format\": \"date\",\n      \"title\": \"Filing Date\",\n      \"description\": \"The date the priority application was filed, aligned with `FilingDate` in ST.96. Refer to [FilingDate in ST.96](https://www.wipo.int/standards/XMLSchema/ST96/V8_0/Patent/FilingDate.xsd).\"\n    },\n    \"priorityApplication\": {\n      \"type\": \"object\",\n      \"title\": \"Priority Application\",\n      \"description\": \"The priorityApplication contains the essential data necessary to identify and reference an earlier patent filing for priority rights. In line with WIPO ST.96 guidelines, it includes the jurisdiction (office code), application number, and filing date-the three key elements that uniquely specify the priority application in a global patent context.\",\n      \"required\": [\"applicationNumber\", \"jurisdiction\", \"filingDate\"],\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"applicationNumber\": {\n          \"$ref\": \"#/definitions/patentApplicationNumber\"\n        },\n        \"jurisdiction\": {\n          \"$ref\": \"#/definitions/patentJurisdiction\"\n        },\n        \"filingDate\": {\n          \"$ref\": \"#/definitions/patentFilingDate\"\n        }\n      }\n    },\n    \"citation\": {\n      \"type\": \"object\",\n      \"title\": \"Citation\",\n      \"description\": \"Details a specific attribution of data within the BOM to a contributing entity or process.\",\n      \"additionalProperties\": false,\n      \"properties\": {\n        \"bom-ref\": {\n          \"$ref\": \"#/definitions/refType\",\n          \"title\": \"BOM Reference\"\n        },\n        \"pointers\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\",\n            \"title\": \"Field Reference\",\n            \"description\": \"A [JSON Pointer](https://datatracker.ietf.org/doc/html/rfc6901) identifying the BOM field to which the attribution applies.\\nUsers of other serialization formats (e.g. XML) shall use the JSON Pointer format to ensure consistent field referencing across representations.\"\n          },\n          \"minItems\": 1,\n          \"title\": \"Field References\",\n          \"description\": \"One or more [JSON Pointers](https://datatracker.ietf.org/doc/html/rfc6901) identifying the BOM fields to which the attribution applies.\\nExactly one of the \\\"pointers\\\" or \\\"expressions\\\" elements must be present.\"\n        },\n        \"expressions\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\",\n            \"title\": \"Path Expression\",\n            \"description\": \"Specifies a path expression used to locate a value within a BOM. The expression syntax shall conform to the format of the BOM's serialization.\\nUse [JSONPath](https://datatracker.ietf.org/doc/html/rfc9535) for JSON, [XPath](https://www.w3.org/TR/xpath/) for XML, and default to JSONPath for Protocol Buffers unless otherwise specified.\\nImplementers shall ensure the expression is valid within the context of the applicable serialization format.\"\n          },\n          \"minItems\": 1,\n          \"title\": \"Path Expressions\",\n          \"description\": \"One or more path expressions used to locate values within a BOM.\\nExactly one of the \\\"pointers\\\" or \\\"expressions\\\" elements must be present.\"\n        },\n        \"timestamp\": {\n          \"type\": \"string\",\n          \"format\": \"date-time\",\n          \"title\": \"Timestamp\",\n          \"description\": \"The date and time when the attribution was made or the information was supplied.\"\n        },\n        \"attributedTo\": {\n          \"$ref\": \"#/definitions/refLinkType\",\n          \"title\": \"Attributed To\",\n          \"description\": \"The `bom-ref` of an object, such as a component, service, tool, organisational entity, or person that supplied the cited information.\\nAt least one of the \\\"attributedTo\\\" or \\\"process\\\" elements must be present.\"\n        },\n        \"process\": {\n          \"$ref\": \"#/definitions/refLinkType\",\n          \"title\": \"Process Reference\",\n          \"description\": \"The `bom-ref` to a process (such as a formula, workflow, task, or step) defined in the `formulation` section that executed or generated the attributed data.\\nAt least one of the \\\"attributedTo\\\" or \\\"process\\\" elements must be present.\"\n        },\n        \"note\": {\n          \"type\": \"string\",\n          \"title\": \"Note\",\n          \"description\": \"A description or comment about the context or quality of the data attribution.\"\n        },\n        \"signature\": {\n          \"$ref\": \"#/definitions/signature\",\n          \"title\": \"Signature\",\n          \"description\": \"A digital signature verifying the authenticity or integrity of the attribution.\"\n        }\n      },\n      \"required\": [\"timestamp\"],\n      \"anyOf\": [\n        { \"required\": [\"attributedTo\"] },\n        { \"required\": [\"process\"] }\n      ],\n      \"oneOf\": [\n        { \"required\": [\"pointers\"] },\n        { \"required\": [\"expressions\"] }\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Encoder/SBOMEncoder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport TSCUtility\n\ninternal struct SBOMEncoder {\n    internal let sbom: SBOMDocument\n    internal let observabilityScope: ObservabilityScope\n\n    internal init(sbom: SBOMDocument, observabilityScope: ObservabilityScope) {\n        self.sbom = sbom\n        self.observabilityScope = observabilityScope\n    }\n\n    internal func writeSBOMs(specs: [Spec], outputDir: AbsolutePath, filter: Filter = .all, fileSystem: any FileSystem = localFileSystem) async throws -> [SBOMResult] {\n        if !fileSystem.exists(outputDir) {\n            try fileSystem.createDirectory(outputDir, recursive: true)\n        }\n        let sbomSpecs = Array(Set(specs.map { $0.internalSpec() })).sorted()\n        var results: [SBOMResult] = []\n        for spec in sbomSpecs {\n            let outputPath = try await self.encodeSBOM(spec: spec, outputDir: outputDir, filter: filter, fileSystem: fileSystem)\n            results.append(SBOMResult(spec: spec, path: outputPath))\n        }\n        return results\n    }\n\n    internal func encodeSBOM(spec: SBOMSpec, outputDir: AbsolutePath, filter: Filter = .all, fileSystem: any FileSystem = localFileSystem) async throws -> AbsolutePath {\n        let timestamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: \":\", with: \"_\")\n        let filename = \"\\(spec.concreteSpec)-\\(spec.versionString)-\\(self.sbom.primaryComponent.name)-\\(self.sbom.primaryComponent.version.revision)-\\(filter)-\\(timestamp).json\"\n        let outputPath = outputDir.appending(component: filename)\n        let encoded = try await encodeSBOMData(spec: spec)\n        try fileSystem.writeFileContents(outputPath, data: encoded)\n        return outputPath\n    }\n\n    internal func encodeSBOMData(spec: SBOMSpec) async throws -> Data {\n        let data: any Encodable = switch spec.concreteSpec {\n        case .cyclonedx1:\n            try await CycloneDXConverter.convertToDocument(from: self.sbom, spec: spec)\n        case .spdx3:\n            try await SPDXConverter.convertToGraph(from: self.sbom, spec: spec)\n            // case .cyclonedx, .cyclonedx2:\n            //     data = try await convertToCycloneDX2Document(from: sbom, spec: spec)\n            // case .spdx, .spdx4:\n            //     data = try await convertToSPDX4Graph(from: sbom, spec: spec)\n        }\n\n        let encoder = JSONEncoder()\n        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]\n        encoder.dateEncodingStrategy = .iso8601\n        let encoded = try encoder.encode(data)\n\n        try await self.validateSBOM(from: encoded, spec: spec)\n\n        return encoded\n    }\n\n    internal func validateSBOM(from encoded: Foundation.Data, spec: SBOMSpec, bundleName: String = \"SwiftPM_SBOMModel\") async throws {\n        guard let sbomJSONObject = try (JSONSerialization.jsonObject(with: encoded)) as? [String: Any] else {\n            throw SBOMEncoderError\n                .jsonConversionFailed(message: \"Could not convert generated SBOM file into JSON object for validation\")\n        }\n\n        do {\n            let validator = try await SBOMValidator.create(for: spec, bundleName: bundleName)\n            try await validator.validate(sbomJSONObject)\n        } catch let error as SBOMSchemaError {\n            if case .bundleNotFound(_) = error {\n                self.observabilityScope.emit(warning: \"\\(error.errorDescription ?? \"Bundle with schemas not found\") - skipping SBOM validation\")\n                return\n            }\n            throw error\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/SBOMModel/Extractor/DependencySourceStrategy.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageGraph\nimport PackageModel\nimport SwiftBuildSupport\n\n/// Protocol defining the strategy for extracting dependencies from different sources\nprotocol DependencySourceStrategy {\n    /// Get dependencies for a module\n    func getDependencies(for module: ResolvedModule) async throws -> [SBOMExtractor.DependencyReference]\n    \n    /// Get dependencies for a product\n    func getDependencies(for product: ResolvedProduct) async throws -> [SBOMExtractor.DependencyReference]\n}\n\n/// Strategy for extracting dependencies from the build graph\nfinal class BuildGraphDependencySource: DependencySourceStrategy {\n    private let dependencyGraph: [String: [String]]\n    private let modulesGraph: ModulesGraph\n    private let caches: SBOMCaches\n    \n    init(dependencyGraph: [String: [String]], modulesGraph: ModulesGraph, caches: SBOMCaches) {\n        self.dependencyGraph = dependencyGraph\n        self.modulesGraph = modulesGraph\n        self.caches = caches\n    }\n    \n    func getDependencies(for module: ResolvedModule) async throws -> [SBOMExtractor.DependencyReference] {\n        guard let targetName = await caches.targetName.get(module.id),\n              let targetDeps = dependencyGraph[targetName] else {\n            return []\n        }\n        \n        return targetDeps.compactMap { targetDep in\n            if let product = SBOMGraphsConverter.toProduct(fromTarget: targetDep, modulesGraph: modulesGraph) {\n                return .product(product)\n            } else if let module = SBOMGraphsConverter.toModule(fromTarget: targetDep, modulesGraph: modulesGraph) {\n                return .module(module)\n            }\n            // TODO: echeng3805, print a warning for targets not in modules graph (ignoring resource bundles)\n            return nil\n        }\n    }\n    \n    func getDependencies(for product: ResolvedProduct) async throws -> [SBOMExtractor.DependencyReference] {\n        guard let targetDeps = dependencyGraph[SBOMGraphsConverter.getTargetName(fromProduct: product.name)] else {\n            return []\n        }\n        \n        return targetDeps.compactMap { targetDep in\n            if let product = SBOMGraphsConverter.toProduct(fromTarget: targetDep, modulesGraph: modulesGraph) {\n                return .product(product)\n            } else if let module = SBOMGraphsConverter.toModule(fromTarget: targetDep, modulesGraph: modulesGraph) {\n                return .module(module)\n            }\n            // TODO: echeng3805, print a warning for targets not in modules graph?\n            return nil\n        }\n    }\n}\n\n/// Strategy for extracting dependencies from the modules graph\nfinal class ModulesGraphDependencySource: DependencySourceStrategy {\n    private let modulesGraph: ModulesGraph\n    \n    init(modulesGraph: ModulesGraph) {\n        self.modulesGraph = modulesGraph\n    }\n    \n    func getDependencies(for module: ResolvedModule) async throws -> [SBOMExtractor.DependencyReference] {\n        return module.dependencies.map { dependency in\n            switch dependency {\n            case .product(let product, _):\n                return .product(product)\n            case .module(let module, _):\n                return .module(module)\n            }\n        }\n    }\n    \n    func getDependencies(for product: ResolvedProduct) async throws -> [SBOMExtractor.DependencyReference] {\n        return product.modules.flatMap { module in\n            module.dependencies.map { dependency in\n                switch dependency {\n                case .product(let product, _):\n                    return .product(product)\n                case .module(let module, _):\n                    return .module(module)\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "Sources/SBOMModel/Extractor/PURL.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport TSCUtility\n\ninternal struct PURL: Codable, Equatable, Hashable, CustomStringConvertible {\n    internal let scheme: String\n    internal let type: String\n    internal let namespace: String?\n    internal let name: String\n    internal let version: String?\n    internal let qualifiers: [String: String]?\n    internal let subpath: String?\n\n    internal init(\n        scheme: String,\n        type: String,\n        namespace: String? = nil,\n        name: String,\n        version: String? = nil,\n        qualifiers: [String: String]? = nil,\n        subpath: String? = nil\n\n    ) {\n        self.scheme = scheme\n        self.type = type\n        self.namespace = namespace\n        self.name = name\n        self.version = version\n        self.qualifiers = qualifiers?.isEmpty == true ? nil : qualifiers\n        self.subpath = subpath\n    }\n\n    internal var description: String {\n        var result = \"\\(scheme):\\(type)\"\n        if let namespace {\n            result += \"/\\(namespace)\"\n        }\n        result += \"/\\(self.name)\"\n        if let version, version != \"unknown\" {\n            result += \"@\\(version)\"\n        }\n        if let qualifiers, !qualifiers.isEmpty {\n            let qualifierPairs = qualifiers.map { \"\\($0.key)=\\($0.value)\" }.sorted()\n            result += \"?\" + qualifierPairs.joined(separator: \"&\")\n        }\n        if let subpath {\n            result += \"#\\(subpath)\"\n        }\n        return result\n    }\n}\n\nextension PURL {\n    internal static func from(package: ResolvedPackage, version: SBOMComponent.Version) async -> PURL {\n        let namespace = await extractNamespace(from: version)\n        let qualifiers = await extractQualifiers(from: version)\n        return PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            namespace: namespace,\n            name: version.entry?.name ?? SBOMExtractor.extractComponentID(from: package).value,\n            version: version.revision,\n            qualifiers: qualifiers\n        )\n    }\n\n    internal static func from(product: ResolvedProduct, version: SBOMComponent.Version) async -> PURL {\n        let namespace = await extractNamespace(from: version)\n        let qualifiers = await extractQualifiers(from: version)\n\n        let name: String\n        if let registryPackageName = version.entry?.name.description {\n            name = \"\\(registryPackageName):\\(product.name)\"\n        } else {\n            name = SBOMExtractor.extractComponentID(from: product).value\n        }\n        return PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            namespace: (namespace == nil && qualifiers?[\"path\"] == nil) ? product.packageIdentity.description : namespace,\n            name: name,\n            version: version.revision,\n            qualifiers: qualifiers\n        )\n    }\n\n    internal static func extractNamespace(from version: SBOMComponent.Version) async -> String? {\n        if let scope = version.entry?.scope {\n            return scope\n        }\n\n        guard let packageLocation = version.commit?.repository else {\n            return nil\n        }\n        // local absolute file system paths: no namespace\n        // path will be included in the qualifiers:\n        // pkg:swift/FooPackage@1.0.0?path=/Users/jdoe/workspace/project/lib/FooPackage\n        if packageLocation.hasPrefix(\"/\") {\n            return nil\n        }\n        // SSH URLs (git@host:org/repo.git or git@host:org/repo)\n        let sshPattern = #\"^[^@]+@([^:]+):([^/]+)(?:/.*)?$\"#\n        if let regex = try? NSRegularExpression(pattern: sshPattern, options: []),\n           let match = regex.firstMatch(\n               in: packageLocation,\n               options: [],\n               range: NSRange(location: 0, length: packageLocation.count)\n           ),\n           match.numberOfRanges == 3\n        {\n            let hostRange = Range(match.range(at: 1), in: packageLocation)\n            let orgRange = Range(match.range(at: 2), in: packageLocation)\n            if let hostRange, let orgRange {\n                let host = String(packageLocation[hostRange])\n                let org = String(packageLocation[orgRange])\n                return \"\\(host)/\\(org)\"\n            }\n        }\n        // HTTP/HTTPS URLs\n        if let url = URL(string: packageLocation), let host = url.host {\n            let pathComponents = url.pathComponents.filter { $0 != \"/\" && !$0.isEmpty }\n            if pathComponents.count >= 2 {\n                let org = pathComponents[0] // swiftlang\n                return \"\\(host)/\\(org)\"\n            }\n        }\n        // com.example.package-name format\n        if packageLocation.contains(\".\") && !packageLocation.hasPrefix(\"/\") && !packageLocation\n            .contains(\"://\") && !packageLocation.contains(\"@\")\n        {\n            let components = packageLocation.components(separatedBy: \".\")\n            if components.count >= 2 {\n                return components.dropLast().joined(separator: \".\") // com.example\n            }\n        }\n        return nil\n    }\n\n    internal static func extractQualifiers(from version: SBOMComponent.Version) async -> [String: String]? {\n        guard let packageLocation = version.commit?.repository else {\n            return nil\n        }\n        // For packages on the local filesystem\n        if packageLocation.hasPrefix(\"/\") {\n            return [\"path\": packageLocation]\n        }\n        return nil\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Extractor/SBOMCache.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageCollections\nimport PackageGraph\nimport PackageModel\nimport SourceControl\nimport TSCUtility\n\ninternal struct SBOMVersionInfo {\n    internal let version: SBOMComponent.Version\n    internal let originator: SBOMOriginator\n\n    internal init(version: SBOMComponent.Version, originator: SBOMOriginator) {\n        self.version = version\n        self.originator = originator\n    }\n}\n\n/// Cache for storing root package version info (to minimize calls to Git)\ninternal actor SBOMVersionCache {\n    private var cache: [PackageIdentity: SBOMVersionInfo] = [:]\n    internal func get(_ identity: PackageIdentity) -> SBOMVersionInfo? {\n        self.cache[identity]\n    }\n\n    internal func set(_ identity: PackageIdentity, versionInfo: SBOMVersionInfo) {\n        self.cache[identity] = versionInfo\n    }\n}\n\n/// Key for product cache entries\ninternal struct ProductCacheKey: Hashable {\n    internal let packageIdentity: PackageIdentity\n    internal let productName: String\n    \n    internal init(packageIdentity: PackageIdentity, productName: String) {\n        self.packageIdentity = packageIdentity\n        self.productName = productName\n    }\n}\n\n/// Cache for storing extracted components (to avoid redundant extraction)\ninternal actor SBOMComponentCache {\n    private var packageCache: [PackageIdentity: SBOMComponent] = [:]\n    private var productCache: [ProductCacheKey: SBOMComponent] = [:]\n\n    internal func getPackage(_ identity: PackageIdentity) -> SBOMComponent? {\n        self.packageCache[identity]\n    }\n\n    internal func setPackage(_ identity: PackageIdentity, component: SBOMComponent) {\n        self.packageCache[identity] = component\n    }\n\n    internal func getProduct(_ packageIdentity: PackageIdentity, productName: String) -> SBOMComponent? {\n        let key = ProductCacheKey(packageIdentity: packageIdentity, productName: productName)\n        return self.productCache[key]\n    }\n\n    internal func setProduct(_ packageIdentity: PackageIdentity, productName: String, component: SBOMComponent) {\n        let key = ProductCacheKey(packageIdentity: packageIdentity, productName: productName)\n        self.productCache[key] = component\n    }\n}\n\n/// Cache for storing module-to-target-name mappings from the build graph\ninternal actor SBOMTargetNameCache {\n    private var cache: [ResolvedModule.ID: String] = [:]\n\n    internal func get(_ moduleID: ResolvedModule.ID) -> String? {\n        self.cache[moduleID]\n    }\n\n    internal func set(_ moduleID: ResolvedModule.ID, targetName: String) {\n        self.cache[moduleID] = targetName\n    }\n}\n\n/// Consolidated container for all SBOM extraction caches\ninternal struct SBOMCaches {\n    internal let version: SBOMVersionCache\n    internal let component: SBOMComponentCache\n    internal let targetName: SBOMTargetNameCache\n\n    internal init() {\n        self.version = SBOMVersionCache()\n        self.component = SBOMComponentCache()\n        self.targetName = SBOMTargetNameCache()\n    }\n\n    internal init(\n        version: SBOMVersionCache,\n        component: SBOMComponentCache,\n        targetName: SBOMTargetNameCache\n    ) {\n        self.version = version\n        self.component = component\n        self.targetName = targetName\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Extractor/SBOMDependenciesExtractor.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageCollections\nimport PackageGraph\nimport PackageModel\nimport SourceControl\nimport TSCUtility\n\nextension SBOMExtractor {\n    enum DependencyReference {\n        case product(ResolvedProduct)\n        case module(ResolvedModule)\n    }\n\n    internal func extractDependencies(product: String? = nil, filter: Filter = .all) async throws -> SBOMDependencies {\n        guard let rootPackage = modulesGraph.rootPackages.first else {\n            throw SBOMExtractorError.noRootPackage(context: \"extract dependencies\")\n        }\n        let primaryComponent = try await self.extractPrimaryComponent(product: product)\n        let targetProducts: [ResolvedProduct]\n        if let name = product {\n            guard let targetProduct = rootPackage.products.first(where: { $0.name == name }) else {\n                throw SBOMExtractorError.productNotFound(\n                    productName: name,\n                    packageIdentity: rootPackage.identity.description\n                )\n            }\n            // only get dependencies for single product\n            targetProducts = [targetProduct]\n        } else {\n            // get dependencies for all products in the root package\n            targetProducts = rootPackage.products\n        }\n        return try await self.extractDependenciesForProducts(targetProducts: targetProducts, primaryComponent: primaryComponent, filter: filter)\n    }\n\n    private func populateTargetNameCache() async {\n        if let buildGraph = dependencyGraph {\n            for targetName in buildGraph.keys {\n                if let module = SBOMGraphsConverter.toModule(fromTarget: targetName, modulesGraph: modulesGraph) {\n                    await caches.targetName.set(module.id, targetName: targetName)\n                }\n            }\n        }\n    }\n\n    private func extractDependenciesForProducts(targetProducts: [ResolvedProduct], primaryComponent: SBOMComponent, filter: Filter) async throws -> SBOMDependencies {\n        guard let rootPackage = modulesGraph.rootPackages.first else {\n            throw SBOMExtractorError\n                .noRootPackage(context: \"extract dependencies for the following products: \\(targetProducts)\")\n        }\n\n        let filterStrategy = filter.createStrategy()\n        \n        // Create the appropriate dependency source strategy\n        let dependencySource: DependencySourceStrategy\n        if let buildGraph = dependencyGraph {\n            await self.populateTargetNameCache()\n            dependencySource = BuildGraphDependencySource(\n                dependencyGraph: buildGraph,\n                modulesGraph: modulesGraph,\n                caches: caches\n            )\n        } else {\n            dependencySource = ModulesGraphDependencySource(modulesGraph: modulesGraph)\n        }\n        \n        var components: Set<SBOMComponent> = []\n        var relationships: [SBOMComponent: Set<SBOMComponent>] = [:] // parent:children\n        \n        func addComponent(_ component: SBOMComponent) {\n            if filterStrategy.shouldIncludeComponent(component, primaryComponent: primaryComponent) {\n                components.insert(component)\n            }\n        }\n\n        func trackRelationship(parent: SBOMComponent, child: SBOMComponent) {\n            if filterStrategy.shouldTrackRelationship(parent: parent, child: child, primaryComponent: primaryComponent) {\n                addComponent(parent)\n                addComponent(child)\n                relationships[parent, default: []].insert(child)\n            }\n        }\n\n        // Processes modules recursively and returns a list of products to process.\n        func processModuleDependency(\n            from product: ResolvedProduct,\n            dependentModule: ResolvedModule\n        ) async throws -> [ResolvedProduct] {\n            var result: [ResolvedProduct] = []\n            var modulesToProcess: [ResolvedModule] = [dependentModule]\n            var processedModules = Set<ResolvedModule.ID>()\n\n            while !modulesToProcess.isEmpty {\n                let currentModule = modulesToProcess.removeFirst()\n                guard processedModules.insert(currentModule.id).inserted else {\n                    continue\n                }\n                let dependencies = try await dependencySource.getDependencies(for: currentModule)\n                for dependency in dependencies {\n                    switch dependency {\n                    case .product(let dependentProduct):\n                        if let processed = try await processProductDependency(from: product, dependentProduct: dependentProduct) {\n                            result.append(processed)\n                        }\n                    case .module(let dependentModule):\n                        if !processedModules.contains(dependentModule.id) {\n                            modulesToProcess.append(dependentModule)\n                        }\n                    }\n                }\n            }\n            \n            return result\n        }\n\n        // Takes a product and a dependent product, processes the relationships, and then returns the dependent product.\n        func processProductDependency(\n            from product: ResolvedProduct,\n            dependentProduct: ResolvedProduct\n        ) async throws -> ResolvedProduct? {\n            // if this relationship was already seen, return early\n            let processedProductComponent = try await extractComponent(product: product)\n            let dependentProductComponent = try await extractComponent(product: dependentProduct)\n            \n            if let productRelationships = relationships[processedProductComponent],\n               productRelationships.contains(dependentProductComponent) {\n                return dependentProduct\n            }\n\n            // check if both products are in the same root package\n            let bothInRootPackage = product.packageIdentity == rootPackage.identity &&\n                dependentProduct.packageIdentity == rootPackage.identity\n\n            // only track dependency if not both in root package\n            // this is because circular dependencies can be created in the SBOM\n            // because products in the same root package can share or be composed of the same targets\n            if !bothInRootPackage {\n                // add product -> dependentProduct dependency\n                trackRelationship(parent: processedProductComponent, child: dependentProductComponent)\n            }\n            if let dependentProductPackage = modulesGraph.packages\n                .first(where: { $0.identity == dependentProduct.packageIdentity }) {\n                let dependentProductPackageComponent = try await extractComponent(package: dependentProductPackage)\n                // add dependentProductPackage -> dependentProduct dependency\n                trackRelationship(parent: dependentProductPackageComponent, child: dependentProductComponent)\n                if let productPackage = modulesGraph.packages.first(where: { $0.identity == product.packageIdentity }) {\n                    let productPackageComponent = try await extractComponent(package: productPackage)\n                    // add productPackage -> dependentProductPackage dependency if they're from different packages\n                    if product.packageIdentity != dependentProduct.packageIdentity {\n                        trackRelationship(\n                            parent: productPackageComponent,\n                            child: dependentProductPackageComponent\n                        )\n                    }\n                    // add rootPackage -> productPackage dependency if it's not the root package itself\n                    if productPackageComponent.id != rootPackageID {\n                        trackRelationship(parent: rootPackageComponent, child: productPackageComponent)\n                    }\n                }\n            }\n            return dependentProduct\n        }\n\n        func processDependencies(for product: ResolvedProduct) async throws -> [ResolvedProduct] {\n            var result = IdentifiableSet<ResolvedProduct>()\n            \n            let dependencies = try await dependencySource.getDependencies(for: product)\n            \n            for dependency in dependencies {\n                switch dependency {\n                case .product(let dependentProduct):\n                    if let toProcess = try await processProductDependency(\n                        from: product,\n                        dependentProduct: dependentProduct\n                    ) {\n                        result.insert(toProcess)\n                    }\n                case .module(let dependentModule):\n                    let toProcess = try await processModuleDependency(\n                        from: product,\n                        dependentModule: dependentModule\n                    )\n                    for productToProcess in toProcess {\n                        result.insert(productToProcess)\n                    }\n                }\n            }\n            return Array(result)\n        }\n\n        func processRelationships() -> [SBOMRelationship] {\n            return relationships.map { parent, childrenSet in\n                SBOMRelationship(\n                    id: SBOMIdentifier(value: \"\\(parent.id.value)-depends-on\"),\n                    parentID: parent.id,\n                    childrenID: Array(childrenSet.map { $0.id }).sorted { $0.value < $1.value }\n                )\n            }.sorted()\n        }\n\n        let rootPackageID = SBOMExtractor.extractComponentID(from: rootPackage)\n        let rootPackageComponent = try await extractComponent(package: rootPackage)\n\n        for targetProduct in targetProducts {\n            let targetComponent = try await extractComponent(product: targetProduct)\n            trackRelationship(parent: rootPackageComponent, child: targetComponent)\n        }\n        \n        var processedProducts = IdentifiableSet<ResolvedProduct>()\n        var productsToProcess: [ResolvedProduct] = targetProducts\n\n        while !productsToProcess.isEmpty {\n            let currentProduct = productsToProcess.removeFirst()\n            processedProducts.insert(currentProduct)\n            let transitiveDeps = try await processDependencies(for: currentProduct)\n            for dep in transitiveDeps\n                where !processedProducts.contains(id: dep.id) && !productsToProcess.contains(where: { $0.id == dep.id })\n            {\n                productsToProcess.append(dep)\n            }\n        }\n\n        return SBOMDependencies(\n            components: Array(components).sorted(),\n            relationships: processRelationships()\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Extractor/SBOMExtractor.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageCollections\nimport PackageGraph\nimport PackageModel\nimport SourceControl\nimport TSCUtility\n\n/// Extractor for generating SBOM documents\ninternal struct SBOMExtractor {\n    let modulesGraph: ModulesGraph\n    let dependencyGraph: [String: [String]]?\n    let store: ResolvedPackagesStore\n    let caches: SBOMCaches\n\n    internal init(\n        modulesGraph: ModulesGraph,\n        dependencyGraph: [String: [String]]? = nil,\n        store: ResolvedPackagesStore\n    ) {\n        self.modulesGraph = modulesGraph\n        self.dependencyGraph = dependencyGraph\n        self.store = store\n        self.caches = SBOMCaches()\n    }\n\n    internal init(\n        modulesGraph: ModulesGraph,\n        dependencyGraph: [String: [String]]? = nil,\n        store: ResolvedPackagesStore,\n        caches: SBOMCaches\n    ) {\n        self.modulesGraph = modulesGraph\n        self.dependencyGraph = dependencyGraph\n        self.store = store\n        self.caches = caches\n    }\n\n    internal func extractMetadata() async throws -> SBOMMetadata {\n        SBOMMetadata(\n            timestamp: Date().ISO8601Format(),\n            creators: [\n                SBOMTool(\n                    id: SBOMIdentifier.generate(),\n                    name: \"swift-package-manager\",\n                    version: SwiftVersion.current.displayString,\n                    purl: PURL(\n                        scheme: \"pkg\",\n                        type: \"swift\",\n                        namespace: \"github.com/swiftlang\",\n                        name: \"swift-package-manager\",\n                        version: SwiftVersion.current.displayString\n                    ),\n                    licenses: [\n                        SBOMLicense(\n                            // TODO: https://github.com/swiftlang/swift-package-manager/issues/9717: better way to get license without hard-coding and without network call?\n                            // can't read the license in the root directory bc SBOM generation isn't always running in swift-package-manager\n                            name: PackageCollectionsModel.LicenseType.Apache2_0.description,\n                            url: \"http://swift.org/LICENSE.txt\"\n                        ),\n                    ]\n                ),\n            ]\n        )\n    }\n\n    internal static func extractCategory(from package: ResolvedPackage) throws -> SBOMComponent.Category {\n        let productCategories = package.products.map(\\.type)\n        if productCategories.contains(.executable) {\n            return .application\n        }\n        return .library\n    }\n\n    internal static func extractCategory(from product: ResolvedProduct) throws -> SBOMComponent.Category {\n        switch product.type {\n        case .executable:\n            .application\n        case .library, .snippet, .plugin, .test, .macro:\n            .library\n        }\n    }\n\n    internal static func extractScope(from product: ResolvedProduct) throws -> SBOMComponent.Scope {\n        if product.type == .test {\n            return .test\n        }\n        guard !product.modules.isEmpty else {\n            return .runtime\n        }\n        let allModulesAreTests = product.modules.allSatisfy { $0.type == .test }\n        return allModulesAreTests ? .test : .runtime\n    }\n\n    internal static func extractScope(from package: ResolvedPackage) throws -> SBOMComponent.Scope {\n        guard !package.products.isEmpty else {\n            return .runtime\n        }\n        let allProductsAreTests = package.products.allSatisfy { product in\n            product.isLinkingXCTest || product.type == .test\n        }\n        return allProductsAreTests ? .test : .runtime\n    }\n\n    private func extractComponentInfoFromGit(packagePath: AbsolutePath) async throws -> SBOMVersionInfo {\n        let gitRepo = GitRepository(path: packagePath, isWorkingRepo: true)\n\n        let currentRevision = try? gitRepo.getCurrentRevision()\n        guard let currentRevision else {\n            return SBOMVersionInfo(\n                version: SBOMComponent.Version(revision: \"unknown\"),\n                originator: SBOMOriginator(commits: nil)\n            )\n        }\n\n        let hasUncommittedChanges = gitRepo.hasUncommittedChanges()\n        let currentTag = gitRepo.getCurrentTag()\n        let revisionString: String = if let currentTag {\n            hasUncommittedChanges ? \"\\(currentTag)-modified\" : currentTag\n        } else {\n            hasUncommittedChanges ? \"\\(currentRevision.identifier)-modified\" : currentRevision.identifier\n        }\n\n        let commit = try gitRepo.getCurrentBranch()\n            .flatMap { try? gitRepo.getRemote(for: $0) }\n            .map { SBOMCommit(sha: currentRevision.identifier, repository: $0.1) }\n        let versionCommit = commit\n        let commits = commit.map { [$0] }\n\n        return SBOMVersionInfo(\n            version: SBOMComponent.Version(\n                revision: revisionString,\n                commit: versionCommit\n            ),\n            originator: SBOMOriginator(commits: commits)\n        )\n    }\n\n    private func extractComponentVersionInfo(from packageIdentity: PackageIdentity) async throws -> SBOMVersionInfo {\n        if let cachedVersionInfo = await caches.version.get(packageIdentity) {\n            return cachedVersionInfo\n        }\n        // root package (built from source)\n        if let rootPackage = modulesGraph.rootPackages.first(where: { $0.identity == packageIdentity }) {\n            let versionInfo = try await extractComponentInfoFromGit(packagePath: rootPackage.path)\n            await self.caches.version.set(packageIdentity, versionInfo: versionInfo)\n            return versionInfo\n        }\n        // non-root package (version is from store, URL is from registry or repo)\n        guard let resolvedPackage = store.resolvedPackages[packageIdentity] else {\n            return SBOMVersionInfo(\n                version: SBOMComponent.Version(revision: \"unknown\"),\n                originator: SBOMOriginator(commits: nil)\n            )\n        }\n\n        // Get the version\n        let version: String\n        let sha: String\n        switch resolvedPackage.state {\n        case .version(let versionValue, let revision):\n            version = versionValue.description\n            if let revision {\n                sha = revision\n            } else {\n                sha = \"unknown\"\n            }\n        case .branch(_, let revision), .revision(let revision):\n            version = revision\n            sha = revision\n        }\n        // Get registry or repo information\n        if resolvedPackage.packageRef.kind == .registry(packageIdentity) {\n            guard let registry = resolvedPackage.packageRef.identity.registry else {\n                return SBOMVersionInfo(\n                    version: SBOMComponent.Version(revision: version),\n                    originator: SBOMOriginator()\n                )\n            }\n            \n            guard let actualResolvedPackage = modulesGraph.packages.first(where: { $0.identity == packageIdentity }),\n                  let registryMetadata = actualResolvedPackage.registryMetadata,\n                  case .registry(let registryURL) = registryMetadata.source else {\n                return SBOMVersionInfo(\n                    version: SBOMComponent.Version(revision: version),\n                    originator: SBOMOriginator()\n                )\n            }\n            \n            let entry = SBOMRegistryEntry(\n                url: registryURL,\n                scope: registry.scope.description,\n                name: registry.name.description,\n                version: version\n            )\n            return SBOMVersionInfo(\n                version: SBOMComponent.Version(revision: version, entry: entry),\n                originator: SBOMOriginator(entries: [entry])\n            )\n        } else {\n            let commit = SBOMCommit(\n                sha: sha,\n                repository: resolvedPackage.packageRef.kind.locationString // absolute path, URL string, or package identity\n            )\n            return SBOMVersionInfo(\n                version: SBOMComponent.Version(revision: version, commit: commit),\n                originator: SBOMOriginator(commits: [commit])\n            )\n        }\n    }\n\n    internal static func extractComponentID(from package: ResolvedPackage) -> SBOMIdentifier {\n        SBOMIdentifier(value: package.identity.description)\n    }\n\n    internal static func extractComponentID(from product: ResolvedProduct) -> SBOMIdentifier {\n        SBOMIdentifier(value: \"\\(product.packageIdentity):\\(product.name)\")\n    }\n\n    private func extractProductsFromPackage(package: ResolvedPackage) async throws -> [SBOMComponent] {\n        var productComponents: [SBOMComponent] = []\n        for product in package.products {\n            let productComponent = try await extractComponent(product: product)\n            productComponents.append(productComponent)\n        }\n        return productComponents\n    }\n\n    internal func extractComponent(package: ResolvedPackage) async throws -> SBOMComponent {\n        if let cached = await caches.component.getPackage(package.identity) {\n            return cached\n        }\n\n        let versionInfo = try await extractComponentVersionInfo(from: package.identity)\n        let products = try await extractProductsFromPackage(package: package)\n        let component = try await SBOMComponent(\n            category: Self.extractCategory(from: package),\n            id: Self.extractComponentID(from: package),\n            purl: PURL.from(package: package, version: versionInfo.version),\n            name: package.identity.description,\n            version: versionInfo.version,\n            originator: versionInfo.originator,\n            description: package.description,\n            scope: Self.extractScope(from: package),\n            components: products,\n            entity: .package\n        )\n\n        await self.caches.component.setPackage(package.identity, component: component)\n\n        return component\n    }\n\n    internal func extractComponent(product: ResolvedProduct) async throws -> SBOMComponent {\n        if let cached = await caches.component.getProduct(product.packageIdentity, productName: product.name) {\n            return cached\n        }\n\n        let versionInfo = try await extractComponentVersionInfo(from: product.packageIdentity)\n        let component = try await SBOMComponent(\n            category: Self.extractCategory(from: product),\n            id: Self.extractComponentID(from: product),\n            purl: PURL.from(product: product, version: versionInfo.version),\n            name: product.name,\n            version: versionInfo.version,\n            originator: versionInfo.originator,\n            description: nil,\n            scope: Self.extractScope(from: product),\n            entity: .product\n        )\n\n        await self.caches.component.setProduct(product.packageIdentity, productName: product.name, component: component)\n\n        return component\n    }\n\n    internal func extractPrimaryComponent(product: String? = nil) async throws -> SBOMComponent {\n        guard let rootPackage = modulesGraph.rootPackages.first else {\n            throw SBOMExtractorError.noRootPackage(context: \"determine primary component for SBOM\")\n        }\n        // product of root package\n        if let productName = product {\n            guard let resolvedProduct = rootPackage.products.first(where: { $0.name == productName }) else {\n                throw SBOMExtractorError.productNotFound(\n                    productName: productName,\n                    packageIdentity: rootPackage.identity.description\n                )\n            }\n            return try await self.extractComponent(product: resolvedProduct)\n        }\n        // root package\n        return try await self.extractComponent(package: rootPackage)\n    }\n\n    internal func extractSBOM(product: String? = nil, filter: Filter = .all) async throws -> SBOMDocument {\n        try await SBOMDocument(\n            id: SBOMIdentifier.generate(),\n            metadata: self.extractMetadata(),\n            primaryComponent: self.extractPrimaryComponent(product: product), // either a root package or a product of the root package\n            dependencies: extractDependencies(product: product, filter: filter)\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Extractor/SBOMFilterStrategy.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Protocol defining filtering behavior for SBOM components and relationships\nprotocol SBOMFilterStrategy {\n    /// Determines whether a component should be included based on the filter criteria\n    func shouldIncludeComponent(_ component: SBOMComponent, primaryComponent: SBOMComponent) -> Bool\n    \n    /// Determines whether a relationship should be tracked based on the filter criteria\n    func shouldTrackRelationship(\n        parent: SBOMComponent,\n        child: SBOMComponent,\n        primaryComponent: SBOMComponent\n    ) -> Bool\n}\n\n/// Filter strategy that includes all components and relationships\nstruct AllFilterStrategy: SBOMFilterStrategy {\n    func shouldIncludeComponent(_ component: SBOMComponent, primaryComponent: SBOMComponent) -> Bool {\n        return true // All filter includes everything\n    }\n    \n    func shouldTrackRelationship(\n        parent: SBOMComponent,\n        child: SBOMComponent,\n        primaryComponent: SBOMComponent\n    ) -> Bool {\n        return parent != child // prevent self-referential dependencies\n    }\n}\n\n/// Filter strategy that only includes product-level components and relationships\nstruct ProductFilterStrategy: SBOMFilterStrategy {\n    func shouldIncludeComponent(_ component: SBOMComponent, primaryComponent: SBOMComponent) -> Bool {\n        // Always include products\n        if component.entity == .product {\n            return true\n        }\n        // If the primary component is a package, also include that root package so that the primary component can connect to the products\n        if primaryComponent.entity == .package && component.id == primaryComponent.id {\n            return true\n        }\n        return false\n    }\n    \n    func shouldTrackRelationship(\n        parent: SBOMComponent,\n        child: SBOMComponent,\n        primaryComponent: SBOMComponent\n    ) -> Bool {\n        // prevent self-referential dependencies\n        guard parent != child else { return false } \n        if child.entity == .product {\n            // if the primary component is a product, then include product-product relationships\n            if parent.entity == .product {\n                return true\n            }\n            // if the primary component is a package, then need to also include root-package-to-root-product relationship(s) for a full graph\n            if primaryComponent.entity == .package && parent.id == primaryComponent.id {\n                return true\n            }\n        }\n        return false\n    }\n}\n\n/// Filter strategy that only includes package-level components and relationships\nstruct PackageFilterStrategy: SBOMFilterStrategy {\n    func shouldIncludeComponent(_ component: SBOMComponent, primaryComponent: SBOMComponent) -> Bool {\n        // Always include packages\n        if component.entity == .package {\n            return true\n        }\n        // If the primary component is a product, also include that product\n        // This allows package-to-product relationships when the root is a product\n        if primaryComponent.entity == .product && component.id == primaryComponent.id {\n            return true\n        }\n        return false\n    }\n    \n    func shouldTrackRelationship(\n        parent: SBOMComponent,\n        child: SBOMComponent,\n        primaryComponent: SBOMComponent\n    ) -> Bool {\n        // prevent self-referential dependencies\n        guard parent != child else { return false } \n        if parent.entity == .package {\n            // always include package-to-package relationships\n            if child.entity == .package {\n                return true\n            }\n            // If the primary component is a product, then include package-to-product relationship for a full graph\n            if primaryComponent.entity == .product && child.id == primaryComponent.id {\n                return true\n            }\n        }\n        return false\n    }\n}\n\nextension Filter {\n    /// Creates the appropriate filter strategy for this filter type\n    func createStrategy() -> SBOMFilterStrategy {\n        switch self {\n        case .all:\n            return AllFilterStrategy()\n        case .product:\n            return ProductFilterStrategy()\n        case .package:\n            return PackageFilterStrategy()\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Extractor/SBOMGraphsConverter.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageGraph\nimport PackageModel\nimport SwiftBuildSupport\n\n/// Utilities for converting between ModulesGraph and dependency graph naming conventions.\ninternal struct SBOMGraphsConverter {\n\n    // The PIF creates target names for products, modules, and resource bundles\n    // Product target names get a -product suffix\n    // Module target names are passed through\n    // Resource bundle target names are packageName_moduleName\n    // SBOMs ignore resource bundles\n\n    internal static func getTargetName(fromProduct name: String) -> String {\n        return PackagePIFBuilder.targetName(forProductName: name)\n    }\n\n    internal static func getTargetName(fromModule name: String) -> String {\n        return PackagePIFBuilder.targetName(forModuleName: name)\n    }\n\n    internal static func getProductName(fromTarget name: String) -> String? {\n        return PackagePIFBuilder.productName(forTargetName: name)\n    }\n\n    internal static func getModuleName(fromTarget name: String) -> String?\n    {\n        return PackagePIFBuilder.moduleName(forTargetName: name)\n    }\n\n    internal static func toProduct(fromTarget name: String, modulesGraph: ModulesGraph) -> ResolvedProduct? {\n        getProductName(fromTarget: name).flatMap { modulesGraph.product(for: $0) }\n    }\n\n    internal static func toModule(fromTarget name: String, modulesGraph: ModulesGraph) -> ResolvedModule? {\n        getModuleName(fromTarget: name).flatMap { modulesGraph.module(for: $0) }\n    }\n}"
  },
  {
    "path": "Sources/SBOMModel/README.md",
    "content": "# SBOMModel - SBOM Version Management\n\nThis document describes how to manage SBOM specification versions in SwiftPM.\n\n## Overview\n\nThe `SBOMVersionRegistry` maintains the most recent minor version for each major version of supported SBOM specifications (CycloneDX and SPDX).\n\n### Version Support Policy\n\nSwiftPM supports **only the most recent minor version** of each **major version**:\n- When a new minor version is released (e.g., CycloneDX 1.8), drop the old minor (1.7)\n- When a new major version is released (e.g., CycloneDX 2.0), maintain both major versions\n\n## Current Supported Versions\n\n### CycloneDX\n- **v1.x**: Latest minor version is 1.7\n\n### SPDX\n- **v3.x**: Latest minor version is 3.0.1\n\n## Updating Minor Versions\n\nWhen a new minor version is released (e.g., CycloneDX 1.8 or SPDX 3.1), follow these steps:\n\n### Step 1: Update Version Constant\n\nIn [`SBOMVersionRegistry.swift`](Core/SBOMVersionRegistry.swift), change the version string:\n\n```swift\n// Before:\ninternal static let cycloneDX1LatestMinor = \"1.7\"\n\n// After:\ninternal static let cycloneDX1LatestMinor = \"1.8\"\n```\n\n### Step 2: Replace Schema File\n\nIn the Resources directory:\n- **Delete**: `Sources/SBOMModel/CycloneDX/Resources/cyclonedx-1.7.schema.json`\n- **Add**: `Sources/SBOMModel/CycloneDX/Resources/cyclonedx-1.8.schema.json`\n\n### Step 3: Update Tests\n\nUpdate test expectations to use the new version:\n\n```swift\n// Before:\nXCTAssertEqual(spec.version, \"1.7\")\n\n// After:\nXCTAssertEqual(spec.version, \"1.8\")\n```\n\n### Step 4: Verify Constants\n\nThe constants should automatically use the new version:\n- `CycloneDXConstants.cyclonedx1SpecVersion` → \"1.8\"\n- `CycloneDXConstants.cyclonedx1Schema` → \"...bom-1.8.schema.json\"\n- `CycloneDXConstants.cyclonedx1SchemaFile` → \"cyclonedx-1.8.schema\"\n\n### Step 5: Test Thoroughly\n\n- Run all SBOM tests\n- Generate sample SBOMs and validate against new schema\n- Verify backward compatibility if needed\n\n## Adding New Major Versions\n\nWhen a new major version is released (e.g., CycloneDX 2.0 or SPDX 4.0), follow these steps:\n\n### Step 1: Update SBOMVersionRegistry.swift\n\nUncomment and set the appropriate version constant:\n\n```swift\ninternal static let cycloneDX2LatestMinor = \"2.0\"  // or spdx4LatestMinor = \"4.0\"\n```\n\nAdd the case to `getLatestVersion(for:)`:\n\n```swift\ncase .cyclonedx2:\n    return cycloneDX2LatestMinor\n```\n\n### Step 2: Update SBOMSpec.swift\n\nAdd new case to the `Spec` enum:\n\n```swift\ncase cyclonedx2  // or spdx4\n```\n\nUpdate all switch statements to handle the new case.\n\n### Step 3: Create New Constants\n\nAdd to [`CycloneDXConstants.swift`](CycloneDX/CycloneDXConstants.swift) (or [`SPDXConstants.swift`](SPDX/SPDXConstants.swift)):\n\n```swift\ninternal static var cyclonedx2SpecVersion: String {\n    SBOMVersionRegistry.cycloneDX2LatestMinor\n}\ninternal static var cyclonedx2Schema: String {\n    \"http://cyclonedx.org/schema/bom-\\(cyclonedx2SpecVersion).schema.json\"\n}\ninternal static var cyclonedx2SchemaFile: String {\n    \"cyclonedx-\\(cyclonedx2SpecVersion).schema\"\n}\n```\n\n### Step 4: Update Encoder and Converter\n\nIn [`SBOMEncoder.swift`](Encoder/SBOMEncoder.swift):\n- Update `encodeSBOMData(spec:)` switch statement\n- Update `getSchemaFilename(from:)` switch statement\n\nIn [`CycloneDXConverter.swift`](Converter/CycloneDXConverter.swift) (or [`SPDXConverter.swift`](Converter/SPDXConverter.swift)):\n- Add converter methods for new major version if format changed\n- Or reuse existing converter if format is compatible\n\n### Step 5: Add Schema File\n\nAdd the schema file to Resources:\n- `Sources/SBOMModel/CycloneDX/Resources/cyclonedx-2.0.schema.json`\n- Or: `Sources/SBOMModel/SPDX/Resources/spdx-4.0.schema.json`\n\n### Step 6: Update Tests\n\n- Add test fixtures for new major version\n- Update test expectations\n- Verify both old and new major versions work correctly\n\n## Version Resolution\n\nThe registry provides a central method to get the latest supported version for any spec type:\n\n```swift\nlet version = SBOMVersionRegistry.getLatestVersion(for: spec)\n```\n"
  },
  {
    "path": "Sources/SBOMModel/SBOMCreator.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\nimport protocol TSCBasic.OutputByteStream\n\ninternal struct SBOMResult {\n    internal let spec: SBOMSpec\n    internal let path: AbsolutePath\n\n    internal init(spec: SBOMSpec, path: AbsolutePath) {\n        self.spec = spec\n        self.path = path\n    }\n}\n\npackage struct SBOMCreator {\n\n    package let input: SBOMInput\n    \n    package init(input: SBOMInput) {\n        self.input = input\n    }\n\n    package static func resolveSBOMDirectory(from configPath: AbsolutePath?, withDefault defaultPath: AbsolutePath) async -> AbsolutePath {\n        return configPath ?? defaultPath.appending(component: \"sboms\")\n    }\n\n    /// Creates SBOMs with timing and logging output to the output stream.\n    /// This method consolidates the common SBOM generation logic used by both\n    /// the `swift build` and `swift package generate-sbom` commands.\n    ///\n    /// - Returns: An array of paths to the created SBOM files\n    /// - Throws: SBOMGenerationError if SBOM creation fails\n    package func createSBOMsWithLogging() async throws {\n        defer { input.outputStream.flush() }\n        \n        input.outputStream.write(\"Creating SBOMs...\\n\")\n        let sbomStartTime = ContinuousClock.Instant.now\n        \n        let results = try await createSBOMs()\n        \n        let duration = ContinuousClock.Instant.now - sbomStartTime\n        let formattedDuration = duration.formatted(.units(allowed: [.seconds], fractionalPart: .show(length: 2, rounded: .up)))\n        \n        for result in results {\n            input.outputStream.write(\"- created \\(result.spec.concreteSpec) v\\(SBOMVersionRegistry.getLatestVersion(for: result.spec)) SBOM at \\(result.path.pathString)\\n\")\n        }\n        input.outputStream.write(\"SBOMs created  (\\(formattedDuration))\\n\")\n    }\n\n    internal func createSBOMs() async throws -> [SBOMResult] {\n        guard !input.specs.isEmpty else {\n            throw SBOMGenerationError.noSpecsProvided\n        }\n        \n        let extractor = SBOMExtractor(\n            modulesGraph: input.modulesGraph,\n            dependencyGraph: input.dependencyGraph,\n            store: input.store\n        )\n        \n        let sbom = try await extractor.extractSBOM(\n            product: input.product,\n            filter: input.filter\n        )\n        \n        let encoder = SBOMEncoder(sbom: sbom, observabilityScope: input.observabilityScope)\n        let results = try await encoder.writeSBOMs(\n            specs: input.specs,\n            outputDir: input.dir,\n            filter: input.filter\n        )\n\n        guard !results.isEmpty else {\n            throw SBOMGenerationError.failedToWriteSBOM\n        }\n\n        return results\n    }\n}\n\n"
  },
  {
    "path": "Sources/SBOMModel/SBOMError.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n// MARK: - General SBOM Errors\n\n/// General errors that can occur across SBOM operations\ninternal enum SBOMGenerationError: Error, LocalizedError, CustomStringConvertible {\n    case unexpectedSpecType(expected: String, actual: SBOMSpec)\n    case failedToWriteSBOM\n    case noSpecsProvided\n\n    internal var errorDescription: String? {\n        switch self {\n        case .unexpectedSpecType(let expected, let actual):\n            \"Expected \\(expected) spec but got \\(actual.concreteSpec)\"\n        case .failedToWriteSBOM:\n            \"Failed to write SBOM\"\n        case .noSpecsProvided:\n            \"No SBOM specifications provided\"\n        }\n    }\n\n    internal var description: String {\n        self.errorDescription ?? \"Unknown SBOM error\"\n    }\n}\n\n// MARK: - Command Errors\n\n/// Errors that can occur during the SBOM generation command\npackage enum SBOMCommandError: Error, LocalizedError {\n    case noSpecArg\n    case targetFlagNotSupported\n    case invalidFilterValue(value: String)\n    case invalidSpecValue(value: String)\n    \n    public var errorDescription: String? {\n        switch self {\n        case .noSpecArg:\n            return \"No SBOM specification argument provided. Use --sbom-spec or SWIFTPM_BUILD_SBOM_SPEC to specify the SBOM format.\"\n        case .targetFlagNotSupported:\n            return \"--sbom-spec or SWIFTPM_BUILD_SBOM_SPEC cannot be used with --target flag\"\n        case .invalidFilterValue(let value):\n            let validValues = Filter.allCases.map(\\.rawValue).joined(separator: \", \")\n            return \"Invalid SBOM filter value '\\(value)' in environment variable SWIFTPM_BUILD_SBOM_FILTER. Valid values are: \\(validValues)\"\n        case .invalidSpecValue(let value):\n            let validValues = Spec.allCases.map(\\.rawValue).joined(separator: \", \")\n            return \"Invalid SBOM spec value '\\(value)' in environment variable SWIFTPM_BUILD_SBOM_SPEC. Valid values are \\(validValues). Specify multiple specs by separating valid values with commas\"\n        }\n    }\n}\n// MARK: - Schema Errors\n\n/// Errors that can occur during SBOM schema operations\ninternal enum SBOMSchemaError: Error, LocalizedError, CustomStringConvertible {\n    /// Schema file not found in bundle\n    case schemaFileNotFound(filename: String, bundlePath: String)\n    /// Invalid JSON schema format\n    case invalidSchemaFormat(message: String)\n    /// Bundle not found (validation will be skipped)\n    case bundleNotFound(bundleName: String)\n    \n    internal var errorDescription: String? {\n        switch self {\n        case .schemaFileNotFound(let filename, let bundlePath):\n            \"SBOM schema file '\\(filename).json' not found in bundle: \\(bundlePath)\"\n        case .invalidSchemaFormat(let message):\n            \"Invalid JSON schema format: \\(message)\"\n        case .bundleNotFound(let bundleName):\n            \"Bundle '\\(bundleName)' with schemas not found\"\n        }\n    }\n\n    internal var description: String {\n        self.errorDescription ?? \"Unknown SBOM schema error\"\n    }\n}\n\n// MARK: - Converter Errors\n\n/// Errors that can occur during SBOM format conversion\ninternal enum SBOMConverterError: Error, LocalizedError, CustomStringConvertible {\n    /// Missing required metadata for conversion\n    case missingRequiredMetadata(message: String)\n\n    internal var errorDescription: String? {\n        switch self {\n        case .missingRequiredMetadata(let message):\n            \"Missing required metadata: \\(message)\"\n        }\n    }\n\n    internal var description: String {\n        self.errorDescription ?? \"Unknown SBOM converter error\"\n    }\n}\n\n// MARK: - Extractor Errors\n\n/// Errors that can occur during SBOM data extraction\ninternal enum SBOMExtractorError: Error, LocalizedError, CustomStringConvertible {\n    /// No root package found in package graph\n    case noRootPackage(context: String)\n    /// No build graph available\n    case noBuildGraph(context: String)\n    /// Product not found in package\n    case productNotFound(productName: String, packageIdentity: String)\n    internal var errorDescription: String? {\n        switch self {\n        case .noRootPackage(let context):\n            \"No root package found in package graph, cannot \\(context)\"\n        case .noBuildGraph(let context):\n            \"No build graph available, cannot \\(context)\"\n        case .productNotFound(let productName, let packageIdentity):\n            \"Product '\\(productName)' not found in root package '\\(packageIdentity)'\"\n        }\n    }\n\n    internal var description: String {\n        self.errorDescription ?? \"Unknown SBOM extractor error\"\n    }\n}\n\n// MARK: - Encoder Errors\n\n/// Errors that can occur during SBOM encoding\ninternal enum SBOMEncoderError: Error, LocalizedError, CustomStringConvertible {\n    /// Failed to convert SBOM to JSON object\n    case jsonConversionFailed(message: String)\n    internal var errorDescription: String? {\n        switch self {\n        case .jsonConversionFailed(let message):\n            \"Failed to convert SBOM to JSON: \\(message)\"\n        }\n    }\n\n    internal var description: String {\n        self.errorDescription ?? \"Unknown SBOM encoder error\"\n    }\n}\n\n// MARK: - Validator Errors\n\n/// Errors that can occur during SBOM validation\ninternal enum SBOMValidatorError: Error, LocalizedError, CustomStringConvertible {\n    /// Value does not match 'not' schema (should not match)\n    case notSchemaViolation(path: String, valueDescription: String)\n    /// Type mismatch during validation\n    case typeMismatch(path: String, expected: String, actual: String, debugInfo: String)\n    /// Missing required property\n    case missingRequired(path: String, property: String)\n    /// Invalid value\n    case invalidValue(path: String, message: String)\n    /// Schema composition error (oneOf, anyOf, allOf)\n    case schemaComposition(path: String, message: String)\n    /// Constraint violation (min/max, pattern, etc.)\n    case constraintViolation(path: String, message: String)\n    internal var errorDescription: String? {\n        switch self {\n        case .notSchemaViolation(let path, let valueDescription):\n            \"Value at \\(path) matches 'not' schema (should not match). Value: \\(valueDescription)\"\n        case .typeMismatch(let path, let expected, let actual, let debugInfo):\n            \"Type mismatch at \\(path): expected \\(expected), got \\(actual) (\\(debugInfo))\"\n        case .missingRequired(let path, let property):\n            \"Missing required property '\\(property)' at \\(path)\"\n        case .invalidValue(let path, let message):\n            \"Invalid value at \\(path): \\(message)\"\n        case .schemaComposition(let path, let message):\n            \"Schema composition error at \\(path): \\(message)\"\n        case .constraintViolation(let path, let message):\n            \"Constraint violation at \\(path): \\(message)\"\n        }\n    }\n\n    internal var description: String {\n        self.errorDescription ?? \"Unknown SBOM validator error\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SBOMInput.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport PackageGraph\nimport PackageModel\n\nimport protocol TSCBasic.OutputByteStream\nimport var TSCBasic.stdoutStream\n\npackage enum Filter: String, Codable, Equatable, CaseIterable {\n    case all\n    case product\n    case package\n\n    package var defaultValueDescription: String {\n        switch self {\n        case .all: \"Include all entities in the SBOM\"\n        case .product: \"Only include product information and product dependencies\"\n        case .package: \"Only include package information and package dependencies\"\n        }\n    }\n}\n\nextension Filter: ExpressibleByArgument {\n    package init?(argument: String) {\n        self.init(rawValue: argument)\n    }\n}\n\npackage struct SBOMInput {\n    // Fields for SBOMExtractor\n    package let modulesGraph: ModulesGraph\n    package let dependencyGraph: [String: [String]]?\n    package let store: ResolvedPackagesStore\n    package let filter: Filter\n    package let product: String?\n    \n    // Fields for SBOMEncoder\n    package let specs: [Spec]\n    package let dir: AbsolutePath\n    \n    // ObservabilityScope for emitting diagnostics\n    package let observabilityScope: ObservabilityScope\n    \n    // Output stream for writing output\n    package let outputStream: OutputByteStream\n    \n    package init(\n        modulesGraph: ModulesGraph,\n        dependencyGraph: [String: [String]]?,\n        store: ResolvedPackagesStore,\n        filter: Filter,\n        product: String?,\n        specs: [Spec],\n        dir: AbsolutePath,\n        observabilityScope: ObservabilityScope,\n        outputStream: OutputByteStream = TSCBasic.stdoutStream\n    ) {\n        self.modulesGraph = modulesGraph\n        self.dependencyGraph = dependencyGraph\n        self.store = store\n        self.filter = filter\n        self.product = product\n        self.specs = specs\n        self.dir = dir\n        self.observabilityScope = observabilityScope\n        self.outputStream = outputStream\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/Resources/spdx-3.0.1.schema.json",
    "content": "{\n  \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n  \"$comment\": \"This file was automatically generated by shacl2code. DO NOT MANUALLY MODIFY IT\",\n  \"type\": \"object\",\n\n  \"properties\": {\n      \"@context\": {\n          \"const\": \"https://spdx.org/rdf/3.0.1/spdx-context.jsonld\"\n      }\n  },\n  \"required\": [\"@context\"],\n\n  \"oneOf\": [\n      {\n          \"type\": \"object\",\n          \"properties\": {\n              \"@graph\": {\n                  \"description\": \"Top level container for JSON-LD objects\",\n                  \"type\": \"array\",\n                  \"items\": {\n                      \"type\": \"object\",\n                      \"$ref\": \"#/$defs/AnyClass\",\n                      \"unevaluatedProperties\": false\n                  }\n              }\n          },\n          \"required\": [\"@graph\"]\n      },\n      { \"$ref\": \"#/$defs/AnyClass\" }\n  ],\n  \"unevaluatedProperties\": false,\n\n  \"$defs\": {\n      \"ai_EnergyConsumption\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ai_EnergyConsumption\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ai_EnergyConsumption_props\" }\n          ]\n      },\n      \"ai_EnergyConsumption_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_EnergyConsumption\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ai_EnergyConsumption_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"ai_finetuningEnergyConsumption\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_EnergyConsumption_ai_finetuningEnergyConsumption\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_inferenceEnergyConsumption\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_EnergyConsumption_ai_inferenceEnergyConsumption\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_trainingEnergyConsumption\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_EnergyConsumption_ai_trainingEnergyConsumption\"\n                                  }\n                              }\n                          ]\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_ai_EnergyConsumption_ai_finetuningEnergyConsumption\": {\n              \"$ref\": \"#/$defs/ai_EnergyConsumptionDescription_derived\"\n      },\n      \"prop_ai_EnergyConsumption_ai_inferenceEnergyConsumption\": {\n              \"$ref\": \"#/$defs/ai_EnergyConsumptionDescription_derived\"\n      },\n      \"prop_ai_EnergyConsumption_ai_trainingEnergyConsumption\": {\n              \"$ref\": \"#/$defs/ai_EnergyConsumptionDescription_derived\"\n      },\n      \"ai_EnergyConsumptionDescription\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ai_EnergyConsumptionDescription\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ai_EnergyConsumptionDescription_props\" }\n          ]\n      },\n      \"ai_EnergyConsumptionDescription_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_EnergyConsumptionDescription\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ai_EnergyConsumptionDescription_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"ai_energyQuantity\": {\n                          \"$ref\": \"#/$defs/prop_ai_EnergyConsumptionDescription_ai_energyQuantity\"\n                      },\n                      \"ai_energyUnit\": {\n                          \"$ref\": \"#/$defs/prop_ai_EnergyConsumptionDescription_ai_energyUnit\"\n                      }\n                  },\n                  \"required\": [\n                      \"ai_energyQuantity\",\n                      \"ai_energyUnit\"\n                  ]\n              }\n          ]\n      },\n      \"prop_ai_EnergyConsumptionDescription_ai_energyQuantity\": {\n                  \"oneOf\": [\n                      {\n                          \"type\": \"number\"\n                      },\n                      {\n                          \"type\": \"string\",\n                          \"pattern\": \"^-?[0-9]+(\\\\.[0-9]*)?$\"\n                      }\n                  ]\n      },\n      \"prop_ai_EnergyConsumptionDescription_ai_energyUnit\": {\n              \"enum\": [\n                  \"kilowattHour\",\n                  \"megajoule\",\n                  \"other\"\n              ]\n      },\n      \"ai_EnergyUnitType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ai_EnergyUnitType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ai_EnergyUnitType_props\" }\n          ]\n      },\n      \"ai_EnergyUnitType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_EnergyUnitType\" }\n                  ]\n              },\n              { \"const\": \"spdx:AI/EnergyUnitType/kilowattHour\" },\n              { \"const\": \"spdx:AI/EnergyUnitType/megajoule\" },\n              { \"const\": \"spdx:AI/EnergyUnitType/other\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ai_EnergyUnitType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"ai_SafetyRiskAssessmentType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ai_SafetyRiskAssessmentType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ai_SafetyRiskAssessmentType_props\" }\n          ]\n      },\n      \"ai_SafetyRiskAssessmentType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_SafetyRiskAssessmentType\" }\n                  ]\n              },\n              { \"const\": \"spdx:AI/SafetyRiskAssessmentType/high\" },\n              { \"const\": \"spdx:AI/SafetyRiskAssessmentType/low\" },\n              { \"const\": \"spdx:AI/SafetyRiskAssessmentType/medium\" },\n              { \"const\": \"spdx:AI/SafetyRiskAssessmentType/serious\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ai_SafetyRiskAssessmentType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"AnnotationType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"AnnotationType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/AnnotationType_props\" }\n          ]\n      },\n      \"AnnotationType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/AnnotationType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/AnnotationType/other\" },\n              { \"const\": \"spdx:Core/AnnotationType/review\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"AnnotationType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"CreationInfo\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"CreationInfo\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/CreationInfo_props\" }\n          ]\n      },\n      \"CreationInfo_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/CreationInfo\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"CreationInfo_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"comment\": {\n                          \"$ref\": \"#/$defs/prop_CreationInfo_comment\"\n                      },\n                      \"created\": {\n                          \"$ref\": \"#/$defs/prop_CreationInfo_created\"\n                      },\n                      \"createdBy\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"minItems\": 1,\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_CreationInfo_createdBy\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"createdUsing\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_CreationInfo_createdUsing\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"specVersion\": {\n                          \"$ref\": \"#/$defs/prop_CreationInfo_specVersion\"\n                      }\n                  },\n                  \"required\": [\n                      \"created\",\n                      \"createdBy\",\n                      \"specVersion\"\n                  ]\n              }\n          ]\n      },\n      \"prop_CreationInfo_comment\": {\n                  \"type\": \"string\"\n      },\n      \"prop_CreationInfo_created\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_CreationInfo_createdBy\": {\n              \"$ref\": \"#/$defs/Agent_derived\"\n      },\n      \"prop_CreationInfo_createdUsing\": {\n              \"$ref\": \"#/$defs/Tool_derived\"\n      },\n      \"prop_CreationInfo_specVersion\": {\n                  \"pattern\": \"^(0|[1-9]\\\\d*)\\\\.(0|[1-9]\\\\d*)\\\\.(0|[1-9]\\\\d*)(?:-((?:0|[1-9]\\\\d*|\\\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\\\.(?:0|[1-9]\\\\d*|\\\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\\\+([0-9a-zA-Z-]+(?:\\\\.[0-9a-zA-Z-]+)*))?$\",\n                  \"type\": \"string\"\n      },\n      \"DictionaryEntry\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"DictionaryEntry\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/DictionaryEntry_props\" }\n          ]\n      },\n      \"DictionaryEntry_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/DictionaryEntry\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"DictionaryEntry_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"key\": {\n                          \"$ref\": \"#/$defs/prop_DictionaryEntry_key\"\n                      },\n                      \"value\": {\n                          \"$ref\": \"#/$defs/prop_DictionaryEntry_value\"\n                      }\n                  },\n                  \"required\": [\n                      \"key\"\n                  ]\n              }\n          ]\n      },\n      \"prop_DictionaryEntry_key\": {\n                  \"type\": \"string\"\n      },\n      \"prop_DictionaryEntry_value\": {\n                  \"type\": \"string\"\n      },\n      \"Element_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_AIPackage\" },\n                      { \"$ref\": \"#/$defs/build_Build\" },\n                      { \"$ref\": \"#/$defs/Agent\" },\n                      { \"$ref\": \"#/$defs/Annotation\" },\n                      { \"$ref\": \"#/$defs/Bom\" },\n                      { \"$ref\": \"#/$defs/Bundle\" },\n                      { \"$ref\": \"#/$defs/IndividualElement\" },\n                      { \"$ref\": \"#/$defs/LifecycleScopedRelationship\" },\n                      { \"$ref\": \"#/$defs/Organization\" },\n                      { \"$ref\": \"#/$defs/Person\" },\n                      { \"$ref\": \"#/$defs/Relationship\" },\n                      { \"$ref\": \"#/$defs/SoftwareAgent\" },\n                      { \"$ref\": \"#/$defs/SpdxDocument\" },\n                      { \"$ref\": \"#/$defs/Tool\" },\n                      { \"$ref\": \"#/$defs/dataset_DatasetPackage\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_ConjunctiveLicenseSet\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_CustomLicense\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_CustomLicenseAddition\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_DisjunctiveLicenseSet\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_IndividualLicensingInfo\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_ListedLicense\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_ListedLicenseException\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_OrLaterOperator\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_WithAdditionOperator\" },\n                      { \"$ref\": \"#/$defs/security_CvssV2VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_CvssV3VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_CvssV4VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_EpssVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_ExploitCatalogVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_SsvcVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexAffectedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexFixedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexNotAffectedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexUnderInvestigationVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_Vulnerability\" },\n                      { \"$ref\": \"#/$defs/simplelicensing_LicenseExpression\" },\n                      { \"$ref\": \"#/$defs/simplelicensing_SimpleLicensingText\" },\n                      { \"$ref\": \"#/$defs/software_File\" },\n                      { \"$ref\": \"#/$defs/software_Package\" },\n                      { \"$ref\": \"#/$defs/software_Sbom\" },\n                      { \"$ref\": \"#/$defs/software_Snippet\" }\n                  ]\n              },\n              { \"const\": \"NoAssertionElement\" },\n              { \"const\": \"NoneElement\" },\n              { \"const\": \"SpdxOrganization\" },\n              { \"const\": \"expandedlicensing_NoAssertionLicense\" },\n              { \"const\": \"expandedlicensing_NoneLicense\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Element_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"comment\": {\n                          \"$ref\": \"#/$defs/prop_Element_comment\"\n                      },\n                      \"creationInfo\": {\n                          \"$ref\": \"#/$defs/prop_Element_creationInfo\"\n                      },\n                      \"description\": {\n                          \"$ref\": \"#/$defs/prop_Element_description\"\n                      },\n                      \"extension\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_Element_extension\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"externalIdentifier\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_Element_externalIdentifier\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"externalRef\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_Element_externalRef\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"name\": {\n                          \"$ref\": \"#/$defs/prop_Element_name\"\n                      },\n                      \"summary\": {\n                          \"$ref\": \"#/$defs/prop_Element_summary\"\n                      },\n                      \"verifiedUsing\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_Element_verifiedUsing\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"creationInfo\"\n                  ]\n              }\n          ]\n      },\n      \"prop_Element_comment\": {\n                  \"type\": \"string\"\n      },\n      \"prop_Element_creationInfo\": {\n              \"$ref\": \"#/$defs/CreationInfo_derived\"\n      },\n      \"prop_Element_description\": {\n                  \"type\": \"string\"\n      },\n      \"prop_Element_extension\": {\n              \"$ref\": \"#/$defs/extension_Extension_derived\"\n      },\n      \"prop_Element_externalIdentifier\": {\n              \"$ref\": \"#/$defs/ExternalIdentifier_derived\"\n      },\n      \"prop_Element_externalRef\": {\n              \"$ref\": \"#/$defs/ExternalRef_derived\"\n      },\n      \"prop_Element_name\": {\n                  \"type\": \"string\"\n      },\n      \"prop_Element_summary\": {\n                  \"type\": \"string\"\n      },\n      \"prop_Element_verifiedUsing\": {\n              \"$ref\": \"#/$defs/IntegrityMethod_derived\"\n      },\n      \"ElementCollection_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Bom\" },\n                      { \"$ref\": \"#/$defs/Bundle\" },\n                      { \"$ref\": \"#/$defs/SpdxDocument\" },\n                      { \"$ref\": \"#/$defs/software_Sbom\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ElementCollection_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"element\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ElementCollection_element\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"profileConformance\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ElementCollection_profileConformance\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"rootElement\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ElementCollection_rootElement\"\n                                  }\n                              }\n                          ]\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_ElementCollection_element\": {\n              \"$ref\": \"#/$defs/Element_derived\"\n      },\n      \"prop_ElementCollection_profileConformance\": {\n              \"enum\": [\n                  \"ai\",\n                  \"build\",\n                  \"core\",\n                  \"dataset\",\n                  \"expandedLicensing\",\n                  \"extension\",\n                  \"lite\",\n                  \"security\",\n                  \"simpleLicensing\",\n                  \"software\"\n              ]\n      },\n      \"prop_ElementCollection_rootElement\": {\n              \"$ref\": \"#/$defs/Element_derived\"\n      },\n      \"ExternalIdentifier\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ExternalIdentifier\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ExternalIdentifier_props\" }\n          ]\n      },\n      \"ExternalIdentifier_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ExternalIdentifier\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ExternalIdentifier_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"comment\": {\n                          \"$ref\": \"#/$defs/prop_ExternalIdentifier_comment\"\n                      },\n                      \"externalIdentifierType\": {\n                          \"$ref\": \"#/$defs/prop_ExternalIdentifier_externalIdentifierType\"\n                      },\n                      \"identifier\": {\n                          \"$ref\": \"#/$defs/prop_ExternalIdentifier_identifier\"\n                      },\n                      \"identifierLocator\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ExternalIdentifier_identifierLocator\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"issuingAuthority\": {\n                          \"$ref\": \"#/$defs/prop_ExternalIdentifier_issuingAuthority\"\n                      }\n                  },\n                  \"required\": [\n                      \"externalIdentifierType\",\n                      \"identifier\"\n                  ]\n              }\n          ]\n      },\n      \"prop_ExternalIdentifier_comment\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ExternalIdentifier_externalIdentifierType\": {\n              \"enum\": [\n                  \"cpe22\",\n                  \"cpe23\",\n                  \"cve\",\n                  \"email\",\n                  \"gitoid\",\n                  \"other\",\n                  \"packageUrl\",\n                  \"securityOther\",\n                  \"swhid\",\n                  \"swid\",\n                  \"urlScheme\"\n              ]\n      },\n      \"prop_ExternalIdentifier_identifier\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ExternalIdentifier_identifierLocator\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_ExternalIdentifier_issuingAuthority\": {\n                  \"type\": \"string\"\n      },\n      \"ExternalIdentifierType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ExternalIdentifierType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ExternalIdentifierType_props\" }\n          ]\n      },\n      \"ExternalIdentifierType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ExternalIdentifierType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/cpe22\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/cpe23\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/cve\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/email\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/gitoid\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/other\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/packageUrl\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/securityOther\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/swhid\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/swid\" },\n              { \"const\": \"spdx:Core/ExternalIdentifierType/urlScheme\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ExternalIdentifierType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"ExternalMap\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ExternalMap\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ExternalMap_props\" }\n          ]\n      },\n      \"ExternalMap_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ExternalMap\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ExternalMap_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"definingArtifact\": {\n                          \"$ref\": \"#/$defs/prop_ExternalMap_definingArtifact\"\n                      },\n                      \"externalSpdxId\": {\n                          \"$ref\": \"#/$defs/prop_ExternalMap_externalSpdxId\"\n                      },\n                      \"locationHint\": {\n                          \"$ref\": \"#/$defs/prop_ExternalMap_locationHint\"\n                      },\n                      \"verifiedUsing\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ExternalMap_verifiedUsing\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"externalSpdxId\"\n                  ]\n              }\n          ]\n      },\n      \"prop_ExternalMap_definingArtifact\": {\n              \"$ref\": \"#/$defs/Artifact_derived\"\n      },\n      \"prop_ExternalMap_externalSpdxId\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_ExternalMap_locationHint\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_ExternalMap_verifiedUsing\": {\n              \"$ref\": \"#/$defs/IntegrityMethod_derived\"\n      },\n      \"ExternalRef\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ExternalRef\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ExternalRef_props\" }\n          ]\n      },\n      \"ExternalRef_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ExternalRef\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ExternalRef_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"comment\": {\n                          \"$ref\": \"#/$defs/prop_ExternalRef_comment\"\n                      },\n                      \"contentType\": {\n                          \"$ref\": \"#/$defs/prop_ExternalRef_contentType\"\n                      },\n                      \"externalRefType\": {\n                          \"$ref\": \"#/$defs/prop_ExternalRef_externalRefType\"\n                      },\n                      \"locator\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ExternalRef_locator\"\n                                  }\n                              }\n                          ]\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_ExternalRef_comment\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ExternalRef_contentType\": {\n                  \"pattern\": \"^[^\\\\/]+\\\\/[^\\\\/]+$\",\n                  \"type\": \"string\"\n      },\n      \"prop_ExternalRef_externalRefType\": {\n              \"enum\": [\n                  \"altDownloadLocation\",\n                  \"altWebPage\",\n                  \"binaryArtifact\",\n                  \"bower\",\n                  \"buildMeta\",\n                  \"buildSystem\",\n                  \"certificationReport\",\n                  \"chat\",\n                  \"componentAnalysisReport\",\n                  \"cwe\",\n                  \"documentation\",\n                  \"dynamicAnalysisReport\",\n                  \"eolNotice\",\n                  \"exportControlAssessment\",\n                  \"funding\",\n                  \"issueTracker\",\n                  \"license\",\n                  \"mailingList\",\n                  \"mavenCentral\",\n                  \"metrics\",\n                  \"npm\",\n                  \"nuget\",\n                  \"other\",\n                  \"privacyAssessment\",\n                  \"productMetadata\",\n                  \"purchaseOrder\",\n                  \"qualityAssessmentReport\",\n                  \"releaseHistory\",\n                  \"releaseNotes\",\n                  \"riskAssessment\",\n                  \"runtimeAnalysisReport\",\n                  \"secureSoftwareAttestation\",\n                  \"securityAdversaryModel\",\n                  \"securityAdvisory\",\n                  \"securityFix\",\n                  \"securityOther\",\n                  \"securityPenTestReport\",\n                  \"securityPolicy\",\n                  \"securityThreatModel\",\n                  \"socialMedia\",\n                  \"sourceArtifact\",\n                  \"staticAnalysisReport\",\n                  \"support\",\n                  \"vcs\",\n                  \"vulnerabilityDisclosureReport\",\n                  \"vulnerabilityExploitabilityAssessment\"\n              ]\n      },\n      \"prop_ExternalRef_locator\": {\n                  \"type\": \"string\"\n      },\n      \"ExternalRefType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ExternalRefType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ExternalRefType_props\" }\n          ]\n      },\n      \"ExternalRefType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ExternalRefType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/ExternalRefType/altDownloadLocation\" },\n              { \"const\": \"spdx:Core/ExternalRefType/altWebPage\" },\n              { \"const\": \"spdx:Core/ExternalRefType/binaryArtifact\" },\n              { \"const\": \"spdx:Core/ExternalRefType/bower\" },\n              { \"const\": \"spdx:Core/ExternalRefType/buildMeta\" },\n              { \"const\": \"spdx:Core/ExternalRefType/buildSystem\" },\n              { \"const\": \"spdx:Core/ExternalRefType/certificationReport\" },\n              { \"const\": \"spdx:Core/ExternalRefType/chat\" },\n              { \"const\": \"spdx:Core/ExternalRefType/componentAnalysisReport\" },\n              { \"const\": \"spdx:Core/ExternalRefType/cwe\" },\n              { \"const\": \"spdx:Core/ExternalRefType/documentation\" },\n              { \"const\": \"spdx:Core/ExternalRefType/dynamicAnalysisReport\" },\n              { \"const\": \"spdx:Core/ExternalRefType/eolNotice\" },\n              { \"const\": \"spdx:Core/ExternalRefType/exportControlAssessment\" },\n              { \"const\": \"spdx:Core/ExternalRefType/funding\" },\n              { \"const\": \"spdx:Core/ExternalRefType/issueTracker\" },\n              { \"const\": \"spdx:Core/ExternalRefType/license\" },\n              { \"const\": \"spdx:Core/ExternalRefType/mailingList\" },\n              { \"const\": \"spdx:Core/ExternalRefType/mavenCentral\" },\n              { \"const\": \"spdx:Core/ExternalRefType/metrics\" },\n              { \"const\": \"spdx:Core/ExternalRefType/npm\" },\n              { \"const\": \"spdx:Core/ExternalRefType/nuget\" },\n              { \"const\": \"spdx:Core/ExternalRefType/other\" },\n              { \"const\": \"spdx:Core/ExternalRefType/privacyAssessment\" },\n              { \"const\": \"spdx:Core/ExternalRefType/productMetadata\" },\n              { \"const\": \"spdx:Core/ExternalRefType/purchaseOrder\" },\n              { \"const\": \"spdx:Core/ExternalRefType/qualityAssessmentReport\" },\n              { \"const\": \"spdx:Core/ExternalRefType/releaseHistory\" },\n              { \"const\": \"spdx:Core/ExternalRefType/releaseNotes\" },\n              { \"const\": \"spdx:Core/ExternalRefType/riskAssessment\" },\n              { \"const\": \"spdx:Core/ExternalRefType/runtimeAnalysisReport\" },\n              { \"const\": \"spdx:Core/ExternalRefType/secureSoftwareAttestation\" },\n              { \"const\": \"spdx:Core/ExternalRefType/securityAdversaryModel\" },\n              { \"const\": \"spdx:Core/ExternalRefType/securityAdvisory\" },\n              { \"const\": \"spdx:Core/ExternalRefType/securityFix\" },\n              { \"const\": \"spdx:Core/ExternalRefType/securityOther\" },\n              { \"const\": \"spdx:Core/ExternalRefType/securityPenTestReport\" },\n              { \"const\": \"spdx:Core/ExternalRefType/securityPolicy\" },\n              { \"const\": \"spdx:Core/ExternalRefType/securityThreatModel\" },\n              { \"const\": \"spdx:Core/ExternalRefType/socialMedia\" },\n              { \"const\": \"spdx:Core/ExternalRefType/sourceArtifact\" },\n              { \"const\": \"spdx:Core/ExternalRefType/staticAnalysisReport\" },\n              { \"const\": \"spdx:Core/ExternalRefType/support\" },\n              { \"const\": \"spdx:Core/ExternalRefType/vcs\" },\n              { \"const\": \"spdx:Core/ExternalRefType/vulnerabilityDisclosureReport\" },\n              { \"const\": \"spdx:Core/ExternalRefType/vulnerabilityExploitabilityAssessment\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ExternalRefType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"HashAlgorithm\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"HashAlgorithm\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/HashAlgorithm_props\" }\n          ]\n      },\n      \"HashAlgorithm_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/HashAlgorithm\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/HashAlgorithm/adler32\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/blake2b256\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/blake2b384\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/blake2b512\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/blake3\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/crystalsDilithium\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/crystalsKyber\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/falcon\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/md2\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/md4\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/md5\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/md6\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/other\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha1\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha224\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha256\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha384\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha3_224\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha3_256\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha3_384\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha3_512\" },\n              { \"const\": \"spdx:Core/HashAlgorithm/sha512\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"HashAlgorithm_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"IndividualElement\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"IndividualElement\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/IndividualElement_props\" }\n          ]\n      },\n      \"IndividualElement_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/IndividualElement\" }\n                  ]\n              },\n              { \"const\": \"NoAssertionElement\" },\n              { \"const\": \"NoneElement\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"IndividualElement_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"IntegrityMethod_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Hash\" },\n                      { \"$ref\": \"#/$defs/PackageVerificationCode\" },\n                      { \"$ref\": \"#/$defs/software_ContentIdentifier\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"IntegrityMethod_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"comment\": {\n                          \"$ref\": \"#/$defs/prop_IntegrityMethod_comment\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_IntegrityMethod_comment\": {\n                  \"type\": \"string\"\n      },\n      \"LifecycleScopeType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"LifecycleScopeType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/LifecycleScopeType_props\" }\n          ]\n      },\n      \"LifecycleScopeType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/LifecycleScopeType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/LifecycleScopeType/build\" },\n              { \"const\": \"spdx:Core/LifecycleScopeType/design\" },\n              { \"const\": \"spdx:Core/LifecycleScopeType/development\" },\n              { \"const\": \"spdx:Core/LifecycleScopeType/other\" },\n              { \"const\": \"spdx:Core/LifecycleScopeType/runtime\" },\n              { \"const\": \"spdx:Core/LifecycleScopeType/test\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"LifecycleScopeType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"NamespaceMap\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"NamespaceMap\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/NamespaceMap_props\" }\n          ]\n      },\n      \"NamespaceMap_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/NamespaceMap\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"NamespaceMap_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"namespace\": {\n                          \"$ref\": \"#/$defs/prop_NamespaceMap_namespace\"\n                      },\n                      \"prefix\": {\n                          \"$ref\": \"#/$defs/prop_NamespaceMap_prefix\"\n                      }\n                  },\n                  \"required\": [\n                      \"namespace\",\n                      \"prefix\"\n                  ]\n              }\n          ]\n      },\n      \"prop_NamespaceMap_namespace\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_NamespaceMap_prefix\": {\n                  \"type\": \"string\"\n      },\n      \"PackageVerificationCode\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"PackageVerificationCode\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/PackageVerificationCode_props\" }\n          ]\n      },\n      \"PackageVerificationCode_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/PackageVerificationCode\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"PackageVerificationCode_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/IntegrityMethod_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"algorithm\": {\n                          \"$ref\": \"#/$defs/prop_PackageVerificationCode_algorithm\"\n                      },\n                      \"hashValue\": {\n                          \"$ref\": \"#/$defs/prop_PackageVerificationCode_hashValue\"\n                      },\n                      \"packageVerificationCodeExcludedFile\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_PackageVerificationCode_packageVerificationCodeExcludedFile\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"algorithm\",\n                      \"hashValue\"\n                  ]\n              }\n          ]\n      },\n      \"prop_PackageVerificationCode_algorithm\": {\n              \"enum\": [\n                  \"adler32\",\n                  \"blake2b256\",\n                  \"blake2b384\",\n                  \"blake2b512\",\n                  \"blake3\",\n                  \"crystalsDilithium\",\n                  \"crystalsKyber\",\n                  \"falcon\",\n                  \"md2\",\n                  \"md4\",\n                  \"md5\",\n                  \"md6\",\n                  \"other\",\n                  \"sha1\",\n                  \"sha224\",\n                  \"sha256\",\n                  \"sha384\",\n                  \"sha3_224\",\n                  \"sha3_256\",\n                  \"sha3_384\",\n                  \"sha3_512\",\n                  \"sha512\"\n              ]\n      },\n      \"prop_PackageVerificationCode_hashValue\": {\n                  \"type\": \"string\"\n      },\n      \"prop_PackageVerificationCode_packageVerificationCodeExcludedFile\": {\n                  \"type\": \"string\"\n      },\n      \"PositiveIntegerRange\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"PositiveIntegerRange\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/PositiveIntegerRange_props\" }\n          ]\n      },\n      \"PositiveIntegerRange_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/PositiveIntegerRange\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"PositiveIntegerRange_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"beginIntegerRange\": {\n                          \"$ref\": \"#/$defs/prop_PositiveIntegerRange_beginIntegerRange\"\n                      },\n                      \"endIntegerRange\": {\n                          \"$ref\": \"#/$defs/prop_PositiveIntegerRange_endIntegerRange\"\n                      }\n                  },\n                  \"required\": [\n                      \"beginIntegerRange\",\n                      \"endIntegerRange\"\n                  ]\n              }\n          ]\n      },\n      \"prop_PositiveIntegerRange_beginIntegerRange\": {\n                  \"type\": \"integer\",\n                  \"minimum\": 1\n      },\n      \"prop_PositiveIntegerRange_endIntegerRange\": {\n                  \"type\": \"integer\",\n                  \"minimum\": 1\n      },\n      \"PresenceType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"PresenceType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/PresenceType_props\" }\n          ]\n      },\n      \"PresenceType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/PresenceType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/PresenceType/no\" },\n              { \"const\": \"spdx:Core/PresenceType/noAssertion\" },\n              { \"const\": \"spdx:Core/PresenceType/yes\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"PresenceType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"ProfileIdentifierType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ProfileIdentifierType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/ProfileIdentifierType_props\" }\n          ]\n      },\n      \"ProfileIdentifierType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ProfileIdentifierType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/ai\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/build\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/core\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/dataset\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/expandedLicensing\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/extension\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/lite\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/security\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/simpleLicensing\" },\n              { \"const\": \"spdx:Core/ProfileIdentifierType/software\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ProfileIdentifierType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"Relationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Relationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/Relationship_props\" }\n          ]\n      },\n      \"Relationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/LifecycleScopedRelationship\" },\n                      { \"$ref\": \"#/$defs/security_CvssV2VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_CvssV3VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_CvssV4VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_EpssVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_ExploitCatalogVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_SsvcVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexAffectedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexFixedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexNotAffectedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexUnderInvestigationVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/Relationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Relationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"completeness\": {\n                          \"$ref\": \"#/$defs/prop_Relationship_completeness\"\n                      },\n                      \"endTime\": {\n                          \"$ref\": \"#/$defs/prop_Relationship_endTime\"\n                      },\n                      \"from\": {\n                          \"$ref\": \"#/$defs/prop_Relationship_from_\"\n                      },\n                      \"relationshipType\": {\n                          \"$ref\": \"#/$defs/prop_Relationship_relationshipType\"\n                      },\n                      \"startTime\": {\n                          \"$ref\": \"#/$defs/prop_Relationship_startTime\"\n                      },\n                      \"to\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"minItems\": 1,\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_Relationship_to\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"from\",\n                      \"relationshipType\",\n                      \"to\"\n                  ]\n              }\n          ]\n      },\n      \"prop_Relationship_completeness\": {\n              \"enum\": [\n                  \"complete\",\n                  \"incomplete\",\n                  \"noAssertion\"\n              ]\n      },\n      \"prop_Relationship_endTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_Relationship_from_\": {\n              \"$ref\": \"#/$defs/Element_derived\"\n      },\n      \"prop_Relationship_relationshipType\": {\n              \"enum\": [\n                  \"affects\",\n                  \"amendedBy\",\n                  \"ancestorOf\",\n                  \"availableFrom\",\n                  \"configures\",\n                  \"contains\",\n                  \"coordinatedBy\",\n                  \"copiedTo\",\n                  \"delegatedTo\",\n                  \"dependsOn\",\n                  \"descendantOf\",\n                  \"describes\",\n                  \"doesNotAffect\",\n                  \"expandsTo\",\n                  \"exploitCreatedBy\",\n                  \"fixedBy\",\n                  \"fixedIn\",\n                  \"foundBy\",\n                  \"generates\",\n                  \"hasAddedFile\",\n                  \"hasAssessmentFor\",\n                  \"hasAssociatedVulnerability\",\n                  \"hasConcludedLicense\",\n                  \"hasDataFile\",\n                  \"hasDeclaredLicense\",\n                  \"hasDeletedFile\",\n                  \"hasDependencyManifest\",\n                  \"hasDistributionArtifact\",\n                  \"hasDocumentation\",\n                  \"hasDynamicLink\",\n                  \"hasEvidence\",\n                  \"hasExample\",\n                  \"hasHost\",\n                  \"hasInput\",\n                  \"hasMetadata\",\n                  \"hasOptionalComponent\",\n                  \"hasOptionalDependency\",\n                  \"hasOutput\",\n                  \"hasPrerequisite\",\n                  \"hasProvidedDependency\",\n                  \"hasRequirement\",\n                  \"hasSpecification\",\n                  \"hasStaticLink\",\n                  \"hasTest\",\n                  \"hasTestCase\",\n                  \"hasVariant\",\n                  \"invokedBy\",\n                  \"modifiedBy\",\n                  \"other\",\n                  \"packagedBy\",\n                  \"patchedBy\",\n                  \"publishedBy\",\n                  \"reportedBy\",\n                  \"republishedBy\",\n                  \"serializedInArtifact\",\n                  \"testedOn\",\n                  \"trainedOn\",\n                  \"underInvestigationFor\",\n                  \"usesTool\"\n              ]\n      },\n      \"prop_Relationship_startTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_Relationship_to\": {\n              \"$ref\": \"#/$defs/Element_derived\"\n      },\n      \"RelationshipCompleteness\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"RelationshipCompleteness\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/RelationshipCompleteness_props\" }\n          ]\n      },\n      \"RelationshipCompleteness_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/RelationshipCompleteness\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/RelationshipCompleteness/complete\" },\n              { \"const\": \"spdx:Core/RelationshipCompleteness/incomplete\" },\n              { \"const\": \"spdx:Core/RelationshipCompleteness/noAssertion\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"RelationshipCompleteness_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"RelationshipType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"RelationshipType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/RelationshipType_props\" }\n          ]\n      },\n      \"RelationshipType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/RelationshipType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/RelationshipType/affects\" },\n              { \"const\": \"spdx:Core/RelationshipType/amendedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/ancestorOf\" },\n              { \"const\": \"spdx:Core/RelationshipType/availableFrom\" },\n              { \"const\": \"spdx:Core/RelationshipType/configures\" },\n              { \"const\": \"spdx:Core/RelationshipType/contains\" },\n              { \"const\": \"spdx:Core/RelationshipType/coordinatedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/copiedTo\" },\n              { \"const\": \"spdx:Core/RelationshipType/delegatedTo\" },\n              { \"const\": \"spdx:Core/RelationshipType/dependsOn\" },\n              { \"const\": \"spdx:Core/RelationshipType/descendantOf\" },\n              { \"const\": \"spdx:Core/RelationshipType/describes\" },\n              { \"const\": \"spdx:Core/RelationshipType/doesNotAffect\" },\n              { \"const\": \"spdx:Core/RelationshipType/expandsTo\" },\n              { \"const\": \"spdx:Core/RelationshipType/exploitCreatedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/fixedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/fixedIn\" },\n              { \"const\": \"spdx:Core/RelationshipType/foundBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/generates\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasAddedFile\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasAssessmentFor\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasAssociatedVulnerability\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasConcludedLicense\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasDataFile\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasDeclaredLicense\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasDeletedFile\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasDependencyManifest\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasDistributionArtifact\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasDocumentation\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasDynamicLink\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasEvidence\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasExample\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasHost\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasInput\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasMetadata\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasOptionalComponent\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasOptionalDependency\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasOutput\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasPrerequisite\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasProvidedDependency\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasRequirement\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasSpecification\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasStaticLink\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasTest\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasTestCase\" },\n              { \"const\": \"spdx:Core/RelationshipType/hasVariant\" },\n              { \"const\": \"spdx:Core/RelationshipType/invokedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/modifiedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/other\" },\n              { \"const\": \"spdx:Core/RelationshipType/packagedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/patchedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/publishedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/reportedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/republishedBy\" },\n              { \"const\": \"spdx:Core/RelationshipType/serializedInArtifact\" },\n              { \"const\": \"spdx:Core/RelationshipType/testedOn\" },\n              { \"const\": \"spdx:Core/RelationshipType/trainedOn\" },\n              { \"const\": \"spdx:Core/RelationshipType/underInvestigationFor\" },\n              { \"const\": \"spdx:Core/RelationshipType/usesTool\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"RelationshipType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"SpdxDocument\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"SpdxDocument\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/SpdxDocument_props\" }\n          ]\n      },\n      \"SpdxDocument_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/SpdxDocument\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"SpdxDocument_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/ElementCollection_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"dataLicense\": {\n                          \"$ref\": \"#/$defs/prop_SpdxDocument_dataLicense\"\n                      },\n                      \"import\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_SpdxDocument_import_\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"namespaceMap\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_SpdxDocument_namespaceMap\"\n                                  }\n                              }\n                          ]\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_SpdxDocument_dataLicense\": {\n              \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_derived\"\n      },\n      \"prop_SpdxDocument_import_\": {\n              \"$ref\": \"#/$defs/ExternalMap_derived\"\n      },\n      \"prop_SpdxDocument_namespaceMap\": {\n              \"$ref\": \"#/$defs/NamespaceMap_derived\"\n      },\n      \"SupportType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"SupportType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/SupportType_props\" }\n          ]\n      },\n      \"SupportType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/SupportType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Core/SupportType/deployed\" },\n              { \"const\": \"spdx:Core/SupportType/development\" },\n              { \"const\": \"spdx:Core/SupportType/endOfSupport\" },\n              { \"const\": \"spdx:Core/SupportType/limitedSupport\" },\n              { \"const\": \"spdx:Core/SupportType/noAssertion\" },\n              { \"const\": \"spdx:Core/SupportType/noSupport\" },\n              { \"const\": \"spdx:Core/SupportType/support\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"SupportType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"Tool\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Tool\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/Tool_props\" }\n          ]\n      },\n      \"Tool_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Tool\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Tool_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"dataset_ConfidentialityLevelType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"dataset_ConfidentialityLevelType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/dataset_ConfidentialityLevelType_props\" }\n          ]\n      },\n      \"dataset_ConfidentialityLevelType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/dataset_ConfidentialityLevelType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Dataset/ConfidentialityLevelType/amber\" },\n              { \"const\": \"spdx:Dataset/ConfidentialityLevelType/clear\" },\n              { \"const\": \"spdx:Dataset/ConfidentialityLevelType/green\" },\n              { \"const\": \"spdx:Dataset/ConfidentialityLevelType/red\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"dataset_ConfidentialityLevelType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"dataset_DatasetAvailabilityType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"dataset_DatasetAvailabilityType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/dataset_DatasetAvailabilityType_props\" }\n          ]\n      },\n      \"dataset_DatasetAvailabilityType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/dataset_DatasetAvailabilityType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Dataset/DatasetAvailabilityType/clickthrough\" },\n              { \"const\": \"spdx:Dataset/DatasetAvailabilityType/directDownload\" },\n              { \"const\": \"spdx:Dataset/DatasetAvailabilityType/query\" },\n              { \"const\": \"spdx:Dataset/DatasetAvailabilityType/registration\" },\n              { \"const\": \"spdx:Dataset/DatasetAvailabilityType/scrapingScript\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"dataset_DatasetAvailabilityType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"dataset_DatasetType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"dataset_DatasetType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/dataset_DatasetType_props\" }\n          ]\n      },\n      \"dataset_DatasetType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/dataset_DatasetType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Dataset/DatasetType/audio\" },\n              { \"const\": \"spdx:Dataset/DatasetType/categorical\" },\n              { \"const\": \"spdx:Dataset/DatasetType/graph\" },\n              { \"const\": \"spdx:Dataset/DatasetType/image\" },\n              { \"const\": \"spdx:Dataset/DatasetType/noAssertion\" },\n              { \"const\": \"spdx:Dataset/DatasetType/numeric\" },\n              { \"const\": \"spdx:Dataset/DatasetType/other\" },\n              { \"const\": \"spdx:Dataset/DatasetType/sensor\" },\n              { \"const\": \"spdx:Dataset/DatasetType/structured\" },\n              { \"const\": \"spdx:Dataset/DatasetType/syntactic\" },\n              { \"const\": \"spdx:Dataset/DatasetType/text\" },\n              { \"const\": \"spdx:Dataset/DatasetType/timeseries\" },\n              { \"const\": \"spdx:Dataset/DatasetType/timestamp\" },\n              { \"const\": \"spdx:Dataset/DatasetType/video\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"dataset_DatasetType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"expandedlicensing_LicenseAddition_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_CustomLicenseAddition\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_ListedLicenseException\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_LicenseAddition_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"expandedlicensing_additionText\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_LicenseAddition_expandedlicensing_additionText\"\n                      },\n                      \"expandedlicensing_isDeprecatedAdditionId\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_LicenseAddition_expandedlicensing_isDeprecatedAdditionId\"\n                      },\n                      \"expandedlicensing_licenseXml\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_LicenseAddition_expandedlicensing_licenseXml\"\n                      },\n                      \"expandedlicensing_obsoletedBy\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_LicenseAddition_expandedlicensing_obsoletedBy\"\n                      },\n                      \"expandedlicensing_seeAlso\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_expandedlicensing_LicenseAddition_expandedlicensing_seeAlso\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"expandedlicensing_standardAdditionTemplate\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_LicenseAddition_expandedlicensing_standardAdditionTemplate\"\n                      }\n                  },\n                  \"required\": [\n                      \"expandedlicensing_additionText\"\n                  ]\n              }\n          ]\n      },\n      \"prop_expandedlicensing_LicenseAddition_expandedlicensing_additionText\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_LicenseAddition_expandedlicensing_isDeprecatedAdditionId\": {\n                  \"type\": \"boolean\"\n      },\n      \"prop_expandedlicensing_LicenseAddition_expandedlicensing_licenseXml\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_LicenseAddition_expandedlicensing_obsoletedBy\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_LicenseAddition_expandedlicensing_seeAlso\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_expandedlicensing_LicenseAddition_expandedlicensing_standardAdditionTemplate\": {\n                  \"type\": \"string\"\n      },\n      \"expandedlicensing_ListedLicenseException\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_ListedLicenseException\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_ListedLicenseException_props\" }\n          ]\n      },\n      \"expandedlicensing_ListedLicenseException_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_ListedLicenseException\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_ListedLicenseException_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/expandedlicensing_LicenseAddition_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"expandedlicensing_deprecatedVersion\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_ListedLicenseException_expandedlicensing_deprecatedVersion\"\n                      },\n                      \"expandedlicensing_listVersionAdded\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_ListedLicenseException_expandedlicensing_listVersionAdded\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_expandedlicensing_ListedLicenseException_expandedlicensing_deprecatedVersion\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_ListedLicenseException_expandedlicensing_listVersionAdded\": {\n                  \"type\": \"string\"\n      },\n      \"extension_CdxPropertyEntry\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"extension_CdxPropertyEntry\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/extension_CdxPropertyEntry_props\" }\n          ]\n      },\n      \"extension_CdxPropertyEntry_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/extension_CdxPropertyEntry\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"extension_CdxPropertyEntry_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"extension_cdxPropName\": {\n                          \"$ref\": \"#/$defs/prop_extension_CdxPropertyEntry_extension_cdxPropName\"\n                      },\n                      \"extension_cdxPropValue\": {\n                          \"$ref\": \"#/$defs/prop_extension_CdxPropertyEntry_extension_cdxPropValue\"\n                      }\n                  },\n                  \"required\": [\n                      \"extension_cdxPropName\"\n                  ]\n              }\n          ]\n      },\n      \"prop_extension_CdxPropertyEntry_extension_cdxPropName\": {\n                  \"type\": \"string\"\n      },\n      \"prop_extension_CdxPropertyEntry_extension_cdxPropValue\": {\n                  \"type\": \"string\"\n      },\n      \"extension_Extension\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": true,\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"allOf\":  [\n                              { \"$ref\": \"#/$defs/IRI\" },\n                              { \"not\": { \"const\": \"extension_Extension\" } }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/extension_Extension_props\" }\n          ]\n      },\n      \"extension_Extension_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/extension_CdxPropertiesExtension\" },\n                      { \"$ref\": \"#/$defs/extension_Extension_props\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"extension_Extension_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"security_CvssSeverityType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_CvssSeverityType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/security_CvssSeverityType_props\" }\n          ]\n      },\n      \"security_CvssSeverityType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_CvssSeverityType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Security/CvssSeverityType/critical\" },\n              { \"const\": \"spdx:Security/CvssSeverityType/high\" },\n              { \"const\": \"spdx:Security/CvssSeverityType/low\" },\n              { \"const\": \"spdx:Security/CvssSeverityType/medium\" },\n              { \"const\": \"spdx:Security/CvssSeverityType/none\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_CvssSeverityType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"security_ExploitCatalogType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_ExploitCatalogType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/security_ExploitCatalogType_props\" }\n          ]\n      },\n      \"security_ExploitCatalogType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_ExploitCatalogType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Security/ExploitCatalogType/kev\" },\n              { \"const\": \"spdx:Security/ExploitCatalogType/other\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_ExploitCatalogType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"security_SsvcDecisionType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_SsvcDecisionType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/security_SsvcDecisionType_props\" }\n          ]\n      },\n      \"security_SsvcDecisionType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_SsvcDecisionType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Security/SsvcDecisionType/act\" },\n              { \"const\": \"spdx:Security/SsvcDecisionType/attend\" },\n              { \"const\": \"spdx:Security/SsvcDecisionType/track\" },\n              { \"const\": \"spdx:Security/SsvcDecisionType/trackStar\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_SsvcDecisionType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"security_VexJustificationType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_VexJustificationType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/security_VexJustificationType_props\" }\n          ]\n      },\n      \"security_VexJustificationType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_VexJustificationType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Security/VexJustificationType/componentNotPresent\" },\n              { \"const\": \"spdx:Security/VexJustificationType/inlineMitigationsAlreadyExist\" },\n              { \"const\": \"spdx:Security/VexJustificationType/vulnerableCodeCannotBeControlledByAdversary\" },\n              { \"const\": \"spdx:Security/VexJustificationType/vulnerableCodeNotInExecutePath\" },\n              { \"const\": \"spdx:Security/VexJustificationType/vulnerableCodeNotPresent\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_VexJustificationType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"security_VulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_CvssV2VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_CvssV3VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_CvssV4VulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_EpssVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_ExploitCatalogVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_SsvcVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexAffectedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexFixedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexNotAffectedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexUnderInvestigationVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_VulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Relationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"suppliedBy\": {\n                          \"$ref\": \"#/$defs/prop_security_VulnAssessmentRelationship_suppliedBy\"\n                      },\n                      \"security_assessedElement\": {\n                          \"$ref\": \"#/$defs/prop_security_VulnAssessmentRelationship_security_assessedElement\"\n                      },\n                      \"security_modifiedTime\": {\n                          \"$ref\": \"#/$defs/prop_security_VulnAssessmentRelationship_security_modifiedTime\"\n                      },\n                      \"security_publishedTime\": {\n                          \"$ref\": \"#/$defs/prop_security_VulnAssessmentRelationship_security_publishedTime\"\n                      },\n                      \"security_withdrawnTime\": {\n                          \"$ref\": \"#/$defs/prop_security_VulnAssessmentRelationship_security_withdrawnTime\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_security_VulnAssessmentRelationship_suppliedBy\": {\n              \"$ref\": \"#/$defs/Agent_derived\"\n      },\n      \"prop_security_VulnAssessmentRelationship_security_assessedElement\": {\n              \"$ref\": \"#/$defs/software_SoftwareArtifact_derived\"\n      },\n      \"prop_security_VulnAssessmentRelationship_security_modifiedTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_security_VulnAssessmentRelationship_security_publishedTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_security_VulnAssessmentRelationship_security_withdrawnTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"simplelicensing_AnyLicenseInfo_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_ConjunctiveLicenseSet\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_CustomLicense\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_DisjunctiveLicenseSet\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_IndividualLicensingInfo\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_ListedLicense\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_OrLaterOperator\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_WithAdditionOperator\" },\n                      { \"$ref\": \"#/$defs/simplelicensing_LicenseExpression\" }\n                  ]\n              },\n              { \"const\": \"expandedlicensing_NoAssertionLicense\" },\n              { \"const\": \"expandedlicensing_NoneLicense\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"simplelicensing_AnyLicenseInfo_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"simplelicensing_LicenseExpression\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"simplelicensing_LicenseExpression\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/simplelicensing_LicenseExpression_props\" }\n          ]\n      },\n      \"simplelicensing_LicenseExpression_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/simplelicensing_LicenseExpression\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"simplelicensing_LicenseExpression_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"simplelicensing_customIdToUri\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_simplelicensing_LicenseExpression_simplelicensing_customIdToUri\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"simplelicensing_licenseExpression\": {\n                          \"$ref\": \"#/$defs/prop_simplelicensing_LicenseExpression_simplelicensing_licenseExpression\"\n                      },\n                      \"simplelicensing_licenseListVersion\": {\n                          \"$ref\": \"#/$defs/prop_simplelicensing_LicenseExpression_simplelicensing_licenseListVersion\"\n                      }\n                  },\n                  \"required\": [\n                      \"simplelicensing_licenseExpression\"\n                  ]\n              }\n          ]\n      },\n      \"prop_simplelicensing_LicenseExpression_simplelicensing_customIdToUri\": {\n              \"$ref\": \"#/$defs/DictionaryEntry_derived\"\n      },\n      \"prop_simplelicensing_LicenseExpression_simplelicensing_licenseExpression\": {\n                  \"type\": \"string\"\n      },\n      \"prop_simplelicensing_LicenseExpression_simplelicensing_licenseListVersion\": {\n                  \"pattern\": \"^(0|[1-9]\\\\d*)\\\\.(0|[1-9]\\\\d*)\\\\.(0|[1-9]\\\\d*)(?:-((?:0|[1-9]\\\\d*|\\\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\\\.(?:0|[1-9]\\\\d*|\\\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\\\+([0-9a-zA-Z-]+(?:\\\\.[0-9a-zA-Z-]+)*))?$\",\n                  \"type\": \"string\"\n      },\n      \"simplelicensing_SimpleLicensingText\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"simplelicensing_SimpleLicensingText\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/simplelicensing_SimpleLicensingText_props\" }\n          ]\n      },\n      \"simplelicensing_SimpleLicensingText_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/simplelicensing_SimpleLicensingText\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"simplelicensing_SimpleLicensingText_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"simplelicensing_licenseText\": {\n                          \"$ref\": \"#/$defs/prop_simplelicensing_SimpleLicensingText_simplelicensing_licenseText\"\n                      }\n                  },\n                  \"required\": [\n                      \"simplelicensing_licenseText\"\n                  ]\n              }\n          ]\n      },\n      \"prop_simplelicensing_SimpleLicensingText_simplelicensing_licenseText\": {\n                  \"type\": \"string\"\n      },\n      \"software_ContentIdentifier\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_ContentIdentifier\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/software_ContentIdentifier_props\" }\n          ]\n      },\n      \"software_ContentIdentifier_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_ContentIdentifier\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_ContentIdentifier_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/IntegrityMethod_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"software_contentIdentifierType\": {\n                          \"$ref\": \"#/$defs/prop_software_ContentIdentifier_software_contentIdentifierType\"\n                      },\n                      \"software_contentIdentifierValue\": {\n                          \"$ref\": \"#/$defs/prop_software_ContentIdentifier_software_contentIdentifierValue\"\n                      }\n                  },\n                  \"required\": [\n                      \"software_contentIdentifierType\",\n                      \"software_contentIdentifierValue\"\n                  ]\n              }\n          ]\n      },\n      \"prop_software_ContentIdentifier_software_contentIdentifierType\": {\n              \"enum\": [\n                  \"gitoid\",\n                  \"swhid\"\n              ]\n      },\n      \"prop_software_ContentIdentifier_software_contentIdentifierValue\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"software_ContentIdentifierType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_ContentIdentifierType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/software_ContentIdentifierType_props\" }\n          ]\n      },\n      \"software_ContentIdentifierType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_ContentIdentifierType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Software/ContentIdentifierType/gitoid\" },\n              { \"const\": \"spdx:Software/ContentIdentifierType/swhid\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_ContentIdentifierType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"software_FileKindType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_FileKindType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/software_FileKindType_props\" }\n          ]\n      },\n      \"software_FileKindType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_FileKindType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Software/FileKindType/directory\" },\n              { \"const\": \"spdx:Software/FileKindType/file\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_FileKindType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"software_SbomType\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_SbomType\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/software_SbomType_props\" }\n          ]\n      },\n      \"software_SbomType_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_SbomType\" }\n                  ]\n              },\n              { \"const\": \"spdx:Software/SbomType/analyzed\" },\n              { \"const\": \"spdx:Software/SbomType/build\" },\n              { \"const\": \"spdx:Software/SbomType/deployed\" },\n              { \"const\": \"spdx:Software/SbomType/design\" },\n              { \"const\": \"spdx:Software/SbomType/runtime\" },\n              { \"const\": \"spdx:Software/SbomType/source\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_SbomType_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"software_SoftwarePurpose\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_SoftwarePurpose\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/software_SoftwarePurpose_props\" }\n          ]\n      },\n      \"software_SoftwarePurpose_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_SoftwarePurpose\" }\n                  ]\n              },\n              { \"const\": \"spdx:Software/SoftwarePurpose/application\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/archive\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/bom\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/configuration\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/container\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/data\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/device\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/deviceDriver\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/diskImage\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/documentation\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/evidence\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/executable\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/file\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/filesystemImage\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/firmware\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/framework\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/install\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/library\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/manifest\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/model\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/module\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/operatingSystem\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/other\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/patch\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/platform\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/requirement\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/source\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/specification\" },\n              { \"const\": \"spdx:Software/SoftwarePurpose/test\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_SoftwarePurpose_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/SHACLClass\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"build_Build\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"build_Build\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/build_Build_props\" }\n          ]\n      },\n      \"build_Build_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/build_Build\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"build_Build_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"build_buildEndTime\": {\n                          \"$ref\": \"#/$defs/prop_build_Build_build_buildEndTime\"\n                      },\n                      \"build_buildId\": {\n                          \"$ref\": \"#/$defs/prop_build_Build_build_buildId\"\n                      },\n                      \"build_buildStartTime\": {\n                          \"$ref\": \"#/$defs/prop_build_Build_build_buildStartTime\"\n                      },\n                      \"build_buildType\": {\n                          \"$ref\": \"#/$defs/prop_build_Build_build_buildType\"\n                      },\n                      \"build_configSourceDigest\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_build_Build_build_configSourceDigest\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"build_configSourceEntrypoint\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_build_Build_build_configSourceEntrypoint\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"build_configSourceUri\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_build_Build_build_configSourceUri\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"build_environment\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_build_Build_build_environment\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"build_parameter\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_build_Build_build_parameter\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"build_buildType\"\n                  ]\n              }\n          ]\n      },\n      \"prop_build_Build_build_buildEndTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_build_Build_build_buildId\": {\n                  \"type\": \"string\"\n      },\n      \"prop_build_Build_build_buildStartTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_build_Build_build_buildType\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_build_Build_build_configSourceDigest\": {\n              \"$ref\": \"#/$defs/Hash_derived\"\n      },\n      \"prop_build_Build_build_configSourceEntrypoint\": {\n                  \"type\": \"string\"\n      },\n      \"prop_build_Build_build_configSourceUri\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_build_Build_build_environment\": {\n              \"$ref\": \"#/$defs/DictionaryEntry_derived\"\n      },\n      \"prop_build_Build_build_parameter\": {\n              \"$ref\": \"#/$defs/DictionaryEntry_derived\"\n      },\n      \"Agent\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Agent\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/Agent_props\" }\n          ]\n      },\n      \"Agent_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Organization\" },\n                      { \"$ref\": \"#/$defs/Person\" },\n                      { \"$ref\": \"#/$defs/SoftwareAgent\" },\n                      { \"$ref\": \"#/$defs/Agent\" }\n                  ]\n              },\n              { \"const\": \"SpdxOrganization\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Agent_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"Annotation\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Annotation\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/Annotation_props\" }\n          ]\n      },\n      \"Annotation_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Annotation\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Annotation_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"annotationType\": {\n                          \"$ref\": \"#/$defs/prop_Annotation_annotationType\"\n                      },\n                      \"contentType\": {\n                          \"$ref\": \"#/$defs/prop_Annotation_contentType\"\n                      },\n                      \"statement\": {\n                          \"$ref\": \"#/$defs/prop_Annotation_statement\"\n                      },\n                      \"subject\": {\n                          \"$ref\": \"#/$defs/prop_Annotation_subject\"\n                      }\n                  },\n                  \"required\": [\n                      \"annotationType\",\n                      \"subject\"\n                  ]\n              }\n          ]\n      },\n      \"prop_Annotation_annotationType\": {\n              \"enum\": [\n                  \"other\",\n                  \"review\"\n              ]\n      },\n      \"prop_Annotation_contentType\": {\n                  \"pattern\": \"^[^\\\\/]+\\\\/[^\\\\/]+$\",\n                  \"type\": \"string\"\n      },\n      \"prop_Annotation_statement\": {\n                  \"type\": \"string\"\n      },\n      \"prop_Annotation_subject\": {\n              \"$ref\": \"#/$defs/Element_derived\"\n      },\n      \"Artifact_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_AIPackage\" },\n                      { \"$ref\": \"#/$defs/dataset_DatasetPackage\" },\n                      { \"$ref\": \"#/$defs/security_Vulnerability\" },\n                      { \"$ref\": \"#/$defs/software_File\" },\n                      { \"$ref\": \"#/$defs/software_Package\" },\n                      { \"$ref\": \"#/$defs/software_Snippet\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Artifact_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Element_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"builtTime\": {\n                          \"$ref\": \"#/$defs/prop_Artifact_builtTime\"\n                      },\n                      \"originatedBy\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_Artifact_originatedBy\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"releaseTime\": {\n                          \"$ref\": \"#/$defs/prop_Artifact_releaseTime\"\n                      },\n                      \"standardName\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_Artifact_standardName\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"suppliedBy\": {\n                          \"$ref\": \"#/$defs/prop_Artifact_suppliedBy\"\n                      },\n                      \"supportLevel\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_Artifact_supportLevel\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"validUntilTime\": {\n                          \"$ref\": \"#/$defs/prop_Artifact_validUntilTime\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_Artifact_builtTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_Artifact_originatedBy\": {\n              \"$ref\": \"#/$defs/Agent_derived\"\n      },\n      \"prop_Artifact_releaseTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_Artifact_standardName\": {\n                  \"type\": \"string\"\n      },\n      \"prop_Artifact_suppliedBy\": {\n              \"$ref\": \"#/$defs/Agent_derived\"\n      },\n      \"prop_Artifact_supportLevel\": {\n              \"enum\": [\n                  \"deployed\",\n                  \"development\",\n                  \"endOfSupport\",\n                  \"limitedSupport\",\n                  \"noAssertion\",\n                  \"noSupport\",\n                  \"support\"\n              ]\n      },\n      \"prop_Artifact_validUntilTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"Bundle\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Bundle\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/Bundle_props\" }\n          ]\n      },\n      \"Bundle_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Bom\" },\n                      { \"$ref\": \"#/$defs/software_Sbom\" },\n                      { \"$ref\": \"#/$defs/Bundle\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Bundle_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/ElementCollection_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"context\": {\n                          \"$ref\": \"#/$defs/prop_Bundle_context\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_Bundle_context\": {\n                  \"type\": \"string\"\n      },\n      \"Hash\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Hash\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/Hash_props\" }\n          ]\n      },\n      \"Hash_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Hash\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Hash_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/IntegrityMethod_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"algorithm\": {\n                          \"$ref\": \"#/$defs/prop_Hash_algorithm\"\n                      },\n                      \"hashValue\": {\n                          \"$ref\": \"#/$defs/prop_Hash_hashValue\"\n                      }\n                  },\n                  \"required\": [\n                      \"algorithm\",\n                      \"hashValue\"\n                  ]\n              }\n          ]\n      },\n      \"prop_Hash_algorithm\": {\n              \"enum\": [\n                  \"adler32\",\n                  \"blake2b256\",\n                  \"blake2b384\",\n                  \"blake2b512\",\n                  \"blake3\",\n                  \"crystalsDilithium\",\n                  \"crystalsKyber\",\n                  \"falcon\",\n                  \"md2\",\n                  \"md4\",\n                  \"md5\",\n                  \"md6\",\n                  \"other\",\n                  \"sha1\",\n                  \"sha224\",\n                  \"sha256\",\n                  \"sha384\",\n                  \"sha3_224\",\n                  \"sha3_256\",\n                  \"sha3_384\",\n                  \"sha3_512\",\n                  \"sha512\"\n              ]\n      },\n      \"prop_Hash_hashValue\": {\n                  \"type\": \"string\"\n      },\n      \"LifecycleScopedRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"LifecycleScopedRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/LifecycleScopedRelationship_props\" }\n          ]\n      },\n      \"LifecycleScopedRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/LifecycleScopedRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"LifecycleScopedRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Relationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"scope\": {\n                          \"$ref\": \"#/$defs/prop_LifecycleScopedRelationship_scope\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_LifecycleScopedRelationship_scope\": {\n              \"enum\": [\n                  \"build\",\n                  \"design\",\n                  \"development\",\n                  \"other\",\n                  \"runtime\",\n                  \"test\"\n              ]\n      },\n      \"Organization\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Organization\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/Organization_props\" }\n          ]\n      },\n      \"Organization_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Organization\" }\n                  ]\n              },\n              { \"const\": \"SpdxOrganization\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Organization_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Agent_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"Person\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Person\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/Person_props\" }\n          ]\n      },\n      \"Person_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/Person\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Person_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Agent_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"SoftwareAgent\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"SoftwareAgent\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/SoftwareAgent_props\" }\n          ]\n      },\n      \"SoftwareAgent_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/SoftwareAgent\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"SoftwareAgent_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Agent_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"expandedlicensing_ConjunctiveLicenseSet\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_ConjunctiveLicenseSet\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_ConjunctiveLicenseSet_props\" }\n          ]\n      },\n      \"expandedlicensing_ConjunctiveLicenseSet_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_ConjunctiveLicenseSet\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_ConjunctiveLicenseSet_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"expandedlicensing_member\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"minItems\": 2,\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_expandedlicensing_ConjunctiveLicenseSet_expandedlicensing_member\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"expandedlicensing_member\"\n                  ]\n              }\n          ]\n      },\n      \"prop_expandedlicensing_ConjunctiveLicenseSet_expandedlicensing_member\": {\n              \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_derived\"\n      },\n      \"expandedlicensing_CustomLicenseAddition\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_CustomLicenseAddition\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_CustomLicenseAddition_props\" }\n          ]\n      },\n      \"expandedlicensing_CustomLicenseAddition_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_CustomLicenseAddition\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_CustomLicenseAddition_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/expandedlicensing_LicenseAddition_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"expandedlicensing_DisjunctiveLicenseSet\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_DisjunctiveLicenseSet\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_DisjunctiveLicenseSet_props\" }\n          ]\n      },\n      \"expandedlicensing_DisjunctiveLicenseSet_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_DisjunctiveLicenseSet\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_DisjunctiveLicenseSet_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"expandedlicensing_member\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"minItems\": 2,\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_expandedlicensing_DisjunctiveLicenseSet_expandedlicensing_member\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"expandedlicensing_member\"\n                  ]\n              }\n          ]\n      },\n      \"prop_expandedlicensing_DisjunctiveLicenseSet_expandedlicensing_member\": {\n              \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_derived\"\n      },\n      \"expandedlicensing_ExtendableLicense_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_CustomLicense\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_ListedLicense\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_OrLaterOperator\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_ExtendableLicense_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"expandedlicensing_IndividualLicensingInfo\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_IndividualLicensingInfo\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_IndividualLicensingInfo_props\" }\n          ]\n      },\n      \"expandedlicensing_IndividualLicensingInfo_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_IndividualLicensingInfo\" }\n                  ]\n              },\n              { \"const\": \"expandedlicensing_NoAssertionLicense\" },\n              { \"const\": \"expandedlicensing_NoneLicense\" },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_IndividualLicensingInfo_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"expandedlicensing_License_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_CustomLicense\" },\n                      { \"$ref\": \"#/$defs/expandedlicensing_ListedLicense\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_License_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/expandedlicensing_ExtendableLicense_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"expandedlicensing_isDeprecatedLicenseId\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_License_expandedlicensing_isDeprecatedLicenseId\"\n                      },\n                      \"expandedlicensing_isFsfLibre\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_License_expandedlicensing_isFsfLibre\"\n                      },\n                      \"expandedlicensing_isOsiApproved\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_License_expandedlicensing_isOsiApproved\"\n                      },\n                      \"expandedlicensing_licenseXml\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_License_expandedlicensing_licenseXml\"\n                      },\n                      \"expandedlicensing_obsoletedBy\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_License_expandedlicensing_obsoletedBy\"\n                      },\n                      \"expandedlicensing_seeAlso\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_expandedlicensing_License_expandedlicensing_seeAlso\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"expandedlicensing_standardLicenseHeader\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_License_expandedlicensing_standardLicenseHeader\"\n                      },\n                      \"expandedlicensing_standardLicenseTemplate\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_License_expandedlicensing_standardLicenseTemplate\"\n                      },\n                      \"simplelicensing_licenseText\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_License_simplelicensing_licenseText\"\n                      }\n                  },\n                  \"required\": [\n                      \"simplelicensing_licenseText\"\n                  ]\n              }\n          ]\n      },\n      \"prop_expandedlicensing_License_expandedlicensing_isDeprecatedLicenseId\": {\n                  \"type\": \"boolean\"\n      },\n      \"prop_expandedlicensing_License_expandedlicensing_isFsfLibre\": {\n                  \"type\": \"boolean\"\n      },\n      \"prop_expandedlicensing_License_expandedlicensing_isOsiApproved\": {\n                  \"type\": \"boolean\"\n      },\n      \"prop_expandedlicensing_License_expandedlicensing_licenseXml\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_License_expandedlicensing_obsoletedBy\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_License_expandedlicensing_seeAlso\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_expandedlicensing_License_expandedlicensing_standardLicenseHeader\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_License_expandedlicensing_standardLicenseTemplate\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_License_simplelicensing_licenseText\": {\n                  \"type\": \"string\"\n      },\n      \"expandedlicensing_ListedLicense\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_ListedLicense\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_ListedLicense_props\" }\n          ]\n      },\n      \"expandedlicensing_ListedLicense_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_ListedLicense\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_ListedLicense_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/expandedlicensing_License_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"expandedlicensing_deprecatedVersion\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_ListedLicense_expandedlicensing_deprecatedVersion\"\n                      },\n                      \"expandedlicensing_listVersionAdded\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_ListedLicense_expandedlicensing_listVersionAdded\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_expandedlicensing_ListedLicense_expandedlicensing_deprecatedVersion\": {\n                  \"type\": \"string\"\n      },\n      \"prop_expandedlicensing_ListedLicense_expandedlicensing_listVersionAdded\": {\n                  \"type\": \"string\"\n      },\n      \"expandedlicensing_OrLaterOperator\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_OrLaterOperator\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_OrLaterOperator_props\" }\n          ]\n      },\n      \"expandedlicensing_OrLaterOperator_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_OrLaterOperator\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_OrLaterOperator_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/expandedlicensing_ExtendableLicense_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"expandedlicensing_subjectLicense\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_OrLaterOperator_expandedlicensing_subjectLicense\"\n                      }\n                  },\n                  \"required\": [\n                      \"expandedlicensing_subjectLicense\"\n                  ]\n              }\n          ]\n      },\n      \"prop_expandedlicensing_OrLaterOperator_expandedlicensing_subjectLicense\": {\n              \"$ref\": \"#/$defs/expandedlicensing_License_derived\"\n      },\n      \"expandedlicensing_WithAdditionOperator\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_WithAdditionOperator\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_WithAdditionOperator_props\" }\n          ]\n      },\n      \"expandedlicensing_WithAdditionOperator_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_WithAdditionOperator\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_WithAdditionOperator_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/simplelicensing_AnyLicenseInfo_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"expandedlicensing_subjectAddition\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_WithAdditionOperator_expandedlicensing_subjectAddition\"\n                      },\n                      \"expandedlicensing_subjectExtendableLicense\": {\n                          \"$ref\": \"#/$defs/prop_expandedlicensing_WithAdditionOperator_expandedlicensing_subjectExtendableLicense\"\n                      }\n                  },\n                  \"required\": [\n                      \"expandedlicensing_subjectAddition\",\n                      \"expandedlicensing_subjectExtendableLicense\"\n                  ]\n              }\n          ]\n      },\n      \"prop_expandedlicensing_WithAdditionOperator_expandedlicensing_subjectAddition\": {\n              \"$ref\": \"#/$defs/expandedlicensing_LicenseAddition_derived\"\n      },\n      \"prop_expandedlicensing_WithAdditionOperator_expandedlicensing_subjectExtendableLicense\": {\n              \"$ref\": \"#/$defs/expandedlicensing_ExtendableLicense_derived\"\n      },\n      \"extension_CdxPropertiesExtension\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"@id\": { \"$ref\": \"#/$defs/BlankNodeOrIRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"extension_CdxPropertiesExtension\" }\n                          ]\n                      }\n                  }\n              },\n              { \"$ref\": \"#/$defs/extension_CdxPropertiesExtension_props\" }\n          ]\n      },\n      \"extension_CdxPropertiesExtension_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/extension_CdxPropertiesExtension\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"extension_CdxPropertiesExtension_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/extension_Extension_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"extension_cdxProperty\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"minItems\": 1,\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_extension_CdxPropertiesExtension_extension_cdxProperty\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"extension_cdxProperty\"\n                  ]\n              }\n          ]\n      },\n      \"prop_extension_CdxPropertiesExtension_extension_cdxProperty\": {\n              \"$ref\": \"#/$defs/extension_CdxPropertyEntry_derived\"\n      },\n      \"security_CvssV2VulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_CvssV2VulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_CvssV2VulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_CvssV2VulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_CvssV2VulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_CvssV2VulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_score\": {\n                          \"$ref\": \"#/$defs/prop_security_CvssV2VulnAssessmentRelationship_security_score\"\n                      },\n                      \"security_vectorString\": {\n                          \"$ref\": \"#/$defs/prop_security_CvssV2VulnAssessmentRelationship_security_vectorString\"\n                      }\n                  },\n                  \"required\": [\n                      \"security_score\",\n                      \"security_vectorString\"\n                  ]\n              }\n          ]\n      },\n      \"prop_security_CvssV2VulnAssessmentRelationship_security_score\": {\n                  \"oneOf\": [\n                      {\n                          \"type\": \"number\"\n                      },\n                      {\n                          \"type\": \"string\",\n                          \"pattern\": \"^-?[0-9]+(\\\\.[0-9]*)?$\"\n                      }\n                  ]\n      },\n      \"prop_security_CvssV2VulnAssessmentRelationship_security_vectorString\": {\n                  \"type\": \"string\"\n      },\n      \"security_CvssV3VulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_CvssV3VulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_CvssV3VulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_CvssV3VulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_CvssV3VulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_CvssV3VulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_score\": {\n                          \"$ref\": \"#/$defs/prop_security_CvssV3VulnAssessmentRelationship_security_score\"\n                      },\n                      \"security_severity\": {\n                          \"$ref\": \"#/$defs/prop_security_CvssV3VulnAssessmentRelationship_security_severity\"\n                      },\n                      \"security_vectorString\": {\n                          \"$ref\": \"#/$defs/prop_security_CvssV3VulnAssessmentRelationship_security_vectorString\"\n                      }\n                  },\n                  \"required\": [\n                      \"security_score\",\n                      \"security_severity\",\n                      \"security_vectorString\"\n                  ]\n              }\n          ]\n      },\n      \"prop_security_CvssV3VulnAssessmentRelationship_security_score\": {\n                  \"oneOf\": [\n                      {\n                          \"type\": \"number\"\n                      },\n                      {\n                          \"type\": \"string\",\n                          \"pattern\": \"^-?[0-9]+(\\\\.[0-9]*)?$\"\n                      }\n                  ]\n      },\n      \"prop_security_CvssV3VulnAssessmentRelationship_security_severity\": {\n              \"enum\": [\n                  \"critical\",\n                  \"high\",\n                  \"low\",\n                  \"medium\",\n                  \"none\"\n              ]\n      },\n      \"prop_security_CvssV3VulnAssessmentRelationship_security_vectorString\": {\n                  \"type\": \"string\"\n      },\n      \"security_CvssV4VulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_CvssV4VulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_CvssV4VulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_CvssV4VulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_CvssV4VulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_CvssV4VulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_score\": {\n                          \"$ref\": \"#/$defs/prop_security_CvssV4VulnAssessmentRelationship_security_score\"\n                      },\n                      \"security_severity\": {\n                          \"$ref\": \"#/$defs/prop_security_CvssV4VulnAssessmentRelationship_security_severity\"\n                      },\n                      \"security_vectorString\": {\n                          \"$ref\": \"#/$defs/prop_security_CvssV4VulnAssessmentRelationship_security_vectorString\"\n                      }\n                  },\n                  \"required\": [\n                      \"security_score\",\n                      \"security_severity\",\n                      \"security_vectorString\"\n                  ]\n              }\n          ]\n      },\n      \"prop_security_CvssV4VulnAssessmentRelationship_security_score\": {\n                  \"oneOf\": [\n                      {\n                          \"type\": \"number\"\n                      },\n                      {\n                          \"type\": \"string\",\n                          \"pattern\": \"^-?[0-9]+(\\\\.[0-9]*)?$\"\n                      }\n                  ]\n      },\n      \"prop_security_CvssV4VulnAssessmentRelationship_security_severity\": {\n              \"enum\": [\n                  \"critical\",\n                  \"high\",\n                  \"low\",\n                  \"medium\",\n                  \"none\"\n              ]\n      },\n      \"prop_security_CvssV4VulnAssessmentRelationship_security_vectorString\": {\n                  \"type\": \"string\"\n      },\n      \"security_EpssVulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_EpssVulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_EpssVulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_EpssVulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_EpssVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_EpssVulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_percentile\": {\n                          \"$ref\": \"#/$defs/prop_security_EpssVulnAssessmentRelationship_security_percentile\"\n                      },\n                      \"security_probability\": {\n                          \"$ref\": \"#/$defs/prop_security_EpssVulnAssessmentRelationship_security_probability\"\n                      }\n                  },\n                  \"required\": [\n                      \"security_percentile\",\n                      \"security_probability\"\n                  ]\n              }\n          ]\n      },\n      \"prop_security_EpssVulnAssessmentRelationship_security_percentile\": {\n                  \"oneOf\": [\n                      {\n                          \"type\": \"number\"\n                      },\n                      {\n                          \"type\": \"string\",\n                          \"pattern\": \"^-?[0-9]+(\\\\.[0-9]*)?$\"\n                      }\n                  ]\n      },\n      \"prop_security_EpssVulnAssessmentRelationship_security_probability\": {\n                  \"oneOf\": [\n                      {\n                          \"type\": \"number\"\n                      },\n                      {\n                          \"type\": \"string\",\n                          \"pattern\": \"^-?[0-9]+(\\\\.[0-9]*)?$\"\n                      }\n                  ]\n      },\n      \"security_ExploitCatalogVulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_ExploitCatalogVulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_ExploitCatalogVulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_ExploitCatalogVulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_ExploitCatalogVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_ExploitCatalogVulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_catalogType\": {\n                          \"$ref\": \"#/$defs/prop_security_ExploitCatalogVulnAssessmentRelationship_security_catalogType\"\n                      },\n                      \"security_exploited\": {\n                          \"$ref\": \"#/$defs/prop_security_ExploitCatalogVulnAssessmentRelationship_security_exploited\"\n                      },\n                      \"security_locator\": {\n                          \"$ref\": \"#/$defs/prop_security_ExploitCatalogVulnAssessmentRelationship_security_locator\"\n                      }\n                  },\n                  \"required\": [\n                      \"security_catalogType\",\n                      \"security_exploited\",\n                      \"security_locator\"\n                  ]\n              }\n          ]\n      },\n      \"prop_security_ExploitCatalogVulnAssessmentRelationship_security_catalogType\": {\n              \"enum\": [\n                  \"kev\",\n                  \"other\"\n              ]\n      },\n      \"prop_security_ExploitCatalogVulnAssessmentRelationship_security_exploited\": {\n                  \"type\": \"boolean\"\n      },\n      \"prop_security_ExploitCatalogVulnAssessmentRelationship_security_locator\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"security_SsvcVulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_SsvcVulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_SsvcVulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_SsvcVulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_SsvcVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_SsvcVulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_decisionType\": {\n                          \"$ref\": \"#/$defs/prop_security_SsvcVulnAssessmentRelationship_security_decisionType\"\n                      }\n                  },\n                  \"required\": [\n                      \"security_decisionType\"\n                  ]\n              }\n          ]\n      },\n      \"prop_security_SsvcVulnAssessmentRelationship_security_decisionType\": {\n              \"enum\": [\n                  \"act\",\n                  \"attend\",\n                  \"track\",\n                  \"trackStar\"\n              ]\n      },\n      \"security_VexVulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_VexAffectedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexFixedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexNotAffectedVulnAssessmentRelationship\" },\n                      { \"$ref\": \"#/$defs/security_VexUnderInvestigationVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_VexVulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_statusNotes\": {\n                          \"$ref\": \"#/$defs/prop_security_VexVulnAssessmentRelationship_security_statusNotes\"\n                      },\n                      \"security_vexVersion\": {\n                          \"$ref\": \"#/$defs/prop_security_VexVulnAssessmentRelationship_security_vexVersion\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_security_VexVulnAssessmentRelationship_security_statusNotes\": {\n                  \"type\": \"string\"\n      },\n      \"prop_security_VexVulnAssessmentRelationship_security_vexVersion\": {\n                  \"type\": \"string\"\n      },\n      \"security_Vulnerability\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_Vulnerability\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_Vulnerability_props\" }\n          ]\n      },\n      \"security_Vulnerability_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_Vulnerability\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_Vulnerability_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Artifact_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_modifiedTime\": {\n                          \"$ref\": \"#/$defs/prop_security_Vulnerability_security_modifiedTime\"\n                      },\n                      \"security_publishedTime\": {\n                          \"$ref\": \"#/$defs/prop_security_Vulnerability_security_publishedTime\"\n                      },\n                      \"security_withdrawnTime\": {\n                          \"$ref\": \"#/$defs/prop_security_Vulnerability_security_withdrawnTime\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_security_Vulnerability_security_modifiedTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_security_Vulnerability_security_publishedTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_security_Vulnerability_security_withdrawnTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"software_SoftwareArtifact_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_AIPackage\" },\n                      { \"$ref\": \"#/$defs/dataset_DatasetPackage\" },\n                      { \"$ref\": \"#/$defs/software_File\" },\n                      { \"$ref\": \"#/$defs/software_Package\" },\n                      { \"$ref\": \"#/$defs/software_Snippet\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_SoftwareArtifact_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Artifact_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"software_additionalPurpose\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_software_SoftwareArtifact_software_additionalPurpose\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"software_attributionText\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_software_SoftwareArtifact_software_attributionText\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"software_contentIdentifier\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_software_SoftwareArtifact_software_contentIdentifier\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"software_copyrightText\": {\n                          \"$ref\": \"#/$defs/prop_software_SoftwareArtifact_software_copyrightText\"\n                      },\n                      \"software_primaryPurpose\": {\n                          \"$ref\": \"#/$defs/prop_software_SoftwareArtifact_software_primaryPurpose\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_software_SoftwareArtifact_software_additionalPurpose\": {\n              \"enum\": [\n                  \"application\",\n                  \"archive\",\n                  \"bom\",\n                  \"configuration\",\n                  \"container\",\n                  \"data\",\n                  \"device\",\n                  \"deviceDriver\",\n                  \"diskImage\",\n                  \"documentation\",\n                  \"evidence\",\n                  \"executable\",\n                  \"file\",\n                  \"filesystemImage\",\n                  \"firmware\",\n                  \"framework\",\n                  \"install\",\n                  \"library\",\n                  \"manifest\",\n                  \"model\",\n                  \"module\",\n                  \"operatingSystem\",\n                  \"other\",\n                  \"patch\",\n                  \"platform\",\n                  \"requirement\",\n                  \"source\",\n                  \"specification\",\n                  \"test\"\n              ]\n      },\n      \"prop_software_SoftwareArtifact_software_attributionText\": {\n                  \"type\": \"string\"\n      },\n      \"prop_software_SoftwareArtifact_software_contentIdentifier\": {\n              \"$ref\": \"#/$defs/software_ContentIdentifier_derived\"\n      },\n      \"prop_software_SoftwareArtifact_software_copyrightText\": {\n                  \"type\": \"string\"\n      },\n      \"prop_software_SoftwareArtifact_software_primaryPurpose\": {\n              \"enum\": [\n                  \"application\",\n                  \"archive\",\n                  \"bom\",\n                  \"configuration\",\n                  \"container\",\n                  \"data\",\n                  \"device\",\n                  \"deviceDriver\",\n                  \"diskImage\",\n                  \"documentation\",\n                  \"evidence\",\n                  \"executable\",\n                  \"file\",\n                  \"filesystemImage\",\n                  \"firmware\",\n                  \"framework\",\n                  \"install\",\n                  \"library\",\n                  \"manifest\",\n                  \"model\",\n                  \"module\",\n                  \"operatingSystem\",\n                  \"other\",\n                  \"patch\",\n                  \"platform\",\n                  \"requirement\",\n                  \"source\",\n                  \"specification\",\n                  \"test\"\n              ]\n      },\n      \"Bom\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"Bom\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/Bom_props\" }\n          ]\n      },\n      \"Bom_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_Sbom\" },\n                      { \"$ref\": \"#/$defs/Bom\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"Bom_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Bundle_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"expandedlicensing_CustomLicense\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"expandedlicensing_CustomLicense\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/expandedlicensing_CustomLicense_props\" }\n          ]\n      },\n      \"expandedlicensing_CustomLicense_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/expandedlicensing_CustomLicense\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"expandedlicensing_CustomLicense_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/expandedlicensing_License_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"security_VexAffectedVulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_VexAffectedVulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_VexAffectedVulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_VexAffectedVulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_VexAffectedVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_VexAffectedVulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VexVulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_actionStatement\": {\n                          \"$ref\": \"#/$defs/prop_security_VexAffectedVulnAssessmentRelationship_security_actionStatement\"\n                      },\n                      \"security_actionStatementTime\": {\n                          \"$ref\": \"#/$defs/prop_security_VexAffectedVulnAssessmentRelationship_security_actionStatementTime\"\n                      }\n                  },\n                  \"required\": [\n                      \"security_actionStatement\"\n                  ]\n              }\n          ]\n      },\n      \"prop_security_VexAffectedVulnAssessmentRelationship_security_actionStatement\": {\n                  \"type\": \"string\"\n      },\n      \"prop_security_VexAffectedVulnAssessmentRelationship_security_actionStatementTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"security_VexFixedVulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_VexFixedVulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_VexFixedVulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_VexFixedVulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_VexFixedVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_VexFixedVulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VexVulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"security_VexNotAffectedVulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_VexNotAffectedVulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_VexNotAffectedVulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_VexNotAffectedVulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_VexNotAffectedVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_VexNotAffectedVulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VexVulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"security_impactStatement\": {\n                          \"$ref\": \"#/$defs/prop_security_VexNotAffectedVulnAssessmentRelationship_security_impactStatement\"\n                      },\n                      \"security_impactStatementTime\": {\n                          \"$ref\": \"#/$defs/prop_security_VexNotAffectedVulnAssessmentRelationship_security_impactStatementTime\"\n                      },\n                      \"security_justificationType\": {\n                          \"$ref\": \"#/$defs/prop_security_VexNotAffectedVulnAssessmentRelationship_security_justificationType\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_security_VexNotAffectedVulnAssessmentRelationship_security_impactStatement\": {\n                  \"type\": \"string\"\n      },\n      \"prop_security_VexNotAffectedVulnAssessmentRelationship_security_impactStatementTime\": {\n                  \"type\": \"string\",\n                  \"allOf\": [\n                      {\n                          \"pattern\": \"^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](Z|[+-][0-9]{2}:[0-9]{2})$\"\n                      },\n                      {\n                          \"pattern\": \"^\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\dT\\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\dZ$\"\n                      }\n                  ]\n      },\n      \"prop_security_VexNotAffectedVulnAssessmentRelationship_security_justificationType\": {\n              \"enum\": [\n                  \"componentNotPresent\",\n                  \"inlineMitigationsAlreadyExist\",\n                  \"vulnerableCodeCannotBeControlledByAdversary\",\n                  \"vulnerableCodeNotInExecutePath\",\n                  \"vulnerableCodeNotPresent\"\n              ]\n      },\n      \"security_VexUnderInvestigationVulnAssessmentRelationship\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"security_VexUnderInvestigationVulnAssessmentRelationship\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/security_VexUnderInvestigationVulnAssessmentRelationship_props\" }\n          ]\n      },\n      \"security_VexUnderInvestigationVulnAssessmentRelationship_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/security_VexUnderInvestigationVulnAssessmentRelationship\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"security_VexUnderInvestigationVulnAssessmentRelationship_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/security_VexVulnAssessmentRelationship_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                  }\n              }\n          ]\n      },\n      \"software_File\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_File\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/software_File_props\" }\n          ]\n      },\n      \"software_File_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_File\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_File_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/software_SoftwareArtifact_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"contentType\": {\n                          \"$ref\": \"#/$defs/prop_software_File_contentType\"\n                      },\n                      \"software_fileKind\": {\n                          \"$ref\": \"#/$defs/prop_software_File_software_fileKind\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_software_File_contentType\": {\n                  \"pattern\": \"^[^\\\\/]+\\\\/[^\\\\/]+$\",\n                  \"type\": \"string\"\n      },\n      \"prop_software_File_software_fileKind\": {\n              \"enum\": [\n                  \"directory\",\n                  \"file\"\n              ]\n      },\n      \"software_Package\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_Package\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/software_Package_props\" }\n          ]\n      },\n      \"software_Package_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_AIPackage\" },\n                      { \"$ref\": \"#/$defs/dataset_DatasetPackage\" },\n                      { \"$ref\": \"#/$defs/software_Package\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_Package_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/software_SoftwareArtifact_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"software_downloadLocation\": {\n                          \"$ref\": \"#/$defs/prop_software_Package_software_downloadLocation\"\n                      },\n                      \"software_homePage\": {\n                          \"$ref\": \"#/$defs/prop_software_Package_software_homePage\"\n                      },\n                      \"software_packageUrl\": {\n                          \"$ref\": \"#/$defs/prop_software_Package_software_packageUrl\"\n                      },\n                      \"software_packageVersion\": {\n                          \"$ref\": \"#/$defs/prop_software_Package_software_packageVersion\"\n                      },\n                      \"software_sourceInfo\": {\n                          \"$ref\": \"#/$defs/prop_software_Package_software_sourceInfo\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_software_Package_software_downloadLocation\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_software_Package_software_homePage\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_software_Package_software_packageUrl\": {\n                  \"$ref\": \"#/$defs/anyURI\"\n      },\n      \"prop_software_Package_software_packageVersion\": {\n                  \"type\": \"string\"\n      },\n      \"prop_software_Package_software_sourceInfo\": {\n                  \"type\": \"string\"\n      },\n      \"software_Sbom\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_Sbom\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/software_Sbom_props\" }\n          ]\n      },\n      \"software_Sbom_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_Sbom\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_Sbom_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/Bom_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"software_sbomType\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_software_Sbom_software_sbomType\"\n                                  }\n                              }\n                          ]\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_software_Sbom_software_sbomType\": {\n              \"enum\": [\n                  \"analyzed\",\n                  \"build\",\n                  \"deployed\",\n                  \"design\",\n                  \"runtime\",\n                  \"source\"\n              ]\n      },\n      \"software_Snippet\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"software_Snippet\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/software_Snippet_props\" }\n          ]\n      },\n      \"software_Snippet_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/software_Snippet\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"software_Snippet_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/software_SoftwareArtifact_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"software_byteRange\": {\n                          \"$ref\": \"#/$defs/prop_software_Snippet_software_byteRange\"\n                      },\n                      \"software_lineRange\": {\n                          \"$ref\": \"#/$defs/prop_software_Snippet_software_lineRange\"\n                      },\n                      \"software_snippetFromFile\": {\n                          \"$ref\": \"#/$defs/prop_software_Snippet_software_snippetFromFile\"\n                      }\n                  },\n                  \"required\": [\n                      \"software_snippetFromFile\"\n                  ]\n              }\n          ]\n      },\n      \"prop_software_Snippet_software_byteRange\": {\n              \"$ref\": \"#/$defs/PositiveIntegerRange_derived\"\n      },\n      \"prop_software_Snippet_software_lineRange\": {\n              \"$ref\": \"#/$defs/PositiveIntegerRange_derived\"\n      },\n      \"prop_software_Snippet_software_snippetFromFile\": {\n              \"$ref\": \"#/$defs/software_File_derived\"\n      },\n      \"ai_AIPackage\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"ai_AIPackage\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/ai_AIPackage_props\" }\n          ]\n      },\n      \"ai_AIPackage_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/ai_AIPackage\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"ai_AIPackage_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/software_Package_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"ai_autonomyType\": {\n                          \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_autonomyType\"\n                      },\n                      \"ai_domain\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_domain\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_energyConsumption\": {\n                          \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_energyConsumption\"\n                      },\n                      \"ai_hyperparameter\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_hyperparameter\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_informationAboutApplication\": {\n                          \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_informationAboutApplication\"\n                      },\n                      \"ai_informationAboutTraining\": {\n                          \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_informationAboutTraining\"\n                      },\n                      \"ai_limitation\": {\n                          \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_limitation\"\n                      },\n                      \"ai_metric\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_metric\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_metricDecisionThreshold\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_metricDecisionThreshold\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_modelDataPreprocessing\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_modelDataPreprocessing\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_modelExplainability\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_modelExplainability\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_safetyRiskAssessment\": {\n                          \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_safetyRiskAssessment\"\n                      },\n                      \"ai_standardCompliance\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_standardCompliance\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_typeOfModel\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_typeOfModel\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"ai_useSensitivePersonalInformation\": {\n                          \"$ref\": \"#/$defs/prop_ai_AIPackage_ai_useSensitivePersonalInformation\"\n                      }\n                  }\n              }\n          ]\n      },\n      \"prop_ai_AIPackage_ai_autonomyType\": {\n              \"enum\": [\n                  \"no\",\n                  \"noAssertion\",\n                  \"yes\"\n              ]\n      },\n      \"prop_ai_AIPackage_ai_domain\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ai_AIPackage_ai_energyConsumption\": {\n              \"$ref\": \"#/$defs/ai_EnergyConsumption_derived\"\n      },\n      \"prop_ai_AIPackage_ai_hyperparameter\": {\n              \"$ref\": \"#/$defs/DictionaryEntry_derived\"\n      },\n      \"prop_ai_AIPackage_ai_informationAboutApplication\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ai_AIPackage_ai_informationAboutTraining\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ai_AIPackage_ai_limitation\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ai_AIPackage_ai_metric\": {\n              \"$ref\": \"#/$defs/DictionaryEntry_derived\"\n      },\n      \"prop_ai_AIPackage_ai_metricDecisionThreshold\": {\n              \"$ref\": \"#/$defs/DictionaryEntry_derived\"\n      },\n      \"prop_ai_AIPackage_ai_modelDataPreprocessing\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ai_AIPackage_ai_modelExplainability\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ai_AIPackage_ai_safetyRiskAssessment\": {\n              \"enum\": [\n                  \"high\",\n                  \"low\",\n                  \"medium\",\n                  \"serious\"\n              ]\n      },\n      \"prop_ai_AIPackage_ai_standardCompliance\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ai_AIPackage_ai_typeOfModel\": {\n                  \"type\": \"string\"\n      },\n      \"prop_ai_AIPackage_ai_useSensitivePersonalInformation\": {\n              \"enum\": [\n                  \"no\",\n                  \"noAssertion\",\n                  \"yes\"\n              ]\n      },\n      \"dataset_DatasetPackage\": {\n          \"allOf\": [\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"spdxId\": { \"$ref\": \"#/$defs/IRI\" },\n                      \"type\": {\n                          \"oneOf\": [\n                              { \"const\": \"dataset_DatasetPackage\" }\n                          ]\n                      }\n                  },\n                  \"required\": [\"spdxId\"]\n              },\n              { \"$ref\": \"#/$defs/dataset_DatasetPackage_props\" }\n          ]\n      },\n      \"dataset_DatasetPackage_derived\": {\n          \"anyOf\": [\n              {\n                  \"type\": \"object\",\n                  \"unevaluatedProperties\": false,\n                  \"anyOf\": [\n                      { \"$ref\": \"#/$defs/dataset_DatasetPackage\" }\n                  ]\n              },\n              { \"$ref\": \"#/$defs/BlankNodeOrIRI\" }\n          ]\n      },\n      \"dataset_DatasetPackage_props\": {\n          \"allOf\": [\n              { \"$ref\": \"#/$defs/software_Package_props\" },\n              {\n                  \"type\": \"object\",\n                  \"properties\": {\n                      \"dataset_anonymizationMethodUsed\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_anonymizationMethodUsed\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"dataset_confidentialityLevel\": {\n                          \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_confidentialityLevel\"\n                      },\n                      \"dataset_dataCollectionProcess\": {\n                          \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_dataCollectionProcess\"\n                      },\n                      \"dataset_dataPreprocessing\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_dataPreprocessing\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"dataset_datasetAvailability\": {\n                          \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_datasetAvailability\"\n                      },\n                      \"dataset_datasetNoise\": {\n                          \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_datasetNoise\"\n                      },\n                      \"dataset_datasetSize\": {\n                          \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_datasetSize\"\n                      },\n                      \"dataset_datasetType\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"minItems\": 1,\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_datasetType\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"dataset_datasetUpdateMechanism\": {\n                          \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_datasetUpdateMechanism\"\n                      },\n                      \"dataset_hasSensitivePersonalInformation\": {\n                          \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_hasSensitivePersonalInformation\"\n                      },\n                      \"dataset_intendedUse\": {\n                          \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_intendedUse\"\n                      },\n                      \"dataset_knownBias\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_knownBias\"\n                                  }\n                              }\n                          ]\n                      },\n                      \"dataset_sensor\": {\n                          \"oneOf\": [\n                              {\n                                  \"type\": \"array\",\n                                  \"items\": {\n                                      \"$ref\": \"#/$defs/prop_dataset_DatasetPackage_dataset_sensor\"\n                                  }\n                              }\n                          ]\n                      }\n                  },\n                  \"required\": [\n                      \"dataset_datasetType\"\n                  ]\n              }\n          ]\n      },\n      \"prop_dataset_DatasetPackage_dataset_anonymizationMethodUsed\": {\n                  \"type\": \"string\"\n      },\n      \"prop_dataset_DatasetPackage_dataset_confidentialityLevel\": {\n              \"enum\": [\n                  \"amber\",\n                  \"clear\",\n                  \"green\",\n                  \"red\"\n              ]\n      },\n      \"prop_dataset_DatasetPackage_dataset_dataCollectionProcess\": {\n                  \"type\": \"string\"\n      },\n      \"prop_dataset_DatasetPackage_dataset_dataPreprocessing\": {\n                  \"type\": \"string\"\n      },\n      \"prop_dataset_DatasetPackage_dataset_datasetAvailability\": {\n              \"enum\": [\n                  \"clickthrough\",\n                  \"directDownload\",\n                  \"query\",\n                  \"registration\",\n                  \"scrapingScript\"\n              ]\n      },\n      \"prop_dataset_DatasetPackage_dataset_datasetNoise\": {\n                  \"type\": \"string\"\n      },\n      \"prop_dataset_DatasetPackage_dataset_datasetSize\": {\n                  \"type\": \"integer\",\n                  \"minimum\": 0\n      },\n      \"prop_dataset_DatasetPackage_dataset_datasetType\": {\n              \"enum\": [\n                  \"audio\",\n                  \"categorical\",\n                  \"graph\",\n                  \"image\",\n                  \"noAssertion\",\n                  \"numeric\",\n                  \"other\",\n                  \"sensor\",\n                  \"structured\",\n                  \"syntactic\",\n                  \"text\",\n                  \"timeseries\",\n                  \"timestamp\",\n                  \"video\"\n              ]\n      },\n      \"prop_dataset_DatasetPackage_dataset_datasetUpdateMechanism\": {\n                  \"type\": \"string\"\n      },\n      \"prop_dataset_DatasetPackage_dataset_hasSensitivePersonalInformation\": {\n              \"enum\": [\n                  \"no\",\n                  \"noAssertion\",\n                  \"yes\"\n              ]\n      },\n      \"prop_dataset_DatasetPackage_dataset_intendedUse\": {\n                  \"type\": \"string\"\n      },\n      \"prop_dataset_DatasetPackage_dataset_knownBias\": {\n                  \"type\": \"string\"\n      },\n      \"prop_dataset_DatasetPackage_dataset_sensor\": {\n              \"$ref\": \"#/$defs/DictionaryEntry_derived\"\n      },\n      \"IRI\": {\n          \"type\": \"string\",\n          \"pattern\": \"^(?!_:).+:.+\"\n      },\n      \"BlankNode\": {\n          \"type\": \"string\",\n          \"pattern\": \"^_:.+\"\n      },\n      \"BlankNodeOrIRI\": {\n          \"oneOf\": [\n              { \"$ref\": \"#/$defs/IRI\" },\n              { \"$ref\": \"#/$defs/BlankNode\" }\n          ]\n      },\n      \"anyURI\": {\n          \"type\": \"string\"\n      },\n      \"SHACLClass\": {\n          \"type\": \"object\",\n          \"properties\": {\n              \"type\": {\n                  \"oneOf\": [\n                      { \"$ref\": \"#/$defs/IRI\" },\n                      {\n                          \"enum\": [\n                              \"ai_EnergyConsumption\",\n                              \"ai_EnergyConsumptionDescription\",\n                              \"ai_EnergyUnitType\",\n                              \"ai_SafetyRiskAssessmentType\",\n                              \"AnnotationType\",\n                              \"CreationInfo\",\n                              \"DictionaryEntry\",\n                              \"ExternalIdentifier\",\n                              \"ExternalIdentifierType\",\n                              \"ExternalMap\",\n                              \"ExternalRef\",\n                              \"ExternalRefType\",\n                              \"HashAlgorithm\",\n                              \"IndividualElement\",\n                              \"LifecycleScopeType\",\n                              \"NamespaceMap\",\n                              \"PackageVerificationCode\",\n                              \"PositiveIntegerRange\",\n                              \"PresenceType\",\n                              \"ProfileIdentifierType\",\n                              \"Relationship\",\n                              \"RelationshipCompleteness\",\n                              \"RelationshipType\",\n                              \"SpdxDocument\",\n                              \"SupportType\",\n                              \"Tool\",\n                              \"dataset_ConfidentialityLevelType\",\n                              \"dataset_DatasetAvailabilityType\",\n                              \"dataset_DatasetType\",\n                              \"expandedlicensing_ListedLicenseException\",\n                              \"extension_CdxPropertyEntry\",\n                              \"security_CvssSeverityType\",\n                              \"security_ExploitCatalogType\",\n                              \"security_SsvcDecisionType\",\n                              \"security_VexJustificationType\",\n                              \"simplelicensing_LicenseExpression\",\n                              \"simplelicensing_SimpleLicensingText\",\n                              \"software_ContentIdentifier\",\n                              \"software_ContentIdentifierType\",\n                              \"software_FileKindType\",\n                              \"software_SbomType\",\n                              \"software_SoftwarePurpose\",\n                              \"build_Build\",\n                              \"Agent\",\n                              \"Annotation\",\n                              \"Bundle\",\n                              \"Hash\",\n                              \"LifecycleScopedRelationship\",\n                              \"Organization\",\n                              \"Person\",\n                              \"SoftwareAgent\",\n                              \"expandedlicensing_ConjunctiveLicenseSet\",\n                              \"expandedlicensing_CustomLicenseAddition\",\n                              \"expandedlicensing_DisjunctiveLicenseSet\",\n                              \"expandedlicensing_IndividualLicensingInfo\",\n                              \"expandedlicensing_ListedLicense\",\n                              \"expandedlicensing_OrLaterOperator\",\n                              \"expandedlicensing_WithAdditionOperator\",\n                              \"extension_CdxPropertiesExtension\",\n                              \"security_CvssV2VulnAssessmentRelationship\",\n                              \"security_CvssV3VulnAssessmentRelationship\",\n                              \"security_CvssV4VulnAssessmentRelationship\",\n                              \"security_EpssVulnAssessmentRelationship\",\n                              \"security_ExploitCatalogVulnAssessmentRelationship\",\n                              \"security_SsvcVulnAssessmentRelationship\",\n                              \"security_Vulnerability\",\n                              \"Bom\",\n                              \"expandedlicensing_CustomLicense\",\n                              \"security_VexAffectedVulnAssessmentRelationship\",\n                              \"security_VexFixedVulnAssessmentRelationship\",\n                              \"security_VexNotAffectedVulnAssessmentRelationship\",\n                              \"security_VexUnderInvestigationVulnAssessmentRelationship\",\n                              \"software_File\",\n                              \"software_Package\",\n                              \"software_Sbom\",\n                              \"software_Snippet\",\n                              \"ai_AIPackage\",\n                              \"dataset_DatasetPackage\"\n                          ]\n                      }\n                  ]\n              }\n          },\n          \"required\": [\"type\"]\n      },\n      \"AnyClass\": {\n          \"anyOf\": [\n              { \"$ref\": \"#/$defs/ai_EnergyConsumption\" },\n              { \"$ref\": \"#/$defs/ai_EnergyConsumptionDescription\" },\n              { \"$ref\": \"#/$defs/ai_EnergyUnitType\" },\n              { \"$ref\": \"#/$defs/ai_SafetyRiskAssessmentType\" },\n              { \"$ref\": \"#/$defs/AnnotationType\" },\n              { \"$ref\": \"#/$defs/CreationInfo\" },\n              { \"$ref\": \"#/$defs/DictionaryEntry\" },\n              { \"$ref\": \"#/$defs/ExternalIdentifier\" },\n              { \"$ref\": \"#/$defs/ExternalIdentifierType\" },\n              { \"$ref\": \"#/$defs/ExternalMap\" },\n              { \"$ref\": \"#/$defs/ExternalRef\" },\n              { \"$ref\": \"#/$defs/ExternalRefType\" },\n              { \"$ref\": \"#/$defs/HashAlgorithm\" },\n              { \"$ref\": \"#/$defs/IndividualElement\" },\n              { \"$ref\": \"#/$defs/LifecycleScopeType\" },\n              { \"$ref\": \"#/$defs/NamespaceMap\" },\n              { \"$ref\": \"#/$defs/PackageVerificationCode\" },\n              { \"$ref\": \"#/$defs/PositiveIntegerRange\" },\n              { \"$ref\": \"#/$defs/PresenceType\" },\n              { \"$ref\": \"#/$defs/ProfileIdentifierType\" },\n              { \"$ref\": \"#/$defs/Relationship\" },\n              { \"$ref\": \"#/$defs/RelationshipCompleteness\" },\n              { \"$ref\": \"#/$defs/RelationshipType\" },\n              { \"$ref\": \"#/$defs/SpdxDocument\" },\n              { \"$ref\": \"#/$defs/SupportType\" },\n              { \"$ref\": \"#/$defs/Tool\" },\n              { \"$ref\": \"#/$defs/dataset_ConfidentialityLevelType\" },\n              { \"$ref\": \"#/$defs/dataset_DatasetAvailabilityType\" },\n              { \"$ref\": \"#/$defs/dataset_DatasetType\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_ListedLicenseException\" },\n              { \"$ref\": \"#/$defs/extension_CdxPropertyEntry\" },\n              { \"$ref\": \"#/$defs/security_CvssSeverityType\" },\n              { \"$ref\": \"#/$defs/security_ExploitCatalogType\" },\n              { \"$ref\": \"#/$defs/security_SsvcDecisionType\" },\n              { \"$ref\": \"#/$defs/security_VexJustificationType\" },\n              { \"$ref\": \"#/$defs/simplelicensing_LicenseExpression\" },\n              { \"$ref\": \"#/$defs/simplelicensing_SimpleLicensingText\" },\n              { \"$ref\": \"#/$defs/software_ContentIdentifier\" },\n              { \"$ref\": \"#/$defs/software_ContentIdentifierType\" },\n              { \"$ref\": \"#/$defs/software_FileKindType\" },\n              { \"$ref\": \"#/$defs/software_SbomType\" },\n              { \"$ref\": \"#/$defs/software_SoftwarePurpose\" },\n              { \"$ref\": \"#/$defs/build_Build\" },\n              { \"$ref\": \"#/$defs/Agent\" },\n              { \"$ref\": \"#/$defs/Annotation\" },\n              { \"$ref\": \"#/$defs/Bundle\" },\n              { \"$ref\": \"#/$defs/Hash\" },\n              { \"$ref\": \"#/$defs/LifecycleScopedRelationship\" },\n              { \"$ref\": \"#/$defs/Organization\" },\n              { \"$ref\": \"#/$defs/Person\" },\n              { \"$ref\": \"#/$defs/SoftwareAgent\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_ConjunctiveLicenseSet\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_CustomLicenseAddition\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_DisjunctiveLicenseSet\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_IndividualLicensingInfo\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_ListedLicense\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_OrLaterOperator\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_WithAdditionOperator\" },\n              { \"$ref\": \"#/$defs/extension_CdxPropertiesExtension\" },\n              { \"$ref\": \"#/$defs/security_CvssV2VulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_CvssV3VulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_CvssV4VulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_EpssVulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_ExploitCatalogVulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_SsvcVulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_Vulnerability\" },\n              { \"$ref\": \"#/$defs/Bom\" },\n              { \"$ref\": \"#/$defs/expandedlicensing_CustomLicense\" },\n              { \"$ref\": \"#/$defs/security_VexAffectedVulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_VexFixedVulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_VexNotAffectedVulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/security_VexUnderInvestigationVulnAssessmentRelationship\" },\n              { \"$ref\": \"#/$defs/software_File\" },\n              { \"$ref\": \"#/$defs/software_Package\" },\n              { \"$ref\": \"#/$defs/software_Sbom\" },\n              { \"$ref\": \"#/$defs/software_Snippet\" },\n              { \"$ref\": \"#/$defs/ai_AIPackage\" },\n              { \"$ref\": \"#/$defs/dataset_DatasetPackage\" }\n          ]\n      }\n  }\n}"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXAgent.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXAgent: Codable, Equatable {\n    internal let id: String\n    internal let type: SPDXType\n    internal let name: String\n    internal let creationInfoID: String\n\n    internal init(\n        id: String,\n        type: SPDXType,\n        name: String,\n        creationInfoID: String\n    ) {\n        self.id = id\n        self.type = type\n        self.name = name\n        self.creationInfoID = creationInfoID\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case id = \"spdxId\"\n        case type\n        case name\n        case creationInfoID = \"creationInfo\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXConstants.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXConstants: Codable, Equatable {\n    /// The latest minor version of SPDX v3.x (from SBOMVersionRegistry)\n    internal static var spdx3SpecVersion: String {\n        SBOMVersionRegistry.spdx3LatestMinor\n    }\n    \n    /// The JSON-LD context URL for SPDX v3.x\n    /// This is embedded as a field in the SBOM, and points to an official schema URL on the SPDX website\n    internal static var spdx3Context: String {\n        \"https://spdx.org/rdf/\\(spdx3SpecVersion)/spdx-context.jsonld\"\n    }\n    \n    /// The schema filename for SPDX v3.x (without .json extension) that's bundled as an internal resource with SwiftPM\n    internal static var spdx3SchemaFile: String {\n        \"spdx-\\(spdx3SpecVersion).schema\"\n    }\n    \n    /// The root creation info ID used in SPDX documents\n    internal static let spdxRootCreationInfoID = \"_:creationInfo\"\n    \n    // Future major versions (uncomment when SPDX 4.0 is released):\n    // /// The latest minor version of SPDX v4.x (from SBOMVersionRegistry)\n    // internal static var spdx4SpecVersion: String {\n    //     SBOMVersionRegistry.spdx4LatestMinor\n    // }\n    //\n    // /// The JSON-LD context URL for SPDX v4.x\n    // internal static var spdx4Context: String {\n    //     \"https://spdx.org/rdf/\\(spdx4SpecVersion)/spdx-context.jsonld\"\n    // }\n    //\n    // /// The schema filename for SPDX v4.x (without .json extension)\n    // internal static var spdx4SchemaFile: String {\n    //     \"spdx-\\(spdx4SpecVersion).schema\"\n    // }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXCreationInfo.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXCreationInfo: Codable, Equatable {\n    internal let id: String\n    internal let type: SPDXType\n    internal let specVersion: String?\n    internal let createdBy: [String]\n    internal let created: String\n\n    internal init(\n        id: String,\n        type: SPDXType,\n        specVersion: String? = nil,\n        createdBy: [String],\n        created: String\n    ) {\n        self.id = id\n        self.type = type\n        self.specVersion = specVersion\n        self.createdBy = createdBy\n        self.created = created\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case id = \"@id\"\n        case type\n        case specVersion\n        case createdBy\n        case created\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXDocument.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXDocument: Codable, Equatable {\n    internal let id: String\n    internal let type: SPDXType\n    internal let creationInfoID: String\n    internal let profileConformance: [String]\n    internal let rootElementIDs: [String]\n\n    internal init(\n        id: String,\n        type: SPDXType,\n        creationInfoID: String,\n        profileConformance: [String],\n        rootElementIDs: [String]\n    ) {\n        self.id = id\n        self.type = type\n        self.creationInfoID = creationInfoID\n        self.profileConformance = profileConformance\n        self.rootElementIDs = rootElementIDs\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case id = \"spdxId\"\n        case type\n        case creationInfoID = \"creationInfo\"\n        case profileConformance\n        case rootElementIDs = \"rootElement\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXExternalIdentifier.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXExternalIdentifier: Codable, Equatable {\n    internal enum Category: String, Codable, Equatable {\n        case gitoid\n        case urlScheme\n    }\n\n    internal let identifier: String\n    internal let identifierLocator: [String]\n    internal let type: SPDXType\n    internal let category: Category\n\n    internal init(\n        identifier: String,\n        identifierLocator: [String],\n        type: SPDXType,\n        category: Category\n    ) {\n        self.identifier = identifier\n        self.identifierLocator = identifierLocator\n        self.type = type\n        self.category = category\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case identifier\n        case identifierLocator\n        case type\n        case category = \"externalIdentifierType\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXGraph.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\ninternal struct SPDXGraphElement: Encodable {\n    private let value: any Encodable\n\n    internal init(_ value: some Encodable) {\n        self.value = value\n    }\n\n    internal func encode(to encoder: Encoder) throws {\n        var container = encoder.singleValueContainer()\n        try container.encode(self.value)\n    }\n\n    internal func getValue<T>() -> T? {\n        self.value as? T\n    }\n}\n\ninternal struct SPDXGraph: Encodable {\n    internal let context: String\n    internal let graph: [SPDXGraphElement]\n\n    internal init(\n        context: String,\n        graph: [SPDXGraphElement]\n    ) {\n        self.context = context\n        self.graph = graph\n    }\n\n    internal init(\n        context: String,\n        graph: [any SPDXObject]\n    ) {\n        self.context = context\n        self.graph = graph.map { SPDXGraphElement($0) }\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case context = \"@context\"\n        case graph = \"@graph\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXLicenseExpression.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXLicenseExpression: Codable, Equatable {\n    internal let id: String\n    internal let type: SPDXType\n    internal let expression: String\n    internal let creationInfoID: String\n\n    internal init(\n        id: String,\n        type: SPDXType,\n        expression: String,\n        creationInfoID: String,\n    ) {\n        self.id = id\n        self.type = type\n        self.expression = expression\n        self.creationInfoID = creationInfoID\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case id = \"spdxId\"\n        case type\n        case expression = \"simplelicensing_licenseExpression\"\n        case creationInfoID = \"creationInfo\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXObject.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A protocol representing any object that can be part of an SPDX graph.\n/// All SPDX types (Agent, CreationInfo, Document, Package, Relationship, etc.)\n/// conform to this protocol to provide type safety when building SPDX graphs.\ninternal protocol SPDXObject: Codable, Equatable {}\n\n// Conformance for all SPDX types\nextension SPDXAgent: SPDXObject {}\nextension SPDXCreationInfo: SPDXObject {}\nextension SPDXDocument: SPDXObject {}\nextension SPDXPackage: SPDXObject {}\nextension SPDXRelationship: SPDXObject {}\nextension SPDXExternalIdentifier: SPDXObject {}\nextension SPDXSBOM: SPDXObject {}\nextension SPDXLicenseExpression: SPDXObject {}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXPackage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXPackage: Codable, Equatable {\n    internal enum Purpose: String, Codable, Equatable {\n        case application\n        case framework\n        case library\n        case file\n    }\n\n    internal let id: String\n    internal let type: SPDXType\n    internal let purpose: Purpose\n    internal let purl: String\n    internal let name: String\n    internal let version: String\n    internal let creationInfoID: String\n    internal let description: String?\n    internal let summary: String?\n\n    internal init(\n        id: String,\n        type: SPDXType,\n        purpose: Purpose,\n        purl: String,\n        name: String,\n        version: String,\n        creationInfoID: String,\n        description: String?,\n        summary: String?\n    ) {\n        self.id = id\n        self.type = type\n        self.purpose = purpose\n        self.purl = purl\n        self.name = name\n        self.version = version\n        self.creationInfoID = creationInfoID\n        self.description = description\n        self.summary = summary\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case id = \"spdxId\"\n        case type\n        case purpose = \"software_primaryPurpose\"\n        case purl = \"externalUrl\"\n        case name\n        case version = \"software_internalVersion\"\n        case creationInfoID = \"creationInfo\"\n        case description\n        case summary\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXRelationship.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXRelationship: Codable, Equatable {\n    internal enum Category: String, Codable, Equatable {\n        case describes\n        case dependsOn\n        case hasOptionalDependency\n        case hasTest\n        case generates\n        case hasDeclaredLicense\n        case availableFrom\n    }\n\n    internal let id: String\n    internal let type: SPDXType\n    internal let category: Category\n    internal let creationInfoID: String\n    internal let parentID: String\n    internal let childrenID: [String]\n\n    internal init(\n        id: String,\n        type: SPDXType,\n        category: Category,\n        creationInfoID: String,\n        parentID: String,\n        childrenID: [String]\n    ) {\n        self.id = id\n        self.type = type\n        self.category = category\n        self.creationInfoID = creationInfoID\n        self.parentID = parentID\n        self.childrenID = childrenID\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case id = \"spdxId\"\n        case type\n        case category = \"relationshipType\"\n        case creationInfoID = \"creationInfo\"\n        case parentID = \"from\"\n        case childrenID = \"to\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXSBOM.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal struct SPDXSBOM: Codable, Equatable {\n    internal let id: String\n    internal let type: SPDXType\n    internal let creationInfoID: String\n    internal let profileConformance: [String]\n    internal let rootElementIDs: [String]\n\n    internal init(\n        id: String,\n        type: SPDXType,\n        creationInfoID: String,\n        profileConformance: [String],\n        rootElementIDs: [String]\n    ) {\n        self.id = id\n        self.type = type\n        self.creationInfoID = creationInfoID\n        self.profileConformance = profileConformance\n        self.rootElementIDs = rootElementIDs\n    }\n\n    private enum CodingKeys: String, CodingKey {\n        case id = \"spdxId\"\n        case type\n        case creationInfoID = \"creationInfo\"\n        case profileConformance\n        case rootElementIDs = \"rootElement\"\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/SPDX/SPDXType.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal enum SPDXType: String, Codable, Equatable {\n    case Agent\n    case CreationInfo\n    case SpdxDocument\n    case SoftwareSBOM = \"software_Sbom\"\n    case SoftwarePackage = \"software_Package\"\n    case Relationship\n    case ExternalIdentifier\n    case LicenseExpression = \"simplelicensing_LicenseExpression\"\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Validator/CycloneDXValidator.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nstruct CycloneDXValidator: SBOMValidatorProtocol {\n    private let validator: SBOMValidator\n\n    init(schema: [String: Any]) {\n        self.validator = SBOMValidator(schema: schema)\n    }\n\n    func validate(_ object: Any) async throws {\n        try await self.validator.validate(object)\n    }\n\n    func validateValue(_ value: Any, path: String) async throws {\n        try await self.validator.validateValue(value, path: path)\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Validator/SBOMValidator.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n// MARK: - Bundle Loading\n\nprivate actor BundleCache {\n    static let shared = BundleCache()\n    \n    private var cache: [String: Bundle] = [:]\n    \n    private init() {}\n    \n    func findBundle(named bundleName: String) -> Bundle? {\n        if let cachedBundle = cache[bundleName] {\n            return cachedBundle\n        }\n        \n        let foundBundle = searchForBundle(named: bundleName)\n        \n        if let foundBundle = foundBundle {\n            cache[bundleName] = foundBundle\n        }\n        \n        return foundBundle\n    }\n    \n    private func searchForBundle(named bundleName: String) -> Bundle? {\n        // Avoid using Bundle.module because it causes a fatal error if not found (e.g., when using custom toolchains)\n        // Avoid using Bundle.allBundles because it's not thread-safe on Linux and only includes bundles that have already been loaded from disk\n        \n        // On macOS, these are .bundle directories; on other platforms, they're .resources directories\n        let bundleExtensions = [\"bundle\", \"resources\"]\n        let searchLocations = [Bundle.main.resourceURL, Bundle.main.bundleURL, Bundle.main.executableURL]\n\n        for ext in bundleExtensions {\n            for searchLocation in searchLocations {\n                guard let searchURL = searchLocation?.deletingLastPathComponent() else {\n                    continue\n                }\n                let bundleURL = searchURL.appendingPathComponent(\"\\(bundleName).\\(ext)\")\n                if let bundle = Bundle(url: bundleURL) {\n                    return bundle\n                }\n            }\n        }\n        return nil\n    }\n}\n\n/// Cache for storing compiled regex patterns (to avoid redundant compilation)\n/// Note: Using NSRegularExpression instead of Swift's native Regex type for Windows compatibility.\n/// Windows Swift toolchain currently lacks _StringProcessing module support, which causes linker errors\n/// with symbols like __imp_$sSS17_StringProcessing14RegexComponent0C7BuilderMc\ninternal actor SBOMRegexCache {\n    private var cache: [String: NSRegularExpression] = [:]\n    \n    internal func get(_ pattern: String) -> NSRegularExpression? {\n        self.cache[pattern]\n    }\n    \n    internal func set(_ pattern: String, regex: NSRegularExpression) {\n        self.cache[pattern] = regex\n    }\n}\n\n/// Cache for storing resolved schema references (to avoid redundant traversals)\ninternal actor SBOMSchemaReferenceCache {\n    private var cache: [String: [String: Any]] = [:]\n    \n    internal func get(_ reference: String) -> [String: Any]? {\n        self.cache[reference]\n    }\n    \n    internal func set(_ reference: String, schema: [String: Any]) {\n        self.cache[reference] = schema\n    }\n}\n\n\n// TODO: https://github.com/swiftlang/swift-package-manager/issues/9768\n// MARK: - Base Validator\n\nstruct SBOMValidator: SBOMValidatorProtocol {\n    // MARK: - Constants\n    \n    private static let iso8601Formatter = ISO8601DateFormatter()\n    private static let dateFormatter: DateFormatter = {\n        let formatter = DateFormatter()\n        formatter.dateFormat = \"yyyy-MM-dd\"\n        return formatter\n    }()\n    \n    // Note: Using NSRegularExpression for Windows compatibility (see SBOMRegexCache comment)\n    private static let emailRegex = try! NSRegularExpression(pattern: \"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$\", options: [])\n    private static let regexCache = SBOMRegexCache()\n    private static let referenceCache = SBOMSchemaReferenceCache()\n\n    // MARK: - Factory Method\n    \n    /// Create a validator for the given spec by loading its schema from the bundle\n    static func create(for spec: SBOMSpec, bundleName: String = \"SwiftPM_SBOMModel\") async throws -> any SBOMValidatorProtocol {\n        let schemaFilename = spec.schemaFilename\n        guard let foundBundle = await BundleCache.shared.findBundle(named: bundleName),\n              let schemaURL = foundBundle.url(forResource: schemaFilename, withExtension: \"json\") else {\n            throw SBOMSchemaError.bundleNotFound(bundleName: bundleName)\n        }\n        \n        let schemaData = try Data(contentsOf: schemaURL)\n        guard let jsonObject = try JSONSerialization.jsonObject(with: schemaData) as? [String: Any] else {\n            throw SBOMSchemaError.invalidSchemaFormat(message: \"Could not parse schema as JSON dictionary\")\n        }\n        \n        return try createValidator(for: spec, schema: jsonObject)\n    }\n    \n    /// Create the appropriate validator instance for the given spec\n    private static func createValidator(for spec: SBOMSpec, schema: [String: Any]) throws -> any SBOMValidatorProtocol {\n        switch spec.concreteSpec {\n        case .cyclonedx1: // add other cyclonedx versions here\n            return CycloneDXValidator(schema: schema)\n        case .spdx3: // add other spdx versions here\n            return SPDXValidator(schema: schema)\n        }\n    }\n\n    enum StringFormat: String {\n        case dateTime = \"date-time\"\n        case date\n        case email\n        case idnEmail = \"idn-email\"\n        case uri\n        case iriReference = \"iri-reference\"\n\n        func validate(_ value: String, path: String) throws {\n            switch self {\n            case .dateTime:\n                if SBOMValidator.iso8601Formatter.date(from: value) == nil {\n                    throw SBOMValidatorError.invalidValue(path: path, message: \"invalid date-time format\")\n                }\n            case .date:\n                if SBOMValidator.dateFormatter.date(from: value) == nil {\n                    throw SBOMValidatorError.invalidValue(path: path, message: \"invalid date format\")\n                }\n            case .email, .idnEmail:\n                let range = NSRange(location: 0, length: value.utf16.count)\n                if SBOMValidator.emailRegex.firstMatch(in: value, options: [], range: range) == nil {\n                    throw SBOMValidatorError.invalidValue(path: path, message: \"invalid email format\")\n                }\n            case .uri, .iriReference:\n                if URL(string: value) == nil {\n                    throw SBOMValidatorError.invalidValue(path: path, message: \"invalid URI format\")\n                }\n            }\n        }\n    }\n\n    enum SchemaKeys {\n        static let type = \"type\"\n        static let required = \"required\"\n        static let properties = \"properties\"\n        static let items = \"items\"\n        static let enumKey = \"enum\"\n        static let pattern = \"pattern\"\n        static let format = \"format\"\n        static let ref = \"$ref\"\n        static let oneOf = \"oneOf\"\n        static let anyOf = \"anyOf\"\n        static let allOf = \"allOf\"\n        static let const = \"const\"\n        static let not = \"not\"\n        static let additionalProperties = \"additionalProperties\"\n        static let unevaluatedProperties = \"unevaluatedProperties\"\n        static let minimum = \"minimum\"\n        static let maximum = \"maximum\"\n        static let minLength = \"minLength\"\n        static let maxLength = \"maxLength\"\n        static let minItems = \"minItems\"\n        static let maxItems = \"maxItems\"\n        static let uniqueItems = \"uniqueItems\"\n    }\n\n    let schema: [String: Any]\n\n    init(schema: [String: Any]) {\n        self.schema = schema\n    }\n\n    // MARK: - SBOMValidatorProtocol Implementation\n\n    func validate(_ object: Any) async throws {\n        try await self.validateValue(object, path: \"$\")\n    }\n\n    func validateValue(_ value: Any, path: String) async throws {\n        try await self.validateValue(value, path: path, schema: self.schema)\n    }\n\n    func validateValue(_ value: Any, path: String, schema: [String: Any]) async throws {\n        if let expectedType = schema[SchemaKeys.type] as? String {\n            try self.validateType(value, expectedType: expectedType, path: path)\n        }\n\n        if let constValue = schema[SchemaKeys.const] {\n            try self.validateConst(value, expectedValue: constValue, path: path)\n        }\n        if let enumValues = schema[SchemaKeys.enumKey] as? [Any] {\n            try self.validateEnum(value, allowedValues: enumValues, path: path)\n        }\n        try self.validateNumberIfNeeded(value, schema: schema, path: path)\n\n\n        if let ref = schema[SchemaKeys.ref] as? String {\n            try await self.validateReference(value, ref: ref, path: path, schema: schema)\n        }\n        if let oneOf = schema[SchemaKeys.oneOf] as? [[String: Any]] {\n            try await self.validateOneOf(value, schemas: oneOf, path: path)\n        }\n        if let anyOf = schema[SchemaKeys.anyOf] as? [[String: Any]] {\n            try await self.validateAnyOf(value, schemas: anyOf, path: path)\n        }\n        if let allOf = schema[SchemaKeys.allOf] as? [[String: Any]] {\n            try await self.validateAllOf(value, schemas: allOf, path: path)\n        }\n        if let notSchema = schema[SchemaKeys.not] as? [String: Any] {\n            try await self.validateNot(value, schema: notSchema, path: path)\n        }\n\n        try await self.validateObjectIfNeeded(value, schema: schema, path: path)\n        try await self.validateArrayIfNeeded(value, schema: schema, path: path)\n        try await self.validateStringIfNeeded(value, schema: schema, path: path)\n    }\n\n    // MARK: - Type Validation\n\n    private func validateType(_ value: Any, expectedType: String, path: String) throws {\n        let (actualType, debugInfo) = self.determineActualType(value)\n        if expectedType == \"number\" && actualType == \"integer\" {\n            return\n        }\n        guard actualType == expectedType else {\n            throw SBOMValidatorError.typeMismatch(\n                path: path,\n                expected: expectedType,\n                actual: actualType,\n                debugInfo: debugInfo\n            )\n        }\n    }\n\n    private func determineActualType(_ value: Any) -> (type: String, debugInfo: String) {\n        switch value {\n        case let string as String:\n            return (\"string\", \"value: \\\"\\(string)\\\"\")\n        case let number as NSNumber where isBoolean(number):\n            return (\"boolean\", \"value: \\(number.boolValue)\")\n        case let number as NSNumber where isFloatType(number):\n            return (\"number\", \"value: \\(number.doubleValue)\")\n        case let number as NSNumber:\n            return (\"integer\", \"value: \\(number.intValue)\")\n        case let array as [Any]:\n            return (\"array\", \"length: \\(array.count)\")\n        case let dict as [String: Any]:\n            let keys = dict.keys.sorted().joined(separator: \", \")\n            return (\"object\", \"keys: \\(keys)\")\n        case is NSNull:\n            return (\"null\", \"null\")\n        default:\n            return (\"unknown\", \"type: \\(type(of: value))\")\n        }\n    }\n\n    private func isBoolean(_ number: NSNumber) -> Bool {\n        #if canImport(Darwin)\n        return number === kCFBooleanTrue as NSNumber || number === kCFBooleanFalse as NSNumber\n        #else\n        // On Linux, check the objCType to determine if it's a boolean\n        let objCType = String(cString: number.objCType)\n        return objCType == \"c\" || objCType == \"B\"\n        #endif\n    }\n    \n    private func isFloatType(_ number: NSNumber) -> Bool {\n        #if canImport(Darwin)\n        return CFNumberIsFloatType(number)\n        #else\n        // On Linux, check the objCType to determine if it's a floating point type\n        let objCType = String(cString: number.objCType)\n        return objCType == \"f\" || objCType == \"d\"\n        #endif\n    }\n\n    // MARK: - Schema Composition Validation\n\n    private func validateReference(_ value: Any, ref: String, path: String, schema: [String: Any]) async throws {\n        guard ref.hasPrefix(\"#/\") else { return }\n\n        let pointer = String(ref.dropFirst(2))\n        let components = pointer.components(separatedBy: \"/\")\n\n        // References starting with #/ are always resolved from the root schema (self.schema)\n        // not from the current schema being validated\n        guard let referencedSchema = await resolveReference(components: components, in: self.schema) else {\n            throw SBOMValidatorError.invalidValue(path: path, message: \"Could not resolve reference '\\(ref)'\")\n        }\n\n        try await self.validateValue(value, path: path, schema: referencedSchema)\n    }\n\n    func validateOneOf(_ value: Any, schemas: [[String: Any]], path: String) async throws {\n        var validCount = 0\n        var validationErrors: [String] = []\n        var matchingSchemas: [Int] = []\n\n        for (index, schema) in schemas.enumerated() {\n            do {\n                try await self.validateValue(value, path: path, schema: schema)\n                validCount += 1\n                matchingSchemas.append(index)\n            } catch {\n                validationErrors.append(\"Schema \\(index): \\(error.localizedDescription)\")\n            }\n        }\n\n        if validCount != 1 {\n            let valueDesc = self.describeValue(value, maxLength: 200)\n            if validCount == 0 {\n                let allErrors = validationErrors.joined(separator: \"\\n  \")\n                throw SBOMValidatorError.schemaComposition(\n                    path: path,\n                    message: \"Value does not match any oneOf schemas.\\nValue: \\(valueDesc)\\nErrors:\\n  \\(allErrors)\"\n                )\n            } else {\n                let matchingIndices = matchingSchemas.map(String.init).joined(separator: \", \")\n                throw SBOMValidatorError.schemaComposition(\n                    path: path,\n                    message: \"Value matches multiple oneOf schemas (expected exactly one). Matched \\(validCount) schemas at indices: \\(matchingIndices)\\nValue: \\(valueDesc)\"\n                )\n            }\n        }\n    }\n\n    private func validateAnyOf(_ value: Any, schemas: [[String: Any]], path: String) async throws {\n        var schemaNames: [String] = []\n\n        for (index, schema) in schemas.enumerated() {\n            do {\n                try await self.validateValue(value, path: path, schema: schema)\n                return // Successfully validated against one schema, we're done\n            } catch {\n                // Extract just the schema name/type for concise error reporting\n                let schemaName = self.extractSchemaName(from: schema, index: index)\n                schemaNames.append(schemaName)\n            }\n        }\n\n        // None of the schemas matched\n        let valueDesc = self.describeValue(value, maxLength: 200)\n\n        // Show concise list of attempted schemas\n        let summary: String\n        if schemaNames.count > 15 {\n            let shown = schemaNames.prefix(10).joined(separator: \", \")\n            summary = \"Tried \\(schemaNames.count) schemas: \\(shown), ... and \\(schemaNames.count - 10) more\"\n        } else {\n            summary = \"Tried schemas: \\(schemaNames.joined(separator: \", \"))\"\n        }\n\n        throw SBOMValidatorError.schemaComposition(\n            path: path,\n            message: \"Value does not match any anyOf schemas.\\nValue: \\(valueDesc)\\n\\(summary)\"\n        )\n    }\n\n    private func validateAllOf(_ value: Any, schemas: [[String: Any]], path: String) async throws {\n        var errors: [String] = []\n\n        for (index, schema) in schemas.enumerated() {\n            do {\n                try await self.validateValue(value, path: path, schema: schema)\n            } catch {\n                errors.append(\"Schema \\(index): \\(error.localizedDescription)\")\n            }\n        }\n\n        if !errors.isEmpty {\n            let valueDesc = self.describeValue(value, maxLength: 200)\n            let allErrors = errors.joined(separator: \"\\n  \")\n            throw SBOMValidatorError.schemaComposition(\n                path: path,\n                message: \"Value does not match all allOf schemas.\\nValue: \\(valueDesc)\\nErrors:\\n  \\(allErrors)\"\n            )\n        }\n    }\n\n    private func validateNot(_ value: Any, schema: [String: Any], path: String) async throws {\n        do {\n            try await self.validateValue(value, path: path, schema: schema)\n            let valueDesc = self.describeValue(value, maxLength: 200)\n            throw SBOMValidatorError.notSchemaViolation(path: path, valueDescription: valueDesc)\n        } catch let error as SBOMValidatorError { // rethrow notSchemaViolation errors (from nested \"not\" schemas)\n            if case .notSchemaViolation = error {\n                throw error\n            }\n            return\n        } catch { // rethrow unexpected errors (parsing errors, system errors, programming bugs)\n            throw error\n        }\n    }\n\n    // MARK: - Value Validation\n\n    private func validateConst(_ value: Any, expectedValue: Any, path: String) throws {\n        if !self.areEqual(value, expectedValue) {\n            let valueDesc = self.describeValue(value)\n            let expectedDesc = self.describeValue(expectedValue)\n            throw SBOMValidatorError.invalidValue(\n                path: path,\n                message: \"Value does not match const. Expected: \\(expectedDesc), got: \\(valueDesc)\"\n            )\n        }\n    }\n\n    private func validateEnum(_ value: Any, allowedValues: [Any], path: String) throws {\n        let isValid = allowedValues.contains { allowedValue in\n            self.areEqual(value, allowedValue)\n        }\n\n        if !isValid {\n            let valueStr = self.describeValue(value)\n            let allowedStr = allowedValues.map { self.describeValue($0) }.joined(separator: \", \")\n            throw SBOMValidatorError.invalidValue(\n                path: path,\n                message: \"Value is not one of the allowed enum values. Got: \\(valueStr), allowed: [\\(allowedStr)]\"\n            )\n        }\n    }\n\n    // MARK: - Type-Specific Validation - Object\n\n    private func validateObjectIfNeeded(_ value: Any, schema: [String: Any], path: String) async throws {\n        guard let objectValue = value as? [String: Any] else { return }\n\n        // Collect all schema metadata in a single traversal pass\n        let metadata = await self.collectSchemaMetadata(from: schema)\n        \n        // Validate required properties\n        if !metadata.required.isEmpty {\n            try self.validateRequiredProperties(objectValue, required: metadata.required, path: path)\n        }\n\n        // Validate object properties\n        if !metadata.properties.isEmpty {\n            try await self.validateObjectProperties(objectValue, properties: metadata.properties, path: path)\n        }\n\n        // Validate additional and unevaluated properties\n        try await self.validateAdditionalProperties(objectValue, schema: schema, path: path, allowedProperties: metadata.allowedProperties)\n        try await self.validateUnevaluatedProperties(objectValue, schema: schema, path: path, evaluatedProperties: metadata.evaluatedProperties)\n    }\n\n    private func validateRequiredProperties(_ object: [String: Any], required: [String], path: String) throws {\n        for property in required {\n            guard object[property] != nil else {\n                throw SBOMValidatorError.missingRequired(path: path, property: property)\n            }\n        }\n    }\n\n    private func validateObjectProperties(\n        _ object: [String: Any],\n        properties: [String: [String: Any]],\n        path: String\n    ) async throws {\n        for (key, value) in object {\n            guard let propertySchema = properties[key] else {\n                continue\n            }\n            try await self.validateValue(value, path: \"\\(path).\\(key)\", schema: propertySchema)\n        }\n    }\n\n    private func validateAdditionalProperties(_ object: [String: Any], schema: [String: Any], path: String, allowedProperties: Set<String>) async throws {\n        guard let additionalProps = schema[SchemaKeys.additionalProperties] else { return }\n\n        let extraProperties = Set(object.keys).subtracting(allowedProperties)\n\n        if let allowsAdditional = additionalProps as? Bool, !allowsAdditional {\n            guard extraProperties.isEmpty else {\n                let extraList = extraProperties.sorted().joined(separator: \", \")\n                throw SBOMValidatorError.constraintViolation(\n                    path: path,\n                    message: \"Additional properties not allowed: \\(extraList)\"\n                )\n            }\n            return\n        }\n\n        guard let additionalPropsSchema = additionalProps as? [String: Any] else { return }\n\n        for key in extraProperties {\n            guard let value = object[key] else { continue }\n            try await self.validateValue(value, path: \"\\(path).\\(key)\", schema: additionalPropsSchema)\n        }\n    }\n\n    private func validateUnevaluatedProperties(_ object: [String: Any], schema: [String: Any], path: String, evaluatedProperties: Set<String>) async throws {\n        guard let unevaluatedProps = schema[SchemaKeys.unevaluatedProperties] as? Bool,\n              !unevaluatedProps\n        else {\n            return\n        }\n\n        let unevaluated = Set(object.keys).subtracting(evaluatedProperties)\n\n        guard unevaluated.isEmpty else {\n            let unevaluatedList = unevaluated.sorted().joined(separator: \", \")\n            throw SBOMValidatorError.constraintViolation(\n                path: path,\n                message: \"Unevaluated properties found: \\(unevaluatedList)\"\n            )\n        }\n    }\n\n    // MARK: - Type-Specific Validation - Array\n\n    private func validateArrayIfNeeded(_ value: Any, schema: [String: Any], path: String) async throws {\n        guard let arrayValue = value as? [Any] else { return }\n\n        if let items = schema[SchemaKeys.items] as? [String: Any] {\n            try await self.validateArrayItems(arrayValue, itemSchema: items, path: path)\n        }\n        try self.validateArrayConstraints(arrayValue, schema: schema, path: path)\n    }\n\n    private func validateArrayItems(_ array: [Any], itemSchema: [String: Any], path: String) async throws {\n        for (index, item) in array.enumerated() {\n            try await self.validateValue(item, path: \"\\(path)[\\(index)]\", schema: itemSchema)\n        }\n    }\n\n    private func validateArrayConstraints(_ array: [Any], schema: [String: Any], path: String) throws {\n        if let minItems = schema[\"minItems\"] as? Int {\n            guard array.count >= minItems else {\n                throw SBOMValidatorError.constraintViolation(\n                    path: path,\n                    message: \"Array has fewer items than minimum. Expected at least \\(minItems), got \\(array.count)\"\n                )\n            }\n        }\n\n        if let maxItems = schema[\"maxItems\"] as? Int {\n            guard array.count <= maxItems else {\n                throw SBOMValidatorError.constraintViolation(\n                    path: path,\n                    message: \"Array has more items than maximum. Expected at most \\(maxItems), got \\(array.count)\"\n                )\n            }\n        }\n\n        if let uniqueItems = schema[\"uniqueItems\"] as? Bool, uniqueItems {\n            try self.validateUniqueItems(array, path: path)\n        }\n    }\n\n    private func validateUniqueItems(_ array: [Any], path: String) throws {\n        var seen = Set<String>()\n\n        for (index, item) in array.enumerated() {\n            // Create a canonical representation of the item for comparison\n            let itemKey = try canonicalRepresentation(of: item)\n\n            if seen.contains(itemKey) {\n                let itemDesc = self.describeValue(item, maxLength: 100)\n                throw SBOMValidatorError.constraintViolation(\n                    path: path,\n                    message: \"Array contains duplicate items. Duplicate found at index \\(index): \\(itemDesc)\"\n                )\n            }\n            seen.insert(itemKey)\n        }\n    }\n\n    private func canonicalRepresentation(of value: Any) throws -> String {\n        // Convert value to a canonical JSON string for comparison\n        // This handles objects, arrays, strings, numbers, booleans, and null\n        if let dict = value as? [String: Any] {\n            // Sort keys for consistent comparison\n            let sortedData = try JSONSerialization.data(withJSONObject: dict, options: [.sortedKeys])\n            return String(data: sortedData, encoding: .utf8) ?? \"\"\n        } else if let array = value as? [Any] {\n            let data = try JSONSerialization.data(withJSONObject: array, options: [])\n            return String(data: data, encoding: .utf8) ?? \"\"\n        } else if let string = value as? String {\n            return \"\\\"\\(string)\\\"\"\n        } else if let number = value as? NSNumber {\n            if self.isBoolean(number) {\n                return number.boolValue ? \"true\" : \"false\"\n            }\n            return \"\\(number)\"\n        } else if value is NSNull {\n            return \"null\"\n        }\n        return \"\\(value)\"\n    }\n\n    // MARK: - Type-Specific Validation - String\n\n    private func validateStringIfNeeded(_ value: Any, schema: [String: Any], path: String) async throws {\n        guard let stringValue = value as? String else { return }\n\n        try self.validateStringLength(stringValue, schema: schema, path: path)\n\n        if let pattern = schema[SchemaKeys.pattern] as? String {\n            try await self.validatePattern(stringValue, pattern: pattern, path: path)\n        }\n        if let format = schema[SchemaKeys.format] as? String {\n            try self.validateFormat(stringValue, format: format, path: path)\n        }\n    }\n\n    private func validateStringLength(_ value: String, schema: [String: Any], path: String) throws {\n        let minLength = schema[SchemaKeys.minLength] as? Int\n        let maxLength = schema[SchemaKeys.maxLength] as? Int\n        let length = value.count\n        if let min = minLength, length < min {\n            throw SBOMValidatorError.constraintViolation(\n                path: path,\n                message: \"String \\(value) is shorter than minimum length. Expected at least \\(min), got \\(length)\"\n            )\n        }\n        if let max = maxLength, length > max {\n            throw SBOMValidatorError.constraintViolation(\n                path: path,\n                message: \"String \\(value) is longer than maximum length. Expected at most \\(max), got \\(length)\"\n            )\n        }\n    }\n\n    private func validatePattern(_ value: String, pattern: String, path: String) async throws {\n        let regex = try await Self.getCachedRegex(for: pattern, path: path)\n        \n        let range = NSRange(location: 0, length: value.utf16.count)\n        guard let match = regex.firstMatch(in: value, options: [], range: range),\n              match.range.location == 0,\n              match.range.length == value.utf16.count else {\n            throw SBOMValidatorError.constraintViolation(\n                path: path,\n                message: \"String does not match pattern: \\(pattern). Value: \\\"\\(value)\\\"\"\n            )\n        }\n    }\n    \n    /// Get a cached compiled regex pattern, or compile and cache it if not present\n    /// Note: Using NSRegularExpression for Windows compatibility (see SBOMRegexCache comment)\n    private static func getCachedRegex(for pattern: String, path: String) async throws -> NSRegularExpression {\n        // Check cache first\n        if let cached = await regexCache.get(pattern) {\n            return cached\n        }\n        \n        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {\n            throw SBOMValidatorError.invalidValue(path: path, message: \"Invalid regex pattern: \\(pattern)\")\n        }\n        await regexCache.set(pattern, regex: regex)\n        return regex\n    }\n\n    private func validateFormat(_ value: String, format: String, path: String) throws {\n        guard let stringFormat = StringFormat(rawValue: format) else {\n            // JSON Schema allows unknown formats\n            return\n        }\n        try stringFormat.validate(value, path: path)\n    }\n\n    // MARK: - Type-Specific Validation - Number\n\n    private func validateNumberIfNeeded(_ value: Any, schema: [String: Any], path: String) throws {\n        guard let numberValue = value as? NSNumber else { return }\n        try self.validateNumericConstraints(numberValue, schema: schema, path: path)\n    }\n\n    private func validateNumericConstraints(_ value: NSNumber, schema: [String: Any], path: String) throws {\n        let doubleValue = value.doubleValue\n        if let minimum = schema[SchemaKeys.minimum] as? NSNumber {\n            let minValue = minimum.doubleValue\n            if doubleValue < minValue {\n                throw SBOMValidatorError.constraintViolation(\n                    path: path,\n                    message: \"Value is below minimum: \\(minimum). Got: \\(value)\"\n                )\n            }\n        }\n        if let maximum = schema[SchemaKeys.maximum] as? NSNumber {\n            let maxValue = maximum.doubleValue\n            if doubleValue > maxValue {\n                throw SBOMValidatorError.constraintViolation(\n                    path: path,\n                    message: \"Value is above maximum: \\(maximum). Got: \\(value)\"\n                )\n            }\n        }\n    }\n\n    // MARK: - Schema Resolution and Collection Helpers\n    \n    /// Struct to hold all collected schema metadata in a single pass\n    private struct SchemaMetadata {\n        var required: [String] = []\n        var properties: [String: [String: Any]] = [:]\n        var allowedProperties: Set<String> = []\n        var evaluatedProperties: Set<String> = []\n    }\n    \n    /// Collect all schema metadata in a single iterative pass for better performance\n    /// Uses an iterative approach with cycle detection to avoid stack overflow and improve performance\n    private func collectSchemaMetadata(from schema: [String: Any]) async -> SchemaMetadata {\n        var metadata = SchemaMetadata()\n        var queue: [[String: Any]] = [schema]\n        var visited = Set<String>() // Track by schema identity to avoid reprocessing\n        \n        while let current = queue.popLast() {\n            // Create unique identifier for this schema to detect cycles\n            let schemaId = self.createSchemaIdentifier(current)\n            guard !visited.contains(schemaId) else { continue }\n            visited.insert(schemaId)\n            \n            // 1. Collect required properties\n            if let required = current[SchemaKeys.required] as? [String] {\n                metadata.required.append(contentsOf: required)\n                metadata.evaluatedProperties.formUnion(required)\n            }\n            \n            // 2. Collect properties\n            if let properties = current[SchemaKeys.properties] as? [String: [String: Any]] {\n                metadata.properties.merge(properties) { _, new in new }\n                metadata.allowedProperties.formUnion(properties.keys)\n                metadata.evaluatedProperties.formUnion(properties.keys)\n            }\n            \n            // 3. Handle $ref - resolve once and add to queue\n            if let ref = current[SchemaKeys.ref] as? String, ref.hasPrefix(\"#/\") {\n                if let resolved = await self.resolveAndCacheReference(ref) {\n                    queue.append(resolved)\n                }\n            }\n            \n            // 4. Handle allOf - all schemas must be satisfied\n            if let allOf = current[SchemaKeys.allOf] as? [[String: Any]] {\n                queue.append(contentsOf: allOf)\n            }\n            \n            // 5. Handle anyOf/oneOf - collect allowed properties only\n            for compositionKey in [SchemaKeys.anyOf, SchemaKeys.oneOf] {\n                if let schemas = current[compositionKey] as? [[String: Any]] {\n                    for subSchema in schemas {\n                        // Extract properties without recursing\n                        if let properties = subSchema[SchemaKeys.properties] as? [String: [String: Any]] {\n                            metadata.allowedProperties.formUnion(properties.keys)\n                            metadata.evaluatedProperties.formUnion(properties.keys)\n                        }\n                        \n                        // Handle $ref in composition schemas\n                        if let ref = subSchema[SchemaKeys.ref] as? String, ref.hasPrefix(\"#/\") {\n                            if let resolved = await self.resolveAndCacheReference(ref),\n                               let properties = resolved[SchemaKeys.properties] as? [String: [String: Any]] {\n                                metadata.allowedProperties.formUnion(properties.keys)\n                                metadata.evaluatedProperties.formUnion(properties.keys)\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        \n        return metadata\n    }\n    \n    /// Create a unique identifier for a schema to detect cycles\n    private func createSchemaIdentifier(_ schema: [String: Any]) -> String {\n        // Use memory address for identity-based comparison\n        return String(describing: ObjectIdentifier(schema as AnyObject))\n    }\n    \n    /// Resolve reference with caching helper\n    private func resolveAndCacheReference(_ ref: String) async -> [String: Any]? {\n        let pointer = String(ref.dropFirst(2))\n        let components = pointer.components(separatedBy: \"/\")\n        return await self.resolveReference(components: components, in: self.schema)\n    }\n    \n    /// Resolve a schema reference with caching\n    private func resolveReference(components: [String], in schema: [String: Any]) async -> [String: Any]? {\n        let referenceKey = components.joined(separator: \"/\")\n        \n        if let cached = await Self.referenceCache.get(referenceKey) {\n            return cached\n        }\n        \n        var current: Any = schema\n        for component in components {\n            guard let dict = current as? [String: Any] else {\n                return nil\n            }\n            guard let next = dict[component] else {\n                return nil\n            }\n            current = next\n        }\n        \n        guard let resolvedSchema = current as? [String: Any] else {\n            return nil\n        }\n        \n        await Self.referenceCache.set(referenceKey, schema: resolvedSchema)\n        return resolvedSchema\n    }\n\n    // MARK: - Utility Functions\n\n    private func areEqual(_ lhs: Any, _ rhs: Any) -> Bool {\n        guard let lhsCanonical = try? canonicalRepresentation(of: lhs),\n              let rhsCanonical = try? canonicalRepresentation(of: rhs) else {\n            return false\n        }\n        return lhsCanonical == rhsCanonical\n    }\n\n    /// Extract a concise schema name for error reporting\n    private func extractSchemaName(from schema: [String: Any], index: Int) -> String {\n        // Check for $ref first\n        if let ref = schema[\"$ref\"] as? String {\n            let components = ref.components(separatedBy: \"/\")\n            if let last = components.last {\n                return last\n            }\n        }\n\n        // Check for const type value\n        if let constValue = schema[\"const\"] as? String {\n            return constValue\n        }\n\n        // Check for type in properties\n        if let properties = schema[\"properties\"] as? [String: Any],\n           let typeSchema = properties[\"type\"] as? [String: Any],\n           let oneOf = typeSchema[\"oneOf\"] as? [[String: Any]],\n           let firstConst = oneOf.first?[\"const\"] as? String\n        {\n            return firstConst\n        }\n\n        return \"#\\(index)\"\n    }\n\n    /// Helper function to describe a value for debugging purposes\n    func describeValue(_ value: Any, maxLength: Int = 100) -> String {\n        let description: String\n\n        switch value {\n        case let str as String:\n            description = \"\\\"\\(str)\\\"\"\n        case let num as NSNumber:\n            if self.isBoolean(num) {\n                description = \"\\(num.boolValue) (boolean)\"\n            } else if self.isFloatType(num) {\n                description = \"\\(num.doubleValue) (number)\"\n            } else {\n                description = \"\\(num.intValue) (integer)\"\n            }\n        case let array as [Any]:\n            description = \"[\\(array.count) items]\"\n        case let dict as [String: Any]:\n            let keys = dict.keys.sorted().prefix(5).joined(separator: \", \")\n            let more = dict.keys.count > 5 ? \", ...\" : \"\"\n            description = \"{keys: \\(keys)\\(more)}\"\n        case is NSNull:\n            description = \"null\"\n        default:\n            description = \"\\(type(of: value))\"\n        }\n\n        if description.count > maxLength {\n            let truncated = description.prefix(maxLength - 3)\n            return \"\\(truncated)...\"\n        }\n        return description\n    }\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Validator/SBOMValidatorProtocol.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nprotocol SBOMValidatorProtocol {\n    func validate(_ object: Any) async throws\n    func validateValue(_ value: Any, path: String) async throws\n}\n"
  },
  {
    "path": "Sources/SBOMModel/Validator/SPDXValidator.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nstruct SPDXValidator: SBOMValidatorProtocol {\n    enum SPDXKeys {\n        static let context = \"@context\"\n        static let graph = \"@graph\"\n        static let id = \"@id\"\n        static let spdxId = \"spdxId\"\n    }\n\n    private let validator: SBOMValidator\n    private let graphElementSchema: [String: Any]\n\n    init(schema: [String: Any]) {\n        self.validator = SBOMValidator(schema: schema)\n        self.graphElementSchema = SPDXValidator.extractGraphElementSchema(from: schema)\n    }\n\n    func validate(_ object: Any) async throws {\n        guard let rootDict = object as? [String: Any] else {\n            throw SBOMValidatorError.typeMismatch(\n                path: \"$\",\n                expected: \"dictionary\",\n                actual: \"other\",\n                debugInfo: \"Expected dictionary for SPDX JSON-LD document\"\n            )\n        }\n        guard let contextString = rootDict[SPDXKeys.context] as? String,\n              !contextString.isEmpty\n        else {\n            throw SBOMValidatorError.invalidValue(path: \"$\", message: \"@context must be a non-empty string\")\n        }\n        guard let graph = rootDict[SPDXKeys.graph] as? [Any],\n              !graph.isEmpty\n        else {\n            throw SBOMValidatorError.invalidValue(path: \"$\", message: \"@graph must be a non-empty array\")\n        }\n\n        for (index, element) in graph.enumerated() {\n            try await self.validateValue(element, path: \"$[@graph][\\(index)]\")\n        }\n    }\n\n    func validateValue(_ value: Any, path: String) async throws {\n        if let dictObject = value as? [String: Any] {\n            try await self.validateObjectWithSPDXRules(dictObject, path: path)\n        }\n        try await self.validator.validateValue(value, path: path, schema: self.graphElementSchema)\n    }\n\n    private func validateObjectWithSPDXRules(_ object: [String: Any], path: String) async throws {\n        let schema = self.validator.schema\n\n        if let required = schema[\"required\"] as? [String] {\n            for property in required {\n                if property == SPDXKeys.context {\n                    continue\n                }\n                // allow @id as substitute for spdxId\n                if property == SPDXKeys.spdxId && object[SPDXKeys.id] != nil {\n                    continue\n                }\n                guard object[property] != nil else {\n                    throw SBOMValidatorError.missingRequired(path: path, property: property)\n                }\n            }\n        }\n\n        if let properties = schema[\"properties\"] as? [String: [String: Any]] {\n            for (key, value) in object {\n                let propertySchema: [String: Any]?\n\n                // @id can use spdxId schema\n                if key == SPDXKeys.id, let spdxIdSchema = properties[SPDXKeys.spdxId] {\n                    propertySchema = spdxIdSchema\n                }\n                // skip spdxId if @id is present\n                else if key == SPDXKeys.spdxId && object[SPDXKeys.id] != nil {\n                    continue\n                } else {\n                    propertySchema = properties[key]\n                }\n                if let propSchema = propertySchema {\n                    try await self.validator.validateValue(value, path: \"\\(path).\\(key)\", schema: propSchema)\n                }\n            }\n        }\n\n        if let oneOf = schema[\"oneOf\"] as? [[String: Any]] {\n            try await self.validator.validateOneOf(object, schemas: oneOf, path: path)\n        }\n    }\n\n    private static func extractGraphElementSchema(from schema: [String: Any]) -> [String: Any] {\n        // Graph elements use AnyClass schema (oneOf[1]) rather than root schema\n        if let oneOf = schema[SBOMValidator.SchemaKeys.oneOf] as? [[String: Any]], oneOf.count > 1 {\n            return oneOf[1]\n        } else if let anyOf = schema[SBOMValidator.SchemaKeys.anyOf] as? [[String: Any]], !anyOf.isEmpty {\n            return anyOf[0]\n        }\n        return schema\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BinaryTarget+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport struct TSCBasic.StringError\n\n/// Information about a library from a binary dependency.\npublic struct LibraryInfo: Equatable {\n    /// The path to the binary.\n    public let libraryPath: Basics.AbsolutePath\n\n    /// The paths to the headers directories.\n    public let headersPaths: [Basics.AbsolutePath]\n    /// The path to the module map of this library.\n    public let moduleMapPath: AbsolutePath?\n}\n\n/// Information about an executable from a binary dependency.\npublic struct ExecutableInfo: Equatable {\n    /// The tool name\n    public let name: String\n\n    /// The path to the executable.\n    public let executablePath: Basics.AbsolutePath\n\n    /// Supported triples, e.g. `x86_64-apple-macosx`\n    public let supportedTriples: [Triple]\n}\n\n/// Information about a Windows DLL from a binary dependency.\npublic struct WindowsDLLInfo: Equatable {\n    /// The tool name\n    public let name: String\n\n    /// The path to the executable.\n    public let dllPath: Basics.AbsolutePath\n\n    /// Supported triples, e.g. `x86_64-apple-macosx`\n    public let supportedTriples: [Triple]\n}\n\nextension BinaryModule {\n    public func parseXCFrameworks(for triple: Triple, fileSystem: FileSystem) throws -> [LibraryInfo] {\n        // At the moment we return at most a single library.\n        let metadata = try XCFrameworkMetadata.parse(fileSystem: fileSystem, rootPath: self.artifactPath)\n        // Filter the libraries that are relevant to the triple.\n        guard let library = metadata.libraries.first(where: {\n            $0.platform == triple.asXCFrameworkPlatformString &&\n            $0.variant == triple.environment?.asXCFrameworkPlatformVariantString &&\n            $0.architectures.contains(triple.archName)\n        }) else {\n            return []\n        }\n        // Construct a LibraryInfo for the library.\n        let libraryDir = self.artifactPath.appending(component: library.libraryIdentifier)\n        let libraryFile = try AbsolutePath(validating: library.libraryPath, relativeTo: libraryDir)\n        let headersDirs = try library.headersPath\n            .map { [try AbsolutePath(validating: $0, relativeTo: libraryDir)] } ?? [] + [libraryDir]\n        return [LibraryInfo(libraryPath: libraryFile, headersPaths: headersDirs, moduleMapPath: nil)]\n    }\n\n    public func parseExecutableArtifactArchives(for triple: Triple, fileSystem: any FileSystem) throws -> [ExecutableInfo] {\n        // The host triple might contain a version which we don't want to take into account here.\n        let versionLessTriple = try triple.withoutVersion()\n        // We return at most a single variant of each artifact.\n        let metadata = try ArtifactsArchiveMetadata.parse(fileSystem: fileSystem, rootPath: self.artifactPath)\n        // Filter out everything except executables.\n        let executables = metadata.artifacts.filter { $0.value.type == .executable }\n        // Construct an ExecutableInfo for each matching variant.\n        return try executables.flatMap { entry in\n            // Filter supported triples with versionLessTriple and pass into\n            // ExecutableInfo; empty if non matching triples found.\n            try entry.value.variants.map {\n                guard let supportedTriples = $0.supportedTriples else {\n                    throw StringError(\"No \\\"supportedTriples\\\" found in the artifact metadata for \\(entry.key) in \\(self.artifactPath)\")\n                }\n                let filteredSupportedTriples = try supportedTriples\n                    .filter { try $0.withoutVersion() == versionLessTriple }\n                return ExecutableInfo(\n                    name: entry.key,\n                    executablePath: self.artifactPath.appending($0.path),\n                    supportedTriples: filteredSupportedTriples\n                )\n            }\n        }\n    }\n\n    public func parseWindowsDLLArtifactArchives(for triple: Triple, fileSystem: any FileSystem) throws -> [WindowsDLLInfo] {\n        // The host triple might contain a version which we don't want to take into account here.\n        let versionLessTriple = try triple.withoutVersion()\n        // We return at most a single variant of each artifact.\n        let metadata = try ArtifactsArchiveMetadata.parse(fileSystem: fileSystem, rootPath: self.artifactPath)\n        // Filter out everything except executables.\n        let dlls = metadata.artifacts.filter { $0.value.type == .experimentalWindowsDLL }\n        // Construct an ExecutableInfo for each matching variant.\n        return try dlls.flatMap { entry in\n            // Filter supported triples with versionLessTriple and pass into\n            // ExecutableInfo; empty if non matching triples found.\n            try entry.value.variants.map {\n                guard let supportedTriples = $0.supportedTriples else {\n                    throw StringError(\"No \\\"supportedTriples\\\" found in the artifact metadata for \\(entry.key) in \\(self.artifactPath)\")\n                }\n                let filteredSupportedTriples = try supportedTriples\n                    .filter { try $0.withoutVersion() == versionLessTriple }\n                return WindowsDLLInfo(\n                    name: entry.key,\n                    dllPath: self.artifactPath.appending($0.path),\n                    supportedTriples: filteredSupportedTriples\n                )\n            }\n        }\n    }\n\n    public func parseLibraryArtifactArchives(for triple: Triple, fileSystem: any FileSystem) throws -> [LibraryInfo] {\n        // The host triple might contain a version which we don't want to take into account here.\n        let versionLessTriple = try triple.withoutVersion()\n\n       return try ArtifactsArchiveMetadata.parse(fileSystem: fileSystem, rootPath: self.artifactPath).artifacts\n            .lazy\n            .filter { $0.value.type == .staticLibrary }\n            .flatMap { entry in\n                // Construct a `LibraryInfo` for each matching variant.\n                try entry.value.variants\n                    .lazy\n                    .filter { try ($0.supportedTriples ?? []).contains { try $0.withoutVersion() == versionLessTriple } }\n                    .map {\n                    return LibraryInfo(\n                        libraryPath: self.artifactPath.appending($0.path),\n                        headersPaths: $0.staticLibraryMetadata?.headerPaths.map { self.artifactPath.appending($0) } ?? [],\n                        moduleMapPath: $0.staticLibraryMetadata?.moduleMapPath.map { self.artifactPath.appending($0) }\n                    )\n                }\n            }\n    }\n}\n\nextension Triple {\n    func withoutVersion() throws -> Triple {\n        if isDarwin() {\n            let stringWithoutVersion = tripleString(forPlatformVersion: \"\")\n            return try Triple(stringWithoutVersion)\n        } else {\n            return self\n        }\n    }\n\n    /// Returns a representation of the receiver that can be compared with platform strings declared in an XCFramework.\n    fileprivate var asXCFrameworkPlatformString: String? {\n        switch self.os {\n        case .darwin, .wasi, .win32, .openbsd, .freebsd, .noneOS:\n            return nil // XCFrameworks do not support any of these platforms today.\n        case .macosx:\n            return \"macos\"\n        case .ios:\n            return \"ios\"\n        case .tvos:\n            return \"tvos\"\n        case .watchos:\n            return \"watchos\"\n        case .linux:\n            if environment == .android {\n                return nil\n            }\n            return \"linux\" // Only if --experimental-xcframeworks-on-linux has been passed\n        default:\n            return nil // XCFrameworks do not support any of these platforms today.\n        }\n    }\n}\n\nextension Triple.Environment {\n    fileprivate var asXCFrameworkPlatformVariantString: String? {\n        switch self {\n        case .simulator:\n            return \"simulator\"\n        case .macabi:\n            return \"maccatalyst\"\n        default:\n            return nil // XCFrameworks do not support any of these platform variants today.\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildParameters/BuildParameters+APIDigester.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nextension BuildParameters {\n    public enum APIDigesterMode: Encodable {\n        case generateBaselines(baselinesDirectory: AbsolutePath, modulesRequestingBaselines: Set<String>)\n        case compareToBaselines(baselinesDirectory: AbsolutePath, modulesToCompare: Set<String>, breakageAllowListPath: AbsolutePath?)\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildParameters/BuildParameters+Debugging.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.Triple\nimport enum PackageModel.BuildConfiguration\n\nextension BuildParameters {\n    public struct Debugging: Encodable {\n        public init(\n            debugInfoFormat: DebugInfoFormat = .dwarf,\n            triple: Triple,\n            shouldEnableDebuggingEntitlement: Bool,\n            omitFramePointers: Bool?\n        ) {\n            self.debugInfoFormat = debugInfoFormat\n\n            // Per rdar://112065568 for backtraces to work on macOS a special entitlement needs to be granted on the final\n            // executable.\n            self.shouldEnableDebuggingEntitlement = triple.isMacOSX && shouldEnableDebuggingEntitlement\n            // rdar://117578677: frame-pointer to support backtraces\n            // this can be removed once the backtracer uses DWARF instead of frame pointers\n            if let omitFramePointers {\n                // if set, we respect user's preference\n                self.omitFramePointers = omitFramePointers\n            } else if triple.isLinux() {\n                // on Linux we preserve frame pointers by default\n                self.omitFramePointers = false\n            } else {\n                // otherwise, use the platform default\n                self.omitFramePointers = nil\n            }\n        }\n\n        public var debugInfoFormat: DebugInfoFormat\n        \n        /// Whether the produced executable should be codesigned with the debugging entitlement, enabling enhanced\n        /// backtraces on macOS.\n        public var shouldEnableDebuggingEntitlement: Bool\n\n        /// Whether to omit frame pointers\n        public var omitFramePointers: Bool?\n    }\n\n    /// Represents the debugging strategy.\n    ///\n    /// Swift binaries requires the swiftmodule files in order for lldb to work.\n    /// On Darwin, linker can directly take the swiftmodule file path using the\n    /// -add_ast_path flag. On other platforms, we convert the swiftmodule into\n    /// an object file using Swift's modulewrap tool.\n    public enum DebuggingStrategy {\n        case swiftAST\n        case modulewrap\n    }\n\n    /// The debugging strategy according to the current build parameters.\n    public var debuggingStrategy: DebuggingStrategy? {\n        guard configuration == .debug, prepareForIndexing == .off else {\n            return nil\n        }\n\n        if self.triple.isApple() {\n            return .swiftAST\n        }\n        return .modulewrap\n    }\n\n    /// Represents the debug information format.\n    ///\n    /// The debug information format controls the format of the debug information\n    /// that the compiler generates.  Some platforms support debug information\n    // formats other than DWARF.\n    public enum DebugInfoFormat: String, Encodable {\n        /// DWARF debug information format, the default format used by Swift.\n        case dwarf\n        /// CodeView debug information format, used on Windows.\n        case codeview\n        /// No debug information to be emitted.\n        case none\n    }\n\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildParameters/BuildParameters+Driver.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nextension BuildParameters {\n    /// A mode for explicit import checking\n    public enum TargetDependencyImportCheckingMode : Codable {\n        case none\n        case warn\n        case error\n    }\n\n    /// Build parameters related to Swift Driver grouped in a single type to aggregate those in one place.\n    public struct Driver: Encodable {\n        public init(\n            canRenameEntrypointFunctionName: Bool = false,\n            enableParseableModuleInterfaces: Bool = false,\n            explicitTargetDependencyImportCheckingMode: TargetDependencyImportCheckingMode = .none,\n            useIntegratedSwiftDriver: Bool = false,\n            isPackageAccessModifierSupported: Bool = false,\n            codesizeProfileEnabled: Bool = false,\n            emitSILFiles: Bool = false,\n            emitIRFiles: Bool = false,\n            emitOptimizationRecord: Bool = false,\n            silOutputDirectory: AbsolutePath? = nil,\n            irOutputDirectory: AbsolutePath? = nil,\n            optimizationRecordDirectory: AbsolutePath? = nil\n        ) {\n            self.canRenameEntrypointFunctionName = canRenameEntrypointFunctionName\n            self.enableParseableModuleInterfaces = enableParseableModuleInterfaces\n            self.explicitTargetDependencyImportCheckingMode = explicitTargetDependencyImportCheckingMode\n            self.useIntegratedSwiftDriver = useIntegratedSwiftDriver\n            self.isPackageAccessModifierSupported = isPackageAccessModifierSupported\n            self.codesizeProfileEnabled = codesizeProfileEnabled\n            self.emitSILFiles = emitSILFiles\n            self.emitIRFiles = emitIRFiles\n            self.emitOptimizationRecord = emitOptimizationRecord\n            self.silOutputDirectory = silOutputDirectory\n            self.irOutputDirectory = irOutputDirectory\n            self.optimizationRecordDirectory = optimizationRecordDirectory\n        }\n\n        /// Whether to enable the entry-point-function-name feature.\n        public var canRenameEntrypointFunctionName: Bool\n\n        /// A flag that indicates this build should check whether targets only import.\n        /// their explicitly-declared dependencies\n        public var explicitTargetDependencyImportCheckingMode: TargetDependencyImportCheckingMode\n\n        /// Whether to enable generation of `.swiftinterface` files alongside.\n        /// `.swiftmodule`s.\n        public var enableParseableModuleInterfaces: Bool\n\n        /// Whether to use the integrated Swift Driver rather than shelling out\n        /// to a separate process.\n        public var useIntegratedSwiftDriver: Bool\n\n        /// Whether the version of Swift Driver used in the currently selected toolchain\n        /// supports `-package-name` options.\n        @_spi(SwiftPMInternal)\n        public var isPackageAccessModifierSupported: Bool\n\n        /// Whether code size profiling mode is enabled\n        public var codesizeProfileEnabled: Bool\n\n        /// Whether to emit SIL files\n        public var emitSILFiles: Bool\n\n        /// Whether to emit LLVM IR files\n        public var emitIRFiles: Bool\n\n        /// Whether to emit optimization records\n        public var emitOptimizationRecord: Bool\n\n        /// Output directory for SIL files.\n        public var silOutputDirectory: AbsolutePath?\n\n        /// Output directory for IR files.\n        public var irOutputDirectory: AbsolutePath?\n\n        /// Output directory for optimization record files.\n        public var optimizationRecordDirectory: AbsolutePath?\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildParameters/BuildParameters+Linking.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension BuildParameters {\n    /// An optional intermodule optimization to run at link time.\n    ///\n    /// When using Link Time Optimization (LTO for short) the swift and clang\n    /// compilers produce objects containing containing a higher level\n    /// representation of the program bitcode instead of machine code. The\n    /// linker combines these objects together performing additional\n    /// optimizations with visibility into each module/object, resulting in a\n    /// further optimized version of the executable.\n    ///\n    /// Using LTO can have significant impact on compile times, however can be\n    /// used to dramatically reduce code-size in some cases.\n    ///\n    /// Note: Bitcode objects and machine code objects can be linked together.\n    public enum LinkTimeOptimizationMode: String, Encodable {\n        /// The \"standard\" LTO mode designed to produce minimal code sign.\n        ///\n        /// Full LTO can lead to large link times. Consider using thin LTO if\n        /// build time is more important than minimizing binary size.\n        case full\n        /// An LTO mode designed to scale better with input size.\n        ///\n        /// Thin LTO typically results in faster link times than traditional LTO.\n        /// However, thin LTO may not result in binary as small as full LTO.\n        case thin\n    }\n\n    /// Build parameters related to linking grouped in a single type to aggregate those in one place.\n    public struct Linking: Encodable {\n        /// Whether to disable dead code stripping by the linker\n        public var linkerDeadStrip: Bool\n        \n        public var linkTimeOptimizationMode: LinkTimeOptimizationMode?\n\n        /// Disables adding $ORIGIN/@loader_path to the rpath, useful when deploying\n        public var shouldDisableLocalRpath: Bool\n\n        /// If should link the Swift stdlib statically.\n        public var shouldLinkStaticSwiftStdlib: Bool\n\n        public init(\n            linkerDeadStrip: Bool = true,\n            linkTimeOptimizationMode: LinkTimeOptimizationMode? = nil,\n            shouldDisableLocalRpath: Bool = false,\n            shouldLinkStaticSwiftStdlib: Bool = false\n        ) {\n            self.linkerDeadStrip = linkerDeadStrip\n            self.linkTimeOptimizationMode = linkTimeOptimizationMode\n            self.shouldDisableLocalRpath = shouldDisableLocalRpath\n            self.shouldLinkStaticSwiftStdlib = shouldLinkStaticSwiftStdlib\n        }\n    }\n}\n\nextension [String] {\n    /// Converts a set of C compiler flags into an equivalent set to be\n    /// indirected through the Swift compiler instead.\n    public func asSwiftcCCompilerFlags() -> Self {\n        self.flatMap { [\"-Xcc\", $0] }\n    }\n\n    /// Converts a set of C++ compiler flags into an equivalent set to be\n    /// indirected through the Swift compiler instead.\n    public func asSwiftcCXXCompilerFlags() -> Self {\n        _ = self.flatMap { [\"-Xcxx\", $0] }\n        // TODO: Pass -Xcxx flags to swiftc (#6491)\n        // Remove fatal error when downstream support arrives.\n        fatalError(\"swiftc does support -Xcxx flags yet.\")\n    }\n\n    /// Converts a set of linker flags into an equivalent set to be indirected\n    /// through the Swift compiler instead.\n    ///\n    /// Some arguments can be passed directly to the Swift compiler. We omit\n    /// prefixing these arguments (in both the \"-option value\" and\n    /// \"-option[=]value\" forms) with \"-Xlinker\". All other arguments are\n    /// prefixed with \"-Xlinker\".\n    public func asSwiftcLinkerFlags() -> Self {\n        // Arguments that can be passed directly to the Swift compiler and\n        // doesn't require -Xlinker prefix.\n        //\n        // We do this to avoid sending flags like linker search path at the end\n        // of the search list.\n        let directSwiftLinkerArgs = [\"-L\"]\n\n        var flags: [String] = []\n        var it = self.makeIterator()\n        while let flag = it.next() {\n            if directSwiftLinkerArgs.contains(flag) {\n                // `<option> <value>` variant.\n                flags.append(flag)\n                guard let nextFlag = it.next() else {\n                    // We expected a flag but don't have one.\n                    continue\n                }\n                flags.append(nextFlag)\n            } else if directSwiftLinkerArgs.contains(where: { flag.hasPrefix($0) }) {\n                // `<option>[=]<value>` variant.\n                flags.append(flag)\n            } else {\n                flags += [\"-Xlinker\", flag]\n            }\n        }\n        return flags\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildParameters/BuildParameters+Output.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nextension BuildParameters {\n    /// Build parameters related to output and logging grouped in a single type to aggregate those in one place.\n    public struct Output: Encodable {\n        public init(\n            isColorized: Bool = false,\n            isVerbose: Bool = false,\n            enableTaskBacktraces: Bool = false\n        ) {\n            self.isColorized = isColorized\n            self.isVerbose = isVerbose\n            self.enableTaskBacktraces = enableTaskBacktraces\n        }\n\n        public var isColorized: Bool\n\n        public var isVerbose: Bool\n\n        public var enableTaskBacktraces: Bool\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildParameters/BuildParameters+Testing.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport struct Basics.Triple\nimport enum PackageModel.BuildConfiguration\n\nextension BuildParameters {\n    /// Represents the test product style.\n    public enum TestProductStyle: Encodable {\n        /// Test product is a loadable bundle. This style is used on Darwin platforms and, for XCTest tests, relies on the Objective-C\n        /// runtime to automatically discover all tests.\n        case loadableBundle\n\n        /// Test product is an executable which serves as the testing entry point. This style is used on non-Darwin platforms and,\n        /// for XCTests, relies on the testing entry point file to indicate which tests to run. By default, the test entry point file is\n        /// synthesized automatically, and uses indexer data to locate all tests and run them. But the entry point may be customized\n        /// in one of two ways: if a path to a test entry point file was explicitly passed via the\n        /// `--experimental-test-entry-point-path <file>` option, that file is used, otherwise if an `XCTMain.swift`\n        /// (formerly `LinuxMain.swift`) file is located in the package, it is used.\n        ///\n        /// - Parameter explicitlyEnabledDiscovery: Whether test discovery generation was forced by passing\n        ///   `--enable-test-discovery`, overriding any custom test entry point file specified via other CLI options or located in\n        ///   the package.\n        /// - Parameter explicitlySpecifiedPath: The path to the test entry point file, if one was specified explicitly via\n        ///   `--experimental-test-entry-point-path <file>`.\n        case entryPointExecutable(\n            explicitlyEnabledDiscovery: Bool,\n            explicitlySpecifiedPath: AbsolutePath?\n        )\n\n        /// The explicitly-specified entry point file path, if this style of test product supports it and a path was specified.\n        public var explicitlySpecifiedEntryPointPath: AbsolutePath? {\n            switch self {\n            case .loadableBundle:\n                return nil\n            case .entryPointExecutable(explicitlyEnabledDiscovery: _, explicitlySpecifiedPath: let entryPointPath):\n                return entryPointPath\n            }\n        }\n\n        public enum DiscriminatorKeys: String, Codable {\n            case loadableBundle\n            case entryPointExecutable\n        }\n\n        public enum CodingKeys: CodingKey {\n            case _case\n            case explicitlyEnabledDiscovery\n            case explicitlySpecifiedPath\n        }\n\n        public func encode(to encoder: Encoder) throws {\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            switch self {\n            case .loadableBundle:\n                try container.encode(DiscriminatorKeys.loadableBundle, forKey: ._case)\n            case .entryPointExecutable(let explicitlyEnabledDiscovery, let explicitlySpecifiedPath):\n                try container.encode(DiscriminatorKeys.entryPointExecutable, forKey: ._case)\n                try container.encode(explicitlyEnabledDiscovery, forKey: .explicitlyEnabledDiscovery)\n                try container.encode(explicitlySpecifiedPath, forKey: .explicitlySpecifiedPath)\n            }\n        }\n    }\n\n    /// Build parameters related to testing grouped in a single type to aggregate those in one place.\n    public struct Testing: Encodable {\n        /// Whether to enable code coverage.\n        public var enableCodeCoverage: Bool\n\n        /// Whether building for testability is explicitly enabled or disabled.\n        package var explicitlyEnabledTestability: Bool?\n\n        /// Whether or not to enable the experimental test output mode.\n        public var experimentalTestOutput: Bool\n\n        /// Whether to force test discovery.\n        fileprivate var explicitlyEnabledDiscovery: Bool\n\n        /// The path to the test entry point file, if one was specified explicitly\n        /// via `--experimental-test-entry-point-path <file>`.\n        fileprivate var explicitlySpecifiedPath: AbsolutePath?\n\n        public init(\n            enableCodeCoverage: Bool = false,\n            enableTestability: Bool? = nil,\n            experimentalTestOutput: Bool = false,\n            forceTestDiscovery: Bool = false,\n            testEntryPointPath: AbsolutePath? = nil\n        ) {\n            self.enableCodeCoverage = enableCodeCoverage\n            self.experimentalTestOutput = experimentalTestOutput\n            self.explicitlyEnabledTestability = enableTestability\n            self.explicitlyEnabledDiscovery = forceTestDiscovery\n            self.explicitlySpecifiedPath = testEntryPointPath\n        }\n    }\n\n    /// Whether building for testability is enabled.\n    public var enableTestability: Bool {\n        // decide on testability based on debug/release config\n        // the goals of this being based on the build configuration is\n        // that `swift build` followed by a `swift test` will need to do minimal rebuilding\n        // given that the default configuration for `swift build` is debug\n        // and that `swift test` normally requires building with testable enabled.\n        // when building and testing in release mode, one can use the '--disable-testable-imports' flag\n        // to disable testability in `swift test`, but that requires that the tests do not use the testable imports feature\n        self.testingParameters.explicitlyEnabledTestability ?? (self.configuration == .debug)\n    }\n\n    /// The style of test product to produce.\n    public var testProductStyle: TestProductStyle {\n        return triple.isDarwin() ? .loadableBundle : .entryPointExecutable(\n            explicitlyEnabledDiscovery: testingParameters.explicitlyEnabledDiscovery,\n            explicitlySpecifiedPath: testingParameters.explicitlySpecifiedPath\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildParameters/BuildParameters.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport class Foundation.ProcessInfo\nimport PackageModel\nimport PackageGraph\nimport TSCBasic\n\npublic struct BuildParameters: Encodable {\n    public enum PrepareForIndexingMode: Encodable {\n        /// Perform a normal build and don't prepare for indexing\n        case off\n        /// Prepare for indexing but don't pass `-experimental-lazy-typecheck`.\n        ///\n        /// This is intended as a workaround if lazy type checking is causing compiler crashes.\n        case noLazy\n        /// Do minimal build to prepare for indexing\n        case on\n    }\n\n    /// Mode for the indexing-while-building feature.\n    public enum IndexStoreMode: String, Encodable, CaseIterable {\n        /// Index store should be enabled.\n        case on\n        /// Index store should be disabled.\n        case off\n        /// Index store should be enabled in debug configuration.\n        case auto\n    }\n\n    /// The destination for which code should be compiled for.\n    public enum Destination: Hashable, Encodable {\n        /// The destination for which build tools are compiled.\n        case host\n\n        /// The destination for which end products are compiled.\n        case target\n    }\n\n    /// The destination these parameters are going to be used for.\n    public var destination: Destination\n\n    /// The path to the data directory.\n    public var dataPath: Basics.AbsolutePath\n\n    /// The build configuration.\n    public var configuration: BuildConfiguration\n\n    /// The toolchain.\n    public var toolchain: Toolchain { _toolchain.toolchain }\n    private let _toolchain: _Toolchain\n\n    @available(*, deprecated, renamed: \"triple\", message: \"Use separate `BuildParameters` values for host and target.\")\n    public var targetTriple: Triple { self.triple }\n\n    /// The triple for which the code is built using these build parameters.\n    public var triple: Triple\n\n    /// Extra build flags.\n    public var flags: BuildFlags\n\n    /// An array of paths to search for pkg-config `.pc` files.\n    public var pkgConfigDirectories: [Basics.AbsolutePath]\n\n    /// Paths to toolset files specified on the command line via `--toolset`.\n    public var customToolsetPaths: [Basics.AbsolutePath]\n\n    /// The architectures to build for.\n    // FIXME: this may be inconsistent with `targetTriple`.\n    public var architectures: [String]?\n\n    /// How many jobs should llbuild and the Swift compiler spawn.\n    public var workers: UInt32\n\n    /// Which compiler sanitizers should be enabled.\n    public var sanitizers: EnabledSanitizers\n\n    /// The mode to use for indexing-while-building feature.\n    public var indexStoreMode: IndexStoreMode\n\n    /// Whether to create dylibs for dynamic library products.\n    public var shouldCreateDylibForDynamicProducts: Bool\n\n    /// The current build environment.\n    public var buildEnvironment: BuildEnvironment {\n        BuildEnvironment(platform: currentPlatform, configuration: configuration)\n    }\n\n    /// The current platform we're building for.\n    var currentPlatform: PackageModel.Platform {\n        if self.triple.isDarwin() {\n            switch self.triple.darwinPlatform {\n            case .iOS(.catalyst):\n                return .macCatalyst\n            case .iOS(.device), .iOS(.simulator):\n                return .iOS\n            case .tvOS:\n                return .tvOS\n            case .watchOS:\n                return .watchOS\n            case .macOS, nil:\n                return .macOS\n            }\n        } else if self.triple.isAndroid() {\n            return .android\n        } else if self.triple.isWASI() {\n            return .wasi\n        } else if self.triple.isWindows() {\n            return .windows\n        } else if self.triple.isOpenBSD() {\n            return .openbsd\n        } else if self.triple.isFreeBSD() {\n            return .freebsd\n        } else {\n            return .linux\n        }\n    }\n\n    public var buildSystemKind: BuildSystemProvider.Kind\n\n    public var shouldSkipBuilding: Bool\n\n    public var printPIFManifestGraphviz: Bool = false\n\n    /// Do minimal build to prepare for indexing\n    public var prepareForIndexing: PrepareForIndexingMode\n\n    /// Support Experimental XCF on Linux\n    public var enableXCFrameworksOnLinux: Bool\n\n    /// Build parameters related to debugging.\n    public var debuggingParameters: Debugging\n\n    /// Build parameters related to Swift Driver.\n    public var driverParameters: Driver\n\n    /// Build parameters related to linking.\n    public var linkingParameters: Linking\n\n    /// Build parameters related to output and logging.\n    public var outputParameters: Output\n\n    /// Build parameters related to testing.\n    public var testingParameters: Testing\n\n    /// The mode to run the API digester in, if any.\n    public var apiDigesterMode: APIDigesterMode?\n\n    public init(\n        destination: Destination,\n        dataPath: Basics.AbsolutePath,\n        configuration: BuildConfiguration,\n        toolchain: Toolchain,\n        triple: Triple? = nil,\n        flags: BuildFlags,\n        buildSystemKind: BuildSystemProvider.Kind,\n        pkgConfigDirectories: [Basics.AbsolutePath] = [],\n        customToolsetPaths: [Basics.AbsolutePath] = [],\n        architectures: [String]? = nil,\n        workers: UInt32 = UInt32(ProcessInfo.processInfo.activeProcessorCount),\n        shouldCreateDylibForDynamicProducts: Bool = true,\n        sanitizers: EnabledSanitizers = EnabledSanitizers(),\n        indexStoreMode: IndexStoreMode = .auto,\n        shouldSkipBuilding: Bool = false,\n        prepareForIndexing: PrepareForIndexingMode = .off,\n        enableXCFrameworksOnLinux: Bool = false,\n        debuggingParameters: Debugging? = nil,\n        driverParameters: Driver = .init(),\n        linkingParameters: Linking = .init(),\n        outputParameters: Output = .init(),\n        testingParameters: Testing = .init(),\n        apiDigesterMode: APIDigesterMode? = nil\n    ) throws {\n        // Default to the unversioned triple if none is provided so that we defer to the package's requested deployment target, for Darwin platforms. For other platforms, continue to include the version since those don't have the concept of a package-specified version, and the version is meaningful for some platforms including Android and FreeBSD.\n        let triple = try triple ?? {\n            let hostTriple = try Triple.getHostTriple(\n                    usingSwiftCompiler: toolchain.swiftCompilerPath)\n            return hostTriple.versionedTriple.isDarwin() ? hostTriple.unversionedTriple : hostTriple.versionedTriple\n        }()\n\n        self.debuggingParameters = debuggingParameters ?? .init(\n            triple: triple,\n            shouldEnableDebuggingEntitlement: configuration == .debug,\n            omitFramePointers: nil\n        )\n\n        self.destination = destination\n        self.dataPath = dataPath\n        self.configuration = configuration\n        self._toolchain = _Toolchain(toolchain: toolchain)\n        self.triple = triple\n        self.buildSystemKind = buildSystemKind\n        switch self.debuggingParameters.debugInfoFormat {\n        case .dwarf:\n            var flags = flags\n            // DWARF requires lld as link.exe expects CodeView debug info.\n            self.flags = flags.merging(triple.isWindows() ? BuildFlags(\n                cCompilerFlags: [\"-gdwarf\"].constructBuildFlags(source: .debugging),\n                cxxCompilerFlags: [\"-gdwarf\"].constructBuildFlags(source: .debugging),\n                swiftCompilerFlags: [\"-g\", \"-use-ld=lld\"].constructBuildFlags(source: .debugging),\n                linkerFlags: [\"-debug:dwarf\"].constructBuildFlags(source: .debugging)\n            ) : BuildFlags(cCompilerFlags: [\"-g\"].constructBuildFlags(source: .debugging), cxxCompilerFlags: [\"-g\"].constructBuildFlags(source: .debugging), swiftCompilerFlags: [BuildFlag(value: \"-g\", source: .debugging)]))\n        case .codeview:\n            if !triple.isWindows() {\n                throw StringError(\"CodeView debug information is currently not supported on \\(triple.osName)\")\n            }\n            var flags = flags\n            self.flags = flags.merging(BuildFlags(\n                cCompilerFlags: [\"-g\"].constructBuildFlags(source: .debugging),\n                cxxCompilerFlags: [\"-g\"].constructBuildFlags(source: .debugging),\n                swiftCompilerFlags: [\"-g\", \"-debug-info-format=codeview\"].constructBuildFlags(source: .debugging),\n                linkerFlags: [\"-debug\"].constructBuildFlags(source: .debugging)\n            ))\n        case .none:\n            var flags = flags\n            self.flags = flags.merging(BuildFlags(\n                cCompilerFlags: [\"-g0\"].constructBuildFlags(source: .debugging),\n                cxxCompilerFlags: [\"-g0\"].constructBuildFlags(source: .debugging),\n                swiftCompilerFlags: [BuildFlag(value: \"-gnone\", source: .debugging)]\n            ))\n        }\n        self.pkgConfigDirectories = pkgConfigDirectories\n        self.customToolsetPaths = customToolsetPaths\n        self.architectures = architectures\n        self.workers = workers\n        self.shouldCreateDylibForDynamicProducts = shouldCreateDylibForDynamicProducts\n        self.sanitizers = sanitizers\n        self.indexStoreMode = indexStoreMode\n        self.shouldSkipBuilding = shouldSkipBuilding\n        self.prepareForIndexing = prepareForIndexing\n        self.enableXCFrameworksOnLinux = enableXCFrameworksOnLinux\n        self.driverParameters = driverParameters\n        self.linkingParameters = linkingParameters\n        self.outputParameters = outputParameters\n        self.testingParameters = testingParameters\n        self.apiDigesterMode = apiDigesterMode\n    }\n\n    /// The path to the build directory (inside the data directory).\n    public var buildPath: Basics.AbsolutePath {\n        // TODO: query the build system for this.\n        switch buildSystemKind {\n        case .xcode, .swiftbuild:\n            var configDir: String = configuration.dirname.capitalized\n            if self.triple.isMacOSX {\n                // no suffix\n            } else if self.triple.isAndroid() {\n                configDir += \"-android\"\n            } else if self.triple.isWasm {\n                configDir += \"-webassembly\"\n            } else {\n                configDir += \"-\" + (self.triple.darwinPlatform?.platformName ?? self.triple.osNameUnversioned)\n            }\n            return dataPath.appending(components: \"Products\", configDir)\n        case .native:\n            return dataPath.appending(component: configuration.dirname)\n        }\n    }\n\n    /// The path to the index store directory.\n    public var indexStore: Basics.AbsolutePath {\n        assert(indexStoreMode != .off, \"index store is disabled\")\n        return buildPath.appending(components: \"index\", \"store\")\n    }\n\n    /// The path to the code coverage directory.\n    public var codeCovPath: Basics.AbsolutePath {\n        return buildPath.appending(\"codecov\")\n    }\n\n    /// The path to the code coverage profdata file.\n    public var codeCovDataFile: Basics.AbsolutePath {\n        return codeCovPath.appending(\"default.profdata\")\n    }\n\n    public var llbuildManifest: Basics.AbsolutePath {\n        // FIXME: this path isn't specific to `BuildParameters` due to its use of `..`\n        // FIXME: it should be calculated in a different place\n        return dataPath.appending(components: \"..\", configuration.dirname + \".yaml\")\n    }\n\n    public var pifManifest: Basics.AbsolutePath {\n        // FIXME: this path isn't specific to `BuildParameters` due to its use of `..`\n        // FIXME: it should be calculated in a different place\n        return dataPath.appending(components: \"..\", \"manifest.pif\")\n    }\n\n    public var buildDescriptionPath: Basics.AbsolutePath {\n        // FIXME: this path isn't specific to `BuildParameters`, should be moved one directory level higher\n        return buildPath.appending(components: \"description.json\")\n    }\n\n    public var testOutputPath: Basics.AbsolutePath {\n        return buildPath.appending(component: \"testOutput.txt\")\n    }\n    /// Returns the path to the binary of a product for the current build parameters.\n    public func binaryPath(for product: ResolvedProduct) throws -> Basics.AbsolutePath {\n        return try buildPath.appending(binaryRelativePath(for: product))\n    }\n\n    public func macroBinaryPath(_ module: ResolvedModule) throws -> Basics.AbsolutePath {\n        assert(module.type == .macro)\n        #if BUILD_MACROS_AS_DYLIBS\n        return buildPath.appending(try dynamicLibraryPath(for: module.name))\n        #else\n        return buildPath.appending(try executablePath(for: module.name))\n        #endif\n    }\n\n    /// Returns the path to the dynamic library of a product for the current build parameters.\n    private func dynamicLibraryPath(for name: String) throws -> Basics.RelativePath {\n        try RelativePath(validating: \"\\(self.triple.dynamicLibraryPrefix)\\(name)\\(self.suffix)\\(self.triple.dynamicLibraryExtension)\")\n    }\n\n    /// Returns the path to the executable of a product for the current build parameters.\n    package func executablePath(for name: String) throws -> Basics.RelativePath {\n        try RelativePath(validating: \"\\(name)\\(self.suffix)\\(self.triple.executableExtension)\")\n    }\n\n    /// Returns the path to the binary of a product for the current build parameters, relative to the build directory.\n    public func binaryRelativePath(for product: ResolvedProduct) throws -> Basics.RelativePath {\n        switch product.type {\n        case .executable, .snippet:\n            return try executablePath(for: product.name)\n        case .library(.static):\n            return try RelativePath(validating: \"lib\\(product.name)\\(self.suffix)\\(self.triple.staticLibraryExtension)\")\n        case .library(.dynamic):\n            return try dynamicLibraryPath(for: product.name)\n        case .library(.automatic), .plugin:\n            fatalError(\"\\(#file):\\(#line) - Illegal call of function \\(#function) with automatica library and plugin\")\n        case .test:\n            switch buildSystemKind {\n            case .native, .xcode:\n                let base = \"\\(product.name).xctest\"\n                if self.triple.isDarwin() {\n                    return try RelativePath(validating: \"\\(base)/Contents/MacOS/\\(product.name)\")\n                } else {\n                    return try RelativePath(validating: base)\n                }\n            case .swiftbuild:\n                if self.triple.isDarwin() {\n                    let base = \"\\(product.name).xctest\"\n                    return try RelativePath(validating: \"\\(base)/Contents/MacOS/\\(product.name)\")\n                } else {\n                    var base = \"\\(product.name)-test-runner\"\n                    let ext = self.triple.executableExtension\n                    if !ext.isEmpty {\n                        base += ext\n                    }\n                    return try RelativePath(validating: base)\n                }\n            }\n        case .macro:\n            #if BUILD_MACROS_AS_DYLIBS\n            return try dynamicLibraryPath(for: product.name)\n            #else\n            return try executablePath(for: product.name)\n            #endif\n        }\n    }\n}\n\n/// A shim struct for toolchain so we can encode it without having to write encode(to:) for\n/// entire BuildParameters by hand.\nprivate struct _Toolchain: Encodable {\n    let toolchain: Toolchain\n\n    enum CodingKeys: String, CodingKey {\n        case swiftCompiler\n        case clangCompiler\n        case extraCCFlags\n        case extraSwiftCFlags\n        case extraCPPFlags\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        try container.encode(toolchain.swiftCompilerPath, forKey: .swiftCompiler)\n        try container.encode(toolchain.getClangCompiler(), forKey: .clangCompiler)\n\n        try container.encode(toolchain.extraFlags.cCompilerFlags, forKey: .extraCCFlags)\n        // Maintaining `extraCPPFlags` key for compatibility with older encoding.\n        try container.encode(toolchain.extraFlags.cxxCompilerFlags, forKey: .extraCPPFlags)\n        try container.encode(toolchain.extraFlags.swiftCompilerFlags, forKey: .extraSwiftCFlags)\n        try container.encode(toolchain.swiftCompilerPath, forKey: .swiftCompiler)\n    }\n}\n\nextension Triple {\n    public var supportsTestSummary: Bool {\n        return !self.isWindows()\n    }\n}\n\nextension BuildParameters {\n    /// Suffix appended to build manifest nodes to distinguish nodes created for tools from nodes created for\n    /// end products, i.e. nodes for host vs target triples.\n    package var suffix: String {\n        if destination == .host { \"-tool\" } else { \"\" }\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildSystem/BuildSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageGraph\n\nimport enum PackageModel.TraitConfiguration\n\nimport protocol TSCBasic.OutputByteStream\n\n/// An enum representing what subset of the package to build.\npublic enum BuildSubset {\n    /// Represents the subset of all products and non-test targets.\n    case allExcludingTests\n\n    /// Represents the subset of all products and targets.\n    case allIncludingTests\n\n    /// Represents a specific product. Allows to set a specific\n    /// destination if it's known.\n    case product(String, for: BuildParameters.Destination? = .none)\n\n    /// Represents a specific target. Allows to set a specific\n    /// destination if it's known.\n    case target(String, for: BuildParameters.Destination? = .none)\n}\n\n/// Represents possible extra build outputs for a build. Some build systems\n/// can produce certain extra outputs in the process of building. Not all\n/// build systems can produce all possible build outputs. Check the build\n/// result for indication that the output was produced.\npublic enum BuildOutput: Equatable {\n    public enum SymbolGraphAccessLevel: String {\n        case `private`, `fileprivate`, `internal`, `package`, `public`, `open`\n    }\n    public struct SymbolGraphOptions: Equatable {\n        public var prettyPrint: Bool\n        public var minimumAccessLevel: SymbolGraphAccessLevel\n        public var includeInheritedDocs: Bool\n        public var includeSynthesized: Bool\n        public var includeSPI: Bool\n        public var emitExtensionBlocks: Bool\n\n        public init(\n            prettyPrint: Bool = false,\n            minimumAccessLevel: SymbolGraphAccessLevel,\n            includeInheritedDocs: Bool,\n            includeSynthesized: Bool,\n            includeSPI: Bool,\n            emitExtensionBlocks: Bool\n        ) {\n            self.prettyPrint = prettyPrint\n            self.minimumAccessLevel = minimumAccessLevel\n            self.includeInheritedDocs = includeInheritedDocs\n            self.includeSynthesized = includeSynthesized\n            self.includeSPI = includeSPI\n            self.emitExtensionBlocks = emitExtensionBlocks\n        }\n    }\n\n    case symbolGraph(SymbolGraphOptions)\n    case buildPlan\n    case replArguments\n    case builtArtifacts\n    case dependencyGraph\n}\n\n/// A protocol that represents a build system used by SwiftPM for all build operations. This allows factoring out the\n/// implementation details between SwiftPM's `BuildOperation` and the Swift Build backed `SwiftBuildSystem`.\npublic protocol BuildSystem: Cancellable {\n\n    /// The delegate used by the build system.\n    var delegate: BuildSystemDelegate? { get }\n\n    /// The test products that this build system will build.\n    var builtTestProducts: [BuiltTestProduct] { get async }\n\n    /// Returns the package graph used by the build system.\n    func getPackageGraph() async throws -> ModulesGraph\n\n    /// Builds a subset of the package graph.\n    /// - Parameters:\n    ///   - buildOutputs: Additional build outputs requested from the build system.\n    /// - Returns: A build result with details about requested build and outputs.\n    @discardableResult\n    func build(subset: BuildSubset, buildOutputs: [BuildOutput]) async throws -> BuildResult\n\n    var hasIntegratedAPIDigesterSupport: Bool { get }\n\n    func generatePIF(preserveStructure: Bool) async throws -> String\n}\n\nextension BuildSystem {\n    /// Builds the default subset: all targets excluding tests with no extra build outputs.\n    @discardableResult\n    public func build() async throws -> BuildResult {\n        try await build(subset: .allExcludingTests, buildOutputs: [])\n    }\n}\n\npublic struct SymbolGraphResult {\n    public init(outputLocationForTarget: @escaping (String, BuildParameters) -> [String]) {\n        self.outputLocationForTarget = outputLocationForTarget\n    }\n\n    /// Find the build path relative location of the symbol graph output directory\n    /// for a provided target and build parameters. Note that the directory may not\n    /// exist when the target doesn't have any symbol graph output, as one example.\n    public let outputLocationForTarget: (String, BuildParameters) -> [String]\n}\n\npublic typealias CLIArguments = [String]\n\npublic struct BuildResult {\n    package init(\n        serializedDiagnosticPathsByTargetName: Result<[String: [AbsolutePath]], Error>,\n        symbolGraph: SymbolGraphResult? = nil,\n        buildPlan: BuildPlan? = nil,\n        replArguments: CLIArguments?,\n        builtArtifacts: [(String, PluginInvocationBuildResult.BuiltArtifact)]? = nil,\n        // TODO: echeng3805, there's probably a better type for this?\n        dependencyGraph: [String: [String]]? = nil\n    ) {\n        self.serializedDiagnosticPathsByTargetName = serializedDiagnosticPathsByTargetName\n        self.symbolGraph = symbolGraph\n        self.buildPlan = buildPlan\n        self.replArguments = replArguments\n        self.builtArtifacts = builtArtifacts\n        self.dependencyGraph = dependencyGraph\n    }\n\n    public let replArguments: CLIArguments?\n    public let symbolGraph: SymbolGraphResult?\n    public let buildPlan: BuildPlan?\n    public let dependencyGraph: [String: [String]]?\n\n    public var serializedDiagnosticPathsByTargetName: Result<[String: [AbsolutePath]], Error>\n    public var builtArtifacts: [(String, PluginInvocationBuildResult.BuiltArtifact)]?\n}\n\npublic protocol ProductBuildDescription {\n    /// The reference to the product.\n    var package: ResolvedPackage { get }\n\n    /// The reference to the product.\n    var product: ResolvedProduct { get }\n\n    /// The build parameters.\n    var buildParameters: BuildParameters { get }\n}\n\nextension ProductBuildDescription {\n    /// The path to the product binary produced.\n    public var binaryPath: AbsolutePath {\n        get throws {\n            try self.buildParameters.binaryPath(for: product)\n        }\n    }\n}\n\npublic protocol ModuleBuildDescription {\n    /// The package the module belongs to.\n    var package: ResolvedPackage { get }\n\n    /// The underlying module this description is for.\n    var module: ResolvedModule { get }\n\n    /// The build parameters.\n    var buildParameters: BuildParameters { get }\n\n    /// The diagnostic file locations for all the source files\n    /// associated with this module.\n    var diagnosticFiles: [AbsolutePath] { get }\n\n    /// FIXME: This shouldn't be necessary and ideally\n    /// there should be a way to ask build system to\n    /// introduce these arguments while building for symbol\n    /// graph extraction.\n    func symbolGraphExtractArguments() throws -> [String]\n}\n\npublic protocol BuildPlan {\n    /// Parameters used when building end products for the destination platform.\n    var destinationBuildParameters: BuildParameters { get }\n\n    /// Parameters used when building tools (macros and plugins).\n    var toolsBuildParameters: BuildParameters { get }\n\n    var buildProducts: AnySequence<ProductBuildDescription> { get }\n\n    var buildModules: AnySequence<ModuleBuildDescription> { get }\n\n    func createAPIToolCommonArgs(includeLibrarySearchPaths: Bool) throws -> [String]\n    func createREPLArguments() throws -> [String]\n}\n\npublic protocol BuildSystemFactory {\n    func makeBuildSystem(\n        explicitProduct: String?,\n        enableAllTraits: Bool,\n        cacheBuildManifest: Bool,\n        productsBuildParameters: BuildParameters?,\n        toolsBuildParameters: BuildParameters?,\n        packageGraphLoader: (() async throws -> ModulesGraph)?,\n        outputStream: OutputByteStream?,\n        logLevel: Diagnostic.Severity?,\n        observabilityScope: ObservabilityScope?,\n        delegate: BuildSystemDelegate?\n    ) async throws -> any BuildSystem\n}\n\npublic struct BuildSystemProvider {\n    // TODO: In the future, we may want this to be about specific capabilities of a build system rather than choosing a concrete one.\n    public enum Kind: String, Codable, CaseIterable {\n        case native\n        case swiftbuild\n        case xcode\n\n        public var defaultValueDescription: String {\n            switch self {\n                case .native: \"Native Build System\"\n                case .swiftbuild: \"Swift Build build engine (preview; recommended for feedback and testing.  Report issues at https://github.com/swiftlang/swift-package-manager/issues)\"\n                case .xcode: \"Xcode build system integration (discouraged)\"\n            }\n        }\n    }\n\n    public let providers: [Kind: any BuildSystemFactory]\n\n    public init(providers: [Kind: any BuildSystemFactory]) {\n        self.providers = providers\n    }\n\n    public func createBuildSystem(\n        kind: Kind,\n        explicitProduct: String? = .none,\n        enableAllTraits: Bool = false,\n        cacheBuildManifest: Bool = true,\n        productsBuildParameters: BuildParameters? = .none,\n        toolsBuildParameters: BuildParameters? = .none,\n        packageGraphLoader: (() async throws -> ModulesGraph)? = .none,\n        outputStream: OutputByteStream? = .none,\n        logLevel: Diagnostic.Severity? = .none,\n        observabilityScope: ObservabilityScope? = .none,\n        delegate: BuildSystemDelegate? = nil\n    ) async throws -> any BuildSystem {\n        guard let buildSystemFactory = self.providers[kind] else {\n            throw Errors.buildSystemProviderNotRegistered(kind: kind)\n        }\n        return try await buildSystemFactory.makeBuildSystem(\n            explicitProduct: explicitProduct,\n            enableAllTraits: enableAllTraits,\n            cacheBuildManifest: cacheBuildManifest,\n            productsBuildParameters: productsBuildParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            packageGraphLoader: packageGraphLoader,\n            outputStream: outputStream,\n            logLevel: logLevel,\n            observabilityScope: observabilityScope,\n            delegate: delegate\n        )\n    }\n}\n\nprivate enum Errors: Swift.Error {\n    case buildSystemProviderNotRegistered(kind: BuildSystemProvider.Kind)\n}\n\npublic enum BuildSystemUtilities {\n    /// Returns the build path from the environment, if present.\n    public static func getEnvBuildPath(workingDir: AbsolutePath) throws -> AbsolutePath? {\n        // Don't rely on build path from env for SwiftPM's own tests.\n        guard Environment.current[\"SWIFTPM_TESTS_MODULECACHE\"] == nil else { return nil }\n        guard let env = Environment.current[\"SWIFTPM_BUILD_DIR\"] else { return nil }\n        return try AbsolutePath(validating: env, relativeTo: workingDir)\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildSystem/BuildSystemCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\npublic struct BuildSystemCommand: Hashable {\n    public let name: String\n    public let targetName: String?\n    public let description: String\n    public let verboseDescription: String?\n    public let serializedDiagnosticPaths: [AbsolutePath]\n\n    public init(name: String, targetName: String? = nil, description: String, verboseDescription: String? = nil, serializedDiagnosticPaths: [AbsolutePath] = []) {\n        self.name = name\n        self.targetName = targetName\n        self.description = description\n        self.verboseDescription = verboseDescription\n        self.serializedDiagnosticPaths = serializedDiagnosticPaths\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildSystem/BuildSystemDelegate.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n/// BuildSystem delegate\npublic protocol BuildSystemDelegate: AnyObject {\n    ///Called when build command is about to start.\n    func buildSystem(_ buildSystem: BuildSystem, willStartCommand command: BuildSystemCommand)\n\n    /// Called when build command did start.\n    func buildSystem(_ buildSystem: BuildSystem, didStartCommand command: BuildSystemCommand)\n\n    /// Called when build task did update progress.\n    func buildSystem(_ buildSystem: BuildSystem, didUpdateTaskProgress text: String)\n\n    /// Called when build command did finish.\n    func buildSystem(_ buildSystem: BuildSystem, didFinishCommand command: BuildSystemCommand)\n\n    func buildSystemDidDetectCycleInRules(_ buildSystem: BuildSystem)\n\n    /// Called when build did finish.\n    func buildSystem(_ buildSystem: BuildSystem, didFinishWithResult success: Bool)\n\n    /// Called when build did cancel\n    func buildSystemDidCancel(_ buildSystem: BuildSystem)\n}\n\npublic extension BuildSystemDelegate {\n    func buildSystem(_ buildSystem: BuildSystem, willStartCommand command: BuildSystemCommand) { }\n    func buildSystem(_ buildSystem: BuildSystem, didStartCommand command: BuildSystemCommand) { }\n    func buildSystem(_ buildSystem: BuildSystem, didUpdateTaskProgress text: String) { }\n    func buildSystem(_ buildSystem: BuildSystem, didFinishCommand command: BuildSystemCommand) { }\n    func buildSystemDidDetectCycleInRules(_ buildSystem: BuildSystem) { }\n    func buildSystem(_ buildSystem: BuildSystem, didFinishWithResult success: Bool) { }\n    func buildSystemDidCancel(_ buildSystem: BuildSystem) { }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuildSystem/DiagnosticsCapturingBuildSystemDelegate.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// A BuildSystemDelegate implementation which captures serialized diagnostics paths for all completed tasks.\npackage class DiagnosticsCapturingBuildSystemDelegate: BuildSystemDelegate {\n    package private(set) var serializedDiagnosticsPathsByTarget: [String?: Set<AbsolutePath>] = [:]\n\n    package init() {}\n\n    package func buildSystem(_ buildSystem: any BuildSystem, didFinishCommand command: BuildSystemCommand) {\n        serializedDiagnosticsPathsByTarget[command.targetName, default: []].formUnion(command.serializedDiagnosticPaths)\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/BuiltTestProduct.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// Represents a test product which is built and is present on disk.\npublic struct BuiltTestProduct: Codable {\n    /// The test product name.\n    public let productName: String\n\n    /// The name of the \"umbrella\" test product (if any) which includes this test product\n    public let umbrellaProductName: String?\n\n    /// The path of the test binary.\n    public let binaryPath: AbsolutePath\n\n    /// The path to the package this product was declared in.\n    public let packagePath: AbsolutePath\n\n    /// The path of the test bundle.\n    ///\n    /// When the test product is not bundled (for instance, when using XCTest on\n    /// non-Darwin targets), this path is equal to ``binaryPath``.\n    public var bundlePath: AbsolutePath {\n        // If the binary path is a test runner binary, return it as-is.\n        guard !binaryPath.basenameWithoutExt.hasSuffix(\"test-runner\") else {\n            return binaryPath\n        }\n        // Go up the folder hierarchy until we find the .xctest bundle.\n        let pathExtension = \".xctest\"\n        let hierarchySequence = sequence(first: binaryPath, next: { $0.isRoot ? nil : $0.parentDirectory })\n        guard let bundlePath = hierarchySequence.first(where: { $0.basename.hasSuffix(pathExtension) }) else {\n            fatalError(\"could not find test bundle path from '\\(binaryPath)'\")\n        }\n        \n        return bundlePath\n    }\n\n    /// The path to the entry point source file (XCTMain.swift, LinuxMain.swift,\n    /// etc.) used, if any.\n    public let testEntryPointPath: AbsolutePath?\n\n    /// Creates a new instance.\n    /// - Parameters:\n    ///   - productName: The test product name.\n    ///   - binaryPath: The path of the test binary.\n    ///   - packagePath: The path to the package this product was declared in.\n    ///   - mainSourceFilePath: The path to the main source file used, if any.\n    public init(productName: String, umbrellaProductName: String?, binaryPath: AbsolutePath, packagePath: AbsolutePath, testEntryPointPath: AbsolutePath?) {\n        self.productName = productName\n        self.umbrellaProductName = umbrellaProductName\n        self.binaryPath = binaryPath\n        self.packagePath = packagePath\n        self.testEntryPointPath = testEntryPointPath\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SPMBuildCore\n  BinaryTarget+Extensions.swift\n  BuildParameters/BuildParameters.swift\n  BuildParameters/BuildParameters+APIDigester.swift\n  BuildParameters/BuildParameters+Debugging.swift\n  BuildParameters/BuildParameters+Driver.swift\n  BuildParameters/BuildParameters+Linking.swift\n  BuildParameters/BuildParameters+Output.swift\n  BuildParameters/BuildParameters+Testing.swift\n  BuildSystem/BuildSystem.swift\n  BuildSystem/BuildSystemCommand.swift\n  BuildSystem/BuildSystemDelegate.swift\n  BuildSystem/DiagnosticsCapturingBuildSystemDelegate.swift\n  BuiltTestProduct.swift\n  Plugins/DefaultPluginScriptRunner.swift\n  Plugins/PluginContextSerializer.swift\n  Plugins/PluginInvocation.swift\n  Plugins/PluginMessages.swift\n  Plugins/PluginScriptRunner.swift\n  CommandPluginResult.swift\n  ConfigurableEnvVar.swift\n  MainAttrDetection.swift\n  ResolvedPackage+Extensions.swift\n  Triple+Extensions.swift\n  WarningControlFlags.swift\n  XCFrameworkMetadata.swift\n  XcodeProjectRepresentation.swift)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(SPMBuildCore PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\ntarget_link_libraries(SPMBuildCore PUBLIC\n  TSCBasic\n  TSCUtility\n  Basics\n  SwiftCollections::OrderedCollections\n  PackageGraph)\n\n\ninstall(TARGETS SPMBuildCore\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS SPMBuildCore)\n"
  },
  {
    "path": "Sources/SPMBuildCore/CommandPluginResult.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n@available(*,\n    deprecated,\n    renamed: \"CommandPluginResult\",\n    message: \"renamed to unify terminology with the Swift Evolution proposal\"\n)\npublic typealias PrebuildCommandResult = CommandPluginResult\n\n/// Represents the result of running a command plugin for a single plugin invocation for a target.\npublic struct CommandPluginResult {\n    /// Paths of any derived files that should be included in the build.\n    public var derivedFiles: [AbsolutePath]\n    \n    /// Paths of any directories whose contents influence the build plan.\n    public var outputDirectories: [AbsolutePath]\n\n    public init(derivedFiles: [AbsolutePath], outputDirectories: [AbsolutePath]) {\n        self.derivedFiles = derivedFiles\n        self.outputDirectories = outputDirectories\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/ConfigurableEnvVar.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\npackage enum ConfigurableEnvVar: String {\n    /// SBOM specification(s) to generate (comma-separated list)\n    case SWIFTPM_BUILD_SBOM_SPEC\n\n    /// Directory path to generate SBOM(s) in\n    case SWIFTPM_BUILD_SBOM_OUTPUT_DIR\n\n    /// Filter SBOM components and dependencies by entity (package, product, or both)\n    case SWIFTPM_BUILD_SBOM_FILTER\n\n    /// Whether to treat SBOM generation errors as warnings\n    case SWIFTPM_BUILD_SBOM_WARNING_ONLY\n\n    package func getEnvVar() -> String? {\n        ProcessInfo.processInfo.environment[self.rawValue]\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/MainAttrDetection.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n// looking into the file content to see if it is using the @main annotation\n// this is not bullet-proof since theoretically the file can contain the @main string for other reasons\n// but it is the closest to accurate we can do at this point\npackage func containsAtMain(fileSystem: FileSystem, path: AbsolutePath) throws -> Bool {\n    let content: String = try fileSystem.readFileContents(path)\n    let lines = content.split(whereSeparator: { $0.isNewline }).map { $0.trimmingCharacters(in: .whitespaces) }\n\n    var multilineComment = false\n    for line in lines {\n        if line.hasPrefix(\"//\") {\n            continue\n        }\n        if line.hasPrefix(\"/*\") {\n            multilineComment = true\n        }\n        if line.hasSuffix(\"*/\") {\n            multilineComment = false\n        }\n        if multilineComment {\n            continue\n        }\n        if line.hasPrefix(\"@main\") {\n            return true\n        }\n    }\n    return false\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/Plugins/DefaultPluginScriptRunner.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\n\nimport Foundation\nimport PackageGraph\nimport PackageModel\n\nimport struct TSCBasic.ByteString\nimport struct Basics.AsyncProcessResult\nimport class Basics.AsyncProcess\n\nimport struct TSCUtility.SerializedDiagnostics\n\n#if os(Android)\nimport Android\n#endif\n\n/// A plugin script runner that compiles the plugin source files as an executable binary for the host platform, and invokes it as a subprocess.\npublic struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable {\n    private let fileSystem: FileSystem\n    private let cacheDir: Basics.AbsolutePath\n    private let toolchain: UserToolchain\n    private let extraPluginSwiftCFlags: [String]\n    private let enableSandbox: Bool\n    private let cancellator: Cancellator\n    private let verboseOutput: Bool\n\n    private let sdkRootCache = ThreadSafeBox<Basics.AbsolutePath?>()\n\n    public init(\n        fileSystem: Basics.FileSystem,\n        cacheDir: Basics.AbsolutePath,\n        toolchain: UserToolchain,\n        extraPluginSwiftCFlags: [String] = [],\n        enableSandbox: Bool = true,\n        verboseOutput: Bool = false\n    ) {\n        self.fileSystem = fileSystem\n        self.cacheDir = cacheDir\n        self.toolchain = toolchain\n        self.extraPluginSwiftCFlags = extraPluginSwiftCFlags\n        self.enableSandbox = enableSandbox\n        self.cancellator = Cancellator(observabilityScope: .none)\n        self.verboseOutput = verboseOutput\n    }\n\n    /// Starts evaluating a plugin by compiling it and running it as a subprocess. The name is used as the basename for the executable and auxiliary files.  The tools version controls the availability of APIs in PackagePlugin, and should be set to the tools version of the package that defines the plugin (not the package containing the target to which it is being applied). This function returns immediately and then repeated calls the output handler on the given callback queue as plain-text output is received from the plugin, and then eventually calls the completion handler on the given callback queue once the plugin is done.\n    public func runPluginScript(\n        sourceFiles: [Basics.AbsolutePath],\n        pluginName: String,\n        initialMessage: Data,\n        toolsVersion: ToolsVersion,\n        workingDirectory: Basics.AbsolutePath,\n        writableDirectories: [Basics.AbsolutePath],\n        readOnlyDirectories: [Basics.AbsolutePath],\n        allowNetworkConnections: [SandboxNetworkPermission],\n        workers: UInt32,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        delegate: PluginScriptCompilerDelegate & PluginScriptRunnerDelegate,\n        completion: @escaping (Result<Int32, Error>) -> Void\n    ) {\n        // If needed, compile the plugin script to an executable (asynchronously). Compilation is skipped if the plugin hasn't changed since it was last compiled.\n        self.compilePluginScript(\n            sourceFiles: sourceFiles,\n            pluginName: pluginName,\n            toolsVersion: toolsVersion,\n            workers: workers,\n            observabilityScope: observabilityScope,\n            callbackQueue: DispatchQueue.sharedConcurrent,\n            delegate: delegate,\n            completion: {\n                dispatchPrecondition(condition: .onQueue(DispatchQueue.sharedConcurrent))\n                switch $0 {\n                case .success(let result):\n                    if result.succeeded {\n                        // Compilation succeeded, so run the executable. We are already running on an asynchronous queue.\n                        self.invoke(\n                            compiledExec: result.executableFile,\n                            workingDirectory: workingDirectory,\n                            writableDirectories: writableDirectories,\n                            readOnlyDirectories: readOnlyDirectories,\n                            allowNetworkConnections: allowNetworkConnections,\n                            initialMessage: initialMessage,\n                            observabilityScope: observabilityScope,\n                            callbackQueue: callbackQueue,\n                            delegate: delegate,\n                            completion: completion)\n                    }\n                    else {\n                        // Compilation failed, so throw an error.\n                        callbackQueue.async { completion(.failure(DefaultPluginScriptRunnerError.compilationFailed(result))) }\n                    }\n                case .failure(let error):\n                    // Compilation failed, so just call the callback block on the appropriate queue.\n                    callbackQueue.async { completion(.failure(error)) }\n                }\n            }\n        )\n    }\n\n    public var hostTriple: Triple {\n        return self.toolchain.targetTriple\n    }\n\n    /// Starts compiling a plugin script asynchronously and when done, calls the completion handler on the callback queue with the results (including the path of the compiled plugin executable and with any emitted diagnostics, etc).  Existing compilation results that are still valid are reused, if possible.  This function itself returns immediately after starting the compile.  Note that the completion handler only receives a `.failure` result if the compiler couldn't be invoked at all; a non-zero exit code from the compiler still returns `.success` with a full compilation result that notes the error in the diagnostics (in other words, a `.failure` result only means \"failure to invoke the compiler\").\n    public func compilePluginScript(\n        sourceFiles: [Basics.AbsolutePath],\n        pluginName: String,\n        toolsVersion: ToolsVersion,\n        workers: UInt32,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        delegate: PluginScriptCompilerDelegate,\n        completion: @escaping (Result<PluginCompilationResult, Error>) -> Void\n    ) {\n        // Determine the path of the executable and other produced files.\n        let execName = pluginName.spm_mangledToC99ExtendedIdentifier()\n        #if os(Windows)\n        let execSuffix = \".exe\"\n        #else\n        let execSuffix = \"\"\n        #endif\n        let execFilePath = self.cacheDir.appending(component: execName + execSuffix)\n        let diagFilePath = self.cacheDir.appending(component: execName + \".dia\")\n        observabilityScope.emit(debug: \"Compiling plugin to executable at \\(execFilePath)\")\n\n        // Construct the command line for compiling the plugin script(s).\n        // FIXME: Much of this is similar to what the ManifestLoader is doing. This should be consolidated.\n\n        // We use the toolchain's Swift compiler for compiling the plugin.\n        var commandLine = [self.toolchain.swiftCompilerPathForManifests.pathString]\n\n        observabilityScope.emit(debug: \"Using compiler \\(self.toolchain.swiftCompilerPathForManifests.pathString)\")\n\n        // Get access to the path containing the PackagePlugin module and library.\n        let pluginLibraryPath = self.toolchain.swiftPMLibrariesLocation.pluginLibraryPath\n        let pluginModulesPath = self.toolchain.swiftPMLibrariesLocation.pluginModulesPath\n\n        // if runtimePath is set to \"PackageFrameworks\" that means we could be developing SwiftPM in Xcode\n        // which produces a framework for dynamic package products.\n        if pluginLibraryPath.extension == \"framework\" {\n            commandLine += [\n                \"-F\", pluginLibraryPath.parentDirectory.pathString,\n                \"-framework\", \"PackagePlugin\",\n                \"-Xlinker\", \"-rpath\", \"-Xlinker\", pluginLibraryPath.parentDirectory.pathString,\n            ]\n        } else {\n            commandLine += [\n                \"-L\", pluginLibraryPath.pathString,\n                \"-lPackagePlugin\",\n            ]\n            #if !os(Windows)\n            // -rpath argument is not supported on Windows,\n            // so we add runtimePath to PATH when executing the manifest instead\n            commandLine += [\"-Xlinker\", \"-rpath\", \"-Xlinker\", pluginLibraryPath.pathString]\n            #endif\n        }\n\n        #if os(macOS)\n        // On macOS earlier than 12, add an rpath to the directory that contains the concurrency fallback library.\n        if #available(macOS 12.0, *) {\n            // Nothing is needed; the system has everything we need.\n        }\n        else {\n            // Add an `-rpath` so the Swift 5.5 fallback libraries can be found.\n            let swiftSupportLibPath = self.toolchain.swiftCompilerPathForManifests.parentDirectory.parentDirectory.appending(components: \"lib\", \"swift-5.5\", \"macosx\")\n            commandLine += [\"-Xlinker\", \"-rpath\", \"-Xlinker\", swiftSupportLibPath.pathString]\n        }\n        #endif\n\n        // Use the same minimum deployment target as the PackagePlugin library (with a fallback to the default host triple).\n        #if os(macOS)\n        if let version = self.toolchain.swiftPMLibrariesLocation.pluginLibraryMinimumDeploymentTarget?.versionString {\n            commandLine += [\"-target\", \"\\(self.toolchain.targetTriple.tripleString(forPlatformVersion: version))\"]\n        } else {\n            commandLine += [\"-target\", self.toolchain.targetTriple.tripleString]\n        }\n        #endif\n\n        // Add any extra flags required as indicated by the ManifestLoader.\n        commandLine += self.toolchain.swiftCompilerFlags\n\n        commandLine.append(\"-g\")\n\n        // Add the Swift language version implied by the package tools version.\n        commandLine += [\"-swift-version\", toolsVersion.swiftLanguageVersion.rawValue]\n\n        // Add the PackageDescription version specified by the package tools version, which controls what PackagePlugin API is seen.\n        commandLine += [\"-package-description-version\", toolsVersion.description]\n\n        // if runtimePath is set to \"PackageFrameworks\" that means we could be developing SwiftPM in Xcode\n        // which produces a framework for dynamic package products.\n        if pluginModulesPath.extension == \"framework\" {\n            commandLine += [\"-I\", pluginModulesPath.parentDirectory.parentDirectory.pathString]\n        } else {\n            commandLine += [\"-I\", pluginModulesPath.pathString]\n        }\n        #if os(macOS)\n        if let sdkRoot = self.toolchain.sdkRootPath ?? self.sdkRoot() {\n            commandLine += [\"-sdk\", sdkRoot.pathString]\n        }\n        #endif\n\n        // Honor any module cache override that's set in the environment.\n        let moduleCachePath = Environment.current[\"SWIFTPM_MODULECACHE_OVERRIDE\"] ?? Environment.current[\"SWIFTPM_TESTS_MODULECACHE\"]\n        if let moduleCachePath {\n            commandLine += [\"-module-cache-path\", moduleCachePath]\n        }\n\n        // Parse the plugin as a library so that `@main` is supported even though there might be only a single source file.\n        commandLine += [\"-parse-as-library\"]\n\n        // Enable concurrent compilation.\n        commandLine += [\"-j\\(workers)\"]\n\n        // Ask the compiler to create a diagnostics file (we'll put it next to the executable).\n        commandLine += [\"-Xfrontend\", \"-serialize-diagnostics-path\", \"-Xfrontend\", diagFilePath.pathString]\n\n        // Add all the source files that comprise the plugin scripts.\n        commandLine += sourceFiles.map { $0.pathString }\n\n        // Finally add the output path of the compiled executable.\n        commandLine += [\"-o\", execFilePath.pathString]\n\n        // Add any extra flags passed for the host in the command line\n        commandLine += self.extraPluginSwiftCFlags\n\n        if (verboseOutput) {\n            commandLine.append(\"-v\")\n        }\n        // Pass through the compilation environment.\n        let environment = toolchain.swiftCompilerEnvironment\n\n        // First try to create the output directory.\n        do {\n            observabilityScope.emit(debug: \"Plugin compilation output directory '\\(execFilePath.parentDirectory)'\")\n            try FileManager.default.createDirectory(at: execFilePath.parentDirectory.asURL, withIntermediateDirectories: true, attributes: nil)\n        }\n        catch {\n            // Bail out right away if we didn't even get this far.\n            return callbackQueue.async {\n                completion(.failure(DefaultPluginScriptRunnerError.compilationPreparationFailed(error: error)))\n            }\n        }\n\n        // Hash the compiler inputs to decide whether we really need to recompile.\n        let compilerInputHash: String?\n        do {\n            // Include the full compiler arguments and environment, and the contents of the source files.\n            var stringToHash = commandLine.description\n            for (key, value) in toolchain.swiftCompilerEnvironment.sorted(by: { $0.key < $1.key }) {\n                stringToHash.append(\"\\(key)=\\(value)\\n\")\n            }\n            for sourceFile in sourceFiles {\n                let source: String = try fileSystem.readFileContents(sourceFile)\n                stringToHash.append(source)\n            }\n            compilerInputHash = ByteString(encodingAsUTF8: stringToHash).sha256Checksum\n            observabilityScope.emit(debug: \"Computed hash of plugin compilation inputs: \\(compilerInputHash!)\")\n        }\n        catch {\n            // We couldn't compute the hash. We warn about it but proceed with the compilation (a cache miss).\n            observabilityScope.emit(debug: \"Couldn't compute hash of plugin compilation inputs\", underlyingError: error)\n            compilerInputHash = .none\n        }\n\n        /// Persisted information about the last time the compiler was invoked.\n        struct PersistedCompilationState: Codable {\n            var commandLine: [String]\n            var environment: Environment\n            var inputHash: String?\n            var output: String\n            var result: Result\n            enum Result: Equatable, Codable {\n                case exit(code: Int32)\n                case abnormal(exception: UInt32)\n                case signal(number: Int32)\n\n                init(_ processExitStatus: AsyncProcessResult.ExitStatus) {\n                    switch processExitStatus {\n                    case .terminated(let code):\n                        self = .exit(code: code)\n                    #if os(Windows)\n                    case .abnormal(let exception):\n                        self = .abnormal(exception: exception)\n                    #else\n                    case .signalled(let signal):\n                        self = .signal(number: signal)\n                    #endif\n                    }\n                }\n            }\n\n            var succeeded: Bool {\n                return result == .exit(code: 0)\n            }\n        }\n\n        // Check if we already have a compiled executable and a persisted state (we only recompile if things have changed).\n        let stateFilePath = self.cacheDir.appending(component: execName + \"-state\" + \".json\")\n        var compilationState: PersistedCompilationState? = .none\n        if fileSystem.exists(execFilePath) && fileSystem.exists(stateFilePath) {\n            do {\n                // Try to load the previous compilation state.\n                let previousState = try JSONDecoder.makeWithDefaults().decode(\n                    path: stateFilePath,\n                    fileSystem: fileSystem,\n                    as: PersistedCompilationState.self)\n\n                // If it succeeded last time and the compiler inputs are the same, we don't need to recompile.\n                if previousState.succeeded && previousState.inputHash == compilerInputHash {\n                    compilationState = previousState\n                }\n            }\n            catch {\n                // We couldn't read the compilation state file even though it existed. We warn about it but proceed with recompiling.\n                observabilityScope.emit(debug: \"Couldn't read previous compilation state\", underlyingError: error)\n            }\n        }\n\n        // If we still have a compilation state, it means the executable is still valid and we don't need to do anything.\n        if let compilationState {\n            // Just call the completion handler with the persisted results.\n            let result = PluginCompilationResult(\n                succeeded: compilationState.succeeded,\n                commandLine: commandLine,\n                executableFile: execFilePath,\n                diagnosticsFile: diagFilePath,\n                compilerOutput: compilationState.output,\n                cached: true)\n            delegate.skippedCompilingPlugin(cachedResult: result)\n            return callbackQueue.async {\n                completion(.success(result))\n            }\n        }\n\n        // Otherwise we need to recompile. We start by telling the delegate.\n        delegate.willCompilePlugin(commandLine: commandLine, environment: .init(environment))\n\n        // Clean up any old files to avoid confusion if the compiler can't be invoked.\n        do {\n            try fileSystem.removeFileTree(execFilePath)\n            try fileSystem.removeFileTree(diagFilePath)\n            try fileSystem.removeFileTree(stateFilePath)\n        }\n        catch {\n            observabilityScope.emit(debug: \"Couldn't clean up before invoking compiler\", underlyingError: error)\n        }\n\n        // Now invoke the compiler asynchronously.\n        AsyncProcess.popen(arguments: commandLine, environment: environment, queue: callbackQueue) {\n            // We are now on our caller's requested callback queue, so we just call the completion handler directly.\n            dispatchPrecondition(condition: .onQueue(callbackQueue))\n            completion($0.tryMap { process in\n                // Emit the compiler output as observable info.\n                let compilerOutput = ((try? process.utf8Output()) ?? \"\") + ((try? process.utf8stderrOutput()) ?? \"\")\n                if !compilerOutput.isEmpty {\n                    observabilityScope.emit(info: compilerOutput)\n                }\n\n                // Save the persisted compilation state for possible reuse next time.\n                let compilationState = PersistedCompilationState(\n                    commandLine: commandLine,\n                    environment: toolchain.swiftCompilerEnvironment.cachable,\n                    inputHash: compilerInputHash,\n                    output: compilerOutput,\n                    result: .init(process.exitStatus))\n                do {\n                    try JSONEncoder.makeWithDefaults().encode(path: stateFilePath, fileSystem: self.fileSystem, compilationState)\n                }\n                catch {\n                    // We couldn't write out the `.state` file. We warn about it but proceed.\n                    observabilityScope.emit(debug: \"Couldn't save plugin compilation state\", underlyingError: error)\n                }\n\n                // Construct a PluginCompilationResult for both the successful and unsuccessful cases (to convey diagnostics, etc).\n                let result = PluginCompilationResult(\n                    succeeded: compilationState.succeeded,\n                    commandLine: commandLine,\n                    executableFile: execFilePath,\n                    diagnosticsFile: diagFilePath,\n                    compilerOutput: compilerOutput,\n                    cached: false)\n\n                // Tell the delegate that we're done compiling the plugin, passing it the result.\n                delegate.didCompilePlugin(result: result)\n\n                // Also return the result to the caller.\n                return result\n            })\n        }\n    }\n\n    /// Returns path to the sdk, if possible.\n    // FIXME: This is copied from ManifestLoader.  This should be consolidated when ManifestLoader is cleaned up.\n    private func sdkRoot() -> Basics.AbsolutePath? {\n        return self.sdkRootCache.memoizeOptional(body: {\n            var sdkRootPath: Basics.AbsolutePath?\n            // Find SDKROOT on macOS using xcrun.\n            #if os(macOS)\n            let foundPath = try? AsyncProcess.checkNonZeroExit(\n                args: \"/usr/bin/xcrun\", \"--sdk\", \"macosx\", \"--show-sdk-path\"\n            )\n            guard let sdkRoot = foundPath?.spm_chomp(), !sdkRoot.isEmpty else {\n                return nil\n            }\n            if let path = try? Basics.AbsolutePath(validating: sdkRoot) {\n                sdkRootPath = path\n            }\n            #endif\n\n            return sdkRootPath\n        })\n    }\n    \n    /// Private function that invokes a compiled plugin executable and communicates with it until it finishes.\n    fileprivate func invoke(\n        compiledExec: Basics.AbsolutePath,\n        workingDirectory: Basics.AbsolutePath,\n        writableDirectories: [Basics.AbsolutePath],\n        readOnlyDirectories: [Basics.AbsolutePath],\n        allowNetworkConnections: [SandboxNetworkPermission],\n        initialMessage: Data,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        delegate: PluginScriptRunnerDelegate,\n        completion: @escaping (Result<Int32, Error>) -> Void\n    ) {\n#if canImport(Darwin) && !os(macOS)\n        callbackQueue.async {\n            completion(.failure(DefaultPluginScriptRunnerError.pluginUnavailable(reason: \"subprocess invocations are unavailable on this platform\")))\n        }\n#else\n        // Construct the command line. Currently we just invoke the executable built from the plugin without any parameters.\n        var command = [compiledExec.pathString]\n\n        // Optionally wrap the command in a sandbox, which places some limits on what it can do. In particular, it blocks network access and restricts the paths to which the plugin can make file system changes. It does allow writing to temporary directories.\n        if self.enableSandbox {\n            do {\n                command = try Sandbox.apply(\n                    command: command,\n                    fileSystem: self.fileSystem,\n                    strictness: .writableTemporaryDirectory,\n                    writableDirectories: writableDirectories + [self.cacheDir],\n                    readOnlyDirectories: readOnlyDirectories,\n                    allowNetworkConnections: allowNetworkConnections\n                )\n            } catch {\n                return callbackQueue.async {\n                    completion(.failure(error))\n                }\n            }\n        }\n\n        // Create and configure a Process. We set the working directory to the cache directory, so that relative paths end up there.\n        let process = Foundation.Process()\n        process.executableURL = URL(fileURLWithPath: command[0])\n        process.arguments = Array(command.dropFirst())\n\n        var env = Environment.current\n\n        // FIXME: This is largely a workaround for improper rpath setup on Linux. It should be\n        // removed once the Swift Build backend switches to use swiftc as the linker driver\n        // for targets with Swift sources. For now, limit the scope to non-macOS, so that\n        // plugins do not inadvertently use the toolchain stdlib instead of the OS stdlib\n        // when built with a Swift.org toolchain.\n        #if !os(macOS)\n        // Update the environment for any runtime library paths that tools compiled\n        // for the command plugin might require after they have been built.\n        let runtimeLibPaths = self.toolchain.runtimeLibraryPaths\n        for libPath in runtimeLibPaths {\n            env.appendPath(key: .libraryPath, value: libPath.pathString)\n        }\n        #endif\n\n#if os(Windows)\n        let pluginLibraryPath = self.toolchain.swiftPMLibrariesLocation.pluginLibraryPath.pathString\n        env.prependPath(key: .path, value: pluginLibraryPath)\n#endif\n        process.environment = .init(env)\n\n        process.currentDirectoryURL = workingDirectory.asURL\n\n        // Set up a pipe for sending structured messages to the plugin on its stdin.\n        let stdinPipe = Pipe()\n        let outputHandle = stdinPipe.fileHandleForWriting\n        let outputQueue = DispatchQueue(label: \"plugin-send-queue\")\n        process.standardInput = stdinPipe\n\n        // Set up a pipe for receiving messages from the plugin on its stdout.\n        let stdoutPipe = Pipe()\n        let stdoutLock = NSLock()\n        stdoutPipe.fileHandleForReading.readabilityHandler = { fileHandle in\n            // Receive the next message and pass it on to the delegate.\n            stdoutLock.withLock {\n                do {\n                    while let message = try fileHandle.readPluginMessage() {\n                        // FIXME: We should handle errors here.\n                        callbackQueue.async {\n                            do {\n                                try delegate.handleMessage(data: message, responder: { data in\n                                    outputQueue.async {\n                                        do {\n                                            try outputHandle.writePluginMessage(data)\n                                        }\n                                        catch {\n                                            print(\"error while trying to send message to plugin: \\(error.interpolationDescription)\")\n                                        }\n                                    }\n                                })\n                            }\n                            catch DecodingError.keyNotFound(let key, _) where key.stringValue == \"version\" {\n                                print(\"message from plugin did not contain a 'version' key, likely an incompatible plugin library is being loaded by the plugin\")\n                            }\n                            catch {\n                                print(\"error while trying to handle message from plugin: \\(error.interpolationDescription)\")\n                            }\n                        }\n                    }\n                }\n                catch {\n                    print(\"error while trying to read message from plugin: \\(error.interpolationDescription)\")\n                }\n            }\n        }\n        process.standardOutput = stdoutPipe\n\n        // Set up a pipe for receiving free-form text output from the plugin on its stderr.\n        let stderrPipe = Pipe()\n        let stderrLock = NSLock()\n        var stderrData = Data()\n        let stderrHandler = { (data: Data) in\n            // Pass on any available data to the delegate.\n            if data.isEmpty { return }\n            stderrData.append(contentsOf: data)\n            callbackQueue.async { delegate.handleOutput(data: data) }\n        }\n        stderrPipe.fileHandleForReading.readabilityHandler = { fileHandle in\n            // Read and pass on any available free-form text output from the plugin.\n            // We need the lock since we could run concurrently with the termination handler.\n            stderrLock.withLock { stderrHandler(fileHandle.availableData) }\n        }\n        process.standardError = stderrPipe\n        \n        // Add it to the list of currently running plugin processes, so it can be cancelled if the host is interrupted.\n        guard let cancellationKey = self.cancellator.register(process) else {\n            return callbackQueue.async {\n                completion(.failure(CancellationError()))\n            }\n        }\n\n        // Set up a handler to deal with the exit of the plugin process.\n        process.terminationHandler = { process in\n            // Remove the process from the list of currently running ones.\n            self.cancellator.deregister(cancellationKey)\n\n            // Close the output handle through which we talked to the plugin.\n            try? outputHandle.close()\n\n            // Read and pass on any remaining free-form text output from the plugin.\n            // We need the lock since we could run concurrently with the readability handler.\n            stderrLock.withLock {\n                try? stderrPipe.fileHandleForReading.readToEnd().map{ stderrHandler($0) }\n            }\n\n            // Read and pass on any remaining messages from the plugin.\n            let handle = stdoutPipe.fileHandleForReading\n            if let handler = handle.readabilityHandler {\n                handler(handle)\n            }\n\n            // Call the completion block with a result that depends on how the process ended.\n            callbackQueue.async {\n                completion(Result {\n                    // We throw an error if the plugin ended with a signal.\n                    if process.terminationReason == .uncaughtSignal {\n                        throw DefaultPluginScriptRunnerError.invocationEndedBySignal(\n                            signal: process.terminationStatus,\n                            command: command,\n                            output: String(decoding: stderrData, as: UTF8.self))\n                    }\n                    // Otherwise return the termination satatus.\n                    return process.terminationStatus\n                })\n            }\n        }\n \n        // Start the plugin process.\n        do {\n            try process.run()\n        }\n        catch {\n            callbackQueue.async {\n                completion(.failure(DefaultPluginScriptRunnerError.invocationFailed(error: error, command: command)))\n            }\n        }\n\n        /// Send the initial message to the plugin.\n        outputQueue.async {\n            try? outputHandle.writePluginMessage(initialMessage)\n        }\n#endif\n    }\n\n    public func cancel(deadline: DispatchTime) throws {\n        try self.cancellator.cancel(deadline: deadline)\n    }\n}\n\n/// An error encountered by the default plugin runner.\npublic enum DefaultPluginScriptRunnerError: Error, CustomStringConvertible {\n    /// The plugin is not available for some reason.\n    case pluginUnavailable(reason: String)\n\n    /// An error occurred while preparing to compile the plugin script.\n    case compilationPreparationFailed(error: Error)\n\n    /// An error occurred while compiling the plugin script (e.g. syntax error).\n    /// The diagnostics are available in the plugin compilation result.\n    case compilationFailed(PluginCompilationResult)\n\n    /// The plugin invocation couldn't be started.\n    case invocationFailed(error: Error, command: [String])\n\n    /// The plugin invocation ended by a signal.\n    case invocationEndedBySignal(signal: Int32, command: [String], output: String)\n\n    /// The plugin invocation ended with a non-zero exit code.\n    case invocationEndedWithNonZeroExitCode(exitCode: Int32, command: [String], output: String)\n\n    /// There was an error communicating with the plugin.\n    case pluginCommunicationError(message: String, command: [String], output: String)\n\n    public var description: String {\n        func makeContextString(_ command: [String], _ output: String) -> String {\n            return \"<command: \\(command.map{ $0.spm_shellEscaped() }.joined(separator: \" \"))>, <output:\\n\\(output.spm_shellEscaped())>\"\n        }\n        switch self {\n        case .pluginUnavailable(let reason):\n            return \"plugin is unavailable: \\(reason)\"\n        case .compilationPreparationFailed(let error):\n            return \"plugin compilation preparation failed: \\(error.interpolationDescription)\"\n        case .compilationFailed(let result):\n            return \"plugin compilation failed: \\(result)\"\n        case .invocationFailed(let error, let command):\n            return \"plugin invocation failed: \\(error.interpolationDescription) \\(makeContextString(command, \"\"))\"\n        case .invocationEndedBySignal(let signal, let command, let output):\n            return \"plugin process ended by an uncaught signal: \\(signal) \\(makeContextString(command, output))\"\n        case .invocationEndedWithNonZeroExitCode(let exitCode, let command, let output):\n            return \"plugin process ended with a non-zero exit code: \\(exitCode) \\(makeContextString(command, output))\"\n        case .pluginCommunicationError(let message, let command, let output):\n            return \"plugin communication error: \\(message) \\(makeContextString(command, output))\"\n        }\n    }\n}\n\nfileprivate extension FileHandle {\n    \n    func writePluginMessage(_ message: Data) throws {\n        // Write the header (a 64-bit length field in little endian byte order).\n        var length = UInt64(littleEndian: UInt64(message.count))\n        let header = Swift.withUnsafeBytes(of: &length) { Data($0) }\n        assert(header.count == 8)\n        try self.write(contentsOf: header)\n        \n        // Write the payload.\n        try self.write(contentsOf: message)\n    }\n    \n    func readPluginMessage() throws -> Data? {\n        // Read the header (a 64-bit length field in little endian byte order).\n        guard let header = try self.read(upToCount: 8) else { return nil }\n        guard header.count == 8 else {\n            throw PluginMessageError.truncatedHeader\n        }\n        let length = header.withUnsafeBytes{ $0.loadUnaligned(as: UInt64.self).littleEndian }\n        guard length >= 2 else {\n            throw PluginMessageError.invalidPayloadSize\n        }\n\n        // Read and return the message.\n        guard let message = try self.read(upToCount: Int(length)), message.count == length else {\n            throw PluginMessageError.truncatedPayload\n        }\n        return message\n    }\n\n    enum PluginMessageError: Swift.Error {\n        case truncatedHeader\n        case invalidPayloadSize\n        case truncatedPayload\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/Plugins/PluginContextSerializer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport TSCBasic\nimport TSCUtility\n\ntypealias WireInput = HostToPluginMessage.InputContext\n\n/// Creates the serialized input structure for the plugin script based on all\n/// the input information to a plugin.\ninternal struct PluginContextSerializer {\n    let fileSystem: FileSystem\n    let modulesGraph: ModulesGraph\n    let buildEnvironment: BuildEnvironment\n    let pkgConfigDirectories: [Basics.AbsolutePath]\n    let sdkRootPath: Basics.AbsolutePath?\n    var paths: [WireInput.URL] = []\n    var pathsToIds: [Basics.AbsolutePath: WireInput.URL.Id] = [:]\n    var targets: [WireInput.Target] = []\n    var targetsToWireIDs: [ResolvedModule.ID: WireInput.Target.Id] = [:]\n    var products: [WireInput.Product] = []\n    var productsToWireIDs: [ResolvedProduct.ID: WireInput.Product.Id] = [:]\n    var packages: [WireInput.Package] = []\n    var packagesToWireIDs: [ResolvedPackage.ID: WireInput.Package.Id] = [:]\n\n    var xcodeTargets: [WireInput.XcodeTarget] = []\n    var xcodeTargetsToIds: [XcodeProjectRepresentation.Target: WireInput.XcodeTarget.Id] = [:]\n    var xcodeProjects: [WireInput.XcodeProject] = []\n    var xcodeProjectsToIds: [XcodeProjectRepresentation: WireInput.XcodeProject.Id] = [:]\n    \n    /// Adds a path to the serialized structure, if it isn't already there.\n    /// Either way, this function returns the path's wire ID.\n    mutating func serialize(path: Basics.AbsolutePath) throws -> WireInput.URL.Id {\n        // If we've already seen the path, just return the wire ID we already assigned to it.\n        if let id = pathsToIds[path] { return id }\n        \n        // Split up the path into a base path and a subpath (currently always with the last path component as the\n        // subpath, but this can be optimized where there are sequences of path components with a valence of one).\n        let basePathId: Int?\n        if path.parentDirectory.isRoot {\n            // Windows does not have a single root path like UNIX, so capture the root path itself such that we can rejoin it later\n            #if os(Windows)\n            let id = paths.count\n            paths.append(.init(baseURLId: nil, subpath: path.parentDirectory.pathString))\n            pathsToIds[path] = id\n            basePathId = id\n            #else\n            basePathId = nil\n            #endif\n        } else {\n            basePathId = try serialize(path: path.parentDirectory)\n        }\n\n        let subpathString = path.basename\n        \n        // Finally assign the next wire ID to the path, and append a serialized Path record.\n        let id = paths.count\n        paths.append(.init(baseURLId: basePathId, subpath: subpathString))\n        pathsToIds[path] = id\n        return id\n    }\n\n    // Adds a target to the serialized structure, if it isn't already there and\n    // if it is of a kind that should be passed to the plugin. If so, this func-\n    // tion returns the target's wire ID. If not, it returns nil.\n    mutating func serialize(target: ResolvedModule) throws -> WireInput.Target.Id? {\n        // If we've already seen the target, just return the wire ID we already assigned to it.\n        if let id = targetsToWireIDs[target.id] { return id }\n\n        // Construct the FileList\n        var targetFiles: [WireInput.File] = []\n        targetFiles.append(contentsOf: try target.underlying.sources.paths.map {\n            .init(basePathId: try serialize(path: $0.parentDirectory), name: $0.basename, type: .source)\n        })\n        targetFiles.append(contentsOf: try target.underlying.resources.map {\n            .init(basePathId: try serialize(path: $0.path.parentDirectory), name: $0.path.basename, type: .resource)\n        })\n        targetFiles.append(contentsOf: try target.underlying.ignored.map {\n            .init(basePathId: try serialize(path: $0.parentDirectory), name: $0.basename, type: .unknown)\n        })\n        targetFiles.append(contentsOf: try target.underlying.others.map {\n            .init(basePathId: try serialize(path: $0.parentDirectory), name: $0.basename, type: .unknown)\n        })\n        \n        // Create a scope for evaluating build settings.\n        let scope = BuildSettings.Scope(target.underlying.buildSettings, environment: buildEnvironment)\n        \n        // Look at the target and decide what to serialize. At this point we may decide to not serialize it at all.\n        let targetInfo: WireInput.Target.TargetInfo\n        switch target.underlying {\n        case let target as SwiftModule:\n            targetInfo = .swiftSourceModuleInfo(\n                moduleName: target.c99name,\n                kind: try .init(target.type),\n                sourceFiles: targetFiles,\n                compilationConditions: scope.evaluate(.SWIFT_ACTIVE_COMPILATION_CONDITIONS),\n                linkedLibraries: scope.evaluate(.LINK_LIBRARIES),\n                linkedFrameworks: scope.evaluate(.LINK_FRAMEWORKS))\n\n        case let target as ClangModule:\n            targetInfo = .clangSourceModuleInfo(\n                moduleName: target.c99name,\n                kind: try .init(target.type),\n                sourceFiles: targetFiles,\n                preprocessorDefinitions: scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS),\n                headerSearchPaths: scope.evaluate(.HEADER_SEARCH_PATHS),\n                publicHeadersDirId: try serialize(path: target.includeDir),\n                linkedLibraries: scope.evaluate(.LINK_LIBRARIES),\n                linkedFrameworks: scope.evaluate(.LINK_FRAMEWORKS))\n\n        case let target as SystemLibraryModule:\n            var cFlags: [String] = []\n            var ldFlags: [String] = []\n            // FIXME: What do we do with any diagnostics here?\n            let observabilityScope = ObservabilitySystem({ _, _ in }, outputStream: nil, logLevel: .debug).topScope\n            for result in try pkgConfigArgs(\n                for: target,\n                pkgConfigDirectories: pkgConfigDirectories,\n                sdkRootPath: sdkRootPath,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            ) {\n                if let error = result.error {\n                    observabilityScope.emit(\n                        warning: \"\\(error.interpolationDescription)\",\n                        metadata: .pkgConfig(pcFile: result.pkgConfigName, targetName: target.name)\n                    )\n                }\n                else {\n                    cFlags += result.cFlags\n                    ldFlags += result.libs\n                }\n            }\n\n            targetInfo = .systemLibraryInfo(\n                pkgConfig: target.pkgConfig,\n                compilerFlags: cFlags,\n                linkerFlags: ldFlags)\n            \n        case let target as BinaryModule:\n            let artifactKind: WireInput.Target.TargetInfo.BinaryArtifactKind\n            switch target.kind {\n            case .artifactsArchive:\n                artifactKind = .artifactsArchive\n            case .xcframework:\n                artifactKind = .xcframework\n            case .unknown:\n                // Skip unknown binary targets.\n                return nil\n            }\n            let artifactOrigin: WireInput.Target.TargetInfo.BinaryArtifactOrigin\n            switch target.origin {\n            case .local:\n                artifactOrigin = .local\n            case .remote(let url):\n                artifactOrigin = .remote(url: url)\n            }\n            targetInfo = .binaryArtifactInfo(\n                kind: artifactKind,\n                origin: artifactOrigin,\n                artifactId: try serialize(path: target.artifactPath))\n            \n        default:\n            // It's not a type of target that we pass through to the plugin.\n            return nil\n        }\n        \n        // We only get this far if we are serializing the target. If so we also serialize its dependencies. This needs to be done before assigning the next wire ID for the target we're serializing, to make sure we end up with the correct one.\n        let dependencies: [WireInput.Target.Dependency] = try target.dependencies(satisfying: buildEnvironment).compactMap {\n            switch $0 {\n            case .module(let target, _):\n                return try serialize(target: target).map { .target(targetId: $0) }\n            case .product(let product, _):\n                return try serialize(product: product).map { .product(productId: $0) }\n            }\n        }\n\n        // Finally assign the next wire ID to the target, and append a serialized Target record.\n        let id = targets.count\n        targets.append(.init(\n            name: target.name,\n            directoryId: try serialize(path: target.sources.root),\n            dependencies: dependencies,\n            info: targetInfo))\n        targetsToWireIDs[target.id] = id\n        return id\n    }\n\n    // Adds a product to the serialized structure, if it isn't already there and\n    // if it is of a kind that should be passed to the plugin. If so, this func-\n    // tion returns the product's wire ID. If not, it returns nil.\n    mutating func serialize(product: ResolvedProduct) throws -> WireInput.Product.Id? {\n        // If we've already seen the product, just return the wire ID we already assigned to it.\n        if let id = productsToWireIDs[product.id] { return id }\n\n        // Look at the product and decide what to serialize. At this point we may decide to not serialize it at all.\n        let productInfo: WireInput.Product.ProductInfo\n        switch product.type {\n            \n        case .executable:\n            let mainExecTarget = try product.executableModule\n            guard let mainExecTargetId = try serialize(target: mainExecTarget) else {\n                throw InternalError(\"unable to serialize main executable target \\(mainExecTarget) for product \\(product)\")\n            }\n            productInfo = .executable(mainTargetId: mainExecTargetId)\n\n        case .library(let kind):\n            switch kind {\n            case .static:\n                productInfo = .library(kind: .static)\n            case .dynamic:\n                productInfo = .library(kind: .dynamic)\n            case .automatic:\n                productInfo = .library(kind: .automatic)\n            }\n\n        default:\n            // It's not a type of product that we pass through to the plugin.\n            return nil\n        }\n        \n        // Finally assign the next wire ID to the product, and append a serialized Product record.\n        let id = products.count\n        products.append(.init(\n            name: product.name,\n            targetIds: try product.modules.compactMap{ try serialize(target: $0) },\n            info: productInfo))\n        productsToWireIDs[product.id] = id\n        return id\n    }\n\n    // Adds a package to the serialized structure, if it isn't already there.\n    // Either way, this function returns the package's wire ID.\n    mutating func serialize(package: ResolvedPackage) throws -> WireInput.Package.Id {\n        // If we've already seen the package, just return the wire ID we already assigned to it.\n        if let id = packagesToWireIDs[package.id] { return id }\n\n        // Determine how we should represent the origin of the package to the plugin.\n        func origin(for package: ResolvedPackage) throws -> WireInput.Package.Origin {\n            switch package.manifest.packageKind {\n            case .root(_):\n                return .root\n            case .fileSystem(let path):\n                return .local(path: try serialize(path: path))\n            case .localSourceControl(let path):\n                return .repository(url: path.asURL.absoluteString, displayVersion: package.manifest.version?.description ?? \"no version\", scmRevision: package.manifest.revision ?? \"no revision\")\n            case .remoteSourceControl(let url):\n                return .repository(url: url.absoluteString, displayVersion: package.manifest.version?.description ?? \"no version\", scmRevision: package.manifest.revision ?? \"no revision\")\n            case .registry(let identity):\n                return .registry(identity: identity.description, displayVersion: package.manifest.version?.description ?? \"no version\")\n            }\n        }\n\n        // Serialize the dependencies. It is important to do this before the `let id = package.count` below so the correct wire ID gets assigned.\n        let dependencies = try modulesGraph.directDependencies(for: package).map {\n            WireInput.Package.Dependency(packageId: try serialize(package: $0))\n        }\n\n        // Assign the next wire ID to the package, and append a serialized Package record.\n        let id = packages.count\n        packages.append(.init(\n            identity: package.identity.description,\n            displayName: package.manifest.displayName,\n            directoryId: try serialize(path: package.path),\n            origin: try origin(for: package),\n            toolsVersion: .init(\n                major: package.manifest.toolsVersion.major,\n                minor: package.manifest.toolsVersion.minor,\n                patch: package.manifest.toolsVersion.patch),\n            dependencies: dependencies,\n            productIds: try package.products.compactMap{ try serialize(product: $0) },\n            targetIds: try package.modules.compactMap{ try serialize(target: $0) }))\n        packagesToWireIDs[package.id] = id\n        return id\n    }\n\n    // Adds an Xcode target to the serialized structure, if it isn't already there and if it is of a kind that should be passed to the plugin. If so, this function returns the target's wire ID. If not, it returns nil.\n    mutating func serialize(xcodeTarget: XcodeProjectRepresentation.Target) throws -> WireInput.XcodeTarget.Id? {\n        // If we've already seen the target, just return the wire ID we already assigned to it.\n        if let id = xcodeTargetsToIds[xcodeTarget] { return id }\n\n        // Create the list of source files.\n        var inputFiles: [WireInput.File] = []\n        inputFiles.append(contentsOf: try xcodeTarget.inputFiles.map {\n            .init(basePathId: try serialize(path: $0.path.parentDirectory), name: $0.path.basename, type: .init($0.role))\n        })\n\n        // Assign the next wire ID to the target, and append a serialized XcodeProject record.\n        let id = xcodeTargets.count\n        xcodeTargets.append(.init(\n            displayName: xcodeTarget.displayName,\n            product: xcodeTarget.product.map{ .init(name: $0.name, kind: .init($0.kind)) },\n            dependencies: [],\n            inputFiles: inputFiles))\n        xcodeTargetsToIds[xcodeTarget] = id\n        return id\n    }\n\n\n    // Adds an Xcode project to the serialized structure, if it isn't already there.\n    // Either way, this function returns the project's wire ID.\n    mutating func serialize(xcodeProject: XcodeProjectRepresentation) throws -> WireInput.XcodeProject.Id {\n        // If we've already seen the project, just return the wire ID we already assigned to it.\n        if let id = xcodeProjectsToIds[xcodeProject] { return id }\n\n        // Assign the next wire ID to the project, and append a serialized XcodeProject record.\n        let id = xcodeProjects.count\n        xcodeProjects.append(.init(\n            displayName: xcodeProject.displayName,\n            directoryPathId: try serialize(path: xcodeProject.directoryPath),\n            dependencies: [],\n            urlIds: try xcodeProject.filePaths.map { try serialize(path: $0) },\n            targetIds: try xcodeProject.targets.compactMap{ try serialize(xcodeTarget: $0) }))\n        xcodeProjectsToIds[xcodeProject] = id\n        return id\n    }\n}\n\nfileprivate extension WireInput.Target.TargetInfo.SourceModuleKind {\n    init(_ kind: Module.Kind) throws {\n        switch kind {\n        case .library:\n            self = .generic\n        case .executable:\n            self = .executable\n        case .snippet:\n            self = .snippet\n        case .test:\n            self = .test\n        case .macro:\n            self = .macro\n        case .binary, .plugin, .systemModule:\n            throw StringError(\"unexpected target kind \\(kind) for source module\")\n        }\n    }\n}\n\nfileprivate extension WireInput.File.FileType {\n    init(_ role: XcodeProjectRepresentation.Target.InputFile.Role) {\n        switch role {\n        case .source:\n            self = .source\n        case .header:\n            self = .header\n        case .resource:\n            self = .resource\n        case .unknown:\n            self = .unknown\n        }\n    }\n}\n\nfileprivate extension WireInput.XcodeTarget.XcodeProduct.Kind {\n    init(_ kind: XcodeProjectRepresentation.Target.Product.Kind) {\n        switch kind {\n        case .application:\n            self = .application\n        case .executable:\n            self = .executable\n        case .framework:\n            self = .framework\n        case .library:\n            self = .library\n        case .other(let ident):\n            self = .other(ident)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/Plugins/PluginInvocation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\nimport _Concurrency\n\nimport Foundation\nimport PackageModel\nimport PackageLoading\nimport PackageGraph\n\nimport struct OrderedCollections.OrderedDictionary\n\nimport protocol TSCBasic.DiagnosticLocation\n\npublic enum PluginAction {\n    case createBuildToolCommands(\n        package: ResolvedPackage,\n        target: ResolvedModule,\n        pluginGeneratedSources: [AbsolutePath],\n        pluginGeneratedResources: [AbsolutePath]\n    )\n    case createXcodeProjectBuildToolCommands(\n        project: XcodeProjectRepresentation,\n        target: XcodeProjectRepresentation.Target,\n        pluginGeneratedSources: [AbsolutePath],\n        pluginGeneratedResources: [AbsolutePath]\n    )\n    case performCommand(package: ResolvedPackage, arguments: [String])\n    case performXcodeProjectCommand(project: XcodeProjectRepresentation, arguments: [String])\n}\n\npublic struct PluginTool {\n    public let path: AbsolutePath\n    public let triples: [String]?\n    public let source: Source\n\n    public enum Source {\n        // Built from an executable target\n        case built\n        // Brought in from a binary target\n        case vended\n    }\n\n    public init(path: AbsolutePath, triples: [String]? = nil, source: Source) {\n        self.path = path\n        self.triples = triples\n        self.source = source\n    }\n}\n\nextension PluginModule {\n    public func invoke(\n        action: PluginAction,\n        buildEnvironment: BuildEnvironment,\n        workers: UInt32,\n        scriptRunner: PluginScriptRunner,\n        workingDirectory: AbsolutePath,\n        outputDirectory: AbsolutePath,\n        toolSearchDirectories: [AbsolutePath],\n        accessibleTools: [String: PluginTool],\n        writableDirectories: [AbsolutePath],\n        readOnlyDirectories: [AbsolutePath],\n        allowNetworkConnections: [SandboxNetworkPermission],\n        pkgConfigDirectories: [AbsolutePath],\n        sdkRootPath: AbsolutePath?,\n        fileSystem: FileSystem,\n        modulesGraph: ModulesGraph,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        delegate: PluginInvocationDelegate\n    ) async throws -> Bool {\n        try await withCheckedThrowingContinuation { continuation in\n            self.invoke(\n                action: action,\n                buildEnvironment: buildEnvironment,\n                workers: workers,\n                scriptRunner: scriptRunner,\n                workingDirectory: workingDirectory,\n                outputDirectory: outputDirectory,\n                toolSearchDirectories: toolSearchDirectories,\n                accessibleTools: accessibleTools,\n                writableDirectories: writableDirectories,\n                readOnlyDirectories: readOnlyDirectories,\n                allowNetworkConnections: allowNetworkConnections,\n                pkgConfigDirectories: pkgConfigDirectories,\n                sdkRootPath: sdkRootPath,\n                fileSystem: fileSystem,\n                modulesGraph: modulesGraph,\n                observabilityScope: observabilityScope,\n                callbackQueue: callbackQueue,\n                delegate: delegate,\n                completion: {\n                    continuation.resume(with: $0)\n                }\n            )\n        }\n    }\n\n    /// Invokes the plugin by compiling its source code (if needed) and then running it as a subprocess. The specified\n    /// plugin action determines which entry point is called in the subprocess, and the package and the tool mapping\n    /// determine the context that is available to the plugin.\n    ///\n    /// The working directory should be a path in the file system into which the plugin is allowed to write information\n    /// that persists between all invocations of a plugin for the same purpose. The exact meaning of \"same\" means here\n    /// depends on the particular plugin; for a build tool plugin, it might be the combination of the plugin and target\n    /// for which it is being invoked.\n    ///\n    /// Note that errors thrown by this function relate to problems actually invoking the plugin. Any diagnostics that\n    /// are emitted by the plugin are contained in the returned result structure.\n    ///\n    /// - Parameters:\n    ///   - action: The plugin action (i.e. entry point) to invoke, possibly containing parameters.\n    ///   - package: The root of the package graph to pass down to the plugin.\n    ///   - scriptRunner: Entity responsible for actually running the code of the plugin.\n    ///   - workingDirectory: The initial working directory of the invoked plugin.\n    ///   - outputDirectory: A directory under which the plugin can write anything it wants to.\n    ///   - toolNamesToPaths: A mapping from name of tools available to the plugin to the corresponding absolute paths.\n    ///   - pkgConfigDirectory: A directory for searching `pkg-config` `.pc` files in it.\n    ///   - fileSystem: The file system to which all of the paths refers.\n    ///\n    /// - Returns: A PluginInvocationResult that contains the results of invoking the plugin.\n    @available(*, noasync, message: \"Use the async alternative\")\n    public func invoke(\n        action: PluginAction,\n        buildEnvironment: BuildEnvironment,\n        workers: UInt32,\n        scriptRunner: PluginScriptRunner,\n        workingDirectory: AbsolutePath,\n        outputDirectory: AbsolutePath,\n        toolSearchDirectories: [AbsolutePath],\n        accessibleTools: [String: PluginTool],\n        writableDirectories: [AbsolutePath],\n        readOnlyDirectories: [AbsolutePath],\n        allowNetworkConnections: [SandboxNetworkPermission],\n        pkgConfigDirectories: [AbsolutePath],\n        sdkRootPath: AbsolutePath?,\n        fileSystem: FileSystem,\n        modulesGraph: ModulesGraph,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        delegate: PluginInvocationDelegate,\n        completion: @escaping (Result<Bool, Error>) -> Void\n    ) {\n        // Create the plugin's output directory if needed (but don't do anything with it if it already exists).\n        do {\n            try fileSystem.createDirectory(outputDirectory, recursive: true)\n        }\n        catch {\n            return callbackQueue.async { completion(.failure(PluginEvaluationError.couldNotCreateOuputDirectory(path: outputDirectory, underlyingError: error))) }\n        }\n\n        // Serialize the plugin action to send as the initial message.\n        let initialMessage: Data\n        do {\n            var serializer = PluginContextSerializer(\n                fileSystem: fileSystem,\n                modulesGraph: modulesGraph,\n                buildEnvironment: buildEnvironment,\n                pkgConfigDirectories: pkgConfigDirectories,\n                sdkRootPath: sdkRootPath\n            )\n            let pluginWorkDirId = try serializer.serialize(path: outputDirectory)\n            let toolSearchDirIds = try toolSearchDirectories.map{ try serializer.serialize(path: $0) }\n            let accessibleTools = try accessibleTools.mapValues { (tool) -> HostToPluginMessage.InputContext.Tool in\n                let path = try serializer.serialize(path: tool.path)\n                return .init(path: path, triples: tool.triples)\n            }\n            let actionMessage: HostToPluginMessage\n            switch action {\n\n            case .createBuildToolCommands(let package, let target, let pluginGeneratedSources, let pluginGeneratedResources):\n                let rootPackageId = try serializer.serialize(package: package)\n                guard let targetId = try serializer.serialize(target: target) else {\n                    throw StringError(\"unexpectedly was unable to serialize target \\(target)\")\n                }\n                let generatedSources = try pluginGeneratedSources.map { try serializer.serialize(path: $0) }\n                let generatedResources = try pluginGeneratedResources.map { try serializer.serialize(path: $0) }\n                let wireInput = WireInput(\n                    paths: serializer.paths,\n                    targets: serializer.targets,\n                    products: serializer.products,\n                    packages: serializer.packages,\n                    xcodeTargets: serializer.xcodeTargets,\n                    xcodeProjects: serializer.xcodeProjects,\n                    pluginWorkDirId: pluginWorkDirId,\n                    toolSearchDirIds: toolSearchDirIds,\n                    accessibleTools: accessibleTools)\n                actionMessage = .createBuildToolCommands(\n                    context: wireInput,\n                    rootPackageId: rootPackageId,\n                    targetId: targetId,\n                    pluginGeneratedSources: generatedSources,\n                    pluginGeneratedResources: generatedResources\n                )\n\n            case .createXcodeProjectBuildToolCommands(let project, let target, let generatedSources, let generatedResources):\n                let rootProjectId = try serializer.serialize(xcodeProject: project)\n                guard let targetId = try serializer.serialize(xcodeTarget: target) else {\n                    throw StringError(\"unexpectedly was unable to serialize target \\(target)\")\n                }\n                let pluginGeneratedSources = try generatedSources.map { try serializer.serialize(path: $0) }\n                let pluginGeneratedResources = try generatedResources.map { try serializer.serialize(path: $0) }\n                let wireInput = WireInput(\n                    paths: serializer.paths,\n                    targets: serializer.targets,\n                    products: serializer.products,\n                    packages: serializer.packages,\n                    xcodeTargets: serializer.xcodeTargets,\n                    xcodeProjects: serializer.xcodeProjects,\n                    pluginWorkDirId: pluginWorkDirId,\n                    toolSearchDirIds: toolSearchDirIds,\n                    accessibleTools: accessibleTools)\n                actionMessage = .createXcodeProjectBuildToolCommands(\n                    context: wireInput,\n                    rootProjectId: rootProjectId,\n                    targetId: targetId,\n                    pluginGeneratedSources: pluginGeneratedSources,\n                    pluginGeneratedResources: pluginGeneratedResources\n                )\n\n            case .performCommand(let package, let arguments):\n                let rootPackageId = try serializer.serialize(package: package)\n                let wireInput = WireInput(\n                    paths: serializer.paths,\n                    targets: serializer.targets,\n                    products: serializer.products,\n                    packages: serializer.packages,\n                    xcodeTargets: serializer.xcodeTargets,\n                    xcodeProjects: serializer.xcodeProjects,\n                    pluginWorkDirId: pluginWorkDirId,\n                    toolSearchDirIds: toolSearchDirIds,\n                    accessibleTools: accessibleTools)\n                actionMessage = .performCommand(\n                    context: wireInput,\n                    rootPackageId: rootPackageId,\n                    arguments: arguments)\n                \n            case .performXcodeProjectCommand(let xcodeProject, let arguments):\n                let rootProjectId = try serializer.serialize(xcodeProject: xcodeProject)\n                let wireInput = WireInput(\n                    paths: serializer.paths,\n                    targets: serializer.targets,\n                    products: serializer.products,\n                    packages: serializer.packages,\n                    xcodeTargets: serializer.xcodeTargets,\n                    xcodeProjects: serializer.xcodeProjects,\n                    pluginWorkDirId: pluginWorkDirId,\n                    toolSearchDirIds: toolSearchDirIds,\n                    accessibleTools: accessibleTools)\n                actionMessage = .performXcodeProjectCommand(\n                    context: wireInput,\n                    rootProjectId: rootProjectId,\n                    arguments: arguments)\n            }\n            initialMessage = try actionMessage.toData()\n        }\n        catch {\n            return callbackQueue.async { completion(.failure(PluginEvaluationError.couldNotSerializePluginInput(underlyingError: error))) }\n        }\n\n        // Handle messages and output from the plugin.\n        class ScriptRunnerDelegate: PluginScriptCompilerDelegate, PluginScriptRunnerDelegate {\n            /// Delegate that should be told about events involving the plugin.\n            let invocationDelegate: PluginInvocationDelegate\n\n            /// Observability scope for the invoking of the plugin. Diagnostics from the plugin itself are sent through the delegate.\n            let observabilityScope: ObservabilityScope\n\n            /// Whether at least one error has been reported; this is used to make sure there is at least one error if the plugin fails.\n            var hasReportedError = false\n\n            /// If this is true, we exited early with an error.\n            var exitEarly = false\n\n            init(invocationDelegate: PluginInvocationDelegate, observabilityScope: ObservabilityScope) {\n                self.invocationDelegate = invocationDelegate\n                self.observabilityScope = observabilityScope\n            }\n\n            func willCompilePlugin(commandLine: [String], environment: [String: String]) {\n                invocationDelegate.pluginCompilationStarted(commandLine: commandLine, environment: environment)\n            }\n\n            func didCompilePlugin(result: PluginCompilationResult) {\n                invocationDelegate.pluginCompilationEnded(result: result)\n            }\n\n            func skippedCompilingPlugin(cachedResult: PluginCompilationResult) {\n                invocationDelegate.pluginCompilationWasSkipped(cachedResult: cachedResult)\n            }\n\n            /// Invoked when the plugin emits arbitrary data on its stdout/stderr. There is no guarantee that the data is split on UTF-8 character encoding boundaries etc.  The script runner delegate just passes it on to the invocation delegate.\n            func handleOutput(data: Data) {\n                invocationDelegate.pluginEmittedOutput(data)\n            }\n\n            /// Invoked when the plugin emits a message. The `responder` closure can be used to send any reply messages.\n            func handleMessage(data: Data, responder: @escaping (Data) -> Void) throws {\n                let message = try PluginToHostMessage(data)\n                switch message {\n\n                case .emitDiagnostic(let severity, let message, let file, let line):\n                    let metadata: ObservabilityMetadata? = file.map {\n                        var metadata = ObservabilityMetadata()\n                        // FIXME: We should probably report some kind of protocol error if the path isn't valid.\n                        metadata.fileLocation = try? .init(.init(validating: $0), line: line)\n                        return metadata\n                    }\n                    let diagnostic: Basics.Diagnostic\n                    switch severity {\n                    case .error:\n                        diagnostic = .error(message, metadata: metadata)\n                        hasReportedError = true\n                    case .warning:\n                        diagnostic = .warning(message, metadata: metadata)\n                    case .remark:\n                        diagnostic = .info(message, metadata: metadata)\n                    }\n                    self.invocationDelegate.pluginEmittedDiagnostic(diagnostic)\n\n                case .emitProgress(let message):\n                    self.invocationDelegate.pluginEmittedProgress(message)\n\n                case .defineBuildCommand(let config, let inputFiles, let outputFiles):\n                    if config.version != 2 {\n                        throw PluginEvaluationError.pluginUsesIncompatibleVersion(expected: 2, actual: config.version)\n                    }\n                    self.invocationDelegate.pluginDefinedBuildCommand(\n                        displayName: config.displayName,\n                        executable: try config.executable.filePath,\n                        arguments: config.arguments,\n                        environment: config.environment,\n                        workingDirectory: try config.workingDirectory.map{ try $0.filePath },\n                        inputFiles: try inputFiles.map{ try $0.filePath },\n                        outputFiles: try outputFiles.map{ try $0.filePath })\n\n                case .definePrebuildCommand(let config, let outputFilesDir):\n                    if config.version != 2 {\n                        throw PluginEvaluationError.pluginUsesIncompatibleVersion(expected: 2, actual: config.version)\n                    }\n                    let success = self.invocationDelegate.pluginDefinedPrebuildCommand(\n                        displayName: config.displayName,\n                        executable: try config.executable.filePath,\n                        arguments: config.arguments,\n                        environment: config.environment,\n                        workingDirectory: try config.workingDirectory.map{ try $0.filePath },\n                        outputFilesDirectory: try outputFilesDir.filePath)\n\n                    if !success {\n                        exitEarly = true\n                        hasReportedError = true\n                    }\n\n                case .buildOperationRequest(let subset, let parameters):\n                    self.invocationDelegate.pluginRequestedBuildOperation(subset: .init(subset), parameters: .init(parameters)) {\n                        do {\n                            switch $0 {\n                            case .success(let result):\n                                responder(try HostToPluginMessage.buildOperationResponse(result: .init(result)).toData())\n                            case .failure(let error):\n                                responder(try HostToPluginMessage.errorResponse(error: String(describing: error)).toData())\n                            }\n                        }\n                        catch {\n                            self.observabilityScope.emit(debug: \"couldn't send reply to plugin\", underlyingError: error)\n                        }\n                    }\n\n                case .testOperationRequest(let subset, let parameters):\n                    self.invocationDelegate.pluginRequestedTestOperation(subset: .init(subset), parameters: .init(parameters)) {\n                        do {\n                            switch $0 {\n                            case .success(let result):\n                                responder(try HostToPluginMessage.testOperationResponse(result: .init(result)).toData())\n                            case .failure(let error):\n                                responder(try HostToPluginMessage.errorResponse(error: String(describing: error)).toData())\n                            }\n                        }\n                        catch {\n                            self.observabilityScope.emit(debug: \"couldn't send reply to plugin\", underlyingError: error)\n                        }\n                    }\n\n                case .symbolGraphRequest(let targetName, let options):\n                    // The plugin requested symbol graph information for a target. We ask the delegate and then send a response.\n                    self.invocationDelegate.pluginRequestedSymbolGraph(forTarget: .init(targetName), options: .init(options)) {\n                        do {\n                            switch $0 {\n                            case .success(let result):\n                                responder(try HostToPluginMessage.symbolGraphResponse(result: .init(result)).toData())\n                            case .failure(let error):\n                                responder(try HostToPluginMessage.errorResponse(error: String(describing: error)).toData())\n                            }\n                        }\n                        catch {\n                            self.observabilityScope.emit(debug: \"couldn't send reply to plugin\", underlyingError: error)\n                        }\n                    }\n                }\n            }\n        }\n        let runnerDelegate = ScriptRunnerDelegate(invocationDelegate: delegate, observabilityScope: observabilityScope)\n\n        // Call the plugin script runner to actually invoke the plugin.\n        scriptRunner.runPluginScript(\n            sourceFiles: sources.paths,\n            pluginName: self.name,\n            initialMessage: initialMessage,\n            toolsVersion: self.apiVersion,\n            workingDirectory: workingDirectory,\n            writableDirectories: writableDirectories,\n            readOnlyDirectories: readOnlyDirectories,\n            allowNetworkConnections: allowNetworkConnections,\n            workers: workers,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            callbackQueue: callbackQueue,\n            delegate: runnerDelegate) { result in\n                dispatchPrecondition(condition: .onQueue(callbackQueue))\n                completion(result.map { exitCode in\n                    // Return a result based on the exit code or the `exitEarly` parameter. If the plugin\n                    // exits with an error but hasn't already emitted an error, we do so for it.\n                    let exitedCleanly = (exitCode == 0) && !runnerDelegate.exitEarly\n                    if !exitedCleanly && !runnerDelegate.hasReportedError {\n                        delegate.pluginEmittedDiagnostic(\n                            .error(\"Plugin ended with exit code \\(exitCode)\")\n                        )\n                    }\n                    return exitedCleanly\n                })\n        }\n    }\n\n    package func invoke(\n        module: ResolvedModule,\n        action: PluginAction,\n        buildEnvironment: BuildEnvironment,\n        workers: UInt32,\n        scriptRunner: PluginScriptRunner,\n        workingDirectory: AbsolutePath,\n        outputDirectory: AbsolutePath,\n        toolSearchDirectories: [AbsolutePath],\n        accessibleTools: [String: PluginTool],\n        writableDirectories: [AbsolutePath],\n        readOnlyDirectories: [AbsolutePath],\n        allowNetworkConnections: [SandboxNetworkPermission],\n        pkgConfigDirectories: [AbsolutePath],\n        sdkRootPath: AbsolutePath?,\n        fileSystem: FileSystem,\n        modulesGraph: ModulesGraph,\n        observabilityScope: ObservabilityScope\n    ) async throws -> BuildToolPluginInvocationResult {\n        try await withCheckedThrowingContinuation { continuation in\n            self.invoke(\n                module: module,\n                action: action,\n                buildEnvironment: buildEnvironment,\n                workers: workers,\n                scriptRunner: scriptRunner,\n                workingDirectory: workingDirectory,\n                outputDirectory: outputDirectory,\n                toolSearchDirectories: toolSearchDirectories,\n                accessibleTools: accessibleTools,\n                writableDirectories: writableDirectories,\n                readOnlyDirectories: readOnlyDirectories,\n                allowNetworkConnections: allowNetworkConnections,\n                pkgConfigDirectories: pkgConfigDirectories,\n                sdkRootPath: sdkRootPath,\n                fileSystem: fileSystem,\n                modulesGraph: modulesGraph,\n                observabilityScope: observabilityScope,\n                completion: {\n                    continuation.resume(with: $0)\n                }\n            )\n        }\n    }\n\n    /// This is a convenient way to get results of the plugin invocation without having\n    /// to deal with delegates and other internal details.\n    @available(*, noasync, message: \"Use the async alternative\")\n    package func invoke(\n        module: ResolvedModule,\n        action: PluginAction,\n        buildEnvironment: BuildEnvironment,\n        workers: UInt32,\n        scriptRunner: PluginScriptRunner,\n        workingDirectory: AbsolutePath,\n        outputDirectory: AbsolutePath,\n        toolSearchDirectories: [AbsolutePath],\n        accessibleTools: [String: PluginTool],\n        writableDirectories: [AbsolutePath],\n        readOnlyDirectories: [AbsolutePath],\n        allowNetworkConnections: [SandboxNetworkPermission],\n        pkgConfigDirectories: [AbsolutePath],\n        sdkRootPath: AbsolutePath?,\n        fileSystem: FileSystem,\n        modulesGraph: ModulesGraph,\n        observabilityScope: ObservabilityScope,\n        completion: @escaping (Result<BuildToolPluginInvocationResult, Error>) -> Void\n    ) {\n        /// Determine the package that contains the target.\n        guard let package = modulesGraph.package(for: module) else {\n            completion(.failure(InternalError(\"Could not find package for \\(self)\")))\n            return\n        }\n\n        // Set up a delegate to handle callbacks from the build tool plugin.\n        // We'll capture free-form text output as well as defined commands and diagnostics.\n        let delegateQueue = DispatchQueue(label: \"plugin-invocation\")\n\n        // Determine additional input dependencies for any plugin commands,\n        // based on any executables the plugin target depends on.\n        let toolPaths = accessibleTools.values.map(\\.path).sorted()\n        \n        let builtToolPaths = accessibleTools.values.filter({ $0.source == .built }).map((\\.path)).sorted()\n\n        let delegate = DefaultPluginInvocationDelegate(\n            fileSystem: fileSystem,\n            delegateQueue: delegateQueue,\n            toolPaths: toolPaths,\n            builtToolPaths: builtToolPaths\n        )\n\n        let startTime = DispatchTime.now()\n\n        self.invoke(\n            action: action,\n            buildEnvironment: buildEnvironment,\n            workers: workers,\n            scriptRunner: scriptRunner,\n            workingDirectory: workingDirectory,\n            outputDirectory: outputDirectory,\n            toolSearchDirectories: toolSearchDirectories,\n            accessibleTools: accessibleTools,\n            writableDirectories: writableDirectories,\n            readOnlyDirectories: readOnlyDirectories,\n            allowNetworkConnections: allowNetworkConnections,\n            pkgConfigDirectories: pkgConfigDirectories,\n            sdkRootPath: sdkRootPath,\n            fileSystem: fileSystem,\n            modulesGraph: modulesGraph,\n            observabilityScope: observabilityScope,\n            callbackQueue: delegateQueue,\n            delegate: delegate,\n            completion: {\n                let duration = startTime.distance(to: .now())\n\n                let success: Bool = switch $0 {\n                case .success(let result):\n                    result\n                case .failure:\n                    false\n                }\n\n                let invocationResult = BuildToolPluginInvocationResult(\n                    plugin: self,\n                    pluginOutputDirectory: outputDirectory,\n                    package: package,\n                    target: module,\n                    succeeded: success,\n                    duration: duration,\n                    diagnostics: delegate.diagnostics,\n                    textOutput: String(decoding: delegate.outputData, as: UTF8.self),\n                    buildCommands: delegate.buildCommands,\n                    prebuildCommands: delegate.prebuildCommands\n                )\n\n                completion(.success(invocationResult))\n            }\n        )\n    }\n}\n\nfileprivate extension HostToPluginMessage {\n    func toData() throws -> Data {\n        return try JSONEncoder.makeWithDefaults().encode(self)\n    }\n}\n\nfileprivate extension PluginToHostMessage {\n    init(_ data: Data) throws {\n        self = try JSONDecoder.makeWithDefaults().decode(Self.self, from: data)\n    }\n}\n\nextension ModulesGraph {\n    public func pluginsPerModule(\n        satisfying buildEnvironment: BuildEnvironment\n    ) -> [ResolvedModule.ID: [ResolvedModule]] {\n        var pluginsPerModule = [ResolvedModule.ID: [ResolvedModule]]()\n        for module in self.allModules.sorted(by: { $0.name < $1.name }) {\n            let pluginDependencies = module.pluginDependencies(\n                satisfying: buildEnvironment\n            )\n            if !pluginDependencies.isEmpty {\n                pluginsPerModule[module.id] = pluginDependencies\n            }\n        }\n        return pluginsPerModule\n    }\n\n    public static func computePluginGeneratedFiles(\n        target: ResolvedModule,\n        toolsVersion: ToolsVersion,\n        additionalFileRules: [FileRuleDescription],\n        buildParameters: BuildParameters,\n        buildToolPluginInvocationResults: [BuildToolPluginInvocationResult],\n        prebuildCommandResults: [CommandPluginResult],\n        observabilityScope: ObservabilityScope\n    ) -> GeneratedFiles {\n        // Add any derived files that were declared for any commands from plugin invocations.\n        var generatedFiles = GeneratedFiles()\n\n        for result in buildToolPluginInvocationResults {\n            let files = TargetSourcesBuilder.computeContents(\n                for: result.buildCommands.flatMap(\\.outputFiles),\n                toolsVersion: toolsVersion,\n                additionalFileRules: additionalFileRules,\n                defaultLocalization: target.defaultLocalization,\n                module: target.underlying,\n                observabilityScope: observabilityScope\n            )\n            generatedFiles.add(files)\n            if !files.headers.isEmpty {\n                // Capture the public include directory if there were header files generated there\n                // Hardcoding as the default for now\n                let publicDir = result.pluginOutputDirectory.appending(ClangModule.defaultPublicHeadersComponent)\n                if files.headers.contains(where: { $0.isDescendantOfOrEqual(to: publicDir) }) {\n                    generatedFiles.publicHeaderPaths.append(publicDir)\n                }\n            }\n        }\n\n        // Add any derived files that were discovered from output directories of prebuild commands.\n        for result in prebuildCommandResults {\n            let files = TargetSourcesBuilder.computeContents(\n                for: result.derivedFiles,\n                toolsVersion: toolsVersion,\n                additionalFileRules: additionalFileRules,\n                defaultLocalization: target.defaultLocalization,\n                module: target.underlying,\n                observabilityScope: observabilityScope\n            )\n            if !files.headers.isEmpty {\n                observabilityScope.emit(warning: \"C header file generation not supported in prebuilt commands: \\(target.name)\")\n            }\n            if !files.moduleMaps.isEmpty {\n                observabilityScope.emit(warning: \"Module map generation not supported in prebuilt commands: \\(target.name)\")\n            }\n            if !files.apiNotes.isEmpty {\n                observabilityScope.emit(warning: \"API note generation not supported in prebuilt commands: \\(target.name)\")\n            }\n            generatedFiles.add(GeneratedFiles(sources: files.sources, resources: files.resources))\n        }\n\n        return generatedFiles\n    }\n}\n\n/// A description of a tool to which a plugin has access.\npublic enum PluginAccessibleTool: Hashable {\n    /// A tool that is built by an ExecutableTarget (the path is relative to the built-products directory).\n    case builtTool(name: String, path: RelativePath)\n\n    /// A tool that is vended by a BinaryTarget (the path is absolute and refers to an unpackaged binary target).\n    case vendedTool(name: String, path: AbsolutePath, supportedTriples: [String])\n}\n\n/// The set of tools that are accessible to this plugin.\nfileprivate func collectAccessibleTools(\n    plugin: ResolvedModule,\n    fileSystem: FileSystem,\n    environment: BuildEnvironment,\n    for hostTriple: Triple\n) throws -> Set<PluginAccessibleTool> {\n    precondition(plugin.underlying is PluginModule)\n    return try Set(plugin.dependencies(satisfying: environment).flatMap { dependency -> [PluginAccessibleTool] in\n        let builtToolName: String\n        let executableOrBinaryModule: Module\n        switch dependency {\n        case .module(let module, _):\n            builtToolName = module.name\n            executableOrBinaryModule = module.underlying\n        case .product(let product, _):\n            guard let executableModule = product.modules.map({ $0.underlying }).executables.spm_only\n            else {\n                throw StringError(\"no product named \\(product.name)\")\n            }\n            builtToolName = product.name\n            executableOrBinaryModule = executableModule\n        }\n\n        // For a binary target we create a `vendedTool`.\n        if let module = executableOrBinaryModule as? BinaryModule {\n            // TODO: Memoize this result for the host triple\n            let execInfos = try module.parseExecutableArtifactArchives(for: hostTriple, fileSystem: fileSystem)\n            return try execInfos.map {\n                .vendedTool(\n                    name: $0.name,\n                    path: $0.executablePath,\n                    supportedTriples: try $0.supportedTriples.map { try $0.withoutVersion().tripleString }\n                )\n            }\n        }\n        // For an executable target we create a `builtTool`.\n        else if executableOrBinaryModule.type == .executable {\n            let exeName = executableOrBinaryModule.name + hostTriple.executableExtension\n            return try [.builtTool(name: builtToolName, path: RelativePath(validating: exeName))]\n        }\n        else {\n            return []\n        }\n    })\n}\n\npublic extension ResolvedModule {\n    func preparePluginTools(\n        fileSystem: FileSystem,\n        environment: BuildEnvironment,\n        for hostTriple: Triple,\n        builtToolHandler: (_ name: String, _ path: RelativePath) async throws -> AbsolutePath?\n    ) async throws -> [String: PluginTool] {\n        precondition(self.underlying is PluginModule)\n\n        var tools: [String: PluginTool] = [:]\n\n        for tool in try collectAccessibleTools(\n            plugin: self,\n            fileSystem: fileSystem,\n            environment: environment,\n            for: hostTriple\n        ) {\n            switch tool {\n            case .builtTool(let name, let path):\n                if let path = try await builtToolHandler(name, path) {\n                    tools[name] = PluginTool(path: path, source: .built)\n                }\n            case .vendedTool(let name, let path, let triples):\n                // Avoid having the path of an unsupported tool overwrite a supported one.\n                guard !triples.isEmpty || tools[name] == nil else {\n                    continue\n                }\n                let priorTriples = tools[name]?.triples ?? []\n                tools[name] = PluginTool(path: path, triples: priorTriples + triples, source: .vended)\n            }\n        }\n\n        return tools\n    }\n}\n\n/// Represents the result of invoking a build tool plugin for a particular target. The result includes generated build commands and prebuild commands as well as any diagnostics and stdout/stderr output emitted by the plugin.\npublic struct BuildToolPluginInvocationResult {\n    /// The plugin that produced the results.\n    public var plugin: PluginModule\n\n    /// The directory given to the plugin as a place in which it and the commands are allowed to write.\n    public var pluginOutputDirectory: AbsolutePath\n\n    /// The package to which the plugin was applied.\n    public var package: ResolvedPackage\n\n    /// The target in that package to which the plugin was applied.\n    public var target: ResolvedModule\n\n    /// If the plugin finished successfully.\n    public var succeeded: Bool\n\n    /// Duration of the plugin invocation.\n    public var duration: DispatchTimeInterval\n\n    /// Any diagnostics emitted by the plugin.\n    public var diagnostics: [Basics.Diagnostic]\n\n    /// Any textual output emitted by the plugin.\n    public var textOutput: String\n\n    /// The build commands generated by the plugin (in the order in which they should run).\n    public var buildCommands: [BuildCommand]\n\n    /// The prebuild commands generated by the plugin (in the order in which they should run).\n    public var prebuildCommands: [PrebuildCommand]\n\n    /// A command to incorporate into the build graph so that it runs during the build whenever it needs to.\n    public struct BuildCommand {\n        public var configuration: CommandConfiguration\n        public var inputFiles: [AbsolutePath]\n        public var outputFiles: [AbsolutePath]\n    }\n\n    /// A command to run before the start of every build.\n    public struct PrebuildCommand {\n        // TODO: In the future these should be folded into regular build commands when the build system can handle not knowing the names of all the outputs before the command runs.\n        public var configuration: CommandConfiguration\n        public var outputFilesDirectory: AbsolutePath\n    }\n\n    /// Launch configuration of a command that can be run (including a display name to show in logs etc).\n    public struct CommandConfiguration {\n        public var displayName: String?\n        public var executable: AbsolutePath\n        public var arguments: [String]\n        public var environment: Environment\n        public var workingDirectory: AbsolutePath?\n    }\n\n    /// A location representing a file name or path and an optional line number.\n    // FIXME: This should be part of the Diagnostics APIs.\n    struct FileLineLocation: DiagnosticLocation {\n        var file: String\n        var line: Int?\n        var description: String {\n            \"\\(file)\\(line.map{\":\\($0)\"} ?? \"\")\"\n        }\n    }\n}\n\n\n/// An error in plugin evaluation.\npublic enum PluginEvaluationError: Swift.Error {\n    case couldNotFindPackage(for: PluginModule)\n    case couldNotCreateOuputDirectory(path: AbsolutePath, underlyingError: Error)\n    case couldNotSerializePluginInput(underlyingError: Error)\n    case runningPluginFailed(underlyingError: Error)\n    case decodingPluginOutputFailed(json: Data, underlyingError: Error)\n    case pluginUsesIncompatibleVersion(expected: Int, actual: Int)\n}\n\npublic protocol PluginInvocationDelegate {\n    /// Called before a plugin is compiled. This call is always followed by a `pluginCompilationEnded()`, but is mutually exclusive with `pluginCompilationWasSkipped()` (which is called if the plugin didn't need to be recompiled).\n    func pluginCompilationStarted(commandLine: [String], environment: [String: String])\n\n    /// Called after a plugin is compiled. This call always follows a `pluginCompilationStarted()`, but is mutually exclusive with `pluginCompilationWasSkipped()` (which is called if the plugin didn't need to be recompiled).\n    func pluginCompilationEnded(result: PluginCompilationResult)\n\n    /// Called if a plugin didn't need to be recompiled. This call is always mutually exclusive with `pluginCompilationStarted()` and `pluginCompilationEnded()`.\n    func pluginCompilationWasSkipped(cachedResult: PluginCompilationResult)\n\n    /// Called for each piece of textual output data emitted by the plugin. Note that there is no guarantee that the data begins and ends on a UTF-8 byte sequence boundary (much less on a line boundary) so the delegate should buffer partial data as appropriate.\n    func pluginEmittedOutput(_: Data)\n\n    /// Called when a plugin emits a diagnostic through the PackagePlugin APIs.\n    func pluginEmittedDiagnostic(_: Basics.Diagnostic)\n\n    /// Called when a plugin emits a progress message through the PackagePlugin APIs.\n    func pluginEmittedProgress(_: String)\n\n    /// Called when a plugin defines a build command through the PackagePlugin APIs.\n    func pluginDefinedBuildCommand(displayName: String?, executable: AbsolutePath, arguments: [String], environment: [String: String], workingDirectory: AbsolutePath?, inputFiles: [AbsolutePath], outputFiles: [AbsolutePath])\n\n    /// Called when a plugin defines a prebuild command through the PackagePlugin APIs.\n    func pluginDefinedPrebuildCommand(displayName: String?, executable: AbsolutePath, arguments: [String], environment: [String: String], workingDirectory: AbsolutePath?, outputFilesDirectory: AbsolutePath) -> Bool\n\n    /// Called when a plugin requests a build operation through the PackagePlugin APIs.\n    func pluginRequestedBuildOperation(subset: PluginInvocationBuildSubset, parameters: PluginInvocationBuildParameters, completion: @escaping (Result<PluginInvocationBuildResult, Error>) -> Void)\n\n    /// Called when a plugin requests a test operation through the PackagePlugin APIs.\n    func pluginRequestedTestOperation(subset: PluginInvocationTestSubset, parameters: PluginInvocationTestParameters, completion: @escaping (Result<PluginInvocationTestResult, Error>) -> Void)\n\n    /// Called when a plugin requests that the host computes and returns symbol graph information for a particular target.\n    func pluginRequestedSymbolGraph(forTarget name: String, options: PluginInvocationSymbolGraphOptions, completion: @escaping (Result<PluginInvocationSymbolGraphResult, Error>) -> Void)\n}\n\nfinal class DefaultPluginInvocationDelegate: PluginInvocationDelegate {\n    let fileSystem: FileSystem\n    let delegateQueue: DispatchQueue\n    let toolPaths: [AbsolutePath]\n    let builtToolPaths: [AbsolutePath]\n    var outputData = Data()\n    var diagnostics = [Basics.Diagnostic]()\n    var buildCommands = [BuildToolPluginInvocationResult.BuildCommand]()\n    var prebuildCommands = [BuildToolPluginInvocationResult.PrebuildCommand]()\n\n    package init(\n        fileSystem: FileSystem,\n        delegateQueue: DispatchQueue,\n        toolPaths: [AbsolutePath],\n        builtToolPaths: [AbsolutePath]\n    ) {\n        self.fileSystem = fileSystem\n        self.delegateQueue = delegateQueue\n        self.toolPaths = toolPaths\n        self.builtToolPaths = builtToolPaths\n    }\n\n    func pluginCompilationStarted(commandLine: [String], environment: [String: String]) {}\n\n    func pluginCompilationEnded(result: PluginCompilationResult) {}\n\n    func pluginCompilationWasSkipped(cachedResult: PluginCompilationResult) {}\n\n    func pluginEmittedOutput(_ data: Data) {\n        dispatchPrecondition(condition: .onQueue(self.delegateQueue))\n        self.outputData.append(contentsOf: data)\n    }\n\n    func pluginEmittedProgress(_: String) {}\n\n    func pluginEmittedDiagnostic(_ diagnostic: Basics.Diagnostic) {\n        dispatchPrecondition(condition: .onQueue(self.delegateQueue))\n        self.diagnostics.append(diagnostic)\n    }\n\n    func pluginDefinedBuildCommand(\n        displayName: String?,\n        executable: AbsolutePath,\n        arguments: [String],\n        environment: [String: String],\n        workingDirectory: AbsolutePath?,\n        inputFiles: [AbsolutePath],\n        outputFiles: [AbsolutePath]\n    ) {\n        dispatchPrecondition(condition: .onQueue(self.delegateQueue))\n        self.buildCommands.append(.init(\n            configuration: .init(\n                displayName: displayName,\n                executable: executable,\n                arguments: arguments,\n                environment: .init(environment),\n                workingDirectory: workingDirectory\n            ),\n            inputFiles: self.toolPaths + inputFiles,\n            outputFiles: outputFiles\n        ))\n    }\n\n    func pluginDefinedPrebuildCommand(\n        displayName: String?,\n        executable: AbsolutePath,\n        arguments: [String],\n        environment: [String: String],\n        workingDirectory: AbsolutePath?,\n        outputFilesDirectory: AbsolutePath\n    ) -> Bool {\n        dispatchPrecondition(condition: .onQueue(self.delegateQueue))\n        // executable must exist before running prebuild command\n        if builtToolPaths.contains(executable) {\n            self.diagnostics\n                .append(\n                    .error(\n                        \"a prebuild command cannot use executables built from source, including executable target '\\(executable.basename)'\"\n                    )\n                )\n            return false\n        }\n        self.prebuildCommands.append(.init(\n            configuration: .init(\n                displayName: displayName,\n                executable: executable,\n                arguments: arguments,\n                environment: .init(environment),\n                workingDirectory: workingDirectory\n            ),\n            outputFilesDirectory: outputFilesDirectory\n        ))\n        return true\n    }\n}\n\npublic struct PluginInvocationSymbolGraphOptions {\n    public var minimumAccessLevel: AccessLevel\n    public enum AccessLevel: String {\n        case `private`, `fileprivate`, `internal`, `package`, `public`, `open`\n    }\n    public var includeInheritedDocs: Bool\n    public var includeSynthesized: Bool\n    public var includeSPI: Bool\n    public var emitExtensionBlocks: Bool\n}\n\npublic struct PluginInvocationSymbolGraphResult {\n    public var directoryPath: String\n    public init(directoryPath: String) {\n        self.directoryPath = directoryPath\n    }\n}\n\npublic enum PluginInvocationBuildSubset {\n    case all(includingTests: Bool)\n    case product(String)\n    case target(String)\n}\n\npublic struct PluginInvocationBuildParameters {\n    public var configuration: Configuration\n    public enum Configuration: String {\n        case debug, release, inherit\n    }\n    public var logging: LogVerbosity\n    public enum LogVerbosity: String {\n        case concise, verbose, debug\n    }\n    public var echoLogs: Bool\n    public var otherCFlags: [String]\n    public var otherCxxFlags: [String]\n    public var otherSwiftcFlags: [String]\n    public var otherLinkerFlags: [String]\n}\n\npublic struct PluginInvocationBuildResult {\n    public var succeeded: Bool\n    public var logText: String\n    public var builtArtifacts: [BuiltArtifact]\n    public struct BuiltArtifact {\n        public var path: String\n        public var kind: Kind\n        public enum Kind: String {\n            case executable, dynamicLibrary, staticLibrary\n        }\n        public init(path: String, kind: Kind) {\n            self.path = path\n            self.kind = kind\n        }\n    }\n    public init(succeeded: Bool, logText: String, builtArtifacts: [BuiltArtifact]) {\n        self.succeeded = succeeded\n        self.logText = logText\n        self.builtArtifacts = builtArtifacts\n    }\n}\n\npublic enum PluginInvocationTestSubset {\n    case all\n    case filtered([String])\n}\n\npublic struct PluginInvocationTestParameters {\n    public var enableCodeCoverage: Bool\n}\n\npublic struct PluginInvocationTestResult {\n    public var succeeded: Bool\n    public var testTargets: [TestTarget]\n    public var codeCoverageDataFile: String?\n\n    public struct TestTarget {\n        public var name: String\n        public var testCases: [TestCase]\n        public struct TestCase {\n            public var name: String\n            public var tests: [Test]\n            public struct Test {\n                public var name: String\n                public var result: Result\n                public var duration: Double\n                public enum Result: String {\n                    case succeeded, skipped, failed\n                }\n                public init(name: String, result: Result, duration: Double) {\n                    self.name = name\n                    self.result = result\n                    self.duration = duration\n                }\n            }\n            public init(name: String, tests: [Test]) {\n                self.name = name\n                self.tests = tests\n            }\n        }\n        public init(name: String, testCases: [TestCase]) {\n            self.name = name\n            self.testCases = testCases\n        }\n    }\n    public init(succeeded: Bool, testTargets: [TestTarget], codeCoverageDataFile: String?) {\n        self.succeeded = succeeded\n        self.testTargets = testTargets\n        self.codeCoverageDataFile = codeCoverageDataFile\n    }\n}\n\npublic extension PluginInvocationDelegate {\n    func pluginDefinedBuildCommand(displayName: String?, executable: AbsolutePath, arguments: [String], environment: [String: String], workingDirectory: AbsolutePath?, inputFiles: [AbsolutePath], outputFiles: [AbsolutePath]) {\n    }\n    func pluginDefinedPrebuildCommand(displayName: String?, executable: AbsolutePath, arguments: [String], environment: [String: String], workingDirectory: AbsolutePath?, outputFilesDirectory: AbsolutePath) -> Bool {\n        return true\n    }\n    func pluginRequestedBuildOperation(subset: PluginInvocationBuildSubset, parameters: PluginInvocationBuildParameters, completion: @escaping (Result<PluginInvocationBuildResult, Error>) -> Void) {\n        DispatchQueue.sharedConcurrent.async { completion(Result.failure(StringError(\"unimplemented\"))) }\n    }\n    func pluginRequestedTestOperation(subset: PluginInvocationTestSubset, parameters: PluginInvocationTestParameters, completion: @escaping (Result<PluginInvocationTestResult, Error>) -> Void) {\n        DispatchQueue.sharedConcurrent.async { completion(Result.failure(StringError(\"unimplemented\"))) }\n    }\n    func pluginRequestedSymbolGraph(forTarget name: String, options: PluginInvocationSymbolGraphOptions, completion: @escaping (Result<PluginInvocationSymbolGraphResult, Error>) -> Void) {\n        DispatchQueue.sharedConcurrent.async { completion(Result.failure(StringError(\"unimplemented\"))) }\n    }\n}\n\nfileprivate extension PluginInvocationBuildSubset {\n    init(_ subset: PluginToHostMessage.BuildSubset) {\n        switch subset {\n        case .all(let includingTests):\n            self = .all(includingTests: includingTests)\n        case .product(let name):\n            self = .product(name)\n        case .target(let name):\n            self = .target(name)\n        }\n    }\n}\n\nfileprivate extension PluginInvocationBuildParameters {\n    init(_ parameters: PluginToHostMessage.BuildParameters) {\n        self.configuration = .init(parameters.configuration)\n        self.logging = .init(parameters.logging)\n        self.echoLogs = parameters.echoLogs\n        self.otherCFlags = parameters.otherCFlags\n        self.otherCxxFlags = parameters.otherCxxFlags\n        self.otherSwiftcFlags = parameters.otherSwiftcFlags\n        self.otherLinkerFlags = parameters.otherLinkerFlags\n    }\n}\n\nfileprivate extension PluginInvocationBuildParameters.Configuration {\n    init(_ configuration: PluginToHostMessage.BuildParameters.Configuration) {\n        switch configuration {\n        case .debug:\n            self = .debug\n        case .release:\n            self = .release\n        case .inherit:\n            self = .inherit\n        }\n    }\n}\n\nfileprivate extension PluginInvocationBuildParameters.LogVerbosity {\n    init(_ verbosity: PluginToHostMessage.BuildParameters.LogVerbosity) {\n        switch verbosity {\n        case .concise:\n            self = .concise\n        case .verbose:\n            self = .verbose\n        case .debug:\n            self = .debug\n        }\n    }\n}\n\nfileprivate extension HostToPluginMessage.BuildResult {\n    init(_ result: PluginInvocationBuildResult) {\n        self.succeeded = result.succeeded\n        self.logText = result.logText\n        self.builtArtifacts = result.builtArtifacts.map { .init($0) }\n    }\n}\n\nfileprivate extension HostToPluginMessage.BuildResult.BuiltArtifact {\n    init(_ artifact: PluginInvocationBuildResult.BuiltArtifact) {\n        self.path = .init(fileURLWithPath: artifact.path)\n        self.kind = .init(artifact.kind)\n    }\n}\n\nfileprivate extension HostToPluginMessage.BuildResult.BuiltArtifact.Kind {\n    init(_ kind: PluginInvocationBuildResult.BuiltArtifact.Kind) {\n        switch kind {\n        case .executable:\n            self = .executable\n        case .dynamicLibrary:\n            self = .dynamicLibrary\n        case .staticLibrary:\n            self = .staticLibrary\n        }\n    }\n}\n\nfileprivate extension PluginInvocationTestSubset {\n    init(_ subset: PluginToHostMessage.TestSubset) {\n        switch subset {\n        case .all:\n            self = .all\n        case .filtered(let regexes):\n            self = .filtered(regexes)\n        }\n    }\n}\n\nfileprivate extension PluginInvocationTestParameters {\n    init(_ parameters: PluginToHostMessage.TestParameters) {\n        self.enableCodeCoverage = parameters.enableCodeCoverage\n    }\n}\n\nfileprivate extension HostToPluginMessage.TestResult {\n    init(_ result: PluginInvocationTestResult) {\n        self.succeeded = result.succeeded\n        self.testTargets = result.testTargets.map{ .init($0) }\n        self.codeCoverageDataFile = result.codeCoverageDataFile.map{ .init($0) }\n    }\n}\n\nfileprivate extension HostToPluginMessage.TestResult.TestTarget {\n    init(_ testTarget: PluginInvocationTestResult.TestTarget) {\n        self.name = testTarget.name\n        self.testCases = testTarget.testCases.map{ .init($0) }\n    }\n}\n\nfileprivate extension HostToPluginMessage.TestResult.TestTarget.TestCase {\n    init(_ testCase: PluginInvocationTestResult.TestTarget.TestCase) {\n        self.name = testCase.name\n        self.tests = testCase.tests.map{ .init($0) }\n    }\n}\n\nfileprivate extension HostToPluginMessage.TestResult.TestTarget.TestCase.Test {\n    init(_ test: PluginInvocationTestResult.TestTarget.TestCase.Test) {\n        self.name = test.name\n        self.result = .init(test.result)\n        self.duration = test.duration\n    }\n}\n\nfileprivate extension HostToPluginMessage.TestResult.TestTarget.TestCase.Test.Result {\n    init(_ result: PluginInvocationTestResult.TestTarget.TestCase.Test.Result) {\n        switch result {\n        case .succeeded:\n            self = .succeeded\n        case .skipped:\n            self = .skipped\n        case .failed:\n            self = .failed\n        }\n    }\n}\n\nfileprivate extension PluginInvocationSymbolGraphOptions {\n    init(_ options: PluginToHostMessage.SymbolGraphOptions) {\n        self.minimumAccessLevel = .init(options.minimumAccessLevel)\n        self.includeInheritedDocs = options.includeInheritedDocs ?? true\n        self.includeSynthesized = options.includeSynthesized\n        self.includeSPI = options.includeSPI\n        self.emitExtensionBlocks = options.emitExtensionBlocks\n    }\n}\n\nfileprivate extension PluginInvocationSymbolGraphOptions.AccessLevel {\n    init(_ accessLevel: PluginToHostMessage.SymbolGraphOptions.AccessLevel) {\n        switch accessLevel {\n        case .private:\n            self = .private\n        case .fileprivate:\n            self = .fileprivate\n        case .internal:\n            self = .internal\n        case .package:\n            self = .package\n        case .public:\n            self = .public\n        case .open:\n            self = .open\n        }\n    }\n}\n\nfileprivate extension HostToPluginMessage.SymbolGraphResult {\n    init(_ result: PluginInvocationSymbolGraphResult) {\n        self.directoryPath = .init(fileURLWithPath: result.directoryPath)\n    }\n}\n\nextension ObservabilityMetadata {\n    public var fileLocation: FileLocation? {\n        get {\n            self[FileLocationKey.self]\n        }\n        set {\n            self[FileLocationKey.self] = newValue\n        }\n    }\n\n    private enum FileLocationKey: Key {\n        typealias Value = FileLocation\n    }\n}\n\npublic struct FileLocation: Equatable, CustomStringConvertible, Sendable {\n    public let file: AbsolutePath\n    public let line: Int?\n\n    public init(_ file: AbsolutePath, line: Int?) {\n        self.file = file\n        self.line = line\n    }\n\n    public var description: String {\n        \"\\(self.file)\\(self.line?.description.appending(\" \") ?? \"\")\"\n    }\n}\n\nextension ObservabilityMetadata {\n    /// Provides information about the plugin from which the diagnostics originated.\n    public var pluginName: String? {\n        get {\n            self[PluginNameKey.self]\n        }\n        set {\n            self[PluginNameKey.self] = newValue\n        }\n    }\n\n    enum PluginNameKey: Key {\n        typealias Value = String\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/Plugins/PluginScriptRunner.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Foundation\nimport PackageModel\nimport PackageLoading\nimport PackageGraph\nimport TSCBasic\nimport TSCUtility\n\n/// Implements the mechanics of running and communicating with a plugin (implemented as a set of Swift source files). In most environments this is done by compiling the code to an executable, invoking it as a sandboxed subprocess, and communicating with it using pipes. Specific implementations are free to implement things differently, however.\npublic protocol PluginScriptRunner {\n    \n    /// Public protocol function that starts compiling the plugin script to an executable. The name is used as the basename for the executable and auxiliary files. The tools version controls the availability of APIs in PackagePlugin, and should be set to the tools version of the package that defines the plugin (not of the target to which it is being applied). This function returns immediately and then calls the completion handler on the callback queue when compilation ends.\n    @available(*, noasync, message: \"Use the async alternative\")\n    func compilePluginScript(\n        sourceFiles: [Basics.AbsolutePath],\n        pluginName: String,\n        toolsVersion: ToolsVersion,\n        workers: UInt32,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        delegate: PluginScriptCompilerDelegate,\n        completion: @escaping (Result<PluginCompilationResult, Error>) -> Void\n    )\n\n    /// Implements the mechanics of running a plugin script implemented as a set of Swift source files, for use\n    /// by the package graph when it is evaluating package plugins.\n    ///\n    /// The `sources` refer to the Swift source files and are accessible in the provided `fileSystem`. The input is\n    /// a PluginScriptRunnerInput structure.\n    ///\n    /// The text output callback handler will receive free-form output from the script as it's running. Structured\n    /// diagnostics emitted by the plugin will be added to the observability scope.\n    ///\n    /// Every concrete implementation should cache any intermediates as necessary to avoid redundant work.\n    func runPluginScript(\n        sourceFiles: [Basics.AbsolutePath],\n        pluginName: String,\n        initialMessage: Data,\n        toolsVersion: ToolsVersion,\n        workingDirectory: Basics.AbsolutePath,\n        writableDirectories: [Basics.AbsolutePath],\n        readOnlyDirectories: [Basics.AbsolutePath],\n        allowNetworkConnections: [SandboxNetworkPermission],\n        workers: UInt32,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        delegate: PluginScriptCompilerDelegate & PluginScriptRunnerDelegate,\n        completion: @escaping (Result<Int32, Error>) -> Void\n    )\n\n    /// Returns the Triple that represents the host for which plugin script tools should be built, or for which binary\n    /// tools should be selected.\n    var hostTriple: Basics.Triple { get throws }\n}\n\npublic extension PluginScriptRunner {\n    func compilePluginScript(\n        sourceFiles: [Basics.AbsolutePath],\n        pluginName: String,\n        toolsVersion: ToolsVersion,\n        workers: UInt32,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        delegate: PluginScriptCompilerDelegate\n    ) async throws -> PluginCompilationResult {\n        try await withCheckedThrowingContinuation { continuation in\n            self.compilePluginScript(\n                sourceFiles: sourceFiles,\n                pluginName: pluginName,\n                toolsVersion: toolsVersion,\n                workers: workers,\n                observabilityScope: observabilityScope,\n                callbackQueue: callbackQueue,\n                delegate: delegate,\n                completion: {\n                  continuation.resume(with: $0)\n                }\n            )\n        }\n    }\n}\n\n/// Protocol by which `PluginScriptRunner` communicates back to the caller as it compiles plugins.\npublic protocol PluginScriptCompilerDelegate {\n    /// Called immediately before compiling a plugin. Will not be called if the plugin didn't have to be compiled. This call is always followed by a `didCompilePlugin()` but is mutually exclusive with a `skippedCompilingPlugin()` call.\n    func willCompilePlugin(commandLine: [String], environment: [String: String])\n\n    /// Called immediately after compiling a plugin (regardless of whether it succeeded or failed). Will not be called if the plugin didn't have to be compiled. This call is always follows a `willCompilePlugin()` but is mutually exclusive with a `skippedCompilingPlugin()` call.\n    func didCompilePlugin(result: PluginCompilationResult)\n    \n    /// Called if a plugin didn't need to be compiled because previous compilation results were still valid. In this case neither `willCompilePlugin()` nor `didCompilePlugin()` will be called.\n    func skippedCompilingPlugin(cachedResult: PluginCompilationResult)\n}\n\n/// Protocol by which `PluginScriptRunner` communicates back to the caller as it runs plugins.\npublic protocol PluginScriptRunnerDelegate {\n    /// Called for each piece of textual output data emitted by the plugin. Note that there is no guarantee that the data begins and ends on a UTF-8 byte sequence boundary (much less on a line boundary) so the delegate should buffer partial data as appropriate.\n    func handleOutput(data: Data)\n    \n    /// Called for each length-delimited message received from the plugin. The `responder` is closure that can be used to send one or more messages in reply.\n    func handleMessage(data: Data, responder: @escaping (Data) -> Void) throws\n}\n\n/// The result of compiling a plugin. The executable path will only be present if the compilation succeeds, while the other properties are present in all cases.\npublic struct PluginCompilationResult: Equatable {\n    /// Whether compilation succeeded.\n    public var succeeded: Bool\n    \n    /// Complete compiler command line.\n    public var commandLine: [String]\n    \n    /// Path of the compiled executable.\n    public var executableFile: Basics.AbsolutePath\n\n    /// Path of the libClang diagnostics file emitted by the compiler.\n    public var diagnosticsFile: Basics.AbsolutePath\n    \n    /// Any output emitted by the compiler (stdout and stderr combined).\n    public var rawCompilerOutput: String\n    \n    /// Whether the compilation result came from the cache (false means that the compiler did run).\n    public var cached: Bool\n    \n    public init(\n        succeeded: Bool,\n        commandLine: [String],\n        executableFile: Basics.AbsolutePath,\n        diagnosticsFile: Basics.AbsolutePath,\n        compilerOutput rawCompilerOutput: String,\n        cached: Bool\n    ) {\n        self.succeeded = succeeded\n        self.commandLine = commandLine\n        self.executableFile = executableFile\n        self.diagnosticsFile = diagnosticsFile\n        self.rawCompilerOutput = rawCompilerOutput\n        self.cached = cached\n    }\n}\n\nextension PluginCompilationResult {\n    public var compilerOutput: String {\n        let output = self.rawCompilerOutput.spm_chomp()\n        return output + (output.isEmpty || output.hasSuffix(\"\\n\") ? \"\" : \"\\n\")\n    }\n}\n\nextension PluginCompilationResult: CustomDebugStringConvertible {\n    public var debugDescription: String {\n        return \"\"\"\n            <PluginCompilationResult(\n                succeeded: \\(succeeded),\n                commandLine: \\(commandLine.map{ $0.spm_shellEscaped() }.joined(separator: \" \")),\n                executable: \\(executableFile.prettyPath())\n                diagnostics: \\(diagnosticsFile.prettyPath())\n                compilerOutput: \\(compilerOutput.spm_shellEscaped())\n            )>\n            \"\"\"\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/ResolvedPackage+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageModel\nimport TSCUtility\n\nimport struct PackageGraph.ResolvedPackage\nimport struct PackageGraph.ResolvedModule\n\nextension ResolvedPackage {\n    @_spi(SwiftPMInternal)\n    public func packageNameArgument(target: ResolvedModule, isPackageNameSupported: Bool) -> [String] {\n        if self.manifest.usePackageNameFlag, target.packageAccess {\n            [\"-package-name\", self.identity.description.spm_mangledToC99ExtendedIdentifier()]\n        } else {\n            []\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/Triple+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.Triple\n\nextension Triple {\n    public var platformBuildPathComponent: String {\n        if isDarwin() {\n            return self.tripleString(forPlatformVersion: \"\")\n        } else if isFreeBSD() {\n            return \"\\(self.archName)-\\(self.vendorName)-\\(self.osNameUnversioned)\"\n        }\n\n        return self.tripleString\n    }\n}\n\nextension Triple {\n    public func platformBuildPathComponent(buildSystem: BuildSystemProvider.Kind) -> String {\n        switch buildSystem {\n        case .xcode:\n            // Use \"apple\" as the subdirectory because in theory Xcode build system\n            // can be used to build for any Apple platform and it has its own\n            // conventions for build subpaths based on platforms.\n            return \"apple\"\n        case .swiftbuild:\n            return \"out\"\n        case .native:\n            return self.platformBuildPathComponent\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/WarningControlFlags.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2026 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npackage enum WarningControlFlags {\n    package static func filterSwiftWarningControlFlags(_ args: [String]) -> [String] {\n        var filtered: [String] = []\n        var skipNextArg = false\n\n        for arg in args {\n            if skipNextArg {\n                skipNextArg = false\n                continue\n            }\n\n            switch arg {\n            case \"-warnings-as-errors\", \"-no-warnings-as-errors\":\n                break\n            case \"-Wwarning\", \"-Werror\":\n                skipNextArg = true\n            default:\n                filtered.append(arg)\n            }\n        }\n        return filtered\n    }\n\n    package static func filterClangWarningControlFlags(_ args: [String]) -> [String] {\n        args.filter { arg in\n            // Filter out warning control flags:\n            // -Wxxxx\n            // -Wno-xxxx\n            // -Werror\n            // -Werror=xxxx\n            // -Wno-error\n            // -Wno-error=xxxx\n            arg.count <= 2 || !arg.starts(with: \"-W\")\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/XCFrameworkMetadata.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport protocol Basics.FileSystem\nimport struct Basics.Triple\nimport Foundation\nimport PackageModel\n\nimport struct TSCBasic.StringError\n\npublic struct XCFrameworkMetadata: Equatable {\n    public struct Library: Equatable {\n        public let libraryIdentifier: String\n        public let libraryPath: String\n        public let headersPath: String?\n        public let platform: String\n        public let architectures: [String]\n        public let variant: String?\n\n        public init(\n            libraryIdentifier: String,\n            libraryPath: String,\n            headersPath: String?,\n            platform: String,\n            architectures: [String],\n            variant: String?\n        ) {\n            self.libraryIdentifier = libraryIdentifier\n            self.libraryPath = libraryPath\n            self.headersPath = headersPath\n            self.platform = platform\n            self.architectures = architectures\n            self.variant = variant\n        }\n    }\n\n    public let libraries: [Library]\n\n    public init(libraries: [Library]) {\n        self.libraries = libraries\n    }\n}\n\nextension XCFrameworkMetadata {\n    public static func parse(fileSystem: FileSystem, rootPath: AbsolutePath) throws -> XCFrameworkMetadata {\n        let path = rootPath.appending(\"Info.plist\")\n        guard fileSystem.exists(path) else {\n            throw StringError(\"XCFramework Info.plist not found at '\\(rootPath)'\")\n        }\n\n        do {\n            let data: Data = try fileSystem.readFileContents(path)\n            let decoder = PropertyListDecoder()\n            return try decoder.decode(XCFrameworkMetadata.self, from: data)\n        } catch {\n            throw StringError(\"failed parsing XCFramework Info.plist at '\\(path)': \\(error.interpolationDescription)\")\n        }\n    }\n}\n\nextension XCFrameworkMetadata: Decodable {\n    enum CodingKeys: String, CodingKey {\n        case libraries = \"AvailableLibraries\"\n    }\n}\n\nextension XCFrameworkMetadata.Library: Decodable {\n    enum CodingKeys: String, CodingKey {\n        case libraryIdentifier = \"LibraryIdentifier\"\n        case libraryPath = \"LibraryPath\"\n        case headersPath = \"HeadersPath\"\n        case platform = \"SupportedPlatform\"\n        case architectures = \"SupportedArchitectures\"\n        case variant = \"SupportedPlatformVariant\"\n    }\n}\n"
  },
  {
    "path": "Sources/SPMBuildCore/XcodeProjectRepresentation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n/// Represents a simplifed view of an Xcode project to a plugin.\npublic struct XcodeProjectRepresentation: Equatable, Hashable {\n    public var displayName: String\n    public var directoryPath: AbsolutePath\n    public var filePaths: [AbsolutePath]\n    public var targets: [Target]\n\n    public init(displayName: String, directoryPath: AbsolutePath, filePaths: [AbsolutePath], targets: [Target]) {\n        self.displayName = displayName\n        self.directoryPath = directoryPath\n        self.filePaths = filePaths\n        self.targets = targets\n    }\n\n    public struct Target: Equatable, Hashable {\n        public var displayName: String\n        public var product: Product?\n        public var inputFiles: [InputFile]\n\n        public init(displayName: String, product: Product?, inputFiles: [InputFile]) {\n            self.displayName = displayName\n            self.product = product\n            self.inputFiles = inputFiles\n        }\n\n        public struct Product: Equatable, Hashable {\n            public var name: String\n            public var kind: Kind\n\n            public init(name: String, kind: Kind) {\n                self.name = name\n                self.kind = kind\n            }\n\n            /// Represents a kind of product produced by an Xcode target.\n            public enum Kind: Equatable, Hashable {\n                case application\n                case executable\n                case framework\n                case library\n                case other(String)\n            }\n        }\n\n        public struct InputFile: Equatable, Hashable {\n            public var path: AbsolutePath\n            public var role: Role\n\n            public init(path: AbsolutePath, role: Role) {\n                self.path = path\n                self.role = role\n            }\n\n            public enum Role: Equatable, Hashable {\n                case source\n                case header\n                case resource\n                case unknown\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SPMLLBuild/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SPMLLBuild STATIC\n  llbuild.swift)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(SPMLLBuild PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\ntarget_link_libraries(SPMLLBuild PUBLIC\n  Basics\n  TSCBasic\n  TSCUtility\n  llbuildSwift)\n"
  },
  {
    "path": "Sources/SPMLLBuild/llbuild.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// We either export the llbuildSwift shared library or the llbuild framework.\n#if canImport(llbuildSwift)\n@_exported import llbuildSwift\n@_exported import llbuild\n#else\n@_exported import llbuild\n#endif\n\nimport Basics\nimport Foundation\n\n/// An llbuild value.\npublic protocol LLBuildValue: Codable {\n}\n\n/// An llbuild key.\npublic protocol LLBuildKey: Codable {\n    /// The value that this key computes.\n    associatedtype BuildValue: LLBuildValue\n\n    /// The rule that this key operates on.\n    associatedtype BuildRule: LLBuildRule\n}\n\npublic protocol LLBuildEngineDelegate {\n    func lookupRule(rule: String, key: Key) -> Rule\n}\n\npublic final class LLBuildEngine {\n\n    enum Error: Swift.Error, CustomStringConvertible {\n        case failed(errors: [String])\n\n        var description: String {\n            switch self {\n            case .failed(let errors):\n                return errors.joined(separator: \"\\n\")\n            }\n        }\n    }\n\n    private final class Delegate: BuildEngineDelegate {\n        let delegate: LLBuildEngineDelegate\n        var errors: [String] = []\n\n        init(_ delegate: LLBuildEngineDelegate) {\n            self.delegate = delegate\n        }\n\n        func lookupRule(_ key: Key) -> Rule {\n            let ruleKey = try! RuleKey(key)\n            return delegate.lookupRule(\n                rule: ruleKey.rule, key: Key(ruleKey.data))\n        }\n\n        func error(_ message: String) {\n            errors.append(message)\n        }\n    }\n\n    private let engine: BuildEngine\n    private let delegate: Delegate\n\n    public init(delegate: LLBuildEngineDelegate) {\n        self.delegate = Delegate(delegate)\n        engine = BuildEngine(delegate: self.delegate)\n    }\n\n    deinit {\n        engine.close()\n    }\n\n    public func build<T: LLBuildKey>(key: T) throws -> T.BuildValue {\n        // Clear out any errors from the previous build.\n        delegate.errors.removeAll()\n\n        let encodedKey = try RuleKey(\n            rule: T.BuildRule.ruleName, data: try key.toKey().data).toKey()\n        let value = engine.build(key: encodedKey)\n\n        // Throw if the engine encountered any fatal error during the build.\n        if !delegate.errors.isEmpty || value.data.isEmpty {\n            throw Error.failed(errors: delegate.errors)\n        }\n\n        return try T.BuildValue(value)\n    }\n\n    public func attachDB(path: String, schemaVersion: Int = 2) throws {\n        try engine.attachDB(path: path, schemaVersion: schemaVersion)\n    }\n\n    public func close() {\n        engine.close()\n    }\n}\n\n// FIXME: Rename to something else.\npublic class LLTaskBuildEngine {\n\n    let engine: TaskBuildEngine\n\n    init(_ engine: TaskBuildEngine) {\n        self.engine = engine\n    }\n\n    public func taskNeedsInput<T: LLBuildKey>(_ key: T, inputID: Int) throws {\n        let encodedKey = try RuleKey(\n            rule: T.BuildRule.ruleName, data: try key.toKey().data).toKey()\n        engine.taskNeedsInput(encodedKey, inputID: inputID)\n    }\n\n    public func taskIsComplete<T: LLBuildValue>(_ result: T) throws {\n        engine.taskIsComplete(try result.toValue(), forceChange: false)\n    }\n}\n\n/// An individual build rule.\nopen class LLBuildRule: Rule, Task {\n\n    /// The name of the rule.\n    ///\n    /// This name will be available in the delegate's lookupRule(rule:key:).\n    open class var ruleName: String {\n        fatalError(\"subclass responsibility\")\n    }\n\n    public init() {\n    }\n\n    public func createTask() -> Task {\n        return self\n    }\n\n    public func start(_ engine: TaskBuildEngine) {\n        self.start(LLTaskBuildEngine(engine))\n    }\n\n    public func provideValue(_ engine: TaskBuildEngine, inputID: Int, value: Value) {\n        self.provideValue(LLTaskBuildEngine(engine), inputID: inputID, value: value)\n    }\n\n    public func inputsAvailable(_ engine: TaskBuildEngine) {\n        self.inputsAvailable(LLTaskBuildEngine(engine))\n    }\n\n    // MARK:-\n\n    open func isResultValid(_ priorValue: Value) -> Bool {\n        return true\n    }\n\n    open func start(_ engine: LLTaskBuildEngine) {\n    }\n\n    open func provideValue(_ engine: LLTaskBuildEngine, inputID: Int, value: Value) {\n    }\n\n    open func inputsAvailable(_ engine: LLTaskBuildEngine) {\n    }\n}\n\n// MARK:- Helpers\n\nprivate struct RuleKey: Codable {\n\n    let rule: String\n    let data: [UInt8]\n\n    init(rule: String, data: [UInt8]) {\n        self.rule = rule\n        self.data = data\n    }\n\n    init(_ key: Key) throws {\n        try self.init(key.data)\n    }\n\n    init(_ data: [UInt8]) throws {\n        self = try fromBytes(data)\n    }\n\n    func toKey() throws -> Key {\n        return try Key(toBytes(self))\n    }\n}\n\npublic extension LLBuildKey {\n    init(_ key: Key) throws {\n        try self.init(key.data)\n    }\n\n    init(_ data: [UInt8]) throws {\n        do {\n            self = try fromBytes(data)\n        } catch {\n            let stringValue: String\n            if let str = String(bytes: data, encoding: .utf8) {\n                stringValue = str\n            } else {\n                stringValue = String(describing: data)\n            }\n            throw InternalError(\"LLBuildKey: ###\\(error.interpolationDescription)### ----- ###\\(stringValue)###\")\n        }\n    }\n\n    func toKey() throws -> Key {\n        return try Key(toBytes(self))\n    }\n}\n\npublic extension LLBuildValue {\n    init(_ value: Value) throws {\n        self = try fromBytes(value.data)\n    }\n\n    func toValue() throws -> Value {\n        return try Value(toBytes(self))\n    }\n}\n\nprivate func fromBytes<T: Decodable>(_ bytes: [UInt8]) throws -> T {\n    var bytes = bytes\n    let data = Data(bytes: &bytes, count: bytes.count)\n    let decoder = JSONDecoder.makeWithDefaults()\n    return try decoder.decode(T.self, from: data)\n}\n\nprivate func toBytes<T: Encodable>(_ value: T) throws -> [UInt8] {\n    let encoder = JSONEncoder.makeWithDefaults()\n    let encoded = try encoder.encode(value)\n    return [UInt8](encoded)\n}\n"
  },
  {
    "path": "Sources/SPMSQLite3/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SPMSQLite3 INTERFACE)\ntarget_include_directories(SPMSQLite3 INTERFACE\n  ${CMAKE_CURRENT_SOURCE_DIR})\ntarget_link_libraries(SPMSQLite3 INTERFACE\n  SQLite::SQLite3)\nif(CMAKE_SYSTEM_NAME STREQUAL OpenBSD)\n  target_link_options(SPMSQLite3 INTERFACE \"-L/usr/local/lib\")\nendif()\n"
  },
  {
    "path": "Sources/SPMSQLite3/module.modulemap",
    "content": "module SPMSQLite3 [system] {\n  header \"sqlite.h\"\n  link \"sqlite3\"\n  export *\n}\n"
  },
  {
    "path": "Sources/SPMSQLite3/sqlite.h",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#pragma once\n#include <sqlite3.h>\n"
  },
  {
    "path": "Sources/SourceControl/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SourceControl\n  GitRepository.swift\n  Repository.swift\n  RepositoryManager.swift)\ntarget_link_libraries(SourceControl PUBLIC\n  Basics\n  PackageModel\n  TSCBasic\n  TSCUtility\n  Basics)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(SourceControl PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS SourceControl\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS SourceControl)\n"
  },
  {
    "path": "Sources/SourceControl/GitRepository.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(ProcessEnvironmentBlockShim)\nimport Basics\nimport Dispatch\nimport class Foundation.NSLock\n\nimport struct PackageModel.CanonicalPackageURL\n\nimport struct TSCBasic.ByteString\nimport protocol TSCBasic.DiagnosticLocation\nimport struct TSCBasic.FileInfo\nimport enum TSCBasic.FileMode\nimport struct TSCBasic.FileSystemError\nimport class Basics.AsyncProcess\nimport struct Basics.AsyncProcessResult\nimport struct TSCBasic.RegEx\n\nimport protocol TSCUtility.DiagnosticLocationProviding\nimport enum TSCUtility.Git\n\n// MARK: - GitShellHelper\n\n/// Helper for shelling out to `git`\nprivate struct GitShellHelper {\n    private let cancellator: Cancellator\n\n    init(cancellator: Cancellator) {\n        self.cancellator = cancellator\n    }\n\n    /// Private function to invoke the Git tool with its default environment and given set of arguments.  The specified\n    /// failure message is used only in case of error.  This function waits for the invocation to finish and returns the\n    /// output as a string.\n    func run(\n        _ args: [String],\n        environment: Environment = .init(Git.environmentBlock),\n        outputRedirection: AsyncProcess.OutputRedirection = .collect\n    ) throws -> String {\n        let process = AsyncProcess(\n            arguments: [Git.tool] + args,\n            environment: environment,\n            outputRedirection: outputRedirection\n        )\n        let result: AsyncProcessResult\n        do {\n            guard let terminationKey = self.cancellator.register(process) else {\n                throw CancellationError() // terminating\n            }\n            defer { self.cancellator.deregister(terminationKey) }\n            try process.launch()\n            result = try process.waitUntilExit()\n            guard result.exitStatus == .terminated(code: 0) else {\n                throw GitShellError(result: result)\n            }\n            return try result.utf8Output().spm_chomp()\n        } catch let error as GitShellError {\n            throw error\n        } catch {\n            // Handle a failure to even launch the Git tool by synthesizing a result that we can wrap an error around.\n            let result = AsyncProcessResult(\n                arguments: process.arguments,\n                environment: process.environment,\n                exitStatus: .terminated(code: -1),\n                output: .failure(error),\n                stderrOutput: .failure(error)\n            )\n            throw GitShellError(result: result)\n        }\n    }\n}\n\n// MARK: - GitRepositoryProvider\n\n/// A `git` repository provider.\npublic struct GitRepositoryProvider: RepositoryProvider, Cancellable {\n    private let cancellator: Cancellator\n    private let git: GitShellHelper\n\n    private let repositoryCache = ThreadSafeKeyValueStore<String, Repository>()\n\n    public init() {\n        // helper to cancel outstanding processes\n        self.cancellator = Cancellator(observabilityScope: .none)\n        // helper to abstract shelling out to git\n        self.git = GitShellHelper(cancellator: cancellator)\n    }\n\n    @discardableResult\n    private func callGit(\n        _ args: [String],\n        environment: Environment = .init(Git.environmentBlock),\n        repository: RepositorySpecifier,\n        failureMessage: String = \"\",\n        progress: FetchProgress.Handler? = nil\n    ) throws -> String {\n        if let progress {\n            var stdoutBytes: [UInt8] = [], stderrBytes: [UInt8] = []\n            do {\n                // Capture stdout and stderr from the Git subprocess invocation, but also pass along stderr to the\n                // handler. We count on it being line-buffered.\n                let outputHandler = AsyncProcess.OutputRedirection.stream(stdout: { stdoutBytes += $0 }, stderr: {\n                    stderrBytes += $0\n                    gitFetchStatusFilter($0, progress: progress)\n                })\n                return try self.git.run(\n                    args + [\"--progress\"],\n                    environment: environment,\n                    outputRedirection: outputHandler\n                )\n            } catch let error as GitShellError {\n                let result = AsyncProcessResult(\n                    arguments: error.result.arguments,\n                    environment: error.result.environment,\n                    exitStatus: error.result.exitStatus,\n                    output: .success(stdoutBytes),\n                    stderrOutput: .success(stderrBytes)\n                )\n                throw GitCloneError(repository: repository, message: failureMessage, result: result)\n            }\n        } else {\n            do {\n                return try self.git.run(args, environment: environment)\n            } catch let error as GitShellError {\n                throw GitCloneError(repository: repository, message: failureMessage, result: error.result)\n            }\n        }\n    }\n\n    @discardableResult\n    private func callGit(\n        _ args: String...,\n        environment: Environment = .init(Git.environmentBlock),\n        repository: RepositorySpecifier,\n        failureMessage: String = \"\",\n        progress: FetchProgress.Handler? = nil\n    ) throws -> String {\n        try callGit(\n            args.map { $0 },\n            environment: environment,\n            repository: repository,\n            failureMessage: failureMessage,\n            progress: progress\n        )\n    }\n\n    private func clone(\n        _ repository: RepositorySpecifier,\n        _ origin: String,\n        _ destination: String,\n        _ options: [String],\n        progress: FetchProgress.Handler? = nil\n    ) throws {\n        let invocation: [String] = [\n            \"clone\",\n            // Enable symbolic links for Windows support.\n            \"-c\", \"core.symlinks=true\",\n            // Disable fsmonitor to avoid spawning a monitor process.\n            \"-c\", \"core.fsmonitor=false\",\n            // Enable long path support on Windows as otherwise we are limited\n            // to 261 characters in the complete path.\n            \"-c\", \"core.longpaths=true\",\n        ] + options + [origin, destination]\n\n        try self.callGit(\n            invocation,\n            repository: repository,\n            failureMessage: \"Failed to clone repository \\(repository.location)\",\n            progress: progress\n        )\n    }\n\n    public func fetch(\n        repository: RepositorySpecifier,\n        to path: Basics.AbsolutePath,\n        progressHandler: FetchProgress.Handler? = nil\n    ) async throws {\n        // Perform a bare clone.\n        //\n        // NOTE: We intentionally do not create a shallow clone here; the\n        // expected cost of iterative updates on a full clone is less than on a\n        // shallow clone.\n        guard !localFileSystem.exists(path) else {\n            throw InternalError(\"\\(path) already exists\")\n        }\n\n        try self.clone(\n            repository,\n            repository.location.gitURL,\n            path.pathString,\n            [\"--mirror\"],\n            progress: progressHandler\n        )\n    }\n\n    public func isValidDirectory(_ directory: Basics.AbsolutePath) throws -> Bool {\n        let result = try self.git.run([\"-C\", directory.pathString, \"rev-parse\", \"--git-dir\"])\n        return result == \".git\" || result == \".\" || result == directory.pathString\n    }\n\n    public func isValidDirectory(_ directory: Basics.AbsolutePath, for repository: RepositorySpecifier) throws -> Bool {\n        let remoteURL = try self.git.run([\"-C\", directory.pathString, \"config\", \"--get\", \"remote.origin.url\"])\n        return CanonicalPackageURL(remoteURL) == CanonicalPackageURL(repository.url)\n    }\n\n    public func copy(from sourcePath: Basics.AbsolutePath, to destinationPath: Basics.AbsolutePath) throws {\n        try localFileSystem.copy(from: sourcePath, to: destinationPath)\n    }\n\n    public func open(repository: RepositorySpecifier, at path: Basics.AbsolutePath) -> Repository {\n        let key = \"\\(repository)@\\(path)\"\n        return self.repositoryCache.memoize(key) {\n            GitRepository(git: self.git, path: path, isWorkingRepo: false)\n        }\n    }\n\n    public func createWorkingCopy(\n        repository: RepositorySpecifier,\n        sourcePath: Basics.AbsolutePath,\n        at destinationPath: Basics.AbsolutePath,\n        editable: Bool\n    ) async throws -> WorkingCheckout {\n        if editable {\n            // For editable clones, i.e. the user is expected to directly work on them, first we create\n            // a clone from our cache of repositories and then we replace the remote to the one originally\n            // present in the bare repository.\n\n            try self.clone(\n                repository,\n                sourcePath.pathString,\n                destinationPath.pathString,\n                [\"--no-checkout\"]\n            )\n\n            // The default name of the remote.\n            let origin = \"origin\"\n            // In destination repo remove the remote which will be pointing to the source repo.\n            let clone = GitRepository(git: self.git, path: destinationPath)\n            // Set the original remote to the new clone.\n            try clone.setURL(remote: origin, url: repository.location.gitURL)\n            // FIXME: This is unfortunate that we have to fetch to update remote's data.\n            try clone.fetch()\n        } else {\n            // Clone using a shared object store with the canonical copy.\n            //\n            // We currently expect using shared storage here to be safe because we\n            // only ever expect to attempt to use the working copy to materialize a\n            // revision we selected in response to dependency resolution, and if we\n            // re-resolve such that the objects in this repository changed, we would\n            // only ever expect to get back a revision that remains present in the\n            // object storage.\n\n            try self.clone(\n                repository,\n                sourcePath.pathString,\n                destinationPath.pathString,\n                [\"--shared\", \"--no-checkout\"]\n            )\n        }\n        return try self.openWorkingCopy(at: destinationPath)\n    }\n\n    public func workingCopyExists(at path: Basics.AbsolutePath) throws -> Bool {\n        guard localFileSystem.exists(path) else {\n            throw InternalError(\"\\(path) does not exist\")\n        }\n\n        let repo = GitRepository(git: self.git, path: path)\n        return try repo.checkoutExists()\n    }\n\n    public func openWorkingCopy(at path: Basics.AbsolutePath) throws -> WorkingCheckout {\n        GitRepository(git: self.git, path: path)\n    }\n\n    public func cancel(deadline: DispatchTime) throws {\n        try self.cancellator.cancel(deadline: deadline)\n    }\n}\n\n// MARK: - GitRepository\n\n// FIXME: Currently, this class is serving two goals, it is the Repository\n// interface used by `RepositoryProvider`, but is also a class which can be\n// instantiated directly against non-RepositoryProvider controlled\n// repositories. This may prove inconvenient if what is currently `Repository`\n// becomes inconvenient or incompatible with the ideal interface for this\n// class. It is possible we should rename `Repository` to something more\n// abstract, and change the provider to just return an adaptor around this\n// class.\n//\n/// A basic Git repository in the local file system (almost always a clone of a remote).  This class is thread safe.\npublic final class GitRepository: Repository, WorkingCheckout {\n    /// A hash object.\n    public struct Hash: Hashable {\n        // FIXME: We should optimize this representation.\n        let bytes: ByteString\n\n        /// Create a hash from the given hexadecimal representation.\n        ///\n        /// - Returns; The hash, or nil if the identifier is invalid.\n        public init?(_ identifier: String) {\n            self.init(asciiBytes: ByteString(encodingAsUTF8: identifier).contents)\n        }\n\n        /// Create a hash from the given ASCII bytes.\n        ///\n        /// - Returns; The hash, or nil if the identifier is invalid.\n        init?<C: Collection>(asciiBytes bytes: C) where C.Iterator.Element == UInt8 {\n            if bytes.count != 40 {\n                return nil\n            }\n            for byte in bytes {\n                switch byte {\n                case UInt8(ascii: \"0\") ... UInt8(ascii: \"9\"),\n                     UInt8(ascii: \"a\") ... UInt8(ascii: \"z\"):\n                    continue\n                default:\n                    return nil\n                }\n            }\n            self.bytes = ByteString(bytes)\n        }\n    }\n\n    /// A commit object.\n    public struct Commit: Equatable {\n        /// The object hash.\n        public let hash: Hash\n\n        /// The tree contained in the commit.\n        public let tree: Hash\n    }\n\n    /// A tree object.\n    public struct Tree {\n        public enum Location: Hashable {\n            case hash(Hash)\n            case tag(String)\n        }\n\n        public struct Entry {\n            public enum EntryType {\n                case blob\n                case commit\n                case executableBlob\n                case symlink\n                case tree\n\n                init?(mode: Int) {\n                    // Although the mode is a full UNIX mode mask, there are\n                    // only a limited set of allowed values.\n                    switch mode {\n                    case 0o040000:\n                        self = .tree\n                    case 0o100644:\n                        self = .blob\n                    case 0o100755:\n                        self = .executableBlob\n                    case 0o120000:\n                        self = .symlink\n                    case 0o160000:\n                        self = .commit\n                    default:\n                        return nil\n                    }\n                }\n            }\n\n            /// The object location.\n            public let location: Location\n\n            /// The type of object referenced.\n            public let type: EntryType\n\n            /// The name of the object.\n            public let name: String\n        }\n\n        /// The object location.\n        public let location: Location\n\n        /// The list of contents.\n        public let contents: [Entry]\n    }\n\n    /// The path of the repository in the local file system.\n    public let path: AbsolutePath\n\n    /// Concurrent queue to execute git cli on.\n    private let git: GitShellHelper\n\n    // lock top protect concurrent modifications to the repository\n    private let lock = NSLock()\n\n    /// If this repo is a work tree repo (checkout) as opposed to a bare repo.\n    private let isWorkingRepo: Bool\n\n    /// Dictionary for memoizing results of git calls that are not expected to change.\n    private var cachedHashes = ThreadSafeKeyValueStore<String, Hash>()\n    private var cachedBlobs = ThreadSafeKeyValueStore<Hash, ByteString>()\n    private var cachedTrees = ThreadSafeKeyValueStore<String, Tree>()\n    private var cachedTags = ThreadSafeBox<[String]?>()\n    private var cachedBranches = ThreadSafeBox<[String]?>()\n    private var cachedIsBareRepo = ThreadSafeBox<Bool?>()\n    private var cachedHasSubmodules = ThreadSafeBox<Bool?>()\n\n    public convenience init(path: AbsolutePath, isWorkingRepo: Bool = true, cancellator: Cancellator? = .none) {\n        // used in one-off operations on git repo, as such the terminator is not ver important\n        let cancellator = cancellator ?? Cancellator(observabilityScope: .none)\n        let git = GitShellHelper(cancellator: cancellator)\n        self.init(git: git, path: path, isWorkingRepo: isWorkingRepo)\n    }\n\n    fileprivate init(git: GitShellHelper, path: AbsolutePath, isWorkingRepo: Bool = true) {\n        self.git = git\n        self.path = path\n        self.isWorkingRepo = isWorkingRepo\n        assert({\n            // Ignore if we couldn't run popen for some reason.\n            (try? self.isBare() != isWorkingRepo) ?? true\n        }())\n    }\n\n    /// Private function to invoke the Git tool with its default environment and given set of arguments, specifying the\n    /// path of the repository as the one to operate on.  The specified failure message is used only in case of error.\n    /// This function waits for the invocation to finish and returns the output as a string.\n    @discardableResult\n    private func callGit(\n        _ args: String...,\n        environment: Environment = .init(Git.environmentBlock),\n        failureMessage: String = \"\",\n        progress: FetchProgress.Handler? = nil\n    ) throws -> String {\n        if let progress {\n            var stdoutBytes: [UInt8] = [], stderrBytes: [UInt8] = []\n            do {\n                // Capture stdout and stderr from the Git subprocess invocation, but also pass along stderr to the\n                // handler. We count on it being line-buffered.\n                let outputHandler = AsyncProcess.OutputRedirection.stream(stdout: { stdoutBytes += $0 }, stderr: {\n                    stderrBytes += $0\n                    gitFetchStatusFilter($0, progress: progress)\n                })\n                return try self.git.run(\n                    [\"-C\", self.path.pathString] + args,\n                    environment: environment,\n                    outputRedirection: outputHandler\n                )\n            } catch let error as GitShellError {\n                let result = AsyncProcessResult(\n                    arguments: error.result.arguments,\n                    environment: error.result.environment,\n                    exitStatus: error.result.exitStatus,\n                    output: .success(stdoutBytes),\n                    stderrOutput: .success(stderrBytes))\n                throw GitRepositoryError(path: self.path, message: failureMessage, result: result)\n            }\n        } else {\n            do {\n                return try self.git.run([\"-C\", self.path.pathString] + args, environment: environment)\n            } catch let error as GitShellError {\n                throw GitRepositoryError(path: self.path, message: failureMessage, result: error.result)\n            }\n        }\n    }\n\n    /// Changes URL for the remote.\n    ///\n    /// - parameters:\n    ///   - remote: The name of the remote to operate on. It should already be present.\n    ///   - url: The new url of the remote.\n    public func setURL(remote: String, url: String) throws {\n        // use barrier for write operations\n        try self.lock.withLock {\n            try callGit(\n                \"remote\",\n                \"set-url\",\n                remote,\n                url,\n                failureMessage: \"Couldn’t set the URL of the remote ‘\\(remote)’ to ‘\\(url)’\"\n            )\n        }\n    }\n\n    /// Gets the current list of remotes of the repository.\n    ///\n    /// - Returns: An array of tuple containing name and url of the remote.\n    public func remotes() throws -> [(name: String, url: String)] {\n        try self.lock.withLock {\n            // Get the remote names.\n            let remoteNamesOutput = try callGit(\n                \"remote\",\n                failureMessage: \"Couldn’t get the list of remotes\"\n            )\n            let remoteNames = remoteNamesOutput.split(whereSeparator: { $0.isNewline }).map(String.init)\n            return try remoteNames.map { name in\n                // For each remote get the url.\n                let url = try callGit(\n                    \"config\",\n                    \"--get\",\n                    \"remote.\\(name).url\",\n                    failureMessage: \"Couldn’t get the URL of the remote ‘\\(name)’\"\n                )\n                return (name, url)\n            }\n        }\n    }\n\n    // MARK: Helpers for package search functionality\n\n    public func getDefaultBranch() throws -> String {\n        try callGit(\"rev-parse\", \"--abbrev-ref\", \"HEAD\", failureMessage: \"Couldn’t get the default branch\")\n    }\n\n    public func getBranches() throws -> [String] {\n        try self.cachedBranches.memoize {\n            try self.lock.withLock {\n                let branches = try callGit(\"branch\", \"-l\", failureMessage: \"Couldn’t get the list of branches\")\n                return branches.split(whereSeparator: { $0.isNewline }).map { $0.dropFirst(2) }.map(String.init)\n            }\n        }\n    }\n\n    // MARK: Helpers for SBOM functionality\n    public func getCurrentBranch() throws -> String? {\n        try self.lock.withLock {\n            let branch = try callGit(\n                \"rev-parse\",\n                \"--abbrev-ref\",\n                \"HEAD\",\n                failureMessage: \"Couldn't get the current branch\"\n            )\n            // Return nil if in detached HEAD state\n            return branch == \"HEAD\" ? nil : branch\n        }\n    }\n\n    public func getRemote(for branch: String) throws -> (name: String, url: String)? {\n        try self.lock.withLock {\n            guard let remoteName = try? callGit(\n                \"config\",\n                \"--get\",\n                \"branch.\\(branch).remote\",\n                failureMessage: \"Couldn't get remote for branch '\\(branch)'\"\n            ) else {\n                return nil\n            }\n            \n            let url = try callGit(\n                \"config\",\n                \"--get\",\n                \"remote.\\(remoteName).url\",\n                failureMessage: \"Couldn't get URL for remote '\\(remoteName)'\"\n            )\n            \n            return (name: remoteName, url: url)\n        }\n    }\n\n\n    // MARK: Repository Interface\n\n    /// Returns the tags present in repository.\n    public func getTags() throws -> [String] {\n        // Get the contents using `ls-tree`.\n        try self.cachedTags.memoize {\n            try self.lock.withLock {\n                let tagList = try callGit(\n                    \"tag\",\n                    \"-l\",\n                    failureMessage: \"Couldn’t get the list of tags\"\n                )\n                return tagList.split(whereSeparator: { $0.isNewline }).map(String.init)\n            }\n        }\n    }\n\n    public func resolveRevision(tag: String) throws -> Revision {\n        try Revision(identifier: self.resolveHash(treeish: tag, type: \"commit\").bytes.description)\n    }\n\n    public func resolveRevision(identifier: String) throws -> Revision {\n        try Revision(identifier: self.resolveHash(treeish: identifier, type: \"commit\").bytes.description)\n    }\n\n    public func fetch() throws {\n        try self.fetch(progress: nil)\n    }\n\n    public func fetch(progress: FetchProgress.Handler? = nil) throws {\n        // use barrier for write operations\n        try self.lock.withLock {\n            try callGit(\n                \"remote\",\n                \"-v\",\n                \"update\",\n                \"-p\",\n                failureMessage: \"Couldn’t fetch updates from remote repositories\",\n                progress: progress\n            )\n            self.cachedTags.clear()\n        }\n    }\n\n    public func hasUncommittedChanges() -> Bool {\n        // Only a working repository can have changes.\n        guard self.isWorkingRepo else { return false }\n        return self.lock.withLock {\n            guard let result = try? callGit(\"status\", \"-s\") else {\n                return false\n            }\n            return !result.isEmpty\n        }\n    }\n\n    public func openFileView(revision: Revision) throws -> FileSystem {\n        try GitFileSystemView(repository: self, revision: revision)\n    }\n\n    public func openFileView(tag: String) throws -> FileSystem {\n        try GitFileSystemView(repository: self, tag: tag)\n    }\n\n    // MARK: Working Checkout Interface\n\n    public func hasUnpushedCommits() throws -> Bool {\n        try self.lock.withLock {\n            let hasOutput = try callGit(\n                \"log\",\n                \"--branches\",\n                \"--not\",\n                \"--remotes\",\n                failureMessage: \"Couldn’t check for unpushed commits\"\n            ).isEmpty\n            return !hasOutput\n        }\n    }\n\n    public func getCurrentRevision() throws -> Revision {\n        try self.lock.withLock {\n            try Revision(identifier: callGit(\n                \"rev-parse\",\n                \"--verify\",\n                \"HEAD\",\n                failureMessage: \"Couldn’t get current revision\"\n            ))\n        }\n    }\n\n    public func getCurrentTag() -> String? {\n        self.lock.withLock {\n            try? callGit(\n                \"describe\",\n                \"--exact-match\",\n                \"--tags\",\n                failureMessage: \"Couldn’t get current tag\"\n            )\n        }\n    }\n\n    public func checkout(tag: String) throws {\n        // FIXME: Audit behavior with off-branch tags in remote repositories, we\n        // may need to take a little more care here.\n        // use barrier for write operations\n        try self.lock.withLock {\n            try callGit(\n                \"reset\",\n                \"--hard\",\n                tag,\n                failureMessage: \"Couldn’t check out tag ‘\\(tag)’\"\n            )\n            try self.updateSubmoduleAndCleanIfNecessary()\n        }\n    }\n\n    public func checkout(revision: Revision) throws {\n        // FIXME: Audit behavior with off-branch tags in remote repositories, we\n        // may need to take a little more care here.\n        // use barrier for write operations\n        try self.lock.withLock {\n            try callGit(\n                \"checkout\",\n                \"-f\",\n                revision.identifier,\n                failureMessage: \"Couldn’t check out revision ‘\\(revision.identifier)’\"\n            )\n            try self.updateSubmoduleAndCleanIfNecessary()\n        }\n    }\n\n    internal func isBare() throws -> Bool {\n        return try self.cachedIsBareRepo.memoize(body: {\n            let output = try callGit(\n                \"rev-parse\",\n                \"--is-bare-repository\",\n                failureMessage: \"Couldn’t test for bare repository\"\n            )\n\n            return output == \"true\"\n        })\n    }\n\n    internal func checkoutExists() throws -> Bool {\n        return try !self.isBare()\n    }\n\n    private func updateSubmoduleAndCleanIfNecessary() throws {\n        if self.cachedHasSubmodules.get(default: false) || localFileSystem.exists(self.path.appending(\".gitmodules\")) {\n            self.cachedHasSubmodules.put(true)\n            try self.updateSubmoduleAndCleanNotOnQueue()\n        }\n    }\n\n    /// Initializes and updates the submodules, if any, and cleans left over the files and directories using git-clean.\n    private func updateSubmoduleAndCleanNotOnQueue() throws {\n        try self.callGit(\n            \"submodule\",\n            \"update\",\n            \"--init\",\n            \"--recursive\",\n            failureMessage: \"Couldn’t update repository submodules\"\n        )\n        try self.callGit(\n            \"clean\",\n            \"-ffdx\",\n            failureMessage: \"Couldn’t clean repository submodules\"\n        )\n    }\n\n    /// Returns true if a revision exists.\n    public func exists(revision: Revision) -> Bool {\n        let output = try? callGit(\"rev-parse\", \"--verify\", \"\\(revision.identifier)^{commit}\")\n        return output != nil\n    }\n\n    public func checkout(newBranch: String) throws {\n        guard self.isWorkingRepo else {\n            throw InternalError(\"This operation is only valid in a working repository\")\n        }\n        // use barrier for write operations\n        try self.lock.withLock {\n            try callGit(\n                \"checkout\",\n                \"-b\",\n                newBranch,\n                failureMessage: \"Couldn’t check out new branch ‘\\(newBranch)’\"\n            )\n        }\n    }\n\n    public func archive(to path: AbsolutePath) throws {\n        guard self.isWorkingRepo else {\n            throw InternalError(\"This operation is only valid in a working repository\")\n        }\n\n        try self.lock.withLock {\n            try callGit(\n                \"archive\",\n                \"--format\",\n                \"zip\",\n                \"--prefix\",\n                \"\\(path.basenameWithoutExt)/\",\n                \"--output\",\n                path.pathString,\n                \"HEAD\",\n                failureMessage: \"Couldn’t create an archive\"\n            )\n        }\n    }\n\n    /// Returns true if there is an alternative object store in the repository and it is valid.\n    public func isAlternateObjectStoreValid(expected: AbsolutePath) -> Bool {\n        let objectStoreFile = self.path.appending(components: \".git\", \"objects\", \"info\", \"alternates\")\n        guard let bytes = try? localFileSystem.readFileContents(objectStoreFile) else {\n            return false\n        }\n        let split = bytes.contents.split(separator: UInt8(ascii: \"\\n\"), maxSplits: 1, omittingEmptySubsequences: false)\n        guard let firstLine = ByteString(split[0]).validDescription else {\n            return false\n        }\n        guard let objectsPath = try? AbsolutePath(validating: firstLine), localFileSystem.isDirectory(objectsPath) else {\n            return false\n        }\n        let repositoryPath = objectsPath.parentDirectory\n        return expected == repositoryPath\n    }\n\n    /// Returns true if the file at `path` is ignored by `git`\n    public func areIgnored(_ paths: [Basics.AbsolutePath]) throws -> [Bool] {\n        try self.lock.withLock {\n            let stringPaths = paths.map(\\.pathString)\n\n            let output: String\n            do {\n                output = try self.git.run([\"-C\", self.path.pathString, \"check-ignore\"] + stringPaths)\n            } catch let error as GitShellError {\n                guard error.result.exitStatus == .terminated(code: 1) else {\n                    throw GitRepositoryError(\n                        path: self.path,\n                        message: \"unable to check ignored files\",\n                        result: error.result\n                    )\n                }\n                output = try error.result.utf8Output().spm_chomp()\n            }\n\n            return stringPaths.map(output.split(whereSeparator: { $0.isNewline }).map {\n                let string = String($0).replacing(\"\\\\\\\\\", with: \"\\\\\")\n                if string.utf8.first == UInt8(ascii: \"\\\"\") {\n                    return String(string.dropFirst(1).dropLast(1))\n                }\n                return string\n            }.contains)\n        }\n    }\n\n    // MARK: Git Operations\n\n    /// Resolve a \"treeish\" to a concrete hash.\n    ///\n    /// Technically this method can accept much more than a \"treeish\", it maps\n    /// to the syntax accepted by `git rev-parse`.\n    public func resolveHash(treeish: String, type: String? = nil) throws -> Hash {\n        let specifier: String\n        if let type {\n            specifier = treeish + \"^{\\(type)}\"\n        } else {\n            specifier = treeish\n        }\n        return try self.cachedHashes.memoize(specifier) {\n            try self.lock.withLock {\n                let output = try callGit(\n                    \"rev-parse\",\n                    \"--verify\",\n                    specifier,\n                    failureMessage: \"Couldn’t get revision ‘\\(specifier)’\"\n                )\n                guard let hash = Hash(output) else {\n                    throw GitInterfaceError.malformedResponse(\"expected an object hash in \\(output)\")\n                }\n                return hash\n            }\n        }\n    }\n\n    /// Read the commit referenced by `hash`.\n    public func readCommit(hash: Hash) throws -> Commit {\n        // Currently, we just load the tree, using the typed `rev-parse` syntax.\n        let treeHash = try resolveHash(treeish: hash.bytes.description, type: \"tree\")\n\n        return Commit(hash: hash, tree: treeHash)\n    }\n\n    /// Read a tree object.\n    public func readTree(location: Tree.Location) throws -> Tree {\n        switch location {\n        case .hash(let hash):\n            return try self.readTree(hash: hash)\n        case .tag(let tag):\n            return try self.readTree(tag: tag)\n        }\n    }\n\n    /// Read a tree object.\n    public func readTree(hash: Hash) throws -> Tree {\n        let hashString = hash.bytes.description\n        return try self.cachedTrees.memoize(hashString) {\n            try self.lock.withLock {\n                let output = try callGit(\n                    \"ls-tree\",\n                    hashString,\n                    failureMessage: \"Couldn’t read '\\(hashString)'\"\n                )\n                let entries = try self.parseTree(output)\n                return Tree(location: .hash(hash), contents: entries)\n            }\n        }\n    }\n\n    public func readTree(tag: String) throws -> Tree {\n        try self.cachedTrees.memoize(tag) {\n            try self.lock.withLock {\n                let output = try callGit(\n                    \"ls-tree\",\n                    tag,\n                    failureMessage: \"Couldn’t read '\\(tag)'\"\n                )\n                let entries = try self.parseTree(output)\n                return Tree(location: .tag(tag), contents: entries)\n            }\n        }\n    }\n\n    private func parseTree(_ text: String) throws -> [Tree.Entry] {\n        var entries = [Tree.Entry]()\n        for line in text.components(separatedBy: \"\\n\") {\n            // Ignore empty lines.\n            if line == \"\" { continue }\n\n            // Each line in the response should match:\n            //\n            //   `mode type hash\\tname`\n            //\n            // where `mode` is the 6-byte octal file mode, `type` is a 4-byte or 6-byte\n            // type (\"blob\", \"tree\", \"commit\"), `hash` is the hash, and the remainder of\n            // the line is the file name.\n            let bytes = ByteString(encodingAsUTF8: line)\n            let expectedBytesCount = 6 + 1 + 4 + 1 + 40 + 1\n            guard bytes.count > expectedBytesCount,\n                  bytes.contents[6] == UInt8(ascii: \" \"),\n                  // Search for the second space since `type` is of variable length.\n                  let secondSpace = bytes.contents[6 + 1 ..< bytes.contents.endIndex].firstIndex(of: UInt8(ascii: \" \")),\n                  bytes.contents[secondSpace] == UInt8(ascii: \" \"),\n                  bytes.contents[secondSpace + 1 + 40] == UInt8(ascii: \"\\t\")\n            else {\n                throw GitInterfaceError.malformedResponse(\"unexpected tree entry '\\(line)' in '\\(text)'\")\n            }\n\n            // Compute the mode.\n            let mode = bytes.contents[0 ..< 6].reduce(0) { (acc: Int, char: UInt8) in\n                (acc << 3) | (Int(char) - Int(UInt8(ascii: \"0\")))\n            }\n            guard let type = Tree.Entry.EntryType(mode: mode),\n                  let hash = Hash(asciiBytes: bytes.contents[(secondSpace + 1) ..< (secondSpace + 1 + 40)]),\n                  let name = ByteString(bytes.contents[(secondSpace + 1 + 40 + 1) ..< bytes.count]).validDescription\n            else {\n                throw GitInterfaceError.malformedResponse(\"unexpected tree entry '\\(line)' in '\\(text)'\")\n            }\n\n            // FIXME: We do not handle de-quoting of names, currently.\n            if name.hasPrefix(\"\\\"\") {\n                throw GitInterfaceError.malformedResponse(\"unexpected tree entry '\\(line)' in '\\(text)'\")\n            }\n\n            entries.append(Tree.Entry(location: .hash(hash), type: type, name: name))\n        }\n        return entries\n    }\n\n    /// Read a blob object.\n    func readBlob(hash: Hash) throws -> ByteString {\n        try self.cachedBlobs.memoize(hash) {\n            try self.lock.withLock {\n                // Get the contents using `cat-file`.\n                //\n                // FIXME: We need to get the raw bytes back, not a String.\n                let output = try callGit(\n                    \"cat-file\",\n                    \"-p\",\n                    hash.bytes.description,\n                    failureMessage: \"Couldn’t read ‘\\(hash.bytes.description)’\"\n                )\n                return ByteString(encodingAsUTF8: output)\n            }\n        }\n    }\n\n    /// Read a symbolic link.\n    func readLink(hash: Hash) throws -> String {\n        return try callGit(\n            \"cat-file\", \"-p\", String(describing: hash.bytes),\n            failureMessage: \"Couldn't read '\\(String(describing: hash.bytes))'\"\n        )\n    }\n}\n\n// MARK: - GitFileSystemView\n\n/// A `git` file system view.\n///\n/// The current implementation is based on lazily caching data with no eviction\n/// policy, and is very unoptimized.\nprivate class GitFileSystemView: FileSystem {\n    typealias Hash = GitRepository.Hash\n    typealias Tree = GitRepository.Tree\n\n    // MARK: Git Object Model\n\n    // The map of loaded trees.\n    var trees = ThreadSafeKeyValueStore<Tree.Location, Tree>()\n\n    /// The underlying repository.\n    let repository: GitRepository\n\n    /// The root tree hash.\n    // let root: GitRepository.Hash\n    let root: Tree.Location\n\n    init(repository: GitRepository, revision: Revision) throws {\n        self.repository = repository\n        self.root = try .hash(repository.readCommit(hash: Hash(revision.identifier)!).tree)\n    }\n\n    init(repository: GitRepository, tag: String) throws {\n        self.repository = repository\n        self.root = .tag(tag)\n    }\n\n    // MARK: FileSystem Implementations\n\n    private func getEntry(_ path: TSCAbsolutePath) throws -> Tree.Entry? {\n        // Walk the components resolving the tree (starting with a synthetic\n        // root entry).\n        var current = Tree.Entry(location: self.root, type: .tree, name: AbsolutePath.root.pathString)\n        var currentPath = AbsolutePath.root\n        for component in path.components {\n            // Skip the root pseudo-component.\n            if component == AbsolutePath.root.pathString { continue }\n\n            currentPath = currentPath.appending(component: component)\n            // We have a component to resolve, so the current entry must be a tree.\n            guard current.type == .tree else {\n                throw FileSystemError(.notDirectory, .init(currentPath))\n            }\n\n            // Fetch the tree.\n            let tree = try self.getTree(current.location)\n\n            // Search the tree for the component.\n            //\n            // FIXME: This needs to be optimized, somewhere.\n            guard let index = tree.contents.firstIndex(where: { $0.name == component }) else {\n                return nil\n            }\n\n            current = tree.contents[index]\n        }\n\n        return current\n    }\n\n    private func getTree(_ location: Tree.Location) throws -> Tree {\n        // Check the cache.\n        if let tree = trees[location] {\n            return tree\n        }\n\n        // Otherwise, load it.\n        let tree = try repository.readTree(location: location)\n        self.trees[location] = tree\n        return tree\n    }\n\n    func exists(_ path: TSCAbsolutePath, followSymlink: Bool) -> Bool {\n        do {\n            return try self.getEntry(path) != nil\n        } catch {\n            return false\n        }\n    }\n\n    func isFile(_ path: TSCAbsolutePath) -> Bool {\n        do {\n            if let entry = try getEntry(path), entry.type != .tree {\n                return true\n            }\n            return false\n        } catch {\n            return false\n        }\n    }\n\n    func isDirectory(_ path: TSCAbsolutePath) -> Bool {\n        do {\n            if let entry = try getEntry(path), entry.type == .tree {\n                return true\n            }\n            return false\n        } catch {\n            return false\n        }\n    }\n\n    func isSymlink(_ path: TSCAbsolutePath) -> Bool {\n        do {\n            if let entry = try getEntry(path), entry.type == .symlink {\n                return true\n            }\n            return false\n        } catch {\n            return false\n        }\n    }\n\n    func isExecutableFile(_ path: TSCAbsolutePath) -> Bool {\n        if let entry = try? getEntry(path), entry.type == .executableBlob {\n            return true\n        }\n        return false\n    }\n\n    func isReadable(_ path: TSCAbsolutePath) -> Bool {\n        self.exists(path)\n    }\n\n    func isWritable(_: TSCAbsolutePath) -> Bool {\n        false\n    }\n\n    public var currentWorkingDirectory: TSCAbsolutePath? {\n        TSCAbsolutePath.root\n    }\n\n    func changeCurrentWorkingDirectory(to path: TSCAbsolutePath) throws {\n        throw InternalError(\"changeCurrentWorkingDirectory not supported\")\n    }\n\n    func getDirectoryContents(_ path: TSCAbsolutePath) throws -> [String] {\n        guard let entry = try getEntry(path) else {\n            throw FileSystemError(.noEntry, path)\n        }\n        guard entry.type == .tree else {\n            throw FileSystemError(.notDirectory, path)\n        }\n        return try self.getTree(entry.location).contents.map(\\.name)\n    }\n\n    func readFileContents(_ path: TSCAbsolutePath) throws -> ByteString {\n        guard let entry = try getEntry(path) else {\n            throw FileSystemError(.noEntry, path)\n        }\n        guard entry.type != .tree else {\n            throw FileSystemError(.isDirectory, path)\n        }\n        guard case .hash(let hash) = entry.location else {\n            throw InternalError(\"only hash locations supported\")\n        }\n        switch entry.type {\n        case .symlink:\n            let path = try repository.readLink(hash: hash)\n            return try readFileContents(AbsolutePath(validating: path))\n        case .blob, .executableBlob:\n            return try self.repository.readBlob(hash: hash)\n        default:\n            throw InternalError(\"unsupported git entry type \\(entry.type) at path \\(path)\")\n        }\n    }\n\n    // MARK: Unsupported methods.\n\n    public var homeDirectory: TSCAbsolutePath {\n        fatalError(\"unsupported\")\n    }\n\n    public var cachesDirectory: TSCAbsolutePath? {\n        fatalError(\"unsupported\")\n    }\n\n    public var tempDirectory: TSCAbsolutePath {\n        fatalError(\"unsupported\")\n    }\n\n    func createDirectory(_ path: TSCAbsolutePath) throws {\n        throw FileSystemError(.unsupported, path)\n    }\n\n    func createDirectory(_ path: TSCAbsolutePath, recursive: Bool) throws {\n        throw FileSystemError(.unsupported, path)\n    }\n\n    func createSymbolicLink(_ path: TSCAbsolutePath, pointingAt destination: TSCAbsolutePath, relative: Bool) throws {\n        throw FileSystemError(.unsupported, path)\n    }\n\n    func writeFileContents(_ path: TSCAbsolutePath, bytes: ByteString) throws {\n        throw FileSystemError(.unsupported, path)\n    }\n\n    func removeFileTree(_ path: TSCAbsolutePath) throws {\n        throw FileSystemError(.unsupported, path)\n    }\n\n    func chmod(_ mode: FileMode, path: TSCAbsolutePath, options: Set<FileMode.Option>) throws {\n        throw FileSystemError(.unsupported, path)\n    }\n\n    func copy(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws {\n        fatalError(\"will never be supported\")\n    }\n\n    func move(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws {\n        fatalError(\"will never be supported\")\n    }\n}\n\n// State of `GitFileSystemView` is protected with `ThreadSafeKeyValueStore`.\nextension GitFileSystemView: @unchecked Sendable {}\n\n// MARK: - Errors\n\npackage struct GitShellError: Error, CustomStringConvertible {\n    let result: AsyncProcessResult\n\n    public var description: String {\n        let stdout = (try? self.result.utf8Output()) ?? \"\"\n        let stderr = (try? self.result.utf8stderrOutput()) ?? \"\"\n        let output = (stdout + stderr).spm_chomp()\n        let command = self.result.arguments.joined(separator: \" \")\n        return \"Git command '\\(command)' failed: \\(output)\"\n    }\n}\n\nprivate enum GitInterfaceError: Swift.Error {\n    /// This indicates a problem communicating with the `git` tool.\n    case malformedResponse(String)\n\n    /// This indicates that a fatal error was encountered\n    case fatalError\n}\n\npublic struct GitRepositoryError: Error, CustomStringConvertible, DiagnosticLocationProviding {\n    public let path: AbsolutePath\n    public let message: String\n    package let result: AsyncProcessResult\n\n    public struct Location: DiagnosticLocation {\n        public let path: AbsolutePath\n        public var description: String {\n            self.path.pathString\n        }\n    }\n\n    public var diagnosticLocation: DiagnosticLocation? {\n        Location(path: self.path)\n    }\n\n    public var description: String {\n        let stdout = (try? self.result.utf8Output()) ?? \"\"\n        let stderr = (try? self.result.utf8stderrOutput()) ?? \"\"\n        let output = (stdout + stderr).spm_chomp().spm_multilineIndent(count: 4)\n        return \"\\(self.message):\\n\\(output)\"\n    }\n}\n\npublic struct GitCloneError: Error, CustomStringConvertible, DiagnosticLocationProviding {\n    public let repository: RepositorySpecifier\n    public let message: String\n    package let result: AsyncProcessResult\n\n    public struct Location: DiagnosticLocation {\n        public let repository: RepositorySpecifier\n        public var description: String {\n            self.repository.location.description\n        }\n    }\n\n    public var diagnosticLocation: DiagnosticLocation? {\n        Location(repository: self.repository)\n    }\n\n    public var description: String {\n        let stdout = (try? self.result.utf8Output()) ?? \"\"\n        let stderr = (try? self.result.utf8stderrOutput()) ?? \"\"\n        let output = (stdout + stderr).spm_chomp().spm_multilineIndent(count: 4)\n        return \"\\(self.message):\\n\\(output)\"\n    }\n}\n\npublic enum GitProgressParser: FetchProgress {\n    case enumeratingObjects(currentObjects: Int)\n    case countingObjects(progress: Double, currentObjects: Int, totalObjects: Int)\n    case compressingObjects(progress: Double, currentObjects: Int, totalObjects: Int)\n    case receivingObjects(\n        progress: Double,\n        currentObjects: Int,\n        totalObjects: Int,\n        downloadProgress: String?,\n        downloadSpeed: String?\n    )\n    case resolvingDeltas(progress: Double, currentObjects: Int, totalObjects: Int)\n\n    /// The pattern used to match git output. Capture groups are labeled from ?<i0> to ?<i19>.\n    static let pattern = #\"\"\"\n    (?xi)\n    (?:\n        remote: \\h+ (?<i0>Enumerating \\h objects): \\h+ (?<i1>[0-9]+)\n    )|\n    (?:\n        remote: \\h+ (?<i2>Counting \\h objects): \\h+ (?<i3>[0-9]+)% \\h+ \\((?<i4>[0-9]+)\\/(?<i5>[0-9]+)\\)\n    )|\n    (?:\n        remote: \\h+ (?<i6>Compressing \\h objects): \\h+ (?<i7>[0-9]+)% \\h+ \\((?<i8>[0-9]+)\\/(?<i9>[0-9]+)\\)\n    )|\n    (?:\n        (?<i10>Resolving \\h deltas): \\h+ (?<i11>[0-9]+)% \\h+ \\((?<i12>[0-9]+)\\/(?<i13>[0-9]+)\\)\n    )|\n    (?:\n        (?<i14>Receiving \\h objects): \\h+ (?<i15>[0-9]+)% \\h+ \\((?<i16>[0-9]+)\\/(?<i17>[0-9]+)\\)\n        (?:, \\h+ (?<i18>[0-9]+.?[0-9]+ \\h [A-Z]iB) \\h+ \\| \\h+ (?<i19>[0-9]+.?[0-9]+ \\h [A-Z]iB\\/s))?\n    )\n    \"\"\"#\n    static let regex = try? RegEx(pattern: pattern)\n\n    init?(from string: String) {\n        guard let matches = GitProgressParser.regex?.matchGroups(in: string).first,\n              matches.count == 20 else { return nil }\n\n        if matches[0] == \"Enumerating objects\" {\n            guard let currentObjects = Int(matches[1]) else { return nil }\n\n            self = .enumeratingObjects(currentObjects: currentObjects)\n        } else if matches[2] == \"Counting objects\" {\n            guard let progress = Double(matches[3]),\n                  let currentObjects = Int(matches[4]),\n                  let totalObjects = Int(matches[5]) else { return nil }\n\n            self = .countingObjects(\n                progress: progress / 100,\n                currentObjects: currentObjects,\n                totalObjects: totalObjects\n            )\n\n        } else if matches[6] == \"Compressing objects\" {\n            guard let progress = Double(matches[7]),\n                  let currentObjects = Int(matches[8]),\n                  let totalObjects = Int(matches[9]) else { return nil }\n\n            self = .compressingObjects(\n                progress: progress / 100,\n                currentObjects: currentObjects,\n                totalObjects: totalObjects\n            )\n\n        } else if matches[10] == \"Resolving deltas\" {\n            guard let progress = Double(matches[11]),\n                  let currentObjects = Int(matches[12]),\n                  let totalObjects = Int(matches[13]) else { return nil }\n\n            self = .resolvingDeltas(\n                progress: progress / 100,\n                currentObjects: currentObjects,\n                totalObjects: totalObjects\n            )\n\n        } else if matches[14] == \"Receiving objects\" {\n            guard let progress = Double(matches[15]),\n                  let currentObjects = Int(matches[16]),\n                  let totalObjects = Int(matches[17]) else { return nil }\n\n            let downloadProgress = matches[18]\n            let downloadSpeed = matches[19]\n\n            self = .receivingObjects(\n                progress: progress / 100,\n                currentObjects: currentObjects,\n                totalObjects: totalObjects,\n                downloadProgress: downloadProgress,\n                downloadSpeed: downloadSpeed\n            )\n\n        } else {\n            return nil\n        }\n    }\n\n    public var message: String {\n        switch self {\n        case .enumeratingObjects: return \"Enumerating objects\"\n        case .countingObjects: return \"Counting objects\"\n        case .compressingObjects: return \"Compressing objects\"\n        case .receivingObjects: return \"Receiving objects\"\n        case .resolvingDeltas: return \"Resolving deltas\"\n        }\n    }\n\n    public var step: Int {\n        switch self {\n        case .enumeratingObjects(let currentObjects):\n            return currentObjects\n        case .countingObjects(_, let currentObjects, _):\n            return currentObjects\n        case .compressingObjects(_, let currentObjects, _):\n            return currentObjects\n        case .receivingObjects(_, let currentObjects, _, _, _):\n            return currentObjects\n        case .resolvingDeltas(_, let currentObjects, _):\n            return currentObjects\n        }\n    }\n\n    public var totalSteps: Int? {\n        switch self {\n        case .enumeratingObjects:\n            return 0\n        case .countingObjects(_, _, let totalObjects):\n            return totalObjects\n        case .compressingObjects(_, _, let totalObjects):\n            return totalObjects\n        case .receivingObjects(_, _, let totalObjects, _, _):\n            return totalObjects\n        case .resolvingDeltas(_, _, let totalObjects):\n            return totalObjects\n        }\n    }\n\n    public var downloadProgress: String? {\n        switch self {\n        case .receivingObjects(_, _, _, let downloadProgress, _):\n            return downloadProgress\n        default:\n            return nil\n        }\n    }\n\n    public var downloadSpeed: String? {\n        switch self {\n        case .receivingObjects(_, _, _, _, let downloadSpeed):\n            return downloadSpeed\n        default:\n            return nil\n        }\n    }\n}\n\n/// Processes stdout output and calls the progress callback with `GitStatus` objects.\nprivate func gitFetchStatusFilter(_ bytes: [UInt8], progress: FetchProgress.Handler) {\n    guard let string = String(bytes: bytes, encoding: .utf8) else { return }\n    let lines = string\n        .split { $0.isNewline }\n        .map { String($0) }\n\n    for line in lines {\n        if let status = GitProgressParser(from: line) {\n            switch status {\n            case .receivingObjects:\n                progress(status)\n            default:\n                continue\n            }\n        }\n    }\n}\n\nextension RepositorySpecifier.Location {\n    fileprivate var gitURL: String {\n        switch self {\n        case .path(let path):\n            return path.pathString\n        case .url(let url):\n            return url.absoluteString\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SourceControl/Repository.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n/// Specifies a repository address.\npublic struct RepositorySpecifier: Hashable, Sendable {\n    public let location: Location\n\n    public init(location: Location) {\n        self.location = location\n    }\n\n    /// Create a specifier based on a path.\n    public init(path: AbsolutePath) {\n        self.init(location: .path(path))\n    }\n\n    /// Create a specifier on a URL.\n    public init(url: SourceControlURL) {\n        self.init(location: .url(url))\n    }\n\n    /// The location of the repository as string.\n    public var url: String {\n        switch self.location {\n        case .path(let path): return path.pathString\n        case .url(let url): return url.absoluteString\n        }\n    }\n\n    /// Returns the cleaned basename for the specifier.\n    public var basename: String {\n        // FIXME: this might be wrong\n        //var basename = self.url.pathComponents.dropFirst(1).last(where: { !$0.isEmpty }) ?? \"\"\n        var basename = (self.url as NSString).lastPathComponent\n        if basename.hasSuffix(\".git\") {\n            basename = String(basename.dropLast(4))\n        }\n        if basename == \"/\" || basename == \"\\\\\" {\n            return \"\"\n        }\n        return basename\n    }\n\n    public enum Location: Hashable, CustomStringConvertible, Sendable {\n        case path(AbsolutePath)\n        case url(SourceControlURL)\n\n        public var description: String {\n            switch self {\n            case .path(let path):\n                return path.pathString\n            case .url(let url):\n                return url.absoluteString\n            }\n        }\n    }\n}\n\nextension RepositorySpecifier: CustomStringConvertible {\n    public var description: String {\n        return self.location.description\n    }\n}\n\n/// A repository provider.\n///\n/// This protocol defines the lower level interface used to to access\n/// repositories. High-level clients should access repositories via a\n/// `RepositoryManager`.\npublic protocol RepositoryProvider: Cancellable, Sendable {\n    /// Fetch the complete repository at the given location to `path`.\n    ///\n    /// - Parameters:\n    ///   - repository: The specifier of the repository to fetch.\n    ///   - path: The destination path for the fetch.\n    ///   - progress: Reports the progress of the current fetch operation.\n    /// - Throws: If there is any error fetching the repository.\n    func fetch(repository: RepositorySpecifier, to path: AbsolutePath, progressHandler: FetchProgress.Handler?) async throws\n\n    /// Open the given repository.\n    ///\n    /// - Parameters:\n    ///   - repository: The specifier of the original repository from which the\n    ///     local clone repository was created.\n    ///   - path: The location of the repository on disk, at which the\n    ///     repository has previously been created via `fetch`.\n    ///\n    /// - Throws: If the repository is unable to be opened.\n    func open(repository: RepositorySpecifier, at path: AbsolutePath) async throws -> Repository\n\n    /// Create a working copy from a managed repository.\n    ///\n    /// Once complete, the repository can be opened using `openWorkingCopy`. Note\n    /// that there is no requirement that the files have been materialized into\n    /// the file system at the completion of this call, since it will always be\n    /// followed by checking out the cloned working copy at a particular ref.\n    ///\n    /// - Parameters:\n    ///   - repository: The specifier of the original repository from which the\n    ///     local clone repository was created.\n    ///   - sourcePath: The location of the repository on disk, at which the\n    ///     repository has previously been created via `fetch`.\n    ///   - destinationPath: The path at which to create the working copy; it is\n    ///     expected to be non-existent when called.\n    ///   - editable: The checkout is expected to be edited by users.\n    ///\n    /// - Throws: If there is any error cloning the repository.\n    func createWorkingCopy(\n        repository: RepositorySpecifier,\n        sourcePath: AbsolutePath,\n        at destinationPath: AbsolutePath,\n        editable: Bool) async throws -> WorkingCheckout\n\n    /// Returns true if a working repository exists at `path`\n    func workingCopyExists(at path: AbsolutePath) throws -> Bool\n\n    /// Open a working repository copy.\n    ///\n    /// - Parameters:\n    ///   - path: The location of the repository on disk, at which the repository\n    ///     has previously been created via `copyToWorkingDirectory`.\n    func openWorkingCopy(at path: AbsolutePath) async throws -> WorkingCheckout\n\n    /// Copies the repository at path `from` to path `to`.\n    /// - Parameters:\n    ///   - sourcePath: the source path.\n    ///   - destinationPath: the destination  path.\n    func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws\n\n    /// Returns true if the directory is valid git location.\n    func isValidDirectory(_ directory: AbsolutePath) throws -> Bool\n\n    /// Returns true if the directory is valid git location for the specified repository\n    func isValidDirectory(_ directory: AbsolutePath, for repository: RepositorySpecifier) throws -> Bool\n}\n\n/// Abstract repository operations.\n///\n/// This interface provides access to an abstracted representation of a\n/// repository which is ultimately owned by a `RepositoryManager`. This interface\n/// is designed in such a way as to provide the minimal facilities required by\n/// the package manager to gather basic information about a repository, but it\n/// does not aim to provide all of the interfaces one might want for working\n/// with an editable checkout of a repository on disk.\n///\n/// The goal of this design is to allow the `RepositoryManager` a large degree of\n/// flexibility in the storage and maintenance of its underlying repositories.\n///\n/// This protocol is designed under the assumption that the repository can only\n/// be mutated via the functions provided here; thus, e.g., `tags` is expected\n/// to be unchanged through the lifetime of an instance except as otherwise\n/// documented. The behavior when this assumption is violated is undefined,\n/// although the expectation is that implementations should throw or crash when\n/// an inconsistency can be detected.\npublic protocol Repository: Sendable {\n    /// Get the list of tags in the repository.\n    func getTags() throws -> [String]\n\n    /// Resolve the revision for a specific tag.\n    ///\n    /// - Precondition: The `tag` should be a member of `tags`.\n    /// - Throws: If a error occurs accessing the named tag.\n    func resolveRevision(tag: String) throws -> Revision\n\n    /// Resolve the revision for an identifier.\n    ///\n    /// The identifier can be a branch name or a revision identifier.\n    ///\n    /// - Throws: If the identifier can not be resolved.\n    func resolveRevision(identifier: String) throws -> Revision\n\n    /// Fetch and update the repository from its remote.\n    ///\n    /// - Throws: If an error occurs while performing the fetch operation.\n    func fetch() throws\n\n    /// Fetch and update the repository from its remote.\n    ///\n    /// - Throws: If an error occurs while performing the fetch operation.\n    func fetch(progress: FetchProgress.Handler?) throws\n\n    /// Returns true if the given revision exists.\n    func exists(revision: Revision) -> Bool\n\n    /// Open an immutable file system view for a particular revision.\n    ///\n    /// This view exposes the contents of the repository at the given revision\n    /// as a file system rooted inside the repository. The repository must\n    /// support opening multiple views concurrently, but the expectation is that\n    /// clients should be prepared for this to be inefficient when performing\n    /// interleaved accesses across separate views (i.e., the repository may\n    /// back the view by an actual file system representation of the\n    /// repository).\n    ///\n    /// It is expected behavior that attempts to mutate the given FileSystem\n    /// will fail or crash.\n    ///\n    /// - Throws: If an error occurs accessing the revision.\n    func openFileView(revision: Revision) throws -> FileSystem\n\n    /// Open an immutable file system view for a particular tag.\n    ///\n    /// This view exposes the contents of the repository at the given revision\n    /// as a file system rooted inside the repository. The repository must\n    /// support opening multiple views concurrently, but the expectation is that\n    /// clients should be prepared for this to be inefficient when performing\n    /// interleaved accesses across separate views (i.e., the repository may\n    /// back the view by an actual file system representation of the\n    /// repository).\n    ///\n    /// It is expected behavior that attempts to mutate the given FileSystem\n    /// will fail or crash.\n    ///\n    /// - Throws: If an error occurs accessing the revision.\n    func openFileView(tag: String) throws -> FileSystem\n}\n\nextension Repository {\n    public func fetch(progress: FetchProgress.Handler?) throws {\n        try fetch()\n    }\n}\n\n/// An editable checkout of a repository (i.e. a working copy) on the local file\n/// system.\npublic protocol WorkingCheckout {\n    /// Get the list of tags in the repository.\n    func getTags() throws -> [String]\n\n    /// Get the current revision.\n    func getCurrentRevision() throws -> Revision\n\n    /// Fetch and update the repository from its remote.\n    ///\n    /// - Throws: If an error occurs while performing the fetch operation.\n    func fetch() throws\n\n    /// Query whether the checkout has any commits which are not pushed to its remote.\n    func hasUnpushedCommits() throws -> Bool\n\n    /// This check for any modified state of the repository and returns true\n    /// if there are uncommitted changes.\n    func hasUncommittedChanges() -> Bool\n\n    /// Check out the given tag.\n    func checkout(tag: String) throws\n\n    /// Check out the given revision.\n    func checkout(revision: Revision) throws\n\n    /// Returns true if the given revision exists.\n    func exists(revision: Revision) -> Bool\n\n    /// Create a new branch and checkout HEAD to it.\n    ///\n    /// Note: It is an error to provide a branch name which already exists.\n    func checkout(newBranch: String) throws\n\n    /// Returns true if there is an alternative store in the checkout and it is valid.\n    func isAlternateObjectStoreValid(expected: AbsolutePath) -> Bool\n\n    /// Returns true if the file at `path` is ignored by `git`\n    func areIgnored(_ paths: [AbsolutePath]) throws -> [Bool]\n}\n\n/// A single repository revision.\npublic struct Revision: Hashable, Sendable {\n    /// A precise identifier for a single repository revision, in a repository-specified manner.\n    ///\n    /// This string is intended to be opaque to the client, but understandable\n    /// by a user. For example, a Git repository might supply the SHA1 of a\n    /// commit, or an SVN repository might supply a string such as 'r123'.\n    public let identifier: String\n\n    public init(identifier: String) {\n        self.identifier = identifier\n    }\n}\n\npublic protocol FetchProgress: Sendable {\n    typealias Handler = (FetchProgress) -> Void\n\n    var message: String { get }\n    var step: Int { get }\n    var totalSteps: Int? { get }\n    /// The current download progress including the unit\n    var downloadProgress: String? { get }\n    /// The current download speed including the unit\n    var downloadSpeed: String? { get }\n}\n"
  },
  {
    "path": "Sources/SourceControl/RepositoryManager.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport Foundation\nimport PackageModel\nimport TSCBasic\n\n/// Manages a collection of bare repositories.\npublic class RepositoryManager: Cancellable {\n    public typealias Delegate = RepositoryManagerDelegate\n\n    /// The path under which repositories are stored.\n    public let path: Basics.AbsolutePath\n\n    /// The path to the directory where all cached git repositories are stored.\n    private let cachePath: Basics.AbsolutePath?\n\n    // used in tests to disable skipping of local packages.\n    private let cacheLocalPackages: Bool\n\n    /// The repository provider.\n    private let provider: RepositoryProvider\n\n    /// The delegate interface.\n    private let delegate: RepositoryManagerDelegateProxy?\n\n    /// The filesystem to operate on.\n    private let fileSystem: FileSystem\n\n    // tracks outstanding lookups for de-duping requests\n    private var pendingLookups = [RepositorySpecifier: Task<RepositoryManager.RepositoryHandle, Error>]()\n    private var pendingLookupsLock = NSLock()\n\n    // Limits how many concurrent operations can be performed at once.\n    private let asyncOperationQueue: AsyncOperationQueue\n\n    private var emitNoConnectivityWarning = ThreadSafeBox<[String: Bool]>([:])\n\n    /// Create a new empty manager.\n    ///\n    /// - Parameters:\n    ///   - fileSystem: The filesystem to operate on.\n    ///   - path: The path under which to store repositories. This should be a\n    ///           directory in which the content can be completely managed by this\n    ///           instance.\n    ///   - provider: The repository provider.\n    ///   - cachePath: The repository cache location.\n    ///   - cacheLocalPackages: Should cache local packages as well. For testing purposes.\n    ///   - maxConcurrentOperations: Max concurrent lookup operations\n    ///   - initializationWarningHandler: Initialization warnings handler.\n    ///   - delegate: The repository manager delegate.\n    public init(\n        fileSystem: FileSystem,\n        path: Basics.AbsolutePath,\n        provider: RepositoryProvider,\n        cachePath: Basics.AbsolutePath? =  .none,\n        cacheLocalPackages: Bool = false,\n        maxConcurrentOperations: Int? = .none,\n        initializationWarningHandler: (String) -> Void,\n        delegate: Delegate? = .none\n    ) {\n        self.fileSystem = fileSystem\n        self.path = path\n        self.cachePath = cachePath\n        self.cacheLocalPackages = cacheLocalPackages\n\n        self.provider = provider\n        self.delegate = RepositoryManagerDelegateProxy(delegate)\n\n        // this queue and semaphore is used to limit the amount of concurrent git operations taking place\n        let maxConcurrentOperations = max(1, maxConcurrentOperations ?? (3 * Concurrency.maxOperations / 4))\n        self.asyncOperationQueue = AsyncOperationQueue(concurrentTasks: maxConcurrentOperations)\n    }\n\n    /// Get a handle to a repository.\n    ///\n    /// This will initiate a clone of the repository automatically, if necessary.\n    ///\n    /// Note: Recursive lookups are not supported i.e. calling lookup inside\n    /// completion block of another lookup will block.\n    ///\n    /// - Parameters:\n    ///   - package: The package identity of the repository to fetch,\n    ///   - repository: The repository to look up.\n    ///   - updateStrategy: strategy to update the repository.\n    ///   - observabilityScope: The observability scope\n    ///   - delegateQueue: Dispatch queue for delegate events\n    ///   - callbackQueue: Dispatch queue for callbacks\n    ///   - completion: The completion block that should be called after lookup finishes.\n    @available(*, noasync, message: \"Use the async alternative\")\n    public func lookup(\n        package: PackageIdentity,\n        repository: RepositorySpecifier,\n        updateStrategy: RepositoryUpdateStrategy,\n        observabilityScope: ObservabilityScope,\n        callbackQueue: DispatchQueue,\n        completion: @escaping @Sendable (Result<RepositoryHandle, Error>) -> Void\n    ) {\n        callbackQueue.asyncResult(completion) {\n            // check if the repository is already being looked up\n            // if so, wait for it to finish and return the result\n            try await self.lookup(\n                package: package,\n                repository: repository,\n                updateStrategy: updateStrategy,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    public func lookup(\n        package: PackageIdentity,\n        repository repositorySpecifier: RepositorySpecifier,\n        updateStrategy: RepositoryUpdateStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> RepositoryHandle {\n        return try await self.asyncOperationQueue.withOperation {\n            let task = await withCheckedContinuation { continuation in\n                self.pendingLookupsLock.lock()\n                defer { self.pendingLookupsLock.unlock() }\n\n                let lookupTask: Task<RepositoryManager.RepositoryHandle, any Error>\n                if let inFlight = self.pendingLookups[repositorySpecifier] {\n                    lookupTask = Task {\n                        // Let the existing in-flight task finish before queuing up the new one\n                        let _ = try await inFlight.value\n\n                        if Task.isCancelled {\n                            throw CancellationError()\n                        }\n\n                        let result = try await self.performLookup(\n                            package: package,\n                            repository: repositorySpecifier,\n                            updateStrategy: updateStrategy,\n                            observabilityScope: observabilityScope\n                        )\n\n                        if Task.isCancelled {\n                            throw CancellationError()\n                        }\n\n                        return result\n                    }\n                } else {\n                    lookupTask = Task {\n                        if Task.isCancelled {\n                            throw CancellationError()\n                        }\n\n                        let result = try await self.performLookup(\n                            package: package,\n                            repository: repositorySpecifier,\n                            updateStrategy: updateStrategy,\n                            observabilityScope: observabilityScope\n                        )\n\n                        if Task.isCancelled {\n                            throw CancellationError()\n                        }\n\n                        return result\n                    }\n                }\n\n                self.pendingLookups[repositorySpecifier] = lookupTask\n                continuation.resume(returning: lookupTask)\n            }\n\n            do {\n                let result = try await task.value\n                return result\n            } catch {\n                throw error\n            }\n        }\n    }\n\n    private func performLookup(\n        package: PackageIdentity,\n        repository repositorySpecifier: RepositorySpecifier,\n        updateStrategy: RepositoryUpdateStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> RepositoryHandle {\n        let relativePath = try repositorySpecifier.storagePath()\n        let repositoryPath = self.path.appending(relativePath)\n        let handle = RepositoryHandle(manager: self, repository: repositorySpecifier, subpath: relativePath)\n        let delegate = self.delegate\n\n        // check if a repository already exists\n        // errors when trying to check if a repository already exists are legitimate\n        // and recoverable, and as such can be ignored\n        quick: if (try? self.provider.isValidDirectory(repositoryPath)) ?? false {\n            let repository = try await handle.open()\n\n            guard ((try? self.provider.isValidDirectory(repositoryPath, for: repositorySpecifier)) ?? false) else {\n                observabilityScope.emit(warning: \"\\(repositoryPath) is not valid git repository for '\\(repositorySpecifier.location)', will fetch again.\")\n                break quick\n            }\n\n            // Update the repository if needed\n            if self.fetchRequired(repository: repository, updateStrategy: updateStrategy) {\n                let start = DispatchTime.now()\n\n                Task {\n                    await delegate?.willUpdate(package: package, repository: handle.repository)\n                }\n\n                try repository.fetch()\n                let duration = start.distance(to: .now())\n                Task {\n                    await delegate?.didUpdate(package: package, repository: handle.repository, duration: duration)\n                }\n            }\n\n            return handle\n        }\n\n        // inform delegate that we are starting to fetch\n        // calculate if cached (for delegate call) outside queue as it may change while queue is processing\n        let isCached = self.cachePath.map { self.fileSystem.exists($0.appending(handle.subpath)) } ?? false\n        Task {\n            let details = FetchDetails(fromCache: isCached, updatedCache: false)\n            await delegate?.willFetch(package: package, repository: handle.repository, details: details)\n        }\n\n        // perform the fetch\n        let start = DispatchTime.now()\n        do {\n            // make sure destination is free.\n            try? self.fileSystem.removeFileTree(repositoryPath)\n            // fetch the repo and cache the results\n            let result = try await self.fetchAndPopulateCache(\n                package: package,\n                handle: handle,\n                repositoryPath: repositoryPath,\n                updateStrategy: updateStrategy,\n                observabilityScope: observabilityScope\n            )\n            // inform delegate fetch is done\n            let duration = start.distance(to: .now())\n            Task {\n                await delegate?.didFetch(package: package, repository: handle.repository, result: .success(result), duration: duration)\n            }\n            return handle\n        } catch {\n            // inform delegate fetch is done\n            let duration = start.distance(to: .now())\n            Task {\n                await delegate?.didFetch(package: package, repository: handle.repository, result: .failure(error), duration: duration)\n            }\n            throw error\n        }\n    }\n\n    public func cancel(deadline: DispatchTime) throws {\n        // ask the provider to cancel\n        try self.provider.cancel(deadline: deadline)\n\n        self.pendingLookupsLock.lock()\n        defer { self.pendingLookupsLock.unlock() }\n        for task in self.pendingLookups.values {\n            task.cancel()\n        }\n        self.pendingLookups = [:]\n    }\n\n    /// Fetches the repository into the cache. If no `cachePath` is set or an error occurred fall back to fetching the repository without populating the cache.\n    /// - Parameters:\n    ///   - package: The package identity of the repository to fetch.\n    ///   - handle: The specifier of the repository to fetch.\n    ///   - repositoryPath: The path where the repository should be fetched to.\n    ///   - observabilityScope: The observability scope\n    ///   - delegateQueue: Dispatch queue for delegate events\n    @discardableResult\n    private func fetchAndPopulateCache(\n        package: PackageIdentity,\n        handle: RepositoryHandle,\n        repositoryPath: Basics.AbsolutePath,\n        updateStrategy: RepositoryUpdateStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> FetchDetails {\n        var cacheUsed = false\n        var cacheUpdated = false\n\n        // utility to update progress\n        func updateFetchProgress(progress: FetchProgress) -> Void {\n            if let total = progress.totalSteps {\n                let delegate = self.delegate\n                Task {\n                    await delegate?.fetching(\n                        package: package,\n                        repository: handle.repository,\n                        objectsFetched: progress.step,\n                        totalObjectsToFetch: total\n                    )\n                }\n            }\n        }\n\n        // We are expecting handle.repository.url to always be a resolved absolute path.\n        let shouldCacheLocalPackages = Environment.current[\"SWIFTPM_TESTS_PACKAGECACHE\"] == \"1\" || cacheLocalPackages\n\n        if let cachePath, !(handle.repository.isLocal && !shouldCacheLocalPackages) {\n            let cachedRepositoryPath = try cachePath.appending(handle.repository.storagePath())\n            do {\n                try self.initializeCacheIfNeeded(cachePath: cachePath)\n                try await self.fileSystem.withLock(on: cachePath, type: .shared) {\n                    try await self.fileSystem.withLock(on: cachedRepositoryPath, type: .exclusive) {\n                        // Fetch the repository into the cache.\n                        if (self.fileSystem.exists(cachedRepositoryPath)) {\n                            let repo = try await self.provider.open(repository: handle.repository, at: cachedRepositoryPath)\n                            if self.fetchRequired(repository: repo, updateStrategy: updateStrategy) {\n                                try repo.fetch(progress: updateFetchProgress(progress:))\n                            }\n                            cacheUsed = true\n                        } else {\n                            try await self.provider.fetch(repository: handle.repository, to: cachedRepositoryPath, progressHandler: updateFetchProgress(progress:))\n                        }\n                        cacheUpdated = true\n                        // extra validation to defend from racy edge cases\n                        if self.fileSystem.exists(repositoryPath) {\n                            throw StringError(\"\\(repositoryPath) already exists unexpectedly\")\n                        }\n                        // Copy the repository from the cache into the repository path.\n                        try self.fileSystem.createDirectory(repositoryPath.parentDirectory, recursive: true)\n                        try self.provider.copy(from: cachedRepositoryPath, to: repositoryPath)\n                    }\n                }\n            } catch {\n                // If we are offline and have a valid cached repository, use the cache anyway.\n                if try isOffline(error) && self.provider.isValidDirectory(cachedRepositoryPath, for: handle.repository) {\n                    // For the first offline use in the lifetime of this repository manager, emit a warning.\n                    self.emitNoConnectivityWarning.mutate(body: {\n                        if !$0[handle.repository.url, default: false] {\n                            $0[handle.repository.url] = true\n                            observabilityScope.emit(warning: \"no connectivity to \\(handle.repository.url), using previously cached repository state\")\n                        }\n                    })\n                    observabilityScope.emit(info: \"using previously cached repository state for \\(package)\")\n\n                    cacheUsed = true\n                    // Copy the repository from the cache into the repository path.\n                    try self.fileSystem.createDirectory(repositoryPath.parentDirectory, recursive: true)\n                    try self.provider.copy(from: cachedRepositoryPath, to: repositoryPath)\n                } else {\n                    cacheUsed = false\n                    // Fetch without populating the cache in the case of an error.\n                    observabilityScope.emit(\n                        warning: \"skipping cache due to an error\",\n                        underlyingError: error\n                    )\n                    // it is possible that we already created the directory from failed attempts, so clear leftover data if present.\n                    try? self.fileSystem.removeFileTree(repositoryPath)\n                    try await self.provider.fetch(repository: handle.repository, to: repositoryPath, progressHandler: updateFetchProgress(progress:))\n                }\n            }\n        } else {\n            // it is possible that we already created the directory from failed attempts, so clear leftover data if present.\n            try? self.fileSystem.removeFileTree(repositoryPath)\n            // fetch without populating the cache when no `cachePath` is set.\n            try await self.provider.fetch(repository: handle.repository, to: repositoryPath, progressHandler: updateFetchProgress(progress:))\n        }\n        return FetchDetails(fromCache: cacheUsed, updatedCache: cacheUpdated)\n    }\n\n    private func fetchRequired(\n        repository: Repository,\n        updateStrategy: RepositoryUpdateStrategy\n    ) -> Bool {\n        switch updateStrategy {\n        case .never:\n            return false\n        case .always:\n            return true\n        case .ifNeeded(let revision):\n            return !repository.exists(revision: revision)\n        }\n    }\n\n    /// Open a working copy checkout at a path\n    public func openWorkingCopy(at path: Basics.AbsolutePath) async throws -> WorkingCheckout {\n        try await self.provider.openWorkingCopy(at: path)\n    }\n\n    /// Validate a working copy check is aligned with its repository setup\n    public func isValidWorkingCopy(_ workingCopy: WorkingCheckout, for repository: RepositorySpecifier) throws -> Bool {\n        let relativePath = try repository.storagePath()\n        let repositoryPath = self.path.appending(relativePath)\n        return workingCopy.isAlternateObjectStoreValid(expected: repositoryPath)\n    }\n\n    /// Open a repository from a handle.\n    private func open(_ handle: RepositoryHandle) async throws -> Repository {\n        try await self.provider.open(\n            repository: handle.repository,\n            at: self.path.appending(handle.subpath)\n        )\n    }\n\n    /// Create a working copy of the repository from a handle.\n    private func createWorkingCopy(\n        _ handle: RepositoryHandle,\n        at destinationPath: Basics.AbsolutePath,\n        editable: Bool\n    ) async throws -> WorkingCheckout {\n        try await self.provider.createWorkingCopy(\n            repository: handle.repository,\n            sourcePath: self.path.appending(handle.subpath),\n            at: destinationPath,\n            editable: editable)\n    }\n\n    /// Removes the repository.\n    public func remove(repository: RepositorySpecifier) throws {\n        let relativePath = try repository.storagePath()\n        let repositoryPath = self.path.appending(relativePath)\n        try self.fileSystem.removeFileTree(repositoryPath)\n    }\n\n    /// Returns true if the directory is valid git location.\n    public func isValidDirectory(_ directory: Basics.AbsolutePath) throws -> Bool {\n        try self.provider.isValidDirectory(directory)\n    }\n\n    /// Returns true if the directory is valid git location for the specified repository\n    public func isValidDirectory(_ directory: Basics.AbsolutePath, for repository: RepositorySpecifier) throws -> Bool {\n        try self.provider.isValidDirectory(directory, for: repository)\n    }\n\n    /// Reset the repository manager.\n    ///\n    /// Note: This also removes the cloned repositories from the disk.\n    public func reset(observabilityScope: ObservabilityScope) {\n        do {\n            try self.fileSystem.removeFileTree(self.path)\n        } catch {\n            observabilityScope.emit(\n                error: \"Error resetting repository manager at '\\(self.path)'\",\n                underlyingError: error\n            )\n        }\n    }\n\n    /// Sets up the cache directories if they don't already exist.\n    private func initializeCacheIfNeeded(cachePath: Basics.AbsolutePath) throws {\n        // Create the supplied cache directory.\n        if !self.fileSystem.exists(cachePath) {\n            try self.fileSystem.createDirectory(cachePath, recursive: true)\n        }\n    }\n\n    /// Purges the cached repositories from the cache.\n    public func purgeCache(observabilityScope: ObservabilityScope) {\n        guard let cachePath else {\n            return\n        }\n\n        guard self.fileSystem.exists(cachePath) else {\n            return\n        }\n\n        observabilityScope.emit(info: \"Purging repository cache at '\\(cachePath)'\")\n\n        do {\n            try self.fileSystem.withLock(on: cachePath, type: .exclusive) {\n                let cachedRepositories = try self.fileSystem.getDirectoryContents(cachePath)\n                for repoPath in cachedRepositories {\n                    let pathToDelete = cachePath.appending(component: repoPath)\n                    do {\n                        try self.fileSystem.removeFileTree(pathToDelete)\n                    } catch {\n                        observabilityScope.emit(\n                            error: \"Error removing cached repository at '\\(pathToDelete)'\",\n                            underlyingError: error\n                        )\n                    }\n                }\n            }\n        } catch {\n            observabilityScope.emit(\n                error: \"Error purging repository cache at '\\(cachePath)'\",\n                underlyingError: error\n            )\n        }\n    }\n}\n\nextension RepositoryManager {\n    /// Handle to a managed repository.\n    public struct RepositoryHandle: Sendable {\n        /// The manager this repository is owned by.\n        private unowned let manager: RepositoryManager\n\n        /// The repository specifier.\n        public let repository: RepositorySpecifier\n\n        /// The subpath of the repository within the manager.\n        ///\n        /// This is intentionally hidden from the clients so that the manager is\n        /// allowed to move repositories transparently.\n        fileprivate let subpath: Basics.RelativePath\n\n        /// Create a handle.\n        fileprivate init(manager: RepositoryManager, repository: RepositorySpecifier, subpath: Basics.RelativePath) {\n            self.manager = manager\n            self.repository = repository\n            self.subpath = subpath\n        }\n\n        /// Open the given repository.\n        public func open() async throws -> Repository {\n            return try await self.manager.open(self)\n        }\n\n        /// Create a working copy at on the local file system.\n        ///\n        /// - Parameters:\n        ///   - path: The path at which to create the working copy; it is\n        ///           expected to be non-existent when called.\n        ///\n        ///   - editable: The clone is expected to be edited by user.\n        public func createWorkingCopy(at path: Basics.AbsolutePath, editable: Bool) async throws -> WorkingCheckout {\n            return try await self.manager.createWorkingCopy(self, at: path, editable: editable)\n        }\n    }\n}\n\nextension RepositoryManager {\n    /// Additional information about a fetch\n    public struct FetchDetails: Equatable, Sendable {\n        /// Indicates if the repository was fetched from the cache or from the remote.\n        public let fromCache: Bool\n        /// Indicates whether the repository was already present in the cache and updated or if a clean fetch was performed.\n        public let updatedCache: Bool\n    }\n}\n\npublic enum RepositoryUpdateStrategy: Sendable {\n    case never\n    case always\n    case ifNeeded(revision: Revision)\n}\n\n/// Delegate to notify clients about actions being performed by RepositoryManager.\npublic protocol RepositoryManagerDelegate: Sendable {\n    /// Called when a repository is about to be fetched.\n    func willFetch(package: PackageIdentity, repository: RepositorySpecifier, details: RepositoryManager.FetchDetails)\n\n    /// Called every time the progress of a repository fetch operation updates.\n    func fetching(package: PackageIdentity, repository: RepositorySpecifier, objectsFetched: Int, totalObjectsToFetch: Int)\n\n    /// Called when a repository has finished fetching.\n    func didFetch(package: PackageIdentity, repository: RepositorySpecifier, result: Result<RepositoryManager.FetchDetails, Error>, duration: DispatchTimeInterval)\n\n    /// Called when a repository has started updating from its remote.\n    func willUpdate(package: PackageIdentity, repository: RepositorySpecifier)\n\n    /// Called when a repository has finished updating from its remote.\n    func didUpdate(package: PackageIdentity, repository: RepositorySpecifier, duration: DispatchTimeInterval)\n}\n\n/// Actor to proxy the delegate methods to the actual delegate, ensuring serialized delegate calls.\nfileprivate actor RepositoryManagerDelegateProxy {\n    private let delegate: RepositoryManagerDelegate\n\n    init?(_ delegate: RepositoryManagerDelegate?) {\n        guard let delegate else {\n            return nil\n        }\n        self.delegate = delegate\n    }\n\n    func willFetch(package: PackageIdentity, repository: RepositorySpecifier, details: RepositoryManager.FetchDetails) {\n        delegate.willFetch(package: package, repository: repository, details: details)\n    }\n\n    func fetching(package: PackageIdentity, repository: RepositorySpecifier, objectsFetched: Int, totalObjectsToFetch: Int) {\n        delegate.fetching(package: package, repository: repository, objectsFetched: objectsFetched, totalObjectsToFetch: totalObjectsToFetch)\n    }\n\n    func didFetch(package: PackageIdentity, repository: RepositorySpecifier, result: Result<RepositoryManager.FetchDetails, Error>, duration: DispatchTimeInterval) {\n        delegate.didFetch(package: package, repository: repository, result: result, duration: duration)\n    }\n\n    func willUpdate(package: PackageIdentity, repository: RepositorySpecifier) {\n        delegate.willUpdate(package: package, repository: repository)\n    }\n\n    func didUpdate(package: PackageIdentity, repository: RepositorySpecifier, duration: DispatchTimeInterval) {\n        delegate.didUpdate(package: package, repository: repository, duration: duration)\n    }\n}\n\n\nextension RepositoryManager.RepositoryHandle: CustomStringConvertible {\n    public var description: String {\n        return \"<\\(type(of: self)) subpath:\\(subpath)>\"\n    }\n}\n\nextension RepositorySpecifier {\n    // relative path where the repository should be stored\n    internal func storagePath() throws -> Basics.RelativePath {\n        return try RelativePath(validating: self.fileSystemIdentifier)\n    }\n\n    /// A unique identifier for this specifier.\n    ///\n    /// This identifier is suitable for use in a file system path, and\n    /// unique for each repository.\n    private var fileSystemIdentifier: String {\n        // canonicalize across similar locations (mainly for URLs)\n        // Use first 8 chars of a stable hash.\n        let suffix = self.canonicalLocation.description.sha256Checksum.prefix(8)\n        return \"\\(self.basename)-\\(suffix)\"\n    }\n}\n\nextension RepositorySpecifier {\n    fileprivate var canonicalLocation: String {\n        let canonicalPackageLocation: CanonicalPackageURL = .init(self.location.description)\n        return \"\\(canonicalPackageLocation.description)_\\(canonicalPackageLocation.scheme ?? \"\")\"\n    }\n}\n\nextension RepositorySpecifier {\n    fileprivate var isLocal: Bool {\n        switch self.location {\n        case .path:\n            return true\n        case .url:\n            return false\n        }\n    }\n}\n\n/// This used to rely on the SCNetworkReachability APIs on Darwin platforms and\n/// the string match elsewhere, however SCNetworkReachability has not been recommended\n/// to determine online/offline status. Instead do a simple string match on the error\n/// message indicating the host could not be resolved.\n/// This may falsely report offline status if the host is down, but this is effectively\n/// equivalent from the user's perspective.\nfileprivate func isOffline(_ error: Swift.Error) -> Bool {\n    return \"\\(error)\".contains(\"Could not resolve host\")\n}\n\n"
  },
  {
    "path": "Sources/SourceKitLSPAPI/BuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport TSCBasic\n\n// Ideally wouldn't expose these (it defeats the purpose of this module), but we should replace this entire API with\n// a BSP server, so this is good enough for now (and LSP is using all these types internally anyway).\nimport Basics\nimport Build\nimport PackageGraph\ninternal import PackageLoading\nimport PackageModel\nimport SPMBuildCore\n\npublic enum BuildDestination {\n    case host\n    case target\n}\n\npublic enum BuildTargetCompiler {\n    case swift\n    case clang\n}\n\n/// Information about a source file that belongs to a target.\npublic struct SourceItem {\n    /// The URL of the source file itself.\n    public let sourceFile: URL\n\n    /// If the file has a unique output path (eg. for clang files), the output paths. `nil` for eg. Swift targets,\n    /// which don't have unique output paths for each file.\n    public let outputFile: URL?\n}\n\npublic protocol BuildTarget {\n    /// Source files in the target\n    var sources: [SourceItem] { get }\n\n    /// Header files in the target\n    var headers: [URL] { get }\n\n    /// The resource files in the target.\n    var resources: [URL] { get }\n\n    /// Files in the target that were marked as ignored.\n    var ignored: [URL] { get }\n\n    /// Other kinds of files in the target.\n    var others: [URL] { get }\n\n    /// The name of the target. It should be possible to build a target by passing this name to `swift build --target`\n    var name: String { get }\n\n    /// The compiler that is responsible for building this target.\n    var compiler: BuildTargetCompiler { get }\n\n    var destination: BuildDestination { get }\n\n    /// Whether the target is part of the root package that the user opened or if it's part of a package dependency.\n    var isPartOfRootPackage: Bool { get }\n\n    var isTestTarget: Bool { get }\n\n    func compileArguments(for fileURL: URL) throws -> [String]\n}\n\nprivate struct WrappedClangTargetBuildDescription: BuildTarget {\n    private let description: ClangModuleBuildDescription\n    let isPartOfRootPackage: Bool\n    let isTestTarget: Bool\n\n    init(description: ClangModuleBuildDescription, isPartOfRootPackage: Bool) {\n        self.description = description\n        self.isPartOfRootPackage = isPartOfRootPackage\n        self.isTestTarget = description.isTestTarget\n    }\n\n    public var sources: [SourceItem] {\n        guard let compilePaths = try? description.compilePaths() else {\n            return []\n        }\n        return compilePaths.map {\n            SourceItem(sourceFile: $0.source.asURL, outputFile: $0.object.asURL)\n        }\n    }\n\n    public var headers: [URL] {\n        return description.clangTarget.headers.map(\\.asURL)\n    }\n\n    var resources: [URL] {\n        return description.resources.map(\\.path.asURL)\n    }\n\n    var ignored: [URL] {\n        return description.ignored.map(\\.asURL)\n    }\n\n    var others: [URL] {\n        var others = Set(description.others)\n        for pluginResult in description.buildToolPluginInvocationResults {\n            for buildCommand in pluginResult.buildCommands {\n                others.formUnion(buildCommand.inputFiles)\n            }\n        }\n        return others.map(\\.asURL)\n    }\n\n    public var name: String {\n        return description.clangTarget.name\n    }\n\n    var compiler: BuildTargetCompiler { .clang }\n\n\n    public var destination: BuildDestination {\n        return description.destination == .host ? .host : .target\n    }\n\n    public func compileArguments(for fileURL: URL) throws -> [String] {\n        let filePath = try resolveSymlinks(try Basics.AbsolutePath(validating: fileURL.path))\n        let commandLine = try description.emitCommandLine(for: filePath)\n        // First element on the command line is the compiler itself, not an argument.\n        return Array(commandLine.dropFirst())\n    }\n}\n\nprivate struct WrappedSwiftTargetBuildDescription: BuildTarget {\n    private let description: SwiftModuleBuildDescription\n    let isPartOfRootPackage: Bool\n    let isTestTarget: Bool\n\n    init(description: SwiftModuleBuildDescription, isPartOfRootPackage: Bool) {\n        self.description = description\n        self.isPartOfRootPackage = isPartOfRootPackage\n        self.isTestTarget = description.isTestTarget\n    }\n\n    public var name: String {\n        return description.target.name\n    }\n\n    var compiler: BuildTargetCompiler { .swift }\n\n    public var destination: BuildDestination {\n        return description.destination == .host ? .host : .target\n    }\n\n    var sources: [SourceItem] {\n        return description.sources.map {\n            return SourceItem(sourceFile: $0.asURL, outputFile: nil)\n        }\n    }\n\n    var headers: [URL] { [] }\n\n    var resources: [URL] {\n        return description.resources.map(\\.path.asURL)\n    }\n\n    var ignored: [URL] {\n        return description.ignored.map(\\.asURL)\n    }\n\n    var others: [URL] {\n        var others = Set(description.others)\n        for pluginResult in description.buildToolPluginInvocationResults {\n            for buildCommand in pluginResult.buildCommands {\n                others.formUnion(buildCommand.inputFiles)\n            }\n        }\n        return others.map(\\.asURL)\n    }\n\n    var outputPaths: [URL] {\n        get throws {\n            struct NotSupportedError: Error, CustomStringConvertible {\n                var description: String { \"Getting output paths for a Swift target is not supported\" }\n            }\n            throw NotSupportedError()\n        }\n    }\n\n    func compileArguments(for fileURL: URL) throws -> [String] {\n        // Note: we ignore the `fileURL` here as the expectation is that we get a command line for the entire target\n        // in case of Swift.\n        let commandLine = try description.emitCommandLine(scanInvocation: false, writeOutputFileMap: false)\n        // First element on the command line is the compiler itself, not an argument.\n        return Array(commandLine.dropFirst())\n    }\n}\n\npublic struct BuildDescription {\n    private let buildPlan: Build.BuildPlan\n\n    /// The inputs of the build plan so we don't need to re-compute them  on every call to\n    /// `fileAffectsSwiftOrClangBuildSettings`.\n    private let inputs: [Build.BuildPlan.Input]\n\n    /// Wrap an already constructed build plan.\n    public init(buildPlan: Build.BuildPlan) {\n        self.buildPlan = buildPlan\n        self.inputs = buildPlan.inputs\n    }\n\n    /// Construct a build description, compiling build tool plugins and generating their output when necessary.\n    public static func load(\n        destinationBuildParameters: BuildParameters,\n        toolsBuildParameters: BuildParameters,\n        packageGraph: ModulesGraph,\n        pluginConfiguration: PluginConfiguration,\n        traitConfiguration: TraitConfiguration,\n        disableSandbox: Bool,\n        scratchDirectory: URL,\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> (description: BuildDescription, errors: String) {\n        let bufferedOutput = BufferedOutputByteStream()\n        let threadSafeOutput = ThreadSafeOutputByteStream(bufferedOutput)\n\n        // This is quite an abuse of `BuildOperation`, building plugins should really be refactored out of it. Though\n        // even better would be to have a BSP server that handles both preparing and getting settings.\n        // https://github.com/swiftlang/swift-package-manager/issues/8287\n        let operation = BuildOperation(\n            productsBuildParameters: destinationBuildParameters,\n            toolsBuildParameters: toolsBuildParameters,\n            cacheBuildManifest: true,\n            packageGraphLoader: { packageGraph },\n            pluginConfiguration: pluginConfiguration,\n            scratchDirectory: try Basics.AbsolutePath(validating: scratchDirectory.path),\n            traitConfiguration: traitConfiguration,\n            additionalFileRules: FileRuleDescription.swiftpmFileTypes,\n            pkgConfigDirectories: [],\n            outputStream: threadSafeOutput,\n            logLevel: .error,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            delegate: nil\n        )\n\n        let plan = try await operation.generatePlan()\n        return (BuildDescription(buildPlan: plan), bufferedOutput.bytes.description)\n    }\n\n    func getBuildTarget(\n        for module: ResolvedModule,\n        destination: BuildParameters.Destination\n    ) -> BuildTarget? {\n        if let description = self.buildPlan.description(for: module, context: destination) {\n            let modulesGraph = self.buildPlan.graph\n            switch description {\n            case .clang(let description):\n                return WrappedClangTargetBuildDescription(\n                    description: description,\n                    isPartOfRootPackage: modulesGraph.rootPackages.map(\\.id).contains(description.package.id)\n                )\n            case .swift(let description):\n                return WrappedSwiftTargetBuildDescription(\n                    description: description,\n                    isPartOfRootPackage: modulesGraph.rootPackages.map(\\.id).contains(description.package.id)\n                )\n            }\n        } else {\n            if module.type == .plugin, let package = self.buildPlan.graph.package(for: module) {\n                let modulesGraph = self.buildPlan.graph\n                return PluginTargetBuildDescription(\n                    target: module,\n                    toolsVersion: package.manifest.toolsVersion,\n                    toolchain: buildPlan.toolsBuildParameters.toolchain,\n                    isPartOfRootPackage: modulesGraph.rootPackages.map(\\.id).contains(package.id)\n                )\n            }\n            return nil\n        }\n    }\n\n    public func traverseModules(\n        callback: (any BuildTarget, _ parent: (any BuildTarget)?) -> Void\n    ) {\n        self.buildPlan.traverseModules { module, parent in\n            let parentDescription: (any BuildTarget)? = if let parent {\n                getBuildTarget(for: parent.0, destination: parent.1)\n            } else {\n                nil\n            }\n\n            if let description = getBuildTarget(for: module.0, destination: module.1) {\n                callback(description, parentDescription)\n            }\n        }\n    }\n\n    /// Returns `true` if the file at the given path might influence build settings for a `swiftc` or `clang` invocation\n    /// generated by SwiftPM.\n    public func fileAffectsSwiftOrClangBuildSettings(_ url: URL) -> Bool {\n        guard let filePath = try? Basics.AbsolutePath(validating: url.path) else {\n            return false\n        }\n\n        for input in self.inputs {\n            switch input {\n            case .directoryStructure(let path):\n                if path.isAncestor(of: filePath) {\n                    return true\n                }\n            case .file(let path):\n                if filePath == path {\n                    return true\n                }\n            }\n        }\n        return false\n    }\n}\n"
  },
  {
    "path": "Sources/SourceKitLSPAPI/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SourceKitLSPAPI STATIC\n  BuildDescription.swift\n  PluginTargetBuildDescription.swift)\ntarget_link_libraries(SourceKitLSPAPI PUBLIC\n  Basics\n  Build\n  PackageGraph\n  SPMBuildCore)\ntarget_link_libraries(SourceKitLSPAPI PRIVATE\n  PackageLoading\n  PackageModel)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(SourceKitLSPAPI PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS SourceKitLSPAPI)\n"
  },
  {
    "path": "Sources/SourceKitLSPAPI/PluginTargetBuildDescription.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport Basics\nimport PackageGraph\ninternal import PackageLoading\nimport PackageModel\n\nstruct PluginTargetBuildDescription: BuildTarget {\n    private let target: ResolvedModule\n    private let toolsVersion: ToolsVersion\n    private let toolchain: any Toolchain\n    let isPartOfRootPackage: Bool\n    var isTestTarget: Bool { false }\n\n    init(target: ResolvedModule, toolsVersion: ToolsVersion, toolchain: any Toolchain, isPartOfRootPackage: Bool) {\n        assert(target.type == .plugin)\n        self.target = target\n        self.toolsVersion = toolsVersion\n        self.toolchain = toolchain\n        self.isPartOfRootPackage = isPartOfRootPackage\n    }\n\n    var sources: [SourceItem] {\n        return target.sources.paths.map {\n          SourceItem(sourceFile: $0.asURL, outputFile: nil)\n        }\n    }\n\n    var headers: [URL] { [] }\n\n    var resources: [URL] {\n        return target.underlying.resources.map(\\.path.asURL)\n    }\n\n    var ignored: [URL] {\n        return target.underlying.ignored.map(\\.asURL)\n    }\n\n    var others: [URL] {\n        return target.underlying.others.map(\\.asURL)\n    }\n\n    var name: String {\n        return target.name\n    }\n\n    var compiler: BuildTargetCompiler { .swift }\n\n    var destination: BuildDestination {\n        // Plugins are always built for the host.\n        .host\n    }\n\n    var outputPaths: [URL] {\n        get throws {\n            struct NotSupportedError: Error, CustomStringConvertible {\n                var description: String { \"Getting output paths for a plugin target is not supported\" }\n            }\n            throw NotSupportedError()\n        }\n    }\n\n    func compileArguments(for fileURL: URL) throws -> [String] {\n        // FIXME: This is very odd and we should clean this up by merging `ManifestLoader` and `DefaultPluginScriptRunner` again.\n        var args = ManifestLoader.interpreterFlags(for: self.toolsVersion, toolchain: toolchain)\n        // Note: we ignore the `fileURL` here as the expectation is that we get a commandline for the entire target in case of Swift. Plugins are always assumed to only consist of Swift files.\n        args += try sources.map { try $0.sourceFile.filePath }\n        return args\n    }\n}\n\nfileprivate enum FilePathError: Error, CustomStringConvertible {\n  case noFileSystemRepresentation(URL)\n  case noFileURL(URL)\n\n  var description: String {\n    switch self {\n    case .noFileSystemRepresentation(let url):\n      return \"\\(url.description) cannot be represented as a file system path\"\n    case .noFileURL(let url):\n      return \"\\(url.description) is not a file URL\"\n    }\n  }\n}\n\nfileprivate extension URL {\n  /// Assuming that this is a file URL, the path with which the file system refers to the file. This is similar to\n  /// `path` but has two differences:\n  /// - It uses backslashes as the path separator on Windows instead of forward slashes\n  /// - It throws an error when called on a non-file URL.\n  ///\n  /// `filePath` should generally be preferred over `path` when dealing with file URLs.\n  var filePath: String {\n    get throws {\n      guard self.isFileURL else {\n        throw FilePathError.noFileURL(self)\n      }\n      return try self.withUnsafeFileSystemRepresentation { buffer in\n        guard let buffer else {\n          throw FilePathError.noFileSystemRepresentation(self)\n        }\n        return String(cString: buffer)\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/BuildSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SPMBuildCore\nimport PackageModel\n\nextension BuildConfiguration {\n    public var swiftbuildName: String {\n        switch self {\n        case .debug: \"Debug\"\n        case .release: \"Release\"\n        }\n    }\n}\n\nextension BuildSubset {\n    var pifTargetName: String {\n        switch self {\n        case .product(let name, _):\n            PackagePIFBuilder.targetName(forProductName: name)\n        case .target(let name, _):\n            name\n        case .allExcludingTests:\n            PIFBuilder.allExcludingTestsTargetName\n        case .allIncludingTests:\n            PIFBuilder.allIncludingTestsTargetName\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SwiftBuildSupport\n  BuildSystem.swift\n  Diagnostics+Extensions.swift\n  DotPIFSerializer.swift\n  PackagePIFBuilder.swift\n  PackagePIFBuilder+Helpers.swift\n  PackagePIFBuilder+Plugins.swift\n  PackagePIFProjectBuilder.swift\n  PackagePIFProjectBuilder+Modules.swift\n  PackagePIFProjectBuilder+Products.swift\n  PIF.swift\n  PIFBuilder.swift\n  PluginConfiguration.swift\n  SwiftBuildSystem.swift\n  SwiftBuildSystemMessageHandler.swift)\ntarget_link_libraries(SwiftBuildSupport PUBLIC\n  Basics\n  Build\n  DriverSupport\n  TSCBasic\n  TSCUtility\n  PackageGraph\n  SwiftBuild::SwiftBuild\n  SwiftBuild::SWBBuildService\n)\n\nset_target_properties(SwiftBuildSupport PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS SwiftBuildSupport\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS SwiftBuildSupport)\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/Diagnostics+Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nextension Basics.Diagnostic {\n    package static var swiftBackDeployWarning: Self {\n        .warning(\n            \"\"\"\n            Swift compiler no longer supports statically linking the Swift libraries. They're included in the OS by \\\n            default starting with macOS Mojave 10.14.4 beta 3. For macOS Mojave 10.14.3 and earlier, there's an \\\n            optional \"Swift 5 Runtime Support for Command Line Tools\" package that can be downloaded from \\\"More Downloads\\\" \\\n            for Apple Developers at https://developer.apple.com/download/more/\n            \"\"\"\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/DotPIFSerializer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport protocol TSCBasic.OutputByteStream\n\nimport SwiftBuild\n\n/// Serializes the specified PIF as a **Graphviz** directed graph.\n///\n/// * [DOT command line](https://graphviz.org/doc/info/command.html)\n/// * [DOT language specs](https://graphviz.org/doc/info/lang.html)\nfunc writePIF(_ workspace: PIF.Workspace, toDOT outputStream: OutputByteStream) {\n    var graph = DotPIFSerializer()\n\n    graph.node(\n        id: workspace.id,\n        label: \"\"\"\n            <workspace>\n            \\(workspace.id)\n            \"\"\",\n        shape: \"box3d\",\n        color: .black,\n        fontsize: 7\n    )\n\n    for project in workspace.projects.map(\\.underlying) {\n        graph.edge(from: workspace.id, to: project.id, color: .lightskyblue)\n        graph.node(\n            id: project.id,\n            label: \"\"\"\n                <project>\n                \\(project.id)\n                \"\"\",\n            shape: \"box3d\",\n            color: .gray56,\n            fontsize: 7\n        )\n\n        for target in project.targets {\n            graph.edge(from: project.id, to: target.id, color: .lightskyblue)\n\n            switch target {\n            case .target(let target):\n                graph.node(\n                    id: target.id,\n                    label: \"\"\"\n                        <target>\n                        \\(target.id)\n                        name: \\(target.name)\n                        product type: \\(target.productType)\n                        \\(target.buildPhases.summary)\n                        \"\"\",\n                    shape: \"box\",\n                    color: .gray88,\n                    fontsize: 5\n                )\n\n            case .aggregate:\n                graph.node(\n                    id: target.id,\n                    label: \"\"\"\n                        <aggregate target>\n                        \\(target.id)\n                        \"\"\",\n                    shape: \"folder\",\n                    color: .gray88,\n                    fontsize: 5,\n                    style: \"bold\"\n                )\n            }\n\n            for targetDependency in target.common.dependencies {\n                let linked = target.isLinkedAgainst(dependencyId: targetDependency.targetId)\n                graph.edge(from: target.id, to: targetDependency.targetId, color: .gray40, style: linked ? \"filled\" : \"dotted\")\n            }\n        }\n    }\n\n    graph.write(to: outputStream)\n}\n\nfileprivate struct DotPIFSerializer {\n    private var objects: [String] = []\n\n    mutating func write(to outputStream: OutputByteStream) {\n        func write(_ object: String) { outputStream.write(\"\\(object)\\n\") }\n\n        write(\"digraph PIF {\")\n        write(\"  dpi=400;\") // i.e., MacBook Pro 16\" is 226 pixels per inch (3072 x 1920).\n        for object in objects {\n            write(\"  \\(object);\")\n        }\n        write(\"}\")\n    }\n\n    mutating func node(\n        id: PIF.GUID,\n        label: String? = nil,\n        shape: String? = nil,\n        color: Color? = nil,\n        fontname: String? = \"SF Mono Light\",\n        fontsize: Int? = nil,\n        style: String? = nil,\n        margin: Int? = nil\n    ) {\n        var attributes: [String] = []\n\n        if let label { attributes.append(\"label=\\(label.quote)\") }\n        if let shape { attributes.append(\"shape=\\(shape)\") }\n        if let color { attributes.append(\"color=\\(color)\") }\n\n        if let fontname { attributes.append(\"fontname=\\(fontname.quote)\") }\n        if let fontsize { attributes.append(\"fontsize=\\(fontsize)\") }\n\n        if let style { attributes.append(\"style=\\(style)\") }\n        if let margin { attributes.append(\"margin=\\(margin)\") }\n\n        var node = \"\\(id.quote)\"\n        if !attributes.isEmpty {\n            let attributesList = attributes.joined(separator: \", \")\n            node += \" [\\(attributesList)]\"\n        }\n        objects.append(node)\n    }\n\n    mutating func edge(\n        from left: PIF.GUID,\n        to right: PIF.GUID,\n        color: Color? = nil,\n        style: String? = nil\n    ) {\n        var attributes: [String] = []\n\n        if let color { attributes.append(\"color=\\(color)\") }\n        if let style { attributes.append(\"style=\\(style)\") }\n\n        var edge = \"\\(left.quote) -> \\(right.quote)\"\n        if !attributes.isEmpty {\n            let attributesList = attributes.joined(separator: \", \")\n            edge += \" [\\(attributesList)]\"\n        }\n        objects.append(edge)\n    }\n\n    /// Graphviz  default color scheme is **X11**:\n    /// * https://graphviz.org/doc/info/colors.html\n    enum Color: String {\n        case black\n        case gray\n        case gray40\n        case gray56\n        case gray88\n        case lightskyblue\n    }\n}\n\n// MARK: - Helpers\n\nfileprivate extension ProjectModel.BaseTarget {\n    func isLinkedAgainst(dependencyId: ProjectModel.GUID) -> Bool {\n        for buildPhase in self.common.buildPhases {\n            switch buildPhase {\n            case .frameworks(let frameworksPhase):\n                for buildFile in frameworksPhase.files {\n                    switch buildFile.ref {\n                    case .reference(let id):\n                        if dependencyId == id { return true }\n                    case .targetProduct(let id):\n                        if dependencyId == id { return true }\n                    }\n                }\n\n            case .sources, .shellScript, .headers, .copyFiles, .copyBundleResources:\n                break\n            }\n        }\n        return false\n    }\n}\n\nfileprivate extension [ProjectModel.BuildPhase] {\n    var summary: String {\n        var phases: [String] = []\n\n        for buildPhase in self {\n            switch buildPhase {\n            case .sources(let sourcesPhase):\n                var sources = \"sources: \"\n                if sourcesPhase.files.count == 1 {\n                    sources += \"1 source file\"\n                } else {\n                    sources += \"\\(sourcesPhase.files.count) source files\"\n                }\n                phases.append(sources)\n\n            case .frameworks(let frameworksPhase):\n                var frameworks = \"frameworks: \"\n                if frameworksPhase.files.count == 1 {\n                    frameworks += \"1 linked target\"\n                } else {\n                    frameworks += \"\\(frameworksPhase.files.count) linked targets\"\n                }\n                phases.append(frameworks)\n\n            case .shellScript:\n                phases.append(\"shellScript: 1 shell script\")\n\n            case .headers, .copyFiles, .copyBundleResources:\n                break\n            }\n        }\n\n        guard !phases.isEmpty else { return \"\" }\n        return phases.joined(separator: \"\\n\")\n    }\n}\n\nfileprivate extension PIF.GUID {\n    var quote: String {\n        self.value.quote\n    }\n}\n\nfileprivate extension String {\n    /// Quote the name and escape the quotes and backslashes.\n    var quote: String {\n        \"\\\"\" + self\n            .replacing(\"\\\"\", with: \"\\\\\\\"\")\n            .replacing(\"\\\\\", with: \"\\\\\\\\\")\n            .replacing(\"\\n\", with: \"\\\\n\") +\n        \"\\\"\"\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PIF.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport OrderedCollections\nimport PackageModel\n\nimport struct TSCBasic.ByteString\n\nimport enum SwiftBuild.ProjectModel\n\n/// The Project Interchange Format (PIF) is a structured representation of the\n/// project model created by clients to send to SwiftBuild.\n///\n/// The PIF is a representation of the project model describing the static\n/// objects which contribute to building products from the project, independent\n/// of \"how\" the user has chosen to build those products in any particular\n/// build. This information can be cached by SwiftBuild between builds (even\n/// between builds which use different schemes or configurations), and can be\n/// incrementally updated by clients when something changes.\npublic enum PIF {\n    /// The type used for identifying PIF objects.\n    public typealias GUID = ProjectModel.GUID\n    \n    /// The top-level PIF object.\n    public struct TopLevelObject: Encodable {\n        public let workspace: PIF.Workspace\n        \n        public init(workspace: PIF.Workspace) {\n            self.workspace = workspace\n        }\n        \n        public func encode(to encoder: Encoder) throws {\n            var container = encoder.unkeyedContainer()\n            \n            // Encode the workspace.\n            try container.encode(workspace)\n            \n            // Encode the projects and their targets.\n            for project in workspace.projects {\n                try container.encode(project)\n                let targets = project.underlying.targets\n                \n                for target in targets where !target.id.hasSuffix(.dynamic) {\n                    try container.encode(Target(wrapping: target))\n                }\n                \n                // Add *dynamic variants* at the end just to have a clear split from other targets.\n                for target in targets where target.id.hasSuffix(.dynamic) {\n                    try container.encode(Target(wrapping: target))\n                }\n            }\n        }\n    }\n    \n    /// Represents a high-level PIF object.\n    ///\n    /// For instance, a JSON serialized *workspace* might look like this:\n    /// ```json\n    /// {\n    ///     \"type\" : \"workspace\",\n    ///     \"signature\" : \"22e9436958aec481799\",\n    ///     \"contents\" : {\n    ///         \"guid\" : \"Workspace:/Users/foo/BarPackage\",\n    ///         \"name\" : \"BarPackage\",\n    ///         \"path\" : \"/Users/foo/BarPackage\",\n    ///         \"projects\" : [\n    ///             \"70a588f37dcfcddbc1f\",\n    ///             \"c1d9cb257bd42cafbb8\"\n    ///         ]\n    ///     }\n    /// }\n    /// ```\n    public class HighLevelObject: Codable {\n        class var type: String {\n            fatalError(\"\\(self) missing implementation\")\n        }\n        \n        let type: String\n        \n        fileprivate init() {\n            type = Self.type\n        }\n        \n        fileprivate enum CodingKeys: CodingKey {\n            case type\n            case signature, contents // Used by subclasses.\n        }\n        \n        public func encode(to encoder: Encoder) throws {\n            var superContainer = encoder.container(keyedBy: CodingKeys.self)\n            try superContainer.encode(type, forKey: .type)\n        }\n        \n        required public init(from decoder: Decoder) throws {\n            let superContainer = try decoder.container(keyedBy: CodingKeys.self)\n            self.type = try superContainer.decode(String.self, forKey: .type)\n            \n            guard self.type == Self.type else {\n                throw InternalError(\"Expected same type for high-level object: \\(self.type)\")\n            }\n        }\n    }\n    \n    /// The high-level PIF *workspace* object.\n    public final class Workspace: HighLevelObject {\n        override class var type: String { \"workspace\" }\n        \n        public let id: GUID\n        public var name: String\n        public var path: AbsolutePath\n        public var projects: [Project]\n        var signature: String?\n\n        public init(id: GUID, name: String, path: AbsolutePath, projects: [ProjectModel.Project]) {\n            precondition(!id.value.isEmpty)\n            precondition(!name.isEmpty)\n            precondition(Set(projects.map(\\.id)).count == projects.count)\n            \n            self.id = id\n            self.name = name\n            self.path = path\n            self.projects = projects.map { Project(wrapping: $0) }\n            super.init()\n        }\n        \n        private enum CodingKeys: CodingKey {\n            case guid, name, path, projects\n        }\n        \n        public override func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            \n            var superContainer = encoder.container(keyedBy: HighLevelObject.CodingKeys.self)\n            var contents = superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .contents)\n            \n            try contents.encode(\"\\(id)\", forKey: .guid)\n            try contents.encode(name, forKey: .name)\n            try contents.encode(path, forKey: .path)\n            try contents.encode(projects.map(\\.signature), forKey: .projects)\n            \n            if encoder.userInfo.keys.contains(.encodeForSwiftBuild) {\n                guard let signature else {\n                    throw InternalError(\"Expected to have workspace *signature* when encoding for SwiftBuild\")\n                }\n                try superContainer.encode(signature, forKey: .signature)\n            }\n        }\n        \n        // FIXME: Delete this (https://github.com/swiftlang/swift-package-manager/issues/8552).\n        public required init(from decoder: Decoder) throws {\n            let superContainer = try decoder.container(keyedBy: HighLevelObject.CodingKeys.self)\n            let contents = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .contents)\n            \n            self.id = try contents.decode(GUID.self, forKey: .guid)\n            self.name = try contents.decode(String.self, forKey: .name)\n            self.path = try contents.decode(AbsolutePath.self, forKey: .path)\n            self.projects = try contents.decode([Project].self, forKey: .projects)\n            \n            try super.init(from: decoder)\n        }\n    }\n    \n    /// A high-level PIF *project* object.\n    public final class Project: HighLevelObject {\n        override class var type: String { \"project\" }\n        \n        public var underlying: ProjectModel.Project\n        var signature: String?\n        var id: ProjectModel.GUID { underlying.id }\n        \n        public init(wrapping underlying: ProjectModel.Project) {\n            precondition(!underlying.name.isEmpty)\n            precondition(!underlying.id.value.isEmpty)\n            precondition(!underlying.path.isEmpty)\n            precondition(!underlying.projectDir.isEmpty)\n            \n            precondition(Set(underlying.targets.map(\\.id)).count == underlying.targets.count)\n            precondition(Set(underlying.buildConfigs.map(\\.id)).count == underlying.buildConfigs.count)\n            \n            self.underlying = underlying\n            super.init()\n        }\n        \n        public override func encode(to encoder: any Encoder) throws {\n            try super.encode(to: encoder)\n            var superContainer = encoder.container(keyedBy: HighLevelObject.CodingKeys.self)\n            try superContainer.encode(underlying, forKey: .contents)\n\n            if encoder.userInfo.keys.contains(.encodeForSwiftBuild) {\n                guard let signature else {\n                    throw InternalError(\"Expected to have project *signature* when encoding for SwiftBuild\")\n                }\n                try superContainer.encode(signature, forKey: .signature)\n            }\n        }\n        \n        // FIXME: Delete this (https://github.com/swiftlang/swift-package-manager/issues/8552).\n        public required init(from decoder: Decoder) throws {\n            let superContainer = try decoder.container(keyedBy: HighLevelObject.CodingKeys.self)\n            self.underlying = try superContainer.decode(ProjectModel.Project.self, forKey: .contents)\n            \n            try super.init(from: decoder)\n        }\n    }\n    \n    /// A high-level PIF *target* object.\n    private final class Target: HighLevelObject {\n        override class var type: String { \"target\" }\n        \n        public var underlying: ProjectModel.BaseTarget\n        var id: ProjectModel.GUID { underlying.id }\n        \n        public init(wrapping underlying: ProjectModel.BaseTarget) {\n            precondition(!underlying.id.value.isEmpty)\n            precondition(!underlying.common.name.isEmpty)\n            \n            self.underlying = underlying\n            super.init()\n        }\n        \n        public override func encode(to encoder: any Encoder) throws {\n            try super.encode(to: encoder)\n            var superContainer = encoder.container(keyedBy: HighLevelObject.CodingKeys.self)\n            try superContainer.encode(underlying, forKey: .contents)\n\n            if encoder.userInfo.keys.contains(.encodeForSwiftBuild) {\n                guard let signature = underlying.common.signature else {\n                    throw InternalError(\"Expected to have target *signature* when encoding for SwiftBuild\")\n                }\n                try superContainer.encode(signature, forKey: .signature)\n            }\n        }\n        \n        public required init(from decoder: Decoder) throws {\n            // FIXME: Remove all support for decoding PIF objects in SwiftBuildSupport?\n            // (https://github.com/swiftlang/swift-package-manager/issues/8552)\n            fatalError(\"Decoding not implemented\")\n            /*\n            let superContainer = try decoder.container(keyedBy: HighLevelObject.CodingKeys.self)\n            self.underlying = try superContainer.decode(ProjectModel.BaseTarget.self, forKey: .contents)\n            \n            try super.init(from: decoder)\n            */\n        }\n    }\n}\n\n// MARK: - PIF Signature Support\n\nextension CodingUserInfoKey {\n    /// Perform the encoding for SwiftBuild consumption.\n    public static let encodeForSwiftBuild: CodingUserInfoKey = CodingUserInfoKey(rawValue: \"encodeForXCBuild\")!\n}\n\nextension PIF {\n    /// Add signature to workspace and its high-level subobjects.\n    static func sign(workspace: PIF.Workspace) throws {\n        let encoder = JSONEncoder.makeWithDefaults()\n\n        func signature(of obj: some Encodable) throws -> String {\n            let signatureContent = try encoder.encode(obj)\n            let signatureBytes = ByteString(signatureContent)\n            let signature = signatureBytes.sha256Checksum\n            return signature\n        }\n\n        for project in workspace.projects {\n            for targetIndex in project.underlying.targets.indices {\n                let targetSignature = try signature(of: project.underlying.targets[targetIndex])\n                project.underlying.targets[targetIndex].common.signature = targetSignature\n            }\n            project.signature = try signature(of: project)\n        }\n        workspace.signature = try signature(of: workspace)\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PIFBuilder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal) import Basics\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport TSCUtility\n\n@_spi(SwiftPMInternal)\nimport SPMBuildCore\n\nimport func TSCBasic.topologicalSort\nimport var TSCBasic.stdoutStream\n\nimport enum SwiftBuild.ProjectModel\n\nfileprivate func memoize<T>(to cache: inout T?, build: () async throws -> T) async rethrows -> T {\n    if let value = cache {\n        return value\n    } else {\n        let value = try await build()\n        cache = value\n        return value\n    }\n}\n\n/// The parameters required by `PIFBuilder`.\npackage struct PIFBuilderParameters {\n    /// Whether the toolchain supports `-package-name` option.\n    let isPackageAccessModifierSupported: Bool\n\n    /// Whether or not build for testability is enabled.\n    let enableTestability: Bool\n\n    /// Whether to create dylibs for dynamic library products.\n    let shouldCreateDylibForDynamicProducts: Bool\n\n    /// Eagerly materialize static archive products.\n    let materializeStaticArchiveProductsForRootPackages: Bool\n\n    /// Create dynamic library variants for automatic library products.\n    let createDynamicVariantsForLibraryProducts: Bool\n\n    /// The path to the library directory of the active toolchain.\n    let toolchainLibDir: AbsolutePath\n\n    /// An array of paths to search for pkg-config `.pc` files.\n    let pkgConfigDirectories: [AbsolutePath]\n\n    /// The Swift language versions supported by the SwiftBuild being used for the build.\n    let supportedSwiftVersions: [SwiftLanguageVersion]\n\n    /// The plugin script runner that will compile and run plugins.\n    let pluginScriptRunner: PluginScriptRunner\n\n    /// Disable the sandbox for the custom tasks\n    let disableSandbox: Bool\n\n    /// The working directory where the plugins should produce their results\n    let pluginWorkingDirectory: AbsolutePath\n\n    /// Additional rules for including a source or resource file in a target\n    let additionalFileRules: [FileRuleDescription]\n\n    /// Add rpaths which allow loading libraries adjacent to the current image at runtime. This is desirable\n    /// when launching build products from the build directory, but should often be disabled when deploying\n    /// the build products to a different location.\n    let addLocalRpaths: Bool\n\n    package init(isPackageAccessModifierSupported: Bool, enableTestability: Bool, shouldCreateDylibForDynamicProducts: Bool, materializeStaticArchiveProductsForRootPackages: Bool, createDynamicVariantsForLibraryProducts: Bool, toolchainLibDir: AbsolutePath, pkgConfigDirectories: [AbsolutePath], supportedSwiftVersions: [SwiftLanguageVersion], pluginScriptRunner: PluginScriptRunner, disableSandbox: Bool, pluginWorkingDirectory: AbsolutePath, additionalFileRules: [FileRuleDescription], addLocalRPaths: Bool) {\n        self.isPackageAccessModifierSupported = isPackageAccessModifierSupported\n        self.enableTestability = enableTestability\n        self.shouldCreateDylibForDynamicProducts = shouldCreateDylibForDynamicProducts\n        self.materializeStaticArchiveProductsForRootPackages = materializeStaticArchiveProductsForRootPackages\n        self.createDynamicVariantsForLibraryProducts = createDynamicVariantsForLibraryProducts\n        self.toolchainLibDir = toolchainLibDir\n        self.pkgConfigDirectories = pkgConfigDirectories\n        self.supportedSwiftVersions = supportedSwiftVersions\n        self.pluginScriptRunner = pluginScriptRunner\n        self.disableSandbox = disableSandbox\n        self.pluginWorkingDirectory = pluginWorkingDirectory\n        self.additionalFileRules = additionalFileRules\n        self.addLocalRpaths = addLocalRPaths\n    }\n}\n\n/// PIF object builder for a package graph.\npublic final class PIFBuilder {\n    /// Name of the PIF target aggregating all targets (*excluding* tests).\n    public static let allExcludingTestsTargetName = \"AllExcludingTests\"\n\n    /// Name of the PIF target aggregating all targets (*including* tests).\n    public static let allIncludingTestsTargetName = \"AllIncludingTests\"\n\n    /// The package graph to build from.\n    let graph: ModulesGraph\n\n    /// The parameters used to configure the PIF.\n    let parameters: PIFBuilderParameters\n\n    /// The ObservabilityScope to emit diagnostics to.\n    let observabilityScope: ObservabilityScope\n\n    /// The file system to read from.\n    let fileSystem: FileSystem\n\n    /// Configuration for building and invoking plugins.\n    private let pluginConfiguration: PluginConfiguration\n\n    /// Creates a `PIFBuilder` instance.\n    /// - Parameters:\n    ///   - graph: The package graph to build from.\n    ///   - parameters: The parameters used to configure the PIF.\n    ///   - fileSystem: The file system to read from.\n    ///   - observabilityScope: The ObservabilityScope to emit diagnostics to.\n    package init(\n        graph: ModulesGraph,\n        parameters: PIFBuilderParameters,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n    ) {\n        self.graph = graph\n        self.parameters = parameters\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope.makeChildScope(description: \"PIF Builder\")\n\n        self.pluginConfiguration = PluginConfiguration(\n            scriptRunner: parameters.pluginScriptRunner,\n            workDirectory: parameters.pluginWorkingDirectory,\n            disableSandbox: parameters.disableSandbox,\n        )\n    }\n\n    /// Generates the PIF representation.\n    /// - Parameters:\n    ///   - prettyPrint: Whether to return a formatted JSON.\n    ///   - preservePIFModelStructure: Whether to preserve model structure.\n    /// - Returns: The package graph in the JSON PIF format.\n    package func generatePIF(\n        prettyPrint: Bool = true,\n        preservePIFModelStructure: Bool = false,\n        printPIFManifestGraphviz: Bool = false,\n        buildParameters: BuildParameters\n    ) async throws -> String {\n        let encoder = prettyPrint ? JSONEncoder.makeWithDefaults() : JSONEncoder()\n\n        if !preservePIFModelStructure {\n            encoder.userInfo[.encodeForSwiftBuild] = true\n        }\n\n        let topLevelObject = try await self.constructPIF(buildParameters: buildParameters)\n\n        // Sign the PIF objects before encoding it for Swift Build.\n        try PIF.sign(workspace: topLevelObject.workspace)\n\n        let pifData = try encoder.encode(topLevelObject)\n        let pifString = String(decoding: pifData, as: UTF8.self)\n\n        if printPIFManifestGraphviz {\n            // Print dot graph to stdout.\n            writePIF(topLevelObject.workspace, toDOT: stdoutStream)\n            stdoutStream.flush()\n\n            // Abort the build process, ensuring we don't add\n            // further noise to stdout (and break `dot` graph parsing).\n            throw PIFGenerationError.printedPIFManifestGraphviz\n        }\n\n        return pifString\n    }\n\n    private var cachedPIF: PIF.TopLevelObject?\n\n    /// Compute the available build tools, and their destination build path for host for each plugin.\n    private func availableBuildPluginTools(\n        graph: ModulesGraph,\n        buildParameters: BuildParameters,\n        pluginsPerModule: [ResolvedModule.ID: [ResolvedModule]],\n        hostTriple: Basics.Triple\n    ) async throws -> [ResolvedModule.ID: [String: PluginTool]] {\n        var accessibleToolsPerPlugin: [ResolvedModule.ID: [String: PluginTool]] = [:]\n\n        for (_, plugins) in pluginsPerModule {\n            for plugin in plugins where accessibleToolsPerPlugin[plugin.id] == nil {\n                // Determine the tools to which this plugin has access, and create a name-to-path mapping from tool\n                // names to the corresponding paths. Built tools are assumed to be in the build tools directory.\n                let accessibleTools = try await plugin.preparePluginTools(\n                    fileSystem: fileSystem,\n                    environment: buildParameters.buildEnvironment,\n                    for: hostTriple\n                ) { name, path in\n                    return buildParameters.buildPath.appending(path)\n                }\n\n                accessibleToolsPerPlugin[plugin.id] = accessibleTools\n            }\n        }\n\n        return accessibleToolsPerPlugin\n    }\n\n    /// Constructs all `PackagePIFBuilder` objects used by the `constructPIF` function.\n    /// In particular, this is useful for unit testing the complex `PIFBuilder` class.\n    func makePIFBuilders(\n        buildParameters: BuildParameters\n    ) async throws -> [(ResolvedPackage, PackagePIFBuilder, any PackagePIFBuilder.BuildDelegate)] {\n        let pluginScriptRunner = self.parameters.pluginScriptRunner\n        let outputDir = self.parameters.pluginWorkingDirectory.appending(\"outputs\")\n\n        let pluginsPerModule = graph.pluginsPerModule(\n            satisfying: buildParameters.buildEnvironment // .buildEnvironment(for: .host)\n        )\n\n        let availablePluginTools = try await availableBuildPluginTools(\n            graph: graph,\n            buildParameters: buildParameters,\n            pluginsPerModule: pluginsPerModule,\n            hostTriple: try pluginScriptRunner.hostTriple\n        )\n\n        let sortedPackages = self.graph.packages\n            .sorted { $0.manifest.displayName < $1.manifest.displayName } // TODO: use identity instead?\n\n        var packagesAndBuilders: [(ResolvedPackage, PackagePIFBuilder, any PackagePIFBuilder.BuildDelegate)] = []\n\n        for package in sortedPackages {\n            var buildToolPluginResultsByTargetName: [String: [PackagePIFBuilder.BuildToolPluginInvocationResult]] = [:]\n\n            for module in package.modules {\n                // Apply each build tool plugin used by the target in order,\n                // creating a list of results (one for each plugin usage).\n                var buildToolPluginResults: [BuildToolPluginInvocationResult] = []\n                var buildCommands: [PackagePIFBuilder.CustomBuildCommand] = []\n                var prebuildCommands: [BuildToolPluginInvocationResult.PrebuildCommand] = []\n\n                for plugin in module.pluginDependencies(satisfying: buildParameters.buildEnvironment) {\n                    let pluginModule = plugin.underlying as! PluginModule\n\n                    // Determine the tools to which this plugin has access, and create a name-to-path mapping from tool\n                    // names to the corresponding paths. Built tools are assumed to be in the build tools directory.\n                    guard let accessibleTools = availablePluginTools[plugin.id] else {\n                        throw InternalError(\"No tools found for plugin \\(plugin.name)\")\n                    }\n\n                    // Assign a plugin working directory based on the package, target, and plugin.\n                    let pluginOutputDir = outputDir.appending(\n                        components: [\n                            package.identity.description,\n                            module.name,\n                            buildParameters.destination == .host ? \"tools\" : \"destination\",\n                            plugin.name,\n                        ]\n                    )\n\n                    // Determine the set of directories under which plugins are allowed to write.\n                    // We always include just the output directory, and for now there is no possibility\n                    // of opting into others.\n                    let writableDirectories = [outputDir]\n\n                    // Determine a set of further directories under which plugins are never allowed\n                    // to write, even if they are covered by other rules (such as being able to write\n                    // to the temporary directory).\n                    let readOnlyDirectories = [package.path]\n\n                    // In tools version 6.0 and newer, we vend the list of files generated by previous plugins.\n                    let pluginDerivedSources: Sources\n                    let pluginDerivedResources: [Resource]\n                    if package.manifest.toolsVersion >= .v6_0 {\n                        // Set up dummy observability because we don't want to emit diagnostics for this before the actual\n                        // build.\n                        let observability = ObservabilitySystem { _, _ in }\n                        // Compute the generated files based on all results we have computed so far.\n                        let pluginGeneratedFiles = ModulesGraph.computePluginGeneratedFiles(\n                            target: module,\n                            toolsVersion: package.manifest.toolsVersion,\n                            additionalFileRules: self.parameters.additionalFileRules,\n                            buildParameters: buildParameters,\n                            buildToolPluginInvocationResults: buildToolPluginResults,\n                            prebuildCommandResults: [],\n                            observabilityScope: observability.topScope\n                        )\n                        pluginDerivedSources = Sources(\n                                paths: pluginGeneratedFiles.sources.map(\\.self),\n                                root: buildParameters.dataPath\n                            )\n                        pluginDerivedResources = pluginGeneratedFiles.resources.values.map(\\.self)\n                    } else {\n                        pluginDerivedSources = .init(paths: [], root: package.path)\n                        pluginDerivedResources = []\n                    }\n\n                    let result = try await pluginModule.invoke(\n                        module: plugin,\n                        action: .createBuildToolCommands(\n                            package: package,\n                            target: module,\n                            pluginGeneratedSources: pluginDerivedSources.paths,\n                            pluginGeneratedResources: pluginDerivedResources.map(\\.path)\n                        ),\n                        buildEnvironment: buildParameters.buildEnvironment,\n                        workers: buildParameters.workers,\n                        scriptRunner: pluginScriptRunner,\n                        workingDirectory: package.path,\n                        outputDirectory: pluginOutputDir,\n                        toolSearchDirectories: [buildParameters.toolchain.swiftCompilerPath.parentDirectory],\n                        accessibleTools: accessibleTools,\n                        writableDirectories: writableDirectories,\n                        readOnlyDirectories: readOnlyDirectories,\n                        allowNetworkConnections: [],\n                        pkgConfigDirectories: self.parameters.pkgConfigDirectories,\n                        sdkRootPath: buildParameters.toolchain.sdkRootPath,\n                        fileSystem: fileSystem,\n                        modulesGraph: self.graph,\n                        observabilityScope: observabilityScope\n                    )\n\n                    buildToolPluginResults.append(result)\n\n                    let diagnosticsEmitter = observabilityScope.makeDiagnosticsEmitter {\n                        var metadata = ObservabilityMetadata()\n                        metadata.moduleName = module.name\n                        metadata.pluginName = result.plugin.name\n                        return metadata\n                    }\n\n                    for line in result.textOutput.split(whereSeparator: { $0.isNewline }) {\n                        diagnosticsEmitter.emit(info: line)\n                    }\n\n                    for diag in result.diagnostics {\n                        diagnosticsEmitter.emit(diag)\n                    }\n\n                    prebuildCommands.append(contentsOf: result.prebuildCommands)\n\n                    buildCommands.append(contentsOf: result.buildCommands.map( { buildCommand in\n                        var newEnv: Environment = buildCommand.configuration.environment\n\n                        // FIXME: This is largely a workaround for improper rpath setup on Linux. It should be\n                        // removed once the Swift Build backend switches to use swiftc as the linker driver\n                        // for targets with Swift sources. For now, limit the scope to non-macOS, so that\n                        // plugins do not inadvertently use the toolchain stdlib instead of the OS stdlib\n                        // when built with a Swift.org toolchain.\n                        #if !os(macOS)\n                        let runtimeLibPaths = buildParameters.toolchain.runtimeLibraryPaths\n\n                        // Add paths to swift standard runtime libraries to the library path so that they can be found at runtime\n                        for libPath in runtimeLibPaths {\n                            newEnv.appendPath(key: .libraryPath, value: libPath.pathString)\n                        }\n                        #endif\n\n                        // Append the system path at the end so that necessary system tool paths can be found\n                        if let pathValue = Environment.current[EnvironmentKey.path] {\n                            newEnv.appendPath(key: .path, value: pathValue)\n                        }\n\n                        let writableDirectories: [AbsolutePath] = [pluginOutputDir]\n\n                        return PackagePIFBuilder.CustomBuildCommand(\n                            displayName: buildCommand.configuration.displayName,\n                            executable: buildCommand.configuration.executable.pathString,\n                            arguments: buildCommand.configuration.arguments,\n                            environment: .init(newEnv),\n                            workingDir: package.path,\n                            inputPaths: buildCommand.inputFiles,\n                            outputPaths: buildCommand.outputFiles.map(\\.pathString),\n                            pluginOutputDir: pluginOutputDir,\n                            sandboxProfile:\n                                self.parameters.disableSandbox ?\n                            nil :\n                                    .init(\n                                        strictness: .writableTemporaryDirectory,\n                                        writableDirectories: writableDirectories,\n                                        readOnlyDirectories: buildCommand.inputFiles\n                                    )\n                        )\n                    }))\n                }\n\n                // Run the prebuild commands generated from the plugin invocation now for this module. This will\n                // also give use the derived source code files needed for PIF generation.\n                let runResults = try Self.runPluginCommands(\n                    using: self.pluginConfiguration,\n                    for: buildToolPluginResults,\n                    fileSystem: fileSystem,\n                    observabilityScope: observabilityScope\n                )\n\n                let result = PackagePIFBuilder.BuildToolPluginInvocationResult(\n                    prebuildCommandOutputPaths: runResults.flatMap( { $0.derivedFiles }),\n                    buildCommands: buildCommands\n                )\n\n                // Add a BuildToolPluginInvocationResult to the mapping.\n                if var existingResults = buildToolPluginResultsByTargetName[module.name] {\n                    existingResults.append(result)\n                } else {\n                    buildToolPluginResultsByTargetName[module.name] = [result]\n                }\n            }\n\n            let packagePIFBuilderDelegate = PackagePIFBuilderDelegate(\n                package: package\n            )\n            let packagePIFBuilder = PackagePIFBuilder(\n                modulesGraph: self.graph,\n                resolvedPackage: package,\n                packageManifest: package.manifest,\n                delegate: packagePIFBuilderDelegate,\n                buildToolPluginResultsByTargetName: buildToolPluginResultsByTargetName,\n                createDylibForDynamicProducts: self.parameters.shouldCreateDylibForDynamicProducts,\n                materializeStaticArchiveProductsForRootPackages: self.parameters.materializeStaticArchiveProductsForRootPackages,\n                createDynamicVariantsForLibraryProducts: self.parameters.createDynamicVariantsForLibraryProducts,\n                addLocalRpaths: self.parameters.addLocalRpaths,\n                packageDisplayVersion: package.manifest.displayName,\n                pkgConfigDirectories: self.parameters.pkgConfigDirectories,\n                fileSystem: self.fileSystem,\n                observabilityScope: self.observabilityScope\n            )\n\n            packagesAndBuilders.append((package, packagePIFBuilder, packagePIFBuilderDelegate))\n        }\n\n        return packagesAndBuilders\n    }\n\n    /// Constructs a `PIF.TopLevelObject` representing the package graph.\n    package func constructPIF(\n        buildParameters: BuildParameters\n    ) async throws -> PIF.TopLevelObject {\n        return try await memoize(to: &self.cachedPIF) {\n            let rootPackages = self.graph.rootPackages\n            guard !rootPackages.isEmpty else {\n                throw PIFGenerationError.rootPackageNotFound\n            }\n\n            let packagesAndPIFBuilders = try await makePIFBuilders(buildParameters: buildParameters)\n\n            let packagesAndPIFProjects = try packagesAndPIFBuilders.map { (package, pifBuilder, _) in\n                try pifBuilder.build()\n                let pifProject: ProjectModel.Project = pifBuilder.pifProject\n                return (package, pifProject)\n            }\n\n            var pifProjects: [ProjectModel.Project] = packagesAndPIFProjects.map(\\.1)\n            pifProjects.append(\n                try buildAggregatePIFProject(\n                    packagesAndProjects: packagesAndPIFProjects,\n                    observabilityScope: observabilityScope,\n                    modulesGraph: graph,\n                    buildParameters: buildParameters\n                )\n            )\n\n            let rootPackagesSorted = rootPackages.sorted()\n            let rootPackagesPaths = rootPackagesSorted.map { $0.path }\n            let ids: String = rootPackagesPaths.map { $0.pathString}.joined(separator: \",\")\n            let names = rootPackagesSorted.map { $0.manifest.displayName }.joined(separator: \",\")\n            let workspace = PIF.Workspace(\n                id: \"Workspace:\\(ids)\",\n                name: names,\n                path: try getCommonParentDirectory(paths: rootPackagesPaths),\n                projects: pifProjects\n            )\n            return PIF.TopLevelObject(workspace: workspace)\n        }\n    }\n\n    /// Runs any commands associated with the given list of plugin invocation results,\n    /// in order, and returns the results of running those prebuild commands.\n    fileprivate static func runPluginCommands(\n        using pluginConfiguration: PluginConfiguration,\n        for pluginResults: [BuildToolPluginInvocationResult],\n        fileSystem: any FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws -> [CommandPluginResult] {\n        // Run through all the commands from all the plugin usages in the target.\n        try pluginResults.map { pluginResult in\n            // As we go we will collect a list of prebuild output directories whose contents should be input to the\n            // build, and a list of the files in those directories after running the commands.\n            var derivedFiles: [Basics.AbsolutePath] = []\n            var prebuildOutputDirs: [Basics.AbsolutePath] = []\n            for command in pluginResult.prebuildCommands {\n                observabilityScope\n                    .emit(\n                        info: \"Running \" +\n                            (command.configuration.displayName ?? command.configuration.executable.basename)\n                    )\n\n                // Run the command configuration as a subshell. This doesn't return until it is done.\n                // TODO: We need to also use any working directory, but that support isn't yet available on all platforms at a lower level.\n                var commandLine = [command.configuration.executable.pathString] + command.configuration.arguments\n                if !pluginConfiguration.disableSandbox {\n                    commandLine = try Sandbox.apply(\n                        command: commandLine,\n                        fileSystem: fileSystem,\n                        strictness: .writableTemporaryDirectory,\n                        writableDirectories: [pluginResult.pluginOutputDirectory]\n                    )\n                }\n                let processResult = try AsyncProcess.popen(\n                    arguments: commandLine,\n                    environment: command.configuration.environment\n                )\n                let output = try processResult.utf8Output() + processResult.utf8stderrOutput()\n                if processResult.exitStatus != .terminated(code: 0) {\n                    throw StringError(\"failed: \\(command)\\n\\n\\(output)\")\n                }\n\n                // Add any files found in the output directory declared for the prebuild command after the command ends.\n                let outputFilesDir = command.outputFilesDirectory\n                if let swiftFiles = try? fileSystem.getDirectoryContents(outputFilesDir).sorted() {\n                    derivedFiles.append(contentsOf: swiftFiles.map { outputFilesDir.appending(component: $0) })\n                }\n\n                // Add the output directory to the list of directories whose structure should affect the build plan.\n                prebuildOutputDirs.append(outputFilesDir)\n            }\n\n            // Add the results of running any prebuild commands for this invocation.\n            return CommandPluginResult(derivedFiles: derivedFiles, outputDirectories: prebuildOutputDirs)\n        }\n    }\n\n    // Convenience method for generating PIF.\n    public static func generatePIF(\n        buildParameters: BuildParameters,\n        packageGraph: ModulesGraph,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        preservePIFModelStructure: Bool,\n        pluginScriptRunner: PluginScriptRunner,\n        disableSandbox: Bool,\n        pluginWorkingDirectory: AbsolutePath,\n        pkgConfigDirectories: [Basics.AbsolutePath],\n        additionalFileRules: [FileRuleDescription],\n        addLocalRpaths: Bool,\n        materializeStaticArchiveProductsForRootPackages: Bool,\n        createDynamicVariantsForLibraryProducts: Bool\n    ) async throws -> String {\n        let parameters = PIFBuilderParameters(\n            buildParameters,\n            supportedSwiftVersions: [],\n            pluginScriptRunner: pluginScriptRunner,\n            disableSandbox: disableSandbox,\n            pluginWorkingDirectory: pluginWorkingDirectory,\n            additionalFileRules: additionalFileRules,\n            addLocalRpaths: addLocalRpaths,\n            materializeStaticArchiveProductsForRootPackages: materializeStaticArchiveProductsForRootPackages,\n            createDynamicVariantsForLibraryProducts: createDynamicVariantsForLibraryProducts\n\n        )\n        let builder = Self(\n            graph: packageGraph,\n            parameters: parameters,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n        return try await builder.generatePIF(preservePIFModelStructure: preservePIFModelStructure, buildParameters: buildParameters)\n    }\n}\n\nfileprivate final class PackagePIFBuilderDelegate: PackagePIFBuilder.BuildDelegate {\n    let package: ResolvedPackage\n\n    init(package: ResolvedPackage) {\n        self.package = package\n    }\n\n    var isRootPackage: Bool {\n        self.package.manifest.packageKind.isRoot\n    }\n\n    var isRemote: Bool {\n        self.package.manifest.packageKind.isRemote\n    }\n\n    var hostsOnlyPackages: Bool {\n        false\n    }\n\n    var isUserManaged: Bool {\n        true\n    }\n\n    var isBranchOrRevisionBased: Bool {\n        false\n    }\n\n    func customProductType(forExecutable product: PackageModel.Product) -> ProjectModel.Target.ProductType? {\n        nil\n    }\n\n    func deviceFamilyIDs() -> Set<Int> {\n        []\n    }\n\n    func shouldPackagesBuildForARM64e(platform: PackageModel.Platform) -> Bool {\n        false\n    }\n\n    var isPluginExecutionSandboxingDisabled: Bool {\n        false\n    }\n\n    func configureProjectBuildSettings(_ buildSettings: inout ProjectModel.BuildSettings) {\n        /* empty */\n    }\n\n    func configureSourceModuleBuildSettings(sourceModule: ResolvedModule, settings: inout ProjectModel.BuildSettings) {\n        settings[.SYMBOL_GRAPH_EXTRACTOR_OUTPUT_DIR] = \"$(TARGET_BUILD_DIR)/$(CURRENT_ARCH)/\\(sourceModule.name).symbolgraphs\"\n    }\n\n    func customInstallPath(product: PackageModel.Product) -> String? {\n        nil\n    }\n\n    func customExecutableName(product: PackageModel.Product) -> String? {\n        nil\n    }\n\n    func customLibraryType(product: PackageModel.Product) -> PackageModel.ProductType.LibraryType? {\n        nil\n    }\n\n    func customSDKOptions(forPlatform: PackageModel.Platform) -> [String] {\n        []\n    }\n\n    func addCustomTargets(pifProject: inout SwiftBuild.ProjectModel.Project) throws -> [PackagePIFBuilder.ModuleOrProduct] {\n        return []\n    }\n\n    func shouldSuppressProductDependency(product: PackageModel.Product, buildSettings: inout SwiftBuild.ProjectModel.BuildSettings) -> Bool {\n        false\n    }\n\n    func shouldSetInstallPathForDynamicLib(productName: String) -> Bool {\n        false\n    }\n\n    func configureLibraryProduct(\n        product: PackageModel.Product,\n        project: inout ProjectModel.Project,\n        target: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n        additionalFiles: WritableKeyPath<ProjectModel.Group, ProjectModel.Group>\n    ) {\n        /* empty */\n    }\n\n    func suggestAlignedPlatformVersionGiveniOSVersion(platform: PackageModel.Platform, iOSVersion: PackageModel.PlatformVersion) -> String? {\n        nil\n    }\n\n    func validateMacroFingerprint(for macroModule: ResolvedModule) -> Bool {\n        true\n    }\n}\n\nfileprivate func buildAggregatePIFProject(\n    packagesAndProjects: [(package: ResolvedPackage, project: ProjectModel.Project)],\n    observabilityScope: ObservabilityScope,\n    modulesGraph: ModulesGraph,\n    buildParameters: BuildParameters\n) throws -> ProjectModel.Project {\n    precondition(!packagesAndProjects.isEmpty)\n\n    var aggregateProject = ProjectModel.Project(\n        id: \"AGGREGATE\",\n        path: packagesAndProjects[0].project.path,\n        projectDir: packagesAndProjects[0].project.projectDir,\n        name: \"Aggregate\",\n        developmentRegion: \"en\"\n    )\n    observabilityScope.logPIF(.debug, \"Created project '\\(aggregateProject.id)' with name '\\(aggregateProject.name)'\")\n\n    var settings = ProjectModel.BuildSettings()\n    settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n    settings[.SUPPORTED_PLATFORMS] = [\"$(AVAILABLE_PLATFORMS)\"]\n    settings[.SDKROOT] = \"auto\"\n    settings[.SDK_VARIANT] = \"auto\"\n    settings[.SKIP_INSTALL] = \"YES\"\n\n    aggregateProject.addBuildConfig { id in BuildConfig(id: id, name: \"Debug\", settings: settings) }\n    aggregateProject.addBuildConfig { id in BuildConfig(id: id, name: \"Release\", settings: settings) }\n\n    func addEmptyBuildConfig(\n        to targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.AggregateTarget>,\n        name: String\n    ) {\n        let emptySettings = BuildSettings()\n        aggregateProject[keyPath: targetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: name, settings: emptySettings)\n        }\n    }\n\n    let allIncludingTestsTargetKeyPath = try aggregateProject.addAggregateTarget { _ in\n        ProjectModel.AggregateTarget(\n            id: \"ALL-INCLUDING-TESTS\",\n            name: PIFBuilder.allIncludingTestsTargetName\n        )\n    }\n    addEmptyBuildConfig(to: allIncludingTestsTargetKeyPath, name: \"Debug\")\n    addEmptyBuildConfig(to: allIncludingTestsTargetKeyPath, name: \"Release\")\n\n    let allExcludingTestsTargetKeyPath = try aggregateProject.addAggregateTarget { _ in\n        ProjectModel.AggregateTarget(\n            id: \"ALL-EXCLUDING-TESTS\",\n            name: PIFBuilder.allExcludingTestsTargetName\n        )\n    }\n    addEmptyBuildConfig(to: allExcludingTestsTargetKeyPath, name: \"Debug\")\n    addEmptyBuildConfig(to: allExcludingTestsTargetKeyPath, name: \"Release\")\n\n    for (package, packageProject) in packagesAndProjects where package.manifest.packageKind.isRoot {\n        for target in packageProject.targets {\n            switch target {\n            case .target(let target):\n                guard !target.id.hasSuffix(.dynamic) else {\n                    // Otherwise we hit a bunch of \"Unknown multiple commands produce: ...\" errors,\n                    // as the build artifacts from \"PACKAGE-TARGET:Foo\"\n                    // conflicts with those from \"PACKAGE-TARGET:Foo-dynamic\".\n                    continue\n                }\n\n                if let resolvedModule = modulesGraph.module(for: target.name) {\n                    guard modulesGraph.isInRootPackages(resolvedModule, satisfying: buildParameters.buildEnvironment) else {\n                        // Disconnected target, possibly due to platform when condition that isn't satisfied\n                        continue\n                    }\n                }\n\n                aggregateProject[keyPath: allIncludingTestsTargetKeyPath].common.addDependency(\n                    on: target.id,\n                    platformFilters: [],\n                    linkProduct: false\n                )\n                if ![.unitTest, .swiftpmTestRunner].contains(target.productType) {\n                    aggregateProject[keyPath: allExcludingTestsTargetKeyPath].common.addDependency(\n                        on: target.id,\n                        platformFilters: [],\n                        linkProduct: false\n                    )\n                }\n            case .aggregate:\n                break\n            }\n        }\n    }\n\n    do {\n        let allIncludingTests = aggregateProject[keyPath: allIncludingTestsTargetKeyPath]\n        let allExcludingTests = aggregateProject[keyPath: allExcludingTestsTargetKeyPath]\n\n        observabilityScope.logPIF(\n            .debug,\n            indent: 1,\n            \"Created target '\\(allIncludingTests.id)' with name '\\(allIncludingTests.name)' \" +\n            \"and \\(allIncludingTests.common.dependencies.count) (unlinked) dependencies\"\n        )\n        observabilityScope.logPIF(\n            .debug,\n            indent: 1,\n            \"Created target '\\(allExcludingTests.id)' with name '\\(allExcludingTests.name)' \" +\n            \"and \\(allExcludingTests.common.dependencies.count) (unlinked) dependencies\"\n        )\n    }\n\n    return aggregateProject\n}\n\npublic enum PIFGenerationError: Error {\n    case rootPackageNotFound\n\n    case unsupportedSwiftLanguageVersions(\n        targetName: String,\n        versions: [SwiftLanguageVersion],\n        supportedVersions: [SwiftLanguageVersion]\n    )\n\n    /// Early build termination when using `--print-pif-manifest-graph`.\n    case printedPIFManifestGraphviz\n}\n\nextension PIFGenerationError: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .rootPackageNotFound:\n            \"No root package was found\"\n\n        case .unsupportedSwiftLanguageVersions(\n            targetName: let target,\n            versions: let given,\n            supportedVersions: let supported\n        ):\n            \"None of the Swift language versions used in target '\\(target)' settings are supported.\" +\n            \" (given: \\(given), supported: \\(supported))\"\n\n        case .printedPIFManifestGraphviz:\n            \"Printed PIF manifest as graphviz\"\n        }\n    }\n}\n\n// MARK: - Helpers\n\nextension PIFBuilderParameters {\n    init(\n        _ buildParameters: BuildParameters,\n        supportedSwiftVersions: [SwiftLanguageVersion],\n        pluginScriptRunner: PluginScriptRunner,\n        disableSandbox: Bool,\n        pluginWorkingDirectory: AbsolutePath,\n        additionalFileRules: [FileRuleDescription],\n        addLocalRpaths: Bool,\n        materializeStaticArchiveProductsForRootPackages: Bool,\n        createDynamicVariantsForLibraryProducts: Bool\n    ) {\n        self.init(\n            isPackageAccessModifierSupported: buildParameters.driverParameters.isPackageAccessModifierSupported,\n            enableTestability: buildParameters.enableTestability,\n            shouldCreateDylibForDynamicProducts: buildParameters.shouldCreateDylibForDynamicProducts,\n            materializeStaticArchiveProductsForRootPackages: materializeStaticArchiveProductsForRootPackages,\n            createDynamicVariantsForLibraryProducts: createDynamicVariantsForLibraryProducts,\n            toolchainLibDir: (try? buildParameters.toolchain.toolchainLibDir) ?? .root,\n            pkgConfigDirectories: buildParameters.pkgConfigDirectories,\n            supportedSwiftVersions: supportedSwiftVersions,\n            pluginScriptRunner: pluginScriptRunner,\n            disableSandbox: disableSandbox,\n            pluginWorkingDirectory: pluginWorkingDirectory,\n            additionalFileRules: additionalFileRules,\n            addLocalRPaths: addLocalRpaths,\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PackagePIFBuilder+Helpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport protocol TSCBasic.FileSystem\nimport struct TSCUtility.Version\n\nimport struct Basics.AbsolutePath\nimport struct Basics.Diagnostic\nimport struct Basics.ObservabilityMetadata\nimport struct Basics.RelativePath\nimport struct Basics.SourceControlURL\nimport class Basics.ObservabilityScope\nimport class Basics.ObservabilitySystem\nimport class Basics.ThreadSafeArrayStore\n\nimport enum PackageModel.BuildConfiguration\nimport enum PackageModel.BuildSettings\nimport class PackageModel.ClangModule\nimport struct PackageModel.ConfigurationCondition\nimport class PackageModel.Manifest\nimport class PackageModel.Module\nimport enum PackageModel.ModuleMapType\nimport class PackageModel.Package\nimport enum PackageModel.PackageCondition\nimport struct PackageModel.PackageIdentity\nimport struct PackageModel.Platform\nimport struct PackageModel.PlatformDescription\nimport struct PackageModel.PlatformRegistry\nimport struct PackageModel.PlatformsCondition\nimport class PackageModel.PluginModule\nimport class PackageModel.Product\nimport enum PackageModel.ProductType\nimport struct PackageModel.Resource\nimport struct PackageModel.SupportedPlatform\nimport struct PackageModel.SwiftLanguageVersion\nimport class PackageModel.SwiftModule\nimport class PackageModel.SystemLibraryModule\nimport struct PackageModel.ToolsVersion\nimport struct PackageModel.TraitCondition\n\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedPackage\nimport struct PackageGraph.ResolvedProduct\n\nimport func PackageLoading.pkgConfigArgs\n\nimport SPMBuildCore\n\nimport enum SwiftBuild.ProjectModel\n\n// MARK: - PIF GUID Helpers\n\npublic enum TargetSuffix: String, CaseIterable {\n    case testable, dynamic\n\n    func hasSuffix(id: GUID) -> Bool {\n        id.value.hasSuffix(\"-\\(self.rawValue)\")\n    }\n}\n\nextension TargetSuffix? {\n    func uniqueDescription(forName name: String) -> String {\n        switch self {\n        case .some(let suffix):\n            \"-\\(String(name.hash, radix: 16, uppercase: true))-\\(suffix.rawValue)\"\n        case .none:\n            \"\"\n        }\n    }\n}\n\nextension GUID {\n    func hasSuffix(_ suffix: TargetSuffix) -> Bool {\n        self.value.hasSuffix(\"-\\(suffix.rawValue)\")\n    }\n}\n\nextension PackageModel.Module {\n    var pifTargetGUID: GUID { pifTargetGUID(suffix: nil) }\n\n    func pifTargetGUID(suffix: TargetSuffix?) -> GUID {\n        PackagePIFBuilder.targetGUID(forModuleName: self.name, suffix: suffix)\n    }\n}\n\nextension PackageGraph.ResolvedModule {\n    var pifTargetGUID: GUID { pifTargetGUID(suffix: nil) }\n\n    func pifTargetGUID(suffix: TargetSuffix?) -> GUID {\n        self.underlying.pifTargetGUID(suffix: suffix)\n    }\n}\n\nextension PackageModel.Product {\n    var pifTargetGUID: GUID { pifTargetGUID(suffix: nil) }\n\n    func pifTargetGUID(suffix: TargetSuffix?) -> GUID {\n        PackagePIFBuilder.targetGUID(forProductName: self.name, withId:self.identity, suffix: suffix)\n    }\n}\n\nextension PackageGraph.ResolvedProduct {\n    var pifTargetGUID: GUID { pifTargetGUID(suffix: nil) }\n\n    func pifTargetGUID(suffix: TargetSuffix?) -> GUID {\n        self.underlying.pifTargetGUID(suffix: suffix)\n    }\n\n    func targetName(suffix: TargetSuffix? = nil) -> String {\n        PackagePIFBuilder.targetName(forProductName: self.name, suffix: suffix)\n    }\n}\n\nextension PackagePIFBuilder {\n    /// Helper function to consistently generate a PIF target identifier string for a module in a package.\n    ///\n    /// This format helps make sure that there is no collision with any other PIF targets,\n    /// and in particular that a PIF target and a PIF product can have the same name (as they often do).\n    static func targetGUID(forModuleName name: String, suffix: TargetSuffix? = nil) -> GUID {\n        let suffixDescription = suffix.uniqueDescription(forName: name)\n        return \"PACKAGE-TARGET:\\(name)\\(suffixDescription)\"\n    }\n\n    /// Helper function to consistently generate a PIF target identifier string for a product in a package.\n    ///\n    /// This format helps make sure that there is no collision with any other PIF targets,\n    /// and in particular that a PIF target and a PIF product can have the same name (as they often do).\n    public static func targetGUID(forProductName name: String, withId id: String, suffix: TargetSuffix? = nil) -> GUID {\n        let suffixDescription: String = suffix.uniqueDescription(forName: name)\n        return \"PACKAGE-PRODUCT:\\(id).\\(name)\\(suffixDescription)\"\n    }\n\n    /// Helper function to consistently generate a target name string for a product in a package.\n    ///\n    /// This format helps make sure that modules and products with the same name (as they often have)\n    /// have different target names in the PIF.\n    public static func targetName(forProductName name: String, suffix: TargetSuffix? = nil) -> String {\n        let suffix = suffix?.rawValue ?? \"\"\n        return \"\\(name)\\(suffix)-product\"\n    }\n\n    /// Helper function to consistently generate a target name string for a module in a product.\n    package static func targetName(forModuleName name: String, suffix: TargetSuffix? = nil) -> String {\n        let suffix = suffix?.rawValue ?? \"\"\n        return \"\\(name)\\(suffix)\"\n    }\n    \n    /// Removes known TargetSuffix patterns from a name string.\n    private static func removeSuffix(from name: String) -> String {\n        for suffix in TargetSuffix.allCases {\n            let suffixPattern: String\n            switch suffix {\n            case .testable, .dynamic:\n                suffixPattern = \"-\\(suffix.rawValue)\"\n                if name.hasSuffix(suffixPattern) {\n                    return String(name.dropLast(suffixPattern.count))\n                }\n            }\n        }\n        return name\n    }\n\n    /// Extracts a Swift Package product name from a PIF target name.\n    ///\n    /// This reverses the conversion performed by `targetName(forProductName:suffix:)`.\n    /// Returns `nil` if the target name doesn't represent a product (i.e., doesn't end with \"-product\").\n    ///\n    /// - Parameter targetName: The PIF target name to parse\n    /// - Returns: The Swift Package product name, or `nil` if this isn't a product target name\n    package static func productName(forTargetName targetName: String) -> String? {\n        guard targetName.hasSuffix(\"-product\") else {\n            return nil\n        }\n        let nameWithoutProduct = String(targetName.dropLast(\"-product\".count))\n        return removeSuffix(from: nameWithoutProduct)\n    }\n\n        /// Extracts a Swift Package module name from a PIF target name.\n    ///\n    /// This reverses the conversion performed by `targetName(forModuleName:suffix:)`.\n    /// Returns `nil` if the target name represents a product or resource bundle.\n    ///\n    /// - Parameter targetName: The PIF target name to parse\n    /// - Returns: The Swift Package module name, or `nil` if this isn't a module target name\n    ///\n    /// - Note: Resource bundle target names follow the pattern `packageName_moduleName`\n    ///   (e.g., `swift-nio_NIOPosix`, `swift-crypto__CryptoExtras`) and are excluded.\n    ///   However, module names can start with `_` (e.g., `_CryptoExtras`, `__AsyncFileSystem`).\n    package static func moduleName(forTargetName targetName: String) -> String? {\n        guard !targetName.hasSuffix(\"-product\") else {\n            return nil\n        }\n        // Resource bundle target names follow the pattern packageName_moduleName\n        // e.g., swift-nio_NIOPosix, swift-crypto__CryptoExtras\n        // So should be ignored by moduleName()\n        // But moduleName can start with _, like _CryptoExtras and __AsyncFileSystem\n        if targetName.contains(\"_\") && targetName.first != \"_\" {\n            return nil\n        }\n        return removeSuffix(from: targetName)\n    }\n}\n\n// MARK: - SwiftPM PackageModel Helpers\n\nextension PackageModel.PackageIdentity {\n    var c99name: String {\n        self.description.spm_mangledToC99ExtendedIdentifier()\n    }\n}\n\nextension PackageModel.Package {\n    /// Package name as defined in the manifest.\n    var name: String {\n        self.manifest.displayName\n    }\n\n    var packageBaseBuildSettings: ProjectModel.BuildSettings {\n        var settings = BuildSettings()\n        settings[.SDKROOT] = \"auto\"\n        settings[.SDK_VARIANT] = \"auto\"\n\n        if self.manifest.toolsVersion >= ToolsVersion.v6_0 {\n            if let version = manifest.version, !version.isPrerelease && !version.hasBuildMetadata {\n                settings[.SWIFT_USER_MODULE_VERSION] = version.stringRepresentation\n            }\n        }\n        return settings\n    }\n}\n\nextension PackageModel.Module {\n    var isExecutable: Bool {\n        switch self.type {\n        case .executable, .snippet:\n            true\n        case .library, .test, .macro, .systemModule, .plugin, .binary:\n            false\n        }\n    }\n\n    var isBinary: Bool {\n        switch self.type {\n        case .binary:\n            true\n        case .library, .executable, .snippet, .test, .plugin, .macro, .systemModule:\n            false\n        }\n    }\n\n    /// Is this a source module? i.e., one that's compiled into a module from source code.\n    var isSourceModule: Bool {\n        switch self.type {\n        case .library, .executable, .snippet, .test, .macro:\n            true\n        case .systemModule, .plugin, .binary:\n            false\n        }\n    }\n}\n\nextension PackageModel.ProductType {\n    var targetType: Module.Kind {\n        switch self {\n        case .executable: .executable\n        case .snippet: .snippet\n        case .test: .test\n        case .library: .library\n        case .plugin: .plugin\n        case .macro: .macro\n        }\n    }\n}\n\nextension PackageModel.Platform {\n    static var knownPlatforms: Set<PackageModel.Platform> {\n        Set(PlatformRegistry.default.knownPlatforms)\n    }\n}\n\nextension Sequence<PackageModel.PackageCondition> {\n    func toPlatformFilter(toolsVersion: ToolsVersion) -> Set<ProjectModel.PlatformFilter> {\n        let pifPlatforms = self.flatMap { packageCondition -> [ProjectModel.BuildSettings.Platform] in\n            guard let platforms = packageCondition.platformsCondition?.platforms else {\n                return []\n            }\n\n            var pifPlatformsForCondition: [ProjectModel.BuildSettings.Platform] = platforms\n                .compactMap { try? ProjectModel.BuildSettings.Platform(from: $0) }\n\n            // Treat catalyst like macOS for backwards compatibility with older tools versions.\n            if pifPlatformsForCondition.contains(.macOS), toolsVersion < ToolsVersion.v5_5 {\n                pifPlatformsForCondition.append(.macCatalyst)\n            }\n            return pifPlatformsForCondition\n        }\n        return Set(pifPlatforms.flatMap { $0.toPlatformFilter() })\n    }\n\n    var splitIntoConcreteConditions: (\n        [PackageModel.Platform?],\n        [PackageModel.BuildConfiguration],\n        [PackageModel.TraitCondition]\n    ) {\n        var platformConditions: [PackageModel.PlatformsCondition] = []\n        var configurationConditions: [PackageModel.ConfigurationCondition] = []\n        var traitConditions: [PackageModel.TraitCondition] = []\n\n        for packageCondition in self {\n            switch packageCondition {\n            case .platforms(let condition): platformConditions.append(condition)\n            case .configuration(let condition): configurationConditions.append(condition)\n            case .traits(let condition): traitConditions.append(condition)\n            }\n        }\n\n        // Determine the *platform* conditions, if any.\n        // An empty set means that there are no platform restrictions.\n        let platforms: [PackageModel.Platform?] = if platformConditions.isEmpty {\n            [nil]\n        } else {\n            platformConditions.flatMap(\\.platforms)\n        }\n\n        // Determine the *configuration* conditions, if any.\n        // If there are none, we apply the setting to both debug and release builds (ie, `allCases`).\n        let configurations: [BuildConfiguration] = if configurationConditions.isEmpty {\n            BuildConfiguration.allCases\n        } else {\n            configurationConditions.map(\\.configuration)\n        }\n\n        return (platforms, configurations, traitConditions)\n    }\n}\n\nextension PackageModel.BuildSettings.Declaration {\n    var allowsMultipleValues: Bool {\n        switch self {\n        // Swift.\n        case .SWIFT_ACTIVE_COMPILATION_CONDITIONS, .OTHER_SWIFT_FLAGS:\n            true\n\n        case .SWIFT_VERSION:\n            false\n\n        // C family.\n        case .GCC_PREPROCESSOR_DEFINITIONS, .HEADER_SEARCH_PATHS, .OTHER_CFLAGS, .OTHER_CPLUSPLUSFLAGS:\n            true\n\n        // Linker.\n        case .OTHER_LDFLAGS, .LINK_LIBRARIES, .LINK_FRAMEWORKS:\n            true\n\n        // Prebuilts\n        case .PREBUILT_INCLUDE_PATHS, .PREBUILT_LIBRARY_PATHS, .PREBUILT_LIBRARIES:\n            true\n\n        default:\n            true\n        }\n    }\n}\n\n// MARK: - SwiftPM PackageGraph Helpers\n\nextension PackageGraph.ResolvedPackage {\n    var name: String {\n        self.underlying.name\n    }\n\n    /// The options declared per platform.\n    func sdkOptions(delegate: PackagePIFBuilder.BuildDelegate) -> [PackageModel.Platform: [String]] {\n        let platformDescriptionsByName: [String: PlatformDescription] = Dictionary(\n            uniqueKeysWithValues: self.manifest.platforms.map { platformDescription in\n                let key = platformDescription.platformName.lowercased()\n                let value = platformDescription\n                return (key, value)\n            }\n        )\n\n        var sdkOptions: [PackageModel.Platform: [String]] = [:]\n        for platform in Platform.knownPlatforms {\n            sdkOptions[platform] = platformDescriptionsByName[platform.name.lowercased()]?.options\n\n            let customSDKOptions = delegate.customSDKOptions(forPlatform: platform)\n            if customSDKOptions.hasContent {\n                sdkOptions[platform, default: []].append(contentsOf: customSDKOptions)\n            }\n        }\n        return sdkOptions\n    }\n}\n\nextension PackageGraph.ResolvedPackage {\n    public var packageBaseBuildSettings: ProjectModel.BuildSettings {\n        self.underlying.packageBaseBuildSettings\n    }\n}\n\nextension PackageGraph.ResolvedModule {\n    var isExecutable: Bool { self.underlying.isExecutable }\n    var isBinary: Bool { self.underlying.isBinary }\n    var isSourceModule: Bool { self.underlying.isSourceModule }\n\n    /// The path of the module.\n    var path: AbsolutePath { self.underlying.path }\n\n    /// The stable sorted list of resources in the module\n    var resources: [PackageModel.Resource] {\n        self.underlying.resources.sorted(on: \\.path)\n    }\n\n    /// The name of the group this module belongs to; by default, the package identity.\n    var packageName: String? {\n        self.packageAccess ? packageIdentity.c99name : nil\n    }\n\n    /// Minimum deployment targets for particular platforms, as declared in the manifest.\n    func deploymentTargets(using delegate: PackagePIFBuilder.BuildDelegate) -> [PackageModel.Platform: String] {\n        let isUsingXCTest = (self.type == .test)\n        let derivedSupportedPlatforms: [SupportedPlatform] = Platform.knownPlatforms.map {\n            self.getSupportedPlatform(for: $0, usingXCTest: isUsingXCTest)\n        }\n\n        var deploymentTargets: [PackageModel.Platform: String] = [:]\n        for derivedSupportedPlatform in derivedSupportedPlatforms {\n            deploymentTargets[derivedSupportedPlatform.platform] = derivedSupportedPlatform.version.versionString\n\n            // If the version for this platform wasn't actually declared explicitly in the manifest,\n            // try to derive an aligned version from the iOS declaration, if there was one.\n            let targetPlatform = derivedSupportedPlatform.platform\n            let isPlatformMissing = !self.supportedPlatforms.map(\\.platform).contains(targetPlatform)\n            guard isPlatformMissing else { continue }\n\n            let iOSDeploymentTarget = self.getSupportedPlatform(for: .iOS, usingXCTest: isUsingXCTest).version\n            let mappedVersion = delegate.suggestAlignedPlatformVersionGiveniOSVersion(\n                platform: targetPlatform,\n                iOSVersion: iOSDeploymentTarget\n            )\n\n            if let mappedVersion {\n                deploymentTargets[targetPlatform] = mappedVersion\n            }\n        }\n        return deploymentTargets\n    }\n\n    /// Platforms explicitly declared in the manifest for the purpose of customizing deployment targets.\n    ///\n    /// This does not include any custom platforms the user may have defined.\n    /// A package is still considered to be runnable for *all* platforms.\n    var declaredPlatforms: [PackageModel.Platform] {\n        let knownPlatforms = Platform.knownPlatforms\n\n        let declaredPlatforms: [PackageModel.Platform] = self.supportedPlatforms.compactMap {\n            guard knownPlatforms.contains($0.platform) else { return nil }\n            return $0.platform\n        }\n        return declaredPlatforms\n    }\n\n    /// Relative paths of each of the source files (relative to `target.sources.root`).\n    var sourceFileRelativePaths: [RelativePath] {\n        self.sources.relativePaths.map { try! RelativePath(validating: $0.pathString) }\n    }\n\n    /// Absolute path of the top-level directory of the sources.\n    var sourceDirAbsolutePath: AbsolutePath {\n        try! AbsolutePath(validating: self.sources.root.pathString)\n    }\n\n    /// Absolute paths to each of the header files  (*only* applies to C-language modules).\n    var headerFileAbsolutePaths: [AbsolutePath] {\n        guard let clangTarget = self.underlying as? ClangModule else { return [] }\n        return clangTarget.headers\n    }\n\n    /// Relative path of the `include` directory (*only* applies to C-language modules).\n    var includeDirRelativePath: RelativePath? {\n        guard let clangModule = self.underlying as? ClangModule else { return nil }\n        let relativePath = clangModule.includeDir.relative(to: self.sources.root).pathString\n        return try! RelativePath(validating: relativePath)\n    }\n\n    /// Include directory as an *absolute* path.\n    var includeDirAbsolutePath: AbsolutePath? {\n        guard let includeDirRelativePath = self.includeDirRelativePath else { return nil }\n        return self.sourceDirAbsolutePath.appending(includeDirRelativePath)\n    }\n\n    /// Module map type (*only* applies to C-language modules).\n    var moduleMapType: ModuleMapType? {\n        guard let clangModule = self.underlying as? ClangModule else { return nil }\n        return clangModule.moduleMapType\n    }\n\n    /// The C language standard for which the module is configured (*only* applies to C-language modules).\n    var cLanguageStandard: String? {\n        guard let clangModule = self.underlying as? ClangModule else { return nil }\n        return clangModule.cLanguageStandard\n    }\n\n    /// The C++ language standard for which the module is configured (*only* applies to C-language modules).\n    var cxxLanguageStandard: String? {\n        guard let clangTarget = self.underlying as? ClangModule else { return nil }\n        return clangTarget.cxxLanguageStandard\n    }\n\n    /// Whether or not this module contains C++ sources (*only* applies to C-language modules).\n    var isCxx: Bool {\n        guard let clangTarget = self.underlying as? ClangModule else { return false }\n        return clangTarget.isCXX\n    }\n\n    /// The list of swift versions declared by the manifest.\n    var declaredSwiftVersions: [SwiftLanguageVersion]? {\n        guard let swiftTarget = self.underlying as? SwiftModule else { return nil }\n        return swiftTarget.declaredSwiftVersions\n    }\n\n    /// Is this a Swift module?\n    var usesSwift: Bool {\n        self.declaredSwiftVersions != nil\n    }\n\n    /// Swift language version for which the module is configured.\n    func packageSwiftLanguageVersion(manifest: PackageModel.Manifest) -> String? {\n        guard let declaredSwiftVersions else { return nil }\n\n        // Probably wrong at this point since we have *per* target versioning,\n        // but at the time the original code was written, the version aligned everywhere.\n        // See: rdar://147618136 (SwiftPM PIFBuilder — review how we compute the Swift version for a given target).\n        let packageSwiftLanguageVersion = declaredSwiftVersions.first ?? manifest.toolsVersion.swiftLanguageVersion\n        return packageSwiftLanguageVersion.rawValue\n    }\n\n    var pluginsAppliedToModule: [PackageGraph.ResolvedModule] {\n        var pluginModules: [PackageGraph.ResolvedModule] = []\n\n        for dependency in self.dependencies {\n            switch dependency {\n            case .module(let moduleDependency, _):\n                if moduleDependency.type == .plugin {\n                    pluginModules.append(moduleDependency)\n                }\n            case .product(let productDependency, _):\n                let productPlugins = productDependency.modules.filter { $0.type == .plugin }\n                pluginModules.append(contentsOf: productPlugins)\n            }\n        }\n        return pluginModules\n    }\n\n    func productRepresentingDependencyOfBuildPlugin(in mainModuleProducts: [ResolvedProduct]) -> ResolvedProduct? {\n        mainModuleProducts.only { (mainModuleProduct: ResolvedProduct) -> Bool in\n            // Handle binary-only executable products that don't have a main module, i.e. binaryTarget\n            guard let mainModule = mainModuleProduct.mainModule else {\n                return mainModuleProduct.type == .executable &&\n                    mainModuleProduct.modules.only?.type == .binary &&\n                    mainModuleProduct.modules.only?.name == self.name\n            }\n            // NOTE: We can't use the 'id' here as we need to explicitly ignore the build triple because our build\n            // triple will be '.tools' while the target we want to depend on will have a build triple of '.destination'.\n            // See for more details:\n            // https://github.com/swiftlang/swift-package-manager/commit/b22168ec41061ddfa3438f314a08ac7a776bef7a.\n            return mainModule.packageIdentity == self.packageIdentity &&\n                mainModule.name == self.name\n            // Intentionally ignore the build triple!\n        }\n    }\n\n    struct AllBuildSettings {\n        typealias SingleValueSettingsByPlatform =\n            [ProjectModel.BuildSettings.Platform?: [ProjectModel.BuildSettings.SingleValueSetting: String]]\n        typealias MultipleValueSettingsByPlatform =\n            [ProjectModel.BuildSettings.Platform?: [ProjectModel.BuildSettings.MultipleValueSetting: [String]]]\n\n        /// Target-specific single-value build settings declared in the manifest and that apply to the target itself.\n        var targetSingleValueSettings: [BuildConfiguration: SingleValueSettingsByPlatform] = [:]\n\n        /// Target-specific multiple-value build settings declared in the manifest and that apply to the target itself.\n        var targetMultipleValueSettings: [BuildConfiguration: MultipleValueSettingsByPlatform] = [:]\n\n        /// Target-specific single-value build settings that should be imparted to client targets (packages and projects).\n        var impartedSingleValueSettings: SingleValueSettingsByPlatform = [:]\n\n        /// Target-specific multiple-value build settings that should be imparted to client targets (packages and projects).\n        var impartedMultipleValueSettings: MultipleValueSettingsByPlatform = [:]\n\n        // MARK: - Convenience Methods\n\n        /// Apply all settings to a ProjectModel.BuildSettings instance\n        func apply(to buildSettings: inout ProjectModel.BuildSettings, for configuration: BuildConfiguration) {\n            // Apply single value settings for all platforms\n            if let singleValuesByPlatform = targetSingleValueSettings[configuration] {\n                for (platform, singleValues) in singleValuesByPlatform {\n                    for (setting, value) in singleValues {\n                        if let platform = platform {\n                            buildSettings[setting, platform] = value\n                        } else {\n                            buildSettings[setting] = value\n                        }\n                    }\n                }\n            }\n\n            // Apply multiple value settings for all platforms\n            if let multipleValuesByPlatform = targetMultipleValueSettings[configuration] {\n                // First, collect all multiple-value settings that are being used\n                var usedMultipleValueSettings = Set<ProjectModel.BuildSettings.MultipleValueSetting>()\n                for (_, multipleValues) in multipleValuesByPlatform {\n                    for (setting, _) in multipleValues {\n                        usedMultipleValueSettings.insert(setting)\n                    }\n                }\n\n                // Now apply the platform-specific values\n                for (platform, multipleValues) in multipleValuesByPlatform {\n                    for (setting, values) in multipleValues {\n                        if let platform = platform {\n                            // Get existing values (should now be initialized with inherited)\n                            let existingValues = buildSettings[setting, platform] ?? [\"$(inherited)\"]\n                            buildSettings[setting, platform] = existingValues + values\n                        } else {\n                            // Append to existing values instead of overwriting\n                            let existingValues = buildSettings[setting] ?? [\"$(inherited)\"]\n                            buildSettings[setting] = existingValues + values\n                        }\n                    }\n                }\n            }\n        }\n\n        /// Apply imparted settings to a ProjectModel.BuildSettings instance\n        func applyImparted(to buildSettings: inout ProjectModel.BuildSettings) {\n            // Apply imparted single value settings for all platforms\n            for (platform, singleValues) in impartedSingleValueSettings {\n                for (setting, value) in singleValues {\n                    if let platform = platform {\n                        buildSettings[setting, platform] = value\n                    } else {\n                        buildSettings[setting] = value\n                    }\n                }\n            }\n\n            // Apply imparted multiple value settings for all platforms\n            for (platform, multipleValues) in impartedMultipleValueSettings {\n                for (setting, values) in multipleValues {\n                    if let platform = platform {\n                        let existingValues = buildSettings[setting, platform] ?? [\"$(inherited)\"]\n                        buildSettings[setting, platform] = existingValues + values\n                    } else {\n                        let existingValues = buildSettings[setting] ?? [\"$(inherited)\"]\n                        buildSettings[setting] = existingValues + values\n                    }\n                }\n            }\n        }\n    }\n\n    /// Target-specific build settings declared in the manifest and that apply to the target itself.\n    ///\n    /// Collect the build settings defined in the package manifest.\n    /// Some of them apply *only* to the target itself, while others are also imparted to clients.\n    /// Note that the platform is *optional*; unconditional settings have no platform condition.\n    func computeAllBuildSettings(observabilityScope: ObservabilityScope, forRemotePackage: Bool) -> AllBuildSettings {\n        var allSettings = AllBuildSettings()\n\n        for (declaration, settingsAssigments) in self.underlying.buildSettings.assignments {\n            for settingAssignment in settingsAssigments {\n                // Create a build setting value; in some cases there\n                // isn't a direct mapping to Swift Build build settings.\n                let values: [String]\n                let singleValueSetting: ProjectModel.BuildSettings.SingleValueSetting?\n                let multipleValueSetting: ProjectModel.BuildSettings.MultipleValueSetting?\n\n                switch declaration {\n                case .LINK_FRAMEWORKS:\n                    singleValueSetting = nil\n                    multipleValueSetting = .OTHER_LDFLAGS\n                    values = settingAssignment.values.flatMap { [\"-framework\", $0] }\n                case .LINK_LIBRARIES:\n                    singleValueSetting = nil\n                    multipleValueSetting = .OTHER_LDFLAGS\n                    values = settingAssignment.values.map { \"-l\\($0)\" }\n                case .HEADER_SEARCH_PATHS:\n                    singleValueSetting = nil\n                    multipleValueSetting = .HEADER_SEARCH_PATHS\n                    values = settingAssignment.values.map { self.sourceDirAbsolutePath.pathString + \"/\" + $0 }\n                case .PREBUILT_INCLUDE_PATHS:\n                    singleValueSetting = nil\n                    multipleValueSetting = .OTHER_SWIFT_FLAGS\n                    values = settingAssignment.values.flatMap { [\"-I\", $0] }\n                case .PREBUILT_LIBRARY_PATHS:\n                    singleValueSetting = nil\n                    multipleValueSetting = .LIBRARY_SEARCH_PATHS\n                    values = settingAssignment.values\n                case .PREBUILT_LIBRARIES:\n                    singleValueSetting = nil\n                    multipleValueSetting = .OTHER_LDFLAGS\n                    values = settingAssignment.values.map { \"-l\\($0)\" }\n                case .OTHER_SWIFT_FLAGS:\n                    singleValueSetting = nil\n                    multipleValueSetting = .OTHER_SWIFT_FLAGS\n                    if forRemotePackage {\n                        values = WarningControlFlags.filterSwiftWarningControlFlags(settingAssignment.values)\n                    } else {\n                        values = settingAssignment.values\n                    }\n                case .OTHER_CFLAGS, .OTHER_CPLUSPLUSFLAGS:\n                    singleValueSetting = nil\n                    multipleValueSetting = ProjectModel.BuildSettings.MultipleValueSetting(from: declaration)\n                    if forRemotePackage {\n                        values = WarningControlFlags.filterClangWarningControlFlags(settingAssignment.values)\n                    } else {\n                        values = settingAssignment.values\n                    }\n                default:\n                    if declaration.allowsMultipleValues {\n                        singleValueSetting = nil\n                        multipleValueSetting = ProjectModel.BuildSettings.MultipleValueSetting(from: declaration)\n                    } else {\n                        singleValueSetting = ProjectModel.BuildSettings.SingleValueSetting(from: declaration)\n                        multipleValueSetting = nil\n                    }\n                    values = settingAssignment.values\n                }\n\n                // TODO: We are currently ignoring package traits (see rdar://138149810).\n                let (platforms, configurations, _) = settingAssignment.conditions.splitIntoConcreteConditions\n\n                for platform in platforms {\n                    let pifPlatform: ProjectModel.BuildSettings.Platform?\n                    if let platform {\n                        guard let computedPifPlatform = try? ProjectModel.BuildSettings.Platform(from: platform) else {\n                            observabilityScope.logPIF(.warning, \"Ignoring settings assignments for unknown platform '\\(platform.name)'\")\n                            continue\n                        }\n                        pifPlatform = computedPifPlatform\n                    } else {\n                        pifPlatform = nil\n                    }\n\n                    // Handle imparted settings for OTHER_LDFLAGS and prebuilts include paths (always multiple values)\n                    // TODO: Do we realy need to impart OTHER_LDFLAGS?\n                    // TODO: Doing that for the PREBUILT_LIBRARIES was causing duplicate library warnings.\n                    if let multipleValueSetting = multipleValueSetting,\n                        declaration != .PREBUILT_LIBRARIES,\n                        (multipleValueSetting == .OTHER_LDFLAGS || declaration == .PREBUILT_INCLUDE_PATHS) {\n                        allSettings.impartedMultipleValueSettings[pifPlatform, default: [:]][multipleValueSetting, default: []].append(contentsOf: values)\n                    }\n\n                    for configuration in configurations {\n                        if let multipleValueSetting = multipleValueSetting {\n                            // Handle multiple value settings\n                            allSettings.targetMultipleValueSettings[configuration, default: [:]][pifPlatform, default: [:]][multipleValueSetting, default: []].append(contentsOf: values)\n                        } else if let singleValueSetting = singleValueSetting, let singleValue = values.only {\n                            // Handle single value settings\n                            allSettings.targetSingleValueSettings[configuration, default: [:]][pifPlatform, default: [:]][singleValueSetting] = singleValue\n                        }\n                    }\n                }\n            }\n        }\n        return allSettings\n    }\n}\n\n/// Specialization of `Module` for \"system module\" targets,\n/// i.e. those that just provide information about a library already on the system.\nextension SystemLibraryModule {\n    /// Absolute path of the *module-map* file.\n    var modulemapFileAbsolutePath: String {\n        self.moduleMapPath.pathString\n    }\n\n    /// Returns pkgConfig result for a system library target.\n    func pkgConfig(\n        package: PackageGraph.ResolvedPackage,\n        pkgConfigDirectories: [AbsolutePath],\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws -> (cFlags: [String], libs: [String]) {\n        let diagnostics = ThreadSafeArrayStore<Basics.Diagnostic>()\n        defer {\n            for diagnostic in diagnostics.get() {\n                observabilityScope.emit(diagnostic)\n            }\n        }\n\n        let pkgConfigParsingScope = ObservabilitySystem({ _, diagnostic in\n            diagnostics.append(diagnostic)\n        }, outputStream: nil, logLevel: .debug).topScope.makeChildScope(description: \"PkgConfig\") {\n            var packageMetadata = ObservabilityMetadata.packageMetadata(\n                identity: package.identity,\n                kind: package.manifest.packageKind\n            )\n            packageMetadata.moduleName = self.name\n            return packageMetadata\n        }\n\n        let brewPrefix: AbsolutePath?\n        // Normally PIF should be independent of the host OS, but in this case\n        // we need to invoke a tool (pkg-config) installed on the host system by homebrew.\n        if ProcessInfo.hostOperatingSystem == .macOS {\n            let brewPath = if FileManager.default.fileExists(atPath: \"/opt/brew\") {\n                \"/opt/brew\" // Legacy path for Homebrew.\n            } else if FileManager.default.fileExists(atPath: \"/opt/homebrew\") {\n                \"/opt/homebrew\" // Default path for Homebrew on Apple Silicon.\n            } else {\n                \"/usr/local\" // Fallback to default path for Homebrew.\n            }\n\n            brewPrefix = try? AbsolutePath(\n                validating: UserDefaults.standard.string(forKey: \"IDEHomebrewPrefixPath\") ?? brewPath\n            )\n        } else {\n            brewPrefix = nil\n        }\n\n        let pkgConfigResult = try? pkgConfigArgs(\n            for: self,\n            pkgConfigDirectories: pkgConfigDirectories,\n            brewPrefix: brewPrefix,\n            fileSystem: fileSystem,\n            observabilityScope: pkgConfigParsingScope\n        )\n        guard let pkgConfigResult else { return ([], []) }\n\n        let pkgConfig = (\n            cFlags: pkgConfigResult.flatMap(\\.cFlags),\n            libs: pkgConfigResult.flatMap(\\.libs)\n        )\n        return pkgConfig\n    }\n}\n\n// MARK: - SwiftPM PackageGraph.ResolvedProduct Helpers\n\nextension PackageGraph.ResolvedProduct {\n    /// Returns the main module (aka, target) of this product, if any.\n    var mainModule: PackageGraph.ResolvedModule? {\n        self.modules.only { $0.type == self.type.targetType }\n    }\n\n    /// Returns the other modules of this product.\n    var otherModules: [PackageGraph.ResolvedModule] {\n        modules.filter { $0.isSourceModule && $0.type != self.type.targetType }\n    }\n\n    /// These are the kinds of products for whom one module is special\n    /// (e.g., executables have one executable module, test bundles have one test module, etc).\n    var isMainModuleProduct: Bool {\n        switch self.type {\n        case .executable, .snippet, .test:\n            true\n        case .library, .macro, .plugin:\n            false\n        }\n    }\n\n    /// Is this a *system library* product?\n    var isSystemLibraryProduct: Bool {\n        if self.modules.only?.type == .systemModule {\n            true\n        } else {\n            false\n        }\n    }\n\n    var isExecutable: Bool {\n        switch self.type {\n        case .executable, .snippet:\n            true\n        case .library, .test, .plugin, .macro:\n            false\n        }\n    }\n\n    var isBinaryOnlyExecutableProduct: Bool {\n        self.isExecutable && !self.hasSourceTargets\n    }\n\n    var hasSourceTargets: Bool {\n        self.modules.anySatisfy { !$0.isBinary }\n    }\n\n    /// Returns the corresponding *system library* module, if this is a system library product.\n    var systemModule: SystemLibraryModule? {\n        guard self.isSystemLibraryProduct else { return nil }\n        return (self.modules.only?.underlying as! SystemLibraryModule)\n    }\n\n    /// Returns the corresponding *plugin* module, if this is a plugin product.\n    var pluginModules: [PackageModel.PluginModule]? {\n        guard self.type == .plugin else { return nil }\n        return self.modules.compactMap { $0.underlying as? PackageModel.PluginModule }\n    }\n\n    var c99name: String {\n        self.name.spm_mangledToC99ExtendedIdentifier()\n    }\n\n    var libraryType: ProductType.LibraryType? {\n        switch self.type {\n        case .library(let libraryType):\n            libraryType\n        default:\n            nil\n        }\n    }\n\n    /// Shoud we link this product dependency?\n    var isLinkable: Bool {\n        switch self.type {\n        case .library, .executable, .snippet, .test, .macro:\n            true\n        case .plugin:\n            false\n        }\n    }\n\n    /// Is this product dependency automatic?\n    var isAutomatic: Bool {\n        self.type == .library(.automatic)\n    }\n\n    var usesUnsafeFlags: Bool {\n        get throws {\n            try self.recursiveModuleDependencies().contains { $0.underlying.usesUnsafeFlags }\n        }\n    }\n}\n\nextension PackageGraph.ResolvedModule {\n    func recursivelyTraverseDependencies(with block: (ResolvedModule.Dependency) -> Void) {\n        [self].recursivelyTraverseDependencies(with: block)\n    }\n\n    func addParseAsLibrarySettings(to settings: inout BuildSettings, toolsVersion: ToolsVersion, fileSystem: FileSystem) {\n        if toolsVersion > .v5_5 && [.executable, .snippet, .macro].contains(self.type) {\n            let usesAtMainAttr = self.sources.paths.contains { sourcePath in\n                (try? containsAtMain(fileSystem: fileSystem, path: sourcePath)) ?? false\n            }\n            if usesAtMainAttr {\n                // Always pass -parse-as-library if @main is used\n                settings[.SWIFT_LIBRARIES_ONLY] = \"YES\"\n                settings[.SWIFT_DISABLE_PARSE_AS_LIBRARY] = \"NO\"\n            } else {\n                // Never pass -parse-as-library if @main isn't used, fall back to compiler heuristics\n                settings[.SWIFT_LIBRARIES_ONLY] = \"NO\"\n                settings[.SWIFT_DISABLE_PARSE_AS_LIBRARY] = \"YES\"\n            }\n        } else if [.library, .test].contains(self.type) {\n            // Always pass -parse-as-library for libraries and tests\n            settings[.SWIFT_LIBRARIES_ONLY] = \"YES\"\n            settings[.SWIFT_DISABLE_PARSE_AS_LIBRARY] = \"NO\"\n        }\n    }\n}\n\nextension Collection<PackageGraph.ResolvedModule> {\n    /// Recursively applies a block to each of the *dependencies* of the given module, in topological sort order.\n    /// Each module or product dependency is visited only once.\n    func recursivelyTraverseDependencies(with block: (ResolvedModule.Dependency) -> Void) {\n        var moduleIDsSeen: Set<ResolvedModule.ID> = []\n        var productIDsSeen: Set<ResolvedProduct.ID> = []\n\n        func visitDependency(_ dependency: ResolvedModule.Dependency) {\n            switch dependency {\n            case .module(let moduleDependency, _):\n                let (unseenModule, _) = moduleIDsSeen.insert(moduleDependency.id)\n                guard unseenModule else { return }\n\n                // Do not traverse into *macro* or *plugin* dependencies.\n                // Macros run at compile time and their dependencies should not be linked into the client.\n                // Plugins run at build time and their dependencies should not be linked into the client neither.\n                if ![.macro, .plugin].contains(moduleDependency.underlying.type) {\n                    for dependency in moduleDependency.dependencies {\n                        visitDependency(dependency)\n                    }\n                }\n                block(dependency)\n\n            case .product(let productDependency, let conditions):\n                let (unseenProduct, _) = productIDsSeen.insert(productDependency.id)\n                guard unseenProduct && !productDependency.isBinaryOnlyExecutableProduct else { return }\n                block(dependency)\n\n                // We need to visit any binary modules to be able to add direct references to them to any client targets.\n                // This is needed so that XCFramework processing always happens *prior* to building any client targets.\n                for moduleDependency in productDependency.modules where moduleDependency.isBinary {\n                    if moduleIDsSeen.contains(moduleDependency.id) { continue }\n                    block(.module(moduleDependency, conditions: conditions))\n                }\n            }\n        }\n\n        for dependency in self.flatMap(\\.dependencies) {\n            visitDependency(dependency)\n        }\n    }\n}\n\n// MARK: - SwiftPM TSCUtility Helpers\n\nextension TSCUtility.Version {\n    var isPrerelease: Bool {\n        !self.prereleaseIdentifiers.isEmpty\n    }\n\n    var hasBuildMetadata: Bool {\n        !self.buildMetadataIdentifiers.isEmpty\n    }\n\n    var stringRepresentation: String {\n        self.description\n    }\n}\n\n// MARK: - Swift Build ProjectModel Helpers\n\n/// Helpful for logging.\nextension ProjectModel.GUID: @retroactive CustomStringConvertible  {\n    public var description: String {\n        value\n    }\n}\n\nextension ProjectModel.BuildSettings {\n    subscript(_ setting: MultipleValueSetting, default defaultValue: [String]) -> [String] {\n        get { self[setting] ?? defaultValue }\n        set { self[setting] = newValue }\n    }\n}\n\n/// Helpers for building custom PIF targets by `PackagePIFBuilder` clients.\nextension ProjectModel.Project {\n    @discardableResult\n    public mutating func addTarget(\n        packageProductId: String,\n        packageProductName: String,\n        productType: ProjectModel.Target.ProductType\n    ) throws -> WritableKeyPath<ProjectModel.Project, ProjectModel.Target> {\n        let targetKeyPath = try self.addTarget { _ in\n            ProjectModel.Target(\n                id: PackagePIFBuilder.targetGUID(forProductName: packageProductName, withId: packageProductId),\n                productType: productType,\n                name: packageProductName,\n                productName: packageProductName\n            )\n        }\n        return targetKeyPath\n    }\n\n    @discardableResult\n    public mutating func addTarget(\n        packageModuleName: String,\n        productType: ProjectModel.Target.ProductType\n    ) throws -> WritableKeyPath<ProjectModel.Project, ProjectModel.Target> {\n        let targetKeyPath = try self.addTarget { _ in\n            ProjectModel.Target(\n                id: PackagePIFBuilder.targetGUID(forModuleName: packageModuleName),\n                productType: productType,\n                name: packageModuleName,\n                productName: packageModuleName\n            )\n        }\n        return targetKeyPath\n    }\n}\n\nextension ProjectModel.BuildSettings {\n    /// Internal helper function that appends list of string values to a declaration.\n    /// If a platform is specified, then the values are appended to the `platformSpecificSettings`,\n    /// otherwise they are appended to the platform-neutral settings.\n    ///\n    /// Note that this restricts the settings that can be set by this function to those that can have platform-specific\n    /// values, i.e. those in `ProjectModel.BuildSettings.Declaration`. If a platform is specified,\n    /// it must be one of the known platforms in `ProjectModel.BuildSettings.Platform`.\n}\n\n\nextension ProjectModel.BuildSettings.Platform {\n    enum Error: Swift.Error {\n        case unknownPlatform(String)\n    }\n\n    init(from platform: PackageModel.Platform) throws {\n        self = switch platform {\n        case .macOS: .macOS\n        case .macCatalyst: .macCatalyst\n        case .iOS: .iOS\n        case .tvOS: .tvOS\n        case .watchOS: .watchOS\n        case .visionOS: .xrOS\n        case .driverKit: .driverKit\n        case .linux: .linux\n        case .android: .android\n        case .windows: .windows\n        case .wasi: .wasi\n        case .openbsd: .openbsd\n        case .freebsd: .freebsd\n        default: throw Error.unknownPlatform(platform.name)\n        }\n    }\n}\n\nextension ProjectModel.BuildSettings {\n    /// Configure necessary settings for a dynamic library/framework.\n    mutating func configureDynamicSettings(\n        productName: String,\n        targetName: String,\n        packageIdentity: PackageIdentity,\n        packageName: String?,\n        createDylibForDynamicProducts: Bool,\n        installPath: String,\n        delegate: PackagePIFBuilder.BuildDelegate,\n    ) {\n        self[.TARGET_NAME] = targetName\n        self[.TARGET_TEMP_DIR_SUFFIX] = \"-t\"\n        self[.PRODUCT_NAME] = productName\n        self[.PRODUCT_MODULE_NAME] = productName\n        self[.PRODUCT_BUNDLE_IDENTIFIER] = \"\\(packageIdentity).\\(productName)\".spm_mangledToBundleIdentifier()\n        self[.SWIFT_PACKAGE_NAME] = packageName ?? nil\n\n        if createDylibForDynamicProducts {\n            // This should really be swift-build defaults set in the .xcspec files, but changing that requires\n            // some extensive testing to ensure xcode projects are not affected.\n            // So for now lets just force it here.\n            self[.EXECUTABLE_PREFIX] = \"lib\"\n            self[.EXECUTABLE_PREFIX, Platform.windows] = \"\"\n        }\n\n        if !createDylibForDynamicProducts {\n            self[.GENERATE_INFOPLIST_FILE] = \"YES\"\n            // If the built framework is named same as one of the target in the package,\n            // it can be picked up automatically during indexing since the build system always adds a -F flag\n            // to the built products dir.\n            // To avoid this problem, we build all package frameworks in a subdirectory.\n            self[.TARGET_BUILD_DIR] = \"$(TARGET_BUILD_DIR)/PackageFrameworks\"\n\n            // Set the project and marketing version for the framework because the app store requires these to be\n            // present.\n            // The AppStore requires bumping the project version when ingesting new builds but that's for top-level apps\n            // and not frameworks embedded inside it.\n            self[.MARKETING_VERSION] = \"1.0\" // Version\n            self[.CURRENT_PROJECT_VERSION] = \"1\" // Build\n        }\n\n        // Might set install path depending on build delegate.\n        if delegate.shouldSetInstallPathForDynamicLib(productName: productName) {\n            self[.SKIP_INSTALL] = \"NO\"\n            self[.INSTALL_PATH] = installPath\n        }\n    }\n}\n\nextension ProjectModel.BuildSettings.SingleValueSetting {\n    init?(from declaration: PackageModel.BuildSettings.Declaration) {\n        switch declaration {\n        case .SWIFT_VERSION:\n            self = .SWIFT_VERSION\n        default:\n            return nil\n        }\n    }\n}\n\nextension ProjectModel.BuildSettings.MultipleValueSetting {\n    init?(from declaration: PackageModel.BuildSettings.Declaration) {\n        switch declaration {\n        case .SWIFT_ACTIVE_COMPILATION_CONDITIONS:\n            self = .SWIFT_ACTIVE_COMPILATION_CONDITIONS\n        case .OTHER_SWIFT_FLAGS:\n            self = .OTHER_SWIFT_FLAGS\n        case .GCC_PREPROCESSOR_DEFINITIONS:\n            self = .GCC_PREPROCESSOR_DEFINITIONS\n        case .HEADER_SEARCH_PATHS:\n            self = .HEADER_SEARCH_PATHS\n        case .OTHER_CFLAGS:\n            self = .OTHER_CFLAGS\n        case .OTHER_CPLUSPLUSFLAGS:\n            self = .OTHER_CPLUSPLUSFLAGS\n        case .OTHER_LDFLAGS:\n            self = .OTHER_LDFLAGS\n        default:\n            return nil\n        }\n    }\n}\n\n// MARK: - ObservabilityScope Helpers\n\nextension ObservabilityScope {\n    /// Logs an informational PIF message (intended for developers, not end users).\n    func logPIF(\n        _ severity: Diagnostic.Severity = .debug,\n        indent: UInt = 0,\n        _ message: String,\n        sourceFile: StaticString = #fileID,\n        sourceLine: UInt = #line\n    ) {\n        var metadata = ObservabilityMetadata()\n        metadata.sourceLocation = SourceLocation(sourceFile, sourceLine)\n\n        let indentation = String(repeating: \"  \", count: Int(indent))\n        let message = \"PIF: \\(indentation)\\(message)\"\n\n        let diagnostic = Diagnostic(severity: severity, message: message, metadata: metadata)\n        self.emit(diagnostic)\n    }\n}\n\nextension ObservabilityMetadata {\n    public var sourceLocation: SourceLocation? {\n        get {\n            self[SourceLocationKey.self]\n        }\n        set {\n            self[SourceLocationKey.self] = newValue\n        }\n    }\n\n    private enum SourceLocationKey: Key {\n        typealias Value = SourceLocation\n    }\n}\n\npublic struct SourceLocation: Sendable {\n    public let file: StaticString\n    public let line: UInt\n\n    public init(_ file: StaticString, _ line: UInt) {\n        precondition(file.description.hasContent)\n\n        self.file = file\n        self.line = line\n    }\n}\n\n// MARK: - General Helpers\n\nextension SourceControlURL {\n    init(fileURLWithPath path: AbsolutePath) {\n        let fileURL = Foundation.URL(fileURLWithPath: path.pathString)\n        self.init(fileURL.description)\n    }\n}\n\nextension String {\n    /// Returns the path extension from a `String`.\n    var pathExtension: String {\n        (self as NSString).pathExtension\n    }\n}\n\nextension Optional {\n    func unwrap(\n        orAssert message: @autoclosure () -> String,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) -> Wrapped {\n        if let unwrapped = self {\n            unwrapped\n        } else {\n            fatalError(message(), file: file, line: line)\n        }\n    }\n\n    @discardableResult\n    mutating func lazilyInitialize(\n        _ initializer: () -> Wrapped\n    ) -> Wrapped {\n        if let result = self {\n            return result\n        } else {\n            let result = initializer()\n            self = .some(result)\n            return result\n        }\n    }\n\n    @discardableResult\n    mutating func lazilyInitializeAndMutate<R>(\n        initialValue initializer: @autoclosure () -> Wrapped,\n        mutator: (inout Wrapped) throws -> R\n    ) rethrows -> R {\n        if self == nil {\n            self = .some(initializer())\n        }\n        return try mutator(&self!)\n    }\n}\n\nextension Sequence {\n    /// Evaluates `predicate` on each element in the collection.\n    /// If exactly 1 element returns `true` return that element.\n    /// Returns the *only* element in the sequence satisfying the specified predicate.\n    ///\n    /// **Complexity**.  O(n), where n is the length of the sequence.\n    func only(where predicate: (Element) throws -> Bool) rethrows -> Element? {\n        var match: Element?\n        for candidate in self {\n            if try predicate(candidate) {\n                if match == nil {\n                    match = candidate\n                } else {\n                    return nil\n                }\n            }\n        }\n        return match\n    }\n}\n\nextension Collection {\n    /// Positive sense of `isEmpty`.\n    var hasContent: Bool {\n        !self.isEmpty\n    }\n\n    var only: Element? {\n        (count == 1) ? first : nil\n    }\n\n    func anySatisfy(_ predicate: (Element) throws -> Bool) rethrows -> Bool {\n        try contains(where: predicate)\n    }\n\n    /// For example: `people.sorted(on: \\.name)`.\n    func sorted(on projection: (Element) -> some Comparable) -> [Element] {\n        self.sorted(on: projection, by: <)\n    }\n\n    /// For example: `people.sorted(on: \\.name, comparator: >)`.\n    func sorted<T>(on projection: (Element) -> T, by comparator: (T, T) -> Bool) -> [Element] {\n        self.sorted { lhs, rhs in\n            comparator(projection(lhs), projection(rhs))\n        }\n    }\n}\n\nextension Array {\n    func prepending(_ newElement: Element) -> [Element] {\n        [newElement] + self\n    }\n}\n\nextension UserDefaults {\n    func bool(forKey key: String, defaultValue: Bool) -> Bool {\n        if self.object(forKey: key) != nil {\n            self.bool(forKey: key)\n        } else {\n            defaultValue\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PackagePIFBuilder+Plugins.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport protocol TSCBasic.FileSystem\n\nimport enum Basics.Sandbox\nimport struct Basics.AbsolutePath\nimport struct Basics.SourceControlURL\n\nimport enum SwiftBuild.ProjectModel\n\nextension PackagePIFBuilder {\n    /// Contains all of the information resulting from applying a build tool plugin to a package target thats affect how\n    /// a target is built.\n    ///\n    /// This includes any commands that should be incorporated into the build graph and all derived source files that\n    /// should be compiled\n    /// (i.e., those from prebuild commands as well as from the build commands).\n    public struct BuildToolPluginInvocationResult: Equatable {\n        /// Absolute paths of output files of any prebuild commands.\n        public let prebuildCommandOutputPaths: [AbsolutePath]\n\n        /// Build commands to incorporate into the dependency graph.\n        public let buildCommands: [CustomBuildCommand]\n\n        /// Absolute paths of all derived source files that should be compiled as sources of the target.\n        /// This includes the outputs of any prebuild commands as well as all the outputs referenced in all the build\n        /// commands.\n        public var allDerivedOutputPaths: [AbsolutePath] {\n            self.prebuildCommandOutputPaths + self.buildCommands.flatMap(\\.absoluteOutputPaths)\n        }\n\n        public init(\n            prebuildCommandOutputPaths: [AbsolutePath],\n            buildCommands: [CustomBuildCommand]\n        ) {\n            self.prebuildCommandOutputPaths = prebuildCommandOutputPaths\n            self.buildCommands = buildCommands\n        }\n    }\n\n    /// A command provided by a build tool plugin.\n    /// Build tool plugins are evaluated after package graph resolution (and subsequently, when conditions change).\n    ///\n    /// There are *two* basic kinds of build tool commands: prebuild commands and regular build commands.\n    public struct CustomBuildCommand: Equatable {\n        public var displayName: String?\n        public var executable: String\n        public var arguments: [String]\n        public var environment: [String: String]\n        public var workingDir: AbsolutePath?\n        public var inputPaths: [AbsolutePath] = []\n\n        /// Output paths can contain references with un-resolved paths (e.g. \"$(DERIVED_FILE_DIR)/myOutput.txt\")\n        public var outputPaths: [String] = []\n        public var absoluteOutputPaths: [AbsolutePath] {\n            self.outputPaths.compactMap { try? AbsolutePath(validating: $0) }\n        }\n\n        public var pluginOutputDir: AbsolutePath\n\n        public var sandboxProfile: SandboxProfile? = nil\n\n        public init(\n            displayName: String?,\n            executable: String,\n            arguments: [String],\n            environment: [String: String],\n            workingDir: AbsolutePath?,\n            inputPaths: [AbsolutePath],\n            outputPaths: [String],\n            pluginOutputDir: AbsolutePath,\n            sandboxProfile: SandboxProfile?\n        ) {\n            self.displayName = displayName\n            self.executable = executable\n            self.arguments = arguments\n            self.environment = environment\n            self.workingDir = workingDir\n            self.inputPaths = inputPaths\n            self.outputPaths = outputPaths\n            self.pluginOutputDir = pluginOutputDir\n            self.sandboxProfile = sandboxProfile\n        }\n    }\n\n    /// Represents a libSwiftPM sandbox profile that can be applied to a given command line.\n    public struct SandboxProfile: Equatable {\n        public var strictness: Sandbox.Strictness\n        public var writableDirectories: [AbsolutePath]\n        public var readOnlyDirectories: [AbsolutePath]\n\n        public init(\n            strictness: Sandbox.Strictness,\n            writableDirectories: [AbsolutePath],\n            readOnlyDirectories: [AbsolutePath]\n        ) {\n            self.strictness = strictness\n            self.writableDirectories = writableDirectories\n            self.readOnlyDirectories = readOnlyDirectories\n        }\n\n        init(writableDirectories: [AbsolutePath] = [], readOnlyDirectories: [AbsolutePath] = []) {\n            self.strictness = .writableTemporaryDirectory\n            self.writableDirectories = writableDirectories\n            self.readOnlyDirectories = readOnlyDirectories\n        }\n\n        public var writableDirectoryPathStrings: [String] {\n            self.writableDirectories.map(\\.pathString)\n        }\n\n        public var readOnlyDirectoryPathStrings: [String] {\n            self.readOnlyDirectories.map(\\.pathString)\n        }\n\n        /// Applies the sandbox profile to the given command line, and return the modified command line.\n        public func apply(to command: [String], fileSystem: FileSystem) throws -> [String] {\n            try Sandbox.apply(\n                command: command,\n                fileSystem: fileSystem,\n                strictness: self.strictness,\n                writableDirectories: self.writableDirectories,\n                readOnlyDirectories: self.readOnlyDirectories\n            )\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PackagePIFBuilder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport protocol TSCBasic.FileSystem\n\nimport struct Basics.AbsolutePath\nimport struct Basics.SourceControlURL\nimport struct Basics.Diagnostic\nimport struct Basics.ObservabilityMetadata\nimport class Basics.ObservabilityScope\n\nimport class PackageModel.Manifest\nimport class PackageModel.Package\nimport class PackageModel.Product\nimport struct PackageModel.Platform\nimport struct PackageModel.PlatformVersion\nimport enum PackageModel.PrebuiltsPlatform\nimport struct PackageModel.Resource\nimport struct PackageModel.PackageIdentity\nimport enum PackageModel.ProductType\n\nimport struct PackageGraph.ModulesGraph\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedPackage\n\nimport struct SPMBuildCore.BuildParameters\n\nimport enum SwiftBuild.ProjectModel\n\npublic typealias GUID = SwiftBuild.ProjectModel.GUID\ntypealias BuildFile = SwiftBuild.ProjectModel.BuildFile\ntypealias BuildConfig = SwiftBuild.ProjectModel.BuildConfig\ntypealias BuildSettings = SwiftBuild.ProjectModel.BuildSettings\ntypealias FileReference = SwiftBuild.ProjectModel.FileReference\n\n/// A builder for generating the PIF object from a package.\npublic final class PackagePIFBuilder {\n    let modulesGraph: ModulesGraph\n    private let package: ResolvedPackage\n\n    /// Contains the package declarative specification.\n    let packageManifest: PackageModel.Manifest // FIXME: Can't we just use `package.manifest` instead? —— Paulo\n\n    /// The built PIF project object.\n    public var pifProject: ProjectModel.Project {\n        assert(self._pifProject != nil, \"Call build() method to build the PIF first\")\n        return self._pifProject!\n    }\n\n    private var _pifProject: ProjectModel.Project?\n\n    /// Scope for logging informational debug messages (intended for developers, not end users).\n    let observabilityScope: ObservabilityScope\n\n    /// Logs an informational message (intended for developers, not end users).\n    func log(\n        _ severity: Diagnostic.Severity,\n        _ message: String,\n        sourceFile: StaticString = #fileID,\n        sourceLine: UInt = #line\n    ) {\n        self.observabilityScope.logPIF(severity, message, sourceFile: sourceFile, sourceLine: sourceLine)\n    }\n\n    unowned let delegate: BuildDelegate\n\n    public protocol BuildDelegate: AnyObject {\n        /// Is this the root package?\n        var isRootPackage: Bool { get }\n\n        /// Is this a remote package?\n        var isRemote: Bool { get }\n\n        // TODO: Maybe move these 3-4 properties to the `PIFBuilder.PIFBuilderParameters` struct.\n\n        /// If a pure Swift package is open in the workspace.\n        var hostsOnlyPackages: Bool { get }\n\n        /// Returns `true` if the package is managed by the user\n        /// (i.e., the user is allowed to modify its sources, package structure, etc).\n        var isUserManaged: Bool { get }\n\n        /// Whether or not this package is required by *branch* or *revision*.\n        var isBranchOrRevisionBased: Bool { get }\n\n        /// For executables — only executables for now — we check to see if there is a\n        /// custom package product type provider that can provide this information.\n        func customProductType(forExecutable product: PackageModel.Product) -> ProjectModel.Target.ProductType?\n\n        /// Returns all *device family* IDs for all SDK variants.\n        func deviceFamilyIDs() -> Set<Int>\n\n        /// Have packages referenced by this workspace build for *arm64e*\n        /// when building for iOS devices, macOS, and visionOS.\n        func shouldPackagesBuildForARM64e(platform: PackageModel.Platform) -> Bool\n\n        /// Is the sandbox disabled for plug-in execution? It should be `false` by default.\n        var isPluginExecutionSandboxingDisabled: Bool { get }\n\n        /// Hook to customize the project-wide build settings.\n        func configureProjectBuildSettings(_ buildSettings: inout ProjectModel.BuildSettings)\n\n        /// Hook to customize source module build settings.\n        func configureSourceModuleBuildSettings(\n            sourceModule: PackageGraph.ResolvedModule,\n            settings: inout ProjectModel.BuildSettings\n        )\n\n        /// Custom install path for the specified product, if any.\n        func customInstallPath(product: PackageModel.Product) -> String?\n\n        /// Custom executable name for the specified product, if any.\n        func customExecutableName(product: PackageModel.Product) -> String?\n\n        /// Custom library type for the specified product.\n        func customLibraryType(product: PackageModel.Product) -> PackageModel.ProductType.LibraryType?\n\n        /// Custom option for the specified platform.\n        func customSDKOptions(forPlatform: PackageModel.Platform) -> [String]\n\n        /// Create additional custom PIF targets after all targets have been built.\n        func addCustomTargets(pifProject: inout ProjectModel.Project) throws -> [PackagePIFBuilder.ModuleOrProduct]\n\n        /// Should we suppresses the specific product dependency, updating the provided build settings if necessary?\n        /// The specified product may be in the same package or a different one.\n        func shouldSuppressProductDependency(\n            product: PackageModel.Product,\n            buildSettings: inout ProjectModel.BuildSettings\n        ) -> Bool\n\n        /// Should we set the install path for a dynamic library/framework?\n        func shouldSetInstallPathForDynamicLib(productName: String) -> Bool\n\n        // FIXME: Let's try to replace `WritableKeyPath><_, Foo>` with `inout Foo` —— Paulo\n\n        /// Provides additional configuration and files for the specified library product.\n        func configureLibraryProduct(\n            product: PackageModel.Product,\n            project: inout ProjectModel.Project,\n            target: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n            additionalFiles: WritableKeyPath<ProjectModel.Group, ProjectModel.Group>\n        )\n\n        /// The design intention behind this is to set a value for `watchOS`, `tvOS`, and `visionOS`\n        /// that \"follows\" the aligned iOS version if they are not explicitly set.\n        ///\n        /// Prior to this enhancement, it was common to find packages which worked perfectly fine on `watchOS`\n        /// aside from the one issue where developers failed to specify the correct deployment target.\n        ///\n        /// See: rdar://144661020 (SwiftPM PIFBuilder — compute unset deployment targets).\n        func suggestAlignedPlatformVersionGiveniOSVersion(platform: PackageModel.Platform, iOSVersion: PlatformVersion)\n            -> String?\n\n        /// Validates the specified macro fingerprint. Each remote package has a fingerprint.\n        func validateMacroFingerprint(for macroModule: ResolvedModule) -> Bool\n    }\n\n    /// Records the results of applying build tool plugins to modules in the package.\n    let buildToolPluginResultsByTargetName: [String: [PackagePIFBuilder.BuildToolPluginInvocationResult]]\n\n    /// Whether to create dynamic libraries for dynamic products.\n    ///\n    /// This tracks removing this *user default* once clients stop relying on this implementation detail:\n    /// * <rdar://56889224> Remove IDEPackageSupportCreateDylibsForDynamicProducts.\n    let createDylibForDynamicProducts: Bool\n\n    /// When building a static library product for a root package, ensure the final build product is always materialized.\n    /// In other words, don't represent it using the `packageProduct` target type which only allows other targets\n    /// built from source in the same build to consume it without eagerly linking it into a product.\n    let materializeStaticArchiveProductsForRootPackages: Bool\n\n    /// Create dynamic library variants for automatic library products, for use by development-time features such as Previews and Swift Playgrounds.\n    let createDynamicVariantsForLibraryProducts: Bool\n\n    /// Add rpaths which allow loading libraries adjacent to the current image at runtime. This is desirable\n    /// when launching build products from the build directory, but should often be disabled when deploying\n    /// the build products to a different location.\n    let addLocalRpaths: Bool\n\n    /// Package display version, if any (i.e., it can be a version, branch or a git ref).\n    let packageDisplayVersion: String?\n\n    let pkgConfigDirectories: [AbsolutePath]\n\n    /// The file system to read from.\n    let fileSystem: FileSystem\n\n    /// Whether to suppress warnings from compilers, linkers, and other build tools for package dependencies.\n    private var suppressWarningsForPackageDependencies: Bool {\n        UserDefaults.standard.bool(forKey: \"SuppressWarningsForPackageDependencies\", defaultValue: true)\n    }\n\n    /// Whether to skip running the static analyzer for package dependencies.\n    private var skipStaticAnalyzerForPackageDependencies: Bool {\n        UserDefaults.standard.bool(forKey: \"SkipStaticAnalyzerForPackageDependencies\", defaultValue: true)\n    }\n\n    public static func computePackageProductFrameworkName(productName: String) -> String {\n        \"\\(productName)_\\(String(productName.hash, radix: 16, uppercase: true))_PackageProduct\"\n    }\n\n    public init(\n        modulesGraph: ModulesGraph,\n        resolvedPackage: ResolvedPackage,\n        packageManifest: PackageModel.Manifest,\n        delegate: PackagePIFBuilder.BuildDelegate,\n        buildToolPluginResultsByTargetName: [String: [BuildToolPluginInvocationResult]],\n        createDylibForDynamicProducts: Bool = false,\n        materializeStaticArchiveProductsForRootPackages: Bool = false,\n        createDynamicVariantsForLibraryProducts: Bool = true,\n        addLocalRpaths: Bool = true,\n        packageDisplayVersion: String?,\n        pkgConfigDirectories: [AbsolutePath],\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n    ) {\n        self.package = resolvedPackage\n        self.packageManifest = packageManifest\n        self.modulesGraph = modulesGraph\n        self.delegate = delegate\n        self.buildToolPluginResultsByTargetName = buildToolPluginResultsByTargetName\n        self.createDylibForDynamicProducts = createDylibForDynamicProducts\n        self.materializeStaticArchiveProductsForRootPackages = materializeStaticArchiveProductsForRootPackages\n        self.createDynamicVariantsForLibraryProducts = createDynamicVariantsForLibraryProducts\n        self.packageDisplayVersion = packageDisplayVersion\n        self.pkgConfigDirectories = pkgConfigDirectories\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n        self.addLocalRpaths = addLocalRpaths\n    }\n\n    public init(\n        modulesGraph: ModulesGraph,\n        resolvedPackage: ResolvedPackage,\n        packageManifest: PackageModel.Manifest,\n        delegate: PackagePIFBuilder.BuildDelegate,\n        buildToolPluginResultsByTargetName: [String: BuildToolPluginInvocationResult],\n        createDylibForDynamicProducts: Bool = false,\n        materializeStaticArchiveProductsForRootPackages: Bool = false,\n        createDynamicVariantsForLibraryProducts: Bool = true,\n        addLocalRpaths: Bool = true,\n        packageDisplayVersion: String?,\n        pkgConfigDirectories: [AbsolutePath],\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n    ) {\n        self.package = resolvedPackage\n        self.packageManifest = packageManifest\n        self.modulesGraph = modulesGraph\n        self.delegate = delegate\n        self.buildToolPluginResultsByTargetName = buildToolPluginResultsByTargetName.mapValues { [$0] }\n        self.createDylibForDynamicProducts = createDylibForDynamicProducts\n        self.materializeStaticArchiveProductsForRootPackages = materializeStaticArchiveProductsForRootPackages\n        self.createDynamicVariantsForLibraryProducts = createDynamicVariantsForLibraryProducts\n        self.addLocalRpaths = addLocalRpaths\n        self.packageDisplayVersion = packageDisplayVersion\n        self.pkgConfigDirectories = pkgConfigDirectories\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope\n    }\n\n    /// Build an empty PIF project.\n    public func buildEmptyPIF() {\n        self._pifProject = PackagePIFBuilder.buildEmptyPIF(package: self.package.underlying)\n    }\n\n    /// Build an empty PIF project for the specified `Package`.\n\n    public class func buildEmptyPIF(package: PackageModel.Package) -> ProjectModel.Project {\n        self.buildEmptyPIF(\n            id: \"PACKAGE:\\(package.identity)\",\n            path: package.manifest.path.pathString,\n            projectDir: package.path.pathString,\n            name: package.name,\n            developmentRegion: package.manifest.defaultLocalization\n        )\n    }\n\n    /// Build an empty PIF project.\n    public class func buildEmptyPIF(\n        id: String,\n        path: String,\n        projectDir: String,\n        name: String,\n        developmentRegion: String? = nil\n    ) -> ProjectModel.Project {\n        var project = ProjectModel.Project(\n            id: GUID(id),\n            path: path,\n            projectDir: projectDir,\n            name: name,\n            developmentRegion: developmentRegion\n        )\n        let settings = ProjectModel.BuildSettings()\n\n        project.addBuildConfig { id in ProjectModel.BuildConfig(id: id, name: \"Debug\", settings: settings) }\n        project.addBuildConfig { id in ProjectModel.BuildConfig(id: id, name: \"Release\", settings: settings) }\n\n        return project\n    }\n\n    public func buildPlaceholderPIF(id: String, path: String, projectDir: String, name: String) -> ModuleOrProduct {\n        var project = ProjectModel.Project(\n            id: GUID(id),\n            path: path,\n            projectDir: projectDir,\n            name: name\n        )\n\n        let projectSettings = ProjectModel.BuildSettings()\n\n        project.addBuildConfig { id in ProjectModel.BuildConfig(id: id, name: \"Debug\", settings: projectSettings) }\n        project.addBuildConfig { id in ProjectModel.BuildConfig(id: id, name: \"Release\", settings: projectSettings) }\n\n        let targetKeyPath = try! project.addAggregateTarget { _ in\n            ProjectModel.AggregateTarget(id: \"PACKAGE-PLACEHOLDER:\\(id)\", name: id)\n        }\n        let targetSettings: ProjectModel.BuildSettings = self.package.underlying.packageBaseBuildSettings\n\n        project[keyPath: targetKeyPath].common.addBuildConfig { id in\n            ProjectModel.BuildConfig(id: id, name: \"Debug\", settings: targetSettings)\n        }\n        project[keyPath: targetKeyPath].common.addBuildConfig { id in\n            ProjectModel.BuildConfig(id: id, name: \"Release\", settings: targetSettings)\n        }\n\n        self._pifProject = project\n\n        let placeholderModule = ModuleOrProduct(\n            type: .placeholder,\n            name: name,\n            moduleName: name,\n            pifTarget: .aggregate(project[keyPath: targetKeyPath]),\n            indexableFileURLs: [],\n            headerFiles: [],\n            linkedPackageBinaries: [],\n            swiftLanguageVersion: nil,\n            declaredPlatforms: nil,\n            deploymentTargets: nil\n        )\n        return placeholderModule\n    }\n\n    // FIXME: Maybe break this up in a `ArtifactMetadata` protocol and two value types —— Paulo\n    // Like `ProductMetadata` and also `ModuleMetadata`.\n\n    /// Value type with information about a given PIF module or product.\n    public struct ModuleOrProduct {\n        public var type: ModuleOrProductType\n        public var name: String\n        public var moduleName: String?\n        public var isDynamicLibraryVariant: Bool = false\n\n        public var pifTarget: ProjectModel.BaseTarget?\n\n        public var indexableFileURLs: [SourceControlURL]\n        public var headerFiles: Set<AbsolutePath>\n        public var linkedPackageBinaries: [LinkedPackageBinary]\n\n        public var swiftLanguageVersion: String?\n\n        public var declaredPlatforms: [PackageModel.Platform]?\n        public var deploymentTargets: [PackageModel.Platform: String?]?\n    }\n\n    public struct LinkedPackageBinary {\n        public let name: String\n        public let type: BinaryType\n        public let packageIdentity: PackageIdentity\n\n        @frozen\n        public enum BinaryType {\n            case product\n            case target\n        }\n\n        public init(product: String, packageIdentity: PackageIdentity) {\n            self.name = product\n            self.type = .product\n            self.packageIdentity = packageIdentity\n        }\n\n        public init(module: String, packageIdentity: PackageIdentity) {\n            self.name = module\n            self.type = .target\n            self.packageIdentity = packageIdentity\n        }\n    }\n\n    public enum ModuleOrProductType: String, Sendable, CustomStringConvertible {\n        // Products.\n        case application\n        case staticArchive\n        case commonObject\n        case dynamicLibrary\n        case framework\n        case executable\n        case unitTest\n        case unitTestRunner\n        case bundle\n        case resourceBundle\n        case packageProduct\n        case commandPlugin\n        case buildToolPlugin\n\n        // Modules.\n        case module\n        case plugin\n        case macro\n        case placeholder\n\n        public var description: String { rawValue }\n\n        init(from pifProductType: ProjectModel.Target.ProductType) {\n            self = switch pifProductType {\n            case .application: .application\n            case .commonStaticArchive: .staticArchive\n            case .staticArchive: .staticArchive\n            case .commonObject: .commonObject\n            case .objectFile: .commonObject\n            case .dynamicLibrary: .dynamicLibrary\n            case .framework: .framework\n            case .executable: .executable\n            case .unitTest: .unitTest\n            case .swiftpmTestRunner: .unitTestRunner\n            case .bundle: .bundle\n            case .packageProduct: .packageProduct\n            case .hostBuildTool: fatalError(\"Unexpected hostBuildTool type\")\n            @unknown default:\n                fatalError(\"Unknown product type: \\(pifProductType)\")\n            }\n        }\n    }\n\n    /// Build the PIF.\n    @discardableResult\n    public func build() throws -> [ModuleOrProduct] {\n        self.log(\n            .info,\n            \"Building PIF project for package '\\(self.package.identity)' \" +\n            \"(\\(package.products.count) products, \\(package.modules.count) modules)\"\n        )\n\n        var projectBuilder = PackagePIFProjectBuilder(createForPackage: package, builder: self)\n        self.addProjectBuildSettings(&projectBuilder)\n\n        //\n        // Construct PIF *targets* (for modules, products, and test bundles) based on the contents\n        // of the parsed package. These PIF targets will be sent down to Swift Build.\n        //\n        // We also track all constructed objects as `ModuleOrProduct` value for easy introspection by clients.\n        // In SwiftPM a product is a codeless entity with a reference to the modules(s) that contains the\n        // implementation. In order to avoid creating two ModuleOrProducts for each product in the package,\n        // the logic below creates a single unified ModuleOrProduct from the combination of a product\n        // and the single target that contains its implementation.\n        //\n        // Products. SwiftPM considers unit tests to be products, so in this discussion, the term *product*\n        // refers to an *executable*, a *library*, or an *unit test*.\n        //\n        // Automatic libraries. The current implementation treats all automatic libraries as *static*;\n        // in the future, we will want to do more holistic analysis so that the decision about whether\n        // or not to build a separate dynamic library for a package library product takes into account\n        // the structure of the client(s).\n        //\n\n        self.log(.debug, \"Processing \\(package.products.count) products:\")\n\n        // For each of the **products** in the package we create a corresponding `PIFTarget` of the appropriate type.\n        for product in self.package.products {\n            switch product.type {\n            case .library(.static):\n                let libraryType = self.delegate.customLibraryType(product: product.underlying) ?? .static\n                try projectBuilder.makeLibraryProduct(product, type: libraryType)\n\n            case .library(.dynamic):\n                let libraryType = self.delegate.customLibraryType(product: product.underlying) ?? .dynamic\n                try projectBuilder.makeLibraryProduct(product, type: libraryType)\n\n            case .library(.automatic):\n                // Check if this is a system library product.\n                if product.isSystemLibraryProduct {\n                    try projectBuilder.makeSystemLibraryProduct(product)\n                } else {\n                    // Otherwise, it is a regular library product.\n                    let libraryType = self.delegate.customLibraryType(product: product.underlying) ?? .automatic\n                    try projectBuilder.makeLibraryProduct(product, type: libraryType)\n                }\n\n            case .executable, .test, .snippet:\n                try projectBuilder.makeMainModuleProduct(product)\n\n            case .plugin:\n                try projectBuilder.makePluginProduct(product)\n\n            case .macro:\n                break // TODO: Double-check what's going on here as we skip snippet modules too (rdar://147705448)\n            }\n        }\n\n        self.log(.debug, \"Processing \\(package.modules.count) modules:\")\n\n        // For each of the **modules** in the package other than those that are the *main* module of a product\n        // —— which we've already dealt with above —— we create a corresponding `PIFTarget` of the appropriate type.\n        for module in self.package.modules {\n            switch module.type {\n            case .executable:\n                try projectBuilder.makeTestableExecutableSourceModule(module)\n\n            case .snippet:\n                // Already handled as a product. Note that snippets don't need testable modules.\n                break\n\n            case .library:\n                try projectBuilder.makeLibraryModule(module)\n\n            case .systemModule:\n                try projectBuilder.makeSystemLibraryModule(module)\n\n            case .test:\n                // Skip test module targets.\n                // They will have been dealt with as part of the *products* to which they belong.\n                break\n\n            case .binary:\n                // Skip binary module targets.\n                break\n\n            case .plugin:\n                try projectBuilder.makePluginModule(module)\n\n            case .macro:\n                try projectBuilder.makeMacroModule(module)\n            }\n        }\n\n        let customModulesAndProducts = try delegate.addCustomTargets(pifProject: &projectBuilder.project)\n        projectBuilder.builtModulesAndProducts.append(contentsOf: customModulesAndProducts)\n\n        try projectBuilder.makePackageTestProduct()\n\n        self._pifProject = projectBuilder.project\n        return projectBuilder.builtModulesAndProducts\n    }\n\n    /// Configure the project-wide build settings.\n    /// First we set those that are in common between the \"Debug\" and \"Release\" configurations, and then we set those\n    /// that are different.\n    private func addProjectBuildSettings(_ builder: inout PackagePIFProjectBuilder) {\n        var settings = ProjectModel.BuildSettings()\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        settings[.SUPPORTED_PLATFORMS] = [\"$(AVAILABLE_PLATFORMS)\"]\n        settings[.SKIP_INSTALL] = \"YES\"\n        settings[.MACOSX_DEPLOYMENT_TARGET] = builder.deploymentTargets[.macOS] ?? nil\n        settings[.IPHONEOS_DEPLOYMENT_TARGET] = builder.deploymentTargets[.iOS] ?? nil\n        if let deploymentTarget_macCatalyst = builder.deploymentTargets[.macCatalyst] ?? nil {\n            settings[.IPHONEOS_DEPLOYMENT_TARGET, .macCatalyst] = deploymentTarget_macCatalyst\n        }\n        settings[.TVOS_DEPLOYMENT_TARGET] = builder.deploymentTargets[.tvOS] ?? nil\n        settings[.WATCHOS_DEPLOYMENT_TARGET] = builder.deploymentTargets[.watchOS] ?? nil\n        settings[.DRIVERKIT_DEPLOYMENT_TARGET] = builder.deploymentTargets[.driverKit] ?? nil\n        settings[.XROS_DEPLOYMENT_TARGET] = builder.deploymentTargets[.visionOS] ?? nil\n\n        for machoPlatform: ProjectModel.BuildSettings.Platform in [ProjectModel.BuildSettings.Platform.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .xrOS, .driverKit] {\n            settings[.DYLIB_INSTALL_NAME_BASE, machoPlatform] = \"@rpath\"\n            settings[.CLANG_ENABLE_MODULES, machoPlatform] = \"YES\"\n        }\n\n        settings[.USE_HEADERMAP] = \"NO\"\n        settings[.OTHER_SWIFT_FLAGS].lazilyInitializeAndMutate(initialValue: [\"$(inherited)\"]) { $0.append(\"-DXcode\") }\n\n        // TODO: Might be relevant to make customizable —— Paulo\n        // (If we want to be extra careful with differences to the existing PIF in the SwiftPM.)\n        settings[.OTHER_CFLAGS] = [\"$(inherited)\", \"-DXcode\"]\n\n        if self.delegate.isRemote {\n            if self.suppressWarningsForPackageDependencies {\n                settings[.SUPPRESS_WARNINGS] = \"YES\"\n            }\n            if self.skipStaticAnalyzerForPackageDependencies {\n                settings[.SKIP_CLANG_STATIC_ANALYZER] = \"YES\"\n            }\n        }\n        settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS]\n            .lazilyInitializeAndMutate(initialValue: [\"$(inherited)\"]) { $0.append(\"SWIFT_PACKAGE\") }\n        settings[.GCC_PREPROCESSOR_DEFINITIONS] = [\"$(inherited)\", \"SWIFT_PACKAGE\"]\n        settings[.KEEP_PRIVATE_EXTERNS] = \"NO\"\n\n        // We currently deliberately do not support Swift ObjC interface headers.\n        settings[.SWIFT_INSTALL_OBJC_HEADER] = \"NO\"\n        settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME] = \"\"\n\n        // rdar://47937899 (Don't try to link frameworks to object files)\n        //  - looks like this defaults to OTHER_LDFLAGS (via xcspec) which can result in linking frameworks to mh_objects which is unwanted.\n        settings[.OTHER_LDRFLAGS] = []\n\n        // Packages use the SwiftPM workspace's cache directory as a compiler working directory to maximize module\n        // sharing.\n        settings[.COMPILER_WORKING_DIRECTORY] = \"$(WORKSPACE_DIR)\"\n\n        // Defer to the build system for linker driver selection.\n        settings[.LINKER_DRIVER] = \"auto\"\n\n        // Hook to customize the project-wide build settings.\n        self.delegate.configureProjectBuildSettings(&settings)\n\n        for (platform, platformOptions) in self.package.sdkOptions(delegate: self.delegate) {\n            guard let pifPlatform = try? ProjectModel.BuildSettings.Platform(from: platform) else {\n                log(.warning, \"Ignoring options '\\(platformOptions.joined(separator: \" \"))' specified for unknown platform \\(platform.name)\")\n                continue\n            }\n            settings[.SPECIALIZATION_SDK_OPTIONS, pifPlatform] = (settings[.SPECIALIZATION_SDK_OPTIONS, pifPlatform] ?? []) + platformOptions\n        }\n\n        let deviceFamilyIDs: Set<Int> = self.delegate.deviceFamilyIDs()\n        settings[.TARGETED_DEVICE_FAMILY] = deviceFamilyIDs.sorted().map { String($0) }.joined(separator: \",\")\n\n        // This will add the XCTest related search paths automatically,\n        // including the Swift overlays.\n        settings[.ENABLE_TESTING_SEARCH_PATHS] = \"YES\"\n\n        // Disable signing for all the things since there is no way\n        // to configure signing information in packages right now.\n        settings[.ENTITLEMENTS_REQUIRED] = \"NO\"\n        settings[.CODE_SIGNING_REQUIRED] = \"NO\"\n        settings[.CODE_SIGN_IDENTITY] = \"\"\n\n        // If in a workspace that's set to build packages for _arm64e_, pass that along to Swift Build.\n        let arm64ePlatforms: [PackageModel.Platform] = [.iOS, .macOS, .visionOS]\n        for arm64ePlatform in arm64ePlatforms {\n            if self.delegate.shouldPackagesBuildForARM64e(platform: arm64ePlatform) {\n                let pifPlatform: ProjectModel.BuildSettings.Platform\n                do {\n                    pifPlatform = try .init(from: arm64ePlatform)\n                } catch {\n                    preconditionFailure(\"Unhandled arm64e platform: \\(error)\")\n                }\n                settings[.ARCHS, pifPlatform] = (settings[.ARCHS, pifPlatform] ?? []) + [\"arm64e\"]\n            }\n        }\n\n        // Add the build settings that are specific to debug builds, and set those as the \"Debug\" configuration.\n        var debugSettings = settings\n        debugSettings[.COPY_PHASE_STRIP] = \"NO\"\n        debugSettings[.DEBUG_INFORMATION_FORMAT] = \"dwarf\"\n        debugSettings[.ENABLE_NS_ASSERTIONS] = \"YES\"\n        debugSettings[.GCC_OPTIMIZATION_LEVEL] = \"0\"\n        debugSettings[.ONLY_ACTIVE_ARCH] = \"YES\"\n        debugSettings[.SWIFT_OPTIMIZATION_LEVEL] = \"-Onone\"\n        debugSettings[.ENABLE_TESTABILITY] = \"YES\"\n        debugSettings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, default: []].append(contentsOf: [\"DEBUG\"])\n        debugSettings[.GCC_PREPROCESSOR_DEFINITIONS, default: [\"$(inherited)\"]].append(contentsOf: [\"DEBUG=1\"])\n        debugSettings[.SWIFT_INDEX_STORE_ENABLE] = \"YES\"\n        builder.project.addBuildConfig { id in BuildConfig(id: id, name: \"Debug\", settings: debugSettings) }\n\n        // Add the build settings that are specific to release builds, and set those as the \"Release\" configuration.\n        var releaseSettings = settings\n        releaseSettings[.COPY_PHASE_STRIP] = \"YES\"\n        releaseSettings[.DEBUG_INFORMATION_FORMAT] = \"dwarf-with-dsym\"\n        releaseSettings[.GCC_OPTIMIZATION_LEVEL] = \"s\"\n        releaseSettings[.SWIFT_OPTIMIZATION_LEVEL] = \"-Owholemodule\"\n        releaseSettings[.DEPLOYMENT_POSTPROCESSING] = \"YES\"\n        builder.project.addBuildConfig { id in BuildConfig(id: id, name: \"Release\", settings: releaseSettings) }\n    }\n\n    private enum SourceModuleType {\n        case dynamicLibrary\n        case staticLibrary\n        case executable\n        case macro\n    }\n\n    struct EmbedResourcesResult {\n        let bundleName: String?\n        let shouldGenerateBundleAccessor: Bool\n        let shouldGenerateEmbedInCodeAccessor: Bool\n    }\n\n    struct Resource {\n        let path: String\n        let rule: PackageModel.Resource.Rule\n\n        init(path: String, rule: PackageModel.Resource.Rule) {\n            self.path = path\n            self.rule = rule\n        }\n\n        init(_ resource: PackageModel.Resource) {\n            self.path = resource.path.pathString\n            self.rule = resource.rule\n        }\n    }\n}\n\n// MARK: - Helpers\n\nextension PackagePIFBuilder.ModuleOrProduct {\n    public init(\n        type moduleOrProductType: PackagePIFBuilder.ModuleOrProductType,\n        name: String,\n        moduleName: String?,\n        pifTarget: ProjectModel.BaseTarget?,\n        indexableFileURLs: [SourceControlURL] = [],\n        headerFiles: Set<AbsolutePath> = [],\n        linkedPackageBinaries: [PackagePIFBuilder.LinkedPackageBinary] = [],\n        swiftLanguageVersion: String? = nil,\n        declaredPlatforms: [PackageModel.Platform]? = [],\n        deploymentTargets: [PackageModel.Platform: String?]? = [:]\n    ) {\n        self.type = moduleOrProductType\n        self.name = name\n        self.moduleName = moduleName\n        self.pifTarget = pifTarget\n        self.indexableFileURLs = indexableFileURLs\n        self.headerFiles = headerFiles\n        self.linkedPackageBinaries = linkedPackageBinaries\n        self.swiftLanguageVersion = swiftLanguageVersion\n        self.declaredPlatforms = declaredPlatforms\n        self.deploymentTargets = deploymentTargets\n    }\n}\n\nenum PIFBuildingError: Error {\n    case packageExtensionFeatureNotEnabled\n}\n\nextension PackagePIFBuilder.LinkedPackageBinary {\n    init?(module: ResolvedModule) {\n        switch module.type {\n        case .executable, .snippet, .test:\n            self.init(product: module.name, packageIdentity: module.packageIdentity)\n\n        case .library, .binary, .macro:\n            self.init(module: module.name, packageIdentity: module.packageIdentity)\n\n        case .systemModule, .plugin:\n            return nil\n        }\n    }\n\n    init?(dependency: ResolvedModule.Dependency) {\n        switch dependency {\n        case .product(let productDependency, _):\n            guard productDependency.hasSourceTargets else { return nil }\n            self.init(product: productDependency.name, packageIdentity: productDependency.packageIdentity)\n\n        case .module(let moduleDependency, _):\n            self.init(module: moduleDependency)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PackagePIFProjectBuilder+Modules.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport TSCUtility\n\nimport struct Basics.AbsolutePath\nimport struct Basics.RelativePath\nimport class Basics.ObservabilitySystem\nimport func Basics.resolveSymlinks\nimport struct Basics.SourceControlURL\n\nimport class PackageModel.Manifest\nimport class PackageModel.Module\nimport class PackageModel.BinaryModule\nimport enum PackageModel.PrebuiltsPlatform\nimport class PackageModel.Product\nimport class PackageModel.SystemLibraryModule\n\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedPackage\n\nimport struct PackageLoading.GeneratedFiles\n\nimport enum SwiftBuild.ProjectModel\n\n/// Extension to create PIF **modules** for a given package.\nextension PackagePIFProjectBuilder {\n    // MARK: - Plugin Modules\n\n    mutating func makePluginModule(_ pluginModule: PackageGraph.ResolvedModule) throws {\n        precondition(pluginModule.type == .plugin)\n\n        // Create an executable PIF target in order to get specialization.\n        let pluginTargetKeyPath = try self.project.addTarget { _ in\n            ProjectModel.Target(\n                id: pluginModule.pifTargetGUID,\n                productType: .hostBuildTool,\n                name: pluginModule.name,\n                productName: pluginModule.name\n            )\n        }\n        do {\n            let pluginTarget = self.project[keyPath: pluginTargetKeyPath]\n            log(\n                .debug,\n                \"Created target '\\(pluginTarget.id)' of type \" +\n                \"\\(pluginTarget.productType) and name '\\(pluginTarget.name)'\"\n            )\n        }\n\n        var buildSettings: ProjectModel.BuildSettings = self.package.underlying.packageBaseBuildSettings\n\n        // Add the dependencies.\n        pluginModule.recursivelyTraverseDependencies { dependency in\n            switch dependency {\n            case .module(let moduleDependency, let packageConditions):\n                // This assertion is temporarily disabled since we may see targets from\n                // _other_ packages, but this should be resolved; see rdar://95467710.\n                /* assert(moduleDependency.packageName == self.package.name) */\n\n                let dependencyPlatformFilters = packageConditions\n                    .toPlatformFilter(toolsVersion: self.package.manifest.toolsVersion)\n\n                switch moduleDependency.type {\n                case .executable, .snippet:\n                    // For executable targets, add a build time dependency on the product.\n                    // FIXME: Maybe we should we do this at the libSwiftPM level.\n                    let moduleProducts = self.package.products.filter(\\.isMainModuleProduct)\n                    let productDependency = moduleDependency\n                        .productRepresentingDependencyOfBuildPlugin(in: moduleProducts)\n\n                    if let productDependency {\n                        self.project[keyPath: pluginTargetKeyPath].common.addDependency(\n                            on: productDependency.pifTargetGUID,\n                            platformFilters: dependencyPlatformFilters\n                        )\n                        log(.debug, indent: 1, \"Added dependency on product '\\(productDependency.pifTargetGUID)'\")\n                    } else {\n                        log(\n                            .debug,\n                            indent: 1,\n                            \"Could not find a build plugin product to depend on for target '\\(moduleDependency.pifTargetGUID)'\"\n                        )\n                    }\n\n                case .library, .systemModule, .test, .binary, .plugin, .macro:\n                    let dependencyGUID = moduleDependency.pifTargetGUID\n                    self.project[keyPath: pluginTargetKeyPath].common.addDependency(\n                        on: dependencyGUID,\n                        platformFilters: dependencyPlatformFilters\n                    )\n                    log(.debug, indent: 1, \"Added dependency on target '\\(dependencyGUID)'\")\n                }\n\n            case .product(let productDependency, let packageConditions):\n                // Do not add a dependency for binary-only executable products since they are not part of the build.\n                if productDependency.isBinaryOnlyExecutableProduct {\n                    break\n                }\n\n                if !pifBuilder.delegate.shouldSuppressProductDependency(\n                    product: productDependency.underlying,\n                    buildSettings: &buildSettings\n                ) {\n                    let dependencyGUID = productDependency.pifTargetGUID\n                    let dependencyPlatformFilters = packageConditions\n                        .toPlatformFilter(toolsVersion: self.package.manifest.toolsVersion)\n\n                    self.project[keyPath: pluginTargetKeyPath].common.addDependency(\n                        on: dependencyGUID,\n                        platformFilters: dependencyPlatformFilters\n                    )\n                    log(.debug, indent: 1, \"Added dependency on product '\\(dependencyGUID)'\")\n                }\n            }\n        }\n\n        // Any dependencies of plugin targets need to be built for the host.\n        buildSettings[.SUPPORTED_PLATFORMS] = [\"$(HOST_PLATFORM)\"]\n\n        self.project[keyPath: pluginTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Debug\", settings: buildSettings)\n        }\n        self.project[keyPath: pluginTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Release\", settings: buildSettings)\n        }\n\n        let pluginModuleMetadata = PackagePIFBuilder.ModuleOrProduct(\n            type: .plugin,\n            name: pluginModule.name,\n            moduleName: pluginModule.name,\n            pifTarget: .target(self.project[keyPath: pluginTargetKeyPath]),\n            indexableFileURLs: [],\n            headerFiles: [],\n            linkedPackageBinaries: [],\n            swiftLanguageVersion: nil,\n            declaredPlatforms: self.declaredPlatforms,\n            deploymentTargets: self.deploymentTargets\n        )\n        self.builtModulesAndProducts.append(pluginModuleMetadata)\n    }\n\n    // MARK: - Macro Modules\n\n    mutating func makeMacroModule(_ macroModule: PackageGraph.ResolvedModule) throws {\n        precondition(macroModule.type == .macro)\n\n        let (builtMacroModule, _) = try buildSourceModule(macroModule, type: .macro)\n        self.builtModulesAndProducts.append(builtMacroModule)\n\n        // We also create a testable version of the macro, similar to what we're doing for regular executable targets.\n        let (builtTestableMacroModule, _) = try buildSourceModule(\n            macroModule,\n            type: .executable,\n            targetSuffix: .testable\n        )\n        self.builtModulesAndProducts.append(builtTestableMacroModule)\n    }\n\n    // MARK: - Library Modules\n\n    // Build a *static library* that can be linked together into other products.\n    mutating func makeLibraryModule(_ libraryModule: PackageGraph.ResolvedModule) throws {\n        precondition(libraryModule.type == .library)\n\n        let (staticLibrary, resourceBundleName) = try buildSourceModule(libraryModule, type: .staticLibrary)\n        self.builtModulesAndProducts.append(staticLibrary)\n\n        if self.shouldOfferDynamicTarget(libraryModule.name) {\n            var (dynamicLibraryVariant, _) = try buildSourceModule(\n                libraryModule,\n                type: .dynamicLibrary,\n                targetSuffix: .dynamic,\n                addBuildToolPluginCommands: false,\n                inputResourceBundleName: resourceBundleName\n            )\n            dynamicLibraryVariant.isDynamicLibraryVariant = true\n            self.builtModulesAndProducts.append(dynamicLibraryVariant)\n\n            guard let pifTarget = staticLibrary.pifTarget,\n                  let pifTargetKeyPath = self.project.findTarget(id: pifTarget.id),\n                  let dynamicPifTarget = dynamicLibraryVariant.pifTarget\n            else {\n                fatalError(\"Could not assign dynamic PIF target\")\n            }\n            self.project[keyPath: pifTargetKeyPath].dynamicTargetVariantId = dynamicPifTarget.id\n        }\n    }\n\n    // MARK: - Executable Source Modules\n\n    /// If we're building an *executable* and the tools version is new enough,\n    /// we also construct a testable version of said executable.\n    mutating func makeTestableExecutableSourceModule(_ executableModule: PackageGraph.ResolvedModule) throws {\n        precondition(executableModule.type == .executable)\n        guard self.package.manifest.toolsVersion >= .v5_5 else { return }\n\n        let inputResourceBundleName: String? = if mainModuleTargetNamesWithResources.contains(executableModule.name) {\n            resourceBundleName(forModuleName: executableModule.name)\n        } else {\n            nil\n        }\n\n        let (testableExecutableModule, _) = try buildSourceModule(\n            executableModule,\n            type: .executable,\n            targetSuffix: .testable,\n            addBuildToolPluginCommands: false,\n            inputResourceBundleName: inputResourceBundleName\n        )\n        self.builtModulesAndProducts.append(testableExecutableModule)\n    }\n\n    // MARK: - Source Modules\n\n    enum SourceModuleType: String {\n        case dynamicLibrary\n        case staticLibrary\n        case executable\n        case macro\n    }\n\n    static func createBinaryModuleFileReference(_ binaryModule: BinaryModule, id: ProjectModel.GUID) -> FileReference {\n        let fileTypeIdentifier: String?\n        switch binaryModule.kind {\n        case .artifactsArchive:\n            fileTypeIdentifier = \"wrapper.artifactbundle\"\n        case .xcframework:\n            fileTypeIdentifier = \"wrapper.xcframework\"\n        case .unknown:\n            fileTypeIdentifier = nil\n        }\n        return FileReference(id: id, path: binaryModule.artifactPath.pathString, fileType: fileTypeIdentifier)\n    }\n\n    /// Constructs a *PIF target* for building a *module* as a particular type.\n    /// An optional target identifier suffix is passed when building variants of a target.\n    @discardableResult\n    private mutating func buildSourceModule(\n        _ sourceModule: PackageGraph.ResolvedModule,\n        type desiredModuleType: SourceModuleType,\n        targetSuffix: TargetSuffix? = nil,\n        addBuildToolPluginCommands: Bool = true,\n        inputResourceBundleName: String? = nil\n    ) throws -> (PackagePIFBuilder.ModuleOrProduct, resourceBundleName: String?) {\n        precondition(sourceModule.isSourceModule)\n\n        let productType: ProjectModel.Target.ProductType\n\n        switch desiredModuleType {\n        case .dynamicLibrary:\n            // We are re-using this default for dynamic targets as well.\n            if pifBuilder.createDylibForDynamicProducts {\n                productType = .dynamicLibrary\n            } else {\n                productType = .framework\n            }\n\n        case .staticLibrary:\n            productType = .commonStaticArchive\n\n        case .executable:\n            productType = .commonObject\n\n        case .macro:\n            productType = .hostBuildTool\n        }\n\n        // Create a PIF target configured to build a single .o file.\n        // For now wrapped in a static archive, since Swift Build can *not* yet produce a single .o as an output.\n\n        // Macros are currently the only target type that requires explicit approval by users.\n        let approvedByUser: Bool = if desiredModuleType == .macro {\n            // Look up the current approval status in the underlying fingerprint storage.\n            pifBuilder.delegate.validateMacroFingerprint(for: sourceModule) == true\n        } else {\n            true\n        }\n\n        let sourceModuleTargetKeyPath = try self.project.addTarget { _ in\n            ProjectModel.Target(\n                id: sourceModule.pifTargetGUID(suffix: targetSuffix),\n                productType: productType,\n                name: sourceModule.name,\n                productName: \"$(EXECUTABLE_NAME)\",\n                approvedByUser: approvedByUser\n            )\n        }\n        do {\n            let sourceModule = self.project[keyPath: sourceModuleTargetKeyPath]\n            log(\n                .debug,\n                \"Created target '\\(sourceModule.id)' of type '\\(sourceModule.productType)' \" +\n                \"with name '\\(sourceModule.name)' and product name '\\(sourceModule.productName)'\"\n            )\n        }\n\n        // Deal with any generated source files or resource files.\n        let generatedFiles = computePluginGeneratedFiles(\n            module: sourceModule,\n            targetKeyPath: sourceModuleTargetKeyPath,\n            addBuildToolPluginCommands: false\n        )\n\n        // Either create or reuse the resource bundle.\n        var resourceBundleName = inputResourceBundleName\n        let shouldGenerateBundleAccessor: Bool\n        let shouldGenerateEmbedInCodeAccessor: Bool\n        if resourceBundleName == nil && desiredModuleType != .executable && desiredModuleType != .macro {\n            // FIXME: We are not handling resource rules here, but the same is true for non-generated resources.\n            // (Today, everything gets essentially treated as `.processResource` even if it may have been declared as\n            // `.copy` in the manifest.)\n            let (result, resourceBundle) = try addResourceBundle(\n                for: sourceModule,\n                targetKeyPath: sourceModuleTargetKeyPath,\n                generatedResourceFiles: generatedFiles.resources.keys.map(\\.pathString)\n            )\n            if let resourceBundle { self.builtModulesAndProducts.append(resourceBundle) }\n\n            resourceBundleName = result.bundleName\n            shouldGenerateBundleAccessor = result.shouldGenerateBundleAccessor\n            shouldGenerateEmbedInCodeAccessor = result.shouldGenerateEmbedInCodeAccessor\n        } else {\n            // Here we have to assume we need both types of accessors which will always bring in Foundation into the\n            // current target\n            // through the bundle accessor and will lead to Swift Build evaluating all resources, but neither should\n            // technically be a problem.\n            // Would still be nice to eventually make this accurate which would require storing these in addition to\n            // `inputResourceBundleName`.\n            shouldGenerateBundleAccessor = true\n            shouldGenerateEmbedInCodeAccessor = true\n            if resourceBundleName != nil {\n                let resourceTargetID = pifTargetIdForResourceBundle(sourceModule.name)\n                self.project[keyPath: sourceModuleTargetKeyPath].common.addDependency(\n                    on: resourceTargetID,\n                    platformFilters: [],\n                    linkProduct: false\n                )\n            }\n        }\n\n        // Find the PIF target for the resource bundle, if any. Otherwise fall back to the module.\n        let resourceBundleTargetKeyPath = self.resourceBundleTargetKeyPath(\n            forModuleName: sourceModule.name\n        ) ?? sourceModuleTargetKeyPath\n\n        // Add build tool commands to the resource bundle target.\n        if desiredModuleType != .executable && desiredModuleType != .macro && addBuildToolPluginCommands {\n            addBuildToolCommands(\n                module: sourceModule,\n                sourceModuleTargetKeyPath: sourceModuleTargetKeyPath,\n                resourceBundleTargetKeyPath: resourceBundleTargetKeyPath,\n                sourceFilePaths: generatedFiles.sources.map(\\.self),\n                resourceFilePaths: generatedFiles.resources.keys.map(\\.pathString)\n            )\n        }\n\n        // Create a set of build settings that will be imparted to any target that depends on this one.\n        var impartedSettings = BuildSettings()\n\n        // Configure the target-wide build settings. The details depend on the kind of product we're building.\n        var settings: BuildSettings = self.package.underlying.packageBaseBuildSettings\n\n        // Ensure the intermediates for this target don't clash with the intermediates of a target representing a package product with the same name\n        settings[.TARGET_TEMP_DIR_SUFFIX] = \"-t\"\n\n        if sourceModule.platformConstraint == .host {\n            settings[.SUPPORTED_PLATFORMS] = [\"$(HOST_PLATFORM)\"]\n        }\n        if shouldGenerateBundleAccessor {\n            settings[.GENERATE_RESOURCE_ACCESSORS] = \"YES\"\n        }\n        if shouldGenerateEmbedInCodeAccessor {\n            settings[.GENERATE_EMBED_IN_CODE_ACCESSORS] = \"YES\"\n        }\n\n        // Generate a module map file, if needed.\n        var moduleMapFileContents = \"\"\n        let generatedModuleMapDir = \"$(GENERATED_MODULEMAP_DIR)\"\n        let generatedModuleMapPath = try RelativePath(validating:\"\\(generatedModuleMapDir)/\\(sourceModule.name).modulemap\").pathString\n\n        if sourceModule.usesSwift && desiredModuleType != .macro {\n            // Generate ObjC compatibility header for Swift library targets.\n            settings[.SWIFT_OBJC_INTERFACE_HEADER_DIR] = generatedModuleMapDir\n            settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME] = \"\\(sourceModule.name)-Swift.h\"\n\n            moduleMapFileContents = \"\"\"\n            module \\(sourceModule.c99name) {\n            header \"\\(sourceModule.name)-Swift.h\"\n            export *\n            }\n            \"\"\"\n            // We only need to impart this to C clients.\n            impartedSettings[.OTHER_CFLAGS] = [\"-fmodule-map-file=\\(generatedModuleMapPath)\", \"$(inherited)\"]\n        } else {\n            // Otherwise, this is a C library module and we generate a modulemap if one is already not provided.\n            if let generatedModuleMapPath = generatedFiles.moduleMaps.first {\n                // Warn about ignored generated module maps if more than one\n                if generatedFiles.moduleMaps.count > 1 {\n                    let ignoredFiles = generatedFiles.moduleMaps.filter({ $0 != generatedModuleMapPath })\n                    pifBuilder.observabilityScope.emit(\n                        severity: .warning,\n                        message: \"Plugins generated multiple module maps. Selected \\(generatedModuleMapPath) and ignored \\(ignoredFiles.map(\\.pathString).joined(separator: \" \"))\"\n                    )\n                }\n                // The modulemap was already generated, we should explicitly impart it on dependents,\n                impartedSettings[.OTHER_CFLAGS] = [\"-fmodule-map-file=\\(generatedModuleMapPath)\", \"$(inherited)\"]\n                impartedSettings[.OTHER_SWIFT_FLAGS] = [\"-Xcc\", \"-fmodule-map-file=\\(generatedModuleMapPath)\", \"$(inherited)\"]\n            } else {\n                switch sourceModule.moduleMapType {\n                case nil, .some(.none):\n                    // No modulemap, no action required.\n                    break\n                case .custom(let customModuleMapPath):\n                    // We don't need to generate a modulemap, but we should explicitly impart it on dependents,\n                    // even if it will appear in search paths. See: https://github.com/swiftlang/swift-package-manager/issues/9290\n                    impartedSettings[.OTHER_CFLAGS] = [\"-fmodule-map-file=\\(customModuleMapPath)\", \"$(inherited)\"]\n                    impartedSettings[.OTHER_SWIFT_FLAGS] = [\"-Xcc\", \"-fmodule-map-file=\\(customModuleMapPath)\", \"$(inherited)\"]\n                case .umbrellaHeader(let path):\n                    log(.debug, \"\\(package.name).\\(sourceModule.name) generated umbrella header\")\n                    moduleMapFileContents = \"\"\"\n                    module \\(sourceModule.c99name) {\n                    umbrella header \"\\(path.escapedPathString)\"\n                    export *\n                    }\n                    \"\"\"\n                    // Pass the path of the module map up to all direct and indirect clients.\n                    impartedSettings[.OTHER_CFLAGS] = [\"-fmodule-map-file=\\(generatedModuleMapPath)\", \"$(inherited)\"]\n                    impartedSettings[.OTHER_SWIFT_FLAGS] = [\"-Xcc\", \"-fmodule-map-file=\\(generatedModuleMapPath)\", \"$(inherited)\"]\n                case .umbrellaDirectory(let path):\n                    log(.debug, \"\\(package.name).\\(sourceModule.name) generated umbrella directory\")\n                    moduleMapFileContents = \"\"\"\n                    module \\(sourceModule.c99name) {\n                    umbrella \"\\(path.escapedPathString)\"\n                    export *\n                    }\n                    \"\"\"\n                    // Pass the path of the module map up to all direct and indirect clients.\n                    impartedSettings[.OTHER_CFLAGS] = [\"-fmodule-map-file=\\(generatedModuleMapPath)\", \"$(inherited)\"]\n                    impartedSettings[.OTHER_SWIFT_FLAGS] = [\"-Xcc\", \"-fmodule-map-file=\\(generatedModuleMapPath)\", \"$(inherited)\"]\n                }\n            }\n        }\n\n        if desiredModuleType == .dynamicLibrary {\n            settings.configureDynamicSettings(\n                productName: sourceModule.name,\n                targetName: sourceModule.name,\n                packageIdentity: package.identity,\n                packageName: sourceModule.packageName,\n                createDylibForDynamicProducts: pifBuilder.createDylibForDynamicProducts,\n                installPath: \"/usr/local/lib\",\n                delegate: pifBuilder.delegate,\n            )\n        } else {\n            settings[.TARGET_NAME] = sourceModule.name\n            settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n            settings[.PRODUCT_MODULE_NAME] = sourceModule.c99name\n            settings[.PRODUCT_BUNDLE_IDENTIFIER] = \"\\(self.package.identity).\\(sourceModule.name)\"\n                .spm_mangledToBundleIdentifier()\n            settings[.GENERATE_PRELINK_OBJECT_FILE] = \"NO\"\n            settings[.STRIP_INSTALLED_PRODUCT] = \"NO\"\n\n            settings[.SWIFT_PACKAGE_NAME] = sourceModule.packageName\n\n            // On Windows, disable static linking mode when this module is a dependency of a dynamic library.\n            // This ensures the module is compiled correctly for linking into a dynamic library.\n            if self.modulesInDynamicLibraries.contains(sourceModule.name) {\n                settings[.SWIFT_COMPILE_FOR_STATIC_LINKING, .windows] = \"NO\"\n            }\n\n            // This entrypoint is only used for the testable variant of executable and macro targets. The primary PIF generation\n            // for executables is in makeMainModuleProduct.\n            if desiredModuleType == .executable {\n                // Tell the Swift compiler to produce an alternate entry point rather than the standard `_main` entry\n                // point`,\n                // so that we can link one or more testable executable modules together into a single test bundle.\n                // This allows the test bundle to treat the executable as if it were any regular library module,\n                // and will have access to all symbols except the main entry point its.\n                settings[.OTHER_SWIFT_FLAGS].lazilyInitializeAndMutate(initialValue: [\"$(inherited)\"]) {\n                    $0.append(contentsOf: [\"-Xfrontend\", \"-entry-point-function-name\"])\n                    $0.append(contentsOf: [\"-Xfrontend\", \"\\(sourceModule.c99name)_main\"])\n                }\n\n                // We have to give each target a unique name.\n                settings[.TARGET_NAME] = sourceModule.name + targetSuffix.uniqueDescription(forName: sourceModule.name)\n\n                // Redirect the built executable into a separate directory so it won't conflict with the real one.\n                settings[.TARGET_BUILD_DIR] = \"$(TARGET_BUILD_DIR)/ExecutableModules\"\n\n                // on windows modules are libraries, so we need to add a search path so the linker finds them\n                impartedSettings[.LIBRARY_SEARCH_PATHS, .windows] = [\"$(inherited)\", \"$(TARGET_BUILD_DIR)/ExecutableModules\"]\n            }\n\n            if let aliases = sourceModule.moduleAliases {\n                // Format each entry as \"original_name=alias\"\n                let list = aliases.map { $0.0 + \"=\" + $0.1 }\n                settings[.SWIFT_MODULE_ALIASES] = list.isEmpty ? nil : list\n            }\n\n            // We mark in the PIF that we are intentionally not offering a dynamic target here,\n            // so we can emit a diagnostic if it is being requested by Swift Build.\n            if !self.shouldOfferDynamicTarget(sourceModule.name) {\n                settings[.PACKAGE_TARGET_NAME_CONFLICTS_WITH_PRODUCT_NAME] = \"YES\"\n            }\n\n            // We are setting this instead of `LD_DYLIB_INSTALL_NAME` because `mh_object` files\n            // don't actually have install names, so we should not pass an install name to the linker.\n            settings[.TAPI_DYLIB_INSTALL_NAME] = sourceModule.name\n        }\n\n        settings[.PACKAGE_RESOURCE_TARGET_KIND] = \"regular\"\n        settings[.MODULEMAP_FILE_CONTENTS] = moduleMapFileContents\n        settings[.MODULEMAP_PATH] = generatedModuleMapPath\n        settings[.DEFINES_MODULE] = \"YES\"\n\n        // Settings for text-based API.\n        // Due to rdar://78331694 (Cannot use TAPI for packages in contexts where we need to code-sign (e.g. apps))\n        // we are only enabling TAPI in `configureSourceModuleBuildSettings`, if desired.\n        settings[.SUPPORTS_TEXT_BASED_API] = \"NO\"\n\n        // If the module includes C headers, we set up the HEADER_SEARCH_PATHS setting appropriately.\n        var headerSearchPaths: [AbsolutePath] = []\n        if let includeDirAbsPath = sourceModule.includeDirAbsolutePath {\n            headerSearchPaths.append(includeDirAbsPath)\n        }\n        // Include generated public header paths.\n        headerSearchPaths += generatedFiles.publicHeaderPaths\n\n        if !headerSearchPaths.isEmpty {\n            // Let the target itself find its own headers.\n            settings[.HEADER_SEARCH_PATHS] = headerSearchPaths.map(\\.pathString) + [\"$(inherited)\"]\n            for path in headerSearchPaths {\n                log(.debug, indent: 1, \"Added '\\(path)' to HEADER_SEARCH_PATHS\")\n            }\n\n            // Also propagate this search path to all direct and indirect clients.\n            impartedSettings[.HEADER_SEARCH_PATHS] = headerSearchPaths.map(\\.pathString) + [\"$(inherited)\"]\n            for path in headerSearchPaths {\n                log(.debug, indent: 1, \"Added '\\(path)' to imparted HEADER_SEARCH_PATHS\")\n            }\n        }\n\n        // Additional settings for the linker.\n        let enableDuplicateLinkageCulling = UserDefaults.standard.bool(\n            forKey: \"IDESwiftPackagesEnableDuplicateLinkageCulling\",\n            defaultValue: true\n        )\n        if enableDuplicateLinkageCulling {\n            impartedSettings[.LD_WARN_DUPLICATE_LIBRARIES] = \"NO\"\n        }\n        if sourceModule.isCxx {\n            for platform in ProjectModel.BuildSettings.Platform.allCases {\n                // darwin & freebsd\n                switch platform {\n                    case .macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .xrOS, .driverKit, .freebsd:\n                        impartedSettings[.OTHER_LDFLAGS, platform] = [\"-lc++\", \"$(inherited)\"]\n                    case .android, .linux, .wasi, .openbsd:\n                        impartedSettings[.OTHER_LDFLAGS, platform] = [\"-lstdc++\", \"$(inherited)\"]\n                    case .windows, ._iOSDevice:\n                        break\n                }\n            }\n        }\n        // This should be only for dynamic targets, but that isn't possible today.\n        // Improvement is tracked by rdar://77403529 (Only impart `PackageFrameworks` search paths to clients of dynamic\n        // package targets and products).\n        impartedSettings[.FRAMEWORK_SEARCH_PATHS] = [\"$(BUILT_PRODUCTS_DIR)/PackageFrameworks\", \"$(inherited)\"]\n        log(\n            .debug,\n            indent: 1,\n            \"Added '\\(impartedSettings[.FRAMEWORK_SEARCH_PATHS]!)' to imparted FRAMEWORK_SEARCH_PATHS\"\n        )\n\n        // Set the appropriate language versions.\n        settings[.SWIFT_VERSION] = sourceModule.packageSwiftLanguageVersion(manifest: packageManifest)\n        settings[.GCC_C_LANGUAGE_STANDARD] = sourceModule.cLanguageStandard\n        settings[.CLANG_CXX_LANGUAGE_STANDARD] = sourceModule.cxxLanguageStandard\n        settings[.SWIFT_ENABLE_BARE_SLASH_REGEX] = \"NO\"\n\n        // Create a group for the target's source files.\n        //\n        // For now we use an absolute path for it, but we should really make it be container-relative,\n        // since it's always inside the package directory. Resolve symbolic links otherwise there will\n        // be a mismatch between the paths that the index service is using for Swift Build queries,\n        // and what paths Swift Build uses in its build description; such a mismatch would result\n        // in the index service failing to get compiler arguments for source files of the target.\n        let targetSourceFileGroupKeyPath = self.project.mainGroup.addGroup { id in\n            ProjectModel.Group(\n                id: id,\n                path: try! resolveSymlinks(sourceModule.sourceDirAbsolutePath).pathString,\n                pathBase: .absolute\n            )\n        }\n        do {\n            let targetSourceFileGroup = self.project.mainGroup[keyPath: targetSourceFileGroupKeyPath]\n            log(.debug, indent: 1, \"Added source file group '\\(targetSourceFileGroup.path)'\")\n        }\n\n        // Add a source file reference for each of the source files,\n        // and also an indexable-file URL for each one.\n        //\n        // Symlinks should be resolved externally.\n        var indexableFileURLs: [SourceControlURL] = []\n        for sourcePath in sourceModule.sourceFileRelativePaths {\n            let sourceFileRef = self.project.mainGroup[keyPath: targetSourceFileGroupKeyPath].addFileReference { id in\n                FileReference(id: id, path: sourcePath.pathString, pathBase: .groupDir)\n            }\n            self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in\n                BuildFile(id: id, fileRef: sourceFileRef)\n            }\n            indexableFileURLs.append(\n                SourceControlURL(fileURLWithPath: sourceModule.sourceDirAbsolutePath.appending(sourcePath))\n            )\n            log(.debug, indent: 2, \"Added source file '\\(sourcePath)'\")\n        }\n        for resource in sourceModule.resources {\n            log(.debug, indent: 2, \"Added resource file '\\(resource.path)'\")\n            indexableFileURLs.append(SourceControlURL(fileURLWithPath: resource.path))\n        }\n\n        let headerFiles = Set(sourceModule.headerFileAbsolutePaths)\n\n        // Add any additional source files emitted by custom build commands.\n        for path in generatedFiles.sources {\n            let sourceFileRef = self.project.mainGroup[keyPath: targetSourceFileGroupKeyPath].addFileReference { id in\n                FileReference(id: id, path: path.pathString, pathBase: .absolute)\n            }\n            self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in\n                BuildFile(id: id, fileRef: sourceFileRef)\n            }\n            log(.debug, indent: 2, \"Added generated source file '\\(path)'\")\n        }\n\n        if let resourceBundle = resourceBundleName {\n            impartedSettings[.EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES] = [\"$(inherited)\", resourceBundle]\n            settings[.PACKAGE_RESOURCE_BUNDLE_NAME] = resourceBundle\n            settings[.COREML_CODEGEN_LANGUAGE] = sourceModule.usesSwift ? \"Swift\" : \"Objective-C\"\n            settings[.COREML_COMPILER_CONTAINER] = \"swift-package\"\n        }\n\n        if sourceModule.usesSwift {\n            // Leave an explicit indicator regarding whether we are generating a Bundle.module accessor.\n            // This will be read by the #bundle macro defined in Foundation.\n            if !shouldGenerateBundleAccessor {\n                // No resources, so explicitly indicate that.\n                // #bundle will then produce an error about there being no resources.\n                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS].lazilyInitializeAndMutate(initialValue: [\"$(inherited)\"]) { $0.append(\"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\") }\n            } else if !(resourceBundleName?.isEmpty ?? true) {\n                // We have an explicit resource bundle via Bundle.module.\n                // #bundle should call into that.\n                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS].lazilyInitializeAndMutate(initialValue: [\"$(inherited)\"]) { $0.append(\"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\") }\n            } // else we won't set either of those and just let #bundle point to the same bundle as the source code.\n        }\n\n        if desiredModuleType == .macro {\n            settings[.SWIFT_IMPLEMENTS_MACROS_FOR_MODULE_NAMES] = [sourceModule.c99name]\n\n            // Don't install the Swift module when building the macro executable, lest it conflict with the testable variant.\n            // The contents of the testable variant's module will exactly match the binary linked by dependencies (test targets).\n            settings[.SWIFT_INSTALL_MODULE] = \"NO\"\n        }\n        if sourceModule.type == .macro {\n            settings[.SKIP_BUILDING_DOCUMENTATION] = \"YES\"\n        }\n\n        sourceModule.addParseAsLibrarySettings(to: &settings, toolsVersion: package.manifest.toolsVersion, fileSystem: pifBuilder.fileSystem)\n\n        // Handle the target's dependencies (but only link against them if needed).\n        let shouldLinkProduct = (desiredModuleType == .dynamicLibrary) || (desiredModuleType == .macro)\n        sourceModule.recursivelyTraverseDependencies { dependency in\n            switch dependency {\n            case .module(let moduleDependency, let packageConditions):\n                // This assertion is temporarily disabled since we may see targets from\n                // _other_ packages, but this should be resolved; see rdar://95467710.\n                /* assert(moduleDependency.packageName == self.package.name) */\n\n                let dependencyPlatformFilters = packageConditions\n                    .toPlatformFilter(toolsVersion: self.package.manifest.toolsVersion)\n\n                switch moduleDependency.type {\n                case .executable, .snippet:\n                    // Always depend on product of executable targets (if available).\n                    // FIXME: Maybe we should we do this at the libSwiftPM level.\n                    let moduleMainProducts = self.package.products.filter(\\.isMainModuleProduct)\n                    if let product = moduleDependency\n                        .productRepresentingDependencyOfBuildPlugin(in: moduleMainProducts)\n                    {\n                        self.project[keyPath: sourceModuleTargetKeyPath].common.addDependency(\n                            on: product.pifTargetGUID,\n                            platformFilters: dependencyPlatformFilters,\n                            linkProduct: false\n                        )\n                        log(.debug, indent: 1, \"Added dependency on product '\\(product.pifTargetGUID)'\")\n                    } else {\n                        log(\n                            .debug,\n                            indent: 1,\n                            \"Could not find a build plugin product to depend on for target '\\(moduleDependency.pifTargetGUID)'\"\n                        )\n                    }\n\n                case .binary:\n                    guard let binaryModule = moduleDependency.underlying as? BinaryModule else {\n                        log(.error, \"'\\(moduleDependency.name)' is a binary dependency, but its underlying module was not\")\n                        break\n                    }\n                    let binaryReference = self.binaryGroup.addFileReference { id in\n                        return Self.createBinaryModuleFileReference(binaryModule, id: id)\n                    }\n                    if shouldLinkProduct {\n                        self.project[keyPath: sourceModuleTargetKeyPath].addLibrary { id in\n                            BuildFile(\n                                id: id,\n                                fileRef: binaryReference,\n                                platformFilters: dependencyPlatformFilters,\n                                codeSignOnCopy: true,\n                                removeHeadersOnCopy: true\n                            )\n                        }\n                    } else {\n                        // If we are producing a single \".o\", don't link binaries since they\n                        // could be static which would cause them to become part of the \".o\".\n                        self.project[keyPath: sourceModuleTargetKeyPath].addResourceFile { id in\n                            BuildFile(\n                                id: id,\n                                fileRef: binaryReference,\n                                platformFilters: dependencyPlatformFilters\n                            )\n                        }\n                    }\n                    log(.debug, indent: 1, \"Added use of binary library '\\(moduleDependency.path)'\")\n\n                case .plugin:\n                    let dependencyGUID = moduleDependency.pifTargetGUID\n                    self.project[keyPath: sourceModuleTargetKeyPath].common.addDependency(\n                        on: dependencyGUID,\n                        platformFilters: dependencyPlatformFilters,\n                        linkProduct: false\n                    )\n                    log(.debug, indent: 1, \"Added use of plugin target '\\(dependencyGUID)'\")\n\n                case .library, .test, .macro, .systemModule:\n                    self.project[keyPath: sourceModuleTargetKeyPath].common.addDependency(\n                        on: moduleDependency.pifTargetGUID,\n                        platformFilters: dependencyPlatformFilters,\n                        linkProduct: shouldLinkProduct\n                    )\n                    log(\n                        .debug,\n                        indent: 1,\n                        \"Added \\(shouldLinkProduct ? \"linked \" : \"\")dependency on target '\\(moduleDependency.pifTargetGUID)'\"\n                    )\n                }\n\n            case .product(let productDependency, let packageConditions):\n                // Do not add a dependency for binary-only executable products since they are not part of the build.\n                if productDependency.isBinaryOnlyExecutableProduct {\n                    return\n                }\n\n                if !pifBuilder.delegate.shouldSuppressProductDependency(\n                    product: productDependency.underlying,\n                    buildSettings: &settings\n                ) {\n                    let dependencyPlatformFilters = packageConditions\n                        .toPlatformFilter(toolsVersion: self.package.manifest.toolsVersion)\n                    let shouldLinkProduct = shouldLinkProduct && productDependency.isLinkable\n\n                    self.project[keyPath: sourceModuleTargetKeyPath].common.addDependency(\n                        on: productDependency.pifTargetGUID,\n                        platformFilters: dependencyPlatformFilters,\n                        linkProduct: shouldLinkProduct\n                    )\n                    log(\n                        .debug,\n                        indent: 1,\n                        \"Added \\(shouldLinkProduct ? \"linked \" : \"\")dependency on product '\\(productDependency.pifTargetGUID)'\"\n                    )\n                }\n            }\n        }\n\n        // Custom source module build settings, if any.\n        pifBuilder.delegate.configureSourceModuleBuildSettings(sourceModule: sourceModule, settings: &settings)\n\n        // Until this point the build settings for the target have been the same between debug and release\n        // configurations.\n        // The custom manifest settings might cause them to diverge.\n        var debugSettings = settings\n        var releaseSettings = settings\n\n        let allBuildSettings = sourceModule.computeAllBuildSettings(observabilityScope: pifBuilder.observabilityScope, forRemotePackage: pifBuilder.delegate.isRemote)\n\n        // Apply target-specific build settings defined in the manifest.\n        allBuildSettings.apply(to: &debugSettings, for: .debug)\n        allBuildSettings.apply(to: &releaseSettings, for: .release)\n\n        // Apply imparted settings\n        allBuildSettings.applyImparted(to: &impartedSettings)\n\n        // Set the **imparted** settings, which are ones that clients (both direct and indirect ones) use.\n        // For instance, given targets A, B, C with the following dependency graph:\n        //\n        //   A (executable) -> B (dynamicLibrary) -> C (objectFile)\n        //\n        // An imparted build setting on C will propagate back to both B and A.\n        // FIXME: -rpath should not be given if -static is\n        var rpaths: [String] = []\n        if let existingRpaths = impartedSettings[.LD_RUNPATH_SEARCH_PATHS] {\n            rpaths.append(contentsOf: existingRpaths)\n        }\n        if pifBuilder.addLocalRpaths {\n            rpaths.append(\"$(RPATH_ORIGIN)\")\n            impartedSettings[.LD_RUNPATH_SEARCH_PATHS] = rpaths + [\"$(inherited)\"]\n        }\n\n        var impartedDebugSettings = impartedSettings\n        if pifBuilder.addLocalRpaths {\n            // FIXME: Why is this rpath only added to the debug config? We should investigate reworking this.\n            rpaths.append(\"$(BUILT_PRODUCTS_DIR)/PackageFrameworks\")\n            impartedDebugSettings[.LD_RUNPATH_SEARCH_PATHS] = rpaths + [\"$(inherited)\"]\n        }\n\n        self.project[keyPath: sourceModuleTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(\n                id: id,\n                name: \"Debug\",\n                settings: debugSettings,\n                impartedBuildSettings: impartedDebugSettings\n            )\n        }\n        self.project[keyPath: sourceModuleTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(\n                id: id,\n                name: \"Release\",\n                settings: releaseSettings,\n                impartedBuildSettings: impartedSettings\n            )\n        }\n\n        // Collect linked binaries.\n        let linkedPackageBinaries: [PackagePIFBuilder.LinkedPackageBinary] = sourceModule.dependencies.compactMap {\n            PackagePIFBuilder.LinkedPackageBinary(dependency: $0)\n        }\n\n        let productOrModuleType: PackagePIFBuilder.ModuleOrProductType = if desiredModuleType == .dynamicLibrary {\n            pifBuilder.createDylibForDynamicProducts ? .dynamicLibrary : .framework\n        } else if desiredModuleType == .macro {\n            .macro\n        } else {\n            .module\n        }\n\n        let moduleOrProduct = PackagePIFBuilder.ModuleOrProduct(\n            type: productOrModuleType,\n            name: sourceModule.name,\n            moduleName: sourceModule.c99name,\n            pifTarget: .target(self.project[keyPath: sourceModuleTargetKeyPath]),\n            indexableFileURLs: indexableFileURLs,\n            headerFiles: headerFiles,\n            linkedPackageBinaries: linkedPackageBinaries,\n            swiftLanguageVersion: sourceModule.packageSwiftLanguageVersion(manifest: packageManifest),\n            declaredPlatforms: self.declaredPlatforms,\n            deploymentTargets: self.deploymentTargets\n        )\n\n        return (moduleOrProduct, resourceBundleName)\n    }\n\n    // MARK: - System Library Targets\n\n    mutating func makeSystemLibraryModule(_ resolvedSystemLibrary: PackageGraph.ResolvedModule) throws {\n        precondition(resolvedSystemLibrary.type == .systemModule)\n        let systemLibrary = resolvedSystemLibrary.underlying as! SystemLibraryModule\n\n        // Create an aggregate PIF target (which doesn't have an actual product).\n        let systemLibraryTargetKeyPath = try self.project.addAggregateTarget { _ in\n            ProjectModel.AggregateTarget(\n                id: resolvedSystemLibrary.pifTargetGUID,\n                name: resolvedSystemLibrary.name\n            )\n        }\n        do {\n            let systemLibraryTarget = self.project[keyPath: systemLibraryTargetKeyPath]\n            log(\n                .debug,\n                \"Created aggregate target '\\(systemLibraryTarget.id)' with name '\\(systemLibraryTarget.name)'\"\n            )\n        }\n\n        let settings: ProjectModel.BuildSettings = self.package.underlying.packageBaseBuildSettings\n        let pkgConfig = try systemLibrary.pkgConfig(\n            package: self.package,\n            pkgConfigDirectories: self.pifBuilder.pkgConfigDirectories,\n            fileSystem: self.pifBuilder.fileSystem,\n            observabilityScope: pifBuilder.observabilityScope\n        )\n\n        // Impart the header search path to all direct and indirect clients.\n        var impartedSettings = ProjectModel.BuildSettings()\n        impartedSettings[.OTHER_CFLAGS] = [\"-fmodule-map-file=\\(systemLibrary.modulemapFileAbsolutePath)\"] +\n            pkgConfig.cFlags.prepending(\"$(inherited)\")\n        impartedSettings[.OTHER_LDFLAGS] = pkgConfig.libs.prepending(\"$(inherited)\")\n        impartedSettings[.OTHER_SWIFT_FLAGS] = [\"-Xcc\"] + impartedSettings[.OTHER_CFLAGS]!\n        log(.debug, indent: 1, \"Added '\\(systemLibrary.path.pathString)' to imparted HEADER_SEARCH_PATHS\")\n\n        self.project[keyPath: systemLibraryTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(\n                id: id,\n                name: \"Debug\",\n                settings: settings,\n                impartedBuildSettings: impartedSettings\n            )\n        }\n        self.project[keyPath: systemLibraryTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(\n                id: id,\n                name: \"Release\",\n                settings: settings,\n                impartedBuildSettings: impartedSettings\n            )\n        }\n        // FIXME: Should we also impart linkage?\n\n        let systemModule = PackagePIFBuilder.ModuleOrProduct(\n            type: .module,\n            name: resolvedSystemLibrary.name,\n            moduleName: resolvedSystemLibrary.c99name,\n            pifTarget: .aggregate(self.project[keyPath: systemLibraryTargetKeyPath]),\n            indexableFileURLs: [],\n            headerFiles: [],\n            linkedPackageBinaries: [],\n            swiftLanguageVersion: nil,\n            declaredPlatforms: self.declaredPlatforms,\n            deploymentTargets: self.deploymentTargets\n        )\n        self.builtModulesAndProducts.append(systemModule)\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PackagePIFProjectBuilder+Products.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport TSCBasic\nimport TSCUtility\n\nimport struct Basics.AbsolutePath\nimport class Basics.ObservabilitySystem\nimport struct Basics.SourceControlURL\n\nimport PackageLoading\n\nimport class PackageModel.BinaryModule\nimport class PackageModel.Manifest\nimport enum PackageModel.PackageCondition\nimport enum PackageModel.PrebuiltsPlatform\nimport class PackageModel.Product\nimport enum PackageModel.ProductType\nimport struct PackageModel.RegistryReleaseMetadata\n\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedPackage\nimport struct PackageGraph.ResolvedProduct\nimport PackageLoading\n\nimport enum SwiftBuild.ProjectModel\n\n/// Extension to create PIF **products** for a given package.\nextension PackagePIFProjectBuilder {\n    // MARK: - Main Module Products\n\n    mutating func makeMainModuleProduct(_ product: PackageGraph.ResolvedProduct) throws {\n        precondition(product.isMainModuleProduct)\n\n        // We'll be infusing the product's main module into the one for the product itself.\n        guard let mainModule = product.mainModule, mainModule.isSourceModule else {\n            return\n        }\n\n        // Skip test products from non-root packages. libSwiftPM will stop vending them after\n        // target-based dependency resolution anyway but this should be fine until then.\n        if !pifBuilder.delegate.isRootPackage && (mainModule.type == .test || mainModule.type == .binary) {\n            return\n        }\n\n        // Determine the kind of PIF target *product type* to create for the package product.\n        let pifProductType: ProjectModel.Target.ProductType\n        let moduleOrProductType: PackagePIFBuilder.ModuleOrProductType\n        let synthesizedResourceGeneratingPluginInvocationResults: [PackagePIFBuilder.BuildToolPluginInvocationResult] =\n            []\n\n        if [.executable, .snippet].contains(product.type) {\n            if let customPIFProductType = pifBuilder.delegate.customProductType(forExecutable: product.underlying) {\n                pifProductType = customPIFProductType\n                moduleOrProductType = PackagePIFBuilder.ModuleOrProductType(from: customPIFProductType)\n            } else {\n                // No custom type provider. Current behavior is to fall back on regular executable.\n                pifProductType = .executable\n                moduleOrProductType = .executable\n            }\n        } else {\n            // If it's not an executable product, it must currently be a test bundle.\n            assert(product.type == .test, \"Unexpected product type: \\(product.type)\")\n            pifProductType = .unitTest\n            moduleOrProductType = .unitTest\n        }\n\n        // It's not a library product, so create a regular PIF target of the appropriate product type.\n        let mainModuleTargetKeyPath = try self.project.addTarget { _ in\n            ProjectModel.Target(\n                id: product.pifTargetGUID,\n                productType: pifProductType,\n                name: product.targetName(),\n                productName: \"$(EXECUTABLE_NAME)\"\n            )\n        }\n        do {\n            let mainModuleTarget = self.project[keyPath: mainModuleTargetKeyPath]\n            log(\n                .debug,\n                \"Created target '\\(mainModuleTarget.id)' of type '\\(mainModuleTarget.productType)' \" +\n                \"with name '\\(mainModuleTarget.name)' and product name '\\(mainModuleTarget.productName)'\"\n            )\n        }\n\n        // We're currently *not* handling other module targets (and SwiftPM should never return them) for\n        // a main-module product but, for diagnostic purposes, we warn about any that we do come across.\n        if product.otherModules.hasContent {\n            let otherModuleNames = product.otherModules.map(\\.name).joined(separator: \",\")\n            log(.debug, indent: 1, \"Warning: ignored unexpected other module targets \\(otherModuleNames)\")\n        }\n\n        // Deal with any generated source files or resource files.\n        let generatedFiles = computePluginGeneratedFiles(\n            module: mainModule,\n            targetKeyPath: mainModuleTargetKeyPath,\n            addBuildToolPluginCommands: pifProductType == .application\n        )\n        if mainModule.resources.hasContent || generatedFiles.resources.hasContent {\n            mainModuleTargetNamesWithResources.insert(mainModule.name)\n        }\n\n        // Configure the target-wide build settings. The details depend on the kind of product we're building,\n        // but are in general the ones that are suitable for end-product artifacts such as executables and test bundles.\n        var settings: ProjectModel.BuildSettings = package.underlying.packageBaseBuildSettings\n        settings[.TARGET_NAME] = product.name\n        settings[.TARGET_TEMP_DIR_SUFFIX] = \"-p\"\n        settings[.PACKAGE_RESOURCE_TARGET_KIND] = \"regular\"\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        // We must use the main module name here instead of the product name, because they're not guranteed to be the same, and the users may have authored e.g. tests which rely on an executable's module name.\n        settings[.PRODUCT_MODULE_NAME] = mainModule.c99name\n        if product.type == .executable {\n            // Don't install the Swift module of the executable product, lest it conflict with the testable variant.\n            // The contents of the testable variant's module will exactly match the binary linked by dependencies (test targets).\n            // Also, multiple executable products may incorporate sources from the same executable target, while the testable\n            // variant of an executable target's module will always be unique, so we avoid producing conflicting copies.\n            settings[.SWIFT_INSTALL_MODULE] = \"NO\"\n        }\n\n        settings[.PRODUCT_BUNDLE_IDENTIFIER] = \"\\(self.package.identity).\\(product.name)\"\n            .spm_mangledToBundleIdentifier()\n        settings[.SWIFT_PACKAGE_NAME] = mainModule.packageName\n\n        if mainModule.type == .test {\n            // FIXME: we shouldn't always include both the deep and shallow bundle paths here, but for that we'll need rdar://31867023\n            if pifBuilder.addLocalRpaths {\n                settings[.LD_RUNPATH_SEARCH_PATHS] = [\n                    \"$(RPATH_ORIGIN)/Frameworks\",\n                    \"$(RPATH_ORIGIN)/../Frameworks\",\n                    \"$(inherited)\"\n                ]\n            }\n            settings[.GENERATE_INFOPLIST_FILE] = \"YES\"\n            settings[.SKIP_INSTALL] = \"NO\"\n            settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS].lazilyInitialize { [\"$(inherited)\"] }\n            // Enable index-while building for Swift compilations to facilitate discovery of XCTest tests.\n            settings[.SWIFT_INDEX_STORE_ENABLE] = \"YES\"\n\n            if mainModule.platformConstraint == .host {\n                // This is a macro test using prebuilts\n                settings[.SUPPORTED_PLATFORMS] = [\"$(HOST_PLATFORM)\"]\n                switch PrebuiltsPlatform.hostPlatform?.arch {\n                case .aarch64:\n                    settings[.ARCHS] = [\"arm64\"]\n                case .x86_64:\n                    settings[.ARCHS] = [\"86_64\"]\n                case .none:\n                    break\n                }\n            }\n        } else if mainModule.type == .executable {\n            // Setup install path for executables if it's in root of a pure Swift package.\n            if pifBuilder.delegate.hostsOnlyPackages && pifBuilder.delegate.isRootPackage {\n                settings[.SKIP_INSTALL] = \"NO\"\n                settings[.INSTALL_PATH] = \"/usr/local/bin\"\n                settings[.LD_RUNPATH_SEARCH_PATHS] = [\"$(inherited)\", \"@executable_path/../lib\"]\n            }\n        }\n\n        mainModule.addParseAsLibrarySettings(to: &settings, toolsVersion: package.manifest.toolsVersion, fileSystem: pifBuilder.fileSystem)\n\n        let mainTargetDeploymentTargets = mainModule.deploymentTargets(using: pifBuilder.delegate)\n\n        settings[.MACOSX_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.macOS] ?? nil\n        settings[.IPHONEOS_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.iOS] ?? nil\n        if let deploymentTarget_macCatalyst = mainTargetDeploymentTargets[.macCatalyst] {\n            settings[.IPHONEOS_DEPLOYMENT_TARGET, .macCatalyst] = deploymentTarget_macCatalyst\n        }\n        settings[.TVOS_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.tvOS] ?? nil\n        settings[.WATCHOS_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.watchOS] ?? nil\n        settings[.DRIVERKIT_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.driverKit] ?? nil\n        settings[.XROS_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.visionOS] ?? nil\n\n        // If the main module includes C headers, then we need to set up the HEADER_SEARCH_PATHS setting appropriately.\n        var headerSearchPaths: [AbsolutePath] = []\n        if let includeDirAbsolutePath = mainModule.includeDirAbsolutePath {\n            headerSearchPaths.append(includeDirAbsolutePath)\n        }\n        headerSearchPaths += generatedFiles.publicHeaderPaths\n\n        if !headerSearchPaths.isEmpty {\n            // Let the main module itself find its own headers.\n            settings[.HEADER_SEARCH_PATHS] = headerSearchPaths.map(\\.pathString) + [\"$(inherited)\"]\n            for path in headerSearchPaths {\n                log(.debug, indent: 1, \"Added '\\(path)' to HEADER_SEARCH_PATHS\")\n            }\n        }\n\n        // Set the appropriate language versions.\n        settings[.SWIFT_VERSION] = mainModule.packageSwiftLanguageVersion(manifest: packageManifest)\n        settings[.GCC_C_LANGUAGE_STANDARD] = mainModule.cLanguageStandard\n        settings[.CLANG_CXX_LANGUAGE_STANDARD] = mainModule.cxxLanguageStandard\n        settings[.SWIFT_ENABLE_BARE_SLASH_REGEX] = \"NO\"\n\n        // Create a group for the source files of the main module\n        // For now we use an absolute path for it, but we should really make it\n        // container-relative, since it's always inside the package directory.\n        let mainTargetSourceFileGroupKeyPath = self.project.mainGroup.addGroup { id in\n            ProjectModel.Group(\n                id: id,\n                path: mainModule.sourceDirAbsolutePath.pathString,\n                pathBase: .absolute\n            )\n        }\n        do {\n            let mainTargetSourceFileGroup = self.project.mainGroup[keyPath: mainTargetSourceFileGroupKeyPath]\n            log(.debug, indent: 1, \"Added source file group '\\(mainTargetSourceFileGroup.path)'\")\n        }\n\n        // Add a source file reference for each of the source files, and also an indexable-file URL for each one.\n        // Note that the indexer requires them to have any symbolic links resolved.\n        var indexableFileURLs: [SourceControlURL] = []\n        for sourcePath in mainModule.sourceFileRelativePaths {\n            let sourceFileRef = self.project.mainGroup[keyPath: mainTargetSourceFileGroupKeyPath]\n                .addFileReference { id in\n                    FileReference(\n                        id: id,\n                        path: sourcePath.pathString,\n                        pathBase: .groupDir\n                    )\n                }\n            self.project[keyPath: mainModuleTargetKeyPath].addSourceFile { id in\n                BuildFile(id: id, fileRef: sourceFileRef)\n            }\n            log(.debug, indent: 2, \"Added source file '\\(sourcePath)'\")\n            indexableFileURLs.append(\n                SourceControlURL(fileURLWithPath: mainModule.sourceDirAbsolutePath.appending(sourcePath))\n            )\n        }\n\n        let headerFiles = Set(mainModule.headerFileAbsolutePaths)\n\n        // Add any additional source files emitted by custom build commands.\n        for path in generatedFiles.sources {\n            let sourceFileRef = self.project.mainGroup[keyPath: mainTargetSourceFileGroupKeyPath]\n                .addFileReference { id in\n                    FileReference(\n                        id: id,\n                        path: path.pathString,\n                        pathBase: .absolute\n                    )\n                }\n            self.project[keyPath: mainModuleTargetKeyPath].addSourceFile { id in\n                BuildFile(id: id, fileRef: sourceFileRef)\n            }\n            log(.debug, indent: 2, \"Added generated source file '\\(path)'\")\n        }\n\n        // Add any additional resource files emitted by synthesized build commands\n        let generatedResourceFiles: [String] = {\n            var generatedResourceFiles = generatedFiles.resources.keys.map(\\.pathString)\n            generatedResourceFiles.append(\n                contentsOf: addBuildToolCommands(\n                    from: synthesizedResourceGeneratingPluginInvocationResults,\n                    targetKeyPath: mainModuleTargetKeyPath,\n                    addBuildToolPluginCommands: pifProductType == .application\n                )\n            )\n            return generatedResourceFiles\n        }()\n\n        // Create a separate target to build a resource bundle for any resources files in the product's main target.\n        // FIXME: We should extend this to other kinds of products, but the immediate need for Swift Playgrounds Projects is for applications.\n        if pifProductType == .application {\n            let result = processResources(\n                for: mainModule,\n                sourceModuleTargetKeyPath: mainModuleTargetKeyPath,\n                // For application products we embed the resources directly into the PIF target.\n                resourceBundleTargetKeyPath: nil,\n                generatedResourceFiles: generatedResourceFiles\n            )\n\n            if result.shouldGenerateBundleAccessor {\n                settings[.GENERATE_RESOURCE_ACCESSORS] = \"YES\"\n\n                // Do not set `SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE` here since it is just going to point to the same bundle as code.\n                // #bundle can use its default implementation for that.\n            }\n            if result.shouldGenerateEmbedInCodeAccessor {\n                settings[.GENERATE_EMBED_IN_CODE_ACCESSORS] = \"YES\"\n            }\n            // FIXME: We should also adjust the generated module bundle glue so that `Bundle.module` is a synonym for `Bundle.main` in this case.\n        } else {\n            let (result, resourceBundle) = try addResourceBundle(\n                for: mainModule,\n                targetKeyPath: mainModuleTargetKeyPath,\n                generatedResourceFiles: generatedResourceFiles\n            )\n            if let resourceBundle { self.builtModulesAndProducts.append(resourceBundle) }\n\n            if let resourceBundle = result.bundleName {\n                // Associate the resource bundle with the target.\n                settings[.PACKAGE_RESOURCE_BUNDLE_NAME] = resourceBundle\n\n                if result.shouldGenerateBundleAccessor {\n                    settings[.GENERATE_RESOURCE_ACCESSORS] = \"YES\"\n\n                    if mainModule.usesSwift {\n                        settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS].lazilyInitializeAndMutate(initialValue: [\"$(inherited)\"]) { $0.append(\"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\") }\n                    }\n                } else if mainModule.usesSwift {\n                    settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS].lazilyInitializeAndMutate(initialValue: [\"$(inherited)\"]) { $0.append(\"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\") }\n                }\n                if result.shouldGenerateEmbedInCodeAccessor {\n                    settings[.GENERATE_EMBED_IN_CODE_ACCESSORS] = \"YES\"\n                }\n\n                // If it's a kind of product that can contain resources, we also add a use of it.\n                let resourceBundleRef = self.project.mainGroup.addFileReference { id in\n                    FileReference(id: id, path: \"$(CONFIGURATION_BUILD_DIR)/\\(resourceBundle).bundle\")\n                }\n                if pifProductType == .bundle || pifProductType == .unitTest {\n                    settings[.COREML_CODEGEN_LANGUAGE] = mainModule.usesSwift ? \"Swift\" : \"Objective-C\"\n                    settings[.COREML_COMPILER_CONTAINER] = \"swift-package\"\n\n                    self.project[keyPath: mainModuleTargetKeyPath].addResourceFile { id in\n                        BuildFile(id: id, fileRef: resourceBundleRef)\n                    }\n                    log(.debug, indent: 2, \"Added use of resource bundle '\\(resourceBundleRef.path)'\")\n                } else {\n                    log(\n                        .debug,\n                        indent: 2,\n                        \"Ignored resource bundle '\\(resourceBundleRef.path)' for main module of type \\(type(of: mainModule))\"\n                    )\n                }\n\n                // Add build tool commands to the resource bundle target.\n                let mainResourceBundleTargetKeyPath = self.resourceBundleTargetKeyPath(forModuleName: mainModule.name)\n                let resourceBundleTargetKeyPath = mainResourceBundleTargetKeyPath ?? mainModuleTargetKeyPath\n\n                addBuildToolCommands(\n                    module: mainModule,\n                    sourceModuleTargetKeyPath: mainModuleTargetKeyPath,\n                    resourceBundleTargetKeyPath: resourceBundleTargetKeyPath,\n                    sourceFilePaths: generatedFiles.sources.map(\\.self),\n                    resourceFilePaths: generatedFiles.resources.keys.map(\\.pathString)\n                )\n            } else {\n                // Generated resources always trigger the creation of a bundle accessor.\n                settings[.GENERATE_RESOURCE_ACCESSORS] = \"YES\"\n                settings[.GENERATE_EMBED_IN_CODE_ACCESSORS] = \"NO\"\n\n                // Do not set `SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE` here since it is just going to point to the same bundle as code.\n                // #bundle can use its default implementation for that.\n\n                // If we did not create a resource bundle target,\n                // we still need to add build tool commands for any generated files.\n                addBuildToolCommands(\n                    module: mainModule,\n                    sourceModuleTargetKeyPath: mainModuleTargetKeyPath,\n                    resourceBundleTargetKeyPath: mainModuleTargetKeyPath,\n                    sourceFilePaths: generatedFiles.sources.map(\\.self),\n                    resourceFilePaths: generatedFiles.resources.keys.map(\\.pathString)\n                )\n            }\n        }\n\n        // Handle the main target's dependencies (and link against them).\n        mainModule.recursivelyTraverseDependencies { dependency in\n            switch dependency {\n            case .module(let moduleDependency, let packageConditions):\n                // This assertion is temporarily disabled since we may see targets from\n                // _other_ packages, but this should be resolved; see rdar://95467710.\n                /* assert(moduleDependency.packageName == self.package.name) */\n\n                switch moduleDependency.type {\n                case .binary:\n                    guard let binaryModule = moduleDependency.underlying as? BinaryModule else {\n                        log(.error, \"'\\(moduleDependency.name)' is a binary dependency, but its underlying module was not\")\n                        break\n                    }\n                    let binaryFileRef = self.binaryGroup.addFileReference { id in\n                        Self.createBinaryModuleFileReference(binaryModule, id: id)\n                    }\n                    let toolsVersion = self.package.manifest.toolsVersion\n                    self.project[keyPath: mainModuleTargetKeyPath].addLibrary { id in\n                        BuildFile(\n                            id: id,\n                            fileRef: binaryFileRef,\n                            platformFilters: packageConditions.toPlatformFilter(toolsVersion: toolsVersion),\n                            codeSignOnCopy: true,\n                            removeHeadersOnCopy: true\n                        )\n                    }\n                    log(.debug, indent: 1, \"Added use of binary library '\\(moduleDependency.path)'\")\n\n                case .plugin:\n                    let dependencyId = moduleDependency.pifTargetGUID\n                    self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(\n                        on: dependencyId,\n                        platformFilters: packageConditions\n                            .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                        linkProduct: false\n                    )\n                    log(.debug, indent: 1, \"Added use of plugin target '\\(dependencyId)'\")\n\n                case .macro:\n                    let dependencyId = moduleDependency.pifTargetGUID\n                    self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(\n                        on: dependencyId,\n                        platformFilters: packageConditions\n                            .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                        linkProduct: false\n                    )\n                    log(.debug, indent: 1, \"Added dependency on product '\\(dependencyId)'\")\n\n                    // Link with a testable version of the macro if appropriate.\n                    if product.type == .test {\n                        self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(\n                            on: moduleDependency.pifTargetGUID(suffix: .testable),\n                            platformFilters: packageConditions\n                                .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                            linkProduct: true\n                        )\n                        log(\n                            .debug,\n                            indent: 1,\n                            \"Added linked dependency on target '\\(moduleDependency.pifTargetGUID(suffix: .testable))'\"\n                        )\n\n                        // FIXME: Manually propagate product dependencies of macros but the build system should really handle this.\n                        moduleDependency.recursivelyTraverseDependencies { dependency in\n                            switch dependency {\n                            case .product(let productDependency, let packageConditions):\n                                let isLinkable = productDependency.isLinkable\n                                self.handleProduct(\n                                    productDependency,\n                                    with: packageConditions,\n                                    isLinkable: isLinkable,\n                                    targetKeyPath: mainModuleTargetKeyPath,\n                                    settings: &settings\n                                )\n                            case .module:\n                                break\n                            }\n                        }\n                    }\n\n                case .executable, .snippet:\n                    // For executable targets, we depend on the *product* instead\n                    // (i.e., we infuse the product's main module target into the one for the product itself).\n                    let productDependency = modulesGraph.allProducts.only { $0.mainModule?.name == moduleDependency.name }\n                    if let productDependency {\n                        let productDependencyGUID = productDependency.pifTargetGUID\n                        self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(\n                            on: productDependencyGUID,\n                            platformFilters: packageConditions\n                                .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                            linkProduct: false\n                        )\n                        log(.debug, indent: 1, \"Added dependency on product '\\(productDependencyGUID)'\")\n                    }\n\n                    // If we're linking against an executable and the tools version is new enough,\n                    // we also link against a testable version of the executable.\n                    if product.type == .test, self.package.manifest.toolsVersion >= .v5_5 {\n                        let moduleDependencyGUID = moduleDependency.pifTargetGUID(suffix: .testable)\n                        self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(\n                            on: moduleDependencyGUID,\n                            platformFilters: packageConditions\n                                .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                            // Only link the testable version of executables which use Swift, as we do not currently support renaming entrypoints written in other languages.\n                            linkProduct: moduleDependency.usesSwift\n                        )\n                        log(.debug, indent: 1, \"Added linked dependency on target '\\(moduleDependencyGUID)'\")\n                    }\n\n                case .library, .systemModule, .test:\n                    let shouldLinkProduct = moduleDependency.type != .systemModule\n                    let dependencyGUID = moduleDependency.pifTargetGUID\n                    self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(\n                        on: dependencyGUID,\n                        platformFilters: packageConditions\n                            .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                        linkProduct: shouldLinkProduct\n                    )\n                    log(\n                        .debug,\n                        indent: 1,\n                        \"Added \\(shouldLinkProduct ? \"linked \" : \"\")dependency on target '\\(dependencyGUID)'\"\n                    )\n                }\n\n            case .product(let productDependency, let packageConditions):\n                let isLinkable = productDependency.isLinkable\n                self.handleProduct(\n                    productDependency,\n                    with: packageConditions,\n                    isLinkable: isLinkable,\n                    targetKeyPath: mainModuleTargetKeyPath,\n                    settings: &settings\n                )\n            }\n        }\n\n        // Until this point the build settings for the target have been the same between debug and release\n        // configurations.\n        // The custom manifest settings might cause them to diverge.\n        var debugSettings: ProjectModel.BuildSettings = settings\n        var releaseSettings: ProjectModel.BuildSettings = settings\n\n        // Apply target-specific build settings defined in the manifest.\n        let allBuildSettings = mainModule.computeAllBuildSettings(observabilityScope: pifBuilder.observabilityScope, forRemotePackage: pifBuilder.delegate.isRemote)\n\n        // Apply settings using the convenience methods\n        allBuildSettings.apply(to: &debugSettings, for: .debug)\n        allBuildSettings.apply(to: &releaseSettings, for: .release)\n        self.project[keyPath: mainModuleTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Debug\", settings: debugSettings)\n        }\n        self.project[keyPath: mainModuleTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Release\", settings: releaseSettings)\n        }\n\n        // Collect linked binaries.\n        let linkedPackageBinaries: [PackagePIFBuilder.LinkedPackageBinary] = mainModule.dependencies.compactMap {\n            PackagePIFBuilder.LinkedPackageBinary(dependency: $0)\n        }\n\n        let moduleOrProduct = PackagePIFBuilder.ModuleOrProduct(\n            type: moduleOrProductType,\n            name: product.name,\n            moduleName: product.c99name,\n            pifTarget: .target(self.project[keyPath: mainModuleTargetKeyPath]),\n            indexableFileURLs: indexableFileURLs,\n            headerFiles: headerFiles,\n            linkedPackageBinaries: linkedPackageBinaries,\n            swiftLanguageVersion: mainModule.packageSwiftLanguageVersion(manifest: packageManifest),\n            declaredPlatforms: self.declaredPlatforms,\n            deploymentTargets: mainTargetDeploymentTargets\n        )\n        self.builtModulesAndProducts.append(moduleOrProduct)\n\n        if moduleOrProductType == .unitTest {\n            try makeTestRunnerProduct(for: moduleOrProduct)\n        }\n    }\n\n    private mutating func handleProduct(\n        _ product: PackageGraph.ResolvedProduct,\n        with packageConditions: [PackageModel.PackageCondition],\n        isLinkable: Bool,\n        targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n        settings: inout ProjectModel.BuildSettings\n    ) {\n        // Do not add a dependency for binary-only executable products since they are not part of the build.\n        if product.isBinaryOnlyExecutableProduct {\n            return\n        }\n\n        if !pifBuilder.delegate.shouldSuppressProductDependency(product: product.underlying, buildSettings: &settings) {\n            let shouldLinkProduct = isLinkable\n            self.project[keyPath: targetKeyPath].common.addDependency(\n                on: product.pifTargetGUID,\n                platformFilters: packageConditions.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                linkProduct: shouldLinkProduct\n            )\n            log(\n                .debug,\n                indent: 1,\n                \"Added \\(shouldLinkProduct ? \"linked \" : \"\")dependency on product '\\(product.pifTargetGUID)'\"\n            )\n        }\n    }\n\n    // MARK: - Library Products\n\n    /// We treat library products specially, in that they are just collections of other targets.\n    mutating func makeLibraryProduct(\n        _ libraryProduct: PackageGraph.ResolvedProduct,\n        type libraryType: ProductType.LibraryType\n    ) throws {\n        precondition(libraryProduct.type.isLibrary)\n\n        let library = try self.buildLibraryProduct(\n            libraryProduct,\n            type: libraryType,\n            embedResources: false\n        )\n        self.builtModulesAndProducts.append(library)\n\n        // Also create a dynamic product for use by development-time features such as Previews and Swift Playgrounds.\n        // If all targets this product is comprised of are binaries, we should *not* create a dynamic variant.\n        if libraryType == .automatic && libraryProduct.hasSourceTargets && pifBuilder.createDynamicVariantsForLibraryProducts {\n            var dynamicLibraryVariant = try self.buildLibraryProduct(\n                libraryProduct,\n                type: .dynamic,\n                targetSuffix: .dynamic,\n                embedResources: true\n            )\n            dynamicLibraryVariant.isDynamicLibraryVariant = true\n            self.builtModulesAndProducts.append(dynamicLibraryVariant)\n\n            guard let pifTarget = library.pifTarget,\n                  let pifTargetKeyPath = self.project.findTarget(id: pifTarget.id),\n                  let dynamicPifTarget = dynamicLibraryVariant.pifTarget\n            else {\n                fatalError(\"Could not assign dynamic PIF target\")\n            }\n            self.project[keyPath: pifTargetKeyPath].dynamicTargetVariantId = dynamicPifTarget.id\n        }\n    }\n\n    /// Helper function to create a PIF target for a **library product**.\n    ///\n    /// In order to support development-time features such as Preview and Swift Playgrounds,\n    /// all SwiftPM library products are represented by two PIF targets:\n    /// one of the \"native\" manifestation that gets linked into the client,\n    /// and another for a dynamic framework specifically for use by the development-time features.\n    private mutating func buildLibraryProduct(\n        _ product: PackageGraph.ResolvedProduct,\n        type desiredProductType: ProductType.LibraryType,\n        targetSuffix: TargetSuffix? = nil,\n        embedResources: Bool\n    ) throws -> PackagePIFBuilder.ModuleOrProduct {\n        precondition(product.type.isLibrary)\n\n        // FIXME: Cleanup this mess with <rdar://56889224>\n\n        let productType: ProjectModel.Target.ProductType\n        var productName = \"$(EXECUTABLE_NAME)\"\n        if desiredProductType == .dynamic {\n            if pifBuilder.createDylibForDynamicProducts {\n                productType = .dynamicLibrary\n            } else {\n                productName = \"$(WRAPPER_NAME)\"\n                productType = .framework\n            }\n        } else if pifBuilder.delegate.isRootPackage && pifBuilder.materializeStaticArchiveProductsForRootPackages {\n            productType = .staticArchive\n        } else {\n            productType = .packageProduct\n        }\n\n        // Create a special kind of PIF target that just \"groups\" a set of targets for clients to depend on.\n        // Swift Build will *not* produce a separate artifact for a package product, but will instead consider any\n        // dependency on the package product to be a dependency on the whole set of targets\n        // on which the package product depends.\n        let libraryUmbrellaTargetKeyPath = try self.project.addTarget { _ in\n            ProjectModel.Target(\n                id: product.pifTargetGUID(suffix: targetSuffix),\n                productType: productType,\n                name: product.targetName(suffix: targetSuffix),\n                productName: productName\n            )\n        }\n        do {\n            let librayTarget = self.project[keyPath: libraryUmbrellaTargetKeyPath]\n            log(\n                .debug,\n                \"Created target '\\(librayTarget.id)' of type '\\(librayTarget.productType)' with \" +\n                \"name '\\(librayTarget.name)' and product name '\\(librayTarget.productName)'\"\n            )\n        }\n\n        // Add linked dependencies on the *targets* that comprise the product.\n        for module in product.modules {\n            // Binary targets are special in that they are just linked, not built.\n            if let binaryTarget = module.underlying as? BinaryModule {\n                let binaryFileRef = self.binaryGroup.addFileReference { id in\n                    FileReference(id: id, path: binaryTarget.artifactPath.pathString)\n                }\n                self.project[keyPath: libraryUmbrellaTargetKeyPath].addLibrary { id in\n                    BuildFile(id: id, fileRef: binaryFileRef, codeSignOnCopy: true, removeHeadersOnCopy: true)\n                }\n                log(.debug, indent: 1, \"Added use of binary library '\\(binaryTarget.artifactPath)'\")\n                continue\n            }\n            // We add these as linked dependencies; because the product type is `.packageProduct`,\n            // SwiftBuild won't actually link them, but will instead impart linkage to any clients that\n            // link against the package product.\n            self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(\n                on: module.pifTargetGUID,\n                platformFilters: [],\n                linkProduct: true\n            )\n            log(.debug, indent: 1, \"Added linked dependency on target '\\(module.pifTargetGUID)'\")\n        }\n\n        for module in product.modules where module.underlying.isSourceModule && module.resources.hasContent {\n            // FIXME: Find a way to determine whether a module has generated resources\n            // here so that we can embed resources into dynamic targets.\n            self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(\n                on: pifTargetIdForResourceBundle(module.name),\n                platformFilters: []\n            )\n\n            let packageName = self.package.name\n            let fileRef = self.project.mainGroup.addFileReference { id in\n                FileReference(id: id, path: \"$(CONFIGURATION_BUILD_DIR)/\\(packageName)_\\(module.name).bundle\")\n            }\n            if embedResources {\n                self.project[keyPath: libraryUmbrellaTargetKeyPath].addResourceFile { id in\n                    BuildFile(id: id, fileRef: fileRef)\n                }\n                log(.debug, indent: 1, \"Added use of resource bundle '\\(fileRef.path)'\")\n            } else {\n                log(\n                    .debug,\n                    indent: 1,\n                    \"Ignored resource bundle '\\(fileRef.path)' because resource embedding is disabled\"\n                )\n            }\n        }\n\n        var settings: ProjectModel.BuildSettings = package.underlying.packageBaseBuildSettings\n\n        // Add other build settings when we're building an actual dylib.\n        if desiredProductType == .dynamic {\n            settings.configureDynamicSettings(\n                productName: product.name,\n                targetName: product.targetName(),\n                packageIdentity: package.identity,\n                packageName: package.identity.c99name,\n                createDylibForDynamicProducts: pifBuilder.createDylibForDynamicProducts,\n                installPath: installPath(for: product.underlying),\n                delegate: pifBuilder.delegate\n            )\n            // An empty sources phase is required in order to trigger linking.\n            self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addSourcesBuildPhase { id in\n                ProjectModel.SourcesBuildPhase(id: id)\n            }\n\n            // For dynamic libraries, track which source modules are DIRECT dependencies so we can set\n            // SWIFT_COMPILE_FOR_STATIC_LINKING=NO on Windows for those modules.\n            // Collect only DIRECT module dependencies (not recursive)\n            for module in product.modules where module.isSourceModule {\n                self.modulesInDynamicLibraries.insert(module.name)\n            }\n        } else if productType == .staticArchive {\n            settings[.TARGET_NAME] = product.targetName()\n            settings[.TARGET_TEMP_DIR_SUFFIX] = \"-p\"\n            settings[.PRODUCT_NAME] = product.name\n\n            // This should really be swift-build defaults set in the .xcspec files, but changing that requires\n            // some extensive testing to ensure xcode projects are not affected.\n            // So for now lets just force it here.\n            settings[.EXECUTABLE_PREFIX] = \"lib\"\n            settings[.EXECUTABLE_PREFIX, ProjectModel.BuildSettings.Platform.windows] = \"\"\n            // An empty sources phase is required in order to trigger linking.\n            self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addSourcesBuildPhase { id in\n                ProjectModel.SourcesBuildPhase(id: id)\n            }\n        }\n\n        // Additional configuration and files for this library product.\n        pifBuilder.delegate.configureLibraryProduct(\n            product: product.underlying,\n            project: &self.project,\n            target: libraryUmbrellaTargetKeyPath,\n            additionalFiles: additionalFilesGroupKeyPath\n        )\n\n        // If the given package is a root package or it is used via a branch/revision, we allow unsafe flags.\n        let implicitlyAllowAllUnsafeFlags = pifBuilder.delegate.isBranchOrRevisionBased ||\n            pifBuilder.delegate.isUserManaged\n        let recordUsesUnsafeFlags = try !implicitlyAllowAllUnsafeFlags && product.usesUnsafeFlags\n        settings[.USES_SWIFTPM_UNSAFE_FLAGS] = recordUsesUnsafeFlags ? \"YES\" : \"NO\"\n\n        // Handle the dependencies of the targets in the product\n        // (and link against them, which in the case of a package product, really just means that clients should link\n        // against them).\n        product.modules.recursivelyTraverseDependencies { dependency in\n            switch dependency {\n            case .module(let moduleDependency, let packageConditions):\n                // This assertion is temporarily disabled since we may see targets from\n                // _other_ packages, but this should be resolved; see rdar://95467710.\n                /* assert(moduleDependency.packageName == self.package.name) */\n\n                if moduleDependency.type == .systemModule {\n                    log(.debug, indent: 1, \"Noted use of system module '\\(moduleDependency.name)'\")\n                    return\n                }\n\n                if let binaryTarget = moduleDependency.underlying as? BinaryModule {\n                    let binaryFileRef = self.binaryGroup.addFileReference { id in\n                        FileReference(id: id, path: binaryTarget.artifactPath.pathString)\n                    }\n                    let toolsVersion = package.manifest.toolsVersion\n                    self.project[keyPath: libraryUmbrellaTargetKeyPath].addLibrary { id in\n                        BuildFile(\n                            id: id,\n                            fileRef: binaryFileRef,\n                            platformFilters: packageConditions.toPlatformFilter(toolsVersion: toolsVersion),\n                            codeSignOnCopy: true,\n                            removeHeadersOnCopy: true\n                        )\n                    }\n                    log(.debug, indent: 1, \"Added use of binary library '\\(binaryTarget.path)'\")\n                    return\n                }\n\n                if moduleDependency.type == .plugin {\n                    let dependencyId = moduleDependency.pifTargetGUID\n                    self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(\n                        on: dependencyId,\n                        platformFilters: packageConditions\n                            .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                        linkProduct: false\n                    )\n                    log(.debug, indent: 1, \"Added use of plugin target '\\(dependencyId)'\")\n                    return\n                }\n\n                // If this dependency is already present in the product's module target then don't re-add it.\n                if product.modules.contains(where: { $0.name == moduleDependency.name }) { return }\n\n                // For executable targets, add a build time dependency on the product.\n                // FIXME: Maybe we should we do this at the libSwiftPM level.\n                if moduleDependency.isExecutable {\n                    let mainModuleProducts = package.products.filter(\\.isMainModuleProduct)\n\n                    if let product = moduleDependency\n                        .productRepresentingDependencyOfBuildPlugin(in: mainModuleProducts)\n                    {\n                        self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(\n                            on: product.pifTargetGUID,\n                            platformFilters: packageConditions\n                                .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                            linkProduct: false\n                        )\n                        log(.debug, indent: 1, \"Added dependency on product '\\(product.pifTargetGUID)'\")\n                        return\n                    } else {\n                        log(\n                            .debug,\n                            indent: 1,\n                            \"Could not find a build plugin product to depend on for target '\\(product.pifTargetGUID)'\"\n                        )\n                    }\n                }\n\n                self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(\n                    on: moduleDependency.pifTargetGUID,\n                    platformFilters: packageConditions.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                    linkProduct: true\n                )\n                log(.debug, indent: 1, \"Added linked dependency on target '\\(moduleDependency.pifTargetGUID)'\")\n\n            case .product(let productDependency, let packageConditions):\n                // Do not add a dependency for binary-only executable products since they are not part of the build.\n                if productDependency.isBinaryOnlyExecutableProduct {\n                    return\n                }\n\n                if !pifBuilder.delegate.shouldSuppressProductDependency(\n                    product: productDependency.underlying,\n                    buildSettings: &settings\n                ) {\n                    let shouldLinkProduct = productDependency.isLinkable\n                    self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(\n                        on: productDependency.pifTargetGUID,\n                        platformFilters: packageConditions\n                            .toPlatformFilter(toolsVersion: package.manifest.toolsVersion),\n                        linkProduct: shouldLinkProduct\n                    )\n                    log(\n                        .debug,\n                        indent: 1,\n                        \"Added \\(shouldLinkProduct ? \"linked\" : \"\") dependency on product '\\(productDependency.pifTargetGUID)'\"\n                    )\n                }\n            }\n        }\n\n        // For *registry* packages, vend any registry release metadata to the build system.\n        if let metadata = package.registryMetadata,\n           let signature = metadata.signature,\n           let version = pifBuilder.packageDisplayVersion,\n           case RegistryReleaseMetadata.Source.registry(let url) = metadata.source\n        {\n            let signatureData = PackageRegistrySignature(\n                packageIdentity: package.identity.description,\n                packageVersion: version,\n                signature: signature,\n                libraryName: product.name,\n                source: .registry(url: url)\n            )\n\n            let encoder = PropertyListEncoder()\n            encoder.outputFormat = .xml\n            let data = try encoder.encode(signatureData)\n            settings[.PACKAGE_REGISTRY_SIGNATURE] = String(data: data, encoding: .utf8)\n        }\n\n        self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Debug\", settings: settings)\n        }\n        self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Release\", settings: settings)\n        }\n\n        // Collect linked binaries.\n        let linkedPackageBinaries = product.modules.compactMap {\n            PackagePIFBuilder.LinkedPackageBinary(module: $0)\n        }\n\n        let moduleOrProductType: PackagePIFBuilder.ModuleOrProductType = switch product.libraryType {\n        case .dynamic:\n            pifBuilder.createDylibForDynamicProducts ? .dynamicLibrary : .framework\n        default:\n            .staticArchive\n        }\n\n        return PackagePIFBuilder.ModuleOrProduct(\n            type: moduleOrProductType,\n            name: product.name,\n            moduleName: product.c99name,\n            pifTarget: .target(self.project[keyPath: libraryUmbrellaTargetKeyPath]),\n            indexableFileURLs: [],\n            headerFiles: [],\n            linkedPackageBinaries: linkedPackageBinaries,\n            swiftLanguageVersion: nil,\n            declaredPlatforms: self.declaredPlatforms,\n            deploymentTargets: self.deploymentTargets\n        )\n    }\n\n    // MARK: - System Library Products\n\n    mutating func makeSystemLibraryProduct(_ product: PackageGraph.ResolvedProduct) throws {\n        precondition(product.type == .library(.automatic))\n\n        let systemLibraryTargetKeyPath = try self.project.addTarget { _ in\n            ProjectModel.Target(\n                id: product.pifTargetGUID,\n                productType: .packageProduct,\n                name: product.targetName(),\n                productName: product.name\n            )\n        }\n        do {\n            let systemLibraryTarget = self.project[keyPath: systemLibraryTargetKeyPath]\n            log(\n                .debug,\n                \"Created target '\\(systemLibraryTarget.id)' of type '\\(systemLibraryTarget.productType)' \" +\n                \"with name '\\(systemLibraryTarget.name)' and product name '\\(systemLibraryTarget.productName)'\"\n            )\n        }\n\n        let buildSettings = self.package.underlying.packageBaseBuildSettings\n        self.project[keyPath: systemLibraryTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Debug\", settings: buildSettings)\n        }\n        self.project[keyPath: systemLibraryTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Release\", settings: buildSettings)\n        }\n\n        self.project[keyPath: systemLibraryTargetKeyPath].common.addDependency(\n            on: product.systemModule!.pifTargetGUID,\n            platformFilters: [],\n            linkProduct: false\n        )\n\n        let systemLibrary = PackagePIFBuilder.ModuleOrProduct(\n            type: .staticArchive,\n            name: product.name,\n            moduleName: product.c99name,\n            pifTarget: .target(self.project[keyPath: systemLibraryTargetKeyPath]),\n            indexableFileURLs: [],\n            headerFiles: [],\n            linkedPackageBinaries: [],\n            swiftLanguageVersion: nil,\n            declaredPlatforms: self.declaredPlatforms,\n            deploymentTargets: self.deploymentTargets\n        )\n        self.builtModulesAndProducts.append(systemLibrary)\n    }\n\n    // MARK: - Plugin Product\n\n    mutating func makePluginProduct(_ pluginProduct: PackageGraph.ResolvedProduct) throws {\n        precondition(pluginProduct.type == .plugin)\n\n        let pluginTargetKeyPath = try self.project.addAggregateTarget { _ in\n            ProjectModel.AggregateTarget(\n                id: pluginProduct.pifTargetGUID,\n                name: pluginProduct.targetName()\n            )\n        }\n        do {\n            let pluginTarget = self.project[keyPath: pluginTargetKeyPath]\n            log(.debug, \"Created aggregate target '\\(pluginTarget.id)' with name '\\(pluginTarget.name)'\")\n        }\n\n        let buildSettings: ProjectModel.BuildSettings = package.underlying.packageBaseBuildSettings\n\n        self.project[keyPath: pluginTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Debug\", settings: buildSettings)\n        }\n        self.project[keyPath: pluginTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Release\", settings: buildSettings)\n        }\n\n        for pluginModule in pluginProduct.pluginModules! {\n            self.project[keyPath: pluginTargetKeyPath].common.addDependency(\n                on: pluginModule.pifTargetGUID,\n                platformFilters: []\n            )\n        }\n\n        let pluginType: PackagePIFBuilder.ModuleOrProductType = {\n            if let pluginTarget = pluginProduct.pluginModules!.only {\n                switch pluginTarget.capability {\n                case .buildTool:\n                    return .buildToolPlugin\n                case .command:\n                    return .commandPlugin\n                }\n            } else {\n                assertionFailure(\n                    \"This should never be reached since there is always exactly one plugin target in a product by definition\"\n                )\n                return .commandPlugin\n            }\n        }()\n\n        let pluginProductMetadata = PackagePIFBuilder.ModuleOrProduct(\n            type: pluginType,\n            name: pluginProduct.name,\n            moduleName: pluginProduct.c99name,\n            pifTarget: .aggregate(self.project[keyPath: pluginTargetKeyPath]),\n            indexableFileURLs: [],\n            headerFiles: [],\n            linkedPackageBinaries: [],\n            swiftLanguageVersion: nil,\n            declaredPlatforms: self.declaredPlatforms,\n            deploymentTargets: self.deploymentTargets\n        )\n        self.builtModulesAndProducts.append(pluginProductMetadata)\n    }\n\n    // MARK: - Test Runners\n    mutating func makeTestRunnerProduct(for unitTestProduct: PackagePIFBuilder.ModuleOrProduct) throws {\n        // Only generate a test runner for root packages with tests.\n        guard pifBuilder.delegate.isRootPackage else {\n            return\n        }\n\n        guard let unitTestModuleName = unitTestProduct.moduleName else {\n            throw StringError(\"Unit test product '\\(unitTestProduct.name)' is missing a module name\")\n        }\n\n        let name = \"\\(unitTestProduct.name)-test-runner\"\n        let moduleName = \"\\(unitTestModuleName)_test_runner\"\n        let guid = PackagePIFBuilder.targetGUID(forModuleName: moduleName)\n\n        let testRunnerTargetKeyPath = try self.project.addTarget { _ in\n            ProjectModel.Target (\n                id: guid,\n                productType: .swiftpmTestRunner,\n                name: name,\n                productName: name\n            )\n        }\n\n        var settings: BuildSettings = self.package.underlying.packageBaseBuildSettings\n        let impartedSettings = BuildSettings()\n\n        settings[.TARGET_NAME] = name\n        settings[.PACKAGE_RESOURCE_TARGET_KIND] = \"regular\"\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        settings[.PRODUCT_MODULE_NAME] = moduleName\n        settings[.PRODUCT_BUNDLE_IDENTIFIER] = \"\\(self.package.identity).\\(name)\"\n            .spm_mangledToBundleIdentifier()\n        settings[.SKIP_INSTALL] = \"NO\"\n        settings[.SWIFT_VERSION] = \"5.0\"\n        // This should eventually be set universally for all package targets/products.\n        settings[.LINKER_DRIVER] = \"swiftc\"\n\n        // A test-runner should always be adjacent to the dynamic library containing the tests,\n        // so add the appropriate rpaths.\n        if pifBuilder.addLocalRpaths {\n            settings[.LD_RUNPATH_SEARCH_PATHS] = [\n                \"$(inherited)\",\n                \"$(RPATH_ORIGIN)\"\n            ]\n        }\n\n        let deploymentTargets = unitTestProduct.deploymentTargets\n        settings[.MACOSX_DEPLOYMENT_TARGET] = deploymentTargets?[.macOS] ?? nil\n        settings[.IPHONEOS_DEPLOYMENT_TARGET] = deploymentTargets?[.iOS] ?? nil\n        if let deploymentTarget_macCatalyst = deploymentTargets?[.macCatalyst] ?? nil {\n            settings[.IPHONEOS_DEPLOYMENT_TARGET, .macCatalyst] = deploymentTarget_macCatalyst\n        }\n        settings[.TVOS_DEPLOYMENT_TARGET] = deploymentTargets?[.tvOS] ?? nil\n        settings[.WATCHOS_DEPLOYMENT_TARGET] = deploymentTargets?[.watchOS] ?? nil\n        settings[.DRIVERKIT_DEPLOYMENT_TARGET] = deploymentTargets?[.driverKit] ?? nil\n        settings[.XROS_DEPLOYMENT_TARGET] = deploymentTargets?[.visionOS] ?? nil\n\n        // Add an empty sources phase so derived sources are compiled\n        self.project[keyPath: testRunnerTargetKeyPath].common.addSourcesBuildPhase { id in\n            ProjectModel.SourcesBuildPhase(id: id)\n        }\n\n        guard let unitTestGUID = unitTestProduct.pifTarget?.id else {\n            throw StringError(\"Unit test product '\\(unitTestProduct.name)' is missing a PIF GUID\")\n        }\n        self.project[keyPath: testRunnerTargetKeyPath].common.addDependency(\n            on: unitTestGUID,\n            platformFilters: [],\n            linkProduct: true\n        )\n\n        self.project[keyPath: testRunnerTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(\n                id: id,\n                name: \"Debug\",\n                settings: settings,\n                impartedBuildSettings: impartedSettings\n            )\n        }\n        self.project[keyPath: testRunnerTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(\n                id: id,\n                name: \"Release\",\n                settings: settings,\n                impartedBuildSettings: impartedSettings\n            )\n        }\n\n        let testRunner = PackagePIFBuilder.ModuleOrProduct(\n            type: .unitTestRunner,\n            name: name,\n            moduleName: moduleName,\n            pifTarget: .target(self.project[keyPath: testRunnerTargetKeyPath]),\n            indexableFileURLs: [],\n            headerFiles: [],\n            linkedPackageBinaries: [],\n            swiftLanguageVersion: nil,\n            declaredPlatforms: self.declaredPlatforms,\n            deploymentTargets: self.deploymentTargets\n        )\n        self.builtModulesAndProducts.append(testRunner)\n    }\n\n    mutating func makePackageTestProduct() throws {\n        let productName = packageManifest.umbrellaPackageTestsProductName\n        let packageIdentity = package.identity\n        let packageTestProductKeyPath = try project.addAggregateTarget { _ in\n            ProjectModel.AggregateTarget(\n                id: PackagePIFBuilder.targetGUID(forProductName: productName, withId: \"\\(packageIdentity.description)-\\(productName)\"),\n                name: PackagePIFBuilder.targetName(forProductName: productName)\n            )\n        }\n\n        for config in [\"Debug\", \"Release\"] {\n            project[keyPath: packageTestProductKeyPath].common.addBuildConfig { id in\n                BuildConfig(id: id, name: config, settings: BuildSettings())\n            }\n        }\n\n        for target in project.targets {\n            switch target {\n            case .target(let target):\n                switch target.productType {\n                case .unitTest, .swiftpmTestRunner:\n                    project[keyPath: packageTestProductKeyPath].common.addDependency(\n                        on: target.id,\n                        platformFilters: [],\n                        linkProduct: false\n                    )\n                default:\n                    break\n                }\n            case .aggregate:\n                break\n            }\n        }\n    }\n}\n\n// MARK: - Helper Types\n\nprivate struct PackageRegistrySignature: Encodable {\n    enum Source: Encodable {\n        case registry(url: Foundation.URL)\n    }\n\n    let packageIdentity: String\n    let packageVersion: String\n    let signature: RegistryReleaseMetadata.RegistrySignature\n    let libraryName: String\n    let source: Source\n    let formatVersion = 2\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PackagePIFProjectBuilder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport TSCUtility\n\nimport struct Basics.AbsolutePath\nimport struct Basics.Diagnostic\nimport class Basics.ObservabilitySystem\nimport struct Basics.SourceControlURL\n\nimport class PackageModel.ClangModule\nimport class PackageModel.Manifest\nimport struct PackageModel.Platform\nimport class PackageModel.Product\nimport struct PackageModel.Resource\nimport struct PackageModel.ToolsVersion\n\nimport struct PackageGraph.ModulesGraph\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedPackage\n\nimport struct PackageLoading.FileRuleDescription\nimport struct PackageLoading.TargetSourcesBuilder\nimport struct PackageLoading.GeneratedFiles\n\nimport struct SwiftBuild.Pair\nimport enum SwiftBuild.ProjectModel\nimport struct SwiftBuild.SwiftBuildFileType\n\n/// Helper type to create PIF **project** and **targets** for a given package.\nstruct PackagePIFProjectBuilder {\n    let pifBuilder: PackagePIFBuilder\n    let package: PackageGraph.ResolvedPackage\n    let packageManifest: PackageModel.Manifest\n    let modulesGraph: PackageGraph.ModulesGraph\n\n    var project: ProjectModel.Project\n\n    let binaryGroupKeyPath: WritableKeyPath<ProjectModel.Group, ProjectModel.Group>\n    var binaryGroup: ProjectModel.Group {\n        get { self.project.mainGroup[keyPath: self.binaryGroupKeyPath] }\n        set { self.project.mainGroup[keyPath: self.binaryGroupKeyPath] = newValue }\n    }\n\n    let additionalFilesGroupKeyPath: WritableKeyPath<ProjectModel.Group, ProjectModel.Group>\n    var additionalFilesGroup: ProjectModel.Group {\n        get { self.project.mainGroup[keyPath: self.additionalFilesGroupKeyPath] }\n        set { self.project.mainGroup[keyPath: self.additionalFilesGroupKeyPath] = newValue }\n    }\n\n    let declaredPlatforms: [PackageModel.Platform]?\n    let deploymentTargets: [PackageModel.Platform: String?]\n\n    /// Current set of names of any package products that are explicitly declared dynamic libraries.\n    private let dynamicLibraryProductNames: Set<String>\n\n    /// Module names that are direct dependencies of dynamic library products.\n    /// These modules should be compiled without static linking on Windows.\n    var modulesInDynamicLibraries: Set<String> = []\n\n    /// FIXME: We should eventually clean this up but right now we have to carry over this\n    /// bit of information from processing the *products* to processing the *targets*.\n    var mainModuleTargetNamesWithResources: Set<String> = []\n\n    var builtModulesAndProducts: [PackagePIFBuilder.ModuleOrProduct]\n\n    func log(\n        _ severity: Diagnostic.Severity,\n        indent: UInt = 0,\n        _ message: String,\n        sourceFile: StaticString = #fileID,\n        sourceLine: UInt = #line\n    ) {\n        self.pifBuilder.observabilityScope.logPIF(\n            severity,\n            indent: indent,\n            message,\n            sourceFile: sourceFile,\n            sourceLine: sourceLine\n        )\n    }\n\n    init(createForPackage package: PackageGraph.ResolvedPackage, builder: PackagePIFBuilder) {\n        // Create a PIF project using an identifier that's based on the normalized absolute path of the package.\n        // We use the package manifest path as the project path, and the package path as the project's base source\n        // directory.\n        // FIXME: The PIF creation should ideally be done on a background thread.\n        var pifProject = ProjectModel.Project(\n            id: \"PACKAGE:\\(package.identity)\",\n            path: package.manifest.path.pathString,\n            projectDir: package.path.pathString,\n            name: package.name,\n            developmentRegion: package.manifest.defaultLocalization\n        )\n\n        let additionalFilesGroupKeyPath = pifProject.mainGroup.addGroup { id in\n            ProjectModel.Group(\n                id: id,\n                path: \"/\",\n                pathBase: .absolute,\n                name: \"AdditionalFiles\"\n            )\n        }\n        let binaryGroupKeyPath = pifProject.mainGroup.addGroup { id in\n            ProjectModel.Group(\n                id: id,\n                path: \"/\",\n                pathBase: .absolute,\n                name: \"Binaries\"\n            )\n        }\n\n        // Test modules have a higher minimum deployment target by default,\n        // so we favor non-test modules as representative for the package's deployment target.\n        let firstModule = package.modules.first { $0.type != .test } ?? package.modules.first\n\n        let moduleDeploymentTargets = firstModule?.deploymentTargets(using: builder.delegate)\n\n        // The deployment targets are passed through to the eventual `ModuleOrProduct` values,\n        // so that querying them yields reasonable results for those build settings.\n        var deploymentTargets: [PackageModel.Platform: String?] = [\n            .macOS: moduleDeploymentTargets?[.macOS],\n            .macCatalyst: moduleDeploymentTargets?[.macCatalyst],\n            .iOS: moduleDeploymentTargets?[.iOS],\n            .tvOS: moduleDeploymentTargets?[.tvOS],\n            .watchOS: moduleDeploymentTargets?[.watchOS],\n            .driverKit: moduleDeploymentTargets?[.driverKit],\n        ]\n        deploymentTargets[.visionOS] = moduleDeploymentTargets?[.visionOS]\n        let declaredPlatforms = firstModule?.declaredPlatforms\n\n        // Compute the names of all explicitly dynamic library products, we need to avoid\n        // name clashes with any package targets we could decide to build dynamically.\n        let allPackages = builder.modulesGraph.packages\n        let dynamicLibraryProductNames = Set(\n            allPackages\n                .flatMap(\\.products)\n                .filter { $0.type == .library(.dynamic) }\n                .map(\\.name)\n        )\n\n        self.pifBuilder = builder\n        self.package = package\n        self.packageManifest = self.pifBuilder.packageManifest\n        self.modulesGraph = self.pifBuilder.modulesGraph\n        self.project = pifProject\n        self.binaryGroupKeyPath = binaryGroupKeyPath\n        self.additionalFilesGroupKeyPath = additionalFilesGroupKeyPath\n        self.declaredPlatforms = declaredPlatforms\n        self.deploymentTargets = deploymentTargets\n        self.dynamicLibraryProductNames = dynamicLibraryProductNames\n        self.builtModulesAndProducts = []\n    }\n\n    // MARK: - Handling Resources\n\n    mutating func addResourceBundle(\n        for module: PackageGraph.ResolvedModule,\n        targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n        generatedResourceFiles: [String]\n    ) throws -> (PackagePIFBuilder.EmbedResourcesResult, PackagePIFBuilder.ModuleOrProduct?) {\n        if module.resources.isEmpty && generatedResourceFiles.isEmpty {\n            return (PackagePIFBuilder.EmbedResourcesResult(\n                bundleName: nil,\n                shouldGenerateBundleAccessor: false,\n                shouldGenerateEmbedInCodeAccessor: false\n            ), nil)\n        }\n\n        let bundleName = self.resourceBundleName(forModuleName: module.name)\n        let resourceBundleGUID = self.pifTargetIdForResourceBundle(module.name)\n        let resourcesTargetKeyPath = try self.project.addTarget { _ in\n            ProjectModel.Target(\n                id: resourceBundleGUID,\n                productType: .bundle,\n                name: bundleName,\n                productName: bundleName\n            )\n        }\n        var resourcesTarget: ProjectModel.Target { self.project[keyPath: resourcesTargetKeyPath] }\n\n        self.project[keyPath: targetKeyPath].common.addDependency(\n            on: resourcesTarget.id,\n            platformFilters: [],\n            linkProduct: false\n        )\n        self.log(.debug, indent: 1, \"Added dependency on resource target '\\(resourcesTarget.id)'\")\n\n        for pluginModule in module.pluginsAppliedToModule {\n            self.project[keyPath: resourcesTargetKeyPath].common.addDependency(\n                on: pluginModule.pifTargetGUID,\n                platformFilters: [],\n                linkProduct: false\n            )\n        }\n\n        self.log(\n            .debug,\n            indent: 1,\n            \"Created target '\\(resourcesTarget.id)' of type '\\(resourcesTarget.productType)' \" +\n            \"with name '\\(resourcesTarget.name)' and product name '\\(resourcesTarget.productName)'\"\n        )\n\n        var settings: ProjectModel.BuildSettings = self.package.underlying.packageBaseBuildSettings\n        settings[.TARGET_NAME] = bundleName\n        settings[.TARGET_TEMP_DIR_SUFFIX] = \"-b\"\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        settings[.PRODUCT_MODULE_NAME] = bundleName\n        settings[.PRODUCT_BUNDLE_IDENTIFIER] = \"\\(self.package.identity).\\(module.name).resources\"\n            .spm_mangledToBundleIdentifier()\n        // Resource bundles are not executable. Setting the name to an empty string will\n        // omit the CFBundleExecutable key from the Info.plist.\n        settings[.EXECUTABLE_NAME] = \"\"\n        settings[.GENERATE_INFOPLIST_FILE] = \"YES\"\n        settings[.PACKAGE_RESOURCE_TARGET_KIND] = \"resource\"\n\n        settings[.COREML_COMPILER_CONTAINER] = \"swift-package\"\n        settings[.COREML_CODEGEN_LANGUAGE] = \"None\"\n\n        self.project[keyPath: resourcesTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Debug\", settings: settings)\n        }\n        self.project[keyPath: resourcesTargetKeyPath].common.addBuildConfig { id in\n            BuildConfig(id: id, name: \"Release\", settings: settings)\n        }\n\n        let result = self.processResources(\n            for: module,\n            sourceModuleTargetKeyPath: targetKeyPath,\n            resourceBundleTargetKeyPath: resourcesTargetKeyPath,\n            generatedResourceFiles: generatedResourceFiles\n        )\n\n        let resourceBundle = PackagePIFBuilder.ModuleOrProduct(\n            type: .resourceBundle,\n            name: bundleName,\n            moduleName: bundleName,\n            pifTarget: .target(resourcesTarget),\n            indexableFileURLs: [],\n            headerFiles: [],\n            linkedPackageBinaries: [],\n            swiftLanguageVersion: nil,\n            declaredPlatforms: [],\n            deploymentTargets: [:]\n        )\n\n        return (result, resourceBundle)\n    }\n\n    mutating func processResources(\n        for module: PackageGraph.ResolvedModule,\n        sourceModuleTargetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n        resourceBundleTargetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>?,\n        generatedResourceFiles: [String]\n    ) -> PackagePIFBuilder.EmbedResourcesResult {\n        if module.resources.isEmpty && generatedResourceFiles.isEmpty {\n            return PackagePIFBuilder.EmbedResourcesResult(\n                bundleName: nil,\n                shouldGenerateBundleAccessor: false,\n                shouldGenerateEmbedInCodeAccessor: false\n            )\n        }\n        // If resourceBundleTarget is nil, we add resources to the sourceModuleTarget instead.\n        let targetForResourcesKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target> =\n            resourceBundleTargetKeyPath ?? sourceModuleTargetKeyPath\n\n        // Generated resources get a default treatment for rule and localization.\n        let generatedResources = generatedResourceFiles.compactMap {\n            PackagePIFBuilder.Resource(path: $0, rule: .process(localization: nil))\n        }\n\n        let resources = module.resources.map { PackagePIFBuilder.Resource($0) } + generatedResources\n        let shouldGenerateBundleAccessor = resources.anySatisfy { $0.rule != .embedInCode }\n        let shouldGenerateEmbedInCodeAccessor = resources.anySatisfy { $0.rule == .embedInCode }\n\n        for resource in resources {\n            let resourcePath = resource.path\n            // Add a file reference for the resource. We use an absolute path, as for all the other files,\n            // but we should be able to optimize this later by making it group-relative.\n            let ref = self.project.mainGroup.addFileReference { id in\n                ProjectModel.FileReference(id: id, path: resourcePath, pathBase: .absolute)\n            }\n\n            // CoreData files should also be in the actual target because they\n            // can end up generating code during the build.\n            // The build system will only perform codegen tasks for the main target in this case.\n            let isCoreDataFile = [SwiftBuild.SwiftBuildFileType.xcdatamodeld, .xcdatamodel]\n                .contains { $0.fileTypes.contains(resourcePath.pathExtension) }\n\n            if isCoreDataFile {\n                self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in\n                    BuildFile(id: id, fileRef: ref)\n                }\n                self.log(.debug, indent: 2, \"Added core data resource as source file '\\(resourcePath)'\")\n            }\n\n            // Core ML files need to be included in the source module as well, because there is code generation.\n            let coreMLFileTypes: [SwiftBuild.SwiftBuildFileType] = [.mlmodel, .mlpackage]\n            let isCoreMLFile = coreMLFileTypes.contains { $0.fileTypes.contains(resourcePath.pathExtension) }\n\n            if isCoreMLFile {\n                self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in\n                    BuildFile(id: id, fileRef: ref, generatedCodeVisibility: .public)\n                }\n                self.log(.debug, indent: 2, \"Added coreml resource as source file '\\(resourcePath)'\")\n            }\n\n            // Metal source code needs to be added to the source build phase.\n            let isMetalFile = SwiftBuild.SwiftBuildFileType.metal.fileTypes.contains(resourcePath.pathExtension)\n\n            if isMetalFile, case .process = resource.rule {\n                self.project[keyPath: targetForResourcesKeyPath].addSourceFile { id in\n                    BuildFile(id: id, fileRef: ref)\n                }\n            } else {\n                let swiftBuildResourceRule: BuildFile.ResourceRule\n                switch resource.rule {\n                case .process:\n                    swiftBuildResourceRule = .process\n                case .copy:\n                    swiftBuildResourceRule = .copy\n                case .embedInCode:\n                    swiftBuildResourceRule = .embedInCode\n                }\n                self.project[keyPath: targetForResourcesKeyPath].addResourceFile { id in\n                    BuildFile(\n                        id: id,\n                        fileRef: ref,\n                        platformFilters: [],\n                        resourceRule: swiftBuildResourceRule\n                    )\n                }\n            }\n\n            // Asset Catalogs need to be included in the sources modules for generated asset symbols.\n            let isAssetCatalog = resourcePath.pathExtension == \"xcassets\"\n            if isAssetCatalog {\n                self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in\n                    BuildFile(id: id, fileRef: ref)\n                }\n                self.log(.debug, indent: 2, \"Added asset catalog as source file '\\(resourcePath)'\")\n            }\n\n            // String Catalogs can also generate symbols.\n            if SwiftBuild.SwiftBuildFileType.xcstrings.fileTypes.contains(resourcePath.pathExtension) {\n                self.project[keyPath: sourceModuleTargetKeyPath].addSourceFile { id in\n                    BuildFile(id: id, fileRef: ref)\n                }\n                self.log(.debug, indent: 2, \"Added string catalog as source file '\\(resourcePath)'\")\n            }\n\n            self.log(.debug, indent: 2, \"Added resource file '\\(resourcePath)'\")\n        }\n\n        let resourceBundleTargetName: String?\n        if let resourceBundleTargetKeyPath {\n            let resourceBundleTarget = self.project[keyPath: resourceBundleTargetKeyPath]\n            resourceBundleTargetName = resourceBundleTarget.name\n        } else {\n            resourceBundleTargetName = nil\n        }\n\n        return PackagePIFBuilder.EmbedResourcesResult(\n            bundleName: resourceBundleTargetName,\n            shouldGenerateBundleAccessor: shouldGenerateBundleAccessor,\n            shouldGenerateEmbedInCodeAccessor: shouldGenerateEmbedInCodeAccessor\n        )\n    }\n\n    func resourceBundleTargetKeyPath(\n        forModuleName name: String\n    ) -> WritableKeyPath<ProjectModel.Project, ProjectModel.Target>? {\n        let resourceBundleGUID = self.pifTargetIdForResourceBundle(name)\n        let targetKeyPath = self.project.findTarget(id: resourceBundleGUID)\n        return targetKeyPath\n    }\n\n    func pifTargetIdForResourceBundle(_ name: String) -> GUID {\n        GUID(\"PACKAGE-RESOURCE:\\(name)\")\n    }\n\n    func resourceBundleName(forModuleName name: String) -> String {\n        \"\\(self.package.name)_\\(name)\"\n    }\n\n    // MARK: - Plugin Helpers\n\n    /// Helper function that compiles the plugin-generated files for a target,\n    /// optionally also adding the corresponding plugin-provided commands to the PIF target.\n    ///\n    /// The reason we might not add them is that some targets are derivatives of other targets — in such cases,\n    /// only the primary target adds the build tool commands to the PIF target.\n    mutating func computePluginGeneratedFiles(\n        module: PackageGraph.ResolvedModule,\n        targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n        addBuildToolPluginCommands: Bool\n    ) -> GeneratedFiles {\n        var generatedFiles = GeneratedFiles()\n        guard let pluginResults = pifBuilder.buildToolPluginResultsByTargetName[module.name] else {\n            // We found no results for the target.\n            return generatedFiles\n        }\n\n        for pluginResult in pluginResults {\n            // Process the results of applying any build tool plugins on the target.\n            // If we've been asked to add build tool commands for the result, we do so now.\n            if addBuildToolPluginCommands {\n                for command in pluginResult.buildCommands {\n                    self.addBuildToolCommand(command, to: targetKeyPath)\n                }\n            }\n\n            // Process all the paths of derived output paths using the same rules as for source.\n            for command in pluginResult.buildCommands {\n                let files = self.process(\n                    pluginGeneratedFilePaths: command.absoluteOutputPaths,\n                    forModule: module,\n                    toolsVersion: self.package.manifest.toolsVersion\n                )\n\n                generatedFiles.add(files)\n                if !files.headers.isEmpty {\n                    // Capture the public include directory if there were header files generated there\n                    // Hardcoding as the default for now\n                    let publicDir = command.pluginOutputDir.appending(ClangModule.defaultPublicHeadersComponent)\n                    if files.headers.contains(where: { $0.isDescendantOfOrEqual(to: publicDir) }) {\n                        generatedFiles.publicHeaderPaths.append(publicDir)\n                    }\n                }\n            }\n\n            let files = self.process(\n                pluginGeneratedFilePaths: pluginResult.prebuildCommandOutputPaths,\n                forModule: module,\n                toolsVersion: self.package.manifest.toolsVersion)\n            generatedFiles.add(files)\n        }\n\n        return generatedFiles\n    }\n\n    /// Helper function for adding build tool commands to the right PIF target depending on whether they generate\n    /// sources or resources.\n    mutating func addBuildToolCommands(\n        module: PackageGraph.ResolvedModule,\n        sourceModuleTargetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n        resourceBundleTargetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n        sourceFilePaths: [AbsolutePath],\n        resourceFilePaths: [String]\n    ) {\n        guard let pluginResults = pifBuilder.buildToolPluginResultsByTargetName[module.name] else {\n            return\n        }\n\n        for pluginResult in pluginResults {\n            for command in pluginResult.buildCommands {\n                let producesResources = Set(command.outputPaths).intersection(resourceFilePaths).hasContent\n\n                if producesResources {\n                    self.addBuildToolCommand(command, to: resourceBundleTargetKeyPath)\n                } else {\n                    self.addBuildToolCommand(command, to: sourceModuleTargetKeyPath)\n                }\n            }\n        }\n    }\n\n    /// Adds build rules to `pifTarget` for any build tool   commands from invocation results.\n    /// Returns the absolute paths of any generated source files that should be added to the sources build phase of the\n    /// PIF target.\n    mutating func addBuildToolCommands(\n        from pluginInvocationResults: [PackagePIFBuilder.BuildToolPluginInvocationResult],\n        targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,\n        addBuildToolPluginCommands: Bool\n    ) -> [String] {\n        var generatedSourceFileAbsPaths: [String] = []\n        for result in pluginInvocationResults {\n            // Create build rules for all the commands in the result.\n            if addBuildToolPluginCommands {\n                for command in result.buildCommands {\n                    self.addBuildToolCommand(command, to: targetKeyPath)\n                }\n            }\n            // Add the paths of the generated source files, so that they can be added to the Sources build phase.\n            generatedSourceFileAbsPaths.append(contentsOf: result.allDerivedOutputPaths.map(\\.pathString))\n        }\n        return generatedSourceFileAbsPaths\n    }\n\n    /// Adds a single plugin-created build command to a PIF target.\n    mutating func addBuildToolCommand(\n        _ command: PackagePIFBuilder.CustomBuildCommand,\n        to targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>\n    ) {\n        var commandLine = [command.executable] + command.arguments\n        if let sandbox = command.sandboxProfile, !pifBuilder.delegate.isPluginExecutionSandboxingDisabled {\n            commandLine = try! sandbox.apply(to: commandLine, fileSystem: self.pifBuilder.fileSystem)\n        }\n\n        self.project[keyPath: targetKeyPath].customTasks.append(\n            ProjectModel.CustomTask(\n                commandLine: commandLine,\n                environment: command.environment.map { Pair($0, $1) }.sorted(by: <),\n                workingDirectory: command.workingDir?.pathString,\n                executionDescription: command.displayName ?? \"Performing build tool plugin command\",\n                inputFilePaths: [command.executable] + command.inputPaths.map(\\.pathString),\n                outputFilePaths: command.outputPaths,\n                enableSandboxing: false,\n                preparesForIndexing: true\n            )\n        )\n    }\n\n    /// Processes the paths of plugin-generated files for a particular package target,\n    /// returning paths of those that should be treated as sources vs resources.\n    private func process(\n        pluginGeneratedFilePaths: [AbsolutePath],\n        forModule module: PackageGraph.ResolvedModule,\n        toolsVersion: PackageModel.ToolsVersion?\n    ) -> GeneratedFiles {\n        precondition(module.isSourceModule)\n\n        // If we have no tools version, all files are treated as *source* files.\n        guard let toolsVersion else {\n            return GeneratedFiles()\n        }\n\n        // Use the `TargetSourcesBuilder` from libSwiftPM to split the generated files into sources and resources.\n        return TargetSourcesBuilder.computeContents(\n            for: pluginGeneratedFilePaths,\n            toolsVersion: toolsVersion,\n            additionalFileRules: Self.additionalFileRules,\n            defaultLocalization: module.defaultLocalization,\n            module: module.underlying,\n            observabilityScope: pifBuilder.observabilityScope\n        )\n    }\n\n    private static let additionalFileRules: [FileRuleDescription] =\n        FileRuleDescription.xcbuildFileTypes + [\n            FileRuleDescription(\n                rule: .compile,\n                toolsVersion: .v5_5,\n                fileTypes: [\"docc\"]\n            ),\n            FileRuleDescription(\n                rule: .processResource(localization: .none),\n                toolsVersion: .v5_7,\n                fileTypes: [\"mlmodel\", \"mlpackage\"]\n            ),\n            FileRuleDescription(\n                rule: .processResource(localization: .none),\n                toolsVersion: .v5_7,\n                fileTypes: [\"rkassets\"] // visionOS\n            ),\n        ]\n\n    // MARK: - General Helpers\n\n    func installPath(for product: PackageModel.Product) -> String {\n        if let customInstallPath = pifBuilder.delegate.customInstallPath(product: product) {\n            customInstallPath\n        } else {\n            \"/usr/local/lib\"\n        }\n    }\n\n    /// Always create a dynamic variant for targets, for automatic resolution of diamond problems,\n    /// unless there is a potential name clash with an explicitly *dynamic library* product.\n    ///\n    /// Swift Build will emit a diagnostic if such a package target is part of a diamond.\n    func shouldOfferDynamicTarget(_ targetName: String) -> Bool {\n        !self.dynamicLibraryProductNames.contains(targetName)\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/PluginConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal) import Basics\n@_spi(SwiftPMInternal) import SPMBuildCore\n\npublic struct PluginConfiguration {\n    /// Entity responsible for compiling and running plugin scripts.\n    let scriptRunner: PluginScriptRunner\n\n    /// Directory where plugin intermediate files are stored.\n    let workDirectory: Basics.AbsolutePath\n\n    /// Whether to sandbox commands from build tool plugins.\n    let disableSandbox: Bool\n\n    public init(\n        scriptRunner: PluginScriptRunner,\n        workDirectory: Basics.AbsolutePath,\n        disableSandbox: Bool\n    ) {\n        self.scriptRunner = scriptRunner\n        self.workDirectory = workDirectory\n        self.disableSandbox = disableSandbox\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/README.md",
    "content": "# Swift Build System Support\n\nThere is experimental support for using Swift Build as the build system for SwiftPM. You can try the build system with the `--build-system` option like this:\n\n```\nswift build --build-system=swiftbuild\n```\n\nWhat works so far:\n* Builds on macOS\n* Simple packages\n\nWork is continuing in these areas:\n* Builds on Linux and Windows\n* Conditional target dependencies (i.e. dependencies that are conditional on \".when()\" specific platforms)\n* Plugin support\n* Friendly Error and Warning Descriptions and Fixups\n* Cross compiling Swift SDK's (e.g. Static Linux SDK, and Wasm with WASI)\n* Improvements to test coverage\n* Task execution reporting\n\n## Problem Reporting\n\nWhen raising an issue with problems regarding the Swift Build System, please indicate that you are using this build system instead of the built-in native (or xcode) build systems. Including a minimal package that exhibits the bad behaviour will help with problem diagnosis and fixing.\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/SwiftBuildSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\nimport Dispatch\nimport class Foundation.FileManager\nimport class Foundation.JSONEncoder\nimport class Foundation.NSArray\nimport class Foundation.NSDictionary\nimport PackageGraph\nimport PackageModel\nimport PackageLoading\n\n@_spi(SwiftPMInternal)\nimport SPMBuildCore\n\nimport class Basics.AsyncProcess\nimport func TSCBasic.memoize\nimport protocol TSCBasic.OutputByteStream\nimport func TSCBasic.withTemporaryFile\n\nimport enum TSCUtility.Diagnostics\n\nimport var TSCBasic.stdoutStream\n\nimport Foundation\nimport SWBBuildService\nimport SwiftBuild\nimport enum SWBCore.SwiftAPIDigesterMode\nimport struct SWBUtil.XcodeVersionInfo\nimport struct SWBUtil.Path\n\nstruct SessionFailedError: Error {\n    var error: Error\n    var diagnostics: [SwiftBuild.SwiftBuildMessage.DiagnosticInfo]\n}\n\npackage func withService<T>(\n    connectionMode: SWBBuildServiceConnectionMode = .default,\n    variant: SWBBuildServiceVariant = .default,\n    serviceBundleURL: URL? = nil,\n    body: @escaping (_ service: SWBBuildService) async throws -> T\n) async throws -> T {\n    let service = try await SWBBuildService(connectionMode: connectionMode, variant: variant, serviceBundleURL: serviceBundleURL)\n    let result: T\n    do {\n        result = try await body(service)\n    } catch {\n        await service.close()\n        throw error\n    }\n    await service.close()\n    return result\n}\n\npublic func createSession(\n    service: SWBBuildService,\n    name: String,\n    toolchain: Toolchain,\n    packageManagerResourcesDirectory: Basics.AbsolutePath?\n) async throws-> (SWBBuildServiceSession, [SwiftBuildMessage.DiagnosticInfo]) {\n\n    var buildSessionEnv: [String: String]? = nil\n    if let metalToolchainPath = toolchain.metalToolchainPath {\n        buildSessionEnv = [\"EXTERNAL_TOOLCHAINS_DIR\": metalToolchainPath.pathString]\n    }\n    var toolchainPath = try toolchain.toolchainDir\n\n    // On Windows, the \"developer dir\" is two levels up from the toolchain dir,\n    // unlike Swift.org toolchains on other platforms where they are both the same.\n    if ProcessInfo.hostOperatingSystem == .windows {\n        toolchainPath = toolchainPath\n            .parentDirectory\n            .parentDirectory\n    }\n\n    // Users often rename Xcode.app, and in Swift.org CI on macOS we construct the toolchain under a nonfunctioning shell\n    // of Xcode.app. Instead of just checking the app name, see if we can find the app's version.plist at the expected\n    // location.\n    let toolchainIsEmbeddedInXcode: Bool\n    let xcodeVersionPlistPath = toolchainPath\n        .parentDirectory // Remove 'XcodeDefault.xctoolchain'\n        .parentDirectory // Remove 'Toolchains'\n        .parentDirectory // Remove 'Developer'\n        .appending(component: \"version.plist\")\n    if (try? XcodeVersionInfo.versionInfo(versionPath: SWBUtil.Path(xcodeVersionPlistPath.pathString))) != nil {\n        toolchainIsEmbeddedInXcode = true\n    } else {\n        toolchainIsEmbeddedInXcode = false\n    }\n\n    // SWIFT_EXEC and SWIFT_EXEC_MANIFEST may need to be overridden in debug scenarios in order to pick up Open Source toolchains\n    let sessionResult = if toolchainIsEmbeddedInXcode {\n        // If this toolchain is bundled with Xcode.app, let the build service handle toolchain registration.\n        await service.createSession(name: name, developerPath: nil, resourceSearchPaths: packageManagerResourcesDirectory.map { [$0.pathString] } ?? [], cachePath: nil, inferiorProductsPath: nil, environment: buildSessionEnv)\n    } else {\n        // Otherwise, treat this toolchain as standalone when initializing the build service.\n        await service.createSession(name: name, swiftToolchainPath: toolchainPath.pathString, resourceSearchPaths: packageManagerResourcesDirectory.map { [$0.pathString] } ?? [], cachePath: nil, inferiorProductsPath: nil, environment: buildSessionEnv)\n    }\n    switch sessionResult {\n    case (.success(let session), let diagnostics):\n        return (session, diagnostics)\n    case (.failure(let error), let diagnostics):\n        throw SessionFailedError(error: error, diagnostics: diagnostics)\n    }\n}\n\nfunc withSession(\n    service: SWBBuildService,\n    name: String,\n    toolchain: Toolchain,\n    packageManagerResourcesDirectory: Basics.AbsolutePath?,\n    body: @escaping (\n        _ session: SWBBuildServiceSession,\n        _ diagnostics: [SwiftBuild.SwiftBuildMessage.DiagnosticInfo]\n    ) async throws -> Void\n) async throws {\n    let (session, diagnostics) = try await createSession(service: service, name: name, toolchain: toolchain, packageManagerResourcesDirectory: packageManagerResourcesDirectory)\n    do {\n        try await body(session, diagnostics)\n    } catch let bodyError {\n        do {\n            try await session.close()\n        } catch _ {\n            // Assumption is that the first error is the most important one\n            throw bodyError\n        }\n\n        throw bodyError\n    }\n    do {\n        try await session.close()\n    } catch {\n        throw SessionFailedError(error: error, diagnostics: diagnostics)\n    }\n}\n\npackage final class SwiftBuildSystemPlanningOperationDelegate: SWBPlanningOperationDelegate, SWBIndexingDelegate, Sendable {\n    private let shouldEnableDebuggingEntitlement: Bool\n\n    package init(shouldEnableDebuggingEntitlement: Bool) {\n        self.shouldEnableDebuggingEntitlement = shouldEnableDebuggingEntitlement\n    }\n\n    public func provisioningTaskInputs(\n        targetGUID: String,\n        provisioningSourceData: SWBProvisioningTaskInputsSourceData\n    ) async -> SWBProvisioningTaskInputs {\n        let identity = if provisioningSourceData.signingCertificateIdentifier.isEmpty && shouldEnableDebuggingEntitlement {\n            \"-\"\n        } else {\n            provisioningSourceData.signingCertificateIdentifier\n        }\n\n        if identity == \"-\" {\n            let getTaskAllowEntitlementKey: String\n            let applicationIdentifierEntitlementKey: String\n\n            if provisioningSourceData.sdkRoot.contains(\"macos\") || provisioningSourceData.sdkRoot\n                .contains(\"simulator\")\n            {\n                getTaskAllowEntitlementKey = \"com.apple.security.get-task-allow\"\n                applicationIdentifierEntitlementKey = \"com.apple.application-identifier\"\n            } else {\n                getTaskAllowEntitlementKey = \"get-task-allow\"\n                applicationIdentifierEntitlementKey = \"application-identifier\"\n            }\n\n            let signedEntitlements = provisioningSourceData\n                .entitlementsDestination == \"Signature\" ? provisioningSourceData.productTypeEntitlements.merging(\n                    [applicationIdentifierEntitlementKey: .plString(provisioningSourceData.bundleIdentifier)],\n                    uniquingKeysWith: { _, new in new }\n                ).merging(provisioningSourceData.projectEntitlements ?? [:], uniquingKeysWith: { _, new in new })\n                : [:]\n\n            let simulatedEntitlements = provisioningSourceData.entitlementsDestination == \"__entitlements\"\n                ? provisioningSourceData.productTypeEntitlements.merging(\n                    [\"application-identifier\": .plString(provisioningSourceData.bundleIdentifier)],\n                    uniquingKeysWith: { _, new in new }\n                ).merging(provisioningSourceData.projectEntitlements ?? [:], uniquingKeysWith: { _, new in new })\n                : [:]\n\n            var additionalEntitlements: [String: SWBPropertyListItem] = [:]\n\n            if shouldEnableDebuggingEntitlement {\n                additionalEntitlements[getTaskAllowEntitlementKey] = .plBool(true)\n            }\n\n            return SWBProvisioningTaskInputs(\n                identityHash: \"-\",\n                identityName: \"-\",\n                profileName: nil,\n                profileUUID: nil,\n                profilePath: nil,\n                designatedRequirements: nil,\n                signedEntitlements: signedEntitlements.merging(\n                    additionalEntitlements,\n                    uniquingKeysWith: { _, new in new }\n                ),\n                simulatedEntitlements: simulatedEntitlements,\n                appIdentifierPrefix: nil,\n                teamIdentifierPrefix: nil,\n                isEnterpriseTeam: nil,\n                keychainPath: nil,\n                errors: [],\n                warnings: []\n            )\n        } else if identity.isEmpty {\n            return SWBProvisioningTaskInputs()\n        } else {\n            return SWBProvisioningTaskInputs(\n                identityHash: \"-\",\n                errors: [\n                    [\n                        \"description\": \"unable to supply accurate provisioning inputs for CODE_SIGN_IDENTITY=\\(identity)\\\"\",\n                    ],\n                ]\n            )\n        }\n    }\n\n    public func executeExternalTool(\n        commandLine: [String],\n        workingDirectory: String?,\n        environment: [String: String]\n    ) async throws -> SWBExternalToolResult {\n        .deferred\n    }\n}\n\npublic final class SwiftBuildSystem: SPMBuildCore.BuildSystem {\n    package let buildParameters: BuildParameters\n    private let packageGraphLoader: () async throws -> ModulesGraph\n    private let packageManagerResourcesDirectory: Basics.AbsolutePath?\n    private let logLevel: Basics.Diagnostic.Severity\n    private var packageGraph: AsyncThrowingValueMemoizer<ModulesGraph> = .init()\n    private var pifBuilder: AsyncThrowingValueMemoizer<PIFBuilder> = .init()\n    private let fileSystem: FileSystem\n    private let observabilityScope: ObservabilityScope\n\n    /// The output stream for the build delegate.\n    private let outputStream: OutputByteStream\n\n    /// The delegate used by the build system.\n    public weak var delegate: SPMBuildCore.BuildSystemDelegate?\n\n    /// Configuration for building and invoking plugins.\n    private let pluginConfiguration: PluginConfiguration\n\n    /// Additional rules for different file types generated from plugins.\n    private let additionalFileRules: [FileRuleDescription]\n\n    public var builtTestProducts: [BuiltTestProduct] {\n        get async {\n            do {\n                let graph = try await getPackageGraph()\n\n                var builtProducts: [BuiltTestProduct] = []\n\n                for package in graph.rootPackages {\n                    for product in package.products where product.type == .test {\n                        let binaryPath = try buildParameters.binaryPath(for: product)\n                        builtProducts.append(\n                            BuiltTestProduct(\n                                productName: product.name,\n                                umbrellaProductName: package.manifest.umbrellaPackageTestsProductName,\n                                binaryPath: binaryPath,\n                                packagePath: package.path,\n                                testEntryPointPath: product.underlying.testEntryPointPath\n                            )\n                        )\n                    }\n                }\n\n                return builtProducts\n            } catch {\n                self.observabilityScope.emit(error)\n                return []\n            }\n        }\n    }\n\n    public var buildPlan: SPMBuildCore.BuildPlan {\n        get throws {\n            throw StringError(\"Swift Build does not provide a build plan\")\n        }\n    }\n\n    public var hasIntegratedAPIDigesterSupport: Bool { true }\n\n    public var enableTaskBacktraces: Bool {\n        self.buildParameters.outputParameters.enableTaskBacktraces\n    }\n\n    public init(\n        buildParameters: BuildParameters,\n        packageGraphLoader: @escaping () async throws -> ModulesGraph,\n        packageManagerResourcesDirectory: Basics.AbsolutePath?,\n        additionalFileRules: [FileRuleDescription],\n        outputStream: OutputByteStream,\n        logLevel: Basics.Diagnostic.Severity,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        pluginConfiguration: PluginConfiguration,\n        delegate: BuildSystemDelegate?\n    ) throws {\n        self.buildParameters = buildParameters\n        self.packageGraphLoader = packageGraphLoader\n        self.packageManagerResourcesDirectory = packageManagerResourcesDirectory\n        self.additionalFileRules = additionalFileRules\n        self.outputStream = outputStream\n        self.logLevel = logLevel\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope.makeChildScope(description: \"Swift Build System\")\n        self.pluginConfiguration = pluginConfiguration\n        self.delegate = delegate\n    }\n\n    private func createREPLArguments(\n        session: SWBBuildServiceSession,\n        request: SWBBuildRequest\n    ) async throws -> CLIArguments {\n        self.outputStream.send(\"Gathering repl arguments...\")\n        self.outputStream.flush()\n\n        func getUniqueBuildSettingsIncludingDependencies(of targetGuid: [SWBConfiguredTarget], buildSettings: [String]) async throws -> Set<String> {\n            let dependencyGraph = try await session.computeDependencyGraph(\n                targetGUIDs: request.configuredTargets.map { SWBTargetGUID(rawValue: $0.guid)},\n                buildParameters: request.parameters,\n                includeImplicitDependencies: true,\n            )\n            var uniquePaths = Set<String>()\n            for setting in buildSettings {\n                self.outputStream.send(\".\")\n                self.outputStream.flush()\n                for (target, targetDependencies) in dependencyGraph {\n                    for t in [target] + targetDependencies {\n                        try await session.evaluateMacroAsStringList(\n                            setting,\n                            level: .target(t.rawValue),\n                            buildParameters: request.parameters,\n                            overrides: nil,\n                        ).forEach({\n                            uniquePaths.insert($0)\n                        })\n                    }\n                }\n\n            }\n            return uniquePaths\n        }\n\n        // TODO: Need to determine how to get the include path of package system library dependencies\n        let includePaths = try await getUniqueBuildSettingsIncludingDependencies(\n            of: request.configuredTargets,\n            buildSettings: [\n                \"BUILT_PRODUCTS_DIR\",\n                \"HEADER_SEARCH_PATHS\",\n                \"USER_HEADER_SEARCH_PATHS\",\n                \"FRAMEWORK_SEARCH_PATHS\",\n            ]\n        )\n\n        let graph = try await self.getPackageGraph()\n        // Link the special REPL product that contains all of the library targets.\n        let replProductName: String = try graph.getReplProductName()\n\n        // The graph should have the REPL product.\n        assert(graph.product(for: replProductName) != nil)\n\n        let arguments = [\"repl\", \"-l\\(replProductName)\"] + includePaths.map {\n            \"-I\\($0)\"\n        }\n\n        self.outputStream.send(\"Done.\\n\")\n        return arguments\n    }\n\n    private func supportedSwiftVersions() throws -> [SwiftLanguageVersion] {\n        // Swift Build should support any of the supported language versions of SwiftPM and the rest of the toolchain\n        SwiftLanguageVersion.supportedSwiftLanguageVersions\n    }\n\n    public func build(subset: BuildSubset, buildOutputs: [BuildOutput]) async throws -> BuildResult {\n        // If any plugins are part of the build set, compile them now to surface\n        // any errors up-front. Returns true if we should proceed with the build\n        // or false if not. It will already have thrown any appropriate error.\n        var result = BuildResult(\n            serializedDiagnosticPathsByTargetName: .failure(StringError(\"Building was skipped\")),\n            replArguments: nil,\n        )\n\n        guard !buildParameters.shouldSkipBuilding else {\n            result.serializedDiagnosticPathsByTargetName = .failure(StringError(\"Building was skipped\"))\n            return result\n        }\n\n        guard try await self.compilePlugins(in: subset) else {\n            result.serializedDiagnosticPathsByTargetName = .failure(StringError(\"Plugin compilation failed\"))\n            return result\n        }\n\n        try await writePIF(buildParameters: self.buildParameters)\n\n        return try await startSWBuildOperation(\n            pifTargetName: subset.pifTargetName,\n            buildOutputs: buildOutputs,\n        )\n    }\n\n    /// Compute the available build tools, and their destination build path for host for each plugin.\n    private func availableBuildPluginTools(\n        graph: ModulesGraph,\n        buildParameters: BuildParameters,\n        pluginsPerModule: [ResolvedModule.ID: [ResolvedModule]],\n        hostTriple: Basics.Triple\n    ) async throws -> [ResolvedModule.ID: [String: PluginTool]] {\n        var accessibleToolsPerPlugin: [ResolvedModule.ID: [String: PluginTool]] = [:]\n\n        for (_, plugins) in pluginsPerModule {\n            for plugin in plugins where accessibleToolsPerPlugin[plugin.id] == nil {\n                // Determine the tools to which this plugin has access, and create a name-to-path mapping from tool\n                // names to the corresponding paths. Built tools are assumed to be in the build tools directory.\n                let accessibleTools = try await plugin.preparePluginTools(\n                    fileSystem: fileSystem,\n                    environment: buildParameters.buildEnvironment,\n                    for: hostTriple\n                ) { name, path in\n                    return buildParameters.buildPath.appending(path)\n                }\n\n                accessibleToolsPerPlugin[plugin.id] = accessibleTools\n            }\n        }\n\n        return accessibleToolsPerPlugin\n    }\n\n    /// Compiles any plugins specified or implied by the build subset, returning\n    /// true if the build should proceed. Throws an error in case of failure. A\n    /// reason why the build might not proceed even on success is if only plugins\n    /// should be compiled.\n    func compilePlugins(in subset: BuildSubset) async throws -> Bool {\n        // Figure out what, if any, plugin descriptions to compile, and whether\n        // to continue building after that based on the subset.\n        let graph = try await getPackageGraph()\n\n        /// Description for a plugin module. This is treated a bit differently from the\n        /// regular kinds of modules, and is not included in the LLBuild description.\n        /// But because the modules graph and build plan are not loaded for incremental\n        /// builds, this information is included in the BuildDescription, and the plugin\n        /// modules are compiled directly.\n        struct PluginBuildDescription: Codable {\n            /// The identity of the package in which the plugin is defined.\n            public let package: PackageIdentity\n\n            /// The name of the plugin module in that package (this is also the name of\n            /// the plugin).\n            public let moduleName: String\n\n            /// The language-level module name.\n            public let moduleC99Name: String\n\n            /// The names of any plugin products in that package that vend the plugin\n            /// to other packages.\n            public let productNames: [String]\n\n            /// The tools version of the package that declared the module. This affects\n            /// the API that is available in the PackagePlugin module.\n            public let toolsVersion: ToolsVersion\n\n            /// Swift source files that comprise the plugin.\n            public let sources: Sources\n\n            /// Initialize a new plugin module description. The module is expected to be\n            /// a `PluginTarget`.\n            init(\n                module: ResolvedModule,\n                products: [ResolvedProduct],\n                package: ResolvedPackage,\n                toolsVersion: ToolsVersion,\n                testDiscoveryTarget: Bool = false,\n                fileSystem: FileSystem\n            ) throws {\n                guard module.underlying is PluginModule else {\n                    throw InternalError(\"underlying target type mismatch \\(module)\")\n                }\n\n                self.package = package.identity\n                self.moduleName = module.name\n                self.moduleC99Name = module.c99name\n                self.productNames = products.map(\\.name)\n                self.toolsVersion = toolsVersion\n                self.sources = module.sources\n            }\n        }\n\n        var allPlugins: [PluginBuildDescription] = []\n\n        for pluginModule in graph.allModules.filter({ ($0.underlying as? PluginModule) != nil }) {\n            guard let package = graph.package(for: pluginModule) else {\n                throw InternalError(\"Package not found for module: \\(pluginModule.name)\")\n            }\n\n            let toolsVersion = package.manifest.toolsVersion\n\n            let pluginProducts = package.products.filter { $0.modules.contains(id: pluginModule.id) }\n\n            allPlugins.append(try PluginBuildDescription(\n                module: pluginModule,\n                products: pluginProducts,\n                package: package,\n                toolsVersion: toolsVersion,\n                fileSystem: fileSystem\n            ))\n        }\n\n        let pluginsToCompile: [PluginBuildDescription]\n        let continueBuilding: Bool\n        switch subset {\n        case .allExcludingTests, .allIncludingTests:\n            pluginsToCompile = allPlugins\n            continueBuilding = true\n        case .product(let productName, _):\n            pluginsToCompile = allPlugins.filter{ $0.productNames.contains(productName) }\n            continueBuilding = pluginsToCompile.isEmpty\n        case .target(let targetName, _):\n            pluginsToCompile = allPlugins.filter{ $0.moduleName == targetName }\n            continueBuilding = pluginsToCompile.isEmpty\n        }\n\n        final class Delegate: PluginScriptCompilerDelegate {\n            var failed: Bool = false\n            var observabilityScope: ObservabilityScope\n\n            public init(observabilityScope: ObservabilityScope) {\n                self.observabilityScope = observabilityScope\n            }\n\n            func willCompilePlugin(commandLine: [String], environment: [String: String]) { }\n\n            func didCompilePlugin(result: PluginCompilationResult) {\n                if !result.compilerOutput.isEmpty && !result.succeeded {\n                    print(result.compilerOutput, to: &stdoutStream)\n                } else if !result.compilerOutput.isEmpty {\n                    observabilityScope.emit(info: result.compilerOutput)\n                }\n\n                failed = !result.succeeded\n            }\n\n            func skippedCompilingPlugin(cachedResult: PluginCompilationResult) { }\n        }\n\n        // Compile any plugins we ended up with. If any of them fails, it will\n        // throw.\n        for plugin in pluginsToCompile {\n            let delegate = Delegate(observabilityScope: observabilityScope)\n\n            _ = try await self.pluginConfiguration.scriptRunner.compilePluginScript(\n                sourceFiles: plugin.sources.paths,\n                pluginName: plugin.moduleName,\n                toolsVersion: plugin.toolsVersion,\n                workers: self.buildParameters.workers,\n                observabilityScope: observabilityScope,\n                callbackQueue: DispatchQueue.sharedConcurrent,\n                delegate: delegate\n            )\n\n            if delegate.failed {\n                throw Diagnostics.fatalError\n            }\n        }\n\n        // If we get this far they all succeeded. Return whether to continue the\n        // build, based on the subset.\n        return continueBuilding\n    }\n\n    private func startSWBuildOperation(\n        pifTargetName: String,\n        buildOutputs: [BuildOutput]\n    ) async throws -> BuildResult {\n        let buildStartTime = ContinuousClock.Instant.now\n        var symbolGraphOptions: BuildOutput.SymbolGraphOptions?\n        for output in buildOutputs {\n            switch output {\n            case .symbolGraph(let options):\n                symbolGraphOptions = options\n            default:\n                continue\n            }\n        }\n\n        var replArguments: CLIArguments?\n        var artifacts: [(String, PluginInvocationBuildResult.BuiltArtifact)]?\n        var dependencyGraph: [String: [String]]?\n        return try await withService(connectionMode: .inProcessStatic(swiftbuildServiceEntryPoint)) { service in\n            let derivedDataPath = self.buildParameters.dataPath\n\n            let buildMessageHandler = SwiftBuildSystemMessageHandler(\n                observabilityScope: self.observabilityScope,\n                outputStream: self.outputStream,\n                logLevel: self.logLevel,\n                enableBacktraces: self.enableTaskBacktraces,\n                buildDelegate: self.delegate\n            )\n\n            do {\n                try await withSession(service: service, name: self.buildParameters.pifManifest.pathString, toolchain: self.buildParameters.toolchain, packageManagerResourcesDirectory: self.packageManagerResourcesDirectory) { session, _ in\n                    self.outputStream.send(\"Building for \\(self.buildParameters.configuration == .debug ? \"debugging\" : \"production\")...\\n\")\n\n                    // Load the workspace, and set the system information to the default\n                    do {\n                        try await session.loadWorkspace(containerPath: self.buildParameters.pifManifest.pathString)\n                        try await session.setSystemInfo(.default())\n                    } catch {\n                        self.observabilityScope.emit(error: error.localizedDescription)\n                        throw error\n                    }\n\n                    // Find the targets to build.\n                    let workspaceInfo = try await session.workspaceInfo()\n                    let configuredTargets: [SWBTargetGUID]\n                    do {\n                        configuredTargets = try [pifTargetName].map { targetName in\n                            // TODO we filter dynamic targets until Swift Build doesn't give them to us anymore\n                            let infos = workspaceInfo.targetInfos.filter { $0.targetName == targetName && !TargetSuffix.dynamic.hasSuffix(id: GUID($0.guid)) }\n                            switch infos.count {\n                            case 0:\n                                self.observabilityScope.emit(error: \"Could not find target named '\\(targetName)'\")\n                                throw Diagnostics.fatalError\n                            case 1:\n                                return SWBTargetGUID(rawValue: infos[0].guid)\n                            default:\n                                self.observabilityScope.emit(error: \"Found multiple targets named '\\(targetName)'\")\n                                throw Diagnostics.fatalError\n                            }\n                        }\n                    } catch {\n                        self.observabilityScope.emit(error: error.localizedDescription)\n                        throw error\n                    }\n\n                    let request = try await self.makeBuildRequest(session: session, configuredTargets: configuredTargets, derivedDataPath: derivedDataPath, symbolGraphOptions: symbolGraphOptions)\n\n                    let operation = try await session.createBuildOperation(\n                        request: request,\n                        delegate: SwiftBuildSystemPlanningOperationDelegate(shouldEnableDebuggingEntitlement: self.buildParameters\n                            .debuggingParameters.shouldEnableDebuggingEntitlement\n                        ),\n                        retainBuildDescription: true\n                    )\n\n                    var buildDescriptionID: SWBBuildDescriptionID? = nil\n                    for try await event in try await operation.start() {\n                        if case .reportBuildDescription(let info) = event {\n                            if buildDescriptionID != nil {\n                                self.observabilityScope.emit(debug: \"build unexpectedly reported multiple build description IDs\")\n                            }\n                            buildDescriptionID = SWBBuildDescriptionID(info.buildDescriptionID)\n                        }\n                        if let delegateCallback = try buildMessageHandler.emitEvent(event) {\n                            delegateCallback(self)\n                        }\n                    }\n\n                    await operation.waitForCompletion()\n\n                    switch operation.state {\n                    case .succeeded:\n                        guard !self.logLevel.isQuiet else { return }\n                        buildMessageHandler.progressAnimation.update(step: 100, total: 100, text: \"\")\n                        buildMessageHandler.progressAnimation.complete(success: true)\n                        let duration = ContinuousClock.Instant.now - buildStartTime\n                        let formattedDuration = duration.formatted(.units(allowed: [.seconds], fractionalPart: .show(length: 2, rounded: .up)))\n                        self.outputStream.send(\"Build complete! (\\(formattedDuration))\\n\")\n                        self.outputStream.flush()\n                    case .failed:\n                        self.observabilityScope.emit(error: \"Build failed\")\n                        throw Diagnostics.fatalError\n                    case .cancelled:\n                        self.observabilityScope.emit(error: \"Build was cancelled\")\n                        throw Diagnostics.fatalError\n                    case .requested, .running, .aborted:\n                        self.observabilityScope.emit(error: \"Unexpected build state\")\n                        throw Diagnostics.fatalError\n                    }\n\n                    if buildOutputs.contains(.replArguments) {\n                        replArguments = try await self.createREPLArguments(session: session, request: request)\n                    }\n\n                    if buildOutputs.contains(.dependencyGraph) {\n                        let depGraph = try await session.computeDependencyGraph(\n                            targetGUIDs: request.configuredTargets.map { SWBTargetGUID(rawValue: $0.guid) },\n                            buildParameters: request.parameters,\n                            includeImplicitDependencies: true\n                        )\n                        // SWBTargetGUID wraps the GUID that PIFBuilder generates\n                        var result: [String: [String]] = [:]\n                        for (target, dependencies) in depGraph {\n                            let targetInfo = workspaceInfo.targetInfos.first { $0.guid == target.rawValue }\n                            guard let targetName = targetInfo?.targetName else { continue }\n                            let depNames = dependencies.compactMap { depGUID in\n                                workspaceInfo.targetInfos.first { $0.guid == depGUID.rawValue }?.targetName\n                            }\n                            result[targetName] = depNames\n                        }\n                        dependencyGraph = result\n                    }\n\n                    if buildOutputs.contains(.builtArtifacts) {\n                        if let buildDescriptionID {\n                            let targetInfo = try await session.configuredTargets(buildDescription: buildDescriptionID, buildRequest: request)\n                            artifacts = targetInfo.compactMap { target in\n                                guard let artifactInfo = target.artifactInfo else {\n                                    return nil\n                                }\n                                let kind: PluginInvocationBuildResult.BuiltArtifact.Kind = switch artifactInfo.kind {\n                                case .executable:\n                                    .executable\n                                case .staticLibrary:\n                                    .staticLibrary\n                                case .dynamicLibrary:\n                                    .dynamicLibrary\n                                case .framework:\n                                    // We treat frameworks as dylibs here, but the plugin API should grow to accomodate more product types\n                                    .dynamicLibrary\n                                }\n                                var name = target.name\n                                // FIXME: We need a better way to map between SwiftPM target/product names and PIF target names\n                                if pifTargetName.hasSuffix(\"-product\") {\n                                    name = String(name.dropLast(8))\n                                }\n                                return (name, .init(\n                                    path: artifactInfo.path,\n                                    kind: kind\n                                ))\n                            }\n                        } else {\n                            self.observabilityScope.emit(error: \"failed to compute built artifacts list\")\n                        }\n                    }\n\n                    if let buildDescriptionID {\n                        await session.releaseBuildDescription(id: buildDescriptionID)\n                    }\n                }\n            } catch let sessError as SessionFailedError {\n                for diagnostic in sessError.diagnostics {\n                    self.observabilityScope.emit(error: diagnostic.message)\n                }\n                throw sessError.error\n            } catch {\n                throw error\n            }\n\n            return BuildResult(\n                serializedDiagnosticPathsByTargetName: .success(buildMessageHandler.serializedDiagnosticPathsByTargetName),\n                symbolGraph: SymbolGraphResult(\n                    outputLocationForTarget: { target, buildParameters in\n                        return [\"\\(buildParameters.triple.archName)\", \"\\(target).symbolgraphs\"]\n                    }\n                ),\n                replArguments: replArguments,\n                builtArtifacts: artifacts,\n                dependencyGraph: dependencyGraph\n            )\n        }\n    }\n\n    private func makeRunDestination() -> SwiftBuild.SWBRunDestinationInfo {\n        if let sdkManifestPath = self.buildParameters.toolchain.swiftSDK.swiftSDKManifest {\n            return SwiftBuild.SWBRunDestinationInfo(\n                buildTarget: .swiftSDK(sdkManifestPath: sdkManifestPath.pathString, triple: self.buildParameters.triple.tripleString),\n                targetArchitecture: buildParameters.triple.archName,\n                supportedArchitectures: [],\n                disableOnlyActiveArch: (buildParameters.architectures?.count ?? 1) > 1,\n            )\n        } else {\n            let platformName: String\n            let sdkName: String\n\n            if self.buildParameters.triple.isAndroid() {\n                // Android triples are identified by the environment part of the triple\n                platformName = \"android\"\n                sdkName = platformName\n            } else {\n                platformName = self.buildParameters.triple.darwinPlatform?.platformName ?? self.buildParameters.triple.osNameUnversioned\n                sdkName = platformName\n            }\n\n            let sdkVariant: String?\n            if self.buildParameters.triple.environment == .macabi {\n                sdkVariant = \"iosmac\"\n            } else {\n                sdkVariant = nil\n            }\n\n            return SwiftBuild.SWBRunDestinationInfo(\n                buildTarget: .toolchainSDK(\n                    platform: platformName,\n                    sdk: sdkName,\n                    sdkVariant: sdkVariant\n                ),\n                targetArchitecture: buildParameters.triple.archName,\n                supportedArchitectures: [],\n                disableOnlyActiveArch: (buildParameters.architectures?.count ?? 1) > 1,\n                hostTargetedPlatform: nil\n            )\n        }\n    }\n\n    internal func makeBuildParameters(\n        session: SWBBuildServiceSession,\n        symbolGraphOptions: BuildOutput.SymbolGraphOptions?,\n        setToolchainSetting: Bool = true,\n    ) async throws -> SwiftBuild.SWBBuildParameters {\n        // Generate the run destination parameters.\n        let runDestination = makeRunDestination()\n\n        var verboseFlag: [String] = []\n        if self.logLevel == .debug {\n            verboseFlag = [\"-v\"] // Clang's verbose flag\n        }\n\n        // Generate a table of any overriding build settings.\n        var settings: [String: String] = [:]\n\n        if setToolchainSetting {\n            // If the SwiftPM toolchain corresponds to a toolchain registered with the lower level build system, add it to the toolchain stack.\n            // Otherwise, apply overrides for each component of the SwiftPM toolchain.\n            let toolchainID = try await session.lookupToolchain(at: buildParameters.toolchain.toolchainDir.pathString)\n            if toolchainID == nil {\n                // FIXME: This list of overrides is incomplete.\n                // An error with determining the override should not be fatal here.\n                settings[\"CC\"] = try? buildParameters.toolchain.getClangCompiler().pathString\n                // Always specify the path of the effective Swift compiler, which was determined in the same way as for the\n                // native build system.\n                settings[\"SWIFT_EXEC\"] = buildParameters.toolchain.swiftCompilerPath.pathString\n            }\n\n            let overrideToolchains = [buildParameters.toolchain.metalToolchainId, toolchainID?.rawValue].compactMap { $0 }\n            if !overrideToolchains.isEmpty {\n                settings[\"TOOLCHAINS\"] = (overrideToolchains + [\"$(inherited)\"]).joined(separator: \" \")\n            }\n        }\n\n        for sanitizer in buildParameters.sanitizers.sanitizers {\n            self.observabilityScope.emit(debug:\"Enabling \\(sanitizer) sanitizer\")\n            switch sanitizer {\n                case .address:\n                    settings[\"ENABLE_ADDRESS_SANITIZER\"] = \"YES\"\n                case .thread:\n                    settings[\"ENABLE_THREAD_SANITIZER\"] = \"YES\"\n                case .undefined:\n                    settings[\"ENABLE_UNDEFINED_BEHAVIOR_SANITIZER\"] = \"YES\"\n                case .fuzzer, .scudo:\n                    throw StringError(\"\\(sanitizer) is not currently supported with this build system.\")\n            }\n        }\n\n        // FIXME: workaround for old Xcode installations such as what is in CI\n        settings[\"LM_SKIP_METADATA_EXTRACTION\"] = \"YES\"\n        if let symbolGraphOptions {\n            settings[\"RUN_SYMBOL_GRAPH_EXTRACT\"] = \"YES\"\n\n            if symbolGraphOptions.prettyPrint {\n                settings[\"DOCC_PRETTY_PRINT\"] = \"YES\"\n            }\n\n            if symbolGraphOptions.emitExtensionBlocks {\n                settings[\"DOCC_EXTRACT_EXTENSION_SYMBOLS\"] = \"YES\"\n            }\n\n            if !symbolGraphOptions.includeInheritedDocs {\n                settings[\"DOCC_SKIP_INHERITED_DOCS\"] = \"YES\"\n            }\n\n            if !symbolGraphOptions.includeSynthesized {\n                settings[\"DOCC_SKIP_SYNTHESIZED_MEMBERS\"] = \"YES\"\n            }\n\n            if symbolGraphOptions.includeSPI {\n                settings[\"DOCC_EXTRACT_SPI_DOCUMENTATION\"] = \"YES\"\n            }\n\n            switch symbolGraphOptions.minimumAccessLevel {\n            case .private:\n                settings[\"DOCC_MINIMUM_ACCESS_LEVEL\"] = \"private\"\n            case .fileprivate:\n                settings[\"DOCC_MINIMUM_ACCESS_LEVEL\"] = \"fileprivate\"\n            case .internal:\n                settings[\"DOCC_MINIMUM_ACCESS_LEVEL\"] = \"internal\"\n            case .package:\n                settings[\"DOCC_MINIMUM_ACCESS_LEVEL\"] = \"package\"\n            case .public:\n                settings[\"DOCC_MINIMUM_ACCESS_LEVEL\"] = \"public\"\n            case .open:\n                settings[\"DOCC_MINIMUM_ACCESS_LEVEL\"] = \"open\"\n            }\n        }\n\n        if !buildParameters.customToolsetPaths.isEmpty {\n            settings[\"SWIFT_SDK_TOOLSETS\"] =\n                ([\"$(inherited)\"] + buildParameters.customToolsetPaths.map { $0.pathString })\n                .joined(separator: \" \")\n        }\n\n        let normalizedTriple = Triple(buildParameters.triple.triple, normalizing: true)\n        if let deploymentTargetSettingName = normalizedTriple.deploymentTargetSettingName, let value = normalizedTriple.deploymentTargetVersionString {\n            // Only override the deployment target if a version is explicitly specified;\n            // for Apple platforms this normally comes from the package manifest and may\n            // not be set to the same value for all packages in the package graph.\n            settings[deploymentTargetSettingName] = value\n        }\n\n        // FIXME: \"none\" triples get a placeholder SDK/platform and don't support any specific triple by default. Unlike most platforms, where the vendor and environment is implied as a function of the arch and \"platform\", bare metal operates in terms of triples directly. We need to replace this bringup convenience with a more idiomatic mechanism, perhaps in the build request.\n        if buildParameters.triple.os == .noneOS {\n            settings[\"ARCHS\"] = buildParameters.triple.archName\n            settings[\"VALID_ARCHS\"] = buildParameters.triple.archName\n            settings[\"LLVM_TARGET_TRIPLE_VENDOR\"] = buildParameters.triple.vendorName\n            if !buildParameters.triple.environmentName.isEmpty {\n                settings[\"LLVM_TARGET_TRIPLE_SUFFIX\"] = \"-\" + buildParameters.triple.environmentName\n            }\n        }\n\n        let compilerAndLinkerFlags = [\n            \"OTHER_CFLAGS\": buildParameters.toolchain.extraFlags.cCompilerFlags + buildParameters.flags.cCompilerFlags,\n            \"OTHER_CPLUSPLUSFLAGS\": buildParameters.toolchain.extraFlags.cxxCompilerFlags + buildParameters.flags.cxxCompilerFlags,\n            \"OTHER_SWIFT_FLAGS\": buildParameters.toolchain.extraFlags.swiftCompilerFlags + buildParameters.flags.swiftCompilerFlags,\n            \"OTHER_LDFLAGS\": (buildParameters.toolchain.extraFlags.linkerFlags + buildParameters.flags.linkerFlags)\n        ]\n        for (settingName, buildFlags) in compilerAndLinkerFlags {\n            var rawFlags = buildFlags.rawFlagsForSwiftBuild\n            if settingName == \"OTHER_LDFLAGS\" {\n                rawFlags = rawFlags.asSwiftcLinkerFlags()\n            }\n            settings[settingName] = (verboseFlag + [\"$(inherited)\"] +\n                rawFlags.map { $0.shellEscaped() }).joined(separator: \" \")\n        }\n\n        if buildParameters.driverParameters.emitSILFiles {\n            settings[\"SWIFT_EMIT_SIL_FILES\"] = \"YES\"\n            if let outputDir = buildParameters.driverParameters.silOutputDirectory {\n                settings[\"SWIFT_SIL_OUTPUT_DIR\"] = outputDir.pathString\n            }\n        }\n\n        if buildParameters.driverParameters.emitIRFiles {\n            settings[\"SWIFT_EMIT_IR_FILES\"] = \"YES\"\n            if let outputDir = buildParameters.driverParameters.irOutputDirectory {\n                settings[\"SWIFT_IR_OUTPUT_DIR\"] = outputDir.pathString\n            }\n        }\n\n        if buildParameters.driverParameters.emitOptimizationRecord {\n            settings[\"SWIFT_EMIT_OPT_RECORDS\"] = \"YES\"\n            if let outputDir = buildParameters.driverParameters.optimizationRecordDirectory {\n                settings[\"SWIFT_OPT_RECORD_OUTPUT_DIR\"] = outputDir.pathString\n            }\n        }\n\n        if buildParameters.driverParameters.codesizeProfileEnabled {\n            // dSYM generation is required to attribute code size to source locations\n            settings[\"DEBUG_INFORMATION_FORMAT\"] = \"dwarf-with-dsym\"\n        }\n\n        // Optionally also set the list of architectures to build for.\n        if let architectures = buildParameters.architectures, !architectures.isEmpty {\n            settings[\"ARCHS\"] = architectures.joined(separator: \" \")\n        }\n\n        // When building with the CLI for macOS, test bundles should generate entrypoints for compatibility with swiftpm-testing-helper.\n        if buildParameters.triple.isMacOSX {\n            settings[\"GENERATE_TEST_ENTRYPOINTS_FOR_BUNDLES\"] = \"YES\"\n        }\n\n        // Set the value of the index store\n        struct IndexStoreSettings {\n            let enableVariableName: String\n            let pathVariable: String\n        }\n\n        let indexStoreSettingNames: [IndexStoreSettings] = [\n            IndexStoreSettings(\n                enableVariableName: \"CLANG_INDEX_STORE_ENABLE\",\n                pathVariable: \"CLANG_INDEX_STORE_PATH\",\n            ),\n            IndexStoreSettings(\n                enableVariableName: \"SWIFT_INDEX_STORE_ENABLE\",\n                pathVariable: \"SWIFT_INDEX_STORE_PATH\",\n            ),\n        ]\n\n        switch self.buildParameters.indexStoreMode {\n        case .on:\n            for setting in indexStoreSettingNames {\n                settings[setting.enableVariableName] = \"YES\"\n                settings[setting.pathVariable] = self.buildParameters.indexStore.pathString\n            }\n        case .off:\n            for setting in indexStoreSettingNames {\n                settings[setting.enableVariableName] = \"NO\"\n            }\n        case .auto:\n            // The settings are handles in the PIF builder\n            break\n        }\n\n        func reportConflict(_ a: String, _ b: String) throws -> String {\n            throw StringError(\"Build parameters constructed conflicting settings overrides '\\(a)' and '\\(b)'\")\n        }\n        try settings.merge(Self.constructDebuggingSettingsOverrides(from: buildParameters.debuggingParameters), uniquingKeysWith: reportConflict)\n        try settings.merge(Self.constructDriverSettingsOverrides(from: buildParameters.driverParameters), uniquingKeysWith: reportConflict)\n        try settings.merge(self.constructLinkerSettingsOverrides(from: buildParameters.linkingParameters, triple: buildParameters.triple), uniquingKeysWith: reportConflict)\n        try settings.merge(Self.constructTestingSettingsOverrides(from: buildParameters.testingParameters), uniquingKeysWith: reportConflict)\n        try settings.merge(Self.constructAPIDigesterSettingsOverrides(from: buildParameters.apiDigesterMode), uniquingKeysWith: reportConflict)\n\n        // Generate the build parameters.\n        var params = SwiftBuild.SWBBuildParameters()\n        params.configurationName = buildParameters.configuration.swiftbuildName\n        var overridesSynthesized = SwiftBuild.SWBSettingsTable()\n        for (key, value) in settings {\n            overridesSynthesized.set(value: value, for: key)\n        }\n        params.overrides.synthesized = overridesSynthesized\n        params.activeRunDestination = runDestination\n\n        return params\n    }\n\n    public func makeBuildRequest(\n        session: SWBBuildServiceSession,\n        configuredTargets: [SWBTargetGUID],\n        derivedDataPath: Basics.AbsolutePath,\n        symbolGraphOptions: BuildOutput.SymbolGraphOptions?,\n        setToolchainSetting: Bool = true,\n        ) async throws -> SWBBuildRequest {\n        var request = SWBBuildRequest()\n        request.parameters = try await makeBuildParameters(\n            session: session,\n            symbolGraphOptions: symbolGraphOptions,\n            setToolchainSetting: setToolchainSetting,\n        )\n        request.configuredTargets = configuredTargets.map { SWBConfiguredTarget(guid: $0.rawValue, parameters: request.parameters) }\n        request.useParallelTargets = true\n        request.useImplicitDependencies = false\n        request.useDryRun = false\n        request.hideShellScriptEnvironment = true\n        request.showNonLoggedProgress = true\n        request.recordBuildBacktraces = buildParameters.outputParameters.enableTaskBacktraces\n        request.schedulerLaneWidthOverride = buildParameters.workers\n\n        // Override the arena. We need to apply the arena info to both the request-global build\n        // parameters as well as the target-specific build parameters, since they may have been\n        // deserialized from the build request file above overwriting the build parameters we set\n        // up earlier in this method.\n\n        #if os(Windows)\n        let ddPathPrefix = derivedDataPath.pathString.replacingOccurrences(of: \"\\\\\", with: \"/\")\n        #else\n        let ddPathPrefix = derivedDataPath.pathString\n        #endif\n\n        let arenaInfo = SWBArenaInfo(\n            derivedDataPath: ddPathPrefix,\n            buildProductsPath: ddPathPrefix + \"/Products\",\n            buildIntermediatesPath: ddPathPrefix + \"/Intermediates.noindex\",\n            pchPath: ddPathPrefix + \"/PCH\",\n            indexRegularBuildProductsPath: nil,\n            indexRegularBuildIntermediatesPath: nil,\n            indexPCHPath: ddPathPrefix,\n            indexDataStoreFolderPath: ddPathPrefix,\n            indexEnableDataStore: request.parameters.arenaInfo?.indexEnableDataStore ?? false\n        )\n\n        request.parameters.arenaInfo = arenaInfo\n        request.configuredTargets = request.configuredTargets.map { configuredTarget in\n            var configuredTarget = configuredTarget\n            configuredTarget.parameters?.arenaInfo = arenaInfo\n            return configuredTarget\n        }\n\n        return request\n    }\n\n    private static func constructDebuggingSettingsOverrides(from parameters: BuildParameters.Debugging) -> [String: String] {\n        var settings: [String: String] = [:]\n        // TODO: debugInfoFormat: https://github.com/swiftlang/swift-build/issues/560\n        if parameters.shouldEnableDebuggingEntitlement {\n            settings[\"DEPLOYMENT_POSTPROCESSING\"] = \"NO\"\n        }\n        // TODO: omitFramePointer: https://github.com/swiftlang/swift-build/issues/561\n        return settings\n    }\n\n    private static func constructDriverSettingsOverrides(from parameters: BuildParameters.Driver) -> [String: String] {\n        var settings: [String: String] = [:]\n        switch parameters.explicitTargetDependencyImportCheckingMode {\n        case .none:\n            break\n        case .warn:\n            settings[\"DIAGNOSE_MISSING_TARGET_DEPENDENCIES\"] = \"YES\"\n        case .error:\n            settings[\"DIAGNOSE_MISSING_TARGET_DEPENDENCIES\"] = \"YES_ERROR\"\n        }\n\n        if parameters.enableParseableModuleInterfaces {\n            settings[\"SWIFT_EMIT_MODULE_INTERFACE\"] = \"YES\"\n        }\n\n        return settings\n    }\n\n    private func constructLinkerSettingsOverrides(\n        from parameters: BuildParameters.Linking,\n        triple: Triple,\n    ) -> [String: String] {\n        var settings: [String: String] = [:]\n\n        if parameters.linkerDeadStrip {\n            settings[\"DEAD_CODE_STRIPPING\"] = \"YES\"\n        }\n\n        switch parameters.linkTimeOptimizationMode {\n        case .full:\n            settings[\"LLVM_LTO\"] = \"YES\"\n            settings[\"SWIFT_LTO\"] = \"YES\"\n        case .thin:\n            settings[\"LLVM_LTO\"] = \"YES_THIN\"\n            settings[\"SWIFT_LTO\"] = \"YES_THIN\"\n        case nil:\n            break\n        }\n\n        if triple.isDarwin() && parameters.shouldLinkStaticSwiftStdlib {\n            self.observabilityScope.emit(Basics.Diagnostic.swiftBackDeployWarning)\n        } else {\n            if parameters.shouldLinkStaticSwiftStdlib {\n                settings[\"SWIFT_FORCE_STATIC_LINK_STDLIB\"] = \"YES\"\n            } else {\n                settings[\"SWIFT_FORCE_STATIC_LINK_STDLIB\"] = \"NO\"\n            }\n        }\n\n        return settings\n    }\n\n    private static func constructTestingSettingsOverrides(from parameters: BuildParameters.Testing) -> [String: String] {\n        var settings: [String: String] = [:]\n\n        // Coverage settings\n        settings[\"CLANG_COVERAGE_MAPPING\"] = parameters.enableCodeCoverage ? \"YES\" : \"NO\"\n\n        switch parameters.explicitlyEnabledTestability {\n        case true:\n            settings[\"ENABLE_TESTABILITY\"] = \"YES\"\n        case false:\n            settings[\"ENABLE_TESTABILITY\"] = \"NO\"\n        default:\n            break\n        }\n\n        // TODO: experimentalTestOutput\n        // TODO: explicitlyEnabledDiscovery\n        // TODO: explicitlySpecifiedPath\n\n        return settings\n    }\n\n    private static func constructAPIDigesterSettingsOverrides(from digesterMode: BuildParameters.APIDigesterMode?) -> [String: String] {\n        var settings: [String: String] = [:]\n        switch digesterMode {\n        case .generateBaselines(let baselinesDirectory, let modulesRequestingBaselines):\n            settings[\"SWIFT_API_DIGESTER_MODE\"] = SwiftAPIDigesterMode.api.rawValue\n            for module in modulesRequestingBaselines {\n                settings[\"RUN_SWIFT_ABI_GENERATION_TOOL_MODULE_\\(module)\"] = \"YES\"\n            }\n            settings[\"RUN_SWIFT_ABI_GENERATION_TOOL\"] = \"$(RUN_SWIFT_ABI_GENERATION_TOOL_MODULE_$(PRODUCT_MODULE_NAME))\"\n            settings[\"SWIFT_ABI_GENERATION_TOOL_OUTPUT_DIR\"] = baselinesDirectory.appending(components: [\"$(PRODUCT_MODULE_NAME)\", \"ABI\"]).pathString\n        case .compareToBaselines(let baselinesDirectory, let modulesToCompare, let breakageAllowListPath):\n            settings[\"SWIFT_API_DIGESTER_MODE\"] = SwiftAPIDigesterMode.api.rawValue\n            settings[\"SWIFT_ABI_CHECKER_DOWNGRADE_ERRORS\"] = \"YES\"\n            for module in modulesToCompare {\n                settings[\"RUN_SWIFT_ABI_CHECKER_TOOL_MODULE_\\(module)\"] = \"YES\"\n            }\n            settings[\"RUN_SWIFT_ABI_CHECKER_TOOL\"] = \"$(RUN_SWIFT_ABI_CHECKER_TOOL_MODULE_$(PRODUCT_MODULE_NAME))\"\n            settings[\"SWIFT_ABI_CHECKER_BASELINE_DIR\"] = baselinesDirectory.appending(component: \"$(PRODUCT_MODULE_NAME)\").pathString\n            if let breakageAllowListPath {\n                settings[\"SWIFT_ABI_CHECKER_EXCEPTIONS_FILE\"] = breakageAllowListPath.pathString\n            }\n        case nil:\n            break\n        }\n        return settings\n    }\n\n    private func getPIFBuilder() async throws -> PIFBuilder {\n        try await pifBuilder.memoize {\n            let graph = try await getPackageGraph()\n            // materializeStaticArchiveProductsForRootPackages currently has some minor compatibility\n            // issues when building interdependent root packages on Windows, primarily where projects\n            // like swift-corelibs-foundation relied on specific linkage patterns when using\n            // @_dynamicReplacement(for:). For now, disable this option if there is more than one\n            // root package, but we should reconsider this decision in the future.\n            let materializeStaticArchiveProductsForRootPackages = graph.rootPackages.count == 1\n            let pifBuilder = try PIFBuilder(\n                graph: graph,\n                parameters: .init(\n                    buildParameters,\n                    supportedSwiftVersions: supportedSwiftVersions(),\n                    pluginScriptRunner: self.pluginConfiguration.scriptRunner,\n                    disableSandbox: self.pluginConfiguration.disableSandbox,\n                    pluginWorkingDirectory: self.pluginConfiguration.workDirectory,\n                    additionalFileRules: additionalFileRules,\n                    addLocalRpaths: !self.buildParameters.linkingParameters.shouldDisableLocalRpath,\n                    materializeStaticArchiveProductsForRootPackages: materializeStaticArchiveProductsForRootPackages,\n                    createDynamicVariantsForLibraryProducts: false,\n                ),\n                fileSystem: self.fileSystem,\n                observabilityScope: self.observabilityScope,\n            )\n            return pifBuilder\n        }\n    }\n\n    public func generatePIF(preserveStructure: Bool) async throws -> String {\n        pifBuilder = .init()\n        packageGraph = .init()\n        let pifBuilder = try await getPIFBuilder()\n        let pif = try await pifBuilder.generatePIF(\n            preservePIFModelStructure: preserveStructure,\n            printPIFManifestGraphviz: buildParameters.printPIFManifestGraphviz,\n            buildParameters: buildParameters\n        )\n        return pif\n    }\n\n    public func writePIF(buildParameters: BuildParameters) async throws {\n        let pif = try await generatePIF(preserveStructure: false)\n        try self.fileSystem.writeIfChanged(path: buildParameters.pifManifest, string: pif)\n    }\n\n    package struct LongLivedBuildServiceSession {\n        package var session: SWBBuildServiceSession\n        package var diagnostics: [SwiftBuildMessage.DiagnosticInfo]\n        package var teardownHandler: () async throws -> Void\n    }\n\n    package func createLongLivedSession(name: String) async throws -> LongLivedBuildServiceSession {\n        let service = try await SWBBuildService(connectionMode: .inProcessStatic(swiftbuildServiceEntryPoint))\n        do {\n            let (session, diagnostics) = try await createSession(service: service, name: name, toolchain: buildParameters.toolchain, packageManagerResourcesDirectory: packageManagerResourcesDirectory)\n            let teardownHandler = {\n                try await session.close()\n                await service.close()\n            }\n            return LongLivedBuildServiceSession(session: session, diagnostics: diagnostics, teardownHandler: teardownHandler)\n        } catch {\n            await service.close()\n            throw error\n        }\n    }\n\n    public func cancel(deadline: DispatchTime) throws {}\n\n    /// Returns the package graph using the graph loader closure.\n    ///\n    /// First access will cache the graph.\n    public func getPackageGraph() async throws -> ModulesGraph {\n        try await packageGraph.memoize {\n            try await packageGraphLoader()\n        }\n    }\n}\n\n// MARK: - Helpers\n\nextension String {\n    /// Escape the usual shell related things, such as quoting, but also handle Windows\n    /// back-slashes.\n    fileprivate func shellEscaped() -> String {\n        #if os(Windows)\n        return self.spm_shellEscaped().replacingOccurrences(of: \"\\\\\", with: \"/\")\n        #else\n        return self.spm_shellEscaped()\n        #endif\n    }\n}\n\nfileprivate extension Triple {\n    var deploymentTargetSettingName: String? {\n        switch (self.os, self.environment) {\n        case (.macosx, _):\n            return \"MACOSX_DEPLOYMENT_TARGET\"\n        case (.ios, _):\n            return \"IPHONEOS_DEPLOYMENT_TARGET\"\n        case (.tvos, _):\n            return \"TVOS_DEPLOYMENT_TARGET\"\n        case (.watchos, _):\n            return \"WATCHOS_DEPLOYMENT_TARGET\"\n        case (_, .android):\n            return \"ANDROID_DEPLOYMENT_TARGET\"\n        case (.freebsd, _):\n            return \"FREEBSD_DEPLOYMENT_TARGET\"\n        default:\n            return nil\n        }\n    }\n\n    var deploymentTargetVersion: Version {\n        if isAndroid() {\n            // Android triples store the version in the environment\n            var environmentName = self.environmentName[...]\n            if environment != nil {\n                let prefixes = [\"androideabi\", \"android\"]\n                for prefix in prefixes {\n                    if environmentName.hasPrefix(prefix) {\n                        environmentName = environmentName.dropFirst(prefix.count)\n                        break\n                    }\n                }\n            }\n\n            return Version(parse: environmentName)\n        }\n        return osVersion\n    }\n\n    var deploymentTargetVersionString: String? {\n        let v = deploymentTargetVersion\n        guard v != .zero else {\n            return nil\n        }\n        var components = [v.major, v.minor, v.micro]\n        let minimumComponentCount = isApple() ? 2 : 1\n        while components.last == 0 && components.count > minimumComponentCount {\n            components.removeLast()\n        }\n        return components.map { String($0) }.joined(separator: \".\")\n    }\n}\n\nfileprivate extension [BuildFlag] {\n    var rawFlagsForSwiftBuild: [String] {\n        filter {\n            switch $0.source {\n            case .commandLineOptions:\n                // Flags specified by the user. These are generally the only ones that should be passed on.\n                return true\n            case .plugin:\n                // FIXME: Not yet handled\n                return true\n            case .debugging:\n                // FIXME: Not yet handled\n                return true\n            case .toolset:\n                // Swift Build loads toolset flags internally as part of loading Swift SDKs, or by passing the custom toolsets\n                // via the SWIFT_SDK_TOOLSETS build setting, and may introspect them to override build settings.\n                // Don't duplicate them here.\n                return false\n            case .defaultSwiftTestingSearchPath:\n                // Swift Build computes these internally. It's important not to add them a second time here\n                // as it can break the intended search path ordering, for example, if the user is building\n                // Swift Testing as a package dependency.\n                return false\n            case .defaultWindowsSettings:\n                // Swift Build computes these internally.\n                return false\n            case .swiftSDK:\n                // Swift Build loads Swift SDK flags internally, and may introspect them to override build\n                // settings. Don't duplicate them here.\n                return false\n            case nil:\n                // Remaining flags are legacy build system specific (one occurrence only), or in tests.\n                return false\n            }\n        }.map { $0.value }\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftBuildSupport/SwiftBuildSystemMessageHandler.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\nimport Foundation\n@_spi(SwiftPMInternal)\nimport SPMBuildCore\nimport enum TSCUtility.Diagnostics\nimport SWBBuildService\nimport SwiftBuild\nimport protocol TSCBasic.OutputByteStream\n\n\n/// Handler for SwiftBuildMessage events sent by the SWBBuildOperation.\npublic final class SwiftBuildSystemMessageHandler {\n    private let observabilityScope: ObservabilityScope\n    private let outputStream: OutputByteStream\n    private let logLevel: Basics.Diagnostic.Severity\n    private var buildState: BuildState = .init()\n    private let enableBacktraces: Bool\n    private let buildDelegate: SPMBuildCore.BuildSystemDelegate?\n\n    public typealias BuildSystemCallback = (SwiftBuildSystem) -> Void\n\n    let progressAnimation: ProgressAnimationProtocol\n    var serializedDiagnosticPathsByTargetID: [Int: [Basics.AbsolutePath]] = [:]\n    // FIXME: This eventually gets passed into the BuildResult, which expects a\n    // dictionary of [String: [AbsolutePath]]. Eventually, we should refactor it\n    // to accept a dictionary keyed by a unique identifier (possibly `ResolvedModule.ID`),\n    // and instead use the above dictionary keyed by target ID.\n    var serializedDiagnosticPathsByTargetName: [String: [Basics.AbsolutePath]] {\n        serializedDiagnosticPathsByTargetID.reduce(into: [:]) { result, entry in\n            if let name = buildState.targetsByID[entry.key]?.targetName {\n                result[name, default: []].append(contentsOf: entry.value)\n            }\n        }\n    }\n\n    /// Tracks the task IDs for failed tasks.\n    private var failedTasks: [Int] = []\n    /// Tracks the tasks by their signature for which we have already emitted output.\n    private var tasksEmitted: EmittedTasks = .init()\n\n    public init(\n        observabilityScope: ObservabilityScope,\n        outputStream: OutputByteStream,\n        logLevel: Basics.Diagnostic.Severity,\n        enableBacktraces: Bool = false,\n        buildDelegate: SPMBuildCore.BuildSystemDelegate? = nil\n    )\n    {\n        self.observabilityScope = observabilityScope\n        self.outputStream = outputStream\n        self.logLevel = logLevel\n        self.progressAnimation = ProgressAnimation.ninja(\n            stream: outputStream,\n            verbose: self.logLevel.isVerbose,\n            normalizeStep: false\n        )\n        self.enableBacktraces = enableBacktraces\n        self.buildDelegate = buildDelegate\n    }\n\n    private func emitInfoAsDiagnostic(info: SwiftBuildMessage.DiagnosticInfo) {\n        let fixItsDescription = if info.fixIts.hasContent {\n            \": \" + info.fixIts.map { String(describing: $0) }.joined(separator: \", \")\n        } else {\n            \"\"\n        }\n        let message = if let locationDescription = info.location.userDescription {\n            \"\\(locationDescription) \\(info.message)\\(fixItsDescription)\"\n        } else {\n            \"\\(info.message)\\(fixItsDescription)\"\n        }\n        let severity: Diagnostic.Severity = switch info.kind {\n        case .error: .error\n        case .warning: .warning\n        case .note: .info\n        case .remark: .debug\n        }\n        self.observabilityScope.emit(severity: severity, message: \"\\(message)\\n\")\n\n        for childDiagnostic in info.childDiagnostics {\n            emitInfoAsDiagnostic(info: childDiagnostic)\n        }\n    }\n\n    private func emitDiagnosticCompilerOutput(_ info: SwiftBuildMessage.TaskStartedInfo, condition: OutputCondition) {\n        // Don't redundantly emit task output.\n        guard !self.tasksEmitted.contains(info.taskSignature) else {\n            return\n        }\n        // Assure we have a data buffer to decode.\n        guard let buffer = buildState.dataBuffer(for: info), !buffer.isEmpty else {\n            return\n        }\n\n        // Decode the buffer to a string\n        let decodedOutput = String(decoding: buffer, as: UTF8.self)\n\n        // Emit message.\n        observabilityScope.print(decodedOutput, condition: condition)\n\n        // Record that we've emitted the output for a given task.\n        self.tasksEmitted.insert(info)\n    }\n\n    private func handleTaskOutput(\n        _ info: SwiftBuildMessage.TaskCompleteInfo,\n        _ startedInfo: SwiftBuildMessage.TaskStartedInfo,\n        _ enableTaskBacktraces: Bool\n    ) throws {\n        // Begin by emitting the text received by the task started event.\n        if let started = self.buildState.startedInfo(for: startedInfo) {\n            // Emit depending on verbosity level.\n            if logLevel.isVerbose {\n                self.outputStream.send(started)\n            }\n            self.observabilityScope.print(started, condition: .onlyWhenVerbose)\n        }\n\n        guard info.result == .success else {\n            emitFailedTaskOutput(info, startedInfo)\n            return\n        }\n\n        // Handle diagnostics, if applicable.\n        // This handles diagnostics for successful tasks, which could be notes or warnings.\n        let diagnostics = self.buildState.diagnostics(for: info)\n        if !diagnostics.isEmpty {\n            // Emit diagnostics using the `DiagnosticInfo` model.\n            diagnostics.forEach({ emitInfoAsDiagnostic(info: $0) })\n        } else {\n            // Emit diagnostics through textual compiler output.\n            let isDiagnosticOutput = self.buildState.diagnosticDataBufferExists(for: info)\n            emitDiagnosticCompilerOutput(startedInfo, condition: isDiagnosticOutput ? .always : .onlyWhenVerbose)\n        }\n\n        // Handle task backtraces, if applicable.\n        if enableTaskBacktraces {\n            if let id = SWBBuildOperationBacktraceFrame.Identifier(taskSignatureData: Data(startedInfo.taskSignature.utf8)),\n               let backtrace = SWBTaskBacktrace(from: id, collectedFrames: buildState.collectedBacktraceFrames) {\n                let formattedBacktrace = backtrace.renderTextualRepresentation()\n                if !formattedBacktrace.isEmpty {\n                    self.observabilityScope.emit(info: \"Task backtrace:\\n\\(formattedBacktrace)\")\n                }\n            }\n        }\n    }\n\n    private func emitFailedTaskOutput(\n        _ info: SwiftBuildMessage.TaskCompleteInfo,\n        _ startedInfo: SwiftBuildMessage.TaskStartedInfo\n    ) {\n        // Assure that the task has failed.\n        guard info.result != .success else {\n            return\n        }\n        // Don't redundantly emit task output.\n        guard !tasksEmitted.contains(startedInfo.taskSignature) else {\n            return\n        }\n\n        // Track failed tasks.\n        self.failedTasks.append(info.taskID)\n\n        // Check for existing diagnostics with matching taskID/taskSignature.\n        // If we've captured the compiler output with formatted diagnostics keyed by\n        // this task's signature, emit them.\n        // Note that this is a workaround instead of emitting directly from a `DiagnosticInfo`\n        // message, as here we receive the formatted code snippet directly from the compiler.\n        let diagnosticsBuffer = buildState.diagnostics(for: info)\n        if !diagnosticsBuffer.isEmpty {\n            diagnosticsBuffer.forEach({ emitInfoAsDiagnostic(info: $0) })\n        } else {\n            emitDiagnosticCompilerOutput(startedInfo, condition: .always)\n        }\n\n        let message = \"\\(startedInfo.ruleInfo) failed with a nonzero exit code.\"\n        // If we have the command line display string available, then we\n        // should continue to emit this as an error. Otherwise, this doesn't\n        // give enough information to the user for it to be useful so we can\n        // demote it to an info-level log.\n        if let cmdLineDisplayStr = startedInfo.commandLineDisplayString {\n            self.observabilityScope.emit(severity: .error, message: \"\\(message) Command line: \\(cmdLineDisplayStr)\")\n        } else {\n            self.observabilityScope.emit(severity: .info, message: message)\n        }\n\n        // Track that we have emitted output for this task.\n        tasksEmitted.insert(startedInfo)\n    }\n\n    public func emitEvent(_ message: SwiftBuild.SwiftBuildMessage) throws -> BuildSystemCallback? {\n        var callback: BuildSystemCallback? = nil\n\n        guard !self.logLevel.isQuiet else { return callback }\n        switch message {\n        case .buildCompleted(let info):\n            progressAnimation.complete(success: info.result == .ok)\n            if info.result == .cancelled {\n                callback = { [weak self] buildSystem in\n                    self?.buildDelegate?.buildSystemDidCancel(buildSystem)\n                }\n            } else {\n                callback = { [weak self] buildSystem in\n                    self?.buildDelegate?.buildSystem(buildSystem, didFinishWithResult: info.result == .ok)\n                }\n            }\n        case .didUpdateProgress(let progressInfo):\n            let step = Int(progressInfo.percentComplete)\n            let message = if let targetName = progressInfo.targetName {\n                \"\\(targetName) \\(progressInfo.message)\"\n            } else {\n                \"\\(progressInfo.message)\"\n            }\n\n            // Skip if message doesn't contain anything useful to display.\n            // TODO: To file an issue for SwiftBuild here.\n            if message.contains(where: \\.isLetter) {\n                progressAnimation.update(step: step, total: 100, text: message)\n            }\n\n            callback = { [weak self] buildSystem in\n                self?.buildDelegate?.buildSystem(buildSystem, didUpdateTaskProgress: message)\n            }\n        case .diagnostic(let info):\n            // If this is representative of a global/target diagnostic\n            // then we can emit immediately.\n            // Otherwise, defer emission of diagnostic to matching taskCompleted event.\n            if info.locationContext.isGlobal || info.locationContext.isTarget {\n                emitInfoAsDiagnostic(info: info)\n            } else if info.appendToOutputStream {\n                buildState.appendDiagnostic(info)\n            } else {\n                // Track task IDs for diagnostics to later emit them via compiler output.\n                buildState.appendDiagnosticID(info)\n            }\n        case .output(let info):\n            // Append to buffer-per-task storage\n            buildState.appendToBuffer(info)\n        case .taskStarted(let info):\n            try buildState.started(task: info, self.logLevel)\n\n            let targetInfo = try buildState.target(for: info)\n            callback = { [weak self] buildSystem in\n                self?.buildDelegate?.buildSystem(buildSystem, willStartCommand: BuildSystemCommand(info, targetInfo: targetInfo))\n                self?.buildDelegate?.buildSystem(buildSystem, didStartCommand: BuildSystemCommand(info, targetInfo: targetInfo))\n            }\n        case .taskComplete(let info):\n            let startedInfo = try buildState.completed(task: info)\n\n            // Handler for task output, handling failures if applicable.\n            try self.handleTaskOutput(info, startedInfo, self.enableBacktraces)\n\n            let targetInfo = try buildState.target(for: startedInfo)\n            callback = { [weak self] buildSystem in\n                self?.buildDelegate?.buildSystem(buildSystem, didFinishCommand: BuildSystemCommand(startedInfo, targetInfo: targetInfo))\n            }\n            if let targetID = targetInfo?.targetID {\n                try serializedDiagnosticPathsByTargetID[targetID, default: []].append(contentsOf: startedInfo.serializedDiagnosticsPaths.compactMap {\n                    try Basics.AbsolutePath(validating: $0.pathString)\n                })\n            }\n        case .targetStarted(let info):\n            try buildState.started(target: info)\n        case .backtraceFrame(let info):\n            if self.enableBacktraces {\n                buildState.collectedBacktraceFrames.add(frame: info)\n            }\n        case .targetComplete(let info):\n            _ = try buildState.completed(target: info)\n        case .planningOperationStarted(_):\n            // Emitting under higher-level verbosity so as not to overwhelm output.\n            // This is the same behaviour as the native system.\n            if self.logLevel.isVerbose {\n                self.outputStream.send(\"Planning build\" + \"\\n\")\n            }\n        case .planningOperationCompleted(_):\n            // Emitting under higher-level verbosity so as not to overwhelm output.\n            if self.logLevel.isVerbose {\n                self.outputStream.send(\"Planning complete\" + \"\\n\")\n            }\n        case .targetUpToDate(let info):\n            // Received when a target is entirely up to date and did not need to be built.\n            if self.logLevel.isVerbose {\n                self.outputStream.send(\"Target \\(info.guid) up to date.\" + \"\\n\")\n            }\n        case .reportBuildDescription, .reportPathMap, .preparedForIndex, .buildStarted, .preparationComplete, .taskUpToDate:\n            break\n        case .buildDiagnostic, .targetDiagnostic, .taskDiagnostic:\n            break // deprecated\n        case .buildOutput, .targetOutput, .taskOutput:\n            break // deprecated\n        @unknown default:\n            break\n        }\n\n        return callback\n    }\n}\n\n// MARK: SwiftBuildSystemMessageHandler.BuildState\n\nextension SwiftBuildSystemMessageHandler {\n    /// Manages the state of an active build operation, tracking targets, tasks, buffers, and backtrace frames.\n    /// This struct maintains the complete state model for build operations, coordinating data between\n    /// different phases of the build lifecycle.\n    struct BuildState {\n        // Targets\n        internal var targetsByID: [Int: SwiftBuild.SwiftBuildMessage.TargetStartedInfo] = [:]\n        private var completedTargets: [Int: SwiftBuild.SwiftBuildMessage.TargetCompleteInfo] = [:]\n\n        // Tasks\n        private var activeTasks: [Int: SwiftBuild.SwiftBuildMessage.TaskStartedInfo] = [:]\n        private var completedTasks: [Int: SwiftBuild.SwiftBuildMessage.TaskCompleteInfo] = [:]\n        private var taskIDToSignature: [Int: String] = [:]\n\n        // Per-task buffers\n        private var taskDataBuffer: TaskDataBuffer = .init()\n        private var diagnosticsBuffer: TaskDiagnosticBuffer = .init()\n        private var diagnosticTaskIDs: Set<Int> = []\n\n        // Backtrace frames\n        internal var collectedBacktraceFrames = SWBBuildOperationCollectedBacktraceFrames()\n\n        /// Registers the start of a build task, validating that the task hasn't already been started.\n        /// - Parameter task: The task start information containing task ID and signature\n        /// - Throws: Fatal error if the task is already active\n        mutating func started(task: SwiftBuild.SwiftBuildMessage.TaskStartedInfo, _ logLevel: Basics.Diagnostic.Severity) throws {\n            if activeTasks[task.taskID] != nil {\n                throw Diagnostics.fatalError\n            }\n            activeTasks[task.taskID] = task\n            taskIDToSignature[task.taskID] = task.taskSignature\n\n            // Track relevant task info to emit to user.\n            let output = if let cmdLineDisplayStr = task.commandLineDisplayString, logLevel.isVerbose {\n                \"\\(task.executionDescription)\\n\\(cmdLineDisplayStr)\"\n            } else {\n                task.executionDescription\n            }\n            taskDataBuffer.setTaskStartedInfo(task, output)\n        }\n\n        /// Marks a task as completed and removes it from active tracking.\n        /// - Parameter task: The task completion information\n        /// - Returns: The original task start information for the completed task\n        /// - Throws: Fatal error if the task was not started or already completed\n        mutating func completed(task: SwiftBuild.SwiftBuildMessage.TaskCompleteInfo) throws -> SwiftBuild.SwiftBuildMessage.TaskStartedInfo {\n            guard let startedTaskInfo = activeTasks[task.taskID] else {\n                throw Diagnostics.fatalError\n            }\n            if completedTasks[task.taskID] != nil {\n                throw Diagnostics.fatalError\n            }\n            // Track completed task, remove from active tasks.\n            self.completedTasks[task.taskID] = task\n            self.activeTasks[task.taskID] = nil\n\n            return startedTaskInfo\n        }\n\n        /// Registers the start of a build target, validating that the target hasn't already been started.\n        /// - Parameter target: The target start information containing target ID and name\n        /// - Throws: Fatal error if the target is already active\n        mutating func started(target: SwiftBuild.SwiftBuildMessage.TargetStartedInfo) throws {\n            if targetsByID[target.targetID] != nil {\n                throw Diagnostics.fatalError\n            }\n            targetsByID[target.targetID] = target\n        }\n\n        /// Marks a target as completed and removes it from active tracking.\n        /// - Parameter target: The target completion information\n        /// - Returns: The original target start information for the completed target\n        /// - Throws: Fatal error if the target was not started\n        mutating func completed(target: SwiftBuild.SwiftBuildMessage.TargetCompleteInfo) throws -> SwiftBuild.SwiftBuildMessage.TargetStartedInfo {\n            guard let targetStartedInfo = targetsByID[target.targetID] else {\n                throw Diagnostics.fatalError\n            }\n\n            completedTargets[target.targetID] = target\n            return targetStartedInfo\n        }\n\n        /// Retrieves the target information associated with a given task.\n        /// - Parameter task: The task start information to look up the target for\n        /// - Returns: The target start information if the task has an associated target, nil otherwise\n        /// - Throws: Fatal error if the target ID exists but no matching target is found\n        func target(for task: SwiftBuild.SwiftBuildMessage.TaskStartedInfo) throws -> SwiftBuild.SwiftBuildMessage.TargetStartedInfo? {\n            guard let id = task.targetID else {\n                return nil\n            }\n            guard let target = targetsByID[id] else {\n                throw Diagnostics.fatalError\n            }\n            return target\n        }\n\n        /// Retrieves the task signature for a given task ID.\n        /// - Parameter id: The task ID to look up\n        /// - Returns: The task signature string if found, nil otherwise\n        func taskSignature(for id: Int) -> String? {\n            if let signature = taskIDToSignature[id] {\n                return signature\n            }\n            return nil\n        }\n    }\n}\n\n// MARK: - SwiftBuildSystemMessageHandler.BuildState.TaskDataBuffer\n\nextension SwiftBuildSystemMessageHandler.BuildState {\n    /// Manages data buffers for build tasks, supporting multiple indexing strategies.\n    /// This buffer system stores output data from tasks using both task signatures and task IDs,\n    /// providing flexible access patterns for different build message types and legacy support.\n    struct TaskDataBuffer {\n        // Emit using observabilityScope.print(_:verbose:)\n        private var taskSignatureBuffer: [String: Data] = [:]\n        private var taskIDBuffer: [Int: Data] = [:]\n\n        // Emit using observabilityScope.emit(info:)\n        private var taskStartedNotifications: [Int: String] = [:]\n\n        /// Retrieves data for a task signature key.\n        /// - Parameter key: The task signature string\n        /// - Returns: The associated data buffer, or nil if not found\n        subscript(key: String) -> Data? {\n            self.taskSignatureBuffer[key]\n        }\n\n        /// Retrieves or sets data for a task signature key with a default value.\n        /// - Parameters:\n        ///   - key: The task signature string\n        ///   - defaultValue: The default data to return/store if no value exists\n        /// - Returns: The stored data buffer or the default value\n        subscript(key: String, default defaultValue: Data) -> Data {\n            get { self.taskSignatureBuffer[key] ?? defaultValue }\n            set { self.taskSignatureBuffer[key] = newValue }\n        }\n\n        /// Retrieves or sets data using a LocationContext for task identification.\n        /// - Parameters:\n        ///   - key: The location context containing task or target ID information\n        ///   - defaultValue: The default data to return/store if no value exists\n        /// - Returns: The stored data buffer or the default value\n        subscript(key: SwiftBuildMessage.LocationContext, default defaultValue: Data) -> Data {\n            get {\n                // Check each ID kind and try to fetch the associated buffer.\n                // If unable to get a non-nil result, then follow through to the\n                // next check.\n                if let taskID = key.taskID,\n                   let result = self.taskIDBuffer[taskID] {\n                    return result\n                } else {\n                    return defaultValue\n                }\n            }\n\n            set {\n                if let taskID = key.taskID {\n                    self.taskIDBuffer[taskID] = newValue\n                }\n            }\n        }\n\n        /// Retrieves or sets data using a LocationContext2 for task identification.\n        /// - Parameter key: The location context containing task signature information\n        /// - Returns: The associated data buffer, or nil if not found\n        subscript(key: SwiftBuildMessage.LocationContext2) -> Data? {\n            get {\n                if let taskSignature = key.taskSignature {\n                    return self.taskSignatureBuffer[taskSignature]\n                }\n\n                return nil\n            }\n\n            set {\n                if let taskSignature = key.taskSignature {\n                    self.taskSignatureBuffer[taskSignature] = newValue\n                }\n            }\n        }\n\n        /// Retrieves data for a specific task using TaskStartedInfo.\n        /// - Parameter task: The task start information containing signature and ID\n        /// - Returns: The associated data buffer, or nil if not found\n        subscript(task: SwiftBuildMessage.TaskStartedInfo) -> Data? {\n            get {\n                guard let result = self.taskSignatureBuffer[task.taskSignature] else {\n                    // Default to checking targetID and taskID.\n                    if let result = self.taskIDBuffer[task.taskID] {\n                        return result\n                    }\n\n                    return nil\n                }\n\n                return result\n            }\n        }\n\n        func taskStartedInfo(_ task: SwiftBuildMessage.TaskStartedInfo) -> String? {\n            guard let result = taskStartedNotifications[task.taskID] else {\n                return nil\n            }\n\n            return result\n        }\n\n        mutating func setTaskStartedInfo(_ task: SwiftBuildMessage.TaskStartedInfo, _ text: String) {\n            self.taskStartedNotifications[task.taskID] = text\n        }\n    }\n\n    /// Appends output data to the appropriate task buffer based on location context information.\n    /// - Parameter info: The output info containing data and location context for storage\n    mutating func appendToBuffer(_ info: SwiftBuildMessage.OutputInfo) {\n        // Attempt to key by taskSignature; at times this may not be possible,\n        // in which case we'd need to fall back to using LocationContext.\n        guard let taskSignature = info.locationContext2.taskSignature else {\n            // If we cannot find the task signature from the locationContext2,\n            // use deprecated locationContext instead to find task signature.\n            // If this fails to find an associated task signature, track\n            // relevant IDs from the location context in the task buffer.\n            if let taskID = info.locationContext.taskID,\n               let taskSignature = self.taskSignature(for: taskID) {\n                self.taskDataBuffer[taskSignature, default: .init()].append(info.data)\n            }\n\n            self.taskDataBuffer[info.locationContext, default: .init()].append(info.data)\n\n            return\n        }\n\n        self.taskDataBuffer[taskSignature, default: .init()].append(info.data)\n    }\n\n    /// Retrieves the accumulated data buffer for a specific task.\n    /// - Parameter task: The task start information to look up data for\n    /// - Returns: The accumulated data buffer for the task, or nil if no data exists\n    func dataBuffer(for task: SwiftBuild.SwiftBuildMessage.TaskStartedInfo) -> Data? {\n        guard let data = taskDataBuffer[task.taskSignature] else {\n            // Fallback to checking taskID and targetID.\n            return taskDataBuffer[task]\n        }\n\n        return data\n    }\n\n    func startedInfo(for task: SwiftBuild.SwiftBuildMessage.TaskStartedInfo) -> String? {\n        return self.taskDataBuffer.taskStartedInfo(task)\n    }\n}\n\n// MARK: - SwiftBuildSystemMessageHandler.BuildState.TaskDiagnosticBuffer\n\nextension SwiftBuildSystemMessageHandler.BuildState {\n    /// Manages diagnostic information buffers for build tasks, organized by task signatures and IDs.\n    /// This buffer system collects diagnostic messages during task execution for later retrieval\n    /// and structured reporting of build errors, warnings, and other diagnostic information.\n    struct TaskDiagnosticBuffer {\n        private var diagnosticSignatureBuffer: [String: [SwiftBuildMessage.DiagnosticInfo]] = [:]\n        private var diagnosticIDBuffer: [Int: [SwiftBuildMessage.DiagnosticInfo]] = [:]\n\n        /// Retrieves diagnostic information using LocationContext2 for task identification.\n        /// - Parameter key: The location context containing task signature information\n        /// - Returns: Array of diagnostic info for the task, or nil if not found\n        subscript(key: SwiftBuildMessage.LocationContext2) -> [SwiftBuildMessage.DiagnosticInfo]? {\n            guard let taskSignature = key.taskSignature else {\n                return nil\n            }\n            return self.diagnosticSignatureBuffer[taskSignature]\n        }\n\n        /// Retrieves or sets diagnostic information using LocationContext2 with a default value.\n        /// - Parameters:\n        ///   - key: The location context containing task signature information\n        ///   - defaultValue: The default diagnostic array to return if no value exists\n        /// - Returns: Array of diagnostic info for the task, or the default value\n        subscript(key: SwiftBuildMessage.LocationContext2, default defaultValue: [SwiftBuildMessage.DiagnosticInfo]) -> [SwiftBuildMessage.DiagnosticInfo] {\n            get { self[key] ?? defaultValue }\n            set {\n                self[key, default: defaultValue]\n            }\n        }\n\n        /// Retrieves diagnostic information using LocationContext for task identification.\n        /// - Parameter key: The location context containing task ID information\n        /// - Returns: Array of diagnostic info for the task, or nil if not found\n        subscript(key: SwiftBuildMessage.LocationContext) -> [SwiftBuildMessage.DiagnosticInfo]? {\n            guard let taskID = key.taskID else {\n                return nil\n            }\n\n            return self.diagnosticIDBuffer[taskID]\n        }\n\n        /// Retrieves diagnostic information using LocationContext with a default value.\n        /// - Parameters:\n        ///   - key: The location context containing task ID information\n        ///   - defaultValue: The default diagnostic array to return if no value exists\n        /// - Returns: Array of diagnostic info for the task, or the default value\n        subscript(key: SwiftBuildMessage.LocationContext, default defaultValue: [SwiftBuildMessage.DiagnosticInfo]) -> [SwiftBuildMessage.DiagnosticInfo] {\n            get { self[key] ?? defaultValue }\n        }\n\n        /// Retrieves or sets diagnostic information using a task signature string.\n        /// - Parameter key: The task signature string\n        /// - Returns: Array of diagnostic info for the task signature\n        subscript(key: String) -> [SwiftBuildMessage.DiagnosticInfo] {\n            get { self.diagnosticSignatureBuffer[key] ?? [] }\n            set { self.diagnosticSignatureBuffer[key] = newValue }\n        }\n\n        /// Retrieves or sets diagnostic information using a task ID.\n        /// - Parameter key: The task ID\n        /// - Returns: Array of diagnostic info for the task ID\n        subscript(key: Int) -> [SwiftBuildMessage.DiagnosticInfo] {\n            get { self.diagnosticIDBuffer[key] ?? [] }\n            set { self.diagnosticIDBuffer[key] = newValue }\n        }\n    }\n\n    /// Appends a diagnostic message to the appropriate diagnostic buffer.\n    /// - Parameter info: The diagnostic information to store, containing location context for identification\n    mutating func appendDiagnostic(_ info: SwiftBuildMessage.DiagnosticInfo) {\n        guard let taskID = info.locationContext.taskID else {\n            return\n        }\n\n        diagnosticsBuffer[taskID].append(info)\n    }\n\n    /// Appends a diagnostic task ID to the appropriate diagnostic buffer.\n    /// - Parameter info: The diagnostic information to store, containing location context for identification\n    mutating func appendDiagnosticID(_ info: SwiftBuildMessage.DiagnosticInfo) {\n        guard let taskID = info.locationContext.taskID else {\n            return\n        }\n\n        self.diagnosticTaskIDs.insert(taskID)\n        // Swift compiler subtasks may also contribute diagnostics, mark their parents\n        // as containing diagnostics so that they get printed.\n        if let task = activeTasks[taskID], let parentID = task.parentTaskID {\n            self.diagnosticTaskIDs.insert(parentID)\n        }\n    }\n\n    /// Retrieves all diagnostic information for a completed task.\n    /// - Parameter task: The task completion information containing the task ID\n    /// - Returns: Array of diagnostic info associated with the task\n    func diagnostics(for task: SwiftBuild.SwiftBuildMessage.TaskCompleteInfo) -> [SwiftBuildMessage.DiagnosticInfo] {\n        return self.diagnosticsBuffer[task.taskID]\n    }\n\n    /// Determines whether there is a data buffer for the given diagnostic task ID.\n    /// - Parameter task: The task completion information containing the task ID\n    /// - Returns: A Bool that indicates whether a data buffer entry exists for the given task ID.\n    func diagnosticDataBufferExists(for task: SwiftBuild.SwiftBuildMessage.TaskCompleteInfo) -> Bool {\n        return self.diagnosticTaskIDs.contains(task.taskID)\n    }\n}\n\n// MARK: - SwiftBuildSystemMessageHandler.EmittedTasks\n\nextension SwiftBuildSystemMessageHandler {\n    /// A collection that tracks tasks for which output has already been emitted to prevent duplicate output.\n    /// This struct ensures that task output is only displayed once during the build process, improving\n    /// the readability and accuracy of build logs by avoiding redundant messaging.\n    struct EmittedTasks: Collection {\n        public typealias Index = Set<TaskInfo>.Index\n        public typealias Element = Set<TaskInfo>.Element\n        var startIndex: Set<SwiftBuildSystemMessageHandler.TaskInfo>.Index {\n            self.storage.startIndex\n        }\n        var endIndex: Set<SwiftBuildSystemMessageHandler.TaskInfo>.Index {\n            self.storage.endIndex\n        }\n\n        private var storage: Set<TaskInfo> = []\n\n        public init() { }\n\n        /// Inserts a task info into the emitted tasks collection.\n        /// - Parameter task: The task information to mark as emitted\n        mutating func insert(_ task: TaskInfo) {\n            storage.insert(task)\n        }\n\n        subscript(position: Index) -> Element {\n            return storage[position]\n        }\n\n        func index(after i: Set<SwiftBuildSystemMessageHandler.TaskInfo>.Index) -> Set<SwiftBuildSystemMessageHandler.TaskInfo>.Index {\n            return storage.index(after: i)\n        }\n\n        /// Checks if a specific task info has been marked as emitted.\n        /// - Parameter task: The task information to check\n        /// - Returns: True if the task has already been emitted, false otherwise\n        func contains(_ task: TaskInfo) -> Bool {\n            return storage.contains(task)\n        }\n\n        /// Checks if a task with the given ID has been marked as emitted.\n        /// - Parameter taskID: The task ID to check\n        /// - Returns: True if a task with this ID has already been emitted, false otherwise\n        public func contains(_ taskID: Int) -> Bool {\n            return storage.contains(where: { $0.taskID == taskID })\n        }\n\n        /// Checks if a task with the given signature has been marked as emitted.\n        /// - Parameter taskSignature: The task signature to check\n        /// - Returns: True if a task with this signature has already been emitted, false otherwise\n        public func contains(_ taskSignature: String) -> Bool {\n            return storage.contains(where: { $0.taskSignature == taskSignature })\n        }\n\n        /// Convenience method to insert a task using TaskStartedInfo.\n        /// - Parameter startedTaskInfo: The task start information to mark as emitted\n        public mutating func insert(_ startedTaskInfo: SwiftBuildMessage.TaskStartedInfo) {\n            self.storage.insert(.init(startedTaskInfo))\n        }\n    }\n\n    /// Represents essential identifying information for a build task.\n    /// This struct encapsulates both the numeric task ID and string task signature,\n    /// providing efficient lookup and comparison capabilities for task tracking.\n    struct TaskInfo: Hashable {\n        let taskID: Int\n        let taskSignature: String\n\n        /// Initializes TaskInfo from TaskStartedInfo.\n        /// - Parameter startedTaskInfo: The task start information containing ID and signature\n        public init(_ startedTaskInfo: SwiftBuildMessage.TaskStartedInfo) {\n            self.taskID = startedTaskInfo.taskID\n            self.taskSignature = startedTaskInfo.taskSignature\n        }\n\n        /// Compares TaskInfo with a task signature string.\n        /// - Parameters:\n        ///   - lhs: The TaskInfo instance\n        ///   - rhs: The task signature string to compare\n        /// - Returns: True if the TaskInfo's signature matches the string\n        public static func ==(lhs: Self, rhs: String) -> Bool {\n            return lhs.taskSignature == rhs\n        }\n\n        /// Compares TaskInfo with a task ID integer.\n        /// - Parameters:\n        ///   - lhs: The TaskInfo instance\n        ///   - rhs: The task ID integer to compare\n        /// - Returns: True if the TaskInfo's ID matches the integer\n        public static func ==(lhs: Self, rhs: Int) -> Bool {\n            return lhs.taskID == rhs\n        }\n    }\n}\n\n/// Convenience extensions to extract taskID and targetID from the LocationContext.\nextension SwiftBuildMessage.LocationContext {\n    /// Extracts the task ID from the location context.\n    /// - Returns: The task ID if the context represents a task or global task, nil otherwise\n    var taskID: Int? {\n        switch self {\n        case .task(let id, _), .globalTask(let id):\n            return id\n        case .target, .global:\n            return nil\n        }\n    }\n\n    /// Extracts the target ID from the location context.\n    /// - Returns: The target ID if the context represents a task or target, nil otherwise\n    var targetID: Int? {\n        switch self {\n        case .task(_, let id), .target(let id):\n            return id\n        case .global, .globalTask:\n            return nil\n        }\n    }\n\n    /// Determines if the location context represents a global scope.\n    /// - Returns: True if the context is global, false otherwise\n    var isGlobal: Bool {\n        switch self {\n        case .global:\n            return true\n        case .task, .target, .globalTask:\n            return false\n        }\n    }\n\n    /// Determines if the location context represents a target scope.\n    /// - Returns: True if the context is target-specific, false otherwise\n    var isTarget: Bool {\n        switch self {\n        case .target:\n            return true\n        case .global, .globalTask, .task:\n            return false\n        }\n    }\n}\n\nfileprivate extension SwiftBuild.SwiftBuildMessage.DiagnosticInfo.Location {\n    var userDescription: String? {\n        switch self {\n        case .path(let path, let fileLocation):\n            switch fileLocation {\n            case .textual(let line, let column):\n                var description = \"\\(path):\\(line)\"\n                if let column { description += \":\\(column)\" }\n                return description\n            case .object(let identifier):\n                return \"\\(path):\\(identifier)\"\n            case .none:\n                return path\n            }\n\n        case .buildSettings(let names):\n            return names.joined(separator: \", \")\n\n        case .buildFiles(let buildFiles, let targetGUID):\n            return \"\\(targetGUID): \" + buildFiles.map { String(describing: $0) }.joined(separator: \", \")\n\n        case .unknown:\n            return nil\n        }\n    }\n}\n\nfileprivate extension BuildSystemCommand {\n    init(_ taskStartedInfo: SwiftBuildMessage.TaskStartedInfo, targetInfo: SwiftBuildMessage.TargetStartedInfo?) {\n        self = .init(\n            name: taskStartedInfo.executionDescription,\n            targetName: targetInfo?.targetName,\n            description: taskStartedInfo.commandLineDisplayString ?? \"\",\n            serializedDiagnosticPaths: taskStartedInfo.serializedDiagnosticsPaths.compactMap {\n                try? Basics.AbsolutePath(validating: $0.pathString)\n            }\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftFixIt/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SwiftFixIt STATIC\n  SwiftFixIt.swift)\ntarget_link_libraries(SwiftFixIt PUBLIC\n  Basics\n\n  SwiftSyntax::SwiftDiagnostics\n  SwiftSyntax::SwiftIDEUtils\n  SwiftSyntax::SwiftParser\n  SwiftSyntax::SwiftSyntax\n\n  TSCBasic\n  TSCUtility)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(SwiftFixIt PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n"
  },
  {
    "path": "Sources/SwiftFixIt/SwiftFixIt.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport protocol Basics.FileSystem\n\nimport struct SwiftDiagnostics.Diagnostic\nimport struct SwiftDiagnostics.DiagnosticCategory\nimport protocol SwiftDiagnostics.DiagnosticMessage\nimport enum SwiftDiagnostics.DiagnosticSeverity\nimport struct SwiftDiagnostics.DiagnosticsFormatter\nimport struct SwiftDiagnostics.FixIt\nimport protocol SwiftDiagnostics.FixItMessage\nimport struct SwiftDiagnostics.GroupedDiagnostics\nimport struct SwiftDiagnostics.MessageID\n\n@_spi(FixItApplier)\nimport enum SwiftIDEUtils.FixItApplier\n\nimport struct SwiftParser.Parser\n\nimport struct SwiftSyntax.AbsolutePosition\nimport struct SwiftSyntax.SourceEdit\nimport struct SwiftSyntax.SourceFileSyntax\nimport class SwiftSyntax.SourceLocationConverter\nimport struct SwiftSyntax.Syntax\n\nimport struct TSCBasic.ByteString\nimport struct TSCUtility.SerializedDiagnostics\n\nprivate enum Error: Swift.Error {\n    case unexpectedDiagnosticSeverity\n    case failedToResolveSourceLocation\n}\n\n// FIXME: An abstraction for tests to work around missing memberwise initializers in `TSCUtility.SerializedDiagnostics`.\nprotocol AnySourceLocation {\n    var filename: String { get }\n    var line: UInt64 { get }\n    var column: UInt64 { get }\n    var offset: UInt64 { get }\n}\n\n// FIXME: An abstraction for tests to work around missing memberwise initializers in `TSCUtility.SerializedDiagnostics`.\nprotocol AnyFixIt {\n    associatedtype SourceLocation: AnySourceLocation\n\n    var start: SourceLocation { get }\n    var end: SourceLocation { get }\n    var text: String { get }\n}\n\n// FIXME: An abstraction for tests to work around missing memberwise initializers in `TSCUtility.SerializedDiagnostics`.\nprotocol AnyDiagnostic {\n    associatedtype SourceLocation: AnySourceLocation\n    associatedtype FixIt: AnyFixIt where FixIt.SourceLocation == SourceLocation\n\n    var text: String { get }\n    var level: SerializedDiagnostics.Diagnostic.Level { get }\n    var location: SourceLocation? { get }\n    var category: String? { get }\n    var categoryURL: String? { get }\n    var flag: String? { get }\n    var ranges: [(SourceLocation, SourceLocation)] { get }\n    var fixIts: [FixIt] { get }\n}\n\nextension AnyDiagnostic {\n    var isPrimary: Bool {\n        !self.isNote\n    }\n\n    var isNote: Bool {\n        self.level == .note\n    }\n\n    var isIgnored: Bool {\n        self.level == .ignored\n    }\n\n    var hasFixIt: Bool {\n        !self.fixIts.isEmpty\n    }\n\n    var hasNoLocation: Bool {\n        self.location == nil\n    }\n}\n\nextension SerializedDiagnostics.Diagnostic: AnyDiagnostic {}\nextension SerializedDiagnostics.SourceLocation: AnySourceLocation {}\n\nextension SerializedDiagnostics.FixIt: AnyFixIt {}\n\n/// Encapsulates initial diagnostic skipping behavior.\nprivate struct PrimaryDiagnosticFilter<Diagnostic: AnyDiagnostic>: ~Copyable {\n    /// A hashable type storing the minimum data necessary to uniquely identify\n    /// a diagnostic for our purposes.\n    private struct DiagnosticID: Hashable {\n        private let message: String\n        private let filename: String\n        private let utf8Offset: UInt64\n        private let level: SerializedDiagnostics.Diagnostic.Level\n\n        init(diagnostic: Diagnostic) {\n            self.level = diagnostic.level\n            self.message = diagnostic.text\n            // Force the location. We should be filtering out diagnostics\n            // without a location.\n            self.filename = diagnostic.location!.filename\n            self.utf8Offset = diagnostic.location!.offset\n        }\n    }\n\n    private var uniquePrimaryDiagnostics: Set<DiagnosticID> = []\n\n    let categories: Set<String>\n    let excludedSourceDirectories: Set<AbsolutePath>\n\n    init(categories: Set<String>, excludedSourceDirectories: Set<AbsolutePath>) {\n        self.categories = categories\n        self.excludedSourceDirectories = excludedSourceDirectories\n    }\n\n    /// Returns a Boolean value indicating whether to skip the given primary\n    /// diagnostic and its notes.\n    mutating func shouldSkip(primaryDiagnosticWithNotes: some Collection<Diagnostic>) -> Bool {\n        let diagnostic = primaryDiagnosticWithNotes[primaryDiagnosticWithNotes.startIndex]\n        precondition(diagnostic.isPrimary)\n\n        // Skip if ignored.\n        if diagnostic.isIgnored {\n            return true\n        }\n\n        // Skip if no location.\n        guard let location = diagnostic.location else {\n            return true\n        }\n\n        // Skip if categories are given and the diagnostic does not\n        // belong to any of them.\n        if !self.categories.isEmpty {\n            guard let category = diagnostic.category, self.categories.contains(category) else {\n                return true\n            }\n        }\n\n        // Skip if excluded directories were given and the source file the\n        // diagnostic appears in is in any of them.\n        if !self.excludedSourceDirectories.isEmpty {\n            if let sourceFilePath = try? AbsolutePath(validating: location.filename),\n               self.excludedSourceDirectories.contains(where: sourceFilePath.isDescendant(of:))\n            {\n                return true\n            }\n        }\n\n        let notes = primaryDiagnosticWithNotes.dropFirst()\n        precondition(notes.allSatisfy(\\.isNote))\n\n        // Consider the diagnostic compromised if a note does not have a\n        // location.\n        if notes.contains(where: \\.hasNoLocation) {\n            return true\n        }\n\n        switch notes.count(where: \\.hasFixIt) {\n        case 0:\n            // No notes have fix-its. Skip if neither does the primary\n            // diagnostic.\n            guard diagnostic.hasFixIt else {\n                return true\n            }\n        case 1:\n            break\n        default:\n            // Skip if more than 1 note has a fix-it. These diagnostics\n            // generally require user intervention.\n            // TODO: This will have to be done lazier once we support printing them.\n            return true\n        }\n\n        // Skip if we've seen this primary diagnostic before.\n        //\n        // NB: This check is done last to prevent the set from growing without\n        // need.\n        guard self.uniquePrimaryDiagnostics.insert(.init(diagnostic: diagnostic)).inserted else {\n            return true\n        }\n\n        return false\n    }\n}\n\n/// The backing API for `SwiftFixitCommand`.\npackage struct SwiftFixIt /*: ~Copyable */ { // TODO: Crashes with ~Copyable\n    private typealias DiagnosticsPerFile = [SourceFile: [SwiftDiagnostics.Diagnostic]]\n\n    private let fileSystem: any FileSystem\n\n    private let diagnosticsPerFile: DiagnosticsPerFile\n\n    package init(\n        diagnosticFiles: some Collection<AbsolutePath>,\n        categories: Set<String> = [],\n        excludedSourceDirectories: Set<AbsolutePath> = [],\n        fileSystem: any FileSystem\n    ) throws {\n        // Deserialize the diagnostics.\n        let diagnostics = try diagnosticFiles.map { path in\n            let fileContents = try fileSystem.readFileContents(path)\n            return try TSCUtility.SerializedDiagnostics(bytes: fileContents).diagnostics\n        }.joined()\n\n        self = try SwiftFixIt(\n            diagnostics: diagnostics,\n            categories: categories,\n            excludedSourceDirectories: excludedSourceDirectories,\n            fileSystem: fileSystem\n        )\n    }\n\n    init<Diagnostic: AnyDiagnostic>(\n        diagnostics: some Collection<Diagnostic>,\n        categories: Set<String>,\n        excludedSourceDirectories: Set<AbsolutePath>,\n        fileSystem: any FileSystem\n    ) throws {\n        self.fileSystem = fileSystem\n\n        var filter = PrimaryDiagnosticFilter<Diagnostic>(categories: categories, excludedSourceDirectories: excludedSourceDirectories)\n        _ = consume categories\n\n        // Build a map from source files to `SwiftDiagnostics` diagnostics.\n        var diagnosticsPerFile: DiagnosticsPerFile = [:]\n        var diagnosticConverter = DiagnosticConverter(fileSystem: fileSystem)\n\n        var nextPrimaryIndex = diagnostics.startIndex\n        while nextPrimaryIndex != diagnostics.endIndex {\n            let currentPrimaryIndex = nextPrimaryIndex\n            precondition(diagnostics[currentPrimaryIndex].isPrimary)\n\n            // Shift the index to the next primary diagnostic.\n            repeat {\n                diagnostics.formIndex(after: &nextPrimaryIndex)\n            } while nextPrimaryIndex != diagnostics.endIndex && diagnostics[nextPrimaryIndex].isNote\n\n            let primaryDiagnosticWithNotes = diagnostics[currentPrimaryIndex ..< nextPrimaryIndex]\n\n            if filter.shouldSkip(primaryDiagnosticWithNotes: primaryDiagnosticWithNotes) {\n                continue\n            }\n\n            for diagnostic in primaryDiagnosticWithNotes {\n                // We are only interested in diagnostics with fix-its.\n                // TODO: This will have to change once we support printing them.\n                guard diagnostic.hasFixIt else {\n                    continue\n                }\n\n                let (sourceFile, convertedDiagnostic) = try diagnosticConverter.diagnostic(from: diagnostic)\n\n                diagnosticsPerFile[consume sourceFile, default: []].append(consume convertedDiagnostic)\n            }\n        }\n\n        self.diagnosticsPerFile = diagnosticsPerFile\n    }\n}\n\nextension SwiftFixIt {\n    package struct Summary: Equatable {\n        package var numberOfFixItsApplied: Int\n        package var numberOfFilesChanged: Int\n\n        package init(numberOfFixItsApplied: Int, numberOfFilesChanged: Int) {\n            self.numberOfFixItsApplied = numberOfFixItsApplied\n            self.numberOfFilesChanged = numberOfFilesChanged\n        }\n\n        package static func + (lhs: consuming Self, rhs: Self) -> Self {\n            lhs += rhs\n            return lhs\n        }\n\n        package static func += (lhs: inout Self, rhs: Self) {\n            lhs.numberOfFixItsApplied += rhs.numberOfFixItsApplied\n            lhs.numberOfFilesChanged += rhs.numberOfFilesChanged\n        }\n    }\n\n    package func applyFixIts() throws -> Summary {\n        var numberOfFixItsApplied = 0\n\n        // Bulk-apply fix-its to each file and write the results back.\n        for (sourceFile, diagnostics) in self.diagnosticsPerFile {\n            numberOfFixItsApplied += diagnostics.count\n\n            var edits = [SwiftSyntax.SourceEdit]()\n            edits.reserveCapacity(diagnostics.count)\n            for diagnostic in diagnostics {\n                for fixIt in diagnostic.fixIts {\n                    for edit in fixIt.edits {\n                        edits.append(edit)\n                    }\n                }\n            }\n\n            let result = SwiftIDEUtils.FixItApplier.apply(\n                edits: consume edits,\n                to: sourceFile.syntax,\n                allowDuplicateInsertions: false\n            )\n\n            try self.fileSystem.writeFileContents(sourceFile.path, string: consume result)\n        }\n\n        return Summary(\n            numberOfFixItsApplied: numberOfFixItsApplied,\n            numberOfFilesChanged: self.diagnosticsPerFile.keys.count\n        )\n    }\n}\n\nextension SwiftDiagnostics.DiagnosticSeverity {\n    fileprivate init?(from level: TSCUtility.SerializedDiagnostics.Diagnostic.Level) {\n        switch level {\n        case .ignored:\n            return nil\n        case .note:\n            self = .note\n        case .warning:\n            self = .warning\n        case .error, .fatal:\n            self = .error\n        case .remark:\n            self = .remark\n        }\n    }\n}\n\nprivate struct DeserializedDiagnosticMessage: SwiftDiagnostics.DiagnosticMessage {\n    let message: String\n    let severity: SwiftDiagnostics.DiagnosticSeverity\n    let category: SwiftDiagnostics.DiagnosticCategory?\n\n    var diagnosticID: SwiftDiagnostics.MessageID {\n        .init(domain: \"swift-fixit\", id: \"\\(Self.self)\")\n    }\n}\n\nprivate struct DeserializedFixItMessage: SwiftDiagnostics.FixItMessage {\n    var message: String { \"\" }\n\n    var fixItID: SwiftDiagnostics.MessageID {\n        .init(domain: \"swift-fixit\", id: \"\\(Self.self)\")\n    }\n}\n\nprivate struct SourceFile {\n    let path: AbsolutePath\n    let syntax: SwiftSyntax.SourceFileSyntax\n\n    let sourceLocationConverter: SwiftSyntax.SourceLocationConverter\n\n    init(path: AbsolutePath, in fileSystem: borrowing some FileSystem) throws {\n        self.path = path\n\n        let bytes = try fileSystem.readFileContents(path)\n\n        self.syntax = bytes.contents.withUnsafeBufferPointer { pointer in\n            SwiftParser.Parser.parse(source: pointer)\n        }\n\n        self.sourceLocationConverter = SwiftSyntax.SourceLocationConverter(\n            fileName: path.pathString,\n            tree: self.syntax\n        )\n    }\n\n    func position(of location: borrowing some AnySourceLocation) throws -> AbsolutePosition {\n        guard try AbsolutePath(validating: location.filename) == self.path else {\n            // Wrong source file.\n            throw Error.failedToResolveSourceLocation\n        }\n\n        return AbsolutePosition(utf8Offset: Int(location.offset))\n    }\n\n    func node(at location: borrowing some AnySourceLocation) throws -> Syntax {\n        let position = try position(of: location)\n\n        if let token = syntax.token(at: position) {\n            return SwiftSyntax.Syntax(token)\n        }\n\n        if position == self.syntax.endPosition {\n            // FIXME: EOF token is not included in '.token(at: position)'\n            // We might want to include it, but want to avoid special handling.\n            if let token = syntax.lastToken(viewMode: .all) {\n                return SwiftSyntax.Syntax(token)\n            }\n\n            return Syntax(self.syntax)\n        }\n\n        // position out of range.\n        throw Error.failedToResolveSourceLocation\n    }\n}\n\nextension SourceFile: Hashable {\n    static func == (lhs: Self, rhs: Self) -> Bool {\n        lhs.syntax == rhs.syntax\n    }\n\n    func hash(into hasher: inout Hasher) {\n        hasher.combine(self.syntax)\n    }\n}\n\nprivate struct DiagnosticConverter: ~Copyable {\n    private struct SourceFileCache: ~Copyable {\n        private let fileSystem: any FileSystem\n\n        private var sourceFiles: [AbsolutePath: SourceFile]\n\n        init(fileSystem: any FileSystem) {\n            self.fileSystem = fileSystem\n            self.sourceFiles = [:]\n        }\n\n        subscript(location: some AnySourceLocation) -> SourceFile {\n            mutating get throws {\n                let path = try AbsolutePath(validating: location.filename)\n\n                if let cached = sourceFiles[path] {\n                    return cached\n                }\n\n                let sourceFile = try SourceFile(path: path, in: fileSystem)\n                sourceFiles[path] = sourceFile\n\n                return sourceFile\n            }\n        }\n    }\n\n    private var sourceFileCache: SourceFileCache\n\n    init(fileSystem: any FileSystem) {\n        self.sourceFileCache = SourceFileCache(fileSystem: fileSystem)\n    }\n}\n\nextension DiagnosticConverter {\n    // We expect a fix-it to be in the same source file as the diagnostic it is\n    // attached to. The opposite can hurt clarity and is more difficult and\n    // less efficient to model and process in general. The compiler may want to\n    // actually guard against this pattern and establish a convention to instead\n    // emit notes with those fix-its.\n    private static func fixIt(\n        from diagnostic: borrowing some AnyDiagnostic,\n        in sourceFile: /* borrowing */ SourceFile\n    ) throws -> SwiftDiagnostics.FixIt {\n        let changes = try diagnostic.fixIts.map { fixIt in\n            let startPosition = try sourceFile.position(of: fixIt.start)\n            let endPosition = try sourceFile.position(of: fixIt.end)\n\n            return SwiftDiagnostics.FixIt.Change.replaceText(\n                range: startPosition ..< endPosition,\n                with: fixIt.text,\n                in: Syntax(sourceFile.syntax)\n            )\n        }\n\n        return SwiftDiagnostics.FixIt(message: DeserializedFixItMessage(), changes: changes)\n    }\n\n    private static func highlights(\n        from diagnostic: borrowing some AnyDiagnostic,\n        in sourceFile: /* borrowing */ SourceFile\n    ) throws -> [Syntax] {\n        try diagnostic.ranges.map { startLocation, endLocation in\n            let startPosition = try sourceFile.position(of: startLocation)\n            let endPosition = try sourceFile.position(of: endLocation)\n\n            var highlightedNode = try sourceFile.node(at: startLocation)\n\n            // Walk up from the start token until we find a syntax node that matches\n            // the highlight range.\n            while true {\n                // If this syntax matches our starting/ending positions, add the\n                // highlight and we're done.\n                if highlightedNode.positionAfterSkippingLeadingTrivia == startPosition\n                    && highlightedNode.endPositionBeforeTrailingTrivia == endPosition\n                {\n                    break\n                }\n\n                // Go up to the parent.\n                guard let parent = highlightedNode.parent else {\n                    break\n                }\n\n                highlightedNode = parent\n            }\n\n            return highlightedNode\n        }\n    }\n\n    typealias Diagnostic = (sourceFile: SourceFile, diagnostic: SwiftDiagnostics.Diagnostic)\n\n    mutating func diagnostic(\n        from diagnostic: borrowing some AnyDiagnostic\n    ) throws -> Diagnostic {\n        guard !diagnostic.fixIts.isEmpty else {\n            preconditionFailure(\"Expected diagnostic with fix-its\")\n        }\n\n        guard let location = diagnostic.location else {\n            preconditionFailure(\"Diagnostic without location cannot be converted\")\n        }\n\n        let message: DeserializedDiagnosticMessage\n        do {\n            guard let severity = SwiftDiagnostics.DiagnosticSeverity(from: diagnostic.level) else {\n                preconditionFailure(\"Diagnostic with 'ignored' severity cannot be converted\")\n            }\n\n            let category: SwiftDiagnostics.DiagnosticCategory? =\n                if let category = diagnostic.category {\n                    .init(name: category, documentationURL: diagnostic.categoryURL)\n                } else {\n                    nil\n                }\n\n            message = .init(\n                message: diagnostic.text,\n                severity: severity,\n                category: category\n            )\n        }\n\n        let sourceFile = try sourceFileCache[location]\n\n        return try Diagnostic(\n            sourceFile: sourceFile,\n            diagnostic: SwiftDiagnostics.Diagnostic(\n                node: sourceFile.node(at: location),\n                position: sourceFile.position(of: location),\n                message: message,\n                highlights: Self.highlights(from: diagnostic, in: sourceFile),\n                fixIts: [\n                    Self.fixIt(from: diagnostic, in: sourceFile),\n                ]\n            )\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftPMBuildServer/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SwiftPMBuildServer STATIC\n  DisableSigpipe.swift\n  SwiftPMBuildServer.swift)\ntarget_link_libraries(SwiftPMBuildServer PUBLIC\n  Basics\n  Build\n  PackageGraph\n  PackageLoading\n  PackageModel\n  SPMBuildCore\n  SourceControl\n  SourceKitLSPAPI\n  SwiftBuildSupport\n  Workspace\n\n  SwiftBuild::SwiftBuild\n\n  SwiftToolsProtocols::ToolsProtocolsSwiftExtensions\n  SwiftToolsProtocols::BuildServerProtocol\n  SwiftToolsProtocols::LanguageServerProtocol\n  SwiftToolsProtocols::LanguageServerProtocolTransport\n\n  TSCBasic)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(SwiftPMBuildServer PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n"
  },
  {
    "path": "Sources/SwiftPMBuildServer/DisableSigpipe.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if canImport(Glibc)\nimport Glibc\n#elseif canImport(Musl)\nimport Musl\n#elseif canImport(Android)\nimport Android\n#endif\n\n#if canImport(Glibc) || canImport(Musl) || canImport(Android)\n// This is a lazily initialised global variable that when read for the first time, will ignore SIGPIPE.\nprivate let globallyIgnoredSIGPIPE: Bool = {\n  /* no F_SETNOSIGPIPE on Linux :( */\n  _ = signal(SIGPIPE, SIG_IGN)\n  return true\n}()\n#endif\n\n/// We receive a `SIGPIPE` if we write to a pipe that points to a crashed process. This in particular happens if the\n/// target of a `JSONRPCConnection` has crashed and we try to send it a message or if swift-format crashes and we try\n/// to send the source file to it.\n///\n/// On Darwin, `DispatchIO` ignores `SIGPIPE` for the pipes handled by it and swift-tools-support-core offers\n/// `LocalFileOutputByteStream.disableSigpipe`, but that features is not available on Linux.\n///\n/// Instead, globally ignore `SIGPIPE` on Linux to prevent us from crashing if the `JSONRPCConnection`'s target crashes.\n///\n/// On Darwin platforms and on Windows this is a no-op.\npackage func globallyDisableSigpipeIfNeeded() {\n  #if !canImport(Darwin) && !os(Windows)\n  let haveWeIgnoredSIGPIEThisIsHereToTriggerIgnoringIt = globallyIgnoredSIGPIPE\n  guard haveWeIgnoredSIGPIEThisIsHereToTriggerIgnoringIt else {\n    fatalError(\"globallyIgnoredSIGPIPE should always be true\")\n  }\n  #endif\n}\n"
  },
  {
    "path": "Sources/SwiftPMBuildServer/SwiftPMBuildServer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n#if canImport(LanguageServerProtocolTransport)\nimport Basics\nimport SwiftBuild\nimport Foundation\nimport SPMBuildCore\nimport SwiftBuildSupport\nimport SwiftBuild\nimport SWBBuildService\nimport Workspace\nimport BuildServerProtocol\nimport LanguageServerProtocol\nimport LanguageServerProtocolTransport\nimport ToolsProtocolsSwiftExtensions\n\n// Remove these extensions once they've been added to swift-tools-protocols\npackage extension Connection {\n    func withCancellableCheckedThrowingContinuation<Handle: Sendable, Result>(\n        _ operation: (_ continuation: CheckedContinuation<Result, any Error>) -> Handle,\n        cancel: @Sendable (Handle) -> Void\n    ) async throws -> Result {\n        let handleWrapper = ThreadSafeBox<Handle?>(nil)\n\n        @Sendable\n        func callCancel() {\n            /// Take the request ID out of the box. This ensures that we only send the\n            /// cancel notification once in case the `Task.isCancelled` and the\n            /// `onCancel` check race.\n            if let handle = handleWrapper.takeValue() {\n                cancel(handle)\n            }\n        }\n\n        return try await withTaskCancellationHandler(\n            operation: {\n                try Task.checkCancellation()\n                return try await withCheckedThrowingContinuation { continuation in\n                    handleWrapper.put(operation(continuation))\n\n                    // Check if the task was cancelled. This ensures we send a\n                    // CancelNotification even if the task gets cancelled after we register\n                    // the cancellation handler but before we set the `requestID`.\n                    if Task.isCancelled {\n                        callCancel()\n                    }\n                }\n            },\n            onCancel: callCancel\n        )\n    }\n\n    // Disfavor this over Connection.send implemented in swift-tools-protocols by https://github.com/swiftlang/swift-tools-protocols/pull/28\n    // TODO: Remove this method once we have updated the swift-tools-protocols dependency to include #28\n    @_disfavoredOverload\n    func send<R: RequestType>(_ request: R) async throws -> R.Response {\n        return try await withCancellableCheckedThrowingContinuation { continuation in\n            return self.send(request) { result in\n                continuation.resume(with: result)\n            }\n        } cancel: { requestID in\n            self.send(CancelRequestNotification(id: requestID))\n        }\n    }\n}\n\npublic actor SwiftPMBuildServer: QueueBasedMessageHandler {\n    private let underlyingBuildServer: SWBBuildServer\n    private let connectionToUnderlyingBuildServer: LocalConnection\n    private let packageRoot: Basics.AbsolutePath\n    private let buildSystem: SwiftBuildSystem\n    private let workspace: Workspace\n\n    public let messageHandlingHelper = QueueBasedMessageHandlerHelper(\n        signpostLoggingCategory: \"build-server-message-handling\",\n        createLoggingScope: false\n    )\n    public let messageHandlingQueue = AsyncQueue<BuildServerMessageDependencyTracker>()\n    /// Serializes package loading\n    private let packageLoadingQueue = AsyncQueue<Serial>()\n    /// Connection used to send messages to the client of the build server.\n    private let connectionToClient: any Connection\n\n    /// Represents the lifetime of the build server implementation..\n    enum ServerState: CustomStringConvertible {\n        case waitingForInitializeRequest\n        case waitingForInitializedNotification\n        case running\n        case shutdown\n\n        var description: String {\n            switch self {\n            case .waitingForInitializeRequest:\n                \"waiting for initialization request\"\n            case .waitingForInitializedNotification:\n                \"waiting for initialization notification\"\n            case .running:\n                \"running\"\n            case .shutdown:\n                \"shutdown\"\n            }\n        }\n    }\n    var state: ServerState = .waitingForInitializeRequest\n    /// Allows customization of server exit behavior.\n    var exitHandler: (Int) -> Void\n\n    public init(packageRoot: Basics.AbsolutePath, buildSystem: SwiftBuildSystem, workspace: Workspace, connectionToClient: any Connection, exitHandler: @escaping (Int) -> Void) async throws {\n        self.packageRoot = packageRoot\n        self.buildSystem = buildSystem\n        self.workspace = workspace\n        self.connectionToClient = connectionToClient\n        self.exitHandler = exitHandler\n        let session = try await buildSystem.createLongLivedSession(name: \"swiftpm-build-server\")\n        let connectionToUnderlyingBuildServer = LocalConnection(receiverName: \"underlying-swift-build-server\")\n        self.connectionToUnderlyingBuildServer = connectionToUnderlyingBuildServer\n        let connectionFromUnderlyingBuildServer = LocalConnection(receiverName: \"swiftpm-build-server\")\n        let buildrequest = try await self.buildSystem.makeBuildRequest(\n            session: session.session,\n            configuredTargets: [.init(rawValue: \"ALL-INCLUDING-TESTS\")],\n            derivedDataPath: self.buildSystem.buildParameters.dataPath,\n            symbolGraphOptions: nil\n        )\n        self.underlyingBuildServer = SWBBuildServer(\n            session: session.session,\n            containerPath: buildSystem.buildParameters.pifManifest.pathString,\n            buildRequest: buildrequest,\n            connectionToClient: connectionFromUnderlyingBuildServer,\n            exitHandler: { _ in\n                connectionToUnderlyingBuildServer.close()\n                try? await session.teardownHandler()\n            }\n        )\n        connectionToUnderlyingBuildServer.start(handler: underlyingBuildServer)\n        connectionFromUnderlyingBuildServer.start(handler: self)\n    }\n\n    public func handle(notification: some NotificationType) async {\n        switch notification {\n        case is OnBuildExitNotification:\n            connectionToUnderlyingBuildServer.send(notification)\n            if state == .shutdown {\n                exitHandler(0)\n            } else {\n                exitHandler(1)\n            }\n        case is OnBuildInitializedNotification:\n            connectionToUnderlyingBuildServer.send(notification)\n            state = .running\n            scheduleRegeneratingBuildDescription()\n        case let notification as OnWatchedFilesDidChangeNotification:\n            // The underlying build server only receives updates via new PIF, so don't forward this notification.\n            for change in notification.changes {\n                if self.fileEventShouldTriggerPackageReload(event: change) {\n                    scheduleRegeneratingBuildDescription()\n                    return\n                }\n            }\n        case is OnBuildLogMessageNotification:\n            // If we receive a build log message notification, forward it on to the client\n            connectionToClient.send(notification)\n        case is OnBuildTargetDidChangeNotification:\n            // If the underlying server notifies us of target updates, forward the notification to the client\n            connectionToClient.send(notification)\n        default:\n            logToClient(.warning, \"SwiftPM build server received unknown notification type: \\(notification)\")\n        }\n    }\n\n    private func logToClient(_ kind: BuildServerProtocol.MessageType, _ message: String, _ structure: BuildServerProtocol.StructuredLogKind? = nil) {\n        connectionToClient.send(\n            OnBuildLogMessageNotification(type: .log, message: \"\\(message)\", structure: structure)\n        )\n    }\n\n    public func handle<Request: RequestType>(\n        request: Request,\n        id: RequestID,\n        reply: @Sendable @escaping (LSPResult<Request.Response>) -> Void\n    ) async {\n        let request = RequestAndReply(request, reply: reply)\n        switch request {\n        case let request as RequestAndReply<BuildShutdownRequest>:\n            await request.reply {\n                _ = try await connectionToUnderlyingBuildServer.send(request.params)\n                return await shutdown()\n            }\n        case let request as RequestAndReply<BuildTargetPrepareRequest>:\n            await request.reply {\n                var underlyingRequest = request.params\n                underlyingRequest.targets.removeAll(where: \\.isSwiftPMBuildServerTargetID )\n                return try await connectionToUnderlyingBuildServer.send(underlyingRequest)\n            }\n        case let request as RequestAndReply<BuildTargetSourcesRequest>:\n            await request.reply {\n                var underlyingRequest = request.params\n                underlyingRequest.targets.removeAll(where: \\.isSwiftPMBuildServerTargetID)\n                var sourcesResponse = try await connectionToUnderlyingBuildServer.send(underlyingRequest)\n                for target in request.params.targets.filter({ $0.isSwiftPMBuildServerTargetID }) {\n                    if target == .forPackageManifest {\n                        sourcesResponse.items.append(await manifestSourcesItem())\n                    } else {\n                        await logToClient(.warning, \"SwiftPM build server processed target sources request for unexpected target '\\(target)'\")\n                    }\n                }\n                return sourcesResponse\n            }\n        case let request as RequestAndReply<InitializeBuildRequest>:\n            await request.reply { try await self.initialize(request: request.params) }\n        case let request as RequestAndReply<TextDocumentSourceKitOptionsRequest>:\n            await request.reply {\n                if request.params.target.isSwiftPMBuildServerTargetID {\n                    return try await manifestSourceKitOptions(request: request.params)\n                } else {\n                    return try await connectionToUnderlyingBuildServer.send(request.params)\n                }\n            }\n        case let request as RequestAndReply<WorkspaceBuildTargetsRequest>:\n            await request.reply {\n                var targetsResponse = try await connectionToUnderlyingBuildServer.send(request.params)\n                targetsResponse.targets.append(await manifestTarget())\n                return targetsResponse\n            }\n        case let request as RequestAndReply<WorkspaceWaitForBuildSystemUpdatesRequest>:\n            await request.reply {\n                await waitForBuildSystemUpdates(request: request.params)\n            }\n        default:\n            await request.reply { throw ResponseError.methodNotFound(Request.method) }\n        }\n    }\n\n    private func initialize(request: InitializeBuildRequest) async throws -> InitializeBuildResponse {\n        if state != .waitingForInitializeRequest {\n            logToClient(.warning, \"Received initialization request while the build server is \\(state)\")\n        }\n        let underlyingInitializationResponse = try await connectionToUnderlyingBuildServer.send(request)\n        let underlyingSourceKitData = SourceKitInitializeBuildResponseData(fromLSPAny: underlyingInitializationResponse.data)\n        if underlyingSourceKitData?.watchers?.isEmpty == false {\n            logToClient(.warning, \"Underlying build server reported unexpected file watchers\")\n        }\n        state = .waitingForInitializedNotification\n        return InitializeBuildResponse(\n            displayName: \"SwiftPM Build Server\",\n            version: SwiftVersion.current.displayString,\n            bspVersion: \"2.2.0\",\n            capabilities: BuildServerCapabilities(),\n            dataKind: .sourceKit,\n            data: SourceKitInitializeBuildResponseData(\n                indexDatabasePath: underlyingSourceKitData?.indexDatabasePath,\n                indexStorePath: underlyingSourceKitData?.indexStorePath,\n                outputPathsProvider: true,\n                prepareProvider: true,\n                sourceKitOptionsProvider: true,\n                watchers: []\n            ).encodeToLSPAny()\n        )\n    }\n\n    private func manifestTarget() -> BuildTarget {\n        // In the future, we should add a new target to represent plugin scripts so they can load the PackagePlugin module.\n        return BuildTarget(\n            id: .forPackageManifest,\n            displayName: \"Package Manifest\",\n            tags: [.notBuildable],\n            languageIds: [.swift],\n            dependencies: []\n        )\n    }\n\n    private let versionSpecificManifestRegex = #/^Package@swift-(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?.swift$/#\n\n    private func manifestSourcesItem() -> SourcesItem {\n        let versionSpecificManifests = try? FileManager.default.contentsOfDirectory(\n            at: packageRoot.asURL,\n          includingPropertiesForKeys: nil\n        ).compactMap { (url) -> SourceItem? in\n          guard (try? versionSpecificManifestRegex.wholeMatch(in: url.lastPathComponent)) != nil else {\n            return nil\n          }\n          return SourceItem(\n            uri: DocumentURI(url),\n            kind: .file,\n            generated: false\n          )\n        }\n        return SourcesItem(target: .forPackageManifest, sources: [\n            SourceItem(\n                uri: DocumentURI(packageRoot.appending(component: \"Package.swift\").asURL),\n              kind: .file,\n              generated: false\n            )\n        ] + (versionSpecificManifests ?? []))\n    }\n\n    private func manifestSourceKitOptions(request: TextDocumentSourceKitOptionsRequest) async throws -> TextDocumentSourceKitOptionsResponse? {\n        guard request.target == .forPackageManifest else {\n            throw ResponseError.unknown(\"Unknown target \\(request.target)\")\n        }\n        guard let path = try request.textDocument.uri.fileURL?.filePath else {\n            throw ResponseError.unknown(\"Unknown manifest path for \\(request.textDocument.uri.pseudoPath)\")\n        }\n        let compilerArgs = try workspace.interpreterFlags(for: path) + [path.pathString]\n        return TextDocumentSourceKitOptionsResponse(compilerArguments: compilerArgs)\n    }\n\n    private func shutdown() -> VoidResponse {\n        state = .shutdown\n        return VoidResponse()\n    }\n\n    private func waitForBuildSystemUpdates(request: WorkspaceWaitForBuildSystemUpdatesRequest) async -> VoidResponse {\n        await packageLoadingQueue.async {}.valuePropagatingCancellation\n        return VoidResponse()\n    }\n\n    /// An event is relevant if it modifies a file that matches one of the file rules used by the SwiftPM workspace.\n    private func fileEventShouldTriggerPackageReload(event: FileEvent) -> Bool {\n        guard let fileURL = event.uri.fileURL else {\n            return false\n        }\n        switch event.type {\n        case .created, .deleted:\n            // This is overly conservative, we may want to consider restricting it to file types which will be built.\n            // However, the possibility of a plugin which might process an arbitrary file type makes this difficult.\n            return true\n        case .changed:\n            return fileURL.lastPathComponent == \"Package.swift\" || fileURL.lastPathComponent == \"Package.resolved\" ||  fileURL.lastPathComponent.wholeMatch(of: versionSpecificManifestRegex) != nil\n        default:\n            logToClient(.warning, \"received unknown file event type: '\\(event.type)'\")\n            return false\n        }\n    }\n\n    public func scheduleRegeneratingBuildDescription() {\n        packageLoadingQueue.async { [buildSystem] in\n            do {\n                try await buildSystem.writePIF(buildParameters: buildSystem.buildParameters)\n                self.connectionToUnderlyingBuildServer.send(OnWatchedFilesDidChangeNotification(changes: [\n                    .init(uri: .init(buildSystem.buildParameters.pifManifest.asURL), type: .changed)\n                ]))\n                _ = try await self.connectionToUnderlyingBuildServer.send(WorkspaceWaitForBuildSystemUpdatesRequest())\n            } catch {\n                self.logToClient(.warning, \"error regenerating build description: \\(error)\")\n            }\n        }\n    }\n}\n\nextension BuildTargetIdentifier {\n    static let swiftPMBuildServerTargetScheme = \"swiftpm\"\n\n    static let forPackageManifest = BuildTargetIdentifier(uri: try! URI(string: \"\\(swiftPMBuildServerTargetScheme)://package-manifest\"))\n\n    var isSwiftPMBuildServerTargetID: Bool {\n        uri.scheme == Self.swiftPMBuildServerTargetScheme\n    }\n}\n#endif\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(SwiftSDKCommand\n  Configuration/ConfigurationSubcommand.swift\n  Configuration/DeprecatedSwiftSDKConfigurationCommand.swift\n  Configuration/ResetConfiguration.swift\n  Configuration/SetConfiguration.swift\n  Configuration/ShowConfiguration.swift\n  ConfigureSwiftSDK.swift\n  SwiftSDKSubcommand.swift\n  InstallSwiftSDK.swift\n  ListSwiftSDKs.swift\n  RemoveSwiftSDK.swift\n  SwiftSDKCommand.swift)\ntarget_link_libraries(SwiftSDKCommand PUBLIC\n  ArgumentParser\n  Basics\n  CoreCommands\n  SPMBuildCore\n  PackageModel)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(SwiftSDKCommand PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS SwiftSDKCommand\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/Configuration/ConfigurationSubcommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport Foundation\nimport PackageModel\n\nprotocol ConfigurationSubcommand: SwiftSDKSubcommand {\n    /// An identifier of an already installed Swift SDK.\n    var sdkID: String { get }\n\n    /// A target triple of the Swift SDK.\n    var targetTriple: String { get }\n\n    /// Run a command related to configuration of Swift SDKs, passing it required configuration\n    /// values.\n    /// - Parameters:\n    ///   - hostTriple: triple of the machine this command is running on.\n    ///   - targetTriple: triple of the machine on which cross-compiled code will run on.\n    ///   - swiftSDK: Swift SDK configuration fetched that matches currently set `sdkID` and\n    ///   `targetTriple`.\n    ///   - configurationStore: storage for configuration properties that this command operates on.\n    ///   - swiftSDKsDirectory: directory containing Swift SDK artifact bundles and their configuration.\n    ///   - observabilityScope: observability scope used for logging.\n    func run(\n        hostTriple: Triple,\n        targetTriple: Triple,\n        _ swiftSDK: SwiftSDK,\n        _ configurationStore: SwiftSDKConfigurationStore,\n        _ swiftSDKsDirectory: AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) throws\n}\n\nextension ConfigurationSubcommand {\n    func run(\n        hostTriple: Triple,\n        hostToolchain: UserToolchain,\n        _ swiftSDKsDirectory: AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) throws {\n        fputs(\"warning: `swift sdk configuration` command is deprecated and will be removed in a future version of SwiftPM. Use `swift sdk configure` instead.\\n\", stderr)\n\n        let bundleStore = SwiftSDKBundleStore(\n            swiftSDKsDirectory: swiftSDKsDirectory,\n            hostToolchainBinDir: hostToolchain.swiftCompilerPath.parentDirectory,\n            fileSystem: self.fileSystem,\n            observabilityScope: observabilityScope,\n            outputHandler: { print($0) }\n        )\n        let configurationStore = try SwiftSDKConfigurationStore(\n            hostTimeTriple: hostTriple,\n            swiftSDKBundleStore: bundleStore\n        )\n        let targetTriple = try Triple(self.targetTriple)\n\n        guard let swiftSDK = try configurationStore.readConfiguration(\n            sdkID: sdkID,\n            targetTriple: targetTriple\n        ) else {\n            throw SwiftSDKError.swiftSDKNotFound(\n                artifactID: sdkID,\n                hostTriple: hostTriple,\n                targetTriple: targetTriple\n            )\n        }\n\n        try run(\n            hostTriple: hostTriple,\n            targetTriple: targetTriple,\n            swiftSDK,\n            configurationStore,\n            swiftSDKsDirectory,\n            observabilityScope\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/Configuration/DeprecatedSwiftSDKConfigurationCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport PackageModel\n\npackage struct DeprecatedSwiftSDKConfigurationCommand: ParsableCommand {\n    package static let configuration = CommandConfiguration(\n        commandName: \"configuration\",\n        abstract: \"\"\"\n        Deprecated: use `swift sdk configure` instead.\n\n        Manages configuration options for installed Swift SDKs.\n        \"\"\",\n        subcommands: [\n            ResetConfiguration.self,\n            SetConfiguration.self,\n            ShowConfiguration.self,\n        ]\n    )\n\n    package init() {}\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/Configuration/ResetConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageModel\n\nstruct ResetConfiguration: ConfigurationSubcommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"reset\",\n        abstract: \"\"\"\n        Resets configuration properties currently applied to a given Swift SDK and target triple. If no specific \\\n        property is specified, all of them are reset for the Swift SDK.\n        \"\"\"\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var locations: LocationOptions\n\n    @Flag(help: \"Reset custom configuration for a path to a directory containing the SDK root.\")\n    var sdkRootPath = false\n\n    @Flag(help: \"Reset custom configuration for a path to a directory containing Swift resources for dynamic linking.\")\n    var swiftResourcesPath = false\n\n    @Flag(help: \"Reset custom configuration for a path to a directory containing Swift resources for static linking.\")\n    var swiftStaticResourcesPath = false\n\n    @Flag(help: \"Reset custom configuration for a path to a directory containing headers.\")\n    var includeSearchPath = false\n\n    @Flag(help: \"Reset custom configuration for a path to a directory containing libraries.\")\n    var librarySearchPath = false\n\n    @Flag(help: \"Reset custom configuration for a path to a toolset file.\")\n    var toolsetPath = false\n\n    @Argument(\n        help: \"\"\"\n        An identifier of an already installed Swift SDK. Use the `list` subcommand to see all available \\\n        identifiers.\n        \"\"\"\n    )\n    var sdkID: String\n\n    @Argument(help: \"A target triple of the Swift SDK specified by `sdk-id` identifier string.\")\n    var targetTriple: String\n\n    func run(\n        hostTriple: Triple,\n        targetTriple: Triple,\n        _ swiftSDK: SwiftSDK,\n        _ configurationStore: SwiftSDKConfigurationStore,\n        _ swiftSDKsDirectory: AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) throws {\n        var configuration = swiftSDK.pathsConfiguration\n        var shouldResetAll = true\n        var resetProperties = [String]()\n\n        if sdkRootPath {\n            configuration.sdkRootPath = nil\n            shouldResetAll = false\n            resetProperties.append(CodingKeys.sdkRootPath.stringValue)\n        }\n\n        if swiftResourcesPath {\n            configuration.swiftResourcesPath = nil\n            shouldResetAll = false\n            resetProperties.append(CodingKeys.swiftResourcesPath.stringValue)\n        }\n\n        if swiftStaticResourcesPath {\n            configuration.swiftResourcesPath = nil\n            shouldResetAll = false\n            resetProperties.append(CodingKeys.swiftStaticResourcesPath.stringValue)\n        }\n\n        if includeSearchPath {\n            configuration.includeSearchPaths = nil\n            shouldResetAll = false\n            resetProperties.append(CodingKeys.includeSearchPath.stringValue)\n        }\n\n        if librarySearchPath {\n            configuration.librarySearchPaths = nil\n            shouldResetAll = false\n            resetProperties.append(CodingKeys.librarySearchPath.stringValue)\n        }\n\n        if toolsetPath {\n            configuration.toolsetPaths = nil\n            shouldResetAll = false\n            resetProperties.append(CodingKeys.toolsetPath.stringValue)\n        }\n\n        if shouldResetAll {\n            if try !configurationStore.resetConfiguration(sdkID: sdkID, targetTriple: targetTriple) {\n                observabilityScope.emit(\n                    warning: \"No configuration for Swift SDK `\\(sdkID)`\"\n                )\n            } else {\n                observabilityScope.emit(\n                    info: \"\"\"\n                    All configuration properties of Swift SDK `\\(sdkID)` for target triple \\\n                    `\\(targetTriple)` were successfully reset.\n                    \"\"\"\n                )\n            }\n        } else {\n            var swiftSDK = swiftSDK\n            swiftSDK.pathsConfiguration = configuration\n            try configurationStore.updateConfiguration(sdkID: sdkID, swiftSDK: swiftSDK)\n\n            observabilityScope.emit(\n                info: \"\"\"\n                These properties of Swift SDK `\\(sdkID)` for target triple \\\n                `\\(targetTriple)` were successfully reset: \\(resetProperties.joined(separator: \", \")).\n                \"\"\"\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/Configuration/SetConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageModel\n\nstruct SetConfiguration: ConfigurationSubcommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"set\",\n        abstract: \"\"\"\n        Sets configuration options for installed Swift SDKs.\n        \"\"\"\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var locations: LocationOptions\n\n    @Option(help: \"A path to a directory containing the SDK root.\")\n    var sdkRootPath: String? = nil\n\n    @Option(help: \"A path to a directory containing Swift resources for dynamic linking.\")\n    var swiftResourcesPath: String? = nil\n\n    @Option(help: \"A path to a directory containing Swift resources for static linking.\")\n    var swiftStaticResourcesPath: String? = nil\n\n    @Option(\n        parsing: .singleValue,\n        help: \"\"\"\n        A path to a directory containing headers. Multiple paths can be specified by providing this option multiple \\\n        times to the command.\n        \"\"\"\n    )\n    var includeSearchPath: [String] = []\n\n    @Option(\n        parsing: .singleValue,\n        help: \"\"\"\n        \"A path to a directory containing libraries. Multiple paths can be specified by providing this option multiple \\\n        times to the command.\n        \"\"\"\n    )\n    var librarySearchPath: [String] = []\n\n    @Option(\n        parsing: .singleValue,\n        help: \"\"\"\n        \"A path to a toolset file. Multiple paths can be specified by providing this option multiple times to the command.\n        \"\"\"\n    )\n    var toolsetPath: [String] = []\n\n    @Argument(\n        help: \"\"\"\n        An identifier of an already installed Swift SDK. Use the `list` subcommand to see all available \\\n        identifiers.\n        \"\"\"\n    )\n    var sdkID: String\n\n    @Argument(help: \"The target triple of the Swift SDK to configure.\")\n    var targetTriple: String\n\n    func run(\n        hostTriple: Triple,\n        targetTriple: Triple,\n        _ swiftSDK: SwiftSDK,\n        _ configurationStore: SwiftSDKConfigurationStore,\n        _ swiftSDKsDirectory: AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) throws {\n        var configuration = swiftSDK.pathsConfiguration\n        var updatedProperties = [String]()\n\n        let currentWorkingDirectory: AbsolutePath? = fileSystem.currentWorkingDirectory\n\n        if let sdkRootPath {\n            configuration.sdkRootPath = try AbsolutePath(validating: sdkRootPath, relativeTo: currentWorkingDirectory)\n            updatedProperties.append(CodingKeys.sdkRootPath.stringValue)\n        }\n\n        if let swiftResourcesPath {\n            configuration.swiftResourcesPath =\n                try AbsolutePath(validating: swiftResourcesPath, relativeTo: currentWorkingDirectory)\n            updatedProperties.append(CodingKeys.swiftResourcesPath.stringValue)\n        }\n\n        if let swiftStaticResourcesPath {\n            configuration.swiftResourcesPath =\n                try AbsolutePath(validating: swiftStaticResourcesPath, relativeTo: currentWorkingDirectory)\n            updatedProperties.append(CodingKeys.swiftStaticResourcesPath.stringValue)\n        }\n\n        if !includeSearchPath.isEmpty {\n            configuration.includeSearchPaths =\n                try includeSearchPath.map { try AbsolutePath(validating: $0, relativeTo: currentWorkingDirectory) }\n            updatedProperties.append(CodingKeys.includeSearchPath.stringValue)\n        }\n\n        if !librarySearchPath.isEmpty {\n            configuration.librarySearchPaths =\n                try librarySearchPath.map { try AbsolutePath(validating: $0, relativeTo: currentWorkingDirectory) }\n            updatedProperties.append(CodingKeys.librarySearchPath.stringValue)\n        }\n\n        if !toolsetPath.isEmpty {\n            configuration.toolsetPaths =\n                try toolsetPath.map { try AbsolutePath(validating: $0, relativeTo: currentWorkingDirectory) }\n            updatedProperties.append(CodingKeys.toolsetPath.stringValue)\n        }\n\n        guard !updatedProperties.isEmpty else {\n            observabilityScope.emit(\n                error: \"\"\"\n                No properties of Swift SDK `\\(sdkID)` for target triple `\\(targetTriple)` were updated \\\n                since none were specified. Pass `--help` flag to see the list of all available properties.\n                \"\"\"\n            )\n            return\n        }\n\n        var swiftSDK = swiftSDK\n        swiftSDK.pathsConfiguration = configuration\n        try configurationStore.updateConfiguration(sdkID: sdkID, swiftSDK: swiftSDK)\n\n        observabilityScope.emit(\n            info: \"\"\"\n            These properties of Swift SDK `\\(sdkID)` for target triple \\\n            `\\(targetTriple)` were successfully updated: \\(updatedProperties.joined(separator: \", \")).\n            \"\"\"\n        )\n    }\n}\n\nextension AbsolutePath {\n    fileprivate init(validating string: String, relativeTo basePath: AbsolutePath?) throws {\n        if let basePath {\n            try self.init(validating: string, relativeTo: basePath)\n        } else {\n            try self.init(validating: string)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/Configuration/ShowConfiguration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageModel\n\nstruct ShowConfiguration: ConfigurationSubcommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"show\",\n        abstract: \"\"\"\n        Prints all configuration properties currently applied to a given Swift SDK and target triple.\n        \"\"\"\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var locations: LocationOptions\n\n    @Argument(\n        help: \"\"\"\n        An identifier of an already installed Swift SDK. Use the `list` subcommand to see all available \\\n        identifiers.\n        \"\"\"\n    )\n    var sdkID: String\n\n    @Argument(help: \"The target triple of the Swift SDK to configure.\")\n    var targetTriple: String\n\n    func run(\n        hostTriple: Triple,\n        targetTriple: Triple,\n        _ swiftSDK: SwiftSDK,\n        _ configurationStore: SwiftSDKConfigurationStore,\n        _ swiftSDKsDirectory: AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) throws {\n        print(swiftSDK.pathsConfiguration)\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/ConfigureSwiftSDK.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Dispatch\nimport PackageModel\n\nimport var TSCBasic.stdoutStream\n\nstruct ConfigureSwiftSDK: AsyncParsableCommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"configure\",\n        abstract: \"\"\"\n        Manages configuration options for installed Swift SDKs.\n        \"\"\"\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var locations: LocationOptions\n\n    @Option(help: \"A path to a directory containing the SDK root.\")\n    var sdkRootPath: String? = nil\n\n    @Option(help: \"A path to a directory containing Swift resources for dynamic linking.\")\n    var swiftResourcesPath: String? = nil\n\n    @Option(help: \"A path to a directory containing Swift resources for static linking.\")\n    var swiftStaticResourcesPath: String? = nil\n\n    @Option(\n        parsing: .singleValue,\n        help: \"\"\"\n        A path to a directory containing headers. Multiple paths can be specified by providing this option multiple \\\n        times to the command.\n        \"\"\"\n    )\n    var includeSearchPath: [String] = []\n\n    @Option(\n        parsing: .singleValue,\n        help: \"\"\"\n        A path to a directory containing libraries. Multiple paths can be specified by providing this option multiple \\\n        times to the command.\n        \"\"\"\n    )\n    var librarySearchPath: [String] = []\n\n    @Option(\n        parsing: .singleValue,\n        help: \"\"\"\n        A path to a toolset file. Multiple paths can be specified by providing this option multiple times to the command.\n        \"\"\"\n    )\n    var toolsetPath: [String] = []\n\n    @Flag(\n        name: .customLong(\"reset\"),\n        help: \"\"\"\n        Reset configuration properties currently applied to a given Swift SDK and target triple. If no specific \\\n        property is specified, all of them are reset for the Swift SDK.\n        \"\"\"\n    )\n    var shouldReset: Bool = false\n\n    @Flag(\n        name: .customLong(\"show-configuration\"),\n        help: \"\"\"\n        Print all configuration properties currently applied to a given Swift SDK and target triple.\n        \"\"\"\n    )\n    var shouldShowConfiguration: Bool = false\n\n    @Argument(\n        help: \"\"\"\n        An identifier of an already installed Swift SDK. Use the `list` subcommand to see all available \\\n        identifiers.\n        \"\"\"\n    )\n    var sdkID: String\n\n    @Argument(help: \"The target triple of the Swift SDK to configure.\")\n    var targetTriple: String?\n\n    /// The file system used by default by this command.\n    private var fileSystem: FileSystem { localFileSystem }\n\n    /// Parses Swift SDKs directory option if provided or uses the default path for Swift SDKs\n    /// on the file system. A new directory at this path is created if one doesn't exist already.\n    /// - Returns: existing or a newly created directory at the computed location.\n    private func getOrCreateSwiftSDKsDirectory() throws -> AbsolutePath {\n        var swiftSDKsDirectory = try fileSystem.getSharedSwiftSDKsDirectory(\n            explicitDirectory: locations.swiftSDKsDirectory\n        )\n\n        if !self.fileSystem.exists(swiftSDKsDirectory) {\n            swiftSDKsDirectory = try self.fileSystem.getOrCreateSwiftPMSwiftSDKsDirectory()\n        }\n\n        return swiftSDKsDirectory\n    }\n\n    func run() async throws {\n        let observabilityHandler = SwiftCommandObservabilityHandler(outputStream: stdoutStream, logLevel: .info)\n        let observabilitySystem = ObservabilitySystem(observabilityHandler)\n        let observabilityScope = observabilitySystem.topScope\n        let swiftSDKsDirectory = try self.getOrCreateSwiftSDKsDirectory()\n\n        let hostToolchain = try UserToolchain(swiftSDK: SwiftSDK.hostSwiftSDK())\n        let triple = try Triple.getVersionedHostTriple(usingSwiftCompiler: hostToolchain.swiftCompilerPath)\n\n        var commandError: Error? = nil\n        do {\n            let bundleStore = SwiftSDKBundleStore(\n                swiftSDKsDirectory: swiftSDKsDirectory,\n                hostToolchainBinDir: hostToolchain.swiftCompilerPath.parentDirectory,\n                fileSystem: self.fileSystem,\n                observabilityScope: observabilityScope,\n                outputHandler: { print($0) }\n            )\n            let configurationStore = try SwiftSDKConfigurationStore(\n                hostTimeTriple: triple,\n                swiftSDKBundleStore: bundleStore\n            )\n            let config = SwiftSDK.PathsConfiguration(\n                sdkRootPath: self.sdkRootPath,\n                swiftResourcesPath: self.swiftResourcesPath,\n                swiftStaticResourcesPath: self.swiftStaticResourcesPath,\n                includeSearchPaths: self.includeSearchPath,\n                librarySearchPaths: self.librarySearchPath,\n                toolsetPaths: self.toolsetPath\n            )\n            if try !configurationStore.configure(\n                sdkID: sdkID,\n                targetTriple: targetTriple,\n                showConfiguration: shouldShowConfiguration,\n                resetConfiguration: shouldReset,\n                config: config\n            ) {\n                throw ExitCode.failure\n            }\n        } catch {\n            commandError = error\n        }\n\n        // wait for all observability items to process\n        observabilityHandler.wait(timeout: .now() + 5)\n\n        if let commandError {\n            throw commandError\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/InstallSwiftSDK.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\n@_spi(SwiftPMInternal)\nimport Basics\nimport CoreCommands\nimport Foundation\nimport PackageModel\n\nimport var TSCBasic.stdoutStream\nimport class Workspace.Workspace\n\nstruct InstallSwiftSDK: SwiftSDKSubcommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"install\",\n        abstract: \"\"\"\n        Installs a given Swift SDK bundle to a location discoverable by SwiftPM. If the artifact bundle \\\n        is at a remote location, it's downloaded to local filesystem first.\n        \"\"\"\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var locations: LocationOptions\n\n    @Argument(help: \"A local filesystem path or a URL of a Swift SDK bundle to install.\")\n    var bundlePathOrURL: String\n\n    @Option(help: \"The checksum of the bundle generated with `swift package compute-checksum`.\")\n    var checksum: String? = nil\n\n    @Flag(\n        name: .customLong(\"color-diagnostics\"),\n        inversion: .prefixedNo,\n        help: \"\"\"\n            Determines whether color diagnostics appear when printing to a TTY.\n            By default, color diagnostics are enabled when connected to a TTY and disabled otherwise.\n            \"\"\"\n    )\n    public var colorDiagnostics: Bool = ProcessInfo.processInfo.environment[\"NO_COLOR\"] == nil\n\n    func run(\n        hostTriple: Triple,\n        hostToolchain: UserToolchain,\n        _ swiftSDKsDirectory: AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) async throws {\n        let cancellator = Cancellator(observabilityScope: observabilityScope)\n        cancellator.installSignalHandlers()\n\n        let store = SwiftSDKBundleStore(\n            swiftSDKsDirectory: swiftSDKsDirectory,\n            hostToolchainBinDir: hostToolchain.swiftCompilerPath.parentDirectory,\n            fileSystem: self.fileSystem,\n            observabilityScope: observabilityScope,\n            outputHandler: { print($0.description) },\n            downloadProgressAnimation: ProgressAnimation\n                .percent(\n                    stream: stdoutStream,\n                    verbose: false,\n                    header: \"Downloading\",\n                    isColorized: self.colorDiagnostics\n                )\n                .throttled(interval: .milliseconds(300))\n        )\n\n        try await store.install(\n            bundlePathOrURL: bundlePathOrURL,\n            checksum: self.checksum,\n            UniversalArchiver(self.fileSystem, cancellator),\n            HTTPClient(),\n            hasher: {\n                try Workspace.BinaryArtifactsManager.checksum(\n                    forBinaryArtifactAt: $0,\n                    fileSystem: self.fileSystem\n                )\n            }\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/ListSwiftSDKs.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageModel\nimport SPMBuildCore\n\npackage struct ListSwiftSDKs: SwiftSDKSubcommand {\n    package static let configuration = CommandConfiguration(\n        commandName: \"list\",\n        abstract:\n        \"\"\"\n        Print a list of IDs of available Swift SDKs available on the filesystem.\n        \"\"\"\n    )\n\n    @OptionGroup()\n    var locations: LocationOptions\n\n    package init() {}\n\n    func run(\n        hostTriple: Triple,\n        hostToolchain: UserToolchain,\n        _ swiftSDKsDirectory: AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) throws {\n        let store = SwiftSDKBundleStore(\n            swiftSDKsDirectory: swiftSDKsDirectory,\n            hostToolchainBinDir: hostToolchain.swiftCompilerPath.parentDirectory,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            outputHandler: { print($0.description) }\n        )\n        let validBundles = try store.allValidBundles\n\n        guard !validBundles.isEmpty else {\n            print(\"No Swift SDKs are currently installed.\")\n            return\n        }\n\n        for artifactID in validBundles.sortedArtifactIDs {\n            print(artifactID)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/README.md",
    "content": "# Swift SDKs Command\n\nThis module implements `swift sdk` command and its subcommands, which allow managing artifact\nbundles used as Swift SDKs, as specified in [SE-0387](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0387-cross-compilation-destinations.md).\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/RemoveSwiftSDK.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport PackageModel\nimport TSCBasic\n\npackage struct RemoveSwiftSDK: SwiftSDKSubcommand {\n    package static let configuration = CommandConfiguration(\n        commandName: \"remove\",\n        abstract: \"\"\"\n        Removes a previously installed Swift SDK bundle from the filesystem.\n        \"\"\"\n    )\n\n    @OptionGroup(visibility: .hidden)\n    var locations: LocationOptions\n\n    @Argument(help: \"Name of the Swift SDK bundle or ID of the Swift SDK to remove from the filesystem.\")\n    var sdkIDOrBundleName: String\n\n    public init() {}\n\n    func run(\n        hostTriple: Triple,\n        hostToolchain: UserToolchain,\n        _ swiftSDKsDirectory: Basics.AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) async throws {\n        let artifactBundleDirectory = swiftSDKsDirectory.appending(component: self.sdkIDOrBundleName)\n\n        let removedBundleDirectory: Basics.AbsolutePath\n        if fileSystem.exists(artifactBundleDirectory) {\n            try fileSystem.removeFileTree(artifactBundleDirectory)\n\n            removedBundleDirectory = artifactBundleDirectory\n        } else {\n            let bundleStore = SwiftSDKBundleStore(\n                swiftSDKsDirectory: swiftSDKsDirectory,\n                hostToolchainBinDir: hostToolchain.swiftCompilerPath.parentDirectory,\n                fileSystem: self.fileSystem,\n                observabilityScope: observabilityScope,\n                outputHandler: { print($0) }\n            )\n\n            let bundles = try bundleStore.allValidBundles\n\n            let matchingBundles = bundles.compactMap { bundle in\n                bundle.artifacts[sdkIDOrBundleName] != nil ? bundle : nil\n            }\n\n            guard !matchingBundles.isEmpty else {\n                throw StringError(\n                    \"\"\"\n                    Neither a Swift SDK bundle with name `\\(self.sdkIDOrBundleName)` nor an \\\n                    artifact with such ID are currently installed. Use `list` subcommand to see all available \\\n                    Swift SDKs.\n                    \"\"\"\n                )\n            }\n\n            guard matchingBundles.count == 1 else {\n                let namesOfBundles = matchingBundles.map { \"`\\($0.name)`\" }.joined(separator: \", \")\n\n                throw StringError(\n                    \"\"\"\n                    Multiple bundles contain Swift SDKs with ID \\(self.sdkIDOrBundleName). Names of these \\\n                    bundles are: \\(namesOfBundles). This will lead to issues when specifying such ID for \\\n                    building. Delete one of the bundles first by their full name to disambiguate.\n                    \"\"\"\n                )\n            }\n\n            let matchingBundle = matchingBundles[0]\n\n            // Don't leave an empty bundle and remove the whole thing if it has only a single artifact and that's also\n            // matching.\n            if matchingBundle.artifacts.count > 1 {\n                let otherArtifactIDs = matchingBundle.artifacts.keys\n                    .filter { $0 == self.sdkIDOrBundleName }\n                    .map { \"`\\($0)`\" }\n                    .joined(separator: \", \")\n\n                print(\n                    \"\"\"\n                    WARNING: the Swift SDK bundle containing artifact with ID \\(self.sdkIDOrBundleName) \\\n                    also contains other artifacts: \\(otherArtifactIDs).\n                    \"\"\"\n                )\n\n                print(\"Would you like to remove the whole bundle with all of its Swift SDKs? (Yes/No): \")\n                guard readLine(strippingNewline: true)?.lowercased() == \"yes\" else {\n                    print(\"Bundle not removed. Exiting...\")\n                    return\n                }\n            }\n\n            try fileSystem.removeFileTree(matchingBundle.path)\n            removedBundleDirectory = matchingBundle.path\n        }\n\n        print(\"Swift SDK bundle at path `\\(removedBundleDirectory)` was successfully removed from the file system.\")\n    }\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/SwiftSDKCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\n    \npackage struct SwiftSDKCommand: AsyncParsableCommand {\n    package static let configuration = CommandConfiguration(\n        commandName: \"sdk\",\n        _superCommandName: \"swift\",\n        abstract: \"Perform operations on Swift SDKs.\",\n        version: SwiftVersion.current.completeDisplayString,\n        subcommands: [\n            ConfigureSwiftSDK.self,\n            DeprecatedSwiftSDKConfigurationCommand.self,\n            InstallSwiftSDK.self,\n            ListSwiftSDKs.self,\n            RemoveSwiftSDK.self,\n        ],\n        helpNames: [.short, .long, .customLong(\"help\", withSingleDash: true)]\n    )\n\n    package init() {}\n}\n"
  },
  {
    "path": "Sources/SwiftSDKCommand/SwiftSDKSubcommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport CoreCommands\nimport Dispatch\nimport PackageModel\n\nimport var TSCBasic.stdoutStream\n\n/// A protocol for functions and properties common to all Swift SDK subcommands.\nprotocol SwiftSDKSubcommand: AsyncParsableCommand {\n    /// Common locations options provided by ArgumentParser.\n    var locations: LocationOptions { get }\n\n    /// Run a command operating on Swift SDKs, passing it required configuration values.\n    /// - Parameters:\n    ///   - hostTriple: triple of the machine this command is running on.\n    ///   - swiftSDKsDirectory: directory containing Swift SDK artifact bundles and their configuration.\n    ///   - observabilityScope: observability scope used for logging.\n    func run(\n        hostTriple: Triple,\n        hostToolchain: UserToolchain,\n        _ swiftSDKsDirectory: AbsolutePath,\n        _ observabilityScope: ObservabilityScope\n    ) async throws\n}\n\nextension SwiftSDKSubcommand {\n    /// The file system used by default by this command.\n    var fileSystem: FileSystem { localFileSystem }\n\n    /// Parses Swift SDKs directory option if provided or uses the default path for Swift SDKs\n    /// on the file system. A new directory at this path is created if one doesn't exist already.\n    /// - Returns: existing or a newly created directory at the computed location.\n    func getOrCreateSwiftSDKsDirectory() throws -> AbsolutePath {\n        var swiftSDKsDirectory = try fileSystem.getSharedSwiftSDKsDirectory(\n            explicitDirectory: locations.swiftSDKsDirectory\n        )\n\n        if !self.fileSystem.exists(swiftSDKsDirectory) {\n            swiftSDKsDirectory = try self.fileSystem.getOrCreateSwiftPMSwiftSDKsDirectory()\n        }\n\n        return swiftSDKsDirectory\n    }\n\n    public func run() async throws {\n        let observabilityHandler = SwiftCommandObservabilityHandler(outputStream: stdoutStream, logLevel: .info)\n        let observabilitySystem = ObservabilitySystem(observabilityHandler)\n        let observabilityScope = observabilitySystem.topScope\n        let swiftSDKsDirectory = try self.getOrCreateSwiftSDKsDirectory()\n\n        let environment = Environment.current\n        let hostToolchain = try UserToolchain(\n            swiftSDK: SwiftSDK.hostSwiftSDK(\n                environment: environment\n            ),\n            environment: environment\n        )\n        let triple = try Triple.getVersionedHostTriple(usingSwiftCompiler: hostToolchain.swiftCompilerPath)\n\n        var commandError: Error? = nil\n        do {\n            try await self.run(hostTriple: triple, hostToolchain: hostToolchain, swiftSDKsDirectory, observabilityScope)\n            if observabilityScope.errorsReported {\n                throw ExitCode.failure\n            }\n        } catch {\n            commandError = error\n        }\n\n        // wait for all observability items to process\n        observabilityHandler.wait(timeout: .now() + 5)\n\n        if let commandError {\n            throw commandError\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(Workspace\n  CheckoutState.swift\n  Diagnostics.swift\n  InitPackage.swift\n  LoadableResult.swift\n  ManagedArtifact.swift\n  ManagedDependency.swift\n  ManagedPrebuilt.swift\n  ManifestSigning/Base64URL.swift\n  ManifestSigning/CertificatePolicy.swift\n  ManifestSigning/embedded_resources.swift\n  ManifestSigning/ManifestSigning.swift\n  ManifestSigning/Signature.swift\n  ManifestSigning/Utilities.swift\n  ManifestSigning/X509Extensions.swift\n  PackageContainer/FileSystemPackageContainer.swift\n  PackageContainer/RegistryPackageContainer.swift\n  PackageContainer/SourceControlPackageContainer.swift\n  ResolvedFileWatcher.swift\n  ResolverPrecomputationProvider.swift\n  ToolsVersionSpecificationRewriter.swift\n  Workspace.swift\n  Workspace+BinaryArtifacts.swift\n  Workspace+Configuration.swift\n  Workspace+Delegation.swift\n  Workspace+Dependencies.swift\n  Workspace+Editing.swift\n  Workspace+Manifests.swift\n  Workspace+PackageContainer.swift\n  Workspace+Prebuilts.swift\n  Workspace+Registry.swift\n  Workspace+ResolvedPackages.swift\n  Workspace+Signing.swift\n  Workspace+SourceControl.swift\n  Workspace+State.swift\n  Workspace+Traits.swift)\ntarget_link_libraries(Workspace PUBLIC\n  TSCBasic\n  TSCUtility\n  Basics\n  SPMBuildCore\n  SwiftCollections::OrderedCollections\n  PackageFingerprint\n  PackageGraph\n  PackageLoading\n  PackageModel\n  PackageRegistry\n  PackageSigning\n  SourceControl)\ntarget_link_libraries(Workspace PUBLIC\n  $<$<NOT:$<PLATFORM_ID:Darwin>>:Foundation>)\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(Workspace PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS Workspace\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/Workspace/CheckoutState.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCUtility.Version\nimport struct SourceControl.Revision\n\n/// A checkout state represents the current state of a repository.\n///\n/// A state will always have a revision. It can also have a branch or a version but not both.\npublic enum CheckoutState: Equatable, Hashable {\n    case revision(_ revision: Revision)\n    case version(_ version: Version, revision: Revision)\n    case branch(name: String, revision: Revision)\n}\n\nextension CheckoutState: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .revision(let revision):\n            return revision.identifier\n        case .version(let version, _):\n            return version.description\n        case .branch(let branch, let revision):\n            return \"\\(branch) (\\(revision.identifier.prefix(7)))\"\n        }\n    }\n}\n\nextension CheckoutState: CustomDebugStringConvertible {\n    public var debugDescription: String {\n        switch self {\n        case .revision(let revision):\n            return revision.identifier\n        case .version(let version, let revision):\n            return \"\\(version.description) (\\(revision.identifier))\"\n        case .branch(let branch, let revision):\n            return \"\\(branch) (\\(revision.identifier))\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Diagnostics.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\n\nimport struct TSCBasic.FileSystemError\n\npublic struct ManifestParseDiagnostic: CustomStringConvertible {\n    public let errors: [String]\n    public let diagnosticFile: AbsolutePath?\n\n    public init(_ errors: [String], diagnosticFile: AbsolutePath?) {\n        self.errors = errors\n        self.diagnosticFile = diagnosticFile\n    }\n\n    public var description: String {\n        \"manifest parse error(s):\\n\" + self.errors.joined(separator: \"\\n\")\n    }\n}\n\npublic enum WorkspaceDiagnostics {\n    // MARK: - Errors\n\n    /// The diagnostic triggered when an operation fails because its completion\n    /// would lose the uncommitted changes in a repository.\n    public struct UncommittedChanges: Error, CustomStringConvertible {\n        /// The local path to the repository.\n        public let repositoryPath: AbsolutePath\n\n        public var description: String {\n            \"repository '\\(self.repositoryPath)' has uncommitted changes\"\n        }\n    }\n\n    /// The diagnostic triggered when an operation fails because its completion\n    /// would lose the unpushed changes in a repository.\n    public struct UnpushedChanges: Error, CustomStringConvertible {\n        /// The local path to the repository.\n        public let repositoryPath: AbsolutePath\n\n        public var description: String {\n            \"repository '\\(self.repositoryPath)' has unpushed changes\"\n        }\n    }\n\n    /// The diagnostic triggered when the unedit operation fails because the dependency\n    /// is not in edit mode.\n    public struct DependencyNotInEditMode: Error, CustomStringConvertible {\n        /// The name of the dependency being unedited.\n        public let dependencyName: String\n\n        public var description: String {\n            \"dependency '\\(self.dependencyName)' not in edit mode\"\n        }\n    }\n\n    /// The diagnostic triggered when the edit operation fails because the branch\n    /// to be created already exists.\n    public struct BranchAlreadyExists: Error, CustomStringConvertible {\n        /// The branch to create.\n        public let branch: String\n\n        public var description: String {\n            \"branch '\\(self.branch)' already exists\"\n        }\n    }\n\n    /// The diagnostic triggered when the edit operation fails because the specified\n    /// revision does not exist.\n    public struct RevisionDoesNotExist: Error, CustomStringConvertible {\n        /// The revision requested.\n        public let revision: String\n\n        public var description: String {\n            \"revision '\\(self.revision)' does not exist\"\n        }\n    }\n}\n\nextension Basics.Diagnostic {\n    static func dependencyNotFound(packageName: String) -> Self {\n        .warning(\"dependency '\\(packageName)' was not found\")\n    }\n\n    static func editBranchNotCheckedOut(packageName: String, branchName: String) -> Self {\n        .warning(\n            \"dependency '\\(packageName)' already exists at the edit destination; not checking-out branch '\\(branchName)'\"\n        )\n    }\n\n    static func editRevisionNotUsed(packageName: String, revisionIdentifier: String) -> Self {\n        .warning(\n            \"dependency '\\(packageName)' already exists at the edit destination; not using revision '\\(revisionIdentifier)'\"\n        )\n    }\n\n    static func editedDependencyMissing(packageName: String) -> Self {\n        .warning(\"dependency '\\(packageName)' was being edited but is missing; falling back to original checkout\")\n    }\n\n    static func checkedOutDependencyMissing(packageName: String) -> Self {\n        .warning(\"dependency '\\(packageName)' is missing; cloning again\")\n    }\n\n    static func registryDependencyMissing(packageName: String) -> Self {\n        .warning(\"dependency '\\(packageName)' is missing; downloading again\")\n    }\n\n    static func customDependencyMissing(packageName: String) -> Self {\n        .warning(\"dependency '\\(packageName)' is missing; retrieving again\")\n    }\n}\n\nstruct BinaryArtifactsManagerError: Error, CustomStringConvertible {\n    let description: String\n\n    private init(description: String) {\n        self.description = description\n    }\n\n    static func artifactInvalidArchive(artifactURL: URL, targetName: String) -> Self {\n        .init(\n            description: \"invalid archive returned from '\\(artifactURL.absoluteString)' which is required by binary target '\\(targetName)'\"\n        )\n    }\n\n    static func artifactChecksumChanged(targetName: String) -> Self {\n        .init(\n            description: \"artifact of binary target '\\(targetName)' has changed checksum; this is a potential security risk so the new artifact won't be downloaded\"\n        )\n    }\n\n    static func artifactInvalidChecksum(targetName: String, expectedChecksum: String, actualChecksum: String?) -> Self {\n        .init(\n            description: \"checksum of downloaded artifact of binary target '\\(targetName)' (\\(actualChecksum ?? \"none\")) does not match checksum specified by the manifest (\\(expectedChecksum))\"\n        )\n    }\n\n    static func artifactFailedDownload(artifactURL: URL, targetName: String, reason: String) -> Self {\n        .init(\n            description: \"failed downloading '\\(artifactURL.absoluteString)' which is required by binary target '\\(targetName)': \\(reason)\"\n        )\n    }\n\n    static func artifactFailedValidation(artifactURL: URL, targetName: String, reason: String) -> Self {\n        .init(\n            description: \"failed validating archive from '\\(artifactURL.absoluteString)' which is required by binary target '\\(targetName)': \\(reason)\"\n        )\n    }\n\n    static func remoteArtifactFailedExtraction(artifactURL: URL, targetName: String, reason: String) -> Self {\n        .init(\n            description: \"failed extracting '\\(artifactURL.absoluteString)' which is required by binary target '\\(targetName)': \\(reason)\"\n        )\n    }\n\n    static func localArtifactFailedExtraction(artifactPath: AbsolutePath, targetName: String, reason: String) -> Self {\n        .init(description: \"failed extracting '\\(artifactPath)' which is required by binary target '\\(targetName)': \\(reason)\")\n    }\n\n    static func remoteArtifactNotFound(artifactURL: URL, targetName: String) -> Self {\n        .init(\n            description: \"downloaded archive of binary target '\\(targetName)' from '\\(artifactURL.absoluteString)' does not contain a binary artifact.\"\n        )\n    }\n\n    static func localArchivedArtifactNotFound(archivePath: AbsolutePath, targetName: String) -> Self {\n        .init(description: \"local archive of binary target '\\(targetName)' at '\\(archivePath)' does not contain a binary artifact.\")\n    }\n\n    static func localArtifactNotFound(artifactPath: AbsolutePath, targetName: String) -> Self {\n        .init(description: \"local binary target '\\(targetName)' at '\\(artifactPath)' does not contain a binary artifact.\")\n    }\n\n    static func exhaustedAttempts(missing: [PackageReference]) -> Self {\n        let missing = missing.sorted(by: { $0.identity < $1.identity }).map {\n            switch $0.kind {\n            case .registry(let identity):\n                return \"'\\(identity.description)'\"\n            case .remoteSourceControl(let url):\n                return \"'\\($0.identity)' from \\(url)\"\n            case .localSourceControl(let path), .fileSystem(let path), .root(let path):\n                return \"'\\($0.identity)' at \\(path)\"\n            }\n        }\n        return .init(\n            description: \"exhausted attempts to resolve the dependencies graph, with the following dependencies unresolved:\\n* \\(missing.joined(separator: \"\\n* \"))\"\n        )\n    }\n}\n\nextension FileSystemError {\n    public var description: String {\n        guard let path else {\n            switch self.kind {\n            case .invalidAccess:\n                return \"invalid access\"\n            case .ioError(let code):\n                return \"encountered I/O error (code: \\(code))\"\n            case .isDirectory:\n                return \"is a directory\"\n            case .noEntry:\n                return \"doesn't exist in file system\"\n            case .notDirectory:\n                return \"is not a directory\"\n            case .unsupported:\n                return \"unsupported operation\"\n            case .unknownOSError:\n                return \"unknown system error\"\n            case .alreadyExistsAtDestination:\n                return \"already exists in file system\"\n            case .couldNotChangeDirectory:\n                return \"could not change directory\"\n            case .mismatchedByteCount(expected: let expected, actual: let actual):\n                return \"mismatched byte count, expected \\(expected), got \\(actual)\"\n            }\n        }\n\n        switch self.kind {\n        case .invalidAccess:\n            return \"invalid access to \\(path)\"\n        case .ioError(let code):\n            return \"encountered an I/O error (code: \\(code)) while reading \\(path)\"\n        case .isDirectory:\n            return \"\\(path) is a directory\"\n        case .noEntry:\n            return \"\\(path) doesn't exist in file system\"\n        case .notDirectory:\n            return \"\\(path) is not a directory\"\n        case .unsupported:\n            return \"unsupported operation on \\(path)\"\n        case .unknownOSError:\n            return \"unknown system error while operating on \\(path)\"\n        case .alreadyExistsAtDestination:\n            return \"\\(path) already exists in file system\"\n        case .couldNotChangeDirectory:\n            return \"could not change directory to \\(path)\"\n        case .mismatchedByteCount(expected: let expected, actual: let actual):\n            return \"mismatched byte count, expected \\(expected), got \\(actual)\"\n        }\n    }\n}\n\nextension FileSystemError: @retroactive CustomStringConvertible {}\n"
  },
  {
    "path": "Sources/Workspace/InitPackage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport SPMBuildCore\nimport TSCUtility\n\nimport protocol TSCBasic.OutputByteStream\n\n/// Create an initial template package.\npublic final class InitPackage {\n    /// The tool version to be used for new packages.\n    public static let newPackageToolsVersion = ToolsVersion.current\n\n    /// Options for the template package.\n    public struct InitPackageOptions {\n        /// The type of package to create.\n        public var packageType: PackageType\n\n        /// The set of supported testing libraries to include in the package.\n        public var supportedTestingLibraries: Set<TestingLibrary>\n\n        /// The list of platforms in the manifest.\n        ///\n        /// Note: This should only contain Apple platforms right now.\n        public var platforms: [SupportedPlatform]\n\n        /// The swiftLanguageModes to include\n        public var swiftLanguageModes: [SwiftLanguageVersion]\n\n        public init(\n            packageType: PackageType,\n            supportedTestingLibraries: Set<TestingLibrary>,\n            platforms: [SupportedPlatform] = [],\n            swiftLanguageModes: [SwiftLanguageVersion] = [SwiftLanguageVersion.v6]\n        ) {\n            self.packageType = packageType\n            self.supportedTestingLibraries = supportedTestingLibraries\n            self.platforms = platforms\n            self.swiftLanguageModes = swiftLanguageModes\n        }\n    }\n\n    /// Represents a package type for the purposes of initialization.\n    public enum PackageType: String, CustomStringConvertible {\n        case empty = \"empty\"\n        case library = \"library\"\n        case executable = \"executable\"\n        case tool = \"tool\"\n        case buildToolPlugin = \"build-tool-plugin\"\n        case commandPlugin = \"command-plugin\"\n        case macro = \"macro\"\n\n        public var description: String {\n            return rawValue\n        }\n    }\n\n    /// A block that will be called to report progress during package creation\n    public var progressReporter: ((String) -> Void)?\n\n    /// The file system to use\n    let fileSystem: FileSystem\n\n    /// Where to create the new package\n    let destinationPath: AbsolutePath\n\n    /// The type of package to create.\n    var packageType: PackageType { options.packageType }\n\n    /// The options for package to create.\n    let options: InitPackageOptions\n\n    /// Configuration from the used toolchain.\n    let installedSwiftPMConfiguration: InstalledSwiftPMConfiguration\n\n    /// The name of the package to create.\n    let pkgname: String\n\n    /// The name of the target to create.\n    var moduleName: String\n\n    /// The name of the type to create (within the package).\n    var typeName: String {\n        return moduleName\n    }\n\n    /// Create an instance that can create a package with given arguments.\n    public convenience init(\n        name: String,\n        packageType: PackageType,\n        supportedTestingLibraries: Set<TestingLibrary>,\n        destinationPath: AbsolutePath,\n        installedSwiftPMConfiguration: InstalledSwiftPMConfiguration,\n        fileSystem: FileSystem\n    ) throws {\n        try self.init(\n            name: name,\n            options: InitPackageOptions(packageType: packageType, supportedTestingLibraries: supportedTestingLibraries),\n            destinationPath: destinationPath,\n            installedSwiftPMConfiguration: installedSwiftPMConfiguration,\n            fileSystem: fileSystem\n        )\n    }\n\n    /// Create an instance that can create a package with given arguments.\n    public init(\n        name: String,\n        options: InitPackageOptions,\n        destinationPath: AbsolutePath,\n        installedSwiftPMConfiguration: InstalledSwiftPMConfiguration,\n        fileSystem: FileSystem\n    ) throws {\n        if options.packageType == .macro && options.supportedTestingLibraries.contains(.swiftTesting) {\n            // FIXME: https://github.com/swiftlang/swift-syntax/issues/2400\n            throw InitError.unsupportedTestingLibraryForPackageType(.swiftTesting, .macro)\n        }\n\n        self.options = options\n        self.pkgname = name\n        var mangledName = name.spm_mangledToC99ExtendedIdentifier()\n        // Single underscore produces targets that wont compile, so use double underscore instead.\n        if mangledName == \"_\" {\n            mangledName = \"__\"\n        }\n        self.moduleName = mangledName\n        self.destinationPath = destinationPath\n        self.installedSwiftPMConfiguration = installedSwiftPMConfiguration\n        self.fileSystem = fileSystem\n    }\n\n    /// Actually creates the new package at the destinationPath\n    public func writePackageStructure() throws {\n        progressReporter?(\"Creating \\(packageType) package: \\(pkgname)\")\n\n        // FIXME: We should form everything we want to write, then validate that\n        // none of it exists, and then act.\n        try writeManifestFile()\n        try writeGitIgnore()\n        try writePlugins()\n        try writeSources()\n        try writeTests()\n    }\n\n    private func writePackageFile(_ path: AbsolutePath, body: (OutputByteStream) -> Void) throws {\n        progressReporter?(\"Creating \\(path.relative(to: destinationPath))\")\n        try self.fileSystem.writeFileContents(path, body: body)\n    }\n\n    private func writeManifestFile() throws {\n        let manifest = destinationPath.appending(component: Manifest.filename)\n        guard self.fileSystem.exists(manifest) == false else {\n            throw InitError.manifestAlreadyExists\n        }\n\n        try writePackageFile(manifest) { stream in\n            stream.send(\n                \"\"\"\n                // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n                import PackageDescription\n\n                \"\"\"\n            )\n\n            if packageType == .macro {\n                stream.send(\n                  \"\"\"\n                  import CompilerPluginSupport\n\n                  \"\"\"\n                )\n            }\n\n            stream.send(\n                \"\"\"\n\n                let package = Package(\n\n                \"\"\"\n            )\n\n            var pkgParams = [String]()\n            pkgParams.append(\"\"\"\n                    name: \"\\(pkgname)\"\n                \"\"\")\n\n            var platforms = options.platforms\n\n            // Macros require macOS 10.15, iOS 13, etc.\n            if packageType == .macro {\n                func addIfMissing(_ newPlatform: SupportedPlatform) {\n                  if platforms.contains(where: { platform in\n                      platform.platform == newPlatform.platform\n                  }) {\n                      return\n                  }\n\n                  platforms.append(newPlatform)\n                }\n\n              addIfMissing(.init(platform: .macOS, version: .init(\"10.15\")))\n              addIfMissing(.init(platform: .iOS, version: .init(\"13\")))\n              addIfMissing(.init(platform: .tvOS, version: .init(\"13\")))\n              addIfMissing(.init(platform: .watchOS, version: .init(\"6\")))\n              addIfMissing(.init(platform: .macCatalyst, version: .init(\"13\")))\n            }\n\n            var platformsParams = [String]()\n            for supportedPlatform in platforms {\n                let version = supportedPlatform.version\n                let platform = supportedPlatform.platform\n\n                var param = \".\\(platform.manifestName)(\"\n                if supportedPlatform.isManifestAPIAvailable {\n                    if version.minor > 0 {\n                        param += \".v\\(version.major)_\\(version.minor)\"\n                    } else {\n                        param += \".v\\(version.major)\"\n                    }\n                } else {\n                    param += \"\\\"\\(version.versionString)\\\"\"\n                }\n                param += \")\"\n\n                platformsParams.append(param)\n            }\n\n            // Package platforms\n            if !platforms.isEmpty {\n                pkgParams.append(\"\"\"\n                        platforms: [\\(platformsParams.joined(separator: \", \"))]\n                    \"\"\")\n            }\n\n            // Package products\n            if packageType == .library {\n                pkgParams.append(\"\"\"\n                    products: [\n                        // Products define the executables and libraries a package produces, making them visible to other packages.\n                        .library(\n                            name: \"\\(pkgname)\",\n                            targets: [\"\\(moduleName)\"]\n                        ),\n                    ]\n                \"\"\")\n            } else if packageType == .buildToolPlugin || packageType == .commandPlugin {\n                pkgParams.append(\"\"\"\n                    products: [\n                        // Products can be used to vend plugins, making them visible to other packages.\n                        .plugin(\n                            name: \"\\(pkgname)\",\n                            targets: [\"\\(moduleName)\"]\n                        ),\n                    ]\n                \"\"\")\n            } else if packageType == .macro {\n                pkgParams.append(\"\"\"\n                    products: [\n                        // Products define the executables and libraries a package produces, making them visible to other packages.\n                        .library(\n                            name: \"\\(pkgname)\",\n                            targets: [\"\\(moduleName)\"]\n                        ),\n                        .executable(\n                            name: \"\\(pkgname)Client\",\n                            targets: [\"\\(moduleName)Client\"]\n                        ),\n                    ]\n                \"\"\")\n\n            }\n\n            // Package dependencies\n            var dependencies = [String]()\n            if packageType == .tool {\n                dependencies.append(#\".package(url: \"https://github.com/apple/swift-argument-parser.git\", from: \"1.2.0\")\"#)\n            } else if packageType == .macro {\n                dependencies.append(#\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", from: \"\\#(self.installedSwiftPMConfiguration.swiftSyntaxVersionForMacroTemplate.description)\")\"#)\n            }\n            if !dependencies.isEmpty {\n                let dependencies = dependencies.map { dependency in\n                    \"        \\(dependency),\"\n                }.joined(separator: \"\\n\")\n                pkgParams.append(\"\"\"\n                    dependencies: [\n                \\(dependencies)\n                    ]\n                \"\"\")\n            }\n\n            // Package targets\n            if packageType != .empty {\n                var param = \"\"\n\n                param += \"\"\"\n                    targets: [\n                        // Targets are the basic building blocks of a package, defining a module or a test suite.\n                        // Targets can depend on other targets in this package and products from dependencies.\n\n                \"\"\"\n                if packageType == .executable {\n                    let testTarget: String\n                    if !options.supportedTestingLibraries.isEmpty {\n                        testTarget = \"\"\"\n                                .testTarget(\n                                    name: \"\\(moduleName)Tests\",\n                                    dependencies: [\"\\(moduleName)\"],\n                                    swiftSettings: [\n                                        .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                    ],\n                                ),\n                        \"\"\"\n                    } else {\n                        testTarget = \"\"\n                    }\n                    param += \"\"\"\n                            .executableTarget(\n                                name: \"\\(moduleName)\",\n                                swiftSettings: [\n                                    .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                ],\n                            ),\n                    \\(testTarget)\n                        ]\n                    \"\"\"\n                } else if packageType == .tool {\n                    let testTarget: String\n                    if !options.supportedTestingLibraries.isEmpty {\n                        testTarget = \"\"\"\n                                .testTarget(\n                                    name: \"\\(moduleName)Tests\",\n                                    dependencies: [\"\\(moduleName)\"],\n                                    swiftSettings: [\n                                        .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                    ],\n                                ),\n                        \"\"\"\n                    } else {\n                        testTarget = \"\"\n                    }\n                    param += \"\"\"\n                            .executableTarget(\n                                name: \"\\(moduleName)\",\n                                dependencies: [\n                                    .product(name: \"ArgumentParser\", package: \"swift-argument-parser\"),\n                                ],\n                                swiftSettings: [\n                                    .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                ],\n                            ),\n                    \\(testTarget)\n                        ]\n                    \"\"\"\n                } else if packageType == .buildToolPlugin {\n                    param += \"\"\"\n                            .plugin(\n                                name: \"\\(moduleName)\",\n                                capability: .buildTool()\n                            ),\n                        ]\n                    \"\"\"\n                } else if packageType == .commandPlugin {\n                    param += \"\"\"\n                            .plugin(\n                                name: \"\\(moduleName)\",\n                                capability: .command(intent: .custom(\n                                    verb: \"\\(typeName)\",\n                                    description: \"prints hello world\"\n                                ))\n                            ),\n                        ]\n                    \"\"\"\n                } else if packageType == .macro {\n                    let testTarget: String\n                    if options.supportedTestingLibraries.contains(.swiftTesting) {\n                        testTarget = \"\"\"\n\n                                // A test target used to develop the macro implementation.\n                                .testTarget(\n                                    name: \"\\(moduleName)Tests\",\n                                    dependencies: [\n                                        \"\\(moduleName)Macros\",\n                                        .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n                                        .product(name: \"Testing\", package: \"swift-testing\"),\n                                    ]\n                                ),\n                        \"\"\"\n                    } else if options.supportedTestingLibraries.contains(.xctest) {\n                        testTarget = \"\"\"\n\n                                // A test target used to develop the macro implementation.\n                                .testTarget(\n                                    name: \"\\(moduleName)Tests\",\n                                    dependencies: [\n                                        \"\\(moduleName)Macros\",\n                                        .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n                                    ],\n                                    swiftSettings: [\n                                        .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                    ],\n                                ),\n                        \"\"\"\n                    } else {\n                        testTarget = \"\"\n                    }\n                    param += \"\"\"\n                            // Macro implementation that performs the source transformation of a macro.\n                            .macro(\n                                name: \"\\(moduleName)Macros\",\n                                dependencies: [\n                                    .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                    .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\")\n                                ]\n                            ),\n\n                            // Library that exposes a macro as part of its API, which is used in client programs.\n                            .target(\n                                name: \"\\(moduleName)\", \n                                dependencies: [\"\\(moduleName)Macros\"],\n                                swiftSettings: [\n                                    .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                ],\n                            ),\n\n                            // A client of the library, which is able to use the macro in its own code.\n                            .executableTarget(\n                                name: \"\\(moduleName)Client\", \n                                dependencies: [\"\\(moduleName)\"],\n                                swiftSettings: [\n                                    .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                ],\n                            ),\n                    \\(testTarget)\n                        ]\n                    \"\"\"\n                } else {\n                    let testTarget: String\n                    if !options.supportedTestingLibraries.isEmpty {\n                        testTarget = \"\"\"\n                                .testTarget(\n                                    name: \"\\(moduleName)Tests\",\n                                    dependencies: [\"\\(moduleName)\"],\n                                    swiftSettings: [\n                                        .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                    ],\n                                ),\n                        \"\"\"\n                    } else {\n                        testTarget = \"\"\n                    }\n\n                    param += \"\"\"\n                            .target(\n                                name: \"\\(moduleName)\",\n                                swiftSettings: [\n                                    .enableUpcomingFeature(\"ApproachableConcurrency\"),\n                                ],\n                            ),\n                    \\(testTarget)\n                        ]\n                    \"\"\"\n                }\n\n                pkgParams.append(param)\n            }\n\n            if (!options.swiftLanguageModes.isEmpty) {\n                pkgParams.append(\"\"\"\n                    swiftLanguageModes: [\\(options.swiftLanguageModes.map { \".v\\($0)\" }.joined(separator: \", \"))]\n                \"\"\")\n            }\n\n            stream.send(\"\\(pkgParams.joined(separator: \",\\n\"))\\n)\\n\")\n        }\n\n        // Create a tools version with current version but with patch set to zero.\n        // We do this to avoid adding unnecessary constraints to patch versions, if\n        // the package really needs it, they should add it manually.\n        let version = InitPackage.newPackageToolsVersion.zeroedPatch\n\n        // Write the current tools version.\n        try ToolsVersionSpecificationWriter.rewriteSpecification(\n            manifestDirectory: manifest.parentDirectory,\n            toolsVersion: version,\n            fileSystem: self.fileSystem\n        )\n    }\n\n    private func writeGitIgnore() throws {\n        guard packageType != .empty else {\n            return\n        }\n        let gitignore = destinationPath.appending(\".gitignore\")\n        guard self.fileSystem.exists(gitignore) == false else {\n            return\n        }\n\n        try writePackageFile(gitignore) { stream in\n            stream.send(\n                \"\"\"\n                .DS_Store\n                /.build\n                /Packages\n                xcuserdata/\n                DerivedData/\n                .swiftpm/configuration/registries.json\n                .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata\n                .netrc\n\n                \"\"\"\n            )\n        }\n    }\n\n    private func writePlugins() throws {\n        switch packageType {\n        case .buildToolPlugin, .commandPlugin:\n            let plugins = destinationPath.appending(component: \"Plugins\")\n            guard self.fileSystem.exists(plugins) == false else {\n                return\n            }\n            progressReporter?(\"Creating \\(plugins.relative(to: destinationPath))/\")\n            try makeDirectories(plugins)\n\n            let moduleDir = plugins\n            try makeDirectories(moduleDir)\n\n            let sourceFileName = \"\\(pkgname).swift\"\n            let sourceFile = try AbsolutePath(validating: sourceFileName, relativeTo: moduleDir)\n\n            var content = \"\"\"\n                import PackagePlugin\n                import struct Foundation.URL\n\n                @main\n\n                \"\"\"\n            if packageType == .buildToolPlugin {\n                content += \"\"\"\n                struct \\(typeName): BuildToolPlugin {\n                    /// Entry point for creating build commands for targets in Swift packages.\n                    func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n                        // This plugin only runs for package targets that can have source files.\n                        guard let sourceFiles = target.sourceModule?.sourceFiles else { return [] }\n\n                        // Find the code generator tool to run (replace this with the actual one).\n                        let generatorTool = try context.tool(named: \"my-code-generator\")\n\n                        // Construct a build command for each source file with a particular suffix.\n                        return sourceFiles.map(\\\\.url).compactMap {\n                            createBuildCommand(for: $0, in: context.pluginWorkDirectoryURL, with: generatorTool.url)\n                        }\n                    }\n                }\n\n                #if canImport(XcodeProjectPlugin)\n                import XcodeProjectPlugin\n\n                extension \\(typeName): XcodeBuildToolPlugin {\n                    // Entry point for creating build commands for targets in Xcode projects.\n                    func createBuildCommands(context: XcodePluginContext, target: XcodeTarget) throws -> [Command] {\n                        // Find the code generator tool to run (replace this with the actual one).\n                        let generatorTool = try context.tool(named: \"my-code-generator\")\n\n                        // Construct a build command for each source file with a particular suffix.\n                        return target.inputFiles.map(\\\\.url).compactMap {\n                            createBuildCommand(for: $0, in: context.pluginWorkDirectoryURL, with: generatorTool.url)\n                        }\n                    }\n                }\n\n                #endif\n\n                extension \\(typeName) {\n                    /// Shared function that returns a configured build command if the input files is one that should be processed.\n                    func createBuildCommand(for inputPath: URL, in outputDirectoryPath: URL, with generatorToolPath: URL) -> Command? {\n                        // Skip any file that doesn't have the extension we're looking for (replace this with the actual one).\n                        guard inputPath.pathExtension == \"my-input-suffix\" else { return .none }\n\n                        // Return a command that will run during the build to generate the output file.\n                        let inputName = inputPath.lastPathComponent\n                        let outputName = inputPath.deletingPathExtension().lastPathComponent + \".swift\"\n                        let outputPath = outputDirectoryPath.appendingPathComponent(outputName)\n                        return .buildCommand(\n                            displayName: \"Generating \\\\(outputName) from \\\\(inputName)\",\n                            executable: generatorToolPath,\n                            arguments: [\"\\\\(inputPath)\", \"-o\", \"\\\\(outputPath)\"],\n                            inputFiles: [inputPath],\n                            outputFiles: [outputPath]\n                        )\n                    }\n                }\n\n                \"\"\"\n            }\n            else {\n                content += \"\"\"\n                struct \\(typeName): CommandPlugin {\n                    // Entry point for command plugins applied to Swift Packages.\n                    func performCommand(context: PluginContext, arguments: [String]) async throws {\n                        print(\"Hello, World!\")\n                    }\n                }\n\n                #if canImport(XcodeProjectPlugin)\n                import XcodeProjectPlugin\n\n                extension \\(typeName): XcodeCommandPlugin {\n                    // Entry point for command plugins applied to Xcode projects.\n                    func performCommand(context: XcodePluginContext, arguments: [String]) throws {\n                        print(\"Hello, World!\")\n                    }\n                }\n\n                #endif\n\n                \"\"\"\n            }\n\n            try writePackageFile(sourceFile) { stream in\n                stream.write(content)\n            }\n\n        case .empty, .library, .executable, .tool, .macro:\n            break\n        }\n    }\n\n    private func writeSources() throws {\n        if packageType == .empty || packageType == .buildToolPlugin || packageType == .commandPlugin {\n            return\n        }\n\n        let sources = destinationPath.appending(\"Sources\")\n        guard self.fileSystem.exists(sources) == false else {\n            return\n        }\n        progressReporter?(\"Creating \\(sources.relative(to: destinationPath))\")\n        try makeDirectories(sources)\n\n        let moduleDir = sources.appending(\"\\(moduleName)\")\n        try makeDirectories(moduleDir)\n\n        // If we're creating an executable we can't have both a @main declaration and a main.swift file.\n        // Handle the edge case of a user creating a project called \"main\" by give the generated file a different name.\n        let sourceFileName = ((packageType == .executable || packageType == .tool) && typeName == \"main\") ? \"MainEntrypoint.swift\" : \"\\(typeName).swift\"\n        let sourceFile = try AbsolutePath(validating: sourceFileName, relativeTo: moduleDir)\n\n        let content: String\n        switch packageType {\n        case .library:\n            content = \"\"\"\n                // The Swift Programming Language\n                // https://docs.swift.org/swift-book\n\n                \"\"\"\n        case .executable:\n            content = \"\"\"\n                // The Swift Programming Language\n                // https://docs.swift.org/swift-book\n\n                @main\n                struct \\(typeName) {\n                    static func main() {\n                        print(\"Hello, world!\")\n                    }\n                }\n\n                \"\"\"\n        case .tool:\n            content = \"\"\"\n            // The Swift Programming Language\n            // https://docs.swift.org/swift-book\n            //\n            // Swift Argument Parser\n            // https://swiftpackageindex.com/apple/swift-argument-parser/documentation\n\n            import ArgumentParser\n\n            @main\n            struct \\(typeName): ParsableCommand {\n                mutating func run() throws {\n                    print(\"Hello, world!\")\n                }\n            }\n\n            \"\"\"\n        case .macro:\n            content = \"\"\"\n            // The Swift Programming Language\n            // https://docs.swift.org/swift-book\n\n            /// A macro that produces both a value and a string containing the\n            /// source code that generated the value. For example,\n            ///\n            ///     #stringify(x + y)\n            ///\n            /// produces a tuple `(x + y, \"x + y\")`.\n            @freestanding(expression)\n            public macro stringify<T>(_ value: T) -> (T, String) = #externalMacro(module: \"\\(moduleName)Macros\", type: \"StringifyMacro\")\n\n            \"\"\"\n\n        case .empty, .buildToolPlugin, .commandPlugin:\n            throw InternalError(\"invalid packageType \\(packageType)\")\n        }\n\n        try writePackageFile(sourceFile) { stream in\n            stream.write(content)\n        }\n\n        if packageType == .macro {\n          try writeMacroPluginSources(sources.appending(\"\\(moduleName)Macros\"))\n          try writeMacroClientSources(sources.appending(\"\\(moduleName)Client\"))\n        }\n    }\n\n    private func writeTests() throws {\n        if options.supportedTestingLibraries.isEmpty {\n            // If the developer disabled all testing libraries, do not bother to\n            // emit any test content.\n            return\n        }\n\n        switch packageType {\n        case .empty, .buildToolPlugin, .commandPlugin:\n            return\n        case .library, .executable, .tool, .macro:\n            break\n        }\n\n        let tests = destinationPath.appending(\"Tests\")\n        guard self.fileSystem.exists(tests) == false else {\n            return\n        }\n        progressReporter?(\"Creating \\(tests.relative(to: destinationPath))/\")\n        try makeDirectories(tests)\n        try writeTestFileStubs(testsPath: tests)\n    }\n\n    private func writeLibraryTestsFile(_ path: AbsolutePath) throws {\n        var content = \"\"\n\n        // XCTest is only added if it was explicitly asked for, so add tests\n        // for it *and* Testing if it is enabled (or just XCTest if Testing\n        // is explicitly disabled).\n\n        if options.supportedTestingLibraries.contains(.swiftTesting) {\n            content += \"import Testing\\n\"\n        }\n        if options.supportedTestingLibraries.contains(.xctest) {\n            content += \"import XCTest\\n\"\n        }\n        content += \"@testable import \\(moduleName)\\n\"\n\n        if options.supportedTestingLibraries.contains(.swiftTesting) {\n            content += \"\"\"\n\n                @Test func example() async throws {\n                    // Write your test here and use APIs like `#expect(...)` to check expected conditions.\n                    // Swift Testing Documentation\n                    // https://swiftpackageindex.com/swiftlang/swift-testing/documentation\n                }\n\n                \"\"\"\n        }\n\n        if options.supportedTestingLibraries.contains(.xctest) {\n            content += \"\"\"\n\n                final class \\(moduleName)Tests: XCTestCase {\n                    func testExample() throws {\n                        // XCTest Documentation\n                        // https://developer.apple.com/documentation/xctest\n\n                        // Defining Test Cases and Test Methods\n                        // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods\n                    }\n                }\n\n                \"\"\"\n        }\n\n        try writePackageFile(path) { stream in\n            stream.send(content)\n        }\n    }\n\n    private func writeMacroTestsFile(_ path: AbsolutePath) throws {\n        var content = \"\"\n\n        content += ##\"\"\"\n            import SwiftSyntax\n            import SwiftSyntaxBuilder\n            import SwiftSyntaxMacros\n            import SwiftSyntaxMacrosTestSupport\n\n            \"\"\"##\n\n        if options.supportedTestingLibraries.contains(.swiftTesting) {\n            content += \"import Testing\\n\"\n        }\n        if options.supportedTestingLibraries.contains(.xctest) {\n            content += \"import XCTest\\n\"\n        }\n\n        content += ##\"\"\"\n\n            // Macro implementations build for the host, so the corresponding module is not available when cross-compiling. Cross-compiled tests may still make use of the macro itself in end-to-end tests.\n            #if canImport(\\##(moduleName)Macros)\n            import \\##(moduleName)Macros\n\n            let testMacros: [String: Macro.Type] = [\n                \"stringify\": StringifyMacro.self,\n            ]\n            #endif\n\n\n            \"\"\"##\n\n        // XCTest is only added if it was explicitly asked for, so add tests\n        // for it *and* Testing if it is enabled.\n\n        if options.supportedTestingLibraries.contains(.swiftTesting) {\n            // FIXME: https://github.com/swiftlang/swift-syntax/issues/2400\n        }\n\n        if options.supportedTestingLibraries.contains(.xctest) {\n            content += ##\"\"\"\n                final class \\##(moduleName)Tests: XCTestCase {\n                    func testMacro() throws {\n                        #if canImport(\\##(moduleName)Macros)\n                        assertMacroExpansion(\n                            \"\"\"\n                            #stringify(a + b)\n                            \"\"\",\n                            expandedSource: \"\"\"\n                            (a + b, \"a + b\")\n                            \"\"\",\n                            macros: testMacros\n                        )\n                        #else\n                        throw XCTSkip(\"macros are only supported when running tests for the host platform\")\n                        #endif\n                    }\n\n                    func testMacroWithStringLiteral() throws {\n                        #if canImport(\\##(moduleName)Macros)\n                        assertMacroExpansion(\n                            #\"\"\"\n                            #stringify(\"Hello, \\(name)\")\n                            \"\"\"#,\n                            expandedSource: #\"\"\"\n                            (\"Hello, \\(name)\", #\"\"Hello, \\(name)\"\"#)\n                            \"\"\"#,\n                            macros: testMacros\n                        )\n                        #else\n                        throw XCTSkip(\"macros are only supported when running tests for the host platform\")\n                        #endif\n                    }\n                }\n\n                \"\"\"##\n        }\n\n        try writePackageFile(path) { stream in\n            stream.send(content)\n        }\n    }\n\n    private func writeMacroPluginSources(_ path: AbsolutePath) throws {\n        try makeDirectories(path)\n\n        try writePackageFile(path.appending(\"\\(moduleName)Macro.swift\")) { stream in\n            stream.send(\n                ##\"\"\"\n                import SwiftCompilerPlugin\n                import SwiftSyntax\n                import SwiftSyntaxBuilder\n                import SwiftSyntaxMacros\n\n                /// Implementation of the `stringify` macro, which takes an expression\n                /// of any type and produces a tuple containing the value of that expression\n                /// and the source code that produced the value. For example\n                ///\n                ///     #stringify(x + y)\n                ///\n                ///  will expand to\n                ///\n                ///     (x + y, \"x + y\")\n                public struct StringifyMacro: ExpressionMacro {\n                    public static func expansion(\n                        of node: some FreestandingMacroExpansionSyntax,\n                        in context: some MacroExpansionContext\n                    ) -> ExprSyntax {\n                        guard let argument = node.arguments.first?.expression else {\n                            fatalError(\"compiler bug: the macro does not have any arguments\")\n                        }\n\n                        return \"(\\(argument), \\(literal: argument.description))\"\n                    }\n                }\n\n                @main\n                struct \\##(moduleName)Plugin: CompilerPlugin {\n                    let providingMacros: [Macro.Type] = [\n                        StringifyMacro.self,\n                    ]\n                }\n\n                \"\"\"##\n            )\n        }\n    }\n\n    private func writeMacroClientSources(_ path: AbsolutePath) throws {\n        try makeDirectories(path)\n\n        try writePackageFile(path.appending(\"main.swift\")) { stream in\n            stream.send(\n                ##\"\"\"\n                import \\##(moduleName)\n\n                let a = 17\n                let b = 25\n\n                let (result, code) = #stringify(a + b)\n\n                print(\"The value \\(result) was produced by the code \\\"\\(code)\\\"\")\n\n                \"\"\"##\n            )\n        }\n    }\n\n    private func writeTestFileStubs(testsPath: AbsolutePath) throws {\n        let testModule = try AbsolutePath(validating: moduleName + Module.testModuleNameSuffix, relativeTo: testsPath)\n        progressReporter?(\"Creating \\(testModule.relative(to: destinationPath))/\")\n        try makeDirectories(testModule)\n\n        let testClassFile = try AbsolutePath(validating: \"\\(moduleName)Tests.swift\", relativeTo: testModule)\n\n        switch packageType {\n        case .empty, .buildToolPlugin, .commandPlugin:\n            break\n        case .library, .executable, .tool:\n            try writeLibraryTestsFile(testClassFile)\n        case .macro:\n            try writeMacroTestsFile(testClassFile)\n        }\n    }\n}\n\n// Private helpers\n\nprivate enum InitError: Swift.Error {\n    case manifestAlreadyExists\n    case unsupportedTestingLibraryForPackageType(_ testingLibrary: TestingLibrary, _ packageType: InitPackage.PackageType)\n}\n\nextension InitError: CustomStringConvertible {\n    var description: String {\n        switch self {\n        case .manifestAlreadyExists:\n            return \"a manifest file already exists in this directory\"\n        case let .unsupportedTestingLibraryForPackageType(library, packageType):\n            return \"\\(library) cannot be used when initializing a \\(packageType) package\"\n        }\n    }\n}\n\nextension PackageModel.Platform {\n    var manifestName: String {\n        switch self {\n        case .macOS:\n            return \"macOS\"\n        case .macCatalyst:\n            return \"macCatalyst\"\n        case .iOS:\n            return \"iOS\"\n        case .tvOS:\n            return \"tvOS\"\n        case .watchOS:\n            return \"watchOS\"\n        case .visionOS:\n            return \"visionOS\"\n        case .driverKit:\n            return \"DriverKit\"\n        default:\n            fatalError(\"unexpected manifest name call for platform \\(self)\")\n        }\n    }\n}\n\nextension SupportedPlatform {\n    var isManifestAPIAvailable: Bool {\n        if platform == .macOS && self.version.major == 10 {\n            guard self.version.patch == 0 else {\n                return false\n            }\n        } else if [Platform.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .driverKit].contains(platform) {\n            guard self.version.minor == 0, self.version.patch == 0 else {\n                return false\n            }\n        } else {\n            return false\n        }\n\n        switch platform {\n        case .macOS where version.major == 10:\n            return (10...15).contains(version.minor)\n        case .macOS:\n            return (11...11).contains(version.major)\n        case .macCatalyst:\n            return (13...14).contains(version.major)\n        case .iOS:\n            return (8...14).contains(version.major)\n        case .tvOS:\n            return (9...14).contains(version.major)\n        case .watchOS:\n            return (2...7).contains(version.major)\n        case .visionOS:\n            return (1...1).contains(version.major)\n        case .driverKit:\n            return (19...20).contains(version.major)\n\n        default:\n            return false\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/LoadableResult.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// A result which can be loaded.\n///\n/// It is useful for objects that hold a state on disk and need to be\n/// loaded frequently.\npublic final class LoadableResult<Value> {\n    /// The constructor closure for the value.\n    private let construct: () throws -> Value\n\n    /// Create a loadable result.\n    public init(_ construct: @escaping () throws -> Value) {\n        self.construct = construct\n    }\n\n    /// Load and return the result.\n    public func loadResult() -> Result<Value, Error> {\n        Result(catching: {\n            try self.construct()\n        })\n    }\n\n    /// Load and return the value.\n    public func load() throws -> Value {\n        try self.loadResult().get()\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManagedArtifact.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageGraph\nimport PackageModel\nimport SourceControl\nimport TSCBasic\n\nextension Workspace {\n    /// A downloaded artifact managed by the workspace.\n    public struct ManagedArtifact {\n        /// The package reference.\n        public let packageRef: PackageReference\n\n        /// The name of the binary target the artifact corresponds to.\n        public let targetName: String\n\n        /// The source of the artifact (local or remote).\n        public let source: Source\n\n        /// The path of the artifact on disk\n        public let path: Basics.AbsolutePath\n\n        public let kind: BinaryModule.Kind\n\n        public init(\n            packageRef: PackageReference,\n            targetName: String,\n            source: Source,\n            path: Basics.AbsolutePath,\n            kind: BinaryModule.Kind\n        ) {\n            self.packageRef = packageRef\n            self.targetName = targetName\n            self.source = source\n            self.path = path\n            self.kind = kind\n        }\n\n        /// Create an artifact downloaded from a remote url.\n        public static func remote(\n            packageRef: PackageReference,\n            targetName: String,\n            url: String,\n            checksum: String,\n            path: Basics.AbsolutePath,\n            kind: BinaryModule.Kind\n        ) -> ManagedArtifact {\n            return ManagedArtifact(\n                packageRef: packageRef,\n                targetName: targetName,\n                source: .remote(url: url, checksum: checksum),\n                path: path,\n                kind: kind\n            )\n        }\n\n        /// Create an artifact present locally on the filesystem.\n        public static func local(\n            packageRef: PackageReference,\n            targetName: String,\n            path: Basics.AbsolutePath,\n            kind: BinaryModule.Kind,\n            checksum: String? = nil\n        ) -> ManagedArtifact {\n            return ManagedArtifact(\n                packageRef: packageRef,\n                targetName: targetName,\n                source: .local(checksum: checksum),\n                path: path,\n                kind: kind\n            )\n        }\n\n        /// Represents the source of the artifact.\n        public enum Source: Equatable {\n\n            /// Represents a remote artifact, with the url it was downloaded from, its checksum, and its path relative to\n            /// the workspace artifacts path.\n            case remote(url: String, checksum: String)\n\n            /// Represents a locally available artifact, with its path relative either to its package or to the workspace artifacts\n            /// path, in the latter case, the checksum of the local archive the artifact was extracted from is set.\n            case local(checksum: String? = nil)\n        }\n    }\n}\n\nextension Workspace.ManagedArtifact: CustomStringConvertible {\n    public var description: String {\n        return \"<ManagedArtifact: \\(self.packageRef.identity).\\(self.targetName) \\(self.source) \\(self.path)>\"\n    }\n}\n\nextension Workspace.ManagedArtifact.Source: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .local(let checksum):\n            return \"local(checksum: \\(checksum ?? \"nil\"))\"\n        case .remote(let url, let checksum):\n            return \"remote(url: \\(url), checksum: \\(checksum))\"\n        }\n    }\n}\n\n// MARK: - ManagedArtifacts\n\nextension Workspace {\n    /// A collection of managed artifacts which have been downloaded.\n    public final class ManagedArtifacts {\n        /// A mapping from package identity, to target name, to ManagedArtifact.\n        private var artifactMap: [PackageIdentity: [String: ManagedArtifact]]\n\n        internal var artifacts: AnyCollection<ManagedArtifact> {\n            AnyCollection(self.artifactMap.values.lazy.flatMap{ $0.values })\n        }\n\n        init() {\n            self.artifactMap = [:]\n        }\n\n        init(_ artifacts: [ManagedArtifact]) throws {\n            let artifactsByPackagePath = Dictionary(grouping: artifacts, by: { $0.packageRef.identity })\n            self.artifactMap = try artifactsByPackagePath.mapValues{ artifacts in\n                // rdar://86857825 do not use Dictionary(uniqueKeysWithValues:) as it can crash the process when input is incorrect such as in older versions of SwiftPM\n                var map = [String: ManagedArtifact]()\n                for artifact in artifacts {\n                    if map[artifact.targetName] != nil {\n                        throw StringError(\"binary artifact for '\\(artifact.targetName)' already exists in managed artifacts\")\n                    }\n                    map[artifact.targetName] = artifact\n                }\n                return map\n            }\n        }\n\n        public subscript(packageIdentity packageIdentity: PackageIdentity, targetName targetName: String) -> ManagedArtifact? {\n            self.artifactMap[packageIdentity]?[targetName]\n        }\n\n        public func add(_ artifact: ManagedArtifact) {\n            self.artifactMap[artifact.packageRef.identity, default: [:]][artifact.targetName] = artifact\n        }\n\n        public func remove(packageIdentity: PackageIdentity, targetName: String) {\n            self.artifactMap[packageIdentity]?[targetName] = nil\n        }\n    }\n}\n\nextension Workspace.ManagedArtifacts: Collection {\n    public var startIndex: AnyIndex {\n        self.artifacts.startIndex\n    }\n\n    public var endIndex: AnyIndex {\n        self.artifacts.endIndex\n    }\n\n    public subscript(index: AnyIndex) -> Workspace.ManagedArtifact {\n        self.artifacts[index]\n    }\n\n    public func index(after index: AnyIndex) -> AnyIndex {\n        self.artifacts.index(after: index)\n    }\n}\n\nextension Workspace.ManagedArtifacts: CustomStringConvertible {\n    public var description: String {\n        \"<ManagedArtifacts: \\(Array(self.artifacts))>\"\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManagedDependency.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageGraph\nimport PackageModel\nimport SourceControl\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\nextension Workspace {\n    /// An individual managed dependency.\n    ///\n    /// Each dependency will have a checkout containing the sources at a\n    /// particular revision, and may have an associated version.\n    public struct ManagedDependency: Equatable {\n        /// Represents the state of the managed dependency.\n        public indirect enum State: Equatable, CustomStringConvertible {\n            /// The dependency is a local package on the file system.\n            case fileSystem(Basics.AbsolutePath)\n\n            /// The dependency is a managed source control checkout.\n            case sourceControlCheckout(CheckoutState)\n\n            /// The dependency is downloaded from a registry.\n            case registryDownload(version: Version)\n\n            /// The dependency is in edited state.\n            ///\n            /// If the path is non-nil, the dependency is managed by a user and is\n            /// located at the path. In other words, this dependency is being used\n            /// for top of the tree style development.\n            case edited(basedOn: ManagedDependency?, unmanagedPath: Basics.AbsolutePath?)\n\n            case custom(version: Version, path: Basics.AbsolutePath)\n\n            public var description: String {\n                switch self {\n                case .fileSystem(let path):\n                    return \"fileSystem (\\(path))\"\n                case .sourceControlCheckout(let checkoutState):\n                    return \"sourceControlCheckout (\\(checkoutState))\"\n                case .registryDownload(let version):\n                    return \"registryDownload (\\(version))\"\n                case .edited:\n                    return \"edited\"\n                case .custom:\n                    return \"custom\"\n                }\n            }\n        }\n\n        /// The package reference.\n        public let packageRef: PackageReference\n\n        /// The state of the managed dependency.\n        public let state: State\n\n        /// The checked out path of the dependency on disk, relative to the workspace checkouts path.\n        public let subpath: Basics.RelativePath\n\n        internal init(\n            packageRef: PackageReference,\n            state: State,\n            subpath: Basics.RelativePath\n        ) {\n            self.packageRef = packageRef\n            self.subpath = subpath\n            self.state = state\n        }\n\n        /// Create an editable managed dependency based on a dependency which\n        /// was *not* in edit state.\n        ///\n        /// - Parameters:\n        ///     - subpath: The subpath inside the editable directory.\n        ///     - unmanagedPath: A custom absolute path instead of the subpath.\n        public func edited(subpath: Basics.RelativePath, unmanagedPath: Basics.AbsolutePath?) throws -> ManagedDependency {\n            guard case .sourceControlCheckout =  self.state else {\n                throw InternalError(\"invalid dependency state: \\(self.state)\")\n            }\n            return ManagedDependency(\n                packageRef: self.packageRef,\n                state: .edited(basedOn: self, unmanagedPath: unmanagedPath),\n                subpath: subpath\n            )\n        }\n\n        /// Create a dependency present locally on the filesystem.\n        public static func fileSystem(\n            packageRef: PackageReference\n        ) throws -> ManagedDependency {\n            switch packageRef.kind {\n            case .root(let path), .fileSystem(let path), .localSourceControl(let path):\n                return try ManagedDependency(\n                    packageRef: packageRef,\n                    state: .fileSystem(path),\n                    // FIXME: This is just a fake entry, we should fix it.\n                    subpath: RelativePath(validating: packageRef.identity.description)\n                )\n            default:\n                throw InternalError(\"invalid package type: \\(packageRef.kind)\")\n            }\n        }\n\n        /// Create a source control dependency checked out\n        public static func sourceControlCheckout(\n            packageRef: PackageReference,\n            state: CheckoutState,\n            subpath: Basics.RelativePath\n        ) throws -> ManagedDependency {\n            switch packageRef.kind {\n            case .localSourceControl, .remoteSourceControl:\n                return ManagedDependency(\n                    packageRef: packageRef,\n                    state: .sourceControlCheckout(state),\n                    subpath: subpath\n                )\n            default:\n                throw InternalError(\"invalid package type: \\(packageRef.kind)\")\n            }\n        }\n\n        /// Create a registry dependency downloaded\n        public static func registryDownload(\n            packageRef: PackageReference,\n            version: Version,\n            subpath: Basics.RelativePath\n        ) throws -> ManagedDependency {\n            guard case .registry = packageRef.kind else {\n                throw InternalError(\"invalid package type: \\(packageRef.kind)\")\n            }\n            return ManagedDependency(\n                packageRef: packageRef,\n                state: .registryDownload(version: version),\n                subpath: subpath\n            )\n        }\n\n        /// Create an edited dependency\n        public static func edited(\n            packageRef: PackageReference,\n            subpath: Basics.RelativePath,\n            basedOn: ManagedDependency?,\n            unmanagedPath: Basics.AbsolutePath?\n        ) -> ManagedDependency {\n            return ManagedDependency(\n                packageRef: packageRef,\n                state: .edited(basedOn: basedOn, unmanagedPath: unmanagedPath),\n                subpath: subpath\n            )\n        }\n    }\n}\n\nextension Workspace.ManagedDependency: CustomStringConvertible {\n    public var description: String {\n        return \"<ManagedDependency: \\(self.packageRef.identity) \\(self.state)>\"\n    }\n}\n\n// MARK: - ManagedDependencies\n\nextension Workspace {\n    /// A collection of managed dependencies.\n    public struct ManagedDependencies {\n        private var dependencies: [PackageIdentity: ManagedDependency]\n\n        init() {\n            self.dependencies = [:]\n        }\n        \n        private init(\n            _ dependencies: [PackageIdentity: ManagedDependency]\n        ) {\n            self.dependencies = dependencies\n        }\n\n        init(_ dependencies: [ManagedDependency]) throws {\n            // rdar://86857825 do not use Dictionary(uniqueKeysWithValues:) as it can crash the process when input is incorrect such as in older versions of SwiftPM\n            self.dependencies = [:]\n            for dependency in dependencies {\n                if self.dependencies[dependency.packageRef.identity] != nil {\n                    throw StringError(\"\\(dependency.packageRef.identity) already exists in managed dependencies\")\n                }\n                self.dependencies[dependency.packageRef.identity] = dependency\n            }\n        }\n\n        public subscript(identity: PackageIdentity) -> ManagedDependency? {\n            return self.dependencies[identity]\n        }\n\n        // When loading manifests in Workspace, there are cases where we must also compare the location\n        // as it may attempt to load manifests for dependencies that have the same identity but from a different location\n        // (e.g. dependency is changed to a fork with the same identity)\n        public subscript(comparingLocation package: PackageReference) -> ManagedDependency? {\n            if let dependency = self.dependencies[package.identity], dependency.packageRef.equalsIncludingLocation(package) {\n                return dependency\n            }\n            return .none\n        }\n\n        public func add(_ dependency: ManagedDependency) -> Self {\n            var dependencies = dependencies\n            dependencies[dependency.packageRef.identity] = dependency\n            return ManagedDependencies(dependencies)\n        }\n\n        public func remove(_ identity: PackageIdentity) -> Self {\n            var dependencies = dependencies\n            dependencies[identity] = nil\n            return ManagedDependencies(dependencies)\n        }\n    }\n}\n\nextension Workspace.ManagedDependencies: Collection {\n    public typealias Index = Dictionary<PackageIdentity, Workspace.ManagedDependency>.Index\n    public typealias Element = Workspace.ManagedDependency\n\n    public var startIndex: Index {\n        self.dependencies.startIndex\n    }\n\n    public var endIndex: Index {\n        self.dependencies.endIndex\n    }\n\n    public subscript(index: Index) -> Element {\n        self.dependencies[index].value\n    }\n\n    public func index(after index: Index) -> Index {\n        self.dependencies.index(after: index)\n    }\n}\n\nextension Workspace.ManagedDependencies: CustomStringConvertible {\n    public var description: String {\n        \"<ManagedDependencies: \\(Array(self.dependencies.values))>\"\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManagedPrebuilt.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct TSCUtility.Version\nimport struct TSCBasic.StringError\n\nimport Basics\nimport PackageModel\n\nextension Workspace {\n    /// A downloaded prebuilt managed by the workspace.\n    public struct ManagedPrebuilt {\n        /// The package identity\n        public let identity: PackageIdentity\n\n        /// The package version\n        public let version: Version\n\n        /// The name of the binary target the artifact corresponds to.\n        public let libraryName: String\n\n        /// The path to the extracted prebuilt artifacts\n        public let path: AbsolutePath\n\n        /// The path to the checked out source\n        public let checkoutPath: AbsolutePath?\n\n        /// The products in the library\n        public let products: [String]\n\n        /// The include path for the C modules\n        public let includePath: [RelativePath]?\n\n        /// The C modules that need their includes directory added to the include path\n        public let cModules: [String]\n    }\n}\n\nextension Workspace.ManagedPrebuilt: CustomStringConvertible {\n    public var description: String {\n        return \"<ManagedArtifact: \\(self.identity).\\(self.libraryName)>\"\n    }\n}\n\n// MARK: - ManagedArtifacts\n\nextension Workspace {\n    /// A collection of managed artifacts which have been downloaded.\n    public final class ManagedPrebuilts {\n        /// A mapping from package identity, to target name, to ManagedArtifact.\n        private var prebuiltMap: [PackageIdentity: [String: ManagedPrebuilt]]\n\n        internal var prebuilts: AnyCollection<ManagedPrebuilt> {\n            AnyCollection(self.prebuiltMap.values.lazy.flatMap{ $0.values })\n        }\n\n        init() {\n            self.prebuiltMap = [:]\n        }\n\n        init(_ prebuilts: [ManagedPrebuilt]) throws {\n            let prebuiltsByPackagePath = Dictionary(grouping: prebuilts, by: { $0.identity })\n            self.prebuiltMap = try prebuiltsByPackagePath.mapValues{ prebuilt in\n                try Dictionary(prebuilt.map { ($0.libraryName, $0) }, uniquingKeysWith: { _, _ in\n                    // should be unique\n                    throw StringError(\"prebuilt already exists in managed prebuilts\")\n                })\n            }\n        }\n\n        public subscript(packageIdentity packageIdentity: PackageIdentity, targetName targetName: String) -> ManagedPrebuilt? {\n            self.prebuiltMap[packageIdentity]?[targetName]\n        }\n\n        public func add(_ prebuilt: ManagedPrebuilt) {\n            self.prebuiltMap[prebuilt.identity, default: [:]][prebuilt.libraryName] = prebuilt\n        }\n\n        public func remove(packageIdentity: PackageIdentity, targetName: String) {\n            self.prebuiltMap[packageIdentity]?[targetName] = nil\n        }\n    }\n}\n\nextension Workspace.ManagedPrebuilts: Collection {\n    public var startIndex: AnyIndex {\n        self.prebuilts.startIndex\n    }\n\n    public var endIndex: AnyIndex {\n        self.prebuilts.endIndex\n    }\n\n    public subscript(index: AnyIndex) -> Workspace.ManagedPrebuilt {\n        self.prebuilts[index]\n    }\n\n    public func index(after index: AnyIndex) -> AnyIndex {\n        self.prebuilts.index(after: index)\n    }\n}\n\nextension Workspace.ManagedPrebuilts: CustomStringConvertible {\n    public var description: String {\n        \"<ManagedArtifacts: \\(Array(self.prebuilts))>\"\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManifestSigning/Base64URL.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Vapor open source project\n//\n// Copyright (c) 2017-2020 Vapor project authors\n// Licensed under MIT\n//\n// See LICENSE for license information\n//\n// SPDX-License-Identifier: MIT\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n// Source: https://github.com/vapor/jwt-kit/blob/main/Sources/JWTKit/Utilities/Base64URL.swift\n\nextension DataProtocol {\n    func base64URLDecodedBytes() -> Data? {\n        var data = Data(self)\n        data.base64URLUnescape()\n        return Data(base64Encoded: data)\n    }\n\n    func base64URLEncodedBytes() -> Data {\n        var data = Data(self).base64EncodedData()\n        data.base64URLEscape()\n        return data\n    }\n}\n\nextension Data {\n    /// Converts base64-url encoded data to a base64 encoded data.\n    ///\n    /// https://tools.ietf.org/html/rfc4648#page-7\n    mutating func base64URLUnescape() {\n        for i in 0 ..< self.count {\n            switch self[i] {\n            case 0x2D: self[self.index(self.startIndex, offsetBy: i)] = 0x2B\n            case 0x5F: self[self.index(self.startIndex, offsetBy: i)] = 0x2F\n            default: break\n            }\n        }\n        /// https://stackoverflow.com/questions/43499651/decode-base64url-to-base64-swift\n        let padding = count % 4\n        if padding > 0 {\n            self += Data(repeating: 0x3D, count: 4 - padding)\n        }\n    }\n\n    /// Converts base64 encoded data to a base64-url encoded data.\n    ///\n    /// https://tools.ietf.org/html/rfc4648#page-7\n    mutating func base64URLEscape() {\n        for i in 0 ..< self.count {\n            switch self[i] {\n            case 0x2B: self[self.index(self.startIndex, offsetBy: i)] = 0x2D\n            case 0x2F: self[self.index(self.startIndex, offsetBy: i)] = 0x5F\n            default: break\n            }\n        }\n        self = split(separator: 0x3D).first ?? .init()\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManifestSigning/CertificatePolicy.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Dispatch\nimport Foundation\nimport Basics\nimport struct TSCBasic.ByteString\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftASN1\n@_implementationOnly import X509\n#else\nimport SwiftASN1\nimport X509\n#endif\n\npublic enum CertificatePolicyKey: Hashable, CustomStringConvertible {\n    case `default`(subjectUserID: String? = nil, subjectOrganizationalUnit: String? = nil)\n    case appleSwiftPackageCollection(subjectUserID: String? = nil, subjectOrganizationalUnit: String? = nil)\n\n    @available(*, deprecated, message: \"use `appleSwiftPackageCollection` instead\")\n    case appleDistribution(subjectUserID: String? = nil, subjectOrganizationalUnit: String? = nil)\n\n    /// For testing only\n    case custom\n\n    public var description: String {\n        switch self {\n        case .default(let userID, let organizationalUnit):\n            return \"Default certificate policy\\(userID.map { \" (userID: \\($0))\" } ?? \"\")\\(organizationalUnit.map { \" (organizationalUnit: \\($0))\" } ?? \"\")\"\n        case .appleSwiftPackageCollection(let userID, let organizationalUnit):\n            return \"Swift Package Collection certificate policy\\(userID.map { \" (userID: \\($0))\" } ?? \"\")\\(organizationalUnit.map { \" (organizationalUnit: \\($0))\" } ?? \"\")\"\n        case .appleDistribution(let userID, let organizationalUnit):\n            return \"Distribution certificate policy\\(userID.map { \" (userID: \\($0))\" } ?? \"\")\\(organizationalUnit.map { \" (organizationalUnit: \\($0))\" } ?? \"\")\"\n        case .custom:\n            return \"Custom certificate policy\"\n        }\n    }\n\n    public static let `default` = CertificatePolicyKey.default()\n    public static let appleSwiftPackageCollection = CertificatePolicyKey.appleSwiftPackageCollection()\n    @available(*, deprecated, message: \"use `appleSwiftPackageCollection` instead\")\n    public static let appleDistribution = CertificatePolicyKey.appleDistribution()\n}\n\n// MARK: - Certificate policies\n\nprotocol CertificatePolicy {\n    /// Validates the given certificate chain.\n    ///\n    /// - Parameters:\n    ///   - certChain: The certificate being verified must be the first element of the array, with its issuer the next\n    ///                element and so on, and the root CA certificate is last.\n    ///   - validationTime: Overrides the timestamp used for checking certificate expiry (e.g., for testing).\n    ///                     By default the current time is used.\n    func validate(certChain: [Certificate], validationTime: Date) async throws\n}\n\nextension CertificatePolicy {\n    /// Validates the given certificate chain.\n    ///\n    /// - Parameters:\n    ///   - certChain: The certificate being verified must be the first element of the array, with its issuer the next\n    ///                element and so on, and the root CA certificate is last.\n    func validate(certChain: [Certificate]) async throws {\n        try await self.validate(certChain: certChain, validationTime: Date())\n    }\n\n    func verify(\n        certChain: [Certificate],\n        trustedRoots: [Certificate]?,\n        @PolicyBuilder policies: () -> some VerifierPolicy,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        guard !certChain.isEmpty else {\n            throw CertificatePolicyError.emptyCertChain\n        }\n\n        let policies = policies()\n\n        var trustStore = CertificateStores.defaultTrustRoots\n        if let trustedRoots {\n            trustStore.append(contentsOf: trustedRoots)\n        }\n\n        guard !trustStore.isEmpty else {\n            throw CertificatePolicyError.noTrustedRootCertsConfigured\n        }\n\n        var verifier = Verifier(rootCertificates: CertificateStore(trustStore)) {\n            policies\n        }\n        let result = await verifier.validate(\n            leafCertificate: certChain[0],\n            intermediates: CertificateStore(certChain)\n        )\n\n        switch result {\n        case .validCertificate:\n            return\n        case .couldNotValidate(let failures):\n            observabilityScope.emit(error: \"Failed to validate certificate chain \\(certChain): \\(failures)\")\n            throw CertificatePolicyError.invalidCertChain\n        }\n    }\n}\n\nenum CertificatePolicyError: Error, Equatable {\n    case noTrustedRootCertsConfigured\n    case emptyCertChain\n    case invalidCertChain\n}\n\n/// Default policy for validating certificates used to sign package collections.\n///\n/// Certificates must satisfy these conditions:\n///   - The timestamp at which signing/verification is done must fall within the signing certificate’s validity period.\n///   - The certificate’s “Extended Key Usage” extension must include “Code Signing”.\n///   - The certificate must use either 256-bit EC (recommended) or 2048-bit RSA key.\n///   - The certificate must not be revoked. The certificate authority must support OCSP.\n///   - The certificate chain is valid and root certificate must be trusted.\nstruct DefaultCertificatePolicy: CertificatePolicy {\n    let trustedRoots: [Certificate]\n    let expectedSubjectUserID: String?\n    let expectedSubjectOrganizationalUnit: String?\n\n    private let httpClient: HTTPClient\n    private let observabilityScope: ObservabilityScope\n\n    /// Initializes a `DefaultCertificatePolicy`.\n    ///\n    /// - Parameters:\n    ///   - trustedRootCertsDir: Users may specify root certificates in addition to SwiftPM's default trust\n    ///                          store by placing them in this directory.\n    ///   - additionalTrustedRootCerts: Root certificates to be trusted in addition to those in `trustedRootCertsDir`.\n    ///                                 The difference between this and `trustedRootCertsDir` is that the latter is\n    ///                                 user configured and dynamic, while this is configured by SwiftPM and static.\n    ///   - expectedSubjectUserID: The subject user ID that must match if specified.\n    ///   - expectedSubjectOrganizationalUnit: The subject organizational unit name that must match if specified.\n    init(\n        trustedRootCertsDir: AbsolutePath?,\n        fileSystem: FileSystem?,\n        additionalTrustedRootCerts: [Certificate]?,\n        expectedSubjectUserID: String? = nil,\n        expectedSubjectOrganizationalUnit: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) {\n        var trustedRoots = [Certificate]()\n        if let trustedRootCertsDir, let fileSystem {\n            trustedRoots\n                .append(contentsOf: Self.loadCerts(at: trustedRootCertsDir, fileSystem: fileSystem, observabilityScope: observabilityScope))\n        }\n        if let additionalTrustedRootCerts {\n            trustedRoots.append(contentsOf: additionalTrustedRootCerts)\n        }\n        self.trustedRoots = trustedRoots\n        self.expectedSubjectUserID = expectedSubjectUserID\n        self.expectedSubjectOrganizationalUnit = expectedSubjectOrganizationalUnit\n        self.httpClient = HTTPClient.makeDefault()\n        self.observabilityScope = observabilityScope\n    }\n\n    func validate(certChain: [Certificate], validationTime: Date) async throws {\n        guard !certChain.isEmpty else {\n            throw CertificatePolicyError.emptyCertChain\n        }\n\n        try await self.verify(\n            certChain: certChain,\n            trustedRoots: self.trustedRoots,\n            policies: {\n                _ADPCertificatePolicy() // included for testing\n                // Check if subject name matches\n                _SubjectNamePolicy(\n                    expectedUserID: self.expectedSubjectUserID,\n                    expectedOrganizationalUnit: self.expectedSubjectOrganizationalUnit\n                )\n                // Must be a code signing certificate\n                _CodeSigningPolicy()\n                // Basic validations including expiry check\n                RFC5280Policy(validationTime: validationTime)\n                // Must support OCSP\n                _OCSPVerifierPolicy(\n                    httpClient: self.httpClient,\n                    validationTime: validationTime\n                )\n            },\n            observabilityScope: self.observabilityScope\n        )\n    }\n}\n\n/// Policy for validating developer.apple.com Swift Package Collection certificates.\n///\n/// This has the same requirements as `DefaultCertificatePolicy` plus additional\n/// marker extensions for Swift Package Collection certifiicates.\nstruct ADPSwiftPackageCollectionCertificatePolicy: CertificatePolicy {\n    let trustedRoots: [Certificate]\n    let expectedSubjectUserID: String?\n    let expectedSubjectOrganizationalUnit: String?\n\n    private let httpClient: HTTPClient\n    private let observabilityScope: ObservabilityScope\n\n    /// Initializes a `ADPSwiftPackageCollectionCertificatePolicy`.\n    ///\n    /// - Parameters:\n    ///   - trustedRootCertsDir: Users may specify root certificates in addition to SwiftPM's default trust\n    ///                          store by placing them in this directory.\n    ///   - additionalTrustedRootCerts: Root certificates to be trusted in addition to those in `trustedRootCertsDir`.\n    ///                                 The difference between this and `trustedRootCertsDir` is that the latter is\n    ///                                 user configured and dynamic, while this is configured by SwiftPM and static.\n    ///   - expectedSubjectUserID: The subject user ID that must match if specified.\n    ///   - expectedSubjectOrganizationalUnit: The subject organizational unit name that must match if specified.\n    init(\n        trustedRootCertsDir: AbsolutePath?,\n        fileSystem: FileSystem?,\n        additionalTrustedRootCerts: [Certificate]?,\n        expectedSubjectUserID: String? = nil,\n        expectedSubjectOrganizationalUnit: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) {\n        var trustedRoots = [Certificate]()\n        if let trustedRootCertsDir, let fileSystem {\n            trustedRoots\n                .append(contentsOf: Self.loadCerts(at: trustedRootCertsDir, fileSystem: fileSystem, observabilityScope: observabilityScope))\n        }\n        if let additionalTrustedRootCerts {\n            trustedRoots.append(contentsOf: additionalTrustedRootCerts)\n        }\n        self.trustedRoots = trustedRoots\n        self.expectedSubjectUserID = expectedSubjectUserID\n        self.expectedSubjectOrganizationalUnit = expectedSubjectOrganizationalUnit\n        self.httpClient = HTTPClient.makeDefault()\n        self.observabilityScope = observabilityScope\n    }\n\n    func validate(certChain: [Certificate], validationTime: Date) async throws {\n        guard !certChain.isEmpty else {\n            throw CertificatePolicyError.emptyCertChain\n        }\n\n        try await self.verify(\n            certChain: certChain,\n            trustedRoots: self.trustedRoots,\n            policies: {\n                // Check for specific markers\n                _ADPSwiftPackageCertificatePolicy()\n                _ADPCertificatePolicy() // included for testing\n                // Check if subject name matches\n                _SubjectNamePolicy(\n                    expectedUserID: self.expectedSubjectUserID,\n                    expectedOrganizationalUnit: self.expectedSubjectOrganizationalUnit\n                )\n                // Must be a code signing certificate\n                _CodeSigningPolicy()\n                // Basic validations including expiry check\n                RFC5280Policy(validationTime: validationTime)\n                // Must support OCSP\n                _OCSPVerifierPolicy(\n                    httpClient: self.httpClient,\n                    validationTime: validationTime\n                )\n            },\n            observabilityScope: self.observabilityScope\n        )\n    }\n}\n\n/// Policy for validating developer.apple.com Apple Distribution certificates.\n///\n/// This has the same requirements as `DefaultCertificatePolicy` plus additional\n/// marker extensions for Apple Distribution certifiicates.\nstruct ADPAppleDistributionCertificatePolicy: CertificatePolicy {\n    let trustedRoots: [Certificate]\n    let expectedSubjectUserID: String?\n    let expectedSubjectOrganizationalUnit: String?\n\n    private let httpClient: HTTPClient\n    private let observabilityScope: ObservabilityScope\n\n    /// Initializes a `ADPAppleDistributionCertificatePolicy`.\n    ///\n    /// - Parameters:\n    ///   - trustedRootCertsDir: Users may specify root certificates in addition to SwiftPM's default trust\n    ///                          store by placing them in this directory.\n    ///   - additionalTrustedRootCerts: Root certificates to be trusted in addition to those in `trustedRootCertsDir`.\n    ///                                 The difference between this and `trustedRootCertsDir` is that the latter is\n    ///                                 user configured and dynamic, while this is configured by SwiftPM and static.\n    ///   - expectedSubjectUserID: The subject user ID that must match if specified.\n    ///   - expectedSubjectOrganizationalUnit: The subject organizational unit name that must match if specified.\n    init(\n        trustedRootCertsDir: AbsolutePath?,\n        fileSystem: FileSystem?,\n        additionalTrustedRootCerts: [Certificate]?,\n        expectedSubjectUserID: String? = nil,\n        expectedSubjectOrganizationalUnit: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) {\n        var trustedRoots = [Certificate]()\n        if let trustedRootCertsDir, let fileSystem {\n            trustedRoots\n                .append(contentsOf: Self.loadCerts(at: trustedRootCertsDir, fileSystem: fileSystem, observabilityScope: observabilityScope))\n        }\n        if let additionalTrustedRootCerts {\n            trustedRoots.append(contentsOf: additionalTrustedRootCerts)\n        }\n        self.trustedRoots = trustedRoots\n        self.expectedSubjectUserID = expectedSubjectUserID\n        self.expectedSubjectOrganizationalUnit = expectedSubjectOrganizationalUnit\n        self.httpClient = HTTPClient.makeDefault()\n        self.observabilityScope = observabilityScope\n    }\n\n    func validate(certChain: [Certificate], validationTime: Date) async throws {\n        guard !certChain.isEmpty else {\n            throw CertificatePolicyError.emptyCertChain\n        }\n\n        try await self.verify(\n            certChain: certChain,\n            trustedRoots: self.trustedRoots,\n            policies: {\n                // Check for specific markers\n                _ADPAppleDistributionCertificatePolicy()\n                _ADPCertificatePolicy() // included for testing\n                // Check if subject name matches\n                _SubjectNamePolicy(\n                    expectedUserID: self.expectedSubjectUserID,\n                    expectedOrganizationalUnit: self.expectedSubjectOrganizationalUnit\n                )\n                // Must be a code signing certificate\n                _CodeSigningPolicy()\n                // Basic validations including expiry check\n                RFC5280Policy(validationTime: validationTime)\n                // Must support OCSP\n                _OCSPVerifierPolicy(\n                    httpClient: self.httpClient,\n                    validationTime: validationTime\n                )\n            },\n            observabilityScope: self.observabilityScope\n        )\n    }\n}\n\n// MARK: - Verifier policies\n\n/// Policy for code signing certificates.\nstruct _CodeSigningPolicy: VerifierPolicy {\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = [\n        ASN1ObjectIdentifier.X509ExtensionID.keyUsage,\n        ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage,\n    ]\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        let isCodeSigning = (\n            try? chain.leaf.extensions.extendedKeyUsage?.contains(ExtendedKeyUsage.Usage.codeSigning)\n        ) ?? false\n        guard isCodeSigning else {\n            return .failsToMeetPolicy(reason: \"Certificate \\(chain.leaf) does not have code signing extended key usage\")\n        }\n        return .meetsPolicy\n    }\n}\n\n/// Policy for revocation check via OCSP.\nstruct _OCSPVerifierPolicy: VerifierPolicy {\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []\n\n    private static let cacheTTL: DispatchTimeInterval = .seconds(5 * 60)\n    private let cache = ThreadSafeKeyValueStore<\n        UnverifiedCertificateChain,\n        (result: PolicyEvaluationResult, expires: DispatchTime)\n    >()\n\n    private var underlying: OCSPVerifierPolicy<_OCSPRequester>\n\n    init(httpClient: HTTPClient, validationTime: Date) {\n        self.underlying = OCSPVerifierPolicy(\n            failureMode: .soft,\n            requester: _OCSPRequester(httpClient: httpClient),\n            validationTime: validationTime\n        )\n    }\n\n    mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        // Look for cached result\n        if let cached = self.cache[chain], cached.expires < .now() {\n            return cached.result\n        }\n\n        // This makes HTTP requests\n        let result = await self.underlying.chainMeetsPolicyRequirements(chain: chain)\n\n        // Save result to cache\n        self.cache[chain] = (result: result, expires: .now() + Self.cacheTTL)\n        return result\n    }\n}\n\nprivate struct _OCSPRequester: OCSPRequester {\n    let httpClient: HTTPClient\n\n    func query(request: [UInt8], uri: String) async -> OCSPRequesterQueryResult {\n        guard let url = URL(string: uri), let host = url.host else {\n            return .terminalError(SwiftOCSPRequesterError.invalidURL(uri))\n        }\n\n        do {\n            let response = try await self.httpClient.post(\n                url,\n                body: Data(request),\n                headers: [\n                    \"Content-Type\": \"application/ocsp-request\",\n                    \"Host\": host,\n                ]\n            )\n\n            guard response.statusCode == 200 else {\n                throw SwiftOCSPRequesterError.invalidResponse(statusCode: response.statusCode)\n            }\n            guard let responseBody = response.body else {\n                throw SwiftOCSPRequesterError.emptyResponse\n            }\n            return .response(Array(responseBody))\n        } catch {\n            return .nonTerminalError(error)\n        }\n    }\n}\n\nenum SwiftOCSPRequesterError: Error {\n    case invalidURL(String)\n    case emptyResponse\n    case invalidResponse(statusCode: Int)\n}\n\n/// Policy for matching subject name.\nstruct _SubjectNamePolicy: VerifierPolicy {\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []\n\n    let expectedUserID: String?\n    let expectedOrganizationalUnit: String?\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        if let expectedUserID {\n            let userID = chain.leaf.subject.userID\n            guard userID == expectedUserID else {\n                return .failsToMeetPolicy(\n                    reason: \"Subject user ID '\\(String(describing: userID))' does not match expected '\\(expectedUserID)'\"\n                )\n            }\n        }\n\n        if let expectedOrganizationalUnit {\n            let organizationUnit = chain.leaf.subject.organizationalUnitName\n            guard organizationUnit == expectedOrganizationalUnit else {\n                return .failsToMeetPolicy(\n                    reason: \"Subject organizational unit name '\\(String(describing: organizationUnit))' does not match expected '\\(expectedOrganizationalUnit)'\"\n                )\n            }\n        }\n\n        return .meetsPolicy\n    }\n}\n\n/// Policy for ADP certificates.\nstruct _ADPCertificatePolicy: VerifierPolicy {\n    /// Include custom marker extensions (which can be critical) so they would not\n    /// be considered unhandled and cause certificate chain validation to fail.\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] =\n        ASN1ObjectIdentifier.NameAttributes.adpAppleDevelopmentMarkers // included for testing\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        // Not policing anything here. This policy is mainly for\n        // listing marker extensions to prevent chain validation\n        // from failing prematurely.\n        .meetsPolicy\n    }\n}\n\n/// Policy for ADP Swift Package (Collection) certificates.\nstruct _ADPSwiftPackageCertificatePolicy: VerifierPolicy {\n    /// Include custom marker extensions (which can be critical) so they would not\n    /// be considered unhandled and cause certificate chain validation to fail.\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = [\n        ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageCollectionMarker,\n        ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageMarker,\n    ]\n\n    // developer.apple.com cert chain is always 3-long\n    private static let expectedCertChainLength = 3\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        guard chain.count == Self.expectedCertChainLength else {\n            return .failsToMeetPolicy(\n                reason: \"Certificate chain should have length \\(Self.expectedCertChainLength) but it's \\(chain.count)\"\n            )\n        }\n\n        // Package collection can be signed with \"Swift Package Collection\"\n        // or \"Swift Package\" certificate\n        guard chain.leaf.hasExtension(oid: ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageCollectionMarker)\n            || chain.leaf.hasExtension(oid: ASN1ObjectIdentifier.NameAttributes.adpSwiftPackageMarker)\n        else {\n            return .failsToMeetPolicy(reason: \"Leaf certificate missing marker OID\")\n        }\n\n        for marker in ASN1ObjectIdentifier.NameAttributes.wwdrIntermediateMarkers {\n            if chain[1].hasExtension(oid: marker) {\n                return .meetsPolicy\n            }\n        }\n        return .failsToMeetPolicy(reason: \"Intermediate missing marker OID\")\n    }\n}\n\n/// Policy for ADP Apple Distribution certificates.\nstruct _ADPAppleDistributionCertificatePolicy: VerifierPolicy {\n    /// Include custom marker extensions (which can be critical) so they would not\n    /// be considered unhandled and cause certificate chain validation to fail.\n    let verifyingCriticalExtensions: [ASN1ObjectIdentifier] =\n        ASN1ObjectIdentifier.NameAttributes.adpAppleDistributionMarkers\n\n    // developer.apple.com cert chain is always 3-long\n    private static let expectedCertChainLength = 3\n\n    func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {\n        guard chain.count == Self.expectedCertChainLength else {\n            return .failsToMeetPolicy(\n                reason: \"Certificate chain should have length \\(Self.expectedCertChainLength) but it's \\(chain.count)\"\n            )\n        }\n\n        var hasMarker = false\n        for marker in ASN1ObjectIdentifier.NameAttributes.adpAppleDistributionMarkers {\n            if chain.leaf.hasExtension(oid: marker) {\n                hasMarker = true\n                break\n            }\n        }\n        guard hasMarker else {\n            return .failsToMeetPolicy(reason: \"Leaf certificate missing marker OID\")\n        }\n\n        for marker in ASN1ObjectIdentifier.NameAttributes.wwdrIntermediateMarkers {\n            if chain[1].hasExtension(oid: marker) {\n                return .meetsPolicy\n            }\n        }\n        return .failsToMeetPolicy(reason: \"Intermediate missing marker OID\")\n    }\n}\n\n// MARK: - Default trust store\n\nenum Certificates {\n    static let appleRootsRaw = [\n        PackageResources.AppleComputerRootCertificate_cer,\n        PackageResources.AppleIncRootCertificate_cer,\n        PackageResources.AppleRootCA_G2_cer,\n        PackageResources.AppleRootCA_G3_cer,\n    ]\n\n    static let appleRoots = Self.appleRootsRaw.compactMap {\n        try? Certificate(derEncoded: $0)\n    }\n}\n\nenum CertificateStores {\n    static let defaultTrustRoots = Certificates.appleRoots\n}\n\n// MARK: - Utils\n\nextension CertificatePolicy {\n    fileprivate static func loadCerts(at directory: AbsolutePath, fileSystem: FileSystem, observabilityScope: ObservabilityScope) -> [Certificate] {\n        var certs = [Certificate]()\n        do {\n            try fileSystem.enumerate(directory: directory) { file in\n                do {\n                    let certData = try fileSystem.readFileContents(file)\n                    certs.append(try Certificate(derEncoded: Array(certData.contents)))\n                } catch {\n                    observabilityScope.emit(\n                        warning: \"The certificate \\(file.pathString) is invalid\",\n                        underlyingError: error\n                    )\n                }\n            }\n        } catch {\n            observabilityScope.emit(\n                warning: \"Failed enumerating certificates directory\",\n                underlyingError: error\n            )\n        }\n        return certs\n    }\n}\n\nextension HTTPClient {\n    fileprivate static func makeDefault() -> HTTPClient {\n        var httpClientConfig = HTTPClientConfiguration()\n        httpClientConfig.requestTimeout = .seconds(1)\n        return HTTPClient(configuration: httpClientConfig)\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManifestSigning/ManifestSigning.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\nimport Basics\nimport Dispatch\nimport Foundation\nimport SwiftASN1\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import _CryptoExtras\n@_implementationOnly import Crypto\n@_implementationOnly import X509\n#else\nimport _CryptoExtras\nimport Crypto\nimport X509\n#endif\n\npublic struct ManifestSignature: Equatable, Codable {\n    /// The signature\n    public let signature: String\n\n    /// Details about the certificate used to generate the signature\n    public let certificate: Certificate\n\n    public init(signature: String, certificate: Certificate) {\n        self.signature = signature\n        self.certificate = certificate\n    }\n\n    public struct Certificate: Equatable, Codable {\n        /// Subject of the certificate\n        public let subject: Name\n\n        /// Issuer of the certificate\n        public let issuer: Name\n\n        /// Creates a `Certificate`\n        public init(subject: Name, issuer: Name) {\n            self.subject = subject\n            self.issuer = issuer\n        }\n\n        /// Generic certificate name (e.g., subject, issuer)\n        public struct Name: Equatable, Codable {\n            /// User ID\n            public let userID: String?\n\n            /// Common name\n            public let commonName: String?\n\n            /// Organizational unit\n            public let organizationalUnit: String?\n\n            /// Organization\n            public let organization: String?\n\n            /// Creates a `Name`\n            public init(userID: String?,\n                        commonName: String?,\n                        organizationalUnit: String?,\n                        organization: String?) {\n                self.userID = userID\n                self.commonName = commonName\n                self.organizationalUnit = organizationalUnit\n                self.organization = organization\n            }\n        }\n    }\n}\n\npublic protocol ManifestSigner {\n    /// Signs package collection using the given certificate and key.\n    ///\n    /// - Parameters:\n    ///   - collection: The package collection to be signed\n    ///   - certChainPaths: Paths to all DER-encoded certificates in the chain. The certificate used for signing\n    ///                     must be the first in the array.\n    ///   - privateKeyPEM: Data of the private key (*.pem) of the certificate\n    ///   - certPolicyKey: The key of the `CertificatePolicy` to use for validating certificates\n    func sign(\n        manifest: some Encodable,\n        certChainPaths: [AbsolutePath],\n        privateKeyPEM: Data,\n        fileSystem: FileSystem,\n        certPolicyKey: CertificatePolicyKey\n    ) async throws -> ManifestSignature\n}\n\nextension ManifestSigner {\n    /// Signs package collection using the given certificate and key.\n    ///\n    /// - Parameters:\n    ///   - collection: The package collection to be signed\n    ///   - certChainPaths: Paths to all DER-encoded certificates in the chain. The certificate used for signing\n    ///                     must be the first in the array.\n    ///   - certPrivateKeyPath: Path to the private key (*.pem) of the certificate\n    ///   - certPolicyKey: The key of the `CertificatePolicy` to use for validating certificates\n    public func sign(\n        manifest: some Encodable,\n        certChainPaths: [AbsolutePath],\n        certPrivateKeyPath: AbsolutePath,\n        fileSystem: FileSystem,\n        certPolicyKey: CertificatePolicyKey = .default\n    ) async throws -> ManifestSignature {\n        let privateKey: Data = try fileSystem.readFileContents(certPrivateKeyPath)\n        return try await self.sign(\n            manifest: manifest,\n            certChainPaths: certChainPaths,\n            privateKeyPEM: privateKey,\n            fileSystem: fileSystem,\n            certPolicyKey: certPolicyKey\n        )\n    }\n}\n\npublic protocol ManifestSignatureValidator {\n    /// Validates a signed package collection.\n    ///\n    /// - Parameters:\n    ///   - signedCollection: The signed package collection\n    ///   - certPolicyKey: The key of the `CertificatePolicy` to use for validating certificates\n    func validate(\n        manifest: any Encodable,\n        signature: ManifestSignature,\n        fileSystem: FileSystem,\n        certPolicyKey: CertificatePolicyKey\n    ) async throws\n}\n\n// MARK: - Implementation\n\npublic actor ManifestSigning: ManifestSigner, ManifestSignatureValidator {\n    private static let minimumRSAKeySizeInBits = 2048\n\n    /// Path of the optional directory containing root certificates to be trusted.\n    private let trustedRootCertsDir: AbsolutePath?\n    /// Root certificates to be trusted in additional to those found in `trustedRootCertsDir`\n    private let additionalTrustedRootCerts: [Certificate]?\n\n    /// Internal cache/storage of `CertificatePolicy`s\n    private let certPolicies: [CertificatePolicyKey: CertificatePolicy]\n\n    private let encoder: JSONEncoder\n    private let decoder: JSONDecoder\n\n    private let observabilityScope: ObservabilityScope\n\n    public init(\n        trustedRootCertsDir: AbsolutePath? = nil,\n        additionalTrustedRootCerts: [String]? = nil,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.trustedRootCertsDir = trustedRootCertsDir\n        self.additionalTrustedRootCerts = additionalTrustedRootCerts.map { $0.compactMap {\n            guard let data = Data(base64Encoded: $0) else {\n                observabilityScope.emit(error: \"The certificate \\($0) is not in valid base64 encoding\")\n                return nil\n            }\n            do {\n                return try Certificate(derEncoded: Array(data))\n            } catch {\n                observabilityScope.emit(\n                    error: \"The certificate \\($0) is not in valid DER format\",\n                    underlyingError: error\n                )\n                return nil\n            }\n        } }\n\n        self.certPolicies = [:]\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n        self.observabilityScope = observabilityScope\n    }\n\n    init(certPolicy: CertificatePolicy, observabilityScope: ObservabilityScope) {\n        // These should be set through the given CertificatePolicy\n        self.trustedRootCertsDir = nil\n        self.additionalTrustedRootCerts = nil\n\n        self.certPolicies = [CertificatePolicyKey.custom: certPolicy]\n        self.encoder = JSONEncoder.makeWithDefaults()\n        self.decoder = JSONDecoder.makeWithDefaults()\n        self.observabilityScope = observabilityScope\n    }\n\n    private func getCertificatePolicy(key: CertificatePolicyKey, fileSystem: FileSystem) throws -> CertificatePolicy {\n        switch key {\n        case .default(let subjectUserID, let subjectOrganizationalUnit):\n            // Create new instance each time since contents of trustedRootCertsDir might change\n            return DefaultCertificatePolicy(\n                trustedRootCertsDir: self.trustedRootCertsDir,\n                fileSystem: fileSystem,\n                additionalTrustedRootCerts: self.additionalTrustedRootCerts,\n                expectedSubjectUserID: subjectUserID,\n                expectedSubjectOrganizationalUnit: subjectOrganizationalUnit,\n                observabilityScope: self.observabilityScope\n            )\n        case .appleSwiftPackageCollection(let subjectUserID, let subjectOrganizationalUnit):\n            // Create new instance each time since contents of trustedRootCertsDir might change\n            return ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: self.trustedRootCertsDir,\n                fileSystem: fileSystem,\n                additionalTrustedRootCerts: self.additionalTrustedRootCerts,\n                expectedSubjectUserID: subjectUserID,\n                expectedSubjectOrganizationalUnit: subjectOrganizationalUnit,\n                observabilityScope: self.observabilityScope\n            )\n        case .appleDistribution(let subjectUserID, let subjectOrganizationalUnit):\n            // Create new instance each time since contents of trustedRootCertsDir might change\n            return ADPAppleDistributionCertificatePolicy(\n                trustedRootCertsDir: self.trustedRootCertsDir,\n                fileSystem: fileSystem,\n                additionalTrustedRootCerts: self.additionalTrustedRootCerts,\n                expectedSubjectUserID: subjectUserID,\n                expectedSubjectOrganizationalUnit: subjectOrganizationalUnit,\n                observabilityScope: self.observabilityScope\n            )\n        case .custom:\n            // Custom `CertificatePolicy` can be set using the internal initializer only\n            guard let certPolicy = self.certPolicies[key] else {\n                throw ManifestSigningError.certPolicyNotFound\n            }\n            return certPolicy\n        }\n    }\n\n    public func sign(\n        manifest: some Encodable,\n        certChainPaths: [AbsolutePath],\n        privateKeyPEM: Data,\n        fileSystem: FileSystem,\n        certPolicyKey: CertificatePolicyKey = .default\n    ) async throws -> ManifestSignature {\n        let certChainData: [Data] = try certChainPaths.map { try fileSystem.readFileContents($0) }\n        // Check that the certificate is valid\n        let certChain = try await self.validateCertChain(certChainData, certPolicyKey: certPolicyKey, fileSystem: fileSystem)\n\n        let privateKeyPEMString = String(decoding: privateKeyPEM, as: UTF8.self)\n\n        let signatureAlgorithm: Signature.Algorithm\n        let signatureProvider: (Data) throws -> Data\n        // Determine key type\n        do {\n            let privateKey = try P256.Signing.PrivateKey(pemRepresentation: privateKeyPEMString)\n            signatureAlgorithm = .ES256\n            signatureProvider = {\n                try privateKey.signature(for: SHA256.hash(data: $0)).rawRepresentation\n            }\n        } catch {\n            do {\n                let privateKey = try _RSA.Signing.PrivateKey(pemRepresentation: privateKeyPEMString)\n\n                guard privateKey.keySizeInBits >= Self.minimumRSAKeySizeInBits else {\n                    throw ManifestSigningError.invalidKeySize(minimumBits: Self.minimumRSAKeySizeInBits)\n                }\n\n                signatureAlgorithm = .RS256\n                signatureProvider = {\n                    try privateKey.signature(for: SHA256.hash(data: $0), padding: Signature.rsaSigningPadding)\n                        .rawRepresentation\n                }\n            } catch let error as ManifestSigningError {\n                throw error\n            } catch {\n                throw ManifestSigningError.unsupportedKeyType\n            }\n        }\n\n        // Generate signature\n        let signatureData = try Signature.generate(\n            payload: manifest,\n            certChainData: certChainData,\n            jsonEncoder: self.encoder,\n            signatureAlgorithm: signatureAlgorithm,\n            signatureProvider: signatureProvider\n        )\n\n        guard let signature = String(bytes: signatureData, encoding: .utf8) else {\n            throw ManifestSigningError.invalidSignature\n        }\n\n        let certificate = certChain.first! // !-safe because certChain cannot be empty at this point\n        return ManifestSignature(\n            signature: signature,\n            certificate: ManifestSignature.Certificate(\n                subject: ManifestSignature.Certificate.Name(from: certificate.subject),\n                issuer: ManifestSignature.Certificate.Name(from: certificate.issuer)\n            )\n        )\n    }\n\n    public func validate(\n        manifest: any Encodable,\n        signature: ManifestSignature,\n        fileSystem: FileSystem,\n        certPolicyKey: CertificatePolicyKey = .default\n    ) async throws {\n        let signatureBytes = Data(signature.signature.utf8).copyBytes()\n\n        // Parse the signature\n        let certChainValidate = { certChainData in\n            try await self.validateCertChain(certChainData, certPolicyKey: certPolicyKey, fileSystem: fileSystem)\n        }\n        let signature = try await Signature.parse(\n            signatureBytes,\n            certChainValidate: certChainValidate,\n            jsonDecoder: self.decoder\n        )\n\n        // Verify the collection embedded in the signature is the same as received\n        // i.e., the signature is associated with the given collection and not another\n        guard try self.encoder.encode(manifest) == signature.payload else {\n            throw ManifestSigningError.invalidSignature\n        }\n    }\n\n    private func validateCertChain(\n        _ certChainData: [Data],\n        certPolicyKey: CertificatePolicyKey,\n        fileSystem: FileSystem\n    ) async throws -> [Certificate] {\n        guard !certChainData.isEmpty else {\n            throw ManifestSigningError.emptyCertChain\n        }\n\n        do {\n            let certChain = try certChainData.map { try Certificate(derEncoded: Array($0)) }\n            let certPolicy = try self.getCertificatePolicy(key: certPolicyKey, fileSystem: fileSystem)\n\n            do {\n                try await certPolicy.validate(certChain: certChain)\n                return certChain\n            } catch {\n                self.observabilityScope.emit(\n                    error: \"\\(certPolicyKey): The certificate chain is invalid\",\n                    underlyingError: error\n                )\n\n                if CertificatePolicyError.noTrustedRootCertsConfigured == error as? CertificatePolicyError {\n                    throw ManifestSigningError.noTrustedRootCertsConfigured\n                } else {\n                    throw ManifestSigningError.invalidCertChain\n                }\n            }\n        } catch let error as ManifestSigningError {\n            throw error\n        } catch {\n            self.observabilityScope.emit(\n                error: \"An error has occurred while validating certificate chain\",\n                underlyingError: error\n            )\n            throw ManifestSigningError.invalidCertChain\n        }\n    }\n}\n\npublic enum ManifestSigningError: Error, Equatable {\n    case certPolicyNotFound\n    case emptyCertChain\n    case noTrustedRootCertsConfigured\n    case invalidCertChain\n\n    case invalidSignature\n\n    case unsupportedKeyType\n    case invalidKeySize(minimumBits: Int)\n}\n\nextension ManifestSignature.Certificate.Name {\n    fileprivate init(from name: DistinguishedName) {\n        self.init(\n            userID: name.userID,\n            commonName: name.commonName,\n            organizationalUnit: name.organizationalUnitName,\n            organization: name.organizationName\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManifestSigning/Signature.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Vapor open source project\n//\n// Copyright (c) 2017-2020 Vapor project authors\n// Licensed under MIT\n//\n// See LICENSE for license information\n//\n// SPDX-License-Identifier: MIT\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import _CryptoExtras\n@_implementationOnly import Crypto\n@_implementationOnly import X509\n#else\nimport _CryptoExtras\nimport Crypto\nimport X509\n#endif\n\n// The logic in this source file loosely follows https://www.rfc-editor.org/rfc/rfc7515.html\n// for JSON Web Signature (JWS).\n\nstruct Signature {\n    let header: Header\n    let payload: Data\n    let signature: Data\n}\n\nextension Signature {\n    enum Algorithm: String, Codable {\n        case RS256 // RSASSA-PKCS1-v1_5 using SHA-256\n        case ES256 // ECDSA using P-256 and SHA-256\n    }\n\n    struct Header: Equatable, Codable {\n        // https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.1\n        let algorithm: Algorithm\n\n        /// Base64 encoded certificate chain\n        let certChain: [String]\n\n        enum CodingKeys: String, CodingKey {\n            case algorithm = \"alg\"\n            case certChain = \"x5c\"\n        }\n    }\n}\n\n// Reference: https://github.com/vapor/jwt-kit/blob/main/Sources/JWTKit/JWTSerializer.swift\nextension Signature {\n    static let rsaSigningPadding = _RSA.Signing.Padding.insecurePKCS1v1_5\n\n    static func generate(\n        payload: some Encodable,\n        certChainData: [Data],\n        jsonEncoder: JSONEncoder,\n        signatureAlgorithm: Signature.Algorithm,\n        signatureProvider: @escaping (Data) throws -> Data\n    ) throws -> Data {\n        let header = Signature.Header(\n            algorithm: signatureAlgorithm,\n            certChain: certChainData.map { $0.base64EncodedString() }\n        )\n        let headerData = try jsonEncoder.encode(header)\n        let encodedHeader = headerData.base64URLEncodedBytes()\n\n        let payloadData = try jsonEncoder.encode(payload)\n        let encodedPayload = payloadData.base64URLEncodedBytes()\n\n        // https://www.rfc-editor.org/rfc/rfc7515.html#section-5.1\n        // Signing input: BASE64URL(header) + '.' + BASE64URL(payload)\n        let signatureData = try signatureProvider(encodedHeader + .period + encodedPayload)\n        let encodedSignature = signatureData.base64URLEncodedBytes()\n\n        // Result: header.payload.signature\n        let bytes = encodedHeader\n            + .period\n            + encodedPayload\n            + .period\n            + encodedSignature\n        return bytes\n    }\n}\n\n// Reference: https://github.com/vapor/jwt-kit/blob/main/Sources/JWTKit/JWTParser.swift\nextension Signature {\n    typealias CertChainValidate = ([Data]) async throws -> [Certificate]\n\n    static func parse(\n        _ signature: String,\n        certChainValidate: CertChainValidate,\n        jsonDecoder: JSONDecoder\n    ) async throws -> Signature {\n        let bytes = Array(signature.utf8)\n        return try await Self.parse(bytes, certChainValidate: certChainValidate, jsonDecoder: jsonDecoder)\n    }\n\n    static func parse(\n        _ signature: some DataProtocol,\n        certChainValidate: CertChainValidate,\n        jsonDecoder: JSONDecoder\n    ) async throws -> Signature {\n        let parts = signature.copyBytes().split(separator: .period)\n        guard parts.count == 3 else {\n            throw SignatureError.malformedSignature\n        }\n\n        let encodedHeader = parts[0]\n        let encodedPayload = parts[1]\n        let encodedSignature = parts[2]\n\n        guard let headerBytes = encodedHeader.base64URLDecodedBytes(),\n              let header = try? jsonDecoder.decode(Header.self, from: headerBytes)\n        else {\n            throw SignatureError.malformedSignature\n        }\n\n        // Signature header contains the certificate and public key for verification\n        let certChainData = header.certChain.compactMap { Data(base64Encoded: $0) }\n        // Make sure we restore all certs successfully\n        guard certChainData.count == header.certChain.count else {\n            throw SignatureError.malformedSignature\n        }\n\n        let certChain = try await certChainValidate(certChainData)\n\n        guard let payloadBytes = encodedPayload.base64URLDecodedBytes(),\n              let signatureBytes = encodedSignature.base64URLDecodedBytes()\n        else {\n            throw SignatureError.malformedSignature\n        }\n\n        // Extract public key from the certificate\n        let certificate = certChain.first! // !-safe because certChain is not empty at this point\n        // Verify the key was used to generate the signature\n        let message = Data(encodedHeader) + .period + Data(encodedPayload)\n        let digest = SHA256.hash(data: message)\n\n        switch header.algorithm {\n        case .ES256:\n            guard let publicKey = P256.Signing.PublicKey(certificate.publicKey) else {\n                throw SignatureError.invalidPublicKey\n            }\n            guard try publicKey.isValidSignature(.init(rawRepresentation: signatureBytes), for: digest)\n            else {\n                throw SignatureError.invalidSignature\n            }\n        case .RS256:\n            guard let publicKey = _RSA.Signing.PublicKey(certificate.publicKey) else {\n                throw SignatureError.invalidPublicKey\n            }\n            guard publicKey.isValidSignature(\n                .init(rawRepresentation: signatureBytes),\n                for: digest,\n                padding: .insecurePKCS1v1_5\n            ) else {\n                throw SignatureError.invalidSignature\n            }\n        }\n\n        return Signature(header: header, payload: payloadBytes, signature: signatureBytes)\n    }\n}\n\nenum SignatureError: Error {\n    case malformedSignature\n    case invalidSignature\n    case invalidPublicKey\n}\n"
  },
  {
    "path": "Sources/Workspace/ManifestSigning/Utilities.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nextension DataProtocol {\n    func copyBytes() -> [UInt8] {\n        [UInt8](unsafeUninitializedCapacity: self.count) { buffer, initializedCount in\n            self.copyBytes(to: buffer)\n            initializedCount = self.count\n        }\n    }\n}\n\nextension UInt8 {\n    static var period: UInt8 {\n        UInt8(ascii: \".\")\n    }\n}\n\n/// Cannot use `extension Data` if `period` is going to be used with\n/// `+` operator via leading-dot syntax, for example: `Data(...) + .period`\n/// because `+` is declared as `(Self, Other) -> Self` where\n/// `Other: RangeReplaceableCollection, Other.Element == Self.Element`\n/// which means that `.period` couldn't get `Data` inferred from the first argument.\nextension RangeReplaceableCollection where Self == Data {\n    static var period: Data {\n        Data([UInt8.period])\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManifestSigning/X509Extensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if USE_IMPL_ONLY_IMPORTS\n@_implementationOnly import SwiftASN1\n@_implementationOnly import X509\n#else\nimport SwiftASN1\nimport X509\n#endif\n\nextension Certificate {\n    func hasExtension(oid: ASN1ObjectIdentifier) -> Bool {\n        self.extensions[oid: oid] != nil\n    }\n}\n\nextension ASN1ObjectIdentifier.NameAttributes {\n    static let userID: ASN1ObjectIdentifier = [0, 9, 2342, 19_200_300, 100, 1, 1]\n\n    // Marker OIDs for ADP certificates\n    static let adpSwiftPackageMarker: ASN1ObjectIdentifier = [1, 2, 840, 113_635, 100, 6, 1, 35]\n    static let adpSwiftPackageCollectionMarker: ASN1ObjectIdentifier = [1, 2, 840, 113_635, 100, 6, 1, 35]\n    static let adpAppleDevelopmentMarkers: [ASN1ObjectIdentifier] = [\n        [1, 2, 840, 113_635, 100, 6, 1, 2],\n        [1, 2, 840, 113_635, 100, 6, 1, 12],\n    ]\n    static let adpAppleDistributionMarkers: [ASN1ObjectIdentifier] = [\n        [1, 2, 840, 113_635, 100, 6, 1, 4],\n        [1, 2, 840, 113_635, 100, 6, 1, 7],\n    ]\n    static let wwdrIntermediateMarkers: [ASN1ObjectIdentifier] = [\n        [1, 2, 840, 113_635, 100, 6, 2, 1],\n        [1, 2, 840, 113_635, 100, 6, 2, 15],\n    ]\n}\n\nextension DistinguishedName {\n    var userID: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.userID)\n    }\n\n    var commonName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.commonName)\n    }\n\n    var organizationalUnitName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.organizationalUnitName)\n    }\n\n    var organizationName: String? {\n        self.stringAttribute(oid: ASN1ObjectIdentifier.NameAttributes.organizationName)\n    }\n\n    private func stringAttribute(oid: ASN1ObjectIdentifier) -> String? {\n        for relativeDistinguishedName in self {\n            for attribute in relativeDistinguishedName where attribute.type == oid {\n                return attribute.value.description\n            }\n        }\n        return nil\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ManifestSigning/embedded_resources.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nstruct PackageResources {\nstatic let AppleWWDRCAG2_cer: [UInt8] = [48,130,2,247,48,130,2,124,160,3,2,1,2,2,8,111,239,216,245,233,163,167,238,48,10,6,8,42,134,72,206,61,4,3,2,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,53,48,54,50,51,52,51,50,52,90,23,13,50,57,48,53,48,54,50,51,52,51,50,52,90,48,129,128,49,52,48,50,6,3,85,4,3,12,43,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,221,240,183,6,75,207,221,115,4,19,196,67,137,3,147,128,251,94,246,116,173,66,97,82,88,2,38,83,25,200,99,34,7,9,82,97,202,196,217,87,239,109,38,104,139,116,145,140,196,249,128,104,40,252,9,104,240,16,218,233,208,46,201,26,163,129,247,48,129,244,48,70,6,8,43,6,1,5,5,7,1,1,4,58,48,56,48,54,6,8,43,6,1,5,5,7,48,1,134,42,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,52,45,97,112,112,108,101,114,111,111,116,99,97,103,51,48,29,6,3,85,29,14,4,22,4,20,132,182,132,204,58,134,98,114,22,89,148,232,26,163,189,72,223,58,223,11,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,31,6,3,85,29,35,4,24,48,22,128,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,55,6,3,85,29,31,4,48,48,46,48,44,160,42,160,40,134,38,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,114,111,111,116,99,97,103,51,46,99,114,108,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,15,4,2,5,0,48,10,6,8,42,134,72,206,61,4,3,2,3,105,0,48,102,2,49,0,217,177,199,49,198,35,246,79,77,208,217,71,197,125,24,105,17,135,113,39,211,104,173,224,155,101,154,190,108,223,63,70,166,144,9,190,110,161,59,44,176,81,137,65,60,135,210,191,2,49,0,252,100,82,137,75,60,93,191,107,28,194,137,152,47,114,174,181,155,170,26,11,35,84,119,84,232,21,67,162,197,18,218,151,80,115,124,94,208,110,178,92,98,80,215,81,241,58,90]\nstatic let AppleWWDRCAG3_cer: [UInt8] = [48,130,4,81,48,130,3,57,160,3,2,1,2,2,16,124,175,105,10,37,183,57,254,123,155,68,122,193,120,197,238,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,48,50,49,57,49,56,49,51,52,55,90,23,13,51,48,48,50,50,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,51,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,216,245,137,252,168,89,11,135,199,76,145,46,45,86,144,211,120,29,164,48,233,165,72,239,11,67,191,45,132,251,36,93,69,27,229,235,89,54,18,92,84,100,158,108,98,45,180,198,151,202,204,60,246,214,6,145,252,229,2,166,28,106,180,121,213,103,203,172,233,63,7,17,225,132,188,71,29,102,142,57,162,232,180,73,237,58,210,225,16,96,122,142,147,140,202,192,218,12,192,131,208,227,249,145,214,167,140,200,193,115,226,174,70,209,98,157,146,168,144,96,55,125,104,150,205,141,224,252,155,250,120,187,227,123,175,45,23,221,91,254,128,89,35,117,23,184,18,193,237,27,229,52,206,254,34,181,158,73,176,229,85,191,143,132,162,60,168,186,197,134,149,22,228,0,201,159,3,208,204,179,58,22,123,214,5,92,157,235,71,174,13,181,45,140,14,105,77,64,208,75,76,59,4,158,141,33,177,172,46,67,84,48,206,193,138,134,148,152,75,223,106,13,63,254,251,28,174,151,23,194,120,10,48,224,95,31,84,59,73,183,37,0,26,55,130,210,86,151,165,82,73,124,96,56,155,239,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,9,254,192,21,144,249,175,100,10,146,18,185,38,40,99,12,151,236,167,178,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,173,101,19,232,246,224,129,119,68,2,71,66,190,95,165,57,32,234,98,169,253,197,144,201,115,19,213,158,155,208,170,15,141,141,203,237,1,207,108,40,64,91,199,85,36,65,248,252,207,193,181,35,233,220,236,241,111,202,128,29,119,194,196,97,73,37,103,175,15,202,57,37,173,211,227,122,204,51,40,13,14,46,161,87,64,115,250,230,92,174,6,81,41,237,227,133,12,79,97,220,50,22,139,119,208,68,202,93,114,3,49,70,156,174,155,64,26,250,244,224,211,62,250,47,140,102,159,151,196,84,89,239,210,72,244,7,153,73,96,89,25,199,221,148,209,192,193,108,127,120,33,239,12,235,59,108,153,130,75,82,96,56,181,57,130,109,236,82,49,83,190,15,145,76,73,73,116,143,166,81,203,132,71,78,29,117,39,110,189,249,210,92,243,127,194,108,11,9,54,226,100,228,194,55,3,20,25,213,234,106,148,170,169,219,254,246,154,8,103,139,239,43,184,170,23,73,131,175,207,203,188,233,207,234,149,113,176,180,69,162,204,229,135,170,10,195,65,58,121,92,218,80,52,157,149,59]\nstatic let AppleWWDRCAG5_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,59,126,128,10,238,211,2,161,230,236,219,151,217,202,172,40,156,241,105,148,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,49,50,49,54,49,57,51,56,53,54,90,23,13,51,48,49,50,49,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,53,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,159,93,218,31,251,250,188,208,75,34,60,199,214,38,250,23,247,244,159,30,62,100,17,102,154,239,94,190,171,52,189,170,44,33,110,214,30,148,33,133,44,116,193,14,16,97,170,60,99,74,126,74,227,200,117,214,207,194,156,8,72,123,106,185,41,177,201,102,253,200,138,22,209,178,4,60,130,186,128,108,226,255,10,114,235,172,254,59,111,72,190,158,139,17,77,149,125,178,123,144,47,2,28,78,252,73,190,215,111,181,79,190,120,198,218,222,178,205,201,217,102,17,59,90,233,9,69,115,137,80,212,78,226,104,5,126,218,117,156,75,1,174,218,227,207,109,116,77,222,83,208,213,26,56,130,58,208,157,227,93,41,123,177,129,234,41,39,11,251,96,124,134,18,251,240,98,79,6,231,76,209,31,217,109,158,237,115,218,120,33,13,157,112,217,70,87,144,95,103,132,193,115,119,10,168,98,98,182,174,112,134,187,117,35,137,173,121,246,230,164,212,253,131,38,50,10,59,36,146,91,32,161,156,209,47,128,24,155,221,60,11,231,181,253,236,128,87,15,23,158,63,43,135,39,187,247,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,25,139,151,141,74,91,97,120,87,244,165,92,53,18,138,57,8,227,176,117,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,90,196,53,162,217,230,10,158,82,162,0,130,34,119,205,114,47,144,249,34,175,20,37,204,170,10,66,96,146,194,189,117,29,235,76,202,21,229,126,107,64,16,94,251,91,69,116,13,240,122,125,136,145,206,222,99,139,66,137,210,24,223,65,179,88,158,6,8,135,72,221,64,175,35,213,237,235,44,96,229,235,164,127,28,233,156,131,214,148,95,76,98,57,138,78,174,19,141,125,67,184,220,94,172,190,24,64,242,230,15,44,93,19,147,241,123,101,168,194,104,72,222,255,180,150,155,12,251,50,54,158,158,13,149,95,56,10,139,150,210,18,108,183,139,11,142,215,62,236,111,1,170,206,77,69,96,219,132,113,102,98,229,25,101,48,205,138,255,69,83,251,110,251,136,119,67,195,72,99,249,247,81,179,114,94,121,226,86,207,188,187,132,185,56,90,120,174,17,72,82,187,13,53,139,148,222,204,116,154,104,245,73,96,148,172,242,168,179,21,134,144,208,204,48,67,134,211,229,112,2,81,180,129,192,168,151,212,234,234,176,140,9,64,239,56,147,178,205,34,3,235,103,67,101,200,69]\nstatic let AppleRootCA_G2_cer: [UInt8] = [48,130,5,146,48,130,3,122,160,3,2,1,2,2,8,1,224,229,181,131,103,163,224,48,13,6,9,42,134,72,134,247,13,1,1,12,5,0,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,52,51,48,49,56,49,48,48,57,90,23,13,51,57,48,52,51,48,49,56,49,48,48,57,90,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,50,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,2,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,2,15,0,48,130,2,10,2,130,2,1,0,216,17,18,72,72,218,41,138,73,197,28,199,236,110,51,109,254,77,251,224,28,222,172,94,226,54,167,36,249,127,80,107,76,206,185,48,84,39,229,179,214,237,37,230,48,182,5,55,94,20,34,17,197,232,170,27,210,251,178,210,9,149,56,164,239,42,73,140,93,62,113,102,3,56,251,22,245,133,136,228,90,146,12,4,50,242,200,64,251,82,95,159,246,192,241,227,186,69,160,80,213,18,139,242,221,222,145,134,35,240,245,182,114,46,1,218,11,246,46,57,8,95,25,161,99,65,11,28,167,148,193,134,196,83,47,118,246,10,215,12,209,131,63,26,83,25,243,87,213,39,127,252,19,184,248,146,141,252,211,40,67,60,181,104,0,37,93,39,98,211,221,85,221,68,32,144,131,53,147,197,191,184,25,251,107,227,220,8,66,230,175,109,250,158,64,202,78,133,133,120,73,177,215,195,193,48,57,50,171,126,95,170,211,139,111,159,45,26,33,104,112,103,179,163,241,152,65,109,145,124,248,215,219,168,231,95,33,26,140,51,191,49,116,183,184,209,244,224,34,244,191,114,52,223,247,129,77,113,125,81,161,226,179,240,211,40,22,115,111,205,204,173,55,125,78,235,173,64,225,63,129,253,247,61,10,62,162,241,189,49,150,41,89,220,194,25,128,140,91,116,198,44,211,16,83,38,29,20,79,196,212,129,102,60,135,103,51,39,20,8,233,180,119,132,52,82,143,137,248,104,152,23,191,195,187,170,19,147,31,93,84,47,168,199,124,251,13,20,190,21,61,36,52,242,154,220,117,65,102,34,180,1,214,11,175,144,158,12,234,98,248,155,89,60,8,226,150,52,228,99,222,188,55,212,235,12,136,3,67,11,80,175,160,52,221,80,77,21,251,90,36,216,12,250,12,99,158,31,3,177,225,238,225,170,67,244,102,101,40,55,2,49,239,1,199,30,209,204,159,109,202,84,58,64,219,206,207,79,70,139,74,101,154,106,198,104,108,215,204,153,27,71,176,114,195,119,143,196,247,97,156,116,31,206,253,107,161,194,156,148,130,171,148,162,231,189,27,186,185,112,57,149,23,197,41,243,57,88,52,245,196,164,198,123,96,185,102,67,80,63,110,97,252,14,249,134,170,96,12,67,75,149,2,3,1,0,1,163,66,48,64,48,29,6,3,85,29,14,4,22,4,20,196,153,19,108,24,3,194,123,192,163,160,13,127,114,128,122,28,119,38,141,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,13,6,9,42,134,72,134,247,13,1,1,12,5,0,3,130,2,1,0,81,166,243,226,244,184,61,147,191,45,206,15,187,91,225,85,20,78,78,209,229,206,121,93,129,127,254,182,240,135,51,248,239,148,229,126,220,106,121,167,28,190,240,148,183,166,209,48,156,200,13,10,117,158,125,146,149,126,24,157,126,194,113,105,124,20,234,207,131,14,228,20,66,158,116,14,16,205,171,26,186,17,97,129,120,216,241,181,69,64,120,171,168,192,206,251,125,99,55,104,246,231,251,175,198,195,75,236,31,54,38,19,84,134,148,114,178,234,2,237,139,109,228,12,166,144,192,87,117,207,140,66,125,92,230,49,125,243,201,178,146,105,70,14,136,248,227,45,66,178,56,168,166,25,141,241,159,205,238,106,101,188,26,176,37,189,167,41,253,244,62,162,117,73,191,158,219,201,247,167,30,99,153,225,92,70,255,146,5,140,250,30,32,249,134,148,86,37,229,180,87,56,157,235,136,100,20,33,73,33,57,191,98,102,169,177,162,202,111,63,33,96,197,137,212,69,54,200,152,124,189,246,254,153,73,128,59,44,210,166,167,136,3,4,49,25,183,182,58,97,69,250,201,242,35,200,99,115,191,86,137,49,176,217,124,98,167,123,21,168,136,138,171,56,64,194,204,18,255,21,227,240,55,223,55,114,203,204,152,230,191,162,188,250,38,138,113,86,215,231,36,27,72,68,62,158,252,159,201,204,26,236,67,60,1,188,52,120,200,105,245,198,230,86,236,6,9,54,144,235,20,74,27,94,201,136,35,218,3,48,145,11,184,54,62,249,231,181,40,111,190,63,236,60,143,101,29,229,192,30,135,164,170,186,152,253,146,227,108,38,119,221,6,180,100,6,135,244,78,214,186,74,170,22,168,244,5,103,102,150,186,226,85,121,195,44,93,73,143,128,73,43,138,18,199,118,128,81,223,186,189,101,93,62,55,71,99,49,233,229,244,197,63,75,173,4,138,122,113,44,175,9,67,55,15,168,227,50,79,244,69,182,109,151,54,236,132,245,10,1,234,23,187,133,141,66,147,112,195,80,229,20,139,191,63,195,65,15,221,34,4,35,8,138,186,109,113,68,171,115,9,58,201,249,82,128,9,223,186,233,230,22,202,46,46,76,178,211,220,229,4,84,178,212,52,128,50,181,188,15,23,225]\nstatic let AppleComputerRootCertificate_cer: [UInt8] = [48,130,5,186,48,130,4,162,160,3,2,1,2,2,1,1,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,129,134,49,11,48,9,6,3,85,4,6,19,2,85,83,49,29,48,27,6,3,85,4,10,19,20,65,112,112,108,101,32,67,111,109,112,117,116,101,114,44,32,73,110,99,46,49,45,48,43,6,3,85,4,11,19,36,65,112,112,108,101,32,67,111,109,112,117,116,101,114,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,49,41,48,39,6,3,85,4,3,19,32,65,112,112,108,101,32,82,111,111,116,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,48,30,23,13,48,53,48,50,49,48,48,48,49,56,49,52,90,23,13,50,53,48,50,49,48,48,48,49,56,49,52,90,48,129,134,49,11,48,9,6,3,85,4,6,19,2,85,83,49,29,48,27,6,3,85,4,10,19,20,65,112,112,108,101,32,67,111,109,112,117,116,101,114,44,32,73,110,99,46,49,45,48,43,6,3,85,4,11,19,36,65,112,112,108,101,32,67,111,109,112,117,116,101,114,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,49,41,48,39,6,3,85,4,3,19,32,65,112,112,108,101,32,82,111,111,116,32,67,101,114,116,105,102,105,99,97,116,101,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,228,145,169,9,31,145,219,30,71,80,235,5,237,94,121,132,45,235,54,162,87,76,85,236,139,25,137,222,249,75,108,245,7,171,34,48,2,232,24,62,248,80,9,211,127,65,168,152,249,209,202,102,156,36,107,17,208,163,187,228,27,42,195,31,149,158,122,12,164,71,139,91,212,22,55,51,203,196,15,77,206,20,105,209,201,25,114,245,93,14,213,127,95,155,242,37,3,186,85,143,77,93,13,241,100,53,35,21,75,21,89,29,179,148,247,246,156,158,207,80,186,193,88,80,103,143,8,180,32,247,203,172,44,32,111,112,182,63,1,48,140,183,67,207,15,157,61,243,43,73,40,26,200,254,206,181,185,14,217,94,28,214,203,61,181,58,173,244,15,14,0,146,11,177,33,22,46,116,213,60,13,219,98,22,171,163,113,146,71,83,85,193,175,47,65,179,248,251,227,112,205,230,163,76,69,126,31,76,107,80,150,65,137,196,116,98,11,16,131,65,135,51,138,129,177,48,88,236,90,4,50,140,104,179,143,29,222,101,115,255,103,94,101,188,73,216,118,159,51,20,101,161,119,148,201,45,2,3,1,0,1,163,130,2,47,48,130,2,43,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,29,6,3,85,29,14,4,22,4,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,130,1,41,6,3,85,29,32,4,130,1,32,48,130,1,28,48,130,1,24,6,9,42,134,72,134,247,99,100,5,1,48,130,1,9,48,65,6,8,43,6,1,5,5,7,2,1,22,53,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,116,101,114,109,115,46,104,116,109,108,48,129,195,6,8,43,6,1,5,5,7,2,2,48,129,182,26,129,179,82,101,108,105,97,110,99,101,32,111,110,32,116,104,105,115,32,99,101,114,116,105,102,105,99,97,116,101,32,98,121,32,97,110,121,32,112,97,114,116,121,32,97,115,115,117,109,101,115,32,97,99,99,101,112,116,97,110,99,101,32,111,102,32,116,104,101,32,116,104,101,110,32,97,112,112,108,105,99,97,98,108,101,32,115,116,97,110,100,97,114,100,32,116,101,114,109,115,32,97,110,100,32,99,111,110,100,105,116,105,111,110,115,32,111,102,32,117,115,101,44,32,99,101,114,116,105,102,105,99,97,116,101,32,112,111,108,105,99,121,32,97,110,100,32,99,101,114,116,105,102,105,99,97,116,105,111,110,32,112,114,97,99,116,105,99,101,32,115,116,97,116,101,109,101,110,116,115,46,48,68,6,3,85,29,31,4,61,48,59,48,57,160,55,160,53,134,51,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,114,111,111,116,46,99,114,108,48,85,6,8,43,6,1,5,5,7,1,1,4,73,48,71,48,69,6,8,43,6,1,5,5,7,48,2,134,57,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,99,101,114,116,105,102,105,99,97,116,101,97,117,116,104,111,114,105,116,121,47,99,97,115,105,103,110,101,114,115,46,104,116,109,108,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,157,218,45,40,88,47,125,118,4,185,4,211,62,206,183,102,99,78,143,47,212,254,75,173,114,189,163,57,198,82,77,5,152,82,245,137,81,1,36,121,190,26,50,247,229,68,139,75,68,7,57,130,214,90,202,180,32,94,217,174,21,93,29,140,29,50,191,56,49,98,72,93,199,225,144,177,248,36,64,248,95,88,155,81,93,87,157,193,229,255,60,204,114,33,110,196,233,233,161,119,215,44,23,38,195,63,235,154,232,11,3,186,233,179,74,114,235,51,9,91,173,230,98,49,106,232,175,47,213,175,30,87,118,143,127,55,45,46,2,92,221,99,201,242,113,184,38,64,223,21,141,117,68,63,121,189,230,29,153,225,67,44,62,173,111,190,185,164,254,14,53,25,81,99,177,195,222,181,146,62,81,120,1,115,138,164,35,202,164,136,241,30,92,31,65,22,45,126,149,10,170,233,137,65,152,27,26,221,203,32,191,71,94,12,38,197,85,53,77,198,48,139,153,103,20,199,9,31,186,71,199,218,1,9,135,36,66,149,189,19,96,25,10,239,234,127,14,110,205,193,68,67,58,74,213,227]\nstatic let AppleWWDRCAG7_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,52,24,88,255,1,254,6,63,142,241,159,31,233,60,1,180,193,70,255,201,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,50,49,49,49,55,50,48,52,48,53,51,90,23,13,50,51,49,49,49,55,50,48,52,48,53,50,90,48,117,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,11,12,2,71,55,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,172,174,209,211,182,138,177,27,40,149,173,222,81,81,76,63,51,225,78,92,175,179,252,2,210,101,79,42,212,116,104,140,117,23,101,207,40,228,72,9,152,113,82,50,44,22,78,120,142,146,86,100,169,221,139,205,226,212,199,59,162,18,69,55,2,25,98,100,47,127,97,198,211,89,34,191,171,249,20,163,237,182,158,153,186,47,241,177,220,48,66,79,182,182,178,198,116,170,98,86,187,237,68,54,15,209,229,32,116,147,87,58,93,158,220,1,252,120,111,105,22,53,195,110,1,194,158,114,212,113,54,177,118,9,122,190,13,42,151,241,176,94,11,27,18,173,43,171,7,223,99,45,245,136,233,50,18,162,85,88,67,118,60,61,23,128,31,41,219,177,169,159,171,150,5,157,21,220,221,219,78,15,231,19,124,90,43,46,2,65,246,238,122,106,182,115,96,247,151,25,20,139,149,51,56,147,218,0,37,54,174,85,90,124,159,249,244,98,4,7,116,233,29,167,149,87,35,172,43,36,218,100,79,40,114,233,150,176,8,60,136,27,20,99,67,215,137,174,152,193,242,45,142,227,81,37,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,93,66,16,108,27,187,199,82,151,78,68,189,19,39,185,58,18,119,131,43,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,82,163,8,41,19,101,183,181,31,230,52,3,237,246,24,119,188,61,202,39,181,112,236,236,108,51,75,246,153,37,148,7,158,33,51,3,106,245,125,10,46,43,223,8,169,130,222,74,127,225,231,11,75,5,184,39,152,73,221,193,12,134,215,129,100,174,130,156,196,69,241,234,143,28,34,48,227,162,37,97,68,137,254,133,122,86,240,114,146,124,12,68,84,36,183,181,164,159,38,240,50,249,87,157,106,121,108,64,237,15,52,6,6,66,255,216,14,49,101,109,230,46,1,217,6,191,197,202,13,174,71,212,5,23,136,60,233,156,228,25,100,109,138,148,173,17,220,1,246,229,120,175,173,232,112,215,13,93,129,62,70,42,44,174,36,161,199,210,224,125,191,29,245,54,107,197,222,169,10,154,128,177,17,94,178,100,126,179,193,87,204,194,108,89,153,183,244,176,221,49,218,72,214,106,129,238,178,139,80,53,22,230,231,92,113,98,110,176,242,81,226,168,109,248,42,203,104,115,198,166,196,26,67,73,1,62,169,169,0,138,134,108,131,136,210,92,112,87,122,218,248,118,204,25,213,176]\nstatic let AppleIncRootCertificate_cer: [UInt8] = [48,130,4,187,48,130,3,163,160,3,2,1,2,2,1,2,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,48,54,48,52,50,53,50,49,52,48,51,54,90,23,13,51,53,48,50,48,57,50,49,52,48,51,54,90,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,228,145,169,9,31,145,219,30,71,80,235,5,237,94,121,132,45,235,54,162,87,76,85,236,139,25,137,222,249,75,108,245,7,171,34,48,2,232,24,62,248,80,9,211,127,65,168,152,249,209,202,102,156,36,107,17,208,163,187,228,27,42,195,31,149,158,122,12,164,71,139,91,212,22,55,51,203,196,15,77,206,20,105,209,201,25,114,245,93,14,213,127,95,155,242,37,3,186,85,143,77,93,13,241,100,53,35,21,75,21,89,29,179,148,247,246,156,158,207,80,186,193,88,80,103,143,8,180,32,247,203,172,44,32,111,112,182,63,1,48,140,183,67,207,15,157,61,243,43,73,40,26,200,254,206,181,185,14,217,94,28,214,203,61,181,58,173,244,15,14,0,146,11,177,33,22,46,116,213,60,13,219,98,22,171,163,113,146,71,83,85,193,175,47,65,179,248,251,227,112,205,230,163,76,69,126,31,76,107,80,150,65,137,196,116,98,11,16,131,65,135,51,138,129,177,48,88,236,90,4,50,140,104,179,143,29,222,101,115,255,103,94,101,188,73,216,118,159,51,20,101,161,119,148,201,45,2,3,1,0,1,163,130,1,122,48,130,1,118,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,29,6,3,85,29,14,4,22,4,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,130,1,17,6,3,85,29,32,4,130,1,8,48,130,1,4,48,130,1,0,6,9,42,134,72,134,247,99,100,5,1,48,129,242,48,42,6,8,43,6,1,5,5,7,2,1,22,30,104,116,116,112,115,58,47,47,119,119,119,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,99,97,47,48,129,195,6,8,43,6,1,5,5,7,2,2,48,129,182,26,129,179,82,101,108,105,97,110,99,101,32,111,110,32,116,104,105,115,32,99,101,114,116,105,102,105,99,97,116,101,32,98,121,32,97,110,121,32,112,97,114,116,121,32,97,115,115,117,109,101,115,32,97,99,99,101,112,116,97,110,99,101,32,111,102,32,116,104,101,32,116,104,101,110,32,97,112,112,108,105,99,97,98,108,101,32,115,116,97,110,100,97,114,100,32,116,101,114,109,115,32,97,110,100,32,99,111,110,100,105,116,105,111,110,115,32,111,102,32,117,115,101,44,32,99,101,114,116,105,102,105,99,97,116,101,32,112,111,108,105,99,121,32,97,110,100,32,99,101,114,116,105,102,105,99,97,116,105,111,110,32,112,114,97,99,116,105,99,101,32,115,116,97,116,101,109,101,110,116,115,46,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,92,54,153,76,45,120,183,237,140,155,220,243,119,155,242,118,210,119,48,79,193,31,133,131,133,27,153,61,71,55,242,169,155,64,142,44,212,177,144,18,216,190,244,115,155,238,210,100,15,203,121,79,52,216,162,62,249,120,255,107,200,7,236,125,57,131,139,83,32,211,56,196,177,191,154,79,10,107,255,43,252,89,167,5,9,124,23,64,86,17,30,116,211,183,139,35,59,71,163,213,111,36,226,235,209,183,112,223,15,69,225,39,202,241,109,120,237,231,181,23,23,168,220,126,34,53,202,37,213,217,15,214,107,212,162,36,35,17,247,161,172,143,115,129,96,198,27,91,9,47,146,178,248,68,72,240,96,56,158,21,245,61,38,103,32,138,51,106,247,13,130,207,222,235,163,47,249,83,106,91,100,192,99,51,119,247,58,7,44,86,235,218,15,33,14,218,186,115,25,79,181,217,54,127,193,135,85,217,167,153,185,50,66,251,216,213,113,158,126,161,82,183,27,189,147,66,36,18,42,199,15,29,182,77,156,94,99,200,75,128,23,80,170,138,213,218,228,252,208,9,7,55,176,117,117,33]\nstatic let AppleWWDRCAG4_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,19,220,119,149,82,113,229,61,198,50,232,204,255,229,33,243,204,197,206,210,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,48,49,50,49,54,49,57,51,54,48,52,90,23,13,51,48,49,50,49,48,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,52,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,208,31,120,170,122,39,50,176,70,95,231,23,118,216,160,157,14,41,142,173,61,50,165,196,107,55,201,228,65,145,106,183,121,113,93,12,52,4,96,117,247,174,67,143,71,196,134,30,8,232,191,214,57,82,47,30,103,252,113,241,130,109,60,126,6,82,118,157,44,188,213,67,233,177,180,188,64,58,120,81,93,81,161,37,225,190,108,145,157,107,33,89,24,65,213,15,141,109,65,42,57,74,33,224,144,159,78,19,79,208,140,154,50,184,215,106,146,30,37,106,164,50,206,34,25,133,5,96,220,2,74,242,90,235,119,121,2,125,192,151,84,108,146,142,118,1,230,70,143,229,230,42,251,162,176,173,24,173,109,51,133,56,35,139,234,138,150,237,159,174,102,79,163,12,64,39,109,149,208,98,136,217,67,41,39,253,237,164,191,83,46,144,21,101,60,217,46,98,100,51,29,108,106,221,142,33,170,164,95,21,198,48,237,95,230,140,54,146,148,183,220,57,2,0,251,100,140,212,12,129,242,63,213,52,151,135,117,38,194,111,174,3,99,33,12,123,212,27,177,98,197,2,156,189,253,175,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,91,217,250,29,231,154,26,11,163,153,118,34,80,134,62,145,200,91,119,168,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,3,130,1,1,0,63,86,61,158,229,182,195,121,230,69,32,104,189,191,115,139,44,18,158,2,227,174,128,34,140,4,30,195,82,200,112,128,168,251,206,167,176,213,66,68,130,3,130,79,6,252,59,73,20,251,216,116,82,133,175,167,157,33,231,1,18,3,159,205,64,88,208,1,215,191,50,131,43,83,88,40,60,238,156,159,84,118,61,100,39,198,126,141,29,56,77,45,174,129,230,185,165,184,156,137,148,247,159,199,135,165,81,102,52,27,57,113,57,36,227,135,103,239,165,177,104,123,140,238,61,247,174,182,123,226,210,255,223,97,198,106,117,73,149,34,68,168,4,252,148,184,11,46,57,17,73,18,209,229,129,234,89,0,79,91,60,90,54,218,122,34,115,9,9,105,205,192,124,234,226,36,254,152,68,184,248,239,178,113,63,26,93,212,93,126,51,77,156,29,36,190,0,240,144,3,88,153,65,61,49,90,98,64,175,57,168,81,67,146,171,4,168,156,194,77,177,75,210,171,124,74,95,235,157,59,188,79,136,64,6,19,255,144,23,138,8,71,41,232,98,152,41,165,79,17,5,105,58,207,242,159]\nstatic let AppleWWDRCAG6_cer: [UInt8] = [48,130,3,22,48,130,2,156,160,3,2,1,2,2,20,34,193,161,71,10,116,115,105,239,83,134,18,201,198,159,61,56,243,108,215,48,10,6,8,42,134,72,206,61,4,3,3,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,50,49,48,51,49,55,50,48,51,55,49,48,90,23,13,51,54,48,51,49,57,48,48,48,48,48,48,90,48,117,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,11,48,9,6,3,85,4,11,12,2,71,54,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,118,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,3,98,0,4,110,196,10,11,222,15,174,85,166,101,121,215,130,220,115,117,82,75,241,61,18,25,137,224,13,17,169,158,9,247,55,163,211,240,147,4,111,177,67,139,134,193,152,248,66,157,157,255,178,174,143,23,247,6,112,165,214,176,190,111,58,215,145,135,34,120,231,29,192,72,254,220,56,31,154,106,143,116,125,202,113,74,255,196,100,86,231,136,6,205,129,145,161,34,26,72,163,129,250,48,129,247,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,70,6,8,43,6,1,5,5,7,1,1,4,58,48,56,48,54,6,8,43,6,1,5,5,7,48,1,134,42,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,103,51,48,55,6,3,85,29,31,4,48,48,46,48,44,160,42,160,40,134,38,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,97,112,112,108,101,114,111,111,116,99,97,103,51,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,63,47,148,35,81,211,80,201,154,40,61,237,176,124,229,207,165,144,98,153,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,10,6,8,42,134,72,206,61,4,3,3,3,104,0,48,101,2,48,64,94,20,170,228,140,138,162,3,2,62,220,56,247,64,90,7,174,251,9,161,6,37,123,159,64,31,196,169,145,157,232,36,163,136,43,78,158,227,19,109,117,87,155,28,92,197,249,2,49,0,211,72,252,90,173,149,239,54,185,49,83,116,228,80,194,55,223,44,239,21,85,81,79,140,49,88,144,189,247,131,172,117,198,120,249,17,141,177,128,242,71,152,38,118,189,39,12,104]\nstatic let AppleWWDRCAG8_cer: [UInt8] = [48,130,4,85,48,130,3,61,160,3,2,1,2,2,20,84,181,11,175,121,13,141,127,140,175,104,76,86,47,80,105,10,26,186,95,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,48,98,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,19,10,65,112,112,108,101,32,73,110,99,46,49,38,48,36,6,3,85,4,11,19,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,22,48,20,6,3,85,4,3,19,13,65,112,112,108,101,32,82,111,111,116,32,67,65,48,30,23,13,50,51,48,54,50,48,50,51,51,55,49,53,90,23,13,50,53,48,49,50,52,48,48,48,48,48,48,90,48,117,49,11,48,9,6,3,85,4,6,19,2,85,83,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,11,12,2,71,56,49,68,48,66,6,3,85,4,3,12,59,65,112,112,108,101,32,87,111,114,108,100,119,105,100,101,32,68,101,118,101,108,111,112,101,114,32,82,101,108,97,116,105,111,110,115,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,48,130,1,34,48,13,6,9,42,134,72,134,247,13,1,1,1,5,0,3,130,1,15,0,48,130,1,10,2,130,1,1,0,208,64,16,212,8,249,82,33,99,79,60,104,247,212,156,130,2,140,131,104,188,183,141,127,136,231,66,77,44,239,34,165,194,137,222,189,12,215,77,97,80,45,57,228,48,115,165,210,213,104,154,51,242,239,217,42,173,46,31,3,186,248,165,241,66,11,87,46,70,198,208,88,211,112,95,247,178,55,239,106,31,62,191,137,57,194,173,254,245,5,251,88,150,49,200,135,44,213,35,186,117,176,44,245,171,160,186,242,32,12,76,235,36,99,105,233,34,64,240,142,88,91,222,100,123,137,27,81,18,4,224,23,178,89,205,223,241,231,206,175,44,50,232,105,193,208,8,126,29,162,71,115,209,75,59,253,185,133,220,71,167,40,130,121,41,72,137,2,40,226,193,236,44,31,91,134,252,216,182,203,113,192,115,1,75,252,5,17,17,108,1,3,52,90,246,129,194,94,31,124,20,14,222,63,107,33,203,79,245,215,97,230,132,3,146,188,231,37,41,158,205,91,12,193,219,227,196,58,217,118,87,172,47,56,20,25,200,183,177,162,85,79,95,78,142,25,89,169,218,253,114,218,176,4,33,5,2,3,1,0,1,163,129,239,48,129,236,48,18,6,3,85,29,19,1,1,255,4,8,48,6,1,1,255,2,1,0,48,31,6,3,85,29,35,4,24,48,22,128,20,43,208,105,71,148,118,9,254,244,107,141,46,64,166,247,71,77,127,8,94,48,68,6,8,43,6,1,5,5,7,1,1,4,56,48,54,48,52,6,8,43,6,1,5,5,7,48,1,134,40,104,116,116,112,58,47,47,111,99,115,112,46,97,112,112,108,101,46,99,111,109,47,111,99,115,112,48,51,45,97,112,112,108,101,114,111,111,116,99,97,48,46,6,3,85,29,31,4,39,48,37,48,35,160,33,160,31,134,29,104,116,116,112,58,47,47,99,114,108,46,97,112,112,108,101,46,99,111,109,47,114,111,111,116,46,99,114,108,48,29,6,3,85,29,14,4,22,4,20,181,189,188,128,196,12,227,56,164,244,183,173,35,179,239,68,206,185,90,133,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,16,6,10,42,134,72,134,247,99,100,6,2,1,4,2,5,0,48,13,6,9,42,134,72,134,247,13,1,1,5,5,0,3,130,1,1,0,76,179,235,122,57,148,74,149,102,250,22,49,234,13,138,143,93,66,56,198,7,205,232,201,34,172,252,8,66,126,95,147,95,49,42,168,34,193,118,25,43,238,174,114,233,189,86,207,73,36,146,8,247,205,25,117,195,249,26,39,13,14,220,41,141,63,182,219,165,79,76,114,196,96,145,137,17,126,36,149,67,34,96,103,188,223,255,171,229,60,22,23,157,130,20,78,157,244,117,254,80,185,173,5,178,184,121,246,149,214,16,229,246,83,244,207,35,230,119,15,236,184,75,105,248,226,158,2,49,217,142,217,202,190,99,94,95,225,160,105,206,193,205,110,73,163,120,97,175,57,60,106,75,10,52,37,100,213,48,181,60,171,221,17,129,57,113,232,192,195,88,128,17,16,26,17,210,194,188,89,240,138,217,53,115,192,230,109,228,201,125,98,20,62,130,2,169,16,105,55,121,97,111,240,70,148,62,53,245,171,172,99,208,216,94,89,87,105,209,184,75,110,93,212,95,19,156,112,78,37,17,220,36,44,30,22,158,150,90,4,237,69,238,58,238,103,93,143,195,134,176,245,76,31,104,16]\nstatic let AppleRootCA_G3_cer: [UInt8] = [48,130,2,67,48,130,1,201,160,3,2,1,2,2,8,45,197,252,136,210,197,75,149,48,10,6,8,42,134,72,206,61,4,3,3,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,30,23,13,49,52,48,52,51,48,49,56,49,57,48,54,90,23,13,51,57,48,52,51,48,49,56,49,57,48,54,90,48,103,49,27,48,25,6,3,85,4,3,12,18,65,112,112,108,101,32,82,111,111,116,32,67,65,32,45,32,71,51,49,38,48,36,6,3,85,4,11,12,29,65,112,112,108,101,32,67,101,114,116,105,102,105,99,97,116,105,111,110,32,65,117,116,104,111,114,105,116,121,49,19,48,17,6,3,85,4,10,12,10,65,112,112,108,101,32,73,110,99,46,49,11,48,9,6,3,85,4,6,19,2,85,83,48,118,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,34,3,98,0,4,152,233,47,61,64,114,164,237,147,34,114,129,19,28,221,16,149,241,197,163,78,113,220,20,22,217,14,229,166,5,42,119,100,123,95,78,56,211,187,28,68,181,127,245,31,182,50,98,93,201,233,132,91,79,48,79,17,90,0,253,88,88,12,165,245,15,44,77,7,71,19,117,218,151,151,151,111,49,92,237,43,157,123,32,59,216,185,84,217,94,153,164,58,81,10,49,163,66,48,64,48,29,6,3,85,29,14,4,22,4,20,187,176,222,161,88,51,136,154,164,138,153,222,190,189,235,175,218,203,36,171,48,15,6,3,85,29,19,1,1,255,4,5,48,3,1,1,255,48,14,6,3,85,29,15,1,1,255,4,4,3,2,1,6,48,10,6,8,42,134,72,206,61,4,3,3,3,104,0,48,101,2,49,0,131,233,193,196,22,94,26,93,52,24,217,237,239,244,108,14,0,70,75,184,223,178,70,17,197,15,253,230,122,140,161,166,107,206,194,3,212,156,245,147,198,116,184,106,223,170,35,21,2,48,109,102,138,16,202,212,13,212,79,205,141,67,62,180,138,99,165,51,110,227,109,218,23,183,100,31,200,83,38,249,136,98,116,57,11,23,91,203,81,168,12,232,24,3,231,162,178,40]\n}\n"
  },
  {
    "path": "Sources/Workspace/PackageContainer/FileSystemPackageContainer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\n\nimport struct TSCUtility.Version\n\n/// Local file system package container.\n///\n/// This class represent packages that are referenced locally in the file system.\n/// There is no need to perform any git operations on such packages and they\n/// should be used as-is. In fact, they might not even have a git repository.\n/// Examples: Root packages, local dependencies, edited packages.\npublic struct FileSystemPackageContainer: PackageContainer {\n    public let package: PackageReference\n    private let identityResolver: IdentityResolver\n    private let dependencyMapper: DependencyMapper\n    private let manifestLoader: ManifestLoaderProtocol\n    private let currentToolsVersion: ToolsVersion\n\n    /// File system that should be used to load this package.\n    private let fileSystem: FileSystem\n\n    /// Observability scope to emit diagnostics\n    private let observabilityScope: ObservabilityScope\n\n    /// cached version of the manifest\n    private let manifest = AsyncThrowingValueMemoizer<Manifest>()\n\n    public init(\n        package: PackageReference,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        manifestLoader: ManifestLoaderProtocol,\n        currentToolsVersion: ToolsVersion,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        switch package.kind {\n        case .root, .fileSystem:\n            break\n        default:\n            throw InternalError(\"invalid package type \\(package.kind)\")\n        }\n        self.package = package\n        self.identityResolver = identityResolver\n        self.dependencyMapper = dependencyMapper\n        self.manifestLoader = manifestLoader\n        self.currentToolsVersion = currentToolsVersion\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope.makeChildScope(\n            description: \"FileSystemPackageContainer\",\n            metadata: package.diagnosticsMetadata)\n    }\n\n    private func loadManifest() async throws -> Manifest {\n        try await manifest.memoize {\n            let packagePath: AbsolutePath\n            switch self.package.kind {\n            case .root(let path), .fileSystem(let path):\n                packagePath = path\n            default:\n                throw InternalError(\"invalid package type \\(package.kind)\")\n            }\n\n            // Load the manifest.\n            return try await manifestLoader.load(\n                packagePath: packagePath,\n                packageIdentity: self.package.identity,\n                packageKind: self.package.kind,\n                packageLocation: self.package.locationString,\n                packageVersion: nil,\n                currentToolsVersion: self.currentToolsVersion,\n                identityResolver: self.identityResolver,\n                dependencyMapper: self.dependencyMapper,\n                fileSystem: self.fileSystem,\n                observabilityScope: self.observabilityScope,\n                delegateQueue: .sharedConcurrent\n            )\n        }\n    }\n\n    public func getUnversionedDependencies(productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) async throws -> [PackageContainerConstraint] {\n        let manifest = try await self.loadManifest()\n        return try manifest.dependencyConstraints(productFilter: productFilter, enabledTraits)\n    }\n\n    public func loadPackageReference(at boundVersion: BoundVersion) async throws -> PackageReference {\n        assert(boundVersion == .unversioned, \"Unexpected bound version \\(boundVersion)\")\n        let manifest = try await loadManifest()\n        return package.withName(manifest.displayName)\n    }\n\n    public func isToolsVersionCompatible(at version: Version) -> Bool {\n        fatalError(\"This should never be called\")\n    }\n\n    public func toolsVersion(for version: Version) throws -> ToolsVersion {\n        fatalError(\"This should never be called\")\n    }\n\n    public func toolsVersionsAppropriateVersionsDescending() throws -> [Version] {\n        fatalError(\"This should never be called\")\n    }\n\n    public func versionsAscending() throws -> [Version] {\n        fatalError(\"This should never be called\")\n    }\n\n    public func getDependencies(at version: Version, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        fatalError(\"This should never be called\")\n    }\n\n    public func getDependencies(at revision: String, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        fatalError(\"This should never be called\")\n    }\n}\n\nextension FileSystemPackageContainer: CustomStringConvertible  {\n    public var description: String {\n        return \"FileSystemPackageContainer(\\(self.package.identity))\"\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/PackageContainer/RegistryPackageContainer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport PackageRegistry\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\npublic class RegistryPackageContainer: PackageContainer {\n    public let package: PackageReference\n\n    private let registryClient: RegistryClient\n    private let identityResolver: IdentityResolver\n    private let dependencyMapper: DependencyMapper\n    private let manifestLoader: ManifestLoaderProtocol\n    private let currentToolsVersion: ToolsVersion\n    private let observabilityScope: ObservabilityScope\n\n    private var knownVersionsCache = AsyncThrowingValueMemoizer<[Version]>()\n    private var toolsVersionsCache = ThrowingAsyncKeyValueMemoizer<Version, ToolsVersion>()\n    private var validToolsVersionsCache = AsyncKeyValueMemoizer<Version, Bool>()\n    private var manifestsCache = ThrowingAsyncKeyValueMemoizer<Version, Manifest>()\n    private var availableManifestsCache = ThreadSafeKeyValueStore<Version, (manifests: [String: (toolsVersion: ToolsVersion, content: String?)], fileSystem: FileSystem)>()\n\n    public init(\n        package: PackageReference,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        registryClient: RegistryClient,\n        manifestLoader: ManifestLoaderProtocol,\n        currentToolsVersion: ToolsVersion,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.package = package\n        self.identityResolver = identityResolver\n        self.dependencyMapper = dependencyMapper\n        self.registryClient = registryClient\n        self.manifestLoader = manifestLoader\n        self.currentToolsVersion = currentToolsVersion\n        self.observabilityScope = observabilityScope.makeChildScope(\n            description: \"RegistryPackageContainer\",\n            metadata: package.diagnosticsMetadata)\n    }\n\n    // MARK: - PackageContainer\n\n    public func isToolsVersionCompatible(at version: Version) async -> Bool {\n        await self.validToolsVersionsCache.memoize(version) {\n            do {\n                let toolsVersion = try await self.toolsVersion(for: version)\n                try toolsVersion.validateToolsVersion(self.currentToolsVersion, packageIdentity: self.package.identity)\n                return true\n            } catch {\n                return false\n            }\n        }\n    }\n\n    public func toolsVersion(for version: Version) async throws -> ToolsVersion {\n        try await self.toolsVersionsCache.memoize(version) {\n            let result = try await self.getAvailableManifestsFilesystem(version: version)\n            // find the manifest path and parse it's tools-version\n            let manifestPath = try ManifestLoader.findManifest(packagePath: .root, fileSystem: result.fileSystem, currentToolsVersion: self.currentToolsVersion)\n            return try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: result.fileSystem)\n        }\n    }\n\n    public func versionsDescending() async throws -> [Version] {\n        try await self.knownVersionsCache.memoize {\n            let metadata = try await self.registryClient.getPackageMetadata(\n                package: self.package.identity,\n                observabilityScope: self.observabilityScope\n            )\n            return metadata.versions.sorted(by: >)\n        }\n    }\n\n    public func versionsAscending() async throws -> [Version] {\n        try await self.versionsDescending().reversed()\n    }\n\n    public func toolsVersionsAppropriateVersionsDescending() async throws -> [Version] {\n        var results: [Version] = []\n        for version in try await self.versionsDescending() {\n            if await self.isToolsVersionCompatible(at: version) {\n                results.append(version)\n            }\n        }\n        return results\n    }\n\n    public func getDependencies(at version: Version, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) async throws -> [PackageContainerConstraint] {\n        let manifest = try await self.loadManifest(version: version)\n        return try manifest.dependencyConstraints(productFilter: productFilter, enabledTraits)\n    }\n\n    public func getDependencies(at revision: String, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        throw InternalError(\"getDependencies for revision not supported by RegistryPackageContainer\")\n    }\n\n    public func getUnversionedDependencies(productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        throw InternalError(\"getUnversionedDependencies not supported by RegistryPackageContainer\")\n    }\n\n    public func loadPackageReference(at boundVersion: BoundVersion) throws -> PackageReference {\n        return self.package\n    }\n\n    // marked internal for testing\n    internal func loadManifest(version: Version) async throws -> Manifest {\n        let result = try await self.getAvailableManifestsFilesystem(version: version)\n\n        let manifests = result.manifests\n        let fileSystem = result.fileSystem\n\n        // first, decide the tools-version we should use\n        guard let defaultManifestToolsVersion = manifests.first(where: { $0.key == Manifest.filename })?.value.toolsVersion else {\n            throw StringError(\"Could not find the '\\(Manifest.filename)' file for '\\(self.package.identity)' '\\(version)'\")\n        }\n        // find the preferred manifest path and parse it's tools-version\n        let preferredToolsVersionManifestPath = try ManifestLoader.findManifest(packagePath: .root, fileSystem: fileSystem, currentToolsVersion: self.currentToolsVersion)\n        let preferredToolsVersion = try ToolsVersionParser.parse(manifestPath: preferredToolsVersionManifestPath, fileSystem: fileSystem)\n        // load the manifest content\n        let loadManifest = {\n            try await self.manifestLoader.load(\n                packagePath: .root,\n                packageIdentity: self.package.identity,\n                packageKind: self.package.kind,\n                packageLocation: self.package.locationString,\n                packageVersion: (version: version, revision: nil),\n                currentToolsVersion: self.currentToolsVersion,\n                identityResolver: self.identityResolver,\n                dependencyMapper: self.dependencyMapper,\n                fileSystem: result.fileSystem,\n                observabilityScope: self.observabilityScope,\n                delegateQueue: .sharedConcurrent\n            )\n        }\n\n        if preferredToolsVersion == defaultManifestToolsVersion {\n            // default tools version - we already have the content on disk from getAvailableManifestsFileSystem()\n            return try await loadManifest()\n        } else {\n            // custom tools-version, we need to fetch the content from the server\n            let manifestContent = try await self.registryClient.getManifestContent(\n                package: self.package.identity,\n                version: version,\n                customToolsVersion: preferredToolsVersion,\n                observabilityScope: self.observabilityScope\n            )\n            // find the fake manifest so we can replace it with the real manifest content\n            guard let placeholderManifestFileName = try fileSystem.getDirectoryContents(.root).first(where: { file in\n                if file == Manifest.basename + \"@swift-\\(preferredToolsVersion).swift\" {\n                    return true\n                } else if preferredToolsVersion.patch == 0, file == Manifest.basename + \"@swift-\\(preferredToolsVersion.major).\\(preferredToolsVersion.minor).swift\" {\n                    return true\n                } else if preferredToolsVersion.patch == 0, preferredToolsVersion.minor == 0, file == Manifest.basename + \"@swift-\\(preferredToolsVersion.major).swift\" {\n                    return true\n                } else {\n                    return false\n                }\n            }) else {\n                throw StringError(\"failed locating placeholder manifest for \\(preferredToolsVersion)\")\n            }\n            // replace the fake manifest with the real manifest content\n            let manifestPath = Basics.AbsolutePath.root.appending(component: placeholderManifestFileName)\n            try fileSystem.removeFileTree(manifestPath)\n            try fileSystem.writeFileContents(manifestPath, string: manifestContent)\n            // finally, load the manifest\n            return try await loadManifest()\n        }\n    }\n\n    private func getAvailableManifestsFilesystem(version: Version) async throws -> (manifests: [String: (toolsVersion: ToolsVersion, content: String?)], fileSystem: FileSystem) {\n        // try cached first\n        if let availableManifests = self.availableManifestsCache[version] {\n            return availableManifests\n        }\n\n        // get from server\n        let manifests = try await self.registryClient.getAvailableManifests(\n            package: self.package.identity,\n            version: version,\n            observabilityScope: self.observabilityScope\n        )\n\n        // ToolsVersionLoader is designed to scan files to decide which is the best tools-version\n        // as such, this writes a fake manifest based on the information returned by the registry\n        // with only the header line which is all that is needed by ToolsVersionLoader\n        let fileSystem = Basics.InMemoryFileSystem()\n        for manifest in manifests {\n            let content = manifest.value.content ?? \"// swift-tools-version:\\(manifest.value.toolsVersion)\"\n            try fileSystem.writeFileContents(AbsolutePath.root.appending(component: manifest.key), string: content)\n        }\n        self.availableManifestsCache[version] = (manifests: manifests, fileSystem: fileSystem)\n        return (manifests: manifests, fileSystem: fileSystem)\n    }\n}\n\n// MARK: - CustomStringConvertible\n\nextension RegistryPackageContainer: CustomStringConvertible {\n    public var description: String {\n        return \"RegistryPackageContainer(\\(package.identity))\"\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/PackageContainer/SourceControlPackageContainer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport class Foundation.NSLock\nimport PackageFingerprint\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SourceControl\n\nimport struct TSCBasic.RegEx\n\nimport enum TSCUtility.Git\nimport struct TSCUtility.Version\n\n/// Adaptor to expose an individual repository as a package container.\ninternal final class SourceControlPackageContainer: PackageContainer, CustomStringConvertible {\n    public typealias Constraint = PackageContainerConstraint\n\n    // A wrapper for getDependencies() errors. This adds additional information\n    // about the container to identify it for diagnostics.\n    public struct GetDependenciesError: Error, CustomStringConvertible {\n        /// The repository  that encountered the error.\n        public let repository: RepositorySpecifier\n\n        /// The source control reference (version, branch, revision, etc) that was involved.\n        public let reference: String\n\n        /// The actual error that occurred.\n        public let underlyingError: Error\n\n        /// Optional suggestion for how to resolve the error.\n        public let suggestion: String?\n\n        /// Description shown for errors of this kind.\n        public var description: String {\n            var desc = \"\\(underlyingError) in \\(self.repository.location)\"\n            if let suggestion {\n                desc += \" (\\(suggestion))\"\n            }\n            return desc\n        }\n    }\n\n    public let package: PackageReference\n    private let repositorySpecifier: RepositorySpecifier\n    private let repository: Repository\n    private let identityResolver: IdentityResolver\n    private let dependencyMapper: DependencyMapper\n    private let manifestLoader: ManifestLoaderProtocol\n    private let currentToolsVersion: ToolsVersion\n    private let fingerprintStorage: PackageFingerprintStorage?\n    private let fingerprintCheckingMode: FingerprintCheckingMode\n    private let observabilityScope: ObservabilityScope\n\n    /// The cached dependency information.\n    private var dependenciesCache = [String: [ProductFilter: (Manifest, [Constraint])]]()\n    private var dependenciesCacheLock = NSLock()\n\n    private var knownVersionsCache = ThreadSafeBox<[Version: String]?>()\n    private var manifestsCache = ThrowingAsyncKeyValueMemoizer<String, Manifest>()\n    private var toolsVersionsCache = ThreadSafeKeyValueStore<Version, ToolsVersion>()\n\n    /// This is used to remember if tools version of a particular version is\n    /// valid or not.\n    internal var validToolsVersionsCache = ThreadSafeKeyValueStore<Version, Bool>()\n\n    init(\n        package: PackageReference,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        repositorySpecifier: RepositorySpecifier,\n        repository: Repository,\n        manifestLoader: ManifestLoaderProtocol,\n        currentToolsVersion: ToolsVersion,\n        fingerprintStorage: PackageFingerprintStorage?,\n        fingerprintCheckingMode: FingerprintCheckingMode,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        self.package = package\n        self.identityResolver = identityResolver\n        self.dependencyMapper = dependencyMapper\n        self.repositorySpecifier = repositorySpecifier\n        self.repository = repository\n        self.manifestLoader = manifestLoader\n        self.currentToolsVersion = currentToolsVersion\n        self.fingerprintStorage = fingerprintStorage\n        self.fingerprintCheckingMode = fingerprintCheckingMode\n        self.observabilityScope = observabilityScope.makeChildScope(\n            description: \"SourceControlPackageContainer\",\n            metadata: package.diagnosticsMetadata)\n    }\n\n    // Compute the map of known versions.\n    private func knownVersions() throws -> [Version: String] {\n        try self.knownVersionsCache.memoize {\n            let knownVersionsWithDuplicates = Git.convertTagsToVersionMap(tags: try repository.getTags(), toolsVersion: self.currentToolsVersion)\n\n            return knownVersionsWithDuplicates.mapValues { tags -> String in\n                if tags.count > 1 {\n                    // FIXME: Warn if the two tags point to different git references.\n\n                    // If multiple tags are present with the same semantic version (e.g. v1.0.0, 1.0.0, 1.0) reconcile which one we prefer.\n                    // Prefer the most specific tag, e.g. 1.0.0 is preferred over 1.0.\n                    // Sort the tags so the most specific tag is first, order is ascending so the most specific tag will be last\n                    let tagsSortedBySpecificity = tags.sorted {\n                        let componentCounts = ($0.components(separatedBy: \".\").count, $1.components(separatedBy: \".\").count)\n                        if componentCounts.0 == componentCounts.1 {\n                            // if they are both have the same number of components, favor the one without a v prefix.\n                            // this matches previously defined behavior\n                            // this assumes we can only enter this situation because one tag has a v prefix and the other does not.\n                            return $0.hasPrefix(\"v\")\n                        }\n                        return componentCounts.0 < componentCounts.1\n                    }\n                    return tagsSortedBySpecificity.last!\n                }\n                assert(tags.count == 1, \"Unexpected number of tags\")\n                return tags[0]\n            }\n        }\n    }\n\n    public func versionsAscending() throws -> [Version] {\n        [Version](try self.knownVersions().keys).sorted()\n    }\n\n    /// The available version list (in reverse order).\n    public func toolsVersionsAppropriateVersionsDescending() async throws -> [Version] {\n        let reversedVersions = try await self.versionsDescending()\n        return reversedVersions.lazy.filter {\n            // If we have the result cached, return that.\n            if let result = self.validToolsVersionsCache[$0] {\n                return result\n            }\n\n            // Otherwise, compute and cache the result.\n            let isValid = (try? self.toolsVersion(for: $0)).flatMap(self.isValidToolsVersion(_:)) ?? false\n            self.validToolsVersionsCache[$0] = isValid\n            return isValid\n        }\n    }\n\n    public func getTag(for version: Version) -> String? {\n        return try? self.knownVersions()[version]\n    }\n\n    func checkIntegrity(version: Version, revision: Revision) throws {\n        guard let fingerprintStorage else {\n            return\n        }\n\n        guard case .remoteSourceControl(let sourceControlURL) = self.package.kind else {\n            return\n        }\n\n        let fingerprint: Fingerprint\n        do {\n            fingerprint = try fingerprintStorage.get(\n                package: self.package,\n                version: version,\n                kind: .sourceControl,\n                contentType: .sourceCode,\n                observabilityScope: self.observabilityScope\n            )\n        } catch PackageFingerprintStorageError.notFound {\n            fingerprint = Fingerprint(\n                origin: .sourceControl(sourceControlURL),\n                value: revision.identifier,\n                contentType: .sourceCode\n            )\n            // Write to storage if fingerprint not yet recorded\n            do {\n                try fingerprintStorage.put(\n                    package: self.package,\n                    version: version,\n                    fingerprint: fingerprint,\n                    observabilityScope: self.observabilityScope\n                )\n            } catch PackageFingerprintStorageError.conflict(_, let existing) {\n                let message = \"Revision \\(revision.identifier) for \\(self.package) version \\(version) does not match previously recorded value \\(existing.value) from \\(String(describing: existing.origin.url?.absoluteString))\"\n                switch self.fingerprintCheckingMode {\n                case .strict:\n                    throw StringError(message)\n                case .warn:\n                    observabilityScope.emit(warning: message)\n                }\n            }\n        } catch {\n            self.observabilityScope.emit(\n                error: \"Failed to get source control fingerprint for \\(self.package) version \\(version) from storage\",\n                underlyingError: error\n            )\n            throw error\n        }\n\n        // The revision (i.e., hash) must match that in fingerprint storage otherwise the integrity check fails\n        if revision.identifier != fingerprint.value {\n            let message = \"Revision \\(revision.identifier) for \\(self.package) version \\(version) does not match previously recorded value \\(fingerprint.value)\"\n            switch self.fingerprintCheckingMode {\n            case .strict:\n                throw StringError(message)\n            case .warn:\n                observabilityScope.emit(warning: message)\n            }\n        }\n    }\n\n    /// Returns revision for the given tag.\n    public func getRevision(forTag tag: String) throws -> Revision {\n        return try repository.resolveRevision(tag: tag)\n    }\n\n    /// Returns revision for the given identifier.\n    public func getRevision(forIdentifier identifier: String) throws -> Revision {\n        return try repository.resolveRevision(identifier: identifier)\n    }\n\n    /// Returns the tools version of the given version of the package.\n    public func toolsVersion(for version: Version) throws -> ToolsVersion {\n        try self.toolsVersionsCache.memoize(version) {\n            guard let tag = try self.knownVersions()[version] else {\n                throw StringError(\"unknown tag \\(version)\")\n            }\n            let fileSystem = try repository.openFileView(tag: tag)\n            // find the manifest path and parse it's tools-version\n            let manifestPath = try ManifestLoader.findManifest(packagePath: .root, fileSystem: fileSystem, currentToolsVersion: self.currentToolsVersion)\n            return try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fileSystem)\n        }\n    }\n\n    public func getDependencies(at version: Version, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) async throws -> [Constraint] {\n        do {\n            return try await self.getCachedDependencies(forIdentifier: version.description, productFilter: productFilter) {\n                guard let tag = try self.knownVersions()[version] else {\n                    throw StringError(\"unknown tag \\(version)\")\n                }\n                return try await self.loadDependencies(tag: tag, version: version, productFilter: productFilter, enabledTraits: enabledTraits)\n            }.1\n        } catch {\n            throw GetDependenciesError(\n                repository: self.repositorySpecifier,\n                reference: version.description,\n                underlyingError: error,\n                suggestion: .none\n            )\n        }\n    }\n\n    public func getDependencies(at revision: String, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) async throws -> [Constraint] {\n        do {\n            return try await self.getCachedDependencies(forIdentifier: revision, productFilter: productFilter) {\n                // resolve the revision identifier and return its dependencies.\n                let revision = try repository.resolveRevision(identifier: revision)\n                return try await self.loadDependencies(at: revision, productFilter: productFilter, enabledTraits: enabledTraits)\n            }.1\n        } catch {\n            // Examine the error to see if we can come up with a more informative and actionable error message.  We know that the revision is expected to be a branch name or a hash (tags are handled through a different code path).\n            if let error = error as? GitRepositoryError, error.description.contains(\"Needed a single revision\") {\n                // It was a Git process invocation error.  Take a look at the repository to see if we can come up with a reasonable diagnostic.\n                if let rev = try? repository.resolveRevision(identifier: revision), repository.exists(revision: rev) {\n                    // Revision does exist, so something else must be wrong.\n                    throw GetDependenciesError(\n                        repository: self.repositorySpecifier,\n                        reference: revision,\n                        underlyingError: error,\n                        suggestion: .none\n                    )\n                } else {\n                    // Revision does not exist, so we customize the error.\n                    let sha1RegEx = try! RegEx(pattern: #\"\\A[:xdigit:]{40}\\Z\"#)\n                    let isBranchRev = sha1RegEx.matchGroups(in: revision).compactMap { $0 }.isEmpty\n                    let errorMessage = \"could not find \" + (isBranchRev ? \"a branch named ‘\\(revision)’\" : \"the commit \\(revision)\")\n                    let mainBranchExists = (try? repository.resolveRevision(identifier: \"main\")) != nil\n                    let suggestion = (revision == \"master\" && mainBranchExists) ? \"did you mean ‘main’?\" : nil          //ignore-unacceptable-language\n                    throw GetDependenciesError(\n                        repository: self.repositorySpecifier,\n                        reference: revision,\n                        underlyingError: StringError(errorMessage),\n                        suggestion: suggestion\n                    )\n                }\n            }\n            // If we get this far without having thrown an error, we wrap and throw the underlying error.\n            throw GetDependenciesError(\n                repository: self.repositorySpecifier,\n                reference: revision,\n                underlyingError: error,\n                suggestion: .none\n            )\n        }\n    }\n\n    private func getCachedDependencies(\n        forIdentifier identifier: String,\n        productFilter: ProductFilter,\n        getDependencies: () async throws -> (Manifest, [Constraint])\n    ) async throws -> (Manifest, [Constraint]) {\n        if let result = (self.dependenciesCacheLock.withLock { self.dependenciesCache[identifier, default: [:]][productFilter] }) {\n            return result\n        }\n        let result = try await getDependencies()\n        self.dependenciesCacheLock.withLock {\n            self.dependenciesCache[identifier, default: [:]][productFilter] = result\n        }\n        return result\n    }\n\n    /// Returns dependencies of a container at the given revision.\n    private func loadDependencies(\n        tag: String,\n        version: Version? = nil,\n        productFilter: ProductFilter,\n        enabledTraits: EnabledTraits\n    ) async throws -> (Manifest, [Constraint]) {\n        let manifest = try await self.loadManifest(tag: tag, version: version)\n        return (manifest, try manifest.dependencyConstraints(productFilter: productFilter, enabledTraits))\n    }\n\n    /// Returns dependencies of a container at the given revision.\n    private func loadDependencies(\n        at revision: Revision,\n        version: Version? = nil,\n        productFilter: ProductFilter,\n        enabledTraits: EnabledTraits\n    ) async throws -> (Manifest, [Constraint]) {\n        let manifest = try await self.loadManifest(at: revision, version: version)\n        return (manifest, try manifest.dependencyConstraints(productFilter: productFilter, enabledTraits))\n    }\n\n    public func getUnversionedDependencies(productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [Constraint] {\n        // We just return an empty array if requested for unversioned dependencies.\n        return []\n    }\n\n    public func loadPackageReference(at boundVersion: BoundVersion) async throws -> PackageReference {\n        let revision: Revision\n        var version: Version?\n        switch boundVersion {\n        case .version(let v):\n            guard let tag = try self.knownVersions()[v] else {\n                throw StringError(\"unknown tag \\(v)\")\n            }\n            version = v\n            revision = try repository.resolveRevision(tag: tag)\n        case .revision(let identifier, _):\n            revision = try repository.resolveRevision(identifier: identifier)\n        case .unversioned, .excluded:\n            assertionFailure(\"Unexpected type requirement \\(boundVersion)\")\n            return self.package\n        }\n\n        let manifest = try await self.loadManifest(at: revision, version: version)\n        return self.package.withName(manifest.displayName)\n    }\n\n    /// Returns true if the tools version is valid and can be used by this\n    /// version of the package manager.\n    private func isValidToolsVersion(_ toolsVersion: ToolsVersion) -> Bool {\n        do {\n            try toolsVersion.validateToolsVersion(currentToolsVersion, packageIdentity: .plain(\"unknown\"))\n            return true\n        } catch {\n            return false\n        }\n    }\n\n    public func isToolsVersionCompatible(at version: Version) -> Bool {\n        return (try? self.toolsVersion(for: version)).flatMap(self.isValidToolsVersion(_:)) ?? false\n    }\n\n    private func loadManifest(tag: String, version: Version?) async throws -> Manifest {\n        try await self.manifestsCache.memoize(tag) {\n            let fileSystem = try self.repository.openFileView(tag: tag)\n            return try await self.loadManifest(fileSystem: fileSystem, version: version, revision: tag)\n        }\n    }\n\n    private func loadManifest(at revision: Revision, version: Version?) async throws -> Manifest {\n        try await self.manifestsCache.memoize(revision.identifier) {\n            let fileSystem = try self.repository.openFileView(revision: revision)\n            return try await self.loadManifest(fileSystem: fileSystem, version: version, revision: revision.identifier)\n        }\n    }\n\n    private func loadManifest(fileSystem: FileSystem, version: Version?, revision: String) async throws -> Manifest {\n        // Load the manifest.\n        return try await self.manifestLoader.load(\n            packagePath: .root,\n            packageIdentity: self.package.identity,\n            packageKind: self.package.kind,\n            packageLocation: self.package.locationString,\n            packageVersion: (version: version, revision: revision),\n            currentToolsVersion: self.currentToolsVersion,\n            identityResolver: self.identityResolver,\n            dependencyMapper: self.dependencyMapper,\n            fileSystem: fileSystem,\n            observabilityScope: self.observabilityScope,\n            delegateQueue: .sharedConcurrent\n        )\n    }\n\n    public var isRemoteContainer: Bool? {\n        return true\n    }\n\n    public var description: String {\n        return \"SourceControlPackageContainer(\\(self.repositorySpecifier))\"\n    }\n}\n\nextension Git {\n    fileprivate static func convertTagsToVersionMap(tags: [String], toolsVersion: ToolsVersion) -> [Version: [String]] {\n        // First, check if we need to restrict the tag set to version-specific tags.\n        var knownVersions: [Version: [String]] = [:]\n        var versionSpecificKnownVersions: [Version: [String]] = [:]\n\n        for tag in tags {\n            for versionSpecificKey in toolsVersion.versionSpecificKeys {\n                if tag.hasSuffix(versionSpecificKey) {\n                    let trimmedTag = String(tag.dropLast(versionSpecificKey.count))\n                    if let version = Version(tag: trimmedTag) {\n                        versionSpecificKnownVersions[version, default: []].append(tag)\n                    }\n                    break\n                }\n            }\n\n            if let version = Version(tag: tag) {\n                knownVersions[version, default: []].append(tag)\n            }\n        }\n        // Check if any version specific tags were found.\n        // If true, then return the version specific tags,\n        // or else return the version independent tags.\n        if !versionSpecificKnownVersions.isEmpty {\n            return versionSpecificKnownVersions\n        } else {\n            return knownVersions\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ResolvedFileWatcher.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport class Foundation.NSLock\nimport PackageModel\nimport PackageGraph\n\nimport struct TSCBasic.ByteString\n\nimport class TSCUtility.FSWatch\n\n/// A file watcher utility for the Package.resolved file.\n///\n/// This is not intended to be used directly by clients.\nfinal class ResolvedFileWatcher {\n    private var fswatch: FSWatch!\n    private var existingValue: ByteString?\n    private let valueLock = NSLock()\n    private let resolvedFile: TSCAbsolutePath\n\n    public func updateValue() {\n        valueLock.withLock {\n            self.existingValue = try? localFileSystem.readFileContents(resolvedFile)\n        }\n    }\n\n    init(resolvedFile: AbsolutePath, onChange: @escaping () -> ()) throws {\n        let resolvedFile = TSCAbsolutePath(resolvedFile)\n        self.resolvedFile = resolvedFile\n\n        let block = { [weak self] (paths: [TSCAbsolutePath]) in\n            guard let self else { return }\n\n            // Check if resolved file is part of the received paths.\n            let hasResolvedFile = paths.contains{ $0.appending(component: resolvedFile.basename) == resolvedFile }\n            guard hasResolvedFile else { return }\n\n            self.valueLock.withLock {\n                // Compute the contents of the resolved file and fire the onChange block\n                // if its value is different than existing value.\n                let newValue: ByteString? = try? localFileSystem.readFileContents(resolvedFile)\n                if self.existingValue != newValue {\n                    self.existingValue = newValue\n                    onChange()\n                }\n            }\n        }\n\n        fswatch = FSWatch(paths: [resolvedFile.parentDirectory], latency: 1, block: block)\n        try fswatch.start()\n    }\n\n    deinit {\n        fswatch.stop()\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ResolverPrecomputationProvider.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport PackageGraph\nimport PackageModel\nimport SourceControl\n\nimport struct TSCUtility.Version\n\n/// Enumeration of the different errors that can arise from the `ResolverPrecomputationProvider` provider.\nenum ResolverPrecomputationError: Error {\n    /// Represents the error when a package was requested but couldn't be found.\n    case missingPackage(package: PackageReference)\n\n    /// Represents the error when a different requirement of a package was requested.\n    case differentRequirement(\n        package: PackageReference,\n        state: Workspace.ManagedDependency.State?,\n        requirement: PackageRequirement\n    )\n}\n\n/// PackageContainerProvider implementation used by Workspace to do a dependency pre-calculation using the cached\n/// dependency information (Workspace.DependencyManifests) to check if dependency resolution is required before\n/// performing a full resolution.\nstruct ResolverPrecomputationProvider: PackageContainerProvider {\n    /// The package graph inputs.\n    let root: PackageGraphRoot\n\n    /// The managed manifests to make available to the resolver.\n    let dependencyManifests: Workspace.DependencyManifests\n\n    /// The tools version currently in use.\n    let currentToolsVersion: ToolsVersion\n\n    init(\n        root: PackageGraphRoot,\n        dependencyManifests: Workspace.DependencyManifests,\n        currentToolsVersion: ToolsVersion = ToolsVersion.current\n    ) {\n        self.root = root\n        self.dependencyManifests = dependencyManifests\n        self.currentToolsVersion = currentToolsVersion\n    }\n\n    func getContainer(\n        for package: PackageReference,\n        updateStrategy: ContainerUpdateStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> PackageContainer {\n        // Start by searching manifests from the Workspace's resolved dependencies.\n        if let manifest = self.dependencyManifests.dependencies.first(where: { _, managed, _, _ in managed.packageRef == package }) {\n            let container = LocalPackageContainer(\n                package: package,\n                manifest: manifest.manifest,\n                dependency: manifest.dependency,\n                currentToolsVersion: self.currentToolsVersion\n            )\n            return container\n        }\n\n        // Continue searching from the Workspace's root manifests.\n        if let rootPackage = self.dependencyManifests.root.packages[package.identity] {\n            let container = LocalPackageContainer(\n                package: package,\n                manifest: rootPackage.manifest,\n                dependency: nil,\n                currentToolsVersion: self.currentToolsVersion\n            )\n            return container\n        }\n\n        // As we don't have anything else locally, error out.\n        throw ResolverPrecomputationError.missingPackage(package: package)\n    }\n}\n\nprivate struct LocalPackageContainer: PackageContainer {\n    let package: PackageReference\n    let manifest: Manifest\n    /// The managed dependency if the package is not a root package.\n    let dependency: Workspace.ManagedDependency?\n    let currentToolsVersion: ToolsVersion\n    let shouldInvalidatePinnedVersions = false\n\n    func versionsAscending() throws -> [Version] {\n        switch dependency?.state {\n        case .sourceControlCheckout(.version(let version, revision: _)):\n            return [version]\n        case .registryDownload(let version):\n            return [version]\n        default:\n            return []\n        }\n    }\n\n    func isToolsVersionCompatible(at version: Version) -> Bool {\n        do {\n            try manifest.toolsVersion.validateToolsVersion(currentToolsVersion, packageIdentity: .plain(\"unknown\"))\n            return true\n        } catch {\n            return false\n        }\n    }\n\n    func toolsVersion(for version: Version) throws -> ToolsVersion {\n        return currentToolsVersion\n    }\n\n    func toolsVersionsAppropriateVersionsDescending() async throws -> [Version] {\n        try await self.versionsDescending()\n    }\n\n    func getDependencies(at version: Version, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        // Because of the implementation of `reversedVersions`, we should only get the exact same version.\n        switch dependency?.state {\n        case .sourceControlCheckout(.version(version, revision: _)):\n            return try manifest.dependencyConstraints(productFilter: productFilter, enabledTraits)\n        case .registryDownload(version: version):\n            return try manifest.dependencyConstraints(productFilter: productFilter, enabledTraits)\n        default:\n            throw InternalError(\"expected version based state, but state was \\(String(describing: dependency?.state))\")\n        }\n    }\n\n    func getDependencies(at revisionString: String, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        let revision = Revision(identifier: revisionString)\n        switch dependency?.state {\n        case .sourceControlCheckout(.branch(_, revision: revision)), .sourceControlCheckout(.revision(revision)):\n            // Return the dependencies if the checkout state matches the revision.\n            return try manifest.dependencyConstraints(productFilter: productFilter, enabledTraits)\n        default:\n            // Throw an error when the dependency is not revision based to fail resolution.\n            throw ResolverPrecomputationError.differentRequirement(\n                package: self.package,\n                state: self.dependency?.state,\n                requirement: .revision(revisionString)\n            )\n        }\n    }\n\n    func getUnversionedDependencies(productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        switch dependency?.state {\n        case .none, .fileSystem, .edited:\n            return try manifest.dependencyConstraints(productFilter: productFilter, enabledTraits)\n        default:\n            // Throw an error when the dependency is not unversioned to fail resolution.\n            throw ResolverPrecomputationError.differentRequirement(\n                package: package,\n                state: dependency?.state,\n                requirement: .unversioned\n            )\n        }\n    }\n\n    // Gets the package reference from the managed dependency or computes it for root packages.\n    func loadPackageReference(at boundVersion: BoundVersion) throws -> PackageReference {\n        if let packageRef = dependency?.packageRef {\n            return packageRef\n        } else {\n            return .root(identity: self.package.identity, path: self.manifest.path)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/ToolsVersionSpecificationRewriter.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// -----------------------------------------------------------------------------\n///\n/// This file implements a global function that rewrite the Swift tools version specification of a manifest file.\n///\n// -----------------------------------------------------------------------------\n\nimport Basics\nimport PackageModel\nimport PackageLoading\n\nimport struct TSCBasic.ByteString\nimport class TSCBasic.BufferedOutputByteStream\n\npublic struct ToolsVersionSpecificationWriter {\n    // designed to be used as a static utility\n    private init() {}\n\n    /// Rewrites Swift tools version specification to the non-version-specific manifest file (`Package.swift`) in the given directory.\n    ///\n    /// If the main manifest file already contains a valid tools version specification (ignoring the validity of the version specifier and that of everything following it), then the existing specification is replaced by this new one.\n    ///\n    /// The version specifier in the specification does not contain any build metadata or pre-release identifier. The patch version is included if and only if it's not zero.\n    ///\n    /// A `FileSystemError` is thrown if the manifest file is unable to be read from or written to.\n    ///\n    /// - Precondition: `manifestDirectoryPath` must be a valid path to a directory that contains a `Package.swift` file.\n    ///\n    /// - Parameters:\n    ///   - manifestDirectory: The absolute path to the given directory.\n    ///   - toolsVersion: The Swift tools version to specify as the lowest supported version.\n    ///   - fileSystem: The filesystem to read/write the manifest file on.\n    public static func rewriteSpecification(manifestDirectory: AbsolutePath, toolsVersion: ToolsVersion, fileSystem: FileSystem) throws {\n        let manifestFilePath = manifestDirectory.appending(component: Manifest.filename)\n\n        guard fileSystem.isFile(manifestFilePath) else {\n            guard fileSystem.exists(manifestFilePath) else {\n                throw ManifestAccessError(.noSuchFileOrDirectory, at: manifestFilePath)\n            }\n            guard !fileSystem.isDirectory(manifestFilePath) else {\n                throw ManifestAccessError(.isADirectory, at: manifestFilePath)\n            }\n            throw ManifestAccessError(.unknown, at: manifestFilePath)\n        }\n\n        /// The current contents of the file.\n        let contents = try fileSystem.readFileContents(manifestFilePath)\n\n        let stream = BufferedOutputByteStream()\n        // Write out the tools version specification, including the patch version if and only if it's not zero.\n        stream.send(\"\\(toolsVersion.specification(roundedTo: .automatic))\\n\")\n\n        // The following lines up to line 77 append the file contents except for the Swift tools version specification line.\n\n        guard let contentsDecodedWithUTF8 = contents.validDescription else {\n            throw ToolsVersionParser.Error.nonUTF8EncodedManifest(path: manifestFilePath)\n        }\n\n        let manifestComponents = ToolsVersionParser.split(contentsDecodedWithUTF8)\n\n        let toolsVersionSpecificationComponents = manifestComponents.toolsVersionSpecificationComponents\n\n        // Replace the Swift tools version specification line if and only if it's well-formed up to the version specifier.\n        // This matches the behavior of the old (now removed) [`ToolsVersionLoader.split(:_)`](https://github.com/WowbaggersLiquidLunch/swift-package-manager/blob/49cfc46bc5defd3ce8e0c0261e3e2cb475bcdb91/Sources/PackageLoading/ToolsVersionLoader.swift#L160).\n        if toolsVersionSpecificationComponents.everythingUpToVersionSpecifierIsWellFormed {\n            stream.send(String(manifestComponents.contentsAfterToolsVersionSpecification))\n        } else {\n            stream.send(contents)\n        }\n\n        try fileSystem.writeFileContents(manifestFilePath, bytes: stream.bytes)\n    }\n\n    /// An error that causes the access to a manifest to fails.\n    struct ManifestAccessError: Error, CustomStringConvertible {\n        public init(_ kind: Kind, at path: AbsolutePath) {\n            self.kind = kind\n            self.path = path\n        }\n\n        /// The kind of the error being raised.\n        public enum Kind: Equatable {\n            /// A component of a specified pathname did not exist, or the pathname was an empty string.\n            ///\n            /// This error is equivalent to `TSCBasic.FileSystemError.Kind.noEntry` and corresponds to the POSIX ENOENT error code, but is specialised for manifest access.\n            case noSuchFileOrDirectory\n            /// The path points to a directory.\n            ///\n            /// This error is equivalent to `TSCBasic.FileSystemError.Kind.isDirectory` and corresponds to rhe POSIX EISDIR error code, but is specialised for manifest access.\n            case isADirectory\n            /// The manifest cannot be accessed for an unknown reason.\n            case unknown\n        }\n\n        /// The kind of the error being raised.\n        public let kind: Kind\n\n        /// The absolute path where the error occurred.\n        public let path: AbsolutePath\n\n        public var description: String {\n            var reason: String {\n                switch kind {\n                case .noSuchFileOrDirectory:\n                    return \"a component of the path does not exist, or the path is an empty string\"\n                case .isADirectory:\n                    return \"the path is a directory; a file is expected\"\n                case .unknown:\n                    return \"an unknown error occurred\"\n                }\n            }\n            return \"no accessible Swift Package Manager manifest file found at '\\(path)'; \\(reason)\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+BinaryArtifacts.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageLoading\nimport PackageGraph\nimport PackageModel\nimport SPMBuildCore\n\nimport struct TSCBasic.ByteString\nimport protocol TSCBasic.HashAlgorithm\nimport struct TSCBasic.SHA256\nimport enum TSCUtility.Diagnostics\n\nextension Workspace {\n    // marked public for testing\n    public struct CustomBinaryArtifactsManager {\n        let httpClient: HTTPClient?\n        let archiver: Archiver?\n        let useCache: Bool?\n\n        public init(\n            httpClient: HTTPClient? = .none,\n            archiver: Archiver? = .none,\n            useCache: Bool? = .none\n        ) {\n            self.httpClient = httpClient\n            self.archiver = archiver\n            self.useCache = useCache\n        }\n    }\n\n    // marked public since used in tools\n    public struct BinaryArtifactsManager: Cancellable {\n        public typealias Delegate = BinaryArtifactsManagerDelegate\n\n        private let fileSystem: FileSystem\n        private let authorizationProvider: AuthorizationProvider?\n        private let hostToolchain: UserToolchain\n        private let httpClient: HTTPClient\n        private let archiver: Archiver\n        private let checksumAlgorithm: HashAlgorithm\n        private let cachePath: AbsolutePath?\n        private let delegate: Delegate?\n\n        public init(\n            fileSystem: FileSystem,\n            authorizationProvider: AuthorizationProvider?,\n            hostToolchain: UserToolchain,\n            checksumAlgorithm: HashAlgorithm,\n            cachePath: AbsolutePath?,\n            customHTTPClient: HTTPClient?,\n            customArchiver: Archiver?,\n            delegate: Delegate?\n        ) {\n            self.fileSystem = fileSystem\n            self.authorizationProvider = authorizationProvider\n            self.hostToolchain = hostToolchain\n            self.checksumAlgorithm = checksumAlgorithm\n            self.httpClient = customHTTPClient ?? HTTPClient()\n            self.archiver = customArchiver ?? ZipArchiver(fileSystem: fileSystem)\n            self.cachePath = cachePath\n            self.delegate = delegate\n        }\n\n        func parseArtifacts(\n            from manifests: DependencyManifests,\n            identityResolver: IdentityResolver,\n            observabilityScope: ObservabilityScope\n        ) throws -> (local: [ManagedArtifact], remote: [RemoteArtifact]) {\n            let packageAndManifests: [(reference: PackageReference, manifest: Manifest)] =\n                manifests.root.packages.values + // Root package and manifests.\n                manifests.dependencies\n                .map { manifest, managed, _, _ in (managed.packageRef, manifest) } // Dependency package and manifests.\n\n            var localArtifacts: [ManagedArtifact] = []\n            var remoteArtifacts: [RemoteArtifact] = []\n\n            for (packageReference, manifest) in packageAndManifests {\n                for target in manifest.targets where target.type == .binary {\n                    if let path = target.path {\n                        // TODO: find a better way to get the base path (not via the manifest)\n                        let absolutePath = try manifest.path.parentDirectory.appending(RelativePath(validating: path))\n                        if absolutePath.extension?.lowercased() == \"zip\" {\n                            localArtifacts.append(\n                                .local(\n                                    packageRef: packageReference,\n                                    targetName: target.name,\n                                    path: absolutePath,\n                                    kind: .unknown // an archive, we will extract it later\n                                )\n                            )\n                        } else {\n                            guard let (artifactPath, artifactKind) = try Self.deriveBinaryArtifact(\n                                fileSystem: self.fileSystem,\n                                path: absolutePath,\n                                observabilityScope: observabilityScope\n                            ) else {\n                                observabilityScope.emit(\n                                    BinaryArtifactsManagerError.localArtifactNotFound(\n                                        artifactPath: absolutePath,\n                                        targetName: target.name\n                                    )\n                                )\n                                continue\n                            }\n                            localArtifacts.append(\n                                .local(\n                                    packageRef: packageReference,\n                                    targetName: target.name,\n                                    path: artifactPath,\n                                    kind: artifactKind\n                                )\n                            )\n                        }\n                    } else if let urlString = target.url, let checksum = target.checksum {\n                        // Apply mirroring to the URL\n                        let mappedURLString = identityResolver.mappedLocation(for: urlString)\n                        guard let url = URL(string: mappedURLString) else {\n                            observabilityScope.emit(\n                                BinaryArtifactsManagerError.artifactFailedDownload(\n                                    artifactURL: URL(string: urlString) ?? URL(string: \"unknown\")!,\n                                    targetName: target.name,\n                                    reason: \"Invalid URL after mirroring: \\(mappedURLString)\"\n                                )\n                            )\n                            continue\n                        }\n                        remoteArtifacts.append(\n                            .init(\n                                packageRef: packageReference,\n                                targetName: target.name,\n                                url: url,\n                                checksum: checksum\n                            )\n                        )\n                    } else {\n                        throw StringError(\"a binary target should have either a path or a URL and a checksum\")\n                    }\n                }\n            }\n\n            return (local: localArtifacts, remote: remoteArtifacts)\n        }\n\n        func fetch(\n            _ artifacts: [RemoteArtifact],\n            artifactsDirectory: AbsolutePath,\n            observabilityScope: ObservabilityScope\n        ) async throws -> [ManagedArtifact] {\n            // zip files to download\n            // stored in a thread-safe way as we may fetch more from \"artifactbundleindex\" files\n            var zipArtifacts = artifacts.filter {\n                $0.url.pathExtension.lowercased() == \"zip\"\n            }\n\n            // fetch and parse \"artifactbundleindex\" files, if any\n            let indexFiles = artifacts.filter { $0.url.pathExtension.lowercased() == \"artifactbundleindex\" }\n            if !indexFiles.isEmpty {\n                let errors = ThreadSafeArrayStore<Error>()\n\n                try await zipArtifacts.append(contentsOf: withThrowingTaskGroup(\n                    of: RemoteArtifact?.self,\n                    returning: [RemoteArtifact].self\n                ) { group in\n                    let jsonDecoder = JSONDecoder.makeWithDefaults()\n                    for indexFile in indexFiles {\n                        group.addTask {\n                            var request = HTTPClient.Request(method: .get, url: indexFile.url)\n                            request.options.validResponseCodes = [200]\n                            request.options.authorizationProvider = self.authorizationProvider?\n                                .httpAuthorizationHeader(for:)\n                            do {\n                                let response = try await self.httpClient.execute(request)\n                                guard let body = response.body else {\n                                    throw StringError(\"Body is empty\")\n                                }\n                                // FIXME: would be nice if checksumAlgorithm.hash took Data directly\n                                let bodyChecksum = self.checksumAlgorithm.hash(ByteString(body))\n                                    .hexadecimalRepresentation\n                                guard bodyChecksum == indexFile.checksum else {\n                                    throw StringError(\n                                        \"checksum of downloaded artifact of binary target '\\(indexFile.targetName)' (\\(bodyChecksum)) does not match checksum specified by the manifest (\\(indexFile.checksum))\"\n                                    )\n                                }\n                                let metadata = try jsonDecoder.decode(ArchiveIndexFile.self, from: body)\n                                // FIXME: this filter needs to become more sophisticated\n                                guard let supportedArchive = metadata.archives.first(where: {\n                                    $0.fileName.lowercased().hasSuffix(\".zip\") && $0.supportedTriples\n                                        .contains(self.hostToolchain.targetTriple)\n                                }) else {\n                                    throw StringError(\n                                        \"No supported archive was found for '\\(self.hostToolchain.targetTriple.tripleString)'\"\n                                    )\n                                }\n                                // add relevant archive\n                                return RemoteArtifact(\n                                    packageRef: indexFile.packageRef,\n                                    targetName: indexFile.targetName,\n                                    url: indexFile.url.deletingLastPathComponent()\n                                        .appendingPathComponent(supportedArchive.fileName),\n                                    checksum: supportedArchive.checksum\n                                )\n                            } catch {\n                                errors.append(error)\n                                observabilityScope.emit(\n                                    error: \"failed retrieving '\\(indexFile.url)'\",\n                                    underlyingError: error\n                                )\n                            }\n\n                            return nil\n                        }\n                    }\n\n                    // no reason to continue if we already ran into issues\n                    if !errors.isEmpty {\n                        throw Diagnostics.fatalError\n                    }\n\n                    return try await group.reduce(into: []) {\n                        if let artifact = $1 {\n                            $0.append(artifact)\n                        }\n                    }\n                })\n            }\n\n            let result = await withTaskGroup(of: ManagedArtifact?.self, returning: [ManagedArtifact].self) { group in\n                // finally download zip files, if any\n                for artifact in zipArtifacts {\n                    group.addTask { () -> ManagedArtifact? in\n                        let destinationDirectory = artifactsDirectory\n                            .appending(components: [artifact.packageRef.identity.description, artifact.targetName])\n                        guard observabilityScope.trap({ try fileSystem.createDirectory(\n                            destinationDirectory,\n                            recursive: true\n                        ) })\n                        else {\n                            return nil\n                        }\n\n                        let archivePath = destinationDirectory.appending(component: artifact.url.lastPathComponent)\n                        if self.fileSystem.exists(archivePath) {\n                            guard observabilityScope.trap({ try self.fileSystem.removeFileTree(archivePath) }) else {\n                                return nil\n                            }\n                        }\n\n                        let fetchStart: DispatchTime = .now()\n                        do {\n                            let cached = try await self.fetch(\n                                artifact: artifact,\n                                destination: archivePath,\n                                observabilityScope: observabilityScope,\n                                progress: { bytesDownloaded, totalBytesToDownload in\n                                    self.delegate?.downloadingBinaryArtifact(\n                                        from: artifact.url.absoluteString,\n                                        bytesDownloaded: bytesDownloaded,\n                                        totalBytesToDownload: totalBytesToDownload\n                                    )\n                                }\n                            )\n\n                            // TODO: Use the same extraction logic for both remote and local archived artifacts.\n                            observabilityScope.emit(debug: \"validating \\(archivePath)\")\n                            do {\n                                let valid = try await self.archiver.validate(path: archivePath)\n\n                                guard valid else {\n                                    observabilityScope.emit(BinaryArtifactsManagerError.artifactInvalidArchive(\n                                        artifactURL: artifact.url,\n                                        targetName: artifact.targetName\n                                    ))\n                                    return nil\n                                }\n\n                                guard let archiveChecksum = observabilityScope\n                                    .trap({ try self.checksum(forBinaryArtifactAt: archivePath) })\n                                else {\n                                    return nil\n                                }\n                                guard archiveChecksum == artifact.checksum else {\n                                    observabilityScope.emit(BinaryArtifactsManagerError.artifactInvalidChecksum(\n                                        targetName: artifact.targetName,\n                                        expectedChecksum: artifact.checksum,\n                                        actualChecksum: archiveChecksum\n                                    ))\n                                    observabilityScope.trap { try self.fileSystem.removeFileTree(archivePath) }\n                                    return nil\n                                }\n\n                                guard let tempExtractionDirectory = observabilityScope.trap({ () -> AbsolutePath in\n                                    let path = artifactsDirectory.appending(\n                                        components: \"extract\",\n                                        artifact.packageRef.identity.description,\n                                        artifact.targetName,\n                                        UUID().uuidString\n                                    )\n                                    try self.fileSystem.forceCreateDirectory(at: path)\n                                    return path\n                                }) else {\n                                    return nil\n                                }\n\n                                observabilityScope\n                                    .emit(debug: \"extracting \\(archivePath) to \\(tempExtractionDirectory)\")\n                                do {\n                                    try await self.archiver.extract(\n                                        from: archivePath,\n                                        to: tempExtractionDirectory\n                                    )\n\n                                    defer {\n                                        observabilityScope.trap { try self.fileSystem.removeFileTree(archivePath) }\n                                    }\n                                    observabilityScope.trap {\n                                        try self.fileSystem.withLock(\n                                            on: destinationDirectory,\n                                            type: .exclusive\n                                        ) {\n                                            // strip first level component if needed\n                                            if try self.fileSystem.shouldStripFirstLevel(\n                                                archiveDirectory: tempExtractionDirectory,\n                                                acceptableExtensions: BinaryModule.Kind.allCases\n                                                    .map(\\.fileExtension)\n                                            ) {\n                                                observabilityScope.emit(\n                                                    debug: \"stripping first level component from  \\(tempExtractionDirectory)\"\n                                                )\n                                                try self.fileSystem\n                                                    .stripFirstLevel(of: tempExtractionDirectory)\n                                            } else {\n                                                observabilityScope.emit(\n                                                    debug: \"no first level component stripping needed for \\(tempExtractionDirectory)\"\n                                                )\n                                            }\n                                            let content = try self.fileSystem\n                                                .getDirectoryContents(tempExtractionDirectory)\n                                            // copy from temp location to actual location\n                                            for file in content {\n                                                let source = tempExtractionDirectory\n                                                    .appending(component: file)\n                                                let destination = destinationDirectory\n                                                    .appending(component: file)\n                                                if self.fileSystem.exists(destination) {\n                                                    try self.fileSystem.removeFileTree(destination)\n                                                }\n                                                try self.fileSystem.copy(from: source, to: destination)\n                                            }\n                                        }\n                                        // remove temp location\n                                        try self.fileSystem.removeFileTree(tempExtractionDirectory)\n                                    }\n\n                                    // derive concrete artifact path and type\n                                    guard let (artifactPath, artifactKind) = try? Self.deriveBinaryArtifact(\n                                        fileSystem: self.fileSystem,\n                                        path: destinationDirectory,\n                                        observabilityScope: observabilityScope\n                                    ) else {\n                                        observabilityScope.emit(BinaryArtifactsManagerError.remoteArtifactNotFound(\n                                            artifactURL: artifact.url,\n                                            targetName: artifact.targetName\n                                        ))\n                                        return nil\n                                    }\n\n                                    self.delegate?.didDownloadBinaryArtifact(\n                                        from: artifact.url.absoluteString,\n                                        result: .success((path: artifactPath, fromCache: cached)),\n                                        duration: fetchStart.distance(to: .now())\n                                    )\n\n                                    return ManagedArtifact.remote(\n                                        packageRef: artifact.packageRef,\n                                        targetName: artifact.targetName,\n                                        url: artifact.url.absoluteString,\n                                        checksum: artifact.checksum,\n                                        path: artifactPath,\n                                        kind: artifactKind\n                                    )\n\n                                } catch {\n                                    observabilityScope.emit(BinaryArtifactsManagerError.remoteArtifactFailedExtraction(\n                                        artifactURL: artifact.url,\n                                        targetName: artifact.targetName,\n                                        reason: error.interpolationDescription\n                                    ))\n                                    self.delegate?.didDownloadBinaryArtifact(\n                                        from: artifact.url.absoluteString,\n                                        result: .failure(error),\n                                        duration: fetchStart.distance(to: .now())\n                                    )\n                                }\n                            } catch {\n                                observabilityScope.emit(BinaryArtifactsManagerError.artifactFailedValidation(\n                                    artifactURL: artifact.url,\n                                    targetName: artifact.targetName,\n                                    reason: error.interpolationDescription\n                                ))\n                                self.delegate?.didDownloadBinaryArtifact(\n                                    from: artifact.url.absoluteString,\n                                    result: .failure(error),\n                                    duration: fetchStart.distance(to: .now())\n                                )\n                            }\n                        } catch {\n                            observabilityScope.trap { try self.fileSystem.removeFileTree(archivePath) }\n                            observabilityScope.emit(BinaryArtifactsManagerError.artifactFailedDownload(\n                                artifactURL: artifact.url,\n                                targetName: artifact.targetName,\n                                reason: error.interpolationDescription\n                            ))\n                            self.delegate?.didDownloadBinaryArtifact(\n                                from: artifact.url.absoluteString,\n                                result: .failure(error),\n                                duration: fetchStart.distance(to: .now())\n                            )\n                        }\n\n                        return nil\n                    }\n                }\n\n                return await group.reduce(into: []) {\n                    if let artifact = $1 {\n                        $0.append(artifact)\n                    }\n                }\n            }\n\n            if zipArtifacts.count > 0 {\n                delegate?.didDownloadAllBinaryArtifacts()\n            }\n\n            return result\n        }\n\n        func extract(\n            _ artifacts: [ManagedArtifact],\n            artifactsDirectory: AbsolutePath,\n            observabilityScope: ObservabilityScope\n        ) async throws -> [ManagedArtifact] {\n            try await withThrowingTaskGroup(of: ManagedArtifact?.self) { group in\n                for artifact in artifacts {\n                    group.addTask { () -> ManagedArtifact? in\n                        let destinationDirectory = artifactsDirectory\n                            .appending(components: [artifact.packageRef.identity.description, artifact.targetName])\n                        try fileSystem.createDirectory(destinationDirectory, recursive: true)\n\n                        let tempExtractionDirectory = artifactsDirectory.appending(\n                            components: \"extract\",\n                            artifact.packageRef.identity.description,\n                            artifact.targetName,\n                            UUID().uuidString\n                        )\n                        try self.fileSystem.forceCreateDirectory(at: tempExtractionDirectory)\n\n                        do {\n                            try await self.archiver.extract(from: artifact.path, to: tempExtractionDirectory)\n\n                            return observabilityScope.trap {\n                                try self.fileSystem.withLock(on: destinationDirectory, type: .exclusive) {\n                                    // strip first level component if needed\n                                    if try self.fileSystem.shouldStripFirstLevel(\n                                        archiveDirectory: tempExtractionDirectory,\n                                        acceptableExtensions: BinaryModule.Kind.allCases.map(\\.fileExtension)\n                                    ) {\n                                        observabilityScope\n                                            .emit(\n                                                debug: \"stripping first level component from  \\(tempExtractionDirectory)\"\n                                            )\n                                        try self.fileSystem.stripFirstLevel(of: tempExtractionDirectory)\n                                    } else {\n                                        observabilityScope.emit(\n                                            debug: \"no first level component stripping needed for \\(tempExtractionDirectory)\"\n                                        )\n                                    }\n                                    let content = try self.fileSystem.getDirectoryContents(tempExtractionDirectory)\n                                    // copy from temp location to actual location\n                                    for file in content {\n                                        let source = tempExtractionDirectory.appending(component: file)\n                                        let destination = destinationDirectory.appending(component: file)\n                                        if self.fileSystem.exists(destination) {\n                                            try self.fileSystem.removeFileTree(destination)\n                                        }\n                                        try self.fileSystem.copy(from: source, to: destination)\n                                    }\n                                }\n\n                                // remove temp location\n                                try self.fileSystem.removeFileTree(tempExtractionDirectory)\n\n                                // derive concrete artifact path and type\n                                guard let (artifactPath, artifactKind) = try Self.deriveBinaryArtifact(\n                                    fileSystem: self.fileSystem,\n                                    path: destinationDirectory,\n                                    observabilityScope: observabilityScope\n                                ) else {\n                                    throw BinaryArtifactsManagerError.localArchivedArtifactNotFound(\n                                        archivePath: artifact.path,\n                                        targetName: artifact.targetName\n                                    )\n                                }\n\n                                // compute the checksum\n                                let artifactChecksum = try self.checksum(forBinaryArtifactAt: artifact.path)\n\n                                return ManagedArtifact.local(\n                                    packageRef: artifact.packageRef,\n                                    targetName: artifact.targetName,\n                                    path: artifactPath,\n                                    kind: artifactKind,\n                                    checksum: artifactChecksum\n                                )\n                            }\n                        } catch {\n                            let reason = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription\n\n                            observabilityScope.emit(BinaryArtifactsManagerError.localArtifactFailedExtraction(\n                                artifactPath: artifact.path,\n                                targetName: artifact.targetName,\n                                reason: reason\n                            ))\n\n                            return nil\n                        }\n                    }\n                }\n\n                return try await group.reduce(into: []) {\n                    if let artifact = $1 { $0.append(artifact) }\n                }\n            }\n        }\n\n        package static func checksum(\n            forBinaryArtifactAt path: AbsolutePath,\n            hashAlgorithm: HashAlgorithm = SHA256(),\n            archiver: (any Archiver)? = nil,\n            fileSystem: any FileSystem\n        ) throws -> String {\n            let archiver = archiver ?? UniversalArchiver(fileSystem)\n            // Validate the path has a supported extension.\n            guard let lastPathComponent = path.components.last, archiver.isFileSupported(lastPathComponent) else {\n                let supportedExtensionList = archiver.supportedExtensions.joined(separator: \", \")\n                throw StringError(\"unexpected file type; supported extensions are: \\(supportedExtensionList)\")\n            }\n\n            // Ensure that the path with the accepted extension is a file.\n            guard fileSystem.isFile(path) else {\n                throw StringError(\"file not found at path: \\(path.pathString)\")\n            }\n\n            let contents = try fileSystem.readFileContents(path)\n            return hashAlgorithm.hash(contents).hexadecimalRepresentation\n        }\n\n        public func checksum(forBinaryArtifactAt path: AbsolutePath) throws -> String {\n            try Self.checksum(\n                forBinaryArtifactAt: path,\n                hashAlgorithm: self.checksumAlgorithm,\n                archiver: self.archiver,\n                fileSystem: self.fileSystem\n            )\n        }\n\n        public func cancel(deadline: DispatchTime) throws {\n            if let cancellableArchiver = self.archiver as? Cancellable {\n                try cancellableArchiver.cancel(deadline: deadline)\n            }\n        }\n\n        private func fetch(\n            artifact: RemoteArtifact,\n            destination: AbsolutePath,\n            observabilityScope: ObservabilityScope,\n            progress: @escaping @Sendable (Int64, Int64?) -> Void\n        ) async throws -> Bool {\n            // not using cache, download directly\n            guard let cachePath = self.cachePath else {\n                self.delegate?.willDownloadBinaryArtifact(from: artifact.url.absoluteString, fromCache: false)\n                try await self.download(\n                    artifact: artifact,\n                    destination: destination,\n                    observabilityScope: observabilityScope,\n                    progress: progress\n                )\n\n                // not fetched from cache\n                return false\n            }\n\n            // initialize cache if necessary\n            if !self.fileSystem.exists(cachePath) {\n                try self.fileSystem.createDirectory(cachePath, recursive: true)\n            }\n\n            // try to fetch from cache, or download and cache\n            // / FIXME: use better escaping of URL\n            let cacheKey = artifact.url.absoluteString.spm_mangledToC99ExtendedIdentifier()\n            let cachedArtifactPath = cachePath.appending(cacheKey)\n\n            if self.fileSystem.exists(cachedArtifactPath) {\n                observabilityScope\n                    .emit(debug: \"copying cached binary artifact for \\(artifact.url) from \\(cachedArtifactPath)\")\n                self.delegate?.willDownloadBinaryArtifact(from: artifact.url.absoluteString, fromCache: true)\n\n                // copy from cache to destination\n                try self.fileSystem.copy(from: cachedArtifactPath, to: destination)\n                return true // fetched from cache\n            }\n\n            // download to the cache\n            observabilityScope\n                .emit(debug: \"downloading binary artifact for \\(artifact.url) to cache at \\(cachedArtifactPath)\")\n\n            self.delegate?.willDownloadBinaryArtifact(from: artifact.url.absoluteString, fromCache: false)\n\n            do {\n                try await self.download(\n                    artifact: artifact,\n                    destination: cachedArtifactPath,\n                    observabilityScope: observabilityScope,\n                    progress: progress\n                )\n                try self.fileSystem.copy(from: cachedArtifactPath, to: destination)\n                return false // not fetched from cache\n            } catch {\n                try? self.fileSystem.removeFileTree(cachedArtifactPath)\n                throw error\n            }\n        }\n\n        private func download(\n            artifact: RemoteArtifact,\n            destination: AbsolutePath,\n            observabilityScope: ObservabilityScope,\n            progress: @escaping @Sendable (Int64, Int64?) -> Void\n        ) async throws {\n            observabilityScope.emit(debug: \"downloading \\(artifact.url) to \\(destination)\")\n\n            var headers = HTTPClientHeaders()\n            headers.add(name: \"Accept\", value: \"application/octet-stream\")\n            var request = HTTPClient.Request.download(\n                url: artifact.url,\n                headers: headers,\n                fileSystem: self.fileSystem,\n                destination: destination\n            )\n            request.options.authorizationProvider = self.authorizationProvider?.httpAuthorizationHeader(for:)\n            request.options.retryStrategy = .exponentialBackoff(maxAttempts: 3, baseDelay: .milliseconds(50))\n            request.options.validResponseCodes = [200]\n\n            _ = try await self.httpClient.execute(request, progress: progress)\n        }\n    }\n}\n\n/// Delegate to notify clients about actions being performed by BinaryArtifactsDownloadsManage.\npublic protocol BinaryArtifactsManagerDelegate {\n    /// The workspace has started downloading a binary artifact.\n    func willDownloadBinaryArtifact(from url: String, fromCache: Bool)\n    /// The workspace has finished downloading a binary artifact.\n    func didDownloadBinaryArtifact(\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    )\n    /// The workspace is downloading a binary artifact.\n    func downloadingBinaryArtifact(from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?)\n    /// The workspace finished downloading all binary artifacts.\n    func didDownloadAllBinaryArtifacts()\n}\n\nextension Workspace.BinaryArtifactsManager {\n    struct RemoteArtifact {\n        let packageRef: PackageReference\n        let targetName: String\n        let url: URL\n        let checksum: String\n    }\n}\n\nextension Workspace.BinaryArtifactsManager {\n    struct ArchiveIndexFile: Decodable {\n        let schemaVersion: String\n        let archives: [Archive]\n\n        struct Archive: Decodable {\n            let fileName: String\n            let checksum: String\n            let supportedTriples: [Triple]\n\n            enum CodingKeys: String, CodingKey {\n                case fileName\n                case checksum\n                case supportedTriples\n            }\n\n            public init(from decoder: Decoder) throws {\n                let container = try decoder.container(keyedBy: CodingKeys.self)\n                self.fileName = try container.decode(String.self, forKey: .fileName)\n                self.checksum = try container.decode(String.self, forKey: .checksum)\n                self.supportedTriples = try container.decode([String].self, forKey: .supportedTriples).map(Triple.init)\n            }\n        }\n    }\n}\n\nextension Workspace.BinaryArtifactsManager {\n    static func deriveBinaryArtifact(\n        fileSystem: FileSystem,\n        path: AbsolutePath,\n        observabilityScope: ObservabilityScope\n    ) throws -> (AbsolutePath, BinaryModule.Kind)? {\n        let binaryArtifacts = try Self.deriveBinaryArtifacts(\n            fileSystem: fileSystem,\n            path: path,\n            observabilityScope: observabilityScope\n        )\n        if binaryArtifacts.count > 1, let binaryArtifact = binaryArtifacts.last {\n            // multiple ones, return the last one to preserve old behavior\n            observabilityScope\n                .emit(\n                    warning: \"multiple potential binary artifacts found: '\\(binaryArtifacts.map(\\.0.description).joined(separator: \"', '\"))', using the one in '\\(binaryArtifact.0)'\"\n                )\n            return binaryArtifact\n        } else if let binaryArtifact = binaryArtifacts.first {\n            // single one\n            observabilityScope.emit(info: \"found binary artifact: '\\(binaryArtifact)'\")\n            return binaryArtifact\n        } else {\n            return .none\n        }\n    }\n\n    private static func deriveBinaryArtifacts(\n        fileSystem: FileSystem,\n        path: AbsolutePath,\n        observabilityScope: ObservabilityScope\n    ) throws -> [(AbsolutePath, BinaryModule.Kind)] {\n        guard fileSystem.exists(path) else {\n            return []\n        }\n\n        let subdirectories = try fileSystem.getDirectoryContents(path)\n            .map { path.appending(component: $0) }\n            .filter { fileSystem.isDirectory($0) }\n\n        // is the current path it?\n        if let kind = try deriveBinaryArtifactKind(\n            fileSystem: fileSystem,\n            path: path,\n            observabilityScope: observabilityScope\n        ) {\n            return [(path, kind)]\n        }\n\n        // try to find a matching subdirectory\n        var results = [(AbsolutePath, BinaryModule.Kind)]()\n        for subdirectory in subdirectories {\n            observabilityScope.emit(debug: \"searching for binary artifact in '\\(path)'\")\n            let subdirectoryResults = try Self.deriveBinaryArtifacts(\n                fileSystem: fileSystem,\n                path: subdirectory,\n                observabilityScope: observabilityScope\n            )\n            results.append(contentsOf: subdirectoryResults)\n        }\n\n        return results\n    }\n\n    package static func deriveBinaryArtifactKind(\n        fileSystem: FileSystem,\n        path: AbsolutePath,\n        observabilityScope: ObservabilityScope\n    ) throws -> BinaryModule.Kind? {\n        let files = try fileSystem.getDirectoryContents(path)\n            .map { path.appending(component: $0) }\n            .filter { fileSystem.isFile($0) }\n\n        if let infoPlist = files.first(where: { $0.basename.lowercased() == \"info.plist\" }) {\n            let decoder = PropertyListDecoder()\n            do {\n                _ = try decoder.decode(XCFrameworkMetadata.self, from: fileSystem.readFileContents(infoPlist))\n                return .xcframework\n            } catch {\n                observabilityScope\n                    .emit(debug: \"info.plist found in '\\(path)' but failed to parse: \\(error.interpolationDescription)\")\n            }\n        }\n\n        if let infoJSON = files.first(where: { $0.basename.lowercased() == \"info.json\" }) {\n            do {\n                let metadata = try ArtifactsArchiveMetadata.parse(fileSystem: fileSystem, rootPath: infoJSON.parentDirectory)\n                return .artifactsArchive(types: metadata.artifacts.map { $0.value.type })\n            } catch {\n                observabilityScope.emit(\n                    debug: \"info.json found in '\\(path)' but failed to parse\",\n                    underlyingError: error\n                )\n            }\n        }\n\n        return .none\n    }\n}\n\nextension Workspace {\n    func updateBinaryArtifacts(\n        manifests: DependencyManifests,\n        addedOrUpdatedPackages: [PackageReference],\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        try await withAsyncThrowing {\n            try await self._updateBinaryArtifacts(\n                manifests: manifests,\n                addedOrUpdatedPackages: addedOrUpdatedPackages,\n                observabilityScope: observabilityScope\n            )\n        } defer: {\n            // Make sure the workspace state is saved exactly once, even if the method exits early.\n            // Files may have been deleted, download, etc. and the state needs to reflect that.\n            await observabilityScope.trap {\n                try await self.state.save()\n            }\n        }\n    }\n\n    private func _updateBinaryArtifacts(\n        manifests: DependencyManifests,\n        addedOrUpdatedPackages: [PackageReference],\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        let manifestArtifacts = try self.binaryArtifactsManager.parseArtifacts(\n            from: manifests,\n            identityResolver: self.identityResolver,\n            observabilityScope: observabilityScope\n        )\n\n        var artifactsToRemove: [ManagedArtifact] = []\n        var artifactsToAdd: [ManagedArtifact] = []\n        var artifactsToDownload: [BinaryArtifactsManager.RemoteArtifact] = []\n        var artifactsToExtract: [ManagedArtifact] = []\n\n        for artifact in await state.artifacts {\n            if !manifestArtifacts.local\n                .contains(where: { $0.packageRef == artifact.packageRef && $0.targetName == artifact.targetName }) &&\n                !manifestArtifacts.remote\n                .contains(where: { $0.packageRef == artifact.packageRef && $0.targetName == artifact.targetName })\n            {\n                artifactsToRemove.append(artifact)\n            }\n        }\n\n        for artifact in manifestArtifacts.local {\n            let existingArtifact = await self.state.artifacts[\n                packageIdentity: artifact.packageRef.identity,\n                targetName: artifact.targetName\n            ]\n\n            if artifact.path.extension?.lowercased() == \"zip\" {\n                // If we already have an artifact that was extracted from an archive with the same checksum,\n                // we don't need to extract the artifact again.\n                if case .local(let existingChecksum) = existingArtifact?.source,\n                   try existingChecksum == (self.binaryArtifactsManager.checksum(forBinaryArtifactAt: artifact.path))\n                {\n                    continue\n                }\n\n                artifactsToExtract.append(artifact)\n            } else {\n                guard let _ = try BinaryArtifactsManager.deriveBinaryArtifact(\n                    fileSystem: self.fileSystem,\n                    path: artifact.path,\n                    observabilityScope: observabilityScope\n                ) else {\n                    observabilityScope.emit(BinaryArtifactsManagerError.localArtifactNotFound(\n                        artifactPath: artifact.path,\n                        targetName: artifact.targetName\n                    ))\n                    continue\n                }\n                artifactsToAdd.append(artifact)\n            }\n\n            if let existingArtifact, isAtArtifactsDirectory(existingArtifact) {\n                // Remove the old extracted artifact, be it local archived or remote one.\n                artifactsToRemove.append(existingArtifact)\n            }\n        }\n\n        for artifact in manifestArtifacts.remote {\n            let existingArtifact = await self.state.artifacts[\n                packageIdentity: artifact.packageRef.identity,\n                targetName: artifact.targetName\n            ]\n\n            if let existingArtifact {\n                if case .remote(let existingURL, let existingChecksum) = existingArtifact.source {\n                    // If we already have an artifact with the same checksum, we don't need to download it again.\n                    if artifact.checksum == existingChecksum {\n                        continue\n                    }\n\n                    let urlChanged = artifact.url != URL(string: existingURL)\n                    // If the checksum is different but the package wasn't updated, this is a security risk.\n                    if !urlChanged && !addedOrUpdatedPackages.contains(artifact.packageRef) {\n                        observabilityScope.emit(\n                            BinaryArtifactsManagerError.artifactChecksumChanged(targetName: artifact.targetName)\n                        )\n                        continue\n                    }\n                }\n\n                if isAtArtifactsDirectory(existingArtifact) {\n                    // Remove the old extracted artifact, be it local archived or remote one.\n                    artifactsToRemove.append(existingArtifact)\n                }\n            }\n\n            artifactsToDownload.append(artifact)\n        }\n\n        // Remove the artifacts and directories which are not needed anymore.\n        await observabilityScope.trap {\n            for artifact in artifactsToRemove {\n                await state.artifacts.remove(\n                    packageIdentity: artifact.packageRef.identity,\n                    targetName: artifact.targetName\n                )\n\n                if isAtArtifactsDirectory(artifact) {\n                    try fileSystem.removeFileTree(artifact.path)\n                }\n            }\n\n            for directory in try fileSystem.getDirectoryContents(self.location.artifactsDirectory) {\n                let directoryPath = self.location.artifactsDirectory.appending(component: directory)\n                if try fileSystem.isDirectory(directoryPath) && fileSystem.getDirectoryContents(directoryPath).isEmpty {\n                    try fileSystem.removeFileTree(directoryPath)\n                }\n            }\n        }\n\n        guard !observabilityScope.errorsReported else {\n            throw Diagnostics.fatalError\n        }\n\n        // Download the artifacts\n        let downloadedArtifacts = try await self.binaryArtifactsManager.fetch(\n            artifactsToDownload,\n            artifactsDirectory: self.location.artifactsDirectory,\n            observabilityScope: observabilityScope\n        )\n        artifactsToAdd.append(contentsOf: downloadedArtifacts)\n\n        // Extract the local archived artifacts\n        let extractedLocalArtifacts = try await self.binaryArtifactsManager.extract(\n            artifactsToExtract,\n            artifactsDirectory: self.location.artifactsDirectory,\n            observabilityScope: observabilityScope\n        )\n        artifactsToAdd.append(contentsOf: extractedLocalArtifacts)\n\n        // Add the new artifacts\n        for artifact in artifactsToAdd {\n            await self.state.artifacts.add(artifact)\n        }\n\n        guard !observabilityScope.errorsReported else {\n            throw Diagnostics.fatalError\n        }\n\n        func isAtArtifactsDirectory(_ artifact: ManagedArtifact) -> Bool {\n            artifact.path.isDescendant(of: self.location.artifactsDirectory)\n        }\n    }\n}\n\nextension FileSystem {\n    // helper to decide if an archive directory would benefit from stripping first level\n    fileprivate func shouldStripFirstLevel(\n        archiveDirectory: AbsolutePath,\n        acceptableExtensions: [String]? = nil\n    ) throws -> Bool {\n        let subdirectories = try self.getDirectoryContents(archiveDirectory)\n            .map { archiveDirectory.appending(component: $0) }\n            .filter { self.isDirectory($0) }\n\n        // single top-level directory required\n        guard subdirectories.count == 1, let rootDirectory = subdirectories.first else {\n            return false\n        }\n\n        // no acceptable extensions defined, so the single top-level directory is a good candidate\n        guard let acceptableExtensions else {\n            return true\n        }\n\n        // the single top-level directory is already one of the acceptable extensions, so no need to strip\n        if rootDirectory.extension.map({ acceptableExtensions.contains($0) }) ?? false {\n            return false\n        }\n\n        // see if there is \"grand-child\" directory with one of the acceptable extensions\n        return try self.getDirectoryContents(rootDirectory)\n            .map { rootDirectory.appending(component: $0) }\n            .first { $0.extension.map { acceptableExtensions.contains($0) } ?? false } != nil\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Configuration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageFingerprint\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport PackageRegistry\n\nimport struct TSCBasic.ByteString\n\nimport protocol TSCUtility.SimplePersistanceProtocol\nimport class TSCUtility.SimplePersistence\n\n// MARK: - Location\n\nextension Workspace {\n    /// Workspace location configuration\n    public struct Location {\n        /// Path to scratch space (working) directory for this workspace (aka .build).\n        public var scratchDirectory: AbsolutePath\n\n        /// Path to store the editable versions of dependencies.\n        public var editsDirectory: AbsolutePath\n\n        /// Path to the Package.resolved file.\n        public var resolvedVersionsFile: AbsolutePath\n\n        /// Path to the local configuration directory.\n        public var localConfigurationDirectory: AbsolutePath\n\n        /// Path to the shared configuration directory.\n        public var sharedConfigurationDirectory: AbsolutePath?\n\n        /// Path to the shared security directory.\n        public var sharedSecurityDirectory: AbsolutePath?\n\n        /// Path to the shared cache directory.\n        public var sharedCacheDirectory: AbsolutePath?\n\n        /// Path to the shared Swift SDKs directory.\n        public var sharedSwiftSDKsDirectory: AbsolutePath?\n\n        /// Whether or not to emit a warning about the existence of deprecated configuration files.\n        public var emitDeprecatedConfigurationWarning: Bool\n\n        // working directories\n\n        /// Path to the repositories clones.\n        public var repositoriesDirectory: AbsolutePath {\n            self.scratchDirectory.appending(\"repositories\")\n        }\n\n        /// Path to the repository checkouts.\n        public var repositoriesCheckoutsDirectory: AbsolutePath {\n            self.scratchDirectory.appending(\"checkouts\")\n        }\n\n        /// Path to the registry downloads.\n        public var registryDownloadDirectory: AbsolutePath {\n            self.scratchDirectory.appending(components: \"registry\", \"downloads\")\n        }\n\n        /// Path to the downloaded binary artifacts.\n        public var artifactsDirectory: AbsolutePath {\n            self.scratchDirectory.appending(\"artifacts\")\n        }\n\n        /// Path to the downloaded prebuilts directory\n        public var prebuiltsDirectory: AbsolutePath {\n            self.scratchDirectory.appending(\"prebuilts\")\n        }\n\n        // Path to temporary files related to running plugins in the workspace\n        public var pluginWorkingDirectory: AbsolutePath {\n            self.scratchDirectory.appending(\"plugins\")\n        }\n\n        // config locations\n\n        /// Path to the local mirrors configuration.\n        public var localMirrorsConfigurationFile: AbsolutePath {\n            get throws {\n                // backwards compatibility\n                if let customPath = Environment.current[\"SWIFTPM_MIRROR_CONFIG\"] {\n                    return try AbsolutePath(validating: customPath)\n                }\n                return DefaultLocations.mirrorsConfigurationFile(at: self.localConfigurationDirectory)\n            }\n        }\n\n        /// Path to the shared mirrors configuration.\n        public var sharedMirrorsConfigurationFile: AbsolutePath? {\n            self.sharedConfigurationDirectory.map { DefaultLocations.mirrorsConfigurationFile(at: $0) }\n        }\n\n        /// Path to the local registries configuration.\n        public var localRegistriesConfigurationFile: AbsolutePath {\n            DefaultLocations.registriesConfigurationFile(at: self.localConfigurationDirectory)\n        }\n\n        /// Path to the shared registries configuration.\n        public var sharedRegistriesConfigurationFile: AbsolutePath? {\n            self.sharedConfigurationDirectory.map { DefaultLocations.registriesConfigurationFile(at: $0) }\n        }\n\n        // security locations\n\n        /// Path to the shared fingerprints directory.\n        public var sharedFingerprintsDirectory: AbsolutePath? {\n            self.sharedSecurityDirectory.map { $0.appending(\"fingerprints\") }\n        }\n\n        /// Path to the shared directory where package signing records are kept.\n        public var sharedSigningEntitiesDirectory: AbsolutePath? {\n            self.sharedSecurityDirectory.map { $0.appending(\"signing-entities\") }\n        }\n\n        /// Path to the shared trusted root certificates directory.\n        public var sharedTrustedRootCertificatesDirectory: AbsolutePath? {\n            self.sharedSecurityDirectory.map { $0.appending(\"trusted-root-certs\") }\n        }\n\n        // cache locations\n\n        /// Path to the shared manifests cache.\n        public var sharedManifestsCacheDirectory: AbsolutePath? {\n            self.sharedCacheDirectory.map { DefaultLocations.manifestsDirectory(at: $0) }\n        }\n\n        /// Path to the shared repositories cache.\n        public var sharedRepositoriesCacheDirectory: AbsolutePath? {\n            self.sharedCacheDirectory.map { $0.appending(\"repositories\") }\n        }\n\n        /// Path to the shared registry download cache.\n        public var sharedRegistryDownloadsCacheDirectory: AbsolutePath? {\n            self.sharedCacheDirectory.map { $0.appending(components: \"registry\", \"downloads\") }\n        }\n\n        /// Path to the shared repositories cache.\n        public var sharedBinaryArtifactsCacheDirectory: AbsolutePath? {\n            self.sharedCacheDirectory.map { $0.appending(\"artifacts\") }\n        }\n\n        /// Path to the shared prebuilts cache\n        public var sharedPrebuiltsCacheDirectory: AbsolutePath? {\n            self.sharedCacheDirectory.map { $0.appending(\"prebuilts\")}\n        }\n\n        /// Create a new workspace location.\n        ///\n        /// - Parameters:\n        ///   - scratchDirectory: Path to scratch space (working) directory for this workspace.\n        ///   - editsDirectory: Path to store the editable versions of dependencies.\n        ///   - resolvedVersionsFile: Path to the Package.resolved file.\n        ///   - sharedSecurityDirectory: Path to the shared security directory.\n        ///   - sharedCacheDirectory: Path to the shared cache directory.\n        ///   - sharedConfigurationDirectory: Path to the shared configuration directory.\n        public init(\n            scratchDirectory: AbsolutePath,\n            editsDirectory: AbsolutePath,\n            resolvedVersionsFile: AbsolutePath,\n            localConfigurationDirectory: AbsolutePath,\n            sharedConfigurationDirectory: AbsolutePath?,\n            sharedSecurityDirectory: AbsolutePath?,\n            sharedCacheDirectory: AbsolutePath?,\n            emitDeprecatedConfigurationWarning: Bool = true\n        ) {\n            self.scratchDirectory = scratchDirectory\n            self.editsDirectory = editsDirectory\n            self.resolvedVersionsFile = resolvedVersionsFile\n            self.localConfigurationDirectory = localConfigurationDirectory\n            self.sharedConfigurationDirectory = sharedConfigurationDirectory\n            self.sharedSecurityDirectory = sharedSecurityDirectory\n            self.sharedCacheDirectory = sharedCacheDirectory\n            self.emitDeprecatedConfigurationWarning = emitDeprecatedConfigurationWarning\n        }\n\n        /// Create a new workspace location.\n        ///\n        /// - Parameters:\n        ///   - rootPath: Path to the root of the package, from which other locations can be derived.\n        public init(forRootPackage rootPath: AbsolutePath, fileSystem: FileSystem) throws {\n            try self.init(\n                scratchDirectory: DefaultLocations.scratchDirectory(forRootPackage: rootPath),\n                editsDirectory: DefaultLocations.editsDirectory(forRootPackage: rootPath),\n                resolvedVersionsFile: DefaultLocations.resolvedVersionsFile(forRootPackage: rootPath),\n                localConfigurationDirectory: DefaultLocations.configurationDirectory(forRootPackage: rootPath),\n                sharedConfigurationDirectory: fileSystem.swiftPMConfigurationDirectory,\n                sharedSecurityDirectory: fileSystem.swiftPMSecurityDirectory,\n                sharedCacheDirectory: fileSystem.swiftPMCacheDirectory\n            )\n        }\n    }\n}\n\n// MARK: - Default locations\n\nextension Workspace {\n    /// Workspace default locations utilities\n    public struct DefaultLocations {\n        public static var resolvedFileName = \"Package.resolved\"\n\n        public static func scratchDirectory(forRootPackage rootPath: AbsolutePath) -> AbsolutePath {\n            rootPath.appending(\".build\")\n        }\n\n        public static func editsDirectory(forRootPackage rootPath: AbsolutePath) -> AbsolutePath {\n            rootPath.appending(\"Packages\")\n        }\n\n        public static func resolvedVersionsFile(forRootPackage rootPath: AbsolutePath) -> AbsolutePath {\n            rootPath.appending(self.resolvedFileName)\n        }\n\n        public static func configurationDirectory(forRootPackage rootPath: AbsolutePath) -> AbsolutePath {\n            rootPath.appending(components: \".swiftpm\", \"configuration\")\n        }\n\n        public static func mirrorsConfigurationFile(forRootPackage rootPath: AbsolutePath) -> AbsolutePath {\n            self.mirrorsConfigurationFile(at: self.configurationDirectory(forRootPackage: rootPath))\n        }\n\n        public static func mirrorsConfigurationFile(at path: AbsolutePath) -> AbsolutePath {\n            path.appending(\"mirrors.json\")\n        }\n\n        public static func registriesConfigurationFile(forRootPackage rootPath: AbsolutePath) -> AbsolutePath {\n            self.registriesConfigurationFile(at: self.configurationDirectory(forRootPackage: rootPath))\n        }\n\n        public static func registriesConfigurationFile(at path: AbsolutePath) -> AbsolutePath {\n            path.appending(\"registries.json\")\n        }\n\n        public static func manifestsDirectory(at path: AbsolutePath) -> AbsolutePath {\n            path.appending(\"manifests\")\n        }\n    }\n\n    public static func migrateMirrorsConfiguration(\n        from legacyPath: AbsolutePath,\n        to newPath: AbsolutePath,\n        observabilityScope: ObservabilityScope\n    ) throws -> AbsolutePath {\n        if localFileSystem.isFile(legacyPath) {\n            if localFileSystem.isSymlink(legacyPath) {\n                let resolvedLegacyPath = try resolveSymlinks(legacyPath)\n                return try self.migrateMirrorsConfiguration(\n                    from: resolvedLegacyPath,\n                    to: newPath,\n                    observabilityScope: observabilityScope\n                )\n            } else if localFileSystem.isFile(newPath.parentDirectory) {\n                observabilityScope\n                    .emit(\n                        warning: \"Unable to migrate legacy mirrors configuration, because \\(newPath.parentDirectory) already exists.\"\n                    )\n            } else if let content = try? localFileSystem.readFileContents(legacyPath), content.count > 0 {\n                observabilityScope\n                    .emit(\n                        warning: \"Usage of \\(legacyPath) has been deprecated. Please delete it and use the new \\(newPath) instead.\"\n                    )\n                if !localFileSystem.exists(newPath, followSymlink: false) {\n                    try localFileSystem.createDirectory(newPath.parentDirectory, recursive: true)\n                    try localFileSystem.copy(from: legacyPath, to: newPath)\n                }\n            }\n        }\n        return newPath.parentDirectory\n    }\n}\n\n// MARK: - Authorization\n\nextension Workspace.Configuration {\n    public struct Authorization {\n        public var netrc: Netrc\n        public var keychain: Keychain\n\n        public static var `default`: Self {\n            #if canImport(Security)\n            Self(netrc: .user, keychain: .enabled)\n            #else\n            Self(netrc: .user, keychain: .disabled)\n            #endif\n        }\n\n        public init(netrc: Netrc, keychain: Keychain) {\n            self.netrc = netrc\n            self.keychain = keychain\n        }\n\n        public func makeAuthorizationProvider(\n            fileSystem: FileSystem,\n            observabilityScope: ObservabilityScope\n        ) throws -> AuthorizationProvider? {\n            var providers = [AuthorizationProvider]()\n\n            switch self.netrc {\n            case .custom(let path):\n                guard fileSystem.exists(path) else {\n                    throw StringError(\"Did not find netrc file at \\(path).\")\n                }\n                try providers.append(NetrcAuthorizationProvider(path: path, fileSystem: fileSystem))\n            case .user:\n                // user .netrc file (most typical)\n                let userHomePath = try fileSystem.homeDirectory.appending(\".netrc\")\n\n                // user didn't tell us to explicitly use these .netrc files so be more lenient with errors\n                if let userHomeProvider = self.loadOptionalNetrc(\n                    fileSystem: fileSystem,\n                    path: userHomePath,\n                    observabilityScope: observabilityScope\n                ) {\n                    providers.append(userHomeProvider)\n                }\n            case .disabled:\n                // noop\n                break\n            }\n\n            switch self.keychain {\n            case .enabled:\n                #if canImport(Security)\n                providers.append(KeychainAuthorizationProvider(observabilityScope: observabilityScope))\n                #else\n                throw InternalError(\"Keychain not supported on this platform\")\n                #endif\n            case .disabled:\n                // noop\n                break\n            }\n\n            return providers.isEmpty ? .none : CompositeAuthorizationProvider(\n                providers,\n                observabilityScope: observabilityScope\n            )\n        }\n\n        public func makeRegistryAuthorizationProvider(\n            fileSystem: FileSystem,\n            observabilityScope: ObservabilityScope\n        ) throws -> AuthorizationProvider? {\n            var providers = [AuthorizationProvider]()\n\n            // OS-specific AuthorizationProvider has higher precedence\n            switch self.keychain {\n            case .enabled:\n                #if canImport(Security)\n                providers.append(KeychainAuthorizationProvider(observabilityScope: observabilityScope))\n                #else\n                throw InternalError(\"Keychain not supported on this platform\")\n                #endif\n            case .disabled:\n                // noop\n                break\n            }\n\n            switch self.netrc {\n            case .custom(let path):\n                guard fileSystem.exists(path) else {\n                    throw StringError(\"did not find netrc file at \\(path)\")\n                }\n                try providers.append(NetrcAuthorizationProvider(path: path, fileSystem: fileSystem))\n            case .user:\n                let userHomePath = try fileSystem.homeDirectory.appending(\".netrc\")\n                // Add user .netrc file unless we don't have access\n                if let userHomeProvider = try? NetrcAuthorizationProvider(path: userHomePath, fileSystem: fileSystem) {\n                    providers.append(userHomeProvider)\n                }\n            case .disabled:\n                throw InternalError(\"netrc file should not have been disabled\")\n            }\n\n            // Use at-most one AuthorizationProvider (i.e., no CompositeAuthorizationProvider)\n            return providers.first\n        }\n\n        private func loadOptionalNetrc(\n            fileSystem: FileSystem,\n            path: AbsolutePath,\n            observabilityScope: ObservabilityScope\n        ) -> NetrcAuthorizationProvider? {\n            guard fileSystem.exists(path) && fileSystem.isReadable(path) else {\n                return .none\n            }\n\n            do {\n                return try NetrcAuthorizationProvider(path: path, fileSystem: fileSystem)\n            } catch {\n                observabilityScope.emit(\n                    warning: \"Failed to load netrc file at \\(path)\",\n                    underlyingError: error\n                )\n                return .none\n            }\n        }\n\n        public enum Netrc {\n            case disabled\n            case custom(AbsolutePath)\n            case user\n        }\n\n        public enum Keychain {\n            case disabled\n            case enabled\n        }\n    }\n}\n\n// MARK: - Mirrors\n\nextension Workspace.Configuration {\n    public struct Mirrors {\n        private let localMirrors: MirrorsStorage\n        private let sharedMirrors: MirrorsStorage?\n        private let fileSystem: FileSystem\n\n        private var _mirrors: DependencyMirrors\n        private let lock = NSLock()\n\n        /// The mirrors in this configuration\n        public var mirrors: DependencyMirrors {\n            self.lock.withLock {\n                self._mirrors\n            }\n        }\n\n        /// A convenience initializer for creating a workspace mirrors configuration for the given root\n        /// package path.\n        ///\n        /// - Parameters:\n        ///   - forRootPackage: The path for the root package.\n        ///   - sharedMirrorFile: Path to the shared mirrors configuration file, defaults to the standard location.\n        ///   - fileSystem: The file system to use.\n        public init(\n            forRootPackage rootPath: AbsolutePath,\n            sharedMirrorFile: AbsolutePath?,\n            fileSystem: FileSystem\n        ) throws {\n            let localMirrorConfigFile = Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: rootPath)\n            try self.init(\n                fileSystem: fileSystem,\n                localMirrorsFile: localMirrorConfigFile,\n                sharedMirrorsFile: sharedMirrorFile\n            )\n        }\n\n        /// Initialize the workspace mirrors configuration\n        ///\n        /// - Parameters:\n        ///   - fileSystem: The file system to use.\n        ///   - localMirrorsFile: Path to the workspace mirrors configuration file\n        ///   - sharedMirrorsFile: Path to the shared mirrors configuration file, defaults to the standard location.\n        public init(\n            fileSystem: FileSystem,\n            localMirrorsFile: AbsolutePath,\n            sharedMirrorsFile: AbsolutePath?\n        ) throws {\n            self.localMirrors = .init(path: localMirrorsFile, fileSystem: fileSystem, deleteWhenEmpty: true)\n            self.sharedMirrors = sharedMirrorsFile\n                .map { .init(path: $0, fileSystem: fileSystem, deleteWhenEmpty: false) }\n            self.fileSystem = fileSystem\n            // computes the initial mirrors\n            self._mirrors = try DependencyMirrors()\n            try self.computeMirrors()\n        }\n\n        @discardableResult\n        public func applyLocal(handler: (inout DependencyMirrors) throws -> Void) throws -> DependencyMirrors {\n            try self.localMirrors.apply(handler: handler)\n            try self.computeMirrors()\n            return self.mirrors\n        }\n\n        @discardableResult\n        public func applyShared(handler: (inout DependencyMirrors) throws -> Void) throws -> DependencyMirrors {\n            guard let sharedMirrors else {\n                throw InternalError(\"shared mirrors not configured\")\n            }\n            try sharedMirrors.apply(handler: handler)\n            try self.computeMirrors()\n            return self.mirrors\n        }\n\n        // mutating the state we hold since we are passing it by reference to the workspace\n        // access should be done using a lock\n        private func computeMirrors() throws {\n            try self.lock.withLock {\n                self._mirrors.removeAll()\n\n                // prefer local mirrors to shared ones\n                let local = try self.localMirrors.get()\n                if !local.isEmpty {\n                    try self._mirrors.append(contentsOf: local)\n                    return\n                }\n\n                // use shared if local was not found or empty\n                if let shared = try self.sharedMirrors?.get(), !shared.isEmpty {\n                    try self._mirrors.append(contentsOf: shared)\n                }\n            }\n        }\n    }\n}\n\nextension Workspace.Configuration {\n    public struct MirrorsStorage {\n        private let path: AbsolutePath\n        private let fileSystem: FileSystem\n        private let deleteWhenEmpty: Bool\n\n        public init(path: AbsolutePath, fileSystem: FileSystem, deleteWhenEmpty: Bool) {\n            self.path = path\n            self.fileSystem = fileSystem\n            self.deleteWhenEmpty = deleteWhenEmpty\n        }\n\n        /// The mirrors in this configuration\n        public func get() throws -> DependencyMirrors {\n            guard self.fileSystem.exists(self.path) else {\n                return try DependencyMirrors()\n            }\n            return try self.fileSystem.withLock(on: self.path.parentDirectory, type: .shared) {\n                try DependencyMirrors(Self.load(self.path, fileSystem: self.fileSystem))\n            }\n        }\n\n        /// Apply a mutating handler on the mirrors in this configuration\n        @discardableResult\n        public func apply(handler: (inout DependencyMirrors) throws -> Void) throws -> DependencyMirrors {\n            if !self.fileSystem.exists(self.path.parentDirectory) {\n                try self.fileSystem.createDirectory(self.path.parentDirectory, recursive: true)\n            }\n            return try self.fileSystem.withLock(on: self.path.parentDirectory, type: .exclusive) {\n                let mirrors = try DependencyMirrors(Self.load(self.path, fileSystem: self.fileSystem))\n                var updatedMirrors = try DependencyMirrors(mirrors.mapping)\n                try handler(&updatedMirrors)\n                if updatedMirrors != mirrors {\n                    try Self.save(\n                        updatedMirrors.mapping,\n                        to: self.path,\n                        fileSystem: self.fileSystem,\n                        deleteWhenEmpty: self.deleteWhenEmpty\n                    )\n                }\n                return updatedMirrors\n            }\n        }\n\n        private static func load(_ path: AbsolutePath, fileSystem: FileSystem) throws -> [String: String] {\n            guard fileSystem.exists(path) else {\n                return [:]\n            }\n            let data: Data = try fileSystem.readFileContents(path)\n            let decoder = JSONDecoder.makeWithDefaults()\n            let mirrors = try decoder.decode(MirrorsStorage.self, from: data)\n            let mirrorsMap = Dictionary(\n                mirrors.object.map { ($0.original, $0.mirror) },\n                uniquingKeysWith: { first, _ in first }\n            )\n            return mirrorsMap\n        }\n\n        private static func save(\n            _ mirrors: [String: String],\n            to path: AbsolutePath,\n            fileSystem: FileSystem,\n            deleteWhenEmpty: Bool\n        ) throws {\n            if mirrors.isEmpty {\n                if deleteWhenEmpty && fileSystem.exists(path) {\n                    // deleteWhenEmpty is a backward compatibility mode\n                    return try fileSystem.removeFileTree(path)\n                } else if !fileSystem.exists(path) {\n                    // nothing to do\n                    return\n                }\n            }\n\n            let encoder = JSONEncoder.makeWithDefaults()\n            let mirrors = MirrorsStorage(version: 1, object: mirrors.map { .init(original: $0, mirror: $1) })\n            let data = try encoder.encode(mirrors)\n            if !fileSystem.exists(path.parentDirectory) {\n                try fileSystem.createDirectory(path.parentDirectory, recursive: true)\n            }\n            try fileSystem.writeFileContents(path, data: data)\n        }\n\n        // structure is for backwards compatibility\n        private struct MirrorsStorage: Codable {\n            var version: Int\n            var object: [Mirror]\n\n            struct Mirror: Codable {\n                var original: String\n                var mirror: String\n            }\n        }\n    }\n}\n\n// MARK: - Registries\n\nextension Workspace.Configuration {\n    public class Registries {\n        private let localRegistries: RegistriesStorage?\n        private let sharedRegistries: RegistriesStorage?\n        private let fileSystem: FileSystem\n\n        private var _configuration = RegistryConfiguration()\n        private let lock = NSLock()\n\n        /// The registry configuration\n        public var configuration: RegistryConfiguration {\n            self.lock.withLock {\n                self._configuration\n            }\n        }\n\n        /// Initialize the workspace registries configuration\n        ///\n        /// - Parameters:\n        ///   - fileSystem: The file system to use.\n        ///   - localRegistriesFile: Path to the workspace registries configuration file\n        ///   - sharedRegistriesFile: Path to the shared registries configuration file,\n        ///                           defaults to the standard location.\n        public init(\n            fileSystem: FileSystem,\n            localRegistriesFile: AbsolutePath?,\n            sharedRegistriesFile: AbsolutePath?\n        ) throws {\n            // At least one of local or shared is required\n            if localRegistriesFile == nil, sharedRegistriesFile == nil {\n                throw StringError(\"No registries configuration provided\")\n            }\n\n            self.fileSystem = fileSystem\n            self.localRegistries = localRegistriesFile.map { .init(path: $0, fileSystem: fileSystem) }\n            self.sharedRegistries = sharedRegistriesFile.map { .init(path: $0, fileSystem: fileSystem) }\n            try self.computeRegistries()\n        }\n\n        @discardableResult\n        public func updateLocal(with handler: (inout RegistryConfiguration) throws -> Void) throws\n            -> RegistryConfiguration\n        {\n            guard let localRegistries else {\n                throw InternalError(\"local registries not configured\")\n            }\n            try localRegistries.update(with: handler)\n            try self.computeRegistries()\n            return self.configuration\n        }\n\n        @discardableResult\n        public func updateShared(with handler: (inout RegistryConfiguration) throws -> Void) throws\n            -> RegistryConfiguration\n        {\n            guard let sharedRegistries else {\n                throw InternalError(\"shared registries not configured\")\n            }\n            try sharedRegistries.update(with: handler)\n            try self.computeRegistries()\n            return self.configuration\n        }\n\n        // mutating the state we hold since we are passing it by reference to the workspace\n        // access should be done using a lock\n        private func computeRegistries() throws {\n            try self.lock.withLock {\n                var configuration = RegistryConfiguration()\n\n                if let sharedConfiguration = try sharedRegistries?.load() {\n                    configuration.merge(sharedConfiguration)\n                }\n\n                if let localConfiguration = try localRegistries?.load() {\n                    configuration.merge(localConfiguration)\n                }\n\n                self._configuration = configuration\n            }\n        }\n    }\n}\n\nextension Workspace.Configuration {\n    private struct RegistriesStorage {\n        private let path: AbsolutePath\n        private let fileSystem: FileSystem\n\n        public init(path: AbsolutePath, fileSystem: FileSystem) {\n            self.path = path\n            self.fileSystem = fileSystem\n        }\n\n        public func load() throws -> RegistryConfiguration {\n            guard self.fileSystem.exists(self.path) else {\n                return RegistryConfiguration()\n            }\n\n            do {\n                let decoder = JSONDecoder.makeWithDefaults()\n                return try decoder.decode(path: self.path, fileSystem: self.fileSystem, as: RegistryConfiguration.self)\n            } catch {\n                throw StringError(\n                    \"Failed loading registries configuration from '\\(self.path)': \\(error.interpolationDescription)\"\n                )\n            }\n        }\n\n        public func save(_ configuration: RegistryConfiguration) throws {\n            let encoder = JSONEncoder.makeWithDefaults()\n            let data = try encoder.encode(configuration)\n\n            if !self.fileSystem.exists(self.path.parentDirectory) {\n                try self.fileSystem.createDirectory(self.path.parentDirectory, recursive: true)\n            }\n            try self.fileSystem.writeFileContents(self.path, data: data)\n        }\n\n        @discardableResult\n        public func update(with handler: (inout RegistryConfiguration) throws -> Void) throws -> RegistryConfiguration {\n            let configuration = try load()\n            var updatedConfiguration = configuration\n            try handler(&updatedConfiguration)\n            if updatedConfiguration != configuration {\n                try self.save(updatedConfiguration)\n            }\n\n            return updatedConfiguration\n        }\n    }\n}\n\n// FIXME: better name\npublic struct WorkspaceConfiguration {\n    /// Enables the dependencies resolver automatic version updates.  Disabled by default.\n    /// When disabled the resolver does not attempt to update the dependencies as part of resolution.\n    public var skipDependenciesUpdates: Bool\n\n    /// Enables the dependencies resolver prefetching based on the resolved versions file.  Enabled by default.\n    /// When disabled the resolver does not attempt to pre-fetch the dependencies based on the  resolved versions file.\n    public var prefetchBasedOnResolvedFile: Bool\n\n    /// File rules to determine resource handling behavior.\n    public var additionalFileRules: [FileRuleDescription]\n\n    /// Enables the shared dependencies cache. Enabled by default.\n    public var sharedDependenciesCacheEnabled: Bool\n\n    ///  Fingerprint checking mode. Defaults to strict.\n    public var fingerprintCheckingMode: CheckingMode\n\n    ///  Signing entity checking mode. Defaults to warn.\n    public var signingEntityCheckingMode: CheckingMode\n\n    /// Whether to skip validating signature of signed packages downloaded from registry\n    public var skipSignatureValidation: Bool\n\n    ///  Attempt to transform source control based dependencies to registry ones\n    public var sourceControlToRegistryDependencyTransformation: SourceControlToRegistryDependencyTransformation\n\n    /// URL of the implicitly configured, default registry\n    public var defaultRegistry: Registry?\n\n    /// Whether to create multiple test products or one per package\n    public var shouldCreateMultipleTestProducts: Bool\n\n    /// Whether to create a product for use in the Swift REPL\n    public var createREPLProduct: Bool\n\n    /// Whether or not there should be import restrictions applied when loading manifests\n    public var manifestImportRestrictions: (startingToolsVersion: ToolsVersion, allowedImports: [String])?\n\n    /// Whether or not to use prebuilt swift-syntax for macros\n    public var usePrebuilts: Bool\n\n    /// String URL to allow override of the prebuilts download location\n    public var prebuiltsDownloadURL: String?\n\n    /// Path to root certificate used when validating the manifest signing during testing\n    public var prebuiltsRootCertPath: String?\n\n    /// Whether to omit unused dependencies.\n    public var pruneDependencies: Bool\n\n    /// The trait configuration for the root.\n    public var traitConfiguration: TraitConfiguration\n\n    public init(\n        skipDependenciesUpdates: Bool,\n        prefetchBasedOnResolvedFile: Bool,\n        shouldCreateMultipleTestProducts: Bool,\n        createREPLProduct: Bool,\n        additionalFileRules: [FileRuleDescription],\n        sharedDependenciesCacheEnabled: Bool,\n        fingerprintCheckingMode: CheckingMode,\n        signingEntityCheckingMode: CheckingMode,\n        skipSignatureValidation: Bool,\n        sourceControlToRegistryDependencyTransformation: SourceControlToRegistryDependencyTransformation,\n        defaultRegistry: Registry?,\n        manifestImportRestrictions: (startingToolsVersion: ToolsVersion, allowedImports: [String])?,\n        usePrebuilts: Bool,\n        prebuiltsDownloadURL: String?,\n        prebuiltsRootCertPath: String?,\n        pruneDependencies: Bool,\n        traitConfiguration: TraitConfiguration\n    ) {\n        self.skipDependenciesUpdates = skipDependenciesUpdates\n        self.prefetchBasedOnResolvedFile = prefetchBasedOnResolvedFile\n        self.shouldCreateMultipleTestProducts = shouldCreateMultipleTestProducts\n        self.createREPLProduct = createREPLProduct\n        self.additionalFileRules = additionalFileRules\n        self.sharedDependenciesCacheEnabled = sharedDependenciesCacheEnabled\n        self.fingerprintCheckingMode = fingerprintCheckingMode\n        self.signingEntityCheckingMode = signingEntityCheckingMode\n        self.skipSignatureValidation = skipSignatureValidation\n        self.sourceControlToRegistryDependencyTransformation = sourceControlToRegistryDependencyTransformation\n        self.defaultRegistry = defaultRegistry\n        self.manifestImportRestrictions = manifestImportRestrictions\n        self.usePrebuilts = usePrebuilts\n        self.prebuiltsDownloadURL = prebuiltsDownloadURL\n        self.prebuiltsRootCertPath = prebuiltsRootCertPath\n        self.pruneDependencies = pruneDependencies\n        self.traitConfiguration = traitConfiguration\n    }\n\n    /// Default instance of WorkspaceConfiguration\n    public static var `default`: Self {\n        .init(\n            skipDependenciesUpdates: false,\n            prefetchBasedOnResolvedFile: true,\n            shouldCreateMultipleTestProducts: false,\n            createREPLProduct: false,\n            additionalFileRules: [],\n            sharedDependenciesCacheEnabled: true,\n            fingerprintCheckingMode: .strict,\n            signingEntityCheckingMode: .warn,\n            skipSignatureValidation: false,\n            sourceControlToRegistryDependencyTransformation: .disabled,\n            defaultRegistry: .none,\n            manifestImportRestrictions: .none,\n            usePrebuilts: false,\n            prebuiltsDownloadURL: nil,\n            prebuiltsRootCertPath: nil,\n            pruneDependencies: false,\n            traitConfiguration: .default\n        )\n    }\n\n    public enum SourceControlToRegistryDependencyTransformation {\n        case disabled\n        case identity\n        case swizzle\n    }\n\n    public enum CheckingMode: String {\n        case strict\n        case warn\n    }\n}\n\n// MARK: - Deprecated 8/20201\n\nextension Workspace {\n    /// Manages a package workspace's configuration.\n    // FIXME: change into enum after deprecation grace period\n    public final class Configuration {}\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Delegation.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport struct Basics.Diagnostic\nimport enum Dispatch.DispatchTimeInterval\nimport struct Foundation.URL\nimport class PackageLoading.ManifestLoader\nimport class PackageModel.Manifest\nimport struct PackageModel.PackageIdentity\nimport struct PackageModel.PackageReference\nimport struct PackageModel.Registry\nimport class PackageRegistry.RegistryClient\nimport class PackageRegistry.RegistryDownloadsManager\nimport class SourceControl.RepositoryManager\nimport struct SourceControl.RepositorySpecifier\nimport struct TSCUtility.Version\n\n/// The delegate interface used by the workspace to report status information.\npublic protocol WorkspaceDelegate: AnyObject {\n    /// The workspace is about to load a package manifest (which might be in the cache, or might need to be parsed).\n    /// Note that this does not include speculative loading of manifests that may occur during\n    /// dependency resolution; rather, it includes only the final manifest loading that happens after a particular\n    /// package version has been checked out into a working directory.\n    func willLoadManifest(\n        packageIdentity: PackageIdentity,\n        packagePath: AbsolutePath,\n        url: String,\n        version: Version?,\n        packageKind: PackageReference.Kind\n    )\n    /// The workspace has loaded a package manifest, either successfully or not. The manifest is nil if an error occurs,\n    /// in which case there will also be at least one error in the list of diagnostics (there may be warnings even if a\n    /// manifest is loaded successfully).\n    func didLoadManifest(\n        packageIdentity: PackageIdentity,\n        packagePath: AbsolutePath,\n        url: String,\n        version: Version?,\n        packageKind: PackageReference.Kind,\n        manifest: Manifest?,\n        diagnostics: [Diagnostic],\n        duration: DispatchTimeInterval\n    )\n\n    /// The workspace is about to compile a package manifest, as reported by the assigned manifest loader. this happens\n    /// for non-cached manifests\n    func willCompileManifest(packageIdentity: PackageIdentity, packageLocation: String)\n    /// The workspace successfully compiled a package manifest, as reported by the assigned manifest loader. this\n    /// happens for non-cached manifests\n    func didCompileManifest(packageIdentity: PackageIdentity, packageLocation: String, duration: DispatchTimeInterval)\n\n    /// The workspace is about to evaluate (execute) a compiled package manifest, as reported by the assigned manifest\n    /// loader. this happens for non-cached manifests\n    func willEvaluateManifest(packageIdentity: PackageIdentity, packageLocation: String)\n    /// The workspace successfully evaluated (executed) a compiled package manifest, as reported by the assigned\n    /// manifest loader. this happens for non-cached manifests\n    func didEvaluateManifest(packageIdentity: PackageIdentity, packageLocation: String, duration: DispatchTimeInterval)\n\n    /// The workspace has started fetching this package.\n    func willFetchPackage(package: PackageIdentity, packageLocation: String?, fetchDetails: PackageFetchDetails)\n    /// The workspace has finished fetching this package.\n    func didFetchPackage(\n        package: PackageIdentity,\n        packageLocation: String?,\n        result: Result<PackageFetchDetails, Error>,\n        duration: DispatchTimeInterval\n    )\n    /// Called every time the progress of the package fetch operation updates.\n    func fetchingPackage(package: PackageIdentity, packageLocation: String?, progress: Int64, total: Int64?)\n\n    /// The workspace has started updating this repository.\n    func willUpdateRepository(package: PackageIdentity, repository url: String)\n    /// The workspace has finished updating this repository.\n    func didUpdateRepository(package: PackageIdentity, repository url: String, duration: DispatchTimeInterval)\n\n    /// The workspace has finished updating and all the dependencies are already up-to-date.\n    func dependenciesUpToDate()\n\n    /// The workspace is about to clone a repository from the local cache to a working directory.\n    func willCreateWorkingCopy(package: PackageIdentity, repository url: String, at path: AbsolutePath)\n    /// The workspace has cloned a repository from the local cache to a working directory. The error indicates whether\n    /// the operation failed or succeeded.\n    func didCreateWorkingCopy(\n        package: PackageIdentity,\n        repository url: String,\n        at path: AbsolutePath,\n        duration: DispatchTimeInterval\n    )\n\n    /// The workspace is about to check out a particular revision of a working directory.\n    func willCheckOut(package: PackageIdentity, repository url: String, revision: String, at path: AbsolutePath)\n    /// The workspace has checked out a particular revision of a working directory. The error indicates whether the\n    /// operation failed or succeeded.\n    func didCheckOut(\n        package: PackageIdentity,\n        repository url: String,\n        revision: String,\n        at path: AbsolutePath,\n        duration: DispatchTimeInterval\n    )\n\n    /// The workspace is removing this repository because it is no longer needed.\n    func removing(package: PackageIdentity, packageLocation: String?)\n\n    /// Called when the resolver is about to be run.\n    func willResolveDependencies(reason: WorkspaceResolveReason)\n\n    /// Called when the resolver begins to be compute the version for the repository.\n    func willComputeVersion(package: PackageIdentity, location: String)\n    /// Called when the resolver finished computing the version for the repository.\n    func didComputeVersion(package: PackageIdentity, location: String, version: String, duration: DispatchTimeInterval)\n\n    /// Called when the Package.resolved file is changed *outside* of libSwiftPM operations.\n    ///\n    /// This is only fired when activated using Workspace's watchResolvedFile() method.\n    func resolvedFileChanged()\n\n    /// The workspace has started downloading a binary artifact.\n    func willDownloadBinaryArtifact(from url: String, fromCache: Bool)\n    /// The workspace has finished downloading a binary artifact.\n    func didDownloadBinaryArtifact(\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    )\n    /// The workspace is downloading a binary artifact.\n    func downloadingBinaryArtifact(from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?)\n    /// The workspace finished downloading all binary artifacts.\n    func didDownloadAllBinaryArtifacts()\n\n    /// The workspace has started downloading a binary artifact.\n    func willDownloadPrebuilt(\n        package: PackageIdentity,\n        from url: String,\n        fromCache: Bool\n    )\n    /// The workspace has finished downloading a binary artifact.\n    func didDownloadPrebuilt(\n        package: PackageIdentity,\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    )\n    /// The workspace is downloading a binary artifact.\n    func downloadingPrebuilt(\n        package: PackageIdentity,\n        from url: String,\n        bytesDownloaded: Int64,\n        totalBytesToDownload: Int64?\n    )\n    /// The workspace finished downloading all binary artifacts.\n    func didDownloadAllPrebuilts()\n\n    // handlers for unsigned and untrusted registry based dependencies\n    func onUnsignedRegistryPackage(\n        registryURL: URL,\n        package: PackageModel.PackageIdentity,\n        version: TSCUtility.Version,\n        completion: (Bool) -> Void\n    )\n    func onUntrustedRegistryPackage(\n        registryURL: URL,\n        package: PackageModel.PackageIdentity,\n        version: TSCUtility.Version,\n        completion: (Bool) -> Void\n    )\n\n    /// The workspace has started updating dependencies\n    func willUpdateDependencies()\n    /// The workspace has finished updating dependencies\n    func didUpdateDependencies(duration: DispatchTimeInterval)\n\n    /// The workspace has started resolving dependencies\n    func willResolveDependencies()\n    /// The workspace has finished resolving dependencies\n    func didResolveDependencies(duration: DispatchTimeInterval)\n\n    /// The workspace has started loading the graph to memory\n    func willLoadGraph()\n    /// The workspace has finished loading the graph to memory\n    func didLoadGraph(duration: DispatchTimeInterval)\n}\n\n// FIXME: default implementation until the feature is stable, at which point we should remove this and force the clients to implement\nextension WorkspaceDelegate {\n    public func onUnsignedRegistryPackage(\n        registryURL: URL,\n        package: PackageModel.PackageIdentity,\n        version: TSCUtility.Version,\n        completion: (Bool) -> Void\n    ) {\n        // true == continue resolution\n        // false == stop dependency resolution\n        completion(true)\n    }\n\n    public func onUntrustedRegistryPackage(\n        registryURL: URL,\n        package: PackageModel.PackageIdentity,\n        version: TSCUtility.Version,\n        completion: (Bool) -> Void\n    ) {\n        // true == continue resolution\n        // false == stop dependency resolution\n        completion(true)\n    }\n}\n\nstruct WorkspaceManifestLoaderDelegate: ManifestLoader.Delegate, @unchecked Sendable {\n    private weak var workspaceDelegate: Workspace.Delegate?\n\n    init(workspaceDelegate: Workspace.Delegate) {\n        self.workspaceDelegate = workspaceDelegate\n    }\n\n    func willLoad(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        // handled by workspace directly\n    }\n\n    func didLoad(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath,\n        duration: DispatchTimeInterval\n    ) {\n        // handled by workspace directly\n    }\n\n    func willParse(packageIdentity: PackageIdentity, packageLocation: String) {\n        // noop\n    }\n\n    func didParse(packageIdentity: PackageIdentity, packageLocation: String, duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    func willCompile(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        self.workspaceDelegate?.willCompileManifest(packageIdentity: packageIdentity, packageLocation: packageLocation)\n    }\n\n    func didCompile(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath,\n        duration: DispatchTimeInterval\n    ) {\n        self.workspaceDelegate?.didCompileManifest(\n            packageIdentity: packageIdentity,\n            packageLocation: packageLocation,\n            duration: duration\n        )\n    }\n\n    func willEvaluate(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        self.workspaceDelegate?.willCompileManifest(packageIdentity: packageIdentity, packageLocation: packageLocation)\n    }\n\n    func didEvaluate(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        manifestPath: AbsolutePath,\n        duration: DispatchTimeInterval\n    ) {\n        self.workspaceDelegate?.didEvaluateManifest(\n            packageIdentity: packageIdentity,\n            packageLocation: packageLocation,\n            duration: duration\n        )\n    }\n}\n\nstruct WorkspaceRepositoryManagerDelegate: RepositoryManager.Delegate, @unchecked Sendable {\n    private weak var workspaceDelegate: Workspace.Delegate?\n\n    init(workspaceDelegate: Workspace.Delegate) {\n        self.workspaceDelegate = workspaceDelegate\n    }\n\n    func willFetch(package: PackageIdentity, repository: RepositorySpecifier, details: RepositoryManager.FetchDetails) {\n        self.workspaceDelegate?.willFetchPackage(\n            package: package,\n            packageLocation: repository.location.description,\n            fetchDetails: PackageFetchDetails(fromCache: details.fromCache, updatedCache: details.updatedCache)\n        )\n    }\n\n    func fetching(\n        package: PackageIdentity,\n        repository: RepositorySpecifier,\n        objectsFetched: Int,\n        totalObjectsToFetch: Int\n    ) {\n        self.workspaceDelegate?.fetchingPackage(\n            package: package,\n            packageLocation: repository.location.description,\n            progress: Int64(objectsFetched),\n            total: Int64(totalObjectsToFetch)\n        )\n    }\n\n    func didFetch(\n        package: PackageIdentity,\n        repository: RepositorySpecifier,\n        result: Result<RepositoryManager.FetchDetails, Error>,\n        duration: DispatchTimeInterval\n    ) {\n        self.workspaceDelegate?.didFetchPackage(\n            package: package,\n            packageLocation: repository.location.description,\n            result: result.map { PackageFetchDetails(fromCache: $0.fromCache, updatedCache: $0.updatedCache) },\n            duration: duration\n        )\n    }\n\n    func willUpdate(package: PackageIdentity, repository: RepositorySpecifier) {\n        self.workspaceDelegate?.willUpdateRepository(package: package, repository: repository.location.description)\n    }\n\n    func didUpdate(package: PackageIdentity, repository: RepositorySpecifier, duration: DispatchTimeInterval) {\n        self.workspaceDelegate?.didUpdateRepository(\n            package: package,\n            repository: repository.location.description,\n            duration: duration\n        )\n    }\n}\n\nstruct WorkspaceRegistryDownloadsManagerDelegate: RegistryDownloadsManager.Delegate, @unchecked Sendable {\n    private weak var workspaceDelegate: Workspace.Delegate?\n\n    init(workspaceDelegate: Workspace.Delegate) {\n        self.workspaceDelegate = workspaceDelegate\n    }\n\n    func willFetch(package: PackageIdentity, version: Version, fetchDetails: RegistryDownloadsManager.FetchDetails) {\n        self.workspaceDelegate?.willFetchPackage(\n            package: package,\n            packageLocation: .none,\n            fetchDetails: PackageFetchDetails(\n                fromCache: fetchDetails.fromCache,\n                updatedCache: fetchDetails.updatedCache\n            )\n        )\n    }\n\n    func didFetch(\n        package: PackageIdentity,\n        version: Version,\n        result: Result<RegistryDownloadsManager.FetchDetails, Error>,\n        duration: DispatchTimeInterval\n    ) {\n        self.workspaceDelegate?.didFetchPackage(\n            package: package,\n            packageLocation: .none,\n            result: result.map { PackageFetchDetails(fromCache: $0.fromCache, updatedCache: $0.updatedCache) },\n            duration: duration\n        )\n    }\n\n    func fetching(package: PackageIdentity, version: Version, bytesDownloaded: Int64, totalBytesToDownload: Int64?) {\n        self.workspaceDelegate?.fetchingPackage(\n            package: package,\n            packageLocation: .none,\n            progress: bytesDownloaded,\n            total: totalBytesToDownload\n        )\n    }\n}\n\nstruct WorkspaceRegistryClientDelegate: RegistryClient.Delegate {\n    private weak var workspaceDelegate: Workspace.Delegate?\n\n    init(workspaceDelegate: Workspace.Delegate?) {\n        self.workspaceDelegate = workspaceDelegate\n    }\n\n    func onUnsigned(registry: Registry, package: PackageIdentity, version: Version, completion: (Bool) -> Void) {\n        if let delegate = self.workspaceDelegate {\n            delegate.onUnsignedRegistryPackage(\n                registryURL: registry.url,\n                package: package,\n                version: version,\n                completion: completion\n            )\n        } else {\n            // true == continue resolution\n            // false == stop dependency resolution\n            completion(true)\n        }\n    }\n\n    func onUntrusted(registry: Registry, package: PackageIdentity, version: Version, completion: (Bool) -> Void) {\n        if let delegate = self.workspaceDelegate {\n            delegate.onUntrustedRegistryPackage(\n                registryURL: registry.url,\n                package: package,\n                version: version,\n                completion: completion\n            )\n        } else {\n            // true == continue resolution\n            // false == stop dependency resolution\n            completion(true)\n        }\n    }\n}\n\nstruct WorkspaceBinaryArtifactsManagerDelegate: Workspace.BinaryArtifactsManager.Delegate {\n    private weak var workspaceDelegate: Workspace.Delegate?\n\n    init(workspaceDelegate: Workspace.Delegate) {\n        self.workspaceDelegate = workspaceDelegate\n    }\n\n    func willDownloadBinaryArtifact(from url: String, fromCache: Bool) {\n        self.workspaceDelegate?.willDownloadBinaryArtifact(from: url, fromCache: fromCache)\n    }\n\n    func didDownloadBinaryArtifact(\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    ) {\n        self.workspaceDelegate?.didDownloadBinaryArtifact(from: url, result: result, duration: duration)\n    }\n\n    func downloadingBinaryArtifact(from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?) {\n        self.workspaceDelegate?.downloadingBinaryArtifact(\n            from: url,\n            bytesDownloaded: bytesDownloaded,\n            totalBytesToDownload: totalBytesToDownload\n        )\n    }\n\n    func didDownloadAllBinaryArtifacts() {\n        self.workspaceDelegate?.didDownloadAllBinaryArtifacts()\n    }\n}\n\nstruct WorkspacePrebuiltsManagerDelegate: Workspace.PrebuiltsManager.Delegate {\n    private weak var workspaceDelegate: Workspace.Delegate?\n\n    init(workspaceDelegate: Workspace.Delegate) {\n        self.workspaceDelegate = workspaceDelegate\n    }\n\n    func willDownloadPrebuilt(\n        for package: PackageIdentity,\n        from url: String,\n        fromCache: Bool\n    ) {\n        self.workspaceDelegate?.willDownloadPrebuilt(\n            package: package,\n            from: url,\n            fromCache: fromCache\n        )\n    }\n\n    func didDownloadPrebuilt(\n        for package: PackageIdentity,\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    ) {\n        self.workspaceDelegate?.didDownloadPrebuilt(\n            package: package,\n            from: url,\n            result: result,\n            duration: duration\n        )\n    }\n\n    func downloadingPrebuilt(\n        for package: PackageIdentity,\n        from url: String,\n        bytesDownloaded: Int64,\n        totalBytesToDownload: Int64?\n    ) {\n        self.workspaceDelegate?.downloadingPrebuilt(\n            package: package,\n            from: url,\n            bytesDownloaded: bytesDownloaded,\n            totalBytesToDownload: totalBytesToDownload\n        )\n    }\n\n    func didDownloadAllPrebuilts() {\n        self.workspaceDelegate?.didDownloadAllPrebuilts()\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Dependencies.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\n\nimport struct Basics.AbsolutePath\nimport struct Basics.InternalError\nimport class Basics.ObservabilityScope\nimport func Basics.os_signpost\nimport struct Basics.RelativePath\nimport enum Basics.SignpostName\nimport class Basics.ThreadSafeKeyValueStore\nimport class Dispatch.DispatchGroup\nimport struct Dispatch.DispatchTime\nimport enum Dispatch.DispatchTimeInterval\nimport struct PackageGraph.Assignment\nimport enum PackageGraph.BoundVersion\nimport enum PackageGraph.ContainerUpdateStrategy\nimport protocol PackageGraph.CustomPackageContainer\nimport struct PackageGraph.DependencyResolverBinding\nimport protocol PackageGraph.DependencyResolverDelegate\nimport struct PackageGraph.Incompatibility\nimport struct PackageGraph.MultiplexResolverDelegate\nimport struct PackageGraph.ObservabilityDependencyResolverDelegate\nimport struct PackageGraph.PackageContainerConstraint\nimport struct PackageGraph.PackageGraphRoot\nimport struct PackageGraph.PackageGraphRootInput\nimport class PackageGraph.ResolvedPackagesStore\nimport struct PackageGraph.PubGrubDependencyResolver\nimport struct PackageGraph.Term\nimport class PackageLoading.ManifestLoader\nimport enum PackageModel.PackageDependency\nimport struct PackageModel.PackageIdentity\nimport struct PackageModel.PackageReference\nimport enum PackageModel.ProductFilter\nimport struct PackageModel.ToolsVersion\nimport struct SourceControl.Revision\nimport struct TSCUtility.Version\nimport struct PackageModel.TargetDescription\nimport struct PackageModel.TraitDescription\nimport enum PackageModel.TraitConfiguration\nimport class PackageModel.Manifest\n\nextension Workspace {\n    enum ResolvedFileStrategy {\n        case lockFile\n        case update(forceResolution: Bool)\n        case bestEffort\n    }\n\n    func _updateDependencies(\n        root: PackageGraphRootInput,\n        packages: [String] = [],\n        dryRun: Bool = false,\n        observabilityScope: ObservabilityScope\n    ) async throws -> [(PackageReference, Workspace.PackageStateChange)]? {\n        let start = DispatchTime.now()\n        self.delegate?.willUpdateDependencies()\n        defer {\n            self.delegate?.didUpdateDependencies(duration: start.distance(to: .now()))\n        }\n\n        // Create cache directories.\n        self.createCacheDirectories(observabilityScope: observabilityScope)\n\n        // Load the root manifests and currently checked out manifests.\n        let rootManifests = try await self.loadRootManifests(\n            packages: root.packages,\n            observabilityScope: observabilityScope\n        )\n        let rootManifestsMinimumToolsVersion = rootManifests.values.map(\\.toolsVersion).min() ?? ToolsVersion.current\n        let resolvedFileOriginHash = try self.computeResolvedFileOriginHash(root: root)\n\n        // Load the current manifests.\n        let graphRoot = try PackageGraphRoot(\n            input: root,\n            manifests: rootManifests,\n            dependencyMapper: self.dependencyMapper,\n            observabilityScope: observabilityScope,\n            enabledTraitsMap: self.enabledTraitsMap\n        )\n        let currentManifests = try await self.loadDependencyManifests(\n            root: graphRoot,\n            observabilityScope: observabilityScope\n        )\n\n        // Abort if we're unable to load the `Package.resolved` store or have any diagnostics.\n        guard let resolvedPackagesStore = observabilityScope.trap({ try self.resolvedPackagesStore.load() }) else { return nil }\n\n        // Ensure we don't have any error at this point.\n        guard !observabilityScope.errorsReported else {\n            return nil\n        }\n\n        // Add unversioned constraints for edited packages.\n        var updateConstraints = currentManifests.editedPackagesConstraints\n\n        // Create constraints based on root manifest and `Package.resolved` for the update resolution.\n        updateConstraints += try graphRoot.constraints(self.enabledTraitsMap)\n\n        let resolvedPackages: ResolvedPackagesStore.ResolvedPackages\n        if packages.isEmpty {\n            // No input packages so we have to do a full update. Set resolved packages map to empty.\n            resolvedPackages = [:]\n        } else {\n            // We have input packages so we have to partially update the package graph. Remove\n            // resolved packages for the input packages so only those packages are updated.\n            resolvedPackages = resolvedPackagesStore.resolvedPackages\n                .filter {\n                    !packages.contains($0.value.packageRef.identity.description) && !packages\n                        .contains($0.value.packageRef.deprecatedName)\n                }\n        }\n\n        // Resolve the dependencies.\n        let resolver = try self.createResolver(resolvedPackages: resolvedPackages, observabilityScope: observabilityScope)\n        self.activeResolver = resolver\n\n        let updateResults = await self.resolveDependencies(\n            resolver: resolver,\n            constraints: updateConstraints,\n            observabilityScope: observabilityScope\n        )\n\n        // Reset the active resolver.\n        self.activeResolver = nil\n\n        guard !observabilityScope.errorsReported else {\n            return nil\n        }\n\n        if dryRun {\n            return await observabilityScope.trap {\n                try await self.computePackageStateChanges(\n                    root: graphRoot,\n                    resolvedDependencies: updateResults,\n                    updateBranches: true,\n                    observabilityScope: observabilityScope\n                )\n            }\n        }\n\n        // Update the checkouts based on new dependency resolution.\n        let packageStateChanges = await self.updateDependenciesCheckouts(\n            root: graphRoot,\n            updateResults: updateResults,\n            updateBranches: true,\n            observabilityScope: observabilityScope\n        )\n        guard !observabilityScope.errorsReported else {\n            return nil\n        }\n\n        // Load the updated manifests.\n        let updatedDependencyManifests = try await self.loadDependencyManifests(\n            root: graphRoot,\n            observabilityScope: observabilityScope\n        )\n        // If we have missing packages, something is fundamentally wrong with the resolution of the graph\n        let stillMissingPackages = try updatedDependencyManifests.missingPackages\n        guard stillMissingPackages.isEmpty else {\n            observabilityScope.emit(BinaryArtifactsManagerError.exhaustedAttempts(missing: stillMissingPackages))\n            return nil\n        }\n\n        // Update the resolved file.\n        try await self.saveResolvedFile(\n            resolvedPackagesStore: resolvedPackagesStore,\n            dependencyManifests: updatedDependencyManifests,\n            originHash: resolvedFileOriginHash,\n            rootManifestsMinimumToolsVersion: rootManifestsMinimumToolsVersion,\n            observabilityScope: observabilityScope\n        )\n\n        // Update the binary target artifacts.\n        let addedOrUpdatedPackages = packageStateChanges.compactMap { $0.1.isAddedOrUpdated ? $0.0 : nil }\n        try await self.updateBinaryArtifacts(\n            manifests: updatedDependencyManifests,\n            addedOrUpdatedPackages: addedOrUpdatedPackages,\n            observabilityScope: observabilityScope\n        )\n\n        // Update prebuilts\n        try await self.updatePrebuilts(\n            manifests: currentManifests,\n            addedOrUpdatedPackages: addedOrUpdatedPackages,\n            observabilityScope: observabilityScope\n        )\n\n        return packageStateChanges\n    }\n\n    @discardableResult\n    func _resolve(\n        root: PackageGraphRootInput,\n        explicitProduct: String?,\n        resolvedFileStrategy: ResolvedFileStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> DependencyManifests {\n        let start = DispatchTime.now()\n        self.delegate?.willResolveDependencies()\n        defer {\n            self.delegate?.didResolveDependencies(duration: start.distance(to: .now()))\n        }\n\n        switch resolvedFileStrategy {\n        case .lockFile:\n            observabilityScope.emit(info: \"using '\\(self.location.resolvedVersionsFile.basename)' file as lock file\")\n            return try await self._resolveBasedOnResolvedVersionsFile(\n                root: root,\n                explicitProduct: explicitProduct,\n                observabilityScope: observabilityScope\n            )\n        case .update(let forceResolution):\n            return try await resolveAndUpdateResolvedFile(forceResolution: forceResolution)\n        case .bestEffort:\n            guard await !self.state.dependencies.hasEditedDependencies() else {\n                return try await resolveAndUpdateResolvedFile(forceResolution: false)\n            }\n            guard self.fileSystem.exists(self.location.resolvedVersionsFile) else {\n                return try await resolveAndUpdateResolvedFile(forceResolution: false)\n            }\n\n            guard let resolvedPackagesStore = try? self.resolvedPackagesStore.load(), let storedHash = resolvedPackagesStore.originHash else {\n                observabilityScope\n                    .emit(\n                        debug: \"'\\(self.location.resolvedVersionsFile.basename)' origin hash is missing. resolving and updating accordingly\"\n                    )\n                return try await resolveAndUpdateResolvedFile(forceResolution: false)\n            }\n\n            let currentHash = try self.computeResolvedFileOriginHash(root: root)\n            guard storedHash == currentHash else {\n                observabilityScope\n                    .emit(\n                        debug: \"'\\(self.location.resolvedVersionsFile.basename)' origin hash does do not match manifest dependencies. resolving and updating accordingly\"\n                    )\n                return try await resolveAndUpdateResolvedFile(forceResolution: false)\n            }\n\n            observabilityScope\n                .emit(\n                    debug: \"'\\(self.location.resolvedVersionsFile.basename)' origin hash matches manifest dependencies, attempting resolution based on this file\"\n                )\n            let (manifests, precomputationResult) = try await self.tryResolveBasedOnResolvedVersionsFile(\n                root: root,\n                explicitProduct: explicitProduct,\n                observabilityScope: observabilityScope\n            )\n            switch precomputationResult {\n            case .notRequired:\n                return manifests\n            case .required(reason: .errorsPreviouslyReported):\n                return manifests\n            case .required(let reason):\n                // FIXME: ideally this is not done based on a side-effect\n                let reasonString = Self.format(workspaceResolveReason: reason)\n                observabilityScope\n                    .emit(\n                        debug: \"resolution based on '\\(self.location.resolvedVersionsFile.basename)' could not be completed because \\(reasonString). resolving and updating accordingly\"\n                    )\n                return try await resolveAndUpdateResolvedFile(forceResolution: false)\n            }\n        }\n\n        func resolveAndUpdateResolvedFile(forceResolution: Bool) async throws -> DependencyManifests {\n            observabilityScope.emit(debug: \"resolving and updating '\\(self.location.resolvedVersionsFile.basename)'\")\n            return try await self.resolveAndUpdateResolvedFile(\n                root: root,\n                explicitProduct: explicitProduct,\n                forceResolution: forceResolution,\n                constraints: [],\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    private func computeResolvedFileOriginHash(root: PackageGraphRootInput) throws -> String {\n        var content = try root.packages.reduce(into: \"\") { partial, element in\n            let path = try ManifestLoader.findManifest(\n                packagePath: element,\n                fileSystem: self.fileSystem,\n                currentToolsVersion: self.currentToolsVersion\n            )\n            try partial.append(self.fileSystem.readFileContents(path))\n        }\n        content += root.dependencies.reduce(into: \"\") { partial, element in\n            partial += element.locationString\n        }\n        return content.sha256Checksum\n    }\n\n    @discardableResult\n    func _resolveBasedOnResolvedVersionsFile(\n        root: PackageGraphRootInput,\n        explicitProduct: String?,\n        observabilityScope: ObservabilityScope\n    ) async throws -> DependencyManifests {\n        let (manifests, precomputationResult) = try await self.tryResolveBasedOnResolvedVersionsFile(\n            root: root,\n            explicitProduct: explicitProduct,\n            observabilityScope: observabilityScope\n        )\n        switch precomputationResult {\n        case .notRequired:\n            return manifests\n        case .required(reason: .errorsPreviouslyReported):\n            return manifests\n        case .required(let reason):\n            // FIXME: ideally this is not done based on a side-effect\n            let reasonString = Self.format(workspaceResolveReason: reason)\n            if !self.fileSystem.exists(self.location.resolvedVersionsFile) {\n                observabilityScope\n                    .emit(\n                        error: \"a resolved file is required when automatic dependency resolution is disabled and should be placed at \\(self.location.resolvedVersionsFile.pathString). \\(reasonString)\"\n                    )\n            } else {\n                observabilityScope\n                    .emit(\n                        error: \"an out-of-date resolved file was detected at \\(self.location.resolvedVersionsFile.pathString), which is not allowed when automatic dependency resolution is disabled; please make sure to update the file to reflect the changes in dependencies. \\(reasonString)\"\n                    )\n            }\n            return manifests\n        }\n    }\n\n    /// Resolves the dependencies according to the entries present in the Package.resolved file.\n    ///\n    /// This method bypasses the dependency resolution and resolves dependencies\n    /// according to the information in the resolved file.\n    fileprivate func tryResolveBasedOnResolvedVersionsFile(\n        root: PackageGraphRootInput,\n        explicitProduct: String?,\n        observabilityScope: ObservabilityScope\n    ) async throws -> (DependencyManifests, ResolutionPrecomputationResult) {\n        // Ensure the cache path exists.\n        self.createCacheDirectories(observabilityScope: observabilityScope)\n\n        let rootManifests = try await self.loadRootManifests(\n            packages: root.packages,\n            observabilityScope: observabilityScope\n        )\n        let graphRoot = try PackageGraphRoot(\n            input: root,\n            manifests: rootManifests,\n            explicitProduct: explicitProduct,\n            dependencyMapper: self.dependencyMapper,\n            observabilityScope: observabilityScope,\n            enabledTraitsMap: self.enabledTraitsMap\n        )\n\n        // Load the `Package.resolved` store or abort now.\n        guard let resolvedPackagesStore = observabilityScope.trap({ try self.resolvedPackagesStore.load() }),\n              !observabilityScope.errorsReported\n        else {\n            let dependencyManifests = try await self.loadDependencyManifests(\n                root: graphRoot,\n                observabilityScope: observabilityScope\n                )\n\n            return (dependencyManifests,\n                .notRequired\n            )\n        }\n\n        // Request all the containers to fetch them in parallel.\n        //\n        // We just request the packages here, repository manager will\n        // automatically manage the parallelism.\n        await withThrowingTaskGroup(of: Void.self) { taskGroup in\n            for resolvedPackage in resolvedPackagesStore.resolvedPackages.values {\n                let observabilityScope = observabilityScope.makeChildScope(\n                    description: \"requesting package containers\",\n                    metadata: resolvedPackage.packageRef.diagnosticsMetadata\n                )\n\n                let updateStrategy: ContainerUpdateStrategy = {\n                    if self.configuration.skipDependenciesUpdates {\n                        return .never\n                    } else {\n                        switch resolvedPackage.state {\n                            case .branch(_, let revision):\n                                return .ifNeeded(revision: revision)\n                            case .revision(let revision):\n                                return .ifNeeded(revision: revision)\n                            case .version(_, .some(let revision)):\n                                return .ifNeeded(revision: revision)\n                            case .version(_, .none):\n                                return .always\n                        }\n                    }\n                }()\n\n                taskGroup.addTask {\n                    _ = try await self.packageContainerProvider.getContainer(\n                        for: resolvedPackage.packageRef,\n                        updateStrategy: updateStrategy,\n                        observabilityScope: observabilityScope\n                    )\n                }\n            }\n        }\n\n        // Compute resolved packages that we need to actually clone.\n        //\n        // We require cloning if there is no checkout or if the checkout doesn't\n        // match with the pin.\n        let dependencies = await state.dependencies\n        let requiredResolvedPackages = resolvedPackagesStore.resolvedPackages.values.filter { pin in\n            // also compare the location in case it has changed\n            guard let dependency = dependencies[comparingLocation: pin.packageRef] else {\n                return true\n            }\n            switch dependency.state {\n            case .sourceControlCheckout(let checkoutState):\n                return !pin.state.equals(checkoutState)\n            case .registryDownload(let version):\n                return !pin.state.equals(version)\n            case .edited, .fileSystem, .custom:\n                return true\n            }\n        }\n\n        // Retrieve the required resolved packages.\n        await withThrowingTaskGroup(of: Void.self) { taskGroup in\n            for resolvedPackage in requiredResolvedPackages {\n                let observabilityScope = observabilityScope.makeChildScope(\n                    description: \"retrieving resolved package versions for dependencies\",\n                    metadata: resolvedPackage.packageRef.diagnosticsMetadata\n                )\n                taskGroup.addTask {\n                    await observabilityScope.trap {\n                        switch resolvedPackage.packageRef.kind {\n                        case .localSourceControl, .remoteSourceControl:\n                            _ = try await self.checkoutRepository(\n                                package: resolvedPackage.packageRef,\n                                at: resolvedPackage.state,\n                                observabilityScope: observabilityScope\n                            )\n                        case .registry:\n                            _ = try await self.downloadRegistryArchive(\n                                package: resolvedPackage.packageRef,\n                                at: resolvedPackage.state,\n                                observabilityScope: observabilityScope\n                            )\n                        default:\n                            throw InternalError(\"invalid resolved package type \\(resolvedPackage.packageRef.kind)\")\n                        }\n                    }\n                }\n            }\n        }\n\n        let currentManifests = try await self.loadDependencyManifests(\n            root: graphRoot,\n            automaticallyAddManagedDependencies: true,\n            observabilityScope: observabilityScope\n        )\n        \n        try await self.updateBinaryArtifacts(\n            manifests: currentManifests,\n            addedOrUpdatedPackages: [],\n            observabilityScope: observabilityScope\n        )\n\n        // Update prebuilts\n        try await self.updatePrebuilts(\n            manifests: currentManifests,\n            addedOrUpdatedPackages: [],\n            observabilityScope: observabilityScope\n        )\n\n        let precomputationResult = try await self.precomputeResolution(\n            root: graphRoot,\n            dependencyManifests: currentManifests,\n            resolvedPackagesStore: resolvedPackagesStore,\n            constraints: [],\n            observabilityScope: observabilityScope\n        )\n\n        return (currentManifests, precomputationResult)\n    }\n\n    /// Implementation of resolve(root:diagnostics:).\n    ///\n    /// The extra constraints will be added to the main requirements.\n    /// It is useful in situations where a requirement is being\n    /// imposed outside of manifest and `Package.resolved` file. E.g., when using a command\n    /// like `$ swift package resolve foo --version 1.0.0`.\n    @discardableResult\n    func resolveAndUpdateResolvedFile(\n        root: PackageGraphRootInput,\n        explicitProduct: String? = nil,\n        forceResolution: Bool,\n        constraints: [PackageContainerConstraint],\n        observabilityScope: ObservabilityScope\n    ) async throws -> DependencyManifests {\n        // Ensure the cache path exists and validate that edited dependencies.\n        self.createCacheDirectories(observabilityScope: observabilityScope)\n\n        // Load the root manifests and currently checked out manifests.\n        let rootManifests = try await self.loadRootManifests(\n            packages: root.packages,\n            observabilityScope: observabilityScope\n        )\n        let rootManifestsMinimumToolsVersion = rootManifests.values.map(\\.toolsVersion).min() ?? ToolsVersion.current\n        let resolvedFileOriginHash = try self.computeResolvedFileOriginHash(root: root)\n\n        // Load the current manifests.\n        let graphRoot = try PackageGraphRoot(\n            input: root,\n            manifests: rootManifests,\n            explicitProduct: explicitProduct,\n            dependencyMapper: self.dependencyMapper,\n            observabilityScope: observabilityScope,\n            enabledTraitsMap: self.enabledTraitsMap\n        )\n\n        let currentManifests = try await self.loadDependencyManifests(\n            root: graphRoot,\n            observabilityScope: observabilityScope\n        )\n\n        guard !observabilityScope.errorsReported else {\n            return currentManifests\n        }\n\n        // load and update the `Package.resolved` store with any changes from loading the top level dependencies\n        guard let resolvedPackagesStore = await self.loadAndUpdateResolvedPackagesStore(\n            dependencyManifests: currentManifests,\n            rootManifestsMinimumToolsVersion: rootManifestsMinimumToolsVersion,\n            observabilityScope: observabilityScope\n        ), !observabilityScope.errorsReported else {\n            // abort if `Package.resolved` store reported any errors.\n            return currentManifests\n        }\n\n        // Compute the missing package identities.\n        let missingPackages = try currentManifests.missingPackages\n\n        // Compute if we need to run the resolver. We always run the resolver if\n        // there are extra constraints.\n        if !missingPackages.isEmpty {\n            delegate?.willResolveDependencies(reason: .newPackages(packages: Array(missingPackages)))\n        } else if !constraints.isEmpty || forceResolution {\n            delegate?.willResolveDependencies(reason: .forced)\n        } else {\n            let result = try await self.precomputeResolution(\n                root: graphRoot,\n                dependencyManifests: currentManifests,\n                resolvedPackagesStore: resolvedPackagesStore,\n                constraints: constraints,\n                observabilityScope: observabilityScope\n            )\n\n            switch result {\n            case .notRequired:\n                // since nothing changed we can exit early,\n                // but need update resolved file and download an missing binary artifact\n                try await self.saveResolvedFile(\n                    resolvedPackagesStore: resolvedPackagesStore,\n                    dependencyManifests: currentManifests,\n                    originHash: resolvedFileOriginHash,\n                    rootManifestsMinimumToolsVersion: rootManifestsMinimumToolsVersion,\n                    observabilityScope: observabilityScope\n                )\n\n                try await self.updateBinaryArtifacts(\n                    manifests: currentManifests,\n                    addedOrUpdatedPackages: [],\n                    observabilityScope: observabilityScope\n                )\n\n                try await self.updatePrebuilts(\n                    manifests: currentManifests,\n                    addedOrUpdatedPackages: [],\n                    observabilityScope: observabilityScope\n                )\n\n                return currentManifests\n            case .required(let reason):\n                delegate?.willResolveDependencies(reason: reason)\n            }\n        }\n\n        // Create the constraints; filter unused dependencies.\n        var computedConstraints = [PackageContainerConstraint]()\n        computedConstraints += currentManifests.editedPackagesConstraints\n        computedConstraints += try graphRoot.constraints(self.enabledTraitsMap) + constraints\n\n\n        // Perform dependency resolution.\n        let resolver = try self.createResolver(resolvedPackages: resolvedPackagesStore.resolvedPackages, observabilityScope: observabilityScope)\n        self.activeResolver = resolver\n\n        let result = await self.resolveDependencies(\n            resolver: resolver,\n            constraints: computedConstraints,\n            observabilityScope: observabilityScope\n        )\n\n        // Reset the active resolver.\n        self.activeResolver = nil\n\n        guard !observabilityScope.errorsReported else {\n            return currentManifests\n        }\n\n        // Update the checkouts with dependency resolution result.\n        let packageStateChanges = await self.updateDependenciesCheckouts(\n            root: graphRoot,\n            updateResults: result,\n            observabilityScope: observabilityScope\n        )\n        guard !observabilityScope.errorsReported else {\n            return currentManifests\n        }\n\n        // Update the `Package.resolved` store.\n        let updatedDependencyManifests = try await self.loadDependencyManifests(\n            root: graphRoot,\n            observabilityScope: observabilityScope\n        )\n\n        // If we still have missing packages, something is fundamentally wrong with the resolution of the graph\n        let stillMissingPackages = try updatedDependencyManifests.missingPackages\n        guard stillMissingPackages.isEmpty else {\n            observabilityScope.emit(BinaryArtifactsManagerError.exhaustedAttempts(missing: stillMissingPackages))\n            return updatedDependencyManifests\n        }\n\n        // Update the resolved file.\n        try await self.saveResolvedFile(\n            resolvedPackagesStore: resolvedPackagesStore,\n            dependencyManifests: updatedDependencyManifests,\n            originHash: resolvedFileOriginHash,\n            rootManifestsMinimumToolsVersion: rootManifestsMinimumToolsVersion,\n            observabilityScope: observabilityScope\n        )\n\n        let addedOrUpdatedPackages = packageStateChanges.compactMap { $0.1.isAddedOrUpdated ? $0.0 : nil }\n\n        try await self.updateBinaryArtifacts(\n            manifests: updatedDependencyManifests,\n            addedOrUpdatedPackages: addedOrUpdatedPackages,\n            observabilityScope: observabilityScope\n        )\n\n        try await self.updatePrebuilts(\n            manifests: updatedDependencyManifests,\n            addedOrUpdatedPackages: addedOrUpdatedPackages,\n            observabilityScope: observabilityScope\n        )\n\n        return updatedDependencyManifests\n    }\n\n    /// Updates the current working checkouts i.e. clone or remove based on the\n    /// provided dependency resolution result.\n    ///\n    /// - Parameters:\n    ///   - updateResults: The updated results from dependency resolution.\n    ///   - diagnostics: The diagnostics engine that reports errors, warnings\n    ///     and notes.\n    ///   - updateBranches: If the branches should be updated in case they're pinned.\n    @discardableResult\n    fileprivate func updateDependenciesCheckouts(\n        root: PackageGraphRoot,\n        updateResults: [DependencyResolverBinding],\n        updateBranches: Bool = false,\n        observabilityScope: ObservabilityScope\n    ) async -> [(PackageReference, PackageStateChange)] {\n        // Get the update package states from resolved results.\n        guard let packageStateChanges = await observabilityScope.trap({\n            try await self.computePackageStateChanges(\n                root: root,\n                resolvedDependencies: updateResults,\n                updateBranches: updateBranches,\n                observabilityScope: observabilityScope\n            )\n        }) else {\n            return []\n        }\n\n        // First remove the checkouts that are no longer required.\n        for (packageRef, state) in packageStateChanges {\n            await observabilityScope.makeChildScope(\n                description: \"removing unneeded checkouts\",\n                metadata: packageRef.diagnosticsMetadata\n            ).trap {\n                switch state {\n                case .added, .updated, .unchanged:\n                    break\n                case .removed:\n                    try await self.remove(package: packageRef)\n                }\n            }\n        }\n\n        // Update or clone new packages.\n        for (packageRef, state) in packageStateChanges {\n            await observabilityScope.makeChildScope(\n                description: \"updating or cloning new packages\",\n                metadata: packageRef.diagnosticsMetadata\n            ).trap {\n                switch state {\n                case .added(let state):\n                    _ = try await self.updateDependency(\n                        package: packageRef,\n                        requirement: state.requirement,\n                        productFilter: state.products,\n                        observabilityScope: observabilityScope\n                    )\n                case .updated(let state):\n                    _ = try await self.updateDependency(\n                        package: packageRef,\n                        requirement: state.requirement,\n                        productFilter: state.products,\n                        observabilityScope: observabilityScope\n                    )\n                case .removed, .unchanged:\n                    break\n                }\n            }\n        }\n\n        // Inform the delegate if nothing was updated.\n        if packageStateChanges.filter({ $0.1 == .unchanged }).count == packageStateChanges.count {\n            delegate?.dependenciesUpToDate()\n        }\n\n        return packageStateChanges\n    }\n\n    private func updateDependency(\n        package: PackageReference,\n        requirement: PackageStateChange.Requirement,\n        productFilter: ProductFilter,\n        observabilityScope: ObservabilityScope\n    ) async throws -> AbsolutePath {\n        switch requirement {\n        case .version(let version):\n            let container = try await packageContainerProvider.getContainer(\n                for: package,\n                updateStrategy: ContainerUpdateStrategy.never,\n                observabilityScope: observabilityScope\n            )\n\n            if let container = container as? SourceControlPackageContainer {\n                // FIXME: We need to get the revision here, and we don't have a\n                // way to get it back out of the resolver which is very\n                // annoying. Maybe we should make an SPI on the provider for this?\n                guard let tag = container.getTag(for: version) else {\n                    throw try await InternalError(\n                        \"unable to get tag for \\(package) \\(version); available versions \\(container.versionsDescending())\"\n                    )\n                }\n                let revision = try container.getRevision(forTag: tag)\n                try container.checkIntegrity(version: version, revision: revision)\n                return try await self.checkoutRepository(\n                    package: package,\n                    at: .version(version, revision: revision),\n                    observabilityScope: observabilityScope\n                )\n            } else if let _ = container as? RegistryPackageContainer {\n                return try await self.downloadRegistryArchive(\n                    package: package,\n                    at: version,\n                    observabilityScope: observabilityScope\n                )\n            } else if let customContainer = container as? CustomPackageContainer {\n                let path = try customContainer.retrieve(at: version, observabilityScope: observabilityScope)\n                let dependency = try ManagedDependency(\n                    packageRef: package,\n                    state: .custom(version: version, path: path),\n                    subpath: RelativePath(validating: \"\")\n                )\n                await self.state.add(dependency: dependency)\n                try await self.state.save()\n                return path\n            } else {\n                throw InternalError(\"invalid container for \\(package.identity) of type \\(package.kind)\")\n            }\n\n        case .revision(let revision, .none):\n            return try await self.checkoutRepository(\n                package: package,\n                at: .revision(revision),\n                observabilityScope: observabilityScope\n            )\n\n        case .revision(let revision, .some(let branch)):\n            return try await self.checkoutRepository(\n                package: package,\n                at: .branch(name: branch, revision: revision),\n                observabilityScope: observabilityScope\n            )\n\n        case .unversioned:\n            let dependency = try ManagedDependency.fileSystem(packageRef: package)\n            // this is silly since we just created it above, but no good way to force cast it and extract the path\n            guard case .fileSystem(let path) = dependency.state else {\n                throw InternalError(\"invalid package type: \\(package.kind)\")\n            }\n\n            await self.state.add(dependency: dependency)\n            try await self.state.save()\n            return path\n        }\n    }\n\n    public enum ResolutionPrecomputationResult: Equatable {\n        case required(reason: WorkspaceResolveReason)\n        case notRequired\n\n        public var isRequired: Bool {\n            switch self {\n            case .required: return true\n            case .notRequired: return false\n            }\n        }\n    }\n\n    @available(*, deprecated, renamed: \"precomputeResolution(root:dependencyManifests:resolvedPackagesStore:constraints:observabilityScope:)\", message: \"Renamed for consistency with the actual name of the feature\")\n    public func precomputeResolution(\n        root: PackageGraphRoot,\n        dependencyManifests: DependencyManifests,\n        pinsStore: ResolvedPackagesStore,\n        constraints: [PackageContainerConstraint],\n        observabilityScope: ObservabilityScope\n    ) async throws -> ResolutionPrecomputationResult {\n        try await self.precomputeResolution(\n            root: root,\n            dependencyManifests: dependencyManifests,\n            resolvedPackagesStore: pinsStore,\n            constraints: constraints,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Computes if dependency resolution is required based on input constraints and `Package.resolved` file.\n    ///\n    /// - Returns: Returns a result defining whether dependency resolution is required and the reason for it.\n    // @testable internal\n    public func precomputeResolution(\n        root: PackageGraphRoot,\n        dependencyManifests: DependencyManifests,\n        resolvedPackagesStore: ResolvedPackagesStore,\n        constraints: [PackageContainerConstraint],\n        observabilityScope: ObservabilityScope\n    ) async throws -> ResolutionPrecomputationResult {\n        let computedConstraints =\n        try root.constraints(self.enabledTraitsMap) +\n            // Include constraints from the manifests in the graph root.\n        root.manifests.values.flatMap { try $0.dependencyConstraints(productFilter: .everything, self.enabledTraitsMap[$0.packageIdentity]) } +\n            dependencyManifests.dependencyConstraints +\n            constraints\n\n        let precomputationProvider = ResolverPrecomputationProvider(\n            root: root,\n            dependencyManifests: dependencyManifests\n        )\n        let resolver = PubGrubDependencyResolver(\n            provider: precomputationProvider,\n            resolvedPackages: resolvedPackagesStore.resolvedPackages,\n            observabilityScope: observabilityScope\n        )\n        let result = await resolver.solve(constraints: computedConstraints)\n\n        guard !observabilityScope.errorsReported else {\n            return .required(reason: .errorsPreviouslyReported)\n        }\n\n        switch result {\n        case .success:\n            return .notRequired\n        case .failure(ResolverPrecomputationError.missingPackage(let package)):\n            return .required(reason: .newPackages(packages: [package]))\n        case .failure(ResolverPrecomputationError.differentRequirement(let package, let state, let requirement)):\n            return .required(reason: .packageRequirementChange(\n                package: package,\n                state: state,\n                requirement: requirement\n            ))\n        case .failure(let error):\n            return .required(reason: .other(\"\\(error.interpolationDescription)\"))\n        }\n    }\n\n    /// Validates that each checked out managed dependency has an entry in `Package.resolved` store.\n    private func loadAndUpdateResolvedPackagesStore(\n        dependencyManifests: DependencyManifests,\n        rootManifestsMinimumToolsVersion: ToolsVersion,\n        observabilityScope: ObservabilityScope\n    ) async -> ResolvedPackagesStore? {\n        guard let resolvedPackagesStore = observabilityScope.trap({ try self.resolvedPackagesStore.load() }) else {\n            return nil\n        }\n\n        guard let requiredDependencies = observabilityScope\n            .trap({ try dependencyManifests.requiredPackages.filter(\\.kind.isResolvable) })\n        else {\n            return nil\n        }\n        for dependency in await self.state.dependencies.filter(\\.packageRef.kind.isResolvable) {\n            // a required dependency that is already loaded (managed) should be represented in the `Package.resolved` store.\n            // also comparing location as it may have changed at this point\n            if requiredDependencies.contains(where: { $0.equalsIncludingLocation(dependency.packageRef) }) {\n                // if resolved package is not found, or location is different (it may have changed at this point) add it\n                if resolvedPackagesStore.resolvedPackages[comparingLocation: dependency.packageRef] == .none {\n                    resolvedPackagesStore.add(dependency)\n                }\n            } else if let pin = resolvedPackagesStore.resolvedPackages[dependency.packageRef.identity] {\n                // otherwise, it should *not* be in the `Package.resolved` store.\n                resolvedPackagesStore.remove(pin)\n            }\n        }\n\n        return resolvedPackagesStore\n    }\n\n    /// This enum represents state of an external package.\n    public enum PackageStateChange: Equatable, CustomStringConvertible {\n        /// The requirement imposed by the the state.\n        public enum Requirement: Equatable, CustomStringConvertible {\n            /// A version requirement.\n            case version(Version)\n\n            /// A revision requirement.\n            case revision(Revision, branch: String?)\n\n            case unversioned\n\n            public var description: String {\n                switch self {\n                case .version(let version):\n                    return \"requirement(\\(version))\"\n                case .revision(let revision, let branch):\n                    return \"requirement(\\(revision) \\(branch ?? \"\"))\"\n                case .unversioned:\n                    return \"requirement(unversioned)\"\n                }\n            }\n\n            public var prettyPrinted: String {\n                switch self {\n                case .version(let version):\n                    return \"\\(version)\"\n                case .revision(let revision, let branch):\n                    return \"\\(revision) \\(branch ?? \"\")\"\n                case .unversioned:\n                    return \"unversioned\"\n                }\n            }\n        }\n\n        public struct State: Equatable {\n            public let requirement: Requirement\n            public let products: ProductFilter\n            public init(requirement: Requirement, products: ProductFilter) {\n                self.requirement = requirement\n                self.products = products\n            }\n        }\n\n        /// The package is added.\n        case added(State)\n\n        /// The package is removed.\n        case removed\n\n        /// The package is unchanged.\n        case unchanged\n\n        /// The package is updated.\n        case updated(State)\n\n        public var description: String {\n            switch self {\n            case .added(let requirement):\n                return \"added(\\(requirement))\"\n            case .removed:\n                return \"removed\"\n            case .unchanged:\n                return \"unchanged\"\n            case .updated(let requirement):\n                return \"updated(\\(requirement))\"\n            }\n        }\n\n        public var isAddedOrUpdated: Bool {\n            switch self {\n            case .added, .updated:\n                return true\n            case .unchanged, .removed:\n                return false\n            }\n        }\n    }\n\n    /// Computes states of the packages based on last stored state.\n    fileprivate func computePackageStateChanges(\n        root: PackageGraphRoot,\n        resolvedDependencies: [DependencyResolverBinding],\n        updateBranches: Bool,\n        observabilityScope: ObservabilityScope\n    ) async throws -> [(PackageReference, PackageStateChange)] {\n        // Load `Package.resolved` store and managed dependencies.\n        let resolvedPackagesStore = try self.resolvedPackagesStore.load()\n        var packageStateChanges: [PackageIdentity: (PackageReference, PackageStateChange)] = [:]\n\n        // Set the states from resolved dependencies results.\n        for binding in resolvedDependencies {\n            // Get the existing managed dependency for this package ref, if any.\n\n            // first find by identity only since edit location may be different by design\n            var currentDependency = await self.state.dependencies[binding.package.identity]\n            // Check if this is an edited dependency.\n            if case .edited(let basedOn, _) = currentDependency?.state, let originalReference = basedOn?.packageRef {\n                packageStateChanges[originalReference.identity] = (originalReference, .unchanged)\n            } else {\n                // if not edited, also compare by location since it may have changed\n                currentDependency = await self.state.dependencies[comparingLocation: binding.package]\n            }\n\n            switch binding.boundVersion {\n            case .excluded:\n                throw InternalError(\"Unexpected excluded binding\")\n\n            case .unversioned:\n                // Ignore the root packages.\n                if root.packages.keys.contains(binding.package.identity) {\n                    continue\n                }\n\n                if let currentDependency {\n                    switch currentDependency.state {\n                    case .fileSystem, .edited:\n                        packageStateChanges[binding.package.identity] = (binding.package, .unchanged)\n                    case .sourceControlCheckout:\n                        let newState = PackageStateChange.State(requirement: .unversioned, products: binding.products)\n                        packageStateChanges[binding.package.identity] = (binding.package, .updated(newState))\n                    case .registryDownload:\n                        throw InternalError(\"Unexpected unversioned binding for downloaded dependency\")\n                    case .custom:\n                        throw InternalError(\"Unexpected unversioned binding for custom dependency\")\n                    }\n                } else {\n                    let newState = PackageStateChange.State(requirement: .unversioned, products: binding.products)\n                    packageStateChanges[binding.package.identity] = (binding.package, .added(newState))\n                }\n\n            case .revision(let identifier, let branch):\n                // Get the latest revision from the container.\n                // TODO: replace with async/await when available\n                guard let container = try await\n                    packageContainerProvider.getContainer(\n                        for: binding.package,\n                        updateStrategy: .never,\n                        observabilityScope: observabilityScope\n                    )\n                 as? SourceControlPackageContainer else {\n                    throw InternalError(\n                        \"invalid container for \\(binding.package) expected a SourceControlPackageContainer\"\n                    )\n                }\n                var revision = try container.getRevision(forIdentifier: identifier)\n                let branch = branch ?? (identifier == revision.identifier ? nil : identifier)\n\n                // If we have a branch and we shouldn't be updating the\n                // branches, use the revision from resolved package instead (if present).\n                if branch != nil, !updateBranches {\n                    if case .branch(branch, let resolvedPackageRevision) = resolvedPackagesStore.resolvedPackages.values\n                        .first(where: { $0.packageRef == binding.package })?.state\n                    {\n                        revision = Revision(identifier: resolvedPackageRevision)\n                    }\n                }\n\n                // First check if we have this dependency.\n                if let currentDependency {\n                    // If current state and new state are equal, we don't need\n                    // to do anything.\n                    let newState: CheckoutState\n                    if let branch {\n                        newState = .branch(name: branch, revision: revision)\n                    } else {\n                        newState = .revision(revision)\n                    }\n                    if case .sourceControlCheckout(let checkoutState) = currentDependency.state,\n                       checkoutState == newState\n                    {\n                        packageStateChanges[binding.package.identity] = (binding.package, .unchanged)\n                    } else {\n                        // Otherwise, we need to update this dependency to this revision.\n                        let newState = PackageStateChange.State(\n                            requirement: .revision(revision, branch: branch),\n                            products: binding.products\n                        )\n                        packageStateChanges[binding.package.identity] = (binding.package, .updated(newState))\n                    }\n                } else {\n                    let newState = PackageStateChange.State(\n                        requirement: .revision(revision, branch: branch),\n                        products: binding.products\n                    )\n                    packageStateChanges[binding.package.identity] = (binding.package, .added(newState))\n                }\n\n            case .version(let version):\n                let stateChange: PackageStateChange\n                switch currentDependency?.state {\n                case .sourceControlCheckout(.version(version, _)), .registryDownload(version), .custom(version, _):\n                    stateChange = .unchanged\n                case .edited, .fileSystem, .sourceControlCheckout, .registryDownload, .custom:\n                    stateChange = .updated(.init(requirement: .version(version), products: binding.products))\n                case nil:\n                    stateChange = .added(.init(requirement: .version(version), products: binding.products))\n                }\n                packageStateChanges[binding.package.identity] = (binding.package, stateChange)\n            }\n        }\n        // Set the state of any old package that might have been removed.\n        for packageRef in await self.state.dependencies.lazy.map(\\.packageRef)\n            where packageStateChanges[packageRef.identity] == nil\n        {\n            packageStateChanges[packageRef.identity] = (packageRef, .removed)\n        }\n\n        return Array(packageStateChanges.values)\n    }\n\n    /// Creates resolver for the workspace.\n    fileprivate func createResolver(\n        resolvedPackages: ResolvedPackagesStore.ResolvedPackages,\n        observabilityScope: ObservabilityScope\n    ) throws -> PubGrubDependencyResolver {\n        var delegate: DependencyResolverDelegate\n        let observabilityDelegate = ObservabilityDependencyResolverDelegate(observabilityScope: observabilityScope)\n        if let workspaceDelegate = self.delegate {\n            delegate = MultiplexResolverDelegate([\n                observabilityDelegate,\n                WorkspaceDependencyResolverDelegate(workspaceDelegate),\n            ])\n        } else {\n            delegate = observabilityDelegate\n        }\n\n        return PubGrubDependencyResolver(\n            provider: packageContainerProvider,\n            resolvedPackages: resolvedPackages,\n            skipDependenciesUpdates: self.configuration.skipDependenciesUpdates,\n            prefetchBasedOnResolvedFile: self.configuration.prefetchBasedOnResolvedFile,\n            observabilityScope: observabilityScope,\n            delegate: delegate\n        )\n    }\n\n    /// Runs the dependency resolver based on constraints provided and returns the results.\n    fileprivate func resolveDependencies(\n        resolver: PubGrubDependencyResolver,\n        constraints: [PackageContainerConstraint],\n        observabilityScope: ObservabilityScope\n    ) async -> [DependencyResolverBinding] {\n        os_signpost(.begin, name: SignpostName.pubgrub)\n        let result = await resolver.solve(constraints: constraints)\n        os_signpost(.end, name: SignpostName.pubgrub)\n\n        // Take an action based on the result.\n        switch result {\n        case .success(let bindings):\n            return bindings\n        case .failure(let error):\n            observabilityScope.emit(error)\n            return []\n        }\n    }\n\n    /// Create the cache directories.\n    fileprivate func createCacheDirectories(observabilityScope: ObservabilityScope) {\n        observabilityScope.trap {\n            try fileSystem.createDirectory(self.repositoryManager.path, recursive: true)\n            try fileSystem.createDirectory(self.location.repositoriesCheckoutsDirectory, recursive: true)\n            try fileSystem.createDirectory(self.location.artifactsDirectory, recursive: true)\n        }\n    }\n}\n\nprivate struct WorkspaceDependencyResolverDelegate: DependencyResolverDelegate {\n    private weak var workspaceDelegate: Workspace.Delegate?\n    private let resolving = ThreadSafeKeyValueStore<PackageIdentity, Bool>()\n\n    init(_ delegate: Workspace.Delegate) {\n        self.workspaceDelegate = delegate\n    }\n\n    func willResolve(term: Term) {\n        // this may be called multiple time by the resolver for various version ranges, but we only want to propagate\n        // once since we report at package level\n        self.resolving.memoize(term.node.package.identity) {\n            self.workspaceDelegate?.willComputeVersion(\n                package: term.node.package.identity,\n                location: term.node.package.locationString\n            )\n            return true\n        }\n    }\n\n    func didResolve(term: Term, version: Version, duration: DispatchTimeInterval) {\n        self.workspaceDelegate?.didComputeVersion(\n            package: term.node.package.identity,\n            location: term.node.package.locationString,\n            version: version.description,\n            duration: duration\n        )\n    }\n\n    // noop\n    func derived(term: Term) {}\n    func conflict(conflict: Incompatibility) {}\n    func satisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility) {}\n    func partiallySatisfied(\n        term: Term,\n        by assignment: Assignment,\n        incompatibility: Incompatibility,\n        difference: Term\n    ) {}\n    func failedToResolve(incompatibility: Incompatibility) {}\n    func solved(result: [DependencyResolverBinding]) {}\n}\n\n// FIXME: the manifest loading logic should be changed to use identity instead of location once identity is unique\n// at that time we should remove this\n// @available(*, deprecated)\nextension PackageDependency {\n    var locationString: String {\n        switch self {\n        case .fileSystem(let settings):\n            return settings.path.pathString\n        case .sourceControl(let settings):\n            switch settings.location {\n            case .local(let path):\n                return path.pathString\n            case .remote(let url):\n                return url.absoluteString\n            }\n        case .registry:\n            // FIXME: placeholder\n            return self.identity.description\n        }\n    }\n}\n\nextension Workspace.ManagedDependencies {\n    fileprivate func hasEditedDependencies() -> Bool {\n        self.contains(where: {\n            switch $0.state {\n            case .edited:\n                return true\n            default:\n                return false\n            }\n        })\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Editing.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport PackageModel\nimport TSCBasic\n\nimport struct Basics.AbsolutePath\nimport class Basics.InMemoryFileSystem\nimport class Basics.ObservabilityScope\nimport struct Basics.RelativePath\nimport struct PackageGraph.PackageGraphRootInput\nimport struct SourceControl.Revision\n\nextension Workspace {\n    /// Edit implementation.\n    func _edit(\n        packageIdentity: String,\n        path: AbsolutePath? = nil,\n        revision: Revision? = nil,\n        checkoutBranch: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        // Look up the dependency and check if we can edit it.\n        guard let dependency = await self.state.dependencies[.plain(packageIdentity)] else {\n            observabilityScope.emit(.dependencyNotFound(packageName: packageIdentity))\n            return\n        }\n\n        let observabilityScope = observabilityScope.makeChildScope(\n            description: \"editing package\",\n            metadata: dependency.packageRef.diagnosticsMetadata\n        )\n\n        let checkoutState: CheckoutState\n        switch dependency.state {\n        case .sourceControlCheckout(let _checkoutState):\n            checkoutState = _checkoutState\n        case .edited:\n            observabilityScope.emit(error: \"dependency '\\(dependency.packageRef.identity)' already in edit mode\")\n            return\n        case .fileSystem:\n            observabilityScope.emit(error: \"local dependency '\\(dependency.packageRef.identity)' can't be edited\")\n            return\n        case .registryDownload:\n            observabilityScope.emit(error: \"registry dependency '\\(dependency.packageRef.identity)' can't be edited\")\n            return\n        case .custom:\n            observabilityScope.emit(error: \"custom dependency '\\(dependency.packageRef.identity)' can't be edited\")\n            return\n        }\n\n        // If a path is provided then we use it as destination. If not, we\n        // use the folder with packageName inside editablesPath.\n        let destination = path ?? self.location.editsDirectory.appending(component: packageIdentity)\n\n        // If there is something present at the destination, we confirm it has\n        // a valid manifest with name canonical location as the package we are trying to edit.\n        if fileSystem.exists(destination) {\n            let manifest = try await self.loadManifest(\n                packageIdentity: dependency.packageRef.identity,\n                packageKind: .fileSystem(destination),\n                packagePath: destination,\n                packageLocation: dependency.packageRef.locationString,\n                observabilityScope: observabilityScope\n            )\n\n            guard dependency.packageRef.canonicalLocation == manifest.canonicalPackageLocation else {\n                return observabilityScope\n                    .emit(\n                        error: \"package at '\\(destination)' is \\(dependency.packageRef.identity) but was expecting \\(packageIdentity)\"\n                    )\n            }\n\n            // Emit warnings for branch and revision, if they're present.\n            if let checkoutBranch {\n                observabilityScope.emit(.editBranchNotCheckedOut(\n                    packageName: packageIdentity,\n                    branchName: checkoutBranch\n                ))\n            }\n            if let revision {\n                observabilityScope.emit(.editRevisionNotUsed(\n                    packageName: packageIdentity,\n                    revisionIdentifier: revision.identifier\n                ))\n            }\n        } else {\n            // Otherwise, create a checkout at the destination from our repository store.\n            //\n            // Get handle to the repository.\n            let repository = try dependency.packageRef.makeRepositorySpecifier()\n            let handle = try await repositoryManager.lookup(\n                package: dependency.packageRef.identity,\n                repository: repository,\n                updateStrategy: .never,\n                observabilityScope: observabilityScope\n            )\n            let repo = try await handle.open()\n\n            // Do preliminary checks on branch and revision, if provided.\n            if let branch = checkoutBranch, repo.exists(revision: Revision(identifier: branch)) {\n                throw WorkspaceDiagnostics.BranchAlreadyExists(branch: branch)\n            }\n            if let revision, !repo.exists(revision: revision) {\n                throw WorkspaceDiagnostics.RevisionDoesNotExist(revision: revision.identifier)\n            }\n\n            let workingCopy = try await handle.createWorkingCopy(at: destination, editable: true)\n            try workingCopy.checkout(revision: revision ?? checkoutState.revision)\n\n            // Checkout to the new branch if provided.\n            if let branch = checkoutBranch {\n                try workingCopy.checkout(newBranch: branch)\n            }\n        }\n\n        // For unmanaged dependencies, create the symlink under editables dir.\n        if let path {\n            try fileSystem.createDirectory(self.location.editsDirectory)\n            // FIXME: We need this to work with InMem file system too.\n            if !(fileSystem is InMemoryFileSystem) {\n                let symLinkPath = self.location.editsDirectory.appending(component: packageIdentity)\n\n                // Cleanup any existing symlink.\n                if fileSystem.isSymlink(symLinkPath) {\n                    try fileSystem.removeFileTree(symLinkPath)\n                }\n\n                // FIXME: We should probably just warn in case we fail to create\n                // this symlink, which could happen if there is some non-symlink\n                // entry at this location.\n                try fileSystem.createSymbolicLink(symLinkPath, pointingAt: path, relative: false)\n            }\n        }\n\n        // Remove the existing checkout.\n        do {\n            let oldCheckoutPath = self.location.repositoriesCheckoutSubdirectory(for: dependency)\n            try fileSystem.chmod(.userWritable, path: oldCheckoutPath, options: [.recursive, .onlyFiles])\n            try fileSystem.removeFileTree(oldCheckoutPath)\n        }\n\n        // Save the new state.\n        try await self.state.add(\n            dependency: dependency.edited(subpath: RelativePath(validating: packageIdentity), unmanagedPath: path)\n        )\n        try await self.state.save()\n    }\n\n    /// Unedit a managed dependency. See public API unedit(packageName:forceRemove:).\n    func unedit(\n        dependency: ManagedDependency,\n        forceRemove: Bool,\n        root: PackageGraphRootInput? = nil,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        // Compute if we need to force remove.\n        var forceRemove = forceRemove\n\n        // If the dependency isn't in edit mode, we can't unedit it.\n        guard case .edited(_, let unmanagedPath) = dependency.state else {\n            throw WorkspaceDiagnostics\n                .DependencyNotInEditMode(dependencyName: dependency.packageRef.identity.description)\n        }\n\n        // Set force remove to true for unmanaged dependencies.  Note that\n        // this only removes the symlink under the editable directory and\n        // not the actual unmanaged package.\n        if unmanagedPath != nil {\n            forceRemove = true\n        }\n\n        // Form the edit working repo path.\n        let path = self.location.editSubdirectory(for: dependency)\n        // Check for uncommitted and unpushed changes if force removal is off.\n        if !forceRemove {\n            let workingCopy = try await repositoryManager.openWorkingCopy(at: path)\n            guard !workingCopy.hasUncommittedChanges() else {\n                throw WorkspaceDiagnostics.UncommittedChanges(repositoryPath: path)\n            }\n            guard try !workingCopy.hasUnpushedCommits() else {\n                throw WorkspaceDiagnostics.UnpushedChanges(repositoryPath: path)\n            }\n        }\n        // Remove the editable checkout from disk.\n        if fileSystem.exists(path) {\n            try fileSystem.removeFileTree(path)\n        }\n        // If this was the last editable dependency, remove the editables directory too.\n        if fileSystem.exists(self.location.editsDirectory),\n           try fileSystem.getDirectoryContents(self.location.editsDirectory).isEmpty\n        {\n            try fileSystem.removeFileTree(self.location.editsDirectory)\n        }\n\n        if case .edited(let basedOn, _) = dependency.state,\n           case .sourceControlCheckout(let checkoutState) = basedOn?.state\n        {\n            // Restore the original checkout.\n            //\n            // The retrieve method will automatically update the managed dependency state.\n            _ = try await self.checkoutRepository(\n                package: dependency.packageRef,\n                at: checkoutState,\n                observabilityScope: observabilityScope\n            )\n        } else {\n            // The original dependency was removed, update the managed dependency state.\n            await self.state.remove(identity: dependency.packageRef.identity)\n            try await self.state.save()\n        }\n\n        // Resolve the dependencies if workspace root is provided. We do this to\n        // ensure the unedited version of this dependency is resolved properly.\n        if let root {\n            try await self._resolve(\n                root: root,\n                explicitProduct: .none,\n                resolvedFileStrategy: .update(forceResolution: false),\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Manifests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\n\nimport struct Basics.AbsolutePath\nimport func Basics.depthFirstSearch\nimport struct Basics.Diagnostic\nimport struct Basics.InternalError\nimport class Basics.ObservabilityScope\nimport struct Basics.SwiftVersion\nimport class Basics.ThreadSafeKeyValueStore\nimport class Dispatch.DispatchGroup\nimport struct Dispatch.DispatchTime\nimport struct OrderedCollections.OrderedDictionary\nimport struct OrderedCollections.OrderedSet\nimport protocol PackageGraph.CustomPackageContainer\nimport struct PackageGraph.GraphLoadingNode\nimport struct PackageGraph.PackageContainerConstraint\nimport struct PackageGraph.PackageGraphRoot\nimport class PackageLoading.ManifestLoader\nimport struct PackageLoading.ManifestValidator\nimport struct PackageLoading.ToolsVersionParser\nimport struct PackageModel.EnabledTrait\nimport struct PackageModel.EnabledTraits\nimport enum PackageModel.TraitError\nimport class PackageModel.Manifest\nimport struct PackageModel.PackageIdentity\nimport struct PackageModel.PackageReference\nimport enum PackageModel.ProductFilter\nimport struct PackageModel.ToolsVersion\nimport enum PackageModel.TraitConfiguration\nimport protocol TSCBasic.FileSystem\nimport func TSCBasic.findCycle\nimport struct TSCBasic.KeyedPair\nimport struct TSCBasic.StringError\nimport func TSCBasic.topologicalSort\nimport func TSCBasic.transitiveClosure\nimport enum TSCUtility.Diagnostics\nimport struct TSCUtility.Version\n\n// MARK: - Manifest Loading and caching\n\nextension Workspace {\n    /// A struct representing all the current manifests (root + external) in a package graph.\n    public struct DependencyManifests {\n        /// The package graph root.\n        var root: PackageGraphRoot\n\n        /// The dependency manifests in the transitive closure of root manifest.\n        let dependencies: [(\n            manifest: Manifest,\n            dependency: ManagedDependency,\n            productFilter: ProductFilter,\n            fileSystem: FileSystem\n        )]\n\n        private let workspace: Workspace\n\n        private let observabilityScope: ObservabilityScope\n\n        private let _dependencies: LoadableResult<(\n            required: OrderedCollections.OrderedSet<PackageReference>,\n            missing: OrderedCollections.OrderedSet<PackageReference>,\n            unused: OrderedCollections.OrderedSet<PackageReference>\n        )>\n\n        private let _constraints: LoadableResult<[PackageContainerConstraint]>\n\n        fileprivate init(\n            root: PackageGraphRoot,\n            dependencies: [(\n                manifest: Manifest,\n                dependency: ManagedDependency,\n                productFilter: ProductFilter,\n                fileSystem: FileSystem\n            )],\n            workspace: Workspace,\n            observabilityScope: ObservabilityScope\n        ) {\n            self.root = root\n            self.dependencies = dependencies\n            self.workspace = workspace\n            self.observabilityScope = observabilityScope\n            self._dependencies = LoadableResult {\n                try Self.computeDependencies(\n                    root: root,\n                    dependencies: dependencies,\n                    workspace: workspace,\n                    observabilityScope: observabilityScope\n                )\n            }\n            self._constraints = LoadableResult {\n                try Self.computeConstraints(\n                    root: root,\n                    dependencies: dependencies,\n                    workspace: workspace\n                )\n            }\n        }\n\n        /// Returns all manifests contained in DependencyManifests.\n        public var allDependencyManifests: OrderedCollections.OrderedDictionary<\n            PackageIdentity,\n            (manifest: Manifest, fs: FileSystem)\n        > {\n            self.dependencies.reduce(into: OrderedCollections.OrderedDictionary<\n                PackageIdentity,\n                (manifest: Manifest, fs: FileSystem)\n            >()) { partial, item in\n                partial[item.dependency.packageRef.identity] = (item.manifest, item.fileSystem)\n            }\n        }\n\n        /// Computes the identities which are declared in the manifests but aren't present in dependencies.\n        public var missingPackages: [PackageReference] {\n            get throws {\n                try self._dependencies.load().missing.elements\n            }\n        }\n\n        /// Computes the identities which are declared in the manifests but aren't present in dependencies.\n        public var requiredPackages: [PackageReference] {\n            get throws {\n                try self._dependencies.load().required.elements\n            }\n        }\n\n        /// Computes the identities which are declared in the manifests are aren't used by any targets.\n        public var unusedPackages: [PackageReference] {\n            get throws {\n                try self._dependencies.load().unused.elements\n            }\n        }\n\n        /// Returns the list of packages which are allowed to vend products with unsafe flags.\n        var unsafeAllowedPackages: Set<PackageReference> {\n            var result = Set<PackageReference>()\n\n            for dependency in self.dependencies {\n                let dependency = dependency.dependency\n                switch dependency.state {\n                case .sourceControlCheckout(let checkout):\n                    let packageRef = dependency.packageRef\n\n                    if checkout.isBranchOrRevisionBased\n                        // FIXME: Remove this once we have a general mechanism\n                        //        for passing \"safe\" flags.\n                        || packageRef.identity == .plain(\"swift-corelibs-foundation\")\n                    {\n                        result.insert(packageRef)\n                    }\n\n                case .registryDownload, .custom:\n                    continue\n\n                case .fileSystem, .edited:\n                    result.insert(dependency.packageRef)\n                }\n            }\n\n            // Root packages are always allowed to use unsafe flags.\n            result.formUnion(root.packageReferences)\n\n            return result\n        }\n\n        private static func computeDependencies(\n            root: PackageGraphRoot,\n            dependencies: [(\n                manifest: Manifest,\n                dependency: ManagedDependency,\n                productFilter: ProductFilter,\n                fileSystem: FileSystem\n            )],\n            workspace: Workspace,\n            observabilityScope: ObservabilityScope\n        ) throws\n            -> (\n                required: OrderedCollections.OrderedSet<PackageReference>,\n                missing: OrderedCollections.OrderedSet<PackageReference>,\n                unused: OrderedCollections.OrderedSet<PackageReference>\n            )\n        {\n            // Temporary countermeasures against rdar://83316222; be robust against having colliding identities in both\n            // `root.packages` and `dependencies`.\n            var manifestsMap: [PackageIdentity: Manifest] = [:]\n            root.packages.map { ($0.key, $0.value.manifest) }.forEach {\n                if manifestsMap[$0.0] == nil {\n                    manifestsMap[$0.0] = $0.1\n                }\n            }\n            dependencies.map { ($0.dependency.packageRef.identity, $0.manifest) }.forEach {\n                if manifestsMap[$0.0] == nil {\n                    manifestsMap[$0.0] = $0.1\n                }\n            }\n\n            var unusedIdentities: OrderedCollections.OrderedSet<PackageReference> = []\n            var inputIdentities: OrderedCollections.OrderedSet<PackageReference> = []\n\n            let inputNodes: [GraphLoadingNode] = try root.packages.map { identity, package in\n                inputIdentities.append(package.reference)\n\n                let node = try GraphLoadingNode(\n                    identity: identity,\n                    manifest: package.manifest,\n                    productFilter: .everything,\n                    enabledTraits: workspace.enabledTraitsMap[package.reference.identity]\n                )\n                return node\n            } + root.dependencies.compactMap { dependency in\n                let package = dependency.packageRef\n                inputIdentities.append(package)\n                return try manifestsMap[dependency.identity].map { manifest in\n\n                    return try GraphLoadingNode(\n                        identity: dependency.identity,\n                        manifest: manifest,\n                        productFilter: dependency.productFilter,\n                        enabledTraits: workspace.enabledTraitsMap[dependency.identity]\n                    )\n                }\n            }\n\n            // Begin with all packages having everything as an unused dependency.\n            var unusedDepsPerPackage: [PackageIdentity: [PackageReference]] = manifestsMap\n                .reduce(into: [PackageIdentity: [PackageReference]]()) { depsMap, manifestMap in\n                    depsMap[manifestMap.key] = manifestsMap.compactMap { identity, manifest in\n                        guard !root.manifests.contains(where: { identity == $0.key }) else { return nil }\n                        let kind = manifest.packageKind\n                        let ref = PackageReference(identity: identity, kind: kind)\n                        return ref\n                    }\n                }\n\n            let topLevelDependencies = root.packages.flatMap { $1.manifest.dependencies.map(\\.packageRef) }\n\n            var requiredIdentities: OrderedCollections.OrderedSet<PackageReference> = []\n            _ = try transitiveClosure(inputNodes) { node in\n                return try node.manifest.dependenciesRequired(for: node.productFilter, node.enabledTraits)\n                    .compactMap { dependency in\n                        let package = dependency.packageRef\n\n                        // Check if traits are guarding the dependency from being enabled.\n                        // Also check whether we've enabled pruning unused dependencies.\n                        let isDepUsed = try node.manifest.isPackageDependencyUsed(\n                            dependency,\n                            enabledTraits: node.enabledTraits\n                        )\n                        if !isDepUsed && workspace.configuration.pruneDependencies {\n                            if !node.enabledTraits.isEmpty {\n                                observabilityScope.emit(debug: \"\"\"\n                            '\\(package.identity)' from '\\(package.locationString)' was omitted \\\n                            from required dependencies because it is being guarded by the following traits:' \\\n                            \\(node.enabledTraits.joined(separator: \", \"))\n                            \"\"\")\n                            } else {\n                                observabilityScope.emit(debug: \"\"\"\n                            '\\(package.identity)' from '\\(package.locationString)' was omitted \\\n                            from required dependencies because it is unused\n                            \"\"\")\n                            }\n                        } else {\n                            unusedDepsPerPackage[node.identity, default: []] = unusedDepsPerPackage[\n                                node.identity,\n                                default: []\n                            ].filter { $0.identity != dependency.identity }\n                            let (inserted, index) = requiredIdentities.append(package)\n                            if !inserted {\n                                let existing = requiredIdentities.elements[index]\n                                // if identity already tracked, compare the locations and used the preferred variant\n                                if existing.canonicalLocation == package.canonicalLocation {\n                                    // same literal location is fine\n                                    if existing.locationString != package.locationString {\n                                        // we prefer the top level dependencies\n                                        if topLevelDependencies.contains(where: {\n                                            $0.locationString == existing.locationString\n                                        }) {\n                                            observabilityScope.emit(debug: \"\"\"\n                                            similar variants of package '\\(package.identity)' \\\n                                            found at '\\(package.locationString)' and '\\(existing.locationString)'. \\\n                                            using preferred root variant '\\(existing.locationString)'\n                                            \"\"\")\n                                        } else {\n                                            let preferred = [existing, package].sorted(by: {\n                                                $0.locationString > $1.locationString\n                                            }).first! // safe\n                                            observabilityScope.emit(debug: \"\"\"\n                                            similar variants of package '\\(package.identity)' \\\n                                            found at '\\(package.locationString)' and '\\(existing.locationString)'. \\\n                                            using preferred variant '\\(preferred.locationString)'\n                                            \"\"\")\n                                            if preferred.locationString != existing.locationString {\n                                                requiredIdentities.remove(existing)\n                                                requiredIdentities.insert(preferred, at: index)\n                                            }\n                                        }\n                                    }\n                                } else {\n                                    observabilityScope.emit(debug: \"\"\"\n                                    '\\(package.identity)' from '\\(package.locationString)' was omitted \\\n                                    from required dependencies because it has the same identity as the \\\n                                    one from '\\(existing.locationString)'\n                                    \"\"\")\n                                }\n                            }\n                        }\n\n                        let enabledTraitsSet = workspace.enabledTraitsMap[dependency.identity]\n\n                        return try manifestsMap[dependency.identity].map { manifest in\n\n                            return try GraphLoadingNode(\n                                identity: dependency.identity,\n                                manifest: manifest,\n                                productFilter: dependency.productFilter,\n                                enabledTraits: enabledTraitsSet\n                            )\n                        }\n                    }\n            }\n            requiredIdentities = inputIdentities.union(requiredIdentities)\n\n            // Calculate all unused identities:\n            let unusedAcrossAllPackages = unusedDepsPerPackage.values.map { Set($0) }\n                .reduce(Set(unusedDepsPerPackage.values.first ?? [])) { unused, deps in\n                    unused.intersection(deps)\n                }\n\n            unusedIdentities = unusedIdentities.union(unusedAcrossAllPackages)\n\n            if workspace.configuration.pruneDependencies {\n                requiredIdentities = requiredIdentities.subtracting(unusedIdentities)\n            }\n\n            var availableIdentities: Set<PackageReference> = try Set(manifestsMap.map {\n                // FIXME: adding this guard to ensure refactoring is correct 9/21\n                // we only care about remoteSourceControl for this validation. it would otherwise trigger for\n                // a dependency is put into edit mode, which we want to deprecate anyways\n                if case .remoteSourceControl = $0.1.packageKind {\n                    let effectiveURL = workspace.mirrors.effective(for: $0.1.packageLocation)\n                    guard effectiveURL == $0.1.packageKind.locationString else {\n                        throw InternalError(\n                            \"effective url for \\($0.1.packageLocation) is \\(effectiveURL), different from expected \\($0.1.packageKind.locationString)\"\n                        )\n                    }\n                }\n                return PackageReference(identity: $0.key, kind: $0.1.packageKind)\n            })\n\n            if workspace.configuration.pruneDependencies {\n                availableIdentities = availableIdentities.subtracting(unusedIdentities)\n            }\n\n            // We should never have loaded a manifest we don't need.\n            assert(\n                availableIdentities.isSubset(of: requiredIdentities),\n                \"\\(availableIdentities.map(\\.identity)) | \\(requiredIdentities.map(\\.identity))\"\n            )\n            // These are the missing package identities.\n            let missingIdentities = requiredIdentities.subtracting(availableIdentities)\n\n            return (requiredIdentities, missingIdentities, unusedIdentities)\n        }\n\n        /// Returns constraints of the dependencies, including edited package constraints.\n        var dependencyConstraints: [PackageContainerConstraint] {\n            get throws {\n                try self._constraints.load()\n            }\n        }\n\n        private static func computeConstraints(\n            root: PackageGraphRoot,\n            dependencies: [(\n                manifest: Manifest,\n                dependency: ManagedDependency,\n                productFilter: ProductFilter,\n                fileSystem: FileSystem\n            )],\n            workspace: Workspace\n        ) throws -> [PackageContainerConstraint] {\n            var allConstraints = [PackageContainerConstraint]()\n\n            for (externalManifest, managedDependency, productFilter, _) in dependencies {\n                // For edited packages, add a constraint with unversioned requirement so the\n                // resolver doesn't try to resolve it.\n                switch managedDependency.state {\n                case .edited:\n                    // FIXME: We shouldn't need to construct a new package reference object here.\n                    // We should get the correct one from managed dependency object.\n                    let ref = PackageReference.fileSystem(\n                        identity: managedDependency.packageRef.identity,\n                        path: workspace.path(to: managedDependency)\n                    )\n                    let constraint = PackageContainerConstraint(\n                        package: ref,\n                        requirement: .unversioned,\n                        products: productFilter\n                    )\n                    allConstraints.append(constraint)\n                case .sourceControlCheckout, .registryDownload, .fileSystem, .custom:\n                    break\n                }\n                allConstraints += try externalManifest.dependencyConstraints(\n                    productFilter: productFilter,\n                    workspace.enabledTraitsMap[managedDependency.packageRef.identity]\n                )\n            }\n            return allConstraints\n        }\n\n        // FIXME: @testable(internal)\n        /// Returns a list of constraints for all 'edited' package.\n        public var editedPackagesConstraints: [PackageContainerConstraint] {\n            var constraints = [PackageContainerConstraint]()\n\n            for (_, managedDependency, productFilter, _) in dependencies {\n                switch managedDependency.state {\n                case .sourceControlCheckout, .registryDownload, .fileSystem, .custom: continue\n                case .edited: break\n                }\n                // FIXME: We shouldn't need to construct a new package reference object here.\n                // We should get the correct one from managed dependency object.\n                let ref = PackageReference.fileSystem(\n                    identity: managedDependency.packageRef.identity,\n                    path: workspace.path(to: managedDependency)\n                )\n                let constraint = PackageContainerConstraint(\n                    package: ref,\n                    requirement: .unversioned,\n                    products: productFilter\n                )\n                constraints.append(constraint)\n            }\n            return constraints\n        }\n    }\n\n    /// Returns the location of the dependency.\n    ///\n    /// Source control dependencies will return the subpath inside `checkoutsPath` and\n    /// Registry dependencies will return the subpath inside `registryDownloadsPath` and\n    /// edited dependencies will either return a subpath inside `editablesPath` or\n    /// a custom path.\n    public func path(to dependency: Workspace.ManagedDependency) -> AbsolutePath {\n        switch dependency.state {\n        case .sourceControlCheckout:\n            self.location.repositoriesCheckoutSubdirectory(for: dependency)\n        case .registryDownload:\n            self.location.registryDownloadSubdirectory(for: dependency)\n        case .edited(_, let path):\n            path ?? self.location.editSubdirectory(for: dependency)\n        case .fileSystem(let path):\n            path\n        case .custom(_, let path):\n            path\n        }\n    }\n\n    /// Returns manifest interpreter flags for a package.\n    public func interpreterFlags(for manifestPath: AbsolutePath) throws -> [String] {\n        guard let manifestLoader = self.manifestLoader as? ManifestLoader else {\n            throw StringError(\"unexpected manifest loader kind\")\n        }\n\n        let manifestToolsVersion = (try? ToolsVersionParser.parse(\n            manifestPath: manifestPath,\n            fileSystem: self.fileSystem\n        )) ?? self.currentToolsVersion\n\n        guard self.currentToolsVersion >= manifestToolsVersion || SwiftVersion.current.isDevelopment,\n              manifestToolsVersion >= ToolsVersion.minimumRequired\n        else {\n            throw StringError(\"invalid tools version\")\n        }\n        return manifestLoader.interpreterFlags(for: manifestToolsVersion)\n    }\n\n    /// Load the manifests for the current dependency tree.\n    ///\n    /// This will load the manifests for the root package as well as all the\n    /// current dependencies from the working checkouts.\n    public func loadDependencyManifests(\n        root: PackageGraphRoot,\n        automaticallyAddManagedDependencies: Bool = false,\n        observabilityScope: ObservabilityScope\n    ) async throws -> DependencyManifests {\n        let prepopulateManagedDependencies: ([PackageReference]) async throws -> Void = { refs in\n            // pre-populate managed dependencies if we are asked to do so (this happens when resolving to a resolved\n            // file)\n            if automaticallyAddManagedDependencies {\n                for ref in refs {\n                    // Since we are creating managed dependencies based on the resolved file in this mode, but local\n                    // packages aren't part of that file, they will be missing from it. So we're eagerly adding them\n                    // here, but explicitly don't add any that are overridden by a root with the same identity since\n                    // that would lead to loading the given package twice, once as a root and once as a dependency\n                    // which violates various assumptions.\n                    if case .fileSystem = ref.kind, !root.manifests.keys.contains(ref.identity) {\n                        try await self.state.add(dependency: .fileSystem(packageRef: ref))\n                    }\n                }\n                await observabilityScope.trap { try await self.state.save() }\n            }\n        }\n\n        // Make a copy of dependencies as we might mutate them in the for loop.\n        let dependenciesToCheck = await Array(self.state.dependencies)\n        // Remove any managed dependency which has become a root.\n        for dependency in dependenciesToCheck {\n            if root.packages.keys.contains(dependency.packageRef.identity) {\n                await observabilityScope.makeChildScope(\n                    description: \"removing managed dependencies\",\n                    metadata: dependency.packageRef.diagnosticsMetadata\n                ).trap {\n                    try await self.remove(package: dependency.packageRef)\n                }\n            }\n        }\n\n        // Validates that all the managed dependencies are still present in the file system.\n        await self.fixManagedDependencies(\n            observabilityScope: observabilityScope\n        )\n        guard !observabilityScope.errorsReported else {\n            // return partial results\n            return DependencyManifests(\n                root: root,\n                dependencies: [],\n                workspace: self,\n                observabilityScope: observabilityScope\n            )\n        }\n\n        // Load root dependencies manifests (in parallel)\n        let rootDependencies = root.dependencies.map(\\.packageRef)\n        try await prepopulateManagedDependencies(rootDependencies)\n        let rootDependenciesManifests = try await self.loadManagedManifests(\n            for: rootDependencies,\n            observabilityScope: observabilityScope\n        )\n\n        let rootManifests = try root.manifests.mapValues { manifest in\n            let parentEnabledTraits = self.enabledTraitsMap[manifest.packageIdentity]\n            let deps = try manifest.dependencies.filter { dep in\n                let isDepUsed = try manifest.isPackageDependencyUsed(dep, enabledTraits: parentEnabledTraits)\n                return isDepUsed\n            }\n\n            return Manifest(\n                displayName: manifest.displayName,\n                packageIdentity: manifest.packageIdentity,\n                path: manifest.path,\n                packageKind: manifest.packageKind,\n                packageLocation: manifest.packageLocation,\n                defaultLocalization: manifest.defaultLocalization,\n                platforms: manifest.platforms,\n                version: manifest.version,\n                revision: manifest.revision,\n                toolsVersion: manifest.toolsVersion,\n                pkgConfig: manifest.pkgConfig,\n                providers: manifest.providers,\n                cLanguageStandard: manifest.cLanguageStandard,\n                cxxLanguageStandard: manifest.cxxLanguageStandard,\n                swiftLanguageVersions: manifest.swiftLanguageVersions,\n                dependencies: deps,\n                products: manifest.products,\n                targets: manifest.targets,\n                traits: manifest.traits,\n                pruneDependencies: manifest.pruneDependencies\n            )\n        }\n\n        let topLevelManifests = rootManifests.merging(rootDependenciesManifests, uniquingKeysWith: { lhs, _ in\n            lhs // prefer roots!\n        })\n\n        // optimization: preload first level dependencies manifest (in parallel)\n        let firstLevelDependencies = try topLevelManifests.values.map { manifest in\n            let parentEnabledTraits = self.enabledTraitsMap[manifest.packageIdentity]\n\n            // Resolve and flatten the list of traits on top level manifests. This handles\n            // the case where a package is being loaded in a wrapper project (not package),\n            // where there are no root packages but there are dependencies.\n            if root.packages.isEmpty {\n                let topLevelManifestTraits = try manifest.enabledTraits(using: parentEnabledTraits)\n                self.enabledTraitsMap[manifest.packageIdentity] = topLevelManifestTraits\n            }\n\n            return try manifest.dependencies.filter { dep in\n                let isDepUsed = try manifest.isPackageDependencyUsed(dep, enabledTraits: parentEnabledTraits)\n                return isDepUsed\n\n            }.map(\\.packageRef)\n        }.flatMap(\\.self)\n\n        let firstLevelManifests = try await self.loadManagedManifests(\n            for: firstLevelDependencies,\n            observabilityScope: observabilityScope\n        )\n\n        // Continue to load the rest of the manifest for this graph\n        // Creates a map of loaded manifests. We do this to avoid reloading the shared nodes.\n        var loadedManifests = firstLevelManifests\n        let successorNodes: (KeyedPair<GraphLoadingNode, PackageIdentity>) async throws -> [KeyedPair<\n            GraphLoadingNode,\n            PackageIdentity\n        >] = { node in\n            // optimization: preload manifest we know about in parallel\n            // avoid loading dependencies that are trait-guarded here since this is redundant.\n            let dependenciesRequired = try node.item.manifest.dependenciesRequired(\n                for: node.item.productFilter,\n                node.item.enabledTraits\n            )\n            let dependenciesToLoad = dependenciesRequired.map(\\.packageRef)\n                .filter { !loadedManifests.keys.contains($0.identity) }\n            try await prepopulateManagedDependencies(dependenciesToLoad)\n            let dependenciesManifests = try await self.loadManagedManifests(\n                for: dependenciesToLoad,\n                observabilityScope: observabilityScope\n            )\n            dependenciesManifests.forEach { loadedManifests[$0.key] = $0.value }\n            return try dependenciesRequired.compactMap { dependency in\n                return try loadedManifests[dependency.identity].flatMap { manifest in\n                    // we also compare the location as this function may attempt to load\n                    // dependencies that have the same identity but from a different location\n                    // which is an error case we diagnose an report about in the GraphLoading part which\n                    // is prepared to handle the case where not all manifest are available\n                    return manifest.canonicalPackageLocation == dependency.packageRef.canonicalLocation ?\n                        try KeyedPair(\n                            GraphLoadingNode(\n                                identity: dependency.identity,\n                                manifest: manifest,\n                                productFilter: dependency.productFilter,\n                                enabledTraits: self.enabledTraitsMap[dependency.identity]\n                            ),\n                            key: dependency.identity\n                        ) :\n                        nil\n                }\n            }\n        }\n\n        var allNodes = OrderedDictionary<PackageIdentity, GraphLoadingNode>()\n\n        do {\n            let manifestGraphRoots = try topLevelManifests.map { identity, manifest in\n                return try KeyedPair(\n                    GraphLoadingNode(\n                        identity: identity,\n                        manifest: manifest,\n                        productFilter: .everything,\n                        enabledTraits: self.enabledTraitsMap[identity]\n                    ),\n                    key: identity\n                )\n            }\n\n            try await depthFirstSearch(\n                manifestGraphRoots,\n                successors: successorNodes\n            ) {\n                allNodes[$0.key] = $0.item\n            } onDuplicate: { _, _ in\n                // Nothing we need to compute here.\n            }\n        }\n\n        // Second pass: Update enabled traits for dependencies now that we have all manifests loaded\n        // This resolves the race condition where parents might set traits for dependencies\n        // before the dependency manifest is loaded and its default traits are known.\n        let allManifests = allNodes.mapValues(\\.manifest)\n        for (_, manifest) in allManifests {\n            try updateEnabledTraits(for: manifest)\n        }\n\n        let dependencyManifests = allNodes.filter { !$0.value.manifest.packageKind.isRoot }\n\n        // TODO: this check should go away when introducing explicit overrides\n        // check for overrides attempts with same name but different path\n        let rootManifestsByName = Array(root.manifests.values).spm_createDictionary { ($0.displayName, $0) }\n        for (_, node) in dependencyManifests {\n            if let override = rootManifestsByName[node.manifest.displayName],\n               override.packageLocation != node.manifest.packageLocation\n            {\n                observabilityScope\n                    .emit(\n                        error: \"unable to override package '\\(node.manifest.displayName)' because its identity '\\(PackageIdentity(urlString: node.manifest.packageLocation))' doesn't match override's identity (directory name) '\\(PackageIdentity(urlString: override.packageLocation))'\"\n                    )\n            }\n        }\n\n        var dependencies: [(Manifest, ManagedDependency, ProductFilter, FileSystem)] = []\n        for (identity, node) in dependencyManifests {\n            guard let dependency = await self.state.dependencies[identity] else {\n                throw InternalError(\"dependency not found for \\(identity) at \\(node.manifest.packageLocation)\")\n            }\n\n            let packageRef = PackageReference(identity: identity, kind: node.manifest.packageKind)\n            let fileSystem = try await self.getFileSystem(\n                package: packageRef,\n                state: dependency.state,\n                observabilityScope: observabilityScope\n            )\n            dependencies.append((node.manifest, dependency, node.productFilter, fileSystem ?? self.fileSystem))\n        }\n\n        return DependencyManifests(\n            root: root,\n            dependencies: dependencies,\n            workspace: self,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Loads the given manifests, if it is present in the managed dependencies.\n    ///\n\n    private func loadManagedManifests(\n        for packages: [PackageReference],\n        observabilityScope: ObservabilityScope\n    ) async throws -> [PackageIdentity: Manifest] {\n        try await withThrowingTaskGroup(of: (PackageIdentity, Manifest?).self) { group in\n            for package in Set(packages) {\n                group.addTask {\n                    await (\n                        package.identity,\n                        try self.loadManagedManifest(for: package, observabilityScope: observabilityScope)\n                    )\n                }\n            }\n            return try await group.compactMap {\n                $0 as? (PackageIdentity, Manifest)\n            }.reduce(into: [PackageIdentity: Manifest]()) { partialResult, loadedManifest in\n                partialResult[loadedManifest.0] = loadedManifest.1\n            }\n        }\n    }\n\n    /// Loads the given manifest, if it is present in the managed dependencies.\n    private func loadManagedManifest(\n        for package: PackageReference,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Manifest? {\n        // Check if this dependency is available.\n        // we also compare the location as this function may attempt to load\n        // dependencies that have the same identity but from a different location\n        // which is an error case we diagnose an report about in the GraphLoading part which\n        // is prepared to handle the case where not all manifest are available\n        guard let managedDependency = await self.state.dependencies[comparingLocation: package] else {\n            return nil\n        }\n\n        // Get the path of the package.\n        let packagePath = self.path(to: managedDependency)\n\n        // The kind and version, if known.\n        let packageKind: PackageReference.Kind\n        let packageVersion: Version?\n        switch managedDependency.state {\n        case .sourceControlCheckout(let checkoutState):\n            packageKind = managedDependency.packageRef.kind\n            switch checkoutState {\n            case .version(let checkoutVersion, _):\n                packageVersion = checkoutVersion\n            default:\n                packageVersion = .none\n            }\n        case .registryDownload(let downloadedVersion):\n            packageKind = managedDependency.packageRef.kind\n            packageVersion = downloadedVersion\n        case .custom(let availableVersion, _):\n            packageKind = managedDependency.packageRef.kind\n            packageVersion = availableVersion\n        case .edited, .fileSystem:\n            packageKind = .fileSystem(packagePath)\n            packageVersion = .none\n        }\n\n        let fileSystem: FileSystem?\n        do {\n            fileSystem = try await self.getFileSystem(\n                package: package,\n                state: managedDependency.state,\n                observabilityScope: observabilityScope\n            )\n        } catch {\n            // only warn here in case of issues since we should not even get here without a valid package container\n            observabilityScope.emit(\n                warning: \"unexpected failure while accessing custom package container\",\n                underlyingError: error\n            )\n            fileSystem = nil\n        }\n\n        // Load and return the manifest.\n        return try await self.loadManifest(\n            packageIdentity: managedDependency.packageRef.identity,\n            packageKind: packageKind,\n            packagePath: packagePath,\n            packageLocation: managedDependency.packageRef.locationString,\n            packageVersion: packageVersion,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Load the manifest at a given path.\n    ///\n    /// This is just a helper wrapper to the manifest loader.\n    func loadManifest(\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packagePath: AbsolutePath,\n        packageLocation: String,\n        packageVersion: Version? = nil,\n        fileSystem: FileSystem? = nil,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Manifest {\n        let fileSystem = fileSystem ?? self.fileSystem\n\n        // Load the manifest, bracketed by the calls to the delegate callbacks.\n        delegate?.willLoadManifest(\n            packageIdentity: packageIdentity,\n            packagePath: packagePath,\n            url: packageLocation,\n            version: packageVersion,\n            packageKind: packageKind\n        )\n\n        let manifestLoadingScope = observabilityScope.makeChildScope(description: \"Loading manifest\") {\n            .packageMetadata(identity: packageIdentity, kind: packageKind)\n        }\n\n        var manifestLoadingDiagnostics = [Diagnostic]()\n        defer { manifestLoadingScope.emit(manifestLoadingDiagnostics) }\n\n        let start = DispatchTime.now()\n        let manifest: Manifest\n        do {\n            manifest = try await self.manifestLoader.load(\n                packagePath: packagePath,\n                packageIdentity: packageIdentity,\n                packageKind: packageKind,\n                packageLocation: packageLocation,\n                packageVersion: packageVersion.map { (version: $0, revision: nil) },\n                currentToolsVersion: self.currentToolsVersion,\n                identityResolver: self.identityResolver,\n                dependencyMapper: self.dependencyMapper,\n                fileSystem: fileSystem,\n                observabilityScope: manifestLoadingScope,\n                delegateQueue: .sharedConcurrent\n            )\n        } catch {\n            let duration = start.distance(to: .now())\n            manifestLoadingDiagnostics.append(.error(error))\n            self.delegate?.didLoadManifest(\n                packageIdentity: packageIdentity,\n                packagePath: packagePath,\n                url: packageLocation,\n                version: packageVersion,\n                packageKind: packageKind,\n                manifest: nil,\n                diagnostics: manifestLoadingDiagnostics,\n                duration: duration\n            )\n            throw error\n        }\n\n        let duration = start.distance(to: .now())\n        let validator = ManifestValidator(\n            manifest: manifest,\n            sourceControlValidator: self.repositoryManager,\n            fileSystem: self.fileSystem\n        )\n        let validationIssues = validator.validate()\n        if !validationIssues.isEmpty {\n            // Diagnostics.fatalError indicates that a more specific diagnostic has already been added.\n            manifestLoadingDiagnostics.append(contentsOf: validationIssues)\n            throw Diagnostics.fatalError\n        }\n\n        // Upon loading a new manifest, update enabled traits.\n        try self.updateEnabledTraits(for: manifest)\n\n        self.delegate?.didLoadManifest(\n            packageIdentity: packageIdentity,\n            packagePath: packagePath,\n            url: packageLocation,\n            version: packageVersion,\n            packageKind: packageKind,\n            manifest: manifest,\n            diagnostics: manifestLoadingDiagnostics,\n            duration: duration\n        )\n\n        return manifest\n    }\n\n    /// Validates that all the edited dependencies are still present in the file system.\n    /// If some checkout dependency is removed form the file system, clone it again.\n    /// If some edited dependency is removed from the file system, mark it as unedited and\n    /// fallback on the original checkout.\n    private func fixManagedDependencies(\n        observabilityScope: ObservabilityScope\n    ) async {\n        // Reset managed dependencies if the state file was removed during the lifetime of the Workspace object.\n        if await !self.state.dependencies.isEmpty, await !self.state.stateFileExists() {\n            try? await self.state.reset()\n        }\n\n        // Make a copy of dependencies as we might mutate them in the for loop.\n        let allDependencies = await Array(self.state.dependencies)\n        for dependency in allDependencies {\n            await observabilityScope.makeChildScope(\n                description: \"copying managed dependencies\",\n                metadata: dependency.packageRef.diagnosticsMetadata\n            ).trap {\n                // If the dependency is present, we're done.\n                let dependencyPath = self.path(to: dependency)\n                if fileSystem.isDirectory(dependencyPath) {\n                    return\n                }\n\n                switch dependency.state {\n                case .sourceControlCheckout(let checkoutState):\n                    // If some checkout dependency has been removed, retrieve it again.\n                    _ = try await self.checkoutRepository(\n                        package: dependency.packageRef,\n                        at: checkoutState,\n                        observabilityScope: observabilityScope\n                    )\n                    observabilityScope\n                        .emit(.checkedOutDependencyMissing(packageName: dependency.packageRef.identity.description))\n\n                case .registryDownload(let version):\n                    // If some downloaded dependency has been removed, retrieve it again.\n                    _ = try await self.downloadRegistryArchive(\n                        package: dependency.packageRef,\n                        at: version,\n                        observabilityScope: observabilityScope\n                    )\n                    observabilityScope\n                        .emit(.registryDependencyMissing(packageName: dependency.packageRef.identity.description))\n\n                case .custom(let version, let path):\n                    let container = try await self.packageContainerProvider.getContainer(\n                        for: dependency.packageRef,\n                        updateStrategy: .never,\n                        observabilityScope: observabilityScope\n                    )\n                    if let customContainer = container as? CustomPackageContainer {\n                        let newPath = try customContainer.retrieve(at: version, observabilityScope: observabilityScope)\n                        observabilityScope\n                            .emit(.customDependencyMissing(packageName: dependency.packageRef.identity.description))\n\n                        // FIXME: We should be able to handle this case and also allow changed paths for registry and SCM downloads.\n                        if newPath != path {\n                            observabilityScope\n                                .emit(error: \"custom dependency was retrieved at a different path: \\(newPath)\")\n                        }\n                    } else {\n                        observabilityScope.emit(error: \"invalid custom dependency container: \\(container)\")\n                    }\n\n                case .edited:\n                    // If some edited dependency has been removed, mark it as unedited.\n                    //\n                    // Note: We don't resolve the dependencies when unediting\n                    // here because we expect this method to be called as part\n                    // of some other resolve operation (i.e. resolve, update, etc).\n                    try await self.unedit(\n                        dependency: dependency,\n                        forceRemove: true,\n                        observabilityScope: observabilityScope\n                    )\n\n                    observabilityScope\n                        .emit(.editedDependencyMissing(packageName: dependency.packageRef.identity.description))\n\n                case .fileSystem:\n                    await self.state.remove(identity: dependency.packageRef.identity)\n                    try await self.state.save()\n                }\n            }\n        }\n    }\n\n    private func getFileSystem(\n        package: PackageReference,\n        state: Workspace.ManagedDependency.State,\n        observabilityScope: ObservabilityScope\n    ) async throws -> FileSystem? {\n        // Only custom containers may provide a file system.\n        guard self.customPackageContainerProvider != nil else {\n            return nil\n        }\n\n        switch state {\n        // File-system based dependencies do not provide a custom file system object.\n        case .fileSystem:\n            return nil\n        case .custom:\n            let container = try await withCheckedThrowingContinuation { continuation in\n                self.packageContainerProvider.getContainer(\n                    for: package,\n                    updateStrategy: .never,\n                    observabilityScope: observabilityScope,\n                    on: .sharedConcurrent,\n                    completion: {\n                        continuation.resume(with: $0)\n                    }\n                )\n            }\n            guard let customContainer = container as? CustomPackageContainer else {\n                observabilityScope.emit(error: \"invalid custom dependency container: \\(container)\")\n                return nil\n            }\n            return try customContainer.getFileSystem()\n        default:\n            observabilityScope.emit(error: \"invalid managed dependency state for custom dependency: \\(state)\")\n            return nil\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+PackageContainer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SourceControl\nimport TSCBasic\n\nimport class Basics.ObservabilityScope\nimport class Dispatch.DispatchQueue\nimport enum PackageFingerprint.FingerprintCheckingMode\nimport enum PackageGraph.ContainerUpdateStrategy\nimport protocol PackageGraph.PackageContainer\nimport protocol PackageGraph.PackageContainerProvider\nimport struct PackageModel.PackageReference\n\n// MARK: - Package container provider\n\nextension Workspace: PackageContainerProvider {\n    public func getContainer(\n        for package: PackageReference,\n        updateStrategy: ContainerUpdateStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> any PackageContainer {\n        switch package.kind {\n        // If the container is local, just create and return a local package container.\n        case .root, .fileSystem:\n            let container = try FileSystemPackageContainer(\n                package: package,\n                identityResolver: self.identityResolver,\n                dependencyMapper: self.dependencyMapper,\n                manifestLoader: self.manifestLoader,\n                currentToolsVersion: self.currentToolsVersion,\n                fileSystem: self.fileSystem,\n                observabilityScope: observabilityScope\n            )\n            return container\n        // Resolve the container using the repository manager.\n        case .localSourceControl, .remoteSourceControl:\n            let repositorySpecifier = try package.makeRepositorySpecifier()\n            let handle = try await self.repositoryManager.lookup(\n                package: package.identity,\n                repository: repositorySpecifier,\n                updateStrategy: updateStrategy.repositoryUpdateStrategy,\n                observabilityScope: observabilityScope\n            )\n\n            // Open the repository.\n            //\n            // FIXME: Do we care about holding this open for the lifetime of the container.\n            let repository = try await handle.open()\n            let result = try SourceControlPackageContainer(\n                package: package,\n                identityResolver: self.identityResolver,\n                dependencyMapper: self.dependencyMapper,\n                repositorySpecifier: repositorySpecifier,\n                repository: repository,\n                manifestLoader: self.manifestLoader,\n                currentToolsVersion: self.currentToolsVersion,\n                fingerprintStorage: self.fingerprints,\n                fingerprintCheckingMode: FingerprintCheckingMode\n                    .map(self.configuration.fingerprintCheckingMode),\n                observabilityScope: observabilityScope\n            )\n            return result\n        // Resolve the container using the registry\n        case .registry:\n            let container = RegistryPackageContainer(\n                package: package,\n                identityResolver: self.identityResolver,\n                dependencyMapper: self.dependencyMapper,\n                registryClient: self.registryClient,\n                manifestLoader: self.manifestLoader,\n                currentToolsVersion: self.currentToolsVersion,\n                observabilityScope: observabilityScope\n            )\n            return container\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Prebuilts.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport OrderedCollections\nimport PackageModel\n\nimport protocol TSCBasic.HashAlgorithm\nimport struct TSCBasic.SHA256\nimport struct TSCUtility.Version\n\n/// Delegate to notify clients about actions being performed by BinaryArtifactsDownloadsManage.\npublic protocol PrebuiltsManagerDelegate {\n    /// The workspace has started downloading a binary artifact.\n    func willDownloadPrebuilt(\n        for package: PackageIdentity,\n        from url: String,\n        fromCache: Bool\n    )\n    /// The workspace has finished downloading a binary artifact.\n    func didDownloadPrebuilt(\n        for package: PackageIdentity,\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    )\n    /// The workspace is downloading a binary artifact.\n    func downloadingPrebuilt(\n        for package: PackageIdentity,\n        from url: String,\n        bytesDownloaded: Int64,\n        totalBytesToDownload: Int64?\n    )\n    /// The workspace finished downloading all binary artifacts.\n    func didDownloadAllPrebuilts()\n}\n\nextension Workspace {\n    public struct PrebuiltsManifest: Codable {\n        public var libraries: [Library]\n\n        public struct Library: Identifiable, Codable {\n            public let name: String\n            public var checksum: String\n            public var products: [String]\n            public var includePath: [String]?\n\n            public var id: String { name }\n\n            public init(\n                name: String,\n                checksum: String,\n                products: [String] = [],\n                includePath: [RelativePath]? = nil\n            ) {\n                self.name = name\n                self.checksum = checksum\n                self.products = products\n                self.includePath = includePath?.map({ $0.pathString.replacingOccurrences(of: \"\\\\\", with: \"/\") })\n            }\n        }\n\n        public init(libraries: [Library] = []) {\n            self.libraries = libraries\n        }\n    }\n\n    public struct SignedPrebuiltsManifest: Codable {\n        public var manifest: PrebuiltsManifest\n        public var signature: ManifestSignature\n\n        public init(manifest: PrebuiltsManifest, signature: ManifestSignature) {\n            self.manifest = manifest\n            self.signature = signature\n        }\n    }\n\n    /// For simplified init in tests\n    public struct CustomPrebuiltsManager {\n        let swiftVersion: String\n        let httpClient: HTTPClient?\n        let archiver: Archiver?\n        let useCache: Bool?\n        let hostPlatform: PrebuiltsPlatform?\n        let rootCertPath: AbsolutePath?\n\n        public init(\n            swiftVersion: String,\n            httpClient: HTTPClient? = .none,\n            archiver: Archiver? = .none,\n            useCache: Bool? = .none,\n            hostPlatform: PrebuiltsPlatform? = nil,\n            rootCertPath: AbsolutePath? = nil\n        ) {\n            self.swiftVersion = swiftVersion\n            self.httpClient = httpClient\n            self.archiver = archiver\n            self.useCache = useCache\n            self.hostPlatform = hostPlatform\n            self.rootCertPath = rootCertPath\n        }\n    }\n\n    /// Provider of prebuilt binaries for packages. Currently only supports swift-syntax for macros.\n    public struct PrebuiltsManager: Cancellable {\n        public typealias Delegate = PrebuiltsManagerDelegate\n\n        private let fileSystem: FileSystem\n        private let authorizationProvider: AuthorizationProvider?\n        private let httpClient: HTTPClient\n        private let archiver: Archiver\n        private let scratchPath: AbsolutePath\n        private let cachePath: AbsolutePath?\n        private let delegate: Delegate?\n        private let hashAlgorithm: HashAlgorithm = SHA256()\n        private let prebuiltsDownloadURL: URL\n        private let rootCertPath: AbsolutePath?\n        private let customSwiftCompilerVersion: String?\n        let hostPlatform: PrebuiltsPlatform\n\n        init(\n            fileSystem: FileSystem,\n            hostPlatform: PrebuiltsPlatform,\n            authorizationProvider: AuthorizationProvider?,\n            scratchPath: AbsolutePath,\n            cachePath: AbsolutePath?,\n            customSwiftCompilerVersion: String?,\n            customHTTPClient: HTTPClient?,\n            customArchiver: Archiver?,\n            delegate: Delegate?,\n            prebuiltsDownloadURL: String?,\n            rootCertPath: AbsolutePath?\n        ) {\n            self.fileSystem = fileSystem\n            self.hostPlatform = hostPlatform\n            self.authorizationProvider = authorizationProvider\n            self.httpClient = customHTTPClient ?? HTTPClient()\n            self.customSwiftCompilerVersion = customSwiftCompilerVersion\n\n#if os(Linux)\n            self.archiver = customArchiver ?? TarArchiver(fileSystem: fileSystem)\n#else\n            self.archiver = customArchiver ?? ZipArchiver(fileSystem: fileSystem)\n#endif\n\n            self.scratchPath = scratchPath\n            self.cachePath = cachePath\n            self.delegate = delegate\n            if let prebuiltsDownloadURL, let url = URL(string: prebuiltsDownloadURL) {\n                self.prebuiltsDownloadURL = url\n            } else {\n                self.prebuiltsDownloadURL = URL(string: \"https://download.swift.org/prebuilts\")!\n            }\n            self.rootCertPath = rootCertPath\n\n            self.prebuiltPackages = [\n                // TODO: we should have this in a manifest somewhere, not hardcoded like this\n                .init(\n                    identity: .plain(\"swift-syntax\"),\n                    packageRefs: [\n                        .init(\n                            identity: .plain(\"swift-syntax\"),\n                            kind: .remoteSourceControl(\"https://github.com/swiftlang/swift-syntax.git\")\n                        ),\n                        // The old site that's being redirected but still in use.\n                        .init(\n                            identity: .plain(\"swift-syntax\"),\n                            kind: .remoteSourceControl(\"https://github.com/apple/swift-syntax.git\")\n                        ),\n                        .init(\n                            identity: .plain(\"swift-syntax\"),\n                            kind: .remoteSourceControl(\"git@github.com:swiftlang/swift-syntax.git\")\n                        ),\n                    ]\n                ),\n            ]\n        }\n\n        struct PrebuiltPackage {\n            let identity: PackageIdentity\n            let packageRefs: [PackageReference]\n        }\n\n        private let prebuiltPackages: [PrebuiltPackage]\n\n        fileprivate func findPrebuilts(packages: [PackageReference]) -> [PrebuiltPackage] {\n            var prebuilts: [PrebuiltPackage] = []\n            for packageRef in packages {\n                guard case let .remoteSourceControl(pkgURL) = packageRef.kind else {\n                    // Only support remote source control for now\n                    continue\n                }\n\n                if let prebuilt = prebuiltPackages.first(where: {\n                    $0.packageRefs.contains(where: {\n                        guard case let .remoteSourceControl(prebuiltURL) = $0.kind,\n                              $0.identity == packageRef.identity else {\n                            return false\n                        }\n\n                        if pkgURL == prebuiltURL {\n                            return true\n                        } else if !pkgURL.lastPathComponent.hasSuffix(\".git\") {\n                            // try with the git extension\n                            // TODO: Does this need to be in the PackageRef Equatable?\n                            let gitURL = SourceControlURL(pkgURL.absoluteString + \".git\")\n                            return gitURL == prebuiltURL\n                        } else {\n                            return false\n                        }\n                    })\n                }) {\n                    prebuilts.append(prebuilt)\n                }\n            }\n            return prebuilts\n        }\n\n        func prebuiltName(workspace: Workspace) throws -> String {\n            if let customSwiftCompilerVersion {\n                return \"\\(customSwiftCompilerVersion)\"\n            } else {\n                return try hostPlatform.prebuiltName(hostToolchain: workspace.hostToolchain)\n            }\n\n        }\n\n        func downloadManifest(\n            workspace: Workspace,\n            package: PrebuiltPackage,\n            version: Version,\n            observabilityScope: ObservabilityScope\n        ) async throws -> PrebuiltsManifest? {\n            let prebuiltName = try prebuiltName(workspace: workspace)\n            let manifestFile = \"\\(prebuiltName).json\"\n            let manifestPath = try RelativePath(validating: \"\\(package.identity)/\\(version)/\\(manifestFile)\")\n            let destination = scratchPath.appending(manifestPath)\n            let cacheDest = cachePath?.appending(manifestPath)\n\n            func loadManifest() async throws -> PrebuiltsManifest? {\n                do {\n                    let signedManifest = try JSONDecoder().decode(\n                        path: destination,\n                        fileSystem: fileSystem,\n                        as: SignedPrebuiltsManifest.self\n                    )\n\n                    // Check the signature\n                    // Ignore errors coming from the certificate loading, that will shutdown the build\n                    // instead of letting it continue with build from source.\n                    if let rootCertPath {\n                        try await withTemporaryDirectory(fileSystem: fileSystem) { tmpDir in\n                            try fileSystem.copy(from: rootCertPath, to: tmpDir.appending(rootCertPath.basename))\n                            let validator = ManifestSigning(trustedRootCertsDir: tmpDir, observabilityScope: ObservabilitySystem.NOOP)\n                            try await validator.validate(\n                                manifest: signedManifest.manifest,\n                                signature: signedManifest.signature,\n                                fileSystem: fileSystem\n                            )\n                        }.value\n                    } else {\n                        let validator = ManifestSigning(observabilityScope: ObservabilitySystem.NOOP)\n                        try await validator.validate(\n                            manifest: signedManifest.manifest,\n                            signature: signedManifest.signature,\n                            fileSystem: fileSystem\n                        )\n                    }\n\n                    return signedManifest.manifest\n                } catch {\n                    // redownload it\n                    observabilityScope.emit(\n                        info: \"Failed to decode prebuilt manifest\",\n                        underlyingError: error\n                    )\n                    try fileSystem.removeFileTree(destination)\n                    return nil\n                }\n            }\n\n            // Skip prebuilts if this file exists.\n            if let cachePath, fileSystem.exists(cachePath.appending(\"noprebuilts\")) {\n                return nil\n            }\n\n            if fileSystem.exists(destination), let manifest = try? await loadManifest() {\n                return manifest\n            } else if let cacheDest, fileSystem.exists(cacheDest) {\n                // Pull it out of the cache\n                try fileSystem.createDirectory(destination.parentDirectory, recursive: true)\n                try fileSystem.copy(from: cacheDest, to: destination)\n\n                if let manifest = try? await loadManifest() {\n                    return manifest\n                }\n            } else if fileSystem.exists(destination.parentDirectory) {\n                // We tried previously and were not able to find the manifest.\n                // Don't try again to avoid excessive server traffic\n                return nil\n            }\n\n            try fileSystem.createDirectory(destination.parentDirectory, recursive: true)\n\n            let manifestURL = self.prebuiltsDownloadURL.appending(\n                components: package.identity.description, version.description, manifestFile\n            )\n\n            if manifestURL.scheme == \"file\" {\n                let sourcePath = try AbsolutePath(validating: manifestURL.path)\n                if fileSystem.exists(sourcePath) {\n                    // simply copy it over\n                    try fileSystem.copy(from: sourcePath, to: destination)\n                } else {\n                    return nil\n                }\n            } else {\n                var headers = HTTPClientHeaders()\n                headers.add(name: \"Accept\", value: \"application/json\")\n                var request = HTTPClient.Request.download(\n                    url: manifestURL,\n                    headers: headers,\n                    fileSystem: self.fileSystem,\n                    destination: destination\n                )\n                request.options.authorizationProvider =\n                self.authorizationProvider?.httpAuthorizationHeader(for:)\n                request.options.retryStrategy = .exponentialBackoff(\n                    maxAttempts: 3,\n                    baseDelay: .milliseconds(50)\n                )\n                request.options.validResponseCodes = [200]\n\n                do {\n                    _ = try await self.httpClient.execute(request) { _, _ in\n                        // TODO: send to delegate\n                    }\n                } catch {\n                    observabilityScope.emit(\n                        info: \"Prebuilt \\(manifestFile)\",\n                        underlyingError: error\n                    )\n                    // Create an empty manifest so we don't keep trying to download it\n                    let manifest = PrebuiltsManifest(libraries: [])\n                    try? fileSystem.writeFileContents(destination, data: JSONEncoder().encode(manifest))\n                    return nil\n                }\n            }\n\n            if let manifest = try await loadManifest() {\n                // Cache the manifest\n                if let cacheDest {\n                    if fileSystem.exists(cacheDest) {\n                        try fileSystem.removeFileTree(cacheDest)\n                    }\n                    try fileSystem.createDirectory(cacheDest.parentDirectory, recursive: true)\n                    try fileSystem.copy(from: destination, to: cacheDest)\n                }\n\n                return manifest\n            } else {\n                return nil\n            }\n        }\n\n        func check(path: AbsolutePath, checksum: String) throws -> Bool {\n            let contents = try fileSystem.readFileContents(path)\n            let hash = hashAlgorithm.hash(contents).hexadecimalRepresentation\n            return hash == checksum\n        }\n\n        func downloadPrebuilt(\n            workspace: Workspace,\n            package: PrebuiltPackage,\n            version: Version,\n            library: PrebuiltsManifest.Library,\n            observabilityScope: ObservabilityScope\n        ) async throws -> AbsolutePath? {\n            let prebuiltName = try prebuiltName(workspace: workspace)\n            let artifactName = \"\\(prebuiltName)-\\(library.name)\"\n            let scratchDir = scratchPath.appending(components: package.identity.description, version.description)\n\n            let artifactDir = scratchDir.appending(artifactName)\n            guard !fileSystem.exists(artifactDir) else {\n                return artifactDir\n            }\n\n            let artifactFile = artifactName + (hostPlatform.os == .linux ? \".tar.gz\" : \".zip\")\n            let destination = scratchDir.appending(artifactFile)\n            let cacheFile = cachePath?.appending(components: package.identity.description, version.description, artifactFile)\n\n            let zipExists = fileSystem.exists(destination)\n            if try (!zipExists || !check(path: destination, checksum: library.checksum)) {\n                try fileSystem.createDirectory(destination.parentDirectory, recursive: true)\n\n                if let cacheFile, fileSystem.exists(cacheFile), try check(path: cacheFile, checksum: library.checksum) {\n                    // Copy over the cached file\n                    observabilityScope.emit(info: \"Using cached \\(artifactFile)\")\n                    try fileSystem.copy(from: cacheFile, to: destination)\n                } else {\n                    if zipExists {\n                        // Exists but failed checksum\n                        observabilityScope.emit(info: \"Prebuilt artifact \\(artifactFile) checksum mismatch, redownloading.\")\n                        try fileSystem.removeFileTree(destination)\n                    }\n\n                    // Download\n                    let artifactURL = self.prebuiltsDownloadURL.appending(\n                        components: package.identity.description, version.description, artifactFile\n                    )\n\n                    let fetchStart = DispatchTime.now()\n                    if artifactURL.scheme == \"file\" {\n                        let artifactPath = try AbsolutePath(validating: artifactURL.path)\n                        if fileSystem.exists(artifactPath) {\n                            self.delegate?.willDownloadPrebuilt(\n                                for: package.identity,\n                                from: artifactURL.absoluteString,\n                                fromCache: true\n                            )\n                            try fileSystem.copy(from: artifactPath, to: destination)\n                            self.delegate?.didDownloadPrebuilt(\n                                for: package.identity,\n                                from: artifactURL.absoluteString,\n                                result: .success((destination, false)),\n                                duration: fetchStart.distance(to: .now())\n                            )\n                        } else {\n                            return nil\n                        }\n                    } else {\n                        var headers = HTTPClientHeaders()\n                        headers.add(name: \"Accept\", value: \"application/octet-stream\")\n                        var request = HTTPClient.Request.download(\n                            url: artifactURL,\n                            headers: headers,\n                            fileSystem: self.fileSystem,\n                            destination: destination\n                        )\n                        request.options.authorizationProvider =\n                        self.authorizationProvider?.httpAuthorizationHeader(for:)\n                        request.options.retryStrategy = .exponentialBackoff(\n                            maxAttempts: 3,\n                            baseDelay: .milliseconds(50)\n                        )\n                        request.options.validResponseCodes = [200]\n\n                        self.delegate?.willDownloadPrebuilt(\n                            for: package.identity,\n                            from: artifactURL.absoluteString,\n                            fromCache: false\n                        )\n                        do {\n                            _ = try await self.httpClient.execute(request) {\n                                bytesDownloaded,\n                                totalBytesToDownload in\n                                self.delegate?.downloadingPrebuilt(\n                                    for: package.identity,\n                                    from: artifactURL.absoluteString,\n                                    bytesDownloaded: bytesDownloaded,\n                                    totalBytesToDownload: totalBytesToDownload\n                                )\n                            }\n                        } catch {\n                            observabilityScope.emit(\n                                info: \"Prebuilt artifact \\(artifactFile)\",\n                                underlyingError: error\n                            )\n                            self.delegate?.didDownloadPrebuilt(\n                                for: package.identity,\n                                from: artifactURL.absoluteString,\n                                result: .failure(error),\n                                duration: fetchStart.distance(to: .now())\n                            )\n                            return nil\n                        }\n\n                        // Check the checksum\n                        if try !check(path: destination, checksum: library.checksum) {\n                            let errorString =\n                                \"Prebuilt artifact \\(artifactFile) checksum mismatch\"\n                            observabilityScope.emit(info: errorString)\n                            self.delegate?.didDownloadPrebuilt(\n                                for: package.identity,\n                                from: artifactURL.absoluteString,\n                                result: .failure(StringError(errorString)),\n                                duration: fetchStart.distance(to: .now())\n                            )\n                            return nil\n                        }\n\n                        self.delegate?.didDownloadPrebuilt(\n                            for: package.identity,\n                            from: artifactURL.absoluteString,\n                            result: .success((destination, false)),\n                            duration: fetchStart.distance(to: .now())\n                        )\n                    }\n\n                    if let cacheFile {\n                        // Cache the zip file\n                        if fileSystem.exists(cacheFile) {\n                            try fileSystem.removeFileTree(cacheFile)\n                        } else {\n                            try fileSystem.createDirectory(cacheFile.parentDirectory, recursive: true)\n                        }\n                        try fileSystem.copy(from: destination, to: cacheFile)\n                    }\n                }\n            }\n\n            // Extract\n            if fileSystem.exists(artifactDir) {\n                try fileSystem.removeFileTree(artifactDir)\n            }\n            try fileSystem.createDirectory(artifactDir, recursive: true)\n            try await archiver.extract(from: destination, to: artifactDir)\n\n            observabilityScope.emit(\n                info: \"Prebuilt artifact \\(artifactFile) downloaded\"\n            )\n\n            return artifactDir\n        }\n\n        public func cancel(deadline: DispatchTime) throws {\n            if let cancellableArchiver = self.archiver as? Cancellable {\n                try cancellableArchiver.cancel(deadline: deadline)\n            }\n        }\n    }\n}\n\nextension Workspace {\n    func updatePrebuilts(\n        manifests: DependencyManifests,\n        addedOrUpdatedPackages: [PackageReference],\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        guard let prebuiltsManager else {\n            // Disabled\n            return\n        }\n\n        let addedPrebuilts = ManagedPrebuilts()\n\n        for prebuilt in prebuiltsManager.findPrebuilts(packages: try manifests.requiredPackages) {\n            guard\n                let manifest = manifests.allDependencyManifests[prebuilt.identity],\n                let packageVersion = manifest.manifest.version,\n                let prebuiltManifest = try await prebuiltsManager\n                    .downloadManifest(\n                        workspace: self,\n                        package: prebuilt,\n                        version: packageVersion,\n                        observabilityScope: observabilityScope\n                    )\n            else {\n                continue\n            }\n\n            let hostPlatform = prebuiltsManager.hostPlatform\n\n            for library in prebuiltManifest.libraries {\n                if let path = try await prebuiltsManager\n                    .downloadPrebuilt(\n                        workspace: self,\n                        package: prebuilt,\n                        version: packageVersion,\n                        library: library,\n                        observabilityScope: observabilityScope\n                    )\n                {\n                    // Add to workspace state\n                    let checkoutPath = self.location.repositoriesCheckoutsDirectory\n                        .appending(component: prebuilt.identity.description)\n                    let managedPrebuilt = ManagedPrebuilt(\n                        identity: prebuilt.identity,\n                        version: packageVersion,\n                        libraryName: library.name,\n                        path: path,\n                        checkoutPath: checkoutPath,\n                        products: library.products,\n                        includePath: try library.includePath?.map({ try RelativePath(validating: $0) }),\n                        cModules: []\n                    )\n                    addedPrebuilts.add(managedPrebuilt)\n                    await self.state.prebuilts.add(managedPrebuilt)\n                }\n            }\n        }\n\n        for prebuilt in await self.state.prebuilts.prebuilts {\n            if !addedPrebuilts.contains(where: { $0.identity == prebuilt.identity && $0.version == prebuilt.version }) {\n                await self.state.prebuilts.remove(packageIdentity: prebuilt.identity, targetName: prebuilt.libraryName)\n            }\n        }\n\n        try await self.state.save()\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Registry.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\n\nimport struct Basics.AbsolutePath\nimport protocol Basics.FileSystem\nimport struct Basics.InternalError\nimport class Basics.ObservabilityScope\nimport struct Basics.SourceControlURL\nimport class Basics.ThreadSafeKeyValueStore\nimport class PackageGraph.ResolvedPackagesStore\nimport protocol PackageLoading.ManifestLoaderProtocol\nimport protocol PackageModel.DependencyMapper\nimport protocol PackageModel.IdentityResolver\nimport class PackageModel.Manifest\nimport enum PackageModel.PackageDependency\nimport struct PackageModel.PackageIdentity\nimport struct PackageModel.PackageReference\nimport struct PackageModel.TargetDescription\nimport struct PackageModel.ToolsVersion\nimport class PackageRegistry.RegistryClient\nimport struct TSCUtility.Version\n\n// Need to import the whole module to get access to `+` operator on `DispatchTimeInterval`\nimport Dispatch\n\nextension Workspace {\n    // the goal of this code is to help align dependency identities across source control and registry origins\n    // the issue this solves is that dependencies will have different identities across the origins\n    // for example, source control based dependency on http://github.com/apple/swift-nio would have an identifier of\n    // \"swift-nio\"\n    // while in the registry, the same package will [likely] have an identifier of \"apple.swift-nio\"\n    // since there is not generally fire sure way to translate one system to the other (urls can vary widely, so the\n    // best we would be able to do is guess)\n    // what this code does is query the registry of it \"knows\" what the registry identity of URL is, and then use the\n    // registry identity instead of the URL bases one\n    // the code also supports a \"full swizzle\" mode in which it _replaces_ the source control dependency with a registry\n    // one which encourages the transition\n    // from source control based dependencies to registry based ones\n\n    // TODO:\n    // 1. handle mixed situation when some versions on the registry but some on source control. we need a second lookup\n    // to make sure the version exists\n    // 2. handle registry returning multiple identifiers, how do we choose the right one?\n    struct RegistryAwareManifestLoader: ManifestLoaderProtocol {\n        private let underlying: ManifestLoaderProtocol\n        private let registryClient: RegistryClient\n        private let transformationMode: TransformationMode\n\n        private let cacheTTL = DispatchTimeInterval.seconds(300) // 5m\n        private let identityLookupCache = ThreadSafeKeyValueStore<\n            SourceControlURL,\n            (result: Result<PackageIdentity?, Error>, expirationTime: DispatchTime)\n        >()\n\n        init(\n            underlying: ManifestLoaderProtocol,\n            registryClient: RegistryClient,\n            transformationMode: TransformationMode\n        ) {\n            self.underlying = underlying\n            self.registryClient = registryClient\n            self.transformationMode = transformationMode\n        }\n\n        func load(\n            manifestPath: AbsolutePath,\n            manifestToolsVersion: ToolsVersion,\n            packageIdentity: PackageIdentity,\n            packageKind: PackageReference.Kind,\n            packageLocation: String,\n            packageVersion: (version: Version?, revision: String?)?,\n            identityResolver: any IdentityResolver,\n            dependencyMapper: any DependencyMapper,\n            fileSystem: any FileSystem,\n            observabilityScope: ObservabilityScope,\n            delegateQueue: DispatchQueue\n        ) async throws -> Manifest {\n            let manifest = try await self.underlying.load(\n                manifestPath: manifestPath,\n                manifestToolsVersion: manifestToolsVersion,\n                packageIdentity: packageIdentity,\n                packageKind: packageKind,\n                packageLocation: packageLocation,\n                packageVersion: packageVersion,\n                identityResolver: identityResolver,\n                dependencyMapper: dependencyMapper,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope,\n                delegateQueue: delegateQueue\n            )\n            return try await self.transformSourceControlDependenciesToRegistry(\n                manifest: manifest,\n                transformationMode: transformationMode,\n                observabilityScope: observabilityScope\n            )\n        }\n\n        func resetCache(observabilityScope: ObservabilityScope) async {\n            await self.underlying.resetCache(observabilityScope: observabilityScope)\n        }\n\n        func purgeCache(observabilityScope: ObservabilityScope) async {\n            await self.underlying.purgeCache(observabilityScope: observabilityScope)\n        }\n\n        private func transformSourceControlDependenciesToRegistry(\n            manifest: Manifest,\n            transformationMode: TransformationMode,\n            observabilityScope: ObservabilityScope\n        ) async throws -> Manifest {\n            var transformations = [PackageDependency: PackageIdentity]()\n\n            try await withThrowingTaskGroup(of: (PackageDependency, PackageIdentity?).self) { group in\n                for dependency in manifest.dependencies {\n                    if case .sourceControl(let settings) = dependency, case .remote(let url) = settings.location {\n                        group.addTask {\n                            do {\n                                let identity = try await self.mapRegistryIdentity(\n                                    url: url,\n                                    observabilityScope: observabilityScope\n                                )\n                                return (dependency, identity)\n                            } catch {\n                                // do not raise error, only report it as warning\n                                observabilityScope.emit(\n                                    warning: \"failed querying registry identity for '\\(url)'\",\n                                    underlyingError: error\n                                )\n                                return (dependency, nil)\n                            }\n                        }\n                    }\n                }\n\n                // Collect the results from the group\n                for try await (dependency, identity) in group {\n                    if let identity {\n                        transformations[dependency] = identity\n                    }\n                }\n            }\n\n            // update the manifest with the transformed dependencies\n            let updatedManifest = try self.transformManifest(\n                manifest: manifest,\n                transformations: transformations,\n                transformationMode: transformationMode,\n                observabilityScope: observabilityScope\n            )\n\n            return updatedManifest\n        }\n\n        private func transformManifest(\n            manifest: Manifest,\n            transformations: [PackageDependency: PackageIdentity],\n            transformationMode: TransformationMode,\n            observabilityScope: ObservabilityScope\n        ) throws -> Manifest {\n            var targetDependencyPackageNameTransformations = [String: String]()\n\n            var modifiedDependencies = [PackageDependency]()\n            for dependency in manifest.dependencies {\n                var modifiedDependency = dependency\n                if let registryIdentity = transformations[dependency] {\n                    guard case .sourceControl(let settings) = dependency, case .remote = settings.location else {\n                        // an implementation mistake\n                        throw InternalError(\"unexpected non-source-control dependency: \\(dependency)\")\n                    }\n                    switch transformationMode {\n                    case .identity:\n                        // we replace the *identity* of the dependency in order to align the identities\n                        // and de-dupe across source control and registry origins\n                        observabilityScope\n                            .emit(\n                                info: \"adjusting '\\(dependency.locationString)' identity to registry identity of '\\(registryIdentity)'.\"\n                            )\n                        modifiedDependency = .sourceControl(\n                            identity: registryIdentity,\n                            nameForTargetDependencyResolutionOnly: settings.nameForTargetDependencyResolutionOnly,\n                            location: settings.location,\n                            requirement: settings.requirement,\n                            productFilter: settings.productFilter,\n                            traits: settings.traits\n                        )\n                    case .swizzle:\n                        // we replace the *entire* source control dependency with a registry one\n                        // this helps de-dupe across source control and registry dependencies\n                        // and also encourages use of registry over source control\n                        switch settings.requirement {\n                        case .exact, .range:\n                            let requirement = try settings.requirement.asRegistryRequirement()\n                            observabilityScope\n                                .emit(\n                                    info: \"swizzling '\\(dependency.locationString)' with registry dependency '\\(registryIdentity)'.\"\n                                )\n                            targetDependencyPackageNameTransformations[dependency\n                                .nameForModuleDependencyResolutionOnly.lowercased()] = registryIdentity.description\n                            modifiedDependency = .registry(\n                                identity: registryIdentity,\n                                requirement: requirement,\n                                productFilter: settings.productFilter,\n                                traits: settings.traits\n                            )\n                        case .branch, .revision:\n                            // branch and revision dependencies are not supported by the registry\n                            // in such case, the best we can do is to replace the *identity* of the\n                            // source control dependency in order to align the identities\n                            // and de-dupe across source control and registry origins\n                            observabilityScope\n                                .emit(\n                                    info: \"adjusting '\\(dependency.locationString)' identity to registry identity of '\\(registryIdentity)'.\"\n                                )\n                            modifiedDependency = .sourceControl(\n                                identity: registryIdentity,\n                                nameForTargetDependencyResolutionOnly: settings.nameForTargetDependencyResolutionOnly,\n                                location: settings.location,\n                                requirement: settings.requirement,\n                                productFilter: settings.productFilter,\n                                traits: settings.traits\n                            )\n                        }\n                    }\n                }\n                modifiedDependencies.append(modifiedDependency)\n            }\n\n            var modifiedTargets = manifest.targets\n            if !transformations.isEmpty {\n                modifiedTargets = []\n                for target in manifest.targets {\n                    var modifiedDependencies = [TargetDescription.Dependency]()\n                    for dependency in target.dependencies {\n                        var modifiedDependency = dependency\n                        switch dependency {\n                        case .product(\n                            name: let name,\n                            package: let packageName,\n                            moduleAliases: let moduleAliases,\n                            condition: let condition\n                        ):\n                            if let packageName,\n                               // makes sure we use the updated package name for target based dependencies\n                               let modifiedPackageName =\n                               targetDependencyPackageNameTransformations[packageName.lowercased()]\n                            {\n                                modifiedDependency = .product(\n                                    name: name,\n                                    package: modifiedPackageName,\n                                    moduleAliases: moduleAliases,\n                                    condition: condition\n                                )\n                            }\n                        case .byName(name: let packageName, condition: let condition):\n                            if let modifiedPackageName =\n                                targetDependencyPackageNameTransformations[packageName.lowercased()]\n                            {\n                                modifiedDependency = .product(\n                                    name: packageName,\n                                    package: modifiedPackageName,\n                                    moduleAliases: [:],\n                                    condition: condition\n                                )\n                            }\n                        case .target:\n                            break\n                        }\n                        modifiedDependencies.append(modifiedDependency)\n                    }\n\n                    try modifiedTargets.append(\n                        TargetDescription(\n                            name: target.name,\n                            dependencies: modifiedDependencies,\n                            path: target.path,\n                            url: target.url,\n                            exclude: target.exclude,\n                            sources: target.sources,\n                            resources: target.resources,\n                            publicHeadersPath: target.publicHeadersPath,\n                            type: target.type,\n                            packageAccess: target.packageAccess,\n                            pkgConfig: target.pkgConfig,\n                            providers: target.providers,\n                            pluginCapability: target.pluginCapability,\n                            settings: target.settings,\n                            checksum: target.checksum,\n                            pluginUsages: target.pluginUsages\n                        )\n                    )\n                }\n            }\n\n            let modifiedManifest = Manifest(\n                displayName: manifest.displayName,\n                packageIdentity: manifest.packageIdentity,\n                path: manifest.path,\n                packageKind: manifest.packageKind,\n                packageLocation: manifest.packageLocation,\n                defaultLocalization: manifest.defaultLocalization,\n                platforms: manifest.platforms,\n                version: manifest.version,\n                revision: manifest.revision,\n                toolsVersion: manifest.toolsVersion,\n                pkgConfig: manifest.pkgConfig,\n                providers: manifest.providers,\n                cLanguageStandard: manifest.cLanguageStandard,\n                cxxLanguageStandard: manifest.cxxLanguageStandard,\n                swiftLanguageVersions: manifest.swiftLanguageVersions,\n                dependencies: modifiedDependencies,\n                products: manifest.products,\n                targets: modifiedTargets,\n                traits: manifest.traits,\n                pruneDependencies: manifest.pruneDependencies\n            )\n\n            return modifiedManifest\n        }\n\n        private func mapRegistryIdentity(\n            url: SourceControlURL,\n            observabilityScope: ObservabilityScope\n        ) async throws -> PackageIdentity? {\n            if let cached = self.identityLookupCache[url], cached.expirationTime > .now() {\n                switch cached.result {\n                case .success(let identity):\n                    return identity;\n                case .failure:\n                    // server error, do not try again\n                    return nil\n                }\n            }\n\n            do {\n                let identities = try await self.registryClient.lookupIdentities(\n                    scmURL: url,\n                    observabilityScope: observabilityScope\n                )\n                let identity = identities.sorted().first\n                self.identityLookupCache[url] = (result: .success(identity), expirationTime: .now() + self.cacheTTL)\n                return identity\n            } catch {\n                self.identityLookupCache[url] = (result: .failure(error), expirationTime: .now() + self.cacheTTL)\n                throw error\n            }\n        }\n\n        enum TransformationMode {\n            case identity\n            case swizzle\n\n            init?(_ seed: WorkspaceConfiguration.SourceControlToRegistryDependencyTransformation) {\n                switch seed {\n                case .identity:\n                    self = .identity\n                case .swizzle:\n                    self = .swizzle\n                case .disabled:\n                    return nil\n                }\n            }\n        }\n    }\n}\n\nextension PackageDependency.SourceControl.Requirement {\n    fileprivate func asRegistryRequirement() throws -> PackageDependency.Registry.Requirement {\n        switch self {\n        case .range(let versions):\n            return .range(versions)\n        case .exact(let version):\n            return .exact(version)\n        case .branch, .revision:\n            throw InternalError(\"invalid source control to registry requirement transformation\")\n        }\n    }\n}\n\n// MARK: - Registry Source archive management\n\nextension Workspace {\n    func downloadRegistryArchive(\n        package: PackageReference,\n        at version: Version,\n        observabilityScope: ObservabilityScope\n    ) async throws -> AbsolutePath {\n        let downloadPath = try await self.registryDownloadsManager.lookup(\n            package: package.identity,\n            version: version,\n            observabilityScope: observabilityScope\n        )\n\n        // Record the new state.\n        observabilityScope.emit(\n            debug: \"adding '\\(package.identity)' (\\(package.locationString)) to managed dependencies\",\n            metadata: package.diagnosticsMetadata\n        )\n        try await self.state.add(\n            dependency: .registryDownload(\n                packageRef: package,\n                version: version,\n                subpath: downloadPath.relative(to: self.location.registryDownloadDirectory)\n            )\n        )\n        try await self.state.save()\n\n        return downloadPath\n    }\n\n    func downloadRegistryArchive(\n        package: PackageReference,\n        at resolutionState: ResolvedPackagesStore.ResolutionState,\n        observabilityScope: ObservabilityScope\n    ) async throws -> AbsolutePath {\n        switch resolutionState {\n        case .version(let version, _):\n            return try await self.downloadRegistryArchive(\n                package: package,\n                at: version,\n                observabilityScope: observabilityScope\n            )\n        default:\n            throw InternalError(\"invalid resolution state: \\(resolutionState)\")\n        }\n    }\n\n    func removeRegistryArchive(for dependency: ManagedDependency) throws {\n        guard case .registryDownload = dependency.state else {\n            throw InternalError(\"cannot remove source archive for \\(dependency) with state \\(dependency.state)\")\n        }\n\n        let downloadPath = self.location.registryDownloadSubdirectory(for: dependency)\n        try self.fileSystem.removeFileTree(downloadPath)\n\n        // remove the local copy\n        try registryDownloadsManager.remove(package: dependency.packageRef.identity)\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+ResolvedPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SourceControl\n\nimport class Basics.ObservabilityScope\nimport class PackageGraph.ResolvedPackagesStore\nimport struct PackageModel.PackageReference\nimport struct PackageModel.ToolsVersion\nimport struct TSCUtility.Version\n\nextension Workspace {\n    /// Saves all of the current managed dependencies at their checkout state in `Package.resolved` file.\n    func saveResolvedFile(\n        resolvedPackagesStore: ResolvedPackagesStore,\n        dependencyManifests: DependencyManifests,\n        originHash: String,\n        rootManifestsMinimumToolsVersion: ToolsVersion,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        var dependenciesToSaveAsResolved = [ManagedDependency]()\n        let requiredDependencies = try dependencyManifests.requiredPackages.filter(\\.kind.isResolvable)\n        for dependency in requiredDependencies {\n            if let managedDependency = await self.state.dependencies[comparingLocation: dependency] {\n                dependenciesToSaveAsResolved.append(managedDependency)\n            } else if let managedDependency = await self.state.dependencies[dependency.identity] {\n                observabilityScope\n                    .emit(\n                        info: \"required dependency '\\(dependency.identity)' from '\\(dependency.locationString)' was not found in managed dependencies, using alternative location '\\(managedDependency.packageRef.locationString)' instead\"\n                    )\n                dependenciesToSaveAsResolved.append(ManagedDependency(packageRef: dependency, state: managedDependency.state, subpath: managedDependency.subpath))\n            } else {\n                observabilityScope\n                    .emit(\n                        warning: \"required dependency '\\(dependency.identity)' from '\\(dependency.locationString)' was not found in managed dependencies and will not be recorded in resolved file\"\n                    )\n            }\n        }\n\n        // try to load the `Package.resolved` store from disk so we can compare for any changes\n        // this is needed as we want to avoid re-writing the resolved files unless absolutely necessary\n        var needsUpdate = false\n        if let persistedResolvedPackagesStore = try? self.resolvedPackagesStore.load() {\n            // compare for any differences between the existing state and the stored one\n            // subtle changes between versions of SwiftPM could treat URLs differently\n            // in which case we don't want to cause unnecessary churn\n            if dependenciesToSaveAsResolved.count != persistedResolvedPackagesStore.resolvedPackages.count {\n                needsUpdate = true\n            } else {\n                for dependency in dependenciesToSaveAsResolved {\n                    if let resolvedPackage = persistedResolvedPackagesStore.resolvedPackages[comparingLocation: dependency.packageRef] {\n                        if resolvedPackage.state != ResolvedPackagesStore.ResolvedPackage(dependency)?.state {\n                            needsUpdate = true\n                            break\n                        }\n                    } else {\n                        needsUpdate = true\n                        break\n                    }\n                }\n            }\n        } else {\n            needsUpdate = true\n        }\n\n        // exist early is there is nothing to do\n        if !needsUpdate {\n            return\n        }\n\n        // reset the `Package.resolved` store and start saving the required dependencies.\n        resolvedPackagesStore.reset()\n        for dependency in dependenciesToSaveAsResolved {\n            resolvedPackagesStore.add(dependency)\n        }\n\n        observabilityScope.trap {\n            try resolvedPackagesStore.saveState(\n                toolsVersion: rootManifestsMinimumToolsVersion,\n                originHash: originHash\n            )\n        }\n\n        // Ask resolved file watcher to update its value so we don't fire\n        // an extra event if the file was modified by us.\n        self.resolvedFileWatcher?.updateValue()\n    }\n\n    /// Watch the Package.resolved for changes.\n    ///\n    /// This is useful if clients want to be notified when the Package.resolved\n    /// file is changed *outside* of libSwiftPM operations. For example, as part\n    /// of a git operation.\n    public func watchResolvedFile() throws {\n        // Return if we're already watching it.\n        guard self.resolvedFileWatcher == nil else { return }\n        self.resolvedFileWatcher = try ResolvedFileWatcher(\n            resolvedFile: self.location.resolvedVersionsFile\n        ) { [weak self] in\n            self?.delegate?.resolvedFileChanged()\n        }\n    }\n}\n\nextension ResolvedPackagesStore {\n    /// Add a managed dependency at its checkout state as resolved.\n    ///\n    /// This method does nothing if the dependency is in edited state.\n    func add(_ dependency: Workspace.ManagedDependency) {\n        if let resolvedPackage = ResolvedPackagesStore.ResolvedPackage(dependency) {\n            self.add(resolvedPackage)\n        }\n    }\n}\n\nextension ResolvedPackagesStore.ResolvedPackage {\n    fileprivate init?(_ dependency: Workspace.ManagedDependency) {\n        switch dependency.state {\n        case .sourceControlCheckout(.version(let version, let revision)):\n            self.init(\n                packageRef: dependency.packageRef,\n                state: .version(version, revision: revision.identifier)\n            )\n        case .sourceControlCheckout(.branch(let branch, let revision)):\n            self.init(\n                packageRef: dependency.packageRef,\n                state: .branch(name: branch, revision: revision.identifier)\n            )\n        case .sourceControlCheckout(.revision(let revision)):\n            self.init(\n                packageRef: dependency.packageRef,\n                state: .revision(revision.identifier)\n            )\n        case .registryDownload(let version):\n            self.init(\n                packageRef: dependency.packageRef,\n                state: .version(version, revision: .none)\n            )\n        case .edited, .fileSystem, .custom:\n            // NOOP\n            return nil\n        }\n    }\n}\n\nextension PackageReference.Kind {\n    var isResolvable: Bool {\n        switch self {\n        case .remoteSourceControl, .localSourceControl, .registry:\n            return true\n        default:\n            return false\n        }\n    }\n}\n\nextension ResolvedPackagesStore.ResolutionState {\n    func equals(_ checkoutState: CheckoutState) -> Bool {\n        switch (self, checkoutState) {\n        case (.version(let lversion, let lrevision), .version(let rversion, let rrevision)):\n            return lversion == rversion && lrevision == rrevision.identifier\n        case (.branch(let lbranch, let lrevision), .branch(let rbranch, let rrevision)):\n            return lbranch == rbranch && lrevision == rrevision.identifier\n        case (.revision(let lrevision), .revision(let rrevision)):\n            return lrevision == rrevision.identifier\n        default:\n            return false\n        }\n    }\n\n    func equals(_: Version) -> Bool {\n        switch self {\n        case .version(let version, _):\n            return version == version\n        default:\n            return false\n        }\n    }\n}\n\nextension ResolvedPackagesStore.ResolvedPackages {\n    subscript(comparingLocation package: PackageReference) -> ResolvedPackagesStore.ResolvedPackage? {\n        if let resolvedPackage = self[package.identity], resolvedPackage.packageRef.equalsIncludingLocation(package) {\n            return resolvedPackage\n        }\n        return .none\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Signing.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport enum PackageFingerprint.FingerprintCheckingMode\nimport struct PackageGraph.ModulesGraph\nimport struct PackageModel.PackageIdentity\nimport struct PackageModel.RegistryReleaseMetadata\nimport enum PackageSigning.SigningEntityCheckingMode\n\nextension FingerprintCheckingMode {\n    static func map(_ checkingMode: WorkspaceConfiguration.CheckingMode) -> FingerprintCheckingMode {\n        switch checkingMode {\n        case .strict:\n            return .strict\n        case .warn:\n            return .warn\n        }\n    }\n}\n\nextension SigningEntityCheckingMode {\n    static func map(_ checkingMode: WorkspaceConfiguration.CheckingMode) -> SigningEntityCheckingMode {\n        switch checkingMode {\n        case .strict:\n            return .strict\n        case .warn:\n            return .warn\n        }\n    }\n}\n\n// MARK: - Signatures\n\nextension Workspace {\n    func validateSignatures(\n        packageGraph: ModulesGraph,\n        expectedSigningEntities: [PackageIdentity: RegistryReleaseMetadata.SigningEntity]\n    ) throws {\n        try expectedSigningEntities.forEach { identity, expectedSigningEntity in\n            if let package = packageGraph.package(for: identity) {\n                guard let actualSigningEntity = package.registryMetadata?.signature?.signedBy else {\n                    throw SigningError.unsigned(package: identity, expected: expectedSigningEntity)\n                }\n                if actualSigningEntity != expectedSigningEntity {\n                    throw SigningError.mismatchedSigningEntity(\n                        package: identity,\n                        expected: expectedSigningEntity,\n                        actual: actualSigningEntity\n                    )\n                }\n            } else {\n                guard let mirror = self.mirrors.mirror(for: identity.description) else {\n                    throw SigningError.expectedIdentityNotFound(package: identity)\n                }\n                let mirroredIdentity = PackageIdentity.plain(mirror)\n                guard mirroredIdentity.isRegistry else {\n                    throw SigningError.expectedSignedMirroredToSourceControl(\n                        package: identity,\n                        expected: expectedSigningEntity\n                    )\n                }\n                guard let package = packageGraph.package(for: mirroredIdentity) else {\n                    // Unsure if this case is reachable in practice.\n                    throw SigningError.expectedIdentityNotFound(package: identity)\n                }\n                guard let actualSigningEntity = package.registryMetadata?.signature?.signedBy else {\n                    throw SigningError.unsigned(package: identity, expected: expectedSigningEntity)\n                }\n                if actualSigningEntity != expectedSigningEntity {\n                    throw SigningError.mismatchedSigningEntity(\n                        package: identity,\n                        expected: expectedSigningEntity,\n                        actual: actualSigningEntity\n                    )\n                }\n            }\n        }\n    }\n\n    public enum SigningError: Swift.Error {\n        case expectedIdentityNotFound(package: PackageIdentity)\n        case expectedSignedMirroredToSourceControl(\n            package: PackageIdentity,\n            expected: RegistryReleaseMetadata.SigningEntity\n        )\n        case mismatchedSigningEntity(\n            package: PackageIdentity,\n            expected: RegistryReleaseMetadata.SigningEntity,\n            actual: RegistryReleaseMetadata.SigningEntity\n        )\n        case unsigned(package: PackageIdentity, expected: RegistryReleaseMetadata.SigningEntity)\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+SourceControl.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TSCBasic\n\nimport struct Basics.AbsolutePath\nimport struct Basics.InternalError\nimport class Basics.ObservabilityScope\nimport struct Dispatch.DispatchTime\nimport enum PackageGraph.PackageRequirement\nimport class PackageGraph.ResolvedPackagesStore\nimport struct PackageModel.PackageReference\nimport struct SourceControl.Revision\nimport struct TSCUtility.Version\n\n// FIXME: this mixes quite a bit of workspace logic with repository specific one\n// need to better separate the concerns\nextension Workspace {\n    /// Create a local clone of the given `repository` checked out to `checkoutState`.\n    ///\n    /// If an existing clone is present, the repository will be reset to the\n    /// requested revision, if necessary.\n    ///\n    /// - Parameters:\n    ///   - package: The package to clone.\n    ///   - checkoutState: The state to check out.\n    /// - Returns: The path of the local repository.\n    /// - Throws: If the operation could not be satisfied.\n    func checkoutRepository(\n        package: PackageReference,\n        at checkoutState: CheckoutState,\n        observabilityScope: ObservabilityScope\n    ) async throws -> AbsolutePath {\n        let repository = try package.makeRepositorySpecifier()\n\n        // first fetch the repository\n        let checkoutPath = try await self.fetchRepository(\n            package: package,\n            at: checkoutState.revision,\n            observabilityScope: observabilityScope\n        )\n\n        // Check out the given revision.\n        let workingCopy = try await self.repositoryManager.openWorkingCopy(at: checkoutPath)\n\n        // Inform the delegate that we're about to start.\n        delegate?.willCheckOut(\n            package: package.identity,\n            repository: repository.location.description,\n            revision: checkoutState.description,\n            at: checkoutPath\n        )\n        let start = DispatchTime.now()\n\n        // Do mutable-immutable dance because checkout operation modifies the disk state.\n        try fileSystem.chmod(.userWritable, path: checkoutPath, options: [.recursive, .onlyFiles])\n        try workingCopy.checkout(revision: checkoutState.revision)\n        try? fileSystem.chmod(.userUnWritable, path: checkoutPath, options: [.recursive, .onlyFiles])\n\n        // Record the new state.\n        observabilityScope.emit(\n            debug: \"adding '\\(package.identity)' (\\(package.locationString)) to managed dependencies\",\n            metadata: package.diagnosticsMetadata\n        )\n        try await self.state.add(\n            dependency: .sourceControlCheckout(\n                packageRef: package,\n                state: checkoutState,\n                subpath: checkoutPath.relative(to: self.location.repositoriesCheckoutsDirectory)\n            )\n        )\n        try await self.state.save()\n\n        // Inform the delegate that we're done.\n        let duration = start.distance(to: .now())\n        delegate?.didCheckOut(\n            package: package.identity,\n            repository: repository.location.description,\n            revision: checkoutState.description,\n            at: checkoutPath,\n            duration: duration\n        )\n        observabilityScope\n            .emit(debug: \"`\\(repository.location.description)` checked out at \\(checkoutState.debugDescription)\")\n\n        return checkoutPath\n    }\n\n    func checkoutRepository(\n        package: PackageReference,\n        at resolutionStater: ResolvedPackagesStore.ResolutionState,\n        observabilityScope: ObservabilityScope\n    ) async throws -> AbsolutePath {\n        switch resolutionStater {\n        case .version(let version, revision: let revision) where revision != nil:\n            return try await self.checkoutRepository(\n                package: package,\n                at: .version(version, revision: .init(identifier: revision!)), // nil checked above\n                observabilityScope: observabilityScope\n            )\n        case .branch(let branch, revision: let revision):\n            return try await self.checkoutRepository(\n                package: package,\n                at: .branch(name: branch, revision: .init(identifier: revision)),\n                observabilityScope: observabilityScope\n            )\n        case .revision(let revision):\n            return try await self.checkoutRepository(\n                package: package,\n                at: .revision(.init(identifier: revision)),\n                observabilityScope: observabilityScope\n            )\n        default:\n            throw InternalError(\"invalid resolution state: \\(resolutionStater)\")\n        }\n    }\n\n    /// Fetch a given `package` and create a local checkout for it.\n    ///\n    /// This will first clone the repository into the canonical repositories\n    /// location, if necessary, and then check it out from there.\n    ///\n    /// - Returns: The path of the local repository.\n    /// - Throws: If the operation could not be satisfied.\n    private func fetchRepository(\n        package: PackageReference,\n        at revision: Revision,\n        observabilityScope: ObservabilityScope\n    ) async throws -> AbsolutePath {\n        let repository = try package.makeRepositorySpecifier()\n\n        // If we already have it, fetch to update the repo from its remote.\n        // also compare the location as it may have changed\n        if let dependency = await self.state.dependencies[comparingLocation: package] {\n            let checkoutPath = self.location.repositoriesCheckoutSubdirectory(for: dependency)\n\n            // Make sure the directory is not missing (we will have to clone again if not).\n            // This can become invalid if the build directory is moved.\n            fetch: if self.fileSystem.isDirectory(checkoutPath) {\n                // Fetch the checkout in case there are updates available.\n                let workingCopy = try await self.repositoryManager.openWorkingCopy(at: checkoutPath)\n\n                // Ensure that the alternative object store is still valid.\n                guard try self.repositoryManager.isValidWorkingCopy(workingCopy, for: repository) else {\n                    observabilityScope\n                        .emit(\n                            debug: \"working copy at '\\(checkoutPath)' does not align with expected local path of '\\(repository)'\"\n                        )\n                    break fetch\n                }\n\n                // only update if necessary\n                if !workingCopy.exists(revision: revision) {\n                    // The fetch operation may update contents of the checkout,\n                    // so we need to do mutable-immutable dance.\n                    try self.fileSystem.chmod(.userWritable, path: checkoutPath, options: [.recursive, .onlyFiles])\n                    try workingCopy.fetch()\n                    try? self.fileSystem.chmod(.userUnWritable, path: checkoutPath, options: [.recursive, .onlyFiles])\n                }\n\n                return checkoutPath\n            }\n        }\n\n        // If not, we need to get the repository from the checkouts.\n        let handle = try await self.repositoryManager.lookup(\n            package: package.identity,\n            repository: repository,\n            updateStrategy: .never,\n            observabilityScope: observabilityScope\n        )\n\n        // Clone the repository into the checkouts.\n        let checkoutPath = self.location.repositoriesCheckoutsDirectory.appending(component: repository.basename)\n\n        // Remove any existing content at that path.\n        try self.fileSystem.chmod(.userWritable, path: checkoutPath, options: [.recursive, .onlyFiles])\n        try self.fileSystem.removeFileTree(checkoutPath)\n\n        // Inform the delegate that we're about to start.\n        self.delegate?.willCreateWorkingCopy(\n            package: package.identity,\n            repository: handle.repository.location.description,\n            at: checkoutPath\n        )\n        let start = DispatchTime.now()\n\n        // Create the working copy.\n        _ = try await handle.createWorkingCopy(at: checkoutPath, editable: false)\n\n        // Inform the delegate that we're done.\n        let duration = start.distance(to: .now())\n        self.delegate?.didCreateWorkingCopy(\n            package: package.identity,\n            repository: handle.repository.location.description,\n            at: checkoutPath,\n            duration: duration\n        )\n\n        return checkoutPath\n    }\n\n    /// Removes the clone and checkout of the provided specifier.\n    func removeRepository(dependency: ManagedDependency) async throws {\n        guard case .sourceControlCheckout = dependency.state else {\n            throw InternalError(\"cannot remove repository for \\(dependency) with state \\(dependency.state)\")\n        }\n\n        // Remove the checkout.\n        let dependencyPath = self.location.repositoriesCheckoutSubdirectory(for: dependency)\n        let workingCopy = try await self.repositoryManager.openWorkingCopy(at: dependencyPath)\n        guard !workingCopy.hasUncommittedChanges() else {\n            throw WorkspaceDiagnostics.UncommittedChanges(repositoryPath: dependencyPath)\n        }\n\n        try self.fileSystem.chmod(.userWritable, path: dependencyPath, options: [.recursive, .onlyFiles])\n        try self.fileSystem.removeFileTree(dependencyPath)\n\n        // Remove the clone.\n        try self.repositoryManager.remove(repository: dependency.packageRef.makeRepositorySpecifier())\n    }\n}\n\nextension CheckoutState {\n    var revision: Revision {\n        switch self {\n        case .revision(let revision):\n            return revision\n        case .version(_, let revision):\n            return revision\n        case .branch(_, let revision):\n            return revision\n        }\n    }\n\n    var isBranchOrRevisionBased: Bool {\n        switch self {\n        case .revision, .branch:\n            return true\n        case .version:\n            return false\n        }\n    }\n\n    var requirement: PackageRequirement {\n        switch self {\n        case .revision(let revision):\n            return .revision(revision.identifier)\n        case .version(let version, _):\n            return .versionSet(.exact(version))\n        case .branch(let branch, _):\n            return .revision(branch)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+State.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport SourceControl\nimport TSCBasic\n\nimport struct TSCUtility.Version\n\n/// Represents the workspace internal state persisted on disk.\npublic actor WorkspaceState {\n    /// The dependencies managed by the Workspace.\n    public private(set) var dependencies: Workspace.ManagedDependencies\n\n    /// The artifacts managed by the Workspace.\n    public private(set) var artifacts: Workspace.ManagedArtifacts\n\n    /// The prebuilts managed by the Workspace\n    public private(set) var prebuilts: Workspace.ManagedPrebuilts\n\n    /// Path to the state file.\n    public let storagePath: Basics.AbsolutePath\n\n    /// storage\n    private let storage: WorkspaceStateStorage\n\n    init(\n        fileSystem: FileSystem,\n        storageDirectory: Basics.AbsolutePath,\n        initializationWarningHandler: (String) -> Void\n    ) {\n        self.storagePath = storageDirectory.appending(\"workspace-state.json\")\n        self.storage = WorkspaceStateStorage(path: self.storagePath, fileSystem: fileSystem)\n\n        // Load the state from disk, if possible.\n        //\n        // If the disk operation here fails, we ignore the error here.\n        // This means if managed dependencies data is corrupted or out of date,\n        // clients will not see the old data and managed dependencies will be\n        // reset.  However there could be other errors, like permission issues,\n        // these errors will also be ignored but will surface when clients try\n        // to save the state.\n        do {\n            let storedState = try self.storage.load()\n            self.dependencies = storedState.dependencies\n            self.artifacts = storedState.artifacts\n            self.prebuilts = storedState.prebuilts\n        } catch {\n            self.dependencies = .init()\n            self.artifacts = .init()\n            self.prebuilts = .init()\n            try? self.storage.reset()\n            initializationWarningHandler(\"unable to restore workspace state: \\(error.interpolationDescription)\")\n        }\n    }\n\n    func reset() throws {\n        self.dependencies = Workspace.ManagedDependencies()\n        self.artifacts = Workspace.ManagedArtifacts()\n        self.prebuilts = Workspace.ManagedPrebuilts()\n        try self.save()\n    }\n\n    // marked public for testing\n    public func save() throws {\n        try self.storage.save(dependencies: self.dependencies, artifacts: self.artifacts, prebuilts: self.prebuilts)\n    }\n\n    /// Returns true if the state file exists on the filesystem.\n    func stateFileExists() -> Bool {\n        self.storage.fileExists()\n    }\n\n    func reload() throws {\n        let storedState = try self.storage.load()\n        self.dependencies = storedState.dependencies\n        self.artifacts = storedState.artifacts\n        self.prebuilts = storedState.prebuilts\n    }\n    \n    public func add(dependency: Workspace.ManagedDependency) {\n        dependencies = dependencies.add(dependency)\n    }\n\n    public func remove(identity: PackageIdentity) {\n        dependencies = dependencies.remove(identity)\n    }\n}\n\n// MARK: - Serialization\n\nprivate struct WorkspaceStateStorage {\n    private let path: Basics.AbsolutePath\n    private let fileSystem: FileSystem\n    private let encoder = JSONEncoder.makeWithDefaults()\n    private let decoder = JSONDecoder.makeWithDefaults()\n\n    init(path: Basics.AbsolutePath, fileSystem: FileSystem) {\n        self.path = path\n        self.fileSystem = fileSystem\n    }\n\n    struct State {\n        let dependencies: Workspace.ManagedDependencies\n        let artifacts: Workspace.ManagedArtifacts\n        let prebuilts: Workspace.ManagedPrebuilts\n    }\n\n    func load() throws -> State {\n        if !self.fileSystem.exists(self.path) {\n            return .init(dependencies: .init(), artifacts: .init(), prebuilts: .init())\n        }\n\n        return try self.fileSystem.withLock(on: self.path, type: .shared) {\n            let version = try decoder.decode(path: self.path, fileSystem: self.fileSystem, as: Version.self)\n            switch version.version {\n            case 1, 2, 3, 4:\n                let v4 = try self.decoder.decode(path: self.path, fileSystem: self.fileSystem, as: V4.self)\n                let dependencies = try v4.object.dependencies.map { try Workspace.ManagedDependency($0) }\n                let artifacts = try v4.object.artifacts.map { try Workspace.ManagedArtifact($0) }\n                return try .init(dependencies: .init(dependencies), artifacts: .init(artifacts), prebuilts: .init())\n            case 5:\n                let v5 = try self.decoder.decode(path: self.path, fileSystem: self.fileSystem, as: V5.self)\n                let dependencies = try v5.object.dependencies.map { try Workspace.ManagedDependency($0) }\n                let artifacts = try v5.object.artifacts.map { try Workspace.ManagedArtifact($0) }\n                return try .init(dependencies: .init(dependencies), artifacts: .init(artifacts), prebuilts: .init())\n            case 6:\n                let v6 = try self.decoder.decode(path: self.path, fileSystem: self.fileSystem, as: V6.self)\n                let dependencies = try v6.object.dependencies.map { try Workspace.ManagedDependency($0) }\n                let artifacts = try v6.object.artifacts.map { try Workspace.ManagedArtifact($0) }\n                return try .init(dependencies: .init(dependencies), artifacts: .init(artifacts), prebuilts: .init())\n            case 7:\n                let v7 = try self.decoder.decode(path: self.path, fileSystem: self.fileSystem, as: V7.self)\n                let dependencies = try v7.object.dependencies.map { try Workspace.ManagedDependency($0) }\n                let artifacts = try v7.object.artifacts.map { try Workspace.ManagedArtifact($0) }\n                let prebuilts = try v7.object.prebuilts.map { try Workspace.ManagedPrebuilt($0) }\n                return try .init(dependencies: .init(dependencies), artifacts: .init(artifacts), prebuilts: .init(prebuilts))\n\n            default:\n                throw StringError(\"unknown 'WorkspaceStateStorage' version '\\(version.version)' at '\\(self.path)'\")\n            }\n        }\n    }\n\n    func save(\n        dependencies: Workspace.ManagedDependencies,\n        artifacts: Workspace.ManagedArtifacts,\n        prebuilts: Workspace.ManagedPrebuilts\n    ) throws {\n        if !self.fileSystem.exists(self.path.parentDirectory) {\n            try self.fileSystem.createDirectory(self.path.parentDirectory)\n        }\n\n        try self.fileSystem.withLock(on: self.path, type: .exclusive) {\n            let storage = V7(dependencies: dependencies, artifacts: artifacts, prebuilts: prebuilts)\n\n            let data = try self.encoder.encode(storage)\n            try self.fileSystem.writeIfChanged(path: self.path, data: data)\n        }\n    }\n\n    func reset() throws {\n        if !self.fileSystem.exists(self.path.parentDirectory) {\n            return\n        }\n        try self.fileSystem.withLock(on: self.path, type: .exclusive) {\n            try self.fileSystem.removeFileTree(self.path)\n        }\n    }\n\n    func fileExists() -> Bool {\n        self.fileSystem.exists(self.path)\n    }\n}\n\nextension WorkspaceStateStorage {\n    // version reader\n    struct Version: Codable {\n        let version: Int\n    }\n}\n\n// MARK: - V7 format\n\nextension WorkspaceStateStorage {\n    // v7 storage format\n    struct V7: Codable {\n        let version: Int\n        let object: Container\n\n        init(\n            dependencies: Workspace.ManagedDependencies,\n            artifacts: Workspace.ManagedArtifacts,\n            prebuilts: Workspace.ManagedPrebuilts\n        ) {\n            self.version = 7\n            self.object = .init(\n                dependencies: dependencies.map { .init($0) }.sorted { $0.packageRef.identity < $1.packageRef.identity },\n                artifacts: artifacts.map { .init($0) }.sorted { $0.packageRef.identity < $1.packageRef.identity },\n                prebuilts: prebuilts.map { .init($0) }.sorted { $0.identity < $1.identity }\n            )\n        }\n\n        struct Container: Codable {\n            var dependencies: [Dependency]\n            var artifacts: [Artifact]\n            var prebuilts: [Prebuilt]\n        }\n\n        struct Dependency: Codable {\n            let packageRef: PackageReference\n            let state: State\n            let subpath: String\n\n            init(packageRef: PackageReference, state: State, subpath: String) {\n                self.packageRef = packageRef\n                self.state = state\n                self.subpath = subpath\n            }\n\n            init(_ dependency: Workspace.ManagedDependency) {\n                self.packageRef = .init(dependency.packageRef)\n                self.state = .init(underlying: dependency.state)\n                self.subpath = dependency.subpath.pathString\n            }\n\n            init(from decoder: Decoder) throws {\n                let container = try decoder.container(keyedBy: CodingKeys.self)\n                let packageRef = try container.decode(PackageReference.self, forKey: .packageRef)\n                let subpath = try container.decode(String.self, forKey: .subpath)\n                let basedOn = try container.decode(Dependency?.self, forKey: .basedOn)\n                let state = try State.decode(\n                    container: container.nestedContainer(keyedBy: State.CodingKeys.self, forKey: .state),\n                    basedOn: basedOn\n                )\n\n                self.init(\n                    packageRef: packageRef,\n                    state: state,\n                    subpath: subpath\n                )\n            }\n\n            func encode(to encoder: Encoder) throws {\n                var container = encoder.container(keyedBy: CodingKeys.self)\n                try container.encode(self.packageRef, forKey: .packageRef)\n                try container.encode(self.state, forKey: .state)\n                try container.encode(self.subpath, forKey: .subpath)\n                var basedOn: Dependency? = .none\n                if case .edited(let _basedOn, _) = self.state.underlying {\n                    basedOn = _basedOn.map { .init($0) }\n                }\n                try container.encode(basedOn, forKey: .basedOn)\n            }\n\n            enum CodingKeys: CodingKey {\n                case packageRef\n                case state\n                case subpath\n                case basedOn\n            }\n\n            struct State: Encodable {\n                let underlying: Workspace.ManagedDependency.State\n\n                init(underlying: Workspace.ManagedDependency.State) {\n                    self.underlying = underlying\n                }\n\n                static func decode(\n                    container: KeyedDecodingContainer<Self.CodingKeys>,\n                    basedOn: Dependency?\n                ) throws -> State {\n                    let kind = try container.decode(String.self, forKey: .name)\n                    switch kind {\n                    case \"local\", \"fileSystem\":\n                        let path = try container.decode(Basics.AbsolutePath.self, forKey: .path)\n                        return self.init(underlying: .fileSystem(path))\n                    case \"checkout\", \"sourceControlCheckout\":\n                        let checkout = try container.decode(CheckoutInfo.self, forKey: .checkoutState)\n                        return try self.init(underlying: .sourceControlCheckout(.init(checkout)))\n                    case \"registryDownload\":\n                        let version = try container.decode(String.self, forKey: .version)\n                        return try self\n                            .init(underlying: .registryDownload(version: TSCUtility.Version(versionString: version)))\n                    case \"edited\":\n                        let path = try container.decode(Basics.AbsolutePath?.self, forKey: .path)\n                        return try self.init(underlying: .edited(\n                            basedOn: basedOn.map { try .init($0) },\n                            unmanagedPath: path\n                        ))\n                    case \"custom\":\n                        let version = try container.decode(String.self, forKey: .version)\n                        let path = try container.decode(Basics.AbsolutePath.self, forKey: .path)\n                        return try self.init(underlying: .custom(\n                            version: TSCUtility.Version(versionString: version),\n                            path: path\n                        ))\n                    default:\n                        throw StringError(\"unknown dependency state \\(kind)\")\n                    }\n                }\n\n                func encode(to encoder: Encoder) throws {\n                    var container = encoder.container(keyedBy: CodingKeys.self)\n                    switch self.underlying {\n                    case .fileSystem(let path):\n                        try container.encode(\"fileSystem\", forKey: .name)\n                        try container.encode(path, forKey: .path)\n                    case .sourceControlCheckout(let state):\n                        try container.encode(\"sourceControlCheckout\", forKey: .name)\n                        try container.encode(CheckoutInfo(state), forKey: .checkoutState)\n                    case .registryDownload(let version):\n                        try container.encode(\"registryDownload\", forKey: .name)\n                        try container.encode(version, forKey: .version)\n                    case .edited(_, let path):\n                        try container.encode(\"edited\", forKey: .name)\n                        try container.encode(path, forKey: .path)\n                    case .custom(let version, let path):\n                        try container.encode(\"custom\", forKey: .name)\n                        try container.encode(version, forKey: .version)\n                        try container.encode(path, forKey: .path)\n                    }\n                }\n\n                enum CodingKeys: CodingKey {\n                    case name\n                    case path\n                    case version\n                    case checkoutState\n                }\n\n                struct CheckoutInfo: Codable {\n                    let revision: String\n                    let branch: String?\n                    let version: String?\n\n                    init(_ state: CheckoutState) {\n                        switch state {\n                        case .version(let version, let revision):\n                            self.version = version.description\n                            self.branch = nil\n                            self.revision = revision.identifier\n                        case .branch(let branch, let revision):\n                            self.version = nil\n                            self.branch = branch\n                            self.revision = revision.identifier\n                        case .revision(let revision):\n                            self.version = nil\n                            self.branch = nil\n                            self.revision = revision.identifier\n                        }\n                    }\n                }\n            }\n        }\n\n        struct Artifact: Codable {\n            let packageRef: PackageReference\n            let targetName: String\n            let source: Source\n            let path: String\n            let kind: Kind\n\n            init(_ artifact: Workspace.ManagedArtifact) {\n                self.packageRef = .init(artifact.packageRef)\n                self.targetName = artifact.targetName\n                self.source = .init(underlying: artifact.source)\n                self.path = artifact.path.pathString\n                self.kind = .init(artifact.kind)\n            }\n\n            struct Source: Codable {\n                let underlying: Workspace.ManagedArtifact.Source\n\n                init(underlying: Workspace.ManagedArtifact.Source) {\n                    self.underlying = underlying\n                }\n\n                init(from decoder: Decoder) throws {\n                    let container = try decoder.container(keyedBy: CodingKeys.self)\n                    let kind = try container.decode(String.self, forKey: .type)\n                    switch kind {\n                    case \"local\":\n                        let checksum = try container.decodeIfPresent(String.self, forKey: .checksum)\n                        self.init(underlying: .local(checksum: checksum))\n                    case \"remote\":\n                        let url = try container.decode(String.self, forKey: .url)\n                        let checksum = try container.decode(String.self, forKey: .checksum)\n                        self.init(underlying: .remote(url: url, checksum: checksum))\n                    default:\n                        throw StringError(\"unknown artifact source \\(kind)\")\n                    }\n                }\n\n                func encode(to encoder: Encoder) throws {\n                    var container = encoder.container(keyedBy: CodingKeys.self)\n                    switch self.underlying {\n                    case .local(let checksum):\n                        try container.encode(\"local\", forKey: .type)\n                        try container.encodeIfPresent(checksum, forKey: .checksum)\n                    case .remote(let url, let checksum):\n                        try container.encode(\"remote\", forKey: .type)\n                        try container.encode(url, forKey: .url)\n                        try container.encode(checksum, forKey: .checksum)\n                    }\n                }\n\n                enum CodingKeys: CodingKey {\n                    case type\n                    case url\n                    case checksum\n                }\n            }\n\n            enum Kind: Codable {\n                case xcframework\n                case artifactsArchive\n                case typedArtifactsArchive([String])\n                case unknown\n\n                init(_ underlying: BinaryModule.Kind) {\n                    switch underlying {\n                    case .xcframework:\n                        self = .xcframework\n                    case .artifactsArchive(let types):\n                        self = .typedArtifactsArchive(types.map { $0.rawValue })\n                    case .unknown:\n                        self = .unknown\n                    }\n                }\n\n                var underlying: BinaryModule.Kind {\n                    switch self {\n                    case .xcframework:\n                        return .xcframework\n                    case .artifactsArchive:\n                        // For backwards compatiblity reasons we assume an empty types array which in the worst case\n                        // results in a need for a clean build but we won't fail decoding the JSON.\n                        return .artifactsArchive(types: [])\n                    case .typedArtifactsArchive(let types):\n                        return .artifactsArchive(types: types.compactMap { ArtifactsArchiveMetadata.ArtifactType(rawValue: $0) })\n                    case .unknown:\n                        return .unknown\n                    }\n                }\n            }\n        }\n\n        struct Prebuilt: Codable {\n            let identity: PackageIdentity\n            let version: TSCUtility.Version\n            let libraryName: String\n            let path: Basics.AbsolutePath\n            let checkoutPath: Basics.AbsolutePath?\n            let products: [String]\n            let includePath: [Basics.RelativePath]?\n            let cModules: [String]\n\n            init(_ managedPrebuilt: Workspace.ManagedPrebuilt) {\n                self.identity = managedPrebuilt.identity\n                self.version = managedPrebuilt.version\n                self.libraryName = managedPrebuilt.libraryName\n                self.path = managedPrebuilt.path\n                self.checkoutPath = managedPrebuilt.checkoutPath\n                self.products = managedPrebuilt.products\n                self.includePath = managedPrebuilt.includePath\n                self.cModules = managedPrebuilt.cModules\n            }\n        }\n\n        struct PackageReference: Codable {\n            let identity: String\n            let kind: Kind\n            let location: String\n            let name: String\n\n            init(_ reference: PackageModel.PackageReference) {\n                self.identity = reference.identity.description\n                switch reference.kind {\n                case .root(let path):\n                    self.kind = .root\n                    self.location = path.pathString\n                case .fileSystem(let path):\n                    self.kind = .fileSystem\n                    self.location = path.pathString\n                case .localSourceControl(let path):\n                    self.kind = .localSourceControl\n                    self.location = path.pathString\n                case .remoteSourceControl(let url):\n                    self.kind = .remoteSourceControl\n                    self.location = url.absoluteString\n                case .registry:\n                    self.kind = .registry\n                    // FIXME: placeholder\n                    self.location = self.identity.description\n                }\n                self.name = reference.deprecatedName\n            }\n\n            enum Kind: String, Codable {\n                case root\n                case fileSystem\n                case localSourceControl\n                case remoteSourceControl\n                case registry\n            }\n        }\n    }\n}\n\nextension Workspace.ManagedDependency {\n    fileprivate init(_ dependency: WorkspaceStateStorage.V7.Dependency) throws {\n        try self.init(\n            packageRef: .init(dependency.packageRef),\n            state: dependency.state.underlying,\n            subpath: RelativePath(validating: dependency.subpath)\n        )\n    }\n}\n\nextension Workspace.ManagedArtifact {\n    fileprivate init(_ artifact: WorkspaceStateStorage.V7.Artifact) throws {\n        try self.init(\n            packageRef: .init(artifact.packageRef),\n            targetName: artifact.targetName,\n            source: artifact.source.underlying,\n            path: AbsolutePath(validating: artifact.path),\n            kind: artifact.kind.underlying\n        )\n    }\n}\n\nextension Workspace.ManagedPrebuilt {\n    fileprivate init(_ prebuilt: WorkspaceStateStorage.V7.Prebuilt) throws {\n        self.init(\n            identity: prebuilt.identity,\n            version: prebuilt.version,\n            libraryName: prebuilt.libraryName,\n            path: prebuilt.path,\n            checkoutPath: prebuilt.checkoutPath,\n            products: prebuilt.products,\n            includePath: prebuilt.includePath,\n            cModules: prebuilt.cModules\n        )\n    }\n}\n\nextension PackageModel.PackageReference {\n    fileprivate init(_ reference: WorkspaceStateStorage.V7.PackageReference) throws {\n        let identity = PackageIdentity.plain(reference.identity)\n        let kind: PackageModel.PackageReference.Kind\n        switch reference.kind {\n        case .root:\n            kind = try .root(.init(validating: reference.location))\n        case .fileSystem:\n            kind = try .fileSystem(.init(validating: reference.location))\n        case .localSourceControl:\n            kind = try .localSourceControl(.init(validating: reference.location))\n        case .remoteSourceControl:\n            kind = .remoteSourceControl(SourceControlURL(reference.location))\n        case .registry:\n            kind = .registry(identity)\n        }\n\n        self.init(\n            identity: identity,\n            kind: kind,\n            name: reference.name\n        )\n    }\n}\n\nextension CheckoutState {\n    fileprivate init(_ state: WorkspaceStateStorage.V7.Dependency.State.CheckoutInfo) throws {\n        let revision: Revision = .init(identifier: state.revision)\n        if let branch = state.branch {\n            self = .branch(name: branch, revision: revision)\n        } else if let version = state.version {\n            self = try .version(Version(versionString: version), revision: revision)\n        } else {\n            self = .revision(revision)\n        }\n    }\n}\n\n// MARK: - V6 format (deprecated)\n\nextension WorkspaceStateStorage {\n    // v6 storage format\n    struct V6: Codable {\n        let version: Int\n        let object: Container\n\n        init(dependencies: Workspace.ManagedDependencies, artifacts: Workspace.ManagedArtifacts) {\n            self.version = 6\n            self.object = .init(\n                dependencies: dependencies.map { .init($0) }.sorted { $0.packageRef.identity < $1.packageRef.identity },\n                artifacts: artifacts.map { .init($0) }.sorted { $0.packageRef.identity < $1.packageRef.identity }\n            )\n        }\n\n        struct Container: Codable {\n            var dependencies: [Dependency]\n            var artifacts: [Artifact]\n        }\n\n        struct Dependency: Codable {\n            let packageRef: PackageReference\n            let state: State\n            let subpath: String\n\n            init(packageRef: PackageReference, state: State, subpath: String) {\n                self.packageRef = packageRef\n                self.state = state\n                self.subpath = subpath\n            }\n\n            init(_ dependency: Workspace.ManagedDependency) {\n                self.packageRef = .init(dependency.packageRef)\n                self.state = .init(underlying: dependency.state)\n                self.subpath = dependency.subpath.pathString\n            }\n\n            init(from decoder: Decoder) throws {\n                let container = try decoder.container(keyedBy: CodingKeys.self)\n                let packageRef = try container.decode(PackageReference.self, forKey: .packageRef)\n                let subpath = try container.decode(String.self, forKey: .subpath)\n                let basedOn = try container.decode(Dependency?.self, forKey: .basedOn)\n                let state = try State.decode(\n                    container: container.nestedContainer(keyedBy: State.CodingKeys.self, forKey: .state),\n                    basedOn: basedOn\n                )\n\n                self.init(\n                    packageRef: packageRef,\n                    state: state,\n                    subpath: subpath\n                )\n            }\n\n            func encode(to encoder: Encoder) throws {\n                var container = encoder.container(keyedBy: CodingKeys.self)\n                try container.encode(self.packageRef, forKey: .packageRef)\n                try container.encode(self.state, forKey: .state)\n                try container.encode(self.subpath, forKey: .subpath)\n                var basedOn: Dependency? = .none\n                if case .edited(let _basedOn, _) = self.state.underlying {\n                    basedOn = _basedOn.map { .init($0) }\n                }\n                try container.encode(basedOn, forKey: .basedOn)\n            }\n\n            enum CodingKeys: CodingKey {\n                case packageRef\n                case state\n                case subpath\n                case basedOn\n            }\n\n            struct State: Encodable {\n                let underlying: Workspace.ManagedDependency.State\n\n                init(underlying: Workspace.ManagedDependency.State) {\n                    self.underlying = underlying\n                }\n\n                static func decode(\n                    container: KeyedDecodingContainer<Self.CodingKeys>,\n                    basedOn: Dependency?\n                ) throws -> State {\n                    let kind = try container.decode(String.self, forKey: .name)\n                    switch kind {\n                    case \"local\", \"fileSystem\":\n                        let path = try container.decode(Basics.AbsolutePath.self, forKey: .path)\n                        return self.init(underlying: .fileSystem(path))\n                    case \"checkout\", \"sourceControlCheckout\":\n                        let checkout = try container.decode(CheckoutInfo.self, forKey: .checkoutState)\n                        return try self.init(underlying: .sourceControlCheckout(.init(checkout)))\n                    case \"registryDownload\":\n                        let version = try container.decode(String.self, forKey: .version)\n                        return try self\n                            .init(underlying: .registryDownload(version: TSCUtility.Version(versionString: version)))\n                    case \"edited\":\n                        let path = try container.decode(Basics.AbsolutePath?.self, forKey: .path)\n                        return try self.init(underlying: .edited(\n                            basedOn: basedOn.map { try .init($0) },\n                            unmanagedPath: path\n                        ))\n                    case \"custom\":\n                        let version = try container.decode(String.self, forKey: .version)\n                        let path = try container.decode(Basics.AbsolutePath.self, forKey: .path)\n                        return try self.init(underlying: .custom(\n                            version: TSCUtility.Version(versionString: version),\n                            path: path\n                        ))\n                    default:\n                        throw StringError(\"unknown dependency state \\(kind)\")\n                    }\n                }\n\n                func encode(to encoder: Encoder) throws {\n                    var container = encoder.container(keyedBy: CodingKeys.self)\n                    switch self.underlying {\n                    case .fileSystem(let path):\n                        try container.encode(\"fileSystem\", forKey: .name)\n                        try container.encode(path, forKey: .path)\n                    case .sourceControlCheckout(let state):\n                        try container.encode(\"sourceControlCheckout\", forKey: .name)\n                        try container.encode(CheckoutInfo(state), forKey: .checkoutState)\n                    case .registryDownload(let version):\n                        try container.encode(\"registryDownload\", forKey: .name)\n                        try container.encode(version, forKey: .version)\n                    case .edited(_, let path):\n                        try container.encode(\"edited\", forKey: .name)\n                        try container.encode(path, forKey: .path)\n                    case .custom(let version, let path):\n                        try container.encode(\"custom\", forKey: .name)\n                        try container.encode(version, forKey: .version)\n                        try container.encode(path, forKey: .path)\n                    }\n                }\n\n                enum CodingKeys: CodingKey {\n                    case name\n                    case path\n                    case version\n                    case checkoutState\n                }\n\n                struct CheckoutInfo: Codable {\n                    let revision: String\n                    let branch: String?\n                    let version: String?\n\n                    init(_ state: CheckoutState) {\n                        switch state {\n                        case .version(let version, let revision):\n                            self.version = version.description\n                            self.branch = nil\n                            self.revision = revision.identifier\n                        case .branch(let branch, let revision):\n                            self.version = nil\n                            self.branch = branch\n                            self.revision = revision.identifier\n                        case .revision(let revision):\n                            self.version = nil\n                            self.branch = nil\n                            self.revision = revision.identifier\n                        }\n                    }\n                }\n            }\n        }\n\n        struct Artifact: Codable {\n            let packageRef: PackageReference\n            let targetName: String\n            let source: Source\n            let path: String\n            let kind: Kind\n\n            init(_ artifact: Workspace.ManagedArtifact) {\n                self.packageRef = .init(artifact.packageRef)\n                self.targetName = artifact.targetName\n                self.source = .init(underlying: artifact.source)\n                self.path = artifact.path.pathString\n                self.kind = .init(artifact.kind)\n            }\n\n            struct Source: Codable {\n                let underlying: Workspace.ManagedArtifact.Source\n\n                init(underlying: Workspace.ManagedArtifact.Source) {\n                    self.underlying = underlying\n                }\n\n                init(from decoder: Decoder) throws {\n                    let container = try decoder.container(keyedBy: CodingKeys.self)\n                    let kind = try container.decode(String.self, forKey: .type)\n                    switch kind {\n                    case \"local\":\n                        let checksum = try container.decodeIfPresent(String.self, forKey: .checksum)\n                        self.init(underlying: .local(checksum: checksum))\n                    case \"remote\":\n                        let url = try container.decode(String.self, forKey: .url)\n                        let checksum = try container.decode(String.self, forKey: .checksum)\n                        self.init(underlying: .remote(url: url, checksum: checksum))\n                    default:\n                        throw StringError(\"unknown artifact source \\(kind)\")\n                    }\n                }\n\n                func encode(to encoder: Encoder) throws {\n                    var container = encoder.container(keyedBy: CodingKeys.self)\n                    switch self.underlying {\n                    case .local(let checksum):\n                        try container.encode(\"local\", forKey: .type)\n                        try container.encodeIfPresent(checksum, forKey: .checksum)\n                    case .remote(let url, let checksum):\n                        try container.encode(\"remote\", forKey: .type)\n                        try container.encode(url, forKey: .url)\n                        try container.encode(checksum, forKey: .checksum)\n                    }\n                }\n\n                enum CodingKeys: CodingKey {\n                    case type\n                    case url\n                    case checksum\n                }\n            }\n\n            enum Kind: String, Codable {\n                case xcframework\n                case artifactsArchive\n                case unknown\n\n                init(_ underlying: BinaryModule.Kind) {\n                    switch underlying {\n                    case .xcframework:\n                        self = .xcframework\n                    case .artifactsArchive:\n                        self = .artifactsArchive\n                    case .unknown:\n                        self = .unknown\n                    }\n                }\n\n                var underlying: BinaryModule.Kind {\n                    switch self {\n                    case .xcframework:\n                        return .xcframework\n                    case .artifactsArchive:\n                        return .artifactsArchive(types: [])\n                    case .unknown:\n                        return .unknown\n                    }\n                }\n            }\n        }\n\n        struct PackageReference: Codable {\n            let identity: String\n            let kind: Kind\n            let location: String\n            let name: String\n\n            init(_ reference: PackageModel.PackageReference) {\n                self.identity = reference.identity.description\n                switch reference.kind {\n                case .root(let path):\n                    self.kind = .root\n                    self.location = path.pathString\n                case .fileSystem(let path):\n                    self.kind = .fileSystem\n                    self.location = path.pathString\n                case .localSourceControl(let path):\n                    self.kind = .localSourceControl\n                    self.location = path.pathString\n                case .remoteSourceControl(let url):\n                    self.kind = .remoteSourceControl\n                    self.location = url.absoluteString\n                case .registry:\n                    self.kind = .registry\n                    // FIXME: placeholder\n                    self.location = self.identity.description\n                }\n                self.name = reference.deprecatedName\n            }\n\n            enum Kind: String, Codable {\n                case root\n                case fileSystem\n                case localSourceControl\n                case remoteSourceControl\n                case registry\n            }\n        }\n    }\n}\n\nextension Workspace.ManagedDependency {\n    fileprivate init(_ dependency: WorkspaceStateStorage.V6.Dependency) throws {\n        try self.init(\n            packageRef: .init(dependency.packageRef),\n            state: dependency.state.underlying,\n            subpath: RelativePath(validating: dependency.subpath)\n        )\n    }\n}\n\nextension Workspace.ManagedArtifact {\n    fileprivate init(_ artifact: WorkspaceStateStorage.V6.Artifact) throws {\n        try self.init(\n            packageRef: .init(artifact.packageRef),\n            targetName: artifact.targetName,\n            source: artifact.source.underlying,\n            path: AbsolutePath(validating: artifact.path),\n            kind: artifact.kind.underlying\n        )\n    }\n}\n\nextension PackageModel.PackageReference {\n    fileprivate init(_ reference: WorkspaceStateStorage.V6.PackageReference) throws {\n        let identity = PackageIdentity.plain(reference.identity)\n        let kind: PackageModel.PackageReference.Kind\n        switch reference.kind {\n        case .root:\n            kind = try .root(.init(validating: reference.location))\n        case .fileSystem:\n            kind = try .fileSystem(.init(validating: reference.location))\n        case .localSourceControl:\n            kind = try .localSourceControl(.init(validating: reference.location))\n        case .remoteSourceControl:\n            kind = .remoteSourceControl(SourceControlURL(reference.location))\n        case .registry:\n            kind = .registry(identity)\n        }\n\n        self.init(\n            identity: identity,\n            kind: kind,\n            name: reference.name\n        )\n    }\n}\n\nextension CheckoutState {\n    fileprivate init(_ state: WorkspaceStateStorage.V6.Dependency.State.CheckoutInfo) throws {\n        let revision: Revision = .init(identifier: state.revision)\n        if let branch = state.branch {\n            self = .branch(name: branch, revision: revision)\n        } else if let version = state.version {\n            self = try .version(Version(versionString: version), revision: revision)\n        } else {\n            self = .revision(revision)\n        }\n    }\n}\n\n// MARK: - V5 format (deprecated)\n\nextension WorkspaceStateStorage {\n    // v5 storage format\n    struct V5: Codable {\n        let version: Int\n        let object: Container\n\n        init(dependencies: Workspace.ManagedDependencies, artifacts: Workspace.ManagedArtifacts) {\n            self.version = 5\n            self.object = .init(\n                dependencies: dependencies.map { .init($0) }.sorted { $0.packageRef.identity < $1.packageRef.identity },\n                artifacts: artifacts.map { .init($0) }.sorted { $0.packageRef.identity < $1.packageRef.identity }\n            )\n        }\n\n        struct Container: Codable {\n            var dependencies: [Dependency]\n            var artifacts: [Artifact]\n        }\n\n        struct Dependency: Codable {\n            let packageRef: PackageReference\n            let state: State\n            let subpath: String\n\n            init(packageRef: PackageReference, state: State, subpath: String) {\n                self.packageRef = packageRef\n                self.state = state\n                self.subpath = subpath\n            }\n\n            init(_ dependency: Workspace.ManagedDependency) {\n                self.packageRef = .init(dependency.packageRef)\n                self.state = .init(underlying: dependency.state)\n                self.subpath = dependency.subpath.pathString\n            }\n\n            init(from decoder: Decoder) throws {\n                let container = try decoder.container(keyedBy: CodingKeys.self)\n                let packageRef = try container.decode(PackageReference.self, forKey: .packageRef)\n                let subpath = try container.decode(String.self, forKey: .subpath)\n                let basedOn = try container.decode(Dependency?.self, forKey: .basedOn)\n                let state = try State.decode(\n                    container: container.nestedContainer(keyedBy: State.CodingKeys.self, forKey: .state),\n                    basedOn: basedOn\n                )\n\n                self.init(\n                    packageRef: packageRef,\n                    state: state,\n                    subpath: subpath\n                )\n            }\n\n            func encode(to encoder: Encoder) throws {\n                var container = encoder.container(keyedBy: CodingKeys.self)\n                try container.encode(self.packageRef, forKey: .packageRef)\n                try container.encode(self.state, forKey: .state)\n                try container.encode(self.subpath, forKey: .subpath)\n                var basedOn: Dependency? = .none\n                if case .edited(let _basedOn, _) = self.state.underlying {\n                    basedOn = _basedOn.map { .init($0) }\n                }\n                try container.encode(basedOn, forKey: .basedOn)\n            }\n\n            enum CodingKeys: CodingKey {\n                case packageRef\n                case state\n                case subpath\n                case basedOn\n            }\n\n            struct State: Encodable {\n                let underlying: Workspace.ManagedDependency.State\n\n                init(underlying: Workspace.ManagedDependency.State) {\n                    self.underlying = underlying\n                }\n\n                static func decode(\n                    container: KeyedDecodingContainer<Self.CodingKeys>,\n                    basedOn: Dependency?\n                ) throws -> State {\n                    let kind = try container.decode(String.self, forKey: .name)\n                    switch kind {\n                    case \"local\", \"fileSystem\":\n                        let path = try container.decode(Basics.AbsolutePath.self, forKey: .path)\n                        return self.init(underlying: .fileSystem(path))\n                    case \"checkout\", \"sourceControlCheckout\":\n                        let checkout = try container.decode(CheckoutInfo.self, forKey: .checkoutState)\n                        return try self.init(underlying: .sourceControlCheckout(.init(checkout)))\n                    case \"registryDownload\":\n                        let version = try container.decode(String.self, forKey: .version)\n                        return try self\n                            .init(underlying: .registryDownload(version: TSCUtility.Version(versionString: version)))\n                    case \"edited\":\n                        let path = try container.decode(Basics.AbsolutePath?.self, forKey: .path)\n                        return try self.init(underlying: .edited(\n                            basedOn: basedOn.map { try .init($0) },\n                            unmanagedPath: path\n                        ))\n                    case \"custom\":\n                        let version = try container.decode(String.self, forKey: .version)\n                        let path = try container.decode(Basics.AbsolutePath.self, forKey: .path)\n                        return try self.init(underlying: .custom(\n                            version: TSCUtility.Version(versionString: version),\n                            path: path\n                        ))\n                    default:\n                        throw StringError(\"unknown dependency state \\(kind)\")\n                    }\n                }\n\n                func encode(to encoder: Encoder) throws {\n                    var container = encoder.container(keyedBy: CodingKeys.self)\n                    switch self.underlying {\n                    case .fileSystem(let path):\n                        try container.encode(\"fileSystem\", forKey: .name)\n                        try container.encode(path, forKey: .path)\n                    case .sourceControlCheckout(let state):\n                        try container.encode(\"sourceControlCheckout\", forKey: .name)\n                        try container.encode(CheckoutInfo(state), forKey: .checkoutState)\n                    case .registryDownload(let version):\n                        try container.encode(\"registryDownload\", forKey: .name)\n                        try container.encode(version, forKey: .version)\n                    case .edited(_, let path):\n                        try container.encode(\"edited\", forKey: .name)\n                        try container.encode(path, forKey: .path)\n                    case .custom(let version, let path):\n                        try container.encode(\"custom\", forKey: .name)\n                        try container.encode(version, forKey: .version)\n                        try container.encode(path, forKey: .path)\n                    }\n                }\n\n                enum CodingKeys: CodingKey {\n                    case name\n                    case path\n                    case version\n                    case checkoutState\n                }\n\n                struct CheckoutInfo: Codable {\n                    let revision: String\n                    let branch: String?\n                    let version: String?\n\n                    init(_ state: CheckoutState) {\n                        switch state {\n                        case .version(let version, let revision):\n                            self.version = version.description\n                            self.branch = nil\n                            self.revision = revision.identifier\n                        case .branch(let branch, let revision):\n                            self.version = nil\n                            self.branch = branch\n                            self.revision = revision.identifier\n                        case .revision(let revision):\n                            self.version = nil\n                            self.branch = nil\n                            self.revision = revision.identifier\n                        }\n                    }\n                }\n            }\n        }\n\n        struct Artifact: Codable {\n            let packageRef: PackageReference\n            let targetName: String\n            let source: Source\n            let path: String\n\n            init(_ artifact: Workspace.ManagedArtifact) {\n                self.packageRef = .init(artifact.packageRef)\n                self.targetName = artifact.targetName\n                self.source = .init(underlying: artifact.source)\n                self.path = artifact.path.pathString\n            }\n\n            struct Source: Codable {\n                let underlying: Workspace.ManagedArtifact.Source\n\n                init(underlying: Workspace.ManagedArtifact.Source) {\n                    self.underlying = underlying\n                }\n\n                init(from decoder: Decoder) throws {\n                    let container = try decoder.container(keyedBy: CodingKeys.self)\n                    let kind = try container.decode(String.self, forKey: .type)\n                    switch kind {\n                    case \"local\":\n                        let checksum = try container.decodeIfPresent(String.self, forKey: .checksum)\n                        self.init(underlying: .local(checksum: checksum))\n                    case \"remote\":\n                        let url = try container.decode(String.self, forKey: .url)\n                        let checksum = try container.decode(String.self, forKey: .checksum)\n                        self.init(underlying: .remote(url: url, checksum: checksum))\n                    default:\n                        throw StringError(\"unknown artifact source \\(kind)\")\n                    }\n                }\n\n                func encode(to encoder: Encoder) throws {\n                    var container = encoder.container(keyedBy: CodingKeys.self)\n                    switch self.underlying {\n                    case .local(let checksum):\n                        try container.encode(\"local\", forKey: .type)\n                        try container.encodeIfPresent(checksum, forKey: .checksum)\n                    case .remote(let url, let checksum):\n                        try container.encode(\"remote\", forKey: .type)\n                        try container.encode(url, forKey: .url)\n                        try container.encode(checksum, forKey: .checksum)\n                    }\n                }\n\n                enum CodingKeys: CodingKey {\n                    case type\n                    case url\n                    case checksum\n                }\n            }\n        }\n\n        struct PackageReference: Codable {\n            let identity: String\n            let kind: Kind\n            let location: String\n            let name: String\n\n            init(_ reference: PackageModel.PackageReference) {\n                self.identity = reference.identity.description\n                switch reference.kind {\n                case .root(let path):\n                    self.kind = .root\n                    self.location = path.pathString\n                case .fileSystem(let path):\n                    self.kind = .fileSystem\n                    self.location = path.pathString\n                case .localSourceControl(let path):\n                    self.kind = .localSourceControl\n                    self.location = path.pathString\n                case .remoteSourceControl(let url):\n                    self.kind = .remoteSourceControl\n                    self.location = url.absoluteString\n                case .registry:\n                    self.kind = .registry\n                    // FIXME: placeholder\n                    self.location = self.identity.description\n                }\n                self.name = reference.deprecatedName\n            }\n\n            enum Kind: String, Codable {\n                case root\n                case fileSystem\n                case localSourceControl\n                case remoteSourceControl\n                case registry\n            }\n        }\n    }\n}\n\nextension Workspace.ManagedDependency {\n    fileprivate init(_ dependency: WorkspaceStateStorage.V5.Dependency) throws {\n        try self.init(\n            packageRef: .init(dependency.packageRef),\n            state: dependency.state.underlying,\n            subpath: RelativePath(validating: dependency.subpath)\n        )\n    }\n}\n\nextension Workspace.ManagedArtifact {\n    fileprivate init(_ artifact: WorkspaceStateStorage.V5.Artifact) throws {\n        let path = try Basics.AbsolutePath(validating: artifact.path)\n        try self.init(\n            packageRef: .init(artifact.packageRef),\n            targetName: artifact.targetName,\n            source: artifact.source.underlying,\n            path: path,\n            kind: .forPath(path)\n        )\n    }\n}\n\nextension PackageModel.PackageReference {\n    fileprivate init(_ reference: WorkspaceStateStorage.V5.PackageReference) throws {\n        let identity = PackageIdentity.plain(reference.identity)\n        let kind: PackageModel.PackageReference.Kind\n        switch reference.kind {\n        case .root:\n            kind = try .root(.init(validating: reference.location))\n        case .fileSystem:\n            kind = try .fileSystem(.init(validating: reference.location))\n        case .localSourceControl:\n            kind = try .localSourceControl(.init(validating: reference.location))\n        case .remoteSourceControl:\n            kind = .remoteSourceControl(SourceControlURL(reference.location))\n        case .registry:\n            kind = .registry(identity)\n        }\n\n        self.init(\n            identity: identity,\n            kind: kind,\n            name: reference.name\n        )\n    }\n}\n\nextension CheckoutState {\n    fileprivate init(_ state: WorkspaceStateStorage.V5.Dependency.State.CheckoutInfo) throws {\n        let revision: Revision = .init(identifier: state.revision)\n        if let branch = state.branch {\n            self = .branch(name: branch, revision: revision)\n        } else if let version = state.version {\n            self = try .version(Version(versionString: version), revision: revision)\n        } else {\n            self = .revision(revision)\n        }\n    }\n}\n\n// MARK: - V1...4 format (deprecated)\n\nextension WorkspaceStateStorage {\n    /// * 4: Artifacts.\n    /// * 3: Package kind.\n    /// * 2: Package identity.\n    /// * 1: Initial version.\n    // v4 storage format\n    struct V4: Decodable {\n        let version: Int\n        let object: Container\n\n        struct Container: Decodable {\n            var dependencies: [Dependency]\n            var artifacts: [Artifact]\n        }\n\n        struct Dependency: Decodable {\n            let packageRef: PackageReference\n            let state: State\n            let subpath: String\n\n            init(packageRef: PackageReference, state: State, subpath: String) {\n                self.packageRef = packageRef\n                self.state = state\n                self.subpath = subpath\n            }\n\n            init(from decoder: Decoder) throws {\n                let container = try decoder.container(keyedBy: CodingKeys.self)\n                let packageRef = try container.decode(PackageReference.self, forKey: .packageRef)\n                let subpath = try container.decode(String.self, forKey: .subpath)\n                let basedOn = try container.decode(Dependency?.self, forKey: .basedOn)\n                let state = try State.decode(\n                    container: container.nestedContainer(keyedBy: State.CodingKeys.self, forKey: .state),\n                    packageRef: packageRef,\n                    basedOn: basedOn\n                )\n\n                self.init(\n                    packageRef: packageRef,\n                    state: state,\n                    subpath: subpath\n                )\n            }\n\n            enum CodingKeys: CodingKey {\n                case packageRef\n                case state\n                case subpath\n                case basedOn\n            }\n\n            struct State {\n                let underlying: Workspace.ManagedDependency.State\n\n                init(underlying: Workspace.ManagedDependency.State) {\n                    self.underlying = underlying\n                }\n\n                static func decode(\n                    container: KeyedDecodingContainer<Self.CodingKeys>,\n                    packageRef: PackageReference,\n                    basedOn: Dependency?\n                ) throws -> State {\n                    let kind = try container.decode(String.self, forKey: .name)\n                    switch kind {\n                    case \"local\":\n                        return try self.init(underlying: .fileSystem(.init(validating: packageRef.location)))\n                    case \"checkout\":\n                        let checkout = try container.decode(CheckoutInfo.self, forKey: .checkoutState)\n                        return try self.init(underlying: .sourceControlCheckout(.init(checkout)))\n                    case \"edited\":\n                        let path = try container.decode(Basics.AbsolutePath?.self, forKey: .path)\n                        return try self.init(underlying: .edited(\n                            basedOn: basedOn.map { try .init($0) },\n                            unmanagedPath: path\n                        ))\n                    default:\n                        throw StringError(\"unknown dependency state \\(kind)\")\n                    }\n                }\n\n                enum CodingKeys: CodingKey {\n                    case name\n                    case path\n                    case checkoutState\n                }\n\n                struct CheckoutInfo: Codable {\n                    let revision: String\n                    let branch: String?\n                    let version: String?\n\n                    init(_ state: CheckoutState) {\n                        switch state {\n                        case .version(let version, let revision):\n                            self.version = version.description\n                            self.branch = nil\n                            self.revision = revision.identifier\n                        case .branch(let branch, let revision):\n                            self.version = nil\n                            self.branch = branch\n                            self.revision = revision.identifier\n                        case .revision(let revision):\n                            self.version = nil\n                            self.branch = nil\n                            self.revision = revision.identifier\n                        }\n                    }\n                }\n            }\n        }\n\n        struct Artifact: Decodable {\n            let packageRef: PackageReference\n            let targetName: String\n            let source: Source\n            let path: String\n\n            struct Source: Decodable {\n                let underlying: Workspace.ManagedArtifact.Source\n\n                init(underlying: Workspace.ManagedArtifact.Source) {\n                    self.underlying = underlying\n                }\n\n                init(from decoder: Decoder) throws {\n                    let container = try decoder.container(keyedBy: CodingKeys.self)\n                    let kind = try container.decode(String.self, forKey: .type)\n                    switch kind {\n                    case \"local\":\n                        let checksum = try container.decodeIfPresent(String.self, forKey: .checksum)\n                        self.init(underlying: .local(checksum: checksum))\n                    case \"remote\":\n                        let url = try container.decode(String.self, forKey: .url)\n                        let checksum = try container.decode(String.self, forKey: .checksum)\n                        self.init(underlying: .remote(url: url, checksum: checksum))\n                    default:\n                        throw StringError(\"unknown artifact source \\(kind)\")\n                    }\n                }\n\n                enum CodingKeys: CodingKey {\n                    case type\n                    case url\n                    case checksum\n                }\n            }\n        }\n\n        struct PackageReference: Decodable {\n            let identity: String\n            let kind: String\n            let location: String\n            let name: String\n\n            init(from decoder: Decoder) throws {\n                let container = try decoder.container(keyedBy: CodingKeys.self)\n                self.identity = try container.decode(String.self, forKey: .identity)\n                self.kind = try container.decode(String.self, forKey: .kind)\n                self.name = try container.decode(String.self, forKey: .name)\n                if let location = try container.decodeIfPresent(String.self, forKey: .location) {\n                    self.location = location\n                } else if let path = try container.decodeIfPresent(String.self, forKey: .path) {\n                    self.location = path\n                } else {\n                    throw StringError(\"invalid package ref, missing location and path\")\n                }\n            }\n\n            enum CodingKeys: CodingKey {\n                case identity\n                case kind\n                case location\n                case path\n                case name\n            }\n        }\n    }\n}\n\nextension Workspace.ManagedDependency {\n    fileprivate init(_ dependency: WorkspaceStateStorage.V4.Dependency) throws {\n        try self.init(\n            packageRef: .init(dependency.packageRef),\n            state: dependency.state.underlying,\n            subpath: RelativePath(validating: dependency.subpath)\n        )\n    }\n}\n\nextension Workspace.ManagedArtifact {\n    fileprivate init(_ artifact: WorkspaceStateStorage.V4.Artifact) throws {\n        let path = try Basics.AbsolutePath(validating: artifact.path)\n        try self.init(\n            packageRef: .init(artifact.packageRef),\n            targetName: artifact.targetName,\n            source: artifact.source.underlying,\n            path: path,\n            kind: .forPath(path)\n        )\n    }\n}\n\nextension PackageModel.PackageReference {\n    fileprivate init(_ reference: WorkspaceStateStorage.V4.PackageReference) throws {\n        let identity = PackageIdentity.plain(reference.identity)\n        let kind: PackageModel.PackageReference.Kind\n        switch reference.kind {\n        case \"root\":\n            kind = try .root(.init(validating: reference.location))\n        case \"local\":\n            kind = try .fileSystem(.init(validating: reference.location))\n        case \"remote\":\n            if let path = try? Basics.AbsolutePath(validating: reference.location) {\n                kind = .localSourceControl(path)\n            } else {\n                kind = .remoteSourceControl(SourceControlURL(reference.location))\n            }\n        default:\n            throw StringError(\"invalid package kind \\(reference.kind)\")\n        }\n\n        self.init(\n            identity: identity,\n            kind: kind,\n            name: reference.name\n        )\n    }\n}\n\nextension CheckoutState {\n    fileprivate init(_ state: WorkspaceStateStorage.V4.Dependency.State.CheckoutInfo) throws {\n        let revision: Revision = .init(identifier: state.revision)\n        if let branch = state.branch {\n            self = .branch(name: branch, revision: revision)\n        } else if let version = state.version {\n            self = try .version(Version(versionString: version), revision: revision)\n        } else {\n            self = .revision(revision)\n        }\n    }\n}\n\n// backwards compatibility for older formats\n\nextension BinaryModule.Kind {\n    fileprivate static func forPath(_ path: Basics.AbsolutePath) -> Self {\n        if let kind = allCases.first(where: { $0.fileExtension == path.extension }) {\n            return kind\n        }\n        return .unknown\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace+Traits.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class PackageModel.Manifest\nimport struct PackageModel.PackageIdentity\nimport enum PackageModel.ProductFilter\nimport enum PackageModel.PackageDependency\nimport struct PackageModel.EnabledTrait\nimport struct PackageModel.EnabledTraits\n\nextension Workspace {\n    /// Given a loaded `Manifest`, determine the traits that are enabled for it and\n    /// calculate whichever traits are enabled transitively from this, if possible, and update the\n    /// map of enabled traits on `Workspace` (`Workspace.enabledTraitsMap`).\n    ///\n    /// If the package defines a dependency with an explicit set of enabled traits, it will also\n    /// add them to the enabled traits map.\n    public func updateEnabledTraits(for manifest: Manifest) throws {\n        // If the `Manifest` is a root, then we should default to using\n        // the trait configuration set in the `Workspace`. Otherwise,\n        // check the enabled traits map to see if there are traits\n        // that have already been recorded as enabled.\n        let explicitlyEnabledTraits = manifest.packageKind.isRoot ?\n        try manifest.enabledTraits(using: self.traitConfiguration) :\n        self.enabledTraitsMap[manifest.packageIdentity]\n\n        var enabledTraits = try manifest.enabledTraits(using: explicitlyEnabledTraits)\n\n        // Check if any parents requested default traits for this package\n        // If so, expand the default traits and union them with existing traits\n        if let defaultSetters = self.enabledTraitsMap[defaultSettersFor: manifest.packageIdentity],\n           !defaultSetters.isEmpty {\n            // Calculate what the default traits are for this manifest\n            let defaultTraits = try manifest.enabledTraits(using: .defaults)\n\n            // Create enabled traits for each setter that requested defaults\n            for setter in defaultSetters {\n                let traitsFromSetter = EnabledTraits(\n                    defaultTraits.map(\\.name),\n                    setBy: setter\n                )\n                enabledTraits.formUnion(traitsFromSetter)\n            }\n        }\n\n        self.enabledTraitsMap[manifest.packageIdentity] = enabledTraits\n\n        // Check enabled traits for the dependencies\n        for dep in manifest.dependencies {\n            updateEnabledTraits(forDependency: dep, manifest)\n        }\n    }\n\n    /// Update the enabled traits for a `PackageDependency` of a given parent `Manifest`.\n    ///\n    /// This is called when a manifest is loaded to register the parent's trait requirements for its dependencies.\n    /// When a parent doesn't specify traits, this explicitly registers that the parent wants the dependency\n    /// to use its default traits, with the parent as the setter.\n    private func updateEnabledTraits(forDependency dependency: PackageDependency, _ parent: Manifest) {\n        let parentEnabledTraits = self.enabledTraitsMap[parent.packageIdentity]\n\n        if let dependencyTraits = dependency.traits {\n            // Parent explicitly specified traits (could be [] to disable, or a list of specific traits)\n            let explicitlyEnabledTraits = dependencyTraits\n                .filter { $0.isEnabled(by: parentEnabledTraits) }\n                .map(\\.name)\n\n            let enabledTraits = EnabledTraits(\n                explicitlyEnabledTraits,\n                setBy: .package(.init(parent))\n            )\n            self.enabledTraitsMap[dependency.identity] = enabledTraits\n        } else {\n            // Parent didn't specify traits - it wants the dependency to use its defaults.\n            // Explicitly register \"default\" with this parent as the setter.\n            // This ensures the union system properly tracks that this parent wants defaults enabled,\n            // even if other parents have disabled traits.\n            let defaultTraits = EnabledTraits(\n                [\"default\"],\n                setBy: .package(.init(parent))\n            )\n            self.enabledTraitsMap[dependency.identity] = defaultTraits\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/Workspace/Workspace.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Basics\nimport Foundation\nimport PackageFingerprint\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport PackageRegistry\nimport PackageSigning\nimport SourceControl\n\nimport func TSCBasic.findCycle\nimport protocol TSCBasic.HashAlgorithm\nimport struct TSCBasic.KeyedPair\nimport struct TSCBasic.SHA256\nimport var TSCBasic.stderrStream\nimport func TSCBasic.topologicalSort\nimport func TSCBasic.transitiveClosure\n\nimport enum TSCUtility.Diagnostics\nimport struct TSCUtility.Version\n\n/// Enumeration of the different reasons for which the resolver needs to be run.\npublic enum WorkspaceResolveReason: Equatable {\n    /// Resolution was forced.\n    case forced\n\n    /// Requirements were added for new packages.\n    case newPackages(packages: [PackageReference])\n\n    /// The requirement of a dependency has changed.\n    case packageRequirementChange(\n        package: PackageReference,\n        state: Workspace.ManagedDependency.State?,\n        requirement: PackageRequirement\n    )\n\n    /// An unknown reason.\n    case other(String)\n\n    /// Errors previously reported, e.g. during cloning. This will skip emitting additional unhelpful diagnostics.\n    case errorsPreviouslyReported\n}\n\npublic struct PackageFetchDetails {\n    /// Indicates if the package was fetched from the cache or from the remote.\n    public let fromCache: Bool\n    /// Indicates whether the package was already present in the cache and updated or if a clean fetch was\n    /// performed.\n    public let updatedCache: Bool\n}\n\n/// A workspace represents the state of a working project directory.\n///\n/// The workspace is responsible for managing the persistent working state of a\n/// project directory (e.g., the active set of checked out repositories) and for\n/// coordinating the changes to that state.\n///\n/// This class glues together the basic facilities provided by the dependency\n/// resolution, source control, and package graph loading subsystems into a\n/// cohesive interface for exposing the high-level operations for the package\n/// manager to maintain working package directories.\n///\n/// This class does *not* support concurrent operations.\npublic class Workspace {\n    public typealias Delegate = WorkspaceDelegate\n\n    /// The delegate interface.\n    private(set) weak var delegate: Delegate?\n\n    /// The workspace location.\n    public let location: Location\n\n    /// The mirrors config.\n    let mirrors: DependencyMirrors\n\n    /// The current persisted state of the workspace.\n    // public visibility for testing\n    public let state: WorkspaceState\n\n    // `public` visibility for testing\n    @available(\n        *,\n        deprecated,\n        renamed: \"resolvedPackagesStore\",\n        message: \"Renamed for consistency with the actual name of the feature\"\n    )\n    public var pinsStore: LoadableResult<PinsStore> { self.resolvedPackagesStore }\n\n    /// The `Package.resolved` store. The `Package.resolved` file will be created when first resolved package is added\n    /// to the store.\n    package let resolvedPackagesStore: LoadableResult<ResolvedPackagesStore>\n\n    ///  Computed enabled traits per package in the workspace\n    public var enabledTraitsMap: EnabledTraitsMap = [:]\n\n    /// The file system on which the workspace will operate.\n    package let fileSystem: any FileSystem\n\n    /// The host toolchain to use.\n    let hostToolchain: UserToolchain\n\n    /// The manifest loader to use.\n    let manifestLoader: ManifestLoaderProtocol\n\n    /// The tools version currently in use.\n    let currentToolsVersion: ToolsVersion\n\n    /// Utility to resolve package identifiers\n    // var for backwards compatibility with deprecated initializers, remove with them\n    let identityResolver: IdentityResolver\n\n    /// Utility to map dependencies\n    let dependencyMapper: DependencyMapper\n\n    /// The custom package container provider used by this workspace, if any.\n    let customPackageContainerProvider: PackageContainerProvider?\n\n    /// The package container provider used by this workspace.\n    var packageContainerProvider: PackageContainerProvider {\n        self.customPackageContainerProvider ?? self\n    }\n\n    /// Source control repository manager used for interacting with source control based dependencies\n    let repositoryManager: RepositoryManager\n\n    /// The registry manager.\n    let registryClient: RegistryClient\n\n    /// Registry based dependencies downloads manager used for interacting with registry based dependencies\n    let registryDownloadsManager: RegistryDownloadsManager\n\n    /// Binary artifacts manager used for downloading and extracting binary artifacts\n    let binaryArtifactsManager: BinaryArtifactsManager\n\n    /// Prebuilts manager used for downloading and extracting package prebuilt libraries\n    let prebuiltsManager: PrebuiltsManager?\n\n    /// The package fingerprints storage\n    let fingerprints: PackageFingerprintStorage?\n\n    /// The workspace configuration settings\n    let configuration: WorkspaceConfiguration\n\n    /// The trait configuration as described in the Workspace's configuration.\n    public var traitConfiguration: TraitConfiguration {\n        configuration.traitConfiguration\n    }\n\n    // MARK: State\n\n    /// The active package resolver. This is set during a dependency resolution operation.\n    var activeResolver: PubGrubDependencyResolver?\n\n    var resolvedFileWatcher: ResolvedFileWatcher?\n\n    /// Create a new package workspace.\n    ///\n    /// This initializer is designed for use cases when the workspace needs to be highly customized such as testing.\n    /// In other cases, use the other, more straight forward, initializers\n    ///\n    /// This will automatically load the persisted state for the package, if\n    /// present. If the state isn't present then a default state will be\n    /// constructed.\n    ///\n    /// - Parameters:\n    ///   - fileSystem: The file system to use.\n    ///   - location: Workspace location configuration.\n    ///   - authorizationProvider: Provider of authentication information for outbound network requests.\n    ///   - registryAuthorizationProvider: Provider of authentication information for registry requests.\n    ///   - configuration: Configuration to fine tune the dependency resolution behavior.\n    ///   - cancellator: Cancellation handler\n    ///   - initializationWarningHandler: Initialization warnings handler\n    ///   - customHostToolchain: Custom host toolchain. Used to create a customized ManifestLoader, customizing how\n    /// manifest are loaded.\n    ///   - customManifestLoader: Custom manifest loader. Used to customize how manifest are loaded.\n    ///   - customPackageContainerProvider: Custom package container provider. Used to provide specialized package\n    /// providers.\n    ///   - customRepositoryProvider: Custom repository provider. Used to customize source control access.\n    ///   - delegate: Delegate for workspace events\n    public convenience init(\n        fileSystem: any FileSystem,\n        environment: Environment = .current,\n        location: Location,\n        authorizationProvider: (any AuthorizationProvider)? = .none,\n        registryAuthorizationProvider: (any AuthorizationProvider)? = .none,\n        configuration: WorkspaceConfiguration? = .none,\n        cancellator: Cancellator? = .none,\n        initializationWarningHandler: ((String) -> Void)? = .none,\n        // optional customization used for advanced integration situations\n        customHostToolchain: UserToolchain? = .none,\n        customManifestLoader: (any ManifestLoaderProtocol)? = .none,\n        customPackageContainerProvider: (any PackageContainerProvider)? = .none,\n        customRepositoryProvider: (any RepositoryProvider)? = .none,\n        // delegate\n        delegate: Delegate? = .none\n    ) throws {\n        try self.init(\n            fileSystem: fileSystem,\n            environment: environment,\n            location: location,\n            authorizationProvider: authorizationProvider,\n            registryAuthorizationProvider: registryAuthorizationProvider,\n            configuration: configuration,\n            cancellator: cancellator,\n            initializationWarningHandler: initializationWarningHandler,\n            customRegistriesConfiguration: .none,\n            customFingerprints: .none,\n            customSigningEntities: .none,\n            skipSignatureValidation: false,\n            customMirrors: .none,\n            customToolsVersion: .none,\n            customHostToolchain: customHostToolchain,\n            customManifestLoader: customManifestLoader,\n            customPackageContainerProvider: customPackageContainerProvider,\n            customRepositoryManager: .none,\n            customRepositoryProvider: customRepositoryProvider,\n            customRegistryClient: .none,\n            customBinaryArtifactsManager: .none,\n            customPrebuiltsManager: .none,\n            customIdentityResolver: .none,\n            customDependencyMapper: .none,\n            customChecksumAlgorithm: .none,\n            delegate: delegate\n        )\n    }\n\n    /// A convenience method for creating a workspace for the given root\n    /// package path.\n    ///\n    /// The root package path is used to compute the build directory and other\n    /// default paths.\n    ///\n    /// - Parameters:\n    ///   - fileSystem: The file system to use, defaults to local file system.\n    ///   - forRootPackage: The path for the root package.\n    ///   - authorizationProvider: Provider of authentication information for outbound network requests.\n    ///   - registryAuthorizationProvider: Provider of authentication information for registry requests.\n    ///   - configuration: Configuration to fine tune the dependency resolution behavior.\n    ///   - cancellator: Cancellation handler\n    ///   - initializationWarningHandler: Initialization warnings handler\n    ///   - customManifestLoader: Custom manifest loader. Used to customize how manifest are loaded.\n    ///   - customPackageContainerProvider: Custom package container provider. Used to provide specialized package\n    /// providers.\n    ///   - customRepositoryProvider: Custom repository provider. Used to customize source control access.\n    ///   - delegate: Delegate for workspace events\n    public convenience init(\n        fileSystem: FileSystem? = .none,\n        environment: Environment = .current,\n        forRootPackage packagePath: AbsolutePath,\n        authorizationProvider: AuthorizationProvider? = .none,\n        registryAuthorizationProvider: AuthorizationProvider? = .none,\n        configuration: WorkspaceConfiguration? = .none,\n        cancellator: Cancellator? = .none,\n        initializationWarningHandler: ((String) -> Void)? = .none,\n        // optional customization used for advanced integration situations\n        customHostToolchain: UserToolchain? = .none,\n        customManifestLoader: ManifestLoaderProtocol? = .none,\n        customPackageContainerProvider: PackageContainerProvider? = .none,\n        customRepositoryProvider: RepositoryProvider? = .none,\n        // delegate\n        delegate: Delegate? = .none\n    ) throws {\n        let fileSystem = fileSystem ?? localFileSystem\n        let location = try Location(forRootPackage: packagePath, fileSystem: fileSystem)\n        try self.init(\n            fileSystem: fileSystem,\n            environment: environment,\n            location: location,\n            authorizationProvider: authorizationProvider,\n            registryAuthorizationProvider: registryAuthorizationProvider,\n            configuration: configuration,\n            cancellator: cancellator,\n            initializationWarningHandler: initializationWarningHandler,\n            customHostToolchain: customHostToolchain,\n            customManifestLoader: customManifestLoader,\n            customPackageContainerProvider: customPackageContainerProvider,\n            customRepositoryProvider: customRepositoryProvider,\n            delegate: delegate\n        )\n    }\n\n    /// A convenience method for creating a workspace for the given root\n    /// package path.\n    ///\n    /// The root package path is used to compute the build directory and other\n    /// default paths.\n    ///\n    /// - Parameters:\n    ///   - fileSystem: The file system to use, defaults to local file system.\n    ///   - forRootPackage: The path for the root package.\n    ///   - authorizationProvider: Provider of authentication information for outbound network requests.\n    ///   - registryAuthorizationProvider: Provider of authentication information for registry requests.\n    ///   - configuration: Configuration to fine tune the dependency resolution behavior.\n    ///   - cancellator: Cancellation handler\n    ///   - initializationWarningHandler: Initialization warnings handler\n    ///   - customHostToolchain: Custom host toolchain. Used to create a customized ManifestLoader, customizing how\n    /// manifest are loaded.\n    ///   - customPackageContainerProvider: Custom package container provider. Used to provide specialized package\n    /// providers.\n    ///   - customRepositoryProvider: Custom repository provider. Used to customize source control access.\n    ///   - delegate: Delegate for workspace events\n    public convenience init(\n        fileSystem: FileSystem? = .none,\n        forRootPackage packagePath: AbsolutePath,\n        authorizationProvider: AuthorizationProvider? = .none,\n        registryAuthorizationProvider: AuthorizationProvider? = .none,\n        configuration: WorkspaceConfiguration? = .none,\n        cancellator: Cancellator? = .none,\n        initializationWarningHandler: ((String) -> Void)? = .none,\n        // optional customization used for advanced integration situations\n        customHostToolchain: UserToolchain,\n        customPackageContainerProvider: PackageContainerProvider? = .none,\n        customRepositoryProvider: RepositoryProvider? = .none,\n        // delegate\n        delegate: Delegate? = .none\n    ) throws {\n        let fileSystem = fileSystem ?? localFileSystem\n        let location = try Location(forRootPackage: packagePath, fileSystem: fileSystem)\n        let manifestLoader = ManifestLoader(\n            toolchain: customHostToolchain,\n            cacheDir: location.sharedManifestsCacheDirectory,\n            importRestrictions: configuration?.manifestImportRestrictions,\n            delegate: delegate.map(WorkspaceManifestLoaderDelegate.init(workspaceDelegate:)),\n            pruneDependencies: configuration?.pruneDependencies ?? false\n        )\n        try self.init(\n            fileSystem: fileSystem,\n            location: location,\n            authorizationProvider: authorizationProvider,\n            registryAuthorizationProvider: registryAuthorizationProvider,\n            configuration: configuration,\n            cancellator: cancellator,\n            initializationWarningHandler: initializationWarningHandler,\n            customHostToolchain: customHostToolchain,\n            customManifestLoader: manifestLoader,\n            customPackageContainerProvider: customPackageContainerProvider,\n            customRepositoryProvider: customRepositoryProvider,\n            delegate: delegate\n        )\n    }\n\n    /// Initializer for testing purposes only. Use non underscored initializers instead.\n    // this initializer is only public because of cross module visibility (eg MockWorkspace)\n    // as such it is by design an exact mirror of the private initializer below\n    public static func _init(\n        // core\n        fileSystem: FileSystem,\n        environment: Environment,\n        location: Location,\n        authorizationProvider: AuthorizationProvider? = .none,\n        registryAuthorizationProvider: AuthorizationProvider? = .none,\n        configuration: WorkspaceConfiguration? = .none,\n        cancellator: Cancellator? = .none,\n        initializationWarningHandler: ((String) -> Void)? = .none,\n        // optional customization, primarily designed for testing but also used in some cases by libSwiftPM consumers\n        customRegistriesConfiguration: RegistryConfiguration? = .none,\n        customFingerprints: PackageFingerprintStorage? = .none,\n        customSigningEntities: PackageSigningEntityStorage? = .none,\n        skipSignatureValidation: Bool = false,\n        customMirrors: DependencyMirrors? = .none,\n        customToolsVersion: ToolsVersion? = .none,\n        customHostToolchain: UserToolchain? = .none,\n        customManifestLoader: ManifestLoaderProtocol? = .none,\n        customPackageContainerProvider: PackageContainerProvider? = .none,\n        customRepositoryManager: RepositoryManager? = .none,\n        customRepositoryProvider: RepositoryProvider? = .none,\n        customRegistryClient: RegistryClient? = .none,\n        customBinaryArtifactsManager: CustomBinaryArtifactsManager? = .none,\n        customPrebuiltsManager: CustomPrebuiltsManager? = .none,\n        customIdentityResolver: IdentityResolver? = .none,\n        customDependencyMapper: DependencyMapper? = .none,\n        customChecksumAlgorithm: HashAlgorithm? = .none,\n        // delegate\n        delegate: Delegate? = .none\n    ) throws -> Workspace {\n        try .init(\n            fileSystem: fileSystem,\n            environment: environment,\n            location: location,\n            authorizationProvider: authorizationProvider,\n            registryAuthorizationProvider: registryAuthorizationProvider,\n            configuration: configuration,\n            cancellator: cancellator,\n            initializationWarningHandler: initializationWarningHandler,\n            customRegistriesConfiguration: customRegistriesConfiguration,\n            customFingerprints: customFingerprints,\n            customSigningEntities: customSigningEntities,\n            skipSignatureValidation: skipSignatureValidation,\n            customMirrors: customMirrors,\n            customToolsVersion: customToolsVersion,\n            customHostToolchain: customHostToolchain,\n            customManifestLoader: customManifestLoader,\n            customPackageContainerProvider: customPackageContainerProvider,\n            customRepositoryManager: customRepositoryManager,\n            customRepositoryProvider: customRepositoryProvider,\n            customRegistryClient: customRegistryClient,\n            customBinaryArtifactsManager: customBinaryArtifactsManager,\n            customPrebuiltsManager: customPrebuiltsManager,\n            customIdentityResolver: customIdentityResolver,\n            customDependencyMapper: customDependencyMapper,\n            customChecksumAlgorithm: customChecksumAlgorithm,\n            delegate: delegate\n        )\n    }\n\n    private convenience init(\n        // core\n        fileSystem: FileSystem,\n        environment: Environment,\n        location: Location,\n        authorizationProvider: AuthorizationProvider?,\n        registryAuthorizationProvider: AuthorizationProvider?,\n        configuration: WorkspaceConfiguration?,\n        cancellator: Cancellator?,\n        initializationWarningHandler: ((String) -> Void)?,\n        // optional customization, primarily designed for testing but also used in some cases by libSwiftPM consumers\n        customRegistriesConfiguration: RegistryConfiguration?,\n        customFingerprints: PackageFingerprintStorage?,\n        customSigningEntities: PackageSigningEntityStorage?,\n        skipSignatureValidation: Bool,\n        customMirrors: DependencyMirrors?,\n        customToolsVersion: ToolsVersion?,\n        customHostToolchain: UserToolchain?,\n        customManifestLoader: ManifestLoaderProtocol?,\n        customPackageContainerProvider: PackageContainerProvider?,\n        customRepositoryManager: RepositoryManager?,\n        customRepositoryProvider: RepositoryProvider?,\n        customRegistryClient: RegistryClient?,\n        customBinaryArtifactsManager: CustomBinaryArtifactsManager?,\n        customPrebuiltsManager: CustomPrebuiltsManager?,\n        customIdentityResolver: IdentityResolver?,\n        customDependencyMapper: DependencyMapper?,\n        customChecksumAlgorithm: HashAlgorithm?,\n        // delegate\n        delegate: Delegate?\n    ) throws {\n        // we do not store an observabilityScope in the workspace initializer as the workspace is designed to be long\n        // lived.\n        // instead, observabilityScope is passed into the individual workspace methods which are short lived.\n        let initializationWarningHandler = initializationWarningHandler ?? warnToStderr\n        // validate locations, returning a potentially modified one to deal with non-accessible or non-writable shared\n        // locations\n        let location = try location.validatingSharedLocations(\n            fileSystem: fileSystem,\n            warningHandler: initializationWarningHandler\n        )\n\n        let currentToolsVersion = customToolsVersion ?? ToolsVersion.current\n        let hostToolchain = try customHostToolchain ?? UserToolchain(\n            swiftSDK: .hostSwiftSDK(\n                environment: environment\n            ),\n            environment: environment,\n            fileSystem: fileSystem\n        )\n        var manifestLoader = customManifestLoader ?? ManifestLoader(\n            toolchain: hostToolchain,\n            cacheDir: location.sharedManifestsCacheDirectory,\n            importRestrictions: configuration?.manifestImportRestrictions,\n            pruneDependencies: configuration?.pruneDependencies ?? false\n        )\n        // set delegate if not set\n        if let manifestLoader = manifestLoader as? ManifestLoader, manifestLoader.delegate == nil {\n            manifestLoader.delegate = delegate.map(WorkspaceManifestLoaderDelegate.init(workspaceDelegate:))\n        }\n\n        let configuration = configuration ?? .default\n\n        let mirrors = try customMirrors ?? Workspace.Configuration.Mirrors(\n            fileSystem: fileSystem,\n            localMirrorsFile: location.localMirrorsConfigurationFile,\n            sharedMirrorsFile: location.sharedMirrorsConfigurationFile\n        ).mirrors\n\n        let identityResolver = customIdentityResolver ?? DefaultIdentityResolver(\n            locationMapper: mirrors.effective(for:),\n            identityMapper: mirrors.effectiveIdentity(for:)\n        )\n        let dependencyMapper = customDependencyMapper ?? DefaultDependencyMapper(identityResolver: identityResolver)\n        let checksumAlgorithm = customChecksumAlgorithm ?? SHA256()\n\n        let repositoryProvider = customRepositoryProvider ?? GitRepositoryProvider()\n        let repositoryManager = customRepositoryManager ?? RepositoryManager(\n            fileSystem: fileSystem,\n            path: location.repositoriesDirectory,\n            provider: repositoryProvider,\n            cachePath: configuration.sharedDependenciesCacheEnabled ? location.sharedRepositoriesCacheDirectory : .none,\n            initializationWarningHandler: initializationWarningHandler,\n            delegate: delegate.map(WorkspaceRepositoryManagerDelegate.init(workspaceDelegate:))\n        )\n        // register the source control dependencies fetcher with the cancellation handler\n        cancellator?.register(name: \"repository fetching\", handler: repositoryManager)\n\n        let fingerprints = customFingerprints ?? location.sharedFingerprintsDirectory.map {\n            FilePackageFingerprintStorage(\n                fileSystem: fileSystem,\n                directoryPath: $0\n            )\n        }\n\n        let signingEntities = customSigningEntities ?? location.sharedSigningEntitiesDirectory.map {\n            FilePackageSigningEntityStorage(\n                fileSystem: fileSystem,\n                directoryPath: $0\n            )\n        }\n\n        let registriesConfiguration = try customRegistriesConfiguration ?? Workspace.Configuration.Registries(\n            fileSystem: fileSystem,\n            localRegistriesFile: location.localRegistriesConfigurationFile,\n            sharedRegistriesFile: location.sharedRegistriesConfigurationFile\n        ).configuration\n\n        let registryClient = customRegistryClient ?? RegistryClient(\n            configuration: registriesConfiguration,\n            fingerprintStorage: fingerprints,\n            fingerprintCheckingMode: FingerprintCheckingMode.map(configuration.fingerprintCheckingMode),\n            skipSignatureValidation: skipSignatureValidation,\n            signingEntityStorage: signingEntities,\n            signingEntityCheckingMode: SigningEntityCheckingMode.map(configuration.signingEntityCheckingMode),\n            authorizationProvider: registryAuthorizationProvider,\n            delegate: WorkspaceRegistryClientDelegate(workspaceDelegate: delegate),\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        // set default registry if not already set by configuration\n        if registryClient.defaultRegistry == nil, let defaultRegistry = configuration.defaultRegistry {\n            registryClient.defaultRegistry = defaultRegistry\n        }\n\n        let registryDownloadsManager = RegistryDownloadsManager(\n            fileSystem: fileSystem,\n            path: location.registryDownloadDirectory,\n            cachePath: configuration.sharedDependenciesCacheEnabled ? location\n                .sharedRegistryDownloadsCacheDirectory : .none,\n            registryClient: registryClient,\n            delegate: delegate.map(WorkspaceRegistryDownloadsManagerDelegate.init(workspaceDelegate:))\n        )\n        // register the registry dependencies downloader with the cancellation handler\n        cancellator?.register(name: \"registry downloads\", handler: registryDownloadsManager)\n\n        if let transformationMode = RegistryAwareManifestLoader\n            .TransformationMode(configuration.sourceControlToRegistryDependencyTransformation)\n        {\n            manifestLoader = RegistryAwareManifestLoader(\n                underlying: manifestLoader,\n                registryClient: registryClient,\n                transformationMode: transformationMode\n            )\n        }\n\n        let binaryArtifactsManager = BinaryArtifactsManager(\n            fileSystem: fileSystem,\n            authorizationProvider: authorizationProvider,\n            hostToolchain: hostToolchain,\n            checksumAlgorithm: checksumAlgorithm,\n            cachePath: customBinaryArtifactsManager?.useCache == false || !configuration\n                .sharedDependenciesCacheEnabled ? .none : location.sharedBinaryArtifactsCacheDirectory,\n            customHTTPClient: customBinaryArtifactsManager?.httpClient,\n            customArchiver: customBinaryArtifactsManager?.archiver,\n            delegate: delegate.map(WorkspaceBinaryArtifactsManagerDelegate.init(workspaceDelegate:))\n        )\n        // register the binary artifacts downloader with the cancellation handler\n        cancellator?.register(name: \"binary artifacts downloads\", handler: binaryArtifactsManager)\n\n        var prebuiltsManager: PrebuiltsManager?\n        if configuration.usePrebuilts,\n           let hostPlatform = customPrebuiltsManager?.hostPlatform ?? PrebuiltsPlatform.hostPlatform\n        {\n            let rootCertPath: AbsolutePath?\n            if let path = configuration.prebuiltsRootCertPath {\n                rootCertPath = try AbsolutePath(validating: path)\n            } else {\n                rootCertPath = nil\n            }\n\n            let prebuiltsManagerObj = PrebuiltsManager(\n                fileSystem: fileSystem,\n                hostPlatform: hostPlatform,\n                authorizationProvider: authorizationProvider,\n                scratchPath: location.prebuiltsDirectory,\n                cachePath: customPrebuiltsManager?.useCache == false || !configuration.sharedDependenciesCacheEnabled ? .none : location.sharedPrebuiltsCacheDirectory,\n                customSwiftCompilerVersion: customPrebuiltsManager?.swiftVersion,\n                customHTTPClient: customPrebuiltsManager?.httpClient,\n                customArchiver: customPrebuiltsManager?.archiver,\n                delegate: delegate.map(WorkspacePrebuiltsManagerDelegate.init(workspaceDelegate:)),\n                prebuiltsDownloadURL: configuration.prebuiltsDownloadURL,\n                rootCertPath: customPrebuiltsManager?.rootCertPath ?? rootCertPath\n            )\n            cancellator?.register(name: \"package prebuilts downloads\", handler: prebuiltsManagerObj)\n            prebuiltsManager = prebuiltsManagerObj\n        } else {\n            prebuiltsManager = nil\n        }\n\n        // initialize\n        let resolvedPackagesStore = LoadableResult {\n            try ResolvedPackagesStore(\n                packageResolvedFile: location.resolvedVersionsFile,\n                workingDirectory: location.scratchDirectory,\n                fileSystem: fileSystem,\n                mirrors: mirrors\n            )\n        }\n\n        let state = WorkspaceState(\n            fileSystem: fileSystem,\n            storageDirectory: location.scratchDirectory,\n            initializationWarningHandler: initializationWarningHandler\n        )\n\n        self.init(\n            fileSystem: fileSystem,\n            configuration: configuration,\n            location: location,\n            delegate: delegate,\n            mirrors: mirrors,\n            hostToolchain: hostToolchain,\n            manifestLoader: manifestLoader,\n            currentToolsVersion: currentToolsVersion,\n            customPackageContainerProvider: customPackageContainerProvider,\n            repositoryManager: repositoryManager,\n            registryClient: registryClient,\n            registryDownloadsManager: registryDownloadsManager,\n            binaryArtifactsManager: binaryArtifactsManager,\n            identityResolver: identityResolver,\n            dependencyMapper: dependencyMapper,\n            fingerprints: fingerprints,\n            resolvedPackagesStore: resolvedPackagesStore,\n            prebuiltsManager: prebuiltsManager,\n            state: state\n        )\n    }\n\n    private init(\n        fileSystem: any FileSystem,\n        configuration: WorkspaceConfiguration,\n        location: Location,\n        delegate: Delegate?,\n        mirrors: DependencyMirrors,\n        hostToolchain: UserToolchain,\n        manifestLoader: ManifestLoaderProtocol,\n        currentToolsVersion: ToolsVersion,\n        customPackageContainerProvider: PackageContainerProvider?,\n        repositoryManager: RepositoryManager,\n        registryClient: RegistryClient,\n        registryDownloadsManager: RegistryDownloadsManager,\n        binaryArtifactsManager: BinaryArtifactsManager,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fingerprints: PackageFingerprintStorage?,\n        resolvedPackagesStore: LoadableResult<ResolvedPackagesStore>,\n        prebuiltsManager: PrebuiltsManager?,\n        state: WorkspaceState\n    ) {\n        self.fileSystem = fileSystem\n        self.configuration = configuration\n        self.location = location\n        self.delegate = delegate\n        self.mirrors = mirrors\n\n        self.hostToolchain = hostToolchain\n        self.manifestLoader = manifestLoader\n        self.currentToolsVersion = currentToolsVersion\n\n        self.customPackageContainerProvider = customPackageContainerProvider\n        self.repositoryManager = repositoryManager\n        self.registryClient = registryClient\n        self.registryDownloadsManager = registryDownloadsManager\n        self.binaryArtifactsManager = binaryArtifactsManager\n\n        self.identityResolver = identityResolver\n        self.dependencyMapper = dependencyMapper\n        self.fingerprints = fingerprints\n\n        self.resolvedPackagesStore = resolvedPackagesStore\n        self.prebuiltsManager = prebuiltsManager\n\n        self.state = state\n    }\n}\n\n// MARK: - Public API\n\nextension Workspace {\n    /// Puts a dependency in edit mode creating a checkout in editables directory.\n    ///\n    /// - Parameters:\n    ///     - packageIdentity: The identity of the package to edit.\n    ///     - path: If provided, creates or uses the checkout at this location.\n    ///     - revision: If provided, the revision at which the dependency\n    ///       should be checked out to otherwise current revision.\n    ///     - checkoutBranch: If provided, a new branch with this name will be\n    ///       created from the revision provided.\n    ///     - observabilityScope: The observability scope that reports errors, warnings, etc\n    public func edit(\n        packageIdentity: String,\n        path: AbsolutePath? = nil,\n        revision: Revision? = nil,\n        checkoutBranch: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) async {\n        do {\n            try await self._edit(\n                packageIdentity: packageIdentity,\n                path: path,\n                revision: revision,\n                checkoutBranch: checkoutBranch,\n                observabilityScope: observabilityScope\n            )\n        } catch {\n            observabilityScope.emit(error)\n        }\n    }\n\n    /// Ends the edit mode of an edited dependency.\n    ///\n    /// This will re-resolve the dependencies after ending edit as the original\n    /// checkout may be outdated.\n    ///\n    /// - Parameters:\n    ///     - packageName: The name of the package to edit.\n    ///     - forceRemove: If true, the dependency will be unedited even if has unpushed\n    ///           or uncommitted changes. Otherwise will throw respective errors.\n    ///     - root: The workspace root. This is used to resolve the dependencies post unediting.\n    ///     - observabilityScope: The observability scope that reports errors, warnings, etc\n    public func unedit(\n        packageIdentity: String,\n        forceRemove: Bool,\n        root: PackageGraphRootInput,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        guard let dependency = await self.state.dependencies[.plain(packageIdentity)] else {\n            observabilityScope.emit(.dependencyNotFound(packageName: packageIdentity))\n            return\n        }\n\n        let observabilityScope = observabilityScope.makeChildScope(\n            description: \"editing package\",\n            metadata: dependency.packageRef.diagnosticsMetadata\n        )\n\n        try await self.unedit(\n            dependency: dependency,\n            forceRemove: forceRemove,\n            root: root,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Perform dependency resolution if needed.\n    ///\n    /// This method will perform dependency resolution based on the root\n    /// manifests and `Package.resolved` file. `Package.resolved` values are respected as long as they are\n    /// satisfied by the root manifest closure requirements.  Any outdated\n    /// checkout will be restored according to its resolved package.\n    public func resolve(\n        root: PackageGraphRootInput,\n        explicitProduct: String? = .none,\n        forceResolution: Bool = false,\n        forceResolvedVersions: Bool = false,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        try await self._resolve(\n            root: root,\n            explicitProduct: explicitProduct,\n            resolvedFileStrategy: forceResolvedVersions ? .lockFile : forceResolution ? .update(forceResolution: true) :\n                .bestEffort,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Resolve a package at the given state.\n    ///\n    /// Only one of version, branch and revision will be used and in the same\n    /// order. If none of these is provided, the dependency will be resolved to\n    /// the current checkout state.\n    ///\n    /// - Parameters:\n    ///   - packageName: The name of the package which is being resolved.\n    ///   - root: The workspace's root input.\n    ///   - version: The version to resolve to.\n    ///   - branch: The branch to resolve to.\n    ///   - revision: The revision to resolve to.\n    ///   - observabilityScope: The observability scope that reports errors, warnings, etc\n    public func resolve(\n        packageName: String,\n        root: PackageGraphRootInput,\n        version: Version? = nil,\n        branch: String? = nil,\n        revision: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        // Look up the dependency and check if we can pin it.\n        guard let dependency = await self.state.dependencies[.plain(packageName)] else {\n            throw StringError(\"dependency '\\(packageName)' was not found\")\n        }\n\n        let observabilityScope = observabilityScope.makeChildScope(\n            description: \"editing package\",\n            metadata: dependency.packageRef.diagnosticsMetadata\n        )\n\n        let defaultRequirement: PackageRequirement\n        switch dependency.state {\n        case .sourceControlCheckout(let checkoutState):\n            defaultRequirement = checkoutState.requirement\n        case .registryDownload(let version), .custom(let version, _):\n            defaultRequirement = .versionSet(.exact(version))\n        case .fileSystem:\n            throw StringError(\"local dependency '\\(dependency.packageRef.identity)' can't be resolved\")\n        case .edited:\n            throw StringError(\"edited dependency '\\(dependency.packageRef.identity)' can't be resolved\")\n        }\n\n        // Compute the custom or extra constraint we need to impose.\n        let requirement: PackageRequirement = if let version {\n            .versionSet(.exact(version))\n        } else if let branch {\n            .revision(branch)\n        } else if let revision {\n            .revision(revision)\n        } else {\n            defaultRequirement\n        }\n\n        // If any products are required, the rest of the package graph will supply those constraints.\n        let constraint = PackageContainerConstraint(\n            package: dependency.packageRef,\n            requirement: requirement,\n            products: .nothing,\n            enabledTraits: self.enabledTraitsMap[dependency.packageRef.identity]\n        )\n\n        // Run the resolution.\n        try await self.resolveAndUpdateResolvedFile(\n            root: root,\n            forceResolution: false,\n            constraints: [constraint],\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Resolves the dependencies according to the entries present in the Package.resolved file.\n    ///\n    /// This method bypasses the dependency resolution and resolves dependencies\n    /// according to the information in the resolved file.\n    public func resolveBasedOnResolvedVersionsFile(\n        root: PackageGraphRootInput,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        try await self._resolveBasedOnResolvedVersionsFile(\n            root: root,\n            explicitProduct: .none,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Cleans the build artifacts from workspace data.\n    ///\n    /// - Parameters:\n    ///     - observabilityScope: The observability scope that reports errors, warnings, etc\n    public func clean(observabilityScope: ObservabilityScope) {\n        // These are the things we don't want to remove while cleaning.\n        let protectedAssets = [\n            self.repositoryManager.path,\n            self.location.repositoriesCheckoutsDirectory,\n            self.location.artifactsDirectory,\n            self.state.storagePath,\n        ].map { path -> String in\n            // Assert that these are present inside data directory.\n            assert(path.parentDirectory == self.location.scratchDirectory)\n            return path.basename\n        }\n\n        // If we have no data yet, we're done.\n        guard self.fileSystem.exists(self.location.scratchDirectory) else {\n            return\n        }\n\n        guard let contents = observabilityScope\n            .trap({ try fileSystem.getDirectoryContents(self.location.scratchDirectory) })\n        else {\n            return\n        }\n\n        // Remove all but protected paths.\n        let contentsToRemove = Set(contents).subtracting(protectedAssets)\n        for name in contentsToRemove {\n            try? self.fileSystem.removeFileTree(AbsolutePath(\n                validating: name,\n                relativeTo: self.location.scratchDirectory\n            ))\n        }\n    }\n\n    /// Resets the entire workspace by removing the data directory.\n    ///\n    /// - Parameters:\n    ///     - observabilityScope: The observability scope that reports errors, warnings, etc\n    public func reset(observabilityScope: ObservabilityScope) async {\n        let removed = await observabilityScope.trap { () -> Bool in\n            try self.fileSystem.chmod(\n                .userWritable,\n                path: self.location.repositoriesCheckoutsDirectory,\n                options: [.recursive, .onlyFiles]\n            )\n            // Reset state.\n            try await self.resetState()\n            return true\n        }\n\n        guard removed ?? false else {\n            return\n        }\n\n        self.repositoryManager.reset(observabilityScope: observabilityScope)\n        self.registryDownloadsManager.reset(observabilityScope: observabilityScope)\n        await self.manifestLoader.resetCache(observabilityScope: observabilityScope)\n        do {\n            try self.fileSystem.removeFileTree(self.location.scratchDirectory)\n        } catch {\n            observabilityScope.emit(\n                error: \"Error removing scratch directory at '\\(self.location.scratchDirectory)'\",\n                underlyingError: error\n            )\n        }\n    }\n\n    // FIXME: @testable internal\n    public func resetState() async throws {\n        try await self.state.reset()\n    }\n\n    /// Cancel the active dependency resolution operation.\n    public func cancelActiveResolverOperation() {\n        // FIXME: Need to add cancel support.\n    }\n\n    /// Updates the current dependencies.\n    ///\n    /// - Parameters:\n    ///     - observabilityScope: The observability scope that reports errors, warnings, etc\n    @discardableResult\n    public func updateDependencies(\n        root: PackageGraphRootInput,\n        packages: [String] = [],\n        dryRun: Bool = false,\n        observabilityScope: ObservabilityScope\n    ) async throws -> [(PackageReference, Workspace.PackageStateChange)]? {\n        try await self._updateDependencies(\n            root: root,\n            packages: packages,\n            dryRun: dryRun,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    @discardableResult\n    public func loadPackageGraph(\n        rootInput root: PackageGraphRootInput,\n        explicitProduct: String? = nil,\n        forceResolvedVersions: Bool = false,\n        customXCTestMinimumDeploymentTargets: [PackageModel.Platform: PlatformVersion]? = .none,\n        testEntryPointPath: AbsolutePath? = nil,\n        expectedSigningEntities: [PackageIdentity: RegistryReleaseMetadata.SigningEntity] = [:],\n        observabilityScope: ObservabilityScope\n    ) async throws -> ModulesGraph {\n        let start = DispatchTime.now()\n        self.delegate?.willLoadGraph()\n        defer {\n            self.delegate?.didLoadGraph(duration: start.distance(to: .now()))\n        }\n\n        // reload state in case it was modified externally (eg by another process) before reloading the graph\n        // long running host processes (ie IDEs) need this in case other SwiftPM processes (ie CLI) made changes to the\n        // state\n        // such hosts processes call loadPackageGraph to make sure the workspace state is correct\n        try await self.state.reload()\n\n        // Perform dependency resolution, if required.\n        let manifests = try await self._resolve(\n            root: root,\n            explicitProduct: explicitProduct,\n            resolvedFileStrategy: forceResolvedVersions ? .lockFile : .bestEffort,\n            observabilityScope: observabilityScope\n        )\n\n        let binaryArtifacts = await self.state.artifacts\n            .reduce(into: [PackageIdentity: [String: BinaryArtifact]]()) { partial, artifact in\n                partial[artifact.packageRef.identity, default: [:]][artifact.targetName] = BinaryArtifact(\n                    kind: artifact.kind,\n                    originURL: artifact.originURL,\n                    path: artifact.path\n                )\n            }\n\n        let prebuilts: [PackageIdentity: [String: PrebuiltLibrary]] = await self.state.prebuilts.reduce(into: .init()) {\n            let prebuilt = PrebuiltLibrary(\n                identity: $1.identity,\n                libraryName: $1.libraryName,\n                path: $1.path,\n                checkoutPath: $1.checkoutPath,\n                products: $1.products,\n                includePath: $1.includePath,\n                cModules: $1.cModules)\n            for product in $1.products {\n                $0[$1.identity, default: [:]][product] = prebuilt\n            }\n        }\n\n        // Load the graph.\n        let packageGraph = try ModulesGraph.load(\n            root: manifests.root,\n            identityResolver: self.identityResolver,\n            additionalFileRules: self.configuration.additionalFileRules,\n            externalManifests: manifests.allDependencyManifests,\n            requiredDependencies: manifests.requiredPackages,\n            unsafeAllowedPackages: manifests.unsafeAllowedPackages,\n            binaryArtifacts: binaryArtifacts,\n            prebuilts: prebuilts,\n            shouldCreateMultipleTestProducts: self.configuration.shouldCreateMultipleTestProducts,\n            createREPLProduct: self.configuration.createREPLProduct,\n            customXCTestMinimumDeploymentTargets: customXCTestMinimumDeploymentTargets,\n            testEntryPointPath: testEntryPointPath,\n            fileSystem: self.fileSystem,\n            observabilityScope: observabilityScope,\n            enabledTraitsMap: self.enabledTraitsMap\n        )\n\n        try self.validateSignatures(\n            packageGraph: packageGraph,\n            expectedSigningEntities: expectedSigningEntities\n        )\n\n        return packageGraph\n    }\n\n    @discardableResult\n    public func loadPackageGraph(\n        rootPath: AbsolutePath,\n        explicitProduct: String? = nil,\n        observabilityScope: ObservabilityScope\n    ) async throws -> ModulesGraph {\n        try await self.loadPackageGraph(\n            rootPath: rootPath,\n            explicitProduct: explicitProduct,\n            traitConfiguration: .default,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    @discardableResult\n    package func loadPackageGraph(\n        rootPath: AbsolutePath,\n        explicitProduct: String? = nil,\n        traitConfiguration: TraitConfiguration = .default,\n        observabilityScope: ObservabilityScope\n    ) async throws -> ModulesGraph {\n        try await self.loadPackageGraph(\n            rootInput: PackageGraphRootInput(packages: [rootPath], traitConfiguration: traitConfiguration),\n            explicitProduct: explicitProduct,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    /// Loads and returns manifests at the given paths.\n    public func loadRootManifests(\n        packages: [AbsolutePath],\n        observabilityScope: ObservabilityScope\n    ) async throws -> [AbsolutePath: Manifest] {\n        try await withThrowingTaskGroup(of: Optional<(AbsolutePath, Manifest)>.self) { group in\n            var rootManifests = [AbsolutePath: Manifest]()\n            for package in Set(packages) {\n                group.addTask {\n                    // TODO: this does not use the identity resolver which is probably fine since its the root packages\n                    do {\n                        let manifest = try await self.loadManifest(\n                            packageIdentity: PackageIdentity(path: package),\n                            packageKind: .root(package),\n                            packagePath: package,\n                            packageLocation: package.pathString,\n                            observabilityScope: observabilityScope\n                        )\n                        return (package, manifest)\n                    } catch {\n                        // Propagate the TraitError if it exists.\n                        if let error = error as? TraitError {\n                            throw error\n                        }\n                        return nil\n                    }\n                }\n            }\n\n            // Collect the results.\n            for try await result in group {\n                if let (package, manifest) = result {\n                    // Store the manifest.\n                    rootManifests[package] = manifest\n                }\n            }\n\n\n\n            // Check for duplicate root packages after all manifests are loaded.\n            let duplicateRoots = rootManifests.values.spm_findDuplicateElements(by: \\.displayName)\n            if let firstDuplicateSet = duplicateRoots.first, let firstDuplicate = firstDuplicateSet.first {\n                observabilityScope.emit(error: \"found multiple top-level packages named '\\(firstDuplicate.displayName)'\")\n                // Decide how to handle duplicates, e.g., throw an error or return an empty dictionary.\n                // For now, matching the original behavior of returning an empty dictionary on error.\n                // Consider throwing an error instead for better error propagation.\n                return [:]\n            }\n\n            return rootManifests\n        }\n    }\n\n    /// Loads and returns manifests at the given paths.\n    @available(*, noasync, message: \"Use the async alternative\")\n    public func loadRootManifests(\n        packages: [AbsolutePath],\n        observabilityScope: ObservabilityScope,\n        completion: @escaping @Sendable (Result<[AbsolutePath: Manifest], Error>) -> Void\n    ) {\n        DispatchQueue.sharedConcurrent.asyncResult(completion) {\n            try await self.loadRootManifests(\n                packages: packages,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    /// Loads and returns manifest at the given path.\n    public func loadRootManifest(\n        at path: AbsolutePath,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Manifest {\n        try await withCheckedThrowingContinuation { continuation in\n            self.loadRootManifest(at: path, observabilityScope: observabilityScope) { result in\n                continuation.resume(with: result)\n            }\n        }\n    }\n\n    /// Loads and returns manifest at the given path.\n    public func loadRootManifest(\n        at path: AbsolutePath,\n        observabilityScope: ObservabilityScope,\n        completion: @escaping (Result<Manifest, Error>) -> Void\n    ) {\n        self.loadRootManifests(packages: [path], observabilityScope: observabilityScope) { result in\n            completion(result.tryMap {\n                // normally, we call loadRootManifests which attempts to load any manifest it can and report errors via\n                // diagnostics\n                // in this case, we want to load a specific manifest, so if the diagnostics contains an error we want to\n                // throw\n                guard !observabilityScope.errorsReported else {\n                    throw Diagnostics.fatalError\n                }\n                guard let manifest = $0[path] else {\n                    throw InternalError(\"Unknown manifest for '\\(path)'\")\n                }\n                return manifest\n            })\n        }\n    }\n\n    /// Loads root package\n    public func loadRootPackage(at path: AbsolutePath, observabilityScope: ObservabilityScope) async throws -> Package {\n        try await withCheckedThrowingContinuation { continuation in\n            self.loadRootPackage(at: path, observabilityScope: observabilityScope) { result in\n                continuation.resume(with: result)\n            }\n        }\n    }\n\n    /// Loads root package\n    public func loadRootPackage(\n        at path: AbsolutePath,\n        observabilityScope: ObservabilityScope,\n        completion: @escaping (Result<Package, Error>) -> Void\n    ) {\n        self.loadRootManifest(at: path, observabilityScope: observabilityScope) { result in\n            let result = result.tryMap { manifest -> Package in\n                let identity = try self.identityResolver.resolveIdentity(for: manifest.packageKind)\n\n                // radar/82263304\n                // compute binary artifacts for the sake of constructing a project model\n                // note this does not actually download remote artifacts and as such does not have the artifact's type\n                // or path\n                let binaryArtifacts = try manifest.targets.filter { $0.type == .binary }\n                    .reduce(into: [String: BinaryArtifact]()) { partial, target in\n                        if let path = target.path {\n                            let artifactPath = try manifest.path.parentDirectory\n                                .appending(RelativePath(validating: path))\n                            if artifactPath.extension?.lowercased() == \"zip\" {\n                                partial[target.name] = BinaryArtifact(\n                                    kind: .unknown,\n                                    originURL: .none,\n                                    path: artifactPath\n                                )\n                            } else if let (_, artifactKind) = try BinaryArtifactsManager.deriveBinaryArtifact(\n                                fileSystem: self.fileSystem,\n                                path: artifactPath,\n                                observabilityScope: observabilityScope\n                            ) {\n                                partial[target.name] = BinaryArtifact(\n                                    kind: artifactKind,\n                                    originURL: .none,\n                                    path: artifactPath\n                                )\n                            } else {\n                                throw StringError(\"\\(artifactPath) does not contain binary artifact\")\n                            }\n                        } else if let urlString = target.url {\n                            // Apply mirroring to the URL\n                            let mappedURLString = self.identityResolver.mappedLocation(for: urlString)\n                            guard let url = URL(string: mappedURLString) else {\n                                throw StringError(\"Invalid URL after mirroring: \\(mappedURLString)\")\n                            }\n                            let fakePath = try manifest.path.parentDirectory.appending(components: \"remote\", \"archive\")\n                                .appending(RelativePath(validating: url.lastPathComponent))\n                            partial[target.name] = BinaryArtifact(\n                                kind: .unknown,\n                                originURL: url.absoluteString,\n                                path: fakePath\n                            )\n                        } else {\n                            throw InternalError(\"a binary target should have either a path or a URL and a checksum\")\n                        }\n                    }\n\n                let builder = PackageBuilder(\n                    identity: identity,\n                    manifest: manifest,\n                    productFilter: .everything,\n                    path: path,\n                    additionalFileRules: [],\n                    binaryArtifacts: binaryArtifacts,\n                    fileSystem: self.fileSystem,\n                    observabilityScope: observabilityScope,\n                    enabledTraits: try manifest.enabledTraits(using: self.traitConfiguration)\n                )\n                return try builder.construct()\n            }\n            completion(result)\n        }\n    }\n\n    public func loadPluginImports(\n        packageGraph: ModulesGraph\n    ) async throws -> [PackageIdentity: [String: [String]]] {\n        let pluginTargets = packageGraph.allModules.filter { $0.type == .plugin }\n        let scanner = SwiftcImportScanner(\n            swiftCompilerEnvironment: hostToolchain.swiftCompilerEnvironment,\n            swiftCompilerFlags: self.hostToolchain\n                .swiftCompilerFlags + [\"-I\", self.hostToolchain.swiftPMLibrariesLocation.pluginLibraryPath.pathString],\n            swiftCompilerPath: self.hostToolchain.swiftCompilerPath\n        )\n        var importList = [PackageIdentity: [String: [String]]]()\n\n        for pluginTarget in pluginTargets {\n            let paths = pluginTarget.sources.paths\n            guard let pkgId = packageGraph.package(for: pluginTarget)?.identity else { continue }\n\n            if importList[pkgId] == nil {\n                importList[pkgId] = [pluginTarget.name: []]\n            } else if importList[pkgId]?[pluginTarget.name] == nil {\n                importList[pkgId]?[pluginTarget.name] = []\n            }\n\n            for path in paths {\n                let result = try await scanner.scanImports(path)\n                importList[pkgId]?[pluginTarget.name]?.append(contentsOf: result)\n            }\n        }\n        return importList\n    }\n\n    public func loadPackage(\n        with identity: PackageIdentity,\n        packageGraph: ModulesGraph,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Package {\n        guard let previousPackage = packageGraph.package(for: identity) else {\n            throw StringError(\"could not find package with identity \\(identity)\")\n        }\n\n        let manifest = try await self.loadManifest(\n            packageIdentity: identity,\n            packageKind: previousPackage.underlying.manifest.packageKind,\n            packagePath: previousPackage.path,\n            packageLocation: previousPackage.underlying.manifest.packageLocation,\n            observabilityScope: observabilityScope\n        )\n        let builder = PackageBuilder(\n            identity: identity,\n            manifest: manifest,\n            productFilter: .everything,\n            // TODO: this will not be correct when reloading a transitive dependencies if `ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION` is enabled\n            path: previousPackage.path,\n            additionalFileRules: self.configuration.additionalFileRules,\n            binaryArtifacts: packageGraph.binaryArtifacts[identity] ?? [:],\n            shouldCreateMultipleTestProducts: self.configuration.shouldCreateMultipleTestProducts,\n            createREPLProduct: self.configuration.createREPLProduct,\n            fileSystem: self.fileSystem,\n            observabilityScope: observabilityScope,\n            enabledTraits: try manifest.enabledTraits(using: self.traitConfiguration)\n        )\n        return try builder.construct()\n    }\n\n    /// Loads a single package in the context of a previously loaded graph. This can be useful for incremental loading\n    /// in a longer-lived program, like an IDE.\n    @available(*, noasync, message: \"Use the async alternative\")\n    public func loadPackage(\n        with identity: PackageIdentity,\n        packageGraph: ModulesGraph,\n        observabilityScope: ObservabilityScope,\n        completion: @escaping @Sendable (Result<Package, Error>) -> Void\n    ) {\n        DispatchQueue.sharedConcurrent.asyncResult(completion) {\n            try await self.loadPackage(\n                with: identity,\n                packageGraph: packageGraph,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    public func changeSigningEntityFromVersion(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.registryClient.changeSigningEntityFromVersion(\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            origin: origin,\n            observabilityScope: observabilityScope\n        )\n    }\n}\n\nextension Workspace {\n    /// Removes the clone and checkout of the provided specifier.\n    ///\n    /// - Parameters:\n    ///   - package: The package to remove\n    func remove(package: PackageReference) async throws {\n        guard let dependency = await self.state.dependencies[package.identity] else {\n            throw InternalError(\"trying to remove \\(package.identity) which isn't in workspace\")\n        }\n\n        // We only need to update the managed dependency structure to \"remove\"\n        // a local package.\n        //\n        // Note that we don't actually remove a local package from disk.\n        if case .fileSystem = dependency.state {\n            await self.state.remove(identity: package.identity)\n            try await self.state.save()\n            return\n        }\n\n        // Inform the delegate.\n        let repository = try? dependency.packageRef.makeRepositorySpecifier()\n        self.delegate?.removing(package: package.identity, packageLocation: repository?.location.description)\n\n        // Compute the dependency which we need to remove.\n        let dependencyToRemove: ManagedDependency\n\n        if case .edited(let _basedOn, let unmanagedPath) = dependency.state, let basedOn = _basedOn {\n            // Remove the underlying dependency for edited packages.\n            dependencyToRemove = basedOn\n            let updatedDependency = Workspace.ManagedDependency.edited(\n                packageRef: dependency.packageRef,\n                subpath: dependency.subpath,\n                basedOn: .none,\n                unmanagedPath: unmanagedPath\n            )\n            await self.state.add(dependency: updatedDependency)\n        } else {\n            dependencyToRemove = dependency\n            await self.state.remove(identity: dependencyToRemove.packageRef.identity)\n        }\n\n        switch package.kind {\n        case .root, .fileSystem:\n            break // NOOP\n        case .localSourceControl:\n            break // NOOP\n        case .remoteSourceControl:\n            try await self.removeRepository(dependency: dependencyToRemove)\n        case .registry:\n            try self.removeRegistryArchive(for: dependencyToRemove)\n        }\n\n        // Save the state.\n        try await self.state.save()\n    }\n}\n\n\n// MARK: - Utility extensions\n\nextension Workspace {\n    /// Creates and returns a copy of the current workspace with an updated configuration using the passed parameters.\n    /// - Parameters:\n    /// - traitConfiguration: A configuration of traits that will override the existing trait configuration in the WorkspaceConfiguration.\n    public func updateConfiguration(with traitConfiguration: TraitConfiguration) -> Workspace {\n        var newConfig = self.configuration\n        newConfig.traitConfiguration = traitConfiguration\n        \n        return Workspace(\n            fileSystem: self.fileSystem,\n            configuration: newConfig,\n            location: self.location,\n            delegate: self.delegate,\n            mirrors: self.mirrors,\n            hostToolchain: self.hostToolchain,\n            manifestLoader: self.manifestLoader,\n            currentToolsVersion: self.currentToolsVersion,\n            customPackageContainerProvider: self.customPackageContainerProvider,\n            repositoryManager: self.repositoryManager,\n            registryClient: self.registryClient,\n            registryDownloadsManager: self.registryDownloadsManager,\n            binaryArtifactsManager: self.binaryArtifactsManager,\n            identityResolver: self.identityResolver,\n            dependencyMapper: self.dependencyMapper,\n            fingerprints: self.fingerprints,\n            resolvedPackagesStore: self.resolvedPackagesStore,\n            prebuiltsManager: prebuiltsManager,\n            state: self.state\n        )\n    }\n}\n\nextension Workspace.ManagedArtifact {\n    fileprivate var originURL: String? {\n        switch self.source {\n        case .remote(let url, _):\n            url\n        case .local:\n            nil\n        }\n    }\n}\n\nextension PackageReference {\n    func makeRepositorySpecifier() throws -> RepositorySpecifier {\n        switch self.kind {\n        case .localSourceControl(let path):\n            return .init(path: path)\n        case .remoteSourceControl(let url):\n            return .init(url: url)\n        default:\n            throw StringError(\"invalid dependency kind \\(self.kind)\")\n        }\n    }\n}\n\n// FIXME: remove this when remove the single call site that uses it\nextension PackageDependency {\n    private var isLocal: Bool {\n        switch self {\n        case .fileSystem:\n            true\n        case .sourceControl:\n            false\n        case .registry:\n            false\n        }\n    }\n}\n\nextension Workspace {\n    public static func format(workspaceResolveReason reason: WorkspaceResolveReason) -> String {\n        guard reason != .errorsPreviouslyReported else {\n            return \"\"\n        }\n\n        var result = \"Running resolver because \"\n\n        switch reason {\n        case .forced:\n            result.append(\"it was forced\")\n        case .newPackages(let packages):\n            let dependencies = packages.lazy.map { \"'\\($0.identity)' (\\($0.kind.locationString))\" }\n                .joined(separator: \", \")\n            result.append(\"the following dependencies were added: \\(dependencies)\")\n        case .packageRequirementChange(let package, let state, let requirement):\n            result.append(\"dependency '\\(package.identity)' (\\(package.kind.locationString)) was \")\n\n            switch state {\n            case .sourceControlCheckout(let checkoutState)?:\n                switch checkoutState.requirement {\n                case .versionSet(.exact(let version)):\n                    result.append(\"resolved to '\\(version)'\")\n                case .versionSet:\n                    // Impossible\n                    break\n                case .revision(let revision):\n                    result.append(\"resolved to '\\(revision)'\")\n                case .unversioned:\n                    result.append(\"unversioned\")\n                }\n            case .registryDownload(let version)?, .custom(let version, _):\n                result.append(\"resolved to '\\(version)'\")\n            case .edited?:\n                result.append(\"edited\")\n            case .fileSystem?:\n                result.append(\"versioned\")\n            case nil:\n                result.append(\"root\")\n            }\n\n            result.append(\" but now has a \")\n\n            switch requirement {\n            case .versionSet:\n                result.append(\"different version-based\")\n            case .revision:\n                result.append(\"different revision-based\")\n            case .unversioned:\n                result.append(\"unversioned\")\n            }\n\n            result.append(\" requirement.\")\n        default:\n            result.append(\"requirements have changed.\")\n        }\n\n        return result\n    }\n}\n\nextension Workspace.Location {\n    /// Returns the path to the dependency's repository checkout directory.\n    func repositoriesCheckoutSubdirectory(for dependency: Workspace.ManagedDependency) -> AbsolutePath {\n        self.repositoriesCheckoutsDirectory.appending(dependency.subpath)\n    }\n\n    /// Returns the path to the  dependency's download directory.\n    func registryDownloadSubdirectory(for dependency: Workspace.ManagedDependency) -> AbsolutePath {\n        self.registryDownloadDirectory.appending(dependency.subpath)\n    }\n\n    /// Returns the path to the dependency's edit directory.\n    func editSubdirectory(for dependency: Workspace.ManagedDependency) -> AbsolutePath {\n        self.editsDirectory.appending(dependency.subpath)\n    }\n}\n\nextension Workspace.Location {\n    func validatingSharedLocations(\n        fileSystem: FileSystem,\n        warningHandler: @escaping (String) -> Void\n    ) throws -> Self {\n        var location = self\n\n        try location.validate(\n            keyPath: \\.sharedConfigurationDirectory,\n            fileSystem: fileSystem,\n            getOrCreateHandler: {\n                try fileSystem.getOrCreateSwiftPMConfigurationDirectory(\n                    warningHandler: self.emitDeprecatedConfigurationWarning ? warningHandler : { _ in }\n                )\n            },\n            warningHandler: warningHandler\n        )\n\n        try location.validate(\n            keyPath: \\.sharedSecurityDirectory,\n            fileSystem: fileSystem,\n            getOrCreateHandler: fileSystem.getOrCreateSwiftPMSecurityDirectory,\n            warningHandler: warningHandler\n        )\n\n        try location.validate(\n            keyPath: \\.sharedCacheDirectory,\n            fileSystem: fileSystem,\n            getOrCreateHandler: fileSystem.getOrCreateSwiftPMCacheDirectory,\n            warningHandler: warningHandler\n        )\n\n        try location.validate(\n            keyPath: \\.sharedSwiftSDKsDirectory,\n            fileSystem: fileSystem,\n            getOrCreateHandler: fileSystem.getOrCreateSwiftPMSwiftSDKsDirectory,\n            warningHandler: warningHandler\n        )\n\n        return location\n    }\n\n    mutating func validate(\n        keyPath: WritableKeyPath<Workspace.Location, AbsolutePath?>,\n        fileSystem: FileSystem,\n        getOrCreateHandler: () throws -> AbsolutePath,\n        warningHandler: @escaping (String) -> Void\n    ) throws {\n        // check that shared configuration directory is accessible, or warn + reset if not\n        if let sharedDirectory = self[keyPath: keyPath] {\n            // It may not always be possible to create default location (for example de to restricted sandbox),\n            // in which case defaultDirectory would be nil.\n            let defaultDirectory = try? getOrCreateHandler()\n            if defaultDirectory != nil, sharedDirectory != defaultDirectory {\n                // custom location _must_ be writable, throw if we cannot access it\n                guard fileSystem.isWritable(sharedDirectory) else {\n                    throw StringError(\"\\(sharedDirectory) is not accessible or not writable\")\n                }\n            } else {\n                if !fileSystem.isWritable(sharedDirectory) {\n                    self[keyPath: keyPath] = nil\n                    warningHandler(\n                        \"\\(sharedDirectory) is not accessible or not writable, disabling user-level cache features.\"\n                    )\n                }\n            }\n        }\n    }\n}\n\nprivate func warnToStderr(_ message: String) {\n    TSCBasic.stderrStream.write(\"warning: \\(message)\\n\")\n    TSCBasic.stderrStream.flush()\n}\n\n// used for manifest validation\nextension RepositoryManager: ManifestSourceControlValidator {}\n\nextension ContainerUpdateStrategy {\n    var repositoryUpdateStrategy: RepositoryUpdateStrategy {\n        switch self {\n        case .always:\n            .always\n        case .never:\n            .never\n        case .ifNeeded(let revision):\n            .ifNeeded(revision: .init(identifier: revision))\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/XCBuildSupport/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(XCBuildSupport STATIC\n  PIF.swift\n  PIFBuilder.swift\n  XCBuildDelegate.swift\n  XCBuildMessage.swift\n  XCBuildOutputParser.swift\n  XcodeBuildSystem.swift)\ntarget_link_libraries(XCBuildSupport PUBLIC\n  Build\n  DriverSupport\n  TSCBasic\n  TSCUtility\n  SwiftCollections::OrderedCollections\n  PackageGraph\n)\n\nset_target_properties(XCBuildSupport PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n"
  },
  {
    "path": "Sources/XCBuildSupport/PIF.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport OrderedCollections\nimport PackageModel\n\nimport struct TSCBasic.ByteString\n\n/// The Project Interchange Format (PIF) is a structured representation of the\n/// project model created by clients (Xcode/SwiftPM) to send to XCBuild.\n///\n/// The PIF is a representation of the project model describing the static\n/// objects which contribute to building products from the project, independent\n/// of \"how\" the user has chosen to build those products in any particular\n/// build. This information can be cached by XCBuild between builds (even\n/// between builds which use different schemes or configurations), and can be\n/// incrementally updated by clients when something changes.\npublic enum PIF {\n    /// This is used as part of the signature for the high-level PIF objects, to ensure that changes to the PIF schema\n    /// are represented by the objects which do not use a content-based signature scheme (workspaces and projects,\n    /// currently).\n    static let schemaVersion = 11\n\n    /// The type used for identifying PIF objects.\n    public typealias GUID = String\n\n    /// The top-level PIF object.\n    public struct TopLevelObject: Encodable {\n        public let workspace: PIF.Workspace\n\n        public init(workspace: PIF.Workspace) {\n            self.workspace = workspace\n        }\n\n        public func encode(to encoder: Encoder) throws {\n            var container = encoder.unkeyedContainer()\n\n            // Encode the workspace.\n            try container.encode(workspace)\n\n            // Encode the projects and their targets.\n            for project in workspace.projects {\n                try container.encode(project)\n\n                for target in project.targets {\n                    try container.encode(target)\n                }\n            }\n        }\n    }\n\n    public class TypedObject: Codable {\n        class var type: String {\n            fatalError(\"\\(self) missing implementation\")\n        }\n\n        let type: String?\n\n        fileprivate init() {\n            type = Swift.type(of: self).type\n        }\n\n        private enum CodingKeys: CodingKey {\n            case type\n        }\n\n        public func encode(to encoder: Encoder) throws {\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            try container.encode(Swift.type(of: self).type, forKey: .type)\n        }\n\n        required public init(from decoder: Decoder) throws {\n            let container = try decoder.container(keyedBy: CodingKeys.self)\n            type = try container.decode(String.self, forKey: .type)\n        }\n    }\n\n    public final class Workspace: TypedObject {\n        override class var type: String { \"workspace\" }\n\n        public let guid: GUID\n        public var name: String\n        public var path: AbsolutePath\n        public var projects: [Project]\n        var signature: String?\n\n        public init(guid: GUID,  name: String, path: AbsolutePath, projects: [Project]) {\n            precondition(!guid.isEmpty)\n            precondition(!name.isEmpty)\n            precondition(Set(projects.map({ $0.guid })).count == projects.count)\n\n            self.guid = guid\n            self.name = name\n            self.path = path\n            self.projects = projects\n            super.init()\n        }\n\n        private enum CodingKeys: CodingKey {\n            case guid, name, path, projects, signature\n        }\n\n        public override func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            var container = encoder.container(keyedBy: StringKey.self)\n            var contents = container.nestedContainer(keyedBy: CodingKeys.self, forKey: \"contents\")\n            try contents.encode(\"\\(guid)@\\(schemaVersion)\", forKey: .guid)\n            try contents.encode(name, forKey: .name)\n            try contents.encode(path, forKey: .path)\n\n            if encoder.userInfo.keys.contains(.encodeForXCBuild) {\n                guard let signature else {\n                    throw InternalError(\"Expected to have workspace signature when encoding for XCBuild\")\n                }\n                try container.encode(signature, forKey: \"signature\")\n                try contents.encode(projects.map({ $0.signature }), forKey: .projects)\n            } else {\n                try contents.encode(projects, forKey: .projects)\n            }\n        }\n\n        public required init(from decoder: Decoder) throws {\n            let superContainer = try decoder.container(keyedBy: StringKey.self)\n            let container = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: \"contents\")\n\n            let guidString = try container.decode(GUID.self, forKey: .guid)\n            self.guid = String(guidString.dropLast(\"\\(schemaVersion)\".count + 1))\n            self.name = try container.decode(String.self, forKey: .name)\n            self.path = try container.decode(AbsolutePath.self, forKey: .path)\n            self.projects = try container.decode([Project].self, forKey: .projects)\n            try super.init(from: decoder)\n        }\n    }\n\n    /// A PIF project, consisting of a tree of groups and file references, a list of targets, and some additional\n    /// information.\n    public final class Project: TypedObject {\n        override class var type: String { \"project\" }\n\n        public let guid: GUID\n        public var name: String\n        public var path: AbsolutePath\n        public var projectDirectory: AbsolutePath\n        public var developmentRegion: String\n        public var buildConfigurations: [BuildConfiguration]\n        public var targets: [BaseTarget]\n        public var groupTree: Group\n        var signature: String?\n\n        public init(\n            guid: GUID,\n            name: String,\n            path: AbsolutePath,\n            projectDirectory: AbsolutePath,\n            developmentRegion: String,\n            buildConfigurations: [BuildConfiguration],\n            targets: [BaseTarget],\n            groupTree: Group\n        ) {\n            precondition(!guid.isEmpty)\n            precondition(!name.isEmpty)\n            precondition(!developmentRegion.isEmpty)\n            precondition(Set(targets.map({ $0.guid })).count == targets.count)\n            precondition(Set(buildConfigurations.map({ $0.guid })).count == buildConfigurations.count)\n\n            self.guid = guid\n            self.name = name\n            self.path = path\n            self.projectDirectory = projectDirectory\n            self.developmentRegion = developmentRegion\n            self.buildConfigurations = buildConfigurations\n            self.targets = targets\n            self.groupTree = groupTree\n            super.init()\n        }\n\n        private enum CodingKeys: CodingKey {\n            case guid, projectName, projectIsPackage, path, projectDirectory, developmentRegion, defaultConfigurationName, buildConfigurations, targets, groupTree, signature\n        }\n\n        public override func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            var container = encoder.container(keyedBy: StringKey.self)\n            var contents = container.nestedContainer(keyedBy: CodingKeys.self, forKey: \"contents\")\n            try contents.encode(\"\\(guid)@\\(schemaVersion)\", forKey: .guid)\n            try contents.encode(name, forKey: .projectName)\n            try contents.encode(\"true\", forKey: .projectIsPackage)\n            try contents.encode(path, forKey: .path)\n            try contents.encode(projectDirectory, forKey: .projectDirectory)\n            try contents.encode(developmentRegion, forKey: .developmentRegion)\n            try contents.encode(\"Release\", forKey: .defaultConfigurationName)\n            try contents.encode(buildConfigurations, forKey: .buildConfigurations)\n\n            if encoder.userInfo.keys.contains(.encodeForXCBuild) {\n                guard let signature else {\n                    throw InternalError(\"Expected to have project signature when encoding for XCBuild\")\n                }\n                try container.encode(signature, forKey: \"signature\")\n                try contents.encode(targets.map{ $0.signature }, forKey: .targets)\n            } else {\n                try contents.encode(targets, forKey: .targets)\n            }\n\n            try contents.encode(groupTree, forKey: .groupTree)\n        }\n\n        public required init(from decoder: Decoder) throws {\n            let superContainer = try decoder.container(keyedBy: StringKey.self)\n            let container = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: \"contents\")\n\n            let guidString = try container.decode(GUID.self, forKey: .guid)\n            self.guid = String(guidString.dropLast(\"\\(schemaVersion)\".count + 1))\n            self.name = try container.decode(String.self, forKey: .projectName)\n            self.path = try container.decode(AbsolutePath.self, forKey: .path)\n            self.projectDirectory = try container.decode(AbsolutePath.self, forKey: .projectDirectory)\n            self.developmentRegion = try container.decode(String.self, forKey: .developmentRegion)\n            self.buildConfigurations = try container.decode([BuildConfiguration].self, forKey: .buildConfigurations)\n\n            let untypedTargets = try container.decode([UntypedTarget].self, forKey: .targets)\n            var targetContainer = try container.nestedUnkeyedContainer(forKey: .targets)\n            self.targets = try untypedTargets.map { target in\n                let type = target.contents.type\n                switch type {\n                case \"aggregate\":\n                    return try targetContainer.decode(AggregateTarget.self)\n                case \"standard\", \"packageProduct\":\n                    return try targetContainer.decode(Target.self)\n                default:\n                    throw InternalError(\"unknown target type \\(type)\")\n                }\n            }\n\n            self.groupTree = try container.decode(Group.self, forKey: .groupTree)\n            try super.init(from: decoder)\n        }\n    }\n\n    /// Abstract base class for all items in the group hierarchy.\n    public class Reference: TypedObject {\n        /// Determines the base path for a reference's relative path.\n        public enum SourceTree: String, Codable {\n\n            /// Indicates that the path is relative to the source root (i.e. the \"project directory\").\n            case sourceRoot = \"SOURCE_ROOT\"\n\n            /// Indicates that the path is relative to the path of the parent group.\n            case group = \"<group>\"\n\n            /// Indicates that the path is relative to the effective build directory (which varies depending on active\n            /// scheme, active run destination, or even an overridden build setting.\n            case builtProductsDir = \"BUILT_PRODUCTS_DIR\"\n\n            /// Indicates that the path is an absolute path.\n            case absolute = \"<absolute>\"\n        }\n\n        public let guid: GUID\n\n        /// Relative path of the reference.  It is usually a literal, but may in fact contain build settings.\n        public var path: String\n\n        /// Determines the base path for the reference's relative path.\n        public var sourceTree: SourceTree\n\n        /// Name of the reference, if different from the last path component (if not set, the last path component will\n        /// be used as the name).\n        public var name: String?\n\n        fileprivate init(\n            guid: GUID,\n            path: String,\n            sourceTree: SourceTree,\n            name: String?\n        ) {\n            precondition(!guid.isEmpty)\n            precondition(!(name?.isEmpty ?? false))\n\n            self.guid = guid\n            self.path = path\n            self.sourceTree = sourceTree\n            self.name = name\n            super.init()\n        }\n\n        private enum CodingKeys: CodingKey {\n            case guid, sourceTree, path, name, type\n        }\n\n        public override func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            try container.encode(guid, forKey: .guid)\n            try container.encode(sourceTree, forKey: .sourceTree)\n            try container.encode(path, forKey: .path)\n            try container.encode(name ?? path, forKey: .name)\n        }\n\n        public required init(from decoder: Decoder) throws {\n            let container = try decoder.container(keyedBy: CodingKeys.self)\n            self.guid = try container.decode(String.self, forKey: .guid)\n            self.sourceTree = try container.decode(SourceTree.self, forKey: .sourceTree)\n            self.path = try container.decode(String.self, forKey: .path)\n            self.name = try container.decodeIfPresent(String.self, forKey: .name)\n            try super.init(from: decoder)\n        }\n    }\n\n    /// A reference to a file system entity (a file, folder, etc).\n    public final class FileReference: Reference {\n        override class var type: String { \"file\" }\n\n        public var fileType: String\n\n        public init(\n            guid: GUID,\n            path: String,\n            sourceTree: SourceTree = .group,\n            name: String? = nil,\n            fileType: String? = nil\n        ) {\n            self.fileType = fileType ?? FileReference.fileTypeIdentifier(forPath: path)\n            super.init(guid: guid, path: path, sourceTree: sourceTree, name: name)\n        }\n\n        private enum CodingKeys: CodingKey {\n            case fileType\n        }\n\n        public override func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            try container.encode(fileType, forKey: .fileType)\n        }\n\n        public required init(from decoder: Decoder) throws {\n            let container = try decoder.container(keyedBy: CodingKeys.self)\n            self.fileType = try container.decode(String.self, forKey: .fileType)\n            try super.init(from: decoder)\n        }\n    }\n\n    /// A group that can contain References (FileReferences and other Groups). The resolved path of a group is used as\n    /// the base path for any child references whose source tree type is GroupRelative.\n    public final class Group: Reference {\n        override class var type: String { \"group\" }\n\n        public var children: [Reference]\n\n        public init(\n            guid: GUID,\n            path: String,\n            sourceTree: SourceTree = .group,\n            name: String? = nil,\n            children: [Reference]\n        ) {\n            precondition(\n                Set(children.map({ $0.guid })).count == children.count,\n                \"multiple group children with the same guid: \\(children.map({ $0.guid }))\"\n            )\n\n            self.children = children\n\n            super.init(guid: guid, path: path, sourceTree: sourceTree, name: name)\n        }\n\n        private enum CodingKeys: CodingKey {\n            case children, type\n        }\n\n        public override func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            try container.encode(children, forKey: .children)\n        }\n\n        public required init(from decoder: Decoder) throws {\n            let container = try decoder.container(keyedBy: CodingKeys.self)\n\n            let untypedChildren = try container.decode([TypedObject].self, forKey: .children)\n            var childrenContainer = try container.nestedUnkeyedContainer(forKey: .children)\n\n            self.children = try untypedChildren.map { child in\n                switch child.type {\n                case Group.type:\n                    return try childrenContainer.decode(Group.self)\n                case FileReference.type:\n                    return try childrenContainer.decode(FileReference.self)\n                default:\n                    throw InternalError(\"unknown reference type \\(child.type ?? \"<nil>\")\")\n                }\n            }\n\n            try super.init(from: decoder)\n        }\n    }\n\n    /// Represents a dependency on another target (identified by its PIF GUID).\n    public struct TargetDependency: Codable {\n        /// Identifier of depended-upon target.\n        public var targetGUID: String\n\n        /// The platform filters for this target dependency.\n        public var platformFilters: [PlatformFilter]\n\n        public init(targetGUID: String, platformFilters: [PlatformFilter] = [])  {\n            self.targetGUID = targetGUID\n            self.platformFilters = platformFilters\n        }\n\n        private enum CodingKeys: CodingKey {\n            case guid, platformFilters\n        }\n\n        public func encode(to encoder: Encoder) throws {\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            try container.encode(\"\\(targetGUID)@\\(schemaVersion)\", forKey: .guid)\n\n            if !platformFilters.isEmpty {\n                try container.encode(platformFilters, forKey: .platformFilters)\n            }\n        }\n\n        public init(from decoder: Decoder) throws {\n            let container = try decoder.container(keyedBy: CodingKeys.self)\n\n            let targetGUIDString = try container.decode(String.self, forKey: .guid)\n            self.targetGUID = String(targetGUIDString.dropLast(\"\\(schemaVersion)\".count + 1))\n            platformFilters = try container.decodeIfPresent([PlatformFilter].self, forKey: .platformFilters) ?? []\n        }\n    }\n\n    public class BaseTarget: TypedObject {\n        class override var type: String { \"target\" }\n        public let guid: GUID\n        public var name: String\n        public var buildConfigurations: [BuildConfiguration]\n        public var buildPhases: [BuildPhase]\n        public var dependencies: [TargetDependency]\n        public var impartedBuildProperties: ImpartedBuildProperties\n        var signature: String?\n\n        fileprivate init(\n            guid: GUID,\n            name: String,\n            buildConfigurations: [BuildConfiguration],\n            buildPhases: [BuildPhase],\n            dependencies: [TargetDependency],\n            impartedBuildSettings: PIF.BuildSettings,\n            signature: String?\n        ) {\n            self.guid = guid\n            self.name = name\n            self.buildConfigurations = buildConfigurations\n            self.buildPhases = buildPhases\n            self.dependencies = dependencies\n            impartedBuildProperties = ImpartedBuildProperties(settings: impartedBuildSettings)\n            self.signature = signature\n            super.init()\n        }\n\n        public required init(from decoder: Decoder) throws {\n            throw InternalError(\"init(from:) has not been implemented\")\n        }\n    }\n\n    public final class AggregateTarget: BaseTarget {\n        public init(\n            guid: GUID,\n            name: String,\n            buildConfigurations: [BuildConfiguration],\n            buildPhases: [BuildPhase],\n            dependencies: [TargetDependency],\n            impartedBuildSettings: PIF.BuildSettings\n        ) {\n            super.init(\n                guid: guid,\n                name: name,\n                buildConfigurations: buildConfigurations,\n                buildPhases: buildPhases,\n                dependencies: dependencies,\n                impartedBuildSettings: impartedBuildSettings,\n                signature: nil\n            )\n        }\n\n        private enum CodingKeys: CodingKey {\n            case type, guid, name, buildConfigurations, buildPhases, dependencies, impartedBuildProperties, signature\n        }\n\n        public override func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            var container = encoder.container(keyedBy: StringKey.self)\n            var contents = container.nestedContainer(keyedBy: CodingKeys.self, forKey: \"contents\")\n            try contents.encode(\"aggregate\", forKey: .type)\n            try contents.encode(\"\\(guid)@\\(schemaVersion)\", forKey: .guid)\n            try contents.encode(name, forKey: .name)\n            try contents.encode(buildConfigurations, forKey: .buildConfigurations)\n            try contents.encode(buildPhases, forKey: .buildPhases)\n            try contents.encode(dependencies, forKey: .dependencies)\n            try contents.encode(impartedBuildProperties, forKey: .impartedBuildProperties)\n\n            if encoder.userInfo.keys.contains(.encodeForXCBuild) {\n                guard let signature else {\n                    throw InternalError(\"Expected to have \\(Swift.type(of: self)) signature when encoding for XCBuild\")\n                }\n                try container.encode(signature, forKey: \"signature\")\n            }\n        }\n\n        public required init(from decoder: Decoder) throws {\n            let superContainer = try decoder.container(keyedBy: StringKey.self)\n            let container = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: \"contents\")\n\n            let guidString = try container.decode(GUID.self, forKey: .guid)\n            let guid = String(guidString.dropLast(\"\\(schemaVersion)\".count + 1))\n\n            let name = try container.decode(String.self, forKey: .name)\n            let buildConfigurations = try container.decode([BuildConfiguration].self, forKey: .buildConfigurations)\n\n            let untypedBuildPhases = try container.decode([TypedObject].self, forKey: .buildPhases)\n            var buildPhasesContainer = try container.nestedUnkeyedContainer(forKey: .buildPhases)\n\n            let buildPhases: [BuildPhase] = try untypedBuildPhases.map {\n                guard let type = $0.type else {\n                    throw InternalError(\"Expected type in build phase \\($0)\")\n                }\n                return try BuildPhase.decode(container: &buildPhasesContainer, type: type)\n            }\n\n            let dependencies = try container.decode([TargetDependency].self, forKey: .dependencies)\n            let impartedBuildProperties = try container.decode(BuildSettings.self, forKey: .impartedBuildProperties)\n\n            super.init(\n                guid: guid,\n                name: name,\n                buildConfigurations: buildConfigurations,\n                buildPhases: buildPhases,\n                dependencies: dependencies,\n                impartedBuildSettings: impartedBuildProperties,\n                signature: nil\n            )\n        }\n    }\n\n    /// An Xcode target, representing a single entity to build.\n    public final class Target: BaseTarget {\n        public enum ProductType: String, Codable {\n            case application = \"com.apple.product-type.application\"\n            case staticArchive = \"com.apple.product-type.library.static\"\n            case objectFile = \"com.apple.product-type.objfile\"\n            case dynamicLibrary = \"com.apple.product-type.library.dynamic\"\n            case framework = \"com.apple.product-type.framework\"\n            case executable = \"com.apple.product-type.tool\"\n            case unitTest = \"com.apple.product-type.bundle.unit-test\"\n            case bundle = \"com.apple.product-type.bundle\"\n            case packageProduct = \"packageProduct\"\n        }\n\n        public var productName: String\n        public var productType: ProductType\n\n        public init(\n            guid: GUID,\n            name: String,\n            productType: ProductType,\n            productName: String,\n            buildConfigurations: [BuildConfiguration],\n            buildPhases: [BuildPhase],\n            dependencies: [TargetDependency],\n            impartedBuildSettings: PIF.BuildSettings\n        ) {\n            self.productType = productType\n            self.productName = productName\n\n            super.init(\n                guid: guid,\n                name: name,\n                buildConfigurations: buildConfigurations,\n                buildPhases: buildPhases,\n                dependencies: dependencies,\n                impartedBuildSettings: impartedBuildSettings,\n                signature: nil\n            )\n        }\n\n        private enum CodingKeys: CodingKey {\n            case guid, name, dependencies, buildConfigurations, type, frameworksBuildPhase, productTypeIdentifier, productReference, buildRules, buildPhases, impartedBuildProperties, signature\n        }\n\n        override public func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            var container = encoder.container(keyedBy: StringKey.self)\n            var contents = container.nestedContainer(keyedBy: CodingKeys.self, forKey: \"contents\")\n            try contents.encode(\"\\(guid)@\\(schemaVersion)\", forKey: .guid)\n            try contents.encode(name, forKey: .name)\n            try contents.encode(dependencies, forKey: .dependencies)\n            try contents.encode(buildConfigurations, forKey: .buildConfigurations)\n\n            if encoder.userInfo.keys.contains(.encodeForXCBuild) {\n                guard let signature else {\n                    throw InternalError(\"Expected to have \\(Swift.type(of: self)) signature when encoding for XCBuild\")\n                }\n                try container.encode(signature, forKey: \"signature\")\n            }\n\n            if productType == .packageProduct {\n                try contents.encode(\"packageProduct\", forKey: .type)\n\n                // Add the framework build phase, if present.\n                if let phase = buildPhases.first as? PIF.FrameworksBuildPhase {\n                    try contents.encode(phase, forKey: .frameworksBuildPhase)\n                }\n            } else {\n                try contents.encode(\"standard\", forKey: .type)\n                try contents.encode(productType, forKey: .productTypeIdentifier)\n\n                let productReference = [\n                    \"type\": \"file\",\n                    \"guid\": \"PRODUCTREF-\\(guid)\",\n                    \"name\": productName,\n                ]\n                try contents.encode(productReference, forKey: .productReference)\n\n                try contents.encode([String](), forKey: .buildRules)\n                try contents.encode(buildPhases, forKey: .buildPhases)\n                try contents.encode(impartedBuildProperties, forKey: .impartedBuildProperties)\n            }\n        }\n\n        public required init(from decoder: Decoder) throws {\n            let superContainer = try decoder.container(keyedBy: StringKey.self)\n            let container = try superContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: \"contents\")\n\n            let guidString = try container.decode(GUID.self, forKey: .guid)\n            let guid = String(guidString.dropLast(\"\\(schemaVersion)\".count + 1))\n            let name = try container.decode(String.self, forKey: .name)\n            let buildConfigurations = try container.decode([BuildConfiguration].self, forKey: .buildConfigurations)\n            let dependencies = try container.decode([TargetDependency].self, forKey: .dependencies)\n\n            let type = try container.decode(String.self, forKey: .type)\n\n            let buildPhases: [BuildPhase]\n            let impartedBuildProperties: ImpartedBuildProperties\n\n            if type == \"packageProduct\" {\n                self.productType = .packageProduct\n                self.productName = \"\"\n                let fwkBuildPhase = try container.decodeIfPresent(FrameworksBuildPhase.self, forKey: .frameworksBuildPhase)\n                buildPhases = fwkBuildPhase.map{ [$0] } ?? []\n                impartedBuildProperties = ImpartedBuildProperties(settings: BuildSettings())\n            } else if type == \"standard\" {\n                self.productType = try container.decode(ProductType.self, forKey: .productTypeIdentifier)\n\n                let productReference = try container.decode([String: String].self, forKey: .productReference)\n                self.productName = productReference[\"name\"]!\n\n                let untypedBuildPhases = try container.decodeIfPresent([TypedObject].self, forKey: .buildPhases) ?? []\n                var buildPhasesContainer = try container.nestedUnkeyedContainer(forKey: .buildPhases)\n\n                buildPhases = try untypedBuildPhases.map {\n                    guard let type = $0.type else {\n                        throw InternalError(\"Expected type in build phase \\($0)\")\n                    }\n                    return try BuildPhase.decode(container: &buildPhasesContainer, type: type)\n                }\n\n                impartedBuildProperties = try container.decode(ImpartedBuildProperties.self, forKey: .impartedBuildProperties)\n            } else {\n                throw InternalError(\"Unhandled target type \\(type)\")\n            }\n\n            super.init(\n                guid: guid,\n                name: name,\n                buildConfigurations: buildConfigurations,\n                buildPhases: buildPhases,\n                dependencies: dependencies,\n                impartedBuildSettings: impartedBuildProperties.buildSettings,\n                signature: nil\n            )\n        }\n    }\n\n    /// Abstract base class for all build phases in a target.\n    public class BuildPhase: TypedObject {\n        static func decode(container: inout UnkeyedDecodingContainer, type: String) throws -> BuildPhase {\n            switch type {\n            case HeadersBuildPhase.type:\n                return try container.decode(HeadersBuildPhase.self)\n            case SourcesBuildPhase.type:\n                return try container.decode(SourcesBuildPhase.self)\n            case FrameworksBuildPhase.type:\n                return try container.decode(FrameworksBuildPhase.self)\n            case ResourcesBuildPhase.type:\n                return try container.decode(ResourcesBuildPhase.self)\n            default:\n                throw InternalError(\"unknown build phase \\(type)\")\n            }\n        }\n\n        public let guid: GUID\n        public var buildFiles: [BuildFile]\n\n        public init(guid: GUID, buildFiles: [BuildFile]) {\n            precondition(!guid.isEmpty)\n\n            self.guid = guid\n            self.buildFiles = buildFiles\n            super.init()\n        }\n\n        private enum CodingKeys: CodingKey {\n            case guid, buildFiles\n        }\n\n        public override func encode(to encoder: Encoder) throws {\n            try super.encode(to: encoder)\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            try container.encode(guid, forKey: .guid)\n            try container.encode(buildFiles, forKey: .buildFiles)\n        }\n\n        public required init(from decoder: Decoder) throws {\n            let container = try decoder.container(keyedBy: CodingKeys.self)\n            self.guid = try container.decode(GUID.self, forKey: .guid)\n            self.buildFiles = try container.decode([BuildFile].self, forKey: .buildFiles)\n            try super.init(from: decoder)\n        }\n    }\n\n    /// A \"headers\" build phase, i.e. one that copies headers into a directory of the product, after suitable\n    /// processing.\n    public final class HeadersBuildPhase: BuildPhase {\n        override class var type: String { \"com.apple.buildphase.headers\" }\n    }\n\n    /// A \"sources\" build phase, i.e. one that compiles sources and provides them to be linked into the executable code\n    /// of the product.\n    public final class SourcesBuildPhase: BuildPhase {\n        override class var type: String { \"com.apple.buildphase.sources\" }\n    }\n\n    /// A \"frameworks\" build phase, i.e. one that links compiled code and libraries into the executable of the product.\n    public final class FrameworksBuildPhase: BuildPhase {\n        override class var type: String { \"com.apple.buildphase.frameworks\" }\n    }\n\n    public final class ResourcesBuildPhase: BuildPhase {\n        override class var type: String { \"com.apple.buildphase.resources\" }\n    }\n\n    /// A build file, representing the membership of either a file or target product reference in a build phase.\n    public struct BuildFile: Codable {\n        public enum Reference {\n            case file(guid: PIF.GUID)\n            case target(guid: PIF.GUID)\n        }\n\n        public enum HeaderVisibility: String, Codable {\n            case `public` = \"public\"\n            case `private` = \"private\"\n        }\n\n        public let guid: GUID\n        public var reference: Reference\n        public var headerVisibility: HeaderVisibility? = nil\n        public var platformFilters: [PlatformFilter]\n\n        public init(guid: GUID, file: FileReference, platformFilters: [PlatformFilter], headerVisibility: HeaderVisibility? = nil) {\n            self.guid = guid\n            self.reference = .file(guid: file.guid)\n            self.platformFilters = platformFilters\n            self.headerVisibility = headerVisibility\n        }\n\n        public init(guid: GUID, fileGUID: PIF.GUID, platformFilters: [PlatformFilter], headerVisibility: HeaderVisibility? = nil) {\n            self.guid = guid\n            self.reference = .file(guid: fileGUID)\n            self.platformFilters = platformFilters\n            self.headerVisibility = headerVisibility\n        }\n\n        public init(guid: GUID, target: PIF.BaseTarget, platformFilters: [PlatformFilter], headerVisibility: HeaderVisibility? = nil) {\n            self.guid = guid\n            self.reference = .target(guid: target.guid)\n            self.platformFilters = platformFilters\n            self.headerVisibility = headerVisibility\n        }\n\n        public init(guid: GUID, targetGUID: PIF.GUID, platformFilters: [PlatformFilter], headerVisibility: HeaderVisibility? = nil) {\n            self.guid = guid\n            self.reference = .target(guid: targetGUID)\n            self.platformFilters = platformFilters\n            self.headerVisibility = headerVisibility\n        }\n\n        public init(guid: GUID, reference: Reference, platformFilters: [PlatformFilter], headerVisibility: HeaderVisibility? = nil) {\n            self.guid = guid\n            self.reference = reference\n            self.platformFilters = platformFilters\n            self.headerVisibility = headerVisibility\n        }\n\n        private enum CodingKeys: CodingKey {\n            case guid, platformFilters, fileReference, targetReference, headerVisibility\n        }\n\n        public func encode(to encoder: Encoder) throws {\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            try container.encode(guid, forKey: .guid)\n            try container.encode(platformFilters, forKey: .platformFilters)\n            try container.encodeIfPresent(headerVisibility, forKey: .headerVisibility)\n\n            switch self.reference {\n            case .file(let fileGUID):\n                try container.encode(fileGUID, forKey: .fileReference)\n            case .target(let targetGUID):\n                try container.encode(\"\\(targetGUID)@\\(schemaVersion)\", forKey: .targetReference)\n            }\n        }\n\n        public init(from decoder: Decoder) throws {\n            let container = try decoder.container(keyedBy: CodingKeys.self)\n            guid = try container.decode(GUID.self, forKey: .guid)\n            platformFilters = try container.decode([PlatformFilter].self, forKey: .platformFilters)\n            headerVisibility = try container.decodeIfPresent(HeaderVisibility.self, forKey: .headerVisibility)\n\n            if container.allKeys.contains(.fileReference) {\n                reference = try .file(guid: container.decode(GUID.self, forKey: .fileReference))\n            } else if container.allKeys.contains(.targetReference) {\n                let targetGUIDString = try container.decode(GUID.self, forKey: .targetReference)\n                let targetGUID = String(targetGUIDString.dropLast(\"\\(schemaVersion)\".count + 1))\n                reference = .target(guid: targetGUID)\n            } else {\n                throw InternalError(\"Expected \\(CodingKeys.fileReference) or \\(CodingKeys.targetReference) in the keys\")\n            }\n        }\n    }\n\n    /// Represents a generic platform filter.\n    public struct PlatformFilter: Codable, Equatable {\n        /// The name of the platform (`LC_BUILD_VERSION`).\n        ///\n        /// Example: macos, ios, watchos, tvos.\n        public var platform: String\n\n        /// The name of the environment (`LC_BUILD_VERSION`)\n        ///\n        /// Example: simulator, maccatalyst.\n        public var environment: String\n\n        public init(platform: String, environment: String = \"\") {\n            self.platform = platform\n            self.environment = environment\n        }\n    }\n\n    /// A build configuration, which is a named collection of build settings.\n    public struct BuildConfiguration: Codable {\n        public let guid: GUID\n        public var name: String\n        public var buildSettings: BuildSettings\n        public let impartedBuildProperties: ImpartedBuildProperties\n\n        public init(guid: GUID, name: String, buildSettings: BuildSettings, impartedBuildProperties: ImpartedBuildProperties = ImpartedBuildProperties(settings: BuildSettings())) {\n            precondition(!guid.isEmpty)\n            precondition(!name.isEmpty)\n\n            self.guid = guid\n            self.name = name\n            self.buildSettings = buildSettings\n            self.impartedBuildProperties = impartedBuildProperties\n        }\n    }\n\n    public struct ImpartedBuildProperties: Codable {\n        public var buildSettings: BuildSettings\n\n        public init(settings: BuildSettings) {\n            self.buildSettings = settings\n        }\n    }\n\n    /// A set of build settings, which is represented as a struct of optional build settings. This is not optimally\n    /// efficient, but it is great for code completion and type-checking.\n    public struct BuildSettings: Codable {\n        public enum SingleValueSetting: String, Codable {\n            case APPLICATION_EXTENSION_API_ONLY\n            case BUILT_PRODUCTS_DIR\n            case CLANG_CXX_LANGUAGE_STANDARD\n            case CLANG_ENABLE_MODULES\n            case CLANG_ENABLE_OBJC_ARC\n            case CODE_SIGNING_REQUIRED\n            case CODE_SIGN_IDENTITY\n            case COMBINE_HIDPI_IMAGES\n            case COPY_PHASE_STRIP\n            case DEBUG_INFORMATION_FORMAT\n            case DEFINES_MODULE\n            case DRIVERKIT_DEPLOYMENT_TARGET\n            case DYLIB_INSTALL_NAME_BASE\n            case EMBEDDED_CONTENT_CONTAINS_SWIFT\n            case ENABLE_NS_ASSERTIONS\n            case ENABLE_TESTABILITY\n            case ENABLE_TESTING_SEARCH_PATHS\n            case ENTITLEMENTS_REQUIRED\n            case EXECUTABLE_PREFIX\n            case GENERATE_INFOPLIST_FILE\n            case GCC_C_LANGUAGE_STANDARD\n            case GCC_OPTIMIZATION_LEVEL\n            case GENERATE_MASTER_OBJECT_FILE\n            case INFOPLIST_FILE\n            case IPHONEOS_DEPLOYMENT_TARGET\n            case KEEP_PRIVATE_EXTERNS\n            case CLANG_COVERAGE_MAPPING_LINKER_ARGS\n            case MACH_O_TYPE\n            case MACOSX_DEPLOYMENT_TARGET\n            case MODULEMAP_FILE\n            case MODULEMAP_FILE_CONTENTS\n            case MODULEMAP_PATH\n            case MODULE_CACHE_DIR\n            case ONLY_ACTIVE_ARCH\n            case PACKAGE_RESOURCE_BUNDLE_NAME\n            case PACKAGE_RESOURCE_TARGET_KIND\n            case PRODUCT_BUNDLE_IDENTIFIER\n            case PRODUCT_MODULE_NAME\n            case PRODUCT_NAME\n            case PROJECT_NAME\n            case SDKROOT\n            case SDK_VARIANT\n            case SKIP_INSTALL\n            case INSTALL_PATH\n            case SUPPORTS_MACCATALYST\n            case SWIFT_SERIALIZE_DEBUGGING_OPTIONS\n            case SWIFT_INSTALL_OBJC_HEADER\n            case SWIFT_OBJC_INTERFACE_HEADER_NAME\n            case SWIFT_OBJC_INTERFACE_HEADER_DIR\n            case SWIFT_OPTIMIZATION_LEVEL\n            case SWIFT_VERSION\n            case TARGET_NAME\n            case TARGET_BUILD_DIR\n            case TVOS_DEPLOYMENT_TARGET\n            case USE_HEADERMAP\n            case USES_SWIFTPM_UNSAFE_FLAGS\n            case WATCHOS_DEPLOYMENT_TARGET\n            case XROS_DEPLOYMENT_TARGET\n            case MARKETING_VERSION\n            case CURRENT_PROJECT_VERSION\n            case SWIFT_EMIT_MODULE_INTERFACE\n            case GENERATE_RESOURCE_ACCESSORS\n        }\n\n        public enum MultipleValueSetting: String, Codable {\n            case EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES\n            case FRAMEWORK_SEARCH_PATHS\n            case GCC_PREPROCESSOR_DEFINITIONS\n            case HEADER_SEARCH_PATHS\n            case LD_RUNPATH_SEARCH_PATHS\n            case LIBRARY_SEARCH_PATHS\n            case OTHER_CFLAGS\n            case OTHER_CPLUSPLUSFLAGS\n            case OTHER_LDFLAGS\n            case OTHER_LDRFLAGS\n            case OTHER_SWIFT_FLAGS\n            case PRELINK_FLAGS\n            case SPECIALIZATION_SDK_OPTIONS\n            case SUPPORTED_PLATFORMS\n            case SWIFT_ACTIVE_COMPILATION_CONDITIONS\n            case SWIFT_MODULE_ALIASES\n        }\n\n        public enum Platform: String, CaseIterable, Codable {\n            case macOS = \"macos\"\n            case macCatalyst = \"maccatalyst\"\n            case iOS = \"ios\"\n            case tvOS = \"tvos\"\n            case watchOS = \"watchos\"\n            case driverKit = \"driverkit\"\n            case linux\n\n            public var packageModelPlatform: PackageModel.Platform {\n                switch self {\n                case .macOS: return .macOS\n                case .macCatalyst: return .macCatalyst\n                case .iOS: return .iOS\n                case .tvOS: return .tvOS\n                case .watchOS: return .watchOS\n                case .driverKit: return .driverKit\n                case .linux: return .linux\n                }\n            }\n\n            public var conditions: [String] {\n                let filters = [PackageCondition(platforms: [packageModelPlatform])].toPlatformFilters().map { filter in\n                    if filter.environment.isEmpty {\n                        return filter.platform\n                    } else {\n                        return \"\\(filter.platform)-\\(filter.environment)\"\n                    }\n                }.sorted()\n                return [\"__platform_filter=\\(filters.joined(separator: \";\"))\"]\n            }\n        }\n\n        public private(set) var platformSpecificSingleValueSettings = OrderedDictionary<Platform, OrderedDictionary<SingleValueSetting, String>>()\n        public private(set) var platformSpecificMultipleValueSettings = OrderedDictionary<Platform, OrderedDictionary<MultipleValueSetting, [String]>>()\n        public private(set) var singleValueSettings: OrderedDictionary<SingleValueSetting, String> = [:]\n        public private(set) var multipleValueSettings: OrderedDictionary<MultipleValueSetting, [String]> = [:]\n\n        public subscript(_ setting: SingleValueSetting) -> String? {\n            get { singleValueSettings[setting] }\n            set { singleValueSettings[setting] = newValue }\n        }\n\n        public subscript(_ setting: SingleValueSetting, for platform: Platform) -> String? {\n            get { platformSpecificSingleValueSettings[platform]?[setting] }\n            set { platformSpecificSingleValueSettings[platform, default: [:]][setting] = newValue }\n        }\n\n        public subscript(_ setting: SingleValueSetting, default defaultValue: @autoclosure () -> String) -> String {\n            get { singleValueSettings[setting, default: defaultValue()] }\n            set { singleValueSettings[setting] = newValue }\n        }\n\n        public subscript(_ setting: MultipleValueSetting) -> [String]? {\n            get { multipleValueSettings[setting] }\n            set { multipleValueSettings[setting] = newValue }\n        }\n\n        public subscript(_ setting: MultipleValueSetting, for platform: Platform) -> [String]? {\n            get { platformSpecificMultipleValueSettings[platform]?[setting] }\n            set { platformSpecificMultipleValueSettings[platform, default: [:]][setting] = newValue }\n        }\n\n        public subscript(\n            _ setting: MultipleValueSetting,\n            default defaultValue: @autoclosure () -> [String]\n        ) -> [String] {\n            get { multipleValueSettings[setting, default: defaultValue()] }\n            set { multipleValueSettings[setting] = newValue }\n        }\n\n        public subscript(\n            _ setting: MultipleValueSetting,\n            for platform: Platform,\n            default defaultValue: @autoclosure () -> [String]\n        ) -> [String] {\n            get { platformSpecificMultipleValueSettings[platform, default: [:]][setting, default: defaultValue()] }\n            set { platformSpecificMultipleValueSettings[platform, default: [:]][setting] = newValue }\n        }\n\n        public init() {\n        }\n\n        private enum CodingKeys: CodingKey {\n            case platformSpecificSingleValueSettings, platformSpecificMultipleValueSettings, singleValueSettings, multipleValueSettings\n        }\n\n        public func encode(to encoder: Encoder) throws {\n            if encoder.userInfo.keys.contains(.encodeForXCBuild) {\n                return try encodeForXCBuild(to: encoder)\n            }\n\n            var container = encoder.container(keyedBy: CodingKeys.self)\n            try container.encode(platformSpecificSingleValueSettings, forKey: .platformSpecificSingleValueSettings)\n            try container.encode(platformSpecificMultipleValueSettings, forKey: .platformSpecificMultipleValueSettings)\n            try container.encode(singleValueSettings, forKey: .singleValueSettings)\n            try container.encode(multipleValueSettings, forKey: .multipleValueSettings)\n        }\n\n        private func encodeForXCBuild(to encoder: Encoder) throws {\n            var container = encoder.container(keyedBy: StringKey.self)\n\n            for (key, value) in singleValueSettings {\n                try container.encode(value, forKey: StringKey(key.rawValue))\n            }\n\n            for (key, value) in multipleValueSettings {\n                try container.encode(value, forKey: StringKey(key.rawValue))\n            }\n\n            for (platform, values) in platformSpecificSingleValueSettings {\n                for condition in platform.conditions {\n                    for (key, value) in values {\n                        try container.encode(value, forKey: \"\\(key.rawValue)[\\(condition)]\")\n                    }\n                }\n            }\n\n            for (platform, values) in platformSpecificMultipleValueSettings {\n                for condition in platform.conditions {\n                    for (key, value) in values {\n                        try container.encode(value, forKey: \"\\(key.rawValue)[\\(condition)]\")\n                    }\n                }\n            }\n        }\n\n        public init(from decoder: Decoder) throws {\n            let container = try decoder.container(keyedBy: CodingKeys.self)\n\n            platformSpecificSingleValueSettings = try container.decodeIfPresent(OrderedDictionary<Platform, OrderedDictionary<SingleValueSetting, String>>.self, forKey: .platformSpecificSingleValueSettings) ?? .init()\n            platformSpecificMultipleValueSettings = try container.decodeIfPresent(OrderedDictionary<Platform, OrderedDictionary<MultipleValueSetting, [String]>>.self, forKey: .platformSpecificMultipleValueSettings) ?? .init()\n            singleValueSettings = try container.decodeIfPresent(OrderedDictionary<SingleValueSetting, String>.self, forKey: .singleValueSettings) ?? [:]\n            multipleValueSettings = try container.decodeIfPresent(OrderedDictionary<MultipleValueSetting, [String]>.self, forKey: .multipleValueSettings) ?? [:]\n        }\n    }\n}\n\n/// Represents a filetype recognized by the Xcode build system.\npublic struct XCBuildFileType: CaseIterable {\n    public static let xcassets: XCBuildFileType = XCBuildFileType(\n        fileType: \"xcassets\",\n        fileTypeIdentifier: \"folder.abstractassetcatalog\"\n    )\n\n    public static let xcstrings: XCBuildFileType = XCBuildFileType(\n        fileType: \"xcstrings\",\n        fileTypeIdentifier: \"text.json.xcstrings\"\n    )\n\n    public static let xcdatamodeld: XCBuildFileType = XCBuildFileType(\n        fileType: \"xcdatamodeld\",\n        fileTypeIdentifier: \"wrapper.xcdatamodeld\"\n    )\n\n    public static let xcdatamodel: XCBuildFileType = XCBuildFileType(\n        fileType: \"xcdatamodel\",\n        fileTypeIdentifier: \"wrapper.xcdatamodel\"\n    )\n\n    public static let xcmappingmodel: XCBuildFileType = XCBuildFileType(\n        fileType: \"xcmappingmodel\",\n        fileTypeIdentifier: \"wrapper.xcmappingmodel\"\n    )\n\n    public static let allCases: [XCBuildFileType] = [\n        .xcassets,\n        .xcstrings,\n        .xcdatamodeld,\n        .xcdatamodel,\n        .xcmappingmodel,\n    ]\n\n    public let fileTypes: Set<String>\n    public let fileTypeIdentifier: String\n\n    private init(fileTypes: Set<String>, fileTypeIdentifier: String) {\n        self.fileTypes = fileTypes\n        self.fileTypeIdentifier = fileTypeIdentifier\n    }\n\n    private init(fileType: String, fileTypeIdentifier: String) {\n        self.init(fileTypes: [fileType], fileTypeIdentifier: fileTypeIdentifier)\n    }\n}\n\nstruct StringKey: CodingKey, ExpressibleByStringInterpolation {\n    var stringValue: String\n    var intValue: Int?\n\n    init(stringLiteral stringValue: String) {\n        self.stringValue = stringValue\n    }\n\n    init(stringValue value: String) {\n        self.stringValue = value\n    }\n\n    init(_ value: String) {\n        self.stringValue = value\n    }\n\n    init?(intValue: Int) {\n        assertionFailure(\"does not support integer keys\")\n        return nil\n    }\n}\n\nextension PIF.FileReference {\n    fileprivate static func fileTypeIdentifier(forPath path: String) -> String {\n        let pathExtension: String?\n        if let path = try? AbsolutePath(validating: path) {\n            pathExtension = path.extension\n        } else if let path = try? RelativePath(validating: path) {\n            pathExtension = path.extension\n        } else {\n            pathExtension = nil\n        }\n\n        switch pathExtension {\n        case \"a\":\n            return \"archive.ar\"\n        case \"s\", \"S\":\n            return \"sourcecode.asm\"\n        case \"c\":\n            return \"sourcecode.c.c\"\n        case \"cl\":\n            return \"sourcecode.opencl\"\n        case \"cpp\", \"cp\", \"cxx\", \"cc\", \"c++\", \"C\", \"tcc\":\n            return \"sourcecode.cpp.cpp\"\n        case \"d\":\n            return \"sourcecode.dtrace\"\n        case \"defs\", \"mig\":\n            return \"sourcecode.mig\"\n        case \"m\":\n            return \"sourcecode.c.objc\"\n        case \"mm\", \"M\":\n            return \"sourcecode.cpp.objcpp\"\n        case \"metal\":\n            return \"sourcecode.metal\"\n        case \"l\", \"lm\", \"lmm\", \"lpp\", \"lp\", \"lxx\":\n            return \"sourcecode.lex\"\n        case \"swift\":\n            return \"sourcecode.swift\"\n        case \"y\", \"ym\", \"ymm\", \"ypp\", \"yp\", \"yxx\":\n            return \"sourcecode.yacc\"\n\n        case \"xcassets\":\n            return \"folder.assetcatalog\"\n        case \"xcstrings\":\n            return \"text.json.xcstrings\"\n        case \"storyboard\":\n            return \"file.storyboard\"\n        case \"xib\":\n            return \"file.xib\"\n\n        case \"xcframework\":\n            return \"wrapper.xcframework\"\n\n        default:\n            return pathExtension.flatMap({ pathExtension in\n                XCBuildFileType.allCases.first(where:{ $0.fileTypes.contains(pathExtension) })\n            })?.fileTypeIdentifier ?? \"file\"\n        }\n    }\n}\n\nextension CodingUserInfoKey {\n    public static let encodingPIFSignature: CodingUserInfoKey = CodingUserInfoKey(rawValue: \"encodingPIFSignature\")!\n\n    /// Perform the encoding for XCBuild consumption.\n    public static let encodeForXCBuild: CodingUserInfoKey = CodingUserInfoKey(rawValue: \"encodeForXCBuild\")!\n}\n\nprivate struct UntypedTarget: Decodable {\n    struct TargetContents: Decodable {\n        let type: String\n    }\n    let contents: TargetContents\n}\n\nprotocol PIFSignableObject: AnyObject {\n    var signature: String? { get set }\n}\nextension PIF.Workspace: PIFSignableObject {}\nextension PIF.Project: PIFSignableObject {}\nextension PIF.BaseTarget: PIFSignableObject {}\n\nextension PIF {\n    /// Add signature to workspace and its subobjects.\n    public static func sign(_ workspace: PIF.Workspace) throws {\n        let encoder = JSONEncoder.makeWithDefaults()\n\n        func sign<T: PIFSignableObject & Encodable>(_ obj: T) throws {\n            let signatureContent = try encoder.encode(obj)\n            let bytes = ByteString(signatureContent)\n            obj.signature = bytes.sha256Checksum\n        }\n\n        let projects = workspace.projects\n        try projects.flatMap{ $0.targets }.forEach(sign)\n        try projects.forEach(sign)\n        try sign(workspace)\n    }\n}\n"
  },
  {
    "path": "Sources/XCBuildSupport/PIFBuilder.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport TSCUtility\n\n@_spi(SwiftPMInternal)\nimport SPMBuildCore\n\nimport func TSCBasic.memoize\nimport func TSCBasic.topologicalSort\n\n/// The parameters required by `PIFBuilder`.\nstruct PIFBuilderParameters {\n    let triple: Basics.Triple\n\n    /// Whether the toolchain supports `-package-name` option.\n    let isPackageAccessModifierSupported: Bool\n\n    /// Whether or not build for testability is enabled.\n    let enableTestability: Bool\n\n    /// Whether to create dylibs for dynamic library products.\n    let shouldCreateDylibForDynamicProducts: Bool\n\n    /// The path to the library directory of the active toolchain.\n    let toolchainLibDir: AbsolutePath\n\n    /// An array of paths to search for pkg-config `.pc` files.\n    let pkgConfigDirectories: [AbsolutePath]\n\n    /// The toolchain's SDK root path.\n    let sdkRootPath: AbsolutePath?\n\n    /// The Swift language versions supported by the XCBuild being used for the buid.\n    let supportedSwiftVersions: [SwiftLanguageVersion]\n}\n\n/// PIF object builder for a package graph.\npublic final class PIFBuilder {\n    /// Name of the PIF target aggregating all targets (excluding tests).\n    public static let allExcludingTestsTargetName = \"AllExcludingTests\"\n\n    /// Name of the PIF target aggregating all targets (including tests).\n    public static let allIncludingTestsTargetName = \"AllIncludingTests\"\n\n    /// The package graph to build from.\n    let graph: ModulesGraph\n\n    /// The parameters used to configure the PIF.\n    let parameters: PIFBuilderParameters\n\n    /// The ObservabilityScope to emit diagnostics to.\n    let observabilityScope: ObservabilityScope\n\n    /// The file system to read from.\n    let fileSystem: FileSystem\n\n    private var pif: PIF.TopLevelObject?\n\n    /// Creates a `PIFBuilder` instance.\n    /// - Parameters:\n    ///   - graph: The package graph to build from.\n    ///   - parameters: The parameters used to configure the PIF.\n    ///   - fileSystem: The file system to read from.\n    ///   - observabilityScope: The ObservabilityScope to emit diagnostics to.\n    init(\n        graph: ModulesGraph,\n        parameters: PIFBuilderParameters,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.graph = graph\n        self.parameters = parameters\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope.makeChildScope(description: \"PIF Builder\")\n    }\n\n    /// Generates the PIF representation.\n    /// - Parameters:\n    ///   - prettyPrint: Whether to return a formatted JSON.\n    ///   - preservePIFModelStructure: Whether to preserve model structure.\n    /// - Returns: The package graph in the JSON PIF format.\n    func generatePIF(\n        prettyPrint: Bool = true,\n        preservePIFModelStructure: Bool = false\n    ) throws -> String {\n        let encoder = prettyPrint ? JSONEncoder.makeWithDefaults() : JSONEncoder()\n\n        if !preservePIFModelStructure {\n            encoder.userInfo[.encodeForXCBuild] = true\n        }\n\n        let topLevelObject = try self.construct()\n\n        // Sign the pif objects before encoding it for XCBuild.\n        try PIF.sign(topLevelObject.workspace)\n\n        let pifData = try encoder.encode(topLevelObject)\n        return String(decoding: pifData, as: UTF8.self)\n    }\n\n    /// Constructs a `PIF.TopLevelObject` representing the package graph.\n    public func construct() throws -> PIF.TopLevelObject {\n        try memoize(to: &self.pif) {\n            let rootPackage = self.graph.rootPackages[self.graph.rootPackages.startIndex]\n\n            let sortedPackages = self.graph.packages\n                .sorted { $0.manifest.displayName < $1.manifest.displayName } // TODO: use identity instead?\n            var projects: [PIFProjectBuilder] = try sortedPackages.map { package in\n                try PackagePIFProjectBuilder(\n                    package: package,\n                    parameters: self.parameters,\n                    fileSystem: self.fileSystem,\n                    observabilityScope: self.observabilityScope\n                )\n            }\n\n            projects.append(AggregatePIFProjectBuilder(projects: projects))\n\n            let workspace = try PIF.Workspace(\n                guid: \"Workspace:\\(rootPackage.path.pathString)\",\n                name: rootPackage.manifest.displayName, // TODO: use identity instead?\n                path: rootPackage.path,\n                projects: projects.map { try $0.construct() }\n            )\n\n            return PIF.TopLevelObject(workspace: workspace)\n        }\n    }\n\n    // Convenience method for generating PIF.\n    public static func generatePIF(\n        buildParameters: BuildParameters,\n        packageGraph: ModulesGraph,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        preservePIFModelStructure: Bool\n    ) throws -> String {\n        let parameters = PIFBuilderParameters(buildParameters, supportedSwiftVersions: [])\n        let builder = Self(\n            graph: packageGraph,\n            parameters: parameters,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n        return try builder.generatePIF(preservePIFModelStructure: preservePIFModelStructure)\n    }\n}\n\nclass PIFProjectBuilder {\n    let groupTree: PIFGroupBuilder\n    private(set) var targets: [PIFBaseTargetBuilder]\n    private(set) var buildConfigurations: [PIFBuildConfigurationBuilder]\n\n    @DelayedImmutable\n    var guid: PIF.GUID\n    @DelayedImmutable\n    var name: String\n    @DelayedImmutable\n    var path: AbsolutePath\n    @DelayedImmutable\n    var projectDirectory: AbsolutePath\n    @DelayedImmutable\n    var developmentRegion: String\n\n    fileprivate init() {\n        self.groupTree = PIFGroupBuilder(path: \"\")\n        self.targets = []\n        self.buildConfigurations = []\n    }\n\n    /// Creates and adds a new empty build configuration, i.e. one that does not initially have any build settings.\n    /// The name must not be empty and must not be equal to the name of any existing build configuration in the target.\n    @discardableResult\n    func addBuildConfiguration(\n        name: String,\n        settings: PIF.BuildSettings = PIF.BuildSettings(),\n        impartedBuildProperties: PIF.ImpartedBuildProperties = PIF\n            .ImpartedBuildProperties(settings: PIF.BuildSettings())\n    ) -> PIFBuildConfigurationBuilder {\n        let builder = PIFBuildConfigurationBuilder(\n            name: name,\n            settings: settings,\n            impartedBuildProperties: impartedBuildProperties\n        )\n        self.buildConfigurations.append(builder)\n        return builder\n    }\n\n    /// Creates and adds a new empty target, i.e. one that does not initially have any build phases. If provided,\n    /// the ID must be non-empty and unique within the PIF workspace; if not provided, an arbitrary guaranteed-to-be-\n    /// unique identifier will be assigned. The name must not be empty and must not be equal to the name of any existing\n    /// target in the project.\n    @discardableResult\n    func addTarget(\n        guid: PIF.GUID,\n        name: String,\n        productType: PIF.Target.ProductType,\n        productName: String\n    ) -> PIFTargetBuilder {\n        let target = PIFTargetBuilder(guid: guid, name: name, productType: productType, productName: productName)\n        self.targets.append(target)\n        return target\n    }\n\n    @discardableResult\n    func addAggregateTarget(guid: PIF.GUID, name: String) -> PIFAggregateTargetBuilder {\n        let target = PIFAggregateTargetBuilder(guid: guid, name: name)\n        self.targets.append(target)\n        return target\n    }\n\n    func construct() throws -> PIF.Project {\n        let buildConfigurations = self.buildConfigurations.map { builder -> PIF.BuildConfiguration in\n            builder.guid = \"\\(self.guid)::BUILDCONFIG_\\(builder.name)\"\n            return builder.construct()\n        }\n\n        // Construct group tree before targets to make sure file references have GUIDs.\n        groupTree.guid = \"\\(self.guid)::MAINGROUP\"\n        let groupTree = self.groupTree.construct() as! PIF.Group\n        let targets = try self.targets.map { try $0.construct() }\n\n        return PIF.Project(\n            guid: self.guid,\n            name: self.name,\n            path: self.path,\n            projectDirectory: self.projectDirectory,\n            developmentRegion: self.developmentRegion,\n            buildConfigurations: buildConfigurations,\n            targets: targets,\n            groupTree: groupTree\n        )\n    }\n}\n\nfinal class PackagePIFProjectBuilder: PIFProjectBuilder {\n    private let package: ResolvedPackage\n    private let parameters: PIFBuilderParameters\n    private let fileSystem: FileSystem\n    private let observabilityScope: ObservabilityScope\n    private var binaryGroup: PIFGroupBuilder!\n    private let executableTargetProductMap: [ResolvedModule.ID: ResolvedProduct]\n\n    var isRootPackage: Bool { self.package.manifest.packageKind.isRoot }\n\n    init(\n        package: ResolvedPackage,\n        parameters: PIFBuilderParameters,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        self.package = package\n        self.parameters = parameters\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope.makeChildScope(\n            description: \"Package PIF Builder\",\n            metadata: package.underlying.diagnosticsMetadata\n        )\n\n        self.executableTargetProductMap = try Dictionary(\n            throwingUniqueKeysWithValues: package.products\n                .filter { $0.type == .executable }\n                .map { ($0.mainTarget.id, $0) }\n        )\n\n        super.init()\n\n        self.guid = package.pifProjectGUID\n        self.name = package.manifest.displayName // TODO: use identity instead?\n        self.path = package.path\n        self.projectDirectory = package.path\n        self.developmentRegion = package.manifest.defaultLocalization ?? \"en\"\n        self.binaryGroup = groupTree.addGroup(path: \"/\", sourceTree: .absolute, name: \"Binaries\")\n\n        // Configure the project-wide build settings.  First we set those that are in common between the \"Debug\" and\n        // \"Release\" configurations, and then we set those that are different.\n        var settings = PIF.BuildSettings()\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        settings[.SUPPORTED_PLATFORMS] = [\"$(AVAILABLE_PLATFORMS)\"]\n        settings[.SDKROOT] = \"auto\"\n        settings[.SDK_VARIANT] = \"auto\"\n        settings[.SKIP_INSTALL] = \"YES\"\n        settings[.MACOSX_DEPLOYMENT_TARGET] = package.deploymentTarget(for: .macOS)\n        settings[.IPHONEOS_DEPLOYMENT_TARGET] = package.deploymentTarget(for: .iOS)\n        settings[.IPHONEOS_DEPLOYMENT_TARGET, for: .macCatalyst] = package.deploymentTarget(for: .macCatalyst)\n        settings[.TVOS_DEPLOYMENT_TARGET] = package.deploymentTarget(for: .tvOS)\n        settings[.WATCHOS_DEPLOYMENT_TARGET] = package.deploymentTarget(for: .watchOS)\n        settings[.XROS_DEPLOYMENT_TARGET] = package.deploymentTarget(for: .visionOS)\n        settings[.DRIVERKIT_DEPLOYMENT_TARGET] = package.deploymentTarget(for: .driverKit)\n        settings[.DYLIB_INSTALL_NAME_BASE] = \"@rpath\"\n        settings[.USE_HEADERMAP] = \"NO\"\n        settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS] = [\"$(inherited)\", \"SWIFT_PACKAGE\"]\n        settings[.GCC_PREPROCESSOR_DEFINITIONS] = [\"$(inherited)\", \"SWIFT_PACKAGE\"]\n        settings[.CLANG_ENABLE_OBJC_ARC] = \"YES\"\n\n        settings[.KEEP_PRIVATE_EXTERNS] = \"NO\"\n        // We currently deliberately do not support Swift ObjC interface headers.\n        settings[.SWIFT_INSTALL_OBJC_HEADER] = \"NO\"\n        settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME] = \"\"\n        settings[.OTHER_LDRFLAGS] = []\n\n        // This will add the XCTest related search paths automatically\n        // (including the Swift overlays).\n        settings[.ENABLE_TESTING_SEARCH_PATHS] = \"YES\"\n\n        // XCTest search paths should only be specified for certain platforms (watchOS doesn't have XCTest).\n        for platform: PIF.BuildSettings.Platform in [.macOS, .iOS, .tvOS] {\n            settings[.FRAMEWORK_SEARCH_PATHS, for: platform, default: [\"$(inherited)\"]]\n                .append(\"$(PLATFORM_DIR)/Developer/Library/Frameworks\")\n        }\n\n        PlatformRegistry.default.knownPlatforms.forEach {\n            guard let platform = PIF.BuildSettings.Platform.from(platform: $0) else { return }\n            let supportedPlatform = package.getSupportedPlatform(for: $0, usingXCTest: false)\n            if !supportedPlatform.options.isEmpty {\n                settings[.SPECIALIZATION_SDK_OPTIONS, for: platform] = supportedPlatform.options\n            }\n        }\n\n        // Disable signing for all the things since there is no way to configure\n        // signing information in packages right now.\n        settings[.ENTITLEMENTS_REQUIRED] = \"NO\"\n        settings[.CODE_SIGNING_REQUIRED] = \"NO\"\n        settings[.CODE_SIGN_IDENTITY] = \"\"\n\n        var debugSettings = settings\n        debugSettings[.COPY_PHASE_STRIP] = \"NO\"\n        debugSettings[.DEBUG_INFORMATION_FORMAT] = \"dwarf\"\n        debugSettings[.ENABLE_NS_ASSERTIONS] = \"YES\"\n        debugSettings[.GCC_OPTIMIZATION_LEVEL] = \"0\"\n        debugSettings[.ONLY_ACTIVE_ARCH] = \"YES\"\n        debugSettings[.SWIFT_OPTIMIZATION_LEVEL] = \"-Onone\"\n        debugSettings[.ENABLE_TESTABILITY] = \"YES\"\n        debugSettings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, default: []].append(\"DEBUG\")\n        debugSettings[.GCC_PREPROCESSOR_DEFINITIONS, default: [\"$(inherited)\"]].append(\"DEBUG=1\")\n        addBuildConfiguration(name: \"Debug\", settings: debugSettings)\n\n        var releaseSettings = settings\n        releaseSettings[.COPY_PHASE_STRIP] = \"YES\"\n        releaseSettings[.DEBUG_INFORMATION_FORMAT] = \"dwarf-with-dsym\"\n        releaseSettings[.GCC_OPTIMIZATION_LEVEL] = \"s\"\n        releaseSettings[.SWIFT_OPTIMIZATION_LEVEL] = \"-Owholemodule\"\n\n        if parameters.enableTestability {\n            releaseSettings[.ENABLE_TESTABILITY] = \"YES\"\n        }\n\n        addBuildConfiguration(name: \"Release\", settings: releaseSettings)\n\n        for product in package.products.sorted(by: { $0.name < $1.name }) {\n            let productScope = observabilityScope.makeChildScope(\n                description: \"Adding \\(product.name) product\",\n                metadata: package.underlying.diagnosticsMetadata\n            )\n\n            productScope.trap { try self.addTarget(for: product) }\n        }\n\n        for target in package.modules.sorted(by: { $0.name < $1.name }) {\n            let targetScope = observabilityScope.makeChildScope(\n                description: \"Adding \\(target.name) module\",\n                metadata: package.underlying.diagnosticsMetadata\n            )\n            targetScope.trap { try self.addTarget(for: target) }\n        }\n\n        if self.binaryGroup.children.isEmpty {\n            groupTree.removeChild(self.binaryGroup)\n        }\n    }\n\n    private func addTarget(for product: ResolvedProduct) throws {\n        switch product.type {\n        case .executable, .snippet, .test:\n            try self.addMainModuleTarget(for: product)\n        case .library:\n            self.addLibraryTarget(for: product)\n        case .plugin, .macro:\n            return\n        }\n    }\n\n    private func addTarget(for target: ResolvedModule) throws {\n        switch target.type {\n        case .library:\n            try self.addLibraryTarget(for: target)\n        case .systemModule:\n            try self.addSystemTarget(for: target)\n        case .executable, .snippet, .test:\n            // Skip executable module targets and test module targets (they will have been dealt with as part of the\n            // products to which they belong).\n            return\n        case .binary:\n            // Binary target don't need to be built.\n            return\n        case .plugin:\n            // Package plugin modules.\n            return\n        case .macro:\n            // Macros are not supported when using XCBuild, similar to package plugins.\n            return\n        }\n    }\n\n    private func targetName(for product: ResolvedProduct) -> String {\n        Self.targetName(for: product.name)\n    }\n\n    static func targetName(for productName: String) -> String {\n        \"\\(productName)_\\(String(productName.hash, radix: 16, uppercase: true))_PackageProduct\"\n    }\n\n    private func addMainModuleTarget(for product: ResolvedProduct) throws {\n        let productType: PIF.Target.ProductType = product.type == .executable ? .executable : .unitTest\n        let pifTarget = self.addTarget(\n            guid: product.pifTargetGUID,\n            name: self.targetName(for: product),\n            productType: productType,\n            productName: \"\\(product.name)\\(parameters.triple.executableExtension)\"\n        )\n\n        // We'll be infusing the product's main module target into the one for the product itself.\n        let mainTarget = product.mainTarget\n\n        self.addSources(mainTarget.sources, to: pifTarget)\n\n        let dependencies = try! topologicalSort(mainTarget.dependencies) { $0.packageDependencies }.sorted()\n        for dependency in dependencies {\n            self.addDependency(to: dependency, in: pifTarget, linkProduct: true)\n        }\n\n        // Configure the target-wide build settings. The details depend on the kind of product we're building, but are\n        // in general the ones that are suitable for end-product artifacts such as executables and test bundles.\n        var settings = PIF.BuildSettings()\n        settings[.TARGET_NAME] = product.name\n        settings[.PACKAGE_RESOURCE_TARGET_KIND] = \"regular\"\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        settings[.PRODUCT_MODULE_NAME] = mainTarget.c99name\n        settings[.PRODUCT_BUNDLE_IDENTIFIER] = product.name\n        settings[.CLANG_ENABLE_MODULES] = \"YES\"\n        settings[.DEFINES_MODULE] = \"YES\"\n\n        if product.type == .executable || product.type == .test {\n            if let darwinPlatform = parameters.triple.darwinPlatform {\n                settings[.LIBRARY_SEARCH_PATHS] = [\n                    \"$(inherited)\",\n                    \"\\(self.parameters.toolchainLibDir.pathString)/swift/\\(darwinPlatform.platformName)\",\n                ]\n            }\n        }\n\n        // Tests can have a custom deployment target based on the minimum supported by XCTest.\n        if mainTarget.underlying.type == .test {\n            settings[.MACOSX_DEPLOYMENT_TARGET] = mainTarget.deploymentTarget(for: .macOS, usingXCTest: true)\n            settings[.IPHONEOS_DEPLOYMENT_TARGET] = mainTarget.deploymentTarget(for: .iOS, usingXCTest: true)\n            settings[.TVOS_DEPLOYMENT_TARGET] = mainTarget.deploymentTarget(for: .tvOS, usingXCTest: true)\n            settings[.WATCHOS_DEPLOYMENT_TARGET] = mainTarget.deploymentTarget(for: .watchOS, usingXCTest: true)\n            settings[.XROS_DEPLOYMENT_TARGET] = mainTarget.deploymentTarget(for: .visionOS, usingXCTest: true)\n        }\n\n        if product.type == .executable {\n            // Setup install path for executables if it's in root of a pure Swift package.\n            if self.isRootPackage {\n                settings[.SKIP_INSTALL] = \"NO\"\n                settings[.INSTALL_PATH] = \"/usr/local/bin\"\n                settings[.LD_RUNPATH_SEARCH_PATHS, default: [\"$(inherited)\"]].append(\"@executable_path/../lib\")\n            }\n        } else {\n            // FIXME: we shouldn't always include both the deep and shallow bundle paths here, but for that we'll need\n            // rdar://problem/31867023\n            settings[.LD_RUNPATH_SEARCH_PATHS, default: [\"$(inherited)\"]] +=\n                [\"@loader_path/Frameworks\", \"@loader_path/../Frameworks\"]\n            settings[.GENERATE_INFOPLIST_FILE] = \"YES\"\n        }\n\n        var isSwiftModule = false\n        if let clangTarget = mainTarget.underlying as? ClangModule {\n            // Let the target itself find its own headers.\n            settings[.HEADER_SEARCH_PATHS, default: [\"$(inherited)\"]].append(clangTarget.includeDir.pathString)\n            settings[.GCC_C_LANGUAGE_STANDARD] = clangTarget.cLanguageStandard\n            settings[.CLANG_CXX_LANGUAGE_STANDARD] = clangTarget.cxxLanguageStandard\n        } else if let swiftTarget = mainTarget.underlying as? SwiftModule {\n            isSwiftModule = true\n            try settings.addSwiftVersionSettings(target: swiftTarget, parameters: self.parameters)\n            settings.addCommonSwiftSettings(package: self.package, target: mainTarget, parameters: self.parameters)\n        }\n\n        if let resourceBundle = addResourceBundle(for: mainTarget, in: pifTarget) {\n            settings[.PACKAGE_RESOURCE_BUNDLE_NAME] = resourceBundle\n            settings[.GENERATE_RESOURCE_ACCESSORS] = \"YES\"\n\n            if isSwiftModule {\n                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, default: [\"$(inherited)\"]].append(\"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\")\n            }\n        } else if isSwiftModule {\n            settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, default: [\"$(inherited)\"]].append(\"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\")\n        }\n\n        // For targets, we use the common build settings for both the \"Debug\" and the \"Release\" configurations (all\n        // differentiation is at the project level).\n        var debugSettings = settings\n        var releaseSettings = settings\n\n        var impartedSettings = PIF.BuildSettings()\n        try self.addManifestBuildSettings(\n            from: mainTarget.underlying,\n            debugSettings: &debugSettings,\n            releaseSettings: &releaseSettings,\n            impartedSettings: &impartedSettings\n        )\n\n        let impartedBuildProperties = PIF.ImpartedBuildProperties(settings: impartedSettings)\n        pifTarget.addBuildConfiguration(\n            name: \"Debug\",\n            settings: debugSettings,\n            impartedBuildProperties: impartedBuildProperties\n        )\n        pifTarget.addBuildConfiguration(\n            name: \"Release\",\n            settings: releaseSettings,\n            impartedBuildProperties: impartedBuildProperties\n        )\n    }\n\n    private func addLibraryTarget(for product: ResolvedProduct) {\n        // For the name of the product reference\n        let pifTargetProductName: String\n        let productType: PIF.Target.ProductType\n        if product.type == .library(.dynamic) {\n            if self.parameters.shouldCreateDylibForDynamicProducts {\n                pifTargetProductName = \"\\(parameters.triple.dynamicLibraryPrefix)\\(product.name)\\(parameters.triple.dynamicLibraryExtension)\"\n                productType = .dynamicLibrary\n            } else {\n                pifTargetProductName = product.name + \".framework\"\n                productType = .framework\n            }\n        } else {\n            pifTargetProductName = \"lib\\(product.name)\\(parameters.triple.staticLibraryExtension)\"\n            productType = .packageProduct\n        }\n\n        // Create a special kind of .packageProduct PIF target that just \"groups\" a set of targets for clients to\n        // depend on. XCBuild will not produce a separate artifact for a package product, but will instead consider any\n        // dependency on the package product to be a dependency on the whole set of targets on which the package product\n        // depends.\n        let pifTarget = self.addTarget(\n            guid: product.pifTargetGUID,\n            name: self.targetName(for: product),\n            productType: productType,\n            productName: pifTargetProductName\n        )\n\n        // Handle the dependencies of the targets in the product (and link against them, which in the case of a package\n        // product, really just means that clients should link against them).\n        let dependencies = product.recursivePackageDependencies()\n        for dependency in dependencies {\n            switch dependency {\n            case .module(let target, let conditions):\n                if target.type != .systemModule {\n                    self.addDependency(to: target, in: pifTarget, conditions: conditions, linkProduct: true)\n                }\n            case .product(let product, let conditions):\n                self.addDependency(to: product, in: pifTarget, conditions: conditions, linkProduct: true)\n            }\n        }\n\n        var settings = PIF.BuildSettings()\n        let usesUnsafeFlags = dependencies.contains { $0.module?.underlying.usesUnsafeFlags == true }\n        settings[.USES_SWIFTPM_UNSAFE_FLAGS] = usesUnsafeFlags ? \"YES\" : \"NO\"\n\n        // If there are no system modules in the dependency graph, mark the target as extension-safe.\n        let dependsOnAnySystemModules = dependencies.contains { $0.module?.type == .systemModule }\n        if !dependsOnAnySystemModules {\n            settings[.APPLICATION_EXTENSION_API_ONLY] = \"YES\"\n        }\n\n        // Add other build settings when we're building an actual dylib.\n        if product.type == .library(.dynamic) {\n            settings[.TARGET_NAME] = product.name\n            settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n            settings[.PRODUCT_MODULE_NAME] = product.name\n            settings[.PRODUCT_BUNDLE_IDENTIFIER] = product.name\n            settings[.EXECUTABLE_PREFIX] = parameters.triple.dynamicLibraryPrefix\n            settings[.CLANG_ENABLE_MODULES] = \"YES\"\n            settings[.DEFINES_MODULE] = \"YES\"\n            settings[.SKIP_INSTALL] = \"NO\"\n            settings[.INSTALL_PATH] = \"/usr/local/lib\"\n            if let darwinPlatform = parameters.triple.darwinPlatform {\n                settings[.LIBRARY_SEARCH_PATHS] = [\n                    \"$(inherited)\",\n                    \"\\(self.parameters.toolchainLibDir.pathString)/swift/\\(darwinPlatform.platformName)\",\n                ]\n            }\n\n            if !self.parameters.shouldCreateDylibForDynamicProducts {\n                settings[.GENERATE_INFOPLIST_FILE] = \"YES\"\n                // If the built framework is named same as one of the target in the package, it can be picked up\n                // automatically during indexing since the build system always adds a -F flag to the built products dir.\n                // To avoid this problem, we build all package frameworks in a subdirectory.\n                settings[.BUILT_PRODUCTS_DIR] = \"$(BUILT_PRODUCTS_DIR)/PackageFrameworks\"\n                settings[.TARGET_BUILD_DIR] = \"$(TARGET_BUILD_DIR)/PackageFrameworks\"\n\n                // Set the project and marketing version for the framework because the app store requires these to be\n                // present. The AppStore requires bumping the project version when ingesting new builds but that's for\n                // top-level apps and not frameworks embedded inside it.\n                settings[.MARKETING_VERSION] = \"1.0\" // Version\n                settings[.CURRENT_PROJECT_VERSION] = \"1\" // Build\n            }\n\n            pifTarget.addSourcesBuildPhase()\n        }\n\n        pifTarget.addBuildConfiguration(name: \"Debug\", settings: settings)\n        pifTarget.addBuildConfiguration(name: \"Release\", settings: settings)\n    }\n\n    private func addLibraryTarget(for target: ResolvedModule) throws {\n        let pifTarget = self.addTarget(\n            guid: target.pifTargetGUID,\n            name: target.name,\n            productType: .objectFile,\n            productName: \"\\(target.name)_Module.o\"\n        )\n\n        var settings = PIF.BuildSettings()\n        settings[.TARGET_NAME] = target.name + \"_Module\"\n        settings[.PACKAGE_RESOURCE_TARGET_KIND] = \"regular\"\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        settings[.PRODUCT_MODULE_NAME] = target.c99name\n        settings[.PRODUCT_BUNDLE_IDENTIFIER] = target.name\n        settings[.CLANG_ENABLE_MODULES] = \"YES\"\n        settings[.DEFINES_MODULE] = \"YES\"\n        settings[.MACH_O_TYPE] = \"mh_object\"\n        settings[.GENERATE_MASTER_OBJECT_FILE] = \"NO\"\n        // Disable code coverage linker flags since we're producing .o files. Otherwise, we will run into duplicated\n        // symbols when there are more than one targets that produce .o as their product.\n        settings[.CLANG_COVERAGE_MAPPING_LINKER_ARGS] = \"NO\"\n        if let aliases = target.moduleAliases {\n            settings[.SWIFT_MODULE_ALIASES] = aliases.map { $0.key + \"=\" + $0.value }\n        }\n\n        // Create a set of build settings that will be imparted to any target that depends on this one.\n        var impartedSettings = PIF.BuildSettings()\n\n        let generatedModuleMapDir = \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)\"\n        let moduleMapFile = \"\\(generatedModuleMapDir)/\\(target.name).modulemap\"\n        let moduleMapFileContents: String?\n        let shouldImpartModuleMap: Bool\n\n        var isSwiftModule = false\n        if let clangTarget = target.underlying as? ClangModule {\n            // Let the target itself find its own headers.\n            settings[.HEADER_SEARCH_PATHS, default: [\"$(inherited)\"]].append(clangTarget.includeDir.pathString)\n            settings[.GCC_C_LANGUAGE_STANDARD] = clangTarget.cLanguageStandard\n            settings[.CLANG_CXX_LANGUAGE_STANDARD] = clangTarget.cxxLanguageStandard\n\n            // Also propagate this search path to all direct and indirect clients.\n            impartedSettings[.HEADER_SEARCH_PATHS, default: [\"$(inherited)\"]].append(clangTarget.includeDir.pathString)\n\n            if !self.fileSystem.exists(clangTarget.moduleMapPath) {\n                impartedSettings[.OTHER_SWIFT_FLAGS, default: [\"$(inherited)\"]] +=\n                    [\"-Xcc\", \"-fmodule-map-file=\\(moduleMapFile)\"]\n\n                moduleMapFileContents = \"\"\"\n                module \\(target.c99name) {\n                    umbrella \"\\(clangTarget.includeDir.pathString)\"\n                    export *\n                }\n                \"\"\"\n\n                shouldImpartModuleMap = true\n            } else {\n                moduleMapFileContents = nil\n                shouldImpartModuleMap = false\n            }\n        } else if let swiftTarget = target.underlying as? SwiftModule {\n            isSwiftModule = true\n            try settings.addSwiftVersionSettings(target: swiftTarget, parameters: self.parameters)\n\n            // Generate ObjC compatibility header for Swift library targets.\n            settings[.SWIFT_OBJC_INTERFACE_HEADER_DIR] = \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)\"\n            settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME] = \"\\(target.name)-Swift.h\"\n\n            settings.addCommonSwiftSettings(package: self.package, target: target, parameters: self.parameters)\n\n            moduleMapFileContents = \"\"\"\n            module \\(target.c99name) {\n                header \"\\(target.name)-Swift.h\"\n                export *\n            }\n            \"\"\"\n\n            shouldImpartModuleMap = true\n        } else {\n            throw InternalError(\"unexpected target\")\n        }\n\n        if let moduleMapFileContents {\n            settings[.MODULEMAP_PATH] = moduleMapFile\n            settings[.MODULEMAP_FILE_CONTENTS] = moduleMapFileContents\n        }\n\n        // Pass the path of the module map up to all direct and indirect clients.\n        if shouldImpartModuleMap {\n            impartedSettings[.OTHER_CFLAGS, default: [\"$(inherited)\"]].append(\"-fmodule-map-file=\\(moduleMapFile)\")\n        }\n        impartedSettings[.OTHER_LDRFLAGS] = []\n\n        if target.underlying.isCxx {\n            impartedSettings[.OTHER_LDFLAGS, default: [\"$(inherited)\"]].append(\"-lc++\")\n        }\n\n        // radar://112671586 supress unnecessary warnings\n        impartedSettings[.OTHER_LDFLAGS, default: [\"$(inherited)\"]].append(\"-Wl,-no_warn_duplicate_libraries\")\n\n        self.addSources(target.sources, to: pifTarget)\n\n        // Handle the target's dependencies (but don't link against them).\n        let dependencies = try! topologicalSort(target.dependencies) { $0.packageDependencies }.sorted()\n        for dependency in dependencies {\n            self.addDependency(to: dependency, in: pifTarget, linkProduct: false)\n        }\n\n        if let resourceBundle = addResourceBundle(for: target, in: pifTarget) {\n            settings[.PACKAGE_RESOURCE_BUNDLE_NAME] = resourceBundle\n            settings[.GENERATE_RESOURCE_ACCESSORS] = \"YES\"\n            if isSwiftModule {\n                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, default: [\"$(inherited)\"]].append(\"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\")\n            }\n            impartedSettings[.EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES, default: [\"$(inherited)\"]].append(resourceBundle)\n        } else if isSwiftModule {\n            settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, default: [\"$(inherited)\"]].append(\"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\")\n        }\n\n        // For targets, we use the common build settings for both the \"Debug\" and the \"Release\" configurations (all\n        // differentiation is at the project level).\n        var debugSettings = settings\n        var releaseSettings = settings\n\n        try addManifestBuildSettings(\n            from: target.underlying,\n            debugSettings: &debugSettings,\n            releaseSettings: &releaseSettings,\n            impartedSettings: &impartedSettings\n        )\n\n        let impartedBuildProperties = PIF.ImpartedBuildProperties(settings: impartedSettings)\n        pifTarget.addBuildConfiguration(\n            name: \"Debug\",\n            settings: debugSettings,\n            impartedBuildProperties: impartedBuildProperties\n        )\n        pifTarget.addBuildConfiguration(\n            name: \"Release\",\n            settings: releaseSettings,\n            impartedBuildProperties: impartedBuildProperties\n        )\n        pifTarget.impartedBuildSettings = impartedSettings\n    }\n\n    private func addSystemTarget(for target: ResolvedModule) throws {\n        guard let systemTarget = target.underlying as? SystemLibraryModule else {\n            throw InternalError(\"unexpected target type\")\n        }\n\n        // Impart the header search path to all direct and indirect clients.\n        var impartedSettings = PIF.BuildSettings()\n\n        var cFlags: [String] = []\n        for result in try pkgConfigArgs(\n            for: systemTarget,\n            pkgConfigDirectories: self.parameters.pkgConfigDirectories,\n            sdkRootPath: self.parameters.sdkRootPath,\n            fileSystem: self.fileSystem,\n            observabilityScope: self.observabilityScope\n        ) {\n            if let error = result.error {\n                self.observabilityScope.emit(\n                    warning: \"\\(error.interpolationDescription)\",\n                    metadata: .pkgConfig(pcFile: result.pkgConfigName, targetName: target.name)\n                )\n            } else {\n                cFlags = result.cFlags\n                impartedSettings[.OTHER_LDFLAGS, default: [\"$(inherited)\"]] += result.libs\n            }\n        }\n\n        impartedSettings[.OTHER_LDRFLAGS] = []\n        impartedSettings[.OTHER_CFLAGS, default: [\"$(inherited)\"]] +=\n            [\"-fmodule-map-file=\\(systemTarget.moduleMapPath)\"] + cFlags\n        impartedSettings[.OTHER_SWIFT_FLAGS, default: [\"$(inherited)\"]] +=\n            [\"-Xcc\", \"-fmodule-map-file=\\(systemTarget.moduleMapPath)\"] + cFlags\n        let impartedBuildProperties = PIF.ImpartedBuildProperties(settings: impartedSettings)\n\n        // Create an aggregate PIF target (which doesn't have an actual product).\n        let pifTarget = addAggregateTarget(guid: target.pifTargetGUID, name: target.name)\n        pifTarget.addBuildConfiguration(\n            name: \"Debug\",\n            settings: PIF.BuildSettings(),\n            impartedBuildProperties: impartedBuildProperties\n        )\n        pifTarget.addBuildConfiguration(\n            name: \"Release\",\n            settings: PIF.BuildSettings(),\n            impartedBuildProperties: impartedBuildProperties\n        )\n        pifTarget.impartedBuildSettings = impartedSettings\n    }\n\n    private func addSources(_ sources: Sources, to pifTarget: PIFTargetBuilder) {\n        // Create a group for the target's source files.  For now we use an absolute path for it, but we should really\n        // make it be container-relative, since it's always inside the package directory.\n        let targetGroup = groupTree.addGroup(\n            path: sources.root.relative(to: self.package.path).pathString,\n            sourceTree: .group\n        )\n\n        // Add a source file reference for each of the source files, and also an indexable-file URL for each one.\n        for path in sources.relativePaths {\n            pifTarget.addSourceFile(targetGroup.addFileReference(path: path.pathString, sourceTree: .group))\n        }\n    }\n\n    private func addDependency(\n        to dependency: ResolvedModule.Dependency,\n        in pifTarget: PIFTargetBuilder,\n        linkProduct: Bool\n    ) {\n        switch dependency {\n        case .module(let target, let conditions):\n            self.addDependency(\n                to: target,\n                in: pifTarget,\n                conditions: conditions,\n                linkProduct: linkProduct\n            )\n        case .product(let product, let conditions):\n            self.addDependency(\n                to: product,\n                in: pifTarget,\n                conditions: conditions,\n                linkProduct: linkProduct\n            )\n        }\n    }\n\n    private func addDependency(\n        to target: ResolvedModule,\n        in pifTarget: PIFTargetBuilder,\n        conditions: [PackageCondition],\n        linkProduct: Bool\n    ) {\n        // Only add the binary target as a library when we want to link against the product.\n        if let binaryTarget = target.underlying as? BinaryModule {\n            let ref = self.binaryGroup.addFileReference(path: binaryTarget.artifactPath.pathString)\n            pifTarget.addLibrary(ref, platformFilters: conditions.toPlatformFilters())\n        } else {\n            // If this is an executable target, the dependency should be to the PIF target created from the its\n            // product, as we don't have PIF targets corresponding to executable targets.\n            let targetGUID = self.executableTargetProductMap[target.id]?.pifTargetGUID ?? target.pifTargetGUID\n            let linkProduct = linkProduct && target.type != .systemModule && target.type != .executable\n            pifTarget.addDependency(\n                toTargetWithGUID: targetGUID,\n                platformFilters: conditions.toPlatformFilters(),\n                linkProduct: linkProduct\n            )\n        }\n    }\n\n    private func addDependency(\n        to product: ResolvedProduct,\n        in pifTarget: PIFTargetBuilder,\n        conditions: [PackageCondition],\n        linkProduct: Bool\n    ) {\n        pifTarget.addDependency(\n            toTargetWithGUID: product.pifTargetGUID,\n            platformFilters: conditions.toPlatformFilters(),\n            linkProduct: linkProduct\n        )\n    }\n\n    private func addResourceBundle(for target: ResolvedModule, in pifTarget: PIFTargetBuilder) -> String? {\n        guard !target.underlying.resources.isEmpty else {\n            return nil\n        }\n\n        let bundleName = \"\\(package.manifest.displayName)_\\(target.name)\" // TODO: use identity instead?\n        let resourcesTarget = self.addTarget(\n            guid: target.pifResourceTargetGUID,\n            name: bundleName,\n            productType: .bundle,\n            productName: bundleName\n        )\n\n        pifTarget.addDependency(\n            toTargetWithGUID: resourcesTarget.guid,\n            platformFilters: [],\n            linkProduct: false\n        )\n\n        var settings = PIF.BuildSettings()\n        settings[.TARGET_NAME] = bundleName\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        settings[.PRODUCT_MODULE_NAME] = bundleName\n        let bundleIdentifier = \"\\(package.manifest.displayName).\\(target.name).resources\"\n            .spm_mangledToBundleIdentifier() // TODO: use identity instead?\n        settings[.PRODUCT_BUNDLE_IDENTIFIER] = bundleIdentifier\n        settings[.GENERATE_INFOPLIST_FILE] = \"YES\"\n        settings[.PACKAGE_RESOURCE_TARGET_KIND] = \"resource\"\n\n        resourcesTarget.addBuildConfiguration(name: \"Debug\", settings: settings)\n        resourcesTarget.addBuildConfiguration(name: \"Release\", settings: settings)\n\n        let coreDataFileTypes = [XCBuildFileType.xcdatamodeld, .xcdatamodel].flatMap(\\.fileTypes)\n        for resource in target.underlying.resources {\n            // FIXME: Handle rules here.\n            let resourceFile = groupTree.addFileReference(\n                path: resource.path.pathString,\n                sourceTree: .absolute\n            )\n\n            // CoreData files should also be in the actual target because they can end up generating code during the\n            // build. The build system will only perform codegen tasks for the main target in this case.\n            if coreDataFileTypes.contains(resource.path.extension ?? \"\") {\n                pifTarget.addSourceFile(resourceFile)\n            }\n\n            // Asset Catalogs need to be included in the sources target for generated asset symbols.\n            if XCBuildFileType.xcassets.fileTypes.contains(resource.path.extension ?? \"\") {\n                pifTarget.addSourceFile(resourceFile)\n            }\n\n            // String Catalogs can also generate symbols.\n            if XCBuildFileType.xcstrings.fileTypes.contains(resource.path.extension ?? \"\") {\n                pifTarget.addSourceFile(resourceFile)\n            }\n\n            resourcesTarget.addResourceFile(resourceFile)\n        }\n\n        let targetGroup = groupTree.addGroup(path: \"/\", sourceTree: .group)\n        pifTarget.addResourceFile(targetGroup.addFileReference(\n            path: \"\\(bundleName)\\(parameters.triple.nsbundleExtension)\",\n            sourceTree: .builtProductsDir\n        ))\n\n        return bundleName\n    }\n\n    // Add inferred build settings for a particular value for a manifest setting and value.\n    private func addInferredBuildSettings(\n        for setting: PIF.BuildSettings.MultipleValueSetting,\n        value: [String],\n        platform: PIF.BuildSettings.Platform? = nil,\n        configuration: BuildConfiguration,\n        settings: inout PIF.BuildSettings\n    ) {\n        // Automatically set SWIFT_EMIT_MODULE_INTERFACE if the package author uses unsafe flags to enable\n        // library evolution (this is needed until there is a way to specify this in the package manifest).\n        if setting == .OTHER_SWIFT_FLAGS && value.contains(\"-enable-library-evolution\") {\n            settings[.SWIFT_EMIT_MODULE_INTERFACE] = \"YES\"\n        }\n    }\n\n    // Apply target-specific build settings defined in the manifest.\n    private func addManifestBuildSettings(\n        from target: Module,\n        debugSettings: inout PIF.BuildSettings,\n        releaseSettings: inout PIF.BuildSettings,\n        impartedSettings: inout PIF.BuildSettings\n    ) throws {\n        for (setting, assignments) in target.buildSettings.pifAssignments {\n            for assignment in assignments {\n                var value = assignment.value\n                if setting == .HEADER_SEARCH_PATHS {\n                    value = try value\n                        .map { try AbsolutePath(validating: $0, relativeTo: target.sources.root).pathString }\n                }\n\n                if let platforms = assignment.platforms {\n                    for platform in platforms {\n                        for configuration in assignment.configurations {\n                            switch configuration {\n                            case .debug:\n                                debugSettings[setting, for: platform, default: [\"$(inherited)\"]] += value\n                                self.addInferredBuildSettings(\n                                    for: setting,\n                                    value: value,\n                                    platform: platform,\n                                    configuration: .debug,\n                                    settings: &debugSettings\n                                )\n                            case .release:\n                                releaseSettings[setting, for: platform, default: [\"$(inherited)\"]] += value\n                                self.addInferredBuildSettings(\n                                    for: setting,\n                                    value: value,\n                                    platform: platform,\n                                    configuration: .release,\n                                    settings: &releaseSettings\n                                )\n                            }\n                        }\n\n                        if setting == .OTHER_LDFLAGS {\n                            impartedSettings[setting, for: platform, default: [\"$(inherited)\"]] += value\n                        }\n                    }\n                } else {\n                    for configuration in assignment.configurations {\n                        switch configuration {\n                        case .debug:\n                            debugSettings[setting, default: [\"$(inherited)\"]] += value\n                            self.addInferredBuildSettings(\n                                for: setting,\n                                value: value,\n                                configuration: .debug,\n                                settings: &debugSettings\n                            )\n                        case .release:\n                            releaseSettings[setting, default: [\"$(inherited)\"]] += value\n                            self.addInferredBuildSettings(\n                                for: setting,\n                                value: value,\n                                configuration: .release,\n                                settings: &releaseSettings\n                            )\n                        }\n                    }\n\n                    if setting == .OTHER_LDFLAGS {\n                        impartedSettings[setting, default: [\"$(inherited)\"]] += value\n                    }\n                }\n            }\n        }\n    }\n}\n\nfinal class AggregatePIFProjectBuilder: PIFProjectBuilder {\n    init(projects: [PIFProjectBuilder]) {\n        super.init()\n\n        guid = \"AGGREGATE\"\n        name = \"Aggregate\"\n        path = projects[0].path\n        projectDirectory = projects[0].projectDirectory\n        developmentRegion = \"en\"\n\n        var settings = PIF.BuildSettings()\n        settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n        settings[.SUPPORTED_PLATFORMS] = [\"$(AVAILABLE_PLATFORMS)\"]\n        settings[.SDKROOT] = \"auto\"\n        settings[.SDK_VARIANT] = \"auto\"\n        settings[.SKIP_INSTALL] = \"YES\"\n\n        addBuildConfiguration(name: \"Debug\", settings: settings)\n        addBuildConfiguration(name: \"Release\", settings: settings)\n\n        let allExcludingTestsTarget = addAggregateTarget(\n            guid: \"ALL-EXCLUDING-TESTS\",\n            name: PIFBuilder.allExcludingTestsTargetName\n        )\n\n        allExcludingTestsTarget.addBuildConfiguration(name: \"Debug\")\n        allExcludingTestsTarget.addBuildConfiguration(name: \"Release\")\n\n        let allIncludingTestsTarget = addAggregateTarget(\n            guid: \"ALL-INCLUDING-TESTS\",\n            name: PIFBuilder.allIncludingTestsTargetName\n        )\n\n        allIncludingTestsTarget.addBuildConfiguration(name: \"Debug\")\n        allIncludingTestsTarget.addBuildConfiguration(name: \"Release\")\n\n        for case let project as PackagePIFProjectBuilder in projects where project.isRootPackage {\n            for case let target as PIFTargetBuilder in project.targets {\n                if target.productType != .unitTest {\n                    allExcludingTestsTarget.addDependency(\n                        toTargetWithGUID: target.guid,\n                        platformFilters: [],\n                        linkProduct: false\n                    )\n                }\n\n                allIncludingTestsTarget.addDependency(\n                    toTargetWithGUID: target.guid,\n                    platformFilters: [],\n                    linkProduct: false\n                )\n            }\n        }\n    }\n}\n\nprotocol PIFReferenceBuilder: AnyObject {\n    var guid: String { get set }\n\n    func construct() -> PIF.Reference\n}\n\nfinal class PIFFileReferenceBuilder: PIFReferenceBuilder {\n    let path: String\n    let sourceTree: PIF.Reference.SourceTree\n    let name: String?\n    let fileType: String?\n\n    @DelayedImmutable\n    var guid: String\n\n    init(path: String, sourceTree: PIF.Reference.SourceTree, name: String? = nil, fileType: String? = nil) {\n        self.path = path\n        self.sourceTree = sourceTree\n        self.name = name\n        self.fileType = fileType\n    }\n\n    func construct() -> PIF.Reference {\n        PIF.FileReference(\n            guid: self.guid,\n            path: self.path,\n            sourceTree: self.sourceTree,\n            name: self.name,\n            fileType: self.fileType\n        )\n    }\n}\n\nfinal class PIFGroupBuilder: PIFReferenceBuilder {\n    let path: String\n    let sourceTree: PIF.Reference.SourceTree\n    let name: String?\n    private(set) var children: [PIFReferenceBuilder]\n\n    @DelayedImmutable\n    var guid: PIF.GUID\n\n    init(path: String, sourceTree: PIF.Reference.SourceTree = .group, name: String? = nil) {\n        self.path = path\n        self.sourceTree = sourceTree\n        self.name = name\n        self.children = []\n    }\n\n    /// Creates and appends a new Group to the list of children. The new group is returned so that it can be configured.\n    func addGroup(\n        path: String,\n        sourceTree: PIF.Reference.SourceTree = .group,\n        name: String? = nil\n    ) -> PIFGroupBuilder {\n        let group = PIFGroupBuilder(path: path, sourceTree: sourceTree, name: name)\n        self.children.append(group)\n        return group\n    }\n\n    /// Creates and appends a new FileReference to the list of children.\n    func addFileReference(\n        path: String,\n        sourceTree: PIF.Reference.SourceTree = .group,\n        name: String? = nil,\n        fileType: String? = nil\n    ) -> PIFFileReferenceBuilder {\n        let file = PIFFileReferenceBuilder(path: path, sourceTree: sourceTree, name: name, fileType: fileType)\n        self.children.append(file)\n        return file\n    }\n\n    func removeChild(_ reference: PIFReferenceBuilder) {\n        self.children.removeAll { $0 === reference }\n    }\n\n    func construct() -> PIF.Reference {\n        let children = self.children.enumerated().map { kvp -> PIF.Reference in\n            let (index, builder) = kvp\n            builder.guid = \"\\(self.guid)::REF_\\(index)\"\n            return builder.construct()\n        }\n\n        return PIF.Group(\n            guid: self.guid,\n            path: self.path,\n            sourceTree: self.sourceTree,\n            name: self.name,\n            children: children\n        )\n    }\n}\n\nclass PIFBaseTargetBuilder {\n    public let guid: PIF.GUID\n    public let name: String\n    public fileprivate(set) var buildConfigurations: [PIFBuildConfigurationBuilder]\n    public fileprivate(set) var buildPhases: [PIFBuildPhaseBuilder]\n    public fileprivate(set) var dependencies: [PIF.TargetDependency]\n    public fileprivate(set) var impartedBuildSettings: PIF.BuildSettings\n\n    fileprivate init(guid: PIF.GUID, name: String) {\n        self.guid = guid\n        self.name = name\n        self.buildConfigurations = []\n        self.buildPhases = []\n        self.dependencies = []\n        self.impartedBuildSettings = PIF.BuildSettings()\n    }\n\n    /// Creates and adds a new empty build configuration, i.e. one that does not initially have any build settings.\n    /// The name must not be empty and must not be equal to the name of any existing build configuration in the\n    /// target.\n    @discardableResult\n    public func addBuildConfiguration(\n        name: String,\n        settings: PIF.BuildSettings = PIF.BuildSettings(),\n        impartedBuildProperties: PIF.ImpartedBuildProperties = PIF\n            .ImpartedBuildProperties(settings: PIF.BuildSettings())\n    ) -> PIFBuildConfigurationBuilder {\n        let builder = PIFBuildConfigurationBuilder(\n            name: name,\n            settings: settings,\n            impartedBuildProperties: impartedBuildProperties\n        )\n        self.buildConfigurations.append(builder)\n        return builder\n    }\n\n    func construct() throws -> PIF.BaseTarget {\n        throw InternalError(\"implement in subclass\")\n    }\n\n    /// Adds a \"headers\" build phase, i.e. one that copies headers into a directory of the product, after suitable\n    /// processing.\n    @discardableResult\n    func addHeadersBuildPhase() -> PIFHeadersBuildPhaseBuilder {\n        let buildPhase = PIFHeadersBuildPhaseBuilder()\n        self.buildPhases.append(buildPhase)\n        return buildPhase\n    }\n\n    /// Adds a \"sources\" build phase, i.e. one that compiles sources and provides them to be linked into the\n    /// executable code of the product.\n    @discardableResult\n    func addSourcesBuildPhase() -> PIFSourcesBuildPhaseBuilder {\n        let buildPhase = PIFSourcesBuildPhaseBuilder()\n        self.buildPhases.append(buildPhase)\n        return buildPhase\n    }\n\n    /// Adds a \"frameworks\" build phase, i.e. one that links compiled code and libraries into the executable of the\n    /// product.\n    @discardableResult\n    func addFrameworksBuildPhase() -> PIFFrameworksBuildPhaseBuilder {\n        let buildPhase = PIFFrameworksBuildPhaseBuilder()\n        self.buildPhases.append(buildPhase)\n        return buildPhase\n    }\n\n    @discardableResult\n    func addResourcesBuildPhase() -> PIFResourcesBuildPhaseBuilder {\n        let buildPhase = PIFResourcesBuildPhaseBuilder()\n        self.buildPhases.append(buildPhase)\n        return buildPhase\n    }\n\n    /// Adds a dependency on another target. It is the caller's responsibility to avoid creating dependency cycles.\n    /// A dependency of one target on another ensures that the other target is built first. If `linkProduct` is\n    /// true, the receiver will also be configured to link against the product produced by the other target (this\n    /// presumes that the product type is one that can be linked against).\n    func addDependency(toTargetWithGUID targetGUID: String, platformFilters: [PIF.PlatformFilter], linkProduct: Bool) {\n        self.dependencies.append(.init(targetGUID: targetGUID, platformFilters: platformFilters))\n        if linkProduct {\n            let frameworksPhase = self.buildPhases.first { $0 is PIFFrameworksBuildPhaseBuilder }\n                ?? self.addFrameworksBuildPhase()\n            frameworksPhase.addBuildFile(toTargetWithGUID: targetGUID, platformFilters: platformFilters)\n        }\n    }\n\n    /// Convenience function to add a file reference to the Headers build phase, after creating it if needed.\n    @discardableResult\n    public func addHeaderFile(\n        _ fileReference: PIFFileReferenceBuilder,\n        headerVisibility: PIF.BuildFile.HeaderVisibility\n    ) -> PIFBuildFileBuilder {\n        let headerPhase = self.buildPhases.first { $0 is PIFHeadersBuildPhaseBuilder } ?? self.addHeadersBuildPhase()\n        return headerPhase.addBuildFile(to: fileReference, platformFilters: [], headerVisibility: headerVisibility)\n    }\n\n    /// Convenience function to add a file reference to the Sources build phase, after creating it if needed.\n    @discardableResult\n    public func addSourceFile(_ fileReference: PIFFileReferenceBuilder) -> PIFBuildFileBuilder {\n        let sourcesPhase = self.buildPhases.first { $0 is PIFSourcesBuildPhaseBuilder } ?? self.addSourcesBuildPhase()\n        return sourcesPhase.addBuildFile(to: fileReference, platformFilters: [])\n    }\n\n    /// Convenience function to add a file reference to the Frameworks build phase, after creating it if needed.\n    @discardableResult\n    public func addLibrary(\n        _ fileReference: PIFFileReferenceBuilder,\n        platformFilters: [PIF.PlatformFilter]\n    ) -> PIFBuildFileBuilder {\n        let frameworksPhase = self.buildPhases.first { $0 is PIFFrameworksBuildPhaseBuilder } ?? self\n            .addFrameworksBuildPhase()\n        return frameworksPhase.addBuildFile(to: fileReference, platformFilters: platformFilters)\n    }\n\n    @discardableResult\n    public func addResourceFile(_ fileReference: PIFFileReferenceBuilder) -> PIFBuildFileBuilder {\n        let resourcesPhase = self.buildPhases.first { $0 is PIFResourcesBuildPhaseBuilder } ?? self\n            .addResourcesBuildPhase()\n        return resourcesPhase.addBuildFile(to: fileReference, platformFilters: [])\n    }\n\n    fileprivate func constructBuildConfigurations() -> [PIF.BuildConfiguration] {\n        self.buildConfigurations.map { builder -> PIF.BuildConfiguration in\n            builder.guid = \"\\(self.guid)::BUILDCONFIG_\\(builder.name)\"\n            return builder.construct()\n        }\n    }\n\n    fileprivate func constructBuildPhases() throws -> [PIF.BuildPhase] {\n        try self.buildPhases.enumerated().map { kvp in\n            let (index, builder) = kvp\n            builder.guid = \"\\(self.guid)::BUILDPHASE_\\(index)\"\n            return try builder.construct()\n        }\n    }\n}\n\nfinal class PIFAggregateTargetBuilder: PIFBaseTargetBuilder {\n    override func construct() throws -> PIF.BaseTarget {\n        try PIF.AggregateTarget(\n            guid: guid,\n            name: name,\n            buildConfigurations: constructBuildConfigurations(),\n            buildPhases: self.constructBuildPhases(),\n            dependencies: dependencies,\n            impartedBuildSettings: impartedBuildSettings\n        )\n    }\n}\n\nfinal class PIFTargetBuilder: PIFBaseTargetBuilder {\n    let productType: PIF.Target.ProductType\n    let productName: String\n    var productReference: PIF.FileReference? = nil\n\n    public init(guid: PIF.GUID, name: String, productType: PIF.Target.ProductType, productName: String) {\n        self.productType = productType\n        self.productName = productName\n        super.init(guid: guid, name: name)\n    }\n\n    override func construct() throws -> PIF.BaseTarget {\n        try PIF.Target(\n            guid: guid,\n            name: name,\n            productType: self.productType,\n            productName: self.productName,\n            buildConfigurations: constructBuildConfigurations(),\n            buildPhases: self.constructBuildPhases(),\n            dependencies: dependencies,\n            impartedBuildSettings: impartedBuildSettings\n        )\n    }\n}\n\nclass PIFBuildPhaseBuilder {\n    public private(set) var buildFiles: [PIFBuildFileBuilder]\n\n    @DelayedImmutable\n    var guid: PIF.GUID\n\n    fileprivate init() {\n        self.buildFiles = []\n    }\n\n    /// Adds a new build file builder that refers to a file reference.\n    /// - Parameters:\n    ///   - file: The builder for the file reference.\n    @discardableResult\n    func addBuildFile(\n        to file: PIFFileReferenceBuilder,\n        platformFilters: [PIF.PlatformFilter],\n        headerVisibility: PIF.BuildFile.HeaderVisibility? = nil\n    ) -> PIFBuildFileBuilder {\n        let builder = PIFBuildFileBuilder(\n            file: file,\n            platformFilters: platformFilters,\n            headerVisibility: headerVisibility\n        )\n        self.buildFiles.append(builder)\n        return builder\n    }\n\n    /// Adds a new build file builder that refers to a target GUID.\n    /// - Parameters:\n    ///   - targetGUID: The GIUD referencing the target.\n    @discardableResult\n    func addBuildFile(\n        toTargetWithGUID targetGUID: PIF.GUID,\n        platformFilters: [PIF.PlatformFilter]\n    ) -> PIFBuildFileBuilder {\n        let builder = PIFBuildFileBuilder(targetGUID: targetGUID, platformFilters: platformFilters)\n        self.buildFiles.append(builder)\n        return builder\n    }\n\n    func construct() throws -> PIF.BuildPhase {\n        throw InternalError(\"implement in subclass\")\n    }\n\n    fileprivate func constructBuildFiles() -> [PIF.BuildFile] {\n        self.buildFiles.enumerated().map { kvp -> PIF.BuildFile in\n            let (index, builder) = kvp\n            builder.guid = \"\\(self.guid)::\\(index)\"\n            return builder.construct()\n        }\n    }\n}\n\nfinal class PIFHeadersBuildPhaseBuilder: PIFBuildPhaseBuilder {\n    override func construct() -> PIF.BuildPhase {\n        PIF.HeadersBuildPhase(guid: guid, buildFiles: constructBuildFiles())\n    }\n}\n\nfinal class PIFSourcesBuildPhaseBuilder: PIFBuildPhaseBuilder {\n    override func construct() -> PIF.BuildPhase {\n        PIF.SourcesBuildPhase(guid: guid, buildFiles: constructBuildFiles())\n    }\n}\n\nfinal class PIFFrameworksBuildPhaseBuilder: PIFBuildPhaseBuilder {\n    override func construct() -> PIF.BuildPhase {\n        PIF.FrameworksBuildPhase(guid: guid, buildFiles: constructBuildFiles())\n    }\n}\n\nfinal class PIFResourcesBuildPhaseBuilder: PIFBuildPhaseBuilder {\n    override func construct() -> PIF.BuildPhase {\n        PIF.ResourcesBuildPhase(guid: guid, buildFiles: constructBuildFiles())\n    }\n}\n\nfinal class PIFBuildFileBuilder {\n    private enum Reference {\n        case file(builder: PIFFileReferenceBuilder)\n        case target(guid: PIF.GUID)\n\n        var pifReference: PIF.BuildFile.Reference {\n            switch self {\n            case .file(let builder):\n                .file(guid: builder.guid)\n            case .target(let guid):\n                .target(guid: guid)\n            }\n        }\n    }\n\n    private let reference: Reference\n\n    @DelayedImmutable\n    var guid: PIF.GUID\n\n    let platformFilters: [PIF.PlatformFilter]\n\n    let headerVisibility: PIF.BuildFile.HeaderVisibility?\n\n    fileprivate init(\n        file: PIFFileReferenceBuilder,\n        platformFilters: [PIF.PlatformFilter],\n        headerVisibility: PIF.BuildFile.HeaderVisibility? = nil\n    ) {\n        self.reference = .file(builder: file)\n        self.platformFilters = platformFilters\n        self.headerVisibility = headerVisibility\n    }\n\n    fileprivate init(\n        targetGUID: PIF.GUID,\n        platformFilters: [PIF.PlatformFilter],\n        headerVisibility: PIF.BuildFile.HeaderVisibility? = nil\n    ) {\n        self.reference = .target(guid: targetGUID)\n        self.platformFilters = platformFilters\n        self.headerVisibility = headerVisibility\n    }\n\n    func construct() -> PIF.BuildFile {\n        PIF.BuildFile(\n            guid: self.guid,\n            reference: self.reference.pifReference,\n            platformFilters: self.platformFilters,\n            headerVisibility: self.headerVisibility\n        )\n    }\n}\n\nfinal class PIFBuildConfigurationBuilder {\n    let name: String\n    let settings: PIF.BuildSettings\n    let impartedBuildProperties: PIF.ImpartedBuildProperties\n\n    @DelayedImmutable\n    var guid: PIF.GUID\n\n    public init(name: String, settings: PIF.BuildSettings, impartedBuildProperties: PIF.ImpartedBuildProperties) {\n        precondition(!name.isEmpty)\n        self.name = name\n        self.settings = settings\n        self.impartedBuildProperties = impartedBuildProperties\n    }\n\n    func construct() -> PIF.BuildConfiguration {\n        PIF.BuildConfiguration(\n            guid: self.guid,\n            name: self.name,\n            buildSettings: self.settings,\n            impartedBuildProperties: self.impartedBuildProperties\n        )\n    }\n}\n\n// Helper functions to consistently generate a PIF target identifier string for a product/target/resource bundle in a\n// package. This format helps make sure that there is no collision with any other PIF targets, and in particular that a\n// PIF target and a PIF product can have the same name (as they often do).\n\nextension ResolvedPackage {\n    var pifProjectGUID: PIF.GUID { \"PACKAGE:\\(manifest.packageLocation)\" }\n}\n\nextension ResolvedProduct {\n    var pifTargetGUID: PIF.GUID { \"PACKAGE-PRODUCT:\\(name)\" }\n\n    var mainTarget: ResolvedModule {\n        modules.first { $0.type == underlying.type.targetType }!\n    }\n\n    /// Returns the recursive dependencies, limited to the target's package, which satisfy the input build environment,\n    /// based on their conditions and in a stable order.\n    /// - Parameters:\n    ///     - environment: The build environment to use to filter dependencies on.\n    public func recursivePackageDependencies() -> [ResolvedModule.Dependency] {\n        let initialDependencies = modules.map { ResolvedModule.Dependency.module($0, conditions: []) }\n        return try! topologicalSort(initialDependencies) { dependency in\n            dependency.packageDependencies\n        }.sorted()\n    }\n}\n\nextension ResolvedModule {\n    var pifTargetGUID: PIF.GUID { \"PACKAGE-TARGET:\\(name)\" }\n    var pifResourceTargetGUID: PIF.GUID { \"PACKAGE-RESOURCE:\\(name)\" }\n}\n\nextension [ResolvedModule.Dependency] {\n    /// Sorts to get products first, sorted by name, followed by targets, sorted by name.\n    func sorted() -> [ResolvedModule.Dependency] {\n        self.sorted { lhsDependency, rhsDependency in\n            switch (lhsDependency, rhsDependency) {\n            case (.product, .module):\n                true\n            case (.module, .product):\n                false\n            case (.product(let lhsProduct, _), .product(let rhsProduct, _)):\n                lhsProduct.name < rhsProduct.name\n            case (.module(let lhsTarget, _), .module(let rhsTarget, _)):\n                lhsTarget.name < rhsTarget.name\n            }\n        }\n    }\n}\n\nextension ResolvedPackage {\n    func deploymentTarget(for platform: PackageModel.Platform, usingXCTest: Bool = false) -> String? {\n        self.getSupportedPlatform(for: platform, usingXCTest: usingXCTest).version.versionString\n    }\n}\n\nextension ResolvedModule {\n    func deploymentTarget(for platform: PackageModel.Platform, usingXCTest: Bool = false) -> String? {\n        self.getSupportedPlatform(for: platform, usingXCTest: usingXCTest).version.versionString\n    }\n}\n\nextension Module {\n    var isCxx: Bool {\n        (self as? ClangModule)?.isCXX ?? false\n    }\n}\n\nextension ProductType {\n    var targetType: Module.Kind {\n        switch self {\n        case .executable:\n            .executable\n        case .snippet:\n            .snippet\n        case .test:\n            .test\n        case .library:\n            .library\n        case .plugin:\n            .plugin\n        case .macro:\n            .macro\n        }\n    }\n}\n\nprivate struct PIFBuildSettingAssignment {\n    /// The assignment value.\n    let value: [String]\n\n    /// The configurations this assignment applies to.\n    let configurations: [BuildConfiguration]\n\n    /// The platforms this assignment is restrained to, or nil to apply to all platforms.\n    let platforms: [PIF.BuildSettings.Platform]?\n}\n\nextension BuildSettings.AssignmentTable {\n    fileprivate var pifAssignments: [PIF.BuildSettings.MultipleValueSetting: [PIFBuildSettingAssignment]] {\n        var pifAssignments: [PIF.BuildSettings.MultipleValueSetting: [PIFBuildSettingAssignment]] = [:]\n\n        for (declaration, assignments) in self.assignments {\n            for assignment in assignments {\n                let setting: PIF.BuildSettings.MultipleValueSetting\n                let value: [String]\n\n                switch declaration {\n                case .LINK_LIBRARIES:\n                    setting = .OTHER_LDFLAGS\n                    value = assignment.values.map { \"-l\\($0)\" }\n                case .LINK_FRAMEWORKS:\n                    setting = .OTHER_LDFLAGS\n                    value = assignment.values.flatMap { [\"-framework\", $0] }\n                default:\n                    guard let parsedSetting = PIF.BuildSettings.MultipleValueSetting(rawValue: declaration.name) else {\n                        continue\n                    }\n                    setting = parsedSetting\n                    value = assignment.values\n                }\n\n                let pifAssignment = PIFBuildSettingAssignment(\n                    value: value,\n                    configurations: assignment.configurations,\n                    platforms: assignment.pifPlatforms\n                )\n\n                pifAssignments[setting, default: []].append(pifAssignment)\n            }\n        }\n\n        return pifAssignments\n    }\n}\n\nextension BuildSettings.Assignment {\n    fileprivate var configurations: [BuildConfiguration] {\n        if let configurationCondition = conditions.lazy.compactMap(\\.configurationCondition).first {\n            [configurationCondition.configuration]\n        } else {\n            BuildConfiguration.allCases\n        }\n    }\n\n    fileprivate var pifPlatforms: [PIF.BuildSettings.Platform]? {\n        if let platformsCondition = conditions.lazy.compactMap(\\.platformsCondition).first {\n            platformsCondition.platforms.compactMap { PIF.BuildSettings.Platform(rawValue: $0.name) }\n        } else {\n            nil\n        }\n    }\n}\n\n@propertyWrapper\npublic struct DelayedImmutable<Value> {\n    private var _value: Value? = nil\n\n    public init() {}\n\n    public var wrappedValue: Value {\n        get {\n            guard let value = _value else {\n                fatalError(\"property accessed before being initialized\")\n            }\n            return value\n        }\n        set {\n            if self._value != nil {\n                fatalError(\"property initialized twice\")\n            }\n            self._value = newValue\n        }\n    }\n}\n\nextension [PackageCondition] {\n    func toPlatformFilters() -> [PIF.PlatformFilter] {\n        var result: [PIF.PlatformFilter] = []\n        let platformConditions = self.compactMap(\\.platformsCondition).flatMap(\\.platforms)\n\n        for condition in platformConditions {\n            switch condition {\n            case .macOS:\n                result += PIF.PlatformFilter.macOSFilters\n\n            case .macCatalyst:\n                result += PIF.PlatformFilter.macCatalystFilters\n\n            case .iOS:\n                result += PIF.PlatformFilter.iOSFilters\n\n            case .tvOS:\n                result += PIF.PlatformFilter.tvOSFilters\n\n            case .watchOS:\n                result += PIF.PlatformFilter.watchOSFilters\n\n            case .visionOS:\n                result += PIF.PlatformFilter.visionOSFilters\n\n            case .linux:\n                result += PIF.PlatformFilter.linuxFilters\n\n            case .android:\n                result += PIF.PlatformFilter.androidFilters\n\n            case .windows:\n                result += PIF.PlatformFilter.windowsFilters\n\n            case .driverKit:\n                result += PIF.PlatformFilter.driverKitFilters\n\n            case .wasi:\n                result += PIF.PlatformFilter.webAssemblyFilters\n\n            case .openbsd:\n                result += PIF.PlatformFilter.openBSDFilters\n\n            case .freebsd:\n                result += PIF.PlatformFilter.freeBSDFilters\n\n            default:\n                assertionFailure(\"Unhandled platform condition: \\(condition)\")\n            }\n        }\n        return result\n    }\n}\n\nextension PIF.PlatformFilter {\n    /// macOS platform filters.\n    public static let macOSFilters: [PIF.PlatformFilter] = [.init(platform: \"macos\")]\n\n    /// Mac Catalyst platform filters.\n    public static let macCatalystFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"ios\", environment: \"maccatalyst\"),\n    ]\n\n    /// iOS platform filters.\n    public static let iOSFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"ios\"),\n        .init(platform: \"ios\", environment: \"simulator\"),\n    ]\n\n    /// tvOS platform filters.\n    public static let tvOSFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"tvos\"),\n        .init(platform: \"tvos\", environment: \"simulator\"),\n    ]\n\n    /// watchOS platform filters.\n    public static let watchOSFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"watchos\"),\n        .init(platform: \"watchos\", environment: \"simulator\"),\n    ]\n\n    /// DriverKit platform filters.\n    public static let driverKitFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"driverkit\"),\n    ]\n\n    /// Windows platform filters.\n    public static let windowsFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"windows\", environment: \"msvc\"),\n        .init(platform: \"windows\", environment: \"gnu\"),\n    ]\n\n    /// Android platform filters.\n    public static let androidFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"linux\", environment: \"android\"),\n        .init(platform: \"linux\", environment: \"androideabi\"),\n    ]\n\n    /// Common Linux platform filters.\n    public static let linuxFilters: [PIF.PlatformFilter] = [\"\", \"eabi\", \"gnu\", \"gnueabi\", \"gnueabihf\"].map {\n        .init(platform: \"linux\", environment: $0)\n    }\n\n    /// OpenBSD filters.\n    public static let openBSDFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"openbsd\"),\n    ]\n\n    /// FreeBSD filters.\n    public static let freeBSDFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"freebsd\"),\n    ]\n\n    /// WebAssembly platform filters.\n    public static let webAssemblyFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"wasi\"),\n    ]\n\n    /// VisionOS platform filters.\n    public static let visionOSFilters: [PIF.PlatformFilter] = [\n        .init(platform: \"xros\"),\n        .init(platform: \"xros\", environment: \"simulator\"),\n        .init(platform: \"visionos\"),\n        .init(platform: \"visionos\", environment: \"simulator\"),\n    ]\n}\n\nextension PIF.BuildSettings {\n    fileprivate mutating func addSwiftVersionSettings(\n        target: SwiftModule,\n        parameters: PIFBuilderParameters\n    ) throws {\n        guard let versionAssignments = target.buildSettings.assignments[.SWIFT_VERSION] else {\n            // This should never happens in practice because there is always a default tools version based value.\n            return\n        }\n\n        func isSupportedVersion(_ version: SwiftLanguageVersion) -> Bool {\n            parameters.supportedSwiftVersions.isEmpty || parameters.supportedSwiftVersions.contains(version)\n        }\n\n        func computeEffectiveSwiftVersions(for versions: [SwiftLanguageVersion]) -> [String] {\n            versions\n                .filter { isSupportedVersion($0) }.map(\\.description)\n        }\n\n        func computeEffectiveTargetVersion(for assignment: BuildSettings.Assignment) throws -> String {\n            let versions = assignment.values.compactMap { SwiftLanguageVersion(string: $0) }\n            if let effectiveVersion = computeEffectiveSwiftVersions(for: versions).last {\n                return effectiveVersion\n            }\n\n            throw PIFGenerationError.unsupportedSwiftLanguageVersions(\n                targetName: target.name,\n                versions: versions,\n                supportedVersions: parameters.supportedSwiftVersions\n            )\n        }\n\n        var toolsSwiftVersion: SwiftLanguageVersion? = nil\n        // First, check whether there are any target specific settings.\n        for assignment in versionAssignments {\n            if assignment.default {\n                toolsSwiftVersion = assignment.values.first.flatMap { .init(string: $0) }\n                continue\n            }\n\n            if assignment.conditions.isEmpty {\n                self[.SWIFT_VERSION] = try computeEffectiveTargetVersion(for: assignment)\n                continue\n            }\n\n            for condition in assignment.conditions {\n                if let platforms = condition.platformsCondition {\n                    for platform: Platform in platforms.platforms.compactMap({ .init(rawValue: $0.name) }) {\n                        self[.SWIFT_VERSION, for: platform] = try computeEffectiveTargetVersion(for: assignment)\n                    }\n                }\n            }\n        }\n\n        // If there were no target specific assignments, let's add a fallback tools version based value.\n        if let toolsSwiftVersion, self[.SWIFT_VERSION] == nil {\n            // Use tools based version if it's supported.\n            if isSupportedVersion(toolsSwiftVersion) {\n                self[.SWIFT_VERSION] = toolsSwiftVersion.description\n                return\n            }\n\n            // Otherwise pick the newest supported tools version based value.\n\n            // We have to normalize to two component strings to match the results from XCBuild w.r.t. to hashing of\n            // `SwiftLanguageVersion` instances.\n            let normalizedDeclaredVersions = Set(target.declaredSwiftVersions.compactMap {\n                SwiftLanguageVersion(string: \"\\($0.major).\\($0.minor)\")\n            })\n\n            let declaredSwiftVersions = Array(\n                normalizedDeclaredVersions\n                    .intersection(parameters.supportedSwiftVersions)\n            ).sorted(by: >)\n            if let swiftVersion = declaredSwiftVersions.first {\n                self[.SWIFT_VERSION] = swiftVersion.description\n                return\n            }\n\n            throw PIFGenerationError.unsupportedSwiftLanguageVersions(\n                targetName: target.name,\n                versions: Array(normalizedDeclaredVersions),\n                supportedVersions: parameters.supportedSwiftVersions\n            )\n        }\n    }\n\n    fileprivate mutating func addCommonSwiftSettings(\n        package: ResolvedPackage,\n        target: ResolvedModule,\n        parameters: PIFBuilderParameters\n    ) {\n        let packageOptions = package.packageNameArgument(\n            target: target,\n            isPackageNameSupported: parameters.isPackageAccessModifierSupported\n        )\n        if !packageOptions.isEmpty {\n            self[.OTHER_SWIFT_FLAGS] = packageOptions\n        }\n    }\n}\n\nextension PIF.BuildSettings.Platform {\n    fileprivate static func from(platform: PackageModel.Platform) -> PIF.BuildSettings.Platform? {\n        switch platform {\n        case .iOS: .iOS\n        case .linux: .linux\n        case .macCatalyst: .macCatalyst\n        case .macOS: .macOS\n        case .tvOS: .tvOS\n        case .watchOS: .watchOS\n        case .driverKit: .driverKit\n        default: nil\n        }\n    }\n}\n\npublic enum PIFGenerationError: Error {\n    case unsupportedSwiftLanguageVersions(\n        targetName: String,\n        versions: [SwiftLanguageVersion],\n        supportedVersions: [SwiftLanguageVersion]\n    )\n}\n\nextension PIFGenerationError: CustomStringConvertible {\n    public var description: String {\n        switch self {\n        case .unsupportedSwiftLanguageVersions(\n            targetName: let target,\n            versions: let given,\n            supportedVersions: let supported\n        ):\n            \"Some of the Swift language versions used in target '\\(target)' settings are unsupported. (given: \\(given), supported: \\(supported))\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/XCBuildSupport/XCBuildDelegate.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport SPMBuildCore\n\nimport class TSCBasic.ThreadSafeOutputByteStream\nimport protocol TSCBasic.OutputByteStream\n\nimport enum TSCUtility.Diagnostics\nimport protocol TSCUtility.ProgressAnimationProtocol\n\npublic class XCBuildDelegate {\n    private let buildSystem: SPMBuildCore.BuildSystem\n    private var parser: XCBuildOutputParser!\n    private let observabilityScope: ObservabilityScope\n    private let outputStream: ThreadSafeOutputByteStream\n    private let progressAnimation: ProgressAnimationProtocol\n    private var percentComplete: Int = 0\n    private let queue = DispatchQueue(label: \"org.swift.swiftpm.xcbuild-delegate\")\n\n    /// The verbosity level to print out at\n    private let logLevel: Basics.Diagnostic.Severity\n\n    /// True if any progress output was emitted.\n    fileprivate var didEmitProgressOutput: Bool = false\n\n    /// True if any output was parsed.\n    fileprivate(set) var didParseAnyOutput: Bool = false\n\n    public init(\n        buildSystem: SPMBuildCore.BuildSystem,\n        outputStream: OutputByteStream,\n        progressAnimation: ProgressAnimationProtocol,\n        logLevel: Basics.Diagnostic.Severity,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.buildSystem = buildSystem\n        // FIXME: Implement a class convenience initializer that does this once they are supported\n        // https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924\n        self.outputStream = outputStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(outputStream)\n        self.progressAnimation = progressAnimation\n        self.logLevel = logLevel\n        self.observabilityScope = observabilityScope\n        self.parser = XCBuildOutputParser(delegate: self)\n    }\n\n    public func parse(bytes: [UInt8]) {\n        parser.parse(bytes: bytes)\n    }\n}\n\nextension XCBuildDelegate: XCBuildOutputParserDelegate {\n    public func xcBuildOutputParser(_ parser: XCBuildOutputParser, didParse message: XCBuildMessage) {\n        self.didParseAnyOutput = true\n\n        switch message {\n        case .taskStarted(let info):\n            queue.async {\n                self.didEmitProgressOutput = true\n                let text = self.logLevel.isVerbose ? [info.executionDescription, info.commandLineDisplayString].compactMap { $0 }.joined(separator: \"\\n\") : info.executionDescription\n                if !self.logLevel.isQuiet {\n                    self.progressAnimation.update(step: self.percentComplete, total: 100, text: text)\n                }\n                self.buildSystem.delegate?.buildSystem(self.buildSystem, willStartCommand: BuildSystemCommand(name: \"\\(info.taskID)\", description: info.executionDescription, verboseDescription: info.commandLineDisplayString))\n                self.buildSystem.delegate?.buildSystem(self.buildSystem, didStartCommand: BuildSystemCommand(name: \"\\(info.taskID)\", description: info.executionDescription, verboseDescription: info.commandLineDisplayString))\n            }\n        case .taskOutput(let info):\n            guard !self.logLevel.isQuiet else { return }\n            queue.async {\n                self.progressAnimation.clear()\n                self.outputStream.send(\"\\(info.data)\\n\")\n                self.outputStream.flush()\n            }\n        case .taskComplete(let info):\n            queue.async {\n                self.buildSystem.delegate?.buildSystem(self.buildSystem, didFinishCommand: BuildSystemCommand(name: \"\\(info.taskID)\", description: info.result.rawValue))\n            }\n        case .buildDiagnostic(let info):\n            guard !self.logLevel.isQuiet else { return }\n            queue.async {\n                self.progressAnimation.clear()\n                self.outputStream.send(\"\\(info.message)\\n\")\n                self.outputStream.flush()\n            }\n        case .taskDiagnostic(let info):\n            guard !self.logLevel.isQuiet else { return }\n            queue.async {\n                self.progressAnimation.clear()\n                self.outputStream.send(\"\\(info.message)\\n\")\n                self.outputStream.flush()\n            }\n        case .targetDiagnostic(let info):\n            guard !self.logLevel.isQuiet else { return }\n            queue.async {\n                self.progressAnimation.clear()\n                self.outputStream.send(\"\\(info.message)\\n\")\n                self.outputStream.flush()\n            }\n        case .buildOutput(let info):\n            guard !self.logLevel.isQuiet else { return }\n            queue.async {\n                self.progressAnimation.clear()\n                self.outputStream.send(\"\\(info.data)\\n\")\n                self.outputStream.flush()\n            }\n        case .didUpdateProgress(let info):\n            queue.async {\n                let percent = Int(info.percentComplete)\n                self.percentComplete = percent > 0 ? percent : 0\n                self.buildSystem.delegate?.buildSystem(self.buildSystem, didUpdateTaskProgress: info.message)\n            }\n        case .buildCompleted(let info):\n            queue.async {\n                switch info.result {\n                case .aborted, .cancelled, .failed:\n                    self.outputStream.send(\"Build \\(info.result)\\n\")\n                    self.outputStream.flush()\n                    self.buildSystem.delegate?.buildSystem(self.buildSystem, didFinishWithResult: false)\n                case .ok:\n                    if self.didEmitProgressOutput && !self.logLevel.isQuiet {\n                        self.progressAnimation.update(step: 100, total: 100, text: \"Build succeeded\")\n                    }\n                    self.buildSystem.delegate?.buildSystem(self.buildSystem, didFinishWithResult: true)\n                }\n            }\n        case .buildStarted, .preparationComplete, .targetUpToDate, .targetStarted, .targetComplete, .taskUpToDate, .unknown:\n            break\n        }\n    }\n\n    public func xcBuildOutputParser(_ parser: XCBuildOutputParser, didFailWith error: Error) {\n        self.didParseAnyOutput = true\n        self.observabilityScope.emit(.xcbuildOutputParsingError(error))\n    }\n}\n\nprivate extension Basics.Diagnostic {\n    static func xcbuildOutputParsingError(_ error: Error) -> Self {\n        let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription\n        return .error(\"failed parsing XCBuild output: \\(message)\")\n    }\n}\n\n@available(*, deprecated, message: \"use ProgressAnimation.ninja(stream:) instead\")\npublic final class VerboseProgressAnimation: ProgressAnimationProtocol {\n    private let stream: OutputByteStream\n\n    public init(stream: OutputByteStream) {\n        self.stream = stream\n    }\n\n    public func update(step: Int, total: Int, text: String) {\n        stream.send(\"\\(text)\\n\")\n        stream.flush()\n    }\n\n    public func complete(success: Bool) {\n        stream.send(\"\\n\")\n        stream.flush()\n    }\n\n    public func clear() {\n    }\n}\n"
  },
  {
    "path": "Sources/XCBuildSupport/XCBuildMessage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n/// Represents a message output by xcbuild.\npublic enum XCBuildMessage {\n    public struct BuildDiagnosticInfo {\n        public let message: String\n    }\n\n    public struct BuildCompletedInfo {\n        public enum Result: String {\n            case ok\n            case failed\n            case cancelled\n            case aborted\n        }\n\n        public let result: Result\n    }\n\n    public struct BuildOutputInfo {\n        public let data: String\n    }\n\n    public struct DidUpdateProgressInfo {\n        public let message: String\n        public let percentComplete: Double\n        public let showInLog: Bool\n    }\n\n    public struct TargetUpToDateInfo {\n        public let guid: PIF.GUID\n    }\n\n    public struct TargetStartedInfo {\n        public enum Kind: String {\n            case native = \"Native\"\n            case aggregate = \"Aggregate\"\n            case external = \"External\"\n            case packageProduct = \"Package Product\"\n        }\n\n        public let targetID: Int\n        public let targetGUID: PIF.GUID\n        public let targetName: String\n        public let type: Kind\n    }\n\n    public struct TargetCompleteInfo {\n        public let targetID: Int\n    }\n\n    public struct TaskUpToDateInfo {\n        public let targetID: Int?\n        public let taskSignature: String\n        public let parentTaskID: Int?\n    }\n\n    public struct TaskStartedInfo {\n        public let taskID: Int\n        public let targetID: Int?\n        public let taskSignature: String\n        public let parentTaskID: Int?\n        public let ruleInfo: String\n        public let interestingPath: AbsolutePath?\n        public let commandLineDisplayString: String?\n        public let executionDescription: String\n    }\n\n    public struct TaskDiagnosticInfo {\n        public let taskID: Int\n        public let targetID: Int?\n        public let message: String\n    }\n\n    public struct TaskOutputInfo {\n        public let taskID: Int\n        public let data: String\n    }\n\n    public struct TaskCompleteInfo {\n        public enum Result: String {\n            case success\n            case failed\n            case cancelled\n        }\n\n        public let taskID: Int\n        public let result: Result\n        public let signalled: Bool\n    }\n\n    public struct TargetDiagnosticInfo {\n        public let targetID: Int\n        public let message: String\n    }\n\n    case buildStarted\n    case buildDiagnostic(BuildDiagnosticInfo)\n    case buildCompleted(BuildCompletedInfo)\n    case buildOutput(BuildOutputInfo)\n    case preparationComplete\n    case didUpdateProgress(DidUpdateProgressInfo)\n    case targetUpToDate(TargetUpToDateInfo)\n    case targetStarted(TargetStartedInfo)\n    case targetComplete(TargetCompleteInfo)\n    case taskUpToDate(TaskUpToDateInfo)\n    case taskStarted(TaskStartedInfo)\n    case taskDiagnostic(TaskDiagnosticInfo)\n    case taskOutput(TaskOutputInfo)\n    case taskComplete(TaskCompleteInfo)\n    case targetDiagnostic(TargetDiagnosticInfo)\n    case unknown\n}\n\nextension XCBuildMessage.BuildDiagnosticInfo: Codable, Equatable, Sendable {}\nextension XCBuildMessage.BuildCompletedInfo.Result: Codable, Equatable, Sendable {}\nextension XCBuildMessage.BuildCompletedInfo: Codable, Equatable, Sendable {}\nextension XCBuildMessage.BuildOutputInfo: Codable, Equatable, Sendable {}\nextension XCBuildMessage.TargetUpToDateInfo: Codable, Equatable, Sendable {}\nextension XCBuildMessage.TaskDiagnosticInfo: Codable, Equatable, Sendable {}\nextension XCBuildMessage.TargetDiagnosticInfo: Codable, Equatable, Sendable {}\n\nextension XCBuildMessage.DidUpdateProgressInfo: Codable, Equatable, Sendable {\n    enum CodingKeys: String, CodingKey {\n        case message\n        case percentComplete\n        case showInLog\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        message = try container.decode(String.self, forKey: .message)\n        percentComplete = try container.decodeDoubleOrString(forKey: .percentComplete)\n        showInLog = try container.decodeBoolOrString(forKey: .showInLog)\n    }\n}\n\nextension XCBuildMessage.TargetStartedInfo.Kind: Codable, Equatable, Sendable {}\nextension XCBuildMessage.TargetStartedInfo: Codable, Equatable, Sendable {\n    enum CodingKeys: String, CodingKey {\n        case targetID = \"id\"\n        case targetGUID = \"guid\"\n        case targetName = \"name\"\n        case type\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        targetID = try container.decodeIntOrString(forKey: .targetID)\n        targetGUID = try container.decode(PIF.GUID.self, forKey: .targetGUID)\n        targetName = try container.decode(String.self, forKey: .targetName)\n        type = try container.decode(Kind.self, forKey: .type)\n    }\n}\n\nextension XCBuildMessage.TargetCompleteInfo: Codable, Equatable, Sendable {\n    enum CodingKeys: String, CodingKey {\n        case targetID = \"id\"\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        targetID = try container.decodeIntOrString(forKey: .targetID)\n    }\n}\n\nextension XCBuildMessage.TaskUpToDateInfo: Codable, Equatable, Sendable {\n    enum CodingKeys: String, CodingKey {\n        case targetID\n        case taskSignature = \"signature\"\n        case parentTaskID = \"parentID\"\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        targetID = try container.decodeIntOrStringIfPresent(forKey: .targetID)\n        taskSignature = try container.decode(String.self, forKey: .taskSignature)\n        parentTaskID = try container.decodeIntOrStringIfPresent(forKey: .parentTaskID)\n    }\n}\n\nextension XCBuildMessage.TaskStartedInfo: Codable, Equatable, Sendable {\n    enum CodingKeys: String, CodingKey {\n        case taskID = \"id\"\n        case targetID\n        case taskSignature = \"signature\"\n        case parentTaskID = \"parentID\"\n        case ruleInfo\n        case interestingPath\n        case commandLineDisplayString\n        case executionDescription\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        taskID = try container.decodeIntOrString(forKey: .taskID)\n        targetID = try container.decodeIntOrStringIfPresent(forKey: .targetID)\n        taskSignature = try container.decode(String.self, forKey: .taskSignature)\n        parentTaskID = try container.decodeIntOrStringIfPresent(forKey: .parentTaskID)\n        ruleInfo = try container.decode(String.self, forKey: .ruleInfo)\n        interestingPath = try AbsolutePath(validatingOrNilIfEmpty: container.decodeIfPresent(String.self, forKey: .interestingPath))\n        commandLineDisplayString = try container.decodeIfPresent(String.self, forKey: .commandLineDisplayString)\n        executionDescription = try container.decode(String.self, forKey: .executionDescription)\n    }\n}\n\nextension XCBuildMessage.TaskOutputInfo: Codable, Equatable, Sendable {\n    enum CodingKeys: String, CodingKey {\n        case taskID\n        case data\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        taskID = try container.decodeIntOrString(forKey: .taskID)\n        data = try container.decode(String.self, forKey: .data)\n    }\n}\n\nextension XCBuildMessage.TaskCompleteInfo.Result: Codable, Equatable, Sendable {}\nextension XCBuildMessage.TaskCompleteInfo: Codable, Equatable, Sendable {\n    enum CodingKeys: String, CodingKey {\n        case taskID = \"id\"\n        case result\n        case signalled\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        taskID = try container.decodeIntOrString(forKey: .taskID)\n        result = try container.decode(Result.self, forKey: .result)\n        signalled = try container.decode(Bool.self, forKey: .signalled)\n    }\n}\n\nextension XCBuildMessage: Codable, Equatable, Sendable {\n    enum CodingKeys: CodingKey {\n        case kind\n    }\n\n    public init(from decoder: Decoder) throws {\n        let container = try decoder.container(keyedBy: CodingKeys.self)\n        let kind = try container.decode(String.self, forKey: .kind)\n        switch kind {\n        case \"buildStarted\":\n            self = .buildStarted\n        case \"buildDiagnostic\":\n            self = try .buildDiagnostic(BuildDiagnosticInfo(from: decoder))\n        case \"buildCompleted\":\n            self = try .buildCompleted(BuildCompletedInfo(from: decoder))\n        case \"buildOutput\":\n            self = try .buildOutput(BuildOutputInfo(from: decoder))\n        case \"preparationComplete\":\n            self = .preparationComplete\n        case \"didUpdateProgress\":\n            self = try .didUpdateProgress(DidUpdateProgressInfo(from: decoder))\n        case \"targetUpToDate\":\n            self = try .targetUpToDate(TargetUpToDateInfo(from: decoder))\n        case \"targetStarted\":\n            self = try .targetStarted(TargetStartedInfo(from: decoder))\n        case \"targetComplete\":\n            self = try .targetComplete(TargetCompleteInfo(from: decoder))\n        case \"taskUpToDate\":\n            self = try .taskUpToDate(TaskUpToDateInfo(from: decoder))\n        case \"taskStarted\":\n            self = try .taskStarted(TaskStartedInfo(from: decoder))\n        case \"taskDiagnostic\":\n            self = try .taskDiagnostic(TaskDiagnosticInfo(from: decoder))\n        case \"taskOutput\":\n            self = try .taskOutput(TaskOutputInfo(from: decoder))\n        case \"taskComplete\":\n            self = try .taskComplete(TaskCompleteInfo(from: decoder))\n        case \"targetDiagnostic\":\n            self = try .targetDiagnostic(TargetDiagnosticInfo(from: decoder))\n        default:\n            self = .unknown\n        }\n    }\n\n    public func encode(to encoder: Encoder) throws {\n        var container = encoder.container(keyedBy: CodingKeys.self)\n        switch self {\n        case .buildStarted:\n            try container.encode(\"buildStarted\", forKey: .kind)\n        case let .buildDiagnostic(info):\n            try container.encode(\"buildDiagnostic\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .buildCompleted(info):\n            try container.encode(\"buildCompleted\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .buildOutput(info):\n            try container.encode(\"buildOutput\", forKey: .kind)\n            try info.encode(to: encoder)\n        case .preparationComplete:\n            try container.encode(\"preparationComplete\", forKey: .kind)\n        case let .didUpdateProgress(info):\n            try container.encode(\"didUpdateProgress\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .targetUpToDate(info):\n            try container.encode(\"targetUpToDate\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .targetStarted(info):\n            try container.encode(\"targetStarted\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .targetComplete(info):\n            try container.encode(\"targetComplete\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .taskUpToDate(info):\n            try container.encode(\"taskUpToDate\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .taskStarted(info):\n            try container.encode(\"taskStarted\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .taskDiagnostic(info):\n            try container.encode(\"taskDiagnostic\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .taskOutput(info):\n            try container.encode(\"taskOutput\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .taskComplete(info):\n            try container.encode(\"taskComplete\", forKey: .kind)\n            try info.encode(to: encoder)\n        case let .targetDiagnostic(info):\n            try container.encode(\"targetDiagnostic\", forKey: .kind)\n            try info.encode(to: encoder)\n        case .unknown:\n            assertionFailure()\n            break\n        }\n    }\n}\n\nfileprivate extension KeyedDecodingContainer {\n    func decodeBoolOrString(forKey key: Key) throws -> Bool {\n        do {\n            return try decode(Bool.self, forKey: key)\n        } catch {\n            let string = try decode(String.self, forKey: key)\n            guard let value = Bool(string) else {\n                throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: \"Could not parse '\\(string)' as Bool for key \\(key)\")\n            }\n            return value\n        }\n    }\n\n    func decodeDoubleOrString(forKey key: Key) throws -> Double {\n        do {\n            return try decode(Double.self, forKey: key)\n        } catch {\n            let string = try decode(String.self, forKey: key)\n            guard let value = Double(string) else {\n                throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: \"Could not parse '\\(string)' as Double for key \\(key)\")\n            }\n            return value\n        }\n    }\n\n    func decodeIntOrString(forKey key: Key) throws -> Int {\n        do {\n            return try decode(Int.self, forKey: key)\n        } catch {\n            let string = try decode(String.self, forKey: key)\n            guard let value = Int(string) else {\n                throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: \"Could not parse '\\(string)' as Int for key \\(key)\")\n            }\n            return value\n        }\n    }\n\n    func decodeIntOrStringIfPresent(forKey key: Key) throws -> Int? {\n        do {\n            return try decodeIfPresent(Int.self, forKey: key)\n        } catch {\n            guard let string = try decodeIfPresent(String.self, forKey: key), !string.isEmpty else {\n                return nil\n            }\n            guard let value = Int(string) else {\n                throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: \"Could not parse '\\(string)' as Int for key \\(key)\")\n            }\n            return value\n        }\n    }\n}\n\nfileprivate extension AbsolutePath {\n    init?(validatingOrNilIfEmpty path: String?) throws {\n        guard let path = path, !path.isEmpty else {\n            return nil\n        }\n        try self.init(validating: path)\n    }\n}\n"
  },
  {
    "path": "Sources/XCBuildSupport/XCBuildOutputParser.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport class TSCUtility.JSONMessageStreamingParser\nimport protocol TSCUtility.JSONMessageStreamingParserDelegate\n\n/// Protocol for the parser delegate to get notified of parsing events.\npublic protocol XCBuildOutputParserDelegate: AnyObject {\n\n    /// Called for each message parsed.\n    func xcBuildOutputParser(_ parser: XCBuildOutputParser, didParse message: XCBuildMessage)\n\n    /// Called on an un-expected parsing error. No more events will be received after that.\n    func xcBuildOutputParser(_ parser: XCBuildOutputParser, didFailWith error: Error)\n}\n\n/// Parser for XCBuild output.\npublic final class XCBuildOutputParser {\n\n    /// The underlying JSON message parser.\n    private var jsonParser: JSONMessageStreamingParser<XCBuildOutputParser>!\n\n    /// Whether the parser is in a failing state.\n    private var hasFailed: Bool\n\n    /// Delegate to notify of parsing events.\n    public weak var delegate: XCBuildOutputParserDelegate? = nil\n\n    /// Initializes the parser with a delegate to notify of parsing events.\n    /// - Parameters:\n    ///     - delegate: Delegate to notify of parsing events.\n    public init(delegate: XCBuildOutputParserDelegate) {\n        self.hasFailed = false\n        self.delegate = delegate\n        self.jsonParser = JSONMessageStreamingParser<XCBuildOutputParser>(delegate: self)\n    }\n\n    /// Parse the next bytes of the Swift compiler JSON output.\n    /// - Note: If a parsing error is encountered, the delegate will be notified and the parser won't accept any further\n    ///   input.\n    public func parse<C>(bytes: C) where C: Collection, C.Element == UInt8 {\n        guard !hasFailed else {\n            return\n        }\n\n        jsonParser.parse(bytes: bytes)\n    }\n}\n\nextension XCBuildOutputParser: JSONMessageStreamingParserDelegate {\n    public func jsonMessageStreamingParser(\n        _ parser: JSONMessageStreamingParser<XCBuildOutputParser>,\n        didParse message: XCBuildMessage\n    ) {\n        guard !hasFailed else {\n            return\n        }\n\n        delegate?.xcBuildOutputParser(self, didParse: message)\n    }\n\n    public func jsonMessageStreamingParser(\n        _ parser: JSONMessageStreamingParser<XCBuildOutputParser>,\n        didParseRawText text: String\n    ) {\n        // Don't do anything with raw text.\n    }\n\n    public func jsonMessageStreamingParser(\n        _ parser: JSONMessageStreamingParser<XCBuildOutputParser>,\n        didFailWith error: Error\n    ) {\n        delegate?.xcBuildOutputParser(self, didFailWith: error)\n    }\n}\n"
  },
  {
    "path": "Sources/XCBuildSupport/XcodeBuildSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\nimport Dispatch\nimport class Foundation.JSONEncoder\nimport class Foundation.NSArray\nimport class Foundation.NSDictionary\nimport PackageGraph\nimport PackageModel\n\n@_spi(SwiftPMInternal)\nimport SPMBuildCore\n\nimport class Basics.AsyncProcess\nimport func TSCBasic.memoize\nimport protocol TSCBasic.OutputByteStream\nimport func TSCBasic.withTemporaryFile\n\nimport enum TSCUtility.Diagnostics\n\npublic final class XcodeBuildSystem: SPMBuildCore.BuildSystem {\n    private let buildParameters: BuildParameters\n    private let packageGraphLoader: () async throws -> ModulesGraph\n    private let logLevel: Basics.Diagnostic.Severity\n    private let xcbuildPath: AbsolutePath\n    private var packageGraph: AsyncThrowingValueMemoizer<ModulesGraph> = .init()\n    private var pifBuilder: AsyncThrowingValueMemoizer<PIFBuilder> = .init()\n    private let fileSystem: FileSystem\n    private let observabilityScope: ObservabilityScope\n    private let isColorized: Bool\n    /// The output stream for the build delegate.\n    private let outputStream: OutputByteStream\n\n    /// The delegate used by the build system.\n    public weak var delegate: SPMBuildCore.BuildSystemDelegate?\n\n    public var builtTestProducts: [BuiltTestProduct] {\n        get async {\n            do {\n                let graph = try await getPackageGraph()\n\n                var builtProducts: [BuiltTestProduct] = []\n\n                for package in graph.rootPackages {\n                    for product in package.products where product.type == .test {\n                        let binaryPath = try buildParameters.binaryPath(for: product)\n                        builtProducts.append(\n                            BuiltTestProduct(\n                                productName: product.name,\n                                umbrellaProductName: nil,\n                                binaryPath: binaryPath,\n                                packagePath: package.path,\n                                testEntryPointPath: product.underlying.testEntryPointPath\n                            )\n                        )\n                    }\n                }\n\n                return builtProducts\n            } catch {\n                self.observabilityScope.emit(error)\n                return []\n            }\n        }\n    }\n\n    public var buildPlan: SPMBuildCore.BuildPlan {\n        get throws {\n            throw StringError(\"XCBuild does not provide a build plan\")\n        }\n    }\n\n    public var hasIntegratedAPIDigesterSupport: Bool { false }\n\n    public init(\n        buildParameters: BuildParameters,\n        packageGraphLoader: @escaping () async throws -> ModulesGraph,\n        outputStream: OutputByteStream,\n        logLevel: Basics.Diagnostic.Severity,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        delegate: BuildSystemDelegate?\n    ) throws {\n        self.buildParameters = buildParameters\n        self.packageGraphLoader = packageGraphLoader\n        self.outputStream = outputStream\n        self.logLevel = logLevel\n        self.fileSystem = fileSystem\n        self.observabilityScope = observabilityScope.makeChildScope(description: \"Xcode Build System\")\n        self.delegate = delegate\n        self.isColorized = buildParameters.outputParameters.isColorized\n        if let xcbuildTool = Environment.current[\"XCBUILD_TOOL\"] {\n            xcbuildPath = try AbsolutePath(validating: xcbuildTool)\n        } else {\n            let xcodeSelectOutput = try AsyncProcess.popen(args: \"xcode-select\", \"-p\").utf8Output().spm_chomp()\n            let xcodeDirectory = try AbsolutePath(validating: xcodeSelectOutput)\n            xcbuildPath = try {\n                let newPath = try AbsolutePath(\n                    validating: \"../SharedFrameworks/SwiftBuild.framework/Versions/A/Support/swbuild\",\n                    relativeTo: xcodeDirectory\n                )\n                if fileSystem.exists(newPath) {\n                    return newPath\n                }\n                return try AbsolutePath(\n                    validating: \"../SharedFrameworks/XCBuild.framework/Versions/A/Support/xcbuild\",\n                    relativeTo: xcodeDirectory\n                )\n            }()\n        }\n\n        guard fileSystem.exists(xcbuildPath) else {\n            throw StringError(\"xcbuild executable at '\\(xcbuildPath)' does not exist or is not executable\")\n        }\n    }\n\n    private func supportedSwiftVersions() throws -> [SwiftLanguageVersion] {\n        for path in [\n            \"../../../../../Developer/Library/Xcode/Plug-ins/XCBSpecifications.ideplugin/Contents/Resources/Swift.xcspec\",\n            \"../PlugIns/XCBBuildService.bundle/Contents/PlugIns/XCBSpecifications.ideplugin/Contents/Resources/Swift.xcspec\",\n        ] {\n            let swiftSpecPath = try AbsolutePath(validating: path, relativeTo: xcbuildPath.parentDirectory)\n            if !fileSystem.exists(swiftSpecPath) {\n                continue\n            }\n\n            let swiftSpec = NSArray(contentsOfFile: swiftSpecPath.pathString)\n            let compilerSpec = swiftSpec?.compactMap { $0 as? NSDictionary }.first {\n                if let identifier = $0[\"Identifier\"] as? String {\n                    identifier == \"com.apple.xcode.tools.swift.compiler\"\n                } else {\n                    false\n                }\n            }\n            let supportedSwiftVersions: [SwiftLanguageVersion] = if let versions =\n                compilerSpec?[\"SupportedLanguageVersions\"] as? NSArray\n            {\n                versions.compactMap {\n                    if let stringValue = $0 as? String {\n                        SwiftLanguageVersion(string: stringValue)\n                    } else {\n                        nil\n                    }\n                }\n            } else {\n                []\n            }\n            return supportedSwiftVersions\n        }\n        return []\n    }\n\n    public func build(subset: BuildSubset, buildOutputs: [BuildOutput]) async throws -> BuildResult {\n        let buildResult = BuildResult(\n            serializedDiagnosticPathsByTargetName: .failure(StringError(\"XCBuild does not support reporting serialized diagnostics.\")),\n            replArguments: nil,\n            dependencyGraph: nil\n        )\n\n        guard !buildParameters.shouldSkipBuilding else {\n            return buildResult\n        }\n\n        let pifBuilder = try await getPIFBuilder()\n        let pif = try pifBuilder.generatePIF()\n        try self.fileSystem.writeIfChanged(path: buildParameters.pifManifest, string: pif)\n\n        var arguments = [\n            xcbuildPath.pathString,\n            \"build\",\n            buildParameters.pifManifest.pathString,\n            \"--configuration\",\n            buildParameters.configuration.xcbuildName,\n            \"--derivedDataPath\",\n            buildParameters.dataPath.pathString,\n            \"--target\",\n            subset.pifTargetName,\n        ]\n\n        let buildParamsFile: AbsolutePath?\n        // Do not generate a build parameters file if a custom one has been passed.\n        if let flags = buildParameters.flags.xcbuildFlags, !flags.contains(\"--buildParametersFile\") {\n            buildParamsFile = try createBuildParametersFile()\n            if let buildParamsFile {\n                arguments += [\"--buildParametersFile\", buildParamsFile.pathString]\n            }\n        } else {\n            buildParamsFile = nil\n        }\n\n        if let flags = buildParameters.flags.xcbuildFlags {\n            arguments += flags\n        }\n\n        let delegate = createBuildDelegate()\n        var hasStdout = false\n        var stdoutBuffer: [UInt8] = []\n        var stderrBuffer: [UInt8] = []\n        let redirection: AsyncProcess.OutputRedirection = .stream(stdout: { bytes in\n            hasStdout = hasStdout || !bytes.isEmpty\n            delegate.parse(bytes: bytes)\n\n            if !delegate.didParseAnyOutput {\n                stdoutBuffer.append(contentsOf: bytes)\n            }\n        }, stderr: { bytes in\n            stderrBuffer.append(contentsOf: bytes)\n        })\n\n        // We need to sanitize the environment we are passing to XCBuild because we could otherwise interfere with its\n        // linked dependencies e.g. when we have a custom swift-driver dynamic library in the path.\n        var sanitizedEnvironment = Environment.current\n        sanitizedEnvironment[\"DYLD_LIBRARY_PATH\"] = nil\n\n        let process = AsyncProcess(\n            arguments: arguments,\n            environment: sanitizedEnvironment,\n            outputRedirection: redirection\n        )\n        try process.launch()\n        let result = try await process.waitUntilExit()\n\n        if let buildParamsFile {\n            try? self.fileSystem.removeFileTree(buildParamsFile)\n        }\n\n        guard result.exitStatus == .terminated(code: 0) else {\n            if hasStdout {\n                if !delegate.didParseAnyOutput {\n                    self.observabilityScope.emit(error: String(decoding: stdoutBuffer, as: UTF8.self))\n                }\n            } else {\n                if !stderrBuffer.isEmpty {\n                    self.observabilityScope.emit(error: String(decoding: stderrBuffer, as: UTF8.self))\n                } else {\n                    self.observabilityScope.emit(error: \"Unknown error: stdout and stderr are empty\")\n                }\n            }\n\n            throw Diagnostics.fatalError\n        }\n\n        guard !self.logLevel.isQuiet else { return buildResult }\n        self.outputStream.send(\"Build complete!\\n\")\n        self.outputStream.flush()\n\n        return buildResult\n    }\n\n    func createBuildParametersFile() throws -> AbsolutePath {\n        // Generate the run destination parameters.\n        let runDestination = XCBBuildParameters.RunDestination(\n            platform: self.buildParameters.triple.osNameUnversioned,\n            sdk: self.buildParameters.triple.osNameUnversioned,\n            sdkVariant: nil,\n            targetArchitecture: buildParameters.triple.archName,\n            supportedArchitectures: [],\n            disableOnlyActiveArch: true\n        )\n\n        // Generate a table of any overriding build settings.\n        var settings: [String: String] = [:]\n        // An error with determining the override should not be fatal here.\n        settings[\"CC\"] = try? buildParameters.toolchain.getClangCompiler().pathString\n        // Always specify the path of the effective Swift compiler, which was determined in the same way as for the\n        // native build system.\n        settings[\"SWIFT_EXEC\"] = buildParameters.toolchain.swiftCompilerPath.pathString\n        settings[\"LIBRARY_SEARCH_PATHS\"] = try \"$(inherited) \\(buildParameters.toolchain.toolchainLibDir.pathString)\"\n        settings[\"OTHER_CFLAGS\"] = (\n            [\"$(inherited)\"]\n                + buildParameters.toolchain.extraFlags.cCompilerFlags.rawFlags.map { $0.spm_shellEscaped() }\n                + buildParameters.flags.cCompilerFlags.rawFlags.map { $0.spm_shellEscaped() }\n        ).joined(separator: \" \")\n        settings[\"OTHER_CPLUSPLUSFLAGS\"] = (\n            [\"$(inherited)\"]\n                + buildParameters.toolchain.extraFlags.cxxCompilerFlags.rawFlags.map { $0.spm_shellEscaped() }\n                + buildParameters.flags.cxxCompilerFlags.rawFlags.map { $0.spm_shellEscaped() }\n        ).joined(separator: \" \")\n        settings[\"OTHER_SWIFT_FLAGS\"] = (\n            [\"$(inherited)\"]\n            + buildParameters.toolchain.extraFlags.swiftCompilerFlags.rawFlags.map { $0.spm_shellEscaped() }\n            + buildParameters.flags.swiftCompilerFlags.rawFlags.map { $0.spm_shellEscaped() }\n        ).joined(separator: \" \")\n        settings[\"OTHER_LDFLAGS\"] = (\n            [\"$(inherited)\"]\n                + buildParameters.toolchain.extraFlags.linkerFlags.rawFlags.map { $0.spm_shellEscaped() }\n                + buildParameters.flags.linkerFlags.rawFlags.map { $0.spm_shellEscaped() }\n        ).joined(separator: \" \")\n\n        // Optionally also set the list of architectures to build for.\n        if let architectures = buildParameters.architectures, !architectures.isEmpty {\n            settings[\"ARCHS\"] = architectures.joined(separator: \" \")\n        }\n\n        // Generate the build parameters.\n        let params = XCBBuildParameters(\n            configurationName: buildParameters.configuration.xcbuildName,\n            overrides: .init(synthesized: .init(table: settings)),\n            activeRunDestination: runDestination\n        )\n\n        // Write out the parameters as a JSON file, and return the path.\n        let encoder = JSONEncoder.makeWithDefaults()\n        let data = try encoder.encode(params)\n        let file = try withTemporaryFile(deleteOnClose: false) { AbsolutePath($0.path) }\n        try self.fileSystem.writeFileContents(file, data: data)\n        return file\n    }\n\n    public func cancel(deadline: DispatchTime) throws {}\n\n    /// Returns a new instance of `XCBuildDelegate` for a build operation.\n    private func createBuildDelegate() -> XCBuildDelegate {\n        let progressAnimation = ProgressAnimation.percent(\n            stream: self.outputStream,\n            verbose: self.logLevel.isVerbose,\n            header: \"\",\n            isColorized: buildParameters.outputParameters.isColorized\n        )\n        let delegate = XCBuildDelegate(\n            buildSystem: self,\n            outputStream: self.outputStream,\n            progressAnimation: progressAnimation,\n            logLevel: self.logLevel,\n            observabilityScope: self.observabilityScope\n        )\n        return delegate\n    }\n\n    private func getPIFBuilder() async throws -> PIFBuilder {\n        try await pifBuilder.memoize {\n            let graph = try await getPackageGraph()\n            let pifBuilder = try PIFBuilder(\n                graph: graph,\n                parameters: .init(buildParameters, supportedSwiftVersions: supportedSwiftVersions()),\n                fileSystem: self.fileSystem,\n                observabilityScope: self.observabilityScope\n            )\n            return pifBuilder\n        }\n    }\n\n    /// Returns the package graph using the graph loader closure.\n    ///\n    /// First access will cache the graph.\n    public func getPackageGraph() async throws -> ModulesGraph {\n        try await packageGraph.memoize {\n            try await packageGraphLoader()\n        }\n    }\n\n    public func generatePIF(preserveStructure: Bool) async throws -> String {\n        let graph = try await getPackageGraph()\n        return try PIFBuilder.generatePIF(\n            buildParameters: buildParameters,\n            packageGraph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            preservePIFModelStructure: preserveStructure\n        )\n    }\n}\n\nstruct XCBBuildParameters: Encodable {\n    struct RunDestination: Encodable {\n        var platform: String\n        var sdk: String\n        var sdkVariant: String?\n        var targetArchitecture: String\n        var supportedArchitectures: [String]\n        var disableOnlyActiveArch: Bool\n    }\n\n    struct XCBSettingsTable: Encodable {\n        var table: [String: String]\n    }\n\n    struct SettingsOverride: Encodable {\n        var synthesized: XCBSettingsTable? = nil\n    }\n\n    var configurationName: String\n    var overrides: SettingsOverride\n    var activeRunDestination: RunDestination\n}\n\nextension BuildConfiguration {\n    public var xcbuildName: String {\n        switch self {\n        case .debug: \"Debug\"\n        case .release: \"Release\"\n        }\n    }\n}\n\nextension PIFBuilderParameters {\n    public init(_ buildParameters: BuildParameters, supportedSwiftVersions: [SwiftLanguageVersion]) {\n        self.init(\n            triple: buildParameters.triple,\n            isPackageAccessModifierSupported: buildParameters.driverParameters.isPackageAccessModifierSupported,\n            enableTestability: buildParameters.enableTestability,\n            shouldCreateDylibForDynamicProducts: buildParameters.shouldCreateDylibForDynamicProducts,\n            toolchainLibDir: (try? buildParameters.toolchain.toolchainLibDir) ?? .root,\n            pkgConfigDirectories: buildParameters.pkgConfigDirectories,\n            sdkRootPath: buildParameters.toolchain.sdkRootPath,\n            supportedSwiftVersions: supportedSwiftVersions\n        )\n    }\n}\n\nextension BuildSubset {\n    var pifTargetName: String {\n        switch self {\n        case .product(let name, _):\n            PackagePIFProjectBuilder.targetName(for: name)\n        case .target(let name, _):\n            name\n        case .allExcludingTests:\n            PIFBuilder.allExcludingTestsTargetName\n        case .allIncludingTests:\n            PIFBuilder.allIncludingTestsTargetName\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/AsyncFileSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npackage import _Concurrency\n@preconcurrency package import struct SystemPackage.Errno\n@preconcurrency package import struct SystemPackage.FilePath\n\n/// An abstract file system protocol with first-class support for Swift Concurrency.\npackage protocol AsyncFileSystem: Actor {\n    /// Whether a file exists on the file system.\n    /// - Parameter path: Absolute path to the file to check.\n    /// - Returns: `true` if the file exists, `false` otherwise.\n    func exists(_ path: FilePath) async -> Bool\n\n    /// Temporarily opens a read-only file within a scope defined by a given closure.\n    /// - Parameters:\n    ///   - path: Absolute path to a readable file on this file system.\n    ///   - body: Closure that has temporary read-only access to the open file. The underlying file handle is closed\n    ///   when this closure returns, thus in the current absence of `~Escapable` types in Swift 6.0, users should take\n    ///   care not to allow this handle to escape the closure.\n    /// - Returns: Result of the `body` closure.\n    func withOpenReadableFile<T>(\n        _ path: FilePath,\n        _ body: @Sendable (_ fileHandle: OpenReadableFile) async throws -> T\n    ) async throws -> T\n\n    /// Temporarily opens a write-only file within a scope defined by a given closure.\n    /// - Parameters:\n    ///   - path: Absolute path to a writable file on this file system.\n    ///   - body: Closure that has temporary write-only access to the open file. The underlying file handle is closed\n    ///   when this closure returns, thus in the current absence of `~Escapable` types in Swift 6.0, users should take\n    ///   care not to allow this handle to escape the closure.\n    /// - Returns: Result of the `body` closure.\n    func withOpenWritableFile<T>(\n        _ path: FilePath,\n        _ body: @Sendable (_ fileHandle: OpenWritableFile) async throws -> T\n    ) async throws -> T\n}\n\n/// Errors that can be thrown by the ``AsyncFileSystem`` type.\npackage enum AsyncFileSystemError: Error {\n    /// A file with the associated ``FilePath`` value does not exist.\n    case fileDoesNotExist(FilePath)\n\n    /// A wrapper for the underlying `SystemPackage` error types that attaches a ``FilePath`` value to it.\n    case systemError(FilePath, Errno)\n}\n\nextension Error {\n    /// Makes a system error value more actionable and readable by the end user.\n    /// - Parameter path: absolute path to the file, operations on which caused this error.\n    /// - Returns: An ``AsyncFileSystemError`` value augmented by the given file path.\n    func attach(_ path: FilePath) -> any Error {\n        if let error = self as? Errno {\n            return AsyncFileSystemError.systemError(path, error)\n        } else {\n            return self\n        }\n    }\n}\n\nextension AsyncFileSystem {\n    package func write(_ path: FilePath, bytes: some Collection<UInt8> & Sendable) async throws {\n        try await self.withOpenWritableFile(path) { fileHandle in\n            try await fileHandle.write(bytes)\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(_AsyncFileSystem\n  AsyncFileSystem.swift\n  ConcurrencySupport.swift\n  MockFileSystem.swift\n  OpenReadableFile.swift\n  OpenWritableFile.swift\n  OSFileSystem.swift\n  ReadableFileStream.swift\n  WritableStream.swift\n)\ntarget_link_libraries(_AsyncFileSystem PRIVATE\n  SwiftSystem::SystemPackage)\n\n# NOTE(compnerd) workaround for CMake not setting up include flags yet\nset_target_properties(_AsyncFileSystem PROPERTIES\n  INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})\n\ninstall(TARGETS _AsyncFileSystem\n  ARCHIVE DESTINATION lib\n  LIBRARY DESTINATION lib\n  RUNTIME DESTINATION bin)\n\nset_property(GLOBAL APPEND PROPERTY SwiftPM_EXPORTS _AsyncFileSystem)\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/ConcurrencySupport.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal import _Concurrency\ninternal import class Dispatch.DispatchQueue\n\nextension DispatchQueue {\n    /// Schedules blocking synchronous work item on this ``DispatchQueue`` instance.\n    /// - Parameter work: Blocking synchronous closure that should be scheduled on this queue.\n    /// - Returns: Result of the `work` closure.\n    package func scheduleOnQueue<T>(work: @escaping @Sendable () throws -> T) async throws -> T {\n        try await withCheckedThrowingContinuation { continuation in\n            self.async {\n                do {\n                    continuation.resume(returning: try work())\n                } catch {\n                    continuation.resume(throwing: error)\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/MockFileSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npackage import struct SystemPackage.FilePath\n\n/// In-memory implementation of `AsyncFileSystem` for mocking and testing purposes.\npackage actor MockFileSystem: AsyncFileSystem {\n    /// The default size of chunks in bytes read by this file system.\n    package static let defaultChunkSize = 512 * 1024\n\n    /// Maximum size of chunks in bytes read by this instance of file system.\n    let readChunkSize: Int\n\n    /// Underlying in-memory dictionary-based storage for this mock file system.\n    final class Storage {\n        init(_ content: [FilePath: [UInt8]]) {\n            self.content = content\n        }\n\n        var content: [FilePath: [UInt8]]\n    }\n\n    /// Concrete instance of the underlying storage used by this file system.\n    private let storage: Storage\n\n    /// Creates a new instance of the mock file system.\n    /// - Parameters:\n    ///   - content: Dictionary of paths to their in-memory contents to use for seeding the file system.\n    ///   - readChunkSize: Size of chunks in bytes produced by this file system when reading files.\n    package init(content: [FilePath: [UInt8]] = [:], readChunkSize: Int = defaultChunkSize) {\n        self.storage = .init(content)\n        self.readChunkSize = readChunkSize\n    }\n\n    package func exists(_ path: FilePath) -> Bool {\n        self.storage.content.keys.contains(path)\n    }\n\n    /// Writes a sequence of bytes to a file. Any existing content is replaced with new content.\n    /// - Parameters:\n    ///   - path: absolute path of the file to write bytes to.\n    ///   - bytes: sequence of bytes to write to file's contents replacing old content.\n    func write(path: FilePath, bytes: some Sequence<UInt8>) {\n        storage.content[path] = Array(bytes)\n    }\n\n    /// Appends a sequence of bytes to a file.\n    /// - Parameters:\n    ///   - path: absolute path of the file to append bytes to.\n    ///   - bytes: sequence of bytes to append to file's contents.\n    func append(path: FilePath, bytes: some Sequence<UInt8>) {\n        storage.content[path, default: []].append(contentsOf: bytes)\n    }\n\n    package func withOpenReadableFile<T: Sendable>(\n        _ path: FilePath,\n        _ body: (OpenReadableFile) async throws -> T\n    ) async throws -> T {\n        guard let bytes = storage.content[path] else {\n            throw AsyncFileSystemError.fileDoesNotExist(path)\n        }\n        return try await body(.init(chunkSize: self.readChunkSize, fileHandle: .mock(bytes)))\n    }\n\n    package func withOpenWritableFile<T: Sendable>(\n        _ path: FilePath,\n        _ body: (OpenWritableFile) async throws -> T\n    ) async throws -> T {\n        try await body(.init(storage: .mock(self), path: path))\n    }\n}\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/OSFileSystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@preconcurrency package import SystemPackage\n\npublic actor OSFileSystem: AsyncFileSystem {\n  public static let defaultChunkSize = 512 * 1024\n\n  let readChunkSize: Int\n  private let ioQueue = DispatchQueue(label: \"org.swift.sdk-generator-io\")\n\n  package init(readChunkSize: Int = defaultChunkSize) {\n    self.readChunkSize = readChunkSize\n  }\n\n  package func withOpenReadableFile<T: Sendable>(\n    _ path: FilePath,\n    _ body: (OpenReadableFile) async throws -> T\n  ) async throws -> T {\n    let fd = try FileDescriptor.open(path, .readOnly)\n    // Can't use ``FileDescriptor//closeAfter` here, as that doesn't support async closures.\n    do {\n      let result = try await body(.init(chunkSize: readChunkSize, fileHandle: .real(fd, self.ioQueue)))\n      try fd.close()\n      return result\n    } catch {\n      try fd.close()\n      throw error.attach(path)\n    }\n  }\n\n  package func withOpenWritableFile<T: Sendable>(\n    _ path: FilePath,\n    _ body: (OpenWritableFile) async throws -> T\n  ) async throws -> T {\n      let fd = try FileDescriptor.open(\n        path,\n        .writeOnly,\n        options: [.create, .truncate],\n        permissions: [\n            .groupRead,\n            .otherRead,\n            .ownerReadWrite\n        ]\n      )\n    do {\n      let result = try await body(.init(storage: .real(fd, self.ioQueue), path: path))\n      try fd.close()\n      return result\n    } catch {\n      try fd.close()\n      throw error.attach(path)\n    }\n  }\n\n  package func exists(_ path: SystemPackage.FilePath) async -> Bool {\n    FileManager.default.fileExists(atPath: path.string)\n  }\n}\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/OpenReadableFile.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal import class Dispatch.DispatchQueue\ninternal import struct SystemPackage.FileDescriptor\n\n/// A read-only thread-safe handle to an open file.\npackage struct OpenReadableFile: Sendable {\n    /// Maximum size of chunks in bytes produced when reading this file handle.\n    let chunkSize: Int\n\n    /// Underlying storage for this file handle, dependent on the file system type that produced it.\n    enum Storage {\n        /// Operating system file descriptor and a queue used for reading from that file descriptor without blocking\n        /// the Swift Concurrency thread pool.\n        case real(FileDescriptor, DispatchQueue)\n\n        /// Complete contents of the file represented by this handle stored in memory as an array of bytes.\n        case mock([UInt8])\n    }\n\n    /// Concrete instance of underlying file storage.\n    let fileHandle: Storage\n\n    /// Creates a readable ``AsyncSequence`` that can be iterated on to read from this file handle.\n    /// - Returns: `ReadableFileStream` value conforming to ``AsyncSequence``, ready for asynchronous iteration.\n    package func read() async throws -> ReadableFileStream {\n        switch self.fileHandle {\n        case let .real(fileDescriptor, ioQueue):\n            return ReadableFileStream.real(\n                .init(\n                    fileDescriptor: fileDescriptor,\n                    ioQueue: ioQueue,\n                    readChunkSize: self.chunkSize\n                )\n            )\n\n        case .mock(let array):\n            return ReadableFileStream.mock(.init(bytes: array, chunkSize: self.chunkSize))\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/OpenWritableFile.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal import class Dispatch.DispatchQueue\ninternal import struct SystemPackage.FileDescriptor\ninternal import struct SystemPackage.FilePath\n\n/// A write-only thread-safe handle to an open file.\npackage actor OpenWritableFile: WritableStream {\n    /// Underlying storage for this file handle, dependent on the file system type that produced it.\n    enum Storage {\n        /// Operating system file descriptor and a queue used for reading from that file descriptor without blocking\n        /// the Swift Concurrency thread pool.\n        case real(FileDescriptor, DispatchQueue)\n\n        /// Reference to the ``MockFileSystem`` actor that provides file storage.\n        case mock(MockFileSystem)\n    }\n\n    /// Concrete instance of underlying storage.\n    let storage: Storage\n\n    /// Absolute path to the file represented by this file handle.\n    let path: FilePath\n\n    /// Whether the underlying file descriptor has been closed.\n    private var isClosed = false\n\n    /// Creates a new write-only file handle.\n    /// - Parameters:\n    ///   - storage: Underlying storage for the file.\n    ///   - path: Absolute path to the file on the file system that provides `storage`.\n    init(storage: OpenWritableFile.Storage, path: FilePath) {\n        self.storage = storage\n        self.path = path\n    }\n\n    /// Writes a sequence of bytes to the buffer.\n    package func write(_ bytes: some Collection<UInt8> & Sendable) async throws {\n        assert(!isClosed)\n        switch self.storage {\n        case let .real(fileDescriptor, queue):\n            let path = self.path\n            try await queue.scheduleOnQueue {\n                do {\n                    let writtenBytesCount = try fileDescriptor.writeAll(bytes)\n                    assert(bytes.count == writtenBytesCount)\n                } catch {\n                    throw error.attach(path)\n                }\n            }\n        case let .mock(storage):\n            await storage.write(path: self.path, bytes: bytes)\n        }\n    }\n\n    /// Closes the underlying stream handle. It is a programmer error to write to a stream after it's closed.\n    package func close() async throws {\n        isClosed = true\n\n        guard case let .real(fileDescriptor, queue) = self.storage else {\n            return\n        }\n\n        try await queue.scheduleOnQueue {\n            try fileDescriptor.close()\n        }\n    }\n}\n\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/ReadableFileStream.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\ninternal import SystemPackage\ninternal import class Dispatch.DispatchQueue\n\n/// Type-erasure wrapper over underlying file system readable streams.\npackage enum ReadableFileStream: AsyncSequence {\n    package typealias Element = ArraySlice<UInt8>\n\n    case real(RealReadableFileStream)\n    case mock(MockReadableFileStream)\n\n    package enum Iterator: AsyncIteratorProtocol {\n        case real(RealReadableFileStream.Iterator)\n        case mock(MockReadableFileStream.Iterator)\n\n        package func next() async throws -> ArraySlice<UInt8>? {\n            switch self {\n            case .real(let local):\n                return try await local.next()\n            case .mock(let virtual):\n                return try await virtual.next()\n            }\n        }\n    }\n\n    package func makeAsyncIterator() -> Iterator {\n        switch self {\n        case .real(let real):\n            return .real(real.makeAsyncIterator())\n        case .mock(let mock):\n            return .mock(mock.makeAsyncIterator())\n        }\n    }\n}\n\n/// A stream of file contents from the real file system provided by the OS.\npackage struct RealReadableFileStream: AsyncSequence {\n    package typealias Element = ArraySlice<UInt8>\n\n    let fileDescriptor: FileDescriptor\n    let ioQueue: DispatchQueue\n    let readChunkSize: Int\n\n    package final class Iterator: AsyncIteratorProtocol {\n        init(_ fileDescriptor: FileDescriptor, ioQueue: DispatchQueue, readChunkSize: Int) {\n            self.fileDescriptor = fileDescriptor\n            self.ioQueue = ioQueue\n            self.chunkSize = readChunkSize\n        }\n\n        private let fileDescriptor: FileDescriptor\n        private let ioQueue: DispatchQueue\n        private let chunkSize: Int\n\n        package func next() async throws -> ArraySlice<UInt8>? {\n            let chunkSize = self.chunkSize\n            let fileDescriptor = self.fileDescriptor\n\n            return try await ioQueue.scheduleOnQueue {\n                var buffer = [UInt8](repeating: 0, count: chunkSize)\n\n                let bytesRead = try buffer.withUnsafeMutableBytes {\n                    try fileDescriptor.read(into: $0)\n                }\n\n                guard bytesRead > 0 else {\n                    return nil\n                }\n\n                buffer.removeLast(chunkSize - bytesRead)\n                return buffer[...]\n            }\n        }\n    }\n\n    package func makeAsyncIterator() -> Iterator {\n        Iterator(self.fileDescriptor, ioQueue: ioQueue, readChunkSize: self.readChunkSize)\n    }\n}\n\n\n/// A stream of file contents backed by an in-memory array of bytes.\npackage struct MockReadableFileStream: AsyncSequence {\n    package typealias Element = ArraySlice<UInt8>\n\n    package final class Iterator: AsyncIteratorProtocol {\n        init(bytes: [UInt8], chunkSize: Int) {\n            self.bytes = bytes\n            self.chunkSize = chunkSize\n        }\n\n        private let chunkSize: Int\n        var bytes: [UInt8]\n        private var position = 0\n\n        package func next() async throws -> ArraySlice<UInt8>? {\n            let nextPosition = Swift.min(bytes.count, position + chunkSize)\n\n            guard nextPosition > position else {\n                return nil\n            }\n\n            defer { self.position = nextPosition }\n            return self.bytes[position..<nextPosition]\n        }\n    }\n\n    let bytes: [UInt8]\n    let chunkSize: Int\n\n    package func makeAsyncIterator() -> Iterator {\n        Iterator(bytes: self.bytes, chunkSize: self.chunkSize)\n    }\n}\n"
  },
  {
    "path": "Sources/_AsyncFileSystem/WritableStream.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\npackage import _Concurrency\n\n/// An asynchronous output byte stream.\n///\n/// This protocol is designed to be able to support efficient streaming to\n/// different output destinations, e.g., a file or an in memory buffer.\n///\n/// The stream is generally used in conjunction with the ``WritableStream/write(_:)`` function.\n/// For example:\n/// ```swift\n/// let stream = fileSystem.withOpenWritableFile { stream in\n///     stream.write(\"Hello, world!\".utf8)\n/// }\n/// ```\n/// would write the UTF8 encoding of \"Hello, world!\" to the stream.\npackage protocol WritableStream: Actor {\n    /// Writes a sequence of bytes to the buffer.\n    func write(_ bytes: some Collection<UInt8> & Sendable) async throws\n\n    /// Closes the underlying stream handle. It is a programmer error to write to a stream after it's closed.\n    func close() async throws\n}\n"
  },
  {
    "path": "Sources/_IntegrationTestSupport/Filesystem.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nextension FileSystem {\n    // Returns true if a path does not exist. Makes #expect statements more obvious.\n    public func notExists(_ path: AbsolutePath, followSymlink: Bool = false) -> Bool {\n        !exists(path, followSymlink: followSymlink)\n    }\n}\n"
  },
  {
    "path": "Sources/_IntegrationTestSupport/Helpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Testing\nimport _InternalTestSupport\nimport enum TSCUtility.Git\nimport Basics\n\npackage typealias ShReturnType = (stdout: String, stderr: String, returnCode: AsyncProcessResult.ExitStatus)\n\npublic let sdkRoot: AbsolutePath? = {\n    if let environmentPath = ProcessInfo.processInfo.environment[\"SDK_ROOT\"] {\n        return try! AbsolutePath(validating: environmentPath)\n    }\n\n    #if os(macOS)\n    let result = try! AsyncProcess.popen(arguments: [\"xcrun\", \"--sdk\", \"macosx\", \"--show-sdk-path\"])\n    let sdkRoot = try! AbsolutePath(validating: result.utf8Output().spm_chomp())\n    return sdkRoot\n    #else\n    return nil\n    #endif\n}()\n\npublic let toolchainPath: AbsolutePath = {\n    if let environmentPath = ProcessInfo.processInfo.environment[\"TOOLCHAIN_PATH\"] {\n        return try! AbsolutePath(validating: environmentPath)\n    }\n\n    #if os(macOS)\n    let swiftcPath = try! AbsolutePath(\n        validating: sh(\"xcrun\", \"--find\", \"swift\").stdout.spm_chomp()\n    )\n    #elseif os(Windows)\n    let swiftcPath = try! AbsolutePath(validating: sh(\"where.exe\", \"swift.exe\").stdout.spm_chomp())\n    #else\n    let swiftcPath = try! AbsolutePath(validating: sh(\"which\", \"swift\").stdout.spm_chomp())\n    #endif\n    let toolchainPath = swiftcPath.parentDirectory.parentDirectory.parentDirectory\n    return toolchainPath\n}()\n\npublic let clang: AbsolutePath = {\n    if let environmentPath = ProcessInfo.processInfo.environment[\"CLANG_PATH\"] {\n        return try! AbsolutePath(validating: environmentPath)\n    }\n\n    let clangPath = toolchainPath.appending(components: \"usr\", \"bin\", \"clang\")\n    return clangPath\n}()\n\npublic let xcodebuild: AbsolutePath = {\n    #if os(macOS)\n    let xcodebuildPath = try! AbsolutePath(\n        validating: sh(\"xcrun\", \"--find\", \"xcodebuild\").stdout.spm_chomp()\n    )\n    return xcodebuildPath\n    #else\n    fatalError(\"should not be used on other platforms than macOS\")\n    #endif\n}()\n\n@discardableResult\npackage func sh(\n    _ arguments: CustomStringConvertible...,\n    env: [String: String] = [:],\n    workingDirectory: AbsolutePath? = nil,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) throws -> ShReturnType {\n    let result = try _sh(arguments, env: env, workingDirectory: workingDirectory)\n    let stdout = try result.utf8Output()\n    let stderr = try result.utf8stderrOutput()\n\n    if result.exitStatus != .terminated(code: 0) {\n        Issue\n            .record(\n                Comment(\n                    \"Command failed with exit code: \\(result.exitStatus) - \\(result.integrationTests_debugDescription)\"\n                ),\n                sourceLocation: sourceLocation,\n            )\n    }\n\n    return (stdout, stderr, result.exitStatus)\n}\n\n@discardableResult\npackage func _sh(\n    _ arguments: [CustomStringConvertible],\n    env: [String: String] = [:],\n    workingDirectory: AbsolutePath? = nil\n) throws -> AsyncProcessResult {\n    var environment = Environment()\n\n    if let sdkRoot {\n        environment[\"SDKROOT\"] = sdkRoot.pathString\n    }\n\n    for (varName, value) in env {\n        environment[EnvironmentKey(varName)] = value\n    }\n\n    let result = try AsyncProcess.popen(\n        arguments: arguments.map(\\.description), environment: environment, workingDirectory: workingDirectory\n    )\n    return result\n}\n\npublic func binaryTargetsFixture(_ closure: (AbsolutePath) async throws -> Void) async throws {\n    try await fixture(name: \"BinaryTargets\", removeFixturePathOnDeinit: false) { fixturePath in\n        let inputsPath = fixturePath.appending(component: \"Inputs\")\n        let packagePath = fixturePath.appending(component: \"TestBinary\")\n\n        // Generating StaticLibrary.xcframework.\n        try withTemporaryDirectory { tmpDir in\n            let subpath = inputsPath.appending(component: \"StaticLibrary\")\n            let sourcePath = subpath.appending(component: \"StaticLibrary.m\")\n            let headersPath = subpath.appending(component: \"include\")\n            let libraryPath = tmpDir.appending(component: \"libStaticLibrary.a\")\n            try sh(\n                clang, \"-c\", sourcePath, \"-I\", headersPath, \"-fobjc-arc\", \"-fmodules\", \"-o\",\n                libraryPath\n            )\n            let xcframeworkPath = packagePath.appending(component: \"StaticLibrary.xcframework\")\n            try sh(\n                xcodebuild, \"-create-xcframework\", \"-library\", libraryPath, \"-headers\", headersPath,\n                \"-output\", xcframeworkPath\n            )\n        }\n\n        // Generating DynamicLibrary.xcframework.\n        try withTemporaryDirectory { tmpDir in\n            let subpath = inputsPath.appending(component: \"DynamicLibrary\")\n            let sourcePath = subpath.appending(component: \"DynamicLibrary.m\")\n            let headersPath = subpath.appending(component: \"include\")\n            let libraryPath = tmpDir.appending(component: \"libDynamicLibrary.dylib\")\n            try sh(\n                clang, sourcePath, \"-I\", headersPath, \"-fobjc-arc\", \"-fmodules\", \"-dynamiclib\",\n                \"-o\", libraryPath\n            )\n            let xcframeworkPath = packagePath.appending(component: \"DynamicLibrary.xcframework\")\n            try sh(\n                xcodebuild, \"-create-xcframework\", \"-library\", libraryPath, \"-headers\", headersPath,\n                \"-output\", xcframeworkPath\n            )\n        }\n\n        // Generating SwiftFramework.xcframework.\n        try withTemporaryDirectory { tmpDir in\n            let subpath = inputsPath.appending(component: \"SwiftFramework\")\n            let projectPath = subpath.appending(component: \"SwiftFramework.xcodeproj\")\n            try sh(\n                xcodebuild, \"-project\", projectPath, \"-scheme\", \"SwiftFramework\",\n                \"-derivedDataPath\", tmpDir, \"COMPILER_INDEX_STORE_ENABLE=NO\", \"DEPLOYMENT_LOCATION=NO\"\n            )\n            let frameworkPath = try AbsolutePath(\n                validating: \"Build/Products/Debug/SwiftFramework.framework\",\n                relativeTo: tmpDir\n            )\n            let xcframeworkPath = packagePath.appending(component: \"SwiftFramework.xcframework\")\n            try sh(\n                xcodebuild, \"-create-xcframework\", \"-framework\", frameworkPath, \"-output\",\n                xcframeworkPath\n            )\n        }\n\n        try await closure(packagePath)\n    }\n}\n\nextension AsyncProcessResult {\n    var integrationTests_debugDescription: String {\n        \"\"\"\n        command: \\(arguments.map(\\.description).joined(separator: \" \"))\n\n        stdout:\n        \\((try? utf8Output()) ?? \"\")\n\n        stderr:\n        \\((try? utf8stderrOutput()) ?? \"\")\n        \"\"\"\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalBuildTestSupport/MockBuildTestHelper.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n@_spi(SwiftPMInternal)\nimport Build\n\nimport _InternalTestSupport\nimport struct PackageGraph.ModulesGraph\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedProduct\nimport PackageModel\nimport SPMBuildCore\nimport TSCUtility\nimport XCTest\nimport Testing\n\npublic func mockBuildPlan(\n    buildPath: AbsolutePath? = nil,\n    environment: BuildEnvironment,\n    toolchain: PackageModel.Toolchain = try! MockToolchain(),\n    graph: ModulesGraph,\n    commonFlags: PackageModel.BuildFlags = .init(),\n    indexStoreMode: BuildParameters.IndexStoreMode = .off,\n    omitFramePointers: Bool? = nil,\n    driverParameters: BuildParameters.Driver = .init(),\n    linkingParameters: BuildParameters.Linking = .init(),\n    targetSanitizers: EnabledSanitizers = .init(),\n    fileSystem fs: any FileSystem,\n    observabilityScope: ObservabilityScope\n) async throws -> Build.BuildPlan {\n    try await mockBuildPlan(\n        buildPath: buildPath,\n        config: environment.configuration ?? .debug,\n        platform: environment.platform,\n        toolchain: toolchain,\n        graph: graph,\n        commonFlags: commonFlags,\n        indexStoreMode: indexStoreMode,\n        omitFramePointers: omitFramePointers,\n        driverParameters: driverParameters,\n        linkingParameters: linkingParameters,\n        targetSanitizers: targetSanitizers,\n        fileSystem: fs,\n        observabilityScope: observabilityScope\n    )\n}\n\npublic func mockBuildPlan(\n    buildPath: AbsolutePath? = nil,\n    config: BuildConfiguration = .debug,\n    triple: Basics.Triple? = nil,\n    platform: PackageModel.Platform? = nil,\n    toolchain: PackageModel.Toolchain = try! MockToolchain(),\n    graph: ModulesGraph,\n    pluginConfiguration: PluginConfiguration? = nil,\n    pluginTools: [ResolvedModule.ID: [String: PluginTool]] = [:],\n    commonFlags: PackageModel.BuildFlags = .init(),\n    indexStoreMode: BuildParameters.IndexStoreMode = .off,\n    omitFramePointers: Bool? = nil,\n    enableXCFrameworksOnLinux: Bool = false,\n    driverParameters: BuildParameters.Driver = .init(),\n    linkingParameters: BuildParameters.Linking = .init(),\n    targetSanitizers: EnabledSanitizers = .init(),\n    fileSystem fs: any FileSystem,\n    observabilityScope: ObservabilityScope\n) async throws -> Build.BuildPlan {\n    let inferredTriple: Basics.Triple\n    if let platform {\n        precondition(triple == nil)\n\n        inferredTriple = switch platform {\n        case .macOS:\n            Triple.x86_64MacOS\n        case .linux:\n            Triple.arm64Linux\n        case .android:\n            Triple.arm64Android\n        case .windows:\n            Triple.windows\n        default:\n            fatalError(\"unsupported platform in tests\")\n        }\n    } else {\n        inferredTriple = triple ?? hostTriple\n    }\n\n    let commonDebuggingParameters = BuildParameters.Debugging(\n        triple: inferredTriple,\n        shouldEnableDebuggingEntitlement: config == .debug,\n        omitFramePointers: omitFramePointers\n    )\n\n    var destinationParameters = mockBuildParameters(\n        destination: .target,\n        buildPath: buildPath,\n        config: config,\n        toolchain: toolchain,\n        flags: commonFlags,\n        triple: inferredTriple,\n        indexStoreMode: indexStoreMode,\n        enableXCFrameworksOnLinux: enableXCFrameworksOnLinux\n    )\n    destinationParameters.debuggingParameters = commonDebuggingParameters\n    destinationParameters.driverParameters = driverParameters\n    destinationParameters.linkingParameters = linkingParameters\n    destinationParameters.sanitizers = targetSanitizers\n\n    var hostParameters = mockBuildParameters(\n        destination: .host,\n        buildPath: buildPath,\n        config: config,\n        toolchain: toolchain,\n        flags: commonFlags,\n        triple: inferredTriple,\n        indexStoreMode: indexStoreMode,\n        enableXCFrameworksOnLinux: enableXCFrameworksOnLinux\n    )\n    hostParameters.debuggingParameters = commonDebuggingParameters\n    hostParameters.driverParameters = driverParameters\n    hostParameters.linkingParameters = linkingParameters\n\n    return try await BuildPlan(\n        destinationBuildParameters: destinationParameters,\n        toolsBuildParameters: hostParameters,\n        graph: graph,\n        pluginConfiguration: pluginConfiguration,\n        pluginTools: pluginTools,\n        fileSystem: fs,\n        observabilityScope: observabilityScope\n    )\n}\n\npackage func mockPluginTools(\n    plugins: IdentifiableSet<ResolvedModule>,\n    fileSystem: any FileSystem,\n    buildParameters: BuildParameters,\n    hostTriple: Basics.Triple\n) async throws -> [ResolvedModule.ID: [String: PluginTool]] {\n    var accessibleToolsPerPlugin: [ResolvedModule.ID: [String: PluginTool]] = [:]\n    for plugin in plugins where accessibleToolsPerPlugin[plugin.id] == nil {\n        let accessibleTools = try await plugin.preparePluginTools(\n            fileSystem: fileSystem,\n            environment: buildParameters.buildEnvironment,\n            for: hostTriple\n        ) { name, path in\n            buildParameters.buildPath.appending(path)\n        }\n\n        accessibleToolsPerPlugin[plugin.id] = accessibleTools\n    }\n\n    return accessibleToolsPerPlugin\n}\n\nenum BuildError: Swift.Error {\n    case error(String)\n}\n\npublic struct BuildPlanResult {\n    public let plan: Build.BuildPlan\n\n    public var productMap: IdentifiableSet<Build.ProductBuildDescription> {\n        self.plan.productMap\n    }\n\n    public var targetMap: IdentifiableSet<Build.ModuleBuildDescription> {\n        self.plan.targetMap\n    }\n\n    public init(plan: Build.BuildPlan) throws {\n        self.plan = plan\n    }\n\n    public func checkTargetsCount(\n        _ count: Int,\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) {\n        if Test.current != nil {\n            #expect(self.targetMap.count ==  count, sourceLocation: sourceLocation)\n        } else {\n            XCTAssertEqual(self.targetMap.count, count, file: file, line: line)\n        }\n    }\n\n    public func checkProductsCount(\n        _ count: Int,\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) {\n        if Test.current != nil {\n            #expect(self.productMap.count ==  count, sourceLocation: sourceLocation)\n        } else {\n            XCTAssertEqual(self.productMap.count, count, file: file, line: line)\n        }\n    }\n\n    public func moduleBuildDescription(for name: String) throws -> Build.ModuleBuildDescription {\n        let matches = self.targetMap.filter({ $0.module.name == name })\n        guard matches.count == 1 else {\n            if matches.isEmpty {\n                throw BuildError.error(\"Target \\(name) not found.\")\n            } else {\n                throw BuildError.error(\"More than one target \\(name) found.\")\n            }\n        }\n        return matches.first!\n    }\n\n    public func buildProduct(for name: String) throws -> Build.ProductBuildDescription {\n        let matches = self.productMap.filter({ $0.product.name == name })\n        guard matches.count == 1 else {\n            if matches.isEmpty {\n                // <rdar://problem/30162871> Display the thrown error on macOS\n                throw BuildError.error(\"Product \\(name) not found.\")\n            } else {\n                throw BuildError.error(\"More than one target \\(name) found.\")\n            }\n        }\n        return matches.first!\n    }\n}\n\nextension Build.ModuleBuildDescription {\n    public func swift() throws -> SwiftModuleBuildDescription {\n        switch self {\n        case .swift(let description):\n            return description\n        default:\n            throw BuildError.error(\"Unexpected \\(self) type found\")\n        }\n    }\n\n    public func clang() throws -> ClangModuleBuildDescription {\n        switch self {\n        case .clang(let description):\n            return description\n        default:\n            throw BuildError.error(\"Unexpected \\(self) type\")\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalBuildTestSupport/PIFTester.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport XCBuildSupport\nimport XCTest\nimport Testing\n\npublic func PIFTester(_ pif: PIF.TopLevelObject, _ body: (PIFWorkspaceTester) throws -> Void) throws {\n    try body(PIFWorkspaceTester(workspace: pif.workspace))\n}\n\npublic final class PIFWorkspaceTester {\n    private let workspace: PIF.Workspace\n    private let projectMap: [PIF.GUID: PIF.Project]\n    private let targetMap: [PIF.GUID: PIF.BaseTarget]\n\n    fileprivate init(workspace: PIF.Workspace) {\n        self.workspace = workspace\n\n        let projectsByGUID = workspace.projects.map { ($0.guid, $0) }\n        projectMap = Dictionary(uniqueKeysWithValues: projectsByGUID)\n        let targetsByGUID = workspace.projects.flatMap { $0.targets.map { ($0.guid, $0) } }\n        targetMap = Dictionary(uniqueKeysWithValues: targetsByGUID)\n    }\n\n    public func checkProject(\n        _ guid: PIF.GUID,\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (PIFProjectTester) -> Void\n    ) throws {\n        guard let project = projectMap[guid] else {\n            if Test.current != nil {\n                Issue.record(\"project \\(guid) not found\", sourceLocation: sourceLocation)\n                return\n            } else {\n                return XCTFail(\"project \\(guid) not found\", file: file, line: line)\n            }\n        }\n\n        body(try PIFProjectTester(project: project, targetMap: targetMap))\n    }\n}\n\npublic final class PIFProjectTester {\n    private let project: PIF.Project\n    private let targetMap: [PIF.GUID: PIF.BaseTarget]\n    private let fileMap: [PIF.GUID: String]\n\n    public var guid: PIF.GUID { project.guid }\n    public var path: AbsolutePath { project.path }\n    public var projectDirectory: AbsolutePath { project.projectDirectory }\n    public var name: String { project.name }\n    public var developmentRegion: String { project.developmentRegion }\n\n    fileprivate init(project: PIF.Project, targetMap: [PIF.GUID: PIF.BaseTarget]) throws {\n        self.project = project\n        self.targetMap = targetMap\n        self.fileMap = try collectFiles(\n            from: project.groupTree,\n            parentPath: project.path,\n            projectPath: project.path,\n            builtProductsPath: project.path\n        )\n    }\n\n    public func checkTarget(\n        _ guid: PIF.GUID,\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: ((PIFTargetTester) -> Void)? = nil\n    ) {\n        guard let baseTarget = baseTarget(withGUID: guid) else {\n            let guids = project.targets.map { $0.guid }.joined(separator: \", \")\n            if Test.current != nil {\n                Issue.record(\"target \\(guid) not found among \\(guids)\", sourceLocation: sourceLocation)\n                return\n            } else {\n                return XCTFail(\"target \\(guid) not found among \\(guids)\", file: file, line: line)\n            }\n        }\n\n        guard let target = baseTarget as? PIF.Target else {\n            if Test.current != nil {\n                Issue.record(\"target \\(guid) is not a standard target\", sourceLocation: sourceLocation)\n                return\n            } else {\n                return XCTFail(\"target \\(guid) is not a standard target\", file: file, line: line)\n            }\n        }\n\n        body?(PIFTargetTester(target: target, targetMap: targetMap, fileMap: fileMap))\n    }\n\n    public func checkNoTarget(\n        _ guid: PIF.GUID,\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: ((PIFTargetTester) -> Void)? = nil\n    ) {\n        if baseTarget(withGUID: guid) != nil {\n            if Test.current != nil {\n                Issue.record(\"target \\(guid) found\", sourceLocation: sourceLocation)\n            } else {\n                XCTFail(\"target \\(guid) found\", file: file, line: line)\n            }\n        }\n    }\n\n    public func checkAggregateTarget(\n        _ guid: PIF.GUID,\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: ((PIFAggregateTargetTester) -> Void)? = nil\n    ) {\n        guard let baseTarget = baseTarget(withGUID: guid) else {\n            let guids = project.targets.map { $0.guid }.joined(separator: \", \")\n            if Test.current != nil {\n                Issue.record(\"target \\(guid) not found among \\(guids)\", sourceLocation: sourceLocation)\n                return\n            } else {\n                return XCTFail(\"target \\(guid) not found among \\(guids)\", file: file, line: line)\n            }\n        }\n\n        guard let target = baseTarget as? PIF.AggregateTarget else {\n            if Test.current != nil {\n                Issue.record(\"target \\(guid) is not an aggregate target\", sourceLocation: sourceLocation)\n                return\n            } else {\n                return XCTFail(\"target \\(guid) is not an aggregate target\", file: file, line: line)\n            }\n        }\n\n        body?(PIFAggregateTargetTester(target: target, targetMap: targetMap, fileMap: fileMap))\n    }\n\n    public func checkBuildConfiguration(\n        _ name: String,\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (PIFBuildConfigurationTester) -> Void\n    ) {\n        guard let configuration = buildConfiguration(withName: name) else {\n            let names = project.buildConfigurations.map { $0.name }.joined(separator: \", \")\n            if Test.current != nil {\n                Issue.record(\"build configuration \\(name) not found among \\(names)\", sourceLocation: sourceLocation)\n                return\n            } else {\n                return XCTFail(\"build configuration \\(name) not found among \\(names)\", file: file, line: line)\n            }\n        }\n\n        body(PIFBuildConfigurationTester(buildConfiguration: configuration))\n    }\n\n    public func buildConfiguration(withName name: String) -> PIF.BuildConfiguration? {\n        return project.buildConfigurations.first { $0.name == name }\n    }\n\n    public func baseTarget(withGUID guid: PIF.GUID) -> PIF.BaseTarget? {\n        return project.targets.first { $0.guid == guid }\n    }\n}\n\npublic class PIFBaseTargetTester {\n    public let baseTarget: PIF.BaseTarget\n\n    public var guid: PIF.GUID { baseTarget.guid }\n    public var name: String { baseTarget.name }\n    public let dependencies: Set<PIF.GUID>\n    public let sources: Set<String>\n    public let frameworks: Set<String>\n    public let resources: Set<String>\n\n    fileprivate init(baseTarget: PIF.BaseTarget, targetMap: [PIF.GUID: PIF.BaseTarget], fileMap: [PIF.GUID: String]) {\n        self.baseTarget = baseTarget\n        dependencies = Set(baseTarget.dependencies.map { targetMap[$0.targetGUID]!.guid })\n\n        let sourcesBuildFiles = baseTarget.buildPhases.first { $0 is PIF.SourcesBuildPhase }?.buildFiles ?? []\n        sources = Set(sourcesBuildFiles.map { buildFile -> String in\n            if case .file(let guid) = buildFile.reference {\n                return fileMap[guid]!\n            } else {\n                fatalError(\"unexpected build file reference: \\(buildFile)\")\n            }\n        })\n\n        let frameworksBuildFiles = baseTarget.buildPhases.first { $0 is PIF.FrameworksBuildPhase }?.buildFiles ?? []\n        frameworks = Set(frameworksBuildFiles.map { buildFile -> String in\n            switch buildFile.reference {\n            case .target(let guid):\n                return targetMap[guid]!.guid\n            case .file(let guid):\n                return fileMap[guid]!\n            }\n        })\n\n        let resourcesBuildFiles = baseTarget.buildPhases.first { $0 is PIF.ResourcesBuildPhase }?.buildFiles ?? []\n        resources = Set(resourcesBuildFiles.map { buildFile -> String in\n            if case .file(let guid) = buildFile.reference {\n                return fileMap[guid]!\n            } else {\n                fatalError(\"unexpected build file reference: \\(buildFile)\")\n            }\n        })\n    }\n\n    public func checkBuildConfiguration(\n        _ name: String,\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (PIFBuildConfigurationTester) -> Void\n    ) {\n        guard let configuration = buildConfiguration(withName: name) else {\n            if Test.current != nil {\n                Issue.record(\"build configuration \\(name) not found\", sourceLocation: #_sourceLocation)\n                return\n            } else {\n                return XCTFail(\"build configuration \\(name) not found\", file: file, line: line)\n            }\n        }\n\n        body(PIFBuildConfigurationTester(buildConfiguration: configuration))\n    }\n\n    public func buildConfiguration(withName name: String) -> PIF.BuildConfiguration? {\n        return baseTarget.buildConfigurations.first { $0.name == name }\n    }\n\n    public func checkImpartedBuildSettings(\n        file: StaticString = #file,\n        line: UInt = #line,\n        _ body: (PIFBuildSettingsTester) -> Void\n    ) {\n        let buildSettingsTester = PIFBuildSettingsTester(\n            buildSettings: baseTarget.buildConfigurations.first!.impartedBuildProperties.buildSettings\n        )\n        body(buildSettingsTester)\n    }\n\n    public func checkAllImpartedBuildSettings(\n        file: StaticString = #file,\n        line: UInt = #line,\n        _ body: (PIFBuildSettingsTester) -> Void\n    ) {\n        let buildSettingsTester = PIFBuildSettingsTester(\n            buildSettings: baseTarget.buildConfigurations.first!.impartedBuildProperties.buildSettings\n        )\n        body(buildSettingsTester)\n        buildSettingsTester.checkUncheckedSettings(file: file, line: line)\n    }\n\n    public func checkNoImpartedBuildSettings(file: StaticString = #file, line: UInt = #line) {\n        let buildSettingsTester = PIFBuildSettingsTester(\n            buildSettings: baseTarget.buildConfigurations.first!.impartedBuildProperties.buildSettings\n        )\n        buildSettingsTester.checkUncheckedSettings(file: file, line: line)\n    }\n}\n\npublic final class PIFTargetTester: PIFBaseTargetTester {\n    private let target: PIF.Target\n    public var productType: PIF.Target.ProductType { target.productType }\n    public var productName: String { target.productName }\n\n    fileprivate init(target: PIF.Target, targetMap: [PIF.GUID: PIF.BaseTarget], fileMap: [PIF.GUID: String]) {\n        self.target = target\n        super.init(baseTarget: target, targetMap: targetMap, fileMap: fileMap)\n    }\n}\n\npublic final class PIFAggregateTargetTester: PIFBaseTargetTester {\n    private let target: PIF.AggregateTarget\n\n    fileprivate init(target: PIF.AggregateTarget, targetMap: [PIF.GUID: PIF.BaseTarget], fileMap: [PIF.GUID: String]) {\n        self.target = target\n        super.init(baseTarget: target, targetMap: targetMap, fileMap: fileMap)\n    }\n}\n\npublic final class PIFBuildConfigurationTester {\n    private let buildConfiguration: PIF.BuildConfiguration\n\n    public var guid: PIF.GUID { buildConfiguration.guid }\n    public var name: String { buildConfiguration.name }\n\n    fileprivate init(buildConfiguration: PIF.BuildConfiguration) {\n        self.buildConfiguration = buildConfiguration\n    }\n\n    public func checkBuildSettings(file: StaticString = #file, line: UInt = #line, _ body: (PIFBuildSettingsTester) -> Void) {\n        let buildSettingsTester = PIFBuildSettingsTester(buildSettings: buildConfiguration.buildSettings)\n        body(buildSettingsTester)\n    }\n\n    public func checkAllBuildSettings(file: StaticString = #file, line: UInt = #line, _ body: (PIFBuildSettingsTester) -> Void) {\n        let buildSettingsTester = PIFBuildSettingsTester(buildSettings: buildConfiguration.buildSettings)\n        body(buildSettingsTester)\n        buildSettingsTester.checkUncheckedSettings(file: file, line: line)\n    }\n\n    public func checkNoBuildSettings(file: StaticString = #file, line: UInt = #line) {\n        let buildSettingsTester = PIFBuildSettingsTester(buildSettings: buildConfiguration.buildSettings)\n        buildSettingsTester.checkUncheckedSettings(file: file, line: line)\n    }\n}\n\npublic final class PIFBuildSettingsTester {\n    private var buildSettings: PIF.BuildSettings\n\n    fileprivate init(buildSettings: PIF.BuildSettings) {\n        self.buildSettings = buildSettings\n    }\n\n    public subscript(_ key: PIF.BuildSettings.SingleValueSetting) -> String? {\n        if let value = buildSettings[key] {\n            buildSettings[key] = nil\n            return value\n        } else {\n            return nil\n        }\n    }\n\n    public subscript(_ key: PIF.BuildSettings.SingleValueSetting, for platform: PIF.BuildSettings.Platform) -> String? {\n        if let value = buildSettings[key, for: platform] {\n            buildSettings[key, for: platform] = nil\n            return value\n        } else {\n            return nil\n        }\n    }\n\n    public subscript(_ key: PIF.BuildSettings.MultipleValueSetting) -> [String]? {\n        if let value = buildSettings[key] {\n            buildSettings[key] = nil\n            return value\n        } else {\n            return nil\n        }\n    }\n\n    public subscript(_ key: PIF.BuildSettings.MultipleValueSetting, for platform: PIF.BuildSettings.Platform) -> [String]? {\n        if let value = buildSettings[key, for: platform] {\n            buildSettings[key, for: platform] = nil\n            return value\n        } else {\n            return nil\n        }\n    }\n\n    public func checkUncheckedSettings(file: StaticString = #file, line: UInt = #line, sourceLocation: SourceLocation = #_sourceLocation) {\n        let uncheckedKeys =\n            Array(buildSettings.singleValueSettings.keys.map { $0.rawValue }) +\n            Array(buildSettings.multipleValueSettings.keys.map { $0.rawValue })\n        if Test.current != nil {\n            #expect(\n                uncheckedKeys.isEmpty,\n                \"settings are left unchecked: \\(uncheckedKeys)\",\n                sourceLocation: sourceLocation,\n            )\n        } else {\n            XCTAssert(uncheckedKeys.isEmpty, \"settings are left unchecked: \\(uncheckedKeys)\", file: file, line: line)\n        }\n\n        for (platform, settings) in buildSettings.platformSpecificSingleValueSettings {\n            let uncheckedKeys = Array(settings.keys.map { $0.rawValue })\n            if Test.current != nil {\n                #expect(\n                    uncheckedKeys.isEmpty, \"\\(platform) settings are left unchecked: \\(uncheckedKeys)\",\n                    sourceLocation: sourceLocation,\n                )\n            } else {\n                XCTAssert(uncheckedKeys.isEmpty, \"\\(platform) settings are left unchecked: \\(uncheckedKeys)\", file: file, line: line)\n            }\n        }\n\n        for (platform, settings) in buildSettings.platformSpecificMultipleValueSettings {\n            let uncheckedKeys = Array(settings.keys.map { $0.rawValue })\n            if Test.current != nil {\n                #expect(\n                    uncheckedKeys.isEmpty, \"\\(platform) settings are left unchecked: \\(uncheckedKeys)\",\n                    sourceLocation: sourceLocation,\n                )\n            } else {\n                XCTAssert(uncheckedKeys.isEmpty, \"\\(platform) settings are left unchecked: \\(uncheckedKeys)\", file: file, line: line)\n            }\n        }\n    }\n}\n\nprivate func collectFiles(\n    from reference: PIF.Reference,\n    parentPath: AbsolutePath,\n    projectPath: AbsolutePath,\n    builtProductsPath: AbsolutePath\n) throws -> [PIF.GUID: String] {\n    let referencePath: AbsolutePath\n    switch reference.sourceTree {\n    case .absolute:\n        referencePath = try AbsolutePath(validating: reference.path)\n    case .group:\n        referencePath = try AbsolutePath(validating: reference.path, relativeTo: parentPath)\n    case .sourceRoot:\n        referencePath = try AbsolutePath(validating: reference.path, relativeTo: projectPath)\n    case .builtProductsDir:\n        referencePath = try AbsolutePath(validating: reference.path, relativeTo: builtProductsPath)\n    }\n\n    var files: [PIF.GUID: String] = [:]\n\n    if reference is PIF.FileReference {\n        assert(files[reference.guid] == nil, \"non-unique GUID\")\n        files[reference.guid] = referencePath.pathString\n    } else if let group = reference as? PIF.Group {\n        for child in group.children {\n            let childFiles = try collectFiles(\n                from: child,\n                parentPath: referencePath,\n                projectPath: projectPath,\n                builtProductsPath: builtProductsPath\n            )\n            files.merge(childFiles, uniquingKeysWith: { _, _ in fatalError(\"non-unique GUID\") })\n        }\n    }\n\n    return files\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/BuildConfiguration+Helpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport enum PackageModel.BuildConfiguration\n\nextension BuildConfiguration {\n\n    public var buildFor: String {\n        switch self {\n        case .debug:\n            return \"debugging\"\n        case .release:\n            return \"production\"\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/BuildSystemProvider+Configuration.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.Triple\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum PackageModel.BuildConfiguration\nimport class PackageModel.UserToolchain\n\nextension BuildSystemProvider.Kind {\n\n    @available(*, deprecated, message: \"use binPath(for:scrathPath:triple) instead\")\n    public func binPathSuffixes(for config: BuildConfiguration) -> [String] {\n        let suffix: String\n\n        #if os(Linux)\n        suffix = \"-linux\"\n        #elseif os(Windows)\n        suffix = \"-windows\"\n        #else\n        suffix = \"\"\n        #endif\n        switch self {\n            case .native:\n                return [\"\\(config)\".lowercased()]\n            case .swiftbuild:\n                return [\"Products\" , \"\\(config)\".capitalized + suffix]\n            case .xcode:\n                return [\"apple\", \"Products\" , \"\\(config)\".capitalized + suffix]\n        }\n    }\n\n    public func binPath(\n        for config: BuildConfiguration,\n        scratchPath: [String] = [\".build\"],\n        triple: String? = nil,\n    ) throws -> [String] {\n        let suffix: String\n        let tripleString: String\n        let targetTriple: Triple\n        if let triple {\n            targetTriple = try Triple(triple)\n            tripleString = triple\n        } else {\n            targetTriple = try UserToolchain.default.targetTriple\n            tripleString = targetTriple.platformBuildPathComponent\n        }\n\n        if targetTriple.isLinux() {\n            suffix = \"-linux\"\n        } else if targetTriple.isWindows() {\n            suffix = \"-windows\"\n        } else {\n            suffix = \"\"\n        }\n\n        switch self {\n        case .native:\n            return scratchPath + [tripleString, \"\\(config)\".lowercased()]\n        case .swiftbuild:\n            return scratchPath + [\"out\", \"Products\", \"\\(config)\".capitalized + suffix]\n        case .xcode:\n            return scratchPath + [\"apple\", \"Products\", \"\\(config)\".capitalized + suffix]\n        }\n    }\n\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/BuildSystemProvider+Supported.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum PackageModel.BuildConfiguration\n\npublic var SupportedBuildSystemOnAllPlatforms: [BuildSystemProvider.Kind] = BuildSystemProvider.Kind.allCases.filter { $0 != .xcode }\n\npublic var SupportedBuildSystemOnPlatform: [BuildSystemProvider.Kind] {\n    #if os(macOS)\n        BuildSystemProvider.Kind.allCases\n    #else\n        SupportedBuildSystemOnAllPlatforms\n    #endif\n}\n\npublic struct BuildData {\n    public let buildSystem: BuildSystemProvider.Kind\n    public let config: BuildConfiguration\n\n    public init(\n        buildSystem: BuildSystemProvider.Kind,\n        config: BuildConfiguration,\n    ) {\n        self.buildSystem = buildSystem\n        self.config = config\n    }\n}\n\npublic func getBuildData(for buildSystems: [BuildSystemProvider.Kind]) -> [BuildData] {\n    buildSystems.flatMap { buildSystem in\n        BuildConfiguration.allCases.compactMap { config in\n            return BuildData(\n                buildSystem: buildSystem,\n                config: config,\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/CombinationsWithRepetition.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\npackage  struct CombinationsWithRepetition<C: Collection> : Sequence {\n\n    let base: C\n    let length: Int\n\n    init(of base: C, length: Int) {\n        self.base = base\n        self.length = length\n    }\n\n    package struct Iterator : IteratorProtocol {\n        let base: C\n\n        var firstIteration = true\n        var finished: Bool\n        var positions: [C.Index]\n\n        package init(of base: C, length: Int) {\n            self.base = base\n            finished = base.isEmpty\n            positions = Array(repeating: base.startIndex, count: length)\n        }\n\n        package mutating func next() -> [C.Element]? {\n            if firstIteration {\n                firstIteration = false\n            } else {\n                // Update indices for next combination.\n                finished = true\n                for i in positions.indices.reversed() {\n                    base.formIndex(after: &positions[i])\n                    if positions[i] != base.endIndex {\n                        finished = false\n                        break\n                    } else {\n                        positions[i] = base.startIndex\n                    }\n                }\n\n            }\n            return finished ? nil : positions.map { base[$0] }\n        }\n    }\n\n    package func makeIterator() -> Iterator {\n        return Iterator(of: base, length: length)\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/Commands.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport SPMBuildCore\nimport XCTest\n\nopen class BuildSystemProviderTestCase: XCTestCase {\n    open var buildSystemProvider: BuildSystemProvider.Kind {\n        fatalError(\"\\(self) does not implement \\(#function)\")\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/FileSystemHelpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\nimport Basics\n\nfunc getFiles(atPath path: String, matchingExtension fileExtension: String) -> [URL] {\n    let fileManager = FileManager.default\n    var matchingFiles: [URL] = []\n\n    guard\n        let enumerator = fileManager.enumerator(\n            at: URL(fileURLWithPath: path),\n            includingPropertiesForKeys: [.isRegularFileKey],\n            options: [.skipsHiddenFiles, .skipsPackageDescendants]\n        )\n    else {\n        print(\"Error: Could not create enumerator for path: \\(path)\")\n        return []\n    }\n\n    for case let fileURL as URL in enumerator {\n        do {\n            let resourceValues = try fileURL.resourceValues(forKeys: [.isRegularFileKey])\n            if let isRegularFile = resourceValues.isRegularFile, isRegularFile {\n                if fileURL.pathExtension.lowercased() == fileExtension.lowercased() {\n                    matchingFiles.append(fileURL)\n                }\n            }\n        } catch {\n            print(\"Error retrieving resource values for \\(fileURL.lastPathComponent): \\(error.localizedDescription)\")\n        }\n    }\n    return matchingFiles\n}\n\n/// Returns all files that match the given extension in the specified directory.\n///\n/// - Parameters:\n///   - directory: The directory to search in (AbsolutePath)\n///   - extension: The file extension to match (without the leading dot)\n///   - recursive: Whether to search subdirectories recursively (default: true)\n///   - fileSystem: The file system to use for operations (defaults to localFileSystem)\n/// - Returns: An array of AbsolutePath objects\n/// - Throws: FileSystemError if the directory cannot be accessed or enumerated\npublic func getFiles(\n    in directory: AbsolutePath,\n    matchingExtension extension: String,\n    recursive: Bool = true,\n    fileSystem: FileSystem = localFileSystem\n) throws -> [AbsolutePath] {\n    var matchingFiles: [AbsolutePath] = []\n    let normalizedExtension = `extension`.lowercased()\n\n    guard fileSystem.exists(directory) else {\n        throw StringError(\"Directory does not exist: \\(directory)\")\n    }\n\n    guard fileSystem.isDirectory(directory) else {\n        throw StringError(\"Path is not a directory: \\(directory)\")\n    }\n\n    if recursive {\n        try fileSystem.enumerate(directory: directory) { filePath in\n            if fileSystem.isFile(filePath) {\n                if let fileExtension = filePath.extension?.lowercased(),\n                   fileExtension == normalizedExtension {\n                    matchingFiles.append(filePath)\n                }\n            }\n        }\n    } else {\n        // Non-recursive: only check direct children\n        let contents = try fileSystem.getDirectoryContents(directory)\n        for item in contents {\n            let itemPath = directory.appending(component: item)\n            if fileSystem.isFile(itemPath) {\n                if let fileExtension = itemPath.extension?.lowercased(),\n                   fileExtension == normalizedExtension {\n                    matchingFiles.append(itemPath)\n                }\n            }\n        }\n    }\n\n    return matchingFiles\n}\n\n/// Returns all files that match the given extension in the specified directory.\n///\n/// - Parameters:\n///   - directory: The directory to search in (RelativePath)\n///   - extension: The file extension to match (without the leading dot)\n///   - recursive: Whether to search subdirectories recursively (default: true)\n///   - fileSystem: The file system to use for operations (defaults to localFileSystem)\n/// - Returns: An array of RelativePath objects\n/// - Throws: FileSystemError if the directory cannot be accessed or enumerated\npublic func getFiles(\n    in directory: RelativePath,\n    matchingExtension extension: String,\n    recursive: Bool = true,\n    fileSystem: FileSystem = localFileSystem\n) throws -> [RelativePath] {\n    // Convert RelativePath to AbsolutePath for enumeration\n    guard let currentWorkingDirectory = fileSystem.currentWorkingDirectory else {\n        throw StringError(\"Cannot determine current working directory\")\n    }\n\n    let absoluteDirectory = currentWorkingDirectory.appending(directory)\n    let absoluteResults = try getFiles(\n        in: absoluteDirectory,\n        matchingExtension: `extension`,\n        recursive: recursive,\n        fileSystem: fileSystem\n    )\n\n    // Convert results back to RelativePath\n    return absoluteResults.map { absolutePath in\n        absolutePath.relative(to: currentWorkingDirectory)\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/GitRepositoryExtensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SourceControl\n\nimport class Basics.AsyncProcess\nimport class TSCBasic.Process\n\nimport enum TSCUtility.Git\n\n/// Extensions useful for unit testing purposes.\n/// Note: These are not thread safe.\npackage extension GitRepository {\n    /// Create the repository using git init.\n    func create() throws {\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"init\")\n    }\n\n    /// Returns current branch name. If HEAD is on a detached state, this returns HEAD.\n    func currentBranch() throws -> String {\n        return try AsyncProcess.checkNonZeroExit(\n            args: Git.tool, \"-C\", path.pathString, \"rev-parse\", \"--abbrev-ref\", \"HEAD\").spm_chomp()\n    }\n\n    /// Returns the revision for a given tag.\n    func revision(forTag tag: String) throws -> String {\n        return try AsyncProcess.checkNonZeroExit(\n            args: Git.tool, \"-C\", path.pathString, \"rev-parse\", tag).spm_chomp()\n    }\n\n    /// Stage a file.\n    func stage(file: String) throws {\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"add\", file)\n    }\n\n    /// Stage multiple files.\n    func stage(files: String...) throws {\n        try Process.checkNonZeroExit(arguments: [Git.tool, \"-C\", self.path.pathString, \"add\"] + files)\n    }\n\n    /// Stage entire unstaged changes.\n    func stageEverything() throws {\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"add\", \".\")\n    }\n\n    /// Commit the staged changes. If the message is not provided a dummy message will be used for the commit.\n    func commit(message: String? = nil) throws {\n        // FIXME: We don't need to set these every time but we usually only commit once or twice for a test repo.\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"config\", \"user.email\", \"example@example.com\")\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"config\", \"user.name\", \"Example Example\")\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"config\", \"commit.gpgsign\", \"false\")\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"config\", \"tag.gpgsign\", \"false\")\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"commit\", \"-m\", message ?? \"Add some files.\")\n    }\n\n    /// Tag the git repo.\n    func tag(name: String) throws {\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"tag\", name)\n    }\n\n    /// Push the changes to specified remote and branch.\n    func push(remote: String, branch: String) throws {\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", self.path.pathString, \"push\", remote, branch)\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/InMemoryGitRepository.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport Foundation\nimport SourceControl\nimport struct PackageModel.CanonicalPackageURL\n\nimport struct TSCBasic.ByteString\nimport enum TSCBasic.FileMode\nimport struct TSCBasic.FileSystemError\n\n/// The error encountered during in memory git repository operations.\npublic enum InMemoryGitRepositoryError: Swift.Error {\n    case unknownRevision\n    case unknownTag\n    case tagAlreadyPresent\n}\n\n/// A class that implements basic git features on in-memory file system. It takes the path and file system reference\n/// where the repository should be created. The class itself is a file system pointing to current revision state\n/// i.e. HEAD. All mutations should be made on file system interface of this class and then they can be committed using\n/// commit() method. Calls to checkout related methods will checkout the HEAD on the passed file system at the\n/// repository path, as well as on the file system interface of this class.\n/// Note: This class is intended to be used as testing infrastructure only.\n/// Note: This class is not thread safe yet.\npublic final class InMemoryGitRepository {\n    /// The revision identifier.\n    public typealias RevisionIdentifier = String\n\n    /// A struct representing a revision state. Minimally it contains a hash identifier for the revision\n    /// and the file system state.\n    fileprivate struct RevisionState {\n        /// The revision identifier hash. It should be unique among all the identifiers.\n        var hash: RevisionIdentifier\n\n        /// The filesystem state contained in this revision.\n        let fileSystem: InMemoryFileSystem\n\n        /// Creates copy of the state.\n        func copy() -> RevisionState {\n            return RevisionState(hash: self.hash, fileSystem: self.fileSystem.copy())\n        }\n    }\n\n    /// THe HEAD i.e. the current checked out state.\n    fileprivate var head: RevisionState\n\n    /// The history dictionary.\n    fileprivate var history: [RevisionIdentifier: RevisionState] = [:]\n\n    /// The map containing tag name to revision identifier values.\n    fileprivate var tagsMap: [String: RevisionIdentifier] = [:]\n\n    /// Indicates whether there are any uncommitted changes in the repository.\n    fileprivate var isDirty = false\n\n    /// The path at which this repository is located.\n    fileprivate let path: AbsolutePath\n\n    /// The file system in which this repository should be installed.\n    fileprivate let fs: InMemoryFileSystem\n\n    private let lock = NSLock()\n\n    /// Create a new repository at the given path and filesystem.\n    public init(path: AbsolutePath, fs: InMemoryFileSystem) {\n        self.path = path\n        self.fs = fs\n        // Point head to a new revision state with empty hash to begin with.\n        self.head = RevisionState(hash: \"\", fileSystem: InMemoryFileSystem())\n    }\n\n    /// The array of current tags in the repository.\n    public func getTags() throws -> [String] {\n        self.lock.withLock {\n            Array(self.tagsMap.keys)\n        }\n    }\n\n    /// The list of revisions in the repository.\n    public var revisions: [RevisionIdentifier] {\n        self.lock.withLock {\n            Array(self.history.keys)\n        }\n    }\n\n    /// Copy/clone this repository.\n    fileprivate func copy(at newPath: AbsolutePath? = nil)  throws -> InMemoryGitRepository {\n        let path = newPath ?? self.path\n        try self.fs.createDirectory(path, recursive: true)\n        let repo = InMemoryGitRepository(path: path, fs: self.fs)\n        self.lock.withLock {\n            for (revision, state) in self.history {\n                repo.history[revision] = state.copy()\n            }\n            repo.tagsMap = self.tagsMap\n            repo.head = self.head.copy()\n        }\n        return repo\n    }\n\n    /// Commits the current state of the repository filesystem and returns the commit identifier.\n    @discardableResult\n    public func commit(hash: String? = nil) throws -> String {\n        // Create a fake hash for this commit.\n        let hash = hash ?? String((UUID().uuidString + UUID().uuidString).prefix(40))\n        self.lock.withLock {\n            self.head.hash = hash\n            // Store the commit in history.\n            self.history[hash] = head.copy()\n            // We are not dirty anymore.\n            self.isDirty = false\n        }\n        // Install the current HEAD i.e. this commit to the filesystem that was passed.\n        try installHead()\n        return hash\n    }\n\n    /// Checks out the provided revision.\n    public func checkout(revision: RevisionIdentifier) throws {\n        guard let state = (self.lock.withLock { history[revision] }) else {\n            throw InMemoryGitRepositoryError.unknownRevision\n        }\n        // Point the head to the revision state.\n        self.lock.withLock {\n            self.head = state\n            self.isDirty = false\n        }\n        // Install this state on the passed filesystem.\n        try self.installHead()\n    }\n\n    /// Checks out a given tag.\n    public func checkout(tag: String) throws {\n        guard let hash = (self.lock.withLock { tagsMap[tag] }) else {\n            throw InMemoryGitRepositoryError.unknownTag\n        }\n        // Point the head to the revision state of the tag.\n        // It should be impossible that a tag exists which does not have a state.\n        try self.lock.withLock {\n            guard let head = history[hash] else {\n                throw InternalError(\"unknown hash \\(hash)\")\n            }\n            self.head = head\n            self.isDirty = false\n        }\n        // Install this state on the passed filesystem.\n        try self.installHead()\n    }\n\n    /// Installs (or checks out) current head on the filesystem on which this repository exists.\n    fileprivate func installHead() throws {\n        // Remove the old state.\n        try self.fs.removeFileTree(self.path)\n        // Create the repository directory.\n        try self.fs.createDirectory(self.path, recursive: true)\n        // Get the file system state at the HEAD,\n        let headFs = self.lock.withLock { self.head.fileSystem }\n\n        /// Recursively copies the content at HEAD to fs.\n        func install(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {\n            assert(headFs.isDirectory(sourcePath))\n            for entry in try headFs.getDirectoryContents(sourcePath) {\n                // The full path of the entry.\n                let sourceEntryPath = sourcePath.appending(component: entry)\n                let destinationEntryPath = destinationPath.appending(component: entry)\n                if headFs.isFile(sourceEntryPath) {\n                    // If we have a file just write the file.\n                    let bytes = try headFs.readFileContents(sourceEntryPath)\n                    try self.fs.writeFileContents(destinationEntryPath, bytes: bytes)\n                } else if headFs.isDirectory(sourceEntryPath) {\n                    // If we have a directory, create that directory and copy its contents.\n                    try self.fs.createDirectory(destinationEntryPath, recursive: false)\n                    try install(from: sourceEntryPath, to: destinationEntryPath)\n                }\n            }\n        }\n        // Install at the repository path.\n        try install(from: .root, to: path)\n    }\n\n    /// Tag the current HEAD with the given name.\n    public func tag(name: String) throws {\n        guard (self.lock.withLock { self.tagsMap[name] }) == nil else {\n            throw InMemoryGitRepositoryError.tagAlreadyPresent\n        }\n        self.lock.withLock {\n            self.tagsMap[name] = self.head.hash\n        }\n    }\n\n    public func hasUncommittedChanges() -> Bool {\n        self.lock.withLock {\n            isDirty\n        }\n    }\n\n    public func fetch() throws {\n        // TODO.\n    }\n}\n\nextension InMemoryGitRepository: FileSystem {\n    public func exists(_ path: TSCAbsolutePath, followSymlink: Bool) -> Bool {\n        self.lock.withLock {\n            self.head.fileSystem.exists(path, followSymlink: followSymlink)\n        }\n    }\n\n    public func isDirectory(_ path: TSCAbsolutePath) -> Bool {\n        self.lock.withLock {\n            self.head.fileSystem.isDirectory(path)\n        }\n    }\n\n    public func isFile(_ path: TSCAbsolutePath) -> Bool {\n        self.lock.withLock {\n            self.head.fileSystem.isFile(path)\n        }\n    }\n\n    public func isSymlink(_ path: TSCAbsolutePath) -> Bool {\n        self.lock.withLock {\n            self.head.fileSystem.isSymlink(path)\n        }\n    }\n\n    public func isExecutableFile(_ path: TSCAbsolutePath) -> Bool {\n        self.lock.withLock {\n            self.head.fileSystem.isExecutableFile(path)\n        }\n    }\n\n    public func isReadable(_ path: TSCAbsolutePath) -> Bool {\n        return self.exists(path)\n    }\n\n    public func isWritable(_ path: TSCAbsolutePath) -> Bool {\n        return false\n    }\n\n    public var currentWorkingDirectory: TSCAbsolutePath? {\n        return .root\n    }\n\n    public func changeCurrentWorkingDirectory(to path: TSCAbsolutePath) throws {\n        throw FileSystemError(.unsupported, path)\n    }\n\n    public var homeDirectory: TSCAbsolutePath {\n        fatalError(\"Unsupported\")\n    }\n\n    public var cachesDirectory: TSCAbsolutePath? {\n        fatalError(\"Unsupported\")\n    }\n\n    public var tempDirectory: TSCAbsolutePath {\n        fatalError(\"Unsupported\")\n    }\n\n    public func getDirectoryContents(_ path: TSCAbsolutePath) throws -> [String] {\n        try self.lock.withLock {\n            try self.head.fileSystem.getDirectoryContents(path)\n        }\n    }\n\n    public func createDirectory(_ path: TSCAbsolutePath, recursive: Bool) throws {\n        try self.lock.withLock {\n            try self.head.fileSystem.createDirectory(path, recursive: recursive)\n        }\n    }\n\n    public func createSymbolicLink(_ path: TSCAbsolutePath, pointingAt destination: TSCAbsolutePath, relative: Bool) throws {\n        throw FileSystemError(.unsupported, path)\n    }\n\n    public func readFileContents(_ path: TSCAbsolutePath) throws -> ByteString {\n        try self.lock.withLock {\n            return try head.fileSystem.readFileContents(path)\n        }\n    }\n\n    public func writeFileContents(_ path: TSCAbsolutePath, bytes: ByteString) throws {\n        try self.lock.withLock {\n            try self.head.fileSystem.writeFileContents(path, bytes: bytes)\n            self.isDirty = true\n        }\n    }\n\n    public func removeFileTree(_ path: TSCAbsolutePath) throws {\n        try self.lock.withLock {\n            try self.head.fileSystem.removeFileTree(path)\n        }\n    }\n\n    public func chmod(_ mode: FileMode, path: TSCAbsolutePath, options: Set<FileMode.Option>) throws {\n        try self.lock.withLock {\n            try self.head.fileSystem.chmod(mode, path: path, options: options)\n        }\n    }\n\n    public func copy(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws {\n        try self.lock.withLock {\n            try self.head.fileSystem.copy(from: sourcePath, to: destinationPath)\n        }\n    }\n\n    public func move(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws {\n        try self.lock.withLock {\n            try self.head.fileSystem.move(from: sourcePath, to: destinationPath)\n        }\n    }\n}\n\nextension InMemoryGitRepository: Repository {\n    public func resolveRevision(tag: String) throws -> Revision {\n        try self.lock.withLock {\n            guard let revision = self.tagsMap[tag] else {\n                throw InternalError(\"unknown tag \\(tag)\")\n            }\n            return Revision(identifier: revision)\n        }\n    }\n\n    public func resolveRevision(identifier: String) throws -> Revision {\n        self.lock.withLock {\n            return Revision(identifier: self.tagsMap[identifier] ?? identifier)\n        }\n    }\n\n    public func exists(revision: Revision) -> Bool {\n        self.lock.withLock {\n            return self.history[revision.identifier] != nil\n        }\n    }\n\n    public func openFileView(revision: Revision) throws -> FileSystem {\n        try self.lock.withLock {\n            guard let entry = self.history[revision.identifier] else {\n                throw InternalError(\"unknown revision \\(revision)\")\n            }\n            return entry.fileSystem\n        }\n    }\n\n    public func openFileView(tag: String) throws -> FileSystem {\n        let revision = try self.resolveRevision(tag: tag)\n        return try self.openFileView(revision: revision)\n    }\n}\n\nextension InMemoryGitRepository: WorkingCheckout {\n    public func getCurrentRevision() throws -> Revision {\n        self.lock.withLock {\n            return Revision(identifier: self.head.hash)\n        }\n    }\n\n    public func checkout(revision: Revision) throws {\n        // will lock\n        try checkout(revision: revision.identifier)\n    }\n\n    public func hasUnpushedCommits() throws -> Bool {\n        return false\n    }\n\n    public func checkout(newBranch: String) throws {\n        self.lock.withLock {\n            self.history[newBranch] = head\n        }\n    }\n\n    public func isAlternateObjectStoreValid(expected: AbsolutePath) -> Bool {\n        return true\n    }\n\n    public func areIgnored(_ paths: [AbsolutePath]) throws -> [Bool] {\n        return [false]\n    }\n}\n\n// Public mutation of `InMemoryGitRepository` is protected with a lock.\nextension InMemoryGitRepository: @unchecked Sendable {}\n\n/// This class implement provider for in memory git repository.\npublic final class InMemoryGitRepositoryProvider: RepositoryProvider, @unchecked Sendable {\n    /// Contains the repository added to this provider.\n    public var specifierMap = ThreadSafeKeyValueStore<RepositorySpecifier, InMemoryGitRepository>()\n\n    /// Contains the repositories which are fetched using this provider.\n    public var fetchedMap = ThreadSafeKeyValueStore<AbsolutePath, InMemoryGitRepository>()\n\n    /// Contains the repositories which are checked out using this provider.\n    public var checkoutsMap = ThreadSafeKeyValueStore<AbsolutePath, InMemoryGitRepository>()\n\n    /// Create a new provider.\n    public init() {\n    }\n\n    /// Add a repository to this provider. Only the repositories added with this interface can be operated on\n    /// with this provider.\n    public func add(specifier: RepositorySpecifier, repository: InMemoryGitRepository) {\n        // Save the repository in specifier map.\n        specifierMap[specifier] = repository\n    }\n\n    /// This method returns the stored reference to the git repository which was fetched or checked out.\n    public func openRepo(at path: AbsolutePath) throws -> InMemoryGitRepository {\n        if let fetch = fetchedMap[path] {\n            return fetch\n        }\n        guard let checkout = checkoutsMap[path] else {\n            throw InternalError(\"unknown repo at \\(path)\")\n        }\n        return checkout\n    }\n\n    // MARK: - RepositoryProvider conformance\n    // Note: These methods use force unwrap (instead of throwing) to honor their preconditions.\n\n    public func fetch(repository: RepositorySpecifier, to path: AbsolutePath, progressHandler: FetchProgress.Handler? = nil) async throws {\n        guard let repo = specifierMap[RepositorySpecifier(location: repository.location)] else {\n            throw InternalError(\"unknown repo at \\(repository.location)\")\n        }\n        fetchedMap[path] = try repo.copy()\n        add(specifier: RepositorySpecifier(path: path), repository: repo)\n    }\n\n    public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {\n        guard let repo = fetchedMap[sourcePath] else {\n            throw InternalError(\"unknown repo at \\(sourcePath)\")\n        }\n        fetchedMap[destinationPath] = try repo.copy()\n    }\n\n    public func open(repository: RepositorySpecifier, at path: AbsolutePath) throws -> Repository {\n        guard let repository = self.fetchedMap[path] else {\n            throw InternalError(\"unknown repository at \\(path)\")\n        }\n        return repository\n    }\n\n    public func createWorkingCopy(\n        repository: RepositorySpecifier,\n        sourcePath: AbsolutePath,\n        at destinationPath: AbsolutePath,\n        editable: Bool\n    ) async throws -> WorkingCheckout {\n        guard let checkout = fetchedMap[sourcePath] else {\n            throw InternalError(\"unknown checkout at \\(sourcePath)\")\n        }\n        let copy = try checkout.copy(at: destinationPath)\n        checkoutsMap[destinationPath] = copy\n        return copy\n    }\n\n    public func workingCopyExists(at path: AbsolutePath) throws -> Bool {\n        return checkoutsMap.contains(path)\n    }\n\n    public func openWorkingCopy(at path: AbsolutePath) async throws -> WorkingCheckout {\n        guard let checkout = checkoutsMap[path] else {\n            throw InternalError(\"unknown checkout at \\(path)\")\n        }\n        return checkout\n    }\n\n    public func isValidDirectory(_ directory: AbsolutePath) throws -> Bool {\n        return fetchedMap[directory] != nil || specifierMap.get().values.map(\\.path).contains(directory)\n    }\n\n    public func isValidDirectory(_ directory: AbsolutePath, for repository: RepositorySpecifier) throws -> Bool {\n        return fetchedMap[directory] != nil || specifierMap[repository] != nil\n    }\n\n    public func cancel(deadline: DispatchTime) throws {\n        // noop\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/ManifestExtensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\n\nimport struct TSCUtility.Version\n\nextension Manifest {\n    public static func createRootManifest(\n        displayName: String,\n        path: AbsolutePath = .root,\n        defaultLocalization: String? = nil,\n        platforms: [PlatformDescription] = [],\n        version: TSCUtility.Version? = nil,\n        toolsVersion: ToolsVersion = .v4,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProviderDescription]? = nil,\n        cLanguageStandard: String? = nil,\n        cxxLanguageStandard: String? = nil,\n        swiftLanguageVersions: [SwiftLanguageVersion]? = nil,\n        dependencies: [PackageDependency] = [],\n        products: [ProductDescription] = [],\n        targets: [TargetDescription] = [],\n        traits: Set<TraitDescription> = [],\n        pruneDependencies: Bool = false\n    ) -> Manifest {\n        Self.createManifest(\n            displayName: displayName,\n            path: path,\n            packageKind: .root(path),\n            packageIdentity: .plain(displayName.lowercased()),\n            packageLocation: path.pathString,\n            defaultLocalization: defaultLocalization,\n            platforms: platforms,\n            version: version,\n            toolsVersion: toolsVersion,\n            pkgConfig: pkgConfig,\n            providers: providers,\n            cLanguageStandard: cLanguageStandard,\n            cxxLanguageStandard: cxxLanguageStandard,\n            swiftLanguageVersions: swiftLanguageVersions,\n            dependencies: dependencies,\n            products: products,\n            targets: targets,\n            traits: traits,\n            pruneDependencies: pruneDependencies\n        )\n    }\n\n    public static func createFileSystemManifest(\n        displayName: String,\n        path: AbsolutePath,\n        defaultLocalization: String? = nil,\n        platforms: [PlatformDescription] = [],\n        version: TSCUtility.Version? = nil,\n        toolsVersion: ToolsVersion = .v4,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProviderDescription]? = nil,\n        cLanguageStandard: String? = nil,\n        cxxLanguageStandard: String? = nil,\n        swiftLanguageVersions: [SwiftLanguageVersion]? = nil,\n        dependencies: [PackageDependency] = [],\n        products: [ProductDescription] = [],\n        targets: [TargetDescription] = [],\n        traits: Set<TraitDescription> = [],\n        pruneDependencies: Bool = false\n    ) -> Manifest {\n        Self.createManifest(\n            displayName: displayName,\n            path: path,\n            packageKind: .fileSystem(path),\n            packageIdentity: .plain(displayName.lowercased()),\n            packageLocation: path.pathString,\n            defaultLocalization: defaultLocalization,\n            platforms: platforms,\n            version: version,\n            toolsVersion: toolsVersion,\n            pkgConfig: pkgConfig,\n            providers: providers,\n            cLanguageStandard: cLanguageStandard,\n            cxxLanguageStandard: cxxLanguageStandard,\n            swiftLanguageVersions: swiftLanguageVersions,\n            dependencies: dependencies,\n            products: products,\n            targets: targets,\n            traits: traits,\n            pruneDependencies: pruneDependencies\n        )\n    }\n\n    public static func createLocalSourceControlManifest(\n        displayName: String,\n        path: AbsolutePath,\n        defaultLocalization: String? = nil,\n        platforms: [PlatformDescription] = [],\n        version: TSCUtility.Version? = nil,\n        toolsVersion: ToolsVersion = .v4,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProviderDescription]? = nil,\n        cLanguageStandard: String? = nil,\n        cxxLanguageStandard: String? = nil,\n        swiftLanguageVersions: [SwiftLanguageVersion]? = nil,\n        dependencies: [PackageDependency] = [],\n        products: [ProductDescription] = [],\n        targets: [TargetDescription] = [],\n        pruneDependencies: Bool = false\n    ) -> Manifest {\n        Self.createManifest(\n            displayName: displayName,\n            path: path,\n            packageKind: .localSourceControl(path),\n            packageIdentity: .plain(displayName.lowercased()),\n            packageLocation: path.pathString,\n            defaultLocalization: defaultLocalization,\n            platforms: platforms,\n            version: version,\n            toolsVersion: toolsVersion,\n            pkgConfig: pkgConfig,\n            providers: providers,\n            cLanguageStandard: cLanguageStandard,\n            cxxLanguageStandard: cxxLanguageStandard,\n            swiftLanguageVersions: swiftLanguageVersions,\n            dependencies: dependencies,\n            products: products,\n            targets: targets,\n            traits: [],\n            pruneDependencies: pruneDependencies\n        )\n    }\n\n    public static func createRemoteSourceControlManifest(\n        displayName: String,\n        url: SourceControlURL,\n        path: AbsolutePath,\n        defaultLocalization: String? = nil,\n        platforms: [PlatformDescription] = [],\n        version: TSCUtility.Version? = nil,\n        toolsVersion: ToolsVersion = .v4,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProviderDescription]? = nil,\n        cLanguageStandard: String? = nil,\n        cxxLanguageStandard: String? = nil,\n        swiftLanguageVersions: [SwiftLanguageVersion]? = nil,\n        dependencies: [PackageDependency] = [],\n        products: [ProductDescription] = [],\n        targets: [TargetDescription] = [],\n        pruneDependencies: Bool = false\n    ) -> Manifest {\n        Self.createManifest(\n            displayName: displayName,\n            path: path,\n            packageKind: .remoteSourceControl(url),\n            packageIdentity: .plain(displayName.lowercased()),\n            packageLocation: url.absoluteString,\n            defaultLocalization: defaultLocalization,\n            platforms: platforms,\n            version: version,\n            toolsVersion: toolsVersion,\n            pkgConfig: pkgConfig,\n            providers: providers,\n            cLanguageStandard: cLanguageStandard,\n            cxxLanguageStandard: cxxLanguageStandard,\n            swiftLanguageVersions: swiftLanguageVersions,\n            dependencies: dependencies,\n            products: products,\n            targets: targets,\n            pruneDependencies: pruneDependencies\n        )\n    }\n\n    public static func createRegistryManifest(\n        displayName: String,\n        identity: PackageIdentity,\n        path: AbsolutePath = .root,\n        defaultLocalization: String? = nil,\n        platforms: [PlatformDescription] = [],\n        version: TSCUtility.Version? = nil,\n        toolsVersion: ToolsVersion = .v4,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProviderDescription]? = nil,\n        cLanguageStandard: String? = nil,\n        cxxLanguageStandard: String? = nil,\n        swiftLanguageVersions: [SwiftLanguageVersion]? = nil,\n        dependencies: [PackageDependency] = [],\n        products: [ProductDescription] = [],\n        targets: [TargetDescription] = [],\n        pruneDependencies: Bool = false\n    ) -> Manifest {\n        Self.createManifest(\n            displayName: displayName,\n            path: path,\n            packageKind: .registry(identity),\n            packageIdentity: .plain(displayName.lowercased()),\n            packageLocation: identity.description,\n            defaultLocalization: defaultLocalization,\n            platforms: platforms,\n            version: version,\n            toolsVersion: toolsVersion,\n            pkgConfig: pkgConfig,\n            providers: providers,\n            cLanguageStandard: cLanguageStandard,\n            cxxLanguageStandard: cxxLanguageStandard,\n            swiftLanguageVersions: swiftLanguageVersions,\n            dependencies: dependencies,\n            products: products,\n            targets: targets,\n            pruneDependencies: pruneDependencies\n        )\n    }\n\n    public static func createManifest(\n        displayName: String,\n        path: AbsolutePath = .root,\n        packageKind: PackageReference.Kind,\n        packageIdentity: PackageIdentity,\n        packageLocation: String? = nil,\n        defaultLocalization: String? = nil,\n        platforms: [PlatformDescription] = [],\n        version: TSCUtility.Version? = nil,\n        toolsVersion: ToolsVersion,\n        pkgConfig: String? = nil,\n        providers: [SystemPackageProviderDescription]? = nil,\n        cLanguageStandard: String? = nil,\n        cxxLanguageStandard: String? = nil,\n        swiftLanguageVersions: [SwiftLanguageVersion]? = nil,\n        dependencies: [PackageDependency] = [],\n        products: [ProductDescription] = [],\n        targets: [TargetDescription] = [],\n        traits: Set<TraitDescription> = [],\n        pruneDependencies: Bool = false\n    ) -> Manifest {\n        return Manifest(\n            displayName: displayName,\n            packageIdentity: packageIdentity,\n            path: path.basename == Manifest.filename ? path : path.appending(component: Manifest.filename),\n            packageKind: packageKind,\n            packageLocation: packageLocation ?? path.pathString,\n            defaultLocalization: defaultLocalization,\n            platforms: platforms,\n            version: version,\n            revision: .none,\n            toolsVersion: toolsVersion,\n            pkgConfig: pkgConfig,\n            providers: providers,\n            cLanguageStandard: cLanguageStandard,\n            cxxLanguageStandard: cxxLanguageStandard,\n            swiftLanguageVersions: swiftLanguageVersions,\n            dependencies: dependencies,\n            products: products,\n            targets: targets,\n            traits: traits,\n            pruneDependencies: pruneDependencies\n        )\n    }\n\n    public func with(location: String) -> Manifest {\n        Manifest(\n            displayName: self.displayName,\n            packageIdentity: self.packageIdentity,\n            path: self.path,\n            packageKind: self.packageKind,\n            packageLocation: location,\n            defaultLocalization: self.defaultLocalization,\n            platforms: self.platforms,\n            version: self.version,\n            revision: self.revision,\n            toolsVersion: self.toolsVersion,\n            pkgConfig: self.pkgConfig,\n            providers: self.providers,\n            cLanguageStandard: self.cLanguageStandard,\n            cxxLanguageStandard: self.cxxLanguageStandard,\n            swiftLanguageVersions: self.swiftLanguageVersions,\n            dependencies: self.dependencies,\n            products: self.products,\n            targets: self.targets,\n            traits: self.traits,\n            pruneDependencies: false\n        )\n    }\n\n    public func with(dependencies: [PackageDependency]) -> Manifest {\n        Manifest(\n            displayName: self.displayName,\n            packageIdentity: self.packageIdentity,\n            path: self.path,\n            packageKind: self.packageKind,\n            packageLocation: self.packageLocation,\n            defaultLocalization: self.defaultLocalization,\n            platforms: self.platforms,\n            version: self.version,\n            revision: self.revision,\n            toolsVersion: self.toolsVersion,\n            pkgConfig: self.pkgConfig,\n            providers: self.providers,\n            cLanguageStandard: self.cLanguageStandard,\n            cxxLanguageStandard: self.cxxLanguageStandard,\n            swiftLanguageVersions: self.swiftLanguageVersions,\n            dependencies: dependencies,\n            products: self.products,\n            targets: self.targets,\n            traits: self.traits\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockArchiver.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\npackage final class MockArchiver: Archiver {\n    package typealias ExtractionHandler = @Sendable (\n        MockArchiver,\n        AbsolutePath,\n        AbsolutePath,\n        (Result<Void, Error>) -> Void\n    ) throws -> Void\n    package typealias CompressionHandler = @Sendable (\n        MockArchiver,\n        AbsolutePath,\n        AbsolutePath\n    ) async throws -> Void\n    package typealias ValidationHandler = @Sendable (\n        MockArchiver,\n        AbsolutePath,\n        (Result<Bool, Error>) -> Void\n    ) throws -> Void\n\n    package struct Extraction: Equatable {\n        public let archivePath: AbsolutePath\n        public let destinationPath: AbsolutePath\n\n        public init(archivePath: AbsolutePath, destinationPath: AbsolutePath) {\n            self.archivePath = archivePath\n            self.destinationPath = destinationPath\n        }\n    }\n\n    package struct Compression: Equatable {\n        public let directory: AbsolutePath\n        public let destinationPath: AbsolutePath\n\n        public init(directory: AbsolutePath, destinationPath: AbsolutePath) {\n            self.directory = directory\n            self.destinationPath = destinationPath\n        }\n    }\n\n    package let supportedExtensions: Set<String> = [\"zip\"]\n    package let extractions = ThreadSafeArrayStore<Extraction>()\n    package let compressions = ThreadSafeArrayStore<Compression>()\n    package let extractionHandler: ExtractionHandler?\n    package let compressionHandler: CompressionHandler?\n    package let validationHandler: ValidationHandler?\n\n    package convenience init(handler: ExtractionHandler? = .none) {\n        self.init(extractionHandler: handler, compressionHandler: .none, validationHandler: .none)\n    }\n\n    package init(\n        extractionHandler: ExtractionHandler? = .none,\n        compressionHandler: CompressionHandler? = .none,\n        validationHandler: ValidationHandler? = .none\n    ) {\n        self.extractionHandler = extractionHandler\n        self.compressionHandler = compressionHandler\n        self.validationHandler = validationHandler\n    }\n\n    package func extract(\n        from archivePath: AbsolutePath,\n        to destinationPath: AbsolutePath,\n        completion: @escaping (Result<Void, Error>) -> Void\n    ) {\n        do {\n            if let handler = self.extractionHandler {\n                try handler(self, archivePath, destinationPath, completion)\n            } else {\n                self.extractions.append(Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            }\n        } catch {\n            completion(.failure(error))\n        }\n    }\n\n    package func compress(\n        directory: AbsolutePath,\n        to destinationPath: AbsolutePath\n    ) async throws {\n        guard let handler = self.compressionHandler else {\n            self.compressions.append(Compression(directory: directory, destinationPath: destinationPath))\n            return\n        }\n        try await handler(self, directory, destinationPath)\n    }\n\n    package func validate(path: AbsolutePath, completion: @escaping (Result<Bool, Error>) -> Void) {\n        do {\n            if let handler = self.validationHandler {\n                try handler(self, path, completion)\n            } else {\n                completion(.success(true))\n            }\n        } catch {\n            completion(.failure(error))\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockBuildTestHelper.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nimport struct PackageGraph.ModulesGraph\nimport struct PackageGraph.ResolvedModule\nimport struct PackageGraph.ResolvedProduct\nimport PackageModel\nimport SPMBuildCore\nimport TSCUtility\n\npublic struct MockToolchain: PackageModel.Toolchain {\n    public let metalToolchainId: String?\n    public let metalToolchainPath: Basics.AbsolutePath?\n    #if os(Windows)\n    public let librarianPath = AbsolutePath(\"/fake/path/to/link.exe\")\n    #elseif canImport(Darwin)\n    public let librarianPath = AbsolutePath(\"/fake/path/to/libtool\")\n    #else\n    public let librarianPath = AbsolutePath(\"/fake/path/to/llvm-ar\")\n    #endif\n    public let swiftCompilerPath = AbsolutePath(\"/fake/path/to/swiftc\")\n    public let includeSearchPaths = [AbsolutePath]()\n    public let librarySearchPaths = [AbsolutePath]()\n    public let runtimeLibraryPaths: [AbsolutePath] = [AbsolutePath]()\n    public let swiftResourcesPath: AbsolutePath?\n    public let swiftStaticResourcesPath: AbsolutePath? = nil\n    public let sdkRootPath: AbsolutePath? = nil\n    public let extraFlags = PackageModel.BuildFlags()\n    public let installedSwiftPMConfiguration = InstalledSwiftPMConfiguration.default\n    public let swiftPMLibrariesLocation = ToolchainConfiguration.SwiftPMLibrariesLocation(\n        manifestLibraryPath: AbsolutePath(\"/fake/manifestLib/path\"), pluginLibraryPath: AbsolutePath(\"/fake/pluginLibrary/path\")\n    )\n    public var swiftSDK: PackageModel.SwiftSDK\n\n    public func getClangCompiler() throws -> AbsolutePath {\n        \"/fake/path/to/clang\"\n    }\n\n    public func _isClangCompilerVendorApple() throws -> Bool? {\n        #if os(macOS)\n        return true\n        #else\n        return false\n        #endif\n    }\n\n    public init(swiftResourcesPath: AbsolutePath? = nil) throws {\n        self.swiftResourcesPath = swiftResourcesPath\n        self.metalToolchainPath = nil\n        self.metalToolchainId = nil\n        self.swiftSDK = try .hostSwiftSDK()\n    }\n}\n\nextension Basics.Triple {\n    public static let x86_64MacOS = try! Self(\"x86_64-apple-macosx\")\n    public static let x86_64Linux = try! Self(\"x86_64-unknown-linux-gnu\")\n    public static let arm64Linux = try! Self(\"aarch64-unknown-linux-gnu\")\n    public static let arm64Android = try! Self(\"aarch64-unknown-linux-android\")\n    public static let windows = try! Self(\"x86_64-unknown-windows-msvc\")\n    public static let x86_64Windows = try! Self(\"x86_64-unknown-windows-msvc\")\n    public static let arm64Windows = try! Self(\"aarch64-unknown-windows-msvc\")\n    public static let wasi = try! Self(\"wasm32-unknown-wasi\")\n    public static let arm64iOS = try! Self(\"arm64-apple-ios\")\n    public static let arm64MacOS = try! Self(\"arm64-apple-macosx\")\n}\n\npublic let hostTriple = try! UserToolchain.default.targetTriple\n#if os(macOS)\npublic let defaultTargetTriple: String = hostTriple.tripleString(forPlatformVersion: \"10.13\")\n#else\npublic let defaultTargetTriple: String = hostTriple.tripleString\n#endif\n\npublic func mockBuildParameters(\n    destination: BuildParameters.Destination,\n    buildPath: AbsolutePath? = nil,\n    config: BuildConfiguration = .debug,\n    toolchain: PackageModel.Toolchain = try! MockToolchain(),\n    flags: PackageModel.BuildFlags = PackageModel.BuildFlags(),\n    buildSystemKind: BuildSystemProvider.Kind = .native,\n    shouldLinkStaticSwiftStdlib: Bool = false,\n    shouldDisableLocalRpath: Bool = false,\n    canRenameEntrypointFunctionName: Bool = false,\n    triple: Basics.Triple = hostTriple,\n    indexStoreMode: BuildParameters.IndexStoreMode = .auto,\n    linkerDeadStrip: Bool = true,\n    linkTimeOptimizationMode: BuildParameters.LinkTimeOptimizationMode? = nil,\n    omitFramePointers: Bool? = nil,\n    enableXCFrameworksOnLinux: Bool = false,\n    prepareForIndexing: BuildParameters.PrepareForIndexingMode = .off,\n    sanitizers: [Sanitizer] = [],\n    numberOfWorkers: UInt32 = 3,\n) -> BuildParameters {\n    try! BuildParameters(\n        destination: destination,\n        dataPath: buildPath ?? AbsolutePath(\"/path/to/build\").appending(triple.tripleString),\n        configuration: config,\n        toolchain: toolchain,\n        triple: triple,\n        flags: flags,\n        buildSystemKind: buildSystemKind,\n        pkgConfigDirectories: [],\n        workers: numberOfWorkers,\n        sanitizers: EnabledSanitizers(Set(sanitizers)),\n        indexStoreMode: indexStoreMode,\n        prepareForIndexing: prepareForIndexing,\n        enableXCFrameworksOnLinux: enableXCFrameworksOnLinux,\n        debuggingParameters: .init(\n            triple: triple,\n            shouldEnableDebuggingEntitlement: config == .debug,\n            omitFramePointers: omitFramePointers\n        ),\n        driverParameters: .init(\n            canRenameEntrypointFunctionName: canRenameEntrypointFunctionName,\n        ),\n        linkingParameters: .init(\n            linkerDeadStrip: linkerDeadStrip,\n            linkTimeOptimizationMode: linkTimeOptimizationMode,\n            shouldDisableLocalRpath: shouldDisableLocalRpath,\n            shouldLinkStaticSwiftStdlib: shouldLinkStaticSwiftStdlib\n        ),\n    )\n}\n\npublic func mockBuildParameters(\n    destination: BuildParameters.Destination,\n    environment: BuildEnvironment\n) -> BuildParameters {\n    let triple: Basics.Triple\n    switch environment.platform {\n    case .macOS:\n        triple = Triple.x86_64MacOS\n    case .linux:\n        triple = Triple.arm64Linux\n    case .android:\n        triple = Triple.arm64Android\n    case .windows:\n        triple = Triple.windows\n    default:\n        fatalError(\"unsupported platform in tests\")\n    }\n\n    return mockBuildParameters(\n        destination: destination,\n        config: environment.configuration ?? .debug,\n        triple: triple\n    )\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockDependency.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageLoading\nimport PackageModel\n\npublic typealias SourceControlRequirement = PackageDependency.SourceControl.Requirement\npublic typealias RegistryRequirement = PackageDependency.Registry.Requirement\n\npublic struct MockDependency {\n    public let deprecatedName: String?\n    public let location: Location\n    public let products: ProductFilter\n    public let traits: Set<PackageDependency.Trait>\n\n    init(\n        deprecatedName: String? = nil,\n        location: Location,\n        products: ProductFilter = .everything,\n        traits: Set<PackageDependency.Trait> = [\"default\"]\n    ) {\n        self.deprecatedName = deprecatedName\n        self.location = location\n        self.products = products\n        self.traits = traits\n    }\n\n    public func convert(baseURL: AbsolutePath, identityResolver: IdentityResolver) throws -> PackageDependency {\n        switch self.location {\n        case .fileSystem(let path):\n            let absolutePath = baseURL.appending(path)\n            let mappedLocation = identityResolver.mappedLocation(for: absolutePath.pathString)\n            guard let mappedPath = try? AbsolutePath(validating: mappedLocation) else {\n                throw StringError(\"invalid mapping of '\\(path)' to '\\(mappedLocation)', no requirement information available.\")\n            }\n            let identity = try identityResolver.resolveIdentity(for: mappedPath)\n            return .fileSystem(\n                identity: identity,\n                deprecatedName: self.deprecatedName,\n                path: mappedPath,\n                productFilter: self.products,\n                traits: self.traits\n            )\n        case .localSourceControl(let path, let requirement):\n            let absolutePath = baseURL.appending(path)\n            let mappedLocation = identityResolver.mappedLocation(for: absolutePath.pathString)\n            guard let mappedPath = try? AbsolutePath(validating: mappedLocation) else {\n                throw StringError(\"invalid mapping of '\\(path)' to '\\(mappedLocation)', no requirement information available.\")\n            }\n            let identity = try identityResolver.resolveIdentity(for: mappedPath)\n            return .localSourceControl(\n                identity: identity,\n                deprecatedName: self.deprecatedName,\n                path: mappedPath,\n                requirement: requirement,\n                productFilter: self.products,\n                traits: self.traits\n            )\n        case .remoteSourceControl(let url, let _requirement):\n            let mappedLocation = identityResolver.mappedLocation(for: url.absoluteString)\n            if PackageIdentity.plain(mappedLocation).isRegistry {\n                let identity = PackageIdentity.plain(mappedLocation)\n                let requirement: RegistryRequirement\n                switch _requirement {\n                case .branch, .revision:\n                    throw StringError(\"invalid mapping of source control to registry, requirement information mismatch.\")\n                case .exact(let value):\n                    requirement = .exact(value)\n                case .range(let value):\n                    requirement = .range(value)\n                }\n                return .registry(\n                    identity: identity,\n                    requirement: requirement,\n                    productFilter: self.products,\n                    traits: self.traits\n                )\n\n            } else {\n                let mappedURL = SourceControlURL(mappedLocation)\n                let identity = try identityResolver.resolveIdentity(for: mappedURL)\n                return .remoteSourceControl(\n                    identity: identity,\n                    deprecatedName: self.deprecatedName,\n                    url: mappedURL,\n                    requirement: _requirement,\n                    productFilter: self.products,\n                    traits: self.traits\n                )\n            }\n        case .registry(let identity, let _requirement):\n            let mappedLocation = identityResolver.mappedLocation(for: identity.description)\n            if PackageIdentity.plain(mappedLocation).isRegistry {\n                let identity = PackageIdentity.plain(mappedLocation)\n                return .registry(\n                    identity: identity,\n                    requirement: _requirement,\n                    productFilter: self.products,\n                    traits: self.traits\n                )\n            } else {\n                let mappedURL = SourceControlURL(mappedLocation)\n                let identity = try identityResolver.resolveIdentity(for: mappedURL)\n                let requirement: SourceControlRequirement\n                switch _requirement {\n                case .exact(let value):\n                    requirement = .exact(value)\n                case .range(let value):\n                    requirement = .range(value)\n                }\n                return .remoteSourceControl(\n                    identity: identity,\n                    deprecatedName: self.deprecatedName,\n                    url: mappedURL,\n                    requirement: requirement,\n                    productFilter: self.products,\n                    traits: self.traits\n                )\n            }\n        }\n        \n    }\n\n    public static func fileSystem(path: String, products: ProductFilter = .everything, traits: Set<PackageDependency.Trait> = [\"default\"]) -> MockDependency {\n        try! MockDependency(location: .fileSystem(path: RelativePath(validating: path)), products: products, traits: traits)\n    }\n\n    public static func sourceControl(path: String, requirement: SourceControlRequirement, products: ProductFilter = .everything, traits: Set<PackageDependency.Trait> = [\"default\"]) -> MockDependency {\n        try! .sourceControl(path: RelativePath(validating: path), requirement: requirement, products: products, traits: traits)\n    }\n\n    public static func sourceControl(path: RelativePath, requirement: SourceControlRequirement, products: ProductFilter = .everything, traits: Set<PackageDependency.Trait> = [\"default\"]) -> MockDependency {\n        MockDependency(location: .localSourceControl(path: path, requirement: requirement), products: products, traits: traits)\n    }\n\n    public static func sourceControlWithDeprecatedName(name: String, path: String, requirement: SourceControlRequirement, products: ProductFilter = .everything, traits: Set<PackageDependency.Trait> = [\"default\"]) -> MockDependency {\n        try! MockDependency(deprecatedName: name, location: .localSourceControl(path: RelativePath(validating: path), requirement: requirement), products: products, traits: traits)\n    }\n\n    public static func sourceControl(url: String, requirement: SourceControlRequirement, products: ProductFilter = .everything, traits: Set<PackageDependency.Trait> = [\"default\"]) -> MockDependency {\n        .sourceControl(url: SourceControlURL(url), requirement: requirement, products: products, traits: traits)\n    }\n\n    public static func sourceControl(url: SourceControlURL, requirement: SourceControlRequirement, products: ProductFilter = .everything, traits: Set<PackageDependency.Trait> = [\"default\"]) -> MockDependency {\n        MockDependency(location: .remoteSourceControl(url: url, requirement: requirement), products: products, traits: traits)\n    }\n\n    public static func registry(identity: String, requirement: RegistryRequirement, products: ProductFilter = .everything, traits: Set<PackageDependency.Trait> = [\"default\"]) -> MockDependency {\n        .registry(identity: .plain(identity), requirement: requirement, traits: traits)\n    }\n\n    public static func registry(identity: PackageIdentity, requirement: RegistryRequirement, products: ProductFilter = .everything, traits: Set<PackageDependency.Trait> = [\"default\"]) -> MockDependency {\n        MockDependency(location: .registry(identity: identity, requirement: requirement), products: products, traits: traits)\n    }\n\n    public enum Location {\n        case fileSystem(path: RelativePath)\n        case localSourceControl(path: RelativePath, requirement: SourceControlRequirement)\n        case remoteSourceControl(url: SourceControlURL, requirement: SourceControlRequirement)\n        case registry(identity: PackageIdentity, requirement: RegistryRequirement)\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockDependencyGraph.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport XCTest\nimport Testing\n\nimport PackageGraph\nimport PackageModel\n\nimport struct TSCUtility.Version\n\npublic struct MockDependencyGraph {\n    public let name: String\n    public let constraints: [MockPackageContainer.Constraint]\n    public let containers: [MockPackageContainer]\n    public let result: [PackageReference: Version]\n\n    public init(name: String, constraints: [MockPackageContainer.Constraint], containers: [MockPackageContainer], result: [PackageReference : Version]) {\n        self.name = name\n        self.constraints = constraints\n        self.containers = containers\n        self.result = result\n    }\n\n    public func checkResult(\n        _ output: [(container: PackageReference, version: Version)],\n        file: StaticString = #file,\n        line: UInt = #line,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) {\n        var result = self.result\n        for item in output {\n            if Test.current != nil {\n                #expect(\n                    result[item.container] == item.version,\n                    sourceLocation: sourceLocation,\n                )\n            } else {\n                XCTAssertEqual(result[item.container], item.version, file: file, line: line)\n            }\n            result[item.container] = nil\n        }\n        if !result.isEmpty {\n            if Test.current != nil {\n                Issue.record(\n                    \"Unchecked containers: \\(result)\",\n                    sourceLocation: sourceLocation,\n                )\n            } else {\n                XCTFail(\"Unchecked containers: \\(result)\", file: file, line: line)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockHTTPClient.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nextension HTTPClient {\n    public static func mock(fileSystem: FileSystem) -> HTTPClient {\n        HTTPClient { request, _ in\n            switch request.kind {\n            case.generic:\n                return .okay(body: request.url.absoluteString)\n\n            case .download(let fileSystem, let destination):\n                try fileSystem.writeFileContents(\n                    destination,\n                    string: request.url.absoluteString\n                )\n                return .okay(body: request.url.absoluteString)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockHashAlgorithm.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\nimport struct TSCBasic.ByteString\nimport protocol TSCBasic.HashAlgorithm\n\npublic final class MockHashAlgorithm {\n    public typealias Handler = @Sendable (ByteString) -> ByteString\n\n    public let hashes = ThreadSafeArrayStore<ByteString>()\n    private let handler: Handler?\n\n    public init(handler: Handler? = nil) {\n        self.handler = handler\n    }\n\n    public func hash(_ hash: ByteString) -> ByteString {\n        if let handler = self.handler {\n            return handler(hash)\n        } else {\n            self.hashes.append(hash)\n            return ByteString(hash.contents.reversed())\n        }\n    }\n}\n\nextension MockHashAlgorithm: HashAlgorithm {}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockManifestLoader.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport PackageModel\nimport PackageLoading\nimport PackageGraph\n\nimport func XCTest.XCTFail\n\nimport struct TSCUtility.Version\n\npublic enum MockManifestLoaderError: Swift.Error {\n    case unknownRequest(String)\n}\n\n/// A mock manifest loader implementation.\n///\n/// This implementation takes a canned set of manifests for known URLs and\n/// versions and exposes them via the `ManifestLoaderProtocol`, for use in\n/// testing higher-level clients which use manifests, but don't require testing\n/// the loading logic itself.\n///\n/// This implementation will throw an error if a request to load an unknown\n/// manifest is made.\npublic final class MockManifestLoader: ManifestLoaderProtocol {\n    public struct Key: Hashable {\n        public let url: String\n        public let version: Version?\n\n        public init(url: String, version: Version? = nil) {\n            self.url = url\n            self.version = version\n        }\n    }\n\n    public let manifests: ThreadSafeKeyValueStore<Key, Manifest>\n\n    public init(manifests: [Key: Manifest]) {\n        self.manifests = ThreadSafeKeyValueStore<Key, Manifest>(manifests)\n    }\n\n    public func load(\n        manifestPath: AbsolutePath,\n        manifestToolsVersion: ToolsVersion,\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packageLocation: String,\n        packageVersion: (version: Version?, revision: String?)?,\n        identityResolver: IdentityResolver,\n        dependencyMapper: DependencyMapper,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope,\n        delegateQueue: DispatchQueue\n    ) async throws -> Manifest {\n        let key = Key(url: packageLocation, version: packageVersion?.version)\n        if let result = self.manifests[key] {\n            return result\n        } else {\n            throw MockManifestLoaderError.unknownRequest(\"\\(key)\")\n        }\n    }\n\n    public func resetCache(observabilityScope: ObservabilityScope) async {}\n    public func purgeCache(observabilityScope: ObservabilityScope) async {}\n}\n\nextension ManifestLoader {\n    public func load(\n        manifestPath: AbsolutePath,\n        packageKind: PackageReference.Kind,\n        toolsVersion manifestToolsVersion: ToolsVersion,\n        identityResolver: IdentityResolver = DefaultIdentityResolver(),\n        dependencyMapper: DependencyMapper? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Manifest{\n        let packageIdentity: PackageIdentity\n        let packageLocation: String\n        switch packageKind {\n        case .root(let path):\n            packageIdentity = try identityResolver.resolveIdentity(for: path)\n            packageLocation = path.pathString\n        case .fileSystem(let path):\n            packageIdentity = try identityResolver.resolveIdentity(for: path)\n            packageLocation = path.pathString\n        case .localSourceControl(let path):\n            packageIdentity = try identityResolver.resolveIdentity(for: path)\n            packageLocation = path.pathString\n        case .remoteSourceControl(let url):\n            packageIdentity = try identityResolver.resolveIdentity(for: url)\n            packageLocation = url.absoluteString\n        case .registry(let identity):\n            packageIdentity = identity\n            // FIXME: placeholder\n            packageLocation = identity.description\n        }\n        return try await self.load(\n            manifestPath: manifestPath,\n            manifestToolsVersion: manifestToolsVersion,\n            packageIdentity: packageIdentity,\n            packageKind: packageKind,\n            packageLocation: packageLocation,\n            packageVersion: nil,\n            identityResolver: identityResolver,\n            dependencyMapper: dependencyMapper ?? DefaultDependencyMapper(identityResolver: identityResolver),\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            delegateQueue: .sharedConcurrent\n        )\n    }\n}\n\nextension ManifestLoader {\n    public func load(\n        packagePath: AbsolutePath,\n        packageKind: PackageReference.Kind,\n        currentToolsVersion: ToolsVersion,\n        identityResolver: IdentityResolver = DefaultIdentityResolver(),\n        dependencyMapper: DependencyMapper? = .none,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) async throws -> Manifest {\n        let packageIdentity: PackageIdentity\n        let packageLocation: String\n        switch packageKind {\n        case .root(let path):\n            packageIdentity = try identityResolver.resolveIdentity(for: path)\n            packageLocation = path.pathString\n        case .fileSystem(let path):\n            packageIdentity = try identityResolver.resolveIdentity(for: path)\n            packageLocation = path.pathString\n        case .localSourceControl(let path):\n            packageIdentity = try identityResolver.resolveIdentity(for: path)\n            packageLocation = path.pathString\n        case .remoteSourceControl(let url):\n            packageIdentity = try identityResolver.resolveIdentity(for: url)\n            packageLocation = url.absoluteString\n        case .registry(let identity):\n            packageIdentity = identity\n            // FIXME: placeholder\n            packageLocation = identity.description\n        }\n        return try await self.load(\n            packagePath: packagePath,\n            packageIdentity: packageIdentity,\n            packageKind: packageKind,\n            packageLocation: packageLocation,\n            packageVersion: nil,\n            currentToolsVersion: currentToolsVersion,\n            identityResolver: identityResolver,\n            dependencyMapper: dependencyMapper ?? DefaultDependencyMapper(identityResolver: identityResolver),\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope,\n            delegateQueue: .sharedConcurrent\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockPackage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\n\npublic struct MockPackage {\n    public let name: String\n    public let platforms: [PlatformDescription]\n    public let location: Location\n    public let targets: [MockTarget]\n    public let products: [MockProduct]\n    public let dependencies: [MockDependency]\n    public let versions: [String?]\n    package let traits: Set<TraitDescription>\n    /// Provides revision identifier for the given version. A random identifier might be assigned if this is nil.\n    public let revisionProvider: ((String) -> String)?\n    // FIXME: This should be per-version.\n    public let toolsVersion: ToolsVersion?\n\n    public init(\n        name: String,\n        platforms: [PlatformDescription] = [],\n        path: String? = nil,\n        targets: [MockTarget],\n        products: [MockProduct] = [],\n        dependencies: [MockDependency] = [],\n        traits: Set<TraitDescription> = [],\n        versions: [String?] = [],\n        revisionProvider: ((String) -> String)? = nil,\n        toolsVersion: ToolsVersion? = nil\n    ) {\n        let path = try! RelativePath(validating: path ?? name)\n        self.name = name\n        self.platforms = platforms\n        self.location = .fileSystem(path: path)\n        self.targets = targets\n        self.products = products\n        self.dependencies = dependencies\n        self.traits = traits\n        self.versions = versions\n        self.revisionProvider = revisionProvider\n        self.toolsVersion = toolsVersion\n    }\n\n    public init(\n        name: String,\n        platforms: [PlatformDescription] = [],\n        url: String,\n        targets: [MockTarget],\n        products: [MockProduct],\n        dependencies: [MockDependency] = [],\n        traits: Set<TraitDescription> = [.init(name: \"default\")],\n        versions: [String?] = [],\n        revisionProvider: ((String) -> String)? = nil,\n        toolsVersion: ToolsVersion? = nil\n    ) {\n        self.name = name\n        self.platforms = platforms\n        self.location = .sourceControl(url: SourceControlURL(url))\n        self.targets = targets\n        self.products = products\n        self.dependencies = dependencies\n        self.traits = traits\n        self.versions = versions\n        self.revisionProvider = revisionProvider\n        self.toolsVersion = toolsVersion\n    }\n\n    public init(\n        name: String,\n        platforms: [PlatformDescription] = [],\n        identity: String,\n        alternativeURLs: [String]? = .none,\n        metadata: RegistryReleaseMetadata? = .none,\n        targets: [MockTarget],\n        products: [MockProduct],\n        dependencies: [MockDependency] = [],\n        traits: Set<TraitDescription> = [.init(name: \"default\")],\n        versions: [String?] = [],\n        revisionProvider: ((String) -> String)? = nil,\n        toolsVersion: ToolsVersion? = nil\n    ) {\n        self.name = name\n        self.platforms = platforms\n        self.location = .registry(\n            identity: .plain(identity),\n            alternativeURLs: alternativeURLs?.compactMap{ URL(string: $0) },\n            metadata: metadata\n        )\n        self.targets = targets\n        self.products = products\n        self.dependencies = dependencies\n        self.traits = traits\n        self.versions = versions\n        self.revisionProvider = revisionProvider\n        self.toolsVersion = toolsVersion\n    }\n\n    public static func genericPackage(named name: String) throws -> MockPackage {\n        return MockPackage(\n            name: name,\n            targets: [\n                try MockTarget(name: name),\n            ],\n            products: [\n                MockProduct(name: name, modules: [name]),\n            ],\n            versions: [\"1.0.0\"]\n        )\n    }\n\n    public enum Location {\n        case fileSystem(path: RelativePath)\n        case sourceControl(url: SourceControlURL)\n        case registry(identity: PackageIdentity, alternativeURLs: [URL]?, metadata: RegistryReleaseMetadata?)\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockPackageContainer.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport PackageGraph\nimport PackageModel\nimport SourceControl\n\nimport struct TSCUtility.Version\n\npublic class MockPackageContainer: CustomPackageContainer {\n    public typealias Constraint = PackageContainerConstraint\n\n    public typealias Dependency = (container: PackageReference, requirement: PackageRequirement)\n\n    public let package: PackageReference\n\n    let dependencies: [String: [Dependency]]\n    let filteredMode: Bool\n    let filteredDependencies: [ProductFilter: [Dependency]]\n    let fileSystem: FileSystem?\n    let customRetrievalPath: AbsolutePath?\n\n    public var unversionedDeps: [MockPackageContainer.Constraint] = []\n\n    /// Contains the versions for which the dependencies were requested by resolver using getDependencies().\n    public var requestedVersions: Set<Version> = []\n\n    public let _versions: [Version]\n    public func toolsVersionsAppropriateVersionsDescending() async throws -> [Version] {\n        return try await self.versionsDescending()\n    }\n\n    public func versionsAscending() throws -> [Version] {\n        return _versions\n    }\n\n    public func getDependencies(at version: Version, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) -> [MockPackageContainer.Constraint] {\n        requestedVersions.insert(version)\n        return getDependencies(at: version.description, productFilter: productFilter, enabledTraits)\n    }\n\n    public func getDependencies(at revision: String, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) -> [MockPackageContainer.Constraint] {\n        let dependencies: [Dependency]\n        if filteredMode {\n            dependencies = filteredDependencies[productFilter]!\n        } else {\n            dependencies = self.dependencies[revision]!\n        }\n        return dependencies.map { value in\n            let (package, requirement) = value\n            return MockPackageContainer.Constraint(package: package, requirement: requirement, products: productFilter)\n        }\n    }\n\n    public func getUnversionedDependencies(productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) -> [MockPackageContainer.Constraint] {\n        return unversionedDeps\n    }\n\n    public func loadPackageReference(at boundVersion: BoundVersion) throws -> PackageReference {\n        return self.package\n    }\n\n    public func isToolsVersionCompatible(at version: Version) -> Bool {\n        return true\n    }\n\n    public func toolsVersion(for version: Version) throws -> ToolsVersion {\n        return ToolsVersion.current\n    }\n\n    public var isRemoteContainer: Bool? {\n        return true\n    }\n\n    public func retrieve(at version: Version, progressHandler: ((Int64, Int64?) -> Void)?, observabilityScope: ObservabilityScope) throws -> AbsolutePath {\n        if let customRetrievalPath {\n            return customRetrievalPath\n        } else {\n            throw StringError(\"no path configured for mock package container\")\n        }\n    }\n\n    public func getFileSystem() throws -> FileSystem? {\n        return fileSystem\n    }\n\n    public convenience init(\n        name: String,\n        dependenciesByVersion: [Version: [(container: String, versionRequirement: VersionSetSpecifier)]]\n    ) throws {\n        var dependencies: [String: [Dependency]] = [:]\n        for (version, deps) in dependenciesByVersion {\n            dependencies[version.description] = try deps.map {\n                let path = try AbsolutePath(validating: \"/\\($0.container)\")\n                let ref = PackageReference.localSourceControl(identity: .init(path: path), path: path)\n                return (ref, .versionSet($0.versionRequirement))\n            }\n        }\n        let path = try AbsolutePath(validating: \"/\\(name)\")\n        let ref = PackageReference.localSourceControl(identity: .init(path: path), path: path)\n        self.init(package: ref, dependencies: dependencies)\n    }\n\n    public init(\n        package: PackageReference,\n        dependencies: [String: [Dependency]] = [:],\n        fileSystem: FileSystem? = nil,\n        customRetrievalPath: AbsolutePath? = nil\n    ) {\n        self.package = package\n        self._versions = dependencies.keys.compactMap(Version.init(_:)).sorted()\n        self.dependencies = dependencies\n        self.filteredMode = false\n        self.filteredDependencies = [:]\n\n        self.fileSystem = fileSystem\n        self.customRetrievalPath = customRetrievalPath\n    }\n\n    public init(\n        name: String,\n        dependenciesByProductFilter: [ProductFilter: [(container: String, versionRequirement: VersionSetSpecifier)]]\n    ) throws {\n        var dependencies: [ProductFilter: [Dependency]] = [:]\n        for (filter, deps) in dependenciesByProductFilter {\n            dependencies[filter] = try deps.map {\n                let path = try AbsolutePath(validating: \"/\\($0.container)\")\n                let ref = PackageReference.localSourceControl(identity: .init(path: path), path: path)\n                return (ref, .versionSet($0.versionRequirement))\n            }\n        }\n        let path = try AbsolutePath(validating: \"/\\(name)\")\n        let ref = PackageReference.localSourceControl(identity: .init(path: path), path: path)\n        self.package = ref\n        self._versions = [Version(1, 0, 0)]\n        self.dependencies = [:]\n        self.filteredMode = true\n        self.filteredDependencies = dependencies\n\n        self.fileSystem = nil\n        self.customRetrievalPath = nil\n    }\n}\n\npublic struct MockPackageContainerProvider: PackageContainerProvider {\n    public let containers: [MockPackageContainer]\n    public let containersByIdentifier: [PackageReference: MockPackageContainer]\n\n    public init(containers: [MockPackageContainer]) {\n        self.containers = containers\n        self.containersByIdentifier = Dictionary(uniqueKeysWithValues: containers.map { ($0.package, $0) })\n    }\n\n    public func getContainer(\n        for package: PackageReference,\n        updateStrategy: ContainerUpdateStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> PackageContainer {\n        guard let container = self.containersByIdentifier[package] else {\n            throw StringError(\"unknown module \\(package)\")\n        }\n        return container\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockPackageFingerprintStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport class Foundation.NSLock\nimport PackageFingerprint\nimport PackageModel\n\nimport struct TSCUtility.Version\n\npublic class MockPackageFingerprintStorage: PackageFingerprintStorage {\n    private var packageFingerprints: [PackageIdentity: [Version: [Fingerprint\n            .Kind: [Fingerprint.ContentType: Fingerprint]]]]\n    private let lock = NSLock()\n\n    public init(_ packageFingerprints: [PackageIdentity: [Version: [Fingerprint\n            .Kind: [Fingerprint.ContentType: Fingerprint]]]] = [:])\n    {\n        self.packageFingerprints = packageFingerprints\n    }\n\n    public func get(\n        package: PackageIdentity,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] {\n        guard let fingerprints = self.lock.withLock({ self.packageFingerprints[package]?[version] }) else {\n            throw PackageFingerprintStorageError.notFound\n        }\n        return fingerprints\n    }\n\n    public func put(\n        package: PackageIdentity,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.lock.withLock {\n            var versionFingerprints = self.packageFingerprints.removeValue(forKey: package) ?? [:]\n            var fingerprintsForVersion = versionFingerprints.removeValue(forKey: version) ?? [:]\n            var fingerprintsForKind = fingerprintsForVersion.removeValue(forKey: fingerprint.origin.kind) ?? [:]\n\n            if let existing = fingerprintsForKind[fingerprint.contentType] {\n                // Error if we try to write a different fingerprint\n                guard fingerprint == existing else {\n                    throw PackageFingerprintStorageError.conflict(given: fingerprint, existing: existing)\n                }\n                // Don't need to do anything if fingerprints are the same\n                return\n            }\n\n            fingerprintsForKind[fingerprint.contentType] = fingerprint\n            fingerprintsForVersion[fingerprint.origin.kind] = fingerprintsForKind\n            versionFingerprints[version] = fingerprintsForVersion\n            self.packageFingerprints[package] = versionFingerprints\n        }\n    }\n\n    public func get(\n        package: PackageReference,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] {\n        try self.get(\n            package: package.identity,\n            version: version,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    public func put(\n        package: PackageReference,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.put(\n            package: package.identity,\n            version: version,\n            fingerprint: fingerprint,\n            observabilityScope: observabilityScope\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockPackageGraphs.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport class Basics.InMemoryFileSystem\nimport class Basics.ObservabilitySystem\nimport class Basics.ObservabilityScope\n\nimport struct PackageGraph.ModulesGraph\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport func PackageGraph.loadModulesGraph\n\nimport class PackageModel.Manifest\nimport struct PackageModel.ProductDescription\nimport enum PackageModel.ProductType\nimport struct PackageModel.TargetDescription\nimport protocol TSCBasic.FileSystem\n\npackage typealias MockPackageGraph = (\n    graph: ModulesGraph,\n    fileSystem: any FileSystem,\n    observabilityScope: ObservabilityScope\n)\n\npackage func macrosPackageGraph() throws -> MockPackageGraph {\n    let fs = InMemoryFileSystem(emptyFiles:\n        \"/swift-firmware/Sources/Core/source.swift\",\n        \"/swift-firmware/Sources/HAL/source.swift\",\n        \"/swift-firmware/Tests/CoreTests/source.swift\",\n        \"/swift-firmware/Tests/HALTests/source.swift\",\n        \"/swift-mmio/Sources/MMIO/source.swift\",\n        \"/swift-mmio/Sources/MMIOMacros/source.swift\",\n        \"/swift-syntax/Sources/SwiftSyntax/source.swift\",\n        \"/swift-syntax/Tests/SwiftSyntaxTests/source.swift\"\n    )\n\n    let observability = ObservabilitySystem.makeForTesting()\n    let graph = try loadModulesGraph(\n        fileSystem: fs,\n        manifests: [\n            Manifest.createRootManifest(\n                displayName: \"swift-firmware\",\n                path: \"/swift-firmware\",\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/swift-mmio\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    )\n                ],\n                products: [\n                    ProductDescription(\n                        name: \"Core\",\n                        type: .executable,\n                        targets: [\"Core\"]\n                    )\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Core\",\n                        dependencies: [\"HAL\"],\n                        type: .executable\n                    ),\n                    TargetDescription(\n                        name: \"HAL\",\n                        dependencies: [.product(name: \"MMIO\", package: \"swift-mmio\")]\n                    ),\n                    TargetDescription(name: \"CoreTests\", dependencies: [\"Core\"], type: .test),\n                    TargetDescription(name: \"HALTests\", dependencies: [\"HAL\"], type: .test),\n                ],\n                traits: []\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"swift-mmio\",\n                path: \"/swift-mmio\",\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/swift-syntax\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    )\n                ],\n                products: [\n                    ProductDescription(\n                        name: \"MMIO\",\n                        type: .library(.automatic),\n                        targets: [\"MMIO\"]\n                    )\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"MMIO\",\n                        dependencies: [.target(name: \"MMIOMacros\")]\n                    ),\n                    TargetDescription(\n                        name: \"MMIOMacros\",\n                        dependencies: [.product(name: \"SwiftSyntax\", package: \"swift-syntax\")],\n                        type: .macro\n                    )\n                ],\n                traits: []\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"swift-syntax\",\n                path: \"/swift-syntax\",\n                products: [\n                    ProductDescription(\n                        name: \"SwiftSyntax\",\n                        type: .library(.automatic),\n                        targets: [\"SwiftSyntax\"]\n                    )\n                ],\n                targets: [\n                    TargetDescription(name: \"SwiftSyntax\", dependencies: []),\n                    TargetDescription(name: \"SwiftSyntaxTests\", dependencies: [\"SwiftSyntax\"], type: .test),\n                ],\n                traits: []\n            ),\n        ],\n        observabilityScope: observability.topScope,\n        traitConfiguration: .default,\n        enabledTraitsMap: .init()\n    )\n\n    XCTAssertNoDiagnostics(observability.diagnostics)\n\n    return (graph, fs, observability.topScope)\n}\n\npackage func macrosTestsPackageGraph() throws -> MockPackageGraph {\n    let fs = InMemoryFileSystem(emptyFiles:\n        \"/swift-mmio/Plugins/MMIOPlugin/source.swift\",\n        \"/swift-mmio/Sources/MMIO/source.swift\",\n        \"/swift-mmio/Sources/MMIOMacros/source.swift\",\n        \"/swift-mmio/Sources/MMIOMacrosTests/source.swift\",\n        \"/swift-mmio/Sources/MMIOMacro+PluginTests/source.swift\",\n        \"/swift-mmio/Sources/NOOPTests/source.swift\",\n        \"/swift-syntax/Sources/SwiftSyntax/source.swift\",\n        \"/swift-syntax/Sources/SwiftSyntaxMacrosTestSupport/source.swift\",\n        \"/swift-syntax/Sources/SwiftSyntaxMacros/source.swift\",\n        \"/swift-syntax/Sources/SwiftCompilerPlugin/source.swift\",\n        \"/swift-syntax/Sources/SwiftCompilerPluginMessageHandling/source.swift\",\n        \"/swift-syntax/Tests/SwiftSyntaxTests/source.swift\"\n    )\n\n    let observability = ObservabilitySystem.makeForTesting()\n    let graph = try loadModulesGraph(\n        fileSystem: fs,\n        manifests: [\n            Manifest.createRootManifest(\n                displayName: \"swift-mmio\",\n                path: \"/swift-mmio\",\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/swift-syntax\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    )\n                ],\n                products: [\n                    ProductDescription(\n                        name: \"MMIO\",\n                        type: .library(.automatic),\n                        targets: [\"MMIO\"]\n                    ),\n                    ProductDescription(\n                        name: \"MMIOPlugin\",\n                        type: .plugin,\n                        targets: [\"MMIOPlugin\"]\n                    )\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"MMIO\",\n                        dependencies: [.target(name: \"MMIOMacros\")]\n                    ),\n                    TargetDescription(\n                        name: \"MMIOMacros\",\n                        dependencies: [\n                            .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                            .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\"),\n                        ],\n                        type: .macro\n                    ),\n                    TargetDescription(\n                        name: \"MMIOPlugin\",\n                        type: .plugin,\n                        pluginCapability: .buildTool\n                    ),\n                    TargetDescription(\n                        name: \"MMIOMacrosTests\",\n                        dependencies: [\n                            .target(name: \"MMIOMacros\"),\n                            .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\")\n                        ],\n                        type: .test\n                    ),\n                    TargetDescription(\n                        name: \"MMIOMacro+PluginTests\",\n                        dependencies: [\n                            .target(name: \"MMIOPlugin\"),\n                            .target(name: \"MMIOMacros\")\n                        ],\n                        type: .test\n                    ),\n                    TargetDescription(\n                        name: \"NOOPTests\",\n                        dependencies: [],\n                        type: .test\n                    )\n                ],\n                traits: []\n            ),\n            Manifest.createRootManifest(\n                displayName: \"swift-syntax\",\n                path: \"/swift-syntax\",\n                products: [\n                    ProductDescription(\n                        name: \"SwiftSyntaxMacros\",\n                        type: .library(.automatic),\n                        targets: [\"SwiftSyntax\"]\n                    ),\n                    ProductDescription(\n                        name: \"SwiftSyntax\",\n                        type: .library(.automatic),\n                        targets: [\"SwiftSyntax\"]\n                    ),\n                    ProductDescription(\n                        name: \"SwiftSyntaxMacrosTestSupport\",\n                        type: .library(.automatic),\n                        targets: [\"SwiftSyntaxMacrosTestSupport\"]\n                    ),\n                    ProductDescription(\n                        name: \"SwiftCompilerPlugin\",\n                        type: .library(.automatic),\n                        targets: [\"SwiftCompilerPlugin\"]\n                    ),\n                    ProductDescription(\n                        name: \"SwiftCompilerPluginMessageHandling\",\n                        type: .library(.automatic),\n                        targets: [\"SwiftCompilerPluginMessageHandling\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"SwiftSyntax\",\n                        dependencies: []\n                    ),\n                    TargetDescription(\n                        name: \"SwiftSyntaxMacros\",\n                        dependencies: [.target(name: \"SwiftSyntax\")]\n                    ),\n                    TargetDescription(\n                        name: \"SwiftCompilerPlugin\",\n                        dependencies: [\n                            .target(name: \"SwiftCompilerPluginMessageHandling\"),\n                            .target(name: \"SwiftSyntaxMacros\"),\n                        ]\n                    ),\n                    TargetDescription(\n                        name: \"SwiftCompilerPluginMessageHandling\",\n                        dependencies: [\n                            .target(name: \"SwiftSyntax\"),\n                            .target(name: \"SwiftSyntaxMacros\"),\n                        ]\n                    ),\n                    TargetDescription(\n                        name: \"SwiftSyntaxMacrosTestSupport\",\n                        dependencies: [.target(name: \"SwiftSyntax\")]\n                    ),\n                    TargetDescription(\n                        name: \"SwiftSyntaxTests\",\n                        dependencies: [\"SwiftSyntax\"],\n                        type: .test\n                    ),\n                ],\n                traits: []\n            ),\n        ],\n        observabilityScope: observability.topScope,\n        traitConfiguration: .default,\n        enabledTraitsMap: .init()\n    )\n\n    XCTAssertNoDiagnostics(observability.diagnostics)\n\n    return (graph, fs, observability.topScope)\n}\n\npackage func trivialPackageGraph() throws -> MockPackageGraph {\n    let fs = InMemoryFileSystem(\n        emptyFiles:\n        \"/Pkg/Sources/app/main.swift\",\n        \"/Pkg/Sources/lib/lib.c\",\n        \"/Pkg/Sources/lib/include/lib.h\",\n        \"/Pkg/Tests/test/TestCase.swift\"\n    )\n\n    let observability = ObservabilitySystem.makeForTesting()\n    let graph = try loadModulesGraph(\n        fileSystem: fs,\n        manifests: [\n            Manifest.createRootManifest(\n                displayName: \"Pkg\",\n                path: \"/Pkg\",\n                targets: [\n                    TargetDescription(name: \"app\", dependencies: [\"lib\"]),\n                    TargetDescription(name: \"lib\", dependencies: []),\n                    TargetDescription(name: \"test\", dependencies: [\"lib\"], type: .test),\n                ],\n                traits: []\n            ),\n        ],\n        observabilityScope: observability.topScope,\n        traitConfiguration: .default,\n        enabledTraitsMap: .init()\n    )\n    XCTAssertNoDiagnostics(observability.diagnostics)\n\n    return (graph, fs, observability.topScope)\n}\n\npackage func embeddedCxxInteropPackageGraph() throws -> MockPackageGraph {\n    let fs = InMemoryFileSystem(\n        emptyFiles:\n        \"/Pkg/Sources/app/main.swift\",\n        \"/Pkg/Sources/lib/lib.cpp\",\n        \"/Pkg/Sources/lib/include/lib.h\",\n        \"/Pkg/Tests/test/TestCase.swift\"\n    )\n\n    let observability = ObservabilitySystem.makeForTesting()\n    let graph = try loadModulesGraph(\n        fileSystem: fs,\n        manifests: [\n            Manifest.createRootManifest(\n                displayName: \"Pkg\",\n                path: \"/Pkg\",\n                targets: [\n                    TargetDescription(\n                        name: \"app\",\n                        dependencies: [\"lib\"],\n                        settings: [.init(tool: .swift, kind: .enableExperimentalFeature(\"Embedded\"))]\n                    ),\n                    TargetDescription(\n                        name: \"lib\",\n                        dependencies: [],\n                        settings: [.init(tool: .swift, kind: .interoperabilityMode(.Cxx))]\n                    ),\n                    TargetDescription(\n                        name: \"test\",\n                        dependencies: [\"lib\"],\n                        type: .test\n                    ),\n                ],\n                traits: []\n            ),\n        ],\n        observabilityScope: observability.topScope,\n        traitConfiguration: .default,\n        enabledTraitsMap: .init()\n    )\n    XCTAssertNoDiagnostics(observability.diagnostics)\n\n    return (graph, fs, observability.topScope)\n}\n\npackage func toolsExplicitLibrariesGraph(linkage: ProductType.LibraryType) throws -> MockPackageGraph {\n    let fs = InMemoryFileSystem(emptyFiles:\n        \"/swift-mmio/Sources/MMIOMacros/source.swift\",\n        \"/swift-mmio/Sources/MMIOMacrosTests/source.swift\",\n        \"/swift-syntax/Sources/SwiftSyntax/source.swift\"\n    )\n\n    let observability = ObservabilitySystem.makeForTesting()\n    let graph = try loadModulesGraph(\n        fileSystem: fs,\n        manifests: [\n            Manifest.createRootManifest(\n                displayName: \"swift-mmio\",\n                path: \"/swift-mmio\",\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/swift-syntax\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    )\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"MMIOMacros\",\n                        dependencies: [\n                            .product(name: \"SwiftSyntax\", package: \"swift-syntax\"),\n                        ],\n                        type: .macro\n                    ),\n                    TargetDescription(\n                        name: \"MMIOMacrosTests\",\n                        dependencies: [\n                            .target(name: \"MMIOMacros\"),\n                        ],\n                        type: .test\n                    )\n                ],\n                traits: []\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"swift-syntax\",\n                path: \"/swift-syntax\",\n                products: [\n                    ProductDescription(\n                        name: \"SwiftSyntax\",\n                        type: .library(linkage),\n                        targets: [\"SwiftSyntax\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"SwiftSyntax\",\n                        dependencies: []\n                    ),\n                ],\n                traits: []\n            ),\n        ],\n        observabilityScope: observability.topScope,\n        traitConfiguration: .default,\n        enabledTraitsMap: .init()\n    )\n\n    XCTAssertNoDiagnostics(observability.diagnostics)\n\n    return (graph, fs, observability.topScope)\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockPackageSigningEntityStorage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Dispatch\nimport class Foundation.NSLock\nimport PackageModel\nimport PackageSigning\n\nimport struct TSCUtility.Version\n\npublic class MockPackageSigningEntityStorage: PackageSigningEntityStorage {\n    private var packageSigners: [PackageIdentity: PackageSigners]\n    private let lock = NSLock()\n\n    public init(_ packageSigners: [PackageIdentity: PackageSigners] = [:]) {\n        self.packageSigners = packageSigners\n    }\n    \n    public func get(\n        package: PackageIdentity,\n        observabilityScope: ObservabilityScope\n    ) throws -> PackageSigners {\n        guard let packageSigners = self.lock.withLock({ self.packageSigners[package] }) else {\n            return PackageSigners()\n        }\n        return packageSigners\n    }\n\n    public func put(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.lock.withLock {\n            let otherSigningEntities = self.packageSigners[package]?.signingEntities(of: version)\n                .filter { $0 != signingEntity } ?? []\n            // Error if we try to write a different signing entity for a version\n            guard otherSigningEntities.isEmpty else {\n                throw PackageSigningEntityStorageError.conflict(\n                    package: package,\n                    version: version,\n                    given: signingEntity,\n                    existing: otherSigningEntities.first! // !-safe because otherSigningEntities is not empty\n                )\n            }\n\n            try self.addSigner(\n                package: package,\n                signingEntity: signingEntity,\n                origin: origin,\n                version: version\n            )\n        }\n    }\n\n    public func add(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.lock.withLock {\n            try self.addSigner(\n                package: package,\n                signingEntity: signingEntity,\n                origin: origin,\n                version: version\n            )\n        }\n    }\n\n    public func changeSigningEntityFromVersion(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.lock.withLock {\n            self.setExpectedSigner(\n                package: package,\n                expectedSigningEntity: signingEntity,\n                expectedFromVersion: version\n            )\n            try self.addSigner(\n                package: package,\n                signingEntity: signingEntity,\n                origin: origin,\n                version: version\n            )\n        }\n    }\n\n    public func changeSigningEntityForAllVersions(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.lock.withLock {\n            self.setExpectedSigner(\n                package: package,\n                expectedSigningEntity: signingEntity,\n                expectedFromVersion: version\n            )\n            // Delete all other signers\n            if let existing = self.packageSigners[package] {\n                self.packageSigners[package] = PackageSigners(\n                    expectedSigner: existing.expectedSigner,\n                    signers: existing.signers.filter { $0.key == signingEntity }\n                )\n            }\n            try self.addSigner(\n                package: package,\n                signingEntity: signingEntity,\n                origin: origin,\n                version: version\n            )\n        }\n    }\n\n    private func setExpectedSigner(\n        package: PackageIdentity,\n        expectedSigningEntity: SigningEntity,\n        expectedFromVersion: Version\n    ) {\n        self.packageSigners[package] = PackageSigners(\n            expectedSigner: (signingEntity: expectedSigningEntity, fromVersion: expectedFromVersion),\n            signers: self.packageSigners[package]?.signers ?? [:]\n        )\n    }\n\n    private func addSigner(\n        package: PackageIdentity,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        version: Version\n    ) throws {\n        guard case .recognized = signingEntity else {\n            throw PackageSigningEntityStorageError.unrecognizedSigningEntity(signingEntity)\n        }\n\n        let packageSigners = self.packageSigners[package] ?? PackageSigners()\n\n        let packageSigner: PackageSigner\n        if let existingSigner = packageSigners.signers[signingEntity] {\n            var origins = existingSigner.origins\n            origins.insert(origin)\n            var versions = existingSigner.versions\n            versions.insert(version)\n            packageSigner = PackageSigner(\n                signingEntity: signingEntity,\n                origins: origins,\n                versions: versions\n            )\n        } else {\n            packageSigner = PackageSigner(\n                signingEntity: signingEntity,\n                origins: [origin],\n                versions: [version]\n            )\n        }\n\n        var signers = packageSigners.signers\n        signers[signingEntity] = packageSigner\n\n        self.packageSigners[package] = PackageSigners(\n            expectedSigner: packageSigners.expectedSigner,\n            signers: signers\n        )\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockProduct.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageModel\n\npublic struct MockProduct {\n    public let name: String\n    public let modules: [String]\n    public let type: ProductType?\n\n    public init(\n        name: String,\n        modules: [String],\n        type: ProductType? = nil\n    ) {\n        self.name = name\n        self.modules = modules\n        self.type = type\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockRegistry.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageFingerprint\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport PackageRegistry\nimport PackageSigning\n\nimport protocol TSCBasic.HashAlgorithm\n\nimport struct TSCUtility.Version\n\npublic class MockRegistry {\n    private let baseURL: URL\n    private let fileSystem: FileSystem\n    private let identityResolver: IdentityResolver\n    private let checksumAlgorithm: HashAlgorithm\n    public var registryClient: RegistryClient!\n    private let jsonEncoder: JSONEncoder\n\n    private var packageVersions = [PackageIdentity: [String: InMemoryRegistryPackageSource]]()\n    private var packagesSourceControlURLs = [PackageIdentity: [URL]]()\n    private var sourceControlURLs = [URL: PackageIdentity]()\n    private let packagesLock = NSLock()\n\n    public init(\n        filesystem: FileSystem,\n        identityResolver: IdentityResolver,\n        checksumAlgorithm: HashAlgorithm,\n        fingerprintStorage: PackageFingerprintStorage,\n        signingEntityStorage: PackageSigningEntityStorage,\n        customBaseURL: URL? = .none\n    ) {\n        self.fileSystem = filesystem\n        self.identityResolver = identityResolver\n        self.checksumAlgorithm = checksumAlgorithm\n        self.jsonEncoder = JSONEncoder.makeWithDefaults()\n\n        var configuration = RegistryConfiguration()\n        if let customBaseURL {\n            self.baseURL = customBaseURL\n\n        } else {\n            self.baseURL = URL(\"http://localhost/registry/mock\")\n        }\n        configuration.defaultRegistry = .init(url: self.baseURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        self.registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: .strict,\n            authorizationProvider: .none,\n            customHTTPClient: HTTPClient(implementation: self.httpHandler),\n            customArchiverProvider: { fileSystem in MockRegistryArchiver(fileSystem: fileSystem) },\n            delegate: .none,\n            checksumAlgorithm: checksumAlgorithm\n        )\n    }\n\n    public func addPackage(\n        identity: PackageIdentity,\n        versions: [Version],\n        sourceControlURLs: [URL]? = .none,\n        source: InMemoryRegistryPackageSource\n    ) {\n        self.addPackage(\n            identity: identity,\n            versions: versions.map(\\.description),\n            sourceControlURLs: sourceControlURLs,\n            source: source\n        )\n    }\n\n    public func addPackage(\n        identity: PackageIdentity,\n        versions: [String],\n        sourceControlURLs: [URL]? = .none,\n        source: InMemoryRegistryPackageSource\n    ) {\n        self.packagesLock.withLock {\n            // versions\n            var updatedVersions = self.packageVersions[identity] ?? [:]\n            for version in versions {\n                updatedVersions[version.description] = source\n            }\n            self.packageVersions[identity] = updatedVersions\n            // source control URLs\n            if let sourceControlURLs {\n                var packageSourceControlURLs = self.packagesSourceControlURLs[identity] ?? []\n                packageSourceControlURLs.append(contentsOf: sourceControlURLs)\n                self.packagesSourceControlURLs[identity] = packageSourceControlURLs\n                // reverse index\n                for sourceControlURL in sourceControlURLs {\n                    self.sourceControlURLs[sourceControlURL] = identity\n                }\n            }\n        }\n    }\n\n    @Sendable func httpHandler(\n        request: HTTPClient.Request,\n        progress: HTTPClient.ProgressHandler?\n    ) async throws -> HTTPClient.Response {\n        guard request.url.absoluteString.hasPrefix(self.baseURL.absoluteString) else {\n            throw StringError(\"url outside mock registry \\(self.baseURL)\")\n        }\n\n        switch request.kind {\n        case .generic:\n            let response = try self.handleRequest(request: request)\n            return response\n        case .download(let fileSystem, let destination):\n            let response = try self.handleDownloadRequest(\n                request: request,\n                progress: progress,\n                fileSystem: fileSystem,\n                destination: destination\n            )\n            return response\n        }\n    }\n\n    private func handleRequest(request: HTTPClient.Request) throws -> HTTPClient.Response {\n        let routeComponents = request.url.absoluteString.dropFirst(self.baseURL.absoluteString.count + 1)\n            .split(separator: \"/\")\n        switch routeComponents.count {\n        case _ where routeComponents[0].hasPrefix(\"identifiers?url=\"):\n            guard let query = request.url.query else {\n                throw StringError(\"invalid url: \\(request.url)\")\n            }\n            guard let sourceControlURL = URL(string: String(query.dropFirst(4))) else {\n                throw StringError(\"invalid url query: \\(query)\")\n            }\n            return try self.getIdentifiers(url: sourceControlURL)\n        case 2:\n            let package = PackageIdentity.plain(routeComponents.joined(separator: \".\"))\n            return try self.getPackageMetadata(packageIdentity: package)\n        case 3:\n            let package = PackageIdentity.plain(routeComponents[0 ... 1].joined(separator: \".\"))\n            let version = String(routeComponents[2])\n            return try self.getVersionMetadata(packageIdentity: package, version: version)\n        case 4 where routeComponents[3] == \"Package.swift\":\n            let package = PackageIdentity.plain(routeComponents[0 ... 1].joined(separator: \".\"))\n            let version = String(routeComponents[2])\n            guard let components = URLComponents(url: request.url, resolvingAgainstBaseURL: false) else {\n                throw StringError(\"invalid url: \\(request.url)\")\n            }\n            let toolsVersion = components.queryItems?.first(where: { $0.name == \"swift-version\" })?.value\n                .flatMap({ ToolsVersion(string: $0) })\n            return try self.getManifest(packageIdentity: package, version: version, toolsVersion: toolsVersion)\n        default:\n            throw StringError(\"unknown request \\(request.url)\")\n        }\n    }\n\n    private func getPackageMetadata(packageIdentity: PackageIdentity) throws -> HTTPClientResponse {\n        guard let registryIdentity = packageIdentity.registry else {\n            throw StringError(\"invalid package identifier '\\(packageIdentity)'\")\n        }\n\n        let versions = self.packageVersions[packageIdentity] ?? [:]\n        let metadata = RegistryClient.Serialization.PackageMetadata(\n            releases: versions.keys\n                .reduce(into: [String: RegistryClient.Serialization.PackageMetadata.Release]()) { partial, item in\n                    partial[item] =\n                        .init(\n                            url: \"\\(self.baseURL.absoluteString)/\\(registryIdentity.scope)/\\(registryIdentity.name)/\\(item)\"\n                        )\n                }\n        )\n\n        /*\n         <https://github.com/mona/LinkedList>; rel=\"canonical\",\n         <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\"\n         */\n        let sourceControlURLs = self.packagesSourceControlURLs[packageIdentity]\n        let links = sourceControlURLs?.map { url in\n            \"<\\(url.absoluteString)>; rel=alternate\"\n        }.joined(separator: \", \")\n\n        var headers = HTTPClientHeaders()\n        headers.add(name: \"Content-Version\", value: \"1\")\n        headers.add(name: \"Content-Type\", value: \"application/json\")\n        if let links {\n            headers.add(name: \"Link\", value: links)\n        }\n\n        return try HTTPClientResponse(\n            statusCode: 200,\n            headers: headers,\n            body: self.jsonEncoder.encode(metadata)\n        )\n    }\n\n    private func getVersionMetadata(packageIdentity: PackageIdentity, version: String) throws -> HTTPClientResponse {\n        guard let package = self.packageVersions[packageIdentity]?[version] else {\n            return .notFound()\n        }\n\n        let zipfileContent = try self.zipFileContent(\n            packageIdentity: packageIdentity,\n            version: version,\n            source: package\n        )\n        let zipfileChecksum = self.checksumAlgorithm.hash(zipfileContent)\n\n        let metadata = RegistryClient.Serialization.VersionMetadata(\n            id: packageIdentity.description,\n            version: version,\n            resources: [\n                .init(\n                    name: \"source-archive\",\n                    type: \"application/zip\",\n                    checksum: zipfileChecksum.hexadecimalRepresentation,\n                    signing: nil\n                ),\n            ],\n            metadata: .init(\n                description: \"\\(packageIdentity) description\",\n                readmeURL: \"http://\\(packageIdentity)/readme\"\n            ),\n            publishedAt: Date()\n        )\n\n        var headers = HTTPClientHeaders()\n        headers.add(name: \"Content-Version\", value: \"1\")\n        headers.add(name: \"Content-Type\", value: \"application/json\")\n\n        return try HTTPClientResponse(\n            statusCode: 200,\n            headers: headers,\n            body: self.jsonEncoder.encode(metadata)\n        )\n    }\n\n    private func getManifest(\n        packageIdentity: PackageIdentity,\n        version: String,\n        toolsVersion: ToolsVersion? = .none\n    ) throws -> HTTPClientResponse {\n        guard let package = self.packageVersions[packageIdentity]?[version] else {\n            return .notFound()\n        }\n\n        let filename: String\n        if let toolsVersion {\n            filename = Manifest.basename + \"@swift-\\(toolsVersion).swift\"\n        } else {\n            filename = Manifest.basename + \".swift\"\n        }\n\n        let content: Data = try package.fileSystem.readFileContents(package.path.appending(component: filename))\n\n        var headers = HTTPClientHeaders()\n        headers.add(name: \"Content-Version\", value: \"1\")\n        headers.add(name: \"Content-Type\", value: \"text/x-swift\")\n\n        return HTTPClientResponse(\n            statusCode: 200,\n            headers: headers,\n            body: content\n        )\n    }\n\n    private func getIdentifiers(url: URL) throws -> HTTPClientResponse {\n        let identifiers = self.sourceControlURLs[url].map { [$0.description] } ?? []\n\n        let packageIdentifiers = RegistryClient.Serialization.PackageIdentifiers(\n            identifiers: identifiers\n        )\n\n        var headers = HTTPClientHeaders()\n        headers.add(name: \"Content-Version\", value: \"1\")\n        headers.add(name: \"Content-Type\", value: \"application/json\")\n\n        return HTTPClientResponse(\n            statusCode: 200,\n            headers: headers,\n            body: try self.jsonEncoder.encode(packageIdentifiers)\n        )\n    }\n\n    private func handleDownloadRequest(\n        request: HTTPClient.Request,\n        progress: HTTPClient.ProgressHandler?,\n        fileSystem: FileSystem,\n        destination: AbsolutePath\n    ) throws -> HTTPClientResponse {\n        let routeComponents = request.url.absoluteString.dropFirst(self.baseURL.absoluteString.count + 1)\n            .split(separator: \"/\")\n        guard routeComponents.count == 3, routeComponents[2].hasSuffix(\".zip\") else {\n            throw StringError(\"invalid request \\(request.url), expecting zip suffix\")\n        }\n\n        let packageIdentity = PackageIdentity.plain(routeComponents[0 ... 1].joined(separator: \".\"))\n        let version = String(routeComponents[2].dropLast(4))\n\n        guard let package = self.packageVersions[packageIdentity]?[version] else {\n            return .notFound()\n        }\n\n        if !fileSystem.exists(destination.parentDirectory) {\n            try fileSystem.createDirectory(destination.parentDirectory, recursive: true)\n        }\n\n        let zipfileContent = try self.zipFileContent(\n            packageIdentity: packageIdentity,\n            version: version,\n            source: package\n        )\n        try fileSystem.writeFileContents(destination, string: zipfileContent)\n\n        var headers = HTTPClientHeaders()\n        headers.add(name: \"Content-Version\", value: \"1\")\n        headers.add(name: \"Content-Type\", value: \"application/zip\")\n\n        return HTTPClientResponse(\n            statusCode: 200,\n            headers: headers\n        )\n    }\n\n    private func zipFileContent(\n        packageIdentity: PackageIdentity,\n        version: String,\n        source: InMemoryRegistryPackageSource\n    ) throws -> String {\n        var content = \"\\(packageIdentity)_\\(version)\\n\"\n        content += source.path.pathString + \"\\n\"\n        for file in try source.listFiles() {\n            content += file.pathString + \"\\n\"\n        }\n        return content\n    }\n}\n\npublic struct InMemoryRegistryPackageSource {\n    let fileSystem: FileSystem\n    public let path: AbsolutePath\n\n    public init(fileSystem: FileSystem, path: AbsolutePath, writeContent: Bool = true) {\n        self.fileSystem = fileSystem\n        self.path = path\n    }\n\n    public func writePackageContent(targets: [String] = [], toolsVersion: ToolsVersion = .current) throws {\n        try self.fileSystem.createDirectory(self.path, recursive: true)\n        let sourcesDir = self.path.appending(\"Sources\")\n        for target in targets {\n            let targetDir = sourcesDir.appending(component: target)\n            try self.fileSystem.createDirectory(targetDir, recursive: true)\n            try self.fileSystem.writeFileContents(targetDir.appending(\"file.swift\"), bytes: \"\")\n        }\n        let manifestPath = self.path.appending(component: Manifest.filename)\n        try self.fileSystem.writeFileContents(manifestPath, string: \"// swift-tools-version:\\(toolsVersion)\")\n    }\n\n    public func listFiles(root: AbsolutePath? = .none) throws -> [AbsolutePath] {\n        var files = [AbsolutePath]()\n        let root = root ?? self.path\n        let entries = try self.fileSystem.getDirectoryContents(root)\n        for entry in entries.map({ root.appending(component: $0) }) {\n            if self.fileSystem.isDirectory(entry) {\n                let directoryFiles = try self.listFiles(root: entry)\n                files.append(contentsOf: directoryFiles)\n            } else if self.fileSystem.isFile(entry) {\n                files.append(entry)\n            } else {\n                throw StringError(\"invalid entry type\")\n            }\n        }\n        return files\n    }\n}\n\nprivate struct MockRegistryArchiver: Archiver {\n    let supportedExtensions = Set<String>([\"zip\"])\n    let fileSystem: FileSystem\n\n    init(fileSystem: FileSystem) {\n        self.fileSystem = fileSystem\n    }\n\n    func extract(\n        from archivePath: AbsolutePath,\n        to destinationPath: AbsolutePath,\n        completion: @escaping (Result<Void, Error>) -> Void\n    ) {\n        do {\n            let lines = try self.readFileContents(archivePath)\n            guard lines.count >= 2 else {\n                throw StringError(\"invalid mock zip format, not enough lines\")\n            }\n            let rootPath = lines[1]\n            for path in lines[2 ..< lines.count] {\n                let relativePath = String(path.dropFirst(rootPath.count + 1))\n                let targetPath = try AbsolutePath(\n                    validating: relativePath,\n                    relativeTo: destinationPath.appending(\"package\")\n                )\n                if !self.fileSystem.exists(targetPath.parentDirectory) {\n                    try self.fileSystem.createDirectory(targetPath.parentDirectory, recursive: true)\n                }\n                try self.fileSystem.copy(from: try AbsolutePath(validating: path), to: targetPath)\n            }\n            completion(.success(()))\n        } catch {\n            completion(.failure(error))\n        }\n    }\n\n    func compress(\n        directory: AbsolutePath,\n        to destinationPath: AbsolutePath\n    ) async throws {\n        fatalError(\"not implemented\")\n    }\n\n    func validate(path: AbsolutePath, completion: @escaping (Result<Bool, Error>) -> Void) {\n        do {\n            let lines = try self.readFileContents(path)\n            completion(.success(lines.count >= 2))\n        } catch {\n            completion(.failure(error))\n        }\n    }\n\n    private func readFileContents(_ path: AbsolutePath) throws -> [String] {\n        let content: String = try self.fileSystem.readFileContents(path)\n        return content.split(whereSeparator: { $0.isNewline }).map(String.init)\n    }\n}\n\nextension RegistryConfiguration.Security {\n    public static let testDefault: RegistryConfiguration.Security = {\n        var signing = RegistryConfiguration.Security.Signing()\n        signing.onUnsigned = .silentAllow\n        signing.onUntrustedCertificate = .silentAllow\n\n        var security = RegistryConfiguration.Security()\n        security.default.signing = signing\n        return security\n    }()\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockTarget.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageGraph\nimport PackageModel\n\npublic struct MockTarget {\n    public enum `Type` {\n        case regular, test, binary, macro, executable, plugin\n    }\n\n    public let name: String\n    public let dependencies: [TargetDescription.Dependency]\n    public let path: String?\n    public let url: String?\n    public let checksum: String?\n    public let packageAccess: Bool\n    public let settings: [TargetBuildSettingDescription.Setting]\n    public let type: Type\n    public let pluginCapability: TargetDescription.PluginCapability?\n\n    public init(\n        name: String,\n        dependencies: [TargetDescription.Dependency] = [],\n        type: Type = .regular,\n        pluginCapability: TargetDescription.PluginCapability? = nil,\n        path: String? = nil,\n        url: String? = nil,\n        packageAccess: Bool = true,\n        settings: [TargetBuildSettingDescription.Setting] = [],\n        checksum: String? = nil\n    ) throws {\n        self.name = name\n        self.dependencies = dependencies\n        self.type = type\n        self.pluginCapability = pluginCapability\n        self.path = path\n        self.url = url\n        self.packageAccess = packageAccess\n        self.settings = settings\n        self.checksum = checksum\n    }\n\n    func convert(identityResolver: IdentityResolver) throws -> TargetDescription {\n        switch self.type {\n        case .regular:\n            return try TargetDescription(\n                name: self.name,\n                dependencies: self.dependencies.map{ try $0.convert(identityResolver: identityResolver) },\n                path: self.path,\n                exclude: [],\n                sources: nil,\n                publicHeadersPath: nil,\n                type: .regular,\n                packageAccess: packageAccess,\n                settings: self.settings\n            )\n        case .test:\n            return try TargetDescription(\n                name: self.name,\n                dependencies: self.dependencies.map{ try $0.convert(identityResolver: identityResolver) },\n                path: self.path,\n                exclude: [],\n                sources: nil,\n                publicHeadersPath: nil,\n                type: .test,\n                packageAccess: packageAccess,\n                settings: self.settings\n            )\n        case .binary:\n            return try TargetDescription(\n                name: self.name,\n                dependencies: self.dependencies.map{ try $0.convert(identityResolver: identityResolver) },\n                path: self.path,\n                url: self.url,\n                exclude: [],\n                sources: nil,\n                publicHeadersPath: nil,\n                type: .binary,\n                packageAccess: packageAccess,\n                settings: [],\n                checksum: self.checksum\n            )\n        case .macro:\n            return try TargetDescription(\n                name: self.name,\n                dependencies: self.dependencies.map{ try $0.convert(identityResolver: identityResolver) },\n                path: self.path,\n                exclude: [],\n                sources: nil,\n                publicHeadersPath: nil,\n                type: .macro,\n                packageAccess: packageAccess,\n                settings: self.settings\n            )\n        case .executable:\n            return try TargetDescription(\n                name: self.name,\n                dependencies: self.dependencies.map{ try $0.convert(identityResolver: identityResolver) },\n                path: self.path,\n                exclude: [],\n                sources: nil,\n                publicHeadersPath: nil,\n                type: .executable,\n                packageAccess: packageAccess,\n                settings: self.settings\n            )\n        case .plugin:\n            return try TargetDescription(\n                name: self.name,\n                dependencies: self.dependencies.map{ try $0.convert(identityResolver: identityResolver) },\n                path: self.path,\n                exclude: [],\n                sources: nil,\n                publicHeadersPath: nil,\n                type: .plugin,\n                packageAccess: packageAccess,\n                pluginCapability: pluginCapability,\n                settings: self.settings,\n            )\n        }\n    }\n}\n\nextension TargetDescription.Dependency {\n    func convert(identityResolver: IdentityResolver) throws -> Self {\n        switch self {\n        case .product(let name, let package, let moduleAliases, let condition):\n            return .product(\n                name: name,\n                package: try package.flatMap { try identityResolver.mappedIdentity(for: .plain($0)).description },\n                moduleAliases: moduleAliases,\n                condition: condition\n            )\n        default:\n            return self\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/MockWorkspace.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Basics\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport PackageRegistry\nimport SourceControl\nimport Workspace\nimport XCTest\n\nimport struct TSCUtility.Version\nimport enum TSCBasic.JSON\n\nextension UserToolchain {\n    package static var mockTargetInfo: JSON {\n        JSON.dictionary([\n            \"compilerVersion\": .string(\"Apple Swift version 6.2-dev (LLVM 815013bbc318474, Swift 1459ecafa998782)\")\n        ])\n    }\n\n    package static func mockHostToolchain(\n        _ fileSystem: InMemoryFileSystem,\n        hostTriple: Triple = hostTriple\n    ) throws -> UserToolchain {\n        var hostSwiftSDK = try SwiftSDK.hostSwiftSDK(environment: .mockEnvironment, fileSystem: fileSystem)\n        hostSwiftSDK.targetTriple = hostTriple\n\n        let env = Environment.mockEnvironment\n\n        return try UserToolchain(\n            swiftSDK: hostSwiftSDK,\n            environment: env,\n            searchStrategy: .custom(\n                searchPaths: getEnvSearchPaths(\n                    pathString: env[.path],\n                    currentWorkingDirectory: fileSystem.currentWorkingDirectory\n                ),\n                useXcrun: true\n            ),\n            customTargetInfo: Self.mockTargetInfo,\n            fileSystem: fileSystem\n        )\n    }\n}\n\nextension Environment {\n    package static var mockEnvironment: Self { [\"PATH\": \"/fake/path/to\"] }\n}\n\nextension InMemoryFileSystem {\n    package func createMockToolchain() throws {\n        let files = [\n            \"/fake/path/to/swiftc\",\n            \"/fake/path/to/swiftc.exe\",\n            \"/fake/path/to/ar\",\n            \"/fake/path/to/ar.exe\",\n            \"/fake/path/to/libtool\",\n            \"/fake/path/to/libtool.exe\",\n            \"/fake/path/to/link.exe\",\n            \"/fake/path/to/lld-link.exe\",\n        ]\n        self.createEmptyFiles(at: AbsolutePath.root, files: files)\n        for toolPath in files {\n            try self.updatePermissions(.init(toolPath), isExecutable: true)\n        }\n    }\n}\n\npublic final class MockWorkspace {\n    let sandbox: AbsolutePath\n    let fileSystem: InMemoryFileSystem\n    let roots: [MockPackage]\n    let packages: [MockPackage]\n    let customToolsVersion: ToolsVersion?\n    private let customHostToolchain: UserToolchain\n    let fingerprints: MockPackageFingerprintStorage\n    let signingEntities: MockPackageSigningEntityStorage\n    let mirrors: DependencyMirrors\n    public var registryClient: RegistryClient\n    let registry: MockRegistry\n    let customBinaryArtifactsManager: Workspace.CustomBinaryArtifactsManager\n    let customPrebuiltsManager: Workspace.CustomPrebuiltsManager?\n    public var checksumAlgorithm: MockHashAlgorithm\n    public private(set) var manifestLoader: MockManifestLoader\n    public let repositoryProvider: InMemoryGitRepositoryProvider\n    let identityResolver: IdentityResolver\n    let customPackageContainerProvider: MockPackageContainerProvider?\n    public let delegate = MockWorkspaceDelegate()\n    let skipDependenciesUpdates: Bool\n    public var sourceControlToRegistryDependencyTransformation: WorkspaceConfiguration\n        .SourceControlToRegistryDependencyTransformation\n    var defaultRegistry: Registry?\n    public let traitConfiguration: TraitConfiguration\n    public var enabledTraitsMap: EnabledTraitsMap\n    public let pruneDependencies: Bool\n\n    public init(\n        sandbox: AbsolutePath,\n        fileSystem: InMemoryFileSystem,\n        roots: [MockPackage],\n        packages: [MockPackage] = [],\n        toolsVersion customToolsVersion: ToolsVersion? = .none,\n        fingerprints customFingerprints: MockPackageFingerprintStorage? = .none,\n        signingEntities customSigningEntities: MockPackageSigningEntityStorage? = .none,\n        mirrors customMirrors: DependencyMirrors? = nil,\n        registryClient customRegistryClient: RegistryClient? = .none,\n        binaryArtifactsManager customBinaryArtifactsManager: Workspace.CustomBinaryArtifactsManager? = .none,\n        prebuiltsManager customPrebuiltsManager: Workspace.CustomPrebuiltsManager? = .none,\n        checksumAlgorithm customChecksumAlgorithm: MockHashAlgorithm? = .none,\n        customPackageContainerProvider: MockPackageContainerProvider? = .none,\n        skipDependenciesUpdates: Bool = false,\n        sourceControlToRegistryDependencyTransformation: WorkspaceConfiguration\n            .SourceControlToRegistryDependencyTransformation = .disabled,\n        defaultRegistry: Registry? = .none,\n        customHostTriple: Triple = hostTriple,\n        traitConfiguration: TraitConfiguration = .default,\n        pruneDependencies: Bool = false,\n        enabledTraitsMap: EnabledTraitsMap = .init()\n    ) async throws {\n        try fileSystem.createMockToolchain()\n\n        self.sandbox = sandbox\n        self.fileSystem = fileSystem\n        self.roots = roots\n        self.packages = packages\n        self.fingerprints = customFingerprints ?? MockPackageFingerprintStorage()\n        self.signingEntities = customSigningEntities ?? MockPackageSigningEntityStorage()\n        self.mirrors = try customMirrors ?? DependencyMirrors()\n        self.identityResolver = DefaultIdentityResolver(\n            locationMapper: self.mirrors.effective(for:),\n            identityMapper: self.mirrors.effectiveIdentity(for:)\n        )\n        self.manifestLoader = MockManifestLoader(manifests: [:])\n        self.customPackageContainerProvider = customPackageContainerProvider\n        self.repositoryProvider = InMemoryGitRepositoryProvider()\n        self.checksumAlgorithm = customChecksumAlgorithm ?? MockHashAlgorithm()\n        self.registry = MockRegistry(\n            filesystem: self.fileSystem,\n            identityResolver: self.identityResolver,\n            checksumAlgorithm: self.checksumAlgorithm,\n            fingerprintStorage: self.fingerprints,\n            signingEntityStorage: self.signingEntities\n        )\n        self.registryClient = customRegistryClient ?? self.registry.registryClient\n        self.customToolsVersion = customToolsVersion\n        self.skipDependenciesUpdates = skipDependenciesUpdates\n        self.sourceControlToRegistryDependencyTransformation = sourceControlToRegistryDependencyTransformation\n        self.defaultRegistry = defaultRegistry\n        self.customBinaryArtifactsManager = customBinaryArtifactsManager ?? .init(\n            httpClient: HTTPClient.mock(fileSystem: fileSystem),\n            archiver: MockArchiver()\n        )\n        self.customPrebuiltsManager = customPrebuiltsManager\n        self.customHostToolchain = try UserToolchain.mockHostToolchain(fileSystem, hostTriple: customHostTriple)\n        self.traitConfiguration = traitConfiguration\n        self.pruneDependencies = pruneDependencies\n        self.enabledTraitsMap = enabledTraitsMap\n        try await self.create()\n    }\n\n    public var rootsDir: AbsolutePath {\n        self.sandbox.appending(\"roots\")\n    }\n\n    public var packagesDir: AbsolutePath {\n        self.sandbox.appending(\"pkgs\")\n    }\n\n    public var artifactsDir: AbsolutePath {\n        self.sandbox.appending(components: \".build\", \"artifacts\")\n    }\n\n    public var workspaceLocation: Workspace.Location? {\n        self._workspace?.location\n    }\n\n    public func pathToRoot(withName name: String) throws -> AbsolutePath {\n        try AbsolutePath(validating: name, relativeTo: self.rootsDir)\n    }\n\n    public func pathToPackage(withName name: String) throws -> AbsolutePath {\n        try AbsolutePath(validating: name, relativeTo: self.packagesDir)\n    }\n\n    private func create() async throws {\n        // Remove the sandbox if present.\n        if self.fileSystem.exists(self.sandbox) {\n            try self.fileSystem.removeFileTree(self.sandbox)\n        }\n\n        // Create directories.\n        try self.fileSystem.createDirectory(self.sandbox, recursive: true)\n        try self.fileSystem.createDirectory(self.rootsDir, recursive: true)\n        try self.fileSystem.createDirectory(self.packagesDir, recursive: true)\n\n        var manifests: [MockManifestLoader.Key: Manifest] = [:]\n\n        func create(package: MockPackage, basePath: AbsolutePath, isRoot: Bool) async throws {\n            let packagePath: AbsolutePath\n            switch package.location {\n            case .fileSystem(let path):\n                packagePath = basePath.appending(path)\n            case .sourceControl(let url):\n                if let containerProvider = customPackageContainerProvider {\n                    let observability = ObservabilitySystem.makeForTesting()\n                    let packageRef = PackageReference(\n                        identity: PackageIdentity(url: url),\n                        kind: .remoteSourceControl(url)\n                    )\n                    let container = try await containerProvider.getContainer(\n                        for: packageRef,\n                        updateStrategy: .never,\n                        observabilityScope: observability.topScope\n                    )\n                    guard let customContainer = container as? CustomPackageContainer else {\n                        throw StringError(\"invalid custom container: \\(container)\")\n                    }\n                    packagePath = try customContainer.retrieve(\n                        at: Version(versionString: package.versions.first!!),\n                        observabilityScope: observability.topScope\n                    )\n                } else {\n                    packagePath = basePath.appending(\n                        components: \"sourceControl\",\n                        url.absoluteString.spm_mangledToC99ExtendedIdentifier()\n                    )\n                }\n            case .registry(let identity, _, let metadata):\n                packagePath = basePath.appending(\n                    components: \"registry\",\n                    identity.description.spm_mangledToC99ExtendedIdentifier()\n                )\n\n                // Write registry release metadata if the mock package provided it.\n                if let metadata {\n                    try self.fileSystem.createDirectory(packagePath, recursive: true)\n                    let path = packagePath.appending(component: RegistryReleaseMetadataStorage.fileName)\n                    try RegistryReleaseMetadataStorage.save(metadata, to: path, fileSystem: self.fileSystem)\n                }\n            }\n\n            let packageLocation: String\n            let packageKind: PackageReference.Kind\n            let packageVersions: [String?] = isRoot ? [nil] : package.versions\n\n            var sourceControlSpecifier: RepositorySpecifier? = nil\n            var registryIdentity: PackageIdentity? = nil\n            var registryAlternativeURLs: [URL]? = nil\n\n            switch (isRoot, package.location) {\n            case (true, _):\n                packageLocation = packagePath.pathString\n                packageKind = .root(packagePath)\n                sourceControlSpecifier = RepositorySpecifier(path: packagePath)\n            case (_, .fileSystem(let path)):\n                packageLocation = self.packagesDir.appending(path).pathString\n                packageKind = .fileSystem(packagePath)\n                sourceControlSpecifier = RepositorySpecifier(path: self.packagesDir.appending(path))\n            case (_, .sourceControl(let url)):\n                packageLocation = url.absoluteString\n                packageKind = .remoteSourceControl(url)\n                sourceControlSpecifier = RepositorySpecifier(url: url)\n            case (_, .registry(let identity, let alternativeURLs, _)):\n                packageLocation = identity.description\n                packageKind = .registry(identity)\n                registryIdentity = identity\n                registryAlternativeURLs = alternativeURLs\n            }\n\n            // Create modules on disk.\n            let packageToolsVersion = package.toolsVersion ?? .current\n            if let specifier = sourceControlSpecifier {\n                let repository = self.repositoryProvider.specifierMap[specifier] ?? .init(\n                    path: packagePath,\n                    fs: self.fileSystem\n                )\n                try writePackageContent(fileSystem: repository, root: .root, toolsVersion: packageToolsVersion)\n\n                let versions = packageVersions.compactMap { $0 }\n                if versions.isEmpty {\n                    try repository.commit()\n                } else {\n                    for version in versions {\n                        try repository.commit(hash: package.revisionProvider.map { $0(version) })\n                        try repository.tag(name: version)\n                    }\n                }\n\n                self.repositoryProvider.add(specifier: specifier, repository: repository)\n            } else if let identity = registryIdentity {\n                let source = InMemoryRegistryPackageSource(\n                    fileSystem: self.fileSystem,\n                    path: packagePath,\n                    writeContent: false\n                )\n                try writePackageContent(\n                    fileSystem: source.fileSystem,\n                    root: source.path,\n                    toolsVersion: packageToolsVersion\n                )\n                self.registry.addPackage(\n                    identity: identity,\n                    versions: packageVersions.compactMap { $0 },\n                    sourceControlURLs: registryAlternativeURLs ?? [],\n                    source: source\n                )\n            } else {\n                throw InternalError(\"unknown package type\")\n            }\n\n            for version in packageVersions {\n                let v = version.flatMap(Version.init(_:))\n                manifests[.init(url: packageLocation, version: v)] = try Manifest.createManifest(\n                    displayName: package.name,\n                    path: packagePath,\n                    packageKind: packageKind,\n                    packageIdentity: .plain(package.name.lowercased()),\n                    packageLocation: packageLocation,\n                    platforms: package.platforms,\n                    version: v,\n                    toolsVersion: packageToolsVersion,\n                    dependencies: package.dependencies.map { try $0.convert(\n                        baseURL: self.packagesDir,\n                        identityResolver: self.identityResolver\n                    ) },\n                    products: package.products.map { try ProductDescription(\n                        name: $0.name,\n                        type: $0.type ?? .library(.automatic),\n                        targets: $0.modules\n                    ) },\n                    targets: package.targets.map { try $0.convert(identityResolver: self.identityResolver) },\n                    traits: package.traits,\n                    pruneDependencies: self.pruneDependencies\n                )\n            }\n\n            func writePackageContent(fileSystem: FileSystem, root: AbsolutePath, toolsVersion: ToolsVersion) throws {\n                let sourcesDir = root.appending(\"Sources\")\n                let pluginsDir = root.appending(\"Plugins\")\n                for target in package.targets {\n                    let targetDir = (target.type == .plugin ? pluginsDir : sourcesDir).appending(component: target.name)\n                    try fileSystem.createDirectory(targetDir, recursive: true)\n                    try fileSystem.writeFileContents(targetDir.appending(\"file.swift\"), bytes: \"\")\n                }\n                let manifestPath = root.appending(component: Manifest.filename)\n                try fileSystem.writeFileContents(manifestPath, bytes: \"\")\n                try ToolsVersionSpecificationWriter.rewriteSpecification(\n                    manifestDirectory: root,\n                    toolsVersion: toolsVersion,\n                    fileSystem: fileSystem\n                )\n            }\n        }\n\n        // Create root packages.\n        for package in self.roots {\n            try await create(package: package, basePath: self.rootsDir, isRoot: true)\n        }\n\n        // Create dependency packages.\n        for package in self.packages {\n            try await create(package: package, basePath: self.packagesDir, isRoot: false)\n        }\n\n        self.manifestLoader = MockManifestLoader(manifests: manifests)\n    }\n\n    public func getOrCreateWorkspace() throws -> Workspace {\n        if let workspace = self._workspace {\n            return workspace\n        }\n\n        let workspace = try Workspace._init(\n            fileSystem: self.fileSystem,\n            environment: .mockEnvironment,\n            location: .init(\n                scratchDirectory: self.sandbox.appending(\".build\"),\n                editsDirectory: self.sandbox.appending(\"edits\"),\n                resolvedVersionsFile: Workspace.DefaultLocations.resolvedVersionsFile(forRootPackage: self.sandbox),\n                localConfigurationDirectory: Workspace.DefaultLocations\n                    .configurationDirectory(forRootPackage: self.sandbox),\n                sharedConfigurationDirectory: self.fileSystem.swiftPMConfigurationDirectory,\n                sharedSecurityDirectory: self.fileSystem.swiftPMSecurityDirectory,\n                sharedCacheDirectory: self.fileSystem.swiftPMCacheDirectory\n            ),\n            configuration: .init(\n                skipDependenciesUpdates: self.skipDependenciesUpdates,\n                prefetchBasedOnResolvedFile: WorkspaceConfiguration.default.prefetchBasedOnResolvedFile,\n                shouldCreateMultipleTestProducts: WorkspaceConfiguration.default.shouldCreateMultipleTestProducts,\n                createREPLProduct: WorkspaceConfiguration.default.createREPLProduct,\n                additionalFileRules: WorkspaceConfiguration.default.additionalFileRules,\n                sharedDependenciesCacheEnabled: WorkspaceConfiguration.default.sharedDependenciesCacheEnabled,\n                fingerprintCheckingMode: .strict,\n                signingEntityCheckingMode: .strict,\n                skipSignatureValidation: false,\n                sourceControlToRegistryDependencyTransformation: self.sourceControlToRegistryDependencyTransformation,\n                defaultRegistry: self.defaultRegistry,\n                manifestImportRestrictions: .none,\n                usePrebuilts: self.customPrebuiltsManager != nil,\n                prebuiltsDownloadURL: nil,\n                prebuiltsRootCertPath: nil,\n                pruneDependencies: self.pruneDependencies,\n                traitConfiguration: self.traitConfiguration\n            ),\n            customFingerprints: self.fingerprints,\n            customMirrors: self.mirrors,\n            customToolsVersion: self.customToolsVersion,\n            customHostToolchain: self.customHostToolchain,\n            customManifestLoader: self.manifestLoader,\n            customPackageContainerProvider: self.customPackageContainerProvider,\n            customRepositoryProvider: self.repositoryProvider,\n            customRegistryClient: self.registryClient,\n            customBinaryArtifactsManager: self.customBinaryArtifactsManager,\n            customPrebuiltsManager: self.customPrebuiltsManager,\n            customIdentityResolver: self.identityResolver,\n            customChecksumAlgorithm: self.checksumAlgorithm,\n            delegate: self.delegate\n        )\n\n        self._workspace = workspace\n\n        return workspace\n    }\n\n    private var _workspace: Workspace?\n\n    public func closeWorkspace(resetState: Bool = true, resetResolvedFile: Bool = true) async throws {\n        if resetState {\n            try await self._workspace?.resetState()\n        }\n        if resetResolvedFile {\n            try self._workspace.map {\n                try self.fileSystem.removeFileTree($0.location.resolvedVersionsFile)\n            }\n        }\n        self._workspace = nil\n    }\n\n    public func rootPaths(for packages: [String]) throws -> [AbsolutePath] {\n        try packages.map { try AbsolutePath(validating: $0, relativeTo: self.rootsDir) }\n    }\n\n    public func checkEdit(\n        packageIdentity: String,\n        path: AbsolutePath? = nil,\n        revision: Revision? = nil,\n        checkoutBranch: String? = nil,\n        _ result: ([Basics.Diagnostic]) -> Void\n    ) async {\n        let observability = ObservabilitySystem.makeForTesting()\n        await observability.topScope.trap {\n            let ws = try self.getOrCreateWorkspace()\n            await ws.edit(\n                packageIdentity: packageIdentity,\n                path: path,\n                revision: revision,\n                checkoutBranch: checkoutBranch,\n                observabilityScope: observability.topScope\n            )\n        }\n        result(observability.diagnostics)\n    }\n\n    public func checkUnedit(\n        packageIdentity: String,\n        roots: [String],\n        forceRemove: Bool = false,\n        _ result: ([Basics.Diagnostic]) -> Void\n    ) async {\n        let observability = ObservabilitySystem.makeForTesting()\n        await observability.topScope.trap {\n            let rootInput = try PackageGraphRootInput(\n                packages: rootPaths(for: roots),\n                traitConfiguration: traitConfiguration\n            )\n            let ws = try self.getOrCreateWorkspace()\n            try await ws.unedit(\n                packageIdentity: packageIdentity,\n                forceRemove: forceRemove,\n                root: rootInput,\n                observabilityScope: observability.topScope\n            )\n        }\n        result(observability.diagnostics)\n    }\n\n    public func checkResolve(\n        pkg: String,\n        roots: [String],\n        version: TSCUtility.Version,\n        _ result: ([Basics.Diagnostic]) -> Void\n    ) async {\n        let observability = ObservabilitySystem.makeForTesting()\n        await observability.topScope.trap {\n            let rootInput = try PackageGraphRootInput(\n                packages: rootPaths(for: roots),\n                traitConfiguration: traitConfiguration\n            )\n            let workspace = try self.getOrCreateWorkspace()\n            try await workspace.resolve(\n                packageName: pkg,\n                root: rootInput,\n                version: version,\n                branch: nil,\n                revision: nil,\n                observabilityScope: observability.topScope\n            )\n        }\n        result(observability.diagnostics)\n    }\n\n    public func checkClean(_ result: ([Basics.Diagnostic]) -> Void) {\n        let observability = ObservabilitySystem.makeForTesting()\n        observability.topScope.trap {\n            let workspace = try self.getOrCreateWorkspace()\n            workspace.clean(observabilityScope: observability.topScope)\n        }\n        result(observability.diagnostics)\n    }\n\n    public func checkReset(_ result: ([Basics.Diagnostic]) -> Void) async {\n        let observability = ObservabilitySystem.makeForTesting()\n        await observability.topScope.trap {\n            let workspace = try self.getOrCreateWorkspace()\n            await workspace.reset(observabilityScope: observability.topScope)\n        }\n        result(observability.diagnostics)\n    }\n\n    public func checkUpdate(\n        roots: [String] = [],\n        deps: [MockDependency] = [],\n        packages: [String] = [],\n        _ result: ([Basics.Diagnostic]) -> Void\n    ) async throws {\n        let dependencies = try deps.map { try $0.convert(\n            baseURL: self.packagesDir,\n            identityResolver: self.identityResolver\n        ) }\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await observability.topScope.trap {\n            let rootInput = try PackageGraphRootInput(\n                packages: rootPaths(for: roots),\n                dependencies: dependencies,\n                traitConfiguration: traitConfiguration\n            )\n            let workspace = try self.getOrCreateWorkspace()\n            try await workspace.updateDependencies(\n                root: rootInput,\n                packages: packages,\n                observabilityScope: observability.topScope\n            )\n        }\n        result(observability.diagnostics)\n    }\n\n    public func checkUpdateDryRun(\n        roots: [String] = [],\n        deps: [MockDependency] = [],\n        _ result: ([(PackageReference, Workspace.PackageStateChange)]?, [Basics.Diagnostic]) -> Void\n    ) async throws {\n        let dependencies = try deps.map { try $0.convert(\n            baseURL: self.packagesDir,\n            identityResolver: self.identityResolver\n        ) }\n        let rootInput = try PackageGraphRootInput(\n            packages: rootPaths(for: roots),\n            dependencies: dependencies,\n            traitConfiguration: traitConfiguration\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let changes = await observability.topScope.trap { () -> [(PackageReference, Workspace.PackageStateChange)]? in\n            let workspace = try self.getOrCreateWorkspace()\n            return try await workspace.updateDependencies(\n                root: rootInput,\n                dryRun: true,\n                observabilityScope: observability.topScope\n            )\n        } ?? nil\n        result(changes, observability.diagnostics)\n    }\n\n    public func checkPackageGraph(\n        roots: [String] = [],\n        deps: [MockDependency],\n        _ result: (ModulesGraph, [Basics.Diagnostic]) throws -> Void\n    ) async throws {\n        let dependencies = try deps.map { try $0.convert(\n            baseURL: self.packagesDir,\n            identityResolver: self.identityResolver\n        ) }\n        try await self.checkPackageGraph(roots: roots, dependencies: dependencies, result)\n    }\n\n    public func checkPackageGraph(\n        roots: [String] = [],\n        dependencies: [PackageDependency] = [],\n        forceResolvedVersions: Bool = false,\n        expectedSigningEntities: [PackageIdentity: RegistryReleaseMetadata.SigningEntity] = [:],\n        _ result: (ModulesGraph, [Basics.Diagnostic]) throws -> Void\n    ) async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let rootInput = try PackageGraphRootInput(\n            packages: rootPaths(for: roots), dependencies: dependencies, traitConfiguration: traitConfiguration\n        )\n        let workspace = try self.getOrCreateWorkspace()\n        do {\n            let graph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                forceResolvedVersions: forceResolvedVersions,\n                expectedSigningEntities: expectedSigningEntities,\n                observabilityScope: observability.topScope\n            )\n            try result(graph, observability.diagnostics)\n        } catch {\n            // helpful when graph fails to load\n            if observability.hasErrorDiagnostics {\n                print(observability.diagnostics.map(\\.description).joined(separator: \"\\n\"))\n            }\n            throw error\n        }\n    }\n\n    public func checkPackageGraphFailure(\n        roots: [String] = [],\n        deps: [MockDependency],\n        _ result: ([Basics.Diagnostic]) -> Void\n    ) async throws {\n        let dependencies = try deps.map { try $0.convert(\n            baseURL: self.packagesDir,\n            identityResolver: self.identityResolver\n        ) }\n        await self.checkPackageGraphFailure(roots: roots, dependencies: dependencies, result)\n    }\n\n    public func checkPackageGraphFailure(\n        roots: [String] = [],\n        dependencies: [PackageDependency] = [],\n        forceResolvedVersions: Bool = false,\n        _ result: ([Basics.Diagnostic]) -> Void\n    ) async {\n        let observability = ObservabilitySystem.makeForTesting()\n        await observability.topScope.trap {\n            let rootInput = try PackageGraphRootInput(\n                packages: rootPaths(for: roots),\n                dependencies: dependencies,\n                traitConfiguration: traitConfiguration\n            )\n            let workspace = try self.getOrCreateWorkspace()\n            try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                forceResolvedVersions: forceResolvedVersions,\n                observabilityScope: observability.topScope\n            )\n        }\n        result(observability.diagnostics)\n    }\n\n    public struct ResolutionPrecomputationResult {\n        public let result: Workspace.ResolutionPrecomputationResult\n        public let diagnostics: [Basics.Diagnostic]\n    }\n\n    public func checkPrecomputeResolution() async throws -> ResolutionPrecomputationResult {\n        let observability = ObservabilitySystem.makeForTesting()\n        let workspace = try self.getOrCreateWorkspace()\n        let resolvedPackagesStore = try workspace.resolvedPackagesStore.load()\n\n        let rootInput = try PackageGraphRootInput(\n            packages: rootPaths(for: roots.map(\\.name)),\n            dependencies: [],\n            traitConfiguration: self.traitConfiguration\n        )\n        let rootManifests = try await workspace.loadRootManifests(\n            packages: rootInput.packages,\n            observabilityScope: observability.topScope\n        )\n        let root = try PackageGraphRoot(\n            input: rootInput,\n            manifests: rootManifests,\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: workspace.enabledTraitsMap\n        )\n\n        let dependencyManifests = try await workspace.loadDependencyManifests(\n            root: root,\n            observabilityScope: observability.topScope\n        )\n\n        let result = try await workspace.precomputeResolution(\n            root: root,\n            dependencyManifests: dependencyManifests,\n            resolvedPackagesStore: resolvedPackagesStore,\n            constraints: [],\n            observabilityScope: observability.topScope\n        )\n\n        return ResolutionPrecomputationResult(result: result, diagnostics: observability.diagnostics)\n    }\n\n    public func set(\n        resolvedPackages: [PackageReference: CheckoutState] = [:],\n        managedDependencies: [AbsolutePath: Workspace.ManagedDependency] = [:],\n        managedArtifacts: [Workspace.ManagedArtifact] = []\n    ) async throws {\n        let resolvedPackages = resolvedPackages.mapValues { checkoutState -> ResolvedPackagesStore.ResolutionState in\n            switch checkoutState {\n            case .version(let version, let revision):\n                return .version(version, revision: revision.identifier)\n            case .branch(let name, let revision):\n                return .branch(name: name, revision: revision.identifier)\n            case .revision(let revision):\n                return .revision(revision.identifier)\n            }\n        }\n        try await self.set(\n            resolvedPackages: resolvedPackages,\n            managedDependencies: managedDependencies,\n            managedArtifacts: managedArtifacts\n        )\n    }\n\n    public func set(\n        resolvedPackages: [PackageReference: ResolvedPackagesStore.ResolutionState],\n        managedDependencies: [AbsolutePath: Workspace.ManagedDependency] = [:],\n        managedArtifacts: [Workspace.ManagedArtifact] = []\n    ) async throws {\n        let workspace = try self.getOrCreateWorkspace()\n        let resolvedPackagesStore = try workspace.resolvedPackagesStore.load()\n\n        for (ref, state) in resolvedPackages {\n            resolvedPackagesStore.track(packageRef: ref, state: state)\n        }\n\n        for dependency in managedDependencies {\n            // copy the package content to expected managed path\n            let managedPath = workspace.path(to: dependency.value)\n            if managedPath != dependency.key, self.fileSystem.exists(dependency.key) {\n                try self.fileSystem.createDirectory(managedPath.parentDirectory, recursive: true)\n                try self.fileSystem.copy(from: dependency.key, to: managedPath)\n            } else {\n                try self.fileSystem.createDirectory(managedPath, recursive: true)\n            }\n            await workspace.state.add(dependency: dependency.value)\n        }\n\n        for artifact in managedArtifacts {\n            // create an empty directory representing the artifact\n            try self.fileSystem.createDirectory(artifact.path, recursive: true)\n            await workspace.state.artifacts.add(artifact)\n        }\n\n        try await workspace.state.save()\n    }\n\n    public func resetState() async throws {\n        let workspace = try self.getOrCreateWorkspace()\n        try await workspace.resetState()\n    }\n\n    public enum State {\n        public enum CheckoutState {\n            case version(TSCUtility.Version)\n            case revision(String)\n            case branch(String)\n        }\n\n        case checkout(CheckoutState)\n        case registryDownload(TSCUtility.Version)\n        case edited(AbsolutePath?)\n        case local\n        case custom(TSCUtility.Version, AbsolutePath)\n    }\n\n    public struct ManagedDependencyResult {\n        public let managedDependencies: Workspace.ManagedDependencies\n\n        public init(_ managedDependencies: Workspace.ManagedDependencies) {\n            self.managedDependencies = managedDependencies\n        }\n\n        public func check(notPresent name: String, file: StaticString = #file, line: UInt = #line) {\n            self.check(notPresent: .plain(name), file: file, line: line)\n        }\n\n        public func check(notPresent dependencyId: PackageIdentity, file: StaticString = #file, line: UInt = #line) {\n            let dependency = self.managedDependencies[dependencyId]\n            XCTAssertNil(\n                dependency,\n                \"Unexpectedly found \\(dependencyId) in managed dependencies\",\n                file: file,\n                line: line\n            )\n        }\n\n        public func checkEmpty(file: StaticString = #file, line: UInt = #line) {\n            XCTAssertEqual(self.managedDependencies.count, 0, file: file, line: line)\n        }\n\n        public func check(dependency name: String, at state: State, file: StaticString = #file, line: UInt = #line) {\n            self.check(dependency: .plain(name), at: state, file: file, line: line)\n        }\n\n        public func check(\n            dependency dependencyId: PackageIdentity,\n            at state: State,\n            file: StaticString = #file,\n            line: UInt = #line\n        ) {\n            guard let dependency = managedDependencies[dependencyId] else {\n                return XCTFail(\"\\(dependencyId) does not exists\", file: file, line: line)\n            }\n            switch state {\n            case .checkout(let checkoutState):\n                guard case .sourceControlCheckout(let dependencyCheckoutState) = dependency.state else {\n                    return XCTFail(\"invalid dependency state \\(dependency.state)\", file: file, line: line)\n                }\n                switch checkoutState {\n                case .version(let version):\n                    XCTAssertEqual(dependencyCheckoutState.version, version, file: file, line: line)\n                case .revision(let revision):\n                    XCTAssertEqual(dependencyCheckoutState.revision.identifier, revision, file: file, line: line)\n                case .branch(let branch):\n                    XCTAssertEqual(dependencyCheckoutState.branch, branch, file: file, line: line)\n                }\n            case .registryDownload(let downloadVersion):\n                guard case .registryDownload(let dependencyVersion) = dependency.state else {\n                    return XCTFail(\"invalid dependency state \\(dependency.state)\", file: file, line: line)\n                }\n                XCTAssertEqual(dependencyVersion, downloadVersion, file: file, line: line)\n            case .edited(let path):\n                guard case .edited(_, unmanagedPath: path) = dependency.state else {\n                    XCTFail(\"Expected edited dependency; found '\\(dependency.state)' instead\", file: file, line: line)\n                    return\n                }\n            case .local:\n                guard case .fileSystem = dependency.state else {\n                    XCTFail(\"Expected local dependency\", file: file, line: line)\n                    return\n                }\n            case .custom(let currentVersion, let currentPath):\n                guard case .custom(let version, let path) = dependency.state else {\n                    return XCTFail(\"invalid dependency state \\(dependency.state)\", file: file, line: line)\n                }\n                XCTAssertTrue(currentVersion == version && currentPath == path, file: file, line: line)\n            }\n        }\n    }\n\n    public struct ManagedArtifactResult {\n        public let managedArtifacts: Workspace.ManagedArtifacts\n\n        public init(_ managedArtifacts: Workspace.ManagedArtifacts) {\n            self.managedArtifacts = managedArtifacts\n        }\n\n        public func checkNotPresent(\n            packageName: String,\n            targetName: String,\n            file: StaticString = #file,\n            line: UInt = #line\n        ) {\n            self.checkNotPresent(packageIdentity: .plain(packageName), targetName: targetName, file: file, line: line)\n        }\n\n        public func checkNotPresent(\n            packageIdentity: PackageIdentity,\n            targetName: String,\n            file: StaticString = #file,\n            line: UInt = #line\n        ) {\n            let artifact = self.managedArtifacts[packageIdentity: packageIdentity, targetName: targetName]\n            XCTAssert(\n                artifact == nil,\n                \"Unexpectedly found \\(packageIdentity).\\(targetName) in managed artifacts\",\n                file: file,\n                line: line\n            )\n        }\n\n        public func checkEmpty(file: StaticString = #file, line: UInt = #line) {\n            XCTAssertEqual(self.managedArtifacts.count, 0, file: file, line: line)\n        }\n\n        public func check(\n            packageName: String,\n            targetName: String,\n            source: Workspace.ManagedArtifact.Source,\n            path: AbsolutePath,\n            file: StaticString = #file,\n            line: UInt = #line\n        ) {\n            self.check(\n                packageIdentity: .plain(packageName),\n                targetName: targetName,\n                source: source,\n                path: path,\n                file: file,\n                line: line\n            )\n        }\n\n        public func check(\n            packageIdentity: PackageIdentity,\n            targetName: String,\n            source: Workspace.ManagedArtifact.Source,\n            path: AbsolutePath,\n            file: StaticString = #file,\n            line: UInt = #line\n        ) {\n            guard let artifact = managedArtifacts[packageIdentity: packageIdentity, targetName: targetName] else {\n                XCTFail(\"managed artifact '\\(packageIdentity).\\(targetName)' does not exists\", file: file, line: line)\n                return\n            }\n            XCTAssertEqual(artifact.path, path, file: file, line: line)\n            switch (artifact.source, source) {\n            case (.remote(let lhsURL, let lhsChecksum), .remote(let rhsURL, let rhsChecksum)):\n                XCTAssertEqual(lhsURL, rhsURL, file: file, line: line)\n                XCTAssertEqual(lhsChecksum, rhsChecksum, file: file, line: line)\n            case (.local(let lhsChecksum), .local(let rhsChecksum)):\n                XCTAssertEqual(lhsChecksum, rhsChecksum, file: file, line: line)\n            default:\n                XCTFail(\"wrong source type\", file: file, line: line)\n            }\n        }\n    }\n\n    public func loadDependencyManifests(\n        roots: [String] = [],\n        deps: [MockDependency] = [],\n        _ result: (Workspace.DependencyManifests, [Basics.Diagnostic]) -> Void\n    ) async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let dependencies = try deps.map { try $0.convert(\n            baseURL: self.packagesDir,\n            identityResolver: self.identityResolver\n        ) }\n        let workspace = try self.getOrCreateWorkspace()\n        let rootInput = try PackageGraphRootInput(\n            packages: rootPaths(for: roots), dependencies: dependencies, traitConfiguration: traitConfiguration\n        )\n        let rootManifests = try await workspace.loadRootManifests(\n            packages: rootInput.packages,\n            observabilityScope: observability.topScope\n        )\n        let graphRoot = try PackageGraphRoot(\n            input: rootInput,\n            manifests: rootManifests,\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: workspace.enabledTraitsMap\n        )\n        let manifests = try await workspace.loadDependencyManifests(\n            root: graphRoot,\n            observabilityScope: observability.topScope\n        )\n        result(manifests, observability.diagnostics)\n    }\n\n    public func checkManagedDependencies(\n        file: StaticString = #file,\n        line: UInt = #line,\n        _ result: (ManagedDependencyResult) throws -> Void\n    ) async {\n        do {\n            let workspace = try self.getOrCreateWorkspace()\n            try await result(ManagedDependencyResult(workspace.state.dependencies))\n        } catch {\n            XCTFail(\"Failed with error \\(error.interpolationDescription)\", file: file, line: line)\n        }\n    }\n\n    public func checkManagedArtifacts(\n        file: StaticString = #file,\n        line: UInt = #line,\n        _ result: (ManagedArtifactResult) throws -> Void\n    ) async {\n        do {\n            let workspace = try self.getOrCreateWorkspace()\n            try await result(ManagedArtifactResult(workspace.state.artifacts))\n        } catch {\n            XCTFail(\"Failed with error \\(error.interpolationDescription)\", file: file, line: line)\n        }\n    }\n\n    public struct ResolvedResult {\n        public let store: ResolvedPackagesStore\n\n        public init(_ store: ResolvedPackagesStore) {\n            self.store = store\n        }\n\n        public func check(notPresent name: String, file: StaticString = #file, line: UInt = #line) {\n            XCTAssertFalse(\n                self.store.resolvedPackages.keys.contains(where: { $0.description == name }),\n                \"Unexpectedly found \\(name) in Package.resolved\",\n                file: file,\n                line: line\n            )\n        }\n\n        public func check(dependency package: String, at state: State, file: StaticString = #file, line: UInt = #line) {\n            guard let pin = store.resolvedPackages.first(where: { $0.key.description == package })?.value else {\n                XCTFail(\"Pin for \\(package) not found\", file: file, line: line)\n                return\n            }\n            switch state {\n            case .checkout(let checkoutState):\n                switch (checkoutState, pin.state) {\n                case (.version(let checkoutVersion), .version(let pinVersion, _)):\n                    XCTAssertEqual(pinVersion, checkoutVersion, file: file, line: line)\n                case (.revision(let checkoutRevision), .revision(let pinRevision)):\n                    XCTAssertEqual(checkoutRevision, pinRevision, file: file, line: line)\n                case (.branch(let checkoutBranch), .branch(let pinBranch, _)):\n                    XCTAssertEqual(checkoutBranch, pinBranch, file: file, line: line)\n                default:\n                    XCTFail(\"state dont match \\(checkoutState) \\(pin.state)\", file: file, line: line)\n                }\n            case .registryDownload(let downloadVersion):\n                guard case .version(let pinVersion, _) = pin.state else {\n                    return XCTFail(\"invalid pin state \\(pin.state)\", file: file, line: line)\n                }\n                XCTAssertEqual(pinVersion, downloadVersion, file: file, line: line)\n            case .edited, .local, .custom:\n                XCTFail(\"Unimplemented\", file: file, line: line)\n            }\n        }\n\n        public func check(dependency package: String, url: String, file: StaticString = #file, line: UInt = #line) {\n            guard let pin = store.resolvedPackages.first(where: { $0.key.description == package })?.value else {\n                XCTFail(\"Pin for \\(package) not found\", file: file, line: line)\n                return\n            }\n\n            XCTAssertEqual(pin.packageRef.kind, .remoteSourceControl(SourceControlURL(url)), file: file, line: line)\n        }\n    }\n\n    public func checkResolved(\n        file: StaticString = #file,\n        line: UInt = #line,\n        _ result: (ResolvedResult) throws -> Void\n    ) {\n        do {\n            let workspace = try self.getOrCreateWorkspace()\n            try result(ResolvedResult(workspace.resolvedPackagesStore.load()))\n        } catch {\n            XCTFail(\"Failed with error \\(error.interpolationDescription)\", file: file, line: line)\n        }\n    }\n}\n\npublic final class MockWorkspaceDelegate: WorkspaceDelegate {\n    private let lock = NSLock()\n    private var _events = [String]()\n    private var _manifest: Manifest?\n    private var _manifestLoadingDiagnostics: [Basics.Diagnostic]?\n\n    public init() {}\n\n    public func willUpdateRepository(package: PackageIdentity, repository url: String) {\n        self.append(\"updating repo: \\(url)\")\n    }\n\n    public func didUpdateRepository(package: PackageIdentity, repository url: String, duration: DispatchTimeInterval) {\n        self.append(\"finished updating repo: \\(url)\")\n    }\n\n    public func dependenciesUpToDate() {\n        self.append(\"Everything is already up-to-date\")\n    }\n\n    public func willFetchPackage(\n        package: PackageIdentity,\n        packageLocation: String?,\n        fetchDetails: PackageFetchDetails\n    ) {\n        self.append(\"fetching package: \\(packageLocation ?? package.description)\")\n    }\n\n    public func fetchingPackage(package: PackageIdentity, packageLocation: String?, progress: Int64, total: Int64?) {}\n\n    public func didFetchPackage(\n        package: PackageIdentity,\n        packageLocation: String?,\n        result: Result<PackageFetchDetails, Error>,\n        duration: DispatchTimeInterval\n    ) {\n        self.append(\"finished fetching package: \\(packageLocation ?? package.description)\")\n    }\n\n    public func willCreateWorkingCopy(package: PackageIdentity, repository url: String, at path: AbsolutePath) {\n        self.append(\"creating working copy for: \\(url)\")\n    }\n\n    public func didCreateWorkingCopy(\n        package: PackageIdentity,\n        repository url: String,\n        at path: AbsolutePath,\n        duration: DispatchTimeInterval\n    ) {\n        self.append(\"finished creating working copy for: \\(url)\")\n    }\n\n    public func willCheckOut(\n        package: PackageIdentity,\n        repository url: String,\n        revision: String,\n        at path: AbsolutePath\n    ) {\n        self.append(\"checking out repo: \\(url)\")\n    }\n\n    public func didCheckOut(\n        package: PackageIdentity,\n        repository url: String,\n        revision: String,\n        at path: AbsolutePath,\n        duration: DispatchTimeInterval\n    ) {\n        self.append(\"finished checking out repo: \\(url)\")\n    }\n\n    public func removing(package: PackageIdentity, packageLocation: String?) {\n        self.append(\"removing repo: \\(packageLocation ?? package.description)\")\n    }\n\n    public func willResolveDependencies(reason: WorkspaceResolveReason) {\n        self.append(\"will resolve dependencies\")\n    }\n\n    public func willLoadManifest(\n        packageIdentity: PackageIdentity,\n        packagePath: AbsolutePath,\n        url: String,\n        version: Version?,\n        packageKind: PackageReference.Kind\n    ) {\n        self.append(\"will load manifest for \\(packageKind.displayName) package: \\(url) (identity: \\(packageIdentity))\")\n    }\n\n    public func didLoadManifest(\n        packageIdentity: PackageIdentity,\n        packagePath: AbsolutePath,\n        url: String,\n        version: Version?,\n        packageKind: PackageReference.Kind,\n        manifest: Manifest?,\n        diagnostics: [Basics.Diagnostic],\n        duration: DispatchTimeInterval\n    ) {\n        self.append(\"did load manifest for \\(packageKind.displayName) package: \\(url) (identity: \\(packageIdentity))\")\n        self.lock.withLock {\n            self._manifest = manifest\n            self._manifestLoadingDiagnostics = diagnostics\n        }\n    }\n\n    public func willComputeVersion(package: PackageIdentity, location: String) {\n        // noop\n    }\n\n    public func didComputeVersion(\n        package: PackageIdentity,\n        location: String,\n        version: String,\n        duration: DispatchTimeInterval\n    ) {\n        // noop\n    }\n\n    public func resolvedFileChanged() {\n        // noop\n    }\n\n    public func willDownloadBinaryArtifact(from url: String, fromCache: Bool) {\n        self.append(\"downloading binary artifact package: \\(url)\")\n    }\n\n    public func didDownloadBinaryArtifact(\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    ) {\n        self.append(\"finished downloading binary artifact package: \\(url)\")\n    }\n\n    public func downloadingBinaryArtifact(from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?) {\n        // noop\n    }\n\n    public func didDownloadAllBinaryArtifacts() {\n        // noop\n    }\n\n    public func willDownloadPrebuilt(package: PackageIdentity, from url: String, fromCache: Bool) {\n        self.append(\"downloading package prebuilt: \\(url)\")\n    }\n\n    public func didDownloadPrebuilt(\n        package: PackageIdentity,\n        from url: String,\n        result: Result<(path: AbsolutePath, fromCache: Bool), Error>,\n        duration: DispatchTimeInterval\n    ) {\n        self.append(\"finished downloading package prebuilt: \\(url)\")\n    }\n\n    public func downloadingPrebuilt(package: PackageIdentity, from url: String, bytesDownloaded: Int64, totalBytesToDownload: Int64?) {\n        // noop\n    }\n\n    public func didDownloadAllPrebuilts() {\n        // noop\n    }\n\n    public func willUpdateDependencies() {\n        // noop\n    }\n\n    public func didUpdateDependencies(duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    public func willResolveDependencies() {\n        // noop\n    }\n\n    public func didResolveDependencies(duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    public func willLoadGraph() {\n        // noop\n    }\n\n    public func didLoadGraph(duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    public func willCompileManifest(packageIdentity: PackageIdentity, packageLocation: String) {\n        // noop\n    }\n\n    public func didCompileManifest(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        duration: DispatchTimeInterval\n    ) {\n        // noop\n    }\n\n    public func willEvaluateManifest(packageIdentity: PackageIdentity, packageLocation: String) {\n        // noop\n    }\n\n    public func didEvaluateManifest(\n        packageIdentity: PackageIdentity,\n        packageLocation: String,\n        duration: DispatchTimeInterval\n    ) {\n        // noop\n    }\n\n    private func append(_ event: String) {\n        self.lock.withLock {\n            self._events.append(event)\n        }\n    }\n\n    public var events: [String] {\n        self.lock.withLock {\n            self._events\n        }\n    }\n\n    public func clear() {\n        self.lock.withLock {\n            self._events = []\n        }\n    }\n\n    public var manifest: Manifest? {\n        self.lock.withLock {\n            self._manifest\n        }\n    }\n\n    public var manifestLoadingDiagnostics: [Basics.Diagnostic]? {\n        self.lock.withLock {\n            self._manifestLoadingDiagnostics\n        }\n    }\n}\n\nextension CheckoutState {\n    public var version: Version? {\n        switch self {\n        case .revision:\n            .none\n        case .version(let version, _):\n            version\n        case .branch:\n            .none\n        }\n    }\n\n    public var branch: String? {\n        switch self {\n        case .revision:\n            .none\n        case .version:\n            .none\n        case .branch(let branch, _):\n            branch\n        }\n    }\n}\n\nextension PackageReference.Kind {\n    fileprivate var displayName: String {\n        switch self {\n        case .root:\n            \"root\"\n        case .fileSystem:\n            \"fileSystem\"\n        case .localSourceControl:\n            \"localSourceControl\"\n        case .remoteSourceControl:\n            \"remoteSourceControl\"\n        case .registry:\n            \"registry\"\n        }\n    }\n}\n\nextension CheckoutState {\n    fileprivate var revision: Revision {\n        switch self {\n        case .revision(let revision):\n            revision\n        case .version(_, let revision):\n            revision\n        case .branch(_, let revision):\n            revision\n        }\n    }\n}\n\nextension [Basics.Diagnostic] {\n    public var hasErrors: Bool {\n        self.contains(where: { $0.severity == .error })\n    }\n\n    public var hasWarnings: Bool {\n        self.contains(where: { $0.severity == .warning })\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/Observability.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport func XCTest.XCTAssertTrue\nimport func XCTest.XCTAssertEqual\nimport func XCTest.XCTFail\n\nimport struct TSCBasic.StringError\nimport class TSCBasic.BufferedOutputByteStream\n\nimport TSCTestSupport\nimport Testing\n\nextension ObservabilitySystem {\n    public static func makeForTesting(verbose: Bool = true) -> TestingObservability {\n        let collector = TestingObservability.Collector(verbose: verbose)\n        let observabilitySystem = ObservabilitySystem(collector)\n        return TestingObservability(collector: collector, topScope: observabilitySystem.topScope)\n    }\n\n    public static func makeForTesting(verbose: Bool = true, outputStream: BufferedOutputByteStream) -> TestingObservability {\n        let collector = TestingObservability.Collector(verbose: verbose, outputStream: outputStream)\n        let observabilitySystem = ObservabilitySystem(collector)\n        return TestingObservability(collector: collector, topScope: observabilitySystem.topScope)\n    }\n}\n\npublic struct TestingObservability {\n    private let collector: Collector\n    public let topScope: ObservabilityScope\n\n    fileprivate init(collector: Collector, topScope: ObservabilityScope) {\n        self.collector = collector\n        self.topScope = topScope\n    }\n\n    public var diagnostics: [Basics.Diagnostic] {\n        self.collector.diagnostics.get()\n    }\n\n    public var errors: [Basics.Diagnostic] {\n        self.diagnostics.filter { $0.severity == .error }\n    }\n\n    public var warnings: [Basics.Diagnostic] {\n        self.diagnostics.filter { $0.severity == .warning }\n    }\n\n    public var hasErrorDiagnostics: Bool {\n        self.collector.hasErrors\n    }\n\n    public var hasWarningDiagnostics: Bool {\n        self.collector.hasWarnings\n    }\n\n    fileprivate final class Collector: ObservabilityHandlerProvider, DiagnosticsHandler, CustomStringConvertible {\n        var diagnosticsHandler: DiagnosticsHandler { self }\n\n        private let verbose: Bool\n        let diagnostics = ThreadSafeArrayStore<Basics.Diagnostic>()\n        private let outputStream: BufferedOutputByteStream?\n\n        init(verbose: Bool, outputStream: BufferedOutputByteStream? = nil) {\n            self.verbose = verbose\n            self.outputStream = outputStream\n        }\n\n        // TODO: do something useful with scope\n        func handleDiagnostic(scope: ObservabilityScope, diagnostic: Basics.Diagnostic) {\n            if self.verbose {\n                self.output(diagnostic.description)\n            }\n            self.diagnostics.append(diagnostic)\n        }\n\n        func print(_ output: String, condition: OutputCondition) {\n            switch condition {\n            case .always:\n                self.output(output)\n            case .onlyWhenVerbose:\n                guard self.verbose else { return }\n                self.output(output)\n            }\n        }\n\n        private func output(_ output: String) {\n            if let outputStream {\n                outputStream.write(output)\n            } else {\n                Swift.print(output)\n            }\n        }\n\n        var hasErrors: Bool {\n            self.diagnostics.get().hasErrors\n        }\n\n        var hasWarnings: Bool {\n            self.diagnostics.get().hasWarnings\n        }\n\n        var description: String {\n            let diagnostics = self.diagnostics.get()\n            return \"\\(diagnostics)\"\n        }\n    }\n}\n\npublic func XCTAssertNoDiagnostics(\n    _ diagnostics: [Basics.Diagnostic],\n    problemsOnly: Bool = true,\n    file: StaticString = #file,\n    line: UInt = #line\n) {\n    let diagnostics = problemsOnly ? diagnostics.filter { $0.severity >= .warning } : diagnostics\n    if diagnostics.isEmpty { return }\n    \n    let description = diagnostics.map { \"- \" + $0.description }.joined(separator: \"\\n\")\n    XCTFail(\"Found unexpected diagnostics: \\n\\(description)\", file: file, line: line)\n}\n\npublic func expectNoDiagnostics(\n    _ diagnostics: [Basics.Diagnostic],\n    problemsOnly: Bool = true,\n    sourceLocation: SourceLocation = #_sourceLocation\n) {\n    let diagnostics = problemsOnly ? diagnostics.filter { $0.severity >= .warning } : diagnostics\n    if diagnostics.isEmpty { return }\n\n    let description = diagnostics.map { \"- \" + $0.description }.joined(separator: \"\\n\")\n    Issue.record(\"Found unexpected diagnostics: \\n\\(description)\", sourceLocation: sourceLocation)\n}\n\npublic func testDiagnostics(\n    _ diagnostics: [Basics.Diagnostic],\n    problemsOnly: Bool = true,\n    file: StaticString = #file,\n    line: UInt = #line,\n    handler: (DiagnosticsTestResult) throws -> Void\n) {\n    testDiagnostics(\n        diagnostics,\n        minSeverity: problemsOnly ? .warning : .debug,\n        file: file,\n        line: line,\n        handler: handler\n    )\n}\n\npublic func testDiagnostics(\n    _ diagnostics: [Basics.Diagnostic],\n    minSeverity: Basics.Diagnostic.Severity,\n    file: StaticString = #file,\n    line: UInt = #line,\n    handler: (DiagnosticsTestResult) throws -> Void\n) {\n    let diagnostics = diagnostics.filter { $0.severity >= minSeverity }\n    let testResult = DiagnosticsTestResult(diagnostics)\n\n    do {\n        try handler(testResult)\n    } catch {\n        XCTFail(\"error \\(String(describing: error))\", file: file, line: line)\n    }\n\n    if !testResult.uncheckedDiagnostics.isEmpty {\n        XCTFail(\"unchecked diagnostics \\(testResult.uncheckedDiagnostics)\", file: file, line: line)\n    }\n}\n\npublic func expectDiagnostics(\n    _ diagnostics: [Basics.Diagnostic],\n    problemsOnly: Bool = true,\n    sourceLocation: SourceLocation = #_sourceLocation,\n    handler: (DiagnosticsTestResult) throws -> Void\n) throws {\n    try expectDiagnostics(\n        diagnostics,\n        minSeverity: problemsOnly ? .warning : .debug,\n        sourceLocation: sourceLocation,\n        handler: handler\n    )\n}\n\n\npublic func expectDiagnostics(\n    _ diagnostics: [Basics.Diagnostic],\n    minSeverity: Basics.Diagnostic.Severity,\n    sourceLocation: SourceLocation = #_sourceLocation,\n    handler: (DiagnosticsTestResult) throws -> Void\n) throws {\n    let diagnostics = diagnostics.filter { $0.severity >= minSeverity }\n    let testResult = DiagnosticsTestResult(diagnostics)\n\n    try handler(testResult)\n\n    if !testResult.uncheckedDiagnostics.isEmpty {\n        Issue.record(\"unchecked diagnostics \\(testResult.uncheckedDiagnostics)\", sourceLocation: sourceLocation)\n     }\n}\n \npublic func testPartialDiagnostics(\n    _ diagnostics: [Basics.Diagnostic],\n    minSeverity: Basics.Diagnostic.Severity,\n    file: StaticString = #file,\n    line: UInt = #line,\n    handler: (DiagnosticsTestResult) throws -> Void\n) {\n    let diagnostics = diagnostics.filter { $0.severity >= minSeverity }\n    let testResult = DiagnosticsTestResult(diagnostics)\n\n    do {\n        try handler(testResult)\n    } catch {\n        XCTFail(\"error \\(String(describing: error))\", file: file, line: line)\n    }\n}\n\n/// Helper to check diagnostics in the engine.\npublic class DiagnosticsTestResult {\n    fileprivate var uncheckedDiagnostics: [Basics.Diagnostic]\n\n    init(_ diagnostics: [Basics.Diagnostic]) {\n        self.uncheckedDiagnostics = diagnostics\n    }\n\n    package func checkIsEmpty(\n        file: StaticString = #file,\n        line: UInt = #line\n    ) {\n        XCTAssertTrue(self.uncheckedDiagnostics.isEmpty, file: file, line: line)\n    }\n\n    @discardableResult\n    public func check(\n        diagnostic message: StringPattern,\n        severity: Basics.Diagnostic.Severity,\n        //metadata: ObservabilityMetadata? = .none,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) -> Basics.Diagnostic? {\n        guard !self.uncheckedDiagnostics.isEmpty else {\n            XCTFail(\"No diagnostics left to check\", file: file, line: line)\n            return nil\n        }\n\n        let diagnostic: Basics.Diagnostic = self.uncheckedDiagnostics.removeFirst()\n\n        XCTAssertMatch(diagnostic.message, message, file: file, line: line)\n        XCTAssertEqual(diagnostic.severity, severity, file: file, line: line)\n        // FIXME: (diagnostics) compare complete metadata when legacy bridge is removed\n        //XCTAssertEqual(diagnostic.metadata, metadata, file: file, line: line)\n        //XCTAssertEqual(diagnostic.metadata?.droppingLegacyKeys(), metadata?.droppingLegacyKeys(), file: file, line: line)\n\n        return diagnostic\n    }\n\n    @discardableResult\n    public func checkUnordered(\n        diagnostic diagnosticPattern: StringPattern,\n        severity: Basics.Diagnostic.Severity,\n        //metadata: ObservabilityMetadata? = .none,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) -> Basics.Diagnostic? {\n        guard !self.uncheckedDiagnostics.isEmpty else {\n            XCTFail(\"No diagnostics left to check\", file: file, line: line)\n            return nil\n        }\n\n        let matching = self.uncheckedDiagnostics.indices\n            .filter { diagnosticPattern ~= self.uncheckedDiagnostics[$0].message }\n        if matching.isEmpty {\n            XCTFail(\"No diagnostics match \\(diagnosticPattern)\", file: file, line: line)\n            return nil\n        } else if matching.count == 1, let index = matching.first {\n            let diagnostic = self.uncheckedDiagnostics[index]\n            XCTAssertEqual(diagnostic.severity, severity, file: file, line: line)\n            // FIXME: (diagnostics) compare complete metadata when legacy bridge is removed\n            //XCTAssertEqual(diagnostic.metadata, metadata, file: file, line: line)\n            //XCTAssertEqual(diagnostic.metadata?.droppingLegacyKeys(), metadata?.droppingLegacyKeys(), file: file, line: line)\n            self.uncheckedDiagnostics.remove(at: index)\n            return diagnostic\n        // FIXME: (diagnostics) compare complete metadata when legacy bridge is removed\n        } else if let index = self.uncheckedDiagnostics.firstIndex(where: { diagnostic in diagnostic.severity == severity /*&& diagnostic.metadata == metadata*/}) {\n        //} else if let index = self.uncheckedDiagnostics.firstIndex(where: { diagnostic in diagnostic.severity == severity && diagnostic.metadata?.droppingLegacyKeys() == metadata?.droppingLegacyKeys()}) {\n            let diagnostic = self.uncheckedDiagnostics[index]\n            self.uncheckedDiagnostics.remove(at: index)\n            return diagnostic\n        } else {\n            return nil\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/PackageDependencyDescriptionExtensions.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\n\nimport struct TSCUtility.Version\n\npackage extension PackageDependency {\n    static func fileSystem(\n        identity: PackageIdentity? = nil,\n        deprecatedName: String? = nil,\n        path: AbsolutePath,\n        productFilter: ProductFilter = .everything,\n        traits: Set<Trait> = [.init(name: \"default\")]\n    ) -> Self {\n        let identity = identity ?? PackageIdentity(path: path)\n        return .fileSystem(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: deprecatedName,\n            path: path,\n            productFilter: productFilter,\n            traits: traits\n        )\n    }\n\n    static func localSourceControl(\n        identity: PackageIdentity? = nil,\n        deprecatedName: String? = nil,\n        path: AbsolutePath,\n        requirement: SourceControl.Requirement,\n        productFilter: ProductFilter = .everything,\n        traits: Set<Trait> = [.init(name: \"default\")]\n    ) -> Self {\n        let identity = identity ?? PackageIdentity(path: path)\n        return .localSourceControl(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: deprecatedName,\n            path: path,\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: traits\n        )\n    }\n\n    static func remoteSourceControl(\n        identity: PackageIdentity? = nil,\n        deprecatedName: String? = nil,\n        url: SourceControlURL,\n        requirement: SourceControl.Requirement,\n        productFilter: ProductFilter = .everything,\n        traits: Set<Trait> = [.init(name: \"default\")]\n    ) -> Self {\n        let identity = identity ?? PackageIdentity(url: url)\n        return .remoteSourceControl(\n            identity: identity,\n            nameForTargetDependencyResolutionOnly: deprecatedName,\n            url: url,\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: traits\n        )\n    }\n\n    static func registry(\n        identity: String,\n        requirement: Registry.Requirement,\n        productFilter: ProductFilter = .everything,\n        traits: Set<Trait> = [.init(name: \"default\")]\n    ) -> Self {\n        return .registry(\n            identity: .plain(identity),\n            requirement: requirement,\n            productFilter: productFilter,\n            traits: traits\n        )\n    }\n}\n\n// backwards compatibility with existing tests\n\nextension PackageDependency.SourceControl.Requirement {\n    public static func upToNextMajor(from version: Version) -> Self {\n        return .range(.upToNextMajor(from: version))\n    }\n    public static func upToNextMinor(from version: Version) -> Self {\n        return .range(.upToNextMinor(from: version))\n    }\n}\n\nextension PackageDependency.Registry.Requirement {\n    public static func upToNextMajor(from version: Version) -> Self {\n        return .range(.upToNextMajor(from: version))\n    }\n    public static func upToNextMinor(from version: Version) -> Self {\n        return .range(.upToNextMinor(from: version))\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/PackageGraphTester.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\nimport struct Basics.IdentifiableSet\n\nimport PackageModel\nimport PackageGraph\n\npublic func PackageGraphTester(_ graph: ModulesGraph, _ result: (PackageGraphResult) throws -> Void) rethrows {\n    try result(PackageGraphResult(graph))\n}\n\npublic final class PackageGraphResult {\n    public let graph: ModulesGraph\n\n    public init(_ graph: ModulesGraph) {\n        self.graph = graph\n    }\n\n    public func check(roots: PackageIdentity..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(graph.rootPackages.map{$0.identity }.sorted() == roots.sorted(), sourceLocation: sourceLocation)\n    }\n\n    public func check(packages: PackageIdentity..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(graph.packages.map {$0.identity }.sorted() == packages.sorted(), sourceLocation: sourceLocation)\n    }\n\n    public func check(modules: String..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(\n            graph.allModules\n                .filter { $0.type != .test }\n                .map { $0.name }\n                .sorted() == modules.sorted(), sourceLocation: sourceLocation)\n    }\n\n    public func check(products: String..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(Set(graph.allProducts.map { $0.name }) == Set(products), sourceLocation: sourceLocation)\n    }\n\n    public func check(reachableTargets: String..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(Set(graph.reachableModules.map { $0.name }) == Set(reachableTargets), sourceLocation: sourceLocation)\n    }\n\n    public func check(reachableProducts: String..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(Set(graph.reachableProducts.map { $0.name }) == Set(reachableProducts), sourceLocation: sourceLocation)\n    }\n\n    public func check(\n        reachableBuildTargets: String...,\n        in environment: BuildEnvironment,\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) throws {\n        let targets = Set(try self.reachableBuildTargets(in: environment).map({ $0.name }))\n        #expect(targets == Set(reachableBuildTargets), sourceLocation: sourceLocation)\n    }\n\n    public func check(\n        reachableBuildProducts: String...,\n        in environment: BuildEnvironment,\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) throws {\n        let products = Set(try self.reachableBuildProducts(in: environment).map({ $0.name }))\n        #expect(products == Set(reachableBuildProducts), sourceLocation: sourceLocation)\n    }\n\n    public func checkTarget(\n        _ name: String,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (ResolvedTargetResult) throws -> Void\n    ) throws {\n        let target = try #require(graph.module(for: name), \"Target \\(name) not found\", sourceLocation: sourceLocation)\n\n        try body(ResolvedTargetResult(target))\n    }\n\n    package func checkTargets(\n        _ name: String,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: ([ResolvedTargetResult]) throws -> Void\n    ) rethrows {\n        try body(graph.allModules.filter { $0.name == name }.map(ResolvedTargetResult.init))\n    }\n\n    public func checkProduct(\n        _ name: String,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (ResolvedProductResult) -> Void\n    ) throws {\n        let product = try #require(graph.product(for: name), \"Product \\(name) not found\", sourceLocation: sourceLocation)\n\n\n        body(ResolvedProductResult(product))\n    }\n\n    package func checkPackage(\n        _ name: String,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (ResolvedPackage) -> Void\n    ) throws {\n        let pkg = try #require(find(package: .init(stringLiteral: name)), \"Product \\(name) not found\", sourceLocation: sourceLocation)\n        body(pkg)\n    }\n\n    public func check(testModules: String..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(\n            graph.allModules\n                .filter{ $0.type == .test }\n                .map{ $0.name }\n                .sorted() == testModules.sorted(), sourceLocation: sourceLocation)\n    }\n\n    public func find(package: PackageIdentity) -> ResolvedPackage? {\n        return graph.package(for: package)\n    }\n\n    private func reachableBuildTargets(in environment: BuildEnvironment) throws -> IdentifiableSet<ResolvedModule> {\n        let inputTargets = graph.inputPackages.lazy.flatMap { $0.modules }\n        let recursiveBuildTargetDependencies = try inputTargets\n            .flatMap { try $0.recursiveDependencies(satisfying: environment) }\n            .compactMap { $0.module }\n        return IdentifiableSet(inputTargets).union(recursiveBuildTargetDependencies)\n    }\n\n    private func reachableBuildProducts(in environment: BuildEnvironment) throws -> IdentifiableSet<ResolvedProduct> {\n        let recursiveBuildProductDependencies = try graph.inputPackages\n            .lazy\n            .flatMap { $0.modules }\n            .flatMap { try $0.recursiveDependencies(satisfying: environment) }\n            .compactMap { $0.product }\n        return IdentifiableSet(graph.inputPackages.flatMap { $0.products }).union(recursiveBuildProductDependencies)\n    }\n}\n\npublic final class ResolvedTargetResult {\n    public let target: ResolvedModule\n\n    init(_ target: ResolvedModule) {\n        self.target = target\n    }\n\n    public func check(dependencies: String..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(Set(dependencies) == Set(target.dependencies.map({ $0.name })), sourceLocation: sourceLocation)\n    }\n\n    public func check(dependencies: [String], sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(Set(dependencies) == Set(target.dependencies.map({ $0.name })), sourceLocation: sourceLocation)\n    }\n\n    public func checkDependency(\n        _ name: String,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (ResolvedTargetDependencyResult) -> Void\n    ) throws {\n        let dependency = try #require(\n            target.dependencies.first(where: { $0.name == name }),\n            \"Dependency \\(name) not found\",\n            sourceLocation: sourceLocation,\n        )\n        body(ResolvedTargetDependencyResult(dependency))\n    }\n\n    public func check(type: Module.Kind, sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(type == target.type, sourceLocation: sourceLocation)\n    }\n\n    public func checkDeclaredPlatforms(_ platforms: [String: String], sourceLocation: SourceLocation = #_sourceLocation) {\n        let targetPlatforms = Dictionary(\n            uniqueKeysWithValues: target.supportedPlatforms.map { ($0.platform.name, $0.version.versionString) }\n        )\n        #expect(platforms == targetPlatforms, sourceLocation: sourceLocation)\n    }\n\n    public func checkDerivedPlatforms(_ platforms: [String: String], sourceLocation: SourceLocation = #_sourceLocation) {\n        let derived = platforms.map {\n            let platform = PlatformRegistry.default.platformByName[$0.key] ?? PackageModel.Platform\n                .custom(name: $0.key, oldestSupportedVersion: $0.value)\n            return self.target.getSupportedPlatform(for: platform, usingXCTest: self.target.type == .test)\n        }\n        let targetPlatforms = Dictionary(\n            uniqueKeysWithValues: derived.map { ($0.platform.name, $0.version.versionString) }\n        )\n        #expect(platforms == targetPlatforms, sourceLocation: sourceLocation)\n    }\n\n    public func checkDerivedPlatformOptions(\n        _ platform: PackageModel.Platform,\n        options: [String],\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) {\n        let platform = self.target.getSupportedPlatform(for: platform, usingXCTest: target.type == .test)\n        #expect(platform.options == options, sourceLocation: sourceLocation)\n    }\n\n    package func checkBuildSetting(\n        declaration: BuildSettings.Declaration,\n        assignments: Set<BuildSettings.Assignment>?,\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) {\n        #expect(\n            target.underlying.buildSettings.assignments[declaration].flatMap { Set($0) } == assignments,\n            sourceLocation: sourceLocation\n        )\n    }\n}\n\npublic final class ResolvedTargetDependencyResult {\n    private let dependency: ResolvedModule.Dependency\n\n    init(_ dependency: ResolvedModule.Dependency) {\n        self.dependency = dependency\n    }\n\n    public func checkConditions(satisfy environment: BuildEnvironment, sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(dependency.conditions.allSatisfy({ $0.satisfies(environment) }), sourceLocation: sourceLocation)\n    }\n\n    public func checkConditions(\n        dontSatisfy environment: BuildEnvironment,\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) {\n        #expect(!dependency.conditions.allSatisfy({ $0.satisfies(environment) }), sourceLocation: sourceLocation)\n    }\n\n    public func checkTarget(\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (ResolvedTargetResult) throws -> Void\n    ) throws {\n        guard case let .module(target, _) = self.dependency else {\n            Issue.record(\"Dependency \\(dependency) is not a target\", sourceLocation: sourceLocation)\n            return\n        }\n        try body(ResolvedTargetResult(target))\n    }\n\n    public func checkProduct(\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (ResolvedProductResult) -> Void\n    ) {\n        guard case let .product(product, _) = self.dependency else {\n             Issue.record(\"Dependency \\(dependency) is not a product\", sourceLocation: sourceLocation)\n             return\n        }\n        body(ResolvedProductResult(product))\n    }\n}\n\npublic final class ResolvedProductResult {\n    private let product: ResolvedProduct\n\n    init(_ product: ResolvedProduct) {\n        self.product = product\n    }\n\n    public func check(modules: String..., sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(Set(modules) == Set(product.modules.map({ $0.name })), sourceLocation: sourceLocation)\n    }\n\n    public func check(type: ProductType, sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(type == product.type, sourceLocation: sourceLocation)\n    }\n\n    public func checkDeclaredPlatforms(_ platforms: [String: String], sourceLocation: SourceLocation = #_sourceLocation) {\n        let targetPlatforms = Dictionary(uniqueKeysWithValues: product.supportedPlatforms.map({ ($0.platform.name, $0.version.versionString) }))\n        #expect(platforms == targetPlatforms, sourceLocation: sourceLocation)\n    }\n\n    public func checkDerivedPlatforms(_ platforms: [String: String], sourceLocation: SourceLocation = #_sourceLocation) {\n        let derived = platforms.map {\n            let platform = PlatformRegistry.default.platformByName[$0.key] ?? PackageModel.Platform.custom(name: $0.key, oldestSupportedVersion: $0.value)\n            return product.getSupportedPlatform(for: platform, usingXCTest: product.isLinkingXCTest)\n        }\n        let targetPlatforms = Dictionary(uniqueKeysWithValues: derived.map({ ($0.platform.name, $0.version.versionString) }))\n        #expect(platforms == targetPlatforms, sourceLocation: sourceLocation)\n    }\n\n    public func checkDerivedPlatformOptions(_ platform: PackageModel.Platform, options: [String], sourceLocation: SourceLocation = #_sourceLocation) {\n        let platform = product.getSupportedPlatform(for: platform, usingXCTest: product.isLinkingXCTest)\n        #expect(platform.options == options, sourceLocation: sourceLocation)\n    }\n\n    public func checkTarget(\n        _ name: String,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        body: (ResolvedTargetResult) throws -> Void\n    ) throws {\n        let target = try #require(\n            product.modules.first(where: { $0.name == name }),\n            \"Target \\(name) not found\",\n            sourceLocation: sourceLocation,\n        )\n        try body(ResolvedTargetResult(target))\n    }\n}\n\nextension ResolvedModule.Dependency {\n    public var name: String {\n        switch self {\n        case .module(let target, _):\n            return target.name\n        case .product(let product, _):\n            return product.name\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/PackageGraphTesterXCTest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\nimport struct Basics.IdentifiableSet\n\nimport PackageModel\nimport PackageGraph\n\n@available(*, deprecated, message: \"Migrate to Swift Testing and use 'PackageGraphTester'\")\npublic func PackageGraphTesterXCTest(_ graph: ModulesGraph, _ result: (PackageGraphResultXCTest) throws -> Void) rethrows {\n    try result(PackageGraphResultXCTest(graph))\n}\n\n@available(*, deprecated, message: \"Migrate to Swift Testing and use 'PackageGraphResult'\")\npublic final class PackageGraphResultXCTest {\n    public let graph: ModulesGraph\n\n    public init(_ graph: ModulesGraph) {\n        self.graph = graph\n    }\n\n    public func check(roots: PackageIdentity..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(graph.rootPackages.map{$0.identity }.sorted(), roots.sorted(), file: file, line: line)\n    }\n\n    public func check(packages: PackageIdentity..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(graph.packages.map {$0.identity }.sorted(), packages.sorted(), file: file, line: line)\n    }\n\n    public func check(modules: String..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(\n            graph.allModules\n                .filter { $0.type != .test }\n                .map { $0.name }\n                .sorted(), modules.sorted(), file: file, line: line)\n    }\n\n    public func check(products: String..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(Set(graph.allProducts.map { $0.name }), Set(products), file: file, line: line)\n    }\n\n    public func check(reachableTargets: String..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(Set(graph.reachableModules.map { $0.name }), Set(reachableTargets), file: file, line: line)\n    }\n\n    public func check(reachableProducts: String..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(Set(graph.reachableProducts.map { $0.name }), Set(reachableProducts), file: file, line: line)\n    }\n\n    public func check(\n        reachableBuildTargets: String...,\n        in environment: BuildEnvironment,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) throws {\n        let targets = Set(try self.reachableBuildTargets(in: environment).map({ $0.name }))\n        XCTAssertEqual(targets, Set(reachableBuildTargets), file: file, line: line)\n    }\n\n    public func check(\n        reachableBuildProducts: String...,\n        in environment: BuildEnvironment,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) throws {\n        let products = Set(try self.reachableBuildProducts(in: environment).map({ $0.name }))\n        XCTAssertEqual(products, Set(reachableBuildProducts), file: file, line: line)\n    }\n\n    public func checkTarget(\n        _ name: String,\n        file: StaticString = #file,\n        line: UInt = #line,\n        body: (ResolvedTargetResultXCTest) -> Void\n    ) {\n        let target = graph.module(for: name)\n\n        guard let target else {\n            return XCTFail(\"Target \\(name) not found\", file: file, line: line)\n        }\n\n        body(ResolvedTargetResultXCTest(target))\n    }\n\n    package func checkTargets(\n        _ name: String,\n        file: StaticString = #file,\n        line: UInt = #line,\n        body: ([ResolvedTargetResultXCTest]) throws -> Void\n    ) rethrows {\n        try body(graph.allModules.filter { $0.name == name }.map(ResolvedTargetResultXCTest.init))\n    }\n\n    public func checkProduct(\n        _ name: String,\n        file: StaticString = #file,\n        line: UInt = #line,\n        body: (ResolvedProductResultXCTest) -> Void\n    ) {\n        let product = graph.product(for: name)\n\n        guard let product else {\n            return XCTFail(\"Product \\(name) not found\", file: file, line: line)\n        }\n\n        body(ResolvedProductResultXCTest(product))\n    }\n\n    package func checkPackage(\n        _ name: String,\n        file: StaticString = #file,\n        line: UInt = #line,\n        body: (ResolvedPackage) -> Void\n    ) {\n        guard let package = find(package: .init(stringLiteral: name)) else {\n            return XCTFail(\"Product \\(name) not found\", file: file, line: line)\n        }\n        body(package)\n    }\n\n    public func check(testModules: String..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(\n            graph.allModules\n                .filter{ $0.type == .test }\n                .map{ $0.name }\n                .sorted(), testModules.sorted(), file: file, line: line)\n    }\n\n    public func find(package: PackageIdentity) -> ResolvedPackage? {\n        return graph.package(for: package)\n    }\n\n    private func reachableBuildTargets(in environment: BuildEnvironment) throws -> IdentifiableSet<ResolvedModule> {\n        let inputTargets = graph.inputPackages.lazy.flatMap { $0.modules }\n        let recursiveBuildTargetDependencies = try inputTargets\n            .flatMap { try $0.recursiveDependencies(satisfying: environment) }\n            .compactMap { $0.module }\n        return IdentifiableSet(inputTargets).union(recursiveBuildTargetDependencies)\n    }\n\n    private func reachableBuildProducts(in environment: BuildEnvironment) throws -> IdentifiableSet<ResolvedProduct> {\n        let recursiveBuildProductDependencies = try graph.inputPackages\n            .lazy\n            .flatMap { $0.modules }\n            .flatMap { try $0.recursiveDependencies(satisfying: environment) }\n            .compactMap { $0.product }\n        return IdentifiableSet(graph.inputPackages.flatMap { $0.products }).union(recursiveBuildProductDependencies)\n    }\n}\n\n@available(*, deprecated, message: \"Migrate to Swift Testing and use 'ResolvedTargetResult'\")\npublic final class ResolvedTargetResultXCTest {\n    public let target: ResolvedModule\n\n    init(_ target: ResolvedModule) {\n        self.target = target\n    }\n\n    public func check(dependencies: String..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(Set(dependencies), Set(target.dependencies.map({ $0.name })), file: file, line: line)\n    }\n\n    public func check(dependencies: [String], file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(Set(dependencies), Set(target.dependencies.map({ $0.name })), file: file, line: line)\n    }\n\n    public func checkDependency(\n        _ name: String,\n        file: StaticString = #file,\n        line: UInt = #line,\n        body: (ResolvedTargetDependencyResultXCTest) -> Void\n    ) {\n        guard let dependency = target.dependencies.first(where: { $0.name == name }) else {\n            return XCTFail(\"Dependency \\(name) not found\", file: file, line: line)\n        }\n        body(ResolvedTargetDependencyResultXCTest(dependency))\n    }\n\n    public func check(type: Module.Kind, file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(type, target.type, file: file, line: line)\n    }\n\n    public func checkDeclaredPlatforms(_ platforms: [String: String], file: StaticString = #file, line: UInt = #line) {\n        let targetPlatforms = Dictionary(\n            uniqueKeysWithValues: target.supportedPlatforms.map { ($0.platform.name, $0.version.versionString) }\n        )\n        XCTAssertEqual(platforms, targetPlatforms, file: file, line: line)\n    }\n\n    public func checkDerivedPlatforms(_ platforms: [String: String], file: StaticString = #file, line: UInt = #line) {\n        let derived = platforms.map {\n            let platform = PlatformRegistry.default.platformByName[$0.key] ?? PackageModel.Platform\n                .custom(name: $0.key, oldestSupportedVersion: $0.value)\n            return self.target.getSupportedPlatform(for: platform, usingXCTest: self.target.type == .test)\n        }\n        let targetPlatforms = Dictionary(\n            uniqueKeysWithValues: derived.map { ($0.platform.name, $0.version.versionString) }\n        )\n        XCTAssertEqual(platforms, targetPlatforms, file: file, line: line)\n    }\n\n    public func checkDerivedPlatformOptions(\n        _ platform: PackageModel.Platform,\n        options: [String],\n        file: StaticString = #file,\n        line: UInt = #line\n    ) {\n        let platform = self.target.getSupportedPlatform(for: platform, usingXCTest: target.type == .test)\n        XCTAssertEqual(platform.options, options, file: file, line: line)\n    }\n\n    package func checkBuildSetting(\n        declaration: BuildSettings.Declaration,\n        assignments: Set<BuildSettings.Assignment>?,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) {\n        XCTAssertEqual(\n            target.underlying.buildSettings.assignments[declaration].flatMap { Set($0) },\n            assignments,\n            file: file,\n            line: line\n        )\n    }\n}\n\n@available(*, deprecated, message: \"Migrate to Swift Testing and use 'ResolvedTargetDependencyResult'\")\npublic final class ResolvedTargetDependencyResultXCTest {\n    private let dependency: ResolvedModule.Dependency\n\n    init(_ dependency: ResolvedModule.Dependency) {\n        self.dependency = dependency\n    }\n\n    public func checkConditions(satisfy environment: BuildEnvironment, file: StaticString = #file, line: UInt = #line) {\n        XCTAssert(dependency.conditions.allSatisfy({ $0.satisfies(environment) }), file: file, line: line)\n    }\n\n    public func checkConditions(\n        dontSatisfy environment: BuildEnvironment,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) {\n        XCTAssert(!dependency.conditions.allSatisfy({ $0.satisfies(environment) }), file: file, line: line)\n    }\n\n    public func checkTarget(\n        file: StaticString = #file,\n        line: UInt = #line,\n        body: (ResolvedTargetResultXCTest) -> Void\n    ) {\n        guard case let .module(target, _) = self.dependency else {\n            return XCTFail(\"Dependency \\(dependency) is not a target\", file: file, line: line)\n        }\n        body(ResolvedTargetResultXCTest(target))\n    }\n\n    public func checkProduct(\n        file: StaticString = #file,\n        line: UInt = #line,\n        body: (ResolvedProductResultXCTest) -> Void\n    ) {\n        guard case let .product(product, _) = self.dependency else {\n            return XCTFail(\"Dependency \\(dependency) is not a product\", file: file, line: line)\n        }\n        body(ResolvedProductResultXCTest(product))\n    }\n}\n\n@available(*, deprecated, message: \"Migrate to Swift Testing and use 'ResolvedProductResult'\")\npublic final class ResolvedProductResultXCTest {\n    private let product: ResolvedProduct\n\n    init(_ product: ResolvedProduct) {\n        self.product = product\n    }\n\n    public func check(modules: String..., file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(Set(modules), Set(product.modules.map({ $0.name })), file: file, line: line)\n    }\n\n    public func check(type: ProductType, file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(type, product.type, file: file, line: line)\n    }\n\n    public func checkDeclaredPlatforms(_ platforms: [String: String], file: StaticString = #file, line: UInt = #line) {\n        let targetPlatforms = Dictionary(uniqueKeysWithValues: product.supportedPlatforms.map({ ($0.platform.name, $0.version.versionString) }))\n        XCTAssertEqual(platforms, targetPlatforms, file: file, line: line)\n    }\n\n    public func checkDerivedPlatforms(_ platforms: [String: String], file: StaticString = #file, line: UInt = #line) {\n        let derived = platforms.map {\n            let platform = PlatformRegistry.default.platformByName[$0.key] ?? PackageModel.Platform.custom(name: $0.key, oldestSupportedVersion: $0.value)\n            return product.getSupportedPlatform(for: platform, usingXCTest: product.isLinkingXCTest)\n        }\n        let targetPlatforms = Dictionary(uniqueKeysWithValues: derived.map({ ($0.platform.name, $0.version.versionString) }))\n        XCTAssertEqual(platforms, targetPlatforms, file: file, line: line)\n    }\n\n    public func checkDerivedPlatformOptions(_ platform: PackageModel.Platform, options: [String], file: StaticString = #file, line: UInt = #line) {\n        let platform = product.getSupportedPlatform(for: platform, usingXCTest: product.isLinkingXCTest)\n        XCTAssertEqual(platform.options, options, file: file, line: line)\n    }\n\n    public func checkTarget(\n        _ name: String,\n        file: StaticString = #file,\n        line: UInt = #line,\n        body: (ResolvedTargetResultXCTest) -> Void\n    ) {\n        guard let target = product.modules.first(where: { $0.name == name }) else {\n            return XCTFail(\"Target \\(name) not found\", file: file, line: line)\n        }\n        body(ResolvedTargetResultXCTest(target))\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/ProcessInfo+hostutils.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nextension ProcessInfo {\n    public static func isHostAmazonLinux2(_ content: String? = nil) -> Bool {\n        let contentString: String\n        if let content {\n            contentString = content\n        } else {\n            let osReleasePath = \"/etc/os-release\"\n            do {\n                contentString = try String(contentsOfFile: osReleasePath, encoding: .utf8)\n            } catch {\n                return false\n            }\n        }\n        let al2_name = \"PRETTY_NAME=\\\"Amazon Linux 2\\\"\"\n        return contentString.contains(al2_name)\n    }\n\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/ResolvedModule+Mock.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageGraph\nimport PackageModel\n\nextension ResolvedModule {\n    public static func mock(\n        packageIdentity: PackageIdentity,\n        name: String,\n        deps: ResolvedModule...,\n        conditions: [PackageCondition] = []\n    ) -> ResolvedModule {\n        ResolvedModule(\n            packageIdentity: packageIdentity,\n            underlying: SwiftModule(\n                name: name,\n                type: .library,\n                path: .root,\n                sources: Sources(paths: [], root: \"/\"),\n                dependencies: [],\n                packageAccess: false,\n                usesUnsafeFlags: false,\n                implicit: true\n            ),\n            dependencies: deps.map { .module($0, conditions: conditions) },\n            defaultLocalization: nil,\n            supportedPlatforms: [],\n            platformConstraint: .all,\n            platformVersionProvider: .init(implementation: .minimumDeploymentTargetDefault)\n        )\n    }\n}\n\n"
  },
  {
    "path": "Sources/_InternalTestSupport/SwiftPMProduct.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\nimport class Basics.AsyncProcess\nimport struct Basics.AsyncProcessResult\n\nimport enum TSCBasic.ProcessEnv\n\n// Fan out from invocation of SPM 'swift-*' commands can be quite large.  Limit the number of concurrent tasks to a fraction of total CPUs.\nprivate let swiftPMExecutionQueue = AsyncOperationQueue(concurrentTasks: Int(Double(ProcessInfo.processInfo.activeProcessorCount) * 0.5))\n\n/// Defines the executables used by SwiftPM.\n/// Contains path to the currently built executable and\n/// helper method to execute them.\npublic enum SwiftPM {\n    case Build\n    case Package\n    case Registry\n    case Test\n    case Run\n    case experimentalSDK\n    case sdk\n}\n\nextension SwiftPM {\n    /// Executable name.\n    private var executableName: String {\n        switch self {\n        case .Build:\n            return \"swift-build\"\n        case .Package:\n            return \"swift-package\"\n        case .Registry:\n            return \"swift-package-registry\"\n        case .Test:\n            return \"swift-test\"\n        case .Run:\n            return \"swift-run\"\n        case .experimentalSDK:\n            return \"swift-experimental-sdk\"\n        case .sdk:\n            return \"swift-sdk\"\n        }\n    }\n\n    public var xctestBinaryPath: AbsolutePath {\n        Self.xctestBinaryPath(for: RelativePath(self.executableName))\n    }\n\n    public static func xctestBinaryPath(for executableName: RelativePath) -> AbsolutePath {\n        do {\n            return try resolveBinDir().appending(executableName)\n        } catch {\n            fatalError(\"Unable to determine xctestBinaryPath\")\n        }\n    }\n}\n\nextension SwiftPM {\n    /// Executes the product with specified arguments.\n    ///\n    /// - Parameters:\n    ///         - args: The arguments to pass.\n    ///         - env: Additional environment variables to pass. The values here are merged with default env.\n    ///         - packagePath: Adds argument `--package-path <path>` if not nil.\n    ///         - throwIfCommandFails: If set, will throw an error if the command does not have a 0 return code.\n    ///\n    /// - Returns: The output of the process.\n    @discardableResult\n    public func execute(\n        _ args: [String] = [],\n        packagePath: AbsolutePath? = nil,\n        env: Environment? = nil,\n        throwIfCommandFails: Bool = true\n    ) async throws -> (stdout: String, stderr: String) {\n        // Swift Testing uses Swift concurrency for test execution and creates a task for each test to run in parallel.\n        // A single invocation of \"swift build\" can spawn a large number of subprocesses.\n        // When this pattern is repeated across many tests, thousands of processes compete for\n        // CPU/disk/network resources. Tests can take thousands of seconds to complete, with periods\n        // of no stdout/stderr output that can cause activity timeouts in CI pipelines.\n        // Run all SPM executions under a queue to limit the maximum number of concurrent SPM processes.\n        try await swiftPMExecutionQueue.withOperation {\n            let result = try await executeProcess(\n                args,\n                packagePath: packagePath,\n                env: env\n            )\n            // Remove /r from stdout/stderr so that tests do not have to deal with them\n            let stdout = try String(decoding: result.output.get().filter { $0 != 13 }, as: Unicode.UTF8.self)\n            let stderr = try String(decoding: result.stderrOutput.get().filter { $0 != 13 }, as: Unicode.UTF8.self)\n\n            let returnValue = (stdout: stdout, stderr: stderr)\n            if !throwIfCommandFails { return returnValue }\n\n            if result.exitStatus == .terminated(code: 0) {\n                return returnValue\n            }\n            throw SwiftPMError.executionFailure(\n                underlying: AsyncProcessResult.Error.nonZeroExit(result),\n                stdout: stdout,\n                stderr: stderr\n            )\n        }\n    }\n\n    private func executeProcess(\n        _ args: [String],\n        packagePath: AbsolutePath? = nil,\n        env: Environment? = nil\n    ) async throws -> AsyncProcessResult {\n        var environment = Environment.current\n#if !os(Windows)\n        environment[\"SDKROOT\"] = nil\n#endif\n\n#if Xcode\n        // Unset these variables which causes issues when running tests via Xcode.\n        environment[\"XCTestConfigurationFilePath\"] = nil\n        environment[\"XCTestSessionIdentifier\"] = nil\n        environment[\"XCTestBundlePath\"] = nil\n        environment[\"NSUnbufferedIO\"] = nil\n#endif\n        // FIXME: We use this private environment variable hack to be able to\n        // create special conditions in swift-build for swiftpm tests.\n        environment[\"SWIFTPM_TESTS_MODULECACHE\"] = self.xctestBinaryPath.parentDirectory.pathString\n\n        // Unset the internal env variable that allows skipping certain tests.\n        environment[\"_SWIFTPM_SKIP_TESTS_LIST\"] = nil\n\n        for (key, value) in env ?? [:] {\n            environment[key] = value\n        }\n\n        var completeArgs = [Self.xctestBinaryPath(for: RelativePath(self.executableName)).pathString]\n        if let packagePath = packagePath {\n            completeArgs += [\"--package-path\", packagePath.pathString]\n        }\n        completeArgs += args\n\n        return try await AsyncProcess.popen(arguments: completeArgs, environment: environment)\n    }\n}\n\nextension SwiftPM {\n    public static func packagePath(for packageName: String, packageRoot: AbsolutePath) throws -> AbsolutePath {\n        // FIXME: The directory paths are hard coded right now and should be replaced by --get-package-path\n        // whenever we design that. https://bugs.swift.org/browse/SR-2753\n        let packagesPath = packageRoot.appending(components: \".build\", \"checkouts\")\n        for name in try localFileSystem.getDirectoryContents(packagesPath) {\n            if name.hasPrefix(packageName) {\n                return try AbsolutePath(validating: name, relativeTo: packagesPath)\n            }\n        }\n        throw SwiftPMError.packagePathNotFound\n    }\n}\n\npublic enum SwiftPMError: Error {\n    case packagePathNotFound\n    case executionFailure(underlying: Error, stdout: String, stderr: String)\n}\n\n@available(*, deprecated, message: \"Use SwiftPMError instead\")\npublic enum SwiftPMProductError: Swift.Error {\n    case packagePathNotFound\n    case executionFailure(error: Swift.Error, output: String, stderr: String)\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/SwiftTesting+Data.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\npublic struct TestBuildData {\n    public let buildData: [BuildData]\n    public let tags: any TestTrait\n}\n\npublic let buildDataUsingAllBuildSystemWithTags = TestBuildData(\n    buildData: getBuildData(for: SupportedBuildSystemOnPlatform),\n    tags: .tags(\n        .Feature.CommandLineArguments.BuildSystem,\n        .Feature.CommandLineArguments.Configuration\n    )\n)\n"
  },
  {
    "path": "Sources/_InternalTestSupport/SwiftTesting+Helpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Testing\n\n\nfileprivate func fileErrorMessage(\n    at path: AbsolutePath,\n    prefix: Comment?,\n    comment: Comment,\n) -> Comment {\n    let commentPrefix =\n        if let prefix {\n            \"\\(prefix): \"\n        } else {\n            \"\"\n        }\n\n    let commentSuffix: String\n    do {\n        let parentDir = path.parentDirectory\n        commentSuffix = try \" Directory contents of \\(parentDir) : \\(localFileSystem.getDirectoryContents(parentDir)).\"\n    } catch {\n        commentSuffix = \"\"\n    }\n    return Comment(\"\\(commentPrefix)\\(comment) \\(commentSuffix).\")\n}\npublic func expectFileExists(\n    at path: AbsolutePath,\n    _ comment: Comment? = nil,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) {\n    #expect(\n        localFileSystem.exists(path),\n        fileErrorMessage(\n            at: path,\n            prefix: comment,\n            comment: \"File '\\(path)' does not exist.\",\n        ),\n        sourceLocation: sourceLocation,\n    )\n}\n\npublic func requireFileExists(\n    at path: AbsolutePath,\n    _ comment: Comment? = nil,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) throws {\n    try #require(\n        localFileSystem.exists(path),\n        fileErrorMessage(\n            at: path,\n            prefix: comment,\n            comment: \"File '\\(path)' does not exist.\",\n        ),\n        sourceLocation: sourceLocation,\n    )\n}\n\npublic func expectFileDoesNotExists(\n    at path: AbsolutePath,\n    _ comment: Comment? = nil,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) {\n    #expect(\n        !localFileSystem.exists(path),\n        fileErrorMessage(\n            at: path,\n            prefix: comment,\n            comment: \"File: '\\(path)' was not expected to exist, but does.\",\n        ),\n        sourceLocation: sourceLocation,\n    )\n}\npublic func requireFileDoesNotExists(\n    at path: AbsolutePath,\n    _ comment: Comment? = nil,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) throws {\n    try #require(\n        !localFileSystem.exists(path),\n        fileErrorMessage(\n            at: path,\n            prefix: comment,\n            comment: \"File: '\\(path)' was not expected to exist, but does.\",\n        ),\n        sourceLocation: sourceLocation,\n    )\n}\n\npublic func expectFileIsExecutable(\n    at fixturePath: AbsolutePath,\n    _ comment: Comment? = nil,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) {\n    let commentPrefix =\n        if let comment {\n            \"\\(comment): \"\n        } else {\n            \"\"\n        }\n    #expect(\n        localFileSystem.isExecutableFile(fixturePath),\n        \"\\(commentPrefix)File '\\(fixturePath)' expected to be executable, but is not.\",\n        sourceLocation: sourceLocation,\n    )\n}\n\nprivate func directoryExistsErrorMessage(\n    for path: AbsolutePath,\n    comment: Comment?\n) -> Comment {\n    let commentPrefix =\n        if let comment {\n            \"\\(comment): \"\n        } else {\n            \"\"\n        }\n    let msgSuffix: String\n    do {\n        msgSuffix = try \"Directory contents: \\(localFileSystem.getDirectoryContents(path))\"\n    } catch {\n        msgSuffix = \"\"\n    }\n    return Comment(\"\\(commentPrefix)Expected directory doesn't exist: '\\(path)'. \\(msgSuffix)\")\n}\n\npublic func requireDirectoryExists(\n    at path: AbsolutePath,\n    _ comment: Comment? = nil,\n    fileSystem: FileSystem = localFileSystem,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) throws {\n    try #require(\n        localFileSystem.isDirectory(path),\n        directoryExistsErrorMessage(for: path, comment: comment),\n        sourceLocation: sourceLocation,\n    )\n}\n\npublic func expectDirectoryExists(\n    at path: AbsolutePath,\n    _ comment: Comment? = nil,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) {\n    #expect(\n        localFileSystem.isDirectory(path),\n        directoryExistsErrorMessage(for: path, comment: comment),\n        sourceLocation: sourceLocation,\n    )\n}\n\npublic func expectDirectoryDoesNotExist(\n    at path: AbsolutePath,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) {\n    let msgSuffix: String\n    do {\n        msgSuffix = try \"Directory contents: \\(localFileSystem.getDirectoryContents(path))\"\n    } catch {\n        msgSuffix = \"\"\n    }\n    #expect(\n        !localFileSystem.isDirectory(path),\n        \"Directory exists unexpectedly: '\\(path)'.\\(msgSuffix)\",\n        sourceLocation: sourceLocation,\n    )\n}\n\n/// Expects a directory (recursively) contains a file.\npackage func expectDirectoryContainsFile(\n    dir: AbsolutePath,\n    filename: String,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) {\n    do {\n        for entry in try walk(dir) {\n            if entry.basename == filename { return }\n        }\n    } catch {\n        Issue.record(\"Failed with error \\(error)\", sourceLocation: sourceLocation)\n    }\n    Issue.record(\"Directory \\(dir) does not contain \\(filename)\", sourceLocation: sourceLocation)\n}\n\n\n/// Expects that the expression throws a CommandExecutionError and passes it to the provided throwing error handler.\n/// - Parameters:\n///   - expression: The expression expected to throw\n///   - message: Optional message for the expectation\n///   - sourceLocation: Source location for error reporting\n///   - errorHandler: A throwing closure that receives the CommandExecutionError\npublic func expectThrowsCommandExecutionError<T>(\n    _ expression: @autoclosure () async throws -> T,\n    _ message: @autoclosure () -> Comment = \"\",\n    sourceLocation: SourceLocation = #_sourceLocation,\n    _ errorHandler: (_ error: CommandExecutionError) throws -> Void = { _ in }\n) async rethrows {\n    _ = try await _expectThrowsCommandExecutionError(try await expression(), message(), sourceLocation, errorHandler)\n}\n\n/// Expects that the expression throws a CommandExecutionError and passes it to the provided non-throwing error handler.\n/// This version can be called without `try` when the error handler doesn't throw.\n/// - Parameters:\n///   - expression: The expression expected to throw\n///   - message: Optional message for the expectation\n///   - sourceLocation: Source location for error reporting\n///   - errorHandler: A non-throwing closure that receives the CommandExecutionError\npublic func expectThrowsCommandExecutionError<T>(\n    _ expression: @autoclosure () async throws -> T,\n    _ message: @autoclosure () -> Comment = \"\",\n    sourceLocation: SourceLocation = #_sourceLocation,\n    _ errorHandler: (_ error: CommandExecutionError) -> Void\n) async {\n    _ = try? await _expectThrowsCommandExecutionError(try await expression(), message(), sourceLocation) { error in\n        errorHandler(error)\n        return ()\n    }\n}\n\nprivate func _expectThrowsCommandExecutionError<R, T>(\n    _ expressionClosure: @autoclosure  () async throws -> T,\n    _ message: @autoclosure () -> Comment,\n    _ sourceLocation: SourceLocation,\n    _ errorHandler: (_ error: CommandExecutionError) throws -> R\n) async rethrows -> R? {\n    // Older toolchains don't have https://github.com/swiftlang/swift-evolution/blob/main/proposals/testing/0006-return-errors-from-expect-throws.md\n    // This can be removed once the CI smoke jobs build with 6.2.\n    var err: SwiftPMError?\n    await #expect(throws: SwiftPMError.self, message(), sourceLocation: sourceLocation) {\n        do {\n            let _ = try await expressionClosure()\n        } catch {\n            err = error as? SwiftPMError\n            throw error\n        }\n    }\n\n    guard let error = err,\n          case .executionFailure(let processError, let stdout, let stderr) = error,\n          case AsyncProcessResult.Error.nonZeroExit(let processResult) = processError,\n          processResult.exitStatus != .terminated(code: 0) else {\n        Issue.record(\"Unexpected error type: \\(err?.interpolationDescription ?? \"<unknown>\")\", sourceLocation: sourceLocation)\n        return Optional<R>.none\n    }\n    return try errorHandler(CommandExecutionError(result: processResult, stdout: stdout, stderr: stderr))\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/SwiftTesting+Tags.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\nextension Tag {\n    public enum TestSize {}\n    public enum Feature {}\n    public enum Platform {}\n    public enum FunctionalArea {}\n    @Tag public static var UserWorkflow: Tag\n}\n\nextension Tag.TestSize {\n    @Tag public static var small: Tag\n    @Tag public static var medium: Tag\n    @Tag public static var large: Tag\n}\n\nextension Tag.Platform {\n    @Tag public static var FileSystem: Tag\n}\n\nextension Tag.FunctionalArea {\n    @Tag public static var APIDiff: Tag\n    @Tag public static var PIF: Tag\n    @Tag public static var IndexMode: Tag\n    @Tag public static var Sanitizer: Tag\n    @Tag public static var LibraryEvoluton: Tag\n    @Tag public static var LinkSwiftStaticStdlib: Tag\n    @Tag public static var Metal: Tag\n    @Tag public static var ModuleMaps: Tag\n    @Tag public static var Resources: Tag\n    @Tag public static var Workspace: Tag\n}\n\nextension Tag.Feature {\n    public enum Command {}\n    public enum CommandLineArguments {}\n    public enum EnvironmentVariables {}\n    public enum PackageType {}\n    public enum ProductType {}\n    public enum TargetType {}\n    public enum Product {}\n\n    @Tag public static var BuildCache: Tag\n    @Tag public static var CodeCoverage: Tag\n    @Tag public static var CTargets: Tag\n    @Tag public static var DependencyResolution: Tag\n    @Tag public static var ModuleAliasing: Tag\n    @Tag public static var Mirror: Tag\n    @Tag public static var NetRc: Tag\n    @Tag public static var Plugin: Tag\n    @Tag public static var Resource: Tag\n    @Tag public static var Version: Tag\n    @Tag public static var SBOM: Tag\n    @Tag public static var SourceGeneration: Tag\n    @Tag public static var SpecialCharacters: Tag\n    @Tag public static var Snippets: Tag\n    @Tag public static var TestDiscovery: Tag\n    @Tag public static var Traits: Tag\n    @Tag public static var TargetSettings: Tag\n    @Tag public static var TaskBacktraces: Tag\n}\n\nextension Tag.Feature.Command {\n    public enum Package {}\n    public enum PackageRegistry {}\n    @Tag public static var Build: Tag\n    @Tag public static var Run: Tag\n    @Tag public static var Sdk: Tag\n    @Tag public static var Test: Tag\n}\n\nextension Tag.Feature.CommandLineArguments {\n    public enum Experimental {}\n    @Tag public static var BuildSystem: Tag\n    @Tag public static var BuildTests: Tag\n    @Tag public static var Configuration: Tag\n    @Tag public static var DisableGetTaskAllowEntitlement: Tag\n    @Tag public static var EnableParseableModuleInterfaces: Tag\n    @Tag public static var EnableGetTaskAllowEntitlement: Tag\n    @Tag public static var EnableTestDiscovery: Tag\n    @Tag public static var ExplicitTargetDependencyImportCheck: Tag\n    @Tag public static var Help: Tag\n    @Tag public static var Product: Tag\n    @Tag public static var PrintManifestJobGraph: Tag\n    @Tag public static var PrintPIFManifestGraph: Tag\n    @Tag public static var Quiet: Tag\n    @Tag public static var ShowBinPath: Tag\n    @Tag public static var Target: Tag\n    @Tag public static var Toolset: Tag\n    @Tag public static var Triple: Tag\n    @Tag public static var Version: Tag\n    @Tag public static var Verbose: Tag\n    @Tag public static var VeryVerbose: Tag\n    @Tag public static var Xlinker: Tag\n    @Tag public static var XbuildToolsSwiftc: Tag\n    @Tag public static var Xcc: Tag\n    @Tag public static var Xcxx: Tag\n    @Tag public static var Xld: Tag\n    @Tag public static var Xswiftc: Tag\n    @Tag public static var TestParallel: Tag\n    @Tag public static var TestNoParallel: Tag\n    @Tag public static var TestOutputXunit: Tag\n    @Tag public static var TestEnableSwiftTesting: Tag\n    @Tag public static var TestDisableSwiftTesting: Tag\n    @Tag public static var TestEnableXCTest: Tag\n    @Tag public static var TestDisableXCTest: Tag\n    @Tag public static var TestFilter: Tag\n    @Tag public static var TestSkip: Tag\n    @Tag public static var SkipBuild: Tag\n    @Tag public static var EnableCodeCoverage: Tag\n}\n\nextension Tag.Feature.CommandLineArguments.Experimental {\n    @Tag public static var BuildDylibsAsFrameworks: Tag\n    @Tag public static var PruneUnusedDependencies: Tag\n}\nextension Tag.Feature.EnvironmentVariables {\n    @Tag public static var CUSTOM_SWIFT_VERSION: Tag\n    @Tag public static var SWIFT_EXEC: Tag\n    @Tag public static var SWIFT_EXEC_MANIFEST: Tag\n    @Tag public static var SWIFT_ORIGINAL_PATH: Tag\n}\n\nextension Tag.Feature.Command.Package {\n    @Tag public static var General: Tag\n    @Tag public static var AddDependency: Tag\n    @Tag public static var AddProduct: Tag\n    @Tag public static var ArchiveSource: Tag\n    @Tag public static var AddSetting: Tag\n    @Tag public static var AddTarget: Tag\n    @Tag public static var AddTargetDependency: Tag\n    @Tag public static var BuildPlugin: Tag\n    @Tag public static var Clean: Tag\n    @Tag public static var CommandPlugin: Tag\n    @Tag public static var CompletionTool: Tag\n    @Tag public static var Config: Tag\n    @Tag public static var Describe: Tag\n    @Tag public static var DiagnoseApiBreakingChanges: Tag\n    @Tag public static var DumpPackage: Tag\n    @Tag public static var DumpSymbolGraph: Tag\n    @Tag public static var Edit: Tag\n    @Tag public static var ExperimentalApiDiff: Tag\n    @Tag public static var GenerateSBOM: Tag\n    @Tag public static var Init: Tag\n    @Tag public static var Migrate: Tag\n    @Tag public static var Plugin: Tag\n    @Tag public static var Reset: Tag\n    @Tag public static var PurgeCache: Tag\n    @Tag public static var Resolve: Tag\n    @Tag public static var ShowDependencies: Tag\n    @Tag public static var ShowExecutables: Tag\n    @Tag public static var ShowTraits: Tag\n    @Tag public static var ToolsVersion: Tag\n    @Tag public static var Unedit: Tag\n    @Tag public static var Update: Tag\n}\n\nextension Tag.Feature.Command.PackageRegistry {\n    @Tag public static var General: Tag\n    @Tag public static var Login: Tag\n    @Tag public static var Logout: Tag\n    @Tag public static var Publish: Tag\n    @Tag public static var Set: Tag\n    @Tag public static var Unset: Tag\n}\n\nextension Tag.Feature.TargetType {\n    public enum BinaryTarget {}\n    @Tag public static var Executable: Tag\n    @Tag public static var Library: Tag\n    @Tag public static var Macro: Tag\n    @Tag public static var Test: Tag\n}\n\nextension Tag.Feature.TargetType.BinaryTarget {\n    @Tag public static var ArtifactBundle: Tag\n    @Tag public static var XCFramework: Tag\n}\n\nextension Tag.Feature.ProductType {\n    @Tag public static var DynamicLibrary: Tag\n    @Tag public static var Executable: Tag\n    @Tag public static var Library: Tag\n    @Tag public static var Plugin: Tag\n    @Tag public static var StaticLibrary: Tag\n}\nextension Tag.Feature.PackageType {\n    @Tag public static var Library: Tag\n    @Tag public static var Empty: Tag\n    @Tag public static var Executable: Tag\n    @Tag public static var Tool: Tag\n    @Tag public static var Plugin: Tag\n    @Tag public static var BuildToolPlugin: Tag\n    @Tag public static var CommandPlugin: Tag\n    @Tag public static var Macro: Tag\n}\n\nextension Tag.Feature.Product {\n    @Tag public static var Execute: Tag\n    @Tag public static var Link: Tag\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/SwiftTesting+TraitArgumentData.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum PackageModel.BuildConfiguration\n\n/// A utility struct that represents a list of traits that would be passed through the command line.\n/// This is used for testing purposes, and its use is currently specific to the `TraitTests.swift`\npublic struct TraitArgumentData {\n    public var traitsArgument: String\n    public var expectedOutput: String\n}\n\npublic func getTraitCombinations(_ traitsAndMessage: (traits: String, output: String)...) -> [TraitArgumentData] {\n    traitsAndMessage.map { traitListAndMessage in\n        TraitArgumentData(traitsArgument: traitListAndMessage.traits, expectedOutput: traitListAndMessage.output)\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/SwiftTesting+TraitConditional.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.FileManager\nimport class Foundation.ProcessInfo\nimport class PackageModel.UserToolchain\nimport DriverSupport\nimport Basics\nimport Testing\nimport TSCclibc  // for SPM_posix_spawn_file_actions_addchdir_np_supported\n\nextension Trait where Self == Testing.ConditionTrait {\n    /// Skip test if the host operating system does not match the running OS.\n    public static func requireHostOS(_ os: OperatingSystem, _ comment: Comment? = nil, when condition: Bool = true) -> Self {\n        enabled(comment ?? \"This test requires a \\(os) host OS.\") {\n            ProcessInfo.hostOperatingSystem == os && condition\n        }\n    }\n\n    /// Skip test if the host operating system matches the running OS.\n    public static func skipHostOS(_ os: OperatingSystem, _ comment: Comment? = nil) -> Self {\n        disabled(comment ?? \"This test cannot run on a \\(os) host OS.\") {\n            ProcessInfo.hostOperatingSystem == os\n        }\n    }\n\n    public static func requireCompiledWith6_3OrLater(_ comment: Comment? = nil) -> Self {\n        enabled(comment ?? \"This needs to have been compiled with Swift 6.3 or later.\") {\n            #if compiler(>=6.3)\n            true\n            #else\n            false\n            #endif\n        }\n    }\n\n    /// Enabled only if toolchain support swift concurrency\n    public static var requiresSwiftConcurrencySupport: Self {\n        enabled(\"skipping because test environment doesn't support concurrency\") {\n            (try? UserToolchain.default)?.supportsSwiftConcurrency() != nil\n        }\n    }\n\n    /// Enabled only if 'llvm-profdata' is available\n    public static var requiresLLVMProfData: Self {\n        disabled(\"skipping test because the `llvm-profdata` tool isn't available\") {\n            try (try? UserToolchain.default)?.getLLVMProf() == nil\n        }\n    }\n\n    /// Enabled only if 'llvm-cov' is available\n    public static var requiresLLVMCov: Self {\n        disabled(\"skipping test because the `llvm-cov` tool isn't available\") {\n            try (try? UserToolchain.default)?.getLLVMCov() == nil\n        }\n    }\n\n    /// Enabled only if 'swift-symbolgraph-extract' is available\n    public static var requiresSymbolgraphExtract: Self {\n        disabled(\"skipping test because the `swift-symbolgraph-extract` tools isn't available\") {\n            try (try? UserToolchain.default)?.getSymbolGraphExtract() == nil\n        }\n    }\n\n    /// Enabled only is stdlib is supported by the toolchain\n    public static var requiresStdlibSupport: Self {\n        enabled(\"skipping because static stdlib is not supported by the toolchain\") {\n            let args = try [\n                UserToolchain.default.swiftCompilerPath.pathString,\n                \"-static-stdlib\", \"-emit-executable\", \"-o\", \"/dev/null\", \"-\",\n            ]\n            let process = AsyncProcess(arguments: args)\n            let stdin = try process.launch()\n            stdin.write(sequence: \"\".utf8)\n            try stdin.close()\n            let result = try await process.waitUntilExit()\n\n            return result.exitStatus == .terminated(code: 0)\n        }\n    }\n\n    /// Enabled if toolsupm suported SDK Dependent Tests\n    public static var requiresSDKDependentTestsSupport: Self {\n        enabled(\"skipping because test environment doesn't support this test\") {\n            (try? UserToolchain.default)!.supportsSDKDependentTests()\n        }\n    }\n\n    // Enabled if the toolchain has supported features\n    public static var supportsSupportedFeatures: Self {\n        enabled(\"skipping because test environment compiler doesn't support `-print-supported-features`\") {\n            (try? UserToolchain.default)!.supportsSupportedFeatures\n        }\n    }\n\n    /// Skip of the executable is not available\n    public static func requires(executable: String) -> Self {\n        let message: Comment?\n        let isToolAvailable: Bool\n        do {\n            try _requiresTools(executable)\n            isToolAvailable = true\n            message = nil\n        } catch (let AsyncProcessResult.Error.nonZeroExit(result)) {\n            isToolAvailable = false\n            message = \"Skipping as tool \\(executable) is not found in the path. (\\(result.description))\"\n        } catch {\n            isToolAvailable = false\n            message = \"Skipping. Unable to determine if tool exists. Error: \\(error) \"\n        }\n        return enabled(if: isToolAvailable, message)\n    }\n\n    /// Enaled only if marcros are built as dylibs\n    public static var requiresBuildingMacrosAsDylibs: Self {\n        enabled(\"test is only supported if `BUILD_MACROS_AS_DYLIBS` is set\") {\n            #if BUILD_MACROS_AS_DYLIBS\n                true\n            #else\n                false\n            #endif\n        }\n    }\n\n    /// Check for required compiler support\n    public static func requiresFrontEndFlags(flags: Set<String>) -> Self {\n        enabled(\"test requires \\(flags.joined(separator: \", \"))\") {\n            try DriverSupport.checkSupportedFrontendFlags(flags: flags, toolchain: UserToolchain.default, fileSystem: localFileSystem)\n        }\n    }\n\n    private static func requiresHostLibrary(lib: String) -> Self {\n        enabled(\"test requires `\\(lib)` to exist in the host toolchain\") {\n            let libSwiftSyntaxMacrosPath = try UserToolchain.default.hostLibDir.appending(\"libSwiftSyntaxMacros.dylib\")\n            return localFileSystem.exists(libSwiftSyntaxMacrosPath)\n        }\n    }\n\n    public static var requiresSwiftTestingMacros: Self {\n        requiresHostLibrary(lib: \"libSwiftSyntaxMacros.dylib\")\n    }\n\n    /// Ensure platform support working directory\n    public static var requiresWorkingDirectorySupport: Self {\n        enabled(\"working directory not supported on this platform\") {\n            #if !os(Windows)\n                // needed for archiving\n                if SPM_posix_spawn_file_actions_addchdir_np_supported() {\n                    return true\n                } else {\n                    return false\n                }\n            #else\n                return true\n            #endif\n        }\n    }\n\n    /// Skip test unconditionally\n    public static func skip(_ comment: Comment? = nil) -> Self {\n        disabled(comment ?? \"Unconditional skip, a comment should be added for the reason\") { true }\n    }\n\n    /// Skip test if the environment is self hosted.\n    public static func skipSwiftCISelfHosted(_ comment: Comment? = nil) -> Self {\n        disabled(comment ?? \"SwiftCI is self hosted\") {\n            ProcessInfo.processInfo.environment[\"SWIFTCI_IS_SELF_HOSTED\"] != nil\n        }\n    }\n\n    /// Skip test if the test environment has a restricted network access, i.e. cannot get to internet.\n    public static func requireUnrestrictedNetworkAccess(_ comment: Comment? = nil) -> Self {\n        disabled(comment ?? \"CI Environment has restricted network access\") {\n            ProcessInfo.processInfo.environment[\"SWIFTCI_RESTRICTED_NETWORK_ACCESS\"] != nil\n        }\n    }\n\n    /// Test required setting ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION define\n    public static var requiresTargetBasedDependencyResolution: Self {\n        enabled(\"enabled as target based dependency resolution is defined\") {\n            #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n                true\n            #else\n                false\n            #endif\n        }\n    }\n\n    /// Skip test if built by XCode.\n    public static func skipIfXcodeBuilt() -> Self {\n        disabled(\"Tests built by Xcode\") {\n            #if Xcode\n                true\n            #else\n                false\n            #endif\n        }\n    }\n\n    /// Skip test if compiler is older than 6.2.\n    public static var requireSwift6_2: Self {\n        enabled(\"This test requires Swift 6.2, or newer.\") {\n            #if compiler(>=6.2)\n                true\n            #else\n                false\n            #endif\n        }\n    }\n    /// Skip test if compiler is older than 6.3.\n    public static var requireSwift6_3: Self {\n        enabled(\"This test requires Swift 6.3, or newer.\") {\n            #if compiler(>=6.3)\n                true\n            #else\n                false\n            #endif\n        }\n    }\n\n    /// Skip test if compiler is older than 6.4.\n    public static var requireSwift6_4: Self {\n        enabled(\"This test requires Swift 6.4, or newer.\") {\n            #if compiler(>=6.4)\n                true\n            #else\n                false\n            #endif\n        }\n    }\n\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/SwiftTesting+Traits.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\n#if os(Windows)\n    extension Trait where Self == ParallelizationTrait {\n        public static var serializedIfOnWindows: Self {\n            .serialized\n        }\n    }\n#else\n    extension Trait where Self == ConditionTrait {\n        public static var serializedIfOnWindows: Self {\n            .enabled(if: true)\n        }\n    }\n#endif\n"
  },
  {
    "path": "Sources/_InternalTestSupport/SwiftTesting+TraitsBug.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\nextension Trait where Self == Testing.Bug {\n    public static func SWBINTTODO(_ comment: Comment) -> Self {\n        bug(nil, id: 0, comment)\n    }\n}\n\npublic enum Relationship {\n    case verifies\n    case defect\n    case fixedBy\n}\n\nextension Trait where Self == Testing.Bug {\n    public static func issue(\n        _ issue: _const String,\n        relationship: Relationship,\n    ) -> Self {\n        bug(nil, id: 0, \"\\(relationship): \\(issue)\")\n    }\n\n    public static var IssueWindowsRelativePathAssert: Self {\n        // TSCBasic/Path.swift:969: Assertion failed\n        issue(\n            \"https://github.com/swiftlang/swift-package-manager/issues/8602\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueWindowsPathLastComponent: Self {\n        // $0.path.lastComponent in test code returns fullpaths on Windows\n        issue(\n            \"https://github.com/swiftlang/swift-package-manager/issues/8554\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueWindowsAbsoluteAndRelativePathTestFailures: Self {\n        issue(\n            \"https://github.com/swiftlang/swift-package-manager/issues/8511\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueWindowsLongPath: Self {\n        .issue(\n            // \"https://github.com/swiftlang/swift-tools-support-core/pull/521\",\n            \"rdar://157310562\",\n            relationship: .fixedBy,\n        )\n    }\n\n    public static var IssueWindowsPathTestsFailures: Self {\n        .issue(\n            \"https://github.com/swiftlang/swift-package-manager/issues/8511\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueWindowsPathNoEntry: Self {\n        // error: FileSystemError(kind: TSCBasic.FileSystemError.Kind.noEntry, path: Optional(<AbsolutePath:\"C:\\Users\\ContainerAdministrator\\AppData\\Local\\Temp\\Miscellaneous_EchoExecutable.BVjrEf\\Miscellaneous_EchoExecutable\\.build\\out\\Intermediates.noindex\\EchoExecutable.build\\Debug-windows\\TestSuite-test-runner.build\\Objects-normal\\x86_64\\TestSuite-test-runner.LinkFileList\">))\n        .issue(\n            \"https://github.com/swiftlang/swift-package-manager/issues/9420\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueWindowsCannotSaveAttachment: Self {\n        // error: unable to write file 'C:\\Users\\ContainerAdministrator\\AppData\\Local\\Temp\\CFamilyTargets_CDynamicLookup.hNxGHC\\CFamilyTargets_CDynamicLookup\\.build\\x86_64-unknown-windows-msvc\\Intermediates.noindex\\CDynamicLookup.build\\Release-windows\\CDynamicLookup.build\\Objects-normal\\x86_64\\CDynamicLookup.LinkFileList': No such file or directory (2)\n        .issue(\n            \"https://github.com/swiftlang/swift-foundation/issues/1486\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueWindowsFolderCreationFailure: Self {\n        .issue(\n            \"https://github.com/swiftlang/swift-package-manager/issues/8433\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueProductTypeForObjectLibraries: Self {\n        .issue(\n            \"https://github.com/swiftlang/swift-build/issues/609\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueLdFailsUnexpectedly : Self {\n        .issue(\n            \"https://github.com/swiftlang/swift-package-manager/issues/9249\",\n            relationship: .defect,\n        )\n    }\n\n    public static var IssueSwiftBuildSpaceInPath: Self {\n        .issue(\n            \"https://github.com/swiftlang/swift-package-manager/issues/8400\",\n            relationship: .defect,\n        )\n    }\n\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/Toolchain.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\nimport Workspace\n\nimport struct TSCBasic.ByteString\nimport class Basics.AsyncProcess\nimport struct TSCBasic.StringError\nimport struct TSCUtility.SerializedDiagnostics\n\n#if os(macOS)\npackage func macOSBundleRoot() throws -> AbsolutePath {\n    for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(\".xctest\") {\n        return try AbsolutePath(validating: bundle.bundlePath).parentDirectory\n    }\n    if let testBundlePath = nextItem(in: ProcessInfo.processInfo.arguments, after: \"--test-bundle-path\") {\n        let binDir = AbsolutePath(testBundlePath).parentDirectory.parentDirectory.parentDirectory.parentDirectory\n        return binDir\n    }\n    fatalError(\"Unable to find macOS bundle root\")\n}\n#endif\n\npackage func resolveBinDir() throws -> AbsolutePath {\n#if os(macOS)\n    return try macOSBundleRoot()\n#else\n    guard let cwd = localFileSystem.currentWorkingDirectory else {\n        fatalError(\"Current working directory unavailable!\")\n    }\n    return try AbsolutePath(validating: CommandLine.arguments[0], relativeTo: cwd).parentDirectory\n#endif\n}\n\nextension SwiftSDK {\n    public static var `default`: Self {\n        get throws {\n            let binDir = try resolveBinDir()\n            return try! SwiftSDK.hostSwiftSDK(binDir, environment: .current)\n        }\n    }\n}\n\nextension UserToolchain {\n    public static var `default`: Self {\n        get throws {\n            return try .init(swiftSDK: SwiftSDK.default, environment: .current, fileSystem: localFileSystem)\n        }\n    }\n}\n\nextension UserToolchain {\n    /// Helper function to determine if async await actually works in the current environment.\n    public func supportsSwiftConcurrency() -> Bool {\n      #if os(macOS)\n        if #available(macOS 12.0, *) {\n            // On macOS 12 and later, concurrency is assumed to work.\n            return true\n        }\n        else {\n            // On macOS 11 and earlier, we don't know if concurrency actually works because not all SDKs and toolchains have the right bits.  We could examine the SDK and the various libraries, but the most accurate test is to just try to compile and run a snippet of code that requires async/await support.  It doesn't have to actually do anything, it's enough that all the libraries can be found (but because the library reference is weak we do need the linkage reference to `_swift_task_create` and the like).\n            do {\n                try testWithTemporaryDirectory { tmpPath in\n                    let inputPath = tmpPath.appending(\"foo.swift\")\n                    try localFileSystem.writeFileContents(inputPath, string: \"public func foo() async {}\\nTask { await foo() }\")\n                    let outputPath = tmpPath.appending(\"foo\")\n                    let toolchainPath = self.swiftCompilerPath.parentDirectory.parentDirectory\n                    let backDeploymentLibPath = toolchainPath.appending(components: \"lib\", \"swift-5.5\", \"macosx\")\n                    try AsyncProcess.checkNonZeroExit(arguments: [\"/usr/bin/xcrun\", \"--toolchain\", toolchainPath.pathString, \"swiftc\", inputPath.pathString, \"-Xlinker\", \"-rpath\", \"-Xlinker\", backDeploymentLibPath.pathString, \"-o\", outputPath.pathString])\n                    try AsyncProcess.checkNonZeroExit(arguments: [outputPath.pathString])\n                }\n            } catch {\n                // On any failure we assume false.\n                return false\n            }\n            // If we get this far we could compile and run a trivial executable that uses libConcurrency, so we can say that this toolchain supports concurrency on this host.\n            return true\n        }\n      #else\n        // On other platforms, concurrency is assumed to work since with new enough versions of the toolchain.\n        return true\n      #endif\n    }\n\n    /// Helper function to determine whether serialized diagnostics work properly in the current environment.\n    public func supportsSerializedDiagnostics(otherSwiftFlags: [String] = []) -> Bool {\n        do {\n            try testWithTemporaryDirectory { tmpPath in\n                let inputPath = tmpPath.appending(\"best.swift\")\n                try localFileSystem.writeFileContents(inputPath, string: \"func foo() -> Bool {\\nvar unused: Int\\nreturn true\\n}\\n\")\n                let outputPath = tmpPath.appending(\"foo\")\n                let serializedDiagnosticsPath = tmpPath.appending(\"out.dia\")\n                let toolchainPath = self.swiftCompilerPath.parentDirectory.parentDirectory\n                try AsyncProcess.checkNonZeroExit(\n                    arguments: [\n                        \"/usr/bin/xcrun\", \"--toolchain\", toolchainPath.pathString,\n                        \"swiftc\",\n                        inputPath.pathString,\n                        \"-Xfrontend\", \"-serialize-diagnostics-path\",\n                        \"-Xfrontend\", serializedDiagnosticsPath.pathString,\n                        \"-g\",\n                        \"-o\", outputPath.pathString\n                    ] + otherSwiftFlags\n                )\n                try AsyncProcess.checkNonZeroExit(arguments: [outputPath.pathString])\n\n                let diaFileContents = try localFileSystem.readFileContents(serializedDiagnosticsPath)\n                let diagnosticsSet = try SerializedDiagnostics(bytes: diaFileContents)\n                if diagnosticsSet.diagnostics.isEmpty {\n                    throw StringError(\"does not support diagnostics\")\n                }\n            }\n            return true\n        } catch {\n            return false\n        }\n    }\n\n    /// Helper function to determine whether we should run SDK-dependent tests.\n    public func supportsSDKDependentTests() -> Bool {\n        return ProcessInfo.processInfo.environment[\"SWIFTCI_DISABLE_SDK_DEPENDENT_TESTS\"] == nil\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/XCTAssertHelpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.ProcessInfo\nimport Basics\n#if os(macOS)\nimport class Foundation.Bundle\n#endif\nimport SPMBuildCore\nimport enum PackageModel.BuildConfiguration\nimport TSCTestSupport\nimport XCTest\nimport Testing\n\nimport struct Basics.AsyncProcessResult\n\nimport struct TSCUtility.Version\n\n@_exported import func TSCTestSupport.XCTAssertMatch\n@_exported import func TSCTestSupport.XCTAssertNoMatch\n@_exported import func TSCTestSupport.XCTAssertResultSuccess\n@_exported import func TSCTestSupport.XCTAssertThrows\n\nfileprivate func swiftTestingTestCalledAnXCTestAPI() {\n    if Test.current != nil {\n        Issue.record(\"Swift Testing Test called a XCTest API.\")\n    }\n}\n\npublic func XCTAssertFileExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {\n    TSCTestSupport.XCTAssertFileExists(TSCAbsolutePath(path), file: file, line: line)\n    swiftTestingTestCalledAnXCTestAPI()\n}\n\npublic func XCTAssertDirectoryExists(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {\n    TSCTestSupport.XCTAssertDirectoryExists(TSCAbsolutePath(path), file: file, line: line)\n    swiftTestingTestCalledAnXCTestAPI()\n}\n\npublic func XCTAssertNoSuchPath(_ path: AbsolutePath, file: StaticString = #file, line: UInt = #line) {\n    TSCTestSupport.XCTAssertNoSuchPath(TSCAbsolutePath(path), file: file, line: line)\n    swiftTestingTestCalledAnXCTestAPI()\n}\n\n\npublic func XCTAssertEqual<T:Equatable, U:Equatable> (_ lhs:(T,U), _ rhs:(T,U), file: StaticString = #file, line: UInt = #line) {\n    TSCTestSupport.XCTAssertEqual(lhs, rhs, file: file, line: line)\n    swiftTestingTestCalledAnXCTestAPI()\n}\n\npublic func XCTSkipIfPlatformCI(because reason: String? = nil, file: StaticString = #filePath, line: UInt = #line) throws {\n    // TODO: is this actually the right variable now?\n    if CiEnvironment.runningInSmokeTestPipeline {\n        let failureCause = reason ?? \"Skipping because the test is being run on CI\"\n        throw XCTSkip(failureCause, file: file, line: line)\n    }\n    swiftTestingTestCalledAnXCTestAPI()\n}\n\npublic func XCTSkipIfselfHostedCI(because reason: String, file: StaticString = #filePath, line: UInt = #line) throws {\n    // TODO: is this actually the right variable now?\n    if CiEnvironment.runningInSelfHostedPipeline {\n        throw XCTSkip(reason, file: file, line: line)\n    }\n    swiftTestingTestCalledAnXCTestAPI()\n}\n\npublic func XCTSkipOnWindows(because reason: String? = nil, skipPlatformCi: Bool = false, skipSelfHostedCI: Bool = false , file: StaticString = #filePath, line: UInt = #line) throws {\n    swiftTestingTestCalledAnXCTestAPI()\n    #if os(Windows)\n    let failureCause: String\n    if let reason {\n        failureCause = \" because \\(reason.description)\"\n    } else {\n        failureCause = \"\"\n    }\n    if (skipPlatformCi) {\n        try XCTSkipIfPlatformCI(because: \"Test is run in Platform CI.  Skipping\\(failureCause)\", file: file, line: line)\n    }\n\n    if (skipSelfHostedCI) {\n        try XCTSkipIfselfHostedCI(because: \"Test is run in Self hosted CI.  Skipping\\(failureCause)\", file: file, line: line)\n    }\n\n    if (!skipPlatformCi && !skipSelfHostedCI) {\n        throw XCTSkip(\"Skipping test\\(failureCause)\", file: file, line: line)\n    }\n    #endif\n}\n\npublic func _requiresTools(_ executable: String) throws {\n    func getAsyncProcessArgs(_ executable: String) -> [String] {\n        #if os(Windows)\n            let args = [\"cmd.exe\", \"/c\", \"where.exe\", executable]\n        #else\n            let args = [\"which\", executable]\n        #endif\n        return args\n    }\n    try AsyncProcess.checkNonZeroExit(arguments: getAsyncProcessArgs(executable))\n}\npublic func XCTRequires(\n    executable: String,\n    file: StaticString = #filePath,\n    line: UInt = #line\n) throws {\n    swiftTestingTestCalledAnXCTestAPI()\n\n    do {\n        try _requiresTools(executable)\n    } catch (let AsyncProcessResult.Error.nonZeroExit(result)) {\n        throw XCTSkip(\n            \"Skipping as tool \\(executable) is not found in the path. (\\(result.description))\")\n    }\n}\n\npublic func XCTSkipIfCompilerLessThan6_1() throws {\n    swiftTestingTestCalledAnXCTestAPI()\n    #if compiler(>=6.1)\n    #else\n        throw XCTSkip(\"Skipping as compiler version is less than 6.1\")\n    #endif\n}\n\npublic func XCTSkipIfCompilerLessThan6_2() throws {\n    swiftTestingTestCalledAnXCTestAPI()\n    #if compiler(>=6.2)\n    #else\n        throw XCTSkip(\"Skipping as compiler version is less than 6.2\")\n    #endif\n}\n\n/// An `async`-friendly replacement for `XCTAssertThrowsError`.\npublic func XCTAssertAsyncThrowsError<T>(\n    _ expression: @autoclosure () async throws -> T,\n    _ message: @autoclosure () -> String = \"\",\n    file: StaticString = #filePath,\n    line: UInt = #line,\n    _ errorHandler: (_ error: any Error) -> Void = { _ in }\n) async {\n    swiftTestingTestCalledAnXCTestAPI()\n    do {\n        _ = try await expression()\n        XCTFail(message(), file: file, line: line)\n    } catch {\n        errorHandler(error)\n    }\n}\n\npackage func XCTAssertAsyncNoThrow<T>(\n    _ expression: @autoclosure () async throws -> T,\n    _ message: @autoclosure () -> String = \"\",\n    file: StaticString = #filePath,\n    line: UInt = #line\n) async {\n    swiftTestingTestCalledAnXCTestAPI()\n    do {\n        _ = try await expression()\n    } catch {\n        XCTAssertNoThrow(try { throw error }(), message(), file: file, line: line)\n    }\n}\n\npublic func XCTAssertBuilds(\n    _ path: AbsolutePath,\n    configurations: Set<BuildConfiguration> = [.debug, .release],\n    extraArgs: [String] = [],\n    Xcc: [String] = [],\n    Xld: [String] = [],\n    Xswiftc: [String] = [],\n    env: Environment? = nil,\n    file: StaticString = #file,\n    line: UInt = #line,\n    buildSystem: BuildSystemProvider.Kind,\n) async {\n    swiftTestingTestCalledAnXCTestAPI()\n    for conf in configurations {\n        await XCTAssertAsyncNoThrow(\n            try await executeSwiftBuild(\n                path,\n                configuration: conf,\n                extraArgs: extraArgs,\n                Xcc: Xcc,\n                Xld: Xld,\n                Xswiftc: Xswiftc,\n                env: env,\n                buildSystem: buildSystem\n            ),\n            file: file,\n            line: line\n        )\n    }\n}\n\npublic func XCTAssertSwiftTest(\n    _ path: AbsolutePath,\n    configuration: BuildConfiguration = .debug,\n    extraArgs: [String] = [],\n    Xcc: [String] = [],\n    Xld: [String] = [],\n    Xswiftc: [String] = [],\n    env: Environment? = nil,\n    file: StaticString = #file,\n    line: UInt = #line,\n    buildSystem: BuildSystemProvider.Kind,\n) async {\n    swiftTestingTestCalledAnXCTestAPI()\n    await XCTAssertAsyncNoThrow(\n        try await executeSwiftTest(\n            path,\n            configuration: configuration,\n            extraArgs: extraArgs,\n            Xcc: Xcc,\n            Xld: Xld,\n            Xswiftc: Xswiftc,\n            env: env,\n            buildSystem: buildSystem\n        ),\n        file: file,\n        line: line\n    )\n}\n\n@discardableResult\npublic func XCTAssertBuildFails(\n    _ path: AbsolutePath,\n    Xcc: [String] = [],\n    Xld: [String] = [],\n    Xswiftc: [String] = [],\n    env: Environment? = nil,\n    file: StaticString = #file,\n    line: UInt = #line,\n    buildSystem: BuildSystemProvider.Kind,\n) async -> CommandExecutionError? {\n    swiftTestingTestCalledAnXCTestAPI()\n    var failure: CommandExecutionError? = nil\n    await XCTAssertThrowsCommandExecutionError(\n        try await executeSwiftBuild(\n            path,\n            Xcc: Xcc,\n            Xld: Xld,\n            Xswiftc: Xswiftc,\n            buildSystem: buildSystem\n        ),\n        file: file,\n        line: line\n    ) { error in\n        failure = error\n    }\n    return failure\n}\n\npublic func XCTAssertEqual<T: CustomStringConvertible>(\n    _ assignment: [(container: T, version: Version)],\n    _ expected: [T: Version],\n    file: StaticString = #file,\n    line: UInt = #line\n) where T: Hashable {\n    swiftTestingTestCalledAnXCTestAPI()\n    var actual = [T: Version]()\n    for (identifier, binding) in assignment {\n        actual[identifier] = binding\n    }\n    XCTAssertEqual(actual, expected, file: file, line: line)\n}\n\npublic func XCTAssertAsyncTrue(\n    _ expression: @autoclosure () async throws -> Bool,\n    _ message: @autoclosure () -> String = \"\",\n    file: StaticString = #filePath,\n    line: UInt = #line\n) async rethrows {\n    swiftTestingTestCalledAnXCTestAPI()\n    let result = try await expression()\n    XCTAssertTrue(result, message(), file: file, line: line)\n}\n\npublic func XCTAssertAsyncFalse(\n    _ expression: @autoclosure () async throws -> Bool,\n    _ message: @autoclosure () -> String = \"\",\n    file: StaticString = #filePath,\n    line: UInt = #line\n) async rethrows {\n    swiftTestingTestCalledAnXCTestAPI()\n    let result = try await expression()\n    XCTAssertFalse(result, message(), file: file, line: line)\n}\n\npackage func XCTAssertAsyncNil(\n    _ expression: @autoclosure () async throws -> Any?,\n    _ message: @autoclosure () -> String = \"\",\n    file: StaticString = #filePath,\n    line: UInt = #line\n) async rethrows {\n    swiftTestingTestCalledAnXCTestAPI()\n    let result = try await expression()\n    XCTAssertNil(result, message(), file: file, line: line)\n}\n\npublic func XCTAssertThrowsCommandExecutionError<T>(\n    _ expression: @autoclosure () async throws -> T,\n    _ message: @autoclosure () -> String = \"\",\n    file: StaticString = #filePath,\n    line: UInt = #line,\n    _ errorHandler: (_ error: CommandExecutionError) -> Void = { _ in }\n) async {\n    swiftTestingTestCalledAnXCTestAPI()\n    await XCTAssertAsyncThrowsError(try await expression(), message(), file: file, line: line) { error in\n        guard case SwiftPMError.executionFailure(let processError, let stdout, let stderr) = error,\n              case AsyncProcessResult.Error.nonZeroExit(let processResult) = processError,\n              processResult.exitStatus != .terminated(code: 0) else {\n            return XCTFail(\"Unexpected error type: \\(error.interpolationDescription)\", file: file, line: line)\n        }\n        errorHandler(CommandExecutionError(result: processResult, stdout: stdout, stderr: stderr))\n    }\n}\n\npublic func XCTAssertAsyncEqual<T: Equatable>(\n    _ expression1: @autoclosure () async throws -> T,\n    _ expression2: @autoclosure () async throws -> T,\n    _ message: @autoclosure () -> String = \"\",\n    file: StaticString = #file,\n    line: UInt = #line\n) async rethrows {\n    swiftTestingTestCalledAnXCTestAPI()\n    let value1 = try await expression1()\n    let value2 = try await expression2()\n\n    XCTAssertEqual(value1, value2, message(), file: file, line: line)\n}\n\nstruct XCAsyncTestErrorWhileUnwrappingOptional: Error {}\n\npublic func XCTAsyncUnwrap<T>(\n    _ expression: @autoclosure () async throws -> T?,\n    _ message: @autoclosure () -> String = \"\",\n    file: StaticString = #filePath,\n    line: UInt = #line\n) async throws -> T {\n    swiftTestingTestCalledAnXCTestAPI()\n    guard let result = try await expression() else {\n        throw XCAsyncTestErrorWhileUnwrappingOptional()\n    }\n\n    return result\n}\n\n\npublic struct CommandExecutionError: Error {\n    package let result: AsyncProcessResult\n    public let stdout: String\n    public let stderr: String\n    public let consoleOutput: String\n\n    package init(result: AsyncProcessResult, stdout: String, stderr: String) {\n        self.result = result\n        self.stdout = stdout\n        self.stderr = stderr\n        self.consoleOutput = stdout + stderr\n    }\n}\n"
  },
  {
    "path": "Sources/_InternalTestSupport/misc.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Basics\nimport struct Foundation.URL\n#if os(macOS)\nimport class Foundation.Bundle\n#endif\nimport OrderedCollections\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport PackageGraph\n\nimport PackageLoading\nimport PackageModel\nimport SourceControl\nimport SPMBuildCore\nimport struct SPMBuildCore.BuildParameters\nimport TSCTestSupport\nimport Workspace\nimport Testing\nimport func XCTest.XCTFail\nimport struct XCTest.XCTSkip\n\nimport class TSCBasic.Process\nimport struct TSCBasic.ByteString\nimport struct Basics.AsyncProcessResult\n\nimport enum TSCUtility.Git\n\n@_exported import enum TSCTestSupport.StringPattern\n\n@available(*, deprecated, message: \"Use CiEnvironment.runningInSmokeTestPipeline\")\npublic let isInCiEnvironment = CiEnvironment.runningInSmokeTestPipeline\n\n@available(*, deprecated, message: \"Use CiEnvironment.isSelfHostedCiEnvironment\")\npublic let isSelfHostedCiEnvironment = CiEnvironment.runningInSelfHostedPipeline\n\npublic struct CiEnvironmentStruct {\n    public let runningInSmokeTestPipeline = ProcessInfo.processInfo.environment[\"SWIFTCI_USE_LOCAL_DEPS\"] != nil\n    public let runningInSelfHostedPipeline = ProcessInfo.processInfo.environment[\"SWIFTCI_IS_SELF_HOSTED\"] != nil\n}\n\npublic let CiEnvironment = CiEnvironmentStruct()\n\npublic let isRealSigningIdentyEcLabelEnvVarSet =\n    ProcessInfo.processInfo.environment[\"REAL_SIGNING_IDENTITY_EC_LABEL\"] != nil\n\npublic let isRealSigningIdentitTestDefined = {\n    #if ENABLE_REAL_SIGNING_IDENTITY_TEST\n        return true\n    #else\n        return false\n    #endif\n}()\n\npublic let duplicateSymbolRegex: Regex<AnyRegexOutput>? = {\n    do {\n        return try Regex(\".*One of the duplicates must be removed or renamed.\")\n    } catch {\n        return nil\n    }\n}()\n\n/// Test helper utility for executing a block with a temporary directory.\npublic func testWithTemporaryDirectory(\n    function: StaticString = #function,\n    body: (AbsolutePath) throws -> Void\n) throws {\n    let body2 = { (path: TSCAbsolutePath) in\n        try body(AbsolutePath(path))\n    }\n\n    try TSCTestSupport.testWithTemporaryDirectory(\n        function: function,\n        body: body2\n    )\n}\n\n@discardableResult\npublic func testWithTemporaryDirectory<Result>(\n    function: StaticString = #function,\n    body: (AbsolutePath) async throws -> Result\n) async throws -> Result {\n    let cleanedFunction = function.description\n        .replacing(\"(\", with: \"\")\n        .replacing(\")\", with: \"\")\n        .replacing(\".\", with: \"\")\n        .replacing(\":\", with: \"_\")\n    return try await withTemporaryDirectory(prefix: \"spm-tests-\\(cleanedFunction)\") { tmpDirPath in\n        defer {\n            // Unblock and remove the tmp dir on deinit.\n            try? localFileSystem.chmod(.userWritable, path: tmpDirPath, options: [.recursive])\n            try? localFileSystem.removeFileTree(tmpDirPath)\n        }\n        return try await body(tmpDirPath)\n    }\n}\n\n/// Test-helper function that runs a block of code on a copy of a test fixture\n/// package.  The copy is made into a temporary directory, and the block is\n/// given a path to that directory.  The block is permitted to modify the copy.\n/// The temporary copy is deleted after the block returns.  The fixture name may\n/// contain `/` characters, which are treated as path separators, exactly as if\n/// the name were a relative path.\n@available(*, deprecated, message: \"Migrate test to Swift Testing and use 'fixture' instead\")\n@discardableResult public func fixtureXCTest<T>(\n    name: String,\n    createGitRepo: Bool = false,\n    file: StaticString = #file,\n    line: UInt = #line,\n    body: (AbsolutePath) throws -> T\n) throws -> T {\n    do {\n        // Make a suitable test directory name from the fixture subpath.\n        let fixtureSubpath = try RelativePath(validating: name)\n        let copyName = fixtureSubpath.components.joined(separator: \"_\")\n\n        // Create a temporary directory for the duration of the block.\n        return try withTemporaryDirectory(prefix: copyName) { tmpDirPath in\n\n            defer {\n                // Unblock and remove the tmp dir on deinit.\n                try? localFileSystem.chmod(.userWritable, path: tmpDirPath, options: [.recursive])\n                try? localFileSystem.removeFileTree(tmpDirPath)\n            }\n\n            let fixtureDir = try verifyFixtureExists(at: fixtureSubpath, file: file, line: line)\n            let preparedFixture = try setup(\n                fixtureDir: fixtureDir,\n                in: tmpDirPath,\n                copyName: copyName,\n                createGitRepo:createGitRepo\n            )\n            return try body(preparedFixture)\n        }\n    } catch SwiftPMError.executionFailure(let error, let output, let stderr) {\n        print(\"**** FAILURE EXECUTING SUBPROCESS ****\")\n        print(\"output:\", output)\n        print(\"stderr:\", stderr)\n        throw error\n    }\n}\n\n@discardableResult public func fixture<T>(\n    name: String,\n    createGitRepo: Bool = false,\n    removeFixturePathOnDeinit: Bool = true,\n    file: StaticString = #file,\n    line: UInt = #line,\n    sourceLocation: SourceLocation = #_sourceLocation,\n    body: (AbsolutePath) throws -> T\n) throws -> T {\n    do {\n        // Make a suitable test directory name from the fixture subpath.\n        let fixtureSubpath = try RelativePath(validating: name)\n        let copyName = fixtureSubpath.components.joined(separator: \"_\")\n\n        // Create a temporary directory for the duration of the block.\n        return try withTemporaryDirectory(\n            prefix: copyName,\n            removeTreeOnDeinit: removeFixturePathOnDeinit,\n        ) { tmpDirPath in\n\n            defer {\n                if removeFixturePathOnDeinit {\n                    // Unblock and remove the tmp dir on deinit.\n                    try? localFileSystem.chmod(.userWritable, path: tmpDirPath, options: [.recursive])\n                    try? localFileSystem.removeFileTree(tmpDirPath)\n                }\n            }\n\n            let fixtureDir = try verifyFixtureExists(at: fixtureSubpath, sourceLocation: sourceLocation)\n            let preparedFixture = try setup(\n                fixtureDir: fixtureDir,\n                in: tmpDirPath,\n                copyName: copyName,\n                createGitRepo:createGitRepo\n            )\n            return try body(preparedFixture)\n        }\n    } catch SwiftPMError.executionFailure(let error, let output, let stderr) {\n        print(\"**** FAILURE EXECUTING SUBPROCESS ****\")\n        print(\"output:\", output)\n        print(\"stderr:\", stderr)\n        throw error\n    }\n}\n\npublic enum TestError: Error {\n    case platformNotSupported\n}\n\n@available(*, deprecated, message: \"Migrate test to Swift Testing and use 'fixture' instead\")\n@discardableResult public func fixtureXCTest<T>(\n    name: String,\n    createGitRepo: Bool = false,\n    file: StaticString = #file,\n    line: UInt = #line,\n    body: (AbsolutePath) async throws -> T\n) async throws -> T {\n    do {\n        // Make a suitable test directory name from the fixture subpath.\n        let fixtureSubpath = try RelativePath(validating: name)\n        let copyName = fixtureSubpath.components.joined(separator: \"_\")\n\n        // Create a temporary directory for the duration of the block.\n        return try await withTemporaryDirectory(prefix: copyName) { tmpDirPath in\n\n            defer {\n                // Unblock and remove the tmp dir on deinit.\n                try? localFileSystem.chmod(.userWritable, path: tmpDirPath, options: [.recursive])\n                try? localFileSystem.removeFileTree(tmpDirPath)\n            }\n\n            let fixtureDir = try verifyFixtureExists(at: fixtureSubpath, file: file, line: line)\n            let preparedFixture = try setup(\n                fixtureDir: fixtureDir,\n                in: tmpDirPath,\n                copyName: copyName,\n                createGitRepo:createGitRepo\n            )\n            return try await body(preparedFixture)\n        }\n    } catch SwiftPMError.executionFailure(let error, let output, let stderr) {\n        print(\"**** FAILURE EXECUTING SUBPROCESS ****\")\n        print(\"output:\", output)\n        print(\"stderr:\", stderr)\n        throw error\n    }\n}\n\n@discardableResult public func fixture<T>(\n    name: String,\n    createGitRepo: Bool = false,\n    removeFixturePathOnDeinit: Bool = true,\n    file: StaticString = #file,\n    line: UInt = #line,\n    sourceLocation: SourceLocation = #_sourceLocation,\n    body: (AbsolutePath) async throws -> T\n) async throws -> T {\n    do {\n        // Make a suitable test directory name from the fixture subpath.\n        let fixtureSubpath = try RelativePath(validating: name)\n        let copyName = fixtureSubpath.components.last!\n\n        // Create a temporary directory for the duration of the block.\n        return try await withTemporaryDirectory(\n            prefix: copyName,\n            removeTreeOnDeinit: removeFixturePathOnDeinit\n        ) { tmpDirPath in\n\n            defer {\n                if removeFixturePathOnDeinit {\n                    // Unblock and remove the tmp dir on deinit.\n                    try? localFileSystem.chmod(.userWritable, path: tmpDirPath, options: [.recursive])\n                    try? localFileSystem.removeFileTree(tmpDirPath)\n                }\n            }\n\n            let fixtureDir = try verifyFixtureExists(at: fixtureSubpath, file: file, line: line, sourceLocation: sourceLocation)\n            let preparedFixture = try setup(\n                fixtureDir: fixtureDir,\n                in: tmpDirPath,\n                copyName: copyName,\n                createGitRepo:createGitRepo\n            )\n            return try await body(preparedFixture)\n        }\n    } catch SwiftPMError.executionFailure(let error, let output, let stderr) {\n        print(\"**** FAILURE EXECUTING SUBPROCESS ****\")\n        print(\"output:\", output)\n        print(\"stderr:\", stderr)\n        throw error\n    }\n}\n\nfileprivate func verifyFixtureExists(\n    at fixtureSubpath: RelativePath,\n    file: StaticString = #file,\n    line: UInt = #line,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) throws -> AbsolutePath {\n    let fixtureDir = AbsolutePath(\"../../../Fixtures\", relativeTo: #file)\n        .appending(fixtureSubpath)\n\n    // Check that the fixture is really there.\n    guard localFileSystem.isDirectory(fixtureDir) else {\n        if Test.current != nil {\n            Issue.record(\n                \"No such fixture: \\(fixtureDir)\",\n                sourceLocation: sourceLocation,\n            )\n        } else {\n            XCTFail(\"No such fixture: \\(fixtureDir)\", file: file, line: line)\n        }\n        throw SwiftPMError.packagePathNotFound\n    }\n\n    return fixtureDir\n}\n\nfileprivate func setup(\n    fixtureDir: AbsolutePath,\n    in tmpDirPath: AbsolutePath,\n    copyName: String,\n    createGitRepo: Bool,\n) throws -> AbsolutePath {\n    func copy(from srcDir: AbsolutePath, to dstDir: AbsolutePath) throws {\n\n        // Pure Swift copy implementation that follows symlinks\n        func copyItem(from source: AbsolutePath, to destination: AbsolutePath) throws {\n            // Resolve symlinks to follow them\n            let resolvedSource: AbsolutePath\n            if localFileSystem.isSymlink(source) {\n                resolvedSource = try resolveSymlinks(source)\n            } else {\n                resolvedSource = source\n            }\n\n            if localFileSystem.isDirectory(resolvedSource) {\n                // Create destination directory if it doesn't exist\n                if !localFileSystem.exists(destination) {\n                    try localFileSystem.createDirectory(destination, recursive: true)\n                }\n\n                // Recursively copy directory contents\n                let contents = try localFileSystem.getDirectoryContents(resolvedSource)\n                for item in contents {\n                    let sourcePath = resolvedSource.appending(component: item)\n                    let destPath = destination.appending(component: item)\n                    try copyItem(from: sourcePath, to: destPath)\n                }\n            } else if localFileSystem.isFile(resolvedSource) {\n                try localFileSystem.copy(from: resolvedSource, to: destination)\n\n                // Preserve executable permission if the source file is executable\n                #if !os(Windows)\n                if localFileSystem.isExecutableFile(resolvedSource) {\n                    try localFileSystem.chmod(.executable, path: destination, options: [])\n                }\n                #endif\n            }\n        }\n\n        try copyItem(from: srcDir, to: dstDir)\n        // Ensure we get a clean test fixture.\n        try localFileSystem.removeFileTree(dstDir.appending(component: \".build\"))\n        try localFileSystem.removeFileTree(dstDir.appending(component: \".swiftpm\"))\n    }\n\n    // The fixture contains either a checkout or just a Git directory.\n    if localFileSystem.isFile(fixtureDir.appending(\"Package.swift\")) {\n        // It's a single package, so copy the whole directory as-is.\n        let dstDir = tmpDirPath.appending(component: copyName)\n        try copy(from: fixtureDir, to: dstDir)\n        // Invoke the block, passing it the path of the copied fixture.\n        return dstDir\n    }\n    // Copy each of the package directories and construct a git repo in it.\n    for fileName in try localFileSystem.getDirectoryContents(fixtureDir).sorted() {\n        let srcDir = fixtureDir.appending(component: fileName)\n        guard localFileSystem.isDirectory(srcDir) else { continue }\n        let dstDir = tmpDirPath.appending(component: fileName)\n\n        try copy(from: srcDir, to: dstDir)\n        if createGitRepo {\n            initGitRepo(dstDir, tag: \"1.2.3\", addFile: false)\n        }\n    }\n    return tmpDirPath\n}\n\n/// Test-helper function that creates a new Git repository in a directory.  The new repository will contain\n/// exactly one empty file unless `addFile` is `false`, and if a tag name is provided, a tag with that name will be\n/// created.\npublic func initGitRepo(\n    _ dir: AbsolutePath,\n    tag: String? = nil,\n    addFile: Bool = true,\n    file: StaticString = #file,\n    line: UInt = #line\n) {\n    initGitRepo(dir, tags: tag.flatMap { [$0] } ?? [], addFile: addFile, file: file, line: line)\n}\n\npublic func initGitRepo(\n    _ dir: AbsolutePath,\n    tags: [String],\n    addFile: Bool = true,\n    file: StaticString = #file,\n    line: UInt = #line,\n    sourceLocation: SourceLocation = #_sourceLocation,\n) {\n    do {\n        if addFile {\n            let file = dir.appending(\"file.swift\")\n            try localFileSystem.writeFileContents(file, bytes: \"\")\n        }\n\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", dir.pathString, \"init\")\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", dir.pathString, \"config\", \"user.email\", \"example@example.com\")\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", dir.pathString, \"config\", \"user.name\", \"Example Example\")\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", dir.pathString, \"config\", \"commit.gpgsign\", \"false\")\n        let repo = GitRepository(path: dir)\n        try repo.stageEverything()\n        try repo.commit(message: \"msg\")\n        for tag in tags {\n            try repo.tag(name: tag)\n        }\n        try Process.checkNonZeroExit(args: Git.tool, \"-C\", dir.pathString, \"branch\", \"-m\", \"main\")\n    } catch {\n        if Test.current != nil {\n            Issue.record(\n                \"\\(error.interpolationDescription)\",\n                sourceLocation: sourceLocation,\n            )\n        } else {\n            XCTFail(\"\\(error.interpolationDescription)\", file: file, line: line)\n        }\n    }\n}\n\npublic func getBuildSystemArgs(for buildSystem: BuildSystemProvider.Kind?) -> [String] {\n    guard let system = buildSystem else { return [] }\n\n    return [\n        \"--build-system\",\n        \"\\(system)\"\n    ]\n}\n\n@discardableResult\npublic func executeSwiftBuild(\n    _ packagePath: AbsolutePath?,\n    configuration: BuildConfiguration = .debug,\n    extraArgs: [String] = [],\n    Xcc: [String] = [],\n    Xld: [String] = [],\n    Xswiftc: [String] = [],\n    env: Environment? = nil,\n    buildSystem: BuildSystemProvider.Kind,\n    throwIfCommandFails: Bool = true,\n) async throws -> (stdout: String, stderr: String) {\n    let args = swiftArgs(\n        configuration: configuration,\n        extraArgs: extraArgs,\n        Xcc: Xcc,\n        Xld: Xld,\n        Xswiftc: Xswiftc,\n        buildSystem: buildSystem\n    )\n    return try await SwiftPM.Build.execute(args, packagePath: packagePath, env: env, throwIfCommandFails: throwIfCommandFails)\n}\n\n@discardableResult\npublic func executeSwiftRun(\n    _ packagePath: AbsolutePath?,\n    _ executable: String?,\n    configuration: BuildConfiguration = .debug,\n    extraArgs: [String] = [],\n    Xcc: [String] = [],\n    Xld: [String] = [],\n    Xswiftc: [String] = [],\n    env: Environment? = nil,\n    buildSystem: BuildSystemProvider.Kind,\n) async throws -> (stdout: String, stderr: String) {\n    var args = swiftArgs(\n        configuration: configuration,\n        extraArgs: extraArgs,\n        Xcc: Xcc,\n        Xld: Xld,\n        Xswiftc: Xswiftc,\n        buildSystem: buildSystem\n    )\n    if let executable {\n        args.append(executable)\n    }\n    return try await SwiftPM.Run.execute(args, packagePath: packagePath, env: env)\n}\n\n@discardableResult\npublic func executeSwiftPackage(\n    _ packagePath: AbsolutePath?,\n    configuration: BuildConfiguration = .debug,\n    extraArgs: [String] = [],\n    Xcc: [String] = [],\n    Xld: [String] = [],\n    Xswiftc: [String] = [],\n    env: Environment? = nil,\n    buildSystem: BuildSystemProvider.Kind,\n) async throws -> (stdout: String, stderr: String) {\n    let args = swiftArgs(\n        configuration: configuration,\n        extraArgs: extraArgs,\n        Xcc: Xcc,\n        Xld: Xld,\n        Xswiftc: Xswiftc,\n        buildSystem: buildSystem\n    )\n    return try await SwiftPM.Package.execute(args, packagePath: packagePath, env: env)\n}\n\n@discardableResult\npublic func executeSwiftPackageRegistry(\n    _ packagePath: AbsolutePath?,\n    configuration: BuildConfiguration = .debug,\n    extraArgs: [String] = [],\n    Xcc: [String] = [],\n    Xld: [String] = [],\n    Xswiftc: [String] = [],\n    env: Environment? = nil,\n    buildSystem: BuildSystemProvider.Kind,\n) async throws -> (stdout: String, stderr: String) {\n    let args = swiftArgs(\n        configuration: configuration,\n        extraArgs: extraArgs,\n        Xcc: Xcc,\n        Xld: Xld,\n        Xswiftc: Xswiftc,\n        buildSystem: buildSystem\n    )\n    return try await SwiftPM.Registry.execute(args, packagePath: packagePath, env: env)\n}\n\n@discardableResult\npublic func executeSwiftTest(\n    _ packagePath: AbsolutePath?,\n    configuration: BuildConfiguration = .debug,\n    extraArgs: [String] = [],\n    Xcc: [String] = [],\n    Xld: [String] = [],\n    Xswiftc: [String] = [],\n    env: Environment? = nil,\n    buildSystem: BuildSystemProvider.Kind,\n    throwIfCommandFails: Bool = false,\n) async throws -> (stdout: String, stderr: String) {\n    let args = swiftArgs(\n        configuration: configuration,\n        extraArgs: extraArgs,\n        Xcc: Xcc,\n        Xld: Xld,\n        Xswiftc: Xswiftc,\n        buildSystem: buildSystem\n    )\n    return try await SwiftPM.Test.execute(args, packagePath: packagePath, env: env, throwIfCommandFails: throwIfCommandFails)\n}\n\nprivate func swiftArgs(\n    configuration: BuildConfiguration,\n    extraArgs: [String],\n    Xcc: [String],\n    Xld: [String],\n    Xswiftc: [String],\n    buildSystem: BuildSystemProvider.Kind?\n) -> [String] {\n    var args = [\"--configuration\"]\n    switch configuration {\n    case .debug:\n        args.append(\"debug\")\n    case .release:\n        args.append(\"release\")\n    }\n\n    args += Xcc.flatMap { [\"-Xcc\", $0] }\n    args += Xld.flatMap { [\"-Xlinker\", $0] }\n    args += Xswiftc.flatMap { [\"-Xswiftc\", $0] }\n    args += getBuildSystemArgs(for: buildSystem)\n    args += extraArgs\n    return args\n}\n\n@available(*,\n    deprecated,\n    renamed: \"loadModulesGraph\",\n    message: \"Rename for consistency: the type of this functions return value is named `ModulesGraph`.\"\n)\npublic func loadPackageGraph(\n    identityResolver: IdentityResolver = DefaultIdentityResolver(),\n    fileSystem: FileSystem,\n    manifests: [Manifest],\n    binaryArtifacts: [PackageIdentity: [String: BinaryArtifact]] = [:],\n    explicitProduct: String? = .none,\n    shouldCreateMultipleTestProducts: Bool = false,\n    createREPLProduct: Bool = false,\n    useXCBuildFileRules: Bool = false,\n    customXCTestMinimumDeploymentTargets: [PackageModel.Platform: PlatformVersion]? = .none,\n    observabilityScope: ObservabilityScope,\n    traitConfiguration: TraitConfiguration = .default\n) throws -> ModulesGraph {\n    try loadModulesGraph(\n        identityResolver: identityResolver,\n        fileSystem: fileSystem,\n        manifests: manifests,\n        binaryArtifacts: binaryArtifacts,\n        explicitProduct: explicitProduct,\n        shouldCreateMultipleTestProducts: shouldCreateMultipleTestProducts,\n        createREPLProduct: createREPLProduct,\n        useXCBuildFileRules: useXCBuildFileRules,\n        customXCTestMinimumDeploymentTargets: customXCTestMinimumDeploymentTargets,\n        observabilityScope: observabilityScope,\n        traitConfiguration: traitConfiguration\n    )\n}\n\npublic let emptyZipFile = ByteString([0x80, 0x75, 0x05, 0x06] + [UInt8](repeating: 0x00, count: 18))\n\nextension FileSystem {\n    @_disfavoredOverload\n    public func createEmptyFiles(at root: AbsolutePath, files: String...) {\n        self.createEmptyFiles(at: TSCAbsolutePath(root), files: files)\n    }\n\n    @_disfavoredOverload\n    public func createEmptyFiles(at root: AbsolutePath, files: [String]) {\n        self.createEmptyFiles(at: TSCAbsolutePath(root), files: files)\n    }\n}\n\nextension URL {\n    public init(_ value: StringLiteralType) {\n        self.init(string: value)!\n    }\n}\n\nextension URL {\n    public init(stringLiteral value: String) {\n        self.init(string: value)!\n    }\n}\n\nextension PackageIdentity {\n    public init(stringLiteral value: String) {\n        self = Self.plain(value)\n    }\n}\n\nextension PackageIdentity {\n    public static func registry(_ value: String) -> RegistryIdentity {\n        Self.plain(value).registry!\n    }\n}\n\nextension AbsolutePath {\n    public init(_ value: StringLiteralType) {\n        try! self.init(validating: value)\n    }\n}\n\nextension AbsolutePath {\n    public init(stringLiteral value: String) {\n        try! self.init(validating: value)\n    }\n}\n\nextension AbsolutePath {\n    public init(_ path: StringLiteralType, relativeTo basePath: AbsolutePath) {\n        try! self.init(validating: path, relativeTo: basePath)\n    }\n}\n\nextension RelativePath {\n    @available(*, deprecated, message: \"use direct string instead\")\n    public init(static path: StaticString) {\n        let pathString = path.withUTF8Buffer {\n            String(decoding: $0, as: UTF8.self)\n        }\n        try! self.init(validating: pathString)\n    }\n}\n\nextension RelativePath {\n    public init(_ value: StringLiteralType) {\n        try! self.init(validating: value)\n    }\n}\n\nextension RelativePath {\n    public init(stringLiteral value: String) {\n        try! self.init(validating: value)\n    }\n}\n\nextension InitPackage {\n    public convenience init(\n        name: String,\n        packageType: PackageType,\n        supportedTestingLibraries: Set<TestingLibrary> = [.swiftTesting],\n        destinationPath: AbsolutePath,\n        fileSystem: FileSystem,\n        swiftLanguageModes: [SwiftLanguageVersion] = []\n    ) throws {\n        try self.init(\n            name: name,\n            options: InitPackageOptions(packageType: packageType, supportedTestingLibraries: supportedTestingLibraries, swiftLanguageModes: swiftLanguageModes),\n            destinationPath: destinationPath,\n            installedSwiftPMConfiguration: .default,\n            fileSystem: fileSystem\n        )\n    }\n}\n\nextension RelativePath: ExpressibleByStringLiteral {}\nextension RelativePath: ExpressibleByStringInterpolation {}\nextension URL: @retroactive ExpressibleByStringLiteral {}\nextension URL: @retroactive ExpressibleByStringInterpolation {}\nextension PackageIdentity: ExpressibleByStringLiteral {}\nextension PackageIdentity: ExpressibleByStringInterpolation {}\nextension AbsolutePath: ExpressibleByStringLiteral {}\nextension AbsolutePath: ExpressibleByStringInterpolation {}\n\npublic func getNumberOfMatches(of match: String, in value: String) -> Int {\n    guard match.count != 0 else { return 0 }\n    return value.ranges(of: match).count\n}\n\npublic extension String {\n    var withSwiftLineEnding: String {\n        return replacingOccurrences(of: \"\\r\\n\", with: \"\\n\")\n    }\n}\n\npublic func executableName(_ name: String) -> String {\n#if os(Windows)\n  if name.count > 4, name.suffix(from: name.index(name.endIndex, offsetBy: -4)) == ProcessInfo.exeSuffix {\n    return name\n  }\n  return \"\\(name)\\(ProcessInfo.exeSuffix)\"\n#else\n  return name\n#endif\n}\n\npackage func getCoveragePath(\n    _ path: AbsolutePath,\n    with buildData: BuildData,\n) async throws -> String {\n    return try await executeSwiftTest(\n            path,\n            configuration: buildData.config,\n            extraArgs: [\n                \"--show-coverage-path\",\n            ],\n            buildSystem: buildData.buildSystem,\n            throwIfCommandFails: true,\n        ).stdout.trimmingCharacters(in: .whitespacesAndNewlines)\n}\n"
  },
  {
    "path": "Sources/dummy-swiftc/main.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n// This program can be used as `swiftc` in order to influence `-version` output\n\nimport Foundation\n\nimport class Basics.AsyncProcess\n\nlet info = ProcessInfo.processInfo\nlet env = info.environment\n\nif info.arguments.last == \"-version\" {\n    if let customSwiftVersion = env[\"CUSTOM_SWIFT_VERSION\"] {\n        print(customSwiftVersion)\n    } else {\n        print(\"999.0\")\n    }\n} else {\n    let swiftPath: String\n    if let swiftOriginalPath = env[\"SWIFT_ORIGINAL_PATH\"] {\n        swiftPath = swiftOriginalPath\n    } else {\n        fatalError(\"need `SWIFT_ORIGINAL_PATH` in the environment\")\n    }\n\n    let result = try AsyncProcess.popen(arguments: [swiftPath] + info.arguments.dropFirst())\n    print(try result.utf8Output())\n    print(try result.utf8stderrOutput())\n}\n"
  },
  {
    "path": "Sources/swift-bootstrap/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2022 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_executable(swift-bootstrap\n    main.swift)\ntarget_link_libraries(swift-bootstrap PRIVATE\n  ArgumentParser\n  Basics\n  Build\n  PackageGraph\n  PackageLoading\n  PackageModel\n  SwiftDriver\n  TSCBasic\n  TSCUtility\n  XCBuildSupport\n  SwiftBuildSupport)\n"
  },
  {
    "path": "Sources/swift-bootstrap/main.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport ArgumentParser\nimport Basics\nimport _Concurrency\nimport Build\nimport Dispatch\n\n@_spi(SwiftPMInternal)\nimport DriverSupport\n\nimport Foundation\nimport OrderedCollections\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SPMBuildCore\nimport XCBuildSupport\nimport SwiftBuildSupport\n\nimport struct TSCBasic.KeyedPair\nimport func TSCBasic.topologicalSort\nimport var TSCBasic.stdoutStream\nimport enum TSCBasic.GraphError\nimport struct TSCBasic.OrderedSet\nimport enum TSCUtility.Diagnostics\nimport struct TSCUtility.Version\n\nawait { () async in\n    await SwiftBootstrapBuildTool.main()\n}()\n\nstruct SwiftBootstrapBuildTool: AsyncParsableCommand {\n    static let configuration = CommandConfiguration(\n        commandName: \"swift-bootstrap\",\n        abstract: \"Bootstrapping build tool, only use in the context of bootstrapping SwiftPM itself.\",\n        shouldDisplay: false\n    )\n\n    @Option(name: .customLong(\"package-path\"),\n            help: \"Specify the package path to operate on (default current directory). This changes the working directory before any other operation.\",\n            completion: .directory)\n    public var packageDirectory: AbsolutePath?\n\n    /// The custom .build directory, if provided.\n    @Option(name: .customLong(\"scratch-path\"), help: \"Specify a custom scratch directory path (default .build).\", completion: .directory)\n    var _scratchDirectory: AbsolutePath?\n\n    @Option(name: .customLong(\"build-path\"), help: .hidden)\n    var _deprecated_buildPath: AbsolutePath?\n\n    var scratchDirectory: AbsolutePath? {\n        self._scratchDirectory ?? self._deprecated_buildPath\n    }\n\n    @Option(name: .shortAndLong, help: \"Build with configuration.\")\n    public var configuration: BuildConfiguration = .debug\n\n    @Option(name: .customLong(\"Xcc\", withSingleDash: true),\n            parsing: .unconditionalSingleValue,\n            help: \"Pass flag through to all C compiler invocations.\")\n    var cCompilerFlags: [String] = []\n\n    @Option(name: .customLong(\"Xswiftc\", withSingleDash: true),\n            parsing: .unconditionalSingleValue,\n            help: \"Pass flag through to all Swift compiler invocations.\")\n    var swiftCompilerFlags: [String] = []\n\n    @Option(name: .customLong(\"Xlinker\", withSingleDash: true),\n            parsing: .unconditionalSingleValue,\n            help: \"Pass flag through to all linker invocations.\")\n    var linkerFlags: [String] = []\n\n    @Option(name: .customLong(\"Xcxx\", withSingleDash: true),\n            parsing: .unconditionalSingleValue,\n            help: \"Pass flag through to all C++ compiler invocations.\")\n    var cxxCompilerFlags: [String] = []\n\n    @Option(name: .customLong(\"Xxcbuild\", withSingleDash: true),\n            parsing: .unconditionalSingleValue,\n            help: ArgumentHelp(\n                \"Pass flag through to the Xcode build system invocations.\",\n                visibility: .hidden))\n    public var xcbuildFlags: [String] = []\n\n    @Option(name: .customLong(\"Xbuild-tools-swiftc\", withSingleDash: true),\n            parsing: .unconditionalSingleValue,\n            help: ArgumentHelp(\"Pass flag to the manifest build invocation.\",\n                               visibility: .hidden))\n    public var manifestFlags: [String] = []\n\n    @Option(\n      name: .customLong(\"arch\"),\n      help: ArgumentHelp(\"Build the package for the these architectures.\", visibility: .hidden))\n    public var architectures: [String] = []\n\n    /// The verbosity of informational output.\n    @Flag(name: .shortAndLong, help: \"Increase verbosity to include informational output.\")\n    public var verbose: Bool = false\n\n    /// The verbosity of informational output.\n    @Flag(name: [.long, .customLong(\"vv\")], help: \"Increase verbosity to include debug output.\")\n    public var veryVerbose: Bool = false\n\n    /// Whether to use the integrated Swift driver rather than shelling out\n    /// to a separate process.\n    @Flag()\n    public var useIntegratedSwiftDriver: Bool = false\n\n    /// An option that indicates this build should check whether targets only import\n    /// their explicitly-declared dependencies\n    @Option(help: \"Check that targets only import their explicitly-declared dependencies.\")\n    public var explicitTargetDependencyImportCheck: TargetDependencyImportCheckingMode = .none\n\n    enum TargetDependencyImportCheckingMode: String, Codable, ExpressibleByArgument, CaseIterable {\n        case none\n        case error\n    }\n\n    /// Disables adding $ORIGIN/@loader_path to the rpath, useful when deploying\n    @Flag(name: .customLong(\"disable-local-rpath\"), help: \"Disable adding $ORIGIN/@loader_path to the rpath by default.\")\n    public var shouldDisableLocalRpath: Bool = false\n\n    /// The build system to use.\n    @Option(\n        name: .customLong(\"build-system\"),\n        help: \"The build system to use.\",\n    )\n    var _buildSystem: BuildSystemProvider.Kind = .native\n\n    private var buildSystem: BuildSystemProvider.Kind {\n        #if os(macOS)\n        // Force the Xcode build system if we want to build more than one arch.\n        return self.architectures.count > 1 ? .xcode : self._buildSystem\n        #else\n        // Use whatever the build system provided by the command-line, or default fallback\n        //  on other platforms.\n        return self._buildSystem\n        #endif\n    }\n\n    public var buildFlags: BuildFlags {\n        BuildFlags(\n            cCompilerFlags: self.cCompilerFlags.constructBuildFlags(source: .commandLineOptions),\n            cxxCompilerFlags: self.cxxCompilerFlags.constructBuildFlags(source: .commandLineOptions),\n            swiftCompilerFlags: self.swiftCompilerFlags.constructBuildFlags(source: .commandLineOptions),\n            linkerFlags: self.linkerFlags.constructBuildFlags(source: .commandLineOptions),\n            xcbuildFlags: self.xcbuildFlags\n        )\n    }\n\n    private var logLevel: Basics.Diagnostic.Severity {\n        if self.verbose {\n            return .info\n        } else if self.veryVerbose {\n            return .debug\n        } else {\n            return .warning\n        }\n    }\n\n    public init() {}\n\n    public func run() async throws {\n        do {\n            let fileSystem = localFileSystem\n\n            let observabilityScope = ObservabilitySystem({ _, diagnostics in\n                if diagnostics.severity >= logLevel {\n                    print(diagnostics)\n                }\n            }, outputStream: stdoutStream, logLevel: .debug).topScope\n\n            guard let cwd: AbsolutePath = fileSystem.currentWorkingDirectory else {\n                observabilityScope.emit(error: \"couldn't determine the current working directory\")\n                throw ExitCode.failure\n            }\n\n            guard let packagePath = packageDirectory ?? localFileSystem.currentWorkingDirectory else {\n                throw StringError(\"unknown package path\")\n            }\n\n            let scratchDirectory =\n                try BuildSystemUtilities.getEnvBuildPath(workingDir: cwd) ??\n                self.scratchDirectory ??\n                packagePath.appending(\".build\")\n\n            let builder = try Builder(\n                fileSystem: localFileSystem,\n                observabilityScope: observabilityScope,\n                logLevel: self.logLevel\n            )\n\n            try await builder.build(\n                packagePath: packagePath,\n                scratchDirectory: scratchDirectory,\n                buildSystem: self.buildSystem,\n                configuration: self.configuration,\n                architectures: self.architectures,\n                buildFlags: self.buildFlags,\n                manifestBuildFlags: self.manifestFlags,\n                useIntegratedSwiftDriver: self.useIntegratedSwiftDriver,\n                explicitTargetDependencyImportCheck: self.explicitTargetDependencyImportCheck,\n                shouldDisableLocalRpath: self.shouldDisableLocalRpath\n            )\n        } catch _ as Diagnostics {\n            throw ExitCode.failure\n        }\n    }\n\n    struct Builder {\n        let identityResolver: IdentityResolver\n        let dependencyMapper: DependencyMapper\n        let hostToolchain: UserToolchain\n        let targetToolchain: UserToolchain\n        let fileSystem: FileSystem\n        let observabilityScope: ObservabilityScope\n        let logLevel: Basics.Diagnostic.Severity\n\n        init(fileSystem: FileSystem, observabilityScope: ObservabilityScope, logLevel: Basics.Diagnostic.Severity) throws {\n            self.identityResolver = DefaultIdentityResolver()\n            self.dependencyMapper = DefaultDependencyMapper(identityResolver: self.identityResolver)\n            let environment = Environment.current\n            self.hostToolchain = try UserToolchain(\n                swiftSDK: SwiftSDK.hostSwiftSDK(\n                    environment: environment,\n                    fileSystem: fileSystem\n                ),\n                environment: environment\n            )\n            self.targetToolchain = hostToolchain // TODO: support cross-compilation?\n            self.fileSystem = fileSystem\n            self.observabilityScope = observabilityScope\n            self.logLevel = logLevel\n        }\n\n        func build(\n            packagePath:  AbsolutePath,\n            scratchDirectory: AbsolutePath,\n            buildSystem: BuildSystemProvider.Kind,\n            configuration: BuildConfiguration,\n            architectures: [String],\n            buildFlags: BuildFlags,\n            manifestBuildFlags: [String],\n            useIntegratedSwiftDriver: Bool,\n            explicitTargetDependencyImportCheck: TargetDependencyImportCheckingMode,\n            shouldDisableLocalRpath: Bool\n        ) async throws {\n            let buildSystem = try createBuildSystem(\n                packagePath: packagePath,\n                scratchDirectory: scratchDirectory,\n                buildSystem: buildSystem,\n                configuration: configuration,\n                architectures: architectures,\n                buildFlags: buildFlags,\n                manifestBuildFlags: manifestBuildFlags,\n                useIntegratedSwiftDriver: useIntegratedSwiftDriver,\n                explicitTargetDependencyImportCheck: explicitTargetDependencyImportCheck,\n                shouldDisableLocalRpath: shouldDisableLocalRpath,\n                logLevel: logLevel\n            )\n            try await buildSystem.build(subset: .allExcludingTests, buildOutputs: [])\n        }\n\n        func createBuildSystem(\n            packagePath: AbsolutePath,\n            scratchDirectory: AbsolutePath,\n            buildSystem: BuildSystemProvider.Kind,\n            configuration: BuildConfiguration,\n            architectures: [String],\n            buildFlags: BuildFlags,\n            manifestBuildFlags: [String],\n            useIntegratedSwiftDriver: Bool,\n            explicitTargetDependencyImportCheck: TargetDependencyImportCheckingMode,\n            shouldDisableLocalRpath: Bool,\n            logLevel: Basics.Diagnostic.Severity\n        ) throws -> BuildSystem {\n            let dataPath = scratchDirectory.appending(\n                component: self.targetToolchain.targetTriple.platformBuildPathComponent(buildSystem: buildSystem)\n            )\n\n            let buildParameters = try BuildParameters(\n                destination: .target,\n                dataPath: dataPath,\n                configuration: configuration,\n                toolchain: self.targetToolchain,\n                triple: self.hostToolchain.targetTriple,\n                flags: buildFlags,\n                buildSystemKind: buildSystem,\n                architectures: architectures,\n                driverParameters: .init(\n                    explicitTargetDependencyImportCheckingMode: explicitTargetDependencyImportCheck == .error ? .error : .none,\n                    useIntegratedSwiftDriver: useIntegratedSwiftDriver,\n                    isPackageAccessModifierSupported: DriverSupport.isPackageNameSupported(\n                        toolchain: targetToolchain,\n                        fileSystem: self.fileSystem\n                    )\n                ),\n                linkingParameters: .init(\n                    shouldDisableLocalRpath: shouldDisableLocalRpath\n                ),\n                outputParameters: .init(\n                    isVerbose: logLevel <= .info\n                )\n            )\n\n            let manifestLoader = createManifestLoader(manifestBuildFlags: manifestBuildFlags)\n\n            let asyncUnsafePackageGraphLoader = {\n                try await self.loadPackageGraph(packagePath: packagePath, manifestLoader: manifestLoader)\n            }\n\n            switch buildSystem {\n            case .native:\n                let pluginScriptRunner = DefaultPluginScriptRunner(\n                    fileSystem: self.fileSystem,\n                    cacheDir: scratchDirectory.appending(\"plugin-cache\"),\n                    toolchain: self.hostToolchain,\n                    extraPluginSwiftCFlags: [],\n                    enableSandbox: true,\n                    verboseOutput: self.logLevel <= .info\n                )\n                return BuildOperation(\n                    // when building `swift-bootstrap`, host and target build parameters are the same\n                    productsBuildParameters: buildParameters,\n                    toolsBuildParameters: buildParameters,\n                    cacheBuildManifest: false,\n                    packageGraphLoader: asyncUnsafePackageGraphLoader,\n                    pluginConfiguration: .init(\n                        scriptRunner: pluginScriptRunner,\n                        workDirectory: scratchDirectory.appending(component: \"plugin-working-directory\"),\n                        disableSandbox: false\n                    ),\n                    scratchDirectory: scratchDirectory,\n                    // When bootstrapping no special trait build configuration is used\n                    traitConfiguration: nil,\n                    additionalFileRules: [],\n                    pkgConfigDirectories: [],\n                    outputStream: TSCBasic.stdoutStream,\n                    logLevel: logLevel,\n                    fileSystem: self.fileSystem,\n                    observabilityScope: self.observabilityScope,\n                    delegate: nil\n                )\n            case .xcode:\n                return try XcodeBuildSystem(\n                    buildParameters: buildParameters,\n                    packageGraphLoader: asyncUnsafePackageGraphLoader,\n                    outputStream: TSCBasic.stdoutStream,\n                    logLevel: logLevel,\n                    fileSystem: self.fileSystem,\n                    observabilityScope: self.observabilityScope,\n                    delegate: nil\n                )\n            case .swiftbuild:\n                let pluginScriptRunner = DefaultPluginScriptRunner(\n                    fileSystem: self.fileSystem,\n                    cacheDir: scratchDirectory.appending(\"plugin-cache\"),\n                    toolchain: self.hostToolchain,\n                    extraPluginSwiftCFlags: [],\n                    enableSandbox: true,\n                    verboseOutput: self.logLevel <= .info\n                )\n\n                return try SwiftBuildSystem(\n                    buildParameters: buildParameters,\n                    packageGraphLoader: asyncUnsafePackageGraphLoader,\n                    packageManagerResourcesDirectory: nil,\n                    additionalFileRules: [],\n                    outputStream: TSCBasic.stdoutStream,\n                    logLevel: logLevel,\n                    fileSystem: self.fileSystem,\n                    observabilityScope: self.observabilityScope,\n                    pluginConfiguration: .init(\n                        scriptRunner: pluginScriptRunner,\n                        workDirectory: scratchDirectory.appending(component: \"plugin-working-directory\"),\n                        disableSandbox: false\n                    ),\n                    delegate: nil,\n                )\n            }\n        }\n\n        func createManifestLoader(manifestBuildFlags: [String]) -> ManifestLoader {\n            var extraManifestFlags = manifestBuildFlags\n            if self.logLevel <= .info {\n                extraManifestFlags.append(\"-v\")\n            }\n\n            return ManifestLoader(\n                toolchain: self.hostToolchain,\n                isManifestSandboxEnabled: false,\n                extraManifestFlags: extraManifestFlags\n            )\n        }\n\n        func loadPackageGraph(packagePath: AbsolutePath, manifestLoader: ManifestLoader) async throws -> ModulesGraph {\n            let rootPackageRef = PackageReference(identity: .init(path: packagePath), kind: .root(packagePath))\n            let rootPackageManifest =  try await self.loadManifest(manifestLoader: manifestLoader, package: rootPackageRef)\n\n            var loadedManifests = [PackageIdentity: Manifest]()\n            loadedManifests[rootPackageRef.identity] = rootPackageManifest\n\n            // Compute the transitive closure of available dependencies.\n            let input = loadedManifests.map { identity, manifest in KeyedPair(manifest, key: identity) }\n            _ = try await topologicalSort(input) { pair in\n                // When bootstrapping no special trait build configuration is used\n                let dependenciesRequired = try pair.item.dependenciesRequired(for: .everything)\n                let dependenciesToLoad = dependenciesRequired.map{ $0.packageRef }.filter { !loadedManifests.keys.contains($0.identity) }\n                let dependenciesManifests = try await self.loadManifests(manifestLoader: manifestLoader, packages: dependenciesToLoad)\n                dependenciesManifests.forEach { loadedManifests[$0.key] = $0.value }\n                return dependenciesRequired.compactMap { dependency in\n                    loadedManifests[dependency.identity].flatMap {\n                        KeyedPair($0, key: dependency.identity)\n                    }\n                }\n            }\n\n            let packageGraphRoot = try PackageGraphRoot(\n                input: .init(packages: [packagePath]),\n                manifests: [packagePath: rootPackageManifest],\n                observabilityScope: observabilityScope,\n                enabledTraitsMap: .init()\n            )\n\n            return try ModulesGraph.load(\n                root: packageGraphRoot,\n                identityResolver: identityResolver,\n                externalManifests: loadedManifests.reduce(into: OrderedCollections.OrderedDictionary<PackageIdentity, (manifest: Manifest, fs: FileSystem)>()) { partial, item in\n                    partial[item.key] = (manifest: item.value, fs: self.fileSystem)\n                },\n                binaryArtifacts: [:],\n                prebuilts: [:],\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope,\n                enabledTraitsMap: [:] // When bootstrapping no special trait build configuration is used\n            )\n        }\n\n        func loadManifests(\n            manifestLoader: ManifestLoader,\n            packages: [PackageReference]\n        ) async throws -> [PackageIdentity: Manifest] {\n            return try await withThrowingTaskGroup(of: (package:PackageReference, manifest:Manifest).self) { group in\n                for package in packages {\n                    group.addTask {\n                        try await (package, self.loadManifest(manifestLoader: manifestLoader, package: package))\n                    }\n                }\n                return try await group.reduce(into: [:]) { partialResult, packageManifest in\n                    partialResult[packageManifest.package.identity] = packageManifest.manifest\n                }\n            }\n        }\n\n        func loadManifest(\n            manifestLoader: ManifestLoader,\n            package: PackageReference\n        ) async throws -> Manifest {\n            let packagePath = try Result { try AbsolutePath(validating: package.locationString) }.mapError({ StringError(\"Package path \\(package.locationString) is not an absolute path. This can be caused by a dependency declared somewhere in the package graph that is using a URL instead of a local path. Original error: \\($0)\") }).get()\n            let manifestPath = packagePath.appending(component: Manifest.filename)\n            let manifestToolsVersion = try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fileSystem)\n            return try await manifestLoader.load(\n                manifestPath: manifestPath,\n                manifestToolsVersion: manifestToolsVersion,\n                packageIdentity: package.identity,\n                packageKind: package.kind,\n                packageLocation: package.locationString,\n                packageVersion: .none,\n                identityResolver: identityResolver,\n                dependencyMapper: dependencyMapper,\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope,\n                delegateQueue: .sharedConcurrent\n            )\n        }\n    }\n}\n\n// TODO: move to shared area\nextension AbsolutePath {\n    public init?(argument: String) {\n        if let cwd: AbsolutePath = localFileSystem.currentWorkingDirectory {\n            guard let path = try? AbsolutePath(validating: argument, relativeTo: cwd) else {\n                return nil\n            }\n            self = path\n        } else {\n            guard let path = try? AbsolutePath(validating: argument) else {\n                return nil\n            }\n            self = path\n        }\n    }\n\n    public static var defaultCompletionKind: CompletionKind {\n        // This type is most commonly used to select a directory, not a file.\n        // Specify '.file()' in an argument declaration when necessary.\n        .directory\n    }\n}\n\nextension BuildConfiguration {\n    public init?(argument: String) {\n        self.init(rawValue: argument)\n    }\n}\n\nextension AbsolutePath: ExpressibleByArgument {}\nextension BuildConfiguration: ExpressibleByArgument {}\nextension BuildSystemProvider.Kind: ExpressibleByArgument {}\n\npublic func topologicalSort<T: Hashable>(\n    _ nodes: [T], successors: (T) async throws -> [T]\n) async throws -> [T] {\n    // Implements a topological sort via recursion and reverse postorder DFS.\n    func visit(_ node: T,\n               _ stack: inout OrderedSet<T>, _ visited: inout Set<T>, _ result: inout [T],\n               _ successors: (T) async throws -> [T]) async throws {\n        // Mark this node as visited -- we are done if it already was.\n        if !visited.insert(node).inserted {\n            return\n        }\n\n        // Otherwise, visit each adjacent node.\n        for succ in try await successors(node) {\n            guard stack.append(succ) else {\n                // If the successor is already in this current stack, we have found a cycle.\n                //\n                // FIXME: We could easily include information on the cycle we found here.\n                throw TSCBasic.GraphError.unexpectedCycle\n            }\n            try await visit(succ, &stack, &visited, &result, successors)\n            let popped = stack.removeLast()\n            assert(popped == succ)\n        }\n\n        // Add to the result.\n        result.append(node)\n    }\n\n    // FIXME: This should use a stack not recursion.\n    var visited = Set<T>()\n    var result = [T]()\n    var stack = OrderedSet<T>()\n    for node in nodes {\n        precondition(stack.isEmpty)\n        stack.append(node)\n        try await visit(node, &stack, &visited, &result, successors)\n        let popped = stack.removeLast()\n        assert(popped == node)\n    }\n\n    return result.reversed()\n}\n"
  },
  {
    "path": "Sources/swift-build/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_executable(swift-build\n    Entrypoint.swift)\ntarget_link_libraries(swift-build PRIVATE\n    Commands)\n\ntarget_compile_options(swift-build PRIVATE\n  -parse-as-library)\n\ninstall(TARGETS swift-build\n  DESTINATION bin)\n"
  },
  {
    "path": "Sources/swift-build/Entrypoint.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Commands\n\n@main\nstruct Entrypoint {\n    static func main() async {\n        await SwiftBuildCommand.main()\n    }\n}\n"
  },
  {
    "path": "Sources/swift-build-prebuilts/BuildPrebuilts.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/// Checkout supported versions of the prebuilts, build them, package up the zip and update the manifest file.\n\n// Ideally this would be a script, however until we have package dependencies\n// for scripts, this will need to be a part of the package. But this is why it's\n// reading like a script\n\nimport ArgumentParser\nimport Basics\nimport Foundation\nimport PackageModel\nimport struct TSCBasic.ByteString\nimport let TSCBasic.stdoutStream\nimport struct TSCBasic.SHA256\nimport Workspace\n\n@main\nstruct BuildPrebuilts: AsyncParsableCommand {\n    @Option(help: \"The directory to generate the artifacts to.\")\n    var stageDir = try! AbsolutePath(validating: FileManager.default.currentDirectoryPath).appending(\"stage\")\n\n    @Option(name: .customLong(\"version\"), help: \"swift-syntax versions to build. Multiple are allowed.\")\n    var versions: [String] = [\"600.0.1\", \"601.0.1\", \"602.0.0\"]\n\n    @Flag(help: \"Whether to build the prebuilt artifacts\")\n    var build = false\n\n    @Flag(help: \"Whether to sign the manifest\")\n    var sign = false\n\n    @Option(name: .customLong(\"private-key-path\"), help: \"The path to certificate's private key (PEM encoded)\")\n    var privateKeyPathStr: String?\n\n    @Option(name: .customLong(\"cert-chain-path\"), help: \"Path to a certificate (DER encoded) in the chain. The certificate used for signing must be first and the root certificate last.\")\n    var certChainPathStrs: [String] = []\n\n    @Option(help: .hidden)\n    var prebuiltsUrl: String = \"https://download.swift.org/prebuilts\"\n\n    @Flag(help: .hidden)\n    var testSigning: Bool = false\n\n    func validate() throws {\n        if sign && !testSigning {\n            guard privateKeyPathStr != nil else {\n                throw ValidationError(\"No private key path provided\")\n            }\n\n            guard !certChainPathStrs.isEmpty else {\n                throw ValidationError(\"No certificates provided\")\n            }\n        }\n\n        if !build && !sign && !testSigning {\n            throw ValidationError(\"Requires one of --build or --sign or both\")\n        }\n    }\n\n    mutating func run() async throws {\n        if build {\n            try await build()\n        }\n\n        if sign || testSigning {\n            try await sign()\n        }\n    }\n\n    mutating func build() async throws {\n        let encoder = JSONEncoder()\n        encoder.outputFormatting = .prettyPrinted\n\n        guard let hostPlatform = PrebuiltsPlatform.hostPlatform else {\n            print(\"Unable to determine host platform\")\n            return\n        }\n\n        let fileSystem = localFileSystem\n        let hostToolchain = try UserToolchain(\n            swiftSDK: SwiftSDK.hostSwiftSDK(\n                environment: Environment.current,\n                fileSystem: fileSystem\n            ),\n            environment: Environment.current\n        )\n\n        let srcDir = stageDir.appending(\"src\")\n        let libDir = stageDir.appending(\"lib\")\n        let modulesDir = stageDir.appending(\"Modules\")\n\n        if fileSystem.exists(srcDir) {\n            try fileSystem.removeFileTree(srcDir)\n        }\n        try fileSystem.createDirectory(srcDir, recursive: true)\n\n        if fileSystem.exists(libDir) {\n            try fileSystem.removeFileTree(libDir)\n        }\n\n        if fileSystem.exists(modulesDir) {\n            try fileSystem.removeFileTree(modulesDir)\n        }\n\n        // For now, hardcode what we're building prebuilts for\n        let id = \"swift-syntax\"\n        let libraryName = \"MacroSupport\"\n        let repoDir = srcDir.appending(id)\n        let scratchDir = repoDir.appending(\".build\")\n        let prebuiltDir = stageDir.appending(id)\n\n        try await shell(\"git clone https://github.com/swiftlang/swift-syntax.git\", cwd: srcDir)\n\n        for version in versions {\n            let versionDir = prebuiltDir.appending(version)\n            if !fileSystem.exists(versionDir) {\n                try fileSystem.createDirectory(versionDir, recursive: true)\n            }\n\n            try await shell(\"git checkout \\(version)\", cwd: repoDir)\n\n            // Update package with the libraries\n            let packageFile = repoDir.appending(component: \"Package.swift\")\n            let workspace = try Workspace(fileSystem: fileSystem, location: .init(forRootPackage: repoDir, fileSystem: fileSystem))\n            let package = try await workspace.loadRootPackage(\n                at: repoDir,\n                observabilityScope: ObservabilitySystem({ _, diag in print(diag) }, outputStream: stdoutStream, logLevel: .debug).topScope\n            )\n\n            // Gather the list of targets for the package products\n            let libraryTargets = package.targets(forPackage: package)\n\n            var packageContents = try String(contentsOf: packageFile.asURL)\n            packageContents += \"\"\"\n                    package.products += [\n                        .library(name: \"\\(libraryName)\", type: .static, targets: [\n                            \\(libraryTargets.map({ \"\\\"\\($0.name)\\\"\" }).joined(separator: \",\"))\n                        ])\n                    ]\n                    \"\"\"\n            try fileSystem.writeFileContents(packageFile, string: packageContents)\n\n            // Build\n            let cModules = libraryTargets.compactMap({ $0 as? ClangModule })\n            let lib = \"lib\\(libraryName).a\"\n\n            for platform in hostPlatform.supportedPlatforms {\n                try fileSystem.createDirectory(libDir, recursive: true)\n                try fileSystem.createDirectory(modulesDir, recursive: true)\n\n                // Clean out the scratch dir\n                if fileSystem.exists(scratchDir) {\n                    try fileSystem.removeFileTree(scratchDir)\n                }\n\n                // Build\n                if platform.os == .macos {\n                    // Create universal binaries for macOS\n                    for arch in [\"arm64\", \"x86_64\"] {\n                        let cmd = \"swift build -c release -debug-info-format none --arch \\(arch) --product \\(libraryName)\"\n                        try await shell(cmd, cwd: repoDir)\n                    }\n\n                    let armTriple = \"arm64-apple-macos\"\n                    let armDir = scratchDir.appending(\"arm64-apple-macosx\", \"release\")\n                    let armModulesDir = armDir.appending(\"Modules\")\n                    let x86Triple = \"x86_64-apple-macos\"\n                    let x86Dir = scratchDir.appending(\"x86_64-apple-macosx\", \"release\")\n                    let x86ModulesDir = x86Dir.appending(\"Modules\")\n\n                    // Universal swiftmodules\n                    for swiftmodule in try fileSystem.getDirectoryContents(armModulesDir).filter({ $0.hasSuffix(\".swiftmodule\") }) {\n                        let moduleDir = modulesDir.appending(swiftmodule)\n                        let projectDir = moduleDir.appending(\"Project\")\n                        try fileSystem.createDirectory(projectDir, recursive: true)\n                        let moduleName = swiftmodule.replacingOccurrences(of: \".swiftmodule\", with: \"\")\n                        try fileSystem.copy(from: armModulesDir.appending(swiftmodule), to: moduleDir.appending(armTriple + \".swiftmodule\"))\n                        try fileSystem.copy(from: x86ModulesDir.appending(swiftmodule), to: moduleDir.appending(x86Triple + \".swiftmodule\"))\n                        try fileSystem.copy(from: armModulesDir.appending(moduleName + \".abi.json\"), to: moduleDir.appending(armTriple + \".abi.json\"))\n                        try fileSystem.copy(from: x86ModulesDir.appending(moduleName + \".abi.json\"), to: moduleDir.appending(x86Triple + \".abi.json\"))\n                        try fileSystem.copy(from: armModulesDir.appending(moduleName + \".swiftdoc\"), to: moduleDir.appending(armTriple + \".swiftdoc\"))\n                        try fileSystem.copy(from: x86ModulesDir.appending(moduleName + \".swiftdoc\"), to: moduleDir.appending(x86Triple + \".swiftdoc\"))\n                        try fileSystem.copy(from: armModulesDir.appending(moduleName + \".swiftsourceinfo\"), to: projectDir.appending(armTriple + \".swiftsourceinfo\"))\n                        try fileSystem.copy(from: x86ModulesDir.appending(moduleName + \".swiftsourceinfo\"), to: projectDir.appending(x86Triple + \".swiftsourceinfo\"))\n                    }\n\n                    // lipo the archive\n                    let armLib = armDir.appending(lib)\n                    let x86Lib = x86Dir.appending(lib)\n                    let cmd = \"lipo -create -output \\(lib) \\(armLib) \\(x86Lib)\"\n                    try await shell(cmd, cwd: libDir)\n                } else {\n                    let archArg: String\n                    if let arch = platform.arch {\n                        archArg = \"--arch \\(arch)\"\n                    } else {\n                        archArg = \"\"\n                    }\n                    let cmd = \"swift build -c release \\(archArg) -debug-info-format none --product \\(libraryName)\"\n                    try await shell(cmd, cwd: repoDir)\n\n                    let buildDir = scratchDir.appending(\"release\")\n                    let srcModulesDir = buildDir.appending(\"Modules\")\n\n                    // Copy the swiftmodules\n                    for file in try fileSystem.getDirectoryContents(srcModulesDir) {\n                        try fileSystem.copy(from: srcModulesDir.appending(file), to: modulesDir.appending(file))\n                    }\n\n                    // Copy the library to staging\n                    try fileSystem.copy(from: buildDir.appending(lib), to: libDir.appending(lib))\n                }\n\n                // Name of the prebuilt\n                let prebuiltName = try platform.prebuiltName(hostToolchain: hostToolchain)\n\n                // Zip it up\n                let contentDirs = [\"lib\", \"Modules\"]\n                let contents: ByteString\n                switch platform.os {\n                case .macos:\n                    let zipFile = versionDir.appending(\"\\(prebuiltName)-\\(libraryName).zip\")\n                    try await shell(\"zip -r \\(zipFile.pathString) \\(contentDirs.joined(separator: \" \"))\", cwd: stageDir)\n                    contents = try ByteString(fileSystem.readFileContents(zipFile))\n                case .windows:\n                    let zipFile = versionDir.appending(\"\\(prebuiltName)-\\(libraryName).zip\")\n                    try await shell(\"tar -acf \\(zipFile.pathString) \\(contentDirs.joined(separator: \" \"))\", cwd: stageDir)\n                    contents = try ByteString(fileSystem.readFileContents(zipFile))\n                case .linux:\n                    let tarFile = versionDir.appending(\"\\(prebuiltName)-\\(libraryName).tar.gz\")\n                    try await shell(\"tar -zcf \\(tarFile.pathString) \\(contentDirs.joined(separator: \" \"))\", cwd: stageDir)\n                    contents = try ByteString(fileSystem.readFileContents(tarFile))\n                }\n\n                // Manifest fragment for the zip file\n                let checksum = SHA256().hash(contents).hexadecimalRepresentation\n                let library = Workspace.PrebuiltsManifest.Library(\n                    name: libraryName,\n                    checksum: checksum,\n                    products: package.products.map(\\.name),\n                    includePath: cModules.map({ $0.includeDir.relative(to: repoDir) })\n                )\n                let manifest = Workspace.PrebuiltsManifest(libraries: [library])\n\n                let unsignedJsonFile = versionDir.appending(\"\\(prebuiltName).unsigned\")\n                try fileSystem.writeFileContents(unsignedJsonFile, data: encoder.encode(manifest))\n\n                // Clean up\n                try fileSystem.removeFileTree(libDir)\n                try fileSystem.removeFileTree(modulesDir)\n            }\n\n            try await shell(\"git restore .\", cwd: repoDir)\n        }\n\n        try fileSystem.changeCurrentWorkingDirectory(to: stageDir)\n        try fileSystem.removeFileTree(srcDir)\n    }\n\n    mutating func sign() async throws {\n        let fileSystem = localFileSystem\n        let encoder = JSONEncoder()\n        encoder.outputFormatting = .prettyPrinted\n        let decoder = JSONDecoder()\n\n        if testSigning {\n            // Use SwiftPM's test certificate chain and private key for testing\n            let certsPath = try AbsolutePath(validating: #file)\n                .parentDirectory.parentDirectory.parentDirectory\n                .appending(components: \"Fixtures\", \"Signing\", \"Certificates\")\n            privateKeyPathStr = certsPath.appending(\"Test_rsa_key.pem\").pathString\n            certChainPathStrs = [\n                certsPath.appending(\"Test_rsa.cer\").pathString,\n                certsPath.appending(\"TestIntermediateCA.cer\").pathString,\n                certsPath.appending(\"TestRootCA.cer\").pathString\n            ]\n        }\n\n        func make(path: String) throws -> AbsolutePath {\n            if let path = try? AbsolutePath(validating: path) {\n                // It's already absolute\n                return path\n            }\n\n            return try AbsolutePath(validating: FileManager.default.currentDirectoryPath)\n                .appending(RelativePath(validating: path))\n        }\n\n        guard let privateKeyPathStr else {\n            fatalError(\"No private key path provided\")\n        }\n\n        let certChainPaths = try certChainPathStrs.map { try make(path: $0) }\n\n        guard let rootCertPath = certChainPaths.last else {\n            fatalError(\"No certificates provided\")\n        }\n\n        let privateKeyPath = try make(path: privateKeyPathStr)\n\n        let id = \"swift-syntax\"\n        let prebuiltDir = stageDir.appending(id)\n        for version in try fileSystem.getDirectoryContents(prebuiltDir) {\n            let versionDir = prebuiltDir.appending(version)\n\n            for file in try fileSystem.getDirectoryContents(versionDir).filter({ $0.hasSuffix(\".unsigned\") }) {\n                let unsignedJsonFile = versionDir.appending(file)\n                let signedJsonFile = versionDir.appending(unsignedJsonFile.basenameWithoutExt + \".json\")\n\n                let unsignedData: Data = try fileSystem.readFileContents(unsignedJsonFile)\n                let manifest = try decoder.decode(Workspace.PrebuiltsManifest.self, from: unsignedData)\n\n                try await withTemporaryDirectory { tmpDir in\n                    try fileSystem.copy(from: rootCertPath, to: tmpDir.appending(rootCertPath.basename))\n\n                    let signer = ManifestSigning(\n                        trustedRootCertsDir: tmpDir,\n                        observabilityScope: ObservabilitySystem({ _, diagnostic in print(diagnostic) }, outputStream: stdoutStream, logLevel: .debug).topScope\n                    )\n\n                    let signature = try await signer.sign(\n                        manifest: manifest,\n                        certChainPaths: certChainPaths,\n                        certPrivateKeyPath: privateKeyPath,\n                        fileSystem: fileSystem\n                    )\n\n                    let signedManifest = Workspace.SignedPrebuiltsManifest(manifest: manifest, signature: signature)\n                    try fileSystem.writeFileContents(signedJsonFile, data: encoder.encode(signedManifest))\n                }\n            }\n        }\n    }\n}\n\nfunc shell(_ command: String, cwd: AbsolutePath) async throws {\n    _ = FileManager.default.changeCurrentDirectoryPath(cwd.pathString)\n\n#if os(Windows)\n    let arguments = [\"C:\\\\Windows\\\\System32\\\\cmd.exe\", \"/c\", command]\n#else\n    let arguments = [\"/bin/bash\", \"-c\", command]\n#endif\n    let process = AsyncProcess(\n        arguments: arguments,\n        outputRedirection: .none\n    )\n    print(\"Running:\", command)\n    try process.launch()\n    let result = try await process.waitUntilExit()\n    switch result.exitStatus {\n    case .terminated(code: let code):\n        if code != 0 {\n            throw StringError(\"Command exited with code \\(code): \\(command)\")\n        }\n#if os(Windows)\n    case .abnormal(exception: let exception):\n        throw StringError(\"Command threw exception \\(exception): \\(command)\")\n#else\n    case .signalled(signal: let signal):\n        throw StringError(\"Command exited on signal \\(signal): \\(command)\")\n#endif\n    }\n}\n\nextension AbsolutePath: ExpressibleByArgument {\n    public init?(argument: String) {\n        try? self.init(validating: argument)\n    }\n}\n\nextension Package {\n    /// The transitive list of targets in this package for the given list of products\n    func targets(forPackage package: Package) -> [Module] {\n        var targets: [String: Module] = [:]\n        for product in package.products where product.type.isLibrary {\n            for target in product.modules {\n                if !targets.keys.contains(target.name) {\n                    func transitTarget(_ target: Module) {\n                        for dep in target.dependencies {\n                            switch dep {\n                            case .module(let module, conditions: _):\n                                if !targets.keys.contains(module.name) {\n                                    targets[module.name] = module\n                                    transitTarget(module)\n                                }\n                            default:\n                                break\n                            }\n                        }\n                    }\n\n                    targets[target.name] = target\n                    transitTarget(target)\n                }\n            }\n        }\n        return Array(targets.values)\n    }\n}\n\nextension PrebuiltsPlatform {\n    public var supportedPlatforms: [Self] {\n        switch os {\n        case .macos:\n            // Universal binaries on Mac\n            return [.macos_universal]\n        case .windows:\n            // Windows can build both archs\n            return [.windows_aarch64, .windows_x86_64]\n        case .linux:\n            return [self]\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/swift-build-prebuilts/build.sh",
    "content": "#!/bin/bash\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2025 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\nswift run swift-build-prebuilts --stage-dir ~/swift/stage --build --test-signing \\\n    --version 600.0.1 \\\n    --version 601.0.1 \\\n    --version $(git ls-remote --tags https://github.com/swiftlang/swift-syntax '*.*.*' | cut -d '/' -f 3 | grep ^602 | tail -1)\n"
  },
  {
    "path": "Sources/swift-experimental-sdk/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_executable(swift-experimental-sdk\n  Entrypoint.swift)\ntarget_link_libraries(swift-experimental-sdk PRIVATE\n  SwiftSDKCommand)\n\ntarget_compile_options(swift-experimental-sdk PRIVATE\n  -parse-as-library)\n\ninstall(TARGETS swift-experimental-sdk\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/swift-experimental-sdk/Entrypoint.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftSDKCommand\nimport Foundation\n\n@main\nstruct Entrypoint {\n    static func main() async {\n        fputs(\"warning: `swift experimental-sdk` command is deprecated and will be removed in a future version of SwiftPM. Use `swift sdk` instead.\\n\", stderr)\n        await SwiftSDKCommand.main()\n    }\n}\n"
  },
  {
    "path": "Sources/swift-package/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_executable(swift-package\n  Entrypoint.swift)\ntarget_link_libraries(swift-package PRIVATE\n  Commands\n  TSCBasic)\n\ntarget_compile_options(swift-package PRIVATE\n  -parse-as-library)\n\ninstall(TARGETS swift-package\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/swift-package/Entrypoint.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Commands\n\n@main\nstruct Entrypoint {\n    static func main() async {\n        await SwiftPackageCommand.main()\n    }\n}\n"
  },
  {
    "path": "Sources/swift-package-collection/Entrypoint.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Commands\nimport PackageCollectionsCommand\n\n@main\nstruct Entrypoint {\n    static func main() async {\n        await PackageCollectionsCommand.main()\n    }\n}\n"
  },
  {
    "path": "Sources/swift-package-manager/SwiftPM.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Commands\nimport Foundation\n\nimport SwiftSDKCommand\nimport PackageCollectionsCommand\nimport PackageRegistryCommand\n\nlet firstArg = CommandLine.arguments[0]\nlet baseNameWithoutExtension = (try? AbsolutePath(validating: firstArg).basenameWithoutExt) ??\n    (try? RelativePath(validating: firstArg).basenameWithoutExt)\n\n@main\nstruct SwiftPM {\n    static func main() async {\n        // Workaround a bug in Swift 5.9, where multiple executables with an `async` main entrypoint can't be linked\n        // into the same test bundle. We're then linking single `swift-package-manager` binary instead and passing\n        // executable name via `SWIFTPM_EXEC_NAME`.\n        if baseNameWithoutExtension == \"swift-package-manager\" {\n            await main(execName: Environment.current[\"SWIFTPM_EXEC_NAME\"])\n        } else {\n            await main(execName: baseNameWithoutExtension)\n        }\n    }\n\n    private static func main(execName: String?) async {\n        switch execName {\n        case \"swift-package\":\n            await SwiftPackageCommand.main()\n        case \"swift-build\":\n            await SwiftBuildCommand.main()\n        case \"swift-experimental-sdk\":\n            fputs(\"warning: `swift experimental-sdk` command is deprecated and will be removed in a future version of SwiftPM. Use `swift sdk` instead.\\n\", stderr)\n            fallthrough\n        case \"swift-sdk\":\n            await SwiftSDKCommand.main()\n        case \"swift-test\":\n            await SwiftTestCommand.main()\n        case \"swift-run\":\n            await SwiftRunCommand.main()\n        case \"swift-package-collection\":\n            await PackageCollectionsCommand.main()\n        case \"swift-package-registry\":\n            await PackageRegistryCommand.main()\n        default:\n            fatalError(\"swift-package-manager launched with unexpected name: \\(execName ?? \"(unknown)\")\")\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/swift-package-registry/runner.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Commands\nimport PackageRegistryCommand\n\n@main\nstruct Runner {\n    static func main() async {\n        await PackageRegistryCommand.main()\n    }\n}\n"
  },
  {
    "path": "Sources/swift-run/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_executable(swift-run\n  Entrypoint.swift)\ntarget_link_libraries(swift-run PRIVATE\n  Commands)\n\ntarget_compile_options(swift-run PRIVATE\n  -parse-as-library)\n\ninstall(TARGETS swift-run\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/swift-run/Entrypoint.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Commands\n\n@main\nstruct Entrypoint {\n    static func main() async {\n        await SwiftRunCommand.main()\n    }\n}\n"
  },
  {
    "path": "Sources/swift-sdk/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_executable(swift-sdk\n  Entrypoint.swift)\ntarget_link_libraries(swift-sdk PRIVATE\n  SwiftSDKCommand)\n\ntarget_compile_options(swift-sdk PRIVATE\n  -parse-as-library)\n\ninstall(TARGETS swift-sdk\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/swift-sdk/Entrypoint.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport SwiftSDKCommand\n\n@main\nstruct Entrypoint {\n    static func main() async {\n        await SwiftSDKCommand.main()\n    }\n}\n"
  },
  {
    "path": "Sources/swift-test/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_executable(swift-test\n  Entrypoint.swift)\ntarget_link_libraries(swift-test PRIVATE\n  Commands)\n\ntarget_compile_options(swift-test PRIVATE\n  -parse-as-library)\n\ninstall(TARGETS swift-test\n  RUNTIME DESTINATION bin)\n"
  },
  {
    "path": "Sources/swift-test/Entrypoint.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Commands\n\n@main\nstruct Entrypoint {\n    static func main() async {\n        await SwiftTestCommand.main()\n    }\n}\n"
  },
  {
    "path": "Sources/swiftpm-testing-helper/Entrypoint.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#if canImport(Darwin)\nimport Darwin.C\n#elseif canImport(Android)\nimport Android\n#endif\n\n@main\nstruct Entrypoint {\n    static func main() throws {\n        let args = CommandLine.arguments\n        if args.count >= 3, args[1] == \"--test-bundle-path\" {\n            let bundlePath = args[2]\n            #if canImport(Darwin)\n            let flags = RTLD_LAZY | RTLD_FIRST\n            #else\n            let flags = RTLD_LAZY\n            #endif\n            guard let image = dlopen(bundlePath, flags) else {\n                let errorMessage: String = dlerror().flatMap {\n                    String(validatingCString: $0)\n                } ?? \"An unknown error occurred.\"\n                fatalError(\"Failed to open test bundle at path \\(bundlePath): \\(errorMessage)\")\n            }\n            defer {\n                dlclose(image)\n            }\n\n            // Find and call the main function from the image. This function may\n            // link to the copy of Swift Testing included with Xcode, or may link to\n            // a copy that's included as a package dependency.\n            let main = dlsym(image, \"main\").map {\n                unsafeBitCast(\n                    $0,\n                    to: (@convention(c) (CInt, UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>) -> CInt).self\n                )\n            }\n            if let main {\n                exit(main(CommandLine.argc, CommandLine.unsafeArgv))\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/tsan_utils/CMakeLists.txt",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nadd_library(tsan_utils STATIC\n  tsan_utils.c)\ntarget_include_directories(tsan_utils PUBLIC\n  include)\n"
  },
  {
    "path": "Sources/tsan_utils/include/module.modulemap",
    "content": "module tsan_utils {\n    header \"tsan_utils.h\"\n    export *\n}\n"
  },
  {
    "path": "Sources/tsan_utils/include/tsan_utils.h",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#include <stdbool.h>\n\n/// returns true if the current build supports the thread-sanitizer.\nextern bool is_tsan_enabled(void);\n"
  },
  {
    "path": "Sources/tsan_utils/tsan_utils.c",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n#include \"tsan_utils.h\"\n\nbool is_tsan_enabled() {\n#if defined(__has_feature) && __has_feature(thread_sanitizer)\n    return true;\n#else\n    return false;\n#endif\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Archiver/TarArchiverTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import struct Basics.TarArchiver\nimport TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCBasic.FileSystemError\n\nfinal class TarArchiverTests: XCTestCase {\n    override func setUp() async throws {\n        let archiver = TarArchiver(fileSystem: localFileSystem)\n        try XCTRequires(executable: archiver.tarCommand)\n    }\n\n    func testSuccess() async throws {\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = TarArchiver(fileSystem: localFileSystem)\n            let inputArchivePath = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"archive.tar.gz\")\n            try await archiver.extract(from: inputArchivePath, to: tmpdir)\n            let content = tmpdir.appending(\"file\")\n            XCTAssert(localFileSystem.exists(content))\n            XCTAssertEqual((try? localFileSystem.readFileContents(content))?.cString, \"Hello World!\")\n        }\n    }\n\n    func testArchiveDoesntExist() async {\n        let fileSystem = InMemoryFileSystem()\n        let archiver = TarArchiver(fileSystem: fileSystem)\n        let archive = AbsolutePath(\"/archive.tar.gz\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: archive, to: \"/\")) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.noEntry, archive))\n        }\n    }\n\n    func testDestinationDoesntExist() async throws {\n        let fileSystem = InMemoryFileSystem(emptyFiles: \"/archive.tar.gz\")\n        let archiver = TarArchiver(fileSystem: fileSystem)\n        let destination = AbsolutePath(\"/destination\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: \"/archive.tar.gz\", to: destination)) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.notDirectory, destination))\n        }\n    }\n\n    func testDestinationIsFile() async {\n        let fileSystem = InMemoryFileSystem(emptyFiles: \"/archive.tar.gz\", \"/destination\")\n        let archiver = TarArchiver(fileSystem: fileSystem)\n        let destination = AbsolutePath(\"/destination\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: \"/archive.tar.gz\", to: destination)) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.notDirectory, destination))\n        }\n    }\n\n    func testInvalidArchive() async throws {\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = TarArchiver(fileSystem: localFileSystem)\n            let inputArchivePath = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"invalid_archive.tar.gz\")\n            await XCTAssertAsyncThrowsError(try await archiver.extract(from: inputArchivePath, to: tmpdir)) { error in\n                #if os(Linux)\n                XCTAssertMatch((error as? StringError)?.description, .contains(\"not in gzip format\"))\n                #else\n                XCTAssertMatch((error as? StringError)?.description, .contains(\"Unrecognized archive format\"))\n                #endif\n            }\n        }\n    }\n\n    func testValidation() async throws {\n        // valid\n        try await testWithTemporaryDirectory { _ in\n            let archiver = TarArchiver(fileSystem: localFileSystem)\n            let path = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"archive.tar.gz\")\n            try await XCTAssertAsyncTrue(try await archiver.validate(path: path))\n        }\n        // invalid\n        try await testWithTemporaryDirectory { _ in\n            let archiver = TarArchiver(fileSystem: localFileSystem)\n            let path = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"invalid_archive.tar.gz\")\n            try await XCTAssertAsyncFalse(try await archiver.validate(path: path))\n        }\n        // error\n        try await  testWithTemporaryDirectory { _ in\n            let archiver = TarArchiver(fileSystem: localFileSystem)\n            let path = AbsolutePath.root.appending(\"does_not_exist.tar.gz\")\n            await XCTAssertAsyncThrowsError(try await archiver.validate(path: path)) { error in\n                XCTAssertEqual(error as? FileSystemError, FileSystemError(.noEntry, path))\n            }\n        }\n    }\n\n    func testCompress() async throws {\n        #if !os(Windows)\n        guard SPM_posix_spawn_file_actions_addchdir_np_supported() else {\n            throw XCTSkip(\"working directory not supported on this platform\")\n        }\n        #endif\n\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = TarArchiver(fileSystem: localFileSystem)\n\n            let rootDir = tmpdir.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(rootDir)\n            try localFileSystem.writeFileContents(rootDir.appending(\"file1.txt\"), string: \"Hello World!\")\n\n            let dir1 = rootDir.appending(\"dir1\")\n            try localFileSystem.createDirectory(dir1)\n            try localFileSystem.writeFileContents(dir1.appending(\"file2.txt\"), string: \"Hello World 2!\")\n\n            let dir2 = dir1.appending(\"dir2\")\n            try localFileSystem.createDirectory(dir2)\n            try localFileSystem.writeFileContents(dir2.appending(\"file3.txt\"), string: \"Hello World 3!\")\n            try localFileSystem.writeFileContents(dir2.appending(\"file4.txt\"), string: \"Hello World 4!\")\n\n            let archivePath = tmpdir.appending(component: UUID().uuidString + \".tar.gz\")\n            try await archiver.compress(directory: rootDir, to: archivePath)\n            XCTAssertFileExists(archivePath)\n\n            let extractRootDir = tmpdir.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(extractRootDir)\n            try await archiver.extract(from: archivePath, to: extractRootDir)\n            try localFileSystem.stripFirstLevel(of: extractRootDir)\n\n            XCTAssertFileExists(extractRootDir.appending(\"file1.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractRootDir.appending(\"file1.txt\")),\n                \"Hello World!\"\n            )\n\n            let extractedDir1 = extractRootDir.appending(\"dir1\")\n            XCTAssertDirectoryExists(extractedDir1)\n            XCTAssertFileExists(extractedDir1.appending(\"file2.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir1.appending(\"file2.txt\")),\n                \"Hello World 2!\"\n            )\n\n            let extractedDir2 = extractedDir1.appending(\"dir2\")\n            XCTAssertDirectoryExists(extractedDir2)\n            XCTAssertFileExists(extractedDir2.appending(\"file3.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir2.appending(\"file3.txt\")),\n                \"Hello World 3!\"\n            )\n            XCTAssertFileExists(extractedDir2.appending(\"file4.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir2.appending(\"file4.txt\")),\n                \"Hello World 4!\"\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Archiver/UniversalArchiverTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import struct Basics.TarArchiver\n@testable import struct Basics.ZipArchiver\nimport TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCBasic.FileSystemError\n\nfinal class UniversalArchiverTests: XCTestCase {\n    override func setUp() async throws {\n        let zipAchiver = ZipArchiver(fileSystem: localFileSystem)\n        #if os(Windows)\n            try XCTRequires(executable: zipAchiver.windowsTar)\n        #else\n            try XCTRequires(executable: zipAchiver.unzip)\n            try XCTRequires(executable: zipAchiver.zip)\n        #endif\n        #if os(FreeBSD)\n            try XCTRequires(executable: zipAchiver.tar)\n        #endif\n\n        let tarAchiver = TarArchiver(fileSystem: localFileSystem)\n        try XCTRequires(executable: tarAchiver.tarCommand)\n    }\n\n    func testSuccess() async throws {\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = UniversalArchiver(localFileSystem)\n            let inputArchivePath = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"archive.tar.gz\")\n            let tarDestination = tmpdir.appending(\"tar\")\n            try localFileSystem.createDirectory(tarDestination)\n            try await archiver.extract(from: inputArchivePath, to: tarDestination)\n            let tarContent = tarDestination.appending(\"file\")\n            XCTAssert(localFileSystem.exists(tarContent))\n            XCTAssertEqual((try? localFileSystem.readFileContents(tarContent))?.cString, \"Hello World!\")\n\n            let zipDestination = tmpdir.appending(\"zip\")\n            try localFileSystem.createDirectory(zipDestination)\n            try await archiver.extract(from: inputArchivePath, to: zipDestination)\n            let zipContent = zipDestination.appending(\"file\")\n            XCTAssert(localFileSystem.exists(zipContent))\n            XCTAssertEqual((try? localFileSystem.readFileContents(zipContent))?.cString, \"Hello World!\")\n        }\n    }\n\n    func testArchiveDoesntExist() async {\n        let fileSystem = InMemoryFileSystem()\n        let archiver = UniversalArchiver(fileSystem)\n        let archive = AbsolutePath(\"/archive.tar.gz\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: archive, to: \"/\")) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.noEntry, archive))\n        }\n    }\n\n    func testDestinationDoesntExist() async throws {\n        let fileSystem = InMemoryFileSystem(emptyFiles: \"/archive.tar.gz\")\n        let archiver = UniversalArchiver(fileSystem)\n        let destination = AbsolutePath(\"/destination\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: \"/archive.tar.gz\", to: destination)) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.notDirectory, destination))\n        }\n    }\n\n    func testDestinationIsFile() async throws {\n        let fileSystem = InMemoryFileSystem(emptyFiles: \"/archive.tar.gz\", \"/destination\")\n        let archiver = UniversalArchiver(fileSystem)\n        let destination = AbsolutePath(\"/destination\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: \"/archive.tar.gz\", to: destination)) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.notDirectory, destination))\n        }\n    }\n\n    func testInvalidArchive() async throws {\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = UniversalArchiver(localFileSystem)\n            var inputArchivePath = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"invalid_archive.tar.gz\")\n            await XCTAssertAsyncThrowsError(try await archiver.extract(from: inputArchivePath, to: tmpdir)) { error in\n                #if os(Linux)\n                XCTAssertMatch((error as? StringError)?.description, .contains(\"not in gzip format\"))\n                #else\n                XCTAssertMatch((error as? StringError)?.description, .contains(\"Unrecognized archive format\"))\n                #endif\n            }\n\n            inputArchivePath = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"invalid_archive.zip\")\n            await XCTAssertAsyncThrowsError(try await archiver.extract(from: inputArchivePath, to: tmpdir)) { error in\n#if os(Windows) || os(FreeBSD)\n                XCTAssertMatch((error as? StringError)?.description, .contains(\"Unrecognized archive format\"))\n#else\n                XCTAssertMatch((error as? StringError)?.description, .contains(\"End-of-central-directory signature not found\"))\n#endif\n            }\n        }\n    }\n\n    func testValidation() async throws {\n        // valid\n        try await testWithTemporaryDirectory { _ in\n            let archiver = UniversalArchiver(localFileSystem)\n            let path = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"archive.tar.gz\")\n            try await XCTAssertAsyncTrue(try await archiver.validate(path: path))\n        }\n        // invalid\n        try await testWithTemporaryDirectory { _ in\n            let archiver = UniversalArchiver(localFileSystem)\n            let path = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"invalid_archive.tar.gz\")\n            try await XCTAssertAsyncFalse(try await archiver.validate(path: path))\n        }\n        // error\n        try await testWithTemporaryDirectory { _ in\n            let archiver = UniversalArchiver(localFileSystem)\n            let path = AbsolutePath.root.appending(\"does_not_exist.tar.gz\")\n            await XCTAssertAsyncThrowsError(try await archiver.validate(path: path)) { error in\n                XCTAssertEqual(error as? FileSystemError, FileSystemError(.noEntry, path))\n            }\n        }\n    }\n\n    func testCompress() async throws {\n        #if !os(Windows)\n        guard SPM_posix_spawn_file_actions_addchdir_np_supported() else {\n            throw XCTSkip(\"working directory not supported on this platform\")\n        }\n        #endif\n\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = UniversalArchiver(localFileSystem)\n\n            let rootDir = tmpdir.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(rootDir)\n            try localFileSystem.writeFileContents(rootDir.appending(\"file1.txt\"), string: \"Hello World!\")\n\n            let dir1 = rootDir.appending(\"dir1\")\n            try localFileSystem.createDirectory(dir1)\n            try localFileSystem.writeFileContents(dir1.appending(\"file2.txt\"), string: \"Hello World 2!\")\n\n            let dir2 = dir1.appending(\"dir2\")\n            try localFileSystem.createDirectory(dir2)\n            try localFileSystem.writeFileContents(dir2.appending(\"file3.txt\"), string: \"Hello World 3!\")\n            try localFileSystem.writeFileContents(dir2.appending(\"file4.txt\"), string: \"Hello World 4!\")\n\n            var archivePath = tmpdir.appending(component: UUID().uuidString + \".tar.gz\")\n            try await archiver.compress(directory: rootDir, to: archivePath)\n            XCTAssertFileExists(archivePath)\n\n            var extractRootDir = tmpdir.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(extractRootDir)\n            try await archiver.extract(from: archivePath, to: extractRootDir)\n            try localFileSystem.stripFirstLevel(of: extractRootDir)\n\n            XCTAssertFileExists(extractRootDir.appending(\"file1.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractRootDir.appending(\"file1.txt\")),\n                \"Hello World!\"\n            )\n\n            var extractedDir1 = extractRootDir.appending(\"dir1\")\n            XCTAssertDirectoryExists(extractedDir1)\n            XCTAssertFileExists(extractedDir1.appending(\"file2.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir1.appending(\"file2.txt\")),\n                \"Hello World 2!\"\n            )\n\n            var extractedDir2 = extractedDir1.appending(\"dir2\")\n            XCTAssertDirectoryExists(extractedDir2)\n            XCTAssertFileExists(extractedDir2.appending(\"file3.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir2.appending(\"file3.txt\")),\n                \"Hello World 3!\"\n            )\n            XCTAssertFileExists(extractedDir2.appending(\"file4.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir2.appending(\"file4.txt\")),\n                \"Hello World 4!\"\n            )\n\n            archivePath = tmpdir.appending(component: UUID().uuidString + \".zip\")\n            try await archiver.compress(directory: rootDir, to: archivePath)\n            XCTAssertFileExists(archivePath)\n\n            extractRootDir = tmpdir.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(extractRootDir)\n            try await archiver.extract(from: archivePath, to: extractRootDir)\n            try localFileSystem.stripFirstLevel(of: extractRootDir)\n\n            XCTAssertFileExists(extractRootDir.appending(\"file1.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractRootDir.appending(\"file1.txt\")),\n                \"Hello World!\"\n            )\n\n            extractedDir1 = extractRootDir.appending(\"dir1\")\n            XCTAssertDirectoryExists(extractedDir1)\n            XCTAssertFileExists(extractedDir1.appending(\"file2.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir1.appending(\"file2.txt\")),\n                \"Hello World 2!\"\n            )\n\n            extractedDir2 = extractedDir1.appending(\"dir2\")\n            XCTAssertDirectoryExists(extractedDir2)\n            XCTAssertFileExists(extractedDir2.appending(\"file3.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir2.appending(\"file3.txt\")),\n                \"Hello World 3!\"\n            )\n            XCTAssertFileExists(extractedDir2.appending(\"file4.txt\"))\n            XCTAssertEqual(\n                try? localFileSystem.readFileContents(extractedDir2.appending(\"file4.txt\")),\n                \"Hello World 4!\"\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Archiver/ZipArchiverTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import struct Basics.ZipArchiver\nimport _InternalTestSupport\nimport XCTest\nimport TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported\n\nimport struct TSCBasic.FileSystemError\n\nfinal class ZipArchiverTests: XCTestCase {\n    override func setUp() async throws {\n        let archiver = ZipArchiver(fileSystem: localFileSystem)\n        #if os(Windows)\n            try XCTRequires(executable: archiver.windowsTar)\n        #else\n            try XCTRequires(executable: archiver.unzip)\n            try XCTRequires(executable: archiver.zip)\n        #endif\n        #if os(FreeBSD)\n            try XCTRequires(executable: archiver.tar)\n        #endif\n    }\n\n    func testZipArchiverSuccess() async throws {\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = ZipArchiver(fileSystem: localFileSystem)\n            let inputArchivePath = AbsolutePath(#file).parentDirectory.appending(components: \"Inputs\", \"archive.zip\")\n            try await archiver.extract(from: inputArchivePath, to: tmpdir)\n            let content = tmpdir.appending(\"file\")\n            XCTAssert(localFileSystem.exists(content))\n            XCTAssertEqual((try? localFileSystem.readFileContents(content))?.cString, \"Hello World!\")\n        }\n    }\n\n    func testZipArchiverArchiveDoesntExist() async {\n        let fileSystem = InMemoryFileSystem()\n        let archiver = ZipArchiver(fileSystem: fileSystem)\n        let archive = AbsolutePath(\"/archive.zip\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: archive, to: \"/\")) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.noEntry, archive))\n        }\n    }\n\n    func testZipArchiverDestinationDoesntExist() async throws {\n        let fileSystem = InMemoryFileSystem(emptyFiles: \"/archive.zip\")\n        let archiver = ZipArchiver(fileSystem: fileSystem)\n        let destination = AbsolutePath(\"/destination\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: \"/archive.zip\", to: destination)) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.notDirectory, destination))\n        }\n    }\n\n    func testZipArchiverDestinationIsFile() async throws {\n        let fileSystem = InMemoryFileSystem(emptyFiles: \"/archive.zip\", \"/destination\")\n        let archiver = ZipArchiver(fileSystem: fileSystem)\n        let destination = AbsolutePath(\"/destination\")\n        await XCTAssertAsyncThrowsError(try await archiver.extract(from: \"/archive.zip\", to: destination)) { error in\n            XCTAssertEqual(error as? FileSystemError, FileSystemError(.notDirectory, destination))\n        }\n    }\n\n    func testZipArchiverInvalidArchive() async throws {\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = ZipArchiver(fileSystem: localFileSystem)\n            let inputArchivePath = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"invalid_archive.zip\")\n            await XCTAssertAsyncThrowsError(try await archiver.extract(from: inputArchivePath, to: tmpdir)) { error in\n#if os(Windows) || os(FreeBSD)\n                // On FreeBSD, unzip (bsdunzip) is backed by libarchive\n                XCTAssertMatch((error as? StringError)?.description, .contains(\"Unrecognized archive format\"))\n#else\n                XCTAssertMatch((error as? StringError)?.description, .contains(\"End-of-central-directory signature not found\"))\n#endif\n            }\n        }\n    }\n\n    func testValidation() async throws {\n        // valid\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = ZipArchiver(fileSystem: localFileSystem)\n            let path = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"archive.zip\")\n            try await XCTAssertAsyncTrue(try await archiver.validate(path: path))\n        }\n        // invalid\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = ZipArchiver(fileSystem: localFileSystem)\n            let path = AbsolutePath(#file).parentDirectory\n                .appending(components: \"Inputs\", \"invalid_archive.zip\")\n            try await XCTAssertAsyncFalse(try await archiver.validate(path: path))\n        }\n        // error\n        try await testWithTemporaryDirectory { tmpdir in\n            let archiver = ZipArchiver(fileSystem: localFileSystem)\n            let path = AbsolutePath.root.appending(\"does_not_exist.zip\")\n            await XCTAssertAsyncThrowsError(try await archiver.validate(path: path)) { error in\n                XCTAssertEqual(error as? FileSystemError, FileSystemError(.noEntry, path))\n            }\n        }\n    }\n\n    func testCompress() async throws {\n        #if !os(Windows)\n        guard SPM_posix_spawn_file_actions_addchdir_np_supported() else {\n            throw XCTSkip(\"working directory not supported on this platform\")\n        }\n        #endif\n\n         try await testWithTemporaryDirectory { tmpdir in\n             let archiver = ZipArchiver(fileSystem: localFileSystem)\n\n             let rootDir = tmpdir.appending(component: UUID().uuidString)\n             try localFileSystem.createDirectory(rootDir)\n             try localFileSystem.writeFileContents(rootDir.appending(\"file1.txt\"), string: \"Hello World!\")\n\n             let dir1 = rootDir.appending(\"dir1\")\n             try localFileSystem.createDirectory(dir1)\n             try localFileSystem.writeFileContents(dir1.appending(\"file2.txt\"), string: \"Hello World 2!\")\n\n             let dir2 = dir1.appending(\"dir2\")\n             try localFileSystem.createDirectory(dir2)\n             try localFileSystem.writeFileContents(dir2.appending(\"file3.txt\"), string: \"Hello World 3!\")\n             try localFileSystem.writeFileContents(dir2.appending(\"file4.txt\"), string: \"Hello World 4!\")\n             try localFileSystem.createSymbolicLink(dir2.appending(\"file5.txt\"), pointingAt: dir1.appending(\"file2.txt\"), relative: true)\n\n             let archivePath = tmpdir.appending(component: UUID().uuidString + \".zip\")\n             try await archiver.compress(directory: rootDir, to: archivePath)\n             XCTAssertFileExists(archivePath)\n\n             let extractRootDir = tmpdir.appending(component: UUID().uuidString)\n             try localFileSystem.createDirectory(extractRootDir)\n             try await archiver.extract(from: archivePath, to: extractRootDir)\n             try localFileSystem.stripFirstLevel(of: extractRootDir)\n\n             XCTAssertFileExists(extractRootDir.appending(\"file1.txt\"))\n             XCTAssertEqual(\n                 try? localFileSystem.readFileContents(extractRootDir.appending(\"file1.txt\")),\n                 \"Hello World!\"\n             )\n\n             let extractedDir1 = extractRootDir.appending(\"dir1\")\n             XCTAssertDirectoryExists(extractedDir1)\n             XCTAssertFileExists(extractedDir1.appending(\"file2.txt\"))\n             XCTAssertEqual(\n                 try? localFileSystem.readFileContents(extractedDir1.appending(\"file2.txt\")),\n                 \"Hello World 2!\"\n             )\n\n             let extractedDir2 = extractedDir1.appending(\"dir2\")\n             XCTAssertDirectoryExists(extractedDir2)\n             XCTAssertFileExists(extractedDir2.appending(\"file3.txt\"))\n             XCTAssertEqual(\n                 try? localFileSystem.readFileContents(extractedDir2.appending(\"file3.txt\")),\n                 \"Hello World 3!\"\n             )\n             XCTAssertFileExists(extractedDir2.appending(\"file4.txt\"))\n             XCTAssertEqual(\n                 try? localFileSystem.readFileContents(extractedDir2.appending(\"file4.txt\")),\n                 \"Hello World 4!\"\n             )\n            \n             XCTAssertTrue(localFileSystem.isSymlink(extractedDir2.appending(\"file5.txt\")))\n             XCTAssertEqual(\n                 try? localFileSystem.readFileContents(extractedDir2.appending(\"file5.txt\")),\n                 try? localFileSystem.readFileContents(extractedDir1.appending(\"file2.txt\"))\n             )\n         }\n     }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/ArrayHelpersTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\nimport func Basics.nextItem\n@testable import func Basics.containsNonContiguousSubset\n@testable import func Basics.containsContiguousSubset\nimport Testing\n@Suite\nstruct ArrayHelpersTests {\n    @Test(\n        .tags(\n            Tag.TestSize.small,\n        ),\n        // Convert to parameterized test once https://github.com/swiftlang/swift-testing/pull/808\n        // is available in a Swift toolchain.\n    )\n    func nextItemReturnsExpectedValue() async throws {\n        #expect(nextItem(in: [0, 1, 2, 3, 4], after: 1) == 2)\n        #expect(nextItem(in: [0, 1, 2, 3, 4], after: 4) == nil)\n        #expect(nextItem(in: [\"zero\", \"one\", \"two\", \"three\", \"four\"], after: \"one\") == \"two\")\n        #expect(nextItem(in: [\"zero\", \"one\", \"two\", \"three\", \"four\"], after: \"does not exisr\") == nil)\n        #expect(nextItem(in: [], after: \"1\") == nil)\n        #expect(nextItem(in: [1], after: 1) == nil)\n        #expect(nextItem(in: [0, 1, 12, 1, 4], after: 1) == 12)\n    }\n\n    @Test(\n        .tags(\n            Tag.TestSize.small,\n        ),\n    )\n    func containsNonContiguousSubsetReturnsExpectedValue() async throws {\n        // Empty subset should always return true\n        #expect(containsNonContiguousSubset(array: [] as [String], subset: []) == true)\n        #expect(containsNonContiguousSubset(array: [] as [Int], subset: []) == true)\n        #expect(containsNonContiguousSubset(array: [] as [Bool], subset: []) == true)\n        #expect(containsNonContiguousSubset(array: [1, 2, 3], subset: []) == true)\n\n        // Empty array with non-empty subset should return false\n        #expect(containsNonContiguousSubset(array: [] as [Int], subset: [1]) == false)\n\n        // Single element tests\n        #expect(containsNonContiguousSubset(array: [1], subset: [1]) == true)\n        #expect(containsNonContiguousSubset(array: [1], subset: [2]) == false)\n\n        // Basic subset tests - all elements present\n        #expect(containsNonContiguousSubset(array: [1, 2, 3, 4, 5], subset: [1, 3, 5]) == true)\n        #expect(containsNonContiguousSubset(array: [1, 2, 3, 4, 5], subset: [5, 1, 3]) == true)  // Order doesn't matter\n        #expect(containsNonContiguousSubset(array: [1, 2, 3, 4, 5], subset: [2, 4]) == true)\n\n        // Missing elements tests\n        #expect(containsNonContiguousSubset(array: [1, 2, 3, 4, 5], subset: [1, 6]) == false)\n        #expect(containsNonContiguousSubset(array: [1, 2, 3, 4, 5], subset: [6, 7, 8]) == false)\n\n        // Duplicate elements in subset\n        #expect(containsNonContiguousSubset(array: [1, 2, 2, 3, 4], subset: [2, 2]) == true)\n        #expect(containsNonContiguousSubset(array: [1, 2, 3, 4], subset: [2, 2]) == true)  // Only one 2 in array, but still contains 2\n\n        // String tests\n        #expect(containsNonContiguousSubset(array: [\"a\", \"b\", \"c\", \"d\"], subset: [\"a\", \"c\"]) == true)\n        #expect(containsNonContiguousSubset(array: [\"a\", \"b\", \"c\", \"d\"], subset: [\"d\", \"a\"]) == true)\n        #expect(containsNonContiguousSubset(array: [\"a\", \"b\", \"c\", \"d\"], subset: [\"e\"]) == false)\n\n        // Subset same size as array\n        #expect(containsNonContiguousSubset(array: [1, 2, 3], subset: [3, 2, 1]) == true)\n        #expect(containsNonContiguousSubset(array: [1, 2, 3], subset: [1, 2, 4]) == false)\n\n        // Subset larger than array\n        #expect(containsNonContiguousSubset(array: [1, 2], subset: [1, 2, 3]) == false)\n    }\n\n    @Test(\n        .tags(\n            Tag.TestSize.small,\n        ),\n    )\n    func containsContiguousSubsetReturnsExpectedValue() async throws {\n        // Empty subset should always return true\n        #expect(containsContiguousSubset(array: [] as [String], subset: []) == true)\n        #expect(containsContiguousSubset(array: [] as [Int], subset: []) == true)\n        #expect(containsContiguousSubset(array: [] as [Bool], subset: []) == true)\n        #expect(containsContiguousSubset(array: [1, 2, 3], subset: []) == true)\n\n        // Empty array with non-empty subset should return false\n        #expect(containsContiguousSubset(array: [] as [Int], subset: [1]) == false)\n\n        // Single element tests\n        #expect(containsContiguousSubset(array: [1], subset: [1]) == true)\n        #expect(containsContiguousSubset(array: [1], subset: [2]) == false)\n\n        // Basic contiguous subset tests\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [2, 3, 4]) == true)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [1, 2]) == true)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [4, 5]) == true)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [1, 2, 3, 4, 5]) == true)  // Entire array\n\n        // Non-contiguous elements should return false\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [1, 3, 5]) == false)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [2, 4]) == false)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [1, 3]) == false)\n\n        // Wrong order should return false\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [3, 2, 1]) == false)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [5, 4, 3]) == false)\n\n        // Missing elements\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [1, 6]) == false)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4, 5], subset: [6, 7]) == false)\n\n        // Duplicate elements\n        #expect(containsContiguousSubset(array: [1, 2, 2, 3, 4], subset: [2, 2, 3]) == true)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 2, 4], subset: [2, 2]) == false)  // 2s are not contiguous\n        #expect(containsContiguousSubset(array: [1, 1, 2, 3], subset: [1, 1]) == true)\n\n        // String tests\n        #expect(containsContiguousSubset(array: [\"a\"], subset: [\"b\", \"c\"]) == false)\n        #expect(containsContiguousSubset(array: [\"a\"], subset: []) == true)\n        #expect(containsContiguousSubset(array: [\"a\", \"b\", \"c\", \"d\"], subset: [\"b\", \"c\"]) == true)\n        #expect(containsContiguousSubset(array: [\"a\", \"b\", \"c\", \"d\"], subset: [\"a\", \"c\"]) == false)  // Not contiguous\n        #expect(containsContiguousSubset(array: [\"hello\", \"world\", \"test\"], subset: [\"world\", \"test\"]) == true)\n\n        // Subset larger than array\n        #expect(containsContiguousSubset(array: [1, 2], subset: [1, 2, 3]) == false)\n\n        // Multiple occurrences - should find first match\n        #expect(containsContiguousSubset(array: [1, 2, 3, 1, 2, 3], subset: [1, 2]) == true)\n        #expect(containsContiguousSubset(array: [1, 2, 3, 1, 2, 3], subset: [2, 3]) == true)\n\n        // Edge case: subset at the end\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4], subset: [3, 4]) == true)\n\n        // Edge case: subset at the beginning\n        #expect(containsContiguousSubset(array: [1, 2, 3, 4], subset: [1, 2]) == true)\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/AsyncProcessTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport _InternalTestSupport\nimport _Concurrency\nimport Basics\nimport XCTest\n\nimport TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported\n\nimport class TSCBasic.BufferedOutputByteStream\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.Format\nimport class TSCBasic.Thread\nimport func TSCBasic.withTemporaryFile\n\n#if os(Windows)\nlet catExecutable = \"type\"\n#else\nlet catExecutable = \"cat\"\n#endif\n\nfinal class AsyncProcessTests: XCTestCase {\n    let echoExecutableArgs = getAsyncProcessArgs(executable: \"echo\")\n    let catExecutableArgs = getAsyncProcessArgs(executable: catExecutable)\n\n    func testBasicsProcess() throws {\n            let process = AsyncProcess(arguments: echoExecutableArgs + [\"hello\"])\n            try process.launch()\n            let result = try process.waitUntilExit()\n            XCTAssertEqual(try result.utf8Output(), \"hello\\(ProcessInfo.EOL)\")\n            XCTAssertEqual(result.exitStatus, .terminated(code: 0))\n            XCTAssertEqual(result.arguments, process.arguments)\n    }\n\n    func testBasicsScript() throws {\n            let process = AsyncProcess(scriptName: \"exit4\\(ProcessInfo.batSuffix)\")\n            try process.launch()\n            let result = try process.waitUntilExit()\n            XCTAssertEqual(result.exitStatus, .terminated(code: 4))\n    }\n\n    func testPopenBasic() throws {\n        // Test basic echo.\n        XCTAssertEqual(try AsyncProcess.popen(arguments: echoExecutableArgs + [\"hello\"]).utf8Output(), \"hello\\(ProcessInfo.EOL)\")\n    }\n\n    func testPopenWithBufferLargerThanAllocated() throws {\n        // Test buffer larger than that allocated.\n        try withTemporaryFile { file in\n            let count = 10000\n            let stream = BufferedOutputByteStream()\n            stream.send(Format.asRepeating(string: \"a\", count: count))\n            file.fileHandle.write(Data(stream.bytes.contents))\n            let actualStreamCount = stream.bytes.count\n            XCTAssertTrue(actualStreamCount == count, \"Actual stream count (\\(actualStreamCount)) is not as expected (\\(count))\")\n            let outputCount = try AsyncProcess.popen(arguments: catExecutableArgs + [file.path.pathString]).utf8Output().count\n            XCTAssert(outputCount == count, \"Actual count (\\(outputCount)) is not as expected (\\(count))\")\n        }\n    }\n\n    func testPopenLegacyAsync() throws {\n        #if os(Windows)\n        let args = [\"where.exe\", \"where\"]\n        let answer = \"C:\\\\Windows\\\\System32\\\\where.exe\"\n        #else\n        let args = [\"whoami\"]\n        let answer = NSUserName()\n        #endif\n        let popenResult = ThreadSafeBox<Result<AsyncProcessResult, Error>?>()\n        let group = DispatchGroup()\n        group.enter()\n        AsyncProcess.popen(arguments: args) { result in\n            popenResult.put(result)\n            group.leave()\n        }\n        group.wait()\n        switch popenResult.get() {\n        case .success(let processResult):\n            let output = try processResult.utf8Output()\n            XCTAssertTrue(output.hasPrefix(answer))\n        case .failure(let error):\n            XCTFail(\"error = \\(error)\")\n        case nil:\n            XCTFail()\n        }\n    }\n\n    @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)\n    func testPopenAsync() async throws {\n        #if os(Windows)\n        let args = [\"where.exe\", \"where\"]\n        let answer = \"C:\\\\Windows\\\\System32\\\\where.exe\"\n        #else\n        let args = [\"whoami\"]\n        let answer = NSUserName()\n        #endif\n        let processResult: AsyncProcessResult\n        do {\n            processResult = try await AsyncProcess.popen(arguments: args)\n        } catch {\n            XCTFail(\"error = \\(error)\")\n            return\n        }\n        let output = try processResult.utf8Output()\n        XCTAssertTrue(output.hasPrefix(answer))\n    }\n\n    func testCheckNonZeroExit() async throws {\n        do {\n            let output = try await AsyncProcess.checkNonZeroExit(args: echoExecutableArgs + [\"hello\"])\n            XCTAssertEqual(output, \"hello\\(ProcessInfo.EOL)\")\n        }\n\n        do {\n            let output = try await AsyncProcess.checkNonZeroExit(scriptName: \"exit4\\(ProcessInfo.batSuffix)\")\n            XCTFail(\"Unexpected success \\(output)\")\n        } catch AsyncProcessResult.Error.nonZeroExit(let result) {\n            XCTAssertEqual(result.exitStatus, .terminated(code: 4))\n        }\n    }\n\n    @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)\n    func testCheckNonZeroExitAsync() async throws {\n        do {\n            let output = try await AsyncProcess.checkNonZeroExit(args: echoExecutableArgs + [\"hello\"])\n            XCTAssertEqual(output, \"hello\\(ProcessInfo.EOL)\")\n        }\n\n        do {\n            let output = try await AsyncProcess.checkNonZeroExit(scriptName: \"exit4\\(ProcessInfo.batSuffix)\")\n            XCTFail(\"Unexpected success \\(output)\")\n        } catch AsyncProcessResult.Error.nonZeroExit(let result) {\n            XCTAssertEqual(result.exitStatus, .terminated(code: 4))\n        }\n    }\n\n    func testFindExecutable() throws {\n        try testWithTemporaryDirectory { tmpdir in\n            // This process should always work.\n            #if os(Windows)\n            XCTAssertTrue(AsyncProcess.findExecutable(\"cmd.exe\") != nil)\n            #else\n            XCTAssertTrue(AsyncProcess.findExecutable(\"ls\") != nil)\n            #endif\n\n            XCTAssertEqual(AsyncProcess.findExecutable(\"nonExistantProgram\"), nil)\n            XCTAssertEqual(AsyncProcess.findExecutable(\"\"), nil)\n\n            // Create a local nonexecutable file to test.\n            let tempExecutable = tmpdir.appending(component: \"nonExecutableProgram\")\n            #if os(Windows)\n            let exitScriptContent = ByteString(\"EXIT /B\")\n            #else\n            let exitScriptContent = ByteString(\"\"\"\n            #!/bin/sh\n            exit\n\n            \"\"\")\n            #endif\n            try localFileSystem.writeFileContents(tempExecutable, bytes: exitScriptContent)\n\n            try Environment.makeCustom([\"PATH\": tmpdir.pathString]) {\n                XCTAssertEqual(AsyncProcess.findExecutable(\"nonExecutableProgram\"), nil)\n            }\n        }\n    }\n\n    func testNonExecutableLaunch() throws {\n        try testWithTemporaryDirectory { tmpdir in\n            // Create a local nonexecutable file to test.\n            let tempExecutable = tmpdir.appending(component: \"nonExecutableProgram\")\n            try localFileSystem.writeFileContents(tempExecutable, bytes: \"\"\"\n            #!/bin/sh\n            exit\n\n            \"\"\")\n\n            try Environment.makeCustom([\"PATH\": tmpdir.pathString]) {\n                do {\n                    let process = AsyncProcess(args: \"nonExecutableProgram\")\n                    try process.launch()\n                    XCTFail(\"Should have failed to validate nonExecutableProgram\")\n                } catch AsyncProcess.Error.missingExecutableProgram(let program) {\n                    XCTAssert(program == \"nonExecutableProgram\")\n                }\n            }\n        }\n    }\n\n    func testThreadSafetyOnWaitUntilExit() throws {\n        let process = AsyncProcess(args: echoExecutableArgs + [\"hello\"])\n        try process.launch()\n\n        var result1 = \"\"\n        var result2 = \"\"\n\n        let t1 = Thread {\n            result1 = try! process.waitUntilExit().utf8Output()\n        }\n\n        let t2 = Thread {\n            result2 = try! process.waitUntilExit().utf8Output()\n        }\n\n        t1.start()\n        t2.start()\n        t1.join()\n        t2.join()\n\n        XCTAssertEqual(result1, \"hello\\(ProcessInfo.EOL)\")\n        XCTAssertEqual(result2, \"hello\\(ProcessInfo.EOL)\")\n    }\n\n    @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)\n    func testThreadSafetyOnWaitUntilExitAsync() async throws {\n        let process = AsyncProcess(args: echoExecutableArgs + [\"hello\"])\n        try process.launch()\n\n        let t1 = Task {\n            try await process.waitUntilExit().utf8Output()\n        }\n\n        let t2 = Task {\n            try await process.waitUntilExit().utf8Output()\n        }\n\n        let result1 = try await t1.value\n        let result2 = try await t2.value\n\n        XCTAssertEqual(result1, \"hello\\(ProcessInfo.EOL)\")\n        XCTAssertEqual(result2, \"hello\\(ProcessInfo.EOL)\")\n    }\n\n    func testStdin() throws {\n        let stdout = ThreadSafeBox<[UInt8]>([])\n        let process = AsyncProcess(scriptName: \"in-to-out\\(ProcessInfo.batSuffix)\", outputRedirection: .stream(stdout: { stdoutBytes in\n            stdout.mutate {\n                $0.append(contentsOf: stdoutBytes)\n            }\n        }, stderr: { _ in }))\n        let stdinStream = try process.launch()\n\n        stdinStream.write(\"hello\\(ProcessInfo.EOL)\")\n        stdinStream.flush()\n\n        try stdinStream.close()\n\n        try process.waitUntilExit()\n\n        XCTAssertEqual(String(decoding: stdout.get(), as: UTF8.self), \"hello\\(ProcessInfo.EOL)\")\n    }\n\n    func testStdoutStdErr() throws {\n        // A simple script to check that stdout and stderr are captured separatly.\n        do {\n            let result = try AsyncProcess.popen(scriptName: \"simple-stdout-stderr\\(ProcessInfo.batSuffix)\")\n            XCTAssertEqual(try result.utf8Output(), \"simple output\\(ProcessInfo.EOL)\")\n            XCTAssertEqual(try result.utf8stderrOutput(), \"simple error\\(ProcessInfo.EOL)\")\n        }\n\n        // A long stdout and stderr output.\n        do {\n            let result = try AsyncProcess.popen(scriptName: \"long-stdout-stderr\\(ProcessInfo.batSuffix)\")\n            let count = 16 * 1024\n            XCTAssertEqual(try result.utf8Output(), String(repeating: \"1\", count: count))\n            XCTAssertEqual(try result.utf8stderrOutput(), String(repeating: \"2\", count: count))\n        }\n\n        // This script will block if the streams are not read.\n        do {\n            let result = try AsyncProcess.popen(scriptName: \"deadlock-if-blocking-io\\(ProcessInfo.batSuffix)\")\n            let count = 16 * 1024\n            XCTAssertEqual(try result.utf8Output(), String(repeating: \"1\", count: count))\n            XCTAssertEqual(try result.utf8stderrOutput(), String(repeating: \"2\", count: count))\n        }\n    }\n\n    @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)\n    func testStdoutStdErrAsync() async throws {\n        // A simple script to check that stdout and stderr are captured separatly.\n        do {\n            let result = try await AsyncProcess.popen(scriptName: \"simple-stdout-stderr\\(ProcessInfo.batSuffix)\")\n            XCTAssertEqual(try result.utf8Output(), \"simple output\\(ProcessInfo.EOL)\")\n            XCTAssertEqual(try result.utf8stderrOutput(), \"simple error\\(ProcessInfo.EOL)\")\n        }\n\n        // A long stdout and stderr output.\n        do {\n            let result = try await AsyncProcess.popen(scriptName: \"long-stdout-stderr\\(ProcessInfo.batSuffix)\")\n            let count = 16 * 1024\n            XCTAssertEqual(try result.utf8Output(), String(repeating: \"1\", count: count))\n            XCTAssertEqual(try result.utf8stderrOutput(), String(repeating: \"2\", count: count))\n        }\n\n        // This script will block if the streams are not read.\n        do {\n            let result = try await AsyncProcess.popen(scriptName: \"deadlock-if-blocking-io\\(ProcessInfo.batSuffix)\")\n            let count = 16 * 1024\n            XCTAssertEqual(try result.utf8Output(), String(repeating: \"1\", count: count))\n            XCTAssertEqual(try result.utf8stderrOutput(), String(repeating: \"2\", count: count))\n        }\n    }\n\n    func testStdoutStdErrRedirected() throws {\n        // A simple script to check that stdout and stderr are captured in the same location.\n        do {\n            let process = AsyncProcess(\n                scriptName: \"simple-stdout-stderr\\(ProcessInfo.batSuffix)\",\n                outputRedirection: .collect(redirectStderr: true)\n            )\n            try process.launch()\n            let result = try process.waitUntilExit()\n            #if os(Windows)\n            let expectedStdout = \"simple output\\(ProcessInfo.EOL)\"\n            let expectedStderr = \"simple error\\(ProcessInfo.EOL)\"\n            #else\n            let expectedStdout = \"simple error\\(ProcessInfo.EOL)simple output\\(ProcessInfo.EOL)\"\n            let expectedStderr = \"\"\n            #endif\n            XCTAssertEqual(try result.utf8Output(), expectedStdout)\n            XCTAssertEqual(try result.utf8stderrOutput(), expectedStderr)\n        }\n\n        // A long stdout and stderr output.\n        do {\n            let process = AsyncProcess(\n                scriptName: \"long-stdout-stderr\\(ProcessInfo.batSuffix)\",\n                outputRedirection: .collect(redirectStderr: true)\n            )\n            try process.launch()\n            let result = try process.waitUntilExit()\n\n            let count = 16 * 1024\n            #if os(Windows)\n            let expectedStdout = String(repeating: \"1\", count: count)\n            let expectedStderr = String(repeating: \"2\", count: count)\n            #else\n            let expectedStdout = String(repeating: \"12\", count: count)\n            let expectedStderr = \"\"\n            #endif\n            XCTAssertEqual(try result.utf8Output(), expectedStdout)\n            XCTAssertEqual(try result.utf8stderrOutput(), expectedStderr)\n        }\n    }\n\n    func testStdoutStdErrStreaming() throws {\n        let stdout = ThreadSafeBox<[UInt8]>([])\n        let stderr = ThreadSafeBox<[UInt8]>([])\n        let process = AsyncProcess(scriptName: \"long-stdout-stderr\\(ProcessInfo.batSuffix)\", outputRedirection: .stream(stdout: { stdoutBytes in\n            stdout.mutate {\n                $0.append(contentsOf: stdoutBytes)\n            }\n        }, stderr: { stderrBytes in\n            stderr.mutate {\n                $0.append(contentsOf: stderrBytes)\n            }\n        }))\n        try process.launch()\n        try process.waitUntilExit()\n\n        let count = 16 * 1024\n        XCTAssertEqual(String(bytes: stdout.get(), encoding: .utf8), String(repeating: \"1\", count: count))\n        XCTAssertEqual(String(bytes: stderr.get(), encoding: .utf8), String(repeating: \"2\", count: count))\n    }\n\n    func testStdoutStdErrStreamingRedirected() throws {\n        let stdout = ThreadSafeBox<[UInt8]>([])\n        let stderr = ThreadSafeBox<[UInt8]>([])\n\n        let process = AsyncProcess(scriptName: \"long-stdout-stderr\\(ProcessInfo.batSuffix)\", outputRedirection: .stream(stdout: { stdoutBytes in\n            stdout.mutate {\n                $0.append(contentsOf: stdoutBytes)\n            }\n        }, stderr: { stderrBytes in\n            stderr.mutate {\n                $0.append(contentsOf: stderrBytes)\n            }\n        }, redirectStderr: true))\n        try process.launch()\n        try process.waitUntilExit()\n\n        let count = 16 * 1024\n        #if os(Windows)\n        let expectedStdout = String(repeating: \"1\", count: count)\n        let expectedStderr = String(repeating: \"2\", count: count)\n        #else\n        let expectedStdout = String(repeating: \"12\", count: count)\n        let expectedStderr = \"\"\n        #endif\n        XCTAssertEqual(String(bytes: stdout.get(), encoding: .utf8), expectedStdout)\n        XCTAssertEqual(String(bytes: stderr.get(), encoding: .utf8), expectedStderr)\n    }\n\n    func testWorkingDirectory() throws {\n        #if !os(Windows)\n        guard SPM_posix_spawn_file_actions_addchdir_np_supported() else {\n            // Skip this test since it's not supported in this OS.\n            return\n        }\n        #endif\n\n        try withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in\n            let parentPath = tempDirPath.appending(component: \"file\")\n            let childPath = tempDirPath.appending(component: \"subdir\").appending(component: \"file\")\n\n            try localFileSystem.writeFileContents(parentPath, bytes: ByteString(\"parent\"))\n            try localFileSystem.createDirectory(childPath.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(childPath, bytes: ByteString(\"child\"))\n\n            do {\n                let process = AsyncProcess(arguments: catExecutableArgs + [\"file\"], workingDirectory: tempDirPath)\n                try process.launch()\n                let result = try process.waitUntilExit()\n                XCTAssertEqual(try result.utf8Output(), \"parent\")\n            }\n\n            do {\n                let process = AsyncProcess(arguments: catExecutableArgs + [\"file\"], workingDirectory: childPath.parentDirectory)\n                try process.launch()\n                let result = try process.waitUntilExit()\n                XCTAssertEqual(try result.utf8Output(), \"child\")\n            }\n        }\n    }\n\n    func testAsyncStream() async throws {\n        // rdar://133548796\n        try XCTSkipIfPlatformCI()\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8547: 'swift test' was stalled.\")\n\n        let (stdoutStream, stdoutContinuation) = AsyncProcess.ReadableStream.makeStream()\n        let (stderrStream, stderrContinuation) = AsyncProcess.ReadableStream.makeStream()\n\n        let process = AsyncProcess(\n            scriptName: \"echo\\(ProcessInfo.batSuffix)\",\n            outputRedirection: .stream {\n                stdoutContinuation.yield($0)\n            } stderr: {\n                stderrContinuation.yield($0)\n            }\n        )\n\n        let result = try await withThrowingTaskGroup(of: Void.self) { group in\n            let stdin = try process.launch()\n\n            group.addTask {\n                var counter = 0\n                stdin.write(\"Hello \\(counter)\\(ProcessInfo.EOL)\")\n                stdin.flush()\n\n                for await output in stdoutStream {\n                    XCTAssertEqual(output, .init(\"Hello \\(counter)\\(ProcessInfo.EOL)\".utf8))\n                    counter += 1\n\n                    stdin.write(.init(\"Hello \\(counter)\\(ProcessInfo.EOL)\".utf8))\n                    stdin.flush()\n                }\n\n                XCTAssertEqual(counter, 5)\n\n                try stdin.close()\n            }\n\n            group.addTask {\n                var counter = 0\n                for await _ in stderrStream {\n                    counter += 1\n                }\n\n                XCTAssertEqual(counter, 0)\n            }\n\n            defer {\n                stdoutContinuation.finish()\n                stderrContinuation.finish()\n            }\n\n            return try await process.waitUntilExit()\n        }\n\n        XCTAssertEqual(result.exitStatus, .terminated(code: 0))\n    }\n\n    func testAsyncStreamHighLevelAPI() async throws {\n        // rdar://133548796\n        try XCTSkipIfPlatformCI()\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8547: 'swift test' was stalled.\")\n\n        let result = try await AsyncProcess.popen(\n            scriptName: \"echo\\(ProcessInfo.batSuffix)\", // maps to 'processInputs/echo' script\n            stdout: { stdin, stdout in\n                var counter = 0\n                stdin.write(\"Hello \\(counter)\\(ProcessInfo.EOL)\")\n                stdin.flush()\n\n                for await output in stdout {\n\n                    XCTAssertEqual(output, .init(\"Hello \\(counter)\\(ProcessInfo.EOL)\".utf8))\n                    counter += 1\n\n                    stdin.write(.init(\"Hello \\(counter)\\(ProcessInfo.EOL)\".utf8))\n                    stdin.flush()\n                }\n\n                XCTAssertEqual(counter, 5)\n\n                try stdin.close()\n            },\n            stderr: { stderr in\n                var counter = 0\n                for await _ in stderr {\n                    counter += 1\n                }\n\n                XCTAssertEqual(counter, 0)\n            }\n        )\n\n        XCTAssertEqual(result.exitStatus, .terminated(code: 0))\n    }\n}\n\nextension AsyncProcess {\n    private static func script(_ name: String) -> String {\n        AbsolutePath(#file).parentDirectory.appending(components: \"processInputs\", name).pathString\n    }\n\n    fileprivate convenience init(\n        scriptName: String,\n        arguments: [String] = [],\n        outputRedirection: OutputRedirection = .collect\n    ) {\n        self.init(\n            arguments: getAsyncProcessArgs(executable: AsyncProcess.script(scriptName)) + arguments,\n            environment: .current,\n            outputRedirection: outputRedirection\n        )\n    }\n\n    @discardableResult\n    fileprivate static func checkNonZeroExit(\n        args: [String],\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) async throws -> String {\n        try await self.checkNonZeroExit(\n            arguments: args,\n            environment: environment,\n            loggingHandler: loggingHandler\n        )\n    }\n\n    @available(*, noasync)\n    fileprivate static func checkNonZeroExit(\n        scriptName: String,\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) throws -> String {\n        try self.checkNonZeroExit(\n            args: self.script(scriptName),\n            environment: environment,\n            loggingHandler: loggingHandler\n        )\n    }\n\n    @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)\n    fileprivate static func checkNonZeroExit(\n        scriptName: String,\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) async throws -> String {\n        try await self.checkNonZeroExit(\n            args: self.script(scriptName),\n            environment: environment,\n            loggingHandler: loggingHandler\n        )\n    }\n\n    @available(*, noasync)\n    @discardableResult\n    fileprivate static func popen(\n        scriptName: String,\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) throws -> AsyncProcessResult {\n        try self.popen(arguments: getAsyncProcessArgs(executable: self.script(scriptName)), environment: .current, loggingHandler: loggingHandler)\n    }\n\n    @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)\n    @discardableResult\n    fileprivate static func popen(\n        scriptName: String,\n        environment: Environment = .current,\n        loggingHandler: LoggingHandler? = .none\n    ) async throws -> AsyncProcessResult {\n        try await self.popen(arguments: getAsyncProcessArgs(executable: self.script(scriptName)), environment: .current, loggingHandler: loggingHandler)\n    }\n\n    fileprivate static func popen(\n        scriptName: String,\n        stdout: @escaping AsyncProcess.DuplexStreamHandler,\n        stderr: AsyncProcess.ReadableStreamHandler? = nil\n    ) async throws -> AsyncProcessResult {\n        try await self.popen(arguments: getAsyncProcessArgs(executable: self.script(scriptName)), stdoutHandler: stdout, stderrHandler: stderr)\n    }\n}\n\nfileprivate func getAsyncProcessArgs(executable: String) -> [String] {\n    #if os(Windows)\n    let args = [\"cmd.exe\", \"/c\", executable]\n    #else\n    let args = [executable]\n    #endif\n    return args\n}\n"
  },
  {
    "path": "Tests/BasicsTests/AuthorizationProviderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport _InternalTestSupport\nimport XCTest\n\nfinal class AuthorizationProviderTests: XCTestCase {\n    func testBasicAPIs() {\n        let url = URL(\"http://\\(UUID().uuidString)\")\n        let user = UUID().uuidString\n        let password = UUID().uuidString\n\n        let provider = TestProvider(map: [url: (user: user, password: password)])\n        self.assertAuthentication(provider, for: url, expected: (user, password))\n    }\n\n    func testNetrc() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let netrcPath = tmpPath.appending(\".netrc\")\n\n            let provider = try NetrcAuthorizationProvider(path: netrcPath, fileSystem: localFileSystem)\n\n            let user = UUID().uuidString\n\n            let url = URL(\"http://\\(UUID().uuidString)\")\n            let password = UUID().uuidString\n\n            let otherURL = URL(\"https://\\(UUID().uuidString)\")\n            let otherPassword = UUID().uuidString\n\n            // Add\n            try await provider.addOrUpdate(for: url, user: user, password: password)\n            try await provider.addOrUpdate(for: otherURL, user: user, password: otherPassword)\n\n            self.assertAuthentication(provider, for: url, expected: (user, password))\n\n            // Update - the new password is appended to the end of file\n            let newPassword = UUID().uuidString\n            try await provider.addOrUpdate(for: url, user: user, password: newPassword)\n\n            // .netrc file now contains two entries for `url`: one with `password` and the other with `newPassword`.\n            // `NetrcAuthorizationProvider` returns the last entry it finds.\n            self.assertAuthentication(provider, for: url, expected: (user, newPassword))\n\n            // Make sure the previous entry is still there\n            XCTAssertNotNil(\n                provider.machines.first(where: {\n                    $0.name == url.host!.lowercased() && $0.login == user && $0.password == password\n                })\n            )\n\n            self.assertAuthentication(provider, for: otherURL, expected: (user, otherPassword))\n        }\n    }\n\n    func testProtocolHostPort() throws {\n        #if !canImport(Security)\n        try XCTSkipIf(true)\n        #else\n        do {\n            let url = URL(\"http://localhost\")\n            let parsed = KeychainAuthorizationProvider.ProtocolHostPort(from: url)\n            XCTAssertNotNil(parsed)\n            XCTAssertEqual(parsed?.protocol, \"http\")\n            XCTAssertEqual(parsed?.host, \"localhost\")\n            XCTAssertNil(parsed?.port)\n            XCTAssertEqual(parsed?.protocolCFString, kSecAttrProtocolHTTP)\n            XCTAssertEqual(parsed?.description, \"http://localhost\")\n        }\n\n        do {\n            let url = URL(\"http://localhost:8080\")\n            let parsed = KeychainAuthorizationProvider.ProtocolHostPort(from: url)\n            XCTAssertNotNil(parsed)\n            XCTAssertEqual(parsed?.protocol, \"http\")\n            XCTAssertEqual(parsed?.host, \"localhost\")\n            XCTAssertEqual(parsed?.port, 8080)\n            XCTAssertEqual(parsed?.protocolCFString, kSecAttrProtocolHTTP)\n            XCTAssertEqual(parsed?.description, \"http://localhost:8080\")\n        }\n\n        do {\n            let url = URL(\"https://localhost\")\n            let parsed = KeychainAuthorizationProvider.ProtocolHostPort(from: url)\n            XCTAssertNotNil(parsed)\n            XCTAssertEqual(parsed?.protocol, \"https\")\n            XCTAssertEqual(parsed?.host, \"localhost\")\n            XCTAssertNil(parsed?.port)\n            XCTAssertEqual(parsed?.protocolCFString, kSecAttrProtocolHTTPS)\n            XCTAssertEqual(parsed?.description, \"https://localhost\")\n        }\n\n        do {\n            let url = URL(\"https://localhost:8080\")\n            let parsed = KeychainAuthorizationProvider.ProtocolHostPort(from: url)\n            XCTAssertNotNil(parsed)\n            XCTAssertEqual(parsed?.protocol, \"https\")\n            XCTAssertEqual(parsed?.host, \"localhost\")\n            XCTAssertEqual(parsed?.port, 8080)\n            XCTAssertEqual(parsed?.protocolCFString, kSecAttrProtocolHTTPS)\n            XCTAssertEqual(parsed?.description, \"https://localhost:8080\")\n        }\n\n        do {\n            let url = URL(\"https://:8080\")\n            let parsed = KeychainAuthorizationProvider.ProtocolHostPort(from: url)\n            XCTAssertNil(parsed)\n        }\n        #endif\n    }\n\n    func testKeychain_protocol() throws {\n        #if !canImport(Security) || !ENABLE_KEYCHAIN_TEST\n        try XCTSkipIf(true)\n        #else\n        let provider = KeychainAuthorizationProvider(observabilityScope: ObservabilitySystem.NOOP)\n\n        let user = UUID().uuidString\n\n        let httpURL = URL(\"http://\\(UUID().uuidString)\")\n        let httpPassword = UUID().uuidString\n\n        let httpsURL = URL(\"https://\\(UUID().uuidString)\")\n        let httpsPassword = UUID().uuidString\n\n        // Add\n        try await provider.addOrUpdate(for: httpURL, user: user, password: httpPassword)\n        try await provider.addOrUpdate(for: httpsURL, user: user, password: httpsPassword)\n\n        self.assertAuthentication(provider, for: httpURL, expected: (user, httpPassword))\n        self.assertAuthentication(provider, for: httpsURL, expected: (user, httpsPassword))\n\n        // Update\n        let newHTTPPassword = UUID().uuidString\n        try await provider.addOrUpdate(for: httpURL, user: user, password: newHTTPPassword)\n\n        let newHTTPSPassword = UUID().uuidString\n        try await provider.addOrUpdate(for: httpsURL, user: user, password: newHTTPSPassword)\n\n\n        // Existing password is updated\n        self.assertAuthentication(provider, for: httpURL, expected: (user, newHTTPPassword))\n        self.assertAuthentication(provider, for: httpsURL, expected: (user, newHTTPSPassword))\n\n        // Delete\n        try await provider.remove(for: httpURL)\n        XCTAssertNil(provider.authentication(for: httpURL))\n        self.assertAuthentication(provider, for: httpsURL, expected: (user, newHTTPSPassword))\n\n        try await provider.remove(for: httpsURL)\n        XCTAssertNil(provider.authentication(for: httpsURL))\n        #endif\n    }\n\n    func testKeychain_port() throws {\n        #if !canImport(Security) || !ENABLE_KEYCHAIN_TEST\n        try XCTSkipIf(true)\n        #else\n        let provider = KeychainAuthorizationProvider(observabilityScope: ObservabilitySystem.NOOP)\n\n        let user = UUID().uuidString\n\n        let noPortURL = URL(\"http://\\(UUID().uuidString)\")\n        let noPortPassword = UUID().uuidString\n\n        let portURL = URL(\"http://\\(UUID().uuidString):8971\")\n        let portPassword = UUID().uuidString\n\n        // Add\n        try await provider.addOrUpdate(for: noPortURL, user: user, password: noPortPassword)\n        try await provider.addOrUpdate(for: portURL, user: user, password: portPassword)\n\n        self.assertAuthentication(provider, for: noPortURL, expected: (user, noPortPassword))\n        self.assertAuthentication(provider, for: portURL, expected: (user, portPassword))\n\n        // Update\n        let newPortPassword = UUID().uuidString\n        try await provider.addOrUpdate(for: portURL, user: user, password: newPortPassword)\n\n        let newNoPortPassword = UUID().uuidString\n        try await provider.addOrUpdate(for: noPortURL, user: user, password: newNoPortPassword)\n\n        // Existing password is updated\n        self.assertAuthentication(provider, for: portURL, expected: (user, newPortPassword))\n        self.assertAuthentication(provider, for: noPortURL, expected: (user, newNoPortPassword))\n\n        // Delete\n        try await provider.remove(for: noPortURL)\n        XCTAssertNil(provider.authentication(for: noPortURL))\n        self.assertAuthentication(provider, for: portURL, expected: (user, newPortPassword))\n\n        try await provider.remove(for: portURL)\n        XCTAssertNil(provider.authentication(for: portURL))\n        #endif\n    }\n\n    func testComposite() throws {\n        let url = URL(\"http://\\(UUID().uuidString)\")\n        let user = UUID().uuidString\n        let passwordOne = UUID().uuidString\n        let passwordTwo = UUID().uuidString\n\n        let providerOne = TestProvider(map: [url: (user: user, password: passwordOne)])\n        let providerTwo = TestProvider(map: [url: (user: user, password: passwordTwo)])\n\n        do {\n            // providerOne's password is returned first\n            let provider = CompositeAuthorizationProvider(\n                providerOne,\n                providerTwo,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            self.assertAuthentication(provider, for: url, expected: (user, passwordOne))\n        }\n\n        do {\n            // providerTwo's password is returned first\n            let provider = CompositeAuthorizationProvider(\n                providerTwo,\n                providerOne,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            self.assertAuthentication(provider, for: url, expected: (user, passwordTwo))\n        }\n\n        do {\n            // Neither has password\n            let unknownURL = URL(\"http://\\(UUID().uuidString)\")\n            let provider = CompositeAuthorizationProvider(\n                providerOne,\n                providerTwo,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            XCTAssertNil(provider.authentication(for: unknownURL))\n        }\n    }\n\n    private func assertAuthentication(\n        _ provider: AuthorizationProvider,\n        for url: URL,\n        expected: (user: String, password: String)\n    ) {\n        let authentication = provider.authentication(for: url)\n        XCTAssertEqual(authentication?.user, expected.user)\n        XCTAssertEqual(authentication?.password, expected.password)\n        XCTAssertEqual(\n            provider.httpAuthorizationHeader(for: url),\n            \"Basic \" + Data(\"\\(expected.user):\\(expected.password)\".utf8).base64EncodedString()\n        )\n    }\n}\n\nprivate struct TestProvider: AuthorizationProvider {\n    let map: [URL: (user: String, password: String)]\n\n    func authentication(for url: URL) -> (user: String, password: String)? {\n        self.map[url]\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/ByteStringExtensionsTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Testing\n\nimport struct TSCBasic.ByteString\n\nstruct ByteStringExtensionsTests {\n    @Test\n    func sHA256Checksum() {\n        let byteString = ByteString(encodingAsUTF8: \"abc\")\n        #expect(byteString.contents == [0x61, 0x62, 0x63])\n\n        // See https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/examples/sha_all.pdf\n        #expect(byteString.sha256Checksum == \"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\")\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/CancellatorTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport _InternalTestSupport\nimport XCTest\n\nimport class Basics.AsyncProcess\n\nfinal class CancellatorTests: XCTestCase {\n    func testHappyCase() throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let cancellator = Cancellator(observabilityScope: observability.topScope)\n        let worker = Worker(name: \"test\")\n        cancellator.register(name: worker.name, handler: worker.cancel)\n\n        let startSemaphore = DispatchSemaphore(value: 0)\n        let finishSemaphore = DispatchSemaphore(value: 0)\n        let finishDeadline = DispatchTime.now() + .seconds(5)\n        DispatchQueue.sharedConcurrent.async() {\n            startSemaphore.signal()\n            defer { finishSemaphore.signal() }\n            if case .timedOut = worker.work(deadline: finishDeadline) {\n                XCTFail(\"worker \\(worker.name) timed out\")\n            }\n        }\n\n        XCTAssertEqual(.success, startSemaphore.wait(timeout: .now() + .seconds(1)), \"timeout starting tasks\")\n\n        let cancelled = cancellator._cancel(deadline: finishDeadline + .seconds(5))\n        XCTAssertEqual(cancelled, 1)\n\n        XCTAssertEqual(.success, finishSemaphore.wait(timeout: finishDeadline + .seconds(5)), \"timeout finishing tasks\")\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testTSCProcess() throws {\n#if os(macOS)\n        try withTemporaryDirectory { temporaryDirectory in\n            let scriptPath = temporaryDirectory.appending(\"script\")\n            try localFileSystem.writeFileContents(\n                scriptPath,\n                string: \"\"\"\n                set -e\n\n                echo \"process started\"\n                sleep 10\n                echo \"exit normally\"\n                \"\"\"\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let cancellator = Cancellator(observabilityScope: observability.topScope)\n\n            // outputRedirection used to signal that the process started\n            let startSemaphore = ProcessStartedSemaphore(term: \"process started\")\n            let process = AsyncProcess(\n                arguments: [\"bash\", scriptPath.pathString],\n                outputRedirection: .stream(\n                    stdout: startSemaphore.handleOutput,\n                    stderr: startSemaphore.handleOutput\n                )\n            )\n\n            let registrationKey = cancellator.register(process)\n            XCTAssertNotNil(registrationKey)\n\n            let finishSemaphore = DispatchSemaphore(value: 0)\n            DispatchQueue.sharedConcurrent.async {\n                defer { finishSemaphore.signal() }\n                do {\n                    try process.launch()\n                    let result = try process.waitUntilExit()\n                    print(\"process finished\")\n                    XCTAssertEqual(result.exitStatus, .signalled(signal: SIGINT))\n                } catch {\n                    XCTFail(\"failed launching process: \\(error)\")\n                }\n            }\n\n            XCTAssertEqual(.success, startSemaphore.wait(timeout: .now() + .seconds(5)), \"timeout starting tasks\")\n            print(\"process started\")\n\n            let canncelled = cancellator._cancel(deadline: .now() + .seconds(1))\n            XCTAssertEqual(canncelled, 1)\n\n            XCTAssertEqual(.success, finishSemaphore.wait(timeout: .now() + .seconds(5)), \"timeout finishing tasks\")\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n#else\n        try XCTSkipIf(true, \"skipping on non-macOS, signal traps do not work well on docker\")\n#endif\n    }\n\n    func testTSCProcessForceKill() throws {\n#if os(macOS)\n        try withTemporaryDirectory { temporaryDirectory in\n            let scriptPath = temporaryDirectory.appending(\"script\")\n            try localFileSystem.writeFileContents(\n                scriptPath,\n                string: \"\"\"\n                set -e\n\n                trap_handler() {\n                    echo \"SIGINT trap\"\n                    sleep 10\n                    echo \"exit SIGINT trap\"\n                }\n\n                echo \"process started\"\n                trap trap_handler SIGINT\n                echo \"trap installed\"\n\n                sleep 10\n                echo \"exit normally\"\n                \"\"\"\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let cancellator = Cancellator(observabilityScope: observability.topScope)\n\n            // outputRedirection used to signal that the process SIGINT traps have been set up\n            let startSemaphore = ProcessStartedSemaphore(term: \"trap installed\")\n            let process = AsyncProcess(\n                arguments: [\"bash\", scriptPath.pathString],\n                outputRedirection: .stream(\n                    stdout: startSemaphore.handleOutput,\n                    stderr: startSemaphore.handleOutput\n                )\n            )\n            let registrationKey = cancellator.register(process)\n            XCTAssertNotNil(registrationKey)\n\n            let finishSemaphore = DispatchSemaphore(value: 0)\n            DispatchQueue.sharedConcurrent.async {\n                defer { finishSemaphore.signal() }\n                do {\n                    try process.launch()\n                    let result = try process.waitUntilExit()\n                    print(\"process finished\")\n                    XCTAssertEqual(result.exitStatus, .signalled(signal: SIGKILL))\n                } catch {\n                    XCTFail(\"failed launching process: \\(error)\")\n                }\n            }\n\n            XCTAssertEqual(.success, startSemaphore.wait(timeout: .now() + .seconds(5)), \"timeout starting tasks\")\n            print(\"process started\")\n\n            let cancelled = cancellator._cancel(deadline: .now() + .seconds(1))\n            XCTAssertEqual(cancelled, 1)\n\n            XCTAssertEqual(.success, finishSemaphore.wait(timeout: .now() + .seconds(5)), \"timeout finishing tasks\")\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n#else\n        try XCTSkipIf(true, \"skipping on non-macOS, signal traps do not work well on docker\")\n#endif\n    }\n\n    func testFoundationProcess() throws {\n#if os(macOS)\n        try withTemporaryDirectory { temporaryDirectory in\n            let scriptPath = temporaryDirectory.appending(\"script\")\n            try localFileSystem.writeFileContents(\n                scriptPath,\n                string: \"\"\"\n                set -e\n\n                echo \"process started\"\n\n                sleep 10\n                echo \"exit normally\"\n                \"\"\"\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let cancellator = Cancellator(observabilityScope: observability.topScope)\n\n            // pipe used to signal that the process started\n            let startSemaphore = ProcessStartedSemaphore(term: \"process started\")\n            let process = Foundation.Process()\n            process.executableURL = URL(fileURLWithPath: \"/bin/bash\")\n            process.arguments = [scriptPath.pathString]\n            let stdoutPipe = Pipe()\n            stdoutPipe.fileHandleForReading.readabilityHandler = { fileHandle in\n                startSemaphore.handleOutput([UInt8](fileHandle.availableData))\n            }\n            let stderrPipe = Pipe()\n            stderrPipe.fileHandleForReading.readabilityHandler = { fileHandle in\n                startSemaphore.handleOutput([UInt8](fileHandle.availableData))\n            }\n            process.standardOutput = stdoutPipe\n            process.standardError = stderrPipe\n\n            let registrationKey = cancellator.register(process)\n            XCTAssertNotNil(registrationKey)\n\n            let finishSemaphore = DispatchSemaphore(value: 0)\n\n            DispatchQueue.sharedConcurrent.async {\n                defer { finishSemaphore.signal() }\n                do {\n                    try process.run()\n                } catch {\n                    XCTFail(\"Process failed to run with error: \\(error)\")\n                }\n                process.waitUntilExit()\n                print(\"process finished\")\n                XCTAssertEqual(process.terminationStatus, SIGINT)\n            }\n\n            XCTAssertEqual(.success, startSemaphore.wait(timeout: .now() + .seconds(5)), \"timeout starting tasks\")\n            print(\"process started\")\n\n            let canncelled = cancellator._cancel(deadline: .now() + .seconds(1))\n            XCTAssertEqual(canncelled, 1)\n\n            XCTAssertEqual(.success, finishSemaphore.wait(timeout: .now() + .seconds(5)), \"timeout finishing tasks\")\n            print(startSemaphore.output)\n            \n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n#else\n        try XCTSkipIf(true, \"skipping on non-macOS, signal traps do not work well on docker\")\n#endif\n    }\n\n    func testFoundationProcessForceKill() throws {\n#if os(macOS)\n\n        try withTemporaryDirectory { temporaryDirectory in\n            let scriptPath = temporaryDirectory.appending(\"script\")\n            try localFileSystem.writeFileContents(\n                scriptPath,\n                string: \"\"\"\n                set -e\n\n                trap_handler() {\n                    echo \"SIGINT trap\"\n                    sleep 10\n                    echo \"exit SIGINT trap\"\n                }\n\n                echo \"process started\"\n                trap trap_handler SIGINT\n                echo \"trap installed\"\n\n                sleep 10\n                echo \"exit normally\"\n                \"\"\"\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let cancellator = Cancellator(observabilityScope: observability.topScope)\n\n            // pipe used to signal that the process SIGINT traps have been set up\n            let startSemaphore = ProcessStartedSemaphore(term: \"trap installed\")\n            let process = Foundation.Process()\n            process.executableURL = URL(fileURLWithPath: \"/bin/bash\")\n            process.arguments = [scriptPath.pathString]\n            let stdoutPipe = Pipe()\n            stdoutPipe.fileHandleForReading.readabilityHandler = { fileHandle in\n                startSemaphore.handleOutput([UInt8](fileHandle.availableData))\n            }\n            let stderrPipe = Pipe()\n            stderrPipe.fileHandleForReading.readabilityHandler = { fileHandle in\n                startSemaphore.handleOutput([UInt8](fileHandle.availableData))\n            }\n            process.standardOutput = stdoutPipe\n            process.standardError = stderrPipe\n\n            let registrationKey = cancellator.register(process)\n            XCTAssertNotNil(registrationKey)\n\n            let finishSemaphore = DispatchSemaphore(value: 0)\n\n            DispatchQueue.sharedConcurrent.async {\n                defer { finishSemaphore.signal() }\n                do {\n                    try process.run()\n                } catch {\n                    XCTFail(\"Process failed to run with error: \\(error)\")\n                }\n                process.waitUntilExit()\n                print(\"process finished\")\n                XCTAssertEqual(process.terminationStatus, SIGTERM)\n            }\n\n            XCTAssertEqual(.success, startSemaphore.wait(timeout: .now() + .seconds(5)), \"timeout starting tasks\")\n            print(\"process started\")\n            print(startSemaphore.output)\n\n            let cancelled = cancellator._cancel(deadline: .now() + .seconds(1))\n            XCTAssertEqual(cancelled, 1)\n\n            XCTAssertEqual(.success, finishSemaphore.wait(timeout: .now() + .seconds(5)), \"timeout finishing tasks\")\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n#else\n        try XCTSkipIf(true, \"skipping on non-macOS, signal traps do not work well on docker\")\n#endif\n    }\n\n    func testConcurrency() throws {\n#if !os(macOS)\n        try XCTSkipIf(true, \"skipping on non-macOS because of timeout problems\")\n#endif\n        let observability = ObservabilitySystem.makeForTesting()\n        let cancellator = Cancellator(observabilityScope: observability.topScope)\n\n        let total = Concurrency.maxOperations\n        let workers: [Worker] = (0 ..< total).map { index in\n            let worker = Worker(name: \"worker \\(index)\")\n            cancellator.register(name: worker.name, handler: worker.cancel)\n            return worker\n        }\n\n        let startGroup = DispatchGroup()\n        let finishGroup = DispatchGroup()\n        let finishDeadline = DispatchTime.now() + .seconds(5)\n        let results = ThreadSafeKeyValueStore<String, DispatchTimeoutResult>()\n        for worker in workers {\n            startGroup.enter()\n            DispatchQueue.sharedConcurrent.async(group: finishGroup) {\n                startGroup.leave()\n                results[worker.name] = worker.work(deadline: finishDeadline)\n            }\n        }\n\n        XCTAssertEqual(.success, startGroup.wait(timeout: .now() + .seconds(1)), \"timeout starting tasks\")\n\n        let cancelled = cancellator._cancel(deadline: finishDeadline + .seconds(5))\n        XCTAssertEqual(cancelled, total)\n\n        XCTAssertEqual(.success, finishGroup.wait(timeout: finishDeadline + .seconds(5)), \"timeout finishing tasks\")\n\n        XCTAssertEqual(results.count, total)\n        for (name, result) in results.get() {\n            if case .timedOut = result {\n                XCTFail(\"worker \\(name) timed out\")\n            }\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testTimeout() throws {\n        struct Worker {\n            @Sendable\n            func cancel() {\n                Thread.sleep(forTimeInterval: 5)\n            }\n        }\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let cancellator = Cancellator(observabilityScope: observability.topScope)\n        let worker = Worker()\n        cancellator.register(name: \"test\", handler: worker.cancel)\n\n        let startSemaphore = DispatchSemaphore(value: 0)\n        DispatchQueue.sharedConcurrent.async {\n            startSemaphore.signal()\n        }\n\n        XCTAssertEqual(.success, startSemaphore.wait(timeout: .now() + .seconds(1)), \"timeout starting tasks\")\n\n        let cancelled = cancellator._cancel(deadline: .now() + .seconds(1))\n        XCTAssertEqual(cancelled, 0)\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: .contains(\"timeout waiting for cancellation\"),\n                severity: .warning\n            )\n        }\n    }\n\n    func testAsyncTimeout() throws {\n        struct Worker: AsyncCancellable {\n            @Sendable\n            func cancel(deadline: DispatchTime) async throws {\n                try await Task.sleep(nanoseconds: 5_000_000_000)\n            }\n        }\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let cancellator = Cancellator(observabilityScope: observability.topScope)\n        let worker = Worker()\n        cancellator.register(name: \"test\", handler: worker)\n        let startSemaphore = DispatchSemaphore(value: 0)\n        DispatchQueue.sharedConcurrent.async {\n            startSemaphore.signal()\n        }\n\n        XCTAssertEqual(.success, startSemaphore.wait(timeout: .now() + .seconds(1)), \"timeout starting tasks\")\n\n        let cancelled = cancellator._cancel(deadline: .now() + .seconds(1))\n        XCTAssertEqual(cancelled, 0)\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: .contains(\"timeout waiting for cancellation\"),\n                severity: .warning\n            )\n        }\n    }\n}\n\nfileprivate struct Worker {\n    let name: String\n    let semaphore = DispatchSemaphore(value: 0)\n\n    init(name: String) {\n        self.name = name\n    }\n\n    func work(deadline: DispatchTime) -> DispatchTimeoutResult {\n        print(\"\\(self.name) work\")\n        return self.semaphore.wait(timeout: deadline)\n    }\n\n    @Sendable\n    func cancel() {\n        print(\"\\(self.name) cancel\")\n        self.semaphore.signal()\n    }\n}\n\nclass ProcessStartedSemaphore {\n    let term: String\n    let underlying = DispatchSemaphore(value: 0)\n    let lock = NSLock()\n    var trapped = false\n    var output = \"\"\n\n    init(term: String) {\n        self.term = term\n    }\n\n    @Sendable func handleOutput(_ bytes: [UInt8]) {\n        self.lock.withLock {\n            guard !self.trapped else {\n                return\n            }\n            if let output = String(bytes: bytes, encoding: .utf8) {\n                self.output += output\n            }\n            if self.output.contains(self.term) {\n                self.trapped = true\n                self.underlying.signal()\n            }\n        }\n    }\n\n    func wait(timeout: DispatchTime) -> DispatchTimeoutResult {\n        self.underlying.wait(timeout: timeout)\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/ConcurrencyHelpersTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\n@testable import Basics\nimport TSCTestSupport\nimport Testing\n\nstruct ConcurrencyHelpersTest {\n    @Suite\n    struct ThreadSafeKeyValueStoreTests {\n\n        @Test(\n            .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8770\"),\n        )\n        func threadSafeKeyValueStore() async throws {\n            for num in 0 ..< 100 {\n                var expected = [Int: Int]()\n                let lock = NSLock()\n\n                let cache = ThreadSafeKeyValueStore<Int, Int>()\n\n                try await withThrowingTaskGroup(of: Void.self) { group in\n                    for index in 0 ..< 1000 {\n                        group.addTask {\n                            try await Task.sleep(nanoseconds: UInt64(Double.random(in: 100 ... 300) * 1000))\n                            let value = Int.random(in: Int.min ..< Int.max)\n                            lock.withLock {\n                                expected[index] = value\n                            }\n                            cache.memoize(index) {\n                                value\n                            }\n                            cache.memoize(index) {\n                                Int.random(in: Int.min ..< Int.max)\n                            }\n                        }\n                    }\n                    try await group.waitForAll()\n                }\n\n                expected.forEach { key, value in\n                    #expect(cache[key] == value, \"Iteration \\(num) failed\")\n                }\n            }\n        }\n\n        @Test(\n            .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8770\"),\n        )\n        func threadSafeArrayStore() async throws {\n            for num in 0 ..< 100 {\n                var expected = [Int]()\n                let lock = NSLock()\n\n                let cache = ThreadSafeArrayStore<Int>()\n\n                try await withThrowingTaskGroup(of: Void.self) { group in\n                    for _ in 0 ..< 1000 {\n                        group.addTask {\n                            try await Task.sleep(nanoseconds: UInt64(Double.random(in: 100 ... 300) * 1000))\n                            let value = Int.random(in: Int.min ..< Int.max)\n                            lock.withLock {\n                                expected.append(value)\n                            }\n                            cache.append(value)\n                        }\n                    }\n                    try await group.waitForAll()\n                }\n\n                let expectedSorted = expected.sorted()\n                let resultsSorted = cache.get().sorted()\n                #expect(expectedSorted == resultsSorted, \"Iteration \\(num) failed\")\n            }\n       }\n    }\n\n    @Suite\n    struct AsyncOperationQueueTests {\n        fileprivate actor ResultsTracker {\n            var results = [Int]()\n            var maxConcurrent = 0\n            var currentConcurrent = 0\n\n            func incrementConcurrent() {\n                currentConcurrent += 1\n                maxConcurrent = max(maxConcurrent, currentConcurrent)\n            }\n\n            func decrementConcurrent() {\n                currentConcurrent -= 1\n            }\n\n            func appendResult(_ value: Int) {\n                results.append(value)\n            }\n        }\n\n        @Test\n        func limitsConcurrentOperations() async throws {\n            let queue = AsyncOperationQueue(concurrentTasks: 5)\n\n            let totalTasks = 20\n            let tracker = ResultsTracker()\n\n            try await withThrowingTaskGroup(of: Void.self) { group in\n                for index in 0..<totalTasks {\n                    group.addTask {\n                        try await queue.withOperation {\n                            await tracker.incrementConcurrent()\n                            try? await Task.sleep(nanoseconds: 5_000_000)\n                            await tracker.decrementConcurrent()\n                            await tracker.appendResult(index)\n                        }\n                    }\n                }\n                try await group.waitForAll()\n            }\n\n            let maxConcurrent = await tracker.maxConcurrent\n            let results = await tracker.results\n\n            // Check that at no point did we exceed 5 concurrent operations\n            #expect(maxConcurrent == 5)\n            #expect(results.count == totalTasks)\n        }\n\n        @Test\n        func passesThroughWhenUnderConcurrencyLimit() async throws {\n            let queue = AsyncOperationQueue(concurrentTasks: 5)\n\n            let totalTasks = 5\n            let tracker = ResultsTracker()\n\n            try await withThrowingTaskGroup(of: Void.self) { group in\n                for index in 0..<totalTasks {\n                    group.addTask {\n                        try await queue.withOperation {\n                            await tracker.incrementConcurrent()\n                            try? await Task.sleep(nanoseconds: 5_000_000)\n                            await tracker.decrementConcurrent()\n                            await tracker.appendResult(index)\n                        }\n                    }\n                }\n                try await group.waitForAll()\n            }\n\n            let maxConcurrent = await tracker.maxConcurrent\n            let results = await tracker.results\n\n            // Check that we never exceeded the concurrency limit\n            #expect(maxConcurrent <= 5)\n            #expect(results.count == totalTasks)\n        }\n\n        @Test\n        func handlesImmediateCancellation() async throws {\n            let queue = AsyncOperationQueue(concurrentTasks: 5)\n            let totalTasks = 20\n            let tracker = ResultsTracker()\n\n            await #expect(throws: _Concurrency.CancellationError.self) {\n                try await withThrowingTaskGroup(of: Void.self) { group in\n                    // Cancel the task group immediately\n                    group.cancelAll()\n\n                    for index in 0..<totalTasks {\n                        group.addTask {\n                            try await queue.withOperation {\n                                if Task.isCancelled {\n                                    throw _Concurrency.CancellationError()\n                                }\n                                await tracker.incrementConcurrent()\n                                // sleep for a long time to ensure cancellation can occur.\n                                // If this is too short the cancellation may be triggered after\n                                // all tasks have completed.\n                                try await Task.sleep(nanoseconds: 10_000_000_000)\n                                await tracker.decrementConcurrent()\n                                await tracker.appendResult(index)\n                            }\n                        }\n                    }\n                    try await group.waitForAll()\n                }\n            }\n\n            let maxConcurrent = await tracker.maxConcurrent\n            let results = await tracker.results\n\n            #expect(maxConcurrent <= 5)\n            #expect(results.count < totalTasks)\n        }\n\n        @Test\n        func handlesCancellationDuringWait() async throws {\n            let queue = AsyncOperationQueue(concurrentTasks: 5)\n            let totalTasks = 20\n            let tracker = ResultsTracker()\n\n            await #expect(throws: _Concurrency.CancellationError.self) {\n                try await withThrowingTaskGroup(of: Void.self) { group in\n                    for index in 0..<totalTasks {\n                        group.addTask {\n                            try await queue.withOperation {\n                                if Task.isCancelled {\n                                    throw _Concurrency.CancellationError()\n                                }\n                                await tracker.incrementConcurrent()\n                                try? await Task.sleep(nanoseconds: 5_000_000)\n                                await tracker.decrementConcurrent()\n                                await tracker.appendResult(index)\n                            }\n                        }\n                    }\n\n                    group.addTask { [group] in\n                        group.cancelAll()\n                    }\n                    try await group.waitForAll()\n                }\n            }\n\n            let maxConcurrent = await tracker.maxConcurrent\n            let results = await tracker.results\n\n            #expect(maxConcurrent <= 5)\n            #expect(results.count < totalTasks)\n        }\n    }\n}\n\nextension ConcurrencyHelpersTest {\n    @Suite struct ThreadSafeBoxTests {\n        // MARK: - Basic Functionality Tests\n\n        @Test\n        func basicGetAndPut() {\n            let box = ThreadSafeBox(42)\n            #expect(box.get() == 42)\n\n            box.put(100)\n            #expect(box.get() == 100)\n        }\n\n        @Test\n        func mutateReturningNewValue() {\n            let box = ThreadSafeBox(10)\n            box.mutate { value in\n                value * 2\n            }\n            #expect(box.get() == 20)\n        }\n\n        @Test\n        func mutateInPlace() {\n            let box = ThreadSafeBox([1, 2, 3])\n            box.mutate { value in\n                value.append(4)\n            }\n            #expect(box.get() == [1, 2, 3, 4])\n        }\n\n        // MARK: - Optional Value Tests\n\n        @Test\n        func optionalInitEmpty() {\n            let box = ThreadSafeBox<Int?>()\n            #expect(box.get() == nil)\n        }\n\n        @Test\n        func optionalClear() {\n            let box = ThreadSafeBox<Int?>(42)\n            #expect(box.get() == 42)\n\n            box.clear()\n            #expect(box.get() == nil)\n        }\n\n        @Test\n        func optionalGetWithDefault() {\n            let emptyBox = ThreadSafeBox<Int?>()\n            #expect(emptyBox.get(default: 999) == 999)\n\n            let filledBox = ThreadSafeBox<Int?>(42)\n            #expect(filledBox.get(default: 999) == 42)\n        }\n\n        @Test\n        func memoizeComputesOnce() {\n            let box = ThreadSafeBox<Int?>()\n            var computeCount = 0\n\n            let result1 = box.memoize {\n                computeCount += 1\n                return 42\n            }\n            #expect(result1 == 42)\n            #expect(computeCount == 1)\n\n            let result2 = box.memoize {\n                computeCount += 1\n                return 99\n            }\n            #expect(result2 == 42)\n            #expect(computeCount == 1)\n        }\n\n        @Test\n        func memoizeOptionalNilValue() {\n            let box = ThreadSafeBox<Int?>()\n            var computeCount = 0\n\n            let result1 = box.memoizeOptional {\n                computeCount += 1\n                return nil\n            }\n            #expect(result1 == nil)\n            #expect(computeCount == 1)\n\n            // Should recompute since result was nil\n            let result2 = box.memoizeOptional {\n                computeCount += 1\n                return 42\n            }\n            #expect(result2 == 42)\n            #expect(computeCount == 2)\n\n            // Now should use cached value\n            let result3 = box.memoizeOptional {\n                computeCount += 1\n                return 99\n            }\n            #expect(result3 == 42)\n            #expect(computeCount == 2)\n        }\n\n        // MARK: - Int Extension Tests\n\n        @Test\n        func intIncrement() {\n            let box = ThreadSafeBox(0)\n            box.increment()\n            #expect(box.get() == 1)\n            box.increment()\n            #expect(box.get() == 2)\n        }\n\n        @Test\n        func intDecrement() {\n            let box = ThreadSafeBox(10)\n            box.decrement()\n            #expect(box.get() == 9)\n            box.decrement()\n            #expect(box.get() == 8)\n        }\n\n        // MARK: - String Extension Tests\n\n        @Test\n        func stringAppend() {\n            let box = ThreadSafeBox(\"Hello\")\n            box.append(\" World\")\n            #expect(box.get() == \"Hello World\")\n            box.append(\"!\")\n            #expect(box.get() == \"Hello World!\")\n        }\n\n        // MARK: - Dynamic Member Lookup Tests\n\n        @Test\n        func dynamicMemberReadOnly() {\n            struct Person {\n                let name: String\n                let age: Int\n            }\n\n            let box = ThreadSafeBox(Person(name: \"Alice\", age: 30))\n            #expect(box.name == \"Alice\")\n            #expect(box.age == 30)\n        }\n\n        @Test\n        func dynamicMemberWritable() {\n            struct Counter {\n                var count: Int\n                var label: String\n            }\n\n            let box = ThreadSafeBox(Counter(count: 0, label: \"Test\"))\n            #expect(box.count == 0)\n            #expect(box.label == \"Test\")\n\n            box.count = 42\n            #expect(box.count == 42)\n            #expect(box.label == \"Test\")\n\n            box.label = \"Updated\"\n            #expect(box.count == 42)\n            #expect(box.label == \"Updated\")\n        }\n\n        // MARK: - Thread Safety Tests\n\n        @Test(\n            .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8770\"),\n        )\n        func concurrentMemoization() async throws {\n            actor SerialCoordinator {\n                func processTask(_ index: Int, winner: inout Int?, cache: ThreadSafeBox<Int?>) {\n                    if winner == nil {\n                        winner = index\n                    }\n                    cache.memoize {\n                        index\n                    }\n                }\n            }\n\n            for num in 0 ..< 100 {\n                var winner: Int?\n                let cache = ThreadSafeBox<Int?>()\n                let coordinator = SerialCoordinator()\n\n                try await withThrowingTaskGroup(of: Void.self) { group in\n                    for index in 0 ..< 1000 {\n                        group.addTask {\n                            try await Task.sleep(nanoseconds: UInt64(Double.random(in: 100 ... 300) * 1000))\n                            await coordinator.processTask(index, winner: &winner, cache: cache)\n                        }\n                    }\n                    try await group.waitForAll()\n                }\n                #expect(cache.get() == winner, \"Iteration \\(num) failed\")\n            }\n        }\n\n        @Test\n        func concurrentIncrements() async throws {\n            let box = ThreadSafeBox(0)\n            let iterations = 1000\n\n            try await withThrowingTaskGroup(of: Void.self) { group in\n                for _ in 0..<iterations {\n                    group.addTask {\n                        box.increment()\n                    }\n                }\n                try await group.waitForAll()\n            }\n\n            #expect(box.get() == iterations)\n        }\n\n        @Test\n        func concurrentMutations() async throws {\n            let box = ThreadSafeBox([Int]())\n\n            try await withThrowingTaskGroup(of: Void.self) { group in\n                for index in 0..<100 {\n                    group.addTask {\n                        box.mutate { value in\n                            value.append(index)\n                        }\n                    }\n                }\n                try await group.waitForAll()\n            }\n\n            let result = box.get()\n            #expect(result.count == 100)\n            #expect(Set(result).count == 100)\n        }\n\n        @Test\n        func concurrentDynamicMemberWrites() async throws {\n            struct Counter {\n                var value: Int\n            }\n\n            let box = ThreadSafeBox(Counter(value: 0))\n\n            try await withThrowingTaskGroup(of: Void.self) { group in\n                for i in 0..<1000 {\n                    group.addTask {\n                        box.value = i\n                    }\n                }\n                try await group.waitForAll()\n            }\n\n            // Value should be one of the concurrent writes\n            let finalValue = box.value\n            #expect(finalValue >= 0 && finalValue < 1000)\n        }\n    }\n\n    @Suite struct AsyncThrowingValueMemoizerTests {\n        // MARK: - Basic Functionality Tests\n\n        @Test\n        func memoizeComputesOnlyOnce() async throws {\n            let memoizer = AsyncThrowingValueMemoizer<Int>()\n            nonisolated(unsafe) var computeCount = 0\n\n            let result1 = try await memoizer.memoize {\n                computeCount += 1\n                return 42\n            }\n            #expect(result1 == 42)\n            #expect(computeCount == 1)\n\n            let result2 = try await memoizer.memoize {\n                computeCount += 1\n                return 99\n            }\n            #expect(result2 == 42)\n            #expect(computeCount == 1)\n        }\n\n        @Test\n        func memoizeWithAsyncWork() async throws {\n            let memoizer = AsyncThrowingValueMemoizer<String>()\n\n            let result = try await memoizer.memoize {\n                try await Task.sleep(nanoseconds: 1_000_000)\n                return \"computed\"\n            }\n\n            #expect(result == \"computed\")\n        }\n\n        @Test\n        func memoizeCachesError() async throws {\n            struct TestError: Error, Equatable {}\n            let memoizer = AsyncThrowingValueMemoizer<Int>()\n\n            await #expect(throws: TestError.self) {\n                try await memoizer.memoize {\n                    throw TestError()\n                }\n            }\n\n            // After error, subsequent calls should return the cached error\n            await #expect(throws: TestError.self) {\n                try await memoizer.memoize {\n                    100\n                }\n            }\n        }\n\n        // MARK: - Concurrency Tests\n\n        @Test\n        func concurrentMemoizationSharesWork() async throws {\n            let memoizer = AsyncThrowingValueMemoizer<Int>()\n            nonisolated(unsafe) var computeCount = 0\n            let lock = NSLock()\n\n            try await withThrowingTaskGroup(of: Int.self) { group in\n                for _ in 0..<100 {\n                    group.addTask {\n                        try await memoizer.memoize {\n                            lock.withLock {\n                                computeCount += 1\n                            }\n                            try await Task.sleep(nanoseconds: 10_000_000)\n                            return 42\n                        }\n                    }\n                }\n\n                var results = [Int]()\n                for try await result in group {\n                    results.append(result)\n                }\n\n                #expect(results.count == 100)\n                #expect(results.allSatisfy { $0 == 42 })\n            }\n\n            // Should only compute once despite 100 concurrent calls\n            #expect(computeCount == 1)\n        }\n\n        @Test\n        func concurrentMemoizationWithQuickCompletion() async throws {\n            let memoizer = AsyncThrowingValueMemoizer<String>()\n            nonisolated(unsafe) var computeCount = 0\n            let lock = NSLock()\n\n            try await withThrowingTaskGroup(of: String.self) { group in\n                for i in 0..<50 {\n                    group.addTask {\n                        try await memoizer.memoize {\n                            lock.withLock {\n                                computeCount += 1\n                            }\n                            return \"value-\\(i)\"\n                        }\n                    }\n                }\n\n                var results = [String]()\n                for try await result in group {\n                    results.append(result)\n                }\n\n                #expect(results.count == 50)\n                // All results should be the same (from the first caller)\n                #expect(Set(results).count == 1)\n            }\n\n            #expect(computeCount == 1)\n        }\n\n        @Test\n        func concurrentErrorPropagation() async throws {\n            struct TestError: Error {}\n            let memoizer = AsyncThrowingValueMemoizer<Int>()\n            var errorCount = 0\n            let lock = NSLock()\n\n            await withThrowingTaskGroup(of: Void.self) { group in\n                for _ in 0..<20 {\n                    group.addTask {\n                        do {\n                            _ = try await memoizer.memoize {\n                                try await Task.sleep(nanoseconds: 5_000_000)\n                                throw TestError()\n                            }\n                        } catch {\n                            lock.withLock {\n                                errorCount += 1\n                            }\n                        }\n                    }\n                }\n\n                // Consume all results (ignoring errors)\n                while let _ = try? await group.next() {}\n            }\n\n            // All concurrent calls should receive the error\n            #expect(errorCount == 20)\n        }\n\n        @Test\n        func sequentialMemoizationAfterSuccess() async throws {\n            let memoizer = AsyncThrowingValueMemoizer<Int>()\n\n            let first = try await memoizer.memoize {\n                try await Task.sleep(nanoseconds: 1_000_000)\n                return 42\n            }\n            #expect(first == 42)\n\n            let second = try await memoizer.memoize {\n                try await Task.sleep(nanoseconds: 1_000_000)\n                return 99\n            }\n            #expect(second == 42)\n        }\n\n        @Test\n        func complexValueType() async throws {\n            struct ComplexValue: Sendable, Equatable {\n                let id: Int\n                let name: String\n                let tags: [String]\n            }\n\n            let memoizer = AsyncThrowingValueMemoizer<ComplexValue>()\n\n            let result = try await memoizer.memoize {\n                try await Task.sleep(nanoseconds: 1_000_000)\n                return ComplexValue(id: 1, name: \"Test\", tags: [\"a\", \"b\", \"c\"])\n            }\n\n            #expect(result.id == 1)\n            #expect(result.name == \"Test\")\n            #expect(result.tags == [\"a\", \"b\", \"c\"])\n        }\n\n        @Test\n        func memoizeWithVariableDelay() async throws {\n            let memoizer = AsyncThrowingValueMemoizer<Int>()\n            nonisolated(unsafe) var firstCallComplete = false\n            let lock = NSLock()\n\n            try await withThrowingTaskGroup(of: Int.self) { group in\n                // First task with delay\n                group.addTask {\n                    try await memoizer.memoize {\n                        try await Task.sleep(nanoseconds: 20_000_000)\n                        lock.withLock {\n                            firstCallComplete = true\n                        }\n                        return 100\n                    }\n                }\n\n                // Wait a bit then add more tasks\n                try await Task.sleep(nanoseconds: 5_000_000)\n\n                for _ in 0..<10 {\n                    group.addTask {\n                        try await memoizer.memoize {\n                            return 999\n                        }\n                    }\n                }\n\n                var results = [Int]()\n                for try await result in group {\n                    results.append(result)\n                }\n\n                #expect(results.count == 11)\n                #expect(results.allSatisfy { $0 == 100 })\n            }\n\n            let wasFirstCallComplete = lock.withLock { firstCallComplete }\n            #expect(wasFirstCallComplete == true)\n        }\n    }\n\n    @Suite struct AsyncKeyValueMemoizerTests {\n        // MARK: - Basic Functionality Tests\n\n        @Test\n        func memoizeComputesOncePerKey() async {\n            let memoizer = AsyncKeyValueMemoizer<String, Int>()\n            nonisolated(unsafe) var computeCount = 0\n\n            let result1 = await memoizer.memoize(\"key1\") {\n                computeCount += 1\n                return 42\n            }\n            #expect(result1 == 42)\n            #expect(computeCount == 1)\n\n            let result2 = await memoizer.memoize(\"key1\") {\n                computeCount += 1\n                return 99\n            }\n            #expect(result2 == 42)\n            #expect(computeCount == 1)\n\n            let result3 = await memoizer.memoize(\"key2\") {\n                computeCount += 1\n                return 100\n            }\n            #expect(result3 == 100)\n            #expect(computeCount == 2)\n        }\n\n        @Test\n        func memoizeWithAsyncWork() async {\n            let memoizer = AsyncKeyValueMemoizer<Int, String>()\n\n            let result = await memoizer.memoize(1) {\n                await Task.yield()\n                return \"computed\"\n            }\n\n            #expect(result == \"computed\")\n        }\n\n        @Test\n        func memoizeMultipleKeys() async {\n            let memoizer = AsyncKeyValueMemoizer<Int, String>()\n\n            let result1 = await memoizer.memoize(1) { \"value1\" }\n            let result2 = await memoizer.memoize(2) { \"value2\" }\n            let result3 = await memoizer.memoize(3) { \"value3\" }\n\n            #expect(result1 == \"value1\")\n            #expect(result2 == \"value2\")\n            #expect(result3 == \"value3\")\n\n            // Verify cached values\n            let cached1 = await memoizer.memoize(1) { \"different\" }\n            let cached2 = await memoizer.memoize(2) { \"different\" }\n            let cached3 = await memoizer.memoize(3) { \"different\" }\n\n            #expect(cached1 == \"value1\")\n            #expect(cached2 == \"value2\")\n            #expect(cached3 == \"value3\")\n        }\n\n        // MARK: - Concurrency Tests\n\n        @Test\n        func concurrentMemoizationSharesWorkPerKey() async {\n            let memoizer = AsyncKeyValueMemoizer<String, Int>()\n            nonisolated(unsafe) var computeCount = 0\n            let lock = NSLock()\n\n            await withTaskGroup(of: Int.self) { group in\n                for _ in 0..<100 {\n                    group.addTask {\n                        await memoizer.memoize(\"shared-key\") {\n                            lock.withLock {\n                                computeCount += 1\n                            }\n                            try? await Task.sleep(nanoseconds: 10_000_000)\n                            return 42\n                        }\n                    }\n                }\n\n                var results = [Int]()\n                for await result in group {\n                    results.append(result)\n                }\n\n                #expect(results.count == 100)\n                #expect(results.allSatisfy { $0 == 42 })\n            }\n\n            // Should only compute once despite 100 concurrent calls\n            #expect(computeCount == 1)\n        }\n\n        @Test\n        func concurrentMemoizationDifferentKeys() async {\n            let memoizer = AsyncKeyValueMemoizer<Int, String>()\n            nonisolated(unsafe) var computeCount = 0\n            let lock = NSLock()\n\n            await withTaskGroup(of: String.self) { group in\n                for i in 0..<50 {\n                    group.addTask {\n                        await memoizer.memoize(i) {\n                            lock.withLock {\n                                computeCount += 1\n                            }\n                            return \"value-\\(i)\"\n                        }\n                    }\n                }\n\n                var results = [String]()\n                for await result in group {\n                    results.append(result)\n                }\n\n                #expect(results.count == 50)\n                #expect(Set(results).count == 50)\n            }\n\n            #expect(computeCount == 50)\n        }\n\n        @Test\n        func complexKeyAndValueTypes() async {\n            struct Key: Hashable, Sendable {\n                let id: Int\n                let category: String\n            }\n\n            struct Value: Sendable, Equatable {\n                let data: [String]\n            }\n\n            let memoizer = AsyncKeyValueMemoizer<Key, Value>()\n\n            let key = Key(id: 1, category: \"test\")\n            let result = await memoizer.memoize(key) {\n                try? await Task.sleep(nanoseconds: 1_000_000)\n                return Value(data: [\"a\", \"b\", \"c\"])\n            }\n\n            #expect(result.data == [\"a\", \"b\", \"c\"])\n\n            let cached = await memoizer.memoize(key) {\n                Value(data: [\"different\"])\n            }\n            #expect(cached.data == [\"a\", \"b\", \"c\"])\n        }\n    }\n\n    @Suite struct ThrowingAsyncKeyValueMemoizerTests {\n        // MARK: - Basic Functionality Tests\n\n        @Test\n        func memoizeComputesOncePerKey() async throws {\n            let memoizer = ThrowingAsyncKeyValueMemoizer<String, Int>()\n            nonisolated(unsafe) var computeCount = 0\n\n            let result1 = try await memoizer.memoize(\"key1\") {\n                computeCount += 1\n                return 42\n            }\n            #expect(result1 == 42)\n            #expect(computeCount == 1)\n\n            let result2 = try await memoizer.memoize(\"key1\") {\n                computeCount += 1\n                return 99\n            }\n            #expect(result2 == 42)\n            #expect(computeCount == 1)\n\n            let result3 = try await memoizer.memoize(\"key2\") {\n                computeCount += 1\n                return 100\n            }\n            #expect(result3 == 100)\n            #expect(computeCount == 2)\n        }\n\n        @Test\n        func memoizeWithAsyncWork() async throws {\n            let memoizer = ThrowingAsyncKeyValueMemoizer<Int, String>()\n\n            let result = try await memoizer.memoize(1) {\n                try await Task.sleep(nanoseconds: 1_000_000)\n                return \"computed\"\n            }\n\n            #expect(result == \"computed\")\n        }\n\n        @Test\n        func memoizeCachesErrorPerKey() async throws {\n            struct TestError: Error, Equatable {}\n            let memoizer = ThrowingAsyncKeyValueMemoizer<String, Int>()\n\n            await #expect(throws: TestError.self) {\n                try await memoizer.memoize(\"error-key\") {\n                    throw TestError()\n                }\n            }\n\n            // Subsequent calls to same key should return cached error\n            await #expect(throws: TestError.self) {\n                try await memoizer.memoize(\"error-key\") {\n                    100\n                }\n            }\n\n            // Different key should work fine\n            let result = try await memoizer.memoize(\"success-key\") {\n                42\n            }\n            #expect(result == 42)\n        }\n\n        @Test\n        func memoizeMultipleKeysWithMixedResults() async throws {\n            struct TestError: Error {}\n            let memoizer = ThrowingAsyncKeyValueMemoizer<Int, String>()\n\n            let result1 = try await memoizer.memoize(1) { \"value1\" }\n            #expect(result1 == \"value1\")\n\n            await #expect(throws: TestError.self) {\n                try await memoizer.memoize(2) {\n                    throw TestError()\n                }\n            }\n\n            let result3 = try await memoizer.memoize(3) { \"value3\" }\n            #expect(result3 == \"value3\")\n\n            // Verify cached values\n            let cached1 = try await memoizer.memoize(1) { \"different\" }\n            #expect(cached1 == \"value1\")\n\n            await #expect(throws: TestError.self) {\n                try await memoizer.memoize(2) { \"different\" }\n            }\n\n            let cached3 = try await memoizer.memoize(3) { \"different\" }\n            #expect(cached3 == \"value3\")\n        }\n\n        // MARK: - Concurrency Tests\n\n        @Test\n        func concurrentMemoizationSharesWorkPerKey() async throws {\n            let memoizer = ThrowingAsyncKeyValueMemoizer<String, Int>()\n            nonisolated(unsafe) var computeCount = 0\n            let lock = NSLock()\n\n            try await withThrowingTaskGroup(of: Int.self) { group in\n                for _ in 0..<100 {\n                    group.addTask {\n                        try await memoizer.memoize(\"shared-key\") {\n                            lock.withLock {\n                                computeCount += 1\n                            }\n                            try await Task.sleep(nanoseconds: 10_000_000)\n                            return 42\n                        }\n                    }\n                }\n\n                var results = [Int]()\n                for try await result in group {\n                    results.append(result)\n                }\n\n                #expect(results.count == 100)\n                #expect(results.allSatisfy { $0 == 42 })\n            }\n\n            // Should only compute once despite 100 concurrent calls\n            #expect(computeCount == 1)\n        }\n\n        @Test\n        func concurrentErrorPropagationPerKey() async throws {\n            struct TestError: Error {}\n            let memoizer = ThrowingAsyncKeyValueMemoizer<String, Int>()\n            var errorCount = 0\n            let lock = NSLock()\n\n            await withThrowingTaskGroup(of: Void.self) { group in\n                for _ in 0..<20 {\n                    group.addTask {\n                        do {\n                            _ = try await memoizer.memoize(\"error-key\") {\n                                try await Task.sleep(nanoseconds: 5_000_000)\n                                throw TestError()\n                            }\n                        } catch {\n                            lock.withLock {\n                                errorCount += 1\n                            }\n                        }\n                    }\n                }\n\n                // Consume all results (ignoring errors)\n                while let _ = try? await group.next() {}\n            }\n\n            // All concurrent calls should receive the error\n            #expect(errorCount == 20)\n        }\n\n        @Test\n        func concurrentMemoizationDifferentKeys() async throws {\n            let memoizer = ThrowingAsyncKeyValueMemoizer<Int, String>()\n            nonisolated(unsafe) var computeCount = 0\n            let lock = NSLock()\n\n            try await withThrowingTaskGroup(of: String.self) { group in\n                for i in 0..<50 {\n                    group.addTask {\n                        try await memoizer.memoize(i) {\n                            lock.withLock {\n                                computeCount += 1\n                            }\n                            return \"value-\\(i)\"\n                        }\n                    }\n                }\n\n                var results = [String]()\n                for try await result in group {\n                    results.append(result)\n                }\n\n                #expect(results.count == 50)\n                #expect(Set(results).count == 50)\n            }\n\n            #expect(computeCount == 50)\n        }\n\n        @Test\n        func complexKeyAndValueTypes() async throws {\n            struct Key: Hashable, Sendable {\n                let id: Int\n                let category: String\n            }\n\n            struct Value: Sendable, Equatable {\n                let data: [String]\n            }\n\n            let memoizer = ThrowingAsyncKeyValueMemoizer<Key, Value>()\n\n            let key = Key(id: 1, category: \"test\")\n            let result = try await memoizer.memoize(key) {\n                try await Task.sleep(nanoseconds: 1_000_000)\n                return Value(data: [\"a\", \"b\", \"c\"])\n            }\n\n            #expect(result.data == [\"a\", \"b\", \"c\"])\n\n            let cached = try await memoizer.memoize(key) {\n                Value(data: [\"different\"])\n            }\n            #expect(cached.data == [\"a\", \"b\", \"c\"])\n        }\n\n        @Test\n        func memoizeWithVariableDelayMultipleKeys() async throws {\n            let memoizer = ThrowingAsyncKeyValueMemoizer<String, Int>()\n            nonisolated(unsafe) var firstCallComplete = false\n            let lock = NSLock()\n\n            try await withThrowingTaskGroup(of: (String, Int).self) { group in\n                // First task with delay for key1\n                group.addTask {\n                    let result = try await memoizer.memoize(\"key1\") {\n                        try await Task.sleep(nanoseconds: 20_000_000)\n                        lock.withLock {\n                            firstCallComplete = true\n                        }\n                        return 100\n                    }\n                    return (\"key1\", result)\n                }\n\n                // Wait a bit then add more tasks for both keys\n                try await Task.sleep(nanoseconds: 5_000_000)\n\n                for _ in 0..<10 {\n                    group.addTask {\n                        let result = try await memoizer.memoize(\"key1\") {\n                            return 999\n                        }\n                        return (\"key1\", result)\n                    }\n                }\n\n                for _ in 0..<10 {\n                    group.addTask {\n                        let result = try await memoizer.memoize(\"key2\") {\n                            return 200\n                        }\n                        return (\"key2\", result)\n                    }\n                }\n\n                var results: [String: [Int]] = [:]\n                for try await (key, value) in group {\n                    results[key, default: []].append(value)\n                }\n\n                #expect(results[\"key1\"]?.count == 11)\n                #expect(results[\"key1\"]?.allSatisfy { $0 == 100 } == true)\n                #expect(results[\"key2\"]?.count == 10)\n                #expect(results[\"key2\"]?.allSatisfy { $0 == 200 } == true)\n            }\n\n            let wasFirstCallComplete = lock.withLock { firstCallComplete }\n            #expect(wasFirstCallComplete == true)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/DictionaryTest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport Testing\n\nstruct DictionaryTests {\n    @Test\n    func throwingUniqueKeysWithValues() throws {\n        do {\n            let keysWithValues = [(\"key1\", \"value1\"), (\"key2\", \"value2\")]\n            let dictionary = try Dictionary(throwingUniqueKeysWithValues: keysWithValues)\n            #expect(dictionary[\"key1\"] == \"value1\")\n            #expect(dictionary[\"key2\"] == \"value2\")\n        }\n        do {\n            let keysWithValues = [(\"key1\", \"value\"), (\"key2\", \"value\")]\n            let dictionary = try Dictionary(throwingUniqueKeysWithValues: keysWithValues)\n            #expect(dictionary[\"key1\"] == \"value\")\n            #expect(dictionary[\"key2\"] == \"value\")\n        }\n        do {\n            let keysWithValues = [(\"key\", \"value1\"), (\"key\", \"value2\")]\n            #expect(throws: StringError(\"duplicate key found: 'key'\")) {\n                try Dictionary(throwingUniqueKeysWithValues: keysWithValues)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/DispatchTimeTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport Testing\n\nstruct DispatchTimeTests {\n    @Test\n    func differencePositive() {\n        let point: DispatchTime = .now()\n        let future: DispatchTime = point + .seconds(10)\n\n        let diff1: DispatchTimeInterval = point.distance(to: future)\n        #expect(diff1.seconds() == 10)\n\n        let diff2: DispatchTimeInterval = future.distance(to: point)\n        #expect(diff2.seconds() == -10)\n    }\n\n    @Test\n    func differenceNegative() {\n        let point: DispatchTime = .now()\n        let past: DispatchTime = point - .seconds(10)\n\n        let diff1: DispatchTimeInterval = point.distance(to: past)\n        #expect(diff1.seconds() == -10)\n\n        let diff2: DispatchTimeInterval = past.distance(to: point)\n        #expect(diff2.seconds() == 10)\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Environment/EnvironmentKeyTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\n@testable import Basics\nimport Testing\n\nstruct EnvironmentKeyTests {\n    @Test\n    func comparable() {\n        let key0 = EnvironmentKey(\"Test\")\n        let key1 = EnvironmentKey(\"Test1\")\n        #expect(key0 < key1)\n\n        let key2 = EnvironmentKey(\"test\")\n        #expect(key0 < key2)\n    }\n\n    @Test\n    func customStringConvertible() {\n        let key = EnvironmentKey(\"Test\")\n        #expect(key.description == \"Test\")\n    }\n\n    @Test\n    func encodable() throws {\n        let key = EnvironmentKey(\"Test\")\n        let data = try JSONEncoder().encode(key)\n        let string = String(data: data, encoding: .utf8)\n        #expect(string == #\"\"Test\"\"#)\n    }\n\n    @Test\n    func equatable() {\n        let key0 = EnvironmentKey(\"Test\")\n        let key1 = EnvironmentKey(\"Test\")\n        #expect(key0 == key1)\n\n        let key2 = EnvironmentKey(\"Test2\")\n        #expect(key0 != key2)\n\n        #if os(Windows)\n        // Test case insensitivity on windows\n        let key3 = EnvironmentKey(\"teSt\")\n            #expect(key0 == key3)\n        #endif\n    }\n\n    @Test\n    func expressibleByStringLiteral() {\n        let key0 = EnvironmentKey(\"Test\")\n        #expect(key0 == \"Test\")\n    }\n\n    @Test\n    func decodable() throws {\n        let jsonString = #\"\"Test\"\"#\n        let data = jsonString.data(using: .utf8)!\n        let key = try JSONDecoder().decode(EnvironmentKey.self, from: data)\n        #expect(key.rawValue == \"Test\")\n    }\n\n    @Test\n    func hashable() {\n        var set = Set<EnvironmentKey>()\n        let key0 = EnvironmentKey(\"Test\")\n        #expect(set.insert(key0).inserted)\n\n        let key1 = EnvironmentKey(\"Test\")\n        #expect(set.contains(key1))\n        #expect(!set.insert(key1).inserted)\n\n        let key2 = EnvironmentKey(\"Test2\")\n        #expect(!set.contains(key2))\n        #expect(set.insert(key2).inserted)\n\n        #if os(Windows)\n        // Test case insensitivity on windows\n        let key3 = EnvironmentKey(\"teSt\")\n            #expect(set.contains(key3))\n            #expect(!set.insert(key3).inserted)\n        #endif\n\n        #expect(set == [\"Test\", \"Test2\"])\n    }\n\n    @Test\n    func rawRepresentable() {\n        let key = EnvironmentKey(rawValue: \"Test\")\n        #expect(key?.rawValue == \"Test\")\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Environment/EnvironmentTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\n@_spi(SwiftPMInternal)\n@testable\nimport Basics\n\nimport Testing\nimport _InternalTestSupport\n\n@Suite(.serialized)\nstruct EnvironmentTests {\n    @Test\n    func initialize() {\n        let environment = Environment()\n        #expect(environment.isEmpty)\n    }\n\n    @Test\n    func setting_and_accessing_via_subscript() {\n        var environment = Environment()\n        let key = EnvironmentKey(\"TestKey\")\n        environment[key] = \"TestValue\"\n        #expect(environment[key] == \"TestValue\")\n    }\n\n    @Test\n    func initDictionaryFromSelf() {\n        let dictionary = [\n            \"TestKey\": \"TestValue\",\n            \"testKey\": \"TestValue2\",\n        ]\n        let environment = Environment(dictionary)\n        let expectedValue: String\n        let expectedCount: Int\n\n        #if os(Windows)\n            expectedValue = \"TestValue2\"  // uppercase sorts before lowercase, so the second value overwrites the first\n            expectedCount = 1\n        #else\n            expectedValue = \"TestValue\"\n            expectedCount = 2\n        #endif\n        #expect(environment[\"TestKey\"] == expectedValue)\n        #expect(environment.count == expectedCount)\n    }\n\n    @Test\n    func initSelfFromDictionary() {\n        let dictionary = [\"TestKey\": \"TestValue\"]\n        let environment = Environment(dictionary)\n        #expect(environment[\"TestKey\"] == \"TestValue\")\n        #expect(environment.count == 1)\n    }\n\n    func path(_ components: String...) -> String {\n        components.joined(separator: Environment.pathEntryDelimiter)\n    }\n\n    @Test\n    func prependPath() {\n        var environment = Environment()\n        let key = EnvironmentKey(UUID().uuidString)\n        #expect(environment[key] == nil)\n\n        environment.prependPath(key: key, value: \"/bin\")\n        #expect(environment[key] == path(\"/bin\"))\n\n        environment.prependPath(key: key, value: \"/usr/bin\")\n        #expect(environment[key] == path(\"/usr/bin\", \"/bin\"))\n\n        environment.prependPath(key: key, value: \"/usr/local/bin\")\n        #expect(environment[key] == path(\"/usr/local/bin\", \"/usr/bin\", \"/bin\"))\n\n        environment.prependPath(key: key, value: \"\")\n        #expect(environment[key] == path(\"/usr/local/bin\", \"/usr/bin\", \"/bin\"))\n    }\n\n    @Test\n    func appendPath() {\n        var environment = Environment()\n        let key = EnvironmentKey(UUID().uuidString)\n        #expect(environment[key] == nil)\n\n        environment.appendPath(key: key, value: \"/bin\")\n        #expect(environment[key] == path(\"/bin\"))\n\n        environment.appendPath(key: key, value: \"/usr/bin\")\n        #expect(environment[key] == path(\"/bin\", \"/usr/bin\"))\n\n        environment.appendPath(key: key, value: \"/usr/local/bin\")\n        #expect(environment[key] == path(\"/bin\", \"/usr/bin\", \"/usr/local/bin\"))\n\n        environment.appendPath(key: key, value: \"\")\n        #expect(environment[key] == path(\"/bin\", \"/usr/bin\", \"/usr/local/bin\"))\n    }\n\n    @Test\n    func pathEntryDelimiter() {\n        let expectedPathDelimiter: String\n        #if os(Windows)\n            expectedPathDelimiter = \";\"\n        #else\n            expectedPathDelimiter = \":\"\n        #endif\n        #expect(Environment.pathEntryDelimiter == expectedPathDelimiter)\n    }\n\n    /// Important: This test is inherently race-prone, if it is proven to be\n    /// flaky, it should run in a singled threaded environment/removed entirely.\n    @Test\n    func current() throws {\n        #if os(Windows)\n        let pathEnvVarName = \"Path\"\n        #else\n        let pathEnvVarName = \"PATH\"\n        #endif\n\n        #expect(Environment.current[\"PATH\"] == ProcessInfo.processInfo.environment[pathEnvVarName])\n    }\n\n    /// Important: This test is inherently race-prone, if it is proven to be\n    /// flaky, it should run in a singled threaded environment/removed entirely.\n    @Test\n    func makeCustom() async throws {\n        let key = EnvironmentKey(UUID().uuidString)\n        let value = \"TestValue\"\n\n        var customEnvironment = Environment()\n        customEnvironment[key] = value\n\n        #expect(Environment.current[key] == nil)\n        try Environment.makeCustom(customEnvironment) {\n            #expect(Environment.current[key] == value)\n        }\n        #expect(Environment.current[key] == nil)\n    }\n\n    /// Important: This test is inherently race-prone, if it is proven to be\n    /// flaky, it should run in a singled threaded environment/removed entirely.\n    @Test(\n        .disabled(if: CiEnvironment.runningInSmokeTestPipeline || CiEnvironment.runningInSelfHostedPipeline, \"This test can disrupt other tests running in parallel.\"),\n    )\n    func makeCustomPathEnv() async throws {\n        let customEnvironment: Environment = .current\n        let origPath = customEnvironment[.path]\n\n        try Environment.makeCustom([\"PATH\": \"/foo/bar\"]) {\n            #expect(Environment.current[.path] == \"/foo/bar\")\n        }\n        #expect(Environment.current[.path] == origPath)\n    }\n\n    /// Important: This test is inherently race-prone, if it is proven to be\n    /// flaky, it should run in a singled threaded environment/removed entirely.\n    @Test\n    func process() throws {\n        let key = EnvironmentKey(UUID().uuidString)\n        let value = \"TestValue\"\n\n        var environment = Environment.current\n        #expect(environment[key] == nil)\n\n        try Environment.set(key: key, value: value)\n        environment = Environment.current // reload\n        #expect(environment[key] == value)\n\n        try Environment.set(key: key, value: nil)\n        #expect(environment[key] == value)  // this is a copy!\n\n        environment = Environment.current // reload\n        #expect(environment[key] == nil)\n    }\n\n    @Test\n    func cachable() {\n        let term = EnvironmentKey(\"TERM\")\n        var environment = Environment()\n        environment[.path] = \"/usr/bin\"\n        environment[term] = \"xterm-256color\"\n\n        let cachableEnvironment = environment.cachable\n        #expect(cachableEnvironment[.path] != nil)\n        #expect(cachableEnvironment[term] == nil)\n    }\n\n    @Test\n    func collection() {\n        let environment: Environment = [\"TestKey\": \"TestValue\"]\n        #expect(environment.count == 1)\n        #expect(environment.first?.key == EnvironmentKey(\"TestKey\"))\n        #expect(environment.first?.value == \"TestValue\")\n    }\n\n    @Test\n    func description() {\n        var environment = Environment()\n        environment[EnvironmentKey(\"TestKey\")] = \"TestValue\"\n        #expect(environment.description == #\"[\"TestKey=TestValue\"]\"#)\n    }\n\n    @Test\n    func encodable() throws {\n        var environment = Environment()\n        environment[\"TestKey\"] = \"TestValue\"\n        let data = try JSONEncoder().encode(environment)\n        let jsonString = String(data: data, encoding: .utf8)\n        #expect(jsonString == #\"{\"TestKey\":\"TestValue\"}\"#)\n    }\n\n    @Test\n    func equatable() {\n        let environment0: Environment = [\"TestKey\": \"TestValue\"]\n        let environment1: Environment = [\"TestKey\": \"TestValue\"]\n        #expect(environment0 == environment1)\n\n#if os(Windows)\n        // Test case insensitivity on windows\n        let environment2: Environment = [\"testKey\": \"TestValue\"]\n            #expect(environment0 == environment2)\n#endif\n    }\n\n    @Test\n    func expressibleByDictionaryLiteral() {\n        let environment: Environment = [\"TestKey\": \"TestValue\"]\n        #expect(environment[\"TestKey\"] == \"TestValue\")\n    }\n\n\n    @Test\n    func decodable() throws {\n        let jsonString = #\"{\"TestKey\":\"TestValue\"}\"#\n        let data = jsonString.data(using: .utf8)!\n        let environment = try JSONDecoder().decode(Environment.self, from: data)\n        #expect(environment[EnvironmentKey(\"TestKey\")] == \"TestValue\")\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/FileSystem/CommonParentDirectoryTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2026 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport Testing\n\n#if os(Windows)\nprivate var windows: Bool { true }\n#else\nprivate var windows: Bool { false }\n#endif\n\n@Suite(\n    .tags(\n        .TestSize.small,\n        .Platform.FileSystem,\n    ),\n)\nstruct CommonParentDirectoryTests {\n\n    @Test(\n        arguments: [\n            // Basic cases\n            (id: \"identical_paths\", paths: [\"/a/b/c\", \"/a/b/c\"], expected: \"/a/b/c\".platformPath),\n            (id: \"simple_siblings\", paths: [\"/a/b/c\", \"/a/b/d\"], expected: \"/a/b\".platformPath),\n            (id: \"simple_cousins\", paths: [\"/a/b/c/d\", \"/a/b/e/f\"], expected: \"/a/b\".platformPath),\n            (id: \"usr_local_paths\", paths: [\"/usr/local/bin\", \"/usr/local/lib\"], expected: \"/usr/local\".platformPath),\n\n            // Multiple paths\n            (id: \"three_user_dirs\", paths: [\"/home/user/docs\", \"/home/user/music\", \"/home/user/videos\"], expected: \"/home/user\".platformPath),\n            (id: \"multiple_descendants\", paths: [\"/a/b/c/d\", \"/a/b/e/f\", \"/a/b/g\"], expected: \"/a/b\".platformPath),\n\n            // Different depths\n            (id: \"ancestor_descendant\", paths: [\"/a/b\", \"/a/b/c/d/e\"], expected: \"/a/b\".platformPath),\n            (id: \"descendant_ancestor\", paths: [\"/a/b/c/d/e\", \"/a/b\"], expected: \"/a/b\".platformPath),\n\n            // Root cases\n            (id: \"single_root\", paths: [\"/\"], expected: \"/\".platformPath),\n            (id: \"multiple_roots\", paths: [\"/\", \"/\"], expected: \"/\".platformPath),\n            (id: \"root_with_subdir\", paths: [\"/\", \"/usr\"], expected: \"/\".platformPath),\n            (id: \"no_common_parent\", paths: [\"/a/b\", \"/x/y\"], expected: \"/\".platformPath),\n            (id: \"system_dirs\", paths: [\"/usr/local\", \"/var/lib\", \"/etc/config\"], expected: \"/\".platformPath),\n\n            // Complex scenarios\n            (id: \"project_structure\", paths: [\"/projects/MyApp/Sources/MyApp/main.swift\", \"/projects/MyApp/Sources/Utils/helper.swift\", \"/projects/MyApp/Tests/MyAppTests/test.swift\", \"/projects/MyApp/Package.swift\"], expected: \"/projects/MyApp\".platformPath),\n            (id: \"var_subdirs\", paths: [\"/var/log/system/auth.log\", \"/var/log/system/kernel.log\", \"/var/log/apache/access.log\"], expected: \"/var/log\".platformPath),\n            (id: \"user_documents\", paths: [\"/home/alice/documents/work\", \"/home/alice/documents/personal\", \"/home/alice/music\"], expected: \"/home/alice\".platformPath),\n\n            // Ancestor relationships\n            (id: \"usr_hierarchy\", paths: [\"/usr\", \"/usr/local\", \"/usr/local/bin\", \"/usr/lib\"], expected: \"/usr\".platformPath),\n            (id: \"nested_hierarchy\", paths: [\"/a/b/c/d/e/f\", \"/a/b/c\", \"/a/b/c/d/g\"], expected: \"/a/b/c\".platformPath),\n\n            // Similar prefixes\n            (id: \"long_shared_prefix\", paths: [\"/very/long/shared/path/branch1/file1\", \"/very/long/shared/path/branch2/file2\", \"/very/long/shared/path/branch3/subdir/file3\"], expected: \"/very/long/shared/path\".platformPath),\n            (id: \"module_paths\", paths: [\"/app/module/feature/component.swift\", \"/app/module/feature\", \"/app/module/other/file.swift\"], expected: \"/app/module\".platformPath),\n\n            // Mixed depth paths\n            (id: \"mixed_depths\", paths: [\"/a/b/c/d/e/f/g/h\", \"/a/b\", \"/a/b/c/x/y/z\", \"/a/b/different\"], expected: \"/a/b\".platformPath),\n\n            // Single path edge case\n            (id: \"single_path\", paths: [\"/home/user/documents\"], expected: \"/home/user/documents\".platformPath),\n\n            // System paths\n            (id: \"system_paths_no_common\", paths: [\"/usr/local/bin\", \"/home/user\", \"/var/log\", \"/etc/config\"], expected: \"/\".platformPath),\n            (id: \"var_paths\", paths: [\"/var/log/messages\", \"/var/cache/apt\", \"/var/tmp/temp.txt\"], expected: \"/var\".platformPath),\n\n            // Identical multiple paths\n            (id: \"five_identical\", paths: [\"/home/user/docs\", \"/home/user/docs\", \"/home/user/docs\", \"/home/user/docs\", \"/home/user/docs\"], expected: \"/home/user/docs\".platformPath),\n\n            // Special characters and edge cases\n            (id: \"paths_with_spaces\", paths: [\"/home/user/My Documents\", \"/home/user/My Pictures\"], expected: \"/home/user\".platformPath),\n            (id: \"paths_with_dots\", paths: [\"/home/user/.config/app\", \"/home/user/.cache/app\"], expected: \"/home/user\".platformPath),\n            (id: \"paths_with_underscores\", paths: [\"/var/log/app_error.log\", \"/var/log/app_debug.log\"], expected: \"/var/log\".platformPath),\n            (id: \"paths_with_hyphens\", paths: [\"/opt/some-app/bin\", \"/opt/some-app/lib\"], expected: \"/opt/some-app\".platformPath),\n            (id: \"paths_with_numbers\", paths: [\"/backup/2023/january\", \"/backup/2023/february\"], expected: \"/backup/2023\".platformPath),\n            (id: \"mixed_special_chars\", paths: [\"/projects/app-v1.0_beta/src\", \"/projects/app-v1.0_beta/test\"], expected: \"/projects/app-v1.0_beta\".platformPath),\n\n            // Normalized path scenarios (testing AbsolutePath normalization)\n            // (id: \"paths_with_dot_segments\", paths: [\"/a/b/./c/d\", \"/a/b/./e/f\"], expected: \"/a/b\".platformPath),\n            (id: \"paths_with_dotdot_segments\", paths: [\"/a/b/c/../d\", \"/a/b/e/../f\"], expected: \"/a/b\".platformPath),\n            (id: \"mixed_normalization\", paths: [\"/a/b/./c/../d\", \"/a/b/e/./f\"], expected: \"/a/b\".platformPath),\n\n            // Deep nesting scenarios\n            (id: \"very_deep_paths\", paths: [\"/a/b/c/d/e/f/g/h/i/j/k/l/m/n\", \"/a/b/c/d/e/f/g/h/i/j/x/y/z\"], expected: \"/a/b/c/d/e/f/g/h/i/j\".platformPath),\n            (id: \"asymmetric_depths\", paths: [\"/a\", \"/a/b/c/d/e/f/g/h/i/j/k/l\"], expected: \"/a\".platformPath),\n\n            // File extensions and similar names\n            (id: \"files_with_extensions\", paths: [\"/src/main.swift\", \"/src/utils.swift\", \"/src/tests.swift\"], expected: \"/src\".platformPath),\n            (id: \"similar_filenames\", paths: [\"/docs/readme.txt\", \"/docs/readme.md\", \"/docs/readme.pdf\"], expected: \"/docs\".platformPath),\n\n            // Unicode and international characters (if supported by AbsolutePath)\n            (id: \"unicode_paths\", paths: [\"/home/用户/文档\", \"/home/用户/图片\"], expected: \"/home/用户\".platformPath),\n        ] as [(String, [String], String)]\n    )\n    func testGetCommonParentDirectory(id: String, paths: [String], expected: String) throws {\n        let absolutePaths = try paths.map { try AbsolutePath(validating: $0) }\n        let result = try getCommonParentDirectory(paths: absolutePaths)\n        let expectedPath = try AbsolutePath(validating: expected)\n\n        #expect(result == expectedPath, \"Test case '\\(id)': Expected common parent \\(expected) but got \\(result.pathString)\")\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .requireHostOS(.windows),\n        arguments: [\n            // Windows-specific path cases\n            (id: \"windows_drive_same\", paths: [#\"\\Users/John/Documents\"#, \"/Users/John/Pictures\"], expected: \"/Users/John\".platformPath),\n            (id: \"windows_drive_different\", paths: [\"/Program Files/App\", \"/Data/Files\"], expected: \"/\".platformPath),\n            (id: \"windows_system_paths\", paths: [\"/Windows/System32\", \"/Windows/Temp\"], expected: \"/Windows\".platformPath),\n            (id: \"windows_program_files\", paths: [\"/Program Files/App1\", \"/Program Files/App2\"], expected: \"/Program Files\".platformPath),\n            (id: \"windows_mixed_separators\", paths: [#\"\\Users\\John\\Documents\"#, \"/Users/John/Pictures\"], expected: \"/Users/John\".platformPath),\n            (id: \"windows_deep_hierarchy\", paths: [\"/Projects/MyApp/Sources/Utils/helper.cpp\", \"/Projects/MyApp/Tests/UnitTests/test.cpp\"], expected: \"/Projects/MyApp\".platformPath),\n            (id: \"windows_root_only\", paths: [\"/\", \"/\", #\"\\\"#], expected: \"/\".platformPath),\n            (id: \"windows_single_drive\", paths: [#\"\\\"#], expected: \"/\".platformPath),\n        ] as [(String, [String], String)]\n    )\n    func testGetCommonParentDirectoryWindows(id: String, paths: [String], expected: String) throws {\n        try withKnownIssue(\"Windows path handling may need adjustment\", isIntermittent: true) {\n            let absolutePaths = try paths.map { try AbsolutePath(validating: $0) }\n            let result = try getCommonParentDirectory(paths: absolutePaths)\n            let expectedPath = try AbsolutePath(validating: expected)\n\n            #expect(result == expectedPath, \"Windows test case '\\(id)': Expected common parent \\(expected) but got \\(result.pathString)\")\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\"Empty array edge case\")\n    func testGetCommonParentDirectoryEmptyArray() throws {\n        let emptyPaths: [AbsolutePath] = []\n        let result = try getCommonParentDirectory(paths: emptyPaths)\n\n        #expect(result == AbsolutePath.root, \"Empty array should return root directory\")\n    }\n}\n\nfileprivate extension String {\n    var platformPath: String {\n        if ProcessInfo.hostOperatingSystem == .windows {\n            return self.replacing(\"/\", with: #\"\\\"#)\n        }\n        return self\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/FileSystem/FileSystemTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\nimport TSCTestSupport\nimport Testing\n\n@testable import Basics\n\nstruct FileSystemTests {\n    @Test\n    func stripFirstLevelComponent() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        let rootPath = AbsolutePath(\"/root\")\n        try fileSystem.createDirectory(rootPath)\n\n        let totalDirectories = Int.random(in: 0..<100)\n        for index in 0..<totalDirectories {\n            let path = rootPath.appending(\"dir\\(index)\")\n            try fileSystem.createDirectory(path, recursive: false)\n        }\n\n        let totalFiles = Int.random(in: 0..<100)\n        for index in 0..<totalFiles {\n            let path = rootPath.appending(\"file\\(index)\")\n            try fileSystem.writeFileContents(path, string: \"\\(index)\")\n        }\n\n        do {\n            let contents = try fileSystem.getDirectoryContents(.root)\n            #expect(contents.count == 1)\n        }\n\n        try fileSystem.stripFirstLevel(of: .root)\n\n        do {\n            let contents = Set(try fileSystem.getDirectoryContents(.root))\n            #expect(contents.count == totalDirectories + totalFiles)\n\n            for index in 0..<totalDirectories {\n                #expect(contents.contains(\"dir\\(index)\"))\n            }\n            for index in 0..<totalFiles {\n                #expect(contents.contains(\"file\\(index)\"))\n            }\n        }\n    }\n\n    @Test\n    func stripFirstLevelComponentErrors() throws {\n        let functionUnderTest = \"stripFirstLevel\"\n        do {\n            let fileSystem = InMemoryFileSystem()\n            #expect(throws: StringError(\"\\(functionUnderTest) requires single top level directory\"))\n            {\n                try fileSystem.stripFirstLevel(of: .root)\n            }\n        }\n\n        do {\n            let fileSystem = InMemoryFileSystem()\n            for index in 0..<3 {\n                let path = AbsolutePath.root.appending(\"dir\\(index)\")\n                try fileSystem.createDirectory(path, recursive: false)\n            }\n            #expect(throws: StringError(\"\\(functionUnderTest) requires single top level directory\"))\n            {\n                try fileSystem.stripFirstLevel(of: .root)\n            }\n        }\n\n        do {\n            let fileSystem = InMemoryFileSystem()\n            for index in 0..<3 {\n                let path = AbsolutePath.root.appending(\"file\\(index)\")\n                try fileSystem.writeFileContents(path, string: \"\\(index)\")\n            }\n            #expect(throws: StringError(\"\\(functionUnderTest) requires single top level directory\"))\n            {\n                try fileSystem.stripFirstLevel(of: .root)\n            }\n        }\n\n        do {\n            let fileSystem = InMemoryFileSystem()\n            let path = AbsolutePath.root.appending(\"file\")\n            try fileSystem.writeFileContents(path, string: \"\")\n            #expect(throws: StringError(\"\\(functionUnderTest) requires single top level directory\"))\n            {\n                try fileSystem.stripFirstLevel(of: .root)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/FileSystem/InMemoryFilesSystemTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Basics\nimport struct TSCBasic.ByteString\nimport struct TSCBasic.FileSystemError\n\nimport Testing\nimport _InternalTestSupport\n\n@Suite(\n    .tags(\n        .TestSize.small,\n        .Platform.FileSystem,\n    ),\n)\nstruct InMemoryFileSystemTests {\n    private static let testFileContent = ByteString([0xAA, 0xBB, 0xCC])\n\n    @Test(\n        arguments: [\n            (\n                path: \"/\",\n                recursive: true,\n                expectedFiles: [\n                    (p: \"/\", shouldExist: true)\n                ],\n                expectError: false\n            ),\n            (\n                path: \"/tmp\",\n                recursive: true,\n                expectedFiles: [\n                    (p: \"/\", shouldExist: true),\n                    (p: \"/tmp\", shouldExist: true),\n                ],\n                expectError: false\n            ),\n            (\n                path: \"/tmp/ws\",\n                recursive: true,\n                expectedFiles: [\n                    (p: \"/\", shouldExist: true),\n                    (p: \"/tmp\", shouldExist: true),\n                    (p: \"/tmp/ws\", shouldExist: true),\n                ],\n                expectError: false\n            ),\n            (\n                path: \"/tmp/ws\",\n                recursive: false,\n                expectedFiles: [\n                    (p: \"/\", shouldExist: true),\n                    (p: \"/tmp\", shouldExist: true),\n                    (p: \"/tmp/ws\", shouldExist: true),\n                ],\n                expectError: true\n            ),\n        ]\n    )\n    func creatingDirectoryCreatesInternalFiles(\n        path: String,\n        recursive: Bool,\n        expectedFiles: [(String, Bool)],\n        expectError: Bool\n    ) async throws {\n        let fs = InMemoryFileSystem()\n        let pathUnderTest = AbsolutePath(path)\n\n        func errorMessage(_ pa: AbsolutePath, _ exists: Bool) -> String {\n            return\n                \"Path '\\(pa) \\(exists ? \"should exists, but doesn't\" : \"should not exist, but does.\")\"\n        }\n        if expectError {\n            #expect(throws: FileSystemError.self) {\n                try fs.createDirectory(pathUnderTest, recursive: recursive)\n            }\n        } else {\n            #expect(throws: Never.self) {\n                try fs.createDirectory(pathUnderTest, recursive: recursive)\n\n                for (p, shouldExist) in expectedFiles {\n                    let expectedPath = AbsolutePath(p)\n                    #expect(\n                        fs.exists(expectedPath) == shouldExist,\n                        \"\\(errorMessage(expectedPath, shouldExist))\")\n                }\n            }\n        }\n    }\n\n    @Test(\n        arguments: [\n            \"/\",\n            \"/tmp\",\n            \"/tmp/\",\n            \"/something/ws\",\n            \"/something/ws/\",\n            \"/what/is/this\",\n            \"/what/is/this/\",\n        ]\n    )\n    func callingCreateDirectoryOnAnExistingDirectoryIsSuccessful(path: String) async throws {\n        let root = AbsolutePath(path)\n        let fs = InMemoryFileSystem()\n\n        #expect(throws: Never.self) {\n            try fs.createDirectory(root, recursive: true)\n        }\n\n        #expect(throws: Never.self) {\n            try fs.createDirectory(root.appending(\"more\"), recursive: true)\n        }\n    }\n\n    struct writeFileContentsTests {\n\n        @Test\n        func testWriteFileContentsSuccessful() async throws {\n            let fs = InMemoryFileSystem()\n            let pathUnderTest = AbsolutePath(\"/myFile.zip\")\n\n            try fs.writeFileContents(pathUnderTest, bytes: testFileContent)\n\n            #expect(\n                fs.exists(pathUnderTest),\n                \"Path \\(pathUnderTest.pathString) does not exists when it should\")\n        }\n\n        @Test\n        func testWritingAFileWithANonExistingParentDirectoryFails() async throws {\n            let fs = InMemoryFileSystem()\n            let pathUnderTest = AbsolutePath(\"/tmp/myFile.zip\")\n\n            #expect(throws: FileSystemError.self) {\n                try fs.writeFileContents(pathUnderTest, bytes: testFileContent)\n            }\n\n            #expect(\n                !fs.exists(pathUnderTest),\n                \"Path \\(pathUnderTest.pathString) does exists when it should not\")\n        }\n\n        @Test\n        func errorOccursWhenWritingToRootDirectory() async throws {\n            let fs = InMemoryFileSystem()\n            let pathUnderTest = AbsolutePath(\"/\")\n\n            #expect(throws: FileSystemError.self) {\n                try fs.writeFileContents(pathUnderTest, bytes: testFileContent)\n            }\n        }\n\n        @Test\n        func testErrorOccursIfParentIsNotADirectory() async throws {\n            let fs = InMemoryFileSystem()\n            let aFile = AbsolutePath(\"/foo\")\n            try fs.writeFileContents(aFile, bytes: \"\")\n\n            let pathUnderTest = aFile.appending(\"myFile\")\n\n            #expect(throws: FileSystemError.self) {\n                try fs.writeFileContents(pathUnderTest, bytes: testFileContent)\n            }\n\n        }\n    }\n\n    struct testReadFileContentsTests {\n        @Test\n        func readingAFileThatDoesNotExistsRaisesAnError() async throws {\n            let fs = InMemoryFileSystem()\n            #expect(throws: FileSystemError.self) {\n                try fs.readFileContents(\"/file/does/not/exists\")\n            }\n        }\n\n        @Test\n        func readingExistingFileReturnsExpectedContents() async throws {\n            let fs = InMemoryFileSystem()\n            let pathUnderTest = AbsolutePath(\"/myFile.zip\")\n            try fs.writeFileContents(pathUnderTest, bytes: testFileContent)\n\n            let actualContents = try fs.readFileContents(pathUnderTest)\n\n            #expect(actualContents == testFileContent, \"Actual is not as expected\")\n        }\n\n        @Suite(\n            .tags(\n                .TestSize.small,\n            ),\n        )\n        struct ChangeCurrentWorkingDirectoryTests {\n            func errorOccursWhenChangingDirectoryToAFile() async throws {\n                let fileUnderTest = AbsolutePath.root.appending(components: \"Foo\", \"Bar\", \"baz.txt\")\n\n                let fs = InMemoryFileSystem(\n                    emptyFiles: [\n                        fileUnderTest.pathString\n                    ]\n                )\n\n                #expect(throws: FileSystemError(.notDirectory, fileUnderTest)) {\n                    try fs.changeCurrentWorkingDirectory(to: fileUnderTest)\n                }\n            }\n\n            func errorOccursWhenChangingDirectoryDoesNotExists() async throws {\n                let fs = InMemoryFileSystem()\n                let nonExistingDirectory = AbsolutePath.root.appending(components: \"does-not-exists\")\n\n                #expect(throws: FileSystemError(.noEntry, nonExistingDirectory)) {\n                    try fs.changeCurrentWorkingDirectory(to: nonExistingDirectory)\n                }\n            }\n\n            func changinDirectoryToTheParentOfAnExistingFileIsSuccessful() async throws {\n                let fileUnderTest = AbsolutePath.root.appending(components: \"Foo\", \"Bar\", \"baz.txt\")\n\n                let fs = InMemoryFileSystem(\n                    emptyFiles: [\n                        fileUnderTest.pathString\n                    ]\n                )\n\n                #expect(throws: Never.self) {\n                    try fs.changeCurrentWorkingDirectory(to: fileUnderTest.parentDirectory)\n                }\n            }\n        }\n\n        @Suite(\n            .tags(\n                .TestSize.small,\n            ),\n        )\n        struct GetDirectoryContentsTests {\n            func returnsExpectedItemsWhenDirectoryHasASingleFile() async throws {\n                let fileUnderTest = AbsolutePath.root.appending(components: \"Foo\", \"Bar\", \"baz.txt\")\n                let fs = InMemoryFileSystem(\n                    emptyFiles: [\n                        fileUnderTest.pathString\n                    ]\n                )\n\n                try fs.changeCurrentWorkingDirectory(to: fileUnderTest.parentDirectory)\n                let contents = try fs.getDirectoryContents(fileUnderTest.parentDirectory)\n\n                #expect([\"baz.txt\"] == contents)\n            }\n        }\n\n        @Test\n        func readingADirectoryFailsWithAnError() async throws {\n            let fs = InMemoryFileSystem()\n            let pathUnderTest = AbsolutePath(\"/myFile.zip\")\n            try fs.writeFileContents(pathUnderTest, bytes: testFileContent)\n\n            #expect(throws: FileSystemError.self) {\n                try fs.readFileContents(pathUnderTest.parentDirectory)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/FileSystem/PathShimTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport Testing\n\nstruct PathShimTests {\n    @Test\n    func rescursiveDirectoryCreation() {\n        try! withTemporaryDirectory(removeTreeOnDeinit: true) { path in\n            // Create a directory under several ancestor directories.\n            let dirPath = path.appending(components: \"abc\", \"def\", \"ghi\", \"mno\", \"pqr\")\n            try! makeDirectories(dirPath)\n\n            // Check that we were able to actually create the directory.\n            #expect(localFileSystem.isDirectory(dirPath))\n\n            // Check that there's no error if we try to create the directory again.\n            #expect(throws: Never.self) {\n                try! makeDirectories(dirPath)\n            }\n        }\n    }\n}\n\nstruct WalkTests {\n    @Test\n    func nonRecursive() throws {\n#if os(Android)\n        let root = \"/system\"\n        var expected: [AbsolutePath] = [\n            \"\\(root)/usr\",\n            \"\\(root)/bin\",\n            \"\\(root)/etc\",\n        ]\n        let expectedCount = 3\n#elseif os(Windows)\n        let root = ProcessInfo.processInfo.environment[\"SystemRoot\"]!\n        var expected: [AbsolutePath] = [\n            \"\\(root)/System32\",\n            \"\\(root)/SysWOW64\",\n        ]\n        let expectedCount = (root as NSString).pathComponents.count + 2\n#else\n        let root = \"\"\n        var expected: [AbsolutePath] = [\n            \"/usr\",\n            \"/bin\",\n            \"/sbin\",\n        ]\n        let expectedCount = 2\n#endif\n        for x in try walk(AbsolutePath(validating: \"\\(root)/\"), recursively: false) {\n            if let i = expected.firstIndex(of: x) {\n                expected.remove(at: i)\n            }\n            #expect(x.components.count == expectedCount, \"Actual is not as expected\")\n        }\n        #expect(expected.count == 0)\n    }\n\n    @Test\n    func recursive() {\n        let root = AbsolutePath(#file).parentDirectory.parentDirectory.parentDirectory.parentDirectory\n            .appending(component: \"Sources\")\n        var expected = [\n            root.appending(component: \"Basics\"),\n            root.appending(component: \"Build\"),\n            root.appending(component: \"Commands\"),\n        ]\n        for x in try! walk(root) {\n            if let i = expected.firstIndex(of: x) {\n                expected.remove(at: i)\n            }\n        }\n        #expect(expected == [])\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/FileSystem/PathTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Basics\nimport Foundation\nimport Testing\n\n#if os(Windows)\nprivate var windows: Bool { true }\n#else\nprivate var windows: Bool { false }\n#endif\n\n\n@Suite(\n    .tags(\n        .TestSize.small,\n        .Platform.FileSystem,\n    ),\n)\nstruct PathTests {\n    struct AbsolutePathTests {\n        private func pathStringIsSetCorrectlyTestImplementation(path: String, expected: String, label: String) {\n            let actual = AbsolutePath(path).pathString\n\n            #expect(actual == expected, \"\\(label): Actual is not as expected. Path is: \\(path)\")\n        }\n\n        @Test(\n            arguments: [\n                (path: \"/\", expected: (windows ? #\"\\\"# : \"/\"), label: \"Basics\"),\n                (path: \"/a\", expected: (windows ? #\"\\a\"# : \"/a\"), label: \"Basics\"),\n                (path: \"/a/b/c\", expected: (windows ? #\"\\a\\b\\c\"# : \"/a/b/c\"), label: \"Basics\"),\n            ]\n        )\n        func pathStringIsSetCorrectly(path: String, expected: String, label: String) {\n            pathStringIsSetCorrectlyTestImplementation(\n                path: path,\n                expected: expected,\n                label: label\n            )\n        }\n\n        @Test(\n            .IssueWindowsPathTestsFailures,\n            arguments: [\n                (path: \"/ab/cd/ef/\", expected: (windows ? #\"\\ab\\cd\\ef\"# : \"/ab/cd/ef\"), label: \"Trailing path seperator\"),\n                (path: \"/ab/cd/ef//\", expected: (windows ? #\"\\ab\\cd\\ef\"# : \"/ab/cd/ef\"), label: \"Trailing path seperator\"),\n                (path: \"/ab/cd/ef///\", expected: (windows ? #\"\\ab\\cd\\ef\"# : \"/ab/cd/ef\"), label: \"Trailing path seperator\"),\n                (path: \"/ab//cd//ef\", expected: (windows ? #\"\\ab\\cd\\ef\"# : \"/ab/cd/ef\"), label: \"repeated path seperators\"),\n                (path: \"/ab///cd//ef\", expected: (windows ? #\"\\ab\\cd\\ef\"# : \"/ab/cd/ef\"), label: \"repeated path seperators\"),\n                (path: \"/ab/././cd//ef\", expected: \"/ab/cd/ef\", label: \"dot path component\"),\n                (path: \"/ab/./cd//ef/.\", expected:  \"/ab/cd/ef\", label: \"dot path component\"),\n                (path: \"/..\", expected: (windows ? #\"\\\"# : \"/\"), label: \"dot dot path component\"),\n                (path: \"/../../../../..\", expected: (windows ? #\"\\\"# : \"/\"), label: \"dot dot path component\"),\n                (path: \"/abc/..\", expected: (windows ? #\"\\\"# : \"/\"), label: \"dot dot path component\"),\n                (path: \"/abc/../..\", expected: (windows ? #\"\\\"# : \"/\"), label: \"dot dot path component\"),\n                (path: \"/../abc\", expected: (windows ? #\"\\abc\"# : \"/abc\"), label: \"dot dot path component\"),\n                (path: \"/../abc/..\", expected: (windows ? #\"\\\"# : \"/\"), label: \"dot dot path component\"),\n                (path: \"/../abc/../def\", expected: (windows ? #\"\\def\"# : \"/def\"), label: \"dot dot path component\"),\n                (path: \"///\", expected: (windows ? #\"\\\"# : \"/\"), label: \"combinations and edge cases\"),\n                (path: \"/./\", expected: (windows ? #\"\\\"# : \"/\"), label: \"combinations and edge cases\"),\n            ]\n        )\n        func pathStringIsSetCorrectlySkipOnWindows(path: String, expected: String, label: String) {\n            withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not properly\", isIntermittent: true) {\n                pathStringIsSetCorrectlyTestImplementation(\n                    path: path,\n                    expected: expected,\n                    label: label\n                )\n            } when :{\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        @Test\n        func stringInitialization() throws {\n            let abs1 = AbsolutePath(\"/\")\n            let abs2 = AbsolutePath(abs1, \".\")\n            #expect(abs1 == abs2)\n            let rel3 = \".\"\n            let abs3 = try AbsolutePath(abs2, validating: rel3)\n            #expect(abs2 == abs3)\n            let base = AbsolutePath(\"/base/path\")\n            let abs4 = AbsolutePath(\"/a/b/c\", relativeTo: base)\n            #expect(abs4 == AbsolutePath(\"/a/b/c\"))\n            let abs5 = AbsolutePath(\"./a/b/c\", relativeTo: base)\n            #expect(abs5 == AbsolutePath(\"/base/path/a/b/c\"))\n            let abs6 = AbsolutePath(\"~/bla\", relativeTo: base)  // `~` isn't special\n            #expect(abs6 == AbsolutePath(\"/base/path/~/bla\"))\n        }\n\n        struct AbsolutePathDirectoryNameAtributeReturnsExpectedValue {\n            private func testImplementation(path: String, expected: String) throws {\n                let actual = AbsolutePath(path).dirname\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"/\", expected: (windows ? #\"\\\"# : \"/\")),\n                    (path: \"/a\", expected: (windows ? #\"\\\"# : \"/\")),\n                    (path: \"/ab/c//d/\", expected: (windows ? #\"\\ab\\c\"# : \"/ab/c\")),\n                ]\n            )\n            func absolutePathDirectoryNameAttributeAllPlatforms(path: String, expected: String) throws {\n                try testImplementation(path: path, expected: expected)\n            }\n\n            @Test(\n                .IssueWindowsPathTestsFailures,\n                arguments: [\n                    (path: \"/./a\", expected: (windows ? #\"\\\"# : \"/\")),\n                    (path: \"/../..\", expected: (windows ? #\"\\\"# : \"/\")),\n                ]\n            )\n            func absolutePathDirectoryNameAttributeFailsOnWindows(path: String, expected: String) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not properly\") {\n                    try testImplementation(path: path, expected: expected)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n        }\n\n        struct AbsolutePathBaseNameAttributeReturnsExpectedValue {\n            private func testImplementation(path: String, expected: String) throws {\n                let actual = AbsolutePath(path).basename\n\n                #expect(actual == expected, \"Actual is not as expected: \\(path)\")\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"/\", expected: (windows ? #\"\\\"# : \"/\")),\n                    (path: \"/a\", expected: \"a\"),\n                    (path: \"/./a\", expected: \"a\"),\n                ]\n            )\n            func absolutePathBaseNameExtractionAllPlatforms(path: String, expected: String) throws {\n                try testImplementation(path: path, expected: expected)\n            }\n\n            @Test(\n                .IssueWindowsPathTestsFailures,\n                arguments: [\n                    (path: \"/../..\", expected: \"/\"),\n                ]\n            )\n            func absolutePathBaseNameExtractionFailsOnWindows(path: String, expected: String) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not properly\") {\n                    try testImplementation(path: path, expected: expected)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n        }\n\n        struct AbsolutePathBasenameWithoutExtAttributeReturnsExpectedValue {\n            private func testImplementation(path: String, expected: String) throws {\n                let actual = AbsolutePath(path).basenameWithoutExt\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"/\", expected:  (windows ? #\"\\\"# : \"/\")),\n                    (path: \"/a\", expected:  \"a\"),\n                    (path: \"/./a\", expected:  \"a\"),\n                    (path: \"/a.txt\", expected:  \"a\"),\n                    (path: \"/./a.txt\", expected:  \"a\"),\n                ]\n            )\n            func absolutePathBaseNameWithoutExt(path: String, expected: String) throws {\n                try testImplementation(path: path, expected: expected)\n            }\n\n            @Test(\n                .IssueWindowsPathTestsFailures,\n                arguments: [\n                    (path: \"/../..\", expected:  \"/\"),\n                ]\n            )\n            func absolutePathBaseNameWithoutExtFailedOnWindows(path: String, expected: String) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not handled properly\") {\n                    try testImplementation(path: path, expected: expected)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n        }\n\n        struct AbsolutePathParentDirectoryAttributeReturnsExpectedValue {\n            private func testImplementation(path: String, numParentDirectoryCalls: Int, expected: String) throws {\n                let pathUnderTest = AbsolutePath(path)\n                let expectedPath = AbsolutePath(expected)\n                try #require(numParentDirectoryCalls >= 1, \"Test configuration Error.\")\n\n                var actual = pathUnderTest\n                for _ in 0 ..< numParentDirectoryCalls {\n                    actual = actual.parentDirectory\n                }\n                #expect(actual == expectedPath)\n            }\n            @Test(\n                .IssueWindowsPathTestsFailures,\n                arguments: [\n                    (path: \"/\", numParentDirectoryCalls: 1, expected: \"/\"),\n                    (path: \"/\", numParentDirectoryCalls: 2, expected: \"/\"),\n                    (path: \"/bar\", numParentDirectoryCalls: 1, expected: \"/\"),\n                ]\n            )\n            func absolutePathParentDirectoryAttributeReturnsAsExpected(path: String, numParentDirectoryCalls: Int, expected: String) throws {\n                try testImplementation(path: path, numParentDirectoryCalls: numParentDirectoryCalls, expected: expected)\n            }\n\n            @Test(\n                .IssueWindowsPathTestsFailures,\n                arguments: [\n                    (path: \"/bar/../foo/..//\", numParentDirectoryCalls: 2, expected: \"/\"),\n                    (path: \"/bar/../foo/..//yabba/a/b\", numParentDirectoryCalls: 2, expected: \"/yabba\")\n                ]\n            )\n            func absolutePathParentDirectoryAttributeReturnsAsExpectedFailsOnWindows(path: String, numParentDirectoryCalls: Int, expected: String) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not handled properly\") {\n                    try testImplementation(path: path, numParentDirectoryCalls: numParentDirectoryCalls, expected: expected)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n\n        }\n\n        @Test(\n            .IssueWindowsPathTestsFailures,\n            arguments: [\n                (path: \"/\", expected: [\"/\"]),\n                (path: \"/.\", expected: [\"/\"]),\n                (path: \"/..\", expected: [\"/\"]),\n                (path: \"/bar\", expected: [\"/\", \"bar\"]),\n                (path: \"/foo/bar/..\", expected: [\"/\", \"foo\"]),\n                (path: \"/bar/../foo\", expected: [\"/\", \"foo\"]),\n                (path: \"/bar/../foo/..//\", expected: [\"/\"]),\n                (path: \"/bar/../foo/..//yabba/a/b/\", expected: [\"/\", \"yabba\", \"a\", \"b\"]),\n            ]\n        )\n        func componentsAttributeReturnsExpectedValue(path: String, expected: [String]) throws {\n            withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not handled properly\") {\n                let actual = AbsolutePath(path).components\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        struct AncestryTest {\n            @Test(\n                arguments: [\n                    (path: \"/a/b/c/d/e/f\", descendentOfOrEqualTo: \"/a/b/c/d\", expected: true),\n                    (path: \"/a/b/c/d/e/f.swift\", descendentOfOrEqualTo: \"/a/b/c\", expected: true),\n                    (path: \"/\", descendentOfOrEqualTo: \"/\", expected: true),\n                    (path: \"/foo/bar\", descendentOfOrEqualTo: \"/\", expected: true),\n                    (path: \"/foo/bar\", descendentOfOrEqualTo: \"/foo/bar/baz\", expected: false),\n                    (path: \"/foo/bar\", descendentOfOrEqualTo: \"/bar\", expected: false)\n                ]\n            )\n            func isDescendantOfOrEqual(path: String, descendentOfOrEqualTo: String, expected: Bool) {\n                let actual = AbsolutePath(path).isDescendantOfOrEqual(to: AbsolutePath(descendentOfOrEqualTo))\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"/foo/bar\", descendentOf: \"/foo/bar\", expected: false),\n                    (path: \"/foo/bar\", descendentOf: \"/foo\", expected: true)\n                ]\n            )\n            func isDescendant(path: String, ancesterOf: String, expected: Bool) {\n                let actual = AbsolutePath(path).isDescendant(of: AbsolutePath(ancesterOf))\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"/a/b/c/d\", ancestorOfOrEqualTo: \"/a/b/c/d/e/f\", expected: true),\n                    (path: \"/a/b/c\", ancestorOfOrEqualTo: \"/a/b/c/d/e/f.swift\", expected: true),\n                    (path: \"/\", ancestorOfOrEqualTo: \"/\", expected: true),\n                    (path: \"/\", ancestorOfOrEqualTo: \"/foo/bar\", expected: true),\n                    (path: \"/foo/bar/baz\", ancestorOfOrEqualTo: \"/foo/bar\", expected: false),\n                    (path: \"/bar\", ancestorOfOrEqualTo: \"/foo/bar\", expected: false),\n                ]\n            )\n            func isAncestorOfOrEqual(path: String, ancestorOfOrEqualTo: String, expected: Bool) {\n                let actual = AbsolutePath(path).isAncestorOfOrEqual(to: AbsolutePath(ancestorOfOrEqualTo))\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"/foo/bar\", ancesterOf: \"/foo/bar\", expected: false),\n                    (path: \"/foo\", ancesterOf: \"/foo/bar\", expected: true),\n                ]\n            )\n            func isAncestor(path: String, ancesterOf: String, expected: Bool) {\n                let actual = AbsolutePath(path).isAncestor(of: AbsolutePath(ancesterOf))\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            }\n        }\n\n        @Test\n        func absolutePathValidation() throws {\n            #expect(throws: Never.self) {\n                try AbsolutePath(validating: \"/a/b/c/d\")\n            }\n\n            withKnownIssue {\n                #expect {try AbsolutePath(validating: \"~/a/b/d\")} throws: { error in\n                    (\"\\(error)\" == \"invalid absolute path '~/a/b/d'; absolute path must begin with '/'\")\n                }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n\n            #expect {try AbsolutePath(validating: \"a/b/d\") } throws: { error in\n                (\"\\(error)\" == \"invalid absolute path 'a/b/d'\")\n            }\n        }\n\n        @Test\n        func comparison() {\n            #expect(AbsolutePath(\"/\") <= AbsolutePath(\"/\"));\n            #expect(AbsolutePath(\"/abc\") < AbsolutePath(\"/def\"));\n            #expect(AbsolutePath(\"/2\") <= AbsolutePath(\"/2.1\"));\n            #expect(AbsolutePath(\"/3.1\") > AbsolutePath(\"/2\"));\n            #expect(AbsolutePath(\"/2\") >= AbsolutePath(\"/2\"));\n            #expect(AbsolutePath(\"/2.1\") >= AbsolutePath(\"/2\"));\n        }\n\n    }\n    struct RelativePathTests {\n        private func pathStringIsSetCorrectlyTestImplementation(path: String, expected: String, label: String) {\n            let actual = RelativePath(path).pathString\n\n            #expect(actual == expected, \"\\(label): Actual is not as expected. Path is: \\(path)\")\n        }\n\n        @Test(\n            arguments: [\n                (path: \".\", expected: \".\", label: \"Basics\"),\n                (path: \"a\", expected: \"a\", label: \"Basics\"),\n                (path: \"a/b/c\", expected: (windows ? #\"a\\b\\c\"# : \"a/b/c\"), label: \"Basics\"),\n                (path: \"~\", expected: \"~\", label: \"Basics\"),\n                (path: \"..\", expected: \"..\", label: \"dot dot path component\"),\n                (path: \"\", expected:  \".\", label: \"combinations and edge cases\"),\n                (path: \".\", expected:  \".\", label: \"combinations and edge cases\"),\n                (path: \"../a\", expected:  (windows ? #\"..\\a\"# : \"../a\"), label: \"combinations and edge cases\"),\n            ]\n        )\n        func pathStringIsSetCorrectly(path: String, expected: String, label: String) {\n            pathStringIsSetCorrectlyTestImplementation(\n                path: path,\n                expected: expected,\n                label: label\n            )\n        }\n\n        @Test(\n            .IssueWindowsPathTestsFailures,\n            arguments: [\n                (path: \"ab//cd//ef\", expected: (windows ? #\"ab\\cd\\ef\"# : \"ab/cd/ef\"), label: \"repeated path seperators\"),\n                (path: \"ab//cd///ef\", expected: (windows ? #\"ab\\cd\\ef\"# : \"ab/cd/ef\"), label: \"repeated path seperators\"),\n\n                (path: \"ab/cd/ef/\", expected: (windows ? #\"ab\\cd\\ef\"# : \"ab/cd/ef\"), label: \"Trailing path seperator\"),\n                (path: \"ab/cd/ef//\", expected: (windows ? #\"ab\\cd\\ef\"# : \"ab/cd/ef\"), label: \"Trailing path seperator\"),\n                (path: \"ab/cd/ef///\", expected: (windows ? #\"ab\\cd\\ef\"# : \"ab/cd/ef\"), label: \"Trailing path seperator\"),\n\n                (path: \"ab/./cd/././ef\", expected: \"ab/cd/ef\", label: \"dot path component\"),\n                (path: \"ab/./cd/ef/.\", expected: \"ab/cd/ef\", label: \"dot path component\"),\n\n                (path: \"../..\", expected: \"../..\", label: \"dot dot path component\"),\n                (path: \".././..\", expected: \"../..\", label: \"dot dot path component\"),\n                (path: \"../abc/..\", expected: \"..\", label: \"dot dot path component\"),\n                (path: \"../abc/.././\", expected: \"..\", label: \"dot dot path component\"),\n                (path: \"abc/..\", expected: \".\", label: \"dot dot path component\"),\n\n                (path: \"../\", expected:  \"..\", label: \"combinations and edge cases\"),\n                (path: \"./abc\", expected:  \"abc\", label: \"combinations and edge cases\"),\n                (path: \"./abc/\", expected:  \"abc\", label: \"combinations and edge cases\"),\n                (path: \"./abc/../bar\", expected:  \"bar\", label: \"combinations and edge cases\"),\n                (path: \"foo/../bar\", expected:  \"bar\", label: \"combinations and edge cases\"),\n                (path: \"foo///..///bar///baz\", expected:  \"bar/baz\", label: \"combinations and edge cases\"),\n                (path: \"foo/../bar/./\", expected:  \"bar\", label: \"combinations and edge cases\"),\n                (path: \"../abc/def/\", expected:  \"../abc/def\", label: \"combinations and edge cases\"),\n                (path: \"././././.\", expected:  \".\", label: \"combinations and edge cases\"),\n                (path: \"./././../.\", expected:  \"..\", label: \"combinations and edge cases\"),\n                (path: \"./\", expected:  \".\", label: \"combinations and edge cases\"),\n                (path: \".//\", expected:  \".\", label: \"combinations and edge cases\"),\n                (path: \"./.\", expected:  \".\", label: \"combinations and edge cases\"),\n                (path: \"././\", expected:  \".\", label: \"combinations and edge cases\"),\n                (path: \"../.\", expected:  \"..\", label: \"combinations and edge cases\"),\n                (path: \"./..\", expected:  \"..\", label: \"combinations and edge cases\"),\n                (path: \"./../.\", expected:  \"..\", label: \"combinations and edge cases\"),\n                (path: \"./////../////./////\", expected:  \"..\", label: \"combinations and edge cases\"),\n                (path: \"../a/..\", expected:  \"..\", label: \"combinations and edge cases\"),\n                (path: \"a/..\", expected:  \".\", label: \"combinations and edge cases\"),\n                (path: \"a/../////../////./////\", expected:  \"..\", label: \"combinations and edge cases\"),\n\n            ]\n        )\n        func pathStringIsSetCorrectlyFailsOnWindows(path: String, expected: String, label: String) {\n            withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) does not resolve properly\", isIntermittent: true) {\n                    pathStringIsSetCorrectlyTestImplementation(\n                    path: path,\n                    expected: expected,\n                    label: label\n                )\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        struct relateivePathDirectoryNameAttributeReturnsExpectedValue {\n            private func testImplementation(path: String, expected: String) throws {\n                let actual = RelativePath(path).dirname\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"ab/c//d/\", expected: (windows ? #\"ab\\c\"# : \"ab/c\")),\n                    (path: \"../a\", expected: \"..\"),\n                    (path: \"./..\", expected: \".\"),\n                ]\n            )\n            func relativePathDirectoryNameExtraction(path: String, expected: String) throws {\n                try testImplementation(path: path, expected: expected)\n            }\n\n            @Test(\n             .IssueWindowsPathTestsFailures,\n               arguments: [\n                    (path: \"../a/..\", expected: \".\"),\n                    (path: \"a/..\", expected: \".\"),\n                    (path: \"a/../////../////./////\", expected: \".\"),\n                    (path: \"abc\", expected: \".\"),\n                    (path: \"\", expected: \".\"),\n                    (path: \".\", expected: \".\"),\n                ]\n            )\n            func relativePathDirectoryNameExtractionFailsOnWindows(path: String, expected: String) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not handled properly\") {\n                    try testImplementation(path: path, expected: expected)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n\n        }\n\n        struct relativePathBaseNameAttributeReturnsExpectedValue {\n            private func testImplementation(path: String, expected: String) throws {\n                let actual = RelativePath(path).basename\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            }\n            @Test(\n                arguments: [\n                    (path: \"../..\", expected:  \"..\"),\n                    (path: \"../a\", expected:  \"a\"),\n                    (path: \"../a/..\", expected:  \"..\"),\n                    (path: \"./..\", expected:  \"..\"),\n                    (path: \"abc\", expected:  \"abc\"),\n                    (path: \"\", expected:  \".\"),\n                    (path: \".\", expected:  \".\"),\n                ]\n            )\n            func relativePathBaseNameExtraction(path: String, expected: String) throws {\n                try testImplementation(path: path, expected: expected)\n            }\n\n            @Test(\n                .IssueWindowsPathTestsFailures,\n                arguments: [\n                    (path: \"a/..\", expected:  \".\"),\n                    (path: \"a/../////../////./////\", expected:  \"..\"),\n                ]\n            )\n            func relativePathBaseNameExtractionFailsOnWindows(path: String, expected: String) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not handled properly\") {\n                    try testImplementation(path: path, expected: expected)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n\n        }\n\n        struct RelativePathBasenameWithoutExtAttributeReturnsExpectedValue {\n            private func testImplementation(path: String, expected: String) throws {\n                let actual: String = RelativePath(path).basenameWithoutExt\n\n                #expect(actual == expected, \"Actual is not as expected. Path is: \\(path)\")\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"../a\", expected:  \"a\"),\n                    (path: \"a/..\", expected:  \".\"),\n                    (path: \"abc\", expected:  \"abc\"),\n                    (path: \"../a.bc\", expected:  \"a\"),\n                    (path: \"abc.swift\", expected:  \"abc\"),\n                    (path: \"../a.b.c\", expected:  \"a.b\"),\n                    (path: \"abc.xyz.123\", expected:  \"abc.xyz\"),\n                ]\n            )\n            func relativePathBaseNameWithoutExt(path: String, expected: String) throws {\n                try testImplementation(path: path, expected: expected)\n            }\n\n            @Test(\n            .IssueWindowsPathTestsFailures,\n                arguments: [\n                    (path: \"../..\", expected:  \"..\"),\n                    (path: \"../a/..\", expected:  \"..\"),\n                    (path: \"./..\", expected:  \"..\"),\n                    (path: \"a/../////../////./////\", expected:  \"..\"),\n                    (path: \"\", expected:  \".\"),\n                    (path: \".\", expected:  \".\"),\n                ]\n            )\n            func relativePathBaseNameWithoutExtFailsOnWindows(path: String, expected: String) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not properly\") {\n                    try testImplementation(path: path, expected: expected)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n\n        }\n\n        struct relativePathSuffixAndExtensionAttributeReturnsExpectedValue {\n            private func testImplementation(path: String, expectedSuffix: String?, expectedExtension: String?) throws {\n                let pathUnderTest = RelativePath(path)\n\n                #expect(pathUnderTest.suffix == expectedSuffix, \"Actual suffix is not as expected.  Path is: \\(path)\")\n                #expect(pathUnderTest.extension == expectedExtension, \"Actual extension is not as expected.  Path is: \\(path)\")\n            }\n            @Test(\n                arguments: [\n                    (path: \"a\", expectedSuffix: nil, expectedExtension: nil),\n                    (path: \"a.foo\", expectedSuffix: \".foo\", expectedExtension: \"foo\"),\n                    (path: \".a.foo\", expectedSuffix: \".foo\", expectedExtension: \"foo\"),\n                    (path: \"a.foo.bar\", expectedSuffix: \".bar\", expectedExtension: \"bar\"),\n                    (path: \".a.foo.bar\", expectedSuffix: \".bar\", expectedExtension: \"bar\"),\n                    (path: \".a.foo.bar.baz\", expectedSuffix: \".baz\", expectedExtension: \"baz\"),\n                ]\n            )\n            func suffixExtraction(path: String, expectedSuffix: String?, expectedExtension: String?) throws {\n                try testImplementation(path: path, expectedSuffix: expectedSuffix, expectedExtension: expectedExtension)\n            }\n\n            @Test(\n             .IssueWindowsPathTestsFailures,\n               arguments:[\n                    \"a.\",\n                    \".a\",\n                    \"\",\n                    \".\",\n                    \"..\",\n                ]\n            )\n            func suffixExtractionFailsOnWindows(path: String) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not handled properly\") {\n                    try testImplementation(path: path, expectedSuffix: nil, expectedExtension: nil)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n\n        }\n\n        struct componentsAttributeReturnsExpectedValue {\n            private func testImplementation(path: String, expected: [String]) throws {\n                let actual = RelativePath(path).components\n\n                #expect(actual == expected, \"Actual is not as expected: \\(path)\")\n            }\n\n            @Test(\n                arguments: [\n                    (path: \"\", expected: [\".\"]),\n                    (path: \".\", expected: [\".\"]),\n                    (path: \"..\", expected: [\"..\"]),\n                    (path: \"bar\", expected: [\"bar\"]),\n                    (path: \"../..\", expected: [\"..\", \"..\"]),\n                    (path: \"../a\", expected: [\"..\", \"a\"]),\n                    (path: \"abc\", expected: [\"abc\"]),\n                ] as [(String, [String])]\n            )\n            func relativePathComponentsAttributeAllPlatform(path: String, expected: [String]) throws {\n                try testImplementation(path: path, expected: expected)\n            }\n\n            @Test(\n            .IssueWindowsPathTestsFailures,\n                arguments: [\n                    (path: \"foo/bar/..\", expected: [\"foo\"]),\n                    (path: \"bar/../foo\", expected: [\"foo\"]),\n                    (path: \"bar/../foo/..//\", expected: [\".\"]),\n                    (path: \"bar/../foo/..//yabba/a/b/\", expected: [\"yabba\", \"a\", \"b\"]),\n                    (path: \".././/..\", expected: [\"..\", \"..\"]),\n                    (path: \"../a/..\", expected: [\"..\"]),\n                    (path: \"a/..\", expected: [\".\"]),\n                    (path: \"./..\", expected: [\"..\"]),\n                    (path: \"a/../////../////./////\", expected: [\"..\"]),\n                ] as [(String, [String])]\n            )\n            func relativePathComponentsAttributeFailsOnWindows(path: String, expected: [String]) throws {\n                try withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: Path \\(path) is not properly\") {\n                    try testImplementation(path: path, expected: expected)\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n        }\n\n        @Test(\n            .IssueWindowsPathTestsFailures,\n        )\n        func relativePathValidation() throws {\n            #expect(throws: Never.self) {\n                try RelativePath(validating: \"a/b/c/d\")\n            }\n\n            withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8511: \\\\\") {\n                #expect {try RelativePath(validating: \"/a/b/d\")} throws: { error in\n                    (\"\\(error)\" == \"invalid relative path '/a/b/d'; relative path should not begin with '/'\")\n                }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n    }\n\n    @Test\n    @available(*, deprecated)\n    func concatenation() throws {\n        #expect(AbsolutePath(AbsolutePath(\"/\"), RelativePath(\"\")).pathString == (windows ? #\"\\\"# : \"/\"))\n        #expect(AbsolutePath(AbsolutePath(\"/\"), RelativePath(\".\")).pathString == (windows ? #\"\\\"# : \"/\"))\n        #expect(AbsolutePath(AbsolutePath(\"/\"), RelativePath(\"..\")).pathString == (windows ? #\"\\\"# : \"/\"))\n        #expect(AbsolutePath(AbsolutePath(\"/\"), RelativePath(\"bar\")).pathString == (windows ? #\"\\bar\"# : \"/bar\"))\n        #expect(AbsolutePath(AbsolutePath(\"/foo/bar\"), RelativePath(\"..\")).pathString == (windows ? #\"\\foo\"# : \"/foo\"))\n        #expect(AbsolutePath(AbsolutePath(\"/bar\"), RelativePath(\"../foo\")).pathString == (windows ? #\"\\foo\"# : \"/foo\"))\n        withKnownIssue {\n            #expect(AbsolutePath(AbsolutePath(\"/bar\"), RelativePath(\"../foo/..//\")).pathString == (windows ? #\"\\\"# : \"/\"))\n            #expect(AbsolutePath(AbsolutePath(\"/bar/../foo/..//yabba/\"), RelativePath(\"a/b\")).pathString == (windows ? #\"\\yabba\\a\\b\"# : \"/yabba/a/b\"))\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n\n        #expect(AbsolutePath(\"/\").appending(RelativePath(\"\")).pathString == (windows ? #\"\\\"# : \"/\"))\n        #expect(AbsolutePath(\"/\").appending(RelativePath(\".\")).pathString == (windows ? #\"\\\"# : \"/\"))\n        #expect(AbsolutePath(\"/\").appending(RelativePath(\"..\")).pathString == (windows ? #\"\\\"# : \"/\"))\n        #expect(AbsolutePath(\"/\").appending(RelativePath(\"bar\")).pathString == (windows ? #\"\\bar\"# : \"/bar\"))\n        #expect(AbsolutePath(\"/foo/bar\").appending(RelativePath(\"..\")).pathString == (windows ? #\"\\foo\"# : \"/foo\"))\n        #expect(AbsolutePath(\"/bar\").appending(RelativePath(\"../foo\")).pathString == (windows ? #\"\\foo\"# : \"/foo\"))\n        withKnownIssue {\n            #expect(AbsolutePath(\"/bar\").appending(RelativePath(\"../foo/..//\")).pathString == (windows ? #\"\\\"# : \"/\"))\n            #expect(AbsolutePath(\"/bar/../foo/..//yabba/\").appending(RelativePath(\"a/b\")).pathString == (windows ? #\"\\yabba\\a\\b\"# : \"/yabba/a/b\"))\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n\n        #expect(AbsolutePath(\"/\").appending(component: \"a\").pathString == (windows ? #\"\\a\"# : \"/a\"))\n        #expect(AbsolutePath(\"/a\").appending(component: \"b\").pathString == (windows ? #\"\\a\\b\"# : \"/a/b\"))\n        #expect(AbsolutePath(\"/\").appending(components: \"a\", \"b\").pathString == (windows ? #\"\\a\\b\"# : \"/a/b\"))\n        #expect(AbsolutePath(\"/a\").appending(components: \"b\", \"c\").pathString == (windows ? #\"\\a\\b\\c\"# : \"/a/b/c\"))\n\n        #expect(AbsolutePath(\"/a/b/c\").appending(components: \"\", \"c\").pathString == (windows ? #\"\\a\\b\\c\\c\"# : \"/a/b/c/c\"))\n        #expect(AbsolutePath(\"/a/b/c\").appending(components: \"\").pathString == (windows ? #\"\\a\\b\\c\"# : \"/a/b/c\"))\n        #expect(AbsolutePath(\"/a/b/c\").appending(components: \".\").pathString == (windows ? #\"\\a\\b\\c\"# : \"/a/b/c\"))\n        #expect(AbsolutePath(\"/a/b/c\").appending(components: \"..\").pathString == (windows ? #\"\\a\\b\"# : \"/a/b\"))\n        #expect(AbsolutePath(\"/a/b/c\").appending(components: \"..\", \"d\").pathString == (windows ? #\"\\a\\b\\d\"# : \"/a/b/d\"))\n        #expect(AbsolutePath(\"/\").appending(components: \"..\").pathString == (windows ? #\"\\\"# : \"/\"))\n        #expect(AbsolutePath(\"/\").appending(components: \".\").pathString == (windows ? #\"\\\"# : \"/\"))\n        #expect(AbsolutePath(\"/\").appending(components: \"..\", \"a\").pathString == (windows ? #\"\\a\"# : \"/a\"))\n\n        #expect(RelativePath(\"hello\").appending(components: \"a\", \"b\", \"c\", \"..\").pathString == (windows ? #\"hello\\a\\b\"# : \"hello/a/b\"))\n        #expect(RelativePath(\"hello\").appending(RelativePath(\"a/b/../c/d\")).pathString == (windows ? #\"hello\\a\\c\\d\"# : \"hello/a/c/d\"))\n    }\n\n    @Test\n    func relativePathFromAbsolutePaths() throws {\n        #expect(AbsolutePath(\"/\").relative(to: AbsolutePath(\"/\")) == RelativePath(\".\"));\n        #expect(AbsolutePath(\"/a/b/c/d\").relative(to: AbsolutePath(\"/\")) == RelativePath(\"a/b/c/d\"));\n        #expect(AbsolutePath(\"/\").relative(to: AbsolutePath(\"/a/b/c\")) == RelativePath(\"../../..\"));\n        #expect(AbsolutePath(\"/a/b/c/d\").relative(to: AbsolutePath(\"/a/b\")) == RelativePath(\"c/d\"));\n        #expect(AbsolutePath(\"/a/b/c/d\").relative(to: AbsolutePath(\"/a/b/c\")) == RelativePath(\"d\"));\n        #expect(AbsolutePath(\"/a/b/c/d\").relative(to: AbsolutePath(\"/a/c/d\")) == RelativePath(\"../../b/c/d\"));\n        #if !os(Windows)\n        #expect(AbsolutePath(\"/a/b/c/d\").relative(to: AbsolutePath(\"/b/c/d\")) == RelativePath(\"../../../a/b/c/d\"));\n        #endif\n    }\n\n    @Test\n    func codable() throws {\n        struct Foo: Codable, Equatable {\n            var path: AbsolutePath\n        }\n\n        struct Bar: Codable, Equatable {\n            var path: RelativePath\n        }\n\n        struct Baz: Codable, Equatable {\n            var path: String\n        }\n\n        do {\n            let foo = Foo(path: \"/path/to/foo\")\n            let data = try JSONEncoder().encode(foo)\n            let decodedFoo = try JSONDecoder().decode(Foo.self, from: data)\n            #expect(foo == decodedFoo)\n        }\n\n        do {\n            let foo = Foo(path: \"/path/to/../to/foo\")\n            let data = try JSONEncoder().encode(foo)\n            let decodedFoo = try JSONDecoder().decode(Foo.self, from: data)\n            #expect(foo == decodedFoo)\n            withKnownIssue {\n                #expect(foo.path.pathString == (windows ? #\"\\path\\to\\foo\"# : \"/path/to/foo\"))\n                #expect(decodedFoo.path.pathString == (windows ? #\"\\path\\to\\foo\"# : \"/path/to/foo\"))\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        do {\n            let bar = Bar(path: \"path/to/bar\")\n            let data = try JSONEncoder().encode(bar)\n            let decodedBar = try JSONDecoder().decode(Bar.self, from: data)\n            #expect(bar == decodedBar)\n        }\n\n        do {\n            let bar = Bar(path: \"path/to/../to/bar\")\n            let data = try JSONEncoder().encode(bar)\n            let decodedBar = try JSONDecoder().decode(Bar.self, from: data)\n            #expect(bar == decodedBar)\n            withKnownIssue {\n                #expect(bar.path.pathString == \"path/to/bar\")\n                #expect(decodedBar.path.pathString == \"path/to/bar\")\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        do {\n            let data = try JSONEncoder().encode(Baz(path: \"\"))\n            #expect(throws: (any Error).self) {\n                try JSONDecoder().decode(Foo.self, from: data)\n            }\n            #expect(throws: Never.self) {\n                try JSONDecoder().decode(Bar.self, from: data)\n            } // empty string is a valid relative path\n        }\n\n        do {\n            let data = try JSONEncoder().encode(Baz(path: \"foo\"))\n            #expect(throws: (any Error).self) {\n                try JSONDecoder().decode(Foo.self, from: data)\n            }\n        }\n\n        do {\n            let data = try JSONEncoder().encode(Baz(path: \"/foo\"))\n            #expect(throws: (any Error).self) {\n                try JSONDecoder().decode(Bar.self, from: data)\n            }\n        }\n    }\n\n    // FIXME: We also need tests for join() operations.\n\n    // FIXME: We also need tests for dirname, basename, suffix, etc.\n\n    // FIXME: We also need test for stat() operations.\n}\n"
  },
  {
    "path": "Tests/BasicsTests/FileSystem/TemporaryFileTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Testing\n\nimport Basics\n\nstruct TemporaryAsyncFileTests {\n    @Test\n    func basicTemporaryDirectory() async throws {\n        let path1: AbsolutePath = try await withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in\n            // Do some async task\n            try await Task.sleep(nanoseconds: 1_000)\n\n            #expect(localFileSystem.isDirectory(tempDirPath))\n            return tempDirPath\n        }.value\n        #expect(!localFileSystem.isDirectory(path1))\n\n        // Test temp directory is not removed when its not empty.\n        let path2: AbsolutePath = try await withTemporaryDirectory { tempDirPath in\n            #expect(localFileSystem.isDirectory(tempDirPath))\n            // Create a file inside the temp directory.\n            let filePath = tempDirPath.appending(\"somefile\")\n            // Do some async task\n            try await Task.sleep(nanoseconds: 1_000)\n\n            try localFileSystem.writeFileContents(filePath, bytes: [])\n            return tempDirPath\n        }.value\n        #expect(localFileSystem.isDirectory(path2))\n        // Cleanup.\n        try localFileSystem.removeFileTree(path2)\n        #expect(!localFileSystem.isDirectory(path2))\n\n        // Test temp directory is removed when its not empty and removeTreeOnDeinit is enabled.\n        let path3: AbsolutePath = try await withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in\n            #expect(localFileSystem.isDirectory(tempDirPath))\n            let filePath = tempDirPath.appending(\"somefile\")\n            // Do some async task\n            try await Task.sleep(nanoseconds: 1_000)\n\n            try localFileSystem.writeFileContents(filePath, bytes: [])\n            return tempDirPath\n        }.value\n        #expect(!localFileSystem.isDirectory(path3))\n    }\n\n    @Test\n    func canCreateUniqueTempDirectories() async throws {\n        let (pathOne, pathTwo): (AbsolutePath, AbsolutePath) = try await withTemporaryDirectory(removeTreeOnDeinit: true) { pathOne in\n            let pathTwo: AbsolutePath = try await withTemporaryDirectory(removeTreeOnDeinit: true) { pathTwo in\n                // Do some async task\n                try await Task.sleep(nanoseconds: 1_000)\n\n                #expect(localFileSystem.isDirectory(pathOne))\n                #expect(localFileSystem.isDirectory(pathTwo))\n                // Their paths should be different.\n                #expect(pathOne != pathTwo)\n                return pathTwo\n            }.value\n            return (pathOne, pathTwo)\n        }.value\n        #expect(!localFileSystem.isDirectory(pathOne))\n        #expect(!localFileSystem.isDirectory(pathTwo))\n    }\n\n    @Test\n    func cancelOfTask() async throws {\n        let task: Task<AbsolutePath, Error> = try withTemporaryDirectory { path in\n\n            try await Task.sleep(nanoseconds: 1_000_000_000)\n            #expect(Task.isCancelled)\n            #expect(!localFileSystem.isDirectory(path))\n            return path\n        }\n        task.cancel()\n        await #expect(throws: (any Error).self, \"Error did not error when accessing `task.value`\") {\n            try await task.value\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/FileSystem/VFSTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport func TSCBasic.withTemporaryFile\nimport Testing\n\nimport struct TSCBasic.ByteString\n\nfunc testWithTemporaryDirectory(\n    function: StaticString = #function,\n    body: @escaping (AbsolutePath) async throws -> Void\n) async throws {\n    let cleanedFunction = function.description\n        .replacingOccurrences(of: \"(\", with: \"\")\n        .replacingOccurrences(of: \")\", with: \"\")\n        .replacingOccurrences(of: \".\", with: \"\")\n    try await withTemporaryDirectory(prefix: \"spm-tests-\\(cleanedFunction)\") { tmpDirPath in\n        defer {\n            // Unblock and remove the tmp dir on deinit.\n            try? localFileSystem.chmod(.userWritable, path: tmpDirPath, options: [.recursive])\n            try? localFileSystem.removeFileTree(tmpDirPath)\n        }\n        try await  body(tmpDirPath)\n    }.value\n}\n\n\nstruct VFSTests {\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9310\", relationship: .defect),\n        .skipHostOS(.windows, \"Test currently fails with: you don't have permissions.\"),\n        .tags(\n            .TestSize.medium,\n            .Platform.FileSystem,\n            .UserWorkflow,\n        )\n    )\n    func localBasics() throws {\n        // tiny PE binary from: https://archive.is/w01DO\n        let contents: [UInt8] = [\n            0x4d, 0x5a, 0x00, 0x00, 0x50, 0x45, 0x00, 0x00, 0x4c, 0x01, 0x01, 0x00,\n            0x6a, 0x2a, 0x58, 0xc3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x04, 0x00, 0x03, 0x01, 0x0b, 0x01, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,\n            0x04, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,\n            0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,\n            0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x68, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n            0x02\n        ]\n\n        let fs = localFileSystem\n        try withTemporaryFile { [contents] vfsPath in\n            try withTemporaryDirectory(removeTreeOnDeinit: true) { [contents] tempDirPath in\n                let file = tempDirPath.appending(\"best\")\n                try fs.writeFileContents(file, string: \"best\")\n\n                let sym = tempDirPath.appending(\"hello\")\n                try fs.createSymbolicLink(sym, pointingAt: file, relative: false)\n\n                let executable = tempDirPath.appending(\"exec-foo\")\n                try fs.writeFileContents(executable, bytes: ByteString(contents))\n#if !os(Windows)\n                try fs.chmod(.executable, path: executable, options: [])\n#endif\n\n                let executableSym = tempDirPath.appending(\"exec-sym\")\n                try fs.createSymbolicLink(executableSym, pointingAt: executable, relative: false)\n\n                try fs.createDirectory(tempDirPath.appending(\"dir\"))\n                try fs.writeFileContents(tempDirPath.appending(components: [\"dir\", \"file\"]), bytes: [])\n\n                try VirtualFileSystem.serializeDirectoryTree(tempDirPath, into: AbsolutePath(vfsPath.path), fs: fs, includeContents: [executable])\n            }\n\n            let vfs = try VirtualFileSystem(path: vfsPath.path, fs: fs)\n\n            // exists()\n            #expect(vfs.exists(AbsolutePath(\"/\")))\n            #expect(!vfs.exists(AbsolutePath(\"/does-not-exist\")))\n\n            // isFile()\n            let filePath = AbsolutePath(\"/best\")\n            #expect(vfs.exists(filePath))\n            #expect(vfs.isFile(filePath))\n            #expect(try vfs.getFileInfo(filePath).fileType == .typeRegular)\n            #expect(!vfs.isDirectory(filePath))\n            #expect(!vfs.isFile(AbsolutePath(\"/does-not-exist\")))\n            #expect(!vfs.isSymlink(AbsolutePath(\"/does-not-exist\")))\n            #expect(throws: (any Error).self) {\n                try vfs.getFileInfo(AbsolutePath(\"/does-not-exist\"))\n            }\n\n            // isSymlink()\n            let symPath = AbsolutePath(\"/hello\")\n            #expect(vfs.isSymlink(symPath))\n            #expect(vfs.isFile(symPath))\n            #expect(try vfs.getFileInfo(symPath).fileType == .typeSymbolicLink)\n            #expect(!vfs.isDirectory(symPath))\n\n            // isExecutableFile\n            let executablePath = AbsolutePath(\"/exec-foo\")\n            let executableSymPath = AbsolutePath(\"/exec-sym\")\n            #expect(vfs.isExecutableFile(executablePath))\n            #expect(vfs.isExecutableFile(executableSymPath))\n            #expect(vfs.isSymlink(executableSymPath))\n            #expect(!vfs.isExecutableFile(symPath))\n            #expect(!vfs.isExecutableFile(filePath))\n            #expect(!vfs.isExecutableFile(AbsolutePath(\"/does-not-exist\")))\n            #expect(!vfs.isExecutableFile(AbsolutePath(\"/\")))\n\n            // readFileContents\n            let execFileContents = try vfs.readFileContents(executablePath)\n            #expect(execFileContents == ByteString(contents))\n\n            // isDirectory()\n            #expect(vfs.isDirectory(AbsolutePath(\"/\")))\n            #expect(!vfs.isDirectory(AbsolutePath(\"/does-not-exist\")))\n\n            // getDirectoryContents()\n            let dirContents = try vfs.getDirectoryContents(AbsolutePath(\"/\"))\n            #expect(dirContents.sorted() == [\"best\", \"dir\", \"exec-foo\", \"exec-sym\", \"hello\"])\n            #expect {try vfs.getDirectoryContents(AbsolutePath(\"/does-not-exist\"))} throws: { error in\n                (error.localizedDescription == \"no such file or directory: \\(AbsolutePath(\"/does-not-exist\"))\")\n            }\n\n            let thisDirectoryContents = try vfs.getDirectoryContents(AbsolutePath(\"/\"))\n            #expect(!thisDirectoryContents.contains(where: { $0 == \".\" }))\n            #expect(!thisDirectoryContents.contains(where: { $0 == \"..\" }))\n            #expect(thisDirectoryContents.sorted() == [\"best\", \"dir\", \"exec-foo\", \"exec-sym\", \"hello\"])\n\n            let contents = try vfs.getDirectoryContents(AbsolutePath(\"/dir\"))\n            #expect(contents == [\"file\"])\n\n            let fileContents = try vfs.readFileContents(AbsolutePath(\"/dir/file\"))\n            #expect(fileContents == \"\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Graph/AdjacencyMatrixTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport Testing\n\nstruct AdjacencyMatrixTests {\n    @Test\n    func empty() {\n        var matrix = AdjacencyMatrix(rows: 0, columns: 0)\n        #expect(matrix.bitCount == 0)\n\n        matrix = AdjacencyMatrix(rows: 0, columns: 42)\n        #expect(matrix.bitCount == 0)\n\n        matrix = AdjacencyMatrix(rows: 42, columns: 0)\n        #expect(matrix.bitCount == 0)\n    }\n\n    @Test\n    func bits() {\n        for count in 1..<10 {\n            var matrix = AdjacencyMatrix(rows: count, columns: count)\n            for row in 0..<count {\n                for column in 0..<count {\n                    #expect(!matrix[row, column])\n                    matrix[row, column] = true\n                    #expect(matrix[row, column])\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Graph/DirectedGraphTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport Basics\n\nimport Testing\n\nstruct DirectedGraphTests {\n    @Test\n    func nodesConnection() {\n        var graph = DirectedGraph(nodes: [\"app1\", \"lib1\", \"lib2\", \"app2\", \"lib3\"])\n        graph.addEdge(source: 0, destination: 1)\n        graph.addEdge(source: 1, destination: 2)\n        #expect(graph.areNodesConnected(source: 0, destination: 2))\n        #expect(!graph.areNodesConnected(source: 2, destination: 0))\n\n        graph.addEdge(source: 0, destination: 4)\n        graph.addEdge(source: 3, destination: 4)\n        #expect(graph.areNodesConnected(source: 3, destination: 4))\n        #expect(graph.areNodesConnected(source: 0, destination: 4))\n        #expect(!graph.areNodesConnected(source: 1, destination: 4))\n        #expect(graph.areNodesConnected(source: 0, destination: 4))\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Graph/UndirectedGraphTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport Basics\n\nimport Testing\n\nstruct UndirectedGraphTests {\n    @Test\n    func nodesConnection() {\n        var graph = UndirectedGraph(nodes: [\"app1\", \"lib1\", \"lib2\", \"app2\", \"lib3\", \"app3\"])\n        graph.addEdge(source: 0, destination: 1)\n        graph.addEdge(source: 1, destination: 2)\n        #expect(graph.areNodesConnected(source: 0, destination: 2))\n        #expect(graph.areNodesConnected(source: 2, destination: 0))\n\n        graph.addEdge(source: 0, destination: 4)\n        graph.addEdge(source: 3, destination: 4)\n        #expect(graph.areNodesConnected(source: 3, destination: 4))\n        #expect(graph.areNodesConnected(source: 4, destination: 3))\n        #expect(graph.areNodesConnected(source: 0, destination: 4))\n        #expect(graph.areNodesConnected(source: 4, destination: 0))\n        #expect(graph.areNodesConnected(source: 1, destination: 4))\n        #expect(graph.areNodesConnected(source: 4, destination: 1))\n\n        for i in 0...4 {\n            #expect(!graph.areNodesConnected(source: i, destination: 5))\n            #expect(!graph.areNodesConnected(source: 5, destination: i))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/HTTPClientTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\n@testable import Basics\nimport _Concurrency\nimport _InternalTestSupport\nimport Testing\nimport XCTest\n\nclass HTTPClientXCTest: XCTestCase {\n    func testEponentialBackoff() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8501\")\n        let counter = SendableBox(0)\n        let lastCall = SendableBox<Date>(Date())\n        let maxAttempts = 5\n        let errorCode = Int.random(in: 500 ..< 600)\n        let delay = SendableTimeInterval.milliseconds(100)\n\n        let httpClient = HTTPClient { _, _ in\n            let count = await counter.value\n            let expectedDelta = pow(2.0, Double(count - 1)) * delay.timeInterval()!\n            let delta = await Date().timeIntervalSince(lastCall.value)\n            XCTAssertEqual(delta, expectedDelta, accuracy: 0.1)\n\n            await counter.increment()\n            await lastCall.resetDate()\n            return .init(statusCode: errorCode)\n        }\n        var request = HTTPClient.Request(method: .get, url: \"http://test\")\n        request.options.retryStrategy = .exponentialBackoff(maxAttempts: maxAttempts, baseDelay: delay)\n\n        let response = try await httpClient.execute(request)\n        XCTAssertEqual(response.statusCode, errorCode)\n        let count = await counter.value\n        XCTAssertEqual(count, maxAttempts, \"retries should match\")\n    }\n}\n\n\nstruct HTTPClientTests {\n    @Test\n    func head() async throws {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody: Data? = nil\n\n        let httpClient = HTTPClient { request, _ in\n            #expect(request.url == url)\n            #expect(request.method == .head)\n            self.expectRequestHeaders(request.headers, expected: requestHeaders)\n            return .init(statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.head(url, headers: requestHeaders)\n        #expect(response.statusCode == responseStatus)\n        self.expectResponseHeaders(response.headers, expected: responseHeaders)\n        #expect(response.body == responseBody)\n    }\n\n    @Test\n    func testGet() async throws {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        let httpClient = HTTPClient { request, _ in\n            #expect(request.url == url)\n            #expect(request.method == .get)\n            self.expectRequestHeaders(request.headers, expected: requestHeaders)\n            return .init(statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.get(url, headers: requestHeaders)\n        #expect(response.statusCode == responseStatus)\n        self.expectResponseHeaders(response.headers, expected: responseHeaders)\n        #expect(response.body == responseBody)\n    }\n\n    @Test\n    func post() async throws {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestBody = Data(UUID().uuidString.utf8)\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        let httpClient = HTTPClient { request, _ in\n            #expect(request.url == url)\n            #expect(request.method == .post)\n            self.expectRequestHeaders(request.headers, expected: requestHeaders)\n            #expect(request.body == requestBody)\n            return .init(statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.post(url, body: requestBody, headers: requestHeaders)\n        #expect(response.statusCode == responseStatus)\n        self.expectResponseHeaders(response.headers, expected: responseHeaders)\n        #expect(response.body == responseBody)\n    }\n\n    @Test\n    func put() async throws {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestBody = Data(UUID().uuidString.utf8)\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        let httpClient = HTTPClient { request, _ in\n            #expect(request.url == url)\n            #expect(request.method == .put)\n            self.expectRequestHeaders(request.headers, expected: requestHeaders)\n            #expect(request.body == requestBody)\n            return .init(statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.put(url, body: requestBody, headers: requestHeaders)\n        #expect(response.statusCode == responseStatus)\n        self.expectResponseHeaders(response.headers, expected: responseHeaders)\n        #expect(response.body == responseBody)\n    }\n\n    @Test\n    func delete() async throws {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        let httpClient = HTTPClient { request, _ in\n            #expect(request.url == url)\n            #expect(request.method == .delete)\n            self.expectRequestHeaders(request.headers, expected: requestHeaders)\n            return .init(statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.delete(url, headers: requestHeaders)\n        #expect(response.statusCode == responseStatus)\n        self.expectResponseHeaders(response.headers, expected: responseHeaders)\n        #expect(response.body == responseBody)\n    }\n\n    @Test\n    func extraHeaders() async throws {\n        let url = URL(\"http://test\")\n        let globalHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let httpClient = HTTPClient(configuration: .init(requestHeaders: globalHeaders)) { request, _ in\n            var expectedHeaders = globalHeaders\n            expectedHeaders.merge(requestHeaders)\n            self.expectRequestHeaders(request.headers, expected: expectedHeaders)\n            return .init(statusCode: 200)\n        }\n\n        var request = HTTPClient.Request(method: .get, url: url, headers: requestHeaders)\n        request.options.addUserAgent = true\n\n        let response = try await httpClient.execute(request)\n        #expect(response.statusCode == 200)\n    }\n\n    @Test\n    func userAgent() async throws {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let httpClient = HTTPClient { request, _ in\n            #expect(request.headers.contains(\"User-Agent\"), \"expecting User-Agent\")\n            self.expectRequestHeaders(request.headers, expected: requestHeaders)\n            return .init(statusCode: 200)\n        }\n        var request = HTTPClient.Request(method: .get, url: url, headers: requestHeaders)\n        request.options.addUserAgent = true\n\n        let response = try await httpClient.execute(request)\n        #expect(response.statusCode == 200)\n    }\n\n    @Test\n    func noUserAgent() async throws {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let httpClient = HTTPClient { request, _ in\n            #expect(!request.headers.contains(\"User-Agent\"), \"expecting User-Agent\")\n            self.expectRequestHeaders(request.headers, expected: requestHeaders)\n            return .init(statusCode: 200)\n        }\n\n        var request = HTTPClient.Request(method: .get, url: url, headers: requestHeaders)\n        request.options.addUserAgent = false\n\n        let response = try await httpClient.execute(request)\n        #expect(response.statusCode == 200)\n    }\n\n    @Test\n    func authorization() async throws {\n        let url = URL(\"http://test\")\n\n        do {\n            let authorization = UUID().uuidString\n\n            let httpClient = HTTPClient { request, _ in\n                #expect(request.headers.contains(\"Authorization\"), \"expecting Authorization\")\n                #expect(request.headers.get(\"Authorization\").first == authorization)\n                return .init(statusCode: 200)\n            }\n\n            var request = HTTPClient.Request(method: .get, url: url)\n            request.options.authorizationProvider = { requestUrl in\n                requestUrl == url ? authorization : nil\n            }\n\n            let response = try await httpClient.execute(request)\n            #expect(response.statusCode == 200)\n        }\n\n        do {\n            let httpClient = HTTPClient { request, _ in\n                #expect(!request.headers.contains(\"Authorization\"), \"not expecting Authorization\")\n                return .init(statusCode: 200)\n            }\n\n            var request = HTTPClient.Request(method: .get, url: url)\n            request.options.authorizationProvider = { _ in \"\" }\n\n            let response = try await httpClient.execute(request)\n            #expect(response.statusCode == 200)\n        }\n    }\n\n    @Test\n    func validResponseCodes() async throws {\n        let statusCode = Int.random(in: 201 ..< 500)\n\n        let httpClient = HTTPClient { _, _ in\n            throw HTTPClientError.badResponseStatusCode(statusCode)\n        }\n\n        var request = HTTPClient.Request(method: .get, url: \"http://test\")\n        request.options.validResponseCodes = [200]\n\n        await #expect(throws: HTTPClientError.badResponseStatusCode(statusCode)) {\n            try await httpClient.execute(request)\n        }\n    }\n\n    @Test\n    func hostCircuitBreaker() async throws {\n        let maxErrors = 5\n        let errorCode = Int.random(in: 500 ..< 600)\n        let age = SendableTimeInterval.seconds(5)\n\n        let host = \"http://tes-\\(UUID().uuidString).com\"\n        let configuration = HTTPClientConfiguration(circuitBreakerStrategy: .hostErrors(maxErrors: maxErrors, age: age))\n        let httpClient = HTTPClient(configuration: configuration) { _, _ in\n                .init(statusCode: errorCode)\n        }\n\n        // make the initial errors\n        do {\n            let counter = SendableBox(0)\n            for index in (0 ..< maxErrors) {\n                let response = try await httpClient.get(URL(\"\\(host)/\\(index)/foo\"))\n                await counter.increment()\n                #expect(response.statusCode == errorCode)\n            }\n            let count = await counter.value\n            #expect(count == maxErrors)\n        }\n\n        // these should all circuit break\n        let counter = SendableBox(0)\n        let total = Int.random(in: 10 ..< 20)\n        for index in (0 ..< total) {\n            do {\n                let response = try await httpClient.get(URL(\"\\(host)/\\(index)/foo\"))\n                Issue.record(\"unexpected success \\(response)\")\n            } catch {\n                #expect(error as? HTTPClientError == .circuitBreakerTriggered)\n            }\n\n            await counter.increment()\n        }\n\n        let count = await counter.value\n        #expect(count == total)\n    }\n\n    @Test\n    func hostCircuitBreakerAging() async throws {\n        let maxErrors = 5\n        let errorCode = Int.random(in: 500 ..< 600)\n        let ageInMilliseconds = 100\n\n        let host = \"http://tes-\\(UUID().uuidString).com\"\n        let configuration = HTTPClientConfiguration(\n            circuitBreakerStrategy: .hostErrors(\n                maxErrors: maxErrors,\n                age: .milliseconds(ageInMilliseconds)\n            )\n        )\n        let httpClient = HTTPClient(configuration: configuration) { request, _ in\n            if request.url.lastPathComponent == \"error\" {\n                return .init(statusCode: errorCode)\n            } else if request.url.lastPathComponent == \"okay\" {\n                return .okay()\n            } else {\n                throw StringError(\"unknown request \\(request.url)\")\n            }\n        }\n\n        // make the initial errors\n        do {\n            let counter = SendableBox(0)\n            for index in (0 ..< maxErrors) {\n                let response = try await httpClient.get(URL(\"\\(host)/\\(index)/error\"))\n                await counter.increment()\n                #expect(response.statusCode == errorCode)\n            }\n            let count = await counter.value\n            #expect(count == maxErrors)\n        }\n\n        // these should not circuit break since they are deliberately aged\n        let total = Int.random(in: 10 ..< 20)\n        let count = ThreadSafeBox<Int>(0)\n\n        for index in (0 ..< total) {\n            // age it\n            let sleepInterval = SendableTimeInterval.milliseconds(ageInMilliseconds)\n            try await Task.sleep(nanoseconds: UInt64(sleepInterval.nanoseconds()!))\n            let response = try await httpClient.get(\"\\(host)/\\(index)/okay\")\n            count.increment()\n            #expect(response.statusCode == 200)\n        }\n\n        #expect(count.get() == total)\n    }\n\n    @Test\n    func hTTPClientHeaders() async throws {\n        var headers = HTTPClientHeaders()\n\n        let items = (1 ... Int.random(in: 10 ... 20)).map { index in HTTPClientHeaders.Item(name: \"header-\\(index)\", value: UUID().uuidString) }\n        headers.add(items)\n\n        #expect(headers.count == items.count)\n        items.forEach { item in\n            #expect(headers.get(item.name).first == item.value)\n        }\n\n        headers.add(items.first!)\n        #expect(headers.count == items.count)\n\n        let name = UUID().uuidString\n        let values = (1 ... Int.random(in: 10 ... 20)).map { \"value-\\($0)\" }\n        values.forEach { value in\n            headers.add(name: name, value: value)\n        }\n        #expect(headers.count == items.count + 1)\n        #expect(values == headers.get(name))\n    }\n\n    @Test\n    func exceedsDownloadSizeLimitProgress() async throws {\n        let maxSize: Int64 = 50\n\n        let httpClient = HTTPClient { request, progress in\n            switch request.method {\n                case .head:\n                    return .init(\n                        statusCode: 200,\n                        headers: .init([.init(name: \"Content-Length\", value: \"0\")])\n                    )\n                case .get:\n                    try progress?(Int64(maxSize * 2), 0)\n                default:\n                    Issue.record(\"method should match\")\n            }\n\n            fatalError(\"unreachable\")\n        }\n\n        var request = HTTPClient.Request(url: \"http://test\")\n        request.options.maximumResponseSizeInBytes = 10\n\n        await #expect(throws: HTTPClientError.responseTooLarge(maxSize * 2)) {\n            try await httpClient.execute(request)\n        }\n    }\n\n    @Test\n    func maxConcurrency() async throws {\n        let maxConcurrentRequests = 2\n        let concurrentRequests = SendableBox(0)\n\n        var configuration = HTTPClient.Configuration()\n        configuration.maxConcurrentRequests = maxConcurrentRequests\n        let httpClient = HTTPClient(configuration: configuration) { request, _ in\n            await concurrentRequests.increment()\n\n            if await concurrentRequests.value > maxConcurrentRequests {\n                Issue.record(\"too many concurrent requests \\(concurrentRequests), expected \\(maxConcurrentRequests)\")\n            }\n\n            await concurrentRequests.decrement()\n\n            return .okay()\n        }\n\n        let total = 1000\n        try await withThrowingTaskGroup(of: HTTPClient.Response.self) { group in\n            for _ in 0..<total {\n                group.addTask {\n                    try await httpClient.get(\"http://localhost/test\")\n                }\n            }\n\n            var results = [HTTPClient.Response]()\n            for try await result in group {\n                results.append(result)\n            }\n\n            #expect(results.count == total)\n\n            for result in results {\n                #expect(result.statusCode == 200)\n            }\n        }\n    }\n\n    private func expectRequestHeaders(_ headers: HTTPClientHeaders, expected: HTTPClientHeaders, sourceLocation: SourceLocation = #_sourceLocation) {\n        let noAgent = HTTPClientHeaders(headers.filter { $0.name != \"User-Agent\" })\n        #expect(noAgent == expected, sourceLocation: sourceLocation)\n    }\n\n    private func expectResponseHeaders(_ headers: HTTPClientHeaders, expected: HTTPClientHeaders, sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(headers == expected, sourceLocation: sourceLocation)\n    }\n\n}\n"
  },
  {
    "path": "Tests/BasicsTests/LegacyHTTPClientTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport _InternalTestSupport\nimport XCTest\n\nfinal class LegacyHTTPClientTests: XCTestCase {\n    func testHead() {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody: Data? = nil\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertEqual(request.method, .head, \"method should match\")\n            self.assertRequestHeaders(request.headers, expected: requestHeaders)\n            completion(.success(LegacyHTTPClient.Response(statusCode: responseStatus, headers: responseHeaders, body: responseBody)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.head(url, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus, \"statusCode should match\")\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody, \"body should match\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testGet() {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertEqual(request.method, .get, \"method should match\")\n            self.assertRequestHeaders(request.headers, expected: requestHeaders)\n            completion(.success(LegacyHTTPClient.Response(statusCode: responseStatus, headers: responseHeaders, body: responseBody)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.get(url, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus, \"statusCode should match\")\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody, \"body should match\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testPost() {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestBody = Data(UUID().uuidString.utf8)\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertEqual(request.method, .post, \"method should match\")\n            self.assertRequestHeaders(request.headers, expected: requestHeaders)\n            XCTAssertEqual(request.body, requestBody, \"body should match\")\n            completion(.success(LegacyHTTPClient.Response(statusCode: responseStatus, headers: responseHeaders, body: responseBody)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.post(url, body: requestBody, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus, \"statusCode should match\")\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody, \"body should match\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testPut() {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestBody = Data(UUID().uuidString.utf8)\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertEqual(request.method, .put, \"method should match\")\n            self.assertRequestHeaders(request.headers, expected: requestHeaders)\n            XCTAssertEqual(request.body, requestBody, \"body should match\")\n            completion(.success(LegacyHTTPClient.Response(statusCode: responseStatus, headers: responseHeaders, body: responseBody)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.put(url, body: requestBody, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus, \"statusCode should match\")\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody, \"body should match\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testDelete() {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseStatus = Int.random(in: 201 ..< 500)\n        let responseHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertEqual(request.method, .delete, \"method should match\")\n            self.assertRequestHeaders(request.headers, expected: requestHeaders)\n            completion(.success(LegacyHTTPClient.Response(statusCode: responseStatus, headers: responseHeaders, body: responseBody)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.delete(url, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus, \"statusCode should match\")\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody, \"body should match\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testExtraHeaders() {\n        let url = URL(\"http://test\")\n        let globalHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            var expectedHeaders = globalHeaders\n            expectedHeaders.merge(requestHeaders)\n            self.assertRequestHeaders(request.headers, expected: expectedHeaders)\n            completion(.success(LegacyHTTPClient.Response(statusCode: 200)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.requestHeaders = globalHeaders\n\n        var request = LegacyHTTPClient.Request(method: .get, url: url, headers: requestHeaders)\n        request.options.addUserAgent = true\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.execute(request) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, 200, \"statusCode should match\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testUserAgent() {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertTrue(request.headers.contains(\"User-Agent\"), \"expecting User-Agent\")\n            self.assertRequestHeaders(request.headers, expected: requestHeaders)\n            completion(.success(LegacyHTTPClient.Response(statusCode: 200)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        var request = LegacyHTTPClient.Request(method: .get, url: url, headers: requestHeaders)\n        request.options.addUserAgent = true\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.execute(request) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, 200, \"statusCode should match\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testNoUserAgent() {\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertFalse(request.headers.contains(\"User-Agent\"), \"expecting User-Agent\")\n            self.assertRequestHeaders(request.headers, expected: requestHeaders)\n            completion(.success(LegacyHTTPClient.Response(statusCode: 200)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        var request = LegacyHTTPClient.Request(method: .get, url: url, headers: requestHeaders)\n        request.options.addUserAgent = false\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.execute(request) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, 200, \"statusCode should match\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testAuthorization() {\n        let url = URL(\"http://test\")\n\n        do {\n            let authorization = UUID().uuidString\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertTrue(request.headers.contains(\"Authorization\"), \"expecting Authorization\")\n                XCTAssertEqual(request.headers.get(\"Authorization\").first, authorization, \"expecting Authorization to match\")\n                completion(.success(LegacyHTTPClient.Response(statusCode: 200)))\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            var request = LegacyHTTPClient.Request(method: .get, url: url)\n\n            request.options.authorizationProvider = { requestUrl in\n                requestUrl == url ? authorization : nil\n            }\n\n            let promise = XCTestExpectation(description: \"completed\")\n            httpClient.execute(request) { result in\n                switch result {\n                case .failure(let error):\n                    XCTFail(\"unexpected error \\(error)\")\n                case .success(let response):\n                    XCTAssertEqual(response.statusCode, 200, \"statusCode should match\")\n                }\n                promise.fulfill()\n            }\n\n            wait(for: [promise], timeout: 1)\n        }\n\n        do {\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertFalse(request.headers.contains(\"Authorization\"), \"not expecting Authorization\")\n                completion(.success(LegacyHTTPClient.Response(statusCode: 200)))\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            var request = LegacyHTTPClient.Request(method: .get, url: url)\n            request.options.authorizationProvider = { _ in \"\" }\n\n            let promise = XCTestExpectation(description: \"completed\")\n            httpClient.execute(request) { result in\n                switch result {\n                case .failure(let error):\n                    XCTFail(\"unexpected error \\(error)\")\n                case .success(let response):\n                    XCTAssertEqual(response.statusCode, 200, \"statusCode should match\")\n                }\n                promise.fulfill()\n            }\n\n            wait(for: [promise], timeout: 1)\n        }\n    }\n\n    func testValidResponseCodes() {\n        let statusCode = Int.random(in: 201 ..< 500)\n        let brokenHandler: LegacyHTTPClient.Handler = { _, _, completion in\n            completion(.failure(HTTPClientError.badResponseStatusCode(statusCode)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: brokenHandler)\n        var request = LegacyHTTPClient.Request(method: .get, url: \"http://test\")\n        request.options.validResponseCodes = [200]\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.execute(request) { result in\n            switch result {\n            case .failure(let error):\n                XCTAssertEqual(error as? HTTPClientError, .badResponseStatusCode(statusCode), \"expected error to match\")\n            case .success(let response):\n                XCTFail(\"unexpected success \\(response)\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testExponentialBackoff() throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8501\")\n\n        let count = ThreadSafeBox<Int>(0)\n        let lastCall = ThreadSafeBox<Date?>()\n        let maxAttempts = 5\n        let errorCode = Int.random(in: 500 ..< 600)\n        let delay = SendableTimeInterval.milliseconds(100)\n\n        let brokenHandler: LegacyHTTPClient.Handler = { _, _, completion in\n            let expectedDelta = pow(2.0, Double(count.get() - 1)) * delay.timeInterval()!\n            let delta = lastCall.get().flatMap { Date().timeIntervalSince($0) } ?? 0\n            XCTAssertEqual(delta, expectedDelta, accuracy: 0.1)\n\n            count.increment()\n            lastCall.put(Date())\n            completion(.success(LegacyHTTPClient.Response(statusCode: errorCode)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: brokenHandler)\n        var request = LegacyHTTPClient.Request(method: .get, url: \"http://test\")\n        request.options.retryStrategy = .exponentialBackoff(maxAttempts: maxAttempts, baseDelay: delay)\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.execute(request) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, errorCode)\n                XCTAssertEqual(count.get(), maxAttempts, \"retries should match\")\n            }\n            promise.fulfill()\n        }\n\n        let timeout = Double(Int(pow(2.0, Double(maxAttempts))) * delay.milliseconds()!) / 1000\n        wait(for: [promise], timeout: 1.0 + timeout)\n    }\n\n    func testHostCircuitBreaker() {\n        let maxErrors = 5\n        let errorCode = Int.random(in: 500 ..< 600)\n        let age = SendableTimeInterval.seconds(5)\n\n        let host = \"http://tes-\\(UUID().uuidString).com\"\n        let httpClient = LegacyHTTPClient(handler: { _, _, completion in\n            completion(.success(LegacyHTTPClient.Response(statusCode: errorCode)))\n        })\n        httpClient.configuration.circuitBreakerStrategy = .hostErrors(maxErrors: maxErrors, age: age)\n\n        // make the initial errors\n        do {\n            let sync = DispatchGroup()\n            let count = ThreadSafeBox<Int>(0)\n            (0 ..< maxErrors).forEach { index in\n                sync.enter()\n                httpClient.get(URL(\"\\(host)/\\(index)/foo\")) { result in\n                    defer { sync.leave() }\n                    count.increment()\n                    switch result {\n                    case .failure(let error):\n                        XCTFail(\"unexpected failure \\(error)\")\n                    case .success(let response):\n                        XCTAssertEqual(response.statusCode, errorCode)\n                    }\n                }\n            }\n            XCTAssertEqual(sync.wait(timeout: .now() + .seconds(1)), .success, \"should not timeout\")\n            XCTAssertEqual(count.get(), maxErrors, \"expected results count to match\")\n        }\n\n        // these should all circuit break\n        let sync = DispatchGroup()\n        let count = ThreadSafeBox<Int>(0)\n        let total = Int.random(in: 10 ..< 20)\n        (0 ..< total).forEach { index in\n            sync.enter()\n            httpClient.get(URL(\"\\(host)/\\(index)/foo\")) { result in\n                defer { sync.leave() }\n                count.increment()\n                switch result {\n                case .failure(let error):\n                    XCTAssertEqual(error as? HTTPClientError, .circuitBreakerTriggered, \"expected error to match\")\n                case .success(let response):\n                    XCTFail(\"unexpected success \\(response)\")\n                }\n            }\n        }\n\n        XCTAssertEqual(sync.wait(timeout: .now() + .seconds(1)), .success, \"should not timeout\")\n        XCTAssertEqual(count.get(), total, \"expected results count to match\")\n    }\n\n    func testHostCircuitBreakerAging() {\n        let maxErrors = 5\n        let errorCode = Int.random(in: 500 ..< 600)\n        let ageInMilliseconds = 100\n\n        let host = \"http://tes-\\(UUID().uuidString).com\"\n        let httpClient = LegacyHTTPClient(handler: { request, _, completion in\n            if request.url.lastPathComponent == \"error\" {\n                completion(.success(LegacyHTTPClient.Response(statusCode: errorCode)))\n            } else if request.url.lastPathComponent == \"okay\" {\n                completion(.success(.okay()))\n            } else {\n                completion(.failure(StringError(\"unknown request \\(request.url)\")))\n            }\n        })\n        httpClient.configuration.circuitBreakerStrategy = .hostErrors(\n            maxErrors: maxErrors,\n            age: .milliseconds(ageInMilliseconds)\n        )\n\n\n        // make the initial errors\n        do {\n            let sync = DispatchGroup()\n            let count = ThreadSafeBox<Int>(0)\n            (0 ..< maxErrors).forEach { index in\n                sync.enter()\n                httpClient.get(URL(\"\\(host)/\\(index)/error\")) { result in\n                    defer { sync.leave() }\n                    count.increment()\n                    switch result {\n                    case .failure(let error):\n                        XCTFail(\"unexpected failure \\(error)\")\n                    case .success(let response):\n                        XCTAssertEqual(response.statusCode, errorCode)\n                    }\n                }\n            }\n            XCTAssertEqual(sync.wait(timeout: .now() + .seconds(1)), .success, \"should not timeout\")\n            XCTAssertEqual(count.get(), maxErrors, \"expected results count to match\")\n        }\n\n        // these should not circuit break since they are deliberately aged\n        let sync = DispatchGroup()\n        let total = Int.random(in: 10 ..< 20)\n        let count = ThreadSafeBox<Int>(0)\n\n        (0 ..< total).forEach { index in\n            sync.enter()\n            // age it\n            DispatchQueue.sharedConcurrent.asyncAfter(deadline: .now() + .milliseconds(ageInMilliseconds)) {\n                httpClient.get(URL(\"\\(host)/\\(index)/okay\")) { result in\n                    defer { sync.leave() }\n                    count.increment()\n                    switch result {\n                    case .failure(let error):\n                        XCTFail(\"unexpected error \\(error)\")\n                    case .success(let response):\n                        XCTAssertEqual(response.statusCode, 200, \"expected status code to match\")\n                    }\n                }\n            }\n        }\n\n        let timeout = DispatchTime.now() + .seconds(1) + .milliseconds(ageInMilliseconds * maxErrors)\n        XCTAssertEqual(sync.wait(timeout: timeout), .success, \"should not timeout\")\n        XCTAssertEqual(count.get(), total, \"expected results count to match\")\n    }\n\n    func testExceedsDownloadSizeLimitProgress() throws {\n        let maxSize: Int64 = 50\n\n        let httpClient = LegacyHTTPClient(handler: { request, progress, completion in\n            switch request.method {\n            case .head:\n                completion(.success(.init(\n                    statusCode: 200,\n                    headers: .init([.init(name: \"Content-Length\", value: \"0\")])\n                )))\n            case .get:\n                do {\n                    try progress?(Int64(maxSize * 2), 0)\n                } catch {\n                    completion(.failure(error))\n                }\n            default:\n                XCTFail(\"method should match\")\n            }\n        })\n\n        var request = LegacyHTTPClient.Request(url: \"http://test\")\n        request.options.maximumResponseSizeInBytes = 10\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.execute(request) { result in\n            switch result {\n            case .failure(let error):\n                XCTAssertEqual(error as? HTTPClientError, .responseTooLarge(maxSize * 2), \"expected error to match\")\n            case .success(let response):\n                XCTFail(\"unexpected success \\(response)\")\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1)\n    }\n\n    func testMaxConcurrency() throws {\n        let maxConcurrentRequests = 2\n        var concurrentRequests = 0\n        let concurrentRequestsLock = NSLock()\n\n        var configuration = LegacyHTTPClient.Configuration()\n        configuration.maxConcurrentRequests = maxConcurrentRequests\n        let httpClient = LegacyHTTPClient(configuration: configuration, handler: { request, _, completion in\n            defer {\n                concurrentRequestsLock.withLock {\n                    concurrentRequests -= 1\n                }\n            }\n\n            concurrentRequestsLock.withLock {\n                concurrentRequests += 1\n                if concurrentRequests > maxConcurrentRequests {\n                    XCTFail(\"too many concurrent requests \\(concurrentRequests), expected \\(maxConcurrentRequests)\")\n                }\n            }\n\n            completion(.success(.okay()))\n        })\n\n        let total = 1000\n        let sync = DispatchGroup()\n        let results = ThreadSafeArrayStore<Result<LegacyHTTPClient.Response, Error>>()\n        for _ in 0 ..< total {\n            sync.enter()\n            httpClient.get(URL(\"http://localhost/test\")) { result in\n                defer { sync.leave() }\n                results.append(result)\n            }\n        }\n\n        if case .timedOut = sync.wait(timeout: .now() + .seconds(5)) {\n            throw StringError(\"requests timed out\")\n        }\n\n        XCTAssertEqual(results.count, total, \"expected number of results to match\")\n        for result in results.get() {\n            XCTAssertEqual(try? result.get().statusCode, 200, \"expected '200 okay' response\")\n        }\n    }\n\n    func testCancel() throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let cancellator = Cancellator(observabilityScope: observability.topScope)\n\n        let total = min(10, ProcessInfo.processInfo.activeProcessorCount / 2)\n        // this DispatchGroup is used to wait for the requests to start before calling cancel\n        let startGroup = DispatchGroup()\n        // this DispatchGroup is used to park the delayed threads that would be cancelled\n        let terminatedGroup = DispatchGroup()\n        terminatedGroup.enter()\n        // this DispatchGroup is used to monitor the outstanding threads that would be cancelled and completion handlers thrown away\n        let outstandingGroup = DispatchGroup()\n\n        let httpClient = LegacyHTTPClient(handler: { request, _, completion in\n            print(\"handling \\(request.url)\")\n            if Int(request.url.lastPathComponent)! < total / 2 {\n                DispatchQueue.sharedConcurrent.async {\n                    defer { startGroup.leave() }\n                    print(\"\\(request.url) okay\")\n                    completion(.success(.okay()))\n                }\n            } else {\n                defer { startGroup.leave() }\n                outstandingGroup.enter()\n                print(\"\\(request.url) waiting to be cancelled\")\n                DispatchQueue.sharedConcurrent.async {\n                    defer { outstandingGroup.leave() }\n                    XCTAssertEqual(.success, terminatedGroup.wait(timeout: .now() + 5), \"timeout waiting on terminated signal\")\n                    completion(.failure(StringError(\"should be cancelled\")))\n                }\n            }\n        })\n\n        cancellator.register(name: \"http client\", handler: httpClient)\n\n        let finishGroup = DispatchGroup()\n        let results = ThreadSafeKeyValueStore<URL, Result<LegacyHTTPClient.Response, Error>>()\n        for index in 0 ..< total {\n            startGroup.enter()\n            finishGroup.enter()\n            let url = URL(\"http://test/\\(index)\")\n            httpClient.head(url) { result in\n                defer { finishGroup.leave() }\n                results[url] = result\n            }\n        }\n\n        XCTAssertEqual(.success, startGroup.wait(timeout: .now() + 5), \"timeout starting tasks\")\n\n        let cancelled = cancellator._cancel(deadline: .now() + .seconds(1))\n        XCTAssertEqual(cancelled, 1, \"expected to be terminated\")\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        // this releases the http handler threads that are waiting to test if the call was cancelled\n        terminatedGroup.leave()\n\n        XCTAssertEqual(.success, finishGroup.wait(timeout: .now() + 5), \"timeout finishing tasks\")\n\n        XCTAssertEqual(results.count, total, \"expected \\(total) results\")\n        for (url, result) in results.get() {\n            switch (Int(url.lastPathComponent)! < total / 2, result) {\n            case (true, .success):\n                break // as expected!\n            case (true, .failure(let error)):\n                XCTFail(\"expected success, but failed with \\(type(of: error)) '\\(error)'\")\n            case (false, .success):\n                XCTFail(\"expected operation to be cancelled\")\n            case (false, .failure(let error)):\n                XCTAssert(error is CancellationError, \"expected error to be CancellationError, but was \\(type(of: error)) '\\(error)'\")\n            }\n        }\n\n        // wait for outstanding threads that would be cancelled and completion handlers thrown away\n        XCTAssertEqual(.success, outstandingGroup.wait(timeout: .now() + .seconds(5)), \"timeout waiting for outstanding tasks\")\n    }\n\n    private func assertRequestHeaders(_ headers: HTTPClientHeaders, expected: HTTPClientHeaders) {\n        let noAgent = HTTPClientHeaders(headers.filter { $0.name != \"User-Agent\" })\n        XCTAssertEqual(noAgent, expected, \"expected headers to match\")\n    }\n\n    private func assertResponseHeaders(_ headers: HTTPClientHeaders, expected: HTTPClientHeaders) {\n        XCTAssertEqual(headers, expected, \"expected headers to match\")\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/NetrcTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport Testing\n\nstruct NetrcTests {\n    /// should load machines for a given inline format\n    @Test\n    func loadMachinesInline() throws {\n        let content = \"machine example.com login anonymous password qwerty\"\n\n        let netrc = try NetrcParser.parse(content)\n        #expect(netrc.machines.count == 1)\n\n        let machine = try #require(netrc.machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == \"anonymous\")\n        #expect(machine.password == \"qwerty\")\n\n        let authorization = netrc.authorization(for: \"http://example.com/resource.zip\")\n        #expect(authorization == Netrc.Authorization(login: \"anonymous\", password: \"qwerty\"))\n\n        #expect(netrc.authorization(for: \"http://example2.com/resource.zip\") == nil)\n        #expect(netrc.authorization(for: \"http://www.example2.com/resource.zip\") == nil)\n    }\n\n    /// should load machines for a given multi-line format\n    @Test\n    func loadMachinesMultiLine() throws {\n        let content = \"\"\"\n                    machine example.com\n                    login anonymous\n                    password qwerty\n                    \"\"\"\n\n        let netrc = try NetrcParser.parse(content)\n        #expect(netrc.machines.count == 1)\n\n        let machine = try #require(netrc.machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == \"anonymous\")\n        #expect(machine.password == \"qwerty\")\n\n        let authorization = netrc.authorization(for: \"http://example.com/resource.zip\")\n        #expect(authorization == Netrc.Authorization(login: \"anonymous\", password: \"qwerty\"))\n\n        #expect(netrc.authorization(for: \"http://example2.com/resource.zip\") == nil)\n        #expect(netrc.authorization(for: \"http://www.example2.com/resource.zip\") == nil)\n    }\n\n    /// Should fall back to default machine when not matching host\n    @Test\n    func loadDefaultMachine() throws {\n        let content = \"\"\"\n                    machine example.com\n                    login anonymous\n                    password qwerty\n\n                    default\n                    login id\n                    password secret\n                    \"\"\"\n\n        let netrc = try NetrcParser.parse(content)\n        #expect(netrc.machines.count == 2)\n\n        let machine = try #require(netrc.machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == \"anonymous\")\n        #expect(machine.password == \"qwerty\")\n\n        let machine2 = try #require(netrc.machines.last)\n        #expect(machine2.name == \"default\")\n        #expect(machine2.login == \"id\")\n        #expect(machine2.password == \"secret\")\n\n        let authorization = netrc.authorization(for: \"http://example2.com/resource.zip\")\n        #expect(authorization == Netrc.Authorization(login: \"id\", password: \"secret\"))\n    }\n\n    @Test\n    func regexParsing() throws {\n        let content = \"\"\"\n                    machine machine\n                    login login\n                    password password\n\n                    machine login\n                    password machine\n                    login password\n\n                    default machine\n                    login id\n                    password secret\n\n                    machinemachine machine\n                    loginlogin id\n                    passwordpassword secret\n\n                    default\n                    login id\n                    password secret\n                    \"\"\"\n\n        let netrc = try NetrcParser.parse(content)\n        #expect(netrc.machines.count == 3)\n\n        #expect(netrc.machines[0].name == \"machine\")\n        #expect(netrc.machines[0].login == \"login\")\n        #expect(netrc.machines[0].password == \"password\")\n\n        #expect(netrc.machines[1].name == \"login\")\n        #expect(netrc.machines[1].login == \"password\")\n        #expect(netrc.machines[1].password == \"machine\")\n\n        #expect(netrc.machines[2].name == \"default\")\n        #expect(netrc.machines[2].login == \"id\")\n        #expect(netrc.machines[2].password == \"secret\")\n\n        let authorization = netrc.authorization(for: \"http://example2.com/resource.zip\")\n        #expect(authorization == Netrc.Authorization(login: \"id\", password: \"secret\"))\n    }\n\n    @Test\n    func outOfOrderDefault() {\n        let content = \"\"\"\n                    machine machine\n                    login login\n                    password password\n\n                    machine login\n                    password machine\n                    login password\n\n                    default\n                    login id\n                    password secret\n\n                    machine machine\n                    login id\n                    password secret\n                    \"\"\"\n\n        #expect(throws: NetrcError.invalidDefaultMachinePosition) {\n            try NetrcParser.parse(content)\n        }\n    }\n\n    @Test\n    func errorOnMultipleDefault() {\n        let content = \"\"\"\n                    machine machine\n                    login login\n                    password password\n\n                    machine login\n                    password machine\n                    login password\n\n                    default\n                    login id\n                    password secret\n\n                    machine machine\n                    login id\n                    password secret\n\n                    default\n                    login di\n                    password terces\n                    \"\"\"\n\n        #expect(throws: NetrcError.invalidDefaultMachinePosition) {\n            try NetrcParser.parse(content)\n        }\n    }\n\n    /// should load machines for a given multi-line format with comments\n    @Test\n    func loadMachinesMultilineComments() throws {\n        let content = \"\"\"\n                    ## This is a comment\n                    # This is another comment\n                    machine example.com # This is an inline comment\n                    login anonymous\n                    password qwerty # and # another #one\n                    \"\"\"\n\n        let machines = try NetrcParser.parse(content).machines\n        #expect(machines.count == 1)\n\n        let machine = try #require(machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == \"anonymous\")\n        #expect(machine.password == \"qwerty\")\n    }\n\n    /// should load machines for a given multi-line + whitespaces format\n    @Test\n    func loadMachinesMultilineWhitespaces() throws {\n        let content = \"\"\"\n                    machine  example.com login     anonymous\n                    password                  qwerty\n                    \"\"\"\n\n        let machines = try NetrcParser.parse(content).machines\n        #expect(machines.count == 1)\n\n        let machine = try #require(machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == \"anonymous\")\n        #expect(machine.password == \"qwerty\")\n    }\n\n    /// should load multiple machines for a given inline format\n    @Test\n    func loadMultipleMachinesInline() throws {\n        let content = \"machine example.com login anonymous password qwerty machine example2.com login anonymous2 password qwerty2\"\n\n        let netrc = try NetrcParser.parse(content)\n        #expect(netrc.machines.count == 2)\n\n        #expect(netrc.machines[0].name == \"example.com\")\n        #expect(netrc.machines[0].login == \"anonymous\")\n        #expect(netrc.machines[0].password == \"qwerty\")\n\n        #expect(netrc.machines[1].name == \"example2.com\")\n        #expect(netrc.machines[1].login == \"anonymous2\")\n        #expect(netrc.machines[1].password == \"qwerty2\")\n    }\n\n    /// should load multiple machines for a given multi-line format\n    @Test\n    func loadMultipleMachinesMultiline() throws {\n        let content = \"\"\"\n                    machine  example.com login     anonymous\n                    password                  qwerty\n                    machine example2.com\n                    login anonymous2\n                    password qwerty2\n                    \"\"\"\n\n        let machines = try NetrcParser.parse(content).machines\n        #expect(machines.count == 2)\n\n        var machine = machines[0]\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == \"anonymous\")\n        #expect(machine.password == \"qwerty\")\n\n        machine = machines[1]\n        #expect(machine.name == \"example2.com\")\n        #expect(machine.login == \"anonymous2\")\n        #expect(machine.password == \"qwerty2\")\n    }\n\n    /// should throw error when machine parameter is missing\n    @Test\n    func errorMachineParameterMissing() throws {\n        let content = \"login anonymous password qwerty\"\n\n        #expect(throws: NetrcError.machineNotFound) {\n            try NetrcParser.parse(content)\n        }\n    }\n\n    /// should throw error for an empty machine values\n    @Test\n    func errorEmptyMachineValue() throws {\n        let content = \"machine\"\n\n        #expect(throws: NetrcError.machineNotFound) {\n            try NetrcParser.parse(content)\n        }\n    }\n\n    /// should throw error for an empty machine values\n    @Test\n    func emptyMachineValueFollowedByDefaultNoError() throws {\n        let content = \"machine default login id password secret\"\n        let netrc = try NetrcParser.parse(content)\n        let authorization = netrc.authorization(for: \"http://example.com/resource.zip\")\n        #expect(authorization == Netrc.Authorization(login: \"id\", password: \"secret\"))\n    }\n\n    /// should return authorization when config contains a given machine\n    @Test\n    func returnAuthorizationForMachineMatch() throws {\n        let content = \"machine example.com login anonymous password qwerty\"\n\n        let netrc = try NetrcParser.parse(content)\n        let authorization = netrc.authorization(for: \"http://example.com/resource.zip\")\n        #expect(authorization == Netrc.Authorization(login: \"anonymous\", password: \"qwerty\"))\n    }\n\n    @Test\n    func returnNoAuthorizationForUnmatched() throws {\n        let content = \"machine example.com login anonymous password qwerty\"\n        let netrc = try NetrcParser.parse(content)\n        #expect(netrc.authorization(for: \"http://www.example.com/resource.zip\") == nil)\n        #expect(netrc.authorization(for: \"ftp.example.com/resource.zip\") == nil)\n        #expect(netrc.authorization(for: \"http://example2.com/resource.zip\") == nil)\n        #expect(netrc.authorization(for: \"http://www.example2.com/resource.zip\") == nil)\n    }\n\n    /// should not return authorization when config does not contain a given machine\n    @Test\n    func noReturnAuthorizationForNoMachineMatch() throws {\n        let content = \"machine example.com login anonymous password qwerty\"\n\n        let netrc = try NetrcParser.parse(content)\n        #expect(netrc.authorization(for: \"https://example99.com\") == nil)\n        #expect(netrc.authorization(for: \"http://www.example.com/resource.zip\") == nil)\n        #expect(netrc.authorization(for: \"ftp.example.com/resource.zip\") == nil)\n        #expect(netrc.authorization(for: \"http://example2.com/resource.zip\") == nil)\n        #expect(netrc.authorization(for: \"http://www.example2.com/resource.zip\") == nil)\n    }\n\n    /// Test case: https://www.ibm.com/support/knowledgecenter/en/ssw_aix_72/filesreference/netrc.html\n    @Test\n    func iBMDocumentation() throws {\n        let content = \"machine host1.austin.century.com login fred password bluebonnet\"\n\n        let netrc = try NetrcParser.parse(content)\n\n        let machine = try #require(netrc.machines.first)\n        #expect(machine.name == \"host1.austin.century.com\")\n        #expect(machine.login == \"fred\")\n        #expect(machine.password == \"bluebonnet\")\n    }\n\n    /// Should not fail on presence of `account`, `macdef`, `default`\n    /// test case: https://gist.github.com/tpope/4247721\n    @Test\n    func noErrorTrailingAccountMacdefDefault() throws {\n        let content = \"\"\"\n            machine api.heroku.com\n              login my@email.com\n              password 01230123012301230123012301230123\n\n            machine api.github.com password something login somebody\n\n            machine ftp.server login abc password def account ghi macdef somemacro\n            cd somehwhere\n            continues until end of paragraph\n\n            default login anonymous password my@email.com\n            \"\"\"\n\n        let netrc = try NetrcParser.parse(content)\n\n        #expect(netrc.machines.count == 4)\n\n        #expect(netrc.machines[0].name == \"api.heroku.com\")\n        #expect(netrc.machines[0].login == \"my@email.com\")\n        #expect(netrc.machines[0].password == \"01230123012301230123012301230123\")\n\n        #expect(netrc.machines[1].name == \"api.github.com\")\n        #expect(netrc.machines[1].login == \"somebody\")\n        #expect(netrc.machines[1].password == \"something\")\n\n        #expect(netrc.machines[2].name == \"ftp.server\")\n        #expect(netrc.machines[2].login == \"abc\")\n        #expect(netrc.machines[2].password == \"def\")\n\n        #expect(netrc.machines[3].name == \"default\")\n        #expect(netrc.machines[3].login == \"anonymous\")\n        #expect(netrc.machines[3].password == \"my@email.com\")\n    }\n\n    /// Should not fail on presence of `account`, `macdef`, `default`\n    /// test case: https://gist.github.com/tpope/4247721\n    @Test\n    func noErrorMixedAccount() throws {\n        let content = \"\"\"\n            machine api.heroku.com\n              login my@email.com\n              password 01230123012301230123012301230123\n\n            machine api.github.com password something account ghi login somebody\n\n            machine ftp.server login abc account ghi password def macdef somemacro\n            cd somehwhere\n            continues until end of paragraph\n\n            default login anonymous password my@email.com\n            \"\"\"\n\n        let netrc = try NetrcParser.parse(content)\n\n        #expect(netrc.machines.count == 4)\n\n        #expect(netrc.machines[0].name == \"api.heroku.com\")\n        #expect(netrc.machines[0].login == \"my@email.com\")\n        #expect(netrc.machines[0].password == \"01230123012301230123012301230123\")\n\n        #expect(netrc.machines[1].name == \"api.github.com\")\n        #expect(netrc.machines[1].login == \"somebody\")\n        #expect(netrc.machines[1].password == \"something\")\n\n        #expect(netrc.machines[2].name == \"ftp.server\")\n        #expect(netrc.machines[2].login == \"abc\")\n        #expect(netrc.machines[2].password == \"def\")\n\n        #expect(netrc.machines[3].name == \"default\")\n        #expect(netrc.machines[3].login == \"anonymous\")\n        #expect(netrc.machines[3].password == \"my@email.com\")\n    }\n\n    /// Should not fail on presence of `account`, `macdef`, `default`\n    /// test case: https://renenyffenegger.ch/notes/Linux/fhs/home/username/_netrc\n    @Test\n    func noErrorMultipleMacdefAndComments() throws {\n        let content = \"\"\"\n            machine  ftp.foobar.baz\n            login    john\n            password 5ecr3t\n\n            macdef   getmyfile       # define a macro (here named 'getmyfile')\n            cd /abc/defghi/jklm      # The macro can be executed in ftp client\n            get myFile.txt           # by prepending macro name with $ sign\n            quit\n\n            macdef   init            # macro init is searched for when\n            binary                   # ftp connects to server.\n\n            machine  other.server.org\n            login    fred\n            password sunshine4ever\n            \"\"\"\n\n        let netrc = try NetrcParser.parse(content)\n\n        #expect(netrc.machines.count == 2)\n\n        #expect(netrc.machines[0].name == \"ftp.foobar.baz\")\n        #expect(netrc.machines[0].login == \"john\")\n        #expect(netrc.machines[0].password == \"5ecr3t\")\n\n        #expect(netrc.machines[1].name == \"other.server.org\")\n        #expect(netrc.machines[1].login == \"fred\")\n        #expect(netrc.machines[1].password == \"sunshine4ever\")\n    }\n\n    @Test\n    func comments() throws {\n        let content = \"\"\"\n            # A comment at the beginning of the line\n            machine example.com # Another comment\n            login anonymous  # Another comment\n            password qw#erty  # Another comment\n            \"\"\"\n\n        let netrc = try NetrcParser.parse(content)\n\n        let machine = try #require(netrc.machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == \"anonymous\")\n        #expect(machine.password == \"qw#erty\")\n    }\n\n    @Test(\n        arguments: [\n            (testCase: \"qwerty\", expected: \"qwerty\"),\n            (testCase: \"qwe#rty\", expected: \"qwe#rty\"),\n            (testCase: \"\\\"qwe#rty\\\"\", expected: \"qwe#rty\"),\n            (testCase: \"\\\"qwe #rty\\\"\", expected: \"qwe #rty\"),\n            (testCase: \"\\\"qwe# rty\\\"\", expected: \"qwe# rty\")\n        ]\n    )\n    func allHashQuotingPermutations(testCase: String, expected: String) throws {\n        let content = \"\"\"\n            machine example.com\n            login \\(testCase)\n            password \\(testCase)\n            \"\"\"\n        let netrc = try NetrcParser.parse(content)\n\n        let machine = try #require(netrc.machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == expected)\n        #expect(machine.password == expected)\n    }\n\n    @Test(\n        arguments: [\n            (testCase: \"qwerty   # a comment\", expected: \"qwerty\"),\n            (testCase: \"qwe#rty   # a comment\", expected: \"qwe#rty\"),\n            (testCase: \"\\\"qwe#rty\\\"   # a comment\", expected: \"qwe#rty\"),\n            (testCase: \"\\\"qwe #rty\\\"   # a comment\", expected: \"qwe #rty\"),\n            (testCase: \"\\\"qwe# rty\\\"   # a comment\", expected: \"qwe# rty\")\n        ]\n    )\n    func allCommentPermutations(testCase: String, expected: String) throws {\n        let content = \"\"\"\n            machine example.com\n            login \\(testCase)\n            password \\(testCase)\n            \"\"\"\n        let netrc = try NetrcParser.parse(content)\n\n        let machine = try #require(netrc.machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == expected)\n        #expect(machine.password == expected)\n    }\n\n    @Test\n    func quotedMachine() throws {\n        let content = \"\"\"\n            machine \"example.com\"\n            login anonymous\n            password qwerty\n            \"\"\"\n\n        let netrc = try NetrcParser.parse(content)\n\n        let machine = try #require(netrc.machines.first)\n        #expect(machine.name == \"example.com\")\n        #expect(machine.login == \"anonymous\")\n        #expect(machine.password == \"qwerty\")\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/ObservabilitySystemTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\n@testable import Basics\nimport _InternalTestSupport\nimport Testing\n\n// TODO: remove when transition to new diagnostics system is complete\ntypealias Diagnostic = Basics.Diagnostic\n\nstruct ObservabilitySystemTest {\n    @Test\n    func scopes() throws {\n        let collector = Collector()\n        let observabilitySystem = ObservabilitySystem(collector)\n\n        var metadata1 = ObservabilityMetadata()\n        metadata1.testKey1 = UUID().uuidString\n        metadata1.testKey2 = Int.random(in: Int.min..<Int.max)\n        metadata1.testKey3 = Int.random(in: Int.min..<Int.max) > Int.max / 2\n\n        let childScope1 = observabilitySystem.topScope.makeChildScope(description: \"child 1\", metadata: metadata1)\n        childScope1.emit(error: \"error 1\")\n\n        let emitter1 = childScope1.makeDiagnosticsEmitter()\n        emitter1.emit(error: \"error 1.5\")\n\n        try expectDiagnostics(collector.diagnostics) { result in\n            let diagnostic1 = try #require(result.check(diagnostic: \"error 1\", severity: .error))\n            let diagnostic1_metadata = try #require(diagnostic1.metadata)\n            #expect(diagnostic1_metadata.testKey1 == metadata1.testKey1)\n            #expect(diagnostic1_metadata.testKey2 == metadata1.testKey2)\n            #expect(diagnostic1_metadata.testKey3 == metadata1.testKey3)\n\n            let diagnostic1_5 = try #require(result.check(diagnostic: \"error 1.5\", severity: .error))\n            let diagnostic1_5_metadata = try #require(diagnostic1_5.metadata)\n\n            #expect(diagnostic1_5_metadata.testKey1 == metadata1.testKey1)\n            #expect(diagnostic1_5_metadata.testKey2 == metadata1.testKey2)\n            #expect(diagnostic1_5_metadata.testKey3 == metadata1.testKey3)\n        }\n\n        collector.clear()\n\n        var metadata2 = ObservabilityMetadata()\n        metadata2.testKey1 = UUID().uuidString\n        metadata2.testKey2 = Int.random(in: Int.min..<Int.max)\n\n        let mergedMetadata2 = metadata1.merging(metadata2)\n        #expect(mergedMetadata2.testKey1 == metadata2.testKey1)\n        #expect(mergedMetadata2.testKey2 == metadata2.testKey2)\n        #expect(mergedMetadata2.testKey3 == metadata1.testKey3)\n\n        let childScope2 = childScope1.makeChildScope(description: \"child 2\", metadata: metadata2)\n        childScope2.emit(error: \"error 2\")\n\n        let emitter2 = childScope2.makeDiagnosticsEmitter()\n        emitter2.emit(error: \"error 2.5\")\n\n        try expectDiagnostics(collector.diagnostics) { result in\n            let diagnostic2 = try #require(result.check(diagnostic: \"error 2\", severity: .error))\n            let diagnostic2_metadata = try #require(diagnostic2.metadata)\n            #expect(diagnostic2_metadata.testKey1 == mergedMetadata2.testKey1)\n            #expect(diagnostic2_metadata.testKey2 == mergedMetadata2.testKey2)\n            #expect(diagnostic2_metadata.testKey3 == mergedMetadata2.testKey3)\n\n            let diagnostic2_5 = try #require(result.check(diagnostic: \"error 2.5\", severity: .error))\n            let diagnostic2_5_metadata = try #require(diagnostic2_5.metadata)\n            #expect(diagnostic2_5_metadata.testKey1 == mergedMetadata2.testKey1)\n            #expect(diagnostic2_5_metadata.testKey2 == mergedMetadata2.testKey2)\n            #expect(diagnostic2_5_metadata.testKey3 == mergedMetadata2.testKey3)\n        }\n\n        collector.clear()\n\n        var metadata3 = ObservabilityMetadata()\n        metadata3.testKey1 = UUID().uuidString\n\n        let mergedMetadata3 = metadata1.merging(metadata2).merging(metadata3)\n        #expect(mergedMetadata3.testKey1 == metadata3.testKey1)\n        #expect(mergedMetadata3.testKey2 == metadata2.testKey2)\n        #expect(mergedMetadata3.testKey3 == metadata1.testKey3)\n\n        let childScope3 = childScope2.makeChildScope(description: \"child 3\", metadata: metadata3)\n        childScope3.emit(error: \"error 3\")\n\n        var metadata3_5 = ObservabilityMetadata()\n        metadata3_5.testKey1 = UUID().uuidString\n\n        let mergedMetadata3_5 = metadata1.merging(metadata2).merging(metadata3).merging(metadata3_5)\n        #expect(mergedMetadata3_5.testKey1 == metadata3_5.testKey1)\n        #expect(mergedMetadata3_5.testKey2 == metadata2.testKey2)\n        #expect(mergedMetadata3_5.testKey3 == metadata1.testKey3)\n\n        let emitter3 = childScope3.makeDiagnosticsEmitter(metadata: metadata3_5)\n        emitter3.emit(error: \"error 3.5\")\n\n        try expectDiagnostics(collector.diagnostics) { result in\n            let diagnostic3 = try #require(result.check(diagnostic: \"error 3\", severity: .error))\n            let diagnostic3_metadata = try #require(diagnostic3.metadata)\n            #expect(diagnostic3_metadata.testKey1 == mergedMetadata3.testKey1)\n            #expect(diagnostic3_metadata.testKey2 == mergedMetadata3.testKey2)\n            #expect(diagnostic3_metadata.testKey3 == mergedMetadata3.testKey3)\n\n            let diagnostic3_5 = try #require(result.check(diagnostic: \"error 3.5\", severity: .error))\n            let diagnostic3_5_metadata = try #require(diagnostic3_5.metadata)\n            #expect(diagnostic3_5_metadata.testKey1 == mergedMetadata3_5.testKey1)\n            #expect(diagnostic3_5_metadata.testKey2 == mergedMetadata3_5.testKey2)\n            #expect(diagnostic3_5_metadata.testKey3 == mergedMetadata3_5.testKey3)\n        }\n    }\n\n    @Test\n    func basicDiagnostics() throws {\n        let collector = Collector()\n        let observabilitySystem = ObservabilitySystem(collector)\n\n        var metadata = ObservabilityMetadata()\n        metadata.testKey1 = UUID().uuidString\n\n        let emitter = observabilitySystem.topScope.makeDiagnosticsEmitter(metadata: metadata)\n\n        emitter.emit(error: \"error\")\n        emitter.emit(.error(\"error 2\"))\n        emitter.emit(StringError(\"error 3\"))\n        emitter.emit(warning: \"warning\")\n        emitter.emit(.warning(\"warning 2\"))\n        emitter.emit(info: \"info\")\n        emitter.emit(.info(\"info 2\"))\n        emitter.emit(debug: \"debug\")\n        emitter.emit(.debug(\"debug 2\"))\n\n        try expectDiagnostics(collector.diagnostics, problemsOnly: false) { result in\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"error\", severity: .error))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"error 2\", severity: .error))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"error 3\", severity: .error))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n                #expect(diagnostic_metadata.underlyingError as? StringError == StringError(\"error 3\"))\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"warning\", severity: .warning))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"warning 2\", severity: .warning))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"info\", severity: .info))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"info 2\", severity: .info))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"debug\", severity: .error))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"debug 2\", severity: .debug))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == metadata.testKey1)\n            }\n        }\n    }\n\n    @Test\n    func diagnosticsErrorDescription() throws {\n        let collector = Collector()\n        let observabilitySystem = ObservabilitySystem(collector)\n\n        observabilitySystem.topScope.emit(error: \"error\")\n        observabilitySystem.topScope.emit(.error(\"error 2\"))\n        observabilitySystem.topScope.emit(MyError(description: \"error 3\"))\n        observabilitySystem.topScope.emit(MyDescribedError(description: \"error 4\"))\n        observabilitySystem.topScope.emit(MyLocalizedError(errorDescription: \"error 5\"))\n\n        try expectDiagnostics(collector.diagnostics, problemsOnly: false) { result in\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"error\", severity: .error))\n                #expect(diagnostic.metadata?.underlyingError == nil)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"error 2\", severity: .error))\n                #expect(diagnostic.metadata?.underlyingError == nil)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"MyError(description: \\\"error 3\\\")\", severity: .error))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.underlyingError as? MyError == MyError(description: \"error 3\"))\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"error 4\", severity: .error))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.underlyingError as? MyDescribedError == MyDescribedError(description: \"error 4\"))\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"error 5\", severity: .error))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.underlyingError as? MyLocalizedError == MyLocalizedError(errorDescription: \"error 5\"))\n            }\n        }\n\n        struct MyError: Error, Equatable {\n            let description: String\n\n        }\n\n        struct MyDescribedError: Error, CustomStringConvertible, Equatable {\n            let description: String\n        }\n\n        struct MyLocalizedError: LocalizedError, Equatable {\n            let errorDescription: String?\n        }\n    }\n\n    @Test\n    func diagnosticsMetadataMerge() throws {\n        let collector = Collector()\n        let observabilitySystem = ObservabilitySystem(collector)\n\n        var scopeMetadata = ObservabilityMetadata()\n        scopeMetadata.testKey1 = UUID().uuidString\n        scopeMetadata.testKey2 = Int.random(in: Int.min..<Int.max)\n        scopeMetadata.testKey3 = Int.random(in: Int.min..<Int.max) > Int.max / 2\n\n        let scope = observabilitySystem.topScope.makeChildScope(description: \"child scope\", metadata: scopeMetadata)\n\n        var emitterMetadata = ObservabilityMetadata()\n        emitterMetadata.testKey1 = UUID().uuidString\n        emitterMetadata.testKey2 = Int.random(in: Int.min..<Int.max)\n\n        let emitterMergedMetadata = scopeMetadata.merging(emitterMetadata)\n        #expect(emitterMergedMetadata.testKey1 == emitterMetadata.testKey1)\n        #expect(emitterMergedMetadata.testKey2 == emitterMetadata.testKey2)\n        #expect(emitterMergedMetadata.testKey3 == scopeMetadata.testKey3)\n\n        let emitter = scope.makeDiagnosticsEmitter(metadata: emitterMetadata)\n        emitter.emit(error: \"error\")\n\n        var diagnosticMetadata = ObservabilityMetadata()\n        diagnosticMetadata.testKey1 = UUID().uuidString\n\n        let diagnosticMergedMetadata = scopeMetadata.merging(emitterMetadata).merging(diagnosticMetadata)\n        #expect(diagnosticMergedMetadata.testKey1 == diagnosticMetadata.testKey1)\n        #expect(diagnosticMergedMetadata.testKey2 == emitterMetadata.testKey2)\n        #expect(diagnosticMergedMetadata.testKey3 == scopeMetadata.testKey3)\n\n        emitter.emit(warning: \"warning\", metadata: diagnosticMetadata)\n\n        try expectDiagnostics(collector.diagnostics) { result in\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"error\", severity: .error))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == emitterMergedMetadata.testKey1)\n                #expect(diagnostic_metadata.testKey2 == emitterMergedMetadata.testKey2)\n                #expect(diagnostic_metadata.testKey3 == emitterMergedMetadata.testKey3)\n            }\n            do {\n                let diagnostic = try #require(result.check(diagnostic: \"warning\", severity: .warning))\n                let diagnostic_metadata = try #require(diagnostic.metadata)\n                #expect(diagnostic_metadata.testKey1 == diagnosticMergedMetadata.testKey1)\n                #expect(diagnostic_metadata.testKey2 == diagnosticMergedMetadata.testKey2)\n                #expect(diagnostic_metadata.testKey3 == diagnosticMergedMetadata.testKey3)\n            }\n        }\n    }\n\n    struct Collector: ObservabilityHandlerProvider, DiagnosticsHandler {\n        public let verbose: Bool\n        private let _diagnostics = ThreadSafeArrayStore<Diagnostic>()\n\n        public init(verbose: Bool = false) {\n            self.verbose = verbose\n        }\n\n        var diagnosticsHandler: DiagnosticsHandler { self }\n\n        var diagnostics: [Diagnostic] {\n            self._diagnostics.get()\n        }\n\n        func clear() {\n            self._diagnostics.clear()\n        }\n\n        func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic) {\n            self._diagnostics.append(diagnostic)\n        }\n\n        func print(_ output: String, condition: OutputCondition) {\n            switch condition {\n            case .always:\n                Swift.print(output)\n            case .onlyWhenVerbose:\n                guard self.verbose else { return }\n                Swift.print(output)\n            }\n        }\n    }\n}\n\nextension ObservabilityMetadata {\n    public var testKey1: String? {\n        get {\n            self[TestKey1.self]\n        }\n        set {\n            self[TestKey1.self] = newValue\n        }\n    }\n\n    public var testKey2: Int? {\n        get {\n            self[TestKey2.self]\n        }\n        set {\n            self[TestKey2.self] = newValue\n        }\n    }\n\n    public var testKey3: Bool? {\n        get {\n            self[TestKey3.self]\n        }\n        set {\n            self[TestKey3.self] = newValue\n        }\n    }\n\n    enum TestKey1: Key {\n        typealias Value = String\n    }\n    enum TestKey2: Key {\n        typealias Value = Int\n    }\n    enum TestKey3: Key {\n        typealias Value = Bool\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/ProcessInfoTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\nimport Basics\nimport Testing\n@testable import struct _InternalTestSupport.CombinationsWithRepetition\n\nfileprivate let d = [\n            [],\n            [\"\"],\n            [\"line1\"],\n            [\"line1\", \"line2\"],\n            [\"line1\", \"line2\", \"line3\"],\n        ]\nfileprivate let prefixAndSuffixData = CombinationsWithRepetition(of: d, length: 2).map( {data in\n    // Content(prefix: data.0, suffix: data.1)\n    Content(prefix: data[0], suffix: data[1])\n})\n\nfileprivate struct Content {\n    let prefix: [String]\n    let suffix: [String]\n\n    init(prefix pre: [String], suffix: [String]) {\n        self.prefix = pre\n        self.suffix = suffix\n    }\n\n    func getContent(_ value: String) -> String {\n        let contentArray: [String] = self.prefix + [value] + self.suffix\n        let content = contentArray.joined(separator: \"\\n\")\n        return content\n    }\n}\n\n@Suite\nstruct ProcessInfoExtensionTests {\n\n    @Suite\n    struct isAmazonLinux2 {\n        @Test(\n            arguments: [\n                (contentUT: \"\", expected: false),\n                (contentUT: \"PRETTY_NAME=\", expected: false),\n                (contentUT: \"PRETTY_NAME=foo\", expected: false),\n                (contentUT: \"PRETTY_NAME=amzn\", expected: false),\n                (contentUT: \"PRETTY_NAME=Amazon Linux 2\", expected: false),\n                (contentUT: \"PRETTY_NAME=Amazon Linux 2023.6.20250107\", expected: false),\n                (contentUT: \" PRETTY_NAME=amzn\", expected: false),\n                (contentUT: \"PRETTY_NAME=\\\"Amazon Linux 2\\\"\", expected: true),\n                (contentUT: \"PRETTY_NAME=\\\"Amazon Linux 2 (something else)\\\"\", expected: false),\n                (\n                    contentUT: \"\"\"\n                        NAME=\"Amazon Linux\"\n                        VERSION=\"2\"\n                        ID=\"amzn\"\n                        ID_LIKE=\"centos rhel fedora\"\n                        VERSION_ID=\"2\"\n                        PRETTY_NAME=\"Amazon Linux 2\"\n                        ANSI_COLOR=\"0;33\"\n                        CPE_NAME=\"cpe:2.3:o:amazon:amazon_linux:2\"\n                        HOME_URL=\"https://amazonlinux.com/\"\n                        SUPPORT_END=\"2026-06-30\"\n                        \"\"\",\n                    expected: true\n                ),\n                (\n                    contentUT: \"\"\"\n                        NAME=\"Amazon Linux\"\n                        VERSION=\"2\"\n                        ID=\"amzn\"\n                        ID_LIKE=\"centos rhel fedora\"\n                        VERSION_ID=\"2\"\n                        PRETTY_NAME=\"Amazon Linux 2 (something else)\"\n                        ANSI_COLOR=\"0;33\"\n                        CPE_NAME=\"cpe:2.3:o:amazon:amazon_linux:2\"\n                        HOME_URL=\"https://amazonlinux.com/\"\n                        SUPPORT_END=\"2026-06-30\"\n                        \"\"\",\n                    expected: false\n                ),\n                (\n                    contentUT: \"\"\"\n                        NAME=\"Amazon Linux\"\n                        VERSION=\"2\"\n                        ID=\"amzn\"\n                        ID_LIKE=\"centos rhel fedora\"\n                        VERSION_ID=\"2\"\n                        PRETTY_NAME=Amazon Linux 2 (something else)\n                        ANSI_COLOR=\"0;33\"\n                        CPE_NAME=\"cpe:2.3:o:amazon:amazon_linux:2\"\n                        HOME_URL=\"https://amazonlinux.com/\"\n                        SUPPORT_END=\"2026-06-30\"\n                        \"\"\",\n                    expected: false\n                ),\n                (\n                    contentUT: \"\"\"\n                        NAME=\"Amazon Linux\"\n                        VERSION=\"2\"\n                        ID=\"amzn\"\n                        ID_LIKE=\"centos rhel fedora\"\n                        VERSION_ID=\"2\"\n                        PRETTY_NAME=Amazon Linux 2\n                        ANSI_COLOR=\"0;33\"\n                        CPE_NAME=\"cpe:2.3:o:amazon:amazon_linux:2\"\n                        HOME_URL=\"https://amazonlinux.com/\"\n                        SUPPORT_END=\"2026-06-30\"\n                        \"\"\",\n                    expected: false\n                ),\n                (\n                    contentUT: \"\"\"\n                    NAME=\"Amazon Linux\"\n                    VERSION=\"2023\"\n                    ID=\"amzn\"\n                    ID_LIKE=\"fedora\"\n                    VERSION_ID=\"2023\"\n                    PLATFORM_ID=\"platform:al2023\"\n                    PRETTY_NAME=\"Amazon Linux 2023.6.20250107\"\n                    ANSI_COLOR=\"0;33\"\n                    CPE_NAME=\"cpe:2.3:o:amazon:amazon_linux:2023\"\n                    HOME_URL=\"https://aws.amazon.com/linux/amazon-linux-2023/\"\n                    DOCUMENTATION_URL=\"https://docs.aws.amazon.com/linux/\"\n                    SUPPORT_URL=\"https://aws.amazon.com/premiumsupport/\"\n                    BUG_REPORT_URL=\"https://github.com/amazonlinux/amazon-linux-2023\"\n                    VENDOR_NAME=\"AWS\"\n                    VENDOR_URL=\"https://aws.amazon.com/\"\n                    SUPPORT_END=\"2028-03-15\"\n                    \"\"\",\n                    expected: false,\n                )\n            ], prefixAndSuffixData,\n        )\n        fileprivate func isAmazonLinux2ReturnsExpectedValue(\n            data: (contentUT: String, expected: Bool),\n            content: Content,\n        ) async throws {\n            let content = content.getContent(data.contentUT)\n\n            let actual = ProcessInfo.isHostAmazonLinux2(content)\n\n            #expect(actual == data.expected, \"Content is: '\\(content)'\")\n        }\n\n        @Test(\n            \"isHostAmazonLinux2 returns false when not executed on Linux\",\n            .skipHostOS(.linux),\n            .tags(Tag.TestSize.medium),\n        )\n        func isAmazonLinux2ReturnsFalseWhenNotRunOnLinux() {\n            let actual = ProcessInfo.isHostAmazonLinux2()\n\n            #expect(actual == false)\n        }\n    }\n}"
  },
  {
    "path": "Tests/BasicsTests/ProgressAnimationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _Concurrency\nimport Testing\n\n@_spi(SwiftPMInternal)\n@testable\nimport Basics\nimport TSCBasic\n\nstruct ProgressAnimationTests {\n    class TrackingProgressAnimation: ProgressAnimationProtocol {\n        var steps: [Int] = []\n\n        func update(step: Int, total: Int, text: String) {\n            steps.append(step)\n        }\n\n        func complete(success: Bool) {}\n        func clear() {}\n    }\n\n    @Test\n    func throttledPercentProgressAnimation1() {\n        do {\n            let tracking = TrackingProgressAnimation()\n            var now = ContinuousClock().now\n            let animation = ThrottledProgressAnimation(\n                tracking, now: { now }, interval: .milliseconds(100),\n                clock: ContinuousClock.self\n            )\n\n            // Update the animation 10 times with a 50ms interval.\n            let total = 10\n            for i in 0...total {\n                animation.update(step: i, total: total, text: \"\")\n                now += .milliseconds(50)\n            }\n            animation.complete(success: true)\n            #expect(tracking.steps == [0, 2, 4, 6, 8, 10])\n        }\n\n        do {\n            // Check that the last animation update is sent even if\n            // the interval has not passed.\n            let tracking = TrackingProgressAnimation()\n            var now = ContinuousClock().now\n            let animation = ThrottledProgressAnimation(\n                tracking, now: { now }, interval: .milliseconds(100),\n                clock: ContinuousClock.self\n            )\n\n            // Update the animation 10 times with a 50ms interval.\n            let total = 10\n            for i in 0...total - 1 {\n                animation.update(step: i, total: total, text: \"\")\n                now += .milliseconds(50)\n            }\n            // The next update is at 1000ms, but we are at 950ms,\n            // so \"step 9\" is not sent yet.\n            #expect(tracking.steps == [0, 2, 4, 6, 8])\n            // After explicit \"completion\", the last step is flushed out.\n            animation.complete(success: true)\n            #expect(tracking.steps == [0, 2, 4, 6, 8, 9])\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/SQLiteBackedCacheTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\n@testable import Basics\nimport _InternalTestSupport\nimport tsan_utils\nimport Testing\n\nstruct SQLiteBackedCacheTests {\n    @Test\n    func happyCase() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            let cache = SQLiteBackedCache<String>(tableName: \"SQLiteBackedCacheTest\", path: path)\n            defer {\n                #expect(throws: Never.self) {\n                    try cache.close()\n                }\n            }\n\n            let mockData = try makeMockData(fileSystem: localFileSystem, rootPath: tmpPath)\n            try mockData.forEach { key, value in\n                _ = try cache.put(key: key, value: value)\n            }\n\n            try mockData.forEach { key, _ in\n                let result = try cache.get(key: key)\n                #expect(mockData[key] == result)\n            }\n\n            let key = mockData.first!.key\n\n            _ = try cache.put(key: key, value: \"foobar\", replace: false)\n            #expect(try cache.get(key: key) == mockData[key], \"Actual is not as expected\")\n\n            _ = try cache.put(key: key, value: \"foobar\", replace: true)\n            #expect(try cache.get(key: key) == \"foobar\", \"Actual is not as expected\")\n\n            try cache.remove(key: key)\n            #expect(try cache.get(key: key) == nil, \"Actual is not as expected\")\n\n            guard case .path(let cachePath) = cache.location else {\n                Issue.record(\"invalid location \\(cache.location)\")\n                return\n            }\n\n            #expect(cache.fileSystem.exists(cachePath), \"expected file to be written\")\n        }\n    }\n\n    @Test(\n        .disabled(if: (ProcessInfo.hostOperatingSystem == .windows), \"open file cannot be deleted on Windows\"),\n        .disabled(if: is_tsan_enabled(), \"Disabling as tsan is enabled\")\n    )\n    func fileDeleted() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            let cache = SQLiteBackedCache<String>(tableName: \"SQLiteBackedCacheTest\", path: path)\n            defer {\n                #expect(throws: Never.self) {\n                    try cache.close()\n                }\n            }\n\n            let mockData = try makeMockData(fileSystem: localFileSystem, rootPath: tmpPath)\n            try mockData.forEach { key, value in\n                _ = try cache.put(key: key, value: value)\n            }\n\n            try mockData.forEach { key, _ in\n                let result = try cache.get(key: key)\n                #expect(mockData[key] == result)\n            }\n\n            guard case .path(let cachePath) = cache.location else {\n                Issue.record(\"invalid location \\(cache.location)\")\n                return\n            }\n\n            #expect(cache.fileSystem.exists(cachePath), \"expected file to exist at \\(cachePath)\")\n            try cache.fileSystem.removeFileTree(cachePath)\n\n            let key = mockData.first!.key\n\n            do {\n                let result = try cache.get(key: key)\n                #expect(result == nil)\n            }\n\n            do {\n                #expect(throws: Never.self) {\n                    try cache.put(key: key, value: mockData[key]!)\n                }\n                let result = try cache.get(key: key)\n                #expect(mockData[key] == result)\n            }\n\n            #expect(cache.fileSystem.exists(cachePath), \"expected file to exist at \\(cachePath)\")\n        }\n    }\n\n    @Test(\n        .disabled(if: is_tsan_enabled(), \"Disabling as tsan is enabled\")\n    )\n    func fileCorrupt() throws {\n\n        try testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            let cache = SQLiteBackedCache<String>(tableName: \"SQLiteBackedCacheTest\", path: path)\n            defer {\n                #expect(throws: Never.self) {\n                    try cache.close()\n                }\n            }\n\n            let mockData = try makeMockData(fileSystem: localFileSystem, rootPath: tmpPath)\n            try mockData.forEach { key, value in\n                _ = try cache.put(key: key, value: value)\n            }\n\n            try mockData.forEach { key, _ in\n                let result = try cache.get(key: key)\n                #expect(mockData[key] == result)\n            }\n\n            guard case .path(let cachePath) = cache.location else {\n                Issue.record(\"invalid location \\(cache.location)\")\n                return\n            }\n\n            try cache.close()\n\n            #expect(cache.fileSystem.exists(cachePath), \"expected file to exist at \\(path)\")\n            try cache.fileSystem.writeFileContents(cachePath, string: \"blah\")\n\n            #expect {\n                try cache.get(key: mockData.first!.key)\n            } throws: { error in\n                return \"\\(error)\".contains(\"is not a database\")\n            }\n\n            #expect {\n                try cache.put(key: mockData.first!.key, value: mockData.first!.value)\n            } throws: { error in\n                return \"\\(error)\".contains(\"is not a database\")\n            }\n        }\n    }\n\n    @Test\n    func maxSizeNotHandled() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            var configuration = SQLiteBackedCacheConfiguration()\n            configuration.maxSizeInBytes = 1024 * 3\n            configuration.truncateWhenFull = false\n            let cache = SQLiteBackedCache<String>(tableName: \"SQLiteBackedCacheTest\", path: path, configuration: configuration)\n            defer {\n                #expect(throws: Never.self) {\n                    try cache.close()\n                }\n            }\n\n            func create() throws {\n                let mockData = try makeMockData(fileSystem: localFileSystem, rootPath: tmpPath, count: 500)\n                try mockData.forEach { key, value in\n                    _ = try cache.put(key: key, value: value)\n                }\n            }\n\n            #expect {\n                try create()\n            } throws: { error in\n                let error = try #require(error as? SQLite.Errors)\n                return error == .databaseFull\n            }\n        }\n    }\n\n    @Test\n    func maxSizeHandled() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            var configuration = SQLiteBackedCacheConfiguration()\n            configuration.maxSizeInBytes = 1024 * 3\n            configuration.truncateWhenFull = true\n            let cache = SQLiteBackedCache<String>(tableName: \"SQLiteBackedCacheTest\", path: path, configuration: configuration)\n            defer {\n                #expect(throws: Never.self) {\n                    try cache.close()\n                }\n            }\n\n            var keys = [String]()\n            let mockData = try makeMockData(fileSystem: localFileSystem, rootPath: tmpPath, count: 500)\n            try mockData.forEach { key, value in\n                _ = try cache.put(key: key, value: value)\n                keys.append(key)\n            }\n\n            do {\n                let result = try cache.get(key: mockData.first!.key)\n                #expect(result == nil)\n            }\n\n            do {\n                let result = try cache.get(key: keys.last!)\n                #expect(mockData[keys.last!] == result)\n            }\n        }\n    }\n\n    @Test\n    func initialFileCreation() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let paths = [\n                tmpPath.appending(\"foo\", \"test.db\"),\n                // Ensure it works recursively.\n                tmpPath.appending(\"bar\", \"baz\", \"test.db\"),\n            ]\n\n            for path in paths {\n                let cache = SQLiteBackedCache<String>(tableName: \"SQLiteBackedCacheTest\", path: path)\n                // Put an entry to ensure the file is created.\n                #expect(throws: Never.self) {\n                    try cache.put(key: \"foo\", value: \"bar\")\n                }\n                #expect(throws: Never.self) {\n                    try cache.close()\n                }\n                #expect(localFileSystem.exists(path), \"expected file to be created at \\(path)\")\n            }\n        }\n    }\n}\n\nprivate func makeMockData(fileSystem: FileSystem, rootPath: AbsolutePath, count: Int = Int.random(in: 50 ..< 100)) throws -> [String: String] {\n    var data = [String: String]()\n    let value = UUID().uuidString\n    for index in 0 ..< count {\n        data[\"\\(index)\"] = \"\\(index) \\(value)\"\n    }\n    return data\n}\n"
  },
  {
    "path": "Tests/BasicsTests/SandboxTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport _InternalTestSupport\nimport XCTest\n\n#if canImport(Darwin)\nimport Darwin\n#endif\n\nfinal class SandboxTest: XCTestCase {\n    func testSandboxOnAllPlatforms() throws {\n        try withTemporaryDirectory { path in\n#if os(Windows)\n            let command = try Sandbox.apply(command: [\"tar.exe\", \"-h\"], strictness: .default, writableDirectories: [])\n#else\n            let command = try Sandbox.apply(command: [\"echo\", \"0\"], strictness: .default, writableDirectories: [])\n#endif\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: command))\n        }\n    }\n    \n#if canImport(Darwin)\n    // _CS_DARWIN_USER_CACHE_DIR is only on Darwin, will fail to compile on other platforms.\n    func testUniformTypeIdentifiers() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        let testProgram = \"\"\"\n        import Foundation\n\n        let file = URL(fileURLWithPath:\"\\(#file)\", isDirectory:false)\n        guard let resourceValues = try? file.resourceValues(forKeys: [.contentTypeKey]) else {\n            fputs(\"Failed to get content type/type identifier for '\\(#file)'\", stderr)\n            exit(EXIT_FAILURE)\n        }\n        \"\"\"\n        let cacheDirectory = String(unsafeUninitializedCapacity: Int(PATH_MAX)) { buffer in\n            return confstr(_CS_DARWIN_USER_CACHE_DIR, buffer.baseAddress, Int(PATH_MAX))\n        }\n        let command = try Sandbox.apply(command: [\"swift\", \"-\"], strictness: .writableTemporaryDirectory, writableDirectories: [try AbsolutePath(validating: cacheDirectory)])\n        let process = AsyncProcess(arguments: command)\n        let stdin = try process.launch()\n        stdin.write(sequence: testProgram.utf8)\n        try stdin.close()\n        let processResult = try process.waitUntilExit()\n        XCTAssertEqual(processResult.exitStatus, .terminated(code: 0), (try? processResult.utf8stderrOutput()) ?? \"\")\n    }\n#endif\n\n    func testNetworkNotAllowed() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        let command = try Sandbox.apply(command: [\"ping\", \"-t\", \"1\", \"localhost\"], strictness: .default, writableDirectories: [])\n\n        XCTAssertThrowsError(try AsyncProcess.checkNonZeroExit(arguments: command)) { error in\n            guard case AsyncProcessResult.Error.nonZeroExit(let result) = error else {\n                return XCTFail(\"invalid error \\(error)\")\n            }\n            XCTAssertMatch(try! result.utf8stderrOutput(), .contains(\"Operation not permitted\"))\n        }\n    }\n\n    func testWritableAllowed() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        try withTemporaryDirectory { path in\n            let command = try Sandbox.apply(command: [\"touch\", path.appending(component: UUID().uuidString).pathString], strictness: .default, writableDirectories: [path])\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: command))\n        }\n    }\n\n    func testWritableNotAllowed() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        try withTemporaryDirectory { path in\n            let command = try Sandbox.apply(command: [\"touch\", path.appending(component: UUID().uuidString).pathString], strictness: .default, writableDirectories: [])\n            XCTAssertThrowsError(try AsyncProcess.checkNonZeroExit(arguments: command)) { error in\n                guard case AsyncProcessResult.Error.nonZeroExit(let result) = error else {\n                    return XCTFail(\"invalid error \\(error)\")\n                }\n                XCTAssertMatch(try! result.utf8stderrOutput(), .contains(\"Operation not permitted\"))\n            }\n        }\n    }\n\n    func testRemoveNotAllowed() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        try withTemporaryDirectory { path in\n            let file = path.appending(component: UUID().uuidString)\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: [\"touch\", file.pathString]))\n\n            let command = try Sandbox.apply(command: [\"rm\", file.pathString], strictness: .default, writableDirectories: [])\n            XCTAssertThrowsError(try AsyncProcess.checkNonZeroExit(arguments: command)) { error in\n                guard case AsyncProcessResult.Error.nonZeroExit(let result) = error else {\n                    return XCTFail(\"invalid error \\(error)\")\n                }\n                XCTAssertMatch(try! result.utf8stderrOutput(), .contains(\"Operation not permitted\"))\n            }\n        }\n    }\n\n    // FIXME: rdar://75707545 this should not be allowed outside very specific read locations\n    func testReadAllowed() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        try withTemporaryDirectory { path in\n            let file = path.appending(component: UUID().uuidString)\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: [\"touch\", file.pathString]))\n\n            let command = try Sandbox.apply(command: [\"cat\", file.pathString], strictness: .default, writableDirectories: [])\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: command))\n        }\n    }\n\n    // FIXME: rdar://75707545 this should not be allowed outside very specific programs\n    func testExecuteAllowed() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        try withTemporaryDirectory { path in\n            let file = path.appending(component: UUID().uuidString)\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: [\"touch\", file.pathString]))\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: [\"chmod\", \"+x\", file.pathString]))\n\n            let command = try Sandbox.apply(command: [file.pathString], strictness: .default, writableDirectories: [])\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: command))\n        }\n    }\n\n    func testWritingToTemporaryDirectoryAllowed() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        // Try writing to the per-user temporary directory, which is under /var/folders/.../TemporaryItems.\n        let tmpFile1 = NSTemporaryDirectory() + \"/\" + UUID().uuidString\n        let command1 = try Sandbox.apply(command: [\"touch\", tmpFile1], strictness: .writableTemporaryDirectory)\n        XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: command1))\n        try? FileManager.default.removeItem(atPath: tmpFile1)\n\n        let tmpFile2 = \"/tmp\" + \"/\" + UUID().uuidString\n        let command2 = try Sandbox.apply(command: [\"touch\", tmpFile2], strictness: .writableTemporaryDirectory)\n        XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: command2))\n        try? FileManager.default.removeItem(atPath: tmpFile2)\n    }\n\n    func testWritingToReadOnlyInsideWritableNotAllowed() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"sandboxing is only supported on macOS\")\n        #endif\n\n        try withTemporaryDirectory { tmpDir in\n            // Check that we can write into the temporary directory, but not into a read-only directory underneath it.\n            let writableDir = tmpDir.appending(\"ShouldBeWritable\")\n            try localFileSystem.createDirectory(writableDir)\n            let allowedCommand = try Sandbox.apply(command: [\"touch\", writableDir.pathString], strictness: .default, writableDirectories: [writableDir])\n            XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: allowedCommand))\n\n            // Check that we cannot write into a read-only directory inside a writable temporary directory.\n            let readOnlyDir = writableDir.appending(\"ShouldBeReadOnly\")\n            try localFileSystem.createDirectory(readOnlyDir)\n            let deniedCommand = try Sandbox.apply(command: [\"touch\", readOnlyDir.pathString], strictness: .writableTemporaryDirectory, readOnlyDirectories: [readOnlyDir])\n            XCTAssertThrowsError(try AsyncProcess.checkNonZeroExit(arguments: deniedCommand)) { error in\n                guard case AsyncProcessResult.Error.nonZeroExit(let result) = error else {\n                    return XCTFail(\"invalid error \\(error)\")\n                }\n                XCTAssertMatch(try! result.utf8stderrOutput(), .contains(\"Operation not permitted\"))\n            }\n        }\n    }\n\n    func testWritingToWritableInsideReadOnlyAllowed() throws {\n         #if !os(macOS)\n         try XCTSkipIf(true, \"sandboxing is only supported on macOS\")\n         #endif\n\n         try withTemporaryDirectory { tmpDir in\n             // Check that we cannot write into a read-only directory, but into a writable directory underneath it.\n             let readOnlyDir = tmpDir.appending(\"ShouldBeReadOnly\")\n             try localFileSystem.createDirectory(readOnlyDir)\n             let deniedCommand = try Sandbox.apply(command: [\"touch\", readOnlyDir.pathString], strictness: .writableTemporaryDirectory, readOnlyDirectories: [readOnlyDir])\n             XCTAssertThrowsError(try AsyncProcess.checkNonZeroExit(arguments: deniedCommand)) { error in\n                 guard case AsyncProcessResult.Error.nonZeroExit(let result) = error else {\n                     return XCTFail(\"invalid error \\(error)\")\n                 }\n                 XCTAssertMatch(try! result.utf8stderrOutput(), .contains(\"Operation not permitted\"))\n             }\n\n             // Check that we can write into a writable directory underneath it.\n             let writableDir = readOnlyDir.appending(\"ShouldBeWritable\")\n             try localFileSystem.createDirectory(writableDir)\n             let allowedCommand = try Sandbox.apply(command: [\"touch\", writableDir.pathString], strictness: .default, writableDirectories:[writableDir], readOnlyDirectories: [readOnlyDir])\n             XCTAssertNoThrow(try AsyncProcess.checkNonZeroExit(arguments: allowedCommand))\n         }\n     }\n    \n    func testDeterministicOrdering() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        try withTemporaryDirectory { path in\n            // Ensure the contents of the produced sandbox directory is deterministic, in order\n            // to avoid spurious incremental rebuilds. This test is not guaranteed to catch rare\n            // cases of nondeterminism, but in practice guards well against past issues in this area.\n            let writeable1 = path.appending(component: \"w1\")\n            let writeable2 = path.appending(component: \"w2\")\n            let writeable3 = path.appending(component: \"w3\")\n            let writeable4 = path.appending(component: \"w4\")\n            \n            let readable1 = path.appending(component: \"r1\")\n            let readable2 = path.appending(component: \"r2\")\n            let readable3 = path.appending(component: \"r3\")\n            let readable4 = path.appending(component: \"r4\")\n            \n            let command = try Sandbox.apply(command: [\"echo\", \"hello\"], strictness: .default, writableDirectories: [writeable1, writeable2, writeable3, writeable4], readOnlyDirectories: [readable1, readable2, readable3, readable4], fileSystem: localFileSystem)\n            for _ in 0..<10 {\n                let newCommand = try Sandbox.apply(command: [\"echo\", \"hello\"], strictness: .default, writableDirectories: [writeable1, writeable2, writeable3, writeable4], readOnlyDirectories: [readable1, readable2, readable3, readable4],fileSystem: localFileSystem)\n                XCTAssertEqual(command, newCommand)\n            }\n        }\n    }\n}\n\nextension Sandbox {\n    public static func apply(\n        command: [String],\n        strictness: Strictness = .default,\n        writableDirectories: [AbsolutePath] = [],\n        readOnlyDirectories: [AbsolutePath] = [],\n        allowNetworkConnections: [SandboxNetworkPermission] = [],\n        fileSystem: FileSystem = InMemoryFileSystem()\n    ) throws -> [String] {\n        return try self.apply(\n            command: command,\n            fileSystem: fileSystem,\n            strictness: strictness,\n            writableDirectories: writableDirectories,\n            readOnlyDirectories: readOnlyDirectories,\n            allowNetworkConnections: allowNetworkConnections\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/Serialization/SerializedJSONTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport XCTest\nimport _InternalTestSupport // for XCTSkipOnWindows\n\nfinal class SerializedJSONTests: XCTestCase {\n    func testPathInterpolation() throws {\n        var path = try AbsolutePath(validating: #\"/test\\backslashes\"#)\n        var json: SerializedJSON = \"\\(path)\"\n\n#if os(Windows)\n        XCTAssertEqual(json.underlying, #\"\\\\test\\\\backslashes\"#)\n#else\n        XCTAssertEqual(json.underlying, #\"/test\\\\backslashes\"#)\n#endif\n\n        #if os(Windows)\n        path = try AbsolutePath(validating: #\"\\??\\Volumes{b79de17a-a1ed-4c58-a353-731b7c4885a6}\\\\\"#)\n        json = \"\\(path)\"\n\n        XCTAssertEqual(json.underlying, #\"\\\\??\\\\Volumes{b79de17a-a1ed-4c58-a353-731b7c4885a6}\"#)\n        #endif\n    }\n\n    func testPathInterpolationFailsOnWindows() throws {\n#if os(Windows)\n        var path = try AbsolutePath(validating: #\"\\\\?\\C:\\Users\"#)\n        var json: SerializedJSON = \"\\(path)\"\n\n        XCTAssertEqual(json.underlying, #\"\\\\\\\\?\\\\C:\\\\Users\"#)\n\n        path = try AbsolutePath(validating: #\"\\\\.\\UNC\\server\\share\\\"#)\n        json = \"\\(path)\"\n\n        XCTAssertEqual(json.underlying, #\"\\\\\\\\.\\\\UNC\\\\server\\\\share\"#)\n#endif\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/StringExtensionsTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Testing\n\nstruct StringExtensionsTests {\n    @Test\n    func sHA256Checksum() {\n        let string = \"abc\"\n        #expect(Array(string.utf8) == [0x61, 0x62, 0x63])\n\n        // See https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/examples/sha_all.pdf\n        #expect(string.sha256Checksum == \"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\")\n    }\n\n    @Test\n    func dropPrefix() {\n        do {\n            let string = \"prefixSuffix\"\n            #expect(string.spm_dropPrefix(\"prefix\") == \"Suffix\")\n        }\n        do {\n            let string = \"prefixSuffix\"\n            #expect(string.spm_dropPrefix(\"notMyPrefix\") == string)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/TripleTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport Testing\n\nstruct TripleTests {\n    @Test(\n        \"Triple is Apple and is Darwin\",\n        arguments: [\n            (tripleName: \"x86_64-pc-linux-gnu\", isApple: false, isDarwin: false),\n            (tripleName: \"x86_64-pc-linux-musl\", isApple: false, isDarwin: false),\n            (tripleName: \"powerpc-bgp-linux\", isApple: false, isDarwin: false),\n            (tripleName: \"arm-none-none-eabi\", isApple: false, isDarwin: false),\n            (tripleName: \"arm-none-linux-musleabi\", isApple: false, isDarwin: false),\n            (tripleName: \"wasm32-unknown-wasi\", isApple: false, isDarwin: false),\n            (tripleName: \"riscv64-unknown-linux\", isApple: false, isDarwin: false),\n            (tripleName: \"mips-mti-linux-gnu\", isApple: false, isDarwin: false),\n            (tripleName: \"mipsel-img-linux-gnu\", isApple: false, isDarwin: false),\n            (tripleName: \"mips64-mti-linux-gnu\", isApple: false, isDarwin: false),\n            (tripleName: \"mips64el-img-linux-gnu\", isApple: false, isDarwin: false),\n            (tripleName: \"mips64el-img-linux-gnuabin32\", isApple: false, isDarwin: false),\n            (tripleName: \"mips64-unknown-linux-gnuabi64\", isApple: false, isDarwin: false),\n            (tripleName: \"mips64-unknown-linux-gnuabin32\", isApple: false, isDarwin: false),\n            (tripleName: \"mipsel-unknown-linux-gnu\", isApple: false, isDarwin: false),\n            (tripleName: \"mips-unknown-linux-gnu\", isApple: false, isDarwin: false),\n            (tripleName: \"arm-oe-linux-gnueabi\", isApple: false, isDarwin: false),\n            (tripleName: \"aarch64-oe-linux\", isApple: false, isDarwin: false),\n            (tripleName: \"armv7em-unknown-none-macho\", isApple: false, isDarwin: false),\n            (tripleName: \"armv7em-apple-none-macho\", isApple: true, isDarwin: false),\n            (tripleName: \"armv7em-apple-none\", isApple: true, isDarwin: false),\n            (tripleName: \"aarch64-apple-macosx\", isApple: true, isDarwin: true),\n            (tripleName: \"x86_64-apple-macosx\", isApple: true, isDarwin: true),\n            (tripleName: \"x86_64-apple-macosx10.15\", isApple: true, isDarwin: true),\n            (tripleName: \"x86_64h-apple-darwin\", isApple: true, isDarwin: true),\n            (tripleName: \"i686-pc-windows-msvc\", isApple: false, isDarwin: false),\n            (tripleName: \"i686-pc-windows-gnu\", isApple: false, isDarwin: false),\n            (tripleName: \"i686-pc-windows-cygnus\", isApple: false, isDarwin: false),\n        ],\n    )\n    func isAppleIsDarwin(_ tripleName: String, _ isApple: Bool, _ isDarwin: Bool) throws {\n        let triple = try Triple(tripleName)\n        #expect(\n            isApple == triple.isApple(),\n            \"\"\"\n            Expected triple '\\(triple.tripleString)' \\\n            \\(isApple ? \"\" : \" not\") to be an Apple triple.\n            \"\"\",\n        )\n        #expect(\n            isDarwin == triple.isDarwin(),\n            \"\"\"\n            Expected triple '\\(triple.tripleString)' \\\n            \\(isDarwin ? \"\" : \" not\") to be a Darwin triple.\n            \"\"\",\n        )\n    }\n\n    @Test\n    func description() throws {\n        let triple = try Triple(\"x86_64-pc-linux-gnu\")\n        #expect(\"foo \\(triple) bar\" == \"foo x86_64-pc-linux-gnu bar\")\n    }\n\n    @Test(\n        \"Triple String for Platform Version\",\n        arguments: [\n            (\n                tripleName: \"x86_64-apple-macosx\",\n                version: \"\",\n                expectedTriple: \"x86_64-apple-macosx\",\n            ),\n            (\n                tripleName: \"x86_64-apple-macosx\",\n                version: \"13.0\",\n                expectedTriple: \"x86_64-apple-macosx13.0\",\n            ),\n            (\n                tripleName: \"armv7em-apple-macosx10.12\",\n                version: \"\",\n                expectedTriple: \"armv7em-apple-macosx\",\n            ),\n            (\n                tripleName: \"armv7em-apple-macosx10.12\",\n                version: \"13.0\",\n                expectedTriple: \"armv7em-apple-macosx13.0\",\n            ),\n            (\n                tripleName: \"powerpc-apple-macos\",\n                version: \"\",\n                expectedTriple: \"powerpc-apple-macos\",\n            ),\n            (\n                tripleName: \"powerpc-apple-macos\",\n                version: \"13.0\",\n                expectedTriple: \"powerpc-apple-macos13.0\",\n            ),\n            (\n                tripleName: \"i686-apple-macos10.12.0\",\n                version: \"\",\n                expectedTriple: \"i686-apple-macos\",\n            ),\n            (\n                tripleName: \"i686-apple-macos10.12.0\",\n                version: \"13.0\",\n                expectedTriple: \"i686-apple-macos13.0\",\n            ),\n            (\n                tripleName: \"riscv64-apple-darwin\",\n                version: \"\",\n                expectedTriple: \"riscv64-apple-darwin\",\n            ),\n            (\n                tripleName: \"riscv64-apple-darwin\",\n                version: \"22\",\n                expectedTriple: \"riscv64-apple-darwin22\",\n            ),\n            (\n                tripleName: \"mips-apple-darwin19\",\n                version: \"\",\n                expectedTriple: \"mips-apple-darwin\",\n            ),\n            (\n                tripleName: \"mips-apple-darwin19\",\n                version: \"22\",\n                expectedTriple: \"mips-apple-darwin22\",\n            ),\n            (\n                tripleName: \"arm64-apple-ios-simulator\",\n                version: \"\",\n                expectedTriple: \"arm64-apple-ios-simulator\",\n            ),\n            (\n                tripleName: \"arm64-apple-ios-simulator\",\n                version: \"13.0\",\n                expectedTriple: \"arm64-apple-ios13.0-simulator\",\n            ),\n            (\n                tripleName: \"arm64-apple-ios12-simulator\",\n                version: \"\",\n                expectedTriple: \"arm64-apple-ios-simulator\",\n            ),\n            (\n                tripleName: \"arm64-apple-ios12-simulator\",\n                version: \"13.0\",\n                expectedTriple: \"arm64-apple-ios13.0-simulator\",\n            ),\n        ]\n    )\n    func tripleStringForPlatformVersion(\n        tripleName: String, version: String, expectedTriple: String\n    ) throws {\n        let triple = try Triple(tripleName)\n        let actualTriple = triple.tripleString(forPlatformVersion: version)\n        #expect(\n            actualTriple == expectedTriple,\n            \"\"\"\n            Actual triple '\\(actualTriple)' did not match expected triple \\\n            '\\(expectedTriple)' for platform version '\\(version)'.\n            \"\"\",\n        )\n\n    }\n\n    struct DataKnownTripleParsing {\n        var tripleName: String\n        var expectedArch: Triple.Arch?\n        var expectedSubArch: Triple.SubArch?\n        var expectedVendor: Triple.Vendor?\n        var expectedOs: Triple.OS?\n        var expectedEnvironment: Triple.Environment?\n        var expectedObjectFormat: Triple.ObjectFormat?\n    }\n    @Test(\n        \"Known Triple Parsing\",\n        arguments: [\n            DataKnownTripleParsing(\n                tripleName: \"armv7em-apple-none-eabihf-macho\",\n                expectedArch: .arm,\n                expectedSubArch : .arm(.v7em),\n                expectedVendor: .apple,\n                expectedOs: .noneOS,\n                expectedEnvironment: .eabihf,\n                expectedObjectFormat: .macho\n            ),\n            DataKnownTripleParsing(\n                tripleName: \"x86_64-apple-macosx\",\n                expectedArch: .x86_64,\n                expectedSubArch: nil,\n                expectedVendor: .apple,\n                expectedOs: .macosx,\n                expectedEnvironment: nil,\n                expectedObjectFormat: .macho\n            ),\n            DataKnownTripleParsing(\n                tripleName: \"x86_64-unknown-linux-gnu\",\n                expectedArch: .x86_64,\n                expectedSubArch: nil,\n                expectedVendor: nil,\n                expectedOs: .linux,\n                expectedEnvironment: .gnu,\n                expectedObjectFormat: .elf\n            ),\n            DataKnownTripleParsing(\n                tripleName: \"aarch64-unknown-linux-gnu\",\n                expectedArch: .aarch64,\n                expectedSubArch: nil,\n                expectedVendor: nil,\n                expectedOs: .linux,\n                expectedEnvironment: .gnu,\n                expectedObjectFormat: .elf\n            ),\n            DataKnownTripleParsing(\n                tripleName: \"aarch64-unknown-linux-android\",\n                expectedArch: .aarch64,\n                expectedSubArch: nil,\n                expectedVendor: nil,\n                expectedOs: .linux,\n                expectedEnvironment: .android,\n                expectedObjectFormat: .elf\n            ),\n            DataKnownTripleParsing(\n                tripleName: \"x86_64-unknown-windows-msvc\",\n                expectedArch: .x86_64,\n                expectedSubArch: nil,\n                expectedVendor: nil,\n                expectedOs: .win32,\n                expectedEnvironment: .msvc,\n                expectedObjectFormat: .coff\n            ),\n            DataKnownTripleParsing(\n                tripleName: \"wasm32-unknown-wasi\",\n                expectedArch: .wasm32,\n                expectedSubArch: nil,\n                expectedVendor: nil,\n                expectedOs: .wasi,\n                expectedEnvironment: nil,\n                expectedObjectFormat: .wasm\n            )\n        ]\n    )\n    func knownTripleParsing(\n        data: DataKnownTripleParsing,\n    ) throws {\n        let triple = try Triple(data.tripleName)\n        #expect(triple.arch == data.expectedArch, \"Actual arch not as expected\")\n        #expect(triple.subArch == data.expectedSubArch, \"Actual subarch is not as expected\")\n        #expect(triple.vendor == data.expectedVendor, \"Actual Vendor is not as expected\")\n        #expect(triple.os == data.expectedOs, \"Actual OS is not as expcted\")\n        #expect(triple.environment == data.expectedEnvironment, \"Actual environment is not as expected\")\n        #expect(triple.objectFormat == data.expectedObjectFormat, \"Actual object format is not as expected\")\n    }\n\n    @Test\n    func triple() throws {\n        let linux = try Triple(\"x86_64-unknown-linux-gnu\")\n        #expect(linux.os == .linux)\n        #expect(linux.osVersion == Triple.Version.zero)\n        #expect(linux.environment == .gnu)\n\n        let macos = try Triple(\"x86_64-apple-macosx10.15\")\n        #expect(macos.osVersion == .init(parse: \"10.15\"))\n        let newVersion = \"10.12\"\n        let tripleString = macos.tripleString(forPlatformVersion: newVersion)\n        #expect(tripleString == \"x86_64-apple-macosx10.12\")\n        let macosNoX = try Triple(\"x86_64-apple-macos12.2\")\n        #expect(macosNoX.os == .macosx)\n        #expect(macosNoX.osVersion == .init(parse: \"12.2\"))\n\n        let android = try Triple(\"aarch64-unknown-linux-android24\")\n        #expect(android.os == .linux)\n        #expect(android.environment == .android)\n\n        let linuxWithABIVersion = try Triple(\"x86_64-unknown-linux-gnu42\")\n        #expect(linuxWithABIVersion.environment == .gnu)\n    }\n\n    @Test\n    func equality() throws {\n        let macOSTriple = try Triple(\"arm64-apple-macos\")\n        let macOSXTriple = try Triple(\"arm64-apple-macosx\")\n        #expect(macOSTriple == macOSXTriple)\n\n        let intelMacOSTriple = try Triple(\"x86_64-apple-macos\")\n        #expect(macOSTriple != intelMacOSTriple)\n\n        let linuxWithoutGNUABI = try Triple(\"x86_64-unknown-linux\")\n        let linuxWithGNUABI = try Triple(\"x86_64-unknown-linux-gnu\")\n        #expect(linuxWithoutGNUABI != linuxWithGNUABI)\n    }\n\n    @Test\n    func WASI() throws {\n        let wasi = try Triple(\"wasm32-unknown-wasi\")\n\n        // WASI dynamic libraries are only experimental,\n        // but SwiftPM requires this property not to crash.\n        _ = wasi.dynamicLibraryExtension\n    }\n\n    @Test(\n        \"Test dynamicLibraryExtesion attribute on Triple returns expected value\",\n        arguments: [\n            (tripleName: \"armv7em-unknown-none-coff\", expected: \".coff\"),\n            (tripleName: \"armv7em-unknown-none-elf\", expected: \".elf\"),\n            (tripleName: \"armv7em-unknown-none-macho\", expected: \".macho\"),\n            (tripleName: \"armv7em-unknown-none-wasm\", expected: \".wasm\"),\n            (tripleName: \"armv7em-unknown-none-xcoff\", expected: \".xcoff\"),\n            (tripleName: \"wasm32-unknown-wasi\", expected: \".wasm\"),  // Added by bkhouri\n        ],\n    )\n    func noneOSDynamicLibrary(tripleName: String, expected: String) throws {\n        // Dynamic libraries aren't actually supported for OS none, but swiftpm\n        // wants an extension to avoid crashing during build planning.\n        let triple = try Triple(tripleName)\n        #expect(triple.dynamicLibraryExtension == expected)\n    }\n\n    @Test(\n        \"isRuntimeCompatibleWith returns expected value\",\n        arguments: [\n            (\n                firstTripleName: \"x86_64-apple-macosx\",\n                secondTripleName: \"x86_64-apple-macosx\",\n                isCompatible: true,\n            ),\n            (\n                firstTripleName: \"x86_64-unknown-linux\",\n                secondTripleName: \"x86_64-unknown-linux\",\n                isCompatible: true,\n            ),\n            (\n                firstTripleName: \"x86_64-apple-macosx\",\n                secondTripleName: \"x86_64-apple-linux\",\n                isCompatible: false,\n            ),\n            (\n                firstTripleName: \"x86_64-apple-macosx14.0\",\n                secondTripleName: \"x86_64-apple-macosx13.0\",\n                isCompatible: true,\n            ),\n        ],\n    )\n    func isRuntimeCompatibleWith(\n        firstTripleName: String, secondTripleName: String, isCompatible: Bool,\n    ) throws {\n        let triple = try Triple(firstTripleName)\n        let other = try Triple(secondTripleName)\n        #expect(triple.isRuntimeCompatible(with: other) == isCompatible)\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/URLSessionHTTPClientTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport Foundation\n#if canImport(FoundationNetworking)\n// TODO: this brings OpenSSL dependency` on Linux\n// need to decide how to best deal with that\nimport FoundationNetworking\n#endif\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCBasic.ByteString\nimport enum TSCBasic.FileMode\nimport struct TSCBasic.FileSystemError\n\nfinal class URLSessionHTTPClientTest: XCTestCase {\n    func testHead() {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"HEAD\", url) { request in\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.head(url, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus)\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody)\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1.0)\n    }\n\n    func testGet() {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"GET\", url) { request in\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.get(url, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus)\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody)\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1.0)\n    }\n\n    func testPost() {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestBody = Data(UUID().uuidString.utf8)\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"POST\", url) { request in\n            // FIXME:\n            XCTAssertEqual(request.httpBody, requestBody)\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.post(url, body: requestBody, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus)\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody)\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1.0)\n    }\n\n    func testPut() {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestBody = Data(UUID().uuidString.utf8)\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"PUT\", url) { request in\n            XCTAssertEqual(request.httpBody, requestBody)\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.put(url, body: requestBody, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus)\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody)\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1.0)\n    }\n\n    func testDelete() {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        let url = URL(\"http://test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"DELETE\", url) { request in\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let promise = XCTestExpectation(description: \"completed\")\n        httpClient.delete(url, headers: requestHeaders) { result in\n            switch result {\n            case .failure(let error):\n                XCTFail(\"unexpected error \\(error)\")\n            case .success(let response):\n                XCTAssertEqual(response.statusCode, responseStatus)\n                self.assertResponseHeaders(response.headers, expected: responseHeaders)\n                XCTAssertEqual(response.body, responseBody)\n            }\n            promise.fulfill()\n        }\n\n        wait(for: [promise], timeout: 1.0)\n    }\n\n    private func assertRequestHeaders(_ headers: [String: String]?, expected: HTTPClientHeaders) {\n        let headers = (headers?.filter { $0.key != \"User-Agent\" && $0.key != \"Content-Length\" } ?? [])\n            .flatMap { HTTPClientHeaders($0.map { .init(name: $0.key, value: $0.value) }) } ?? .init()\n        XCTAssertEqual(headers, expected)\n    }\n\n    private func assertResponseHeaders(_ headers: HTTPClientHeaders, expected: [String: String]) {\n        let expected = HTTPClientHeaders(expected.map { .init(name: $0.key, value: $0.value) })\n        XCTAssertEqual(headers, expected)\n    }\n\n    // MARK: - download\n\n\n    func testDownloadSuccess() throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        try testWithTemporaryDirectory { temporaryDirectory in\n            let didStartLoadingExpectation = XCTestExpectation(description: \"didStartLoading\")\n            let progress50Expectation = XCTestExpectation(description: \"progress50\")\n            let progress100Expectation = XCTestExpectation(description: \"progress100\")\n            let completionExpectation = XCTestExpectation(description: \"completion\")\n\n            let url = URL(\"https://downloader-tests.com/testBasics.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            let request = LegacyHTTPClient.Request.download(url: url, fileSystem: localFileSystem, destination: destination)\n            httpClient.execute(\n                request,\n                progress: { bytesDownloaded, totalBytesToDownload in\n                    switch (bytesDownloaded, totalBytesToDownload) {\n                    case (512, 1024):\n                        progress50Expectation.fulfill()\n                    case (1024, 1024):\n                        progress100Expectation.fulfill()\n                    default:\n                        XCTFail(\"unexpected progress\")\n                    }\n                },\n                completion: { result in\n                    switch result {\n                    case .success:\n                        XCTAssertFileExists(destination)\n                        let bytes = ByteString(Array(repeating: 0xBE, count: 512) + Array(repeating: 0xEF, count: 512))\n                        XCTAssertEqual(try! localFileSystem.readFileContents(destination), bytes)\n                    case .failure(let error):\n                        XCTFail(\"\\(error)\")\n                    }\n                    completionExpectation.fulfill()\n                }\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                didStartLoadingExpectation.fulfill()\n            }\n            wait(for: [didStartLoadingExpectation], timeout: 1.0)\n\n            let urlRequest = URLRequest(request)\n            MockURLProtocol.sendData(Data(repeating: 0xBE, count: 512), for: urlRequest)\n            wait(for: [progress50Expectation], timeout: 1.0)\n            MockURLProtocol.sendData(Data(repeating: 0xEF, count: 512), for: urlRequest)\n            wait(for: [progress100Expectation], timeout: 1.0)\n            MockURLProtocol.sendCompletion(for: urlRequest)\n            wait(for: [completionExpectation], timeout: 1.0)\n        }\n    }\n\n    func testDownloadAuthenticatedSuccess() throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let netrcContent = \"machine protected.downloader-tests.com login anonymous password qwerty\"\n        let netrc = try NetrcAuthorizationWrapper(underlying: NetrcParser.parse(netrcContent))\n        let authData = Data(\"anonymous:qwerty\".utf8)\n        let testAuthHeader = \"Basic \\(authData.base64EncodedString())\"\n\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        try testWithTemporaryDirectory { temporaryDirectory in\n            let didStartLoadingExpectation = XCTestExpectation(description: \"didStartLoading\")\n            let progress50Expectation = XCTestExpectation(description: \"progress50\")\n            let progress100Expectation = XCTestExpectation(description: \"progress100\")\n            let completionExpectation = XCTestExpectation(description: \"completion\")\n\n            let url = URL(\"https://protected.downloader-tests.com/testBasics.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            var request = LegacyHTTPClient.Request.download(url: url, fileSystem: localFileSystem, destination: destination)\n            request.options.authorizationProvider = netrc.httpAuthorizationHeader(for:)\n\n            httpClient.execute(\n                request,\n                progress: { bytesDownloaded, totalBytesToDownload in\n                    switch (bytesDownloaded, totalBytesToDownload) {\n                    case (512, 1024):\n                        progress50Expectation.fulfill()\n                    case (1024, 1024):\n                        progress100Expectation.fulfill()\n                    default:\n                        XCTFail(\"unexpected progress\")\n                    }\n                },\n                completion: { result in\n                    switch result {\n                    case .success:\n                        XCTAssertFileExists(destination)\n                        let bytes = ByteString(Array(repeating: 0xBE, count: 512) + Array(repeating: 0xEF, count: 512))\n                        XCTAssertEqual(try! localFileSystem.readFileContents(destination), bytes)\n                    case .failure(let error):\n                        XCTFail(\"\\(error)\")\n                    }\n                    completionExpectation.fulfill()\n                }\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                XCTAssertEqual(request.allHTTPHeaderFields?[\"Authorization\"], testAuthHeader)\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                didStartLoadingExpectation.fulfill()\n            }\n            wait(for: [didStartLoadingExpectation], timeout: 1.0)\n\n            let urlRequest = URLRequest(request)\n            MockURLProtocol.sendData(Data(repeating: 0xBE, count: 512), for: urlRequest)\n            wait(for: [progress50Expectation], timeout: 1.0)\n            MockURLProtocol.sendData(Data(repeating: 0xEF, count: 512), for: urlRequest)\n            wait(for: [progress100Expectation], timeout: 1.0)\n            MockURLProtocol.sendCompletion(for: urlRequest)\n            wait(for: [completionExpectation], timeout: 1.0)\n        }\n    }\n\n    func testDownloadDefaultAuthenticationSuccess() throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        try XCTSkipIfPlatformCI()\n        let netrcContent = \"default login default password default\"\n        let netrc = try NetrcAuthorizationWrapper(underlying: NetrcParser.parse(netrcContent))\n        let authData = Data(\"default:default\".utf8)\n        let testAuthHeader = \"Basic \\(authData.base64EncodedString())\"\n\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        try testWithTemporaryDirectory { temporaryDirectory in\n            let didStartLoadingExpectation = XCTestExpectation(description: \"didStartLoading\")\n            let progress50Expectation = XCTestExpectation(description: \"progress50\")\n            let progress100Expectation = XCTestExpectation(description: \"progress100\")\n            let completionExpectation = XCTestExpectation(description: \"completion\")\n\n            let url = URL(\"https://restricted.downloader-tests.com/testBasics.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            var request = LegacyHTTPClient.Request.download(url: url, fileSystem: localFileSystem, destination: destination)\n            request.options.authorizationProvider = netrc.httpAuthorizationHeader(for:)\n\n            httpClient.execute(\n                request,\n                progress: { bytesDownloaded, totalBytesToDownload in\n                    switch (bytesDownloaded, totalBytesToDownload) {\n                    case (512, 1024):\n                        progress50Expectation.fulfill()\n                    case (1024, 1024):\n                        progress100Expectation.fulfill()\n                    default:\n                        XCTFail(\"unexpected progress\")\n                    }\n                },\n                completion: { result in\n                    switch result {\n                    case .success:\n                        XCTAssertFileExists(destination)\n                        let bytes = ByteString(Array(repeating: 0xBE, count: 512) + Array(repeating: 0xEF, count: 512))\n                        XCTAssertEqual(try! localFileSystem.readFileContents(destination), bytes)\n                    case .failure(let error):\n                        XCTFail(\"\\(error)\")\n                    }\n                    completionExpectation.fulfill()\n                }\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                XCTAssertEqual(request.allHTTPHeaderFields?[\"Authorization\"], testAuthHeader)\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                didStartLoadingExpectation.fulfill()\n            }\n            wait(for: [didStartLoadingExpectation], timeout: 1.0)\n\n            let urlRequest = URLRequest(request)\n            MockURLProtocol.sendData(Data(repeating: 0xBE, count: 512), for: urlRequest)\n            wait(for: [progress50Expectation], timeout: 1.0)\n            MockURLProtocol.sendData(Data(repeating: 0xEF, count: 512), for: urlRequest)\n            wait(for: [progress100Expectation], timeout: 1.0)\n            MockURLProtocol.sendCompletion(for: urlRequest)\n            wait(for: [completionExpectation], timeout: 1.0)\n        }\n    }\n\n    func testDownloadClientError() throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        try testWithTemporaryDirectory { temporaryDirectory in\n            let didStartLoadingExpectation = XCTestExpectation(description: \"didStartLoading\")\n            let progress50Expectation = XCTestExpectation(description: \"progress50\")\n            let completionExpectation = XCTestExpectation(description: \"completion\")\n\n            let clientError = StringError(\"boom\")\n            let url = URL(\"https://downloader-tests.com/testClientError.zip\")\n            let request = LegacyHTTPClient.Request.download(url: url, fileSystem: localFileSystem, destination: temporaryDirectory.appending(\"download\"))\n            httpClient.execute(\n                request,\n                progress: { bytesDownloaded, totalBytesToDownload in\n                    switch (bytesDownloaded, totalBytesToDownload) {\n                    case (512, 1024):\n                        progress50Expectation.fulfill()\n                    default:\n                        XCTFail(\"unexpected progress\")\n                    }\n                },\n                completion: { result in\n                    switch result {\n                    case .success:\n                        XCTFail(\"unexpected success\")\n                    case .failure(let error):\n                        XCTAssertEqual(error as? HTTPClientError, HTTPClientError.downloadError(clientError.description))\n                    }\n                    completionExpectation.fulfill()\n                }\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                didStartLoadingExpectation.fulfill()\n            }\n            wait(for: [didStartLoadingExpectation], timeout: 3.0)\n\n            let urlRequest = URLRequest(request)\n            MockURLProtocol.sendData(Data(count: 512), for: urlRequest)\n            wait(for: [progress50Expectation], timeout: 3.0)\n            MockURLProtocol.sendError(clientError, for: urlRequest)\n            wait(for: [completionExpectation], timeout: 3.0)\n        }\n    }\n\n    func testDownloadServerError() throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        try testWithTemporaryDirectory { temporaryDirectory in\n            let didStartLoadingExpectation = XCTestExpectation(description: \"didStartLoading\")\n            let completionExpectation = XCTestExpectation(description: \"completion\")\n\n            let url = URL(\"https://downloader-tests.com/testServerError.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            var request = LegacyHTTPClient.Request.download(url: url, fileSystem: localFileSystem, destination: destination)\n            request.options.validResponseCodes = [200]\n\n            httpClient.execute(\n                request,\n                progress: { _, _ in\n                    XCTFail(\"unexpected progress\")\n                },\n                completion: { result in\n                    switch result {\n                    case .success:\n                        XCTFail(\"unexpected success\")\n                    case .failure(let error):\n                        XCTAssertEqual(error as? HTTPClientError, HTTPClientError.badResponseStatusCode(500))\n                        // Verify that no file was created at the destination for bad response codes\n                        XCTAssertFalse(localFileSystem.exists(destination), \"Destination file should not exist for bad response codes\")\n                    }\n                    completionExpectation.fulfill()\n                }\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                MockURLProtocol.sendResponse(statusCode: 500, for: request)\n                didStartLoadingExpectation.fulfill()\n            }\n            wait(for: [didStartLoadingExpectation], timeout: 1.0)\n\n            MockURLProtocol.sendCompletion(for: URLRequest(request))\n            wait(for: [completionExpectation], timeout: 1.0)\n        }\n    }\n\n    func testDownloadFileSystemError() throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = LegacyHTTPClient(handler: urlSession.execute)\n\n        try testWithTemporaryDirectory { temporaryDirectory in\n            let didStartLoadingExpectation = XCTestExpectation(description: \"didStartLoading\")\n            let completionExpectation = XCTestExpectation(description: \"error\")\n\n            let url = URL(\"https://downloader-tests.com/testFileSystemError.zip\")\n            let request = LegacyHTTPClient.Request.download(url: url, fileSystem: FailingFileSystem(), destination: temporaryDirectory.appending(\"download\"))\n            httpClient.execute(request, progress: { _, _ in }, completion: { result in\n                switch result {\n                case .success:\n                    XCTFail(\"unexpected success\")\n                case .failure(let error):\n                    XCTAssertEqual(error as? FileSystemError, FileSystemError(.unsupported))\n                }\n                completionExpectation.fulfill()\n            })\n\n            MockURLProtocol.onRequest(request) { request in\n                MockURLProtocol.sendResponse(statusCode: 200, for: request)\n                didStartLoadingExpectation.fulfill()\n            }\n            wait(for: [didStartLoadingExpectation], timeout: 1.0)\n\n            let urlRequest = URLRequest(request)\n            MockURLProtocol.sendData(Data([0xDE, 0xAD, 0xBE, 0xEF]), for: urlRequest)\n            MockURLProtocol.sendCompletion(for: urlRequest)\n            wait(for: [completionExpectation], timeout: 1.0)\n        }\n    }\n\n    // FIXME: remove this availability check when back-deployment is available on CI hosts.\n    func testAsyncHead() async throws {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        let url = URL(\"http://async-head-test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"HEAD\", url) { request in\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.execute(.init(method: .head, url: url, headers: requestHeaders))\n\n        XCTAssertEqual(response.statusCode, responseStatus)\n        self.assertResponseHeaders(response.headers, expected: responseHeaders)\n        XCTAssertEqual(response.body, responseBody)\n    }\n\n    func testAsyncGet() async throws {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        let url = URL(\"http://async-get-test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"GET\", url) { request in\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.execute(.init(method: .get, url: url, headers: requestHeaders))\n        XCTAssertEqual(response.statusCode, responseStatus)\n        self.assertResponseHeaders(response.headers, expected: responseHeaders)\n        XCTAssertEqual(response.body, responseBody)\n    }\n\n    func testAsyncPost() async throws {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        let url = URL(\"http://async-post-test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestBody = Data(UUID().uuidString.utf8)\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"POST\", url) { request in\n            // FIXME:\n            XCTAssertEqual(request.httpBody, requestBody)\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.execute(.init(method: .post, url: url, headers: requestHeaders, body: requestBody))\n\n        XCTAssertEqual(response.statusCode, responseStatus)\n        self.assertResponseHeaders(response.headers, expected: responseHeaders)\n        XCTAssertEqual(response.body, responseBody)\n    }\n\n    func testAsyncPut() async throws {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        let url = URL(\"http://async-put-test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n        let requestBody = Data(UUID().uuidString.utf8)\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"PUT\", url) { request in\n            XCTAssertEqual(request.httpBody, requestBody)\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.execute(.init(method: .put, url: url, headers: requestHeaders, body: requestBody))\n\n        XCTAssertEqual(response.statusCode, responseStatus)\n        self.assertResponseHeaders(response.headers, expected: responseHeaders)\n        XCTAssertEqual(response.body, responseBody)\n    }\n\n    func testAsyncDelete() async throws {\n        let configuration = URLSessionConfiguration.ephemeral\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        let url = URL(\"http://async-delete-test\")\n        let requestHeaders = HTTPClientHeaders([HTTPClientHeaders.Item(name: UUID().uuidString, value: UUID().uuidString)])\n\n        let responseStatus = 200\n        let responseHeaders = [UUID().uuidString: UUID().uuidString]\n        let responseBody = Data(UUID().uuidString.utf8)\n\n        MockURLProtocol.onRequest(\"DELETE\", url) { request in\n            self.assertRequestHeaders(request.allHTTPHeaderFields, expected: requestHeaders)\n            MockURLProtocol.respond(request, statusCode: responseStatus, headers: responseHeaders, body: responseBody)\n        }\n\n        let response = try await httpClient.execute(.init(method: .delete, url: url, headers: requestHeaders))\n\n        XCTAssertEqual(response.statusCode, responseStatus)\n        self.assertResponseHeaders(response.headers, expected: responseHeaders)\n        XCTAssertEqual(response.body, responseBody)\n    }\n\n    // MARK: - download\n\n    func testAsyncDownloadSuccess() async throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let url = URL(\"https://async-downloader-tests.com/testBasics.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            let request = HTTPClient.Request.download(\n                url: url,\n                fileSystem: localFileSystem,\n                destination: destination\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                MockURLProtocol.sendData(Data(repeating: 0xBE, count: 512), for: request)\n                MockURLProtocol.sendData(Data(repeating: 0xEF, count: 512), for: request)\n                MockURLProtocol.sendCompletion(for: request)\n            }\n\n            _ = try await httpClient.execute(\n                request,\n                progress: { bytesDownloaded, totalBytesToDownload in\n                    switch (bytesDownloaded, totalBytesToDownload) {\n                    case (512, 1024):\n                        break\n                    case (1024, 1024):\n                        break\n                    default:\n                        XCTFail(\"unexpected progress\")\n                    }\n                }\n            )\n\n            XCTAssertFileExists(destination)\n            let bytes = ByteString(Array(repeating: 0xBE, count: 512) + Array(repeating: 0xEF, count: 512))\n            XCTAssertEqual(try! localFileSystem.readFileContents(destination), bytes)\n        }\n    }\n\n    func testAsyncDownloadAuthenticatedSuccess() async throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let netrcContent = \"machine async-protected.downloader-tests.com login anonymous password qwerty\"\n        let netrc = try NetrcAuthorizationWrapper(underlying: NetrcParser.parse(netrcContent))\n        let authData = Data(\"anonymous:qwerty\".utf8)\n        let testAuthHeader = \"Basic \\(authData.base64EncodedString())\"\n\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let url = URL(\"https://async-protected.downloader-tests.com/testBasics.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            var options = HTTPClientRequest.Options()\n            options.authorizationProvider = netrc.httpAuthorizationHeader(for:)\n            let request = HTTPClient.Request.download(\n                url: url,\n                options: options,\n                fileSystem: localFileSystem,\n                destination: destination\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                XCTAssertEqual(request.allHTTPHeaderFields?[\"Authorization\"], testAuthHeader)\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                MockURLProtocol.sendData(Data(repeating: 0xBE, count: 512), for: request)\n                MockURLProtocol.sendData(Data(repeating: 0xEF, count: 512), for: request)\n                MockURLProtocol.sendCompletion(for: request)\n            }\n\n            _ = try await httpClient.execute(\n                request,\n                progress: { bytesDownloaded, totalBytesToDownload in\n                    switch (bytesDownloaded, totalBytesToDownload) {\n                    case (512, 1024):\n                        break\n                    case (1024, 1024):\n                        break\n                    default:\n                        XCTFail(\"unexpected progress\")\n                    }\n                }\n            )\n\n            XCTAssertFileExists(destination)\n            let bytes = ByteString(Array(repeating: 0xBE, count: 512) + Array(repeating: 0xEF, count: 512))\n            XCTAssertEqual(try! localFileSystem.readFileContents(destination), bytes)\n        }\n    }\n\n    func testAsyncDownloadAuthenticateWithRedirectedSuccess() async throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let netrcContent = \"machine async-protected.downloader-tests2.com login anonymous password qwerty\"\n        let netrc = try NetrcAuthorizationWrapper(underlying: NetrcParser.parse(netrcContent))\n        let authData = Data(\"anonymous:qwerty\".utf8)\n        let testAuthHeader = \"Basic \\(authData.base64EncodedString())\"\n\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let url = URL(\"https://async-protected.downloader-tests2.com/testBasics.zip\")\n            let redirectURL = URL(\"https://cdn-async.downloader-tests.com/testBasics.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            var options = HTTPClientRequest.Options()\n            options.authorizationProvider = netrc.httpAuthorizationHeader(for:)\n            let request = HTTPClient.Request.download(\n                url: url,\n                options: options,\n                fileSystem: localFileSystem,\n                destination: destination\n            )\n            let redirectRequest = HTTPClient.Request.download(\n                url: redirectURL,\n                options: options,\n                fileSystem: localFileSystem,\n                destination: destination\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                XCTAssertEqual(request.allHTTPHeaderFields?[\"Authorization\"], testAuthHeader)\n                MockURLProtocol.sendResponse(statusCode: 302, headers: [\"Location\": redirectURL.absoluteString], for: request)\n                MockURLProtocol.sendRedirect(for: request, to: URLRequest(url: redirectURL))\n            }\n            MockURLProtocol.onRequest(redirectRequest) { request in\n                XCTAssertEqual(request.allHTTPHeaderFields?[\"Authorization\"], nil)\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                MockURLProtocol.sendData(Data(repeating: 0xBE, count: 512), for: request)\n                MockURLProtocol.sendData(Data(repeating: 0xEF, count: 512), for: request)\n                MockURLProtocol.sendCompletion(for: request)\n            }\n\n            let response = try await httpClient.execute(\n                request,\n                progress: { bytesDownloaded, totalBytesToDownload in\n                    switch (bytesDownloaded, totalBytesToDownload) {\n                    case (512, 1024):\n                        break\n                    case (1024, 1024):\n                        break\n                    default:\n                        XCTFail(\"unexpected progress\")\n                    }\n                }\n            )\n\n            XCTAssertEqual(response.statusCode, 200)\n            XCTAssertFileExists(destination)\n\n            let bytes = ByteString(Array(repeating: 0xBE, count: 512) + Array(repeating: 0xEF, count: 512))\n            XCTAssertEqual(try! localFileSystem.readFileContents(destination), bytes)\n        }\n    }\n\n    func testAsyncDownloadDefaultAuthenticationSuccess() async throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let netrcContent = \"default login default password default\"\n        let netrc = try NetrcAuthorizationWrapper(underlying: NetrcParser.parse(netrcContent))\n        let authData = Data(\"default:default\".utf8)\n        let testAuthHeader = \"Basic \\(authData.base64EncodedString())\"\n\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let url = URL(\"https://async-restricted.downloader-tests.com/testBasics.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n\n            var options = HTTPClientRequest.Options()\n            options.authorizationProvider = netrc.httpAuthorizationHeader(for:)\n            let request = HTTPClient.Request.download(\n                url: url,\n                options: options,\n                fileSystem: localFileSystem,\n                destination: destination\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                XCTAssertEqual(request.allHTTPHeaderFields?[\"Authorization\"], testAuthHeader)\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                MockURLProtocol.sendData(Data(repeating: 0xBE, count: 512), for: request)\n                MockURLProtocol.sendData(Data(repeating: 0xEF, count: 512), for: request)\n                MockURLProtocol.sendCompletion(for: request)\n            }\n\n            _ = try await httpClient.execute(\n                request,\n                progress: { bytesDownloaded, totalBytesToDownload in\n                    switch (bytesDownloaded, totalBytesToDownload) {\n                    case (512, 1024):\n                        break\n                    case (1024, 1024):\n                        break\n                    default:\n                        XCTFail(\"unexpected progress\")\n                    }\n                }\n            )\n\n            XCTAssertFileExists(destination)\n            let bytes = ByteString(Array(repeating: 0xBE, count: 512) + Array(repeating: 0xEF, count: 512))\n            XCTAssertEqual(try! localFileSystem.readFileContents(destination), bytes)\n        }\n    }\n\n    func testAsyncDownloadClientError() async throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let clientError = StringError(\"boom\")\n            let url = URL(\"https://async-downloader-tests.com/testClientError.zip\")\n            let request = HTTPClient.Request.download(\n                url: url,\n                fileSystem: localFileSystem,\n                destination: temporaryDirectory.appending(\"download\")\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                MockURLProtocol.sendResponse(statusCode: 200, headers: [\"Content-Length\": \"1024\"], for: request)\n                MockURLProtocol.sendData(Data(count: 512), for: request)\n                MockURLProtocol.sendError(clientError, for: request)\n            }\n\n            do {\n                _ = try await httpClient.execute(\n                    request,\n                    progress: { bytesDownloaded, totalBytesToDownload in\n                        switch (bytesDownloaded, totalBytesToDownload) {\n                        case (512, 1024):\n                            break\n                        default:\n                            XCTFail(\"unexpected progress\")\n                        }\n                    }\n                )\n                XCTFail(\"unexpected success\")\n            } catch {\n                XCTAssertEqual(error as? HTTPClientError, HTTPClientError.downloadError(clientError.description))\n            }\n        }\n    }\n\n    func testAsyncDownloadServerError() async throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let url = URL(\"https://async-downloader-tests.com/testServerError.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            var options = HTTPClientRequest.Options()\n            options.validResponseCodes = [200]\n            let request = HTTPClient.Request.download(\n                url: url,\n                options: options,\n                fileSystem: localFileSystem,\n                destination: destination\n            )\n\n            MockURLProtocol.onRequest(request) { request in\n                MockURLProtocol.sendResponse(statusCode: 500, for: request)\n                MockURLProtocol.sendCompletion(for: request)\n            }\n\n            do {\n                _ = try await httpClient.execute(\n                    request,\n                    progress: { _, _ in\n                        XCTFail(\"unexpected progress\")\n                    }\n                )\n                XCTFail(\"unexpected success\")\n            } catch {\n                XCTAssertEqual(error as? HTTPClientError, HTTPClientError.badResponseStatusCode(500))\n                // Verify that no file was created at the destination for bad response codes\n                XCTAssertFalse(localFileSystem.exists(destination), \"Destination file should not exist for bad response codes\")\n            }\n        }\n    }\n\n    func testAsyncDownloadServerErrorAndResponseBody() async throws {\n        #if !os(macOS)\n        // URLSession Download tests can only run on macOS\n        // as re-libs-foundation's URLSessionTask implementation which expects the temporaryFileURL property to be on the request.\n        // and there is no way to set it in a mock\n        // https://github.com/apple/swift-corelibs-foundation/pull/2593 tries to address the latter part\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let configuration = URLSessionConfiguration.default\n        configuration.protocolClasses = [MockURLProtocol.self]\n        let urlSession = URLSessionHTTPClient(configuration: configuration)\n        let httpClient = HTTPClient(implementation: urlSession.execute)\n\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let url = URL(\"https://async-downloader-tests.com/testServerErrorWithBody.zip\")\n            let destination = temporaryDirectory.appending(\"download\")\n            var options = HTTPClientRequest.Options()\n            options.validResponseCodes = [200]\n            let request = HTTPClient.Request.download(\n                url: url,\n                options: options,\n                fileSystem: localFileSystem,\n                destination: destination\n            )\n\n            // Create an error response body (e.g., JSON error message)\n            let errorJson = Data(\"\"\"\n            {\n              \"errors\" : [ {\n                \"status\" : 500,\n                \"message\" : \"Internal Server Error\"\n              } ]\n            }\n            \"\"\".utf8)\n\n            MockURLProtocol.onRequest(request) { request in\n                MockURLProtocol.sendResponse(statusCode: 500, headers: [\"Content-Type\": \"application/json\", \"Content-Length\": \"\\(errorJson.count)\"], for: request)\n                // Send error response body - this should be downloaded to temp file but then deleted\n                MockURLProtocol.sendData(errorJson, for: request)\n                MockURLProtocol.sendCompletion(for: request)\n            }\n\n            do {\n                _ = try await httpClient.execute(\n                    request,\n                    progress: { _, _ in\n                        // Progress may be called as data is downloaded, even for error responses\n                        // This is expected behavior\n                    }\n                )\n                XCTFail(\"unexpected success\")\n            } catch {\n                XCTAssertEqual(error as? HTTPClientError, HTTPClientError.badResponseStatusCode(500))\n                // Verify that no file was created at the destination for bad response codes\n                // even though a response body was sent\n                XCTAssertFalse(localFileSystem.exists(destination), \"Destination file should not exist for bad response codes, even when response body is present\")\n            }\n        }\n    }\n}\n\nprivate class MockURLProtocol: URLProtocol {\n    typealias Action = (URLRequest) -> Void\n\n    private static var observers = ThreadSafeKeyValueStore<Key, Action>()\n    private static var requests = ThreadSafeKeyValueStore<Key, URLProtocol>()\n\n    static func onRequest(_ request: LegacyHTTPClientRequest, completion: @escaping Action) {\n        self.onRequest(request.method.string, request.url, completion: completion)\n    }\n\n    static func onRequest(_ request: HTTPClientRequest, completion: @escaping Action) {\n        self.onRequest(request.method.string, request.url, completion: completion)\n    }\n\n    static func onRequest(_ method: String, _ url: URL, completion: @escaping Action) {\n        let key = Key(method, url)\n        guard !self.observers.contains(key) else {\n            return XCTFail(\"does not support multiple observers for the same url: \\(key)\")\n        }\n        self.observers[key] = completion\n    }\n\n    static func respond(_ request: URLRequest, statusCode: Int, headers: [String: String]? = nil, body: Data? = nil) {\n        self.respond(request.httpMethod!, request.url!, statusCode: statusCode, headers: headers, body: body)\n    }\n\n    static func respond(_ method: String, _ url: URL, statusCode: Int, headers: [String: String]? = nil, body: Data? = nil) {\n        let key = Key(method, url)\n        self.sendResponse(statusCode: statusCode, headers: headers, for: key)\n        if let data = body {\n            self.sendData(data, for: key)\n        }\n        self.sendCompletion(for: key)\n    }\n\n    static func sendResponse(statusCode: Int, headers: [String: String]? = nil, for request: URLRequest) {\n        self.sendResponse(request.httpMethod!, request.url!, statusCode: statusCode, headers: headers)\n    }\n\n    static func sendResponse(_ method: String, _ url: URL, statusCode: Int, headers: [String: String]? = nil) {\n        let key = Key(method, url)\n        self.sendResponse(statusCode: statusCode, headers: headers, for: key)\n    }\n\n    static func sendData(_ method: String, _ url: URL, _ data: Data) {\n        let key = Key(method, url)\n        self.sendData(data, for: key)\n    }\n\n    static func sendCompletion(_ method: String, _ url: URL) {\n        let key = Key(method, url)\n        self.sendCompletion(for: key)\n    }\n\n    static func sendError(_ method: String, _ url: URL, _ error: Error) {\n        let key = Key(method, url)\n        self.sendError(error, for: key)\n    }\n\n    private static func sendResponse(statusCode: Int, headers: [String: String]? = nil, for key: Key) {\n        guard let request = self.requests[key] else {\n            return XCTFail(\"url did not start loading\")\n        }\n        let response = HTTPURLResponse(url: key.url, statusCode: statusCode, httpVersion: \"1.1\", headerFields: headers)!\n        request.client?.urlProtocol(request, didReceive: response, cacheStoragePolicy: .notAllowed)\n    }\n\n    static func sendData(_ data: Data, for request: URLRequest) {\n        sendData(data, for: Key(request))\n    }\n\n    private static func sendData(_ data: Data, for key: Key) {\n        guard let request = self.requests[key] else {\n            return XCTFail(\"url did not start loading\")\n        }\n        request.client?.urlProtocol(request, didLoad: data)\n    }\n\n    static func sendCompletion(for request: URLRequest) {\n        sendCompletion(for: Key(request))\n    }\n\n    private static func sendCompletion(for key: Key) {\n        guard let request = self.requests[key] else {\n            return XCTFail(\"url did not start loading\")\n        }\n        request.client?.urlProtocolDidFinishLoading(request)\n    }\n\n    static func sendError(_ error: Error, for request: URLRequest) {\n        sendError(error, for: Key(request))\n    }\n\n    private static func sendError(_ error: Error, for key: Key) {\n        guard let request = self.requests[key] else {\n            return XCTFail(\"url did not start loading\")\n        }\n        request.client?.urlProtocol(request, didFailWithError: error)\n    }\n\n    static func sendRedirect(for request: URLRequest, to newRequest: URLRequest) {\n        let key = Key(request.httpMethod!, request.url!)\n        self.sendRedirect(newRequest: newRequest, for: key)\n    }\n\n    private static func sendRedirect(newRequest: URLRequest, for key: Key) {\n        guard let request = self.requests[key] else {\n            return XCTFail(\"url did not start loading\")\n        }\n        let response = HTTPURLResponse(url: key.url, statusCode: 302, httpVersion: \"1.1\", headerFields: nil)!\n        request.client?.urlProtocol(request, wasRedirectedTo: newRequest, redirectResponse: response)\n    }\n\n    private struct Key: Hashable {\n        let method: String\n        let url: URL\n\n        init(_ method: String, _ url: URL) {\n            self.method = method\n            self.url = url\n        }\n\n        init(_ request: URLRequest) {\n            self.method = request.httpMethod!\n            self.url = request.url!\n        }\n    }\n\n    // MARK: - URLProtocol\n\n    override class func canInit(with _: URLRequest) -> Bool {\n        return true\n    }\n\n    override class func canonicalRequest(for request: URLRequest) -> URLRequest {\n        return request\n    }\n\n    override func startLoading() {\n        if let url = self.request.url, let method = self.request.httpMethod {\n            let key = Key(method, url)\n            Self.requests[key] = self\n\n            guard let action = Self.observers[key] else {\n                return\n            }\n\n            // read body if available\n            var request = self.request\n            if let bodyStream = self.request.httpBodyStream {\n                bodyStream.open()\n                defer { bodyStream.close() }\n                let bufferSize: Int = 1024\n                let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)\n                var data = Data()\n                while bodyStream.hasBytesAvailable {\n                    let read = bodyStream.read(buffer, maxLength: bufferSize)\n                    data.append(buffer, count: read)\n                }\n                buffer.deallocate()\n                request.httpBody = data\n            }\n\n            DispatchQueue.main.async {\n                action(request)\n            }\n        }\n    }\n\n    override func stopLoading() {\n        if let url = self.request.url, let method = self.request.httpMethod {\n            let key = Key(method, url)\n            Self.requests[key] = nil\n        }\n    }\n}\n\nfinal class FailingFileSystem: FileSystem {\n    var currentWorkingDirectory: TSCAbsolutePath? {\n        fatalError(\"unexpected call\")\n    }\n\n    var homeDirectory: TSCAbsolutePath {\n        fatalError(\"unexpected call\")\n    }\n\n    var cachesDirectory: TSCAbsolutePath? {\n        fatalError(\"unexpected call\")\n    }\n\n    var tempDirectory: TSCAbsolutePath {\n        fatalError(\"unexpected call\")\n    }\n\n    func changeCurrentWorkingDirectory(to path: TSCAbsolutePath) throws {\n        fatalError(\"unexpected call\")\n    }\n\n    func exists(_ path: TSCAbsolutePath, followSymlink: Bool) -> Bool {\n        fatalError(\"unexpected call\")\n    }\n\n    func isDirectory(_: TSCAbsolutePath) -> Bool {\n        fatalError(\"unexpected call\")\n    }\n\n    func isFile(_: TSCAbsolutePath) -> Bool {\n        fatalError(\"unexpected call\")\n    }\n\n    func isExecutableFile(_: TSCAbsolutePath) -> Bool {\n        fatalError(\"unexpected call\")\n    }\n\n    func isSymlink(_: TSCAbsolutePath) -> Bool {\n        fatalError(\"unexpected call\")\n    }\n\n    func isReadable(_ path: TSCAbsolutePath) -> Bool {\n        fatalError(\"unexpected call\")\n    }\n\n    func isWritable(_ path: TSCAbsolutePath) -> Bool {\n        fatalError(\"unexpected call\")\n    }\n\n    func getDirectoryContents(_: TSCAbsolutePath) throws -> [String] {\n        fatalError(\"unexpected call\")\n    }\n\n    func readFileContents(_: TSCAbsolutePath) throws -> ByteString {\n        fatalError(\"unexpected call\")\n    }\n\n    func removeFileTree(_: TSCAbsolutePath) throws {\n        fatalError(\"unexpected call\")\n    }\n\n    func chmod(_ mode: FileMode, path: TSCAbsolutePath, options: Set<FileMode.Option>) throws {\n        fatalError(\"unexpected call\")\n    }\n\n    func writeFileContents(_ path: TSCAbsolutePath, bytes: ByteString) throws {\n        fatalError(\"unexpected call\")\n    }\n\n    func createDirectory(_ path: TSCAbsolutePath, recursive: Bool) throws {\n        fatalError(\"unexpected call\")\n    }\n\n    func createSymbolicLink(_ path: TSCAbsolutePath, pointingAt destination: TSCAbsolutePath, relative: Bool) throws {\n        fatalError(\"unexpected call\")\n    }\n\n    func copy(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws {\n        fatalError(\"unexpected call\")\n    }\n\n    func move(from sourcePath: TSCAbsolutePath, to destinationPath: TSCAbsolutePath) throws {\n        throw FileSystemError(.unsupported)\n    }\n}\n\nfileprivate struct NetrcAuthorizationWrapper: AuthorizationProvider {\n    let underlying: Netrc\n\n    func authentication(for url: URL) -> (user: String, password: String)? {\n        self.underlying.authorization(for: url).map{ (user: $0.login, password: $0.password) }\n    }\n}\n"
  },
  {
    "path": "Tests/BasicsTests/processInputs/deadlock-if-blocking-io",
    "content": "#!/usr/bin/env python3\n\nimport sys\n\nkb = 1024\n\nfor i in range(0,16 * kb):\n    sys.stdout.write(\"1\")\n    sys.stdout.flush()\n\nfor i in range(0,16 * kb):\n    sys.stderr.write(\"2\")\n    sys.stderr.flush()\n"
  },
  {
    "path": "Tests/BasicsTests/processInputs/deadlock-if-blocking-io.bat",
    "content": "@echo off\npython %~dp0deadlock-if-blocking-io"
  },
  {
    "path": "Tests/BasicsTests/processInputs/echo",
    "content": "#!/usr/bin/env python3\n\nimport sys\n\nfor n in range(5):\n  input = sys.stdin.readline()\n  sys.stdout.write(input)\n  sys.stdout.flush()\n"
  },
  {
    "path": "Tests/BasicsTests/processInputs/echo.bat",
    "content": "@echo off\npython %~dp0echo"
  },
  {
    "path": "Tests/BasicsTests/processInputs/exit4",
    "content": "#!/bin/sh\n\nexit 4\n"
  },
  {
    "path": "Tests/BasicsTests/processInputs/exit4.bat",
    "content": "EXIT /B 4"
  },
  {
    "path": "Tests/BasicsTests/processInputs/in-to-out",
    "content": "#!/usr/bin/env python3\n\nimport sys\n\nsys.stdout.write(sys.stdin.readline())\n"
  },
  {
    "path": "Tests/BasicsTests/processInputs/in-to-out.bat",
    "content": "@echo off\npython %~dp0in-to-out"
  },
  {
    "path": "Tests/BasicsTests/processInputs/long-stdout-stderr",
    "content": "#!/usr/bin/env python3\n\nimport sys\n\nfor i in range(0,16 * 1024):\n    sys.stdout.write(\"1\")\n    sys.stdout.flush()\n    sys.stderr.write(\"2\")\n    sys.stderr.flush()\n\n"
  },
  {
    "path": "Tests/BasicsTests/processInputs/long-stdout-stderr.bat",
    "content": "@echo off\npython %~dp0long-stdout-stderr"
  },
  {
    "path": "Tests/BasicsTests/processInputs/simple-stdout-stderr",
    "content": "#!/usr/bin/env python3\n\nimport sys\n\nsys.stderr.write(\"simple error\\n\")\nsys.stderr.flush()\nsys.stdout.write(\"simple output\\n\")\nsys.stdout.flush()\n"
  },
  {
    "path": "Tests/BasicsTests/processInputs/simple-stdout-stderr.bat",
    "content": "@echo off\npython %~dp0simple-stdout-stderr"
  },
  {
    "path": "Tests/BinarySymbolsTests/LLVMObjdumpSymbolProviderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Testing\nimport BinarySymbols\nimport Basics\n\n@Suite\nstruct LLVMObjdumpSymbolProviderTests {\n    private func getSymbols(_ dump: String) throws -> ReferencedSymbols {\n        var symbols = ReferencedSymbols()\n        // Placeholder executable path since we won't actually run it\n        try LLVMObjdumpSymbolProvider(objdumpPath: AbsolutePath.root).parse(output: dump, symbols: &symbols)\n        return symbols\n    }\n\n    @Test\n    func ignoresHeaderLines() throws {\n        let output = try getSymbols(\n            \"\"\"\n\n            /usr/lib/aarch64-linux-gnu/libc.so.6:   file format elf64-littleaarch64\n\n            SYMBOL TABLE:\n\n            DYNAMIC SYMBOL TABLE:\n            \"\"\"\n        )\n        #expect(output.defined == ReferencedSymbols().defined)\n        #expect(output.undefined.isEmpty)\n    }\n\n    @Test\n    func detectsDefinedSymbol() throws {\n        let output = try getSymbols(\"00000000000e0618 g    DF .text  0000000000000018  GLIBC_2.17  __ppoll_chk\")\n\n        #expect(output.defined.contains(\"__ppoll_chk\"))\n        #expect(output.undefined.isEmpty)\n    }\n\n    @Test\n    func detectsUndefinedSymbol() throws {\n        let output = try getSymbols(\"0000000000000000         *UND*  0000000000000000 calloc\")\n\n        #expect(output.defined == ReferencedSymbols().defined)\n        #expect(output.undefined.contains(\"calloc\"))\n    }\n\n    @Test\n    func treatsCommonSymbolsAsDefined() throws {\n        let output = try getSymbols(\"0000000000000004       O *COM*  0000000000000004 __libc_enable_secure_decided\")\n\n        #expect(output.defined.contains(\"__libc_enable_secure_decided\"))\n        #expect(output.undefined.isEmpty)\n    }\n}\n"
  },
  {
    "path": "Tests/BuildMetalTests/BuildMetalTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Testing\nimport Basics\nimport Foundation\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum PackageModel.BuildConfiguration\n#if os(macOS)\nimport Metal\n#endif\n\n@Suite(\n    .tags(\n        .FunctionalArea.Metal,\n    )\n)\nstruct BuildMetalTests {\n\n    @Test(\n        .disabled(\"Require downloadable Metal toolchain\"),\n        .tags(\n            .TestSize.large,\n        ),\n        .requireHostOS(.macOS),\n        arguments: BuildConfiguration.allCases,\n    )\n    func simpleLibrary(\n        config: BuildConfiguration,\n    ) async throws {\n        let buildSystem = BuildSystemProvider.Kind.swiftbuild\n        let configuration = config\n\n        try await fixture(name: \"Metal/SimpleLibrary\") { fixturePath in\n\n            // Build the package\n            let (_, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n                throwIfCommandFails: true\n            )\n\n            // Get the bin path\n            let (binPathOutput, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: configuration,\n                extraArgs: [\"--show-bin-path\"],\n                buildSystem: buildSystem,\n                throwIfCommandFails: true\n            )\n\n            let binPath = try AbsolutePath(validating: binPathOutput.trimmingCharacters(in: .whitespacesAndNewlines))\n\n            // Check that default.metallib exists\n            let metallibPath = binPath.appending(components:[\"MyRenderer_MyRenderer.bundle\", \"Contents\", \"Resources\", \"default.metallib\"])\n            #expect(\n                localFileSystem.exists(metallibPath),\n                \"Expected default.metallib to exist at \\(metallibPath)\"\n            )\n\n#if os(macOS)\n            // Verify we can load the metal library\n            let device = try #require(MTLCreateSystemDefaultDevice())\n            let library = try device.makeLibrary(URL: URL(fileURLWithPath: metallibPath.pathString))\n\n            #expect(library.functionNames.contains(\"simpleVertexShader\"))\n#endif\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/BuildOperationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Build\n@testable import PackageModel\n\nimport Basics\nimport LLBuildManifest\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport PackageGraph\nimport SPMBuildCore\n@_spi(SwiftPMInternal)\nimport _InternalTestSupport\nimport XCTest\n\nimport class TSCBasic.BufferedOutputByteStream\n\nprivate func mockBuildOperation(\n    productsBuildParameters: BuildParameters,\n    toolsBuildParameters: BuildParameters,\n    cacheBuildManifest: Bool = false,\n    packageGraphLoader: @escaping () -> ModulesGraph = { fatalError() },\n    scratchDirectory: AbsolutePath,\n    fs: any Basics.FileSystem,\n    observabilityScope: ObservabilityScope\n) -> BuildOperation {\n    return BuildOperation(\n        productsBuildParameters: productsBuildParameters,\n        toolsBuildParameters: toolsBuildParameters,\n        cacheBuildManifest: cacheBuildManifest,\n        packageGraphLoader: packageGraphLoader,\n        scratchDirectory: scratchDirectory,\n        additionalFileRules: [],\n        pkgConfigDirectories: [],\n        outputStream: BufferedOutputByteStream(),\n        logLevel: .info,\n        fileSystem: fs,\n        observabilityScope: observabilityScope\n    )\n}\n\nfinal class BuildOperationTests: XCTestCase {\n    func testDetectProductTripleChange() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let fs = InMemoryFileSystem(\n            emptyFiles: \"/Pkg/Sources/ATarget/foo.swift\"\n        )\n        let packageGraph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                .createRootManifest(\n                    displayName: \"SwitchTriple\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"ATarget\"),\n                    ],\n                    traits: []\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        try await withTemporaryDirectory { tmpDir in\n            let scratchDirectory = tmpDir.appending(\".build\")\n            let fs = localFileSystem\n            let triples = try [Triple(\"x86_64-unknown-linux-gnu\"), Triple(\"wasm32-unknown-wasi\")]\n            var llbuildManifestByTriple: [String: String] = [:]\n\n            // Perform initial builds for each triple\n            for triple in triples {\n                let targetBuildParameters = mockBuildParameters(\n                    destination: .target,\n                    buildPath: scratchDirectory.appending(triple.tripleString),\n                    config: .debug,\n                    triple: triple\n                )\n                let buildOp = mockBuildOperation(\n                    productsBuildParameters: targetBuildParameters,\n                    toolsBuildParameters: mockBuildParameters(destination: .host),\n                    cacheBuildManifest: false,\n                    packageGraphLoader: { packageGraph },\n                    scratchDirectory: scratchDirectory,\n                    fs: fs, observabilityScope: observability.topScope\n                )\n                // Generate initial llbuild manifest\n                let _ = try await buildOp.getBuildDescription()\n                // Record the initial llbuild manifest as expected one\n                llbuildManifestByTriple[triple.tripleString] = try fs.readFileContents(targetBuildParameters.llbuildManifest)\n            }\n\n            XCTAssertTrue(fs.exists(scratchDirectory.appending(\"debug.yaml\")))\n            // FIXME: There should be a build database with manifest cache after the initial build.\n            // The initial build usually triggered with `cacheBuildManifest=false` because llbuild\n            // manifest file and description.json are not found. However, with `cacheBuildManifest=false`,\n            // `BuildOperation` does not trigger \"PackageStructure\" build, thus the initial build does\n            // not record the manifest cache. So \"getBuildDescription\" doesn't create build.db for the\n            // initial planning and the second build always need full-planning.\n            //\n            // XCTAssertTrue(fs.exists(scratchDirectory.appending(\"build.db\")))\n\n            // Perform incremental build several times and switch triple for each time\n            for _ in 0..<4 {\n                for triple in triples {\n                    let targetBuildParameters = mockBuildParameters(\n                        destination: .target,\n                        buildPath: scratchDirectory.appending(triple.tripleString),\n                        config: .debug,\n                        triple: triple\n                    )\n                    let buildOp = mockBuildOperation(\n                        productsBuildParameters: targetBuildParameters,\n                        toolsBuildParameters: mockBuildParameters(destination: .host),\n                        cacheBuildManifest: true,\n                        packageGraphLoader: { packageGraph },\n                        scratchDirectory: scratchDirectory,\n                        fs: fs, observabilityScope: observability.topScope\n                    )\n                    // Generate llbuild manifest\n                    let _ = try await buildOp.getBuildDescription()\n\n                    // Ensure that llbuild manifest is updated to the expected one\n                    let actualManifest: String = try fs.readFileContents(targetBuildParameters.llbuildManifest)\n                    let expectedManifest = try XCTUnwrap(llbuildManifestByTriple[triple.tripleString])\n                    XCTAssertEqual(actualManifest, expectedManifest)\n                }\n            }\n        }\n    }\n\n    func testHostProductsAndTargetsWithoutExplicitDestination() async throws {\n        let mock  = try macrosTestsPackageGraph()\n\n        let hostParameters = mockBuildParameters(destination: .host)\n        let targetParameters = mockBuildParameters(destination: .target)\n        let op = mockBuildOperation(\n            productsBuildParameters: targetParameters,\n            toolsBuildParameters: hostParameters,\n            packageGraphLoader: { mock.graph },\n            scratchDirectory: AbsolutePath(\"/.build/\\(hostTriple)\"),\n            fs: mock.fileSystem,\n            observabilityScope: mock.observabilityScope\n        )\n\n        let mmioMacrosProductName = try await op.computeLLBuildTargetName(for: .product(\"MMIOMacros\"))\n        XCTAssertEqual(\n            \"MMIOMacros-\\(hostTriple)-debug-tool.exe\",\n            mmioMacrosProductName\n        )\n\n        let mmioTestsProductName = try await op.computeLLBuildTargetName(\n            for: .product(\"swift-mmioPackageTests\")\n        )\n        XCTAssertEqual(\n            \"swift-mmioPackageTests-\\(hostTriple)-debug-tool.test\",\n            mmioTestsProductName\n        )\n\n        let swiftSyntaxTestsProductName = try await op.computeLLBuildTargetName(\n            for: .product(\"swift-syntaxPackageTests\")\n        )\n        XCTAssertEqual(\n            \"swift-syntaxPackageTests-\\(targetParameters.triple)-debug.test\",\n            swiftSyntaxTestsProductName\n        )\n\n        for target in [\"MMIOMacros\", \"MMIOPlugin\", \"MMIOMacrosTests\", \"MMIOMacro+PluginTests\"] {\n            let targetName = try await op.computeLLBuildTargetName(for: .target(target))\n            XCTAssertEqual(\n                \"\\(target)-\\(hostTriple)-debug-tool.module\",\n                targetName\n            )\n        }\n\n        let swiftSyntaxTestsTarget = try await op.computeLLBuildTargetName(\n            for: .target(\"SwiftSyntaxTests\")\n        )\n        XCTAssertEqual(\n            \"SwiftSyntaxTests-\\(targetParameters.triple)-debug.module\",\n            swiftSyntaxTestsTarget\n        )\n\n        let dependencies = try BuildSubset.target(\"MMIOMacro+PluginTests\").recursiveDependencies(\n            for: mock.graph,\n            observabilityScope: mock.observabilityScope\n        )\n\n        XCTAssertNotNil(dependencies)\n        XCTAssertTrue(dependencies!.count > 0)\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/BuildPlanTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\n@testable import Build\n\n@testable\n@_spi(SwiftPMInternal)\nimport DriverSupport\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\n@testable import PackageGraph\n\nimport PackageLoading\n\n@_spi(SwiftPMInternal)\n@testable import PackageModel\n\nimport SPMBuildCore\nimport _InternalBuildTestSupport\nimport _InternalTestSupport\nimport SwiftDriver\nimport TSCTestSupport\nimport Workspace\nimport XCTest\nimport Testing\n\nimport struct TSCBasic.ByteString\nimport func TSCBasic.withTemporaryFile\n\nimport enum TSCUtility.Diagnostics\n\nextension Build.BuildPlan {\n    var productsBuildPath: AbsolutePath {\n        let buildParameters = self.destinationBuildParameters\n        let buildConfigurationComponent = buildParameters.buildEnvironment\n            .configuration == .release ? \"release\" : \"debug\"\n        return buildParameters.dataPath.appending(components: buildConfigurationComponent)\n    }\n}\n\nclass BuildPlanTestCase: BuildSystemProviderTestCase {\n    override func setUpWithError() throws {\n        try XCTSkipIf(type(of: self) == BuildPlanTestCase.self, \"Skipping this test since it will be run in subclasses that will provide different build systems to test.\")\n    }\n\n    let inputsDir = AbsolutePath(#file).parentDirectory.appending(components: \"Inputs\")\n\n    /// The j argument.\n    private var j: String {\n        \"-j3\"\n    }\n\n    func testDuplicateProductNamesWithNonDefaultLibsThrowError() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles: \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/FooLogging/file.swift\",\n            \"/barPkg/Sources/BarLogging/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let fooPkg: AbsolutePath = \"/fooPkg\"\n        let barPkg: AbsolutePath = \"/barPkg\"\n        XCTAssertThrowsError(try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: fooPkg,\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.dynamic), targets: [\"FooLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"FooLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: barPkg,\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.static), targets: [\"BarLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_8,\n                    dependencies: [\n                        .localSourceControl(path: fooPkg, requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: barPkg, requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(name: \"Logging\", package: \"fooPkg\"),\n                                           .product(name: \"Logging\", package: \"barPkg\")],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )) { error in\n            XCTAssertEqual(\n                (error as? PackageGraphError)?.description,\n                \"multiple packages (\\'barpkg\\' (at '\\(barPkg)'), \\'foopkg\\' (at '\\(fooPkg)')) declare products with a conflicting name: \\'Logging’; product names need to be unique across the package graph\"\n            )\n        }\n    }\n\n    func testDuplicateProductNamesWithADylib() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/FooLogging/file.swift\",\n            \"/barPkg/Sources/BarLogging/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.dynamic), targets: [\"FooLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"FooLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"BarLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_8,\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"barPkg\"\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(2)\n        result.checkTargetsCount(3)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"FooLogging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"BarLogging\" })\n    }\n\n    func testDuplicateProductNamesUpstream1() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/FooLogging/file.swift\",\n            \"/barPkg/Sources/BarLogging/file.swift\",\n            \"/bazPkg/Sources/BazLogging/file.swift\",\n            \"/xPkg/Sources/XUtils/file.swift\",\n            \"/yPkg/Sources/YUtils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"bazPkg\",\n                    path: \"/bazPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"BazLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BazLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"BarLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    toolsVersion: .v5_8,\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/bazPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"FooLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"FooLogging\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"barPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"bazPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"xPkg\",\n                    path: \"/xPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"XUtils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"XUtils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"yPkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"YUtils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"YUtils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_8,\n                    dependencies: [\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            ),\n                            .product(\n                                name: \"Utils\",\n                                package: \"xPkg\"\n                            ),\n                            .product(\n                                name: \"Utils\",\n                                package: \"yPkg\"\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(6)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"FooLogging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"BarLogging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"BazLogging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"XUtils\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"YUtils\" })\n    }\n\n    func testDuplicateProductNamesUpstream2() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/Logging/file.swift\",\n            \"/barPkg/Sources/BarLogging/file.swift\",\n            \"/bazPkg/Sources/BazLogging/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"bazPkg\",\n                    path: \"/bazPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"BazLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BazLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"BarLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    toolsVersion: .v5_8,\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/bazPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Logging\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"barPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"bazPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(4)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Logging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"BarLogging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"BazLogging\" })\n    }\n\n    func testDuplicateProductNamesChained() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/FooLogging/file.swift\",\n            \"/barPkg/Sources/BarLogging/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    toolsVersion: .v5_8,\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"FooLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"FooLogging\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"barPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"BarLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(3)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"FooLogging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"BarLogging\" })\n    }\n\n    func testDuplicateProductNamesThrowError() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/FooLogging/file.swift\",\n            \"/barPkg/Sources/BarLogging/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let fooPkg: AbsolutePath = \"/fooPkg\"\n        let barPkg: AbsolutePath = \"/barPkg\"\n\n        XCTAssertThrowsError(try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: fooPkg,\n                    toolsVersion: .v5_8,\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"FooLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"FooLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: barPkg,\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"BarLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(name: \"Logging\", package: \"fooPkg\"),\n                                           .product(name: \"Logging\", package: \"barPkg\")],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )) { error in\n            XCTAssertEqual(\n                (error as? PackageGraphError)?.description,\n                \"multiple packages (\\'barpkg\\' (at '\\(barPkg)'), \\'foopkg\\' (at '\\(fooPkg)')) declare products with a conflicting name: \\'Logging’; product names need to be unique across the package graph\"\n            )\n        }\n    }\n\n    func testDuplicateProductNamesAllowed() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/FooLogging/file.swift\",\n            \"/barPkg/Sources/BarLogging/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"FooLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"FooLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"BarLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_8,\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"barPkg\"\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(3)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"FooLogging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"BarLogging\" })\n    }\n\n    func testPackageNameFlag() async throws {\n        try XCTSkipIfPlatformCI() // test is disabled because it isn't stable, see rdar://118239206\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8547: 'swift test' was stalled.\")\n        let isFlagSupportedInDriver = try DriverSupport.checkToolchainDriverFlags(\n            flags: [\"package-name\"],\n            toolchain: UserToolchain.default,\n            fileSystem: localFileSystem\n        )\n        try await fixtureXCTest(name: \"Miscellaneous/PackageNameFlag\", createGitRepo: true) { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath.appending(\"appPkg\"),\n                extraArgs: [\"--vv\"],\n                buildSystem: buildSystemProvider\n            )\n\n            let out = if buildSystemProvider == .swiftbuild {\n                stderr\n            } else {\n                stdout\n            }\n\n            XCTAssertMatch(out, .contains(\"-module-name Foo\"))\n            XCTAssertMatch(out, .contains(\"-module-name Zoo\"))\n            XCTAssertMatch(out, .contains(\"-module-name Bar\"))\n            XCTAssertMatch(out, .contains(\"-module-name Baz\"))\n            XCTAssertMatch(out, .contains(\"-module-name App\"))\n            XCTAssertMatch(out, .contains(\"-module-name exe\"))\n            if isFlagSupportedInDriver {\n                XCTAssertMatch(out, .contains(\"-package-name apppkg\"))\n                XCTAssertMatch(out, .contains(\"-package-name foopkg\"))\n                // the flag is not supported if tools-version < 5.9\n                XCTAssertNoMatch(out, .contains(\"-package-name barpkg\"))\n            } else {\n                XCTAssertNoMatch(out, .contains(\"-package-name\"))\n            }\n            XCTAssertMatch(stdout, .contains(\"Build complete!\"))\n        }\n    }\n\n    #if os(macOS)\n    func testPackageNameFlagXCBuild() async throws {\n        let isFlagSupportedInDriver = try DriverSupport.checkToolchainDriverFlags(\n            flags: [\"package-name\"],\n            toolchain: UserToolchain.default,\n            fileSystem: localFileSystem\n        )\n        try await fixtureXCTest(name: \"Miscellaneous/PackageNameFlag\", createGitRepo: true) { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath.appending(\"appPkg\"),\n                extraArgs: [\"--vv\"],\n                buildSystem: .xcode\n            )\n            XCTAssertMatch(stdout, .contains(\"-module-name Foo\"))\n            XCTAssertMatch(stdout, .contains(\"-module-name Zoo\"))\n            XCTAssertMatch(stdout, .contains(\"-module-name Bar\"))\n            XCTAssertMatch(stdout, .contains(\"-module-name Baz\"))\n            XCTAssertMatch(stdout, .contains(\"-module-name App\"))\n            XCTAssertMatch(stdout, .contains(\"-module-name exe\"))\n            if isFlagSupportedInDriver {\n                XCTAssertMatch(stdout, .contains(\"-package-name apppkg\"))\n                XCTAssertMatch(stdout, .contains(\"-package-name foopkg\"))\n                // the flag is not supported if tools-version < 5.9\n                XCTAssertNoMatch(stdout, .contains(\"-package-name barpkg\"))\n            } else {\n                XCTAssertNoMatch(stdout, .contains(\"-package-name\"))\n            }\n            XCTAssertMatch(stdout, .contains(\"Build succeeded\"))\n        }\n    }\n    #endif\n\n    func testTargetsWithPackageAccess() async throws {\n        let isFlagSupportedInDriver = try DriverSupport.checkToolchainDriverFlags(\n            flags: [\"package-name\"],\n            toolchain: UserToolchain.default,\n            fileSystem: localFileSystem\n        )\n        try await fixtureXCTest(name: \"Miscellaneous/TargetPackageAccess\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath.appending(\"libPkg\"),\n                extraArgs: [\"-v\"],\n                buildSystem: buildSystemProvider\n            )\n            if isFlagSupportedInDriver {\n                let moduleFlag1 = stdout.range(of: \"-module-name DataModel\")\n                XCTAssertNotNil(moduleFlag1)\n                let stdoutNext1 = stdout[moduleFlag1!.upperBound...]\n                let packageFlag1 = stdoutNext1.range(of: \"-package-name libpkg\")\n                XCTAssertNotNil(packageFlag1)\n\n                let moduleFlag2 = stdoutNext1.range(of: \"-module-name DataManager\")\n                XCTAssertNotNil(moduleFlag2)\n                XCTAssertTrue(packageFlag1!.upperBound < moduleFlag2!.lowerBound)\n                let stdoutNext2 = stdoutNext1[moduleFlag2!.upperBound...]\n                let packageFlag2 = stdoutNext2.range(of: \"-package-name libpkg\")\n                XCTAssertNotNil(packageFlag2)\n\n                let moduleFlag3 = stdoutNext2.range(of: \"-module-name Core\")\n                XCTAssertNotNil(moduleFlag3)\n                XCTAssertTrue(packageFlag2!.upperBound < moduleFlag3!.lowerBound)\n                let stdoutNext3 = stdoutNext2[moduleFlag3!.upperBound...]\n                let packageFlag3 = stdoutNext3.range(of: \"-package-name libpkg\")\n                XCTAssertNotNil(packageFlag3)\n\n                let moduleFlag4 = stdoutNext3.range(of: \"-module-name MainLib\")\n                XCTAssertNotNil(moduleFlag4)\n                XCTAssertTrue(packageFlag3!.upperBound < moduleFlag4!.lowerBound)\n                let stdoutNext4 = stdoutNext3[moduleFlag4!.upperBound...]\n                let packageFlag4 = stdoutNext4.range(of: \"-package-name libpkg\")\n                XCTAssertNotNil(packageFlag4)\n\n                let moduleFlag5 = stdoutNext4.range(of: \"-module-name ExampleApp\")\n                XCTAssertNotNil(moduleFlag5)\n                XCTAssertTrue(packageFlag4!.upperBound < moduleFlag5!.lowerBound)\n                let stdoutNext5 = stdoutNext4[moduleFlag5!.upperBound...]\n                let packageFlag5 = stdoutNext5.range(of: \"-package-name\")\n                XCTAssertNil(packageFlag5)\n            } else {\n                XCTAssertNoMatch(stdout, .contains(\"-package-name\"))\n            }\n            XCTAssertMatch(stdout, .contains(\"Build complete!\"))\n        }\n    }\n\n    func testBasicSwiftPackage() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        let buildPath = plan.productsBuildPath\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(\n            exe,\n            [\n                \"-enable-batch-mode\",\n                \"-serialize-diagnostics\",\n                \"-Onone\",\n                \"-enable-testing\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DDEBUG\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n                .anySequence,\n            ]\n        )\n\n        let lib = try result.moduleBuildDescription(for: \"lib\").swift().compileArguments()\n        XCTAssertMatch(\n            lib,\n            [\n                \"-enable-batch-mode\",\n                \"-serialize-diagnostics\",\n                \"-Onone\",\n                \"-enable-testing\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DDEBUG\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n                .anySequence,\n            ]\n        )\n\n        #if os(macOS)\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-Xlinker\", \"-add_ast_path\", \"-Xlinker\",\n            buildPath.appending(components: \"Modules\", \"lib.swiftmodule\").pathString,\n            \"-Xlinker\", \"-add_ast_path\", \"-Xlinker\",\n            buildPath.appending(components: \"exe.build\", \"exe.swiftmodule\").pathString,\n            \"-g\",\n        ]\n        #elseif os(Windows)\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            // \"-static-stdlib\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ]\n        #else\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-static-stdlib\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ]\n        #endif\n\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), linkArguments)\n\n        #if os(macOS)\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"can be downloaded\"), severity: .warning)\n        }\n        #else\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        #endif\n    }\n\n    func testSwiftConditionalDependency() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"exe\", \"main.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"PkgLib\", \"lib.swift\").pathString,\n            \"/ExtPkg/Sources/ExtLib/lib.swift\",\n            \"/PlatformPkg/Sources/PlatformLib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    dependencies: [\n                        .localSourceControl(path: \"/ExtPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/PlatformPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\n                            .target(name: \"PkgLib\", condition: PackageConditionDescription(\n                                platformNames: [\"linux\", \"android\"],\n                                config: nil\n                            )),\n                        ]),\n                        TargetDescription(name: \"PkgLib\", dependencies: [\n                            .product(name: \"ExtLib\", package: \"ExtPkg\", condition: PackageConditionDescription(\n                                platformNames: [],\n                                config: \"debug\"\n                            )),\n                            .product(\n                                name: \"PlatformLib\",\n                                package: \"PlatformPkg\",\n                                condition: PackageConditionDescription(\n                                    platformNames: [\"linux\"]\n                                )\n                            ),\n                        ]),\n                    ],\n                    traits: []\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"ExtPkg\",\n                    path: \"/ExtPkg\",\n                    products: [\n                        ProductDescription(name: \"ExtLib\", type: .library(.automatic), targets: [\"ExtLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ExtLib\", dependencies: []),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"PlatformPkg\",\n                    path: \"/PlatformPkg\",\n                    platforms: [PlatformDescription(name: \"macos\", version: \"50.0\")],\n                    products: [\n                        ProductDescription(name: \"PlatformLib\", type: .library(.automatic), targets: [\"PlatformLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"PlatformLib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        do {\n            let plan = try await mockBuildPlan(\n                environment: BuildEnvironment(\n                    platform: .linux,\n                    configuration: .release\n                ),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n\n            let buildPath = plan.destinationBuildParameters.dataPath.appending(components: \"release\")\n\n            let result = try BuildPlanResult(plan: plan)\n            let buildProduct = try result.buildProduct(for: \"exe\")\n            let objectDirectoryNames = buildProduct.objects.map(\\.parentDirectory.basename)\n            XCTAssertTrue(objectDirectoryNames.contains(\"PkgLib.build\"))\n            XCTAssertFalse(objectDirectoryNames.contains(\"ExtLib.build\"))\n\n            let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"release.yaml\")\n            try fs.createDirectory(yaml.parentDirectory, recursive: true)\n            let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n            try llbuild.generateManifest(at: yaml)\n            let contents: String = try fs.readFileContents(yaml)\n            let swiftGetVersionFilePath = try XCTUnwrap(llbuild.swiftGetVersionFiles.first?.value)\n            XCTAssertMatch(\n                contents,\n                .contains(\"\"\"\n                inputs: [\"\\(\n                    Pkg.appending(components: \"Sources\", \"exe\", \"main.swift\")\n                        .escapedPathString\n                )\",\"\\(swiftGetVersionFilePath.escapedPathString)\",\"\\(\n                buildPath\n                    .appending(components: \"Modules\", \"PkgLib.swiftmodule\").escapedPathString\n                )\",\"\\(\n                buildPath\n                    .appending(components: \"exe.build\", \"sources\").escapedPathString\n                )\"]\n                \"\"\")\n            )\n        }\n\n        do {\n            let plan = try await mockBuildPlan(\n                environment: BuildEnvironment(\n                    platform: .macOS,\n                    configuration: .debug\n                ),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n\n            let result = try BuildPlanResult(plan: plan)\n            let buildProduct = try result.buildProduct(for: \"exe\")\n            let objectDirectoryNames = buildProduct.objects.map(\\.parentDirectory.basename)\n            XCTAssertFalse(objectDirectoryNames.contains(\"PkgLib.build\"))\n            XCTAssertFalse(objectDirectoryNames.contains(\"ExtLib.build\"))\n\n            let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"debug.yaml\")\n            try fs.createDirectory(yaml.parentDirectory, recursive: true)\n            let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n            try llbuild.generateManifest(at: yaml)\n            let contents: String = try fs.readFileContents(yaml)\n            let buildPath = plan.productsBuildPath\n            let swiftGetVersionFilePath = try XCTUnwrap(llbuild.swiftGetVersionFiles.first?.value)\n            XCTAssertMatch(contents, .contains(\"\"\"\n                inputs: [\"\\(\n                    Pkg.appending(components: \"Sources\", \"exe\", \"main.swift\")\n                        .escapedPathString\n            )\",\"\\(swiftGetVersionFilePath.escapedPathString)\",\"\\(\n                buildPath\n                    .appending(components: \"exe.build\", \"sources\").escapedPathString\n            )\"]\n            \"\"\"))\n        }\n    }\n\n    func testBasicExtPackages() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/foo.swift\",\n            \"/A/Tests/ATargetTests/foo.swift\",\n            \"/B/Sources/BTarget/foo.swift\",\n            \"/B/Tests/BTargetTests/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BLibrary\"]),\n                        TargetDescription(name: \"ATargetTests\", dependencies: [\"ATarget\"], type: .test),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    products: [\n                        ProductDescription(name: \"BLibrary\", type: .library(.automatic), targets: [\"BTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget\", dependencies: []),\n                        TargetDescription(name: \"BTargetTests\", dependencies: [\"BTarget\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n\n        XCTAssertEqual(Set(result.productMap.map(\\.product.name)), [\"APackageTests\"])\n        var expectedTargets: Set<String> = [\n            \"APackageTests\",\n            \"ATarget\",\n            \"ATargetTests\",\n            \"BTarget\",\n        ]\n#if !os(macOS)\n        expectedTargets.insert(\"APackageDiscoveredTests\")\n#endif\n        XCTAssertEqual(Set(result.targetMap.map(\\.module.name)), expectedTargets)\n    }\n\n    func testBasicReleasePackage() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            config: .release,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(1)\n\n        let buildPath = result.plan.destinationBuildParameters.dataPath.appending(components: \"release\")\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(\n            exe,\n            [\n                \"-O\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n            ]\n        )\n\n        #if os(macOS)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-dead_strip\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #elseif os(Windows)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"/OPT:REF\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #else\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"--gc-sections\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n    }\n\n    func testBasicReleasePackageNoDeadStrip() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            config: .release,\n            graph: graph,\n            linkingParameters: .init(\n                linkerDeadStrip: false\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(1)\n\n        let buildPath = result.plan.destinationBuildParameters.dataPath.appending(components: \"release\")\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(\n            exe,\n            [\n                \"-O\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n            ]\n        )\n\n        #if os(macOS)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #elseif os(Windows)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #else\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n    }\n\n    func testBasicClangPackage() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n        let ExtPkg: AbsolutePath = \"/ExtPkg\"\n\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"exe\", \"main.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"lib.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"lib.S\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"include\", \"lib.h\").pathString,\n            ExtPkg.appending(components: \"Sources\", \"extlib\", \"extlib.c\").pathString,\n            ExtPkg.appending(components: \"Sources\", \"extlib\", \"include\", \"ext.h\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    dependencies: [\n                        .localSourceControl(\n                            path: .init(validating: ExtPkg.pathString),\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: [\"ExtPkg\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"ExtPkg\",\n                    path: .init(validating: ExtPkg.pathString),\n                    products: [\n                        ProductDescription(name: \"ExtPkg\", type: .library(.automatic), targets: [\"extlib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"extlib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(3)\n\n        let buildPath = result.plan.destinationBuildParameters.dataPath.appending(components: \"debug\")\n\n        let ext = try result.moduleBuildDescription(for: \"extlib\").clang()\n        var args: [String] = []\n\n        #if os(macOS)\n        args += [\"-fobjc-arc\"]\n        #endif\n        args += [\"-target\", defaultTargetTriple]\n        args += [\"-O0\", \"-DSWIFT_PACKAGE=1\", \"-DDEBUG=1\"]\n        args += [\"-fblocks\"]\n        #if os(macOS) // FIXME(5473) - support modules on non-Apple platforms\n        args += [\n            \"-fmodules\",\n            \"-fmodule-name=extlib\",\n            \"-fmodules-cache-path=\\(buildPath.appending(components: \"ModuleCache\"))\",\n        ]\n        #endif\n        args += [\"-I\", ExtPkg.appending(components: \"Sources\", \"extlib\", \"include\").pathString]\n        args += [hostTriple.isWindows() ? \"-gdwarf\" : \"-g\"]\n\n        if hostTriple.isLinux() {\n            args += [\"-fno-omit-frame-pointer\"]\n        }\n\n        XCTAssertEqual(try ext.basicArguments(isCXX: false), args)\n        XCTAssertEqual(try ext.objects, [buildPath.appending(components: \"extlib.build\", \"extlib.c.o\")])\n        XCTAssertEqual(ext.moduleMap, buildPath.appending(components: \"extlib.build\", \"module.modulemap\"))\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").clang()\n        args = []\n\n        #if os(macOS)\n        args += [\"-fobjc-arc\", \"-target\", defaultTargetTriple]\n        #else\n        args += [\"-target\", defaultTargetTriple]\n        #endif\n\n        args += [\"-O0\", \"-DSWIFT_PACKAGE=1\", \"-DDEBUG=1\"]\n        args += [\"-fblocks\"]\n        #if os(macOS) // FIXME(5473) - support modules on non-Apple platforms\n        args += [\n            \"-fmodules\",\n            \"-fmodule-name=exe\",\n            \"-fmodules-cache-path=\\(buildPath.appending(components: \"ModuleCache\"))\",\n        ]\n        #endif\n        args += [\n            \"-I\", Pkg.appending(components: \"Sources\", \"exe\", \"include\").pathString,\n            \"-I\", Pkg.appending(components: \"Sources\", \"lib\", \"include\").pathString,\n            \"-fmodule-map-file=\\(buildPath.appending(components: \"lib.build\", \"module.modulemap\"))\",\n            \"-I\", ExtPkg.appending(components: \"Sources\", \"extlib\", \"include\").pathString,\n            \"-fmodule-map-file=\\(buildPath.appending(components: \"extlib.build\", \"module.modulemap\"))\",\n        ]\n        args += [hostTriple.isWindows() ? \"-gdwarf\" : \"-g\"]\n\n        if hostTriple.isLinux() {\n            args += [\"-fno-omit-frame-pointer\"]\n        }\n\n        XCTAssertEqual(try exe.basicArguments(isCXX: false), args)\n        XCTAssertEqual(try exe.objects, [buildPath.appending(components: \"exe.build\", \"main.c.o\")])\n        XCTAssertEqual(exe.moduleMap, nil)\n\n        #if os(macOS)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #elseif os(Windows)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #else\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n\n        let buildProduct = try XCTUnwrap(\n            result.productMap[.init(\n                productID: .init(productName: \"exe\", packageIdentity: \"Pkg\"),\n                destination: .target\n            )]\n        )\n        XCTAssertEqual(Array(buildProduct.objects), [\n            buildPath.appending(components: \"exe.build\", \"main.c.o\"),\n            buildPath.appending(components: \"extlib.build\", \"extlib.c.o\"),\n            buildPath.appending(components: \"lib.build\", \"lib.c.o\"),\n        ])\n    }\n\n    func testClangConditionalDependency() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.c\",\n            \"/Pkg/Sources/PkgLib/lib.c\",\n            \"/Pkg/Sources/PkgLib/lib.S\",\n            \"/Pkg/Sources/PkgLib/include/lib.h\",\n            \"/ExtPkg/Sources/ExtLib/extlib.c\",\n            \"/ExtPkg/Sources/ExtLib/include/ext.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/ExtPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\n                            .target(name: \"PkgLib\", condition: PackageConditionDescription(\n                                platformNames: [\"linux\", \"android\"],\n                                config: nil\n                            )),\n                        ]),\n                        TargetDescription(name: \"PkgLib\", dependencies: [\n                            .product(name: \"ExtPkg\", package: \"ExtPkg\", condition: PackageConditionDescription(\n                                platformNames: [],\n                                config: \"debug\"\n                            )),\n                        ]),\n                    ],\n                    traits: []\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"ExtPkg\",\n                    path: \"/ExtPkg\",\n                    products: [\n                        ProductDescription(name: \"ExtPkg\", type: .library(.automatic), targets: [\"ExtLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ExtLib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: BuildEnvironment(\n                    platform: .linux,\n                    configuration: .release\n                ),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            let exeArguments = try result.moduleBuildDescription(for: \"exe\").clang().basicArguments(isCXX: false)\n            XCTAssert(exeArguments.contains { $0.contains(\"PkgLib\") })\n            XCTAssert(exeArguments.allSatisfy { !$0.contains(\"ExtLib\") })\n\n            let libArguments = try result.moduleBuildDescription(for: \"PkgLib\").clang().basicArguments(isCXX: false)\n            XCTAssert(libArguments.allSatisfy { !$0.contains(\"ExtLib\") })\n        }\n\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: BuildEnvironment(\n                    platform: .macOS,\n                    configuration: .debug\n                ),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            let arguments = try result.moduleBuildDescription(for: \"exe\").clang().basicArguments(isCXX: false)\n            XCTAssert(arguments.allSatisfy { !$0.contains(\"PkgLib\") && !$0.contains(\"ExtLib\") })\n\n            let libArguments = try result.moduleBuildDescription(for: \"PkgLib\").clang().basicArguments(isCXX: false)\n            XCTAssert(libArguments.contains { $0.contains(\"ExtLib\") })\n        }\n    }\n\n    func testCLanguageStandard() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"exe\", \"main.cpp\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"lib.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"libx.cpp\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"include\", \"lib.h\").pathString,\n            Pkg.appending(components: \"Sources\", \"swiftInteropLib\", \"lib.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"swiftLib\", \"lib.swift\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    cLanguageStandard: \"gnu99\",\n                    cxxLanguageStandard: \"c++1z\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                        TargetDescription(\n                            name: \"swiftInteropLib\",\n                            dependencies: [],\n                            settings: [.init(tool: .swift, kind: .interoperabilityMode(.Cxx))]\n                        ),\n                        TargetDescription(name: \"swiftLib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(4)\n\n        let buildPath = plan.productsBuildPath\n\n        #if os(macOS)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-lc++\",\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #elseif os(Windows)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #elseif os(FreeBSD)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-lc++\",\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #else\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-lstdc++\",\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n\n        let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"debug.yaml\")\n        try fs.createDirectory(yaml.parentDirectory, recursive: true)\n        let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.generateManifest(at: yaml)\n        let contents: String = try fs.readFileContents(yaml)\n        XCTAssertMatch(\n            contents,\n            .contains(#\"-std=gnu99\",\"-c\",\"\\#(Pkg.appending(components: \"Sources\", \"lib\", \"lib.c\").escapedPathString)\"#)\n        )\n        XCTAssertMatch(\n            contents,\n            .contains(\n                #\"-std=c++1z\",\"-c\",\"\\#(Pkg.appending(components: \"Sources\", \"lib\", \"libx.cpp\").escapedPathString)\"#\n            )\n        )\n\n        // Assert compile args for swift modules importing cxx modules\n        let swiftInteropLib = try result.moduleBuildDescription(for: \"swiftInteropLib\").swift().compileArguments()\n        XCTAssertMatch(\n            swiftInteropLib,\n            [.anySequence, \"-cxx-interoperability-mode=default\", \"-Xcc\", \"-std=c++1z\", .anySequence]\n        )\n        let swiftLib = try result.moduleBuildDescription(for: \"swiftLib\").swift().compileArguments()\n        XCTAssertNoMatch(swiftLib, [.anySequence, \"-Xcc\", \"-std=c++1z\", .anySequence])\n\n        // Assert symbolgraph-extract args for swift modules importing cxx modules\n        do {\n            let swiftInteropLib = try result.moduleBuildDescription(for: \"swiftInteropLib\").swift().compileArguments()\n            XCTAssertMatch(\n                swiftInteropLib,\n                [.anySequence, \"-cxx-interoperability-mode=default\", \"-Xcc\", \"-std=c++1z\", .anySequence]\n            )\n            let swiftLib = try result.moduleBuildDescription(for: \"swiftLib\").swift().compileArguments()\n            XCTAssertNoMatch(swiftLib, [.anySequence, \"-Xcc\", \"-std=c++1z\", .anySequence])\n        }\n\n        // Assert symbolgraph-extract args for cxx modules\n        do {\n            let swiftInteropLib = try result.moduleBuildDescription(for: \"swiftInteropLib\").swift().compileArguments()\n            XCTAssertMatch(\n                swiftInteropLib,\n                [.anySequence, \"-cxx-interoperability-mode=default\", \"-Xcc\", \"-std=c++1z\", .anySequence]\n            )\n            let swiftLib = try result.moduleBuildDescription(for: \"swiftLib\").swift().compileArguments()\n            XCTAssertNoMatch(swiftLib, [.anySequence, \"-Xcc\", \"-std=c++1z\", .anySequence])\n        }\n    }\n\n    func testSwiftCMixed() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"exe\", \"main.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"lib.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"include\", \"lib.h\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        let buildPath = plan.productsBuildPath\n\n        let lib = try result.moduleBuildDescription(for: \"lib\").clang()\n        var args: [String] = []\n\n        #if os(macOS)\n        args += [\"-fobjc-arc\"]\n        #endif\n        args += [\"-target\", defaultTargetTriple]\n\n        args += [\"-O0\", \"-DSWIFT_PACKAGE=1\", \"-DDEBUG=1\"]\n        args += [\"-fblocks\"]\n        #if os(macOS) // FIXME(5473) - support modules on non-Apple platforms\n        args += [\n            \"-fmodules\",\n            \"-fmodule-name=lib\",\n            \"-fmodules-cache-path=\\(buildPath.appending(components: \"ModuleCache\"))\",\n        ]\n        #endif\n        args += [\"-I\", Pkg.appending(components: \"Sources\", \"lib\", \"include\").pathString]\n        args += [hostTriple.isWindows() ? \"-gdwarf\" : \"-g\"]\n\n        if hostTriple.isLinux() {\n            args += [\"-fno-omit-frame-pointer\"]\n        }\n\n        XCTAssertEqual(try lib.basicArguments(isCXX: false), args)\n        XCTAssertEqual(try lib.objects, [buildPath.appending(components: \"lib.build\", \"lib.c.o\")])\n        XCTAssertEqual(lib.moduleMap, buildPath.appending(components: \"lib.build\", \"module.modulemap\"))\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(\n            exe,\n            [\n                .anySequence,\n                \"-enable-batch-mode\",\n                \"-serialize-diagnostics\",\n                \"-Onone\",\n                \"-enable-testing\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DDEBUG\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-Xcc\",\n                \"-fmodule-map-file=\\(buildPath.appending(components: \"lib.build\", \"module.modulemap\"))\",\n                \"-Xcc\", \"-I\", \"-Xcc\", \"\\(Pkg.appending(components: \"Sources\", \"lib\", \"include\"))\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n                .anySequence,\n            ]\n        )\n\n        #if os(macOS)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-Xlinker\", \"-add_ast_path\", \"-Xlinker\", \"/path/to/build/\\(result.plan.destinationBuildParameters.triple)/debug/exe.build/exe.swiftmodule\",\n            \"-g\",\n        ])\n        #elseif os(Windows)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #else\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n    }\n\n    func testSwiftCAsmMixed() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.c\",\n            \"/Pkg/Sources/lib/lib.S\",\n            \"/Pkg/Sources/lib/include/lib.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    toolsVersion: .v5,\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        let lib = try result.moduleBuildDescription(for: \"lib\").clang()\n        XCTAssertEqual(try lib.objects, [\n            AbsolutePath(\"/path/to/build/\\(result.plan.destinationBuildParameters.triple)/debug/lib.build/lib.S.o\"),\n            AbsolutePath(\"/path/to/build/\\(result.plan.destinationBuildParameters.triple)/debug/lib.build/lib.c.o\"),\n        ])\n    }\n\n    func testSwiftSettings_interoperabilityMode_cxx() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"cxxLib\", \"lib.cpp\").pathString,\n            Pkg.appending(components: \"Sources\", \"cxxLib\", \"include\", \"lib.h\").pathString,\n            Pkg.appending(components: \"Sources\", \"swiftLib\", \"lib.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"swiftLib2\", \"lib2.swift\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    cxxLanguageStandard: \"c++20\",\n                    targets: [\n                        TargetDescription(name: \"cxxLib\", dependencies: []),\n                        TargetDescription(\n                            name: \"swiftLib\",\n                            dependencies: [\"cxxLib\"],\n                            settings: [.init(tool: .swift, kind: .interoperabilityMode(.Cxx))]\n                        ),\n                        TargetDescription(name: \"swiftLib2\", dependencies: [\"swiftLib\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        // Cxx module\n        do {\n            try XCTAssertMatch(\n                result.moduleBuildDescription(for: \"cxxLib\").clang().symbolGraphExtractArguments(),\n                [.anySequence, \"-cxx-interoperability-mode=default\", \"-Xcc\", \"-std=c++20\", .anySequence]\n            )\n        }\n\n        // Swift module directly importing cxx module\n        do {\n            try XCTAssertMatch(\n                result.moduleBuildDescription(for: \"swiftLib\").swift().compileArguments(),\n                [.anySequence, \"-cxx-interoperability-mode=default\", \"-Xcc\", \"-std=c++20\", .anySequence]\n            )\n            try XCTAssertMatch(\n                result.moduleBuildDescription(for: \"swiftLib\").swift().symbolGraphExtractArguments(),\n                [.anySequence, \"-cxx-interoperability-mode=default\", \"-Xcc\", \"-std=c++20\", .anySequence]\n            )\n        }\n\n        // Swift module transitively importing cxx module\n        do {\n            try XCTAssertNoMatch(\n                result.moduleBuildDescription(for: \"swiftLib2\").swift().compileArguments(),\n                [.anySequence, \"-cxx-interoperability-mode=default\", .anySequence]\n            )\n            try XCTAssertNoMatch(\n                result.moduleBuildDescription(for: \"swiftLib2\").swift().compileArguments(),\n                [.anySequence, \"-Xcc\", \"-std=c++20\", .anySequence]\n            )\n            try XCTAssertNoMatch(\n                result.moduleBuildDescription(for: \"swiftLib2\").swift().symbolGraphExtractArguments(),\n                [.anySequence, \"-cxx-interoperability-mode=default\", .anySequence]\n            )\n            try XCTAssertNoMatch(\n                result.moduleBuildDescription(for: \"swiftLib2\").swift().symbolGraphExtractArguments(),\n                [.anySequence, \"-Xcc\", \"-std=c++20\", .anySequence]\n            )\n        }\n    }\n\n    func test_symbolGraphExtract_arguments() async throws {\n        // ModuleGraph:\n        // .\n        // ├── A (Swift)\n        // │   ├── B (Swift)\n        // │   └── C (C)\n        // └── D (C)\n        //     ├── B (Swift)\n        //     └── C (C)\n\n        let Pkg: AbsolutePath = \"/Pkg\"\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            // A\n            Pkg.appending(components: \"Sources\", \"A\", \"A.swift\").pathString,\n            // B\n            Pkg.appending(components: \"Sources\", \"B\", \"B.swift\").pathString,\n            // C\n            Pkg.appending(components: \"Sources\", \"C\", \"C.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"C\", \"include\", \"C.h\").pathString,\n            // D\n            Pkg.appending(components: \"Sources\", \"D\", \"D.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"D\", \"include\", \"D.h\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    targets: [\n                        TargetDescription(name: \"A\", dependencies: [\"B\", \"C\"]),\n                        TargetDescription(name: \"B\", dependencies: []),\n                        TargetDescription(name: \"C\", dependencies: []),\n                        TargetDescription(name: \"D\", dependencies: [\"B\", \"C\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let result = try BuildPlanResult(plan: plan)\n        let triple = result.plan.destinationBuildParameters.triple\n\n        func XCTAssertMatchesSubSequences(\n            _ value: [String],\n            _ patterns: [StringPattern]...,\n            file: StaticString = #file,\n            line: UInt = #line\n        ) {\n            for pattern in patterns {\n                var pattern = pattern\n                pattern.insert(.anySequence, at: 0)\n                pattern.append(.anySequence)\n                XCTAssertMatch(value, pattern, file: file, line: line)\n            }\n        }\n\n        // A\n        do {\n            let expectedModuleMap = AbsolutePath(\"/path/to/build/\\(triple)/debug/C.build/module.modulemap\").pathString\n            try XCTAssertMatchesSubSequences(\n                result.moduleBuildDescription(for: \"A\").symbolGraphExtractArguments(),\n                // Swift Module dependencies\n                [\"-I\", .equal(AbsolutePath(\"/path/to/build/\\(triple)/debug/Modules\").pathString)],\n                // C Module dependencies\n                [\"-Xcc\", \"-I\", \"-Xcc\", .equal(AbsolutePath(\"/Pkg/Sources/C/include\").pathString)],\n                [\"-Xcc\", \"-fmodule-map-file=\\(expectedModuleMap)\"]\n            )\n        }\n\n        // D\n        do {\n            let expectedBInclude = AbsolutePath(\"/path/to/build/\\(triple)/debug/B.build/include\").pathString\n            let expectedCModuleMap = AbsolutePath(\"/path/to/build/\\(triple)/debug/C.build/module.modulemap\").pathString\n            let expectedDModuleMap = AbsolutePath(\"/path/to/build/\\(triple)/debug/D.build/module.modulemap\").pathString\n            let expectedModuleCache = AbsolutePath(\"/path/to/build/\\(triple)/debug/ModuleCache\").pathString\n            try XCTAssertMatchesSubSequences(\n                result.moduleBuildDescription(for: \"D\").symbolGraphExtractArguments(),\n                // Self Module\n                [\"-I\", .equal(AbsolutePath(\"/Pkg/Sources/D/include\").pathString)],\n                [\"-Xcc\", \"-fmodule-map-file=\\(expectedDModuleMap)\"],\n\n                // C Module dependencies\n                [\"-Xcc\", \"-I\", \"-Xcc\", .equal(AbsolutePath(\"/Pkg/Sources/C/include\").pathString)],\n                [\"-Xcc\", \"-fmodule-map-file=\\(expectedCModuleMap)\"],\n\n                // General Args\n                [\n                    \"-Xcc\", \"-fmodules\",\n                    \"-Xcc\", \"-fmodule-name=D\",\n                    \"-Xcc\", \"-fmodules-cache-path=\\(expectedModuleCache)\",\n                ]\n            )\n\n            try XCTAssertMatchesSubSequences(\n                result.moduleBuildDescription(for: \"D\").symbolGraphExtractArguments(),\n                // Swift Module dependencies\n                [\"-Xcc\", \"-I\", \"-Xcc\", \"\\(expectedBInclude)\"]\n            )\n        }\n    }\n\n    func test_wholeModuleOptimization_enabledInRelease() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n                Pkg.appending(components: \"Sources\", \"A\", \"A.swift\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    targets: [\n                        TargetDescription(name: \"A\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        do {\n            // WMO Should be off in debug\n            let plan = try await mockBuildPlan(\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n\n            let a = try BuildPlanResult(plan: plan)\n                .moduleBuildDescription(for: \"A\").swift().emitCommandLine()\n            XCTAssertNoMatch(a, [\"-whole-module-optimization\"])\n            XCTAssertNoMatch(a, [\"-wmo\"])\n        }\n\n        do {\n            // WMO should be on in release\n            let plan = try await mockBuildPlan(\n                environment: BuildEnvironment(\n                    platform: .linux,\n                    configuration: .release\n                ),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n\n            let a = try BuildPlanResult(plan: plan)\n                .moduleBuildDescription(for: \"A\").swift().emitCommandLine()\n            XCTAssertMatch(a, [\"-whole-module-optimization\"])\n            XCTAssertNoMatch(a, [\"-wmo\"])\n        }\n    }\n\n    func test_wholeModuleOptimization_enabledInEmbedded() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n                Pkg.appending(components: \"Sources\", \"A\", \"A.swift\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            settings: [.init(tool: .swift, kind: .enableExperimentalFeature(\"Embedded\"))]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        // -wmo should be passed with Embedded\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkTargetsCount(1)\n\n        // Compile Swift Target\n        let aCompileArguments = try result.moduleBuildDescription(for: \"A\").swift().compileArguments()\n        let aCompileArgumentsPattern: [StringPattern] = [\"-whole-module-optimization\"]\n        let aCompileArgumentsNegativePattern: [StringPattern] = [\"-wmo\"]\n        XCTAssertMatch(aCompileArguments, aCompileArgumentsPattern)\n        XCTAssertNoMatch(aCompileArguments, aCompileArgumentsNegativePattern)\n    }\n\n    func testREPLArguments() async throws {\n        let Dep = AbsolutePath(\"/Dep\")\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/swiftlib/lib.swift\",\n            \"/Pkg/Sources/lib/lib.c\",\n            \"/Pkg/Sources/lib/include/lib.h\",\n            Dep.appending(components: \"Sources\", \"Dep\", \"dep.swift\").pathString,\n            Dep.appending(components: \"Sources\", \"CDep\", \"cdep.c\").pathString,\n            Dep.appending(components: \"Sources\", \"CDep\", \"include\", \"head.h\").pathString,\n            Dep.appending(components: \"Sources\", \"CDep\", \"include\", \"module.modulemap\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Dep\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"swiftlib\"]),\n                        TargetDescription(name: \"swiftlib\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: [\"Dep\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Dep\",\n                    path: \"/Dep\",\n                    products: [\n                        ProductDescription(name: \"Dep\", type: .library(.automatic), targets: [\"Dep\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Dep\", dependencies: [\"CDep\"]),\n                        TargetDescription(name: \"CDep\", dependencies: []),\n                    ]\n                ),\n            ],\n            createREPLProduct: true,\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let buildPath = plan.productsBuildPath\n        XCTAssertEqual(\n            try plan.createREPLArguments().sorted(),\n            [\n                \"-I\\(Dep.appending(components: \"Sources\", \"CDep\", \"include\"))\",\n                \"-I\\(buildPath)\",\n                \"-I\\(buildPath.appending(components: \"lib.build\"))\",\n                \"-L\\(buildPath)\",\n                \"-lpkg__REPL\",\n                \"repl\",\n            ]\n        )\n\n        XCTAssertEqual(plan.graph.allProducts.map(\\.name).sorted(), [\n            \"Dep\",\n            \"exe\",\n            \"pkg__REPL\",\n        ])\n    }\n\n    func testTestModule() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/Foo/foo.swift\",\n            \"/Pkg/Tests/\\(SwiftModule.defaultTestEntryPointName)\",\n            \"/Pkg/Tests/FooTests/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                        TargetDescription(name: \"FooTests\", dependencies: [\"Foo\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(3)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let foo = try result.moduleBuildDescription(for: \"Foo\").swift().compileArguments()\n        XCTAssertMatch(\n            foo,\n            [\n                .anySequence,\n                \"-enable-batch-mode\",\n                \"-serialize-diagnostics\",\n                \"-Onone\",\n                \"-enable-testing\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DDEBUG\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n                .anySequence,\n            ]\n        )\n\n        let fooTests = try result.moduleBuildDescription(for: \"FooTests\").swift().compileArguments()\n        XCTAssertMatch(\n            fooTests,\n            [\n                .anySequence,\n                \"-enable-batch-mode\",\n                \"-serialize-diagnostics\",\n                \"-Onone\",\n                \"-enable-testing\",\n                \"-Xfrontend\",\n                \"-enable-cross-import-overlays\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DDEBUG\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n                .anySequence,\n            ]\n        )\n\n        #if os(macOS)\n        let version = MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .macOS).versionString\n        var rpathsForBackdeployment: [String] = []\n        if let version = try? Version(string: version, lenient: true), version.major < 12 {\n            rpathsForBackdeployment += [\"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\"]\n        }\n        if let version = try? Version(string: version, lenient: true), version.major < 26 {\n            rpathsForBackdeployment += [\"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\"]\n        }\n        XCTAssertEqual(\n            try result.buildProduct(for: \"PkgPackageTests\").linkArguments(),\n            [\n                result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n                \"-L\", buildPath.pathString,\n                \"-o\",\n                buildPath.appending(components: \"PkgPackageTests.xctest\", \"Contents\", \"MacOS\", \"PkgPackageTests\")\n                    .pathString,\n                \"-module-name\", \"PkgPackageTests\",\n                \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n                \"-Xlinker\", \"-bundle\",\n                \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path/../../../\",\n                \"@\\(buildPath.appending(components: \"PkgPackageTests.product\", \"Objects.LinkFileList\"))\",\n            ] + rpathsForBackdeployment + [\n                \"-target\", \"\\(hostTriple.tripleString(forPlatformVersion: version))\",\n                \"-Xlinker\", \"-add_ast_path\", \"-Xlinker\",\n                buildPath.appending(components: \"Modules\", \"Foo.swiftmodule\").pathString,\n                \"-Xlinker\", \"-add_ast_path\", \"-Xlinker\",\n                buildPath.appending(components: \"Modules\", \"FooTests.swiftmodule\").pathString,\n                \"-Xlinker\", \"-add_ast_path\", \"-Xlinker\",\n                buildPath.appending(components: \"Modules\", \"PkgPackageTests.swiftmodule\").pathString,\n                \"-g\",\n            ]\n        )\n        #elseif os(Windows)\n        XCTAssertEqual(try result.buildProduct(for: \"PkgPackageTests\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"PkgPackageTests.xctest\").pathString,\n            \"-module-name\", \"PkgPackageTests\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"PkgPackageTests.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #else\n        XCTAssertEqual(try result.buildProduct(for: \"PkgPackageTests\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"PkgPackageTests.xctest\").pathString,\n            \"-module-name\", \"PkgPackageTests\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"PkgPackageTests.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n    }\n\n    func testConcurrencyInOS() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"12.0\"),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            config: .release,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(1)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n\n        XCTAssertMatch(\n            exe,\n            [\n                .anySequence,\n                \"-O\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n                .anySequence,\n            ]\n        )\n\n        #if os(macOS)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-dead_strip\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", hostTriple.tripleString(forPlatformVersion: \"12.0\"),\n            \"-g\",\n        ])\n        #endif\n    }\n\n    func testParseAsLibraryFlagForExe() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            // executable has a single source file not named `main.swift`, without @main.\n            \"/Pkg/Sources/exe1/foo.swift\",\n            // executable has a single source file named `main.swift`, without @main.\n            \"/Pkg/Sources/exe2/main.swift\",\n            // executable has a single source file not named `main.swift`, with @main.\n            \"/Pkg/Sources/exe3/foo.swift\",\n            // executable has a single source file named `main.swift`, with @main\n            \"/Pkg/Sources/exe4/main.swift\",\n            // executable has a single source file named `comments.swift`, with @main in comments\n            \"/Pkg/Sources/exe5/comments.swift\",\n            // executable has a single source file named `comments.swift`, with @main in comments\n            \"/Pkg/Sources/exe6/comments.swift\",\n            // executable has a single source file named `comments.swift`, with @main in comments\n            \"/Pkg/Sources/exe7/comments.swift\",\n            // executable has a single source file named `comments.swift`, with @main in comments\n            \"/Pkg/Sources/exe8/comments.swift\",\n            // executable has a single source file named `comments.swift`, with @main in comments\n            \"/Pkg/Sources/exe9/comments.swift\",\n            // executable has a single source file named `comments.swift`, with @main in comments and not in comments\n            \"/Pkg/Sources/exe10/comments.swift\",\n            // executable has a single source file named `comments.swift`, with @main in comments and not in comments\n            \"/Pkg/Sources/exe11/comments.swift\",\n            // executable has a single source file named `comments.swift`, with @main in comments and not in comments\n            \"/Pkg/Sources/exe12/comments.swift\",\n            // executable has multiple source files.\n            \"/Pkg/Sources/exe13/bar.swift\",\n            \"/Pkg/Sources/exe13/main.swift\",\n            // Snippet with top-level code\n            \"/Pkg/Snippets/TopLevelCodeSnippet.swift\",\n            // Snippet with @main\n            \"/Pkg/Snippets/AtMainSnippet.swift\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe3/foo.swift\",\n            string: \"\"\"\n            @main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe4/main.swift\",\n            string: \"\"\"\n            @main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe5/comments.swift\",\n            string: \"\"\"\n            // @main in comment\n            print(\"hello world\")\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe6/comments.swift\",\n            string: \"\"\"\n            /* @main in comment */\n            print(\"hello world\")\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe7/comments.swift\",\n            string: \"\"\"\n            /*\n            @main in comment\n            */\n            print(\"hello world\")\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe8/comments.swift\",\n            string: \"\"\"\n            /*\n            @main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }\n            */\n            print(\"hello world\")\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe9/comments.swift\",\n            string: \"\"\"\n            /*@main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }*/\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe10/comments.swift\",\n            string: \"\"\"\n            // @main in comment\n            @main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe11/comments.swift\",\n            string: \"\"\"\n            /* @main in comment */\n            @main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Sources/exe12/comments.swift\",\n            string: \"\"\"\n            /*\n            @main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }*/\n            @main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Snippets/TopLevelCodeSnippet.swift\",\n            string: \"\"\"\n            struct Foo {\n              init() {}\n              func foo() {}\n            }\n            let foo = Foo()\n            foo.foo()\n            \"\"\"\n        )\n\n        try fs.writeFileContents(\n            \"/Pkg/Snippets/AtMainSnippet.swift\",\n            string: \"\"\"\n            @main\n            struct Runner {\n              static func main() {\n                print(\"hello world\")\n              }\n            }\n            \"\"\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    toolsVersion: .v5_5,\n                    targets: [\n                        TargetDescription(name: \"exe1\", type: .executable),\n                        TargetDescription(name: \"exe2\", type: .executable),\n                        TargetDescription(name: \"exe3\", type: .executable),\n                        TargetDescription(name: \"exe4\", type: .executable),\n                        TargetDescription(name: \"exe5\", type: .executable),\n                        TargetDescription(name: \"exe6\", type: .executable),\n                        TargetDescription(name: \"exe7\", type: .executable),\n                        TargetDescription(name: \"exe8\", type: .executable),\n                        TargetDescription(name: \"exe9\", type: .executable),\n                        TargetDescription(name: \"exe10\", type: .executable),\n                        TargetDescription(name: \"exe11\", type: .executable),\n                        TargetDescription(name: \"exe12\", type: .executable),\n                        TargetDescription(name: \"exe13\", type: .executable),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(15)\n        result.checkTargetsCount(15)\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        // single source file not named main, and without @main should not have -parse-as-library.\n        let exe1 = try result.moduleBuildDescription(for: \"exe1\").swift().emitCommandLine()\n        XCTAssertNoMatch(exe1, [\"-parse-as-library\"])\n\n        // single source file named main, and without @main should not have -parse-as-library.\n        let exe2 = try result.moduleBuildDescription(for: \"exe2\").swift().emitCommandLine()\n        XCTAssertNoMatch(exe2, [\"-parse-as-library\"])\n\n        // single source file not named main, with @main should have -parse-as-library.\n        let exe3 = try result.moduleBuildDescription(for: \"exe3\").swift().emitCommandLine()\n        XCTAssertMatch(exe3, [\"-parse-as-library\"])\n\n        // single source file named main, with @main should have -parse-as-library.\n        let exe4 = try result.moduleBuildDescription(for: \"exe4\").swift().emitCommandLine()\n        XCTAssertMatch(exe4, [\"-parse-as-library\"])\n\n        // multiple source files should not have -parse-as-library.\n        let exe5 = try result.moduleBuildDescription(for: \"exe5\").swift().emitCommandLine()\n        XCTAssertNoMatch(exe5, [\"-parse-as-library\"])\n\n        // @main in comment should not have -parse-as-library.\n        let exe6 = try result.moduleBuildDescription(for: \"exe6\").swift().emitCommandLine()\n        XCTAssertNoMatch(exe6, [\"-parse-as-library\"])\n\n        // @main in comment should not have -parse-as-library.\n        let exe7 = try result.moduleBuildDescription(for: \"exe7\").swift().emitCommandLine()\n        XCTAssertNoMatch(exe7, [\"-parse-as-library\"])\n\n        // @main in comment should not have -parse-as-library.\n        let exe8 = try result.moduleBuildDescription(for: \"exe8\").swift().emitCommandLine()\n        XCTAssertNoMatch(exe8, [\"-parse-as-library\"])\n\n        // @main in comment should not have -parse-as-library.\n        let exe9 = try result.moduleBuildDescription(for: \"exe9\").swift().emitCommandLine()\n        XCTAssertNoMatch(exe9, [\"-parse-as-library\"])\n\n        // @main in comment + non-comment should have -parse-as-library.\n        let exe10 = try result.moduleBuildDescription(for: \"exe10\").swift().emitCommandLine()\n        XCTAssertMatch(exe10, [\"-parse-as-library\"])\n\n        // @main in comment + non-comment should have -parse-as-library.\n        let exe11 = try result.moduleBuildDescription(for: \"exe11\").swift().emitCommandLine()\n        XCTAssertMatch(exe11, [\"-parse-as-library\"])\n\n        // @main in comment + non-comment should have -parse-as-library.\n        let exe12 = try result.moduleBuildDescription(for: \"exe12\").swift().emitCommandLine()\n        XCTAssertMatch(exe12, [\"-parse-as-library\"])\n\n        // multiple source files should not have -parse-as-library.\n        let exe13 = try result.moduleBuildDescription(for: \"exe13\").swift().emitCommandLine()\n        XCTAssertNoMatch(exe13, [\"-parse-as-library\"])\n\n        // A snippet with top-level code should not have -parse-as-library.\n        let topLevelCodeSnippet = try result.moduleBuildDescription(for: \"TopLevelCodeSnippet\").swift().emitCommandLine()\n        XCTAssertNoMatch(topLevelCodeSnippet, [\"-parse-as-library\"])\n\n        // A snippet with @main should have -parse-as-library\n        let atMainSnippet = try result.moduleBuildDescription(for: \"AtMainSnippet\").swift().emitCommandLine()\n        XCTAssertMatch(atMainSnippet, [\"-parse-as-library\"])\n    }\n\n    func testCModule() async throws {\n        let Clibgit = AbsolutePath(\"/Clibgit\")\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            Clibgit.appending(components: \"module.modulemap\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    dependencies: [\n                        .localSourceControl(\n                            path: .init(validating: Clibgit.pathString),\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Clibgit\",\n                    path: \"/Clibgit\"\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(1)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let matchText = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        let assertionText: [StringPattern] = [\n            \"-enable-batch-mode\",\n            \"-serialize-diagnostics\",\n            \"-Onone\",\n            \"-enable-testing\",\n            .equal(self.j),\n            \"-DSWIFT_PACKAGE\",\n            \"-DDEBUG\",\n            \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n            \"-Xcc\", \"-fmodule-map-file=\\(Clibgit.appending(components: \"module.modulemap\"))\",\n            \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n            .anySequence,\n            \"-swift-version\", \"4\",\n            \"-g\",\n            .anySequence,\n        ]\n\n        XCTAssertMatch(\n            matchText,\n            assertionText\n        )\n\n        #if os(macOS)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-Xlinker\", \"-add_ast_path\",\n            \"-Xlinker\", buildPath.appending(components: \"exe.build\", \"exe.swiftmodule\").pathString,\n            \"-g\",\n        ])\n        #elseif os(Windows)\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #else\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n    }\n\n    func testCppModule() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.cpp\",\n            \"/Pkg/Sources/lib/include/lib.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"lib\", dependencies: []),\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        var result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n        var linkArgs = try result.buildProduct(for: \"exe\").linkArguments()\n\n        #if os(macOS) || os(FreeBSD)\n        XCTAssertMatch(linkArgs, [\"-lc++\"])\n        #elseif !os(Windows)\n        XCTAssertMatch(linkArgs, [\"-lstdc++\"])\n        #endif\n\n        // Verify that `-lstdc++` is passed instead of `-lc++` when cross-compiling to Linux.\n        result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: .arm64Linux,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n        linkArgs = try result.buildProduct(for: \"exe\").linkArguments()\n\n        XCTAssertMatch(linkArgs, [\"-lstdc++\"])\n    }\n\n    func testDynamicProducts() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/Foo/main.swift\",\n            \"/Bar/Source/Bar/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let g = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    products: [\n                        ProductDescription(name: \"Bar-Baz\", type: .library(.dynamic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar-Baz\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: g,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(2)\n        result.checkTargetsCount(2)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let fooLinkArgs = try result.buildProduct(for: \"Foo\").linkArguments()\n        let barLinkArgs = try result.buildProduct(for: \"Bar-Baz\").linkArguments()\n\n        #if os(macOS)\n        XCTAssertEqual(fooLinkArgs, [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"Foo\").pathString,\n            \"-module-name\", \"Foo\",\n            \"-lBar-Baz\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"Foo.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-Xlinker\", \"-add_ast_path\",\n            \"-Xlinker\", buildPath.appending(components: \"Foo.build\", \"Foo.swiftmodule\").pathString,\n            \"-g\",\n        ])\n\n        XCTAssertEqual(barLinkArgs, [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"libBar-Baz.dylib\").pathString,\n            \"-module-name\", \"Bar_Baz\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-library\",\n            \"-Xlinker\", \"-install_name\", \"-Xlinker\", \"@rpath/libBar-Baz.dylib\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"Bar-Baz.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-Xlinker\", \"-add_ast_path\",\n            \"-Xlinker\", buildPath.appending(components: \"Modules\", \"Bar.swiftmodule\").pathString,\n            \"-g\",\n        ])\n        #elseif os(Windows)\n        XCTAssertEqual(fooLinkArgs, [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"Foo.exe\").pathString,\n            \"-module-name\", \"Foo\",\n            \"-lBar-Baz\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"Foo.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n\n        XCTAssertEqual(barLinkArgs, [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"Bar-Baz.dll\").pathString,\n            \"-module-name\", \"Bar_Baz\",\n            \"-emit-library\",\n            \"@\\(buildPath.appending(components: \"Bar-Baz.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #else\n        XCTAssertEqual(fooLinkArgs, [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"Foo\").pathString,\n            \"-module-name\", \"Foo\",\n            \"-lBar-Baz\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"Foo.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n\n        XCTAssertEqual(barLinkArgs, [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"libBar-Baz.so\").pathString,\n            \"-module-name\", \"Bar_Baz\",\n            \"-emit-library\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"Bar-Baz.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n\n        #if os(macOS)\n        XCTAssert(\n            barLinkArgs.contains(\"-install_name\")\n                && barLinkArgs.contains(\"@rpath/libBar-Baz.dylib\")\n                && barLinkArgs.contains(\"-rpath\")\n                && barLinkArgs.contains(\"@loader_path\"),\n            \"The dynamic library will not work once moved outside the build directory.\"\n        )\n        #endif\n    }\n\n    func testExecAsDependency() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    products: [\n                        ProductDescription(name: \"lib\", type: .library(.dynamic), targets: [\"lib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"lib\", dependencies: []),\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(2)\n        result.checkTargetsCount(2)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(\n            exe,\n            [\n                \"-enable-batch-mode\",\n                \"-serialize-diagnostics\",\n                \"-Onone\",\n                \"-enable-testing\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DDEBUG\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n                .anySequence,\n            ]\n        )\n\n        let lib = try result.moduleBuildDescription(for: \"lib\").swift().compileArguments()\n        XCTAssertMatch(\n            lib,\n            [\n                \"-enable-batch-mode\",\n                \"-serialize-diagnostics\",\n                \"-Onone\",\n                \"-enable-testing\",\n                .equal(self.j),\n                \"-DSWIFT_PACKAGE\",\n                \"-DDEBUG\",\n                \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n                .anySequence,\n                \"-swift-version\", \"4\",\n                \"-g\",\n                .anySequence,\n            ]\n        )\n\n        #if os(macOS)\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"liblib.dylib\").pathString,\n            \"-module-name\", \"lib\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-library\",\n            \"-Xlinker\", \"-install_name\", \"-Xlinker\", \"@rpath/liblib.dylib\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"lib.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-Xlinker\", \"-add_ast_path\", \"-Xlinker\",\n            buildPath.appending(components: \"Modules\", \"lib.swiftmodule\").pathString,\n            \"-g\",\n        ]\n        #elseif os(Windows)\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"lib.dll\").pathString,\n            \"-module-name\", \"lib\",\n            \"-emit-library\",\n            \"@\\(buildPath.appending(components: \"lib.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\",\n            \"-Xlinker\", \"-debug:dwarf\",\n        ]\n        #else\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"liblib.so\").pathString,\n            \"-module-name\", \"lib\",\n            \"-emit-library\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"lib.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ]\n        #endif\n\n        XCTAssertEqual(try result.buildProduct(for: \"lib\").linkArguments(), linkArguments)\n    }\n\n    func testClangTargets() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"exe\", \"main.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"include\", \"lib.h\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"lib.cpp\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    products: [\n                        ProductDescription(name: \"lib\", type: .library(.dynamic), targets: [\"lib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"lib\", dependencies: []),\n                        TargetDescription(name: \"exe\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(2)\n        result.checkTargetsCount(2)\n\n        let triple = result.plan.destinationBuildParameters.triple\n        let buildPath = result.plan.productsBuildPath\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").clang()\n\n        var expectedExeBasicArgs = triple.isDarwin() ? [\"-fobjc-arc\"] : []\n        expectedExeBasicArgs += [\"-target\", defaultTargetTriple]\n        expectedExeBasicArgs += [\"-O0\", \"-DSWIFT_PACKAGE=1\", \"-DDEBUG=1\", \"-fblocks\"]\n        #if os(macOS) // FIXME(5473) - support modules on non-Apple platforms\n        expectedExeBasicArgs += [\n            \"-fmodules\",\n            \"-fmodule-name=exe\",\n            \"-fmodules-cache-path=\\(buildPath.appending(components: \"ModuleCache\"))\"\n        ]\n        #endif\n        expectedExeBasicArgs += [\"-I\", Pkg.appending(components: \"Sources\", \"exe\", \"include\").pathString]\n\n        expectedExeBasicArgs += [triple.isWindows() ? \"-gdwarf\" : \"-g\"]\n\n        if triple.isLinux() {\n            expectedExeBasicArgs += [\"-fno-omit-frame-pointer\"]\n        }\n\n        XCTAssertEqual(try exe.basicArguments(isCXX: false), expectedExeBasicArgs)\n        XCTAssertEqual(try exe.objects, [buildPath.appending(components: \"exe.build\", \"main.c.o\")])\n        XCTAssertEqual(exe.moduleMap, nil)\n\n        let lib = try result.moduleBuildDescription(for: \"lib\").clang()\n\n        var expectedLibBasicArgs = triple.isDarwin() ? [\"-fobjc-arc\"] : []\n        expectedLibBasicArgs += [\"-target\", defaultTargetTriple]\n        expectedLibBasicArgs += [\"-O0\", \"-DSWIFT_PACKAGE=1\", \"-DDEBUG=1\", \"-fblocks\"]\n//        let shouldHaveModules = false // FIXME(5473) - support modules on non-Apple platforms, and also for C++ on any platform\n//        if shouldHaveModules {\n//            expectedLibBasicArgs += [\"-fmodules\", \"-fmodule-name=lib\"]\n//        }\n        expectedLibBasicArgs += [\"-I\", Pkg.appending(components: \"Sources\", \"lib\", \"include\").pathString]\n//        if shouldHaveModules {\n//            expectedLibBasicArgs += [\"-fmodules-cache-path=\\(buildPath.appending(components: \"ModuleCache\"))\"]\n//        }\n        expectedLibBasicArgs += [\n            triple.isWindows() ? \"-gdwarf\" : \"-g\",\n            triple.isWindows() ? \"-gdwarf\" : \"-g\",\n        ]\n\n        if triple.isLinux() {\n            expectedLibBasicArgs += [\"-fno-omit-frame-pointer\"]\n        }\n\n        XCTAssertEqual(try lib.basicArguments(isCXX: true), expectedLibBasicArgs)\n\n        XCTAssertEqual(try lib.objects, [buildPath.appending(components: \"lib.build\", \"lib.cpp.o\")])\n        XCTAssertEqual(lib.moduleMap, buildPath.appending(components: \"lib.build\", \"module.modulemap\"))\n\n        #if os(macOS)\n        XCTAssertEqual(try result.buildProduct(for: \"lib\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-lc++\",\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"liblib.dylib\").pathString,\n            \"-module-name\", \"lib\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-library\",\n            \"-Xlinker\", \"-install_name\", \"-Xlinker\", \"@rpath/liblib.dylib\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"lib.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@loader_path\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #elseif os(Windows)\n        XCTAssertEqual(try result.buildProduct(for: \"lib\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"lib.dll\").pathString,\n            \"-module-name\", \"lib\",\n            \"-emit-library\",\n            \"@\\(buildPath.appending(components: \"lib.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ])\n        #else\n        #if os(FreeBSD)\n        XCTAssertEqual(try result.buildProduct(for: \"lib\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-lc++\",\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"liblib.so\").pathString,\n            \"-module-name\", \"lib\",\n            \"-emit-library\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"lib.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #else\n        XCTAssertEqual(try result.buildProduct(for: \"lib\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-lstdc++\",\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"liblib.so\").pathString,\n            \"-module-name\", \"lib\",\n            \"-emit-library\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"lib.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"-Xlinker\", \"-rpath=$ORIGIN\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-runtime-compatibility-version\", \"none\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ])\n        #endif\n    }\n\n    func testNonReachableProductsAndTargets() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/main.swift\",\n            \"/B/Sources/BTarget1/BTarget1.swift\",\n            \"/B/Sources/BTarget2/main.swift\",\n            \"/C/Sources/CTarget/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/C\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"aexec\", type: .executable, targets: [\"ATarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BLibrary\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    products: [\n                        ProductDescription(name: \"BLibrary\", type: .library(.static), targets: [\"BTarget1\"]),\n                        ProductDescription(name: \"bexec\", type: .executable, targets: [\"BTarget2\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget1\", dependencies: []),\n                        TargetDescription(name: \"BTarget2\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"C\",\n                    path: \"/C\",\n                    products: [\n                        ProductDescription(name: \"cexec\", type: .executable, targets: [\"CTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"CTarget\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n        XCTAssertEqual(observability.diagnostics.count, 1)\n        let firstDiagnostic = observability.diagnostics.first.map(\\.message)\n        XCTAssert(\n            firstDiagnostic == \"dependency 'c' is not used by any target\",\n            \"Unexpected diagnostic: \" + (firstDiagnostic ?? \"[none]\")\n        )\n        #endif\n\n        let graphResult = PackageGraphResultXCTest(graph)\n        graphResult.check(reachableProducts: \"aexec\", \"BLibrary\")\n        graphResult.check(reachableTargets: \"ATarget\", \"BTarget1\")\n        #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n        graphResult.check(products: \"aexec\", \"BLibrary\")\n        graphResult.check(modules: \"ATarget\", \"BTarget1\")\n        #else\n        graphResult.check(products: \"BLibrary\", \"bexec\", \"aexec\", \"cexec\")\n        graphResult.check(modules: \"ATarget\", \"BTarget1\", \"BTarget2\", \"CTarget\")\n        #endif\n\n        let planResult = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n\n        #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n        planResult.checkProductsCount(2)\n        planResult.checkTargetsCount(2)\n        #else\n        planResult.checkProductsCount(4)\n        planResult.checkTargetsCount(4)\n        #endif\n    }\n\n    func testReachableBuildProductsAndTargets() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/main.swift\",\n            \"/B/Sources/BTarget1/source.swift\",\n            \"/B/Sources/BTarget2/source.swift\",\n            \"/B/Sources/BTarget3/source.swift\",\n            \"/C/Sources/CTarget/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/C\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"aexec\", type: .executable, targets: [\"ATarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\n                            .product(name: \"BLibrary1\", package: \"B\", condition: PackageConditionDescription(\n                                platformNames: [\"linux\"],\n                                config: nil\n                            )),\n                            .product(name: \"BLibrary2\", package: \"B\", condition: PackageConditionDescription(\n                                platformNames: [],\n                                config: \"debug\"\n                            )),\n                            .product(name: \"CLibrary\", package: \"C\", condition: PackageConditionDescription(\n                                platformNames: [\"android\"],\n                                config: \"release\"\n                            )),\n                        ]),\n                    ],\n                    traits: []\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    products: [\n                        ProductDescription(name: \"BLibrary1\", type: .library(.static), targets: [\"BTarget1\"]),\n                        ProductDescription(name: \"BLibrary2\", type: .library(.static), targets: [\"BTarget2\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget1\", dependencies: []),\n                        TargetDescription(name: \"BTarget2\", dependencies: [\n                            .target(name: \"BTarget3\", condition: PackageConditionDescription(\n                                platformNames: [\"macos\"],\n                                config: nil\n                            )),\n                        ]),\n                        TargetDescription(name: \"BTarget3\", dependencies: []),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"C\",\n                    path: \"/C\",\n                    products: [\n                        ProductDescription(name: \"CLibrary\", type: .library(.static), targets: [\"CTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"CTarget\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let graphResult = PackageGraphResultXCTest(graph)\n\n        do {\n            let linuxDebug = BuildEnvironment(platform: .linux, configuration: .debug)\n            try graphResult.check(reachableBuildProducts: \"aexec\", \"BLibrary1\", \"BLibrary2\", in: linuxDebug)\n            try graphResult.check(reachableBuildTargets: \"ATarget\", \"BTarget1\", \"BTarget2\", in: linuxDebug)\n\n            let planResult = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: linuxDebug,\n                graph: graph,\n                fileSystem: fileSystem,\n                observabilityScope: observability.topScope\n            ))\n            planResult.checkProductsCount(4)\n            planResult.checkTargetsCount(5)\n        }\n\n        do {\n            let macosDebug = BuildEnvironment(platform: .macOS, configuration: .debug)\n            try graphResult.check(reachableBuildProducts: \"aexec\", \"BLibrary2\", in: macosDebug)\n            try graphResult.check(reachableBuildTargets: \"ATarget\", \"BTarget2\", \"BTarget3\", in: macosDebug)\n\n            let planResult = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: macosDebug,\n                graph: graph,\n                fileSystem: fileSystem,\n                observabilityScope: observability.topScope\n            ))\n            planResult.checkProductsCount(4)\n            planResult.checkTargetsCount(5)\n        }\n\n        do {\n            let androidRelease = BuildEnvironment(platform: .android, configuration: .release)\n            try graphResult.check(reachableBuildProducts: \"aexec\", \"CLibrary\", in: androidRelease)\n            try graphResult.check(reachableBuildTargets: \"ATarget\", \"CTarget\", in: androidRelease)\n\n            let planResult = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: androidRelease,\n                graph: graph,\n                fileSystem: fileSystem,\n                observabilityScope: observability.topScope\n            ))\n            planResult.checkProductsCount(4)\n            planResult.checkTargetsCount(5)\n        }\n    }\n\n    func testSystemPackageBuildPlan() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/module.modulemap\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\"\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        do {\n            _ = try await mockBuildPlan(\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            XCTFail()\n        } catch {\n            if let buildError = error as? Build.BuildPlan.Error {\n                XCTAssert(buildError == .noBuildableTarget)\n            } else {\n                XCTFail()\n            }\n        }\n    }\n\n    func testPkgConfigHintDiagnostic() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/foo.swift\",\n            \"/A/Sources/BTarget/module.modulemap\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BTarget\"]),\n                        TargetDescription(\n                            name: \"BTarget\",\n                            type: .system,\n                            pkgConfig: \"BTarget\",\n                            providers: [\n                                .brew([\"BTarget\"]),\n                                .apt([\"BTarget\"]),\n                                .yum([\"BTarget\"]),\n                                .pkg([\"BTarget\"])\n                            ]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        _ = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        )\n\n        #if !os(Windows) // FIXME: pkg-config is not generally available on Windows\n        XCTAssertTrue(observability.diagnostics.contains(where: {\n            $0.severity == .warning &&\n                $0.message.hasPrefix(\"you may be able to install BTarget using your system-packager\")\n        }), \"expected PkgConfigHint diagnostics\")\n        #endif\n    }\n\n    func testPkgConfigGenericDiagnostic() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/foo.swift\",\n            \"/A/Sources/BTarget/module.modulemap\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BTarget\"]),\n                        TargetDescription(\n                            name: \"BTarget\",\n                            type: .system,\n                            pkgConfig: \"BTarget\"\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        _ = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        )\n\n        let diagnostic = observability.diagnostics.last!\n\n        XCTAssertEqual(diagnostic.message, \"couldn't find pc file for BTarget\")\n        XCTAssertEqual(diagnostic.severity, .warning)\n        XCTAssertEqual(diagnostic.metadata?.moduleName, \"BTarget\")\n        XCTAssertEqual(diagnostic.metadata?.pcFile, \"BTarget.pc\")\n    }\n\n    func testWindowsTarget() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"exe\", \"main.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"lib.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"lib\", \"include\", \"lib.h\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: .windows,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        let buildPath = result.plan.destinationBuildParameters.dataPath.appending(components: \"debug\")\n\n        let lib = try result.moduleBuildDescription(for: \"lib\").clang()\n        let args = [\n            \"-target\", \"x86_64-unknown-windows-msvc\",\n            \"-O0\",\n            \"-DSWIFT_PACKAGE=1\",\n            \"-DDEBUG=1\",\n            \"-fblocks\",\n            \"-I\", Pkg.appending(components: \"Sources\", \"lib\", \"include\").pathString,\n            \"-gdwarf\",\n        ]\n        XCTAssertEqual(try lib.basicArguments(isCXX: false), args)\n        XCTAssertEqual(try lib.objects, [buildPath.appending(components: \"lib.build\", \"lib.c.o\")])\n        XCTAssertEqual(lib.moduleMap, buildPath.appending(components: \"lib.build\", \"module.modulemap\"))\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(exe, [\n            \"-enable-batch-mode\",\n            \"-serialize-diagnostics\",\n            \"-Onone\",\n            \"-enable-testing\",\n            .equal(self.j),\n            \"-DSWIFT_PACKAGE\", \"-DDEBUG\", \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\",\n            \"-Xcc\", \"-fmodule-map-file=\\(buildPath.appending(components: \"lib.build\", \"module.modulemap\"))\",\n            \"-Xcc\", \"-I\", \"-Xcc\", \"\\(Pkg.appending(components: \"Sources\", \"lib\", \"include\"))\",\n            \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n            .anySequence,\n            \"-swift-version\", \"4\",\n            \"-g\",\n            \"-use-ld=lld\",\n            \"-Xcc\", \"-gdwarf\",\n            .end,\n        ])\n\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\", \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", \"x86_64-unknown-windows-msvc\",\n            \"-g\",\n            \"-use-ld=lld\",\n            \"-Xlinker\", \"-debug:dwarf\",\n        ])\n\n        let executablePathExtension = try result.buildProduct(for: \"exe\").binaryPath.extension\n        XCTAssertMatch(executablePathExtension, \"exe\")\n    }\n\n    func testEntrypointRenaming() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    toolsVersion: .v5_5,\n                    targets: [\n                        TargetDescription(name: \"exe\", type: .executable),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        func createResult(for triple: Basics.Triple) async throws -> BuildPlanResult {\n            try await BuildPlanResult(plan: mockBuildPlan(\n                triple: triple,\n                graph: graph,\n                driverParameters: .init(\n                    canRenameEntrypointFunctionName: true\n                ),\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n        }\n        let supportingTriples: [Basics.Triple] = [.x86_64Linux, .x86_64MacOS, .x86_64Windows]\n        for triple in supportingTriples {\n            let result = try await createResult(for: triple)\n            let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n            XCTAssertMatch(exe, [\"-Xfrontend\", \"-entry-point-function-name\", \"-Xfrontend\", \"exe_main\"])\n            let linkExe = try result.buildProduct(for: \"exe\").linkArguments()\n            XCTAssertMatch(linkExe, [.contains(\"exe_main\")])\n        }\n\n        let unsupportingTriples: [Basics.Triple] = [.wasi]\n        for triple in unsupportingTriples {\n            let result = try await createResult(for: triple)\n            let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n            XCTAssertNoMatch(exe, [\"-entry-point-function-name\"])\n        }\n    }\n\n    func testIndexStore() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.c\",\n            \"/Pkg/Sources/lib/include/lib.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        func check(for mode: BuildParameters.IndexStoreMode, config: BuildConfiguration) async throws {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                config: config,\n                toolchain: try UserToolchain.default,\n                graph: graph,\n                indexStoreMode: mode,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            let lib = try result.moduleBuildDescription(for: \"lib\").clang()\n            let path = StringPattern.equal(result.plan.destinationBuildParameters.indexStore.pathString)\n\n            XCTAssertMatch(\n                try lib.basicArguments(isCXX: false),\n                [.anySequence, \"-index-store-path\", path, .anySequence]\n            )\n\n            let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n            XCTAssertMatch(exe, [.anySequence, \"-index-store-path\", path, .anySequence])\n        }\n\n        try await check(for: .auto, config: .debug)\n        try await check(for: .on, config: .debug)\n        try await check(for: .on, config: .release)\n    }\n\n    func testPlatforms() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/foo.swift\",\n            \"/B/Sources/BTarget/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"10.13\"),\n                    ],\n                    toolsVersion: .v5,\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BLibrary\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"10.12\"),\n                    ],\n                    toolsVersion: .v5,\n                    products: [\n                        ProductDescription(name: \"BLibrary\", type: .library(.automatic), targets: [\"BTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n\n        let aTarget = try result.moduleBuildDescription(for: \"ATarget\").swift().compileArguments()\n        #if os(macOS)\n        XCTAssertMatch(\n            aTarget,\n            [.equal(\"-target\"), .equal(hostTriple.tripleString(forPlatformVersion: \"10.13\")), .anySequence]\n        )\n        #else\n        XCTAssertMatch(aTarget, [.equal(\"-target\"), .equal(defaultTargetTriple), .anySequence])\n        #endif\n\n        let bTarget = try result.moduleBuildDescription(for: \"BTarget\").swift().compileArguments()\n        #if os(macOS)\n        XCTAssertMatch(\n            bTarget,\n            [.equal(\"-target\"), .equal(hostTriple.tripleString(forPlatformVersion: \"10.13\")), .anySequence]\n        )\n        #else\n        XCTAssertMatch(bTarget, [.equal(\"-target\"), .equal(defaultTargetTriple), .anySequence])\n        #endif\n    }\n\n    func testPlatformsCustomTriple() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/foo.swift\",\n            \"/B/Sources/BTarget/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    platforms: [\n                        PlatformDescription(name: \"ios\", version: \"11.0\"),\n                        PlatformDescription(name: \"macos\", version: \"10.13\"),\n                    ],\n                    toolsVersion: .v5,\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BLibrary\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    platforms: [\n                        PlatformDescription(name: \"ios\", version: \"10.0\"),\n                        PlatformDescription(name: \"macos\", version: \"10.12\"),\n                    ],\n                    toolsVersion: .v5,\n                    products: [\n                        ProductDescription(name: \"BLibrary\", type: .library(.automatic), targets: [\"BTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: .init(\"arm64-apple-ios\"),\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n\n        let targetTriple = Triple.arm64iOS\n\n        let aTarget = try result.moduleBuildDescription(for: \"ATarget\").swift().compileArguments()\n        let expectedVersion = Platform.iOS.oldestSupportedVersion.versionString\n\n        XCTAssertMatch(aTarget, [\n            .equal(\"-target\"),\n            .equal(targetTriple.tripleString(forPlatformVersion: expectedVersion)),\n            .anySequence,\n        ])\n\n        let bTarget = try result.moduleBuildDescription(for: \"BTarget\").swift().compileArguments()\n        XCTAssertMatch(bTarget, [\n            .equal(\"-target\"),\n            .equal(targetTriple.tripleString(forPlatformVersion: expectedVersion)),\n            .anySequence,\n        ])\n    }\n\n    func testPlatformsValidationComparesSpecifiedDarwinTriple() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/foo.swift\",\n            \"/B/Sources/BTarget/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"10.13\"),\n                        PlatformDescription(name: \"ios\", version: \"10\"),\n                    ],\n                    toolsVersion: .v5,\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BLibrary\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"10.14\"),\n                        PlatformDescription(name: \"ios\", version: \"10\"),\n                    ],\n                    toolsVersion: .v5,\n                    products: [\n                        ProductDescription(name: \"BLibrary\", type: .library(.automatic), targets: [\"BTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        // macOS versions are different (thus incompatible),\n        // however our build triple *only specifies* `iOS`.\n        // Therefore, we expect no error, as the iOS version\n        // constraints above are valid.\n\n        _ = try await mockBuildPlan(\n            triple: .arm64iOS,\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        )\n\n\n        // For completeness, the invalid target should still throw an error.\n        do {\n            _ = try await mockBuildPlan(\n                triple: .x86_64MacOS,\n                graph: graph,\n                fileSystem: fileSystem,\n                observabilityScope: observability.topScope\n            )\n            XCTFail()\n        } catch Diagnostics.fatalError {\n        } catch {\n            XCTFail()\n        }\n\n        testDiagnostics(observability.diagnostics) { result in\n            let diagnosticMessage = \"\"\"\n            the library 'ATarget' requires macos 10.13, but depends on the product 'BLibrary' which requires macos 10.14; \\\n            consider changing the library 'ATarget' to require macos 10.14 or later, or the product 'BLibrary' to require \\\n            macos 10.13 or earlier.\n            \"\"\"\n            result.check(diagnostic: .contains(diagnosticMessage), severity: .error)\n        }\n    }\n\n    func testPlatformsValidationWhenADependencyRequiresHigherOSVersionThanPackage() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/foo.swift\",\n            \"/B/Sources/BTarget/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"10.13\"),\n                    ],\n                    toolsVersion: .v5,\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BLibrary\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"10.14\"),\n                    ],\n                    toolsVersion: .v5,\n                    products: [\n                        ProductDescription(name: \"BLibrary\", type: .library(.automatic), targets: [\"BTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        do {\n            _ = try await mockBuildPlan(\n                triple: .x86_64MacOS,\n                graph: graph,\n                fileSystem: fileSystem,\n                observabilityScope: observability.topScope\n            )\n            XCTFail()\n        } catch Diagnostics.fatalError {\n        } catch {\n            XCTFail()\n        }\n\n        testDiagnostics(observability.diagnostics) { result in\n            let diagnosticMessage = \"\"\"\n            the library 'ATarget' requires macos 10.13, but depends on the product 'BLibrary' which requires macos 10.14; \\\n            consider changing the library 'ATarget' to require macos 10.14 or later, or the product 'BLibrary' to require \\\n            macos 10.13 or earlier.\n            \"\"\"\n            result.check(diagnostic: .contains(diagnosticMessage), severity: .error)\n        }\n    }\n\n    func testBuildSettings() async throws {\n        let A = AbsolutePath(\"/A\")\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/exe/main.swift\",\n            \"/A/Sources/bar/bar.swift\",\n            \"/A/Sources/cbar/barcpp.cpp\",\n            \"/A/Sources/cbar/bar.c\",\n            \"/A/Sources/cbar/include/bar.h\",\n            \"/A/Tests/MySwiftTests/test.swift\",\n\n            \"/B/Sources/t1/dep.swift\",\n            \"/B/Sources/t2/dep.swift\",\n            \"<end>\"\n        )\n\n        let aManifest = try Manifest.createRootManifest(\n            displayName: \"A\",\n            path: \"/A\",\n            toolsVersion: .v5,\n            cxxLanguageStandard: \"c++17\",\n            dependencies: [\n                .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            ],\n            targets: [\n                TargetDescription(\n                    name: \"cbar\",\n                    settings: [\n                        .init(tool: .c, kind: .headerSearchPath(\"Sources/headers\")),\n                        .init(tool: .cxx, kind: .headerSearchPath(\"Sources/cppheaders\")),\n                        .init(tool: .c, kind: .define(\"CCC=2\")),\n                        .init(tool: .cxx, kind: .define(\"RCXX\"), condition: .init(config: \"release\")),\n                        .init(tool: .linker, kind: .linkedFramework(\"best\")),\n                        .init(tool: .c, kind: .unsafeFlags([\"-Icfoo\", \"-L\", \"cbar\"])),\n                        .init(tool: .cxx, kind: .unsafeFlags([\"-Icxxfoo\", \"-L\", \"cxxbar\"])),\n                    ]\n                ),\n                TargetDescription(\n                    name: \"bar\", dependencies: [\"cbar\", \"Dep\"],\n                    settings: [\n                        .init(tool: .swift, kind: .define(\"LINUX\"), condition: .init(platformNames: [\"linux\"])),\n                        .init(\n                            tool: .swift,\n                            kind: .define(\"RLINUX\"),\n                            condition: .init(platformNames: [\"linux\"], config: \"release\")\n                        ),\n                        .init(\n                            tool: .swift,\n                            kind: .define(\"DMACOS\"),\n                            condition: .init(platformNames: [\"macos\"], config: \"debug\")\n                        ),\n                        .init(tool: .swift, kind: .unsafeFlags([\"-Isfoo\", \"-L\", \"sbar\"])),\n                        .init(\n                            tool: .swift,\n                            kind: .interoperabilityMode(.Cxx),\n                            condition: .init(platformNames: [\"linux\"])\n                        ),\n                        .init(\n                            tool: .swift,\n                            kind: .interoperabilityMode(.Cxx),\n                            condition: .init(platformNames: [\"macos\"])\n                        ),\n                        .init(tool: .swift, kind: .enableUpcomingFeature(\"BestFeature\")),\n                        .init(\n                            tool: .swift,\n                            kind: .enableUpcomingFeature(\"WorstFeature\"),\n                            condition: .init(platformNames: [\"macos\"], config: \"debug\")\n                        ),\n                        .init(tool: .swift, kind: .strictMemorySafety),\n                        .init(tool: .swift, kind: .defaultIsolation(.MainActor)),\n                    ]\n                ),\n                TargetDescription(\n                    name: \"exe\", dependencies: [\"bar\"],\n                    settings: [\n                        .init(tool: .swift, kind: .define(\"FOO\")),\n                        .init(\n                            tool: .swift,\n                            kind: .interoperabilityMode(.C),\n                            condition: .init(platformNames: [\"linux\"])\n                        ),\n                        .init(\n                            tool: .swift,\n                            kind: .interoperabilityMode(.Cxx),\n                            condition: .init(platformNames: [\"macos\"])\n                        ),\n                        .init(\n                            tool: .swift,\n                            kind: .swiftLanguageMode(.v4),\n                            condition: .init(platformNames: [\"macos\"])\n                        ),\n                        .init(\n                            tool: .swift,\n                            kind: .swiftLanguageMode(.v5),\n                            condition: .init(platformNames: [\"linux\"])\n                        ),\n                        .init(tool: .linker, kind: .linkedLibrary(\"sqlite3\")),\n                        .init(\n                            tool: .linker,\n                            kind: .linkedFramework(\"CoreData\"),\n                            condition: .init(platformNames: [\"macos\"])\n                        ),\n                        .init(tool: .linker, kind: .unsafeFlags([\"-Ilfoo\", \"-L\", \"lbar\"])),\n                        .init(tool: .swift, kind: .defaultIsolation(.nonisolated)),\n                    ]\n                ),\n                TargetDescription(\n                    name: \"MySwiftTests\", type: .test,\n                    settings: [\n                        .init(tool: .swift, kind: .interoperabilityMode(.Cxx)),\n                    ]\n                ),\n            ]\n        )\n\n        let bManifest = try Manifest.createFileSystemManifest(\n            displayName: \"B\",\n            path: \"/B\",\n            toolsVersion: .v5,\n            products: [\n                ProductDescription(name: \"Dep\", type: .library(.automatic), targets: [\"t1\", \"t2\"]),\n            ],\n            targets: [\n                TargetDescription(\n                    name: \"t1\",\n                    settings: [\n                        .init(tool: .swift, kind: .define(\"DEP\")),\n                        .init(tool: .swift, kind: .swiftLanguageMode(.v4), condition: .init(platformNames: [\"linux\"])),\n                        .init(tool: .swift, kind: .swiftLanguageMode(.v5), condition: .init(platformNames: [\"macos\"])),\n                        .init(tool: .linker, kind: .linkedLibrary(\"libz\")),\n                    ]\n                ),\n                TargetDescription(\n                    name: \"t2\",\n                    settings: [\n                        .init(tool: .linker, kind: .linkedLibrary(\"libz\")),\n                    ]\n                ),\n            ]\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [aManifest, bManifest],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        func createResult(for dest: Basics.Triple) async throws -> BuildPlanResult {\n            try await BuildPlanResult(plan: mockBuildPlan(\n                triple: dest,\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n        }\n\n        do {\n            let result = try await createResult(for: .x86_64Linux)\n\n            let dep = try result.moduleBuildDescription(for: \"t1\").swift().compileArguments()\n            XCTAssertMatch(dep, [.anySequence, \"-DDEP\", .anySequence])\n            XCTAssertMatch(dep, [.anySequence, \"-swift-version\", \"4\", .anySequence])\n\n            let cbar = try result.moduleBuildDescription(for: \"cbar\").clang().basicArguments(isCXX: false)\n            XCTAssertMatch(\n                cbar,\n                [\n                    .anySequence,\n                    \"-DCCC=2\",\n                    \"-I\\(A.appending(components: \"Sources\", \"cbar\", \"Sources\", \"headers\"))\",\n                    \"-I\\(A.appending(components: \"Sources\", \"cbar\", \"Sources\", \"cppheaders\"))\",\n                    \"-Icfoo\",\n                    \"-L\", \"cbar\",\n                    \"-Icxxfoo\",\n                    \"-L\", \"cxxbar\",\n                    \"-g\",\n                    \"-fno-omit-frame-pointer\",\n                    .end,\n                ]\n            )\n\n            let bar = try result.moduleBuildDescription(for: \"bar\").swift().compileArguments()\n            XCTAssertMatch(\n                bar,\n                [\n                    .anySequence,\n                    \"-swift-version\", \"5\",\n                    \"-DLINUX\",\n                    \"-Isfoo\",\n                    \"-L\", \"sbar\",\n                    \"-cxx-interoperability-mode=default\",\n                    \"-Xcc\", \"-std=c++17\",\n                    \"-enable-upcoming-feature\", \"BestFeature\",\n                    \"-strict-memory-safety\",\n                    \"-default-isolation\", \"MainActor\",\n                    \"-g\",\n                    \"-Xcc\", \"-g\",\n                    \"-Xcc\", \"-fno-omit-frame-pointer\",\n                    .end,\n                ]\n            )\n\n            let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n            XCTAssertMatch(exe, [.anySequence, \"-swift-version\", \"5\", \"-DFOO\", \"-default-isolation\", \"nonisolated\", \"-g\", \"-Xcc\", \"-g\", \"-Xcc\", \"-fno-omit-frame-pointer\", .end])\n\n            let linkExe = try result.buildProduct(for: \"exe\").linkArguments()\n            XCTAssertMatch(linkExe, [.anySequence, \"-lsqlite3\", \"-llibz\", \"-Ilfoo\", \"-L\", \"lbar\", \"-g\", .end])\n\n            let testDiscovery = try result.moduleBuildDescription(for: \"APackageDiscoveredTests\").swift().compileArguments()\n            XCTAssertMatch(testDiscovery, [.anySequence, \"-cxx-interoperability-mode=default\", \"-Xcc\", \"-std=c++17\"])\n\n            let testEntryPoint = try result.moduleBuildDescription(for: \"APackageTests\").swift().compileArguments()\n            XCTAssertMatch(testEntryPoint, [.anySequence, \"-cxx-interoperability-mode=default\", \"-Xcc\", \"-std=c++17\"])\n        }\n\n        // omit frame pointers explicitly set to true\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                triple: .x86_64Linux,\n                graph: graph,\n                omitFramePointers: true,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            let dep = try result.moduleBuildDescription(for: \"t1\").swift().compileArguments()\n            XCTAssertMatch(dep, [.anySequence, \"-DDEP\", .anySequence])\n\n            let cbar = try result.moduleBuildDescription(for: \"cbar\").clang().basicArguments(isCXX: false)\n            XCTAssertMatch(\n                cbar,\n                [\n                    .anySequence,\n                    \"-DCCC=2\",\n                    \"-I\\(A.appending(components: \"Sources\", \"cbar\", \"Sources\", \"headers\"))\",\n                    \"-I\\(A.appending(components: \"Sources\", \"cbar\", \"Sources\", \"cppheaders\"))\",\n                    \"-Icfoo\",\n                    \"-L\", \"cbar\",\n                    \"-Icxxfoo\",\n                    \"-L\", \"cxxbar\",\n                    \"-g\",\n                    \"-fomit-frame-pointer\",\n                    .end,\n                ]\n            )\n\n            let bar = try result.moduleBuildDescription(for: \"bar\").swift().compileArguments()\n            XCTAssertMatch(\n                bar,\n                [\n                    .anySequence,\n                    \"-swift-version\", \"5\",\n                    \"-DLINUX\",\n                    \"-Isfoo\",\n                    \"-L\", \"sbar\",\n                    \"-cxx-interoperability-mode=default\",\n                    \"-Xcc\", \"-std=c++17\",\n                    \"-enable-upcoming-feature\",\n                    \"BestFeature\",\n                    \"-strict-memory-safety\",\n                    \"-default-isolation\", \"MainActor\",\n                    \"-g\",\n                    \"-Xcc\", \"-g\",\n                    \"-Xcc\", \"-fomit-frame-pointer\",\n                    .end,\n                ]\n            )\n\n            let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n            XCTAssertMatch(exe, [.anySequence, \"-swift-version\", \"5\", \"-DFOO\", \"-default-isolation\", \"nonisolated\", \"-g\", \"-Xcc\", \"-g\", \"-Xcc\", \"-fomit-frame-pointer\", .end])\n        }\n\n        // omit frame pointers explicitly set to false\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                triple: .x86_64Linux,\n                graph: graph,\n                omitFramePointers: false,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            let dep = try result.moduleBuildDescription(for: \"t1\").swift().compileArguments()\n            XCTAssertMatch(dep, [.anySequence, \"-DDEP\", .anySequence])\n\n            let cbar = try result.moduleBuildDescription(for: \"cbar\").clang().basicArguments(isCXX: false)\n            XCTAssertMatch(\n                cbar,\n                [\n                    .anySequence,\n                    \"-DCCC=2\",\n                    \"-I\\(A.appending(components: \"Sources\", \"cbar\", \"Sources\", \"headers\"))\",\n                    \"-I\\(A.appending(components: \"Sources\", \"cbar\", \"Sources\", \"cppheaders\"))\",\n                    \"-Icfoo\",\n                    \"-L\", \"cbar\",\n                    \"-Icxxfoo\",\n                    \"-L\", \"cxxbar\",\n                    \"-g\",\n                    \"-fno-omit-frame-pointer\",\n                    .end,\n                ]\n            )\n\n            let bar = try result.moduleBuildDescription(for: \"bar\").swift().compileArguments()\n            XCTAssertMatch(\n                bar,\n                [\n                    .anySequence,\n                    \"-swift-version\", \"5\",\n                    \"-DLINUX\",\n                    \"-Isfoo\",\n                    \"-L\", \"sbar\",\n                    \"-cxx-interoperability-mode=default\",\n                    \"-Xcc\", \"-std=c++17\",\n                    \"-enable-upcoming-feature\",\n                    \"BestFeature\",\n                    \"-strict-memory-safety\",\n                    \"-default-isolation\", \"MainActor\",\n                    \"-g\",\n                    \"-Xcc\", \"-g\",\n                    \"-Xcc\", \"-fno-omit-frame-pointer\",\n                    .end,\n                ]\n            )\n\n            let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n            XCTAssertMatch(exe, [.anySequence, \"-swift-version\", \"5\", \"-DFOO\", \"-default-isolation\", \"nonisolated\", \"-g\", \"-Xcc\", \"-g\", \"-Xcc\", \"-fno-omit-frame-pointer\", .end])\n        }\n\n        do {\n            let result = try await createResult(for: .x86_64MacOS)\n\n            let cbar = try result.moduleBuildDescription(for: \"cbar\").clang().basicArguments(isCXX: false)\n            XCTAssertMatch(\n                cbar,\n                [\n                    .anySequence,\n                    \"-DCCC=2\",\n                    \"-I\\(A.appending(components: \"Sources\", \"cbar\", \"Sources\", \"headers\"))\",\n                    \"-I\\(A.appending(components: \"Sources\", \"cbar\", \"Sources\", \"cppheaders\"))\",\n                    \"-Icfoo\",\n                    \"-L\", \"cbar\",\n                    \"-Icxxfoo\",\n                    \"-L\", \"cxxbar\",\n                    \"-g\",\n                    .end,\n                ]\n            )\n\n            let bar = try result.moduleBuildDescription(for: \"bar\").swift().compileArguments()\n            XCTAssertMatch(\n                bar,\n                [\n                    .anySequence,\n                    \"-swift-version\", \"5\",\n                    \"-DDMACOS\",\n                    \"-Isfoo\",\n                    \"-L\", \"sbar\",\n                    \"-cxx-interoperability-mode=default\",\n                    \"-Xcc\", \"-std=c++17\",\n                    \"-enable-upcoming-feature\", \"BestFeature\",\n                    \"-enable-upcoming-feature\", \"WorstFeature\",\n                    \"-strict-memory-safety\",\n                    \"-default-isolation\", \"MainActor\",\n                    \"-g\",\n                    \"-Xcc\", \"-g\",\n                    .end,\n                ]\n            )\n\n            let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n            XCTAssertMatch(\n                exe,\n                [\n                    .anySequence,\n                    \"-swift-version\", \"4\",\n                    \"-DFOO\",\n                    \"-cxx-interoperability-mode=default\",\n                    \"-Xcc\", \"-std=c++17\",\n                    \"-default-isolation\", \"nonisolated\",\n                    \"-g\",\n                    \"-Xcc\", \"-g\",\n                    .end,\n                ]\n            )\n\n            let linkExe = try result.buildProduct(for: \"exe\").linkArguments()\n            XCTAssertMatch(\n                linkExe,\n                [\n                    .anySequence,\n                    \"-lsqlite3\",\n                    \"-llibz\",\n                    \"-framework\", \"CoreData\",\n                    \"-framework\", \"best\",\n                    \"-Ilfoo\",\n                    \"-L\", \"lbar\",\n                    .anySequence,\n                ]\n            )\n        }\n    }\n\n    func testWarningLevelSettings() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"swiftLib\", \"lib.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"cLib\", \"lib.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"cLib\", \"include\", \"lib.h\").pathString,\n            Pkg.appending(components: \"Sources\", \"cxxLib\", \"lib.cpp\").pathString,\n            Pkg.appending(components: \"Sources\", \"cxxLib\", \"include\", \"lib.h\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    toolsVersion: .v6_2,\n                    targets: [\n                        TargetDescription(\n                            name: \"swiftLib\",\n                            dependencies: [],\n                            settings: [\n                                .init(tool: .swift, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                                .init(tool: .swift, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .warning), condition: .init(config: \"debug\")),\n                                .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .error), condition: .init(config: \"release\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"cLib\",\n                            dependencies: [],\n                            settings: [\n                                .init(tool: .c, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                                .init(tool: .c, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .c, kind: .treatWarning(\"deprecated-declarations\", .warning), condition: .init(config: \"debug\")),\n                                .init(tool: .c, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"cxxLib\",\n                            dependencies: [],\n                            settings: [\n                                .init(tool: .cxx, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                                .init(tool: .cxx, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .warning), condition: .init(config: \"debug\")),\n                                .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                            ]\n                        )\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        // Test debug configuration\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: BuildEnvironment(platform: .macOS, configuration: .debug),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            // Check Swift warning treatment flags\n            let swiftLib = try result.moduleBuildDescription(for: \"swiftLib\").swift().compileArguments()\n            XCTAssertMatch(swiftLib, [.anySequence, \"-no-warnings-as-errors\", \"-Wwarning\", \"DeprecatedDeclaration\", .anySequence])\n\n            // Check C warning treatment flags\n            let cLib = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n            XCTAssertMatch(cLib, [.anySequence, \"-Wno-error\", \"-Wno-error=deprecated-declarations\", .anySequence])\n\n            // Check C++ warning treatment flags\n            let cxxLib = try result.moduleBuildDescription(for: \"cxxLib\").clang().basicArguments(isCXX: true)\n            XCTAssertMatch(cxxLib, [.anySequence, \"-Wno-error\", \"-Wno-error=deprecated-declarations\", .anySequence])\n        }\n\n        // Test release configuration\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: BuildEnvironment(platform: .macOS, configuration: .release),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            // Check Swift warning treatment flags\n            let swiftLib = try result.moduleBuildDescription(for: \"swiftLib\").swift().compileArguments()\n            XCTAssertMatch(swiftLib, [.anySequence, \"-warnings-as-errors\", \"-Werror\", \"DeprecatedDeclaration\", .anySequence])\n\n            // Check C warning treatment flags\n            let cLib = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n            XCTAssertMatch(cLib, [.anySequence, \"-Werror\", \"-Werror=deprecated-declarations\", .anySequence])\n\n            // Check C++ warning treatment flags\n            let cxxLib = try result.moduleBuildDescription(for: \"cxxLib\").clang().basicArguments(isCXX: true)\n            XCTAssertMatch(cxxLib, [.anySequence, \"-Werror\", \"-Werror=deprecated-declarations\", .anySequence])\n        }\n    }\n\n    func testEnableDisableWarningSettings() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"cLib\", \"lib.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"cLib\", \"include\", \"lib.h\").pathString,\n            Pkg.appending(components: \"Sources\", \"cxxLib\", \"lib.cpp\").pathString,\n            Pkg.appending(components: \"Sources\", \"cxxLib\", \"include\", \"lib.h\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    toolsVersion: .v6_2,\n                    targets: [\n                        TargetDescription(\n                            name: \"cLib\",\n                            dependencies: [],\n                            settings: [\n                                .init(tool: .c, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                                .init(tool: .c, kind: .disableWarning(\"unused-parameter\"), condition: .init(config: \"release\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"cxxLib\",\n                            dependencies: [],\n                            settings: [\n                                .init(tool: .cxx, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                                .init(tool: .cxx, kind: .disableWarning(\"unused-parameter\"), condition: .init(config: \"release\")),\n                            ]\n                        )\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        // Test debug configuration\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: BuildEnvironment(platform: .macOS, configuration: .debug),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            // Check C flags\n            let cLib = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n            XCTAssertMatch(cLib, [.anySequence, \"-Wimplicit-fallthrough\", .anySequence])\n\n            // Check C++ flags\n            let cxxLib = try result.moduleBuildDescription(for: \"cxxLib\").clang().basicArguments(isCXX: true)\n            XCTAssertMatch(cxxLib, [.anySequence, \"-Wimplicit-fallthrough\", .anySequence])\n        }\n\n        // Test release configuration\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: BuildEnvironment(platform: .macOS, configuration: .release),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            // Check C flags\n            let cLib = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n            XCTAssertMatch(cLib, [.anySequence, \"-Wno-unused-parameter\", .anySequence])\n\n            // Check C++ flags\n            let cxxLib = try result.moduleBuildDescription(for: \"cxxLib\").clang().basicArguments(isCXX: true)\n            XCTAssertMatch(cxxLib, [.anySequence, \"-Wno-unused-parameter\", .anySequence])\n        }\n    }\n\n    func testWarningSettingsInRemotePackage() async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n        let RootPkg: AbsolutePath = \"/RootPkg\"\n\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            RootPkg.appending(components: \"Sources\", \"swiftTarget\", \"target.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"swiftLib\", \"lib.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"cLib\", \"lib.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"cLib\", \"include\", \"lib.h\").pathString,\n            Pkg.appending(components: \"Sources\", \"cxxLib\", \"lib.cpp\").pathString,\n            Pkg.appending(components: \"Sources\", \"cxxLib\", \"include\", \"lib.h\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"RootPkg\",\n                    path: .init(validating: RootPkg.pathString),\n                    toolsVersion: .v6_2,\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://example.com/ext/pkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"swiftTarget\",\n                            dependencies: [\n                                .product(name: \"swiftLib\", package: \"pkg\"),\n                                .product(name: \"cLib\", package: \"pkg\"),\n                                .product(name: \"cxxLib\", package: \"pkg\"),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRemoteSourceControlManifest(\n                    displayName: \"Pkg\",\n                    url: \"https://example.com/ext/pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    toolsVersion: .v6_2,\n                    products: [\n                        ProductDescription(name: \"swiftLib\", type: .library(.static), targets: [\"swiftLib\"]),\n                        ProductDescription(name: \"cLib\", type: .library(.static), targets: [\"cLib\"]),\n                        ProductDescription(name: \"cxxLib\", type: .library(.static), targets: [\"cxxLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"swiftLib\",\n                            settings: [\n                                .init(tool: .swift, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                                .init(tool: .swift, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .warning), condition: .init(config: \"debug\")),\n                                .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .error), condition: .init(config: \"release\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"cLib\",\n                            settings: [\n                                .init(tool: .c, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                                .init(tool: .c, kind: .disableWarning(\"unused-parameter\"), condition: .init(config: \"release\")),\n                                .init(tool: .c, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                                .init(tool: .c, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .c, kind: .treatWarning(\"deprecated-declarations\", .warning), condition: .init(config: \"debug\")),\n                                .init(tool: .c, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"cxxLib\",\n                            settings: [\n                                .init(tool: .cxx, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                                .init(tool: .cxx, kind: .disableWarning(\"unused-parameter\"), condition: .init(config: \"release\")),\n                                .init(tool: .cxx, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                                .init(tool: .cxx, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .warning), condition: .init(config: \"debug\")),\n                                .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                            ]\n                        )\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let swiftWarningControlFlags: [StringPattern] = [\n            \"DeprecatedDeclaration\",\n            \"-no-warnings-as-errors\",\n            \"-warnings-as-errors\",\n            \"-Wwarning\",\n            \"-Werror\",\n        ]\n        let clangWarningControlFlags: [StringPattern] = [\n            \"-Wno-error\",\n            \"-Werror\",\n            .prefix(\"-Wno-error=\"),\n            .prefix(\"-Werror=\"),\n            .prefix(\"-W\"),\n            .prefix(\"-Wno-\"),\n        ]\n\n        // Test debug configuration\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: BuildEnvironment(platform: .macOS, configuration: .debug),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            // Check Swift warning treatment flags\n            let swiftLib = try result.moduleBuildDescription(for: \"swiftLib\").swift().compileArguments()\n            for pattern in swiftWarningControlFlags {\n                XCTAssertNoMatch(swiftLib, [.anySequence, pattern, .anySequence])\n            }\n            XCTAssertMatch(swiftLib, [.anySequence, \"-suppress-warnings\", .anySequence])\n\n            // Check C warning treatment flags\n            let cLib = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n            for pattern in clangWarningControlFlags {\n                XCTAssertNoMatch(cLib, [.anySequence, pattern, .anySequence])\n            }\n            XCTAssertMatch(cLib, [.anySequence, \"-w\", .anySequence])\n\n            // Check C++ warning treatment flags\n            let cxxLib = try result.moduleBuildDescription(for: \"cxxLib\").clang().basicArguments(isCXX: true)\n            for pattern in clangWarningControlFlags {\n                XCTAssertNoMatch(cxxLib, [.anySequence, pattern, .anySequence])\n            }\n            XCTAssertMatch(cxxLib, [.anySequence, \"-w\", .anySequence])\n        }\n\n        // Test release configuration\n        do {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                environment: BuildEnvironment(platform: .macOS, configuration: .release),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            // Check Swift warning treatment flags\n            let swiftLib = try result.moduleBuildDescription(for: \"swiftLib\").swift().compileArguments()\n            for pattern in swiftWarningControlFlags {\n                XCTAssertNoMatch(swiftLib, [.anySequence, pattern, .anySequence])\n            }\n            XCTAssertMatch(swiftLib, [.anySequence, \"-suppress-warnings\", .anySequence])\n\n            // Check C warning treatment flags\n            let cLib = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n            for pattern in clangWarningControlFlags {\n                XCTAssertNoMatch(cLib, [.anySequence, pattern, .anySequence])\n            }\n            XCTAssertMatch(cLib, [.anySequence, \"-w\", .anySequence])\n\n            // Check C++ warning treatment flags\n            let cxxLib = try result.moduleBuildDescription(for: \"cxxLib\").clang().basicArguments(isCXX: true)\n            for pattern in clangWarningControlFlags {\n                XCTAssertNoMatch(cxxLib, [.anySequence, pattern, .anySequence])\n            }\n            XCTAssertMatch(cxxLib, [.anySequence, \"-w\", .anySequence])\n        }\n    }\n\n    func testExtraBuildFlags() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/exe/main.swift\",\n            \"<end>\"\n        )\n\n        let aManifest = try Manifest.createRootManifest(\n            displayName: \"A\",\n            path: \"/A\",\n            toolsVersion: .v5,\n            targets: [\n                TargetDescription(name: \"exe\", dependencies: []),\n            ]\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [aManifest],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        var flags = BuildFlags()\n        flags.linkerFlags = [\"-L\", \"/path/to/foo\", \"-L/path/to/foo\", \"-rpath=foo\", \"-rpath\", \"foo\"].constructBuildFlags(source: nil)\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            commonFlags: flags,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        let exe = try result.buildProduct(for: \"exe\").linkArguments()\n        XCTAssertMatch(\n            exe,\n            [\n                .anySequence,\n                \"-L\", \"/path/to/foo\",\n                \"-L/path/to/foo\",\n                \"-Xlinker\", \"-rpath=foo\",\n                \"-Xlinker\", \"-rpath\",\n                \"-Xlinker\", \"foo\",\n            ]\n        )\n    }\n\n    func testUserToolchainCompileFlags() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.c\",\n            \"/Pkg/Sources/lib/include/lib.h\"\n        )\n        try fs.createMockToolchain()\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    products: [\n                        ProductDescription(name: \"exe\", type: .executable, targets: [\"exe\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let userSwiftSDK = try SwiftSDK(\n            hostTriple: .arm64Linux,\n            targetTriple: .wasi,\n            toolset: .init(\n                knownTools: [\n                    .cCompiler: .init(extraCLIOptions: [\"-I/fake/sdk/sysroot\", \"-clang-flag-from-json\"]),\n                    .swiftCompiler: .init(extraCLIOptions: [\"-use-ld=lld\", \"-swift-flag-from-json\"]),\n                ],\n                rootPaths: UserToolchain.mockHostToolchain(fs).swiftSDK.toolset.rootPaths\n            ),\n            pathsConfiguration: .init(\n                sdkRootPath: \"/fake/sdk\",\n                swiftResourcesPath: \"/fake/lib/swift\",\n                swiftStaticResourcesPath: \"/fake/lib/swift_static\"\n            )\n        )\n\n        let env = Environment.mockEnvironment\n        let mockToolchain = try UserToolchain(\n            swiftSDK: userSwiftSDK,\n            environment: env,\n            searchStrategy: .custom(\n                searchPaths: getEnvSearchPaths(\n                    pathString: env[.path],\n                    currentWorkingDirectory: fs.currentWorkingDirectory\n                ),\n                useXcrun: true\n            ),\n            customTargetInfo: UserToolchain.mockTargetInfo,\n            fileSystem: fs\n        )\n        let commonFlags = BuildFlags(\n            cCompilerFlags: [BuildFlag(value: \"-clang-command-line-flag\", source: nil)],\n            swiftCompilerFlags: [BuildFlag(value: \"-swift-command-line-flag\", source: nil)]\n        )\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            toolchain: mockToolchain,\n            graph: graph,\n            commonFlags: commonFlags,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let lib = try result.moduleBuildDescription(for: \"lib\").clang()\n        var args: [StringPattern] = [.anySequence]\n        args += [\"--sysroot\"]\n        args += [\n            \"\\(userSwiftSDK.pathsConfiguration.sdkRootPath!)\",\n            \"-I/fake/sdk/sysroot\",\n            \"-clang-flag-from-json\",\n            .anySequence,\n            \"-clang-command-line-flag\",\n        ]\n        XCTAssertMatch(try lib.basicArguments(isCXX: false), args)\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(exe, [\n            \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\",\n            .anySequence,\n            \"-resource-dir\", \"\\(AbsolutePath(\"/fake/lib/swift\"))\",\n            .anySequence,\n            \"-swift-flag-from-json\",\n            .anySequence,\n            \"-swift-command-line-flag\",\n            .anySequence,\n            \"-Xcc\", \"-clang-flag-from-json\",\n            .anySequence,\n            \"-Xcc\", \"-clang-command-line-flag\",\n        ])\n\n        let exeProduct = try result.buildProduct(for: \"exe\").linkArguments()\n        XCTAssertMatch(exeProduct, [\n            .anySequence,\n            \"-resource-dir\", \"\\(AbsolutePath(\"/fake/lib/swift\"))\",\n            \"-Xclang-linker\", \"-resource-dir\",\n            \"-Xclang-linker\", \"\\(AbsolutePath(\"/fake/lib/swift/clang\"))\",\n            .anySequence,\n        ])\n\n        let staticResult = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: .x86_64Linux,\n            toolchain: mockToolchain,\n            graph: graph,\n            commonFlags: commonFlags,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        let staticExe = try staticResult.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(staticExe, [\n            .anySequence,\n            \"-resource-dir\", \"\\(AbsolutePath(\"/fake/lib/swift_static\"))\",\n            .anySequence,\n        ])\n\n        let staticExeProduct = try staticResult.buildProduct(for: \"exe\").linkArguments()\n        XCTAssertMatch(staticExeProduct, [\n            .anySequence,\n            \"-resource-dir\", \"\\(AbsolutePath(\"/fake/lib/swift_static\"))\",\n            \"-Xclang-linker\", \"-resource-dir\",\n            \"-Xclang-linker\", \"\\(AbsolutePath(\"/fake/lib/swift/clang\"))\",\n            .anySequence,\n        ])\n    }\n\n    func testSwiftTestingFlagsOnMacOSWithoutCustomToolchain() async throws {\n        #if !os(macOS)\n        // This is testing swift-testing in a toolchain which is macOS only feature.\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/fake/path/lib/swift/host/plugins/testing/libTestingMacros.dylib\",\n            \"/Pkg/Sources/Lib/main.swift\",\n            \"/Pkg/Tests/LibTest/test.swift\"\n        )\n        try fs.createMockToolchain()\n\n        let userSwiftSDK = SwiftSDK(\n            hostTriple: .x86_64MacOS,\n            targetTriple: .x86_64MacOS,\n            toolset: .init(\n                knownTools: [\n                    .cCompiler: .init(extraCLIOptions: []),\n                    .swiftCompiler: .init(extraCLIOptions: []),\n                ],\n                rootPaths: [\"/fake/path/to\"]\n            ),\n            pathsConfiguration: .init(\n                sdkRootPath: \"/fake/sdk\",\n                swiftResourcesPath: \"/fake/lib/swift\",\n                swiftStaticResourcesPath: \"/fake/lib/swift_static\"\n            )\n        )\n\n        let env = Environment.mockEnvironment\n        let mockToolchain = try UserToolchain(\n            swiftSDK: userSwiftSDK,\n            environment: env,\n            searchStrategy: .custom(\n                searchPaths: getEnvSearchPaths(\n                    pathString: env[.path],\n                    currentWorkingDirectory: fs.currentWorkingDirectory\n                ),\n                useXcrun: true\n            ),\n            customTargetInfo: UserToolchain.mockTargetInfo,\n            fileSystem: fs\n        )\n\n        XCTAssertEqual(\n            mockToolchain.extraFlags.swiftCompilerFlags.rawFlags,\n            [\n                \"-plugin-path\", \"/fake/path/lib/swift/host/plugins/testing\",\n                \"-sdk\", \"/fake/sdk\",\n            ]\n        )\n        XCTAssertNoMatch(mockToolchain.extraFlags.linkerFlags.rawFlags, [\"-rpath\"])\n        XCTAssertNoMatch(mockToolchain.extraFlags.swiftCompilerFlags.rawFlags, [\n            \"-I\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-L\", \"/fake/path/lib/swift/macosx/testing\",\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"Lib\", dependencies: []),\n                        TargetDescription(\n                            name: \"LibTest\",\n                            dependencies: [\"Lib\"],\n                            type: .test\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: mockToolchain.targetTriple,\n            toolchain: mockToolchain,\n            graph: graph,\n            commonFlags: .init(),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(2)\n        result.checkTargetsCount(3)\n\n        let testProductLinkArgs = try result.buildProduct(for: \"Lib\").linkArguments()\n        XCTAssertNoMatch(testProductLinkArgs, [\n            \"-I\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-L\", \"/fake/path/lib/swift/macosx/testing\",\n        ])\n\n        let libModuleArgs = try result.moduleBuildDescription(for: \"Lib\").swift().compileArguments()\n        XCTAssertMatch(libModuleArgs, [\n            \"-plugin-path\", \"/fake/path/lib/swift/host/plugins/testing\",\n        ])\n        XCTAssertNoMatch(libModuleArgs, [\"-Xlinker\"])\n        XCTAssertNoMatch(libModuleArgs, [\n            \"-I\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-L\", \"/fake/path/lib/swift/macosx/testing\",\n        ])\n\n        let testModuleArgs = try result.moduleBuildDescription(for: \"LibTest\").swift().compileArguments()\n        XCTAssertMatch(testModuleArgs, [\n            \"-plugin-path\", \"/fake/path/lib/swift/host/plugins/testing\",\n        ])\n        XCTAssertNoMatch(testModuleArgs, [\"-Xlinker\"])\n        XCTAssertNoMatch(testModuleArgs, [\n            \"-I\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-L\", \"/fake/path/lib/swift/macosx/testing\",\n        ])\n    }\n\n    func testSwiftTestingFlagsOnMacOSWithCustomToolchain() async throws {\n        #if !os(macOS)\n        // This is testing swift-testing in a toolchain which is macOS only feature.\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/fake/path/lib/swift/macosx/testing/Testing.swiftmodule\",\n            \"/fake/path/lib/swift/host/plugins/testing/libTestingMacros.dylib\",\n            \"/Pkg/Sources/Lib/main.swift\",\n            \"/Pkg/Tests/LibTest/test.swift\"\n        )\n        try fs.createMockToolchain()\n\n        let userSwiftSDK = SwiftSDK(\n            hostTriple: .x86_64MacOS,\n            targetTriple: .x86_64MacOS,\n            toolset: .init(\n                knownTools: [\n                    .cCompiler: .init(extraCLIOptions: []),\n                    .swiftCompiler: .init(extraCLIOptions: []),\n                ],\n                rootPaths: [\"/fake/path/to\"]\n            ),\n            pathsConfiguration: .init(\n                sdkRootPath: \"/fake/sdk\",\n                swiftResourcesPath: \"/fake/lib/swift\",\n                swiftStaticResourcesPath: \"/fake/lib/swift_static\"\n            )\n        )\n\n        let env = Environment.mockEnvironment\n        let mockToolchain = try UserToolchain(\n            swiftSDK: userSwiftSDK,\n            environment: env,\n            searchStrategy: .custom(\n                searchPaths: getEnvSearchPaths(\n                    pathString: env[.path],\n                    currentWorkingDirectory: fs.currentWorkingDirectory\n                ),\n                useXcrun: true\n            ),\n            customTargetInfo: UserToolchain.mockTargetInfo,\n            fileSystem: fs\n        )\n\n        XCTAssertEqual(\n            mockToolchain.extraFlags.swiftCompilerFlags.rawFlags,\n            [\n                \"-I\", \"/fake/path/lib/swift/macosx/testing\",\n                \"-L\", \"/fake/path/lib/swift/macosx/testing\",\n                \"-plugin-path\", \"/fake/path/lib/swift/host/plugins/testing\",\n                \"-sdk\", \"/fake/sdk\",\n            ]\n        )\n        XCTAssertNoMatch(mockToolchain.extraFlags.linkerFlags.rawFlags, [\"-rpath\"])\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"Lib\", dependencies: []),\n                        TargetDescription(\n                            name: \"LibTest\",\n                            dependencies: [\"Lib\"],\n                            type: .test\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: mockToolchain.targetTriple,\n            toolchain: mockToolchain,\n            graph: graph,\n            commonFlags: .init(),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(2)\n        result.checkTargetsCount(3)\n\n        let testProductLinkArgs = try result.buildProduct(for: \"Lib\").linkArguments()\n        XCTAssertMatch(testProductLinkArgs, [\n            \"-I\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-L\", \"/fake/path/lib/swift/macosx/testing\",\n        ])\n\n        let libModuleArgs = try result.moduleBuildDescription(for: \"Lib\").swift().compileArguments()\n        XCTAssertMatch(libModuleArgs, [\n            \"-I\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-L\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-plugin-path\", \"/fake/path/lib/swift/host/plugins/testing\",\n        ])\n        XCTAssertNoMatch(libModuleArgs, [\"-Xlinker\"])\n\n        let testModuleArgs = try result.moduleBuildDescription(for: \"LibTest\").swift().compileArguments()\n        XCTAssertMatch(testModuleArgs, [\n            \"-I\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-L\", \"/fake/path/lib/swift/macosx/testing\",\n            \"-plugin-path\", \"/fake/path/lib/swift/host/plugins/testing\",\n        ])\n        XCTAssertNoMatch(testModuleArgs, [\"-Xlinker\"])\n    }\n\n    func testUserToolchainWithToolsetCompileFlags() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/cLib/cLib.c\",\n            \"/Pkg/Sources/cLib/include/cLib.h\",\n            \"/Pkg/Sources/cxxLib/cxxLib.c\",\n            \"/Pkg/Sources/cxxLib/include/cxxLib.h\"\n        )\n        try fileSystem.createMockToolchain()\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"cLib\", \"cxxLib\"]),\n                        TargetDescription(name: \"cLib\", dependencies: []),\n                        TargetDescription(name: \"cxxLib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        func jsonFlag(tool: Toolset.KnownTool) -> String { \"-\\(tool)-flag-from-json\" }\n        func jsonFlag(tool: Toolset.KnownTool) -> StringPattern { .equal(jsonFlag(tool: tool)) }\n        func cliFlag(tool: Toolset.KnownTool) -> String { \"-\\(tool)-flag-from-cli\" }\n        func cliFlag(tool: Toolset.KnownTool) -> StringPattern { .equal(cliFlag(tool: tool)) }\n\n        let toolset = try Toolset(\n            knownTools: [\n                .cCompiler: .init(extraCLIOptions: [jsonFlag(tool: .cCompiler)]),\n                .cxxCompiler: .init(extraCLIOptions: [jsonFlag(tool: .cxxCompiler)]),\n                .swiftCompiler: .init(extraCLIOptions: [jsonFlag(tool: .swiftCompiler)]),\n                .librarian: .init(path: \"/fake/toolchain/usr/bin/librarian\"),\n                .linker: .init(path: \"/fake/toolchain/usr/bin/linker\", extraCLIOptions: [jsonFlag(tool: .linker)]),\n            ],\n            rootPaths: UserToolchain.mockHostToolchain(fileSystem).swiftSDK.toolset.rootPaths\n        )\n        let targetTriple = try Triple(\"armv7em-unknown-none-macho\")\n        let swiftSDK = SwiftSDK(\n            hostTriple: .arm64Linux,\n            targetTriple: targetTriple,\n            toolset: toolset,\n            pathsConfiguration: .init(\n                sdkRootPath: \"/fake/sdk\",\n                swiftStaticResourcesPath: \"/usr/lib/swift_static/none\"\n            )\n        )\n        let toolchain = try UserToolchain(\n            swiftSDK: swiftSDK,\n            environment: .mockEnvironment,\n            customTargetInfo: UserToolchain.mockTargetInfo,\n            fileSystem: fileSystem\n        )\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: targetTriple,\n            toolchain: toolchain,\n            graph: graph,\n            commonFlags: BuildFlags(\n                cCompilerFlags: [cliFlag(tool: .cCompiler)].constructBuildFlags(source: nil),\n                cxxCompilerFlags: [cliFlag(tool: .cxxCompiler)].constructBuildFlags(source: nil),\n                swiftCompilerFlags: [cliFlag(tool: .swiftCompiler)].constructBuildFlags(source: nil),\n                linkerFlags: [cliFlag(tool: .linker)].constructBuildFlags(source: nil)\n            ),\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(3)\n\n        func XCTAssertCount<S>(\n            _ expectedCount: Int,\n            _ sequence: S,\n            _ element: S.Element,\n            file: StaticString = #filePath,\n            line: UInt = #line\n        ) where S: Sequence, S.Element: Equatable {\n            let actualCount = sequence.filter { $0 == element }.count\n            guard actualCount != expectedCount else { return }\n            XCTFail(\n                \"\"\"\n                Failed to find expected element '\\(element)' in \\\n                '\\(sequence)' \\(expectedCount) time(s) but found element \\\n                \\(actualCount) time(s).\n                \"\"\",\n                file: file,\n                line: line\n            )\n        }\n\n        // Compile C Target\n        let cLibCompileArguments = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n        let cLibCompileArgumentsPattern: [StringPattern] = [\n            jsonFlag(tool: .cCompiler), \"-g\", cliFlag(tool: .cCompiler),\n        ]\n        XCTAssertMatch(cLibCompileArguments, cLibCompileArgumentsPattern)\n        XCTAssertCount(0, cLibCompileArguments, jsonFlag(tool: .swiftCompiler))\n        XCTAssertCount(0, cLibCompileArguments, cliFlag(tool: .swiftCompiler))\n        XCTAssertCount(1, cLibCompileArguments, jsonFlag(tool: .cCompiler))\n        XCTAssertCount(1, cLibCompileArguments, cliFlag(tool: .cCompiler))\n        XCTAssertCount(0, cLibCompileArguments, jsonFlag(tool: .cxxCompiler))\n        XCTAssertCount(0, cLibCompileArguments, cliFlag(tool: .cxxCompiler))\n        XCTAssertCount(0, cLibCompileArguments, jsonFlag(tool: .linker))\n        XCTAssertCount(0, cLibCompileArguments, cliFlag(tool: .linker))\n\n        // Compile Cxx Target\n        let cxxLibCompileArguments = try result.moduleBuildDescription(for: \"cxxLib\").clang().basicArguments(isCXX: true)\n        let cxxLibCompileArgumentsPattern: [StringPattern] = [\n            jsonFlag(tool: .cCompiler), \"-g\", cliFlag(tool: .cCompiler),\n            .anySequence,\n            jsonFlag(tool: .cxxCompiler), \"-g\", cliFlag(tool: .cxxCompiler),\n        ]\n        XCTAssertMatch(cxxLibCompileArguments, cxxLibCompileArgumentsPattern)\n        XCTAssertCount(0, cxxLibCompileArguments, jsonFlag(tool: .swiftCompiler))\n        XCTAssertCount(0, cxxLibCompileArguments, cliFlag(tool: .swiftCompiler))\n        XCTAssertCount(1, cxxLibCompileArguments, jsonFlag(tool: .cCompiler))\n        XCTAssertCount(1, cxxLibCompileArguments, cliFlag(tool: .cCompiler))\n        XCTAssertCount(1, cxxLibCompileArguments, jsonFlag(tool: .cxxCompiler))\n        XCTAssertCount(1, cxxLibCompileArguments, cliFlag(tool: .cxxCompiler))\n        XCTAssertCount(0, cxxLibCompileArguments, jsonFlag(tool: .linker))\n        XCTAssertCount(0, cxxLibCompileArguments, cliFlag(tool: .linker))\n\n        // Compile Swift Target\n        let exeCompileArguments = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        let exeCompileArgumentsPattern: [StringPattern] = [\n            jsonFlag(tool: .swiftCompiler),\n            \"-ld-path=\\(AbsolutePath(\"/fake/toolchain/usr/bin/linker\").pathString)\",\n            \"-g\", cliFlag(tool: .swiftCompiler),\n            .anySequence,\n            \"-Xcc\", jsonFlag(tool: .cCompiler), \"-Xcc\", \"-g\", \"-Xcc\", cliFlag(tool: .cCompiler),\n            // TODO: Pass -Xcxx flags to swiftc (#6491)\n            // Uncomment when downstream support arrives.\n            // .anySequence,\n            // \"-Xcxx\", jsonFlag(tool: .cxxCompiler), \"-Xcxx\", cliFlag(tool: .cxxCompiler),\n        ]\n        XCTAssertMatch(exeCompileArguments, exeCompileArgumentsPattern)\n        XCTAssertCount(1, exeCompileArguments, jsonFlag(tool: .swiftCompiler))\n        XCTAssertCount(1, exeCompileArguments, cliFlag(tool: .swiftCompiler))\n        XCTAssertCount(1, exeCompileArguments, jsonFlag(tool: .cCompiler))\n        XCTAssertCount(1, exeCompileArguments, cliFlag(tool: .cCompiler))\n        // TODO: Pass -Xcxx flags to swiftc (#6491)\n        // Change 0 to 1 when downstream support arrives.\n        XCTAssertCount(0, exeCompileArguments, jsonFlag(tool: .cxxCompiler))\n        XCTAssertCount(0, exeCompileArguments, cliFlag(tool: .cxxCompiler))\n        XCTAssertCount(0, exeCompileArguments, jsonFlag(tool: .linker))\n        XCTAssertCount(0, exeCompileArguments, cliFlag(tool: .linker))\n\n        // Link Product\n        let exeLinkArguments = try result.buildProduct(for: \"exe\").linkArguments()\n        let exeLinkArgumentsPattern: [StringPattern] = [\n            jsonFlag(tool: .swiftCompiler),\n            \"-ld-path=\\(AbsolutePath(\"/fake/toolchain/usr/bin/linker\").pathString)\",\n            \"-g\", cliFlag(tool: .swiftCompiler),\n            .anySequence,\n            \"-Xlinker\", jsonFlag(tool: .linker), \"-Xlinker\", cliFlag(tool: .linker),\n        ]\n        XCTAssertMatch(exeLinkArguments, exeLinkArgumentsPattern)\n        XCTAssertCount(1, exeLinkArguments, jsonFlag(tool: .swiftCompiler))\n        XCTAssertCount(1, exeLinkArguments, cliFlag(tool: .swiftCompiler))\n        XCTAssertCount(0, exeLinkArguments, jsonFlag(tool: .cCompiler))\n        XCTAssertCount(0, exeLinkArguments, cliFlag(tool: .cCompiler))\n        XCTAssertCount(0, exeLinkArguments, jsonFlag(tool: .cxxCompiler))\n        XCTAssertCount(0, exeLinkArguments, cliFlag(tool: .cxxCompiler))\n        XCTAssertCount(1, exeLinkArguments, jsonFlag(tool: .linker))\n        XCTAssertCount(1, exeLinkArguments, cliFlag(tool: .linker))\n    }\n\n    func testUserToolchainWithSDKSearchPaths() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/cLib/cLib.c\",\n            \"/Pkg/Sources/cLib/include/cLib.h\"\n        )\n        try fileSystem.createMockToolchain()\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"cLib\"]),\n                        TargetDescription(name: \"cLib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let targetTriple = try UserToolchain.default.targetTriple\n        let sdkIncludeSearchPath = AbsolutePath(\"/usr/lib/swift_static/none/include\")\n        let sdkLibrarySearchPath = AbsolutePath(\"/usr/lib/swift_static/none/lib\")\n        let swiftSDK = try SwiftSDK(\n            targetTriple: targetTriple,\n            properties: .init(\n                sdkRootPath: \"/fake/sdk\",\n                includeSearchPaths: [sdkIncludeSearchPath.pathString],\n                librarySearchPaths: [sdkLibrarySearchPath.pathString]\n            ),\n            toolset: .init(knownTools: [\n                .swiftCompiler: .init(extraCLIOptions: [\"-use-ld=lld\"]),\n            ])\n        )\n\n        let env = Environment.mockEnvironment\n        let toolchain = try UserToolchain(\n            swiftSDK: swiftSDK,\n            environment: env,\n            searchStrategy: .custom(\n                searchPaths: getEnvSearchPaths(\n                    pathString: env[.path],\n                    currentWorkingDirectory: fileSystem.currentWorkingDirectory\n                ),\n                useXcrun: true\n            ),\n            customTargetInfo: UserToolchain.mockTargetInfo,\n            fileSystem: fileSystem\n        )\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            toolchain: toolchain,\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        // Compile C Target\n        let cLibCompileArguments = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n        let cLibCompileArgumentsPattern: [StringPattern] = [\"-I\", \"\\(sdkIncludeSearchPath)\"]\n        XCTAssertMatch(cLibCompileArguments, cLibCompileArgumentsPattern)\n\n        // Compile Swift Target\n        let exeCompileArguments = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        let exeCompileArgumentsPattern: [StringPattern] = [\"-I\", \"\\(sdkIncludeSearchPath)\"]\n        XCTAssertMatch(exeCompileArguments, exeCompileArgumentsPattern)\n\n        // Link Product\n        let exeLinkArguments = try result.buildProduct(for: \"exe\").linkArguments()\n        let exeLinkArgumentsPattern: [StringPattern] = [\"-L\", \"\\(sdkIncludeSearchPath)\"]\n        XCTAssertMatch(exeLinkArguments, exeLinkArgumentsPattern)\n    }\n\n    func testExecBuildTimeDependency() async throws {\n        let PkgA = AbsolutePath(\"/PkgA\")\n\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            PkgA.appending(components: \"Sources\", \"exe\", \"main.swift\").pathString,\n            PkgA.appending(components: \"Sources\", \"swiftlib\", \"lib.swift\").pathString,\n            \"/PkgB/Sources/PkgB/PkgB.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"PkgA\",\n                    path: .init(validating: PkgA.pathString),\n                    products: [\n                        ProductDescription(name: \"swiftlib\", type: .library(.automatic), targets: [\"swiftlib\"]),\n                        ProductDescription(name: \"exe\", type: .executable, targets: [\"exe\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: []),\n                        TargetDescription(name: \"swiftlib\", dependencies: [\"exe\"]),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"PkgB\",\n                    path: \"/PkgB\",\n                    dependencies: [\n                        .localSourceControl(\n                            path: .init(validating: PkgA.pathString),\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"PkgB\", dependencies: [\"swiftlib\"]),\n                    ]\n                ),\n            ],\n            explicitProduct: \"exe\",\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let buildPath = plan.productsBuildPath\n\n        let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"debug.yaml\")\n        try fs.createDirectory(yaml.parentDirectory, recursive: true)\n        let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.generateManifest(at: yaml)\n        let contents: String = try fs.readFileContents(yaml)\n        let swiftGetVersionFilePath = try XCTUnwrap(llbuild.swiftGetVersionFiles.first?.value)\n\n        #if os(Windows)\n        let suffix = \".exe\"\n        #else // FIXME(5472) - the suffix is dropped\n        let suffix = \"\"\n        #endif\n        XCTAssertMatch(contents, .contains(\"\"\"\n            inputs: [\"\\(\n                PkgA.appending(components: \"Sources\", \"swiftlib\", \"lib.swift\")\n                    .escapedPathString\n        )\",\"\\(swiftGetVersionFilePath.escapedPathString)\",\"\\(\n            buildPath\n                .appending(components: \"exe\\(suffix)\").escapedPathString\n        )\",\"\\(\n            buildPath\n                .appending(components: \"swiftlib.build\", \"sources\").escapedPathString\n        )\"]\n            outputs: [\"\\(\n                buildPath.appending(components: \"swiftlib.build\", \"lib.swift.o\")\n                    .escapedPathString\n        )\",\"\\(buildPath.escapedPathString)\n        \"\"\"))\n        }\n\n    func testObjCHeader1() async throws {\n        let PkgA = AbsolutePath(\"/PkgA\")\n\n        // This has a Swift and ObjC target in the same package.\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            PkgA.appending(components: \"Sources\", \"Bar\", \"main.m\").pathString,\n            PkgA.appending(components: \"Sources\", \"Foo\", \"Foo.swift\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"PkgA\",\n                    path: .init(validating: PkgA.pathString),\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                        TargetDescription(name: \"Bar\", dependencies: [\"Foo\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let fooTarget = try result.moduleBuildDescription(for: \"Foo\").swift().compileArguments()\n        XCTAssertMatch(\n            fooTarget,\n            [\n                .anySequence,\n                \"-emit-objc-header\",\n                \"-emit-objc-header-path\",\n                \"\\(buildPath.appending(components: \"Foo.build\", \"include\", \"Foo-Swift.h\"))\",\n                .anySequence,\n            ]\n        )\n\n        let barTarget = try result.moduleBuildDescription(for: \"Bar\").clang().basicArguments(isCXX: false)\n        XCTAssertMatch(\n            barTarget,\n            [\n                .anySequence,\n                \"-I\", \"\\(buildPath.appending(components: \"Foo.build\", \"include\"))\",\n                .anySequence,\n            ]\n        )\n\n        let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"debug.yaml\")\n        try fs.createDirectory(yaml.parentDirectory, recursive: true)\n        let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.generateManifest(at: yaml)\n        let contents: String = try fs.readFileContents(yaml)\n        XCTAssertMatch(contents, .contains(\"\"\"\n          \"\\(buildPath.appending(components: \"Bar.build\", \"main.m.o\").escapedPathString)\":\n            tool: clang\n            inputs: [\"\\(buildPath.appending(components: \"Modules\", \"Foo.swiftmodule\").escapedPathString)\",\"\\(PkgA\n            .appending(components: \"Sources\", \"Bar\", \"main.m\").escapedPathString)\"]\n            outputs: [\"\\(buildPath.appending(components: \"Bar.build\", \"main.m.o\").escapedPathString)\"]\n            description: \"Compiling Bar main.m\"\n        \"\"\"))\n    }\n\n    func testObjCHeader2() async throws {\n        let PkgA = AbsolutePath(\"/PkgA\")\n\n        // This has a Swift and ObjC target in different packages with automatic product type.\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            PkgA.appending(components: \"Sources\", \"Bar\", \"main.m\").pathString,\n            \"/PkgB/Sources/Foo/Foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"PkgA\",\n                    path: .init(validating: PkgA.pathString),\n                    dependencies: [\n                        .localSourceControl(path: \"/PkgB\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\", dependencies: [\"Foo\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"PkgB\",\n                    path: \"/PkgB\",\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let fooTarget = try result.moduleBuildDescription(for: \"Foo\").swift().compileArguments()\n        XCTAssertMatch(\n            fooTarget,\n            [\n                .anySequence,\n                \"-emit-objc-header\",\n                \"-emit-objc-header-path\",\n                \"\\(buildPath.appending(components: \"Foo.build\", \"include\", \"Foo-Swift.h\"))\",\n                .anySequence,\n            ]\n        )\n\n        let barTarget = try result.moduleBuildDescription(for: \"Bar\").clang().basicArguments(isCXX: false)\n        XCTAssertMatch(\n            barTarget,\n            [\n                .anySequence,\n                \"-I\", \"\\(buildPath.appending(components: \"Foo.build\", \"include\"))\",\n                .anySequence,\n            ]\n        )\n\n        let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"debug.yaml\")\n        try fs.createDirectory(yaml.parentDirectory, recursive: true)\n        let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.generateManifest(at: yaml)\n        let contents: String = try fs.readFileContents(yaml)\n        XCTAssertMatch(contents, .contains(\"\"\"\n          \"\\(buildPath.appending(components: \"Bar.build\", \"main.m.o\").escapedPathString)\":\n            tool: clang\n            inputs: [\"\\(buildPath.appending(components: \"Modules\", \"Foo.swiftmodule\").escapedPathString)\",\"\\(PkgA\n            .appending(components: \"Sources\", \"Bar\", \"main.m\").escapedPathString)\"]\n            outputs: [\"\\(buildPath.appending(components: \"Bar.build\", \"main.m.o\").escapedPathString)\"]\n            description: \"Compiling Bar main.m\"\n        \"\"\"))\n    }\n\n    func testObjCHeader3() async throws {\n        let PkgA = AbsolutePath(\"/PkgA\")\n\n        // This has a Swift and ObjC target in different packages with dynamic product type.\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            PkgA.appending(components: \"Sources\", \"Bar\", \"main.m\").pathString,\n            \"/PkgB/Sources/Foo/Foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"PkgA\",\n                    path: .init(validating: PkgA.pathString),\n                    dependencies: [\n                        .localSourceControl(path: \"/PkgB\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\", dependencies: [\"Foo\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"PkgB\",\n                    path: \"/PkgB\",\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.dynamic), targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let dynamicLibraryExtension = plan.destinationBuildParameters.triple.dynamicLibraryExtension\n        #if os(Windows)\n        let dynamicLibraryPrefix = \"\"\n        #else\n        let dynamicLibraryPrefix = \"lib\"\n        #endif\n        let result = try BuildPlanResult(plan: plan)\n        let buildPath = result.plan.productsBuildPath\n\n        let fooTarget = try result.moduleBuildDescription(for: \"Foo\").swift().compileArguments()\n        XCTAssertMatch(\n            fooTarget,\n            [\n                .anySequence,\n                \"-emit-objc-header\",\n                \"-emit-objc-header-path\",\n                \"\\(buildPath.appending(components: \"Foo.build\", \"include\", \"Foo-Swift.h\"))\",\n                .anySequence,\n            ]\n        )\n\n        let barTarget = try result.moduleBuildDescription(for: \"Bar\").clang().basicArguments(isCXX: false)\n        XCTAssertMatch(\n            barTarget,\n            [\n                .anySequence,\n                \"-I\", \"\\(buildPath.appending(components: \"Foo.build\", \"include\"))\",\n                .anySequence,\n            ]\n        )\n\n        let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"debug.yaml\")\n        try fs.createDirectory(yaml.parentDirectory, recursive: true)\n        let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.generateManifest(at: yaml)\n        let contents: String = try fs.readFileContents(yaml)\n        XCTAssertMatch(contents, .contains(\"\"\"\n          \"\\(buildPath.appending(components: \"Bar.build\", \"main.m.o\").escapedPathString)\":\n            tool: clang\n            inputs: [\"\\(\n                buildPath.appending(components: \"\\(dynamicLibraryPrefix)Foo\\(dynamicLibraryExtension)\")\n                    .escapedPathString\n        )\",\"\\(PkgA.appending(components: \"Sources\", \"Bar\", \"main.m\").escapedPathString)\"]\n            outputs: [\"\\(buildPath.appending(components: \"Bar.build\", \"main.m.o\").escapedPathString)\"]\n            description: \"Compiling Bar main.m\"\n        \"\"\"))\n    }\n\n    func testModulewrap() async throws {\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: .x86_64Linux,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        let buildPath = result.plan.productsBuildPath\n\n        let objects = try result.buildProduct(for: \"exe\").objects\n        XCTAssertTrue(\n            objects.contains(buildPath.appending(components: \"exe.build\", \"exe.swiftmodule.o\")),\n            objects.description\n        )\n        XCTAssertTrue(\n            objects.contains(buildPath.appending(components: \"lib.build\", \"lib.swiftmodule.o\")),\n            objects.description\n        )\n\n        let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"debug.yaml\")\n        try fs.createDirectory(yaml.parentDirectory, recursive: true)\n        let llbuild = LLBuildManifestBuilder(result.plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.generateManifest(at: yaml)\n        let contents: String = try fs.readFileContents(yaml)\n        XCTAssertMatch(contents, .contains(\"\"\"\n          \"\\(buildPath.appending(components: \"exe.build\", \"exe.swiftmodule.o\").escapedPathString)\":\n            tool: shell\n            inputs: [\"\\(buildPath.appending(components: \"exe.build\", \"exe.swiftmodule\").escapedPathString)\"]\n            outputs: [\"\\(buildPath.appending(components: \"exe.build\", \"exe.swiftmodule.o\").escapedPathString)\"]\n            description: \"Wrapping AST for exe for debugging\"\n            args: [\"\\(\n                result.plan.destinationBuildParameters.toolchain.swiftCompilerPath\n                    .escapedPathString\n        )\",\"-modulewrap\",\"\\(buildPath.appending(\n            components: \"exe.build\",\n            \"exe.swiftmodule\"\n        ).escapedPathString)\",\"-o\",\"\\(\n            buildPath.appending(components: \"exe.build\", \"exe.swiftmodule.o\")\n                .escapedPathString\n        )\",\"-target\",\"x86_64-unknown-linux-gnu\"]\n        \"\"\"))\n        XCTAssertMatch(contents, .contains(\"\"\"\n          \"\\(buildPath.appending(components: \"lib.build\", \"lib.swiftmodule.o\").escapedPathString)\":\n            tool: shell\n            inputs: [\"\\(buildPath.appending(components: \"Modules\", \"lib.swiftmodule\").escapedPathString)\"]\n            outputs: [\"\\(buildPath.appending(components: \"lib.build\", \"lib.swiftmodule.o\").escapedPathString)\"]\n            description: \"Wrapping AST for lib for debugging\"\n            args: [\"\\(\n                result.plan.destinationBuildParameters.toolchain.swiftCompilerPath\n                    .escapedPathString\n        )\",\"-modulewrap\",\"\\(buildPath.appending(\n            components: \"Modules\",\n            \"lib.swiftmodule\"\n        ).escapedPathString)\",\"-o\",\"\\(\n            buildPath.appending(components: \"lib.build\", \"lib.swiftmodule.o\")\n                .escapedPathString\n        )\",\"-target\",\"x86_64-unknown-linux-gnu\"]\n        \"\"\"))\n    }\n\n    func testArchiving() async throws {\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/Package/Sources/rary/rary.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Package\",\n                    path: \"/Package\",\n                    products: [\n                        ProductDescription(name: \"rary\", type: .library(.static), targets: [\"rary\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"rary\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        let buildPath = result.plan.productsBuildPath\n\n        let yaml = try fs.tempDirectory.appending(components: UUID().uuidString, \"debug.yaml\")\n        try fs.createDirectory(yaml.parentDirectory, recursive: true)\n\n        let llbuild = LLBuildManifestBuilder(\n            result.plan,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        try llbuild.generateManifest(at: yaml)\n\n        let contents: String = try fs.readFileContents(yaml)\n        let triple = result.plan.destinationBuildParameters.triple.tripleString\n\n        if result.plan.destinationBuildParameters.triple.isWindows() {\n            XCTAssertMatch(\n                contents,\n                .contains(\"\"\"\n                \"C.rary-\\(triple)-debug.a\":\n                    tool: shell\n                    inputs: [\"\\(\n                        buildPath.appending(components: \"rary.build\", \"rary.swift.o\")\n                            .escapedPathString\n                    )\",\"\\(\n                    buildPath.appending(components: \"rary.build\", \"rary.swiftmodule.o\")\n                        .escapedPathString\n                    )\",\"\\(\n                    buildPath.appending(components: \"rary.product\", \"Objects.LinkFileList\")\n                        .escapedPathString\n                    )\"]\n                    outputs: [\"\\(buildPath.appending(components: \"library.a\").escapedPathString)\"]\n                    description: \"Archiving \\(buildPath.appending(components: \"library.a\").escapedPathString)\"\n                    args: [\"\\(\n                        result.plan.destinationBuildParameters.toolchain.librarianPath\n                            .escapedPathString\n                    )\",\"/LIB\",\"/OUT:\\(\n                    buildPath.appending(components: \"library.a\")\n                        .escapedPathString\n                    )\",\"@\\(\n                    buildPath.appending(components: \"rary.product\", \"Objects.LinkFileList\")\n                        .escapedPathString\n                    )\"]\n                \"\"\")\n            )\n        } else if result.plan.destinationBuildParameters.triple.isDarwin() {\n            XCTAssertMatch(\n                contents,\n                .contains(\n                \"\"\"\n                \"C.rary-\\(triple)-debug.a\":\n                    tool: shell\n                    inputs: [\"\\(\n                        buildPath.appending(components: \"rary.build\", \"rary.swift.o\")\n                            .escapedPathString\n                    )\",\"\\(\n                    buildPath.appending(components: \"rary.product\", \"Objects.LinkFileList\")\n                        .escapedPathString\n                    )\"]\n                    outputs: [\"\\(buildPath.appending(components: \"library.a\").escapedPathString)\"]\n                    description: \"Archiving \\(buildPath.appending(components: \"library.a\").escapedPathString)\"\n                    args: [\"\\(\n                        result.plan.destinationBuildParameters.toolchain.librarianPath\n                            .escapedPathString\n                    )\",\"-static\",\"-o\",\"\\(\n                    buildPath.appending(components: \"library.a\")\n                        .escapedPathString\n                    )\",\"@\\(\n                    buildPath.appending(components: \"rary.product\", \"Objects.LinkFileList\")\n                        .escapedPathString\n                    )\"]\n                \"\"\")\n            )\n        } else { // assume `llvm-ar` is the librarian\n            XCTAssertMatch(\n                contents,\n                .contains(\n                \"\"\"\n                \"C.rary-\\(triple)-debug.a\":\n                    tool: shell\n                    inputs: [\"\\(\n                        buildPath.appending(components: \"rary.build\", \"rary.swift.o\")\n                            .escapedPathString\n                    )\",\"\\(\n                    buildPath.appending(components: \"rary.build\", \"rary.swiftmodule.o\")\n                        .escapedPathString\n                    )\",\"\\(\n                    buildPath.appending(components: \"rary.product\", \"Objects.LinkFileList\")\n                        .escapedPathString\n                    )\"]\n                    outputs: [\"\\(buildPath.appending(components: \"library.a\").escapedPathString)\"]\n                    description: \"Archiving \\(buildPath.appending(components: \"library.a\").escapedPathString)\"\n                    args: [\"\\(\n                        result.plan.destinationBuildParameters.toolchain.librarianPath\n                            .escapedPathString\n                    )\",\"crs\",\"\\(\n                    buildPath.appending(components: \"library.a\")\n                        .escapedPathString\n                    )\",\"@\\(\n                    buildPath.appending(components: \"rary.product\", \"Objects.LinkFileList\")\n                        .escapedPathString\n                    )\"]\n                \"\"\")\n            )\n        }\n    }\n\n    func testSwiftBundleAccessor() async throws {\n        // This has a Swift and ObjC target in the same package.\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/PkgA/Sources/Foo/Foo.swift\",\n            \"/PkgA/Sources/Foo/foo.txt\",\n            \"/PkgA/Sources/Foo/bar.txt\",\n            \"/PkgA/Sources/Bar/Bar.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"PkgA\",\n                    path: \"/PkgA\",\n                    toolsVersion: .v5_2,\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\",\n                            resources: [\n                                .init(rule: .copy, path: \"foo.txt\"),\n                                .init(rule: .process(localization: .none), path: \"bar.txt\"),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Bar\"\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let fooTarget = try result.moduleBuildDescription(for: \"Foo\").swift()\n        XCTAssertEqual(try fooTarget.objects.map(\\.pathString), [\n            buildPath.appending(components: \"Foo.build\", \"Foo.swift.o\").pathString,\n            buildPath.appending(components: \"Foo.build\", \"resource_bundle_accessor.swift.o\").pathString,\n        ])\n\n        let resourceAccessor = fooTarget.sources.first { $0.basename == \"resource_bundle_accessor.swift\" }!\n        let contents: String = try fs.readFileContents(resourceAccessor)\n        XCTAssertMatch(contents, .contains(\"extension Foundation.Bundle\"))\n        // Assert that `Bundle.main` is executed in the compiled binary (and not during compilation)\n        // See https://bugs.swift.org/browse/SR-14555 and\n        // https://github.com/swiftlang/swift-package-manager/pull/2972/files#r623861646\n        XCTAssertMatch(contents, .contains(\"let mainPath = Bundle.main.\"))\n\n        let barTarget = try result.moduleBuildDescription(for: \"Bar\").swift()\n        XCTAssertEqual(try barTarget.objects.map(\\.pathString), [\n            buildPath.appending(components: \"Bar.build\", \"Bar.swift.o\").pathString,\n        ])\n\n        XCTAssertTrue(try fooTarget.compileArguments().contains([\"-DSWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\"]))\n        XCTAssertTrue(try barTarget.compileArguments().contains([\"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]))\n    }\n\n    func testSwiftWASIBundleAccessor() async throws {\n        // This has a Swift and ObjC target in the same package.\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/PkgA/Sources/Foo/Foo.swift\",\n            \"/PkgA/Sources/Foo/foo.txt\",\n            \"/PkgA/Sources/Foo/bar.txt\",\n            \"/PkgA/Sources/Bar/Bar.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"PkgA\",\n                    path: \"/PkgA\",\n                    toolsVersion: .v5_2,\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\",\n                            resources: [\n                                .init(rule: .copy, path: \"foo.txt\"),\n                                .init(rule: .process(localization: .none), path: \"bar.txt\"),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Bar\"\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            triple: .wasi,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let fooTarget = try result.moduleBuildDescription(for: \"Foo\").swift()\n        XCTAssertEqual(try fooTarget.objects.map(\\.pathString), [\n            buildPath.appending(components: \"Foo.build\", \"Foo.swift.o\").pathString,\n            buildPath.appending(components: \"Foo.build\", \"resource_bundle_accessor.swift.o\").pathString,\n        ])\n\n        let resourceAccessor = fooTarget.sources.first { $0.basename == \"resource_bundle_accessor.swift\" }!\n        let contents: String = try fs.readFileContents(resourceAccessor)\n        XCTAssertMatch(contents, .contains(\"extension Foundation.Bundle\"))\n        // Assert that `Bundle.main` is executed in the compiled binary (and not during compilation)\n        // See https://bugs.swift.org/browse/SR-14555 and\n        // https://github.com/swiftlang/swift-package-manager/pull/2972/files#r623861646\n        XCTAssertMatch(contents, .contains(\"let mainPath = \\\"\"))\n\n        let barTarget = try result.moduleBuildDescription(for: \"Bar\").swift()\n        XCTAssertEqual(try barTarget.objects.map(\\.pathString), [\n            buildPath.appending(components: \"Bar.build\", \"Bar.swift.o\").pathString,\n        ])\n    }\n\n    func testClangBundleAccessor() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/Foo/include/Foo.h\",\n            \"/Pkg/Sources/Foo/Foo.m\",\n            \"/Pkg/Sources/Foo/bar.h\",\n            \"/Pkg/Sources/Foo/bar.c\",\n            \"/Pkg/Sources/Foo/resource.txt\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    toolsVersion: .current,\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\",\n                            resources: [\n                                .init(\n                                    rule: .process(localization: .none),\n                                    path: \"resource.txt\"\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let fooTarget = try result.moduleBuildDescription(for: \"Foo\").clang()\n        XCTAssertEqual(try fooTarget.objects.map(\\.pathString).sorted(), [\n            buildPath.appending(components: \"Foo.build\", \"Foo.m.o\").pathString,\n            buildPath.appending(components: \"Foo.build\", \"bar.c.o\").pathString,\n            buildPath.appending(components: \"Foo.build\", \"resource_bundle_accessor.m.o\").pathString,\n        ].sorted())\n\n        let resourceAccessorDirectory = buildPath.appending(\n            components:\n            \"Foo.build\",\n            \"DerivedSources\"\n        )\n\n        let resourceAccessorHeader = resourceAccessorDirectory\n            .appending(\"resource_bundle_accessor.h\")\n        let headerContents: String = try fs.readFileContents(resourceAccessorHeader)\n        XCTAssertMatch(\n            headerContents,\n            .contains(\"#define SWIFTPM_MODULE_BUNDLE Foo_SWIFTPM_MODULE_BUNDLE()\")\n        )\n\n        let resourceAccessorImpl = resourceAccessorDirectory\n            .appending(\"resource_bundle_accessor.m\")\n        let implContents: String = try fs.readFileContents(resourceAccessorImpl)\n        XCTAssertMatch(\n            implContents,\n            .contains(\"NSBundle* Foo_SWIFTPM_MODULE_BUNDLE() {\")\n        )\n    }\n\n    func testShouldLinkStaticSwiftStdlib() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        let supportingTriples: [Basics.Triple] = [.x86_64Linux, .arm64Linux, .wasi]\n        for triple in supportingTriples {\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n                triple: triple,\n                graph: graph,\n                linkingParameters: .init(\n                    shouldLinkStaticSwiftStdlib: true\n                ),\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ))\n\n            let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n            XCTAssertMatch(exe, [\"-static-stdlib\"])\n            let lib = try result.moduleBuildDescription(for: \"lib\").swift().compileArguments()\n            XCTAssertMatch(lib, [\"-static-stdlib\"])\n            let link = try result.buildProduct(for: \"exe\").linkArguments()\n            XCTAssertMatch(link, [\"-static-stdlib\"])\n        }\n    }\n\n    func testXCFrameworkBinaryTargets(platform: String, arch: String, targetTriple: Basics.Triple) async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"exe\", \"main.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"Library\", \"Library.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"CLibrary\", \"library.c\").pathString,\n            Pkg.appending(components: \"Sources\", \"CLibrary\", \"include\", \"library.h\").pathString\n        )\n\n        try! fs.createDirectory(\"/Pkg/Framework.xcframework\", recursive: true)\n        try! fs.writeFileContents(\n            \"/Pkg/Framework.xcframework/Info.plist\",\n            string: \"\"\"\n            <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n            <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n            <plist version=\"1.0\">\n            <dict>\n                <key>AvailableLibraries</key>\n                <array>\n                    <dict>\n                        <key>LibraryIdentifier</key>\n                        <string>\\(platform)-\\(arch)</string>\n                        <key>LibraryPath</key>\n                        <string>Framework.framework</string>\n                        <key>SupportedArchitectures</key>\n                        <array>\n                            <string>\\(arch)</string>\n                        </array>\n                        <key>SupportedPlatform</key>\n                        <string>\\(platform)</string>\n                    </dict>\n                </array>\n                <key>CFBundlePackageType</key>\n                <string>XFWK</string>\n                <key>XCFrameworkFormatVersion</key>\n                <string>1.0</string>\n            </dict>\n            </plist>\n            \"\"\"\n        )\n\n        try! fs.createDirectory(\"/Pkg/StaticLibrary.xcframework\", recursive: true)\n        try! fs.writeFileContents(\n            \"/Pkg/StaticLibrary.xcframework/Info.plist\",\n            string: \"\"\"\n            <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n            <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n            <plist version=\"1.0\">\n            <dict>\n                <key>AvailableLibraries</key>\n                <array>\n                    <dict>\n                        <key>LibraryIdentifier</key>\n                        <string>\\(platform)-\\(arch)</string>\n                        <key>HeadersPath</key>\n                        <string>Headers</string>\n                        <key>LibraryPath</key>\n                        <string>libStaticLibrary.a</string>\n                        <key>SupportedArchitectures</key>\n                        <array>\n                            <string>\\(arch)</string>\n                        </array>\n                        <key>SupportedPlatform</key>\n                        <string>\\(platform)</string>\n                    </dict>\n                </array>\n                <key>CFBundlePackageType</key>\n                <string>XFWK</string>\n                <key>XCFrameworkFormatVersion</key>\n                <string>1.0</string>\n            </dict>\n            </plist>\n            \"\"\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    products: [\n                        ProductDescription(name: \"exe\", type: .executable, targets: [\"exe\"]),\n                        ProductDescription(name: \"Library\", type: .library(.dynamic), targets: [\"Library\"]),\n                        ProductDescription(name: \"CLibrary\", type: .library(.dynamic), targets: [\"CLibrary\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"Library\"]),\n                        TargetDescription(name: \"Library\", dependencies: [\"Framework\"]),\n                        TargetDescription(name: \"CLibrary\", dependencies: [\"StaticLibrary\"]),\n                        TargetDescription(name: \"Framework\", path: \"Framework.xcframework\", type: .binary),\n                        TargetDescription(name: \"StaticLibrary\", path: \"StaticLibrary.xcframework\", type: .binary),\n                    ]\n                ),\n            ],\n            binaryArtifacts: [\n                .plain(\"pkg\"): [\n                    \"Framework\": .init(kind: .xcframework, originURL: nil, path: \"/Pkg/Framework.xcframework\"),\n                    \"StaticLibrary\": .init(kind: .xcframework, originURL: nil, path: \"/Pkg/StaticLibrary.xcframework\"),\n                ],\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: targetTriple,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        result.checkProductsCount(3)\n        result.checkTargetsCount(3)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let libraryBasicArguments = try result.moduleBuildDescription(for: \"Library\").swift().compileArguments()\n        XCTAssertMatch(libraryBasicArguments, [.anySequence, \"-F\", \"\\(buildPath)\", .anySequence])\n\n        let libraryLinkArguments = try result.buildProduct(for: \"Library\").linkArguments()\n        XCTAssertMatch(libraryLinkArguments, [.anySequence, \"-F\", \"\\(buildPath)\", .anySequence])\n        XCTAssertMatch(libraryLinkArguments, [.anySequence, \"-L\", \"\\(buildPath)\", .anySequence])\n        XCTAssertMatch(libraryLinkArguments, [.anySequence, \"-framework\", \"Framework\", .anySequence])\n\n        let exeCompileArguments = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(exeCompileArguments, [.anySequence, \"-F\", \"\\(buildPath)\", .anySequence])\n        XCTAssertMatch(\n            exeCompileArguments,\n            [\n                .anySequence,\n                \"-I\",\n                \"\\(Pkg.appending(components: \"Framework.xcframework\", \"\\(platform)-\\(arch)\"))\",\n                .anySequence,\n            ]\n        )\n\n        let exeLinkArguments = try result.buildProduct(for: \"exe\").linkArguments()\n        XCTAssertMatch(exeLinkArguments, [.anySequence, \"-F\", \"\\(buildPath)\", .anySequence])\n        XCTAssertMatch(exeLinkArguments, [.anySequence, \"-L\", \"\\(buildPath)\", .anySequence])\n        XCTAssertMatch(exeLinkArguments, [.anySequence, \"-framework\", \"Framework\", .anySequence])\n\n        let clibraryBasicArguments = try result.moduleBuildDescription(for: \"CLibrary\").clang().basicArguments(isCXX: false)\n        XCTAssertMatch(clibraryBasicArguments, [.anySequence, \"-F\", \"\\(buildPath)\", .anySequence])\n        XCTAssertMatch(\n            clibraryBasicArguments,\n            [\n                .anySequence,\n                \"-I\", \"\\(Pkg.appending(components: \"StaticLibrary.xcframework\", \"\\(platform)-\\(arch)\", \"Headers\"))\",\n                .anySequence,\n            ]\n        )\n\n        let clibraryLinkArguments = try result.buildProduct(for: \"CLibrary\").linkArguments()\n        XCTAssertMatch(clibraryLinkArguments, [.anySequence, \"-F\", \"\\(buildPath)\", .anySequence])\n        XCTAssertMatch(clibraryLinkArguments, [.anySequence, \"-L\", \"\\(buildPath)\", .anySequence])\n        XCTAssertMatch(clibraryLinkArguments, [\"-lStaticLibrary\"])\n\n        let executablePathExtension = try result.buildProduct(for: \"exe\").binaryPath.extension ?? \"\"\n        XCTAssertMatch(executablePathExtension, \"\")\n\n        let dynamicLibraryPathExtension = try result.buildProduct(for: \"Library\").binaryPath.extension\n        XCTAssertMatch(dynamicLibraryPathExtension, \"dylib\")\n    }\n\n    func testXCFrameworkBinaryTargetsLinux(platform: String = \"linux\", arch: String, targetTriple: Basics.Triple) async throws {\n        let Pkg: AbsolutePath = \"/Pkg\"\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            Pkg.appending(components: \"Sources\", \"exe\", \"main.swift\").pathString,\n            Pkg.appending(components: \"Sources\", \"Library\", \"Library.swift\").pathString\n        )\n\n        try fs.createDirectory(\"/Pkg/Framework.xcframework\", recursive: true)\n        try fs.writeFileContents(\n            \"/Pkg/Framework.xcframework/Info.plist\",\n            string: \"\"\"\n            <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n            <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n            <plist version=\"1.0\">\n            <dict>\n                <key>AvailableLibraries</key>\n                <array>\n                    <dict>\n                        <key>LibraryIdentifier</key>\n                        <string>\\(platform)-\\(arch)</string>\n                        <key>LibraryPath</key>\n                        <string>Framework.framework</string>\n                        <key>SupportedArchitectures</key>\n                        <array>\n                            <string>\\(arch)</string>\n                        </array>\n                        <key>SupportedPlatform</key>\n                        <string>\\(platform)</string>\n                    </dict>\n                </array>\n                <key>CFBundlePackageType</key>\n                <string>XFWK</string>\n                <key>XCFrameworkFormatVersion</key>\n                <string>1.0</string>\n            </dict>\n            </plist>\n            \"\"\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: Pkg.pathString),\n                    products: [\n                        ProductDescription(name: \"exe\", type: .executable, targets: [\"exe\"]),\n                        ProductDescription(name: \"Library\", type: .library(.dynamic), targets: [\"Library\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"Library\"]),\n                        TargetDescription(name: \"Library\", dependencies: [\"Framework\"]),\n                        TargetDescription(name: \"Framework\", path: \"Framework.xcframework\", type: .binary),\n                    ]\n                ),\n            ],\n            binaryArtifacts: [\n                .plain(\"pkg\"): [\n                    \"Framework\": .init(kind: .xcframework, originURL: nil, path: \"/Pkg/Framework.xcframework\"),\n                ],\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: targetTriple,\n            graph: graph,\n            enableXCFrameworksOnLinux: true,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        result.checkProductsCount(2)\n        result.checkTargetsCount(2)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let libraryBasicArguments = try result.moduleBuildDescription(for: \"Library\").swift().compileArguments()\n        XCTAssertMatch(\n            libraryBasicArguments,\n            [.anySequence, \"-I\", \"\\(Pkg.appending(components: \"Framework.xcframework\", \"\\(platform)-\\(arch)\"))\", .anySequence]\n        )\n\n        let libraryLinkArguments = try result.buildProduct(for: \"Library\").linkArguments()\n        XCTAssertMatch(libraryLinkArguments, [.anySequence, \"-L\", \"\\(buildPath)\", .anySequence])\n\n        let exeCompileArguments = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(\n            exeCompileArguments,\n            [.anySequence, \"-I\", \"\\(Pkg.appending(components: \"Framework.xcframework\", \"\\(platform)-\\(arch)\"))\", .anySequence]\n        )\n\n        let exeLinkArguments = try result.buildProduct(for: \"exe\").linkArguments()\n        XCTAssertMatch(exeLinkArguments, [.anySequence, \"-L\", \"\\(buildPath)\", .anySequence])\n\n        let executablePathExtension = try result.buildProduct(for: \"exe\").binaryPath.extension ?? \"\"\n        XCTAssertMatch(executablePathExtension, \"\")\n\n        let dynamicLibraryPathExtension = try result.buildProduct(for: \"Library\").binaryPath.extension\n        XCTAssertMatch(dynamicLibraryPathExtension, \"so\")\n    }\n\n    func testXCFrameworkBinaryTargets() async throws {\n        try await self.testXCFrameworkBinaryTargets(platform: \"macos\", arch: \"x86_64\", targetTriple: .x86_64MacOS)\n\n        let arm64Triple = try Basics.Triple(\"arm64-apple-macosx\")\n        try await self.testXCFrameworkBinaryTargets(platform: \"macos\", arch: \"arm64\", targetTriple: arm64Triple)\n\n        let arm64eTriple = try Basics.Triple(\"arm64e-apple-macosx\")\n        try await self.testXCFrameworkBinaryTargets(platform: \"macos\", arch: \"arm64e\", targetTriple: arm64eTriple)\n\n        let x86_64Linux = try Basics.Triple(\"x86_64-unknown-linux-gnu\")\n        try await self.testXCFrameworkBinaryTargetsLinux(arch: \"x86_64\", targetTriple: x86_64Linux)\n\n        let aarch64Linux = try Basics.Triple(\"aarch64-unknown-linux-gnu\")\n        try await self.testXCFrameworkBinaryTargetsLinux(arch: \"aarch64\", targetTriple: aarch64Linux)\n    }\n\n    func testArtifactsArchiveBinaryTargets(\n        artifactTriples: [Basics.Triple],\n        targetTriple: Basics.Triple\n    ) async throws -> Bool {\n        let fs = InMemoryFileSystem(emptyFiles: \"/Pkg/Sources/exe/main.swift\")\n\n        let artifactName = \"my-tool\"\n        let toolPath = AbsolutePath(\"/Pkg/MyTool.artifactbundle\")\n        try fs.createDirectory(toolPath, recursive: true)\n\n        try fs.writeFileContents(\n            toolPath.appending(\"info.json\"),\n            string: \"\"\"\n                {\n                    \"schemaVersion\": \"1.0\",\n                    \"artifacts\": {\n                        \"\\(artifactName)\": {\n                            \"type\": \"executable\",\n                            \"version\": \"1.1.0\",\n                            \"variants\": [\n                                {\n                                    \"path\": \"all-platforms/mytool\",\n                                    \"supportedTriples\": [\"\\(\n                                        artifactTriples.map(\\.tripleString)\n                                            .joined(separator: \"\\\", \\\"\"))\"]\n                                }\n                            ]\n                        }\n                    }\n                }\n            \"\"\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    products: [\n                        ProductDescription(name: \"exe\", type: .executable, targets: [\"exe\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"MyTool\"]),\n                        TargetDescription(name: \"MyTool\", path: \"MyTool.artifactbundle\", type: .binary),\n                    ]\n                ),\n            ],\n            binaryArtifacts: [\n                .plain(\"pkg\"): [\n                    \"MyTool\": .init(kind: .artifactsArchive(types: [.executable]), originURL: nil, path: toolPath),\n                ],\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: targetTriple,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(1)\n\n        let availableTools = try result.buildProduct(for: \"exe\").availableTools\n        return availableTools.contains(where: { $0.key == artifactName })\n    }\n\n    func testArtifactsArchiveBinaryTargets() async throws {\n        let result = try await self.testArtifactsArchiveBinaryTargets(\n            artifactTriples: [.x86_64MacOS],\n            targetTriple: .x86_64MacOS\n        )\n        XCTAssertTrue(result)\n\n        do {\n            let triples = try [\"arm64-apple-macosx\", \"x86_64-apple-macosx\", \"x86_64-unknown-linux-gnu\"]\n                .map(Basics.Triple.init)\n            let result2 = try await self.testArtifactsArchiveBinaryTargets(\n                artifactTriples: triples,\n                targetTriple: triples.first!\n            )\n            XCTAssertTrue(result2)\n        }\n\n        do {\n            let triples = try [\"x86_64-unknown-linux-gnu\"].map(Basics.Triple.init)\n            let result3 = try await self.testArtifactsArchiveBinaryTargets(\n                artifactTriples: triples,\n                targetTriple: .x86_64MacOS\n            )\n            XCTAssertFalse(result3)\n        }\n    }\n\n    func testAddressSanitizer() async throws {\n        try await self.sanitizerTest(.address, expectedName: \"address\")\n    }\n\n    func testThreadSanitizer() async throws {\n        try await self.sanitizerTest(.thread, expectedName: \"thread\")\n    }\n\n    func testUndefinedSanitizer() async throws {\n        try await self.sanitizerTest(.undefined, expectedName: \"undefined\")\n    }\n\n    func testScudoSanitizer() async throws {\n        try await self.sanitizerTest(.scudo, expectedName: \"scudo\")\n    }\n\n    func testFuzzerSanitizer() async throws {\n        try await self.sanitizerTest(.fuzzer, expectedName: \"fuzzer\")\n    }\n\n    func testSnippets() async throws {\n        let fs: FileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/Lib/Lib.swift\",\n            \"/Pkg/Snippets/ASnippet.swift\",\n            \"/Pkg/.build/release.yaml\"\n        )\n        let buildPath = AbsolutePath(\"/Pkg/.build\")\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Lib\",\n                    path: \"/Pkg\",\n                    toolsVersion: .vNext,\n                    dependencies: [],\n                    products: [\n                        ProductDescription(name: \"Lib\", type: .library(.automatic), targets: [\"Lib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Lib\", dependencies: [], type: .regular),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let plan = try await mockBuildPlan(\n            buildPath: buildPath,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let result = try BuildPlanResult(plan: plan)\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"ASnippet\" && $0.module.type == .snippet })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Lib\" })\n\n        let yaml = buildPath.appending(\"release.yaml\")\n        let llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.generateManifest(at: yaml)\n        let swiftGetVersionFilePath = try XCTUnwrap(llbuild.swiftGetVersionFiles.first?.value)\n\n        let yamlContents: String = try fs.readFileContents(yaml)\n        let inputs: SerializedJSON = \"\"\"\n            inputs: [\"\\(AbsolutePath(\n                \"/Pkg/Snippets/ASnippet.swift\"\n            ))\",\"\\(swiftGetVersionFilePath)\",\"\\(AbsolutePath(\"/Pkg/.build/debug/Modules/Lib.swiftmodule\"))\"\n        \"\"\"\n        XCTAssertMatch(yamlContents, .contains(inputs.underlying))\n    }\n\n    private func sanitizerTest(_ sanitizer: PackageModel.Sanitizer, expectedName: String) async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.swift\",\n            \"/Pkg/Sources/clib/clib.c\",\n            \"/Pkg/Sources/clib/include/clib.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\", \"clib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                        TargetDescription(name: \"clib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            // Unrealistic: we can't enable all of these at once on all platforms.\n            // This test codifies current behavior, not ideal behavior, and\n            // may need to be amended if we change it.\n            targetSanitizers: EnabledSanitizers([sanitizer]),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(3)\n\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        XCTAssertMatch(exe, [\"-sanitize=\\(expectedName)\"])\n\n        let lib = try result.moduleBuildDescription(for: \"lib\").swift().compileArguments()\n        XCTAssertMatch(lib, [\"-sanitize=\\(expectedName)\"])\n\n        let clib = try result.moduleBuildDescription(for: \"clib\").clang().basicArguments(isCXX: false)\n        XCTAssertMatch(clib, [\"-fsanitize=\\(expectedName)\"])\n\n        if sanitizer == .fuzzer {\n            XCTAssertMatch(exe, [\"-parse-as-library\"])\n            XCTAssertNoMatch(exe, [\"-Xlinker\", \"alias\", \"_main\"])\n            XCTAssertMatch(lib, [\"-parse-as-library\"])\n            XCTAssertNoMatch(lib, [\"-Xlinker\", \"alias\", \"_main\"])\n            XCTAssertNoMatch(clib, [\"-parse-as-library\"])\n        }\n\n        XCTAssertMatch(try result.buildProduct(for: \"exe\").linkArguments(), [\"-sanitize=\\(expectedName)\"])\n    }\n\n    func testBuildParameterLTOMode() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/cLib/cLib.c\",\n            \"/Pkg/Sources/cLib/include/cLib.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"cLib\"]),\n                        TargetDescription(name: \"cLib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let toolchain = try UserToolchain.default\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            toolchain: toolchain,\n            graph: graph,\n            linkingParameters: .init(\n                linkTimeOptimizationMode: .full\n            ),\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        // Compile C Target\n        let cLibCompileArguments = try result.moduleBuildDescription(for: \"cLib\").clang().basicArguments(isCXX: false)\n        let cLibCompileArgumentsPattern: [StringPattern] = [\"-flto=full\"]\n        XCTAssertMatch(cLibCompileArguments, cLibCompileArgumentsPattern)\n\n        // Compile Swift Target\n        let exeCompileArguments = try result.moduleBuildDescription(for: \"exe\").swift().compileArguments()\n        let exeCompileArgumentsPattern: [StringPattern] = [\"-lto=llvm-full\"]\n        XCTAssertMatch(exeCompileArguments, exeCompileArgumentsPattern)\n\n        // Assert the objects built by the Swift Target are actually bitcode\n        // files, indicated by the \"bc\" extension.\n        let exeCompileObjects = try result.moduleBuildDescription(for: \"exe\").swift().objects\n        XCTAssert(exeCompileObjects.allSatisfy { $0.extension == \"bc\" })\n\n        // Assert the objects getting linked contain all the bitcode objects\n        // built by the Swift Target\n        let exeProduct = try result.buildProduct(for: \"exe\")\n        for exeCompileObject in exeCompileObjects {\n            XCTAssertTrue(exeProduct.objects.contains(exeCompileObject))\n        }\n    }\n\n    func testNoRpathForOSNone() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let toolchain = try UserToolchain.default\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: Triple(\"arm64-unknown-none\"),\n            toolchain: toolchain,\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n\n        // Assert the objects getting linked contain all the bitcode objects\n        // built by the Swift Target\n        let exeLinkArguments = try result.buildProduct(for: \"exe\").linkArguments()\n        let exeLinkArgumentsNegativePattern: [StringPattern] = [\"-rpath\"]\n        XCTAssertNoMatch(exeLinkArguments, exeLinkArgumentsNegativePattern)\n    }\n\n    func testPackageDependencySetsUserModuleVersion() async throws {\n        let fs = InMemoryFileSystem(emptyFiles: \"/Pkg/Sources/exe/main.swift\", \"/ExtPkg/Sources/ExtLib/best.swift\")\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/ExtPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\n                            .product(name: \"ExtPkg\", package: \"ExtPkg\"),\n                        ]),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"ExtPkg\",\n                    path: \"/ExtPkg\",\n                    version: \"1.0.0\",\n                    toolsVersion: .v6_0,\n                    products: [\n                        ProductDescription(name: \"ExtPkg\", type: .library(.automatic), targets: [\"ExtLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ExtLib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            environment: BuildEnvironment(\n                platform: .linux,\n                configuration: .release\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        switch try XCTUnwrap(\n            result.plan.targetMap[.init(\n                moduleID: .init(moduleName: \"ExtLib\", packageIdentity: \"ExtPkg\"),\n                destination: .target\n            )]\n        ) {\n        case .swift(let swiftTarget):\n            if #available(macOS 13, *) { // `.contains` is only available in macOS 13 or newer\n                XCTAssertTrue(try swiftTarget.compileArguments().contains([\"-user-module-version\", \"1.0.0\"]))\n            }\n        case .clang:\n            XCTFail(\"expected a Swift target\")\n        }\n    }\n\n    func testBasicSwiftPackageWithoutLocalRpath() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldDisableLocalRpath: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        let buildPath = result.plan.productsBuildPath\n\n        #if os(macOS)\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-Xlinker\", \"-no_warn_duplicate_libraries\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-5.5/macosx\",\n            \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fake/path/lib/swift-6.2/macosx\",\n            \"-target\", defaultTargetTriple,\n            \"-Xlinker\", \"-add_ast_path\",\n            \"-Xlinker\", buildPath.appending(components: \"Modules\", \"lib.swiftmodule\").pathString,\n            \"-Xlinker\", \"-add_ast_path\",\n            \"-Xlinker\", buildPath.appending(components: \"exe.build\", \"exe.swiftmodule\").pathString,\n            \"-g\",\n        ]\n        #elseif os(Windows)\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe.exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\",\n        ]\n        #else\n        let linkArguments = [\n            result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n            \"-L\", buildPath.pathString,\n            \"-o\", buildPath.appending(components: \"exe\").pathString,\n            \"-module-name\", \"exe\",\n            \"-emit-executable\",\n            \"@\\(buildPath.appending(components: \"exe.product\", \"Objects.LinkFileList\"))\",\n            \"-target\", defaultTargetTriple,\n            \"-g\",\n        ]\n        #endif\n\n        XCTAssertEqual(try result.buildProduct(for: \"exe\").linkArguments(), linkArguments)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    // testing of deriving dynamic libraries for explicitly linking rdar://108561857\n    func testDerivingDylibs() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/FooLogging/file.swift\",\n            \"/barPkg/Sources/BarLogging/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"FooLogging\", type: .library(.dynamic), targets: [\"FooLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"FooLogging\",\n                            dependencies: [.product(name: \"BarLogging\", package: \"barPkg\")]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"BarLogging\", type: .library(.dynamic), targets: [\"BarLogging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLogging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_8,\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(name: \"FooLogging\", package: \"fooPkg\"),],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(3)\n        result.checkTargetsCount(3)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"FooLogging\" })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"BarLogging\" })\n        let buildProduct = try XCTUnwrap(\n            result.plan.productMap[.init(\n                productID: .init(productName: \"exe\", packageIdentity: \"thisPkg\"),\n                destination: .target\n            )]\n        )\n        let dylibs = Array(buildProduct.dylibs.map({$0.product.name})).sorted()\n        XCTAssertEqual(dylibs, [\"BarLogging\", \"FooLogging\"])\n    }\n\n    func testDefaultVersions() async throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Pkg/Sources/foo/foo.swift\"\n        )\n\n        let expectedVersions = [\n          ToolsVersion.v4: \"4\",\n          ToolsVersion.v4_2: \"4.2\",\n          ToolsVersion.v5: \"5\",\n          ToolsVersion.v6_0: \"6\",\n          ToolsVersion.vNext: \"6\"\n        ]\n        for (toolsVersion, expectedVersionString) in expectedVersions {\n            let observability = ObservabilitySystem.makeForTesting()\n            let graph = try loadModulesGraph(\n              fileSystem: fs,\n              manifests: [\n                Manifest.createRootManifest(\n                  displayName: \"Pkg\",\n                  path: \"/Pkg\",\n                  toolsVersion: toolsVersion,\n                  targets: [\n                    TargetDescription(\n                      name: \"foo\"\n                    ),\n                  ]\n                ),\n              ],\n              observabilityScope: observability.topScope\n            )\n\n            let result = try await BuildPlanResult(plan: mockBuildPlan(\n              graph: graph,\n              fileSystem: fs,\n              observabilityScope: observability.topScope\n            ))\n\n            XCTAssertMatch(\n              try result.moduleBuildDescription(for: \"foo\").swift().compileArguments(),\n              [\n                \"-swift-version\", .equal(expectedVersionString)\n              ]\n            )\n        }\n    }\n\n    func testProductWithBinaryArtifactDependency() async throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"Test is only supported on macOS\")\n        #endif\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/testpackage/Sources/SwiftLib/lib.swift\",\n            \"/testpackage/Sources/CLib/include/lib.h\",\n            \"/testpackage/Sources/CLib/lib.c\"\n        )\n\n        try fs.createDirectory(\"/testpackagedep/SomeArtifact.xcframework\", recursive: true)\n        try fs.writeFileContents(\n            \"/testpackagedep/SomeArtifact.xcframework/Info.plist\",\n            string: \"\"\"\n            <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n            <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n            <plist version=\"1.0\">\n            <dict>\n                <key>AvailableLibraries</key>\n                <array>\n                    <dict>\n                        <key>LibraryIdentifier</key>\n                        <string>macos</string>\n                        <key>HeadersPath</key>\n                        <string>Headers</string>\n                        <key>LibraryPath</key>\n                        <string>libSomeArtifact.a</string>\n                        <key>SupportedArchitectures</key>\n                        <array>\n                            <string>arm64</string>\n                            <string>x86_64</string>\n                        </array>\n                        <key>SupportedPlatform</key>\n                        <string>macos</string>\n                    </dict>\n                </array>\n                <key>CFBundlePackageType</key>\n                <string>XFWK</string>\n                <key>XCFrameworkFormatVersion</key>\n                <string>1.0</string>\n            </dict>\n            </plist>\n            \"\"\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"testpackagedep\",\n                    path: \"/testpackagedep\",\n                    products: [\n                        ProductDescription(name: \"SomeArtifact\", type: .library(.static), targets: [\"SomeArtifact\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"SomeArtifact\", path: \"SomeArtifact.xcframework\", type: .binary),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"testpackage\",\n                    path: \"/testpackage\",\n                    dependencies: [\n                        .localSourceControl(path: \"/testpackagedep\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"SwiftLib\", type: .library(.static), targets: [\"SwiftLib\"]),\n                        ProductDescription(name: \"CLib\", type: .library(.static), targets: [\"CLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"SwiftLib\", dependencies: [\"SomeArtifact\"]),\n                        TargetDescription(name: \"CLib\", dependencies: [\"SomeArtifact\"])\n                    ]\n                ),\n            ],\n            binaryArtifacts: [\n                .plain(\"testpackagedep\"): [\n                    \"SomeArtifact\": .init(kind: .xcframework, originURL: nil, path: \"/testpackagedep/SomeArtifact.xcframework\"),\n                ],\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let llbuild = LLBuildManifestBuilder(\n            plan,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        try llbuild.generateManifest(at: \"/manifest.yaml\")\n        let contents: String = try fs.readFileContents(\"/manifest.yaml\")\n\n        XCTAssertMatch(contents, .regex(#\"args: \\[.*\"-I\",\"/testpackagedep/SomeArtifact.xcframework/macos/Headers\".*,\"/testpackage/Sources/CLib/lib.c\".*]\"#))\n        XCTAssertMatch(contents, .regex(#\"args: \\[.*\"-module-name\",\"SwiftLib\",.*\"-I\",\"/testpackagedep/SomeArtifact.xcframework/macos/Headers\".*]\"#))\n    }\n\n    func testMacroPluginDependencyLeakage() async throws {\n        // Make sure the include paths from macro and plugin executables don't leak into dependents\n        let observability = ObservabilitySystem.makeForTesting()\n        let fs = InMemoryFileSystem(emptyFiles: [\n            \"/LeakTest/Sources/CLib/include/Clib.h\",\n            \"/LeakTest/Sources/CLib/Clib.c\",\n            \"/LeakTest/Sources/MyMacro/MyMacro.swift\",\n            \"/LeakTest/Sources/MyPluginTool/MyPluginTool.swift\",\n            \"/LeakTest/Sources/MyLib/MyLib.swift\",\n            \"/LeakTest/Plugins/MyPlugin/MyPlugin.swift\",\n            \"/LeakTest/Tests/MyMacroTests/MyMacroTests.swift\",\n            \"/LeakTest/Tests/MyMacro2Tests/MyMacro2Tests.swift\",\n            \"/LeakLib/Sources/CLib2/include/Clib.h\",\n            \"/LeakLib/Sources/CLib2/Clib.c\",\n            \"/LeakLib/Sources/MyMacro2/MyMacro.swift\",\n            \"/LeakLib/Sources/MyPluginTool2/MyPluginTool.swift\",\n            \"/LeakLib/Sources/MyLib2/MyLib.swift\",\n            \"/LeakLib/Plugins/MyPlugin2/MyPlugin.swift\",\n        ])\n\n        let graph = try loadModulesGraph(fileSystem: fs, manifests: [\n            Manifest.createFileSystemManifest(\n                displayName: \"LeakLib\",\n                path: \"/LeakLib\",\n                products: [\n                    ProductDescription(name: \"MyLib2\", type: .library(.automatic), targets: [\"MyLib2\"]),\n                    ProductDescription(name: \"MyMacros2\", type: .macro, targets: [\"MyMacro2\"])\n                ],\n                targets: [\n                    TargetDescription(name: \"CLib2\"),\n                    TargetDescription(name: \"MyMacro2\", dependencies: [\"CLib2\"], type: .macro),\n                    TargetDescription(name: \"MyPluginTool2\", dependencies: [\"CLib2\"], type: .executable),\n                    TargetDescription(name: \"MyPlugin2\", dependencies: [\"MyPluginTool2\"], type: .plugin, pluginCapability: .buildTool),\n                    TargetDescription(name: \"MyLib2\", dependencies: [\"CLib2\", \"MyMacro2\"], pluginUsages: [.plugin(name: \"MyPlugin2\", package: nil)]),\n                ]\n            ),\n            Manifest.createRootManifest(\n                displayName: \"LeakTest\",\n                path: \"/LeakTest\",\n                dependencies: [\n                    .fileSystem(path: \"/LeakLib\")\n                ],\n                targets: [\n                    TargetDescription(name: \"CLib\"),\n                    TargetDescription(name: \"MyMacro\", dependencies: [\"CLib\"], type: .macro),\n                    TargetDescription(name: \"MyPluginTool\", dependencies: [\"CLib\"], type: .executable),\n                    TargetDescription(name: \"MyPlugin\", dependencies: [\"MyPluginTool\"], type: .plugin, pluginCapability: .buildTool),\n                    TargetDescription(\n                        name: \"MyLib\",\n                        dependencies: [\"CLib\", \"MyMacro\", .product(name: \"MyLib2\", package: \"LeakLib\")],\n                        pluginUsages: [.plugin(name: \"MyPlugin\", package: nil)]\n                    ),\n                    TargetDescription(name: \"MyMacroTests\", dependencies: [\"MyMacro\"], type: .test),\n                    TargetDescription(\n                        name: \"MyMacro2Tests\",\n                        dependencies: [.product(name: \"MyMacros2\", package: \"LeakLib\")],\n                        type: .test),\n                ]\n            )\n        ], observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let myLib = try XCTUnwrap(plan.targets.first(where: { $0.module.name == \"MyLib\" })).swift()\n        XCTAssertFalse(myLib.additionalFlags.contains(where: { $0.contains(\"-tool\")}), \"flags shouldn't contain tools items\")\n\n        // Make sure the tests do have the include path and the module map from the lib\n        let myMacroTests = try XCTUnwrap(plan.targets.first(where: { $0.module.name == \"MyMacroTests\" })).swift()\n        let flags = myMacroTests.additionalFlags.joined(separator: \" \")\n        XCTAssertMatch(flags, .regex(\"CLib[/\\\\\\\\]include\"))\n        XCTAssertMatch(flags, .regex(\"CLib-tool.build[/\\\\\\\\]module.modulemap\"))\n        let myMacro2Tests = try XCTUnwrap(plan.targets.first(where: { $0.module.name == \"MyMacro2Tests\" })).swift()\n        let flags2 = myMacro2Tests.additionalFlags.joined(separator: \" \")\n        XCTAssertMatch(flags2, .regex(\"CLib2[/\\\\\\\\]include\"))\n        XCTAssertMatch(flags2, .regex(\"CLib2-tool.build[/\\\\\\\\]module.modulemap\"))\n    }\n\n    func testDiagnosticsAreMentionedInOutputsFileMap() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/exe/aux.swift\",\n            \"/Pkg/Sources/lib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let result = try BuildPlanResult(plan: plan)\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(2)\n\n        for module in result.targetMap {\n            let buildDescription = try module.swift()\n\n            try withTemporaryFile { file in\n                try buildDescription.writeOutputFileMap(to: .init(file.path.pathString))\n\n                let fileMap = try String(bytes: fs.readFileContents(file.path).contents, encoding: .utf8)\n\n                for diagnosticFile in buildDescription.diagnosticFiles {\n                    let fileName = diagnosticFile.pathString.replacingOccurrences(of: \"\\\\\", with: \"\\\\\\\\\")\n                    XCTAssertMatch(fileMap, .contains(fileName))\n                }\n            }\n        }\n    }\n\n    func testImplicitModules() async throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n            \"/A/Sources/ATarget/foo.swift\",\n            \"/A/Sources/AMacro/macro.swift\",\n            \"/A/Sources/AExecutable/main.swift\",\n            \"/A/Sources/ASystemLib/module.modulemap\",\n            \"/A/Plugins/APlugin/main.swift\",\n            \"/A/Tests/ATargetTests/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    dependencies: [\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\"),\n                        TargetDescription(\n                            name: \"AMacro\",\n                            dependencies: [],\n                            type: .`macro`\n                        ),\n                        TargetDescription(\n                            name: \"AExecutable\",\n                            dependencies: [\"ATarget\"],\n                            type: .executable\n                        ),\n                        TargetDescription(\n                            name: \"APlugin\",\n                            type: .plugin,\n                            pluginCapability: .buildTool\n                        ),\n                        TargetDescription(\n                            name: \"ASystemLib\",\n                            type: .system\n                        ),\n                        TargetDescription(\n                            name: \"ATargetTests\",\n                            dependencies: [\"ATarget\"],\n                            type: .test\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            graph: graph,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope\n        ))\n\n        struct ExpectedTarget: Hashable, Equatable {\n            let name: String\n            let implicit: Bool\n        }\n\n        var expectedTargets: Set<ExpectedTarget> = [\n            .init(name: \"ATarget\", implicit: false),\n            .init(name: \"AMacro\", implicit: false),\n            .init(name: \"AExecutable\", implicit: false),\n            .init(name: \"ATargetTests\", implicit: false),\n            .init(name: \"APackageTests\", implicit: true),\n        ]\n        #if !os(macOS)\n        expectedTargets.insert(.init(name: \"APackageDiscoveredTests\", implicit: true))\n        #endif\n        XCTAssertEqual(\n            Set(result.targetMap.map { ExpectedTarget(name: $0.module.name, implicit: $0.module.implicit) }),\n            expectedTargets\n        )\n        XCTAssertEqual(\n            result.plan.graph.module(for: \"APlugin\")?.implicit,\n            false\n        )\n        XCTAssertEqual(\n            result.plan.graph.module(for: \"ASystemLib\")?.implicit,\n            false\n        )\n    }\n\n    func testSupplementaryOutputsCompileArguments() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles: \"/Pkg/Sources/exe/main.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", type: .executable),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        var driverParameters = BuildParameters.Driver()\n        driverParameters.emitSILFiles = true\n        driverParameters.emitIRFiles = true\n        driverParameters.emitOptimizationRecord = true\n\n        let plan = try await mockBuildPlan(\n            config: .release,\n            graph: graph,\n            driverParameters: driverParameters,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let result = try BuildPlanResult(plan: plan)\n        let exe = try result.moduleBuildDescription(for: \"exe\").swift()\n\n        let args = try exe.emitCommandLine()\n        XCTAssertMatch(args, [\"-save-optimization-record\"])\n        XCTAssertMatch(args, [\"-g\"])\n    }\n\n    func testSupplementaryOutputsInWMOMode() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Pkg/Sources/lib/file1.swift\",\n                \"/Pkg/Sources/lib/file2.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"lib\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        var driverParameters = BuildParameters.Driver()\n        driverParameters.emitSILFiles = true\n        driverParameters.emitIRFiles = true\n        driverParameters.emitOptimizationRecord = true\n\n        let plan = try await mockBuildPlan(\n            config: .release,\n            graph: graph,\n            driverParameters: driverParameters,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let result = try BuildPlanResult(plan: plan)\n        let lib = try result.moduleBuildDescription(for: \"lib\").swift()\n\n        let args = try lib.emitCommandLine()\n        XCTAssertMatch(args, [\"-whole-module-optimization\"])\n        XCTAssertMatch(args, [\"-save-optimization-record\"])\n    }\n}\n\nclass BuildPlanNativeTests: BuildPlanTestCase {\n    override open var buildSystemProvider: BuildSystemProvider.Kind {\n        return .native\n    }\n\n    override func testDuplicateProductNamesWithNonDefaultLibsThrowError() async throws {\n        try await super.testDuplicateProductNamesWithNonDefaultLibsThrowError()\n    }\n\n}\n\nclass BuildPlanSwiftBuildTests: BuildPlanTestCase {\n    override open var buildSystemProvider: BuildSystemProvider.Kind {\n        return .swiftbuild\n    }\n\n    override func testDuplicateProductNamesWithNonDefaultLibsThrowError() async throws {\n        try await super.testDuplicateProductNamesWithNonDefaultLibsThrowError()\n    }\n\n    override func testTargetsWithPackageAccess() async throws {\n        throw XCTSkip(\"Skip until swift build system can support this case.\")\n    }\n\n    override func testTestModule() async throws {\n        throw XCTSkip(\"Skip until swift build system can support this case.\")\n    }\n\n    override func testPackageNameFlag() async throws {\n        try XCTSkipOnWindows(because: \"Skip until there is a resolution to the partial linking with Windows that results in a 'subsystem must be defined' error.\")\n        try await super.testPackageNameFlag()\n    }\n\n}\n"
  },
  {
    "path": "Tests/BuildTests/BuildPlanTraversalTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Testing\n\nimport Basics\n@testable import Build\n\nimport PackageGraph\n\nimport _InternalTestSupport\nimport SPMBuildCore\n\nstruct BuildPlanTraversalTests {\n    typealias Dest = BuildParameters.Destination\n\n    struct Result {\n        let parent: (ResolvedModule, Dest)?\n        let module: (ResolvedModule, Dest)\n    }\n\n    func getResults(\n        for module: String,\n        with destination: Dest? = nil,\n        in results: [Result]\n    ) -> [Result] {\n        results.filter { result in\n            if result.module.0.name != module {\n                return false\n            }\n            guard let destination else {\n                return true\n            }\n\n            return result.module.1 == destination\n        }\n    }\n\n    func getParents(\n        in results: [Result],\n        for module: String,\n        destination: Dest? = nil\n    ) -> [String] {\n        self.getResults(\n            for: module,\n            with: destination,\n            in: results\n        ).reduce(into: Set<String>()) {\n            if let parent = $1.parent {\n                $0.insert(parent.0.name)\n            }\n        }.sorted()\n    }\n\n    @Test\n    func trivialTraversal() async throws {\n        let destinationTriple = Triple.arm64Linux\n        let toolsTriple = Triple.x86_64MacOS\n\n        let (graph, fs, scope) = try trivialPackageGraph()\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                triple: destinationTriple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: toolsTriple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        var results: [Result] = []\n        plan.traverseModules {\n            results.append(Result(parent: $1, module: $0))\n        }\n\n        #expect(self.getParents(in: results, for: \"app\") == [])\n        #expect(self.getParents(in: results, for: \"lib\") == [\"app\", \"test\"])\n        #expect(self.getParents(in: results, for: \"test\") == [])\n    }\n\n    @Test\n    func traversalWithDifferentDestinations() async throws {\n        let destinationTriple = Triple.arm64Linux\n        let toolsTriple = Triple.x86_64MacOS\n\n        let (graph, fs, scope) = try macrosPackageGraph()\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                triple: destinationTriple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: toolsTriple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        var results: [Result] = []\n        plan.traverseModules {\n            results.append(Result(parent: $1, module: $0))\n        }\n\n        #expect(self.getParents(in: results, for: \"MMIO\") == [\"HAL\"])\n        #expect(self.getParents(in: results, for: \"SwiftSyntax\", destination: .host) == [\"MMIOMacros\"])\n        #expect(self.getParents(in: results, for: \"HAL\", destination: .target) == [\"Core\", \"HALTests\"])\n        #expect(self.getParents(in: results, for: \"HAL\", destination: .host) == [])\n    }\n\n    @Test\n    func traversalWithTestThatDependsOnMacro() async throws {\n        let destinationTriple = Triple.arm64Linux\n        let toolsTriple = Triple.x86_64MacOS\n\n        let (graph, fs, scope) = try macrosTestsPackageGraph()\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                triple: destinationTriple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: toolsTriple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        // Tests that if one of the test targets directly depends\n        // on a macro - all tests are built for the \"host\".\n        var results: [Result] = []\n        plan.traverseModules {\n            results.append(Result(parent: $1, module: $0))\n        }\n\n        let package = try #require(graph.package(for: \"swift-mmio\"))\n\n        // Tests that if one of the test targets directly depends\n        // on a macro - all tests are built for the \"host\".\n        for module in package.modules where module.type == .test {\n            let results = getResults(for: module.name, in: results)\n            #expect(results.allSatisfy { $0.module.1 == .host })\n        }\n    }\n\n    @Test\n    func recursiveDependencyTraversal() async throws {\n        let destinationTriple = Triple.arm64Linux\n        let toolsTriple = Triple.x86_64MacOS\n\n        let (graph, fs, scope) = try macrosPackageGraph()\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                triple: destinationTriple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: toolsTriple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        let mmioModule = try #require(plan.description(for: graph.module(for: \"MMIO\")!, context: .target))\n\n        var moduleDependencies: [(ResolvedModule, Dest, Build.ModuleBuildDescription?)] = []\n        plan.traverseDependencies(of: mmioModule) { product, destination, description in\n            #expect(product.name == \"SwiftSyntax\")\n            #expect(destination == .host)\n            #expect(description == nil)\n        } onModule: { module, destination, description in\n            moduleDependencies.append((module, destination, description))\n        }\n\n        #expect(moduleDependencies.count == 2)\n\n        // The ordering is guaranteed by the traversal\n\n        #expect(moduleDependencies[0].0.name == \"MMIOMacros\")\n        #expect(moduleDependencies[1].0.name == \"SwiftSyntax\")\n\n        for index in 0 ..< moduleDependencies.count {\n            #expect(moduleDependencies[index].1 == .host)\n            #expect(moduleDependencies[index].2 != nil)\n        }\n\n        let directDependencies = mmioModule.dependencies(using: plan)\n\n        #expect(directDependencies.count == 1)\n\n        let dependency = try #require(directDependencies.first)\n        if case .module(let module, let description) = dependency {\n            #expect(module.name == \"MMIOMacros\")\n            let desc = try #require(description)\n            #expect(desc.destination == .host)\n        } else {\n            Issue.record(\"Expected MMIOMacros module\")\n        }\n\n        let dependencies = mmioModule.recursiveDependencies(using: plan)\n\n        #expect(dependencies.count == 3)\n\n        // MMIOMacros (module) -> SwiftSyntax (product) -> SwiftSyntax (module)\n\n        if case .module(let module, let description) = dependencies[0] {\n            #expect(module.name == \"MMIOMacros\")\n            let desc = try #require(description)\n            #expect(desc.destination == .host)\n        } else {\n            Issue.record(\"Expected MMIOMacros module\")\n        }\n\n        if case .product(let product, let description) = dependencies[1] {\n            #expect(product.name == \"SwiftSyntax\")\n            #expect(description == nil)\n        } else {\n            Issue.record(\"Expected SwiftSyntax product\")\n        }\n\n        if case .module(let module, let description) = dependencies[2] {\n            #expect(module.name == \"SwiftSyntax\")\n            let desc = try #require(description)\n            #expect(desc.destination == .host)\n        } else {\n            Issue.record(\"Expected SwiftSyntax module\")\n        }\n    }\n\n    @Test\n    func recursiveDependencyTraversalWithDuplicates() async throws {\n        let destinationTriple = Triple.arm64Linux\n        let toolsTriple = Triple.x86_64MacOS\n\n        let (graph, fs, scope) = try macrosTestsPackageGraph()\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                triple: destinationTriple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: toolsTriple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        let testModule = try #require(plan.description(for: graph.module(for: \"MMIOMacrosTests\")!, context: .host))\n\n        let dependencies = testModule.recursiveDependencies(using: plan)\n        #expect(dependencies.count == 9)\n\n        struct ModuleResult: Hashable {\n            let module: ResolvedModule\n            let destination: Dest\n        }\n\n        var uniqueModules = Set<ModuleResult>()\n        for dependency in dependencies {\n            if case .module(let module, let description) = dependency {\n                #expect(description != nil)\n                #expect(description!.destination == .host)\n                #expect(uniqueModules.insert(.init(module: module, destination: description!.destination))\n                    .inserted)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/BuildSystemDelegateTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport struct SPMBuildCore.BuildSystemProvider\nimport PackageModel\nimport _InternalTestSupport\nimport Testing\n\nimport var TSCBasic.localFileSystem\n\n@Suite(\n    .tags(\n        .TestSize.large,\n    )\n)\nstruct BuildSystemDelegateTests {\n    @Test(\n        .requiresSDKDependentTestsSupport,\n        .requireHostOS(.macOS),  // These linker diagnostics are only produced on macOS.\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func doNotFilterLinkerDiagnostics(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/DoNotFilterLinkerDiagnostics\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(\n                    stdout.contains(\"ld: warning: search path 'foobar' not found\"),\n                    \"log didn't contain expected linker diagnostics.  stderr: '\\(stderr)')\",\n                )\n            case .swiftbuild:\n                #expect(\n                    stderr.contains(\"ld: warning: search path 'foobar' not found\"),\n                    \"log didn't contain expected linker diagnostics. stderr: '\\(stderr)\",\n                )\n                #expect(\n                    !stdout.contains(\"ld: warning: search path 'foobar' not found\"),\n                    \"log didn't contain expected linker diagnostics.  stderr: '\\(stderr)')\",\n                )\n            case .xcode:\n                Issue.record(\"Test expectation has not be implemented\")\n            }\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8540\", relationship: .defect),  // Package fails to build when the test is being executed\"\n        .requiresSDKDependentTestsSupport,\n        .tags(\n            .Feature.Command.Build,\n            .Feature.TargetType.Executable,\n            .Feature.TargetType.Library,\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Configuration,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func filterNonFatalCodesignMessages(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            // Note: we can re-use the `TestableExe` fixture here since we just need an executable.\n            try await fixture(name: \"Miscellaneous/TestableExe\") { fixturePath in\n                _ = try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let execPath = try fixturePath.appending(\n                    components: buildSystem.binPath(for: config) + [executableName(\"TestableExe1\")]\n                )\n                expectFileExists(at: execPath)\n                try localFileSystem.removeFileTree(execPath)\n                let (stdout, stderr) = try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(!stdout.contains(\"replacing existing signature\"), \"log contained non-fatal codesigning messages stderr: '\\(stderr)'\")\n                #expect(!stderr.contains(\"replacing existing signature\"), \"log contained non-fatal codesigning messages. stdout: '\\(stdout)'\")\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/CGenPluginsBuildPlanTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2026 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Testing\nimport Basics\nimport PackageLoading\nimport _InternalBuildTestSupport\nimport Build\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\n@testable import PackageGraph\n\n@_spi(SwiftPMInternal)\n@testable import PackageModel\n\n@testable import SPMBuildCore\n\n@Suite struct CGenPluginsBuildPlanTests {\n    enum Kind {\n        case cModule\n        case swiftModule\n    }\n\n    let buildDir: Basics.AbsolutePath = \"/MyPkg/.build\"\n    var pluginRootDir: Basics.AbsolutePath { buildDir.appending(\"plugins\") }\n    var pluginOutputDir: Basics.AbsolutePath {\n        pluginRootDir.appending(\"outputs\", \"mypkg\", \"MyModule\", \"destination\", \"MyPlugin\")\n    }\n    var pluginIncludeDir: Basics.AbsolutePath { pluginOutputDir.appending(\"include\") }\n    var pluginModuleMapFile: Basics.AbsolutePath { pluginIncludeDir.appending(\"module.modulemap\") }\n    var pluginModuleMapArg: String { \"-fmodule-map-file=\\(pluginModuleMapFile.pathString)\" }\n    var pluginAPINotesFile: Basics.AbsolutePath { pluginIncludeDir.appending(\"Gened.apinotes\")}\n    var pluginHeaderFile: Basics.AbsolutePath { pluginIncludeDir.appending(\"Gened.h\")}\n    var pluginSourceFile: Basics.AbsolutePath { pluginOutputDir.appending(\"Gened.c\") }\n\n    func setup(\n        kind: Kind = .cModule,\n        gened: [RelativePath],\n        toolsVersion: ToolsVersion? = nil,\n        observability: ObservabilityScope\n    ) async throws -> BuildPlanResult {\n        let toolsVersion = try toolsVersion ?? #require(ToolsVersion(string: \"6.3\", experimentalFeatures: [.experimentalCGen]))\n        let sources = switch kind {\n        case .cModule:\n            [\n                \"/MyPkg/Sources/MyModule/MyModule.c\",\n                \"/MyPkg/Sources/MyModule/include/MyModule.h\",\n            ]\n        case .swiftModule:\n            [\n                \"/MyPkg/Sources/MyModule/MyModule.swift\",\n            ]\n        }\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPkg/Plugins/MyPlugin/MyPlugin.swift\",\n                \"/MyPkg/Sources/MyGenerator/MyGenerator.swift\",\n                \"/MyPkg/Sources/MyModule/data.in\",\n                \"/MyPkg/Sources/MyCModule/include/MyCModule.h\",\n                \"/MyPkg/Sources/MyCModule/MyCModule.c\",\n                \"/MyPkg/Sources/MyExe/MyExe.swift\"\n            ] + sources\n        )\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                .createRootManifest(\n                    displayName: \"MyPkg\",\n                    path: \"/MyPkg\",\n                    toolsVersion: toolsVersion,\n                    products: [\n                        .init(name: \"MyExe\", type: .executable, targets: [\"MyExe\"]),\n                    ],\n                    targets: [\n                        .init(name: \"MyGenerator\", type: .executable),\n                        .init(\n                            name: \"MyPlugin\",\n                            dependencies: [\"MyGenerator\"],\n                            type: .plugin,\n                            pluginCapability: .buildTool\n                        ),\n                        .init(name: \"MyModule\", dependencies: [\"MyPlugin\"]),\n                        .init(name: \"MyCModule\", dependencies: [\"MyModule\"]),\n                        .init(name: \"MyExe\", dependencies: [\"MyCModule\"], type: .executable)\n                    ]\n                )\n            ],\n            observabilityScope: observability\n        )\n\n        // TODO: this should be made a utility\n        struct MockPluginScriptRunner: PluginScriptRunner {\n            let genMessages: (\n                _ sourceFiles: [Basics.AbsolutePath],\n                _ workingDirectory: Basics.AbsolutePath,\n            ) -> [PluginToHostMessage]\n\n            func compilePluginScript(\n                sourceFiles: [Basics.AbsolutePath],\n                pluginName: String,\n                toolsVersion: PackageModel.ToolsVersion,\n                workers: UInt32,\n                observabilityScope: Basics.ObservabilityScope,\n                callbackQueue: DispatchQueue,\n                delegate: any SPMBuildCore.PluginScriptCompilerDelegate,\n                completion: @escaping (Result<SPMBuildCore.PluginCompilationResult, any Error>) -> Void)\n            {\n                callbackQueue.sync {\n                    completion(.failure(StringError(\"unimplemented\")))\n                }\n            }\n\n            func runPluginScript(\n                sourceFiles: [Basics.AbsolutePath],\n                pluginName: String,\n                initialMessage: Data,\n                toolsVersion: PackageModel.ToolsVersion,\n                workingDirectory: Basics.AbsolutePath,\n                writableDirectories: [Basics.AbsolutePath],\n                readOnlyDirectories: [Basics.AbsolutePath],\n                allowNetworkConnections: [Basics.SandboxNetworkPermission],\n                workers: UInt32,\n                fileSystem: any Basics.FileSystem,\n                observabilityScope: Basics.ObservabilityScope,\n                callbackQueue: DispatchQueue,\n                delegate: any SPMBuildCore.PluginScriptCompilerDelegate & SPMBuildCore.PluginScriptRunnerDelegate,\n                completion: @escaping (Result<Int32, any Error>) -> Void)\n            {\n                callbackQueue.sync {\n                    do {\n                        let decoder = JSONDecoder.makeWithDefaults()\n                        let encoder = JSONEncoder(outputFormatting: .prettyPrinted)\n\n                        let initial = try decoder.decode(HostToPluginMessage.self, from: initialMessage)\n                        guard case let .createBuildToolCommands(context: context, rootPackageId: _, targetId: _, pluginGeneratedSources: _, pluginGeneratedResources: _) = initial else {\n                            completion(.failure(StringError(\"Invalid initial message\")))\n                            return\n                        }\n                        let workDir = try context.url(for: context.pluginWorkDirId)\n\n                        for message in genMessages(sourceFiles, workDir) {\n                            let data = try encoder.encode(message)\n                            try delegate.handleMessage(data: data, responder: { _ in })\n                        }\n                        completion(.success(0))\n                    } catch {\n                        completion(.failure(error))\n                    }\n                }\n            }\n\n            var hostTriple: Triple {\n                get throws {\n                    return try UserToolchain.default.targetTriple\n                }\n            }\n        }\n\n        let pluginScriptRunner = MockPluginScriptRunner { sourceFiles, outputDirectory in\n            let inFiles = sourceFiles.filter({ $0.extension == \"in\" }).map(\\.asURL)\n            let outFiles = gened.map({ outputDirectory.appending($0).asURL })\n\n            return [\n                .defineBuildCommand(\n                    configuration: .init(\n                        executable: URL(filePath: \"/foo\"),\n                        arguments: [],\n                        environment: [:]\n                    ),\n                    inputFiles: inFiles,\n                    outputFiles: outFiles\n                )\n            ]\n        }\n\n        let pluginConfiguration = PluginConfiguration(\n            scriptRunner: pluginScriptRunner,\n            workDirectory: pluginRootDir,\n            disableSandbox: true\n        )\n\n        let pluginTools: [ResolvedModule.ID: [String: PluginTool]] = [\n            .init(moduleName: \"MyPlugin\", packageIdentity: .plain(\"MyPkg\")) : [\n                \"MyGenerator\": .init(path: \"/Foo\", source: .built)\n            ]\n        ]\n\n        return try await BuildPlanResult(\n            plan: mockBuildPlan(\n                buildPath: buildDir,\n                triple: UserToolchain.default.targetTriple,\n                graph: graph,\n                pluginConfiguration: pluginConfiguration,\n                pluginTools: pluginTools,\n                fileSystem: fs,\n                observabilityScope: observability\n            )\n        )\n    }\n\n    /// This is more to test out that the setup routines provide a good test environment\n    @Test func testSwift() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try await setup(\n            kind: .swiftModule,\n            gened: [\"Gened.swift\"],\n            observability: observability.topScope\n        )\n        #expect(!observability.hasErrorDiagnostics && !observability.hasWarningDiagnostics)\n    }\n\n    @Test func testSuccess() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let result = try await setup(\n            gened: [\n                \"include/Gened.h\",\n                \"include/module.modulemap\",\n                \"include/Gened.apinotes\",\n                \"Gened.c\",\n            ], observability: observability.topScope\n        )\n        #expect(!observability.hasErrorDiagnostics && !observability.hasWarningDiagnostics)\n\n        let module = try #require(try result.allTargets(named: \"MyModule\").only?.clang())\n        let pluginOutputDir: AbsolutePath = \"/MyPkg/.build/plugins/outputs/mypkg/MyModule/destination/MyPlugin\"\n        let pluginIncludeDir = pluginOutputDir.appending(\"include\")\n        #expect(module.pluginDerivedPublicHeaderPaths == [pluginIncludeDir])\n        let pluginModuleMap = pluginIncludeDir.appending(\"module.modulemap\")\n        let pluginModuleMapFile = \"-fmodule-map-file=\\(pluginModuleMap.pathString)\"\n        #expect(module.pluginDerivedModuleMap == pluginModuleMap)\n        #expect(module.pluginDerivedAPINotes == [pluginIncludeDir.appending(\"Gened.apinotes\")])\n        let pluginSource = pluginOutputDir.appending(\"Gened.c\")\n        #expect(try module.compilePaths().contains(where: { $0.source == pluginSource }))\n        let cmd = try module.emitCommandLine(for: pluginSource)\n        #expect(cmd.contains(pluginIncludeDir.pathString))\n\n        // Ensure the C module consumes the generated module map\n        let cModule = try #require(try result.allTargets(named: \"MyCModule\").only?.clang())\n        let cModuleSource: AbsolutePath = \"/MyPkg/Sources/MyCModule/MyCModule.c\"\n        #expect(try cModule.compilePaths().contains(where: { $0.source == cModuleSource }))\n        let cModuleCmd = try cModule.emitCommandLine(for: cModuleSource)\n        #expect(cModuleCmd.contains(pluginIncludeDir.pathString))\n        #expect(cModuleCmd.contains(pluginModuleMapFile))\n\n        // Ensure the Swift module does also\n        let swiftModule = try #require(try result.allTargets(named: \"MyExe\").only?.swift())\n        let swiftModuleArgs = try swiftModule.compileArguments()\n        #expect(swiftModuleArgs.contains(pluginIncludeDir.pathString))\n        #expect(swiftModuleArgs.contains(pluginModuleMapFile))\n    }\n\n    /// Test that generating C into Swift modules throws warnings\n    @Test func testCinSwift() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try await setup(\n            kind: .swiftModule,\n            gened: [\n                \"include/Gened.h\",\n                \"include/module.modulemap\",\n                \"include/Gened.apinotes\",\n                \"Gened.c\",\n            ], observability: observability.topScope\n        )\n\n        let warnings = observability.warnings.map(\\.message)\n        let messages: [String] = [\n            \"Only C modules support plugin generated C header files: \\(pluginHeaderFile.pathString)\",\n            \"Only C modules support plugin generated module map files: \\(pluginModuleMapFile.pathString)\",\n            \"Only C modules support plugin generated API notes files: \\(pluginAPINotesFile.pathString)\",\n            \"Only C modules support plugin generated C source files: \\(pluginSourceFile.pathString)\",\n        ]\n\n        #expect(warnings.count == messages.count)\n        for message in messages {\n            #expect(warnings.contains(message))\n        }\n\n    }\n\n    /// Test that the feature is disabled on previous tools versions\n    @Test func testOldToolsVersion() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try await setup(\n            gened: [\n                \"include/Gened.h\",\n                \"include/module.modulemap\",\n                \"include/Gened.apinotes\",\n                \"Gened.c\",\n            ],\n            toolsVersion: .v6_2,\n            observability: observability.topScope\n        )\n        let warnings = observability.warnings.map(\\.message)\n        let messages: [String] = [\n            \"C header file generation not enabled: \\(pluginHeaderFile.pathString)\",\n            \"Module map generation not enabled: \\(pluginModuleMapFile.pathString)\",\n            \"API notes generation not enabled: \\(pluginAPINotesFile.pathString)\",\n            \"C source file generation not enabled: \\(pluginSourceFile.pathString)\",\n        ]\n\n        #expect(warnings.count == messages.count)\n        for message in messages {\n            #expect(warnings.contains(message))\n        }\n    }\n\n    /// Test that the feature is disabled on previous tools versions\n    @Test func testFeatureNotEnabled() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try await setup(\n            gened: [\n                \"include/Gened.h\",\n                \"include/module.modulemap\",\n                \"include/Gened.apinotes\",\n                \"Gened.c\",\n            ],\n            toolsVersion: .v6_3,\n            observability: observability.topScope\n        )\n        let warnings = observability.warnings.map(\\.message)\n        let messages: [String] = [\n            \"C header file generation not enabled: \\(pluginHeaderFile.pathString)\",\n            \"Module map generation not enabled: \\(pluginModuleMapFile.pathString)\",\n            \"API notes generation not enabled: \\(pluginAPINotesFile.pathString)\",\n            \"C source file generation not enabled: \\(pluginSourceFile.pathString)\",\n        ]\n\n        #expect(warnings.count == messages.count)\n        for message in messages {\n            #expect(warnings.contains(message))\n        }\n    }\n}\n\nextension HostToPluginMessage.InputContext {\n    func url(for id: WireInput.URL.Id) throws -> AbsolutePath {\n        // Compose a path based on an optional base path and a subpath.\n        let wirePath = paths[id]\n        let basePath = try paths[id].baseURLId.map{ try self.url(for: $0) }\n        let path: AbsolutePath\n        if let basePath {\n            path = basePath.appending(wirePath.subpath)\n        } else {\n            path = AbsolutePath.root.appending(wirePath.subpath)\n        }\n        return path\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/ClangTargetBuildDescriptionTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import Build\nimport PackageGraph\nimport PackageModel\nimport SPMBuildCore\nimport _InternalTestSupport\nimport XCTest\n\nfinal class ClangTargetBuildDescriptionTests: XCTestCase {\n    func testClangIndexStorePath() throws {\n        let targetDescription = try makeTargetBuildDescription(\"test\")\n        XCTAssertTrue(try targetDescription.basicArguments().contains(\"-index-store-path\"))\n        XCTAssertFalse(try targetDescription.basicArguments().contains(\"-w\"))\n    }\n\n    func testSwiftCorelibsFoundationIncludeWorkaround() throws {\n        let toolchain = try MockToolchain(swiftResourcesPath: AbsolutePath(\"/fake/path/lib/swift\"))\n\n        let macosParameters = mockBuildParameters(destination: .target, toolchain: toolchain, triple: .macOS)\n        let linuxParameters = mockBuildParameters(destination: .target, toolchain: toolchain, triple: .arm64Linux)\n        let androidParameters = mockBuildParameters(destination: .target, toolchain: toolchain, triple: .arm64Android)\n\n        let macDescription = try makeTargetBuildDescription(\"swift-corelibs-foundation\",\n                                                            buildParameters: macosParameters)\n        XCTAssertFalse(try macDescription.basicArguments().contains(\"\\(macosParameters.toolchain.swiftResourcesPath!)\"))\n\n        let linuxDescription = try makeTargetBuildDescription(\"swift-corelibs-foundation\",\n                                                              buildParameters: linuxParameters)\n        print(try linuxDescription.basicArguments())\n        XCTAssertTrue(try linuxDescription.basicArguments().contains(\"\\(linuxParameters.toolchain.swiftResourcesPath!)\"))\n\n        let androidDescription = try makeTargetBuildDescription(\"swift-corelibs-foundation\",\n                                                                buildParameters: androidParameters)\n        XCTAssertTrue(try androidDescription.basicArguments().contains(\"\\(androidParameters.toolchain.swiftResourcesPath!)\"))\n    }\n\n    func testWarningSuppressionForRemotePackages() throws {\n        let targetDescription = try makeTargetBuildDescription(\"test-warning-supression\", usesSourceControl: true)\n        XCTAssertTrue(try targetDescription.basicArguments().contains(\"-w\"))\n    }\n\n    private func makeClangTarget() throws -> ClangModule {\n        try ClangModule(\n            name: \"dummy\",\n            cLanguageStandard: nil,\n            cxxLanguageStandard: nil,\n            includeDir: .root,\n            moduleMapType: .none,\n            type: .library,\n            path: .root,\n            sources: .init(paths: [.root.appending(component: \"foo.c\")], root: .root),\n            usesUnsafeFlags: false,\n            implicit: true\n        )\n    }\n\n    private func makeResolvedTarget() throws -> ResolvedModule {\n        ResolvedModule(\n            packageIdentity: .plain(\"dummy\"),\n            underlying: try makeClangTarget(),\n            dependencies: [],\n            supportedPlatforms: [],\n            platformConstraint: .all,\n            platformVersionProvider: .init(implementation: .minimumDeploymentTargetDefault)\n        )\n    }\n\n    private func makeTargetBuildDescription(_ packageName: String,\n                                            buildParameters: BuildParameters? = nil,\n                                            usesSourceControl: Bool = false) throws -> ClangModuleBuildDescription {\n        let observability = ObservabilitySystem.makeForTesting(verbose: false)\n\n        let manifest: Manifest\n        if usesSourceControl {\n            manifest = Manifest.createLocalSourceControlManifest(\n                displayName: packageName, path: AbsolutePath(\"/\\(packageName)\"))\n        } else {\n            manifest = Manifest.createRootManifest(\n                displayName: packageName,\n                toolsVersion: .v5,\n                targets: [try TargetDescription(name: \"dummy\")])\n        }\n\n        let target = try makeResolvedTarget()\n\n        let package = Package(identity: .plain(packageName),\n                              manifest: manifest,\n                              path: .root,\n                              targets: [target.underlying],\n                              products: [],\n                              targetSearchPath: .root,\n                              testTargetSearchPath: .root)\n\n        return try ClangModuleBuildDescription(\n            package: .init(underlying: package,\n                           defaultLocalization: nil,\n                           supportedPlatforms: [],\n                           dependencies: [],\n                           enabledTraits: [],\n                           modules: .init([target]),\n                           products: [],\n                           registryMetadata: nil,\n                           platformVersionProvider: .init(implementation: .minimumDeploymentTargetDefault)),\n            target: target,\n            toolsVersion: .current,\n            buildParameters: buildParameters ?? mockBuildParameters(\n                destination: .target,\n                toolchain: try UserToolchain.default,\n                indexStoreMode: .on\n            ),\n            fileSystem: localFileSystem,\n            observabilityScope: observability.topScope\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/CrossCompilationBuildPlanTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport class Basics.InMemoryFileSystem\nimport class Basics.ObservabilitySystem\nimport class Build.BuildPlan\nimport class Build.ProductBuildDescription\n@testable import enum Build.ModuleBuildDescription\nimport class Build.SwiftModuleBuildDescription\nimport struct Basics.Triple\nimport class PackageModel.Manifest\nimport struct PackageModel.TargetDescription\nimport enum PackageModel.ProductType\nimport struct SPMBuildCore.BuildParameters\nimport func _InternalTestSupport.loadPackageGraph\n\nimport func _InternalTestSupport.embeddedCxxInteropPackageGraph\nimport func _InternalTestSupport.macrosPackageGraph\nimport func _InternalTestSupport.macrosTestsPackageGraph\nimport func _InternalTestSupport.mockBuildParameters\nimport func _InternalBuildTestSupport.mockBuildPlan\nimport func _InternalTestSupport.toolsExplicitLibrariesGraph\nimport func _InternalTestSupport.trivialPackageGraph\n\nimport struct _InternalBuildTestSupport.BuildPlanResult\nimport func _InternalTestSupport.XCTAssertMatch\nimport func _InternalTestSupport.XCTAssertNoDiagnostics\n\nimport XCTest\nimport Testing\n\nfinal class CrossCompilationBuildPlanTests: XCTestCase {\n    func testEmbeddedWasmTarget() async throws {\n        var (graph, fs, observabilityScope) = try trivialPackageGraph()\n\n        let triple = try Triple(\"wasm32-unknown-none-wasm\")\n\n        let linkingParameters = BuildParameters.Linking(\n            shouldLinkStaticSwiftStdlib: true\n        )\n\n        var result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: triple,\n            graph: graph,\n            linkingParameters: linkingParameters,\n            fileSystem: fs,\n            observabilityScope: observabilityScope\n        ))\n        result.checkProductsCount(2)\n        // There are two additional modules on non-Apple platforms, for test discovery and\n        // test entry point\n        result.checkTargetsCount(5)\n\n        let buildPath = result.plan.productsBuildPath\n        var appBuildDescription = try result.buildProduct(for: \"app\")\n        XCTAssertEqual(\n            try appBuildDescription.linkArguments(),\n            [\n                result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n                \"-L\", buildPath.pathString,\n                \"-o\", buildPath.appending(components: \"app.wasm\").pathString,\n                \"-module-name\", \"app\", \"-static-stdlib\", \"-emit-executable\",\n                \"@\\(buildPath.appending(components: \"app.product\", \"Objects.LinkFileList\"))\",\n                \"-target\", triple.tripleString,\n                \"-g\",\n            ]\n        )\n\n        (graph, fs, observabilityScope) = try embeddedCxxInteropPackageGraph()\n\n        result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: triple,\n            graph: graph,\n            linkingParameters: linkingParameters,\n            fileSystem: fs,\n            observabilityScope: observabilityScope\n        ))\n        result.checkProductsCount(2)\n        // There are two additional modules on non-Apple platforms, for test discovery and\n        // test entry point\n        result.checkTargetsCount(5)\n\n        appBuildDescription = try result.buildProduct(for: \"app\")\n        XCTAssertEqual(\n            try appBuildDescription.linkArguments(),\n            [\n                result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n                \"-L\", buildPath.pathString,\n                \"-o\", buildPath.appending(components: \"app.wasm\").pathString,\n                \"-module-name\", \"app\", \"-static-stdlib\", \"-emit-executable\",\n                \"@\\(buildPath.appending(components: \"app.product\", \"Objects.LinkFileList\"))\",\n                \"-enable-experimental-feature\", \"Embedded\",\n                \"-target\", triple.tripleString,\n                \"-g\",\n            ]\n        )\n    }\n\n    func testWasmTargetRelease() async throws {\n        let (graph, fs, observabilityScope) = try trivialPackageGraph()\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            config: .release,\n            triple: .wasi,\n            graph: graph,\n            linkingParameters: .init(\n                linkerDeadStrip: true,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observabilityScope\n        ))\n        let buildPath = result.plan.productsBuildPath\n\n        let appBuildDescription = try result.buildProduct(for: \"app\")\n        XCTAssertEqual(\n            try appBuildDescription.linkArguments(),\n            [\n                result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n                \"-L\", buildPath.pathString,\n                \"-o\", buildPath.appending(components: \"app.wasm\").pathString,\n                \"-module-name\", \"app\", \"-static-stdlib\", \"-emit-executable\",\n                \"-Xlinker\", \"--gc-sections\",\n                \"@\\(buildPath.appending(components: \"app.product\", \"Objects.LinkFileList\"))\",\n                \"-target\", \"wasm32-unknown-wasi\",\n                \"-g\",\n            ]\n        )\n    }\n\n    func testWASITarget() async throws {\n        let pkgPath = AbsolutePath(\"/Pkg\")\n\n        let (graph, fs, observabilityScope) = try trivialPackageGraph()\n\n        let result = try await BuildPlanResult(plan: mockBuildPlan(\n            triple: .wasi,\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observabilityScope\n        ))\n        result.checkProductsCount(2)\n        // There are two additional modules on non-Apple platforms, for test discovery and\n        // test entry point\n        result.checkTargetsCount(5)\n\n        let buildPath = result.plan.productsBuildPath\n\n        let lib = try XCTUnwrap(\n            result.allTargets(named: \"lib\")\n                .map { try $0.clang() }\n                .first { $0.destination == .target }\n        )\n\n        XCTAssertEqual(try lib.basicArguments(isCXX: false), [\n            \"-target\", \"wasm32-unknown-wasi\",\n            \"-O0\", \"-DSWIFT_PACKAGE=1\", \"-DDEBUG=1\",\n            \"-fblocks\",\n            \"-I\", pkgPath.appending(components: \"Sources\", \"lib\", \"include\").pathString,\n            \"-g\",\n        ])\n        XCTAssertEqual(try lib.objects, [buildPath.appending(components: \"lib.build\", \"lib.c.o\")])\n        XCTAssertEqual(lib.moduleMap, buildPath.appending(components: \"lib.build\", \"module.modulemap\"))\n\n        let exe = try result.moduleBuildDescription(for: \"app\").swift().compileArguments()\n        XCTAssertMatch(\n            exe,\n            [\n                \"-enable-batch-mode\", \"-serialize-diagnostics\", \"-Onone\", \"-enable-testing\",\n                \"-j3\", \"-DSWIFT_PACKAGE\", \"-DDEBUG\", \"-DSWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\", \"-Xcc\",\n                \"-fmodule-map-file=\\(buildPath.appending(components: \"lib.build\", \"module.modulemap\"))\",\n                \"-Xcc\", \"-I\", \"-Xcc\", \"\\(pkgPath.appending(components: \"Sources\", \"lib\", \"include\"))\",\n                \"-module-cache-path\", \"\\(buildPath.appending(components: \"ModuleCache\"))\", .anySequence,\n                \"-swift-version\", \"4\", \"-g\", .anySequence,\n            ]\n        )\n\n        let appBuildDescription = try result.buildProduct(for: \"app\")\n        XCTAssertEqual(\n            try appBuildDescription.linkArguments(),\n            [\n                result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n                \"-L\", buildPath.pathString,\n                \"-o\", buildPath.appending(components: \"app.wasm\").pathString,\n                \"-module-name\", \"app\", \"-static-stdlib\", \"-emit-executable\",\n                \"@\\(buildPath.appending(components: \"app.product\", \"Objects.LinkFileList\"))\",\n                \"-target\", \"wasm32-unknown-wasi\",\n                \"-g\",\n            ]\n        )\n\n        let executablePathExtension = try appBuildDescription.binaryPath.extension\n        XCTAssertEqual(executablePathExtension, \"wasm\")\n\n        let testBuildDescription = try result.buildProduct(for: \"PkgPackageTests\")\n        XCTAssertEqual(\n            try testBuildDescription.linkArguments(),\n            [\n                result.plan.destinationBuildParameters.toolchain.swiftCompilerPath.pathString,\n                \"-L\", buildPath.pathString,\n                \"-o\", buildPath.appending(components: \"PkgPackageTests.xctest\").pathString,\n                \"-module-name\", \"PkgPackageTests\",\n                \"-emit-executable\",\n                \"@\\(buildPath.appending(components: \"PkgPackageTests.product\", \"Objects.LinkFileList\"))\",\n                \"-target\", \"wasm32-unknown-wasi\",\n                \"-g\",\n            ]\n        )\n\n        let testPathExtension = try testBuildDescription.binaryPath.extension\n        XCTAssertEqual(testPathExtension, \"xctest\")\n    }\n\n    func testMacros() async throws {\n        let (graph, fs, scope) = try macrosPackageGraph()\n\n        let destinationTriple = Triple.arm64Linux\n        let toolsTriple = Triple.x86_64MacOS\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                shouldLinkStaticSwiftStdlib: true,\n                triple: destinationTriple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: toolsTriple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n        let result = try BuildPlanResult(plan: plan)\n        result.checkProductsCount(3)\n        result.checkTargetsCount(10)\n\n        XCTAssertTrue(try result.allTargets(named: \"SwiftSyntax\")\n            .map { try $0.swift() }\n            .contains { $0.destination == .host })\n        try result.check(destination: .host, triple: toolsTriple, for: \"MMIOMacros\")\n        try result.check(destination: .target, triple: destinationTriple, for: \"MMIO\")\n        try result.check(destination: .target, triple: destinationTriple, for: \"Core\")\n        try result.check(destination: .target, triple: destinationTriple, for: \"HAL\")\n\n        let macroProducts = result.allProducts(named: \"MMIOMacros\")\n        XCTAssertEqual(macroProducts.count, 1)\n        let macroProduct = try XCTUnwrap(macroProducts.first)\n        XCTAssertEqual(macroProduct.buildParameters.triple, toolsTriple)\n\n        let mmioTargets = try result.allTargets(named: \"MMIO\").map { try $0.swift() }\n        XCTAssertEqual(mmioTargets.count, 1)\n        let mmioTarget = try XCTUnwrap(mmioTargets.first)\n        let compileArguments = try mmioTarget.emitCommandLine()\n        XCTAssertMatch(\n            compileArguments,\n            [\n                \"-I\", .equal(mmioTarget.moduleOutputPath.parentDirectory.pathString),\n                .anySequence,\n                \"-Xfrontend\", \"-load-plugin-executable\",\n                // Verify that macros are located in the tools triple directory.\n                \"-Xfrontend\", .contains(toolsTriple.tripleString)\n            ]\n        )\n    }\n\n    func testMacrosTests() async throws {\n        let (graph, fs, scope) = try macrosTestsPackageGraph()\n\n        let destinationTriple = Triple.arm64Linux\n        let toolsTriple = Triple.x86_64MacOS\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                shouldLinkStaticSwiftStdlib: true,\n                triple: destinationTriple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: toolsTriple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        // Make sure that build plan doesn't have any \"target\" tests except SwiftSyntax ones.\n        for description in plan.targetMap where description.module.underlying.type == .test {\n            XCTAssertEqual(\n                description.buildParameters.destination,\n                description.module.name == \"SwiftSyntaxTests\" ? .target : .host\n            )\n        }\n\n        let result = try BuildPlanResult(plan: plan)\n        result.checkProductsCount(3)\n        result.checkTargetsCount(20)\n\n        XCTAssertTrue(try result.allTargets(named: \"SwiftSyntax\")\n            .map { try $0.swift() }\n            .contains { $0.destination == .host })\n\n        try result.check(destination: .host, triple: toolsTriple, for: \"swift-mmioPackageTests\")\n        try result.check(destination: .host, triple: toolsTriple, for: \"swift-mmioPackageDiscoveredTests\")\n        try result.check(destination: .host, triple: toolsTriple, for: \"MMIOMacros\")\n        try result.check(destination: .target, triple: destinationTriple, for: \"MMIO\")\n        try result.check(destination: .host, triple: toolsTriple, for: \"MMIOMacrosTests\")\n        try result.check(destination: .target, triple: destinationTriple, for: \"swift-syntaxPackageTests\")\n\n        let macroProducts = result.allProducts(named: \"MMIOMacros\")\n        XCTAssertEqual(macroProducts.count, 1)\n        let macroProduct = try XCTUnwrap(macroProducts.first)\n        XCTAssertEqual(macroProduct.buildParameters.triple, toolsTriple)\n\n        let mmioTargets = try result.allTargets(named: \"MMIO\").map { try $0.swift() }\n        XCTAssertEqual(mmioTargets.count, 1)\n        let mmioTarget = try XCTUnwrap(mmioTargets.first)\n        let compileArguments = try mmioTarget.emitCommandLine()\n        XCTAssertMatch(\n            compileArguments,\n            [\n                \"-I\", .equal(mmioTarget.moduleOutputPath.parentDirectory.pathString),\n                .anySequence,\n                \"-Xfrontend\", \"-load-plugin-executable\",\n                // Verify that macros are located in the tools triple directory.\n                \"-Xfrontend\", .contains(toolsTriple.tripleString)\n            ]\n        )\n    }\n\n    func testToolsExplicitLibraries() async throws {\n        let destinationTriple = Triple.arm64Linux\n        let toolsTriple = Triple.x86_64MacOS\n\n        for (linkage, productFileName) in [(ProductType.LibraryType.static, \"libSwiftSyntax-tool.a\"), (.dynamic, \"libSwiftSyntax-tool.dylib\")] {\n            let (graph, fs, scope) = try toolsExplicitLibrariesGraph(linkage: linkage)\n            let plan = try await BuildPlan(\n                destinationBuildParameters: mockBuildParameters(\n                    destination: .target,\n                    shouldLinkStaticSwiftStdlib: true,\n                    triple: destinationTriple\n                ),\n                toolsBuildParameters: mockBuildParameters(\n                    destination: .host,\n                    triple: toolsTriple\n                ),\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: scope\n            )\n            let result = try BuildPlanResult(plan: plan)\n            result.checkProductsCount(4)\n            result.checkTargetsCount(6)\n\n            XCTAssertTrue(try result.allTargets(named: \"SwiftSyntax\")\n                .map { try $0.swift() }\n                .contains { $0.destination == .host })\n\n            try result.check(destination: .host, triple: toolsTriple, for: \"swift-mmioPackageTests\")\n            try result.check(destination: .host, triple: toolsTriple, for: \"swift-mmioPackageDiscoveredTests\")\n            try result.check(destination: .host, triple: toolsTriple, for: \"MMIOMacros\")\n            try result.check(destination: .host, triple: toolsTriple, for: \"MMIOMacrosTests\")\n\n            let macroProducts = result.allProducts(named: \"MMIOMacros\")\n            XCTAssertEqual(macroProducts.count, 1)\n            let macroProduct = try XCTUnwrap(macroProducts.first)\n            XCTAssertEqual(macroProduct.buildParameters.triple, toolsTriple)\n\n            let swiftSyntaxProducts = result.allProducts(named: \"SwiftSyntax\")\n            XCTAssertEqual(swiftSyntaxProducts.count, 2)\n            let swiftSyntaxToolsProduct = try XCTUnwrap(swiftSyntaxProducts.first { $0.destination == .host })\n            let archiveArguments = try swiftSyntaxToolsProduct.archiveArguments()\n\n            // Verify that produced library file has a correct name\n            XCTAssertMatch(archiveArguments, [.contains(productFileName)])\n        }\n    }\n}\n\nextension BuildPlanResult {\n    func allTargets(named name: String) throws -> some Collection<ModuleBuildDescription> {\n        self.targetMap\n            .filter { $0.module.name == name }\n    }\n\n    func allProducts(named name: String) -> some Collection<ProductBuildDescription> {\n        self.productMap\n            .filter { $0.product.name == name }\n    }\n\n    func check(\n        destination: BuildParameters.Destination,\n        triple: Triple,\n        for target: String,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) throws {\n        let targets = self.targetMap.filter {\n            $0.module.name == target && $0.destination == destination\n        }\n        XCTAssertEqual(targets.count, 1, file: file, line: line)\n\n        let target = try XCTUnwrap(\n            targets.first,\n            file: file,\n            line: line\n        ).swift()\n        XCTAssertMatch(try target.emitCommandLine(), [.contains(triple.tripleString)], file: file, line: line)\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/IncrementalBuildTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\nimport class Basics.AsyncProcess\nimport typealias TSCBasic.ProcessEnvironmentBlock\n\n/// Functional tests of incremental builds.  These are fairly ad hoc at this\n/// point, and because of the time they take, they need to be kept minimal.\n/// There are at least a couple of ways in which this could be improved to a\n/// greater or lesser degree:\n///\n/// a) we could look at the llbuild manifest to determine that the right fine-\n///    grained dependencies exist (however, this feels a bit too much like a\n///    \"test that we wrote what we wrote\" kind of test, i.e. it doesn't really\n///    test that the net effect of triggering rebuilds is achieved; it is also\n///    hard to write such tests in a black-box manner, i.e. in terms of the\n///    desired effect\n///\n/// b) a much better way would be if llbuild could quickly report on what files\n///    it would update if a build were to be triggered;  this would be a lot\n///    faster than actually doing the build, but would of course also bake in\n///    an assumption that the needs-to-be-rebuilt state of a file system entity\n///    could be determined without running any of the commands (i.e. it would\n///    assume that there's no feedback during the build)\n///\nfinal class IncrementalBuildTests: XCTestCase {\n\n    func testIncrementalSingleModuleCLibraryInSources() async throws {\n        try XCTSkipIf(!UserToolchain.default.supportsSDKDependentTests(), \"skipping because test environment doesn't support this test\")\n        try await fixtureXCTest(name: \"CFamilyTargets/CLibrarySources\") { fixturePath in\n            // Build it once and capture the log (this will be a full build).\n            let (fullLog, _) = try await executeSwiftBuild(fixturePath, buildSystem: .native)\n\n            // Check various things that we expect to see in the full build log.\n            // FIXME:  This is specific to the format of the log output, which\n            // is quite unfortunate but not easily avoidable at the moment.\n            XCTAssertMatch(fullLog, .contains(\"Compiling CLibrarySources Foo.c\"))\n\n            let llbuildManifest = fixturePath.appending(components: \".build\", \"debug.yaml\")\n\n            // Modify the source file in a way that changes its size so that the low-level\n            // build system can detect the change (the timestamp change might be too small\n            // for the granularity of the file system to represent as distinct values).\n            let sourceFile = fixturePath.appending(components: \"Sources\", \"Foo.c\")\n            try localFileSystem.writeFileContents(\n                sourceFile,\n                string: \"\\(try localFileSystem.readFileContents(sourceFile))\\n\"\n            )\n\n            // Read the first llbuild manifest.\n            let llbuildContents1: String = try localFileSystem.readFileContents(llbuildManifest)\n\n            // Now build again.  This should be an incremental build.\n            let (log2, _) = try await executeSwiftBuild(fixturePath, buildSystem: .native)\n            XCTAssertMatch(log2, .contains(\"Compiling CLibrarySources Foo.c\"))\n\n            // Read the second llbuild manifest.\n            let llbuildContents2: String = try localFileSystem.readFileContents(llbuildManifest)\n\n            // Now build again without changing anything.  This should be a null\n            // build.\n            let (log3, _) = try await executeSwiftBuild(fixturePath, buildSystem: .native)\n            XCTAssertNoMatch(log3, .contains(\"Compiling CLibrarySources Foo.c\"))\n\n            // Read the third llbuild manifest.\n            let llbuildContents3: String = try localFileSystem.readFileContents(llbuildManifest)\n\n            XCTAssertEqual(llbuildContents1, llbuildContents2)\n            XCTAssertEqual(llbuildContents2, llbuildContents3)\n\n            // Modify the header file in a way that changes its size so that the low-level\n            // build system can detect the change (the timestamp change might be too small\n            // for the granularity of the file system to represent as distinct values).\n            let headerFile = fixturePath.appending(components: \"Sources\", \"include\", \"Foo.h\")\n            try localFileSystem.writeFileContents(\n                headerFile,\n                string: \"\\(try localFileSystem.readFileContents(headerFile))\\n\"\n            )\n\n            // Now build again.  This should be an incremental build.\n            let (log4, _) = try await executeSwiftBuild(fixturePath, buildSystem: .native)\n            XCTAssertMatch(log4, .contains(\"Compiling CLibrarySources Foo.c\"))\n        }\n    }\n\n    func testBuildManifestCaching() async throws {\n        try XCTSkipIf(!UserToolchain.default.supportsSDKDependentTests(), \"skipping because test environment doesn't support this test\")\n        try await fixtureXCTest(name: \"ValidLayouts/SingleModule/Library\") { fixturePath in\n            @discardableResult\n            func build() async throws -> String {\n                return try await executeSwiftBuild(fixturePath, buildSystem: .native).stdout\n            }\n\n            // Perform a full build.\n            let log1 = try await build()\n            XCTAssertMatch(log1, .contains(\"Compiling Library\"))\n\n            // Ensure manifest caching kicks in.\n            let log2 =  try await build()\n            XCTAssertMatch(log2, .contains(\"Planning build\"))\n\n            // Check that we're not re-planning when nothing has changed.\n            let log3 = try await build()\n            XCTAssertNoMatch(log3, .contains(\"Planning build\"))\n\n            // Check that we do run planning when a new source file is added.\n            let sourceFile = fixturePath.appending(components: \"Sources\", \"Library\", \"new.swift\")\n            try localFileSystem.writeFileContents(sourceFile, bytes: \"\")\n            let log4 = try await build()\n            XCTAssertMatch(log4, .contains(\"Compiling Library\"))\n            XCTAssertMatch(log4, .contains(\"Planning build\"))\n\n            // Check that we don't run planning when a source file is modified.\n            try localFileSystem.writeFileContents(sourceFile, bytes: \"\\n\\n\\n\\n\")\n            let log5 = try await build()\n            XCTAssertNoMatch(log5, .contains(\"Planning build\"))\n        }\n    }\n\n    func testDisableBuildManifestCaching() async throws {\n        try XCTSkipIf(!UserToolchain.default.supportsSDKDependentTests(), \"skipping because test environment doesn't support this test\")\n        try await fixtureXCTest(name: \"ValidLayouts/SingleModule/Library\") { fixturePath in\n            @discardableResult\n            func build() async throws -> String {\n                return try await executeSwiftBuild(\n                    fixturePath,\n                    extraArgs: [\"--disable-build-manifest-caching\"],\n                    buildSystem: .native,\n                ).stdout\n            }\n\n            // Perform a full build.\n            let log1 = try await build()\n            XCTAssertMatch(log1, .contains(\"Compiling Library\"))\n\n            // Ensure manifest caching does not kick in.\n            let log2 = try await build()\n            XCTAssertNoMatch(log2, .contains(\"Planning build\"))\n        }\n    }\n    // testing the fix for tracking SDK dependencies to avoid triggering rebuilds when the SDK changes (rdar://115777026)\n    func testSDKTracking() async throws {\n#if os(macOS)\n        try XCTSkipIf(!UserToolchain.default.supportsSDKDependentTests(), \"skipping because test environment doesn't support this test\")\n\n        try await fixtureXCTest(name: \"ValidLayouts/SingleModule/Library\") { fixturePath in\n            let dummySwiftcPath = SwiftPM.xctestBinaryPath(for: \"dummy-swiftc\")\n            let swiftCompilerPath = try UserToolchain.default.swiftCompilerPath\n            let environment: Environment = [\n                \"SWIFT_EXEC\": dummySwiftcPath.pathString,\n                \"SWIFT_ORIGINAL_PATH\": swiftCompilerPath.pathString\n            ]\n            let sdkPathStr = try await AsyncProcess.checkNonZeroExit(\n                arguments: [\"/usr/bin/xcrun\", \"--sdk\", \"macosx\", \"--show-sdk-path\"],\n                environment: environment\n            ).spm_chomp()\n\n            let newSdkPathStr = \"/tmp/../\\(sdkPathStr)\"\n            // Perform a full build again because SDK changed.\n            let log1 = try await executeSwiftBuild(\n                fixturePath,\n                env: [\"SDKROOT\": newSdkPathStr],\n                buildSystem: .native,\n            ).stdout\n            XCTAssertMatch(log1, .contains(\"Compiling Library\"))\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/LLBuildManifestBuilderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\n@testable import Build\nimport LLBuildManifest\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport PackageGraph\n\nimport PackageModel\nimport struct SPMBuildCore.BuildParameters\n\nimport _InternalBuildTestSupport\n@_spi(SwiftPMInternal)\nimport _InternalTestSupport\n\nimport Testing\n\nstruct LLBuildManifestBuilderTests {\n    @Test\n    func createProductCommand() async throws {\n        let pkg = AbsolutePath(\"/pkg\")\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                pkg.appending(components: \"Sources\", \"exe\", \"main.swift\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: .init(validating: pkg.pathString),\n                    targets: [\n                        TargetDescription(name: \"exe\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        // macOS, release build\n\n        var plan = try await mockBuildPlan(\n            environment: BuildEnvironment(\n                platform: .macOS,\n                configuration: .release\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        var result = try BuildPlanResult(plan: plan)\n        var buildProduct = try result.buildProduct(for: \"exe\")\n\n        var llbuild = LLBuildManifestBuilder(\n            plan,\n            fileSystem: localFileSystem,\n            observabilityScope: observability.topScope\n        )\n        try llbuild.createProductCommand(buildProduct)\n\n        var basicReleaseCommandNames = [\n            AbsolutePath(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/release/exe.product/Objects.LinkFileList\").pathString,\n            \"<exe-\\(plan.destinationBuildParameters.triple)-release.exe>\",\n            \"C.exe-\\(plan.destinationBuildParameters.triple)-release.exe\",\n        ]\n\n        #expect(llbuild.manifest.commands.map(\\.key).sorted() == basicReleaseCommandNames.sorted())\n\n        // macOS, debug build\n\n        plan = try await mockBuildPlan(\n            environment: BuildEnvironment(\n                platform: .macOS,\n                configuration: .debug\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        result = try BuildPlanResult(plan: plan)\n        buildProduct = try result.buildProduct(for: \"exe\")\n\n        llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.createProductCommand(buildProduct)\n\n        let entitlementsCommandName = \"C.exe-\\(plan.destinationBuildParameters.triple)-debug.exe-entitlements\"\n        var basicDebugCommandNames = [\n            AbsolutePath(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/debug/exe.product/Objects.LinkFileList\").pathString,\n            \"<exe-\\(plan.destinationBuildParameters.triple)-debug.exe>\",\n            \"C.exe-\\(plan.destinationBuildParameters.triple)-debug.exe\",\n        ]\n\n        #expect(llbuild.manifest.commands.map(\\.key).sorted() == (basicDebugCommandNames + [\n            AbsolutePath(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/debug/exe-entitlement.plist\").pathString,\n            entitlementsCommandName,\n        ]).sorted())\n\n        let entitlementsCommand = try #require(\n            llbuild.manifest.commands[entitlementsCommandName]?.tool as? ShellTool,\n            \"unexpected entitlements command type\"\n        )\n\n        #expect(entitlementsCommand.inputs == [\n            .file(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/debug/exe\", isMutated: true),\n            .file(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/debug/exe-entitlement.plist\"),\n        ])\n        #expect(entitlementsCommand.outputs == [\n            .virtual(\"exe-\\(plan.destinationBuildParameters.triple)-debug.exe-CodeSigning\"),\n        ])\n\n        // Linux, release build\n\n        plan = try await mockBuildPlan(\n            environment: BuildEnvironment(\n                platform: .linux,\n                configuration: .release\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        result = try BuildPlanResult(plan: plan)\n        buildProduct = try result.buildProduct(for: \"exe\")\n\n        llbuild = LLBuildManifestBuilder(plan, fileSystem: localFileSystem, observabilityScope: observability.topScope)\n        try llbuild.createProductCommand(buildProduct)\n\n        basicReleaseCommandNames = [\n            AbsolutePath(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/release/exe.product/Objects.LinkFileList\").pathString,\n            \"<exe-\\(plan.destinationBuildParameters.triple)-release.exe>\",\n            \"C.exe-\\(plan.destinationBuildParameters.triple)-release.exe\",\n        ]\n\n        #expect(llbuild.manifest.commands.map(\\.key).sorted() == basicReleaseCommandNames.sorted())\n\n        // Linux, debug build\n\n        plan = try await mockBuildPlan(\n            environment: BuildEnvironment(\n                platform: .linux,\n                configuration: .debug\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        result = try BuildPlanResult(plan: plan)\n        buildProduct = try result.buildProduct(for: \"exe\")\n\n        llbuild = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: observability.topScope)\n        try llbuild.createProductCommand(buildProduct)\n\n        basicDebugCommandNames = [\n            AbsolutePath(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/debug/exe.product/Objects.LinkFileList\").pathString,\n            \"<exe-\\(plan.destinationBuildParameters.triple)-debug.exe>\",\n            \"C.exe-\\(plan.destinationBuildParameters.triple)-debug.exe\",\n        ]\n\n        #expect(llbuild.manifest.commands.map(\\.key).sorted() == basicDebugCommandNames.sorted())\n    }\n\n    /// Verifies that two modules with the same name but different triples don't share same build manifest keys.\n    @Test\n    func toolsBuildTriple() async throws {\n        let (graph, fs, scope) = try macrosPackageGraph()\n        let productsTriple = Triple.x86_64MacOS\n        let toolsTriple = Triple.arm64Linux\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                shouldLinkStaticSwiftStdlib: true,\n                triple: productsTriple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: toolsTriple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        let builder = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: scope)\n        let manifest = try builder.generateManifest(at: \"/manifest\")\n\n        #expect(manifest.commands[\"C.SwiftSyntax-aarch64-unknown-linux-gnu-debug-tool.module\"] != nil)\n        // Ensure that Objects.LinkFileList is -tool suffixed.\n        #expect(manifest.commands[AbsolutePath(\"/path/to/build/aarch64-unknown-linux-gnu/debug/MMIOMacros-tool.product/Objects.LinkFileList\").pathString] != nil)\n    }\n\n    /// Verifies the DLLs in an artifact bundle are copied to the output directory on Windows only\n    @Test func windowsDLLsInArtifactBundle() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPkg/Sources/MyExe/MyExe.swift\"\n            ]\n        )\n\n        try fs.writeFileContents(\"/MyPkg/my.artifactbundle/info.json\", string: \"\"\"\n            {\n              \"schemaVersion\": \"1.0\",\n              \"artifacts\": {\n                \"MyBinaryLib\": {\n                  \"version\": \"1\",\n                  \"type\": \"staticLibrary\",\n                  \"variants\": [\n                    {\n                      \"path\": \"x86_64-unknown-windows-msvc/MyBinaryLib.lib\",\n                      \"staticLibraryMetadata\": {\n                        \"headerPaths\": [\n                          \"include\"\n                        ]\n                      },\n                      \"supportedTriples\": [\n                        \"x86_64-unknown-windows-msvc\"\n                      ]\n                    },\n                    {\n                      \"path\": \"arm64-apple-macosx/libMyBinaryLib.a\",\n                      \"staticLibraryMetadata\": {\n                        \"headerPaths\": [\n                          \"include\"\n                        ]\n                      },\n                      \"supportedTriples\": [\n                        \"arm64-apple-macosx\"\n                      ]\n                    },\n                  ]\n                },\n                \"MyBinaryLib.DLL\": {\n                  \"type\": \"experimentalWindowsDLL\",\n                  \"version\": \"1.0.0\",\n                  \"variants\": [\n                    {\n                      \"path\": \"x86_64-unknown-windows-msvc/MyBinaryLib.dll\",\n                      \"supportedTriples\": [\n                        \"x86_64-unknown-windows-msvc\"\n                      ]\n                    }\n                  ]\n                }\n              }\n            }\n            \"\"\")\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                .createRootManifest(\n                    displayName: \"MyPkg\",\n                    path: \"/MyPkg\",\n                    products: [\n                        .init(name: \"MyExe\", type: .executable, targets: [\"MyExe\"])\n                    ],\n                    targets: [\n                        .init(name: \"MyBinaryLib\", path: \"dist\", type: .binary),\n                        .init(name: \"MyExe\", dependencies: [\"MyBinaryLib\"], type: .executable),\n                    ]\n                )\n            ],\n            binaryArtifacts: [\n                .plain(\"MyPkg\"): [\n                    \"MyBinaryLib\": .init(\n                        kind: .artifactsArchive(types: [\n                            .staticLibrary,\n                            .executable,\n                        ]),\n                        originURL: nil, path: \"/MyPkg/my.artifactbundle\")\n                ]\n            ],\n            observabilityScope: observability.topScope\n        )\n        #expect(!observability.hasErrorDiagnostics)\n\n        let windowsPlan = try await mockBuildPlan(\n            triple: .x86_64Windows,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        #expect(!observability.hasErrorDiagnostics)\n\n        let windowsBuild = LLBuildManifestBuilder(windowsPlan, fileSystem: fs, observabilityScope: observability.topScope)\n        #expect(!observability.hasErrorDiagnostics)\n        let windowsManifest = try windowsBuild.generateManifest(at: \"/windows.manifest\")\n\n        let windowsLink = try #require(windowsManifest.commands[\"C.MyExe-x86_64-unknown-windows-msvc-debug.exe\"])\n        let windowsLinkTool = try #require(windowsLink.tool as? ShellTool)\n        #expect(windowsLinkTool.arguments.contains(\"-lMyBinaryLib\"))\n\n        let dll: AbsolutePath = \"/path/to/build/x86_64-unknown-windows-msvc/debug/MyBinaryLib.dll\"\n        let windowsDLLCopy = try #require(windowsManifest.commands[dll.pathString])\n        let windowsDLLCopyTool = try #require(windowsDLLCopy.tool as? CopyTool)\n        let windowsDLLOutput: Node = .file(\"/path/to/build/x86_64-unknown-windows-msvc/debug/MyBinaryLib.dll\")\n        #expect(\n            windowsDLLCopyTool.inputs == [.file(\"/MyPkg/my.artifactbundle/x86_64-unknown-windows-msvc/MyBinaryLib.dll\")]\n            && windowsDLLCopyTool.outputs == [windowsDLLOutput]\n        )\n\n        // Make sure the copy command is consumed in the build graph\n        let consumerCommand = try #require(windowsManifest.commands.filter({ $0.value.tool.inputs.contains(windowsDLLOutput) }).only)\n        #expect(consumerCommand.key == \"C.MyExe-x86_64-unknown-windows-msvc-debug.module\")\n\n        let macosPlan = try await mockBuildPlan(\n            triple: .arm64MacOS,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        #expect(!observability.hasErrorDiagnostics)\n\n        let macosBuild = LLBuildManifestBuilder(macosPlan, fileSystem: fs, observabilityScope: observability.topScope)\n        #expect(!observability.hasErrorDiagnostics)\n        let macosManifest = try macosBuild.generateManifest(at: \"/macos.manifest\")\n\n        let macosLink = try #require(macosManifest.commands[\"C.MyExe-arm64-apple-macosx-debug.exe\"])\n        let macosLinkTool = try #require(macosLink.tool as? ShellTool)\n        #expect(macosLinkTool.arguments.contains(\"-lMyBinaryLib\"))\n\n        #expect(!macosManifest.commands.contains(where: {\n            $0.value.tool.inputs.contains(.file(\"/MyPkg/my.artifactbundle/x86_64-unknown-windows-msvc/MyBinaryLib.dll\"))\n        }))\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/ModuleAliasingBuildTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import Build\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\n@testable import PackageGraph\n\nimport PackageLoading\n@testable import PackageModel\nimport SPMBuildCore\nimport _InternalBuildTestSupport\nimport _InternalTestSupport\nimport SwiftDriver\nimport Workspace\nimport XCTest\nimport Testing\n\nfinal class ModuleAliasingBuildTests: XCTestCase {\n    func testModuleAliasingEmptyAlias() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Foo\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"empty or invalid module alias; ['Logging': '']\"), severity: .error)\n        }\n    }\n\n    func testModuleAliasingInvalidIdentifierAlias() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Foo\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"P$0%^#@\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: .contains(\"empty or invalid module alias; ['Logging': 'P$0%^#@']\"),\n                severity: .error\n            )\n        }\n    }\n\n    func testModuleAliasingDuplicateProductNames() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"barPkg\",\n                                moduleAliases: [\"Logging\": \"BarLogging\"]\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(3)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"BarLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"BarLogging\" }\n        )\n    }\n\n    func testModuleAliasingDuplicateDylibProductNames() async throws {\n        let fooPkg: AbsolutePath = \"/fooPkg\"\n        let barPkg: AbsolutePath = \"/barPkg\"\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        XCTAssertThrowsError(try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: fooPkg,\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.dynamic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: barPkg,\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.dynamic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"barPkg\",\n                                moduleAliases: [\"Logging\": \"BarLogging\"]\n                            )]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )) { error in\n            XCTAssertEqual((error as? PackageGraphError)?.description, \"multiple packages (\\'barpkg\\' (at '\\(barPkg)'), \\'foopkg\\' (at '\\(fooPkg)')) declare products with a conflicting name: \\'Logging’; product names need to be unique across the package graph\")\n        }\n    }\n\n    func testModuleAliasingDuplicateDylibStaticLibProductNames() async throws {\n        let fooPkg: AbsolutePath = \"/fooPkg\"\n        let barPkg: AbsolutePath = \"/barPkg\"\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        XCTAssertThrowsError(try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: fooPkg,\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.dynamic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: barPkg,\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.static), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"barPkg\",\n                                moduleAliases: [\"Logging\": \"BarLogging\"]\n                            )]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )) { error in\n            XCTAssertEqual((error as? PackageGraphError)?.description, \"multiple packages (\\'barpkg\\' (at '\\(barPkg)'), \\'foopkg\\' (at '\\(fooPkg)')) declare products with a conflicting name: \\'Logging’; product names need to be unique across the package graph\")\n        }\n    }\n\n    func testModuleAliasingDuplicateDylibAutomaticProductNames() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\",\n            \"/bazPkg/Sources/Logging/fileLogging.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.dynamic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"barPkg\",\n                                moduleAliases: [\"Logging\": \"BarLogging\"]\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(2)\n        result.checkTargetsCount(3)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"BarLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"BarLogging\" }\n        )\n        #if os(macOS)\n        let dylib = try result.buildProduct(for: \"Logging\")\n        XCTAssertTrue(\n            try dylib.binaryPath.basename == \"libLogging.dylib\" && dylib.package.identity\n                .description == \"barpkg\"\n        )\n        #endif\n    }\n\n    func testModuleAliasingDuplicateStaticLibAutomaticProductNames() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\",\n            \"/bazPkg/Sources/Logging/fileLogging.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bazPkg\",\n                    path: \"/bazPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.static), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/bazPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"fooPkg\"\n                            ),\n                            .product(\n                                name: \"Logging\",\n                                package: \"bazPkg\",\n                                moduleAliases: [\"Logging\": \"BazLogging\"]\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(2)\n        result.checkTargetsCount(3)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"BazLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"BazLogging\" }\n        )\n        #if os(macOS)\n        let staticlib = try result.buildProduct(for: \"Logging\")\n        XCTAssertTrue(\n            try staticlib.binaryPath.basename == \"libLogging.a\" && staticlib.package.identity\n                .description == \"bazpkg\"\n        )\n        #endif\n    }\n\n    func testModuleAliasingDuplicateProductNamesUpstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/xPkg/Sources/Logging/fileLogging.swift\",\n            \"/bPkg/Sources/B/file.swift\",\n            \"/yPkg/Sources/Logging/fileLogging.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"xPkg\",\n                    path: \"/xPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.dynamic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Logging\",\n                            dependencies: []\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"yPkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Logging\",\n                            dependencies: []\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"aPkg\",\n                    path: \"/aPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.dynamic), targets: [\"A\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                .product(name: \"Logging\", package: \"xPkg\"),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bPkg\",\n                    path: \"/bPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"B\", type: .library(.dynamic), targets: [\"B\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"B\",\n                            dependencies: [\n                                .product(name: \"Logging\", package: \"yPkg\"),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [.product(\n                                name: \"A\",\n                                package: \"aPkg\",\n                                moduleAliases: [\"Logging\": \"ALogging\"]\n                            ),\n                            .product(\n                                name: \"B\",\n                                package: \"bPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(4)\n        result.checkTargetsCount(5)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"ALogging\" && $0.module.moduleAliases?[\"Logging\"] == \"ALogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"A\" && $0.module.moduleAliases?[\"Logging\"] == \"ALogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"B\" && $0.module.moduleAliases == nil })\n        #if os(macOS)\n        let dylib = try result.buildProduct(for: \"Logging\")\n        XCTAssertTrue(\n            try dylib.binaryPath.basename == \"libLogging.dylib\" && dylib.package.identity\n                .description == \"xpkg\"\n        )\n        #endif\n    }\n\n    func testModuleAliasingDirectDeps() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Logging\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"FooLogging\"]\n                                           ),\n                                           .product(\n                                               name: \"Logging\",\n                                               package: \"barPkg\",\n                                               moduleAliases: [\"Logging\": \"BarLogging\"]\n                                           )],\n                            type: .executable\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(4)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"FooLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"BarLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"BarLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n\n        let fooLoggingArgs = try result.moduleBuildDescription(for: \"FooLogging\").swift().compileArguments()\n        let barLoggingArgs = try result.moduleBuildDescription(for: \"BarLogging\").swift().compileArguments()\n        let loggingArgs = try result.moduleBuildDescription(for: \"Logging\").swift().compileArguments()\n        let buildPath = result.plan.productsBuildPath\n\n        XCTAssertMatch(\n            fooLoggingArgs,\n            [.anySequence, \"-emit-objc-header\", \"-emit-objc-header-path\",\n             \"\\(buildPath.appending(components: \"FooLogging.build\", \"include\", \"FooLogging-Swift.h\"))\",\n             .anySequence]\n        )\n        XCTAssertMatch(\n            barLoggingArgs,\n            [.anySequence, \"-emit-objc-header\", \"-emit-objc-header-path\",\n             \"\\(buildPath.appending(components: \"BarLogging.build\", \"include\", \"BarLogging-Swift.h\"))\",\n             .anySequence]\n        )\n        XCTAssertMatch(\n            loggingArgs,\n            [.anySequence, \"-emit-objc-header\", \"-emit-objc-header-path\",\n             \"\\(buildPath.appending(components: \"Logging.build\", \"include\", \"Logging-Swift.h\"))\",\n             .anySequence]\n        )\n    }\n\n    func testModuleAliasingDuplicateTargetNameInUpstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/otherPkg/Sources/Utils/fileUtils.swift\",\n            \"/otherPkg/Sources/Logging/fileLogging.swift\",\n            \"/otherPkg/Sources/Math/file.swift\",\n            \"/otherPkg/Sources/Tools/file.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"otherPkg\",\n                    path: \"/otherPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"Math\", type: .library(.automatic), targets: [\"Math\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: [\"Logging\"]),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                        TargetDescription(name: \"Math\", dependencies: [\"Tools\"]),\n                        TargetDescription(name: \"Tools\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/otherPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Math\",\n                                               package: \"otherPkg\"\n                                           ),\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"otherPkg\",\n                                               moduleAliases: [\"Logging\": \"OtherLogging\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(6)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"OtherLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"OtherLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Utils\" && $0.module.moduleAliases?[\"Logging\"] == \"OtherLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n\n        let otherLoggingArgs = try result.moduleBuildDescription(for: \"OtherLogging\").swift().compileArguments()\n        let loggingArgs = try result.moduleBuildDescription(for: \"Logging\").swift().compileArguments()\n        let buildPath = result.plan.productsBuildPath\n\n        XCTAssertMatch(\n            otherLoggingArgs,\n            [.anySequence, \"-emit-objc-header\", \"-emit-objc-header-path\",\n             \"\\(buildPath.appending(components: \"OtherLogging.build\", \"include\", \"OtherLogging-Swift.h\"))\",\n             .anySequence]\n        )\n        XCTAssertMatch(\n            loggingArgs,\n            [.anySequence, \"-emit-objc-header\", \"-emit-objc-header-path\",\n             \"\\(buildPath.appending(components: \"Logging.build\", \"include\", \"Logging-Swift.h\"))\",\n             .anySequence]\n        )\n    }\n\n    func testModuleAliasingMultipleAliasesInProduct() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/otherPkg/Sources/Utils/fileUtils.swift\",\n            \"/otherPkg/Sources/Logging/fileLogging.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        XCTAssertThrowsError(try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"otherPkg\",\n                    path: \"/otherPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"LoggingProd\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: [\"Logging\"]),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/otherPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"otherPkg\",\n                                               moduleAliases: [\"Logging\": \"UtilsLogging\"]\n                                           ),\n                                           .product(\n                                               name: \"LoggingProd\",\n                                               package: \"otherPkg\",\n                                               moduleAliases: [\"Logging\": \"OtherLogging\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )) { error in\n            var diagnosed = false\n            if let realError = error as? PackageGraphError,\n               realError\n               .description ==\n               \"multiple aliases: ['UtilsLogging', 'OtherLogging'] found for target 'Logging' in product 'LoggingProd' from package 'otherPkg'\"\n            {\n                diagnosed = true\n            }\n            XCTAssertTrue(diagnosed)\n        }\n    }\n\n    func testModuleAliasingSameNameTargetsWithAliasesInMultiProducts() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/swift-log/Sources/Logging/fileLogging.swift\",\n            \"/swift-metrics/Sources/Metrics/file.swift\",\n            \"/swift-metrics/Sources/Logging/fileLogging.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"swift-log\",\n                    path: \"/swift-log\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"swift-metrics\",\n                    path: \"/swift-metrics\",\n                    products: [\n                        ProductDescription(name: \"Metrics\", type: .library(.automatic), targets: [\"Metrics\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Metrics\", dependencies: [\"Logging\"]),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/swift-log\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/swift-metrics\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"swift-log\"\n                            ),\n                            .product(\n                                name: \"Metrics\",\n                                package: \"swift-metrics\",\n                                moduleAliases: [\"Logging\": \"MetricsLogging\"]\n                            )]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(4)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"MetricsLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"MetricsLogging\"\n                }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingInvalidSourcesUpstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/fooPkg/Sources/Utils/fileUtils.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.m\",\n            \"/fooPkg/Sources/Logging/include/fileLogging.h\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: [\"Logging\"]),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"FooLogging\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"target 'Logging' for product 'Utils' from package 'foopkg' has module aliases: ['Logging' as 'FooLogging'] but may contain non-Swift sources; there might be a conflict among non-Swift symbols\",\n                severity: .warning\n            )\n        }\n    }\n\n    func testModuleAliasingInvalidSourcesNestedUpstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/fooPkg/Sources/Utils/fileUtils.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.m\",\n            \"/barPkg/Sources/Logging/include/fileLogging.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [.product(name: \"Logging\", package: \"barPkg\")]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"FooLogging\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"target 'Logging' for product 'Logging' from package 'barpkg' has module aliases: ['Logging' as 'FooLogging'] but may contain non-Swift sources; there might be a conflict among non-Swift symbols\",\n                severity: .warning\n            )\n        }\n    }\n\n    func testModuleAliasingInvalidSourcesInNonAliasedModulesUpstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/fooPkg/Sources/Utils/fileUtils.swift\",\n            \"/fooPkg/Sources/Logging/fileLogging.swift\",\n            \"/fooPkg/Sources/Logging/guidelines.txt\",\n            \"/fooPkg/Sources/Perf/filePerf.m\",\n            \"/fooPkg/Sources/Perf/include/filePerf.h\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        XCTAssertNoThrow(try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"Perf\", type: .library(.automatic), targets: [\"Perf\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: [\"Logging\"]),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                        TargetDescription(name: \"Perf\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"FooLogging\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        ))\n    }\n\n    func testModuleAliasingInvalidSourcesInNonAliasedModulesNestedUpstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/fooPkg/Sources/Utils/fileUtils.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\",\n            \"/barPkg/Sources/Logging/readme.md\",\n            \"/barPkg/Sources/Perf/filePerf.m\",\n            \"/barPkg/Sources/Perf/include/filePerf.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        XCTAssertNoThrow(try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                        ProductDescription(name: \"Perf\", type: .library(.automatic), targets: [\"Perf\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                        TargetDescription(name: \"Perf\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [.product(name: \"Logging\", package: \"barPkg\")]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"FooLogging\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        ))\n    }\n\n    func testModuleAliasingDuplicateTargetNameInNestedUpstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file.swift\",\n            \"/fooPkg/Sources/Utils/fileUtils.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [.product(name: \"Logging\", package: \"barPkg\")]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"FooLogging\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(4)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Utils\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"FooLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n    }\n\n    func testModuleAliasingOverrideMultipleAliases() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/Logging/file1.swift\",\n            \"/thisPkg/Sources/Math/file2.swift\",\n            \"/fooPkg/Sources/Utils/fileUtils.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\",\n            \"/barPkg/Sources/Math/fileMath.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"LoggingProd\", type: .library(.automatic), targets: [\"Logging\"]),\n                        ProductDescription(name: \"MathProd\", type: .library(.automatic), targets: [\"Math\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                        TargetDescription(name: \"Math\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [.product(\n                                name: \"LoggingProd\",\n                                package: \"barPkg\",\n                                moduleAliases: [\"Logging\": \"BarLogging\"]\n                            ),\n                            .product(\n                                name: \"MathProd\",\n                                package: \"barPkg\",\n                                moduleAliases: [\"Math\": \"BarMath\"]\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"Logging\",\n                                           \"Math\",\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\n                                                   \"BarLogging\": \"FooLogging\",\n                                                   \"BarMath\": \"FooMath\",\n                                               ]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                        TargetDescription(name: \"Math\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(6)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"FooLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"FooMath\" && $0.module.moduleAliases?[\"Math\"] == \"FooMath\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"Utils\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" && $0.module\n                        .moduleAliases?[\"Math\"] == \"FooMath\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Math\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"exe\" && $0.module.moduleAliases == nil })\n        XCTAssertFalse(result.targetMap.values.contains { $0.module.name == \"BarLogging\" })\n    }\n\n    func testModuleAliasingAliasSkipUpstreamTargets() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/appPkg/Sources/Foo/file.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/yPkg/Sources/Y/file.swift\",\n            \"/zPkg/Sources/Z/file.swift\",\n            \"/zPkg/Sources/Foo/file.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/bPkg/Sources/B/file.swift\",\n            \"/cPkg/Sources/C/file.swift\",\n            \"/cPkg/Sources/Foo/file.swift\",\n            \"/dPkg/Sources/D/file.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"cPkg\",\n                    path: \"/cPkg\",\n                    products: [\n                        ProductDescription(name: \"C\", type: .library(.automatic), targets: [\"C\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"C\", dependencies: [\"Foo\"]),\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"dPkg\",\n                    path: \"/dPkg\",\n                    products: [\n                        ProductDescription(name: \"D\", type: .library(.automatic), targets: [\"D\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"D\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bPkg\",\n                    path: \"/bPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/cPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/dPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"B\", type: .library(.automatic), targets: [\"B\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"B\",\n                            dependencies: [\n                                .product(\n                                    name: \"C\",\n                                    package: \"cPkg\"\n                                ),\n                                .product(\n                                    name: \"D\",\n                                    package: \"dPkg\"\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"aPkg\",\n                    path: \"/aPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"A\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [.product(\n                                name: \"B\",\n                                package: \"bPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"zPkg\",\n                    path: \"/zPkg\",\n                    products: [\n                        ProductDescription(name: \"Z\", type: .library(.automatic), targets: [\"Z\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Z\", dependencies: [\"Foo\"]),\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"yPkg\",\n                    path: \"/yPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/zPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Y\", type: .library(.automatic), targets: [\"Y\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Y\",\n                            dependencies: [\n                                .product(\n                                    name: \"Z\",\n                                    package: \"zPkg\"\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"xPkg\",\n                    path: \"/xPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"X\",\n                            dependencies: [.product(\n                                name: \"Y\",\n                                package: \"yPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\"Foo\",\n                                           .product(\n                                               name: \"A\",\n                                               package: \"aPkg\",\n                                               moduleAliases: [\"Foo\": \"FooA\"]\n                                           ),\n                                           .product(\n                                               name: \"X\",\n                                               package: \"xPkg\",\n                                               moduleAliases: [\"Foo\": \"FooX\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(11)\n\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"D\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"FooA\" && $0.module.moduleAliases?[\"Foo\"] == \"FooA\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"C\" && $0.module.moduleAliases?[\"Foo\"] == \"FooA\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"B\" && $0.module.moduleAliases?[\"Foo\"] == \"FooA\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"A\" && $0.module.moduleAliases?[\"Foo\"] == \"FooA\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"FooX\" && $0.module.moduleAliases?[\"Foo\"] == \"FooX\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Z\" && $0.module.moduleAliases?[\"Foo\"] == \"FooX\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Y\" && $0.module.moduleAliases?[\"Foo\"] == \"FooX\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"X\" && $0.module.moduleAliases?[\"Foo\"] == \"FooX\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingAllConflictingAliasesFromMultiProducts() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/aPkg/Sources/A/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/bPkg/Sources/B/file.swift\",\n            \"/bPkg/Sources/Utils/file.swift\",\n            \"/cPkg/Sources/C/file.swift\",\n            \"/cPkg/Sources/Log/file.swift\",\n            \"/dPkg/Sources/D/file.swift\",\n            \"/dPkg/Sources/Utils/file.swift\",\n            \"/dPkg/Sources/Log/file.swift\",\n            \"/gPkg/Sources/G/file.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"gPkg\",\n                    path: \"/gPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/dPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"G\", type: .library(.automatic), targets: [\"G\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"G\",\n                            dependencies: [.product(\n                                name: \"D\",\n                                package: \"dPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"dPkg\",\n                    path: \"/dPkg\",\n                    products: [\n                        ProductDescription(name: \"D\", type: .library(.automatic), targets: [\"D\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"D\", dependencies: [\"Utils\", \"Log\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Log\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"cPkg\",\n                    path: \"/cPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/dPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"C\", type: .library(.automatic), targets: [\"C\"]),\n                        ProductDescription(name: \"LogInC\", type: .library(.automatic), targets: [\"Log\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"C\", dependencies: [\"Log\"]),\n                        TargetDescription(\n                            name: \"Log\",\n                            dependencies: [\n                                .product(\n                                    name: \"D\",\n                                    package: \"dPkg\",\n                                    moduleAliases: [\"Log\": \"ZLog\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bPkg\",\n                    path: \"/bPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/cPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"B\", type: .library(.automatic), targets: [\"B\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"B\",\n                            dependencies: [\n                                \"Utils\",\n                                .product(\n                                    name: \"C\",\n                                    package: \"cPkg\",\n                                    moduleAliases: [\"Utils\": \"YUtils\",\n                                                    \"Log\": \"YLog\"]\n                                ),\n                            ]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"aPkg\",\n                    path: \"/aPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/gPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                .product(\n                                    name: \"G\",\n                                    package: \"gPkg\"\n                                ),\n                                .product(\n                                    name: \"B\",\n                                    package: \"bPkg\",\n                                    moduleAliases: [\"Utils\": \"XUtils\",\n                                                    \"YLog\": \"XLog\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(9)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"A\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"B\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"C\" && $0.module.moduleAliases?[\"Log\"] == \"XLog\" && $0.module\n                        .moduleAliases?[\"Utils\"] == \"YUtils\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"XLog\" && $0.module.moduleAliases?[\"Log\"] == \"XLog\" && $0.module\n                        .moduleAliases?[\"Utils\"] == \"YUtils\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"D\" && $0.module.moduleAliases?[\"Utils\"] == \"YUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"ZLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"YUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"YUtils\" && $0.module\n                        .moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"ZLog\" && $0.module.moduleAliases?[\"Log\"] == \"ZLog\" && $0.module.moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"G\" && $0.module.moduleAliases?[\"Utils\"] == \"YUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"ZLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n    }\n\n    func testModuleAliasingSomeConflictingAliasesInMultiProducts() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/aPkg/Sources/A/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/bPkg/Sources/B/file.swift\",\n            \"/cPkg/Sources/C/file.swift\",\n            \"/dPkg/Sources/D/file.swift\",\n            \"/dPkg/Sources/Utils/file.swift\",\n            \"/dPkg/Sources/Log/file.swift\",\n            \"/gPkg/Sources/G/file.swift\",\n            \"/hPkg/Sources/Utils/file.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"hPkg\",\n                    path: \"/hPkg\",\n                    dependencies: [\n                    ],\n                    products: [\n                        ProductDescription(name: \"H\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: []\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"gPkg\",\n                    path: \"/gPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/hPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"G\", type: .library(.automatic), targets: [\"G\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"G\",\n                            dependencies: [.product(\n                                name: \"H\",\n                                package: \"hPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"dPkg\",\n                    path: \"/dPkg\",\n                    products: [\n                        ProductDescription(name: \"D\", type: .library(.automatic), targets: [\"D\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"D\", dependencies: [\"Utils\", \"Log\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Log\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"cPkg\",\n                    path: \"/cPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/dPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"C\", type: .library(.automatic), targets: [\"C\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"C\",\n                            dependencies: [\n                                .product(\n                                    name: \"D\",\n                                    package: \"dPkg\",\n                                    moduleAliases: [\"Log\": \"ZLog\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bPkg\",\n                    path: \"/bPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/cPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"B\", type: .library(.automatic), targets: [\"B\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"B\",\n                            dependencies: [\n                                .product(\n                                    name: \"C\",\n                                    package: \"cPkg\",\n                                    moduleAliases: [\"Utils\": \"YUtils\",\n                                                    \"ZLog\": \"YLog\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"aPkg\",\n                    path: \"/aPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/gPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                .product(\n                                    name: \"B\",\n                                    package: \"bPkg\",\n                                    moduleAliases: [\"YUtils\": \"XUtils\",\n                                                    \"YLog\": \"XLog\"]\n                                ),\n                                .product(\n                                    name: \"G\",\n                                    package: \"gPkg\",\n                                    moduleAliases: [\"Utils\": \"GUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(8)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"A\" && $0.module.moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"B\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"C\" && $0.module.moduleAliases?[\"Log\"] == \"XLog\" && $0.module\n                        .moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"D\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"XLog\" && $0.module.moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"G\" && $0.module.moduleAliases?[\"Utils\"] == \"GUtils\" && $0.module.moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"GUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"GUtils\" && $0.module\n                        .moduleAliases?\n                        .count == 1\n                }\n        )\n    }\n\n    func testModuleAliasingMergeAliasesOfSameTargets() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/aPkg/Sources/A/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/bPkg/Sources/B/file.swift\",\n            \"/cPkg/Sources/C/file.swift\",\n            \"/dPkg/Sources/D/file.swift\",\n            \"/dPkg/Sources/Utils/file.swift\",\n            \"/dPkg/Sources/Log/file.swift\",\n            \"/gPkg/Sources/G/file.swift\",\n            \"/hPkg/Sources/H/file.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"hPkg\",\n                    path: \"/hPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/dPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"H\", type: .library(.automatic), targets: [\"H\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"H\",\n                            dependencies: [.product(\n                                name: \"D\",\n                                package: \"dPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"gPkg\",\n                    path: \"/gPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/hPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"G\", type: .library(.automatic), targets: [\"G\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"G\",\n                            dependencies: [.product(\n                                name: \"H\",\n                                package: \"hPkg\",\n                                moduleAliases: [\n                                    \"Utils\": \"GUtils\",\n                                    \"Log\": \"GLog\",\n                                ]\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"dPkg\",\n                    path: \"/dPkg\",\n                    products: [\n                        ProductDescription(name: \"D\", type: .library(.automatic), targets: [\"D\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"D\", dependencies: [\"Utils\", \"Log\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Log\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"cPkg\",\n                    path: \"/cPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/dPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"C\", type: .library(.automatic), targets: [\"C\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"C\",\n                            dependencies: [\n                                .product(\n                                    name: \"D\",\n                                    package: \"dPkg\",\n                                    moduleAliases: [\"Log\": \"ZLog\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bPkg\",\n                    path: \"/bPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/cPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"B\", type: .library(.automatic), targets: [\"B\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"B\",\n                            dependencies: [\n                                .product(\n                                    name: \"C\",\n                                    package: \"cPkg\",\n                                    moduleAliases: [\"Utils\": \"YUtils\",\n                                                    \"ZLog\": \"YLog\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"aPkg\",\n                    path: \"/aPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/gPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                .product(\n                                    name: \"G\",\n                                    package: \"gPkg\"\n                                ),\n                                .product(\n                                    name: \"B\",\n                                    package: \"bPkg\",\n                                    moduleAliases: [\"YUtils\": \"XUtils\",\n                                                    \"YLog\": \"XLog\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(8)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"A\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"B\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"C\" && $0.module.moduleAliases?[\"Log\"] == \"XLog\" && $0.module\n                        .moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"D\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"XLog\" && $0.module.moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?\n                        .count == 1\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"G\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"H\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"Log\"] == \"XLog\" && $0.module.moduleAliases?.count == 2\n                }\n        )\n    }\n\n    func testModuleAliasingOverrideSameNameTargetAndDepWithAliases() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/appPkg/Sources/Utils/file1.swift\",\n            \"/appPkg/Sources/Render/file2.swift\",\n            \"/libPkg/Sources/Lib/fileLib.swift\",\n            \"/gamePkg/Sources/Game/fileGame.swift\",\n            \"/gamePkg/Sources/Render/fileRender.swift\",\n            \"/gamePkg/Sources/Utils/fileUtils.swift\",\n            \"/drawPkg/Sources/Render/fileDraw.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"drawPkg\",\n                    path: \"/drawPkg\",\n                    products: [\n                        ProductDescription(name: \"DrawProd\", type: .library(.automatic), targets: [\"Render\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"gamePkg\",\n                    path: \"/gamePkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/drawPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Game\", type: .library(.automatic), targets: [\"Game\"]),\n                        ProductDescription(name: \"UtilsProd\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"RenderProd\", type: .library(.automatic), targets: [\"Render\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Game\", dependencies: [\"Utils\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(\n                            name: \"Render\",\n                            dependencies: [\n                                .product(\n                                    name: \"DrawProd\",\n                                    package: \"drawPkg\",\n                                    moduleAliases: [\"Render\": \"DrawRender\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"libPkg\",\n                    path: \"/libPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/gamePkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"LibProd\", type: .library(.automatic), targets: [\"Lib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Lib\",\n                            dependencies: [\n                                .product(\n                                    name: \"Game\",\n                                    package: \"gamePkg\",\n                                    moduleAliases: [\"Utils\": \"GameUtils\"]\n                                ),\n                                .product(\n                                    name: \"RenderProd\",\n                                    package: \"gamePkg\",\n                                    moduleAliases: [\"Render\": \"GameRender\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/libPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\"Utils\",\n                                           \"Render\",\n                                           .product(\n                                               name: \"LibProd\",\n                                               package: \"libPkg\",\n                                               moduleAliases: [\n                                                   \"GameUtils\": \"LibUtils\",\n                                                   \"GameRender\": \"LibRender\",\n                                               ]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(8)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"Lib\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" && $0.module\n                        .moduleAliases?[\"Render\"] == \"LibRender\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"LibRender\" && $0.module.moduleAliases?[\"Render\"] == \"LibRender\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"LibUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"Game\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" && $0.module\n                        .moduleAliases?[\"Render\"] == nil\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"DrawRender\" && $0.module.moduleAliases?[\"Render\"] == \"DrawRender\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Render\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n        XCTAssertFalse(result.targetMap.values.contains { $0.module.name == \"GameUtils\" })\n    }\n\n    func testModuleAliasingAddOverrideAliasesUpstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/appPkg/Sources/Utils/file1.swift\",\n            \"/appPkg/Sources/Render/file2.swift\",\n            \"/libPkg/Sources/Lib/fileLib.swift\",\n            \"/gamePkg/Sources/Render/fileRender.swift\",\n            \"/gamePkg/Sources/Utils/fileUtils.swift\",\n            \"/drawPkg/Sources/Render/fileDraw.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"drawPkg\",\n                    path: \"/drawPkg\",\n                    products: [\n                        ProductDescription(name: \"DrawProd\", type: .library(.automatic), targets: [\"Render\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"gamePkg\",\n                    path: \"/gamePkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/drawPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Game\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"UtilsProd\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"RenderProd\", type: .library(.automatic), targets: [\"Render\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Game\", dependencies: [\"Utils\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(\n                            name: \"Render\",\n                            dependencies: [\n                                .product(\n                                    name: \"DrawProd\",\n                                    package: \"drawPkg\",\n                                    moduleAliases: [\"Render\": \"DrawRender\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"libPkg\",\n                    path: \"/libPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/gamePkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"LibProd\", type: .library(.automatic), targets: [\"Lib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Lib\",\n                            dependencies: [.product(\n                                name: \"UtilsProd\",\n                                package: \"gamePkg\",\n                                moduleAliases: [\"Utils\": \"GameUtils\"]\n                            ),\n                            .product(\n                                name: \"RenderProd\",\n                                package: \"gamePkg\",\n                                moduleAliases: [\"Render\": \"GameRender\"]\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/libPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\"Utils\",\n                                           \"Render\",\n                                           .product(\n                                               name: \"LibProd\",\n                                               package: \"libPkg\"\n                                           )]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(7)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"Lib\" && $0.module.moduleAliases?[\"Utils\"] == \"GameUtils\" && $0.module\n                        .moduleAliases?[\"Render\"] == \"GameRender\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"GameRender\" && $0.module.moduleAliases?[\"Render\"] == \"GameRender\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"GameUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"GameUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"DrawRender\" && $0.module.moduleAliases?[\"Render\"] == \"DrawRender\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Render\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingOverrideUpstreamTargetsWithAliases() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/appPkg/Sources/Utils/file1.swift\",\n            \"/appPkg/Sources/Render/file2.swift\",\n            \"/libPkg/Sources/Lib/fileLib.swift\",\n            \"/gamePkg/Sources/Scene/fileScene.swift\",\n            \"/gamePkg/Sources/Render/fileRender.swift\",\n            \"/gamePkg/Sources/Utils/fileUtils.swift\",\n            \"/drawPkg/Sources/Render/fileDraw.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"drawPkg\",\n                    path: \"/drawPkg\",\n                    products: [\n                        ProductDescription(name: \"DrawProd\", type: .library(.automatic), targets: [\"Render\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"gamePkg\",\n                    path: \"/gamePkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/drawPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Game\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"UtilsProd\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"RenderProd\", type: .library(.automatic), targets: [\"Render\"]),\n                        ProductDescription(name: \"SceneProd\", type: .library(.automatic), targets: [\"Scene\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Game\", dependencies: [\"Utils\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Render\", dependencies: []),\n                        TargetDescription(\n                            name: \"Scene\",\n                            dependencies: [\n                                .product(\n                                    name: \"DrawProd\",\n                                    package: \"drawPkg\",\n                                    moduleAliases: [\"Render\": \"DrawRender\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"libPkg\",\n                    path: \"/libPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/gamePkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"LibProd\", type: .library(.automatic), targets: [\"Lib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Lib\",\n                            dependencies: [.product(\n                                name: \"UtilsProd\",\n                                package: \"gamePkg\",\n                                moduleAliases: [\"Utils\": \"GameUtils\"]\n                            ),\n                            .product(\n                                name: \"RenderProd\",\n                                package: \"gamePkg\",\n                                moduleAliases: [\"Render\": \"GameRender\"]\n                            ),\n                            .product(\n                                name: \"SceneProd\",\n                                package: \"gamePkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/libPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\"Utils\",\n                                           \"Render\",\n                                           .product(\n                                               name: \"LibProd\",\n                                               package: \"libPkg\"\n                                           )]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(8)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"Lib\" && $0.module.moduleAliases?[\"Utils\"] == \"GameUtils\" && $0.module\n                        .moduleAliases?[\"Render\"] == \"GameRender\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"GameRender\" && $0.module.moduleAliases?[\"Render\"] == \"GameRender\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"GameUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"GameUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Scene\" && $0.module.moduleAliases?[\"Render\"] == \"DrawRender\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"DrawRender\" && $0.module.moduleAliases?[\"Render\"] == \"DrawRender\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Render\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingOverrideUpstreamTargetsWithAliasesMultipleAliasesInProduct() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/appPkg/Sources/Utils/file1.swift\",\n            \"/appPkg/Sources/Render/file2.swift\",\n            \"/libPkg/Sources/Lib/fileLib.swift\",\n            \"/gamePkg/Sources/Game/fileGame.swift\",\n            \"/gamePkg/Sources/Utils/fileUtils.swift\",\n            \"/drawPkg/Sources/Render/fileDraw.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"drawPkg\",\n                    path: \"/drawPkg\",\n                    products: [\n                        ProductDescription(name: \"DrawProd\", type: .library(.automatic), targets: [\"Render\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"gamePkg\",\n                    path: \"/gamePkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/drawPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"GameProd\", type: .library(.automatic), targets: [\"Game\"]),\n                        ProductDescription(name: \"UtilsProd\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Game\",\n                            dependencies: [\n                                \"Utils\",\n                                .product(\n                                    name: \"DrawProd\",\n                                    package: \"drawPkg\",\n                                    moduleAliases: [\"Render\": \"DrawRender\"]\n                                ),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [\n                                .product(\n                                    name: \"DrawProd\",\n                                    package: \"drawPkg\",\n                                    moduleAliases: [\"Render\": \"DrawRender\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"libPkg\",\n                    path: \"/libPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/gamePkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"LibProd\", type: .library(.automatic), targets: [\"Lib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Lib\",\n                            dependencies: [.product(\n                                name: \"UtilsProd\",\n                                package: \"gamePkg\",\n                                moduleAliases: [\n                                    \"Utils\": \"GameUtils\",\n                                    \"Render\": \"GameRender\",\n                                ]\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/libPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\"Utils\",\n                                           \"Render\",\n                                           .product(\n                                               name: \"LibProd\",\n                                               package: \"libPkg\",\n                                               moduleAliases: [\n                                                   \"GameUtils\": \"LibUtils\",\n                                                   \"GameRender\": \"LibRender\",\n                                               ]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(7)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"Lib\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" && $0.module\n                        .moduleAliases?[\"Render\"] == \"LibRender\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"LibRender\" && $0.module.moduleAliases?[\"Render\"] == \"LibRender\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"LibUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" }\n        )\n        XCTAssertFalse(\n            result.targetMap.values\n                .contains { $0.module.name == \"DrawRender\" || $0.module.moduleAliases?[\"Render\"] == \"DrawRender\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Game\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Render\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingOverrideUpstreamTargetsWithAliasesDownstream() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/appPkg/Sources/Utils/file1.swift\",\n            \"/appPkg/Sources/Render/file2.swift\",\n            \"/libPkg/Sources/Lib/fileLib.swift\",\n            \"/gamePkg/Sources/Scene/fileScene.swift\",\n            \"/gamePkg/Sources/Render/fileRender.swift\",\n            \"/gamePkg/Sources/Utils/fileUtils.swift\",\n            \"/gamePkg/Sources/Game/fileGame.swift\",\n            \"/drawPkg/Sources/Render/fileDraw.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"drawPkg\",\n                    path: \"/drawPkg\",\n                    products: [\n                        ProductDescription(name: \"DrawProd\", type: .library(.automatic), targets: [\"Render\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"gamePkg\",\n                    path: \"/gamePkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/drawPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Game\", type: .library(.automatic), targets: [\"Game\"]),\n                        ProductDescription(name: \"UtilsProd\", type: .library(.automatic), targets: [\"Utils\"]),\n                        ProductDescription(name: \"RenderProd\", type: .library(.automatic), targets: [\"Render\"]),\n                        ProductDescription(name: \"SceneProd\", type: .library(.automatic), targets: [\"Scene\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Game\", dependencies: [\"Utils\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Render\", dependencies: []),\n                        TargetDescription(\n                            name: \"Scene\",\n                            dependencies: [\n                                .product(\n                                    name: \"DrawProd\",\n                                    package: \"drawPkg\",\n                                    moduleAliases: [\"Render\": \"DrawRender\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"libPkg\",\n                    path: \"/libPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/gamePkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"LibProd\", type: .library(.automatic), targets: [\"Lib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Lib\",\n                            dependencies: [.product(\n                                name: \"UtilsProd\",\n                                package: \"gamePkg\",\n                                moduleAliases: [\"Utils\": \"GameUtils\"]\n                            ),\n                            .product(\n                                name: \"RenderProd\",\n                                package: \"gamePkg\",\n                                moduleAliases: [\"Render\": \"GameRender\"]\n                            ),\n                            .product(\n                                name: \"SceneProd\",\n                                package: \"gamePkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/libPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\"Utils\",\n                                           \"Render\",\n                                           .product(\n                                               name: \"LibProd\",\n                                               package: \"libPkg\",\n                                               moduleAliases: [\n                                                   \"GameUtils\": \"LibUtils\",\n                                                   \"GameRender\": \"LibRender\",\n                                               ]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                        TargetDescription(name: \"Render\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(9)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"Lib\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" && $0.module\n                        .moduleAliases?[\"Render\"] == \"LibRender\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"LibRender\" && $0.module.moduleAliases?[\"Render\"] == \"LibRender\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"LibUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Game\" && $0.module.moduleAliases?[\"Utils\"] == \"LibUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Scene\" && $0.module.moduleAliases?[\"Render\"] == \"DrawRender\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"DrawRender\" && $0.module.moduleAliases?[\"Render\"] == \"DrawRender\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Render\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingSameTargetFromUpstreamWithoutAlias() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/MyLogging/file.swift\",\n            \"/fooPkg/Sources/Utils/fileUtils.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"Logging\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [.product(\n                                name: \"Logging\",\n                                package: \"barPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"MyLogging\",\n                                           .product(\n                                               name: \"Utils\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"FooLogging\"]\n                                           ),\n                                           .product(\n                                               name: \"Logging\",\n                                               package: \"barPkg\"\n                                           )]\n                        ),\n                        TargetDescription(name: \"MyLogging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(4)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Utils\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"FooLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" }\n        )\n        XCTAssertFalse(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"MyLogging\" && $0.module.moduleAliases == nil }\n        )\n    }\n\n    func testModuleAliasingDuplicateTargetNamesFromMultiplePkgs() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/thisPkg/Sources/exe/main.swift\",\n            \"/thisPkg/Sources/MyLogging/file.swift\",\n            \"/fooPkg/Sources/Utils/fileUtils.swift\",\n            \"/barPkg/Sources/Logging/fileLogging.swift\",\n            \"/carPkg/Sources/Logging/fileLogging.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"carPkg\",\n                    path: \"/carPkg\",\n                    products: [\n                        ProductDescription(name: \"CarLog\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"barPkg\",\n                    path: \"/barPkg\",\n                    products: [\n                        ProductDescription(name: \"BarLog\", type: .library(.automatic), targets: [\"Logging\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"fooPkg\",\n                    path: \"/fooPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"UtilsProd\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [.product(\n                                name: \"BarLog\",\n                                package: \"barPkg\"\n                            )]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"thisPkg\",\n                    path: \"/thisPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/carPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"MyLogging\",\n                                           .product(\n                                               name: \"UtilsProd\",\n                                               package: \"fooPkg\",\n                                               moduleAliases: [\"Logging\": \"FooLogging\"]\n                                           ),\n                                           .product(\n                                               name: \"CarLog\",\n                                               package: \"carPkg\",\n                                               moduleAliases: [\"Logging\": \"CarLogging\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"MyLogging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n\n        result.checkProductsCount(1)\n        result.checkTargetsCount(5)\n\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"FooLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" }\n        )\n        XCTAssertFalse(\n            result.targetMap.values\n                .contains { $0.module.name == \"Logging\" && $0.module.moduleAliases == nil }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"CarLogging\" && $0.module.moduleAliases?[\"Logging\"] == \"CarLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Utils\" && $0.module.moduleAliases?[\"Logging\"] == \"FooLogging\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"MyLogging\" && $0.module.moduleAliases == nil }\n        )\n    }\n\n    func testModuleAliasingTargetAndProductTargetWithSameName() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/appPkg/Sources/Utils/file.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/xPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"X\", dependencies: [\"Utils\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\"Utils\",\n                                           .product(\n                                               name: \"X\",\n                                               package: \"xpkg\",\n                                               moduleAliases: [\"Utils\": \"XUtils\"]\n                                           )]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(4)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"X\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingProductTargetsWithSameName1() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/yPkg/Sources/Utils/file.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/bPkg/Sources/B/file.swift\",\n            \"/cPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"cpkg\",\n                    path: \"/cPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"bpkg\",\n                    path: \"/bPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/cPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"B\", type: .library(.automatic), targets: [\"B\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"B\",\n                            dependencies: [\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"cpkg\"\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"apkg\",\n                    path: \"/aPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"A\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                .product(\n                                    name: \"B\",\n                                    package: \"bpkg\"\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"ypkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"X\",\n                            dependencies: [\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"ypkg\"\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\n                                .product(\n                                    name: \"X\",\n                                    package: \"xpkg\",\n                                    moduleAliases: [\"Utils\": \"XUtils\"]\n                                ),\n                                .product(\n                                    name: \"A\",\n                                    package: \"apkg\",\n                                    moduleAliases: [\"Utils\": \"AUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(6)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"X\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"A\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"B\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n        XCTAssertFalse(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingUpstreamProductTargetsWithSameName2() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/bPkg/Sources/Utils/file.swift\",\n            \"/cPkg/Sources/Utils/file.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/yPkg/Sources/Utils/file.swift\",\n            \"/zPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"zpkg\",\n                    path: \"/zPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"ypkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/zPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"X\",\n                            dependencies: [\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"zpkg\"\n                                ),\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"ypkg\",\n                                    moduleAliases: [\"Utils\": \"YUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"cpkg\",\n                    path: \"/cPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"bpkg\",\n                    path: \"/bPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"apkg\",\n                    path: \"/aPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/cPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"A\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"cpkg\"\n                                ),\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"bpkg\",\n                                    moduleAliases: [\"Utils\": \"BUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\n                                .product(\n                                    name: \"X\",\n                                    package: \"xpkg\",\n                                    moduleAliases: [\"Utils\": \"XUtils\"]\n                                ),\n                                .product(\n                                    name: \"A\",\n                                    package: \"apkg\",\n                                    moduleAliases: [\"Utils\": \"AUtils\"]\n                                ),\n                            ],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(7)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"X\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"YUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"YUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"A\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"BUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"BUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n        XCTAssertFalse(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingUpstreamProductTargetsWithSameName3() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/aPkg/Sources/Utils/file.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/yPkg/Sources/Utils/file.swift\",\n            \"/zPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"zpkg\",\n                    path: \"/zPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"ypkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/zPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"X\",\n                            dependencies: [\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"zpkg\"\n                                ),\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"ypkg\",\n                                    moduleAliases: [\"Utils\": \"YUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"apkg\",\n                    path: \"/aPkg\",\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"A\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"A\", dependencies: [\"Utils\"]),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\n                                .product(\n                                    name: \"X\",\n                                    package: \"xpkg\"\n                                ),\n                                .product(\n                                    name: \"A\",\n                                    package: \"apkg\",\n                                    moduleAliases: [\"Utils\": \"AUtils\"]\n                                ),\n                            ],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(6)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"X\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"YUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"YUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"A\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingUpstreamProductTargetsWithSameName4() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/aPkg/Sources/Utils/file.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/yPkg/Sources/Utils/file.swift\",\n            \"/zPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"zpkg\",\n                    path: \"/zPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"ypkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/zPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"X\",\n                            dependencies: [\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"zpkg\"\n                                ),\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"ypkg\",\n                                    moduleAliases: [\"Utils\": \"YUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"apkg\",\n                    path: \"/aPkg\",\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [\n                                .product(\n                                    name: \"X\",\n                                    package: \"xpkg\",\n                                    moduleAliases: [\"Utils\": \"XUtils\"]\n                                ),\n                                .product(\n                                    name: \"A\",\n                                    package: \"apkg\",\n                                    moduleAliases: [\"Utils\": \"AUtils\"]\n                                ),\n                            ],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(5)\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"X\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"YUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"YUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n        XCTAssertFalse(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingChainedAliases1() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/aPkg/Sources/Utils/file.swift\",\n            \"/bPkg/Sources/Utils/file.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/xPkg/Sources/Utils/file.swift\",\n            \"/yPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"ypkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"X\",\n                            dependencies: [\n                                \"Utils\",\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"ypkg\",\n                                    moduleAliases: [\"Utils\": \"FooUtils\"]\n                                ),\n                            ]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bpkg\",\n                    path: \"/bPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"apkg\",\n                    path: \"/aPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"A\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                \"Utils\",\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"bpkg\",\n                                    moduleAliases: [\"Utils\": \"FooUtils\"]\n                                ),\n                            ]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [.product(\n                                name: \"A\",\n                                package: \"apkg\",\n                                moduleAliases: [\n                                    \"Utils\": \"AUtils\",\n                                    \"FooUtils\": \"AFooUtils\",\n                                ]\n                            ),\n                            .product(\n                                name: \"X\",\n                                package: \"xpkg\",\n                                moduleAliases: [\n                                    \"Utils\": \"XUtils\",\n                                    \"FooUtils\": \"XFooUtils\",\n                                ]\n                            )]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(7)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"A\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" && $0.module\n                        .moduleAliases?[\"FooUtils\"] == \"AFooUtils\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"X\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"FooUtils\"] == \"XFooUtils\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AFooUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AFooUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XFooUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XFooUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingChainedAliases2() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/aPkg/Sources/Utils/file.swift\",\n            \"/bPkg/Sources/Utils/file.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/xPkg/Sources/Utils/file.swift\",\n            \"/yPkg/Sources/Utils/file.swift\",\n            \"/zPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"zpkg\",\n                    path: \"/zPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"ypkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/zPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"X\",\n                            dependencies: [\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"ypkg\",\n                                    moduleAliases: [\"Utils\": \"FooUtils\"]\n                                ),\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"zpkg\"\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bpkg\",\n                    path: \"/bPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"apkg\",\n                    path: \"/aPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"A\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                \"Utils\",\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"bpkg\",\n                                    moduleAliases: [\"Utils\": \"FooUtils\"]\n                                ),\n                            ]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [.product(\n                                name: \"A\",\n                                package: \"apkg\",\n                                moduleAliases: [\n                                    \"Utils\": \"AUtils\",\n                                    \"FooUtils\": \"AFUtils\",\n                                ]\n                            ),\n                            .product(\n                                name: \"X\",\n                                package: \"xpkg\",\n                                moduleAliases: [\"FooUtils\": \"XFUtils\"]\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(7)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"A\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" && $0.module\n                        .moduleAliases?[\"FooUtils\"] == \"AFUtils\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AFUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AFUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"X\" && $0.module.moduleAliases?[\"FooUtils\"] == \"XFUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XFUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XFUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingChainedAliases3() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/aPkg/Sources/A/file.swift\",\n            \"/aPkg/Sources/Utils/file.swift\",\n            \"/bPkg/Sources/Utils/file.swift\",\n            \"/xPkg/Sources/X/file.swift\",\n            \"/xpkg/Sources/Utils/file.swift\",\n            \"/yPkg/Sources/Utils/file.swift\",\n            \"/zPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"zpkg\",\n                    path: \"/zPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"ypkg\",\n                    path: \"/yPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/zPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"X\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"X\",\n                            dependencies: [\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"ypkg\",\n                                    moduleAliases: [\"Utils\": \"FooUtils\"]\n                                ),\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"zpkg\",\n                                    moduleAliases: [\"Utils\": \"ZUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"bpkg\",\n                    path: \"/bPkg\",\n                    products: [\n                        ProductDescription(name: \"Utils\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"apkg\",\n                    path: \"/aPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/bPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"A\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"A\",\n                            dependencies: [\n                                \"Utils\",\n                                .product(\n                                    name: \"Utils\",\n                                    package: \"bpkg\",\n                                    moduleAliases: [\"Utils\": \"FooUtils\"]\n                                ),\n                            ]\n                        ),\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [.product(\n                                name: \"A\",\n                                package: \"apkg\",\n                                moduleAliases: [\n                                    \"Utils\": \"AUtils\",\n                                    \"FooUtils\": \"AFooUtils\",\n                                ]\n                            ),\n                            .product(\n                                name: \"X\",\n                                package: \"xpkg\",\n                                moduleAliases: [\n                                    \"ZUtils\": \"XUtils\",\n                                    \"FooUtils\": \"XFooUtils\",\n                                ]\n                            )],\n                            type: .executable\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(7)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"A\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" && $0.module\n                        .moduleAliases?[\"FooUtils\"] == \"AFooUtils\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AFooUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AFooUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains {\n                    $0.module.name == \"X\" && $0.module.moduleAliases?[\"ZUtils\"] == \"XUtils\" && $0.module\n                        .moduleAliases?[\"FooUtils\"] == \"XFooUtils\"\n                }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XFooUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XFooUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n        XCTAssertFalse(result.targetMap.values.contains { $0.module.name == \"Utils\" && $0.module.moduleAliases == nil })\n    }\n\n    func testModuleAliasingChainedAliases5() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/appPkg/Sources/App/main.swift\",\n            \"/xPkg/Sources/Utils/file.swift\",\n            \"/yPkg/Sources/Utils/file.swift\",\n            \"/zPkg/Sources/Utils/file.swift\",\n            \"/wPkg/Sources/Utils/file.swift\",\n            \"/aPkg/Sources/Utils/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"apkg\",\n                    path: \"/aPkg\",\n                    products: [\n                        ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"wpkg\",\n                    path: \"/wPkg\",\n                    products: [\n                        ProductDescription(name: \"W\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"zpkg\",\n                    path: \"/zPkg\",\n                    products: [\n                        ProductDescription(name: \"Z\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Utils\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"ypkg\",\n                    path: \"/yPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/zPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Y\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [\n                                .product(\n                                    name: \"Z\",\n                                    package: \"zpkg\", // import ZUtils\n                                    moduleAliases: [\"Utils\": \"ZUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"xpkg\",\n                    path: \"/xPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/yPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/wPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"X\", type: .library(.automatic), targets: [\"Utils\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Utils\",\n                            dependencies: [\n                                .product(\n                                    name: \"Y\",\n                                    package: \"ypkg\", // import YUtils\n                                    moduleAliases: [\"ZUtils\": \"YUtils\"]\n                                ),\n                                .product(\n                                    name: \"W\",\n                                    package: \"wpkg\", // import WUtils\n                                    moduleAliases: [\"Utils\": \"WUtils\"]\n                                ),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"appPkg\",\n                    path: \"/appPkg\",\n                    dependencies: [\n                        .localSourceControl(path: \"/aPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/xPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"App\",\n                            dependencies: [.product(\n                                name: \"X\",\n                                package: \"xpkg\",\n                                moduleAliases: [\n                                    \"Utils\": \"XUtils\",\n                                ]\n                            ),\n                            .product(\n                                name: \"A\",\n                                package: \"apkg\",\n                                moduleAliases: [\n                                    \"Utils\": \"AUtils\",\n                                ]\n                            )]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkProductsCount(1)\n        result.checkTargetsCount(6)\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"Utils\" && $0.module.moduleAliases?[\"ZUtils\"] == \"YUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"XUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"XUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"YUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"YUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"WUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"WUtils\" }\n        )\n        XCTAssertTrue(\n            result.targetMap.values\n                .contains { $0.module.name == \"AUtils\" && $0.module.moduleAliases?[\"Utils\"] == \"AUtils\" }\n        )\n        XCTAssertTrue(result.targetMap.values.contains { $0.module.name == \"App\" && $0.module.moduleAliases == nil })\n        XCTAssertFalse(\n            result.targetMap.values\n                .contains { $0.module.name == \"ZUtils\" || $0.module.moduleAliases?[\"Utils\"] == \"ZUtils\" }\n        )\n    }\n\n    func testProductAliasingDoesNotBreakPackagesWithOlderToolsVersions() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Lunch/Sources/MyTarget/file.swift\",\n            \"/Some/Sources/Some/file.swift\",\n            \"/Other/Sources/Other/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"lunch\",\n                    path: \"/Lunch\",\n                    dependencies: [\n                        .fileSystem(path: \"/Some\"),\n                        .fileSystem(path: \"/Other\"),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .byName(name: \"SomeProduct\", condition: nil),\n                                .product(name: \"Other\", package: nil, moduleAliases: [\"Other\": \"Other2\"], condition: nil),\n                            ]\n                        )\n                    ],\n                    traits: []\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Some\",\n                    path: \"/Some\",\n                    products: [\n                        ProductDescription(\n                            name: \"SomeProduct\",\n                            type: .library(.automatic),\n                            targets: [\"Some\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Some\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Other\",\n                    path: \"/Other\",\n                    products: [\n                        ProductDescription(\n                            name: \"Other\",\n                            type: .library(.automatic),\n                            targets: [\"Other\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Other\"),\n                    ]\n                )\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let result = try await BuildPlanResult(plan: try mockBuildPlan(\n            graph: graph,\n            linkingParameters: .init(\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ))\n        result.checkTargetsCount(3)\n    }\n\n    func testProductAliasingWarnsIfPackageWithOlderToolsVersionIsPossibleCauseOfConflict() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Lunch/Sources/MyTarget/file.swift\",\n            \"/Some/Sources/Some/file.swift\",\n            \"/Other/Sources/Some/file.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        do {\n            _ = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [\n                    Manifest.createRootManifest(\n                        displayName: \"lunch\",\n                        path: \"/Lunch\",\n                        dependencies: [\n                            .fileSystem(path: \"/Some\"),\n                            .fileSystem(path: \"/Other\"),\n                        ],\n                        targets: [\n                            TargetDescription(\n                                name: \"MyTarget\",\n                                dependencies: [\n                                    .byName(name: \"SomeProduct\", condition: nil),\n                                    .product(name: \"Some\", package: nil, moduleAliases: [\"Some\": \"Some2\"], condition: nil),\n                                ]\n                            )\n                        ],\n                        traits: []\n                    ),\n                    Manifest.createFileSystemManifest(\n                        displayName: \"Some\",\n                        path: \"/Some\",\n                        products: [\n                            ProductDescription(\n                                name: \"SomeProduct\",\n                                type: .library(.automatic),\n                                targets: [\"Some\"]\n                            )\n                        ],\n                        targets: [\n                            TargetDescription(name: \"Some\"),\n                        ]\n                    ),\n                    Manifest.createFileSystemManifest(\n                        displayName: \"Some\",\n                        path: \"/Other\",\n                        products: [\n                            ProductDescription(\n                                name: \"SomeProduct\",\n                                type: .library(.automatic),\n                                targets: [\"Some\"]\n                            )\n                        ],\n                        targets: [\n                            TargetDescription(name: \"Some\"),\n                        ]\n                    )\n                ],\n                observabilityScope: observability.topScope\n            )\n\n            XCTFail(\"unexpectedly resolved the package graph successfully\")\n        } catch {\n            XCTAssertEqual(error.interpolationDescription, \"multiple packages ('other' (at '\\(AbsolutePath(\"/Other\"))'), 'some' (at '\\(AbsolutePath(\"/Some\"))')) declare products with a conflicting name: 'SomeProduct’; product names need to be unique across the package graph\")\n        }\n        XCTAssertEqual(observability.diagnostics.map { $0.description }.sorted(), [\"[warning]: product aliasing requires tools-version 5.2 or later, so it is not supported by \\'other\\'\", \"[warning]: product aliasing requires tools-version 5.2 or later, so it is not supported by \\'some\\'\"])\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/PluginInvocationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(SwiftPMInternal)\nimport Basics\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\n@testable import PackageGraph\n\nimport PackageLoading\n\n@_spi(SwiftPMInternal)\nimport PackageModel\n\n@testable import SPMBuildCore\nimport _InternalBuildTestSupport\nimport _InternalTestSupport\nimport Workspace\nimport XCTest\nimport Testing\n\n@testable import class Build.BuildPlan\nimport struct Build.PluginConfiguration\n\nimport struct TSCUtility.SerializedDiagnostics\n\nfinal class PluginInvocationTests: XCTestCase {\n    func testBasics() async throws {\n        // Construct a canned file system and package graph with a single package and a library that uses a build tool plugin that invokes a tool.\n        let fileSystem = InMemoryFileSystem(emptyFiles:\n            \"/Foo/Plugins/FooPlugin/source.swift\",\n            \"/Foo/Sources/FooTool/source.swift\",\n            \"/Foo/Sources/FooToolLib/source.swift\",\n            \"/Foo/Sources/Foo/source.swift\",\n            \"/Foo/Sources/Foo/SomeFile.abc\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    products: [\n                        ProductDescription(\n                            name: \"Foo\",\n                            type: .library(.dynamic),\n                            targets: [\"Foo\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\",\n                            type: .regular,\n                            pluginUsages: [.plugin(name: \"FooPlugin\", package: nil)]\n                        ),\n                        TargetDescription(\n                            name: \"FooPlugin\",\n                            dependencies: [\"FooTool\"],\n                            type: .plugin,\n                            pluginCapability: .buildTool\n                        ),\n                        TargetDescription(\n                            name: \"FooTool\",\n                            dependencies: [\"FooToolLib\"],\n                            type: .executable\n                        ),\n                        TargetDescription(\n                            name: \"FooToolLib\",\n                            dependencies: [],\n                            type: .regular\n                        ),\n                    ]\n                )\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        // Check the basic integrity before running plugins.\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        PackageGraphTesterXCTest(graph) { graph in\n            graph.check(packages: \"Foo\")\n            graph.check(modules: \"Foo\", \"FooPlugin\", \"FooTool\", \"FooToolLib\")\n            graph.checkTarget(\"Foo\") { target in\n                target.check(dependencies: \"FooPlugin\")\n            }\n            graph.checkTarget(\"FooPlugin\") { target in\n                target.check(type: .plugin)\n                target.check(dependencies: \"FooTool\")\n            }\n            graph.checkTarget(\"FooTool\") { target in\n                target.check(type: .executable)\n                target.checkDependency(\"FooToolLib\") { dependency in\n                    dependency.checkTarget { _ in\n                    }\n                }\n            }\n        }\n\n        // \"FooTool{Lib}\" duplicated as it's present for both build host and end target.\n        do {\n            let buildPlanResult = try await BuildPlanResult(plan: mockBuildPlan(\n                graph: graph,\n                linkingParameters: .init(\n                    shouldLinkStaticSwiftStdlib: true\n                ),\n                fileSystem: fileSystem,\n                observabilityScope: observability.topScope\n            ))\n            buildPlanResult.checkProductsCount(3)\n            buildPlanResult.checkTargetsCount(5) // Note: plugins are not included here.\n\n            buildPlanResult.check(destination: .target, for: \"Foo\")\n\n            buildPlanResult.check(destination: .host, for: \"FooTool\")\n            buildPlanResult.check(destination: .target, for: \"FooTool\")\n\n            buildPlanResult.check(destination: .host, for: \"FooToolLib\")\n            buildPlanResult.check(destination: .target, for: \"FooToolLib\")\n        }\n\n        // A fake PluginScriptRunner that just checks the input conditions and returns canned output.\n        struct MockPluginScriptRunner: PluginScriptRunner {\n            var hostTriple: Triple {\n                get throws {\n                    return try UserToolchain.default.targetTriple\n                }\n            }\n\n            func compilePluginScript(\n                sourceFiles: [AbsolutePath],\n                pluginName: String,\n                toolsVersion: ToolsVersion,\n                workers: UInt32,\n                observabilityScope: ObservabilityScope,\n                callbackQueue: DispatchQueue,\n                delegate: PluginScriptCompilerDelegate,\n                completion: @escaping (Result<PluginCompilationResult, Error>) -> Void\n            ) {\n                callbackQueue.sync {\n                    completion(.failure(StringError(\"unimplemented\")))\n                }\n            }\n\n            func runPluginScript(\n                sourceFiles: [AbsolutePath],\n                pluginName: String,\n                initialMessage: Data,\n                toolsVersion: ToolsVersion,\n                workingDirectory: AbsolutePath,\n                writableDirectories: [AbsolutePath],\n                readOnlyDirectories: [AbsolutePath],\n                allowNetworkConnections: [SandboxNetworkPermission],\n                workers: UInt32,\n                fileSystem: FileSystem,\n                observabilityScope: ObservabilityScope,\n                callbackQueue: DispatchQueue,\n                delegate: PluginScriptCompilerDelegate & PluginScriptRunnerDelegate,\n                completion: @escaping (Result<Int32, Error>) -> Void\n            ) {\n                // Check that we were given the right sources.\n                XCTAssertEqual(sourceFiles, [\"/Foo/Plugins/FooPlugin/source.swift\"])\n\n                do {\n                    // Pretend the plugin emitted some output.\n                    callbackQueue.sync {\n                        delegate.handleOutput(data: Data(\"Hello Plugin!\".utf8))\n                    }\n\n                    // Pretend it emitted a warning.\n                    try callbackQueue.sync {\n                        let message = Data(\"\"\"\n                        {   \"emitDiagnostic\": {\n                                \"severity\": \"warning\",\n                                \"message\": \"A warning\",\n                                \"file\": \"/Foo/Sources/Foo/SomeFile.abc\",\n                                \"line\": 42\n                            }\n                        }\n                        \"\"\".utf8)\n                        try delegate.handleMessage(data: message, responder: { _ in })\n                    }\n\n                    // Pretend it defined a build command.\n                    try callbackQueue.sync {\n                        let message = Data(\"\"\"\n                        {   \"defineBuildCommand\": {\n                                \"configuration\": {\n                                    \"version\": 2,\n                                    \"displayName\": \"Do something\",\n                                    \"executable\": \"file:///bin/FooTool\",\n                                    \"arguments\": [\n                                        \"-c\", \"/Foo/Sources/Foo/SomeFile.abc\"\n                                    ],\n                                    \"workingDirectory\": \"file:///Foo/Sources/Foo\",\n                                    \"environment\": {\n                                        \"X\": \"Y\"\n                                    },\n                                },\n                                \"inputFiles\": [\n                                ],\n                                \"outputFiles\": [\n                                ]\n                            }\n                        }\n                        \"\"\".utf8)\n                        try delegate.handleMessage(data: message, responder: { _ in })\n                    }\n                }\n                catch {\n                    callbackQueue.sync {\n                        completion(.failure(error))\n                    }\n                    return\n                }\n\n                // If we get this far we succeeded, so invoke the completion handler.\n                callbackQueue.sync {\n                    completion(.success(0))\n                }\n            }\n        }\n\n        // Construct a canned input and run plugins using our MockPluginScriptRunner().\n        let outputDir = AbsolutePath(\"/Foo/.build\")\n        let pluginRunner = MockPluginScriptRunner()\n        let buildParameters = mockBuildParameters(\n            destination: .host,\n            environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n        )\n\n        let results = try await invokeBuildToolPlugins(\n            graph: graph,\n            buildParameters: buildParameters,\n            fileSystem: fileSystem,\n            outputDir: outputDir,\n            pluginScriptRunner: pluginRunner,\n            observabilityScope: observability.topScope\n        )\n        let builtToolsDir = AbsolutePath(\"/path/to/build/\\(buildParameters.triple)/debug\")\n\n        // Check the canned output to make sure nothing was lost in transport.\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertEqual(results.count, 1)\n        let (_, (evalTarget, evalResults)) = try XCTUnwrap(results.first)\n        XCTAssertEqual(evalTarget.name, \"Foo\")\n\n        XCTAssertEqual(evalResults.count, 1)\n        let evalFirstResult = try XCTUnwrap(evalResults.first)\n        XCTAssertEqual(evalFirstResult.prebuildCommands.count, 0)\n        XCTAssertEqual(evalFirstResult.buildCommands.count, 1)\n        let evalFirstCommand = try XCTUnwrap(evalFirstResult.buildCommands.first)\n        XCTAssertEqual(evalFirstCommand.configuration.displayName, \"Do something\")\n        XCTAssertEqual(evalFirstCommand.configuration.executable, AbsolutePath(\"/bin/FooTool\"))\n        XCTAssertEqual(evalFirstCommand.configuration.arguments, [\"-c\", \"/Foo/Sources/Foo/SomeFile.abc\"])\n        XCTAssertEqual(evalFirstCommand.configuration.environment, [\"X\": \"Y\"])\n        XCTAssertEqual(evalFirstCommand.configuration.workingDirectory, AbsolutePath(\"/Foo/Sources/Foo\"))\n        XCTAssertEqual(evalFirstCommand.inputFiles, [builtToolsDir.appending(\"FooTool\" + ProcessInfo.exeSuffix)])\n        XCTAssertEqual(evalFirstCommand.outputFiles, [])\n\n        XCTAssertEqual(evalFirstResult.diagnostics.count, 1)\n        let evalFirstDiagnostic = try XCTUnwrap(evalFirstResult.diagnostics.first)\n        XCTAssertEqual(evalFirstDiagnostic.severity, .warning)\n        XCTAssertEqual(evalFirstDiagnostic.message, \"A warning\")\n        XCTAssertEqual(evalFirstDiagnostic.metadata?.fileLocation, FileLocation(\"/Foo/Sources/Foo/SomeFile.abc\", line: 42))\n\n        XCTAssertEqual(evalFirstResult.textOutput, \"Hello Plugin!\")\n    }\n\n    func testCompilationDiagnostics() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library target and a plugin.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(packageDir.appending(\"Package.swift\"), string: \"\"\"\n                // swift-tools-version: 5.6\n                import PackageDescription\n                let package = Package(\n                    name: \"MyPackage\",\n                    targets: [\n                        .target(\n                            name: \"MyLibrary\",\n                            plugins: [\n                                \"MyPlugin\",\n                            ]\n                        ),\n                        .plugin(\n                            name: \"MyPlugin\",\n                            capability: .buildTool()\n                        ),\n                    ]\n                )\n                \"\"\")\n\n            let myLibraryTargetDir = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n            try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(myLibraryTargetDir.appending(\"library.swift\"), string: \"\"\"\n                public func Foo() { }\n                \"\"\")\n\n            let myPluginTargetDir = packageDir.appending(components: \"Plugins\", \"MyPlugin\")\n            try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(myPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                import PackagePlugin\n                @main struct MyBuildToolPlugin: BuildToolPlugin {\n                    func createBuildCommands(\n                        context: PluginContext,\n                        target: Target\n                    ) throws -> [Command] {\n                        // missing return statement\n                    }\n                }\n                \"\"\")\n\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            XCTAssert(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssert(packageGraph.packages.count == 1, \"\\(packageGraph.packages)\")\n\n            // Find the build tool plugin.\n            let buildToolPlugin = try XCTUnwrap(packageGraph.packages.first?.modules.map(\\.underlying).first{ $0.name == \"MyPlugin\" } as? PluginModule)\n            XCTAssertEqual(buildToolPlugin.name, \"MyPlugin\")\n            XCTAssertEqual(buildToolPlugin.capability, .buildTool)\n\n            // Create a plugin script runner for the duration of the test.\n            let pluginCacheDir = tmpPath.appending(\"plugin-cache\")\n            let pluginScriptRunner = DefaultPluginScriptRunner(\n                fileSystem: localFileSystem,\n                cacheDir: pluginCacheDir,\n                toolchain: try UserToolchain.default\n            )\n\n            // Define a plugin compilation delegate that just captures the passed information.\n            class Delegate: PluginScriptCompilerDelegate {\n                var commandLine: [String]?\n                var environment: Environment?\n                var compiledResult: PluginCompilationResult?\n                var cachedResult: PluginCompilationResult?\n                init() {\n                }\n                func willCompilePlugin(commandLine: [String], environment: [String: String]) {\n                    self.commandLine = commandLine\n                    self.environment = .init(environment)\n                }\n                func didCompilePlugin(result: PluginCompilationResult) {\n                    self.compiledResult = result\n                }\n                func skippedCompilingPlugin(cachedResult: PluginCompilationResult) {\n                    self.cachedResult = cachedResult\n                }\n            }\n\n            // Try to compile the broken plugin script.\n            do {\n                let delegate = Delegate()\n                let result = try await pluginScriptRunner.compilePluginScript(\n                    sourceFiles: buildToolPlugin.sources.paths,\n                    pluginName: buildToolPlugin.name,\n                    toolsVersion: buildToolPlugin.apiVersion,\n                    workers: 1,\n                    observabilityScope: observability.topScope,\n                    callbackQueue: DispatchQueue.sharedConcurrent,\n                    delegate: delegate\n                )\n\n                // This should invoke the compiler but should fail.\n                XCTAssert(result.succeeded == false)\n                XCTAssert(result.cached == false)\n                XCTAssert(result.commandLine.contains(result.executableFile.pathString), \"\\(result.commandLine)\")\n                XCTAssert(result.commandLine.contains(\"-j1\"), \"expected workers flag in \\(result.commandLine)\")\n                XCTAssert(result.executableFile.components.contains(\"plugin-cache\"), \"\\(result.executableFile.pathString)\")\n                XCTAssert(result.compilerOutput.contains(\"error: missing return\"), \"\\(result.compilerOutput)\")\n                XCTAssert(result.diagnosticsFile.suffix == \".dia\", \"\\(result.diagnosticsFile.pathString)\")\n\n                // Check the delegate callbacks.\n                XCTAssertEqual(delegate.commandLine, result.commandLine)\n                XCTAssertNotNil(delegate.environment)\n                XCTAssertEqual(delegate.compiledResult, result)\n                XCTAssertNil(delegate.cachedResult)\n\n                // Check the serialized diagnostics. We should have an error.\n                let diaFileContents = try localFileSystem.readFileContents(result.diagnosticsFile)\n                let diagnosticsSet = try SerializedDiagnostics(bytes: diaFileContents)\n                XCTAssertEqual(diagnosticsSet.diagnostics.count, 1)\n                let errorDiagnostic = try XCTUnwrap(diagnosticsSet.diagnostics.first)\n                XCTAssertTrue(errorDiagnostic.text.hasPrefix(\"missing return\"), \"\\(errorDiagnostic)\")\n\n                // Check that the executable file doesn't exist.\n                XCTAssertFalse(localFileSystem.exists(result.executableFile), \"\\(result.executableFile.pathString)\")\n            }\n\n            // Now replace the plugin script source with syntactically valid contents that still produces a warning.\n            try localFileSystem.writeFileContents(myPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                import PackagePlugin\n                @main struct MyBuildToolPlugin: BuildToolPlugin {\n                    func createBuildCommands(\n                        context: PluginContext,\n                        target: Target\n                    ) throws -> [Command] {\n                        var unused: Int\n                        return []\n                    }\n                }\n                \"\"\")\n\n            // Try to compile the fixed plugin.\n            let firstExecModTime: Date\n            do {\n                let delegate = Delegate()\n                let result = try await pluginScriptRunner.compilePluginScript(\n                    sourceFiles: buildToolPlugin.sources.paths,\n                    pluginName: buildToolPlugin.name,\n                    toolsVersion: buildToolPlugin.apiVersion,\n                    workers: 1,\n                    observabilityScope: observability.topScope,\n                    callbackQueue: DispatchQueue.sharedConcurrent,\n                    delegate: delegate\n                )\n\n                // This should invoke the compiler and this time should succeed.\n                XCTAssert(result.succeeded == true)\n                XCTAssert(result.cached == false)\n                XCTAssert(result.commandLine.contains(result.executableFile.pathString), \"\\(result.commandLine)\")\n                XCTAssert(result.executableFile.components.contains(\"plugin-cache\"), \"\\(result.executableFile.pathString)\")\n                XCTAssert(result.compilerOutput.contains(\"warning: variable 'unused' was never used\"), \"\\(result.compilerOutput)\")\n                XCTAssert(result.diagnosticsFile.suffix == \".dia\", \"\\(result.diagnosticsFile.pathString)\")\n\n                // Check the delegate callbacks.\n                XCTAssertEqual(delegate.commandLine, result.commandLine)\n                XCTAssertNotNil(delegate.environment)\n                XCTAssertEqual(delegate.compiledResult, result)\n                XCTAssertNil(delegate.cachedResult)\n\n                if try UserToolchain.default.supportsSerializedDiagnostics() {\n                    // Check the serialized diagnostics. We should no longer have an error but now have a warning.\n                    let diaFileContents = try localFileSystem.readFileContents(result.diagnosticsFile)\n                    let diagnosticsSet = try SerializedDiagnostics(bytes: diaFileContents)\n                    let hasExpectedDiagnosticsCount = diagnosticsSet.diagnostics.count == 1\n                    let warningDiagnosticText = diagnosticsSet.diagnostics.first?.text ?? \"\"\n                    let hasExpectedWarningText = warningDiagnosticText.hasPrefix(\"variable \\'unused\\' was never used\")\n                    if hasExpectedDiagnosticsCount && hasExpectedWarningText {\n                        XCTAssertTrue(hasExpectedDiagnosticsCount, \"unexpected diagnostics count in \\(diagnosticsSet.diagnostics) from \\(result.diagnosticsFile.pathString)\")\n                        XCTAssertTrue(hasExpectedWarningText, \"\\(warningDiagnosticText)\")\n                    } else {\n                        print(\"bytes of serialized diagnostics file `\\(result.diagnosticsFile.pathString)`: \\(diaFileContents.contents)\")\n                        try XCTSkipIf(true, \"skipping because of unknown serialized diagnostics issue\")\n                    }\n                }\n\n                // Check that the executable file exists.\n                XCTAssertTrue(localFileSystem.exists(result.executableFile), \"\\(result.executableFile.pathString)\")\n\n                // Capture the timestamp of the executable so we can compare it later.\n                firstExecModTime = try localFileSystem.getFileInfo(result.executableFile).modTime\n            }\n\n            // Recompile the command plugin again without changing its source code.\n            let secondExecModTime: Date\n            do {\n                let delegate = Delegate()\n                let result = try await pluginScriptRunner.compilePluginScript(\n                    sourceFiles: buildToolPlugin.sources.paths,\n                    pluginName: buildToolPlugin.name,\n                    toolsVersion: buildToolPlugin.apiVersion,\n                    workers: 1,\n                    observabilityScope: observability.topScope,\n                    callbackQueue: DispatchQueue.sharedConcurrent,\n                    delegate: delegate\n                )\n\n                // This should not invoke the compiler (just reuse the cached executable).\n                XCTAssert(result.succeeded == true)\n                XCTAssert(result.cached == true)\n                XCTAssert(result.commandLine.contains(result.executableFile.pathString), \"\\(result.commandLine)\")\n                XCTAssert(result.executableFile.components.contains(\"plugin-cache\"), \"\\(result.executableFile.pathString)\")\n                XCTAssert(result.compilerOutput.contains(\"warning: variable 'unused' was never used\"), \"\\(result.compilerOutput)\")\n                XCTAssert(result.diagnosticsFile.suffix == \".dia\", \"\\(result.diagnosticsFile.pathString)\")\n\n                // Check the delegate callbacks. Note that the nil command line and environment indicates that we didn't get the callback saying that compilation will start; this is expected when the cache is reused. This is a behaviour of our test delegate. The command line is available in the cached result.\n                XCTAssertNil(delegate.commandLine)\n                XCTAssertNil(delegate.environment)\n                XCTAssertNil(delegate.compiledResult)\n                XCTAssertEqual(delegate.cachedResult, result)\n\n                if try UserToolchain.default.supportsSerializedDiagnostics() {\n                    // Check that the diagnostics still have the same warning as before.\n                    let diaFileContents = try localFileSystem.readFileContents(result.diagnosticsFile)\n                    let diagnosticsSet = try SerializedDiagnostics(bytes: diaFileContents)\n                    XCTAssertEqual(diagnosticsSet.diagnostics.count, 1)\n                    let warningDiagnostic = try XCTUnwrap(diagnosticsSet.diagnostics.first)\n                    XCTAssertTrue(warningDiagnostic.text.hasPrefix(\"variable \\'unused\\' was never used\"), \"\\(warningDiagnostic)\")\n                }\n\n                // Check that the executable file exists.\n                XCTAssertTrue(localFileSystem.exists(result.executableFile), \"\\(result.executableFile.pathString)\")\n\n                // Check that the timestamp hasn't changed (at least a mild indication that it wasn't recompiled).\n                secondExecModTime = try localFileSystem.getFileInfo(result.executableFile).modTime\n                XCTAssert(secondExecModTime == firstExecModTime, \"firstExecModTime: \\(firstExecModTime), secondExecModTime: \\(secondExecModTime)\")\n            }\n\n            // Now replace the plugin script source with syntactically valid contents that no longer produces a warning.\n            try localFileSystem.writeFileContents(myPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                import PackagePlugin\n                @main struct MyBuildToolPlugin: BuildToolPlugin {\n                    func createBuildCommands(\n                        context: PluginContext,\n                        target: Target\n                    ) throws -> [Command] {\n                        return []\n                    }\n                }\n                \"\"\")\n\n            // NTFS does not have nanosecond granularity (nor is this is a guaranteed file\n            // system feature on all file systems). Add a sleep before the execution to ensure that we have sufficient\n            // precision to read a difference.\n            try await Task.sleep(nanoseconds: UInt64(SendableTimeInterval.seconds(1).nanoseconds()!))\n\n            // Recompile the plugin again.\n            let thirdExecModTime: Date\n            do {\n                let delegate = Delegate()\n                let result = try await pluginScriptRunner.compilePluginScript(\n                    sourceFiles: buildToolPlugin.sources.paths,\n                    pluginName: buildToolPlugin.name,\n                    toolsVersion: buildToolPlugin.apiVersion,\n                    workers: 1,\n                    observabilityScope: observability.topScope,\n                    callbackQueue: DispatchQueue.sharedConcurrent,\n                    delegate: delegate\n                )\n\n                // This should invoke the compiler and not use the cache.\n                XCTAssert(result.succeeded == true)\n                XCTAssert(result.cached == false)\n                XCTAssert(result.commandLine.contains(result.executableFile.pathString), \"\\(result.commandLine)\")\n                XCTAssert(result.executableFile.components.contains(\"plugin-cache\"), \"\\(result.executableFile.pathString)\")\n                XCTAssert(!result.compilerOutput.contains(\"warning:\"), \"\\(result.compilerOutput)\")\n                XCTAssert(result.diagnosticsFile.suffix == \".dia\", \"\\(result.diagnosticsFile.pathString)\")\n\n                // Check the delegate callbacks.\n                XCTAssertEqual(delegate.commandLine, result.commandLine)\n                XCTAssertNotNil(delegate.environment)\n                XCTAssertEqual(delegate.compiledResult, result)\n                XCTAssertNil(delegate.cachedResult)\n\n                // Check that the diagnostics no longer have a warning.\n                let diaFileContents = try localFileSystem.readFileContents(result.diagnosticsFile)\n                let diagnosticsSet = try SerializedDiagnostics(bytes: diaFileContents)\n                XCTAssertEqual(diagnosticsSet.diagnostics.count, 0)\n\n                // Check that the executable file exists.\n                XCTAssertTrue(localFileSystem.exists(result.executableFile), \"\\(result.executableFile.pathString)\")\n\n                // Check that the timestamp has changed (at least a mild indication that it was recompiled).\n                thirdExecModTime = try localFileSystem.getFileInfo(result.executableFile).modTime\n                XCTAssert(thirdExecModTime != firstExecModTime, \"thirdExecModTime: \\(thirdExecModTime), firstExecModTime: \\(firstExecModTime)\")\n                XCTAssert(thirdExecModTime != secondExecModTime, \"thirdExecModTime: \\(thirdExecModTime), secondExecModTime: \\(secondExecModTime)\")\n            }\n\n            // Now replace the plugin script source with a broken one again.\n            try localFileSystem.writeFileContents(myPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                import PackagePlugin\n                @main struct MyBuildToolPlugin: BuildToolPlugin {\n                    func createBuildCommands(\n                        context: PluginContext,\n                        target: Target\n                    ) throws -> [Command] {\n                        return nil  // returning the wrong type\n                    }\n                }\n                \"\"\")\n\n            // Recompile the plugin again.\n            do {\n                let delegate = Delegate()\n                let result = try await pluginScriptRunner.compilePluginScript(\n                    sourceFiles: buildToolPlugin.sources.paths,\n                    pluginName: buildToolPlugin.name,\n                    toolsVersion: buildToolPlugin.apiVersion,\n                    workers: 1,\n                    observabilityScope: observability.topScope,\n                    callbackQueue: DispatchQueue.sharedConcurrent,\n                    delegate: delegate\n                )\n\n                // This should again invoke the compiler but should fail.\n                XCTAssert(result.succeeded == false)\n                XCTAssert(result.cached == false)\n                XCTAssert(result.commandLine.contains(result.executableFile.pathString), \"\\(result.commandLine)\")\n                XCTAssert(result.executableFile.components.contains(\"plugin-cache\"), \"\\(result.executableFile.pathString)\")\n                XCTAssert(result.compilerOutput.contains(\"error: 'nil' is incompatible with return type\"), \"\\(result.compilerOutput)\")\n                XCTAssert(result.diagnosticsFile.suffix == \".dia\", \"\\(result.diagnosticsFile.pathString)\")\n\n                // Check the delegate callbacks.\n                XCTAssertEqual(delegate.commandLine, result.commandLine)\n                XCTAssertNotNil(delegate.environment)\n                XCTAssertEqual(delegate.compiledResult, result)\n                XCTAssertNil(delegate.cachedResult)\n\n                // Check the diagnostics. We should have a different error than the original one.\n                let diaFileContents = try localFileSystem.readFileContents(result.diagnosticsFile)\n                let diagnosticsSet = try SerializedDiagnostics(bytes: diaFileContents)\n                XCTAssertEqual(diagnosticsSet.diagnostics.count, 1)\n                let errorDiagnostic = try XCTUnwrap(diagnosticsSet.diagnostics.first)\n                XCTAssertTrue(errorDiagnostic.text.hasPrefix(\"'nil' is incompatible with return type\"), \"\\(errorDiagnostic)\")\n\n                // Check that the executable file no longer exists.\n                XCTAssertFalse(localFileSystem.exists(result.executableFile), \"\\(result.executableFile.pathString)\")\n            }\n        }\n    }\n\n    func testUnsupportedDependencyProduct() async throws {\n        // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).\n        try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), \"skipping because test environment doesn't support concurrency\")\n\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library product and a plugin.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(packageDir.appending(\"Package.swift\"), string: \"\"\"\n            // swift-tools-version: 5.7\n            import PackageDescription\n            let package = Package(\n                name: \"MyPackage\",\n                dependencies: [\n                  .package(path: \"../FooPackage\"),\n                ],\n                targets: [\n                    .plugin(\n                        name: \"MyPlugin\",\n                        capability: .buildTool(),\n                        dependencies: [\n                            .product(name: \"FooLib\", package: \"FooPackage\"),\n                        ]\n                    ),\n                ]\n            )\n            \"\"\")\n\n            let myPluginTargetDir = packageDir.appending(components: \"Plugins\", \"MyPlugin\")\n            try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(myPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                  import PackagePlugin\n                  import Foo\n                  @main struct MyBuildToolPlugin: BuildToolPlugin {\n                      func createBuildCommands(\n                          context: PluginContext,\n                          target: Target\n                      ) throws -> [Command] { }\n                  }\n                  \"\"\")\n\n            let fooPkgDir = tmpPath.appending(components: \"FooPackage\")\n            try localFileSystem.createDirectory(fooPkgDir, recursive: true)\n            try localFileSystem.writeFileContents(fooPkgDir.appending(\"Package.swift\"), string: \"\"\"\n                // swift-tools-version: 5.7\n                import PackageDescription\n                let package = Package(\n                    name: \"FooPackage\",\n                    products: [\n                        .library(name: \"FooLib\",\n                                 targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"Foo\",\n                            dependencies: []\n                        ),\n                    ]\n                )\n                \"\"\")\n            let fooTargetDir = fooPkgDir.appending(components: \"Sources\", \"Foo\")\n            try localFileSystem.createDirectory(fooTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(fooTargetDir.appending(\"file.swift\"), string: \"\"\"\n                  public func foo() { }\n                  \"\"\")\n\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            XCTAssert(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            await XCTAssertAsyncThrowsError(try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )) { error in\n                var diagnosed = false\n                if let realError = error as? PackageGraphError,\n                   realError.description == \"plugin 'MyPlugin' cannot depend on 'FooLib' of type 'library' from package 'foopackage'; this dependency is unsupported\" {\n                    diagnosed = true\n                }\n                XCTAssertTrue(diagnosed)\n            }\n        }\n    }\n\n    func testUnsupportedDependencyTarget() async throws {\n        // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).\n        try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), \"skipping because test environment doesn't support concurrency\")\n\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library target and a plugin.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(packageDir.appending(\"Package.swift\"), string: \"\"\"\n                // swift-tools-version: 5.7\n                import PackageDescription\n                let package = Package(\n                    name: \"MyPackage\",\n                    targets: [\n                        .target(\n                            name: \"MyLibrary\",\n                            dependencies: []\n                        ),\n                        .plugin(\n                            name: \"MyPlugin\",\n                            capability: .buildTool(),\n                            dependencies: [\n                                \"MyLibrary\"\n                            ]\n                        ),\n                    ]\n                )\n                \"\"\")\n\n            let myLibraryTargetDir = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n            try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(myLibraryTargetDir.appending(\"library.swift\"), string: \"\"\"\n                    public func hello() { }\n                    \"\"\")\n            let myPluginTargetDir = packageDir.appending(components: \"Plugins\", \"MyPlugin\")\n            try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(myPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                  import PackagePlugin\n                  import MyLibrary\n                  @main struct MyBuildToolPlugin: BuildToolPlugin {\n                      func createBuildCommands(\n                          context: PluginContext,\n                          target: Target\n                      ) throws -> [Command] { }\n                  }\n                  \"\"\")\n\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            XCTAssert(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            await XCTAssertAsyncThrowsError(try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )) { error in\n                var diagnosed = false\n                if let realError = error as? PackageGraphError,\n                   realError.description == \"plugin 'MyPlugin' cannot depend on 'MyLibrary' of type 'library'; this dependency is unsupported\" {\n                    diagnosed = true\n                }\n                XCTAssertTrue(diagnosed)\n            }\n        }\n    }\n\n    func testPrebuildPluginShouldUseBinaryTarget() async throws {\n        // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).\n        try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), \"skipping because test environment doesn't support concurrency\")\n\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library target and a plugin.\n            let packageDir = tmpPath.appending(components: \"mypkg\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(packageDir.appending(\"Package.swift\"), string: \"\"\"\n                // swift-tools-version:6.0\n\n                import PackageDescription\n\n                let package = Package(\n                    name: \"mypkg\",\n                    products: [\n                        .library(\n                            name: \"MyLib\",\n                            targets: [\"MyLib\"])\n                    ],\n                    targets: [\n                        .target(\n                            name: \"MyLib\",\n                            plugins: [\n                                .plugin(name: \"X\")\n                            ]),\n                        .plugin(\n                            name: \"X\",\n                            capability: .buildTool(),\n                            dependencies: [ \"Y\" ]\n                        ),\n                        .binaryTarget(\n                            name: \"Y\",\n                            path: \"Binaries/Y.\\(artifactBundleExtension)\"\n                        ),\n                    ]\n                )\n                \"\"\")\n\n            let libTargetDir = packageDir.appending(components: \"Sources\", \"MyLib\")\n            try localFileSystem.createDirectory(libTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(libTargetDir.appending(\"file.swift\"), string: \"\"\"\n                public struct MyUtilLib {\n                    public let strings: [String]\n                    public init(args: [String]) {\n                        self.strings = args\n                    }\n                }\n            \"\"\")\n\n            let depTargetDir = packageDir.appending(components: \"Sources\", \"Y\")\n            try localFileSystem.createDirectory(depTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(depTargetDir.appending(\"main.swift\"), string: \"\"\"\n                struct Y {\n                    func run() {\n                        print(\"You passed us two arguments, argumentOne, and argumentTwo\")\n                    }\n                }\n                Y.main()\n            \"\"\")\n\n            let pluginTargetDir = packageDir.appending(components: \"Plugins\", \"X\")\n            try localFileSystem.createDirectory(pluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(pluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                  import PackagePlugin\n                  @main struct X: BuildToolPlugin {\n                      func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n                          [\n                              Command.prebuildCommand(\n                                  displayName: \"X: Running Y before the build...\",\n                                  executable: try context.tool(named: \"Y\").url,\n                                  arguments: [ \"ARGUMENT_ONE\", \"ARGUMENT_TWO\" ],\n                                  outputFilesDirectory: context.pluginWorkDirectoryURL.appendingPathComponent(\"OUTPUT_FILES_DIRECTORY\")\n                              )\n                          ]\n                      }\n                  }\n                  \"\"\")\n\n            let artifactVariants = [try UserToolchain.default.targetTriple].map {\n                \"\"\"\n                { \"path\": \"Y\", \"supportedTriples\": [\"\\($0.tripleString)\"] }\n                \"\"\"\n            }\n\n            let bundlePath = packageDir.appending(components: \"Binaries\", \"Y.\\(artifactBundleExtension)\")\n            let bundleMetadataPath = bundlePath.appending(component: \"info.json\")\n            try localFileSystem.createDirectory(bundleMetadataPath.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                bundleMetadataPath,\n                string: \"\"\"\n                {   \"schemaVersion\": \"1.0\",\n                    \"artifacts\": {\n                        \"Y\": {\n                            \"type\": \"executable\",\n                            \"version\": \"1.2.3\",\n                            \"variants\": [\n                                \\(artifactVariants.joined(separator: \",\"))\n                            ]\n                        }\n                    }\n                }\n                \"\"\"\n            )\n            let binaryPath = bundlePath.appending(component: \"Y\")\n            try localFileSystem.writeFileContents(binaryPath, string: \"\")\n\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            XCTAssert(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssert(packageGraph.packages.count == 1, \"\\(packageGraph.packages)\")\n\n            // Find the build tool plugin.\n            let buildToolPlugin = try XCTUnwrap(packageGraph.packages.first?.modules.map(\\.underlying).filter{ $0.name == \"X\" }.first as? PluginModule)\n            XCTAssertEqual(buildToolPlugin.name, \"X\")\n            XCTAssertEqual(buildToolPlugin.capability, .buildTool)\n\n            // Create a plugin script runner for the duration of the test.\n            let pluginCacheDir = tmpPath.appending(\"plugin-cache\")\n            let pluginScriptRunner = DefaultPluginScriptRunner(\n                fileSystem: localFileSystem,\n                cacheDir: pluginCacheDir,\n                toolchain: try UserToolchain.default\n            )\n\n            // Invoke build tool plugin\n            do {\n                let outputDir = packageDir.appending(\".build\")\n                let buildParameters = mockBuildParameters(\n                    destination: .host,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n\n                let result = try await invokeBuildToolPlugins(\n                    graph: packageGraph,\n                    buildParameters: buildParameters,\n                    fileSystem: localFileSystem,\n                    outputDir: outputDir,\n                    pluginScriptRunner: pluginScriptRunner,\n                    observabilityScope: observability.topScope\n                )\n\n                let diags = result.flatMap(\\.value.results).flatMap(\\.diagnostics)\n                testDiagnostics(diags) { result in\n                    result.checkIsEmpty()\n                }\n            }\n        }\n    }\n\n\n    func testPrebuildPluginShouldNotUseExecTarget() async throws {\n        // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).\n        try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), \"skipping because test environment doesn't support concurrency\")\n\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library target and a plugin.\n            let packageDir = tmpPath.appending(components: \"mypkg\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(packageDir.appending(\"Package.swift\"), string: \"\"\"\n                // swift-tools-version:6.0\n\n                import PackageDescription\n\n                let package = Package(\n                    name: \"mypkg\",\n                    products: [\n                        .library(\n                            name: \"MyLib\",\n                            targets: [\"MyLib\"])\n                    ],\n                    targets: [\n                        .target(\n                            name: \"MyLib\",\n                            plugins: [\n                                .plugin(name: \"X\")\n                            ]),\n                        .plugin(\n                            name: \"X\",\n                            capability: .buildTool(),\n                            dependencies: [ \"Y\" ]\n                        ),\n                        .executableTarget(\n                            name: \"Y\",\n                            dependencies: []),\n                    ]\n                )\n                \"\"\")\n\n            let libTargetDir = packageDir.appending(components: \"Sources\", \"MyLib\")\n            try localFileSystem.createDirectory(libTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(libTargetDir.appending(\"file.swift\"), string: \"\"\"\n                public struct MyUtilLib {\n                    public let strings: [String]\n                    public init(args: [String]) {\n                        self.strings = args\n                    }\n                }\n            \"\"\")\n\n            let depTargetDir = packageDir.appending(components: \"Sources\", \"Y\")\n            try localFileSystem.createDirectory(depTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(depTargetDir.appending(\"main.swift\"), string: \"\"\"\n                struct Y {\n                    func run() {\n                        print(\"You passed us two arguments, argumentOne, and argumentTwo\")\n                    }\n                }\n                Y.main()\n            \"\"\")\n\n            let pluginTargetDir = packageDir.appending(components: \"Plugins\", \"X\")\n            try localFileSystem.createDirectory(pluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(pluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                  import PackagePlugin\n                  @main struct X: BuildToolPlugin {\n                      func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n                          [\n                              Command.prebuildCommand(\n                                  displayName: \"X: Running Y before the build...\",\n                                  executable: try context.tool(named: \"Y\").url,\n                                  arguments: [ \"ARGUMENT_ONE\", \"ARGUMENT_TWO\" ],\n                                  outputFilesDirectory: context.pluginWorkDirectoryURL.appendingPathComponent(\"OUTPUT_FILES_DIRECTORY\")\n                              )\n                          ]\n                      }\n                  }\n                  \"\"\")\n\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            XCTAssert(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssert(packageGraph.packages.count == 1, \"\\(packageGraph.packages)\")\n\n            // Find the build tool plugin.\n            let buildToolPlugin = try XCTUnwrap(packageGraph.packages.first?.modules.map(\\.underlying).filter{ $0.name == \"X\" }.first as? PluginModule)\n            XCTAssertEqual(buildToolPlugin.name, \"X\")\n            XCTAssertEqual(buildToolPlugin.capability, .buildTool)\n\n            // Create a plugin script runner for the duration of the test.\n            let pluginCacheDir = tmpPath.appending(\"plugin-cache\")\n            let pluginScriptRunner = DefaultPluginScriptRunner(\n                fileSystem: localFileSystem,\n                cacheDir: pluginCacheDir,\n                toolchain: try UserToolchain.default\n            )\n\n            // Invoke build tool plugin\n            do {\n                let outputDir = packageDir.appending(\".build\")\n                let buildParameters = mockBuildParameters(\n                    destination: .host,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n\n                let result = try await invokeBuildToolPlugins(\n                    graph: packageGraph,\n                    buildParameters: buildParameters,\n                    fileSystem: localFileSystem,\n                    outputDir: outputDir,\n                    pluginScriptRunner: pluginScriptRunner,\n                    observabilityScope: observability.topScope\n                )\n\n                let diags = result.flatMap(\\.value.results).flatMap(\\.diagnostics)\n                testDiagnostics(diags) { result in\n                    let msg = \"a prebuild command cannot use executables built from source, including executable target '\\(\"Y\" + ProcessInfo.exeSuffix)'\"\n                    result.check(diagnostic: .contains(msg), severity: .error)\n                }\n            }\n        }\n    }\n\n    func testScanImportsInPluginTargets() async throws {\n        // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).\n        try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), \"skipping because test environment doesn't support concurrency\")\n\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library target and a plugin.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(packageDir.appending(\"Package.swift\"), string: \"\"\"\n                // swift-tools-version: 5.7\n                import PackageDescription\n                let package = Package(\n                    name: \"MyPackage\",\n                    dependencies: [\n                      .package(path: \"../OtherPackage\"),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"MyLibrary\",\n                            dependencies: [.product(name: \"OtherPlugin\", package: \"OtherPackage\")]\n                        ),\n                        .plugin(\n                            name: \"XPlugin\",\n                            capability: .buildTool()\n                        ),\n                        .plugin(\n                            name: \"YPlugin\",\n                            capability: .command(\n                               intent: .custom(verb: \"YPlugin\", description: \"Plugin example\"),\n                               permissions: []\n                            )\n                        )\n                    ]\n                )\n                \"\"\")\n\n            let myLibraryTargetDir = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n            try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(myLibraryTargetDir.appending(\"library.swift\"), string: \"\"\"\n                    public func hello() { }\n                    \"\"\")\n            let xPluginTargetDir = packageDir.appending(components: \"Plugins\", \"XPlugin\")\n            try localFileSystem.createDirectory(xPluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(xPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                  import PackagePlugin\n                  import XcodeProjectPlugin\n                  @main struct XBuildToolPlugin: BuildToolPlugin {\n                      func createBuildCommands(\n                          context: PluginContext,\n                          target: Target\n                      ) throws -> [Command] { }\n                  }\n                  \"\"\")\n            let yPluginTargetDir = packageDir.appending(components: \"Plugins\", \"YPlugin\")\n            try localFileSystem.createDirectory(yPluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(yPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                     import PackagePlugin\n                     import Foundation\n                     @main struct YPlugin: BuildToolPlugin {\n                         func createBuildCommands(\n                             context: PluginContext,\n                             target: Target\n                         ) throws -> [Command] { }\n                     }\n                     \"\"\")\n\n\n            //////\n\n            let otherPackageDir = tmpPath.appending(components: \"OtherPackage\")\n            try localFileSystem.createDirectory(otherPackageDir, recursive: true)\n            try localFileSystem.writeFileContents(otherPackageDir.appending(\"Package.swift\"), string: \"\"\"\n                // swift-tools-version: 5.7\n                import PackageDescription\n                let package = Package(\n                    name: \"OtherPackage\",\n                    products: [\n                        .plugin(\n                            name: \"OtherPlugin\",\n                            targets: [\"QPlugin\"])\n                    ],\n                    targets: [\n                        .plugin(\n                            name: \"QPlugin\",\n                            capability: .buildTool()\n                        ),\n                        .plugin(\n                            name: \"RPlugin\",\n                            capability: .command(\n                               intent: .custom(verb: \"RPlugin\", description: \"Plugin example\"),\n                               permissions: []\n                            )\n                        )\n                    ]\n                )\n                \"\"\")\n\n            let qPluginTargetDir = otherPackageDir.appending(components: \"Plugins\", \"QPlugin\")\n            try localFileSystem.createDirectory(qPluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(qPluginTargetDir.appending(\"plugin.swift\"), string: \"\"\"\n                  import PackagePlugin\n                  import XcodeProjectPlugin\n                  #if canImport(ModuleFoundViaExtraSearchPaths)\n                  import ModuleFoundViaExtraSearchPaths\n                  #endif\n                  @main struct QBuildToolPlugin: BuildToolPlugin {\n                      func createBuildCommands(\n                          context: PluginContext,\n                          target: Target\n                      ) throws -> [Command] { }\n                  }\n                  \"\"\")\n\n            // Create a valid swift interface file that can be detected via `canImport()`.\n            let fakeExtraModulesDir = tmpPath.appending(\"ExtraModules\")\n            try localFileSystem.createDirectory(fakeExtraModulesDir, recursive: true)\n            let fakeExtraModuleFile = fakeExtraModulesDir.appending(\"ModuleFoundViaExtraSearchPaths.swiftinterface\")\n            try localFileSystem.writeFileContents(fakeExtraModuleFile, string: \"\"\"\n                  // swift-interface-format-version: 1.0\n                  // swift-module-flags: -module-name ModuleFoundViaExtraSearchPaths\n                  \"\"\")\n\n            /////////\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let environment = Environment.current\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                location: try Workspace.Location(forRootPackage: packageDir, fileSystem: localFileSystem),\n                customHostToolchain: UserToolchain(\n                    swiftSDK: .hostSwiftSDK(\n                        environment: environment\n                    ),\n                    environment: environment,\n                    customLibrariesLocation: .init(manifestLibraryPath: fakeExtraModulesDir, pluginLibraryPath: fakeExtraModulesDir)\n                ),\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            XCTAssert(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            let graph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            let dict = try await workspace.loadPluginImports(packageGraph: graph)\n\n            var count = 0\n            for (pkg, entry) in dict {\n                if pkg.description == \"mypackage\" {\n                    XCTAssertNotNil(entry[\"XPlugin\"])\n                    let XPluginPossibleImports1 = [\"PackagePlugin\", \"XcodeProjectPlugin\"]\n                    let XPluginPossibleImports2 = [\"PackagePlugin\", \"XcodeProjectPlugin\", \"_SwiftConcurrencyShims\"]\n                    XCTAssertTrue(entry[\"XPlugin\"] == XPluginPossibleImports1 ||\n                                  entry[\"XPlugin\"] == XPluginPossibleImports2)\n\n                    let YPluginPossibleImports1 = [\"PackagePlugin\", \"Foundation\"]\n                    let YPluginPossibleImports2 = [\"PackagePlugin\", \"Foundation\", \"_SwiftConcurrencyShims\"]\n                    XCTAssertTrue(entry[\"YPlugin\"] == YPluginPossibleImports1 ||\n                                  entry[\"YPlugin\"] == YPluginPossibleImports2)\n                    count += 1\n                } else if pkg.description == \"otherpackage\" {\n                    XCTAssertNotNil(dict[pkg]?[\"QPlugin\"])\n\n                    let possibleImports1 = [\"PackagePlugin\", \"XcodeProjectPlugin\", \"ModuleFoundViaExtraSearchPaths\"]\n                    let possibleImports2 = [\"PackagePlugin\", \"XcodeProjectPlugin\", \"ModuleFoundViaExtraSearchPaths\", \"_SwiftConcurrencyShims\"]\n                    XCTAssertTrue(entry[\"QPlugin\"] == possibleImports1 ||\n                                  entry[\"QPlugin\"] == possibleImports2)\n                    count += 1\n                }\n            }\n\n            XCTAssertEqual(count, 2)\n        }\n    }\n\n    func checkParseArtifactsPlatformCompatibility(\n        artifactSupportedTriples: [Triple],\n        hostTriple: Triple\n    ) async throws -> [ResolvedModule.ID: [BuildToolPluginInvocationResult]]  {\n        // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).\n        try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), \"skipping because test environment doesn't support concurrency\")\n\n        return try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library target and a plugin.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(packageDir.appending(\"Package.swift\"), string: \"\"\"\n                   // swift-tools-version: 5.7\n                   import PackageDescription\n                   let package = Package(\n                       name: \"MyPackage\",\n                       dependencies: [\n                       ],\n                       targets: [\n                           .target(\n                               name: \"MyLibrary\",\n                               plugins: [\n                                   \"Foo\",\n                               ]\n                           ),\n                           .plugin(\n                               name: \"Foo\",\n                               capability: .buildTool(),\n                               dependencies: [\n                                   .target(name: \"LocalBinaryTool\"),\n                               ]\n                            ),\n                           .binaryTarget(\n                               name: \"LocalBinaryTool\",\n                               path: \"Binaries/LocalBinaryTool.\\(artifactBundleExtension)\"\n                           ),\n                        ]\n                   )\n                   \"\"\")\n\n            let libDir = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n            try localFileSystem.createDirectory(libDir, recursive: true)\n            try localFileSystem.writeFileContents(\n                libDir.appending(components: \"library.swift\"),\n                string: \"\"\"\n                public func myLib() { }\n                \"\"\"\n            )\n\n            let myPluginTargetDir = packageDir.appending(components: \"Plugins\", \"Foo\")\n            try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)\n            let content = \"\"\"\n                 import PackagePlugin\n                 @main struct FooPlugin: BuildToolPlugin {\n                     func createBuildCommands(\n                         context: PluginContext,\n                         target: Target\n                     ) throws -> [Command] {\n                        print(\"Looking for LocalBinaryTool...\")\n                        let localBinaryTool = try context.tool(named: \"LocalBinaryTool\")\n                        print(\"... found it at \\\\(localBinaryTool.path)\")\n                        return [.buildCommand(displayName: \"\", executable: localBinaryTool.path, arguments: [], inputFiles: [], outputFiles: [])]\n                    }\n                 }\n            \"\"\"\n            try localFileSystem.writeFileContents(myPluginTargetDir.appending(\"plugin.swift\"), string: content)\n            let artifactVariants = artifactSupportedTriples.map {\n                \"\"\"\n                { \"path\": \"\\($0.tripleString)/LocalBinaryTool\", \"supportedTriples\": [\"\\($0.tripleString)\"] }\n                \"\"\"\n            }\n\n            let bundleMetadataPath = packageDir.appending(\n                components: \"Binaries\",\n                \"LocalBinaryTool.artifactbundle\",\n                \"info.json\"\n            )\n            try localFileSystem.createDirectory(bundleMetadataPath.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                bundleMetadataPath,\n                string: \"\"\"\n                {   \"schemaVersion\": \"1.0\",\n                    \"artifacts\": {\n                        \"LocalBinaryTool\": {\n                            \"type\": \"executable\",\n                            \"version\": \"1.2.3\",\n                            \"variants\": [\n                                \\(artifactVariants.joined(separator: \",\"))\n                            ]\n                        }\n                    }\n                }\n                \"\"\"\n            )\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            XCTAssert(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            XCTAssertNoDiagnostics(observability.diagnostics)\n\n            // Find the build tool plugin.\n            let buildToolPlugin = try XCTUnwrap(packageGraph.packages.first?.modules\n                .map(\\.underlying)\n                .filter { $0.name == \"Foo\" }\n                .first as? PluginModule)\n            XCTAssertEqual(buildToolPlugin.name, \"Foo\")\n            XCTAssertEqual(buildToolPlugin.capability, .buildTool)\n\n            // Construct a toolchain with a made-up host/target triple\n            let swiftSDK = try SwiftSDK.default\n            let toolchain = try UserToolchain(\n                swiftSDK: SwiftSDK(\n                    hostTriple: hostTriple,\n                    targetTriple: hostTriple,\n                    toolset: swiftSDK.toolset,\n                    pathsConfiguration: swiftSDK.pathsConfiguration\n                ),\n                environment: .current\n            )\n\n            // Create a plugin script runner for the duration of the test.\n            let pluginCacheDir = tmpPath.appending(\"plugin-cache\")\n            let pluginScriptRunner = DefaultPluginScriptRunner(\n                fileSystem: localFileSystem,\n                cacheDir: pluginCacheDir,\n                toolchain: toolchain\n            )\n\n            // Invoke build tool plugin\n            let outputDir = packageDir.appending(\".build\")\n            let buildParameters = mockBuildParameters(\n                destination: .host,\n                environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n            )\n\n            return try await invokeBuildToolPlugins(\n                graph: packageGraph,\n                buildParameters: buildParameters,\n                fileSystem: localFileSystem,\n                outputDir: outputDir,\n                pluginScriptRunner: pluginScriptRunner,\n                observabilityScope: observability.topScope\n            ).mapValues(\\.results)\n        }\n    }\n\n    func testParseArtifactNotSupportedOnTargetPlatform() async throws {\n        let hostTriple = try UserToolchain.default.targetTriple\n        let artifactSupportedTriples = try [Triple(\"riscv64-apple-windows-android\")]\n\n        var checked = false\n        let result = try await checkParseArtifactsPlatformCompatibility(artifactSupportedTriples: artifactSupportedTriples, hostTriple: hostTriple)\n        if let pluginResult = result.first,\n           let diag = pluginResult.value.first?.diagnostics,\n           diag.description == \"[[error]: Tool ‘LocalBinaryTool’ is not supported on the target platform]\" {\n            checked = true\n        }\n        XCTAssertTrue(checked)\n    }\n\n    func testParseArtifactsDoesNotCheckPlatformVersion() async throws {\n        #if !os(macOS)\n        throw XCTSkip(\"platform versions are only available if the host is macOS\")\n        #else\n        let hostTriple = try UserToolchain.default.targetTriple\n        let artifactSupportedTriples = try [Triple(\"\\(hostTriple.withoutVersion().tripleString)20.0\")]\n\n        let result = try await checkParseArtifactsPlatformCompatibility(artifactSupportedTriples: artifactSupportedTriples, hostTriple: hostTriple)\n        result.forEach {\n            $0.value.forEach {\n                XCTAssertTrue($0.succeeded, \"plugin unexpectedly failed\")\n                XCTAssertEqual($0.diagnostics.map { $0.message }, [], \"plugin produced unexpected diagnostics\")\n            }\n        }\n        #endif\n    }\n\n    func testParseArtifactsConsidersAllSupportedTriples() async throws {\n        let hostTriple = try UserToolchain.default.targetTriple\n        let artifactSupportedTriples = [hostTriple, try Triple(\"riscv64-apple-windows-android\")]\n\n        let result = try await checkParseArtifactsPlatformCompatibility(artifactSupportedTriples: artifactSupportedTriples, hostTriple: hostTriple)\n        result.forEach {\n            $0.value.forEach {\n                XCTAssertTrue($0.succeeded, \"plugin unexpectedly failed\")\n                XCTAssertEqual($0.diagnostics.map { $0.message }, [], \"plugin produced unexpected diagnostics\")\n                XCTAssertEqual($0.buildCommands.first?.configuration.executable.basename, \"LocalBinaryTool\")\n            }\n        }\n    }\n\n    private func invokeBuildToolPlugins(\n        graph: ModulesGraph,\n        buildParameters: BuildParameters,\n        fileSystem: any FileSystem,\n        outputDir: AbsolutePath,\n        pluginScriptRunner: PluginScriptRunner,\n        observabilityScope: ObservabilityScope\n    ) async throws -> [ResolvedModule.ID: (target: ResolvedModule, results: [BuildToolPluginInvocationResult])] {\n        let pluginsPerModule = graph.pluginsPerModule(\n            satisfying: buildParameters.buildEnvironment\n        )\n\n        let plugins = pluginsPerModule.values.reduce(into: IdentifiableSet<ResolvedModule>()) { result, plugins in\n            plugins.forEach { result.insert($0) }\n        }\n\n        var pluginInvocationResults: [ResolvedModule.ID: (\n            target: ResolvedModule,\n            results: [BuildToolPluginInvocationResult]\n        )] = [:]\n\n        let pluginConfiguration = PluginConfiguration(\n            scriptRunner: pluginScriptRunner,\n            workDirectory: outputDir.parentDirectory,\n            disableSandbox: false\n        )\n\n        for (moduleID, _) in pluginsPerModule {\n            let module = graph.allModules[moduleID]!\n\n            let results = try await BuildPlan.invokeBuildToolPlugins(\n                for: module,\n                destination: .target,\n                configuration: pluginConfiguration,\n                buildParameters: buildParameters,\n                modulesGraph: graph,\n                tools: mockPluginTools(\n                    plugins: plugins,\n                    fileSystem: fileSystem,\n                    buildParameters: buildParameters,\n                    hostTriple: hostTriple\n                ),\n                additionalFileRules: [],\n                pkgConfigDirectories: [],\n                fileSystem: fileSystem,\n                observabilityScope: observabilityScope\n            )\n\n            pluginInvocationResults[moduleID] = (target: module, results: results)\n        }\n\n        return pluginInvocationResults\n    }\n}\n\nextension BuildPlanResult {\n    func check(\n        destination: BuildParameters.Destination,\n        for target: String,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) {\n        let targets = self.targetMap.filter {\n            $0.module.name == target && $0.destination == destination\n        }\n        XCTAssertEqual(targets.count, 1, file: file, line: line)\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/PluginsBuildPlanTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\nimport Basics\nimport PackageModel\nimport Testing\nimport _InternalTestSupport\n\n@testable import SPMBuildCore\n\n@Suite(\n    .serialized,\n    .tags(\n        .TestSize.large,\n    ),\n)\nstruct PluginsBuildPlanTests {\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n            .Feature.Plugin,\n            .Feature.SourceGeneration,\n        ),\n        arguments: BuildConfiguration.allCases,\n    )\n    func buildToolsDatabasePath(\n        config: BuildConfiguration,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPlugin\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: config,\n                buildSystem: .native\n            )\n            #expect(stdout.contains(\"Build complete!\"))\n            // FIXME: This is temporary until build of plugin tools is extracted into its own command.\n            #expect(localFileSystem.exists(fixturePath.appending(RelativePath(\".build/plugin-tools.db\"))))\n            #expect(localFileSystem.exists(fixturePath.appending(RelativePath(\".build/build.db\"))))\n        }\n    }\n\n    @Test(\n        .serialized,\n        .tags(\n            .Feature.Command.Package.CommandPlugin,\n        ),\n        .requireHostOS(.macOS),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandPluginDependenciesWhenNotCrossCompiling(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        let hostToolchain = try UserToolchain(\n            swiftSDK: .hostSwiftSDK(environment: [:]),\n            environment: [:]\n        )\n        let hostTriple = try! hostToolchain.targetTriple.withoutVersion().tripleString\n\n        let hostBinPathSegments = try buildSystem.binPath(\n            for: config,\n            triple: hostTriple,\n        )\n        let hostDebugBinPathSegments = try buildSystem.binPath(\n            for: .debug,\n            triple: hostTriple,\n        )\n        // By default, plugin dependencies are built for the host platform\n        try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n            let hostBinPath: AbsolutePath = fixturePath.appending(components: hostBinPathSegments)\n            let hostDebugBinPath: AbsolutePath = fixturePath.appending(components: hostDebugBinPathSegments)\n            let (stdout, stderr) = try await executeSwiftPackage(\n                fixturePath,\n                configuration: config,\n                extraArgs: [\"-v\", \"build-plugin-dependency\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Hello from dependencies-stub\"))\n            if buildSystem == .native {\n                #expect(stderr.contains(\"Build of product 'plugintool' complete!\"))\n            }\n            let pluginToolName: String\n            switch buildSystem {\n                case .native:\n                pluginToolName = \"plugintool-tool\"\n                case .swiftbuild:\n                pluginToolName = \"plugintool\"\n                case .xcode:\n                pluginToolName = \"\"\n                Issue.record(\"Test has not been updated for this build system\")\n            }\n            expectFileExists(at: hostBinPath.appending(pluginToolName))\n            expectFileExists(at: hostDebugBinPath.appending(\"placeholder\"))\n        }\n    }\n\n    @Test(\n        .serialized,\n        .tags(\n            .Feature.Command.Package.CommandPlugin,\n        ),\n        .requireHostOS(.macOS),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandPluginDependenciesWhenCrossCompiling(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        let hostToolchain = try UserToolchain(\n            swiftSDK: .hostSwiftSDK(environment: [:]),\n            environment: [:]\n        )\n        // let hostTriple = try! hostToolchain.targetTriple.withoutVersion().tripleString\n\n        let x86Triple = \"x86_64-apple-macosx\"\n        let armTriple = \"arm64-apple-macosx\"\n        let targetTriple = hostToolchain.targetTriple.arch == .aarch64 ? x86Triple : armTriple\n\n        let hostBinPathSegments = try buildSystem.binPath(\n            for: config,\n        )\n        let targetDebugBinPathSegments = try buildSystem.binPath(\n            for: .debug,\n            triple: targetTriple,\n        )\n\n        // When cross compiling the final product, plugin dependencies should still be built for the host\n        try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n            // let hostBinPath: AbsolutePath = fixturePath.appending(components: hostBinPathSegments)\n            let targetDebugBinPath: AbsolutePath = fixturePath.appending(components: targetDebugBinPathSegments)\n            let hostBinPath = try fixturePath.appending(\n                components: buildSystem.binPath(\n                    for: config,\n                )\n            )\n            let targetBinPath = try fixturePath.appending(\n                components: buildSystem.binPath(\n                    for: config,\n                    triple: targetTriple,\n                )\n            )\n            let (stdout, stderr) = try await executeSwiftPackage(\n                fixturePath,\n                configuration: config,\n                extraArgs: [\"-v\", \"--triple\", targetTriple, \"build-plugin-dependency\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Hello from dependencies-stub\"))\n            if buildSystem == .native {\n                #expect(stderr.contains(\"Build of product 'plugintool' complete!\"))\n            }\n            let pluginToolName: String\n            let pluginToolBinPath: AbsolutePath\n            switch buildSystem {\n                case .native:\n                pluginToolName = \"plugintool-tool\"\n                pluginToolBinPath = hostBinPath\n                case .swiftbuild:\n                pluginToolName = \"plugintool\"\n                pluginToolBinPath = targetBinPath\n                case .xcode:\n                pluginToolName = \"\"\n                pluginToolBinPath = AbsolutePath(\"/\")\n                Issue.record(\"Test has not been updated for this build system\")\n            }\n\n            expectFileExists(at: targetDebugBinPath.appending(\"placeholder\"))\n            expectFileExists(at: pluginToolBinPath.appending(pluginToolName))\n        }\n    }\n\n}\n"
  },
  {
    "path": "Tests/BuildTests/PrebuiltsBuildPlanTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\nimport Basics\nimport PackageLoading\nimport _InternalBuildTestSupport\nimport Build\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\n@testable import PackageGraph\n\n@_spi(SwiftPMInternal)\n@testable import PackageModel\n\nclass PrebuiltsBuildPlanTests: XCTestCase {\n    func testPrebuiltsFlags() async throws {\n        // Make sure the include path for the prebuilts get passed to the\n        // generated test entry point and discover targets on Linux/Windows\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let prebuiltLibrary = PrebuiltLibrary(\n            identity: .plain(\"swift-syntax\"),\n            libraryName: \"MacroSupport\",\n            path: \"/MyPackage/.build/prebuilts/swift-syntax/600.0.1/6.1-MacroSupport-macos_aarch64\",\n            checkoutPath: \"/MyPackage/.build/checkouts/swift-syntax\",\n            products: [\n                \"SwiftBasicFormat\",\n                \"SwiftCompilerPlugin\",\n                \"SwiftDiagnostics\",\n                \"SwiftIDEUtils\",\n                \"SwiftOperators\",\n                \"SwiftParser\",\n                \"SwiftParserDiagnostics\",\n                \"SwiftRefactor\",\n                \"SwiftSyntax\",\n                \"SwiftSyntaxBuilder\",\n                \"SwiftSyntaxMacros\",\n                \"SwiftSyntaxMacroExpansion\",\n                \"SwiftSyntaxMacrosTestSupport\",\n                \"SwiftSyntaxMacrosGenericTestSupport\",\n                \"_SwiftCompilerPluginMessageHandling\",\n                \"_SwiftLibraryPluginProvider\"\n            ],\n            cModules: [\"_SwiftSyntaxCShims\"]\n        )\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPackage/Sources/MyMacroMacros/MyMacroMacros.swift\",\n                \"/MyPackage/Sources/MyMacros/MyMacros.swift\",\n                \"/MyPackage/Sources/MyMacroTests/MyMacroTests.swift\",\n                \"/swift-syntax/Sources/SwiftSyntaxMacros/SwiftSyntaxMacros.swift\",\n                \"/swift-syntax/Sources/SwiftSyntaxMacrosTestSupport/SwiftSyntaxMacrosTestSupport.swift\",\n                \"/swift-syntax/Sources/SwiftCompilerPlugin/SwiftCompilerPlugin.swift\",\n            ]\n        )\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"MyPackage\",\n                    path: \"/MyPackage\",\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://github.com/swiftlang/swift-syntax\", requirement: .exact(\"600.0.1\")),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MyMacros\",\n                            type: .library(.automatic),\n                            targets: [\"MyMacros\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"MyMacroMacros\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\"),\n                            ],\n                            type: .macro),\n                        TargetDescription(\n                            name: \"MyMacros\",\n                            dependencies: [\n                                \"MyMacroMacros\",\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"MyMacroTests\",\n                            dependencies: [\n                                \"MyMacroMacros\",\n                                .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n                            ],\n                            type: .test\n                        )\n                    ]\n                ),\n                Manifest.createRemoteSourceControlManifest(\n                    displayName: \"swift-syntax\",\n                    url: \"https://github.com/swiftlang/swift-syntax\",\n                    path: \"/swift-syntax\",\n                    products: [\n                        ProductDescription(\n                            name: \"SwiftSyntaxMacros\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftSyntaxMacros\"]\n                        ),\n                        ProductDescription(\n                            name: \"SwiftSyntaxMacrosTestSupport\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftSyntaxMacrosTestSupport\"]\n                        ),\n                        ProductDescription(\n                            name: \"SwiftCompilerPlugin\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftCompilerPlugin\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"SwiftSyntaxMacros\"),\n                        TargetDescription(name: \"SwiftSyntaxMacrosTestSupport\"),\n                        TargetDescription(name: \"SwiftCompilerPlugin\"),\n                    ]\n                )\n            ],\n            prebuilts: [prebuiltLibrary.identity: prebuiltLibrary.products.reduce(into: [:]) {\n                $0[$1] = prebuiltLibrary\n            }],\n            observabilityScope: observability.topScope\n        )\n\n        func checkTriple(triple: Basics.Triple) async throws {\n            let result = try await BuildPlanResult(\n                plan: mockBuildPlan(\n                    triple: triple,\n                    graph: graph,\n                    fileSystem: fs,\n                    observabilityScope: observability.topScope\n                )\n            )\n\n#if os(Windows)\n            let modulesDir = \"\\(prebuiltLibrary.path.pathString)\\\\Modules\"\n#else\n            let modulesDir = \"\\(prebuiltLibrary.path.pathString)/Modules\"\n#endif\n            let mytest = try XCTUnwrap(result.allTargets(named: \"MyMacroTests\").first)\n            XCTAssert(try mytest.swift().compileArguments().contains(modulesDir))\n            let entryPoint = try XCTUnwrap(result.allTargets(named: \"MyPackagePackageTests\").first)\n            XCTAssert(try entryPoint.swift().compileArguments().contains(modulesDir))\n            let discovery = try XCTUnwrap(result.allTargets(named: \"MyPackagePackageDiscoveredTests\").first)\n            XCTAssert(try discovery.swift().compileArguments().contains(modulesDir))\n        }\n\n        try await checkTriple(triple: .x86_64Linux)\n        try await checkTriple(triple: .x86_64Windows)\n    }\n\n    // The prebuilts used for the rest of these tests\n    let prebuiltLibrary = PrebuiltLibrary(\n        identity: .plain(\"swift-syntax\"),\n        libraryName: \"MacroSupport\",\n        path: \"/MyPackage/.build/prebuilts/swift-syntax/600.0.1/6.1-MacroSupport-macos_aarch64\",\n        checkoutPath: \"/MyPackage/.build/checkouts/swift-syntax\",\n        products: [\n            \"SwiftBasicFormat\",\n            \"SwiftCompilerPlugin\",\n            \"SwiftDiagnostics\",\n            \"SwiftIDEUtils\",\n            \"SwiftOperators\",\n            \"SwiftParser\",\n            \"SwiftParserDiagnostics\",\n            \"SwiftRefactor\",\n            \"SwiftSyntax\",\n            \"SwiftSyntaxBuilder\",\n            \"SwiftSyntaxMacros\",\n            \"SwiftSyntaxMacroExpansion\",\n            \"SwiftSyntaxMacrosTestSupport\",\n            \"SwiftSyntaxMacrosGenericTestSupport\",\n            \"_SwiftCompilerPluginMessageHandling\",\n            \"_SwiftLibraryPluginProvider\"\n        ],\n        includePath: [\n            \"Sources/_SwiftSyntaxCShims/include\"\n        ]\n    )\n\n    // Make sure the include path for the prebuilts get passed to the\n    // generated test entry point and discover targets on Linux/Windows\n    func testPrebuiltsWithIncludePath() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPackage/Sources/MyMacroLibrary/MyMacroLibrary.swift\",\n                \"/MyPackage/Sources/MyMacroMacros/MyMacroMacros.swift\",\n                \"/MyPackage/Sources/MyMacros/MyMacros.swift\",\n                \"/MyPackage/Sources/MyMacroTests/MyMacroTests.swift\",\n                \"/swift-syntax/Sources/SwiftSyntaxMacros/SwiftSyntaxMacros.swift\",\n                \"/swift-syntax/Sources/SwiftSyntaxMacrosTestSupport/SwiftSyntaxMacrosTestSupport.swift\",\n                \"/swift-syntax/Sources/SwiftCompilerPlugin/SwiftCompilerPlugin.swift\",\n            ]\n        )\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"MyPackage\",\n                    path: \"/MyPackage\",\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://github.com/swiftlang/swift-syntax\", requirement: .exact(\"600.0.1\")),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MyMacros\",\n                            type: .library(.automatic),\n                            targets: [\"MyMacros\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"MyMacroLibrary\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"MyMacroMacros\",\n                            dependencies: [\n                                \"MyMacroLibrary\",\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\"),\n                            ],\n                            type: .macro,\n                        ),\n                        TargetDescription(\n                            name: \"MyMacros\",\n                            dependencies: [\n                                \"MyMacroMacros\",\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"MyMacroTests\",\n                            dependencies: [\n                                \"MyMacroMacros\",\n                                .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n                            ],\n                            type: .test\n                        )\n                    ]\n                ),\n                Manifest.createRemoteSourceControlManifest(\n                    displayName: \"swift-syntax\",\n                    url: \"https://github.com/swiftlang/swift-syntax\",\n                    path: \"/swift-syntax\",\n                    products: [\n                        ProductDescription(\n                            name: \"SwiftSyntaxMacros\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftSyntaxMacros\"]\n                        ),\n                        ProductDescription(\n                            name: \"SwiftSyntaxMacrosTestSupport\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftSyntaxMacrosTestSupport\"]\n                        ),\n                        ProductDescription(\n                            name: \"SwiftCompilerPlugin\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftCompilerPlugin\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"SwiftSyntaxMacros\"),\n                        TargetDescription(name: \"SwiftSyntaxMacrosTestSupport\"),\n                        TargetDescription(name: \"SwiftCompilerPlugin\"),\n                    ]\n                )\n            ],\n            prebuilts: [prebuiltLibrary.identity: prebuiltLibrary.products.reduce(into: [:]) {\n                $0[$1] = prebuiltLibrary\n            }],\n            observabilityScope: observability.topScope\n        )\n\n        func checkTriple(triple: Basics.Triple) async throws {\n            let result = try await BuildPlanResult(\n                plan: mockBuildPlan(\n                    triple: triple,\n                    graph: graph,\n                    fileSystem: fs,\n                    observabilityScope: observability.topScope\n                )\n            )\n\n            let modulesDir = prebuiltLibrary.path.appending(component: \"Modules\").pathString\n            let checkoutPath = try XCTUnwrap(prebuiltLibrary.checkoutPath)\n            let includeDir = try XCTUnwrap(prebuiltLibrary.includePath)[0]\n            let includePath = checkoutPath.appending(includeDir).pathString\n\n            let mytest = try XCTUnwrap(result.allTargets(named: \"MyMacroTests\").first)\n            XCTAssert(try mytest.swift().compileArguments().contains(modulesDir))\n            let entryPoint = try XCTUnwrap(result.allTargets(named: \"MyPackagePackageTests\").first)\n            XCTAssert(try entryPoint.swift().compileArguments().contains(modulesDir))\n            let discovery = try XCTUnwrap(result.allTargets(named: \"MyPackagePackageDiscoveredTests\").first)\n            XCTAssert(try discovery.swift().compileArguments().contains(modulesDir))\n\n            let mymacro = try XCTUnwrap(result.allTargets(named: \"MyMacroMacros\").first)\n            XCTAssert(try mymacro.swift().compileArguments().contains(modulesDir))\n            XCTAssert(try mymacro.swift().compileArguments().contains(includePath))\n        }\n\n        try await checkTriple(triple: .x86_64Linux)\n        try await checkTriple(triple: .x86_64Windows)\n    }\n\n    // Make sure the prebuilt settings are imparted up the build graph to the executables.\n    // Include skipping over a library that doesn't use prebuilts.\n    func testIndirectLibrary() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPackage/Sources/Base/Base.swift\",\n                \"/MyPackage/Sources/Intermediate/Intermediate.swift\",\n                \"/MyPackage/Sources/Macros/Macros.swift\",\n                \"/MyPackage/Sources/MacroLib/MacroLib.swift\",\n                \"/MyPackage/Sources/Generator/Generator.swift\",\n                \"/MyPackage/Plugins/Plugin/Plugin.swift\",\n                \"/MyRoot/Sources/MyApp/MyApp.swift\",\n                \"/swift-syntax/Sources/SwiftSyntaxMacros/SwiftSyntaxMacros.swift\",\n            ]\n        )\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"MyRoot\",\n                    path: \"/MyRoot\",\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://github.com/swiftlang/swift-syntax\", requirement: .exact(\"600.0.1\")),\n                        .fileSystem(path: \"/MyPackage\"),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MyApp\",\n                            type: .executable,\n                            targets: [\"MyApp\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"MyApp\",\n                            dependencies: [\n                                .product(name: \"MacroLib\", package: \"MyPackage\"),\n                            ],\n                            type: .executable\n                        ),\n                    ],\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"MyPackage\",\n                    path: \"/MyPackage\",\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://github.com/swiftlang/swift-syntax\", requirement: .exact(\"600.0.1\")),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MacroLib\",\n                            type: .library(.automatic),\n                            targets: [\n                                \"MacroLib\"\n                            ]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Base\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Intermediate\",\n                            dependencies: [\n                                \"Base\"\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Macros\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                \"Intermediate\",\n                            ],\n                            type: .macro\n                        ),\n                        TargetDescription(\n                            name: \"MacroLib\",\n                            dependencies: [\n                                \"Macros\"\n                            ]\n                        ),\n                    ],\n                ),\n                Manifest.createRemoteSourceControlManifest(\n                    displayName: \"swift-syntax\",\n                    url: \"https://github.com/swiftlang/swift-syntax\",\n                    path: \"/swift-syntax\",\n                    products: [\n                        ProductDescription(\n                            name: \"SwiftSyntaxMacros\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftSyntaxMacros\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(name: \"SwiftSyntaxMacros\")\n                    ]\n                )\n            ],\n            prebuilts: [prebuiltLibrary.identity: prebuiltLibrary.products.reduce(into: [:]) {\n                $0[$1] = prebuiltLibrary\n            }],\n            observabilityScope: observability.topScope\n        )\n\n        let result = try await BuildPlanResult(\n            plan: mockBuildPlan(\n                triple: .arm64MacOS,\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n        )\n\n        // Make sure everyone has the modules dir that needs it and those that don't don't\n        let modulesDir = prebuiltLibrary.path.appending(component: \"Modules\").pathString\n        let libDir = prebuiltLibrary.path.appending(component: \"lib\").pathString\n        let lib = \"-l\\(prebuiltLibrary.libraryName)\"\n\n        let Base = try XCTUnwrap(result.targetMap.filter({ $0.module.name == \"Base\" }).only)\n        XCTAssertEqual(Base.buildParameters.destination, .host)\n        XCTAssert(try Base.swift().compileArguments().contains(modulesDir))\n\n        let Intermediate = try XCTUnwrap(result.targetMap.filter({ $0.module.name == \"Intermediate\" }).only)\n        XCTAssertEqual(Intermediate.buildParameters.destination, .host)\n        XCTAssert(try Intermediate.swift().compileArguments().contains(modulesDir))\n\n        let Macros = try XCTUnwrap(result.targetMap.filter({ $0.module.name == \"Macros\" }).only)\n        XCTAssertEqual(Macros.buildParameters.destination, .host)\n        XCTAssert(try Macros.swift().compileArguments().contains(modulesDir))\n\n        let MacrosExe = try XCTUnwrap(result.productMap.filter({ $0.product.name == \"Macros\" }).only)\n        XCTAssertEqual(MacrosExe.destination, .host)\n        let MacrosExeLinkArgs = try MacrosExe.linkArguments()\n        XCTAssert(MacrosExeLinkArgs.contains(libDir))\n        XCTAssert(MacrosExeLinkArgs.contains(lib))\n\n        // The MacroLib is target only\n        let MacroLib = try XCTUnwrap(result.targetMap.filter({ $0.module.name == \"MacroLib\" }).only)\n        XCTAssertEqual(MacroLib.buildParameters.destination, .target)\n        XCTAssert(try !MacroLib.swift().compileArguments().contains(modulesDir))\n    }\n\n    // Test that a prebuilt leaking out the root package's products disables them all\n    func testIndirectLibraryLeak() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPackage/Sources/Base/Base.swift\",\n                \"/MyPackage/Sources/Intermediate/Intermediate.swift\",\n                \"/MyPackage/Sources/Macros/Macros.swift\",\n                \"/MyPackage/Sources/MacroLib/MacroLib.swift\",\n                \"/MyPackage/Sources/Generator/Generator.swift\",\n                \"/MyPackage/Plugins/Plugin/Plugin.swift\",\n                \"/MyRoot/Sources/MyApp/MyApp.swift\",\n                \"/MyRoot/Sources/LeakyLib/LeakyLib.swift\",\n                \"/swift-syntax/Sources/SwiftSyntaxMacros/SwiftSyntaxMacros.swift\",\n            ]\n        )\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"MyRoot\",\n                    path: \"/MyRoot\",\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://github.com/swiftlang/swift-syntax\", requirement: .exact(\"600.0.1\")),\n                        .fileSystem(path: \"/MyPackage\"),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MyApp\",\n                            type: .executable,\n                            targets: [\"MyApp\"]\n                        ),\n                        ProductDescription(\n                            name: \"LeakyLib\",\n                            type: .library(.automatic),\n                            targets: [\"LeakyLib\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"MyApp\",\n                            dependencies: [\n                                .product(name: \"MacroLib\", package: \"MyPackage\"),\n                            ],\n                            type: .executable,\n                            pluginUsages: [\n                                .plugin(name: \"Plugin\", package: \"MyPackage\")\n                            ],\n                        ),\n                        TargetDescription(\n                            name: \"LeakyLib\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                            ]\n                        )\n                    ],\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"MyPackage\",\n                    path: \"/MyPackage\",\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://github.com/swiftlang/swift-syntax\", requirement: .exact(\"600.0.1\")),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MacroLib\",\n                            type: .library(.automatic),\n                            targets: [\n                                \"MacroLib\"\n                            ]\n                        ),\n                        ProductDescription(\n                            name: \"Plugin\",\n                            type: .plugin,\n                            targets: [\n                                \"Plugin\"\n                            ]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Base\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Intermediate\",\n                            dependencies: [\n                                \"Base\"\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Macros\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                \"Intermediate\",\n                            ],\n                            type: .macro\n                        ),\n                        TargetDescription(\n                            name: \"MacroLib\",\n                            dependencies: [\n                                \"Macros\"\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Generator\",\n                            dependencies: [\n                                \"Base\"\n                            ],\n                            type: .executable\n                        ),\n                        TargetDescription(\n                            name: \"Plugin\",\n                            dependencies: [\n                                \"Generator\"\n                            ],\n                            type: .plugin,\n                            pluginCapability: .buildTool\n                        ),\n                    ],\n                ),\n                Manifest.createRemoteSourceControlManifest(\n                    displayName: \"swift-syntax\",\n                    url: \"https://github.com/swiftlang/swift-syntax\",\n                    path: \"/swift-syntax\",\n                    products: [\n                        ProductDescription(\n                            name: \"SwiftSyntaxMacros\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftSyntaxMacros\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(name: \"SwiftSyntaxMacros\")\n                    ]\n                )\n            ],\n            prebuilts: [prebuiltLibrary.identity: prebuiltLibrary.products.reduce(into: [:]) {\n                $0[$1] = prebuiltLibrary\n            }],\n            observabilityScope: observability.topScope\n        )\n\n        let result = try await BuildPlanResult(\n            plan: mockBuildPlan(\n                triple: .arm64MacOS,\n                graph: graph,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n        )\n\n        // Make sure nothing is using the prebuilts\n        let modulesDir = prebuiltLibrary.path.appending(component: \"Modules\").pathString\n        let libDir = prebuiltLibrary.path.appending(component: \"lib\").pathString\n        let lib = \"-l\\(prebuiltLibrary.libraryName)\"\n\n        for target in result.targetMap {\n            XCTAssert(try !target.swift().compileArguments().contains(modulesDir))\n        }\n\n        for product in result.productMap {\n            let linkArgs = try product.linkArguments()\n            XCTAssert(!linkArgs.contains(libDir))\n            XCTAssert(!linkArgs.contains(lib))\n        }\n\n        let prebuiltUsers = Set([\n            \"LeakyLib\",\n            \"Base\",\n            \"Macros\"\n        ])\n        for target in result.targetMap where prebuiltUsers.contains(target.module.name) {\n            XCTAssert(target.module.dependencies.contains(where: { $0.product?.packageIdentity == .plain(\"swift-syntax\") }))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/PrepareForIndexTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2015-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Build\nimport Foundation\n@testable import Commands\n@testable import CoreCommands\nimport LLBuildManifest\nimport _InternalTestSupport\nimport TSCBasic\nimport XCTest\nimport class Basics.ObservabilitySystem\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport func PackageGraph.loadModulesGraph\nimport class PackageModel.Manifest\nimport struct PackageGraph.ModulesGraph\nimport struct PackageModel.TargetDescription\n\nclass PrepareForIndexTests: XCTestCase {\n    func testPrepare() async throws {\n        try XCTSkipOnWindows(because: \"coreCommands.count = 0 instead of 1. Possibly related to https://github.com/swiftlang/swift-package-manager/issues/8511\")\n\n        let (graph, fs, scope) = try macrosPackageGraph()\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(destination: .target, prepareForIndexing: .on),\n            toolsBuildParameters: mockBuildParameters(destination: .host, prepareForIndexing: .off),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        let builder = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: scope)\n        let manifest = try builder.generateManifest(at: \"/manifest\")\n\n        // Make sure we're building the swift modules\n        let outputs = manifest.commands.flatMap(\\.value.tool.outputs).map(\\.name)\n        XCTAssertTrue(outputs.contains(where: { $0.hasSuffix(\".swiftmodule\") }))\n\n        // Ensure swiftmodules built with correct arguments\n        let coreCommands = manifest.commands.values.filter {\n            $0.tool.outputs.contains(where: {\n                $0.name.hasSuffix(\"debug/Core.build/Core.swiftmodule\")\n            })\n        }\n        XCTAssertEqual(coreCommands.count, 1)\n        let coreSwiftc = try XCTUnwrap(coreCommands.first?.tool as? SwiftCompilerTool)\n        XCTAssertTrue(coreSwiftc.otherArguments.contains(\"-experimental-skip-all-function-bodies\"))\n\n        // Ensure tools are built normally\n        let toolCommands = manifest.commands.values.filter {\n            $0.tool.outputs.contains(where: {\n                $0.name.hasSuffix(\"debug/Modules-tool/SwiftSyntax.swiftmodule\")\n            })\n        }\n        XCTAssertEqual(toolCommands.count, 1)\n        let toolSwiftc = try XCTUnwrap(toolCommands.first?.tool as? SwiftCompilerTool)\n        XCTAssertFalse(toolSwiftc.otherArguments.contains(\"-experimental-skip-all-function-bodies\"))\n        XCTAssertTrue(toolSwiftc.outputs.contains(where: {\n            $0.name.hasSuffix(\".swift.o\")\n        }))\n\n        // Make sure only object files for tools are built\n        XCTAssertTrue(\n            outputs.filter { $0.hasSuffix(\".o\") }.allSatisfy { $0.contains(\"-tool.build/\") },\n            \"outputs:\\n\\t\\(outputs.filter { $0.hasSuffix(\".o\") }.joined(separator: \"\\n\\t\"))\"\n        )\n    }\n\n    func testCModuleTarget() async throws {\n        let (graph, fs, scope) = try trivialPackageGraph()\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(destination: .target, prepareForIndexing: .on),\n            toolsBuildParameters: mockBuildParameters(destination: .host, prepareForIndexing: .off),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n        let builder = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: scope)\n        let manifest = try builder.generateManifest(at: \"/manifest\")\n\n        // Ensure our C module is here.\n        let lib = try XCTUnwrap(graph.module(for: \"lib\"))\n        let name = lib.getLLBuildTargetName(buildParameters: plan.destinationBuildParameters)\n        XCTAssertTrue(manifest.targets.keys.contains(name))\n    }\n\n    func testEnableTestingSetup() throws-> (fs: InMemoryFileSystem, observability: TestingObservability, graph: ModulesGraph) {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/lib/lib.swift\",\n            \"/Pkg/Tests/test/TestCase.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"lib\", dependencies: []),\n                        TargetDescription(name: \"test\", dependencies: [\"lib\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        return (fs, observability, graph)\n    }\n\n    func testEnableTestingDebugConfiguration() async throws {\n        // enable-testing requires the non-exportable-decls, make sure they aren't skipped.\n        let (fs, observability, graph) = try self.testEnableTestingSetup()\n        let scope = observability.topScope\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        // Under debug, enable-testing is turned on by default. Make sure the flag is not added.\n        let debugPlan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(destination: .target, config: .debug, prepareForIndexing: .on),\n            toolsBuildParameters: mockBuildParameters(destination: .host, prepareForIndexing: .off),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let debugBuilder = LLBuildManifestBuilder(debugPlan, fileSystem: fs, observabilityScope: scope)\n        let debugManifest = try debugBuilder.generateManifest(at: \"/manifest\")\n\n        XCTAssertNil(debugManifest.commands.values.first(where: {\n            guard let swiftCommand = $0.tool as? SwiftCompilerTool,\n                swiftCommand.outputs.contains(where: { $0.name.hasSuffix(\"/lib.swiftmodule\")})\n            else {\n                return false\n            }\n            return swiftCommand.otherArguments.contains(\"-experimental-skip-non-exportable-decls\")\n                && !swiftCommand.otherArguments.contains(\"-enable-testing\")\n        }))\n    }\n\n    func testEnableTestingReleaseConfiguration() async throws {\n        try XCTSkipOnWindows(because: \"\"\"\n            Assertion failure.  (\"0\") is not equal to (\"1\"). Possibly related to https://github.com/swiftlang/swift-package-manager/issues/8511\n        \"\"\")\n\n        let (fs, observability, graph) = try self.testEnableTestingSetup()\n        let scope = observability.topScope\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        // Under release, enable-testing is turned off by default so we should see our flag\n        let releasePlan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(destination: .target, config: .release, prepareForIndexing: .on),\n            toolsBuildParameters: mockBuildParameters(destination: .host, prepareForIndexing: .off),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let releaseBuilder = LLBuildManifestBuilder(releasePlan, fileSystem: fs, observabilityScope: scope)\n        let releaseManifest = try releaseBuilder.generateManifest(at: \"/manifest\")\n\n        XCTAssertEqual(releaseManifest.commands.values.filter({\n            guard let swiftCommand = $0.tool as? SwiftCompilerTool,\n                swiftCommand.outputs.contains(where: { $0.name.hasSuffix(\"/lib.swiftmodule\")})\n            else {\n                return false\n            }\n            return swiftCommand.otherArguments.contains(\"-experimental-skip-non-exportable-decls\")\n                && !swiftCommand.otherArguments.contains(\"-enable-testing\")\n        }).count, 1)\n    }\n\n    func testPrepareNoLazy() async throws {\n        try XCTSkipOnWindows(because: \"coreCommands.count = 0 instead of 1. Possibly related to https://github.com/swiftlang/swift-package-manager/issues/8511\")\n\n        let (graph, fs, scope) = try macrosPackageGraph()\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(destination: .target, prepareForIndexing: .noLazy),\n            toolsBuildParameters: mockBuildParameters(destination: .host, prepareForIndexing: .off),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: scope\n        )\n\n        let builder = LLBuildManifestBuilder(plan, fileSystem: fs, observabilityScope: scope)\n        let manifest = try builder.generateManifest(at: \"/manifest\")\n\n        // Ensure swiftmodules built with correct arguments\n        let coreCommands = manifest.commands.values.filter {\n            $0.tool.outputs.contains(where: {\n                $0.name.hasSuffix(\"debug/Core.build/Core.swiftmodule\")\n            })\n        }\n        XCTAssertEqual(coreCommands.count, 1)\n        let coreSwiftc = try XCTUnwrap(coreCommands.first?.tool as? SwiftCompilerTool)\n        XCTAssertFalse(coreSwiftc.otherArguments.contains(\"-experimental-lazy-typecheck\"))\n        XCTAssertTrue(coreSwiftc.otherArguments.contains(\"-experimental-allow-module-with-compiler-errors\"))\n    }\n\n    func testToolsDontPrepare() throws {\n        let options = try GlobalOptions.parse([\"--experimental-prepare-for-indexing\"])\n        let state = try SwiftCommandState(\n            outputStream: stderrStream,\n            options: options,\n            toolWorkspaceConfiguration: .init(shouldInstallSignalHandlers: false),\n            workspaceDelegateProvider: {\n                CommandWorkspaceDelegate(\n                    observabilityScope: $0,\n                    outputHandler: $1,\n                    progressHandler: $2,\n                    inputHandler: $3\n                )\n            },\n            workspaceLoaderProvider: {\n                XcodeWorkspaceLoader(\n                    fileSystem: $0,\n                    observabilityScope: $1\n                )\n            },\n            createPackagePath: false,\n            hostTriple: .arm64Linux,\n            fileSystem: localFileSystem,\n            environment: .current\n        )\n\n        XCTAssertEqual(try state.productsBuildParameters.prepareForIndexing, .on)\n        // Tools builds should never do prepare for indexing since they're needed\n        // for the prepare builds.\n        XCTAssertEqual(try state.toolsBuildParameters.prepareForIndexing, .off)\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/ProductBuildDescriptionTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable\nimport Build\n\nimport class Basics.InMemoryFileSystem\nimport class Basics.ObservabilitySystem\n\nimport class PackageModel.Manifest\nimport struct PackageModel.TargetDescription\n\n@testable\nimport struct PackageGraph.ResolvedProduct\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport func PackageGraph.loadModulesGraph\n\nimport func _InternalTestSupport.mockBuildParameters\nimport func _InternalTestSupport.XCTAssertNoDiagnostics\nimport XCTest\n\nfinal class ProductBuildDescriptionTests: XCTestCase {\n    func testEmbeddedProducts() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            settings: [.init(tool: .swift, kind: .enableExperimentalFeature(\"Embedded\"))]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let id = ResolvedProduct.ID(productName: \"exe\", packageIdentity: .plain(\"pkg\"))\n        let package = try XCTUnwrap(graph.rootPackages.first)\n        let product = try XCTUnwrap(graph.allProducts[id])\n\n        let buildDescription = try ProductBuildDescription(\n            package: package,\n            product: product,\n            toolsVersion: .v5_9,\n            buildParameters: mockBuildParameters(destination: .target, environment: .init(platform: .macOS)),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertTrue(\n            try buildDescription.linkArguments()\n                .joined(separator: \" \")\n                .contains(\"-enable-experimental-feature Embedded\")\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/SwiftCompilerOutputParserTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Testing\nimport Build\n\nstruct SwiftCompilerOutputParserTests {\n    @Test\n    func parse() throws {\n        let delegate = MockSwiftCompilerOutputParserDelegate()\n        let parser = SwiftCompilerOutputParser(targetName: \"dummy\", delegate: delegate)\n\n        parser.parse(bytes: \"\"\"\n            338\n            {\n              \"kind\": \"began\",\n              \"name\": \"compile\",\n              \"inputs\": [\n                \"test.swift\"\n              ],\n              \"outputs\": [\n                {\n                  \"type\": \"object\",\n                  \"path\": \"/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test-77d991.o\"\n                }\n              ],\n              \"pid\": 22698,\n              \"command_executable\": \"swift\",\n              \"command_arguments\" : [\"-frontend\", \"-c\", \"-primary-file\", \"test.swift\"]\n            }\n            117\n            {\n              \"kind\": \"finished\",\n              \"name\": \"compile\",\n              \"pid\": 22698,\n              \"exit-status\": 1,\n              \"output\": \"error: it failed :-(\"\n            }\n            233\n            {\n              \"kind\": \"skipped\",\n              \"name\": \"compile\",\n              \"inputs\": [\n                \"test2.swift\"\n              ],\n              \"outputs\": [\n                {\n                  \"type\": \"object\",\n                  \"path\": \"/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test2-77d991.o\"\n                }\n              ],\n              \"pid\": 58776\n            }\n            250\n            {\n              \"kind\": \"began\",\n              \"name\": \"verify-module-interface\",\n              \"inputs\": [\n                \"main.swiftinterface\"\n              ],\n              \"pid\": 31337,\n              \"command_executable\": \"swift\",\n              \"command_arguments\" : [\"-frontend\", \"-typecheck-module-from-interface\", \"main.swiftinterface\"]\n            }\n            299\n            {\n              \"kind\": \"began\",\n              \"name\": \"link\",\n              \"inputs\": [\n                \"/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test-77d991.o\"\n              ],\n              \"outputs\": [\n                {\n                  \"type\": \"image\",\n                  \"path\": \"test\"\n                }\n              ],\n              \"pid\": 22699,\n              \"command_executable\": \"ld\",\n              \"command_arguments\" : [\"-o\", \"option\", \"test\"]\n            }\n            119\n            {\n              \"kind\": \"signalled\",\n              \"name\": \"link\",\n              \"pid\": 22699,\n              \"error-message\": \"Segmentation fault: 11\",\n              \"signal\": 4\n            }\n\n            \"\"\".utf8)\n\n        delegate.assert(messages: [\n            SwiftCompilerMessage(\n                name: \"compile\",\n                kind: .began(.init(\n                    pid: 22698,\n                    inputs: [\"test.swift\"],\n                    outputs: [.init(\n                        type: \"object\",\n                        path: \"/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test-77d991.o\")],\n                    commandExecutable: \"swift\",\n                    commandArguments: [\"-frontend\", \"-c\", \"-primary-file\", \"test.swift\"]))),\n            SwiftCompilerMessage(\n                name: \"compile\",\n                kind: .finished(.init(\n                    pid: 22698,\n                    output: \"error: it failed :-(\"))),\n            SwiftCompilerMessage(\n                name: \"compile\",\n                kind: .skipped(.init(\n                    inputs: [\"test2.swift\"],\n                    outputs: [.init(\n                        type: \"object\",\n                        path: \"/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test2-77d991.o\")]))),\n            SwiftCompilerMessage(\n                name: \"verify-module-interface\",\n                kind: .began(.init(\n                    pid: 31337,\n                    inputs: [\"main.swiftinterface\"],\n                    outputs: nil,\n                    commandExecutable: \"swift\",\n                    commandArguments: [\"-frontend\", \"-typecheck-module-from-interface\", \"main.swiftinterface\"]))),\n            SwiftCompilerMessage(\n                name: \"link\",\n                kind: .began(.init(\n                    pid: 22699,\n                    inputs: [\"/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test-77d991.o\"],\n                    outputs: [.init(\n                        type: \"image\",\n                        path: \"test\")],\n                    commandExecutable: \"ld\",\n                    commandArguments: [\"-o\", \"option\", \"test\"]))),\n            SwiftCompilerMessage(\n                name: \"link\",\n                kind: .signalled(.init(\n                    pid: 22699,\n                    output: nil)))\n        ], errorDescription: nil)\n    }\n\n    @Test\n    func rawTextTransformsIntoUnknown() {\n        let delegate = MockSwiftCompilerOutputParserDelegate()\n        let parser = SwiftCompilerOutputParser(targetName: \"dummy\", delegate: delegate)\n\n        parser.parse(bytes: \"\"\"\n            2A\n\n            \"\"\".utf8)\n        delegate.assert(messages: [\n            SwiftCompilerMessage(name: \"unknown\", kind: .unparsableOutput(\"2A\\n\"))\n        ], errorDescription: nil)\n\n        parser.parse(bytes: \"\"\"\n            119\n            {\n              \"kind\": \"signalled\",\n              \"name\": \"link\",\n              \"pid\": 22699,\n              \"error-message\": \"Segmentation fault: 11\",\n              \"signal\": 4\n            }\n            \"\"\".utf8)\n        delegate.assert(messages: [\n            SwiftCompilerMessage(name: \"link\", kind: .signalled(.init(pid: 22699, output: nil)))\n        ], errorDescription: nil)\n    }\n\n    @Test\n    func signalledStopsParsing() {\n        let delegate = MockSwiftCompilerOutputParserDelegate()\n        let parser = SwiftCompilerOutputParser(targetName: \"dummy\", delegate: delegate)\n\n        parser.parse(bytes: \"\"\"\n            119\n            {\n              \"kind\": \"signalled\",\n              \"name\": \"link\",\n              \"pid\": 22699,\n              \"error-message\": \"Segmentation fault: 11\",\n              \"signal\": 4\n            }\n            \"\"\".utf8)\n        delegate.assert(messages: [\n            SwiftCompilerMessage(name: \"link\", kind: .signalled(.init(pid: 22699, output: nil)))\n        ], errorDescription: nil)\n\n        parser.parse(bytes: \"\"\"\n\n            117\n            {\n              \"kind\": \"finished\",\n              \"name\": \"compile\",\n              \"pid\": 22698,\n              \"exit-status\": 1,\n              \"output\": \"error: it failed :-(\"\n            }\n            \"\"\".utf8)\n        delegate.assert(messages: [], errorDescription: nil)\n    }\n}\n\nclass MockSwiftCompilerOutputParserDelegate: SwiftCompilerOutputParserDelegate {\n    private var messages: [SwiftCompilerMessage] = []\n    private var error: Error?\n\n    func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didParse message: SwiftCompilerMessage) {\n        messages.append(message)\n    }\n\n    func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didFailWith error: Error) {\n        self.error = error\n    }\n\n    func assert(\n        messages: [SwiftCompilerMessage],\n        errorDescription: String?,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) {\n        #expect(messages == self.messages, sourceLocation: sourceLocation)\n        let errorReason = (self.error as? LocalizedError)?.errorDescription ?? error?.localizedDescription\n        #expect(errorDescription == errorReason, sourceLocation: sourceLocation)\n        self.messages = []\n        self.error = nil\n    }\n}\n"
  },
  {
    "path": "Tests/BuildTests/WindowsBuildPlanTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Testing\n\nimport Basics\n@testable import Build\nimport LLBuildManifest\nimport _InternalTestSupport\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport PackageGraph\n\nstruct WindowsBuildPlanTests {\n    // Tests that our build plan is build correctly to handle separation\n    // of object files that export symbols and ones that don't and to ensure\n    // DLL products pick up the right ones.\n\n    @Test(\n        arguments: [\n            (triple: Triple.x86_64Windows, label: \"x86_64-unknown-windows-msvc\"),\n            (triple: Triple.x86_64MacOS, label: \"x86_64-apple-macosx\"),\n            (triple: Triple.x86_64Linux, label: \"x86_64-unknown-linux-gnu\"),\n        ]\n    )\n    func validateTriple(triple: Triple, label: String) async throws {\n        let fs = InMemoryFileSystem(emptyFiles: [\n            \"/libPkg/Sources/coreLib/coreLib.swift\",\n            \"/libPkg/Sources/dllLib/dllLib.swift\",\n            \"/libPkg/Sources/staticLib/staticLib.swift\",\n            \"/libPkg/Sources/objectLib/objectLib.swift\",\n            \"/exePkg/Sources/exe/main.swift\",\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                .createFileSystemManifest(\n                    displayName: \"libPkg\",\n                    path: \"/libPkg\",\n                    products: [\n                        .init(name: \"DLLProduct\", type: .library(.dynamic), targets: [\"dllLib\"]),\n                        .init(name: \"StaticProduct\", type: .library(.static), targets: [\"staticLib\"]),\n                        .init(name: \"ObjectProduct\", type: .library(.automatic), targets: [\"objectLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"coreLib\", dependencies: []),\n                        .init(name: \"dllLib\", dependencies: [\"coreLib\"]),\n                        .init(name: \"staticLib\", dependencies: [\"coreLib\"]),\n                        .init(name: \"objectLib\", dependencies: [\"coreLib\"]),\n                    ]\n                ),\n                .createRootManifest(\n                    displayName: \"exePkg\",\n                    path: \"/exePkg\",\n                    dependencies: [.fileSystem(path: \"/libPkg\")],\n                    targets: [\n                        .init(name: \"exe\", dependencies: [\n                            .product(name: \"DLLProduct\", package: \"libPkg\"),\n                            .product(name: \"StaticProduct\", package: \"libPkg\"),\n                            .product(name: \"ObjectProduct\", package: \"libPkg\"),\n                        ]),\n                    ]\n                )\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                triple: triple\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                triple: triple\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let llbuild = LLBuildManifestBuilder(\n            plan,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        try llbuild.generateManifest(at: \"/manifest\")\n        let commands = llbuild.manifest.commands\n\n        func hasStatic(_ name: String) throws -> Bool {\n            let tool = try #require(commands[name]?.tool as? SwiftCompilerTool)\n            return tool.otherArguments.contains(\"-static\")\n        }\n\n        #expect(try hasStatic(\"C.coreLib-\\(label)-debug.module\") == triple.isWindows(), \"\\(label)\")\n        #expect(try hasStatic(\"C.dllLib-\\(label)-debug.module\") == false, \"\\(label)\")\n        #expect(try hasStatic(\"C.staticLib-\\(label)-debug.module\") == triple.isWindows(), \"\\(label)\")\n        #expect(try hasStatic(\"C.objectLib-\\(label)-debug.module\") == triple.isWindows(), \"\\(label)\")\n        #expect(try hasStatic(\"C.exe-\\(label)-debug.module\") == triple.isWindows(), \"\\(label)\")\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/APIDiffTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Build\nimport Commands\nimport SPMBuildCore\n\n@_spi(SwiftPMInternal)\nimport DriverSupport\n\nimport Foundation\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\nimport Workspace\nimport Testing\n\nextension Trait where Self == Testing.ConditionTrait {\n    public static var requiresAPIDigester: Self {\n        enabled(\"This test requires a toolchain with swift-api-digester\") {\n            (try? UserToolchain.default.getSwiftAPIDigester()) != nil && ProcessInfo.hostOperatingSystem != .windows\n        }\n    }\n}\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .FunctionalArea.APIDiff,\n    ),\n)\nstruct APIDiffTests {\n    @discardableResult\n    private func execute(\n        _ args: [String],\n        packagePath: AbsolutePath? = nil,\n        env: Environment? = nil,\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws -> (stdout: String, stderr: String) {\n        var environment = env ?? [:]\n        // don't ignore local packages when caching\n        environment[\"SWIFTPM_TESTS_PACKAGECACHE\"] = \"1\"\n        return try await executeSwiftPackage(\n            packagePath,\n            extraArgs: args,\n            env: environment,\n            buildSystem: buildSystem\n        )\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testInvokeAPIDiffDigester(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Foo\")\n            // Overwrite the existing decl.\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(\"Foo.swift\"),\n                string: \"public let foo = 42\"\n            )\n            await expectThrowsCommandExecutionError(try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\"], packagePath: packageRoot, buildSystem: buildSystem)) { error in\n                #expect(!error.stdout.isEmpty)\n            }\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSimpleAPIDiff(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Foo\")\n            // Overwrite the existing decl.\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(\"Foo.swift\"),\n                string: \"public let foo = 42\"\n            )\n            await expectThrowsCommandExecutionError(try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\"], packagePath: packageRoot, buildSystem: buildSystem)) { error in\n                #expect(error.stdout.contains(\"1 breaking change detected in Foo\"))\n                #expect(error.stdout.contains(\"💔 API breakage: func foo() has been removed\"))\n            }\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8926\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testMultiTargetAPIDiff(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Baz\", \"Baz.swift\"),\n                string: #\"public func baz() -> String { \"hello, world!\" }\"#\n            )\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Qux\", \"Qux.swift\"),\n                string: \"public class Qux<T, U> { private let x = 1 }\"\n            )\n            await expectThrowsCommandExecutionError(try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\"], packagePath: packageRoot, buildSystem: buildSystem)) { error in\n                #expect(error.stdout.contains(\"2 breaking changes detected in Qux\"))\n                #expect(error.stdout.contains(\"💔 API breakage: class Qux has generic signature change from <T> to <T, U>\"))\n                #expect(error.stdout.contains(\"💔 API breakage: var Qux.x has been removed\"))\n                #expect(error.stdout.contains(\"1 breaking change detected in Baz\"))\n                #expect(error.stdout.contains(\"💔 API breakage: func bar() has been removed\"))\n            }\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8926\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testBreakageAllowlist(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Baz\", \"Baz.swift\"),\n                string: #\"public func baz() -> String { \"hello, world!\" }\"#\n            )\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Qux\", \"Qux.swift\"),\n                string: \"public class Qux<T, U> { private let x = 1 }\"\n            )\n            let customAllowlistPath = packageRoot.appending(components: \"foo\", \"allowlist.txt\")\n            try localFileSystem.writeFileContents(\n                customAllowlistPath,\n                string: \"API breakage: class Qux has generic signature change from <T> to <T, U>\\n\"\n            )\n            await expectThrowsCommandExecutionError(\n                try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\", \"--breakage-allowlist-path\", customAllowlistPath.pathString],\n                            packagePath: packageRoot, buildSystem: buildSystem)\n            ) { error in\n                #expect(!error.stdout.contains(\"💔 API breakage: class Qux has generic signature change from <T> to <T, U>\"))\n                #expect(error.stdout.contains(\"1 breaking change detected in Qux\"))\n                #expect(error.stdout.contains(\"💔 API breakage: var Qux.x has been removed\"))\n                #expect(error.stdout.contains(\"1 breaking change detected in Baz\"))\n                #expect(error.stdout.contains(\"💔 API breakage: func bar() has been removed\"))\n            }\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8926\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testCheckVendedModulesOnly(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"NonAPILibraryTargets\")\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Foo\", \"Foo.swift\"),\n                string: #\"public func baz() -> String { \"hello, world!\" }\"#\n            )\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Bar\", \"Bar.swift\"),\n                string: \"public class Qux<T, U> { private let x = 1 }\"\n            )\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Baz\", \"Baz.swift\"),\n                string: \"public enum Baz {case a, b, c }\"\n            )\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Qux\", \"Qux.swift\"),\n                string: \"public class Qux<T, U> { private let x = 1 }\"\n            )\n            try await expectThrowsCommandExecutionError(try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\"], packagePath: packageRoot, buildSystem: buildSystem)) { error in\n                #expect(error.stdout.contains(\"💔 API breakage\"))\n                let regex = try Regex(\"\\\\d+ breaking change(s?) detected in Foo\")\n                #expect(error.stdout.contains(regex))\n                #expect(error.stdout.contains(regex))\n                #expect(error.stdout.contains(regex))\n                // Qux is not part of a library product, so any API changes should be ignored\n                #expect(!error.stdout.contains(\"Qux\"))\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        .requiresAPIDigester,\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8926\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testFilters(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"NonAPILibraryTargets\")\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Foo\", \"Foo.swift\"),\n                string: #\"public func baz() -> String { \"hello, world!\" }\"#\n            )\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Bar\", \"Bar.swift\"),\n                string: \"public class Qux<T, U> { private let x = 1 }\"\n            )\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Baz\", \"Baz.swift\"),\n                string: \"public enum Baz {case a, b, c }\"\n            )\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Qux\", \"Qux.swift\"),\n                string: \"public class Qux<T, U> { private let x = 1 }\"\n            )\n            try await expectThrowsCommandExecutionError(\n                try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\", \"--products\", \"One\", \"--targets\", \"Bar\"], packagePath: packageRoot, buildSystem: buildSystem)\n            ) { error in\n                #expect(error.stdout.contains(\"💔 API breakage\"))\n                let regex = try Regex(\"\\\\d+ breaking change(s?) detected in Foo\")\n\n                #expect(error.stdout.contains(regex))\n\n                // Baz and Qux are not included in the filter, so any API changes should be ignored.\n                #expect(!error.stdout.contains(\"Baz\"))\n                #expect(!error.stdout.contains(\"Qux\"))\n            }\n\n            // Diff a target which didn't have a baseline generated as part of the first invocation\n            try await expectThrowsCommandExecutionError(\n                try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\", \"--targets\", \"Baz\"], packagePath: packageRoot, buildSystem: buildSystem)\n            ) { error in\n                #expect(error.stdout.contains(\"💔 API breakage\"))\n                let regex = try Regex(\"\\\\d+ breaking change(s?) detected in Baz\")\n                #expect(error.stdout.contains(regex))\n                // Only Baz is included, we should not see any other API changes.\n                #expect(!error.stdout.contains(\"Foo\"))\n                #expect(!error.stdout.contains(\"Bar\"))\n                #expect(!error.stdout.contains(\"Qux\"))\n            }\n\n            // Test diagnostics\n            await expectThrowsCommandExecutionError(\n                try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\", \"--targets\", \"NotATarget\", \"Exec\", \"--products\", \"NotAProduct\", \"Exec\"],\n                            packagePath: packageRoot, buildSystem: buildSystem)\n            ) { error in\n                #expect(error.stderr.contains(\"error: no such product 'NotAProduct'\"))\n                #expect(error.stderr.contains(\"error: no such target 'NotATarget'\"))\n                #expect(error.stderr.contains(\"'Exec' is not a library product\"))\n                #expect(error.stderr.contains(\"'Exec' is not a library target\"))\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9699\", relationship: .defect),\n        .requiresAPIDigester,\n        arguments: SupportedBuildSystemOnAllPlatforms\n    )\n    func testAPIDiffOfModuleWithCDependency(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue {\n            try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"CTargetDep\")\n                // Overwrite the existing decl.\n                try localFileSystem.writeFileContents(packageRoot.appending(components: \"Sources\", \"Bar\", \"Bar.swift\"), string:\n                    \"\"\"\n                    import Foo\n\n                    public func bar() -> String {\n                        foo()\n                        return \"hello, world!\"\n                    }\n                    \"\"\"\n                )\n                await expectThrowsCommandExecutionError(try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\"], packagePath: packageRoot, buildSystem: buildSystem)) { error in\n                    #expect(error.stdout.contains(\"1 breaking change detected in Bar\"), \"stderr: \\(error.stderr)\")\n                    #expect(error.stdout.contains(\"💔 API breakage: func bar() has return type change from Swift.Int to Swift.String\"), \"stderr: \\(error.stderr)\")\n                }\n\n                // Report an error if we explicitly ask to diff a C-family target\n                await expectThrowsCommandExecutionError(try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\", \"--targets\", \"Foo\"], packagePath: packageRoot, buildSystem: buildSystem)) { error in\n                    #expect(error.stderr.contains(\"error: 'Foo' is not a Swift language target\"), \"stdout: \\(error.stdout)\")\n                }\n            }\n        } when: {\n            #if compiler(>=6.3)\n            false\n            #else\n            buildSystem == .swiftbuild && [.macOS, .linux].contains(ProcessInfo.hostOperatingSystem) // <unknown>:0: error: missing required module 'Foo'\n            #endif\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        .requiresAPIDigester,\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9699\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms\n    )\n    func testAPIDiffOfVendoredCDependency(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue {\n            try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"CIncludePath\")\n                let (output, _) = try await execute([\"diagnose-api-breaking-changes\", \"main\"], packagePath: packageRoot, buildSystem: buildSystem)\n\n                #expect(output.contains(\"No breaking changes detected in Sample\"))\n            }\n        } when: {\n            #if compiler(>=6.3)\n            false\n            #else\n            buildSystem == .swiftbuild && [.macOS, .linux].contains(ProcessInfo.hostOperatingSystem) // <unknown>:0: error: missing required module 'Foo'\n            #endif\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        .requiresAPIDigester,\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8926\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testNoBreakingChanges(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            // Introduce an API-compatible change\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(components: \"Sources\", \"Baz\", \"Baz.swift\"),\n                string: \"public func bar() -> Int { 100 }\"\n            )\n            let (output, _) = try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\"], packagePath: packageRoot, buildSystem: buildSystem)\n            #expect(output.contains(\"No breaking changes detected in Baz\"))\n            #expect(output.contains(\"No breaking changes detected in Qux\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        .requiresAPIDigester,\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8926\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testAPIDiffAfterAddingNewTarget(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n                try localFileSystem.createDirectory(packageRoot.appending(components: \"Sources\", \"Foo\"))\n                try localFileSystem.writeFileContents(\n                    packageRoot.appending(components: \"Sources\", \"Foo\", \"Foo.swift\"),\n                    string: #\"public let foo = \"All new module!\"\"#\n                )\n                try localFileSystem.writeFileContents(packageRoot.appending(\"Package.swift\"), string:\n                    \"\"\"\n                    // swift-tools-version:4.2\n                    import PackageDescription\n\n                    let package = Package(\n                        name: \"Bar\",\n                        products: [\n                            .library(name: \"Baz\", targets: [\"Baz\"]),\n                            .library(name: \"Qux\", targets: [\"Qux\", \"Foo\"]),\n                        ],\n                        targets: [\n                            .target(name: \"Baz\"),\n                            .target(name: \"Qux\"),\n                            .target(name: \"Foo\")\n                        ]\n                    )\n                    \"\"\"\n                )\n                let (output, _) = try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\"], packagePath: packageRoot, buildSystem: buildSystem)\n                #expect(output.contains(\"No breaking changes detected in Baz\"))\n                #expect(output.contains(\"No breaking changes detected in Qux\"))\n                #expect(output.contains(\"Skipping Foo because it does not exist in the baseline\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.isHostAmazonLinux2()\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testAPIDiffPackageWithPlugin(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"WithPlugin\")\n            let (output, _) = try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\"], packagePath: packageRoot, buildSystem: buildSystem)\n            #expect(output.contains(\"No breaking changes detected in TargetLib\"))\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testBadTreeish(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Foo\")\n            await expectThrowsCommandExecutionError(try await execute([\"diagnose-api-breaking-changes\", \"7.8.9\"], packagePath: packageRoot, buildSystem: buildSystem)) { error in\n                #expect(error.stderr.contains(\"error: Couldn’t get revision\"))\n            }\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testBranchUpdate(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withTemporaryDirectory { baselineDir in\n            try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Foo\")\n                let repo = GitRepository(path: packageRoot)\n                try repo.checkout(newBranch: \"feature\")\n                // Overwrite the existing decl.\n                try localFileSystem.writeFileContents(\n                    packageRoot.appending(\"Foo.swift\"),\n                    string: \"public let foo = 42\"\n                )\n                try repo.stage(file: \"Foo.swift\")\n                try repo.commit(message: \"Add foo\")\n                await expectThrowsCommandExecutionError(\n                    try await execute([\"diagnose-api-breaking-changes\", \"main\", \"--baseline-dir\", baselineDir.pathString],\n                                      packagePath: packageRoot,\n                                      buildSystem: buildSystem)\n                ) { error in\n                    #expect(error.stdout.contains(\"1 breaking change detected in Foo\"))\n                    #expect(error.stdout.contains(\"💔 API breakage: func foo() has been removed\"))\n                }\n\n                // Update `main` and ensure the baseline is regenerated.\n                try repo.checkout(revision: .init(identifier: \"main\"))\n                try localFileSystem.writeFileContents(\n                    packageRoot.appending(\"Foo.swift\"),\n                    string: \"public let foo = 42\"\n                )\n                try repo.stage(file: \"Foo.swift\")\n                try repo.commit(message: \"Add foo\")\n                try repo.checkout(revision: .init(identifier: \"feature\"))\n                let (output, _) = try await execute([\"diagnose-api-breaking-changes\", \"main\", \"--baseline-dir\", baselineDir.pathString],\n                                                    packagePath: packageRoot,\n                                                    buildSystem: buildSystem)\n                #expect(output.contains(\"No breaking changes detected in Foo\"))\n            }\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testBaselineDirOverride(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Foo\")\n            // Overwrite the existing decl.\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(\"Foo.swift\"),\n                string: \"public let foo = 42\"\n            )\n\n            let baselineDir = fixturePath.appending(\"Baselines\")\n            let repo = GitRepository(path: packageRoot)\n            let revision = try repo.resolveRevision(identifier: \"1.2.3\")\n\n            await expectThrowsCommandExecutionError(\n                try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\", \"--baseline-dir\", baselineDir.pathString], packagePath: packageRoot, buildSystem: buildSystem)\n            ) { error in\n                #expect(error.stdout.contains(\"1 breaking change detected in Foo\"))\n                #expect(error.stdout.contains(\"💔 API breakage: func foo() has been removed\"))\n                let baseName: String\n                if buildSystem == .swiftbuild {\n                    baseName = \"Foo\"\n                } else {\n                    baseName = \"Foo.json\"\n                }\n                #expect(localFileSystem.exists(baselineDir.appending(components: revision.identifier, baseName)))\n            }\n        }\n    }\n\n    @Test(\n        .requiresAPIDigester,\n        .tags(\n            .Feature.Command.Package.DiagnoseApiBreakingChanges,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testRegenerateBaseline(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/APIDiff/\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Foo\")\n            // Overwrite the existing decl.\n            try localFileSystem.writeFileContents(\n                packageRoot.appending(\"Foo.swift\"),\n                string: \"public let foo = 42\"\n            )\n\n            let repo = GitRepository(path: packageRoot)\n            let revision = try repo.resolveRevision(identifier: \"1.2.3\")\n\n            let baselineDir = fixturePath.appending(\"Baselines\")\n            let fooBaselinePath: AbsolutePath\n            if buildSystem == .swiftbuild {\n                fooBaselinePath = baselineDir.appending(components: revision.identifier, \"Foo\")\n            } else {\n                fooBaselinePath = baselineDir.appending(components: revision.identifier, \"Foo.json\")\n            }\n\n            var initialTimestamp: Date?\n            try await expectThrowsCommandExecutionError(\n                try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\",\n                             \"--baseline-dir\", baselineDir.pathString],\n                            packagePath: packageRoot,\n                                 buildSystem: buildSystem)\n            ) { error in\n                #expect(error.stdout.contains(\"1 breaking change detected in Foo\"))\n                #expect(error.stdout.contains(\"💔 API breakage: func foo() has been removed\"))\n                #expect(localFileSystem.exists(fooBaselinePath))\n                initialTimestamp = try localFileSystem.getFileInfo(fooBaselinePath).modTime\n            }\n\n            // Accomodate filesystems with low resolution timestamps\n            try await Task.sleep(for: .seconds(1))\n\n            try await expectThrowsCommandExecutionError(\n                try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\",\n                             \"--baseline-dir\", baselineDir.pathString],\n                            packagePath: packageRoot,\n                                 buildSystem: buildSystem)\n            ) { error in\n                #expect(error.stdout.contains(\"1 breaking change detected in Foo\"))\n                #expect(error.stdout.contains(\"💔 API breakage: func foo() has been removed\"))\n                let newTimestamp = try localFileSystem.getFileInfo(fooBaselinePath).modTime\n                #expect(newTimestamp == initialTimestamp)\n            }\n\n            // Accomodate filesystems with low resolution timestamps\n            try await Task.sleep(for: .seconds(1))\n\n            await expectThrowsCommandExecutionError(\n                try await execute([\"diagnose-api-breaking-changes\", \"1.2.3\",\n                             \"--baseline-dir\", baselineDir.pathString, \"--regenerate-baseline\"],\n                            packagePath: packageRoot,\n                                 buildSystem: buildSystem)\n            ) { error in\n                #expect(error.stdout.contains(\"1 breaking change detected in Foo\"))\n                #expect(error.stdout.contains(\"💔 API breakage: func foo() has been removed\"))\n                #expect((try? localFileSystem.getFileInfo(fooBaselinePath).modTime) != initialTimestamp)\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.ExperimentalApiDiff,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testOldName(buildSystem: BuildSystemProvider.Kind) async throws {\n        await expectThrowsCommandExecutionError(try await execute([\"experimental-api-diff\", \"1.2.3\", \"--regenerate-baseline\"], packagePath: nil, buildSystem: buildSystem)) { error in\n            #expect(error.stdout.contains(\"`swift package experimental-api-diff` has been renamed to `swift package diagnose-api-breaking-changes`\"))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/BuildCommandTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\n@testable import Commands\n@testable import CoreCommands\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport enum PackageModel.BuildConfiguration\nimport SPMBuildCore\nimport enum SWBUtil.PropertyList\nimport enum SWBUtil.PropertyListItem\nimport Testing\nimport TSCTestSupport\nimport Workspace\n\nstruct BuildResult {\n    let binPath: AbsolutePath\n    let stdout: String\n    let stderr: String\n    let binContents: [String]\n    let moduleContents: [String]\n}\n\n@discardableResult\nfileprivate func execute(\n    _ args: [String] = [],\n    environment: Environment? = nil,\n    packagePath: AbsolutePath? = nil,\n    configuration: BuildConfiguration,\n    buildSystem: BuildSystemProvider.Kind,\n    throwIfCommandFails: Bool = true,\n) async throws -> (stdout: String, stderr: String) {\n\n    return try await executeSwiftBuild(\n        packagePath,\n        configuration: configuration,\n        extraArgs: args,\n        env: environment,\n        buildSystem: buildSystem,\n        throwIfCommandFails: throwIfCommandFails,\n    )\n}\n\nfileprivate func build(\n    _ args: [String],\n    packagePath: AbsolutePath? = nil,\n    configuration: BuildConfiguration,\n    cleanAfterward: Bool = true,\n    buildSystem: BuildSystemProvider.Kind,\n) async throws -> BuildResult {\n    do {\n        let (stdout, stderr) = try await execute(args, packagePath: packagePath,configuration: configuration, buildSystem: buildSystem,)\n        defer {\n        }\n        let (binPathOutput, _) = try await execute(\n            [\"--show-bin-path\"],\n            packagePath: packagePath,\n            configuration: configuration,\n            buildSystem: buildSystem,\n        )\n        let binPath = try AbsolutePath(validating: binPathOutput.trimmingCharacters(in: .whitespacesAndNewlines))\n        let binContents = try localFileSystem.getDirectoryContents(binPath).filter {\n            guard let contents = try? localFileSystem.getDirectoryContents(binPath.appending(component: $0)) else {\n                return true\n            }\n            // Filter directories which only contain an output file map since we didn't build anything for those which\n            // is what `binContents` is meant to represent.\n            return contents != [\"output-file-map.json\"]\n        }\n        var moduleContents: [String] = []\n        switch buildSystem {\n            case .native:\n                moduleContents = (try? localFileSystem.getDirectoryContents(binPath.appending(component: \"Modules\"))) ?? []\n            case .swiftbuild, .xcode:\n                let moduleDirs = (try? localFileSystem.getDirectoryContents(binPath).filter {\n                    $0.contains(\".swiftmodule\")\n                }) ?? []\n                for dir: String in moduleDirs {\n                    moduleContents +=\n                        (try? localFileSystem.getDirectoryContents(binPath.appending(component: dir)).map { \"\\(dir)/\\($0)\" }) ?? []\n                }\n        }\n\n        if cleanAfterward {\n            try await executeSwiftPackage(\n                packagePath,\n                extraArgs: [\"clean\"],\n                buildSystem: buildSystem\n            )\n        }\n        return BuildResult(\n            binPath: binPath,\n            stdout: stdout,\n            stderr: stderr,\n            binContents: binContents,\n            moduleContents: moduleContents\n        )\n    } catch {\n        if cleanAfterward {\n            try await executeSwiftPackage(\n                packagePath,\n                extraArgs: [\"clean\"],\n                buildSystem: buildSystem\n            )\n        }\n        throw error\n    }\n}\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        Tag.TestSize.large,\n        Tag.Feature.Command.Build,\n        .Feature.CommandLineArguments.BuildSystem,\n    ),\n)\nstruct BuildCommandTestCases {\n\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func usage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let stdout = try await execute([\"-help\"], configuration: .debug, buildSystem: buildSystem).stdout\n        #expect(stdout.contains(\"USAGE: swift build\"))\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.ShowBinPath,\n        ),\n        buildDataUsingAllBuildSystemWithTags.tags,\n        arguments: buildDataUsingAllBuildSystemWithTags.buildData,\n    )\n    func binSymlink(\n        buildData: BuildData,\n    ) async throws {\n        let buildSystem = buildData.buildSystem\n        let configuration = buildData.config\n        // Test is not implemented for Xcode build system\n        try await fixture(name: \"ValidLayouts/SingleModule/ExecutableNew\") { fixturePath in\n            let fullPath = try resolveSymlinks(fixturePath)\n\n            let targetPath = try fullPath.appending(components: buildSystem.binPath(for: configuration))\n            let path = try await execute(\n                [\"--show-bin-path\"],\n                packagePath: fullPath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            ).stdout.trimmingCharacters(in: .whitespacesAndNewlines)\n            #expect(\n                AbsolutePath(path).pathString == targetPath.pathString\n            )\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Help,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func seeAlso(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let stdout = try await execute(\n            [\"--help\"],\n            configuration: .debug,\n            buildSystem: buildSystem,\n        ).stdout\n        #expect(stdout.contains(\"SEE ALSO: swift run, swift package, swift test\"))\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Help,\n        ),\n\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandDoesNotEmitDuplicateSymbols(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let duplicateSymbolRegex = try #require(duplicateSymbolRegex)\n        let (stdout, stderr) = try await execute(\n            [\"--help\"],\n            configuration: .debug,\n            buildSystem: buildSystem,\n        )\n        #expect(!stdout.contains(duplicateSymbolRegex))\n        #expect(!stderr.contains(duplicateSymbolRegex))\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Version,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func version(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let stdout = try await execute(\n            [\"--version\"],\n            configuration: .debug,\n            buildSystem: buildSystem,\n        ).stdout\n        let expectedRegex = try Regex(#\"Swift Package Manager -( \\w+ )?\\d+.\\d+.\\d+(-\\w+)?\"#)\n        #expect(stdout.contains(expectedRegex))\n    }\n\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.ExplicitTargetDependencyImportCheck,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9620\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func importOfMissedDepWarning(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/ImportOfMissingDependency\") { path in\n            let fullPath = try resolveSymlinks(path)\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await build(\n                    [\"--explicit-target-dependency-import-check=warn\"],\n                    packagePath: fullPath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            switch buildSystem {\n                case .native, .swiftbuild:\n                    withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/9620\") {\n                        #expect(\n                            stderr.contains(\"warning: Target A imports another target (B) in the package without declaring it a dependency.\"),\n                            \"got stdout: \\(stdout), stderr: \\(stderr)\",\n                        )\n                    } when: {\n                        buildSystem == .swiftbuild\n                    }\n                case .xcode:\n                    Issue.record(\"Test expectation have not been implemented\")\n                    break\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.ExplicitTargetDependencyImportCheck,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9620\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func importOfMissedDepWarningVerifyingErrorFlow(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/ImportOfMissingDependency\") { path in\n            let fullPath = try resolveSymlinks(path)\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await build(\n                    [\"--explicit-target-dependency-import-check=error\"],\n                    packagePath: fullPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Expected error did not occur\")\n                return\n            }\n\n            switch buildSystem {\n                case .native, .swiftbuild:\n                    withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/9620\") {\n                        #expect(\n                            stderr.contains(\"error: Target A imports another target (B) in the package without declaring it a dependency.\"),\n                            \"got stdout: \\(stdout), stderr: \\(stderr)\",\n                        )\n                    } when: {\n                        buildSystem == .swiftbuild\n                    }\n                case .xcode:\n                    Issue.record(\"Test expectatation have not been implemented.\")\n            }\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9620\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func importOfMissedDepWarningVerifyingDefaultDoesNotRunTheCheck(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/ImportOfMissingDependency\") { path in\n            let fullPath = try resolveSymlinks(path)\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await build(\n                    [],\n                    packagePath: fullPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Expected error did not occur\")\n                return\n            }\n            let mustNotBeMatches: String\n            switch buildSystem {\n                case .native, .swiftbuild:\n                    mustNotBeMatches = \"Target A imports another target (B) in the package without declaring it a dependency.\"\n                case .xcode:\n                    mustNotBeMatches = \"make compiler happy\"\n                    Issue.record(\"Test expectation has not been implemented\")\n            }\n            #expect(!stderr.contains(mustNotBeMatches))\n            #expect(!stdout.contains(mustNotBeMatches))\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func symlink(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"ValidLayouts/SingleModule/ExecutableNew\") { fixturePath in\n                let fullPath = try resolveSymlinks(fixturePath)\n                // Test symlink.\n                try await execute(packagePath: fullPath, configuration: configuration, buildSystem: buildSystem)\n                let actualDebug = try resolveSymlinks(fullPath.appending(components: buildSystem.binPath(for: configuration)))\n                let expectedDebug = try fullPath.appending(components: buildSystem.binPath(for: configuration))\n                #expect(actualDebug == expectedDebug)\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n              .Feature.Command.Build,\n              .Feature.TargetType.Executable\n        ),\n        .IssueWindowsLongPath,\n        buildDataUsingAllBuildSystemWithTags.tags,\n        arguments: buildDataUsingAllBuildSystemWithTags.buildData,\n    )\n    func buildExistingExecutableProductIsSuccessfull(\n        data: BuildData,\n    ) async throws {\n            try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n                let fullPath = try resolveSymlinks(fixturePath)\n\n                let result = try await build(\n                    [\"--product\", \"exec1\"],\n                    packagePath: fullPath,\n                    configuration: data.config,\n                    buildSystem: data.buildSystem,\n                )\n                #expect(result.binContents.contains(executableName(\"exec1\")))\n                #expect(!result.binContents.contains(\"exec2.build\"))\n            }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9137\", relationship: .defect),\n        .IssueWindowsCannotSaveAttachment,\n        .tags(\n            .Feature.CommandLineArguments.Product,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func buildExistingLibraryProductIsSuccessfull(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n                let fullPath = try resolveSymlinks(fixturePath)\n\n                let (_, stderr) = try await execute(\n                    [\"--product\", \"lib1\"],\n                    packagePath: fullPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                switch buildSystem {\n                    case .native:\n                            #expect(\n                                stderr.contains(\n                                    \"'--product' cannot be used with the automatic product 'lib1'; building the default target instead\"\n                                )\n                            )\n                    case .swiftbuild, .xcode:\n                        // Do nothing.\n                        break\n                }\n            }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9138\", relationship: .defect),\n        .tags(\n            .Feature.CommandLineArguments.Target,\n        ),\n        buildDataUsingAllBuildSystemWithTags.tags,\n        arguments: buildDataUsingAllBuildSystemWithTags.buildData,\n    )\n    func buildExistingTargetIsSuccessfull(\n        data: BuildData,\n    ) async throws {\n        let buildSystem = data.buildSystem\n        try await withKnownIssue(\"Could not find target named 'exec2'\") {\n            try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n                let fullPath = try resolveSymlinks(fixturePath)\n\n                let result = try await build(\n                    [\"--target\", \"exec2\"],\n                    packagePath: fullPath,\n                    configuration: data.config,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.binContents.contains(\"exec2.build\"))\n                #expect(!result.binContents.contains(executableName(\"exec1\")))\n            }\n        } when: {\n            [\n                .swiftbuild,\n                .xcode,\n            ].contains(buildSystem)\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Product,\n            .Feature.CommandLineArguments.Target,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func buildProductAndTargetsFailsWithAMutuallyExclusiveMessage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute(\n                    [\"--product\", \"exec1\", \"--target\", \"exec2\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            // THEN I expect a failure\n            guard case SwiftPMError.executionFailure(_, _, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n            #expect(stderr.contains(\"error: '--product' and '--target' are mutually exclusive\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.BuildTests,\n            .Feature.CommandLineArguments.Product,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func buildProductAndTestsFailsWithAMutuallyExclusiveMessage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n\n        try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute(\n                    [\"--product\", \"exec1\", \"--build-tests\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            // THEN I expect a failure\n            guard case SwiftPMError.executionFailure(_, _, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n            #expect(stderr.contains(\"error: '--product' and '--build-tests' are mutually exclusive\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.BuildTests,\n            .Feature.CommandLineArguments.Target,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func buildTargetAndTestsFailsWithAMutuallyExclusiveMessage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute(\n                    [\"--build-tests\", \"--target\", \"exec2\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            // THEN I expect a failure\n            guard case SwiftPMError.executionFailure(_, _, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n            #expect(stderr.contains(\"error: '--target' and '--build-tests' are mutually exclusive\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.BuildTests,\n            .Feature.CommandLineArguments.Product,\n            .Feature.CommandLineArguments.Target,\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnPlatform),\n    )\n    func buildProductTargetAndTestsFailsWithAMutuallyExclusiveMessage(\n        data: BuildData,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute(\n                    [\"--build-tests\", \"--target\", \"exec2\", \"--product\", \"exec1\"],\n                    packagePath: fixturePath,\n                    configuration: data.config,\n                    buildSystem: data.buildSystem,\n                )\n            }\n            // THEN I expect a failure\n            guard case SwiftPMError.executionFailure(_, _, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n            #expect(stderr.contains(\"error: '--product', '--target', and '--build-tests' are mutually exclusive\"), \"stout: \\(stdout)\")\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Product,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func buildUnknownProductFailsWithAppropriateMessage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n            let productName = \"UnknownProduct\"\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute(\n                    [\"--product\", productName],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            // THEN I expect a failure\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            switch buildSystem {\n                case .native:\n                    #expect(stderr.contains(\"error: no product named '\\(productName)'\"))\n                case .swiftbuild, .xcode:\n                    let expectedErrorMessageRegex = try Regex(\"error: Could not find target named '\\(productName).*'\")\n                    #expect(\n                        stderr.contains(expectedErrorMessageRegex),\n                        \"expect log not emitted.\\nstdout: '\\(stdout)'\\n\\nstderr: '\\(stderr)'\",\n                    )\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Target,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func buildUnknownTargetFailsWithAppropriateMessage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n            let targetName = \"UnknownTargetName\"\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute(\n                    [\"--target\", targetName],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            // THEN I expect a failure\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n            let expectedErrorMessage: String\n            switch buildSystem {\n                case .native:\n                    expectedErrorMessage = \"error: no target named '\\(targetName)'\"\n                case .swiftbuild, .xcode:\n                    expectedErrorMessage = \"error: Could not find target named '\\(targetName)'\"\n            }\n            #expect(\n                stderr.contains(expectedErrorMessage),\n                \"expect log not emitted.\\nstdout: '\\(stdout)'\\n\\nstderr: '\\(stderr)'\",\n            )\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Product,\n        ),\n        buildDataUsingAllBuildSystemWithTags.tags,\n        arguments: buildDataUsingAllBuildSystemWithTags.buildData, [\"ClangExecSingleFile\", \"SwiftExecSingleFile\", \"SwiftExecMultiFile\"],\n    )\n    func atMainSupport(\n        data: BuildData,\n        executable: String,\n    ) async throws {\n        let buildSystem = data.buildSystem\n        let config = data.config\n        try await withKnownIssue(\n            \"SWBINTTODO: File not found or missing libclang errors on windows platforms. This needs to be investigated\",\n            isIntermittent: true,\n        ) {\n            try await fixture(name: \"Miscellaneous/AtMainSupport\") { fixturePath in\n                let fullPath = try resolveSymlinks(fixturePath)\n                let result = try await build(\n                    [\"--product\", executable],\n                    packagePath: fullPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.binContents.contains(executableName(executable)))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows  && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func nonReachableProductsAndTargetsFunctional(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/UnreachableTargets\", createGitRepo: true) { fixturePath in\n            let aPath = fixturePath.appending(\"A\")\n\n            let result = try await build(\n                [],\n                packagePath: aPath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(!result.binContents.contains(\"bexec\"))\n            #expect(!result.binContents.contains(\"BTarget2.build\"))\n            #expect(!result.binContents.contains(\"cexec\"))\n            #expect(!result.binContents.contains(\"CTarget.build\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Product,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func nonReachableProductsAndTargetsFunctionalWhereDependencyContainsADependentProducts(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/UnreachableTargets\", createGitRepo: true) { fixturePath in\n                let aPath = fixturePath.appending(\"A\")\n\n                // Dependency contains a dependent product\n\n                let result = try await build(\n                    [\"--product\", \"bexec\"],\n                    packagePath: aPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                switch buildSystem {\n                    case .native:\n                    #expect(result.binContents.contains(\"BTarget2.build\"))\n                    case .swiftbuild, .xcode:\n                    break\n                }\n                #expect(result.binContents.contains(executableName(\"bexec\")))\n                #expect(!result.binContents.contains(executableName(\"aexec\")))\n                #expect(!result.binContents.contains(\"ATarget.build\"))\n                #expect(!result.binContents.contains(\"BLibrary.a\"))\n\n\n                #expect(!result.binContents.contains(\"cexec\"))\n                switch buildSystem {\n                    case .native:\n                    // FIXME: We create the modulemap during build planning, hence this ugliness.\n                    let bTargetBuildDir =\n                    ((try? localFileSystem.getDirectoryContents(result.binPath.appending(\"BTarget1.build\"))) ?? [])\n                        .filter { $0 != moduleMapFilename }\n                    #expect(bTargetBuildDir.isEmpty, \"bTargetBuildDir should be empty\")\n                    #expect(result.binContents.contains(\"BTarget2.build\"))\n                    case .swiftbuild, .xcode:\n                    break\n                }\n                #expect(!result.binContents.contains(\"CTarget.build\"))\n\n                // Also make sure we didn't emit parseable module interfaces\n                // (do this here to avoid doing a second build in\n                // testParseableInterfaces().\n                #expect(!result.moduleContents.contains(\"ATarget.swiftinterface\"))\n                #expect(!result.moduleContents.contains(\"BTarget.swiftinterface\"))\n                #expect(!result.moduleContents.contains(\"CTarget.swiftinterface\"))\n            }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/9130\", relationship: .fixedBy),\n        .tags(\n            .Feature.CommandLineArguments.EnableParseableModuleInterfaces,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func parseableInterfaces(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/ParseableInterfaces\") { fixturePath in\n            try await withKnownIssue(isIntermittent: true) {\n                let result = try await build(\n                    [\"--enable-parseable-module-interfaces\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                switch buildSystem {\n                    case .native:\n                        #expect(result.moduleContents.contains(\"A.swiftinterface\"))\n                        #expect(result.moduleContents.contains(\"B.swiftinterface\"))\n                    case .swiftbuild, .xcode:\n                        let moduleARegex = try Regex(#\"A[.]swiftmodule[/].*[.]swiftinterface\"#)\n                        let moduleBRegex = try Regex(#\"B[.]swiftmodule[/].*[.]swiftmodule\"#)\n                        #expect(result.moduleContents.contains { $0.contains(moduleARegex) })\n                        #expect(result.moduleContents.contains { $0.contains(moduleBRegex) })\n                }\n            } when: {\n                // errors with SwiftBuild on Windows possibly due to long path on windows only for swift build\n                ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .FunctionalArea.LibraryEvoluton,\n            .Feature.CommandLineArguments.Product,\n            .Feature.CommandLineArguments.BuildTests,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func automaticParseableInterfacesWithLibraryEvolution(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/LibraryEvolution\") { fixturePath in\n                let result = try await build(\n                    [],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                switch buildSystem {\n                    case .native:\n                        #expect(result.moduleContents.contains(\"A.swiftinterface\"))\n                        #expect(result.moduleContents.contains(\"B.swiftinterface\"))\n                    case .swiftbuild:\n                        let moduleARegex = try Regex(#\"A[.]swiftmodule[/].*[.]swiftmodule\"#)\n                        let moduleBRegex = try Regex(#\"B[.]swiftmodule[/].*[.]swiftmodule\"#)\n                        #expect(result.moduleContents.contains { $0.contains(moduleARegex) })\n                        #expect(result.moduleContents.contains { $0.contains(moduleBRegex) })\n                    case .xcode:\n                        Issue.record(\"Test configuration error. Build backend is not intended to be tested.\")\n                }\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test\n    func pifManifestFileIsCreatedInTheRootScratchPathDirectory() async throws {\n        try await fixture(name: \"Miscellaneous/ParseableInterfaces\") { fixturePath in\n            try await withTemporaryDirectory { tmpDir in\n                try await executeSwiftBuild(\n                    fixturePath,\n                    extraArgs: [\n                        \"--scratch-path\",\n                        tmpDir.pathString,\n                    ],\n                    buildSystem: .swiftbuild\n                )\n                expectFileExists(at: tmpDir.appending(\"manifest.pif\"))\n            }\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        .tags(\n            .Feature.BuildCache,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func buildCompleteMessage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let buildCompleteRegex = try Regex(#\"Build complete!\\s?(\\([0-9]*\\.[0-9]*\\s*s(econds)?\\))?\"#)\n                do {\n                    let result = try await execute(\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    // This test fails to match the 'Compiling' regex; rdar://101815761\n                    // XCTAssertMatch(result.stdout, .regex(\"\\\\[[1-9][0-9]*\\\\/[1-9][0-9]*\\\\] Compiling\"))\n                    let lines = result.stdout.split(whereSeparator: { $0.isNewline })\n                    let lastLine = try #require(lines.last)\n                    #expect(lastLine.contains(buildCompleteRegex))\n                }\n\n                do {\n                    // test second time, to stabilize the cache\n                    try await execute(\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                }\n\n                do {\n                    // test third time, to make sure message is presented even when nothing to build (cached)\n                    let result = try await execute(\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    // This test fails to match the 'Compiling' regex; rdar://101815761\n                    // XCTAssertNoMatch(result.stdout, .regex(\"\\\\[[1-9][0-9]*\\\\/[1-9][0-9]*\\\\] Compiling\"))\n                    let lines = result.stdout.split(whereSeparator: { $0.isNewline })\n                    let lastLine = try #require(lines.last)\n                    #expect(lastLine.contains(buildCompleteRegex))\n                }\n            }\n        } when: {\n            (buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows)\n        }\n    }\n\n    @Test(\n        buildDataUsingAllBuildSystemWithTags.tags,\n        arguments: buildDataUsingAllBuildSystemWithTags.buildData,\n    )\n    func buildStartMessage(\n        data: BuildData,\n    ) async throws {\n        let buildSystem = data.buildSystem\n        let configuration =  data.config\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let result = try await execute([], packagePath: fixturePath, configuration: configuration, buildSystem: buildSystem, throwIfCommandFails: false)\n            let expectedString: String\n            switch configuration {\n                case .debug:\n                    expectedString = \"debugging\"\n                case .release:\n                    expectedString = \"production\"\n\n            }\n            switch buildSystem {\n                case .native, .swiftbuild:\n                    #expect(\n                        result.stdout.contains(\"Building for \\(expectedString)\"),\n                        \"expect log not emitted.  got stdout: '\\(result.stdout)'\\n\\nstderr '\\(result.stderr)'\",\n                    )\n                case .xcode:\n                    // Xcode build system does not emit the build started message.\n                    break\n            }\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func buildSystemDefaultSettings(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(\"Sometimes failed to build due to a possible path issue\", isIntermittent: true) {\n            try await fixture(name: \"ValidLayouts/SingleModule/ExecutableNew\") { fixturePath in\n                // try await building using XCBuild with default parameters.  This should succeed.  We build verbosely so we get\n                // full command lines.\n                    let output: (stdout: String, stderr: String) = try await execute(\n                        [\"-v\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n    #if os(macOS)\n                // In the case of the native build system check for the cross-compile target, only for macOS\n                if buildSystem == .native {\n                    let targetTripleString = try UserToolchain.default.targetTriple.tripleString(forPlatformVersion: \"\")\n                    #expect(output.stdout.contains(\"-target \\(targetTripleString)\"))\n                }\n    #endif\n\n                // Look for build completion message from the particular build system\n                #expect(output.stdout.contains(\"Build complete!\"))\n            }\n        } when: {\n            (buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows)\n        }\n    }\n\n    @Test(\n        .disabled(\"Disabled for now because it is hitting 'IR generation failure: Cannot read legacy layout file' in CI (rdar://88828632)\"),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Configuration,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.VeryVerbose,\n            .Feature.CommandLineArguments.Xlinker,\n            .Feature.CommandLineArguments.Xcc,\n            .Feature.CommandLineArguments.Xcxx,\n            .Feature.CommandLineArguments.Xswiftc,\n        ),\n        arguments: [BuildSystemProvider.Kind.swiftbuild, .xcode],\n    )\n    func xcodeBuildSystemWithAdditionalBuildFlags(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"ValidLayouts/SingleModule/ExecutableMixed\") { fixturePath in\n            // try await building using XCBuild with additional flags.  This should succeed.  We build verbosely so we get\n            // full command lines.\n            let defaultOutput = try await execute(\n                [\n                    \"--very-verbose\",\n                    \"-Xlinker\", \"-rpath\", \"-Xlinker\", \"/fakerpath\",\n                    \"-Xcc\", \"-I/cfakepath\",\n                    \"-Xcxx\", \"-I/cxxfakepath\",\n                    \"-Xswiftc\", \"-I/swiftfakepath\",\n                ],\n                packagePath: fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            ).stdout\n\n            // Look for certain things in the output from XCBuild.\n            #expect(defaultOutput.contains(\"/fakerpath\"))\n            #expect(defaultOutput.contains(\"-I/cfakepath\"))\n            #expect(defaultOutput.contains(\"-I/cxxfakepath\"))\n            #expect(defaultOutput.contains(\"-I/swiftfakepath\"))\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Configuration,\n        ),\n        .tags(\n            .Feature.EnvironmentVariables.SWIFT_EXEC,\n            .Feature.EnvironmentVariables.SWIFT_EXEC_MANIFEST,\n        ),\n    )\n    func buildSystemOverrides() async throws {\n        let config = BuildConfiguration.debug\n        let buildSystem = BuildSystemProvider.Kind.swiftbuild\n        try await fixture(name: \"ValidLayouts/SingleModule/ExecutableNew\") { fixturePath in\n            let swiftCompilerPath = try UserToolchain.default.swiftCompilerPath\n            // try await building without specifying overrides.  This should succeed, and should use the default\n            // compiler path.\n            let defaultOutput = try await execute(\n                [\"--vv\"],\n                packagePath: fixturePath,\n                configuration: config,\n                buildSystem: buildSystem,\n            ).stdout\n            #expect(defaultOutput.contains(swiftCompilerPath.pathString))\n\n            // Now try await building while specifying a faulty compiler override.  This should fail.  Note that\n            // we need to set the executable to use for the manifest itself to the default one, since it defaults to\n            // SWIFT_EXEC if not provided.\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute(\n                    [\"--vv\"],\n                    environment: [\n                        \"SWIFT_EXEC\": \"/usr/bin/false\",\n                        \"SWIFT_EXEC_MANIFEST\": swiftCompilerPath.pathString,\n                    ],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            // THEN I expect a failure\n            guard case SwiftPMError.executionFailure(_, _, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n            #expect(stderr.contains(\"/usr/bin/false\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.PrintManifestJobGraph,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func printLLBuildManifestJobGraph(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let output = try await execute(\n                [\"--print-manifest-job-graph\"],\n                packagePath: fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            ).stdout\n            #expect(output.hasPrefix(\"digraph Jobs {\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.PrintPIFManifestGraph,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func printPIFManifestGraph(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let output = try await execute(\n                [\"--print-pif-manifest-graph\"],\n                packagePath: fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            ).stdout\n            switch buildSystem {\n                case .native, .xcode:\n                    #expect(!output.hasPrefix(\"digraph PIF {\"))\n                case .swiftbuild:\n                    #expect(output.hasPrefix(\"digraph PIF {\"))\n            }\n        }\n    }\n\n    @Test(\n        .SWBINTTODO(\"Swift build produces an error building the fixture for this test.\"),\n        .tags(\n            .Feature.CommandLineArguments.Xswiftc,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func swiftDriverRawOutputGetsNewlines(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n         try await withKnownIssue(\n            \"error produced for this fixture\",\n            isIntermittent: true,\n        ) {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                // Building with `-wmo` should result in a `remark: Incremental compilation has been disabled: it is not\n                // compatible with whole module optimization` message, which should have a trailing newline.  Since that\n                // message won't be there at all when the legacy compiler driver is used, we gate this check on whether the\n                // remark is there in the first place.\n                let result = try await execute(\n                    [\"-Xswiftc\", \"-wmo\"],\n                    packagePath: fixturePath,\n                    configuration: .release,\n                    buildSystem: buildSystem,\n                )\n                if result.stdout.contains(\n                    \"remark: Incremental compilation has been disabled: it is not compatible with whole module optimization\"\n                ) {\n                    #expect(result.stdout.contains(\"optimization\\n\"))\n                    #expect(!result.stdout.contains(\"optimization[\"))\n                    #expect(!result.stdout.contains(\"optimizationremark\"))\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8659\", \"SWIFT_EXEC override is not working\"),\n        .SWBINTTODO(\"Test fails because the dummy-swiftc used in the test isn't accepted by swift-build. This needs to be investigated\"),\n        .tags(\n            .Feature.EnvironmentVariables.SWIFT_EXEC,\n            .Feature.EnvironmentVariables.SWIFT_ORIGINAL_PATH,\n            .Feature.EnvironmentVariables.CUSTOM_SWIFT_VERSION,\n            .Feature.CommandLineArguments.Verbose,\n        ),\n        arguments: BuildConfiguration.allCases,\n    )\n    func swiftGetVersion(\n        config: BuildConfiguration,\n    ) async throws {\n        let buildSystem = BuildSystemProvider.Kind.native\n        try await fixture(name: \"Miscellaneous/Simple\") { fixturePath in\n            func findSwiftGetVersionFile() throws -> AbsolutePath {\n                let buildArenaPath = fixturePath.appending(components: \".build\", \"debug\")\n                let files = try localFileSystem.getDirectoryContents(buildArenaPath)\n                let filename = try #require(files.first { $0.hasPrefix(\"swift-version\") })\n                return buildArenaPath.appending(component: filename)\n            }\n            let dummySwiftcPath = SwiftPM.xctestBinaryPath(for: \"dummy-swiftc\")\n            let swiftCompilerPath = try UserToolchain.default.swiftCompilerPath\n\n            var environment: Environment = [\n                \"SWIFT_EXEC\": dummySwiftcPath.pathString,\n                // Environment variables used by `dummy-swiftc.sh`\n                \"SWIFT_ORIGINAL_PATH\": swiftCompilerPath.pathString,\n                \"CUSTOM_SWIFT_VERSION\": \"1.0\",\n            ]\n\n            try await withKnownIssue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/8659, SWIFT_EXEC override is not working\",\n                isIntermittent: true\n            ){\n                // Build with a swiftc that returns version 1.0, we expect a successful build which compiles our one source\n                // file.\n                do {\n                    let result = try await execute(\n                        [\"--verbose\"],\n                        environment: environment,\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(\n                        result.stdout.contains(\"\\(dummySwiftcPath.pathString) -module-name\"),\n                        \"compilation task missing from build result: \\(result.stdout)\",\n                    )\n                    #expect(\n                        result.stdout.contains(\"Build complete!\"),\n                        \"unexpected build result: \\(result.stdout)\",\n                    )\n\n                    let swiftGetVersionFilePath = try findSwiftGetVersionFile()\n                    let actualVersion = try String(contentsOfFile: swiftGetVersionFilePath.pathString).spm_chomp()\n                    #expect(actualVersion == \"1.0\")\n                }\n\n                // Build again with that same version, we do not expect any compilation tasks.\n                do {\n                    let result = try await execute(\n                        [\"--verbose\"],\n                        environment: environment,\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(\n                        !result.stdout.contains(\"\\(dummySwiftcPath.pathString) -module-name\"),\n                        \"compilation task present in build result: \\(result.stdout)\",\n                    )\n                    #expect(\n                        result.stdout.contains(\"Build complete!\"),\n                        \"unexpected build result: \\(result.stdout)\",\n                    )\n\n                    let swiftGetVersionFilePath = try findSwiftGetVersionFile()\n                    let actualVersion = try String(contentsOfFile: swiftGetVersionFilePath.pathString).spm_chomp()\n                    #expect(actualVersion == \"1.0\")\n                }\n\n                // Build again with a swiftc that returns version 2.0, we expect compilation happening once more.\n                do {\n                    environment[\"CUSTOM_SWIFT_VERSION\"] = \"2.0\"\n                    let result = try await execute(\n                        [\"--verbose\"],\n                        environment: environment,\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(\n                        result.stdout.contains(\"\\(dummySwiftcPath.pathString) -module-name\"),\n                        \"compilation task missing from build result: \\(result.stdout)\",\n                    )\n                    #expect(\n                        result.stdout.contains(\"Build complete!\"),\n                        \"unexpected build result: \\(result.stdout)\",\n                    )\n\n                    let swiftGetVersionFilePath = try findSwiftGetVersionFile()\n                    let actualVersion = try String(contentsOfFile: swiftGetVersionFilePath.pathString).spm_chomp()\n                    #expect(actualVersion == \"2.0\")\n                }\n            } when: {\n                (ProcessInfo.hostOperatingSystem == .windows)\n                || (buildSystem == .native && config == .release)\n            }\n        }\n    }\n\n    @Test(\n        // Windows builds of ExecutableNew using swiftbuild can fail because of problem with handling long paths which\n        // is root cause of linked issue\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9420\", relationship: .defect),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9745\", relationship: .defect),\n        .tags(\n            .Feature.CommandLineArguments.DisableGetTaskAllowEntitlement,\n            .Feature.CommandLineArguments.EnableGetTaskAllowEntitlement,\n            .Feature.CommandLineArguments.Verbose\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms)\n    )\n    func getTaskAllowEntitlement(data: BuildData) async throws {\n        let buildSystem = data.buildSystem\n        let buildConfiguration = data.config\n        try await fixture(name: \"ValidLayouts/SingleModule/ExecutableNew\") { fixturePath in\n            #if os(macOS)\n            func codesignDisplay(execPath: AbsolutePath) async throws -> PropertyListItem? {\n                let args = [\"codesign\", \"-d\", \"--entitlements\", \"-\", \"--xml\", execPath.pathString]\n                let result = try await AsyncProcess.popen(arguments: args)\n                return if case .success(let output) = result.output,\n                          !output.isEmpty\n                {\n                    try PropertyList.fromBytes(output)\n                } else {\n                    nil\n                }\n            }\n\n            enum EntitlementCheckType {\n                case required, forbidden\n            }\n\n            func verify(entitlements: PropertyListItem?, getTaskAllow: EntitlementCheckType) {\n                guard let entitlements, case .plDict(let dict) = entitlements else {\n                    if getTaskAllow == .required {\n                        Issue.record(\"Missing expected entitlements\")\n                    }\n                    return\n                }\n\n                switch getTaskAllow {\n                case .required:\n                    #expect(dict[\"com.apple.security.get-task-allow\"] == .plBool(true))\n                case .forbidden:\n                    #expect(dict[\"com.apple.security.get-task-allow\"] == nil)\n                }\n            }\n\n            let execName = \"ExecutableNew\"\n\n            var buildResult = try await build(\n                [\"-v\"],\n                packagePath: fixturePath,\n                configuration: buildConfiguration,\n                cleanAfterward: false,\n                buildSystem: buildSystem\n            )\n            var entitlements = try await codesignDisplay(execPath: buildResult.binPath.appending(execName))\n\n            verify(\n                entitlements: entitlements,\n                getTaskAllow:\n                buildConfiguration == .debug ? .required : .forbidden\n            )\n\n            try await executeSwiftPackage(fixturePath, extraArgs: [\"clean\"], buildSystem: buildSystem)\n\n            buildResult = try await build(\n                [\"--enable-get-task-allow-entitlement\"],\n                packagePath: fixturePath,\n                configuration: buildConfiguration,\n                cleanAfterward: false,\n                buildSystem: buildSystem\n            )\n            entitlements = try await codesignDisplay(execPath: buildResult.binPath.appending(execName))\n\n            verify(entitlements: entitlements, getTaskAllow: .required)\n\n            try await executeSwiftPackage(fixturePath, extraArgs: [\"clean\"], buildSystem: buildSystem)\n\n            buildResult = try await build(\n                [\"--disable-get-task-allow-entitlement\"],\n                packagePath: fixturePath,\n                configuration: buildConfiguration,\n                cleanAfterward: false,\n                buildSystem: buildSystem\n            )\n            entitlements = try await codesignDisplay(execPath: buildResult.binPath.appending(execName))\n\n            verify(entitlements: entitlements, getTaskAllow: .forbidden)\n            #else\n            try await withKnownIssue(isIntermittent: true) {\n                var buildResult = try await build(\n                    [\"-v\"],\n                    packagePath: fixturePath,\n                    configuration: buildConfiguration,\n                    buildSystem: buildSystem\n                )\n\n                #expect(!buildResult.stdout.contains(\"codesign --force --sign - --entitlements\"))\n\n                buildResult = try await build(\n                    [\"--disable-get-task-allow-entitlement\", \"-v\"],\n                    packagePath: fixturePath,\n                    configuration: buildConfiguration,\n                    buildSystem: buildSystem\n                )\n\n                #expect(!buildResult.stdout.contains(\"codesign --force --sign - --entitlements\"))\n                #expect(buildResult.stderr.contains(SwiftCommandState.entitlementsMacOSWarning))\n\n                buildResult = try await build(\n                    [\"--enable-get-task-allow-entitlement\", \"-v\"],\n                    packagePath: fixturePath,\n                    configuration: buildConfiguration,\n                    buildSystem: buildSystem\n                )\n\n                #expect(!buildResult.stdout.contains(\"codesign --force --sign - --entitlements\"))\n                #expect(buildResult.stderr.contains(SwiftCommandState.entitlementsMacOSWarning))\n            } when: {\n                buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n            }\n            #endif\n        }\n    }\n\n    @Test(\n        .requireHostOS(.linux),\n        .SWBINTTODO(\"Swift build doesn't currently ignore Linux main when linking on Linux. This needs further investigation.\"),\n        .tags(\n            .Feature.CommandLineArguments.BuildTests,\n            .Feature.CommandLineArguments.EnableTestDiscovery,\n            .Feature.CommandLineArguments.Verbose,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func ignoresLinuxMain(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/TestDiscovery/IgnoresLinuxMain\") { fixturePath in\n            let buildResult = try await build(\n                [\"-v\", \"--build-tests\", \"--enable-test-discovery\"],\n                packagePath: fixturePath,\n                configuration: configuration,\n                cleanAfterward: false,\n                buildSystem: buildSystem,\n            )\n            let testBinaryPath = buildResult.binPath.appending(\"IgnoresLinuxMainPackageTests.xctest\")\n\n            switch buildSystem {\n                case .native:\n                    expectFileExists(at: testBinaryPath)\n                    _ = try await AsyncProcess.checkNonZeroExit(arguments: [testBinaryPath.pathString])\n                case .swiftbuild:\n                    // there are no additional check\n                    break\n                case .xcode:\n                    Issue.record(\"Test expectations have not been implemented.\")\n            }\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9299\", relationship: .defect),\n        .tags(\n            .Feature.CommandLineArguments.Verbose,\n            .Feature.CommandLineArguments.VeryVerbose,\n            .Feature.CommandLineArguments.Xswiftc,\n        ),\n        arguments: SupportedBuildSystemOnPlatform, [\n            [\"--verbose\"],\n            [\"--very-verbose\"],\n            [\"-Xswiftc\", \"-diagnostic-style=llvm\"],\n        ]\n    )\n    func doesNotRebuildWithFlags(\n        buildSystem: BuildSystemProvider.Kind,\n        flags: [String],\n    ) async throws {\n        func buildSystemAndOutputLocation(\n            buildSystem: BuildSystemProvider.Kind,\n            configuration: BuildConfiguration,\n        ) throws -> Basics.RelativePath {\n            let base = try RelativePath(validating: \".build\")\n            let path = try base.appending(components: buildSystem.binPath(for: configuration, scratchPath: []))\n            switch buildSystem {\n                case .xcode:\n                    return path.appending(\"ExecutableNew\")\n                case .swiftbuild:\n                    return path.appending(\"ExecutableNew\")\n                case .native:\n                    return path.appending(\"ExecutableNew.build\")\n                            .appending(\"main.swift.o\")\n            }\n        }\n\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(\n            \"\"\"\n            Windows: Sometimes failed to build due to a possible path issue\n            All: --very-verbose causes rebuild on SwiftBuild (https://github.com/swiftlang/swift-package-manager/issues/9299)\n            \"\"\",\n            isIntermittent: true) {\n            try await fixture(name: \"ValidLayouts/SingleModule/ExecutableNew\") { fixturePath in\n                _ = try await build(\n                    [],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    cleanAfterward: false,\n                    buildSystem: buildSystem,\n                )\n                let mainOFile = try fixturePath.appending(buildSystemAndOutputLocation(buildSystem: buildSystem, configuration: config))\n                let initialMainOMtime = try #require(FileManager.default.attributesOfItem(atPath: mainOFile.pathString)[.modificationDate] as? Date)\n\n                _ = try await build(\n                    flags,\n                    packagePath: fixturePath,\n                    configuration: config,\n                    cleanAfterward: false,\n                    buildSystem: buildSystem,\n                )\n\n                let subsequentMainOMtime = try #require(FileManager.default.attributesOfItem(atPath: mainOFile.pathString)[.modificationDate] as? Date)\n                #expect(initialMainOMtime == subsequentMainOMtime, \"Expected no rebuild to occur when using flags \\(flags), but the file was modified.\")\n            }\n        } when: {\n            buildSystem == .swiftbuild && [.windows, .linux].contains(ProcessInfo.hostOperatingSystem)\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func parseAsLibraryCriteria(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/ParseAsLibrary\") { fixturePath in\n                _ =  try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true\n                )\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.BuildTests,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func fatalErrorDisplayedCorrectNumberOfTimesWhenSingleXCTestHasFatalErrorInBuildCompilation(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        let expected = 0\n        try await fixture(name: \"Miscellaneous/Errors/FatalErrorInSingleXCTest/TypeLibrary\") { fixturePath in\n            // WHEN swift-build --build-tests is executed\"\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute(\n                    [\"--build-tests\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n            // THEN I expect a failure\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            let matchString = \"error: fatalError\"\n            let stdoutMatches = getNumberOfMatches(of: matchString, in: stdout)\n            let stderrMatches = getNumberOfMatches(of: matchString, in: stderr)\n            let actualNumMatches = stdoutMatches + stderrMatches\n\n            // AND a fatal error message is printed \\(expected) times\n            #expect(actualNumMatches == expected)\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8844\", relationship: .defect),\n        .tags(\n            .Feature.CommandLineArguments.Quiet,\n        ),\n    arguments: SupportedBuildSystemOnPlatform,\n    )\n     func swiftBuildQuietLogLevel(\n         buildSystem: BuildSystemProvider.Kind,\n     ) async throws {\n         let configuration = BuildConfiguration.debug\n             // GIVEN we have a simple test package\n             try await fixture(name: \"Miscellaneous/SwiftBuild\") { fixturePath in\n                //WHEN we build with the --quiet option\n                let (stdout, stderr) = try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    extraArgs: [\"--quiet\"],\n                    buildSystem: buildSystem\n                )\n                // THEN we should not see any output in stderr\n                 #expect(stderr.isEmpty)\n                // AND no content in stdout\n                 #expect(stdout.isEmpty)\n            }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8844\", relationship: .defect),\n        .tags(\n            .Feature.CommandLineArguments.Quiet,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func swiftBuildQuietLogLevelWithError(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n         // GIVEN we have a simple test package\n        try await fixture(name: \"Miscellaneous/SwiftBuild\") { fixturePath in\n            let mainFilePath = fixturePath.appending(\"main.swift\")\n            try localFileSystem.removeFileTree(mainFilePath)\n            try localFileSystem.writeFileContents(\n            mainFilePath,\n            string: \"\"\"\n                print(\"done\"\n                \"\"\"\n            )\n\n            //WHEN we build with the --quiet option\n            let error = await #expect(throws: SwiftPMError.self) {\n                try await executeSwiftBuild(\n                fixturePath,\n                configuration: configuration,\n                extraArgs: [\"--quiet\"],\n                buildSystem: buildSystem\n                )\n            }\n\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            switch buildSystem {\n                case .swiftbuild:\n                    // THEN we should see output in stderr\n                    #expect(stderr.isEmpty == false)\n                    // AND no content in stdout\n                    #expect(stdout.isEmpty)\n                case .native, .xcode:\n                    // THEN we should see content in stdout\n                    #expect(stdout.isEmpty == false)\n                    // AND no output in stderr\n                    #expect(stderr.isEmpty)\n            }\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .tags(\n            .Feature.CommandLineArguments.Triple,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildingPackageWhichRequiresOlderDeploymentTarget(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        // This fixture specifies a deployment target of macOS 12, and uses API obsoleted in macOS 13. The goal\n        // of this test is to ensure that SwiftPM respects the deployment target specified in the package manifest\n        // when passed no triple of an unversioned triple, rather than using the latests deployment target.\n\n        // No triple - build should pass\n        try await fixture(name: \"Miscellaneous/RequiresOlderDeploymentTarget\") { path in\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true\n                )\n        }\n\n        let hostArch: String\n        #if arch(arm64)\n        hostArch = \"arm64\"\n        #elseif arch(x86_64)\n        hostArch = \"x86_64\"\n        #else\n        Issue.record(\"test is not supported on host arch\")\n        return\n        #endif\n\n        // Unversioned triple - build should pass\n        try await fixture(name: \"Miscellaneous/RequiresOlderDeploymentTarget\") { path in\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    extraArgs: [\"--triple\", \"\\(hostArch)-apple-macosx\"],\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true\n                )\n        }\n\n        // Versioned triple with supported deployment target - build should pass\n        try await fixture(name: \"Miscellaneous/RequiresOlderDeploymentTarget\") { path in\n                try await executeSwiftBuild(\n                    path,\n                    extraArgs: [\"--triple\", \"\\(hostArch)-apple-macosx12.0\"],\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true\n                )\n        }\n\n        // Versioned triple with unsupported deployment target - build should fail\n        try await withKnownIssue {\n            _ = try await fixture(name: \"Miscellaneous/RequiresOlderDeploymentTarget\") { path in\n                await #expect(throws: Error.self) {\n                    try await executeSwiftBuild(\n                        path,\n                        extraArgs: [\"--triple\", \"\\(hostArch)-apple-macosx14.0\"],\n                        buildSystem: buildSystem,\n                        throwIfCommandFails: true\n                    )\n                }\n            }\n        } when: {\n            // The native build system does not correctly pass the elevated deployment target\n            buildSystem == .native\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .tags(\n            .Feature.CommandLineArguments.Experimental.BuildDylibsAsFrameworks,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Configuration,\n        ),\n        arguments: getBuildData(for: [.swiftbuild]),\n    )\n    func dynamicLibrariesAsFrameworks(\n        data: BuildData,\n    ) async throws {\n        let buildSystem = data.buildSystem\n        try await withKnownIssue {\n            try await fixture(name: \"Miscellaneous/DynamicProduct\") { fixturePath in\n                let aPath = fixturePath.appending(\"exec\")\n                let result = try await build(\n                    [\"--experimental-build-dylibs-as-frameworks\"],\n                    packagePath: aPath,\n                    configuration: data.config,\n                    cleanAfterward: false,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.binContents.contains(\"PackageFrameworks\"))\n                #expect(result.binContents.contains(\"exec\"))\n\n                let packageFrameworkPath = result.binPath.appending(\"PackageFrameworks\")\n                try requireDirectoryExists(at: packageFrameworkPath)\n                let frameworks = try localFileSystem.getDirectoryContents(packageFrameworkPath)\n                #expect(frameworks.contains(\"firstDyna.framework\"))\n                #expect(frameworks.contains(\"secondDyna.framework\"))\n            }\n        } when: {\n            data.config == .release\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Configuration,\n        ),\n    )\n    func trivialPackageResources() async throws {\n        let buildSystem = BuildSystemProvider.Kind.swiftbuild\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/TIF\") { fixturePath in\n            let result = try await build(\n                [],\n                packagePath: fixturePath,\n                configuration: config,\n                cleanAfterward: false,\n                buildSystem: buildSystem,\n            )\n            try #require(result.binContents.contains(\"TIF_TIF.bundle\"))\n            let contentsDir = result.binPath.appending(\"TIF_TIF.bundle\", \"Contents\")\n            let bundleResourceDir = contentsDir.appending(\"Resources\")\n\n            let bundleResources = try localFileSystem.getDirectoryContents(bundleResourceDir)\n            #expect(bundleResources.contains(\"some.txt\"))\n            #expect(bundleResources.contains(\"Assets.car\"))\n            #expect(bundleResources.contains(\"SomeAlert.nib\"))\n\n            // Check that the Info.plist of the resource bundle looks reasonable.  In particular, it shouldn't have a CFBundleExecutable key, since it's a codeless bundle.\n            let infoPlistPath = contentsDir.appending(\"Info.plist\")\n            let infoPlistBytes = try localFileSystem.readFileContents(infoPlistPath)\n            let infoPlist = try infoPlistBytes.withData({\n                try #require(PropertyListSerialization.propertyList(from: $0, options: [], format: nil) as? NSDictionary, \"couldn't parse built resource bundle's Info.plist as a property list\")\n            })\n            #expect(infoPlist[\"CFBundleExecutable\"] == nil, \"Expected CFBundleExecutable to be omitted from the Info.plist of a codeless resource bundle\")\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Configuration,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func executableTargetIntegratedIntoTwoProducts(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await withKnownIssue(\"Sometimes failed to build due to a possible path issue\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/ExecutableTargetWithTwoProducts\") { fixturePath in\n                let config = BuildConfiguration.debug\n                let _ = try await build(\n                    [],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    cleanAfterward: false,\n                    buildSystem: buildSystem,\n                )\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        .requireSwift6_4,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func codesizeProfile(\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        try await fixture(name: \"ValidLayouts/SingleModule/ExecutableNew\") { fixturePath in\n            let config = BuildConfiguration.release // Use release for WMO\n            let _ = try await build(\n                [\"--experimental-enable-codesize-profile\"],\n                packagePath: fixturePath,\n                configuration: config,\n                cleanAfterward: false,\n                buildSystem: buildSystem\n            )\n\n            let (binPathOutput, _) = try await execute(\n                [\"--show-bin-path\"],\n                packagePath: fixturePath,\n                configuration: config,\n                buildSystem: buildSystem\n            )\n            let binPath = try AbsolutePath(validating: binPathOutput.trimmingCharacters(in: .whitespacesAndNewlines))\n\n            switch buildSystem {\n            case .native:\n                let executableBuildDir = binPath.appending(\"ExecutableNew.build\")\n                #expect(localFileSystem.exists(executableBuildDir), \"ExecutableNew.build directory should exist\")\n\n                let buildDirContents = try localFileSystem.getDirectoryContents(executableBuildDir).filter {\n                    $0.hasSuffix(\".sil\") || $0.hasSuffix(\".ll\") || $0.hasSuffix(\".opt.yaml\")\n                }\n                #expect(!buildDirContents.isEmpty, \"Should have supplementary output files (.sil, .ll, .opt.yaml)\")\n\n            case .swiftbuild, .xcode:\n                // Swift Build stores intermediates under:\n                // .build/out/Intermediates.noindex/<Target>.build/<Config-platform>/<Variant>.build/Objects-normal/<arch>/\n                // The variant suffix (e.g. \"-p\" for products) varies by platform, so search recursively.\n                let intermediatesRoot = binPath\n                    .parentDirectory // Products\n                    .parentDirectory // out\n                    .appending(component: \"Intermediates.noindex\")\n                var foundFiles: [String] = []\n                if let enumerator = FileManager.default.enumerator(atPath: intermediatesRoot.pathString) {\n                    for case let file as String in enumerator {\n                        if file.hasSuffix(\".sil\") || file.hasSuffix(\".ll\") || file.hasSuffix(\".opt.yaml\") {\n                            foundFiles.append(file)\n                        }\n                    }\n                }\n                #expect(!foundFiles.isEmpty, \"Should have supplementary output files (.sil, .ll, .opt.yaml) under \\(intermediatesRoot)\")\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        .requireSwift6_4,\n        arguments: [BuildSystemProvider.Kind.native]\n    )\n    func codesizeProfileWithCustomOutputDirectory(\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        try await fixture(name: \"ValidLayouts/SingleModule/ExecutableNew\") { fixturePath in\n            let config = BuildConfiguration.release\n            let customOutputDir = fixturePath.appending(\"custom-codesize-output\")\n\n            let _ = try await build(\n                [\"--experimental-enable-codesize-profile\", \"--experimental-codesize-profile-output-dir\", customOutputDir.pathString],\n                packagePath: fixturePath,\n                configuration: config,\n                cleanAfterward: false,\n                buildSystem: buildSystem\n            )\n\n            #expect(localFileSystem.exists(customOutputDir), \"Custom output directory should be created\")\n\n            let outputContents = try localFileSystem.getDirectoryContents(customOutputDir)\n            let hasSIL = outputContents.contains { $0.hasSuffix(\".sil\") }\n            let hasIR = outputContents.contains { $0.hasSuffix(\".ll\") }\n            let hasOptRecord = outputContents.contains { $0.hasSuffix(\".opt.yaml\") }\n\n            #expect(hasSIL, \"Should have .sil files in custom directory\")\n            #expect(hasIR, \"Should have .ll files in custom directory\")\n            #expect(hasOptRecord, \"Should have .opt.yaml files in custom directory\")\n        }\n    }\n}\n\nextension Triple {\n    func withoutVersion() throws -> Triple {\n        if isDarwin() {\n            let stringWithoutVersion = tripleString(forPlatformVersion: \"\")\n            return try Triple(stringWithoutVersion)\n        } else {\n            return self\n        }\n    }\n}\n\n\n@Suite(\n    .tags(\n        .TestSize.large,\n        Tag.Feature.SBOM\n    ),\n)\nstruct BuildSBOMCommandTests {\n\n    private func verifySBOMCreated(\n        in stdout: String,\n        expectedCount: Int? = nil,\n        expectedDirectory: AbsolutePath? = nil,\n        message: String = \"should produce at least 1 SBOM\",\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) throws {\n        let lines = stdout.split(separator: \"\\n\")\n        var sbomPaths: [String] = []\n\n        for line in lines {\n            // Match the new format: \"- created {spec} v{version} SBOM at {path}\"\n            if line.contains(\" SBOM at \"),\n               let range = line.range(of: \" SBOM at \"),\n               let endRange = line[range.upperBound...].range(of: \".json\") {\n                let pathString = String(line[range.upperBound..<endRange.upperBound])\n                sbomPaths.append(pathString)\n            }\n        }\n\n        guard !sbomPaths.isEmpty else {\n            Issue.record(\"No SBOM paths found in stdout\")\n            return\n        }\n\n        // Verify expected count if specified\n        if let expectedCount = expectedCount {\n            #expect(sbomPaths.count == expectedCount, \"Expected \\(expectedCount) SBOM(s) but found \\(sbomPaths.count)\", sourceLocation: sourceLocation)\n        }\n\n        for pathString in sbomPaths {\n            let absolutePath = try AbsolutePath(validating: pathString)\n            #expect(localFileSystem.exists(absolutePath), \"Reported SBOM should exist at \\(absolutePath)\", sourceLocation: sourceLocation)\n            if let expectedDir = expectedDirectory {\n                #expect(absolutePath.parentDirectory == expectedDir, \"SBOM should be created in the expected directory: \\(expectedDir)\", sourceLocation: sourceLocation)\n            }\n        }\n\n        // If expected directory is specified, verify only the expected number of SBOM files exist there\n        if let expectedDir = expectedDirectory, let expectedCount = expectedCount {\n            let dirContents = try localFileSystem.getDirectoryContents(expectedDir)\n            let sbomFiles = dirContents.filter { $0.hasSuffix(\".json\") }\n            #expect(sbomFiles.count == expectedCount, \"Expected exactly \\(expectedCount) SBOM file(s) in \\(expectedDir) but found \\(sbomFiles.count)\", sourceLocation: sourceLocation)\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithCycloneDXSpec(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"cyclonedx\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"))\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(in: stdout, message: \"should produce at least 1 CycloneDX SBOM\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithSPDXSpec(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"spdx\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"))\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(in: stdout, expectedCount: 1, message: \"should produce at least 1 SPDX SBOM\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithInvalidSBOMSpec(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    fixturePath,\n                    extraArgs: [\"--sbom-spec\", \"cyclonedx22\"],\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(error.stderr.contains(\"The value 'cyclonedx22' is invalid\"))\n            }\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithSBOMSpecAndProduct(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"cyclonedx\", \"--product\", \"Foo\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(in: stdout, expectedCount: 1, message: \"should produce at least 1 CycloneDX SBOM\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithMultipleSBOMSpecs(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"cyclonedx\", \"--sbom-spec\", \"spdx\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"))\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(in: stdout, expectedCount: 2, message: \"should produce at least 2 SBOMs\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithSBOMSpecFromEnvironment(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [],\n                env: [\"SWIFTPM_BUILD_SBOM_SPEC\": \"cyclonedx\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"))\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(in: stdout, expectedCount: 1, message: \"should produce at least 1 SBOM from environment variable\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithMultipleSBOMSpecsFromEnvironment(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [],\n                env: [\"SWIFTPM_BUILD_SBOM_SPEC\": \"cyclonedx,spdx\"],\n                buildSystem: buildSystem,\n            )\n\n            #expect(stdout.contains(\"Build complete!\"))\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(in: stdout, expectedCount: 2, message: \"should produce at least 2 SBOMs from environment variable\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithSBOMDirectory(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let customSBOMDir = fixturePath.appending(\"env-sboms\")\n\n\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"cyclonedx\", \"--sbom-output-dir\", customSBOMDir.pathString],\n                buildSystem: buildSystem,\n            )\n\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(\n                in: stdout,\n                expectedCount: 1,\n                expectedDirectory: customSBOMDir,\n                message: \"should produce at least 1 CycloneDX SBOM in custom directory\"\n            )\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithSBOMDirectoryFromEnvironment(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let customSBOMDir = fixturePath.appending(\"env-sboms\")\n\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [],\n                env: [\n                    \"SWIFTPM_BUILD_SBOM_SPEC\": \"cyclonedx\",\n                    \"SWIFTPM_BUILD_SBOM_OUTPUT_DIR\": customSBOMDir.pathString\n                ],\n                buildSystem: buildSystem,\n            )\n\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(\n                in: stdout,\n                expectedCount: 1,\n                expectedDirectory: customSBOMDir,\n                message: \"should produce at least 1 CycloneDX SBOM in custom directory\"\n            )\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithSBOMFilterFromEnvironment(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [],\n                env: [\n                    \"SWIFTPM_BUILD_SBOM_SPEC\": \"cyclonedx\",\n                    \"SWIFTPM_BUILD_SBOM_FILTER\": \"product\"\n                ],\n                buildSystem: buildSystem,\n            )\n\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(in: stdout, expectedCount: 1, message: \"should produce at least 1 SBOM from environment variable\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandLineFlagOverridesEnvironmentVariable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"spdx\"],\n                env: [\"SWIFTPM_BUILD_SBOM_SPEC\": \"cyclonedx\"],\n                buildSystem: buildSystem,\n            )\n\n            #expect(stdout.contains(\"SBOMs created\"))\n\n            // Verify that command line flag overrides environment variable by checking SBOM path\n            let spdxRegex = try Regex(#\"created spdx.* v.* SBOM at .*\\.json\"#)\n            let cyclonedxRegex = try Regex(#\"created cyclonedx.* v.* SBOM at .*\\.json\"#)\n\n            #expect(stdout.contains(spdxRegex), \"should create SPDX SBOM from command line, not CycloneDX from environment\")\n            #expect(!stdout.contains(cyclonedxRegex), \"should not create CycloneDX SBOM from environment variable\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithAllSBOMEnvironmentVariables(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let customSBOMDir = fixturePath.appending(\"all-env-sboms\")\n\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [],\n                env: [\n                    \"SWIFTPM_BUILD_SBOM_SPEC\": \"cyclonedx,spdx\",\n                    \"SWIFTPM_BUILD_SBOM_OUTPUT_DIR\": customSBOMDir.pathString,\n                    \"SWIFTPM_BUILD_SBOM_FILTER\": \"all\",\n                    \"SWIFTPM_BUILD_SBOM_WARNING_ONLY\": \"false\"\n                ],\n                buildSystem: buildSystem,\n            )\n\n            try verifySBOMCreated(in: stdout, expectedCount: 2, expectedDirectory: customSBOMDir, message: \"should produce at least 2 SBOMs\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithSBOMWarningOnlyMode(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            // Use platform-specific invalid path:\n            // - Windows: NUL is a reserved device name that cannot be used as a directory\n            // - Linux: /proc/self/fd/0 is a read-only file descriptor that cannot be used as a directory\n            // - macOS: /invalid/readonlypath (path doesn't exist and can't be created)\n            let invalidPath: String\n            switch ProcessInfo.hostOperatingSystem {\n            case .windows:\n                invalidPath = \"NUL\"\n            case .linux:\n                invalidPath = \"/proc/self/fd/0\"\n            default:\n                invalidPath = \"/invalid/readonlypath\"\n            }\n\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    fixturePath,\n                    extraArgs: [\"--sbom-spec\", \"cyclonedx\", \"--sbom-output-dir\", invalidPath],\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(error.stderr.contains(invalidPath))\n            }\n\n            let (_, _) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"cyclonedx\", \"--sbom-output-dir\", invalidPath, \"--sbom-warning-only\"],\n                buildSystem: buildSystem,\n            )\n\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    fixturePath,\n                    extraArgs: [\"--sbom-spec\", \"cyclonedx\", \"--sbom-output-dir\", invalidPath],\n                    env: [\"SWIFTPM_BUILD_SBOM_WARNING_ONLY\": \"false\"],\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(error.stderr.contains(invalidPath))\n            }\n\n            let (_, _) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"cyclonedx\", \"--sbom-output-dir\", invalidPath],\n                env: [\"SWIFTPM_BUILD_SBOM_WARNING_ONLY\": \"true\"],\n                buildSystem: buildSystem,\n            )\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithInvalidSBOMFilterFromEnvironment(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    fixturePath,\n                    extraArgs: [],\n                    env: [\n                        \"SWIFTPM_BUILD_SBOM_SPEC\": \"cyclonedx\",\n                        \"SWIFTPM_BUILD_SBOM_FILTER\": \"invalid_filter\"\n                    ],\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(error.stderr.contains(\"Invalid SBOM filter value 'invalid_filter'\"))\n                #expect(error.stderr.contains(\"Valid values are: all, product, package\"))\n            }\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithInvalidSBOMSpecFromEnvironment(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    fixturePath,\n                    extraArgs: [],\n                    env: [\"SWIFTPM_BUILD_SBOM_SPEC\": \"invalid_spec\"],\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(error.stderr.contains(\"Invalid SBOM spec value 'invalid_spec'\"))\n                #expect(error.stderr.contains(\"Valid values are\"))\n            }\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithPartiallyInvalidSBOMSpecsFromEnvironment(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    fixturePath,\n                    extraArgs: [],\n                    env: [\"SWIFTPM_BUILD_SBOM_SPEC\": \"cyclonedx,invalid_spec,spdx\"],\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(error.stderr.contains(\"Invalid SBOM spec value 'invalid_spec'\"))\n                #expect(error.stderr.contains(\"Valid values are\"))\n            }\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandLineFlagOverridesInvalidEnvironmentVariable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            // Valid CLI flag should override invalid environment variable\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"cyclonedx\", \"--sbom-filter\", \"product\"],\n                env: [\n                    \"SWIFTPM_BUILD_SBOM_SPEC\": \"invalid_spec\",\n                    \"SWIFTPM_BUILD_SBOM_FILTER\": \"invalid_filter\"\n                ],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"SBOMs created\"))\n            try verifySBOMCreated(in: stdout, expectedCount: 1, message: \"should produce SBOM despite invalid environment variables\")\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func buildWithSBOMSpecEmitsWarningForNonSwiftBuild(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let (_, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--sbom-spec\", \"cyclonedx\"],\n                buildSystem: buildSystem,\n            )\n\n            if buildSystem != .swiftbuild {\n                #expect(stderr.contains(\"warning: generating SBOM(s) without `--build-system swiftbuild` flag creates SBOM(s) without build-time conditionals.\"))\n            } else {\n                #expect(!stderr.contains(\"without build-time conditionals\"))\n            }\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms, [\"cyclonedx\", \"spdx\"]\n    )\n    func sbomReproducibilityExcludingTimestampsAndUUIDs(\n        buildSystem: BuildSystemProvider.Kind,\n        sbomSpec: String\n    ) async throws {\n        try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let customSBOMDir = fixturePath.appending(\"reproducibility-test-\\(sbomSpec)\")\n\n            // Generate first SBOM\n            try await generateSBOM(\n                fixturePath: fixturePath,\n                sbomSpec: sbomSpec,\n                outputDir: customSBOMDir,\n                buildSystem: buildSystem\n            )\n\n            // Get the first SBOM file from the output directory\n            let sbomFiles1 = try getSBOMFiles(in: customSBOMDir)\n            #expect(sbomFiles1.count == 1, \"Expected exactly 1 SBOM file after first generation\")\n            let sbomPath1 = sbomFiles1[0]\n            let content1 = try readSBOMContent(at: sbomPath1)\n\n            // Small delay to ensure different timestamp\n            try await Task.sleep(for: .seconds(1))\n\n            // Generate second SBOM\n            try await generateSBOM(\n                fixturePath: fixturePath,\n                sbomSpec: sbomSpec,\n                outputDir: customSBOMDir,\n                buildSystem: buildSystem\n            )\n\n            // Get all SBOM files from the output directory (should now have 2)\n            let sbomFiles2 = try getSBOMFiles(in: customSBOMDir)\n            #expect(sbomFiles2.count == 2, \"Expected exactly 2 SBOM files after second generation\")\n\n            // Find the newly created file (the one that's not sbomPath1)\n            guard let sbomPath2 = sbomFiles2.first(where: { $0 != sbomPath1 }) else {\n                throw NSError(domain: \"TestError\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Could not find second SBOM file\"])\n            }\n            let content2 = try readSBOMContent(at: sbomPath2)\n\n            // Verify the two SBOMs are different files (different timestamps in filename)\n            #expect(sbomPath1 != sbomPath2, \"SBOM files should have different names due to timestamps\")\n\n            // Normalize both SBOMs by removing timestamps and UUIDs\n            let normalized1 = try normalizeJSONForComparison(content1)\n            let normalized2 = try normalizeJSONForComparison(content2)\n\n            // Compare normalized content\n            #expect(normalized1 == normalized2, \"SBOMs should be identical after normalizing timestamps and UUIDs\")\n        }\n    }\n\n    /// Generates an SBOM in the specified output directory\n    private func generateSBOM(\n        fixturePath: AbsolutePath,\n        sbomSpec: String,\n        outputDir: AbsolutePath,\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        let (_, _) = try await executeSwiftBuild(\n            fixturePath,\n            extraArgs: [\"--sbom-spec\", sbomSpec, \"--sbom-output-dir\", outputDir.pathString],\n            buildSystem: buildSystem\n        )\n    }\n\n    /// Gets all SBOM JSON files from the specified directory\n    private func getSBOMFiles(in directory: AbsolutePath) throws -> [AbsolutePath] {\n        let contents = try localFileSystem.getDirectoryContents(directory)\n        let sbomFiles = contents.filter { $0.hasSuffix(\".json\") }\n        return sbomFiles.map { directory.appending(component: $0) }.sorted()\n    }\n\n    /// Reads SBOM content from file\n    private func readSBOMContent(at path: AbsolutePath) throws -> String {\n        let data = try localFileSystem.readFileContents(path)\n        guard let content = String(data: Data(data.contents), encoding: .utf8) else {\n            throw NSError(domain: \"TestError\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Could not read SBOM as UTF-8\"])\n        }\n        return content\n    }\n\n    /// Normalizes JSON content by replacing timestamps and UUIDs with placeholder values\n    /// This allows comparison of SBOM content while ignoring non-deterministic fields\n    private func normalizeJSONForComparison(_ jsonString: String) throws -> String {\n        guard let jsonData = jsonString.data(using: .utf8),\n              let jsonObject = try JSONSerialization.jsonObject(with: jsonData) as? [String: Any] else {\n            throw NSError(domain: \"TestError\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Failed to parse JSON\"])\n        }\n\n        // Recursively normalize the JSON object\n        let normalizedObject = normalizeJSONValue(jsonObject)\n\n        // Convert back to string with sorted keys for consistent comparison\n        let normalizedData = try JSONSerialization.data(withJSONObject: normalizedObject, options: [.sortedKeys, .prettyPrinted])\n\n        guard let normalizedString = String(data: normalizedData, encoding: .utf8) else {\n            throw NSError(domain: \"TestError\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Failed to convert normalized JSON to string\"])\n        }\n\n        return normalizedString\n    }\n\n    private func normalizeJSONValue(_ value: Any) -> Any {\n        if let dict = value as? [String: Any] {\n            var normalizedDict: [String: Any] = [:]\n            for (key, val) in dict {\n                // Normalize timestamp fields\n                if key == \"timestamp\" || key == \"created\" || key.contains(\"Time\") || key.contains(\"Date\") {\n                    if val is String {\n                        normalizedDict[key] = \"NORMALIZED_TIMESTAMP\"\n                    } else {\n                        normalizedDict[key] = normalizeJSONValue(val)\n                    }\n                }\n                // Normalize UUID fields and URN-based identifiers\n                else if key == \"serialNumber\" || key == \"bom-ref\" || key == \"spdxId\" ||\n                        key == \"creationInfo\" || key == \"createdBy\" || key.contains(\"uuid\") || key.contains(\"UUID\") {\n                    normalizedDict[key] = normalizeUUIDValue(val)\n                }\n                else {\n                    normalizedDict[key] = normalizeJSONValue(val)\n                }\n            }\n            return normalizedDict\n        }\n        else if let array = value as? [Any] {\n            return array.map { normalizeJSONValue($0) }\n        }\n        else if let string = value as? String {\n            return normalizeStringWithUUIDs(string)\n        }\n        else {\n            return value\n        }\n    }\n\n    /// Normalizes values that may contain UUIDs (strings or arrays of strings)\n    private func normalizeUUIDValue(_ value: Any) -> Any {\n        if let string = value as? String {\n            return normalizeStringWithUUIDs(string)\n        } else if let array = value as? [Any] {\n            return array.map { normalizeUUIDValue($0) }\n        } else {\n            return normalizeJSONValue(value)\n        }\n    }\n\n    /// Replaces UUID patterns in strings with a normalized placeholder\n    private func normalizeStringWithUUIDs(_ string: String) -> String {\n        // Match UUID patterns in various formats:\n        // - Standard UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n        // - URN format: urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n        let uuidPattern = #\"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\"#\n\n        guard let regex = try? NSRegularExpression(pattern: uuidPattern, options: .caseInsensitive) else {\n            return string\n        }\n\n        let range = NSRange(string.startIndex..., in: string)\n        let normalized = regex.stringByReplacingMatches(\n            in: string,\n            options: [],\n            range: range,\n            withTemplate: \"NORMALIZED-UUID\"\n        )\n\n        return normalized\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/CoverageTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Commands\nimport _InternalTestSupport\nimport var Basics.localFileSystem\nimport struct Basics.AbsolutePath\nimport enum PackageModel.BuildConfiguration\nimport struct SPMBuildCore.BuildSystemProvider\nimport Testing\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .TestSize.large,\n        .Feature.CodeCoverage,\n        .Feature.CommandLineArguments.EnableCodeCoverage\n    )\n)\nstruct CoverageTests {\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n            .Feature.Command.Test,\n            .Feature.CommandLineArguments.BuildTests,\n        ),\n        .IssueWindowsPathNoEntry,\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9600\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func executingTestsWithCoverageWithoutCodeBuiltWithCoverageGeneratesAFailure(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { path in\n                _ = try await executeSwiftBuild(\n                    path,\n                    configuration: config,\n                    extraArgs: [\"--build-tests\"],\n                    buildSystem: buildSystem,\n                )\n                await withKnownIssue(isIntermittent: true) {\n                await #expect(throws: (any Error).self ) {\n                    try await executeSwiftTest(\n                        path,\n                        configuration: config,\n                        extraArgs: [\n                            \"--skip-build\",\n                            \"--enable-code-coverage\",\n                        ],\n                        buildSystem: buildSystem,\n                        throwIfCommandFails: true,\n                    )\n                }\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9588\", relationship: .defect),\n        .IssueWindowsPathNoEntry,\n        .tags(\n            .Feature.Command.Test,\n            .Feature.CommandLineArguments.BuildTests,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func executingTestsWithCoverageWithCodeBuiltWithCoverageGeneratesCodeCoverage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        // Test that enabling code coverage during building produces the expected folder.\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { path in\n            let codeCovPathString = try await getCoveragePath(\n                path,\n                with: BuildData(buildSystem: buildSystem, config: config),\n            )\n\n            let codeCovPath = try AbsolutePath(validating: codeCovPathString)\n\n            // WHEN we build with coverage enabled\n                try await executeSwiftBuild(\n                    path,\n                    configuration: config,\n                    extraArgs: [\"--build-tests\", \"--enable-code-coverage\"],\n                    buildSystem: buildSystem,\n                )\n\n                // AND we test with coverag enabled and skip the build\n                try await executeSwiftTest(\n                    path,\n                    configuration: config,\n                    extraArgs: [\n                        \"--skip-build\",\n                        \"--enable-code-coverage\",\n                    ],\n                    buildSystem: buildSystem,\n                )\n\n                // THEN we expect the file to exists\n                expectFileExists(at: codeCovPath)\n\n                // AND the parent directory is non empty\n                let codeCovFiles = try localFileSystem.getDirectoryContents(codeCovPath.parentDirectory)\n                #expect(codeCovFiles.count > 0)\n        }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild // This was no longer an issue when I tested at-desk\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9588\", relationship: .defect),\n        .IssueWindowsPathNoEntry,\n        arguments: SupportedBuildSystemOnAllPlatforms, [\n            \"Coverage/Simple\",\n            \"Miscellaneous/TestDiscovery/Simple\",\n        ],\n    )\n    func generateCoverageReport(\n        buildSystem: BuildSystemProvider.Kind,\n        fixtureName: String\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: fixtureName) { path in\n            let coveragePathString = try await getCoveragePath(\n                path,\n                with: BuildData(buildSystem: buildSystem, config: config),\n            )\n            let coveragePath = try AbsolutePath(validating: coveragePathString)\n            try #require(!localFileSystem.exists(coveragePath))\n\n            // WHEN we test with coverage enabled\n            try await withKnownIssue(isIntermittent: true) {\n                try await executeSwiftTest(\n                    path,\n                    configuration: config,\n                    extraArgs: [\n                        \"--enable-code-coverage\",\n                    ],\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true,\n                )\n\n                // THEN we expect the file to exists\n                #expect(localFileSystem.exists(coveragePath))\n            } when: {\n                (ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild)\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "Tests/CommandsTests/MermaidPackageSerializerTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport class Basics.InMemoryFileSystem\nimport class Basics.ObservabilitySystem\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport func PackageGraph.loadModulesGraph\n\nimport class PackageModel.Manifest\nimport struct PackageModel.ProductDescription\nimport struct PackageModel.TargetDescription\nimport func _InternalTestSupport.XCTAssertNoDiagnostics\n\n@testable\nimport Commands\n\nimport Testing\nimport _InternalTestSupport\n\nstruct MermaidPackageSerializerTests {\n    @Test(\n        .tags(\n            .TestSize.medium, //?\n        ),\n    )\n    func simplePackage() throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n                \"/A/Sources/ATarget/main.swift\",\n            \"/A/Tests/ATargetTests/TestCases.swift\"\n        )\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    targets: [\n                        TargetDescription(name: \"ATarget\"),\n                        TargetDescription(name: \"ATargetTests\", dependencies: [\"ATarget\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        expectNoDiagnostics(observability.diagnostics)\n\n        #expect(graph.packages.count == 1)\n        let package = try #require(graph.packages.first)\n        let serializer = MermaidPackageSerializer(package: package.underlying)\n        #expect(serializer.renderedMarkdown == \"\"\"\n            ```mermaid\n            flowchart TB\n                subgraph a\n                    product:APackageTests[[APackageTests]]-->target:ATargetTests(ATargetTests)\n                    product:ATarget[[ATarget]]-->target:ATarget(ATarget)\n                    target:ATargetTests(ATargetTests)-->target:ATarget(ATarget)\n                end\n            ```\n\n            \"\"\")\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium, //?\n        ),\n    )\n    func dependenciesOnProducts() throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n                \"/A/Sources/ATarget/foo.swift\",\n            \"/A/Tests/ATargetTests/foo.swift\",\n            \"/B/Sources/BTarget/foo.swift\",\n            \"/B/Tests/BTargetTests/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [\"BLibrary\"]),\n                        TargetDescription(name: \"ATargetTests\", dependencies: [\"ATarget\"], type: .test),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    products: [\n                        ProductDescription(name: \"BLibrary\", type: .library(.automatic), targets: [\"BTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget\", dependencies: []),\n                        TargetDescription(name: \"BTargetTests\", dependencies: [\"BTarget\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        expectNoDiagnostics(observability.diagnostics)\n\n        #expect(graph.packages.count == 2)\n        let package = try #require(graph.package(for: .plain(\"A\")))\n        let serializer = MermaidPackageSerializer(package: package.underlying)\n        #expect(serializer.renderedMarkdown == \"\"\"\n            ```mermaid\n            flowchart TB\n                subgraph a\n                    product:APackageTests[[APackageTests]]-->target:ATargetTests(ATargetTests)\n                    target:ATargetTests(ATargetTests)-->target:ATarget(ATarget)\n                    target:ATarget(ATarget)-->BLibrary{{BLibrary}}\n                end\n            ```\n\n            \"\"\")\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium, //?\n        ),\n    )\n    func dependenciesOnPackages() throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles:\n                \"/A/Sources/ATarget/foo.swift\",\n            \"/A/Tests/ATargetTests/foo.swift\",\n            \"/B/Sources/BTarget/foo.swift\",\n            \"/B/Tests/BTargetTests/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ATarget\", dependencies: [.product(name: \"BLibrary\", package: \"B\")]),\n                        TargetDescription(name: \"ATargetTests\", dependencies: [\"ATarget\"], type: .test),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    products: [\n                        ProductDescription(name: \"BLibrary\", type: .library(.automatic), targets: [\"BTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BTarget\", dependencies: []),\n                        TargetDescription(name: \"BTargetTests\", dependencies: [\"BTarget\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        expectNoDiagnostics(observability.diagnostics)\n\n        #expect(graph.packages.count == 2)\n        let package = try #require(graph.package(for: .plain(\"A\")))\n        let serializer = MermaidPackageSerializer(package: package.underlying)\n        #expect(serializer.renderedMarkdown == \"\"\"\n            ```mermaid\n            flowchart TB\n                subgraph a\n                    product:APackageTests[[APackageTests]]-->target:ATargetTests(ATargetTests)\n                    target:ATargetTests(ATargetTests)-->target:ATarget(ATarget)\n                end\n\n                subgraph B\n                    target:ATarget(ATarget)-->BLibrary{{BLibrary}}\n                end\n            ```\n\n            \"\"\")\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/MultiRootSupportTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport Commands\nimport _InternalTestSupport\nimport Workspace\nimport Testing\n\n@Suite(\n    .tags(\n        .TestSize.large,\n    ),\n)\nstruct MultiRootSupportTests {\n    @Test\n    func workspaceLoader() throws {\n        let fs = InMemoryFileSystem(emptyFiles: [\n            \"/tmp/test/dep/Package.swift\",\n            \"/tmp/test/local/Package.swift\",\n        ])\n        let path = AbsolutePath(\"/tmp/test/Workspace.xcworkspace\")\n        try fs.writeFileContents(\n            path.appending(\"contents.xcworkspacedata\"),\n            string:\n                \"\"\"\n                <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n                <Workspace\n                version = \"1.0\">\n                <FileRef\n                    location = \"absolute:/tmp/test/dep\">\n                </FileRef>\n                <FileRef\n                    location = \"group:local\">\n                </FileRef>\n                </Workspace>\n                \"\"\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let result = try XcodeWorkspaceLoader(fileSystem: fs, observabilityScope: observability.topScope).load(workspace: path)\n\n        expectNoDiagnostics(observability.diagnostics)\n        let actual = result.map { $0.pathString }.sorted()\n        let expected = [AbsolutePath(\"/tmp/test/dep\").pathString, AbsolutePath(\"/tmp/test/local\").pathString]\n        #expect(actual == expected)\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/PackageCommandTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly) import PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SourceControl\nimport Testing\nimport Workspace\nimport _InternalTestSupport\n\nimport class Basics.AsyncProcess\nimport struct SPMBuildCore.BuildSystemProvider\nimport typealias SPMBuildCore.CLIArguments\nimport class TSCBasic.BufferedOutputByteStream\nimport struct TSCBasic.ByteString\nimport enum TSCBasic.JSON\n\n@testable import Commands\n@testable import CoreCommands\n\n@discardableResult\nfileprivate func execute(\n    _ args: [String] = [],\n    packagePath: AbsolutePath? = nil,\n    manifest: String? = nil,\n    env: Environment? = nil,\n    configuration: BuildConfiguration,\n    buildSystem: BuildSystemProvider.Kind\n) async throws -> (stdout: String, stderr: String) {\n    var environment = env ?? [:]\n    if let manifest, let packagePath {\n        try localFileSystem.writeFileContents(packagePath.appending(\"Package.swift\"), string: manifest)\n    }\n\n    // don't ignore local packages when caching\n    environment[\"SWIFTPM_TESTS_PACKAGECACHE\"] = \"1\"\n    return try await executeSwiftPackage(\n        packagePath,\n        configuration: configuration,\n        extraArgs: args,\n        env: environment,\n        buildSystem: buildSystem,\n    )\n}\n\n// Helper function to arbitrarily assert on manifest content\nprivate func expectManifest(_ packagePath: AbsolutePath, _ callback: (String) throws -> Void) throws {\n    let manifestPath = packagePath.appending(\"Package.swift\")\n    expectFileExists(at: manifestPath)\n    let contents: String = try localFileSystem.readFileContents(manifestPath)\n    try callback(contents)\n}\n\n// Helper function to assert content exists in the manifest\nprivate func expectManifestContains(_ packagePath: AbsolutePath, _ expected: String) throws {\n    try expectManifest(packagePath) { manifestContents in\n        #expect(manifestContents.contains(expected))\n    }\n}\n\n// Helper function to test adding a URL dependency and asserting the result\nprivate func executeAddURLDependencyAndAssert(\n    packagePath: AbsolutePath,\n    initialManifest: String? = nil,\n    url: String,\n    requirementArgs: [String],\n    expectedManifestString: String,\n    buildSystem: BuildSystemProvider.Kind,\n) async throws {\n    let config = BuildConfiguration.debug\n    _ = try await execute(\n        [\"add-dependency\", url] + requirementArgs,\n        packagePath: packagePath,\n        manifest: initialManifest,\n        configuration: config,\n        buildSystem: buildSystem,\n    )\n    try expectManifestContains(packagePath, expectedManifestString)\n}\n\n@Suite(\n    .serialized,\n    .tags(\n        .TestSize.large,\n        .Feature.Command.Package.General,\n    ),\n)\nstruct PackageCommandTests {\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func noParameters(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        let stdout = try await executeSwiftPackage(\n            AbsolutePath.root,\n            configuration: config,\n            buildSystem: buildSystem,\n        ).stdout\n        #expect(stdout.contains(\"USAGE: swift package\"))\n    }\n\n    @Test(\n        .issue(\"rdar://131126477\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func usage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        await expectThrowsCommandExecutionError(\n            try await executeSwiftPackage(\n                nil,\n                configuration: config,\n                extraArgs: [\"-halp\"],\n                buildSystem: buildSystem,\n            )\n        ) { error in\n            #expect(error.stderr.contains(\"Usage: swift package\"))\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func seeAlso(\n        buildSystem: BuildSystemProvider.Kind,\n     ) async throws {\n        let config = BuildConfiguration.debug\n        let stdout = try await executeSwiftPackage(\n            AbsolutePath.root,\n            configuration: config,\n            extraArgs: [\"--help\"],\n            buildSystem: buildSystem,\n        ).stdout\n        #expect(stdout.contains(\"SEE ALSO: swift build, swift run, swift test \\n(Run this command without --help to see possible dynamic plugin commands.)\"))\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandDoesNotEmitDuplicateSymbols(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let duplicateSymbolRegex = try #require(duplicateSymbolRegex)\n\n        try await withTemporaryDirectory { tmpDir in\n            let (stdout, stderr) = try await executeSwiftPackage(\n                tmpDir,\n                extraArgs: [\"--help\"],\n                buildSystem: buildSystem,\n            )\n\n            #expect(!stdout.contains(duplicateSymbolRegex))\n            #expect(!stderr.contains(duplicateSymbolRegex))\n        }\n    }\n\n    @Test\n    func version() async throws {\n        try await withTemporaryDirectory { tmpDir in\n            let stdout = try await SwiftPM.Package.execute([\"--version\"]).stdout\n\n            let expectedRegex = try Regex(#\"Swift Package Manager -( \\w+ )?\\d+.\\d+.\\d+(-\\w+)?\"#)\n            #expect(stdout.contains(expectedRegex))\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandFailsSilentlyWhenFetchingPluginFails(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPlugin\") { fixturePath in // Contains only build-tool-plugins, therefore would not appear in available plugin commands.\n            let (stdout, _) = try await execute(\n                [\"--help\"],\n                packagePath: fixturePath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n\n            #expect(!stdout.contains(\"AVAILABLE PLUGIN COMMANDS:\"))\n            #expect(!stdout.contains(\"MySourceGenBuildToolPlugin\"))\n            #expect(!stdout.contains(\"MySourceGenPrebuildPlugin\"))\n        }\n    }\n\n    // Have to create empty package, as in CI, --help is invoked on swiftPM, causing test to fail\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandDisplaysNoAvailablePluginCommands(\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await testWithTemporaryDirectory { tmpPath in\n\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n\n            try localFileSystem.writeFileContents(\n                packageDir.appending(components: \"Package.swift\"),\n                string:\n                    \"\"\"\n                    // swift-tools-version: 5.9\n                    // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n                    import PackageDescription\n\n                    let package = Package(\n                        name: \"foo\"\n                    )\n                    \"\"\"\n            )\n            let (stdout, _) = try await execute(\n                [\"--help\"],\n                packagePath: packageDir,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(!stdout.contains(\"AVAILABLE PLUGIN COMMANDS:\"))\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func commandDisplaysAvailablePluginCommands(\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library target, a plugin, and a local tool. It depends on a sample package which also has a tool.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            try localFileSystem.writeFileContents(\n                packageDir.appending(components: \"Package.swift\"),\n                string:\n                    \"\"\"\n                    // swift-tools-version: 5.9\n                    import PackageDescription\n                    let package = Package(\n                        name: \"MyPackage\",\n                        targets: [\n                            .plugin(\n                                name: \"MyPlugin\",\n                                capability: .command(\n                                    intent: .custom(verb: \"mycmd\", description: \"What is mycmd anyway?\")\n                                ),\n                                dependencies: [\n                                    .target(name: \"LocalBuiltTool\"),\n                                ]\n                            ),\n                            .executableTarget(\n                                name: \"LocalBuiltTool\"\n                            )\n                        ]\n                    )\n                    \"\"\"\n            )\n\n            try localFileSystem.writeFileContents(\n                packageDir.appending(components: \"Sources\", \"LocalBuiltTool\", \"main.swift\"),\n                string: #\"print(\"Hello\")\"#\n            )\n            try localFileSystem.writeFileContents(\n                packageDir.appending(components: \"Plugins\", \"MyPlugin\", \"plugin.swift\"),\n                string: \"\"\"\n                    import PackagePlugin\n                    import Foundation\n                    @main\n                    struct MyCommandPlugin: CommandPlugin {\n                        func performCommand(\n                            context: PluginContext,\n                            arguments: [String]\n                        ) throws {\n                            print(\"This is MyCommandPlugin.\")\n                        }\n                    }\n                    \"\"\"\n            )\n\n            let (stdout, _) = try await execute(\n                [\"--help\"],\n                packagePath: packageDir,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n\n            #expect(stdout.contains(\"AVAILABLE PLUGIN COMMANDS:\"))\n            #expect(stdout.contains(\"mycmd\"))\n            #expect(stdout.contains(\"(plugin ‘MyPlugin’ in package ‘MyPackage’)\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.CompletionTool,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func completionTool(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        let stdout = try await execute(\n            [\"completion-tool\", \"--help\"],\n            configuration: config,\n            buildSystem: buildSystem,\n        ).stdout\n        #expect(stdout.contains(\"OVERVIEW: Command to generate shell completions.\"))\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.Init,\n        ),\n    )\n    struct InitHelpUsageTests {\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initOverview(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            let stdout = try await execute(\n                [\"init\", \"--help\"],\n                configuration: config,\n                buildSystem: buildSystem,\n            ).stdout\n            #expect(stdout.contains(\"OVERVIEW: Initialize a new package\"))\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initUsage(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            let stdout = try await execute(\n                [\"init\", \"--help\"],\n                configuration: config,\n                buildSystem: buildSystem,\n            ).stdout\n            #expect(stdout.contains(\"USAGE: swift package init [--type <type>] \"))\n            #expect(stdout.contains(\" [--name <name>]\"))\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initOptionsHelp(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            let stdout = try await execute(\n                [\"init\", \"--help\"],\n                configuration: config,\n                buildSystem: buildSystem,\n            ).stdout\n            #expect(stdout.contains(\"OPTIONS:\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.Plugin,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func plugin(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        await expectThrowsCommandExecutionError(\n            try await execute(\n                [\"plugin\"],\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n        ) { error in\n            #expect(error.stderr.contains(\"error: Missing expected plugin command\"))\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func unknownOption(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        await expectThrowsCommandExecutionError(\n            try await execute(\n                [\"--foo\"],\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n        ) { error in\n            #expect(error.stderr.contains(\"error: Unknown option '--foo'\"))\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func unknownSubcommand(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/ExeTest\") { fixturePath in\n            await expectThrowsCommandExecutionError(\n                try await execute(\n                    [\"foo\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(error.stderr.contains(\"Unknown subcommand or plugin name ‘foo’\"))\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.Resolve,\n        ),\n    )\n    struct ResolveCommandTests {\n        @Suite(\n            .tags(\n                .Feature.NetRc,\n            ),\n        )\n        struct NetRcTests {\n            @Test(\n                arguments: SupportedBuildSystemOnAllPlatforms,\n            )\n            func netrc(\n                buildSystem: BuildSystemProvider.Kind,\n            ) async throws {\n                let config = BuildConfiguration.debug\n                try await fixture(name: \"DependencyResolution/External/XCFramework\") { fixturePath in\n                    // --enable-netrc flag\n                    try await execute(\n                        [\"resolve\", \"--enable-netrc\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // --disable-netrc flag\n                    try await execute(\n                        [\"resolve\", \"--disable-netrc\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // --enable-netrc and --disable-netrc flags\n                    await expectThrowsCommandExecutionError(\n                        try await execute(\n                            [\"resolve\", \"--enable-netrc\", \"--disable-netrc\"],\n                            packagePath: fixturePath,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                    ) { error in\n                        #expect(\n                            error.stderr.contains(\n                                \"Value to be set with flag '--disable-netrc' had already been set with flag '--enable-netrc'\"\n                            )\n                        )\n                    }\n                }\n            }\n\n            @Test(\n                arguments: SupportedBuildSystemOnAllPlatforms,\n            )\n            func netrcFile(\n                buildSystem: BuildSystemProvider.Kind,\n            ) async throws {\n                let config = BuildConfiguration.debug\n                try await fixture(name: \"DependencyResolution/External/XCFramework\") { fixturePath in\n                    let fs = localFileSystem\n                    let netrcPath = fixturePath.appending(\".netrc\")\n                    try fs.writeFileContents(\n                        netrcPath,\n                        string: \"machine mymachine.labkey.org login user@labkey.org password mypassword\"\n                    )\n\n                    // valid .netrc file path\n                    try await execute(\n                        [\"resolve\", \"--netrc-file\", netrcPath.pathString],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // valid .netrc file path with --disable-netrc option\n                    await expectThrowsCommandExecutionError(\n                        try await execute(\n                            [\"resolve\", \"--netrc-file\", netrcPath.pathString, \"--disable-netrc\"],\n                            packagePath: fixturePath,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                    ) { error in\n                        #expect(\n                            error.stderr.contains(\"'--disable-netrc' and '--netrc-file' are mutually exclusive\")\n                        )\n                    }\n\n                    // invalid .netrc file path\n                    let errorRegex = try Regex(#\".* Did not find netrc file at ([A-Z]:\\\\|\\/)foo.*\"#)\n                    await expectThrowsCommandExecutionError(\n                        try await execute(\n                            [\"resolve\", \"--netrc-file\", \"/foo\"],\n                            packagePath: fixturePath,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                    ) { error in\n                        #expect(error.stderr.contains(errorRegex))\n                    }\n\n                    // invalid .netrc file path with --disable-netrc option\n                    await expectThrowsCommandExecutionError(\n                        try await execute(\n                            [\"resolve\", \"--netrc-file\", \"/foo\", \"--disable-netrc\"],\n                            packagePath: fixturePath,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                    ) { error in\n                        #expect(\n                            error.stderr.contains(\"'--disable-netrc' and '--netrc-file' are mutually exclusive\")\n                        )\n                    }\n                }\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.Reset,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func enableDisableCache(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n                let repositoriesPath = packageRoot.appending(components: \".build\", \"repositories\")\n                let cachePath = fixturePath.appending(\"cache\")\n                let repositoriesCachePath = cachePath.appending(\"repositories\")\n\n                do {\n                    // Remove .build and cache folder\n                    _ = try await execute(\n                        [\"reset\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    try localFileSystem.removeFileTree(cachePath)\n\n                    try await execute(\n                        [\"resolve\", \"--enable-dependency-cache\", \"--cache-path\", cachePath.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // we have to check for the prefix here since the hash value changes because spm sees the `prefix`\n                    // directory `/var/...` as `/private/var/...`.\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesCachePath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n\n                    // Remove .build folder\n                    _ = try await execute(\n                        [\"reset\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // Perform another cache this time from the cache\n                    _ = try await execute(\n                        [\"resolve\", \"--enable-dependency-cache\", \"--cache-path\", cachePath.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n\n                    // Remove .build and cache folder\n                    _ = try await execute(\n                        [\"reset\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    try localFileSystem.removeFileTree(cachePath)\n\n                    // Perform another fetch\n                    _ = try await execute(\n                        [\"resolve\", \"--enable-dependency-cache\", \"--cache-path\", cachePath.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesCachePath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n                }\n\n                do {\n                    // Remove .build and cache folder\n                    _ = try await execute(\n                        [\"reset\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    try localFileSystem.removeFileTree(cachePath)\n\n                    try await execute(\n                        [\"resolve\", \"--disable-dependency-cache\", \"--cache-path\", cachePath.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // we have to check for the prefix here since the hash value changes because spm sees the `prefix`\n                    // directory `/var/...` as `/private/var/...`.\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n                    #expect(!localFileSystem.exists(repositoriesCachePath))\n                }\n\n                do {\n                    // Remove .build and cache folder\n                    _ = try await execute(\n                        [\"reset\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    try localFileSystem.removeFileTree(cachePath)\n\n                    let (_, _) = try await execute(\n                        [\"resolve\", \"--enable-dependency-cache\", \"--cache-path\", cachePath.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // we have to check for the prefix here since the hash value changes because spm sees the `prefix`\n                    // directory `/var/...` as `/private/var/...`.\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesCachePath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n\n                    // Remove .build folder\n                    _ = try await execute(\n                        [\"reset\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // Perform another cache this time from the cache\n                    _ = try await execute(\n                        [\"resolve\", \"--enable-dependency-cache\", \"--cache-path\", cachePath.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n\n                    // Remove .build and cache folder\n                    _ = try await execute(\n                        [\"reset\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    try localFileSystem.removeFileTree(cachePath)\n\n                    // Perform another fetch\n                    _ = try await execute(\n                        [\"resolve\", \"--enable-dependency-cache\", \"--cache-path\", cachePath.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesCachePath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n                }\n\n                do {\n                    // Remove .build and cache folder\n                    _ = try await execute(\n                        [\"reset\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    try localFileSystem.removeFileTree(cachePath)\n\n                    let (_, _) = try await execute(\n                        [\"resolve\", \"--disable-dependency-cache\", \"--cache-path\", cachePath.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n\n                    // we have to check for the prefix here since the hash value changes because spm sees the `prefix`\n                    // directory `/var/...` as `/private/var/...`.\n                    #expect(\n                        try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                            $0.hasPrefix(\"Foo-\")\n                        }\n                    )\n                    #expect(!localFileSystem.exists(repositoriesCachePath))\n                }\n            }\n        }\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func resolve(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n\n                // Check that `resolve` works.\n                _ = try await execute(\n                    [\"resolve\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let path = try SwiftPM.packagePath(for: \"Foo\", packageRoot: packageRoot)\n                #expect(try GitRepository(path: path).getTags() == [\"1.2.3\"])\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.Update,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func update(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n\n                // Perform an initial fetch.\n                _ = try await execute(\n                    [\"resolve\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                do {\n                    let checkoutPath = try SwiftPM.packagePath(for: \"Foo\", packageRoot: packageRoot)\n                    let checkoutRepo = GitRepository(path: checkoutPath)\n                    #expect(try checkoutRepo.getTags() == [\"1.2.3\"])\n                    _ = try checkoutRepo.revision(forTag: \"1.2.3\")\n                }\n\n                // update and retag the dependency, and update.\n                let repoPath = fixturePath.appending(\"Foo\")\n                let repo = GitRepository(path: repoPath)\n                try localFileSystem.writeFileContents(repoPath.appending(\"test\"), string: \"test\")\n                try repo.stageEverything()\n                try repo.commit()\n                try repo.tag(name: \"1.2.4\")\n\n                // we will validate it is there\n                let revision = try repo.revision(forTag: \"1.2.4\")\n\n                _ = try await execute(\n                    [\"update\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                do {\n                    // We shouldn't assume package path will be same after an update so ask again for it.\n                    let checkoutPath = try SwiftPM.packagePath(for: \"Foo\", packageRoot: packageRoot)\n                    let checkoutRepo = GitRepository(path: checkoutPath)\n                    // tag may not be there, but revision should be after update\n                    #expect(checkoutRepo.exists(revision: .init(identifier: revision)))\n                }\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.Reset,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func cache(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n                let repositoriesPath = packageRoot.appending(components: \".build\", \"repositories\")\n                let cachePath = fixturePath.appending(\"cache\")\n                let repositoriesCachePath = cachePath.appending(\"repositories\")\n\n                // Perform an initial fetch and populate the cache\n                _ = try await execute(\n                    [\"resolve\", \"--cache-path\", cachePath.pathString],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                // we have to check for the prefix here since the hash value changes because spm sees the `prefix`\n                // directory `/var/...` as `/private/var/...`.\n                #expect(\n                    try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                        $0.hasPrefix(\"Foo-\")\n                    }\n                )\n                #expect(\n                    try localFileSystem.getDirectoryContents(repositoriesCachePath).contains {\n                        $0.hasPrefix(\"Foo-\")\n                    }\n                )\n\n                // Remove .build folder\n                _ = try await execute(\n                    [\"reset\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                // Perform another cache this time from the cache\n                _ = try await execute(\n                    [\"resolve\", \"--cache-path\", cachePath.pathString],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(\n                    try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                        $0.hasPrefix(\"Foo-\")\n                    }\n                )\n\n                // Remove .build and cache folder\n                _ = try await execute(\n                    [\"reset\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                try localFileSystem.removeFileTree(cachePath)\n\n                // Perform another fetch\n                _ = try await execute(\n                    [\"resolve\", \"--cache-path\", cachePath.pathString],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(\n                    try localFileSystem.getDirectoryContents(repositoriesPath).contains {\n                        $0.hasPrefix(\"Foo-\")\n                    }\n                )\n                #expect(\n                    try localFileSystem.getDirectoryContents(repositoriesCachePath).contains {\n                        $0.hasPrefix(\"Foo-\")\n                    }\n                )\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.Describe,\n        ),\n    )\n    struct DescribeCommandTests {\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func describe(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/ExeTest\") { fixturePath in\n                // Generate the JSON description.\n                let (jsonOutput, _) = try await execute(\n                    [\"describe\", \"--type=json\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))\n\n                // Check that tests don't appear in the product memberships.\n                #expect(json[\"name\"]?.string == \"ExeTest\")\n                let jsonTarget0 = try #require(json[\"targets\"]?.array?[0])\n                #expect(jsonTarget0[\"product_memberships\"] == nil)\n                let jsonTarget1 = try #require(json[\"targets\"]?.array?[1])\n                #expect(jsonTarget1[\"product_memberships\"]?.array?[0].stringValue == \"Exe\")\n            }\n\n            try await fixture(name: \"CFamilyTargets/SwiftCMixed\") { fixturePath in\n                // Generate the JSON description.\n                let (jsonOutput, _) = try await execute(\n                    [\"describe\", \"--type=json\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))\n\n                // Check that the JSON description contains what we expect it to.\n                #expect(json[\"name\"]?.string == \"SwiftCMixed\")\n                let pathString = try #require(json[\"path\"]?.string)\n                try #expect(pathString.contains(Regex(#\"^([A-Z]:\\\\|\\/).*\"#)))\n                #expect(pathString.hasSuffix(AbsolutePath(\"/\" + fixturePath.basename).pathString))\n                #expect(json[\"targets\"]?.array?.count == 3)\n                let jsonTarget0 = try #require(json[\"targets\"]?.array?[0])\n                #expect(jsonTarget0[\"name\"]?.stringValue == \"SeaLib\")\n                #expect(jsonTarget0[\"c99name\"]?.stringValue == \"SeaLib\")\n                #expect(jsonTarget0[\"type\"]?.stringValue == \"library\")\n                #expect(jsonTarget0[\"module_type\"]?.stringValue == \"ClangTarget\")\n                let jsonTarget1 = try #require(json[\"targets\"]?.array?[1])\n                #expect(jsonTarget1[\"name\"]?.stringValue == \"SeaExec\")\n                #expect(jsonTarget1[\"c99name\"]?.stringValue == \"SeaExec\")\n                #expect(jsonTarget1[\"type\"]?.stringValue == \"executable\")\n                #expect(jsonTarget1[\"module_type\"]?.stringValue == \"SwiftTarget\")\n                #expect(jsonTarget1[\"product_memberships\"]?.array?[0].stringValue == \"SeaExec\")\n                let jsonTarget2 = try #require(json[\"targets\"]?.array?[2])\n                #expect(jsonTarget2[\"name\"]?.stringValue == \"CExec\")\n                #expect(jsonTarget2[\"c99name\"]?.stringValue == \"CExec\")\n                #expect(jsonTarget2[\"type\"]?.stringValue == \"executable\")\n                #expect(jsonTarget2[\"module_type\"]?.stringValue == \"ClangTarget\")\n                #expect(jsonTarget2[\"product_memberships\"]?.array?[0].stringValue == \"CExec\")\n\n                // Generate the text description.\n                let (textOutput, _) = try await execute(\n                    [\"describe\", \"--type=text\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let textChunks = textOutput.components(separatedBy: \"\\n\").reduce(into: [\"\"]) {\n                    chunks,\n                    line in\n                    // Split the text into chunks based on presence or absence of leading whitespace.\n                    if line.hasPrefix(\" \") == chunks[chunks.count - 1].hasPrefix(\" \") {\n                        chunks[chunks.count - 1].append(line + \"\\n\")\n                    } else {\n                        chunks.append(line + \"\\n\")\n                    }\n                }.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }\n\n                // Check that the text description contains what we expect it to.\n                // FIXME: This is a bit inelegant, but any errors are easy to reason about.\n                let textChunk0 = textChunks[0]\n                #expect(textChunk0.contains(\"Name: SwiftCMixed\"))\n                try #expect(textChunk0.contains(Regex(#\"Path: ([A-Z]:\\\\|\\/)\"#)))\n                #expect(textChunk0.contains(AbsolutePath(\"/\" + fixturePath.basename).pathString + \"\\n\"))\n                #expect(textChunk0.contains(\"Tools version: 4.2\"))\n                #expect(textChunk0.contains(\"Products:\"))\n                let textChunk1 = textChunks[1]\n                #expect(textChunk1.contains(\"Name: SeaExec\"))\n                #expect(textChunk1.contains(\"Type:\\n        Executable\"))\n                #expect(textChunk1.contains(\"Targets:\\n        SeaExec\"))\n                let textChunk2 = textChunks[2]\n                #expect(textChunk2.contains(\"Name: CExec\"))\n                #expect(textChunk2.contains(\"Type:\\n        Executable\"))\n                #expect(textChunk2.contains(\"Targets:\\n        CExec\"))\n                let textChunk3 = textChunks[3]\n                #expect(textChunk3.contains(\"Targets:\"))\n                let textChunk4 = textChunks[4]\n                #expect(textChunk4.contains(\"Name: SeaLib\"))\n                #expect(textChunk4.contains(\"C99name: SeaLib\"))\n                #expect(textChunk4.contains(\"Type: library\"))\n                #expect(textChunk4.contains(\"Module type: ClangTarget\"))\n                #expect(textChunk4.contains(\"Path: \\(RelativePath(\"Sources/SeaLib\").pathString)\"))\n                #expect(textChunk4.contains(\"Sources:\\n        Foo.c\"))\n                let textChunk5 = textChunks[5]\n                #expect(textChunk5.contains(\"Name: SeaExec\"))\n                #expect(textChunk5.contains(\"C99name: SeaExec\"))\n                #expect(textChunk5.contains(\"Type: executable\"))\n                #expect(textChunk5.contains(\"Module type: SwiftTarget\"))\n                #expect(textChunk5.contains(\"Path: \\(RelativePath(\"Sources/SeaExec\").pathString)\"))\n                #expect(textChunk5.contains(\"Sources:\\n        main.swift\"))\n                let textChunk6 = textChunks[6]\n                #expect(textChunk6.contains(\"Name: CExec\"))\n                #expect(textChunk6.contains(\"C99name: CExec\"))\n                #expect(textChunk6.contains(\"Type: executable\"))\n                #expect(textChunk6.contains(\"Module type: ClangTarget\"))\n                #expect(textChunk6.contains(\"Path: \\(RelativePath(\"Sources/CExec\").pathString)\"))\n                #expect(textChunk6.contains(\"Sources:\\n        main.c\"))\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.Describe\n            ),\n            .IssueWindowsRelativePathAssert,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func describeJson(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await withKnownIssue(isIntermittent: true) {\n                try await fixture(name: \"DependencyResolution/External/Simple/Bar\") { fixturePath in\n                    // Generate the JSON description.\n                    let (jsonOutput, _) = try await execute(\n                        [\"describe\", \"--type=json\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))\n\n                    // Check that product dependencies and memberships are as expected.\n                    #expect(json[\"name\"]?.string == \"Bar\")\n                    let jsonTarget = try #require(json[\"targets\"]?.array?[0])\n                    #expect(jsonTarget[\"product_memberships\"]?.array?[0].stringValue == \"Bar\")\n                    #expect(jsonTarget[\"product_dependencies\"]?.array?[0].stringValue == \"Foo\")\n                    #expect(jsonTarget[\"target_dependencies\"] == nil)\n                }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func describePackageUsingPlugins(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPlugin\") { fixturePath in\n                // Generate the JSON description.\n                let (stdout, _) = try await execute(\n                    [\"describe\", \"--type=json\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let json = try JSON(bytes: ByteString(encodingAsUTF8: stdout))\n\n                // Check the contents of the JSON.\n                #expect(try #require(json[\"name\"]).string == \"MySourceGenPlugin\")\n                let targetsArray = try #require(json[\"targets\"]?.array)\n                let buildToolPluginTarget = try #require(\n                    targetsArray.first { $0[\"name\"]?.string == \"MySourceGenBuildToolPlugin\" }?.dictionary\n                )\n                #expect(buildToolPluginTarget[\"module_type\"]?.string == \"PluginTarget\")\n                #expect(\n                    buildToolPluginTarget[\"plugin_capability\"]?.dictionary?[\"type\"]?.string == \"buildTool\"\n                )\n                let prebuildPluginTarget = try #require(\n                    targetsArray.first { $0[\"name\"]?.string == \"MySourceGenPrebuildPlugin\" }?.dictionary\n                )\n                #expect(prebuildPluginTarget[\"module_type\"]?.string == \"PluginTarget\")\n                #expect(\n                    prebuildPluginTarget[\"plugin_capability\"]?.dictionary?[\"type\"]?.string == \"buildTool\"\n                )\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.DumpPackage,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func dumpPackage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/DumpPackage\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"app\")\n            let (dumpOutput, _) = try await execute(\n                [\"dump-package\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            let json = try JSON(bytes: ByteString(encodingAsUTF8: dumpOutput))\n            guard case .dictionary(let contents) = json else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .string(let name)? = contents[\"name\"] else {\n                Issue.record(\"unexpected name\")\n                return\n            }\n            guard case .string(let defaultLocalization)? = contents[\"defaultLocalization\"] else {\n                Issue.record(\"unexpected defaultLocalization\")\n                return\n            }\n            guard case .array(let platforms)? = contents[\"platforms\"] else {\n                Issue.record(\"unexpected platforms\")\n                return\n            }\n            #expect(name == \"Dealer\")\n            #expect(defaultLocalization == \"en\")\n            #expect(\n                platforms == [\n                    .dictionary([\n                        \"platformName\": .string(\"macos\"),\n                        \"version\": .string(\"10.13\"),\n                        \"options\": .array([]),\n                    ]),\n                    .dictionary([\n                        \"platformName\": .string(\"ios\"),\n                        \"version\": .string(\"12.0\"),\n                        \"options\": .array([]),\n                    ]),\n                    .dictionary([\n                        \"platformName\": .string(\"tvos\"),\n                        \"version\": .string(\"12.0\"),\n                        \"options\": .array([]),\n                    ]),\n                    .dictionary([\n                        \"platformName\": .string(\"watchos\"),\n                        \"version\": .string(\"5.0\"),\n                        \"options\": .array([]),\n                    ]),\n                ]\n            )\n            // FIXME: We should also test dependencies and targets here.\n        }\n    }\n\n    @Test(\n        .requireSwift6_3,\n        .tags(\n            .Feature.Command.Package.DumpSymbolGraph,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8848\", relationship: .defect),\n        .IssueWindowsLongPath,\n        .requiresSymbolgraphExtract,\n        arguments: [BuildSystemProvider.Kind.swiftbuild],\n        [\n            true,\n            false,\n        ],\n    )\n    func dumpSymbolGraphFormatting(\n        buildSystem: BuildSystemProvider.Kind,\n        withPrettyPrinting: Bool,\n    ) async throws {\n        let config = BuildConfiguration.debug\n            try await fixture(\n                name: \"DependencyResolution/Internal/Simple\",\n                removeFixturePathOnDeinit: true\n            ) { fixturePath in\n                let symbolGraphExtractorPath = try UserToolchain.default.getSymbolGraphExtract()\n\n                let symbolGraphOutputDir = fixturePath.appending(\"symbolgraph\")\n\n                let arguments = withPrettyPrinting ? [\"--pretty-print\"] : []\n\n                let result = try await execute(\n                    [\"dump-symbol-graph\", \"--output-dir\", symbolGraphOutputDir.pathString] + arguments,\n                    packagePath: fixturePath,\n                    env: [\"SWIFT_SYMBOLGRAPH_EXTRACT\": symbolGraphExtractorPath.pathString],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let enumerator = try #require(\n                    FileManager.default.enumerator(\n                        at: URL(fileURLWithPath: fixturePath.pathString),\n                        includingPropertiesForKeys: nil\n                    )\n                )\n\n                var symbolGraphURLOptional: URL? = nil\n                while let element = enumerator.nextObject() {\n                    if let url = element as? URL, url.lastPathComponent == \"Bar.symbols.json\" {\n                        symbolGraphURLOptional = url\n                        break\n                    }\n                }\n\n                let symbolGraphURL = try #require(\n                    symbolGraphURLOptional,\n                    \"Failed to extract symbol graph: \\(result.stdout)\\n\\(result.stderr)\"\n                )\n                let symbolGraphData = try Data(contentsOf: symbolGraphURL)\n\n                // Double check that it's a valid JSON\n                #expect(throws: Never.self) {\n                    try JSONSerialization.jsonObject(with: symbolGraphData)\n                }\n\n                let JSONText = String(decoding: symbolGraphData, as: UTF8.self)\n                if withPrettyPrinting {\n                    #expect(JSONText.components(separatedBy: .newlines).count > 1)\n                } else {\n                    #expect(JSONText.components(separatedBy: .newlines).count == 1)\n                }\n            }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.CompletionTool,\n        ),\n    )\n    struct CompletionToolCommandTests {\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func completionToolListSnippets(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/Plugins/PluginsAndSnippets\") { fixturePath in\n                let result = try await execute(\n                    [\"completion-tool\", \"list-snippets\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.stdout == \"ContainsMain\\nImportsProductTarget\\nMySnippet\\nmain\\n\")\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func completionToolListDependencies(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Complex\") { fixturePath in\n                let result = try await execute(\n                    [\"completion-tool\", \"list-dependencies\"],\n                    packagePath: fixturePath.appending(\"deck-of-playing-cards-local\"),\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.stdout == \"playingcard\\nfisheryates\\n\")\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func completionToolListExecutables(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n                let result = try await execute(\n                    [\"completion-tool\", \"list-executables\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.stdout == \"exec1\\nexec2\\n\")\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func completionToolListExecutablesDifferentNames(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/DifferentProductTargetName\") { fixturePath in\n                let result = try await execute(\n                    [\"completion-tool\", \"list-executables\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.stdout == \"Foo\\n\")\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.ShowTraits,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func showTraits(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/ShowTraits\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"app\")\n            var (textOutput, _) = try await execute(\n                [\"show-traits\", \"--format=text\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(textOutput.contains(\"trait1 - this trait is the default in app (default)\"))\n            #expect(textOutput.contains(\"trait2 - this trait is not the default in app\"))\n            #expect(!textOutput.contains(\"trait3\"))\n\n            var (jsonOutput, _) = try await execute(\n                [\"show-traits\", \"--format=json\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            var json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))\n            guard case .array(let contents) = json else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n\n            #expect(3 == contents.count)\n\n            guard case let first = contents.first else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .dictionary(let `default`) = first else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            #expect(`default`[\"name\"]?.stringValue ==  \"default\")\n            guard case .array(let enabledTraits) = `default`[\"enabledTraits\"] else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            #expect(enabledTraits.count == 1)\n            let firstEnabledTrait = enabledTraits[0]\n            #expect(firstEnabledTrait.stringValue == \"trait1\")\n\n            guard case let second = contents[1] else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .dictionary(let trait1) = second else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            #expect(trait1[\"name\"]?.stringValue ==  \"trait1\")\n\n            guard case let third = contents[2] else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .dictionary(let trait2) = third else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            #expect(trait2[\"name\"]?.stringValue ==  \"trait2\")\n\n            // Show traits for the dependency based on its package id\n            (textOutput, _) = try await execute(\n                [\"show-traits\", \"--package-id=deck-of-playing-cards\", \"--format=text\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(!textOutput.contains(\"trait1 - this trait is the default in app (default)\"))\n            #expect(!textOutput.contains(\"trait2 - this trait is not the default in app\"))\n            #expect(textOutput.contains(\"trait3\"))\n\n            (jsonOutput, _) = try await execute(\n                [\"show-traits\", \"--package-id=deck-of-playing-cards\", \"--format=json\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))\n            guard case .array(let contents) = json else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n\n            #expect(1 == contents.count)\n\n            guard case let first = contents.first else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .dictionary(let trait3) = first else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            #expect(trait3[\"name\"]?.stringValue ==  \"trait3\")\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.ShowExecutables,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func showExecutables(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/ShowExecutables\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"app\")\n            let (textOutput, _) = try await execute(\n                [\"show-executables\", \"--format=flatlist\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(textOutput.contains(\"dealer\\n\"))\n            #expect(textOutput.contains(\"deck (deck-of-playing-cards)\\n\"))\n\n            let (jsonOutput, _) = try await execute(\n                [\"show-executables\", \"--format=json\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))\n            guard case .array(let contents) = json else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n\n            #expect(2 == contents.count)\n\n            guard case let first = contents.first else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .dictionary(let dealer) = first else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .string(let dealerName)? = dealer[\"name\"] else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            #expect(dealerName == \"dealer\")\n            if case .string(let package)? = dealer[\"package\"] {\n                Issue.record(\"unexpected package for dealer (should be unset): \\(package)\")\n                return\n            }\n\n            guard case let last = contents.last else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .dictionary(let deck) = last else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            guard case .string(let deckName)? = deck[\"name\"] else {\n                Issue.record(\"unexpected result\")\n                return\n            }\n            #expect(deckName == \"deck\")\n            if case .string(let package)? = deck[\"package\"] {\n                #expect(\"deck-of-playing-cards\" == package)\n            } else {\n                Issue.record(\"missing package for deck\")\n                return\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.ShowDependencies,\n        ),\n    )\n    struct ShowDependenciesCommandTests {\n        @Test(\n            .tags(\n                .Feature.Command.Package.ShowDependencies,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func showDependencies(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Complex\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"app\")\n                let (textOutput, _) = try await execute(\n                    [\"show-dependencies\", \"--format=text\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(textOutput.contains(\"FisherYates@1.2.3\"))\n\n                let (jsonOutput, _) = try await execute(\n                    [\"show-dependencies\", \"--format=json\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))\n                guard case .dictionary(let contents) = json else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                guard case .string(let name)? = contents[\"name\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(name == \"Dealer\")\n                guard case .string(let path)? = contents[\"path\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                let actual = try resolveSymlinks(try AbsolutePath(validating: path))\n                let expected = try resolveSymlinks(packageRoot)\n                #expect(actual == expected)\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.ShowDependencies,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func showDependenciesWithTraits(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Traits\") { fixturePath in\n                let packageRoot = fixturePath.appending(\"Example\")\n                let (textOutput, _) = try await execute(\n                    [\"show-dependencies\", \"--format=text\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(textOutput.contains(\"(traits: Package3Trait3)\"))\n\n                let (jsonOutput, _) = try await execute(\n                    [\"show-dependencies\", \"--format=json\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))\n                guard case .dictionary(let contents) = json else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                guard case .string(let name)? = contents[\"name\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(name == \"TraitsExample\")\n\n                // verify the traits JSON entry lists each of the traits in the fixture\n                guard case .array(let traitsProperty)? = contents[\"traits\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(traitsProperty.contains(.string(\"Package1\")))\n                #expect(traitsProperty.contains(.string(\"Package2\")))\n                #expect(traitsProperty.contains(.string(\"Package3\")))\n                #expect(traitsProperty.contains(.string(\"Package4\")))\n                #expect(traitsProperty.contains(.string(\"BuildCondition1\")))\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.ShowDependencies,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func showDependenciesWithTraitsGuardingDependencies(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Traits\") { fixturePath in\n                let packageRoot = fixturePath.appending(\"PackageConditionalDeps\")\n\n                // Test output with default traits\n                let (textOutputDefault, _) = try await execute(\n                    [\"show-dependencies\", \"--format=text\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(textOutputDefault.contains(\"Package1@\"))\n                #expect(!textOutputDefault.contains(\"Package2\"))\n\n                let (jsonOutputDefault, _) = try await execute(\n                    [\"show-dependencies\", \"--format=json\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let jsonDefault = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutputDefault))\n                guard case .dictionary(let contents) = jsonDefault else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                guard case .string(let name)? = contents[\"name\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(name == \"PackageConditionalDeps\")\n\n                guard case .array(let traitsProperty)? = contents[\"traits\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(traitsProperty.contains(.string(\"EnablePackage1Dep\")))\n\n                // Test output with default traits disabled\n                let (textOutputDefaultDisabled, _) = try await execute(\n                    [\"show-dependencies\", \"--disable-default-traits\", \"--format=text\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(textOutputDefaultDisabled.contains(\"No external dependencies found\"))\n                #expect(!textOutputDefaultDisabled.contains(\"Package1\"))\n                #expect(!textOutputDefaultDisabled.contains(\"Package2\"))\n\n                let (jsonOutputDefaultDisabled, _) = try await execute(\n                    [\"show-dependencies\", \"--disable-default-traits\", \"--format=json\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let jsonDefaultDisabled = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutputDefaultDisabled))\n                guard case .dictionary(let contents) = jsonDefaultDisabled else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                guard case .string(let name)? = contents[\"name\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(name == \"PackageConditionalDeps\")\n\n                guard case .array(let traitsProperty)? = contents[\"traits\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(traitsProperty.isEmpty)\n\n                // Test output with overridden trait configuration\n                let (textOutputPackage2Dep, _) = try await execute(\n                    [\"show-dependencies\", \"--traits\", \"EnablePackage2Dep\", \"--format=text\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(!textOutputPackage2Dep.contains(\"Package1\"))\n                #expect(textOutputPackage2Dep.contains(\"Package2@\"))\n\n                let (jsonOutputPackage2Dep, _) = try await execute(\n                    [\"show-dependencies\", \"--traits\", \"EnablePackage2Dep\", \"--format=json\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let jsonPackage2Dep = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutputPackage2Dep))\n                guard case .dictionary(let contents) = jsonPackage2Dep else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                guard case .string(let name)? = contents[\"name\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(name == \"PackageConditionalDeps\")\n\n                guard case .array(let traitsProperty)? = contents[\"traits\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(traitsProperty.contains(.string(\"EnablePackage2Dep\")))\n                #expect(!traitsProperty.contains(.string(\"EnablePackage1Dep\")))\n\n                // Test output with all traits enabled\n                let (textOutputAllTraits, _) = try await execute(\n                    [\"show-dependencies\", \"--enable-all-traits\", \"--format=text\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(textOutputAllTraits.contains(\"Package1@\"))\n                #expect(textOutputAllTraits.contains(\"Package2@\"))\n\n                let (jsonOutputAllTraits, _) = try await execute(\n                    [\"show-dependencies\", \"--enable-all-traits\", \"--format=json\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                let jsonAllTraits = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutputAllTraits))\n                guard case .dictionary(let contents) = jsonAllTraits else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                guard case .string(let name)? = contents[\"name\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(name == \"PackageConditionalDeps\")\n\n                guard case .array(let traitsProperty)? = contents[\"traits\"] else {\n                    Issue.record(\"unexpected result\")\n                    return\n                }\n                #expect(traitsProperty.contains(.string(\"EnablePackage2Dep\")))\n                #expect(traitsProperty.contains(.string(\"EnablePackage1Dep\")))\n\n            }\n        }\n\n        @Test\n        func showDependencies_dotFormat_sr12016() throws {\n            let fileSystem = InMemoryFileSystem(emptyFiles: [\n                \"/PackageA/Sources/TargetA/main.swift\",\n                \"/PackageB/Sources/TargetB/B.swift\",\n                \"/PackageC/Sources/TargetC/C.swift\",\n                \"/PackageD/Sources/TargetD/D.swift\",\n            ])\n\n            let manifestA = Manifest.createRootManifest(\n                displayName: \"PackageA\",\n                path: \"/PackageA\",\n                toolsVersion: .v5_3,\n                dependencies: [\n                    .fileSystem(path: \"/PackageB\"),\n                    .fileSystem(path: \"/PackageC\"),\n                ],\n                products: [\n                    try .init(name: \"exe\", type: .executable, targets: [\"TargetA\"])\n                ],\n                targets: [\n                    try .init(name: \"TargetA\", dependencies: [\"PackageB\", \"PackageC\"])\n                ]\n            )\n\n            let manifestB = Manifest.createFileSystemManifest(\n                displayName: \"PackageB\",\n                path: \"/PackageB\",\n                toolsVersion: .v5_3,\n                dependencies: [\n                    .fileSystem(path: \"/PackageC\"),\n                    .fileSystem(path: \"/PackageD\"),\n                ],\n                products: [\n                    try .init(name: \"PackageB\", type: .library(.dynamic), targets: [\"TargetB\"])\n                ],\n                targets: [\n                    try .init(name: \"TargetB\", dependencies: [\"PackageC\", \"PackageD\"])\n                ]\n            )\n\n            let manifestC = Manifest.createFileSystemManifest(\n                displayName: \"PackageC\",\n                path: \"/PackageC\",\n                toolsVersion: .v5_3,\n                dependencies: [\n                    .fileSystem(path: \"/PackageD\")\n                ],\n                products: [\n                    try .init(name: \"PackageC\", type: .library(.dynamic), targets: [\"TargetC\"])\n                ],\n                targets: [\n                    try .init(name: \"TargetC\", dependencies: [\"PackageD\"])\n                ]\n            )\n\n            let manifestD = Manifest.createFileSystemManifest(\n                displayName: \"PackageD\",\n                path: \"/PackageD\",\n                toolsVersion: .v5_3,\n                products: [\n                    try .init(name: \"PackageD\", type: .library(.dynamic), targets: [\"TargetD\"])\n                ],\n                targets: [\n                    try .init(name: \"TargetD\")\n                ]\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let graph = try loadModulesGraph(\n                fileSystem: fileSystem,\n                manifests: [manifestA, manifestB, manifestC, manifestD],\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n\n            let output = BufferedOutputByteStream()\n            SwiftPackageCommand.ShowDependencies.dumpDependenciesOf(\n                graph: graph,\n                rootPackage: graph.rootPackages[graph.rootPackages.startIndex],\n                mode: .dot,\n                on: output\n            )\n            let dotFormat = output.bytes.description\n\n            var alreadyPutOut: Set<Substring> = []\n            for line in dotFormat.split(whereSeparator: { $0.isNewline }) {\n                if alreadyPutOut.contains(line) {\n                    Issue.record(\"Same line was already put out: \\(line)\")\n                }\n                alreadyPutOut.insert(line)\n            }\n\n            #if os(Windows)\n                let pathSep = \"\\\\\"\n            #else\n                let pathSep = \"/\"\n            #endif\n            let expectedLines: [Substring] = [\n                \"\\\"\\(pathSep)PackageA\\\" [label=\\\"packagea\\\\n\\(pathSep)PackageA\\\\nunspecified\\\"]\",\n                \"\\\"\\(pathSep)PackageB\\\" [label=\\\"packageb\\\\n\\(pathSep)PackageB\\\\nunspecified\\\"]\",\n                \"\\\"\\(pathSep)PackageC\\\" [label=\\\"packagec\\\\n\\(pathSep)PackageC\\\\nunspecified\\\"]\",\n                \"\\\"\\(pathSep)PackageD\\\" [label=\\\"packaged\\\\n\\(pathSep)PackageD\\\\nunspecified\\\"]\",\n                \"\\\"\\(pathSep)PackageA\\\" -> \\\"\\(pathSep)PackageB\\\"\",\n                \"\\\"\\(pathSep)PackageA\\\" -> \\\"\\(pathSep)PackageC\\\"\",\n                \"\\\"\\(pathSep)PackageB\\\" -> \\\"\\(pathSep)PackageC\\\"\",\n                \"\\\"\\(pathSep)PackageB\\\" -> \\\"\\(pathSep)PackageD\\\"\",\n                \"\\\"\\(pathSep)PackageC\\\" -> \\\"\\(pathSep)PackageD\\\"\",\n            ]\n            for expectedLine in expectedLines {\n                #expect(\n                    alreadyPutOut.contains(expectedLine),\n                    \"Expected line is not found: \\(expectedLine)\"\n                )\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func showDependencies_redirectJsonOutput(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let root = tmpPath.appending(components: \"root\")\n                let dep = tmpPath.appending(components: \"dep\")\n\n                // Create root package.\n                let mainFilePath = root.appending(components: \"Sources\", \"root\", \"main.swift\")\n                try fs.writeFileContents(mainFilePath, string: \"\")\n                try fs.writeFileContents(\n                    root.appending(\"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version:4.2\n                        import PackageDescription\n                        let package = Package(\n                            name: \"root\",\n                            dependencies: [.package(url: \"../dep\", from: \"1.0.0\")],\n                            targets: [.target(name: \"root\", dependencies: [\"dep\"])]\n                        )\n                        \"\"\"\n                )\n\n                // Create dependency.\n                try fs.writeFileContents(\n                    dep.appending(components: \"Sources\", \"dep\", \"lib.swift\"),\n                    string: \"\"\n                )\n                try fs.writeFileContents(\n                    dep.appending(\"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version:4.2\n                        import PackageDescription\n                        let package = Package(\n                            name: \"dep\",\n                            products: [.library(name: \"dep\", targets: [\"dep\"])],\n                            targets: [.target(name: \"dep\")]\n                        )\n                        \"\"\"\n                )\n\n                do {\n                    let depGit = GitRepository(path: dep)\n                    try depGit.create()\n                    try depGit.stageEverything()\n                    try depGit.commit()\n                    try depGit.tag(name: \"1.0.0\")\n                }\n\n                let resultPath = root.appending(\"result.json\")\n                _ = try await execute(\n                    [\"show-dependencies\", \"--format\", \"json\", \"--output-path\", resultPath.pathString],\n                    packagePath: root,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                expectFileExists(at: resultPath)\n                let jsonOutput: Data = try fs.readFileContents(resultPath)\n                let json = try JSON(data: jsonOutput)\n\n                #expect(json[\"name\"]?.string == \"root\")\n                #expect(json[\"dependencies\"]?[0]?[\"name\"]?.string == \"dep\")\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.Init,\n        ),\n    )\n    struct InitCommandTests {\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initEmpty(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                try fs.createDirectory(path)\n                _ = try await execute(\n                    [\"init\", \"--type\", \"empty\"],\n                    packagePath: path,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                expectFileExists(at: path.appending(\"Package.swift\"))\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.Init,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initExecutable(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                try fs.createDirectory(path)\n                _ = try await execute(\n                    [\"init\", \"--type\", \"executable\"],\n                    packagePath: path,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                let manifest = path.appending(\"Package.swift\")\n                expectFileExists(at: manifest)\n\n                let contents: String = try localFileSystem.readFileContents(manifest)\n                let version = InitPackage.newPackageToolsVersion\n                let versionSpecifier = \"\\(version.major).\\(version.minor)\"\n                #expect(\n                    contents.hasPrefix(\n                        \"// swift-tools-version:\\(version < .v5_4 ? \"\" : \" \")\\(versionSpecifier)\\n\"\n                    )\n                )\n                #expect(contents.contains(#\".enableUpcomingFeature(\"ApproachableConcurrency\")\"#))\n\n                expectFileExists(at: manifest)\n                #expect(\n                    try fs.getDirectoryContents(path.appending(\"Sources\").appending((\"Foo\"))) == [\"Foo.swift\"]\n                )\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.Init,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initLibrary(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                try fs.createDirectory(path)\n                _ = try await execute(\n                    [\"init\"],\n                    packagePath: path,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                let manifest = path.appending(\"Package.swift\")\n                expectFileExists(at: manifest)\n\n                let contents: String = try localFileSystem.readFileContents(manifest)\n                #expect(contents.contains(#\".enableUpcomingFeature(\"ApproachableConcurrency\")\"#))\n\n                #expect(\n                    try fs.getDirectoryContents(path.appending(\"Sources\").appending(\"Foo\")) == [\"Foo.swift\"]\n                )\n                #expect(try fs.getDirectoryContents(path.appending(\"Tests\")).sorted() == [\"FooTests\"])\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.Init,\n                .Feature.PackageType.Executable,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initCustomNameExecutable(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                try fs.createDirectory(path)\n                _ = try await execute(\n                    [\"init\", \"--name\", \"CustomName\", \"--type\", \"executable\"],\n                    packagePath: path,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                let manifest = path.appending(\"Package.swift\")\n                expectFileExists(at: manifest)\n\n                let contents: String = try localFileSystem.readFileContents(manifest)\n                let version = InitPackage.newPackageToolsVersion\n                let versionSpecifier = \"\\(version.major).\\(version.minor)\"\n                #expect(\n                    contents.hasPrefix(\n                        \"// swift-tools-version:\\(version < .v5_4 ? \"\" : \" \")\\(versionSpecifier)\\n\"\n                    )\n                )\n                #expect(contents.contains(#\".enableUpcomingFeature(\"ApproachableConcurrency\")\"#))\n\n                #expect(\n                    try fs.getDirectoryContents(path.appending(\"Sources\").appending(\"CustomName\")) == [\n                        \"CustomName.swift\"\n                    ]\n                )\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.AddDependency,\n        ),\n    )\n    struct AddDependencyCommandTests {\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func packageAddDifferentDependencyWithSameURLTwiceFails(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"PackageB\")\n                try fs.createDirectory(path)\n\n                let url = \"https://github.com/swiftlang/swift-syntax.git\"\n                let manifest = \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"client\",\n                            dependencies: [\n                                .package(url: \"\\(url)\", exact: \"601.0.1\")\n                            ],\n                            targets: [ .target(name: \"client\", dependencies: [ \"library\" ]) ]\n                        )\n                    \"\"\"\n\n                try localFileSystem.writeFileContents(path.appending(\"Package.swift\"), string: manifest)\n\n                await expectThrowsCommandExecutionError(\n                    try await execute(\n                        [\"add-dependency\", url, \"--revision\", \"58e9de4e7b79e67c72a46e164158e3542e570ab6\"],\n                        packagePath: path,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(\n                        error.stderr.contains(\n                            \"error: unable to add dependency 'https://github.com/swiftlang/swift-syntax.git' because it already exists in the list of dependencies\"\n                        )\n                    )\n                }\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func packageAddSameDependencyURLTwiceHasNoEffect(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"PackageB\")\n                try fs.createDirectory(path)\n\n                let url = \"https://github.com/swiftlang/swift-syntax.git\"\n                let manifest = \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"client\",\n                            dependencies: [\n                                .package(url: \"\\(url)\", exact: \"601.0.1\"),\n                            ],\n                            targets: [ .target(name: \"client\", dependencies: [ \"library\" ]) ]\n                        )\n                    \"\"\"\n                let expected =\n                    #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", exact: \"601.0.1\"),\"#\n\n                try await executeAddURLDependencyAndAssert(\n                    packagePath: path,\n                    initialManifest: manifest,\n                    url: url,\n                    requirementArgs: [\"--exact\", \"601.0.1\"],\n                    expectedManifestString: expected,\n                    buildSystem: buildSystem,\n                )\n\n                try expectManifest(path) {\n                    let components = $0.components(separatedBy: expected)\n                    #expect(components.count == 2)\n                }\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func packageAddSameDependencyPathTwiceHasNoEffect(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"PackageB\")\n                try fs.createDirectory(path)\n\n                let depPath = \"../foo\"\n                let manifest = \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"client\",\n                            dependencies: [\n                                .package(path: \"\\(depPath)\")\n                            ],\n                            targets: [ .target(name: \"client\", dependencies: [ \"library\" ]) ]\n                        )\n                    \"\"\"\n\n                let expected = #\".package(path: \"../foo\")\"#\n                try await executeAddURLDependencyAndAssert(\n                    packagePath: path,\n                    initialManifest: manifest,\n                    url: depPath,\n                    requirementArgs: [\"--type\", \"path\"],\n                    expectedManifestString: expected,\n                    buildSystem: buildSystem,\n                )\n\n                try expectManifest(path) {\n                    let components = $0.components(separatedBy: expected)\n                    #expect(components.count == 2)\n                }\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func packageAddSameDependencyRegistryTwiceHasNoEffect(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"PackageB\")\n                try fs.createDirectory(path)\n\n                let registryId = \"foo\"\n                let manifest = \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"client\",\n                            dependencies: [\n                                .package(id: \"\\(registryId)\")\n                            ],\n                            targets: [ .target(name: \"client\", dependencies: [ \"library\" ]) ]\n                        )\n                    \"\"\"\n\n                let expected = #\".package(id: \"foo\", exact: \"1.0.0\")\"#\n                try await executeAddURLDependencyAndAssert(\n                    packagePath: path,\n                    initialManifest: manifest,\n                    url: registryId,\n                    requirementArgs: [\"--type\", \"registry\", \"--exact\", \"1.0.0\"],\n                    expectedManifestString: expected,\n                    buildSystem: buildSystem,\n                )\n\n                try expectManifest(path) {\n                    let components = $0.components(separatedBy: expected)\n                    #expect(components.count == 2)\n                }\n            }\n        }\n\n        struct PackageAddDependencyTestData {\n            let url: String\n            let requirementArgs: CLIArguments\n            let expectedManifestString: String\n        }\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            [\n                PackageAddDependencyTestData(\n                    // Test adding with --exact using the new helper\n                    url: \"https://github.com/swiftlang/swift-syntax.git\",\n                    requirementArgs: [\"--exact\", \"1.0.0\"],\n                    expectedManifestString:\n                        #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", exact: \"1.0.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --exact using the new helper\n                    url: \"https://github.com/swiftlang/swift-syntax.git\",\n                    requirementArgs: [\"--exact\", \"1.0.0\"],\n                    expectedManifestString:\n                        #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", exact: \"1.0.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --branch\n                    url: \"https://github.com/swiftlang/swift-syntax.git\",\n                    requirementArgs: [\"--branch\", \"main\"],\n                    expectedManifestString:\n                        #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", branch: \"main\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --revision\n                    url: \"https://github.com/swiftlang/swift-syntax.git\",\n                    requirementArgs: [\"--revision\", \"58e9de4e7b79e67c72a46e164158e3542e570ab6\"],\n                    expectedManifestString:\n                        #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", revision: \"58e9de4e7b79e67c72a46e164158e3542e570ab6\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --from\n                    url: \"https://github.com/swiftlang/swift-syntax.git\",\n                    requirementArgs: [\"--from\", \"1.0.0\"],\n                    expectedManifestString:\n                        #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", from: \"1.0.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --from and --to\n                    url: \"https://github.com/swiftlang/swift-syntax.git\",\n                    requirementArgs: [\"--from\", \"2.0.0\", \"--to\", \"2.2.0\"],\n                    expectedManifestString:\n                        #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", \"2.0.0\" ..< \"2.2.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --up-to-next-minor-from\n                    url: \"https://github.com/swiftlang/swift-syntax.git\",\n                    requirementArgs: [\"--up-to-next-minor-from\", \"1.0.0\"],\n                    expectedManifestString:\n                        #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", \"1.0.0\" ..< \"1.1.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --up-to-next-minor-from and --to\n                    url: \"https://github.com/swiftlang/swift-syntax.git\",\n                    requirementArgs: [\"--up-to-next-minor-from\", \"3.0.0\", \"--to\", \"3.3.0\"],\n                    expectedManifestString:\n                        #\".package(url: \"https://github.com/swiftlang/swift-syntax.git\", \"3.0.0\" ..< \"3.3.0\"),\"#,\n                ),\n            ],\n        )\n        func packageAddURLDependency(\n            buildSystem: BuildSystemProvider.Kind,\n            testData: PackageAddDependencyTestData,\n        ) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"PackageB\")\n                try fs.createDirectory(path)\n\n                let manifest = \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"client\",\n                            targets: [ .target(name: \"client\", dependencies: [ \"library\" ]) ]\n                        )\n                    \"\"\"\n\n                try await executeAddURLDependencyAndAssert(\n                    packagePath: path,\n                    initialManifest: manifest,\n                    url: testData.url,\n                    requirementArgs: testData.requirementArgs,\n                    expectedManifestString: testData.expectedManifestString,\n                    buildSystem: buildSystem,\n                )\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            [\n                PackageAddDependencyTestData(\n                    // Add absolute path dependency\n                    url: \"/absolute\",\n                    requirementArgs: [\"--type\", \"path\"],\n                    expectedManifestString: #\".package(path: \"/absolute\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Add relative path dependency (operates on the modified manifest)\n                    url: \"../relative\",\n                    requirementArgs: [\"--type\", \"path\"],\n                    expectedManifestString: #\".package(path: \"../relative\"),\"#,\n                ),\n            ],\n        )\n        func packageAddPathDependency(\n            buildSystem: BuildSystemProvider.Kind,\n            testData: PackageAddDependencyTestData,\n        ) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"PackageB\")\n                try fs.createDirectory(path)\n                let manifest = \"\"\"\n                    // swift-tools-version: 5.9\n                    import PackageDescription\n                    let package = Package(\n                        name: \"client\",\n                        targets: [ .target(name: \"client\", dependencies: [ \"library\" ]) ]\n                    )\n                    \"\"\"\n\n                try await executeAddURLDependencyAndAssert(\n                    packagePath: path,\n                    initialManifest: manifest,\n                    url: testData.url,\n                    requirementArgs: testData.requirementArgs,\n                    expectedManifestString: testData.expectedManifestString,\n                    buildSystem: buildSystem,\n                )\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            [\n                PackageAddDependencyTestData(\n                    // Test adding with --exact\n                    url: \"scope.name\",\n                    requirementArgs: [\"--type\", \"registry\", \"--exact\", \"1.0.0\"],\n                    expectedManifestString: #\".package(id: \"scope.name\", exact: \"1.0.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --from\n                    url: \"scope.name\",\n                    requirementArgs: [\"--type\", \"registry\", \"--from\", \"1.0.0\"],\n                    expectedManifestString: #\".package(id: \"scope.name\", from: \"1.0.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --from and --to\n                    url: \"scope.name\",\n                    requirementArgs: [\"--type\", \"registry\", \"--from\", \"2.0.0\", \"--to\", \"2.2.0\"],\n                    expectedManifestString: #\".package(id: \"scope.name\", \"2.0.0\" ..< \"2.2.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --up-to-next-minor-from\n                    url: \"scope.name\",\n                    requirementArgs: [\"--type\", \"registry\", \"--up-to-next-minor-from\", \"1.0.0\"],\n                    expectedManifestString: #\".package(id: \"scope.name\", \"1.0.0\" ..< \"1.1.0\"),\"#,\n                ),\n                PackageAddDependencyTestData(\n                    // Test adding with --up-to-next-minor-from and --to\n                    url: \"scope.name\",\n                    requirementArgs: [\n                        \"--type\", \"registry\", \"--up-to-next-minor-from\", \"3.0.0\", \"--to\", \"3.3.0\",\n                    ],\n                    expectedManifestString: #\".package(id: \"scope.name\", \"3.0.0\" ..< \"3.3.0\"),\"#,\n                ),\n            ],\n        )\n        func packageAddRegistryDependency(\n            buildSystem: BuildSystemProvider.Kind,\n            testData: PackageAddDependencyTestData,\n        ) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"PackageB\")\n                try fs.createDirectory(path)\n\n                let manifest = \"\"\"\n                    // swift-tools-version: 5.9\n                    import PackageDescription\n                    let package = Package(\n                        name: \"client\",\n                        targets: [ .target(name: \"client\", dependencies: [ \"library\" ]) ]\n                    )\n                    \"\"\"\n                try await executeAddURLDependencyAndAssert(\n                    packagePath: path,\n                    initialManifest: manifest,\n                    url: testData.url,\n                    requirementArgs: testData.requirementArgs,\n                    expectedManifestString: testData.expectedManifestString,\n                    buildSystem: buildSystem,\n                )\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.AddTarget,\n        ),\n    )\n    struct AddTargetCommandTests {\n        @Test(\n            .tags(\n                .Feature.TargetType.Executable,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func packageAddTarget(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"PackageB\")\n                try fs.createDirectory(path)\n\n                try fs.writeFileContents(\n                    path.appending(\"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"client\"\n                        )\n                        \"\"\"\n                )\n\n                let manifest = path.appending(\"Package.swift\")\n                expectFileExists(at: manifest)\n\n                // executable\n                do {\n                    _ = try await execute(\n                      [\"add-target\", \"client\", \"--dependencies\", \"MyLib\", \"OtherLib\", \"--type\", \"executable\"],\n                      packagePath: path,\n                      configuration: config,\n                      buildSystem: buildSystem,\n                    )\n\n                    let contents: String = try fs.readFileContents(manifest)\n\n                    #expect(contents.contains(#\"targets:\"#))\n                    #expect(contents.contains(#\".executableTarget\"#))\n                    #expect(contents.contains(#\"name: \"client\"\"#))\n                    #expect(contents.contains(#\"dependencies:\"#))\n                    #expect(contents.contains(#\"\"MyLib\"\"#))\n                    #expect(contents.contains(#\"\"OtherLib\"\"#))\n                }\n\n                // library\n                do {\n                    _ = try await execute(\n                      [\"add-target\", \"MyLib\", \"--type\", \"library\"],\n                      packagePath: path,\n                      configuration: config,\n                      buildSystem: buildSystem,\n                    )\n\n                    let contents: String = try fs.readFileContents(manifest)\n\n                    #expect(contents.contains(#\"targets:\"#))\n                    #expect(contents.contains(#\".target\"#))\n                    #expect(contents.contains(#\"name: \"MyLib\"\"#))\n\n                    expectFileExists(at: path.appending(components: [\"Sources\", \"MyLib\", \"MyLib.swift\"]))\n                }\n\n                // test\n                do {\n                    _ = try await execute(\n                      [\"add-target\", \"MyTest\", \"--type\", \"test\"],\n                      packagePath: path,\n                      configuration: config,\n                      buildSystem: buildSystem,\n                    )\n\n                    let contents: String = try fs.readFileContents(manifest)\n\n                    #expect(contents.contains(#\"targets:\"#))\n                    #expect(contents.contains(#\".test\"#))\n                    #expect(contents.contains(#\"name: \"MyTest\"\"#))\n\n                    expectFileExists(at: path.appending(components: [\"Tests\", \"MyTest\", \"MyTest.swift\"]))\n                }\n\n                // macro + swift-syntax dependency\n                do {\n                    _ = try await execute(\n                      [\"add-target\", \"MyMacro\", \"--type\", \"macro\"],\n                      packagePath: path,\n                      configuration: config,\n                      buildSystem: buildSystem,\n                    )\n\n                    let contents: String = try fs.readFileContents(manifest)\n\n                    #expect(contents.contains(#\"dependencies:\"#))\n                    #expect(contents.contains(#\".package(url: \"https://github.com/swiftlang/swift-syntax.git\"#))\n                    #expect(contents.contains(#\"targets:\"#))\n                    #expect(contents.contains(#\".macro\"#))\n                    #expect(contents.contains(#\"name: \"MyMacro\"\"#))\n                    #expect(contents.contains(#\"dependencies:\"#))\n                    #expect(contents.contains(#\"\"SwiftCompilerPlugin\"\"#))\n                    #expect(contents.contains(#\"\"SwiftSyntaxMacros\"\"#))\n\n                    expectFileExists(at: path.appending(components: [\"Sources\", \"MyMacro\", \"MyMacro.swift\"]))\n                    expectFileExists(at: path.appending(components: [\"Sources\", \"MyMacro\", \"ProvidedMacros.swift\"]))\n                }\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func packageAddTargetWithoutModuleSourcesFolder(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let manifest = tmpPath.appending(\"Package.swift\")\n                try fs.writeFileContents(\n                    manifest,\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"SimpleExecutable\",\n                            targets: [\n                                .executableTarget(name: \"SimpleExecutable\"),\n                            ]\n                        )\n                        \"\"\"\n                )\n\n                let sourcesFolder = tmpPath.appending(\"Sources\")\n                try fs.createDirectory(sourcesFolder)\n\n                try fs.writeFileContents(\n                    sourcesFolder.appending(\"main.swift\"),\n                    string:\n                        \"\"\"\n                        print(\"Hello World\")\n                        \"\"\"\n                )\n\n                _ = try await execute(\n                    [\"add-target\", \"client\"],\n                    packagePath: tmpPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                expectFileExists(at: manifest)\n                let contents: String = try fs.readFileContents(manifest)\n\n                #expect(contents.contains(#\"targets:\"#))\n                #expect(contents.contains(#\".executableTarget\"#))\n                #expect(contents.contains(#\"name: \"client\"\"#))\n\n                let fileStructure = try fs.getDirectoryContents(sourcesFolder)\n                #expect(fileStructure.sorted() == [\"SimpleExecutable\", \"client\"])\n                #expect(fs.isDirectory(sourcesFolder.appending(\"SimpleExecutable\")))\n                #expect(fs.isDirectory(sourcesFolder.appending(\"client\")))\n                #expect(\n                    try fs.getDirectoryContents(sourcesFolder.appending(\"SimpleExecutable\")) == [\"main.swift\"]\n                )\n                #expect(try fs.getDirectoryContents(sourcesFolder.appending(\"client\")) == [\"client.swift\"])\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func addTargetWithoutManifestThrows(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                await expectThrowsCommandExecutionError(\n                    try await execute(\n                        [\"add-target\", \"client\"],\n                        packagePath: tmpPath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(\n                        error.stderr.contains(\n                            \"error: Could not find Package.swift in this directory or any of its parent directories.\"\n                        )\n                    )\n                }\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.AddTargetDependency,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageAddTargetDependency(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await testWithTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"PackageB\")\n            try fs.createDirectory(path)\n\n            try fs.writeFileContents(\n                path.appending(\"Package.swift\"),\n                string:\n                    \"\"\"\n                    // swift-tools-version: 5.9\n                    import PackageDescription\n                    let package = Package(\n                        name: \"client\",\n                        targets: [ .target(name: \"library\") ]\n                    )\n                    \"\"\"\n            )\n            try localFileSystem.writeFileContents(\n                path.appending(components: \"Sources\", \"library\", \"library.swift\"),\n                string:\n                    \"\"\"\n                    public func Foo() { }\n                    \"\"\"\n            )\n\n            _ = try await execute(\n                [\"add-target-dependency\", \"--package\", \"other-package\", \"other-product\", \"library\"],\n                packagePath: path,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n\n            let manifest = path.appending(\"Package.swift\")\n            expectFileExists(at: manifest)\n            let contents: String = try fs.readFileContents(manifest)\n\n            #expect(contents.contains(#\".product(name: \"other-product\", package: \"other-package\"#))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.AddProduct,\n            .Feature.ProductType.StaticLibrary,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageAddProduct(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await testWithTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"PackageB\")\n            try fs.createDirectory(path)\n\n            try fs.writeFileContents(\n                path.appending(\"Package.swift\"),\n                string:\n                    \"\"\"\n                    // swift-tools-version: 5.9\n                    import PackageDescription\n                    let package = Package(\n                        name: \"client\"\n                    )\n                    \"\"\"\n            )\n\n            _ = try await execute(\n                [\"add-product\", \"MyLib\", \"--targets\", \"MyLib\", \"--type\", \"static-library\"],\n                packagePath: path,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n\n            let manifest = path.appending(\"Package.swift\")\n            expectFileExists(at: manifest)\n            let contents: String = try fs.readFileContents(manifest)\n\n            #expect(contents.contains(#\"products:\"#))\n            #expect(contents.contains(#\".library\"#))\n            #expect(contents.contains(#\"name: \"MyLib\"\"#))\n            #expect(contents.contains(#\"type: .static\"#))\n            #expect(contents.contains(#\"targets:\"#))\n            #expect(contents.contains(#\"\"MyLib\"\"#))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.AddSetting,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageAddSetting(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await testWithTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"PackageA\")\n            try fs.createDirectory(path)\n\n            try fs.writeFileContents(\n                path.appending(\"Package.swift\"),\n                string:\n                    \"\"\"\n                    // swift-tools-version: 6.2\n                    import PackageDescription\n                    let package = Package(\n                        name: \"A\",\n                        targets: [ .target(name: \"test\") ]\n                    )\n                    \"\"\"\n            )\n\n            _ = try await execute(\n                [\n                    \"add-setting\",\n                    \"--target\", \"test\",\n                    \"--swift\", \"languageMode=6\",\n                    \"--swift\", \"upcomingFeature=ExistentialAny:migratable\",\n                    \"--swift\", \"experimentalFeature=TrailingCommas\",\n                    \"--swift\", \"StrictMemorySafety\",\n                ],\n                packagePath: path,\n                configuration: config,\n                buildSystem: buildSystem,\n\n            )\n\n            let manifest = path.appending(\"Package.swift\")\n            expectFileExists(at: manifest)\n            let contents: String = try fs.readFileContents(manifest)\n\n            #expect(contents.contains(#\"swiftSettings:\"#))\n            #expect(contents.contains(#\".swiftLanguageMode(.v6)\"#))\n            #expect(contents.contains(#\".enableUpcomingFeature(\"ExistentialAny:migratable\")\"#))\n            #expect(contents.contains(#\".enableExperimentalFeature(\"TrailingCommas\")\"#))\n            #expect(contents.contains(#\".strictMemorySafety()\"#))\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8774\", relationship: .defect),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8380\", relationship: .defect),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8416\", relationship: .defect),  // swift run linux issue with swift build,\n        .tags(\n            .Feature.Command.Package.Edit,\n            .Feature.Command.Package.Unedit,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageEditAndUnedit(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/PackageEdit\", createGitRepo: true) { fixturePath in\n            let fooPath = fixturePath.appending(\"foo\")\n            func build() async throws -> (stdout: String, stderr: String) {\n                return try await executeSwiftBuild(\n                    fooPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            }\n\n            // Put bar and baz in edit mode.\n            _ = try await execute(\n                [\"edit\", \"bar\", \"--branch\", \"bugfix\"],\n                packagePath: fooPath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            _ = try await execute(\n                [\"edit\", \"baz\", \"--branch\", \"bugfix\"],\n                packagePath: fooPath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n\n            // Path to the executable.\n            let binPath = try fooPath.appending(components: buildSystem.binPath(for: config))\n            let exec = [\n                binPath.appending(\"foo\").pathString\n            ]\n\n            // We should see it now in packages directory.\n            let editsPath = fooPath.appending(components: \"Packages\", \"bar\")\n            expectDirectoryExists(at: editsPath)\n\n            let bazEditsPath = fooPath.appending(components: \"Packages\", \"baz\")\n            expectDirectoryExists(at: bazEditsPath)\n            // Removing baz externally should just emit an warning and not a build failure.\n            try localFileSystem.removeFileTree(bazEditsPath)\n\n            // Do a modification in bar and build.\n            try localFileSystem.writeFileContents(\n                editsPath.appending(components: \"Sources\", \"bar.swift\"),\n                bytes: \"public let theValue = 88888\\n\"\n            )\n            let (_, stderr) = try await build()\n\n            #expect(\n                stderr.contains(\n                    \"dependency 'baz' was being edited but is missing; falling back to original checkout\"\n                )\n            )\n            // We should be able to see that modification now.\n            let processValue = try await AsyncProcess.checkNonZeroExit(arguments: exec)\n            #expect(processValue == \"88888\\(ProcessInfo.EOL)\")\n\n            // The branch of edited package should be the one we provided when putting it in edit mode.\n            let editsRepo = GitRepository(path: editsPath)\n            #expect(try editsRepo.currentBranch() == \"bugfix\")\n\n            // It shouldn't be possible to unedit right now because of uncommitted changes.\n            do {\n                _ = try await execute(\n                    [\"unedit\", \"bar\"],\n                    packagePath: fooPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                Issue.record(\"Unexpected unedit success\")\n            } catch {}\n\n            try editsRepo.stageEverything()\n            try editsRepo.commit()\n\n            // It shouldn't be possible to unedit right now because of unpushed changes.\n            do {\n                _ = try await execute(\n                    [\"unedit\", \"bar\"],\n                    packagePath: fooPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                Issue.record(\"Unexpected unedit success\")\n            } catch {}\n\n            // Push the changes.\n            try editsRepo.push(remote: \"origin\", branch: \"bugfix\")\n\n            // We should be able to unedit now.\n            _ = try await execute(\n                [\"unedit\", \"bar\"],\n                packagePath: fooPath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n\n            // Test editing with a path i.e. ToT development.\n            let bazTot = fixturePath.appending(\"tot\")\n            try await execute(\n                [\"edit\", \"baz\", \"--path\", bazTot.pathString],\n                packagePath: fooPath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(localFileSystem.exists(bazTot))\n            #expect(localFileSystem.isSymlink(bazEditsPath))\n\n            // Edit a file in baz ToT checkout.\n            let bazTotPackageFile = bazTot.appending(\"Package.swift\")\n            var content: String = try localFileSystem.readFileContents(bazTotPackageFile)\n            content += \"\\n// Edited.\"\n            try localFileSystem.writeFileContents(bazTotPackageFile, string: content)\n\n            // Unediting baz will remove the symlink but not the checked out package.\n            try await execute(\n                [\"unedit\", \"baz\"],\n                packagePath: fooPath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(localFileSystem.exists(bazTot))\n            #expect(!localFileSystem.isSymlink(bazEditsPath))\n\n            // Check that on re-editing with path, we don't make a new clone.\n            try await execute(\n                [\"edit\", \"baz\", \"--path\", bazTot.pathString],\n                packagePath: fooPath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(localFileSystem.isSymlink(bazEditsPath))\n            #expect(try localFileSystem.readFileContents(bazTotPackageFile) == content)\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8774\", relationship: .defect),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8380\", relationship: .defect),\n        .tags(\n            .Feature.Command.Package.Clean,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageClean(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n\n            // Build it.\n            try await executeSwiftBuild(\n                packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            let buildPath = packageRoot.appending(\".build\")\n            let binPath = try buildPath.appending(components: buildSystem.binPath(for: config, scratchPath: []))\n            let binFile = binPath.appending(executableName(\"Bar\"))\n            expectFileExists(at: binFile)\n            #expect(localFileSystem.isDirectory(buildPath))\n\n            // Clean, and check for removal of the build directory but not Packages.\n            _ = try await execute(\n                [\"clean\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            expectFileDoesNotExists(at: binFile)\n            // Clean again to ensure we get no error.\n            _ = try await execute(\n                [\"clean\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8774\", relationship: .defect),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8380\", relationship: .defect),\n        .tags(\n            .Feature.Command.Build,\n            .Feature.Command.Package.Reset,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageReset(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n\n            // Build it.\n            try await executeSwiftBuild(\n                packageRoot,\n                configuration: config,\n                buildSystem: buildSystem\n            )\n            let buildPath = packageRoot.appending(\".build\")\n            let binPath = try buildPath.appending(components: buildSystem.binPath(for: config, scratchPath: [], ))\n            let binFile = binPath.appending(executableName(\"Bar\"))\n            expectFileExists(at: binFile)\n            #expect(localFileSystem.isDirectory(buildPath))\n            // Clean, and check for removal of the build directory but not Packages.\n\n            _ = try await execute(\n                [\"clean\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            expectFileDoesNotExists(at: binFile)\n            try #expect(\n                !localFileSystem.getDirectoryContents(buildPath.appending(\"repositories\")).isEmpty\n            )\n\n            // Fully clean.\n            _ = try await execute(\n                [\"reset\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            #expect(!localFileSystem.isDirectory(buildPath))\n\n            // Test that we can successfully run reset again.\n            _ = try await execute(\n                [\"reset\"],\n                packagePath: packageRoot,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n        }\n    }\n\n    @Test(\n        .tags(.Feature.Command.Package.PurgeCache),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func purgeCacheWithoutPackage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            // Create a temporary directory without Package.swift\n            try await fixture(name: \"Miscellaneous\") { fixturePath in\n                let tempDir = fixturePath.appending(\"empty-dir-for-purge-test\")\n                try localFileSystem.createDirectory(tempDir, recursive: true)\n\n                // Use a unique temporary cache directory to avoid conflicts with parallel tests\n                try await withTemporaryDirectory(removeTreeOnDeinit: true) { cacheDir in\n                    let result = try await executeSwiftPackage(\n                        tempDir,\n                        configuration: config,\n                        extraArgs: [\"purge-cache\", \"--cache-path\", cacheDir.pathString],\n                        buildSystem: buildSystem\n                    )\n\n                    #expect(!result.stderr.contains(\"Could not find Package.swift\"))\n                }\n            }\n        } when: {\n            ProcessInfo.isHostAmazonLinux2() //rdar://134238535\n        }\n    }\n\n    @Test(\n        .tags(.Feature.Command.Package.PurgeCache),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func purgeCacheInPackageDirectory(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(\n            isIntermittent: ProcessInfo.isHostAmazonLinux2() // rdar://134238535\n        ) {\n            // Test that purge-cache works in a package directory and successfully purges caches\n            try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n\n                // Use a unique temporary cache directory for this test\n                try await withTemporaryDirectory(removeTreeOnDeinit: true) { tempDir in\n                    let cacheDir = tempDir.appending(\"test-cache\")\n                    let cacheArgs = [\"--cache-path\", cacheDir.pathString]\n\n                    // Resolve dependencies to populate cache\n                    // Note: This fixture uses local dependencies, so only manifest cache will be populated\n                    try await executeSwiftPackage(\n                        packageRoot,\n                        configuration: config,\n                        extraArgs: [\"resolve\"] + cacheArgs,\n                        buildSystem: buildSystem\n                    )\n\n                    // Verify manifest cache was populated\n                    let manifestsCache = cacheDir.appending(components: \"manifests\")\n                    expectDirectoryExists(at: manifestsCache)\n\n                    // Check for manifest.db file (main database file)\n                    let manifestDB = manifestsCache.appending(\"manifest.db\")\n                    let hasManifestDB = localFileSystem.exists(manifestDB)\n\n                    // Check for SQLite auxiliary files that might exist\n                    let manifestDBWAL = manifestsCache.appending(\"manifest.db-wal\")\n                    let manifestDBSHM = manifestsCache.appending(\"manifest.db-shm\")\n                    let hasAuxFiles = localFileSystem.exists(manifestDBWAL) || localFileSystem.exists(manifestDBSHM)\n\n                    // At least one manifest database file should exist\n                    #expect(hasManifestDB || hasAuxFiles, \"Manifest cache should be populated after resolve\")\n\n                    // Run purge-cache\n                    let result = try await executeSwiftPackage(\n                        packageRoot,\n                        configuration: config,\n                        extraArgs: [\"purge-cache\"] + cacheArgs,\n                        buildSystem: buildSystem\n                    )\n\n                    // Verify command succeeded\n                    #expect(!result.stderr.contains(\"Could not find Package.swift\"))\n\n                    // Verify manifest.db was removed (the purge implementation removes this file)\n                    expectFileDoesNotExists(at: manifestDB, \"manifest.db should be removed after purge\")\n\n                    // Note: SQLite auxiliary files (WAL/SHM) may or may not be removed depending on SQLite state\n                    // The important check is that the main database file is removed\n                }\n            }\n        } when: {\n            ProcessInfo.isHostAmazonLinux2()\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Package.Resolve,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func resolvingBranchAndRevision(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/PackageEdit\", createGitRepo: true) { fixturePath in\n            let fooPath = fixturePath.appending(\"foo\")\n\n            @discardableResult\n            func localExecute(_ args: String..., printError: Bool = true) async throws -> String {\n                return try await execute(\n                    [] + args,\n                    packagePath: fooPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                ).stdout\n            }\n\n            try await localExecute(\"update\")\n\n            let packageResolvedFile = fooPath.appending(\"Package.resolved\")\n            expectFileExists(at: packageResolvedFile)\n\n            // Update bar repo.\n            let barPath = fixturePath.appending(\"bar\")\n            let barRepo = GitRepository(path: barPath)\n            try barRepo.checkout(newBranch: \"YOLO\")\n            let yoloRevision = try barRepo.getCurrentRevision()\n\n            // Try to resolve `bar` at a branch.\n            do {\n                try await localExecute(\"resolve\", \"bar\", \"--branch\", \"YOLO\")\n                let resolvedPackagesStore = try ResolvedPackagesStore(\n                    packageResolvedFile: packageResolvedFile,\n                    workingDirectory: fixturePath,\n                    fileSystem: localFileSystem,\n                    mirrors: .init()\n                )\n                let state = ResolvedPackagesStore.ResolutionState.branch(\n                    name: \"YOLO\",\n                    revision: yoloRevision.identifier\n                )\n                let identity = PackageIdentity(path: barPath)\n                #expect(resolvedPackagesStore.resolvedPackages[identity]?.state == state)\n            }\n\n            // Try to resolve `bar` at a revision.\n            do {\n                try await localExecute(\"resolve\", \"bar\", \"--revision\", yoloRevision.identifier)\n                let resolvedPackagesStore = try ResolvedPackagesStore(\n                    packageResolvedFile: packageResolvedFile,\n                    workingDirectory: fixturePath,\n                    fileSystem: localFileSystem,\n                    mirrors: .init()\n                )\n                let state = ResolvedPackagesStore.ResolutionState.revision(yoloRevision.identifier)\n                let identity = PackageIdentity(path: barPath)\n                #expect(resolvedPackagesStore.resolvedPackages[identity]?.state == state)\n            }\n\n            // Try to resolve `bar` at a bad revision.\n            await #expect(throws: (any Error).self) {\n                try await localExecute(\"resolve\", \"bar\", \"--revision\", \"xxxxx\")\n            }\n        }\n    }\n\n    @Test(\n        // windows long path issue\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8774\", relationship: .defect),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8380\", relationship: .defect),\n        .tags(\n            .Feature.Command.Build,\n            .Feature.Command.Package.Resolve,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageResolved(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/PackageEdit\", createGitRepo: true) { fixturePath in\n            let fooPath = fixturePath.appending(\"foo\")\n            let binPath = try fooPath.appending(components: buildSystem.binPath(for: config))\n            let exec = [\n                binPath.appending(\"foo\").pathString\n            ]\n\n            // Build and check.\n            _ = try await executeSwiftBuild(\n                fooPath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            let value = try await AsyncProcess.checkNonZeroExit(arguments: exec).spm_chomp()\n            #expect(value == \"\\(5)\")\n\n\n            // Get path to `bar` checkout.\n            let barPath = try SwiftPM.packagePath(for: \"bar\", packageRoot: fooPath)\n\n            // Checks the content of checked out `bar.swift`.\n            func checkBar(_ value: Int, sourceLocation: SourceLocation = #_sourceLocation) throws {\n                let contents: String = try localFileSystem.readFileContents(\n                    barPath.appending(components: \"Sources\", \"bar.swift\")\n                )\n                #expect(\n                    contents.spm_chomp().hasSuffix(\"\\(value)\"),\n                    \"got \\(contents)\",\n                    sourceLocation: sourceLocation\n                )\n            }\n\n            // We should see a `Package.resolved` file now.\n            let packageResolvedFile = fooPath.appending(\"Package.resolved\")\n            expectFileExists(at: packageResolvedFile)\n\n            // Test `Package.resolved` file.\n            do {\n                let resolvedPackagesStore = try ResolvedPackagesStore(\n                    packageResolvedFile: packageResolvedFile,\n                    workingDirectory: fixturePath,\n                    fileSystem: localFileSystem,\n                    mirrors: .init()\n                )\n                #expect(resolvedPackagesStore.resolvedPackages.count == 2)\n                for pkg in [\"bar\", \"baz\"] {\n                    let path = try SwiftPM.packagePath(for: pkg, packageRoot: fooPath)\n                    let resolvedPackage = resolvedPackagesStore.resolvedPackages[\n                        PackageIdentity(path: path)\n                    ]!\n                    #expect(resolvedPackage.packageRef.identity == PackageIdentity(path: path))\n                    guard case .localSourceControl(let path) = resolvedPackage.packageRef.kind,\n                          path.pathString.hasSuffix(pkg)\n                    else {\n                        Issue.record(\"invalid resolved package location \\(path)\")\n                        return\n                    }\n                    switch resolvedPackage.state {\n                    case .version(let version, revision: _):\n                        #expect(version == \"1.2.3\")\n                    default:\n                        Issue.record(\"invalid `Package.resolved` state\")\n                    }\n                }\n            }\n\n            @discardableResult\n            func localExecute(_ args: String...) async throws -> String {\n                return try await execute(\n                    [] + args,\n                    packagePath: fooPath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                ).stdout\n            }\n\n            // Try to pin bar.\n            do {\n                try await localExecute(\"resolve\", \"bar\")\n                let resolvedPackagesStore = try ResolvedPackagesStore(\n                    packageResolvedFile: packageResolvedFile,\n                    workingDirectory: fixturePath,\n                    fileSystem: localFileSystem,\n                    mirrors: .init()\n                )\n                let identity = PackageIdentity(path: barPath)\n                // let resolvedPackageIdentify = try #require(resolvedPackagesStore.resolvedPackages[identity])\n                // switch resolvedPackageIdentify.state {\n                switch resolvedPackagesStore.resolvedPackages[identity]?.state {\n                case .version(let version, revision: _):\n                    #expect(version == \"1.2.3\")\n                default:\n                    Issue.record(\"invalid resolved package state\")\n                }\n            }\n\n            // Update bar repo.\n            do {\n                let barPath = fixturePath.appending(\"bar\")\n                let barRepo = GitRepository(path: barPath)\n                try localFileSystem.writeFileContents(\n                    barPath.appending(components: \"Sources\", \"bar.swift\"),\n                    bytes: \"public let theValue = 6\\n\"\n                )\n                try barRepo.stageEverything()\n                try barRepo.commit()\n                try barRepo.tag(name: \"1.2.4\")\n            }\n\n            // Running `package update` should update the package.\n            do {\n                try await localExecute(\"update\")\n                try checkBar(6)\n            }\n\n            // We should be able to revert to a older version.\n            do {\n                try await localExecute(\"resolve\", \"bar\", \"--version\", \"1.2.3\")\n                let resolvedPackagesStore = try ResolvedPackagesStore(\n                    packageResolvedFile: packageResolvedFile,\n                    workingDirectory: fixturePath,\n                    fileSystem: localFileSystem,\n                    mirrors: .init()\n                )\n                let identity = PackageIdentity(path: barPath)\n                switch resolvedPackagesStore.resolvedPackages[identity]?.state {\n                case .version(let version, revision: _):\n                    #expect(version == \"1.2.3\")\n                default:\n                    Issue.record(\"invalid resolved package state\")\n                }\n                try checkBar(5)\n            }\n\n            // Try resolving a dependency which is in edit mode.\n            do {\n                try await localExecute(\"edit\", \"bar\", \"--branch\", \"bugfix\")\n                await expectThrowsCommandExecutionError(try await localExecute(\"resolve\", \"bar\")) {\n                    error in\n                    #expect(error.stderr.contains(\"error: edited dependency 'bar' can't be resolved\"))\n                }\n                try await localExecute(\"unedit\", \"bar\")\n            }\n        }\n    }\n\n    @Test(\n        .issue(\n            \"error: Package.resolved file is corrupted or malformed, needs investigation\",\n            relationship: .defect\n        ),\n        .tags(\n            .Feature.Command.Package.Resolve,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func onlyUseVersionsFromResolvedFileFetchesWithExistingState(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        // try XCTSkipOnWindows(because: \"error: Package.resolved file is corrupted or malformed, needs investigation\")\n        func writeResolvedFile(\n            packageDir: AbsolutePath,\n            repositoryURL: String,\n            revision: String,\n            version: String\n        ) throws {\n            try localFileSystem.writeFileContents(\n                packageDir.appending(\"Package.resolved\"),\n                string:\n                    \"\"\"\n                    {\n                      \"object\": {\n                        \"pins\": [\n                          {\n                            \"package\": \"library\",\n                            \"repositoryURL\": \"\\(repositoryURL)\",\n                            \"state\": {\n                              \"branch\": null,\n                              \"revision\": \"\\(revision)\",\n                              \"version\": \"\\(version)\"\n                            }\n                          }\n                        ]\n                      },\n                      \"version\": 1\n                    }\n                    \"\"\"\n            )\n        }\n        try await withKnownIssue(isIntermittent: true) {\n            try await testWithTemporaryDirectory { tmpPath in\n                let packageDir = tmpPath.appending(components: \"library\")\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version:5.0\n                        import PackageDescription\n                        let package = Package(\n                            name: \"library\",\n                            products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                            targets: [ .target(name: \"library\") ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"library\", \"library.swift\"),\n                    string:\n                        \"\"\"\n                        public func Foo() { }\n                        \"\"\"\n                )\n\n                let depGit = GitRepository(path: packageDir)\n                try depGit.create()\n                try depGit.stageEverything()\n                try depGit.commit()\n                try depGit.tag(name: \"1.0.0\")\n\n                let initialRevision = try depGit.revision(forTag: \"1.0.0\")\n                let repositoryURL = #\"file://\\#(packageDir.pathString)\"#\n\n                let clientDir = tmpPath.appending(components: \"client\")\n                try localFileSystem.writeFileContents(\n                    clientDir.appending(\"Package.swift\"),\n                    string:\n                        #\"\"\"\n                        // swift-tools-version:5.0\n                        import PackageDescription\n                        let package = Package(\n                            name: \"client\",\n                            dependencies: [ .package(url: \"\\#(repositoryURL)\", from: \"1.0.0\") ],\n                            targets: [ .target(name: \"client\", dependencies: [ \"library\" ]) ]\n                        )\n                        \"\"\"#\n                )\n                try localFileSystem.writeFileContents(\n                    clientDir.appending(components: \"Sources\", \"client\", \"main.swift\"),\n                    string:\n                        \"\"\"\n                        print(\"hello\")\n                        \"\"\"\n                )\n\n                // Initial resolution with clean state.\n                do {\n                    try writeResolvedFile(\n                        packageDir: clientDir,\n                        repositoryURL: repositoryURL,\n                        revision: initialRevision,\n                        version: \"1.0.0\"\n                    )\n                    let (_, err) = try await execute(\n                        [\"resolve\", \"--only-use-versions-from-resolved-file\", \"-v\"],\n                        packagePath: clientDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(err.contains(\"Fetching \\(repositoryURL)\"))\n                }\n\n                // Make a change to the dependency and tag a new version.\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"library\", \"library.swift\"),\n                    string:\n                        \"\"\"\n                        public func Best() { }\n                        \"\"\"\n                )\n                try depGit.stageEverything()\n                try depGit.commit()\n                try depGit.tag(name: \"1.0.1\")\n                let updatedRevision = try depGit.revision(forTag: \"1.0.1\")\n\n                // Require new version but re-use existing state that hasn't fetched the latest revision, yet.\n                do {\n                    try writeResolvedFile(\n                        packageDir: clientDir,\n                        repositoryURL: repositoryURL,\n                        revision: updatedRevision,\n                        version: \"1.0.1\"\n                    )\n                    let (_, err) = try await execute(\n                        [\"resolve\", \"--only-use-versions-from-resolved-file\", \"-v\"],\n                        packagePath: clientDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(!err.contains(\"Fetching \\(repositoryURL)\"))\n                    #expect(err.contains(\"Updating \\(repositoryURL)\"))\n\n                }\n\n                // And again\n                do {\n                    let (_, err) = try await execute(\n                        [\"resolve\", \"--only-use-versions-from-resolved-file\", \"-v\"],\n                        packagePath: clientDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(!err.contains(\"Updating \\(repositoryURL)\"))\n                    #expect(!err.contains(\"Fetching \\(repositoryURL)\"))\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n            .Feature.Command.Package.Resolve,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func symlinkedDependency(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await testWithTemporaryDirectory { path in\n            let fs = localFileSystem\n            let root = path.appending(components: \"root\")\n            let dep = path.appending(components: \"dep\")\n            let depSym = path.appending(components: \"depSym\")\n\n            // Create root package.\n            try fs.writeFileContents(\n                root.appending(components: \"Sources\", \"root\", \"main.swift\"),\n                string: \"\"\n            )\n            try fs.writeFileContents(\n                root.appending(\"Package.swift\"),\n                string:\n                    \"\"\"\n                    // swift-tools-version:4.2\n                    import PackageDescription\n                    let package = Package(\n                        name: \"root\",\n                        dependencies: [.package(url: \"../depSym\", from: \"1.0.0\")],\n                        targets: [.target(name: \"root\", dependencies: [\"dep\"])]\n                    )\n\n                    \"\"\"\n            )\n\n            // Create dependency.\n            try fs.writeFileContents(dep.appending(components: \"Sources\", \"dep\", \"lib.swift\"), string: \"\")\n            try fs.writeFileContents(\n                dep.appending(\"Package.swift\"),\n                string:\n                    \"\"\"\n                    // swift-tools-version:4.2\n                    import PackageDescription\n                    let package = Package(\n                        name: \"dep\",\n                        products: [.library(name: \"dep\", targets: [\"dep\"])],\n                        targets: [.target(name: \"dep\")]\n                    )\n                    \"\"\"\n            )\n            do {\n                let depGit = GitRepository(path: dep)\n                try depGit.create()\n                try depGit.stageEverything()\n                try depGit.commit()\n                try depGit.tag(name: \"1.0.0\")\n            }\n\n            // Create symlink to the dependency.\n            try fs.createSymbolicLink(depSym, pointingAt: dep, relative: false)\n\n            _ = try await execute(\n                [\"resolve\"],\n                packagePath: root,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.Config,\n        ),\n    )\n    struct ConfigCommandTests {\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func mirrorConfigDeprecation(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { fixturePath in\n                localFileSystem.createEmptyFiles(\n                    at: fixturePath,\n                    files:\n                        \"/Sources/Foo/Foo.swift\",\n                    \"/Package.swift\"\n                )\n\n                let (_, stderr) = try await execute(\n                    [\n                        \"config\", \"set-mirror\", \"--package-url\", \"https://github.com/foo/bar\", \"--mirror-url\",\n                        \"https://mygithub.com/foo/bar\",\n                    ],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(\n                    stderr.contains(\"warning: '--package-url' option is deprecated; use '--original' instead\")\n                )\n                #expect(\n                    stderr.contains(\"warning: '--mirror-url' option is deprecated; use '--mirror' instead\")\n                )\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func mirrorConfig(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { fixturePath in\n                let fs = localFileSystem\n                let packageRoot = fixturePath.appending(\"Foo\")\n                let configOverride = fixturePath.appending(\"configoverride\")\n                let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(\n                    forRootPackage: packageRoot\n                )\n\n                fs.createEmptyFiles(\n                    at: packageRoot,\n                    files:\n                        \"/Sources/Foo/Foo.swift\",\n                    \"/Tests/FooTests/FooTests.swift\",\n                    \"/Package.swift\",\n                    \"anchor\"\n                )\n\n                // Test writing.\n                try await execute(\n                    [\n                        \"config\", \"set-mirror\", \"--original\", \"https://github.com/foo/bar\", \"--mirror\",\n                        \"https://mygithub.com/foo/bar\",\n                    ],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                try await execute(\n                    [\n                        \"config\", \"set-mirror\", \"--original\",\n                        \"git@github.com:swiftlang/swift-package-manager.git\", \"--mirror\",\n                        \"git@mygithub.com:foo/swift-package-manager.git\",\n                    ],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(fs.isFile(configFile))\n\n                // Test env override.\n                try await execute(\n                    [\n                        \"config\", \"set-mirror\", \"--original\", \"https://github.com/foo/bar\", \"--mirror\",\n                        \"https://mygithub.com/foo/bar\",\n                    ],\n                    packagePath: packageRoot,\n                    env: [\"SWIFTPM_MIRROR_CONFIG\": configOverride.pathString],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(fs.isFile(configOverride))\n                let content: String = try fs.readFileContents(configOverride)\n                #expect(content.contains(\"mygithub\"))\n\n                // Test reading.\n                var (stdout, _) = try await execute(\n                    [\"config\", \"get-mirror\", \"--original\", \"https://github.com/foo/bar\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.spm_chomp() == \"https://mygithub.com/foo/bar\")\n                (stdout, _) = try await execute(\n                    [\n                        \"config\", \"get-mirror\", \"--original\",\n                        \"git@github.com:swiftlang/swift-package-manager.git\",\n                    ],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.spm_chomp() == \"git@mygithub.com:foo/swift-package-manager.git\")\n\n                func check(stderr: String, _ block: () async throws -> Void) async {\n                    await expectThrowsCommandExecutionError(try await block()) { error in\n                        #expect(error.stderr.contains(stderr))\n                    }\n                }\n\n                await check(stderr: \"not found\\n\") {\n                    try await execute(\n                        [\"config\", \"get-mirror\", \"--original\", \"foo\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                }\n\n                // Test deletion.\n                try await execute(\n                    [\"config\", \"unset-mirror\", \"--original\", \"https://github.com/foo/bar\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                try await execute(\n                    [\n                        \"config\", \"unset-mirror\", \"--original\",\n                        \"git@mygithub.com:foo/swift-package-manager.git\",\n                    ],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                await check(stderr: \"not found\\n\") {\n                    try await execute(\n                        [\"config\", \"get-mirror\", \"--original\", \"https://github.com/foo/bar\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                }\n                await check(stderr: \"not found\\n\") {\n                    try await execute(\n                        [\n                            \"config\", \"get-mirror\", \"--original\",\n                            \"git@github.com:swiftlang/swift-package-manager.git\",\n                        ],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                }\n\n                await check(stderr: \"error: Mirror not found for 'foo'\\n\") {\n                    try await execute(\n                        [\"config\", \"unset-mirror\", \"--original\", \"foo\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                }\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.DumpPackage,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func mirrorSimple(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { fixturePath in\n                let fs = localFileSystem\n                let packageRoot = fixturePath.appending(\"MyPackage\")\n                let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(\n                    forRootPackage: packageRoot\n                )\n\n                fs.createEmptyFiles(\n                    at: packageRoot,\n                    files:\n                        \"/Sources/Foo/Foo.swift\",\n                    \"/Tests/FooTests/FooTests.swift\",\n                    \"/Package.swift\"\n                )\n\n                try fs.writeFileContents(\n                    packageRoot.appending(\"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.7\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            dependencies: [\n                                .package(url: \"https://scm.com/org/foo\", from: \"1.0.0\")\n                            ],\n                            targets: [\n                                .executableTarget(\n                                    name: \"MyTarget\",\n                                    dependencies: [\n                                        .product(name: \"Foo\", package: \"foo\")\n                                    ])\n                            ]\n                        )\n                        \"\"\"\n                )\n\n                try await execute(\n                    [\n                        \"config\", \"set-mirror\", \"--original\", \"https://scm.com/org/foo\", \"--mirror\",\n                        \"https://scm.com/org/bar\",\n                    ],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(fs.isFile(configFile))\n\n                let (stdout, _) = try await execute(\n                    [\"dump-package\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"https://scm.com/org/bar\"))\n                #expect(!stdout.contains(\"https://scm.com/org/foo\"))\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.DumpPackage,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func mirrorURLToRegistry(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { fixturePath in\n                let fs = localFileSystem\n                let packageRoot = fixturePath.appending(\"MyPackage\")\n                let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(\n                    forRootPackage: packageRoot\n                )\n\n                fs.createEmptyFiles(\n                    at: packageRoot,\n                    files:\n                        \"/Sources/Foo/Foo.swift\",\n                    \"/Tests/FooTests/FooTests.swift\",\n                    \"/Package.swift\"\n                )\n\n                try fs.writeFileContents(\n                    packageRoot.appending(\"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.7\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            dependencies: [\n                                .package(url: \"https://scm.com/org/foo\", from: \"1.0.0\")\n                            ],\n                            targets: [\n                                .executableTarget(\n                                    name: \"MyTarget\",\n                                    dependencies: [\n                                        .product(name: \"Foo\", package: \"foo\")\n                                    ])\n                            ]\n                        )\n                        \"\"\"\n                )\n\n                try await execute(\n                    [\"config\", \"set-mirror\", \"--original\", \"https://scm.com/org/foo\", \"--mirror\", \"org.bar\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(fs.isFile(configFile))\n\n                let (stdout, _) = try await execute(\n                    [\"dump-package\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"org.bar\"))\n                #expect(!stdout.contains(\"https://scm.com/org/foo\"))\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Package.DumpPackage,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func mirrorRegistryToURL(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { fixturePath in\n                let fs = localFileSystem\n                let packageRoot = fixturePath.appending(\"MyPackage\")\n                let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(\n                    forRootPackage: packageRoot\n                )\n\n                fs.createEmptyFiles(\n                    at: packageRoot,\n                    files:\n                        \"/Sources/Foo/Foo.swift\",\n                    \"/Tests/FooTests/FooTests.swift\",\n                    \"/Package.swift\"\n                )\n\n                try fs.writeFileContents(\n                    packageRoot.appending(\"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.7\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            dependencies: [\n                                .package(id: \"org.foo\", from: \"1.0.0\")\n                            ],\n                            targets: [\n                                .executableTarget(\n                                    name: \"MyTarget\",\n                                    dependencies: [\n                                        .product(name: \"Foo\", package: \"org.foo\")\n                                    ])\n                            ]\n                        )\n                        \"\"\"\n                )\n\n                try await execute(\n                    [\"config\", \"set-mirror\", \"--original\", \"org.foo\", \"--mirror\", \"https://scm.com/org/bar\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(fs.isFile(configFile))\n\n                let (stdout, _) = try await execute(\n                    [\"dump-package\"],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"https://scm.com/org/bar\"))\n                #expect(!stdout.contains(\"org.foo\"))\n            }\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .tags(\n            .Feature.Command.Package.DumpPackage,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageLoadingCommandPathResilience(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"ValidLayouts/SingleModule\") { fixturePath in\n            try await testWithTemporaryDirectory { tmpdir in\n                // Create fake `xcrun` and `sandbox-exec` commands.\n                let fakeBinDir = tmpdir\n                for fakeCmdName in [\"xcrun\", \"sandbox-exec\"] {\n                    let fakeCmdPath = fakeBinDir.appending(component: fakeCmdName)\n                    try localFileSystem.writeFileContents(\n                        fakeCmdPath,\n                        string:\n                            \"\"\"\n                            #!/bin/sh\n                            echo \"wrong \\(fakeCmdName) invoked\"\n                            exit 1\n                            \"\"\"\n                    )\n                    try localFileSystem.chmod(.executable, path: fakeCmdPath)\n                }\n\n                // Invoke `swift-package`, passing in the overriding `PATH` environment variable.\n                let packageRoot = fixturePath.appending(\"Library\")\n                let patchedPATH = fakeBinDir.pathString + \":\" + ProcessInfo.processInfo.environment[\"PATH\"]!\n                let (stdout, _) = try await execute(\n                    [\"dump-package\"],\n                    packagePath: packageRoot,\n                    env: [\"PATH\": patchedPATH],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                // Check that the wrong tools weren't invoked.  We can't just check the exit code because of fallbacks.\n                #expect(!stdout.contains(\"wrong xcrun invoked\"))\n                #expect(!stdout.contains(\"wrong sandbox-exec invoked\"))\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.Migrate,\n        ),\n    )\n    struct MigrateCommandTests {\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandHelp(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            let (stdout, _) = try await execute(\n                [\"migrate\", \"--help\"],\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n\n            // Global options are hidden.\n            #expect(!stdout.contains(\"--package-path\"))\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandNoFeatures(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await expectThrowsCommandExecutionError(\n                await execute(\n                    [\"migrate\"],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(\n                    error.stderr.contains(\"error: Missing expected argument '--to-feature <to-feature>'\")\n                )\n            }\n        }\n\n        @Test(\n            .supportsSupportedFeatures,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandUnknownFeature(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await expectThrowsCommandExecutionError(\n                await execute(\n                    [\"migrate\", \"--to-feature\", \"X\"],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(\n                    error.stderr.contains(\"error: Unsupported feature 'X'. Available features:\")\n                )\n            }\n        }\n\n        @Test(\n            .supportsSupportedFeatures,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandNonMigratableFeature(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await expectThrowsCommandExecutionError(\n                await execute(\n                    [\"migrate\", \"--to-feature\", \"StrictConcurrency\"],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                #expect(\n                    error.stderr.contains(\"error: Feature 'StrictConcurrency' is not migratable\")\n                )\n            }\n        }\n\n        struct MigrateCommandTestData {\n            let featureName: String\n            let expectedSummary: String\n        }\n        @Test(\n            .supportsSupportedFeatures,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/9006\",\n                relationship: .defect\n            ),\n            .IssueWindowsCannotSaveAttachment,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            [\n                // When updating these, make sure we keep testing both the singular and\n                // plural forms of the nouns in the summary.\n                MigrateCommandTestData(\n                    featureName: \"ExistentialAny\",\n                    expectedSummary: \"Applied 5 fix-its in 1 file\",\n                ),\n                MigrateCommandTestData(\n                    featureName: \"StrictMemorySafety\",\n                    expectedSummary: \"Applied 1 fix-it in 1 file\",\n                ),\n                MigrateCommandTestData(\n                    featureName: \"InferIsolatedConformances\",\n                    expectedSummary: \"Applied 3 fix-its in 2 files\",\n                ),\n            ],\n        )\n        func migrateCommand(\n            buildSystem: BuildSystemProvider.Kind,\n            testData: MigrateCommandTestData,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            let featureName = testData.featureName\n            let expectedSummary = testData.expectedSummary\n            try await fixture(name: \"SwiftMigrate/\\(featureName)Migration\") { fixturePath in\n                let sourcePaths: [AbsolutePath]\n                let fixedSourcePaths: [AbsolutePath]\n\n                do {\n                    let sourcesPath = fixturePath.appending(components: \"Sources\")\n                    let fixedSourcesPath = sourcesPath.appending(\"Fixed\")\n\n                    sourcePaths = try localFileSystem.getDirectoryContents(sourcesPath).filter { filename in\n                        filename.hasSuffix(\".swift\")\n                    }.sorted().map { filename in\n                        sourcesPath.appending(filename)\n                    }\n                    fixedSourcePaths = try localFileSystem.getDirectoryContents(fixedSourcesPath).filter {\n                        filename in\n                        filename.hasSuffix(\".swift\")\n                    }.sorted().map { filename in\n                        fixedSourcesPath.appending(filename)\n                    }\n                }\n\n                let (stdout, _) = try await execute(\n                    [\"migrate\", \"--to-feature\", featureName],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                #expect(sourcePaths.count == fixedSourcePaths.count)\n\n                for (sourcePath, fixedSourcePath) in zip(sourcePaths, fixedSourcePaths) {\n                    let sourceContent = try localFileSystem.readFileContents(sourcePath)\n                    let fixedSourceContent = try localFileSystem.readFileContents(fixedSourcePath)\n                    #expect(sourceContent == fixedSourceContent)\n                }\n\n                let regexMatch = try Regex(\"> \\(expectedSummary)\" + #\" \\([0-9]\\.[0-9]{1,3}s\\)\"#)\n                #expect(stdout.contains(regexMatch))\n            }\n        }\n\n        @Test(\n            .supportsSupportedFeatures,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/9006\",\n                relationship: .defect\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandWithBuildToolPlugins(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"SwiftMigrate/ExistentialAnyWithPluginMigration\") { fixturePath in\n                let (stdout, _) = try await execute(\n                    [\"migrate\", \"--to-feature\", \"ExistentialAny\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n\n                )\n\n                // Check the plugin target in the manifest wasn't updated\n                let manifestContent = try localFileSystem.readFileContents(\n                    fixturePath.appending(component: \"Package.swift\")\n                ).description\n                #expect(\n                    manifestContent.contains(\n                        \".plugin(name: \\\"Plugin\\\", capability: .buildTool, dependencies: [\\\"Tool\\\"]),\"\n                    )\n                )\n\n                // Building the package produces migration fix-its in both an authored and generated source file. Check we only applied fix-its to the hand-authored one.\n                let regexMatch = try Regex(\n                    \"> \\(\"Applied 3 fix-its in 1 file\")\" + #\" \\([0-9]\\.[0-9]{1,3}s\\)\"#\n                )\n                #expect(stdout.contains(regexMatch))\n            }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        @Test(\n            .supportsSupportedFeatures,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/9006\",\n                relationship: .defect\n            ),\n            .IssueWindowsCannotSaveAttachment,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandWhenDependencyBuildsForHostAndTarget(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"SwiftMigrate/ExistentialAnyWithCommonPluginDependencyMigration\") {\n                fixturePath in\n                let (stdout, _) = try await execute(\n                    [\"migrate\", \"--to-feature\", \"ExistentialAny\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n\n                )\n\n                // Even though the CommonLibrary dependency built for both the host and destination, we should only apply a single fix-it once to its sources.\n                let regexMatch = try Regex(\n                    \"> \\(\"Applied 1 fix-it in 1 file\")\" + #\" \\([0-9]\\.[0-9]{1,3}s\\)\"#\n                )\n                #expect(stdout.contains(regexMatch))\n            }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        @Test(\n            .supportsSupportedFeatures,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/9006\",\n                relationship: .defect\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandUpdateManifestSingleTarget(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"SwiftMigrate/UpdateManifest\") { fixturePath in\n                _ = try await execute(\n                    [\n                        \"migrate\",\n                        \"--to-feature\",\n                        \"ExistentialAny,InferIsolatedConformances\",\n                        \"--target\",\n                        \"A\",\n                    ],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n\n                )\n\n                let updatedManifest = try localFileSystem.readFileContents(\n                    fixturePath.appending(components: \"Package.swift\")\n                )\n                let expectedManifest = try localFileSystem.readFileContents(\n                    fixturePath.appending(components: \"Package.updated.targets-A.swift\")\n                )\n                #expect(updatedManifest == expectedManifest)\n            }\n        }\n\n        @Test(\n            .supportsSupportedFeatures,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/9006\",\n                relationship: .defect\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandUpdateManifest2Targets(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"SwiftMigrate/UpdateManifest\") { fixturePath in\n                _ = try await execute(\n                    [\n                        \"migrate\",\n                        \"--to-feature\",\n                        \"ExistentialAny,InferIsolatedConformances\",\n                        \"--target\",\n                        \"A,B\",\n                    ],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n\n                )\n\n                let updatedManifest = try localFileSystem.readFileContents(\n                    fixturePath.appending(components: \"Package.swift\")\n                )\n                let expectedManifest = try localFileSystem.readFileContents(\n                    fixturePath.appending(components: \"Package.updated.targets-A-B.swift\")\n                )\n                #expect(updatedManifest == expectedManifest)\n            }\n        }\n\n        @Test(\n            .supportsSupportedFeatures,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/9006\",\n                relationship: .defect\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func migrateCommandUpdateManifestWithErrors(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"SwiftMigrate/UpdateManifest\") { fixturePath in\n                try await expectThrowsCommandExecutionError(\n                    await execute(\n                        [\n                            \"migrate\", \"--to-feature\",\n                            \"ExistentialAny,InferIsolatedConformances,StrictMemorySafety\",\n                        ],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    // 'SwiftMemorySafety.strictMemorySafety' was introduced in 6.2.\n                    #expect(\n                        error.stderr.contains(\n                            \"\"\"\n                            error: Could not update manifest to enable requested features for target 'A' (package manifest version 5.8.0 is too old: please update to manifest version 6.2.0 or newer)\n                            error: Could not update manifest to enable requested features for target 'B' (package manifest version 5.8.0 is too old: please update to manifest version 6.2.0 or newer)\n                            error: Could not update manifest to enable requested features for target 'CannotFindSettings' (unable to find array literal for 'swiftSettings' argument). Please enable them manually by adding the following Swift settings to the target: '.enableUpcomingFeature(\"ExistentialAny\"), .enableUpcomingFeature(\"InferIsolatedConformances\"), .strictMemorySafety()'\n                            error: Could not update manifest to enable requested features for target 'CannotFindTarget' (unable to find target named 'CannotFindTarget' in package). Please enable them manually by adding the following Swift settings to the target: '.enableUpcomingFeature(\"ExistentialAny\"), .enableUpcomingFeature(\"InferIsolatedConformances\"), .strictMemorySafety()'\n                            \"\"\"\n                        )\n                    )\n                }\n\n                let updatedManifest = try localFileSystem.readFileContents(\n                    fixturePath.appending(components: \"Package.swift\")\n                )\n                let expectedManifest = try localFileSystem.readFileContents(\n                    fixturePath.appending(components: \"Package.updated.targets-all.swift\")\n                )\n                #expect(updatedManifest == expectedManifest)\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.BuildPlugin,\n        ),\n    )\n    struct BuildPluginTests {\n        @Test(\n            .IssueWindowsRelativePathAssert,\n            .requiresSwiftConcurrencySupport,\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func buildToolPlugin(\n            data: BuildData,\n        ) async throws {\n            try await withKnownIssue(isIntermittent: true) {\n                try await testBuildToolPlugin(data: data, staticStdlib: false)\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows && data.buildSystem == .swiftbuild\n            }\n        }\n\n        @Test(\n            .requiresStdlibSupport,\n            .requiresSwiftConcurrencySupport,\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func buildToolPluginWithStaticStdlib(\n            data: BuildData,\n        ) async throws {\n            try await testBuildToolPlugin(data: data, staticStdlib: true)\n        }\n\n        func testBuildToolPlugin(data: BuildData, staticStdlib: Bool) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a library target and a plugin.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            targets: [\n                                .target(\n                                    name: \"MyLibrary\",\n                                    plugins: [\n                                        \"MyPlugin\",\n                                    ]\n                                ),\n                                .plugin(\n                                    name: \"MyPlugin\",\n                                    capability: .buildTool()\n                                ),\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.swift\"),\n                    string:\n                        \"\"\"\n                        public func Foo() { }\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.foo\"),\n                    string:\n                        \"\"\"\n                        a file with a filename suffix handled by the plugin\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.bar\"),\n                    string:\n                        \"\"\"\n                        a file with a filename suffix not handled by the plugin\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Plugins\", \"MyPlugin\", \"plugin.swift\"),\n                    string:\n                        \"\"\"\n                        import PackagePlugin\n                        import Foundation\n                        @main\n                        struct MyBuildToolPlugin: BuildToolPlugin {\n                            func createBuildCommands(\n                                context: PluginContext,\n                                target: Target\n                            ) throws -> [Command] {\n                                // Expect the initial working directory for build tool plugins is the package directory.\n                                guard FileManager.default.currentDirectoryPath == context.package.directory.string else {\n                                    throw \"expected initial working directory ‘\\\\(FileManager.default.currentDirectoryPath)’\"\n                                }\n\n                                // Check that the package display name is what we expect.\n                                guard context.package.displayName == \"MyPackage\" else {\n                                    throw \"expected display name to be ‘MyPackage’ but found ‘\\\\(context.package.displayName)’\"\n                                }\n\n                                // Create and return a build command that uses all the `.foo` files in the target as inputs, so they get counted as having been handled.\n                                let fooFiles = target.sourceModule?.sourceFiles.compactMap{ $0.path.extension == \"foo\" ? $0.path : nil } ?? []\n                                #if os(Windows)\n                                let exec = \"echo\"\n                                #else\n                                let exec = \"/bin/echo\"\n                                #endif\n                                return [ .buildCommand(displayName: \"A command\", executable: Path(exec), arguments: fooFiles, inputFiles: fooFiles) ]\n                            }\n\n                        }\n                        extension String : Error {}\n                        \"\"\"\n                )\n\n                // Invoke it, and check the results.\n                let args = staticStdlib ? [\"--static-swift-stdlib\"] : []\n                let (stdout, stderr) = try await executeSwiftBuild(\n                    packageDir,\n                    configuration: data.config,\n                    extraArgs: args,\n                    buildSystem: data.buildSystem,\n                )\n                #expect(stdout.contains(\"Build complete!\"))\n\n                // We expect a warning about `library.bar` but not about `library.foo`.\n                let libraryFooPath = RelativePath(\"Sources/MyLibrary/library.foo\").pathString\n                #expect(!stderr.components(separatedBy: \"\\n\").contains { $0.contains(\"warning: \") && $0.contains(libraryFooPath) })\n                switch data.buildSystem {\n                case .native:\n                    #expect(stderr.contains(\"found 1 file(s) which are unhandled\"))\n                    #expect(stderr.contains(RelativePath(\"Sources/MyLibrary/library.bar\").pathString))\n                case .swiftbuild, .xcode:\n                    return\n                }\n            }\n        }\n\n        @Test(\n            .tags(\n              .Feature.Command.Build,\n              .Feature.PackageType.BuildToolPlugin\n            ),\n            .requiresSwiftConcurrencySupport,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func buildToolPluginFailure(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/Plugins/BuildToolPluginCompilationError\") { packageDir in\n                // Invoke it, and check the results.\n                await expectThrowsCommandExecutionError(\n                    try await executeSwiftBuild(\n                        packageDir,\n                        configuration: config,\n                        extraArgs: [\"-v\"],\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(error.stderr.contains(\"This is text from the plugin\"))\n                    #expect(error.stderr.contains(\"error: This is an error from the plugin\"))\n                    switch buildSystem {\n                        case .native:\n                            #expect(\n                                error.stderr.contains(\"build planning stopped due to build-tool plugin failures\")\n                            )\n                        case .swiftbuild, .xcode:\n                            break\n                    }\n                }\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.ArchiveSource,\n        ),\n    )\n    struct ArchiveSourceTests {\n        @Test(\n            arguments: [BuildSystemProvider.Kind.swiftbuild],\n            [1, 2, 5]\n        )\n        func archiveSourceWithoutArguments(\n            buildSystem: BuildSystemProvider.Kind,\n            numberOfExecutions: Int,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n\n                // Running without arguments or options, overwriting existing archive\n                for num in 1...numberOfExecutions {\n                    let (stdout, _) = try await execute(\n                        [\"archive-source\"],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(\n                        stdout.contains(\"Created Bar.zip\"),\n                        #\"Iteration \\#(num) of \\#(numberOfExecutions) failed --> stdout: \"\\#(stdout)\"\"#,\n                    )\n                }\n            }\n        }\n\n        @Test(\n            arguments: [BuildSystemProvider.Kind.swiftbuild],\n        )\n        func archiveSourceRunningWithOutputAsAbsolutePathWithingThePackageRoot(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n                // Running with output as absolute path within package root\n                let destination = packageRoot.appending(\"Bar-1.2.3.zip\")\n                let (stdout, _) = try await execute(\n                    [\"archive-source\", \"--output\", destination.pathString],\n                    packagePath: packageRoot,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"Created Bar-1.2.3.zip\"), #\"actual: \"\\#(stdout)\"\"#)\n            }\n        }\n\n        @Test(\n            arguments: [BuildSystemProvider.Kind.swiftbuild],\n        )\n        func archiveSourceRunningWithoutArgumentsOutsideThePackageRoot(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n                // Running with output is outside the package root\n                try await withTemporaryDirectory { tempDirectory in\n                    let destination = tempDirectory.appending(\"Bar-1.2.3.zip\")\n                    let (stdout, _) = try await execute(\n                        [\"archive-source\", \"--output\", destination.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(stdout.hasPrefix(\"Created \"), #\"actual: \"\\#(stdout)\"\"#)\n                    #expect(stdout.contains(\"Bar-1.2.3.zip\"), #\"actual: \"\\#(stdout)\"\"#)\n                }\n            }\n        }\n\n        @Test(\n            arguments: [BuildSystemProvider.Kind.swiftbuild],\n        )\n        func archiveSourceRunningWithoutArgumentsInNonPackageDirectoryProducesAnError(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n                // Running without arguments or options in non-package directory\n                await expectThrowsCommandExecutionError(\n                    try await execute(\n                        [\"archive-source\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(\n                        error.stderr.contains(\n                            \"error: Could not find Package.swift in this directory or any of its parent directories.\"\n                        ),\n                        #\"actual: \"\\#(stderr)\"\"#\n                    )\n                }\n            }\n        }\n\n        @Test(\n            arguments: [BuildSystemProvider.Kind.swiftbuild],\n        )\n        func archiveSourceRunningWithOuboutAsAbsolutePathToExistingDirectory(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n                // Running with output as absolute path to existing directory\n                let destination = AbsolutePath.root\n                await expectThrowsCommandExecutionError(\n                    try await execute(\n                        [\"archive-source\", \"--output\", destination.pathString],\n                        packagePath: packageRoot,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    let stderr = error.stderr\n                    #expect(\n                        stderr.contains(\"error: Couldn’t create an archive:\"),\n                        #\"actual: \"\\#(stderr)\"\"#\n                    )\n                }\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .Feature.Command.Package.CommandPlugin,\n        ),\n    )\n    struct CommandPluginTests {\n        struct CommandPluginTestData {\n            let packageCommandArgs: CLIArguments\n            let expectedStdout: [String]\n        }\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .requires(executable: \"sed\"),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            [\n                CommandPluginTestData(\n                    // Check that we can invoke the plugin with the \"plugin\" subcommand.\n                    packageCommandArgs: [\"plugin\", \"mycmd\"],\n                    expectedStdout: [\n                        \"This is MyCommandPlugin.\"\n                    ],\n                ),\n\n                CommandPluginTestData(\n                    // Check that we can also invoke it without the \"plugin\" subcommand.\n                    packageCommandArgs: [\"mycmd\"],\n                    expectedStdout: [\n                        \"This is MyCommandPlugin.\"\n                    ],\n                ),\n                CommandPluginTestData(\n                    // Testing listing the available command plugins.\n                    packageCommandArgs: [\"plugin\", \"--list\"],\n                    expectedStdout: [\n                        \"‘mycmd’ (plugin ‘MyPlugin’ in package ‘MyPackage’)\"\n                    ],\n                ),\n\n                CommandPluginTestData(\n                    // Check that the .docc file was properly vended to the plugin.\n                    packageCommandArgs: [\"mycmd\", \"--target\", \"MyLibrary\"],\n                    expectedStdout: [\n                        \"Sources/MyLibrary/library.swift: source\",\n                        \"Sources/MyLibrary/test.docc: unknown\",\n                    ],\n                ),\n                CommandPluginTestData(\n                    // Check that the .docc file was properly vended to the plugin.\n                    packageCommandArgs: [\"mycmd\", \"--target\", \"MyLibrary\"],\n                    expectedStdout: [\n                        \"Sources/MyLibrary/library.swift: source\",\n                        \"Sources/MyLibrary/test.docc: unknown\",\n                    ],\n                ),\n                CommandPluginTestData(\n                    // Check that information about the dependencies was properly sent to the plugin.\n                    packageCommandArgs: [\"mycmd\", \"--target\", \"MyLibrary\"],\n                    expectedStdout: [\n                        \"dependency HelperPackage: local\"\n                    ],\n                ),\n            ]\n        )\n        func commandPlugin(\n            buildSystem: BuildSystemProvider.Kind,\n            testData: CommandPluginTestData,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a library target, a plugin, and a local tool. It depends on a sample package which also has a tool.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            dependencies: [\n                                .package(name: \"HelperPackage\", path: \"VendoredDependencies/HelperPackage\")\n                            ],\n                            targets: [\n                                .target(\n                                    name: \"MyLibrary\",\n                                    dependencies: [\n                                        .product(name: \"HelperLibrary\", package: \"HelperPackage\")\n                                    ]\n                                ),\n                                .plugin(\n                                    name: \"MyPlugin\",\n                                    capability: .command(\n                                        intent: .custom(verb: \"mycmd\", description: \"What is mycmd anyway?\")\n                                    ),\n                                    dependencies: [\n                                        .target(name: \"LocalBuiltTool\"),\n                                        .target(name: \"LocalBinaryTool\"),\n                                        .product(name: \"RemoteBuiltTool\", package: \"HelperPackage\")\n                                    ]\n                                ),\n                                .binaryTarget(\n                                    name: \"LocalBinaryTool\",\n                                    path: \"Binaries/LocalBinaryTool.artifactbundle\"\n                                ),\n                                .executableTarget(\n                                    name: \"LocalBuiltTool\"\n                                )\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.swift\"),\n                    string:\n                        \"\"\"\n                        public func Foo() { }\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"test.docc\"),\n                    string:\n                        \"\"\"\n                        <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n                        <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"https://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n                        <plist version=\"1.0\">\n                        <dict>\n                            <key>CFBundleName</key>\n                            <string>sample</string>\n                        </dict>\n                        \"\"\"\n                )\n                let environment = Environment.current\n                let hostTriple = try UserToolchain(\n                    swiftSDK: .hostSwiftSDK(environment: environment),\n                    environment: environment\n                ).targetTriple\n                let hostTripleString =\n                    if hostTriple.isDarwin() {\n                        hostTriple.tripleString(forPlatformVersion: \"\")\n                    } else {\n                        hostTriple.tripleString\n                    }\n\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\n                        components: \"Binaries\",\n                        \"LocalBinaryTool.artifactbundle\",\n                        \"info.json\"\n                    ),\n                    string: \"\"\"\n                        {   \"schemaVersion\": \"1.0\",\n                            \"artifacts\": {\n                                \"LocalBinaryTool\": {\n                                    \"type\": \"executable\",\n                                    \"version\": \"1.2.3\",\n                                    \"variants\": [\n                                        {   \"path\": \"LocalBinaryTool.sh\",\n                                            \"supportedTriples\": [\"\\(hostTripleString)\"]\n                                        },\n                                    ]\n                                }\n                            }\n                        }\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"LocalBuiltTool\", \"main.swift\"),\n                    string: #\"print(\"Hello\")\"#\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Plugins\", \"MyPlugin\", \"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        import Foundation\n                        @main\n                        struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(\n                                context: PluginContext,\n                                arguments: [String]\n                            ) throws {\n                                print(\"This is MyCommandPlugin.\")\n\n                                // Print out the initial working directory so we can check it in the test.\n                                print(\"Initial working directory: \\\\(FileManager.default.currentDirectoryPath)\")\n\n                                // Check that we can find a binary-provided tool in the same package.\n                                print(\"Looking for LocalBinaryTool...\")\n                                let localBinaryTool = try context.tool(named: \"LocalBinaryTool\")\n                                print(\"... found it at \\\\(localBinaryTool.path)\")\n\n                                // Check that we can find a source-built tool in the same package.\n                                print(\"Looking for LocalBuiltTool...\")\n                                let localBuiltTool = try context.tool(named: \"LocalBuiltTool\")\n                                print(\"... found it at \\\\(localBuiltTool.path)\")\n\n                                // Check that we can find a source-built tool in another package.\n                                print(\"Looking for RemoteBuiltTool...\")\n                                let remoteBuiltTool = try context.tool(named: \"RemoteBuiltTool\")\n                                print(\"... found it at \\\\(remoteBuiltTool.path)\")\n\n                                // Check that we can find a tool in the toolchain.\n                                print(\"Looking for swiftc...\")\n                                let swiftc = try context.tool(named: \"swiftc\")\n                                print(\"... found it at \\\\(swiftc.path)\")\n\n                                // Check that we can find a standard tool.\n                                print(\"Looking for sed...\")\n                                let sed = try context.tool(named: \"sed\")\n                                print(\"... found it at \\\\(sed.path)\")\n\n                                // Extract the `--target` arguments.\n                                var argExtractor = ArgumentExtractor(arguments)\n                                let targetNames = argExtractor.extractOption(named: \"target\")\n                                let targets = try context.package.targets(named: targetNames)\n\n                                // Print out the source files so that we can check them.\n                                if let sourceFiles = targets.first(where: { $0.name == \"MyLibrary\" })?.sourceModule?.sourceFiles {\n                                    for file in sourceFiles {\n                                        print(\"  \\\\(file.path): \\\\(file.type)\")\n                                    }\n                                }\n\n                                // Print out the dependencies so that we can check them.\n                                for dependency in context.package.dependencies {\n                                    print(\"  dependency \\\\(dependency.package.displayName): \\\\(dependency.package.origin)\")\n                                }\n                            }\n                        }\n                        \"\"\"\n                )\n\n                // Create the sample vendored dependency package.\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\n                        components: \"VendoredDependencies\",\n                        \"HelperPackage\",\n                        \"Package.swift\"\n                    ),\n                    string: \"\"\"\n                        // swift-tools-version: 5.5\n                        import PackageDescription\n                        let package = Package(\n                            name: \"HelperPackage\",\n                            products: [\n                                .library(\n                                    name: \"HelperLibrary\",\n                                    targets: [\"HelperLibrary\"]\n                                ),\n                                .executable(\n                                    name: \"RemoteBuiltTool\",\n                                    targets: [\"RemoteBuiltTool\"]\n                                ),\n                            ],\n                            targets: [\n                                .target(\n                                    name: \"HelperLibrary\"\n                                ),\n                                .executableTarget(\n                                    name: \"RemoteBuiltTool\"\n                                ),\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\n                        components: \"VendoredDependencies\",\n                        \"HelperPackage\",\n                        \"Sources\",\n                        \"HelperLibrary\",\n                        \"library.swift\"\n                    ),\n                    string: \"public func Bar() { }\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\n                        components: \"VendoredDependencies\",\n                        \"HelperPackage\",\n                        \"Sources\",\n                        \"RemoteBuiltTool\",\n                        \"main.swift\"\n                    ),\n                    string: #\"print(\"Hello\")\"#\n                )\n\n                let (stdout, _) = try await execute(\n                    testData.packageCommandArgs,\n                    packagePath: packageDir,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                for expected in testData.expectedStdout {\n                    #expect(stdout.contains(expected))\n                }\n            }\n        }\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .requires(executable: \"sed\"),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginSpecialCases(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a library target, a plugin, and a local tool. It depends on a sample package which also has a tool.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            dependencies: [\n                                .package(name: \"HelperPackage\", path: \"VendoredDependencies/HelperPackage\")\n                            ],\n                            targets: [\n                                .target(\n                                    name: \"MyLibrary\",\n                                    dependencies: [\n                                        .product(name: \"HelperLibrary\", package: \"HelperPackage\")\n                                    ]\n                                ),\n                                .plugin(\n                                    name: \"MyPlugin\",\n                                    capability: .command(\n                                        intent: .custom(verb: \"mycmd\", description: \"What is mycmd anyway?\")\n                                    ),\n                                    dependencies: [\n                                        .target(name: \"LocalBuiltTool\"),\n                                        .target(name: \"LocalBinaryTool\"),\n                                        .product(name: \"RemoteBuiltTool\", package: \"HelperPackage\")\n                                    ]\n                                ),\n                                .binaryTarget(\n                                    name: \"LocalBinaryTool\",\n                                    path: \"Binaries/LocalBinaryTool.artifactbundle\"\n                                ),\n                                .executableTarget(\n                                    name: \"LocalBuiltTool\"\n                                )\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.swift\"),\n                    string:\n                        \"\"\"\n                        public func Foo() { }\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"test.docc\"),\n                    string:\n                        \"\"\"\n                        <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n                        <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"https://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n                        <plist version=\"1.0\">\n                        <dict>\n                            <key>CFBundleName</key>\n                            <string>sample</string>\n                        </dict>\n                        \"\"\"\n                )\n                let environment = Environment.current\n                let hostTriple = try UserToolchain(\n                    swiftSDK: .hostSwiftSDK(environment: environment),\n                    environment: environment\n                ).targetTriple\n                let hostTripleString =\n                    if hostTriple.isDarwin() {\n                        hostTriple.tripleString(forPlatformVersion: \"\")\n                    } else {\n                        hostTriple.tripleString\n                    }\n\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\n                        components: \"Binaries\",\n                        \"LocalBinaryTool.artifactbundle\",\n                        \"info.json\"\n                    ),\n                    string: \"\"\"\n                        {   \"schemaVersion\": \"1.0\",\n                            \"artifacts\": {\n                                \"LocalBinaryTool\": {\n                                    \"type\": \"executable\",\n                                    \"version\": \"1.2.3\",\n                                    \"variants\": [\n                                        {   \"path\": \"LocalBinaryTool.sh\",\n                                            \"supportedTriples\": [\"\\(hostTripleString)\"]\n                                        },\n                                    ]\n                                }\n                            }\n                        }\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"LocalBuiltTool\", \"main.swift\"),\n                    string: #\"print(\"Hello\")\"#\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Plugins\", \"MyPlugin\", \"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        import Foundation\n                        @main\n                        struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(\n                                context: PluginContext,\n                                arguments: [String]\n                            ) throws {\n                                print(\"This is MyCommandPlugin.\")\n\n                                // Print out the initial working directory so we can check it in the test.\n                                print(\"Initial working directory: \\\\(FileManager.default.currentDirectoryPath)\")\n\n                                // Check that we can find a binary-provided tool in the same package.\n                                print(\"Looking for LocalBinaryTool...\")\n                                let localBinaryTool = try context.tool(named: \"LocalBinaryTool\")\n                                print(\"... found it at \\\\(localBinaryTool.path)\")\n\n                                // Check that we can find a source-built tool in the same package.\n                                print(\"Looking for LocalBuiltTool...\")\n                                let localBuiltTool = try context.tool(named: \"LocalBuiltTool\")\n                                print(\"... found it at \\\\(localBuiltTool.path)\")\n\n                                // Check that we can find a source-built tool in another package.\n                                print(\"Looking for RemoteBuiltTool...\")\n                                let remoteBuiltTool = try context.tool(named: \"RemoteBuiltTool\")\n                                print(\"... found it at \\\\(remoteBuiltTool.path)\")\n\n                                // Check that we can find a tool in the toolchain.\n                                print(\"Looking for swiftc...\")\n                                let swiftc = try context.tool(named: \"swiftc\")\n                                print(\"... found it at \\\\(swiftc.path)\")\n\n                                // Check that we can find a standard tool.\n                                print(\"Looking for sed...\")\n                                let sed = try context.tool(named: \"sed\")\n                                print(\"... found it at \\\\(sed.path)\")\n\n                                // Extract the `--target` arguments.\n                                var argExtractor = ArgumentExtractor(arguments)\n                                let targetNames = argExtractor.extractOption(named: \"target\")\n                                let targets = try context.package.targets(named: targetNames)\n\n                                // Print out the source files so that we can check them.\n                                if let sourceFiles = targets.first(where: { $0.name == \"MyLibrary\" })?.sourceModule?.sourceFiles {\n                                    for file in sourceFiles {\n                                        print(\"  \\\\(file.path): \\\\(file.type)\")\n                                    }\n                                }\n\n                                // Print out the dependencies so that we can check them.\n                                for dependency in context.package.dependencies {\n                                    print(\"  dependency \\\\(dependency.package.displayName): \\\\(dependency.package.origin)\")\n                                }\n                            }\n                        }\n                        \"\"\"\n                )\n\n                // Create the sample vendored dependency package.\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\n                        components: \"VendoredDependencies\",\n                        \"HelperPackage\",\n                        \"Package.swift\"\n                    ),\n                    string: \"\"\"\n                        // swift-tools-version: 5.5\n                        import PackageDescription\n                        let package = Package(\n                            name: \"HelperPackage\",\n                            products: [\n                                .library(\n                                    name: \"HelperLibrary\",\n                                    targets: [\"HelperLibrary\"]\n                                ),\n                                .executable(\n                                    name: \"RemoteBuiltTool\",\n                                    targets: [\"RemoteBuiltTool\"]\n                                ),\n                            ],\n                            targets: [\n                                .target(\n                                    name: \"HelperLibrary\"\n                                ),\n                                .executableTarget(\n                                    name: \"RemoteBuiltTool\"\n                                ),\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\n                        components: \"VendoredDependencies\",\n                        \"HelperPackage\",\n                        \"Sources\",\n                        \"HelperLibrary\",\n                        \"library.swift\"\n                    ),\n                    string: \"public func Bar() { }\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\n                        components: \"VendoredDependencies\",\n                        \"HelperPackage\",\n                        \"Sources\",\n                        \"RemoteBuiltTool\",\n                        \"main.swift\"\n                    ),\n                    string: #\"print(\"Hello\")\"#\n                )\n\n                // Check that we get the expected error if trying to invoke a plugin with the wrong name.\n                do {\n                    await expectThrowsCommandExecutionError(\n                        try await execute(\n                            [\"my-nonexistent-cmd\"],\n                            packagePath: packageDir,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                    ) { error in\n                        // guard case SwiftPMError.executionFailure(_, _, let stderr) = error else {\n                        //     Issue.record(\"invalid error \\(error)\")\n                        //     return\n                        // }\n                        #expect(error.stderr.contains(\"Unknown subcommand or plugin name ‘my-nonexistent-cmd’\"))\n                    }\n                }\n                do {\n                    // Check that the initial working directory is what we expected.\n                    let workingDirectory = FileManager.default.currentDirectoryPath\n                    let (stdout, _) = try await execute(\n                        [\"mycmd\"],\n                        packagePath: packageDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(stdout.contains(\"Initial working directory: \\(workingDirectory)\"))\n                }\n            }\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func ambiguousCommandPlugin(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/Plugins/AmbiguousCommands\") { fixturePath in\n                let (stdout, _) = try await execute(\n                    [\"plugin\", \"--package\", \"A\", \"A\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"Hello A!\"))\n            }\n        }\n\n        // Test reporting of plugin diagnostic messages at different verbosity levels\n        @Test(\n            .tags(\n              .Feature.Command.Build,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .requiresSwiftConcurrencySupport,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/8180\",\n                relationship: .defect\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginDiagnostics(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n\n            // Match patterns for expected messages\n            let isEmpty = \"\"\n            let isOnlyPrint = \"command plugin: print\\n\"\n            let containsProgress = \"[diagnostics-stub] command plugin: Diagnostics.progress\"\n            let containsRemark = \"command plugin: Diagnostics.remark\"\n            let containsWarning = \"command plugin: Diagnostics.warning\"\n            let containsError = \"command plugin: Diagnostics.error\"\n\n                try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                    func runPlugin(\n                        flags: [String],\n                        diagnostics: [String],\n                        completion: (String, String) -> Void\n                    ) async throws {\n                        let (stdout, stderr) = try await execute(\n                            flags + [\"print-diagnostics\"] + diagnostics,\n                            packagePath: fixturePath,\n                            env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\": \"/this/is/a/bad/path\"],\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                        completion(stdout, stderr)\n                    }\n\n                    // Diagnostics.error causes SwiftPM to return a non-zero exit code, but we still need to check stdout and stderr\n                    func runPluginWithError(\n                        flags: [String],\n                        diagnostics: [String],\n                        completion: (String, String) -> Void\n                    ) async throws {\n                        await expectThrowsCommandExecutionError(\n                            try await execute(\n                                flags + [\"print-diagnostics\"] + diagnostics,\n                                packagePath: fixturePath,\n                                env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\": \"/this/is/a/bad/path\"],\n                                configuration: config,\n                                buildSystem: buildSystem,\n                            )\n                        ) { error in\n                            // guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = error else {\n                            //     Issue.record(\"invalid error \\(error)\")\n                            //     return\n                            // }\n                            completion(error.stdout, error.stderr)\n                        }\n                    }\n\n                    // Default verbosity\n                    //   - stdout is always printed\n                    //   - Diagnostics below 'warning' are suppressed\n\n                    try await runPlugin(flags: [], diagnostics: [\"print\"]) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        let filteredStderr = stderr.components(separatedBy: \"\\n\")\n                            .filter { !$0.contains(\"Unable to locate libSwiftScan\") }.joined(separator: \"\\n\")\n                        #expect(filteredStderr == isEmpty)\n                    }\n\n                    try await runPlugin(flags: [], diagnostics: [\"print\", \"progress\"]) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                    }\n\n                    try await runPlugin(flags: [], diagnostics: [\"print\", \"progress\", \"remark\"]) {\n                        stdout,\n                        stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                    }\n\n                    try await runPlugin(flags: [], diagnostics: [\"print\", \"progress\", \"remark\", \"warning\"]) {\n                        stdout,\n                        stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                        #expect(stderr.contains(containsWarning))\n                    }\n\n                    try await runPluginWithError(\n                        flags: [],\n                        diagnostics: [\"print\", \"progress\", \"remark\", \"warning\", \"error\"]\n                    ) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                        #expect(stderr.contains(containsWarning))\n                        #expect(stderr.contains(containsError))\n                    }\n\n                    // Quiet Mode\n                    //   - stdout is always printed\n                    //   - Diagnostics below 'error' are suppressed\n\n                    try await runPlugin(flags: [\"-q\"], diagnostics: [\"print\"]) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        let filteredStderr = stderr.components(separatedBy: \"\\n\")\n                            .filter { !$0.contains(\"Unable to locate libSwiftScan\") }.joined(separator: \"\\n\")\n                        #expect(filteredStderr == isEmpty)\n                    }\n\n                    try await runPlugin(flags: [\"-q\"], diagnostics: [\"print\", \"progress\"]) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                    }\n\n                    try await runPlugin(flags: [\"-q\"], diagnostics: [\"print\", \"progress\", \"remark\"]) {\n                        stdout,\n                        stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                    }\n\n                    try await runPlugin(\n                        flags: [\"-q\"],\n                        diagnostics: [\"print\", \"progress\", \"remark\", \"warning\"]\n                    ) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                    }\n\n                    try await runPluginWithError(\n                        flags: [\"-q\"],\n                        diagnostics: [\"print\", \"progress\", \"remark\", \"warning\", \"error\"]\n                    ) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                        #expect(!stderr.contains(containsRemark))\n                        #expect(!stderr.contains(containsWarning))\n                        #expect(stderr.contains(containsError))\n                    }\n\n                    // Verbose Mode\n                    //   - stdout is always printed\n                    //   - All diagnostics are printed\n                    //   - Substantial amounts of additional compiler output are also printed\n\n                    try await runPlugin(flags: [\"-v\"], diagnostics: [\"print\"]) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        // At this level stderr contains extra compiler output even if the plugin does not print diagnostics\n                    }\n\n                    try await runPlugin(flags: [\"-v\"], diagnostics: [\"print\", \"progress\"]) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                    }\n\n                    try await runPlugin(flags: [\"-v\"], diagnostics: [\"print\", \"progress\", \"remark\"]) {\n                        stdout,\n                        stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                        #expect(stderr.contains(containsRemark))\n                    }\n\n                    try await runPlugin(\n                        flags: [\"-v\"],\n                        diagnostics: [\"print\", \"progress\", \"remark\", \"warning\"]\n                    ) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                        #expect(stderr.contains(containsRemark))\n                        #expect(stderr.contains(containsWarning))\n                    }\n\n                    try await runPluginWithError(\n                        flags: [\"-v\"],\n                        diagnostics: [\"print\", \"progress\", \"remark\", \"warning\", \"error\"]\n                    ) { stdout, stderr in\n                        #expect(stdout == isOnlyPrint)\n                        #expect(stderr.contains(containsProgress))\n                        #expect(stderr.contains(containsRemark))\n                        #expect(stderr.contains(containsWarning))\n                        #expect(stderr.contains(containsError))\n                    }\n                }\n        }\n\n        // Test target builds requested by a command plugin\n        @Test(\n            .tags(\n              .Feature.Command.Run,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .IssueWindowsRelativePathAssert,\n            .requiresSwiftConcurrencySupport,\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func commandPluginTargetBuilds_BinaryIsBuildinDebugByDefault(\n            buildData: BuildData,\n        ) async throws {\n            let debugTarget = try buildData.buildSystem.binPath(for: .debug) + [executableName(\"placeholder\")]\n            let releaseTarget = try buildData.buildSystem.binPath(for: .release) + [executableName(\"placeholder\")]\n            try await withKnownIssue(isIntermittent: true) {\n                // By default, a plugin-requested build produces a debug binary\n                try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                    let _ = try await execute(\n                        [\"build-target\"],\n                        packagePath: fixturePath,\n                        configuration: buildData.config,\n                        buildSystem: buildData.buildSystem,\n                    )\n                    expectFileIsExecutable(at: fixturePath.appending(components: debugTarget), \"build-target\")\n                    expectFileDoesNotExists(\n                        at: fixturePath.appending(components: releaseTarget),\n                        \"build-target build-inherit\"\n                    )\n                }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        // Test target builds requested by a command plugin\n        @Test(\n            .tags(\n              .Feature.Command.Run,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .IssueWindowsRelativePathAssert,\n            .requiresSwiftConcurrencySupport,\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func commandPluginTargetBuilds_BinaryWillBeBuiltInDebugIfPluginSpecifiesDebugBuild(\n            buildData: BuildData,\n        ) async throws {\n            let debugTarget = try buildData.buildSystem.binPath(for: .debug) + [executableName(\"placeholder\")]\n            let releaseTarget = try buildData.buildSystem.binPath(for: .release) + [executableName(\"placeholder\")]\n            try await withKnownIssue(isIntermittent: true) {\n                // If the plugin specifies a debug binary, that is what will be built, regardless of overall configuration\n                try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                    let _ = try await execute(\n                        [\"build-target\", \"build-debug\"],\n                        packagePath: fixturePath,\n                        configuration: buildData.config,\n                        buildSystem: buildData.buildSystem,\n                    )\n                    expectFileIsExecutable(\n                        at: fixturePath.appending(components: debugTarget),\n                        \"build-target build-debug\"\n                    )\n                    expectFileDoesNotExists(\n                        at: fixturePath.appending(components: releaseTarget),\n                        \"build-target build-inherit\"\n                    )\n                }\n\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        // Test target builds requested by a command plugin\n        @Test(\n            .tags(\n              .Feature.Command.Run,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .IssueWindowsRelativePathAssert,\n            .requiresSwiftConcurrencySupport,\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func commandPluginTargetBuilds_BinaryWillBeBuiltInReleaseIfPluginSpecifiesReleaseBuild(\n            buildData: BuildData,\n        ) async throws {\n            let debugTarget = try buildData.buildSystem.binPath(for: .debug) + [executableName(\"placeholder\")]\n            let releaseTarget = try buildData.buildSystem.binPath(for: .release) + [executableName(\"placeholder\")]\n            // If the plugin requests a release binary, that is what will be built, regardless of overall configuration\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                let _ = try await execute(\n                    [\"build-target\", \"build-release\"],\n                    packagePath: fixturePath,\n                    configuration: buildData.config,\n                    buildSystem: buildData.buildSystem,\n                )\n                expectFileDoesNotExists(\n                    at: fixturePath.appending(components: debugTarget),\n                    \"build-target build-inherit\"\n                )\n                expectFileIsExecutable(\n                    at: fixturePath.appending(components: releaseTarget),\n                    \"build-target build-release\"\n                )\n            }\n        }\n\n        // Test target builds requested by a command plugin\n        @Test(\n            .tags(\n              .Feature.Command.Run,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .IssueWindowsRelativePathAssert,\n            .requiresSwiftConcurrencySupport,\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func commandPluginTargetBuilds_BinaryWillBeBuiltCorrectlyIfPluginSpecifiesInheritBuild(\n            buildData: BuildData,\n        ) async throws {\n            let debugTarget = try buildData.buildSystem.binPath(for: .debug) + [executableName(\"placeholder\")]\n            let releaseTarget = try buildData.buildSystem.binPath(for: .release) + [executableName(\"placeholder\")]\n            // If the plugin inherits the overall build configuration, that is what will be built\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                let _ = try await execute(\n                    [\"build-target\", \"build-inherit\"],\n                    packagePath: fixturePath,\n                    configuration: buildData.config,\n                    buildSystem: buildData.buildSystem,\n                )\n                let fileShouldNotExist: AbsolutePath\n                let fileShouldExist: AbsolutePath\n                switch buildData.config {\n                case .debug:\n                    fileShouldExist = fixturePath.appending(components: debugTarget)\n                    fileShouldNotExist = fixturePath.appending(components: releaseTarget)\n                case .release:\n                    fileShouldNotExist = fixturePath.appending(components: debugTarget)\n                    fileShouldExist = fixturePath.appending(components: releaseTarget)\n                }\n                expectFileDoesNotExists(at: fileShouldNotExist, \"build-target build-inherit\")\n                expectFileIsExecutable(at: fileShouldExist, \"build-target build-inherit\")\n            }\n        }\n\n        @Test(\n            .tags(\n              .Feature.Command.Run,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .IssueWindowsRelativePathAssert,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginBuildTestabilityInternal_ModuleDebug_True(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            // Plugin arguments: check-testability <targetName> <config> <shouldTestable>\n            // Overall configuration: debug, plugin build request: debug -> without testability\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                let _ = await #expect(throws: Never.self) {\n                    try await execute(\n                        [\"check-testability\", \"InternalModule\", \"debug\", \"true\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                }\n            }\n        }\n\n        @Test(\n            .tags(\n              .Feature.Command.Run,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .IssueWindowsRelativePathAssert,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginBuildTestabilityInternalModule_Release_False(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            // Overall configuration: debug, plugin build request: release -> without testability\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                let _ = await #expect(throws: Never.self) {\n                    try await execute(\n                        [\"check-testability\", \"InternalModule\", \"release\", \"false\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                }\n            }\n        }\n\n        @Test(\n            .tags(\n              .Feature.Command.Run,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .IssueWindowsRelativePathAssert,\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginBuildTestabilityAllWithTests_Release_True(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await withKnownIssue(isIntermittent: true) {\n                // Overall configuration: release, plugin build request: release including tests -> with testability\n                try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                    let _ = await #expect(throws: Never.self) {\n                        try await execute(\n                            [\"check-testability\", \"all-with-tests\", \"release\", \"true\"],\n                            packagePath: fixturePath,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                    }\n                }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        // Test logging of builds initiated by a command plugin\n        @Test(\n            .tags(\n              .Feature.Command.Build,\n              .Feature.PackageType.CommandPlugin\n            ),\n            .IssueWindowsRelativePathAssert,\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginBuildLogs(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n\n            // Match patterns for expected messages\n            let isEmpty = \"\"\n\n            // result.logText printed by the plugin has a prefix\n            let containsLogtext =\n                \"command plugin: packageManager.build logtext: Building for debugging...\"\n\n            // Echoed logs have no prefix\n            let containsLogecho = \"Building for debugging...\\n\"\n\n            // These tests involve building a target, so each test must run with a fresh copy of the fixture\n            // otherwise the logs may be different in subsequent tests.\n\n            // Check than nothing is echoed when echoLogs is false\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                let (stdout, stderr) = try await execute(  //got here\n                    [\"print-diagnostics\", \"build\"],\n                    packagePath: fixturePath,\n                    env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\": \"/this/is/a/bad/path\"],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout == isEmpty)\n                // Filter some unrelated output that could show up on stderr.\n                let filteredStderr = stderr.components(separatedBy: \"\\n\")\n                    .filter { !$0.contains(\"Unable to locate libSwiftScan\") }\n                    .filter { !($0.contains(\"warning: \") && $0.contains(\"unable to find libclang\")) }\n                    .filter { !$0.contains(\"Build description\")}\n                    .joined(separator: \"\\n\")\n                #expect(filteredStderr == isEmpty)\n            }\n\n            // Check that logs are returned to the plugin when echoLogs is false\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                let (stdout, stderr) = try await execute(  // got here\n                    [\"print-diagnostics\", \"build\", \"printlogs\"],\n                    packagePath: fixturePath,\n                    env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\": \"/this/is/a/bad/path\"],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(containsLogtext))\n                // Filter some unrelated output that could show up on stderr.\n                let filteredStderr = stderr.components(separatedBy: \"\\n\")\n                    .filter { !$0.contains(\"Unable to locate libSwiftScan\") }\n                    .filter { !($0.contains(\"warning: \") && $0.contains(\"unable to find libclang\")) }\n                    .filter { !$0.contains(\"Build description\")}\n                    .joined(separator: \"\\n\")\n                #expect(filteredStderr == isEmpty)\n            }\n\n            // Check that logs echoed to the console (on stderr) when echoLogs is true\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                let (stdout, stderr) = try await execute(\n                    [\"print-diagnostics\", \"build\", \"echologs\"],\n                    packagePath: fixturePath,\n                    env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\": \"/this/is/a/bad/path\"],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout == isEmpty)\n                #expect(stderr.contains(containsLogecho))\n            }\n\n            // Check that logs are returned to the plugin and echoed to the console (on stderr) when echoLogs is true\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginTestStub\") { fixturePath in\n                let (stdout, stderr) = try await execute(\n                    [\"print-diagnostics\", \"build\", \"printlogs\", \"echologs\"],\n                    packagePath: fixturePath,\n                    env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\": \"/this/is/a/bad/path\"],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(containsLogtext))\n                #expect(stderr.contains(containsLogecho))\n            }\n        }\n\n        private static let allNetworkConnectionPermissionError = \"all network connections on ports: 1, 2, 3\"\n        struct CommandPluginNetworkingPermissionsTestData {\n            let permissionsManifestFragment: String\n            let permissionError: String\n            let reason: String\n            let remedy: CLIArguments\n        }\n        fileprivate static func getCommandPluginNetworkingPermissionTestData()\n            -> [CommandPluginNetworkingPermissionsTestData]\n        {\n            [\n                CommandPluginNetworkingPermissionsTestData(\n                    permissionsManifestFragment:\n                        \"[.allowNetworkConnections(scope: .all(), reason: \\\"internet good\\\")]\",\n                    permissionError: \"all network connections on all ports\",\n                    reason: \"internet good\",\n                    remedy: [\"--allow-network-connections\", \"all\"],\n                ),\n                CommandPluginNetworkingPermissionsTestData(\n                    permissionsManifestFragment:\n                        \"[.allowNetworkConnections(scope: .all(ports: [23, 42, 443, 8080]), reason: \\\"internet good\\\")]\",\n                    permissionError: \"all network connections on ports: 23, 42, 443, 8080\",\n                    reason: \"internet good\",\n                    remedy: [\"--allow-network-connections\", \"all:23,42,443,8080\"],\n                ),\n                CommandPluginNetworkingPermissionsTestData(\n                    permissionsManifestFragment:\n                        \"[.allowNetworkConnections(scope: .all(ports: 1..<4), reason: \\\"internet good\\\")]\",\n                    permissionError: Self.allNetworkConnectionPermissionError,\n                    reason: \"internet good\",\n                    remedy: [\"--allow-network-connections\", \"all:1,2,3\"],\n                ),\n                CommandPluginNetworkingPermissionsTestData(\n                    permissionsManifestFragment:\n                        \"[.allowNetworkConnections(scope: .local(), reason: \\\"localhost good\\\")]\",\n                    permissionError: \"local network connections on all ports\",\n                    reason: \"localhost good\",\n                    remedy: [\"--allow-network-connections\", \"local\"],\n                ),\n                CommandPluginNetworkingPermissionsTestData(\n                    permissionsManifestFragment:\n                        \"[.allowNetworkConnections(scope: .local(ports: [23, 42, 443, 8080]), reason: \\\"localhost good\\\")]\",\n                    permissionError: \"local network connections on ports: 23, 42, 443, 8080\",\n                    reason: \"localhost good\",\n                    remedy: [\"--allow-network-connections\", \"local:23,42,443,8080\"],\n                ),\n                CommandPluginNetworkingPermissionsTestData(\n                    permissionsManifestFragment:\n                        \"[.allowNetworkConnections(scope: .local(ports: 1..<4), reason: \\\"localhost good\\\")]\",\n                    permissionError: \"local network connections on ports: 1, 2, 3\",\n                    reason: \"localhost good\",\n                    remedy: [\"--allow-network-connections\", \"local:1,2,3\"],\n                ),\n                CommandPluginNetworkingPermissionsTestData(\n                    permissionsManifestFragment:\n                        \"[.allowNetworkConnections(scope: .docker, reason: \\\"docker good\\\")]\",\n                    permissionError: \"docker unix domain socket connections\",\n                    reason: \"docker good\",\n                    remedy: [\"--allow-network-connections\", \"docker\"],\n                ),\n                CommandPluginNetworkingPermissionsTestData(\n                    permissionsManifestFragment:\n                        \"[.allowNetworkConnections(scope: .unixDomainSocket, reason: \\\"unix sockets good\\\")]\",\n                    permissionError: \"unix domain socket connections\",\n                    reason: \"unix sockets good\",\n                    remedy: [\"--allow-network-connections\", \"unixDomainSocket\"],\n                ),\n            ]\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .requireHostOS(.macOS),\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            Self.getCommandPluginNetworkingPermissionTestData()\n        )\n        func commandPluginNetworkingPermissionsWithoutUsingRemedy(\n            buildSystem: BuildSystemProvider.Kind,\n            testData: CommandPluginNetworkingPermissionsTestData,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a library target and a plugin.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            targets: [\n                                .target(name: \"MyLibrary\"),\n                                .plugin(name: \"MyPlugin\", capability: .command(intent: .custom(verb: \"Network\", description: \"Help description\"), permissions: \\(testData.permissionsManifestFragment))),\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.swift\"),\n                    string: \"public func Foo() { }\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Plugins\", \"MyPlugin\", \"plugin.swift\"),\n                    string:\n                        \"\"\"\n                        import PackagePlugin\n\n                        @main\n                        struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(context: PluginContext, arguments: [String]) throws {\n                                print(\"hello world\")\n                            }\n                        }\n                        \"\"\"\n                )\n\n                await expectThrowsCommandExecutionError(\n                    try await execute(\n                        [\"plugin\", \"Network\"],\n                        packagePath: packageDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(!error.stdout.contains(\"hello world\"))\n                    #expect(\n                        error.stderr.contains(\n                            \"error: Plugin ‘MyPlugin’ wants permission to allow \\(testData.permissionError).\"\n                        )\n                    )\n                    #expect(error.stderr.contains(\"Stated reason: “\\(testData.reason)”.\"))\n                    #expect(\n                        error.stderr.contains(\"Use `\\(testData.remedy.joined(separator: \" \"))` to allow this.\")\n                    )\n                }\n            }\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Run,\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            .IssueWindowsRelativePathAssert,\n            .IssueWindowsLongPath,\n            .IssueWindowsPathLastComponent,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/9083\",\n                relationship: .defect,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            Self.getCommandPluginNetworkingPermissionTestData()\n        )\n        func commandPluginNetworkingPermissionsUsingRemedy(\n            buildSystem: BuildSystemProvider.Kind,\n            testData: CommandPluginNetworkingPermissionsTestData,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a library target and a plugin.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            targets: [\n                                .target(name: \"MyLibrary\"),\n                                .plugin(name: \"MyPlugin\", capability: .command(intent: .custom(verb: \"Network\", description: \"Help description\"), permissions: \\(testData.permissionsManifestFragment))),\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.swift\"),\n                    string: \"public func Foo() { }\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Plugins\", \"MyPlugin\", \"plugin.swift\"),\n                    string:\n                        \"\"\"\n                        import PackagePlugin\n\n                        @main\n                        struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(context: PluginContext, arguments: [String]) throws {\n                                print(\"hello world\")\n                            }\n                        }\n                        \"\"\"\n                )\n\n                // Check that we don't get an error (and also are allowed to write to the package directory) if we pass `--allow-writing-to-package-directory`.\n                do {\n                    let (stdout, _) = try await execute(\n                        [\"plugin\"] + testData.remedy + [\"Network\"],\n                        packagePath: packageDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    withKnownIssue(isIntermittent: true) {\n                        #expect(stdout.contains(\"hello world\"))\n                    } when: {\n                        ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild && config == .debug && testData.permissionError == Self.allNetworkConnectionPermissionError\n                    }\n                }\n            }\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            Self.getCommandPluginNetworkingPermissionTestData()\n        )\n        func commandPluginNetworkingPermissionsWithDisabledSandbox(\n            buildSystem: BuildSystemProvider.Kind,\n            testData: CommandPluginNetworkingPermissionsTestData,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string:\n                        \"\"\"\n                        // swift-tools-version: 5.9\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            targets: [\n                                .target(name: \"MyLibrary\"),\n                                .plugin(name: \"MyPlugin\", capability: .command(intent: .custom(verb: \"Network\", description: \"Help description\"), permissions: \\(testData.permissionsManifestFragment))),\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.swift\"),\n                    string: \"public func Foo() { }\"\n                )\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Plugins\", \"MyPlugin\", \"plugin.swift\"),\n                    string:\n                        \"\"\"\n                        import PackagePlugin\n\n                        @main\n                        struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(context: PluginContext, arguments: [String]) throws {\n                                print(\"hello world\")\n                            }\n                        }\n                        \"\"\"\n                )\n\n                let (stdout, _) = try await executeSwiftPackage(\n                    packageDir,\n                    configuration: config,\n                    extraArgs: [\"--disable-sandbox\", \"plugin\", \"Network\"],\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"hello world\"))\n            }\n        }\n\n        @Test(\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/8782\",\n                relationship: .defect\n            ),\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/9090\",\n                relationship: .defect,\n            ),\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginPermissions(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await withKnownIssue(isIntermittent: true) {\n                try await testWithTemporaryDirectory { tmpPath in\n                    // Create a sample package with a library target and a plugin.\n                    let packageDir = tmpPath.appending(components: \"MyPackage\")\n                    try localFileSystem.createDirectory(packageDir, recursive: true)\n                    try localFileSystem.writeFileContents(\n                        packageDir.appending(components: \"Package.swift\"),\n                        string:\n                            \"\"\"\n                            // swift-tools-version: 5.6\n                            import PackageDescription\n                            import Foundation\n                            let package = Package(\n                                name: \"MyPackage\",\n                                targets: [\n                                    .target(\n                                        name: \"MyLibrary\"\n                                    ),\n                                    .plugin(\n                                        name: \"MyPlugin\",\n                                        capability: .command(\n                                            intent: .custom(verb: \"PackageScribbler\", description: \"Help description\"),\n                                            // We use an environment here so we can control whether we declare the permission.\n                                            permissions: ProcessInfo.processInfo.environment[\"DECLARE_PACKAGE_WRITING_PERMISSION\"] == \"1\"\n                                                ? [.writeToPackageDirectory(reason: \"For testing purposes\")]\n                                                : []\n                                        )\n                                    ),\n                                ]\n                            )\n                            \"\"\"\n                    )\n                    let libPath = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n                    try localFileSystem.createDirectory(libPath, recursive: true)\n                    try localFileSystem.writeFileContents(\n                        libPath.appending(\"library.swift\"),\n                        string:\n                            \"public func Foo() { }\"\n                    )\n                    let pluginPath = packageDir.appending(components: \"Plugins\", \"MyPlugin\")\n                    try localFileSystem.createDirectory(pluginPath, recursive: true)\n                    try localFileSystem.writeFileContents(\n                        pluginPath.appending(\"plugin.swift\"),\n                        string:\n                            \"\"\"\n                            import PackagePlugin\n                            import Foundation\n\n                            @main\n                            struct MyCommandPlugin: CommandPlugin {\n                                func performCommand(\n                                    context: PluginContext,\n                                    arguments: [String]\n                                ) throws {\n                                    // Check that we can write to the package directory.\n                                    print(\"Trying to write to the package directory...\")\n                                    guard FileManager.default.createFile(atPath: context.package.directory.appending(\"Foo\").string, contents: Data(\"Hello\".utf8)) else {\n                                        throw \"Couldn’t create file at path \\\\(context.package.directory.appending(\"Foo\"))\"\n                                    }\n                                    print(\"... successfully created it\")\n                                }\n                            }\n                            extension String: Error {}\n                            \"\"\"\n                    )\n\n                    // Check that we get an error if the plugin needs permission but if we don't give it to them. Note that sandboxing is only currently supported on macOS.\n                    #if os(macOS)\n                        do {\n                            await expectThrowsCommandExecutionError(\n                                try await execute(\n                                    [\"plugin\", \"PackageScribbler\"],\n                                    packagePath: packageDir,\n                                    env: [\"DECLARE_PACKAGE_WRITING_PERMISSION\": \"1\"],\n                                    configuration: config,\n                                    buildSystem: buildSystem,\n                                )\n                            ) { error in\n                                // guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = error else {\n                                //     return Issue.record(\"invalid error \\(error)\")\n                                // }\n                                #expect(!error.stdout.contains(\"successfully created it\"))\n                                #expect(\n                                    error.stderr.contains(\n                                        \"error: Plugin ‘MyPlugin’ wants permission to write to the package directory.\"\n                                    )\n                                )\n                                #expect(error.stderr.contains(\"Stated reason: “For testing purposes”.\"))\n                                #expect(\n                                    error.stderr.contains(\"Use `--allow-writing-to-package-directory` to allow this.\")\n                                )\n                            }\n                        }\n                    #endif\n\n                    // Check that we don't get an error (and also are allowed to write to the package directory) if we pass `--allow-writing-to-package-directory`.\n                    do {\n                        let (stdout, stderr) = try await execute(\n                            [\"plugin\", \"--allow-writing-to-package-directory\", \"PackageScribbler\"],\n                            packagePath: packageDir,\n                            env: [\"DECLARE_PACKAGE_WRITING_PERMISSION\": \"1\"],\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                        #expect(stdout.contains(\"successfully created it\"))\n                        #expect(!stderr.contains(\"error: Couldn’t create file at path\"))\n                    }\n\n                    // Check that we get an error if the plugin doesn't declare permission but tries to write anyway. Note that sandboxing is only currently supported on macOS.\n                    #if os(macOS)\n                        do {\n                            await expectThrowsCommandExecutionError(\n                                try await execute(\n                                    [\"plugin\", \"PackageScribbler\"],\n                                    packagePath: packageDir,\n                                    env: [\"DECLARE_PACKAGE_WRITING_PERMISSION\": \"0\"],\n                                    configuration: config,\n                                    buildSystem: buildSystem,\n                                )\n                            ) { error in\n                                // guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = error else {\n                                //     Issue.record(\"invalid error \\(error)\")\n                                //     return\n                                // }\n                                #expect(!error.stdout.contains(\"successfully created it\"))\n                                #expect(error.stderr.contains(\"error: Couldn’t create file at path\"))\n                            }\n                        }\n                    #endif\n\n                    // Check default command with arguments\n                    do {\n                        let (stdout, stderr) = try await execute(\n                            [\"--allow-writing-to-package-directory\", \"PackageScribbler\"],\n                            packagePath: packageDir,\n                            env: [\"DECLARE_PACKAGE_WRITING_PERMISSION\": \"1\"],\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                        #expect(stdout.contains(\"successfully created it\"))\n                        #expect(!stderr.contains(\"error: Couldn’t create file at path\"))\n                    }\n\n                    // Check plugin arguments after plugin name\n                    do {\n                        let (stdout, stderr) = try await execute(\n                            [\"plugin\", \"PackageScribbler\", \"--allow-writing-to-package-directory\"],\n                            packagePath: packageDir,\n                            env: [\"DECLARE_PACKAGE_WRITING_PERMISSION\": \"1\"],\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                        #expect(stdout.contains(\"successfully created it\"))\n                        #expect(!stderr.contains(\"error: Couldn’t create file at path\"))\n                    }\n\n                    // Check default command with arguments after plugin name\n                    do {\n                        let (stdout, stderr) = try await execute(\n                            [\"PackageScribbler\", \"--allow-writing-to-package-directory\"],\n                            packagePath: packageDir,\n                            env: [\"DECLARE_PACKAGE_WRITING_PERMISSION\": \"1\"],\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                        #expect(stdout.contains(\"successfully created it\"))\n                        #expect(!stderr.contains(\"error: Couldn’t create file at path\"))\n                    }\n                }\n            } when: {\n                ProcessInfo.processInfo.environment[\"SWIFTCI_EXHIBITS_GH_8782\"] != nil\n            }\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n            [\n                true,  // check argument\n                false,  // check default argument\n            ]\n        )\n        func commandPluginArgumentsNotSwallowed(\n            buildSystem: BuildSystemProvider.Kind,\n            _ checkArgument: Bool,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a library target and a plugin.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n\n                try localFileSystem.createDirectory(packageDir)\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string: \"\"\"\n                        // swift-tools-version: 5.6\n                        import PackageDescription\n                        import Foundation\n                        let package = Package(\n                            name: \"MyPackage\",\n                            targets: [\n                                .plugin(\n                                    name: \"MyPlugin\",\n                                    capability: .command(\n                                        intent: .custom(verb: \"MyPlugin\", description: \"Help description\")\n                                    )\n                                ),\n                            ]\n                        )\n                        \"\"\"\n                )\n\n                let pluginDir = packageDir.appending(components: \"Plugins\", \"MyPlugin\")\n                try localFileSystem.createDirectory(pluginDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    pluginDir.appending(\"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        import Foundation\n\n                        @main\n                        struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(\n                                context: PluginContext,\n                                arguments: [String]\n                            ) throws {\n                                print (arguments)\n                                guard arguments.contains(\"--foo\") else {\n                                    throw \"expecting argument foo\"\n                                }\n                                guard arguments.contains(\"--help\") else {\n                                    throw \"expecting argument help\"\n                                }\n                                guard arguments.contains(\"--version\") else {\n                                    throw \"expecting argument version\"\n                                }\n                                guard arguments.contains(\"--verbose\") else {\n                                    throw \"expecting argument verbose\"\n                                }\n                                print(\"success\")\n                            }\n                        }\n                        extension String: Error {}\n                        \"\"\"\n                )\n\n                let commandPrefix = checkArgument ? [\"plugin\"] : []\n                let (stdout, stderr) = try await execute(\n                    commandPrefix + [\"MyPlugin\", \"--foo\", \"--help\", \"--version\", \"--verbose\"],\n                    packagePath: packageDir,\n                    env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\": \"/this/is/a/bad/path\"],\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"success\"))\n                #expect(!stderr.contains(\"error:\"))\n            }\n        }\n\n        @Test(\n            .IssueWindowsRelativePathAssert,\n            .requiresSwiftConcurrencySupport,\n            // Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.\n            .requiresSymbolgraphExtract,\n            .issue(\n                \"https://github.com/swiftlang/swift-package-manager/issues/8848\",\n                relationship: .defect,\n            ),\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginSymbolGraphCallbacks(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await withKnownIssue(isIntermittent: true) {\n                try await testWithTemporaryDirectory { tmpPath in\n                    // Create a sample package with a library, and executable, and a plugin.\n                    let packageDir = tmpPath.appending(components: \"MyPackage\")\n                    try localFileSystem.createDirectory(packageDir)\n                    try localFileSystem.writeFileContents(\n                        packageDir.appending(components: \"Package.swift\"),\n                        string: \"\"\"\n                            // swift-tools-version: 5.6\n                            import PackageDescription\n                            let package = Package(\n                                name: \"MyPackage\",\n                                targets: [\n                                    .target(\n                                        name: \"MyLibrary\"\n                                    ),\n                                    .executableTarget(\n                                        name: \"MyCommand\",\n                                        dependencies: [\"MyLibrary\"]\n                                    ),\n                                    .plugin(\n                                        name: \"MyPlugin\",\n                                        capability: .command(\n                                            intent: .documentationGeneration()\n                                        )\n                                    ),\n                                ]\n                            )\n                            \"\"\"\n                    )\n\n                    let libraryPath = packageDir.appending(\n                        components: \"Sources\",\n                        \"MyLibrary\",\n                        \"library.swift\"\n                    )\n                    try localFileSystem.createDirectory(libraryPath.parentDirectory, recursive: true)\n                    try localFileSystem.writeFileContents(\n                        libraryPath,\n                        string: #\"public func GetGreeting() -> String { return \"Hello\" }\"#\n                    )\n\n                    let commandPath = packageDir.appending(components: \"Sources\", \"MyCommand\", \"main.swift\")\n                    try localFileSystem.createDirectory(commandPath.parentDirectory, recursive: true)\n                    try localFileSystem.writeFileContents(\n                        commandPath,\n                        string: \"\"\"\n                            import MyLibrary\n                            print(\"\\\\(GetGreeting()), World!\")\n                            \"\"\"\n                    )\n\n                    let pluginPath = packageDir.appending(components: \"Plugins\", \"MyPlugin\", \"plugin.swift\")\n                    try localFileSystem.createDirectory(pluginPath.parentDirectory, recursive: true)\n                    try localFileSystem.writeFileContents(\n                        pluginPath,\n                        string: \"\"\"\n                            import PackagePlugin\n                            import Foundation\n\n                            @main\n                            struct MyCommandPlugin: CommandPlugin {\n                                func performCommand(\n                                    context: PluginContext,\n                                    arguments: [String]\n                                ) throws {\n                                    // Ask for and print out the symbol graph directory for each target.\n                                    var argExtractor = ArgumentExtractor(arguments)\n                                    let targetNames = argExtractor.extractOption(named: \"target\")\n                                    let targets = targetNames.isEmpty\n                                        ? context.package.targets\n                                        : try context.package.targets(named: targetNames)\n                                    for target in targets {\n                                        #if compiler(>=6.3)\n                                        let symbolGraph = try packageManager.getSymbolGraph(for: target,\n                                            options: .init(minimumAccessLevel: .public, includeInheritedDocs: false))\n                                        #else\n                                        let symbolGraph = try packageManager.getSymbolGraph(for: target,\n                                            options: .init(minimumAccessLevel: .public))\n                                        #endif\n                                        print(\"\\\\(target.name): \\\\(symbolGraph.directoryPath)\")\n                                    }\n                                }\n                            }\n                            \"\"\"\n                    )\n\n                    // Check that if we don't pass any target, we successfully get symbol graph information for all targets in the package, and at different paths.\n                    do {\n                        let (stdout, _) = try await execute(\n                            [\"generate-documentation\"],\n                            packagePath: packageDir,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                        switch buildSystem {\n                        case .native:\n                            #expect(stdout.contains(\"MyLibrary:\"))\n                            #expect(stdout.contains(AbsolutePath(\"/mypackage/MyLibrary\").pathString))\n                            #expect(stdout.contains(\"MyCommand:\"))\n                            #expect(stdout.contains(AbsolutePath(\"/mypackage/MyCommand\").pathString))\n                        case .swiftbuild:\n                            #expect(stdout.contains(\"MyLibrary:\"))\n                            #expect(stdout.contains(AbsolutePath(\"/MyLibrary.symbolgraphs\").pathString))\n                            #expect(stdout.contains(\"MyCommand:\"))\n                            #expect(stdout.contains(AbsolutePath(\"/MyCommand.symbolgraphs\").pathString))\n                        case .xcode:\n                            Issue.record(\"Test expectations are not defined\")\n                        }\n                    }\n\n                    // Check that if we pass a target, we successfully get symbol graph information for just the target we asked for.\n                    do {\n                        let (stdout, _) = try await execute(\n                            [\"generate-documentation\", \"--target\", \"MyLibrary\"],\n                            packagePath: packageDir,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                        switch buildSystem {\n                        case .native:\n                            #expect(stdout.contains(\"MyLibrary:\"))\n                            #expect(stdout.contains(AbsolutePath(\"/mypackage/MyLibrary\").pathString))\n                            #expect(!stdout.contains(\"MyCommand:\"))\n                            #expect(!stdout.contains(AbsolutePath(\"/mypackage/MyCommand\").pathString))\n                        case .swiftbuild:\n                            #expect(stdout.contains(\"MyLibrary:\"))\n                            #expect(stdout.contains(AbsolutePath(\"/MyLibrary.symbolgraphs\").pathString))\n                            #expect(!stdout.contains(\"MyCommand:\"))\n                            #expect(!stdout.contains(AbsolutePath(\"/MyCommand.symbolgraphs\").pathString))\n                        case .xcode:\n                            Issue.record(\"Test expectations are not defined\")\n                        }\n                    }\n                }\n            } when: {\n                let shouldSkip = false\n                #if compiler(>=6.3)\n                    return shouldSkip\n                #else\n                    // Symbol graph generation options are only available in 6.3 toolchain or later for swift build\n                    return shouldSkip || buildSystem == .swiftbuild\n                #endif\n            }\n        }\n\n        @Test(\n            .IssueWindowsRelativePathAssert,\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            .skip(\"https://github.com/swiftlang/swift-package-manager/issues/9775\"),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginBuildingCallbacks(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let buildSystemProvider = buildSystem\n                // Create a sample package with a library, an executable, and a command plugin.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.createDirectory(packageDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string: \"\"\"\n                        // swift-tools-version: 5.6\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            products: [\n                                .library(\n                                    name: \"MyAutomaticLibrary\",\n                                    targets: [\"MyLibrary\"]\n                                ),\n                                .library(\n                                    name: \"MyStaticLibrary\",\n                                    type: .static,\n                                    targets: [\"MyLibrary\"]\n                                ),\n                                .library(\n                                    name: \"MyDynamicLibrary\",\n                                    type: .dynamic,\n                                    targets: [\"MyLibrary\"]\n                                ),\n                                .executable(\n                                    name: \"MyExecutable\",\n                                    targets: [\"MyExecutable\"]\n                                ),\n                            ],\n                            targets: [\n                                .target(\n                                    name: \"MyLibrary\"\n                                ),\n                                .executableTarget(\n                                    name: \"MyExecutable\",\n                                    dependencies: [\"MyLibrary\"]\n                                ),\n                                .plugin(\n                                    name: \"MyPlugin\",\n                                    capability: .command(\n                                        intent: .custom(verb: \"my-build-tester\", description: \"Help description\")\n                                    )\n                                ),\n                            ]\n                        )\n                        \"\"\"\n                )\n                let myPluginTargetDir = packageDir.appending(components: \"Plugins\", \"MyPlugin\")\n                try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myPluginTargetDir.appending(\"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        @main\n                        struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(\n                                context: PluginContext,\n                                arguments: [String]\n                            ) throws {\n                                // Extract the plugin arguments.\n                                var argExtractor = ArgumentExtractor(arguments)\n                                let productNames = argExtractor.extractOption(named: \"product\")\n                                if productNames.count != 1 {\n                                    throw \"Expected exactly one product name, but had: \\\\(productNames.joined(separator: \", \"))\"\n                                }\n                                let products = try context.package.products(named: productNames)\n                                let printCommands = (argExtractor.extractFlag(named: \"print-commands\") > 0)\n                                let release = (argExtractor.extractFlag(named: \"release\") > 0)\n                                if let unextractedArgs = argExtractor.unextractedOptionsOrFlags.first {\n                                    throw \"Unknown option: \\\\(unextractedArgs)\"\n                                }\n                                let positionalArgs = argExtractor.remainingArguments\n                                if !positionalArgs.isEmpty {\n                                    throw \"Unexpected extra arguments: \\\\(positionalArgs)\"\n                                }\n                                do {\n                                    var parameters = PackageManager.BuildParameters()\n                                    parameters.configuration = release ? .release : .debug\n                                    parameters.logging = printCommands ? .verbose : .concise\n                                    parameters.otherSwiftcFlags = [\"-DEXTRA_SWIFT_FLAG\"]\n                                    let result = try packageManager.build(.product(products[0].name), parameters: parameters)\n                                    print(\"succeeded: \\\\(result.succeeded)\")\n                                    for artifact in result.builtArtifacts {\n                                        print(\"artifact-path: \\\\(artifact.path.string)\")\n                                        print(\"artifact-kind: \\\\(artifact.kind)\")\n                                    }\n                                    print(\"log:\\\\n\\\\(result.logText)\")\n                                }\n                                catch {\n                                    print(\"error from the plugin host: \\\\(error)\")\n                                }\n                            }\n                        }\n                        extension String: Error {}\n                        \"\"\"\n                )\n                let myLibraryTargetDir = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n                try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myLibraryTargetDir.appending(\"library.swift\"),\n                    string: \"\"\"\n                        public func GetGreeting() -> String { return \"Hello\" }\n                        \"\"\"\n                )\n                let myExecutableTargetDir = packageDir.appending(components: \"Sources\", \"MyExecutable\")\n                try localFileSystem.createDirectory(myExecutableTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myExecutableTargetDir.appending(\"main.swift\"),\n                    string: \"\"\"\n                        import MyLibrary\n                        print(\"\\\\(GetGreeting()), World!\")\n                        \"\"\"\n                )\n\n                // Invoke the plugin with parameters choosing a verbose build of MyExecutable for debugging.\n                do {\n                    let (stdout, _) = try await execute(\n                        [\"my-build-tester\", \"--product\", \"MyExecutable\", \"--print-commands\"],\n                        packagePath: packageDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(stdout.contains(\"Building for debugging...\"))\n                    if buildSystemProvider == .native {\n                        #expect(stdout.contains(\"-module-name MyExecutable\"))\n                        #expect(stdout.contains(\"-DEXTRA_SWIFT_FLAG\"))\n                        #expect(stdout.contains(\"Build of product 'MyExecutable' complete!\"))\n                    }\n                        #expect(stdout.contains(\"succeeded: true\"))\n                        switch buildSystemProvider {\n                        case .native:\n                            #expect(stdout.contains(\"artifact-path:\"))\n                            #expect(stdout.contains(RelativePath(\"debug/MyExecutable\").pathString))\n                        case .swiftbuild:\n                            #expect(stdout.contains(\"artifact-path:\"))\n                            #expect(stdout.contains(RelativePath(\"MyExecutable\").pathString))\n                        case .xcode:\n                            Issue.record(\"unimplemented assertion for --build-system xcode\")\n                        }\n                        #expect(stdout.contains(\"artifact-kind:\"))\n                        #expect(stdout.contains(\"executable\"))\n                    }\n\n                // Invoke the plugin with parameters choosing a concise build of MyExecutable for release.\n                do {\n                    let (stdout, _) = try await execute(\n                        [\"my-build-tester\", \"--product\", \"MyExecutable\", \"--release\"],\n                        packagePath: packageDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(stdout.contains(\"Building for production...\"))\n                    #expect(!stdout.contains(\"-module-name MyExecutable\"))\n                    if buildSystemProvider == .native {\n                        #expect(stdout.contains(\"Build of product 'MyExecutable' complete!\"))\n                    }\n                    #expect(stdout.contains(\"succeeded: true\"))\n                    switch buildSystemProvider {\n                    case .native:\n                        #expect(stdout.contains(\"artifact-path:\"))\n                        #expect(stdout.contains(RelativePath(\"release/MyExecutable\").pathString))\n                    case .swiftbuild:\n                        #expect(stdout.contains(\"artifact-path:\"))\n                        #expect(stdout.contains(RelativePath(\"MyExecutable\").pathString))\n                    case .xcode:\n                        Issue.record(\"unimplemented assertion for --build-system xcode\")\n                    }\n                    #expect(stdout.contains(\"artifact-kind:\"))\n                    #expect(stdout.contains(\"executable\"))\n                }\n\n                // Invoke the plugin with parameters choosing a verbose build of MyStaticLibrary for release.\n                do {\n                    let (stdout, _) = try await execute(\n                        [\"my-build-tester\", \"--product\", \"MyStaticLibrary\", \"--print-commands\", \"--release\"],\n                        packagePath: packageDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(stdout.contains(\"Building for production...\"))\n                    #expect(!stdout.contains(\"Building for debug...\"))\n                    #expect(!stdout.contains(\"-module-name MyLibrary\"))\n                    if buildSystemProvider == .native {\n                        #expect(stdout.contains(\"Build of product 'MyStaticLibrary' complete!\"))\n                    }\n                    #expect(stdout.contains(\"succeeded: true\"))\n                    switch buildSystemProvider {\n                    case .native:\n                        #expect(stdout.contains(\"artifact-path:\"))\n                        #expect(stdout.contains(RelativePath(\"release/libMyStaticLibrary\").pathString))\n                    case .swiftbuild:\n                        #expect(stdout.contains(\"artifact-path:\"))\n                        #expect(stdout.contains(RelativePath(\"MyStaticLibrary\").pathString))\n                    case .xcode:\n                        Issue.record(\"unimplemented assertion for --build-system xcode\")\n                    }\n                    #expect(stdout.contains(\"artifact-kind:\"))\n                    #expect(stdout.contains(\"staticLibrary\"))\n                }\n\n                // Invoke the plugin with parameters choosing a verbose build of MyDynamicLibrary for release.\n                do {\n                    let (stdout, _) = try await execute(\n                        [\n                            \"my-build-tester\", \"--product\", \"MyDynamicLibrary\", \"--print-commands\", \"--release\",\n                        ],\n                        packagePath: packageDir,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(stdout.contains(\"Building for production...\"))\n                    #expect(!stdout.contains(\"Building for debug...\"))\n                    #expect(!stdout.contains(\"-module-name MyLibrary\"))\n                    if buildSystemProvider == .native {\n                        #expect(stdout.contains(\"Build of product 'MyDynamicLibrary' complete!\"))\n                    }\n                    #expect(stdout.contains(\"succeeded: true\"))\n                    switch buildSystemProvider {\n                    case .native:\n                        #if os(Windows)\n                            #expect(stdout.contains(\"artifact-path:\"))\n                            #expect(stdout.contains(RelativePath(\"release/MyDynamicLibrary.dll\").pathString))\n                        #else\n                            #expect(stdout.contains(\"artifact-path:\"))\n                            #expect(stdout.contains(RelativePath(\"release/libMyDynamicLibrary\").pathString))\n                        #endif\n                    case .swiftbuild:\n                        #expect(stdout.contains(\"artifact-path:\"))\n                        #expect(stdout.contains(RelativePath(\"MyDynamicLibrary\").pathString))\n                    case .xcode:\n                        Issue.record(\"unimplemented assertion for --build-system xcode\")\n                    }\n                    #expect(stdout.contains(\"artifact-kind:\"))\n                    #expect(stdout.contains(\"dynamicLibrary\"))\n                }\n            }\n        }\n\n        @Test(\n            arguments: [BuildSystemProvider.Kind.native, .swiftbuild],\n        )\n        func commandPluginBuildingCallbacksExcludeUnbuiltArtifacts(buildSystem: BuildSystemProvider.Kind) async throws {\n            try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"PartiallyUnusedDependency\") { fixturePath in\n                let (stdout, _) = try await execute(\n                    [\"dump-artifacts-plugin\"],\n                    packagePath: fixturePath,\n                    configuration: .debug,\n                    buildSystem: buildSystem\n                )\n                // The build should succeed\n                #expect(stdout.contains(\"succeeded: true\"))\n                // The artifacts corresponding to the executable and dylib we built should be reported\n                #expect(stdout.contains(#/artifact-path: [^\\n]+MyExecutable(.*)?\\nartifact-kind: executable/#))\n                #expect(stdout.contains(#/artifact-path: [^\\n]+MyDynamicLibrary(.*)?\\nartifact-kind: dynamicLibrary/#))\n                // The not-built executable in the dependency should not be reported. The native build system fails to exclude it.\n                switch buildSystem {\n                    case .native:\n                        #expect(stdout.contains(\"MySupportExecutable\"))\n                    case .swiftbuild:\n                        #expect(!stdout.contains(\"MySupportExecutable\"))\n                    case .xcode:\n                        Issue.record(\"unimplemented assertion for --build-system xcode\")\n                }\n            }\n            } when: {\n                buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            // Depending on how the test is running, the `llvm-profdata` and `llvm-cov` tool might be unavailable.\n            .requiresLLVMProfData,\n            .requiresLLVMCov,\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func commandPluginTestingCallbacks(\n            data: BuildData,\n        ) async throws {\n            try await withKnownIssue(isIntermittent: true) {\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a library, a command plugin, and a couple of tests.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.createDirectory(packageDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string: \"\"\"\n                        // swift-tools-version: 5.6\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            targets: [\n                                .target(\n                                    name: \"MyLibrary\"\n                                ),\n                                .plugin(\n                                    name: \"MyPlugin\",\n                                    capability: .command(\n                                        intent: .custom(verb: \"my-test-tester\", description: \"Help description\")\n                                    )\n                                ),\n                                .testTarget(\n                                    name: \"MyBasicTests\"\n                                ),\n                                .testTarget(\n                                    name: \"MyExtendedTests\"\n                                ),\n                            ]\n                        )\n                        \"\"\"\n                )\n                let myPluginTargetDir = packageDir.appending(components: \"Plugins\", \"MyPlugin\")\n                try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myPluginTargetDir.appending(\"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        @main\n                        struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(\n                                context: PluginContext,\n                                arguments: [String]\n                            ) throws {\n                                do {\n                                    let result = try packageManager.test(.filtered([\"MyBasicTests\"]), parameters: .init(enableCodeCoverage: true))\n                                    assert(result.succeeded == true)\n                                    assert(result.testTargets.count == 1)\n                                    assert(result.testTargets[0].name == \"MyBasicTests\")\n                                    assert(result.testTargets[0].testCases.count == 2)\n                                    assert(result.testTargets[0].testCases[0].name == \"MyBasicTests.TestSuite1\")\n                                    assert(result.testTargets[0].testCases[0].tests.count == 2)\n                                    assert(result.testTargets[0].testCases[0].tests[0].name == \"testBooleanInvariants\")\n                                    assert(result.testTargets[0].testCases[0].tests[1].result == .succeeded)\n                                    assert(result.testTargets[0].testCases[0].tests[1].name == \"testNumericalInvariants\")\n                                    assert(result.testTargets[0].testCases[0].tests[1].result == .succeeded)\n                                    assert(result.testTargets[0].testCases[1].name == \"MyBasicTests.TestSuite2\")\n                                    assert(result.testTargets[0].testCases[1].tests.count == 1)\n                                    assert(result.testTargets[0].testCases[1].tests[0].name == \"testStringInvariants\")\n                                    assert(result.testTargets[0].testCases[1].tests[0].result == .succeeded)\n                                    assert(result.codeCoverageDataFile?.extension == \"json\")\n                                }\n                                catch {\n                                    print(\"error from the plugin host: \\\\(error)\")\n                                }\n                            }\n                        }\n                        \"\"\"\n                )\n                let myLibraryTargetDir = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n                try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myLibraryTargetDir.appending(\"library.swift\"),\n                    string: \"\"\"\n                        public func Foo() { }\n                        \"\"\"\n                )\n                let myBasicTestsTargetDir = packageDir.appending(components: \"Tests\", \"MyBasicTests\")\n                try localFileSystem.createDirectory(myBasicTestsTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myBasicTestsTargetDir.appending(\"Test1.swift\"),\n                    string: \"\"\"\n                        import XCTest\n                        class TestSuite1: XCTestCase {\n                            func testBooleanInvariants() throws {\n                                XCTAssertEqual(true || true, true)\n                            }\n                            func testNumericalInvariants() throws {\n                                XCTAssertEqual(1 + 1, 2)\n                            }\n                        }\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    myBasicTestsTargetDir.appending(\"Test2.swift\"),\n                    string: \"\"\"\n                        import XCTest\n                        class TestSuite2: XCTestCase {\n                            func testStringInvariants() throws {\n                                XCTAssertEqual(\"\" + \"\", \"\")\n                            }\n                        }\n                        \"\"\"\n                )\n                let myExtendedTestsTargetDir = packageDir.appending(\n                    components: \"Tests\",\n                    \"MyExtendedTests\"\n                )\n                try localFileSystem.createDirectory(myExtendedTestsTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myExtendedTestsTargetDir.appending(\"Test3.swift\"),\n                    string: \"\"\"\n                        import XCTest\n                        class TestSuite3: XCTestCase {\n                            func testArrayInvariants() throws {\n                                XCTAssertEqual([] + [], [])\n                            }\n                            func testImpossibilities() throws {\n                                XCTFail(\"no can do\")\n                            }\n                        }\n                        \"\"\"\n                )\n\n                // Check basic usage with filtering and code coverage. The plugin itself asserts a bunch of values.\n                try await execute(\n                    [\"my-test-tester\"],\n                    packagePath: packageDir,\n                    configuration: data.config,\n                    buildSystem: data.buildSystem,\n                )\n\n                // We'll add checks for various error conditions here in a future commit.\n            }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows && data.buildSystem == .swiftbuild\n            }\n        }\n\n        struct PluginAPIsData {\n            let commandArgs: CLIArguments\n            let expectedStdout: [String]\n            let expectedStderr: [String]\n        }\n\n        @Test(\n            .IssueWindowsPathLastComponent,\n            // Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.Plugin,\n            ),\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n            [\n                PluginAPIsData(\n                    // Check that a target doesn't include itself in its recursive dependencies.\n                    commandArgs: [\"print-target-dependencies\", \"--target\", \"SecondTarget\"],\n                    expectedStdout: [\n                        \"Recursive dependencies of 'SecondTarget': [\\\"FirstTarget\\\"]\",\n                        \"Module kind of 'SecondTarget': generic\",\n                    ],\n                    expectedStderr: [],\n                ),\n                PluginAPIsData(\n                    // Check that targets are not included twice in recursive dependencies.\n                    commandArgs: [\"print-target-dependencies\", \"--target\", \"ThirdTarget\"],\n                    expectedStdout: [\n                        \"Recursive dependencies of 'ThirdTarget': [\\\"FirstTarget\\\"]\",\n                        \"Module kind of 'ThirdTarget': generic\",\n                    ],\n                    expectedStderr: [],\n                ),\n                PluginAPIsData(\n                    // Check that product dependencies work in recursive dependencies.\n                    commandArgs: [\"print-target-dependencies\", \"--target\", \"FourthTarget\"],\n                    expectedStdout: [\n                        \"Recursive dependencies of 'FourthTarget': [\\\"FirstTarget\\\", \\\"SecondTarget\\\", \\\"ThirdTarget\\\", \\\"HelperLibrary\\\"]\",\n                        \"Module kind of 'FourthTarget': generic\",\n                    ],\n                    expectedStderr: [],\n                ),\n                PluginAPIsData(\n                    // Check some of the other utility APIs.\n                    commandArgs: [\"print-target-dependencies\", \"--target\", \"FifthTarget\"],\n                    expectedStdout: [\n                        \"execProducts: [\\\"FifthTarget\\\"]\",\n                        \"swiftTargets: [\\\"FifthTarget\\\", \\\"FirstTarget\\\", \\\"FourthTarget\\\", \\\"SecondTarget\\\", \\\"TestTarget\\\", \\\"ThirdTarget\\\"]\",\n                        \"swiftSources: [\\\"library.swift\\\", \\\"library.swift\\\", \\\"library.swift\\\", \\\"library.swift\\\", \\\"main.swift\\\", \\\"tests.swift\\\"]\",\n                        \"Module kind of 'FifthTarget': executable\",\n                    ],\n                    expectedStderr: [],\n                ),\n                PluginAPIsData(\n                    // Check a test target.\n                    commandArgs: [\"print-target-dependencies\", \"--target\", \"TestTarget\"],\n                    expectedStdout: [\n                        \"Recursive dependencies of 'TestTarget': [\\\"FirstTarget\\\", \\\"SecondTarget\\\"]\",\n                        \"Module kind of 'TestTarget': test\",\n                    ],\n                    expectedStderr: [],\n                ),\n            ],\n        )\n        func pluginAPIs(\n            buildData: BuildData,\n            testData: PluginAPIsData\n        ) async throws {\n            try await withKnownIssue(isIntermittent: true) {\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a plugin to test various parts of the API.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.createDirectory(packageDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\"Package.swift\"),\n                    string: \"\"\"\n                            // swift-tools-version: 5.9\n                            import PackageDescription\n                            let package = Package(\n                                name: \"MyPackage\",\n                                dependencies: [\n                                    .package(name: \"HelperPackage\", path: \"VendoredDependencies/HelperPackage\")\n                                ],\n                                targets: [\n                                    .target(\n                                        name: \"FirstTarget\",\n                                        dependencies: [\n                                        ]\n                                    ),\n                                    .target(\n                                        name: \"SecondTarget\",\n                                        dependencies: [\n                                            \"FirstTarget\",\n                                        ]\n                                    ),\n                                    .target(\n                                        name: \"ThirdTarget\",\n                                        dependencies: [\n                                            \"FirstTarget\",\n                                        ]\n                                    ),\n                                    .target(\n                                        name: \"FourthTarget\",\n                                        dependencies: [\n                                            \"SecondTarget\",\n                                            \"ThirdTarget\",\n                                            .product(name: \"HelperLibrary\", package: \"HelperPackage\"),\n                                        ]\n                                    ),\n                                    .executableTarget(\n                                        name: \"FifthTarget\",\n                                        dependencies: [\n                                            \"FirstTarget\",\n                                            \"ThirdTarget\",\n                                        ]\n                                    ),\n                                    .testTarget(\n                                        name: \"TestTarget\",\n                                        dependencies: [\n                                            \"SecondTarget\",\n                                        ]\n                                    ),\n                                    .plugin(\n                                        name: \"PrintTargetDependencies\",\n                                        capability: .command(\n                                            intent: .custom(verb: \"print-target-dependencies\", description: \"Plugin that prints target dependencies; argument is name of target\")\n                                        )\n                                    ),\n                                ]\n                            )\n                        \"\"\"\n                )\n\n                let firstTargetDir = packageDir.appending(components: \"Sources\", \"FirstTarget\")\n                try localFileSystem.createDirectory(firstTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    firstTargetDir.appending(\"library.swift\"),\n                    string: \"\"\"\n                        public func FirstFunc() { }\n                        \"\"\"\n                )\n\n                let secondTargetDir = packageDir.appending(components: \"Sources\", \"SecondTarget\")\n                try localFileSystem.createDirectory(secondTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    secondTargetDir.appending(\"library.swift\"),\n                    string: \"\"\"\n                        public func SecondFunc() { }\n                        \"\"\"\n                )\n\n                let thirdTargetDir = packageDir.appending(components: \"Sources\", \"ThirdTarget\")\n                try localFileSystem.createDirectory(thirdTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    thirdTargetDir.appending(\"library.swift\"),\n                    string: \"\"\"\n                        public func ThirdFunc() { }\n                        \"\"\"\n                )\n\n                let fourthTargetDir = packageDir.appending(components: \"Sources\", \"FourthTarget\")\n                try localFileSystem.createDirectory(fourthTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    fourthTargetDir.appending(\"library.swift\"),\n                    string: \"\"\"\n                        public func FourthFunc() { }\n                        \"\"\"\n                )\n\n                let fifthTargetDir = packageDir.appending(components: \"Sources\", \"FifthTarget\")\n                try localFileSystem.createDirectory(fifthTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    fifthTargetDir.appending(\"main.swift\"),\n                    string: \"\"\"\n                        @main struct MyExec {\n                            func run() throws {}\n                        }\n                        \"\"\"\n                )\n\n                let testTargetDir = packageDir.appending(components: \"Tests\", \"TestTarget\")\n                try localFileSystem.createDirectory(testTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    testTargetDir.appending(\"tests.swift\"),\n                    string: \"\"\"\n                        import XCTest\n                        class MyTestCase: XCTestCase {\n                        }\n                        \"\"\"\n                )\n\n                let pluginTargetTargetDir = packageDir.appending(\n                    components: \"Plugins\",\n                    \"PrintTargetDependencies\"\n                )\n                try localFileSystem.createDirectory(pluginTargetTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    pluginTargetTargetDir.appending(\"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        @main struct PrintTargetDependencies: CommandPlugin {\n                            func performCommand(\n                                context: PluginContext,\n                                arguments: [String]\n                            ) throws {\n                                // Print names of the recursive dependencies of the given target.\n                                var argExtractor = ArgumentExtractor(arguments)\n                                guard let targetName = argExtractor.extractOption(named: \"target\").first else {\n                                    throw \"No target argument provided\"\n                                }\n                                guard let target = try? context.package.targets(named: [targetName]).first else {\n                                    throw \"No target found with the name '\\\\(targetName)'\"\n                                }\n                                print(\"Recursive dependencies of '\\\\(target.name)': \\\\(target.recursiveTargetDependencies.map(\\\\.name))\")\n\n                                let execProducts = context.package.products(ofType: ExecutableProduct.self)\n                                print(\"execProducts: \\\\(execProducts.map{ $0.name })\")\n                                let swiftTargets = context.package.targets(ofType: SwiftSourceModuleTarget.self)\n                                print(\"swiftTargets: \\\\(swiftTargets.map{ $0.name }.sorted())\")\n                                let swiftSources = swiftTargets.flatMap{ $0.sourceFiles(withSuffix: \".swift\") }\n                                print(\"swiftSources: \\\\(swiftSources.map{ $0.path.lastComponent }.sorted())\")\n\n                                if let target = target.sourceModule {\n                                    print(\"Module kind of '\\\\(target.name)': \\\\(target.kind)\")\n                                }\n\n                                var sourceModules = context.package.sourceModules\n                                print(\"sourceModules in package: \\\\(sourceModules.map { $0.name })\")\n                                sourceModules = context.package.products.first?.sourceModules ?? []\n                                print(\"sourceModules in first product: \\\\(sourceModules.map { $0.name })\")\n                            }\n                        }\n                        extension String: Error {}\n                        \"\"\"\n                )\n\n                // Create a separate vendored package so that we can test dependencies across products in other packages.\n                let helperPackageDir = packageDir.appending(\n                    components: \"VendoredDependencies\",\n                    \"HelperPackage\"\n                )\n                try localFileSystem.createDirectory(helperPackageDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    helperPackageDir.appending(\"Package.swift\"),\n                    string: \"\"\"\n                        // swift-tools-version: 5.6\n                        import PackageDescription\n                        let package = Package(\n                            name: \"HelperPackage\",\n                            products: [\n                                .library(\n                                    name: \"HelperLibrary\",\n                                    targets: [\"HelperLibrary\"])\n                            ],\n                            targets: [\n                                .target(\n                                    name: \"HelperLibrary\",\n                                    path: \".\")\n                            ]\n                        )\n                        \"\"\"\n                )\n                try localFileSystem.writeFileContents(\n                    helperPackageDir.appending(\"library.swift\"),\n                    string: \"\"\"\n                        public func Foo() { }\n                        \"\"\"\n                )\n\n                let (stdout, stderr) = try await execute(\n                    testData.commandArgs,\n                    packagePath: packageDir,\n                    configuration: buildData.config,\n                    buildSystem: buildData.buildSystem,\n                )\n                for expected in testData.expectedStdout {\n                    #expect(stdout.contains(expected))\n                }\n                for expected in testData.expectedStderr {\n                    #expect(stderr.contains(expected))\n                }\n            }\n            } when: {\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.Plugin,\n            ),\n            arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func pluginCompilationBeforeBuilding(\n            data: BuildData,\n        ) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a couple of plugins a other targets and products.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.createDirectory(packageDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(components: \"Package.swift\"),\n                    string: \"\"\"\n                        // swift-tools-version: 5.6\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            products: [\n                                .library(\n                                    name: \"MyLibrary\",\n                                    targets: [\"MyLibrary\"]\n                                ),\n                                .executable(\n                                    name: \"MyExecutable\",\n                                    targets: [\"MyExecutable\"]\n                                ),\n                            ],\n                            targets: [\n                                .target(\n                                    name: \"MyLibrary\"\n                                ),\n                                .executableTarget(\n                                    name: \"MyExecutable\",\n                                    dependencies: [\"MyLibrary\"]\n                                ),\n                                .plugin(\n                                    name: \"MyBuildToolPlugin\",\n                                    capability: .buildTool()\n                                ),\n                                .plugin(\n                                    name: \"MyCommandPlugin\",\n                                    capability: .command(\n                                        intent: .custom(verb: \"my-build-tester\", description: \"Help description\")\n                                    )\n                                ),\n                            ]\n                        )\n                        \"\"\"\n                )\n                let myLibraryTargetDir = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n                try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myLibraryTargetDir.appending(\"library.swift\"),\n                    string: \"\"\"\n                        public func GetGreeting() -> String { return \"Hello\" }\n                        \"\"\"\n                )\n                let myExecutableTargetDir = packageDir.appending(components: \"Sources\", \"MyExecutable\")\n                try localFileSystem.createDirectory(myExecutableTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myExecutableTargetDir.appending(\"main.swift\"),\n                    string: \"\"\"\n                        import MyLibrary\n                        print(\"\\\\(GetGreeting()), World!\")\n                        \"\"\"\n                )\n                let myBuildToolPluginTargetDir = packageDir.appending(\n                    components: \"Plugins\",\n                    \"MyBuildToolPlugin\"\n                )\n                try localFileSystem.createDirectory(myBuildToolPluginTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myBuildToolPluginTargetDir.appending(\"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        @main struct MyBuildToolPlugin: BuildToolPlugin {\n                            func createBuildCommands(\n                                context: PluginContext,\n                                target: Target\n                            ) throws -> [Command] {\n                                return []\n                            }\n                        }\n                        \"\"\"\n                )\n                let myCommandPluginTargetDir = packageDir.appending(\n                    components: \"Plugins\",\n                    \"MyCommandPlugin\"\n                )\n                try localFileSystem.createDirectory(myCommandPluginTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myCommandPluginTargetDir.appending(\"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        @main struct MyCommandPlugin: CommandPlugin {\n                            func performCommand(\n                                context: PluginContext,\n                                arguments: [String]\n                            ) throws {\n                            }\n                        }\n                        \"\"\"\n                )\n\n                // Check that building without options compiles both plugins and that the build proceeds.\n                do {\n                    let (stdout, _) = try await executeSwiftBuild(\n                        packageDir,\n                        configuration: data.config,\n                        buildSystem: data.buildSystem,\n                    )\n                    if data.buildSystem == .native {\n                        #expect(stdout.contains(\"Compiling plugin MyBuildToolPlugin\"))\n                        #expect(stdout.contains(\"Compiling plugin MyCommandPlugin\"))\n                    }\n                    #expect(stdout.contains(\"Building for \\(data.config.buildFor)...\"))\n                }\n\n                // Check that building just one of them just compiles that plugin and doesn't build anything else.\n                do {\n                    let (stdout, stderr) = try await executeSwiftBuild(\n                        packageDir,\n                        configuration: data.config,\n                        extraArgs: [\"--target\", \"MyCommandPlugin\"],\n                        buildSystem: data.buildSystem,\n                    )\n                    switch data.buildSystem {\n                    case .native:\n                            #expect(!stdout.contains(\"Compiling plugin MyBuildToolPlugin\"), \"stderr: \\(stderr)\")\n                            #expect(stdout.contains(\"Compiling plugin MyCommandPlugin\"), \"stderr: \\(stderr)\")\n                        case .swiftbuild:\n                        // nothing specific\n                        break\n                        case .xcode:\n                            Issue.record(\"Test expected have not been considered\")\n                    }\n                    #expect(!stdout.contains(\"Building for \\(data.config.buildFor)...\"), \"stderr: \\(stderr)\")\n                }\n            }\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.CommandPlugin,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func commandPluginCompilationErrorImplementation(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/Plugins/CommandPluginCompilationError\") { packageDir in\n                // Check that building stops after compiling the plugin and doesn't proceed.\n                // Run this test a number of times to try to catch any race conditions.\n                for num in 1...5 {\n                    await expectThrowsCommandExecutionError(\n                        try await executeSwiftBuild(\n                            packageDir,\n                            configuration: config,\n                            buildSystem: buildSystem,\n                        )\n                    ) { error in\n                        let stdout = error.stdout\n                        let stderr = error.stderr\n                        withKnownIssue(isIntermittent: true) {\n                            #expect(\n                                stdout.contains(\n                                    \"error: consecutive statements on a line must be separated by ';'\"\n                                ),\n                                \"iteration \\(num) failed.  stderr: \\(stderr)\",\n                            )\n                        } when: {\n                            buildSystem == .native\n                        }\n                        #expect(\n                            !stdout.contains(\"Building for \\(config.buildFor)...\"),\n                            \"iteration \\(num) failed.   stderr: \\(stderr)\",\n                        )\n                    }\n                }\n            }\n        }\n\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.Plugin,\n            ),\n            // arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n        )\n        func singlePluginTarget(\n            // data: BuildData,\n        ) async throws {\n            try await testWithTemporaryDirectory { tmpPath in\n                // Create a sample package with a library target and a plugin.\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n                try localFileSystem.createDirectory(packageDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    packageDir.appending(\"Package.swift\"),\n                    string: \"\"\"\n                        // swift-tools-version: 5.7\n                        import PackageDescription\n                        let package = Package(\n                            name: \"MyPackage\",\n                            products: [\n                                .plugin(name: \"Foo\", targets: [\"Foo\"])\n                            ],\n                            dependencies: [\n                            ],\n                            targets: [\n                                .plugin(\n                                    name: \"Foo\",\n                                    capability: .command(\n                                        intent: .custom(verb: \"Foo\", description: \"Plugin example\"),\n                                        permissions: []\n                                    )\n                                )\n                            ]\n                        )\n                        \"\"\"\n                )\n\n                let myPluginTargetDir = packageDir.appending(components: \"Plugins\", \"Foo\")\n                try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)\n                try localFileSystem.writeFileContents(\n                    myPluginTargetDir.appending(\"plugin.swift\"),\n                    string: \"\"\"\n                        import PackagePlugin\n                        @main struct FooPlugin: BuildToolPlugin {\n                            func createBuildCommands(\n                                context: PluginContext,\n                                target: Target\n                            ) throws -> [Command] { }\n                        }\n                        \"\"\"\n                )\n\n                // Load a workspace from the package.\n                let observability = ObservabilitySystem.makeForTesting()\n                let workspace = try Workspace(\n                    fileSystem: localFileSystem,\n                    forRootPackage: packageDir,\n                    customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                    delegate: MockWorkspaceDelegate()\n                )\n\n                // Load the root manifest.\n                let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n                let rootManifests = try await workspace.loadRootManifests(\n                    packages: rootInput.packages,\n                    observabilityScope: observability.topScope\n                )\n                #expect(rootManifests.count == 1, \"Root manifest: \\(rootManifests)\")\n\n                // Load the package graph.\n                let _ = try await workspace.loadPackageGraph(\n                    rootInput: rootInput,\n                    observabilityScope: observability.topScope\n                )\n                expectNoDiagnostics(observability.diagnostics)\n            }\n        }\n\n        @Test(arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms))\n        func commandPluginDynamicDependencies(\n            buildData: BuildData\n        ) async throws {\n            try await withKnownIssue(isIntermittent: true) {\n                try await testWithTemporaryDirectory { tmpPath in\n                    // Create a sample package with a command plugin that has a dynamic dependency.\n                    let packageDir = tmpPath.appending(components: \"MyPackage\")\n                    try localFileSystem.writeFileContents(\n                        packageDir.appending(components: \"Package.swift\"),\n                        string:\n                            \"\"\"\n                            // swift-tools-version: 6.0\n                            // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n                            import PackageDescription\n\n                            let package = Package(\n                                name: \"command-plugin-dynamic-linking\",\n                                products: [\n                                    // Products can be used to vend plugins, making them visible to other packages.\n                                    .plugin(\n                                        name: \"command-plugin-dynamic-linking\",\n                                        targets: [\"command-plugin-dynamic-linking\"]),\n                                ],\n                                dependencies: [\n                                    .package(path: \"LocalPackages/DynamicLib\")\n                                ],\n                                targets: [\n                                    // Targets are the basic building blocks of a package, defining a module or a test suite.\n                                    // Targets can depend on other targets in this package and products from dependencies.\n                                    .executableTarget(\n                                        name: \"Core\",\n                                        dependencies: [\n                                            .product(name: \"DynamicLib\", package: \"DynamicLib\")\n                                        ]\n                                    ),\n                                    .plugin(\n                                        name: \"command-plugin-dynamic-linking\",\n                                        capability: .command(intent: .custom(\n                                            verb: \"command_plugin_dynamic_linking\",\n                                            description: \"prints hello world\"\n                                        )),\n                                        dependencies: [\n                                            \"Core\"\n                                        ]\n                                    )\n                                ]\n                            )\n                            \"\"\"\n                    )\n                    try localFileSystem.writeFileContents(\n                        packageDir.appending(components: \"Sources\", \"Core\", \"Core.swift\"),\n                        string:\n                            \"\"\"\n                            import DynamicLib\n\n                            @main\n                            struct Core {\n                                static func main() {\n                                    let result = dynamicLibFunc()\n                                    print(result)\n                                }\n                            }\n                            \"\"\"\n                    )\n                    try localFileSystem.writeFileContents(\n                        packageDir.appending(components: \"Plugins\", \"command-plugin-dynamic-linking.swift\"),\n                        string:\n                            \"\"\"\n                            import PackagePlugin\n                            import Foundation\n\n                            enum CommandError: Error, CustomStringConvertible {\n                                var description: String {\n                                    String(describing: self)\n                                }\n\n                                case pluginError(String)\n                            }\n\n                            @main\n                            struct command_plugin_dynamic_linking: CommandPlugin {\n                                // Entry point for command plugins applied to Swift Packages.\n                                func performCommand(context: PluginContext, arguments: [String]) async throws {\n                                    let tool = try context.tool(named: \"Core\")\n\n                                    let process = try Process.run(tool.url, arguments: arguments)\n                                    process.waitUntilExit()\n\n                                    if process.terminationReason != .exit || process.terminationStatus != 0 {\n                                        throw CommandError.pluginError(\"\\\\(tool.name) failed\")\n                                    } else {\n                                        print(\"Works fine!\")\n                                    }\n                                }\n                            }\n\n                            #if canImport(XcodeProjectPlugin)\n                            import XcodeProjectPlugin\n\n                            extension command_plugin_dynamic_linking: XcodeCommandPlugin {\n                                // Entry point for command plugins applied to Xcode projects.\n                                func performCommand(context: XcodePluginContext, arguments: [String]) throws {\n                                    print(\"Hello, World!\")\n                                }\n                            }\n\n                            #endif\n                            \"\"\"\n                    )\n\n                    try localFileSystem.writeFileContents(\n                        packageDir.appending(components: \"LocalPackages\", \"DynamicLib\", \"Package.swift\"),\n                        string:\n                            \"\"\"\n                            // swift-tools-version: 6.0\n                            // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n                            import PackageDescription\n\n                            let package = Package(\n                                name: \"DynamicLib\",\n                                products: [\n                                    // Products define the executables and libraries a package produces, making them visible to other packages.\n                                    .library(\n                                        name: \"DynamicLib\",\n                                        type: .dynamic,\n                                        targets: [\"DynamicLib\"]),\n                                ],\n                                targets: [\n                                    // Targets are the basic building blocks of a package, defining a module or a test suite.\n                                    // Targets can depend on other targets in this package and products from dependencies.\n                                    .target(\n                                        name: \"DynamicLib\"),\n                                    .testTarget(\n                                        name: \"DynamicLibTests\",\n                                        dependencies: [\"DynamicLib\"]\n                                    ),\n                                ]\n                            )\n                            \"\"\"\n                    )\n\n                    try localFileSystem.writeFileContents(\n                        packageDir.appending(components: \"LocalPackages\", \"DynamicLib\", \"Sources\", \"DynamicLib.swift\"),\n                        string:\n                            \"\"\"\n                            // The Swift Programming Language\n                            // https://docs.swift.org/swift-book\n\n                            public func dynamicLibFunc() -> String {\n                                return \"Hello from DynamicLib!\"\n                            }\n                            \"\"\"\n                    )\n\n                    let (stdout, _) = try await execute(\n                        [\"plugin\", \"command_plugin_dynamic_linking\"],\n                        packagePath: packageDir,\n                        configuration: buildData.config,\n                        buildSystem: buildData.buildSystem,\n                    )\n\n                    #expect(stdout.contains(\"Works fine!\"))\n                }\n            } when: {\n                [.linux, .windows].contains(ProcessInfo.hostOperatingSystem) && buildData.buildSystem == .swiftbuild\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.Package.GenerateSBOM,\n            .Feature.SBOM,\n        ),\n    )\n\n    struct GenerateSBOMCommandTests {\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSBOMWithoutSpec(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                let customSBOMDir = fixturePath.appending(\"custom-sboms\")\n\n                let (stdout, _) = try await execute(\n                    [\"generate-sbom\", \"--sbom-output-dir\", customSBOMDir.pathString],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                #expect(stdout.contains(\"SBOMs created\"))\n                #expect(localFileSystem.isDirectory(customSBOMDir))\n                let files = try localFileSystem.getDirectoryContents(customSBOMDir)\n                #expect(files.count == 2, \"should produce both CycloneDX and SPDX SBOMs by default\")\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSBOMWithWrongSpec(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                await expectThrowsCommandExecutionError(\n                    try await execute(\n                        [\"generate-sbom\", \"--sbom-spec\", \"cyclonedx22\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(error.stderr.contains(\"The value 'cyclonedx22' is invalid\"))\n                }\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSBOMWithCycloneDXSpec(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                let (stdout, stderr) = try await execute(\n                    [\"generate-sbom\", \"--sbom-spec\", \"cyclonedx\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"SBOMs created\"))\n\n                let prefix = \" SBOM at \"\n                let range = try #require(stdout.range(of: prefix), \"Could not find '\\(prefix)' in output\")\n                let endRange = try #require(stdout[range.upperBound...].range(of: \".json\"), \"Could not find '.json' in output\")\n                let pathString = String(stdout[range.upperBound..<endRange.upperBound])\n                let sbomPath = try AbsolutePath(validating: pathString)\n\n                #expect(localFileSystem.exists(sbomPath))\n                let filesInDirectory = try localFileSystem.getDirectoryContents(sbomPath.parentDirectory)\n                #expect(filesInDirectory.count == 1, \"should only produce 1 CycloneDX SBOM\")\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSBOMWithSPDXSpec(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                let (stdout, stderr) = try await execute(\n                    [\"generate-sbom\", \"--sbom-spec\", \"spdx\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                #expect(stdout.contains(\"SBOMs created\"))\n\n                let prefix = \" SBOM at \"\n                let range = try #require(stdout.range(of: prefix), \"Could not find '\\(prefix)' in output\")\n                let endRange = try #require(stdout[range.upperBound...].range(of: \".json\"), \"Could not find '.json' in output\")\n                let pathString = String(stdout[range.upperBound..<endRange.upperBound])\n                let sbomPath = try AbsolutePath(validating: pathString)\n\n                #expect(localFileSystem.exists(sbomPath))\n                let filesInDirectory = try localFileSystem.getDirectoryContents(sbomPath.parentDirectory)\n                #expect(filesInDirectory.count == 1, \"should only produce 1 SPDX SBOM\")\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSBOMWithCustomDirectory(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                let customSBOMDir = fixturePath.appending(\"custom-sboms\")\n\n                let (stdout, stderr) = try await execute(\n                    [\"generate-sbom\", \"--sbom-spec\", \"cyclonedx\", \"--sbom-output-dir\", customSBOMDir.pathString],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"SBOMs created\"))\n\n                #expect(localFileSystem.isDirectory(customSBOMDir))\n                let files = try localFileSystem.getDirectoryContents(customSBOMDir)\n                    #expect(files.count == 1)\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateCycloneDXSBOMWithProduct(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                let (stdout, stderr) = try await execute(\n                    [\"generate-sbom\", \"--sbom-spec\", \"cyclonedx\", \"--product\", \"Foo\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"SBOMs created\"))\n\n                let prefix = \" SBOM at \"\n                let range = try #require(stdout.range(of: prefix), \"Could not find '\\(prefix)' in output\")\n                let endRange = try #require(stdout[range.upperBound...].range(of: \".json\"), \"Could not find '.json' in output\")\n                let pathString = String(stdout[range.upperBound..<endRange.upperBound])\n                let sbomPath = try AbsolutePath(validating: pathString)\n\n                #expect(localFileSystem.exists(sbomPath))\n                let filesInDirectory = try localFileSystem.getDirectoryContents(sbomPath.parentDirectory)\n                #expect(filesInDirectory.count == 1, \"should only produce 1 CycloneDX SBOM\")\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateCycloneDXSBOMWithTarget(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                await expectThrowsCommandExecutionError(\n                    try await execute(\n                        [\"generate-sbom\", \"--sbom-spec\", \"cyclonedx\", \"--target\", \"Foo\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(error.stderr.contains(\"Unknown option '--target'\"))\n                }\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSPDXSBOMWithProduct(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n            let config = BuildConfiguration.debug\n                let (stdout, stderr) = try await execute(\n                    [\"generate-sbom\", \"--sbom-spec\", \"spdx\", \"--product\", \"Foo\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"SBOMs created\"))\n\n                let prefix = \" SBOM at \"\n                let range = try #require(stdout.range(of: prefix), \"Could not find '\\(prefix)' in output\")\n                let endRange = try #require(stdout[range.upperBound...].range(of: \".json\"), \"Could not find '.json' in output\")\n                let pathString = String(stdout[range.upperBound..<endRange.upperBound])\n                let sbomPath = try AbsolutePath(validating: pathString)\n\n                #expect(localFileSystem.exists(sbomPath))\n                let filesInDirectory = try localFileSystem.getDirectoryContents(sbomPath.parentDirectory)\n                #expect(filesInDirectory.count == 1, \"should only produce 1 SPDX SBOM\")\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSPDXSBOMWithTarget(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                await expectThrowsCommandExecutionError(\n                    try await execute(\n                        [\"generate-sbom\", \"--sbom-spec\", \"spdx\", \"--target\", \"Foo\"],\n                        packagePath: fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(error.stderr.contains(\"Unknown option '--target'\"))\n                }\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSBOMMultipleSpecs(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                let customSBOMDir = fixturePath.appending(\"custom-sboms\")\n\n                let (stdout, stderr) = try await execute(\n                    [\"generate-sbom\", \"--sbom-spec\", \"cyclonedx\", \"--sbom-spec\", \"spdx\", \"--sbom-output-dir\", customSBOMDir.pathString],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                #expect(stdout.contains(\"SBOMs created\"))\n                #expect(localFileSystem.isDirectory(customSBOMDir))\n                let files = try localFileSystem.getDirectoryContents(customSBOMDir)\n                #expect(files.count == 2)\n            }\n        }\n\n        @Test(\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func generateSBOMEmitsWarningAboutBuildTimeConditionals(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                let config = BuildConfiguration.debug\n                let (stdout, stderr) = try await execute(\n                    [\"generate-sbom\", \"--sbom-spec\", \"cyclonedx\"],\n                    packagePath: fixturePath,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                #expect(stderr.contains(\"warning: `generate-sbom` subcommand may be inaccurate as it does not contain build-time conditionals.\"))\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/PackageRegistryCommandTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Commands\nimport Foundation\nimport PackageLoading\nimport PackageModel\nimport PackageRegistry\n@testable import PackageRegistryCommand\nimport struct SPMBuildCore.BuildSystemProvider\nimport PackageSigning\nimport _InternalTestSupport\nimport TSCclibc // for SPM_posix_spawn_file_actions_addchdir_np_supported\nimport Workspace\nimport Testing\n\nimport enum TSCBasic.JSON\nimport struct Basics.AsyncProcessResult\n\nlet defaultRegistryBaseURL = URL(\"https://packages.example.com\")\nlet customRegistryBaseURL = URL(\"https://custom.packages.example.com\")\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .Feature.Command.PackageRegistry.General,\n    ),\n)\nstruct PackageRegistryCommandTests {\n    @discardableResult\n    private func execute(\n        _ args: [String],\n        configuration: BuildConfiguration,\n        packagePath: AbsolutePath? = nil,\n        env: Environment? = nil,\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws -> (stdout: String, stderr: String) {\n        var environment = env ?? [:]\n        // don't ignore local packages when caching\n        environment[\"SWIFTPM_TESTS_PACKAGECACHE\"] = \"1\"\n        return try await executeSwiftPackageRegistry(\n            packagePath,\n            configuration: configuration,\n            extraArgs: args,\n            env: environment,\n            buildSystem: buildSystem,\n        )\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.General,\n        ),\n        .requiresSwiftConcurrencySupport,\n    )\n    func usage() async throws {\n        let stdout = try await SwiftPM.Registry.execute([\"-help\"]).stdout\n        #expect(stdout.contains(\"USAGE: swift package-registry\"), \"got stdout: '\\(stdout)'\")\n    }\n\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.General,\n        ),\n        .requiresSwiftConcurrencySupport,\n    )\n    func seeAlso() async throws {\n        let stdout = try await SwiftPM.Registry.execute([\"--help\"]).stdout\n        #expect(stdout.contains(\"SEE ALSO: swift package\"), \"got stdout: '\\(stdout)'\")\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.General,\n        ),\n    )\n    func commandDoesNotEmitDuplicateSymbols() async throws {\n        let (stdout, stderr) = try await SwiftPM.Registry.execute([\"--help\"])\n        let duplicateSymbolRegex = try #require(duplicateSymbolRegex)\n        #expect(!stdout.contains(duplicateSymbolRegex))\n        #expect(!stderr.contains(duplicateSymbolRegex))\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.General,\n        ),\n        .requiresSwiftConcurrencySupport,\n    )\n    func version() async throws {\n        let stdout = try await SwiftPM.Registry.execute([\"--version\"]).stdout\n        let versionRegex = try Regex(#\"Swift Package Manager -( \\w+ )?\\d+.\\d+.\\d+(-\\w+)?\"#)\n        #expect(stdout.contains(versionRegex))\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Set,\n            .Feature.Command.PackageRegistry.Unset,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func localConfiguration(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            let configurationFilePath = AbsolutePath(\n                \".swiftpm/configuration/registries.json\",\n                relativeTo: packageRoot\n            )\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n\n            // Set default registry\n            do {\n                try await execute(\n                    [\"set\", \"\\(defaultRegistryBaseURL)\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 1)\n                #expect(json[\"registries\"]?.dictionary?[\"[default]\"]?.dictionary?[\"url\"]?.string == \"\\(defaultRegistryBaseURL)\")\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            // Set new default registry\n            do {\n                try await execute(\n                    [\"set\", \"\\(customRegistryBaseURL)\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 1)\n                #expect(json[\"registries\"]?.dictionary?[\"[default]\"]?.dictionary?[\"url\"]?.string == \"\\(customRegistryBaseURL)\")\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            // Set default registry with allow-insecure-http option\n            do {\n                try await execute(\n                    [\"set\", \"\\(customRegistryBaseURL)\", \"--allow-insecure-http\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 1)\n                #expect(json[\"registries\"]?.dictionary?[\"[default]\"]?.dictionary?[\"url\"]?.string == \"\\(customRegistryBaseURL)\")\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            // Unset default registry\n            do {\n                try await execute(\n                    [\"unset\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 0)\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            // Set registry for \"foo\" scope\n            do {\n                try await execute(\n                    [\"set\", \"\\(customRegistryBaseURL)\", \"--scope\", \"foo\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 1)\n                #expect(json[\"registries\"]?.dictionary?[\"foo\"]?.dictionary?[\"url\"]?.string == \"\\(customRegistryBaseURL)\")\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            // Set registry for \"bar\" scope\n            do {\n                try await execute(\n                    [\"set\", \"\\(customRegistryBaseURL)\", \"--scope\", \"bar\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 2)\n                #expect(json[\"registries\"]?.dictionary?[\"foo\"]?.dictionary?[\"url\"]?.string == \"\\(customRegistryBaseURL)\")\n                #expect(json[\"registries\"]?.dictionary?[\"bar\"]?.dictionary?[\"url\"]?.string == \"\\(customRegistryBaseURL)\")\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            // Unset registry for \"foo\" scope\n            do {\n                try await execute(\n                    [\"unset\", \"--scope\", \"foo\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 1)\n                #expect(json[\"registries\"]?.dictionary?[\"bar\"]?.dictionary?[\"url\"]?.string == \"\\(customRegistryBaseURL)\")\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            #expect(localFileSystem.exists(configurationFilePath))\n        }\n    }\n\n    // TODO: Test global configuration\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Set,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func setMissingURL(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            let configurationFilePath = AbsolutePath(\n                \".swiftpm/configuration/registries.json\",\n                relativeTo: packageRoot\n            )\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n\n            // Set default registry\n            await #expect(throws: (any Error).self) {\n                try await execute(\n                    [\"set\", \"--scope\", \"foo\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n            }\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Set,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func setInvalidURL(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            let configurationFilePath = AbsolutePath(\n                \".swiftpm/configuration/registries.json\",\n                relativeTo: packageRoot\n            )\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n\n            // Set default registry\n            await #expect(throws: (any Error).self) {\n                try await execute(\n                    [\"set\", \"invalid\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n            }\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Set,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func setInsecureURL(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            let configurationFilePath = AbsolutePath(\n                \".swiftpm/configuration/registries.json\",\n                relativeTo: packageRoot\n            )\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n\n            // Set default registry\n            await #expect(throws: (any Error).self) {\n                try await execute(\n                    [\"set\", \"http://package.example.com\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n            }\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Set,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func setAllowedInsecureURL(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            let configurationFilePath = AbsolutePath(\n                \".swiftpm/configuration/registries.json\",\n                relativeTo: packageRoot\n            )\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n\n            // Set default registry\n            try await execute(\n                [\"set\", \"http://package.example.com\", \"--allow-insecure-http\"],\n                configuration: config,\n                packagePath: packageRoot,\n                buildSystem: buildSystem,\n            )\n\n            #expect(localFileSystem.exists(configurationFilePath))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Set,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func setInvalidScope(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            let configurationFilePath = AbsolutePath(\n                \".swiftpm/configuration/registries.json\",\n                relativeTo: packageRoot\n            )\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n\n            // Set default registry\n            do {\n                await #expect(throws: (any Error).self) {\n                    try await execute(\n                        [\"set\", \"--scope\", \"_invalid_\", \"\\(defaultRegistryBaseURL)\"],\n                        configuration: config,\n                        packagePath: packageRoot,\n                        buildSystem: buildSystem,\n                    )\n                }\n            }\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Set,\n            .Feature.Command.PackageRegistry.Unset,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func unsetMissingEntry(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"Bar\")\n            let configurationFilePath = AbsolutePath(\n                \".swiftpm/configuration/registries.json\",\n                relativeTo: packageRoot\n            )\n\n            #expect(!localFileSystem.exists(configurationFilePath))\n\n            // Set default registry\n            do {\n                try await execute(\n                    [\"set\", \"\\(defaultRegistryBaseURL)\"],\n                    configuration: config,\n                    packagePath: packageRoot,\n                    buildSystem: buildSystem,\n                )\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 1)\n                #expect(json[\"registries\"]?.dictionary?[\"[default]\"]?.dictionary?[\"url\"]?.string == \"\\(defaultRegistryBaseURL)\")\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            // Unset registry for missing \"baz\" scope\n            do {\n                await #expect(throws: (any Error).self) {\n                    try await execute(\n                        [\"unset\", \"--scope\", \"baz\"],\n                        configuration: config,\n                        packagePath: packageRoot,\n                        buildSystem: buildSystem,\n                    )\n                }\n\n                let json = try JSON(data: localFileSystem.readFileContents(configurationFilePath))\n                #expect(json[\"registries\"]?.dictionary?.count == 1)\n                #expect(json[\"registries\"]?.dictionary?[\"[default]\"]?.dictionary?[\"url\"]?.string == \"\\(defaultRegistryBaseURL)\")\n                #expect(json[\"version\"] == .int(1))\n            }\n\n            #expect(localFileSystem.exists(configurationFilePath))\n        }\n    }\n\n    // TODO: Test example with login and password\n\n    @Test(\n        .tags(\n            .TestSize.large,\n        ),\n        .requiresWorkingDirectorySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func archiving(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let packageIdentity = PackageIdentity.plain(\"org.package\")\n        let metadataFilename = PackageRegistryCommand.Publish.metadataFilename\n\n        // git repo\n        try await withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            initGitRepo(packageDirectory)\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n\n            let archivePath = try await PackageArchiver.archive(\n                packageIdentity: packageIdentity,\n                packageVersion: \"1.3.5\",\n                packageDirectory: packageDirectory,\n                workingDirectory: workingDirectory,\n                workingFilesToCopy: [],\n                cancellator: .none,\n                observabilityScope: observability.topScope\n            )\n\n            try await validatePackageArchive(at: archivePath)\n            #expect(archivePath.isDescendant(of: workingDirectory))\n        }\n\n        // not a git repo\n        try await withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n\n            let archivePath = try await PackageArchiver.archive(\n                packageIdentity: packageIdentity,\n                packageVersion: \"1.5.4\",\n                packageDirectory: packageDirectory,\n                workingDirectory: workingDirectory,\n                workingFilesToCopy: [],\n                cancellator: .none,\n                observabilityScope: observability.topScope\n            )\n\n            try await validatePackageArchive(at: archivePath)\n        }\n\n        // canonical metadata location\n        try await withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            // metadata file\n            try localFileSystem.writeFileContents(\n                packageDirectory.appending(component: metadataFilename),\n                bytes: \"\"\n            )\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n\n            let archivePath = try await PackageArchiver.archive(\n                packageIdentity: packageIdentity,\n                packageVersion: \"0.3.1\",\n                packageDirectory: packageDirectory,\n                workingDirectory: workingDirectory,\n                workingFilesToCopy: [],\n                cancellator: .none,\n                observabilityScope: observability.topScope\n            )\n\n            let extractedPath = try await validatePackageArchive(at: archivePath)\n            expectFileExists(at: extractedPath.appending(component: metadataFilename))\n        }\n\n        @discardableResult\n        func validatePackageArchive(at archivePath: AbsolutePath) async throws -> AbsolutePath {\n            expectFileExists(at: archivePath)\n            let archiver = ZipArchiver(fileSystem: localFileSystem)\n            let extractPath = archivePath.parentDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(extractPath)\n            try await archiver.extract(from: archivePath, to: extractPath)\n            try localFileSystem.stripFirstLevel(of: extractPath)\n            expectFileExists(at: extractPath.appending(\"Package.swift\"))\n            return extractPath\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Publish,\n        ),\n        .requiresWorkingDirectorySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func publishingToHTTPRegistry(\n        buildSystem: BuildSystemProvider.Kind,\n    ) throws {\n        let config = BuildConfiguration.debug\n\n\n        let packageIdentity = \"test.my-package\"\n        let version = \"0.1.0\"\n        let registryURL = \"http://packages.example.com\"\n\n        _ = try withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            await #expect(throws: (any Error).self) {\n                try await executeSwiftPackageRegistry(\n                    packageDirectory,\n                    configuration: config,\n                    extraArgs: [\n                        \"publish\",\n                        packageIdentity,\n                        version,\n                        \"--url=\\(registryURL)\",\n                        \"--scratch-directory=\\(workingDirectory.pathString)\",\n                        \"--dry-run\",\n                    ],\n                    buildSystem: buildSystem,\n                )\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Publish,\n        ),\n        .requiresWorkingDirectorySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func publishingToAllowedHTTPRegistry(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        let packageIdentity = \"test.my-package\"\n        let version = \"0.1.0\"\n        let registryURL = \"http://packages.example.com\"\n\n        // with no authentication configured for registry\n        _ = try await withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            try await executeSwiftPackageRegistry(\n                packageDirectory,\n                configuration: config,\n                extraArgs: [\n                    \"publish\",\n                    packageIdentity,\n                    version,\n                    \"--url=\\(registryURL)\",\n                    \"--scratch-directory=\\(workingDirectory.pathString)\",\n                    \"--allow-insecure-http\",\n                    \"--dry-run\",\n                ],\n                buildSystem: buildSystem,\n            )\n        }\n\n        // with authentication configured for registry\n        _ = try await withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            let configurationFilePath = AbsolutePath(\n                \".swiftpm/configuration/registries.json\",\n                relativeTo: packageDirectory\n            )\n\n            try localFileSystem.createDirectory(configurationFilePath.parentDirectory, recursive: true)\n            var configuration = RegistryConfiguration()\n            try configuration.add(authentication: .init(type: .basic), for: URL(registryURL))\n            try localFileSystem.writeFileContents(configurationFilePath, data: JSONEncoder().encode(configuration))\n\n            await #expect(throws: (any Error).self) {\n                try await executeSwiftPackageRegistry(\n                    packageDirectory,\n                    configuration: config,\n                    extraArgs: [\n                        \"publish\",\n                        packageIdentity,\n                        version,\n                        \"--url=\\(registryURL)\",\n                        \"--scratch-directory=\\(workingDirectory.pathString)\",\n                        \"--allow-insecure-http\",\n                        \"--dry-run\",\n                    ],\n                    buildSystem: buildSystem,\n                )\n            }\n        }\n    }\n\n    @Test(\n        .requiresWorkingDirectorySupport,\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Publish,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func publishingUnsignedPackage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) throws {\n        let config = BuildConfiguration.debug\n        let packageIdentity = \"test.my-package\"\n        let version = \"0.1.0\"\n        let registryURL = \"https://packages.example.com\"\n\n        // custom metadata path\n        _ = try withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            let metadataPath = temporaryDirectory.appending(\"metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, string: \"{}\")\n\n            try await executeSwiftPackageRegistry(\n                packageDirectory,\n                configuration: config,\n                extraArgs: [\n                    \"publish\",\n                    packageIdentity,\n                    version,\n                    \"--url=\\(registryURL)\",\n                    \"--scratch-directory=\\(workingDirectory.pathString)\",\n                    \"--metadata-path=\\(metadataPath.pathString)\",\n                    \"--dry-run\",\n                ],\n                buildSystem: buildSystem,\n            )\n\n            let archivePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).zip\")\n\n            // manifest should not be signed\n            let manifest = try localFileSystem.readFileContents(packageDirectory.appending(\"Package.swift\")).contents\n            try await validateManifest(\n                manifestFile: \"Package.swift\",\n                in: archivePath,\n                manifestContent: manifest\n            )\n        }\n\n        // canonical metadata path\n        _ = try withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            let metadataPath = packageDirectory.appending(PackageRegistryCommand.Publish.metadataFilename)\n            try localFileSystem.writeFileContents(metadataPath, string: \"{}\")\n\n            try await executeSwiftPackageRegistry(\n                packageDirectory,\n                configuration: config,\n                extraArgs: [\n                    \"publish\",\n                    packageIdentity,\n                    version,\n                    \"--url=\\(registryURL)\",\n                    \"--scratch-directory=\\(workingDirectory.pathString)\",\n                    \"--dry-run\",\n                ],\n                buildSystem: buildSystem,\n            )\n\n            let archivePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).zip\")\n\n            // manifest should not be signed\n            let manifest = try localFileSystem.readFileContents(packageDirectory.appending(\"Package.swift\")).contents\n            try await validateManifest(\n                manifestFile: \"Package.swift\",\n                in: archivePath,\n                manifestContent: manifest\n            )\n        }\n\n        // no metadata\n        _ = try withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n            expectFileExists(at: packageDirectory.appending(\"Package.swift\"))\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            try await executeSwiftPackageRegistry(\n                packageDirectory,\n                configuration: config,\n                extraArgs: [\n                    \"publish\",\n                    packageIdentity,\n                    version,\n                    \"--url=\\(registryURL)\",\n                    \"--scratch-directory=\\(workingDirectory.pathString)\",\n                    \"--dry-run\",\n                ],\n                buildSystem: buildSystem,\n            )\n\n            let archivePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).zip\")\n\n            // manifest should not be signed\n            let manifest = try localFileSystem.readFileContents(packageDirectory.appending(\"Package.swift\")).contents\n            try await validateManifest(\n                manifestFile: \"Package.swift\",\n                in: archivePath,\n                manifestContent: manifest\n            )\n        }\n\n        @Sendable\n        func validateManifest(\n            manifestFile: String,\n            in archivePath: AbsolutePath,\n            manifestContent: [UInt8]\n        ) async throws {\n            expectFileExists(at: archivePath)\n            let archiver = ZipArchiver(fileSystem: localFileSystem)\n            let extractPath = archivePath.parentDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(extractPath)\n            try await archiver.extract(from: archivePath, to: extractPath)\n            try localFileSystem.stripFirstLevel(of: extractPath)\n\n            let manifestInArchive = try localFileSystem.readFileContents(extractPath.appending(manifestFile)).contents\n            #expect(manifestInArchive == manifestContent)\n        }\n    }\n\n    @Test(\n        .requiresWorkingDirectorySupport,\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Publish,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)\n    func publishingSignedPackage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        let observabilityScope = ObservabilitySystem.makeForTesting().topScope\n\n        let packageIdentity = \"test.my-package\"\n        let version = \"0.1.0\"\n        let registryURL = \"https://packages.example.com\"\n        let signatureFormat = SignatureFormat.cms_1_0_0\n\n        // custom metadata path\n        try await withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n\n            let manifestPath = packageDirectory.appending(\"Package.swift\")\n            expectFileExists(at: manifestPath)\n\n            let versionSpecificManifestPath = packageDirectory.appending(\"Package@swift-\\(ToolsVersion.current).swift\")\n            try localFileSystem.copy(from: manifestPath, to: versionSpecificManifestPath)\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            let metadataPath = temporaryDirectory.appending(\"metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, string: \"{}\")\n\n            let certificatePath = temporaryDirectory.appending(component: \"certificate.cer\")\n            let intermediateCertificatePath = temporaryDirectory.appending(component: \"intermediate.cer\")\n            let privateKeyPath = temporaryDirectory.appending(component: \"private-key.p8\")\n\n            try fixture(name: \"Signing\") { fixturePath in\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"Test_ec.cer\"),\n                    to: certificatePath\n                )\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"Test_ec_key.p8\"),\n                    to: privateKeyPath\n                )\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                    to: intermediateCertificatePath\n                )\n            }\n\n            try await executeSwiftPackageRegistry(\n                packageDirectory,\n                configuration: config,\n                extraArgs: [\n                    \"publish\",\n                    packageIdentity,\n                    version,\n                    \"--url=\\(registryURL)\",\n                    \"--scratch-directory=\\(workingDirectory.pathString)\",\n                    \"--metadata-path=\\(metadataPath.pathString)\",\n                    \"--private-key-path=\\(privateKeyPath.pathString)\",\n                    \"--cert-chain-paths=\\(certificatePath.pathString)\",\n                    \"\\(intermediateCertificatePath.pathString)\",\n                    \"--dry-run\",\n                ],\n                buildSystem: buildSystem,\n            )\n\n            // Validate signatures\n            var verifierConfiguration = VerifierConfiguration()\n            verifierConfiguration.trustedRoots = try getRoots()\n\n            // archive signature\n            let archivePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).zip\")\n            let archive = try localFileSystem.readFileContents(archivePath).contents\n            let signaturePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).sig\")\n            let signature = try localFileSystem.readFileContents(signaturePath).contents\n            try await self.validateSignature(\n                signature: signature,\n                content: archive,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n\n            // metadata signature\n            let metadata = try localFileSystem.readFileContents(metadataPath).contents\n            let metadataSignaturePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version)-metadata.sig\")\n            let metadataSignature = try localFileSystem.readFileContents(metadataSignaturePath).contents\n            try await self.validateSignature(\n                signature: metadataSignature,\n                content: metadata,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n\n            // manifest signatures\n            let manifest = try localFileSystem.readFileContents(manifestPath).contents\n            try await self.validateSignedManifest(\n                manifestFile: \"Package.swift\",\n                in: archivePath,\n                manifestContent: manifest,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n\n            let versionSpecificManifest = try localFileSystem.readFileContents(versionSpecificManifestPath).contents\n            try await self.validateSignedManifest(\n                manifestFile: \"Package@swift-\\(ToolsVersion.current).swift\",\n                in: archivePath,\n                manifestContent: versionSpecificManifest,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n        }\n\n        // canonical metadata path\n        try await withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n\n            let manifestPath = packageDirectory.appending(\"Package.swift\")\n            expectFileExists(at: manifestPath)\n\n            let versionSpecificManifestPath = packageDirectory.appending(\"Package@swift-\\(ToolsVersion.current).swift\")\n            try localFileSystem.copy(from: manifestPath, to: versionSpecificManifestPath)\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            let metadataPath = packageDirectory.appending(PackageRegistryCommand.Publish.metadataFilename)\n            try localFileSystem.writeFileContents(metadataPath, string: \"{}\")\n\n            let certificatePath = temporaryDirectory.appending(component: \"certificate.cer\")\n            let intermediateCertificatePath = temporaryDirectory.appending(component: \"intermediate.cer\")\n            let privateKeyPath = temporaryDirectory.appending(component: \"private-key.p8\")\n\n            try fixture(name: \"Signing\") { fixturePath in\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"Test_ec.cer\"),\n                    to: certificatePath\n                )\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"Test_ec_key.p8\"),\n                    to: privateKeyPath\n                )\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                    to: intermediateCertificatePath\n                )\n            }\n\n            try await executeSwiftPackageRegistry(\n                packageDirectory,\n                configuration: config,\n                extraArgs: [\n                    \"publish\",\n                    packageIdentity,\n                    version,\n                    \"--url=\\(registryURL)\",\n                    \"--scratch-directory=\\(workingDirectory.pathString)\",\n                    \"--private-key-path=\\(privateKeyPath.pathString)\",\n                    \"--cert-chain-paths=\\(certificatePath.pathString)\",\n                    \"\\(intermediateCertificatePath.pathString)\",\n                    \"--dry-run\",\n                ],\n                buildSystem: buildSystem,\n            )\n\n            // Validate signatures\n            var verifierConfiguration = VerifierConfiguration()\n            verifierConfiguration.trustedRoots = try getRoots()\n\n            // archive signature\n            let archivePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).zip\")\n            let archive = try localFileSystem.readFileContents(archivePath).contents\n            let signaturePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).sig\")\n            let signature = try localFileSystem.readFileContents(signaturePath).contents\n            try await self.validateSignature(\n                signature: signature,\n                content: archive,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n\n            // metadata signature\n            let metadata = try localFileSystem.readFileContents(metadataPath).contents\n            let metadataSignaturePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version)-metadata.sig\")\n            let metadataSignature = try localFileSystem.readFileContents(metadataSignaturePath).contents\n            try await self.validateSignature(\n                signature: metadataSignature,\n                content: metadata,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n\n            // manifest signatures\n            let manifest = try localFileSystem.readFileContents(manifestPath).contents\n            try await self.validateSignedManifest(\n                manifestFile: \"Package.swift\",\n                in: archivePath,\n                manifestContent: manifest,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n\n            let versionSpecificManifest = try localFileSystem.readFileContents(versionSpecificManifestPath).contents\n            try await self.validateSignedManifest(\n                manifestFile: \"Package@swift-\\(ToolsVersion.current).swift\",\n                in: archivePath,\n                manifestContent: versionSpecificManifest,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n        }\n\n        // no metadata\n        try await withTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            try localFileSystem.createDirectory(packageDirectory)\n\n            let initPackage = try InitPackage(\n                name: \"MyPackage\",\n                packageType: .executable,\n                destinationPath: packageDirectory,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n\n            let manifestPath = packageDirectory.appending(\"Package.swift\")\n            expectFileExists(at: manifestPath)\n\n            let versionSpecificManifestPath = packageDirectory.appending(\"Package@swift-\\(ToolsVersion.current).swift\")\n            try localFileSystem.copy(from: manifestPath, to: versionSpecificManifestPath)\n\n            let workingDirectory = temporaryDirectory.appending(component: UUID().uuidString)\n            try localFileSystem.createDirectory(workingDirectory)\n\n            let certificatePath = temporaryDirectory.appending(component: \"certificate.cer\")\n            let intermediateCertificatePath = temporaryDirectory.appending(component: \"intermediate.cer\")\n            let privateKeyPath = temporaryDirectory.appending(component: \"private-key.p8\")\n\n            try fixture(name: \"Signing\") { fixturePath in\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"Test_ec.cer\"),\n                    to: certificatePath\n                )\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"Test_ec_key.p8\"),\n                    to: privateKeyPath\n                )\n                try localFileSystem.copy(\n                    from: fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                    to: intermediateCertificatePath\n                )\n            }\n\n            try await executeSwiftPackageRegistry(\n                packageDirectory,\n                configuration: config,\n                extraArgs: [\n                    \"publish\",\n                    packageIdentity,\n                    version,\n                    \"--url=\\(registryURL)\",\n                    \"--scratch-directory=\\(workingDirectory.pathString)\",\n                    \"--private-key-path=\\(privateKeyPath.pathString)\",\n                    \"--cert-chain-paths=\\(certificatePath.pathString)\",\n                    \"\\(intermediateCertificatePath.pathString)\",\n                    \"--dry-run\",\n                ],\n                buildSystem: buildSystem,\n            )\n\n            // Validate signatures\n            var verifierConfiguration = VerifierConfiguration()\n            verifierConfiguration.trustedRoots = try getRoots()\n\n            // archive signature\n            let archivePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).zip\")\n            let archive = try localFileSystem.readFileContents(archivePath).contents\n            let signaturePath = workingDirectory.appending(\"\\(packageIdentity)-\\(version).sig\")\n            let signature = try localFileSystem.readFileContents(signaturePath).contents\n            try await self.validateSignature(\n                signature: signature,\n                content: archive,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n\n            // no metadata so no signature\n            #expect(!localFileSystem\n                .exists(workingDirectory.appending(\"\\(packageIdentity)-\\(version)-metadata.sig\")))\n\n            // manifest signatures\n            let manifest = try localFileSystem.readFileContents(manifestPath).contents\n            try await self.validateSignedManifest(\n                manifestFile: \"Package.swift\",\n                in: archivePath,\n                manifestContent: manifest,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n\n            let versionSpecificManifest = try localFileSystem.readFileContents(versionSpecificManifestPath).contents\n            try await self.validateSignedManifest(\n                manifestFile: \"Package@swift-\\(ToolsVersion.current).swift\",\n                in: archivePath,\n                manifestContent: versionSpecificManifest,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: observabilityScope\n            )\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Login,\n        ),\n    )\n    func loginRequiresHTTPS() async {\n        let registryURL = URL(string: \"http://packages.example.com\")!\n\n        await #expect(throws: (any Error).self) {\n            try await SwiftPM.Registry.execute([\"login\", \"--url\", registryURL.absoluteString])\n        }\n    }\n\n    struct LogingUrlData {\n        let loginApiPath: String?\n        let expectedComponent: String\n    }\n    @Test(\n        .tags(\n            .TestSize.large,\n            .Feature.Command.PackageRegistry.Login,\n        ),\n        arguments: [\n            LogingUrlData(loginApiPath: nil, expectedComponent: \"login\"),\n            LogingUrlData(loginApiPath: \"/secret-sign-in\", expectedComponent: \"secret-sign-in\"),\n        ], [\n            \"https://packages.example.com\",\n            // \"https://packages.example.com:8081\",\n        ]\n    )\n    func createLoginURL(\n        data: LogingUrlData,\n        registryUrl: String,\n    ) async throws {\n        let registryURL = try #require(URL(string: registryUrl), \"Failed to instantiate registry URL\")\n\n        let actualUrl =  try PackageRegistryCommand.Login.loginURL(from: registryURL, loginAPIPath: data.loginApiPath)\n        let actualString =  actualUrl.absoluteString\n\n        #expect(actualString == \"\\(registryUrl)/\\(data.expectedComponent)\")\n    }\n\n    @Test(\n        .tags(\n            .TestSize.small,\n        ),\n    )\n    func validateRegistryURL() throws {\n\n        try URL(string: \"https://packages.example.com\")!.validateRegistryURL()\n        try URL(string: \"https://packages.example.com\")!.validateRegistryURL(allowHTTP: true)\n\n        // Invalid\n        #expect(throws: (any Error).self) {\n            try URL(string: \"http://packages.example.com\")!.validateRegistryURL()\n        }\n        #expect(throws: (any Error).self) {\n            try URL(string: \"http://packages.example.com\")!.validateRegistryURL(allowHTTP: false)\n        }\n        #expect(throws: (any Error).self) {\n            try URL(string: \"ssh://packages.example.com\")!.validateRegistryURL()\n        }\n        #expect(throws: (any Error).self) {\n            try URL(string: \"ftp://packages.example.com\")!.validateRegistryURL(allowHTTP: true)\n        }\n    }\n\n    private func getRoots() throws -> [[UInt8]] {\n        try fixture(name: \"Signing\") { fixturePath in\n            let rootCA = try localFileSystem\n                .readFileContents(fixturePath.appending(components: \"Certificates\", \"TestRootCA.cer\")).contents\n            return [rootCA]\n        }\n    }\n\n    private func validateSignature(\n        signature: [UInt8],\n        content: [UInt8],\n        format: SignatureFormat = .cms_1_0_0,\n        verifierConfiguration: VerifierConfiguration,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        let signatureStatus = try await SignatureProvider.status(\n            signature: signature,\n            content: content,\n            format: format,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: observabilityScope\n        )\n        guard case .valid = signatureStatus else {\n            Issue.record(\"Expected signature status to be .valid but got \\(signatureStatus)\")\n            return\n        }\n    }\n\n    private func validateSignedManifest(\n        manifestFile: String,\n        in archivePath: AbsolutePath,\n        manifestContent: [UInt8],\n        format: SignatureFormat = .cms_1_0_0,\n        verifierConfiguration: VerifierConfiguration,\n        observabilityScope: ObservabilityScope\n    ) async throws {\n        expectFileExists(at: archivePath)\n        let archiver = ZipArchiver(fileSystem: localFileSystem)\n        let extractPath = archivePath.parentDirectory.appending(component: UUID().uuidString)\n        try localFileSystem.createDirectory(extractPath)\n        try await archiver.extract(from: archivePath, to: extractPath)\n        try localFileSystem.stripFirstLevel(of: extractPath)\n\n        let manifestSignature = try ManifestSignatureParser.parse(\n            manifestPath: extractPath.appending(manifestFile),\n            fileSystem: localFileSystem\n        )\n        #expect(manifestSignature != nil)\n        #expect(manifestSignature!.contents == manifestContent)\n        let signature = manifestSignature!.signature\n        try await self.validateSignature(\n            signature: signature,\n            content: manifestContent,\n            format: format,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: observabilityScope\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/RunCommandTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Foundation.ProcessInfo\nimport Foundation\n\nimport Basics\nimport Commands\nimport struct SPMBuildCore.BuildSystemProvider\nimport _InternalTestSupport\nimport TSCTestSupport\nimport Testing\n\nimport enum PackageModel.BuildConfiguration\nimport class Basics.AsyncProcess\n\n@Suite(\n    .serialized, // to limit the number of swift executable running.\n    .tags(\n        Tag.TestSize.large,\n        Tag.Feature.Command.Run,\n    ),\n)\nstruct RunCommandTests {\n\n    private func execute(\n        _ args: [String] = [],\n        _ executable: String? = nil,\n        packagePath: AbsolutePath? = nil,\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws -> (stdout: String, stderr: String) {\n        return try await executeSwiftRun(\n            packagePath,\n            executable,\n            extraArgs: args,\n            buildSystem: buildSystem,\n        )\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func usage(\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        let stdout = try await execute([\"-help\"], buildSystem: buildSystem).stdout\n\n        #expect(stdout.contains(\"USAGE: swift run <options>\") || stdout.contains(\"USAGE: swift run [<options>]\"), \"got stdout:\\n \\(stdout)\")\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func seeAlso(\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        let stdout = try await execute([\"--help\"], buildSystem: buildSystem).stdout\n        #expect(stdout.contains(\"SEE ALSO: swift build, swift package, swift test\"), \"got stdout:\\n \\(stdout)\")\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func commandDoesNotEmitDuplicateSymbols(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let duplicateSymbolRegex = try #require(duplicateSymbolRegex)\n        let (stdout, stderr) = try await execute([\"--help\"], buildSystem: buildSystem)\n        #expect(!stdout.contains(duplicateSymbolRegex))\n        #expect(!stderr.contains(duplicateSymbolRegex))\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func version(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let stdout = try await execute([\"--version\"], buildSystem: buildSystem).stdout\n        let versionRegex = try Regex(#\"Swift Package Manager -( \\w+ )?\\d+.\\d+.\\d+(-\\w+)?\"#)\n        #expect(stdout.contains(versionRegex))\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .SWBINTTODO(\"Test package fails to build on Windows\"),\n        .tags(\n            .Feature.CommandLineArguments.Toolset,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Configuration,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func toolsetDebugger(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/EchoExecutable\") { fixturePath in\n            #if os(Windows)\n                let win32 = \".win32\"\n            #else\n                let win32 = \"\"\n            #endif\n            let (stdout, stderr) = try await execute(\n                    [\"--toolset\", \"\\(fixturePath.appending(\"toolset\\(win32).json\").pathString)\"],\n                    packagePath: fixturePath,\n                    buildSystem: buildSystem,\n                )\n\n            // We only expect tool's output on the stdout stream.\n            #expect(stdout.contains(\"\\(fixturePath.appending(\".build\").pathString)\"))\n            #expect(stdout.contains(\"sentinel\"))\n\n            // swift-build-tool output should go to stderr.\n            switch buildSystem {\n                case .native:\n                    #expect(stderr.contains(\"Compiling\"))\n                    #expect(stderr.contains(\"Linking\"))\n                case .swiftbuild:\n                    break\n                case .xcode:\n                    Issue.record(\"Test expectations have not been implemented\")\n            }\n        }\n    }\n\n    @Test(\n         .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func productArgumentPassing(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/EchoExecutable\") { fixturePath in\n            let (stdout, stderr) = try await execute(\n                [\"secho\", \"1\", \"--hello\", \"world\"],\n                packagePath: fixturePath,\n                buildSystem: buildSystem,\n            )\n\n            // We only expect tool's output on the stdout stream.\n            #expect(stdout.contains(\"\"\"\n                \"1\" \"--hello\" \"world\"\n                \"\"\"))\n\n            // swift-build-tool output should go to stderr.\n            switch buildSystem {\n                case .native:\n                    #expect(stderr.contains(\"Compiling\"))\n                    #expect(stderr.contains(\"Linking\"))\n                case .swiftbuild:\n                    break\n                case .xcode:\n                    Issue.record(\"Test expectations have not been implemented\")\n            }\n        }\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8279\"),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func unknownProductRaisesAnError(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/EchoExecutable\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute([\"unknown\"], packagePath: fixturePath, buildSystem: buildSystem)\n            }\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            #expect(\n                stderr.contains(\"error: no executable product named 'unknown'\"),\n                \"got stdout: \\(stdout), stderr: \\(stderr)\",\n            )\n\n        }\n    }\n\n\n    @Test(\n         .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .SWBINTTODO(\"Swift run using Swift Build does not output executable content to the terminal\"),\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8279\"),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func multipleExecutableAndExplicitExecutable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/MultipleExecutables\") { fixturePath in\n\n                let error = await #expect(throws: SwiftPMError.self ) {\n                    try await execute(packagePath: fixturePath, buildSystem: buildSystem)\n                }\n                guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                    Issue.record(\"Incorrect error was raised.\")\n                    return\n                }\n\n                #expect(\n                    stderr.contains(\"error: multiple executable products available: exec1, exec2\"),\n                    \"got stdout: \\(stdout), stderr: \\(stderr)\",\n                )\n\n                var (runOutput, _) = try await execute([\"exec1\"], packagePath: fixturePath, buildSystem: buildSystem)\n                #expect(runOutput.contains(\"1\"))\n\n                (runOutput, _) = try await execute([\"exec2\"], packagePath: fixturePath, buildSystem: buildSystem)\n                #expect(runOutput.contains(\"2\"))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func unreachableExecutable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/UnreachableTargets\", createGitRepo: true) { fixturePath in\n                let (output, _) = try await execute([\"bexec\"], packagePath: fixturePath.appending(\"A\"), buildSystem: buildSystem)\n                let outputLines = output.split(whereSeparator: { $0.isNewline })\n                #expect(String(outputLines[0]).contains(\"BTarget2\"))\n            }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && CiEnvironment.runningInSmokeTestPipeline && [.native, .swiftbuild].contains(buildSystem))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func fileDeprecation(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/EchoExecutable\") { fixturePath in\n                let filePath = AbsolutePath(fixturePath, \"Sources/secho/main.swift\").pathString\n                let cwd = try #require(localFileSystem.currentWorkingDirectory, \"Current working directory should not be nil\")\n                let (stdout, stderr) = try await execute([filePath, \"1\", \"2\"], packagePath: fixturePath, buildSystem: buildSystem)\n                #expect(stdout.contains(#\"\"\\#(cwd)\" \"1\" \"2\"\"#))\n                #expect(stderr.contains(\"warning: 'swift run \\(filePath)' command to interpret swift files is deprecated; use 'swift \\(filePath)' instead\"))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.BuildTests,\n            .Feature.CommandLineArguments.SkipBuild\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func mutualExclusiveFlags(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/EchoExecutable\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self ) {\n                try await execute([\"--build-tests\", \"--skip-build\"], packagePath: fixturePath, buildSystem: buildSystem)\n            }\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            #expect(\n                stderr.contains(\"error: '--build-tests' and '--skip-build' are mutually exclusive\"),\n                \"got stdout: \\(stdout), stderr: \\(stderr)\",\n            )\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func swiftRunSIGINT(\n        buildSystem: BuildSystemProvider.Kind,\n    ) throws {\n        try withKnownIssue(\"Seems to be flaky in CI\", isIntermittent: true) {\n            try fixture(name: \"Miscellaneous/SwiftRun\") { fixturePath in\n                let mainFilePath = fixturePath.appending(\"main.swift\")\n                try localFileSystem.removeFileTree(mainFilePath)\n                try localFileSystem.writeFileContents(\n                    mainFilePath,\n                    string: \"\"\"\n                    import Foundation\n\n                    print(\"sleeping\")\n                    fflush(stdout)\n\n                    Thread.sleep(forTimeInterval: 10)\n                    print(\"done\")\n                    \"\"\"\n                )\n\n                let sync = DispatchGroup()\n                let outputHandler = OutputHandler(sync: sync)\n\n                var environment = Environment.current\n                environment[\"SWIFTPM_EXEC_NAME\"] = \"swift-run\"\n                let process = AsyncProcess(\n                    arguments: [SwiftPM.Run.xctestBinaryPath.pathString, \"--package-path\", fixturePath.pathString],\n                    environment: environment,\n                    outputRedirection: .stream(stdout: outputHandler.handle(bytes:), stderr: outputHandler.handle(bytes:))\n                )\n\n                sync.enter()\n                try process.launch()\n\n                // wait for the process to start\n                try #require(sync.wait(timeout: .now() + .seconds(300)) != .timedOut, \"timeout waiting for process to start\")\n\n                // interrupt the process\n                print(\"interrupting\")\n                process.signal(SIGINT)\n\n                // check for interrupt result\n                let result = try process.waitUntilExit()\n    #if os(Windows)\n                #expect(result.exitStatus == .abnormal(exception: 2))\n    #else\n                #expect(result.exitStatus == .signalled(signal: SIGINT))\n    #endif\n            }\n\n            class OutputHandler {\n                let sync: DispatchGroup\n                var state = State.idle\n                let lock = NSLock()\n\n                init(sync: DispatchGroup) {\n                    self.sync = sync\n                }\n\n                @Sendable func handle(bytes: [UInt8]) {\n                    guard let output = String(bytes: bytes, encoding: .utf8) else {\n                        return\n                    }\n                    print(output, terminator: \"\")\n                    self.lock.withLock {\n                        switch self.state {\n                        case .idle:\n                            self.state = processOutput(output)\n                        case .buffering(let buffer):\n                            let newBuffer = buffer + output\n                            self.state = processOutput(newBuffer)\n                        case .done:\n                            break //noop\n                        }\n                    }\n\n                    func processOutput(_ output: String) -> State {\n                        if output.contains(\"sleeping\") {\n                            self.sync.leave()\n                            return .done\n                        } else {\n                            return .buffering(output)\n                        }\n                    }\n                }\n\n                enum State {\n                    case idle\n                    case buffering(String)\n                    case done\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || CiEnvironment.runningInSelfHostedPipeline)\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.Quiet\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8844\", relationship: .verifies),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8911\", relationship: .defect),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8912\", relationship: .defect),\n        arguments: SupportedBuildSystemOnPlatform, BuildConfiguration.allCases,\n    )\n    func swiftRunQuietLogLevel(\n        buildSystem: BuildSystemProvider.Kind,\n        configuration: BuildConfiguration,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            // GIVEN we have a simple test package\n            try await fixture(name: \"Miscellaneous/SwiftRun\") { fixturePath in\n               //WHEN we run with the --quiet option\n               let (stdout, stderr) = try await executeSwiftRun(\n                   fixturePath,\n                   nil,\n                   configuration: configuration,\n                   extraArgs: [\"--quiet\"],\n                   buildSystem: buildSystem\n               )\n               // THEN we should not see any output in stderr\n                #expect(stderr.isEmpty)\n               // AND no content in stdout\n                #expect(stdout == \"done\\n\")\n           }\n        } when: {\n           (CiEnvironment.runningInSmokeTestPipeline && ProcessInfo.hostOperatingSystem == .windows)\n        }\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8844\"),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func swiftRunQuietLogLevelWithError(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        // GIVEN we have a simple test package\n        try await fixture(name: \"Miscellaneous/SwiftRun\") { fixturePath in\n            let mainFilePath = fixturePath.appending(\"main.swift\")\n            try localFileSystem.removeFileTree(mainFilePath)\n            try localFileSystem.writeFileContents(\n                mainFilePath,\n                string: \"\"\"\n                print(\"done\"\n                \"\"\"\n            )\n\n            //WHEN we run with the --quiet option\n            let error = await #expect(throws: SwiftPMError.self) {\n                try await executeSwiftRun(\n                    fixturePath,\n                    nil,\n                    configuration: configuration,\n                    extraArgs: [\"--quiet\"],\n                    buildSystem: buildSystem\n                )\n            }\n\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            // THEN we should see an output in stderr\n            #expect(stderr.isEmpty == false)\n            // AND no content in stdout\n            #expect(stdout.isEmpty)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/Sanitizer+ExtensionsTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\nimport enum PackageModel.Sanitizer\n\n@Suite(\n    .tags(\n        .TestSize.small,\n        .FunctionalArea.Sanitizer,\n    ),\n)\nstruct SanitizerExtensionTests {\n    @Test(\n        arguments: Sanitizer.allCases\n    )\n    func creatingSanitizers(sanitizer: Sanitizer) throws {\n            #expect(sanitizer == Sanitizer(argument: sanitizer.shortName))\n    }\n\n    @Test\n    func invalidSanitizer() throws {\n        #expect(Sanitizer(argument: \"invalid\") == nil)\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/SwiftCommandStateTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\n@testable import Build\n@testable import Commands\n@testable import CoreCommands\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport func PackageGraph.loadModulesGraph\n\nimport _InternalTestSupport\n@testable import PackageModel\nimport XCTest\n\nimport ArgumentParser\nimport class TSCBasic.BufferedOutputByteStream\nimport protocol TSCBasic.OutputByteStream\nimport enum TSCBasic.SystemError\nimport var TSCBasic.stderrStream\n\nfinal class SwiftCommandStateTests: XCTestCase {\n    /// Original working directory before the test ran (if known).\n    private var originalWorkingDirectory: AbsolutePath? = .none\n\n    override func setUp() {\n        originalWorkingDirectory = localFileSystem.currentWorkingDirectory\n    }\n\n    override func tearDown() {\n        if let originalWorkingDirectory {\n            try? localFileSystem.changeCurrentWorkingDirectory(to: originalWorkingDirectory)\n        }\n     }\n\n    func testSeverityEnum() async throws {\n        try fixtureXCTest(name: \"Miscellaneous/Simple\") { _ in\n\n            do {\n                let info = Diagnostic(severity: .info, message: \"info-string\", metadata: nil)\n                let debug = Diagnostic(severity: .debug, message: \"debug-string\", metadata: nil)\n                let warning = Diagnostic(severity: .warning, message: \"warning-string\", metadata: nil)\n                let error = Diagnostic(severity: .error, message: \"error-string\", metadata: nil)\n                // testing color\n                XCTAssertEqual(info.severity.color, .white)\n                XCTAssertEqual(debug.severity.color, .white)\n                XCTAssertEqual(warning.severity.color, .yellow)\n                XCTAssertEqual(error.severity.color, .red)\n\n                // testing prefix\n                XCTAssertEqual(info.severity.logLabel, \"info: \")\n                XCTAssertEqual(debug.severity.logLabel, \"debug: \")\n                XCTAssertEqual(warning.severity.logLabel, \"warning: \")\n                XCTAssertEqual(error.severity.logLabel, \"error: \")\n\n                // testing boldness\n                XCTAssertTrue(info.severity.isBold)\n                XCTAssertTrue(debug.severity.isBold)\n                XCTAssertTrue(warning.severity.isBold)\n                XCTAssertTrue(error.severity.isBold)\n            }\n        }\n    }\n\n    func testVerbosityLogLevel() async throws {\n        try fixtureXCTest(name: \"Miscellaneous/Simple\") { fixturePath in\n            do {\n                let outputStream = BufferedOutputByteStream()\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString])\n                let tool = try SwiftCommandState.makeMockState(outputStream: outputStream, options: options)\n                XCTAssertEqual(tool.logLevel, .warning)\n\n                tool.observabilityScope.emit(error: \"error\")\n                tool.observabilityScope.emit(warning: \"warning\")\n                tool.observabilityScope.emit(info: \"info\")\n                tool.observabilityScope.emit(debug: \"debug\")\n\n                tool.waitForObservabilityEvents(timeout: .now() + .seconds(1))\n\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"error: error\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"warning: warning\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"info: info\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"debug: debug\"))\n            }\n\n            do {\n                let outputStream = BufferedOutputByteStream()\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString, \"--verbose\"])\n                let tool = try SwiftCommandState.makeMockState(outputStream: outputStream, options: options)\n                XCTAssertEqual(tool.logLevel, .info)\n\n                tool.observabilityScope.emit(error: \"error\")\n                tool.observabilityScope.emit(warning: \"warning\")\n                tool.observabilityScope.emit(info: \"info\")\n                tool.observabilityScope.emit(debug: \"debug\")\n\n                tool.waitForObservabilityEvents(timeout: .now() + .seconds(1))\n\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"error: error\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"warning: warning\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"info: info\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"debug: debug\"))\n            }\n\n            do {\n                let outputStream = BufferedOutputByteStream()\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString, \"-v\"])\n                let tool = try SwiftCommandState.makeMockState(outputStream: outputStream, options: options)\n                XCTAssertEqual(tool.logLevel, .info)\n\n                tool.observabilityScope.emit(error: \"error\")\n                tool.observabilityScope.emit(warning: \"warning\")\n                tool.observabilityScope.emit(info: \"info\")\n                tool.observabilityScope.emit(debug: \"debug\")\n\n                tool.waitForObservabilityEvents(timeout: .now() + .seconds(1))\n\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"error: error\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"warning: warning\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"info: info\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"debug: debug\"))\n            }\n\n            do {\n                let outputStream = BufferedOutputByteStream()\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString, \"--very-verbose\"])\n                let tool = try SwiftCommandState.makeMockState(outputStream: outputStream, options: options)\n                XCTAssertEqual(tool.logLevel, .debug)\n\n                tool.observabilityScope.emit(error: \"error\")\n                tool.observabilityScope.emit(warning: \"warning\")\n                tool.observabilityScope.emit(info: \"info\")\n                tool.observabilityScope.emit(debug: \"debug\")\n\n                tool.waitForObservabilityEvents(timeout: .now() + .seconds(1))\n\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"error: error\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"warning: warning\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"info: info\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"debug: debug\"))\n            }\n\n            do {\n                let outputStream = BufferedOutputByteStream()\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString, \"--vv\"])\n                let tool = try SwiftCommandState.makeMockState(outputStream: outputStream, options: options)\n                XCTAssertEqual(tool.logLevel, .debug)\n\n                tool.observabilityScope.emit(error: \"error\")\n                tool.observabilityScope.emit(warning: \"warning\")\n                tool.observabilityScope.emit(info: \"info\")\n                tool.observabilityScope.emit(debug: \"debug\")\n\n                tool.waitForObservabilityEvents(timeout: .now() + .seconds(1))\n\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"error: error\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"warning: warning\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"info: info\"))\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"debug: debug\"))\n            }\n\n            do {\n                let outputStream = BufferedOutputByteStream()\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString, \"--quiet\"])\n                let tool = try SwiftCommandState.makeMockState(outputStream: outputStream, options: options)\n                XCTAssertEqual(tool.logLevel, .error)\n\n                tool.observabilityScope.emit(error: \"error\")\n                tool.observabilityScope.emit(warning: \"warning\")\n                tool.observabilityScope.emit(info: \"info\")\n                tool.observabilityScope.emit(debug: \"debug\")\n\n                tool.waitForObservabilityEvents(timeout: .now() + .seconds(1))\n\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"error: error\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"warning: warning\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"info: info\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"debug: debug\"))\n            }\n\n            do {\n                let outputStream = BufferedOutputByteStream()\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString, \"-q\"])\n                let tool = try SwiftCommandState.makeMockState(outputStream: outputStream, options: options)\n                XCTAssertEqual(tool.logLevel, .error)\n\n                tool.observabilityScope.emit(error: \"error\")\n                tool.observabilityScope.emit(warning: \"warning\")\n                tool.observabilityScope.emit(info: \"info\")\n                tool.observabilityScope.emit(debug: \"debug\")\n\n                tool.waitForObservabilityEvents(timeout: .now() + .seconds(1))\n\n                XCTAssertMatch(outputStream.bytes.validDescription, .contains(\"error: error\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"warning: warning\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"info: info\"))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"debug: debug\"))\n            }\n        }\n    }\n\n    func testAuthorizationProviders() async throws {\n        try fixtureXCTest(name: \"DependencyResolution/External/XCFramework\") { fixturePath in\n            let fs = localFileSystem\n\n            // custom .netrc file\n            do {\n                let customPath = try fs.tempDirectory.appending(component: UUID().uuidString)\n                try fs.writeFileContents(\n                    customPath,\n                    string: \"machine mymachine.labkey.org login custom@labkey.org password custom\"\n                )\n\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString, \"--netrc-file\", customPath.pathString])\n                let tool = try SwiftCommandState.makeMockState(options: options)\n\n                let authorizationProvider = try tool.getAuthorizationProvider() as? CompositeAuthorizationProvider\n                let netrcProviders = authorizationProvider?.providers.compactMap { $0 as? NetrcAuthorizationProvider } ?? []\n                XCTAssertEqual(netrcProviders.count, 1)\n                XCTAssertEqual(try netrcProviders.first.map { try resolveSymlinks($0.path) }, try resolveSymlinks(customPath))\n\n                let auth = try tool.getAuthorizationProvider()?.authentication(for: \"https://mymachine.labkey.org\")\n                XCTAssertEqual(auth?.user, \"custom@labkey.org\")\n                XCTAssertEqual(auth?.password, \"custom\")\n\n                // delete it\n                try localFileSystem.removeFileTree(customPath)\n                XCTAssertThrowsError(try tool.getAuthorizationProvider(), \"error expected\") { error in\n                    XCTAssertEqual(error as? StringError, StringError(\"Did not find netrc file at \\(customPath).\"))\n                }\n            }\n\n            // Tests should not modify user's home dir .netrc so leaving that out intentionally\n        }\n    }\n\n    func testRegistryAuthorizationProviders() async throws {\n        try fixtureXCTest(name: \"DependencyResolution/External/XCFramework\") { fixturePath in\n            let fs = localFileSystem\n\n            // custom .netrc file\n            do {\n                let customPath = try fs.tempDirectory.appending(component: UUID().uuidString)\n                try fs.writeFileContents(\n                    customPath,\n                    string: \"machine mymachine.labkey.org login custom@labkey.org password custom\"\n                )\n\n                let options = try GlobalOptions.parse([\"--package-path\", fixturePath.pathString, \"--netrc-file\", customPath.pathString])\n                let tool = try SwiftCommandState.makeMockState(options: options)\n\n                // There is only one AuthorizationProvider depending on platform\n#if canImport(Security)\n                let keychainProvider = try tool.getRegistryAuthorizationProvider() as? KeychainAuthorizationProvider\n                XCTAssertNotNil(keychainProvider)\n#else\n                let netrcProvider = try tool.getRegistryAuthorizationProvider() as? NetrcAuthorizationProvider\n                XCTAssertNotNil(netrcProvider)\n                XCTAssertEqual(try netrcProvider.map { try resolveSymlinks($0.path) }, try resolveSymlinks(customPath))\n\n                let auth = try tool.getRegistryAuthorizationProvider()?.authentication(for: \"https://mymachine.labkey.org\")\n                XCTAssertEqual(auth?.user, \"custom@labkey.org\")\n                XCTAssertEqual(auth?.password, \"custom\")\n\n                // delete it\n                try localFileSystem.removeFileTree(customPath)\n                XCTAssertThrowsError(try tool.getRegistryAuthorizationProvider(), \"error expected\") { error in\n                    XCTAssertEqual(error as? StringError, StringError(\"did not find netrc file at \\(customPath)\"))\n                }\n#endif\n            }\n\n            // Tests should not modify user's home dir .netrc so leaving that out intentionally\n        }\n    }\n\n    func testDebugFormatFlags() async throws {\n        let fs = InMemoryFileSystem(emptyFiles: [\n            \"/Pkg/Sources/exe/main.swift\",\n        ])\n\n        let observer = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(fileSystem: fs, manifests: [\n            Manifest.createRootManifest(displayName: \"Pkg\",\n                                        path: \"/Pkg\",\n                                        targets: [TargetDescription(name: \"exe\")])\n        ], observabilityScope: observer.topScope)\n\n        var plan: BuildPlan\n\n        /* -debug-info-format dwarf */\n        let explicitDwarfOptions = try GlobalOptions.parse([\"--triple\", \"x86_64-unknown-windows-msvc\", \"-debug-info-format\", \"dwarf\"])\n        let explicitDwarf = try SwiftCommandState.makeMockState(options: explicitDwarfOptions)\n        plan = try await BuildPlan(\n            destinationBuildParameters: explicitDwarf.productsBuildParameters,\n            toolsBuildParameters: explicitDwarf.toolsBuildParameters,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observer.topScope\n        )\n        try XCTAssertMatch(plan.buildProducts.compactMap { $0 as? Build.ProductBuildDescription }.first?.linkArguments() ?? [],\n                           [.anySequence, \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\"])\n\n        /* -debug-info-format codeview */\n        let explicitCodeViewOptions = try GlobalOptions.parse([\"--triple\", \"x86_64-unknown-windows-msvc\", \"-debug-info-format\", \"codeview\"])\n        let explicitCodeView = try SwiftCommandState.makeMockState(options: explicitCodeViewOptions)\n\n        plan = try await BuildPlan(\n            destinationBuildParameters: explicitCodeView.productsBuildParameters,\n            toolsBuildParameters: explicitCodeView.productsBuildParameters,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observer.topScope\n        )\n        try XCTAssertMatch(plan.buildProducts.compactMap { $0 as? Build.ProductBuildDescription }.first?.linkArguments() ?? [],\n                           [.anySequence, \"-g\", \"-debug-info-format=codeview\", \"-Xlinker\", \"-debug\"])\n\n        // Explicitly pass Linux as when the `SwiftCommandState` tests are enabled on\n        // Windows, this would fail otherwise as CodeView is supported on the\n        // native host.\n        let unsupportedCodeViewOptions = try GlobalOptions.parse([\"--triple\", \"x86_64-unknown-linux-gnu\", \"-debug-info-format\", \"codeview\"])\n        let unsupportedCodeView = try SwiftCommandState.makeMockState(options: unsupportedCodeViewOptions)\n\n        XCTAssertThrowsError(try unsupportedCodeView.productsBuildParameters) {\n            XCTAssertEqual($0 as? StringError, StringError(\"CodeView debug information is currently not supported on linux\"))\n        }\n\n        /* <<null>> */\n        let implicitDwarfOptions = try GlobalOptions.parse([\"--triple\", \"x86_64-unknown-windows-msvc\"])\n        let implicitDwarf = try SwiftCommandState.makeMockState(options: implicitDwarfOptions)\n        plan = try await BuildPlan(\n            destinationBuildParameters: implicitDwarf.productsBuildParameters,\n            toolsBuildParameters: implicitDwarf.toolsBuildParameters,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observer.topScope\n        )\n        try XCTAssertMatch(plan.buildProducts.compactMap { $0 as? Build.ProductBuildDescription }.first?.linkArguments() ?? [],\n                           [.anySequence, \"-g\", \"-use-ld=lld\", \"-Xlinker\", \"-debug:dwarf\"])\n\n        /* -debug-info-format none */\n        let explicitNoDebugInfoOptions = try GlobalOptions.parse([\"--triple\", \"x86_64-unknown-windows-msvc\", \"-debug-info-format\", \"none\"])\n        let explicitNoDebugInfo = try SwiftCommandState.makeMockState(options: explicitNoDebugInfoOptions)\n        plan = try await BuildPlan(\n            destinationBuildParameters: explicitNoDebugInfo.productsBuildParameters,\n            toolsBuildParameters: explicitNoDebugInfo.toolsBuildParameters,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observer.topScope\n        )\n        try XCTAssertMatch(plan.buildProducts.compactMap { $0 as? Build.ProductBuildDescription }.first?.linkArguments() ?? [],\n                           [.anySequence, \"-gnone\", .anySequence])\n    }\n\n    func testToolchainOption() async throws {\n        try XCTSkipOnWindows(because: #\"https://github.com/swiftlang/swift-package-manager/issues/8660, threw error \\\"toolchain is invalid: could not find CLI tool `swiftc` at any of these directories: [<AbsolutePath:\\\"\\usr\\bin\\\">]\\\", needs investigation\"#)\n        let customTargetToolchain = AbsolutePath(\"/path/to/toolchain\")\n        let hostSwiftcPath = AbsolutePath(\"/usr/bin/swiftc\")\n        let hostArPath = AbsolutePath(\"/usr/bin/ar\")\n        let targetSwiftcPath = customTargetToolchain.appending(components: [\"usr\", \"bin\", \"swiftc\"])\n        let targetArPath = customTargetToolchain.appending(components: [\"usr\", \"bin\", \"llvm-ar\"])\n\n        let fs = InMemoryFileSystem(emptyFiles: [\n            \"/Pkg/Sources/exe/main.swift\",\n            hostSwiftcPath.pathString,\n            hostArPath.pathString,\n            targetSwiftcPath.pathString,\n            targetArPath.pathString\n        ])\n\n        for path in [hostSwiftcPath, hostArPath, targetSwiftcPath, targetArPath,] {\n            try fs.updatePermissions(path, isExecutable: true)\n        }\n\n        let observer = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [TargetDescription(name: \"exe\")]\n                )\n            ],\n            observabilityScope: observer.topScope\n        )\n\n        let options = try GlobalOptions.parse([\n            \"--toolchain\", customTargetToolchain.pathString,\n            \"--triple\", \"x86_64-unknown-linux-gnu\",\n        ])\n        let swiftCommandState = try SwiftCommandState.makeMockState(\n            options: options,\n            fileSystem: fs,\n            environment: [\"PATH\": \"/usr/bin\"]\n        )\n\n        XCTAssertEqual(swiftCommandState.originalWorkingDirectory, fs.currentWorkingDirectory)\n        XCTAssertEqual(\n            try swiftCommandState.getTargetToolchain().swiftCompilerPath,\n            targetSwiftcPath\n        )\n        XCTAssertEqual(\n            try swiftCommandState.getTargetToolchain().swiftSDK.toolset.knownTools[.swiftCompiler]?.path,\n            nil\n        )\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: swiftCommandState.productsBuildParameters,\n            toolsBuildParameters: swiftCommandState.toolsBuildParameters,\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observer.topScope\n        )\n\n        let arguments = try plan.buildProducts.compactMap { $0 as? Build.ProductBuildDescription }.first?.linkArguments() ?? []\n\n        XCTAssertMatch(arguments, [.contains(\"/path/to/toolchain\")])\n    }\n\n    func testToolsetOption() throws {\n        try XCTSkipOnWindows(because: #\"https://github.com/swiftlang/swift-package-manager/issues/8660. threw error \\\"toolchain is invalid: could not find CLI tool `swiftc` at any of these directories: [<AbsolutePath:\\\"\\usr\\bin\\\">]\\\", needs investigation\"#)\n        let targetToolchainPath = \"/path/to/toolchain\"\n        let customTargetToolchain = AbsolutePath(targetToolchainPath)\n        let hostSwiftcPath = AbsolutePath(\"/usr/bin/swiftc\")\n        let hostArPath = AbsolutePath(\"/usr/bin/ar\")\n        let targetSwiftcPath = customTargetToolchain.appending(components: [\"swiftc\"])\n        let targetArPath = customTargetToolchain.appending(components: [\"llvm-ar\"])\n\n        let fs = InMemoryFileSystem(emptyFiles: [\n            hostSwiftcPath.pathString,\n            hostArPath.pathString,\n            targetSwiftcPath.pathString,\n            targetArPath.pathString\n        ])\n\n        for path in [hostSwiftcPath, hostArPath, targetSwiftcPath, targetArPath,] {\n            try fs.updatePermissions(path, isExecutable: true)\n        }\n\n        try fs.writeFileContents(\"/toolset.json\", string: \"\"\"\n        {\n            \"schemaVersion\": \"1.0\",\n            \"rootPath\": \"\\(targetToolchainPath)\"\n        }\n        \"\"\")\n\n        let options = try GlobalOptions.parse([\"--toolset\", \"/toolset.json\"])\n        let swiftCommandState = try SwiftCommandState.makeMockState(\n            options: options,\n            fileSystem: fs,\n            environment: [\"PATH\": \"/usr/bin\"]\n        )\n\n        let hostToolchain = try swiftCommandState.getHostToolchain()\n        let targetToolchain = try swiftCommandState.getTargetToolchain()\n\n        XCTAssertEqual(\n            targetToolchain.swiftSDK.toolset.rootPaths,\n            [customTargetToolchain] + hostToolchain.swiftSDK.toolset.rootPaths\n        )\n        XCTAssertEqual(targetToolchain.swiftCompilerPath, targetSwiftcPath)\n        XCTAssertEqual(targetToolchain.librarianPath, targetArPath)\n    }\n\n    func testMultipleToolsets() throws {\n        try XCTSkipOnWindows(because: #\"https://github.com/swiftlang/swift-package-manager/issues/8660, threw error \\\"toolchain is invalid: could not find CLI tool `swiftc` at any of these directories: [<AbsolutePath:\\\"\\usr\\bin\\\">]\\\", needs investigation\"#)\n        let targetToolchainPath1 = \"/path/to/toolchain1\"\n        let customTargetToolchain1 = AbsolutePath(targetToolchainPath1)\n        let targetToolchainPath2 = \"/path/to/toolchain2\"\n        let customTargetToolchain2 = AbsolutePath(targetToolchainPath2)\n        let hostSwiftcPath = AbsolutePath(\"/usr/bin/swiftc\")\n        let hostArPath = AbsolutePath(\"/usr/bin/ar\")\n        let targetSwiftcPath = customTargetToolchain1.appending(components: [\"swiftc\"])\n        let targetArPath = customTargetToolchain1.appending(components: [\"llvm-ar\"])\n        let targetClangPath = customTargetToolchain2.appending(components: [\"clang\"])\n\n        let fs = InMemoryFileSystem(emptyFiles: [\n            hostSwiftcPath.pathString,\n            hostArPath.pathString,\n            targetSwiftcPath.pathString,\n            targetArPath.pathString,\n            targetClangPath.pathString\n        ])\n\n        for path in [hostSwiftcPath, hostArPath, targetSwiftcPath, targetArPath, targetClangPath,] {\n            try fs.updatePermissions(path, isExecutable: true)\n        }\n\n        try fs.writeFileContents(\"/toolset1.json\", string: \"\"\"\n        {\n            \"schemaVersion\": \"1.0\",\n            \"rootPath\": \"\\(targetToolchainPath1)\"\n        }\n        \"\"\")\n\n        try fs.writeFileContents(\"/toolset2.json\", string: \"\"\"\n        {\n            \"schemaVersion\": \"1.0\",\n            \"rootPath\": \"\\(targetToolchainPath2)\"\n        }\n        \"\"\")\n\n        let options = try GlobalOptions.parse([\n            \"--toolset\", \"/toolset1.json\", \"--toolset\", \"/toolset2.json\"\n        ])\n        let swiftCommandState = try SwiftCommandState.makeMockState(\n            options: options,\n            fileSystem: fs,\n            environment: [\"PATH\": \"/usr/bin\"]\n        )\n\n        let hostToolchain = try swiftCommandState.getHostToolchain()\n        let targetToolchain = try swiftCommandState.getTargetToolchain()\n\n        XCTAssertEqual(\n            targetToolchain.swiftSDK.toolset.rootPaths,\n            [customTargetToolchain2, customTargetToolchain1] + hostToolchain.swiftSDK.toolset.rootPaths\n        )\n        XCTAssertEqual(targetToolchain.swiftCompilerPath, targetSwiftcPath)\n        XCTAssertEqual(try targetToolchain.getClangCompiler(), targetClangPath)\n        XCTAssertEqual(targetToolchain.librarianPath, targetArPath)\n    }\n\n    func testPackagePathWithMissingFolder() async throws {\n        try withTemporaryDirectory { fixturePath in\n            let packagePath = fixturePath.appending(component: \"Foo\")\n            let options = try GlobalOptions.parse([\"--package-path\", packagePath.pathString])\n\n            do {\n                let outputStream = BufferedOutputByteStream()\n                XCTAssertThrowsError(try SwiftCommandState.makeMockState(outputStream: outputStream, options: options), \"error expected\")\n            }\n\n            do {\n                let outputStream = BufferedOutputByteStream()\n                let tool = try SwiftCommandState.makeMockState(outputStream: outputStream, options: options, createPackagePath: true)\n                tool.waitForObservabilityEvents(timeout: .now() + .seconds(1))\n                XCTAssertNoMatch(outputStream.bytes.validDescription, .contains(\"error:\"))\n            }\n        }\n    }\n}\n\nextension SwiftCommandState {\n    static func makeMockState(\n        outputStream: OutputByteStream = stderrStream,\n        options: GlobalOptions,\n        createPackagePath: Bool = false,\n        fileSystem: any FileSystem = localFileSystem,\n        environment: Environment = .current\n    ) throws -> SwiftCommandState {\n        return try SwiftCommandState(\n            outputStream: outputStream,\n            options: options,\n            toolWorkspaceConfiguration: .init(shouldInstallSignalHandlers: false),\n            workspaceDelegateProvider: {\n                CommandWorkspaceDelegate(\n                    observabilityScope: $0,\n                    outputHandler: $1,\n                    progressHandler: $2,\n                    inputHandler: $3\n                )\n            },\n            workspaceLoaderProvider: {\n                XcodeWorkspaceLoader(\n                    fileSystem: $0,\n                    observabilityScope: $1\n                )\n            },\n            createPackagePath: createPackagePath,\n            hostTriple: .arm64Linux,\n            targetInfo: UserToolchain.mockTargetInfo,\n            fileSystem: fileSystem,\n            environment: environment\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/SwiftSDKCommandTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport Commands\nimport _InternalTestSupport\nimport Testing\n\nimport class Basics.AsyncProcess\n\nprivate let sdkCommandDeprecationWarning = \"\"\"\n    warning: `swift experimental-sdk` command is deprecated and will be removed in a future version of SwiftPM. Use \\\n    `swift sdk` instead.\n\n    \"\"\"\n\n@Suite(\n    .serialized,\n    .tags(\n        .Feature.Command.Sdk,\n        .TestSize.large,\n    ),\n)\nstruct SwiftSDKCommandTests {\n    @Test(\n        arguments: [SwiftPM.sdk, SwiftPM.experimentalSDK],\n    )\n    func usage(\n        command: SwiftPM,\n    ) async throws {\n\n        let stdout = try await command.execute([\"-help\"]).stdout\n        #expect(\n            stdout.contains(\"USAGE: swift sdk <subcommand>\") || stdout.contains(\"USAGE: swift sdk [<subcommand>]\"),\n            \"got stdout:\\n\\(stdout)\",\n        )\n    }\n\n    @Test(\n        arguments: [SwiftPM.sdk, SwiftPM.experimentalSDK],\n    )\n    func commandDoesNotEmitDuplicateSymbols(\n        command: SwiftPM,\n    ) async throws {\n        let (stdout, stderr) = try await command.execute([\"--help\"])\n        let duplicateSymbolRegex = try Regex(#\"objc[83768]: (.*) is implemented in both .* \\(.*\\) and .* \\(.*\\) . One of the two will be used. Which one is undefined.\"#)\n        #expect(!stdout.contains(duplicateSymbolRegex))\n        #expect(!stderr.contains(duplicateSymbolRegex))\n\n    }\n\n    @Test(\n        arguments: [SwiftPM.sdk, SwiftPM.experimentalSDK],\n    )\n    func version(\n        command: SwiftPM,\n    ) async throws {\n        for command in [SwiftPM.sdk, SwiftPM.experimentalSDK] {\n            let stdout = try await command.execute([\"--version\"]).stdout\n            let versionRegex = try Regex(#\"Swift Package Manager -( \\w+ )?\\d+.\\d+.\\d+(-\\w+)?\"#)\n            #expect(stdout.contains(versionRegex))\n        }\n    }\n\n    @Test(\n        arguments: [SwiftPM.sdk, SwiftPM.experimentalSDK],\n        [\"test-sdk.artifactbundle.tar.gz\", \"test-sdk.artifactbundle.zip\"],\n    )\n    func installSubcommand(\n        command: SwiftPM,\n        bundle: String,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"SwiftSDKs\") { fixturePath in\n            let bundlePath = fixturePath.appending(bundle)\n            expectFileExists(at: bundlePath)\n            var (stdout, stderr) = try await command.execute(\n                [\n                    \"install\",\n                    \"--swift-sdks-path\", fixturePath.pathString,\n                    bundlePath.pathString,\n                ]\n            )\n\n            if command == .experimentalSDK {\n                #expect(stderr.contains(sdkCommandDeprecationWarning))\n                #expect(!stdout.contains(sdkCommandDeprecationWarning))\n            }\n\n            // We only expect tool's output on the stdout stream.\n            #expect(\n                (stdout + \"\\nstderr:\\n\" + stderr).contains(\"\\(bundle)` successfully installed as test-sdk.artifactbundle.\")\n            )\n\n            (stdout, stderr) = try await command.execute(\n                [\"list\", \"--swift-sdks-path\", fixturePath.pathString])\n\n            if command == .experimentalSDK {\n                #expect(stderr.contains(sdkCommandDeprecationWarning))\n                #expect(!stdout.contains(sdkCommandDeprecationWarning))\n            }\n\n            // We only expect tool's output on the stdout stream.\n            #expect(stdout.contains(\"test-artifact\"))\n\n            await expectThrowsCommandExecutionError(\n                try await command.execute(\n                    [\n                        \"install\",\n                        \"--swift-sdks-path\", fixturePath.pathString,\n                        bundlePath.pathString,\n                    ]\n                )\n            ) { error in\n                let stderr = error.stderr\n                #expect(\n                    stderr.contains(\n                        \"Error: Swift SDK bundle with name `test-sdk.artifactbundle` is already installed. Can't install a new bundle with the same name.\"\n                    ),\n                )\n            }\n\n            if command == .experimentalSDK {\n                #expect(stderr.contains(sdkCommandDeprecationWarning))\n            }\n\n            (stdout, stderr) = try await command.execute(\n                [\"remove\", \"--swift-sdks-path\", fixturePath.pathString, \"test-artifact\"])\n\n            if command == .experimentalSDK {\n                #expect(stderr.contains(sdkCommandDeprecationWarning))\n                #expect(!stdout.contains(sdkCommandDeprecationWarning))\n            }\n\n            // We only expect tool's output on the stdout stream.\n            #expect(stdout.contains(\"test-sdk.artifactbundle` was successfully removed from the file system.\"))\n\n            (stdout, stderr) = try await command.execute(\n                [\"list\", \"--swift-sdks-path\", fixturePath.pathString])\n\n            if command == .experimentalSDK {\n                #expect(stderr.contains(sdkCommandDeprecationWarning))\n                #expect(!stdout.contains(sdkCommandDeprecationWarning))\n            }\n\n            // We only expect tool's output on the stdout stream.\n            #expect(!stdout.contains(\"test-artifact\"))\n        }\n        } when: {\n            ProcessInfo.isHostAmazonLinux2()\n        }\n    }\n\n    @Test(\n        arguments: [SwiftPM.sdk, SwiftPM.experimentalSDK],\n    )\n    func configureSubcommand(\n        command: SwiftPM,\n    ) async throws {\n        let deprecationWarning = \"\"\"\n            warning: `swift sdk configuration` command is deprecated and will be removed in a future version of \\\n            SwiftPM. Use `swift sdk configure` instead.\n\n            \"\"\"\n\n        try await fixture(name: \"SwiftSDKs\") { fixturePath in\n            let bundle = \"test-sdk.artifactbundle.zip\"\n\n            var (stdout, stderr) = try await command.execute([\n                \"install\",\n                \"--swift-sdks-path\", fixturePath.pathString,\n                fixturePath.appending(bundle).pathString,\n            ])\n\n            // We only expect tool's output on the stdout stream.\n            #expect(\n                stdout.contains(\"\\(bundle)` successfully installed as test-sdk.artifactbundle.\")\n            )\n\n            let deprecatedShowSubcommand = [\"configuration\", \"show\"]\n\n            for showSubcommand in [deprecatedShowSubcommand, [\"configure\", \"--show-configuration\"]] {\n                let invocation =\n                    showSubcommand + [\n                        \"--swift-sdks-path\", fixturePath.pathString,\n                        \"test-artifact\",\n                        \"aarch64-unknown-linux-gnu\",\n                    ]\n                (stdout, stderr) = try await command.execute(invocation)\n\n                if command == .experimentalSDK {\n                    #expect(stderr.contains(sdkCommandDeprecationWarning))\n                }\n\n                if showSubcommand == deprecatedShowSubcommand {\n                    #expect(stderr.contains(deprecationWarning))\n                }\n\n                let sdkSubpath = [\"test-sdk.artifactbundle\", \"sdk\", \"sdk\"]\n\n                #expect(\n                    stdout == \"\"\"\n                        sdkRootPath: \\(fixturePath.appending(components: sdkSubpath))\n                        swiftResourcesPath: not set\n                        swiftStaticResourcesPath: not set\n                        includeSearchPaths: not set\n                        librarySearchPaths: not set\n                        toolsetPaths: not set\n\n                        \"\"\"\n                )\n\n                let deprecatedSetSubcommand = [\"configuration\", \"set\"]\n                let deprecatedResetSubcommand = [\"configuration\", \"reset\"]\n                for setSubcommand in [deprecatedSetSubcommand, [\"configure\"]] {\n                    for resetSubcommand in [deprecatedResetSubcommand, [\"configure\", \"--reset\"]] {\n                        var invocation =\n                            setSubcommand + [\n                                \"--swift-resources-path\", fixturePath.appending(\"foo\").pathString,\n                                \"--swift-sdks-path\", fixturePath.pathString,\n                                \"test-artifact\",\n                                \"aarch64-unknown-linux-gnu\",\n                            ]\n                        (stdout, stderr) = try await command.execute(invocation)\n\n                        #expect(\n                            stdout == \"\"\"\n                                info: These properties of Swift SDK `test-artifact` for target triple `aarch64-unknown-linux-gnu` \\\n                                were successfully updated: swiftResourcesPath.\n\n                                \"\"\"\n                        )\n\n                        if command == .experimentalSDK {\n                            #expect(stderr.contains(sdkCommandDeprecationWarning))\n                        }\n\n                        if setSubcommand == deprecatedSetSubcommand {\n                            #expect(stderr.contains(deprecationWarning))\n                        }\n\n                        invocation =\n                            showSubcommand + [\n                                \"--swift-sdks-path\", fixturePath.pathString,\n                                \"test-artifact\",\n                                \"aarch64-unknown-linux-gnu\",\n                            ]\n                        (stdout, stderr) = try await command.execute(invocation)\n\n                        #expect(\n                            stdout == \"\"\"\n                                sdkRootPath: \\(fixturePath.appending(components: sdkSubpath).pathString)\n                                swiftResourcesPath: \\(fixturePath.appending(\"foo\"))\n                                swiftStaticResourcesPath: not set\n                                includeSearchPaths: not set\n                                librarySearchPaths: not set\n                                toolsetPaths: not set\n\n                                \"\"\"\n                        )\n\n                        invocation =\n                            resetSubcommand + [\n                                \"--swift-sdks-path\", fixturePath.pathString,\n                                \"test-artifact\",\n                                \"aarch64-unknown-linux-gnu\",\n                            ]\n                        (stdout, stderr) = try await command.execute(invocation)\n\n                        if command == .experimentalSDK {\n                            #expect(stderr.contains(sdkCommandDeprecationWarning))\n                        }\n\n                        if resetSubcommand == deprecatedResetSubcommand {\n                            #expect(stderr.contains(deprecationWarning))\n                        }\n\n                        #expect(\n                            stdout == \"\"\"\n                                info: All configuration properties of Swift SDK `test-artifact` for target triple `aarch64-unknown-linux-gnu` were successfully reset.\n\n                                \"\"\"\n                        )\n                    }\n                }\n            }\n\n            (stdout, stderr) = try await command.execute(\n                [\"remove\", \"--swift-sdks-path\", fixturePath.pathString, \"test-artifact\"])\n\n            // We only expect tool's output on the stdout stream.\n            #expect(stdout.contains(\"test-sdk.artifactbundle` was successfully removed from the file system.\"))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/CommandsTests/TestCommandTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport Basics\nimport Commands\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum PackageModel.BuildConfiguration\nimport PackageModel\nimport _InternalTestSupport\nimport TSCTestSupport\nimport Testing\n\n@Suite(\n    .serialized,  // to limit the number of swift executable running.\n    .tags(\n        Tag.TestSize.large,\n        Tag.Feature.Command.Test,\n    )\n)\nstruct TestCommandTests {\n\n    private func execute(\n        _ args: [String],\n        packagePath: AbsolutePath? = nil,\n        configuration: BuildConfiguration = .debug,\n        buildSystem: BuildSystemProvider.Kind,\n        throwIfCommandFails: Bool = true\n    ) async throws -> (stdout: String, stderr: String) {\n        try await executeSwiftTest(\n            packagePath,\n            configuration: configuration,\n            extraArgs: args,\n            buildSystem: buildSystem,\n            throwIfCommandFails: throwIfCommandFails,\n        )\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func usage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        let stdout = try await execute(\n            [\"-help\"],\n            configuration: configuration,\n            buildSystem: buildSystem,\n        ).stdout\n        #expect(stdout.contains(\"USAGE: swift test\"), \"got stdout:\\n\\(stdout)\")\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func experimentalXunitMessageFailureArgumentIsHidden(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        let stdout = try await execute(\n            [\"--help\"],\n            configuration: configuration,\n            buildSystem: buildSystem,\n        ).stdout\n        #expect(\n            !stdout.contains(\"--experimental-xunit-message-failure\"),\n            \"got stdout:\\n\\(stdout)\",\n        )\n        #expect(\n            !stdout.contains(\"When Set, enabled an experimental message failure content (XCTest only).\"),\n            \"got stdout:\\n\\(stdout)\",\n        )\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func seeAlso(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        let stdout = try await execute(\n            [\"--help\"],\n            configuration: configuration,\n            buildSystem: buildSystem,\n        ).stdout\n        #expect(stdout.contains(\"SEE ALSO: swift build, swift run, swift package\"), \"got stdout:\\n\\(stdout)\")\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func version(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        let stdout = try await execute(\n            [\"--version\"],\n            configuration: configuration,\n            buildSystem: buildSystem,\n        ).stdout\n        let versionRegex = try Regex(#\"Swift Package Manager -( \\w+ )?\\d+.\\d+.\\d+(-\\w+)?\"#)\n        #expect(stdout.contains(versionRegex))\n    }\n\n    @Test(\n        .tags(\n            .Feature.CommandLineArguments.Toolset,\n        ),\n        .IssueWindowsPathNoEntry,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func toolsetRunner(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/EchoExecutable\") { fixturePath in\n                #if os(Windows)\n                    let win32 = \".win32\"\n                #else\n                    let win32 = \"\"\n                #endif\n                let (stdout, stderr) = try await execute(\n                    [\n                        \"--toolset\",\n                        fixturePath.appending(\"toolset\\(win32).json\").pathString,\n                    ],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // We only expect tool's output on the stdout stream.\n                #expect(stdout.contains(\"sentinel\"))\n                #expect(stdout.contains(\"\\(fixturePath)\"))\n\n                // swift-build-tool output should go to stderr.\n                switch buildSystem {\n                    case .native:\n                        #expect(stderr.contains(\"Compiling\"))\n                        #expect(stderr.contains(\"Linking\"))\n                    case .swiftbuild, .xcode:\n                        break\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func numWorkersParallelRequirement(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/EchoExecutable\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self) {\n                try await execute(\n                    [\"--num-workers\", \"1\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n            guard case let SwiftPMError.executionFailure(_, stdout, stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            #expect(\n                stderr.contains(\"error: --num-workers must be used with --parallel\"),\n                \"got stdout: \\(stdout), stderr: \\(stderr)\",\n            )\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func numWorkersValueSetToZeroRaisesAnError(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/EchoExecutable\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self) {\n                try await execute(\n                    [\"--parallel\", \"--num-workers\", \"0\"],\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true,\n                )\n            }\n            guard case let SwiftPMError.executionFailure(_, stdout, stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n            #expect(\n                stderr.contains(\"error: '--num-workers' must be greater than zero\"),\n                \"got stdout: \\(stdout), stderr: \\(stderr)\",\n            )\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func enableDisableTestabilityDefaultShouldRunWithTestability(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"fails to build the package\", isIntermittent: true) {\n            // default should run with testability\n            try await fixture(name: \"Miscellaneous/TestableExe\") { fixturePath in\n                let result = try await execute(\n                    [\"--vv\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.stderr.contains(\"-enable-testing\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && .windows == ProcessInfo.hostOperatingSystem\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .SWBINTTODO(\"Test currently fails due to 'error: build failed'\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func enableDisableTestabilityDisabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        // disabled\n        try await withKnownIssue(\"fails to build\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestableExe\") { fixturePath in\n                let error = await #expect(throws: SwiftPMError.self) {\n                    try await execute(\n                        [\"--disable-testable-imports\", \"--vv\"],\n                        packagePath: fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n                guard case let SwiftPMError.executionFailure(_, stdout, stderr) = try #require(error) else {\n                    Issue.record(\"Incorrect error was raised.\")\n                    return\n                }\n\n                #expect(\n                    stderr.contains(\"was not compiled for testing\") || stderr.contains(\"ignore swiftmodule built without '-enable-testing'\"),\n                    \"got stdout: \\(stdout), stderr: \\(stderr)\",\n                )\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func enableDisableTestabilityEnabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"failes to build the package\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestableExe\") { fixturePath in\n                let result = try await execute(\n                    [\"--enable-testable-imports\", \"--vv\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.stderr.contains(\"-enable-testing\"))\n            }\n        } when: {\n            (buildSystem == .swiftbuild && .windows == ProcessInfo.hostOperatingSystem)\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testableExecutableWithDifferentlyNamedExecutableProduct(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestableExeWithDifferentProductName\") { fixturePath in\n                let result = try await execute(\n                    [\"--vv\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n        } when: {\n            .windows == ProcessInfo.hostOperatingSystem\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8479\", relationship: .defect),\n        .SWBINTTODO(\"Result XML could not be found. The build fails because of missing test helper generation logic for non-macOS platforms\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func swiftTestParallel_SerialTesting(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/ParallelTestsPkg\") { fixturePath in\n                // First try normal serial testing.\n                let error = await #expect(throws: SwiftPMError.self) {\n                    try await executeSwiftTest(\n                        fixturePath,\n                        configuration: configuration,\n                        extraArgs: [],\n                        buildSystem: buildSystem,\n                        throwIfCommandFails: true,\n                    )\n                }\n                guard case SwiftPMError.executionFailure(_, let stdout, _) = try #require(error) else {\n                    Issue.record(\"Incorrect error was raised.\")\n                    return\n                }\n                #expect(stdout.contains(\"Executed 2 tests\"))\n                #expect(!stdout.contains(\"[3/3]\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testProductFlag(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            let configuration = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let (stdout, _) = try await executeSwiftTest(\n                    fixturePath,\n                    configuration: configuration,\n                    extraArgs: [\"--test-product\", \"SimplePackageTests\"],\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true,\n                )\n                #expect(stdout.contains(\"Executed 3 tests\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Run,\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestNoParallel,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8479\", relationship: .defect),\n        .SWBINTTODO(\"Result XML could not be found. The build fails because of missing test helper generation logic for non-macOS platforms\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func swiftTestParallel_NoParallelArgument(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/ParallelTestsPkg\") { fixturePath in\n                // Try --no-parallel.\n                let error = await #expect(throws: SwiftPMError.self) {\n                    try await execute(\n                        [\"--no-parallel\"],\n                        packagePath: fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n                guard case SwiftPMError.executionFailure(_, let stdout, _) = try #require(error) else {\n                    Issue.record(\"Incorrect error was raised.\")\n                    return\n                }\n                #expect(stdout.contains(\"Executed 2 tests\"))\n                #expect(!stdout.contains(\"[3/3]\"))\n            }\n        } when: {\n            [.windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n         .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestParallel,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8479\", relationship: .defect),\n        .SWBINTTODO(\"Result XML could not be found. The build fails because of missing test helper generation logic for non-macOS platforms\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func swiftTestParallel_ParallelArgument(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/ParallelTestsPkg\") { fixturePath in\n                // Run tests in parallel.\n                let error = await #expect(throws: SwiftPMError.self) {\n                    try await execute(\n                        [\"--parallel\"],\n                        packagePath: fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem)\n                }\n                guard case SwiftPMError.executionFailure(_, let stdout, _) = try #require(error) else {\n                    Issue.record(\"Incorrect error was raised.\")\n                    return\n                }\n                #expect(stdout.contains(\"testExample1\"))\n                #expect(stdout.contains(\"testExample2\"))\n                #expect(!stdout.contains(\"'ParallelTestsTests' passed\"))\n                #expect(stdout.contains(\"'ParallelTestsFailureTests' failed\"))\n                #expect(stdout.contains(\"[3/3]\"))\n            }\n        } when: {\n            [ .windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestParallel,\n            .Feature.CommandLineArguments.TestOutputXunit,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8479\", relationship: .defect),\n        .SWBINTTODO(\"Result XML could not be found. The build fails because of missing test helper generation logic for non-macOS platforms\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func swiftTestParallel_ParallelArgumentWithXunitOutputGeneration(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/ParallelTestsPkg\") { fixturePath in\n                let xUnitOutput = fixturePath.appending(\"result.xml\")\n                // Run tests in parallel with verbose output.\n                let error = await #expect(throws: SwiftPMError.self) {\n                    try await execute(\n                        [\n                            \"--parallel\",\n                            \"--verbose\",\n                            \"--xunit-output\",\n                            xUnitOutput.pathString,\n                        ],\n                        packagePath: fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n                guard case SwiftPMError.executionFailure(_, let stdout, _) = try #require(error) else {\n                    Issue.record(\"Incorrect error was raised.\")\n                    return\n                }\n                #expect(stdout.contains(\"testExample1\"))\n                #expect(stdout.contains(\"testExample2\"))\n                #expect(stdout.contains(\"'ParallelTestsTests' passed\"))\n                #expect(stdout.contains(\"'ParallelTestsFailureTests' failed\"))\n                #expect(stdout.contains(\"[3/3]\"))\n\n                // Check the xUnit output.\n                expectFileExists(at: xUnitOutput, \"\\(xUnitOutput) does not exist\")\n                let contents: String = try localFileSystem.readFileContents(xUnitOutput)\n                #expect(contents.contains(\"tests=\\\"3\\\" failures=\\\"1\\\"\"))\n                let timeRegex = try Regex(\"time=\\\"[0-9]+\\\\.[0-9]+\\\"\")\n                #expect(contents.contains(timeRegex))\n                #expect(!contents.contains(\"time=\\\"0.0\\\"\"))\n            }\n        } when: {\n            [.windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestParallel,\n            .Feature.CommandLineArguments.TestOutputXunit,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8479\", relationship: .defect),\n        .SWBINTTODO(\"Result XML could not be found. The build fails because of missing test helper generation logic for non-macOS platforms\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func swiftTestXMLOutputWhenEmpty(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/EmptyTestsPkg\") { fixturePath in\n                let xUnitOutput = fixturePath.appending(\"result.xml\")\n                // Run tests in parallel with verbose output.\n                _ = try await execute(\n                    [\"--parallel\", \"--verbose\", \"--xunit-output\", xUnitOutput.pathString],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                ).stdout\n\n                // Check the xUnit output.\n                expectFileExists(at: xUnitOutput)\n                let contents: String = try localFileSystem.readFileContents(xUnitOutput)\n                #expect(contents.contains(\"tests=\\\"0\\\" failures=\\\"0\\\"\"))\n            }\n        } when: {\n            [.windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n    }\n\n    enum TestRunner {\n        case XCTest\n        case SwiftTesting\n\n        var fileSuffix: String {\n            switch self {\n            case .XCTest: return \"\"\n            case .SwiftTesting: return \"-swift-testing\"\n            }\n        }\n    }\n\n    public typealias SwiftTestXMLOutputData = (\n        fixtureName: String,\n        testRunner: TestRunner,\n        enableExperimentalFlag: Bool,\n        matchesPattern: [String],\n        configuration: BuildConfiguration,\n        id: String\n    )\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestParallel,\n            .Feature.CommandLineArguments.TestOutputXunit,\n            .Feature.CommandLineArguments.TestEnableXCTest,\n            .Feature.CommandLineArguments.TestEnableSwiftTesting,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8479\", relationship: .defect),\n        .SWBINTTODO(\"Result XML could not be found. The build fails because of missing test helper generation logic for non-macOS platforms\"),\n        arguments: SupportedBuildSystemOnAllPlatforms.filter { $0 != .xcode }, [\n            (\n                fixtureName: \"Miscellaneous/TestSingleFailureXCTest\",\n                testRunner: TestRunner.XCTest,\n                enableExperimentalFlag: true,\n                matchesPattern: [\"Purposely failing &amp; validating XML espace &quot;'&lt;&gt;\"],\n                configuration: BuildConfiguration.debug,\n                id: \"Single XCTest Test Failure Message With Flag Enabled\",\n            ),\n            (\n                fixtureName: \"Miscellaneous/TestSingleFailureSwiftTesting\",\n                testRunner: TestRunner.SwiftTesting,\n                enableExperimentalFlag: true,\n                matchesPattern: [\"Purposely failing &amp; validating XML espace &quot;'&lt;&gt;\"],\n                configuration: BuildConfiguration.debug,\n                id: \"Single Swift Testing Test Failure Message With Flag Enabled\",\n            ),\n            (\n                fixtureName: \"Miscellaneous/TestSingleFailureXCTest\",\n                testRunner: TestRunner.XCTest,\n                enableExperimentalFlag: false,\n                matchesPattern: [\"failure\"],\n                configuration: BuildConfiguration.debug,\n                id: \"Single XCTest Test Failure Message With Flag Disabled\",\n            ),\n            (\n                fixtureName: \"Miscellaneous/TestSingleFailureSwiftTesting\",\n                testRunner: TestRunner.SwiftTesting,\n                enableExperimentalFlag: false,\n                matchesPattern: [\"Purposely failing &amp; validating XML espace &quot;'&lt;&gt;\"],\n                configuration: BuildConfiguration.debug,\n                id: \"Single Swift Testing Test Failure Message With Flag Disabled\",\n            ),\n            (\n                fixtureName: \"Miscellaneous/TestMultipleFailureXCTest\",\n                testRunner: TestRunner.XCTest,\n                enableExperimentalFlag: true,\n                matchesPattern: [\n                    \"Test failure 1\",\n                    \"Test failure 2\",\n                    \"Test failure 3\",\n                    \"Test failure 4\",\n                    \"Test failure 5\",\n                    \"Test failure 6\",\n                    \"Test failure 7\",\n                    \"Test failure 8\",\n                    \"Test failure 9\",\n                    \"Test failure 10\",\n                ],\n                configuration: BuildConfiguration.debug,\n                id: \"Single Multiple Test Failure Message With Flag Enabled\",\n            ),\n            (\n                fixtureName: \"Miscellaneous/TestMultipleFailureSwiftTesting\",\n                testRunner: TestRunner.SwiftTesting,\n                enableExperimentalFlag: true,\n                matchesPattern: [\n                    \"ST Test failure 1\",\n                    \"ST Test failure 2\",\n                    \"ST Test failure 3\",\n                    \"ST Test failure 4\",\n                    \"ST Test failure 5\",\n                    \"ST Test failure 6\",\n                    \"ST Test failure 7\",\n                    \"ST Test failure 8\",\n                    \"ST Test failure 9\",\n                    \"ST Test failure 10\",\n                ],\n                configuration: BuildConfiguration.debug,\n                id: \"Multiple Swift Testing Test Failure Message With Flag Enabled\",\n            ),\n            (\n                fixtureName: \"Miscellaneous/TestMultipleFailureXCTest\",\n                testRunner: TestRunner.XCTest,\n                enableExperimentalFlag: false,\n                matchesPattern: [\n                    \"failure\",\n                    \"failure\",\n                    \"failure\",\n                    \"failure\",\n                    \"failure\",\n                    \"failure\",\n                    \"failure\",\n                    \"failure\",\n                    \"failure\",\n                    \"failure\",\n                ],\n                configuration: BuildConfiguration.debug,\n                id: \"Multiple XCTest Tests Failure Message With Flag Disabled\",\n            ),\n            (\n                fixtureName: \"Miscellaneous/TestMultipleFailureSwiftTesting\",\n                testRunner: TestRunner.SwiftTesting,\n                enableExperimentalFlag: false,\n                matchesPattern: [\n                    \"ST Test failure 1\",\n                    \"ST Test failure 2\",\n                    \"ST Test failure 3\",\n                    \"ST Test failure 4\",\n                    \"ST Test failure 5\",\n                    \"ST Test failure 6\",\n                    \"ST Test failure 7\",\n                    \"ST Test failure 8\",\n                    \"ST Test failure 9\",\n                    \"ST Test failure 10\",\n                ],\n                configuration: BuildConfiguration.debug,\n                id: \"Multiple Swift Testing Tests Failure Message With Flag Disabled\",\n            )\n        ]\n    )\n    func swiftTestXMLOutputFailureMessage(\n        buildSystem: BuildSystemProvider.Kind,\n        tcdata: SwiftTestXMLOutputData,\n    ) async throws {\n        // windows issue not recorded for:\n        //   - native, single, XCTest, experimental true\n        //   - native, single, XCTest, experimental false\n        try await withKnownIssue( isIntermittent: true) {\n            try await fixture(name: tcdata.fixtureName) { fixturePath in\n                // GIVEN we have a Package with a failing \\(testRunner) test cases\n                let xUnitOutput = fixturePath.appending(\"result.xml\")\n                let xUnitUnderTest = fixturePath.appending(\"result\\(tcdata.testRunner.fileSuffix).xml\")\n\n                // WHEN we execute swift-test in parallel while specifying xUnit generation\n                let extraCommandArgs = tcdata.enableExperimentalFlag ? [\"--experimental-xunit-message-failure\"] : []\n                let (stdout, stderr) = try await execute(\n                    [\n                        \"--parallel\",\n                        \"--verbose\",\n                        \"--enable-swift-testing\",\n                        \"--enable-xctest\",\n                        \"--xunit-output\",\n                        xUnitOutput.pathString,\n                    ] + extraCommandArgs,\n                    packagePath: fixturePath,\n                    configuration: tcdata.configuration,\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: false,\n                )\n\n                if !FileManager.default.fileExists(atPath: xUnitUnderTest.pathString) {\n                    // If the build failed then produce an output dump of what happened during the execution\n                    print(\"\\(stdout)\")\n                    print(\"\\(stderr)\")\n                }\n\n                // THEN we expect \\(xUnitUnderTest) to exists\n                expectFileExists(at: xUnitUnderTest)\n                let contents: String = try localFileSystem.readFileContents(xUnitUnderTest)\n                // AND that the xUnit file has the expected contents\n                for match in tcdata.matchesPattern {\n                    #expect(contents.contains(match))\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    /// An argument to the test function `noteXCTestFailures()`.\n    struct XCTestFailureNoteTestArgument: CustomStringConvertible {\n        /// The relative path to a test fixture in this project.\n        var fixturePath: String\n\n        /// The setting representing whether XCTest should be enabled or disabled\n        /// for the test command, if any. When the value of this property is `nil`,\n        /// no flag will be passed. If non-`nil`, either `--enable-xctest` or\n        /// `--disable-xctest` will be passed representing the value. The default\n        /// value is `nil`, meaning no flag will be passed but the command defaults\n        /// to having XCTest enabled.\n        var isXCTestEnabled: Bool? = nil\n\n        /// The setting representing whether Swift Testing should be enabled or disabled\n        /// for the test command, if any. When the value of this property is `nil`,\n        /// no flag will be passed. If non-`nil`, either `--enable-swift-testing` or\n        /// `--disable-swift-testing` will be passed representing the value. The default\n        /// value is `nil`, meaning no flag will be passed but the command defaults\n        /// to having Swift Testing enabled.\n        var isSwiftTestingEnabled: Bool? = nil\n\n        /// Whether the test command output is expected to include the note.\n        var expectNote: Bool\n\n        var description: String {\n            var description = \"fixture: '\\((fixturePath as NSString).lastPathComponent)'\"\n            if let isXCTestEnabled {\n                description.append(\", XCTest enabled: \\(isXCTestEnabled)\")\n            }\n            if let isSwiftTestingEnabled {\n                description.append(\", Swift Testing enabled: \\(isSwiftTestingEnabled)\")\n            }\n            description.append(\", expectNote: \\(expectNote)\")\n            return description\n        }\n    }\n\n    /// Test whether a note is emitted to stdout indicating that XCTests failed\n    /// after Swift Testing tests finish running.\n    @Test(\n        .tags(\n            .Feature.TargetType.Test,\n            .Feature.CommandLineArguments.TestEnableXCTest,\n            .Feature.CommandLineArguments.TestDisableXCTest,\n            .Feature.CommandLineArguments.TestEnableSwiftTesting,\n            .Feature.CommandLineArguments.TestDisableSwiftTesting,\n        ),\n        arguments: [\n            .init(\n                fixturePath: \"Miscellaneous/TestDiscovery/Simple\",\n                expectNote: false,\n            ),\n            .init(\n                fixturePath: \"Miscellaneous/TestSingleFailureXCTest\",\n                expectNote: true,\n            ),\n            .init(\n                fixturePath: \"Miscellaneous/TestSingleFailureSwiftTesting\",\n                expectNote: false,\n            ),\n            .init(\n                fixturePath: \"Miscellaneous/TestSingleFailureXCTest\",\n                isXCTestEnabled: false,\n                expectNote: false,\n            ),\n            .init(\n                fixturePath: \"Miscellaneous/TestSingleFailureXCTest\",\n                isSwiftTestingEnabled: false,\n                expectNote: false,\n            ),\n            .init(\n                fixturePath: \"Miscellaneous/TestSingleFailureXCTest\",\n                isXCTestEnabled: false,\n                isSwiftTestingEnabled: false,\n                expectNote: false,\n            ),\n        ] as [XCTestFailureNoteTestArgument]\n    )\n    func noteXCTestFailures(noteArgument arg: XCTestFailureNoteTestArgument) async throws {\n        try await fixture(name: arg.fixturePath) { fixturePath in\n            var args: [String] = []\n\n            switch arg.isXCTestEnabled {\n            case .none: break\n            case .some(true): args.append(\"--enable-xctest\")\n            case .some(false): args.append(\"--disable-xctest\")\n            }\n\n            switch arg.isSwiftTestingEnabled {\n            case .none: break\n            case .some(true): args.append(\"--enable-swift-testing\")\n            case .some(false): args.append(\"--disable-swift-testing\")\n            }\n\n            let (stdout, stderr) = try await execute(\n                args,\n                packagePath: fixturePath,\n                buildSystem: .native,\n                throwIfCommandFails: false,\n            )\n            #expect(stdout.contains(SwiftTestCommand.xctestFailedNote) == arg.expectNote, \"stdout: \\(stdout), stderr: \\(stderr)\")\n        }\n    }\n\n    @Test(\n         .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestFilter,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8479\", relationship: .defect),\n        .SWBINTTODO(\"Result XML could not be found. The build fails because of missing test helper generation logic for non-macOS platforms\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func swiftTestFilter(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/SkipTests\") { fixturePath in\n                let (stdout, _) = try await execute(\n                    [\"--filter\", \".*1\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // in \"swift test\" test output goes to stdout\n                #expect(stdout.contains(\"testExample1\"))\n                #expect(!stdout.contains(\"testExample2\"))\n                #expect(!stdout.contains(\"testExample3\"))\n                #expect(!stdout.contains(\"testExample4\"))\n            }\n\n            try await fixture(name: \"Miscellaneous/SkipTests\") { fixturePath in\n                let (stdout, _) = try await execute(\n                    [\"--filter\", \"SomeTests\", \"--skip\", \".*1\", \"--filter\", \"testExample3\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // in \"swift test\" test output goes to stdout\n                #expect(!stdout.contains(\"testExample1\"))\n                #expect(stdout.contains(\"testExample2\"))\n                #expect(stdout.contains(\"testExample3\"))\n                #expect(!stdout.contains(\"testExample4\"))\n            }\n        } when: {\n            [.windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestSkip,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8479\", relationship: .defect),\n        .SWBINTTODO(\"Result XML could not be found. The build fails because of missing test helper generation logic for non-macOS platforms\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func swiftTestSkip(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/SkipTests\") { fixturePath in\n                let (stdout, _) = try await execute(\n                    [\"--skip\", \"SomeTests\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // in \"swift test\" test output goes to stdout\n                #expect(!stdout.contains(\"testExample1\"))\n                #expect(!stdout.contains(\"testExample2\"))\n                #expect(stdout.contains(\"testExample3\"))\n                #expect(stdout.contains(\"testExample4\"))\n            }\n        } when: {\n            [.windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/SkipTests\") { fixturePath in\n                let (stdout, _) = try await execute(\n                    [\n                        \"--filter\",\n                        \"ExampleTests\",\n                        \"--skip\",\n                        \".*2\",\n                        \"--filter\",\n                        \"MoreTests\",\n                        \"--skip\", \"testExample3\",\n                    ],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // in \"swift test\" test output goes to stdout\n                #expect(stdout.contains(\"testExample1\"))\n                #expect(!stdout.contains(\"testExample2\"))\n                #expect(!stdout.contains(\"testExample3\"))\n                #expect(stdout.contains(\"testExample4\"))\n            }\n        } when: {\n            [.windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/SkipTests\") { fixturePath in\n                let (stdout, _) = try await execute(\n                    [\"--skip\", \"Tests\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // in \"swift test\" test output goes to stdout\n                #expect(!stdout.contains(\"testExample1\"))\n                #expect(!stdout.contains(\"testExample2\"))\n                #expect(!stdout.contains(\"testExample3\"))\n                #expect(!stdout.contains(\"testExample4\"))\n            }\n        } when: {\n            [.windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/8722\", relationship: .fixedBy),\n        .IssueWindowsPathNoEntry,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func enableTestDiscoveryDeprecation(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue {\n            let compilerDiagnosticFlags = [\"-Xswiftc\", \"-Xfrontend\", \"-Xswiftc\", \"-Rmodule-interface-rebuild\"]\n            // should emit when LinuxMain is present\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let (_, stderr) = try await execute(\n                    [\"--enable-test-discovery\"] + compilerDiagnosticFlags,\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(stderr.contains(\"warning: '--enable-test-discovery' option is deprecated\"))\n            }\n\n            #if canImport(Darwin)\n                // should emit when LinuxMain is not present\n                let expected = true\n            #else\n                // should not emit when LinuxMain is present\n                let expected = false\n            #endif\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                try localFileSystem.writeFileContents(fixturePath.appending(components: \"Tests\", SwiftModule.defaultTestEntryPointName), bytes: \"fatalError(\\\"boom\\\")\")\n                let (_, stderr) = try await execute(\n                    [\"--enable-test-discovery\"] + compilerDiagnosticFlags,\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(stderr.contains(\"warning: '--enable-test-discovery' option is deprecated\") == expected)\n            }\n        } when: {\n            buildSystem == .swiftbuild && [.linux, .windows].contains(ProcessInfo.hostOperatingSystem)\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .SWBINTTODO(\"Fails to find test executable\"),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/8722\", relationship: .fixedBy),\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func listWithoutBuildingFirst(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"Fails to find test executable\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let (stdout, stderr) = try await execute(\n                    [\"list\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // build was run\n                #expect(stderr.contains(\"Build complete!\"))\n\n                // getting the lists\n                #expect(stdout.contains(\"SimpleTests.SimpleTests/testExample1\"))\n                #expect(stdout.contains(\"SimpleTests.SimpleTests/test_Example2\"))\n                #expect(stdout.contains(\"SimpleTests.SimpleTests/testThrowing\"))\n            }\n        } when: {\n            (buildSystem == .swiftbuild && .windows == ProcessInfo.hostOperatingSystem)\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.BuildTests,\n        ),\n        .SWBINTTODO(\"Fails to find test executable when run in self-hosted pipeline\"),\n        .SWBINTTODO(\"Linux: fails to build with --build-test in Smoke Tests\"),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/8722\", relationship: .fixedBy),\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func listBuildFirstThenList(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n            // build first\n            try await withKnownIssue(\"Fails to save attachment\", isIntermittent: true) {\n                // This might be intermittently failing on windows\n                let (buildStdout, _) = try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    extraArgs: [\"--build-tests\"],\n                    buildSystem: buildSystem,\n                )\n                #expect(buildStdout.contains(\"Build complete!\"))\n            } when: {\n                (buildSystem == .native && configuration == .release) // error: module 'Simple' was not compiled for testing\n                || (configuration == .release && buildSystem != .native && ProcessInfo.hostOperatingSystem != .windows) // (configuration == .release)\n                || (buildSystem != .native && ProcessInfo.hostOperatingSystem == .windows) // || (ProcessInfo.hostOperatingSystem == .windows)\n            }\n\n            // list\n            try await withKnownIssue(\"Fails to find test executable\", isIntermittent: true) { // windows; issue not recorded\n                let (listStdout, listStderr) = try await execute(\n                    [\"list\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // build was run\n                #expect(listStderr.contains(\"Build complete!\"))\n                // getting the lists\n                #expect(listStdout.contains(\"SimpleTests.SimpleTests/testExample1\"))\n                #expect(listStdout.contains(\"SimpleTests.SimpleTests/test_Example2\"))\n                #expect(listStdout.contains(\"SimpleTests.SimpleTests/testThrowing\"))\n            } when: {\n                (configuration == .release && ProcessInfo.hostOperatingSystem != .macOS)\n                || (buildSystem == .swiftbuild && [.windows].contains(ProcessInfo.hostOperatingSystem)) && configuration == .debug\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.BuildTests,\n        ),\n        .SWBINTTODO(\"Fails to find test executable\"),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/8722\", relationship: .fixedBy),\n        .IssueWindowsPathNoEntry,\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func listBuildFirstThenListWhileSkippingBuild(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                // build first\n                    // This might be intermittently failing on windows\n                    let (buildStdout, _) = try await executeSwiftBuild(\n                        fixturePath,\n                        configuration: configuration,\n                        extraArgs: [\"--build-tests\"],\n                        buildSystem: buildSystem,\n                    )\n                    #expect(buildStdout.contains(\"Build complete!\"))\n\n                // list while skipping build\n                let (listStdout, listStderr) = try await execute([\"list\", \"--skip-build\"], packagePath: fixturePath, buildSystem: buildSystem)\n                // build was not run\n                #expect(!listStderr.contains(\"Build complete!\"))\n                // getting the lists\n                #expect(listStdout.contains(\"SimpleTests.SimpleTests/testExample1\"))\n                #expect(listStdout.contains(\"SimpleTests.SimpleTests/test_Example2\"))\n                #expect(listStdout.contains(\"SimpleTests.SimpleTests/testThrowing\"))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func listWithSkipBuildAndNoBuildArtifacts(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self) {\n                try await execute(\n                    [\"list\", \"--skip-build\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true,\n                )\n            }\n            guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n            #expect(\n                stderr.contains(\"Test build artifacts were not found in the build folder\"),\n                \"got stdout: \\(stdout), stderr: \\(stderr)\",\n            )\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestEnableSwiftTesting,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func basicSwiftTestingIntegration(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"Fails to find the test executable\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/SwiftTesting\") { fixturePath in\n                let (stdout, stderr) = try await execute(\n                    [\"--enable-swift-testing\", \"--disable-xctest\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(\n                    stdout.contains(#\"Test \"SOME TEST FUNCTION\" started\"#),\n                    \"Expectation not met.  got '\\(stdout)'\\nstderr: '\\(stderr)'\"\n                )\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testingWithLocalRpathsDisabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"Fails to find the test executable\") {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/SwiftTesting\") { fixturePath in\n                let (stdout, stderr) = try await execute(\n                    [\"--disable-local-rpath\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(\n                    stdout.contains(#\"Test \"SOME TEST FUNCTION\" started\"#),\n                    \"Expectation not met.  got '\\(stdout)'\\nstderr: '\\(stderr)'\"\n                )\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .skipHostOS(.macOS),  // because this was guarded with `#if !canImport(Darwin)`\n        .SWBINTTODO(\"This is a PIF builder missing GUID problem. Further investigation is needed.\"),\n        .IssueWindowsPathNoEntry,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func generatedMainIsConcurrencySafe_XCTest(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            let strictConcurrencyFlags = [\"-Xswiftc\", \"-strict-concurrency=complete\"]\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let (_, stderr) = try await execute(\n                    strictConcurrencyFlags,\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(!stderr.contains(\"is not concurrency-safe\"))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n         .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .skipHostOS(.macOS),  // because this was guarded with `#if !canImport(Darwin)`\n        .SWBINTTODO(\"This is a PIF builder missing GUID problem. Further investigation is needed.\"),\n        .IssueWindowsPathNoEntry,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func generatedMainIsExistentialAnyClean(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            let existentialAnyFlags = [\"-Xswiftc\", \"-enable-upcoming-feature\", \"-Xswiftc\", \"ExistentialAny\"]\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let (_, stderr) = try await execute(\n                    existentialAnyFlags,\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(!stderr.contains(\"error: use of protocol\"))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n         .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .IssueWindowsPathTestsFailures,\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8602\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func libraryEnvironmentVariable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"produces a filepath that is too long, needs investigation\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/CheckTestLibraryEnvironmentVariable\") { fixturePath in\n                var extraEnv = Environment()\n                if try UserToolchain.default.swiftTestingPath != nil {\n                    extraEnv[\"CONTAINS_SWIFT_TESTING\"] = \"1\"\n                }\n                await #expect(throws: Never.self) {\n                    try await executeSwiftTest(\n                        fixturePath,\n                        configuration: configuration,\n                        env: extraEnv,\n                        buildSystem: buildSystem,\n                    )\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n            .Feature.CommandLineArguments.TestDisableSwiftTesting,\n        ),\n        .SWBINTTODO(\"Fails to find test executable\"),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/8722\", relationship: .fixedBy),\n        .IssueWindowsPathNoEntry,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func XCTestOnlyDoesNotLogAboutNoMatchingTests(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let (_, stderr) = try await execute(\n                    [\"--disable-swift-testing\"],\n                    packagePath: fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(!stderr.contains(\"No matching test cases were run\"))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.TargetType.Executable,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/6605\", relationship: .verifies),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8602\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func fatalErrorDisplayedCorrectNumberOfTimesWhenSingleXCTestHasFatalErrorInBuildCompilation(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"Windows path issue\", isIntermittent: true) {\n            // GIVEN we have a Swift Package that has a fatalError building the tests\n            let expected = 1\n            try await fixture(name: \"Miscellaneous/Errors/FatalErrorInSingleXCTest/TypeLibrary\") { fixturePath in\n                // WHEN swift-test is executed\n                let error = await #expect(throws: SwiftPMError.self) {\n                    try await self.execute(\n                        [],\n                        packagePath: fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n\n                // THEN I expect a failure\n                guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = try #require(error) else {\n                    Issue.record(\"Building the package was expected to fail, but it was successful.\")\n                    return\n                }\n\n                let matchString = \"error: fatalError\"\n                let stdoutMatches = getNumberOfMatches(of: matchString, in: stdout)\n                let stderrMatches = getNumberOfMatches(of: matchString, in: stderr)\n                let actualNumMatches = stdoutMatches + stderrMatches\n\n                // AND a fatal error message is printed \\(expected) times\n                let expectationMessage = [\n                    \"Actual (\\(actualNumMatches)) is not as expected (\\(expected))\",\n                    \"stdout: \\(stdout.debugDescription)\",\n                    \"stderr: \\(stderr.debugDescription)\",\n                ].joined(separator: \"\\n\")\n                #expect(\n                    actualNumMatches == expected,\n                    \"\\(expectationMessage)\",\n                )\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n            .IssueWindowsLongPath,\n            .tags(\n                .Feature.TargetType.Executable,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func testableExecutableWithEmbeddedResources(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let configuration = BuildConfiguration.debug\n            try await withKnownIssue(isIntermittent: true) {\n                try await fixture(name: \"Miscellaneous/TestableExeWithResources\") { fixturePath in\n                    let result = try await execute(\n                        [\"--vv\"],\n                        packagePath: fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n            } when: {\n                .windows == ProcessInfo.hostOperatingSystem\n                || ProcessInfo.processInfo.environment[\"SWIFTCI_EXHIBITS_GH_9524\"] != nil\n            }\n         }\n\n}\n"
  },
  {
    "path": "Tests/ExtraTests/.gitignore",
    "content": ".DS_Store\n/.build\n/Packages\n/*.xcodeproj\n"
  },
  {
    "path": "Tests/ExtraTests/Package.swift",
    "content": "// swift-tools-version:4.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"ExtraTests\",\n    dependencies: [\n        .package(path: \"../../\"),\n    ],\n    targets: [\n        .testTarget(\n            name: \"ExtraTests\",\n            dependencies: [\"SPMUtility\"]),\n    ]\n)\n"
  },
  {
    "path": "Tests/ExtraTests/README.md",
    "content": "# ExtraTests\n\nThis contains some extra tests that are not suitable for running on the official\nCI but can be run elsewhere.\n"
  },
  {
    "path": "Tests/ExtraTests/Tests/ExtraTests/FSWatchTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport XCTest\n\nimport Basic\nimport SPMUtility\n\nclass FSWatchTests: XCTestCase {\n\n    func testBasics() throws {\n        try withTemporaryDirectory(removeTreeOnDeinit: true) { path in\n            // Construct the paths that we need to watch.\n            let pathsToWatch = [\n                path.appending(component: \"foo\"),\n                path.appending(component: \"bar\"),\n            ]\n\n            // Create the paths.\n            for path in pathsToWatch {\n                try localFileSystem.createDirectory(path)\n            }\n\n            let condition = Condition()\n            let delegate = Delegate(condition)\n\n            let watcher = FSWatch(paths: pathsToWatch, delegate: delegate)\n            try watcher.start()\n\n            for file in [\"a\", \"b\", \"c\"] {\n                let filePath = path.appending(components: \"foo\", file)\n                try localFileSystem.writeFileContents(filePath, bytes: \"\")\n            }\n\n            condition.whileLocked {\n                condition.wait()\n            }\n\n            XCTAssertFalse(delegate.receivedEvents.isEmpty)\n        }\n    }\n}\n\nclass Delegate: FSWatchDelegate {\n    var receivedEvents: [AbsolutePath] = []\n\n    let condition: Condition\n\n    init(_ condition: Condition) {\n        self.condition = condition\n    }\n\n    func pathsDidReceiveEvent(_ paths: [AbsolutePath]) {\n        receivedEvents += paths\n\n        print(paths)\n\n        condition.whileLocked {\n            condition.signal()\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/ExtraTests/Tests/LinuxMain.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport XCTest\n\nimport ExtraTests\n\nvar tests = [XCTestCaseEntry]()\ntests += ExtraTests.__allTests()\n\nXCTMain(tests)\n"
  },
  {
    "path": "Tests/FunctionalPerformanceTests/BuildPerfTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// FIXME: re-enable when `measure` supports `async` or replace with lower level benchmarks\n//import Basics\n//import Commands\n//import PackageModel\n//import InternalTestSupport\n//import Workspace\n//import XCTest\n//\n//import class TSCTestSupport.XCTestCasePerf\n//\n//final class BuildPerfTests: XCTestCasePerf {\n//    @discardableResult\n//    func execute(args: [String] = [], packagePath: AbsolutePath) async throws -> (stdout: String, stderr: String) {\n//        // FIXME: We should pass the SWIFT_EXEC at lower level.\n//        try await executeSwiftBuild(packagePath, extraArgs: args + [], env: [\"SWIFT_EXEC\": UserToolchain.default.swiftCompilerPath.pathString], buildSystem: .native)\n//    }\n//\n//    func clean(packagePath: AbsolutePath) async throws {\n//        _ = try await executeSwiftPackage(packagePath, extraArgs: [\"clean\"], buildSystem: .native)\n//    }\n//\n//    func testTrivialPackageFullBuild() throws {\n//        #if !os(macOS)\n//        try XCTSkipIf(true, \"test is only supported on macOS\")\n//        #endif\n//        try runFullBuildTest(for: \"DependencyResolution/Internal/Simple\", product: \"foo\")\n//    }\n//\n//    func testTrivialPackageNullBuild() throws {\n//        #if !os(macOS)\n//        try XCTSkipIf(true, \"test is only supported on macOS\")\n//        #endif\n//        try runNullBuildTest(for: \"DependencyResolution/Internal/Simple\", product: \"foo\")\n//    }\n//\n//    func testComplexPackageFullBuild() throws {\n//        #if !os(macOS)\n//        try XCTSkipIf(true, \"test is only supported on macOS\")\n//        #endif\n//        try runFullBuildTest(for: \"DependencyResolution/External/Complex\", app: \"app\", product: \"Dealer\")\n//    }\n//\n//    func testComplexPackageNullBuild() throws {\n//        #if !os(macOS)\n//        try XCTSkipIf(true, \"test is only supported on macOS\")\n//        #endif\n//        try runNullBuildTest(for: \"DependencyResolution/External/Complex\", app: \"app\", product: \"Dealer\")\n//    }\n//\n//    func runFullBuildTest(for name: String, app appString: String? = nil, product productString: String) throws {\n//        try fixtureXCTest(name: name) { fixturePath in\n//            let app = fixturePath.appending(components: (appString ?? \"\"))\n//            let triple = try UserToolchain.default.targetTriple\n//            let product = app.appending(components: \".build\", triple.platformBuildPathComponent, \"debug\", productString)\n//            try await self.execute(packagePath: app)\n//            measure {\n//                try! await self.clean(packagePath: app)\n//                try! await self.execute(packagePath: app)\n//                XCTAssertFileExists(product)\n//            }\n//        }\n//    }\n//\n//    func runNullBuildTest(for name: String, app appString: String? = nil, product productString: String) throws {\n//        try fixtureXCTest(name: name) { fixturePath in\n//            let app = fixturePath.appending(components: (appString ?? \"\"))\n//            let triple = try UserToolchain.default.targetTriple\n//            let product = app.appending(components: \".build\", triple.platformBuildPathComponent, \"debug\", productString)\n//            try self.execute(packagePath: app)\n//            measure {\n//                try! self.execute(packagePath: app)\n//                XCTAssertFileExists(product)\n//            }\n//        }\n//    }\n//}\n"
  },
  {
    "path": "Tests/FunctionalTests/CFamilyTargetTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport Commands\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\nimport Workspace\nimport Testing\n\nimport class Basics.AsyncProcess\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .TestSize.large,\n        .Feature.CTargets,\n    ),\n)\nstruct CFamilyTargetTestCase {\n    @Test(\n        .serialized,  // running tests in parallel causes a stack dump to occur. Needs investigation.\n        .tags(\n            .Feature.Command.Build,\n            .Feature.SpecialCharacters,\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n    )\n    func cLibraryWithSpaces(\n        data: BuildData,\n    ) async throws {\n            try await fixture(name: \"CFamilyTargets/CLibraryWithSpaces\") { fixturePath in\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: data.config,\n                    buildSystem: data.buildSystem,\n                )\n                switch data.buildSystem {\n                case .native:\n                    let binPath = try fixturePath.appending(components: data.buildSystem.binPath(for: data.config))\n                    expectDirectoryContainsFile(dir: binPath, filename: \"Bar.c.o\")\n                    expectDirectoryContainsFile(dir: binPath, filename: \"Foo.c.o\")\n                case .swiftbuild:\n                    break\n                case .xcode:\n                    Issue.record(\"Test expectations have not been implemented.\")\n                }\n            }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n    )\n    func cUsingCAndSwiftDep(\n        data: BuildData,\n    ) async throws {\n            try await fixture(name: \"DependencyResolution/External/CUsingCDep\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"Bar\")\n                try await executeSwiftBuild(\n                    packageRoot,\n                    configuration: data.config,\n                    buildSystem: data.buildSystem,\n                )\n                switch data.buildSystem {\n                case .native:\n                    let binPath = try packageRoot.appending(components: data.buildSystem.binPath(for: data.config))\n                    expectDirectoryContainsFile(dir: binPath, filename: \"Sea.c.o\")\n                    expectDirectoryContainsFile(dir: binPath, filename: \"Foo.c.o\")\n                case .swiftbuild:\n                    break\n                case .xcode:\n                    Issue.record(\"Test expectation have not been implemented.\")\n                }\n                let path = try SwiftPM.packagePath(for: \"Foo\", packageRoot: packageRoot)\n                let actualTags = try GitRepository(path: path).getTags()\n                #expect(actualTags == [\"1.2.3\"])\n            }\n    }\n\n    @Test(\n        .IssueWindowsPathNoEntry,\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n    )\n    func moduleMapGenerationCases(\n        data: BuildData,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"CFamilyTargets/ModuleMapGenerationCases\") { fixturePath in\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: data.config,\n                    buildSystem: data.buildSystem,\n                )\n                switch data.buildSystem {\n                case .native:\n                    let binPath = try fixturePath.appending(components: data.buildSystem.binPath(for: data.config))\n                    expectDirectoryContainsFile(dir: binPath, filename: \"Jaz.c.o\")\n                    expectDirectoryContainsFile(dir: binPath, filename: \"main.swift.o\")\n                    expectDirectoryContainsFile(dir: binPath, filename: \"FlatInclude.c.o\")\n                    expectDirectoryContainsFile(dir: binPath, filename: \"UmbrellaHeader.c.o\")\n                case .swiftbuild:\n                    break\n                case .xcode:\n                    Issue.record(\"Test expectation have not been implemented.\")\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && data.buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n    )\n    func noIncludeDirCheck(\n        data: BuildData,\n    ) async throws {\n        try await fixture(name: \"CFamilyTargets/CLibraryNoIncludeDir\") { fixturePath in\n            let error = try await #require(throws: (any Error).self) {\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: data.config,\n                    buildSystem: data.buildSystem,\n                )\n            }\n\n            let errString = \"\\(error)\"\n            let missingIncludeDirStr = \"\\(ModuleError.invalidPublicHeadersDirectory(\"Cfactorial\"))\"\n            #expect(errString.contains(missingIncludeDirStr))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n            .Feature.CommandLineArguments.Xld,\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n    )\n    func canForwardExtraFlagsToClang(\n        data: BuildData,\n    ) async throws {\n            try await fixture(name: \"CFamilyTargets/CDynamicLookup\") { fixturePath in\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: data.config,\n                    Xld: [\"-undefined\", \"dynamic_lookup\"],\n                    buildSystem: data.buildSystem,\n                )\n                switch data.buildSystem {\n                case .native:\n                    let binPath = try fixturePath.appending(components: data.buildSystem.binPath(for: data.config))\n                    expectDirectoryContainsFile(dir: binPath, filename: \"Foo.c.o\")\n                case .swiftbuild:\n                    break\n                case .xcode:\n                    Issue.record(\"Test expectation ahve not been implemented.\")\n                }\n            }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .tags(\n            .Feature.Command.Build,\n            .Feature.Command.Test,\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n    )\n    func objectiveCPackageWithTestTarget(\n        data: BuildData,\n    ) async throws {\n        try await fixture(name: \"CFamilyTargets/ObjCmacOSPackage\") { fixturePath in\n            // Build the package.\n            try await executeSwiftBuild(\n                fixturePath,\n                configuration: data.config,\n                buildSystem: data.buildSystem,\n            )\n            switch data.buildSystem {\n            case .native:\n                let binPath = try fixturePath.appending(components: data.buildSystem.binPath(for: data.config))\n                expectDirectoryContainsFile(dir: binPath, filename: \"HelloWorldExample.m.o\")\n                expectDirectoryContainsFile(dir: binPath, filename: \"HelloWorldExample.m.o\")\n            case .swiftbuild, .xcode:\n                // there aren't any specific expectations to look for\n                break\n            }\n            // Run swift-test on package.\n            try await executeSwiftTest(\n                fixturePath,\n                configuration: data.config,\n                buildSystem: data.buildSystem,\n            )\n\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: getBuildData(for: SupportedBuildSystemOnAllPlatforms),\n    )\n    func canBuildRelativeHeaderSearchPaths(\n        data: BuildData,\n\n    ) async throws {\n            try await fixture(name: \"CFamilyTargets/CLibraryParentSearchPath\") { fixturePath in\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: data.config,\n                    buildSystem: data.buildSystem,\n                )\n                switch data.buildSystem {\n                case .native:\n                    let binPath = try fixturePath.appending(components: data.buildSystem.binPath(for: data.config))\n                    expectDirectoryContainsFile(dir: binPath, filename: \"HeaderInclude.swiftmodule\")\n                case .swiftbuild, .xcode:\n                    // there aren't any specific expectations to look for\n                    break\n                }\n            }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/DependencyResolutionTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Commands\nimport Foundation\nimport PackageModel\nimport SourceControl\nimport Testing\nimport Workspace\nimport _InternalTestSupport\n\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum TSCUtility.Git\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .TestSize.large,\n        .Feature.DependencyResolution,\n    ),\n)\nstruct DependencyResolutionTests {\n    @Test(\n        .IssueWindowsLongPath,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func internalSimple(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"DependencyResolution/Internal/Simple\") { fixturePath in\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n\n                let binPath = try fixturePath.appending(components: buildSystem.binPath(for: configuration))\n                let executablePath = binPath.appending(components: \"Foo\")\n                let output = try await AsyncProcess.checkNonZeroExit(args: executablePath.pathString).withSwiftLineEnding\n                #expect(output == \"Foo\\nBar\\n\")\n            }\n        } when: {\n            (ProcessInfo.hostOperatingSystem  == .windows && buildSystem == .swiftbuild)\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8984\", relationship: .defect),\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func internalExecAsDep(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/Internal/InternalExecutableAsDependency\") { fixturePath in\n            await withKnownIssue(isIntermittent: true) {\n                await #expect(throws: (any Error).self) {\n                    try await executeSwiftBuild(\n                        fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n            } when: {\n                configuration == .release && buildSystem == .swiftbuild // an error is not raised.\n            }\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func internalComplex(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"DependencyResolution/Internal/Complex\") { fixturePath in\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n\n                let binPath = try fixturePath.appending(components: buildSystem.binPath(for: configuration))\n                let executablePath = binPath.appending(components: \"Foo\")\n                let output = try await AsyncProcess.checkNonZeroExit(args: executablePath.pathString)\n                    .withSwiftLineEnding\n                #expect(output == \"meiow Baz\\n\")\n            }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild)\n        }\n    }\n\n    /// Check resolution of a trivial package with one dependency.\n    @Test(\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func externalSimple(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n                // Add several other tags to check version selection.\n                let repo = GitRepository(path: fixturePath.appending(components: \"Foo\"))\n                for tag in [\"1.1.0\", \"1.2.0\"] {\n                    try repo.tag(name: tag)\n                }\n\n                let packageRoot: AbsolutePath = fixturePath.appending(\"Bar\")\n                try await executeSwiftBuild(\n                    packageRoot,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let binPath = try packageRoot.appending(components: buildSystem.binPath(for: configuration))\n                let executablePath = binPath.appending(components: executableName(\"Bar\"))\n                #expect(\n                    localFileSystem.exists(executablePath),\n                    \"Path \\(executablePath) does not exist\",\n                )\n                let path = try SwiftPM.packagePath(for: \"Foo\", packageRoot: packageRoot)\n                #expect(try GitRepository(path: path).getTags().contains(\"1.2.3\"))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        .IssueLdFailsUnexpectedly,\n        .issue(\"rdar://162339964\", relationship: .defect),\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func externalComplex(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\n            isIntermittent: ProcessInfo.hostOperatingSystem == .windows\n            // rdar://162339964\n            || (ProcessInfo.isHostAmazonLinux2() && buildSystem == .swiftbuild)\n        ) {\n            try await fixture(name: \"DependencyResolution/External/Complex\", createGitRepo: true) { fixturePath in\n                let packageRoot = fixturePath.appending(\"app\")\n                try await executeSwiftBuild(\n                    packageRoot,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let binPath = try packageRoot.appending(components: buildSystem.binPath(for: configuration))\n                let executablePath = binPath.appending(components: \"Dealer\")\n                expectFileExists(at: executablePath)\n                let output = try await AsyncProcess.checkNonZeroExit(args: executablePath.pathString)\n                    .withSwiftLineEnding\n                #expect(output == \"♣︎K\\n♣︎Q\\n♣︎J\\n♣︎10\\n♣︎9\\n♣︎8\\n♣︎7\\n♣︎6\\n♣︎5\\n♣︎4\\n\")\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows // due to long path issues\n            || (ProcessInfo.isHostAmazonLinux2() && buildSystem == .swiftbuild) // Linker ld throws an unexpected error.\n        }\n    }\n\n    @Test(\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func convenienceBranchInit(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"DependencyResolution/External/Branch\", createGitRepo: true) { fixturePath in\n                // Tests the convenience init .package(url: , branch: )\n                let app = fixturePath.appending(\"Bar\")\n                try await executeSwiftBuild(\n                    app,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Mirror,\n            Tag.Feature.Command.Package.ShowDependencies,\n            Tag.Feature.Command.Package.Config,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func mirrors(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"https://github.com/swiftlang/swift-build/issues/609\", isIntermittent: true) {\n            try await fixture(name: \"DependencyResolution/External/Mirror\", createGitRepo: true) { fixturePath in\n                let prefix = try resolveSymlinks(fixturePath)\n                let appPath = prefix.appending(\"App\")\n                let packageResolvedPath = appPath.appending(\"Package.resolved\")\n\n                // prepare the dependencies as git repos\n                for directory in [\"Foo\", \"Bar\", \"BarMirror\"] {\n                    let path = prefix.appending(component: directory)\n                    _ = try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", path.pathString, \"init\")\n                    _ = try await AsyncProcess.checkNonZeroExit(\n                        args: Git.tool,\n                        \"-C\",\n                        path.pathString,\n                        \"checkout\",\n                        \"-b\",\n                        \"newMain\"\n                    )\n                }\n\n                // run with no mirror\n                do {\n                    let output = try await executeSwiftPackage(\n                        appPath,\n                        configuration: configuration,\n                        extraArgs: [\"show-dependencies\", \"-v\"],\n                        buildSystem: buildSystem,\n                    )\n                    // logs are in stderr\n                    #expect(output.stderr.contains(\"Fetching \\(prefix.appending(\"Foo\").pathString)\\n\"))\n                    #expect(output.stderr.contains(\"Fetching \\(prefix.appending(\"Bar\").pathString)\\n\"))\n                    // results are in stdout\n                    #expect(output.stdout.contains(\"foo<\\(prefix.appending(\"Foo\").pathString)@unspecified\"))\n                    #expect(output.stdout.contains(\"bar<\\(prefix.appending(\"Bar\").pathString)@unspecified\"))\n\n                    let resolvedPackages: String = try localFileSystem.readFileContents(packageResolvedPath)\n                    #expect(resolvedPackages.contains(prefix.appending(\"Foo\").escapedPathString))\n                    #expect(resolvedPackages.contains(prefix.appending(\"Bar\").escapedPathString))\n\n                    try await executeSwiftBuild(\n                        appPath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n\n                // clean\n                try localFileSystem.removeFileTree(appPath.appending(\".build\"))\n                try localFileSystem.removeFileTree(packageResolvedPath)\n\n                // set mirror\n                _ = try await executeSwiftPackage(\n                    appPath,\n                    configuration: configuration,\n                    extraArgs: [\n                        \"config\",\n                        \"set-mirror\",\n                        \"--original-url\",\n                        prefix.appending(\"Bar\").pathString,\n                        \"--mirror-url\",\n                        prefix.appending(\"BarMirror\").pathString,\n                    ],\n                    buildSystem: buildSystem,\n                )\n\n                // run with mirror\n                do {\n                    let output = try await executeSwiftPackage(\n                        appPath,\n                        configuration: configuration,\n                        extraArgs: [\"show-dependencies\", \"-v\"],\n                        buildSystem: buildSystem,\n                    )\n                    // logs are in stderr\n                    #expect(output.stderr.contains(\"Fetching \\(prefix.appending(\"Foo\").pathString)\\n\"))\n                    #expect(output.stderr.contains(\"Fetching \\(prefix.appending(\"BarMirror\").pathString)\\n\"))\n                    #expect(!output.stderr.contains(\"Fetching \\(prefix.appending(\"Bar\").pathString)\\n\"))\n                    // result are in stdout\n                    #expect(output.stdout.contains(\"foo<\\(prefix.appending(\"Foo\").pathString)@unspecified\"))\n                    #expect(\n                        output.stdout.contains(\n                            \"barmirror<\\(prefix.appending(\"BarMirror\").pathString)@unspecified\"\n                        )\n                    )\n                    #expect(!output.stdout.contains(\"bar<\\(prefix.appending(\"Bar\").pathString)@unspecified\"))\n\n                    // rdar://52529014 mirrors should not be reflected in `Package.resolved` file\n                    let resolvedPackages: String = try localFileSystem.readFileContents(packageResolvedPath)\n                    #expect(resolvedPackages.contains(prefix.appending(\"Foo\").escapedPathString))\n                    #expect(resolvedPackages.contains(prefix.appending(\"Bar\").escapedPathString))\n                    #expect(!resolvedPackages.contains(prefix.appending(\"BarMirror\").escapedPathString))\n\n                    try await executeSwiftBuild(\n                        appPath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.Update,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageLookupCaseInsensitive(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/PackageLookupCaseInsensitive\") {\n            fixturePath in\n            try await executeSwiftPackage(\n                fixturePath.appending(\"pkg\"),\n                configuration: configuration,\n                extraArgs: [\"update\"],\n                buildSystem: buildSystem,\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/LibraryEvolutionXCFLinuxTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Testing\n\nprivate struct SwiftPMTests {\n    @Test(\n        .requireSwift6_2,\n        .requireHostOS(.linux)\n    )\n    func libraryEvolutionLinuxXCFramework() async throws {\n        try await fixture(name: \"Miscellaneous/LibraryEvolutionLinuxXCF\") { fixturePath in\n            let swiftFramework = \"SwiftFramework\"\n            try await withTemporaryDirectory(removeTreeOnDeinit: false) { tmpDir in\n                let scratchPath = tmpDir.appending(component: \".build\")\n                try await executeSwiftBuild(\n                    fixturePath.appending(component: swiftFramework),\n                    configuration: .debug,\n                    extraArgs: [\"--scratch-path\", scratchPath.pathString],\n                    buildSystem: .native\n                )\n\n                #if arch(arm64)\n                let arch = \"aarch64\"\n                #elseif arch(x86_64)\n                let arch = \"x86_64\"\n                #endif\n\n                let platform = \"linux\"\n                let libraryExtension = \"so\"\n\n                let xcframeworkPath = fixturePath.appending(\n                    components: \"TestBinary\",\n                    \"\\(swiftFramework).xcframework\"\n                )\n                let libraryName = \"lib\\(swiftFramework).\\(libraryExtension)\"\n                let artifactsPath = xcframeworkPath.appending(component: \"\\(platform)-\\(arch)\")\n\n                try localFileSystem.createDirectory(artifactsPath, recursive: true)\n\n                try localFileSystem.copy(\n                    from: scratchPath.appending(components: \"debug\", libraryName),\n                    to: artifactsPath.appending(component: libraryName)\n                )\n\n                try localFileSystem.copy(\n                    from: scratchPath.appending(components: \"debug\", \"Modules\", \"\\(swiftFramework).swiftinterface\"),\n                    to: artifactsPath.appending(component: \"\\(swiftFramework).swiftinterface\")\n                )\n\n                try localFileSystem.writeFileContents(\n                    xcframeworkPath.appending(component: \"Info.plist\"),\n                    string: \"\"\"\n                    <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n                    <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n                    <plist version=\"1.0\">\n                    <dict>\n                        <key>AvailableLibraries</key>\n                        <array>\n                            <dict>\n                                <key>BinaryPath</key>\n                                <string>\\(libraryName)</string>\n                                <key>LibraryIdentifier</key>\n                                <string>\\(platform)-\\(arch)</string>\n                                <key>LibraryPath</key>\n                                <string>\\(libraryName)</string>\n                                <key>SupportedArchitectures</key>\n                                <array>\n                                    <string>\\(arch)</string>\n                                </array>\n                                <key>SupportedPlatform</key>\n                                <string>\\(platform)</string>\n                            </dict>\n                        </array>\n                        <key>CFBundlePackageType</key>\n                        <string>XFWK</string>\n                        <key>XCFrameworkFormatVersion</key>\n                        <string>1.0</string>\n                    </dict>\n                    </plist>\n                    \"\"\"\n                )\n            }\n\n            let packagePath = fixturePath.appending(component: \"TestBinary\")\n            let scratchPath = packagePath.appending(component: \".build-test\")\n            let runOutput = try await executeSwiftRun(\n                packagePath, \"TestBinary\",\n                extraArgs: [\n                    \"--scratch-path\", scratchPath.pathString, \"--experimental-xcframeworks-on-linux\",\n                ],\n                buildSystem: .native\n            )\n            #expect(!runOutput.stderr.contains(\"error:\"))\n            #expect(runOutput.stdout.contains(\"Latest Framework with LibraryEvolution version: v2\"))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/MacroTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport struct SPMBuildCore.BuildSystemProvider\n\nimport DriverSupport\nimport _InternalTestSupport\nimport PackageModel\nimport Testing\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        Tag.TestSize.large\n    ),\n)\nstruct MacroTests {\n    @Test(\n        .requiresBuildingMacrosAsDylibs,\n        .requiresFrontEndFlags(flags: [\"load-plugin-library\"]),\n        .requiresSwiftTestingMacros,\n        .tags(\n            Tag.Feature.Command.Build\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func macrosBasic(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Macros\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath.appending(\"MacroPackage\"),\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"@__swiftmacro_11MacroClient11fontLiteralfMf_.swift as Font\"), \"stdout:\\n\\(stdout)\")\n            #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Build\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func minimalExecutableMacro(\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        try await fixture(name: \"Macros/MinimalMacroPackage\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/MiscellaneousTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport PackageModel\nimport SourceControl\nimport SPMBuildCore\nimport _InternalTestSupport\nimport Workspace\nimport Testing\nimport Testing\n\nimport class Basics.AsyncProcess\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum TSCUtility.Git\n\ntypealias ProcessID = AsyncProcess.ProcessID\n\n@Suite(\n    .tags(\n        .TestSize.large,\n    )\n)\nstruct MiscellaneousTestCase {\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func printsSelectedDependencyVersion(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath.appending(\"Bar\"),\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            // package resolution output goes to stderr\n            let packageRegex = try Regex(\"Computed .* at 1\\\\.2\\\\.3\")\n            #expect(stderr.contains(packageRegex))\n            // in \"swift build\" build output goes to stdout\n            if buildSystem == .native {\n                #expect(stdout.contains(\"Compiling Foo Foo.swift\"))\n                #expect(stdout.contains(\"Compiling Bar main.swift\"))\n                if (config == .debug) {\n                    #expect(stdout.contains(\"Merging module Foo\") || stdout.contains(\"Emitting module Foo\"))\n                    #expect(stdout.contains(\"Merging module Bar\") || stdout.contains(\"Emitting module Bar\"))\n                }\n                #expect(stdout.contains(\"Linking Bar\"))\n            }\n            #expect(stdout.contains(\"Build complete!\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func passExactDependenciesToBuildCommand(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/ExactDependencies\", createGitRepo: true) { fixturePath in\n            let packagePath = fixturePath.appending(\"app\")\n            try await executeSwiftBuild(\n                packagePath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            let buildDir = try packagePath.appending(components: buildSystem.binPath(for: config))\n            expectFileExists(at: buildDir.appending(executableName(\"FooExec\")))\n            if buildSystem == .native {\n                expectFileExists(at: buildDir.appending(components: \"Modules\", \"FooLib1.swiftmodule\"))\n                expectFileExists(at: buildDir.appending(components: \"Modules\", \"FooLib2.swiftmodule\"))\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func canBuildMoreThanTwiceWithExternalDependencies(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"DependencyResolution/External/Complex\", createGitRepo: true) { fixturePath in\n            try await executeSwiftBuild(\n                fixturePath.appending(\"app\"),\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            try await executeSwiftBuild(\n                fixturePath.appending(\"app\"),\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n            try await executeSwiftBuild(\n                fixturePath.appending(\"app\"),\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func noArgumentsExitsWithOne(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        await expectThrowsCommandExecutionError(\n            try await executeSwiftBuild(\n                \"/\",\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n        ) { error in\n            // if our code crashes we'll get an exit code of 256\n            guard error.result.exitStatus == .terminated(code: 1) else {\n                Issue.record(\"failed in an unexpected manner: \\(error)\")\n                return\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func compileFailureExitsGracefully(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/CompileFails\") { fixturePath in\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                // if our code crashes we'll get an exit code of 256\n                guard error.result.exitStatus == .terminated(code: 1) else {\n                    Issue.record(\"failed in an unexpected manner: \\(error)\")\n                    return\n                }\n                if buildSystem == .native {\n                    #expect((error.stdout + error.stderr).contains(\"Compiling CompileFails Foo.swift\"))\n                    #expect((error.stdout + error.stderr).contains(\"compile_failure\"))\n                }\n                #expect((error.stdout + error.stderr).contains(\"error:\"))\n            }\n        }\n    }\n\n    @Test(\n        // TODO: raise a GitHub issue on\n        //  swift run swift-build --package-path Fixtures/Miscellaneous/-DSWIFT_PACKAGE --configuration release -Xcc -DEXTRA_C_DEFINE=2 -Xswiftc -DEXTRA_SWIFTC_DEFINE --build-system swiftbuild\n        //  swift run swift-build --package-path Fixtures/Miscellaneous/-DSWIFT_PACKAGE --configuration debug -Xcc -DEXTRA_C_DEFINE=2 -Xswiftc -DEXTRA_SWIFTC_DEFINE --build-system swiftbuild\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageManagerDefineAndXArgs(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/-DSWIFT_PACKAGE\") { fixturePath in\n            await #expect(throws: SwiftPMError.self) {\n                try await executeSwiftBuild(\n                    fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                )\n            }\n            try await withKnownIssue(isIntermittent: true) {\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    Xcc: [\"-DEXTRA_C_DEFINE=2\"],\n                    Xswiftc: [\"-DEXTRA_SWIFTC_DEFINE\"],\n                    buildSystem: buildSystem,\n                )\n            } when: {\n                buildSystem == .swiftbuild\n            }\n        }\n    }\n\n    /**\n     Tests that modules that are rebuilt causes\n     any executables that link to that module to be relinked.\n     */\n    @Test(\n        .IssueWindowsFolderCreationFailure,\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func internalDependencyEdges(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"Miscellaneous/DependencyEdges/Internal\") { fixturePath in\n            let binPath = try fixturePath.appending(components: buildSystem.binPath(for: configuration))\n            let executable = binPath.appending(components: \"Foo\")\n            let execPath = executable.pathString\n\n            try await executeSwiftBuild(\n                fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            try requireFileExists(at: executable)\n            let output = try await AsyncProcess.checkNonZeroExit(args: execPath)\n            #expect(output == \"Hello\\(ProcessInfo.EOL)\")\n\n            // we need to sleep at least one second otherwise\n            // llbuild does not realize the file has changed\n            try await Task.sleep(for: .seconds(1))\n\n            try localFileSystem.writeFileContents(fixturePath.appending(components: \"Bar\", \"Bar.swift\"), bytes: \"public let bar = \\\"Goodbye\\\"\\n\")\n\n            try await executeSwiftBuild(\n                fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            try requireFileExists(at: executable)\n            let output2 = try await AsyncProcess.checkNonZeroExit(args: execPath)\n            #expect(output2 == \"Goodbye\\(ProcessInfo.EOL)\")\n        }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    /**\n     Tests that modules from other packages that are rebuilt causes\n     any executables that link to that module in the root package.\n     */\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func externalDependencyEdges1(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue {\n        try await fixture(name: \"DependencyResolution/External/Complex\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(component: \"app\")\n            let binPath = try packageRoot.appending(components: buildSystem.binPath(for: configuration))\n            let executable = binPath.appending(component: \"Dealer\")\n            let execPath = executable.pathString\n\n            try await executeSwiftBuild(\n                packageRoot,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            try requireFileExists(at: executable)\n            let output = try await AsyncProcess.checkNonZeroExit(args: execPath).withSwiftLineEnding\n            #expect(output == \"♣︎K\\n♣︎Q\\n♣︎J\\n♣︎10\\n♣︎9\\n♣︎8\\n♣︎7\\n♣︎6\\n♣︎5\\n♣︎4\\n\")\n\n            // we need to sleep at least one second otherwise\n            // llbuild does not realize the file has changed\n            try await Task.sleep(for: .seconds(1))\n\n            let path = try SwiftPM.packagePath(for: \"FisherYates\", packageRoot: packageRoot)\n            try localFileSystem.chmod(.userWritable, path: path, options: [.recursive])\n            try localFileSystem.writeFileContents(path.appending(components: \"src\", \"Fisher-Yates_Shuffle.swift\"), bytes: \"public extension Collection{ func shuffle() -> [Iterator.Element] {return []} }\\n\\npublic extension MutableCollection where Index == Int { mutating func shuffleInPlace() { for (i, _) in enumerated() { self[i] = self[0] } }}\\n\\npublic let shuffle = true\")\n\n            try await executeSwiftBuild(\n                packageRoot,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            try requireFileExists(at: executable)\n            let output2 = try await AsyncProcess.checkNonZeroExit(args: execPath).withSwiftLineEnding\n            #expect(output2 == \"♠︎A\\n♠︎A\\n♠︎A\\n♠︎A\\n♠︎A\\n♠︎A\\n♠︎A\\n♠︎A\\n♠︎A\\n♠︎A\\n\")\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && buildSystem == .native && configuration == .debug)\n            || (ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild)\n        }\n    }\n\n    /**\n     Tests that modules from other packages that are rebuilt causes\n     any executables for another external package to be rebuilt.\n     */\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        // TODO: raise GitHub issue\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func externalDependencyEdges2(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/DependencyEdges/External\", createGitRepo: true) { fixturePath in\n            let packageRoot = fixturePath.appending(\"root\")\n            let binPath = try packageRoot.appending(components: buildSystem.binPath(for: configuration))\n            let executable = binPath.appending(component: \"dep2\")\n            let execpath = [executable.pathString]\n\n            try await executeSwiftBuild(\n                packageRoot,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            try await withKnownIssue {\n                try requireFileExists(at: executable)\n                let output = try await AsyncProcess.checkNonZeroExit(arguments: execpath)\n                #expect(output == \"Hello\\(ProcessInfo.EOL)\")\n\n                // we need to sleep at least one second otherwise\n                // llbuild does not realize the file has changed\n                try await Task.sleep(for: .seconds(1))\n\n                let path = try SwiftPM.packagePath(for: \"dep1\", packageRoot: packageRoot)\n                try localFileSystem.chmod(.userWritable, path: path, options: [.recursive])\n                try localFileSystem.writeFileContents(path.appending(components: \"Foo.swift\"), bytes: \"public let foo = \\\"Goodbye\\\"\")\n\n                try await executeSwiftBuild(\n                    packageRoot,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                try requireFileExists(at: executable)\n                let output2 = try await AsyncProcess.checkNonZeroExit(arguments: execpath)\n                #expect(output2 == \"Goodbye\\(ProcessInfo.EOL)\")\n            } when: {\n                (ProcessInfo.hostOperatingSystem == .windows)\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packagePathContainsSpaces(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) { // might no longer be withKnownIssue, but leaving for now.\n            try await fixture(name: \"Miscellaneous/Spaces Fixture\") { fixturePath in\n                await #expect(throws: Never.self) {\n                    try await executeSwiftBuild(\n                        fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                }\n                let binPath = try fixturePath.appending(components: buildSystem.binPath(for: configuration))\n                switch buildSystem {\n                    case .native:\n                        expectFileExists(at: binPath.appending(components: \"Module_Name_1.build\", \"Foo.swift.o\"))\n                    case .xcode, .swiftbuild:\n                        break\n                }\n            }\n        } when: {\n            buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .disabled(\"XCTest was disabled\"),\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func secondBuildIsNullInModulemapGen(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        // Make sure that swiftpm doesn't rebuild second time if the modulemap is being generated.\n        try await fixture(name: \"CFamilyTargets/SwiftCMixed\") { fixturePath in\n            let output = try await executeSwiftBuild(\n                fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            ).stdout\n            #expect(!output.isEmpty)\n            let secondOutput = try await executeSwiftBuild(\n                fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            ).stdout\n            #expect(secondOutput.isEmpty)\n        }\n    }\n\n    @Test(\n        // TODO: Raise a GitHub issue as Swift Build fails\n        //.   swift run swift-build --package-path Fixtures/Miscellaneous/DistantFutureDeploymentTarget --configuration release -Xswiftc -target -Xswiftc arm64-apple-macosx41.0 --build-system swiftbuild\n        //.   swift run swift-build --package-path Fixtures/Miscellaneous/DistantFutureDeploymentTarget --configuration debug -Xswiftc -target -Xswiftc arm64-apple-macosx41.0 --build-system swiftbuild\n        .requireHostOS(.macOS),\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func overridingDeploymentTargetUsingSwiftCompilerArgument(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/DistantFutureDeploymentTarget\") { fixturePath in\n                let hostTriple = try UserToolchain.default.targetTriple\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    Xswiftc: [\"-target\", \"\\(hostTriple.archName)-apple-macosx41.0\"],\n                    buildSystem: buildSystem,\n                )\n            }\n        } when: {\n            buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .serialized, // Because the tests set the environment variable\n        // TODO: raise a GitHub issue .  the second `swift-build` command fails.\n        .tags(\n            .Feature.Command.Build,\n        ),\n        .requires(executable: executableName(\"clang\")),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func pkgConfigCFamilyTargets(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue {\n        try await fixture(name: \"Miscellaneous/PkgConfig\", createGitRepo: true) { fixturePath in\n            let systemModule = fixturePath.appending(\"SystemModule\")\n            // Create a shared library.\n            let input = systemModule.appending(components: \"Sources\", \"SystemModule.c\")\n            let triple = try UserToolchain.default.targetTriple\n            let output = systemModule.appending(\"libSystemModule\\(triple.dynamicLibraryExtension)\")\n            try await AsyncProcess.checkNonZeroExit(args: executableName(\"clang\"), \"-shared\", input.pathString, \"-o\", output.pathString)\n\n            let pcFile = fixturePath.appending(\"libSystemModule.pc\")\n\n            try localFileSystem.writeFileContents(pcFile, string: \"\"\"\n                prefix=\\(systemModule.pathString)\n                exec_prefix=${prefix}\n                libdir=${exec_prefix}\n                includedir=${prefix}/Sources/include\n                Name: SystemModule\n                URL: http://127.0.0.1/\n                Description: The one and only SystemModule\n                Version: 1.10.0\n                Cflags: -I${includedir}\n                Libs: -L${libdir} -lSystemModule\n\n                \"\"\"\n            )\n\n            let moduleUser = fixturePath.appending(\"SystemModuleUserClang\")\n            let env: Environment = [\"PKG_CONFIG_PATH\": fixturePath.pathString]\n            let binPath = try moduleUser.appending(components: buildSystem.binPath(for: configuration))\n            await withKnownIssue(isIntermittent: true) {\n                await #expect(throws: Never.self) {\n                    _ = try await executeSwiftBuild(\n                        moduleUser,\n                        configuration: configuration,\n                        env: env,\n                        buildSystem: buildSystem,\n                    )\n                }\n                expectFileExists(at: binPath.appending(component: \"SystemModuleUserClang\"))\n            } when:{\n                buildSystem == .swiftbuild && configuration == .release && ProcessInfo.hostOperatingSystem != .linux\n            }\n\n            // Clean up the build directory before re-running the build with\n            // different arguments.\n            _ = try await executeSwiftPackage(\n                moduleUser,\n                configuration: configuration,\n                extraArgs: [\"clean\"],\n                buildSystem: buildSystem,\n            )\n\n            await withKnownIssue(isIntermittent: true) {\n                await #expect(throws: Never.self) {\n                    _ = try await executeSwiftBuild(\n                        moduleUser,\n                        configuration: configuration,\n                        extraArgs: [\"--pkg-config-path\", fixturePath.pathString],\n                        buildSystem: buildSystem,\n                    )\n                }\n\n                expectFileExists(at: binPath.appending(component: \"SystemModuleUserClang\"))\n            } when: {\n                buildSystem == .swiftbuild\n            }\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && buildSystem == .native)\n            || (ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild && configuration == .debug)\n        }\n    }\n\n    @Test(\n        .disabled(\"XCTest was disabled\"),\n        .tags(\n            .Feature.Command.Build,\n        ),\n    )\n    func canKillSubprocessOnSigInt() throws {\n#if false\n        try fixture(name: \"DependencyResolution/External/Simple\") { fixturePath in\n\n            let fakeGit = fixturePath.appending(components: \"bin\", \"git\")\n            let waitFile = fixturePath.appending(components: \"waitfile\")\n\n            try localFileSystem.createDirectory(fakeGit.parentDirectory)\n\n            // Write out fake git.\n            try localFileSystem.writeFileContents(fakeGit, string:\n                \"\"\"\n                    #!/bin/sh\n                    set -e\n                    printf \"$$\" >> \\(waitFile)\n                    while true; do sleep 1; done\n                \"\"\"\n            )\n\n            // Make it executable.\n            _ = try AsyncProcess.popen(args: \"chmod\", \"+x\", fakeGit.description)\n\n            // Put fake git in PATH.\n            var env = ProcessInfo.processInfo.environment\n            let oldPath = env[\"PATH\"]\n            env[\"PATH\"] = fakeGit.parentDirectory.description\n            if let oldPath {\n                env[\"PATH\"] = env[\"PATH\"]! + \":\" + oldPath\n            }\n\n            // Launch swift-build.\n            let app = fixturePath.appending(\"Bar\")\n            let process = AsyncProcess(args: SwiftPM.Build.path.pathString, \"--package-path\", app.pathString, environment: env)\n            try process.launch()\n\n            guard waitForFile(waitFile) else {\n                Issue.record(\"Couldn't launch the process\")\n                return\n            }\n            // Interrupt the process.\n            process.signal(SIGINT)\n            let result = try process.waitUntilExit()\n\n            // We should not have exited with zero.\n            #expect(result.exitStatus != .terminated(code: 0))\n\n            // Process and subprocesses should be dead.\n            let contents: String = try localFileSystem.readFileContents(waitFile)\n            try #expect(!AsyncProcess.running(process.processID))\n            try #expect(!AsyncProcess.running(ProcessID(contents)!))\n        }\n#endif\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func reportingErrorFromGitCommand(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/MissingDependency\") { fixturePath in\n            // This fixture has a setup that is intentionally missing a local\n            // dependency to induce a failure.\n\n            // Launch swift-build.\n            let app = fixturePath.appending(\"Bar\")\n\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    app,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                // We should exited with a failure from the attempt to \"git clone\"\n                // something that doesn't exist.\n                let stderr = error.stderr\n                #expect(\n                    stderr.contains(\"error: Failed to clone repository\"),\n                    \"Error from git was not propagated to process output: \\(stderr)\",\n                )\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func localPackageUsedAsURLValidation(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/LocalPackageAsURL\", createGitRepo: false) { fixturePath in\n            // This fixture has a setup that is trying to use a local package\n            // as a url that hasn't been initialized as a repo\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    fixturePath.appending(\"Bar\"),\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                let stderr = error.stderr\n                #expect(\n                    stderr.contains(\"cannot clone from local directory\"),\n                    \"Didn't find expected output: \\(stderr)\",\n                )\n            }\n        }\n    }\n\n    @Test(\n        .disabled(\"No longer works with newer toolchains\"),\n    )\n    func lTO() async throws {\n#if os(macOS)\n        // FIXME: this test requires swift-driver to be installed\n        // Currently swift-ci does not build/install swift-driver before running\n        // swift-package-manager tests which results in this test failing.\n        // See the following additional discussion:\n        // - https://github.com/swiftlang/swift/pull/69696\n        // - https://github.com/swiftlang/swift/pull/61766\n        // - https://github.com/swiftlang/swift-package-manager/pull/5842#issuecomment-1301632685\n        try await fixture(name: \"Miscellaneous/LTO/SwiftAndCTargets\") { fixturePath in\n            /*let output =*/\n            try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--experimental-lto-mode=full\", \"--verbose\"],\n                buildSystem: .native,\n\n            )\n            // FIXME: On macOS dsymutil cannot find temporary .o files? (#6890)\n            // Ensure warnings like the following are not present in build output\n            // warning: (arm64) /var/folders/ym/6l_0x8vj0b70sz_4h9d70p440000gn/T/main-e120de.o unable to open object file: No such file or directory\n            // XCTAssertNoMatch(output.stdout, .contains(\"unable to open object file\"))\n        }\n#endif\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        .skipHostOS(.linux),\n        .skipHostOS(.android),\n        .tags(\n            .Feature.Command.Test,\n            .Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func unicode(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/Unicode\") { fixturePath in\n                // See the fixture manifest for an explanation of this string.\n                let complicatedString = \"πשּׁµ𝄞🇺🇳🇮🇱x̱̱̱̱̱̄̄̄̄̄\"\n                let verify = \"\\u{03C0}\\u{0FB2C}\\u{00B5}\\u{1D11E}\\u{1F1FA}\\u{1F1F3}\\u{1F1EE}\\u{1F1F1}\\u{0078}\\u{0331}\\u{0304}\\u{0331}\\u{0304}\\u{0331}\\u{0304}\\u{0331}\\u{0304}\\u{0331}\\u{0304}\"\n                #expect(\n                    complicatedString.unicodeScalars.elementsEqual(verify.unicodeScalars),\n                    \"\\(complicatedString) ≠ \\(verify)\",\n                )\n\n                // ••••• Set up dependency.\n                let dependencyName = \"UnicodeDependency‐\\(complicatedString)\"\n                let dependencyOrigin = AbsolutePath(#file).parentDirectory.parentDirectory.parentDirectory\n                    .appending(\"Fixtures\")\n                    .appending(\"Miscellaneous\")\n                    .appending(component: dependencyName)\n                let dependencyDestination = fixturePath.parentDirectory.appending(component: dependencyName)\n                try? FileManager.default.removeItem(atPath: dependencyDestination.pathString)\n                defer { try? FileManager.default.removeItem(atPath: dependencyDestination.pathString) }\n                try FileManager.default.copyItem(\n                    atPath: dependencyOrigin.pathString,\n                    toPath: dependencyDestination.pathString)\n                let dependency = GitRepository(path: dependencyDestination)\n                try dependency.create()\n                try dependency.stageEverything()\n                try dependency.commit()\n                try dependency.tag(name: \"1.0.0\")\n                // •••••\n\n                // Attempt several operations.\n                try await executeSwiftTest(\n                    fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                try await withKnownIssue(isIntermittent: true) {\n                    try await executeSwiftRun(\n                        fixturePath,\n                        complicatedString + \"‐tool\",\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                } when: {\n                    ProcessInfo.hostOperatingSystem == .linux && buildSystem == .swiftbuild\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .skipHostOS(.linux), // TODO: raise GitHub issue.. crashed on Linux\n        // TODO: raise GitHub issue for issue on Windows\n        .tags(\n            .Feature.Command.Test,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testsCanLinkAgainstExecutable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"Miscellaneous/TestableExe\") { fixturePath in\n            do {\n                let (stdout, stderr) = try await executeSwiftTest(\n                    fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                    throwIfCommandFails: true,\n                )\n                // in \"swift test\" build output goes to stderr\n                switch buildSystem {\n                    case .native:\n                        #expect(stderr.contains(\"Linking TestableExe1\"))\n                        #expect(stderr.contains(\"Linking TestableExe2\"))\n                        #expect(stderr.contains(\"Linking TestableExePackageTests\"))\n                    case .swiftbuild, .xcode:\n                        break\n                }\n                #expect(stderr.contains(\"Build complete!\"))\n                // in \"swift test\" test output goes to stdout\n                #expect(stdout.contains(\"Executed 1 test\"))\n                #expect(stdout.contains(\"Hello, world\"))\n                #expect(stdout.contains(\"Hello, planet\"))\n            } catch {\n#if os(macOS) && arch(arm64)\n                // Add some logging but ignore the failure for an environment being investigated.\n                let (stdout, stderr) = try await executeSwiftTest(\n                    fixturePath,\n                    configuration: configuration,\n                    extraArgs: [\"-v\"],\n                    buildSystem: buildSystem,\n                )\n                print(\"\\(String(describing: Test.current?.name)) failed\")\n                print(\"ENV:\\n\")\n                for (k, v) in Environment.current.sorted(by: { $0.key < $1.key }) {\n                    print(\"  \\(k)=\\(v)\")\n                }\n                print(\"STDOUT:\\n\\(stdout)\")\n                print(\"STDERR:\\n\\(stderr)\")\n#else\n                Issue.record(\"\\(error)\")\n#endif\n            }\n        }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    @available(macOS 15, *)\n    func testsCanLinkAgainstAsyncExecutable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue {\n        try await fixture(name: \"Miscellaneous/TestableAsyncExe\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftTest(\n                fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n                throwIfCommandFails: true,\n            )\n            // in \"swift test\" build output goes to stderr\n            switch buildSystem {\n                case .native:\n                    #expect(stderr.contains(\"Linking TestableAsyncExe1\"))\n                    #expect(stderr.contains(\"Linking TestableAsyncExe2\"))\n                    #expect(stderr.contains(\"Linking TestableAsyncExe3\"))\n                    #expect(stderr.contains(\"Linking TestableAsyncExe4\"))\n                    #expect(stderr.contains(\"Linking TestableAsyncExePackageTests\"))\n                case .swiftbuild, .xcode:\n                    break\n            }\n            #expect(stderr.contains(\"Build complete!\"))\n            // in \"swift test\" test output goes to stdout\n            #expect(stdout.contains(\"Executed 1 test\"), \"stderr: \\(stderr)\")\n            #expect(stdout.contains(\"Hello, async world\"), \"stderr: \\(stderr)\")\n            #expect(stdout.contains(\"Hello, async planet\"), \"stderr: \\(stderr)\")\n            #expect(stdout.contains(\"Hello, async galaxy\"), \"stderr: \\(stderr)\")\n            #expect(stdout.contains(\"Hello, async universe\"), \"stderr: \\(stderr)\")\n        }\n        } when: {\n            // error: FileSystemError(kind: TSCBasic.FileSystemError.Kind.noEntry, path: Optional(<AbsolutePath:\"C:\\Users\\ContainerAdministrator\\AppData\\Local\\Temp\\Miscellaneous_TestableAsyncExe.74Koc7\\Miscellaneous_TestableAsyncExe\\.build\\out\\Intermediates.noindex\\TestableAsyncExe.build\\Debug-windows\\TestableAsyncExe4.build\\Objects-normal\\x86_64\\TestableAsyncExe4.LinkFileList\">))\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func executableTargetMismatch(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"Miscellaneous/TargetMismatch\") { path in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                path,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            // in \"swift build\" build output goes to stdout\n            if buildSystem == .native {\n                #expect(stdout.contains(\"Compiling Sample main.swift\"))\n            }\n            #expect(stderr.contains(\"The target named 'Sample' was identified as an executable target but a non-executable product with this name already exists.\"))\n        }\n        } when: {\n            // error: Unable to resolve build file: BuildFile<PACKAGE-PRODUCT:miscellaneous_targetmismatch_Sample.Sample::BUILDPHASE_0::0> (The workspace has a reference to a missing target with GUID 'PACKAGE-TARGET:Sample')\n            buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func libraryTriesToIncludeExecutableTarget(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/PackageWithMalformedLibraryProduct\") { path in\n            await expectThrowsCommandExecutionError(\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            ) { error in\n                // if our code crashes we'll get an exit code of 256\n                guard error.result.exitStatus == .terminated(code: 1) else {\n                    Issue.record(\"failed in an unexpected manner: \\(error)\")\n                    return\n                }\n                #expect((error.stdout + error.stderr).contains(\"library product 'PackageWithMalformedLibraryProduct' should not contain executable targets (it has 'PackageWithMalformedLibraryProduct')\"))\n            }\n        }\n    }\n\n     @Test(\n        .tags(\n            .Feature.Command.Build,\n            .Feature.Command.Package.Edit,\n            .Feature.Command.Package.Unedit,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func editModeEndToEnd(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/Edit\", createGitRepo: true) { fixturePath in\n#if os(Windows)\n            let prefix = fixturePath\n#else\n            let prefix = try resolveSymlinks(fixturePath)\n#endif\n            let appPath = fixturePath.appending(\"App\")\n\n            // prepare the dependencies as git repos\n            for directory in [\"Foo\", \"Bar\"] {\n                let path = fixturePath.appending(component: directory)\n                _ = try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", path.pathString, \"init\")\n            }\n\n            do {\n                // make sure it builds\n                let output = try await executeSwiftBuild(\n                    appPath,\n                    configuration: configuration,\n                    extraArgs: [\"-v\"],\n                    buildSystem: buildSystem,\n                )\n                // package resolution output goes to stderr\n                #expect(output.stderr.contains(\"Fetching \\(prefix.appending(\"Foo\").pathString)\"))\n                #expect(output.stderr.contains(\"Fetched \\(prefix.appending(\"Foo\").pathString)\"))\n                #expect(output.stderr.contains(\"Creating working copy for \\(prefix.appending(\"Foo\").pathString)\"))\n                #expect(output.stderr.contains(\"Fetching \\(prefix.appending(\"Bar\").pathString)\"))\n                #expect(output.stderr.contains(\"Fetched \\(prefix.appending(\"Bar\").pathString)\"))\n                #expect(output.stderr.contains(\"Creating working copy for \\(prefix.appending(\"Bar\").pathString)\"))\n                // in \"swift build\" build output goes to stdout\n                #expect(output.stdout.contains(\"Build complete!\"))\n            }\n\n            // put foo into edit mode\n            _ = try await executeSwiftPackage(\n                appPath,\n                configuration: configuration,\n                extraArgs: [\"edit\", \"Foo\"],\n                buildSystem: buildSystem,\n            )\n            expectDirectoryExists(at: appPath.appending(components: [\"Packages\", \"Foo\"]))\n\n            do {\n                // build again in edit mode\n                let output = try await executeSwiftBuild(\n                    appPath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(output.stdout.contains(\"Build complete!\"))\n            }\n\n            do {\n                // take foo out of edit mode\n                let output = try await executeSwiftPackage(\n                    appPath,\n                    configuration: configuration,\n                    extraArgs: [\"-v\", \"unedit\", \"Foo\"],\n                    buildSystem: buildSystem,\n                )\n                // package resolution output goes to stderr\n                #expect(output.stderr.contains(\"Creating working copy for \\(prefix.appending(\"Foo\"))\"))\n                expectFileDoesNotExists(at: appPath.appending(components: [\"Packages\", \"Foo\"]))\n            }\n\n            // build again in edit mode\n            do {\n                let output = try await executeSwiftBuild(\n                    appPath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                // in \"swift build\" build output goes to stdout\n                #expect(output.stdout.contains(\"Build complete!\"))\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n        [ \"cache-path\", \"config-path\", \"security-path\"],\n    )\n    func customCachePath(\n        buildSystem: BuildSystemProvider.Kind,\n        pathOption: String,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/Simple\") { path in\n            let customPath = path.appending(components: \"custom\", pathOption)\n            expectFileDoesNotExists(at: customPath)\n            expectDirectoryDoesNotExist(at: customPath)\n            try await executeSwiftBuild(\n                path,\n                configuration: configuration,\n                extraArgs: [\"--\\(pathOption)\", customPath.pathString],\n                buildSystem: buildSystem,\n            )\n            expectDirectoryExists(at: customPath)\n        }\n    }\n\n    @Test(\n        // .skipHostOS(.linux, \"`FileSystem` does not support `chmod` on Linux\"),\n        // .skipHostOS(.windows, \"`FileSystem` does not support `chmod` on Windows\"),\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n        [ \"cache-path\", \"config-path\", \"security-path\"],\n    )\n    func customPathUserUnwritableGeneratesPermissionError(\n        buildSystem: BuildSystemProvider.Kind,\n        pathOption: String,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/Simple\") { path in\n            // `FileSystem` does not support `chmod` on Linux\n            try localFileSystem.chmod(.userUnWritable, path: path)\n            defer {\n                do {\n                    try localFileSystem.chmod(.userWritable, path: path)\n                } catch {\n                    // Do nothing\n                }\n            }\n            let customPath = path.appending(components: \"custom\", pathOption)\n            expectFileDoesNotExists(at: customPath)\n            expectDirectoryDoesNotExist(at: customPath)\n            try await withKnownIssue(isIntermittent: true) {\n                await expectThrowsCommandExecutionError(\n                    try await executeSwiftBuild(\n                        path,\n                        configuration: configuration,\n                        extraArgs: [\"--\\(pathOption)\", customPath.pathString],\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    let stderr = error.stderr\n                    #expect(stderr.contains(\"error: invalid access to\"), \"expected permissions error. stderr: '\\(stderr)', stdout '\\(error.stdout)'\")\n                }\n                expectFileDoesNotExists(at: customPath)\n                expectDirectoryDoesNotExist(at: customPath)\n            } when: {\n                ProcessInfo.hostOperatingSystem != .macOS // `FileSystem` many not support `chmod` on this host OS\n            }\n        }\n    }\n\n\n    @Test(\n        .IssueWindowsRelativePathAssert,\n        .IssueWindowsAbsoluteAndRelativePathTestFailures,\n        // TODO: raise github issue..  swift run fails to execute the executable\n        //     Build complete! (4.65 secs.)\n        //     PluginGeneratedResources/PluginGeneratedResources.swift:9: Fatal error: Unexpectedly found nil while unwrapping an Optional value\n        //     [1]    13225 trace trap  swift run swift-run --package-path  --configuration debug --build-system\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func pluginGeneratedResources(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/PluginGeneratedResources\") { path in\n                let result = try await executeSwiftRun(\n                    path,\n                    nil,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                #expect(result.stdout == \"Hello, World!\\n\")\n                #expect(result.stderr.contains(\"Copying best.txt\\n\"), \"build log is missing message about copying resource file\")\n            }\n        }when: {\n            (buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .linux)\n            || (buildSystem == .swiftbuild)\n            || (ProcessInfo.hostOperatingSystem == .windows && CiEnvironment.runningInSmokeTestPipeline)\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func compileCXX17CrashWithFModules(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/CXX17CompilerCrash/v5_8\") { fixturePath in\n            await #expect(throws: Never.self) {\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n        }\n    }\n\n    @Test(\n        .IssueWindowsFolderCreationFailure,\n        .tags(\n            .Feature.Command.Build,\n        ),\n        // TODO: raise GitHub issue for known issue on Windows\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func noJSONOutputWithFlatPackageStructure(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"Miscellaneous/FlatPackage\") { packagePath in\n            // First build, make sure we got the `.build` directory where we expect it, and that there is no JSON output (by looking for known output).\n            let (stdout1, stderr1) = try await executeSwiftBuild(\n                packagePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            let buildOutput = try packagePath.appending(components: buildSystem.binPath(for: configuration))\n            expectDirectoryExists(at: buildOutput)\n            #expect(!stdout1.contains(\"command_arguments\"))\n            #expect(!stderr1.contains(\"command_arguments\"))\n\n            // Now test, make sure we got the `.build` directory where we expect it, and that there is no JSON output (by looking for known output).\n            let (stdout2, stderr2) = try await executeSwiftTest(\n                packagePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            let testOutput = try packagePath.appending(components: buildSystem.binPath(for: configuration))\n            expectDirectoryExists(at: testOutput)\n            #expect(!stdout2.contains(\"command_arguments\"))\n            #expect(!stderr2.contains(\"command_arguments\"))\n        }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func warningWithinFunction(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/WarningWithinFunction\") { path in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                path,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            let buildOutput = try path.appending(components: buildSystem.binPath(for: configuration))\n            expectDirectoryExists(at: buildOutput)\n            #expect((stdout + stderr).contains(\"initialization of variable 'myvariable' was never used\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9078\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func noWarningFromRemoteDependencies(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/DependenciesWarnings\") { path in\n            // prepare the deps as git sources\n            let dependency1Path = path.appending(\"dep1\")\n            initGitRepo(dependency1Path, tag: \"1.0.0\")\n            let dependency2Path = path.appending(\"dep2\")\n            initGitRepo(dependency2Path, tag: \"1.0.0\")\n\n            let appPath = path.appending(\"app\")\n            let (stdout, stderr) = try await executeSwiftBuild(\n                appPath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            let buildOutput = try appPath.appending(components: buildSystem.binPath(for: configuration))\n            expectDirectoryExists(at: buildOutput)\n            #expect((stdout + stderr).contains(\"'DeprecatedApp' is deprecated\"))\n            #expect(!(stdout + stderr).contains(\"'Deprecated1' is deprecated\"))\n            #expect(!(stdout + stderr).contains(\"'Deprecated2' is deprecated\"))\n        }\n        } when: {\n            buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9517\", relationship: .defect),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func noWarningFromRemoteDependenciesWithWarningsAsErrors(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/DependenciesWarnings2\") { path in\n                // prepare the deps as git sources\n                let dependency1Path = path.appending(\"dep1\")\n                initGitRepo(dependency1Path, tag: \"1.0.0\")\n                let dependency2Path = path.appending(\"dep2\")\n                initGitRepo(dependency2Path, tag: \"1.0.0\")\n\n                let appPath = path.appending(\"app\")\n                let (stdout, stderr) = try await executeSwiftBuild(\n                    appPath,\n                    configuration: configuration,\n                    Xswiftc: [\"-warnings-as-errors\"],\n                    buildSystem: buildSystem,\n                )\n                let buildOutput = try appPath.appending(components: buildSystem.binPath(for: configuration))\n                expectDirectoryExists(at: buildOutput)\n                #expect(!(stdout + stderr).contains(\"'Deprecated1' is deprecated\"))\n                #expect(!(stdout + stderr).contains(\"'Deprecated2' is deprecated\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func rootPackageWithConditionals(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/RootPackageWithConditionals\") { path in\n                let (_, stderr) = try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\" : \"/this/is/a/bad/path\"],\n                    buildSystem: buildSystem,\n                )\n                switch buildSystem {\n                    case .native:\n                        let errors = stderr.components(separatedBy: .newlines).filter { !$0.contains(\"[logging] misuse\") && !$0.isEmpty }\n                                                                        .filter { !$0.contains(\"Unable to locate libSwiftScan\") }\n                        #expect(errors == [])\n                    case .swiftbuild, .xcode:\n                        break\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n}\n\n@Suite\nstruct MiscellaneousSwiftTestingTests {\n    @Test(.skipHostOS(.windows), arguments: SupportedBuildSystemOnAllPlatforms)\n    func pkgConfigCFamilyTargets(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/PkgConfig\", createGitRepo: true) { fixturePath in\n            let systemModule = fixturePath.appending(\"SystemModule\")\n            // Create a shared library.\n            let input = systemModule.appending(components: \"Sources\", \"SystemModule.c\")\n            let triple = try UserToolchain.default.targetTriple\n            let output = systemModule.appending(\"libSystemModule\\(triple.dynamicLibraryExtension)\")\n            try await AsyncProcess.checkNonZeroExit(args: executableName(\"clang\"), \"-shared\", input.pathString, \"-o\", output.pathString)\n\n            let pcFile = fixturePath.appending(\"libSystemModule.pc\")\n\n            try localFileSystem.writeFileContents(pcFile, string: \"\"\"\n                prefix=\\(systemModule.pathString)\n                exec_prefix=${prefix}\n                libdir=${exec_prefix}\n                includedir=${prefix}/Sources/include\n                Name: SystemModule\n                URL: http://127.0.0.1/\n                Description: The one and only SystemModule\n                Version: 1.10.0\n                Cflags: -I${includedir}\n                Libs: -L${libdir} -lSystemModule\n\n                \"\"\"\n            )\n\n            let moduleUser = fixturePath.appending(\"SystemModuleUserClang\")\n            let env: Environment = [\"PKG_CONFIG_PATH\": fixturePath.pathString]\n            _ = try await executeSwiftBuild(\n                moduleUser,\n                env: env,\n                buildSystem: buildSystem,\n            )\n\n            // Clean up the build directory before re-running the build with\n            // different arguments.\n            _ = try await executeSwiftPackage(\n                moduleUser,\n                extraArgs: [\"clean\"],\n                buildSystem: buildSystem,\n            )\n\n            _ = try await executeSwiftBuild(\n                moduleUser,\n                extraArgs: [\"--pkg-config-path\", fixturePath.pathString],\n                buildSystem: buildSystem,\n            )\n        }\n    }\n\n    @Test(\n        .tags(.Feature.Command.Build),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func caseInsensitiveCollisions(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/CaseCollision\") { fixturePath in\n            try await executeSwiftBuild(\n                fixturePath,\n                buildSystem: buildSystem,\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/ModuleAliasingFixtureTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport struct SPMBuildCore.BuildSystemProvider\nimport Commands\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\nimport Workspace\nimport Testing\n\n@Suite(\n    .serializedIfOnWindows,\n    .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8987\", relationship: .verifies),\n    .tags(\n        .TestSize.large,\n        .Feature.ModuleAliasing,\n    ),\n)\nstruct ModuleAliasingFixtureTests {\n    @Test(\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func moduleDirectDeps1(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n            try await fixture(name: \"ModuleAliasing/DirectDeps1\") { fixturePath in\n                let pkgPath = fixturePath.appending(components: \"AppPkg\")\n                let buildPath = try pkgPath.appending(components: buildSystem.binPath(for: configuration))\n                let expectedModules = [\n                    \"GameUtils.swiftmodule\",\n                    \"Utils.swiftmodule\",\n                ]\n                try await executeSwiftBuild(\n                    pkgPath,\n                    configuration: configuration,\n                    extraArgs: [\"--vv\"],\n                    buildSystem: buildSystem,\n                )\n\n                expectFileExists(at: buildPath.appending(components: executableName(\"App\")))\n                for file in expectedModules {\n                    switch buildSystem {\n                    case .native:\n                        expectFileExists(at: buildPath.appending(components: \"Modules\", file))\n                    case .swiftbuild:\n                        expectFileExists(at: buildPath.appending(components: file))\n                    case .xcode:\n                        Issue.record(\"expectations are not implemented\")\n                    }\n                }\n                _ = try await executeSwiftBuild(\n                    pkgPath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/9130\", relationship: .fixedBy),\n        .IssueWindowsLongPath,\n        .IssueWindowsCannotSaveAttachment,\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func moduleDirectDeps2(\n        buildSystem: BuildSystemProvider.Kind\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"ModuleAliasing/DirectDeps2\") { fixturePath in\n                let pkgPath = fixturePath.appending(components: \"AppPkg\")\n                let buildPath = try pkgPath.appending(components: buildSystem.binPath(for: configuration))\n                let expectedModules = [\n                    \"AUtils.swiftmodule\",\n                    \"BUtils.swiftmodule\",\n                ]\n                try await executeSwiftBuild(\n                    pkgPath,\n                    configuration: configuration,\n                    extraArgs: [\"--vv\"],\n                    buildSystem: buildSystem,\n                )\n                expectFileExists(at: buildPath.appending(components: executableName(\"App\")))\n                for file in expectedModules {\n                    switch buildSystem {\n                    case .native:\n                        expectFileExists(at: buildPath.appending(components: \"Modules\", file))\n                    case .swiftbuild:\n                        expectFileExists(at: buildPath.appending(components: file))\n                    case .xcode:\n                        Issue.record(\"expectations are not implemented\")\n                    }\n                }\n                _ = try await executeSwiftBuild(\n                    pkgPath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/9130\", relationship: .fixedBy),\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func moduleNestedDeps1(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"ModuleAliasing/NestedDeps1\") { fixturePath in\n            let pkgPath = fixturePath.appending(components: \"AppPkg\")\n            let buildPath = try pkgPath.appending(components: buildSystem.binPath(for: configuration))\n            let expectedModules = [\n                \"A.swiftmodule\",\n                \"AFooUtils.swiftmodule\",\n                \"CarUtils.swiftmodule\",\n                \"X.swiftmodule\",\n                \"XFooUtils.swiftmodule\",\n                \"XUtils.swiftmodule\",\n            ]\n            try await executeSwiftBuild(\n                pkgPath,\n                configuration: configuration,\n                extraArgs: [\"--vv\"],\n                buildSystem: buildSystem,\n            )\n            expectFileExists(at: buildPath.appending(components: executableName(\"App\")))\n            for file in expectedModules {\n                switch buildSystem {\n                case .native:\n                    expectFileExists(at: buildPath.appending(components: \"Modules\", file))\n                case .swiftbuild:\n                    expectFileExists(at: buildPath.appending(components: file))\n                case .xcode:\n                    Issue.record(\"expectations are not implemented\")\n                }\n            }\n\n            _ = try await executeSwiftBuild(\n                pkgPath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/pull/9130\", relationship: .fixedBy),\n        .IssueWindowsLongPath,\n        .IssueWindowsCannotSaveAttachment,\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func moduleNestedDeps2(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"ModuleAliasing/NestedDeps2\") { fixturePath in\n            let pkgPath = fixturePath.appending(components: \"AppPkg\")\n            let buildPath = try pkgPath.appending(components: buildSystem.binPath(for: configuration))\n            try await executeSwiftBuild(\n                pkgPath,\n                configuration: configuration,\n                extraArgs: [\"--vv\"],\n                buildSystem: buildSystem,\n            )\n            let expectedModules = [\n                \"A.swiftmodule\",\n                \"BUtils.swiftmodule\",\n                \"CUtils.swiftmodule\",\n                \"XUtils.swiftmodule\",\n            ]\n            expectFileExists(at: buildPath.appending(components: executableName(\"App\")))\n            for file in expectedModules {\n                switch buildSystem {\n                case .native:\n                    expectFileExists(at: buildPath.appending(components: \"Modules\", file))\n                case .swiftbuild:\n                    expectFileExists(at: buildPath.appending(components: file))\n                case .xcode:\n                    Issue.record(\"expectations are not implemented\")\n                }\n            }\n            _ = try await executeSwiftBuild(\n                pkgPath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/ModuleMapTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2026 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport Basics\nimport Commands\nimport PackageModel\nimport _InternalTestSupport\nimport Workspace\nimport Testing\n\nimport struct SPMBuildCore.BuildSystemProvider\n\n@Suite(\n    .serialized, // crash occurs when executed in parallel. needs investigation\n    .tags(\n        .FunctionalArea.ModuleMaps,\n    ),\n)\nstruct ModuleMapsTestCase {\n    private func localFixture(\n        name: String,\n        cModuleName: String,\n        rootpkg: String,\n        buildSystem: BuildSystemProvider.Kind,\n        config: BuildConfiguration,\n        body: @escaping (AbsolutePath, [String]) async throws -> Void\n    ) async throws {\n        try await fixture(name: name, createGitRepo: true) { fixturePath in\n            let input = fixturePath.appending(components: cModuleName, \"C\", \"foo.c\")\n            let outdir = try fixturePath.appending(components: [rootpkg] + buildSystem.binPath(for: config))\n            try makeDirectories(outdir)\n            let triple = try UserToolchain.default.targetTriple\n            let output = outdir.appending(\"libfoo\\(triple.dynamicLibraryExtension)\")\n            try await AsyncProcess.checkNonZeroExit(args: executableName(\"clang\"), \"-shared\", input.pathString, \"-o\", output.pathString)\n\n            var Xld = [\"-L\", outdir.pathString]\n        #if os(Linux) || os(Android)\n            Xld += [\"-rpath\", outdir.pathString]\n        #endif\n\n            try await body(fixturePath, Xld)\n        }\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func directDependency(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await localFixture(\n                name: \"ModuleMaps/Direct\",\n                cModuleName: \"CFoo\",\n                rootpkg: \"App\",\n                buildSystem: buildSystem,\n                config: configuration,\n            ) { fixturePath, Xld in\n                try await executeSwiftBuild(\n                    fixturePath.appending(\"App\"),\n                    configuration: configuration,\n                    Xld: Xld,\n                    buildSystem: buildSystem,\n                )\n\n                let executable = try fixturePath.appending(components: [\"App\"] + buildSystem.binPath(for: configuration) + [\"App\"])\n                let releaseout = try await AsyncProcess.checkNonZeroExit(\n                    args: executable.pathString\n                )\n                #expect(releaseout == \"123\\n\")\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n            || (buildSystem == .swiftbuild && configuration == .release)\n        }\n    }\n\n    @Test(\n        .serialized, // crash occurs when executed in parallel. needs investigation\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func transitiveDependency(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await localFixture(\n                name: \"ModuleMaps/Transitive\",\n                cModuleName: \"packageD\",\n                rootpkg: \"packageA\",\n                buildSystem: buildSystem,\n                config: configuration,\n            ) { fixturePath, Xld in\n                try await executeSwiftBuild(\n                    fixturePath.appending(\"packageA\"),\n                    configuration: configuration,\n                    Xld: Xld,\n                    buildSystem: buildSystem,\n                )\n\n                let executable = try fixturePath.appending(components: [\"packageA\"] + buildSystem.binPath(for: configuration) + [\"packageA\"])\n                let out = try await AsyncProcess.checkNonZeroExit(\n                    args: executable.pathString\n                )\n                #expect(out == \"\"\"\n                    calling Y.bar()\n                    Y.bar() called\n                    X.foo() called\n                    123\n\n                    \"\"\")\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n            || (buildSystem == .swiftbuild && configuration == .release)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/PluginTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\n\n@_spi(SwiftPMInternal)\n@testable import PackageGraph\nimport PackageLoading\nimport PackageModel\n@testable import SPMBuildCore\nimport _InternalTestSupport\nimport Workspace\nimport Testing\nimport Foundation\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .TestSize.large,\n        .Feature.Command.Package.Plugin,\n        .Feature.Plugin,\n    )\n)\nstruct PluginTests {\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n            .Feature.CommandLineArguments.Product,\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testUseOfBuildToolPluginTargetByExecutableInSamePackage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPlugin\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                extraArgs: [\"--product\", \"MyLocalTool\"],\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Linking MySourceGenBuildTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Generating foo.swift from foo.dat\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking MyLocalTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build of product 'MyLocalTool' complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8786\"),\n        .requiresSwiftConcurrencySupport,\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n        .tags(\n            .Feature.Command.Test,\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n\n    func testUseOfBuildToolPluginTargetNoPreBuildCommands(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPluginNoPreBuildCommands\") { fixturePath in\n                let (_, stderr) = try await executeSwiftTest(\n                    fixturePath,\n                    buildSystem: buildSystem,\n                )\n                #expect(stderr.contains(\"file(s) which are unhandled; explicitly declare them as resources or exclude from the target\"), \"expected warning not emitted\")\n            }\n        } when: {\n            buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Product,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testUseOfBuildToolPluginProductByExecutableAcrossPackages(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath.appending(\"MySourceGenClient\"),\n                configuration: .debug,\n                extraArgs: [\"--product\", \"MyTool\"],\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Linking MySourceGenBuildTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Generating foo.swift from foo.dat\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking MyTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build of product 'MyTool' complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n                case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Product,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testUseOfPrebuildPluginTargetByExecutableAcrossPackages(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPlugin\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                extraArgs: [\"--product\", \"MyOtherLocalTool\"],\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Compiling MyOtherLocalTool bar.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Compiling MyOtherLocalTool baz.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking MyOtherLocalTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build of product 'MyOtherLocalTool' complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n        arguments: SupportedBuildSystemOnAllPlatforms\n    )\n    func testUseOfPluginWithInternalExecutable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath.appending(\"ClientOfPluginWithInternalExecutable\"),\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Compiling PluginExecutable main.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking PluginExecutable\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Generating foo.swift from foo.dat\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Compiling RootTarget foo.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking RootTarget\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testInternalExecutableAvailableOnlyToPlugin(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins\") { fixturePath in\n            let error = try await #require(throws: SwiftPMError.self, \"Illegally used internal executable\") {\n                try await executeSwiftBuild(\n                    fixturePath.appending(\"InvalidUseOfInternalPluginExecutable\"),\n                    buildSystem: buildSystem,\n                )\n            }\n\n            guard case SwiftPMError.executionFailure(_, _, let stderr) = error else {\n                Issue.record(\"Unexpected error type: \\(error.interpolationDescription)\")\n                return\n            }\n\n            #expect(\n                stderr.contains(\"product 'PluginExecutable' required by package 'invaliduseofinternalpluginexecutable' target 'RootTarget' not found in package 'PluginWithInternalExecutable'.\"), \"stderr:\\n\\(stderr)\"\n            )\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n        ),\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testLocalBuildToolPluginUsingRemoteExecutable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath.appending(\"LibraryWithLocalBuildToolPluginUsingRemoteTool\"),\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Compiling MySourceGenBuildTool main.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking MySourceGenBuildTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Generating generated.swift from generated.dat\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Compiling MyLibrary generated.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testBuildToolPluginDependencies(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MyBuildToolPluginDependencies\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Compiling MySourceGenBuildTool main.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking MySourceGenBuildTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Generating foo.swift from foo.dat\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Compiling MyLocalTool foo.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testContrivedTestCases(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/ContrivedTestPlugin\") { fixturePath in\n            let buildSpecificArgs: [String] = switch buildSystem {\n                case .native, .xcode:\n                    []\n                case .swiftbuild:\n                    [\"--disable-sandbox\"]\n            }\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                extraArgs: [\"--product\", \"MyLocalTool\"] + buildSpecificArgs,\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Linking MySourceGenBuildTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Generating foo.swift from foo.dat\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking MyLocalTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build of product 'MyLocalTool' complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .requireHostOS(.macOS, \"Test is only supported on macOS\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testPluginScriptSandbox(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/SandboxTesterPlugin\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                extraArgs: [\"--product\", \"MyLocalTool\"],\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Linking MyLocalTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build of product 'MyLocalTool' complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9215\", relationship: .verifies),\n        .requiresSwiftConcurrencySupport,\n        arguments: [BuildSystemProvider.Kind.native, .swiftbuild]\n    )\n    func testUseOfVendedBinaryTool(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MyBinaryToolPlugin\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                extraArgs: [\"--product\", \"MyLocalTool\"],\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case  .native:\n                #expect(stdout.contains(\"Linking MyLocalTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build of product 'MyLocalTool' complete!\"), \"stdout:\\n(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test has no expectation for \\(buildSystem)\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .requireHostOS(.macOS, \"Test is only supported on macOS\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testUseOfBinaryToolVendedAsProduct(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/BinaryToolProductPlugin\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                extraArgs: [\"--product\", \"MyLocalTool\"],\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Linking MyLocalTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build of product 'MyLocalTool' complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expectations must be defined.\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .disabled(if: (ProcessInfo.hostOperatingSystem == .windows), \"test plugin does not support windows\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testBuildToolWithoutOutputs(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        func createPackageUnderTest(packageDir: AbsolutePath, toolsVersion: ToolsVersion) throws {\n            let manifestFile = packageDir.appending(\"Package.swift\")\n            try localFileSystem.createDirectory(manifestFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                manifestFile,\n                string: \"\"\"\n                // swift-tools-version: \\(toolsVersion.description)\n                import PackageDescription\n                let package = Package(name: \"MyPackage\",\n                    targets: [\n                        .target(name: \"SomeTarget\", plugins: [\"Plugin\"]),\n                        .plugin(name: \"Plugin\", capability: .buildTool),\n                    ])\n                \"\"\")\n\n            let targetSourceFile = packageDir.appending(components: \"Sources\", \"SomeTarget\", \"dummy.swift\")\n            try localFileSystem.createDirectory(targetSourceFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(targetSourceFile, string: \"\")\n\n            let pluginSourceFile = packageDir.appending(components: \"Plugins\", \"Plugin\", \"plugin.swift\")\n            try localFileSystem.createDirectory(pluginSourceFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(pluginSourceFile, string: \"\"\"\n            import PackagePlugin\n            #if os(Android)\n            let touchExe = \"/system/bin/touch\"\n            #else\n            let touchExe = \"/usr/bin/touch\"\n            #endif\n\n            @main\n            struct Plugin: BuildToolPlugin {\n                func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {\n                    return [\n                        .buildCommand(\n                            displayName: \"empty\",\n                            executable: .init(touchExe),\n                            arguments: [context.pluginWorkDirectory.appending(\"best.txt\")],\n                            inputFiles: [],\n                            outputFiles: []\n                        )\n                    ]\n                }\n            }\n            \"\"\")\n        }\n\n        try await testWithTemporaryDirectory { tmpPath in\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            let pathOfGeneratedFile = packageDir.appending(components: [\".build\", \"plugins\", \"outputs\", \"mypackage\", \"SomeTarget\", \"destination\", \"Plugin\", \"best.txt\"])\n\n            try await withKnownIssue {\n                try createPackageUnderTest(packageDir: packageDir, toolsVersion: .v5_9)\n                let (_, stderr) = try await executeSwiftBuild(\n                    packageDir,\n                    env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\" : \"/this/is/a/bad/path\"],\n                    buildSystem: buildSystem,\n                )\n                #expect(stderr.contains(\"warning: Build tool command 'empty' (applied to target 'SomeTarget') does not declare any output files\"), \"expected warning not emitted\")\n                #expect(!localFileSystem.exists(pathOfGeneratedFile), \"plugin generated file unexpectedly exists at \\(pathOfGeneratedFile.pathString)\")\n            } when: {\n                buildSystem == .swiftbuild\n            }\n\n            try createPackageUnderTest(packageDir: packageDir, toolsVersion: .v6_0)\n            let (stdout, stderr2) = try await executeSwiftBuild(\n                packageDir,\n                env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\" : \"/this/is/a/bad/path\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"))\n            #expect(!stderr2.contains(\"error:\"))\n            #expect(localFileSystem.exists(pathOfGeneratedFile), \"plugin did not run, generated file does not exist at \\(pathOfGeneratedFile.pathString)\")\n        }\n    }\n\n    @Test(\n        .bug(\"rdar://117870608\"),\n        .requiresSwiftConcurrencySupport,\n        .disabled()\n    )\n    func testCommandPluginInvocation() async throws {\n        // FIXME: This test is getting quite long — we should add some support functionality for creating synthetic plugin tests and factor this out into separate tests.\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package with a library target and a plugin. It depends on a sample package.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            let manifestFile = packageDir.appending(\"Package.swift\")\n            try localFileSystem.createDirectory(manifestFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                manifestFile,\n                string: \"\"\"\n                // swift-tools-version: 5.6\n                import PackageDescription\n                let package = Package(\n                    name: \"MyPackage\",\n                    dependencies: [\n                        .package(name: \"HelperPackage\", path: \"VendoredDependencies/HelperPackage\")\n                    ],\n                    targets: [\n                        .target(\n                            name: \"MyLibrary\",\n                            dependencies: [\n                                .product(name: \"HelperLibrary\", package: \"HelperPackage\")\n                            ]\n                        ),\n                        .plugin(\n                            name: \"PluginPrintingInfo\",\n                            capability: .command(\n                                intent: .custom(verb: \"print-info\", description: \"Description of the command\"),\n                                permissions: [.writeToPackageDirectory(reason: \"Reason for wanting to write to package directory\")]\n                            )\n                        ),\n                        .plugin(\n                            name: \"PluginFailingWithError\",\n                            capability: .command(\n                                intent: .custom(verb: \"fail-with-error\", description: \"Sample plugin that throws an error\")\n                            )\n                        ),\n                        .plugin(\n                            name: \"PluginFailingWithoutError\",\n                            capability: .command(\n                                intent: .custom(verb: \"fail-without-error\", description: \"Sample plugin that exits without error\")\n                            )\n                        ),\n                        .plugin(\n                            name: \"NeverendingPlugin\",\n                            capability: .command(\n                                intent: .custom(verb: \"neverending-plugin\", description: \"A plugin that doesn't end running\")\n                            )\n                        ),\n                    ]\n                )\n                \"\"\"\n            )\n            let librarySourceFile = packageDir.appending(components: \"Sources\", \"MyLibrary\", \"library.swift\")\n            try localFileSystem.createDirectory(librarySourceFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                librarySourceFile,\n                string: \"\"\"\n                public func Foo() { }\n                \"\"\"\n            )\n            let printingPluginSourceFile = packageDir.appending(components: \"Plugins\", \"PluginPrintingInfo\", \"plugin.swift\")\n            try localFileSystem.createDirectory(printingPluginSourceFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                printingPluginSourceFile,\n                string: \"\"\"\n                import PackagePlugin\n                @main struct MyCommandPlugin: CommandPlugin {\n                    func performCommand(\n                        context: PluginContext,\n                        arguments: [String]\n                    ) throws {\n                        // Check the identity of the root packages.\n                        print(\"Root package is \\\\(context.package.displayName).\")\n\n                        // Check that we can find a tool in the toolchain.\n                        let swiftc = try context.tool(named: \"swiftc\")\n                        print(\"Found the swiftc tool at \\\\(swiftc.path).\")\n                    }\n                }\n                \"\"\"\n            )\n            let pluginFailingWithErrorSourceFile = packageDir.appending(components: \"Plugins\", \"PluginFailingWithError\", \"plugin.swift\")\n            try localFileSystem.createDirectory(pluginFailingWithErrorSourceFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                pluginFailingWithErrorSourceFile,\n                string: \"\"\"\n                import PackagePlugin\n                @main struct MyCommandPlugin: CommandPlugin {\n                    func performCommand(\n                        context: PluginContext,\n                        arguments: [String]\n                    ) throws {\n                        // Print some output that should appear before the error diagnostic.\n                        print(\"This text should appear before the uncaught thrown error.\")\n\n                        // Throw an uncaught error that should be reported as a diagnostics.\n                        throw \"This is the uncaught thrown error.\"\n                    }\n                }\n                extension String: Error { }\n                \"\"\"\n            )\n            let pluginFailingWithoutErrorSourceFile = packageDir.appending(components: \"Plugins\", \"PluginFailingWithoutError\", \"plugin.swift\")\n            try localFileSystem.createDirectory(pluginFailingWithoutErrorSourceFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                pluginFailingWithoutErrorSourceFile,\n                string: \"\"\"\n                import PackagePlugin\n                import Foundation\n                @main struct MyCommandPlugin: CommandPlugin {\n                    func performCommand(\n                        context: PluginContext,\n                        arguments: [String]\n                    ) throws {\n                        // Print some output that should appear before we exit.\n                        print(\"This text should appear before we exit.\")\n\n                        // Just exit with an error code without an emitting error.\n                        exit(1)\n                    }\n                }\n                extension String: Error { }\n                \"\"\"\n            )\n            let neverendingPluginSourceFile = packageDir.appending(components: \"Plugins\", \"NeverendingPlugin\", \"plugin.swift\")\n            try localFileSystem.createDirectory(neverendingPluginSourceFile.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                neverendingPluginSourceFile,\n                string: \"\"\"\n                import PackagePlugin\n                import Foundation\n                @main struct MyCommandPlugin: CommandPlugin {\n                    func performCommand(\n                        context: PluginContext,\n                        arguments: [String]\n                    ) throws {\n                        // Print some output that should appear before we exit.\n                        print(\"This text should appear before we exit.\")\n\n                        // Just exit with an error code without an emitting error.\n                        exit(1)\n                    }\n                }\n                extension String: Error { }\n                \"\"\"\n            )\n\n            // Create the sample vendored dependency package.\n            let library1Path = packageDir.appending(components: \"VendoredDependencies\", \"HelperPackage\", \"Package.swift\")\n            try localFileSystem.createDirectory(library1Path.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                library1Path,\n                string: \"\"\"\n                // swift-tools-version: 5.5\n                import PackageDescription\n                let package = Package(\n                    name: \"HelperPackage\",\n                    products: [\n                        .library(\n                            name: \"HelperLibrary\",\n                            targets: [\"HelperLibrary\"]\n                        ),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"HelperLibrary\"\n                        ),\n                    ]\n                )\n                \"\"\"\n            )\n\n            let library2Path = packageDir.appending(components: \"VendoredDependencies\", \"HelperPackage\", \"Sources\", \"HelperLibrary\", \"library.swift\")\n            try localFileSystem.createDirectory(library2Path.parentDirectory, recursive: true)\n            try localFileSystem.writeFileContents(\n                library2Path,\n                string: \"\"\"\n                public func Bar() { }\n                \"\"\"\n            )\n\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            #expect(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n            #expect(packageGraph.packages.count == 2, \"\\(packageGraph.packages)\")\n            #expect(packageGraph.rootPackages.count == 1, \"\\(packageGraph.rootPackages)\")\n            let package = try #require(packageGraph.rootPackages.first)\n\n            // Find the regular target in our test package.\n            let libraryTarget = try #require(package.modules.map(\\.underlying).first{ $0.name == \"MyLibrary\" } as? SwiftModule)\n            #expect(libraryTarget.type == .library)\n\n            // Set up a delegate to handle callbacks from the command plugin.\n            let delegateQueue = DispatchQueue(label: \"plugin-invocation\")\n            class PluginDelegate: PluginInvocationDelegate {\n                let delegateQueue: DispatchQueue\n                var diagnostics: [Basics.Diagnostic] = []\n\n                init(delegateQueue: DispatchQueue) {\n                    self.delegateQueue = delegateQueue\n                }\n\n                func pluginCompilationStarted(commandLine: [String], environment: [String: String]) {\n                }\n\n                func pluginCompilationEnded(result: PluginCompilationResult) {\n                }\n\n                func pluginCompilationWasSkipped(cachedResult: PluginCompilationResult) {\n                }\n\n                func pluginEmittedOutput(_ data: Data) {\n                    // Add each line of emitted output as a `.info` diagnostic.\n                    dispatchPrecondition(condition: .onQueue(delegateQueue))\n                    let textlines = String(decoding: data, as: UTF8.self).split(whereSeparator: { $0.isNewline })\n                    print(textlines.map{ \"[TEXT] \\($0)\" }.joined(separator: \"\\n\"))\n                    diagnostics.append(contentsOf: textlines.map{\n                        Basics.Diagnostic(severity: .info, message: String($0), metadata: .none)\n                    })\n                }\n\n                func pluginEmittedDiagnostic(_ diagnostic: Basics.Diagnostic) {\n                    // Add the diagnostic as-is.\n                    dispatchPrecondition(condition: .onQueue(delegateQueue))\n                    print(\"[DIAG] \\(diagnostic)\")\n                    diagnostics.append(diagnostic)\n                }\n\n                func pluginEmittedProgress(_ message: String) {}\n            }\n\n            // Helper function to invoke a plugin with given input and to check its outputs.\n            func testCommand(\n                package: ResolvedPackage,\n                plugin pluginName: String,\n                modules moduleNames: [String],\n                arguments: [String],\n                toolNamesToPaths: [String: AbsolutePath] = [:],\n                sourceLocation: SourceLocation = #_sourceLocation,\n                expectFailure: Bool = false,\n                diagnosticsChecker: (DiagnosticsTestResult) throws -> Void\n            ) async throws {\n                // Find the named plugin.\n                let plugins = package.modules.compactMap{ $0.underlying as? PluginModule }\n                let plugin = try #require(plugins.first(where: { $0.name == pluginName }), \"There is no plugin target named ‘\\(pluginName)’\")\n                try #require(plugin.type == .plugin, \"Target \\(plugin) isn’t a plugin\")\n\n                // Find the named input targets to the plugin.\n                var modules: [ResolvedModule] = []\n                for name in moduleNames {\n                    let module = try #require(package.modules.first(where: { $0.underlying.name == name }), \"There is no target named ‘\\(name)’\")\n                    try #require(module.type != .plugin, \"Target \\(module) is a plugin\")\n                    modules.append(module)\n                }\n\n                let pluginDir = tmpPath.appending(components: package.identity.description, plugin.name)\n                let delegate = PluginDelegate(delegateQueue: delegateQueue)\n                do {\n                    let scriptRunner = DefaultPluginScriptRunner(\n                        fileSystem: localFileSystem,\n                        cacheDir: pluginDir.appending(\"cache\"),\n                        toolchain: try UserToolchain.default\n                    )\n\n                    let toolSearchDirectories = [try UserToolchain.default.swiftCompilerPath.parentDirectory]\n                    let success = try await withCheckedThrowingContinuation { continuation in\n                      plugin.invoke(\n                        action: .performCommand(package: package, arguments: arguments),\n                        buildEnvironment: BuildEnvironment(platform: .macOS, configuration: .debug),\n                        workers: 1,\n                        scriptRunner: scriptRunner,\n                        workingDirectory: package.path,\n                        outputDirectory: pluginDir.appending(\"output\"),\n                        toolSearchDirectories: toolSearchDirectories,\n                        accessibleTools: [:],\n                        writableDirectories: [pluginDir.appending(\"output\")],\n                        readOnlyDirectories: [package.path],\n                        allowNetworkConnections: [],\n                        pkgConfigDirectories: [],\n                        sdkRootPath: nil,\n                        fileSystem: localFileSystem,\n                        modulesGraph: packageGraph,\n                        observabilityScope: observability.topScope,\n                        callbackQueue: delegateQueue,\n                        delegate: delegate,\n                        completion: {\n                          continuation.resume(with: $0)\n                        }\n                      )\n                    }\n                    if expectFailure {\n                        #expect(!success, \"expected command to fail, but it succeeded\")\n                    }\n                    else {\n                        #expect(success, \"expected command to succeed, but it failed\", sourceLocation: sourceLocation)\n                    }\n                }\n                catch {\n                    Issue.record(\"error \\(String(describing: error))\", sourceLocation: sourceLocation)\n                }\n\n                // Check that we didn't end up with any completely empty diagnostics.\n                #expect(observability.diagnostics.first{ $0.message.isEmpty } == nil)\n\n                // Invoke the diagnostics checker for the plugin output.\n                try expectDiagnostics(delegate.diagnostics, problemsOnly: false, sourceLocation: sourceLocation, handler: diagnosticsChecker)\n            }\n\n            // Invoke the command plugin that prints out various things it was given, and check them.\n            try await testCommand(package: package, plugin: \"PluginPrintingInfo\", modules: [\"MyLibrary\"], arguments: [\"veni\", \"vidi\", \"vici\"]) { output in\n                output.check(diagnostic: .equal(\"Root package is MyPackage.\"), severity: .info)\n                output.check(diagnostic: .and(.prefix(\"Found the swiftc tool\"), .suffix(\".\")), severity: .info)\n            }\n\n            // Invoke the command plugin that throws an unhandled error at the top level.\n            try await testCommand(package: package, plugin: \"PluginFailingWithError\", modules: [], arguments: [], expectFailure: true) { output in\n                output.check(diagnostic: .equal(\"This text should appear before the uncaught thrown error.\"), severity: .info)\n                output.check(diagnostic: .equal(\"This is the uncaught thrown error.\"), severity: .error)\n\n            }\n            // Invoke the command plugin that exits with code 1 without returning an error.\n            try await testCommand(package: package, plugin: \"PluginFailingWithoutError\", modules: [], arguments: [], expectFailure: true) { output in\n                output.check(diagnostic: .equal(\"This text should appear before we exit.\"), severity: .info)\n                output.check(diagnostic: .equal(\"Plugin ended with exit code 1\"), severity: .error)\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testLocalAndRemoteToolDependencies(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/PluginUsingLocalAndRemoteTool\") { path in\n            let (stdout, stderr) = try await executeSwiftPackage(\n                path.appending(\"MyLibrary\"),\n                configuration: .debug,\n                extraArgs: [\"plugin\", \"my-plugin\"],\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                // Native build system is more explicit about what it's doing in stderr\n                #expect(stderr.contains(\"Linking RemoteTool\"), \"stdout:\\n\\(stderr)\\n\\(stdout)\")\n                #expect(stderr.contains(\"Linking LocalTool\"), \"stdout:\\n\\(stderr)\\n\\(stdout)\")\n                #expect(stderr.contains(\"Linking ImpliedLocalTool\"), \"stdout:\\n\\(stderr)\\n\\(stdout)\")\n                #expect(stderr.contains(\"Build of product 'ImpliedLocalTool' complete!\"), \"stdout:\\n\\(stderr)\\n\\(stdout)\")\n            case .swiftbuild, .xcode:\n                // There are nothing specific to expect\n                break\n            }\n            #expect(stdout.contains(\"A message from the remote tool.\"), \"stdout:\\n\\(stderr)\\n\\(stdout)\")\n            #expect(stdout.contains(\"A message from the local tool.\"), \"stdout:\\n\\(stderr)\\n\\(stdout)\")\n            #expect(stdout.contains(\"A message from the implied local tool.\"), \"stdout:\\n\\(stderr)\\n\\(stdout)\")\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n    )\n    func testPluginUsageDoesntAffectTestTargetMappings() async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPlugin\") { packageDir in\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            #expect(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n\n            // Make sure that the use of plugins doesn't bleed into the use of plugins by tools.\n            let testTargetMappings = try packageGraph.computeTestModulesForExecutableModules()\n            for (target, testTargets) in testTargetMappings {\n                #expect(!testTargets.contains{ $0.name == \"MySourceGenPluginTests\" }, \"target: \\(target), testTargets: \\(testTargets)\")\n            }\n        }\n    }\n\n    @Test(\n        .bug(\"rdar://88792829\"),\n        .requiresSwiftConcurrencySupport,\n        .disabled(if: ProcessInfo.hostOperatingSystem == .windows, \"This hangs intermittently on windows in CI\")\n    )\n    func testCommandPluginCancellation() async throws {\n        try await testWithTemporaryDirectory { (tmpPath: AbsolutePath) -> Void in\n            // Create a sample package with a couple of plugins a other targets and products.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(\n                packageDir.appending(components: \"Package.swift\"),\n                string: \"\"\"\n                // swift-tools-version: 5.6\n                import PackageDescription\n                let package = Package(\n                    name: \"MyPackage\",\n                    products: [\n                        .library(\n                            name: \"MyLibrary\",\n                            targets: [\"MyLibrary\"]\n                        ),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"MyLibrary\"\n                        ),\n                        .plugin(\n                            name: \"NeverendingPlugin\",\n                            capability: .command(\n                                intent: .custom(verb: \"neverending-plugin\", description: \"Help description\")\n                            )\n                        ),\n                    ]\n                )\n                \"\"\"\n            )\n            let myLibraryTargetDir = packageDir.appending(components: \"Sources\", \"MyLibrary\")\n            try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(\n                myLibraryTargetDir.appending(\"library.swift\"),\n                string: \"\"\"\n                public func GetGreeting() -> String { return \"Hello\" }\n                \"\"\"\n            )\n            let neverendingPluginTargetDir = packageDir.appending(components: \"Plugins\", \"NeverendingPlugin\")\n            try localFileSystem.createDirectory(neverendingPluginTargetDir, recursive: true)\n            try localFileSystem.writeFileContents(\n                neverendingPluginTargetDir.appending(\"plugin.swift\"),\n                string: \"\"\"\n                import PackagePlugin\n                import Foundation\n                @main struct NeverendingPlugin: CommandPlugin {\n                    func performCommand(\n                        context: PluginContext,\n                        arguments: [String]\n                    ) throws {\n                        print(\"pid: \\\\(ProcessInfo.processInfo.processIdentifier)\")\n                        while true {\n                            Thread.sleep(forTimeInterval: 1.0)\n                            print(\"still here\")\n                        }\n                    }\n                }\n                \"\"\"\n            )\n\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: packageDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            #expect(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n            #expect(packageGraph.packages.count == 1, \"\\(packageGraph.packages)\")\n            #expect(packageGraph.rootPackages.count == 1, \"\\(packageGraph.rootPackages)\")\n            let package: ResolvedPackage = try #require(packageGraph.rootPackages.first)\n\n            // Find the regular target in our test package.\n            let libraryTarget = try #require(\n                package.modules\n                    .map(\\.underlying)\n                    .first{ $0.name == \"MyLibrary\" } as? SwiftModule\n            )\n            #expect(libraryTarget.type == .library)\n\n            // Set up a delegate to handle callbacks from the command plugin.  In particular we want to know the process identifier.\n            let delegateQueue = DispatchQueue(label: \"plugin-invocation\")\n            class PluginDelegate: PluginInvocationDelegate {\n                let delegateQueue: DispatchQueue\n                var diagnostics: [Basics.Diagnostic] = []\n                var parsedProcessIdentifier: Int? = .none\n\n                init(delegateQueue: DispatchQueue) {\n                    self.delegateQueue = delegateQueue\n                }\n\n                func pluginCompilationStarted(commandLine: [String], environment: [String: String]) {\n                }\n\n                func pluginCompilationEnded(result: PluginCompilationResult) {\n                }\n\n                func pluginCompilationWasSkipped(cachedResult: PluginCompilationResult) {\n                }\n\n                func pluginEmittedOutput(_ data: Data) {\n                    // Add each line of emitted output as a `.info` diagnostic.\n                    dispatchPrecondition(condition: .onQueue(delegateQueue))\n                    let textlines = String(decoding: data, as: UTF8.self).split(whereSeparator: { $0.isNewline })\n                    diagnostics.append(contentsOf: textlines.map{\n                        Basics.Diagnostic(severity: .info, message: String($0), metadata: .none)\n                    })\n\n                    // If we don't already have the process identifier, we try to find it.\n                    if parsedProcessIdentifier == .none {\n                        func parseProcessIdentifier(_ string: String) -> Int? {\n                            guard let match = try? NSRegularExpression(pattern: \"pid: (\\\\d+)\", options: []).firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count)) else { return .none }\n                            // We have a match, so extract the process identifier.\n                            assert(match.numberOfRanges == 2)\n                            return Int((string as NSString).substring(with: match.range(at: 1)))\n                        }\n                        parsedProcessIdentifier = textlines.compactMap{ parseProcessIdentifier(String($0)) }.first\n                    }\n                }\n\n                func pluginEmittedDiagnostic(_ diagnostic: Basics.Diagnostic) {\n                    // Add the diagnostic as-is.\n                    dispatchPrecondition(condition: .onQueue(delegateQueue))\n                    diagnostics.append(diagnostic)\n                }\n\n                func pluginEmittedProgress(_ message: String) {}\n            }\n\n            // Find the relevant plugin.\n            let plugins = package.modules.compactMap { $0.underlying as? PluginModule }\n            let plugin = try #require(plugins.first(where: { $0.name == \"NeverendingPlugin\" }), \"There is no plugin target named ‘NeverendingPlugin’\")\n            #expect(plugin.type == .plugin, \"Target \\(plugin) isn’t a plugin\")\n\n            // Run the plugin.\n            let pluginDir = tmpPath.appending(components: package.identity.description, plugin.name)\n            let scriptRunner = DefaultPluginScriptRunner(\n                fileSystem: localFileSystem,\n                cacheDir: pluginDir.appending(\"cache\"),\n                toolchain: try UserToolchain.default\n            )\n            let delegate = PluginDelegate(delegateQueue: delegateQueue)\n            // Use a task with timeout to test cancellation\n            let pluginTask = Task {\n                try await withTaskCancellationHandler {\n                    _ = try await plugin.invoke(\n                        action: .performCommand(package: package, arguments: []),\n                        buildEnvironment: BuildEnvironment(platform: .macOS, configuration: .debug),\n                        workers: 1,\n                        scriptRunner: scriptRunner,\n                        workingDirectory: package.path,\n                        outputDirectory: pluginDir.appending(\"output\"),\n                        toolSearchDirectories: [try UserToolchain.default.swiftCompilerPath.parentDirectory],\n                        accessibleTools: [:],\n                        writableDirectories: [pluginDir.appending(\"output\")],\n                        readOnlyDirectories: [package.path],\n                        allowNetworkConnections: [],\n                        pkgConfigDirectories: [],\n                        sdkRootPath: try UserToolchain.default.sdkRootPath,\n                        fileSystem: localFileSystem,\n                        modulesGraph: packageGraph,\n                        observabilityScope: observability.topScope,\n                        callbackQueue: delegateQueue,\n                        delegate: delegate\n                    )\n                } onCancel: {\n                    do {\n                        try scriptRunner.cancel(deadline: .now() + .seconds(5))\n                    } catch {\n                        Issue.record(\"Cancelling script runner should not fail: \\(error)\")\n                    }\n                }\n            }\n\n            // Wait for the plugin to start and get its PID\n            try await Task.sleep(nanoseconds: UInt64(DispatchTimeInterval.seconds(3).nanoseconds()!))\n\n            // At this point we should have parsed out the process identifier. But it's possible we don't always — this is being investigated in rdar://88792829.\n            var pid: Int? = .none\n            delegateQueue.sync {\n                pid = delegate.parsedProcessIdentifier\n            }\n            guard let pid = pid else {\n                pluginTask.cancel()\n                print(\"skipping test because no pid was received from the plugin; being investigated as rdar://88792829\\n\\(delegate.diagnostics.description)\")\n                return\n            }\n\n            // Check that it's running (we do this by asking for its priority — this only works on some platforms).\n            #if os(macOS)\n            errno = 0\n            getpriority(Int32(PRIO_PROCESS), UInt32(pid))\n            #expect(errno == 0, \"unexpectedly got errno \\(errno) when trying to check process \\(pid)\")\n            #endif\n\n            // Cancel the plugin task\n            pluginTask.cancel()\n\n            // Wait a bit for cancellation to propagate\n            try await Task.sleep(nanoseconds: UInt64(DispatchTimeInterval.milliseconds(500).nanoseconds()!))\n\n            // Check that it's no longer running (we do this by asking for its priority — this only works on some platforms).\n            #if os(macOS)\n            errno = 0\n            getpriority(Int32(PRIO_PROCESS), UInt32(pid))\n            #expect(errno == ESRCH, \"unexpectedly got errno \\(errno) when trying to check process \\(pid)\")\n            #endif\n\n            // Ensure the task was actually cancelled\n            do {\n                _ = try await pluginTask.value\n                Issue.record(\"Plugin task should have been cancelled\")\n            } catch is CancellationError {\n                // Expected - task was cancelled\n            } catch {\n                // Also acceptable - plugin may have been terminated\n            }\n        }\n    }\n\n    @Test\n    func testUnusedPluginProductWarnings() async throws {\n        // Test the warnings we get around unused plugin products in package dependencies.\n        try await testWithTemporaryDirectory { tmpPath in\n            // Create a sample package that uses three packages that vend plugins.\n            let packageDir = tmpPath.appending(components: \"MyPackage\")\n            try localFileSystem.createDirectory(packageDir, recursive: true)\n            try localFileSystem.writeFileContents(\n                packageDir.appending(\"Package.swift\"),\n                string: \"\"\"\n                // swift-tools-version: 5.6\n                import PackageDescription\n                let package = Package(\n                    name: \"MyPackage\",\n                    dependencies: [\n                        .package(name: \"BuildToolPluginPackage\", path: \"VendoredDependencies/BuildToolPluginPackage\"),\n                        .package(name: \"UnusedBuildToolPluginPackage\", path: \"VendoredDependencies/UnusedBuildToolPluginPackage\"),\n                        .package(name: \"CommandPluginPackage\", path: \"VendoredDependencies/CommandPluginPackage\")\n                    ],\n                    targets: [\n                        .target(\n                            name: \"MyLibrary\",\n                            path: \".\",\n                            plugins: [\n                                .plugin(name: \"BuildToolPlugin\", package: \"BuildToolPluginPackage\")\n                            ]\n                        ),\n                    ]\n                )\n                \"\"\"\n            )\n            try localFileSystem.writeFileContents(\n                packageDir.appending(\"Library.swift\"),\n                string: \"\"\"\n                public var Foo: String\n                \"\"\"\n            )\n\n            // Create the depended-upon package that vends a build tool plugin that is used by the main package.\n            let buildToolPluginPackageDir = packageDir.appending(components: \"VendoredDependencies\", \"BuildToolPluginPackage\")\n            try localFileSystem.createDirectory(buildToolPluginPackageDir, recursive: true)\n            try localFileSystem.writeFileContents(\n                buildToolPluginPackageDir.appending(\"Package.swift\"),\n                string: \"\"\"\n                // swift-tools-version: 5.6\n                import PackageDescription\n                let package = Package(\n                    name: \"BuildToolPluginPackage\",\n                    products: [\n                        .plugin(\n                            name: \"BuildToolPlugin\",\n                            targets: [\"BuildToolPlugin\"])\n                    ],\n                    targets: [\n                        .plugin(\n                            name: \"BuildToolPlugin\",\n                            capability: .buildTool(),\n                            path: \".\")\n                    ]\n                )\n                \"\"\"\n            )\n            try localFileSystem.writeFileContents(\n                buildToolPluginPackageDir.appending(\"Plugin.swift\"),\n                string: \"\"\"\n                import PackagePlugin\n                @main struct MyPlugin: BuildToolPlugin {\n                    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n                        return []\n                    }\n                }\n                \"\"\"\n            )\n\n            // Create the depended-upon package that vends a build tool plugin that is not used by the main package.\n            let unusedBuildToolPluginPackageDir = packageDir.appending(components: \"VendoredDependencies\", \"UnusedBuildToolPluginPackage\")\n            try localFileSystem.createDirectory(unusedBuildToolPluginPackageDir, recursive: true)\n            try localFileSystem.writeFileContents(\n                unusedBuildToolPluginPackageDir.appending(\"Package.swift\"),\n                string: \"\"\"\n                // swift-tools-version: 5.6\n                import PackageDescription\n                let package = Package(\n                    name: \"UnusedBuildToolPluginPackage\",\n                    products: [\n                        .plugin(\n                            name: \"UnusedBuildToolPlugin\",\n                            targets: [\"UnusedBuildToolPlugin\"])\n                    ],\n                    targets: [\n                        .plugin(\n                            name: \"UnusedBuildToolPlugin\",\n                            capability: .buildTool(),\n                            path: \".\")\n                    ]\n                )\n                \"\"\"\n            )\n            try localFileSystem.writeFileContents(\n                unusedBuildToolPluginPackageDir.appending(\"Plugin.swift\"),\n                string: \"\"\"\n                import PackagePlugin\n                @main struct MyPlugin: BuildToolPlugin {\n                    func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {\n                        return []\n                    }\n                }\n                \"\"\"\n            )\n\n            // Create the depended-upon package that vends a command plugin.\n            let commandPluginPackageDir = packageDir.appending(components: \"VendoredDependencies\", \"CommandPluginPackage\")\n            try localFileSystem.createDirectory(commandPluginPackageDir, recursive: true)\n            try localFileSystem.writeFileContents(\n                commandPluginPackageDir.appending(\"Package.swift\"),\n                string: \"\"\"\n                // swift-tools-version: 5.6\n                import PackageDescription\n                let package = Package(\n                    name: \"CommandPluginPackage\",\n                    products: [\n                        .plugin(\n                            name: \"CommandPlugin\",\n                            targets: [\"CommandPlugin\"])\n                    ],\n                    targets: [\n                        .plugin(\n                            name: \"CommandPlugin\",\n                            capability: .command(intent: .custom(verb: \"how\", description: \"why\")),\n                            path: \".\")\n                    ]\n                )\n                \"\"\"\n            )\n            try localFileSystem.writeFileContents(\n                commandPluginPackageDir.appending(\"Plugin.swift\"),\n                string: \"\"\"\n                import PackagePlugin\n                @main struct MyPlugin: CommandPlugin {\n                    func performCommand(context: PluginContext, targets: [Target], arguments: [String]) throws {\n                    }\n                }\n                \"\"\"\n            )\n\n            // Load a workspace from the package.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                location: .init(forRootPackage: packageDir, fileSystem: localFileSystem),\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n\n            // Load the root manifest.\n            let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n            #expect(rootManifests.count == 1, \"\\(rootManifests)\")\n\n            // Load the package graph.\n            let packageGraph = try await workspace.loadPackageGraph(\n                rootInput: rootInput,\n                observabilityScope: observability.topScope\n            )\n            #expect(packageGraph.packages.count == 4, \"\\(packageGraph.packages)\")\n            #expect(packageGraph.rootPackages.count == 1, \"\\(packageGraph.rootPackages)\")\n\n            // Check that we have only a warning about the unused build tool plugin (not about the used one and not about the command plugin).\n            testDiagnostics(observability.diagnostics, problemsOnly: true) { result in\n                result.checkUnordered(diagnostic: .contains(\"dependency 'unusedbuildtoolpluginpackage' is not used by any target\"), severity: .warning)\n            }\n        }\n    }\n\n    @Suite(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9040\", relationship: .verifies),\n        .tags(\n            .Feature.Snippets,\n        )\n    )\n    struct SnippetTests {\n        @Test(\n            .requiresSwiftConcurrencySupport,\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func testSnippetSupport(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/Plugins/PluginsAndSnippets\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftPackage(\n                    fixturePath,\n                    configuration: config,\n                    extraArgs: [\"do-something\"],\n                    buildSystem: buildSystem,\n                )\n                #expect(stdout.contains(\"type of snippet target: snippet\"), \"stderr:\\n\\(stderr)\")\n            }\n        }\n\n        @Test(\n            .disabled(),\n            .requiresSwiftConcurrencySupport,\n            .tags(\n                .Feature.Command.Package.CompletionTool,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func testBasicBuildSnippets(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/Plugins/PluginsAndSnippets\") { fixturePath in\n                await #expect(throws: Never.self) {\n                    let _ = try await executeSwiftBuild(\n                        fixturePath,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                }\n\n                let snippets = try await executeSwiftPackage(\n                    fixturePath,\n                    configuration: config,\n                    extraArgs: [\"completion-tool\", \"list-snippet\"],\n                    buildSystem: buildSystem,\n                ).stdout.split(whereSeparator: \\.isNewline)\n\n                for snippet in snippets {\n                    try expectFileExists(\n                        at: fixturePath.appending(components: buildSystem.binPath(for: config) + [\"\\(snippet)\"])\n                    )\n                }\n            }\n        }\n\n        @Test(\n            .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9040\", relationship: .verifies),\n            .requiresSwiftConcurrencySupport,\n            arguments: SupportedBuildSystemOnAllPlatforms, try getFiles(in: RelativePath(validating: \"Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Snippets\"), matchingExtension: \"swift\",),\n        )\n        func testBasicBuildIndividualSnippets(\n            buildSystem: BuildSystemProvider.Kind,\n            targetPath: RelativePath,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            try await fixture(name: \"Miscellaneous/Plugins/PluginsAndSnippets\") { fixturePath in\n                let targetName = targetPath.basenameWithoutExt\n                await #expect(throws: Never.self) {\n                    let _ = try await executeSwiftBuild(\n                        fixturePath,\n                        configuration: config,\n                        extraArgs: [\"--product\", targetName],\n                        buildSystem: buildSystem,\n                    )\n                }\n            }\n        }\n\n        @Test(\n            .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9040\", relationship: .verifies),\n            .requiresSwiftConcurrencySupport,\n            arguments: SupportedBuildSystemOnAllPlatforms, try getFiles(in: RelativePath(validating: \"Fixtures/Miscellaneous/Plugins/PluginsAndSnippets/Snippets\"), matchingExtension: \"swift\",),\n        )\n        func testBasicRunSnippets(\n            buildSystem: BuildSystemProvider.Kind,\n            targetPath: RelativePath,\n        ) async throws {\n            let config = BuildConfiguration.debug\n            let targetName = targetPath.basenameWithoutExt\n            try await fixture(name: \"Miscellaneous/Plugins/PluginsAndSnippets\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftRun(\n                    fixturePath,\n                    targetName,\n                    configuration: config,\n                    buildSystem: buildSystem,\n                )\n\n                #expect(stdout.contains(\"hello, snippets\"), \"stderr: \\(stderr)\")\n            }\n        }\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8774\"),\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n            .Feature.CommandLineArguments.BuildTests,\n        ),\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testIncorrectDependencies(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/IncorrectDependencies\") { path in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                path,\n                extraArgs: [\"--build-tests\"],\n                buildSystem: buildSystem,\n            )\n\n            #expect(stdout.contains(\"Build complete!\"), \"output:\\n\\(stderr)\\n\\(stdout)\")\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms\n    )\n    func testPrebuildDependencyOnExecutableTarget(buildSystem: BuildSystemProvider.Kind) async throws {\n        // Build tool plugins aren't permitted to depend on executable targets and use them in the prebuild commands\n        // that they return. This is because these commands run immediately and the executable doesn't exist yet or\n        // it isn't up-to-date.\n        try await fixture(name: \"Miscellaneous/Plugins/PrebuildDependsExecutableTarget\") { path in\n            let error = try await #require(throws: Error.self) {\n                try await executeSwiftBuild(\n                    path,\n                    extraArgs: [\"--vv\"],\n                    buildSystem: buildSystem,\n                )\n            }\n\n            #expect(\"\\(error)\".contains(\"a prebuild command cannot use executables built from source\"))\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS, \"sandboxing tests are only supported on macOS\"),\n        .requiresSwiftConcurrencySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSandboxViolatingBuildToolPluginCommands(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        // Check that the build fails with a sandbox violation by default.\n        try await fixture(name: \"Miscellaneous/Plugins/SandboxViolatingBuildToolPluginCommands\") { path in\n            let error = try await #require(throws: Error.self) {\n                try await executeSwiftBuild(\n                    path.appending(\"MyLibrary\"),\n                    configuration: .debug,\n                    buildSystem: buildSystem,\n                )\n            }\n\n            switch buildSystem {\n            case .native:\n                #expect(\"\\(error)\".contains(\"You don’t have permission to save the file “generated” in the folder “MyLibrary”.\"))\n            case .swiftbuild:\n                #expect(\"\\(error)\".contains(\"Operation not permitted\"))\n            case .xcode:\n                Issue.record(\"Test expected have not been considered\")\n            }\n        }\n\n        // Check that the build succeeds if we disable the sandbox.\n        try await fixture(name: \"Miscellaneous/Plugins/SandboxViolatingBuildToolPluginCommands\") { path in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                path.appending(\"MyLibrary\"),\n                configuration: .debug,\n                extraArgs: [\"--disable-sandbox\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"), \"[STDOUT]\\n\\(stdout)\\n[STDERR]\\n\\(stderr)\\n\")\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS, \"sandboxing tests are only supported on macOS\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testBuildToolPluginSwiftFileExecutable(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/SwiftFilePlugin\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                extraArgs: [ \"--verbose\"],\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Hello, Build Tool Plugin!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stderr.contains(\"Hello, Build Tool Plugin!\"), \"stderr:\\n\\(stderr)\")\n            case .xcode:\n                Issue.record(\"Test expected have not been considered\")\n            }\n        }\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8774\"),\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testTransitivePluginOnlyDependency(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/TransitivePluginOnlyDependency\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Compiling plugin MyPlugin\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Compiling Library Library.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expected have not been considered\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testMissingPlugin(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MissingPlugin\") { fixturePath in\n            print(fixturePath)\n            do {\n                try await executeSwiftBuild(\n                    fixturePath,\n                    buildSystem: buildSystem,\n                )\n            } catch SwiftPMError.executionFailure(_, _, let stderr) {\n                #expect(stderr.contains(\"error: 'missingplugin': no plugin named 'NonExistingPlugin' found\"), \"stderr:\\n\\(stderr)\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n        ),\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testPluginCanBeReferencedByProductName(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/PluginCanBeReferencedByProductName\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                buildSystem: buildSystem,\n            )\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Compiling plugin MyPlugin\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Compiling PluginCanBeReferencedByProductName gen.swift\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n            case .xcode:\n                Issue.record(\"Test expected have not been considered\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .tags(\n            .Feature.Command.Build,\n            .Feature.CommandLineArguments.BuildSystem,\n            .Feature.CommandLineArguments.Product,\n            .Feature.CommandLineArguments.XbuildToolsSwiftc,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testPluginCanBeAffectedByXBuildToolsParameters(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPlugin\") { fixturePath in\n            let buildArgs: [String] = switch buildSystem {\n                case .native, .xcode: []\n                case .swiftbuild: [\"-v\"]\n            }\n            let (stdout, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                extraArgs: [\"--product\", \"MyLocalTool\", \"-Xbuild-tools-swiftc\", \"-DUSE_CREATE\"] + buildArgs,\n                buildSystem: buildSystem,\n            )\n\n            switch buildSystem {\n            case .native:\n                #expect(stdout.contains(\"Linking MySourceGenBuildTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Creating foo.swift from foo.dat\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Linking MyLocalTool\"), \"stdout:\\n\\(stdout)\")\n                #expect(stdout.contains(\"Build of product 'MyLocalTool' complete!\"), \"stdout:\\n\\(stdout)\")\n            case .swiftbuild:\n                #expect(stdout.contains(\"MySourceGenBuildTool-product\"), \"stdout:\\n\\(stdout)\\nstderr:\\n\\(stderr)\")\n                #expect(stderr.contains(\"Creating foo.swift from foo.dat\"), \"stdout:\\n\\(stdout)\\nstderr:\\n\\(stderr)\")\n                #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\\nstderr:\\n\\(stderr)\")\n            case .xcode:\n                Issue.record(\"Test expected have not been considered\")\n            }\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testURLBasedPluginAPI(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/MySourceGenPluginUsingURLBasedAPI\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                configuration: .debug,\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n        }\n    }\n\n    @Test(\n        .requiresSwiftConcurrencySupport,\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testDependentPlugins(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"Miscellaneous/Plugins/DependentPlugins\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                buildSystem: buildSystem,\n            )\n            #expect(stdout.contains(\"Build complete!\"), \"stdout:\\n\\(stdout)\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/ResourcesTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport PackageModel\nimport _InternalTestSupport\nimport Testing\nimport struct SPMBuildCore.BuildSystemProvider\n\n@Suite(\n    .tags(\n        .TestSize.large,\n        .FunctionalArea.Resources,\n    ),\n)\nstruct ResourcesTests{\n    @Test(\n        .IssueWindowsRelativePathAssert,\n        .IssueWindowsPathTestsFailures,\n        .tags(\n            .Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func simpleResources(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Resources/Simple\") { fixturePath in\n                var executables = [\"SwiftyResource\"]\n\n                // Objective-C module requires macOS\n                #if os(macOS)\n                executables.append(\"SeaResource\")\n                executables.append(\"CPPResource\")\n                #endif\n\n                for execName in executables {\n                    let (output, _) = try await executeSwiftRun(\n                        fixturePath,\n                        execName,\n                        configuration: config,\n                        buildSystem: buildSystem,\n                    )\n                    #expect(output.contains(\"foo\"))\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .tags(\n            .Feature.Command.Run,\n        ),\n    )\n    func swiftBuildResourceRules() async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Resources/ResourceRules\") { fixturePath in\n            let (output, _) = try await executeSwiftRun(\n                fixturePath,\n                \"ResourceRules\",\n                configuration: config,\n                buildSystem: .swiftbuild,\n            )\n            #expect(output.contains(\"succeeded\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func localizedResources(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Resources/Localized\") { fixturePath in\n            try await executeSwiftBuild(\n                fixturePath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n\n            let exec = try fixturePath.appending(components: buildSystem.binPath(for: configuration) + [executableName(\"exe\")])\n            // Note: <rdar://problem/59738569> Source from LANG and -AppleLanguages on command line for Linux resources\n            let output = try await AsyncProcess.checkNonZeroExit(args: exec.pathString, \"-AppleLanguages\", \"(en_US)\").withSwiftLineEnding\n            #expect(output == \"\"\"\n                ¡Hola Mundo!\n                Hallo Welt!\n                Bonjour le monde !\n\n                \"\"\")\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),  // originally macOS only\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func resourcesInMixedClangPackage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Resources/Simple\") { fixturePath in\n            try await withKnownIssue(isIntermittent: true) {\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    extraArgs: [\"--target\", \"MixedClangResource\"],\n                    buildSystem: buildSystem,\n                )\n            } when: {\n                [.windows, .linux].contains(ProcessInfo.hostOperatingSystem) // Test was originally enabled on macOS only\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func movedBinaryResources(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Resources/Moved\") { fixturePath in\n                var executables = [\"SwiftyResource\"]\n\n                // Objective-C module requires macOS\n                #if os(macOS)\n                executables.append(\"SeaResource\")\n                #endif\n\n                let binPath = try AbsolutePath(validating:\n                    await executeSwiftBuild(\n                        fixturePath,\n                        configuration: configuration,\n                        extraArgs: [\"--show-bin-path\"],\n                        buildSystem: buildSystem,\n                    ).stdout.trimmingCharacters(in: .whitespacesAndNewlines)\n                )\n\n                for execName in executables {\n                    _ = try await executeSwiftBuild(\n                        fixturePath,\n                        configuration: configuration,\n                        extraArgs: [\"--product\", execName],\n                        buildSystem: buildSystem,\n                    )\n\n                    try await withTemporaryDirectory(prefix: execName) { tmpDirPath in\n                        defer {\n                            // Unblock and remove the tmp dir on deinit.\n                            try? localFileSystem.chmod(.userWritable, path: tmpDirPath, options: [.recursive])\n                            try? localFileSystem.removeFileTree(tmpDirPath)\n                        }\n\n                        let destBinPath = tmpDirPath.appending(component: executableName(execName))\n                        // Move the binary\n                        try localFileSystem.move(from: binPath.appending(component: executableName(execName)), to: destBinPath)\n                        // Move the resources\n                        try localFileSystem\n                            .getDirectoryContents(binPath)\n                            .filter { $0.contains(executableName(execName)) && $0.hasSuffix(\".bundle\") || $0.hasSuffix(\".resources\") }\n                            .forEach { try localFileSystem.move(from: binPath.appending(component: $0), to: tmpDirPath.appending(component: $0)) }\n                        // Run the binary\n                        let output = try await AsyncProcess.checkNonZeroExit(args: destBinPath.pathString)\n                        #expect(output.contains(\"foo\"))\n                    }\n                }\n            }\n        } when: {\n            // [2025-12-20T02:55:19.621Z]     SwiftyResource/resource_bundle_accessor.swift:44: Fatal error: unable to find bundle named Resources_SwiftyResource\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .IssueWindowsCannotSaveAttachment,\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func swiftResourceAccessorDoesNotCauseInconsistentImportWarning(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Resources/FoundationlessClient/UtilsWithFoundationPkg\") { fixturePath in\n            try await withKnownIssue(isIntermittent: true) {\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    Xswiftc: [\"-warnings-as-errors\"],\n                    buildSystem: buildSystem,\n                )\n            } when: {\n                // fails on native and SwiftBuild\n                // failure on SwiftBuild is: [2025-12-20T02:52:32.562Z]     error: failed to save attachment: C:\\Users\\ContainerAdministrator\\AppData\\Local\\Temp\\Resources_FoundationlessClient_UtilsWithFoundationPkg.D2Ir4d\\Resources_FoundationlessClient_UtilsWithFoundationPkg\\.build\\out\\Intermediates.noindex\\XCBuildData\\2d5f9f79f8cadfc30e6f49d9f5323426.xcbuilddata\\attachments\\99a55b01714d8caeedaaca3a1ca6347f. Error: File exists but is not a directory: C:\\Users\\ContainerAdministrator\\AppData\\Local\\Temp\\Resources_FoundationlessClient_UtilsWithFoundationPkg.D2Ir4d\\Resources_FoundationlessClient_UtilsWithFoundationPkg\\.build\\out\\Intermediates.noindex\\XCBuildData\n                // failure on native is: [2025-12-20T02:52:32.562Z]     error: encountered an I/O error (code: 514) while reading \\\\?\\C:\\Users\\ContainerAdministrator\\AppData\\Local\\Temp\\Resources_FoundationlessClient_UtilsWithFoundationPkg.0HOUUQ\\Resources_FoundationlessClient_UtilsWithFoundationPkg\\.build\\x86_64-unknown-windows-msvc\\debug\\UtilsWithFoundationPkg.build\\DerivedSources\n                ProcessInfo.hostOperatingSystem == .windows\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func resourceBundleInClangPackageWhenRunningSwiftTest(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Resources/Simple\") { fixturePath in\n            try await executeSwiftTest(\n                fixturePath,\n                configuration: configuration,\n                extraArgs: [\"--filter\", \"ClangResourceTests\"],\n                buildSystem: buildSystem,\n            )\n        }\n    }\n\n    @Test(\n        .serialized, // crash occurs when executed in parallel. needs investigation\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9528\", relationship: .defect),\n        .tags(\n            .Feature.Command.Build,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func resourcesEmbeddedInCode(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue {\n            try await fixture(name: \"Resources/EmbedInCodeSimple\") { fixturePath in\n                let execPath = try fixturePath.appending(components: buildSystem.binPath(for: configuration) + [executableName(\"EmbedInCodeSimple\")])\n                try await executeSwiftBuild(\n                    fixturePath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let result = try await AsyncProcess.checkNonZeroExit(args: execPath.pathString)\n                #expect(result.contains(\"hello world\"))\n                let resourcePath = fixturePath.appending(\n                    components: \"Sources\", \"EmbedInCodeSimple\", \"best.txt\")\n\n                // Check incremental builds\n                for i in 0..<2 {\n                    let content = \"Hi there \\(i)!\"\n                    // Update the resource file.\n                    try localFileSystem.writeFileContents(resourcePath, string: content)\n                    try await executeSwiftBuild(\n                        fixturePath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                    // Run the executable again.\n                    let result2 = try await AsyncProcess.checkNonZeroExit(args: execPath.pathString)\n                    #expect(result2.contains(\"\\(content)\"))\n                }\n            }\n        } when: {\n            buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .serialized, // crash occurs when executed in parallel. needs investigation\n        .tags(\n            .Feature.Command.Test,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func resourcesOutsideOfTargetCanBeIncluded(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let packageDir = tmpPath.appending(components: \"MyPackage\")\n\n                let manifestFile = packageDir.appending(\"Package.swift\")\n                try localFileSystem.createDirectory(manifestFile.parentDirectory, recursive: true)\n                try localFileSystem.writeFileContents(\n                    manifestFile,\n                    string: \"\"\"\n                    // swift-tools-version: 6.0\n                    import PackageDescription\n                    let package = Package(name: \"MyPackage\",\n                        targets: [\n                            .executableTarget(\n                                name: \"exec\",\n                                resources: [.copy(\"../resources\")]\n                            )\n                        ])\n                    \"\"\")\n\n                let targetSourceFile = packageDir.appending(components: \"Sources\", \"exec\", \"main.swift\")\n                try localFileSystem.createDirectory(targetSourceFile.parentDirectory, recursive: true)\n                try localFileSystem.writeFileContents(targetSourceFile, string: \"\"\"\n                import Foundation\n                print(Bundle.module.resourcePath ?? \"<empty>\")\n                \"\"\")\n\n                let resource = packageDir.appending(components: \"Sources\", \"resources\", \"best.txt\")\n                try localFileSystem.createDirectory(resource.parentDirectory, recursive: true)\n                try localFileSystem.writeFileContents(resource, string: \"best\")\n                try requireFileExists(at: resource)\n\n                let (_, stderr) = try await executeSwiftBuild(\n                    packageDir,\n                    configuration: configuration,\n                    env: [\"SWIFT_DRIVER_SWIFTSCAN_LIB\" : \"/this/is/a/bad/path\"],\n                    buildSystem: buildSystem,\n                )\n                // Filter some unrelated output that could show up on stderr.\n                let filteredStderr = stderr.components(separatedBy: \"\\n\").filter { !$0.contains(\"[logging]\") }\n                                                                        .filter { !$0.contains(\"Unable to locate libSwiftScan\") }.joined(separator: \"\\n\")\n                #expect(filteredStderr == \"\", \"unexpectedly received error output: \\(stderr)\")\n\n                let builtProductsDir = try packageDir.appending(components: buildSystem.binPath(for: configuration))\n                // On Apple platforms, it's going to be `.bundle` and elsewhere `.resources`.\n                try requireDirectoryExists(at: builtProductsDir)\n                let potentialResourceBundleName = try #require(localFileSystem.getDirectoryContents(builtProductsDir).filter { $0.hasPrefix(\"MyPackage_exec.\") }.first)\n\n                let additionalComponents: [String]\n                #if os(macOS)\n                    additionalComponents = switch buildSystem {\n                        case .native: []\n                        case .swiftbuild: [\"Contents\", \"Resources\"]\n                        case .xcode: [] // This test expectation was not validated\n                    }\n                #else\n                    additionalComponents = []\n                #endif\n                let resourcePath = builtProductsDir.appending(components: [potentialResourceBundleName] + additionalComponents +  [\"resources\", \"best.txt\"])\n                try requireFileExists(at: resourcePath, \"resource file wasn't copied by the build\")\n                let contents = try String(contentsOfFile: resourcePath.pathString)\n                #expect(contents == \"best\", \"unexpected resource contents: \\(contents)\")\n            }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/StaticBinaryLibrary.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\nimport DriverSupport\nimport PackageModel\nimport TSCBasic\nimport Testing\nimport _InternalTestSupport\nimport struct SPMBuildCore.BuildSystemProvider\n\nstruct StaticBinaryLibraryTests {\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8657\", relationship: .defect),\n        .tags(\n            .TestSize.large,\n            .Feature.Command.Run,\n            .Feature.CommandLineArguments.Experimental.PruneUnusedDependencies,\n            .Feature.TargetType.Library,\n            .Feature.TargetType.BinaryTarget.ArtifactBundle,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func staticLibrary(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        try await fixture(name: \"BinaryLibraries\") { fixturePath in\n            let (stdout, _) = try await executeSwiftRun(\n                fixturePath.appending(\"Static\").appending(\"Package1\"),\n                \"Example\",\n                configuration: .debug,\n                extraArgs: [\"--experimental-prune-unused-dependencies\"],\n                buildSystem: buildSystem,\n            )\n            #expect(stdout == \"\"\"\n            42\n            42\n\n            \"\"\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/TaskBacktracesTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport SPMBuildCore\nimport Testing\nimport _InternalTestSupport\n\n@Suite\nstruct TaskBacktraceTests {\n    @Test(\n        .tags(.TestSize.large, .Feature.TaskBacktraces),\n        .skip(\"https://github.com/swiftlang/swift-package-manager/issues/9775\")\n    )\n    func taskBacktraces() async throws {\n        try await fixture(name: \"Miscellaneous/Simple\") { fixturePath in\n            let (stdout, _) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--experimental-task-backtraces\", \"--verbose\"],\n                buildSystem: .swiftbuild\n            )\n            #expect(stdout.contains(\"Build complete!\"))\n\n            // Wait to ensure file timestamps are different on filesystems with low precision\n            try await Task.sleep(for: .milliseconds(250))\n\n            try localFileSystem.writeFileContents(\n                fixturePath.appending(components: \"Foo.swift\"),\n                bytes: \"public func bar() {}\"\n            )\n\n            let (incrementalStdout, incrementalStderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--experimental-task-backtraces\", \"--verbose\"],\n                buildSystem: .swiftbuild\n            )\n            // Add a basic check that we produce backtrace output. The specifc formatting is tested by Swift Build.\n            #expect(incrementalStderr.contains(\"Task backtrace:\"))\n            #expect(incrementalStderr.split(separator: \"\\n\").contains(where: {\n                $0.contains(\"Foo.swift' changed\")\n            }))\n            #expect(incrementalStdout.contains(\"Build complete!\"))\n        }\n    }\n\n    @Test(\n        .tags(.TestSize.large, .Feature.TaskBacktraces)\n    )\n    func taskBacktracesWarnsWithoutVerboseOutput() async throws {\n        try await fixture(name: \"Miscellaneous/Simple\") { fixturePath in\n            let (_, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--experimental-task-backtraces\"],\n                buildSystem: .swiftbuild,\n                throwIfCommandFails: false\n            )\n            #expect(stderr.contains(\"'--experimental-task-backtraces' requires '--verbose' or '--very-verbose'\"))\n        }\n    }\n\n    @Test(\n        .tags(.TestSize.large, .Feature.TaskBacktraces)\n    )\n    func taskBacktracesWarnsWithNonSwiftBuildSystem() async throws {\n        try await fixture(name: \"Miscellaneous/Simple\") { fixturePath in\n            let (_, stderr) = try await executeSwiftBuild(\n                fixturePath,\n                extraArgs: [\"--experimental-task-backtraces\", \"--verbose\"],\n                buildSystem: .native,\n                throwIfCommandFails: false\n            )\n            #expect(stderr.contains(\"'--experimental-task-backtraces' is only supported when using '--build-system swiftbuild'\"))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/TestDiscoveryTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport SPMBuildCore\nimport _InternalTestSupport\nimport Testing\nimport struct Foundation.UUID\nimport class Foundation.ProcessInfo\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .Feature.TestDiscovery,\n    ),\n)\nstruct TestDiscoveryTests {\n\n    @Test(\n        .tags(\n            .Feature.Command.Build,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func build(_ buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(\"Windows builds encounter long path handling issues\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let (stdout, _) = try await executeSwiftBuild(fixturePath, buildSystem: buildSystem)\n                // in \"swift build\" build output goes to stdout\n                #expect(stdout.contains(\"Build complete!\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .IssueWindowsLongPath,\n        .tags(\n            .Feature.Command.Test,\n            .Feature.CommandLineArguments.VeryVerbose,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func discovery(_ buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(\"Windows builds encounter long path handling issues\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, extraArgs: [\"-vv\"], buildSystem: buildSystem)\n                // in \"swift test\" build output goes to stderr\n                #expect(stderr.contains(\"Build complete!\"))\n                // in \"swift test\" test output goes to stdout\n                #expect(stdout.contains(\"Executed 3 tests\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n            .Feature.SpecialCharacters,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        .IssueWindowsCannotSaveAttachment,\n        .issue(\"https://github.com/swiftlang/swift-build/issues/333\", relationship: .defect),\n        .bug(\"https://github.com/swiftlang/swift-build/issues/13\"),\n        // arguments: [BuildSystemProvider.Kind.native],\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func nonStandardName(_ buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/hello world\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, buildSystem: buildSystem)\n                // in \"swift test\" build output goes to stderr\n                #expect(stderr.contains(\"Build complete!\"))\n                // in \"swift test\" test output goes to stdout\n                #expect(stdout.contains(\"Executed 1 test\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && [.windows, .macOS].contains(ProcessInfo.hostOperatingSystem)\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func asyncMethods(_ buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(\"Windows builds encounter long path handling issues\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Async\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, buildSystem: buildSystem)\n                // in \"swift test\" build output goes to stderr\n                #expect(stderr.contains(\"Build complete!\"))\n                // in \"swift test\" test output goes to stdout\n                #expect(stdout.contains(\"Executed 4 tests\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    // FIXME: eliminate extraneous warnings with --build-system swiftbuild\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        .IssueWindowsCannotSaveAttachment,\n        .bug(\"https://github.com/swiftlang/swift-build/issues/573\"),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func discovery_whenNoTests(_ buildSystem: BuildSystemProvider.Kind) async throws {\n            try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/NoTests\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, buildSystem: buildSystem)\n                // in \"swift test\" build output goes to stderr\n                #expect(stderr.contains(\"Build complete!\"))\n                // we are expecting that no warning is produced\n                withKnownIssue(isIntermittent: true) {\n                    #expect(!stderr.contains(\"warning:\"))\n                } when: {\n                    buildSystem == .swiftbuild\n                }\n                // in \"swift test\" test output goes to stdout\n                #expect(stdout.contains(\"Executed 0 tests\"))\n            }\n            } when: {\n                buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n            }\n    }\n\n    // FIXME: --build-system swiftbuild should support hand-authored entry points.\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-build/issues/572\"),\n        .IssueWindowsCannotSaveAttachment,\n        .skipHostOS(.macOS),\n        .tags(\n            .Feature.Command.Test,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms, SwiftModule.testEntryPointNames\n    )\n    func entryPointOverride(\n        _ buildSystem: BuildSystemProvider.Kind,\n        testEntrypointName: String\n    ) async throws {\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let random = UUID().uuidString\n                let manifestPath = fixturePath.appending(components: \"Tests\", testEntrypointName)\n                try localFileSystem.writeFileContents(manifestPath, string: \"print(\\\"\\(random)\\\")\")\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, buildSystem: buildSystem)\n                // in \"swift test\" build output goes to stderr\n                #expect(stderr.contains(\"Build complete!\"))\n                // in \"swift test\" test output goes to stdout\n                #expect(!stdout.contains(\"Executed 1 test\"))\n                #expect(stdout.contains(random), \"stderr: \\(stderr)\")\n            }\n        } when: {\n            [.windows, .linux].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n        }\n    }\n\n    @Test(\n        .skipHostOS(.macOS),\n        .tags(\n            .Feature.Command.Test,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func entryPointOverrideIgnored(_ buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(\"Windows builds encounter long path handling issues\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Simple\") { fixturePath in\n                let manifestPath = fixturePath.appending(components: \"Tests\", SwiftModule.defaultTestEntryPointName)\n                try localFileSystem.writeFileContents(manifestPath, string: \"fatalError(\\\"should not be called\\\")\")\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, extraArgs: [\"--enable-test-discovery\"], buildSystem: buildSystem)\n                // in \"swift test\" build output goes to stderr\n                #expect(stderr.contains(\"Build complete!\"))\n                // in \"swift test\" test output goes to stdout\n                #expect(!stdout.contains(\"Executed 1 test\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testExtensions(_ buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(\"Windows builds encounter long path handling issues\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Extensions\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, buildSystem: buildSystem)\n                // in \"swift test\" build output goes to stderr\n                #expect(stderr.contains(\"Build complete!\"))\n                // in \"swift test\" test output goes to stdout\n                let delimiter: String\n                #if os(macOS)\n                delimiter = \" \"\n                #else\n                delimiter = \".\"\n                #endif\n                #expect(stdout.contains(\"SimpleTests1\\(delimiter)testExample1\"))\n                #expect(stdout.contains(\"SimpleTests1\\(delimiter)testExample1_a\"))\n                #expect(stdout.contains(\"SimpleTests2\\(delimiter)testExample2\"))\n                #expect(stdout.contains(\"SimpleTests2\\(delimiter)testExample2_a\"))\n                #expect(stdout.contains(\"SimpleTests4\\(delimiter)testExample\"))\n                #expect(stdout.contains(\"SimpleTests4\\(delimiter)testExample1\"))\n                #expect(stdout.contains(\"SimpleTests4\\(delimiter)testExample2\"))\n                #expect(stdout.contains(\"Executed 7 tests\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func deprecatedTests(_ buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(\"Windows builds encounter long path handling issues\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Deprecation\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, buildSystem: buildSystem)\n                // in \"swift test\" test output goes to stdout\n                #expect(stdout.contains(\"Executed 2 tests\"))\n                #expect(!stderr.contains(\"is deprecated\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Command.Test,\n        ),\n        .tags(\n            .Feature.CommandLineArguments.BuildSystem,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSubclassedTestClassTests(_ buildSystem: BuildSystemProvider.Kind) async throws {\n        try await withKnownIssue(\"Windows builds encounter long path handling issues\", isIntermittent: true) {\n            try await fixture(name: \"Miscellaneous/TestDiscovery/Subclass\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftTest(fixturePath, buildSystem: buildSystem)\n                // in \"swift test\" build output goes to stderr\n                #expect(stderr.contains(\"Build complete!\"))\n                // in \"swift test\" test output goes to stdout\n                let delimiter: String\n                #if os(macOS)\n                delimiter = \" \"\n                #else\n                delimiter = \".\"\n                #endif\n                #expect(stdout.contains(\"Tests3\\(delimiter)test11\"))\n                #expect(stdout.contains(\"->Module1::Tests1::test11\"))\n                #expect(stdout.contains(\"Tests3\\(delimiter)test12\"))\n                #expect(stdout.contains(\"->Module1::Tests1::test12\"))\n                #expect(stdout.contains(\"Tests3\\(delimiter)test13\"))\n                #expect(stdout.contains(\"->Module1::Tests1::test13\"))\n                #expect(stdout.contains(\"Tests3\\(delimiter)test21\"))\n                #expect(stdout.contains(\"->Module1::Tests2::test21\"))\n                #expect(stdout.contains(\"Tests3\\(delimiter)test22\"))\n                #expect(stdout.contains(\"->Module1::Tests2::test22\"))\n                #expect(stdout.contains(\"Tests3\\(delimiter)test31\"))\n                #expect(stdout.contains(\"->Module1::Tests3::test31\"))\n                #expect(stdout.contains(\"Tests3\\(delimiter)test32\"))\n                #expect(stdout.contains(\"->Module1::Tests3::test32\"))\n                #expect(stdout.contains(\"Tests3\\(delimiter)test33\"))\n                #expect(stdout.contains(\"->Module1::Tests3::test33\"))\n\n                #expect(stdout.contains(\"->Module2::Tests1::test11\"))\n                #expect(stdout.contains(\"->Module2::Tests1::test12\"))\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/ToolsVersionTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport Commands\nimport PackageModel\nimport SourceControl\nimport Workspace\nimport struct SPMBuildCore.BuildSystemProvider\n\nimport _InternalTestSupport\nimport Testing\n\nstruct ToolsVersionTests {\n\n    @Test(\n        .serialized,\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8416\", relationship: .defect),\n        .issue(\"https://github.com/swiftlang/swift-build/issues/609\", relationship: .defect),\n        .tags(\n            .TestSize.large,\n            .Feature.Command.Build,\n            .Feature.Command.Package.ToolsVersion,\n            .Feature.ProductType.Library,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func toolsVersion(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"https://github.com/swiftlang/swift-build/issues/609\", isIntermittent: true) {\n            try await testWithTemporaryDirectory{ path in\n                let fs = localFileSystem\n\n                // Create a repo for the dependency to test against.\n                let depPath = path.appending(\"Dep\")\n                try fs.createDirectory(depPath)\n                initGitRepo(depPath)\n                let repo = GitRepository(path: depPath)\n\n                try fs.writeFileContents(\n                    depPath.appending(\"Package.swift\"),\n                    string: \"\"\"\n                        // swift-tools-version:5.0\n                        import PackageDescription\n                        let package = Package(\n                            name: \"Dep\",\n                            products: [\n                                .library(name: \"Dep\", targets: [\"Dep\"]),\n                            ],\n                            targets: [\n                                .target(name: \"Dep\", path: \"./\")\n                            ]\n                        )\n                        \"\"\"\n                )\n                try fs.writeFileContents(\n                    depPath.appending(\"foo.swift\"),\n                    string: #\"public func foo() { print(\"foo@1.0\") }\"#\n                )\n                // v1.\n                try repo.stageEverything()\n                try repo.commit(message: \"Initial\")\n                try repo.tag(name: \"1.0.0\")\n\n                // v1.0.1\n                _ = try await executeSwiftPackage(\n                    depPath,\n                    configuration: configuration,\n                    extraArgs: [\"tools-version\", \"--set\", \"10000.1\"],\n                    buildSystem: buildSystem,\n                )\n                try fs.writeFileContents(\n                    depPath.appending(\"foo.swift\"),\n                    string: #\"public func foo() { print(\"foo@1.0.1\") }\"#\n                )\n                try repo.stageEverything()\n                try repo.commit(message: \"1.0.1\")\n                try repo.tag(name: \"1.0.1\")\n\n                // Create the primary repository.\n                let primaryPath = path.appending(\"Primary\")\n                try fs.createDirectory(primaryPath, recursive: true)\n                try fs.writeFileContents(\n                    primaryPath.appending(\"Package.swift\"),\n                    string: \"\"\"\n                        import PackageDescription\n                        let package = Package(\n                            name: \"Primary\",\n                            dependencies: [.package(url: \"../Dep\", from: \"1.0.0\")],\n                            targets: [.target(name: \"Primary\", dependencies: [\"Dep\"], path: \".\")]\n                        )\n                        \"\"\"\n                )\n                // Create a file.\n                try fs.writeFileContents(\n                    primaryPath.appending(\"main.swift\"),\n                    string: \"\"\"\n                        import Dep\n                        Dep.foo()\n                        \"\"\"\n                )\n                _ = try await executeSwiftPackage(\n                    primaryPath,\n                    configuration: configuration,\n                    extraArgs: [\"tools-version\", \"--set\", \"4.2\"],\n                    buildSystem: buildSystem,\n                ).stdout.spm_chomp()\n\n                // Build the primary package.\n                _ = try await executeSwiftBuild(\n                    primaryPath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let binPath = try primaryPath.appending(components: buildSystem.binPath(for: configuration))\n                let exe: String = binPath.appending(components: \"Primary\").pathString\n                // v1 should get selected because v1.0.1 depends on a (way) higher set of tools.\n                let executableActualOutput = try await AsyncProcess.checkNonZeroExit(args: exe).spm_chomp()\n                #expect(executableActualOutput == \"foo@1.0\")\n\n\n                // Set the tools version to something high.\n                _ = try await executeSwiftPackage(\n                    primaryPath,\n                    configuration: configuration,\n                    extraArgs: [\"tools-version\", \"--set\", \"10000.1\"],\n                    buildSystem: buildSystem,\n                )\n\n                await expectThrowsCommandExecutionError(\n                    try await executeSwiftBuild(\n                        primaryPath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(error.stderr.contains(\"is using Swift tools version 10000.1.0 but the installed version is \\(ToolsVersion.current)\"), \"stderr: '\\(error.stderr)'\")\n                }\n\n                // Write the manifest with incompatible sources.\n                try fs.writeFileContents(\n                    primaryPath.appending(\"Package.swift\"),\n                    string: \"\"\"\n                        import PackageDescription\n                        let package = Package(\n                            name: \"Primary\",\n                            dependencies: [.package(url: \"../Dep\", from: \"1.0.0\")],\n                            targets: [.target(name: \"Primary\", dependencies: [\"Dep\"], path: \".\")],\n                            swiftLanguageVersions: [.version(\"1000\")])\n                        \"\"\"\n                )\n                _ = try await executeSwiftPackage(\n                    primaryPath,\n                    configuration: configuration,\n                    extraArgs: [\"tools-version\", \"--set\", \"4.2\"],\n                    buildSystem: buildSystem,\n                ).stdout.spm_chomp()\n\n                await expectThrowsCommandExecutionError(\n                    try await executeSwiftBuild(\n                        primaryPath,\n                        configuration: configuration,\n                        buildSystem: buildSystem,\n                    )\n                ) { error in\n                    #expect(error.stderr.contains(\"package 'primary' requires minimum Swift language version 1000 which is not supported by the current tools version (\\(ToolsVersion.current))\"), \"stderr: '\\(error.stderr)'\")\n                }\n\n                try fs.writeFileContents(\n                    primaryPath.appending(\"Package.swift\"),\n                    string: \"\"\"\n                        import PackageDescription\n                        let package = Package(\n                            name: \"Primary\",\n                            dependencies: [.package(url: \"../Dep\", from: \"1.0.0\")],\n                            targets: [.target(name: \"Primary\", dependencies: [\"Dep\"], path: \".\")],\n                            swiftLanguageVersions: [.version(\"\\(ToolsVersion.current.major)\"), .version(\"1000\")])\n                        \"\"\"\n                )\n                _ = try await executeSwiftPackage(\n                    primaryPath,\n                    configuration: configuration,\n                    extraArgs: [\"tools-version\", \"--set\", \"4.2\"],\n                    buildSystem: buildSystem,\n                ).stdout.spm_chomp()\n                _ = try await executeSwiftBuild(\n                    primaryPath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/TraitTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport DriverSupport\nimport PackageModel\nimport struct TSCBasic.ByteString\nimport enum TSCBasic.JSON\nimport struct SPMBuildCore.BuildSystemProvider\nimport Testing\nimport _InternalTestSupport\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .TestSize.large,\n        .Feature.Traits,\n    ),\n)\nstruct TraitTests {\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_whenNoFlagPassed(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftRun(\n                fixturePath.appending(\"Example\"),\n                \"Example\",\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            // We expect no warnings to be produced. Specifically no unused dependency warnings.\n            let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n            #expect(!stderr.contains(unusedDependencyRegex))\n            #expect(stdout == \"\"\"\n            Package1Library1 trait1 enabled\n            Package2Library1 trait2 enabled\n            Package3Library1 trait3 enabled\n            Package4Library1 trait1 disabled\n            DEFINE1 enabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\")\n        }\n        } when: {\n           (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_whenTraitUnification(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\n            \"\"\"\n            Windows: \"https://github.com/swiftlang/swift-build/issues/609\"\n            \"\"\",\n            isIntermittent: true,\n        ) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftRun(\n                fixturePath.appending(\"Example\"),\n                \"Example\",\n                configuration: configuration,\n                extraArgs: [\"--traits\", \"default,Package9,Package10\"],\n                buildSystem: buildSystem,\n            )\n            // We expect no warnings to be produced. Specifically no unused dependency warnings.\n            let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n            #expect(!stderr.contains(unusedDependencyRegex))\n            #expect(stdout == \"\"\"\n            Package1Library1 trait1 enabled\n            Package2Library1 trait2 enabled\n            Package3Library1 trait3 enabled\n            Package4Library1 trait1 disabled\n            Package10Library1 trait1 enabled\n            Package10Library1 trait2 enabled\n            Package10Library1 trait1 enabled\n            Package10Library1 trait2 enabled\n            Package10Library2 has been included.\n            DEFINE1 enabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\")\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_whenTraitUnification_whenSecondTraitNotEnabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\n            \"\"\"\n            Windows: https://github.com/swiftlang/swift-build/issues/609\n            \"\"\",\n            isIntermittent: true,\n        ) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftRun(\n                fixturePath.appending(\"Example\"),\n                \"Example\",\n                configuration: configuration,\n                extraArgs: [\"--traits\", \"default,Package9\"],\n                buildSystem: buildSystem,\n            )\n            // We expect no warnings to be produced. Specifically no unused dependency warnings.\n            let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n            #expect(!stderr.contains(unusedDependencyRegex))\n            #expect(stdout == \"\"\"\n            Package1Library1 trait1 enabled\n            Package2Library1 trait2 enabled\n            Package3Library1 trait3 enabled\n            Package4Library1 trait1 disabled\n            Package10Library1 trait1 enabled\n            Package10Library1 trait2 enabled\n            DEFINE1 enabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\")\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_whenIndividualTraitsEnabled_andDefaultTraits(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\n            \"\"\"\n            Windows: https://github.com/swiftlang/swift-build/issues/609\n            \"\"\",\n            isIntermittent: true,\n        ) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftRun(\n                fixturePath.appending(\"Example\"),\n                \"Example\",\n                configuration: configuration,\n                extraArgs: [\n                    \"--traits\",\n                    \"default,Package5,Package7,BuildCondition3\",\n                ],\n                buildSystem: buildSystem,\n            )\n            // We expect no warnings to be produced. Specifically no unused dependency warnings.\n            let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n            #expect(!stderr.contains(unusedDependencyRegex))\n            #expect(stdout == \"\"\"\n            Package1Library1 trait1 enabled\n            Package2Library1 trait2 enabled\n            Package3Library1 trait3 enabled\n            Package4Library1 trait1 disabled\n            Package5Library1 trait1 enabled\n            Package6Library1 trait1 enabled\n            Package7Library1 trait1 disabled\n            DEFINE1 enabled\n            DEFINE2 disabled\n            DEFINE3 enabled\n\n            \"\"\")\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_whenDefaultTraitsDisabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftRun(\n                fixturePath.appending(\"Example\"),\n                \"Example\",\n                configuration: configuration,\n                extraArgs: [\"--disable-default-traits\"],\n                buildSystem: buildSystem,\n            )\n            // We expect no warnings to be produced. Specifically no unused dependency warnings.\n            let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n            #expect(!stderr.contains(unusedDependencyRegex))\n            #expect(stdout == \"\"\"\n            DEFINE1 disabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\")\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_whenIndividualTraitsEnabled_andDefaultTraitsDisabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\"\"\"\n            Windows: https://github.com/swiftlang/swift-build/issues/609\n            \"\"\",\n            isIntermittent: true,\n        ) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftRun(\n                fixturePath.appending(\"Example\"),\n                \"Example\",\n                configuration: configuration,\n                extraArgs: [\"--traits\", \"Package5,Package7\"],\n                buildSystem: buildSystem,\n            )\n            // We expect no warnings to be produced. Specifically no unused dependency warnings.\n            let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n            #expect(!stderr.contains(unusedDependencyRegex))\n            #expect(stdout == \"\"\"\n            Package5Library1 trait1 enabled\n            Package6Library1 trait1 enabled\n            Package7Library1 trait1 disabled\n            DEFINE1 disabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\")\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_whenAllTraitsEnabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\n            \"\"\"\n            Windows: https://github.com/swiftlang/swift-build/issues/609\n            \"\"\",\n            isIntermittent: true,\n        ) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftRun(\n                fixturePath.appending(\"Example\"),\n                \"Example\",\n                configuration: configuration,\n                extraArgs: [\"--enable-all-traits\"],\n                buildSystem: buildSystem,\n            )\n            // We expect no warnings to be produced. Specifically no unused dependency warnings.\n            let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n            #expect(!stderr.contains(unusedDependencyRegex))\n            #expect(stdout == \"\"\"\n            Package1Library1 trait1 enabled\n            Package2Library1 trait2 enabled\n            Package3Library1 trait3 enabled\n            Package4Library1 trait1 disabled\n            Package5Library1 trait1 enabled\n            Package6Library1 trait1 enabled\n            Package7Library1 trait1 disabled\n            Package10Library1 trait1 enabled\n            Package10Library1 trait2 enabled\n            Package10Library1 trait1 enabled\n            Package10Library1 trait2 enabled\n            Package10Library2 has been included.\n            Package10Library2 has been included.\n            DEFINE1 enabled\n            DEFINE2 enabled\n            DEFINE3 enabled\n\n            \"\"\")\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_whenAllTraitsEnabled_andDefaultTraitsDisabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\n            \"\"\"\n            Windows: https://github.com/swiftlang/swift-build/issues/609\n            \"\"\",\n            isIntermittent: true\n        ) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, stderr) = try await executeSwiftRun(\n                fixturePath.appending(\"Example\"),\n                \"Example\",\n                configuration: configuration,\n                extraArgs: [\n                    \"--enable-all-traits\",\n                    \"--disable-default-traits\",\n                ],\n                buildSystem: buildSystem,\n            )\n            // We expect no warnings to be produced. Specifically no unused dependency warnings.\n            let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n            #expect(!stderr.contains(unusedDependencyRegex))\n            #expect(stdout == \"\"\"\n            Package1Library1 trait1 enabled\n            Package2Library1 trait2 enabled\n            Package3Library1 trait3 enabled\n            Package4Library1 trait1 disabled\n            Package5Library1 trait1 enabled\n            Package6Library1 trait1 enabled\n            Package7Library1 trait1 disabled\n            Package10Library1 trait1 enabled\n            Package10Library1 trait2 enabled\n            Package10Library1 trait1 enabled\n            Package10Library1 trait2 enabled\n            Package10Library2 has been included.\n            Package10Library2 has been included.\n            DEFINE1 enabled\n            DEFINE2 enabled\n            DEFINE3 enabled\n\n            \"\"\")\n        }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.DumpPackage,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func traits_dumpPackage(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Traits\") { fixturePath in\n            let packageRoot = fixturePath.appending(\"Example\")\n            let (dumpOutput, _) = try await executeSwiftPackage(\n                packageRoot,\n                configuration: configuration,\n                extraArgs: [\"dump-package\"],\n                buildSystem: buildSystem,\n            )\n            let json = try JSON(bytes: ByteString(encodingAsUTF8: dumpOutput))\n            guard case .dictionary(let contents) = json else { Issue.record(\"unexpected result\"); return }\n            guard case .array(let traits)? = contents[\"traits\"] else { Issue.record(\"unexpected result\"); return }\n            #expect(traits.count == 13)\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .IssueWindowsRelativePathAssert,\n        .tags(\n            Tag.Feature.Command.Test,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func tests_whenNoFlagPassed(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n        try await fixture(name: \"Traits\") { fixturePath in\n            let (stdout, _) = try await executeSwiftTest(\n                fixturePath.appending(\"Example\"),\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n            let expectedOut = \"\"\"\n            Package1Library1 trait1 enabled\n            Package2Library1 trait2 enabled\n            Package3Library1 trait3 enabled\n            Package4Library1 trait1 disabled\n            DEFINE1 enabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\"\n            #expect(stdout.contains(expectedOut))\n        }\n        } when: {\n            (buildSystem == .swiftbuild && [.windows].contains(ProcessInfo.hostOperatingSystem))\n        }\n    }\n\n    @Test(\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Test,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func tests_whenAllTraitsEnabled_andDefaultTraitsDisabled(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(\n            \"\"\"\n            Windows: \"https://github.com/swiftlang/swift-build/issues/609\"\n            \"\"\",\n            isIntermittent: true,\n        ) {\n            try await fixture(name: \"Traits\") { fixturePath in\n                let (stdout, stderr) = try await executeSwiftTest(\n                    fixturePath.appending(\"Example\"),\n                    configuration: configuration,\n                    extraArgs: [\n                        \"--enable-all-traits\",\n                        \"--disable-default-traits\",\n                    ],\n                    buildSystem: buildSystem,\n                )\n                let expectedOut = \"\"\"\n                Package1Library1 trait1 enabled\n                Package2Library1 trait2 enabled\n                Package3Library1 trait3 enabled\n                Package4Library1 trait1 disabled\n                Package5Library1 trait1 enabled\n                Package6Library1 trait1 enabled\n                Package7Library1 trait1 disabled\n                Package10Library1 trait1 enabled\n                Package10Library1 trait2 enabled\n                Package10Library1 trait1 enabled\n                Package10Library1 trait2 enabled\n                DEFINE1 enabled\n                DEFINE2 enabled\n                DEFINE3 enabled\n\n                \"\"\"\n                #expect(stdout.contains(expectedOut), \"got stdout: '\\(stdout)'\\nstderr: '\\(stderr)'\")\n            }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.DumpSymbolGraph,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageDumpSymbolGraph_enablesAllTraits(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Traits\") { fixturePath in\n                let (stdout, _) = try await executeSwiftPackage(\n                    fixturePath.appending(\"Package10\"),\n                    configuration: configuration,\n                    extraArgs: [\"dump-symbol-graph\"],\n                    buildSystem: buildSystem,\n                )\n                let optionalPath = stdout\n                    .lazy\n                    .split(whereSeparator: \\.isNewline)\n                    .first { String($0).hasPrefix(\"Files written to \") }?\n                    .dropFirst(17)\n\n                let path = try String(#require(optionalPath))\n                let symbolGraph = try String(contentsOfFile: \"\\(path)/Package10Library1.symbols.json\", encoding: .utf8)\n                #expect(symbolGraph.contains(\"TypeGatedByPackage10Trait1\"))\n                #expect(symbolGraph.contains(\"TypeGatedByPackage10Trait2\"))\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test(\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Package.Plugin,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packagePluginGetSymbolGraph_enablesAllTraits(\n        buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n            try await fixture(name: \"Traits\") { fixturePath in\n                // The swiftbuild build system doesn't yet have the ability for command plugins to request symbol graphs\n                try await withKnownIssue(\n                    \"https://github.com/swiftlang/swift-build/issues/609\",\n                    isIntermittent: true,\n                ) {\n                    let (stdout, _) = try await executeSwiftPackage(\n                        fixturePath.appending(\"Package10\"),\n                        configuration: configuration,\n                        extraArgs: [\"plugin\", \"extract\"],\n                        buildSystem: buildSystem,\n                    )\n                    let path = String(stdout.split(whereSeparator: \\.isNewline).first!)\n                    let symbolGraph = try String(contentsOfFile: \"\\(path)/Package10Library1.symbols.json\", encoding: .utf8)\n                    #expect(symbolGraph.contains(\"TypeGatedByPackage10Trait1\"))\n                    #expect(symbolGraph.contains(\"TypeGatedByPackage10Trait2\"))\n                } when: {\n                    buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows\n                }\n            }\n        } when: {\n            let shouldSkip = !CiEnvironment.runningInSmokeTestPipeline\n\n            #if compiler(>=6.3)\n                return shouldSkip\n            #else\n                // Symbol graph generation options are only available in 6.3 toolchain or later for swift build\n                return shouldSkip || buildSystem == .swiftbuild\n            #endif\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageDisablingDefaultsTrait_whenNoTraits(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await fixture(name: \"Traits\") { fixturePath in\n            let error = await #expect(throws: SwiftPMError.self) {\n                try await executeSwiftRun(\n                fixturePath.appending(\"DisablingEmptyDefaultsExample\"),\n                    \"DisablingEmptyDefaultsExample\",\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n\n            guard case SwiftPMError.executionFailure(_, _, let stderr) = try #require(error) else {\n                Issue.record(\"Incorrect error was raised.\")\n                return\n            }\n\n            let expectedErr = \"\"\"\n                error: Disabled default traits by package 'disablingemptydefaultsexample' (DisablingEmptyDefaultsExample) on package 'package11' (Package11) that declares no traits. This is prohibited to allow packages to adopt traits initially without causing an API break.\n\n                \"\"\"\n            #expect(stderr.contains(expectedErr))\n        }\n    }\n\n    @Test(\n        .IssueProductTypeForObjectLibraries,\n        .tags(\n            Tag.Feature.Command.Run,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n        getTraitCombinations(\n            (\"ExtraTrait\",\n            \"\"\"\n            Package10Library2 has been included.\n            DEFINE1 disabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\"\n            ),\n            (\"Package10\",\n            \"\"\"\n            Package10Library1 trait1 disabled\n            Package10Library1 trait2 enabled\n            Package10Library2 has been included.\n            DEFINE1 disabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\"\n            ),\n            (\"ExtraTrait,Package10\",\n            \"\"\"\n            Package10Library1 trait1 disabled\n            Package10Library1 trait2 enabled\n            Package10Library2 has been included.\n            Package10Library2 has been included.\n            DEFINE1 disabled\n            DEFINE2 disabled\n            DEFINE3 disabled\n\n            \"\"\"\n            )\n        )\n    )\n    func traits_whenManyTraitsEnableTargetDependency(\n        buildSystem: BuildSystemProvider.Kind,\n        traits: TraitArgumentData\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(\n            \"\"\"\n            Windows: https://github.com/swiftlang/swift-build/issues/609\n            \"\"\",\n            isIntermittent: true,\n        ) {\n            try await fixture(name: \"Traits\") { fixturePath in\n                // We expect no warnings to be produced. Specifically no unused dependency warnings.\n                let unusedDependencyRegex = try Regex(\"warning: '.*': dependency '.*' is not used by any target\")\n\n                let (stdout, stderr) = try await executeSwiftRun(\n                    fixturePath.appending(\"Example\"),\n                    \"Example\",\n                    configuration: config,\n                    extraArgs: [\"--traits\", traits.traitsArgument],\n                    buildSystem: buildSystem,\n                )\n                #expect(!stderr.contains(unusedDependencyRegex))\n                #expect(stdout == traits.expectedOutput)\n            }\n        } when: {\n            (ProcessInfo.hostOperatingSystem == .windows && (CiEnvironment.runningInSmokeTestPipeline || buildSystem == .swiftbuild))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/FunctionalTests/VersionSpecificTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport SourceControl\nimport _InternalTestSupport\nimport Testing\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum PackageModel.BuildConfiguration\n\n@Suite(\n    .serializedIfOnWindows,\n    .tags(\n        .TestSize.large,\n    ),\n)\nstruct VersionSpecificTests {\n    /// Functional tests of end-to-end support for version specific dependency resolution.\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-tools-support-core/pull/521\", relationship: .fixedBy), // long file path issue\n        .tags(\n            .Feature.Command.Build,\n            .Feature.Command.Package.Reset,\n            .Feature.Version,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func endToEndResolution(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let configuration = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) { // Test passed on Windows at-desk\n        try await testWithTemporaryDirectory{ path in\n            let fs = localFileSystem\n\n            // Create a repo for the dependency to test against.\n            let depPath = path.appending(\"Dep\")\n            try fs.createDirectory(depPath)\n            initGitRepo(depPath)\n            let repo = GitRepository(path: depPath)\n\n            // Create the initial commit.\n            try fs.writeFileContents(\n                depPath.appending(\"Package.swift\"),\n                string: \"\"\"\n                    // swift-tools-version:4.2\n                    import PackageDescription\n                    let package = Package(\n                        name: \"Dep\",\n                        products: [\n                            .library(name: \"Dep\", targets: [\"Dep\"]),\n                        ],\n                        targets: [\n                            .target(name: \"Dep\", path: \"./\")\n                        ]\n                    )\n                    \"\"\"\n            )\n            try repo.stage(file: \"Package.swift\")\n            try repo.commit(message: \"Initial\")\n            try repo.tag(name: \"1.0.0\")\n\n            // Create the version to test against.\n            try fs.writeFileContents(\n                depPath.appending(\"Package.swift\"),\n                // FIXME: We end up filtering this manifest if it has an invalid\n                // tools version as they're assumed to be v3 manifests. Should we\n                // do something better?\n                string: \"\"\"\n                // swift-tools-version:4.2\n                NOT_A_VALID_PACKAGE\n                \"\"\"\n            )\n            try fs.writeFileContents(\n                depPath.appending(\"foo.swift\"),\n                string: \"\"\"\n                    public func foo() { print(\"foo\\\\n\") }\n                    \"\"\"\n            )\n            try repo.stage(file: \"Package.swift\")\n            try repo.stage(file: \"foo.swift\")\n            try repo.commit(message: \"Bogus v1.1.0\")\n            try repo.tag(name: \"1.1.0\")\n\n            // Create the primary repository.\n            let primaryPath = path.appending(\"Primary\")\n            try fs.createDirectory(primaryPath, recursive: true)\n            try fs.writeFileContents(\n                primaryPath.appending(\"Package.swift\"),\n                string: \"\"\"\n                    // swift-tools-version:4.2\n                    import PackageDescription\n                    let package = Package(\n                        name: \"Primary\",\n                        dependencies: [\n                            .package(url: \"../Dep\", from: \"1.0.0\"),\n                        ],\n                        targets: [\n                            .target(name: \"Primary\", dependencies: [\"Dep\"], path: \"./\")\n                        ]\n                    )\n                    \"\"\"\n            )\n            // This build should fail, because of the invalid package.\n            await #expect(throws: (any Error).self) {\n                try await executeSwiftBuild(\n                    primaryPath,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n\n            // Create a file which requires a version 1.1.0 resolution.\n            try fs.writeFileContents(\n                primaryPath.appending(\"main.swift\"),\n                string: \"\"\"\n                    import Dep\n                    Dep.foo()\n                    \"\"\"\n            )\n\n            // Create a version-specific tag, which should work.\n            try fs.writeFileContents(\n                depPath.appending(\"Package.swift\"),\n                string: \"\"\"\n                    // swift-tools-version:4.2\n                    import PackageDescription\n                    let package = Package(\n                        name: \"Dep\",\n                        products: [\n                            .library(name: \"Dep\", targets: [\"Dep\"]),\n                        ],\n                        targets: [\n                            .target(name: \"Dep\", path: \"./\")\n                        ]\n                    )\n                    \"\"\"\n            )\n            try repo.stage(file: \"Package.swift\")\n            try repo.commit(message: \"OK v1.1.0\")\n            try repo.tag(name: \"1.1.0@swift-\\(SwiftVersion.current.major)\")\n\n            // The build should work now.\n            _ = try await executeSwiftPackage(\n                primaryPath,\n                configuration: configuration,\n                extraArgs: [\"reset\"],\n                buildSystem: buildSystem,\n            )\n            try await executeSwiftBuild(\n                primaryPath,\n                configuration: configuration,\n                buildSystem: buildSystem,\n            )\n        }\n        } when: {\n            buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows && CiEnvironment.runningInSelfHostedPipeline\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/IntegrationTests/BasicTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport _IntegrationTestSupport\nimport _InternalTestSupport\nimport Testing\nimport struct TSCBasic.ByteString\nimport struct SPMBuildCore.BuildSystemProvider\nimport enum PackageModel.BuildConfiguration\nimport Basics\n@Suite(\n    .tags(Tag.TestSize.large)\n)\nprivate struct BasicTests {\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/8409\", relationship: .defect),\n        .requireUnrestrictedNetworkAccess(\"Test requires access to https://github.com\"),\n        .tags(\n            Tag.UserWorkflow,\n            Tag.Feature.Command.Build,\n        ),\n    )\n    func testExamplePackageDealer() async throws {\n        try await withTemporaryDirectory { tempDir in\n            let packagePath = tempDir.appending(component: \"dealer\")\n            let repoToClone = \"https://github.com/swiftlang/example-package-dealer\"\n            withKnownIssue(isIntermittent: true) {\n                // marking as withKnownIssue(intermittent: true) as git operation can fail.\n\n                #if os(macOS)\n                    // On macOS, we add the HOME variable to avoid git errors.\n                    try sh(\"git\\(ProcessInfo.exeSuffix)\", \"clone\", repoToClone, packagePath, env: [\"HOME\": tempDir.pathString])\n                #else\n                    try sh(\"git\\(ProcessInfo.exeSuffix)\", \"clone\", repoToClone, packagePath)\n                #endif\n            }\n\n            // Do not run the test when the git clone operation failed\n            if !FileManager.default.fileExists(atPath: packagePath.pathString) {\n                //TODO: use Test Cancellation when available\n                //https://forums.swift.org/t/pitch-test-cancellation/81847/18\n                #if compiler(>=6.3)\n                    Issue.record(\"Can't clone the repository \\(repoToClone), abording the test.\", severity: .warning)\n                #endif\n                return\n            }\n\n            let build1Output = try await executeSwiftBuild(\n                packagePath,\n                buildSystem: .native,\n            ).stdout\n\n            // Check the build log.\n            #expect(build1Output.contains(\"Build complete\"))\n\n            // Verify that the app works.\n            let dealerOutput = try sh(\n                AbsolutePath(validating: \".build/debug/dealer\", relativeTo: packagePath), \"10\"\n            ).stdout\n            #expect(dealerOutput.filter(\\.isPlayingCardSuit).count == 10)\n\n            // Verify that the 'git status' is clean after a build.\n            let gitOutput = try sh(\"git\\(ProcessInfo.exeSuffix)\", \"-C\", packagePath, \"status\").stdout\n            #expect(gitOutput.contains(\"nothing to commit, working tree clean\"))\n\n            // Verify that another 'swift build' does nothing.\n            let build2Output = try await executeSwiftBuild(\n                packagePath,\n                buildSystem: .native,\n            ).stdout\n            #expect(build2Output.contains(\"Build complete\"))\n\n            // Check that no compilation happened (except for plugins which are allowed)\n            // catch \"Compiling xxx\" but ignore \"Compiling plugin\" messages\n            let compilingRegex = try Regex(\"Compiling (?!plugin)\")\n            #expect(build2Output.contains(compilingRegex) == false)\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Build,\n        ),\n    )\n    func testSwiftBuild() async throws {\n        try await withTemporaryDirectory { tempDir in\n            let packagePath = tempDir.appending(component: \"tool\")\n            try localFileSystem.createDirectory(packagePath)\n            try localFileSystem.writeFileContents(\n                packagePath.appending(component: \"Package.swift\"),\n                bytes: ByteString(\n                    encodingAsUTF8: \"\"\"\n                    // swift-tools-version:4.2\n                    import PackageDescription\n\n                    let package = Package(\n                        name: \"tool\",\n                        targets: [\n                            .target(name: \"tool\", path: \"./\"),\n                        ]\n                    )\n                    \"\"\"\n                )\n            )\n            try localFileSystem.writeFileContents(\n                packagePath.appending(component: \"main.swift\"),\n                bytes: ByteString(encodingAsUTF8: #\"print(\"HI\")\"#)\n            )\n\n            // Check the build.\n            let buildOutput = try await executeSwiftBuild(\n                packagePath,\n                extraArgs: [\"-v\"],\n                buildSystem: .native,\n            ).stdout\n            #expect(try #/swiftc.* -module-name tool/#.firstMatch(in: buildOutput) != nil)\n\n            // Verify that the tool exists and works.\n            let toolOutput = try sh(packagePath.appending(components: \".build\", \"debug\", \"tool\"))\n                .stdout\n            #expect(toolOutput == \"HI\\(ProcessInfo.EOL)\")\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.Init,\n            Tag.Feature.Command.Build,\n            Tag.Feature.PackageType.Executable,\n        ),\n    )\n    func testSwiftPackageInitExec() async throws {\n        try await withTemporaryDirectory { tempDir in\n            // Create a new package with an executable target.\n            let packagePath = tempDir.appending(component: \"Project\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n            extraArgs: [\"init\", \"--type\", \"executable\"],\n                buildSystem: .native,\n            )\n            let packageOutput = try await executeSwiftBuild(\n                packagePath,\n                buildSystem: .native,\n            )\n\n            // Check the build log.\n            let compilingRegex = try Regex(\"Compiling .*Project.*\")\n            let linkingRegex = try Regex(\"Linking .*Project\")\n            #expect(packageOutput.stdout.contains(compilingRegex), \"stdout: '\\(packageOutput.stdout)'\\n stderr:'\\(packageOutput.stderr)'\")\n            #expect(packageOutput.stdout.contains(linkingRegex), \"stdout: '\\(packageOutput.stdout)'\\n stderr:'\\(packageOutput.stderr)'\")\n            #expect(packageOutput.stdout.contains(\"Build complete\"), \"stdout: '\\(packageOutput.stdout)'\\n stderr:'\\(packageOutput.stderr)'\")\n\n            // Verify that the tool was built and works.\n            let toolOutput = try sh(packagePath.appending(components: \".build\", \"debug\", \"Project\"))\n                .stdout\n            #expect(toolOutput.lowercased().contains(\"hello, world!\"))\n\n            // Check there were no compile errors or warnings.\n            #expect(packageOutput.stdout.contains(\"error\") == false)\n            #expect(packageOutput.stdout.contains(\"warning\") == false)\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.Init,\n            Tag.Feature.Command.Test,\n            Tag.Feature.PackageType.Executable,\n            .Feature.CommandLineArguments.VeryVerbose,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSwiftPackageInitLibraryTests(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withTemporaryDirectory { tempDir in\n            // Create a new package with an executable target.\n            let packagePath = tempDir.appending(component: \"Project\")\n            try localFileSystem.createDirectory(packagePath)\n                try await executeSwiftPackage(\n                    packagePath,\n                    configuration: config,\n                    extraArgs: [\"init\", \"--type\", \"library\", \"--enable-xctest\", \"--enable-swift-testing\"],\n                    buildSystem: buildSystem,\n                )\n                let packageOutput = try await executeSwiftTest(\n                    packagePath,\n                    configuration: config,\n                    extraArgs: [\"--vv\"],\n                    buildSystem: buildSystem,\n                )\n\n                // Check the test log.\n                #expect(packageOutput.stdout.contains(\"Executed 1 test\"), \"stdout: '\\(packageOutput.stdout)'\\n\\n\\n stderr:'\\(packageOutput.stderr)'\")\n                #expect(packageOutput.stdout.contains(\"Test run with 1 test\"), \"stdout: '\\(packageOutput.stdout)'\\n\\n\\n stderr:'\\(packageOutput.stderr)'\")\n\n                // Check there were no compile errors or warnings.\n                #expect(!packageOutput.stdout.contains(\"error\"))\n                #expect(!packageOutput.stdout.contains(\"warning\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.Init,\n            Tag.Feature.Command.Build,\n            Tag.Feature.PackageType.Library,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSwiftPackageInitLib(\n        buildSystem: BuildSystemProvider.Kind,\n    ) throws {\n        let config = BuildConfiguration.debug\n        try withTemporaryDirectory { tempDir in\n            // Create a new package with an executable target.\n            let packagePath = tempDir.appending(component: \"Project\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"init\", \"--type\", \"library\"],\n                buildSystem: buildSystem,\n            )\n            let buildOutput = try await executeSwiftBuild(\n                packagePath,\n                configuration: config,\n                buildSystem: buildSystem,\n            ).stdout\n\n            // Check the build log.\n            switch buildSystem {\n                case .native:\n                    #expect(try #/Compiling .*Project.*/#.firstMatch(in: buildOutput) != nil)\n                case .swiftbuild, .xcode:\n                    break\n            }\n            #expect(buildOutput.contains(\"Build complete\"))\n\n            // Check there were no compile errors or warnings.\n            #expect(buildOutput.contains(\"error\") == false)\n            #expect(buildOutput.contains(\"warning\") == false)\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.Init,\n            Tag.Feature.Command.Test,\n            Tag.Feature.PackageType.Library,\n            Tag.Feature.SpecialCharacters,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSwiftPackageLibsTests(\n        buildSystem: BuildSystemProvider.Kind,\n    ) throws {\n        let config = BuildConfiguration.debug\n        try withTemporaryDirectory { tempDir in\n            // Create a new package with an executable target.\n            let packagePath = tempDir.appending(component: \"Project\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"init\", \"--type\", \"library\"],\n                buildSystem: buildSystem,\n            )\n            let output = try await executeSwiftTest(\n                packagePath,\n                configuration: config,\n                buildSystem: buildSystem,\n            )\n\n            // Check there were no compile errors or warnings.\n            #expect(output.stdout.contains(\"error\") == false)\n            #expect(output.stdout.contains(\"warning\") == false)\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Build,\n            Tag.Feature.SpecialCharacters,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSwiftPackageWithSpaces(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withTemporaryDirectory { tempDir in\n            let packagePath = tempDir.appending(components: \"more spaces\", \"special tool\")\n            try localFileSystem.createDirectory(packagePath, recursive: true)\n            try localFileSystem.writeFileContents(\n                packagePath.appending(component: \"Package.swift\"),\n                bytes: ByteString(\n                    encodingAsUTF8: \"\"\"\n                    // swift-tools-version:4.2\n                    import PackageDescription\n\n                    let package = Package(\n                    name: \"special tool\",\n                    targets: [\n                        .target(name: \"special tool\", path: \"./\"),\n                    ]\n                    )\n                    \"\"\"\n                )\n            )\n            try localFileSystem.writeFileContents(\n                packagePath.appending(component: \"main.swift\"),\n                bytes: ByteString(encodingAsUTF8: #\"foo()\"#)\n            )\n            try localFileSystem.writeFileContents(\n                packagePath.appending(component: \"some file.swift\"),\n                bytes: ByteString(encodingAsUTF8: #\"func foo() { print(\"HI\") }\"#)\n            )\n\n            // Check the build.\n            let buildOutput = try await executeSwiftBuild(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"-v\"],\n                buildSystem: buildSystem,\n            ).stdout\n            switch (buildSystem, config) {\n                case (.native, .debug) :\n                    let expression = ProcessInfo\n                        .hostOperatingSystem != .windows ?\n                        #/swiftc.* -module-name special_tool .* '@.*/more spaces/special tool/.build/[^/]+/debug/special_tool.build/sources'/# :\n                        #/swiftc.* -module-name special_tool .* \"@.*\\\\more spaces\\\\special tool\\\\.build\\\\[^\\\\]+\\\\debug\\\\special_tool.build\\\\sources\"/#\n                    #expect(try expression.firstMatch(in: buildOutput) != nil)\n                case (.swiftbuild, _), (.xcode, _), (.native, .release):\n                    break\n            }\n            #expect(buildOutput.contains(\"Build complete\"))\n\n            // Verify that the tool exists and works.\n            let shOutput = try sh(\n                try packagePath.appending(components: buildSystem.binPath(for: config) + [\"special tool\"])\n            ).stdout\n\n            #expect(shOutput == \"HI\\(ProcessInfo.EOL)\")\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Run,\n            Tag.Feature.Command.Package.Init,\n            Tag.Feature.PackageType.Executable,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSwiftRun(\n        buildSystem: BuildSystemProvider.Kind,\n    ) throws {\n        let config = BuildConfiguration.debug\n        try withTemporaryDirectory { tempDir in\n            let packagePath = tempDir.appending(component: \"secho\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"init\", \"--type\", \"executable\"],\n                buildSystem: buildSystem,\n            )\n            // delete any files generated\n            for entry in try localFileSystem.getDirectoryContents(\n                packagePath.appending(components: \"Sources\")\n            ) {\n                try localFileSystem.removeFileTree(\n                    packagePath.appending(components: \"Sources\", entry)\n                )\n            }\n            try localFileSystem.writeFileContents(\n                packagePath.appending(components: \"Sources\", \"secho.swift\"),\n                bytes: ByteString(\n                    encodingAsUTF8: \"\"\"\n                    import Foundation\n                    print(CommandLine.arguments.dropFirst().joined(separator: \" \"))\n                    \"\"\"\n                )\n            )\n            let result = try await executeSwiftRun(\n                packagePath, \"secho\",\n                configuration: config,\n                extraArgs: [ \"1\", #\"\"two\"\"#],\n                buildSystem: buildSystem,\n            )\n\n            // Check the run log.\n            switch buildSystem {\n                case .native:\n                    let compilingRegex = try Regex(\"Compiling .*secho.*\")\n                    let linkingRegex: Regex<AnyRegexOutput> = try Regex(\"Linking .*secho\")\n                    #expect(result.stdout.contains(compilingRegex), \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n                    #expect(result.stdout.contains(linkingRegex),  \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n                case .swiftbuild, .xcode:\n                break\n            }\n            #expect(result.stdout.contains(\"Build of product 'secho' complete\"),  \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n\n            #expect(result.stdout == \"1 \\\"two\\\"\\(ProcessInfo.EOL)\")\n\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Test,\n            Tag.Feature.Command.Package.Init,\n            Tag.Feature.PackageType.Library,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSwiftTest(\n        buildSystem: BuildSystemProvider.Kind,\n    ) throws {\n        let config = BuildConfiguration.debug\n        try withTemporaryDirectory { tempDir in\n            let packagePath = tempDir.appending(component: \"swiftTest\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"init\", \"--type\", \"library\"],\n                buildSystem: buildSystem,\n            )\n            try localFileSystem.writeFileContents(\n                packagePath.appending(components: \"Tests\", \"swiftTestTests\", \"MyTests.swift\"),\n                bytes: ByteString(\n                    encodingAsUTF8: \"\"\"\n                    import XCTest\n\n                    final class MyTests: XCTestCase {\n                        func testFoo() {\n                            XCTAssertTrue(1 == 1)\n                        }\n                        func testBar() {\n                            XCTAssertFalse(1 == 2)\n                        }\n                        func testBaz() { }\n                    }\n                    \"\"\"\n                )\n            )\n            let result = try await executeSwiftTest(\n                packagePath,\n                configuration: config,\n                extraArgs: [\n                    \"--filter\",\n                    \"MyTests.*\",\n                    \"--skip\",\n                    \"testBaz\",\n                    \"--vv\",\n                ],\n                buildSystem: buildSystem,\n            )\n\n            // Check the test log.\n            #expect(result.stdout.contains(\"Test Suite 'MyTests' started\"), \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n            #expect(result.stdout.contains(\"Test Suite 'MyTests' passed\"), \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n            #expect(result.stdout.contains(\"Executed 2 tests, with 0 failures\"), \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Test,\n            Tag.Feature.Resource,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testSwiftTestWithResources(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await fixture(name: \"Miscellaneous/PackageWithResource/\") { packagePath in\n\n            let result = try await executeSwiftTest(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"--filter\", \"MyTests.*\", \"--vv\"],\n                buildSystem: buildSystem,\n            )\n\n            // Check the test log.\n            withKnownIssue(isIntermittent: true) {\n                #expect(result.stdout.contains(\"Test Suite 'MyTests' started\"), \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n                #expect(result.stdout.contains(\"Test Suite 'MyTests' passed\"), \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n                #expect(result.stdout.contains(\"Executed 2 tests, with 0 failures\"), \"stdout: '\\(result.stdout)'\\n stderr:'\\(result.stderr)'\")\n            } when: {\n                [.linux, .windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild // Because the build failed\n            }\n        }\n    }\n}\n\nextension Character {\n    fileprivate var isPlayingCardSuit: Bool {\n        switch self {\n        case \"♠︎\", \"♡\", \"♢\", \"♣︎\":\n            return true\n        default:\n            return false\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/IntegrationTests/SwiftPMTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport _IntegrationTestSupport\nimport _InternalTestSupport\nimport Testing\nimport Basics\nimport enum PackageModel.BuildConfiguration\nimport struct SPMBuildCore.BuildSystemProvider\n\n@Suite(\n    .tags(Tag.TestSize.large)\n)\nprivate struct SwiftPMTests {\n    @Test(.requireHostOS(.macOS), arguments: [BuildSystemProvider.Kind.native, .swiftbuild])\n    func binaryTargets(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await binaryTargetsFixture { fixturePath in\n            do {\n                let runOutput = try await executeSwiftRun(\n                    fixturePath,\n                    \"exe\",\n                    buildSystem: buildSystem,\n                )\n                #expect(!runOutput.stderr.contains(\"error:\"))\n                #expect(\n                    runOutput.stdout == \"\"\"\n                            SwiftFramework()\n                            Library(framework: SwiftFramework.SwiftFramework())\n\n                            \"\"\"\n                )\n            }\n\n            do {\n                let runOutput = try await executeSwiftRun(fixturePath, \"cexe\", buildSystem: buildSystem)\n                #expect(!runOutput.stderr.contains(\"error:\"))\n                #expect(runOutput.stdout.contains(\"<CLibrary: \"))\n            }\n\n            do {\n                let invalidPath = fixturePath.appending(component: \"SwiftFramework.xcframework\")\n\n                await #expect {\n                    try await executeSwiftPackage(\n                        fixturePath,\n                        extraArgs: [\"compute-checksum\", invalidPath.pathString],\n                        buildSystem: .native,\n                    )\n                } throws: { error in\n                    // The order of supported extensions is not ordered, and changes.\n                    //   '...supported extensions are: zip, tar.gz, tar'\n                    //   '...supported extensions are: tar.gz, zip, tar'\n                    // Only check for the start of that string.\n                    // TODO: error.stderr.contains(\"error: unexpected file type; supported extensions are:\")\n                    return true\n                }\n\n                let validPath = fixturePath.appending(component: \"SwiftFramework.zip\")\n                let packageOutput = try await executeSwiftPackage(\n                    fixturePath,\n                    extraArgs: [\"compute-checksum\", validPath.pathString],\n                    buildSystem: .native,\n                )\n                #expect(\n                    packageOutput.stdout.spm_chomp()\n                    == \"d1f202b1bfe04dea30b2bc4038f8059dcd75a5a176f1d81fcaedb6d3597d1158\"\n                )\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.Init,\n            Tag.Feature.PackageType.Executable,\n        ),\n        arguments: SupportedBuildSystemOnPlatform,\n    )\n    func packageInitExecutable(_ buildSystemProvider: BuildSystemProvider.Kind) throws {\n        try withTemporaryDirectory { tmpDir in\n            let packagePath = tmpDir.appending(component: \"foo\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n                extraArgs: [\"init\", \"--type\", \"executable\"],\n                buildSystem: buildSystemProvider,\n            )\n            try await executeSwiftBuild(\n                packagePath,\n                buildSystem: buildSystemProvider,\n            )\n\n            let runOutput = try await executeSwiftRun(\n                packagePath,\n                nil,\n                buildSystem: buildSystemProvider,\n            )\n            #expect(!runOutput.stderr.contains(\"error:\"))\n            #expect(runOutput.stdout.contains(\"Hello, world!\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.Command.Package.Init,\n            Tag.Feature.PackageType.Library,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func packageInitLibrary(_ buildSystemProvider: BuildSystemProvider.Kind) async throws {\n        try await withTemporaryDirectory { tmpDir in\n            let packagePath = tmpDir.appending(component: \"foo\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n                extraArgs: [\"init\", \"--type\", \"library\"],\n                buildSystem: buildSystemProvider,\n            )\n\n            try await executeSwiftBuild(\n                packagePath,\n                buildSystem: buildSystemProvider,\n            )\n            let testOutput = try await executeSwiftTest(\n                packagePath,\n                buildSystem: buildSystemProvider,\n            )\n            // #expect(testOutput.returnCode == .terminated(code: 0))\n            #expect(!testOutput.stderr.contains(\"error:\"))\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        arguments: SupportedBuildSystemOnAllPlatforms,\n    )\n    func testArchCustomization(buildSystem: BuildSystemProvider.Kind) async throws {\n        try await  withTemporaryDirectory { tmpDir in\n            let packagePath = tmpDir.appending(component: \"foo\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n                extraArgs: [\"init\", \"--type\", \"executable\"],\n                buildSystem: buildSystem,\n            )\n            // delete any files generated\n            for entry in try localFileSystem.getDirectoryContents(\n                packagePath.appending(components: \"Sources\")\n            ) {\n                try localFileSystem.removeFileTree(\n                    packagePath.appending(components: \"Sources\", entry)\n                )\n            }\n            try localFileSystem.writeFileContents(\n                AbsolutePath(validating: \"Sources/main.m\", relativeTo: packagePath)\n            ) {\n                $0.send(\"int main() {}\")\n            }\n            let archs = [\"x86_64\", \"arm64\"]\n\n            for arch in archs {\n                try await executeSwiftBuild(\n                    packagePath,\n                    extraArgs: [\"--arch\", arch],\n                    buildSystem: buildSystem,\n                )\n                let fooPath: AbsolutePath\n                switch buildSystem {\n                case .native:\n                    fooPath = try AbsolutePath(\n                        validating: \".build/\\(arch)-apple-macosx/debug/foo\",\n                        relativeTo: packagePath\n                    )\n                case .swiftbuild:\n                    fooPath = try AbsolutePath(\n                        validating: \".build/out/Products/Debug/foo\",\n                        relativeTo: packagePath\n                    )\n                default:\n                    preconditionFailure(\"Unsupported backend: \\(buildSystem)\")\n                }\n                #expect(localFileSystem.exists(fooPath))\n                // Check the product has the expected slice\n                #expect(try sh(\"/usr/bin/file\", fooPath.pathString).stdout.contains(arch))\n            }\n\n            try await executeSwiftBuild(\n                packagePath,\n                extraArgs: archs.flatMap { [\"--arch\", $0] },\n                buildSystem: buildSystem,\n            )\n\n            let fooPath: AbsolutePath\n            let hostArch: String\n            #if arch(x86_64)\n            hostArch = \"x86_64\"\n            #elseif arch(arm64)\n            hostArch = \"arm64\"\n            #else\n            precondition(\"Unsupported platform or host arch for test\")\n            #endif\n            switch buildSystem {\n            case .native:\n                fooPath = try AbsolutePath(\n                    validating: \".build/apple/Products/Debug/foo\", relativeTo: packagePath\n                )\n            case .swiftbuild:\n                fooPath = try AbsolutePath(\n                    validating: \".build/out/Products/Debug/foo\",\n                    relativeTo: packagePath\n                )\n            default:\n                preconditionFailure(\"Unsupported backend: \\(buildSystem)\")\n            }\n            #expect(localFileSystem.exists(fooPath))\n            // Check the product has the expected slices\n            let fileOutput = try sh(\"/usr/bin/file\", fooPath.pathString).stdout\n            for arch in archs {\n                #expect(fileOutput.contains(arch))\n            }\n        }\n    }\n\n    @Test(\n        .requireSwift6_2,\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9588\", relationship: .defect),\n        .tags(\n            .UserWorkflow,\n            .Feature.CodeCoverage,\n            .Feature.Command.Package.Init,\n            .Feature.Command.Package.AddTarget,\n            .Feature.Command.Test,\n            .Feature.PackageType.Empty,\n            .Feature.TargetType.Test,\n        ),\n        arguments: SupportedBuildSystemOnAllPlatforms\n    )\n    func testCodeCoverageMergedAcrossSubprocesses(\n        buildSystem: BuildSystemProvider.Kind,\n    ) async throws {\n        let config = BuildConfiguration.debug\n        try await withKnownIssue(isIntermittent: true) {\n        try await withTemporaryDirectory(removeTreeOnDeinit: false) { tmpDir in\n            let packagePath = tmpDir.appending(component: \"test-package-coverage\")\n            try localFileSystem.createDirectory(packagePath)\n            try await executeSwiftPackage(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"init\", \"--type\", \"empty\"],\n                buildSystem: buildSystem,\n            )\n            try await executeSwiftPackage(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"add-target\", \"--type\", \"test\", \"ReproTests\"],\n                buildSystem: buildSystem,\n            )\n            try localFileSystem.writeFileContents(\n                AbsolutePath(validating: \"Tests/ReproTests/Subject.swift\", relativeTo: packagePath),\n                string: \"\"\"\n                struct Subject {\n                    static func a() { _ = \"a\" }\n                    static func b() { _ = \"b\" }\n                }\n                \"\"\"\n            )\n            try localFileSystem.writeFileContents(\n                AbsolutePath(validating: \"Tests/ReproTests/ReproTests.swift\", relativeTo: packagePath),\n                string: \"\"\"\n                import Testing\n                import class Foundation.ProcessInfo\n                @Suite struct Suite {\n                    @Test func testProfilePathCanary() throws {\n                        let pattern = try #require(ProcessInfo.processInfo.environment[\"LLVM_PROFILE_FILE\"])\n                        #expect(pattern.hasSuffix(\".%p.profraw\"))\n                    }\n                    @Test func testA() async { await #expect(processExitsWith: .success) { Subject.a() } }\n                    @Test func testB() async { await #expect(processExitsWith: .success) { Subject.b() } }\n                }\n                \"\"\"\n            )\n            let expectedCoveragePath = try await getCoveragePath(\n                packagePath,\n                with: BuildData(buildSystem: buildSystem, config: config),\n            )\n\n            try await executeSwiftTest(\n                packagePath,\n                configuration: config,\n                extraArgs: [\"--enable-code-coverage\", \"--disable-xctest\"],\n                buildSystem: buildSystem,\n                throwIfCommandFails: true,\n            )\n            let coveragePath = try AbsolutePath(validating: expectedCoveragePath)\n\n            // Check the coverage path exists.\n            // the CoveragePath file does not exists in Linux platform build\n            expectFileExists(at: coveragePath)\n\n            // This resulting coverage file should be merged JSON, with a schema that valiades against this subset.\n            struct Coverage: Codable {\n                var data: [Entry]\n                struct Entry: Codable {\n                    var files: [File]\n                    struct File: Codable {\n                        var filename: String\n                        var summary: Summary\n                        struct Summary: Codable {\n                            var functions: Functions\n                            struct Functions: Codable {\n                                var count, covered: Int\n                                var percent: Double\n                            }\n                        }\n                    }\n                }\n            }\n            let coverageJSON = try localFileSystem.readFileContents(coveragePath)\n            let coverage = try JSONDecoder().decode(Coverage.self, from: Data(coverageJSON.contents))\n\n            // Check for 100% coverage for Subject.swift, which should happen because the per-PID files got merged.\n            try withKnownIssue(isIntermittent: true) {\n                let data = try #require(coverage.data.first, \"covege JSON = \\(coverage)\")\n                let subjectCoverage = try #require(data.files.first(where: { $0.filename.hasSuffix(\"Subject.swift\") }), \"covege JSON = \\(data.files)\")\n                #expect(subjectCoverage.summary.functions.count == 2)\n                #expect(subjectCoverage.summary.functions.covered == 2)\n                #expect(subjectCoverage.summary.functions.percent == 100)\n\n                // Check the directory with the coverage path contains the profraw files.\n                let coverageDirectory = coveragePath.parentDirectory\n                let coverageDirectoryContents = try localFileSystem.getDirectoryContents(coverageDirectory)\n\n                // SwiftPM uses an LLVM_PROFILE_FILE that ends with \".%p.profraw\", which we validated in the test above.\n                // Let's first check all the files have the expected extension.\n                let profrawFiles = coverageDirectoryContents.filter { $0.hasSuffix(\".profraw\") }\n\n                // Then check that %p expanded as we expected: to something that plausibly looks like a PID.\n                for profrawFile in profrawFiles {\n                    let shouldBePID = try #require(profrawFile.split(separator: \".\").dropLast().last)\n                    #expect(Int(shouldBePID) != nil)\n                }\n\n                // Group the files by binary identifier (have a different prefix, before the per-PID suffix).\n                let groups = Dictionary(grouping: profrawFiles) { path in path.split(separator: \".\").dropLast(2) }.values\n\n                // Check each group has 3 files: one per PID (the above suite has 2 exit tests => 2 forks => 3 PIDs total).\n                for binarySpecificProfrawFiles in groups {\n                    #expect(binarySpecificProfrawFiles.count == 3)\n                }\n            } when: {\n                [.linux, .windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild\n            }\n        }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/IntegrationTests/XCBuildTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\nimport Basics\nimport _IntegrationTestSupport\nimport _InternalTestSupport\nimport Testing\n\n@Suite\nprivate struct XCBuildTests {\n    @Test(.requireHostOS(.macOS))\n    func testExecutableProducts() async throws {\n        try await fixture(name: \"XCBuild/ExecutableProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(fooPath, buildSystem: .xcode)\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"foo\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"bar\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"cbar\")))\n\n            try await executeSwiftBuild(fooPath, configuration: .release, buildSystem: .xcode)\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"foo\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"bar\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"cbar\")))\n        }\n\n        try await fixture(name: \"XCBuild/ExecutableProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--product\",\n                    \"foo\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"foo\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"bar\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"cbar\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--product\",\n                    \"foo\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"foo\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"bar\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"cbar\")))\n        }\n\n        try await fixture(name: \"XCBuild/ExecutableProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--product\",\n                    \"cfoo\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"foo\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"bar\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"cbar\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--product\",\n                    \"cfoo\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"foo\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"bar\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"cbar\")))\n        }\n\n        try await fixture(name: \"XCBuild/ExecutableProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--product\",\n                    \"bar\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"foo\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"bar\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"cbar\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--product\",\n                    \"bar\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"foo\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"bar\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"cbar\")))\n        }\n\n        try await fixture(name: \"XCBuild/ExecutableProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--product\",\n                    \"cbar\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"foo\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"bar\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"cbar\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--product\",\n                    \"cbar\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"foo\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"cfoo\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"bar\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"cbar\")))\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .skip(\n            \"FIXME: /.../XCBuild_TestProducts.551ajO/Foo/.build/apple/Intermediates.noindex/GeneratedModuleMaps/macosx/FooLib.modulemap:2:12: error: header 'FooLib-Swift.h' not found\"\n        )\n    )\n    func testTestProducts() async throws {\n        try await fixture(name: \"XCBuild/TestProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"FooLib.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"FooTests.xctest\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"CFooTests.xctest\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"BarLib.o\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"FooLib.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"FooTests.xctest\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"CFooTests.xctest\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"BarLib.o\")))\n        }\n\n        try await fixture(name: \"XCBuild/TestProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--build-tests\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"FooLib.o\")))\n            #expect(localFileSystem.isDirectory(debugPath.appending(component: \"FooTests.xctest\")))\n            #expect(localFileSystem.isDirectory(debugPath.appending(component: \"CFooTests.xctest\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"BarLib.o\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--build-tests\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"FooLib.o\")))\n            #expect(localFileSystem.isDirectory(releasePath.appending(component: \"FooTests.xctest\")))\n            #expect(localFileSystem.isDirectory(releasePath.appending(component: \"CFooTests.xctest\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"BarLib.o\")))\n        }\n\n        try await fixture(name: \"XCBuild/TestProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--target\",\n                    \"FooTests\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"FooLib.o\")))\n            #expect(localFileSystem.isDirectory(debugPath.appending(component: \"FooTests.xctest\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"CFooTests.xctest\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"BarLib.o\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--target\",\n                    \"FooTests\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"FooLib.o\")))\n            #expect(localFileSystem.isDirectory(releasePath.appending(component: \"FooTests.xctest\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"CFooTests.xctest\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"BarLib.o\")))\n        }\n\n        try await fixture(name: \"XCBuild/TestProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--target\",\n                    \"CFooTests\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"FooLib.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"FooTests.xctest\")))\n            #expect(localFileSystem.isDirectory(debugPath.appending(component: \"CFooTests.xctest\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"BarLib.o\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--target\",\n                    \"CFooTests\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"FooLib.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"FooTests.xctest\")))\n            #expect(localFileSystem.isDirectory(releasePath.appending(component: \"CFooTests.xctest\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"BarLib.o\")))\n        }\n    }\n\n    @Test(.requireHostOS(.macOS))\n    func testLibraryProductsAndTargets() async throws {\n        try await fixture(name: \"XCBuild/Libraries\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"FooLib_Module.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"CFooLib_Module.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"BarLib_Module.o\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"FooLib_Module.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"CFooLib_Module.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"BarLib_Module.o\")))\n        }\n\n        try await fixture(name: \"XCBuild/Libraries\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--target\",\n                    \"FooLib\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"FooLib_Module.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"CFooLib_Module.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"BarLib_Module.o\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--target\",\n                    \"FooLib\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"FooLib_Module.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"CFooLib_Module.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"BarLib_Module.o\")))\n        }\n\n        try await fixture(name: \"XCBuild/Libraries\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--target\",\n                    \"CFooLib\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"FooLib_Module.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"CFooLib_Module.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"BarLib_Module.o\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--target\",\n                    \"CFooLib\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"FooLib_Module.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"CFooLib_Module.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"BarLib_Module.o\")))\n        }\n\n        try await fixture(name: \"XCBuild/Libraries\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--target\",\n                    \"BarLib\",\n                ],\n                buildSystem: .xcode,\n            )\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"FooLib_Module.o\")))\n            #expect(localFileSystem.notExists(debugPath.appending(component: \"CFooLib_Module.o\")))\n            #expect(localFileSystem.exists(debugPath.appending(component: \"BarLib_Module.o\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--target\",\n                    \"BarLib\",\n                ],\n                buildSystem: .xcode,\n            )\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"FooLib_Module.o\")))\n            #expect(localFileSystem.notExists(releasePath.appending(component: \"CFooLib_Module.o\")))\n            #expect(localFileSystem.exists(releasePath.appending(component: \"BarLib_Module.o\")))\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .skip(\n            \"FIXME: ld: warning: ignoring file /../XCBuild_SystemTargets.b38QoO/Inputs/libsys.a, building for macOS-arm64 but attempting to link with file built for unknown-x86_64\\n\\nUndefined symbols for architecture arm64:\\n  \\\"_GetSystemLibName\\\", referenced from:\\n      _main in main.o\\n\\nld: symbol(s) not found for architecture arm64\\n\\nclang: error: linker command failed with exit code 1 (use -v to see invocation)\\n\\nBuild cancelled\\n\"\n        )\n    )\n    func testSystemTargets() async throws {\n        try await fixture(name: \"XCBuild/SystemTargets\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n            let binaryPath = fooPath.appending(components: \".build\", \"apple\", \"Products\")\n            let inputsPath = path.appending(component: \"Inputs\")\n\n            // Because there isn't any one system target that we can depend on for testing purposes, we build our own.\n            let sourcePath = inputsPath.appending(component: \"libsys.c\")\n            let libraryPath = inputsPath.appending(component: \"libsys.a\")\n            try sh(clang, \"-c\", sourcePath, \"-o\", libraryPath)\n\n            // let env = Environment([\"PKG_CONFIG_PATH\": inputsPath.pathString])\n            var env = Environment()\n            env[\"PKG_CONFIG_PATH\"] = inputsPath.pathString\n            try await executeSwiftBuild(\n                fooPath,\n                extraArgs: [\n                    \"--target\",\n                    \"foo\",\n                ],\n                env: env,\n                buildSystem: .xcode,\n            )\n\n            let debugPath = binaryPath.appending(component: \"Debug\")\n            #expect(localFileSystem.exists(debugPath.appending(component: \"foo\")))\n\n            try await executeSwiftBuild(\n                fooPath,\n                configuration: .release,\n                extraArgs: [\n                    \"--target\",\n                    \"foo\",\n                ],\n                env: env,\n                buildSystem: .xcode,\n            )\n\n            let releasePath = binaryPath.appending(component: \"Release\")\n            #expect(localFileSystem.exists(releasePath.appending(component: \"foo\")))\n        }\n    }\n\n    @Test(.skip(\"FIXME: This test randomly succeeds or fails, depending on the order the subtasks are executed in.\"))\n    func testBinaryTargets() async throws {\n        try await binaryTargetsFixture { path in\n            try await executeSwiftBuild(\n                path,\n                configuration: .debug,\n                extraArgs: [\"--target\", \"exe\"],\n                buildSystem: .xcode,\n            )\n        }\n    }\n\n    @Test(\n        .requireHostOS(.macOS),\n        .skipIfXcodeBuilt(),\n        .skip(\"FIXME: swift-test invocations are timing out in Xcode and self-hosted CI\")\n    )\n    func testSwiftTest() async throws {\n        try await fixture(name: \"XCBuild/TestProducts\") { path in\n            let fooPath = path.appending(component: \"Foo\")\n\n            do {\n                let output = try await executeSwiftTest(fooPath, buildSystem: .xcode)\n                #expect(output.stderr.contains(\"Test Suite 'FooTests.xctest'\"))\n                #expect(output.stderr.contains(\"Test Suite 'CFooTests.xctest'\"))\n            }\n\n            do {\n                let output = try await executeSwiftTest(\n                    fooPath,\n                    extraArgs: [\n                        \"--filter\",\n                        \"CFooTests\",\n                    ],\n                    buildSystem: .xcode,\n                )\n                #expect(output.stderr.contains(\"Test Suite 'Selected tests' started\"))\n                #expect(output.stderr.contains(\"Test Suite 'CFooTests.xctest'\"))\n            }\n\n            do {\n                let output = try await executeSwiftTest(\n                    fooPath,\n                    extraArgs: [\"--parallel\"],\n                    buildSystem: .xcode,\n                )\n                #expect(output.stdout.contains(\"Testing FooTests\"))\n                #expect(output.stdout.contains(\"Testing CFooTests\"))\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/LLBuildManifestTests/LLBuildManifestTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport struct Basics.AbsolutePath\nimport class Basics.InMemoryFileSystem\nimport class Foundation.PropertyListDecoder\n@testable import LLBuildManifest\nimport _InternalTestSupport\nimport XCTest\n\nprivate let testEntitlement = \"test-entitlement\"\n\nfinal class LLBuildManifestTests: XCTestCase {\n    func testEntitlementsPlist() throws {\n        let FileType = WriteAuxiliary.EntitlementPlist.self\n        let inputs = FileType.computeInputs(entitlement: testEntitlement)\n        XCTAssertEqual(inputs, [.virtual(FileType.name), .virtual(testEntitlement)])\n\n        let contents = try FileType.getFileContents(inputs: inputs)\n        let decoder = PropertyListDecoder()\n        let decodedEntitlements = try decoder.decode([String: Bool].self, from: .init(contents.utf8))\n        XCTAssertEqual(decodedEntitlements, [testEntitlement: true])\n\n        var manifest = LLBuildManifest()\n        let outputPath = AbsolutePath(\"/test.plist\")\n        manifest.addEntitlementPlistCommand(entitlement: testEntitlement, outputPath: outputPath)\n\n        let commandName = outputPath.pathString\n        XCTAssertEqual(manifest.commands.count, 1)\n        \n        let command = try XCTUnwrap(manifest.commands[commandName]?.tool as? WriteAuxiliaryFile)\n\n        XCTAssertEqual(command, .init(inputs: inputs, outputFilePath: outputPath))\n    }\n\n    func testBasics() throws {\n        var manifest = LLBuildManifest()\n\n        let root: AbsolutePath = \"/some\"\n\n        manifest.defaultTarget = \"main\"\n        manifest.addPhonyCmd(\n            name: \"C.Foo\",\n            inputs: [\n                .file(root.appending(components: \"file.c\")),\n                .directory(root.appending(components: \"dir\")),\n                .directoryStructure(root.appending(components: \"dir\", \"structure\")),\n            ],\n            outputs: [.virtual(\"Foo\")]\n        )\n\n        manifest.addNode(.virtual(\"Foo\"), toTarget: \"main\")\n\n        let fs = InMemoryFileSystem()\n        try LLBuildManifestWriter.write(manifest, at: \"/manifest.yaml\", fileSystem: fs)\n\n        let contents: String = try fs.readFileContents(\"/manifest.yaml\")\n\n        // FIXME(#5475) - use the platform's preferred separator for directory\n        // indicators\n        XCTAssertEqual(contents.replacingOccurrences(of: \"\\\\\\\\\", with: \"\\\\\"), \"\"\"\n            client:\n              name: basic\n              file-system: device-agnostic\n            tools: {}\n            targets:\n              \"main\": [\"<Foo>\"]\n            default: \"main\"\n            nodes:\n              \"\\(root.appending(components: \"dir\", \"structure\"))/\":\n                is-directory-structure: true\n                content-exclusion-patterns: [\".git\",\".build\"]\n            commands:\n              \"C.Foo\":\n                tool: phony\n                inputs: [\"\\(root.appending(components: \"file.c\"))\",\"\\(root.appending(components: \"dir\"))/\",\"\\(root.appending(components: \"dir\", \"structure\"))/\"]\n                outputs: [\"<Foo>\"]\n\n\n            \"\"\")\n    }\n\n    func testShellCommands() throws {\n        var manifest = LLBuildManifest()\n\n        let root: AbsolutePath = .root\n\n        manifest.defaultTarget = \"main\"\n        manifest.addShellCmd(\n            name: \"shelley\",\n            description: \"Shelley, Keats, and Byron\",\n            inputs: [\n                .file(root.appending(components: \"file.in\"))\n            ],\n            outputs: [\n                .file(root.appending(components: \"file.out\"))\n            ],\n            arguments: [\n                \"foo\", \"bar\", \"baz\"\n            ],\n            environment: [\n                \"ABC\": \"DEF\",\n                \"G H\": \"I J K\",\n            ],\n            workingDirectory: \"/wdir\",\n            allowMissingInputs: true\n        )\n\n        manifest.addNode(.file(\"/file.out\"), toTarget: \"main\")\n\n        let fs = InMemoryFileSystem()\n        try LLBuildManifestWriter.write(manifest, at: \"/manifest.yaml\", fileSystem: fs)\n\n        let contents: String = try fs.readFileContents(\"/manifest.yaml\")\n\n        XCTAssertEqual(contents.replacingOccurrences(of: \"\\\\\\\\\", with: \"\\\\\"), \"\"\"\n            client:\n              name: basic\n              file-system: device-agnostic\n            tools: {}\n            targets:\n              \"main\": [\"\\(root.appending(components: \"file.out\"))\"]\n            default: \"main\"\n            commands:\n              \"shelley\":\n                tool: shell\n                inputs: [\"\\(root.appending(components: \"file.in\"))\"]\n                outputs: [\"\\(root.appending(components: \"file.out\"))\"]\n                description: \"Shelley, Keats, and Byron\"\n                args: [\"foo\",\"bar\",\"baz\"]\n                env:\n                  \"ABC\": \"DEF\"\n                  \"G H\": \"I J K\"\n                working-directory: \"/wdir\"\n                allow-missing-inputs: true\n\n\n            \"\"\")\n    }\n\n    func testMutatedNodes() throws {\n        var manifest = LLBuildManifest()\n\n        let root: AbsolutePath = .root\n\n        manifest.addNode(.virtual(\"C.mutate\"), toTarget: \"\")\n        let createTimestampNode = Node.virtual(\"C.create.timestamp\", isCommandTimestamp: true)\n        let mutatedNode = Node.file(root.appending(components: \"file.out\"), isMutated: true)\n\n        manifest.addShellCmd(\n            name: \"C.create\",\n            description: \"C.create\",\n            inputs: [\n                .file(root.appending(components: \"file.in\"))\n            ],\n            outputs: [mutatedNode, createTimestampNode],\n            arguments: [\n                \"cp\", \"file.in\", \"file.out\"\n            ]\n        )\n\n        manifest.addShellCmd(\n            name: \"C.mutate\",\n            description: \"C.mutate\",\n            inputs: [\n                createTimestampNode\n            ],\n            outputs: [\n                .virtual(\"C.mutate\")\n            ],\n            arguments: [\n                \"touch\", \"file.out\"\n            ]\n        )\n\n        let fs = InMemoryFileSystem()\n        try LLBuildManifestWriter.write(manifest, at: \"/manifest.yaml\", fileSystem: fs)\n\n        let contents: String = try fs.readFileContents(\"/manifest.yaml\")\n\n        XCTAssertEqual(contents.replacingOccurrences(of: \"\\\\\\\\\", with: \"\\\\\"), \"\"\"\n            client:\n              name: basic\n              file-system: device-agnostic\n            tools: {}\n            targets:\n              \"\": [\"<C.mutate>\"]\n            default: \"\"\n            nodes:\n              \"<C.create.timestamp>\":\n                is-command-timestamp: true\n              \"\\(AbsolutePath(\"/file.out\"))\":\n                is-mutated: true\n            commands:\n              \"C.create\":\n                tool: shell\n                inputs: [\"\\(AbsolutePath(\"/file.in\"))\"]\n                outputs: [\"\\(AbsolutePath(\"/file.out\"))\",\"<C.create.timestamp>\"]\n                description: \"C.create\"\n                args: [\"cp\",\"file.in\",\"file.out\"]\n\n              \"C.mutate\":\n                tool: shell\n                inputs: [\"<C.create.timestamp>\"]\n                outputs: [\"<C.mutate>\"]\n                description: \"C.mutate\"\n                args: [\"touch\",\"file.out\"]\n\n            \n            \"\"\")\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsModelTests/PackageCollectionModelTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport _InternalTestSupport\nimport XCTest\n\n@testable import PackageCollectionsModel\n\nclass PackageCollectionModelTests: XCTestCase {\n    typealias Model = PackageCollectionModel.V1\n\n    func testCollectionCodable() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                identity: \"foo.bar\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: \"Fix a few bugs\",\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: [.init(name: \"macOS\", version: \"10.15\")]\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: [Model.Compatibility(platform: Model.Platform(name: \"macOS\"), swiftVersion: \"5.2\")],\n                        license: .init(name: \"Apache-2.0\", url: \"https://package-collection-tests.com/repos/foobar/LICENSE\"),\n                        author: .init(name: \"J. Appleseed\"),\n                        signer: .init(\n                            type: \"ADP\",\n                            commonName: \"J. Appleseed\",\n                            organizationalUnitName: \"A1\",\n                            organizationName: \"Appleseed Inc.\"\n                        ),\n                        createdAt: Date()\n                    ),\n                ],\n                readmeURL: \"https://package-collection-tests.com/repos/foobar/README\",\n                license: .init(name: \"Apache-2.0\", url: \"https://package-collection-tests.com/repos/foobar/LICENSE\")\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let data = try JSONEncoder().encode(collection)\n        let decoded = try JSONDecoder().decode(Model.Collection.self, from: data)\n        XCTAssertEqual(collection, decoded)\n    }\n\n    func testSignedCollectionCodable() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                identity: \"foo.bar\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: \"Fix a few bugs\",\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: [.init(name: \"macOS\", version: \"10.15\")]\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: [Model.Compatibility(platform: Model.Platform(name: \"macOS\"), swiftVersion: \"5.2\")],\n                        license: .init(name: \"Apache-2.0\", url: \"https://package-collection-tests.com/repos/foobar/LICENSE\"),\n                        author: .init(name: \"J. Appleseed\"),\n                        signer: .init(\n                            type: \"ADP\",\n                            commonName: \"J. Appleseed\",\n                            organizationalUnitName: \"A1\",\n                            organizationName: \"Appleseed Inc.\"\n                        ),\n                        createdAt: Date()\n                    ),\n                ],\n                readmeURL: \"https://package-collection-tests.com/repos/foobar/README\",\n                license: .init(name: \"Apache-2.0\", url: \"https://package-collection-tests.com/repos/foobar/LICENSE\")\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n        let signature = Model.Signature(\n            signature: \"<SIGNATURE>\",\n            certificate: Model.Signature.Certificate(\n                subject: .init(userID: \"Test User ID\", commonName: \"Test Subject\", organizationalUnit: \"Test Org Unit\", organization: \"Test Org\"),\n                issuer: .init(userID: nil, commonName: \"Test Issuer\", organizationalUnit: nil, organization: nil)\n            )\n        )\n        let signedCollection = Model.SignedCollection(collection: collection, signature: signature)\n\n        let data = try JSONEncoder().encode(signedCollection)\n\n        let decoder = JSONDecoder()\n        let decoded = try decoder.decode(Model.SignedCollection.self, from: data)\n        XCTAssertEqual(signedCollection, decoded)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsSigningTests/CertificatePolicyTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\n@testable import PackageCollectionsSigning\nimport _InternalTestSupport\nimport SwiftASN1\nimport X509\nimport XCTest\n\nclass CertificatePolicyTests: XCTestCase {\n    func test_RSA_validate_happyCase() async throws {\n        let certChain = try await self.readTestRSACertChain()\n        let policy = TestCertificatePolicy(trustedRoots: certChain.suffix(1))\n\n        try await policy.validate(\n            certChain: certChain,\n            validationTime: TestCertificatePolicy.testCertValidDate\n        )\n    }\n\n    func test_EC_validate_happyCase() async throws {\n        let certChain = try await self.readTestECCertChain()\n        let policy = TestCertificatePolicy(trustedRoots: certChain.suffix(1))\n\n        try await policy.validate(\n            certChain: certChain,\n            validationTime: TestCertificatePolicy.testCertValidDate\n        )\n    }\n\n    func test_validate_untrustedRoot() async throws {\n        let certChain = try await self.readTestRSACertChain()\n        // Test root is not trusted\n        let policy = TestCertificatePolicy(trustedRoots: nil)\n\n        do {\n            try await policy.validate(\n                certChain: certChain,\n                validationTime: TestCertificatePolicy.testCertValidDate\n            )\n            XCTFail(\"Expected error\")\n        } catch {\n            guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n            }\n        }\n    }\n\n    func test_validate_expiredCert() async throws {\n        let certChain = try await self.readTestRSACertChain()\n        let policy = TestCertificatePolicy(trustedRoots: certChain.suffix(1))\n\n        // Use verify date outside of cert's validity period\n        do {\n            try await policy.validate(\n                certChain: certChain,\n                validationTime: TestCertificatePolicy.testCertInvalidDate\n            )\n            XCTFail(\"Expected error\")\n        } catch {\n            guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n            }\n        }\n    }\n\n    func test_validate_revoked() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        let certChain = try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"development-revoked.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                ]\n            }\n        )\n\n        // Apple root certs are in SwiftPM's default trust store\n        let policy = DefaultCertificatePolicy(\n            trustedRootCertsDir: nil,\n            additionalTrustedRootCerts: nil,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        do {\n            try await policy.validate(certChain: certChain)\n            XCTFail(\"Expected error\")\n        } catch {\n            guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n            }\n        }\n    }\n\n    func test_validate_defaultPolicy() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        let certChain = try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"development.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                ]\n            }\n        )\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            let policy = DefaultCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // What if `additionalTrustedRootCerts` has a cert that's already in the default trust store?\n            let rootCA = certChain.last!\n            let policy = DefaultCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: [rootCA],\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // What if the same cert is in both `trustedRootCertsDir` and `additionalTrustedRootCerts`?\n            try await withTemporaryDirectory { tmp in\n                let rootCA = certChain.last!\n\n                var serializer = DER.Serializer()\n                try rootCA.serialize(into: &serializer)\n                let rootCABytes = serializer.serializedBytes\n                try localFileSystem.writeFileContents(\n                    tmp.appending(components: \"AppleIncRoot.cer\"),\n                    bytes: .init(rootCABytes)\n                )\n\n                let policy = DefaultCertificatePolicy(\n                    trustedRootCertsDir: tmp.asURL,\n                    additionalTrustedRootCerts: [rootCA],\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n                try await policy.validate(certChain: certChain)\n            }\n        }\n    }\n\n    func test_validate_appleSwiftPackageCollectionPolicy_rsa() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        let certChain = try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"swift_package_collection.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                ]\n            }\n        )\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // What if `additionalTrustedRootCerts` has a cert that's already in the default trust store?\n            let rootCA = certChain.last!\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: [rootCA],\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // What if the same cert is in both `trustedRootCertsDir` and `additionalTrustedRootCerts`?\n            try await withTemporaryDirectory { tmp in\n                let rootCA = certChain.last!\n\n                var serializer = DER.Serializer()\n                try rootCA.serialize(into: &serializer)\n                let rootCABytes = serializer.serializedBytes\n                try localFileSystem.writeFileContents(\n                    tmp.appending(components: \"AppleIncRoot.cer\"),\n                    bytes: .init(rootCABytes)\n                )\n\n                let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                    trustedRootCertsDir: tmp.asURL,\n                    additionalTrustedRootCerts: [rootCA],\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n                try await policy.validate(certChain: certChain)\n            }\n        }\n    }\n\n    func test_validate_appleSwiftPackageCollectionPolicy_ec() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        let certChain = try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"swift_package.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG6.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleRootCAG3.cer\"),\n                ]\n            }\n        )\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // What if `additionalTrustedRootCerts` has a cert that's already in the default trust store?\n            let rootCA = certChain.last!\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: [rootCA],\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // What if the same cert is in both `trustedRootCertsDir` and `additionalTrustedRootCerts`?\n            try await withTemporaryDirectory { tmp in\n                let rootCA = certChain.last!\n\n                var serializer = DER.Serializer()\n                try rootCA.serialize(into: &serializer)\n                let rootCABytes = serializer.serializedBytes\n                try localFileSystem.writeFileContents(\n                    tmp.appending(components: \"AppleIncRoot.cer\"),\n                    bytes: .init(rootCABytes)\n                )\n\n                let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                    trustedRootCertsDir: tmp.asURL,\n                    additionalTrustedRootCerts: [rootCA],\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n                try await policy.validate(certChain: certChain)\n            }\n        }\n    }\n\n    func test_validate_defaultPolicy_user() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        let certChain = try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"development.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                ]\n            }\n        )\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject user ID matches\n            let policy = DefaultCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: expectedSubjectUserID,\n                expectedSubjectOrganizationalUnit: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject user ID does not match\n            let policy = DefaultCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: \"\\(expectedSubjectUserID)-2\",\n                expectedSubjectOrganizationalUnit: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            do {\n                try await policy.validate(certChain: certChain)\n                XCTFail(\"Expected error\")\n            } catch {\n                guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                    return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n                }\n            }\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject organizational unit matches\n            let policy = DefaultCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: nil,\n                expectedSubjectOrganizationalUnit: expectedSubjectOrgUnit,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject organizational unit does not match\n            let policy = DefaultCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: nil,\n                expectedSubjectOrganizationalUnit: \"\\(expectedSubjectOrgUnit)-2\",\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            do {\n                try await policy.validate(certChain: certChain)\n                XCTFail(\"Expected error\")\n            } catch {\n                guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                    return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n                }\n            }\n        }\n    }\n\n    func test_validate_appleSwiftPackageCollectionPolicy_rsa_user() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        let certChain = try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"swift_package_collection.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                ]\n            }\n        )\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject user ID matches\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: expectedSubjectUserID,\n                expectedSubjectOrganizationalUnit: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject user ID does not match\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: \"\\(expectedSubjectUserID)-2\",\n                expectedSubjectOrganizationalUnit: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            do {\n                try await policy.validate(certChain: certChain)\n                XCTFail(\"Expected error\")\n            } catch {\n                guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                    return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n                }\n            }\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject organizational unit matches\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: nil,\n                expectedSubjectOrganizationalUnit: expectedSubjectOrgUnit,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject organizational unit does not match\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: nil,\n                expectedSubjectOrganizationalUnit: \"\\(expectedSubjectOrgUnit)-2\",\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            do {\n                try await policy.validate(certChain: certChain)\n                XCTFail(\"Expected error\")\n            } catch {\n                guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                    return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n                }\n            }\n        }\n    }\n\n    func test_validate_appleSwiftPackageCollectionPolicy_ec_user() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        let certChain = try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"swift_package.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG6.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"AppleRootCAG3.cer\"),\n                ]\n            }\n        )\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject user ID matches\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: expectedSubjectUserID,\n                expectedSubjectOrganizationalUnit: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject user ID does not match\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: \"\\(expectedSubjectUserID)-2\",\n                expectedSubjectOrganizationalUnit: nil,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            do {\n                try await policy.validate(certChain: certChain)\n                XCTFail(\"Expected error\")\n            } catch {\n                guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                    return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n                }\n            }\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject organizational unit matches\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: nil,\n                expectedSubjectOrganizationalUnit: expectedSubjectOrgUnit,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            try await policy.validate(certChain: certChain)\n        }\n\n        do {\n            // Apple root certs are in SwiftPM's default trust store\n            // Subject organizational unit does not match\n            let policy = ADPSwiftPackageCollectionCertificatePolicy(\n                trustedRootCertsDir: nil,\n                additionalTrustedRootCerts: nil,\n                expectedSubjectUserID: nil,\n                expectedSubjectOrganizationalUnit: \"\\(expectedSubjectOrgUnit)-2\",\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            do {\n                try await policy.validate(certChain: certChain)\n                XCTFail(\"Expected error\")\n            } catch {\n                guard CertificatePolicyError.invalidCertChain == error as? CertificatePolicyError else {\n                    return XCTFail(\"Expected CertificatePolicyError.invalidCertChain\")\n                }\n            }\n        }\n    }\n\n    private func readTestRSACertChain() async throws -> [Certificate] {\n        try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"Test_rsa.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"TestRootCA.cer\"),\n                ]\n            }\n        )\n    }\n\n    private func readTestECCertChain() async throws -> [Certificate] {\n        try await self.readTestCertChain(\n            paths: { fixturePath in\n                [\n                    fixturePath.appending(components: \"Certificates\", \"Test_ec.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                    fixturePath.appending(components: \"Certificates\", \"TestRootCA.cer\"),\n                ]\n            }\n        )\n    }\n\n    private func readTestCertChain(paths: (AbsolutePath) -> [AbsolutePath]) async throws -> [Certificate] {\n        try await withCheckedThrowingContinuation { continuation in\n            do {\n                try fixtureXCTest(name: \"Signing\") { fixturePath in\n                    let certPaths = paths(fixturePath)\n                    let certificates = try certPaths.map { certPath in\n                        try Certificate(derEncoded: try localFileSystem.readFileContents(certPath).contents)\n                    }\n                    continuation.resume(returning: certificates)\n                }\n            } catch {\n                continuation.resume(throwing: error)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsSigningTests/PackageCollectionSigningTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Foundation\nimport PackageCollectionsModel\n@testable import PackageCollectionsSigning\nimport _InternalTestSupport\nimport X509\nimport XCTest\n\nclass PackageCollectionSigningTests: XCTestCase {\n    func test_RSA_signAndValidate_happyCase() async throws {\n        try await withTemporaryDirectory { tmp in\n            let collection: PackageCollectionModel.V1.Collection = try await self.readTestPackageCollection()\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"Test_rsa.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"TestRootCA.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in fixturePath.appending(components: \"Certificates\", \"Test_rsa_key.pem\") },\n                tmpDirectoryPath: tmp\n            )\n\n            let rootCA = try Certificate(derEncoded: try localFileSystem.readFileContents(certPaths.last!).contents)\n            let certPolicy = TestCertificatePolicy(trustedRoots: [rootCA])\n            let signing = PackageCollectionSigning(\n                certPolicy: certPolicy,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            // Sign the collection\n            let signedCollection = try await signing.sign(\n                collection: collection,\n                certChainPaths: certPaths.map(\\.asURL),\n                certPrivateKeyPath: privateKeyPath.asURL,\n                certPolicyKey: .custom\n            )\n\n            // Then validate that signature is valid\n            try await signing.validate(signedCollection: signedCollection, certPolicyKey: .custom)\n        }\n    }\n\n    func test_RSA_signAndValidate_collectionMismatch() async throws {\n        let collection1 = PackageCollectionModel.V1.Collection(\n            name: \"Test Package Collection 1\",\n            overview: nil,\n            keywords: nil,\n            packages: [],\n            formatVersion: .v1_0,\n            revision: nil,\n            generatedAt: Date(),\n            generatedBy: nil\n        )\n        let collection2 = PackageCollectionModel.V1.Collection(\n            name: \"Test Package Collection 2\",\n            overview: nil,\n            keywords: nil,\n            packages: [],\n            formatVersion: .v1_0,\n            revision: nil,\n            generatedAt: Date(),\n            generatedBy: nil\n        )\n\n        try await withTemporaryDirectory { tmp in\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"Test_rsa.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"TestRootCA.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in fixturePath.appending(components: \"Certificates\", \"Test_rsa_key.pem\") },\n                tmpDirectoryPath: tmp\n            )\n\n            let rootCA = try Certificate(derEncoded: try localFileSystem.readFileContents(certPaths.last!).contents)\n            let certPolicy = TestCertificatePolicy(trustedRoots: [rootCA])\n            let signing = PackageCollectionSigning(\n                certPolicy: certPolicy,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            // Sign collection1\n            let signedCollection = try await signing.sign(\n                collection: collection1,\n                certChainPaths: certPaths.map(\\.asURL),\n                certPrivateKeyPath: privateKeyPath.asURL,\n                certPolicyKey: .custom\n            )\n\n            // Use collection1's signature for collection2\n            let badSignedCollection = PackageCollectionModel.V1.SignedCollection(\n                collection: collection2,\n                signature: signedCollection.signature\n            )\n\n            // The signature should be invalid\n            do {\n                try await signing.validate(signedCollection: badSignedCollection, certPolicyKey: .custom)\n                XCTFail(\"Expected error\")\n            } catch {\n                guard PackageCollectionSigningError.invalidSignature == error as? PackageCollectionSigningError else {\n                    return XCTFail(\"Expected PackageCollectionSigningError.invalidSignature\")\n                }\n            }\n        }\n    }\n\n    func test_EC_signAndValidate_happyCase() async throws {\n        try await withTemporaryDirectory { tmp in\n            let collection = try await self.readTestPackageCollection()\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"Test_ec.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"TestRootCA.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in fixturePath.appending(components: \"Certificates\", \"Test_ec_key.pem\") },\n                tmpDirectoryPath: tmp\n            )\n\n            let rootCA = try Certificate(derEncoded: try localFileSystem.readFileContents(certPaths.last!).contents)\n            let certPolicy = TestCertificatePolicy(trustedRoots: [rootCA])\n            let signing = PackageCollectionSigning(\n                certPolicy: certPolicy,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            // Sign the collection\n            let signedCollection = try await signing.sign(\n                collection: collection,\n                certChainPaths: certPaths.map(\\.asURL),\n                certPrivateKeyPath: privateKeyPath.asURL,\n                certPolicyKey: .custom\n            )\n\n            // Then validate that signature is valid\n            try await signing.validate(signedCollection: signedCollection, certPolicyKey: .custom)\n        }\n    }\n\n    func test_EC_signAndValidate_collectionMismatch() async throws {\n        let collection1 = PackageCollectionModel.V1.Collection(\n            name: \"Test Package Collection 1\",\n            overview: nil,\n            keywords: nil,\n            packages: [],\n            formatVersion: .v1_0,\n            revision: nil,\n            generatedAt: Date(),\n            generatedBy: nil\n        )\n        let collection2 = PackageCollectionModel.V1.Collection(\n            name: \"Test Package Collection 2\",\n            overview: nil,\n            keywords: nil,\n            packages: [],\n            formatVersion: .v1_0,\n            revision: nil,\n            generatedAt: Date(),\n            generatedBy: nil\n        )\n\n        try await withTemporaryDirectory { tmp in\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"Test_ec.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"TestIntermediateCA.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"TestRootCA.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in fixturePath.appending(components: \"Certificates\", \"Test_ec_key.pem\") },\n                tmpDirectoryPath: tmp\n            )\n\n            let rootCA = try Certificate(derEncoded: try localFileSystem.readFileContents(certPaths.last!).contents)\n            let certPolicy = TestCertificatePolicy(trustedRoots: [rootCA])\n            let signing = PackageCollectionSigning(\n                certPolicy: certPolicy,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            // Sign collection1\n            let signedCollection = try await signing.sign(\n                collection: collection1,\n                certChainPaths: certPaths.map(\\.asURL),\n                certPrivateKeyPath: privateKeyPath.asURL,\n                certPolicyKey: .custom\n            )\n\n            // Use collection1's signature for collection2\n            let badSignedCollection = PackageCollectionModel.V1.SignedCollection(\n                collection: collection2,\n                signature: signedCollection.signature\n            )\n\n            // The signature should be invalid\n            do {\n                try await signing.validate(signedCollection: badSignedCollection, certPolicyKey: .custom)\n                XCTFail(\"Expected error\")\n            } catch {\n                guard PackageCollectionSigningError.invalidSignature == error as? PackageCollectionSigningError else {\n                    return XCTFail(\"Expected PackageCollectionSigningError.invalidSignature\")\n                }\n            }\n        }\n    }\n\n    func test_signAndValidate_defaultPolicy() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try await withTemporaryDirectory { tmp in\n            let collection = try await self.readTestPackageCollection()\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"development.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in\n                    fixturePath.appending(components: \"Certificates\", \"development_key.pem\")\n                },\n                tmpDirectoryPath: tmp\n            )\n\n            let rootCAData: Data = try localFileSystem.readFileContents(certPaths.last!)\n            let certPolicyKey: CertificatePolicyKey = .default\n\n            // Apple root certs are in SwiftPM's default trust store\n            do {\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            // Pass in the root cert with `additionalTrustedRootCerts` even though\n            // it's already in the default trust store\n            do {\n                let signing = PackageCollectionSigning(\n                    additionalTrustedRootCerts: [rootCAData.base64EncodedString()],\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            // Add root cert to `trustedRootCertsDir` even though it's already in the default trust store\n            do {\n                let trustedRootsDirPath = tmp.appending(\"trusted\")\n                try localFileSystem.createDirectory(trustedRootsDirPath, recursive: true)\n\n                let rootCAPath = certPaths.last!\n                try localFileSystem.copy(\n                    from: rootCAPath,\n                    to: trustedRootsDirPath.appending(components: \"AppleIncRoot.cer\")\n                )\n\n                let signing = PackageCollectionSigning(\n                    trustedRootCertsDir: trustedRootsDirPath.asURL,\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n        }\n    }\n\n    func test_signAndValidate_appleSwiftPackageCollectionPolicy_rsa() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try await withTemporaryDirectory { tmp in\n            let collection = try await self.readTestPackageCollection()\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"swift_package_collection.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in\n                    fixturePath.appending(components: \"Certificates\", \"swift_package_collection_key.pem\")\n                },\n                tmpDirectoryPath: tmp\n            )\n\n            let rootCAData: Data = try localFileSystem.readFileContents(certPaths.last!)\n            let certPolicyKey: CertificatePolicyKey = .appleSwiftPackageCollection\n\n            // Apple root certs are in SwiftPM's default trust store\n            do {\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            // Pass in the root cert with `additionalTrustedRootCerts` even though\n            // it's already in the default trust store\n            do {\n                let signing = PackageCollectionSigning(\n                    additionalTrustedRootCerts: [rootCAData.base64EncodedString()],\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            // Add root cert to `trustedRootCertsDir` even though it's already in the default trust store\n            do {\n                let trustedRootsDirPath = tmp.appending(\"trusted\")\n                try localFileSystem.createDirectory(trustedRootsDirPath, recursive: true)\n\n                let rootCAPath = certPaths.last!\n                try localFileSystem.copy(\n                    from: rootCAPath,\n                    to: trustedRootsDirPath.appending(components: \"AppleIncRoot.cer\")\n                )\n\n                let signing = PackageCollectionSigning(\n                    trustedRootCertsDir: trustedRootsDirPath.asURL,\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n        }\n    }\n\n    func test_signAndValidate_appleSwiftPackageCollectionPolicy_ec() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try await withTemporaryDirectory { tmp in\n            let collection = try await self.readTestPackageCollection()\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"swift_package.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG6.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleRootCAG3.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in\n                    fixturePath.appending(components: \"Certificates\", \"swift_package_key.pem\")\n                },\n                tmpDirectoryPath: tmp\n            )\n\n            let rootCAData: Data = try localFileSystem.readFileContents(certPaths.last!)\n            let certPolicyKey: CertificatePolicyKey = .appleSwiftPackageCollection\n\n            // Apple root certs are in SwiftPM's default trust store\n            do {\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            // Pass in the root cert with `additionalTrustedRootCerts` even though\n            // it's already in the default trust store\n            do {\n                let signing = PackageCollectionSigning(\n                    additionalTrustedRootCerts: [rootCAData.base64EncodedString()],\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            // Add root cert to `trustedRootCertsDir` even though it's already in the default trust store\n            do {\n                let trustedRootsDirPath = tmp.appending(\"trusted\")\n                try localFileSystem.createDirectory(trustedRootsDirPath, recursive: true)\n\n                let rootCAPath = certPaths.last!\n                try localFileSystem.copy(\n                    from: rootCAPath,\n                    to: trustedRootsDirPath.appending(components: \"AppleIncRoot.cer\")\n                )\n\n                let signing = PackageCollectionSigning(\n                    trustedRootCertsDir: trustedRootsDirPath.asURL,\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n        }\n    }\n\n    func test_signAndValidate_defaultPolicy_user() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try await withTemporaryDirectory { tmp in\n            let collection = try await self.readTestPackageCollection()\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"development.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in\n                    fixturePath.appending(components: \"Certificates\", \"development_key.pem\")\n                },\n                tmpDirectoryPath: tmp\n            )\n\n            // Apple root certs are in SwiftPM's default trust store\n            do {\n                // Match subject user ID\n                let certPolicyKey: CertificatePolicyKey = .default(subjectUserID: expectedSubjectUserID)\n\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            do {\n                // Match subject organizational unit\n                let certPolicyKey: CertificatePolicyKey = .default(subjectOrganizationalUnit: expectedSubjectOrgUnit)\n\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n        }\n    }\n\n    func test_signAndValidate_appleSwiftPackageCollectionPolicy_rsa_user() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try await withTemporaryDirectory { tmp in\n            let collection = try await self.readTestPackageCollection()\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"swift_package_collection.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG3.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleIncRoot.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in\n                    fixturePath.appending(components: \"Certificates\", \"swift_package_collection_key.pem\")\n                },\n                tmpDirectoryPath: tmp\n            )\n\n            // Apple root certs are in SwiftPM's default trust store\n            do {\n                // Match subject user ID\n                let certPolicyKey: CertificatePolicyKey =\n                    .appleSwiftPackageCollection(subjectUserID: expectedSubjectUserID)\n\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            do {\n                // Match subject organizational unit\n                let certPolicyKey: CertificatePolicyKey =\n                    .appleSwiftPackageCollection(subjectOrganizationalUnit: expectedSubjectOrgUnit)\n\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n        }\n    }\n\n    func test_signAndValidate_appleSwiftPackageCollectionPolicy_ec_user() async throws {\n        #if ENABLE_REAL_CERT_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try await withTemporaryDirectory { tmp in\n            let collection = try await self.readTestPackageCollection()\n            let (certPaths, privateKeyPath) = try await self.copyTestCertChainAndKey(\n                certPaths: { fixturePath in\n                    [\n                        fixturePath.appending(components: \"Certificates\", \"swift_package.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleWWDRCAG6.cer\"),\n                        fixturePath.appending(components: \"Certificates\", \"AppleRootCAG3.cer\"),\n                    ]\n                },\n                keyPath: { fixturePath in\n                    fixturePath.appending(components: \"Certificates\", \"swift_package_key.pem\")\n                },\n                tmpDirectoryPath: tmp\n            )\n\n            // Apple root certs are in SwiftPM's default trust store\n            do {\n                // Match subject user ID\n                let certPolicyKey: CertificatePolicyKey =\n                    .appleSwiftPackageCollection(subjectUserID: expectedSubjectUserID)\n\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n\n            do {\n                // Match subject organizational unit\n                let certPolicyKey: CertificatePolicyKey =\n                    .appleSwiftPackageCollection(subjectOrganizationalUnit: expectedSubjectOrgUnit)\n\n                let signing = PackageCollectionSigning(\n                    observabilityScope: ObservabilitySystem.NOOP\n                )\n\n                // Sign the collection\n                let signedCollection = try await signing.sign(\n                    collection: collection,\n                    certChainPaths: certPaths.map(\\.asURL),\n                    certPrivateKeyPath: privateKeyPath.asURL,\n                    certPolicyKey: certPolicyKey\n                )\n\n                // Then validate that signature is valid\n                try await signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey)\n            }\n        }\n    }\n\n    private func readTestPackageCollection() async throws -> PackageCollectionModel.V1.Collection {\n        try await withCheckedThrowingContinuation { continuation in\n            do {\n                try fixtureXCTest(name: \"Collections\") { fixturePath in\n                    let jsonDecoder = JSONDecoder.makeWithDefaults()\n                    let collectionPath = fixturePath.appending(components: \"JSON\", \"good.json\")\n                    let collectionData: Data = try localFileSystem.readFileContents(collectionPath)\n                    let collection = try jsonDecoder.decode(\n                        PackageCollectionModel.V1.Collection.self,\n                        from: collectionData\n                    )\n                    continuation.resume(returning: collection)\n                }\n            } catch {\n                continuation.resume(throwing: error)\n            }\n        }\n    }\n\n    private func copyTestCertChainAndKey(\n        certPaths: (AbsolutePath) -> [AbsolutePath],\n        keyPath: (AbsolutePath) -> AbsolutePath,\n        tmpDirectoryPath: AbsolutePath\n    ) async throws -> ([AbsolutePath], AbsolutePath) {\n        try await withCheckedThrowingContinuation { continuation in\n            do {\n                try fixtureXCTest(name: \"Signing\") { fixturePath in\n                    let certSourcePaths = certPaths(fixturePath)\n\n                    let certDirectoryPath = tmpDirectoryPath.appending(\"Certificates\")\n                    try localFileSystem.createDirectory(certDirectoryPath, recursive: true)\n\n                    let certDestPaths = certPaths(tmpDirectoryPath)\n                    for (i, sourceCertPath) in certSourcePaths.enumerated() {\n                        let destCertPath = certDestPaths[i]\n                        try localFileSystem.copy(from: sourceCertPath, to: destCertPath)\n                    }\n\n                    let keySourcePath = keyPath(fixturePath)\n                    let keyDestPath = keyPath(tmpDirectoryPath)\n                    try localFileSystem.copy(from: keySourcePath, to: keyDestPath)\n\n                    continuation.resume(returning: (certDestPaths, keyDestPath))\n                }\n            } catch {\n                continuation.resume(throwing: error)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsSigningTests/SignatureTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _CryptoExtras\nimport Basics\nimport _Concurrency\nimport Crypto\nimport Foundation\n@testable import PackageCollectionsSigning\nimport _InternalTestSupport\nimport X509\nimport XCTest\n\nclass SignatureTests: XCTestCase {\n    func test_RS256_generateAndValidate_happyCase() async throws {\n        let jsonEncoder = JSONEncoder.makeWithDefaults()\n        let jsonDecoder = JSONDecoder.makeWithDefaults()\n\n        let certData = try await self.readTestCertData(\n            path: { fixturePath in fixturePath.appending(components: \"Certificates\", \"Test_rsa.cer\") }\n        )\n        let certBase64Encoded = certData.base64EncodedString()\n        let certificate = try Certificate(derEncoded: Array(certData))\n\n        let payload = [\"foo\": \"bar\"]\n        let privateKey = try _RSA.Signing.PrivateKey(pemRepresentation: certRSAPrivateKey)\n        let signature = try Signature.generate(\n            payload: payload,\n            certChainData: [certData],\n            jsonEncoder: jsonEncoder,\n            signatureAlgorithm: .RS256\n        ) {\n            try privateKey.signature(for: SHA256.hash(data: $0), padding: Signature.rsaSigningPadding).rawRepresentation\n        }\n\n        let parsedSignature = try await Signature.parse(\n            signature,\n            certChainValidate: { _ in [certificate] },\n            jsonDecoder: jsonDecoder\n        )\n        XCTAssertEqual(try jsonDecoder.decode([String: String].self, from: parsedSignature.payload), payload)\n        XCTAssertEqual(parsedSignature.header.algorithm, Signature.Algorithm.RS256)\n        XCTAssertEqual(parsedSignature.header.certChain, [certBase64Encoded])\n    }\n\n    func test_RS256_generateAndValidate_keyMismatch() async throws {\n        let jsonEncoder = JSONEncoder.makeWithDefaults()\n        let jsonDecoder = JSONDecoder.makeWithDefaults()\n\n        let certData = try await self.readTestCertData(\n            path: { fixturePath in fixturePath.appending(components: \"Certificates\", \"Test_rsa.cer\") }\n        )\n        let certificate = try Certificate(derEncoded: Array(certData))\n\n        let payload = [\"foo\": \"bar\"]\n        // This is not cert's key so `parse` will fail\n        let privateKey = try _RSA.Signing.PrivateKey(pemRepresentation: rsaPrivateKey)\n        let signature = try Signature.generate(\n            payload: payload,\n            certChainData: [certData],\n            jsonEncoder: jsonEncoder,\n            signatureAlgorithm: .RS256\n        ) {\n            try privateKey.signature(for: SHA256.hash(data: $0), padding: Signature.rsaSigningPadding).rawRepresentation\n        }\n\n        do {\n            _ = try await Signature.parse(\n                signature,\n                certChainValidate: { _ in [certificate] },\n                jsonDecoder: jsonDecoder\n            )\n            XCTFail(\"Expected error\")\n        } catch {\n            guard SignatureError.invalidSignature == error as? SignatureError else {\n                return XCTFail(\"Expected SignatureError.invalidSignature\")\n            }\n        }\n    }\n\n    func test_ES256_generateAndValidate_happyCase() async throws {\n        let jsonEncoder = JSONEncoder.makeWithDefaults()\n        let jsonDecoder = JSONDecoder.makeWithDefaults()\n\n        let certData = try await self.readTestCertData(\n            path: { fixturePath in fixturePath.appending(components: \"Certificates\", \"Test_ec.cer\") }\n        )\n        let certBase64Encoded = certData.base64EncodedString()\n        let certificate = try Certificate(derEncoded: Array(certData))\n\n        let payload = [\"foo\": \"bar\"]\n        let privateKey = try P256.Signing.PrivateKey(pemRepresentation: certECPrivateKey)\n        let signature = try Signature.generate(\n            payload: payload,\n            certChainData: [certData],\n            jsonEncoder: jsonEncoder,\n            signatureAlgorithm: .ES256\n        ) {\n            try privateKey.signature(for: SHA256.hash(data: $0)).rawRepresentation\n        }\n\n        let parsedSignature = try await Signature.parse(\n            signature,\n            certChainValidate: { _ in [certificate] },\n            jsonDecoder: jsonDecoder\n        )\n\n        XCTAssertEqual(try jsonDecoder.decode([String: String].self, from: parsedSignature.payload), payload)\n        XCTAssertEqual(parsedSignature.header.algorithm, Signature.Algorithm.ES256)\n        XCTAssertEqual(parsedSignature.header.certChain, [certBase64Encoded])\n    }\n\n    func test_ES256_generateAndValidate_keyMismatch() async throws {\n        let jsonEncoder = JSONEncoder.makeWithDefaults()\n        let jsonDecoder = JSONDecoder.makeWithDefaults()\n\n        let certData = try await self.readTestCertData(\n            path: { fixturePath in fixturePath.appending(components: \"Certificates\", \"Test_ec.cer\") }\n        )\n        let certificate = try Certificate(derEncoded: Array(certData))\n\n        let payload = [\"foo\": \"bar\"]\n        // This is not cert's key so `parse` will fail\n        let privateKey = try P256.Signing.PrivateKey(pemRepresentation: ecPrivateKey)\n        let signature = try Signature.generate(\n            payload: payload,\n            certChainData: [certData],\n            jsonEncoder: jsonEncoder,\n            signatureAlgorithm: .ES256\n        ) {\n            try privateKey.signature(for: SHA256.hash(data: $0)).rawRepresentation\n        }\n\n        do {\n            _ = try await Signature.parse(\n                signature,\n                certChainValidate: { _ in [certificate] },\n                jsonDecoder: jsonDecoder\n            )\n            XCTFail(\"Expected error\")\n        } catch {\n            guard SignatureError.invalidSignature == error as? SignatureError else {\n                return XCTFail(\"Expected SignatureError.invalidSignature\")\n            }\n        }\n    }\n\n    private func readTestCertData(path: (AbsolutePath) -> AbsolutePath) async throws -> Data {\n        try await withCheckedThrowingContinuation { continuation in\n            do {\n                try fixtureXCTest(name: \"Signing\") { fixturePath in\n                    let certPath = path(fixturePath)\n                    let certData: Data = try localFileSystem.readFileContents(certPath)\n                    continuation.resume(returning: certData)\n                }\n            } catch {\n                continuation.resume(throwing: error)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsSigningTests/Utilities.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport Foundation\n@testable import PackageCollectionsSigning\nimport X509\n\n// Set `REAL_CERT_USER_ID` and `REAL_CERT_ORG_UNIT` env vars when running ENABLE_REAL_CERT_TEST tests\nlet expectedSubjectUserID = Environment.current[\"REAL_CERT_USER_ID\"] ?? \"<USER ID>\"\nlet expectedSubjectOrgUnit = Environment.current[\"REAL_CERT_ORG_UNIT\"] ?? \"<ORG UNIT>\"\n\n// MARK: - CertificatePolicy for test certs\n\nstruct TestCertificatePolicy: CertificatePolicy {\n    static let testCertValidDate: Date = {\n        // This is the datetime that the tests use to validate test certs (Test_rsa.cer, Test_ec.cer).\n        // Make sure it falls within the certs' validity period, across timezones.\n        // For example, suppose the current date is April 17, 2023, the cert validation runs as if\n        // the date were July 18, 2023.\n        var dateComponents = DateComponents()\n        dateComponents.year = 2023\n        dateComponents.month = 7\n        dateComponents.day = 18\n        return Calendar.current.date(from: dateComponents)!\n    }()\n\n    static let testCertInvalidDate: Date = {\n        var dateComponents = DateComponents()\n        dateComponents.year = 2000\n        dateComponents.month = 11\n        dateComponents.day = 16\n        return Calendar.current.date(from: dateComponents)!\n    }()\n\n    let trustedRoots: [Certificate]?\n\n    init(trustedRoots: [Certificate]?) {\n        self.trustedRoots = trustedRoots\n    }\n\n    func validate(\n        certChain: [Certificate],\n        validationTime: Date\n    ) async throws {\n        try await self.verify(\n            certChain: certChain,\n            trustedRoots: self.trustedRoots,\n            policies: {\n                // Must be a code signing certificate\n                _CodeSigningPolicy()\n                // Basic validations including expiry check\n                RFC5280Policy(validationTime: validationTime)\n                // Doesn't require OCSP\n            },\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n}\n\n// MARK: - Test keys\n\nlet ecPrivateKey = \"\"\"\n-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIMFnwA1gjIFnFZim4B2QvoXJIG2L4B8nH1BBZFlotA24oAoGCCqGSM49\nAwEHoUQDQgAEkc2FgXZVz9llhV6+jAGPVHEcxBxK5tui9HWzvtE+ogKPr7i3e2JO\nXwm91hecppS11y/S8bLmrFxA+dCP/V7bnw==\n-----END EC PRIVATE KEY-----\n\"\"\"\n\nlet ecPublicKey = \"\"\"\n-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEkc2FgXZVz9llhV6+jAGPVHEcxBxK\n5tui9HWzvtE+ogKPr7i3e2JOXwm91hecppS11y/S8bLmrFxA+dCP/V7bnw==\n-----END PUBLIC KEY-----\n\"\"\"\n\nlet rsaPrivateKey = \"\"\"\n-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAoQIWz/MQ+mRShQxxxs+zlCLHRz+R1zUPKZhg3eggbXartfyI\nOSPEDaVANCjE1QLg0dtGCpkbMAVQLkC7os5ZuW6A6qtSAU6WUBOvnDBPVumqmDUq\nAeXGEQyDZqReRm3D4Ov4qOTlIk34pRhoCymaNTiw7GfyzzWOcPxcRGGTz6fv1gmS\nwDnURBeL9QUAb2/sdAAsY/SZzziNF+womF8y3mn+IvlKL3EhtSxUfdZpPdFmxPza\noVIlllFQcKnxH4/0PZeyPK0Npq4kCqATXcYXmaa3Ms9tPcsQUggtAR/QepyrKmB1\nSRAouHqKi+bGTlCpFSFbDgW422gfqXEEboh39QIDAQABAoIBAQCRUR9hxFHYjF9m\nMhsmgyPjWZhel+N7RypOMneLEQzjfy3vbONOHxe98R4HdZxhXN2oyq1mt1UwfDsn\n48j2YiPdFv1H0CSNhW5pC7t9zqRtHyyXf7RQTh/8Fz0pkMR98GfQQ2oElcKwuYrn\nByYwnPXPf0E/vXoKxp2vIDXuidssmUl37mvbyppGaVl+Is6GmAiZkNOKN8ZEXPvz\n4BivJ3yhs/RiM5RUF93qj8j/3P6R8rXLemAE9jrKjGG7Vv966p1Fh9+wNnnnbT8t\nzLDUVwD7Q/JERr+3Wdecp+pZIfWTvJJhE8R3IM4WrLQNeUEKo7YovfYA7rah3gP/\nixM2BM5pAoGBAM5+c7Sxl7hzII2yPxN2fIslyKw3E8HP1nnqUPUegFsU3TZRQUnZ\ngm5JgQRPqFYy6fwouL07KdSb/zIes3ra/qkhaOewHsAvvvxKKM6FGqYrkb5BKv0s\ngF/m4qg6GLSW3BVb/QfnwHdWE7z7KPGuomzg+pqshxTyKYkGN2l8IIu7AoGBAMeb\n81636nRy62CYQhNCp13wqmmUJ8/VnNj2jdwdXQ5vlgQdrwFm2p52cEFn/AhL5WIn\nGShRLKL/keK71tsD0hCsTuZISR1xFiFk0TFmjxSX+z2D9VGvSECtNfySRuroKorS\nxIXsrx6dvk/Ef54yDus1O5vvdT3l6vSDbVJESFgPAoGBAIAFJ8kT/YNOZRVUOATi\nBa7jGvmiH+6d41OscMq3QU62rbr6P2cAofusOH+qvyvJ3wUFXht7raBxopK5M/7r\n/MxwuTBDIZ13PIn/lDMNlIsHIhF5J6TUzTYn18gCVMTJbuMTJ9mZ1dpmlFAqyqSj\n53FnPhdc9VaIGDYqk3ojia33AoGAd52bzNH3vMq1BJCZYANcWm4DIPu4k9JViKrP\nPe2WuzThOBw1qGhjb/xXrspKfQpGLnhxmfhzAEaYvL+FtH9onbc0HMmKjwsakO5i\ncfEcouGknCt8kfOxH5jstitONizkeYZuYDcChh1PU2vUcg9bY1XmH77yiiJClz4+\n/8KNe78CgYEArTT+XVctYq5jaFCtGqq3DD/DrgJeWS6V5Op0QgVrVKFeCH2mImOg\n6+95qwqyl3xCTJNvLwcNB+yricsWfUicEPKfDJX1w8m5/fANMRZYXr2nmAZvS9Kw\npkG0a65+K/m4wnZIszEuNZ2ybjrHEwYdWygRkJUmHp5rzmjdKjCBkwU=\n-----END RSA PRIVATE KEY-----\n\"\"\"\n\nlet rsaPublicKey = \"\"\"\n-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoQIWz/MQ+mRShQxxxs+z\nlCLHRz+R1zUPKZhg3eggbXartfyIOSPEDaVANCjE1QLg0dtGCpkbMAVQLkC7os5Z\nuW6A6qtSAU6WUBOvnDBPVumqmDUqAeXGEQyDZqReRm3D4Ov4qOTlIk34pRhoCyma\nNTiw7GfyzzWOcPxcRGGTz6fv1gmSwDnURBeL9QUAb2/sdAAsY/SZzziNF+womF8y\n3mn+IvlKL3EhtSxUfdZpPdFmxPzaoVIlllFQcKnxH4/0PZeyPK0Npq4kCqATXcYX\nmaa3Ms9tPcsQUggtAR/QepyrKmB1SRAouHqKi+bGTlCpFSFbDgW422gfqXEEboh3\n9QIDAQAB\n-----END PUBLIC KEY-----\n\"\"\"\n\nlet certECPrivateKey = \"\"\"\n-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIGfOkQcQq6oTC06KkGMVBAr2MiYFRaLo4/wKdNBpIjhnoAoGCCqGSM49\nAwEHoUQDQgAE6SjFVQRtU/+ywvxslaVsl+iZf65YgkQShuxsbAbNJBTVkEkMGyNL\n8nbaj6B4Jskjo1loNPLirNE7mKeTLYbrcw==\n-----END EC PRIVATE KEY-----\n\"\"\"\n\nlet certRSAPrivateKey = \"\"\"\n-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEA13XgJ9lIhR2LefNxQdo3tVrbXEZ3o4T8+MgteVJVohbPMypf\nyGgGlJJ/r7+hhL/klsPDyR4SAtgLZUGFVt3WzGMolGyV11VUTTFHMWZ10tcgrUmR\n5wg2n5E59FsJf3y3WTs5CpD2tM8igWyAUOyS/MWvhgnMtvBG8I4Mg9xyyWi/GW3g\nPLXfnyULW/v2Zg+yG9j+/Bbpx+AP8TCvWoiPyiLEZ/DKZK2kC+8mkwOtHYDMkBO5\n2nIrxopB42VUWYBfAzHm0M2XlEuc26PVojqno2ht5WU486uJXzWILvW3zFdlNDF/\nSLeqQy1mNLRt5/An6la7e3sjOcuI1W2Qe7dkrwIDAQABAoIBAES+eUx9iSPfr1az\nk5k9NLUKTh785MMpdUUzKT8iQ+w5dtaOWI0qk57ntxGuBKzERPzNbTRIAdsib1BZ\nPV/f297ObG4ezxgrQ4B1jo92b3Vb6jMf3AtolXUH8wPB4B/q/Nzdhm+WnQBHbmz4\n31/ye1tm/3+2tLhRpXCvAdM4jO8xhJlH+Pxg20fliAuiJ+ggSL56CyBR4kg80KtA\nomeGB1DOVFd23aDO/79Mii/2tf6EpmVFB/4zBkPHOH3zucwt8XUttwBeOcGdIbP+\nCiU9VdZmG0XOJfC3apAXf9YwU3WVbmbvUWSwt6iHGZD4AuKY2R0ECTZnYS8ThDhd\nZwPXzCECgYEA6xe9MpBCIVRK51Hb083mDg16UjRvPJA4T8w9xFg4UtAwe/u3CC67\n4fAOSe0P3NtsXhcQFby7PEJwoeo2Hn6hUifxVMsKWmHb+FCg+CG/oBSwRKCa5BwG\nWpJ0jEt6KHZf0u+b/N1aOjVi/9tMrsHXFV3s2Gm9LQqA8u8izshDqakCgYEA6p8t\nKVK2mA+JjvSGyR6WfpVZ1OIi6CEEUhRU3aNHRB2zPf6J3PQLjz+Ad50BCVHXQSy/\naG3LpR44eUu5Q9AmTwDr8eiC8AT6uyE19zJHbK//E40Bn6khQvtymwByjav/5ZB+\nZAhE7E31eCZO8bqufSlnMNTD0Z8oqB5YR8uDApcCgYAkPcGd5N089Bij9luUGD6p\n1ewQdiLbzEPSEWNIPG1aXtvKkTBTI5k1KGObg98ZJf5btuR05WZb0MY6P7feFZla\n5+ttLevHqSRW8F8QQWugCvBtc/DMz4EvPzqWUiBf0nfNNcDvR1RcetRrKux0WE+G\n7LbRWeOe6OqeCL1t8TN1GQKBgHPaH6m8/w689VbSpc+fu/5Lby0wcL4gt4p0IafD\nnUgkRkLBcn/ZPfABEkV+EGnysJCtMOK2/IzPDGHQo2251YDDWr576lPskYZfks86\nU4x2p0SXJwsYr6Tslp21LduI5/YKUG7Cqo3ovOIUQH0ailihXiP9m6fhqGjDeyIQ\neuOHAoGAfDpntw1HRuk812au430Stl5eaTsH+w1msLLKZOukr6qWc2xFeC3fYPWQ\nBBkyzM3p6Se9FsfHY6LMxrEkz9fSdeVOeHenyUCTMqhqrc6o9f79zIlocsMzVGsK\nXKcULjpf67Igyx12eh3rqAEKwm6PGhbv9pK5/NpuzsP1atArMRg=\n-----END RSA PRIVATE KEY-----\n\"\"\"\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/GitHubPackageMetadataProviderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport XCTest\n\nimport Basics\n@testable import PackageCollections\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\n\nimport struct TSCUtility.Version\n\nclass GitHubPackageMetadataProviderTests: XCTestCase {\n    func testBaseURL() throws {\n        let apiURL = URL(\"https://api.github.com/repos/octocat/Hello-World\")\n\n        do {\n            let sshURLRetVal = GitHubPackageMetadataProvider.apiURL(\"git@github.com:octocat/Hello-World.git\")\n            XCTAssertEqual(apiURL, sshURLRetVal)\n        }\n\n        do {\n            let httpsURLRetVal = GitHubPackageMetadataProvider.apiURL(\"https://github.com/octocat/Hello-World.git\")\n            XCTAssertEqual(apiURL, httpsURLRetVal)\n        }\n\n        do {\n            let httpsURLRetVal = GitHubPackageMetadataProvider.apiURL(\"https://github.com/octocat/Hello-World\")\n            XCTAssertEqual(apiURL, httpsURLRetVal)\n        }\n\n        XCTAssertNil(GitHubPackageMetadataProvider.apiURL(\"bad/Hello-World.git\"))\n    }\n\n    func testGood() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n            let apiURL = URL(\"https://api.github.com/repos/octocat/Hello-World\")\n            let releasesURL = URL(\"https://api.github.com/repos/octocat/Hello-World/releases?per_page=20\")\n\n            try await fixtureXCTest(name: \"Collections\") { fixturePath in\n                let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                    switch (request.method, request.url) {\n                    case (.get, apiURL):\n                        let path = fixturePath.appending(components: \"GitHub\", \"metadata.json\")\n                        let data: Data = try! localFileSystem.readFileContents(path)\n                        completion(.success(.init(statusCode: 200,\n                                                  headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                                  body: data)))\n                    case (.get, releasesURL):\n                        let path = fixturePath.appending(components: \"GitHub\", \"releases.json\")\n                        let data: Data = try! localFileSystem.readFileContents(path)\n                        completion(.success(.init(statusCode: 200,\n                                                  headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                                  body: data)))\n                    case (.get, apiURL.appendingPathComponent(\"contributors\")):\n                        let path = fixturePath.appending(components: \"GitHub\", \"contributors.json\")\n                        let data: Data = try! localFileSystem.readFileContents(path)\n                        completion(.success(.init(statusCode: 200,\n                                                  headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                                  body: data)))\n                    case (.get, apiURL.appendingPathComponent(\"readme\")):\n                        let path = fixturePath.appending(components: \"GitHub\", \"readme.json\")\n                        let data: Data = try! localFileSystem.readFileContents(path)\n                        completion(.success(.init(statusCode: 200,\n                                                  headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                                  body: data)))\n                    case (.get, apiURL.appendingPathComponent(\"license\")):\n                        let path = fixturePath.appending(components: \"GitHub\", \"license.json\")\n                        let data: Data = try! localFileSystem.readFileContents(path)\n                        completion(.success(.init(statusCode: 200,\n                                                  headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                                  body: data)))\n                    case (.get, apiURL.appendingPathComponent(\"languages\")):\n                        let path = fixturePath.appending(components: \"GitHub\", \"languages.json\")\n                        let data: Data = try! localFileSystem.readFileContents(path)\n                        completion(.success(.init(statusCode: 200,\n                                                  headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                                  body: data)))\n                    default:\n                        XCTFail(\"method and url should match\")\n                    }\n                }\n\n                let httpClient = LegacyHTTPClient(handler: handler)\n                httpClient.configuration.circuitBreakerStrategy = .none\n                httpClient.configuration.retryStrategy = .none\n                var configuration = GitHubPackageMetadataProvider.Configuration()\n                configuration.cacheDir = tmpPath\n                let provider = GitHubPackageMetadataProvider(configuration: configuration, httpClient: httpClient)\n                defer { XCTAssertNoThrow(try provider.close()) }\n\n                let metadata = try await provider.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString)\n\n                XCTAssertEqual(metadata.summary, \"This your first repo!\")\n                XCTAssertEqual(metadata.versions.count, 2)\n                XCTAssertEqual(metadata.versions[0].version, TSCUtility.Version(tag: \"v2.0.0\"))\n                XCTAssertEqual(metadata.versions[0].title, \"2.0.0\")\n                XCTAssertEqual(metadata.versions[0].summary, \"Description of the release\")\n                XCTAssertEqual(metadata.versions[0].author?.username, \"octocat\")\n                XCTAssertEqual(metadata.versions[1].version, TSCUtility.Version(\"1.0.0\"))\n                XCTAssertEqual(metadata.versions[1].title, \"1.0.0\")\n                XCTAssertEqual(metadata.versions[1].summary, \"Description of the release\")\n                XCTAssertEqual(metadata.versions[1].author?.username, \"octocat\")\n                XCTAssertEqual(metadata.authors, [PackageCollectionsModel.Package.Author(username: \"octocat\",\n                                                                                         url: \"https://api.github.com/users/octocat\",\n                                                                                         service: .init(name: \"GitHub\"))])\n                XCTAssertEqual(metadata.readmeURL, \"https://raw.githubusercontent.com/octokit/octokit.rb/main/README.md\")\n                XCTAssertEqual(metadata.license?.type, PackageCollectionsModel.LicenseType.MIT)\n                XCTAssertEqual(metadata.license?.url, \"https://raw.githubusercontent.com/benbalter/gman/main/LICENSE?lab=true\")\n                XCTAssertEqual(metadata.watchersCount, 80)\n                XCTAssertEqual(metadata.languages, [\"Swift\", \"Shell\", \"C\"])\n            }\n        }\n    }\n\n    func testRepoNotFound() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n\n            let handler: LegacyHTTPClient.Handler = { _, _, completion in\n                completion(.success(.init(statusCode: 404)))\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n            var configuration = GitHubPackageMetadataProvider.Configuration()\n            configuration.cacheDir = tmpPath\n            let provider = GitHubPackageMetadataProvider(configuration: configuration, httpClient: httpClient)\n            defer { XCTAssertNoThrow(try provider.close()) }\n\n            await XCTAssertAsyncThrowsError(try await provider.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString), \"should throw error\") { error in\n                XCTAssert(error is NotFoundError, \"\\(error)\")\n            }\n        }\n    }\n\n    func testOthersNotFound() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n            let apiURL = URL(\"https://api.github.com/repos/octocat/Hello-World\")\n\n            try await fixtureXCTest(name: \"Collections\") { fixturePath in\n                let path = fixturePath.appending(components: \"GitHub\", \"metadata.json\")\n                let data = try Data(localFileSystem.readFileContents(path).contents)\n                let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                    switch (request.method, request.url) {\n                    case (.get, apiURL):\n                        completion(.success(.init(statusCode: 200,\n                                                  headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                                  body: data)))\n                    default:\n                        completion(.success(.init(statusCode: 500)))\n                    }\n                }\n\n                let httpClient = LegacyHTTPClient(handler: handler)\n                httpClient.configuration.circuitBreakerStrategy = .none\n                httpClient.configuration.retryStrategy = .none\n                var configuration = GitHubPackageMetadataProvider.Configuration()\n                configuration.cacheDir = tmpPath\n                let provider = GitHubPackageMetadataProvider(configuration: configuration, httpClient: httpClient)\n                defer { XCTAssertNoThrow(try provider.close()) }\n\n                let metadata = try await provider.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString)\n\n                XCTAssertEqual(metadata.summary, \"This your first repo!\")\n                XCTAssertEqual(metadata.versions, [])\n                XCTAssertNil(metadata.authors)\n                XCTAssertNil(metadata.readmeURL)\n                XCTAssertEqual(metadata.watchersCount, 80)\n            }\n        }\n    }\n\n    func testPermissionDenied() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n            let apiURL = URL(\"https://api.github.com/repos/octocat/Hello-World\")\n\n            let handler: LegacyHTTPClient.Handler = { _, _, completion in\n                completion(.success(.init(statusCode: 401)))\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n            var configuration = GitHubPackageMetadataProvider.Configuration()\n            configuration.cacheDir = tmpPath\n            let provider = GitHubPackageMetadataProvider(configuration: configuration, httpClient: httpClient)\n            defer { XCTAssertNoThrow(try provider.close()) }\n\n            await XCTAssertAsyncThrowsError(try await provider.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString), \"should throw error\") { error in\n                XCTAssertEqual(error as? GitHubPackageMetadataProviderError, .permissionDenied(apiURL))\n            }\n        }\n    }\n\n    func testInvalidAuthToken() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n            let apiURL = URL(\"https://api.github.com/repos/octocat/Hello-World\")\n            let authTokens = [AuthTokenType.github(\"github.com\"): \"foo\"]\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                if request.headers.get(\"Authorization\").first == \"token \\(authTokens.first!.value)\" {\n                    completion(.success(.init(statusCode: 401)))\n                } else {\n                    XCTFail(\"expected correct authorization header\")\n                    completion(.success(.init(statusCode: 500)))\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n            var configuration = GitHubPackageMetadataProvider.Configuration()\n            configuration.cacheDir = tmpPath\n            configuration.authTokens = { authTokens }\n            let provider = GitHubPackageMetadataProvider(configuration: configuration, httpClient: httpClient)\n            defer { XCTAssertNoThrow(try provider.close()) }\n\n            await XCTAssertAsyncThrowsError(try await provider.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString), \"should throw error\") { error in\n                XCTAssertEqual(error as? GitHubPackageMetadataProviderError, .invalidAuthToken(apiURL))\n            }\n        }\n    }\n\n    func testAPILimit() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n            let apiURL = URL(\"https://api.github.com/repos/octocat/Hello-World\")\n\n            let total = 5\n            var remaining = total\n\n            try await fixtureXCTest(name: \"Collections\") { fixturePath in\n                let path = fixturePath.appending(components: \"GitHub\", \"metadata.json\")\n                let data = try Data(localFileSystem.readFileContents(path).contents)\n                let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                    var headers = HTTPClientHeaders()\n                    headers.add(name: \"X-RateLimit-Limit\", value: \"\\(total)\")\n                    headers.add(name: \"X-RateLimit-Remaining\", value: \"\\(remaining)\")\n                    if remaining == 0 {\n                        completion(.success(.init(statusCode: 403, headers: headers)))\n                    } else if request.url == apiURL {\n                        remaining = remaining - 1\n                        headers.add(name: \"Content-Length\", value: \"\\(data.count)\")\n                        completion(.success(.init(statusCode: 200,\n                                                  headers: headers,\n                                                  body: data)))\n                    } else {\n                        completion(.success(.init(statusCode: 500)))\n                    }\n                }\n\n                // Disable cache so we hit the API\n                let configuration = GitHubPackageMetadataProvider.Configuration(disableCache: true)\n\n                let httpClient = LegacyHTTPClient(handler: handler)\n                httpClient.configuration.circuitBreakerStrategy = .none\n                httpClient.configuration.retryStrategy = .none\n\n                let provider = GitHubPackageMetadataProvider(configuration: configuration, httpClient: httpClient)\n                defer { XCTAssertNoThrow(try provider.close()) }\n\n                for index in 0 ... total * 2 {\n                    if index >= total {\n                        await XCTAssertAsyncThrowsError(try await provider.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString), \"should throw error\") { error in\n                            XCTAssertEqual(error as? GitHubPackageMetadataProviderError, .apiLimitsExceeded(apiURL, total))\n                        }\n                    } else {\n                        _ = try await provider.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString)\n                    }\n                }\n            }\n        }\n    }\n\n    func testInvalidURL() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            try await fixtureXCTest(name: \"Collections\") { _ in\n                var configuration = GitHubPackageMetadataProvider.Configuration()\n                configuration.cacheDir = tmpPath\n                let provider = GitHubPackageMetadataProvider(configuration: configuration)\n                defer { XCTAssertNoThrow(try provider.close()) }\n\n                let url = UUID().uuidString\n                let identity = PackageIdentity(urlString: url)\n                await XCTAssertAsyncThrowsError(try await provider.syncGet(identity: identity, location: url), \"should throw error\") { error in\n                    XCTAssertEqual(error as? GitHubPackageMetadataProviderError, .invalidSourceControlURL(url))\n                }\n            }\n        }\n    }\n\n    func testInvalidURL2() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            try await fixtureXCTest(name: \"Collections\") { _ in\n                var configuration = GitHubPackageMetadataProvider.Configuration()\n                configuration.cacheDir = tmpPath\n                let provider = GitHubPackageMetadataProvider(configuration: configuration)\n                defer { XCTAssertNoThrow(try provider.close()) }\n\n                let path = AbsolutePath.root\n                let identity = PackageIdentity(path: path)\n                await XCTAssertAsyncThrowsError(try await provider.syncGet(identity: identity, location: path.pathString), \"should throw error\") { error in\n                    XCTAssertEqual(error as? GitHubPackageMetadataProviderError, .invalidSourceControlURL(path.pathString))\n                }\n            }\n        }\n    }\n\n    func testForRealz() async throws {\n        #if ENABLE_GITHUB_NETWORK_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        let repoURL = SourceControlURL(\"https://github.com/apple/swift-numerics.git\")\n\n        let httpClient = LegacyHTTPClient()\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        httpClient.configuration.requestHeaders = .init()\n        httpClient.configuration.requestHeaders!.add(name: \"Cache-Control\", value: \"no-cache\")\n        var configuration = GitHubPackageMetadataProvider.Configuration(disableCache: true) // Disable cache so we hit the API\n        if let token = Environment.current[\"GITHUB_API_TOKEN\"] {\n            configuration.authTokens = { [.github(\"github.com\"): token] }\n        }\n        configuration.apiLimitWarningThreshold = 50\n        let provider = GitHubPackageMetadataProvider(configuration: configuration, httpClient: httpClient)\n        defer { XCTAssertNoThrow(try provider.close()) }\n\n        for _ in 0 ... 60 {\n            let metadata = try await provider.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString)\n            XCTAssertNotNil(metadata)\n            XCTAssert(metadata.versions.count > 0)\n            XCTAssert(metadata.keywords!.count > 0)\n            XCTAssertNotNil(metadata.license)\n            XCTAssert(metadata.authors!.count > 0)\n        }\n    }\n}\n\ninternal extension GitHubPackageMetadataProvider {\n    init(configuration: Configuration = .init(), httpClient: LegacyHTTPClient? = nil) {\n        self.init(\n            configuration: configuration,\n            observabilityScope: ObservabilitySystem.NOOP,\n            httpClient: httpClient\n        )\n    }\n}\n\nprivate extension GitHubPackageMetadataProvider {\n    func syncGet(identity: PackageIdentity, location: String) async throws -> Model.PackageBasicMetadata {\n        try await self.get(identity: identity, location: location).0.get()\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/JSONPackageCollectionProviderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport XCTest\n\nimport Basics\n@testable import PackageCollections\nimport PackageCollectionsSigning\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\n\nclass JSONPackageCollectionProviderTests: XCTestCase {\n    func testGood() async throws {\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good.json\")\n            let url = URL(\"https://www.test.com/collection.json\")\n            let data: Data = try localFileSystem.readFileContents(path)\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertEqual(request.url, url, \"url should match\")\n                switch request.method {\n                case .head:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n                case .get:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                              body: data)))\n                default:\n                    XCTFail(\"method should match\")\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n            let collection = try await provider.get(source)\n\n            XCTAssertEqual(collection.name, \"Sample Package Collection\")\n            XCTAssertEqual(collection.overview, \"This is a sample package collection listing made-up packages.\")\n            XCTAssertEqual(collection.keywords, [\"sample package collection\"])\n            XCTAssertEqual(collection.createdBy?.name, \"Jane Doe\")\n            XCTAssertEqual(collection.packages.count, 2)\n\n            let package = collection.packages.first!\n            XCTAssertEqual(package.identity, PackageIdentity.plain(\"repos.one\"))\n            XCTAssertEqual(package.location, \"https://www.example.com/repos/RepoOne.git\")\n            XCTAssertEqual(package.summary, \"Package One\")\n            XCTAssertEqual(package.keywords, [\"sample package\"])\n            XCTAssertEqual(package.readmeURL, \"https://www.example.com/repos/RepoOne/README\")\n            XCTAssertEqual(package.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(package.versions.count, 1)\n            let version = package.versions.first!\n            XCTAssertEqual(version.summary, \"Fixed a few bugs\")\n            let manifest = version.manifests.values.first!\n            XCTAssertEqual(manifest.packageName, \"PackageOne\")\n            XCTAssertEqual(manifest.targets, [.init(name: \"Foo\", moduleName: \"Foo\")])\n            XCTAssertEqual(manifest.products, [.init(name: \"Foo\", type: .library(.automatic), targets: [.init(name: \"Foo\", moduleName: \"Foo\")])])\n            XCTAssertEqual(manifest.toolsVersion, ToolsVersion(string: \"5.1\")!)\n            XCTAssertEqual(manifest.minimumPlatformVersions, [SupportedPlatform(platform: .macOS, version: .init(\"10.15\"))])\n            XCTAssertEqual(version.verifiedCompatibility?.count, 3)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.platform, .macOS)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.swiftVersion, SwiftLanguageVersion(string: \"5.1\")!)\n            XCTAssertEqual(version.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(version.author?.username, \"J. Appleseed\")\n            XCTAssertEqual(version.signer?.commonName, \"J. Appleseed\")\n            XCTAssertNotNil(version.createdAt)\n            XCTAssertFalse(collection.isSigned)\n\n            XCTAssertEqual(collection.packages[1].identity, .init(urlString: \"https://www.example.com/repos/RepoTwo.git\"))\n\n            // \"1.8.3\" is originally \"v1.8.3\"\n            XCTAssertEqual([\"2.1.0\", \"1.8.3\"], collection.packages[1].versions.map { $0.version.description })\n        }\n    }\n\n    func testLocalFile() async throws {\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good.json\")\n\n            let httpClient = LegacyHTTPClient(handler: { (_, _, _) -> Void in fatalError(\"should not be called\") })\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: path.asURL)\n            let collection = try await provider.get(source)\n\n            XCTAssertEqual(collection.name, \"Sample Package Collection\")\n            XCTAssertEqual(collection.overview, \"This is a sample package collection listing made-up packages.\")\n            XCTAssertEqual(collection.keywords, [\"sample package collection\"])\n            XCTAssertEqual(collection.createdBy?.name, \"Jane Doe\")\n            XCTAssertEqual(collection.packages.count, 2)\n\n            let package = collection.packages.first!\n            XCTAssertEqual(package.identity, PackageIdentity.plain(\"repos.one\"))\n            XCTAssertEqual(package.location, \"https://www.example.com/repos/RepoOne.git\")\n            XCTAssertEqual(package.summary, \"Package One\")\n            XCTAssertEqual(package.keywords, [\"sample package\"])\n            XCTAssertEqual(package.readmeURL, \"https://www.example.com/repos/RepoOne/README\")\n            XCTAssertEqual(package.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(package.versions.count, 1)\n            let version = package.versions.first!\n            let manifest = version.manifests.values.first!\n            XCTAssertEqual(manifest.packageName, \"PackageOne\")\n            XCTAssertEqual(manifest.targets, [.init(name: \"Foo\", moduleName: \"Foo\")])\n            XCTAssertEqual(manifest.products, [.init(name: \"Foo\", type: .library(.automatic), targets: [.init(name: \"Foo\", moduleName: \"Foo\")])])\n            XCTAssertEqual(manifest.toolsVersion, ToolsVersion(string: \"5.1\")!)\n            XCTAssertEqual(manifest.minimumPlatformVersions, [SupportedPlatform(platform: .macOS, version: .init(\"10.15\"))])\n            XCTAssertEqual(version.verifiedCompatibility?.count, 3)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.platform, .macOS)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.swiftVersion, SwiftLanguageVersion(string: \"5.1\")!)\n            XCTAssertEqual(version.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(version.author?.username, \"J. Appleseed\")\n            XCTAssertEqual(version.signer?.commonName, \"J. Appleseed\")\n            XCTAssertNotNil(version.createdAt)\n            XCTAssertFalse(collection.isSigned)\n\n            XCTAssertEqual(collection.packages[1].identity, .init(urlString: \"https://www.example.com/repos/RepoTwo.git\"))\n\n            // \"1.8.3\" is originally \"v1.8.3\"\n            XCTAssertEqual([\"2.1.0\", \"1.8.3\"], collection.packages[1].versions.map { $0.version.description })\n        }\n    }\n\n    func testInvalidURL() async throws {\n        let url = URL(\"ftp://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n        let httpClient = LegacyHTTPClient(handler: { (_, _, _) -> Void in fatalError(\"should not be called\") })\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let provider = JSONPackageCollectionProvider(httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            guard case .invalidSource(let errorMessage) = error as? JSONPackageCollectionProviderError else {\n                return XCTFail(\"invalid error \\(error)\")\n            }\n            XCTAssertTrue(errorMessage.contains(\"Scheme (\\\"ftp\\\") not allowed: \\(url.absoluteString)\"))\n        })\n    }\n\n    func testExceedsDownloadSizeLimitHead() async throws {\n        let maxSize: Int64 = 50\n        let url = URL(\"https://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertEqual(request.method, .head, \"method should match\")\n            completion(.success(.init(statusCode: 200,\n                                      headers: .init([.init(name: \"Content-Length\", value: \"\\(maxSize * 2)\")]))))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let configuration = JSONPackageCollectionProvider.Configuration(maximumSizeInBytes: 10)\n        let provider = JSONPackageCollectionProvider(configuration: configuration, httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? JSONPackageCollectionProviderError, .responseTooLarge(url, maxSize * 2))\n        })\n    }\n\n    func testExceedsDownloadSizeLimitGet() async throws {\n        let maxSize: Int64 = 50\n        let url = URL(\"https://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            switch request.method {\n            case .head:\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"0\")]))))\n            case .get:\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"\\(maxSize * 2)\")]))))\n            default:\n                XCTFail(\"method should match\")\n            }\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let configuration = JSONPackageCollectionProvider.Configuration(maximumSizeInBytes: 10)\n        let provider = JSONPackageCollectionProvider(configuration: configuration, httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? JSONPackageCollectionProviderError, .responseTooLarge(url, maxSize * 2))\n        })\n    }\n\n    func testNoContentLengthOnGet() async throws {\n        let url = URL(\"https://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertTrue([.head, .get].contains(request.method), \"method should match\")\n            completion(.success(.init(statusCode: 200)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let configuration = JSONPackageCollectionProvider.Configuration(maximumSizeInBytes: 10)\n        let provider = JSONPackageCollectionProvider(configuration: configuration, httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? JSONPackageCollectionProviderError, .invalidResponse(url, \"Missing Content-Length header\"))\n        })\n    }\n\n    func testExceedsDownloadSizeLimitProgress() async throws {\n        let maxSize: Int64 = 50\n        let url = URL(\"https://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n        let handler: LegacyHTTPClient.Handler = { request, progress, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            switch request.method {\n            case .head:\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"0\")]))))\n            case .get:\n                do {\n                    try progress?(Int64(maxSize * 2), 0)\n                } catch {\n                    completion(.failure(error))\n                }\n            default:\n                XCTFail(\"method should match\")\n            }\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let configuration = JSONPackageCollectionProvider.Configuration(maximumSizeInBytes: 10)\n        let provider = JSONPackageCollectionProvider(configuration: configuration, httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? HTTPClientError, .responseTooLarge(maxSize * 2))\n        })\n    }\n\n    func testUnsuccessfulHead_unavailable() async throws {\n        let url = URL(\"https://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n        let statusCode = Int.random(in: 500 ... 550) // Don't use 404 because it leads to a different error message\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertEqual(request.method, .head, \"method should match\")\n            completion(.success(.init(statusCode: statusCode)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let provider = JSONPackageCollectionProvider(httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? JSONPackageCollectionProviderError, .collectionUnavailable(url, statusCode))\n        })\n    }\n\n    func testUnsuccessfulGet_unavailable() async throws {\n        let url = URL(\"https://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n        let statusCode = Int.random(in: 500 ... 550) // Don't use 404 because it leads to a different error message\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            switch request.method {\n            case .head:\n                completion(.success(.init(statusCode: 200, headers: .init([.init(name: \"Content-Length\", value: \"1\")]))))\n            case .get:\n                completion(.success(.init(statusCode: statusCode)))\n            default:\n                XCTFail(\"method should match\")\n            }\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let provider = JSONPackageCollectionProvider(httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? JSONPackageCollectionProviderError, .collectionUnavailable(url, statusCode))\n        })\n    }\n\n    func testUnsuccessfulHead_notFound() async throws {\n        let url = URL(\"https://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            XCTAssertEqual(request.method, .head, \"method should match\")\n            completion(.success(.init(statusCode: 404)))\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let provider = JSONPackageCollectionProvider(httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? JSONPackageCollectionProviderError, .collectionNotFound(url))\n        })\n    }\n\n    func testUnsuccessfulGet_notFound() async throws {\n        let url = URL(\"https://www.test.com/collection.json\")\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            switch request.method {\n            case .head:\n                completion(.success(.init(statusCode: 200, headers: .init([.init(name: \"Content-Length\", value: \"1\")]))))\n            case .get:\n                completion(.success(.init(statusCode: 404)))\n            default:\n                XCTFail(\"method should match\")\n            }\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let provider = JSONPackageCollectionProvider(httpClient: httpClient)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? JSONPackageCollectionProviderError, .collectionNotFound(url))\n        })\n    }\n\n    func testBadJSON() async throws {\n        let url = URL(\"https://www.test.com/collection.json\")\n        let data = Data(\"blah\".utf8)\n\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            XCTAssertEqual(request.url, url, \"url should match\")\n            switch request.method {\n            case .head:\n                completion(.success(.init(statusCode: 200, headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n            case .get:\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                          body: data)))\n            default:\n                XCTFail(\"method should match\")\n            }\n        }\n\n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n        let provider = JSONPackageCollectionProvider(httpClient: httpClient)\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n        await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n            XCTAssertEqual(error as? JSONPackageCollectionProviderError, .invalidJSON(url))\n        })\n    }\n\n    func testSignedGood() async throws {\n        try skipIfSignatureCheckNotSupported()\n\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good_signed.json\")\n            let url = URL(\"https://www.test.com/collection.json\")\n            let data: Data = try localFileSystem.readFileContents(path)\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertEqual(request.url, url, \"url should match\")\n                switch request.method {\n                case .head:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n                case .get:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                              body: data)))\n                default:\n                    XCTFail(\"method should match\")\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n\n            // Mark collection as having valid signature\n            let signatureValidator = MockCollectionSignatureValidator([\"Sample Package Collection\"])\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n            let collection = try await provider.get(source)\n\n            XCTAssertEqual(collection.name, \"Sample Package Collection\")\n            XCTAssertEqual(collection.overview, \"This is a sample package collection listing made-up packages.\")\n            XCTAssertEqual(collection.keywords, [\"sample package collection\"])\n            XCTAssertEqual(collection.createdBy?.name, \"Jane Doe\")\n            XCTAssertEqual(collection.packages.count, 2)\n\n            let package = collection.packages.first!\n            XCTAssertEqual(package.identity, PackageIdentity.plain(\"repos.one\"))\n            XCTAssertEqual(package.location, \"https://www.example.com/repos/RepoOne.git\")\n            XCTAssertEqual(package.summary, \"Package One\")\n            XCTAssertEqual(package.keywords, [\"sample package\"])\n            XCTAssertEqual(package.readmeURL, \"https://www.example.com/repos/RepoOne/README\")\n            XCTAssertEqual(package.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(package.versions.count, 1)\n            let version = package.versions.first!\n            XCTAssertEqual(version.summary, \"Fixed a few bugs\")\n            let manifest = version.manifests.values.first!\n            XCTAssertEqual(manifest.packageName, \"PackageOne\")\n            XCTAssertEqual(manifest.targets, [.init(name: \"Foo\", moduleName: \"Foo\")])\n            XCTAssertEqual(manifest.products, [.init(name: \"Foo\", type: .library(.automatic), targets: [.init(name: \"Foo\", moduleName: \"Foo\")])])\n            XCTAssertEqual(manifest.toolsVersion, ToolsVersion(string: \"5.1\")!)\n            XCTAssertEqual(manifest.minimumPlatformVersions, [SupportedPlatform(platform: .macOS, version: .init(\"10.15\"))])\n            XCTAssertEqual(version.verifiedCompatibility?.count, 3)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.platform, .macOS)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.swiftVersion, SwiftLanguageVersion(string: \"5.1\")!)\n            XCTAssertEqual(version.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(version.author?.username, \"J. Appleseed\")\n            XCTAssertEqual(version.signer?.commonName, \"J. Appleseed\")\n            XCTAssertNotNil(version.createdAt)\n            XCTAssertTrue(collection.isSigned)\n            let signature = collection.signature!\n            XCTAssertTrue(signature.isVerified)\n            XCTAssertEqual(\"Sample Subject\", signature.certificate.subject.commonName)\n            XCTAssertEqual(\"Sample Issuer\", signature.certificate.issuer.commonName)\n\n            XCTAssertEqual(collection.packages[1].identity, .init(urlString: \"https://www.example.com/repos/RepoTwo.git\"))\n\n            // \"1.8.3\" is originally \"v1.8.3\"\n            XCTAssertEqual([\"2.1.0\", \"1.8.3\"], collection.packages[1].versions.map { $0.version.description })\n        }\n    }\n\n    func testSigned_skipSignatureCheck() async throws {\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good_signed.json\")\n            let url = URL(\"https://www.test.com/collection.json\")\n            let data: Data = try localFileSystem.readFileContents(path)\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertEqual(request.url, url, \"url should match\")\n                switch request.method {\n                case .head:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n                case .get:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                              body: data)))\n                default:\n                    XCTFail(\"method should match\")\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n\n            let signatureValidator = MockCollectionSignatureValidator()\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator)\n            // Skip signature check\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: url, skipSignatureCheck: true)\n            let collection = try await provider.get(source)\n\n            XCTAssertEqual(collection.name, \"Sample Package Collection\")\n            XCTAssertEqual(collection.overview, \"This is a sample package collection listing made-up packages.\")\n            XCTAssertEqual(collection.keywords, [\"sample package collection\"])\n            XCTAssertEqual(collection.createdBy?.name, \"Jane Doe\")\n            XCTAssertEqual(collection.packages.count, 2)\n            let package = collection.packages.first!\n            XCTAssertEqual(package.identity, PackageIdentity.plain(\"repos.one\"))\n            XCTAssertEqual(package.location, \"https://www.example.com/repos/RepoOne.git\")\n            XCTAssertEqual(package.summary, \"Package One\")\n            XCTAssertEqual(package.keywords, [\"sample package\"])\n            XCTAssertEqual(package.readmeURL, \"https://www.example.com/repos/RepoOne/README\")\n            XCTAssertEqual(package.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(package.versions.count, 1)\n            let version = package.versions.first!\n            XCTAssertEqual(version.summary, \"Fixed a few bugs\")\n            let manifest = version.manifests.values.first!\n            XCTAssertEqual(manifest.packageName, \"PackageOne\")\n            XCTAssertEqual(manifest.targets, [.init(name: \"Foo\", moduleName: \"Foo\")])\n            XCTAssertEqual(manifest.products, [.init(name: \"Foo\", type: .library(.automatic), targets: [.init(name: \"Foo\", moduleName: \"Foo\")])])\n            XCTAssertEqual(manifest.toolsVersion, ToolsVersion(string: \"5.1\")!)\n            XCTAssertEqual(manifest.minimumPlatformVersions, [SupportedPlatform(platform: .macOS, version: .init(\"10.15\"))])\n            XCTAssertEqual(version.verifiedCompatibility?.count, 3)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.platform, .macOS)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.swiftVersion, SwiftLanguageVersion(string: \"5.1\")!)\n            XCTAssertEqual(version.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(version.author?.username, \"J. Appleseed\")\n            XCTAssertEqual(version.signer?.commonName, \"J. Appleseed\")\n            XCTAssertNotNil(version.createdAt)\n            XCTAssertTrue(collection.isSigned)\n            let signature = collection.signature!\n            XCTAssertFalse(signature.isVerified)\n            XCTAssertEqual(\"Sample Subject\", signature.certificate.subject.commonName)\n            XCTAssertEqual(\"Sample Issuer\", signature.certificate.issuer.commonName)\n\n            XCTAssertEqual(collection.packages[1].identity, .init(urlString: \"https://www.example.com/repos/RepoTwo.git\"))\n        }\n    }\n\n    func testSigned_noTrustedRootCertsConfigured() async throws {\n        try skipIfSignatureCheckNotSupported()\n\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good_signed.json\")\n            let url = URL(\"https://www.test.com/collection.json\")\n            let data: Data = try localFileSystem.readFileContents(path)\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertEqual(request.url, url, \"url should match\")\n                switch request.method {\n                case .head:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n                case .get:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                              body: data)))\n                default:\n                    XCTFail(\"method should match\")\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n\n            let signatureValidator = MockCollectionSignatureValidator(hasTrustedRootCerts: false)\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n            await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n                switch error {\n                case PackageCollectionError.cannotVerifySignature:\n                    break\n                default:\n                    XCTFail(\"unexpected error \\(error)\")\n                }\n            })\n        }\n    }\n\n    func testSignedBad() async throws {\n        try skipIfSignatureCheckNotSupported()\n\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good_signed.json\")\n            let url = URL(\"https://www.test.com/collection.json\")\n            let data: Data = try localFileSystem.readFileContents(path)\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertEqual(request.url, url, \"url should match\")\n                switch request.method {\n                case .head:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n                case .get:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                              body: data)))\n                default:\n                    XCTFail(\"method should match\")\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n\n            // The validator doesn't know about the test collection so its signature would be considered invalid\n            let signatureValidator = MockCollectionSignatureValidator()\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n            await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n                switch error {\n                case PackageCollectionError.invalidSignature:\n                    break\n                default:\n                    XCTFail(\"unexpected error \\(error)\")\n                }\n            })\n        }\n    }\n\n    func testSignedLocalFile() async throws {\n        try skipIfSignatureCheckNotSupported()\n\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good_signed.json\")\n\n            let httpClient = LegacyHTTPClient(handler: { (_, _, _) -> Void in fatalError(\"should not be called\") })\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n\n            // Mark collection as having valid signature\n            let signatureValidator = MockCollectionSignatureValidator([\"Sample Package Collection\"])\n\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: path.asURL)\n            let collection = try await provider.get(source)\n\n            XCTAssertEqual(collection.name, \"Sample Package Collection\")\n            XCTAssertEqual(collection.overview, \"This is a sample package collection listing made-up packages.\")\n            XCTAssertEqual(collection.keywords, [\"sample package collection\"])\n            XCTAssertEqual(collection.createdBy?.name, \"Jane Doe\")\n            XCTAssertEqual(collection.packages.count, 2)\n            let package = collection.packages.first!\n            XCTAssertEqual(package.identity, PackageIdentity.plain(\"repos.one\"))\n            XCTAssertEqual(package.location, \"https://www.example.com/repos/RepoOne.git\")\n            XCTAssertEqual(package.summary, \"Package One\")\n            XCTAssertEqual(package.keywords, [\"sample package\"])\n            XCTAssertEqual(package.readmeURL, \"https://www.example.com/repos/RepoOne/README\")\n            XCTAssertEqual(package.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(package.versions.count, 1)\n            let version = package.versions.first!\n            let manifest = version.manifests.values.first!\n            XCTAssertEqual(manifest.packageName, \"PackageOne\")\n            XCTAssertEqual(manifest.targets, [.init(name: \"Foo\", moduleName: \"Foo\")])\n            XCTAssertEqual(manifest.products, [.init(name: \"Foo\", type: .library(.automatic), targets: [.init(name: \"Foo\", moduleName: \"Foo\")])])\n            XCTAssertEqual(manifest.toolsVersion, ToolsVersion(string: \"5.1\")!)\n            XCTAssertEqual(manifest.minimumPlatformVersions, [SupportedPlatform(platform: .macOS, version: .init(\"10.15\"))])\n            XCTAssertEqual(version.verifiedCompatibility?.count, 3)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.platform, .macOS)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.swiftVersion, SwiftLanguageVersion(string: \"5.1\")!)\n            XCTAssertEqual(version.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(version.author?.username, \"J. Appleseed\")\n            XCTAssertEqual(version.signer?.commonName, \"J. Appleseed\")\n            XCTAssertNotNil(version.createdAt)\n            XCTAssertTrue(collection.isSigned)\n            let signature = collection.signature!\n            XCTAssertTrue(signature.isVerified)\n            XCTAssertEqual(\"Sample Subject\", signature.certificate.subject.commonName)\n            XCTAssertEqual(\"Sample Issuer\", signature.certificate.issuer.commonName)\n\n            XCTAssertEqual(collection.packages[1].identity, .init(urlString: \"https://www.example.com/repos/RepoTwo.git\"))\n        }\n    }\n\n    func testRequiredSigningGood() async throws {\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good_signed.json\")\n            let url = URL(\"https://www.test.com/collection.json\")\n            let data: Data = try localFileSystem.readFileContents(path)\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertEqual(request.url, url, \"url should match\")\n                switch request.method {\n                case .head:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n                case .get:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                              body: data)))\n                default:\n                    XCTFail(\"method should match\")\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n\n            // Mark collection as having valid signature\n            let signatureValidator = MockCollectionSignatureValidator([\"Sample Package Collection\"])\n            // Collections from www.test.com must be signed\n            let sourceCertPolicy = PackageCollectionSourceCertificatePolicy(\n                sourceCertPolicies: [\"www.test.com\": [.init(certPolicyKey: CertificatePolicyKey.default, base64EncodedRootCerts: nil)]]\n            )\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator,\n                                                         sourceCertPolicy: sourceCertPolicy)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n            let collection = try await provider.get(source)\n\n            XCTAssertEqual(collection.name, \"Sample Package Collection\")\n            XCTAssertEqual(collection.overview, \"This is a sample package collection listing made-up packages.\")\n            XCTAssertEqual(collection.keywords, [\"sample package collection\"])\n            XCTAssertEqual(collection.createdBy?.name, \"Jane Doe\")\n            XCTAssertEqual(collection.packages.count, 2)\n            let package = collection.packages.first!\n            XCTAssertEqual(package.identity, PackageIdentity.plain(\"repos.one\"))\n            XCTAssertEqual(package.location, \"https://www.example.com/repos/RepoOne.git\")\n            XCTAssertEqual(package.summary, \"Package One\")\n            XCTAssertEqual(package.keywords, [\"sample package\"])\n            XCTAssertEqual(package.readmeURL, \"https://www.example.com/repos/RepoOne/README\")\n            XCTAssertEqual(package.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(package.versions.count, 1)\n            let version = package.versions.first!\n            XCTAssertEqual(version.summary, \"Fixed a few bugs\")\n            let manifest = version.manifests.values.first!\n            XCTAssertEqual(manifest.packageName, \"PackageOne\")\n            XCTAssertEqual(manifest.targets, [.init(name: \"Foo\", moduleName: \"Foo\")])\n            XCTAssertEqual(manifest.products, [.init(name: \"Foo\", type: .library(.automatic), targets: [.init(name: \"Foo\", moduleName: \"Foo\")])])\n            XCTAssertEqual(manifest.toolsVersion, ToolsVersion(string: \"5.1\")!)\n            XCTAssertEqual(manifest.minimumPlatformVersions, [SupportedPlatform(platform: .macOS, version: .init(\"10.15\"))])\n            XCTAssertEqual(version.verifiedCompatibility?.count, 3)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.platform, .macOS)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.swiftVersion, SwiftLanguageVersion(string: \"5.1\")!)\n            XCTAssertEqual(version.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(version.author?.username, \"J. Appleseed\")\n            XCTAssertEqual(version.signer?.commonName, \"J. Appleseed\")\n            XCTAssertNotNil(version.createdAt)\n            XCTAssertTrue(collection.isSigned)\n            let signature = collection.signature!\n            XCTAssertTrue(signature.isVerified)\n            XCTAssertEqual(\"Sample Subject\", signature.certificate.subject.commonName)\n            XCTAssertEqual(\"Sample Issuer\", signature.certificate.issuer.commonName)\n\n            XCTAssertEqual(collection.packages[1].identity, .init(urlString: \"https://www.example.com/repos/RepoTwo.git\"))\n        }\n    }\n\n    func testRequiredSigningMultiplePoliciesGood() async throws {\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good_signed.json\")\n            let url = URL(\"https://www.test.com/collection.json\")\n            let data: Data = try localFileSystem.readFileContents(path)\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertEqual(request.url, url, \"url should match\")\n                switch request.method {\n                case .head:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n                case .get:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                              body: data)))\n                default:\n                    XCTFail(\"method should match\")\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n\n            // Mark collection as having valid signature\n            let signatureValidator = MockCollectionSignatureValidator(certPolicyKeys: [CertificatePolicyKey.default(subjectUserID: \"test\")])\n            // Collections from www.test.com must be signed\n            let sourceCertPolicy = PackageCollectionSourceCertificatePolicy(\n                sourceCertPolicies: [\n                    \"www.test.com\": [\n                        .init(certPolicyKey: CertificatePolicyKey.default, base64EncodedRootCerts: nil),\n                        .init(certPolicyKey: CertificatePolicyKey.default(subjectUserID: \"test\"), base64EncodedRootCerts: nil),\n                    ],\n                ]\n            )\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator,\n                                                         sourceCertPolicy: sourceCertPolicy)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n            let collection = try await provider.get(source)\n\n            XCTAssertEqual(collection.name, \"Sample Package Collection\")\n            XCTAssertEqual(collection.overview, \"This is a sample package collection listing made-up packages.\")\n            XCTAssertEqual(collection.keywords, [\"sample package collection\"])\n            XCTAssertEqual(collection.createdBy?.name, \"Jane Doe\")\n            XCTAssertEqual(collection.packages.count, 2)\n            let package = collection.packages.first!\n            XCTAssertEqual(package.identity, PackageIdentity.plain(\"repos.one\"))\n            XCTAssertEqual(package.location, \"https://www.example.com/repos/RepoOne.git\")\n            XCTAssertEqual(package.summary, \"Package One\")\n            XCTAssertEqual(package.keywords, [\"sample package\"])\n            XCTAssertEqual(package.readmeURL, \"https://www.example.com/repos/RepoOne/README\")\n            XCTAssertEqual(package.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(package.versions.count, 1)\n            let version = package.versions.first!\n            XCTAssertEqual(version.summary, \"Fixed a few bugs\")\n            let manifest = version.manifests.values.first!\n            XCTAssertEqual(manifest.packageName, \"PackageOne\")\n            XCTAssertEqual(manifest.targets, [.init(name: \"Foo\", moduleName: \"Foo\")])\n            XCTAssertEqual(manifest.products, [.init(name: \"Foo\", type: .library(.automatic), targets: [.init(name: \"Foo\", moduleName: \"Foo\")])])\n            XCTAssertEqual(manifest.toolsVersion, ToolsVersion(string: \"5.1\")!)\n            XCTAssertEqual(manifest.minimumPlatformVersions, [SupportedPlatform(platform: .macOS, version: .init(\"10.15\"))])\n            XCTAssertEqual(version.verifiedCompatibility?.count, 3)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.platform, .macOS)\n            XCTAssertEqual(version.verifiedCompatibility!.first!.swiftVersion, SwiftLanguageVersion(string: \"5.1\")!)\n            XCTAssertEqual(version.license, .init(type: .Apache2_0, url: \"https://www.example.com/repos/RepoOne/LICENSE\"))\n            XCTAssertEqual(version.author?.username, \"J. Appleseed\")\n            XCTAssertEqual(version.signer?.commonName, \"J. Appleseed\")\n            XCTAssertNotNil(version.createdAt)\n            XCTAssertTrue(collection.isSigned)\n            let signature = collection.signature!\n            XCTAssertTrue(signature.isVerified)\n            XCTAssertEqual(\"Sample Subject\", signature.certificate.subject.commonName)\n            XCTAssertEqual(\"Sample Issuer\", signature.certificate.issuer.commonName)\n\n            XCTAssertEqual(collection.packages[1].identity, .init(urlString: \"https://www.example.com/repos/RepoTwo.git\"))\n        }\n    }\n\n    func testMissingRequiredSignature() async throws {\n        try await fixtureXCTest(name: \"Collections\") { fixturePath in\n            let path = fixturePath.appending(components: \"JSON\", \"good.json\")\n            let url = URL(\"https://www.test.com/collection.json\")\n            let data: Data = try localFileSystem.readFileContents(path)\n\n            let handler: LegacyHTTPClient.Handler = { request, _, completion in\n                XCTAssertEqual(request.url, url, \"url should match\")\n                switch request.method {\n                case .head:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]))))\n                case .get:\n                    completion(.success(.init(statusCode: 200,\n                                              headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                              body: data)))\n                default:\n                    XCTFail(\"method should match\")\n                }\n            }\n\n            let httpClient = LegacyHTTPClient(handler: handler)\n            httpClient.configuration.circuitBreakerStrategy = .none\n            httpClient.configuration.retryStrategy = .none\n\n            // The validator doesn't know about the test collection so its signature would be considered invalid\n            let signatureValidator = MockCollectionSignatureValidator()\n            // Collections from www.test.com must be signed\n            let sourceCertPolicy = PackageCollectionSourceCertificatePolicy(\n                sourceCertPolicies: [\"www.test.com\": [.init(certPolicyKey: CertificatePolicyKey.default, base64EncodedRootCerts: nil)]]\n            )\n            let provider = JSONPackageCollectionProvider(httpClient: httpClient, signatureValidator: signatureValidator,\n                                                         sourceCertPolicy: sourceCertPolicy)\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: url)\n\n            await XCTAssertAsyncThrowsError(try await provider.get(source), \"expected error\", { error in\n                switch error {\n                case PackageCollectionError.missingSignature:\n                    break\n                default:\n                    XCTFail(\"unexpected error \\(error)\")\n                }\n            })\n        }\n    }\n}\n\nprivate extension XCTestCase {\n    func skipIfSignatureCheckNotSupported() throws {\n        if !JSONPackageCollectionProvider.isSignatureCheckSupported {\n            throw XCTSkip(\"Skipping test because signature check is not supported\")\n        }\n    }\n}\n\ninternal extension JSONPackageCollectionProvider {\n    init(\n        configuration: Configuration = .init(),\n        httpClient: LegacyHTTPClient? = nil,\n        signatureValidator: PackageCollectionSignatureValidator? = nil,\n        sourceCertPolicy: PackageCollectionSourceCertificatePolicy = PackageCollectionSourceCertificatePolicy(),\n        fileSystem: FileSystem = localFileSystem\n    ) {\n        self.init(\n            configuration: configuration,\n            fileSystem: fileSystem,\n            observabilityScope: ObservabilitySystem.NOOP,\n            sourceCertPolicy: sourceCertPolicy,\n            customHTTPClient: httpClient ,\n            customSignatureValidator: signatureValidator\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageCollectionSourceCertificatePolicyTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport XCTest\n\n@testable import PackageCollections\nimport PackageCollectionsSigning\n\nfinal class PackageCollectionSourceCertificatePolicyTests: XCTestCase {\n    func testCustomData() {\n        let sourceCertPolicy = PackageCollectionSourceCertificatePolicy(sourceCertPolicies: [\n            \"package-collection-1\": [\n                PackageCollectionSourceCertificatePolicy.CertificatePolicyConfig(\n                    certPolicyKey: CertificatePolicyKey.default,\n                    base64EncodedRootCerts: [\"root-cert-1a\", \"root-cert-1b\"]\n                ),\n                PackageCollectionSourceCertificatePolicy.CertificatePolicyConfig(\n                    certPolicyKey: .default(subjectUserID: \"test\"),\n                    base64EncodedRootCerts: [\"root-cert-1c\"]\n                ),\n            ],\n            \"package-collection-2\": [PackageCollectionSourceCertificatePolicy.CertificatePolicyConfig(\n                certPolicyKey: CertificatePolicyKey.default,\n                base64EncodedRootCerts: [\"root-cert-2\"]\n            )],\n        ])\n        let source1 = Model.CollectionSource(type: .json, url: \"https://package-collection-1\")\n        let unsignedSource = Model.CollectionSource(type: .json, url: \"https://package-collection-unsigned\")\n\n        XCTAssertEqual([\"root-cert-1a\", \"root-cert-1b\", \"root-cert-1c\", \"root-cert-2\"], sourceCertPolicy.allRootCerts?.sorted())\n\n        XCTAssertTrue(sourceCertPolicy.mustBeSigned(source: source1))\n        XCTAssertFalse(sourceCertPolicy.mustBeSigned(source: unsignedSource))\n\n        XCTAssertEqual([.default, .default(subjectUserID: \"test\")], sourceCertPolicy.certificatePolicyKeys(for: source1))\n        XCTAssertNil(sourceCertPolicy.certificatePolicyKeys(for: unsignedSource))\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageCollectionValidationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport XCTest\n\n@testable import PackageCollections\n@testable import PackageCollectionsModel\nimport PackageModel\n\nclass PackageCollectionValidationTests: XCTestCase {\n    typealias Model = PackageCollectionModel.V1\n\n    func test_validationOK() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                    Model.Collection.Package.Version(\n                        version: \"v1.3.0\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        XCTAssertNil(validator.validate(collection: collection))\n    }\n\n    func test_validationFailed_noPackages() throws {\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: [],\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertTrue(messages[0].message.contains(\"contain at least one package\"))\n    }\n\n    func test_validationFailed_tooManyPackages() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobaz.git\",\n                summary: \"Package Foobaz\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobaz\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Baz\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator(configuration: .init(maximumPackageCount: 1))\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .warning = messages[0].level else {\n            return XCTFail(\"Expected .warning\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"more than the recommended\", options: .caseInsensitive))\n    }\n\n    func test_validationFailed_noVersions() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"does not have any versions\", options: .caseInsensitive))\n    }\n\n    func test_validationFailed_duplicateVersions_emptyProductsAndTargets() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [],\n                                products: [],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(3, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"duplicate version(s)\", options: .caseInsensitive))\n\n        guard case .error = messages[1].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[1].message.range(of: \"does not contain any products\", options: .caseInsensitive))\n\n        guard case .error = messages[2].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[2].message.range(of: \"does not contain any targets\", options: .caseInsensitive))\n    }\n\n    func test_validationFailed_nonSemanticVersion() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"x1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"non semantic version(s)\", options: .caseInsensitive))\n    }\n\n    func test_validationFailed_tooManyMajorsAndMinors() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"2.0.0\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobaz.git\",\n                summary: \"Package Foobaz\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.4.0\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobaz\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Baz\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobaz\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Baz\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator(configuration: .init(maximumMajorVersionCount: 1, maximumMinorVersionCount: 1))\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(2, messages.count)\n\n        guard case .warning = messages[0].level else {\n            return XCTFail(\"Expected .warning\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"too many major versions\", options: .caseInsensitive))\n\n        guard case .warning = messages[1].level else {\n            return XCTFail(\"Expected .warning\")\n        }\n        XCTAssertNotNil(messages[1].message.range(of: \"too many minor versions\", options: .caseInsensitive))\n    }\n\n    func test_validationFailed_versionEmptyManifests() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [:],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"does not have any manifests\", options: .caseInsensitive))\n    }\n\n    func test_validationFailed_versionProductNoTargets() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.2\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"does not contain any targets\", options: .caseInsensitive))\n    }\n\n    func test_validationFailed_manifestToolsVersionMismatch() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.1\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.1\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"manifest tools version 5.2 does not match 5.1\", options: .caseInsensitive))\n    }\n\n    func test_validationFailed_missingDefaultManifest() throws {\n        let packages = [\n            Model.Collection.Package(\n                url: \"https://package-collection-tests.com/repos/foobar.git\",\n                summary: \"Package Foobar\",\n                keywords: [\"test package\"],\n                versions: [\n                    Model.Collection.Package.Version(\n                        version: \"1.3.2\",\n                        summary: nil,\n                        manifests: [\n                            \"5.2\": Model.Collection.Package.Version.Manifest(\n                                toolsVersion: \"5.2\",\n                                packageName: \"Foobar\",\n                                targets: [.init(name: \"Foo\", moduleName: \"Foo\")],\n                                products: [.init(name: \"Bar\", type: .library(.automatic), targets: [\"Foo\"])],\n                                minimumPlatformVersions: nil\n                            ),\n                        ],\n                        defaultToolsVersion: \"5.1\",\n                        verifiedCompatibility: nil,\n                        license: nil,\n                        author: nil,\n                        signer: nil,\n                        createdAt: nil\n                    ),\n                ],\n                readmeURL: nil,\n                license: nil\n            ),\n        ]\n        let collection = Model.Collection(\n            name: \"Test Package Collection\",\n            overview: \"A test package collection\",\n            keywords: [\"swift packages\"],\n            packages: packages,\n            formatVersion: .v1_0,\n            revision: 3,\n            generatedAt: Date(),\n            generatedBy: .init(name: \"Jane Doe\")\n        )\n\n        let validator = Model.Validator()\n        let messages = validator.validate(collection: collection)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"missing the default manifest\", options: .caseInsensitive))\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageCollectionsModelTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import PackageCollections\n@testable import PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageCollectionsModelTests: XCTestCase {\n    func testLatestVersions() {\n        let targets = [PackageCollectionsModel.Target(name: \"Foo\", moduleName: \"Foo\")]\n        let products = [PackageCollectionsModel.Product(name: \"Foo\", type: .library(.automatic), targets: targets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let manifests = [toolsVersion: PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion, packageName: \"FooBar\", targets: targets, products: products, minimumPlatformVersions: nil\n        )]\n        let versions: [PackageCollectionsModel.Package.Version] = [\n            .init(version: .init(stringLiteral: \"1.2.0\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n            .init(version: .init(stringLiteral: \"2.0.1\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n            .init(version: .init(stringLiteral: \"2.1.0-beta.3\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n            .init(version: .init(stringLiteral: \"2.1.0\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n            .init(version: .init(stringLiteral: \"3.0.0-beta.1\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n        ]\n\n        XCTAssertEqual(\"2.1.0\", versions.latestRelease?.version.description)\n        XCTAssertEqual(\"3.0.0-beta.1\", versions.latestPrerelease?.version.description)\n    }\n\n    func testNoLatestReleaseVersion() {\n        let targets = [PackageCollectionsModel.Target(name: \"Foo\", moduleName: \"Foo\")]\n        let products = [PackageCollectionsModel.Product(name: \"Foo\", type: .library(.automatic), targets: targets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let manifests = [toolsVersion: PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion, packageName: \"FooBar\", targets: targets, products: products, minimumPlatformVersions: nil\n        )]\n        let versions: [PackageCollectionsModel.Package.Version] = [\n            .init(version: .init(stringLiteral: \"2.1.0-beta.3\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n            .init(version: .init(stringLiteral: \"3.0.0-beta.1\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n        ]\n\n        XCTAssertNil(versions.latestRelease)\n        XCTAssertEqual(\"3.0.0-beta.1\", versions.latestPrerelease?.version.description)\n    }\n\n    func testNoLatestPrereleaseVersion() {\n        let targets = [PackageCollectionsModel.Target(name: \"Foo\", moduleName: \"Foo\")]\n        let products = [PackageCollectionsModel.Product(name: \"Foo\", type: .library(.automatic), targets: targets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let manifests = [toolsVersion: PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion, packageName: \"FooBar\", targets: targets, products: products, minimumPlatformVersions: nil\n        )]\n        let versions: [PackageCollectionsModel.Package.Version] = [\n            .init(version: .init(stringLiteral: \"1.2.0\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n            .init(version: .init(stringLiteral: \"2.0.1\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n            .init(version: .init(stringLiteral: \"2.1.0\"), title: nil, summary: nil, manifests: manifests, defaultToolsVersion: toolsVersion, verifiedCompatibility: nil, license: nil, author: nil, signer: nil, createdAt: nil),\n        ]\n\n        XCTAssertEqual(\"2.1.0\", versions.latestRelease?.version.description)\n        XCTAssertNil(versions.latestPrerelease)\n    }\n\n    func testSourceValidation() throws {\n        let httpsSource = PackageCollectionsModel.CollectionSource(type: .json, url: \"https://feed.mock.io\")\n        XCTAssertNil(httpsSource.validate(fileSystem: localFileSystem), \"not expecting errors\")\n\n        let httpsSource2 = PackageCollectionsModel.CollectionSource(type: .json, url: \"HTTPS://feed.mock.io\")\n        XCTAssertNil(httpsSource2.validate(fileSystem: localFileSystem), \"not expecting errors\")\n\n        let httpsSource3 = PackageCollectionsModel.CollectionSource(type: .json, url: \"HttpS://feed.mock.io\")\n        XCTAssertNil(httpsSource3.validate(fileSystem: localFileSystem), \"not expecting errors\")\n\n        let httpSource = PackageCollectionsModel.CollectionSource(type: .json, url: \"http://feed.mock.io\")\n        XCTAssertEqual(httpSource.validate(fileSystem: localFileSystem)?.count, 1, \"expecting errors\")\n\n        let otherProtocolSource = PackageCollectionsModel.CollectionSource(type: .json, url: \"ftp://feed.mock.io\")\n        XCTAssertEqual(otherProtocolSource.validate(fileSystem: localFileSystem)?.count, 1, \"expecting errors\")\n\n        let brokenUrlSource = PackageCollectionsModel.CollectionSource(type: .json, url: \"blah\")\n        XCTAssertEqual(brokenUrlSource.validate(fileSystem: localFileSystem)?.count, 1, \"expecting errors\")\n    }\n\n    func testSourceValidation_localFile() throws {\n        try fixtureXCTest(name: \"Collections\") { fixturePath in\n            // File must exist in local FS\n            let path = fixturePath.appending(components: \"JSON\", \"good.json\")\n\n            let source = PackageCollectionsModel.CollectionSource(type: .json, url: path.asURL)\n            XCTAssertNil(source.validate(fileSystem: localFileSystem))\n        }\n    }\n\n    func testSourceValidation_localFileDoesNotExist() throws {\n        let source = PackageCollectionsModel.CollectionSource(type: .json, url: URL(fileURLWithPath: \"/foo/bar\"))\n\n        let messages = source.validate(fileSystem: localFileSystem)!\n        XCTAssertEqual(1, messages.count)\n\n        guard case .error = messages[0].level else {\n            return XCTFail(\"Expected .error\")\n        }\n        XCTAssertNotNil(messages[0].message.range(of: \"either a non-local path or the file does not exist\", options: .caseInsensitive))\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageCollectionsSourcesStorageTest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import PackageCollections\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageCollectionsSourcesStorageTest: XCTestCase {\n    func testHappyCase() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let storage = FilePackageCollectionsSourcesStorage(fileSystem: mockFileSystem)\n\n        try await assertHappyCase(storage: storage)\n\n        let buffer = try mockFileSystem.readFileContents(storage.path)\n        XCTAssertNotEqual(buffer.count, 0, \"expected file to be written\")\n    }\n\n    func testRealFile() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let fileSystem = localFileSystem\n            let path = tmpPath.appending(\"test.json\")\n            let storage = FilePackageCollectionsSourcesStorage(fileSystem: fileSystem, path: path)\n\n            try await assertHappyCase(storage: storage)\n\n            let buffer = try fileSystem.readFileContents(storage.path)\n            XCTAssertNotEqual(buffer.count, 0, \"expected file to be written\")\n        }\n    }\n\n    func assertHappyCase(storage: PackageCollectionsSourcesStorage) async throws {\n        let sources = makeMockSources()\n\n        for source in sources {\n            _ = try await storage.add(source: source, order: nil)\n        }\n\n        do {\n            let list = try await storage.list()\n            XCTAssertEqual(list.count, sources.count, \"sources should match\")\n        }\n\n        let remove = sources.enumerated().filter { index, _ in index % 2 == 0 }.map { $1 }\n        for source in remove {\n            _ = try await storage.remove(source: source)\n        }\n\n        do {\n            let list = try await storage.list()\n            XCTAssertEqual(list.count, sources.count - remove.count, \"sources should match\")\n        }\n\n        let remaining = sources.filter { !remove.contains($0) }\n        for source in sources {\n            try await XCTAssertAsyncTrue(try await storage.exists(source: source) == remaining.contains(source))\n        }\n\n        do {\n            _ = try await storage.move(source: remaining.last!, to: 0)\n            let list = try await storage.list()\n            XCTAssertEqual(list.count, remaining.count, \"sources should match\")\n            XCTAssertEqual(list.first, remaining.last, \"item should match\")\n        }\n\n        do {\n            _ = try await storage.move(source: remaining.last!, to: remaining.count - 1)\n            let list = try await storage.list()\n            XCTAssertEqual(list.count, remaining.count, \"sources should match\")\n            XCTAssertEqual(list.last, remaining.last, \"item should match\")\n        }\n\n        do {\n            let list = try await storage.list()\n            var source = list.first!\n            source.isTrusted = !(source.isTrusted ?? false)\n            _ = try await storage.update(source: source)\n            let listAfter = try await storage.list()\n            XCTAssertEqual(source.isTrusted, listAfter.first!.isTrusted, \"isTrusted should match\")\n        }\n\n        do {\n            let list = try await storage.list()\n            var source = list.first!\n            source.skipSignatureCheck = !source.skipSignatureCheck\n            _ = try await storage.update(source: source)\n            let listAfter = try await storage.list()\n            XCTAssertEqual(source.skipSignatureCheck, listAfter.first!.skipSignatureCheck, \"skipSignatureCheck should match\")\n        }\n    }\n\n    func testFileDeleted() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let storage = FilePackageCollectionsSourcesStorage(fileSystem: mockFileSystem)\n\n        let sources = makeMockSources()\n\n        for source in sources {\n            _ = try await storage.add(source: source, order: nil)\n        }\n\n        do {\n            let list = try await storage.list()\n            XCTAssertEqual(list.count, sources.count, \"collections should match\")\n        }\n\n        try mockFileSystem.removeFileTree(storage.path)\n        XCTAssertFalse(mockFileSystem.exists(storage.path), \"expected file to be deleted\")\n\n        do {\n            let list = try await storage.list()\n            XCTAssertEqual(list.count, 0, \"collections should match\")\n        }\n    }\n\n    func testFileEmpty() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let storage = FilePackageCollectionsSourcesStorage(fileSystem: mockFileSystem)\n\n        let sources = makeMockSources()\n\n        for source in sources {\n            _ = try await storage.add(source: source, order: nil)\n        }\n\n        do {\n            let list = try await storage.list()\n            XCTAssertEqual(list.count, sources.count, \"collections should match\")\n        }\n\n        try mockFileSystem.writeFileContents(storage.path, bytes: [])\n        let buffer = try mockFileSystem.readFileContents(storage.path)\n        XCTAssertEqual(buffer.count, 0, \"expected file to be empty\")\n\n        do {\n            let list = try await storage.list()\n            XCTAssertEqual(list.count, 0, \"collections should match\")\n        }\n    }\n\n    func testFileCorrupt() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let storage = FilePackageCollectionsSourcesStorage(fileSystem: mockFileSystem)\n\n        let sources = makeMockSources()\n\n        for source in sources {\n            _ = try await storage.add(source: source, order: nil)\n        }\n\n        let list = try await storage.list()\n        XCTAssertEqual(list.count, sources.count, \"collections should match\")\n\n        try mockFileSystem.writeFileContents(storage.path, string: \"{\")\n\n        let buffer = try mockFileSystem.readFileContents(storage.path)\n        XCTAssertNotEqual(buffer.count, 0, \"expected file to be written\")\n        print(buffer)\n\n        await XCTAssertAsyncThrowsError(try await storage.list(), \"expected an error\", { error in\n            XCTAssert(error is DecodingError, \"expected error to match\")\n        })\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageCollectionsStorageTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import PackageCollections\nimport _InternalTestSupport\nimport tsan_utils\nimport XCTest\n\nclass PackageCollectionsStorageTests: XCTestCase {\n    func testHappyCase() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            let storage = SQLitePackageCollectionsStorage(path: path)\n            defer { XCTAssertNoThrow(try storage.close()) }\n\n            let mockSources = makeMockSources()\n            for source in mockSources {\n                await XCTAssertAsyncThrowsError(try await storage.get(identifier: .init(from: source)), \"expected error\", { error in\n                    XCTAssert(error is NotFoundError, \"Expected NotFoundError\")\n                })\n            }\n\n            let mockCollections = makeMockCollections(count: 50)\n            for collection in mockCollections {\n                _ = try await storage.put(collection: collection)\n            }\n\n            for collection in mockCollections {\n                let retVal = try await storage.get(identifier: collection.identifier)\n                XCTAssertEqual(retVal.identifier, collection.identifier)\n            }\n\n            do {\n                let list = try await storage.list()\n                XCTAssertEqual(list.count, mockCollections.count)\n            }\n\n            do {\n                let count = Int.random(in: 1 ..< mockCollections.count)\n                let list = try await storage.list(identifiers: mockCollections.prefix(count).map { $0.identifier })\n                XCTAssertEqual(list.count, count)\n            }\n\n            do {\n                _ = try await storage.remove(identifier: mockCollections.first!.identifier)\n                let list = try await storage.list()\n                XCTAssertEqual(list.count, mockCollections.count - 1)\n            }\n\n            await XCTAssertAsyncThrowsError(try await storage.get(identifier: mockCollections.first!.identifier), \"expected error\", { error in\n                XCTAssert(error is NotFoundError, \"Expected NotFoundError\")\n            })\n\n            guard case .path(let storagePath) = storage.location else {\n                return XCTFail(\"invalid location \\(storage.location)\")\n            }\n\n            XCTAssertTrue(storage.fileSystem.exists(storagePath), \"expected file to be written\")\n        }\n    }\n\n    func testFileDeleted() async throws {\n        try XCTSkipOnWindows(because: \"open files cannot be deleted on Windows\")\n        try XCTSkipIf(is_tsan_enabled())\n\n        try await testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            let storage = SQLitePackageCollectionsStorage(path: path)\n            defer { XCTAssertNoThrow(try storage.close()) }\n\n            let mockCollections = makeMockCollections(count: 3)\n            for collection in mockCollections {\n                _ = try await storage.put(collection: collection)\n            }\n\n            for collection in mockCollections {\n                let retVal = try await storage.get(identifier: collection.identifier)\n                XCTAssertEqual(retVal.identifier, collection.identifier)\n            }\n\n            guard case .path(let storagePath) = storage.location else {\n                return XCTFail(\"invalid location \\(storage.location)\")\n            }\n\n            XCTAssertTrue(storage.fileSystem.exists(storagePath), \"expected file to exist at \\(storagePath)\")\n\n            try storage.fileSystem.removeFileTree(storagePath)\n            storage.resetCache()\n\n            await XCTAssertAsyncThrowsError(try await storage.get(identifier: mockCollections.first!.identifier), \"expected error\", { error in\n                XCTAssert(error is NotFoundError, \"Expected NotFoundError\")\n            })\n\n            _ = try await storage.put(collection: mockCollections.first!)\n            let retVal = try await storage.get(identifier: mockCollections.first!.identifier)\n            XCTAssertEqual(retVal.identifier, mockCollections.first!.identifier)\n\n            XCTAssertTrue(storage.fileSystem.exists(storagePath), \"expected file to exist at \\(storagePath)\")\n        }\n    }\n\n    func testFileCorrupt() async throws {\n        try XCTSkipOnWindows(because: \"open files cannot be deleted on Windows\")\n        try XCTSkipIf(is_tsan_enabled())\n\n        try await testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            let storage = SQLitePackageCollectionsStorage(path: path)\n            defer { XCTAssertNoThrow(try storage.close()) }\n\n            let mockCollections = makeMockCollections(count: 3)\n            for collection in mockCollections {\n                _ = try await storage.put(collection: collection)\n            }\n\n            for collection in mockCollections {\n                let retVal = try await storage.get(identifier: collection.identifier)\n                XCTAssertEqual(retVal.identifier, collection.identifier)\n            }\n\n            guard case .path(let storagePath) = storage.location else {\n                return XCTFail(\"invalid location \\(storage.location)\")\n            }\n\n            try storage.close()\n\n            XCTAssertTrue(storage.fileSystem.exists(storagePath), \"expected file to exist at \\(path)\")\n            try storage.fileSystem.writeFileContents(storagePath, string: \"blah\")\n\n            let storage2 = SQLitePackageCollectionsStorage(path: path)\n            defer { XCTAssertNoThrow(try storage2.close()) }\n            await XCTAssertAsyncThrowsError(try await storage2.get(identifier: mockCollections.first!.identifier), \"expected error\", { error in\n                XCTAssert(\"\\(error)\".contains(\"is not a database\"), \"Expected file is not a database error\")\n            })\n\n            await XCTAssertAsyncThrowsError(try await storage2.put(collection: mockCollections.first!), \"expected error\", { error in\n                XCTAssert(\"\\(error)\".contains(\"is not a database\"), \"Expected file is not a database error\")\n            })\n        }\n    }\n\n    func testListLessThanBatch() async throws {\n        var configuration = SQLitePackageCollectionsStorage.Configuration()\n        configuration.batchSize = 10\n        let storage = SQLitePackageCollectionsStorage(location: .memory, configuration: configuration)\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let count = configuration.batchSize / 2\n        let mockCollections = makeMockCollections(count: count)\n        for collection in mockCollections {\n            _ = try await storage.put(collection: collection)\n        }\n\n        let list = try await storage.list()\n        XCTAssertEqual(list.count, mockCollections.count)\n    }\n\n    func testListNonBatching() async throws {\n        var configuration = SQLitePackageCollectionsStorage.Configuration()\n        configuration.batchSize = 10\n        let storage = SQLitePackageCollectionsStorage(location: .memory, configuration: configuration)\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let count = Int(Double(configuration.batchSize) * 2.5)\n        let mockCollections = makeMockCollections(count: count)\n        for collection in mockCollections {\n            _ = try await storage.put(collection: collection)\n        }\n\n        let list = try await storage.list()\n        XCTAssertEqual(list.count, mockCollections.count)\n    }\n\n    func testListBatching() async throws {\n        var configuration = SQLitePackageCollectionsStorage.Configuration()\n        configuration.batchSize = 10\n        let storage = SQLitePackageCollectionsStorage(location: .memory, configuration: configuration)\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let count = Int(Double(configuration.batchSize) * 2.5)\n        let mockCollections = makeMockCollections(count: count)\n        for collection in mockCollections {\n            _ = try await storage.put(collection: collection)\n        }\n\n        let list = try await storage.list(identifiers: mockCollections.map { $0.identifier })\n        XCTAssertEqual(list.count, mockCollections.count)\n    }\n\n    func testPutUpdates() async throws {\n        let storage = SQLitePackageCollectionsStorage(location: .memory)\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 3)\n        for collection in mockCollections {\n            _ = try await storage.put(collection: collection)\n        }\n\n        let list = try await storage.list(identifiers: mockCollections.map { $0.identifier })\n        XCTAssertEqual(list.count, mockCollections.count)\n\n        _ = try await storage.put(collection: mockCollections.last!)\n        XCTAssertEqual(list.count, mockCollections.count)\n    }\n\n    func testPopulateTargetTrie() async throws {\n        try await testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            let storage = SQLitePackageCollectionsStorage(path: path)\n            defer { XCTAssertNoThrow(try storage.close()) }\n\n            let mockCollections = makeMockCollections(count: 3)\n            for collection in mockCollections {\n                _ = try await storage.put(collection: collection)\n            }\n\n            let version = mockCollections.last!.packages.last!.versions.last!\n            let targetName = version.defaultManifest!.targets.last!.name\n\n            do {\n                let searchResult = try await storage.searchTargets(query: targetName, type: .exactMatch)\n                XCTAssert(searchResult.items.count > 0, \"should get results\")\n            }\n\n            // Create another instance, which should read existing data and populate target trie with it.\n            // Since we are not calling `storage2.put`, there is no other way for target trie to get populated.\n            let storage2 = SQLitePackageCollectionsStorage(path: path)\n            defer { XCTAssertNoThrow(try storage2.close()) }\n\n            // populateTargetTrie is called in `.init`; call it again explicitly so we know when it's finished\n            do {\n                try await storage2.populateTargetTrie()\n\n                let searchResult = try await storage2.searchTargets(query: targetName, type: .exactMatch)\n                XCTAssert(searchResult.items.count > 0, \"should get results\")\n            } catch {\n                // It's possible that some platforms don't have support FTS\n                XCTAssertEqual(false, storage2.useSearchIndices.get(), \"populateTargetTrie should fail only if FTS is not available\")\n            }\n        }\n    }\n}\n\nextension SQLitePackageCollectionsStorage {\n    convenience init(location: SQLite.Location? = nil, configuration: Configuration = .init()) {\n        self.init(location: location, configuration: configuration, observabilityScope: ObservabilitySystem.NOOP)\n    }\n    convenience init(path: AbsolutePath) {\n        self.init(location: .path(path), observabilityScope: ObservabilitySystem.NOOP)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageCollectionsTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport XCTest\nimport _InternalTestSupport\n\nimport Basics\n@testable import PackageCollections\nimport PackageModel\nimport SourceControl\n\nimport struct TSCUtility.Version\n\nfinal class PackageCollectionsTests: XCTestCase {\n    func testUpdateAuthTokens() async throws {\n        let authTokens = ThreadSafeKeyValueStore<AuthTokenType, String>()\n        let configuration = PackageCollections.Configuration(authTokens: { authTokens.get() })\n\n        // This test doesn't use search at all and finishes quickly so disable target trie to prevent race\n        let storageConfig = SQLitePackageCollectionsStorage.Configuration(initializeTargetTrie: false)\n        let storage = makeMockStorage(storageConfig)\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        // Disable cache for this test to avoid setup/cleanup\n        let metadataProviderConfig = GitHubPackageMetadataProvider.Configuration(authTokens: configuration.authTokens, disableCache: true)\n        let metadataProvider = GitHubPackageMetadataProvider(configuration: metadataProviderConfig)\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: [:], metadataProvider: metadataProvider)\n\n        XCTAssertEqual(0, packageCollections.configuration.authTokens()?.count)\n        do {\n            guard let githubMetadataProvider = packageCollections.metadataProvider as? GitHubPackageMetadataProvider else {\n                return XCTFail(\"Expected GitHubPackageMetadataProvider\")\n            }\n            XCTAssertEqual(0, githubMetadataProvider.configuration.authTokens()?.count)\n        }\n\n        authTokens[.github(\"github.test\")] = \"topsekret\"\n\n        // Check that authTokens change is propagated to PackageMetadataProvider\n        XCTAssertEqual(1, packageCollections.configuration.authTokens()?.count)\n        do {\n            guard let githubMetadataProvider = packageCollections.metadataProvider as? GitHubPackageMetadataProvider else {\n                return XCTFail(\"Expected GitHubPackageMetadataProvider\")\n            }\n            XCTAssertEqual(1, githubMetadataProvider.configuration.authTokens()?.count)\n            XCTAssertEqual(authTokens.get(), githubMetadataProvider.configuration.authTokens())\n        }\n    }\n\n    func testBasicRegistration() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, order: nil)\n        }\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list, mockCollections, \"list count should match\")\n        }\n    }\n\n    func testAddDuplicates() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollection = makeMockCollections(count: 1).first!\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider([mockCollection])]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        _ = try await packageCollections.addCollection(mockCollection.source, order: nil)\n        _ = try await packageCollections.addCollection(mockCollection.source, order: nil)\n        _ = try await packageCollections.addCollection(mockCollection.source, order: nil)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 1, \"list count should match\")\n        }\n    }\n\n    func testAddUnsigned() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 3, signed: false)\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        // User trusted\n        _ = try await packageCollections.addCollection(mockCollections[0].source, order: nil, trustConfirmationProvider: { _, cb in cb(true) })\n        // User untrusted\n        await XCTAssertAsyncThrowsError(\n            try await packageCollections.addCollection(mockCollections[1].source, order: nil, trustConfirmationProvider: { _, cb in cb(false) })\n            ) { error in\n            guard case PackageCollectionError.untrusted = error else {\n                return XCTFail(\"Expected PackageCollectionError.untrusted\")\n            }\n        }\n        // User preference unknown\n        await XCTAssertAsyncThrowsError(\n            try await packageCollections.addCollection(mockCollections[2].source, order: nil, trustConfirmationProvider: nil)) { error in\n            guard case PackageCollectionError.trustConfirmationRequired = error else {\n                return XCTFail(\"Expected PackageCollectionError.trustConfirmationRequired\")\n            }\n        }\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 1, \"list count should match\")\n        }\n    }\n\n    func testInvalidCollectionNotAdded() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        // This test doesn't use search at all and finishes quickly so disable target trie to prevent race\n        let storageConfig = SQLitePackageCollectionsStorage.Configuration(initializeTargetTrie: false)\n        let storage = makeMockStorage(storageConfig)\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollection = makeMockCollections(count: 1).first!\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider([])]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n\n            let sources = try await storage.sources.list()\n            XCTAssertEqual(sources.count, 0, \"sources should be empty\")\n        }\n\n        // add fails because collection is not found\n        await XCTAssertAsyncThrowsError(try await packageCollections.addCollection(mockCollection.source, order: nil)) { error in\n            XCTAssert(error is NotFoundError)\n        }\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list count should match\")\n\n            let sources = try await storage.sources.list()\n            XCTAssertEqual(sources.count, 0, \"sources should be empty\")\n        }\n    }\n\n    func testCollectionPendingTrustConfirmIsKeptOnAdd() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        // This test doesn't use search at all and finishes quickly so disable target trie to prevent race\n        let storageConfig = SQLitePackageCollectionsStorage.Configuration(initializeTargetTrie: false)\n        let storage = makeMockStorage(storageConfig)\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollection = makeMockCollections(count: 1, signed: false).first!\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider([mockCollection])]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n\n            let sources = try await storage.sources.list()\n            XCTAssertEqual(sources.count, 0, \"sources should be empty\")\n        }\n\n        // add fails because collection requires trust confirmation\n        await XCTAssertAsyncThrowsError(try await packageCollections.addCollection(mockCollection.source, order: nil)) { error in\n            XCTAssert(error as? PackageCollectionError == PackageCollectionError.trustConfirmationRequired)\n        }\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list count should match\")\n\n            let sources = try await storage.sources.list()\n            XCTAssertEqual(sources.count, 1, \"sources should match\")\n        }\n    }\n\n    func testCollectionWithInvalidSignatureNotAdded() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        // This test doesn't use search at all and finishes quickly so disable target trie to prevent race\n        let storageConfig = SQLitePackageCollectionsStorage.Configuration(initializeTargetTrie: false)\n        let storage = makeMockStorage(storageConfig)\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollection = makeMockCollections(count: 1).first!\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider([mockCollection], collectionsWithInvalidSignature: [mockCollection.source])]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n\n            let sources = try await storage.sources.list()\n            XCTAssertEqual(sources.count, 0, \"sources should be empty\")\n        }\n\n        // add fails because collection's signature is invalid\n        await XCTAssertAsyncThrowsError(try await packageCollections.addCollection(mockCollection.source, order: nil)) { error in\n            XCTAssert((error as? PackageCollectionError) == PackageCollectionError.invalidSignature)\n        }\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list count should match\")\n\n            let sources = try await storage.sources.list()\n            XCTAssertEqual(sources.count, 0, \"sources should be empty\")\n        }\n    }\n\n    func testDelete() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 10)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await packageCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list, mockCollections, \"list count should match\")\n        }\n\n        do {\n            try await packageCollections.removeCollection(mockCollections.first!.source)\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count - 1, \"list count should match\")\n        }\n\n        do {\n            try await packageCollections.removeCollection(mockCollections.first!.source)\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count - 1, \"list count should match\")\n        }\n\n        do {\n            try await packageCollections.removeCollection(mockCollections[mockCollections.count - 1].source)\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count - 2, \"list count should match\")\n        }\n\n        do {\n            let unknownSource = makeMockSources(count: 1).first!\n            try await packageCollections.removeCollection(unknownSource)\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count - 2, \"list should be empty\")\n        }\n    }\n\n    func testDeleteFromBothStorages() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollection = makeMockCollections(count: 1).first!\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider([mockCollection])]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        _ = try await packageCollections.addCollection(mockCollection.source, order: nil)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 1, \"list count should match\")\n        }\n\n        do {\n            try await packageCollections.removeCollection(mockCollection.source)\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list count should match\")\n\n            // check if exists in storage\n            await XCTAssertAsyncThrowsError(try await storage.collections.get(identifier: mockCollection.identifier), \"expected error\")\n        }\n    }\n\n    func testOrdering() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 10)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            _ = try await packageCollections.addCollection(mockCollections[0].source, order: 0)\n            _ = try await packageCollections.addCollection(mockCollections[1].source, order: 1)\n            _ = try await packageCollections.addCollection(mockCollections[2].source, order: 2)\n            _ = try await packageCollections.addCollection(mockCollections[3].source, order: Int.min)\n            _ = try await packageCollections.addCollection(mockCollections[4].source, order: Int.max)\n\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 5, \"list count should match\")\n\n            let expectedOrder = [\n                mockCollections[0].identifier: 0,\n                mockCollections[1].identifier: 1,\n                mockCollections[2].identifier: 2,\n                mockCollections[3].identifier: 3,\n                mockCollections[4].identifier: 4,\n            ]\n\n            list.enumerated().forEach { index, collection in\n                let expectedOrder = expectedOrder[collection.identifier]!\n                XCTAssertEqual(index, expectedOrder, \"order should match\")\n            }\n        }\n\n        // bump the order\n\n        do {\n            _ = try await packageCollections.addCollection(mockCollections[5].source, order: 2)\n            _ = try await packageCollections.addCollection(mockCollections[6].source, order: 2)\n            _ = try await packageCollections.addCollection(mockCollections[7].source, order: 0)\n            _ = try await packageCollections.addCollection(mockCollections[8].source, order: -1)\n\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 9, \"list count should match\")\n\n            let expectedOrder = [\n                mockCollections[0].identifier: 1,\n                mockCollections[1].identifier: 2,\n                mockCollections[2].identifier: 5,\n                mockCollections[3].identifier: 6,\n                mockCollections[4].identifier: 7,\n                mockCollections[5].identifier: 4,\n                mockCollections[6].identifier: 3,\n                mockCollections[7].identifier: 0,\n                mockCollections[8].identifier: 8,\n            ]\n\n            list.enumerated().forEach { index, collection in\n                let expectedOrder = expectedOrder[collection.identifier]!\n                XCTAssertEqual(index, expectedOrder, \"order should match\")\n            }\n        }\n    }\n\n    func testReorder() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 3)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            _ = try await packageCollections.addCollection(mockCollections[0].source, order: 0)\n            _ = try await packageCollections.addCollection(mockCollections[1].source, order: 1)\n            _ = try await packageCollections.addCollection(mockCollections[2].source, order: 2)\n\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 3, \"list count should match\")\n\n            let expectedOrder = [\n                mockCollections[0].identifier: 0,\n                mockCollections[1].identifier: 1,\n                mockCollections[2].identifier: 2,\n            ]\n\n            list.enumerated().forEach { index, collection in\n                let expectedOrder = expectedOrder[collection.identifier]!\n                XCTAssertEqual(index, expectedOrder, \"order should match\")\n            }\n        }\n\n        do {\n            try await packageCollections.moveCollection(mockCollections[2].source, to: -1)\n            let list = try await packageCollections.listCollections()\n\n            let expectedOrder = [\n                mockCollections[0].identifier: 0,\n                mockCollections[1].identifier: 1,\n                mockCollections[2].identifier: 2,\n            ]\n\n            list.enumerated().forEach { index, collection in\n                let expectedOrder = expectedOrder[collection.identifier]!\n                XCTAssertEqual(index, expectedOrder, \"order should match\")\n            }\n        }\n\n        do {\n            try await packageCollections.moveCollection(mockCollections[2].source, to: Int.max)\n            let list = try await packageCollections.listCollections()\n\n            let expectedOrder = [\n                mockCollections[0].identifier: 0,\n                mockCollections[1].identifier: 1,\n                mockCollections[2].identifier: 2,\n            ]\n\n            list.enumerated().forEach { index, collection in\n                let expectedOrder = expectedOrder[collection.identifier]!\n                XCTAssertEqual(index, expectedOrder, \"order should match\")\n            }\n        }\n\n        do {\n            try await packageCollections.moveCollection(mockCollections[2].source, to: 0)\n            let list = try await packageCollections.listCollections()\n\n            let expectedOrder = [\n                mockCollections[0].identifier: 1,\n                mockCollections[1].identifier: 2,\n                mockCollections[2].identifier: 0,\n            ]\n\n            list.enumerated().forEach { index, collection in\n                let expectedOrder = expectedOrder[collection.identifier]!\n                XCTAssertEqual(index, expectedOrder, \"order should match\")\n            }\n        }\n\n        do {\n            try await packageCollections.moveCollection(mockCollections[2].source, to: 1)\n            let list = try await packageCollections.listCollections()\n\n            let expectedOrder = [\n                mockCollections[0].identifier: 0,\n                mockCollections[1].identifier: 2,\n                mockCollections[2].identifier: 1,\n            ]\n\n            list.enumerated().forEach { index, collection in\n                let expectedOrder = expectedOrder[collection.identifier]!\n                XCTAssertEqual(index, expectedOrder, \"order should match\")\n            }\n        }\n    }\n\n    func testUpdateTrust() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 1, signed: false)\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        // User preference unknown - collection not saved to storage\n        _ = try? await packageCollections.addCollection(mockCollections.first!.source, order: nil, trustConfirmationProvider: nil)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        var source = mockCollections.first!.source\n\n        // Update to trust the source. It will trigger a collection refresh which will save collection to storage.\n        source.isTrusted = true\n        _ = try await packageCollections.updateCollection(source)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 1, \"list count should match\")\n        }\n\n        // Update to untrust the source. It will trigger a collection refresh which will remove collection from storage.\n        source.isTrusted = false\n        await XCTAssertAsyncThrowsError(try await packageCollections.updateCollection(source)) { error in\n            guard case PackageCollectionError.untrusted = error else {\n                return XCTFail(\"Expected PackageCollectionError.untrusted\")\n            }\n        }\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n    }\n\n    func testList() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 10)\n        let mockPackage = mockCollections.last!.packages.last!\n        let mockMetadata = makeMockPackageBasicMetadata()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n\n        let list = try await packageCollections.listCollections()\n        XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n    }\n\n    func testListSubset() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 10)\n        let mockPackage = mockCollections.last!.packages.last!\n        let mockMetadata = makeMockPackageBasicMetadata()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n\n        let expectedCollections = Set([mockCollections.first!.identifier, mockCollections.last!.identifier])\n        let list = try await packageCollections.listCollections(identifiers: expectedCollections)\n        XCTAssertEqual(list.count, expectedCollections.count, \"list count should match\")\n    }\n\n    func testListPerformance() async throws {\n        #if ENABLE_COLLECTION_PERF_TESTS\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 1000)\n        let mockPackage = mockCollections.last!.packages.last!\n        let mockMetadata = makeMockPackageBasicMetadata()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, order: nil)\n        }\n\n        let start = Date()\n        let list = try await packageCollections.listCollections()\n        XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        let delta = Date().timeIntervalSince(start)\n        XCTAssert(delta < 1.0, \"should list quickly, took \\(delta)\")\n    }\n\n    func testPackageSearch() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        var mockCollections = makeMockCollections()\n\n        let mockTargets = [UUID().uuidString, UUID().uuidString].map {\n            PackageCollectionsModel.Target(name: $0, moduleName: $0)\n        }\n\n        let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]),\n                            PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let mockManifest = PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: UUID().uuidString,\n            targets: mockTargets,\n            products: mockProducts,\n            minimumPlatformVersions: nil\n        )\n\n        let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0),\n                                                                  title: nil,\n                                                                  summary: nil,\n                                                                  manifests: [toolsVersion: mockManifest],\n                                                                  defaultToolsVersion: toolsVersion,\n                                                                  verifiedCompatibility: nil,\n                                                                  license: nil,\n                                                                  author: nil,\n                                                                  signer: nil,\n                                                                  createdAt: nil)\n\n        let url = \"https://packages.mock/\\(UUID().uuidString)\"\n        let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: url),\n                                                          location: url,\n                                                          summary: UUID().uuidString,\n                                                          keywords: [UUID().uuidString, UUID().uuidString],\n                                                          versions: [mockVersion],\n                                                          watchersCount: nil,\n                                                          readmeURL: nil,\n                                                          license: nil,\n                                                          authors: nil,\n                                                          languages: nil)\n\n        let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                name: UUID().uuidString,\n                                                                overview: UUID().uuidString,\n                                                                keywords: [UUID().uuidString, UUID().uuidString],\n                                                                packages: [mockPackage],\n                                                                createdAt: Date(),\n                                                                createdBy: nil,\n                                                                signature: nil)\n\n        let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                 name: UUID().uuidString,\n                                                                 overview: UUID().uuidString,\n                                                                 keywords: [UUID().uuidString, UUID().uuidString],\n                                                                 packages: [mockPackage],\n                                                                 createdAt: Date(),\n                                                                 createdBy: nil,\n                                                                 signature: nil)\n\n        let expectedCollections = [mockCollection, mockCollection2]\n        let expectedCollectionsIdentifiers = expectedCollections.map { $0.identifier }.sorted()\n\n        mockCollections.append(contentsOf: expectedCollections)\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n\n        do {\n            // search by package name\n            let searchResult = try await packageCollections.findPackages(mockManifest.packageName)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"list count should match\")\n        }\n\n        do {\n            // search by package description/summary\n            let searchResult = try await packageCollections.findPackages(mockPackage.summary!)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"list count should match\")\n        }\n\n        do {\n            // search by package keywords\n            let searchResult = try await packageCollections.findPackages(mockPackage.keywords!.first!)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"list count should match\")\n        }\n\n        do {\n            // search by package repository url\n            let searchResult = try await packageCollections.findPackages(mockPackage.location)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n        }\n\n        do {\n            // search by package identity\n            let searchResult = try await packageCollections.findPackages(mockPackage.identity.description)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n        }\n\n        do {\n            // search by product name\n            let searchResult = try await packageCollections.findPackages(mockProducts.first!.name)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"list count should match\")\n        }\n\n        do {\n            // search by target name\n            let searchResult = try await packageCollections.findPackages(mockTargets.first!.name)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n        }\n\n        do {\n            // empty search\n            let searchResult = try await packageCollections.findPackages(UUID().uuidString)\n            XCTAssertEqual(searchResult.items.count, 0, \"list count should match\")\n        }\n    }\n\n    func testPackageSearchPerformance() async throws {\n        #if ENABLE_COLLECTION_PERF_TESTS\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 1000, maxPackages: 20)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, order: nil)\n        }\n\n        // search by package name\n        let start = Date()\n        let repoName = mockCollections.last!.packages.last!.identity.description\n        let searchResult = try await packageCollections.findPackages(repoName)\n        XCTAssert(searchResult.items.count > 0, \"should get results\")\n        let delta = Date().timeIntervalSince(start)\n        XCTAssert(delta < 1.0, \"should search quickly, took \\(delta)\")\n    }\n\n    func testTargetsSearch() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        var mockCollections = makeMockCollections()\n\n        let mockTargets = [UUID().uuidString, UUID().uuidString].map {\n            PackageCollectionsModel.Target(name: $0, moduleName: $0)\n        }\n\n        let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]),\n                            PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let mockManifest = PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: UUID().uuidString,\n            targets: mockTargets,\n            products: mockProducts,\n            minimumPlatformVersions: nil\n        )\n\n        let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0),\n                                                                  title: nil,\n                                                                  summary: nil,\n                                                                  manifests: [toolsVersion: mockManifest],\n                                                                  defaultToolsVersion: toolsVersion,\n                                                                  verifiedCompatibility: nil,\n                                                                  license: nil,\n                                                                  author: nil,\n                                                                  signer: nil,\n                                                                  createdAt: nil)\n\n        let mockPackageURL = \"https://packages.mock/\\(UUID().uuidString)\"\n        let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: mockPackageURL),\n                                                          location: mockPackageURL,\n                                                          summary: UUID().uuidString,\n                                                          keywords: [UUID().uuidString, UUID().uuidString],\n                                                          versions: [mockVersion],\n                                                          watchersCount: nil,\n                                                          readmeURL: nil,\n                                                          license: nil,\n                                                          authors: nil,\n                                                          languages: nil)\n\n        let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                name: UUID().uuidString,\n                                                                overview: UUID().uuidString,\n                                                                keywords: [UUID().uuidString, UUID().uuidString],\n                                                                packages: [mockPackage],\n                                                                createdAt: Date(),\n                                                                createdBy: nil,\n                                                                signature: nil)\n\n        let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                 name: UUID().uuidString,\n                                                                 overview: UUID().uuidString,\n                                                                 keywords: [UUID().uuidString, UUID().uuidString],\n                                                                 packages: [mockPackage],\n                                                                 createdAt: Date(),\n                                                                 createdBy: nil,\n                                                                 signature: nil)\n\n        let expectedCollections = [mockCollection, mockCollection2]\n        let expectedCollectionsIdentifiers = expectedCollections.map { $0.identifier }.sorted()\n\n        mockCollections.append(contentsOf: expectedCollections)\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n\n        do {\n            // search by exact target name\n            let searchResult = try await packageCollections.findTargets(mockTargets.first!.name, searchType: .exactMatch)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], \"packages should match\")\n            XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n        }\n\n        do {\n            // search by prefix target name\n            let searchResult = try await packageCollections.findTargets(String(mockTargets.first!.name.prefix(mockTargets.first!.name.count - 1)), searchType: .prefix)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], \"packages should match\")\n            XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n        }\n\n        do {\n            // empty search\n            let searchResult = try await packageCollections.findTargets(UUID().uuidString, searchType: .exactMatch)\n            XCTAssertEqual(searchResult.items.count, 0, \"list count should match\")\n        }\n    }\n\n    func testTargetsSearchPerformance() async throws {\n        #if ENABLE_COLLECTION_PERF_TESTS\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 1000)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, order: nil)\n        }\n\n        // search by target name\n        let start = Date()\n        let targetName = mockCollections.last!.packages.last!.versions.last!.defaultManifest!.targets.last!.name\n        let searchResult = try await packageCollections.findTargets(targetName, searchType: .exactMatch)\n        XCTAssert(searchResult.items.count > 0, \"should get results\")\n        let delta = Date().timeIntervalSince(start)\n        XCTAssert(delta < 1.0, \"should search quickly, took \\(delta)\")\n    }\n\n    func testHappyRefresh() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            // save directly to storage to circumvent refresh on add\n            try await storage.sources.add(source: collection.source, order: nil)\n        }\n        _ = try await packageCollections.refreshCollections()\n\n        let list = try await packageCollections.listCollections()\n        XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n    }\n\n    func testBrokenRefresh() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        struct BrokenProvider: PackageCollectionProvider {\n            let brokenSources: [PackageCollectionsModel.CollectionSource]\n            let error: Error\n\n            init(brokenSources: [PackageCollectionsModel.CollectionSource], error: Error) {\n                self.brokenSources = brokenSources\n                self.error = error\n            }\n\n            func get(_ source: PackageCollectionsModel.CollectionSource) async throws -> PackageCollectionsModel.Collection {\n                if self.brokenSources.contains(source) {\n                    throw self.error\n                }\n                let signature = PackageCollectionsModel.SignatureData(\n                    certificate: PackageCollectionsModel.SignatureData.Certificate(\n                        subject: .init(userID: nil, commonName: nil, organizationalUnit: nil, organization: nil),\n                        issuer: .init(userID: nil, commonName: nil, organizationalUnit: nil, organization: nil)\n                    ),\n                    isVerified: true\n                )\n                return PackageCollectionsModel.Collection(source: source, name: \"\", overview: nil, keywords: nil, packages: [], createdAt: Date(), createdBy: nil, signature: signature)\n\n            }\n        }\n\n        struct MyError: Error, Equatable {}\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let expectedError = MyError()\n        let goodSources = [PackageCollectionsModel.CollectionSource(type: .json, url: \"https://feed-\\(UUID().uuidString)\"),\n                           PackageCollectionsModel.CollectionSource(type: .json, url: \"https://feed-\\(UUID().uuidString)\")]\n        let brokenSources = [PackageCollectionsModel.CollectionSource(type: .json, url: \"https://feed-\\(UUID().uuidString)\"),\n                             PackageCollectionsModel.CollectionSource(type: .json, url: \"https://feed-\\(UUID().uuidString)\")]\n        let provider = BrokenProvider(brokenSources: brokenSources, error: expectedError)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: provider]\n\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        await XCTAssertAsyncThrowsError(try await packageCollections.addCollection(brokenSources.first!), \"expected error\") { error in\n            XCTAssertEqual(error as? MyError, expectedError, \"expected error to match\")\n        }\n\n        // save directly to storage to circumvent refresh on add\n        for source in goodSources {\n            try await storage.sources.add(source: source, order: nil)\n        }\n        for source in brokenSources {\n            try await storage.sources.add(source: source, order: nil)\n        }\n        try await storage.sources.add(source: .init(type: .json, url: \"https://feed-\\(UUID().uuidString)\"), order: nil)\n\n        await XCTAssertAsyncThrowsError(try await packageCollections.refreshCollections(), \"expected error\") { error in\n            if let error = error as? MultipleErrors {\n                XCTAssertEqual(error.errors.count, brokenSources.count, \"expected error to match\")\n                error.errors.forEach { error in\n                    XCTAssertEqual(error as? MyError, expectedError, \"expected error to match\")\n                }\n            } else {\n                XCTFail(\"expected error to match\")\n            }\n        }\n\n        // test isolation - broken feeds does not impact good ones\n        let list = try await packageCollections.listCollections()\n        XCTAssertEqual(list.count, goodSources.count + 1, \"list count should match\")\n    }\n\n    func testRefreshOne() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 1)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            // save directly to storage to circumvent refresh on add\n            try await storage.sources.add(source: collection.source, order: nil)\n        }\n        _ = try await packageCollections.refreshCollection(mockCollections.first!.source)\n\n        let list = try await packageCollections.listCollections()\n        XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n    }\n\n    func testRefreshOneTrustedUnsigned() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 1, signed: false)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        // User trusted\n        let collection = try await packageCollections.addCollection(mockCollections[0].source, order: nil, trustConfirmationProvider: { _, cb in cb(true) })\n        XCTAssertEqual(true, collection.source.isTrusted) // isTrusted is nil-able\n\n        // `isTrusted` should be true so refreshCollection should succeed\n        _ = try await packageCollections.refreshCollection(collection.source)\n    }\n\n    func testRefreshOneNotFound() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 1, signed: false)\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        // Don't add collection so it's not found in the config\n        await XCTAssertAsyncThrowsError(try await packageCollections.refreshCollection(mockCollections[0].source), \"expected error\") { error in\n            XCTAssert(error is NotFoundError)\n        }\n    }\n\n    func testListTargets() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await packageCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n\n        let targetsList = try await packageCollections.listTargets()\n        let expectedTargets = Set(mockCollections.flatMap { $0.packages.flatMap { $0.versions.flatMap { $0.defaultManifest!.targets.map { $0.name } } } })\n        XCTAssertEqual(Set(targetsList.map { $0.target.name }), expectedTargets, \"targets should match\")\n\n        let targetsPackagesList = Set(targetsList.flatMap { $0.packages })\n        let expectedPackages = Set(mockCollections.flatMap { $0.packages.filter { !$0.versions.filter { !expectedTargets.isDisjoint(with: $0.defaultManifest!.targets.map { $0.name }) }.isEmpty } }.map { $0.identity })\n        XCTAssertEqual(targetsPackagesList.count, expectedPackages.count, \"packages should match\")\n\n        let targetsCollectionsList = Set(targetsList.flatMap { $0.packages.flatMap { $0.collections } })\n        let expectedCollections = Set(mockCollections.filter { !$0.packages.filter { expectedPackages.contains($0.identity) }.isEmpty }.map { $0.identifier })\n        XCTAssertEqual(targetsCollectionsList, expectedCollections, \"collections should match\")\n    }\n\n    func testFetchMetadataHappy() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections()\n        let mockPackage = mockCollections.last!.packages.last!\n        let mockMetadata = makeMockPackageBasicMetadata()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await packageCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n\n        let metadata = try await packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location)\n\n        let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier })\n        XCTAssertEqual(Set(metadata.collections), expectedCollections, \"collections should match\")\n\n        let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: mockMetadata)\n        XCTAssertEqual(metadata.package, expectedMetadata, \"package should match\")\n\n        XCTAssertNil(metadata.provider, \"provider should be nil\")\n    }\n\n    func testFetchMetadataInOrder() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 2)\n        let mockPackage = mockCollections.last!.packages.first!\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await packageCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n\n        let metadata = try await packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location)\n\n        let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier })\n        XCTAssertEqual(Set(metadata.collections), expectedCollections, \"collections should match\")\n\n        let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: nil)\n        XCTAssertEqual(metadata.package, expectedMetadata, \"package should match\")\n\n        // MockMetadataProvider throws NotFoundError which would cause metadata.provider to be set to nil\n        XCTAssertNil(metadata.provider, \"provider should be nil\")\n    }\n\n    func testFetchMetadataInCollections() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 2)\n        let mockPackage = mockCollections.last!.packages.first!\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await packageCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n\n        let collectionIdentifiers: Set<Model.CollectionIdentifier> = [mockCollections.last!.identifier]\n        let metadata = try await packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location, collections: collectionIdentifiers)\n        XCTAssertEqual(Set(metadata.collections), collectionIdentifiers, \"collections should match\")\n\n        let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: nil)\n        XCTAssertEqual(metadata.package, expectedMetadata, \"package should match\")\n\n        // MockMetadataProvider throws NotFoundError which would cause metadata.provider to be set to nil\n        XCTAssertNil(metadata.provider, \"provider should be nil\")\n    }\n\n    func testMergedPackageMetadata() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let packageId = UUID().uuidString\n\n        let targets = (0 ..< Int.random(in: 1 ... 5)).map {\n            PackageCollectionsModel.Target(name: \"target-\\($0)\", moduleName: \"target-\\($0)\")\n        }\n        let products = (0 ..< Int.random(in: 1 ... 3)).map {\n            PackageCollectionsModel.Product(name: \"product-\\($0)\", type: .executable, targets: targets)\n        }\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let manifest = PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: \"package-\\(packageId)\",\n            targets: targets,\n            products: products,\n            minimumPlatformVersions: [.init(platform: .macOS, version: .init(\"10.15\"))]\n        )\n\n        let versions = (0 ... 3).map {\n            PackageCollectionsModel.Package.Version(version: TSCUtility.Version($0, 0, 0),\n                                                    title: \"\\($0) title\",\n                                                    summary: \"\\($0) description\",\n                                                    manifests: [toolsVersion: manifest],\n                                                    defaultToolsVersion: toolsVersion,\n                                                    verifiedCompatibility: [\n                                                        .init(platform: .iOS, swiftVersion: SwiftLanguageVersion.knownSwiftLanguageVersions.randomElement()!),\n                                                        .init(platform: .linux, swiftVersion: SwiftLanguageVersion.knownSwiftLanguageVersions.randomElement()!),\n                                                    ],\n                                                    license: PackageCollectionsModel.License(type: .Apache2_0, url: \"http://apache.license\"),\n                                                    author: .init(username: \"\\($0)\", url: nil, service: nil),\n                                                    signer: .init(type: .adp, commonName: \"\\($0)\", organizationalUnitName: \"\\($0) org unit\", organizationName: \"\\($0) org\"),\n                                                    createdAt: Date())\n        }\n\n        let mockPackageURL = \"https://package-\\(packageId)\"\n        let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: mockPackageURL),\n                                                          location: mockPackageURL,\n                                                          summary: \"package \\(packageId) description\",\n                                                          keywords: [UUID().uuidString],\n                                                          versions: versions,\n                                                          watchersCount: Int.random(in: 0 ... 50),\n                                                          readmeURL: \"https://package-\\(packageId)-readme\",\n                                                          license: PackageCollectionsModel.License(type: .Apache2_0, url: \"http://apache.license\"),\n                                                          authors: (0 ..< Int.random(in: 1 ... 10)).map { .init(username: \"\\($0)\", url: nil, service: nil) },\n                                                          languages: nil)\n\n        let mockMetadata = PackageCollectionsModel.PackageBasicMetadata(summary: \"\\(mockPackage.summary!) 2\",\n                                                                        keywords: mockPackage.keywords.flatMap { $0.map { \"\\($0)-2\" } },\n                                                                        versions: mockPackage.versions.map { PackageCollectionsModel.PackageBasicVersionMetadata(version: $0.version, title: \"\\($0.title!) 2\", summary: \"\\($0.summary!) 2\", author: .init(username: \"\\(($0.author?.username ?? \"\") + \"2\")\", url: nil, service: nil), createdAt: Date()) },\n                                                                        watchersCount: mockPackage.watchersCount! + 1,\n                                                                        readmeURL: \"\\(mockPackage.readmeURL!.absoluteString)-2\",\n                                                                        license: PackageCollectionsModel.License(type: .Apache2_0, url: \"\\(mockPackage.license!.url.absoluteString)-2\"),\n                                                                        authors: mockPackage.authors.flatMap { $0.map { .init(username: \"\\($0.username + \"2\")\", url: nil, service: nil) } },\n                                                                        languages: [\"Swift\"])\n\n        let metadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: mockMetadata)\n\n        XCTAssertEqual(metadata.identity, mockPackage.identity, \"identity should match\")\n        XCTAssertEqual(metadata.location, mockPackage.location, \"location should match\")\n        XCTAssertEqual(metadata.summary, mockMetadata.summary, \"summary should match\")\n        XCTAssertEqual(metadata.keywords, mockMetadata.keywords, \"keywords should match\")\n        mockPackage.versions.forEach { version in\n            let metadataVersion = metadata.versions.first(where: { $0.version == version.version })\n            XCTAssertNotNil(metadataVersion)\n\n            let mockMetadataVersion = mockMetadata.versions.first(where: { $0.version == version.version })\n            XCTAssertNotNil(mockMetadataVersion)\n\n            let manifest = version.defaultManifest!\n            let metadataManifest = metadataVersion?.defaultManifest\n            XCTAssertEqual(manifest.packageName, metadataManifest?.packageName, \"packageName should match\")\n            XCTAssertEqual(manifest.targets, metadataManifest?.targets, \"targets should match\")\n            XCTAssertEqual(manifest.products, metadataManifest?.products, \"products should match\")\n            XCTAssertEqual(manifest.toolsVersion, metadataManifest?.toolsVersion, \"toolsVersion should match\")\n            XCTAssertEqual(manifest.minimumPlatformVersions, metadataManifest?.minimumPlatformVersions, \"minimumPlatformVersions should match\")\n            XCTAssertEqual(version.verifiedCompatibility, metadataVersion?.verifiedCompatibility, \"verifiedCompatibility should match\")\n            XCTAssertEqual(version.license, metadataVersion?.license, \"license should match\")\n            XCTAssertEqual(mockMetadataVersion?.summary, metadataVersion?.summary, \"summary should match\")\n            XCTAssertEqual(mockMetadataVersion?.author, metadataVersion?.author, \"author should match\")\n            XCTAssertEqual(version.signer, metadataVersion?.signer, \"signer should match\")\n            XCTAssertEqual(mockMetadataVersion?.createdAt, metadataVersion?.createdAt, \"createdAt should match\")\n        }\n        XCTAssertEqual(metadata.latestVersion, metadata.versions.first, \"versions should be sorted\")\n        XCTAssertEqual(metadata.latestVersion?.version, versions.last?.version, \"latestVersion should match\")\n        XCTAssertEqual(metadata.watchersCount, mockMetadata.watchersCount, \"watchersCount should match\")\n        XCTAssertEqual(metadata.readmeURL, mockMetadata.readmeURL, \"readmeURL should match\")\n        XCTAssertEqual(metadata.license, mockMetadata.license, \"license should match\")\n        XCTAssertEqual(metadata.authors, mockMetadata.authors, \"authors should match\")\n        XCTAssertEqual(metadata.languages, mockMetadata.languages, \"languages should match\")\n    }\n\n    func testFetchMetadataNotFoundInCollections() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockPackage = makeMockCollections().first!.packages.first!\n        let mockMetadata = makeMockPackageBasicMetadata()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider([])]\n        let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        await XCTAssertAsyncThrowsError(try await packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location), \"expected error\") { error in\n            XCTAssert(error is NotFoundError)\n        }\n    }\n\n    func testFetchMetadataNotFoundByProvider() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections()\n        let mockPackage = mockCollections.last!.packages.last!\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await packageCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n\n        let metadata = try await packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location)\n\n        let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier })\n        XCTAssertEqual(Set(metadata.collections), expectedCollections, \"collections should match\")\n\n        let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: nil)\n        XCTAssertEqual(metadata.package, expectedMetadata, \"package should match\")\n\n        // MockMetadataProvider throws NotFoundError which would cause metadata.provider to be set to nil\n        XCTAssertNil(metadata.provider, \"provider should be nil\")\n    }\n\n    func testFetchMetadataProviderError() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        struct BrokenMetadataProvider: PackageMetadataProvider {\n            var name: String = \"BrokenMetadataProvider\"\n\n            func get(\n                identity: PackageModel.PackageIdentity,\n                location: String\n            ) async -> (Result<PackageCollectionsModel.PackageBasicMetadata, any Error>, PackageMetadataProviderContext?) {\n                return (.failure(TerribleThing()), nil)\n            }\n\n            struct TerribleThing: Error {}\n        }\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections()\n        let mockPackage = mockCollections.last!.packages.last!\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = BrokenMetadataProvider()\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        do {\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await packageCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await packageCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n\n        // Despite metadata provider error we should still get back data from storage\n        let metadata = try await packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location)\n        let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: nil)\n        XCTAssertEqual(metadata.package, expectedMetadata, \"package should match\")\n\n        // MockMetadataProvider throws unhandled error which would cause metadata.provider to be set to nil\n        XCTAssertNil(metadata.provider, \"provider should be nil\")\n    }\n\n    func testFetchMetadataPerformance() async throws {\n        #if ENABLE_COLLECTION_PERF_TESTS\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        let mockCollections = makeMockCollections(count: 1000)\n        let mockPackage = mockCollections.last!.packages.last!\n        let mockMetadata = makeMockPackageBasicMetadata()\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, order: nil)\n        }\n\n        let start = Date()\n        let metadata = try await packageCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location)\n        XCTAssertNotNil(metadata)\n        let delta = Date().timeIntervalSince(start)\n        XCTAssert(delta < 1.0, \"should fetch quickly, took \\(delta)\")\n    }\n\n    func testListPackages() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let configuration = PackageCollections.Configuration()\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        var mockCollections = makeMockCollections(count: 5)\n\n        let mockTargets = [UUID().uuidString, UUID().uuidString].map {\n            PackageCollectionsModel.Target(name: $0, moduleName: $0)\n        }\n\n        let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]),\n                            PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let mockManifest = PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: UUID().uuidString,\n            targets: mockTargets,\n            products: mockProducts,\n            minimumPlatformVersions: nil\n        )\n\n        let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0),\n                                                                  title: nil,\n                                                                  summary: nil,\n                                                                  manifests: [toolsVersion: mockManifest],\n                                                                  defaultToolsVersion: toolsVersion,\n                                                                  verifiedCompatibility: nil,\n                                                                  license: nil,\n                                                                  author: nil,\n                                                                  signer: nil,\n                                                                  createdAt: nil)\n\n        let mockPackageURL = \"https://packages.mock/\\(UUID().uuidString)\"\n        let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: mockPackageURL),\n                                                          location: mockPackageURL,\n                                                          summary: UUID().uuidString,\n                                                          keywords: [UUID().uuidString, UUID().uuidString],\n                                                          versions: [mockVersion],\n                                                          watchersCount: nil,\n                                                          readmeURL: nil,\n                                                          license: nil,\n                                                          authors: nil,\n                                                          languages: nil)\n\n        let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                name: UUID().uuidString,\n                                                                overview: UUID().uuidString,\n                                                                keywords: [UUID().uuidString, UUID().uuidString],\n                                                                packages: [mockPackage],\n                                                                createdAt: Date(),\n                                                                createdBy: nil,\n                                                                signature: nil)\n\n        let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                 name: UUID().uuidString,\n                                                                 overview: UUID().uuidString,\n                                                                 keywords: [UUID().uuidString, UUID().uuidString],\n                                                                 packages: [mockPackage],\n                                                                 createdAt: Date(),\n                                                                 createdBy: nil,\n                                                                 signature: nil)\n\n        mockCollections.append(mockCollection)\n        mockCollections.append(mockCollection2)\n\n        let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n        let metadataProvider = MockMetadataProvider([:])\n        let packageCollections = PackageCollections(configuration: configuration, storage: storage, collectionProviders: collectionProviders, metadataProvider: metadataProvider)\n\n        for collection in mockCollections {\n            _ = try await packageCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n\n        do {\n            let fetchCollections = Set(mockCollections.map { $0.identifier } + [mockCollection.identifier, mockCollection2.identifier])\n            let expectedPackages = Set(mockCollections.flatMap { $0.packages.map { $0.identity } } + [mockPackage.identity])\n            let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier])\n\n            let searchResult = try await packageCollections.listPackages(collections: fetchCollections)\n            XCTAssertEqual(searchResult.items.count, expectedPackages.count, \"list count should match\")\n            XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, \"items should match\")\n            XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, \"collections should match\")\n        }\n\n        // Call API for specific collections\n        do {\n            let fetchCollections = Set([mockCollections[0].identifier, mockCollection.identifier, mockCollection2.identifier])\n            let expectedPackages = Set(mockCollections[0].packages.map { $0.identity } + [mockPackage.identity])\n            let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier])\n\n            let searchResult = try await packageCollections.listPackages(collections: fetchCollections)\n            XCTAssertEqual(searchResult.items.count, expectedPackages.count, \"list count should match\")\n            XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, \"items should match\")\n            XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, \"collections should match\")\n        }\n    }\n}\n\nprivate extension PackageCollections {\n    init(\n        configuration: Configuration = .init(),\n        storage: Storage,\n        collectionProviders: [Model.CollectionSourceType: PackageCollectionProvider],\n        metadataProvider: PackageMetadataProvider\n    ) {\n        self.init(\n            configuration: configuration,\n            fileSystem: localFileSystem,\n            observabilityScope: ObservabilitySystem.NOOP,\n            storage: storage,\n            collectionProviders: collectionProviders,\n            metadataProvider: metadataProvider\n        )\n    }\n}\n\nfunc PackageCollectionsTests_skipIfUnsupportedPlatform() throws {\n    if !PackageCollections.isSupportedPlatform {\n        throw XCTSkip(\"Skipping test on unsupported platform\")\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageIndexAndCollectionsTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n@testable import PackageCollections\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCUtility.Version\n\nclass PackageIndexAndCollectionsTests: XCTestCase {\n    func testCollectionAddRemoveGetList() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n        \n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n        let mockCollections = makeMockCollections()\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage)\n\n        let packageIndex = MockPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n\n        do {\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await indexAndCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list, mockCollections, \"list count should match\")\n        }\n        \n        do {\n            let collection = try await indexAndCollections.getCollection(mockCollections.first!.source)\n            XCTAssertEqual(collection, mockCollections.first, \"collection should match\")\n        }\n        \n        do {\n            try await indexAndCollections.removeCollection(mockCollections.first!.source)\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count - 1, \"list count should match\")\n        }\n    }\n    \n    func testRefreshCollections() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n        let mockCollections = makeMockCollections()\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage)\n\n        let packageIndex = MockPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n\n        for collection in mockCollections {\n            // save directly to storage to circumvent refresh on add\n            try await storage.sources.add(source: collection.source, order: nil)\n        }\n        _ = try await indexAndCollections.refreshCollections()\n\n        let list = try await indexAndCollections.listCollections()\n        XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n    }\n    \n    func testRefreshCollection() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n        let mockCollections = makeMockCollections()\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage)\n\n        let packageIndex = MockPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n\n        for collection in mockCollections {\n            // save directly to storage to circumvent refresh on add\n            try await storage.sources.add(source: collection.source, order: nil)\n        }\n        _ = try await indexAndCollections.refreshCollection(mockCollections.first!.source)\n\n        let collection = try await indexAndCollections.getCollection(mockCollections.first!.source)\n        XCTAssertEqual(collection, mockCollections.first, \"collection should match\")\n    }\n\n    func testListPackages() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        var mockCollections = makeMockCollections(count: 5)\n\n        let mockTargets = [UUID().uuidString, UUID().uuidString].map {\n            PackageCollectionsModel.Target(name: $0, moduleName: $0)\n        }\n\n        let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]),\n                            PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let mockManifest = PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: UUID().uuidString,\n            targets: mockTargets,\n            products: mockProducts,\n            minimumPlatformVersions: nil\n        )\n\n        let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0),\n                                                                  title: nil,\n                                                                  summary: nil,\n                                                                  manifests: [toolsVersion: mockManifest],\n                                                                  defaultToolsVersion: toolsVersion,\n                                                                  verifiedCompatibility: nil,\n                                                                  license: nil,\n                                                                  author: nil,\n                                                                  signer: nil,\n                                                                  createdAt: nil)\n\n        let mockPackageURL = \"https://packages.mock/\\(UUID().uuidString)\"\n        let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: mockPackageURL),\n                                                          location: mockPackageURL,\n                                                          summary: UUID().uuidString,\n                                                          keywords: [UUID().uuidString, UUID().uuidString],\n                                                          versions: [mockVersion],\n                                                          watchersCount: nil,\n                                                          readmeURL: nil,\n                                                          license: nil,\n                                                          authors: nil,\n                                                          languages: nil)\n\n        let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                name: UUID().uuidString,\n                                                                overview: UUID().uuidString,\n                                                                keywords: [UUID().uuidString, UUID().uuidString],\n                                                                packages: [mockPackage],\n                                                                createdAt: Date(),\n                                                                createdBy: nil,\n                                                                signature: nil)\n\n        let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                 name: UUID().uuidString,\n                                                                 overview: UUID().uuidString,\n                                                                 keywords: [UUID().uuidString, UUID().uuidString],\n                                                                 packages: [mockPackage],\n                                                                 createdAt: Date(),\n                                                                 createdBy: nil,\n                                                                 signature: nil)\n\n        mockCollections.append(mockCollection)\n        mockCollections.append(mockCollection2)\n\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage)\n        \n        let packageIndex = MockPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n\n        for collection in mockCollections {\n            _ = try await indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n\n        do {\n            let fetchCollections = Set(mockCollections.map { $0.identifier } + [mockCollection.identifier, mockCollection2.identifier])\n            let expectedPackages = Set(mockCollections.flatMap { $0.packages.map { $0.identity } } + [mockPackage.identity])\n            let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier])\n\n            let searchResult = try await indexAndCollections.listPackages(collections: fetchCollections)\n            XCTAssertEqual(searchResult.items.count, expectedPackages.count, \"list count should match\")\n            XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, \"items should match\")\n            XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, \"collections should match\")\n        }\n\n        // Call API for specific collections\n        do {\n            let fetchCollections = Set([mockCollections[0].identifier, mockCollection.identifier, mockCollection2.identifier])\n            let expectedPackages = Set(mockCollections[0].packages.map { $0.identity } + [mockPackage.identity])\n            let expectedCollections = Set([mockCollection.identifier, mockCollection2.identifier])\n\n            let searchResult = try await indexAndCollections.listPackages(collections: fetchCollections)\n            XCTAssertEqual(searchResult.items.count, expectedPackages.count, \"list count should match\")\n            XCTAssertEqual(Set(searchResult.items.map { $0.package.identity }), expectedPackages, \"items should match\")\n            XCTAssertEqual(Set(searchResult.items.first(where: { $0.package.identity == mockPackage.identity })?.collections ?? []), expectedCollections, \"collections should match\")\n        }\n    }\n\n    func testListTargets() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n        let mockCollections = makeMockCollections()\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage)\n\n        let packageIndex = MockPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n\n        do {\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await indexAndCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n\n        let targetsList = try await indexAndCollections.listTargets()\n        let expectedTargets = Set(mockCollections.flatMap { $0.packages.flatMap { $0.versions.flatMap { $0.defaultManifest!.targets.map { $0.name } } } })\n        XCTAssertEqual(Set(targetsList.map { $0.target.name }), expectedTargets, \"targets should match\")\n\n        let targetsPackagesList = Set(targetsList.flatMap { $0.packages })\n        let expectedPackages = Set(mockCollections.flatMap { $0.packages.filter { !$0.versions.filter { !expectedTargets.isDisjoint(with: $0.defaultManifest!.targets.map { $0.name }) }.isEmpty } }.map { $0.identity })\n        XCTAssertEqual(targetsPackagesList.count, expectedPackages.count, \"packages should match\")\n\n        let targetsCollectionsList = Set(targetsList.flatMap { $0.packages.flatMap { $0.collections } })\n        let expectedCollections = Set(mockCollections.filter { !$0.packages.filter { expectedPackages.contains($0.identity) }.isEmpty }.map { $0.identifier })\n        XCTAssertEqual(targetsCollectionsList, expectedCollections, \"collections should match\")\n    }\n    \n    func testFindTargets() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        var mockCollections = makeMockCollections()\n\n        let mockTargets = [UUID().uuidString, UUID().uuidString].map {\n            PackageCollectionsModel.Target(name: $0, moduleName: $0)\n        }\n\n        let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]),\n                            PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let mockManifest = PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: UUID().uuidString,\n            targets: mockTargets,\n            products: mockProducts,\n            minimumPlatformVersions: nil\n        )\n\n        let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0),\n                                                                  title: nil,\n                                                                  summary: nil,\n                                                                  manifests: [toolsVersion: mockManifest],\n                                                                  defaultToolsVersion: toolsVersion,\n                                                                  verifiedCompatibility: nil,\n                                                                  license: nil,\n                                                                  author: nil,\n                                                                  signer: nil,\n                                                                  createdAt: nil)\n\n        let mockPackageURL = \"https://packages.mock/\\(UUID().uuidString)\"\n        let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: mockPackageURL),\n                                                          location: mockPackageURL,\n                                                          summary: UUID().uuidString,\n                                                          keywords: [UUID().uuidString, UUID().uuidString],\n                                                          versions: [mockVersion],\n                                                          watchersCount: nil,\n                                                          readmeURL: nil,\n                                                          license: nil,\n                                                          authors: nil,\n                                                          languages: nil)\n\n        let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                name: UUID().uuidString,\n                                                                overview: UUID().uuidString,\n                                                                keywords: [UUID().uuidString, UUID().uuidString],\n                                                                packages: [mockPackage],\n                                                                createdAt: Date(),\n                                                                createdBy: nil,\n                                                                signature: nil)\n\n        let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                 name: UUID().uuidString,\n                                                                 overview: UUID().uuidString,\n                                                                 keywords: [UUID().uuidString, UUID().uuidString],\n                                                                 packages: [mockPackage],\n                                                                 createdAt: Date(),\n                                                                 createdBy: nil,\n                                                                 signature: nil)\n\n        let expectedCollections = [mockCollection, mockCollection2]\n        let expectedCollectionsIdentifiers = expectedCollections.map { $0.identifier }.sorted()\n\n        mockCollections.append(contentsOf: expectedCollections)\n\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage)\n\n        let packageIndex = MockPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n\n        for collection in mockCollections {\n            _ = try await indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n\n        do {\n            // search by exact target name\n            let searchResult = try await indexAndCollections.findTargets(mockTargets.first!.name, searchType: .exactMatch)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], \"packages should match\")\n            XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n        }\n\n        do {\n            // search by prefix target name\n            let searchResult = try await indexAndCollections.findTargets(String(mockTargets.first!.name.prefix(mockTargets.first!.name.count - 1)), searchType: .prefix)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.packages.map { $0.identity }, [mockPackage.identity], \"packages should match\")\n            XCTAssertEqual(searchResult.items.first?.packages.flatMap { $0.collections }.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n        }\n\n        do {\n            // empty search\n            let searchResult = try await indexAndCollections.findTargets(UUID().uuidString, searchType: .exactMatch)\n            XCTAssertEqual(searchResult.items.count, 0, \"list count should match\")\n        }\n    }\n        \n    func testListPackagesInIndex() async throws {\n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n        let packageCollections = makePackageCollections(mockCollections: [], storage: storage)\n        \n        let mockPackages = (0..<10).map { packageIndex -> PackageCollectionsModel.Package in\n            makeMockPackage(id: \"package-\\(packageIndex)\")\n        }\n        let packageIndex = MockPackageIndex(packages: mockPackages)\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n\n        let result = try await indexAndCollections.listPackagesInIndex(offset: 1, limit: 5)\n        XCTAssertFalse(result.items.isEmpty)\n    }\n    \n    func testGetPackageMetadata() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n        \n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n        let mockCollections = makeMockCollections(count: 3)\n        let mockPackage = mockCollections.last!.packages.last!\n        let mockMetadata = makeMockPackageBasicMetadata()\n        let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata])\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, metadataProvider: metadataProvider, storage: storage)\n\n        let packageIndex = MockPackageIndex(packages: mockCollections.last!.packages)\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n        \n        do {\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await indexAndCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n        \n        let metadata = try await indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location)\n        \n        let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier })\n        XCTAssertEqual(Set(metadata.collections), expectedCollections, \"collections should match\")\n        \n        // Metadata comes from package index - package returned as-is, no merging\n        XCTAssertEqual(metadata.package, mockPackage)\n        XCTAssertNotNil(metadata.provider)\n        XCTAssertEqual(metadata.provider?.name, \"package index\")\n    }\n    \n    func testGetPackageMetadata_brokenIndex() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n        \n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n        let mockCollections = makeMockCollections(count: 3)\n        let mockPackage = mockCollections.last!.packages.last!\n        let mockMetadata = makeMockPackageBasicMetadata()\n        let metadataProvider = MockMetadataProvider([mockPackage.identity: mockMetadata])\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, metadataProvider: metadataProvider, storage: storage)\n\n        let packageIndex = BrokenPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n        \n        do {\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list.count, 0, \"list should be empty\")\n        }\n\n        do {\n            for collection in mockCollections {\n                _ = try await indexAndCollections.addCollection(collection.source, order: nil)\n            }\n            let list = try await indexAndCollections.listCollections()\n            XCTAssertEqual(list.count, mockCollections.count, \"list count should match\")\n        }\n        \n        let metadata = try await indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location)\n\n        let expectedCollections = Set(mockCollections.filter { $0.packages.map { $0.identity }.contains(mockPackage.identity) }.map { $0.identifier })\n        XCTAssertEqual(Set(metadata.collections), expectedCollections, \"collections should match\")\n        \n        // Metadata comes from collections - merged with basic metadata\n        let expectedMetadata = PackageCollections.mergedPackageMetadata(package: mockPackage, basicMetadata: mockMetadata)\n        XCTAssertEqual(metadata.package, expectedMetadata, \"package should match\")\n\n        XCTAssertNil(metadata.provider)\n    }\n    \n    func testGetPackageMetadata_indexAndCollectionError() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n        \n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n        let packageCollections = makePackageCollections(mockCollections: [], storage: storage)\n\n        let packageIndex = BrokenPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n        \n        let mockPackage = makeMockPackage(id: \"test-package\")\n        // Package not found in collections; index is broken\n        await XCTAssertAsyncThrowsError(try await indexAndCollections.getPackageMetadata(identity: mockPackage.identity, location: mockPackage.location)) { error in\n            // Index error is returned\n            guard let _ = error as? BrokenPackageIndex.TerribleThing else {\n                return XCTFail(\"Expected BrokenPackageIndex.TerribleThing\")\n            }\n        }\n    }\n    \n    func testFindPackages() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n        \n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        var mockCollections = makeMockCollections()\n\n        let mockTargets = [UUID().uuidString, UUID().uuidString].map {\n            PackageCollectionsModel.Target(name: $0, moduleName: $0)\n        }\n\n        let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]),\n                            PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let mockManifest = PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: UUID().uuidString,\n            targets: mockTargets,\n            products: mockProducts,\n            minimumPlatformVersions: nil\n        )\n\n        let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0),\n                                                                  title: nil,\n                                                                  summary: nil,\n                                                                  manifests: [toolsVersion: mockManifest],\n                                                                  defaultToolsVersion: toolsVersion,\n                                                                  verifiedCompatibility: nil,\n                                                                  license: nil,\n                                                                  author: nil,\n                                                                  signer: nil,\n                                                                  createdAt: nil)\n\n        let url = \"https://packages.mock/\\(UUID().uuidString)\"\n        let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: url),\n                                                          location: url,\n                                                          summary: UUID().uuidString,\n                                                          keywords: [UUID().uuidString, UUID().uuidString],\n                                                          versions: [mockVersion],\n                                                          watchersCount: nil,\n                                                          readmeURL: nil,\n                                                          license: nil,\n                                                          authors: nil,\n                                                          languages: nil)\n\n        let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                name: UUID().uuidString,\n                                                                overview: UUID().uuidString,\n                                                                keywords: [UUID().uuidString, UUID().uuidString],\n                                                                packages: [mockPackage],\n                                                                createdAt: Date(),\n                                                                createdBy: nil,\n                                                                signature: nil)\n\n        let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                 name: UUID().uuidString,\n                                                                 overview: UUID().uuidString,\n                                                                 keywords: [UUID().uuidString, UUID().uuidString],\n                                                                 packages: [mockPackage],\n                                                                 createdAt: Date(),\n                                                                 createdBy: nil,\n                                                                 signature: nil)\n\n        let expectedCollections = [mockCollection, mockCollection2]\n        let expectedCollectionsIdentifiers = expectedCollections.map { $0.identifier }.sorted()\n\n        mockCollections.append(contentsOf: expectedCollections)\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage)\n\n        let packageIndex = MockPackageIndex(packages: [mockPackage])\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n        \n        for collection in mockCollections {\n            _ = try await indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n        \n        // both index and collections\n        do {\n            let searchResult = try await indexAndCollections.findPackages(mockPackage.identity.description, in: .both(collections: nil))\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n            XCTAssertEqual(searchResult.items.first?.indexes, [packageIndex.url], \"indexes should match\")\n        }\n        \n        // index only\n        do {\n            let searchResult = try await indexAndCollections.findPackages(mockPackage.identity.description, in: .index)\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertTrue(searchResult.items.first?.collections.isEmpty ?? true, \"collections should match\")\n            XCTAssertEqual(searchResult.items.first?.indexes, [packageIndex.url], \"indexes should match\")\n        }\n        \n        // collections only\n        do {\n            let searchResult = try await indexAndCollections.findPackages(mockPackage.identity.description, in: .collections(nil))\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n            XCTAssertTrue(searchResult.items.first?.indexes.isEmpty ?? true, \"indexes should match\")\n        }\n    }\n    \n    func testFindPackages_brokenIndex() async throws {\n        try PackageCollectionsTests_skipIfUnsupportedPlatform()\n        \n        let storage = makeMockStorage()\n        defer { XCTAssertNoThrow(try storage.close()) }\n\n        var mockCollections = makeMockCollections()\n\n        let mockTargets = [UUID().uuidString, UUID().uuidString].map {\n            PackageCollectionsModel.Target(name: $0, moduleName: $0)\n        }\n\n        let mockProducts = [PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: [mockTargets.first!]),\n                            PackageCollectionsModel.Product(name: UUID().uuidString, type: .executable, targets: mockTargets)]\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let mockManifest = PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: UUID().uuidString,\n            targets: mockTargets,\n            products: mockProducts,\n            minimumPlatformVersions: nil\n        )\n\n        let mockVersion = PackageCollectionsModel.Package.Version(version: TSCUtility.Version(1, 0, 0),\n                                                                  title: nil,\n                                                                  summary: nil,\n                                                                  manifests: [toolsVersion: mockManifest],\n                                                                  defaultToolsVersion: toolsVersion,\n                                                                  verifiedCompatibility: nil,\n                                                                  license: nil,\n                                                                  author: nil,\n                                                                  signer: nil,\n                                                                  createdAt: nil)\n\n        let url = \"https://packages.mock/\\(UUID().uuidString)\"\n        let mockPackage = PackageCollectionsModel.Package(identity: .init(urlString: url),\n                                                          location: url,\n                                                          summary: UUID().uuidString,\n                                                          keywords: [UUID().uuidString, UUID().uuidString],\n                                                          versions: [mockVersion],\n                                                          watchersCount: nil,\n                                                          readmeURL: nil,\n                                                          license: nil,\n                                                          authors: nil,\n                                                          languages: nil)\n\n        let mockCollection = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                name: UUID().uuidString,\n                                                                overview: UUID().uuidString,\n                                                                keywords: [UUID().uuidString, UUID().uuidString],\n                                                                packages: [mockPackage],\n                                                                createdAt: Date(),\n                                                                createdBy: nil,\n                                                                signature: nil)\n\n        let mockCollection2 = PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed.mock/\\(UUID().uuidString)\"),\n                                                                 name: UUID().uuidString,\n                                                                 overview: UUID().uuidString,\n                                                                 keywords: [UUID().uuidString, UUID().uuidString],\n                                                                 packages: [mockPackage],\n                                                                 createdAt: Date(),\n                                                                 createdBy: nil,\n                                                                 signature: nil)\n\n        let expectedCollections = [mockCollection, mockCollection2]\n        let expectedCollectionsIdentifiers = expectedCollections.map { $0.identifier }.sorted()\n\n        mockCollections.append(contentsOf: expectedCollections)\n        let packageCollections = makePackageCollections(mockCollections: mockCollections, storage: storage)\n\n        let packageIndex = BrokenPackageIndex()\n        let indexAndCollections = PackageIndexAndCollections(index: packageIndex, collections: packageCollections, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try indexAndCollections.close()) }\n        \n        for collection in mockCollections {\n            _ = try await indexAndCollections.addCollection(collection.source, trustConfirmationProvider: { _, cb in cb(true) })\n        }\n        \n        // both index and collections\n        do {\n            let searchResult = try await indexAndCollections.findPackages(mockPackage.identity.description, in: .both(collections: nil))\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n            // Results come from collections since index is broken\n            XCTAssertEqual(searchResult.items.first?.indexes, [], \"indexes should match\")\n        }\n        \n        // index only\n        do {\n            await XCTAssertAsyncThrowsError(try await indexAndCollections.findPackages(mockPackage.identity.description, in: .index)) { error in\n                guard error is BrokenPackageIndex.TerribleThing else {\n                    return XCTFail(\"invalid error \\(error)\")\n                }\n            }\n        }\n        \n        // collections only\n        do {\n            let searchResult = try await indexAndCollections.findPackages(mockPackage.identity.description, in: .collections(nil))\n            XCTAssertEqual(searchResult.items.count, 1, \"list count should match\")\n            XCTAssertEqual(searchResult.items.first?.collections.sorted(), expectedCollectionsIdentifiers, \"collections should match\")\n            // Not searching in index so should not be impacted by its error\n            XCTAssertTrue(searchResult.items.first?.indexes.isEmpty ?? true, \"indexes should match\")\n        }\n    }\n}\n\nprivate func makePackageCollections(\n    mockCollections: [PackageCollectionsModel.Collection],\n    metadataProvider: PackageMetadataProvider = MockMetadataProvider([:]),\n    storage: PackageCollections.Storage\n) -> PackageCollections {\n    let configuration = PackageCollections.Configuration()\n    let collectionProviders = [PackageCollectionsModel.CollectionSourceType.json: MockCollectionsProvider(mockCollections)]\n    let metadataProvider = metadataProvider\n    \n    return PackageCollections(\n        configuration: configuration,\n        fileSystem: localFileSystem,\n        observabilityScope: ObservabilitySystem.NOOP,\n        storage: storage,\n        collectionProviders: collectionProviders,\n        metadataProvider: metadataProvider\n    )\n}\n\nprivate struct MockPackageIndex: PackageIndexProtocol {\n    let isEnabled = true\n    let url: URL\n\n    private let packages: [PackageCollectionsModel.Package]\n    \n    init(\n        url: URL = \"https://mock-package-index\",\n        packages: [PackageCollectionsModel.Package] = []\n    ) {\n        self.url = url\n        self.packages = packages\n    }\n\n    func getPackageMetadata(\n        identity: PackageIdentity,\n        location: String?\n    ) async throws -> PackageCollectionsModel.PackageMetadata {\n        guard let package = self.packages.first(where: { $0.identity == identity }) else {\n            throw NotFoundError(\"Package \\(identity) not found\")\n        }\n        return (package: package, collections: [], provider: .init(name: \"package index\", authTokenType: nil, isAuthTokenConfigured: true))\n    }\n\n    func findPackages(\n        _ query: String\n    ) async throws  -> PackageCollectionsModel.PackageSearchResult{\n        let items = self.packages.filter { $0.identity.description.contains(query) }\n        return PackageCollectionsModel.PackageSearchResult(items: items.map { .init(package: $0, collections: [], indexes: [self.url]) })\n    }\n    \n    func listPackages(\n        offset: Int,\n        limit: Int\n    ) async throws -> PackageCollectionsModel.PaginatedPackageList {\n        guard !self.packages.isEmpty, offset < self.packages.count, limit > 0 else {\n            return PackageCollectionsModel.PaginatedPackageList(items: [], offset: offset, limit: limit, total: self.packages.count)\n        }\n\n        return PackageCollectionsModel.PaginatedPackageList(\n            items: Array(self.packages[offset..<min(self.packages.count, offset + limit)]),\n            offset: offset,\n            limit: limit,\n            total: self.packages.count\n        )\n    }\n}\n\nprivate struct BrokenPackageIndex: PackageIndexProtocol {\n    let isEnabled = true\n    \n    func getPackageMetadata(\n        identity: PackageIdentity,\n        location: String?\n    ) async throws -> PackageCollectionsModel.PackageMetadata {\n        throw TerribleThing()\n    }\n\n    func findPackages(\n        _ query: String\n    ) async throws -> PackageCollectionsModel.PackageSearchResult {\n        throw TerribleThing()\n    }\n    \n    func listPackages(\n        offset: Int,\n        limit: Int\n    ) async throws -> PackageCollectionsModel.PaginatedPackageList {\n        throw TerribleThing()\n    }\n    \n    struct TerribleThing: Error {}\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageIndexConfigurationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Basics.InMemoryFileSystem\nimport PackageCollections\nimport XCTest\n\nfinal class PackageIndexConfigurationTests: XCTestCase {\n    func testSaveAndLoad() throws {\n        let url = URL(\"https://package-index.test\")\n        let configuration = PackageIndexConfiguration(url: url)\n        \n        let fileSystem = InMemoryFileSystem()\n        let storage = PackageIndexConfigurationStorage(path: try fileSystem.swiftPMConfigurationDirectory.appending(\"index.json\"), fileSystem: fileSystem)\n        try storage.save(configuration)\n        \n        let loadedConfiguration = try storage.load()\n        XCTAssertEqual(loadedConfiguration, configuration)\n    }\n    \n    func testLoad_fileDoesNotExist() throws {\n        let fileSystem = InMemoryFileSystem()\n        let storage = PackageIndexConfigurationStorage(path: try fileSystem.swiftPMConfigurationDirectory.appending(\"index.json\"), fileSystem: fileSystem)\n        let configuration = try storage.load()\n        XCTAssertNil(configuration.url)\n    }\n    \n    func testLoad_urlOnly() throws {\n        let url = URL(\"https://package-index.test\")\n        let configJSON = \"\"\"\n        {\n            \"index\": {\n                \"url\": \"\\(url.absoluteString)\"\n            }\n        }\n        \"\"\"\n        \n        let fileSystem = InMemoryFileSystem()\n        let configPath = try fileSystem.swiftPMConfigurationDirectory.appending(\"index.json\")\n        if !fileSystem.exists(configPath.parentDirectory, followSymlink: false) {\n            try fileSystem.createDirectory(configPath.parentDirectory, recursive: true)\n        }\n        try fileSystem.writeFileContents(configPath, string: configJSON)\n        \n        let storage = PackageIndexConfigurationStorage(path: configPath, fileSystem: fileSystem)\n        let configuration = try storage.load()\n        XCTAssertEqual(configuration.url, url)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/PackageIndexTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n@testable import PackageCollections\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nclass PackageIndexTests: XCTestCase {\n    func testGetPackageMetadata() async throws {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, disableCache: true)\n        configuration.enabled = true\n        \n        let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n        let packageIdentity = PackageIdentity(url: repoURL)\n        let package = makeMockPackage(id: \"test-package\")\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            switch (request.method, request.url) {\n            case (.get, url.appendingPathComponent(\"packages\").appendingPathComponent(packageIdentity.description)):\n                let data = try! JSONEncoder.makeWithDefaults().encode(package)\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                          body: data)))\n            default:\n                XCTFail(\"method and url should match\")\n            }\n        }\n        \n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n                \n        let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let metadata = try await index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString)\n        XCTAssertEqual(metadata.package.identity, package.identity)\n        XCTAssert(metadata.collections.isEmpty)\n        XCTAssertNotNil(metadata.provider)\n    }\n    \n    func testGetPackageMetadata_featureDisabled() async {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, disableCache: true)\n        configuration.enabled = false\n                \n        let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n        await XCTAssertAsyncThrowsError(try await index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString)) { error in\n            XCTAssertEqual(error as? PackageIndexError, .featureDisabled)\n        }\n    }\n    \n    func testGetPackageMetadata_notConfigured() async {\n        var configuration = PackageIndexConfiguration(url: nil, disableCache: true)\n        configuration.enabled = true\n                \n        let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n        await XCTAssertAsyncThrowsError(try await index.getPackageMetadata(identity: .init(url: repoURL), location: repoURL.absoluteString)) { error in\n            XCTAssertEqual(error as? PackageIndexError, .notConfigured)\n        }\n    }\n    \n    func testFindPackages() async throws {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, searchResultMaxItemsCount: 10, disableCache: true)\n        configuration.enabled = true\n        \n        let packages = (0..<3).map { packageIndex -> PackageCollectionsModel.Package in\n            makeMockPackage(id: \"package-\\(packageIndex)\")\n        }\n        let query = \"foobar\"\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            switch (request.method, request.url) {\n            case (.get, URL(string: url.appendingPathComponent(\"search\").absoluteString + \"?q=\\(query)\")!):\n                let data = try! JSONEncoder.makeWithDefaults().encode(packages)\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                          body: data)))\n            default:\n                XCTFail(\"method and url should match\")\n            }\n        }\n        \n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n                \n        let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let result = try await index.findPackages(query)\n        XCTAssertEqual(result.items.count, packages.count)\n        for (i, item) in result.items.enumerated() {\n            XCTAssertEqual(item.package.identity, packages[i].identity)\n            XCTAssert(item.collections.isEmpty)\n            XCTAssertEqual(item.indexes, [url])\n        }\n    }\n    \n    func testFindPackages_resultsLimit() async throws {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, searchResultMaxItemsCount: 3, disableCache: true)\n        configuration.enabled = true\n        \n        // This is larger than searchResultMaxItemsCount\n        let packages = (0..<5).map { packageIndex -> PackageCollectionsModel.Package in\n            makeMockPackage(id: \"package-\\(packageIndex)\")\n        }\n        let query = \"foobar\"\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            switch (request.method, request.url) {\n            case (.get, URL(string: url.appendingPathComponent(\"search\").absoluteString + \"?q=\\(query)\")!):\n                let data = try! JSONEncoder.makeWithDefaults().encode(packages)\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                          body: data)))\n            default:\n                XCTFail(\"method and url should match\")\n            }\n        }\n        \n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n                \n        let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let result = try await index.findPackages(query)\n        XCTAssertEqual(result.items.count, configuration.searchResultMaxItemsCount)\n        for (i, item) in result.items.enumerated() {\n            XCTAssertEqual(item.package.identity, packages[i].identity)\n            XCTAssert(item.collections.isEmpty)\n            XCTAssertEqual(item.indexes, [url])\n        }\n    }\n    \n    func testFindPackages_featureDisabled() async {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, disableCache: true)\n        configuration.enabled = false\n                \n        let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        await XCTAssertAsyncThrowsError(try await index.findPackages(\"foobar\")) { error in\n            XCTAssertEqual(error as? PackageIndexError, .featureDisabled)\n        }\n    }\n    \n    func testFindPackages_notConfigured() async {\n        var configuration = PackageIndexConfiguration(url: nil, disableCache: true)\n        configuration.enabled = true\n                \n        let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        await XCTAssertAsyncThrowsError(try await index.findPackages(\"foobar\")) { error in\n            XCTAssertEqual(error as? PackageIndexError, .notConfigured)\n        }\n    }\n    \n    func testListPackages() async throws {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, disableCache: true)\n        configuration.enabled = true\n        \n        let offset = 4\n        let limit = 3\n        let total = 20\n        let packages = (0..<limit).map { packageIndex -> PackageCollectionsModel.Package in\n            makeMockPackage(id: \"package-\\(packageIndex)\")\n        }\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            switch (request.method, request.url) {\n            case (.get, URL(string: url.appendingPathComponent(\"packages\").absoluteString + \"?offset=\\(offset)&limit=\\(limit)\")!):\n                let response = PackageIndex.ListResponse(items: packages, total: total)\n                let data = try! JSONEncoder.makeWithDefaults().encode(response)\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                          body: data)))\n            default:\n                XCTFail(\"method and url should match\")\n            }\n        }\n        \n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n                \n        let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let result = try await index.listPackages(offset: offset, limit: limit)\n        XCTAssertEqual(result.items.count, packages.count)\n        XCTAssertEqual(result.offset, offset)\n        XCTAssertEqual(result.limit, limit)\n        XCTAssertEqual(result.total, total)\n    }\n    \n    func testListPackages_featureDisabled() async {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, disableCache: true)\n        configuration.enabled = false\n                \n        let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        await XCTAssertAsyncThrowsError(try await index.listPackages(offset: 0, limit: 10)) { error in\n            XCTAssertEqual(error as? PackageIndexError, .featureDisabled)\n        }\n    }\n    \n    func testListPackages_notConfigured() async {\n        var configuration = PackageIndexConfiguration(url: nil, disableCache: true)\n        configuration.enabled = true\n                \n        let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        await XCTAssertAsyncThrowsError(try await index.listPackages(offset: 0, limit: 10)) { error in\n            XCTAssertEqual(error as? PackageIndexError, .notConfigured)\n        }\n    }\n    \n    func testAsPackageMetadataProvider() async throws {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, disableCache: true)\n        configuration.enabled = true\n        \n        let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n        let packageIdentity = PackageIdentity(url: repoURL)\n        let package = makeMockPackage(id: \"test-package\")\n        let handler: LegacyHTTPClient.Handler = { request, _, completion in\n            switch (request.method, request.url) {\n            case (.get, url.appendingPathComponent(\"packages\").appendingPathComponent(packageIdentity.description)):\n                let data = try! JSONEncoder.makeWithDefaults().encode(package)\n                completion(.success(.init(statusCode: 200,\n                                          headers: .init([.init(name: \"Content-Length\", value: \"\\(data.count)\")]),\n                                          body: data)))\n            default:\n                XCTFail(\"method and url should match\")\n            }\n        }\n        \n        let httpClient = LegacyHTTPClient(handler: handler)\n        httpClient.configuration.circuitBreakerStrategy = .none\n        httpClient.configuration.retryStrategy = .none\n                \n        let index = PackageIndex(configuration: configuration, customHTTPClient: httpClient, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let metadata = try await index.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString)\n        XCTAssertEqual(metadata.summary, package.summary)\n    }\n    \n    func testAsGetPackageMetadataProvider_featureDisabled() async {\n        let url = URL(\"https://package-index.test\")\n        var configuration = PackageIndexConfiguration(url: url, disableCache: true)\n        configuration.enabled = false\n                \n        let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n        await XCTAssertAsyncThrowsError(try await index.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString)) { error in\n            XCTAssertEqual(error as? PackageIndexError, .featureDisabled)\n        }\n    }\n    \n    func testAsGetPackageMetadataProvider_notConfigured() async {\n        var configuration = PackageIndexConfiguration(url: nil, disableCache: true)\n        configuration.enabled = true\n                \n        let index = PackageIndex(configuration: configuration, callbackQueue: .sharedConcurrent, observabilityScope: ObservabilitySystem.NOOP)\n        defer { XCTAssertNoThrow(try index.close()) }\n        \n        let repoURL = SourceControlURL(\"https://github.com/octocat/Hello-World.git\")\n        await XCTAssertAsyncThrowsError(try await index.syncGet(identity: .init(url: repoURL), location: repoURL.absoluteString)) { error in\n            XCTAssertEqual(error as? PackageIndexError, .notConfigured)\n        }\n    }\n}\n\nprivate extension PackageIndex {\n    func syncGet(identity: PackageIdentity, location: String) async throws -> Model.PackageBasicMetadata {\n        try await self.get(identity: identity, location: location).0.get()\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/TrieTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\n@testable import PackageCollections\n\n@Suite struct TrieTests {\n    @Test func testContains() {\n        let trie = Trie<Int>()\n\n        let doc1 = \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG\"\n        self.indexDocument(id: 1, contents: doc1, trie: trie)\n\n        // Whole word match\n        #expect(trie.contains(word: \"brown\", prefixMatch: false))\n        #expect(trie.contains(word: \"Fox\", prefixMatch: false))\n        #expect(!trie.contains(word: \"foobar\", prefixMatch: false))\n\n        // Prefix match\n        #expect(trie.contains(word: \"d\", prefixMatch: true))\n        #expect(trie.contains(word: \"Do\", prefixMatch: true))\n        #expect(!trie.contains(word: \"doo\", prefixMatch: true))\n    }\n\n    @Test func testFind() throws {\n        let trie = Trie<Int>()\n\n        let doc1 = \"the quick brown fox jumps over the lazy dog and the dog does not notice the fox jumps over it\"\n        let doc2 = \"the quick brown fox jumps over the lazy dog for the lazy dog has blocked its way for far too long\"\n        self.indexDocument(id: 1, contents: doc1, trie: trie)\n        self.indexDocument(id: 2, contents: doc2, trie: trie)\n\n        #expect(try trie.find(word: \"brown\") == [1, 2])\n        #expect(try trie.find(word: \"blocked\") == [2])\n        #expect(throws:NotFoundError.self) {\n            try trie.find(word: \"fo\")\n        }\n    }\n\n    func testFindWithPrefix() throws {\n        let trie = Trie<Int>()\n\n        let doc1 = \"the quick brown fox jumps over the lazy dog and the dog does not notice the fox jumps over it\"\n        let doc2 = \"the quick brown fox jumps over the lazy dog for the lazy dog has blocked its way for far too long\"\n        self.indexDocument(id: 1, contents: doc1, trie: trie)\n        self.indexDocument(id: 2, contents: doc2, trie: trie)\n\n        #expect(try trie.findWithPrefix(\"f\") == [\"fox\": [1, 2], \"for\": [2], \"far\": [2]])\n        #expect(try trie.findWithPrefix(\"fo\") == [\"fox\": [1, 2], \"for\": [2]])\n        #expect(try trie.findWithPrefix(\"far\") == [\"far\": [2]])\n        #expect(throws: NotFoundError.self) {\n            try trie.findWithPrefix(\"foo\")\n        }\n    }\n\n    @Test func testRemoveDocument() throws {\n        let trie = Trie<Int>()\n\n        let doc1 = \"the quick brown fox jumps over the lazy dog\"\n        let doc2 = \"the dog does not notice the fox jumps over it\"\n        let doc3 = \"it has blocked the fox for far too long\"\n        self.indexDocument(id: 1, contents: doc1, trie: trie)\n        self.indexDocument(id: 2, contents: doc2, trie: trie)\n        self.indexDocument(id: 3, contents: doc3, trie: trie)\n\n        #expect(try trie.find(word: \"fox\") == [1, 2, 3])\n        #expect(try trie.find(word: \"dog\") == [1, 2])\n        #expect(try trie.find(word: \"it\") == [2, 3])\n        #expect(try trie.find(word: \"lazy\") == [1])\n        #expect(try trie.find(word: \"notice\") == [2])\n        #expect(try trie.find(word: \"blocked\") == [3])\n\n        trie.remove(document: 3)\n\n        #expect(try trie.find(word: \"fox\") == [1, 2])\n        #expect(try trie.find(word: \"dog\") == [1, 2])\n        #expect(try trie.find(word: \"it\") == [2])\n        #expect(try trie.find(word: \"lazy\") == [1])\n        #expect(try trie.find(word: \"notice\") == [2])\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"blocked\")\n        }\n\n        trie.remove(document: 1)\n\n        #expect(try trie.find(word: \"fox\") == [2])\n        #expect(try trie.find(word: \"dog\") == [2])\n        #expect(try trie.find(word: \"it\") == [2])\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"lazy\")\n        }\n        #expect(try trie.find(word: \"notice\") == [2])\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"blocked\")\n        }\n\n        trie.remove(document: 2)\n\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"fox\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"dog\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"it\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"lazy\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"notice\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"blocked\")\n        }\n    }\n\n    func testRemoveDocumentsWithPredicate() throws {\n        let trie = Trie<Int>()\n\n        let doc1 = \"the quick brown fox jumps over the lazy dog\"\n        let doc2 = \"the dog does not notice the fox jumps over it\"\n        let doc3 = \"it has blocked the fox for far too long\"\n        self.indexDocument(id: 1, contents: doc1, trie: trie)\n        self.indexDocument(id: 2, contents: doc2, trie: trie)\n        self.indexDocument(id: 3, contents: doc3, trie: trie)\n\n        #expect(try trie.find(word: \"fox\") == [1, 2, 3])\n        #expect(try trie.find(word: \"dog\") == [1, 2])\n        #expect(try trie.find(word: \"it\") == [2, 3])\n        #expect(try trie.find(word: \"lazy\") == [1])\n        #expect(try trie.find(word: \"notice\") == [2])\n        #expect(try trie.find(word: \"blocked\") == [3])\n\n        trie.remove { $0 == 3 }\n\n        #expect(try trie.find(word: \"fox\") == [1, 2])\n        #expect(try trie.find(word: \"dog\") == [1, 2])\n        #expect(try trie.find(word: \"it\") == [2])\n        #expect(try trie.find(word: \"lazy\") == [1])\n        #expect(try trie.find(word: \"notice\") == [2])\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"blocked\")\n        }\n\n        trie.remove { $0 == 1 }\n\n        #expect(try trie.find(word: \"fox\") == [2])\n        #expect(try trie.find(word: \"dog\") == [2])\n        #expect(try trie.find(word: \"it\") == [2])\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"lazy\")\n        }\n        #expect(try trie.find(word: \"notice\") == [2])\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"blocked\")\n        }\n\n        trie.remove { $0 == 2 }\n\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"fox\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"dog\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"it\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"lazy\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"notice\")\n        }\n        #expect(throws: NotFoundError.self) {\n            try trie.find(word: \"blocked\")\n        }\n    }\n\n    private func indexDocument(id: Int, contents: String, trie: Trie<Int>) {\n        let words = contents.components(separatedBy: \" \")\n        words.forEach { word in\n            trie.insert(word: word, foundIn: id)\n        }\n    }\n\n    @Test func testThreadSafe() async throws {\n        let trie = Trie<Int>()\n\n        let docCount = 100\n        await withTaskGroup { group in\n            for i in 0 ..< docCount {\n                group.addTask {\n                    try? await Task.sleep(for: .milliseconds(Double.random(in: 100...300)))\n\n                    trie.remove { $0 == i }\n                    trie.insert(word: \"word-\\(i)\", foundIn: i)\n                    trie.insert(word: \"test\", foundIn: i)\n                }\n            }\n            await group.waitForAll()\n        }\n        for doc in 0 ..< docCount {\n            #expect(try trie.find(word: \"word-\\(doc)\") == [doc])\n            #expect(try trie.find(word: \"test\").count == docCount)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/Utility.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport struct Foundation.Date\nimport struct Foundation.URL\nimport struct Foundation.UUID\n@testable import PackageCollections\nimport PackageCollectionsModel\nimport PackageCollectionsSigning\nimport PackageModel\nimport SourceControl\n\nimport struct TSCUtility.Version\n\nfunc makeMockSources(count: Int = Int.random(in: 5 ... 10)) -> [PackageCollectionsModel.CollectionSource] {\n    let isTrusted: [Bool?] = [true, false, nil]\n    return (0 ..< count).map { index in\n        .init(type: .json, url: \"https://source-\\(index)\", isTrusted: isTrusted.randomElement()!)\n    }\n}\n\nfileprivate let platforms: [PackageModel.Platform] = [.macOS, .iOS, .tvOS, .watchOS, .linux, .android, .windows, .wasi, .openbsd]\nfileprivate let supportedPlatforms: [PackageModel.SupportedPlatform] = [\n    .init(platform: .macOS, version: .init(\"10.15\")),\n    .init(platform: .iOS, version: .init(\"13\")),\n    .init(platform: .watchOS, version: \"6\"),\n]\n\nfunc makeMockCollections(count: Int = Int.random(in: 50 ... 100), maxPackages: Int = 50, signed: Bool = true) -> [PackageCollectionsModel.Collection] {\n    (0 ..< count).map { collectionIndex in\n        let packages = (0 ..< Int.random(in: min(5, maxPackages) ... maxPackages)).map { packageIndex -> PackageCollectionsModel.Package in\n            makeMockPackage(id: \"package-\\(packageIndex)\")\n        }\n\n        var signature: PackageCollectionsModel.SignatureData?\n        if signed {\n            signature = .init(\n                certificate: PackageCollectionsModel.SignatureData.Certificate(\n                    subject: .init(userID: nil, commonName: \"subject-\\(collectionIndex)\", organizationalUnit: nil, organization: nil),\n                    issuer: .init(userID: nil, commonName: \"issuer-\\(collectionIndex)\", organizationalUnit: nil, organization: nil)\n                ),\n                isVerified: true\n            )\n        }\n\n        return PackageCollectionsModel.Collection(source: .init(type: .json, url: \"https://feed-\\(collectionIndex)\"),\n                                                  name: \"collection \\(collectionIndex)\",\n                                                  overview: \"collection \\(collectionIndex) description\",\n                                                  keywords: (0 ..< Int.random(in: 1 ... 3)).map { \"keyword \\($0)\" },\n                                                  packages: packages,\n                                                  createdAt: Date(),\n                                                  createdBy: PackageCollectionsModel.Collection.Author(name: \"Jane Doe\"),\n                                                  signature: signature)\n    }\n}\n\nfunc makeMockPackage(id: String) -> PackageCollectionsModel.Package {\n    let versions = (0 ..< Int.random(in: 1 ... 3)).map { versionIndex -> PackageCollectionsModel.Package.Version in\n        let targets = (0 ..< Int.random(in: 1 ... 5)).map {\n            PackageCollectionsModel.Target(name: \"\\(id)-target-\\($0)\",\n                                           moduleName: \"module-\\(id)-target-\\($0)\")\n        }\n        let products = (0 ..< Int.random(in: 1 ... 3)).map {\n            PackageCollectionsModel.Product(name: \"\\(id)-product-\\($0)\",\n                                            type: .executable,\n                                            targets: targets)\n        }\n        let minimumPlatformVersions = (0 ..< Int.random(in: 1 ... 2)).map { _ in supportedPlatforms.randomElement()! }\n        let toolsVersion = ToolsVersion(string: \"5.2\")!\n        let manifests = [toolsVersion: PackageCollectionsModel.Package.Version.Manifest(\n            toolsVersion: toolsVersion,\n            packageName: id,\n            targets: targets,\n            products: products,\n            minimumPlatformVersions: minimumPlatformVersions\n        )]\n\n        let verifiedCompatibility = (0 ..< Int.random(in: 1 ... 3)).map { _ in\n            PackageCollectionsModel.Compatibility(\n                platform: platforms.randomElement()!,\n                swiftVersion: SwiftLanguageVersion.knownSwiftLanguageVersions.randomElement()!\n            )\n        }\n        let licenseType = PackageCollectionsModel.LicenseType.allCases.randomElement()!\n        let license = PackageCollectionsModel.License(type: licenseType, url: \"http://\\(licenseType).license\")\n\n        return PackageCollectionsModel.Package.Version(version: TSCUtility.Version(versionIndex, 0, 0),\n                                                       title: nil,\n                                                       summary: \"\\(versionIndex) description\",\n                                                       manifests: manifests,\n                                                       defaultToolsVersion: toolsVersion,\n                                                       verifiedCompatibility: verifiedCompatibility,\n                                                       license: license,\n                                                       author: nil,\n                                                       signer: nil,\n                                                       createdAt: Date())\n    }\n\n    return PackageCollectionsModel.Package(identity: PackageIdentity.plain(\"test-\\(id).\\(id)\"),\n                                           location: \"https://\\(id)\",\n                                           summary: \"\\(id) description\",\n                                           keywords: (0 ..< Int.random(in: 1 ... 3)).map { \"keyword \\($0)\" },\n                                           versions: versions,\n                                           watchersCount: Int.random(in: 1 ... 1000),\n                                           readmeURL: \"https://\\(id)-readme\",\n                                           license: PackageCollectionsModel.License(type: .Apache2_0, url: \"https://\\(id).license\"),\n                                           authors: nil,\n                                           languages: nil)\n}\n\nfunc makeMockPackageBasicMetadata() -> PackageCollectionsModel.PackageBasicMetadata {\n    return .init(summary: UUID().uuidString,\n                 keywords: (0 ..< Int.random(in: 1 ... 3)).map { \"keyword \\($0)\" },\n                 versions: (0 ..< Int.random(in: 1 ... 10)).map { .init(\n                    version: TSCUtility.Version($0, 0, 0),\n                    title: \"title \\($0)\",\n                    summary: \"description \\($0)\",\n                    author: nil,\n                    createdAt: Date()\n                 )},\n                 watchersCount: Int.random(in: 0 ... 50),\n                 readmeURL: \"https://package-readme\",\n                 license: PackageCollectionsModel.License(type: .Apache2_0, url: \"https://package-license\"),\n                 authors: (0 ..< Int.random(in: 1 ... 10)).map { .init(username: \"\\($0)\", url: nil, service: nil) },\n                 languages: [\"Swift\"])\n}\n\nfunc makeMockStorage(_ collectionsStorageConfig: SQLitePackageCollectionsStorage.Configuration = .init()) -> PackageCollections.Storage {\n    let mockFileSystem = InMemoryFileSystem()\n    return .init(\n        sources: FilePackageCollectionsSourcesStorage(fileSystem: mockFileSystem),\n        collections: SQLitePackageCollectionsStorage(\n            location: .memory,\n            configuration: collectionsStorageConfig,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    )\n}\n\nstruct MockCollectionsProvider: PackageCollectionProvider {\n    let collections: [PackageCollectionsModel.Collection]\n    let collectionsWithInvalidSignature: Set<PackageCollectionsModel.CollectionSource>?\n\n    init(_ collections: [PackageCollectionsModel.Collection], collectionsWithInvalidSignature: Set<PackageCollectionsModel.CollectionSource>? = nil) {\n        self.collections = collections\n        self.collectionsWithInvalidSignature = collectionsWithInvalidSignature\n    }\n\n    func get(_ source: PackageCollectionsModel.CollectionSource) async throws -> PackageCollectionsModel.Collection {\n        if let collection = (self.collections.first { $0.source == source }) {\n            if self.collectionsWithInvalidSignature?.contains(source) ?? false {\n                throw PackageCollectionError.invalidSignature\n            }\n            return collection\n        }\n        throw NotFoundError(\"\\(source)\")\n    }\n}\n\nstruct MockMetadataProvider: PackageMetadataProvider {\n    let name: String = \"MockMetadataProvider\"\n\n    let packages: [PackageIdentity: PackageCollectionsModel.PackageBasicMetadata]\n\n    init(_ packages: [PackageIdentity: PackageCollectionsModel.PackageBasicMetadata]) {\n        self.packages = packages\n    }\n\n    func get(\n        identity: PackageIdentity,\n        location: String\n    ) async -> (Result<PackageCollectionsModel.PackageBasicMetadata, Error>, PackageMetadataProviderContext?) {\n        guard let packageMetadata = self.packages[identity] else {\n            return (.failure(NotFoundError(\"\\(identity)\")), nil)\n        }\n        return (.success(packageMetadata), nil)\n    }\n}\n\nstruct MockCollectionSignatureValidator: PackageCollectionSignatureValidator {\n    let collections: Set<String>\n    let certPolicyKeys: Set<CertificatePolicyKey>\n    let hasTrustedRootCerts: Bool\n\n    init(_ collections: Set<String> = [], certPolicyKeys: Set<CertificatePolicyKey> = [], hasTrustedRootCerts: Bool = true) {\n        self.collections = collections\n        self.certPolicyKeys = certPolicyKeys\n        self.hasTrustedRootCerts = hasTrustedRootCerts\n    }\n\n    func validate(\n        signedCollection: PackageCollectionModel.V1.SignedCollection,\n        certPolicyKey: CertificatePolicyKey\n    ) async throws {\n        guard self.hasTrustedRootCerts else {\n            throw PackageCollectionSigningError.noTrustedRootCertsConfigured\n        }\n\n        if self.collections.contains(signedCollection.collection.name) || self.certPolicyKeys.contains(certPolicyKey) {\n            return\n        } else {\n            throw PackageCollectionSigningError.invalidSignature\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageCollectionsTests/ValidationMessageTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\n@testable import PackageCollections\n\nclass ValidationMessageTests: XCTestCase {\n    func testMessageToError() {\n        let warningWithProperty = ValidationMessage.warning(\"warning with property\", property: \"foo\")\n        let warning = ValidationMessage.warning(\"warning\")\n        let errorWithProperty = ValidationMessage.error(\"error with property\", property: \"bar\")\n        let error = ValidationMessage.error(\"error\")\n\n        let messages = [warningWithProperty, errorWithProperty, warning, error]\n\n        do {\n            let errors = messages.errors(include: [.warning])!\n            XCTAssertEqual(2, errors.count)\n\n            guard case .property(_, let m0) = errors[0], m0 == warningWithProperty.message else {\n                return XCTFail(\"Expected .property error\")\n            }\n            guard case .other(let m1) = errors[1], m1 == warning.message else {\n                return XCTFail(\"Expected .other error\")\n            }\n        }\n\n        do {\n            let errors = messages.errors(include: [.error])!\n            XCTAssertEqual(2, errors.count)\n\n            guard case .property(_, let m0) = errors[0], m0 == errorWithProperty.message else {\n                return XCTFail(\"Expected .property error\")\n            }\n            guard case .other(let m1) = errors[1], m1 == error.message else {\n                return XCTFail(\"Expected .other error\")\n            }\n        }\n\n        do {\n            let errors = messages.errors(include: [.warning, .error])!\n            XCTAssertEqual(4, errors.count)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageDescriptionTests/VersionTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackageDescription\nimport XCTest\n\nclass VersionTests: XCTestCase {\n    \n    func testVersionInitialization() {\n        let v0 = Version(0, 0, 0, prereleaseIdentifiers: [], buildMetadataIdentifiers: [])\n        XCTAssertEqual(v0.minor, 0)\n        XCTAssertEqual(v0.minor, 0)\n        XCTAssertEqual(v0.patch, 0)\n        XCTAssertEqual(v0.prereleaseIdentifiers, [])\n        XCTAssertEqual(v0.buildMetadataIdentifiers, [])\n        \n        let v1 = Version(1, 1, 2, prereleaseIdentifiers: [\"3\", \"5\"], buildMetadataIdentifiers: [\"8\", \"13\"])\n        XCTAssertEqual(v1.minor, 1)\n        XCTAssertEqual(v1.minor, 1)\n        XCTAssertEqual(v1.patch, 2)\n        XCTAssertEqual(v1.prereleaseIdentifiers, [\"3\", \"5\"])\n        XCTAssertEqual(v1.buildMetadataIdentifiers, [\"8\", \"13\"])\n        \n        XCTAssertEqual(\n            Version(3, 5, 8),\n            Version(3, 5, 8, prereleaseIdentifiers: [], buildMetadataIdentifiers: [])\n        )\n        \n        XCTAssertEqual(\n            Version(13, 21, 34, prereleaseIdentifiers: [\"55\"]),\n            Version(13, 21, 34, prereleaseIdentifiers: [\"55\"], buildMetadataIdentifiers: [])\n        )\n        \n        XCTAssertEqual(\n            Version(89, 144, 233, buildMetadataIdentifiers: [\"377\"]),\n            Version(89, 144, 233, prereleaseIdentifiers: [], buildMetadataIdentifiers: [\"377\"])\n        )\n    }\n    \n    // Don't refactor out either `XCTAssertGreaterThan` or `XCTAssertFalse(<)`.\n    // They may appear redundant, but they test different things.\n    // `XCTAssertGreaterThan` tests the \"true\" path of `>` which is basically the \"true\" path of `<`.\n    // `XCTAssertFalse(<)` tests the \"false\" path of `<`.\n    func testVersionComparison() {\n        \n        // MARK: version core vs. version core\n        \n        XCTAssertGreaterThan(Version(2, 1, 1), Version(1, 2, 3))\n        XCTAssertGreaterThan(Version(1, 3, 1), Version(1, 2, 3))\n        XCTAssertGreaterThan(Version(1, 2, 4), Version(1, 2, 3))\n        \n        XCTAssertFalse(Version(2, 1, 1) < Version(1, 2, 3))\n        XCTAssertFalse(Version(1, 3, 1) < Version(1, 2, 3))\n        XCTAssertFalse(Version(1, 2, 4) < Version(1, 2, 3))\n        \n        // MARK: version core vs. version core + pre-release\n        \n        XCTAssertGreaterThan(Version(1, 2, 3), Version(1, 2, 3, prereleaseIdentifiers: [\"\"]))\n        XCTAssertGreaterThan(Version(1, 2, 3), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]))\n        XCTAssertLessThan(Version(1, 2, 2), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]))\n        \n        XCTAssertFalse(Version(1, 2, 3) < Version(1, 2, 3, prereleaseIdentifiers: [\"\"]))\n        XCTAssertFalse(Version(1, 2, 3) < Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]))\n        \n        // MARK: version core + pre-release vs. version core + pre-release\n        \n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"\"]))\n        \n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"alpha1\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"alpha2\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"alpha-\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"alpha\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"beta\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\", \"beta\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"alpha\"]))\n        \n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"1\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"1\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"1\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"2\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"1\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"2\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"2\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"2\", \"1\"]))\n        \n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"123\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"223\"]), Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"]))\n        \n        // MARK: version core vs. version core + build metadata\n        \n        XCTAssertEqual(Version(1, 2, 3), Version(1, 2, 3, buildMetadataIdentifiers: [\"\"]))\n        XCTAssertEqual(Version(1, 2, 3), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        XCTAssertLessThan(Version(1, 2, 2), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        \n        // MARK: version core + pre-release vs. version core + build metadata\n        \n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"alpha\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"alpha-\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"123\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"123alpha\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"223\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"123alpha\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"123\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"223\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"223\"]))\n        XCTAssertLessThan(Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        XCTAssertGreaterThan(Version(2, 2, 3, prereleaseIdentifiers: [\"\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"\"]))\n        XCTAssertGreaterThan(Version(1, 3, 3, prereleaseIdentifiers: [\"alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        XCTAssertGreaterThan(Version(1, 2, 4, prereleaseIdentifiers: [\"223\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"123alpha\"]))\n        \n        XCTAssertFalse(Version(2, 2, 3, prereleaseIdentifiers: [\"\"]) < Version(1, 2, 3, buildMetadataIdentifiers: [\"\"]))\n        XCTAssertFalse(Version(1, 3, 3, prereleaseIdentifiers: [\"alpha\"]) < Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        XCTAssertFalse(Version(1, 2, 4, prereleaseIdentifiers: [\"223\"]) < Version(1, 2, 3, buildMetadataIdentifiers: [\"123alpha\"]))\n        \n        // MARK: version core + build metadata vs. version core + build metadata\n        \n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"\"]))\n        \n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"alpha1\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"alpha2\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"alpha-\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\", \"alpha\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\", \"beta\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"alpha\", \"beta\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\", \"alpha\"]))\n        \n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"1\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"1\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"1\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"2\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"1\", \"1\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"1\", \"2\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"1\", \"2\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"2\", \"1\"]))\n        \n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"123\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"123alpha\"]))\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"223\"]), Version(1, 2, 3, buildMetadataIdentifiers: [\"123alpha\"]))\n        \n        // MARK: version core vs. version core + pre-release + build metadata\n        \n        XCTAssertGreaterThan(Version(1, 2, 3), Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"\"]))\n        XCTAssertGreaterThan(Version(1, 2, 3), Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"123alpha\"]))\n        XCTAssertGreaterThan(Version(1, 2, 3), Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"], buildMetadataIdentifiers: [\"alpha\"]))\n        XCTAssertGreaterThan(Version(1, 2, 3), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"123\"]))\n        XCTAssertLessThan(Version(1, 2, 2), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"alpha\", \"beta\"]))\n        XCTAssertLessThan(Version(1, 2, 2), Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"alpha-\"]))\n        \n        XCTAssertFalse(Version(1, 2, 3) < Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"\"]))\n        XCTAssertFalse(Version(1, 2, 3) < Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"123alpha\"]))\n        XCTAssertFalse(Version(1, 2, 3) < Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"], buildMetadataIdentifiers: [\"alpha\"]))\n        XCTAssertFalse(Version(1, 2, 3) < Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"123\"]))\n        \n        // MARK: version core + pre-release vs. version core + pre-release + build metadata\n        \n        XCTAssertEqual(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"\"])\n        )\n        \n        XCTAssertEqual(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"123alpha\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha1\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha2\"], buildMetadataIdentifiers: [\"alpha\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha-\"], buildMetadataIdentifiers: [\"alpha\", \"beta\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"alpha\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"beta\"], buildMetadataIdentifiers: [\"123\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\", \"beta\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"alpha\"], buildMetadataIdentifiers: [\"alpha-\"])\n        )\n        \n        XCTAssertEqual(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\"], buildMetadataIdentifiers: [\"\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"2\"], buildMetadataIdentifiers: [\"123alpha\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"1\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"2\"], buildMetadataIdentifiers: [\"123\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"2\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"2\", \"1\"], buildMetadataIdentifiers: [\"alpha\", \"beta\"])\n        )\n        \n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"123\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"], buildMetadataIdentifiers: [\"-alpha\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"223\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"], buildMetadataIdentifiers: [\"123\"])\n        )\n        \n        // MARK: version core + pre-release + build metadata vs. version core + pre-release + build metadata\n        \n        XCTAssertEqual(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"\"])\n        )\n        \n        XCTAssertEqual(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"123\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"], buildMetadataIdentifiers: [\"-alpha\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\"], buildMetadataIdentifiers: [\"123alpha\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha1\"], buildMetadataIdentifiers: [\"alpha\", \"beta\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha2\"], buildMetadataIdentifiers: [\"alpha\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\"], buildMetadataIdentifiers: [\"123\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha-\"], buildMetadataIdentifiers: [\"alpha\", \"beta\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"alpha\"], buildMetadataIdentifiers: [\"123alpha\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"beta\"], buildMetadataIdentifiers: [\"123\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"alpha\", \"beta\"], buildMetadataIdentifiers: [\"\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"alpha\"], buildMetadataIdentifiers: [\"alpha-\"])\n        )\n        \n        XCTAssertEqual(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\"], buildMetadataIdentifiers: [\"alpha-\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\"], buildMetadataIdentifiers: [\"\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\"], buildMetadataIdentifiers: [\"123\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"2\"], buildMetadataIdentifiers: [\"123alpha\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"1\"], buildMetadataIdentifiers: [\"alpha\", \"beta\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"2\"], buildMetadataIdentifiers: [\"123\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"1\", \"2\"], buildMetadataIdentifiers: [\"alpha\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"2\", \"1\"], buildMetadataIdentifiers: [\"alpha\", \"beta\"])\n        )\n        \n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"123\"], buildMetadataIdentifiers: [\"123alpha\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"], buildMetadataIdentifiers: [\"-alpha\"])\n        )\n        XCTAssertLessThan(\n            Version(1, 2, 3, prereleaseIdentifiers: [\"223\"], buildMetadataIdentifiers: [\"123alpha\"]),\n            Version(1, 2, 3, prereleaseIdentifiers: [\"123alpha\"], buildMetadataIdentifiers: [\"123\"])\n        )\n        \n    }\n    \n    func testCustomConversionFromVersionToString() {\n        \n        // MARK: Version.description\n        \n        XCTAssertEqual(Version(0, 0, 0).description, \"0.0.0\" as String)\n        XCTAssertEqual(Version(1, 2, 3).description, \"1.2.3\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"\"]).description, \"1.2.3-\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"\", \"\"]).description, \"1.2.3-.\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"beta1\"]).description, \"1.2.3-beta1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"1\"]).description, \"1.2.3-beta.1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"\", \"1\"]).description, \"1.2.3-beta..1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"be-ta\", \"\", \"1\"]).description, \"1.2.3-be-ta..1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"\"]).description, \"1.2.3+\" as String)\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"\", \"\"]).description, \"1.2.3+.\" as String)\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"beta1\"]).description, \"1.2.3+beta1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\", \"1\"]).description, \"1.2.3+beta.1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\", \"\", \"1\"]).description, \"1.2.3+beta..1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, buildMetadataIdentifiers: [\"be-ta\", \"\", \"1\"]).description, \"1.2.3+be-ta..1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"\"]).description, \"1.2.3-+\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"\", \"\"], buildMetadataIdentifiers: [\"\", \"-\", \"\"]).description, \"1.2.3-.+.-.\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"beta1\"], buildMetadataIdentifiers: [\"alpha1\"]).description, \"1.2.3-beta1+alpha1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"1\"], buildMetadataIdentifiers: [\"alpha\", \"1\"]).description, \"1.2.3-beta.1+alpha.1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"\", \"1\"], buildMetadataIdentifiers: [\"alpha\", \"\", \"1\"]).description, \"1.2.3-beta..1+alpha..1\" as String)\n        XCTAssertEqual(Version(1, 2, 3, prereleaseIdentifiers: [\"be-ta\", \"\", \"1\"], buildMetadataIdentifiers: [\"al-pha\", \"\", \"1\"]).description, \"1.2.3-be-ta..1+al-pha..1\" as String)\n        \n        // MARK: String interpolation\n        \n        XCTAssertEqual(\"\\(Version(0, 0, 0))\", \"0.0.0\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3))\", \"1.2.3\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"\"]))\", \"1.2.3-\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"\", \"\"]))\", \"1.2.3-.\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"beta1\"]))\", \"1.2.3-beta1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"1\"]))\", \"1.2.3-beta.1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"\", \"1\"]))\", \"1.2.3-beta..1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"be-ta\", \"\", \"1\"]))\", \"1.2.3-be-ta..1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, buildMetadataIdentifiers: [\"\"]))\", \"1.2.3+\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, buildMetadataIdentifiers: [\"\", \"\"]))\", \"1.2.3+.\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, buildMetadataIdentifiers: [\"beta1\"]))\", \"1.2.3+beta1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\", \"1\"]))\", \"1.2.3+beta.1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, buildMetadataIdentifiers: [\"beta\", \"\", \"1\"]))\", \"1.2.3+beta..1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, buildMetadataIdentifiers: [\"be-ta\", \"\", \"1\"]))\", \"1.2.3+be-ta..1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"\"], buildMetadataIdentifiers: [\"\"]))\", \"1.2.3-+\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"\", \"\"], buildMetadataIdentifiers: [\"\", \"-\", \"\"]))\", \"1.2.3-.+.-.\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"beta1\"], buildMetadataIdentifiers: [\"alpha1\"]))\", \"1.2.3-beta1+alpha1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"1\"], buildMetadataIdentifiers: [\"alpha\", \"1\"]))\", \"1.2.3-beta.1+alpha.1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"beta\", \"\", \"1\"], buildMetadataIdentifiers: [\"alpha\", \"\", \"1\"]))\", \"1.2.3-beta..1+alpha..1\" as String)\n        XCTAssertEqual(\"\\(Version(1, 2, 3, prereleaseIdentifiers: [\"be-ta\", \"\", \"1\"], buildMetadataIdentifiers: [\"al-pha\", \"\", \"1\"]))\", \"1.2.3-be-ta..1+al-pha..1\" as String)\n        \n    }\n    \n    func testLosslessConversionFromStringToVersion() {\n        \n        // We use type coercion `as String` in `Version(_:)` because there is a pair of overloaded initializers: `init(_ version: Version)` and `init?(_ versionString: String)`, and we want to test the latter in this function.\n        \n        // MARK: Well-formed version core\n        \n        XCTAssertNotNil(Version(\"0.0.0\" as String))\n        XCTAssertEqual(Version(\"0.0.0\" as String), Version(0, 0, 0))\n\n        XCTAssertNotNil(Version(\"1.1.2\" as String))\n        XCTAssertEqual(Version(\"1.1.2\" as String), Version(1, 1, 2))\n\n        // MARK: Malformed version core\n\n        XCTAssertNil(Version(\"3\" as String))\n        XCTAssertNil(Version(\"3 5\" as String))\n        XCTAssertNil(Version(\"5.8\" as String))\n        XCTAssertNil(Version(\"-5.8.13\" as String))\n        XCTAssertNil(Version(\"8.-13.21\" as String))\n        XCTAssertNil(Version(\"13.21.-34\" as String))\n        XCTAssertNil(Version(\"-0.0.0\" as String))\n        XCTAssertNil(Version(\"0.-0.0\" as String))\n        XCTAssertNil(Version(\"0.0.-0\" as String))\n        XCTAssertNil(Version(\"21.34.55.89\" as String))\n        XCTAssertNil(Version(\"6 x 9 = 42\" as String))\n        XCTAssertNil(Version(\"forty two\" as String))\n\n        // MARK: Well-formed version core, well-formed pre-release identifiers\n\n        XCTAssertNotNil(Version(\"0.0.0-pre-alpha\" as String))\n        XCTAssertEqual(Version(\"0.0.0-pre-alpha\" as String), Version(0, 0, 0, prereleaseIdentifiers: [\"pre-alpha\"]))\n\n        XCTAssertNotNil(Version(\"55.89.144-beta.1\" as String))\n        XCTAssertEqual(Version(\"55.89.144-beta.1\" as String), Version(55, 89, 144, prereleaseIdentifiers: [\"beta\", \"1\"]))\n        \n        XCTAssertNotNil(Version(\"89.144.233-a.whole..lot.of.pre-release.identifiers\" as String))\n        XCTAssertEqual(Version(\"89.144.233-a.whole..lot.of.pre-release.identifiers\" as String), Version(89, 144, 233, prereleaseIdentifiers: [\"a\", \"whole\", \"\", \"lot\", \"of\", \"pre-release\", \"identifiers\"]))\n\n        XCTAssertNotNil(Version(\"144.233.377-\" as String))\n        XCTAssertEqual(Version(\"144.233.377-\" as String), Version(144, 233, 377, prereleaseIdentifiers: [\"\"]))\n\n        // MARK: Well-formed version core, malformed pre-release identifiers\n        \n        XCTAssertNil(Version(\"233.377.610-hello world\" as String))\n\n        // MARK: Malformed version core, well-formed pre-release identifiers\n\n        XCTAssertNil(Version(\"987-Hello.world--------\" as String))\n        XCTAssertNil(Version(\"987.1597-half-life.3\" as String))\n        XCTAssertNil(Version(\"1597.2584.4181.6765-a.whole.lot.of.pre-release.identifiers\" as String))\n        XCTAssertNil(Version(\"6 x 9 = 42-\" as String))\n        XCTAssertNil(Version(\"forty-two\" as String))\n        \n        // MARK: Well-formed version core, well-formed build metadata identifiers\n        \n        XCTAssertNotNil(Version(\"0.0.0+some-metadata\" as String))\n        XCTAssertEqual(Version(\"0.0.0+some-metadata\" as String), Version(0, 0, 0, buildMetadataIdentifiers: [\"some-metadata\"]))\n        \n        XCTAssertNotNil(Version(\"4181.6765.10946+more.meta..more.data\" as String))\n        XCTAssertEqual(Version(\"4181.6765.10946+more.meta..more.data\" as String), Version(4181, 6765, 10946, buildMetadataIdentifiers: [\"more\", \"meta\", \"\", \"more\", \"data\"]))\n        \n        XCTAssertNotNil(Version(\"6765.10946.17711+-a-very--long---build-----metadata--------identifier-------------with---------------------many----------------------------------hyphens-------------------------------------------------------\" as String))\n        XCTAssertEqual(Version(\"6765.10946.17711+-a-very--long---build-----metadata--------identifier-------------with---------------------many----------------------------------hyphens-------------------------------------------------------\" as String), Version(6765, 10946, 17711, buildMetadataIdentifiers: [\"-a-very--long---build-----metadata--------identifier-------------with---------------------many----------------------------------hyphens-------------------------------------------------------\"]))\n        \n        XCTAssertNotNil(Version(\"10946.17711.28657+\" as String))\n        XCTAssertEqual(Version(\"10946.17711.28657+\" as String), Version(10946, 17711, 28657, buildMetadataIdentifiers: [\"\"]))\n        \n        // MARK: Well-formed version core, malformed build metadata identifiers\n        \n        XCTAssertNil(Version(\"17711.28657.46368+hello world\" as String))\n        XCTAssertNil(Version(\"28657.46368.75025+hello+world\" as String))\n        \n        // MARK: Malformed version core, well-formed build metadata identifiers\n        \n        XCTAssertNil(Version(\"121393+Hello.world--------\" as String))\n        XCTAssertNil(Version(\"121393.196418+half-life.3\" as String))\n        XCTAssertNil(Version(\"196418.317811.514229.832040+a.whole.lot.of.build.metadata.identifiers\" as String))\n        XCTAssertNil(Version(\"196418.317811.514229.832040+a.whole.lot.of.build.metadata.identifiers\" as String))\n        XCTAssertNil(Version(\"6 x 9 = 42+\" as String))\n        XCTAssertNil(Version(\"forty two+a-very-long-build-metadata-identifier-with-many-hyphens\" as String))\n        \n        // MARK: Well-formed version core, well-formed pre-release identifiers, well-formed build metadata identifiers\n        \n        XCTAssertNotNil(Version(\"0.0.0-beta.-42+42-42.42\" as String))\n        XCTAssertEqual(Version(\"0.0.0-beta.-42+42-42.42\" as String), Version(0, 0, 0, prereleaseIdentifiers: [\"beta\", \"-42\"], buildMetadataIdentifiers: [\"42-42\", \"42\"]))\n        \n        // MARK: Well-formed version core, well-formed pre-release identifiers, malformed build metadata identifiers\n        \n        XCTAssertNil(Version(\"514229.832040.1346269-beta1+  \" as String))\n        \n        // MARK: Well-formed version core, malformed pre-release identifiers, well-formed build metadata identifiers\n        \n        XCTAssertNil(Version(\"832040.1346269.2178309-beta 1+-\" as String))\n        \n        // MARK: Well-formed version core, malformed pre-release identifiers, malformed build metadata identifiers\n        \n        XCTAssertNil(Version(\"1346269.2178309.3524578-beta 1++\" as String))\n        \n        // MARK: malformed version core, well-formed pre-release identifiers, well-formed build metadata identifiers\n        \n        XCTAssertNil(Version(\" 832040.1346269.3524578-beta1+abc\" as String))\n        \n        // MARK: malformed version core, well-formed pre-release identifiers, malformed build metadata identifiers\n        \n        XCTAssertNil(Version(\"1346269.3524578.5702887-beta1+😀\" as String))\n        \n        // MARK: malformed version core, malformed pre-release identifiers, well-formed build metadata identifiers\n        \n        XCTAssertNil(Version(\"3524578.5702887.9227465-beta!@#$%^&*1+asdfghjkl123456789\" as String))\n        \n        // MARK: malformed version core, malformed pre-release identifiers, malformed build metadata identifiers\n        \n        XCTAssertNil(Version(\"5702887.9227465-bètá1+±\" as String))\n        \n    }\n    \n    func testExpressingVersionByStringLiteral() {\n        \n        // MARK: Well-formed version core\n        \n        XCTAssertEqual(\"0.0.0\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"1.1.2\" as Version, Version(1, 1, 2))\n        \n        // MARK: Malformed version core\n        \n        XCTAssertEqual(\"\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"3\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"3 5\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"5.8\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"-5.8.13\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"8.-13.21\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"13.21.-34\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"-0.0.0\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"0.-0.0\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"0.0.-0\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"21.34.55.89\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"6 x 9 = 42\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"forty two\" as Version, Version(0, 0, 0))\n        \n        // MARK: Well-formed version core, well-formed pre-release identifiers\n        \n        XCTAssertEqual(\"0.0.0-pre-alpha\" as Version, Version(0, 0, 0, prereleaseIdentifiers: [\"pre-alpha\"]))\n        XCTAssertEqual(\"55.89.144-beta.1\" as Version, Version(55, 89, 144, prereleaseIdentifiers: [\"beta\", \"1\"]))\n        XCTAssertEqual(\"89.144.233-a.whole..lot.of.pre-release.identifiers\" as Version, Version(89, 144, 233, prereleaseIdentifiers: [\"a\", \"whole\", \"\", \"lot\", \"of\", \"pre-release\", \"identifiers\"]))\n        XCTAssertEqual(\"144.233.377-\" as Version, Version(144, 233, 377, prereleaseIdentifiers: [\"\"]))\n        \n        // MARK: Well-formed version core, malformed pre-release identifiers\n        \n        XCTAssertEqual(\"233.377.610-hello world\" as Version, Version(0, 0, 0))\n        \n        // MARK: Malformed version core, well-formed pre-release identifiers\n        \n        XCTAssertEqual(\"-Hello.world--------\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"987-Hello.world--------\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"987.1597-half-life.3\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"1597.2584.4181.6765-a.whole.lot.of.pre-release.identifiers\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"6 x 9 = 42-\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"forty-two\" as Version, Version(0, 0, 0))\n        \n        // MARK: Well-formed version core, well-formed build metadata identifiers\n        \n        XCTAssertEqual(\"0.0.0+some-metadata\" as Version, Version(0, 0, 0, buildMetadataIdentifiers: [\"some-metadata\"]))\n        XCTAssertEqual(\"4181.6765.10946+more.meta..more.data\" as Version, Version(4181, 6765, 10946, buildMetadataIdentifiers: [\"more\", \"meta\", \"\", \"more\", \"data\"]))\n        XCTAssertEqual(\"6765.10946.17711+-a-very--long---build-----metadata--------identifier-------------with---------------------many----------------------------------hyphens-------------------------------------------------------\" as Version, Version(6765, 10946, 17711, buildMetadataIdentifiers: [\"-a-very--long---build-----metadata--------identifier-------------with---------------------many----------------------------------hyphens-------------------------------------------------------\"]))\n        XCTAssertEqual(\"10946.17711.28657+\" as Version, Version(10946, 17711, 28657, buildMetadataIdentifiers: [\"\"]))\n        \n        // MARK: Well-formed version core, malformed build metadata identifiers\n        \n        XCTAssertEqual(\"17711.28657.46368+hello world\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"28657.46368.75025+hello+world\" as Version, Version(0, 0, 0))\n        \n        // MARK: Malformed version core, well-formed build metadata identifiers\n        \n        XCTAssertEqual(\"+Hello.world--------\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"121393+Hello.world--------\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"121393.196418+half-life.3\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"196418.317811.514229.832040+a.whole.lot.of.build.metadata.identifiers\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"196418.317811.514229.832040+a.whole.lot.of.build.metadata.identifiers\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"6 x 9 = 42+\" as Version, Version(0, 0, 0))\n        XCTAssertEqual(\"forty two+a-very-long-build-metadata-identifier-with-many-hyphens\" as Version, Version(0, 0, 0))\n        \n        // MARK: Well-formed version core, well-formed pre-release identifiers, well-formed build metadata identifiers\n        \n        XCTAssertEqual(\"0.0.0-beta.-42+42-42.42\" as Version, Version(0, 0, 0, prereleaseIdentifiers: [\"beta\", \"-42\"], buildMetadataIdentifiers: [\"42-42\", \"42\"]))\n        \n        // MARK: Well-formed version core, well-formed pre-release identifiers, malformed build metadata identifiers\n        \n        XCTAssertEqual(\"514229.832040.1346269-beta1+  \" as Version, Version(0, 0, 0))\n        \n        // MARK: Well-formed version core, malformed pre-release identifiers, well-formed build metadata identifiers\n        \n        XCTAssertEqual(\"832040.1346269.2178309-beta 1+-\" as Version, Version(0, 0, 0))\n        \n        // MARK: Well-formed version core, malformed pre-release identifiers, malformed build metadata identifiers\n        \n        XCTAssertEqual(\"1346269.2178309.3524578-beta 1++\" as Version, Version(0, 0, 0))\n        \n        // MARK: malformed version core, well-formed pre-release identifiers, well-formed build metadata identifiers\n        \n        XCTAssertEqual(\" 832040.1346269.3524578-beta1+abc\" as Version, Version(0, 0, 0))\n        \n        // MARK: malformed version core, well-formed pre-release identifiers, malformed build metadata identifiers\n        \n        XCTAssertEqual(\"1346269.3524578.5702887-beta1+😀\" as Version, Version(0, 0, 0))\n        \n        // MARK: malformed version core, malformed pre-release identifiers, well-formed build metadata identifiers\n        \n        XCTAssertEqual(\"3524578.5702887.9227465-beta!@#$%^&*1+asdfghjkl123456789\" as Version, Version(0, 0, 0))\n        \n        // MARK: malformed version core, malformed pre-release identifiers, malformed build metadata identifiers\n        \n        XCTAssertEqual(\"5702887.9227465-bètá1+±\" as Version, Version(0, 0, 0))\n        \n    }\n    \n    // A semantic version string is always longer than 1 character, so the only way to test these 2 initializers is by calling them directly.\n    \n    func testExpressingVersionByExtendedGraphemeClusterLiteral() {\n        XCTAssertEqual(Version(extendedGraphemeClusterLiteral: \"版⃣\"), Version(0, 0, 0))\n    }\n    \n    func testExpressingVersionByUnicodeScalarLiteral() {\n        XCTAssertEqual(Version(unicodeScalarLiteral: \"a\"), Version(0, 0, 0))\n    }\n    \n}\n\n"
  },
  {
    "path": "Tests/PackageFingerprintTests/FilePackageFingerprintStorageTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport struct Foundation.URL\n@testable import PackageFingerprint\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCUtility.Version\n\nfinal class FilePackageFingerprintStorageTests: XCTestCase {\n    func testHappyCase() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/fingerprints\")\n        let storage = FilePackageFingerprintStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n        let registryURL = URL(\"https://example.packages.com\")\n        let sourceControlURL = SourceControlURL(\"https://example.com/mona/LinkedList.git\")\n\n        // Add fingerprints for mona.LinkedList\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(origin: .registry(registryURL), value: \"checksum-1.0.0\", contentType: .sourceCode)\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .sourceControl(sourceControlURL),\n                value: \"gitHash-1.0.0\",\n                contentType: .sourceCode\n            )\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.1.0\"),\n            fingerprint: .init(origin: .registry(registryURL), value: \"checksum-1.1.0\", contentType: .sourceCode)\n        )\n\n        // Fingerprint for another package\n        let otherPackage = PackageIdentity.plain(\"other.LinkedList\")\n        try storage.put(\n            package: otherPackage,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(origin: .registry(registryURL), value: \"checksum-1.0.0\", contentType: .sourceCode)\n        )\n\n        // A checksum file should have been created for each package\n        XCTAssertTrue(mockFileSystem.exists(storage.directoryPath.appending(component: package.fingerprintsFilename)))\n        XCTAssertTrue(\n            mockFileSystem\n                .exists(storage.directoryPath.appending(component: otherPackage.fingerprintsFilename))\n        )\n\n        // Fingerprints should be saved\n        do {\n            let fingerprints = try storage.get(package: package, version: Version(\"1.0.0\"))\n            XCTAssertEqual(fingerprints.count, 2)\n\n            let registryFingerprints = fingerprints[.registry]\n            XCTAssertEqual(registryFingerprints?.count, 1)\n            XCTAssertEqual(registryFingerprints?[.sourceCode]?.origin.url, SourceControlURL(registryURL))\n            XCTAssertEqual(registryFingerprints?[.sourceCode]?.value, \"checksum-1.0.0\")\n\n            let scmFingerprints = fingerprints[.sourceControl]\n            XCTAssertEqual(scmFingerprints?.count, 1)\n            XCTAssertEqual(scmFingerprints?[.sourceCode]?.origin.url, sourceControlURL)\n            XCTAssertEqual(scmFingerprints?[.sourceCode]?.value, \"gitHash-1.0.0\")\n        }\n\n        do {\n            let fingerprints = try storage.get(package: package, version: Version(\"1.1.0\"))\n            XCTAssertEqual(fingerprints.count, 1)\n\n            let registryFingerprints = fingerprints[.registry]\n            XCTAssertEqual(registryFingerprints?.count, 1)\n            XCTAssertEqual(registryFingerprints?[.sourceCode]?.origin.url, SourceControlURL(registryURL))\n            XCTAssertEqual(registryFingerprints?[.sourceCode]?.value, \"checksum-1.1.0\")\n        }\n\n        do {\n            let fingerprints = try storage.get(package: otherPackage, version: Version(\"1.0.0\"))\n            XCTAssertEqual(fingerprints.count, 1)\n\n            let registryFingerprints = fingerprints[.registry]\n            XCTAssertEqual(registryFingerprints?.count, 1)\n            XCTAssertEqual(registryFingerprints?[.sourceCode]?.origin.url, SourceControlURL(registryURL))\n            XCTAssertEqual(registryFingerprints?[.sourceCode]?.value, \"checksum-1.0.0\")\n        }\n    }\n\n    func testNotFound() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/fingerprints\")\n        let storage = FilePackageFingerprintStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n        let registryURL = URL(\"https://example.packages.com\")\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(origin: .registry(registryURL), value: \"checksum-1.0.0\", contentType: .sourceCode)\n        )\n\n        // No fingerprints found for the content type\n        await XCTAssertAsyncThrowsError(try storage.get(\n            package: package,\n            version: Version(\"1.0.0\"),\n            kind: .registry,\n            contentType: .manifest(.none)\n        )) { error in\n            guard case PackageFingerprintStorageError.notFound = error else {\n                return XCTFail(\"Expected PackageFingerprintStorageError.notFound, got \\(error)\")\n            }\n        }\n\n        // No fingerprints found for the version\n        await XCTAssertAsyncThrowsError(try storage.get(package: package, version: Version(\"1.1.0\"))) { error in\n            guard case PackageFingerprintStorageError.notFound = error else {\n                return XCTFail(\"Expected PackageFingerprintStorageError.notFound, got \\(error)\")\n            }\n        }\n\n        // No fingerprints found for the package\n        let otherPackage = PackageIdentity.plain(\"other.LinkedList\")\n        await XCTAssertAsyncThrowsError(try storage.get(package: otherPackage, version: Version(\"1.0.0\"))) { error in\n            guard case PackageFingerprintStorageError.notFound = error else {\n                return XCTFail(\"Expected PackageFingerprintStorageError.notFound, got \\(error)\")\n            }\n        }\n    }\n\n    func testSingleFingerprintPerKindAndContentType() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/fingerprints\")\n        let storage = FilePackageFingerprintStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n        let registryURL = URL(\"https://example.packages.com\")\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        // Write registry checksum for v1.0.0\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(origin: .registry(registryURL), value: \"checksum-1.0.0\", contentType: .sourceCode)\n        )\n\n        // Writing for the same version and kind and content type but different checksum should fail\n        await XCTAssertAsyncThrowsError(try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .registry(registryURL),\n                value: \"checksum-1.0.0-1\",\n                contentType: .sourceCode\n            )\n        )) { error in\n            guard case PackageFingerprintStorageError.conflict = error else {\n                return XCTFail(\"Expected PackageFingerprintStorageError.conflict, got \\(error)\")\n            }\n        }\n\n        // Writing for the same version and kind and content type same checksum should not fail\n        _ = try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .registry(registryURL),\n                value: \"checksum-1.0.0\",\n                contentType: .sourceCode\n            )\n        )\n    }\n\n    func testHappyCase_PackageReferenceAPI() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/fingerprints\")\n        let storage = FilePackageFingerprintStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n        let sourceControlURL = SourceControlURL(\"https://example.com/mona/LinkedList.git\")\n        let packageRef = PackageReference.remoteSourceControl(\n            identity: PackageIdentity(url: sourceControlURL),\n            url: sourceControlURL\n        )\n\n        try storage.put(\n            package: packageRef,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .sourceControl(sourceControlURL),\n                value: \"gitHash-1.0.0\",\n                contentType: .sourceCode\n            )\n        )\n        try storage.put(\n            package: packageRef,\n            version: Version(\"1.1.0\"),\n            fingerprint: .init(\n                origin: .sourceControl(sourceControlURL),\n                value: \"gitHash-1.1.0\",\n                contentType: .sourceCode\n            )\n        )\n\n        // Fingerprints should be saved\n        let fingerprints = try storage.get(package: packageRef, version: Version(\"1.1.0\"))\n        XCTAssertEqual(fingerprints.count, 1)\n\n        let scmFingerprints = fingerprints[.sourceControl]\n        XCTAssertEqual(scmFingerprints?.count, 1)\n\n        XCTAssertEqual(scmFingerprints?[.sourceCode]?.origin.url, sourceControlURL)\n        XCTAssertEqual(scmFingerprints?[.sourceCode]?.value, \"gitHash-1.1.0\")\n    }\n\n    func testDifferentRepoURLsThatHaveSameIdentity() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/fingerprints\")\n        let storage = FilePackageFingerprintStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n        let fooURL = SourceControlURL(\"https://example.com/foo/LinkedList.git\")\n        let barURL = SourceControlURL(\"https://example.com/bar/LinkedList.git\")\n\n        // foo and bar have the same identity `LinkedList`\n        let fooRef = PackageReference.remoteSourceControl(identity: PackageIdentity(url: fooURL), url: fooURL)\n        let barRef = PackageReference.remoteSourceControl(identity: PackageIdentity(url: barURL), url: barURL)\n\n        try storage.put(\n            package: fooRef,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(origin: .sourceControl(fooURL), value: \"abcde-foo\", contentType: .sourceCode)\n        )\n        // This should succeed because they get written to different files\n        try storage.put(\n            package: barRef,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(origin: .sourceControl(barURL), value: \"abcde-bar\", contentType: .sourceCode)\n        )\n\n        XCTAssertNotEqual(try fooRef.fingerprintsFilename, try barRef.fingerprintsFilename)\n\n        // A checksum file should have been created for each package\n        XCTAssertTrue(\n            mockFileSystem\n                .exists(storage.directoryPath.appending(component: try fooRef.fingerprintsFilename))\n        )\n        XCTAssertTrue(\n            mockFileSystem\n                .exists(storage.directoryPath.appending(component: try barRef.fingerprintsFilename))\n        )\n\n        // This should fail because fingerprint for 1.0.0 already exists and it's different\n        await XCTAssertAsyncThrowsError(try storage.put(\n            package: fooRef,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .sourceControl(fooURL),\n                value: \"abcde-foo-foo\",\n                contentType: .sourceCode\n            )\n        )) { error in\n            guard case PackageFingerprintStorageError.conflict = error else {\n                return XCTFail(\"Expected PackageFingerprintStorageError.conflict, got \\(error)\")\n            }\n        }\n\n        // This should succeed because fingerprint for 2.0.0 doesn't exist yet\n        try storage.put(\n            package: fooRef,\n            version: Version(\"2.0.0\"),\n            fingerprint: .init(origin: .sourceControl(fooURL), value: \"abcde-foo\", contentType: .sourceCode)\n        )\n    }\n\n    func testConvertingFromV1ToV2() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/fingerprints\")\n        try mockFileSystem.createDirectory(directoryPath, recursive: true)\n        let storage = FilePackageFingerprintStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let sourceControlURL = SourceControlURL(\"https://example.com/mona/LinkedList.git\")\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let fingerprintsPath = directoryPath.appending(package.fingerprintsFilename)\n        let v1Fingerprints = \"\"\"\n        {\n          \"versionFingerprints\" : {\n            \"1.0.3\" : {\n              \"sourceControl\" : {\n                \"fingerprint\" : \"e394bf350e38cb100b6bc4172834770ede1b7232\",\n                \"origin\" : \"\\(sourceControlURL)\"\n              }\n            },\n            \"1.2.2\" : {\n              \"sourceControl\" : {\n                \"fingerprint\" : \"fee6933f37fde9a5e12a1e4aeaa93fe60116ff2a\",\n                \"origin\" : \"\\(sourceControlURL)\"\n              }\n            }\n          }\n        }\n        \"\"\"\n        // Write v1 fingerprints file\n        try mockFileSystem.writeFileContents(fingerprintsPath, string: v1Fingerprints)\n\n        // v1 fingerprints file should be converted to v2 when read\n        let fingerprints = try storage.get(package: package, version: Version(\"1.0.3\"))\n        XCTAssertEqual(fingerprints.count, 1)\n\n        let scmFingerprints = fingerprints[.sourceControl]\n        XCTAssertEqual(scmFingerprints?.count, 1)\n        // All v1 fingerprints have content type source code\n        XCTAssertEqual(scmFingerprints?[.sourceCode]?.origin.url, sourceControlURL)\n        XCTAssertEqual(scmFingerprints?[.sourceCode]?.value, \"e394bf350e38cb100b6bc4172834770ede1b7232\")\n    }\n\n    func testFingerprintsOfDifferentContentTypes() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/fingerprints\")\n        let storage = FilePackageFingerprintStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n        let registryURL = URL(\"https://example.packages.com\")\n        let sourceControlURL = SourceControlURL(\"https://example.com/mona/LinkedList.git\")\n\n        // Add fingerprints for 1.0.0 source archive/code\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .registry(registryURL),\n                value: \"archive-checksum-1.0.0\",\n                contentType: .sourceCode\n            )\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .sourceControl(sourceControlURL),\n                value: \"gitHash-1.0.0\",\n                contentType: .sourceCode\n            )\n        )\n\n        // Add fingerprints for 1.0.0 manifests\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .registry(registryURL),\n                value: \"manifest-checksum-1.0.0\",\n                contentType: .manifest(.none)\n            )\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            fingerprint: .init(\n                origin: .registry(registryURL),\n                value: \"manifest-5.6-checksum-1.0.0\",\n                contentType: .manifest(ToolsVersion.v5_6)\n            )\n        )\n\n        // Add fingerprint for 1.1.0 source archive\n        try storage.put(\n            package: package,\n            version: Version(\"1.1.0\"),\n            fingerprint: .init(\n                origin: .registry(registryURL),\n                value: \"archive-checksum-1.1.0\",\n                contentType: .sourceCode\n            )\n        )\n\n        let fingerprints = try storage.get(package: package, version: Version(\"1.0.0\"))\n        XCTAssertEqual(fingerprints.count, 2)\n\n        let registryFingerprints = fingerprints[.registry]\n        XCTAssertEqual(registryFingerprints?.count, 3)\n        XCTAssertEqual(registryFingerprints?[.sourceCode]?.origin.url, SourceControlURL(registryURL))\n        XCTAssertEqual(registryFingerprints?[.sourceCode]?.value, \"archive-checksum-1.0.0\")\n        XCTAssertEqual(registryFingerprints?[.manifest(.none)]?.origin.url, SourceControlURL(registryURL))\n        XCTAssertEqual(registryFingerprints?[.manifest(.none)]?.value, \"manifest-checksum-1.0.0\")\n        XCTAssertEqual(registryFingerprints?[.manifest(ToolsVersion.v5_6)]?.origin.url, SourceControlURL(registryURL))\n        XCTAssertEqual(registryFingerprints?[.manifest(ToolsVersion.v5_6)]?.value, \"manifest-5.6-checksum-1.0.0\")\n\n        let scmFingerprints = fingerprints[.sourceControl]\n        XCTAssertEqual(scmFingerprints?.count, 1)\n        XCTAssertEqual(scmFingerprints?[.sourceCode]?.origin.url, sourceControlURL)\n        XCTAssertEqual(scmFingerprints?[.sourceCode]?.value, \"gitHash-1.0.0\")\n    }\n}\n\nextension PackageFingerprintStorage {\n    fileprivate func get(\n        package: PackageIdentity,\n        version: Version\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] {\n        try self.get(\n            package: package,\n            version: version,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func get(\n        package: PackageIdentity,\n        version: Version,\n        kind: Fingerprint.Kind,\n        contentType: Fingerprint.ContentType\n    ) throws -> Fingerprint {\n        try self.get(\n            package: package,\n            version: version,\n            kind: kind,\n            contentType: contentType,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func put(\n        package: PackageIdentity,\n        version: Version,\n        fingerprint: Fingerprint\n    ) throws {\n        try self.put(\n            package: package,\n            version: version,\n            fingerprint: fingerprint,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func get(\n        package: PackageReference,\n        version: Version\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] {\n        try self.get(\n            package: package,\n            version: version,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func get(\n        package: PackageReference,\n        version: Version,\n        kind: Fingerprint.Kind,\n        contentType: Fingerprint.ContentType\n    ) throws -> Fingerprint {\n        try self.get(\n            package: package,\n            version: version,\n            kind: kind,\n            contentType: contentType,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func put(\n        package: PackageReference,\n        version: Version,\n        fingerprint: Fingerprint\n    ) throws {\n        try self.put(\n            package: package,\n            version: version,\n            fingerprint: fingerprint,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphPerformanceTests/DependencyResolverPerfTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\nimport XCTest\nimport Testing\n\nimport enum TSCBasic.JSON\nimport protocol TSCBasic.JSONMappable\nimport protocol TSCBasic.JSONSerializable\n\nimport func TSCUtility.measure\nimport struct TSCUtility.Version\n\nimport class TSCTestSupport.XCTestCasePerf\n\nprivate let v1: Version = \"1.0.0\"\nprivate let v1Range: VersionSetSpecifier = .range(\"1.0.0\" ..< \"2.0.0\")\n\nclass DependencyResolverRealWorldPerfTests: XCTestCasePerf {\n    func testKituraPubGrub_X100() async throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        try await runPackageTestPubGrub(name: \"kitura.json\", N: 100)\n    }\n\n    func testZewoPubGrub_X100() async throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        try await runPackageTestPubGrub(name: \"ZewoHTTPServer.json\", N: 100)\n    }\n\n    func testPerfectPubGrub_X100() async throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        try await runPackageTestPubGrub(name: \"PerfectHTTPServer.json\", N: 100)\n    }\n\n    func testSourceKittenPubGrub_X100() async throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        try await runPackageTestPubGrub(name: \"SourceKitten.json\", N: 100)\n    }\n\n    func runPackageTestPubGrub(name: String, N: Int = 1) async throws {\n        let graph = try mockGraph(for: name)\n        let provider = MockPackageContainerProvider(containers: graph.containers)\n\n        self.startMeasuring()\n\n        for _ in 0 ..< N {\n            let resolver = PubGrubDependencyResolver(provider: provider, observabilityScope: ObservabilitySystem.NOOP)\n            switch await resolver.solve(constraints: graph.constraints) {\n            case .success(let result):\n                let result: [(container: PackageReference, version: Version)] = result.compactMap {\n                    guard case .version(let version) = $0.boundVersion else {\n                        XCTFail(\"Unexpected result\")\n                        return nil\n                    }\n                    return ($0.package, version)\n                }\n                graph.checkResult(result)\n            case .failure:\n                XCTFail(\"Unexpected result\")\n                return\n            }\n        }\n\n        self.stopMeasuring()\n    }\n\n    func mockGraph(for name: String) throws -> MockDependencyGraph {\n        let input = AbsolutePath(#file).parentDirectory.appending(\"Inputs\").appending(component: name)\n        let jsonString: Data = try localFileSystem.readFileContents(input)\n        let json = try JSON(data: jsonString)\n        return MockDependencyGraph(json)\n    }\n}\n\n\n// MARK: - JSON\n\npublic extension MockDependencyGraph {\n    init(_ json: JSON) {\n        guard case .dictionary(let dict) = json else { fatalError() }\n        guard case .string(let name)? = dict[\"name\"] else { fatalError() }\n        guard case .array(let constraints)? = dict[\"constraints\"] else { fatalError() }\n        guard case .array(let containers)? = dict[\"containers\"] else { fatalError() }\n        guard case .dictionary(let result)? = dict[\"result\"] else { fatalError() }\n\n        self.init(\n            name: name,\n            constraints: constraints.map(PackageContainerConstraint.init(json:)),\n            containers: containers.map(MockPackageContainer.init(json:)),\n            result: Dictionary(uniqueKeysWithValues: try! result.map { value in\n                let (container, version) = value\n                guard case .string(let str) = version else { fatalError() }\n                let package = PackageReference.localSourceControl(identity: .plain(container.lowercased()), path: try .init(validating: \"/\\(container)\"))\n                return (package, Version(str)!)\n            })\n        )\n    }\n}\n\nprivate extension MockPackageContainer {\n    convenience init(json: JSON) {\n        guard case .dictionary(let dict) = json else { fatalError() }\n        guard case .string(let identifier)? = dict[\"identifier\"] else { fatalError() }\n        guard case .dictionary(let versions)? = dict[\"versions\"] else { fatalError() }\n\n        var depByVersion: [Version: [(container: String, versionRequirement: VersionSetSpecifier)]] = [:]\n        for (version, deps) in versions {\n            guard case .array(let depArray) = deps else { fatalError() }\n            depByVersion[Version(version)!] = depArray\n                .map(PackageContainerConstraint.init(json:))\n                .map { constraint in\n                    switch constraint.requirement {\n                    case .versionSet(let versionSet):\n                        return (constraint.package.identity.description, versionSet)\n                    case .unversioned:\n                        fatalError()\n                    case .revision:\n                        fatalError()\n                    }\n                }\n        }\n\n        try! self.init(name: identifier, dependenciesByVersion: depByVersion)\n    }\n}\n\nprivate extension MockPackageContainer.Constraint {\n    init(json: JSON) {\n        guard case .dictionary(let dict) = json else { fatalError() }\n        guard case .string(let identifier)? = dict[\"identifier\"] else { fatalError() }\n        guard let requirement = dict[\"requirement\"] else { fatalError() }\n        let products: ProductFilter = try! JSON(dict).get(\"products\")\n        let ref = PackageReference.localSourceControl(identity: .plain(identifier), path: .root)\n        self.init(package: ref, versionRequirement: VersionSetSpecifier(requirement), products: products)\n    }\n}\n\nprivate extension VersionSetSpecifier {\n    init(_ json: JSON) {\n        switch json {\n        case .string(let str):\n            switch str {\n            case \"any\": self = .any\n            case \"empty\": self = .empty\n            default: fatalError()\n            }\n        case .array(let arr):\n            switch arr.count {\n            case 1:\n                guard case .string(let str) = arr[0] else { fatalError() }\n                self = .exact(Version(str)!)\n            case 2:\n                let versions = arr.map { json -> Version in\n                    guard case .string(let str) = json else { fatalError() }\n                    return Version(str)!\n                }\n                self = .range(versions[0] ..< versions[1])\n            default: fatalError()\n            }\n        default: fatalError()\n        }\n    }\n}\n\nextension ProductFilter {\n    public func toJSON() -> JSON {\n        switch self {\n        case .everything:\n            return \"all\".toJSON()\n        case .specific(let products):\n            return products.sorted().toJSON()\n        }\n    }\n\n    public init(json: JSON) throws {\n        if let products = try? [String](json: json) {\n            self = .specific(Set(products))\n        } else {\n            self = .everything\n        }\n    }\n}\n\nextension ProductFilter: JSONSerializable, JSONMappable {}\n"
  },
  {
    "path": "Tests/PackageGraphPerformanceTests/Inputs/PerfectHTTPServer.json",
    "content": "{\n    \"constraints\": [\n        {\n            \"identifier\": \"https://github.com/PerfectlySoft/Perfect-HTTP.git\",\n            \"requirement\": [\n                \"2.0.0\",\n                \"2.1.0\"\n            ]\n        }\n    ],\n    \"containers\": [\n        {\n            \"identifier\": \"https://github.com/PerfectlySoft/Perfect-HTTP.git\",\n            \"versions\": {\n                \"0.20.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.21.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.22.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.23.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.24.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.25.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.26.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.27.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.28.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.29.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"2.0.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.1\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.2\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.3\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.4\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.5\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.6\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.7\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\",\n            \"versions\": {\n                \"0.1.0\": [],\n                \"0.2.0\": [],\n                \"0.4.0\": [],\n                \"0.5.0\": [],\n                \"0.6.0\": [],\n                \"0.7.0\": [],\n                \"2.0.0\": [],\n                \"2.0.1\": [],\n                \"2.0.2\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n            \"versions\": {\n                \"0.1.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.10.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.11.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.12.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.15.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.16.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.17.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.18.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.19.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.20.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.21.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.22.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.23.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.24.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.25.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.26.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.9.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"2.0.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.1\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.2\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.3\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.4\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ],\n                \"2.0.5\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.1.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Thread.git\",\n            \"versions\": {\n                \"0.1.0\": [],\n                \"0.10.0\": [],\n                \"0.11.0\": [],\n                \"0.12.0\": [],\n                \"0.13.0\": [],\n                \"0.14.0\": [],\n                \"0.2.0\": [],\n                \"0.3.0\": [],\n                \"0.4.0\": [],\n                \"0.5.0\": [],\n                \"0.6.0\": [],\n                \"0.7.0\": [],\n                \"0.8.0\": [],\n                \"0.9.0\": [],\n                \"2.0.0\": [],\n                \"2.0.1\": [],\n                \"2.0.2\": [],\n                \"2.0.3\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/PerfectlySoft/PerfectLib.git\",\n            \"versions\": {\n                \"0.1.0\": [],\n                \"0.10.0\": [],\n                \"0.11.0\": [],\n                \"0.12.0\": [],\n                \"0.13.0\": [],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.15.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.16.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.17.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.18.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.19.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [],\n                \"0.20.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.21.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.22.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.23.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.24.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-libcurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.25.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.26.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.27.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.28.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.29.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [],\n                \"0.30.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.31.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.32.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.33.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.34.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.35.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.36.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.37.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.38.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.39.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [],\n                \"0.40.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.41.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.42.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.43.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.44.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.45.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.46.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.47.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.48.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.49.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [],\n                \"0.50.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.51.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.52.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.53.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.54.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.55.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.56.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.57.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.58.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.59.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [],\n                \"0.60.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.61.0\": [\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-Net.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/PerfectlySoft/Perfect-OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"10.0.0\"\n                        ]\n                    }\n                ],\n                \"0.62.0\": [],\n                \"0.63.0\": [],\n                \"0.64.0\": [],\n                \"0.65.0\": [],\n                \"0.66.0\": [],\n                \"0.67.0\": [],\n                \"0.68.0\": [],\n                \"0.7.0\": [],\n                \"0.9.0\": [],\n                \"2.0.0\": [],\n                \"2.0.1\": [],\n                \"2.0.2\": [],\n                \"2.0.3\": [],\n                \"2.0.4\": []\n            }\n        }\n    ],\n    \"name\": \"PerfectHTTPServer\",\n    \"result\": {\n        \"https://github.com/PerfectlySoft/Perfect-COpenSSL.git\": \"2.0.2\",\n        \"https://github.com/PerfectlySoft/Perfect-HTTP.git\": \"2.0.7\",\n        \"https://github.com/PerfectlySoft/Perfect-Net.git\": \"2.0.5\",\n        \"https://github.com/PerfectlySoft/Perfect-Thread.git\": \"2.0.3\",\n        \"https://github.com/PerfectlySoft/PerfectLib.git\": \"2.0.4\"\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphPerformanceTests/Inputs/SourceKitten.json",
    "content": "{\n    \"constraints\": [\n        {\n            \"identifier\": \"https://github.com/Carthage/Commandant.git\",\n            \"requirement\": [\n                \"0.11.3\",\n                \"0.12.0\"\n            ]\n        },\n        {\n            \"identifier\": \"https://github.com/drmohundro/SWXMLHash.git\",\n            \"requirement\": [\n                \"3.0.3\",\n                \"3.0.4\"\n            ]\n        },\n        {\n            \"identifier\": \"https://github.com/jpsim/Yams.git\",\n            \"requirement\": [\n                \"0.1.2\",\n                \"0.1.3\"\n            ]\n        },\n        {\n            \"identifier\": \"https://github.com/norio-nomura/Clang_C.git\",\n            \"requirement\": [\n                \"1.0.0\",\n                \"2.0.0\"\n            ]\n        },\n        {\n            \"identifier\": \"https://github.com/norio-nomura/SourceKit.git\",\n            \"requirement\": [\n                \"1.0.0\",\n                \"2.0.0\"\n            ]\n        }\n    ],\n    \"containers\": [\n        {\n            \"identifier\": \"https://github.com/jpsim/Yams.git\",\n            \"versions\": {\n                \"0.1.0\": [],\n                \"0.1.1\": [],\n                \"0.1.2\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/norio-nomura/SourceKit.git\",\n            \"versions\": {\n                \"1.0.0\": [],\n                \"1.0.1\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/antitypical/Result.git\",\n            \"versions\": {\n                \"1.0.2\": [],\n                \"2.0.0\": [],\n                \"2.1.0\": [],\n                \"2.1.1\": [],\n                \"2.1.2\": [],\n                \"2.1.3\": [],\n                \"3.0.0\": [],\n                \"3.0.0-alpha.1\": [],\n                \"3.0.0-alpha.2\": [],\n                \"3.0.0-alpha.3\": [],\n                \"3.0.0-alpha.4\": [],\n                \"3.1.0\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/drmohundro/SWXMLHash.git\",\n            \"versions\": {\n                \"1.1.2\": [],\n                \"2.1.0\": [],\n                \"2.2.0\": [],\n                \"2.3.0\": [],\n                \"2.3.1\": [],\n                \"2.3.2\": [],\n                \"2.4.0\": [],\n                \"2.4.1\": [],\n                \"2.4.2\": [],\n                \"2.4.3\": [],\n                \"2.4.4\": [],\n                \"2.4.5\": [],\n                \"2.5.0\": [],\n                \"2.5.1\": [],\n                \"3.0.0\": [],\n                \"3.0.1\": [],\n                \"3.0.2\": [],\n                \"3.0.3\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/norio-nomura/Clang_C.git\",\n            \"versions\": {\n                \"1.0.0\": [],\n                \"1.0.1\": [],\n                \"1.0.2\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Carthage/Commandant.git\",\n            \"versions\": {\n                \"0.10.0\": [\n                    {\n                        \"identifier\": \"https://github.com/antitypical/Result.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"3.0.0\"\n                        ]\n                    }\n                ],\n                \"0.10.1\": [\n                    {\n                        \"identifier\": \"https://github.com/antitypical/Result.git\",\n                        \"requirement\": [\n                            \"2.0.0\",\n                            \"2.0.1\"\n                        ]\n                    }\n                ],\n                \"0.11.0-alpha.1\": [\n                    {\n                        \"identifier\": \"https://github.com/antitypical/Result.git\",\n                        \"requirement\": [\n                            \"3.0.0-alpha.4\",\n                            \"3.0.1\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/norio-nomura/Nimble\",\n                        \"requirement\": [\n                            \"5.0.0-alpha.30p6\",\n                            \"5.0.1\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/norio-nomura/Quick\",\n                        \"requirement\": [\n                            \"0.10.0-alpha.2\",\n                            \"0.10.1\"\n                        ]\n                    }\n                ],\n                \"0.11.1\": [\n                    {\n                        \"identifier\": \"https://github.com/antitypical/Result.git\",\n                        \"requirement\": [\n                            \"3.0.0\",\n                            \"3.1.0\"\n                        ]\n                    }\n                ],\n                \"0.11.2\": [\n                    {\n                        \"identifier\": \"https://github.com/antitypical/Result.git\",\n                        \"requirement\": [\n                            \"3.0.0\",\n                            \"3.1.0\"\n                        ]\n                    }\n                ],\n                \"0.11.3\": [\n                    {\n                        \"identifier\": \"https://github.com/antitypical/Result.git\",\n                        \"requirement\": [\n                            \"3.0.0\",\n                            \"4.0.0\"\n                        ]\n                    }\n                ],\n                \"0.8.3\": [\n                    {\n                        \"identifier\": \"https://github.com/antitypical/Result.git\",\n                        \"requirement\": [\n                            \"1.0.0\",\n                            \"2.0.0\"\n                        ]\n                    }\n                ],\n                \"0.9.0\": [\n                    {\n                        \"identifier\": \"https://github.com/antitypical/Result.git\",\n                        \"requirement\": [\n                            \"1.0.0\",\n                            \"2.0.0\"\n                        ]\n                    }\n                ]\n            }\n        }\n    ],\n    \"name\": \"SourceKitten\",\n    \"result\": {\n        \"https://github.com/Carthage/Commandant.git\": \"0.11.3\",\n        \"https://github.com/antitypical/Result.git\": \"3.1.0\",\n        \"https://github.com/drmohundro/SWXMLHash.git\": \"3.0.3\",\n        \"https://github.com/jpsim/Yams.git\": \"0.1.2\",\n        \"https://github.com/norio-nomura/Clang_C.git\": \"1.0.2\",\n        \"https://github.com/norio-nomura/SourceKit.git\": \"1.0.1\"\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphPerformanceTests/Inputs/ZewoHTTPServer.json",
    "content": "{\n    \"constraints\": [\n        {\n            \"identifier\": \"https://github.com/Zewo/Venice.git\",\n            \"requirement\": [\n                \"0.14.0\",\n                \"0.15.0\"\n            ]\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/HTTPFile.git\",\n            \"requirement\": [\n                \"0.14.0\",\n                \"0.15.0\"\n            ]\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/TCP.git\",\n            \"requirement\": [\n                \"0.14.0\",\n                \"0.15.0\"\n            ]\n        }\n    ],\n    \"containers\": [\n        {\n            \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n            \"versions\": {\n                \"0.1.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.1.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.1.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Axis.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.14.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Axis.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.14.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Axis.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.14.3\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Axis.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.3\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/swiftx/s4.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.4.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/swiftx/s4.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.4.3\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/SwiftX/S4.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.4.4\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/SwiftX/S4.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.4.5\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/SwiftX/S4.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.4.6\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Open-Swift/S4.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/S4.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.5.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/S4.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/S4.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/S4.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.7.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/S4.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.7.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/S4.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/MediaType.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/S4.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/HTTPFile.git\",\n            \"versions\": {\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.3\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.6.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/HTTP.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/CYAJL.git\",\n            \"versions\": {\n                \"0.0.1\": [],\n                \"0.1.0\": [],\n                \"0.13.0\": [],\n                \"0.14.0\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/Venice.git\",\n            \"versions\": {\n                \"0.0.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.1.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.1.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.10.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.12.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Axis.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.7.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.7.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.9.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/open-swift/C7.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/CPOSIX.git\",\n            \"versions\": {\n                \"0.1.0\": [],\n                \"0.13.0\": [],\n                \"0.14.0\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/Reflection.git\",\n            \"versions\": {\n                \"0.13.0\": [],\n                \"0.14.0\": [],\n                \"0.14.1\": [],\n                \"0.14.2\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n            \"versions\": {\n                \"0.1.0\": [],\n                \"0.13.0\": [],\n                \"0.13.1\": [],\n                \"0.14.0\": [],\n                \"0.15.0\": [],\n                \"0.2.0\": [],\n                \"0.3.0\": [],\n                \"0.4.0\": [],\n                \"0.4.1\": [],\n                \"0.4.2\": [],\n                \"0.5.0\": [],\n                \"0.6.0\": [],\n                \"0.6.1\": [],\n                \"0.6.2\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/OpenSSL.git\",\n            \"versions\": {\n                \"0.0.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.1.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/SSL.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.1.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/SSL.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.1.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/SSL.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.1.3\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.1.4\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Axis.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.3\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.4\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/File.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.4.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.5.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.6.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.4\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.5\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.8.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.8.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.8.3\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.8.4\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.8.5\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/File.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/IP.git\",\n            \"versions\": {\n                \"0.0.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.12.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Axis.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/System.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/System.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/System.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/System.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/System.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/OS.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.3\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/OS.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.9.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/TCP.git\",\n            \"versions\": {\n                \"0.0.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.10.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/IP.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/IP.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/OpenSSL.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/IP.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/IP.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/IP.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/IP.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/IP.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Data.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Data.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/URI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.5.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.5.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.7.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.7.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.7.3\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.7.4\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.8.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.9.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/IP.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/Axis.git\",\n            \"versions\": {\n                \"0.1.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.1.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CURIParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Reflection.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Reflection.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Reflection.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CYAJL.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n            \"versions\": {\n                \"0.10.0\": [],\n                \"0.11.0\": [],\n                \"0.12.0\": [],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CPOSIX.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CPOSIX.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CPOSIX.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.14.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CPOSIX.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [],\n                \"0.4.2\": [],\n                \"0.5.0\": [],\n                \"0.5.1\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/File.git\",\n            \"versions\": {\n                \"0.10.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.13.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Core.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Axis.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.3\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.4\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.2.5\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/CLibvenice.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Stream.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.2\": [\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Data.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.3\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/Data.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/tomohisa/Venice.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.7.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.7.2\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.7.3\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.7.4\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.7.5\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.8.1\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.9.0\": [\n                    {\n                        \"identifier\": \"https://github.com/VeniceX/Venice.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/String.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/Zewo/POSIX.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/CHTTPParser.git\",\n            \"versions\": {\n                \"0.13.0\": [],\n                \"0.14.0\": [],\n                \"0.4.0\": [],\n                \"0.5.0\": [],\n                \"0.6.0\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/Zewo/COpenSSL.git\",\n            \"versions\": {\n                \"0.1.0\": [],\n                \"0.13.0\": [],\n                \"0.13.1\": [],\n                \"0.14.0\": [],\n                \"0.2.0\": [],\n                \"0.4.0\": [],\n                \"0.5.0\": [],\n                \"0.6.0\": [],\n                \"0.6.1\": [],\n                \"0.6.2\": [],\n                \"0.8.0\": []\n            }\n        }\n    ],\n    \"name\": \"HTTPServer\",\n    \"result\": {\n        \"https://github.com/Zewo/Axis.git\": \"0.14.0\",\n        \"https://github.com/Zewo/CHTTPParser.git\": \"0.14.0\",\n        \"https://github.com/Zewo/CLibvenice.git\": \"0.14.0\",\n        \"https://github.com/Zewo/COpenSSL.git\": \"0.14.0\",\n        \"https://github.com/Zewo/CPOSIX.git\": \"0.14.0\",\n        \"https://github.com/Zewo/CYAJL.git\": \"0.14.0\",\n        \"https://github.com/Zewo/File.git\": \"0.14.0\",\n        \"https://github.com/Zewo/HTTP.git\": \"0.14.3\",\n        \"https://github.com/Zewo/HTTPFile.git\": \"0.14.0\",\n        \"https://github.com/Zewo/IP.git\": \"0.14.0\",\n        \"https://github.com/Zewo/OpenSSL.git\": \"0.14.0\",\n        \"https://github.com/Zewo/POSIX.git\": \"0.14.1\",\n        \"https://github.com/Zewo/Reflection.git\": \"0.14.2\",\n        \"https://github.com/Zewo/TCP.git\": \"0.14.0\",\n        \"https://github.com/Zewo/Venice.git\": \"0.14.0\"\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphPerformanceTests/Inputs/kitura.json",
    "content": "{\n    \"constraints\": [\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/Kitura-net.git\",\n            \"requirement\": [\n                \"1.2.0\",\n                \"1.3.0\"\n            ]\n        },\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/SwiftyJSON.git\",\n            \"requirement\": [\n                \"15.0.0\",\n                \"16.0.0\"\n            ]\n        },\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/Kitura-TemplateEngine.git\",\n            \"requirement\": [\n                \"1.1.0\",\n                \"1.2.0\"\n            ]\n        }\n    ],\n    \"containers\": [\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n            \"versions\": {\n                \"0.0.1\": [],\n                \"0.0.2\": [],\n                \"0.0.3\": [],\n                \"0.0.4\": [],\n                \"0.0.5\": [],\n                \"0.1.0\": [],\n                \"0.1.1\": [],\n                \"0.1.2\": [],\n                \"0.1.3\": [],\n                \"0.1.4\": [],\n                \"0.10.0\": [],\n                \"0.10.1\": [],\n                \"0.10.10\": [],\n                \"0.10.11\": [],\n                \"0.10.12\": [],\n                \"0.10.13\": [],\n                \"0.10.14\": [],\n                \"0.10.15\": [],\n                \"0.10.2\": [],\n                \"0.10.3\": [],\n                \"0.10.4\": [],\n                \"0.10.5\": [],\n                \"0.10.6\": [],\n                \"0.10.7\": [],\n                \"0.10.8\": [],\n                \"0.10.9\": [],\n                \"0.11.0\": [],\n                \"0.11.1\": [],\n                \"0.11.10\": [],\n                \"0.11.11\": [],\n                \"0.11.12\": [],\n                \"0.11.13\": [],\n                \"0.11.14\": [],\n                \"0.11.15\": [],\n                \"0.11.16\": [],\n                \"0.11.17\": [],\n                \"0.11.18\": [],\n                \"0.11.19\": [],\n                \"0.11.2\": [],\n                \"0.11.20\": [],\n                \"0.11.21\": [],\n                \"0.11.22\": [],\n                \"0.11.23\": [],\n                \"0.11.24\": [],\n                \"0.11.25\": [],\n                \"0.11.26\": [],\n                \"0.11.27\": [],\n                \"0.11.28\": [],\n                \"0.11.29\": [],\n                \"0.11.3\": [],\n                \"0.11.30\": [],\n                \"0.11.31\": [],\n                \"0.11.32\": [],\n                \"0.11.33\": [],\n                \"0.11.34\": [],\n                \"0.11.35\": [],\n                \"0.11.36\": [],\n                \"0.11.37\": [],\n                \"0.11.38\": [],\n                \"0.11.39\": [],\n                \"0.11.4\": [],\n                \"0.11.40\": [],\n                \"0.11.5\": [],\n                \"0.11.6\": [],\n                \"0.11.7\": [],\n                \"0.11.8\": [],\n                \"0.11.9\": [],\n                \"0.12.0\": [],\n                \"0.12.1\": [],\n                \"0.12.2\": [],\n                \"0.12.3\": [],\n                \"0.12.4\": [],\n                \"0.2.0\": [],\n                \"0.2.1\": [],\n                \"0.2.2\": [],\n                \"0.2.3\": [],\n                \"0.3.0\": [],\n                \"0.3.1\": [],\n                \"0.3.2\": [],\n                \"0.3.3\": [],\n                \"0.3.4\": [],\n                \"0.3.5\": [],\n                \"0.4.0\": [],\n                \"0.4.1\": [],\n                \"0.4.2\": [],\n                \"0.4.3\": [],\n                \"0.4.4\": [],\n                \"0.4.5\": [],\n                \"0.4.6\": [],\n                \"0.5.0\": [],\n                \"0.5.1\": [],\n                \"0.5.10\": [],\n                \"0.6.0\": [],\n                \"0.5.12\": [],\n                \"0.5.13\": [],\n                \"0.5.14\": [],\n                \"0.5.15\": [],\n                \"0.5.16\": [],\n                \"0.5.17\": [],\n                \"0.5.18\": [],\n                \"0.5.19\": [],\n                \"0.5.2\": [],\n                \"0.5.20\": [],\n                \"0.5.3\": [],\n                \"0.5.4\": [],\n                \"0.5.5\": [],\n                \"0.5.6\": [],\n                \"0.5.7\": [],\n                \"0.5.8\": [],\n                \"0.5.9\": [],\n                \"0.6.0\": [],\n                \"0.6.1\": [],\n                \"0.6.2\": [],\n                \"0.7.0\": [],\n                \"0.7.1\": [],\n                \"0.7.2\": [],\n                \"0.7.3\": [],\n                \"0.7.4\": [],\n                \"0.7.5\": [],\n                \"0.7.6\": [],\n                \"0.8.0\": [],\n                \"0.8.1\": [],\n                \"0.8.10\": [],\n                \"0.8.11\": [],\n                \"0.8.2\": [],\n                \"0.8.3\": [],\n                \"0.8.4\": [],\n                \"0.8.5\": [],\n                \"0.8.6\": [],\n                \"0.8.7\": [],\n                \"0.8.8\": [],\n                \"0.8.9\": [],\n                \"0.9.0\": [],\n                \"0.9.1\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n            \"versions\": {\n                \"0.0.1\": [],\n                \"0.10.0\": [],\n                \"0.11.0\": [],\n                \"0.12.0\": [],\n                \"0.2.0\": [],\n                \"0.3.0\": [],\n                \"0.4.0\": [],\n                \"0.5.0\": [],\n                \"0.5.1\": [],\n                \"0.7.0\": [],\n                \"0.7.1\": [],\n                \"0.8.0\": [],\n                \"0.9.0\": [],\n                \"1.0.0\": [],\n                \"1.1.0\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n            \"versions\": {\n                \"0.1.0\": [],\n                \"0.1.1\": [],\n                \"0.2.0\": [],\n                \"0.2.1\": [],\n                \"0.2.2\": [],\n                \"0.2.3\": [],\n                \"0.3.0\": [],\n                \"0.3.1\": [],\n                \"0.3.2\": [],\n                \"0.3.3\": [],\n                \"0.3.4\": [],\n                \"0.3.5\": [],\n                \"0.3.6\": [],\n                \"0.3.7\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/Kitura-TemplateEngine.git\",\n            \"versions\": {\n                \"0.13.0\": [],\n                \"0.14.0\": [],\n                \"0.16.0\": [],\n                \"0.26.0\": [],\n                \"0.30.0\": [],\n                \"0.32.0\": [],\n                \"1.0.0\": [],\n                \"1.1.0\": []\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n            \"versions\": {\n                \"0.1.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.1.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.1.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.1.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.1.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.1.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.1.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.1.7\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    }\n                ],\n                \"0.10.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.10\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.11\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.12\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.13\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.14\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.15\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.16\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.17\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.18\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.19\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.20\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.21\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.22\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.23\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.24\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.10.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.7\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.8\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.10.9\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.10\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.11\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.12\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.13\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.14\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.15\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.16\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.17\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.18\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.19\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.20\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.21\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.22\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.23\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.24\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.25\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.26\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.27\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.28\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.29\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.30\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.31\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.32\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.33\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.34\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.35\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.36\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.37\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.38\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.39\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.40\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.41\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.42\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.43\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.44\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.45\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.46\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.47\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.48\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.49\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.50\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.51\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.52\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.53\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.54\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.55\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.56\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.11.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.7\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.8\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.11.9\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    }\n                ],\n                \"0.12.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.12.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.12.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.12.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.8.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.8.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.8.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.8.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    }\n                ],\n                \"0.9.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    }\n                ],\n                \"0.9.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    }\n                ],\n                \"0.9.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    }\n                ],\n                \"0.9.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/OpenSSL-OSX.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.9.0\",\n                            \"0.10.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/Kitura-net.git\",\n            \"versions\": {\n                \"0.0.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    }\n                ],\n                \"0.0.2\": [\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    }\n                ],\n                \"0.0.4\": [\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    }\n                ],\n                \"0.0.5\": [\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    }\n                ],\n                \"0.0.6\": [\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    }\n                ],\n                \"0.0.7\": [\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"git@github.com:IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    }\n                ],\n                \"0.0.8\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    }\n                ],\n                \"0.10.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.11.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.11.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.11.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.11.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.11.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.11.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.11.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.111.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.111.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.111.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.12.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.10\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.7\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.8\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.13.9\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.14.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.14.0\",\n                            \"0.15.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.15.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.15.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.15.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.15.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.15.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.15.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.15.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.16.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.16.0\",\n                            \"0.17.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.17.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.16.0\",\n                            \"0.17.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.17.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.15.0\",\n                            \"0.16.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.17.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.13.0\",\n                            \"0.14.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.17.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.16.0\",\n                            \"0.17.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.17.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.17.0\",\n                            \"0.18.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.17.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.17.0\",\n                            \"0.18.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.17.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.17.0\",\n                            \"0.18.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.18.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.18.0\",\n                            \"0.19.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.19.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.17.0\",\n                            \"0.18.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.20.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.18.0\",\n                            \"0.19.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.21.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.21.0\",\n                            \"0.22.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.21.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.21.0\",\n                            \"0.22.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.5.0\",\n                            \"0.6.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.21.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.21.0\",\n                            \"0.22.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.22.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.22.0\",\n                            \"0.23.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.22.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.22.0\",\n                            \"0.23.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.22.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.22.0\",\n                            \"0.23.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    }\n                ],\n                \"0.23.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.22.0\",\n                            \"0.23.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.23.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.23.0\",\n                            \"0.24.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.23.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.23.0\",\n                            \"0.24.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.23.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.23.0\",\n                            \"0.24.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.24.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.24.0\",\n                            \"0.25.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.24.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.24.0\",\n                            \"0.25.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.25.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.25.0\",\n                            \"0.26.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.26.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.26.0\",\n                            \"0.27.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.27.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.26.0\",\n                            \"0.27.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.27.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.27.0\",\n                            \"0.28.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.27.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.27.0\",\n                            \"0.28.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.28.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.28.0\",\n                            \"0.29.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.28.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.28.0\",\n                            \"0.29.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.29.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.28.0\",\n                            \"0.29.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.29.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.28.0\",\n                            \"0.29.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.3.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    }\n                ],\n                \"0.3.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.3.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.3.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.3.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.3.7\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.3.8\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.30.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.30.0\",\n                            \"0.31.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.31.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.31.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.32.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.10.0\",\n                            \"0.11.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.33.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    }\n                ],\n                \"0.33.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.33.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.33.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"0.4.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.4.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.5.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-CurlHelpers.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-HttpParserHelper.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    }\n                ],\n                \"0.5.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.5.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.5.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"1.0.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.5.4\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.1.0\",\n                            \"0.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.5.5\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.5.6\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.5.7\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.5.8\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.6.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.7.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.6.0\",\n                            \"0.7.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.7.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.7.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.8.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.8.0\",\n                            \"0.9.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"0.9.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/Kitura-sys.git\",\n                        \"requirement\": [\n                            \"0.7.0\",\n                            \"0.8.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"0.4.0\",\n                            \"0.5.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHttpParser.git\",\n                        \"requirement\": [\n                            \"0.0.0\",\n                            \"0.1.0\"\n                        ]\n                    }\n                ],\n                \"1.0.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.0.0\",\n                            \"1.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"1.0.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.0.0\",\n                            \"1.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"1.0.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.0.0\",\n                            \"1.1.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"1.1.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.1.0\",\n                            \"1.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"1.1.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.1.0\",\n                            \"1.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CHTTPParser.git\",\n                        \"requirement\": [\n                            \"0.3.0\",\n                            \"0.4.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.11.0\",\n                            \"0.12.0\"\n                        ]\n                    }\n                ],\n                \"1.2.0\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.1.0\",\n                            \"1.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"1.2.1\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.1.0\",\n                            \"1.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"1.2.2\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.1.0\",\n                            \"1.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ],\n                \"1.2.3\": [\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/LoggerAPI.git\",\n                        \"requirement\": [\n                            \"1.1.0\",\n                            \"1.2.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSocket.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/CCurl.git\",\n                        \"requirement\": [\n                            \"0.2.0\",\n                            \"0.3.0\"\n                        ]\n                    },\n                    {\n                        \"identifier\": \"https://github.com/IBM-Swift/BlueSSLService.git\",\n                        \"requirement\": [\n                            \"0.12.0\",\n                            \"0.13.0\"\n                        ]\n                    }\n                ]\n            }\n        },\n        {\n            \"identifier\": \"https://github.com/IBM-Swift/SwiftyJSON.git\",\n            \"versions\": {\n                \"10.0.2\": [],\n                \"11.0.0\": [],\n                \"12.0.0\": [],\n                \"12.1.0\": [],\n                \"13.0.0\": [],\n                \"14.0.0\": [],\n                \"14.1.0\": [],\n                \"14.2.0\": [],\n                \"14.2.1\": [],\n                \"15.0.0\": [],\n                \"15.0.1\": []\n            }\n        }\n    ],\n    \"name\": \"Kitura\",\n    \"result\": {\n        \"https://github.com/IBM-Swift/BlueSSLService.git\": \"0.12.4\",\n        \"https://github.com/IBM-Swift/BlueSocket.git\": \"0.12.4\",\n        \"https://github.com/IBM-Swift/CCurl.git\": \"0.2.3\",\n        \"https://github.com/IBM-Swift/Kitura-TemplateEngine.git\": \"1.1.0\",\n        \"https://github.com/IBM-Swift/Kitura-net.git\": \"1.2.3\",\n        \"https://github.com/IBM-Swift/LoggerAPI.git\": \"1.1.0\",\n        \"https://github.com/IBM-Swift/SwiftyJSON.git\": \"15.0.1\"\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphPerformanceTests/PackageGraphPerfTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport OrderedCollections\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport PackageGraph\n\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nimport class TSCTestSupport.XCTestCasePerf\n\nfinal class PackageGraphPerfTests: XCTestCasePerf {\n    func testLoading100Packages() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n\n        let N = 100\n        let files = (1...N).map { \"/Foo\\($0)/source.swift\" }\n        let fs = InMemoryFileSystem(emptyFiles: files)\n\n        let identityResolver = DefaultIdentityResolver()\n        var externalManifests = OrderedCollections.OrderedDictionary<PackageIdentity, (manifest: Manifest, fs: FileSystem)>()\n        var rootManifest: Manifest!\n        for pkg in 1...N {\n            let name = \"Foo\\(pkg)\"\n            let location = \"/\" + name\n\n            let dependencies: [PackageDependency]\n            let targets: [TargetDescription]\n            // Create package.\n            if pkg == N {\n                dependencies = []\n                targets = [try TargetDescription(name: name, path: \".\")]\n            } else {\n                let depName = \"Foo\\(pkg + 1)\"\n                let depUrl = \"/\\(depName)\"\n                dependencies = [.localSourceControl(\n                    deprecatedName: depName,\n                    path: try .init(validating: depUrl),\n                    requirement: .upToNextMajor(from: \"1.0.0\")\n                )]\n                targets = [try TargetDescription(\n                    name: name,\n                    dependencies: [.byName(name: depName, condition: nil)],\n                    path: \".\"\n                )]\n            }\n            // Create manifest.\n            let isRoot = pkg == 1\n            let manifest = Manifest.createManifest(\n                displayName: name,\n                path: try AbsolutePath(validating: location).appending(component: Manifest.filename),\n                packageKind: isRoot ? .root(try .init(validating: location)) : .localSourceControl(try .init(validating: location)),\n                packageIdentity: .plain(name),\n                packageLocation: location,\n                platforms: [],\n                version: \"1.0.0\",\n                toolsVersion: .v4_2,\n                dependencies: dependencies,\n                products: [\n                    try ProductDescription(name: name, type: .library(.automatic), targets: [name])\n                ],\n                targets: targets\n            )\n            if isRoot {\n                rootManifest = manifest\n            } else {\n                let identity = try identityResolver.resolveIdentity(for: manifest.packageKind)\n                externalManifests[identity] = (manifest, fs)\n            }\n        }\n\n        measure {\n            let observability = ObservabilitySystem.makeForTesting()\n            let g = try! ModulesGraph.load(\n                root: PackageGraphRoot(\n                    input: PackageGraphRootInput(packages: [rootManifest.path]),\n                    manifests: [rootManifest.path: rootManifest],\n                    observabilityScope: observability.topScope\n                ),\n                identityResolver: identityResolver,\n                externalManifests: externalManifests,\n                binaryArtifacts: [:],\n                prebuilts: [:],\n                fileSystem: fs,\n                observabilityScope: observability.topScope,\n                enabledTraitsMap: [:]\n            )\n            XCTAssertEqual(g.packages.count, N)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    func testEfficientCycleDetection() throws {\n        let lastPackageNumber = 20\n        let packageNumberSequence = (1...lastPackageNumber)\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: packageNumberSequence.map({ \"/Package\\($0)/Sources/Target\\($0)/s.swift\" }) + \n                [\"/PackageA/Sources/TargetA/s.swift\"]\n        )\n\n        let packageSequence: [Manifest] = try packageNumberSequence.map { (sequenceNumber: Int) -> Manifest in\n            let dependencySequence = sequenceNumber < lastPackageNumber ? Array((sequenceNumber + 1)...lastPackageNumber) : []\n            return Manifest.createFileSystemManifest(\n                displayName: \"Package\\(sequenceNumber)\",\n                path: try .init(validating: \"/Package\\(sequenceNumber)\"),\n                toolsVersion: .v5_7,\n                dependencies: try dependencySequence.map({ .fileSystem(path: try .init(validating: \"/Package\\($0)\")) }),\n                products: [\n                    try .init(\n                        name: \"Package\\(sequenceNumber)\",\n                        type: .library(.dynamic),\n                        targets: [\"Target\\(sequenceNumber)\"]\n                    )\n                ],\n                targets: [\n                    try .init(\n                        name: \"Target\\(sequenceNumber)\",\n                        dependencies: dependencySequence.map {\n                            .product(name: \"Target\\($0)\", package: \"Package\\($0)\")\n                        }\n                    )\n                ]\n            )\n        }\n\n        let root = Manifest.createRootManifest(\n            displayName: \"PackageA\",\n            path: \"/PackageA\",\n            toolsVersion: .v5_7,\n            dependencies: try packageNumberSequence.map({ .fileSystem(path: try .init(validating: \"/Package\\($0)\")) }),\n            targets: [try .init(name: \"TargetA\", dependencies: [\"Target1\"]) ]\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let N = 1\n        measure {\n            do {\n                for _ in 0..<N {\n                    _ = try loadModulesGraph(\n                        fileSystem: fs,\n                        manifests: [root] + packageSequence,\n                        observabilityScope: observability.topScope\n                    )\n                }\n            } catch {\n                XCTFail(\"Loading package graph is not expected to fail in this test.\")\n            }\n        }\n    }\n\n    func testRecursiveDependencies() throws {\n        try XCTSkipOnWindows()\n\n        var resolvedTarget = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t0\")\n        for i in 1..<1000 {\n            resolvedTarget = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t\\(i)\", deps: resolvedTarget)\n        }        \n\n        let N = 10\n        measure {\n            do {\n                for _ in 0..<N {\n                    _ = try resolvedTarget.recursiveModuleDependencies()\n                }\n            } catch {\n                XCTFail(\"Loading package graph is not expected to fail in this test.\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphTests/CrossCompilationPackageGraphTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable\n@_spi(SwiftPMInternal)\nimport _InternalTestSupport\n\n@testable\nimport PackageGraph\n\nimport PackageModel\nimport XCTest\n\nfinal class CrossCompilationPackageGraphTests: XCTestCase {\n    func testTrivialPackage() throws {\n        let graph = try trivialPackageGraph().graph\n        PackageGraphTesterXCTest(graph) { result in\n            result.check(packages: \"Pkg\")\n            // \"SwiftSyntax\" is included for both host and target triples and is not pruned on this level\n            result.check(modules: \"app\", \"lib\")\n            result.check(testModules: \"test\")\n            result.checkTarget(\"app\") { result in\n                result.check(dependencies: \"lib\")\n            }\n            result.checkTarget(\"lib\") { result in\n                result.check(dependencies: [])\n            }\n            result.checkTarget(\"test\") { result in\n                result.check(dependencies: \"lib\")\n            }\n        }\n    }\n\n    func testMacros() throws {\n        let graph = try macrosPackageGraph().graph\n        PackageGraphTesterXCTest(graph) { result in\n            result.check(packages: \"swift-firmware\", \"swift-mmio\", \"swift-syntax\")\n            result.check(\n                modules: \"Core\",\n                \"HAL\",\n                \"MMIO\",\n                \"MMIOMacros\",\n                \"SwiftSyntax\"\n            )\n            result.check(testModules: \"CoreTests\", \"HALTests\")\n            result.checkTarget(\"Core\") { result in\n                result.check(dependencies: \"HAL\")\n            }\n            result.checkTarget(\"HAL\") { result in\n                result.check(dependencies: \"MMIO\")\n            }\n            result.checkTarget(\"MMIO\") { result in\n                result.check(dependencies: \"MMIOMacros\")\n            }\n            result.checkTarget(\"MMIOMacros\") { result in\n                result.checkDependency(\"SwiftSyntax\") { result in\n                    result.checkProduct { result in\n                        result.checkTarget(\"SwiftSyntax\") { _ in\n                        }\n                    }\n                }\n            }\n\n            result.checkTargets(\"SwiftSyntax\") { results in\n                XCTAssertEqual(results.count, 1)\n            }\n        }\n    }\n\n    func testMacrosTests() throws {\n        let graph = try macrosTestsPackageGraph().graph\n        PackageGraphTesterXCTest(graph) { result in\n            result.check(packages: \"swift-mmio\", \"swift-syntax\")\n            // \"SwiftSyntax\" is included for both host and target triples and is not pruned on this level\n            result.check(\n                modules: \"MMIO\",\n                \"MMIOMacros\",\n                \"MMIOPlugin\",\n                \"SwiftCompilerPlugin\",\n                \"SwiftCompilerPluginMessageHandling\",\n                \"SwiftSyntax\",\n                \"SwiftSyntaxMacros\",\n                \"SwiftSyntaxMacrosTestSupport\"\n            )\n\n            result.check(testModules: \"MMIOMacrosTests\", \"MMIOMacro+PluginTests\", \"NOOPTests\", \"SwiftSyntaxTests\")\n            result.checkTarget(\"MMIO\") { result in\n                result.check(dependencies: \"MMIOMacros\")\n            }\n            result.checkTargets(\"MMIOMacros\") { results in\n                XCTAssertEqual(results.count, 1)\n            }\n\n            result.checkTarget(\"MMIOMacrosTests\") { result in\n                result.checkDependency(\"MMIOMacros\") { result in\n                    result.checkTarget { result in\n                        result.checkDependency(\"SwiftSyntaxMacros\") { result in\n                            result.checkProduct { _ in\n                            }\n                        }\n                        result.checkDependency(\"SwiftCompilerPlugin\") { result in\n                            result.checkProduct { result in\n                                result.checkTarget(\"SwiftCompilerPlugin\") { result in\n                                    result.checkDependency(\"SwiftCompilerPluginMessageHandling\") { result in\n                                        result.checkTarget { _ in\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            result.checkTarget(\"MMIOMacros\") { _ in\n            }\n\n            result.checkTarget(\"MMIOMacrosTests\") { _ in\n            }\n\n            result.checkTargets(\"SwiftSyntax\") { results in\n                XCTAssertEqual(results.count, 1)\n\n                for result in results {\n                    XCTAssertEqual(result.target.packageIdentity, .plain(\"swift-syntax\"))\n                    XCTAssertEqual(graph.package(for: result.target)?.identity, .plain(\"swift-syntax\"))\n                }\n            }\n\n            result.checkTargets(\"SwiftCompilerPlugin\") { results in\n                XCTAssertEqual(results.count, 1)\n\n                for result in results {\n                    XCTAssertEqual(result.target.packageIdentity, .plain(\"swift-syntax\"))\n                    XCTAssertEqual(graph.package(for: result.target)?.identity, .plain(\"swift-syntax\"))\n                }\n            }\n\n            result.checkTargets(\"NOOPTests\") { results in\n                XCTAssertEqual(results.count, 1)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphTests/DependencyResolverTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\nimport PackageGraph\nimport SourceControl\n\nimport struct TSCUtility.Version\n\nimport _InternalTestSupport\n\nimport PackageModel\n\nprivate typealias MockPackageConstraint = PackageContainerConstraint\n\n// Some handy ranges.\n//\n// The convention is that the name matches how specific the version is, so \"v1\"\n// means \"any 1.?.?\", and \"v1_1\" means \"any 1.1.?\".\n\nprivate let v1: Version = \"1.0.0\"\nprivate let v1_1: Version = \"1.1.0\"\nprivate let v2: Version = \"2.0.0\"\nprivate let v0_0_0Range: VersionSetSpecifier = .range(\"0.0.0\" ..< \"0.0.1\")\nprivate let v1Range: VersionSetSpecifier = .range(\"1.0.0\" ..< \"2.0.0\")\nprivate let v1to3Range: VersionSetSpecifier = .range(\"1.0.0\" ..< \"3.0.0\")\nprivate let v2Range: VersionSetSpecifier = .range(\"2.0.0\" ..< \"3.0.0\")\nprivate let v1_to_3Range: VersionSetSpecifier = .range(\"1.0.0\" ..< \"3.0.0\")\nprivate let v2_to_4Range: VersionSetSpecifier = .range(\"2.0.0\" ..< \"4.0.0\")\nprivate let v1_0Range: VersionSetSpecifier = .range(\"1.0.0\" ..< \"1.1.0\")\nprivate let v1_1Range: VersionSetSpecifier = .range(\"1.1.0\" ..< \"1.2.0\")\nprivate let v1_1_0Range: VersionSetSpecifier = .range(\"1.1.0\" ..< \"1.1.1\")\nprivate let v2_0_0Range: VersionSetSpecifier = .range(\"2.0.0\" ..< \"2.0.1\")\n\nclass DependencyResolverTests: XCTestCase {\n    func testVersionSetSpecifier() {\n        // Check `contains`.\n        XCTAssert(v1Range.contains(\"1.1.0\"))\n        XCTAssert(!v1Range.contains(\"2.0.0\"))\n\n        // Check `intersection`.\n        XCTAssert(v1Range.intersection(v1_1Range) == v1_1Range)\n        XCTAssert(v1Range.intersection(v1_1_0Range) == v1_1_0Range)\n        XCTAssert(v1Range.intersection(v2Range) == .empty)\n        XCTAssert(v1Range.intersection(v2_0_0Range) == .empty)\n        XCTAssert(v1Range.intersection(v1_1Range) == v1_1Range)\n        XCTAssert(v1_to_3Range.intersection(v2_to_4Range) == .range(\"2.0.0\" ..< \"3.0.0\"))\n        XCTAssert(v1Range.intersection(.any) == v1Range)\n        XCTAssert(VersionSetSpecifier.empty.intersection(.any) == .empty)\n        XCTAssert(VersionSetSpecifier.any.intersection(.any) == .any)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphTests/ModulesGraphTests+Traits.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport TSCUtility\nimport Testing\nimport _InternalTestSupport\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\n@testable import PackageGraph\n\nextension ModulesGraphTests {\n    @Test\n    func traits_whenSingleManifest_andDefaultTrait() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_9,\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\"\n                        ),\n                    ],\n                    traits: [\n                        .init(name: \"default\", enabledTraits: [\"Trait1\"]),\n                        \"Trait1\",\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: [\n                \"Foo\": [\"Trait1\"]\n            ]\n        )\n\n        #expect(observability.diagnostics.count == 0)\n\n        try PackageGraphTester(graph) { result in\n            try result.checkPackage(\"Foo\") { package in\n                #expect(package.enabledTraits == [\"Trait1\"])\n            }\n        }\n    }\n\n    @Test\n    func traits_whenTraitEnablesOtherTraits() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_9,\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\"\n                        ),\n                    ],\n                    traits: [\n                        .init(name: \"default\", enabledTraits: [\"Trait1\"]),\n                        .init(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n                        .init(name: \"Trait2\", enabledTraits: [\"Trait3\", \"Trait4\"]),\n                        \"Trait3\",\n                        .init(name: \"Trait4\", enabledTraits: [\"Trait5\"]),\n                        \"Trait5\",\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: [\n                \"Foo\": [\"Trait1\", \"Trait2\", \"Trait3\", \"Trait4\", \"Trait5\"]\n            ]\n        )\n\n        #expect(observability.diagnostics.count == 0)\n\n        try PackageGraphTester(graph) { result in\n            try result.checkPackage(\"Foo\") { package in\n                #expect(package.enabledTraits == [\"Trait1\", \"Trait2\", \"Trait3\", \"Trait4\", \"Trait5\"])\n            }\n        }\n    }\n\n    @Test\n    func traits_whenDependencyTraitEnabled() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Package1/Sources/Package1Target1/source.swift\",\n            \"/Package2/Sources/Package2Target1/source.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Package1\",\n                    path: \"/Package1\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .localSourceControl(\n                            path: \"/Package2\",\n                            requirement: .upToNextMajor(from: \"1.0.0\"),\n                            traits: [\"Package2Trait1\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Package1Target1\",\n                            dependencies: [\n                                .product(name: \"Package2Target1\", package: \"Package2\"),\n                            ]\n                        ),\n                    ],\n                    traits: [\n                        .init(name: \"default\", enabledTraits: [\"Package1Trait1\"]),\n                        \"Package1Trait1\",\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Package2\",\n                    path: \"/Package2\",\n                    toolsVersion: .v5_9,\n                    products: [\n                        .init(\n                            name: \"Package2Target1\",\n                            type: .library(.automatic),\n                            targets: [\"Package2Target1\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Package2Target1\"\n                        ),\n                    ],\n                    traits: [\n                        \"Package2Trait1\",\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: [\n                \"Package1\": [\"Package1Trait1\"],\n                \"Package2\": [\"Package2Trait1\"]\n            ]\n        )\n\n        #expect(observability.diagnostics.count == 0)\n\n        try PackageGraphTester(graph) { result in\n            try result.checkPackage(\"Package1\") { package in\n                #expect(package.enabledTraits == [\"Package1Trait1\"])\n                #expect(package.dependencies.count == 1)\n            }\n            try result.checkPackage(\"Package2\") { package in\n                #expect(package.enabledTraits == [\"Package2Trait1\"])\n            }\n        }\n    }\n\n    @Test\n    func traits_whenTraitEnablesDependencyTrait() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Package1/Sources/Package1Target1/source.swift\",\n            \"/Package2/Sources/Package2Target1/source.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Package1\",\n                path: \"/Package1\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package2\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package2Trait1\", condition: .init(traits: [\"Package1Trait1\"]))])\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package1Target1\",\n                        dependencies: [\n                            .product(name: \"Package2Target1\", package: \"Package2\"),\n                        ]\n                    ),\n                ],\n                traits: [\n                    .init(name: \"default\", enabledTraits: [\"Package1Trait1\"]),\n                    .init(name: \"Package1Trait1\"),\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package2\",\n                path: \"/Package2\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"Package2Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package2Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package2Target1\"\n                    ),\n                ],\n                traits: [\n                    \"Package2Trait1\",\n                ]\n            ),\n        ]\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: manifests,\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: [\n                \"Package1\": [\"Package1Trait1\"],\n                \"Package2\": [\"Package2Trait1\"]\n            ]\n        )\n\n        #expect(observability.diagnostics.count == 0)\n\n        try PackageGraphTester(graph) { result in\n            try result.checkPackage(\"Package1\") { package in\n                #expect(package.enabledTraits == [\"Package1Trait1\"])\n                #expect(package.dependencies.count == 1)\n            }\n            try result.checkPackage(\"Package2\") { package in\n                #expect(package.enabledTraits == [\"Package2Trait1\"])\n            }\n        }\n    }\n\n    @Test\n    func traits_whenComplex() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Package1/Sources/Package1Target1/source.swift\",\n            \"/Package2/Sources/Package2Target1/source.swift\",\n            \"/Package3/Sources/Package3Target1/source.swift\",\n            \"/Package4/Sources/Package4Target1/source.swift\",\n            \"/Package5/Sources/Package5Target1/source.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Package1\",\n                path: \"/Package1\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package2\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package2Trait1\", condition: .init(traits: [\"Package1Trait1\"]))])\n                    ),\n                    .localSourceControl(\n                        path: \"/Package4\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([\"Package4Trait2\"])\n                    ),\n                    .localSourceControl(\n                        path: \"/Package5\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package1Target1\",\n                        dependencies: [\n                            .product(name: \"Package2Target1\", package: \"Package2\"),\n                            .product(name: \"Package4Target1\", package: \"Package4\"),\n                            .product(\n                                name: \"Package5Target1\",\n                                package: \"Package5\",\n                                condition: .init(traits: [\"Package1Trait2\"])\n                            ),\n                        ],\n                        settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .define(\"TEST_DEFINE\"),\n                                condition: .init(traits: [\"Package1Trait1\"])\n                            ),\n                        ]\n                    ),\n                ],\n                traits: [\n                    .init(name: \"default\", enabledTraits: [\"Package1Trait1\", \"Package1Trait2\"]),\n                    .init(name: \"Package1Trait1\"),\n                    .init(name: \"Package1Trait2\"),\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package2\",\n                path: \"/Package2\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package3\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package3Trait1\", condition: .init(traits: [\"Package2Trait1\"]))])\n                    ),\n                ],\n                products: [\n                    .init(\n                        name: \"Package2Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package2Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package2Target1\",\n                        dependencies: [\n                            .product(name: \"Package3Target1\", package: \"Package3\"),\n                        ]\n                    ),\n                ],\n                traits: [\n                    \"Package2Trait1\",\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package3\",\n                path: \"/Package3\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package4\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package4Trait1\", condition: .init(traits: [\"Package3Trait1\"]))])\n                    ),\n                ],\n                products: [\n                    .init(\n                        name: \"Package3Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package3Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package3Target1\",\n                        dependencies: [\n                            .product(name: \"Package4Target1\", package: \"Package4\"),\n                        ]\n                    ),\n                ],\n                traits: [\n                    \"Package3Trait1\",\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package4\",\n                path: \"/Package4\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"Package4Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package4Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package4Target1\"\n                    ),\n                ],\n                traits: [\n                    \"Package4Trait1\",\n                    \"Package4Trait2\",\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package5\",\n                path: \"/Package5\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"Package5Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package5Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package5Target1\"\n                    ),\n                ]\n            ),\n        ]\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: manifests,\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: [\n                \"Package1\": [\"Package1Trait1\", \"Package1Trait2\"],\n                \"Package2\": [\"Package2Trait1\"],\n                \"Package3\": [\"Package3Trait1\"],\n                \"Package4\": [\"Package4Trait1\", \"Package4Trait2\"]\n            ]\n        )\n\n        #expect(observability.diagnostics.count == 0)\n\n        try PackageGraphTester(graph) { result in\n            try result.checkPackage(\"Package1\") { package in\n                #expect(package.enabledTraits == [\"Package1Trait1\", \"Package1Trait2\"])\n                #expect(package.dependencies.count == 3)\n            }\n            try result.checkTarget(\"Package1Target1\") { target in\n                target.check(dependencies: \"Package2Target1\", \"Package4Target1\", \"Package5Target1\")\n                target.checkBuildSetting(\n                    declaration: .SWIFT_ACTIVE_COMPILATION_CONDITIONS,\n                    assignments: [\n                        .init(values: [\"TEST_DEFINE\"], conditions: [.traits(.init(traits: [\"Package1Trait1\"]))]),\n                        .init(values: [\"Package1Trait2\"]),\n                        .init(values: [\"Package1Trait1\"]),\n                    ]\n                )\n            }\n            try result.checkPackage(\"Package2\") { package in\n                #expect(package.enabledTraits == [\"Package2Trait1\"])\n            }\n            try result.checkPackage(\"Package3\") { package in\n                #expect(package.enabledTraits == [\"Package3Trait1\"])\n            }\n            try result.checkPackage(\"Package4\") { package in\n                #expect(package.enabledTraits == [\"Package4Trait1\", \"Package4Trait2\"])\n            }\n        }\n    }\n\n    @Test\n    func traits_whenPruneDependenciesEnabled() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Package1/Sources/Package1Target1/source.swift\",\n            \"/Package2/Sources/Package2Target1/source.swift\",\n            \"/Package3/Sources/Package3Target1/source.swift\",\n            \"/Package4/Sources/Package4Target1/source.swift\",\n            \"/Package5/Sources/Package5Target1/source.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Package1\",\n                path: \"/Package1\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package2\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package2Trait1\", condition: .init(traits: [\"Package1Trait1\"]))])\n                    ),\n                    .localSourceControl(\n                        path: \"/Package4\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([\"Package4Trait2\"])\n                    ),\n                    .localSourceControl(\n                        path: \"/Package5\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package1Target1\",\n                        dependencies: [\n                            .product(name: \"Package2Target1\", package: \"Package2\"),\n                            .product(name: \"Package4Target1\", package: \"Package4\"),\n                            .product(\n                                name: \"Package5Target1\",\n                                package: \"Package5\",\n                                condition: .init(traits: [\"Package1Trait2\"])\n                            ),\n                        ],\n                        settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .define(\"TEST_DEFINE\"),\n                                condition: .init(traits: [\"Package1Trait1\"])\n                            ),\n                            .init(\n                                tool: .swift,\n                                kind: .define(\"TEST_DEFINE_2\"),\n                                condition: .init(traits: [\"Package1Trait3\"])\n                            ),\n                        ]\n                    ),\n                ],\n                traits: [\n                    .init(name: \"default\", enabledTraits: [\"Package1Trait3\"]),\n                    .init(name: \"Package1Trait1\"),\n                    .init(name: \"Package1Trait2\"),\n                    .init(name: \"Package1Trait3\"),\n                ],\n                pruneDependencies: true\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package2\",\n                path: \"/Package2\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package3\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package3Trait1\", condition: .init(traits: [\"Package2Trait1\"]))])\n                    ),\n                ],\n                products: [\n                    .init(\n                        name: \"Package2Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package2Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package2Target1\",\n                        dependencies: [\n                            .product(name: \"Package3Target1\", package: \"Package3\"),\n                        ]\n                    ),\n                ],\n                traits: [\n                    \"Package2Trait1\",\n                ],\n                pruneDependencies: true\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package3\",\n                path: \"/Package3\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package4\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package4Trait1\", condition: .init(traits: [\"Package3Trait1\"]))])\n                    ),\n                ],\n                products: [\n                    .init(\n                        name: \"Package3Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package3Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package3Target1\",\n                        dependencies: [\n                            .product(name: \"Package4Target1\", package: \"Package4\"),\n                        ]\n                    ),\n                ],\n                traits: [\n                    \"Package3Trait1\",\n                ],\n                pruneDependencies: true\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package4\",\n                path: \"/Package4\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"Package4Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package4Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package4Target1\"\n                    ),\n                ],\n                traits: [\n                    \"Package4Trait1\",\n                    \"Package4Trait2\",\n                ],\n                pruneDependencies: true\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package5\",\n                path: \"/Package5\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"Package5Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package5Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package5Target1\"\n                    ),\n                ],\n                pruneDependencies: true\n            ),\n        ]\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: manifests,\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: [\n                \"Package1\": [\"Package1Trait3\"],\n                \"Package2\": [],\n                \"Package3\": [],\n                \"Package4\": [\"Package4Trait2\"]\n            ]\n        )\n\n        #expect(observability.diagnostics.count == 0)\n\n        try PackageGraphTester(graph) { result in\n            try result.checkPackage(\"Package1\") { package in\n                #expect(package.enabledTraits == [\"Package1Trait3\"])\n                #expect(package.dependencies.count == 2)\n            }\n            try result.checkTarget(\"Package1Target1\") { target in\n                target.check(dependencies: \"Package2Target1\", \"Package4Target1\")\n                target.checkBuildSetting(\n                    declaration: .SWIFT_ACTIVE_COMPILATION_CONDITIONS,\n                    assignments: [\n                        .init(values: [\"TEST_DEFINE_2\"], conditions: [.traits(.init(traits: [\"Package1Trait3\"]))]),\n                        .init(values: [\"Package1Trait3\"]),\n                    ]\n                )\n            }\n            try result.checkPackage(\"Package2\") { package in\n                #expect(package.enabledTraits == [])\n            }\n            try result.checkPackage(\"Package3\") { package in\n                #expect(package.enabledTraits == [])\n            }\n            try result.checkPackage(\"Package4\") { package in\n                #expect(package.enabledTraits == [\"Package4Trait2\"])\n            }\n        }\n    }\n\n    @Test\n    func traits_whenPruneDependenciesEnabledForSomeManifests() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Package1/Sources/Package1Target1/source.swift\",\n            \"/Package2/Sources/Package2Target1/source.swift\",\n            \"/Package3/Sources/Package3Target1/source.swift\",\n            \"/Package4/Sources/Package4Target1/source.swift\",\n            \"/Package5/Sources/Package5Target1/source.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Package1\",\n                path: \"/Package1\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package2\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package2Trait1\", condition: .init(traits: [\"Package1Trait1\"]))])\n                    ),\n                    .localSourceControl(\n                        path: \"/Package4\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([\"Package4Trait2\"])\n                    ),\n                    .localSourceControl(\n                        path: \"/Package5\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package1Target1\",\n                        dependencies: [\n                            .product(name: \"Package2Target1\", package: \"Package2\"),\n                            .product(name: \"Package4Target1\", package: \"Package4\"),\n                            .product(\n                                name: \"Package5Target1\",\n                                package: \"Package5\",\n                                condition: .init(traits: [\"Package1Trait2\"])\n                            ),\n                        ],\n                        settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .define(\"TEST_DEFINE\"),\n                                condition: .init(traits: [\"Package1Trait1\"])\n                            ),\n                            .init(\n                                tool: .swift,\n                                kind: .define(\"TEST_DEFINE_2\"),\n                                condition: .init(traits: [\"Package1Trait3\"])\n                            ),\n                        ]\n                    ),\n                ],\n                traits: [\n                    .init(name: \"default\", enabledTraits: [\"Package1Trait3\"]),\n                    .init(name: \"Package1Trait1\"),\n                    .init(name: \"Package1Trait2\"),\n                    .init(name: \"Package1Trait3\"),\n                ],\n                pruneDependencies: false\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package2\",\n                path: \"/Package2\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package3\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package3Trait1\", condition: .init(traits: [\"Package2Trait1\"]))])\n                    ),\n                ],\n                products: [\n                    .init(\n                        name: \"Package2Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package2Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package2Target1\",\n                        dependencies: [\n                            .product(name: \"Package3Target1\", package: \"Package3\"),\n                        ]\n                    ),\n                ],\n                traits: [\n                    \"Package2Trait1\",\n                ],\n                pruneDependencies: true\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package3\",\n                path: \"/Package3\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Package4\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                        traits: .init([.init(name: \"Package4Trait1\", condition: .init(traits: [\"Package3Trait1\"]))])\n                    ),\n                ],\n                products: [\n                    .init(\n                        name: \"Package3Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package3Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package3Target1\",\n                        dependencies: [\n                            .product(name: \"Package4Target1\", package: \"Package4\"),\n                        ]\n                    ),\n                ],\n                traits: [\n                    \"Package3Trait1\",\n                ],\n                pruneDependencies: true\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package4\",\n                path: \"/Package4\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"Package4Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package4Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package4Target1\"\n                    ),\n                ],\n                traits: [\n                    \"Package4Trait1\",\n                    \"Package4Trait2\",\n                ],\n                pruneDependencies: true\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Package5\",\n                path: \"/Package5\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"Package5Target1\",\n                        type: .library(.automatic),\n                        targets: [\"Package5Target1\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Package5Target1\"\n                    ),\n                ],\n                pruneDependencies: true\n            ),\n        ]\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: manifests,\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: [\n                \"Package1\": [\"Package1Trait3\"],\n                \"Package2\": [],\n                \"Package3\": [],\n                \"Package4\": [\"Package4Trait2\"]\n            ]\n        )\n\n        #expect(observability.diagnostics.count == 0)\n        try PackageGraphTester(graph) { result in\n            try result.checkPackage(\"Package1\") { package in\n                #expect(package.enabledTraits == [\"Package1Trait3\"])\n                #expect(package.dependencies.count == 2)\n            }\n            try result.checkTarget(\"Package1Target1\") { target in\n                target.check(dependencies: \"Package2Target1\", \"Package4Target1\")\n                target.checkBuildSetting(\n                    declaration: .SWIFT_ACTIVE_COMPILATION_CONDITIONS,\n                    assignments: [\n                        .init(values: [\"TEST_DEFINE_2\"], conditions: [.traits(.init(traits: [\"Package1Trait3\"]))]),\n                        .init(values: [\"Package1Trait3\"]),\n                    ]\n                )\n            }\n            try result.checkPackage(\"Package2\") { package in\n                #expect(package.enabledTraits == [])\n            }\n            try result.checkPackage(\"Package3\") { package in\n                #expect(package.enabledTraits == [])\n            }\n            try result.checkPackage(\"Package4\") { package in\n                #expect(package.enabledTraits == [\"Package4Trait2\"])\n            }\n        }\n    }\n\n    @Test\n    func traits_whenConditionalDependencies() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Lunch/Sources/Drink/source.swift\",\n            \"/Caffeine/Sources/CoffeeTarget/source.swift\",\n            \"/Juice/Sources/AppleJuiceTarget/source.swift\",\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Lunch\",\n                path: \"/Lunch\",\n                toolsVersion: .v5_9,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Caffeine\",\n                        requirement: .upToNextMajor(from: \"1.0.0\"),\n                    ),\n                    .localSourceControl(\n                        path: \"/Juice\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    )\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"Drink\",\n                        dependencies: [\n                            .product(\n                                name: \"Coffee\",\n                                package: \"Caffeine\",\n                                condition: .init(traits: [\"EnableCoffeeDep\"])\n                            ),\n                            .product(\n                                name: \"AppleJuice\",\n                                package: \"Juice\",\n                                condition: .init(traits: [\"EnableAppleJuiceDep\"])\n                            )\n                        ],\n                    ),\n                ],\n                traits: [\n                    .init(name: \"default\", enabledTraits: [\"EnableCoffeeDep\"]),\n                    .init(name: \"EnableCoffeeDep\"),\n                    .init(name: \"EnableAppleJuiceDep\"),\n                ],\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Caffeine\",\n                path: \"/Caffeine\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"Coffee\",\n                        type: .library(.automatic),\n                        targets: [\"CoffeeTarget\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"CoffeeTarget\",\n                    ),\n                ],\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Juice\",\n                path: \"/Juice\",\n                toolsVersion: .v5_9,\n                products: [\n                    .init(\n                        name: \"AppleJuice\",\n                        type: .library(.automatic),\n                        targets: [\"AppleJuiceTarget\"]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(\n                        name: \"AppleJuiceTarget\",\n                    ),\n                ],\n            )\n        ]\n\n        // Test graph with default trait configuration\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: manifests,\n            observabilityScope: observability.topScope,\n            enabledTraitsMap: [\n                \"Lunch\": [\"EnableCoffeeDep\"]\n            ]\n        )\n\n        #expect(observability.diagnostics.count == 0)\n        try PackageGraphTester(graph) { result in\n            try result.checkPackage(\"Lunch\") { package in\n                #expect(package.enabledTraits == [\"EnableCoffeeDep\"])\n                #expect(package.dependencies.count == 1)\n            }\n            try result.checkTarget(\"Drink\") { target in\n                target.check(dependencies: \"Coffee\")\n            }\n            try result.checkPackage(\"Caffeine\") { package in\n                #expect(package.enabledTraits == [\"default\"])\n            }\n            try result.checkPackage(\"Juice\") { package in\n                #expect(package.enabledTraits == [\"default\"])\n            }\n        }\n\n        // Test graph when disabling all traits\n        let graphWithTraitsDisabled = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: manifests,\n            observabilityScope: observability.topScope,\n            traitConfiguration: .disableAllTraits,\n            enabledTraitsMap: [\n                \"Lunch\": [],\n            ]\n        )\n        #expect(observability.diagnostics.count == 0)\n\n        try PackageGraphTester(graphWithTraitsDisabled) { result in\n            try result.checkPackage(\"Lunch\") { package in\n                #expect(package.enabledTraits == [])\n                #expect(package.dependencies.count == 0)\n            }\n            try result.checkTarget(\"Drink\") { target in\n                #expect(target.target.dependencies.isEmpty)\n            }\n            try result.checkPackage(\"Caffeine\") { package in\n                #expect(package.enabledTraits == [\"default\"])\n            }\n            try result.checkPackage(\"Juice\") { package in\n                #expect(package.enabledTraits == [\"default\"])\n            }\n        }\n\n        // Test graph when we set a trait configuration that enables different traits than the defaults\n        let graphWithDifferentEnabledTraits = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: manifests,\n            observabilityScope: observability.topScope,\n            traitConfiguration: .enabledTraits([\"EnableAppleJuiceDep\"]),\n            enabledTraitsMap: [\n                \"Lunch\": [\"EnableAppleJuiceDep\"],\n            ]\n        )\n        #expect(observability.diagnostics.count == 0)\n\n        try PackageGraphTester(graphWithDifferentEnabledTraits) { result in\n            try result.checkPackage(\"Lunch\") { package in\n                #expect(package.enabledTraits == [\"EnableAppleJuiceDep\"])\n                #expect(package.dependencies.count == 1)\n            }\n            try result.checkTarget(\"Drink\") { target in\n                target.check(dependencies: \"AppleJuice\")\n            }\n            try result.checkPackage(\"Caffeine\") { package in\n                #expect(package.enabledTraits == [\"default\"])\n            }\n            try result.checkPackage(\"Juice\") { package in\n                #expect(package.enabledTraits == [\"default\"])\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "Tests/PackageGraphTests/ModulesGraphTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport PackageLoading\nimport TSCUtility\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\n@testable import PackageGraph\n\nimport _InternalTestSupport\nimport PackageModel\nimport struct PackageGraph.ModulesGraph\nimport Testing\n\nimport struct TSCBasic.ByteString\n\n@Suite\nstruct ModulesGraphTests {\n\n    @Suite(\n        .tags(\n            Tag.TestSize.small,\n        ),\n    )\n    struct getReplProductName {\n        @Test(\n            \"Empty root package throws an error\",\n        )\n        func emptyRootPackages() async throws {\n            let moduleGraph = try ModulesGraph(\n                rootPackages: [],\n                packages: IdentifiableSet([ResolvedPackage]()),\n                dependencies: [],\n                binaryArtifacts: [:],\n            )\n\n            #expect(throws: StringError(\"Root package does not exist.\")) { // Index out of range\n                let _ = try moduleGraph.getReplProductName()\n            }\n        }\n\n        @Test(\n            \"Non-empty root package results expected REPL product name\",\n            arguments: 1...5,\n        )\n        func nonEmptyRootPackages(\n            num: Int,\n        ) async throws {\n            // GIVEN a module graph instance with X number of root packages, where the package names are `package_#`\n            let manifest = Manifest(\n                displayName: \"manifestUT\",\n                packageIdentity: PackageIdentity(\"manifest_id\"),\n                path: AbsolutePath(\"/\"),\n                packageKind: .fileSystem(AbsolutePath(\"/\")),\n                packageLocation: \"\",\n                defaultLocalization: nil,\n                platforms: [],\n                version: nil,\n                revision: nil,\n                toolsVersion: .vNext,\n                pkgConfig: nil,\n                providers: nil,\n                cLanguageStandard: nil,\n                cxxLanguageStandard: nil,\n                swiftLanguageVersions: nil,\n                traits: Set([]),\n            )\n            let rootPackages = (0..<num).map {\n                ResolvedPackage(\n                    underlying: Package(\n                        identity: PackageIdentity(\"package_\\($0)\"),\n                        manifest: manifest,\n                        path: AbsolutePath(\"/\"),\n                        targets: [],\n                        products: [],\n                        targetSearchPath: AbsolutePath(\"/\"),\n                        testTargetSearchPath: AbsolutePath(\"/\"),\n                    ),\n                    defaultLocalization: nil,\n                    supportedPlatforms: [],\n                    dependencies: [],\n                    enabledTraits: Set(),\n                    modules: IdentifiableSet([]),\n                    products: [],\n                    registryMetadata: nil,\n                    platformVersionProvider: .init(implementation: .minimumDeploymentTargetDefault),\n                )\n            }\n            let moduleGraph = try ModulesGraph(\n                rootPackages: rootPackages,\n                packages: IdentifiableSet([ResolvedPackage]()),\n                dependencies: [],\n                binaryArtifacts: [:],\n            )\n\n            // WHEN we get the REPL product name from the module grapen\n            let actual = try moduleGraph.getReplProductName()\n\n            // THEN we expect it to match the root package ID with a REPL suffix\n            #expect(actual == \"package_0\\(Product.replProductSuffix)\")\n        }\n    }\n\n    @Test(\n        .IssueWindowsPathTestsFailures,\n        .disabled(\"Requires swift-testing bug fix https://github.com/swiftlang/swift-testing/pull/1441\"),\n    )\n    func basic() throws {\n        try withKnownIssue {\n            let fs = InMemoryFileSystem(\n                emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n                \"/Foo/Sources/Foo/source.swift\",\n                \"/Foo/Sources/FooDep/source.swift\",\n                \"/Foo/Tests/FooTests/source.swift\",\n                \"/Bar/source.swift\",\n                \"/Baz/Sources/Baz/source.swift\",\n                \"/Baz/Tests/BazTests/source.swift\"\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let g = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [\n                    Manifest.createFileSystemManifest(\n                        displayName: \"Foo\",\n                        path: \"/Foo\",\n                        products: [\n                            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"Foo\", dependencies: [\"FooDep\"]),\n                            TargetDescription(name: \"FooDep\", dependencies: []),\n                        ]\n                    ),\n                    Manifest.createRootManifest(\n                        displayName: \"Bar\",\n                        path: \"/Bar\",\n                        dependencies: [\n                            .localSourceControl(path: \"/Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        ],\n                        products: [\n                            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"Bar\", dependencies: [\"Foo\"], path: \"./\"),\n                        ]\n                    ),\n                    Manifest.createRootManifest(\n                        displayName: \"Baz\",\n                        path: \"/Baz\",\n                        dependencies: [\n                            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"Baz\", dependencies: [\"Bar\"]),\n                            TargetDescription(name: \"BazTests\", dependencies: [\"Baz\"], type: .test),\n                        ]\n                    ),\n                ],\n                observabilityScope: observability.topScope\n            )\n\n            expectNoDiagnostics(observability.diagnostics)\n            try PackageGraphTester(g) { result in\n                result.check(packages: \"Bar\", \"Foo\", \"Baz\")\n                result.check(modules: \"Bar\", \"Foo\", \"Baz\", \"FooDep\")\n                result.check(testModules: \"BazTests\")\n                try result.checkTarget(\"Foo\") { result in result.check(dependencies: \"FooDep\") }\n                try result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Foo\") }\n                try result.checkTarget(\"Baz\") { result in result.check(dependencies: \"Bar\") }\n            }\n\n            let fooPackage = try #require(g.package(for: .plain(\"Foo\")))\n            let fooTarget = try #require(g.module(for: \"Foo\"))\n            let fooDepTarget = try #require(g.module(for: \"FooDep\"))\n            #expect(g.package(for: fooTarget)?.id == fooPackage.id)\n            #expect(g.package(for: fooDepTarget)?.id == fooPackage.id)\n            let barPackage = try #require(g.package(for: .plain(\"Bar\")))\n            let barTarget = try #require(g.module(for: \"Bar\"))\n            #expect(g.package(for: barTarget)?.id == barPackage.id)\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test\n    func productDependencies() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/Foo/source.swift\",\n            \"/Bar/Source/Bar/source.swift\",\n            \"/Bar/Source/CBar/module.modulemap\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let g = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\", \"CBar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                        ProductDescription(name: \"CBar\", type: .library(.automatic), targets: [\"CBar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\", dependencies: [\"CBar\"]),\n                        TargetDescription(name: \"CBar\", type: .system),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n        try PackageGraphTester(g) { result in\n            result.check(packages: \"Bar\", \"Foo\")\n            result.check(modules: \"Bar\", \"CBar\", \"Foo\")\n            try result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Bar\", \"CBar\") }\n            try result.checkTarget(\"Bar\") { result in result.check(dependencies: \"CBar\") }\n        }\n    }\n\n    @Test\n    func cycle() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n            \"/Bar/Sources/Bar/source.swift\",\n            \"/Baz/Sources/Baz/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Baz\",\n                    path: \"/Baz\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Baz\", type: .library(.automatic), targets: [\"Baz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Baz\", dependencies: [\"Bar\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"cyclic dependency between packages Foo -> Bar -> Baz -> Bar requires tools-version 6.0 or later\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func localTargetCycle() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n            \"/Foo/Sources/Bar/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                        TargetDescription(name: \"Bar\", dependencies: [\"Foo\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"cyclic dependency declaration found: Bar -> Foo -> Bar\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func dependencyCycleWithoutTargetCycleV5() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n            \"/Bar/Sources/Bar/source.swift\",\n            \"/Bar/Sources/Baz/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_10,\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                        ProductDescription(name: \"Baz\", type: .library(.automatic), targets: [\"Baz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                        TargetDescription(name: \"Baz\", dependencies: [\"Foo\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"cyclic dependency between packages Foo -> Bar -> Foo requires tools-version 6.0 or later\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func dependencyCycleWithoutTargetCycle() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/A/Sources/A/source.swift\",\n            \"/B/Sources/B/source.swift\",\n            \"/C/Sources/C/source.swift\"\n        )\n\n        func testDependencyCycleDetection(rootToolsVersion: ToolsVersion) throws -> [Diagnostic] {\n            let observability = ObservabilitySystem.makeForTesting()\n            let _ = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [\n                    Manifest.createRootManifest(\n                        displayName: \"A\",\n                        path: \"/A\",\n                        toolsVersion: rootToolsVersion,\n                        dependencies: [\n                            .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        ],\n                        products: [\n                            ProductDescription(name: \"A\", type: .library(.automatic), targets: [\"A\"]),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"A\", dependencies: [\"B\"]),\n                        ]\n                    ),\n                    Manifest.createFileSystemManifest(\n                        displayName: \"B\",\n                        path: \"/B\",\n                        dependencies: [\n                            .localSourceControl(path: \"/C\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        ],\n                        products: [\n                            ProductDescription(name: \"B\", type: .library(.automatic), targets: [\"B\"]),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"B\"),\n                        ]\n                    ),\n                    Manifest.createFileSystemManifest(\n                        displayName: \"C\",\n                        path: \"/C\",\n                        dependencies: [\n                            .localSourceControl(path: \"/A\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        ],\n                        products: [\n                            ProductDescription(name: \"C\", type: .library(.automatic), targets: [\"C\"]),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"C\"),\n                        ]\n                    ),\n                ],\n                observabilityScope: observability.topScope\n            )\n            return observability.diagnostics\n        }\n\n        try expectDiagnostics(testDependencyCycleDetection(rootToolsVersion: .v5)) { result in\n            result.check(\n                diagnostic: \"cyclic dependency between packages A -> B -> C -> A requires tools-version 6.0 or later\",\n                severity: .error\n            )\n        }\n\n        try expectNoDiagnostics(testDependencyCycleDetection(rootToolsVersion: .v6_0))\n    }\n\n    @Test\n    func dependencyCycleWithoutTargetCycleV6() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n            \"/Bar/Sources/Bar/source.swift\",\n            \"/Bar/Sources/Baz/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v6_0,\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                        ProductDescription(name: \"Baz\", type: .library(.automatic), targets: [\"Baz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                        TargetDescription(name: \"Baz\", dependencies: [\"Foo\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n        PackageGraphTester(graph) { result in\n            result.check(packages: \"Foo\", \"Bar\")\n            result.check(modules: \"Bar\", \"Baz\", \"Foo\")\n        }\n    }\n\n    @Test\n    func libraryInvalidDependencyOnTestTarget() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/Foo.swift\",\n            \"/Foo/Tests/FooTest/FooTest.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v6_0,\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"FooTest\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"FooTest\"]),\n                        TargetDescription(name: \"FooTest\", type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"Invalid dependency: 'Foo' cannot depend on test target dependency 'FooTest'. Only test targets can depend on other test targets\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func executableInvalidDependencyOnTestTarget() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/main.swift\",\n            \"/Foo/Tests/FooTest/FooTest.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v6_0,\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"FooTest\"], type: .executable),\n                        TargetDescription(name: \"FooTest\", type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"Invalid dependency: 'Foo' cannot depend on test target dependency 'FooTest'. Only test targets can depend on other test targets\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func pluginInvalidDependencyOnTestTarget() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Plugins/Foo/main.swift\",\n            \"/Foo/Tests/FooTest/FooTest.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v6_0,\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\",\n                            dependencies: [\"FooTest\"],\n                            type: .plugin,\n                            pluginCapability: .buildTool\n                        ),\n                        TargetDescription(name: \"FooTest\", type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"Invalid dependency: 'Foo' cannot depend on test target dependency 'FooTest'. Only test targets can depend on other test targets\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func macroInvalidDependencyOnTestTarget() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/main.swift\",\n            \"/Foo/Tests/FooTest/FooTest.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v6_0,\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\",\n                            dependencies: [\"FooTest\"],\n                            type: .macro\n                        ),\n                        TargetDescription(name: \"FooTest\", type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"Invalid dependency: 'Foo' cannot depend on test target dependency 'FooTest'. Only test targets can depend on other test targets\",\n                severity: .error\n            )\n        }\n    }\n\n\n    @Test\n    func validDependencyOnTestTarget() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Tests/Foo/Foo.swift\",\n            \"/Foo/Tests/FooTest/FooTest.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v6_0,\n                    products: [\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"FooTest\"], type: .test),\n                        TargetDescription(name: \"FooTest\", type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n    }\n\n    // Make sure there is no error when we reference Test targets in a package and then\n    // use it as a dependency to another package. SR-2353\n    @Test\n    func testTargetDeclInExternalPackage() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n            \"/Foo/Tests/FooTests/source.swift\",\n            \"/Bar/Sources/Bar/source.swift\",\n            \"/Bar/Tests/BarTests/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let g = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\", dependencies: [\"Foo\"]),\n                        TargetDescription(name: \"BarTests\", dependencies: [\"Bar\"], type: .test),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                        TargetDescription(name: \"FooTests\", dependencies: [\"Foo\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n        PackageGraphTester(g) { result in\n            result.check(packages: \"Bar\", \"Foo\")\n            result.check(modules: \"Bar\", \"Foo\")\n            result.check(testModules: \"BarTests\")\n        }\n    }\n\n    @Test\n    func targetPackageAccessParam() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/libPkg/Sources/ExampleApp/main.swift\",\n            \"/libPkg/Sources/MainLib/file.swift\",\n            \"/libPkg/Sources/Core/file.swift\",\n            \"/libPkg/Tests/MainLibTests/file.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let g = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"libpkg\",\n                    path: \"/libPkg\",\n                    toolsVersion: .vNext,\n                    products: [\n                        ProductDescription(name: \"ExampleApp\", type: .executable, targets: [\"ExampleApp\"]),\n                        ProductDescription(name: \"Lib\", type: .library(.automatic), targets: [\"MainLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"ExampleApp\",\n                            dependencies: [\"MainLib\"],\n                            type: .executable,\n                            packageAccess: false\n                        ),\n                        TargetDescription(name: \"MainLib\", dependencies: [\"Core\"], packageAccess: true),\n                        TargetDescription(name: \"Core\"),\n                        TargetDescription(\n                            name: \"MainLibTests\",\n                            dependencies: [\"MainLib\"],\n                            type: .test,\n                            packageAccess: true\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n        try PackageGraphTester(g) { result in\n            result.check(modules: \"ExampleApp\", \"MainLib\", \"Core\")\n            result.check(testModules: \"MainLibTests\")\n            try result.checkTarget(\"MainLib\") { result in result.check(dependencies: \"Core\") }\n            try result.checkTarget(\"MainLibTests\") { result in result.check(dependencies: \"MainLib\") }\n            try result.checkTarget(\"ExampleApp\") { result in result.check(dependencies: \"MainLib\") }\n        }\n    }\n\n    @Test\n    func duplicateModules() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n            \"/Foo/Sources/Bar/source.swift\",\n            \"/Bar/Sources/Bar/source.swift\",\n            \"/Bar/Sources/Baz/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\"),\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                        TargetDescription(name: \"Baz\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"multiple packages ('bar', 'foo') declare targets with a conflicting name: 'Bar’; target names need to be unique across the package graph\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func multipleDuplicateModules() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Fourth/Sources/First/source.swift\",\n            \"/Third/Sources/First/source.swift\",\n            \"/Second/Sources/First/source.swift\",\n            \"/First/Sources/First/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"Fourth\",\n                    path: \"/Fourth\",\n                    products: [\n                        ProductDescription(name: \"Fourth\", type: .library(.automatic), targets: [\"First\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"First\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Third\",\n                    path: \"/Third\",\n                    products: [\n                        ProductDescription(name: \"Third\", type: .library(.automatic), targets: [\"First\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"First\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Second\",\n                    path: \"/Second\",\n                    products: [\n                        ProductDescription(name: \"Second\", type: .library(.automatic), targets: [\"First\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"First\"),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"First\",\n                    path: \"/First\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Second\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/Third\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/Fourth\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"First\", dependencies: [\"Second\", \"Third\", \"Fourth\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"multiple packages ('first', 'fourth', 'second', 'third') declare targets with a conflicting name: 'First’; target names need to be unique across the package graph\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func severalDuplicateModules() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Fourth/Sources/Fourth/source.swift\",\n            \"/Fourth/Sources/Bar/source.swift\",\n            \"/Third/Sources/Third/source.swift\",\n            \"/Third/Sources/Bar/source.swift\",\n            \"/Second/Sources/Second/source.swift\",\n            \"/Second/Sources/Foo/source.swift\",\n            \"/First/Sources/First/source.swift\",\n            \"/First/Sources/Foo/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"Fourth\",\n                    path: \"/Fourth\",\n                    products: [\n                        ProductDescription(name: \"Fourth\", type: .library(.automatic), targets: [\"Fourth\", \"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Fourth\"),\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Third\",\n                    path: \"/Third\",\n                    products: [\n                        ProductDescription(name: \"Third\", type: .library(.automatic), targets: [\"Third\", \"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Third\"),\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Second\",\n                    path: \"/Second\",\n                    products: [\n                        ProductDescription(name: \"Second\", type: .library(.automatic), targets: [\"Second\", \"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Second\"),\n                        TargetDescription(name: \"Foo\"),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"First\",\n                    path: \"/First\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Second\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/Third\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/Fourth\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"First\", type: .library(.automatic), targets: [\"First\", \"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"First\"),\n                        TargetDescription(name: \"Foo\", dependencies: [\"Second\", \"Third\", \"Fourth\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.checkUnordered(\n                diagnostic: \"multiple packages ('fourth', 'third') declare targets with a conflicting name: 'Bar’; target names need to be unique across the package graph\",\n                severity: .error\n            )\n            result.checkUnordered(\n                diagnostic: \"multiple packages ('first', 'second') declare targets with a conflicting name: 'Foo’; target names need to be unique across the package graph\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func nestedDuplicateModules() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Fourth/Sources/First/source.swift\",\n            \"/Fourth/Sources/Fourth/source.swift\",\n            \"/Third/Sources/Third/source.swift\",\n            \"/Second/Sources/Second/source.swift\",\n            \"/First/Sources/First/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"Fourth\",\n                    path: \"/Fourth\",\n                    products: [\n                        ProductDescription(name: \"Fourth\", type: .library(.automatic), targets: [\"Fourth\", \"First\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Fourth\"),\n                        TargetDescription(name: \"First\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Third\",\n                    path: \"/Third\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Fourth\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Third\", type: .library(.automatic), targets: [\"Third\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Third\", dependencies: [\"Fourth\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Second\",\n                    path: \"/Second\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Third\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"Second\", type: .library(.automatic), targets: [\"Second\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Second\", dependencies: [\"Third\"]),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"First\",\n                    path: \"/First\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Second\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"First\", type: .library(.automatic), targets: [\"First\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"First\", dependencies: [\"Second\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"multiple packages ('first', 'fourth') declare targets with a conflicting name: 'First’; target names need to be unique across the package graph\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func potentiallyDuplicatePackages() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/First/Sources/Foo/source.swift\",\n            \"/First/Sources/Bar/source.swift\",\n            \"/Second/Sources/Foo/source.swift\",\n            \"/Second/Sources/Bar/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"First\",\n                    path: \"/First\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Second\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"First\", type: .library(.automatic), targets: [\"Foo\", \"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\"),\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Second\",\n                    path: \"/Second\",\n                    products: [\n                        ProductDescription(name: \"Second\", type: .library(.automatic), targets: [\"Foo\", \"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\"),\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: .contains(\"multiple similar targets 'Bar', 'Foo' appear in package 'first' and 'second'\"),\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func potentiallyDuplicatePackagesManyTargets() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/First/Sources/Foo/source.swift\",\n            \"/First/Sources/Bar/source.swift\",\n            \"/First/Sources/Baz/source.swift\",\n            \"/First/Sources/Qux/source.swift\",\n            \"/First/Sources/Quux/source.swift\",\n            \"/Second/Sources/Foo/source.swift\",\n            \"/Second/Sources/Bar/source.swift\",\n            \"/Second/Sources/Baz/source.swift\",\n            \"/Second/Sources/Qux/source.swift\",\n            \"/Second/Sources/Quux/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"First\",\n                    path: \"/First\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Second\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"First\",\n                            type: .library(.automatic),\n                            targets: [\"Foo\", \"Bar\", \"Baz\", \"Qux\", \"Quux\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\"),\n                        TargetDescription(name: \"Bar\"),\n                        TargetDescription(name: \"Baz\"),\n                        TargetDescription(name: \"Qux\"),\n                        TargetDescription(name: \"Quux\"),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Second\",\n                    path: \"/Second\",\n                    products: [\n                        ProductDescription(\n                            name: \"Second\",\n                            type: .library(.automatic),\n                            targets: [\"Foo\", \"Bar\", \"Baz\", \"Qux\", \"Quux\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\"),\n                        TargetDescription(name: \"Bar\"),\n                        TargetDescription(name: \"Baz\"),\n                        TargetDescription(name: \"Qux\"),\n                        TargetDescription(name: \"Quux\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: .contains(\n                    \"multiple similar targets 'Bar', 'Baz', 'Foo' and 2 others appear in package 'first' and 'second'\"\n                ),\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func potentiallyDuplicatePackagesRegistrySCM() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/First/Sources/Foo/source.swift\",\n            \"/First/Sources/Bar/source.swift\",\n            \"/Second/Sources/Foo/source.swift\",\n            \"/Second/Sources/Bar/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"First\",\n                    path: \"/First\",\n                    dependencies: [\n                        .registry(identity: \"test.second\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"First\", type: .library(.automatic), targets: [\"Foo\", \"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\"),\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n                Manifest.createRegistryManifest(\n                    displayName: \"Second\",\n                    identity: .plain(\"test.second\"),\n                    path: \"/Second\",\n                    products: [\n                        ProductDescription(name: \"Second\", type: .library(.automatic), targets: [\"Foo\", \"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\"),\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: .contains(\n                    \"multiple similar targets 'Bar', 'Foo' appear in registry package 'test.second' and source control package 'first'\"\n                ),\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func emptyDependency() throws {\n        let Bar: AbsolutePath = \"/Bar\"\n\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            Bar.appending(components: \"Sources\", \"Bar\", \"source.txt\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: .init(validating: Bar.pathString),\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: .contains(\"Source files for target Bar should be located under 'Sources/Bar'\"),\n                severity: .warning\n            )\n            result.check(\n                diagnostic: \"target 'Bar' referenced in product 'Bar' is empty\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func targetOnlyContainingHeaders() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Bar/Sources/Bar/include/bar.h\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let g = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n        PackageGraphTester(g) { result in\n            result.check(packages: \"Bar\")\n            result.check(modules: \"Bar\")\n        }\n    }\n\n    @Test\n    func productDependencyNotFound() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/FooTarget/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    targets: [\n                        TargetDescription(name: \"FooTarget\", dependencies: [\"Barx\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Barx' required by package 'foo' target 'FooTarget' not found.\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func byNameDependencyWithSimilarTargetName() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/railroad/Sources/Rail/Rail.swift\",\n            \"/railroad/Sources/Spike/Spike.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"railroad\",\n                    path: \"/railroad\",\n                    targets: [\n                        TargetDescription(name: \"Rail\", dependencies: [\"Spoke\"]),\n                        TargetDescription(name: \"Spike\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Spoke' required by package 'railroad' target 'Rail' not found. Did you mean 'Spike'?\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func byNameDependencyWithSimilarProductName() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/weather/Sources/Rain/Rain.swift\",\n            \"/forecast/Sources/Forecast/Forecast.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"weather\",\n                    path: \"/weather\",\n                    products: [\n                        ProductDescription(name: \"Rain\", type: .library(.automatic), targets: [\"Rain\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Rain\"),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"forecast\",\n                    path: \"/forecast\",\n                    dependencies: [.fileSystem(path: \"/weather\")],\n                    targets: [\n                        TargetDescription(name: \"Forecast\", dependencies: [\"Rail\"]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Rail' required by package 'forecast' target 'Forecast' not found. Did you mean '.product(name: \\\"Rain\\\", package: \\\"weather\\\")'?\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func productDependencyWithSimilarNamesFromMultiplePackages() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/flavors/Sources/Bitter/Bitter.swift\",\n            \"/farm/Sources/Butter/Butter.swift\",\n            \"/grocery/Sources/Grocery/Grocery.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"flavors\",\n                    path: \"/flavors\",\n                    products: [ProductDescription(name: \"Bitter\", type: .library(.automatic), targets: [\"Bitter\"])],\n                    targets: [\n                        TargetDescription(name: \"Bitter\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"farm\",\n                    path: \"/farm\",\n                    products: [ProductDescription(name: \"Butter\", type: .library(.automatic), targets: [\"Butter\"])],\n                    targets: [\n                        TargetDescription(name: \"Butter\"),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"grocery\",\n                    path: \"/grocery\",\n                    dependencies: [.fileSystem(path: \"/farm\"), .fileSystem(path: \"/flavors\")],\n                    targets: [\n                        TargetDescription(name: \"Grocery\", dependencies: [\n                            .product(name: \"Biter\", package: \"farm\"),\n                            .product(name: \"Bitter\", package: \"flavors\"),\n                        ]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        // We should expect matching to work only within the package we want even\n        // though there are lexically closer candidates in other packages.\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Biter' required by package 'grocery' target 'Grocery' not found in package 'farm'. Did you mean '.product(name: \\\"Butter\\\", package: \\\"farm\\\")'?\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func productDependencyWithSimilarNamesFromProductTargetsNotProducts() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/lunch/Sources/Lunch/Lunch.swift\",\n            \"/sandwich/Sources/Sandwich/Sandwich.swift\",\n            \"/sandwich/Sources/Bread/Bread.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"sandwich\",\n                    path: \"/sandwich\",\n                    products: [ProductDescription(\n                        name: \"Sandwich\",\n                        type: .library(.automatic),\n                        targets: [\"Sandwich\"]\n                    )],\n                    targets: [\n                        TargetDescription(name: \"Sandwich\", dependencies: [\"Bread\"]),\n                        TargetDescription(name: \"Bread\"),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"lunch\",\n                    path: \"/lunch\",\n                    // Depends on a product which isn't actually declared in sandwich,\n                    // but there's a target with the same name.\n                    dependencies: [.fileSystem(path: \"/sandwich\")],\n                    targets: [\n                        TargetDescription(name: \"Lunch\", dependencies: [.product(name: \"Bread\", package: \"sandwich\")]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Bread' required by package 'lunch' target 'Lunch' not found in package 'sandwich'.\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func productDependencyWithSimilarNamesFromLocalTargetsNotPackageProducts() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/gauges/Sources/Chart/Chart.swift\",\n            \"/gauges/Sources/Value/Value.swift\",\n            \"/controls/Sources/Valve/Valve.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createFileSystemManifest(\n                    displayName: \"controls\",\n                    path: \"/controls\",\n                    products: [ProductDescription(name: \"Valve\", type: .library(.automatic), targets: [\"Valve\"])],\n                    targets: [\n                        TargetDescription(name: \"Valve\"),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"gauges\",\n                    path: \"/gauges\",\n                    // Target dependency should show the local target dependency, even though\n                    // there's a lexically-close product name in a different package.\n                    dependencies: [.fileSystem(path: \"/controls\")],\n                    targets: [\n                        TargetDescription(name: \"Chart\", dependencies: [\n                            \"Valv\",\n                            .product(name: \"Valve\", package: \"controls\")]),\n                        TargetDescription(name: \"Value\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Valv' required by package 'gauges' target 'Chart' not found. Did you mean 'Value'?\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func productDependencyWithNonSimilarName() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Qux\"]),\n                    ]\n                ),\n                Manifest.createRootManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Qux' required by package 'foo' target 'Foo' not found.\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func productDependencyDeclaredInSamePackage() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/FooTarget/src.swift\",\n            \"/Foo/Tests/FooTests/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"FooTarget\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"FooTarget\", dependencies: []),\n                        TargetDescription(name: \"FooTests\", dependencies: [\"Foo\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Foo' is declared in the same package 'foo' and can't be used as a dependency for target 'FooTests'.\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func executableTargetDependency() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/XYZ/Sources/XYZ/main.swift\",\n            \"/XYZ/Tests/XYZTests/tests.swift\"\n        )\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"XYZ\",\n                    path: \"/XYZ\",\n                    targets: [\n                        TargetDescription(name: \"XYZ\", dependencies: [], type: .executable),\n                        TargetDescription(name: \"XYZTests\", dependencies: [\"XYZ\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        try expectDiagnostics(observability.diagnostics) { _ in }\n    }\n\n    @Test\n    func sameProductAndTargetNames() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/src.swift\",\n            \"/Foo/Tests/FooTests/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    products: [\n                        ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: []),\n                        TargetDescription(name: \"FooTests\", dependencies: [\"Foo\"], type: .test),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        try expectDiagnostics(observability.diagnostics) { _ in }\n    }\n\n    @Test\n    func productDependencyNotFoundWithName() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/FooTarget/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    targets: [\n                        TargetDescription(name: \"FooTarget\", dependencies: [.product(name: \"Barx\", package: \"Bar\")]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Barx' required by package 'foo' target 'FooTarget' not found in package 'Bar'.\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func productDependencyNotFoundWithNoName() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/FooTarget/foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    targets: [\n                        TargetDescription(name: \"FooTarget\", dependencies: [.product(name: \"Barx\")]),\n                    ],\n                    traits: []\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'Barx' required by package 'foo' target 'FooTarget' not found.\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func productDependencyNotFoundImprovedDiagnostic() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/BarLib/bar.swift\",\n            \"/BizPath/Sources/Biz/biz.swift\",\n            \"/FizPath/Sources/FizLib/fiz.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .branch(\"main\")),\n                        .localSourceControl(path: \"/BizPath\", requirement: .exact(\"1.2.3\")),\n                        .localSourceControl(path: \"/FizPath\", requirement: .upToNextMajor(from: \"1.1.2\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"BarLib\", \"Biz\", \"FizLib\"]),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    products: [\n                        ProductDescription(name: \"BarLib\", type: .library(.automatic), targets: [\"BarLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"BarLib\"),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Biz\",\n                    path: \"/BizPath\",\n                    version: \"1.2.3\",\n                    products: [\n                        ProductDescription(name: \"Biz\", type: .library(.automatic), targets: [\"Biz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Biz\"),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Fiz\",\n                    path: \"/FizPath\",\n                    version: \"1.2.3\",\n                    products: [\n                        ProductDescription(name: \"FizLib\", type: .library(.automatic), targets: [\"FizLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"FizLib\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.checkUnordered(\n                diagnostic: \"\"\"\n                dependency 'BarLib' in target 'Foo' requires explicit declaration; reference the package in the target dependency with '.product(name: \"BarLib\", package: \"Bar\")'\n                \"\"\",\n                severity: .error\n            )\n            result.checkUnordered(\n                diagnostic: \"\"\"\n                dependency 'Biz' in target 'Foo' requires explicit declaration; reference the package in the target dependency with '.product(name: \"Biz\", package: \"BizPath\")'\n                \"\"\",\n                severity: .error\n            )\n            result.checkUnordered(\n                diagnostic: \"\"\"\n                dependency 'FizLib' in target 'Foo' requires explicit declaration; reference the package in the target dependency with '.product(name: \"FizLib\", package: \"FizPath\")'\n                \"\"\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func packageNameValidationInProductTargetDependency() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    dependencies: [\n                        .localSourceControl(deprecatedName: \"UnBar\", path: \"/Bar\", requirement: .branch(\"main\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [.product(name: \"BarProduct\", package: \"UnBar\")]),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"UnBar\",\n                    path: \"/Bar\",\n                    products: [\n                        ProductDescription(name: \"BarProduct\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        // Expect no diagnostics.\n        try expectDiagnostics(observability.diagnostics) { _ in }\n    }\n\n    @Test\n    func unusedDependency() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\",\n            \"/Baz/Sources/Baz/baz.swift\",\n            \"/Biz/Sources/Biz/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/Biz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"BarLibrary\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Biz\",\n                    path: \"/Biz\",\n                    products: [\n                        ProductDescription(name: \"biz\", type: .executable, targets: [\"Biz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Biz\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    products: [\n                        ProductDescription(name: \"BarLibrary\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Baz\",\n                    path: \"/Baz\",\n                    products: [\n                        ProductDescription(name: \"BazLibrary\", type: .library(.automatic), targets: [\"Baz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Baz\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            let diagnostic = try #require(result.check(diagnostic: \"dependency 'baz' is not used by any target\", severity: .warning))\n            let metadata = try #require(diagnostic.metadata)\n            #expect(metadata.packageIdentity == \"foo\")\n            let packageKind = try #require(metadata.packageKind)\n            #expect(packageKind.isRoot)\n#if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n            result.check(diagnostic: \"dependency 'biz' is not used by any target\", severity: .warning)\n#endif\n        }\n    }\n\n    @Test\n    func unusedDependency2() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/module.modulemap\",\n            \"/Bar/Sources/Bar/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\"\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        // We don't expect any unused dependency diagnostics from a system module package.\n        try expectDiagnostics(observability.diagnostics) { _ in }\n    }\n\n    @Test\n    func unusedDependency_WhenPruneDependenciesEnabled() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        // Baz is unused by all targets in this package, and thus should be omitted\n                        // with `pruneDependencies` enabled.\n                            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Bar\",\n                            dependencies: [\n                                .product(\n                                    name: \"Foo\",\n                                    package: \"Foo\",\n                                    // This target dependency is guarded by Trait2; since Trait2\n                                    // is not enabled by default, the package dependency `Foo` will\n                                    // be omitted since `pruneDependencies` is enabled.\n                                    condition: .init(traits: [\"Trait2\"])\n                                ),\n                            ]\n                        ),\n                    ],\n                    traits: [.init(name: \"default\", enabledTraits: [\"Trait1\"]), \"Trait1\", \"Trait2\"],\n                    pruneDependencies: true\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    products: [\n                        .init(name: \"FooLibrary\", type: .library(.automatic), targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Foo\",\n                            dependencies: []\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Baz\",\n                    path: \"/Baz\",\n                    products: [\n                        .init(name: \"BazLibrary\", type: .library(.automatic), targets: [\"Baz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Baz\",\n                            dependencies: []\n                        ),\n                    ]\n\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n    }\n\n    @Test\n    func duplicateInterPackageTargetNames() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Start/Sources/Foo/foo.swift\",\n            \"/Start/Sources/Bar/bar.swift\",\n            \"/Dep1/Sources/Baz/baz.swift\",\n            \"/Dep2/Sources/Foo/foo.swift\",\n            \"/Dep2/Sources/Bam/bam.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Start\",\n                    path: \"/Start\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Dep1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"BazLibrary\"]),\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Dep1\",\n                    path: \"/Dep1\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Dep2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [\n                        ProductDescription(name: \"BazLibrary\", type: .library(.automatic), targets: [\"Baz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Baz\", dependencies: [\"FooLibrary\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Dep2\",\n                    path: \"/Dep2\",\n                    products: [\n                        ProductDescription(name: \"FooLibrary\", type: .library(.automatic), targets: [\"Foo\"]),\n                        ProductDescription(name: \"BamLibrary\", type: .library(.automatic), targets: [\"Bam\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\"),\n                        TargetDescription(name: \"Bam\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"multiple packages ('dep2', 'start') declare targets with a conflicting name: 'Foo’; target names need to be unique across the package graph\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func duplicateProducts() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\",\n            \"/Baz/Sources/Baz/baz.swift\"\n        )\n        let fooPkg: AbsolutePath = \"/Foo\"\n        let barPkg: AbsolutePath = \"/Bar\"\n        let bazPkg: AbsolutePath = \"/Baz\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        #expect {\n            try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [\n                    Manifest.createRootManifest(\n                        displayName: \"Foo\",\n                        path: fooPkg,\n                        dependencies: [\n                            .localSourceControl(path: barPkg, requirement: .upToNextMajor(from: \"1.0.0\")),\n                            .localSourceControl(path: bazPkg, requirement: .upToNextMajor(from: \"1.0.0\")),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                        ]\n                    ),\n                    Manifest.createFileSystemManifest(\n                        displayName: \"Bar\",\n                        path: barPkg,\n                        products: [\n                            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"Bar\"),\n                        ]\n                    ),\n                    Manifest.createFileSystemManifest(\n                        displayName: \"Baz\",\n                        path: bazPkg,\n                        products: [\n                            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Baz\"]),\n                        ],\n                        targets: [\n                            TargetDescription(name: \"Baz\"),\n                        ]\n                    ),\n                ],\n                observabilityScope: observability.topScope\n            )\n        } throws: { error in\n            let error = try #require(error as? PackageGraphError)\n            return error.description == \"multiple packages (\\'bar\\' (at '\\(barPkg)'), \\'baz\\' (at '\\(bazPkg)')) declare products with a conflicting name: \\'Bar’; product names need to be unique across the package graph\"\n        }\n    }\n\n    func loadUnsafeModulesGraph(toolsVersion: ToolsVersion) throws -> TestingObservability {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Foo/Sources/Foo2/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\",\n            \"/Bar/Sources/Bar2/bar.swift\",\n            \"/Bar/Sources/Bar3/bar.swift\",\n            \"/Bar/Sources/TransitiveBar/bar.swift\",\n            \"<end>\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                        TargetDescription(name: \"Foo2\", dependencies: [\"TransitiveBar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: toolsVersion,\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\", \"Bar2\", \"Bar3\"]),\n                        ProductDescription(\n                            name: \"TransitiveBar\",\n                            type: .library(.automatic),\n                            targets: [\"TransitiveBar\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Bar\",\n                            settings: [\n                                .init(tool: .swift, kind: .unsafeFlags([\"-Icfoo\", \"-L\", \"cbar\"])),\n                                .init(tool: .c, kind: .unsafeFlags([\"-Icfoo\", \"-L\", \"cbar\"])),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Bar2\",\n                            settings: [\n                                .init(tool: .swift, kind: .unsafeFlags([\"-Icfoo\", \"-L\", \"cbar\"])),\n                                .init(tool: .c, kind: .unsafeFlags([\"-Icfoo\", \"-L\", \"cbar\"])),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Bar3\",\n                            settings: [\n                                .init(tool: .swift, kind: .unsafeFlags([])),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"TransitiveBar\",\n                            dependencies: [\"Bar2\"]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        return observability\n    }\n\n    @Test\n    func unsafeFlagsDisabled() throws {\n        let observability = try loadUnsafeModulesGraph(toolsVersion: .v6_2)\n\n        // We have turned off the unsafe flags check\n        #expect(observability.diagnostics.count == 0)\n    }\n\n\n    @Test\n    func testUnsafeFlagsEnabled() throws {\n        let observability = try loadUnsafeModulesGraph(toolsVersion: .v6_1)\n\n        #expect(observability.diagnostics.count == 3)\n        try expectDiagnostics(observability.diagnostics) { result in\n            var expectedMetadata = ObservabilityMetadata()\n            expectedMetadata.moduleName = \"Foo2\"\n            let diagnostic1 = try #require(result.checkUnordered(\n                diagnostic: .contains(\"the target 'Bar2' in product 'TransitiveBar' contains unsafe build flags\"),\n                severity: .error\n            ))\n            let diagnostic1_metadata = try #require(diagnostic1.metadata)\n            #expect(diagnostic1_metadata.moduleName == \"Foo2\")\n\n            let diagnostic2 = try #require(result.checkUnordered(\n                diagnostic: .contains(\"the target 'Bar' in product 'Bar' contains unsafe build flags\"),\n                severity: .error\n            ))\n            let diagnostic2_metadata = try #require(diagnostic2.metadata)\n            #expect(diagnostic2_metadata.moduleName == \"Foo\")\n\n            let diagnostic3 = try #require(result.checkUnordered(\n                diagnostic: .contains(\"the target 'Bar2' in product 'Bar' contains unsafe build flags\"),\n                severity: .error\n            ))\n            let diagnostic3_metadata = try #require(diagnostic3.metadata)\n            #expect(diagnostic3_metadata.moduleName == \"Foo\")\n        }\n    }\n\n    @Test\n    func conditionalTargetDependency() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n            \"/Foo/Sources/Bar/source.swift\",\n            \"/Foo/Sources/Baz/source.swift\",\n            \"/Biz/Sources/Biz/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .fileSystem(path: \"/Biz\"),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\n                            .target(name: \"Bar\", condition: PackageConditionDescription(\n                                platformNames: [\"linux\"],\n                                config: nil\n                            )),\n                            .byName(name: \"Baz\", condition: PackageConditionDescription(\n                                platformNames: [],\n                                config: \"debug\"\n                            )),\n                            .product(name: \"Biz\", package: \"Biz\", condition: PackageConditionDescription(\n                                platformNames: [\"watchos\", \"ios\"],\n                                config: \"release\"\n                            )),\n                        ]),\n                        TargetDescription(name: \"Bar\"),\n                        TargetDescription(name: \"Baz\"),\n                    ],\n                    traits: []\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Biz\",\n                    path: \"/Biz\",\n                    products: [\n                        ProductDescription(name: \"Biz\", type: .library(.automatic), targets: [\"Biz\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Biz\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n        try PackageGraphTester(graph) { result in\n            result.check(modules: \"Foo\", \"Bar\", \"Baz\", \"Biz\")\n            try result.checkTarget(\"Foo\") { result in\n                result.check(dependencies: \"Bar\", \"Baz\", \"Biz\")\n                try result.checkDependency(\"Bar\") { result in\n                    result.checkConditions(satisfy: .init(platform: .linux, configuration: .debug))\n                    result.checkConditions(satisfy: .init(platform: .linux, configuration: .release))\n                    result.checkConditions(dontSatisfy: .init(platform: .macOS, configuration: .release))\n                }\n                try result.checkDependency(\"Baz\") { result in\n                    result.checkConditions(satisfy: .init(platform: .watchOS, configuration: .debug))\n                    result.checkConditions(satisfy: .init(platform: .tvOS, configuration: .debug))\n                    result.checkConditions(dontSatisfy: .init(platform: .tvOS, configuration: .release))\n                }\n                try result.checkDependency(\"Biz\") { result in\n                    result.checkConditions(satisfy: .init(platform: .watchOS, configuration: .release))\n                    result.checkConditions(satisfy: .init(platform: .iOS, configuration: .release))\n                    result.checkConditions(dontSatisfy: .init(platform: .iOS, configuration: .debug))\n                    result.checkConditions(dontSatisfy: .init(platform: .macOS, configuration: .release))\n                }\n            }\n        }\n    }\n\n    @Test(\n        .requiresTargetBasedDependencyResolution,\n    )\n    func unreachableProductsSkipped() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Root/Sources/Root/Root.swift\",\n            \"/Immediate/Sources/ImmediateUsed/ImmediateUsed.swift\",\n            \"/Immediate/Sources/ImmediateUnused/ImmediateUnused.swift\",\n            \"/Transitive/Sources/TransitiveUsed/TransitiveUsed.swift\",\n            \"/Transitive/Sources/TransitiveUnused/TransitiveUnused.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Root\",\n                    path: \"/Root\",\n                    toolsVersion: .v5_2,\n                    dependencies: [\n                        .localSourceControl(path: \"/Immediate\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Root\", dependencies: [\n                            .product(name: \"ImmediateUsed\", package: \"Immediate\"),\n                        ]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Immediate\",\n                    path: \"/Immediate\",\n                    toolsVersion: .v5_2,\n                    dependencies: [\n                        .localSourceControl(\n                            path: \"/Transitive\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .localSourceControl(\n                            path: \"/Nonexistent\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"ImmediateUsed\",\n                            type: .library(.automatic),\n                            targets: [\"ImmediateUsed\"]\n                        ),\n                        ProductDescription(\n                            name: \"ImmediateUnused\",\n                            type: .library(.automatic),\n                            targets: [\"ImmediateUnused\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ImmediateUsed\", dependencies: [\n                            .product(name: \"TransitiveUsed\", package: \"Transitive\"),\n                        ]),\n                        TargetDescription(name: \"ImmediateUnused\", dependencies: [\n                            .product(name: \"TransitiveUnused\", package: \"Transitive\"),\n                            .product(name: \"Nonexistent\", package: \"Nonexistent\"),\n                        ]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Transitive\",\n                    path: \"/Transitive\",\n                    toolsVersion: .v5_2,\n                    dependencies: [\n                        .localSourceControl(\n                            path: \"/Nonexistent\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"TransitiveUsed\",\n                            type: .library(.automatic),\n                            targets: [\"TransitiveUsed\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"TransitiveUsed\"),\n                        TargetDescription(name: \"TransitiveUnused\", dependencies: [\n                            .product(name: \"Nonexistent\", package: \"Nonexistent\"),\n                        ]),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n    }\n\n    @Test\n    func resolvedPackagesStoreIsResilientAgainstDupes() throws {\n        let json = \"\"\"\n              {\n                \"version\": 1,\n                \"object\": {\n                  \"pins\": [\n                    {\n                      \"package\": \"Yams\",\n                      \"repositoryURL\": \"https://github.com/jpsim/yams\",\n                      \"state\": {\n                        \"branch\": null,\n                        \"revision\": \"b08dba4bcea978bf1ad37703a384097d3efce5af\",\n                        \"version\": \"1.0.2\"\n                      }\n                    },\n                    {\n                      \"package\": \"Yams\",\n                      \"repositoryURL\": \"https://github.com/jpsim/yams\",\n                      \"state\": {\n                        \"branch\": null,\n                        \"revision\": \"b08dba4bcea978bf1ad37703a384097d3efce5af\",\n                        \"version\": \"1.0.2\"\n                      }\n                    }\n                  ]\n                }\n              }\n        \"\"\"\n\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n        try fs.writeFileContents(packageResolvedFile, string: json)\n\n        #expect(\n            throws: StringError(\n                \"\\(packageResolvedFile) file is corrupted or malformed; fix or delete the file to continue: duplicated entry for package \\\"yams\\\"\"\n            )\n        ) {\n            _ = try ResolvedPackagesStore(\n                packageResolvedFile: packageResolvedFile,\n                workingDirectory: .root,\n                fileSystem: fs,\n                mirrors: .init()\n            )\n        }\n    }\n\n    @Test\n    func resolutionDeterminism() throws {\n        let fileSystem = InMemoryFileSystem(\n            emptyFiles: [\n                \"/A/Sources/A/A.swift\",\n                \"/B/Sources/B/B.swift\",\n                \"/C/Sources/C/C.swift\",\n                \"/D/Sources/D/D.swift\",\n                \"/E/Sources/E/E.swift\",\n                \"/F/Sources/F/F.swift\",\n            ]\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fileSystem,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"A\",\n                    path: \"/A\",\n                    dependencies: [\n                        .localSourceControl(path: \"/B\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/C\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/D\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/E\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .localSourceControl(path: \"/F\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"A\", dependencies: []),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"B\",\n                    path: \"/B\",\n                    products: [\n                        ProductDescription(name: \"B\", type: .library(.automatic), targets: [\"B\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"B\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"C\",\n                    path: \"/C\",\n                    products: [\n                        ProductDescription(name: \"C\", type: .library(.automatic), targets: [\"C\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"C\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"D\",\n                    path: \"/D\",\n                    products: [\n                        ProductDescription(name: \"D\", type: .library(.automatic), targets: [\"D\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"D\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"E\",\n                    path: \"/E\",\n                    products: [\n                        ProductDescription(name: \"E\", type: .library(.automatic), targets: [\"E\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"E\"),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"F\",\n                    path: \"/F\",\n                    products: [\n                        ProductDescription(name: \"F\", type: .library(.automatic), targets: [\"F\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"F\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: \"dependency 'b' is not used by any target\", severity: .warning)\n            result.check(diagnostic: \"dependency 'c' is not used by any target\", severity: .warning)\n            result.check(diagnostic: \"dependency 'd' is not used by any target\", severity: .warning)\n            result.check(diagnostic: \"dependency 'e' is not used by any target\", severity: .warning)\n            result.check(diagnostic: \"dependency 'f' is not used by any target\", severity: .warning)\n        }\n    }\n\n    @Test\n    func targetDependencies_Pre52() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5,\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v5,\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n    }\n\n    @Test\n    func targetDependencies_Pre52_UnknownProduct() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5,\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Unknown\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v5,\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"\"\"\n                product 'Unknown' required by package 'foo' target 'Foo' not found.\n                \"\"\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func targetDependencies_Post52_NamesAligned() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v5_2,\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        expectNoDiagnostics(observability.diagnostics)\n    }\n\n    @Test\n    func targetDependencies_Post52_UnknownProduct() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Unknown\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v5_2,\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"\"\"\n                product 'Unknown' required by package 'foo' target 'Foo' not found.\n                \"\"\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func targetDependencies_Post52_ProductPackageNoMatch() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: [\n                    .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                ],\n                targets: [\n                    TargetDescription(name: \"Foo\", dependencies: [\"ProductBar\"]),\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Bar\",\n                path: \"/Bar\",\n                toolsVersion: .v5_2,\n                products: [\n                    ProductDescription(name: \"ProductBar\", type: .library(.automatic), targets: [\"Bar\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"Bar\"),\n                ]\n            ),\n        ]\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(fileSystem: fs, manifests: manifests, observabilityScope: observability.topScope)\n            try expectDiagnostics(observability.diagnostics) { result in\n                result.check(\n                    diagnostic: \"\"\"\n                    dependency 'ProductBar' in target 'Foo' requires explicit declaration; reference the package in the target dependency with '.product(name: \"ProductBar\", package: \"Bar\")'\n                    \"\"\",\n                    severity: .error\n                )\n            }\n        }\n\n        // fixit\n\n        do {\n            let fixedManifests = try [\n                manifests[0].withTargets([\n                    TargetDescription(name: \"Foo\", dependencies: [.product(name: \"ProductBar\", package: \"Bar\")]),\n                ]),\n                manifests[1], // same\n            ]\n\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: fixedManifests,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    // TODO: remove this when we remove explicit dependency name\n    @Test\n    func targetDependencies_Post52_ProductPackageNoMatch_DependencyExplicitName() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: [\n                    .localSourceControl(\n                        deprecatedName: \"Bar\",\n                        path: \"/Bar\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    ),\n                ],\n                targets: [\n                    TargetDescription(name: \"Foo\", dependencies: [\"ProductBar\"]),\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Bar\",\n                path: \"/Bar\",\n                toolsVersion: .v5_2,\n                products: [\n                    ProductDescription(name: \"ProductBar\", type: .library(.automatic), targets: [\"Bar\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"Bar\"),\n                ]\n            ),\n        ]\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(fileSystem: fs, manifests: manifests, observabilityScope: observability.topScope)\n            try expectDiagnostics(observability.diagnostics) { result in\n                result.check(\n                    diagnostic: \"\"\"\n                    dependency 'ProductBar' in target 'Foo' requires explicit declaration; reference the package in the target dependency with '.product(name: \"ProductBar\", package: \"Bar\")'\n                    \"\"\",\n                    severity: .error\n                )\n            }\n        }\n\n        // fixit\n\n        do {\n            let fixedManifests = try [\n                manifests[0].withTargets([\n                    TargetDescription(name: \"Foo\", dependencies: [.product(name: \"ProductBar\", package: \"Bar\")]),\n                ]),\n                manifests[1], // same\n            ]\n\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: fixedManifests,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    @Test\n    func targetDependencies_Post52_LocationAndManifestNameDontMatch() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Some-Bar/Sources/Bar/bar.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: [\n                    .localSourceControl(path: \"/Some-Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                ],\n                targets: [\n                    TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Bar\",\n                path: \"/Some-Bar\",\n                toolsVersion: .v5_2,\n                products: [\n                    ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"Bar\"),\n                ]\n            ),\n        ]\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(fileSystem: fs, manifests: manifests, observabilityScope: observability.topScope)\n            try expectDiagnostics(observability.diagnostics) { result in\n                result.check(\n                    diagnostic: \"\"\"\n                    dependency 'Bar' in target 'Foo' requires explicit declaration; reference the package in the target dependency with '.product(name: \"Bar\", package: \"Some-Bar\")'\n                    \"\"\",\n                    severity: .error\n                )\n            }\n        }\n\n        // fixit\n\n        do {\n            let fixedManifests = try [\n                manifests[0].withTargets([\n                    TargetDescription(name: \"Foo\", dependencies: [.product(name: \"Bar\", package: \"Some-Bar\")]),\n                ]),\n                manifests[1], // same\n            ]\n\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: fixedManifests,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    @Test\n    func targetDependencies_Post52_LocationAndManifestNameDontMatch_ProductPackageDontMatch() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Some-Bar/Sources/Bar/bar.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: [\n                    .localSourceControl(path: \"/Some-Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                ],\n                targets: [\n                    TargetDescription(name: \"Foo\", dependencies: [\"ProductBar\"]),\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Bar\",\n                path: \"/Some-Bar\",\n                toolsVersion: .v5_2,\n                products: [\n                    ProductDescription(name: \"ProductBar\", type: .library(.automatic), targets: [\"Bar\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"Bar\"),\n                ]\n            ),\n        ]\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(fileSystem: fs, manifests: manifests, observabilityScope: observability.topScope)\n            try expectDiagnostics(observability.diagnostics) { result in\n                let diagnostic = result.check(\n                    diagnostic: \"\"\"\n                    dependency 'ProductBar' in target 'Foo' requires explicit declaration; reference the package in the target dependency with '.product(name: \"ProductBar\", package: \"Some-Bar\")'\n                    \"\"\",\n                    severity: .error\n                )\n                #expect(diagnostic?.metadata?.packageIdentity == .plain(\"foo\"))\n            }\n        }\n\n        // fix it\n\n        do {\n            let fixedManifests = try [\n                manifests[0].withTargets([\n                    TargetDescription(name: \"Foo\", dependencies: [.product(name: \"ProductBar\", package: \"Foo-Bar\")]),\n                ]),\n                manifests[1], // same\n            ]\n\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: fixedManifests,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    // test backwards compatibility 5.2 < 5.4\n    // TODO: remove this when we remove explicit dependency name\n    @Test\n    func targetDependencies_Post52_LocationAndManifestNameDontMatch_WithDependencyName() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Some-Bar/Sources/Bar/bar.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: [\n                    .localSourceControl(\n                        deprecatedName: \"Bar\",\n                        path: \"/Some-Bar\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    ),\n                ],\n                targets: [\n                    TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Bar\",\n                path: \"/Some-Bar\",\n                toolsVersion: .v5_2,\n                products: [\n                    ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"Bar\"),\n                ]\n            ),\n        ]\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(fileSystem: fs, manifests: manifests, observabilityScope: observability.topScope)\n        expectNoDiagnostics(observability.diagnostics)\n    }\n\n    // test backwards compatibility 5.2 < 5.4\n    // TODO: remove this when we remove explicit dependency name\n    @Test\n    func targetDependencies_Post52_LocationAndManifestNameDontMatch_ProductPackageDontMatch_WithDependencyName() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Some-Bar/Sources/Bar/bar.swift\"\n        )\n\n        let manifests = try [\n            Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: [\n                    .localSourceControl(\n                        deprecatedName: \"Bar\",\n                        path: \"/Some-Bar\",\n                        requirement: .upToNextMajor(from: \"1.0.0\")\n                    ),\n                ],\n                targets: [\n                    TargetDescription(name: \"Foo\", dependencies: [\"ProductBar\"]),\n                ]\n            ),\n            Manifest.createFileSystemManifest(\n                displayName: \"Bar\",\n                path: \"/Some-Bar\",\n                toolsVersion: .v5_2,\n                products: [\n                    ProductDescription(name: \"ProductBar\", type: .library(.automatic), targets: [\"Bar\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"Bar\"),\n                ]\n            ),\n        ]\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(fileSystem: fs, manifests: manifests, observabilityScope: observability.topScope)\n            try expectDiagnostics(observability.diagnostics) { result in\n                let diagnostic = result.check(\n                    diagnostic: \"\"\"\n                    dependency 'ProductBar' in target 'Foo' requires explicit declaration; reference the package in the target dependency with '.product(name: \"ProductBar\", package: \"Bar\")'\n                    \"\"\",\n                    severity: .error\n                )\n                #expect(diagnostic?.metadata?.packageIdentity == .plain(\"foo\"))\n            }\n        }\n\n        // fix it\n\n        do {\n            let fixedManifests = try [\n                manifests[0].withTargets([\n                    TargetDescription(name: \"Foo\", dependencies: [.product(name: \"ProductBar\", package: \"Some-Bar\")]),\n                ]),\n                manifests[1], // same\n            ]\n\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: fixedManifests,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    // test backwards compatibility 5.2 < 5.4\n    // TODO: remove this when we remove explicit dependency name\n    @Test\n    func targetDependencies_Post52_AliasFindsIdentity() throws {\n        let manifest = try Manifest.createRootManifest(\n            displayName: \"Package\",\n            path: \"/Package\",\n            toolsVersion: .v5_2,\n            dependencies: [\n                .localSourceControl(\n                    deprecatedName: \"Alias\",\n                    path: \"/Identity\",\n                    requirement: .upToNextMajor(from: \"1.0.0\")\n                ),\n                .localSourceControl(\n                    path: \"/Unrelated\",\n                    requirement: .upToNextMajor(from: \"1.0.0\")\n                ),\n            ],\n            targets: [\n                TargetDescription(\n                    name: \"Target\",\n                    dependencies: [\n                        .product(name: \"Product\", package: \"Alias\"),\n                        .product(name: \"Unrelated\", package: \"Unrelated\"),\n                    ]\n                ),\n            ]\n        )\n        // Make sure aliases are found properly and do not fall back to pre‐5.2 behavior, leaking across onto other\n        // dependencies.\n        let required = try manifest.dependenciesRequired(for: .everything)\n        let unrelated = try #require(\n            required\n                .first(where: { $0.nameForModuleDependencyResolutionOnly == \"Unrelated\" }))\n        let requestedProducts = unrelated.productFilter\n#if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n        // Unrelated should not have been asked for Product, because it should know Product comes from Identity.\n        #expect(!requestedProducts.contains(\"Product\"), \"Product requests are leaking.\")\n#endif\n    }\n\n    @Test\n    func platforms() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Sources/foo/module.modulemap\",\n            \"/Sources/bar/bar.swift\",\n            \"/Sources/cbar/bar.c\",\n            \"/Sources/cbar/include/bar.h\",\n            \"/Tests/test/test.swift\"\n        )\n\n        let defaultDerivedPlatforms = [\n            \"linux\": \"0.0\",\n            \"macos\": \"10.13\",\n            \"maccatalyst\": \"13.0\",\n            \"ios\": \"12.0\",\n            \"tvos\": \"12.0\",\n            \"driverkit\": \"19.0\",\n            \"watchos\": \"4.0\",\n            \"visionos\": \"1.0\",\n            \"android\": \"0.0\",\n            \"windows\": \"0.0\",\n            \"wasi\": \"0.0\",\n            \"openbsd\": \"0.0\",\n        ]\n\n        let customXCTestMinimumDeploymentTargets = [\n            PackageModel.Platform.macOS: PlatformVersion(\"10.15\"),\n            PackageModel.Platform.iOS: PlatformVersion(\"12.0\"),\n            PackageModel.Platform.tvOS: PlatformVersion(\"12.0\"),\n            PackageModel.Platform.watchOS: PlatformVersion(\"4.0\"),\n            PackageModel.Platform.visionOS: PlatformVersion(\"1.0\"),\n        ]\n\n        let expectedPlatformsForTests = customXCTestMinimumDeploymentTargets\n            .reduce(into: [PackageModel.Platform: PlatformVersion]()) { partialResult, entry in\n                if entry.value > entry.key.oldestSupportedVersion {\n                    partialResult[entry.key] = entry.value\n                } else {\n                    partialResult[entry.key] = entry.key.oldestSupportedVersion\n                }\n            }\n\n        do {\n            // One platform with an override.\n            let manifest = try Manifest.createRootManifest(\n                displayName: \"pkg\",\n                platforms: [\n                    PlatformDescription(name: \"macos\", version: \"10.14\", options: [\"option1\"]),\n                ],\n                products: [\n                    ProductDescription(name: \"foo\", type: .library(.automatic), targets: [\"foo\"]),\n                    ProductDescription(name: \"cbar\", type: .library(.automatic), targets: [\"cbar\"]),\n                    ProductDescription(name: \"bar\", type: .library(.automatic), targets: [\"bar\"]),\n                    ProductDescription(\n                        name: \"multi-target\",\n                        type: .library(.automatic),\n                        targets: [\n                            \"bar\",\n                            \"cbar\",\n                            \"test\",\n                        ]\n                    ),\n                ],\n                targets: [\n                    TargetDescription(name: \"foo\", type: .system),\n                    TargetDescription(name: \"cbar\"),\n                    TargetDescription(name: \"bar\", dependencies: [\"foo\"]),\n                    TargetDescription(name: \"test\", type: .test),\n                ]\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let graph = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [manifest],\n                customXCTestMinimumDeploymentTargets: customXCTestMinimumDeploymentTargets,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n\n            try PackageGraphTester(graph) { result in\n                let expectedDeclaredPlatforms = [\n                    \"macos\": \"10.14\",\n                ]\n\n                // default platforms will be auto-added during package build\n                let expectedDerivedPlatforms = defaultDerivedPlatforms.merging(\n                    expectedDeclaredPlatforms,\n                    uniquingKeysWith: { _, rhs in rhs }\n                )\n\n                try result.checkTarget(\"foo\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                    target.checkDerivedPlatformOptions(.macOS, options: [\"option1\"])\n                    target.checkDerivedPlatformOptions(.iOS, options: [])\n                }\n                try result.checkTarget(\"bar\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                    target.checkDerivedPlatformOptions(.macOS, options: [\"option1\"])\n                    target.checkDerivedPlatformOptions(.iOS, options: [])\n                }\n                try result.checkTarget(\"cbar\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                    target.checkDerivedPlatformOptions(.macOS, options: [\"option1\"])\n                    target.checkDerivedPlatformOptions(.iOS, options: [])\n                }\n                try result.checkTarget(\"test\") { target in\n                    var expected = expectedDerivedPlatforms\n                    for item in [PackageModel.Platform.macOS, .iOS, .tvOS, .watchOS] {\n                        expected[item.name] = expectedPlatformsForTests[item]?.versionString\n                    }\n                    target.checkDerivedPlatforms(expected)\n                    target.checkDerivedPlatformOptions(.macOS, options: [\"option1\"])\n                    target.checkDerivedPlatformOptions(.iOS, options: [])\n                }\n               try result.checkProduct(\"foo\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                    product.checkDerivedPlatformOptions(.macOS, options: [\"option1\"])\n                    product.checkDerivedPlatformOptions(.iOS, options: [])\n                }\n               try result.checkProduct(\"bar\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                    product.checkDerivedPlatformOptions(.macOS, options: [\"option1\"])\n                    product.checkDerivedPlatformOptions(.iOS, options: [])\n                }\n               try result.checkProduct(\"cbar\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                    product.checkDerivedPlatformOptions(.macOS, options: [\"option1\"])\n                    product.checkDerivedPlatformOptions(.iOS, options: [])\n                }\n               try result.checkProduct(\"multi-target\") { product in\n                    var expected = expectedDerivedPlatforms\n                    for item in [PackageModel.Platform.macOS, .iOS, .tvOS, .watchOS] {\n                        expected[item.name] = expectedPlatformsForTests[item]?.versionString\n                    }\n                    product.checkDerivedPlatforms(expected)\n                    product.checkDerivedPlatformOptions(.macOS, options: [\"option1\"])\n                    product.checkDerivedPlatformOptions(.iOS, options: [])\n                }\n            }\n        }\n\n        do {\n            // Two platforms with overrides.\n            let manifest = try Manifest.createRootManifest(\n                displayName: \"pkg\",\n                platforms: [\n                    PlatformDescription(name: \"macos\", version: \"10.14\"),\n                    PlatformDescription(name: \"tvos\", version: \"12.0\"),\n                ],\n                products: [\n                    ProductDescription(name: \"foo\", type: .library(.automatic), targets: [\"foo\"]),\n                    ProductDescription(name: \"cbar\", type: .library(.automatic), targets: [\"cbar\"]),\n                    ProductDescription(name: \"bar\", type: .library(.automatic), targets: [\"bar\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"foo\", type: .system),\n                    TargetDescription(name: \"cbar\"),\n                    TargetDescription(name: \"bar\", dependencies: [\"foo\"]),\n                ]\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let graph = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [manifest],\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n\n            try PackageGraphTester(graph) { result in\n                let expectedDeclaredPlatforms = [\n                    \"macos\": \"10.14\",\n                    \"tvos\": \"12.0\",\n                ]\n\n                // default platforms will be auto-added during package build\n                let expectedDerivedPlatforms = defaultDerivedPlatforms.merging(\n                    expectedDeclaredPlatforms,\n                    uniquingKeysWith: { _, rhs in rhs }\n                )\n\n                try result.checkTarget(\"foo\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n                try result.checkTarget(\"bar\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n                try result.checkTarget(\"cbar\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n               try result.checkProduct(\"foo\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n               try result.checkProduct(\"bar\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n               try result.checkProduct(\"cbar\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n            }\n        }\n\n        do {\n            // Test MacCatalyst overriding behavior.\n            let manifest = try Manifest.createRootManifest(\n                displayName: \"pkg\",\n                platforms: [\n                    PlatformDescription(name: \"ios\", version: \"15.0\"),\n                ],\n                products: [\n                    ProductDescription(name: \"cbar\", type: .library(.automatic), targets: [\"cbar\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"cbar\"),\n                    TargetDescription(name: \"test\", type: .test),\n                ]\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let graph = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [manifest],\n                customXCTestMinimumDeploymentTargets: customXCTestMinimumDeploymentTargets,\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n\n            try PackageGraphTester(graph) { result in\n                let expectedDeclaredPlatforms = [\n                    \"ios\": \"15.0\",\n                ]\n\n                var expectedDerivedPlatforms = defaultDerivedPlatforms.merging(\n                    expectedDeclaredPlatforms,\n                    uniquingKeysWith: { _, rhs in rhs }\n                )\n                var expectedDerivedPlatformsForTests = defaultDerivedPlatforms.merging(\n                    expectedPlatformsForTests.map { ($0.name, $1.versionString) },\n                    uniquingKeysWith: { _, rhs in rhs }\n                )\n                expectedDerivedPlatformsForTests[\"ios\"] = expectedDeclaredPlatforms[\"ios\"]\n\n                // Gets derived to be the same as the declared iOS deployment target.\n                expectedDerivedPlatforms[\"maccatalyst\"] = expectedDeclaredPlatforms[\"ios\"]\n                expectedDerivedPlatformsForTests[\"maccatalyst\"] = expectedDeclaredPlatforms[\"ios\"]\n\n                try result.checkTarget(\"test\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatformsForTests)\n                }\n                try result.checkTarget(\"cbar\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n               try result.checkProduct(\"cbar\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n            }\n        }\n    }\n\n    @Test\n    func customPlatforms() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Sources/foo/module.modulemap\"\n        )\n\n        let defaultDerivedPlatforms = [\n            \"linux\": \"0.0\",\n            \"macos\": \"10.13\",\n            \"maccatalyst\": \"13.0\",\n            \"ios\": \"12.0\",\n            \"tvos\": \"12.0\",\n            \"driverkit\": \"19.0\",\n            \"watchos\": \"4.0\",\n            \"visionos\": \"1.0\",\n            \"android\": \"0.0\",\n            \"windows\": \"0.0\",\n            \"wasi\": \"0.0\",\n            \"openbsd\": \"0.0\",\n        ]\n\n        do {\n            // One custom platform.\n            let manifest = try Manifest.createRootManifest(\n                displayName: \"pkg\",\n                platforms: [\n                    PlatformDescription(name: \"customos\", version: \"1.0\"),\n                ],\n                products: [\n                    ProductDescription(name: \"foo\", type: .library(.automatic), targets: [\"foo\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"foo\", type: .system),\n                ]\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let graph = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [manifest],\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n\n            try PackageGraphTester(graph) { result in\n                let expectedDeclaredPlatforms = [\n                    \"customos\": \"1.0\",\n                ]\n\n                // default platforms will be auto-added during package build\n                let expectedDerivedPlatforms = defaultDerivedPlatforms.merging(\n                    expectedDeclaredPlatforms,\n                    uniquingKeysWith: { _, rhs in rhs }\n                )\n\n                try result.checkTarget(\"foo\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n               try result.checkProduct(\"foo\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n            }\n        }\n\n        do {\n            // Two platforms with overrides.\n            let manifest = try Manifest.createRootManifest(\n                displayName: \"pkg\",\n                platforms: [\n                    PlatformDescription(name: \"customos\", version: \"1.0\"),\n                    PlatformDescription(name: \"anothercustomos\", version: \"2.3\"),\n                ],\n                products: [\n                    ProductDescription(name: \"foo\", type: .library(.automatic), targets: [\"foo\"]),\n                ],\n                targets: [\n                    TargetDescription(name: \"foo\", type: .system),\n                ]\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let graph = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [manifest],\n                observabilityScope: observability.topScope\n            )\n            expectNoDiagnostics(observability.diagnostics)\n\n            try PackageGraphTester(graph) { result in\n                let expectedDeclaredPlatforms = [\n                    \"customos\": \"1.0\",\n                    \"anothercustomos\": \"2.3\",\n                ]\n\n                // default platforms will be auto-added during package build\n                let expectedDerivedPlatforms = defaultDerivedPlatforms.merging(\n                    expectedDeclaredPlatforms,\n                    uniquingKeysWith: { _, rhs in rhs }\n                )\n\n                try result.checkTarget(\"foo\") { target in\n                    target.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    target.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n               try result.checkProduct(\"foo\") { product in\n                    product.checkDeclaredPlatforms(expectedDeclaredPlatforms)\n                    product.checkDerivedPlatforms(expectedDerivedPlatforms)\n                }\n            }\n        }\n    }\n\n    @Test\n    func dependencyOnUpcomingFeatures() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/foo.swift\",\n            \"/Foo/Sources/Foo2/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\",\n            \"/Bar/Sources/Bar2/bar.swift\",\n            \"/Bar/Sources/Bar3/bar.swift\",\n            \"/Bar/Sources/TransitiveBar/bar.swift\",\n            \"<end>\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                        TargetDescription(name: \"Foo2\", dependencies: [\"TransitiveBar\"]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\", \"Bar2\", \"Bar3\"]),\n                        ProductDescription(\n                            name: \"TransitiveBar\",\n                            type: .library(.automatic),\n                            targets: [\"TransitiveBar\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Bar\",\n                            settings: [\n                                .init(tool: .swift, kind: .enableUpcomingFeature(\"ConciseMagicFile\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Bar2\",\n                            settings: [\n                                .init(tool: .swift, kind: .enableUpcomingFeature(\"UnknownToTheseTools\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Bar3\",\n                            settings: [\n                                .init(tool: .swift, kind: .enableUpcomingFeature(\"ExistentialAny\")),\n                                .init(tool: .swift, kind: .enableUpcomingFeature(\"UnknownToTheseTools\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"TransitiveBar\",\n                            dependencies: [\"Bar2\"]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        #expect(observability.diagnostics.count == 0)\n    }\n\n    @Test\n    func customNameInPackageDependency() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/Foo/Sources/Foo/source.swift\",\n            \"/Bar2/Sources/Bar/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_9,\n                    dependencies: [\n                        .fileSystem(deprecatedName: \"Bar\", path: \"/Bar2\"),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Foo\", dependencies: [.product(name: \"Bar\", package: \"BAR\")]),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar2\",\n                    toolsVersion: .v5_9,\n                    products: [\n                        ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"Bar\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        #expect(observability.diagnostics.count == 0)\n    }\n\n    @Test\n    func dependencyResolutionWithErrorMessages() throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n                \"/aaa/Sources/aaa/main.swift\",\n            \"/zzz/Sources/zzz/source.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let _ = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"aaa\",\n                    path: \"/aaa\",\n                    dependencies: [\n                        .localSourceControl(path: \"/zzz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    products: [],\n                    targets: [\n                        TargetDescription(\n                            name: \"aaa\",\n                            dependencies: [\"mmm\"],\n                            type: .executable\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"zzz\",\n                    path: \"/zzz\",\n                    products: [\n                        ProductDescription(\n                            name: \"zzz\",\n                            type: .library(.automatic),\n                            targets: [\"zzz\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"zzz\"\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"product 'mmm' required by package 'aaa' target 'aaa' not found.\",\n                severity: .error\n            )\n        }\n    }\n}\n\nextension Manifest {\n    func withTargets(_ targets: [TargetDescription]) -> Manifest {\n        Manifest.createManifest(\n            displayName: self.displayName,\n            path: self.path.parentDirectory,\n            packageKind: self.packageKind,\n            packageIdentity: self.packageIdentity,\n            packageLocation: self.packageLocation,\n            toolsVersion: self.toolsVersion,\n            dependencies: self.dependencies,\n            targets: targets\n        )\n    }\n\n    func withDependencies(_ dependencies: [PackageDependency]) -> Manifest {\n        Manifest.createManifest(\n            displayName: self.displayName,\n            path: self.path.parentDirectory,\n            packageKind: self.packageKind,\n            packageIdentity: self.packageIdentity,\n            packageLocation: self.packageLocation,\n            toolsVersion: self.toolsVersion,\n            dependencies: dependencies,\n            targets: self.targets\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphTests/PubGrubTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport OrderedCollections\n@testable import PackageGraph\nimport PackageLoading\n@testable import PackageModel\nimport SourceControl\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCUtility.Version\n\n// There's some useful helper utilities defined below for easier testing:\n//\n// Terms conform to ExpressibleByStringLiteral in this test module and their\n// version requirements can be created with a few options:\n//   - \"package@1.0.0\": equivalent to .exact(\"1.0.0\")\n//   - \"package^1.0.0\": equivalent to .upToNextMajor(\"1.0.0\")\n//   - \"package-1.0.0-3.0.0\": equivalent to .range(\"1.0.0\"..<\"3.0.0\")\n//\n// Mocking a dependency graph is easily achieved by using the builder API. It's\n// a global object in this module.\n//   builder.serve(dependencies: dependencies...)\n// or for dependencies\n//   builder.serve(\"packageName\", at: someVersion, with: dependencies...)\n// Calling builder.create() returns a resolver which can then be used to start\n// the resolution by calling .solve() on it and passing a reference to the root\n// package.\n//\n// The functions (AssertBindings,) AssertResult, AssertRootCause & AssertError\n// can be used for checking the success or error outcomes of the resolver\n// without having to manually pull the bindings or errors out of\n// the results. They also offer useful failure messages.\n\nlet builder = DependencyGraphBuilder()\n\nprivate let emptyProvider = MockProvider(containers: [])\n\nprivate let v1: Version = \"1.0.0\"\nprivate let v1_1: Version = \"1.1.0\"\nprivate let v1_5: Version = \"1.5.0\"\nprivate let v2: Version = \"2.0.0\"\nprivate let v3: Version = \"3.0.0\"\nprivate let v1Range: VersionSetSpecifier = .range(v1..<v2)\nprivate let v1_1Range: VersionSetSpecifier = .range(v1_1..<v2)\nprivate let v1_5Range: VersionSetSpecifier = .range(v1_5..<v2)\nprivate let v1to3Range: VersionSetSpecifier = .range(v1..<v3)\nprivate let v2Range: VersionSetSpecifier = .range(v2..<v3)\n\nlet aRef = PackageReference.localSourceControl(identity: .plain(\"a\"), path: .root)\nlet bRef = PackageReference.localSourceControl(identity: .plain(\"b\"), path: .root)\nlet cRef = PackageReference.localSourceControl(identity: .plain(\"c\"), path: .root)\n\nlet rootRef = PackageReference.root(identity: .plain(\"root\"), path: .root)\nlet rootNode = DependencyResolutionNode.root(package: rootRef)\nlet rootCause = try! Incompatibility(Term(rootNode, .exact(v1)), root: rootNode)\nlet _cause = try! Incompatibility(\"cause@0.0.0\", root: rootNode)\n\nfinal class PubGrubTests: XCTestCase {\n    func testTermInverse() {\n        let a = Term(\"a@1.0.0\")\n        XCTAssertFalse(a.inverse.isPositive)\n        XCTAssertTrue(a.inverse.inverse.isPositive)\n    }\n\n    func testTermSatisfies() {\n        let a100 = Term(\"a@1.0.0\")\n\n        XCTAssertTrue(a100.satisfies(a100))\n        XCTAssertFalse(a100.satisfies(\"¬a@1.0.0\"))\n        XCTAssertTrue(a100.satisfies(\"a^1.0.0\"))\n        XCTAssertFalse(a100.satisfies(\"¬a^1.0.0\"))\n        XCTAssertFalse(a100.satisfies(\"a^2.0.0\"))\n\n        XCTAssertFalse(Term(\"¬a@1.0.0\").satisfies(\"¬a^1.0.0\"))\n        XCTAssertFalse(Term(\"¬a@1.0.0\").satisfies(\"a^2.0.0\"))\n        XCTAssertTrue(Term(\"¬a^1.0.0\").satisfies(\"¬a@1.0.0\"))\n        XCTAssertTrue(Term(\"a^2.0.0\").satisfies(\"¬a@1.0.0\"))\n\n        XCTAssertTrue(Term(\"a^1.0.0\").satisfies(\"¬a@2.0.0\"))\n        XCTAssertTrue(Term(\"a^1.0.0\").satisfies(\"¬a^2.0.0\"))\n\n        XCTAssertTrue(Term(\"a^1.0.0\").satisfies(Term(\"a^1.0.0\")))\n        XCTAssertTrue(Term(\"a-1.0.0-1.1.0\").satisfies(Term(\"a^1.0.0\")))\n        XCTAssertFalse(Term(\"a-1.0.0-1.1.0\").satisfies(Term(\"a^2.0.0\")))\n    }\n\n    func _testTermIntersection() {\n        // a^1.0.0 ∩ ¬a@1.5.0 → a >=1.0.0 <1.5.0\n        XCTAssertEqual(\n            Term(\"a^1.0.0\").intersect(with: Term(\"¬a@1.5.0\")),\n            Term(\"a-1.0.0-1.5.0\"))\n\n        // a^1.0.0 ∩ a >=1.5.0 <3.0.0 → a^1.5.0\n        XCTAssertEqual(\n            Term(\"a^1.0.0\").intersect(with: Term(\"a-1.5.0-3.0.0\")),\n            Term(\"a^1.5.0\"))\n\n        // ¬a^1.0.0 ∩ ¬a >=1.5.0 <3.0.0 → ¬a >=1.0.0 <3.0.0\n        XCTAssertEqual(\n            Term(\"¬a^1.0.0\").intersect(with: Term(\"¬a-1.5.0-3.0.0\")),\n            Term(\"¬a-1.0.0-3.0.0\"))\n\n        XCTAssertEqual(\n            Term(\"a^1.0.0\").intersect(with: Term(\"a^1.0.0\")),\n            Term(\"a^1.0.0\"))\n\n        XCTAssertEqual(\n            Term(\"¬a^1.0.0\").intersect(with: Term(\"¬a^1.0.0\")),\n            Term(\"¬a^1.0.0\"))\n\n        XCTAssertNil(Term(\"a^1.0.0\").intersect(with: Term(\"¬a^1.0.0\")))\n        XCTAssertNil(Term(\"a@1.0.0\").difference(with: Term(\"a@1.0.0\")))\n\n        XCTAssertEqual(\n            Term(\"¬a^1.0.0\").intersect(with: Term(\"a^2.0.0\")),\n            Term(\"a^2.0.0\"))\n\n        XCTAssertEqual(\n            Term(\"a^2.0.0\").intersect(with: Term(\"¬a^1.0.0\")),\n            Term(\"a^2.0.0\"))\n\n        XCTAssertEqual(\n            Term(\"¬a^1.0.0\").intersect(with: Term(\"¬a^1.0.0\")),\n            Term(\"¬a^1.0.0\"))\n\n        XCTAssertEqual(\n            Term(\"¬a@1.0.0\").intersect(with: Term(\"¬a@1.0.0\")),\n            Term(\"¬a@1.0.0\"))\n\n        // Check difference.\n        let anyA = Term(.empty(package: \"a\"), .any)\n        XCTAssertNil(Term(\"a^1.0.0\").difference(with: anyA))\n\n        let notEmptyA = Term(not: .empty(package: \"a\"), .empty)\n        XCTAssertNil(Term(\"a^1.0.0\").difference(with: notEmptyA))\n    }\n\n    func testTermRelation() {\n        // Both positive.\n        XCTAssertEqual(Term(\"a^1.1.0\").relation(with: \"a^1.0.0\"), .subset)\n        XCTAssertEqual(Term(\"a^1.9.0\").relation(with: \"a^1.8.9\"), .subset)\n        XCTAssertEqual(Term(\"a^1.5.0\").relation(with: \"a^1.0.0\"), .subset)\n        XCTAssertEqual(Term(\"a^1.9.0\").relation(with: \"a@1.9.0\"), .overlap)\n        XCTAssertEqual(Term(\"a^1.9.0\").relation(with: \"a@1.9.1\"), .overlap)\n        XCTAssertEqual(Term(\"a^1.9.0\").relation(with: \"a@1.20.0\"), .overlap)\n        XCTAssertEqual(Term(\"a^2.0.0\").relation(with: \"a^2.9.0\"), .overlap)\n        XCTAssertEqual(Term(\"a^2.0.0\").relation(with: \"a^2.9.0\"), .overlap)\n        XCTAssertEqual(Term(\"a-1.5.0-3.0.0\").relation(with: \"a^1.0.0\"), .overlap)\n        XCTAssertEqual(Term(\"a^1.9.0\").relation(with: \"a@1.8.1\"), .disjoint)\n        XCTAssertEqual(Term(\"a^1.9.0\").relation(with: \"a@2.0.0\"), .disjoint)\n        XCTAssertEqual(Term(\"a^2.0.0\").relation(with: \"a@1.0.0\"), .disjoint)\n\n        // First term is negative, second term is positive.\n        XCTAssertEqual(Term(\"¬a^1.0.0\").relation(with: \"a@1.5.0\"), .disjoint)\n        XCTAssertEqual(Term(\"¬a^1.5.0\").relation(with: \"a^1.0.0\"), .overlap)\n        XCTAssertEqual(Term(\"¬a^2.0.0\").relation(with: \"a^1.5.0\"), .overlap)\n\n        // First term is positive, second term is negative.\n        XCTAssertEqual(Term(\"a^2.0.0\").relation(with: \"¬a^1.0.0\"), .subset)\n        XCTAssertEqual(Term(\"a^1.5.0\").relation(with: \"¬a^1.0.0\"), .disjoint)\n        XCTAssertEqual(Term(\"a^1.0.0\").relation(with: \"¬a^1.5.0\"), .overlap)\n        XCTAssertEqual(Term(\"a-1.0.0-2.0.0\").relation(with: \"¬a-1.0.0-1.2.0\"), .overlap)\n\n        // Both terms are negative.\n        XCTAssertEqual(Term(\"¬a^1.0.0\").relation(with: \"¬a^1.5.0\"), .subset)\n        XCTAssertEqual(Term(\"¬a^2.0.0\").relation(with: \"¬a^1.0.0\"), .overlap)\n        XCTAssertEqual(Term(\"¬a^1.5.0\").relation(with: \"¬a^1.0.0\"), .overlap)\n    }\n\n    func testTermIsValidDecision() {\n        let solution100_150 = PartialSolution(assignments: [\n            .derivation(\"a^1.0.0\", cause: _cause, decisionLevel: 1),\n            .derivation(\"a^1.5.0\", cause: _cause, decisionLevel: 2)\n        ])\n\n        let allSatisfied = Term(\"a@1.6.0\")\n        XCTAssertTrue(allSatisfied.isValidDecision(for: solution100_150))\n        let partiallySatisfied = Term(\"a@1.2.0\")\n        XCTAssertFalse(partiallySatisfied.isValidDecision(for: solution100_150))\n    }\n\n    func testIncompatibilityNormalizeTermsOnInit() async throws {\n        let i1 = try Incompatibility(Term(\"a^1.0.0\"), Term(\"a^1.5.0\"), Term(\"¬b@1.0.0\"),\n                                 root: rootNode)\n        XCTAssertEqual(i1.terms.count, 2)\n        let a1 = i1.terms.first { $0.node.package == \"a\" }\n        let b1 = i1.terms.first { $0.node.package == \"b\" }\n        XCTAssertEqual(a1?.requirement, v1_5Range)\n        XCTAssertEqual(b1?.requirement, .exact(v1))\n\n        let i2 = try Incompatibility(Term(\"¬a^1.0.0\"), Term(\"a^2.0.0\"),\n                                 root: rootNode)\n        XCTAssertEqual(i2.terms.count, 1)\n        let a2 = i2.terms.first\n        XCTAssertEqual(a2?.requirement, v2Range)\n    }\n\n    func testSolutionPositive() {\n        let s1 = PartialSolution(assignments:[\n            .derivation(\"a^1.5.0\", cause: _cause, decisionLevel: 0),\n            .derivation(\"b@2.0.0\", cause: _cause, decisionLevel: 0),\n            .derivation(\"a^1.0.0\", cause: _cause, decisionLevel: 0)\n        ])\n        let a1 = s1._positive.first { $0.key.package.identity == PackageIdentity(\"a\") }?.value\n        XCTAssertEqual(a1?.requirement, v1_5Range)\n        let b1 = s1._positive.first { $0.key.package.identity == PackageIdentity(\"b\") }?.value\n        XCTAssertEqual(b1?.requirement, .exact(v2))\n\n        let s2 = PartialSolution(assignments: [\n            .derivation(\"¬a^1.5.0\", cause: _cause, decisionLevel: 0),\n            .derivation(\"a^1.0.0\", cause: _cause, decisionLevel: 0)\n        ])\n        let a2 = s2._positive.first { $0.key.package.identity == PackageIdentity(\"a\") }?.value\n        XCTAssertEqual(a2?.requirement, .range(v1..<v1_5))\n    }\n\n    func testSolutionUndecided() async throws {\n        var solution = PartialSolution()\n        solution.derive(\"a^1.0.0\", cause: rootCause)\n        solution.decide(.empty(package: \"b\"), at: v2)\n        solution.derive(\"a^1.5.0\", cause: rootCause)\n        solution.derive(\"¬c^1.5.0\", cause: rootCause)\n        solution.derive(\"d^1.9.0\", cause: rootCause)\n        solution.derive(\"d^1.9.9\", cause: rootCause)\n\n        let undecided = solution.undecided.sorted{ $0.node.package.identity < $1.node.package.identity }\n        XCTAssertEqual(undecided, [Term(\"a^1.5.0\"), Term(\"d^1.9.9\")])\n    }\n\n    func testSolutionAddAssignments() async throws {\n        let root = Term(rootNode, .exact(\"1.0.0\"))\n        let a = Term(\"a@1.0.0\")\n        let b = Term(\"b@2.0.0\")\n\n        var solution = PartialSolution(assignments: [])\n        solution.decide(rootNode, at: v1)\n        solution.decide(.product(\"a\", package: aRef), at: v1)\n        solution.derive(b, cause: _cause)\n        XCTAssertEqual(solution.decisionLevel, 1)\n\n        XCTAssertEqual(solution.assignments, [\n            .decision(root, decisionLevel: 0),\n            .decision(a, decisionLevel: 1),\n            .derivation(b, cause: _cause, decisionLevel: 1)\n        ])\n        XCTAssertEqual(solution.decisions, [\n            rootNode: v1,\n            .product(\"a\", package: aRef): v1,\n        ])\n    }\n\n    func testSolutionBacktrack() {\n        // TODO: This should probably add derivations to cover that logic as well.\n        var solution = PartialSolution()\n        solution.decide(.empty(package: aRef), at: v1)\n        solution.decide(.empty(package: bRef), at: v1)\n        solution.decide(.empty(package: cRef), at: v1)\n\n        XCTAssertEqual(solution.decisionLevel, 2)\n        solution.backtrack(toDecisionLevel: 1)\n        XCTAssertEqual(solution.assignments.count, 2)\n        XCTAssertEqual(solution.decisionLevel, 1)\n    }\n\n    func testPositiveTerms() {\n        let s1 = PartialSolution(assignments: [\n            .derivation(\"a^1.0.0\", cause: _cause, decisionLevel: 0),\n        ])\n        XCTAssertEqual(s1._positive[.product(\"a\", package: \"a\")]?.requirement,\n                       v1Range)\n\n        let s2 = PartialSolution(assignments: [\n            .derivation(\"a^1.0.0\", cause: _cause, decisionLevel: 0),\n            .derivation(\"a^1.5.0\", cause: _cause, decisionLevel: 0)\n        ])\n        XCTAssertEqual(s2._positive[.product(\"a\", package: \"a\")]?.requirement,\n                       v1_5Range)\n    }\n\n    func testResolverAddIncompatibility() async throws {\n        let state = PubGrubDependencyResolver.State(root: rootNode)\n\n        let a = try Incompatibility(Term(\"a@1.0.0\"), root: rootNode)\n        state.addIncompatibility(a, at: .topLevel)\n        let ab = try Incompatibility(Term(\"a@1.0.0\"), Term(\"b@2.0.0\"), root: rootNode)\n        state.addIncompatibility(ab, at: .topLevel)\n\n        XCTAssertEqual(state.incompatibilities, [\n            .product(\"a\", package: \"a\"): [a, ab],\n            .product(\"b\", package: \"b\"): [ab],\n        ])\n    }\n\n    func testUpdatePackageIdentifierAfterResolution() async throws {\n        let fooURL = SourceControlURL(\"https://example.com/foo\")\n        let fooRef = PackageReference.remoteSourceControl(identity: PackageIdentity(url: fooURL), url: fooURL)\n        let foo = MockContainer(package: fooRef, dependenciesByVersion: [v1: [:]])\n        foo.manifestName = \"bar\"\n\n        let provider = MockProvider(containers: [foo])\n\n        let resolver = PubGrubDependencyResolver(provider: provider, observabilityScope: ObservabilitySystem.NOOP)\n        let deps = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"]))\n        ])\n        let result = await resolver.solve(constraints: deps)\n\n        switch result {\n        case .failure(let error):\n            XCTFail(\"Unexpected error: \\(error)\")\n        case .success(let bindings):\n            XCTAssertEqual(bindings.count, 1)\n            let foo = bindings.first { $0.package.identity == .plain(\"foo\") }\n            XCTAssertEqual(foo?.package.deprecatedName, \"bar\")\n        }\n    }\n\n    func testResolverConflictResolution() async throws {\n        let solver1 = PubGrubDependencyResolver(provider: emptyProvider, observabilityScope: ObservabilitySystem.NOOP)\n        let state1 = PubGrubDependencyResolver.State(root: rootNode)\n\n        let notRoot = try Incompatibility(Term(not: rootNode, .any),\n                                      root: rootNode,\n                                      cause: .root)\n        state1.addIncompatibility(notRoot, at: .topLevel)\n        XCTAssertThrowsError(try solver1.resolve(state: state1, conflict: notRoot))\n    }\n\n    func testResolverDecisionMaking() async throws {\n        let solver1 = PubGrubDependencyResolver(provider: emptyProvider, observabilityScope: ObservabilitySystem.NOOP)\n        let state1 = PubGrubDependencyResolver.State(root: rootNode)\n\n        // No decision can be made if no unsatisfied terms are available.\n        let decisionNil = try await solver1.makeDecision(state: state1)\n        XCTAssertNil(decisionNil)\n\n        let a = MockContainer(package: aRef, dependenciesByVersion: [\n            \"0.0.0\": [:],\n            v1: [\"a\": [(package: bRef, requirement: v1Range, productFilter: .specific([\"b\"]))]]\n        ])\n\n        let provider = MockProvider(containers: [a])\n        let solver2 = PubGrubDependencyResolver(provider: provider, observabilityScope: ObservabilitySystem.NOOP)\n        let solution = PartialSolution(assignments: [\n            .derivation(\"a^1.0.0\", cause: rootCause, decisionLevel: 0)\n        ])\n        let state2 = PubGrubDependencyResolver.State(root: rootNode, solution: solution)\n\n        XCTAssertEqual(state2.incompatibilities.count, 0)\n\n        let decision = try await solver2.makeDecision(state: state2)\n        XCTAssertEqual(decision, .product(\"a\", package: \"a\"))\n\n        XCTAssertEqual(state2.incompatibilities.count, 3)\n        XCTAssertEqual(state2.incompatibilities[.product(\"a\", package: \"a\")], [\n            try Incompatibility(\"a@1.0.0\", Term(not: .product(\"b\", package: \"b\"), v1Range),\n                                              root: rootNode,\n                                              cause: .dependency(node: .product(\"a\", package: \"a\"))),\n            try Incompatibility(\"a@1.0.0\", Term(not: .empty(package: \"a\"), .exact(\"1.0.0\")),\n                                              root: rootNode,\n                                              cause: .dependency(node: .product(\"a\", package: \"a\"))),\n        ])\n    }\n\n    func testResolverUnitPropagation() async throws {\n        let solver1 = PubGrubDependencyResolver(provider: emptyProvider, observabilityScope: ObservabilitySystem.NOOP)\n        let state1 = PubGrubDependencyResolver.State(root: rootNode)\n\n        // no known incompatibilities should result in no satisfaction checks\n        try solver1.propagate(state: state1, node: .root(package: \"root\"))\n\n        // even if incompatibilities are present\n        state1.addIncompatibility(try Incompatibility(Term(\"a@1.0.0\"), root: rootNode), at: .topLevel)\n        try solver1.propagate(state: state1, node: .empty(package: \"a\"))\n        try solver1.propagate(state: state1, node: .empty(package: \"a\"))\n        try solver1.propagate(state: state1, node: .empty(package: \"a\"))\n\n        // adding a satisfying term should result in a conflict\n        state1.decide(.empty(package: aRef), at: v1)\n        // FIXME: This leads to fatal error.\n        // try solver1.propagate(aRef)\n\n        // Unit propagation should derive a new assignment from almost satisfied incompatibilities.\n        let solver2 = PubGrubDependencyResolver(provider: emptyProvider, observabilityScope: ObservabilitySystem.NOOP)\n        let state2 = PubGrubDependencyResolver.State(root: rootNode)\n        state2.addIncompatibility(try Incompatibility(Term(.root(package: \"root\"), .any),\n                                    Term(\"¬a@1.0.0\"),\n                                    root: rootNode), at: .topLevel)\n        state2.decide(rootNode, at: v1)\n        XCTAssertEqual(state2.solution.assignments.count, 1)\n        try solver2.propagate(state: state2, node: .root(package: .root(identity: PackageIdentity(\"root\"), path: .root)))\n        XCTAssertEqual(state2.solution.assignments.count, 2)\n    }\n\n    func testSolutionFindSatisfiers() async throws {\n        var solution = PartialSolution()\n        solution.decide(rootNode, at: v1) // ← previous, but actually nil because this is the root decision\n        solution.derive(Term(.product(\"a\", package: aRef), .any), cause: _cause) // ← satisfier\n        solution.decide(.product(\"a\", package: aRef), at: v2)\n        solution.derive(\"b^1.0.0\", cause: _cause)\n\n        XCTAssertEqual(try solution.satisfier(for: Term(\"b^1.0.0\")).term, \"b^1.0.0\")\n        XCTAssertEqual(try solution.satisfier(for: Term(\"¬a^1.0.0\")).term, \"a@2.0.0\")\n        XCTAssertEqual(try solution.satisfier(for: Term(\"a^2.0.0\")).term, \"a@2.0.0\")\n    }\n\n    // this test reconstruct the conditions described in radar/93335995\n    func testRadar93335995() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let delegate = ObservabilityDependencyResolverDelegate(observabilityScope: observability.topScope)\n        let solver = PubGrubDependencyResolver(provider: emptyProvider, observabilityScope: observability.topScope, delegate: delegate)\n        let state = PubGrubDependencyResolver.State(root: rootNode)\n\n        state.decide(.root(package: aRef), at: \"1.1.0\")\n\n        do {\n            let cause = Incompatibility(\n                terms: .init([\n                    Term(node: .root(package: aRef),\n                         requirement: .exact(\"1.1.0\"),\n                         isPositive: true\n                    ),\n                    Term(node: .root(package: bRef),\n                         requirement: .range(\"1.1.0\" ..< \"2.0.0\"),\n                         isPositive: true\n                    )\n                ]),\n                cause: .noAvailableVersion\n            )\n            state.derive(Term(node: .root(package: bRef), requirement: .range(\"1.1.0\" ..< \"2.0.0\"), isPositive: true), cause: cause)\n        }\n\n        do {\n            let cause = Incompatibility(\n                terms: .init([\n                    Term(node: .root(package: aRef),\n                         requirement: .exact(\"1.1.0\"),\n                         isPositive: true\n                    ),\n                    Term(node: .root(package: bRef),\n                         requirement: .range(\"1.3.1\" ..< \"2.0.0\"),\n                         isPositive: true\n                    )\n                ]),\n                cause: .noAvailableVersion\n            )\n            state.derive(Term(node: .root(package: bRef), requirement: .range(\"1.3.1\" ..< \"2.0.0\"), isPositive: false), cause: cause)\n            // order here matters to reproduce the issue\n            state.derive(Term(node: .root(package: bRef), requirement: .exact(\"1.3.0\"), isPositive: false), cause: cause)\n            state.derive(Term(node: .root(package: bRef), requirement: .exact(\"1.3.1\"), isPositive: false), cause: cause)\n            state.derive(Term(node: .root(package: bRef), requirement: .exact(\"1.2.0\"), isPositive: false), cause: cause)\n            state.derive(Term(node: .root(package: bRef), requirement: .exact(\"1.1.0\"), isPositive: false), cause: cause)\n        }\n\n        let conflict = Incompatibility(\n            terms: .init([\n                Term(node: .root(package: aRef),\n                     requirement: .exact(\"1.1.0\"),\n                     isPositive: true\n                ),\n                Term(node: .root(package: bRef),\n                     requirement: .ranges([\"1.1.1\" ..< \"1.2.0\", \"1.2.1\" ..< \"1.3.0\"]),\n                     isPositive: true\n                )\n            ]),\n            cause: .noAvailableVersion\n        )\n\n        _ = try solver.resolve(state: state, conflict: conflict)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testNoInfiniteLoop() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let delegate = ObservabilityDependencyResolverDelegate(observabilityScope: observability.topScope)\n        let solver = PubGrubDependencyResolver(provider: emptyProvider, observabilityScope: observability.topScope, delegate: delegate)\n        let state = PubGrubDependencyResolver.State(root: rootNode)\n\n        do {\n            let cause = Incompatibility(\n                terms: .init([\n                    Term(node: .root(package: aRef),\n                         requirement: .exact(\"1.1.0\"),\n                         isPositive: true\n                    ),\n                    Term(node: .root(package: bRef),\n                         requirement: .range(\"1.1.0\" ..< \"2.0.0\"),\n                         isPositive: true\n                    )\n                ]),\n                cause: .noAvailableVersion\n            )\n            state.derive(Term(node: .root(package: aRef), requirement: .exact(\"1.1.0\"), isPositive: true), cause: cause) // no decision available on this which will throw it into an infinite loop\n            state.derive(Term(node: .root(package: bRef), requirement: .range(\"1.1.0\" ..< \"2.0.0\"), isPositive: true), cause: cause)\n        }\n\n        do {\n            let cause = Incompatibility(\n                terms: .init([\n                    Term(node: .root(package: aRef),\n                         requirement: .exact(\"1.1.0\"),\n                         isPositive: true\n                    ),\n                    Term(node: .root(package: bRef),\n                         requirement: .range(\"1.2.0\" ..< \"2.0.0\"),\n                         isPositive: true\n                    )\n                ]),\n                cause: .noAvailableVersion\n            )\n            state.derive(Term(node: .root(package: bRef), requirement: .range(\"1.2.0\" ..< \"2.0.0\"), isPositive: false), cause: cause)\n            state.derive(Term(node: .root(package: bRef), requirement: .exact(\"1.2.0\"), isPositive: false), cause: cause)\n            state.derive(Term(node: .root(package: bRef), requirement: .exact(\"1.1.0\"), isPositive: false), cause: cause)\n        }\n\n        let conflict = Incompatibility(\n            terms: .init([\n                Term(node: .root(package: aRef),\n                     requirement: .exact(\"1.1.0\"),\n                     isPositive: true\n                ),\n                Term(node: .root(package: bRef),\n                     requirement: .ranges([\"1.1.1\" ..< \"1.2.0\"]),\n                     isPositive: true\n                )\n            ]),\n            cause: .noAvailableVersion\n        )\n\n        XCTAssertThrowsError(try solver.resolve(state: state, conflict: conflict)) { error in\n            XCTAssertTrue(error is PubGrubDependencyResolver.PubGrubError)\n        }\n    }\n\n    func testResolutionNoConflicts() async throws {\n        try builder.serve(\"a\", at: v1, with: [\"a\": [\"b\": (.versionSet(v1Range), .specific([\"b\"]))]])\n        try builder.serve(\"b\", at: v1)\n        try builder.serve(\"b\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"b\", .version(v1))\n        ])\n    }\n\n    func testResolutionAvoidingConflictResolutionDuringDecisionMaking() async throws {\n        try builder.serve(\"a\", at: v1)\n        try builder.serve(\"a\", at: v1_1, with: [\"a\": [\"b\": (.versionSet(v2Range), .specific([\"b\"]))]])\n        try builder.serve(\"b\", at: v1)\n        try builder.serve(\"b\", at: v1_1)\n        try builder.serve(\"b\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n            \"b\": (.versionSet(v1Range), .specific([\"b\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"b\", .version(\"1.1.0\"))\n        ])\n    }\n\n    func testResolutionPerformingConflictResolution() async throws {\n        // PubGrub has a listed as >=1.0.0, which we can't really represent here.\n        // It's either .any or 1.0.0..<n.0.0 with n>2. Both should have the same\n        // effect though.\n        try builder.serve(\"a\", at: v1)\n        try builder.serve(\"a\", at: v2, with: [\"a\": [\"b\": (.versionSet(v1Range), .specific([\"b\"]))]])\n        try builder.serve(\"b\", at: v1, with: [\"b\": [\"a\": (.versionSet(v1Range), .specific([\"a\"]))]])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1to3Range), .specific([\"a\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1))\n        ])\n    }\n\n    func testResolutionConflictResolutionWithAPartialSatisfier() async throws {\n        try builder.serve(\"foo\", at: v1)\n        try builder.serve(\"foo\", at: v1_1, with: [\n            \"foo\": [\"left\": (.versionSet(v1Range), .specific([\"left\"]))],\n            \"foo\": [\"right\": (.versionSet(v1Range), .specific([\"right\"]))]\n        ])\n        try builder.serve(\"left\", at: v1, with: [\"left\": [\"shared\": (.versionSet(v1Range), .specific([\"shared\"]))]])\n        try builder.serve(\"right\", at: v1, with: [\"right\": [\"shared\": (.versionSet(v1Range), .specific([\"shared\"]))]])\n        try builder.serve(\"shared\", at: v1, with: [\"shared\": [\"target\": (.versionSet(v1Range), .specific([\"target\"]))]])\n        try builder.serve(\"shared\", at: v2)\n        try builder.serve(\"target\", at: v1)\n        try builder.serve(\"target\", at: v2)\n\n        // foo 1.1.0 transitively depends on a version of target that's not compatible\n        // with root's constraint. This dependency only exists because of left\n        // *and* right, choosing only one of these would be fine.\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"target\": (.versionSet(v2Range), .specific([\"target\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1)),\n            (\"target\", .version(v2))\n        ])\n    }\n\n    func testUsecase1() async throws {\n        try builder.serve(\"a\",\n                      at: \"1.0.0\",\n                      with: [\n                        \"a\": [\n                            \"b\": (.versionSet(.range(\"1.1.0\" ..< \"2.0.0\")), .everything),\n                            \"c\": (.versionSet(.range(\"1.2.1\" ..< \"2.0.0\")), .everything)\n                        ],\n                      ]\n        )\n\n        try builder.serve(\"b\",\n                      at: \"1.0.0\",\n                      with: [\n                        \"b\": [\n                            \"c\": (.versionSet(.range(\"1.3.1\" ..< \"2.0.0\")), .everything),\n                        ],\n                      ]\n        )\n        try builder.serve(\"b\",\n                      at: \"1.1.0\",\n                      with: [\n                        \"b\": [\n                            \"c\": (.versionSet(.range(\"1.4.1\" ..< \"2.0.0\")), .everything),\n                        ],\n                      ]\n        )\n\n        try builder.serve(\"c\",\n                      at: [\"1.0.0\", \"1.1.0\", \"1.2.0\", \"1.2.1\", \"1.3.0\", \"1.3.1\", \"1.4.0\", \"1.4.1\", \"2.0.0\", \"2.1.0\"],\n                      with: [\n                        \"c\": [\"d\": (.versionSet(v1Range), .everything)],\n                      ]\n        )\n\n        try builder.serve(\"d\", at: [\"1.0.0\", \"1.1.0\", \"1.1.1\", \"1.1.2\", \"1.2.0\", \"1.2.1\"])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1Range), .everything),\n            \"c\": (.versionSet(v1Range), .everything)\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"b\", .version(\"1.1.0\")),\n            (\"c\", .version(\"1.4.1\")),\n            (\"d\", .version(\"1.2.1\"))\n        ])\n    }\n\n    func testCycle1() async throws {\n        try builder.serve(\"foo\", at: v1_1, with: [\"foo\": [\"foo\": (.versionSet(v1Range), .specific([\"foo\"]))]])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1_1)),\n        ])\n    }\n\n    func testCycle2() async throws {\n        try builder.serve(\"foo\", at: v1_1, with: [\"foo\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: v1, with: [\"bar\": [\"baz\": (.versionSet(v1Range), .specific([\"baz\"]))]])\n        try builder.serve(\"baz\", at: v1, with: [\"baz\": [\"bam\": (.versionSet(v1Range), .specific([\"bam\"]))]])\n        try builder.serve(\"bam\", at: v1, with: [\"bam\": [\"baz\": (.versionSet(v1Range), .specific([\"baz\"]))]])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1_1)),\n            (\"bar\", .version(v1)),\n            (\"baz\", .version(v1)),\n            (\"bam\", .version(v1)),\n        ])\n    }\n\n    func testLocalPackageCycle() async throws {\n        try builder.serve(\"foo\", at: .unversioned, with: [\n            \"foo\": [\"bar\": (.unversioned, .specific([\"bar\"]))],\n        ])\n        try builder.serve(\"bar\", at: .unversioned, with: [\n            \"bar\": [\"baz\": (.unversioned, .specific([\"baz\"]))],\n        ])\n        try builder.serve(\"baz\", at: .unversioned, with: [\n            \"baz\": [\"foo\": (.unversioned, .specific([\"foo\"]))],\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.unversioned, .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .unversioned),\n            (\"bar\", .unversioned),\n            (\"baz\", .unversioned),\n        ])\n    }\n\n    func testBranchBasedPackageCycle() async throws {\n        try builder.serve(\"foo\", at: .revision(\"develop\"), with: [\n            \"foo\": [\"bar\": (.revision(\"develop\"), .specific([\"bar\"]))],\n        ])\n        try builder.serve(\"bar\", at: .revision(\"develop\"), with: [\n            \"bar\": [\"baz\": (.revision(\"develop\"), .specific([\"baz\"]))],\n        ])\n        try builder.serve(\"baz\", at: .revision(\"develop\"), with: [\n            \"baz\": [\"foo\": (.revision(\"develop\"), .specific([\"foo\"]))],\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.revision(\"develop\"), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .revision(\"develop\")),\n            (\"bar\", .revision(\"develop\")),\n            (\"baz\", .revision(\"develop\")),\n        ])\n    }\n\n    func testNonExistentPackage() async throws {\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"package\": (.versionSet(.exact(v1)), .specific([\"package\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertError(result, _MockLoadingError.unknownModule)\n    }\n\n    func testUnversioned1() async throws {\n        try builder.serve(\"foo\", at: .unversioned)\n        try builder.serve(\"bar\", at: v1_5)\n        try builder.serve(\"bar\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.unversioned, .specific([\"foo\"])),\n            \"bar\": (.versionSet(v1Range), .specific([\"bar\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .unversioned),\n            (\"bar\", .version(v1_5))\n        ])\n    }\n\n    func testUnversioned2() async throws {\n        try builder.serve(\"foo\", at: .unversioned, with: [\n            \"foo\": [\"bar\": (.versionSet(.range(v1..<\"1.2.0\")), .specific([\"bar\"]))]\n        ])\n        try builder.serve(\"bar\", at: v1)\n        try builder.serve(\"bar\", at: v1_1)\n        try builder.serve(\"bar\", at: v1_5)\n        try builder.serve(\"bar\", at: v2)\n\n        let resolver = builder.create()\n\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.unversioned, .specific([\"foo\"])),\n            \"bar\": (.versionSet(v1Range), .specific([\"bar\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .unversioned),\n            (\"bar\", .version(v1_1))\n        ])\n    }\n\n    func testUnversioned3() async throws {\n        try builder.serve(\"foo\", at: .unversioned)\n        try builder.serve(\"bar\", at: v1, with: [\n            \"bar\": [\"foo\": (.versionSet(.exact(v1)), .specific([\"foo\"]))]\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.unversioned, .specific([\"foo\"])),\n            \"bar\": (.versionSet(v1Range), .specific([\"bar\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .unversioned),\n            (\"bar\", .version(v1))\n        ])\n    }\n\n    func testUnversioned4() async throws {\n        try builder.serve(\"foo\", at: .unversioned)\n        try builder.serve(\"bar\", at: .revision(\"main\"), with: [\n            \"bar\": [\"foo\": (.versionSet(v1Range), .specific([\"foo\"]))]\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.unversioned, .specific([\"foo\"])),\n            \"bar\": (.revision(\"main\"), .specific([\"bar\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .unversioned),\n            (\"bar\", .revision(\"main\"))\n        ])\n    }\n\n    func testUnversioned5() async throws {\n        try builder.serve(\"foo\", at: .unversioned)\n        try builder.serve(\"foo\", at: .revision(\"main\"))\n        try builder.serve(\"bar\", at: .revision(\"main\"), with: [\n            \"bar\": [\"foo\": (.revision(\"main\"), .specific([\"foo\"]))]\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.unversioned, .specific([\"foo\"])),\n            \"bar\": (.revision(\"main\"), .specific([\"bar\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .unversioned),\n            (\"bar\", .revision(\"main\"))\n        ])\n    }\n\n    func testUnversioned7() async throws {\n        try builder.serve(\"local\", at: .unversioned, with: [\n            \"local\": [\"remote\": (.unversioned, .specific([\"remote\"]))]\n        ])\n        try builder.serve(\"remote\", at: .unversioned)\n        try builder.serve(\"remote\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"local\": (.unversioned, .specific([\"local\"])),\n            \"remote\": (.versionSet(v1Range), .specific([\"remote\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"remote\", .unversioned),\n            (\"local\", .unversioned)\n        ])\n    }\n\n    func testUnversioned8() async throws {\n        try builder.serve(\"entry\", at: .unversioned, with: [\n            \"entry\": [\n                \"remote\": (.versionSet(v1Range), .specific([\"remote\"])),\n                \"local\": (.unversioned, .specific([\"local\"])),\n            ]\n        ])\n        try builder.serve(\"local\", at: .unversioned, with: [\n            \"local\": [\"remote\": (.unversioned, .specific([\"remote\"]))]\n        ])\n        try builder.serve(\"remote\", at: .unversioned)\n        try builder.serve(\"remote\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"entry\": (.unversioned, .specific([\"entry\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"entry\", .unversioned),\n            (\"local\", .unversioned),\n            (\"remote\", .unversioned),\n        ])\n    }\n\n    func testUnversioned9() async throws {\n        try builder.serve(\"entry\", at: .unversioned, with: [\n            \"entry\": [\n                \"local\": (.unversioned, .specific([\"local\"])),\n                \"remote\": (.versionSet(v1Range), .specific([\"remote\"])),\n            ]\n        ])\n        try builder.serve(\"local\", at: .unversioned, with: [\n            \"local\": [\"remote\": (.unversioned, .specific([\"remote\"]))]\n        ])\n        try builder.serve(\"remote\", at: .unversioned)\n        try builder.serve(\"remote\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"entry\": (.unversioned, .specific([\"entry\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"entry\", .unversioned),\n            (\"local\", .unversioned),\n            (\"remote\", .unversioned),\n        ])\n    }\n\n    // root -> version -> version\n    // root -> version -> version\n    func testHappyPath1() async throws {\n        try builder.serve(\"foo\", at: v1_1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"bar\", at: v1_1, with: [\"bar\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.versionSet(v1Range), .specific([\"bar\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1_1)),\n            (\"bar\", .version(v1_1)),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n    // root -> version -> version\n    // root -> non-versioned -> version\n    func testHappyPath2() async throws {\n        try builder.serve(\"foo\", at: v1_1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at:  v1)\n        try builder.serve(\"config\", at:  v1_1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.unversioned, .specific([\"bar\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1_1)),\n            (\"bar\", .unversioned),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n    // root -> version -> version\n    // root -> non-versioned -> non-versioned -> version\n    func testHappyPath3() async throws {\n        try builder.serve(\"foo\", at: v1_1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"baz\": (.unversioned, .specific([\"baz\"]))]])\n        try builder.serve(\"baz\", at: .unversioned, with: [\"baz\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.unversioned, .specific([\"bar\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1_1)),\n            (\"bar\", .unversioned),\n            (\"baz\", .unversioned),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n    // root -> version\n    // root -> version -> version\n    func testHappyPath4() async throws {\n        try builder.serve(\"foo\", at: v1_1, with: [\"foo\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1_1)),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n    // root -> version\n    // root -> non-versioned -> version\n    func testHappyPath5() async throws {\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n            \"foo\": (.unversioned, .specific([\"foo\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .unversioned),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n    // root -> version\n    // root -> non-versioned -> non-versioned -> version\n    func testHappyPath6() async throws {\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"bar\": (.unversioned, .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n            \"foo\": (.unversioned, .specific([\"foo\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .unversioned),\n            (\"bar\", .unversioned),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n    // top level package -> version\n    // top level package -> version -> version\n    func testHappyPath7() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n                \"foo\": (.versionSet(v1Range), .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: v1_1, with: [\"foo\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"package\", .unversioned),\n            (\"foo\", .version(v1_1)),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n\n    // top level package -> version\n    // top level package -> non-versioned -> version\n    func testHappyPath8() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n                \"foo\": (.unversioned, .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"package\", .unversioned),\n            (\"foo\", .unversioned),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n    // top level package -> version\n    // top level package -> non-versioned -> non-versioned -> version\n    func testHappyPath9() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n                \"foo\": (.unversioned, .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"bar\": (.unversioned, .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"baz\": (.unversioned, .specific([\"baz\"]))]])\n        try builder.serve(\"baz\", at: .unversioned, with: [\"baz\": [\"config\": (.versionSet(v1_1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"package\", .unversioned),\n            (\"foo\", .unversioned),\n            (\"bar\", .unversioned),\n            (\"baz\", .unversioned),\n            (\"config\", .version(v1_1)),\n        ])\n    }\n\n    // top level package -> beta version\n    //  beta version -> version\n    func testHappyPath10() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"foo\": (.versionSet(.range(\"1.0.0-alpha\" ..< \"2.0.0\")), .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: \"1.0.0-alpha.1\", with: [\"foo\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n        try builder.serve(\"foo\", at: \"1.0.0-alpha.2\", with: [\"foo\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n        try builder.serve(\"foo\", at: \"1.0.0-beta.1\", with: [\"foo\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n        try builder.serve(\"foo\", at: \"1.0.0-beta.2\", with: [\"foo\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n        try builder.serve(\"foo\", at: \"1.0.0-beta.3\", with: [\"foo\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: v1)\n        try builder.serve(\"bar\", at: v1_1)\n        try builder.serve(\"bar\", at: v1_5)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"package\", .unversioned),\n            (\"foo\", .version(\"1.0.0-beta.3\")),\n            (\"bar\", .version(v1_5))\n        ])\n    }\n\n    func testResolutionWithSimpleBranchBasedDependency() async throws {\n        try builder.serve(\"foo\", at: .revision(\"main\"), with: [\"foo\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.revision(\"main\"), .specific([\"foo\"])),\n            \"bar\": (.versionSet(v1Range), .specific([\"bar\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .revision(\"main\")),\n            (\"bar\", .version(v1))\n        ])\n    }\n\n    func testResolutionWithSimpleBranchBasedDependency2() async throws {\n        try builder.serve(\"foo\", at: .revision(\"main\"), with: [\"foo\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.revision(\"main\"), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .revision(\"main\")),\n            (\"bar\", .version(v1))\n        ])\n    }\n\n    func testResolutionWithOverridingBranchBasedDependency() async throws {\n        try builder.serve(\"foo\", at: .revision(\"main\"))\n        try builder.serve(\"bar\", at: v1, with: [\"bar\": [\"foo\": (.versionSet(v1Range), .specific([\"foo\"]))]])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.revision(\"main\"), .specific([\"foo\"])),\n            \"bar\": (.versionSet(.exact(v1)), .specific([\"bar\"])),\n\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .revision(\"main\")),\n            (\"bar\", .version(v1))\n        ])\n    }\n\n    func testResolutionWithOverridingBranchBasedDependency2() async throws {\n        try builder.serve(\"foo\", at: .revision(\"main\"))\n        try builder.serve(\"bar\", at: v1, with: [\"bar\": [\"foo\": (.versionSet(v1Range), .specific([\"foo\"]))]])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"bar\": (.versionSet(.exact(v1)), .specific([\"bar\"])),\n            \"foo\": (.revision(\"main\"), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .revision(\"main\")),\n            (\"bar\", .version(v1))\n        ])\n    }\n\n    func testResolutionWithOverridingBranchBasedDependency3() async throws {\n        try builder.serve(\"foo\", at: .revision(\"main\"), with: [\"foo\": [\"bar\": (.revision(\"main\"), .specific([\"bar\"]))]])\n\n        try builder.serve(\"bar\", at: .revision(\"main\"))\n        try builder.serve(\"bar\", at: v1)\n\n        try builder.serve(\"baz\", at: .revision(\"main\"), with: [\"baz\": [\"bar\": (.versionSet(v1Range), .specific([\"bar\"]))]])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.revision(\"main\"), .specific([\"foo\"])),\n            \"baz\": (.revision(\"main\"), .specific([\"baz\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .revision(\"main\")),\n            (\"bar\", .revision(\"main\")),\n            (\"baz\", .revision(\"main\")),\n        ])\n    }\n\n    func testResolutionWithUnavailableRevision() async throws {\n        try builder.serve(\"foo\", at: .version(v1))\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.revision(\"main\"), .specific([\"foo\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertError(result, _MockLoadingError.unknownRevision)\n    }\n\n    func testResolutionWithRevisionConflict() async throws {\n        try builder.serve(\"foo\", at: .revision(\"main\"), with: [\"foo\": [\"bar\": (.revision(\"main\"), .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: .version(v1))\n        try builder.serve(\"bar\", at: .revision(\"main\"))\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"bar\": (.versionSet(v1Range), .specific([\"bar\"])),\n            \"foo\": (.revision(\"main\"), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .revision(\"main\")),\n            (\"bar\", .revision(\"main\")),\n        ])\n    }\n\n    func testBranchOverriding3() async throws {\n        try builder.serve(\"swift-nio\", at: v1)\n        try builder.serve(\"swift-nio\", at: .revision(\"main\"))\n        try builder.serve(\"swift-nio-ssl\", at: .revision(\"main\"), with: [\n            \"swift-nio-ssl\": [\"swift-nio\": (.versionSet(v2Range), .specific([\"swift-nio\"]))],\n        ])\n        try builder.serve(\"foo\", at: \"1.0.0\", with: [\n            \"foo\": [\"swift-nio\": (.versionSet(v1Range), .specific([\"swift-nio\"]))],\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"swift-nio\": (.revision(\"main\"), .specific([\"swift-nio\"])),\n            \"swift-nio-ssl\": (.revision(\"main\"), .specific([\"swift-nio-ssl\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"swift-nio-ssl\", .revision(\"main\")),\n            (\"swift-nio\", .revision(\"main\")),\n            (\"foo\", .version(v1))\n        ])\n    }\n\n    func testBranchOverriding4() async throws {\n        try builder.serve(\"swift-nio\", at: v1)\n        try builder.serve(\"swift-nio\", at: .revision(\"main\"))\n        try builder.serve(\"swift-nio-ssl\", at: .revision(\"main\"), with: [\n            \"swift-nio-ssl\": [\"swift-nio\": (.versionSet(v2Range), .specific([\"swift-nio\"]))],\n        ])\n        try builder.serve(\"nio-postgres\", at: .revision(\"main\"), with: [\n            \"nio-postgres\": [\n                \"swift-nio\": (.revision(\"main\"), .specific([\"swift-nio\"])),\n                \"swift-nio-ssl\": (.revision(\"main\"), .specific([\"swift-nio-ssl\"])),\n            ]\n        ])\n        try builder.serve(\"http-client\", at: v1, with: [\n            \"http-client\": [\n                \"swift-nio\": (.versionSet(v1Range), .specific([\"swift-nio\"])),\n                \"boring-ssl\": (.versionSet(v1Range), .specific([\"boring-ssl\"])),\n            ]\n        ])\n        try builder.serve(\"boring-ssl\", at: v1, with: [\n            \"boring-ssl\": [\"swift-nio\": (.versionSet(v1Range), .specific([\"swift-nio\"]))],\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"nio-postgres\": (.revision(\"main\"), .specific([\"nio-postgres\"])),\n            \"http-client\": (.versionSet(v1Range), .specific([\"https-client\"])),\n            \"boring-ssl\": (.versionSet(v1Range), .specific([\"boring-ssl\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"swift-nio-ssl\", .revision(\"main\")),\n            (\"swift-nio\", .revision(\"main\")),\n            (\"nio-postgres\", .revision(\"main\")),\n            (\"http-client\", .version(v1)),\n            (\"boring-ssl\", .version(v1)),\n        ])\n    }\n\n    func testNonVersionDependencyInVersionDependency2() async throws {\n        try builder.serve(\"foo\", at: v1_1, with: [\n            \"foo\": [\"bar\": (.revision(\"main\"), .specific([\"bar\"]))]\n        ])\n        try builder.serve(\"foo\", at: v1)\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1)),\n        ])\n    }\n\n    func testTrivialResolvedPackagesStore() async throws {\n        try builder.serve(\"a\", at: v1, with: [\"a\": [\"b\": (.versionSet(v1Range), .specific([\"b\"]))]])\n        try builder.serve(\"a\", at: v1_1)\n        try builder.serve(\"b\", at: v1)\n        try builder.serve(\"b\", at: v1_1)\n        try builder.serve(\"b\", at: v2)\n\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n        ])\n\n        let resolvedPackagesStore = try builder.create(resolvedPackages: [\n            \"a\": (.version(v1), .specific([\"a\"])),\n            \"b\": (.version(v1), .specific([\"b\"])),\n        ])\n\n        let resolver = builder.create(resolvedPackages: resolvedPackagesStore.resolvedPackages)\n        let result = try await resolver.solve(root: rootNode, constraints: dependencies)\n\n        // Since a was pinned, we shouldn't have computed bounds for its incompatibilities.\n        let aIncompat = result.state.positiveIncompatibilities(for: .product(\"a\", package: try builder.reference(for: \"a\")))![0]\n        XCTAssertEqual(aIncompat.terms[0].requirement, .exact(\"1.0.0\"))\n\n        AssertResult(Result.success(result.bindings), [\n            (\"a\", .version(v1)),\n            (\"b\", .version(v1))\n        ])\n    }\n\n    func testPartialResolvedPackages() async throws {\n        // This checks that we can drop resolved packages that are not valid anymore but still keep the ones\n        // which fit the constraints.\n        try builder.serve(\"a\", at: v1, with: [\"a\": [\"b\": (.versionSet(v1Range), .specific([\"b\"]))]])\n        try builder.serve(\"a\", at: v1_1)\n        try builder.serve(\"b\", at: v1)\n        try builder.serve(\"b\", at: v1_1)\n        try builder.serve(\"c\", at: v1, with: [\"c\": [\"b\": (.versionSet(.range(v1_1..<v2)), .specific([\"b\"]))]])\n\n        let dependencies = try builder.create(dependencies: [\n            \"c\": (.versionSet(v1Range), .specific([\"c\"])),\n            \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n        ])\n\n        // Here b is pinned to v1 but its requirement is now 1.1.0..<2.0.0 in the graph\n        // due to addition of a new dependency.\n        let resolvedPackagesStore = try builder.create(resolvedPackages: [\n            \"a\": (.version(v1), .specific([\"a\"])),\n            \"b\": (.version(v1), .specific([\"b\"])),\n        ])\n\n        let resolver = builder.create(resolvedPackages: resolvedPackagesStore.resolvedPackages)\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"b\", .version(v1_1)),\n            (\"c\", .version(v1))\n        ])\n    }\n\n    func testMissingResolvedPackage() async throws {\n        // This checks that we can drop resolved packages that are no longer available but still keep the ones\n        // which fit the constraints.\n        try builder.serve(\"a\", at: v1, with: [\"a\": [\"b\": (.versionSet(v1Range), .specific([\"b\"]))]])\n        try builder.serve(\"a\", at: v1_1)\n        try builder.serve(\"b\", at: v1)\n        try builder.serve(\"b\", at: v1_1)\n\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n        ])\n\n        // Here c is pinned to v1.1, but it is no longer available, so the resolver should fall back\n        // to v1.\n        let resolvedPackagesStore = try builder.create(resolvedPackages: [\n            \"a\": (.version(v1), .specific([\"a\"])),\n            \"b\": (.version(\"1.2.0\"), .specific([\"b\"])),\n        ])\n\n        let resolver = builder.create(resolvedPackages: resolvedPackagesStore.resolvedPackages)\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"b\", .version(v1_1)),\n        ])\n    }\n\n    func testBranchBasedResolvedPackage() async throws {\n        // This test ensures that we get the SHA listed in Package.resolved for branch-based\n        // dependencies.\n        try builder.serve(\"a\", at: .revision(\"develop-sha-1\"))\n        try builder.serve(\"b\", at: .revision(\"main-sha-2\"))\n\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.revision(\"develop\"), .specific([\"a\"])),\n            \"b\": (.revision(\"main\"), .specific([\"b\"])),\n        ])\n\n        let resolvedPackagesStore = try builder.create(resolvedPackages: [\n            \"a\": (.branch(name: \"develop\", revision: \"develop-sha-1\"), .specific([\"a\"])),\n            \"b\": (.branch(name: \"main\", revision: \"main-sha-2\"), .specific([\"b\"])),\n        ])\n\n        let resolver = builder.create(resolvedPackages: resolvedPackagesStore.resolvedPackages)\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .revision(\"develop-sha-1\", branch: \"develop\")),\n            (\"b\", .revision(\"main-sha-2\", branch: \"main\")),\n        ])\n    }\n\n    func testIncompatibleToolsVersion2() async throws {\n        try builder.serve(\"a\", at: v1_1, toolsVersion: ToolsVersion.v5)\n        try builder.serve(\"a\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n        ])\n    }\n\n    func testUnreachableProductsSkipped() async throws {\n        #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        try builder.serve(\"root\", at: .unversioned, with: [\n            \"root\": [\"immediate\": (.versionSet(v1Range), .specific([\"ImmediateUsed\"]))]\n        ])\n        try builder.serve(\"immediate\", at: v1, with: [\n            \"ImmediateUsed\": [\"transitive\": (.versionSet(v1Range), .specific([\"TransitiveUsed\"]))],\n            \"ImmediateUnused\": [\n                \"transitive\": (.versionSet(v1Range), .specific([\"TransitiveUnused\"])),\n                \"nonexistent\": (.versionSet(v1Range), .specific([\"Nonexistent\"]))\n            ]\n        ])\n        try builder.serve(\"transitive\", at: v1, with: [\n            \"TransitiveUsed\": [:],\n            \"TransitiveUnused\": [\n                \"nonexistent\": (.versionSet(v1Range), .specific([\"Nonexistent\"]))\n            ]\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"root\": (.unversioned, .everything)\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"root\", .unversioned),\n            (\"immediate\", .version(v1)),\n            (\"transitive\", .version(v1))\n        ])\n    }\n\n    func testDelegate() async throws {\n        class TestDelegate: DependencyResolverDelegate {\n            var events = [String]()\n            let lock = NSLock()\n\n            func willResolve(term: Term) {\n                self.lock.withLock {\n                    self.events.append(\"willResolve '\\(term.node.package.identity)'\")\n                }\n            }\n\n            func didResolve(term: Term, version: Version, duration: DispatchTimeInterval) {\n                self.lock.withLock {\n                    self.events.append(\"didResolve '\\(term.node.package.identity)' at '\\(version)'\")\n                }\n            }\n\n            func derived(term: Term) {}\n\n            func conflict(conflict: Incompatibility) {}\n\n            func satisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility) {}\n\n            func partiallySatisfied(term: Term, by assignment: Assignment, incompatibility: Incompatibility, difference: Term) {}\n\n            func failedToResolve(incompatibility: Incompatibility) {}\n\n            func solved(result: [DependencyResolverBinding]) {\n                let decisions = result.sorted(by: { $0.package.identity < $1.package.identity }).map { \"'\\($0.package.identity)' at '\\($0.boundVersion)'\" }\n                self.lock.withLock {\n                    self.events.append(\"solved: \\(decisions.joined(separator: \", \"))\")\n                }\n            }\n        }\n\n        try builder.serve(\"foo\", at: \"1.0.0\")\n        try builder.serve(\"foo\", at: \"1.1.0\")\n        try builder.serve(\"foo\", at: \"2.0.0\")\n        try builder.serve(\"foo\", at: \"2.0.1\")\n\n        try builder.serve(\"bar\", at: \"1.0.0\")\n        try builder.serve(\"bar\", at: \"1.1.0\")\n        try builder.serve(\"bar\", at: \"2.0.0\")\n        try builder.serve(\"bar\", at: \"2.0.1\")\n\n        let delegate = TestDelegate()\n        let resolver = builder.create(delegate: delegate)\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.versionSet(v2Range), .specific([\"bar\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(\"1.1.0\")),\n            (\"bar\", .version(\"2.0.1\")),\n        ])\n\n        XCTAssertMatch(delegate.events, [\"willResolve 'foo'\"])\n        XCTAssertMatch(delegate.events, [\"didResolve 'foo' at '1.1.0'\"])\n        XCTAssertMatch(delegate.events, [\"willResolve 'bar'\"])\n        XCTAssertMatch(delegate.events, [\"didResolve 'bar' at '2.0.1'\"])\n        XCTAssertMatch(delegate.events, [\"solved: 'bar' at '2.0.1', 'foo' at '1.1.0'\"])\n    }\n\n    func testPubGrubPackageContainerCacheParameterization() async throws {\n        let container = PubGrubPackageContainer(\n            underlying: try MockPackageContainer(\n                name: \"Package\",\n                dependenciesByProductFilter: [\n                    .specific([\"FilterA\"]): [(\n                        container: \"DependencyA\",\n                        versionRequirement: .exact(Version(1, 0, 0))\n                    )],\n                    .specific([\"FilterB\"]): [(\n                        container: \"DependencyB\",\n                        versionRequirement: .exact(Version(1, 0, 0))\n                    )]\n                ]),\n            resolvedPackages: ResolvedPackagesStore.ResolvedPackages()\n        )\n        let rootLocation = AbsolutePath(\"/Root\")\n        let otherLocation = AbsolutePath(\"/Other\")\n        let dependencyALocation = AbsolutePath(\"/DependencyA\")\n        let dependencyBLocation = AbsolutePath(\"/DependencyB\")\n        let root = PackageReference(identity: PackageIdentity(path: rootLocation), kind: .fileSystem(rootLocation))\n        let other = PackageReference.localSourceControl(identity: .init(path: otherLocation), path: otherLocation)\n        let dependencyA = PackageReference.localSourceControl(identity: .init(path: dependencyALocation), path: dependencyALocation)\n        let dependencyB = PackageReference.localSourceControl(identity: .init(path: dependencyBLocation), path: dependencyBLocation)\n        let result = try await container.incompatibilites(\n            at: Version(1, 0, 0),\n            node: .product(\n                \"FilterA\",\n                package: other\n            ),\n            overriddenPackages: [:],\n            root: .root(package: root)\n        )\n        XCTAssertEqual(\n            result,\n            [\n                Incompatibility(\n                    terms: [\n                        Term(\n                            node: .product(\"FilterA\", package: other), requirement: .exact(Version(1, 0, 0)),\n                            isPositive: true\n                        ),\n                        Term(\n                            node: .product(\"FilterA\", package: dependencyA), requirement: .exact(Version(1, 0, 0)),\n                            isPositive: false\n                        )\n                    ],\n                    cause: .dependency(node: .product(\"FilterA\", package: other))\n                ),\n                Incompatibility(\n                    terms: [\n                        Term(\n                            node: .product(\"FilterA\", package: other), requirement: .exact(Version(1, 0, 0)),\n                            isPositive: true\n                        ),\n                        Term(\n                            node: .empty(package: other), requirement: .exact(Version(1, 0, 0)),\n                            isPositive: false\n                        ),\n                    ],\n                    cause: .dependency(node: .product(\"FilterA\", package: other))\n                )\n            ]\n        )\n        let result2 = try await container.incompatibilites(\n            at: Version(1, 0, 0),\n            node: .product(\n                \"FilterB\",\n                package: other\n            ),\n            overriddenPackages: [:],\n            root: .root(package: root)\n        )\n        XCTAssertEqual(\n            result2,\n            [\n                Incompatibility(\n                    terms: [\n                        Term(\n                            node: .product(\"FilterB\", package: other), requirement: .exact(Version(1, 0, 0)),\n                            isPositive: true\n                        ),\n                        Term(\n                            node: .product(\"FilterB\", package: dependencyB), requirement: .exact(Version(1, 0, 0)),\n                            isPositive: false\n                        )\n                    ],\n                    cause: .dependency(node: .product(\"FilterB\", package: other))\n                ),\n                Incompatibility(\n                    terms: [\n                        Term(\n                            node: .product(\"FilterB\", package: other), requirement: .exact(Version(1, 0, 0)),\n                            isPositive: true\n                        ),\n                        Term(\n                            node: .empty(package: other), requirement: .exact(Version(1, 0, 0)),\n                            isPositive: false\n                        ),\n                    ],\n                    cause: .dependency(node: .product(\"FilterB\", package: other))\n                )\n            ]\n        )\n    }\n}\n\nfinal class PubGrubTestsBasicGraphs: XCTestCase {\n    func testSimple1() async throws {\n        try builder.serve(\"a\", at: v1, with: [\n            \"a\": [\n                \"aa\": (.versionSet(.exact(\"1.0.0\")), .specific([\"aa\"])),\n                \"ab\": (.versionSet(.exact(\"1.0.0\")), .specific([\"ab\"])),\n            ]\n        ])\n        try builder.serve(\"aa\", at: v1)\n        try builder.serve(\"ab\", at: v1)\n        try builder.serve(\"b\", at: v1, with: [\n            \"b\": [\n                \"ba\": (.versionSet(.exact(\"1.0.0\")), .specific([\"ba\"])),\n                \"bb\": (.versionSet(.exact(\"1.0.0\")), .specific([\"bb\"])),\n            ]\n        ])\n        try builder.serve(\"ba\", at: v1)\n        try builder.serve(\"bb\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"])),\n            \"b\": (.versionSet(.exact(\"1.0.0\")), .specific([\"b\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"aa\", .version(v1)),\n            (\"ab\", .version(v1)),\n            (\"b\", .version(v1)),\n            (\"ba\", .version(v1)),\n            (\"bb\", .version(v1)),\n        ])\n    }\n\n    func testSharedDependency1() async throws {\n        try builder.serve(\"a\", at: v1, with: [\n            \"a\": [\"shared\": (.versionSet(.range(\"2.0.0\"..<\"4.0.0\")), .specific([\"shared\"]))],\n        ])\n        try builder.serve(\"b\", at: v1, with: [\n            \"b\": [\"shared\": (.versionSet(.range(\"3.0.0\"..<\"5.0.0\")), .specific([\"shared\"]))],\n        ])\n        try builder.serve(\"shared\", at: \"2.0.0\")\n        try builder.serve(\"shared\", at: \"3.0.0\")\n        try builder.serve(\"shared\", at: \"3.6.9\")\n        try builder.serve(\"shared\", at: \"4.0.0\")\n        try builder.serve(\"shared\", at: \"5.0.0\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"])),\n            \"b\": (.versionSet(.exact(\"1.0.0\")), .specific([\"b\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"b\", .version(v1)),\n            (\"shared\", .version(\"3.6.9\")),\n        ])\n    }\n\n    func testSharedDependency2() async throws {\n        try builder.serve(\"foo\", at: \"1.0.0\")\n        try builder.serve(\"foo\", at: \"1.0.1\", with: [\n            \"foo\": [\"bang\": (.versionSet(.exact(\"1.0.0\")), .specific([\"bang\"]))],\n        ])\n        try builder.serve(\"foo\", at: \"1.0.2\", with: [\n            \"foo\": [\"whoop\": (.versionSet(.exact(\"1.0.0\")), .specific([\"whoop\"]))],\n        ])\n        try builder.serve(\"foo\", at: \"1.0.3\", with: [\n            \"foo\": [\"zoop\": (.versionSet(.exact(\"1.0.0\")), .specific([\"zoop\"]))],\n        ])\n        try builder.serve(\"bar\", at: \"1.0.0\", with: [\n            \"bar\": [\"foo\": (.versionSet(.range(\"0.0.0\"..<\"1.0.2\")), .specific([\"foo\"]))],\n        ])\n        try builder.serve(\"bang\", at: \"1.0.0\")\n        try builder.serve(\"whoop\", at: \"1.0.0\")\n        try builder.serve(\"zoop\", at: \"1.0.0\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(.range(\"0.0.0\"..<\"1.0.3\")), .specific([\"foo\"])),\n            \"bar\": (.versionSet(.exact(\"1.0.0\")), .specific([\"bar\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n        AssertResult(result, [\n            (\"foo\", .version(\"1.0.1\")),\n            (\"bar\", .version(v1)),\n            (\"bang\", .version(v1)),\n        ])\n    }\n\n    func testFallbacksToOlderVersion() async throws {\n        try builder.serve(\"foo\", at: \"1.0.0\")\n        try builder.serve(\"foo\", at: \"2.0.0\")\n        try builder.serve(\"bar\", at: \"1.0.0\")\n        try builder.serve(\"bar\", at: \"2.0.0\", with: [\n            \"bar\": [\"baz\": (.versionSet(.exact(\"1.0.0\")), .specific([\"baz\"]))],\n        ])\n        try builder.serve(\"baz\", at: \"1.0.0\", with: [\n            \"baz\": [\"foo\": (.versionSet(.exact(\"2.0.0\")), .specific([\"foo\"]))],\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"bar\": (.versionSet(.range(\"0.0.0\"..<\"5.0.0\")), .specific([\"bar\"])),\n            \"foo\": (.versionSet(.exact(\"1.0.0\")), .specific([\"foo\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n        AssertResult(result, [\n            (\"foo\", .version(v1)),\n            (\"bar\", .version(v1)),\n        ])\n    }\n}\n\nfinal class PubGrubDiagnosticsTests: XCTestCase {\n\n    func testMissingVersion() async throws {\n        try builder.serve(\"package\", at: v1_1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"package\": (.versionSet(v2Range), .specific([\"package\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because no versions of 'package' match the requirement 2.0.0..<3.0.0 and root depends on 'package' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    func testResolutionNonExistentVersion() async throws {\n        try builder.serve(\"package\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"package\": (.versionSet(.exact(v1)), .specific([\"package\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because no versions of 'package' match the requirement 1.0.0 and root depends on 'package' 1.0.0.\n            \"\"\")\n    }\n\n    func testResolutionNonExistentBetaVersion() async throws {\n        try builder.serve(\"package\", at: \"0.0.1\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"package\": (.versionSet(.range(\"1.0.0-beta\" ..< \"2.0.0\")), .specific([\"package\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because no versions of 'package' match the requirement 1.0.0-beta..<2.0.0 and root depends on 'package' 1.0.0-beta..<2.0.0.\n            \"\"\")\n    }\n\n    func testResolutionNonExistentTransitiveVersion() async throws {\n        try builder.serve(\"package\", at: v1_5, with: [\n            \"package\": [\"foo\": (.versionSet(v1Range), .specific([\"foo\"]))]\n        ])\n        try builder.serve(\"foo\", at: \"0.0.1\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"package\": (.versionSet(v1Range), .specific([\"package\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because no versions of 'foo' match the requirement 1.0.0..<2.0.0 and root depends on 'package' 1.0.0..<2.0.0.\n            'package' practically depends on 'foo' 1.0.0..<2.0.0 because no versions of 'package' match the requirement {1.0.0..<1.5.0, 1.5.1..<2.0.0} and 'package' 1.5.0 depends on 'foo' 1.0.0..<2.0.0.\n            \"\"\")\n    }\n\n    func testResolutionNonExistentTransitiveBetaVersion() async throws {\n        try builder.serve(\"package\", at: v1_5, with: [\n            \"package\": [\"foo\": (.versionSet(.range(\"1.0.0-beta\" ..< \"2.0.0\")), .specific([\"foo\"]))]\n        ])\n        try builder.serve(\"foo\", at: \"0.0.1\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"package\": (.versionSet(v1Range), .specific([\"package\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because no versions of 'foo' match the requirement 1.0.0-beta..<2.0.0 and root depends on 'package' 1.0.0..<2.0.0.\n            'package' practically depends on 'foo' 1.0.0-beta..<2.0.0 because no versions of 'package' match the requirement {1.0.0..<1.5.0, 1.5.1..<2.0.0} and 'package' 1.5.0 depends on 'foo' 1.0.0-beta..<2.0.0.\n            \"\"\")\n    }\n\n    func testResolutionBetaVersionNonExistentTransitiveVersion() async throws {\n        try builder.serve(\"package\", at: \"1.0.0-beta.1\", with: [\n            \"package\": [\"foo\": (.versionSet(v1Range), .specific([\"foo\"]))]\n        ])\n        try builder.serve(\"foo\", at: \"0.0.1\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"package\": (.versionSet(.range(\"1.0.0-beta\" ..< \"2.0.0\")), .specific([\"package\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because no versions of 'foo' match the requirement 1.0.0..<2.0.0 and root depends on 'package' 1.0.0-beta..<2.0.0.\n            'package' practically depends on 'foo' 1.0.0..<2.0.0 because no versions of 'package' match the requirement {1.0.0-beta..<1.0.0-beta.1, 1.0.0-beta.1.0..<2.0.0} and 'package' 1.0.0-beta.1 depends on 'foo' 1.0.0..<2.0.0.\n            \"\"\")\n    }\n\n    func testResolutionLinearErrorReporting() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"bar\": (.versionSet(v2Range), .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: v2, with: [\"bar\": [\"baz\": (.versionSet(.range(\"3.0.0\"..<\"4.0.0\")), .specific([\"baz\"]))]])\n        try builder.serve(\"baz\", at: v1)\n        try builder.serve(\"baz\", at: \"3.0.0\")\n\n        // root transitively depends on a version of baz that's not compatible\n        // with root's constraint.\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"baz\": (.versionSet(v1Range), .specific([\"baz\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'foo' 1.0.0..<2.0.0 and root depends on 'baz' 1.0.0..<2.0.0.\n            'foo' >= 1.0.0 practically depends on 'baz' 3.0.0..<4.0.0.\n            'bar' >= 2.0.0 practically depends on 'baz' 3.0.0..<4.0.0 because 'bar' 2.0.0 depends on 'baz' 3.0.0..<4.0.0 and no versions of 'bar' match the requirement 2.0.1..<3.0.0.\n            'foo' >= 1.0.0 practically depends on 'bar' 2.0.0..<3.0.0 because 'foo' 1.0.0 depends on 'bar' 2.0.0..<3.0.0 and no versions of 'foo' match the requirement 1.0.1..<2.0.0.\n            \"\"\")\n    }\n\n    func testResolutionBranchingErrorReporting() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\n            \"foo\": [\n                \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n                \"b\": (.versionSet(v1Range), .specific([\"b\"]))\n            ]\n        ])\n        try builder.serve(\"foo\", at: v1_1, with: [\n            \"foo\": [\n                \"x\": (.versionSet(v1Range), .specific([\"x\"])),\n                \"y\": (.versionSet(v1Range), .specific([\"y\"]))\n            ]\n        ])\n        try builder.serve(\"a\", at: v1, with: [\"a\": [\"b\": (.versionSet(v2Range), .specific([\"b\"]))]])\n        try builder.serve(\"b\", at: v1)\n        try builder.serve(\"b\", at: v2)\n        try builder.serve(\"x\", at: v1, with: [\"x\": [\"y\": (.versionSet(v2Range), .specific([\"y\"]))]])\n        try builder.serve(\"y\", at: v1)\n        try builder.serve(\"y\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        print(result.errorMsg!)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n              Dependencies could not be resolved because root depends on 'foo' 1.0.0..<2.0.0.\n              'foo' >= 1.0.0 cannot be used because 'foo' {1.0.0..<1.1.0, 1.1.1..<2.0.0} cannot be used (1).\n              'foo' 1.1.0 cannot be used because 'foo' 1.1.0 depends on 'x' 1.0.0..<2.0.0 and 'foo' 1.1.0 depends on 'y' 1.0.0..<2.0.0.\n              'x' >= 1.0.0 practically depends on 'y' 2.0.0..<3.0.0 because 'x' 1.0.0 depends on 'y' 2.0.0..<3.0.0 and no versions of 'x' match the requirement 1.0.1..<2.0.0.\n              'foo' 1.0.0 practically depends on 'b' 2.0.0..<3.0.0 because 'foo' 1.0.0 depends on 'a' 1.0.0..<2.0.0.\n              'a' >= 1.0.0 practically depends on 'b' 2.0.0..<3.0.0 because 'a' 1.0.0 depends on 'b' 2.0.0..<3.0.0 and no versions of 'a' match the requirement 1.0.1..<2.0.0.\n                 (1) As a result, 'foo' {1.0.0..<1.1.0, 1.1.1..<2.0.0} cannot be used because 'foo' 1.0.0 depends on 'b' 1.0.0..<2.0.0 and no versions of 'foo' match the requirement {1.0.1..<1.1.0, 1.1.1..<2.0.0}.\n            \"\"\")\n    }\n\n    func testConflict1() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"bar\", at: v1, with: [\"bar\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.versionSet(v1Range), .specific([\"bar\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'foo' 1.0.0..<2.0.0 and root depends on 'bar' 1.0.0..<2.0.0.\n            'bar' is incompatible with 'foo' because 'foo' 1.0.0 depends on 'config' 1.0.0..<2.0.0 and no versions of 'foo' match the requirement 1.0.1..<2.0.0.\n            'bar' >= 1.0.0 practically depends on 'config' 2.0.0..<3.0.0 because no versions of 'bar' match the requirement 1.0.1..<2.0.0 and 'bar' 1.0.0 depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    func testConflict2() async throws {\n        func addDeps() async throws {\n            try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n            try builder.serve(\"config\", at: v1)\n            try builder.serve(\"config\", at: v2)\n        }\n\n        let dependencies1 = try builder.create(dependencies: [\n            \"config\": (.versionSet(v2Range), .specific([\"config\"])),\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n        ])\n        try await addDeps()\n        let resolver1 = builder.create()\n        let result1 = await resolver1.solve(constraints: dependencies1)\n\n        XCTAssertEqual(result1.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'config' 2.0.0..<3.0.0 and root depends on 'foo' 1.0.0..<2.0.0.\n            'foo' >= 1.0.0 practically depends on 'config' 1.0.0..<2.0.0 because no versions of 'foo' match the requirement 1.0.1..<2.0.0 and 'foo' 1.0.0 depends on 'config' 1.0.0..<2.0.0.\n            \"\"\")\n\n        let dependencies2 = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"config\": (.versionSet(v2Range), .specific([\"config\"])),\n        ])\n        try await addDeps()\n        let resolver2 = builder.create()\n        let result2 = await resolver2.solve(constraints: dependencies2)\n\n        XCTAssertEqual(result2.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'foo' 1.0.0..<2.0.0 and root depends on 'config' 2.0.0..<3.0.0.\n            'foo' >= 1.0.0 practically depends on 'config' 1.0.0..<2.0.0 because 'foo' 1.0.0 depends on 'config' 1.0.0..<2.0.0 and no versions of 'foo' match the requirement 1.0.1..<2.0.0.\n            \"\"\")\n    }\n\n    func testConflict3() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"config\": (.versionSet(v2Range), .specific([\"config\"])),\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because no versions of 'config' match the requirement 2.0.0..<3.0.0 and root depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    func testConflict4() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\n            \"foo\": [\"shared\": (.versionSet(.range(\"2.0.0\"..<\"3.0.0\")), .specific([\"shared\"]))],\n        ])\n        try builder.serve(\"bar\", at: v1, with: [\n            \"bar\": [\"shared\": (.versionSet(.range(\"2.9.0\"..<\"4.0.0\")), .specific([\"shared\"]))],\n        ])\n        try builder.serve(\"shared\", at: \"2.5.0\")\n        try builder.serve(\"shared\", at: \"3.5.0\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"bar\": (.versionSet(.exact(v1)), .specific([\"bar\"])),\n            \"foo\": (.versionSet(.exact(v1)), .specific([\"foo\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'bar' 1.0.0 and root depends on 'foo' 1.0.0.\n            'foo' is incompatible with 'bar' because 'foo' 1.0.0 depends on 'shared' 2.0.0..<3.0.0.\n            'bar' 1.0.0 practically depends on 'shared' 3.0.0..<4.0.0 because 'bar' 1.0.0 depends on 'shared' 2.9.0..<4.0.0 and no versions of 'shared' match the requirement 2.9.0..<3.0.0.\n            \"\"\")\n    }\n\n    func testConflict5() async throws {\n        try builder.serve(\"a\", at: v1, with: [\n            \"a\": [\"b\": (.versionSet(.exact(\"1.0.0\")), .specific([\"b\"]))],\n        ])\n        try builder.serve(\"a\", at: \"2.0.0\", with: [\n            \"a\": [\"b\": (.versionSet(.exact(\"2.0.0\")), .specific([\"b\"]))],\n        ])\n        try builder.serve(\"b\", at: \"1.0.0\", with: [\n            \"b\": [\"a\": (.versionSet(.exact(\"2.0.0\")), .specific([\"a\"]))],\n        ])\n        try builder.serve(\"b\", at: \"2.0.0\", with: [\n            \"b\": [\"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"]))],\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"b\": (.versionSet(.range(\"0.0.0\"..<\"5.0.0\")), .specific([\"b\"])),\n            \"a\": (.versionSet(.range(\"0.0.0\"..<\"5.0.0\")), .specific([\"a\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'a' 0.0.0..<5.0.0.\n            'a' cannot be used.\n            'a' 2.0.0 cannot be used because 'b' 2.0.0 depends on 'a' 1.0.0 and 'a' 2.0.0 depends on 'b' 2.0.0.\n            'a' {0.0.0..<2.0.0, 2.0.1..<5.0.0} cannot be used because 'b' 1.0.0 depends on 'a' 2.0.0.\n            'a' {0.0.0..<2.0.0, 2.0.1..<5.0.0} practically depends on 'b' 1.0.0 because no versions of 'a' match the requirement {0.0.0..<1.0.0, 1.0.1..<2.0.0, 2.0.1..<5.0.0} and 'a' 1.0.0 depends on 'b' 1.0.0.\n            \"\"\")\n    }\n\n    // root -> version -> version\n    // root -> version -> conflicting version\n    func testConflict6() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"bar\", at: v1, with: [\"bar\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.versionSet(v1Range), .specific([\"bar\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'foo' 1.0.0..<2.0.0 and root depends on 'bar' 1.0.0..<2.0.0.\n            'bar' is incompatible with 'foo' because 'foo' 1.0.0 depends on 'config' 1.0.0..<2.0.0 and no versions of 'foo' match the requirement 1.0.1..<2.0.0.\n            'bar' >= 1.0.0 practically depends on 'config' 2.0.0..<3.0.0 because no versions of 'bar' match the requirement 1.0.1..<2.0.0 and 'bar' 1.0.0 depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    // root -> version -> version\n    // root -> non-versioned -> conflicting version\n    func testConflict7() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.unversioned, .specific([\"bar\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because 'bar' depends on 'config' 2.0.0..<3.0.0 and root depends on 'foo' 1.0.0..<2.0.0.\n            'foo' >= 1.0.0 practically depends on 'config' 1.0.0..<2.0.0 because no versions of 'foo' match the requirement 1.0.1..<2.0.0 and 'foo' 1.0.0 depends on 'config' 1.0.0..<2.0.0.\n            \"\"\")\n    }\n\n    // root -> version -> version\n    // root -> non-versioned -> non-versioned -> conflicting version\n    func testConflict8() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"baz\": (.unversioned, .specific([\"baz\"]))]])\n        try builder.serve(\"baz\", at: .unversioned, with: [\"baz\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.unversioned, .specific([\"bar\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because 'baz' depends on 'config' 2.0.0..<3.0.0 and root depends on 'foo' 1.0.0..<2.0.0.\n            'foo' >= 1.0.0 practically depends on 'config' 1.0.0..<2.0.0 because no versions of 'foo' match the requirement 1.0.1..<2.0.0 and 'foo' 1.0.0 depends on 'config' 1.0.0..<2.0.0.\n            \"\"\")\n    }\n\n    // root -> version -> version\n    // root -> non-versioned -> non-existing version\n    func testConflict9() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v1Range), .specific([\"config\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n            \"bar\": (.unversioned, .specific([\"bar\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because no versions of 'config' match the requirement 2.0.0..<3.0.0 and 'bar' depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    // root -> version\n    // root -> non-versioned -> conflicting version\n    func testConflict10() async throws {\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n            \"foo\": (.unversioned, .specific([\"foo\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because 'foo' depends on 'config' 2.0.0..<3.0.0 and root depends on 'config' 1.0.0..<2.0.0.\n            \"\"\")\n    }\n\n    // root -> version\n    // root -> non-versioned -> non-existing version\n    func testConflict11() async throws {\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n            \"foo\": (.unversioned, .specific([\"foo\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because 'foo' depends on 'config' 2.0.0..<3.0.0 and root depends on 'config' 1.0.0..<2.0.0.\n            \"\"\")\n    }\n\n    // root -> version\n    // root -> non-versioned -> non-versioned -> conflicting version\n    func testConflict12() async throws {\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"bar\": (.unversioned, .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"baz\": (.unversioned, .specific([\"baz\"]))]])\n        try builder.serve(\"baz\", at: .unversioned, with: [\"baz\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n            \"foo\": (.unversioned, .specific([\"foo\"]))\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because 'baz' depends on 'config' 2.0.0..<3.0.0 and root depends on 'config' 1.0.0..<2.0.0.\n            \"\"\")\n    }\n\n    // top level package -> version\n    // top level package -> version -> conflicting version\n    func testConflict13() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n                \"foo\": (.versionSet(v1Range), .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'config' 1.0.0..<2.0.0 and root depends on 'foo' 1.0.0..<2.0.0.\n            'foo' >= 1.0.0 practically depends on 'config' 2.0.0..<3.0.0 because no versions of 'foo' match the requirement 1.0.1..<2.0.0 and 'foo' 1.0.0 depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    // top level package -> version\n    // top level package -> version -> non-existing version\n    func testConflict14() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n                \"foo\": (.versionSet(v1Range), .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: v1, with: [\"foo\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'config' 1.0.0..<2.0.0 and root depends on 'foo' 1.0.0..<2.0.0.\n            'foo' >= 1.0.0 practically depends on 'config' 2.0.0..<3.0.0 because no versions of 'foo' match the requirement 1.0.1..<2.0.0 and 'foo' 1.0.0 depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    // top level package -> version\n    // top level package -> non-versioned -> conflicting version\n    func testConflict15() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n                \"foo\": (.unversioned, .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'config' 1.0.0..<2.0.0 and 'foo' depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    // top level package -> version\n    // top level package -> non-versioned -> non-existing version\n    func testConflict16() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n                \"foo\": (.unversioned, .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'config' 1.0.0..<2.0.0 and 'foo' depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    // top level package -> version\n    // top level package -> non-versioned -> non-versioned -> conflicting version\n    func testConflict17() async throws {\n        let package = PackageReference.root(identity: .plain(\"package\"), path: .root)\n        try builder.serve(package, at: .unversioned, with: [\n            \"module\": [\n                \"config\": (.versionSet(v1Range), .specific([\"config\"])),\n                \"foo\": (.unversioned, .specific([\"foo\"]))\n            ]])\n        try builder.serve(\"foo\", at: .unversioned, with: [\"foo\": [\"bar\": (.unversioned, .specific([\"bar\"]))]])\n        try builder.serve(\"bar\", at: .unversioned, with: [\"bar\": [\"baz\": (.unversioned, .specific([\"baz\"]))]])\n        try builder.serve(\"baz\", at: .unversioned, with: [\"baz\": [\"config\": (.versionSet(v2Range), .specific([\"config\"]))]])\n        try builder.serve(\"config\", at: v1)\n        try builder.serve(\"config\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = builder.create(dependencies: [\n            package: (.unversioned, .everything)\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'config' 1.0.0..<2.0.0 and 'baz' depends on 'config' 2.0.0..<3.0.0.\n            \"\"\")\n    }\n\n    func testUnversioned6() async throws {\n        try builder.serve(\"foo\", at: .unversioned)\n        try builder.serve(\"bar\", at: .revision(\"main\"), with: [\n            \"bar\": [\"foo\": (.unversioned, .specific([\"foo\"]))]\n        ])\n\n        let resolver = builder.create()\n\n        let dependencies = try builder.create(dependencies: [\n            \"bar\": (.revision(\"main\"), .specific([\"bar\"]))\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"package 'bar' is required using a revision-based requirement and it depends on local package 'foo', which is not supported\")\n    }\n\n    func testResolutionWithOverridingBranchBasedDependency4() async throws {\n        try builder.serve(\"foo\", at: .revision(\"main\"), with: [\"foo\": [\"bar\": (.revision(\"main\"), .specific([\"bar\"]))]])\n\n        try builder.serve(\"bar\", at: .revision(\"main\"))\n        try builder.serve(\"bar\", at: v1)\n\n        try builder.serve(\"baz\", at: .revision(\"main\"), with: [\"baz\": [\"bar\": (.revision(\"develop\"), .specific([\"baz\"]))]])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.revision(\"main\"), .specific([\"foo\"])),\n            \"baz\": (.revision(\"main\"), .specific([\"baz\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"bar is required using two different revision-based requirements (main and develop), which is not supported\")\n    }\n\n    func testNonVersionDependencyInVersionDependency1() async throws {\n        try builder.serve(\"foo\", at: v1_1, with: [\n            \"foo\": [\"bar\": (.revision(\"main\"), .specific([\"bar\"]))]\n        ])\n        try builder.serve(\"bar\", at: .revision(\"main\"))\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(v1Range), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'foo' 1.0.0..<2.0.0.\n            'foo' cannot be used because no versions of 'foo' match the requirement {1.0.0..<1.1.0, 1.1.1..<2.0.0} and package 'foo' is required using a stable-version but 'foo' depends on an unstable-version package 'bar'.\n            \"\"\")\n    }\n\n    func testNonVersionDependencyInVersionDependency2() async throws {\n        try builder.serve(\"foo\", at: v1, with: [\n            \"foo\": [\"bar\": (.unversioned, .specific([\"bar\"]))]\n        ])\n        try builder.serve(\"bar\", at: .unversioned)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(.exact(v1)), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because package 'foo' is required using a stable-version but 'foo' depends on an unstable-version package 'bar' and root depends on 'foo' 1.0.0.\n            \"\"\")\n    }\n\n    func testNonVersionDependencyInVersionDependency3() async throws {\n        try builder.serve(\"foo\", at: \"1.0.0-beta.1\", with: [\n            \"foo\": [\"bar\": (.revision(\"main\"), .specific([\"bar\"]))]\n        ])\n        try builder.serve(\"foo\", at: \"1.0.0-beta.2\", with: [\n            \"foo\": [\"bar\": (.revision(\"main\"), .specific([\"bar\"]))]\n        ])\n        try builder.serve(\"foo\", at: \"1.0.0-beta.3\", with: [\n            \"foo\": [\"bar\": (.revision(\"main\"), .specific([\"bar\"]))]\n        ])\n        try builder.serve(\"bar\", at: .revision(\"main\"))\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(.range(\"1.0.0-beta\" ..< \"2.0.0\")), .specific([\"foo\"])),\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because package 'foo' is required using a stable-version but 'foo' depends on an unstable-version package 'bar' and root depends on 'foo' 1.0.0-beta..<2.0.0.\n            'foo' {1.0.0-beta..<1.0.0-beta.3, 1.0.0-beta.3.0..<2.0.0} cannot be used because package 'foo' is required using a stable-version but 'foo' depends on an unstable-version package 'bar'.\n            'foo' {1.0.0-beta..<1.0.0-beta.2, 1.0.0-beta.2.0..<1.0.0-beta.3, 1.0.0-beta.3.0..<2.0.0} cannot be used because no versions of 'foo' match the requirement {1.0.0-beta..<1.0.0-beta.1, 1.0.0-beta.1.0..<1.0.0-beta.2, 1.0.0-beta.2.0..<1.0.0-beta.3, 1.0.0-beta.3.0..<2.0.0} and package 'foo' is required using a stable-version but 'foo' depends on an unstable-version package 'bar'.\n            \"\"\")\n    }\n\n    func testIncompatibleToolsVersion1() async throws {\n        try builder.serve(\"a\", at: v1, toolsVersion: .v5)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'a' 1.0.0..<2.0.0.\n            'a' >= 1.0.0 cannot be used because no versions of 'a' match the requirement 1.0.1..<2.0.0 and 'a' 1.0.0 contains incompatible tools version (\\(ToolsVersion.v5)).\n            \"\"\")\n    }\n\n    func testIncompatibleToolsVersion3() async throws {\n        try builder.serve(\"a\", at: v1_1, with: [\n            \"a\": [\"b\": (.versionSet(v1Range), .specific([\"b\"]))]\n        ])\n        try builder.serve(\"a\", at: v1, toolsVersion: .v4)\n\n        try builder.serve(\"b\", at: v1)\n        try builder.serve(\"b\", at: v2)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(v1Range), .specific([\"a\"])),\n            \"b\": (.versionSet(v2Range), .specific([\"b\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because root depends on 'a' 1.0.0..<2.0.0 and root depends on 'b' 2.0.0..<3.0.0.\n            'a' >= 1.0.0 practically depends on 'b' 1.0.0..<2.0.0 because 'a' 1.1.0 depends on 'b' 1.0.0..<2.0.0.\n            'a' {1.0.0..<1.1.0, 1.1.1..<2.0.0} cannot be used because no versions of 'a' match the requirement {1.0.1..<1.1.0, 1.1.1..<2.0.0} and 'a' 1.0.0 contains incompatible tools version (\\(ToolsVersion.v4)).\n            \"\"\")\n    }\n\n    func testIncompatibleToolsVersion4() async throws {\n        try builder.serve(\"a\", at: \"3.2.1\", toolsVersion: .v3)\n        try builder.serve(\"a\", at: \"3.2.2\", toolsVersion: .v4)\n        try builder.serve(\"a\", at: \"3.2.3\", toolsVersion: .v3)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.range(\"3.2.0\"..<\"4.0.0\")), .specific([\"a\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because 'a' contains incompatible tools version (\\(ToolsVersion.v3)) and root depends on 'a' 3.2.0..<4.0.0.\n            \"\"\")\n    }\n\n    func testIncompatibleToolsVersion5() async throws {\n        try builder.serve(\"a\", at: \"3.2.0\", toolsVersion: .v3)\n        try builder.serve(\"a\", at: \"3.2.1\", toolsVersion: .v4)\n        try builder.serve(\"a\", at: \"3.2.2\", toolsVersion: .v5)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.range(\"3.2.0\"..<\"4.0.0\")), .specific([\"a\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because 'a' contains incompatible tools version (\\(ToolsVersion.v5)) and root depends on 'a' 3.2.0..<4.0.0.\n            \"\"\")\n    }\n\n    func testIncompatibleToolsVersion6() async throws {\n        try builder.serve(\"a\", at: \"3.2.1\", toolsVersion: .v5)\n        try builder.serve(\"a\", at: \"3.2.0\", with: [\n            \"a\": [\"b\": (.versionSet(v1Range), .specific([\"b\"]))],\n        ])\n        try builder.serve(\"a\", at: \"3.2.2\", toolsVersion: .v4)\n        try builder.serve(\"b\", at: \"1.0.0\", toolsVersion: .v3)\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.range(\"3.2.0\"..<\"4.0.0\")), .specific([\"a\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        XCTAssertEqual(result.errorMsg, \"\"\"\n            Dependencies could not be resolved because 'a' >= 3.2.1 contains incompatible tools version (\\(ToolsVersion.v4)) and root depends on 'a' 3.2.0..<4.0.0.\n            'a' 3.2.0 cannot be used because 'a' 3.2.0 depends on 'b' 1.0.0..<2.0.0.\n            'b' >= 1.0.0 cannot be used because 'b' 1.0.0 contains incompatible tools version (\\(ToolsVersion.v3)) and no versions of 'b' match the requirement 1.0.1..<2.0.0.\n            \"\"\")\n    }\n\n    func testProductsCannotResolveToDifferentVersions() async throws {\n        try builder.serve(\"package\", at: .unversioned, with: [\n            \"package\": [\n                \"intermediate_a\": (.versionSet(v1Range), .specific([\"Intermediate A\"])),\n                \"intermediate_b\": (.versionSet(v1Range), .specific([\"Intermediate B\"]))\n            ]\n        ])\n        try builder.serve(\"intermediate_a\", at: v1, with: [\n            \"Intermediate A\": [\n                \"transitive\": (.versionSet(.exact(v1)), .specific([\"Product A\"]))\n            ]\n        ])\n        try builder.serve(\"intermediate_b\", at: v1, with: [\n            \"Intermediate B\": [\n                \"transitive\": (.versionSet(.exact(v1_1)), .specific([\"Product B\"]))\n            ]\n        ])\n        try builder.serve(\"transitive\", at: v1, with: [\n            \"Product A\": [:],\n            \"Product B\": [:]\n        ])\n        try builder.serve(\"transitive\", at: v1_1, with: [\n            \"Product A\": [:],\n            \"Product B\": [:]\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"package\": (.unversioned, .everything)\n        ])\n        let result = await resolver.solve(constraints: dependencies)\n\n        // TODO: this description could use refinement\n        XCTAssertEqual(\n            result.errorMsg,\n            \"\"\"\n            Dependencies could not be resolved because 'package' depends on 'intermediate_a' 1.0.0..<2.0.0 and 'package' depends on 'intermediate_b' 1.0.0..<2.0.0.\n            'intermediate_b' is incompatible with 'intermediate_a' because 'intermediate_a' 1.0.0 depends on 'transitive' 1.0.0 and no versions of 'intermediate_a' match the requirement 1.0.1..<2.0.0.\n            'intermediate_b' is incompatible with 'transitive' because 'transitive' 1.1.0 depends on 'transitive' 1.1.0 and 'transitive' 1.0.0 depends on 'transitive' 1.0.0.\n            'intermediate_b' >= 1.0.0 practically depends on 'transitive' 1.1.0 because no versions of 'intermediate_b' match the requirement 1.0.1..<2.0.0 and 'intermediate_b' 1.0.0 depends on 'transitive' 1.1.0.\n            \"\"\"\n        )\n    }\n}\n\nfinal class PubGrubBacktrackTests: XCTestCase {\n    func testBacktrack1() async throws {\n        try builder.serve(\"a\", at: v1)\n        try builder.serve(\"a\", at: \"2.0.0\", with: [\n            \"a\": [\"b\": (.versionSet(.exact(\"1.0.0\")), .specific([\"b\"]))],\n        ])\n        try builder.serve(\"b\", at: \"1.0.0\", with: [\n            \"b\": [\"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"]))],\n        ])\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.range(\"1.0.0\"..<\"3.0.0\")), .specific([\"a\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n        ])\n    }\n\n    func testBacktrack2() async throws {\n        try builder.serve(\"a\", at: v1)\n        try builder.serve(\"a\", at: \"2.0.0\", with: [\n            \"a\": [\"c\": (.versionSet(.range(\"1.0.0\"..<\"2.0.0\")), .specific([\"c\"]))],\n        ])\n\n        try builder.serve(\"b\", at: \"1.0.0\", with: [\n            \"b\": [\"c\": (.versionSet(.range(\"2.0.0\"..<\"3.0.0\")), .specific([\"c\"]))],\n        ])\n        try builder.serve(\"b\", at: \"2.0.0\", with: [\n            \"b\": [\"c\": (.versionSet(.range(\"3.0.0\"..<\"4.0.0\")), .specific([\"c\"]))],\n        ])\n\n        try builder.serve(\"c\", at: \"1.0.0\")\n        try builder.serve(\"c\", at: \"2.0.0\")\n        try builder.serve(\"c\", at: \"3.0.0\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.range(\"1.0.0\"..<\"3.0.0\")), .specific([\"a\"])),\n            \"b\": (.versionSet(.range(\"1.0.0\"..<\"3.0.0\")), .specific([\"b\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"b\", .version(\"2.0.0\")),\n            (\"c\", .version(\"3.0.0\")),\n        ])\n    }\n\n    func testBacktrack3() async throws {\n        try builder.serve(\"a\", at: \"1.0.0\", with: [\n            \"a\": [\"x\": (.versionSet(.range(\"1.0.0\"..<\"5.0.0\")), .specific([\"x\"]))],\n        ])\n        try builder.serve(\"b\", at: \"1.0.0\", with: [\n            \"b\": [\"x\": (.versionSet(.range(\"0.0.0\"..<\"2.0.0\")), .specific([\"x\"]))],\n        ])\n\n        try builder.serve(\"c\", at: \"1.0.0\")\n        try builder.serve(\"c\", at: \"2.0.0\", with: [\n            \"c\": [\n                \"a\": (.versionSet(.range(\"0.0.0\"..<\"5.0.0\")), .specific([\"a\"])),\n                \"b\": (.versionSet(.range(\"0.0.0\"..<\"5.0.0\")), .specific([\"b\"])),\n            ]\n        ])\n\n        try builder.serve(\"x\", at: \"0.0.0\")\n        try builder.serve(\"x\", at: \"2.0.0\")\n        try builder.serve(\"x\", at: \"1.0.0\", with: [\n            \"x\": [\"y\": (.versionSet(.exact(v1)), .specific([\"y\"]))],\n        ])\n\n        try builder.serve(\"y\", at: \"1.0.0\")\n        try builder.serve(\"y\", at: \"2.0.0\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"c\": (.versionSet(.range(\"1.0.0\"..<\"3.0.0\")), .specific([\"c\"])),\n            \"y\": (.versionSet(.range(\"2.0.0\"..<\"3.0.0\")), .specific([\"y\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"c\", .version(v1)),\n            (\"y\", .version(\"2.0.0\")),\n        ])\n    }\n\n    func testBacktrack4() async throws {\n        try builder.serve(\"a\", at: \"1.0.0\", with: [\n            \"a\": [\"x\": (.versionSet(.range(\"1.0.0\"..<\"5.0.0\")), .specific([\"x\"]))],\n        ])\n        try builder.serve(\"b\", at: \"1.0.0\", with: [\n            \"b\": [\"x\": (.versionSet(.range(\"0.0.0\"..<\"2.0.0\")), .specific([\"x\"]))],\n        ])\n\n        try builder.serve(\"c\", at: \"1.0.0\")\n        try builder.serve(\"c\", at: \"2.0.0\", with: [\n            \"c\": [\n                \"a\": (.versionSet(.range(\"0.0.0\"..<\"5.0.0\")), .specific([\"a\"])),\n                \"b\": (.versionSet(.range(\"0.0.0\"..<\"5.0.0\")), .specific([\"b\"])),\n            ]\n        ])\n\n        try builder.serve(\"x\", at: \"0.0.0\")\n        try builder.serve(\"x\", at: \"2.0.0\")\n        try builder.serve(\"x\", at: \"1.0.0\", with: [\n            \"x\": [\"y\": (.versionSet(.exact(v1)), .specific([\"y\"]))],\n        ])\n\n        try builder.serve(\"y\", at: \"1.0.0\")\n        try builder.serve(\"y\", at: \"2.0.0\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"c\": (.versionSet(.range(\"1.0.0\"..<\"3.0.0\")), .specific([\"c\"])),\n            \"y\": (.versionSet(.range(\"2.0.0\"..<\"3.0.0\")), .specific([\"y\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"c\", .version(v1)),\n            (\"y\", .version(\"2.0.0\")),\n        ])\n    }\n\n    func testBacktrack5() async throws {\n        try builder.serve(\"foo\", at: \"1.0.0\", with: [\n            \"foo\": [\"bar\": (.versionSet(.exact(\"1.0.0\")), .specific([\"bar\"]))],\n        ])\n        try builder.serve(\"foo\", at: \"2.0.0\", with: [\n            \"foo\": [\"bar\": (.versionSet(.exact(\"2.0.0\")), .specific([\"bar\"]))],\n        ])\n        try builder.serve(\"foo\", at: \"3.0.0\", with: [\n            \"foo\": [\"bar\": (.versionSet(.exact(\"3.0.0\")), .specific([\"bar\"]))],\n        ])\n\n        try builder.serve(\"bar\", at: \"1.0.0\", with: [\n            \"bar\": [\"baz\": (.versionSet(.range(\"0.0.0\"..<\"3.0.0\")), .specific([\"baz\"]))],\n        ])\n        try builder.serve(\"bar\", at: \"2.0.0\", with: [\n            \"bar\": [\"baz\": (.versionSet(.exact(\"3.0.0\")), .specific([\"baz\"]))],\n        ])\n        try builder.serve(\"bar\", at: \"3.0.0\", with: [\n            \"bar\": [\"baz\": (.versionSet(.exact(\"3.0.0\")), .specific([\"baz\"]))],\n        ])\n\n        try builder.serve(\"baz\", at: \"1.0.0\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"foo\": (.versionSet(.range(\"1.0.0\"..<\"4.0.0\")), .specific([\"foo\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"foo\", .version(v1)),\n            (\"bar\", .version(\"1.0.0\")),\n            (\"baz\", .version(\"1.0.0\")),\n        ])\n    }\n\n    func testBacktrack6() async throws {\n        try builder.serve(\"a\", at: \"1.0.0\")\n        try builder.serve(\"a\", at: \"2.0.0\")\n        try builder.serve(\"b\", at: \"1.0.0\", with: [\n            \"b\": [\"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"]))],\n        ])\n        try builder.serve(\"c\", at: \"1.0.0\", with: [\n            \"c\": [\"b\": (.versionSet(.range(\"0.0.0\"..<\"3.0.0\")), .specific([\"b\"]))],\n        ])\n        try builder.serve(\"d\", at: \"1.0.0\")\n        try builder.serve(\"d\", at: \"2.0.0\")\n\n        let resolver = builder.create()\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.range(\"1.0.0\"..<\"4.0.0\")), .specific([\"a\"])),\n            \"c\": (.versionSet(.range(\"1.0.0\"..<\"4.0.0\")), .specific([\"c\"])),\n            \"d\": (.versionSet(.range(\"1.0.0\"..<\"4.0.0\")), .specific([\"d\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(v1)),\n            (\"b\", .version(v1)),\n            (\"c\", .version(v1)),\n            (\"d\", .version(\"2.0.0\")),\n        ])\n    }\n\n    func testLogging() async throws {\n        try builder.serve(\"a\", at: \"1.0.0\")\n        try builder.serve(\"a\", at: \"2.0.0\")\n        try builder.serve(\"b\", at: \"1.0.1\", with: [\n            \"b\": [\"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"]))],\n        ])\n        try builder.serve(\"c\", at: \"1.5.2\", with: [\n            \"c\": [\"b\": (.versionSet(.range(\"0.0.0\"..<\"3.0.0\")), .specific([\"b\"]))],\n        ])\n        try builder.serve(\"d\", at: \"1.0.1\")\n        try builder.serve(\"d\", at: \"2.3.0\")\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let resolver = builder.create(delegate: ObservabilityDependencyResolverDelegate(observabilityScope: observability.topScope))\n        let dependencies = try builder.create(dependencies: [\n            \"a\": (.versionSet(.range(\"1.0.0\"..<\"4.0.0\")), .specific([\"a\"])),\n            \"c\": (.versionSet(.range(\"1.0.0\"..<\"4.0.0\")), .specific([\"c\"])),\n            \"d\": (.versionSet(.range(\"1.0.0\"..<\"4.0.0\")), .specific([\"d\"])),\n        ])\n\n        let result = await resolver.solve(constraints: dependencies)\n\n        AssertResult(result, [\n            (\"a\", .version(\"1.0.0\")),\n            (\"b\", .version(\"1.0.1\")),\n            (\"c\", .version(\"1.5.2\")),\n            (\"d\", .version(\"2.3.0\")),\n        ])\n\n        observability.diagnostics.forEach { print(\"\\($0)\") }\n\n        XCTAssertTrue(observability.diagnostics.contains(where: { $0.message == \"[DependencyResolver] resolved 'a' @ '1.0.0'\" }))\n        XCTAssertTrue(observability.diagnostics.contains(where: { $0.message == \"[DependencyResolver] resolved 'b' @ '1.0.1'\" }))\n        XCTAssertTrue(observability.diagnostics.contains(where: { $0.message == \"[DependencyResolver] resolved 'c' @ '1.5.2'\" }))\n        XCTAssertTrue(observability.diagnostics.contains(where: { $0.message == \"[DependencyResolver] resolved 'd' @ '2.3.0'\" }))\n    }\n\n    func testPrereleaseVersionSelection() async throws {\n        try builder.serve(\"a\", at: \"1.0.0\", with: [\n            \"a\": [\n                \"b\": (.versionSet(.range(\"0.0.8\"..<\"2.0.0\")), .specific([\"b\"]))\n            ]\n        ])\n\n        try builder.serve(\"b\", at: \"1.0.0-prerelease-20240710\")\n\n        try builder.serve(\"c\", at: \"1.0.0\", with: [\n            \"c\": [\n                \"d\": (.versionSet(.range(\"1.0.5\"..<\"2.0.0\")), .specific([\"d\"]))\n            ]\n        ])\n        try builder.serve(\"c\", at: \"1.0.1\")\n\n        try builder.serve(\"d\", at: \"1.0.0-prerelease-20240710\")\n        try builder.serve(\"d\", at: \"1.0.6-prerelease-1\")\n        try builder.serve(\"d\", at: \"1.0.6\")\n\n        let resolver = builder.create()\n        // The order matters here because solver used to assign `b` before `a`.\n        let dependencies1 = try builder.create(dependencies: [\n            \"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"])),\n            \"b\": (.versionSet(.range(\"1.0.0-latest\"..<\"2.0.0\")), .specific([\"b\"]))\n        ])\n\n        await AssertResult(resolver.solve(constraints: dependencies1), [\n            (\"a\", .version(\"1.0.0\")),\n            (\"b\", .version(\"1.0.0-prerelease-20240710\"))\n        ])\n\n        let dependencies2 = try builder.create(dependencies: [\n            \"c\": (.versionSet(.exact(\"1.0.0\")), .specific([\"c\"])),\n            \"d\": (.versionSet(.range(\"1.0.0-latest\"..<\"2.0.0\")), .specific([\"d\"]))\n        ])\n\n        await AssertResult(resolver.solve(constraints: dependencies2), [\n            (\"c\", .version(\"1.0.0\")),\n            (\"d\", .version(\"1.0.6\"))\n        ])\n    }\n\n    func testPrereleaseExactRequirement() async throws {\n        try builder.serve(\"c\", at: \"1.0.0\", with: [\n            \"c\": [\n                \"d\": (.versionSet(.range(\"1.0.4\"..<\"2.0.0\")), .specific([\"d\"]))\n            ]\n        ])\n        try builder.serve(\"c\", at: \"1.0.1\")\n\n        try builder.serve(\"d\", at: \"1.0.0-prerelease-20240710\")\n        try builder.serve(\"d\", at: \"1.0.4\")\n        try builder.serve(\"d\", at: \"1.0.6-prerelease-1\")\n\n        let resolver = builder.create()\n\n        let exactDependencies = try builder.create(dependencies: [\n            \"c\": (.versionSet(.exact(\"1.0.0\")), .specific([\"c\"])),\n            \"d\": (.versionSet(.exact(\"1.0.6-prerelease-1\")), .specific([\"d\"]))\n        ])\n\n        // FIXME: This should produce a valid solution but cannot at the\n        // moment because \"1.0.4\"..<\"2.0.0\" doesn't support pre-release versions\n        // and there is no way to infer it.\n        let resultWithExact = await resolver.solve(constraints: exactDependencies)\n        XCTAssertMatch(\n            resultWithExact.errorMsg,\n            .contains(\"Dependencies could not be resolved because root depends on 'd' 1.0.6-prerelease-1\")\n        )\n\n        let rangeDependency = try builder.create(dependencies: [\n            \"c\": (.versionSet(.exact(\"1.0.0\")), .specific([\"c\"])),\n            \"d\": (.versionSet(.range(\"1.0.5\"..<\"1.0.6-prerelease-2\")), .specific([\"d\"]))\n        ])\n\n        let resultWithRange = await resolver.solve(constraints: rangeDependency)\n        AssertResult(resultWithRange, [\n            (\"c\", .version(\"1.0.0\")),\n            (\"d\", .version(\"1.0.6-prerelease-1\"))\n        ])\n    }\n\n    func testReleaseOverPrerelease() async throws {\n        try builder.serve(\"a\", at: \"1.0.0\", with: [\n            \"a\": [\n                \"b\": (.versionSet(.range(\"0.0.8\"..<\"2.0.0\")), .specific([\"b\"]))\n            ]\n        ])\n\n        try builder.serve(\"b\", at: \"1.0.0-prerelease-20240616\")\n        try builder.serve(\"b\", at: \"1.0.0\")\n\n        let resolver = builder.create()\n        // The order matters here because solver used to assign `b` before `a`.\n        let dependencies1 = try builder.create(dependencies: [\n            \"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"])),\n            \"b\": (.versionSet(.range(\"1.0.0-latest\"..<\"2.0.0\")), .specific([\"b\"]))\n        ])\n\n        await AssertResult(resolver.solve(constraints: dependencies1), [\n            (\"a\", .version(\"1.0.0\")),\n            (\"b\", .version(\"1.0.0\"))\n        ])\n\n        let dependencies2 = try builder.create(dependencies: [\n            \"b\": (.versionSet(.range(\"1.0.0-latest\"..<\"2.0.0\")), .specific([\"b\"])),\n            \"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"]))\n        ])\n\n        await AssertResult(resolver.solve(constraints: dependencies2), [\n            (\"a\", .version(\"1.0.0\")),\n            (\"b\", .version(\"1.0.0\"))\n        ])\n    }\n\n    func testPrereleaseInferenceThroughDependencies() async throws {\n        try builder.serve(\"a\", at: \"1.0.0\", with: [\n            \"a\": [\n                \"b\": (.versionSet(.range(\"1.0.0\"..<\"2.0.0-latest\")), .specific([\"b\"]))\n            ]\n        ])\n\n        try builder.serve(\"b\", at: \"0.0.8-prerelease-20230310\")\n        try builder.serve(\"b\", at: \"0.0.8\")\n        try builder.serve(\"b\", at: \"1.0.0-prerelease-20230616\")\n        try builder.serve(\"b\", at: \"1.0.0\")\n        try builder.serve(\"b\", at: \"1.9.9-prerelease-20240702\")\n\n        let resolver = builder.create()\n        // The order matters here because solver used to assign `b` before `a`.\n        let dependencies1 = try builder.create(dependencies: [\n            \"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"])),\n            \"b\": (.versionSet(.range(\"0.0.8\"..<\"2.0.0\")), .specific([\"b\"]))\n        ])\n\n        await AssertResult(resolver.solve(constraints: dependencies1), [\n            (\"a\", .version(\"1.0.0\")),\n            (\"b\", .version(\"1.9.9-prerelease-20240702\"))\n        ])\n\n        let dependencies2 = try builder.create(dependencies: [\n            \"b\": (.versionSet(.range(\"0.0.8\"..<\"2.0.0\")), .specific([\"b\"])),\n            \"a\": (.versionSet(.exact(\"1.0.0\")), .specific([\"a\"]))\n        ])\n\n        await AssertResult(resolver.solve(constraints: dependencies2), [\n            (\"a\", .version(\"1.0.0\")),\n            (\"b\", .version(\"1.9.9-prerelease-20240702\"))\n        ])\n    }\n}\n\nfileprivate extension ResolvedPackagesStore.ResolutionState {\n    /// Creates a checkout state with the given version and a mocked revision.\n    static func version(_ version: Version) -> Self {\n        .version(version, revision: .none)\n    }\n}\n\n/// Asserts that the listed packages are present in the bindings with their\n/// specified versions.\nprivate func AssertBindings(\n    _ bindings: [DependencyResolverBinding],\n    _ packages: [(identity: PackageIdentity, version: BoundVersion)],\n    file: StaticString = #file,\n    line: UInt = #line\n) {\n    if bindings.count > packages.count {\n        let unexpectedBindings = bindings\n            .filter { binding in\n                packages.contains(where: { pkg in\n                    pkg.identity != binding.package.identity\n                })\n            }\n            .map { $0.package.identity }\n\n        XCTFail(\"Unexpected binding(s) found for \\(unexpectedBindings.map { $0.description }.joined(separator: \", \")).\", file: file, line: line)\n    }\n    for package in packages {\n        guard let binding = bindings.first(where: { $0.package.identity == package.identity }) else {\n            XCTFail(\"No binding found for \\(package.identity).\", file: file, line: line)\n            continue\n        }\n\n        if binding.boundVersion != package.version {\n            XCTFail(\"Expected \\(package.version) for \\(package.identity), found \\(binding.boundVersion) instead.\", file: file, line: line)\n        }\n    }\n}\n\n/// Asserts that a result succeeded and contains the specified bindings.\nprivate func AssertResult(\n    _ result: Result<[DependencyResolverBinding], Error>,\n    _ packages: [(identifier: String, version: BoundVersion)],\n    file: StaticString = #file,\n    line: UInt = #line\n) {\n    switch result {\n    case .success(let bindings):\n        AssertBindings(bindings, packages.map { (PackageIdentity($0.identifier), $0.version) }, file: file, line: line)\n    case .failure(let error):\n        XCTFail(\"Unexpected error: \\(error)\", file: file, line: line)\n    }\n}\n\n/// Asserts that a result failed with specified error.\nprivate func AssertError(\n    _ result: Result<[DependencyResolverBinding], Error>,\n    _ expectedError: Error,\n    file: StaticString = #file,\n    line: UInt = #line\n) {\n    switch result {\n    case .success(let bindings):\n        let bindingsDesc = bindings.map { \"\\($0.package)@\\($0.boundVersion)\" }.joined(separator: \", \")\n        XCTFail(\"Expected unresolvable graph, found bindings instead: \\(bindingsDesc)\", file: file, line: line)\n    case .failure(let foundError):\n        XCTAssertEqual(String(describing: foundError), String(describing: expectedError), file: file, line: line)\n    }\n}\n\n// FIXME: this is not thread-safe\npublic class MockContainer: PackageContainer {\n    public typealias Dependency = (container: PackageReference, requirement: PackageRequirement, productFilter: ProductFilter)\n\n    public var package: PackageReference\n    var manifestName: PackageReference?\n\n    var dependencies: [String: [String: [Dependency]]]\n\n    public var unversionedDeps: [PackageContainerConstraint] = []\n\n    /// The list of versions that have incompatible tools version.\n    var toolsVersion: ToolsVersion = ToolsVersion.current\n    var versionsToolsVersions = [Version: ToolsVersion]()\n\n    private var _versions: [BoundVersion]\n\n    // TODO: this does not actually do anything with the tools-version\n    public func toolsVersionsAppropriateVersionsDescending() throws -> [Version] {\n        var versions: [Version] = []\n        for version in self._versions.reversed() {\n            guard case .version(let v) = version else { continue }\n            versions.append(v)\n        }\n        return versions\n    }\n\n    public func versionsAscending() throws ->  [Version] {\n        var versions: [Version] = []\n        for version in self._versions {\n            guard case .version(let v) = version else { continue }\n            versions.append(v)\n        }\n        return versions\n    }\n\n    public func isToolsVersionCompatible(at version: Version) -> Bool {\n        // this checks for *exact* version match which is good enough for our current tests\n        if let toolsVersion = try? self.toolsVersion(for: version) {\n            return self.toolsVersion == toolsVersion\n        }\n\n        return (try? self.toolsVersionsAppropriateVersionsDescending().contains(version)) ?? false\n    }\n\n    public func toolsVersion(for version: Version) throws -> ToolsVersion {\n        struct NotFound: Error {}\n\n        guard let version = versionsToolsVersions[version] else {\n            throw NotFound()\n        }\n        return version\n    }\n\n    public func getDependencies(at version: Version, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        return try getDependencies(at: version.description, productFilter: productFilter, enabledTraits)\n    }\n\n    public func getDependencies(at revision: String, productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        guard let revisionDependencies = dependencies[revision] else {\n            throw _MockLoadingError.unknownRevision\n        }\n        var filteredDependencies: [MockContainer.Dependency] = []\n        for (product, productDependencies) in revisionDependencies where productFilter.contains(product) {\n            filteredDependencies.append(contentsOf: productDependencies)\n        }\n        return filteredDependencies.map({ value in\n            let (package, requirement, filter) = value\n            return PackageContainerConstraint(package: package, requirement: requirement, products: filter)\n        })\n    }\n\n    public func getUnversionedDependencies(productFilter: ProductFilter, _ enabledTraits: EnabledTraits = [\"default\"]) throws -> [PackageContainerConstraint] {\n        // FIXME: This is messy, remove unversionedDeps property.\n        if !unversionedDeps.isEmpty {\n            return unversionedDeps\n        }\n        return try getDependencies(at: PackageRequirement.unversioned.description, productFilter: productFilter, enabledTraits)\n    }\n\n    public func loadPackageReference(at boundVersion: BoundVersion) throws -> PackageReference {\n        if let manifestName {\n            self.package = self.package.withName(manifestName.identity.description)\n        }\n        return self.package\n    }\n\n    func appendVersion(_ version: BoundVersion) {\n        self._versions.append(version)\n        self._versions = self._versions\n            .sorted(by: { lhs, rhs -> Bool in\n                guard case .version(let lv) = lhs, case .version(let rv) = rhs else {\n                    return true\n                }\n                return lv < rv\n            })\n    }\n\n    public convenience init(\n        package: PackageReference,\n        unversionedDependencies: [(package: PackageReference, requirement: PackageRequirement, productFilter: ProductFilter)]\n    ) {\n        self.init(package: package)\n        self.unversionedDeps = unversionedDependencies\n            .map { PackageContainerConstraint(package: $0.package, requirement: $0.requirement, products: $0.productFilter) }\n    }\n\n    public convenience init(\n        package: PackageReference,\n        dependenciesByVersion: [Version: [String: [(\n            package: PackageReference,\n            requirement: VersionSetSpecifier,\n            productFilter: ProductFilter\n        )]]]) {\n        var dependencies: [String: [String: [Dependency]]] = [:]\n        for (version, productDependencies) in dependenciesByVersion {\n            if dependencies[version.description] == nil {\n                dependencies[version.description] = [:]\n            }\n            for (product, deps) in productDependencies {\n                dependencies[version.description, default: [:]][product] = deps.map({\n                    ($0.package, .versionSet($0.requirement), $0.productFilter)\n                })\n            }\n        }\n        self.init(package: package, dependencies: dependencies)\n    }\n\n    public init(\n        package: PackageReference,\n        dependencies: [String: [String: [Dependency]]] = [:]\n    ) {\n        self.package = package\n        self.dependencies = dependencies\n        let versions = dependencies.keys.compactMap(Version.init(_:))\n        self._versions = versions\n            .sorted()\n            .map(BoundVersion.version)\n    }\n}\n\npublic enum _MockLoadingError: Error {\n    case unknownModule\n    case unknownRevision\n}\n\npublic struct MockProvider: PackageContainerProvider {\n\n    public let containers: [MockContainer]\n    public let containersByIdentifier: [PackageReference: MockContainer]\n\n    public init(containers: [MockContainer]) {\n        self.containers = containers\n        self.containersByIdentifier = Dictionary(uniqueKeysWithValues: containers.map({ ($0.package, $0) }))\n    }\n\n    public func getContainer(\n        for package: PackageReference,\n        updateStrategy: ContainerUpdateStrategy,\n        observabilityScope: ObservabilityScope\n    ) async throws -> PackageContainer {\n        guard let container = self.containersByIdentifier[package] else {\n            throw _MockLoadingError.unknownModule\n        }\n        return container\n    }\n}\n\nclass DependencyGraphBuilder {\n    private var containers: [String: MockContainer] = [:]\n    private var references: [String: PackageReference] = [:]\n\n    func reference(for packageName: String) throws -> PackageReference {\n        if let reference = self.references[packageName] {\n            return reference\n        }\n        let newReference = PackageReference.localSourceControl(identity: .plain(packageName), path: try .init(validating: \"/\\(packageName)\"))\n        self.references[packageName] = newReference\n        return newReference\n    }\n\n    func create(\n        dependencies: OrderedCollections.OrderedDictionary<String, (PackageRequirement, ProductFilter)>\n    ) throws -> [PackageContainerConstraint] {\n        var refDependencies = OrderedCollections.OrderedDictionary<PackageReference, (PackageRequirement, ProductFilter)>()\n        for dependency in dependencies {\n            try refDependencies[reference(for: dependency.key)] = dependency.value\n        }\n        return self.create(dependencies: refDependencies)\n    }\n\n    func create(\n        dependencies: OrderedCollections.OrderedDictionary<PackageReference, (PackageRequirement, ProductFilter)>\n    ) -> [PackageContainerConstraint] {\n        return dependencies.map {\n            PackageContainerConstraint(package: $0, requirement: $1.0, products: $1.1)\n        }\n    }\n\n    func serve(\n        _ package: String,\n        at versions: [Version],\n        toolsVersion: ToolsVersion? = nil,\n        with dependencies: KeyValuePairs<String, OrderedCollections.OrderedDictionary<String, (PackageRequirement, ProductFilter)>> = [:]\n    ) throws {\n        try self.serve(package, at: versions.map{ .version($0) }, toolsVersion: toolsVersion, with: dependencies)\n    }\n\n    func serve(\n        _ package: String,\n        at version: Version,\n        toolsVersion: ToolsVersion? = nil,\n        with dependencies: KeyValuePairs<String, OrderedCollections.OrderedDictionary<String, (PackageRequirement, ProductFilter)>> = [:]\n    ) throws {\n        try self.serve(package, at: .version(version), toolsVersion: toolsVersion, with: dependencies)\n    }\n\n    func serve(\n        _ package: String,\n        at versions: [BoundVersion],\n        toolsVersion: ToolsVersion? = nil,\n        with dependencies: KeyValuePairs<String, OrderedCollections.OrderedDictionary<String, (PackageRequirement, ProductFilter)>> = [:]\n    ) throws {\n        let packageReference = try reference(for: package)\n        try self.serve(\n            packageReference,\n            at: versions,\n            toolsVersion: toolsVersion,\n            with: dependencies\n        )\n    }\n\n    func serve(\n        _ package: String,\n        at version: BoundVersion,\n        toolsVersion: ToolsVersion? = nil,\n        with dependencies: KeyValuePairs<String, OrderedCollections.OrderedDictionary<String, (PackageRequirement, ProductFilter)>> = [:]\n    ) throws {\n        let packageReference = try reference(for: package)\n        try self.serve(\n            packageReference,\n            at: version,\n            toolsVersion: toolsVersion,\n            with: dependencies\n        )\n    }\n\n    func serve(\n        _ packageReference: PackageReference,\n        at versions: [BoundVersion],\n        toolsVersion: ToolsVersion? = nil,\n        with dependencies: KeyValuePairs<String, OrderedCollections.OrderedDictionary<String, (PackageRequirement, ProductFilter)>> = [:]\n    ) throws {\n        for version in versions {\n            try serve(packageReference, at: version, toolsVersion: toolsVersion, with: dependencies)\n        }\n    }\n\n    func serve(\n        _ packageReference: PackageReference,\n        at version: BoundVersion,\n        toolsVersion: ToolsVersion? = nil,\n        with dependencies: KeyValuePairs<String, OrderedCollections.OrderedDictionary<String, (PackageRequirement, ProductFilter)>> = [:]\n    ) throws {\n        let container = self.containers[packageReference.identity.description] ?? MockContainer(package: packageReference)\n\n        if case .version(let v) = version {\n            container.versionsToolsVersions[v] = toolsVersion ?? container.toolsVersion\n        }\n\n        container.appendVersion(version)\n\n        if container.dependencies[version.description] == nil {\n            container.dependencies[version.description] = [:]\n        }\n        for (product, filteredDependencies) in dependencies {\n            let packageDependencies: [MockContainer.Dependency] = try filteredDependencies.map {\n                (container: try reference(for: $0), requirement: $1.0, productFilter: $1.1)\n            }\n            container.dependencies[version.description, default: [:]][product, default: []] += packageDependencies\n        }\n        self.containers[packageReference.identity.description] = container\n    }\n\n    /// Creates a `Package.resolved` store with the given resolution results.\n    func create(\n        resolvedPackages: [String: (ResolvedPackagesStore.ResolutionState, ProductFilter)]\n    ) throws -> ResolvedPackagesStore {\n        let fs = InMemoryFileSystem()\n        let store = try! ResolvedPackagesStore(\n            packageResolvedFile: \"/tmp/Package.resolved\",\n            workingDirectory: .root,\n            fileSystem: fs,\n            mirrors: .init()\n        )\n\n        for (package, resolution) in resolvedPackages {\n            store.track(packageRef: try reference(for: package), state: resolution.0)\n        }\n\n        try! store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n        return store\n    }\n\n\n    func create(\n        resolvedPackages: ResolvedPackagesStore.ResolvedPackages = [:],\n        delegate: DependencyResolverDelegate? = .none\n    ) -> PubGrubDependencyResolver {\n        defer {\n            self.containers = [:]\n            self.references = [:]\n        }\n        let provider = MockProvider(containers: Array(self.containers.values))\n        return PubGrubDependencyResolver(\n            provider: provider,\n            resolvedPackages: resolvedPackages,\n            observabilityScope: ObservabilitySystem.NOOP,\n            delegate: delegate\n        )\n    }\n}\n\nextension Term {\n    init(_ value: String) {\n        self.init(stringLiteral: value)\n    }\n\n    public init(stringLiteral value: String) {\n        var value = value\n\n        var isPositive = true\n        if value.hasPrefix(\"¬\") {\n            value.removeFirst()\n            isPositive = false\n        }\n\n        var components: [String] = []\n        var requirement: PackageRequirement?\n\n        if value.contains(\"@\") {\n            components = value.split(separator: \"@\").map(String.init)\n            if components[1].contains(\".\") {\n                requirement = .versionSet(.exact(Version(stringLiteral: components[1])))\n            }\n        } else if value.contains(\"^\") {\n            components = value.split(separator: \"^\").map(String.init)\n            let upperMajor = Int(String(components[1].split(separator: \".\").first!))! + 1\n            requirement = .versionSet(.range(Version(stringLiteral: components[1])..<Version(stringLiteral: \"\\(upperMajor).0.0\")))\n        } else if value.contains(\"-\") {\n            components = value.split(separator: \"-\").map(String.init)\n            assert(components.count == 3, \"expected `name-lowerBound-upperBound`\")\n            let (lowerBound, upperBound) = (components[1], components[2])\n            requirement = .versionSet(.range(Version(stringLiteral: lowerBound)..<Version(stringLiteral: upperBound)))\n        }\n\n        let packageReference = PackageReference(identity: .plain(components[0]), kind: .localSourceControl(.root), name: components[0])\n\n        guard case let .versionSet(vs) = requirement! else {\n            fatalError()\n        }\n        self.init(node: .product(packageReference.identity.description, package: packageReference),\n                  requirement: vs,\n                  isPositive: isPositive)\n    }\n}\n\n\nextension PackageReference {\n    public init(stringLiteral value: String) {\n        let ref = PackageReference.localSourceControl(identity: .plain(value), path: .root)\n        self = ref\n    }\n}\n\nextension Term: ExpressibleByStringLiteral {}\nextension PackageReference: ExpressibleByStringLiteral {}\n\nextension Result where Success == [DependencyResolverBinding] {\n    var errorMsg: String? {\n        switch self {\n        case .failure(let error):\n            switch error {\n            case let err as PubGrubDependencyResolver.PubGrubError:\n                guard case .unresolvable(let msg) = err else {\n                    XCTFail(\"Unexpected result \\(self)\")\n                    return nil\n                }\n                return msg\n            case let error as DependencyResolverError:\n                return error.description\n            default:\n                XCTFail(\"Unexpected result \\(self)\")\n        }\n        default:\n            XCTFail(\"Unexpected result \\(self)\")\n        }\n        return nil\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphTests/ResolvedTargetTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\nimport PackageGraph\n@testable import PackageModel\nimport _InternalTestSupport\n\nprivate func XCTAssertEqualTargetIDs(\n    _ lhs: [ResolvedModule],\n    _ rhs: [ResolvedModule],\n    file: StaticString = #filePath,\n    line: UInt = #line\n) {\n    XCTAssertEqual(lhs.map(\\.id), rhs.map(\\.id), file: file, line: line)\n}\n\nfinal class ResolvedModuleDependencyTests: XCTestCase {\n    func test1() throws {\n        let t1 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t1\")\n        let t2 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t2\", deps: t1)\n        let t3 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t3\", deps: t2)\n\n        XCTAssertEqualTargetIDs(try t3.recursiveModuleDependencies(), [t2, t1])\n        XCTAssertEqualTargetIDs(try t2.recursiveModuleDependencies(), [t1])\n    }\n\n    func test2() throws {\n        let t1 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t1\")\n        let t2 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t2\", deps: t1)\n        let t3 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t3\", deps: t2, t1)\n        let t4 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t4\", deps: t2, t3, t1)\n\n        XCTAssertEqualTargetIDs(try t4.recursiveModuleDependencies(), [t3, t2, t1])\n        XCTAssertEqualTargetIDs(try t3.recursiveModuleDependencies(), [t2, t1])\n        XCTAssertEqualTargetIDs(try t2.recursiveModuleDependencies(), [t1])\n    }\n\n    func test3() throws {\n        let t1 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t1\")\n        let t2 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t2\", deps: t1)\n        let t3 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t3\", deps: t2, t1)\n        let t4 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t4\", deps: t1, t2, t3)\n\n        XCTAssertEqualTargetIDs(try t4.recursiveModuleDependencies(), [t3, t2, t1])\n        XCTAssertEqualTargetIDs(try t3.recursiveModuleDependencies(), [t2, t1])\n        XCTAssertEqualTargetIDs(try t2.recursiveModuleDependencies(), [t1])\n    }\n\n    func test4() throws {\n        let t1 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t1\")\n        let t2 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t2\", deps: t1)\n        let t3 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t3\", deps: t2)\n        let t4 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t4\", deps: t3)\n\n        XCTAssertEqualTargetIDs(try t4.recursiveModuleDependencies(), [t3, t2, t1])\n        XCTAssertEqualTargetIDs(try t3.recursiveModuleDependencies(), [t2, t1])\n        XCTAssertEqualTargetIDs(try t2.recursiveModuleDependencies(), [t1])\n    }\n\n    func test5() throws {\n        let t1 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t1\")\n        let t2 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t2\", deps: t1)\n        let t3 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t3\", deps: t2)\n        let t4 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t4\", deps: t3)\n        let t5 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t5\", deps: t2)\n        let t6 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t6\", deps: t5, t4)\n\n        // precise order is not important, but it is important that the following are true\n        let t6rd = try t6.recursiveModuleDependencies().map(\\.id)\n        XCTAssertEqual(t6rd.firstIndex(of: t3.id)!, t6rd.index(after: t6rd.firstIndex(of: t4.id)!))\n        XCTAssert(t6rd.firstIndex(of: t5.id)! < t6rd.firstIndex(of: t2.id)!)\n        XCTAssert(t6rd.firstIndex(of: t5.id)! < t6rd.firstIndex(of: t1.id)!)\n        XCTAssert(t6rd.firstIndex(of: t2.id)! < t6rd.firstIndex(of: t1.id)!)\n        XCTAssert(t6rd.firstIndex(of: t3.id)! < t6rd.firstIndex(of: t2.id)!)\n\n        XCTAssertEqualTargetIDs(try t5.recursiveModuleDependencies(), [t2, t1])\n        XCTAssertEqualTargetIDs(try t4.recursiveModuleDependencies(), [t3, t2, t1])\n        XCTAssertEqualTargetIDs(try t3.recursiveModuleDependencies(), [t2, t1])\n        XCTAssertEqualTargetIDs(try t2.recursiveModuleDependencies(), [t1])\n    }\n\n    func test6() throws {\n        let t1 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t1\")\n        let t2 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t2\", deps: t1)\n        let t3 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t3\", deps: t2)\n        let t4 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t4\", deps: t3)\n        let t5 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t5\", deps: t2)\n        let t6 = ResolvedModule.mock(\n            packageIdentity: \"pkg\",\n            name: \"t6\",\n            deps: t4,\n            t5\n        ) // same as above, but these two swapped\n\n        // precise order is not important, but it is important that the following are true\n        let t6rd = try t6.recursiveModuleDependencies().map(\\.id)\n        XCTAssertEqual(t6rd.firstIndex(of: t3.id)!, t6rd.index(after: t6rd.firstIndex(of: t4.id)!))\n        XCTAssert(t6rd.firstIndex(of: t5.id)! < t6rd.firstIndex(of: t2.id)!)\n        XCTAssert(t6rd.firstIndex(of: t5.id)! < t6rd.firstIndex(of: t1.id)!)\n        XCTAssert(t6rd.firstIndex(of: t2.id)! < t6rd.firstIndex(of: t1.id)!)\n        XCTAssert(t6rd.firstIndex(of: t3.id)! < t6rd.firstIndex(of: t2.id)!)\n\n        XCTAssertEqualTargetIDs(try t5.recursiveModuleDependencies(), [t2, t1])\n        XCTAssertEqualTargetIDs(try t4.recursiveModuleDependencies(), [t3, t2, t1])\n        XCTAssertEqualTargetIDs(try t3.recursiveModuleDependencies(), [t2, t1])\n        XCTAssertEqualTargetIDs(try t2.recursiveModuleDependencies(), [t1])\n    }\n\n    func testConditions() throws {\n        let t1 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t1\")\n        let t2 = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t2\", deps: t1)\n        let t2NoConditions = ResolvedModule.mock(packageIdentity: \"pkg\", name: \"t2\", deps: t1)\n        let t2WithConditions = ResolvedModule.mock(\n            packageIdentity: \"pkg\",\n            name: \"t2\",\n            deps: t1,\n            conditions: [.init(platforms: [.linux])]\n        )\n\n        // FIXME: we should test for actual `t2` and `t2NoConditions` equality, but `SwiftTarget` is a reference type,\n        // which currently breaks this test, and it shouldn't\n        XCTAssertEqual(t2.dependencies, t2NoConditions.dependencies)\n        XCTAssertEqual(t2.dependencies, t2WithConditions.dependencies)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphTests/TopologicalSortTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2016-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\n@testable import PackageGraph\nimport XCTest\n\nprivate func XCTAssertThrows<T: Swift.Error>(\n    _ expectedError: T,\n    file: StaticString = #file,\n    line: UInt = #line,\n    _ body: () throws -> Void\n) where T: Equatable {\n    do {\n        try body()\n        XCTFail(\"body completed successfully\", file: file, line: line)\n    } catch let error as T {\n        XCTAssertEqual(error, expectedError, file: file, line: line)\n    } catch {\n        XCTFail(\"unexpected error thrown: \\(error)\", file: file, line: line)\n    }\n}\n\nextension Int {\n    public var id: Self { self }\n}\n\nextension Int: @retroactive Identifiable {}\n\nprivate func topologicalSort(_ nodes: [Int], _ successors: [Int: [Int]]) throws -> [Int] {\n    return try topologicalSortIdentifiable(nodes, successors: { successors[$0] ?? [] })\n}\nprivate func topologicalSort(_ node: Int, _ successors: [Int: [Int]]) throws -> [Int] {\n    return try topologicalSort([node], successors)\n}\n\nfinal class TopologicalSortTests: XCTestCase {\n    func testTopologicalSort() throws {\n        // A trivial graph.\n        XCTAssertEqual([1, 2], try topologicalSort(1, [1: [2]]))\n        XCTAssertEqual([1, 2], try topologicalSort([2, 1], [1: [2]]))\n\n        // A diamond.\n        let diamond: [Int: [Int]] = [\n            1: [3, 2],\n            2: [4],\n            3: [4]\n        ]\n        XCTAssertEqual([1, 2, 3, 4], try topologicalSort(1, diamond))\n        XCTAssertEqual([2, 3, 4], try topologicalSort([3, 2], diamond))\n        XCTAssertEqual([1, 2, 3, 4], try topologicalSort([4, 3, 2, 1], diamond))\n\n        // Test cycle detection.\n        XCTAssertThrows(GraphError.unexpectedCycle) { _ = try topologicalSort(1, [1: [1]]) }\n        XCTAssertThrows(GraphError.unexpectedCycle) { _ = try topologicalSort(1, [1: [2], 2: [1]]) }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageGraphTests/VersionSetSpecifierTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport TSCUtility\nimport XCTest\n\nimport PackageGraph\n\nfinal class VersionSetSpecifierTests: XCTestCase {\n    func testUnion() {\n        XCTAssertEqual(VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.0.1\"]), .exact(\"1.0.0\"))\n        XCTAssertEqual(VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.0.5\"]), .range(\"1.0.0\"..<\"1.0.5\"))\n        XCTAssertEqual(VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.0.6\", \"1.0.5\"..<\"1.0.9\"]), .range(\"1.0.0\"..<\"1.0.9\"))\n        XCTAssertEqual(VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.0.5\", \"1.0.5\"..<\"1.0.9\"]), .range(\"1.0.0\"..<\"1.0.9\"))\n        XCTAssertEqual(VersionSetSpecifier.union(from: [\"1.0.5\"..<\"1.0.9\", \"1.0.0\"..<\"1.0.5\"]), .range(\"1.0.0\"..<\"1.0.9\"))\n        XCTAssertEqual(VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.0.5\", \"1.0.5\"..<\"1.0.9\", \"1.0.11\"..<\"1.0.15\"]), .ranges([\"1.0.0\"..<\"1.0.9\", \"1.0.11\"..<\"1.0.15\"]))\n        XCTAssertEqual(VersionSetSpecifier.exact(\"1.0.0\").union(.exact(\"1.0.0\")), .exact(\"1.0.0\"))\n\n        let ranges1 = VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.1.0\", \"1.1.1\"..<\"2.0.0\"])\n        XCTAssertEqual(ranges1.union(.exact(\"1.1.0\")), .range(\"1.0.0\"..<\"2.0.0\"))\n\n        XCTAssertEqual(VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.0.0\", \"1.0.1\"..<\"2.0.0\"]), .range(\"1.0.0\"..<\"2.0.0\"))\n    }\n\n    func testIntersection() {\n        let ranges = VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.0.5\", \"1.0.6\"..<\"1.0.10\"])\n        XCTAssertEqual(ranges.intersection(.range(\"1.0.1\"..<\"1.0.8\")), .ranges([\"1.0.1\"..<\"1.0.5\", \"1.0.6\"..<\"1.0.8\"]))\n\n        let ranges1 = VersionSetSpecifier.union(from: [\"1.0.0\"..<\"1.0.5\", \"1.0.6\"..<\"1.0.10\"])\n        let ranges2 = VersionSetSpecifier.union(from: [\"1.0.1\"..<\"1.0.3\", \"1.0.8\"..<\"1.0.9\"])\n        XCTAssertEqual(ranges1.intersection(ranges2), .ranges([\"1.0.1\"..<\"1.0.3\", \"1.0.8\"..<\"1.0.9\"]))\n    }\n\n    func testDifference() {\n        do {\n            let v1: VersionSetSpecifier = .exact(\"1.0.0\")\n            let v2: VersionSetSpecifier = .exact(\"2.0.0\")\n            XCTAssertEqual(v1.difference(v1), .empty)\n            XCTAssertEqual(v2.difference(v1), v2)\n        }\n\n        do {\n            let v1: VersionSetSpecifier = .range(\"1.0.0\"..<\"1.0.0\")\n            let v2: VersionSetSpecifier = .range(\"2.0.0\"..<\"2.0.0\")\n            XCTAssertEqual(v1.difference(v1), .empty)\n            XCTAssertEqual(v2.difference(v1), v2)\n        }\n\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0\"..<\"2.0.0\").difference(.exact(\"2.0.0\")), .range(\"1.0.0\"..<\"2.0.0\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0\"..<\"2.0.0\").difference(.exact(\"1.0.0\")), .range(\"1.0.1\"..<\"2.0.0\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0\"..<\"2.0.0\").difference(.exact(\"1.5.0\")), .ranges([\"1.0.0\"..<\"1.5.0\", \"1.5.1\"..<\"2.0.0\"]))\n        XCTAssertEqual(VersionSetSpecifier.range(\"2.0.0\"..<\"2.0.0\").difference(.exact(\"2.0.0\")), .empty)\n        XCTAssertEqual(VersionSetSpecifier.range(\"2.0.0\"..<\"2.0.1\").difference(.exact(\"2.0.0\")), .empty)\n\n        XCTAssertEqual(VersionSetSpecifier.exact(\"1.0.0\").difference(.range(\"1.0.0\"..<\"2.0.0\")), .empty)\n        XCTAssertEqual(VersionSetSpecifier.exact(\"3.0.0\").difference(.range(\"1.0.0\"..<\"2.0.0\")), .exact(\"3.0.0\"))\n\n        XCTAssertEqual(VersionSetSpecifier.exact(\"3.0.0\").difference(.any), .empty)\n\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"1.0.0\"..<\"2.0.0\", \"3.0.0\"..<\"4.0.0\"]).difference(.exact(\"2.0.0\")), .ranges([\"1.0.0\"..<\"2.0.0\", \"3.0.0\"..<\"4.0.0\"]))\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"1.0.0\"..<\"2.0.0\", \"3.0.0\"..<\"4.0.0\"]).difference(.exact(\"1.0.0\")), .ranges([\"1.0.1\"..<\"2.0.0\", \"3.0.0\"..<\"4.0.0\"]))\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"1.0.0\"..<\"2.0.0\", \"3.0.0\"..<\"4.0.0\"]).difference(.exact(\"3.5.0\")), .ranges([\"1.0.0\"..<\"2.0.0\", \"3.0.0\"..<\"3.5.0\", \"3.5.1\"..<\"4.0.0\"]))\n\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"1.0.0\"..<\"1.0.0\", \"3.0.0\"..<\"4.0.0\"]).difference(.exact(\"1.0.0\")), .range(\"3.0.0\"..<\"4.0.0\"))\n\n        XCTAssertEqual(VersionSetSpecifier.exact(\"1.5.0\").difference(.ranges([\"1.0.0\"..<\"2.0.0\", \"3.0.0\"..<\"4.0.0\"])), .empty)\n        XCTAssertEqual(VersionSetSpecifier.exact(\"2.0.0\").difference(.ranges([\"1.0.0\"..<\"2.0.0\", \"3.0.0\"..<\"4.0.0\"])), .exact(\"2.0.0\"))\n\n        do {\n            let v1: VersionSetSpecifier = .range(\"1.0.0\"..<\"2.0.0\")\n            let v1_5: VersionSetSpecifier = .range(\"1.5.0\"..<\"2.0.0\")\n            let v1_49: VersionSetSpecifier = .range(\"1.4.9\"..<\"2.0.0\")\n\n            XCTAssertEqual(v1.difference(v1), .empty)\n            XCTAssertEqual(v1.difference(.range(\"2.0.0\"..<\"2.0.0\")), v1)\n            XCTAssertEqual(v1.difference(v1_5), .range(\"1.0.0\"..<\"1.5.0\"))\n            XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0\"..<\"2.0.0\").difference(.range(\"1.1.0\"..<\"1.5.0\")), .ranges([\"1.0.0\"..<\"1.1.0\", \"1.5.0\"..<\"2.0.0\"]))\n            XCTAssertEqual(v1_49.difference(v1_5), .range(\"1.4.9\"..<\"1.5.0\"))\n            XCTAssertEqual(v1_5.difference(v1_49), .empty)\n        }\n\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0\"..<\"5.0.0\").difference(.ranges([\"1.0.0\"..<\"2.0.0\", \"3.0.0\"..<\"4.0.0\"])), .ranges([\"2.0.0\"..<\"3.0.0\", \"4.0.0\"..<\"5.0.0\"]))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0\"..<\"2.0.0\").difference(.range(\"1.0.0\"..<\"1.8.0\")), .range(\"1.8.0\"..<\"2.0.0\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0\"..<\"5.0.0\").difference(.ranges([\"1.0.0\"..<\"2.0.0\", \"2.0.1\"..<\"5.0.0\"])), .exact(\"2.0.0\"))\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"3.2.1\"..<\"3.2.4\", \"3.2.5\"..<\"4.0.0\"]).difference(.ranges([\"3.2.1\"..<\"3.2.3\", \"3.2.3\"..<\"4.0.0\"])), .exact(\"3.2.3\"))\n\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"1.0.0\"..<\"2.0.0\", \"2.0.1\"..<\"5.0.0\"]).difference(.ranges([\"1.0.0\"..<\"2.0.0\", \"2.0.1\"..<\"5.0.0\"])), .empty)\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"0.0.0\"..<\"0.9.1\", \"1.0.0\"..<\"2.0.0\", \"2.0.1\"..<\"5.0.0\"]).difference(.ranges([\"1.0.0\"..<\"1.4.0\", \"2.4.1\"..<\"4.0.0\"])), .ranges([\"0.0.0\"..<\"0.9.1\", \"1.4.0\"..<\"2.0.0\", \"2.0.1\"..<\"2.4.1\", \"4.0.0\"..<\"5.0.0\"]))\n\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"1.0.0\"..<\"2.0.0\", \"2.0.1\"..<\"5.0.0\"]).difference(.range(\"1.0.0\"..<\"2.0.0\")), .range(\"2.0.1\"..<\"5.0.0\"))\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"3.2.0\"..<\"3.2.3\", \"3.2.4\"..<\"4.0.0\"]).difference(.exact(\"3.2.2\")), .ranges([\"3.2.0\"..<\"3.2.2\", \"3.2.4\"..<\"4.0.0\"]))\n        XCTAssertEqual(VersionSetSpecifier.ranges([\"3.2.0\"..<\"3.2.1\", \"3.2.3\"..<\"4.0.0\"]).difference(.exact(\"3.2.0\")), .range(\"3.2.3\"..<\"4.0.0\"))\n\n\n        XCTAssertEqual(VersionSetSpecifier.exact(\"1.0.0-beta\").difference(.exact(\"1.0.0-beta\")), .empty)\n        XCTAssertEqual(VersionSetSpecifier.exact(\"2.0.0-beta\").difference(.exact(\"1.0.0\")), .exact(\"2.0.0-beta\"))\n        XCTAssertEqual(VersionSetSpecifier.exact(\"2.0.0-beta\").difference(.exact(\"1.0.0-beta\")), .exact(\"2.0.0-beta\"))\n\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-beta\"..<\"1.0.0-beta\").difference(.range(\"1.0.0-beta\"..<\"1.0.0-beta\")), .empty)\n        XCTAssertEqual(VersionSetSpecifier.range(\"2.0.0-beta\"..<\"2.0.0-beta\").difference(.range(\"1.0.0\"..<\"2.0.0\")), .range(\"2.0.0-beta\"..<\"2.0.0-beta\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"2.0.0-beta\"..<\"2.0.0-beta\").difference(.range(\"1.0.0-beta\"..<\"2.0.0\")), .range(\"2.0.0-beta\"..<\"2.0.0-beta\"))\n\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-beta\"..<\"2.0.0\").difference(.exact(\"2.0.0\")), .range(\"1.0.0-beta\"..<\"2.0.0\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-beta\"..<\"2.0.0\").difference(.exact(\"1.0.0-beta\")), .range(\"1.0.0-beta.0\"..<\"2.0.0\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-beta\"..<\"2.0.0\").difference(.exact(\"1.0.0-beta.5\")), .ranges([\"1.0.0-beta\"..<\"1.0.0-beta.5\", \"1.0.0-beta.5.0\"..<\"2.0.0\"]))\n\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-beta\"..<\"2.0.0\").difference(.range(\"1.0.0-beta.3\" ..< \"2.0.0\")), .range(\"1.0.0-beta\"..<\"1.0.0-beta.3\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-beta.5\"..<\"1.0.0-beta.30\").difference(.range(\"1.0.0-beta.10\" ..< \"2.0.0\")), .range(\"1.0.0-beta.5\"..<\"1.0.0-beta.10\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-beta\"..<\"1.0.0-beta.30\").difference(.range(\"1.0.0-beta.3\" ..< \"1.0.0-beta.10\")), .ranges([\"1.0.0-beta\"..<\"1.0.0-beta.3\", \"1.0.0-beta.10\"..<\"1.0.0-beta.30\"]))\n\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-alpha\"..<\"2.0.0\").difference(.range(\"1.0.0-beta\" ..< \"2.0.0\")), .range(\"1.0.0-alpha\"..<\"1.0.0-beta\"))\n        XCTAssertEqual(VersionSetSpecifier.range(\"1.0.0-beta\"..<\"2.0.0\").difference(.range(\"1.0.0-alpha\" ..< \"2.0.0\")), .empty)\n    }\n\n    func testEquality() {\n        // Basic cases.\n        XCTAssertTrue(VersionSetSpecifier.any == VersionSetSpecifier.any)\n        XCTAssertTrue(VersionSetSpecifier.empty == VersionSetSpecifier.empty)\n        XCTAssertTrue(VersionSetSpecifier.range(\"1.0.0\"..<\"5.0.0\") == VersionSetSpecifier.range(\"1.0.0\"..<\"5.0.0\"))\n        XCTAssertTrue(VersionSetSpecifier.exact(\"1.2.3\") == VersionSetSpecifier.exact(\"1.2.3\"))\n        XCTAssertTrue(VersionSetSpecifier.ranges([\"3.2.0\"..<\"3.2.1\", \"3.2.3\"..<\"4.0.0\"]) == VersionSetSpecifier.ranges([\"3.2.0\"..<\"3.2.1\", \"3.2.3\"..<\"4.0.0\"]))\n\n        // Empty is equivalent to an empty list of ranges or if the list contains one range where the lower bound equals the upper bound./\n        XCTAssertTrue(VersionSetSpecifier.empty == VersionSetSpecifier.ranges([]))\n        XCTAssertTrue(VersionSetSpecifier.ranges([]) == VersionSetSpecifier.empty)\n        XCTAssertTrue(VersionSetSpecifier.empty == VersionSetSpecifier.ranges([\"2.0.0\"..<\"2.0.0\"]))\n        XCTAssertTrue(VersionSetSpecifier.ranges([\"2.0.0\"..<\"2.0.0\"]) == VersionSetSpecifier.empty)\n\n        // Empty is equivalent to a range where the lower bound equals the upper bound.\n        XCTAssertTrue(VersionSetSpecifier.empty == VersionSetSpecifier.range(\"2.0.0\"..<\"2.0.0\"))\n        XCTAssertTrue(VersionSetSpecifier.range(\"2.0.0\"..<\"2.0.0\") == VersionSetSpecifier.empty)\n\n        // Exact is equal to a range that spans a single patch.\n        XCTAssertTrue(VersionSetSpecifier.exact(\"2.0.1\") == VersionSetSpecifier.range(\"2.0.1\"..<\"2.0.2\"))\n        XCTAssertTrue(VersionSetSpecifier.range(\"2.0.1\"..<\"2.0.2\") == VersionSetSpecifier.exact(\"2.0.1\"))\n\n        // Exact is also equal to a list of ranges with one entry that spans a single patch.\n        XCTAssertTrue(VersionSetSpecifier.exact(\"2.0.1\") == VersionSetSpecifier.ranges([\"2.0.1\"..<\"2.0.2\"]))\n        XCTAssertTrue(VersionSetSpecifier.ranges([\"2.0.1\"..<\"2.0.2\"]) == VersionSetSpecifier.exact(\"2.0.1\"))\n\n        // A range is equal to a list of ranges with that one range.\n        XCTAssertTrue(VersionSetSpecifier.range(\"2.0.1\"..<\"2.0.2\") == VersionSetSpecifier.ranges([\"2.0.1\"..<\"2.0.2\"]))\n        XCTAssertTrue(VersionSetSpecifier.ranges([\"2.0.1\"..<\"2.0.2\"]) == VersionSetSpecifier.range(\"2.0.1\"..<\"2.0.2\"))\n    }\n\n    func testPrereleases() {\n        XCTAssertFalse(VersionSetSpecifier.any.supportsPrereleases)\n        XCTAssertFalse(VersionSetSpecifier.empty.supportsPrereleases)\n        XCTAssertFalse(VersionSetSpecifier.exact(\"0.0.1\").supportsPrereleases)\n\n        XCTAssertTrue(VersionSetSpecifier.exact(\"0.0.1-latest\").supportsPrereleases)\n        XCTAssertTrue(VersionSetSpecifier.range(\"0.0.1-latest\" ..< \"2.0.0\").supportsPrereleases)\n        XCTAssertTrue(VersionSetSpecifier.range(\"0.0.1\" ..< \"2.0.0-latest\").supportsPrereleases)\n\n        XCTAssertTrue(VersionSetSpecifier.ranges([\n            \"0.0.1\" ..< \"0.0.2\",\n            \"0.0.1\" ..< \"2.0.0-latest\",\n        ]).supportsPrereleases)\n\n        XCTAssertTrue(VersionSetSpecifier.ranges([\n            \"0.0.1-latest\" ..< \"0.0.2\",\n            \"0.0.1\" ..< \"2.0.0\",\n        ]).supportsPrereleases)\n\n        XCTAssertFalse(VersionSetSpecifier.ranges([\n            \"0.0.1\" ..< \"0.0.2\",\n            \"0.0.1\" ..< \"2.0.0\",\n        ]).supportsPrereleases)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/Inputs/Bar.pc",
    "content": "prefix=/usr\nexec_prefix=${prefix}\nlibdir=${exec_prefix}/lib\nincludedir=${prefix}/include\n\nName: Foo\nURL: http://127.0.0.1/\nDescription: The one and only SystemModule\nVersion: 1.10.0\nCflags: -I${includedir} -I/path/to/inc -DDenyListed\nLibs: -L${libdir} -L/usr/da/lib -lSystemModule -lok\n"
  },
  {
    "path": "Tests/PackageLoadingTests/Inputs/Dependency.pc",
    "content": "Name: Dependency\nCflags: -I/path/to/dependency/include\nLibs: -L/path/to/dependency/lib\n"
  },
  {
    "path": "Tests/PackageLoadingTests/Inputs/Dependent.pc",
    "content": "Name: Dependent\nCflags: -I/path/to/dependent/include\nLibs: -L/path/to/dependent/lib\nRequires: Dependency\n"
  },
  {
    "path": "Tests/PackageLoadingTests/Inputs/Foo.pc",
    "content": "prefix=/usr\nexec_prefix=${prefix}\nlibdir=${exec_prefix}/lib\nincludedir=${prefix}/include\n\nName: Foo\nURL: http://127.0.0.1/\nDescription: The one and only SystemModule\nVersion: 1.10.0\nCflags: -I${includedir} -I/path/to/inc -I${pcfiledir}\nLibs: -L${libdir} -L/usr/da/lib -lSystemModule -lok\n"
  },
  {
    "path": "Tests/PackageLoadingTests/Inputs/Framework.pc",
    "content": "prefix=/usr\nexec_prefix=${prefix}\nlibdir=${exec_prefix}/lib\nincludedir=${prefix}/include\n\nName: Foo\nURL: http://127.0.0.1/\nDescription: The one and only SystemFramework\nVersion: 1.10.0\nCflags: -I${includedir} -F${libdir} -DDenyListed\nLibs: -F${libdir} -framework SystemFramework\n"
  },
  {
    "path": "Tests/PackageLoadingTests/Inputs/package-deps-manifest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2016 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport PackageDescription\n\nlet package = Package(\n    name: \"PackageDeps\",\n    dependencies: [\n        .Package(url: \"https://example.com/example\", majorVersion: 1)])\n"
  },
  {
    "path": "Tests/PackageLoadingTests/Inputs/target-deps-manifest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2016 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport PackageDescription\n\nlet package = Package(\n    name: \"TargetDeps\",\n    targets: [\n        Target(\n            name: \"sys\",\n            dependencies: [.Target(name: \"libc\")]),\n        Target(\n            name: \"dep\",\n            dependencies: [.Target(name: \"sys\"), .Target(name: \"libc\")])])\n"
  },
  {
    "path": "Tests/PackageLoadingTests/Inputs/trivial-manifest.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2016 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport PackageDescription\n\nlet package = Package(name: \"Trivial\")\n"
  },
  {
    "path": "Tests/PackageLoadingTests/ManifestLoaderCacheTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\n@testable import PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\n@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)\nfinal class ManifestLoaderCacheTests: XCTestCase {\n\n    func testDBCaching() async throws {\n        try await testWithTemporaryDirectory { path in\n            let fileSystem = localFileSystem\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let manifestPath = path.appending(components: \"pkg\", \"Package.swift\")\n            try fileSystem.createDirectory(manifestPath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                    import PackageDescription\n                    let package = Package(\n                        name: \"Trivial\",\n                        targets: [\n                            .target(\n                                name: \"foo\",\n                                dependencies: []),\n                        ]\n                    )\n                    \"\"\"\n            )\n\n            let delegate = ManifestTestDelegate()\n\n            let manifestLoader = ManifestLoader(\n                toolchain: try UserToolchain.default,\n                useInMemoryCache: false,\n                cacheDir: path,\n                delegate: delegate\n            )\n\n            func check(loader: ManifestLoader, expectCached: Bool) async throws {\n                delegate.clear()\n\n                let manifest = try await XCTAsyncUnwrap(try await loader.load(\n                    manifestPath: manifestPath,\n                    packageKind: .root(manifestPath.parentDirectory),\n                    toolsVersion: .current,\n                    fileSystem: fileSystem,\n                    observabilityScope: observability.topScope\n                ))\n\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)), [manifestPath])\n                try await XCTAssertAsyncEqual(try await delegate.parsed(timeout: .seconds(1)).count, (expectCached ? 0 : 1))\n                XCTAssertEqual(manifest.displayName, \"Trivial\")\n                XCTAssertEqual(manifest.targets[0].name, \"foo\")\n            }\n\n            try await check(loader: manifestLoader, expectCached: false)\n            for _ in 0..<2 {\n                try await check(loader: manifestLoader, expectCached: true)\n            }\n\n            try fileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                    import PackageDescription\n\n                    let package = Package(\n                        name: \"Trivial\",\n                        targets: [\n                            .target(\n                                name: \"foo\",\n                                dependencies: [  ]),\n                        ]\n                    )\n\n                    \"\"\"\n            )\n\n            try await check(loader: manifestLoader, expectCached: false)\n            for _ in 0..<2 {\n                try await check(loader: manifestLoader, expectCached: true)\n            }\n\n            let noCacheLoader = ManifestLoader(\n                toolchain: try UserToolchain.default,\n                useInMemoryCache: false,\n                cacheDir: .none,\n                delegate: delegate\n            )\n            for _ in 0..<2 {\n                try await check(loader: noCacheLoader, expectCached: false)\n            }\n\n            // Resetting the cache should allow us to remove the cache\n            // directory without triggering assertions in sqlite.\n            await manifestLoader.purgeCache(observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try fileSystem.removeFileTree(path)\n        }\n    }\n\n    func testInMemoryCaching() async throws {\n        let fileSystem = InMemoryFileSystem()\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let manifestPath = AbsolutePath.root.appending(components: \"pkg\", \"Package.swift\")\n        try fileSystem.createDirectory(manifestPath.parentDirectory, recursive: true)\n        try fileSystem.writeFileContents(\n            manifestPath,\n            string: \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    targets: [\n                        .target(\n                            name: \"foo\",\n                            dependencies: []),\n                    ]\n                )\n                \"\"\"\n        )\n\n        let delegate = ManifestTestDelegate()\n\n        let manifestLoader = ManifestLoader(\n            toolchain: try UserToolchain.default,\n            useInMemoryCache: true,\n            cacheDir: .none,\n            delegate: delegate\n        )\n\n        func check(loader: ManifestLoader, expectCached: Bool) async throws {\n            delegate.clear()\n\n            let manifest = try await XCTAsyncUnwrap(try await loader.load(\n                manifestPath: manifestPath,\n                packageKind: .root(manifestPath.parentDirectory),\n                toolsVersion: .current,\n                fileSystem: fileSystem,\n                observabilityScope: observability.topScope\n            ))\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)), [manifestPath])\n            try await XCTAssertAsyncEqual(try await delegate.parsed(timeout: .seconds(1)).count, expectCached ? 0 : 1)\n            XCTAssertEqual(manifest.displayName, \"Trivial\")\n            XCTAssertEqual(manifest.targets[0].name, \"foo\")\n        }\n\n        try await check(loader: manifestLoader, expectCached: false)\n        for _ in 0..<2 {\n            try await check(loader: manifestLoader, expectCached: true)\n        }\n\n        try fileSystem.writeFileContents(\n            manifestPath,\n            string: \"\"\"\n                import PackageDescription\n\n                let package = Package(\n                    name: \"Trivial\",\n                    targets: [\n                        .target(\n                            name: \"foo\",\n                            dependencies: [  ]),\n                    ]\n                )\n\n                \"\"\"\n        )\n\n        try await check(loader: manifestLoader, expectCached: false)\n        for _ in 0..<2 {\n            try await check(loader: manifestLoader, expectCached: true)\n        }\n\n        let noCacheLoader = ManifestLoader(\n            toolchain: try UserToolchain.default,\n            useInMemoryCache: false,\n            cacheDir: .none,\n            delegate: delegate\n        )\n        for _ in 0..<2 {\n            try await check(loader: noCacheLoader, expectCached: false)\n        }\n\n        await manifestLoader.purgeCache(observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testContentBasedCaching() async throws {\n        try await testWithTemporaryDirectory { path in\n            let manifest = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    targets: [\n                        .target(name: \"foo\"),\n                    ]\n                )\n            \"\"\"\n\n            let delegate = ManifestTestDelegate()\n\n            let manifestLoader = ManifestLoader(\n                toolchain: try UserToolchain.default,\n                cacheDir: path,\n                delegate: delegate\n            )\n\n            func check(loader: ManifestLoader, manifest: String) async throws {\n                let fileSystem = InMemoryFileSystem()\n                let observability = ObservabilitySystem.makeForTesting()\n\n                let manifestPath = AbsolutePath.root.appending(component: Manifest.filename)\n                try fileSystem.writeFileContents(manifestPath, string: manifest)\n\n                let m = try await manifestLoader.load(\n                    manifestPath: manifestPath,\n                    packageKind: .root(.root),\n                    toolsVersion: .current,\n                    fileSystem: fileSystem,\n                    observabilityScope: observability.topScope\n                )\n\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                XCTAssertEqual(m.displayName, \"Trivial\")\n            }\n\n            do {\n                try await check(loader: manifestLoader, manifest: manifest)\n                try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)).count, 1)\n                try await XCTAssertAsyncEqual(try await delegate.parsed(timeout: .seconds(1)).count, 1)\n            }\n\n            do {\n                try await check(loader: manifestLoader, manifest: manifest)\n                try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)).count, 2)\n                try await XCTAssertAsyncEqual(try await delegate.parsed(timeout: .seconds(1)).count, 1)\n            }\n\n            do {\n                try await check(loader: manifestLoader, manifest: manifest + \"\\n\\n\")\n                try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)).count, 3)\n                try await XCTAssertAsyncEqual(try await delegate.parsed(timeout: .seconds(1)).count, 2)\n            }\n        }\n    }\n\n    func testCacheInvalidateOnBuildToolsFlags() async throws {\n        try await testWithTemporaryDirectory { path in\n            let fileSystem = InMemoryFileSystem()\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let manifestPath = path.appending(components: \"pkg\", \"Package.swift\")\n            try fileSystem.createDirectory(manifestPath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                    import PackageDescription\n                    let package = Package(\n                        name: \"Trivial\",\n                        targets: [\n                            .target(\n                                name: \"foo\",\n                                dependencies: []),\n                        ]\n                    )\n                    #if TEST_BUILD_FLAG\n                    package.targets[0].name = \"bar\"\n                    #endif\n                    \"\"\"\n            )\n\n            try await check(expectCached: false, extraManifestFlags: [], targetName: \"foo\")\n            try await check(expectCached: true, extraManifestFlags: [], targetName: \"foo\")\n            // Cache key should take into account the extra flags.\n            try await check(expectCached: false, extraManifestFlags: [\"-DTEST_BUILD_FLAG\"], targetName: \"bar\")\n            try await check(expectCached: true, extraManifestFlags: [\"-DTEST_BUILD_FLAG\"], targetName: \"bar\")\n            // Cache should hit after back to original flags.\n            try await check(expectCached: true, extraManifestFlags: [], targetName: \"foo\")\n\n            func check(expectCached: Bool, extraManifestFlags: [String], targetName: String) async throws {\n                let delegate = ManifestTestDelegate()\n\n                let loader = ManifestLoader(\n                    toolchain: try UserToolchain.default,\n                    cacheDir: path,\n                    extraManifestFlags: extraManifestFlags,\n                    delegate: delegate\n                )\n\n                let manifest = try await XCTAsyncUnwrap(try await loader.load(\n                    manifestPath: manifestPath,\n                    packageKind: .root(manifestPath.parentDirectory),\n                    toolsVersion: .current,\n                    fileSystem: fileSystem,\n                    observabilityScope: observability.topScope\n                ))\n\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)), [manifestPath])\n                try await XCTAssertAsyncEqual(try await delegate.parsed(timeout: .seconds(1)).count, expectCached ? 0 : 1)\n                XCTAssertEqual(manifest.displayName, \"Trivial\")\n                XCTAssertEqual(manifest.targets[0].name, targetName)\n            }\n        }\n    }\n\n    func testCacheInvalidationOnEnv() async throws {\n        try await testWithTemporaryDirectory { path in\n            let fileSystem = InMemoryFileSystem()\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let manifestPath = path.appending(components: \"pkg\", \"Package.swift\")\n            try fileSystem.createDirectory(manifestPath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                    import PackageDescription\n                    let package = Package(\n                        name: \"Trivial\",\n                        targets: [\n                            .target(\n                                name: \"foo\",\n                                dependencies: []),\n                        ]\n                    )\n                    \"\"\"\n            )\n\n            let delegate = ManifestTestDelegate()\n\n            let manifestLoader = ManifestLoader(\n                toolchain: try UserToolchain.default,\n                cacheDir: path,\n                delegate: delegate\n            )\n\n            try await check(loader: manifestLoader, expectCached: false)\n            try await check(loader: manifestLoader, expectCached: true)\n\n            try await Environment.makeCustom([\"SWIFTPM_MANIFEST_CACHE_TEST\": \"1\"]) {\n                try await check(loader: manifestLoader, expectCached: false)\n                try await check(loader: manifestLoader, expectCached: true)\n            }\n\n            try await Environment.makeCustom([\"SWIFTPM_MANIFEST_CACHE_TEST\": \"2\"]) {\n                try await check(loader: manifestLoader, expectCached: false)\n                try await check(loader: manifestLoader, expectCached: true)\n            }\n\n            try await check(loader: manifestLoader, expectCached: true)\n\n            func check(loader: ManifestLoader, expectCached: Bool) async throws {\n                delegate.clear()\n\n                let manifest = try await XCTAsyncUnwrap(try await loader.load(\n                    manifestPath: manifestPath,\n                    packageKind: .root(manifestPath.parentDirectory),\n                    toolsVersion: .current,\n                    fileSystem: fileSystem,\n                    observabilityScope: observability.topScope\n                ))\n\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)), [manifestPath])\n                try await XCTAssertAsyncEqual(try await delegate.parsed(timeout: .seconds(1)).count, expectCached ? 0 : 1)\n                XCTAssertEqual(manifest.displayName, \"Trivial\")\n                XCTAssertEqual(manifest.targets[0].name, \"foo\")\n            }\n        }\n    }\n\n    func testCacheDoNotInvalidationExpectedEnv() async throws {\n        try await testWithTemporaryDirectory { path in\n            let fileSystem = InMemoryFileSystem()\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let manifestPath = path.appending(components: \"pkg\", \"Package.swift\")\n            try fileSystem.createDirectory(manifestPath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                    import PackageDescription\n                    let package = Package(\n                        name: \"Trivial\",\n                        targets: [\n                            .target(\n                                name: \"foo\",\n                                dependencies: []),\n                        ]\n                    )\n                    \"\"\"\n            )\n\n            let delegate = ManifestTestDelegate()\n\n            let manifestLoader = ManifestLoader(\n                toolchain: try UserToolchain.default,\n                cacheDir: path,\n                delegate: delegate\n            )\n\n            func check(loader: ManifestLoader, expectCached: Bool) async throws {\n                delegate.clear()\n\n                let manifest = try await XCTAsyncUnwrap(try await loader.load(\n                    manifestPath: manifestPath,\n                    packageKind: .root(manifestPath.parentDirectory),\n                    toolsVersion: .current,\n                    fileSystem: fileSystem,\n                    observabilityScope: observability.topScope\n                ))\n\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)), [manifestPath])\n                try await XCTAssertAsyncEqual(try await delegate.parsed(timeout: .seconds(1)).count, expectCached ? 0 : 1)\n                XCTAssertEqual(manifest.displayName, \"Trivial\")\n                XCTAssertEqual(manifest.targets[0].name, \"foo\")\n            }\n\n            try await check(loader: manifestLoader, expectCached: false)\n            try await check(loader: manifestLoader, expectCached: true)\n\n            for key in EnvironmentKey.nonCachable {\n                try await Environment.makeCustom([key: UUID().uuidString]) {\n                    try await check(loader: manifestLoader, expectCached: true)\n                }\n            }\n\n            try await check(loader: manifestLoader, expectCached: true)\n        }\n    }\n\n    func testSQLiteCacheHappyCase() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let path = tmpPath.appending(\"test.db\")\n            let storage = SQLiteBackedCache<ManifestLoader.EvaluationResult>(tableName: \"manifests\", path: path)\n            defer { XCTAssertNoThrow(try storage.close()) }\n\n            let mockManifests = try makeMockManifests(fileSystem: localFileSystem, rootPath: tmpPath)\n            try mockManifests.forEach { key, manifest in\n                _ = try storage.put(key: key.sha256Checksum, value: manifest)\n            }\n\n            try mockManifests.forEach { key, manifest in\n                let result = try storage.get(key: key.sha256Checksum)\n                XCTAssertEqual(result?.manifestJSON, manifest.manifestJSON)\n            }\n\n            guard case .path(let storagePath) = storage.location else {\n                return XCTFail(\"invalid location \\(storage.location)\")\n            }\n\n            XCTAssertTrue(storage.fileSystem.exists(storagePath), \"expected file to be written\")\n        }\n    }\n\n    func testInMemoryCacheHappyCase() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Root\",\n               dependencies: [\n                   .package(url: \"https://scm.com/foo\", from: \"1.0.0\"),\n                   .package(url: \"https://scm.com/bar\", from: \"2.1.0\")\n               ]\n            )\n            \"\"\"\n\n        let manifestLoader = ManifestLoader(\n            toolchain: try UserToolchain.default,\n            cacheDir: .none,\n            delegate: .none\n        )\n\n        let packageURL = \"https://scm.com/\\(UUID().uuidString)/foo\"\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await PackageDescriptionLoadingTests.loadAndValidateManifest(\n                content,\n                toolsVersion: .current,\n                packageKind: .remoteSourceControl(.init(packageURL)),\n                manifestLoader: manifestLoader,\n                observabilityScope: observability.topScope\n            )\n\n            // first time should not come from cache\n            testDiagnostics(observability.diagnostics, problemsOnly: false) { result in\n                result.check(\n                    diagnostic: .regex(\"evaluating manifest for .*\"),\n                    severity: .debug\n                )\n            }\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n            XCTAssertEqual(deps[\"foo\"], .remoteSourceControl(url: \"https://scm.com/foo\", requirement: .upToNextMajor(from: \"1.0.0\")))\n            XCTAssertEqual(deps[\"bar\"], .remoteSourceControl(url: \"https://scm.com/bar\", requirement: .upToNextMajor(from: \"2.1.0\")))\n        }\n\n        // second time should come from in-memory cache\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await PackageDescriptionLoadingTests.loadAndValidateManifest(\n                content,\n                toolsVersion: .current,\n                packageKind: .remoteSourceControl(.init(packageURL)),\n                manifestLoader: manifestLoader,\n                observabilityScope: observability.topScope\n            )\n\n            testDiagnostics(observability.diagnostics, problemsOnly: false) { result in\n                result.check(\n                    diagnostic: .regex(\"loading manifest .* from memory cache\"),\n                    severity: .debug\n                )\n            }\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n            XCTAssertEqual(deps[\"foo\"], .remoteSourceControl(url: \"https://scm.com/foo\", requirement: .upToNextMajor(from: \"1.0.0\")))\n            XCTAssertEqual(deps[\"bar\"], .remoteSourceControl(url: \"https://scm.com/bar\", requirement: .upToNextMajor(from: \"2.1.0\")))\n        }\n\n        // change location and make sure not coming from cache (rdar://73462555)\n        let newPackageURL = \"https://scm.com/\\(UUID().uuidString)/foo\"\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await PackageDescriptionLoadingTests.loadAndValidateManifest(\n                content,\n                toolsVersion: .current,\n                packageKind: .remoteSourceControl(.init(newPackageURL)),\n                manifestLoader: manifestLoader,\n                observabilityScope: observability.topScope\n            )\n\n            testDiagnostics(observability.diagnostics, problemsOnly: false) { result in\n                result.check(\n                    diagnostic: .regex(\"evaluating manifest for .*\"),\n                    severity: .debug\n                )\n            }\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n            XCTAssertEqual(deps[\"foo\"], .remoteSourceControl(url: \"https://scm.com/foo\", requirement: .upToNextMajor(from: \"1.0.0\")))\n            XCTAssertEqual(deps[\"bar\"], .remoteSourceControl(url: \"https://scm.com/bar\", requirement: .upToNextMajor(from: \"2.1.0\")))\n        }\n\n        // second time should come from in-memory cache\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await PackageDescriptionLoadingTests.loadAndValidateManifest(\n                content,\n                toolsVersion: .current,\n                packageKind: .remoteSourceControl(.init(newPackageURL)),\n                manifestLoader: manifestLoader,\n                observabilityScope: observability.topScope\n            )\n\n            testDiagnostics(observability.diagnostics, problemsOnly: false) { result in\n                result.check(\n                    diagnostic: .regex(\"loading manifest .* from memory cache\"),\n                    severity: .debug\n                )\n            }\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n            XCTAssertEqual(deps[\"foo\"], .remoteSourceControl(url: \"https://scm.com/foo\", requirement: .upToNextMajor(from: \"1.0.0\")))\n            XCTAssertEqual(deps[\"bar\"], .remoteSourceControl(url: \"https://scm.com/bar\", requirement: .upToNextMajor(from: \"2.1.0\")))\n        }\n    }\n}\n\nprivate func makeMockManifests(\n    fileSystem: FileSystem,\n    rootPath: AbsolutePath,\n    count: Int = Int.random(in: 50 ..< 100)\n) throws -> [ManifestLoader.CacheKey: ManifestLoader.EvaluationResult] {\n    var manifests = [ManifestLoader.CacheKey: ManifestLoader.EvaluationResult]()\n    for index in 0 ..< count {\n        let packagePath = rootPath.appending(\"\\(index)\")\n        let manifestPath = packagePath.appending(\"Package.swift\")\n\n        try fileSystem.createDirectory(packagePath, recursive: true)\n        try fileSystem.writeFileContents(\n            manifestPath,\n            string: \"\"\"\n            import PackageDescription\n            let package = Package(\n            name: \"Trivial-\\(index)\",\n                targets: [\n                    .target(\n                        name: \"foo-\\(index)\",\n                        dependencies: []),\n\n            )\n            \"\"\"\n        )\n        let key = try ManifestLoader.CacheKey(\n            packageIdentity: PackageIdentity(path: packagePath),\n            packageLocation: packagePath.pathString,\n            manifestPath: manifestPath,\n            toolsVersion: ToolsVersion.current,\n            env: [:],\n            swiftpmVersion: SwiftVersion.current.displayString,\n            extraManifestFlags: [],\n            fileSystem: fileSystem\n        )\n        manifests[key] = ManifestLoader.EvaluationResult(\n            compilerOutput: \"mock-output-\\(index)\",\n            manifestJSON: \"{ 'name': 'mock-manifest-\\(index)' }\"\n        )\n    }\n\n    return manifests\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/ManifestSignatureParserTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageLoading\nimport _InternalTestSupport\nimport XCTest\n\nclass ManifestSignatureParserTests: XCTestCase {\n    func testSignedManifest() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            let signatureBytes = Array(UUID().uuidString.utf8)\n\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                // signature: cms-1.0.0;\\(Data(signatureBytes).base64EncodedString())\n                \"\"\"\n            )\n\n            let components = try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            XCTAssertNotNil(components)\n            XCTAssertEqual(components?.contents, Array(\"\"\"\n            // swift-tools-version: 5.7\n\n            import PackageDescription\n            let package = Package(\n                name: \"library\",\n                products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                targets: [ .target(name: \"library\") ]\n            )\n\n            \"\"\".utf8))\n            XCTAssertEqual(components?.signatureFormat, \"cms-1.0.0\")\n            XCTAssertEqual(components?.signature, signatureBytes)\n        }\n    }\n\n    func testManifestSignatureWithLeadingAndTrailingWhitespace() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            let signatureBytes = Array(UUID().uuidString.utf8)\n\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                   // signature: cms-1.0.0;\\(Data(signatureBytes).base64EncodedString())\n\n\n                \"\"\"\n            )\n\n            let components = try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            XCTAssertNotNil(components)\n            XCTAssertEqual(components?.contents, Array(\"\"\"\n            // swift-tools-version: 5.7\n\n            import PackageDescription\n            let package = Package(\n                name: \"library\",\n                products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                targets: [ .target(name: \"library\") ]\n            )\n\n            \"\"\".utf8))\n            XCTAssertEqual(components?.signatureFormat, \"cms-1.0.0\")\n            XCTAssertEqual(components?.signature, signatureBytes)\n        }\n    }\n\n    func testUnsignedManifest() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                \"\"\"\n            )\n\n            let components = try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            XCTAssertNil(components)\n        }\n    }\n\n    func testManifestWithCommentAsLastLine() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                // xxx\n                \"\"\"\n            )\n\n            let components = try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            XCTAssertNil(components)\n        }\n    }\n\n    func testManifestWithIncompleteSignatureLine1() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                // signature\n                \"\"\"\n            )\n\n            let components = try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            XCTAssertNil(components)\n        }\n    }\n\n    func testManifestWithIncompleteSignatureLine2() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                // signature:\n                \"\"\"\n            )\n\n            let components = try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            XCTAssertNil(components)\n        }\n    }\n\n    func testManifestWithIncompleteSignatureLine3() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                    // signature: cms\n                \"\"\"\n            )\n\n            let components = try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            XCTAssertNil(components)\n        }\n    }\n\n    func testManifestWithIncompleteSignatureLine4() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                    // signature: cms;\n                \"\"\"\n            )\n\n            let components = try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            XCTAssertNil(components)\n        }\n    }\n\n    func testManifestWithMalformedSignature() throws {\n        try testWithTemporaryDirectory { tmpPath in\n            let manifestPath = tmpPath.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version: 5.7\n\n                import PackageDescription\n                let package = Package(\n                    name: \"library\",\n                    products: [ .library(name: \"library\", targets: [\"library\"]) ],\n                    targets: [ .target(name: \"library\") ]\n                )\n\n                    // signature: cms-1.0.0;signature-not-base64-encoded\n                \"\"\"\n            )\n\n            XCTAssertThrowsError(\n                try ManifestSignatureParser.parse(manifestPath: manifestPath, fileSystem: localFileSystem)\n            ) { error in\n                guard case ManifestSignatureParser.Error.malformedManifestSignature = error else {\n                    return XCTFail(\"Expected .malformedManifestSignature error, got \\(error)\")\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/ModuleMapGenerationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nfinal class ModuleMapGeneration: XCTestCase {\n    func testModuleNameHeaderInInclude() throws {\n        let root: AbsolutePath = .root\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            root.appending(components: \"include\", \"Foo.h\").pathString,\n            root.appending(components: \"Foo.c\").pathString\n        )\n        ModuleMapTester(\"Foo\", in: fs) { result in\n            result.check(contents: \"\"\"\n            module Foo {\n                umbrella header \"\\(root.appending(components: \"include\", \"Foo.h\"))\"\n                export *\n            }\n\n            \"\"\")\n        }\n    }\n\n    func testModuleNameDirAndHeaderInInclude() throws {\n        let root: AbsolutePath = .root\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            root.appending(components: \"include\", \"Foo\", \"Foo.h\").pathString,\n            root.appending(components: \"Foo.c\").pathString\n        )\n        ModuleMapTester(\"Foo\", in: fs) { result in\n            result.check(contents: \"\"\"\n            module Foo {\n                umbrella header \"\\(root.appending(components: \"include\", \"Foo\", \"Foo.h\").pathString)\"\n                export *\n            }\n\n            \"\"\")\n        }\n    }\n\n    func testOtherCases() throws {\n        let root: AbsolutePath = .root\n        var fs: InMemoryFileSystem\n\n        fs = InMemoryFileSystem(emptyFiles:\n            root.appending(components: \"include\", \"Bar.h\").pathString,\n            root.appending(components: \"Foo.c\").pathString\n        )\n        ModuleMapTester(\"Foo\", in: fs) { result in\n            result.check(contents: \"\"\"\n            module Foo {\n                umbrella \"\\(root.appending(components: \"include\"))\"\n                export *\n            }\n\n            \"\"\")\n        }\n\n        fs = InMemoryFileSystem(emptyFiles:\n            root.appending(components: \"include\", \"Baz.h\").pathString,\n            root.appending(components: \"include\", \"Bar.h\").pathString,\n            root.appending(components: \"Foo.c\").pathString\n        )\n        ModuleMapTester(\"Foo\", in: fs) { result in\n            result.check(contents: \"\"\"\n            module Foo {\n                umbrella \"\\(root.appending(components: \"include\"))\"\n                export *\n            }\n\n            \"\"\")\n        }\n\n        fs = InMemoryFileSystem(emptyFiles:\n            root.appending(components: \"include\", \"Baz\", \"Foo.h\").pathString,\n            root.appending(components: \"include\", \"Bar\", \"Bar.h\").pathString,\n            root.appending(components: \"Foo.c\").pathString\n        )\n        ModuleMapTester(\"Foo\", in: fs) { result in\n            result.check(contents: \"\"\"\n            module Foo {\n                umbrella \"\\(root.appending(components: \"include\"))\"\n                export *\n            }\n\n            \"\"\")\n        }\n    }\n\n    func testWarnings() throws {\n        let root: AbsolutePath = .root\n\n        var fs = InMemoryFileSystem(emptyFiles:\n            root.appending(components: \"Foo.c\").pathString\n        )\n        ModuleMapTester(\"Foo\", in: fs) { result in\n            result.checkNotCreated()\n            result.checkDiagnostics { result in\n                let diagnostic = result.check(\n                    diagnostic: \"no include directory found for target \\'Foo\\'; libraries cannot be imported without public headers\",\n                    severity: .warning\n                )\n                XCTAssertEqual(diagnostic?.metadata?.moduleName, \"Foo\")\n            }\n        }\n\n        fs = InMemoryFileSystem(emptyFiles:\n            root.appending(components: \"include\", \"F-o-o.h\").pathString,\n            root.appending(components: \"Foo.c\").pathString\n        )\n        ModuleMapTester(\"F-o-o\", in: fs) { result in\n            result.check(contents: \"\"\"\n                module F_o_o {\n                    umbrella \"\\(root.appending(components: \"include\"))\"\n                    export *\n                }\n\n                \"\"\")\n            result.checkDiagnostics { result in\n                let diagnostic = result.check(\n                    diagnostic: \"\\(root.appending(components: \"include\", \"F-o-o.h\")) should be renamed to \\(root.appending(components: \"include\", \"F_o_o.h\")) to be used as an umbrella header\",\n                    severity: .warning\n                )\n                XCTAssertEqual(diagnostic?.metadata?.moduleName, \"F-o-o\")\n            }\n        }\n    }\n\n    func testUnsupportedLayouts() throws {\n        let include: AbsolutePath = \"/include\"\n\n        var fs = InMemoryFileSystem(emptyFiles:\n            include.appending(components: \"Foo\", \"Foo.h\").pathString,\n            include.appending(components: \"Bar\", \"Foo.h\").pathString\n        )\n        ModuleMapTester(\"Foo\", in: fs) { result in\n            result.checkNotCreated()\n            result.checkDiagnostics { result in\n                let diagnostic = result.check(\n                    diagnostic: \"target 'Foo' has invalid header layout: umbrella header found at '\\(include.appending(components: \"Foo\", \"Foo.h\"))', but more than one directory exists next to its parent directory: \\(include.appending(components: \"Bar\")); consider reducing them to one\",\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic?.metadata?.moduleName, \"Foo\")\n            }\n        }\n\n        fs = InMemoryFileSystem(emptyFiles:\n            include.appending(components: \"Foo.h\").pathString,\n            include.appending(components: \"Bar\", \"Foo.h\").pathString\n        )\n        ModuleMapTester(\"Foo\", in: fs) { result in\n            result.checkNotCreated()\n            result.checkDiagnostics { result in\n                let diagnostic = result.check(\n                    diagnostic: \"target 'Foo' has invalid header layout: umbrella header found at '\\(include.appending(components: \"Foo.h\"))', but directories exist next to it: \\(include.appending(components: \"Bar\")); consider removing them\",\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic?.metadata?.moduleName, \"Foo\")\n            }\n        }\n    }\n}\n\n/// Helper function to test module map generation.  Given a target name and optionally the name of a public-headers directory, this function determines the module map type of the public-headers directory by examining the contents of a file system and invokes a given block to check the module result (including any diagnostics).\nfunc ModuleMapTester(_ targetName: String, includeDir: String = \"include\", in fileSystem: FileSystem, _ body: (ModuleMapResult) -> Void) {\n    let observability = ObservabilitySystem.makeForTesting()\n    // Create a module map generator, and determine the type of module map to use for the header directory.  This may emit diagnostics.\n    let moduleMapGenerator = ModuleMapGenerator(targetName: targetName, moduleName: targetName.spm_mangledToC99ExtendedIdentifier(), publicHeadersDir: AbsolutePath.root.appending(component: includeDir), fileSystem: fileSystem)\n    let moduleMapType = moduleMapGenerator.determineModuleMapType(observabilityScope: observability.topScope)\n    \n    // Generate a module map and capture any emitted diagnostics.\n    let generatedModuleMapPath = AbsolutePath.root.appending(components: \"module.modulemap\")\n    observability.topScope.trap {\n        if let generatedModuleMapType = moduleMapType.generatedModuleMapType {\n            try moduleMapGenerator.generateModuleMap(type: generatedModuleMapType, at: generatedModuleMapPath)\n        }\n    }\n    \n    // Invoke the closure to check the results.\n    let result = ModuleMapResult(diagnostics: observability.diagnostics, path: generatedModuleMapPath, fs: fileSystem)\n    body(result)\n    \n    // Check for any unexpected diagnostics (the ones the closure didn't check for).\n    result.validateDiagnostics()\n}\n\nfinal class ModuleMapResult {\n    private var diagnostics: [Basics.Diagnostic]\n    private var diagsChecked: Bool\n    private let path: AbsolutePath\n    private let fs: FileSystem\n\n    init(diagnostics: [Basics.Diagnostic], path: AbsolutePath, fs: FileSystem) {\n        self.diagnostics = diagnostics\n        self.diagsChecked = false\n        self.path = path\n        self.fs = fs\n    }\n\n    func validateDiagnostics(file: StaticString = #file, line: UInt = #line) {\n        if diagsChecked || diagnostics.isEmpty { return }\n        XCTFail(\"Unchecked diagnostics: \\(diagnostics)\", file: (file), line: line)\n    }\n\n    func checkDiagnostics(_ handler: (DiagnosticsTestResult) throws -> Void) {\n        testDiagnostics(diagnostics, handler: handler)\n        diagsChecked = true\n    }\n\n    func checkNotCreated(file: StaticString = #file, line: UInt = #line) {\n        XCTAssertEqual(isCreated, false, \"unexpected modulemap created: \\(contents)\", file: (file), line: line)\n    }\n\n    private var contents: String {\n        return try! fs.readFileContents(path).replacingOccurrences(of: \"\\\\\\\\\", with: \"\\\\\")\n    }\n\n    private var isCreated: Bool {\n        return fs.isFile(path)\n    }\n\n    func check(contents: String, file: StaticString = #file, line: UInt = #line) {\n        guard isCreated else {\n            return XCTFail(\"Can't compare values, modulemap not generated.\", file: (file), line: line)\n        }\n        XCTAssertEqual(contents, self.contents, file: (file), line: line)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PDAppleProductLoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\nimport Basics\nimport TSCUtility\nimport _InternalTestSupport\nimport PackageModel\nimport PackageLoading\n\nclass PackageDescriptionAppleProductLoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v6_0 // TODO: confirm this value\n    }\n\n    func testApplicationProducts() throws {\n      #if ENABLE_APPLE_PRODUCT_TYPES\n        let content = \"\"\"\n            import PackageDescription\n            import AppleProductTypes\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .iOSApplication(\n                        name: \"Foo\",\n                        targets: [\"Foo\"],\n                        bundleIdentifier: \"com.my.app\",\n                        teamIdentifier: \"ZXYTEAM123\",\n                        displayVersion: \"1.4.2 Extra Cool\",\n                        bundleVersion: \"1.4.2\",\n                        appIcon: .asset(\"icon\"),\n                        accentColor: .asset(\"accentColor\"),\n                        supportedDeviceFamilies: [.pad, .mac],\n                        supportedInterfaceOrientations: [.portrait, .portraitUpsideDown(), .landscapeRight(.when(deviceFamilies: [.mac]))],\n                        capabilities: [\n                            .camera(purposeString: \"All the better to see you with…\"),\n                            .microphone(purposeString: \"All the better to hear you with…\", .when(deviceFamilies: [.pad, .phone])),\n                            .localNetwork(purposeString: \"Communication is key…\", bonjourServiceTypes: [\"_ipp._tcp\"], .when(deviceFamilies: [.mac]))\n                        ],\n                        appCategory: .developerTools\n                    ),\n                ],\n                targets: [\n                    .executableTarget(\n                        name: \"Foo\"\n                    ),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, _) = try loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        // Check the targets.  We expect to have a single executable target.\n        XCTAssertEqual(manifest.targets.count, 1)\n        let mainTarget = manifest.targets[0]\n        XCTAssertEqual(mainTarget.type, .executable)\n        XCTAssertEqual(mainTarget.name, \"Foo\")\n\n        // Check the products.  We expect to have a single executable product with iOS-specific settings.\n        XCTAssertEqual(manifest.products.count, 1)\n        let appProduct = manifest.products[0]\n\n        // Check the core properties and basic settings of the application product.\n        XCTAssertEqual(appProduct.type, .executable)\n        XCTAssertEqual(appProduct.settings.count, 5)\n        XCTAssertTrue(appProduct.settings.contains(.bundleIdentifier(\"com.my.app\")))\n        XCTAssertTrue(appProduct.settings.contains(.bundleVersion(\"1.4.2\")))\n\n        // Find the \"iOS Application Info\" setting.\n        var appInfoSetting: ProductSetting.IOSAppInfo? = nil\n        for case let ProductSetting.iOSAppInfo(value) in appProduct.settings  {\n            appInfoSetting = .init(value)\n        }\n        guard let appInfoSetting = appInfoSetting else {\n            return XCTFail(\"product has no .iOSAppInfo() setting\")\n        }\n\n        // Check the specific properties of the iOS Application Info.\n        XCTAssertEqual(appInfoSetting.appIcon, .asset(name: \"icon\"))\n        XCTAssertEqual(appInfoSetting.accentColor, .asset(name: \"accentColor\"))\n        XCTAssertEqual(appInfoSetting.supportedDeviceFamilies, [.pad, .mac])\n        XCTAssertEqual(appInfoSetting.supportedInterfaceOrientations, [\n            .portrait(condition: nil),\n            .portraitUpsideDown(condition: nil),\n            .landscapeRight(condition: .init(deviceFamilies: [.mac]))\n        ])\n        XCTAssertEqual(appInfoSetting.capabilities, [\n            .init(purpose: \"camera\", purposeString: \"All the better to see you with…\", condition: nil),\n            .init(purpose: \"microphone\", purposeString: \"All the better to hear you with…\", condition: .init(deviceFamilies: [.pad, .phone])),\n            .init(purpose: \"localNetwork\", purposeString: \"Communication is key…\", bonjourServiceTypes: [\"_ipp._tcp\"], condition: .init(deviceFamilies: [.mac]))\n        ])\n        XCTAssertEqual(appInfoSetting.appCategory?.rawValue, \"public.app-category.developer-tools\")\n      #else\n        throw XCTSkip(\"ENABLE_APPLE_PRODUCT_TYPES is not set\")\n      #endif\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PDLoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nclass PackageDescriptionLoadingTests: XCTestCase, ManifestLoaderDelegate {\n    lazy var manifestLoader = ManifestLoader(toolchain: try! UserToolchain.default, delegate: self)\n    var parsedManifest = ThreadSafeBox<AbsolutePath>(.root)\n\n    func willLoad(packageIdentity: PackageModel.PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        // noop\n    }\n\n    func didLoad(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath, duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    func willParse(packageIdentity: PackageIdentity, packageLocation: String) {\n        // noop\n    }\n\n    func didParse(packageIdentity: PackageIdentity, packageLocation: String, duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    func willCompile(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        // noop\n    }\n\n    func didCompile(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath, duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    func willEvaluate(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        // noop\n    }\n\n    func didEvaluate(packageIdentity: PackageModel.PackageIdentity, packageLocation: String, manifestPath: AbsolutePath, duration: DispatchTimeInterval) {\n        parsedManifest.put(manifestPath)\n    }\n\n    var toolsVersion: ToolsVersion {\n        fatalError(\"implement in subclass\")\n    }\n\n    func loadAndValidateManifest(\n        _ content: String,\n        toolsVersion: ToolsVersion? = nil,\n        packageKind: PackageReference.Kind? = nil,\n        customManifestLoader: ManifestLoader? = nil,\n        observabilityScope: ObservabilityScope,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) async throws -> (manifest: Manifest, diagnostics: [Basics.Diagnostic]) {\n        try await Self.loadAndValidateManifest(\n            content,\n            toolsVersion: toolsVersion ?? self.toolsVersion,\n            packageKind: packageKind ?? .fileSystem(.root),\n            manifestLoader: customManifestLoader ?? self.manifestLoader,\n            observabilityScope: observabilityScope,\n            file: file,\n            line: line\n        )\n    }\n\n    static func loadAndValidateManifest(\n        _ content: String,\n        toolsVersion: ToolsVersion,\n        packageKind: PackageReference.Kind,\n        manifestLoader: ManifestLoader,\n        observabilityScope: ObservabilityScope,\n        file: StaticString = #file,\n        line: UInt = #line\n    ) async throws -> (manifest: Manifest, diagnostics: [Basics.Diagnostic]) {\n        let packagePath: AbsolutePath\n        switch packageKind {\n        case .root(let path):\n            packagePath = path\n        case .fileSystem(let path):\n            packagePath = path\n        case .localSourceControl(let path):\n            packagePath = path\n        case .remoteSourceControl, .registry:\n            packagePath = .root\n        }\n\n        let toolsVersion = toolsVersion\n        let fileSystem = InMemoryFileSystem()\n        let manifestPath = packagePath.appending(component: Manifest.filename)\n        try fileSystem.writeFileContents(manifestPath, string: content)\n        let manifest = try await manifestLoader.load(\n            manifestPath: manifestPath,\n            packageKind: packageKind,\n            toolsVersion: toolsVersion,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n\n        if manifest.toolsVersion != toolsVersion {\n            throw StringError(\"Invalid manifest version\")\n        }\n\n        let validator = ManifestValidator(manifest: manifest, sourceControlValidator: NOOPManifestSourceControlValidator(), fileSystem: fileSystem)\n        let diagnostics = validator.validate()\n        return (manifest: manifest, diagnostics: diagnostics)\n    }\n}\n\nfinal class ManifestTestDelegate: ManifestLoaderDelegate {\n    private let loaded = ThreadSafeArrayStore<AbsolutePath>()\n    private let parsed = ThreadSafeArrayStore<AbsolutePath>()\n\n    func willLoad(packageIdentity: PackageModel.PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        // noop\n    }\n\n    func didLoad(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath, duration: DispatchTimeInterval) {\n        self.loaded.append(manifestPath)\n    }\n\n    func willParse(packageIdentity: PackageIdentity, packageLocation: String) {\n        // noop\n    }\n\n    func didParse(packageIdentity: PackageIdentity, packageLocation: String, duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    func willCompile(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        // noop\n    }\n\n    func didCompile(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath, duration: DispatchTimeInterval) {\n        // noop\n    }\n\n    func willEvaluate(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath) {\n        // noop\n    }\n\n    func didEvaluate(packageIdentity: PackageIdentity, packageLocation: String, manifestPath: AbsolutePath, duration: DispatchTimeInterval) {\n        self.parsed.append(manifestPath)\n    }\n\n\n    func clear() {\n        self.loaded.clear()\n        self.parsed.clear()\n    }\n\n    func loaded(timeout: Duration) async throws -> [AbsolutePath] {\n        try await Task.sleep(for: timeout)\n        return self.loaded.get()\n    }\n\n    func parsed(timeout: Duration) async throws -> [AbsolutePath] {\n        try await Task.sleep(for: timeout)\n        return self.parsed.get()\n    }\n}\n\nfileprivate struct NOOPManifestSourceControlValidator: ManifestSourceControlValidator {\n    func isValidDirectory(_ path: AbsolutePath) throws -> Bool {\n        true\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_4_0_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2017-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageDescription4_0LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v4\n    }\n\n    func testTrivial() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\"\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.displayName, \"Trivial\")\n        XCTAssertEqual(manifest.toolsVersion, .v4)\n        XCTAssertEqual(manifest.targets, [])\n        XCTAssertEqual(manifest.dependencies, [])\n    }\n\n    func testTargetDependencies() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                targets: [\n                    .target(name: \"foo\", dependencies: [\n                        \"dep1\",\n                        .target(name: \"dep2\"),\n                        .product(name: \"dep3\", package: \"Pkg\"),\n                        .product(name: \"dep4\"),\n                    ]),\n                    .testTarget(name: \"bar\", dependencies: [\n                        \"foo\",\n                    ])\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.displayName, \"Trivial\")\n        let foo = manifest.targetMap[\"foo\"]!\n        XCTAssertEqual(foo.name, \"foo\")\n        XCTAssertFalse(foo.isTest)\n\n        let expectedDependencies: [TargetDescription.Dependency]\n        expectedDependencies = [\n            \"dep1\",\n            .target(name: \"dep2\"),\n            .product(name: \"dep3\", package: \"Pkg\"),\n            .product(name: \"dep4\"),\n        ]\n        XCTAssertEqual(foo.dependencies, expectedDependencies)\n\n        let bar = manifest.targetMap[\"bar\"]!\n        XCTAssertEqual(bar.name, \"bar\")\n        XCTAssertTrue(bar.isTest)\n        XCTAssertEqual(bar.dependencies, [\"foo\"])\n    }\n\n    func testCompatibleSwiftVersions() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: [3, 4]\n                )\n                \"\"\"\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n            XCTAssertEqual(manifest.swiftLanguageVersions?.map({$0.rawValue}), [\"3\", \"4\"])\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: []\n                )\n                \"\"\"\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n            XCTAssertEqual(manifest.swiftLanguageVersions, [])\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\")\n                \"\"\"\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n            XCTAssertEqual(manifest.swiftLanguageVersions, nil)\n        }\n    }\n\n    func testPackageDependencies() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               dependencies: [\n                   .package(url: \"\\(AbsolutePath(\"/foo1\").escapedPathString)\", from: \"1.0.0\"),\n                   .package(url: \"\\(AbsolutePath(\"/foo2\").escapedPathString)\", .upToNextMajor(from: \"1.0.0\")),\n                   .package(url: \"\\(AbsolutePath(\"/foo3\").escapedPathString)\", .upToNextMinor(from: \"1.0.0\")),\n                   .package(url: \"\\(AbsolutePath(\"/foo4\").escapedPathString)\", .exact(\"1.0.0\")),\n                   .package(url: \"\\(AbsolutePath(\"/foo5\").escapedPathString)\", .branch(\"main\")),\n                   .package(url: \"\\(AbsolutePath(\"/foo6\").escapedPathString)\", .revision(\"58e9de4e7b79e67c72a46e164158e3542e570ab6\")),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n        XCTAssertEqual(deps[\"foo1\"], .localSourceControl(path: \"/foo1\", requirement: .upToNextMajor(from: \"1.0.0\")))\n        XCTAssertEqual(deps[\"foo2\"], .localSourceControl(path: \"/foo2\", requirement: .upToNextMajor(from: \"1.0.0\")))\n        XCTAssertEqual(deps[\"foo3\"], .localSourceControl(path: \"/foo3\", requirement: .upToNextMinor(from: \"1.0.0\")))\n        XCTAssertEqual(deps[\"foo4\"], .localSourceControl(path: \"/foo4\", requirement: .exact(\"1.0.0\")))\n        XCTAssertEqual(deps[\"foo5\"], .localSourceControl(path: \"/foo5\", requirement: .branch(\"main\")))\n        XCTAssertEqual(deps[\"foo6\"], .localSourceControl(path: \"/foo6\", requirement: .revision(\"58e9de4e7b79e67c72a46e164158e3542e570ab6\")))\n    }\n\n    func testProducts() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .executable(name: \"tool\", targets: [\"tool\"]),\n                    .library(name: \"Foo\", targets: [\"Foo\"]),\n                    .library(name: \"FooDy\", type: .dynamic, targets: [\"Foo\"]),\n                ],\n                targets: [\n                    .target(name: \"Foo\"),\n                    .target(name: \"tool\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let products = Dictionary(uniqueKeysWithValues: manifest.products.map{ ($0.name, $0) })\n        // Check tool.\n        let tool = products[\"tool\"]!\n        XCTAssertEqual(tool.name, \"tool\")\n        XCTAssertEqual(tool.targets, [\"tool\"])\n        XCTAssertEqual(tool.type, .executable)\n        // Check Foo.\n        let foo = products[\"Foo\"]!\n        XCTAssertEqual(foo.name, \"Foo\")\n        XCTAssertEqual(foo.type, .library(.automatic))\n        XCTAssertEqual(foo.targets, [\"Foo\"])\n        // Check FooDy.\n        let fooDy = products[\"FooDy\"]!\n        XCTAssertEqual(fooDy.name, \"FooDy\")\n        XCTAssertEqual(fooDy.type, .library(.dynamic))\n        XCTAssertEqual(fooDy.targets, [\"Foo\"])\n    }\n\n    func testSystemPackage() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Copenssl\",\n               pkgConfig: \"openssl\",\n               providers: [\n                   .brew([\"openssl\"]),\n                   .apt([\"openssl\", \"libssl-dev\"]),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.displayName, \"Copenssl\")\n        XCTAssertEqual(manifest.pkgConfig, \"openssl\")\n        XCTAssertEqual(manifest.providers, [\n            .brew([\"openssl\"]),\n            .apt([\"openssl\", \"libssl-dev\"]),\n        ])\n    }\n\n    func testCTarget() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"libyaml\",\n               targets: [\n                   .target(\n                       name: \"Foo\",\n                       publicHeadersPath: \"inc\"),\n                   .target(\n                   name: \"Bar\"),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let foo = manifest.targetMap[\"Foo\"]!\n        XCTAssertEqual(foo.publicHeadersPath, \"inc\")\n\n        let bar = manifest.targetMap[\"Bar\"]!\n        XCTAssertEqual(bar.publicHeadersPath, nil)\n    }\n\n    func testTargetProperties() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"libyaml\",\n               targets: [\n                   .target(\n                       name: \"Foo\",\n                       path: \"foo/z\",\n                       exclude: [\"bar\"],\n                       sources: [\"bar.swift\"],\n                       publicHeadersPath: \"inc\"),\n                   .target(\n                   name: \"Bar\"),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let foo = manifest.targetMap[\"Foo\"]!\n        XCTAssertEqual(foo.publicHeadersPath, \"inc\")\n        XCTAssertEqual(foo.path, \"foo/z\")\n        XCTAssertEqual(foo.exclude, [\"bar\"])\n        XCTAssertEqual(foo.sources ?? [], [\"bar.swift\"])\n\n        let bar = manifest.targetMap[\"Bar\"]!\n        XCTAssertEqual(bar.publicHeadersPath, nil)\n        XCTAssertEqual(bar.path, nil)\n        XCTAssertEqual(bar.exclude, [])\n        XCTAssert(bar.sources == nil)\n    }\n\n    func testUnavailableAPIs() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               dependencies: [\n                   .package(url: \"/foo1\", version: \"1.0.0\"),\n                   .package(url: \"/foo2\", branch: \"main\"),\n                   .package(url: \"/foo3\", revision: \"rev\"),\n                   .package(url: \"/foo4\", range: \"1.0.0\"..<\"1.5.0\"),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                XCTAssert(error.contains(\"error: 'package(url:version:)' is unavailable: use package(url:exact:) instead\"), \"\\(error)\")\n                XCTAssert(error.contains(\"error: 'package(url:range:)' is unavailable: use package(url:_:) instead\"), \"\\(error)\")\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testLanguageStandards() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"testPackage\",\n                targets: [\n                    .target(name: \"Foo\"),\n                ],\n                cLanguageStandard: .iso9899_199409,\n                cxxLanguageStandard: .gnucxx14\n            )\n        \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.displayName, \"testPackage\")\n        XCTAssertEqual(manifest.cLanguageStandard, \"iso9899:199409\")\n        XCTAssertEqual(manifest.cxxLanguageStandard, \"gnu++14\")\n    }\n\n    func testManifestWithWarnings() async throws {\n        let fs = InMemoryFileSystem()\n        let manifestPath = AbsolutePath.root.appending(component: Manifest.filename)\n\n        let content = \"\"\"\n            import PackageDescription\n            func foo() {\n                let a = 5\n            }\n            let package = Package(\n                name: \"Trivial\"\n            )\n            \"\"\"\n\n        try fs.writeFileContents(manifestPath, string: content)\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let manifest = try await manifestLoader.load(\n            manifestPath: manifestPath,\n            packageKind: .root(.root),\n            toolsVersion: .v4,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertEqual(manifest.displayName, \"Trivial\")\n        XCTAssertEqual(manifest.toolsVersion, .v4)\n        XCTAssertEqual(manifest.targets, [])\n        XCTAssertEqual(manifest.dependencies, [])\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"initialization of immutable value 'a' was never used\"), severity: .warning)\n        }\n    }\n\n    func testDuplicateTargets() async throws {\n        let content = \"\"\"\n            import PackageDescription\n\n            let package = Package(\n                name: \"Foo\",\n                targets: [\n                    .target(name: \"A\"),\n                    .target(name: \"B\"),\n                    .target(name: \"A\"),\n                    .target(name: \"B\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        testDiagnostics(validationDiagnostics) { result in\n            result.checkUnordered(diagnostic: \"duplicate target named 'A'\", severity: .error)\n            result.checkUnordered(diagnostic: \"duplicate target named 'B'\", severity: .error)\n        }\n    }\n\n    func testEmptyProductTargets() async throws {\n        let content = \"\"\"\n            import PackageDescription\n\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .library(name: \"Product\", targets: []),\n                ],\n                targets: [\n                    .target(name: \"Target\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        testDiagnostics(validationDiagnostics) { result in\n            result.check(diagnostic: \"product 'Product' doesn't reference any targets\", severity: .error)\n        }\n    }\n\n    func testProductTargetNotFound() async throws {\n        let content = \"\"\"\n            import PackageDescription\n\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .library(name: \"Product\", targets: [\"A\", \"B\"]),\n                ],\n                targets: [\n                    .target(name: \"A\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        testDiagnostics(validationDiagnostics) { result in\n            result.check(diagnostic: \"target 'B' referenced in product 'Product' could not be found; valid targets are: 'A'\", severity: .error)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_4_2_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Dispatch\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nimport enum TSCBasic.PathValidationError\n\nimport struct TSCUtility.Version\n\n@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)\nfinal class PackageDescription4_2LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v4_2\n    }\n\n    func testBasics() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                products: [\n                    .executable(name: \"tool\", targets: [\"tool\"]),\n                    .library(name: \"Foo\", targets: [\"foo\"]),\n                ],\n                dependencies: [\n                    .package(url: \"\\(AbsolutePath(\"/foo1\").escapedPathString)\", from: \"1.0.0\"),\n                ],\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: [\"dep1\", .product(name: \"product\"), .target(name: \"target\")]),\n                    .target(\n                        name: \"tool\"),\n                    .testTarget(\n                        name: \"bar\",\n                        dependencies: [\"foo\"]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.displayName, \"Trivial\")\n\n        // Check targets.\n        let foo = manifest.targetMap[\"foo\"]!\n        XCTAssertEqual(foo.name, \"foo\")\n        XCTAssertFalse(foo.isTest)\n        XCTAssertEqual(foo.dependencies, [\"dep1\", .product(name: \"product\"), .target(name: \"target\")])\n\n        let bar = manifest.targetMap[\"bar\"]!\n        XCTAssertEqual(bar.name, \"bar\")\n        XCTAssertTrue(bar.isTest)\n        XCTAssertEqual(bar.dependencies, [\"foo\"])\n\n        // Check dependencies.\n        let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n        XCTAssertEqual(deps[\"foo1\"], .localSourceControl(path: \"/foo1\", requirement: .upToNextMajor(from: \"1.0.0\")))\n\n        // Check products.\n        let products = Dictionary(uniqueKeysWithValues: manifest.products.map{ ($0.name, $0) })\n\n        let tool = products[\"tool\"]!\n        XCTAssertEqual(tool.name, \"tool\")\n        XCTAssertEqual(tool.targets, [\"tool\"])\n        XCTAssertEqual(tool.type, .executable)\n\n        let fooProduct = products[\"Foo\"]!\n        XCTAssertEqual(fooProduct.name, \"Foo\")\n        XCTAssertEqual(fooProduct.type, .library(.automatic))\n        XCTAssertEqual(fooProduct.targets, [\"foo\"])\n    }\n\n    func testSwiftLanguageVersions() async throws {\n        // Ensure integer values are not accepted.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: [3, 4]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                    XCTAssertMatch(\n                        message,\n                            .and(\n                                .contains(\"'init(name:pkgConfig:providers:products:dependencies:targets:swiftLanguageVersions:cLanguageStandard:cxxLanguageStandard:)' is unavailable\"),\n                                    .contains(\"was obsoleted in PackageDescription 4.2\")\n                            )\n                    )\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        // Check when Swift language versions is empty.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: []\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            XCTAssertEqual(manifest.swiftLanguageVersions, [])\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: [.v3, .v4, .v4_2, .version(\"5\")]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            XCTAssertEqual(\n                manifest.swiftLanguageVersions,\n                [.v3, .v4, .v4_2, SwiftLanguageVersion(string: \"5\")!]\n            )\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: [.v5]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                    XCTAssertMatch(message, .contains(\"is unavailable\"))\n                    XCTAssertMatch(message, .contains(\"was introduced in PackageDescription 5\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n    }\n\n    func testPlatforms() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: nil\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                    XCTAssertMatch(message, .contains(\"is unavailable\"))\n                    XCTAssertMatch(message, .contains(\"was introduced in PackageDescription 5\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [.macOS(.v10_10)]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                    XCTAssertMatch(message, .contains(\"is unavailable\"))\n                    XCTAssertMatch(message, .contains(\"was introduced in PackageDescription 5\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n    }\n\n    func testBuildSettings() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .target(\n                       name: \"Foo\",\n                       swiftSettings: [\n                           .define(\"SWIFT\", .when(configuration: .release)),\n                       ],\n                       linkerSettings: [\n                           .linkedLibrary(\"libz\"),\n                       ]\n                   ),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                XCTAssertMatch(message, .contains(\"is unavailable\"))\n                XCTAssertMatch(message, .contains(\"was introduced in PackageDescription 5\"))\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testPackageDependencies() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               dependencies: [\n                   .package(url: \"\\(AbsolutePath(\"/foo1\").escapedPathString)\", from: \"1.0.0\"),\n                   .package(url: \"\\(AbsolutePath(\"/foo2\").escapedPathString)\", .revision(\"58e9de4e7b79e67c72a46e164158e3542e570ab6\")),\n                   .package(path: \"../foo3\"),\n                   .package(path: \"\\(AbsolutePath(\"/path/to/foo4\").escapedPathString)\"),\n                   .package(url: \"\\(AbsolutePath(\"/foo5\").escapedPathString)\", .exact(\"1.2.3\")),\n                   .package(url: \"\\(AbsolutePath(\"/foo6\").escapedPathString)\", \"1.2.3\"..<\"2.0.0\"),\n                   .package(url: \"\\(AbsolutePath(\"/foo7\").escapedPathString)\", .branch(\"main\")),\n                   .package(url: \"\\(AbsolutePath(\"/foo8\").escapedPathString)\", .upToNextMinor(from: \"1.3.4\")),\n                   .package(url: \"\\(AbsolutePath(\"/foo9\").escapedPathString)\", .upToNextMajor(from: \"1.3.4\")),\n                   .package(path: \"~/path/to/foo10\"),\n                   .package(path: \"~foo11\"),\n                   .package(path: \"~/path/to/~/foo12\"),\n                   .package(path: \"~\"),\n                   .package(path: \"file:///path/to/foo13\"),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n        XCTAssertEqual(deps[\"foo1\"], .localSourceControl(path: \"/foo1\", requirement: .upToNextMajor(from: \"1.0.0\")))\n        XCTAssertEqual(deps[\"foo2\"], .localSourceControl(path: \"/foo2\", requirement: .revision(\"58e9de4e7b79e67c72a46e164158e3542e570ab6\")))\n\n        if case .fileSystem(let dep) = deps[\"foo3\"] {\n            XCTAssertEqual(dep.path, \"/foo3\")\n        } else {\n            XCTFail(\"expected to be local dependency\")\n        }\n\n        if case .fileSystem(let dep) = deps[\"foo4\"] {\n            XCTAssertEqual(dep.path, \"/path/to/foo4\")\n        } else {\n            XCTFail(\"expected to be local dependency\")\n        }\n\n        XCTAssertEqual(deps[\"foo5\"], .localSourceControl(path: \"/foo5\", requirement: .exact(\"1.2.3\")))\n        XCTAssertEqual(deps[\"foo6\"], .localSourceControl(path: \"/foo6\", requirement: .range(\"1.2.3\"..<\"2.0.0\")))\n        XCTAssertEqual(deps[\"foo7\"], .localSourceControl(path: \"/foo7\", requirement: .branch(\"main\")))\n        XCTAssertEqual(deps[\"foo8\"], .localSourceControl(path: \"/foo8\", requirement: .upToNextMinor(from: \"1.3.4\")))\n        XCTAssertEqual(deps[\"foo9\"], .localSourceControl(path: \"/foo9\", requirement: .upToNextMajor(from: \"1.3.4\")))\n\n        let homeDir = \"/home/user\"\n        if case .fileSystem(let dep) = deps[\"foo10\"] {\n            XCTAssertEqual(dep.path, try AbsolutePath(validating: \"\\(homeDir)/path/to/foo10\"))\n        } else {\n            XCTFail(\"expected to be local dependency\")\n        }\n\n        if case .fileSystem(let dep) = deps[\"~foo11\"] {\n            XCTAssertEqual(dep.path, \"/~foo11\")\n        } else {\n            XCTFail(\"expected to be local dependency\")\n        }\n\n        if case .fileSystem(let dep) = deps[\"foo12\"] {\n            XCTAssertEqual(dep.path, try AbsolutePath(validating: \"\\(homeDir)/path/to/~/foo12\"))\n        } else {\n            XCTFail(\"expected to be local dependency\")\n        }\n\n        if case .fileSystem(let dep) = deps[\"~\"] {\n            XCTAssertEqual(dep.path, \"/~\")\n        } else {\n            XCTFail(\"expected to be local dependency\")\n        }\n\n        if case .fileSystem(let dep) = deps[\"foo13\"] {\n            XCTAssertEqual(dep.path, \"/path/to/foo13\")\n        } else {\n            XCTFail(\"expected to be local dependency\")\n        }\n    }\n\n    func testSystemLibraryTargets() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: [\"bar\"]),\n                    .systemLibrary(\n                        name: \"bar\",\n                        pkgConfig: \"libbar\",\n                        providers: [\n                            .brew([\"libgit\"]),\n                            .apt([\"a\", \"b\"]),\n                        ]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let foo = manifest.targetMap[\"foo\"]!\n        XCTAssertEqual(foo.name, \"foo\")\n        XCTAssertFalse(foo.isTest)\n        XCTAssertEqual(foo.type, .regular)\n        XCTAssertEqual(foo.dependencies, [\"bar\"])\n\n        let bar = manifest.targetMap[\"bar\"]!\n        XCTAssertEqual(bar.name, \"bar\")\n        XCTAssertEqual(bar.type, .system)\n        XCTAssertEqual(bar.pkgConfig, \"libbar\")\n        XCTAssertEqual(bar.providers, [.brew([\"libgit\"]), .apt([\"a\", \"b\"])])\n    }\n\n    /// Check that we load the manifest appropriate for the current version, if\n    /// version specific customization is used.\n    func testVersionSpecificLoading() async throws {\n        let bogusManifest = \"THIS WILL NOT PARSE\"\n        let trivialManifest =\n        \"\"\"\n        // swift-tools-version:4.2\n        import PackageDescription\n        let package = Package(name: \\\"Trivial\\\")\n        \"\"\"\n        // Check at each possible spelling.\n        let currentVersion = SwiftVersion.current\n        let possibleSuffixes = [\n            \"\\(currentVersion.major).\\(currentVersion.minor).\\(currentVersion.patch)\",\n            \"\\(currentVersion.major).\\(currentVersion.minor)\",\n            \"\\(currentVersion.major)\"\n        ]\n        for (i, key) in possibleSuffixes.enumerated() {\n            let root = AbsolutePath.root\n            // Create a temporary FS with the version we want to test, and everything else as bogus.\n            let fs = InMemoryFileSystem()\n            // Write the good manifests.\n            try fs.writeFileContents(\n                root.appending(component: Manifest.basename + \"@swift-\\(key).swift\"),\n                string: trivialManifest)\n            // Write the bad manifests.\n            let badManifests = [Manifest.filename] + possibleSuffixes[i+1 ..< possibleSuffixes.count].map{\n                Manifest.basename + \"@swift-\\($0).swift\"\n            }\n            try badManifests.forEach {\n                try fs.writeFileContents(\n                    root.appending(component: $0),\n                    string: bogusManifest\n                )\n            }\n            // Check we can load the repository.\n            let manifest = try await manifestLoader.load(\n                packagePath: root,\n                packageKind: .root(.root),\n                currentToolsVersion: .v4_2,\n                fileSystem: fs,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            XCTAssertEqual(manifest.displayName, \"Trivial\")\n        }\n    }\n\n    // Check that ancient `Package@swift-3.swift` manifests are properly treated as 3.1 even without a tools-version comment.\n    func testVersionSpecificLoadingOfVersion3Manifest() async throws {\n        // Create a temporary FS to hold the package manifests.\n        let fs = InMemoryFileSystem()\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Write a regular manifest with a tools version comment, and a `Package@swift-3.swift` manifest without one.\n        let packageDir = AbsolutePath.root\n        let manifestContents = \"import PackageDescription\\nlet package = Package(name: \\\"Trivial\\\")\"\n        try fs.writeFileContents(\n            packageDir.appending(component: Manifest.basename + \".swift\"),\n            string: \"// swift-tools-version:4.0\\n\" + manifestContents\n        )\n        try fs.writeFileContents(\n            packageDir.appending(component: Manifest.basename + \"@swift-3.swift\"),\n            string: manifestContents\n        )\n        // Check we can load the manifest.\n        let manifest = try await manifestLoader.load(packagePath: packageDir, packageKind: .root(packageDir), currentToolsVersion: .v4_2, fileSystem: fs, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertEqual(manifest.displayName, \"Trivial\")\n\n        // Switch it around so that the main manifest is now the one that doesn't have a comment.\n        try fs.writeFileContents(\n            packageDir.appending(component: Manifest.basename + \".swift\"),\n            string: manifestContents\n        )\n        try fs.writeFileContents(\n            packageDir.appending(component: Manifest.basename + \"@swift-4.swift\"),\n            string: \"// swift-tools-version:4.0\\n\" + manifestContents\n        )\n        // Check we can load the manifest.\n        let manifest2 = try await manifestLoader.load(packagePath: packageDir, packageKind: .root(packageDir), currentToolsVersion: .v4_2, fileSystem: fs, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertEqual(manifest2.displayName, \"Trivial\")\n    }\n\n    func testRuntimeManifestErrors() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                products: [\n                    .executable(name: \"tool\", targets: [\"tool\"]),\n                    .library(name: \"Foo\", targets: [\"Foo\"]),\n                ],\n                dependencies: [\n                    .package(url: \"/foo1\", from: \"1.0,0\"),\n                ],\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: [\"dep1\", .product(name: \"product\"), .target(name: \"target\")]),\n                    .testTarget(\n                        name: \"bar\",\n                        dependencies: [\"foo\"]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.runtimeManifestErrors(let errors) = error {\n                XCTAssertEqual(errors, [\"Invalid semantic version string '1.0,0'\"])\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testNotAbsoluteDependencyPath() async throws {\n        let content = \"\"\"\n        import PackageDescription\n        let package = Package(\n            name: \"Trivial\",\n            dependencies: [\n                .package(path: \"https://someurl.com\"),\n            ],\n            targets: [\n                .target(\n                    name: \"foo\",\n                    dependencies: []),\n            ]\n        )\n        \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let message, let diagnosticFile, _) = error {\n                XCTAssertNil(diagnosticFile)\n                XCTAssertEqual(message, \"'https://someurl.com' is not a valid path for path-based dependencies; use relative or absolute path instead.\")\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testFileURLErrors() async throws {\n        enum ExpectedError {\n          case invalidAbsolutePath\n          case relativePath\n          case unsupportedHostname\n\n          var manifestError: ManifestParseError? {\n            switch self {\n            case .invalidAbsolutePath:\n              return nil\n            case .relativePath:\n              return .invalidManifestFormat(\"file:// URLs cannot be relative, did you mean to use '.package(path:)'?\", diagnosticFile: nil, compilerCommandLine: nil)\n            case .unsupportedHostname:\n              return .invalidManifestFormat(\"file:// URLs with hostnames are not supported, are you missing a '/'?\", diagnosticFile: nil, compilerCommandLine: nil)\n            }\n          }\n\n          var pathError: TSCBasic.PathValidationError? {\n            switch self {\n            case .invalidAbsolutePath:\n              return .invalidAbsolutePath(\"\")\n            default:\n              return nil\n            }\n          }\n        }\n\n        let urls: [(String, ExpectedError)] = [\n          (\"file://../best\", .relativePath), // Possible attempt at a relative path.\n          (\"file://somehost/bar\", .unsupportedHostname), // Obviously non-local.\n          (\"file://localhost/bar\", .unsupportedHostname), // Local but non-trivial (e.g. on Windows, this is a UNC path).\n          (\"file://\", .invalidAbsolutePath) // Invalid path.\n        ]\n        for (url, expectedError) in urls {\n            let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                dependencies: [\n                    .package(url: \"\\(url)\", from: \"1.0.0\"),\n                ],\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: []),\n                ]\n            )\n            \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                switch error {\n                case is ManifestParseError:\n                    XCTAssertEqual(error as? ManifestParseError, expectedError.manifestError)\n                case is TSCBasic.PathValidationError:\n                    XCTAssertEqual(error.localizedDescription, expectedError.pathError?.localizedDescription)\n                default:\n                    XCTFail(\"unhandled error type: \\(error)\")\n                }\n            }\n        }\n    }\n\n    func testProductTargetNotFound() async throws {\n        let content = \"\"\"\n            import PackageDescription\n\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .library(name: \"Product\", targets: [\"B\"]),\n                ],\n                targets: [\n                    .target(name: \"A\"),\n                    .target(name: \"b\"),\n                    .target(name: \"C\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        testDiagnostics(validationDiagnostics) { result in\n            result.check(diagnostic: .contains(\"target 'B' referenced in product 'Product' could not be found; valid targets are: 'A', 'C', 'b'\"), severity: .error)\n        }\n    }\n\n    // run this with TSAN/ASAN to detect concurrency issues\n    func testConcurrencyWithWarmup() async throws {\n        try await testWithTemporaryDirectory { path in\n            let total = 1000\n            let manifestPath = path.appending(components: \"pkg\", \"Package.swift\")\n            try localFileSystem.createDirectory(manifestPath.parentDirectory)\n            try localFileSystem.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    targets: [\n                        .target(\n                            name: \"foo\",\n                            dependencies: []),\n                    ]\n                )\n                \"\"\"\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let delegate = ManifestTestDelegate()\n            let manifestLoader = ManifestLoader(toolchain: try UserToolchain.default, cacheDir: path, delegate: delegate)\n            let identityResolver = DefaultIdentityResolver()\n            let dependencyMapper = DefaultDependencyMapper(identityResolver: identityResolver)\n\n            // warm up caches\n            let manifest = try await manifestLoader.load(\n                manifestPath: manifestPath,\n                manifestToolsVersion: .v4_2,\n                packageIdentity: .plain(\"Trivial\"),\n                packageKind: .fileSystem(manifestPath.parentDirectory),\n                packageLocation: manifestPath.pathString,\n                packageVersion: nil,\n                identityResolver: identityResolver,\n                dependencyMapper: dependencyMapper,\n                fileSystem: localFileSystem,\n                observabilityScope: observability.topScope,\n                delegateQueue: .sharedConcurrent\n            )\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(manifest.displayName, \"Trivial\")\n            XCTAssertEqual(manifest.targets[0].name, \"foo\")\n\n            for _ in 0 ..< total {\n                let manifest = try await manifestLoader.load(\n                    manifestPath: manifestPath,\n                    manifestToolsVersion: .v4_2,\n                    packageIdentity: .plain(\"Trivial\"),\n                    packageKind: .fileSystem(manifestPath.parentDirectory),\n                    packageLocation: manifestPath.pathString,\n                    packageVersion: nil,\n                    identityResolver: identityResolver,\n                    dependencyMapper: dependencyMapper,\n                    fileSystem: localFileSystem,\n                    observabilityScope: observability.topScope,\n                    delegateQueue: .sharedConcurrent\n                )\n\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                XCTAssertEqual(manifest.displayName, \"Trivial\")\n                XCTAssertEqual(manifest.targets[0].name, \"foo\")\n            }\n\n            try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)).count, total+1)\n            XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description)\n            XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description)\n        }\n    }\n\n    // run this with TSAN/ASAN to detect concurrency issues\n    func testConcurrencyNoWarmUp() async throws {\n        // FIXME: does this actually trigger only on Windows or are other\n        // platforms just getting lucky?  I'm feeling lucky.\n        try XCTSkipOnWindows(because: \"Foundation Process.terminationStatus race condition (apple/swift-corelibs-foundation#4589\")\n        try XCTSkipIfPlatformCI()\n\n        try await testWithTemporaryDirectory { path in\n            let total = 100\n            let observability = ObservabilitySystem.makeForTesting()\n            let delegate = ManifestTestDelegate()\n            let manifestLoader = ManifestLoader(toolchain: try UserToolchain.default, cacheDir: path, delegate: delegate)\n            let identityResolver = DefaultIdentityResolver()\n            let dependencyMapper = DefaultDependencyMapper(identityResolver: identityResolver)\n\n            for _ in 0 ..< total {\n                let random = Int.random(in: 0 ... total / 4)\n                let manifestPath = path.appending(components: \"pkg-\\(random)\", \"Package.swift\")\n                if !localFileSystem.exists(manifestPath) {\n                    try localFileSystem.createDirectory(manifestPath.parentDirectory)\n                    try localFileSystem.writeFileContents(\n                        manifestPath,\n                        string: \"\"\"\n                        import PackageDescription\n                        let package = Package(\n                            name: \"Trivial-\\(random)\",\n                            targets: [\n                                .target(\n                                    name: \"foo-\\(random)\",\n                                    dependencies: []),\n                            ]\n                        )\n                        \"\"\"\n                    )\n                }\n\n                let manifest = try await manifestLoader.load(\n                    manifestPath: manifestPath,\n                    manifestToolsVersion: .v4_2,\n                    packageIdentity: .plain(\"Trivial-\\(random)\"),\n                    packageKind: .fileSystem(manifestPath.parentDirectory),\n                    packageLocation: manifestPath.pathString,\n                    packageVersion: nil,\n                    identityResolver: identityResolver,\n                    dependencyMapper: dependencyMapper,\n                    fileSystem: localFileSystem,\n                    observabilityScope: observability.topScope,\n                    delegateQueue: .sharedConcurrent\n                )\n\n                XCTAssertEqual(manifest.displayName, \"Trivial-\\(random)\")\n                XCTAssertEqual(manifest.targets[0].name, \"foo-\\(random)\")\n            }\n\n            try await XCTAssertAsyncEqual(try await delegate.loaded(timeout: .seconds(1)).count, total)\n            XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description)\n            XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_5_0_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCBasic.ByteString\n\nfinal class PackageDescription5_0LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v5\n    }\n\n    func testBasics() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                products: [\n                    .executable(name: \"tool\", targets: [\"tool\"]),\n                    .library(name: \"Foo\", targets: [\"foo\"]),\n                ],\n                dependencies: [\n                    .package(url: \"/foo1\", from: \"1.0.0\"),\n                ],\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: [\"dep1\", .product(name: \"product\"), .target(name: \"target\")]),\n                    .target(\n                        name: \"tool\"),\n                    .testTarget(\n                        name: \"bar\",\n                        dependencies: [\"foo\"]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.displayName, \"Trivial\")\n\n        // Check targets.\n        let foo = manifest.targetMap[\"foo\"]!\n        XCTAssertEqual(foo.name, \"foo\")\n        XCTAssertFalse(foo.isTest)\n        XCTAssertEqual(foo.dependencies, [\"dep1\", .product(name: \"product\"), .target(name: \"target\")])\n\n        let bar = manifest.targetMap[\"bar\"]!\n        XCTAssertEqual(bar.name, \"bar\")\n        XCTAssertTrue(bar.isTest)\n        XCTAssertEqual(bar.dependencies, [\"foo\"])\n\n        // Check dependencies.\n        let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n        XCTAssertEqual(deps[\"foo1\"], .localSourceControl(path: \"/foo1\", requirement: .upToNextMajor(from: \"1.0.0\")))\n\n        // Check products.\n        let products = Dictionary(uniqueKeysWithValues: manifest.products.map{ ($0.name, $0) })\n\n        let tool = products[\"tool\"]!\n        XCTAssertEqual(tool.name, \"tool\")\n        XCTAssertEqual(tool.targets, [\"tool\"])\n        XCTAssertEqual(tool.type, .executable)\n\n        let fooProduct = products[\"Foo\"]!\n        XCTAssertEqual(fooProduct.name, \"Foo\")\n        XCTAssertEqual(fooProduct.type, .library(.automatic))\n        XCTAssertEqual(fooProduct.targets, [\"foo\"])\n    }\n\n    func testSwiftLanguageVersion() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: [.v4, .v4_2, .v5]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            XCTAssertEqual(manifest.swiftLanguageVersions, [.v4, .v4_2, .v5])\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: [.v3]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                    XCTAssertMatch(message, .contains(\"'v3' is unavailable\"))\n                    XCTAssertMatch(message, .contains(\"'v3' was obsoleted in PackageDescription 5\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   swiftLanguageVersions: [.version(\"\")]\n                )\n            \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.runtimeManifestErrors(let messages) = error {\n                    XCTAssertEqual(messages, [\"invalid Swift language version: \"])\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n    }\n\n    func testPlatformOptions() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               platforms: [\n                   .macOS(\"10.13.option1.option2\"), .iOS(\"12.2.option2\"),\n                   .tvOS(\"12.3.4.option5.option7.option9\")\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.platforms, [\n            PlatformDescription(name: \"macos\", version: \"10.13\", options: [\"option1\", \"option2\"]),\n            PlatformDescription(name: \"ios\", version: \"12.2\", options: [\"option2\"]),\n            PlatformDescription(name: \"tvos\", version: \"12.3.4\", options: [\"option5\", \"option7\", \"option9\"]),\n        ])\n    }\n\n    func testPlatforms() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [\n                       .macOS(.v10_13), .iOS(\"12.2\"),\n                       .tvOS(.v12), .watchOS(.v3),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            XCTAssertEqual(manifest.platforms, [\n                PlatformDescription(name: \"macos\", version: \"10.13\"),\n                PlatformDescription(name: \"ios\", version: \"12.2\"),\n                PlatformDescription(name: \"tvos\", version: \"12.0\"),\n                PlatformDescription(name: \"watchos\", version: \"3.0\"),\n            ])\n        }\n\n        // Test invalid custom versions.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [\n                       .macOS(\"-11.2\"), .iOS(\"12.x.2\"), .tvOS(\"10..2\"), .watchOS(\"1.0\"),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.runtimeManifestErrors(let errors) = error {\n                    XCTAssertEqual(errors, [\n                        \"invalid macOS version -11.2; -11 should be a positive integer\",\n                        \"invalid iOS version 12.x.2; x should be a positive integer\",\n                        \"invalid tvOS version 10..2; found an empty component\",\n                        \"invalid watchOS version 1.0; the minimum major version should be 2\",\n                    ])\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        // Duplicates.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [\n                       .macOS(.v10_10), .macOS(.v10_12),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.runtimeManifestErrors(let errors) = error {\n                    XCTAssertEqual(errors, [\"found multiple declaration for the platform: macos\"])\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        // Empty.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: []\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.runtimeManifestErrors(let errors) = error {\n                    XCTAssertEqual(errors, [\"supported platforms can't be empty\"])\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        // Newer OS version.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [\n                       .macOS(.v11), .iOS(.v14),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                    XCTAssertMatch(message, .contains(\"error: 'v11' is unavailable\"))\n                    XCTAssertMatch(message, .contains(\"note: 'v11' was introduced in PackageDescription 5.3\"))\n                    XCTAssertMatch(message, .contains(\"note: 'v14' was introduced in PackageDescription 5.3\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        // Newer OS version alias (now marked as unavailable).\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [\n                       .macOS(.v10_16), .iOS(.v14),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                    XCTAssertMatch(message, .contains(\"error: 'v10_16' has been renamed to 'v11'\"))\n                    XCTAssertMatch(message, .contains(\"note: 'v10_16' has been explicitly marked unavailable here\"))\n                    XCTAssertMatch(message, .contains(\"note: 'v14' was introduced in PackageDescription 5.3\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n    }\n\n    func testBuildSettings() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .target(\n                       name: \"Foo\",\n                       cSettings: [\n                           .headerSearchPath(\"path/to/foo\"),\n                           .define(\"C\", .when(platforms: [.linux])),\n                           .define(\"CC\", to: \"4\", .when(platforms: [.linux], configuration: .release)),\n                       ],\n                       cxxSettings: [\n                           .headerSearchPath(\"path/to/bar\"),\n                           .define(\"CXX\"),\n                       ],\n                       swiftSettings: [\n                           .define(\"SWIFT\", .when(configuration: .release)),\n                           .define(\"SWIFT_DEBUG\", .when(platforms: [.watchOS], configuration: .debug)),\n                       ],\n                       linkerSettings: [\n                           .linkedLibrary(\"libz\"),\n                           .linkedFramework(\"CoreData\", .when(platforms: [.macOS, .tvOS])),\n                       ]\n                   ),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let settings = manifest.targets[0].settings\n\n        XCTAssertEqual(settings[0], .init(tool: .c, kind: .headerSearchPath(\"path/to/foo\")))\n        XCTAssertEqual(settings[1], .init(tool: .c, kind: .define(\"C\"), condition: .init(platformNames: [\"linux\"])))\n        XCTAssertEqual(settings[2], .init(tool: .c, kind: .define(\"CC=4\"), condition: .init(platformNames: [\"linux\"], config: \"release\")))\n\n        XCTAssertEqual(settings[3], .init(tool: .cxx, kind: .headerSearchPath(\"path/to/bar\")))\n        XCTAssertEqual(settings[4], .init(tool: .cxx, kind: .define(\"CXX\")))\n\n        XCTAssertEqual(settings[5], .init(tool: .swift, kind: .define(\"SWIFT\"), condition: .init(config: \"release\")))\n        XCTAssertEqual(settings[6], .init(tool: .swift, kind: .define(\"SWIFT_DEBUG\"), condition: .init(platformNames: [\"watchos\"], config: \"debug\")))\n\n        XCTAssertEqual(settings[7], .init(tool: .linker, kind: .linkedLibrary(\"libz\")))\n        XCTAssertEqual(settings[8], .init(tool: .linker, kind: .linkedFramework(\"CoreData\"), condition: .init(platformNames: [\"macos\", \"tvos\"])))\n    }\n\n    func testSerializedDiagnostics() async throws {\n        try await testWithTemporaryDirectory { path in\n            let fs = localFileSystem\n            let manifestPath = path.appending(components: \"pkg\", \"Package.swift\")\n\n            let loader = ManifestLoader(\n                toolchain: try UserToolchain.default,\n                serializedDiagnostics: true,\n                cacheDir: path)\n\n            do {\n                let observability = ObservabilitySystem.makeForTesting()\n\n                try fs.createDirectory(manifestPath.parentDirectory)\n                try fs.writeFileContents(\n                    manifestPath,\n                    string: \"\"\"\n                    import PackageDescription\n                    let package = Package(\n                    name: \"Trivial\",\n                        targets: [\n                            .target(\n                                name: \"foo\",\n                                dependencies: []),\n\n                    )\n                    \"\"\"\n                )\n\n                do {\n                    _ = try await loader.load(\n                        manifestPath: manifestPath,\n                        packageKind: .fileSystem(manifestPath.parentDirectory),\n                        toolsVersion: .v5,\n                        fileSystem: fs,\n                        observabilityScope: observability.topScope\n                    )\n                } catch ManifestParseError.invalidManifestFormat(let error, let diagnosticFile, _) {\n                    XCTAssertMatch(error, .contains(\"expected expression in container literal\"))\n                    let contents = try localFileSystem.readFileContents(diagnosticFile!)\n                    XCTAssertNotNil(contents)\n                }\n            }\n\n            do {\n                let observability = ObservabilitySystem.makeForTesting()\n\n                try fs.writeFileContents(\n                    manifestPath,\n                    string: \"\"\"\n                    import PackageDescription\n                    func foo() {\n                        let a = 5\n                    }\n                    let package = Package(\n                        name: \"Trivial\",\n                        targets: [\n                            .target(\n                                name: \"foo\",\n                                dependencies: []),\n                        ]\n                    )\n                    \"\"\"\n                )\n\n                _ = try await loader.load(\n                    manifestPath: manifestPath,\n                    packageKind: .fileSystem(manifestPath.parentDirectory),\n                    toolsVersion: .v5,\n                    fileSystem: fs,\n                    observabilityScope: observability.topScope\n                )\n\n                testDiagnostics(observability.diagnostics) { result in\n                    let diagnostic = result.check(diagnostic: .contains(\"initialization of immutable value\"), severity: .warning)\n                    let contents = try diagnostic?.metadata?.manifestLoadingDiagnosticFile.map { try localFileSystem.readFileContents($0) }\n                    XCTAssertNotNil(contents)\n                }\n            }\n        }\n    }\n\n    func testInvalidBuildSettings() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   targets: [\n                       .target(\n                           name: \"Foo\",\n                           cSettings: [\n                               .headerSearchPath(\"$(BYE)/path/to/foo/$(SRCROOT)/$(HELLO)\"),\n                           ]\n                       ),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.runtimeManifestErrors(let errors) = error {\n                    XCTAssertEqual(errors, [\"the build setting 'headerSearchPath' contains invalid component(s): $(BYE) $(SRCROOT) $(HELLO)\"])\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   targets: [\n                       .target(\n                           name: \"Foo\",\n                           cSettings: []\n                       ),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            _ = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    func testWindowsPlatform() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .target(\n                       name: \"foo\",\n                       cSettings: [\n                           .define(\"LLVM_ON_WIN32\", .when(platforms: [.windows])),\n                       ]\n                   ),\n               ]\n            )\n            \"\"\"\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                    XCTAssertMatch(message, .contains(\"is unavailable\"))\n                    XCTAssertMatch(message, .contains(\"was introduced in PackageDescription 5.2\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, toolsVersion: .v5_2, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            XCTAssertEqual(manifest.displayName, \"Foo\")\n\n            // Check targets.\n            let foo = manifest.targetMap[\"foo\"]!\n            XCTAssertEqual(foo.name, \"foo\")\n            XCTAssertFalse(foo.isTest)\n            XCTAssertEqual(foo.dependencies, [])\n\n            let settings = foo.settings\n            XCTAssertEqual(settings[0], .init(tool: .c, kind: .define(\"LLVM_ON_WIN32\"), condition: .init(platformNames: [\"windows\"])))\n        }\n    }\n\n    func testPackageNameUnavailable() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                products: [],\n                dependencies: [\n                    .package(name: \"Foo\", url: \"/foo1\", from: \"1.0.0\"),\n                ],\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: [.product(name: \"product\", package: \"Foo\")]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                XCTAssertMatch(message, .contains(\"is unavailable\"))\n                XCTAssertMatch(message, .contains(\"was introduced in PackageDescription 5.2\"))\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testManifestWithPrintStatements() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            print(String(repeating: \"Hello manifest... \", count: 65536))\n            let package = Package(\n                name: \"PackageWithChattyManifest\"\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.displayName, \"PackageWithChattyManifest\")\n        XCTAssertEqual(manifest.toolsVersion, .v5)\n        XCTAssertEqual(manifest.targets, [])\n        XCTAssertEqual(manifest.dependencies, [])\n    }\n\n    func testManifestLoaderEnvironment() async throws {\n        try await testWithTemporaryDirectory { path in\n            let fs = localFileSystem\n\n            let packagePath = path.appending(\"pkg\")\n            try fs.createDirectory(packagePath)\n            let manifestPath = packagePath.appending(\"Package.swift\")\n            try fs.writeFileContents(\n                manifestPath,\n                string: \"\"\"\n                // swift-tools-version:5\n                import PackageDescription\n\n                let package = Package(\n                    name: \"Trivial\",\n                    targets: [\n                        .target(\n                            name: \"foo\",\n                            dependencies: []),\n                    ]\n                )\n                \"\"\"\n            )\n\n            let moduleTraceFilePath = path.appending(\"swift-module-trace\")\n            var env = Environment.current\n            env[\"SWIFT_LOADED_MODULE_TRACE_FILE\"] = moduleTraceFilePath.pathString\n            let toolchain = try UserToolchain(swiftSDK: SwiftSDK.default, environment: env)\n            let manifestLoader = ManifestLoader(\n                toolchain: toolchain,\n                serializedDiagnostics: true,\n                isManifestSandboxEnabled: false,\n                cacheDir: nil)\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let manifest = try await manifestLoader.load(\n                manifestPath: manifestPath,\n                packageKind: .fileSystem(manifestPath.parentDirectory),\n                toolsVersion: .v5,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(manifest.displayName, \"Trivial\")\n\n            let moduleTraceJSON: String = try localFileSystem.readFileContents(moduleTraceFilePath)\n            XCTAssertMatch(moduleTraceJSON, .contains(\"PackageDescription\"))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_5_2_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageDescription5_2LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v5_2\n    }\n\n    func testMissingTargetProductDependencyPackage() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                products: [],\n                dependencies: [\n                    .package(url: \"/foo1\", from: \"1.0.0\"),\n                ],\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: [.product(name: \"product\")]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                XCTAssert(error.contains(\"error: \\'product(name:package:)\\' is unavailable: the 'package' argument is mandatory as of tools version 5.2\"))\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testDependencyNameForTargetDependencyResolution() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                products: [],\n                dependencies: [\n                    .package(name: \"Foo\", url: \"/foo1\", from: \"1.0.0\"),\n                    .package(name: \"Foo2\", path: \"/foo2\"),\n                    .package(name: \"Foo3\", url: \"/foo3\", .upToNextMajor(from: \"1.0.0\")),\n                    .package(name: \"Foo4\", url: \"/foo4\", \"1.0.0\"..<\"2.0.0\"),\n                    .package(name: \"Foo5\", url: \"/foo5\", \"1.0.0\"...\"2.0.0\"),\n                    .package(url: \"/bar\", from: \"1.0.0\"),\n                    .package(url: \"https://github.com/foo/Bar2.git/\", from: \"1.0.0\"),\n                    .package(url: \"https://github.com/foo/Baz.git\", from: \"1.0.0\"),\n                    .package(url: \"https://github.com/apple/swift\", from: \"1.0.0\"),\n                ],\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: [\n                          .product(name: \"product\", package: \"Foo\"),\n                          .product(name: \"product\", package: \"Foo2\"),\n                          .product(name: \"product\", package: \"Foo3\"),\n                          .product(name: \"product\", package: \"Foo4\"),\n                          .product(name: \"product\", package: \"Foo5\"),\n                          .product(name: \"product\", package: \"bar\"),\n                          .product(name: \"product\", package: \"bar2\"),\n                          .product(name: \"product\", package: \"baz\"),\n                          .product(name: \"product\", package: \"swift\")\n                        ]\n                    ),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.displayName, \"Trivial\")\n        XCTAssertEqual(manifest.dependencies[0].nameForModuleDependencyResolutionOnly, \"Foo\")\n        XCTAssertEqual(manifest.dependencies[1].nameForModuleDependencyResolutionOnly, \"Foo2\")\n        XCTAssertEqual(manifest.dependencies[2].nameForModuleDependencyResolutionOnly, \"Foo3\")\n        XCTAssertEqual(manifest.dependencies[3].nameForModuleDependencyResolutionOnly, \"Foo4\")\n        XCTAssertEqual(manifest.dependencies[4].nameForModuleDependencyResolutionOnly, \"Foo5\")\n        XCTAssertEqual(manifest.dependencies[5].nameForModuleDependencyResolutionOnly, \"bar\")\n        XCTAssertEqual(manifest.dependencies[6].nameForModuleDependencyResolutionOnly, \"Bar2\")\n        XCTAssertEqual(manifest.dependencies[7].nameForModuleDependencyResolutionOnly, \"Baz\")\n        XCTAssertEqual(manifest.dependencies[8].nameForModuleDependencyResolutionOnly, \"swift\")\n    }\n\n    func testTargetDependencyProductInvalidPackage() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    products: [],\n                    dependencies: [\n                        .package(url: \"http://scm.com/org/foo\", from: \"1.0.0\"),\n                        .package(url: \"http://scm.com/org/bar\", from: \"2.0.0\"),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"Target1\",\n                            dependencies: [.product(name: \"product\", package: \"foo1\")]),\n                        .target(\n                            name: \"Target2\",\n                            dependencies: [\"foos\"]),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.checkUnordered(diagnostic: \"unknown package 'foo1' in dependencies of target 'Target1'; valid packages are: 'foo' (from 'http://scm.com/org/foo'), 'bar' (from 'http://scm.com/org/bar')\", severity: .error)\n                result.checkUnordered(diagnostic: \"unknown dependency 'foos' in target 'Target2'; valid dependencies are: 'foo' (from 'http://scm.com/org/foo'), 'bar' (from 'http://scm.com/org/bar')\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    products: [],\n                    dependencies: [\n                        .package(name: \"Foo\", url: \"http://scm.com/org/foo\", from: \"1.0.0\"),\n                        .package(name: \"Bar\", url: \"http://scm.com/org/bar\", from: \"2.0.0\"),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"Target1\",\n                            dependencies: [.product(name: \"product\", package: \"foo1\")]),\n                        .target(\n                            name: \"Target2\",\n                            dependencies: [\"foos\"]),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.checkUnordered(diagnostic: \"unknown package 'foo1' in dependencies of target 'Target1'; valid packages are: 'Foo' (from 'http://scm.com/org/foo'), 'Bar' (from 'http://scm.com/org/bar')\", severity: .error)\n                result.checkUnordered(diagnostic: \"unknown dependency 'foos' in target 'Target2'; valid dependencies are: 'Foo' (from 'http://scm.com/org/foo'), 'Bar' (from 'http://scm.com/org/bar')\", severity: .error)\n            }\n        }\n\n        // packageKind == root has special rules in this case\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    products: [],\n                    dependencies: [\n                        .package(name: \"Foo\", url: \"http://scm.com/org/foo1\", from: \"1.0.0\"),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"Target1\",\n                            dependencies: [.product(name: \"product\", package: \"foo1\")]),\n                        .target(\n                            name: \"Target2\",\n                            dependencies: [\"foos\"]),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, packageKind: .root(.root), observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"unknown package 'foo1' in dependencies of target 'Target1'; valid packages are: 'Foo' (from 'http://scm.com/org/foo1')\", severity: .error)\n            }\n        }\n\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    products: [],\n                    dependencies: [\n                        .package(path: \"/foo\"),\n                        .package(path: \"/bar\"),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"Target1\",\n                            dependencies: [.product(name: \"product\", package: \"foo1\")]),\n                        .target(\n                            name: \"Target2\",\n                            dependencies: [\"foos\"]),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                let fooPkg: AbsolutePath = \"/foo\"\n                let barPkg: AbsolutePath = \"/bar\"\n                result.checkUnordered(diagnostic: \"unknown package 'foo1' in dependencies of target 'Target1'; valid packages are: 'foo' (at '\\(fooPkg)'), 'bar' (at '\\(barPkg)')\", severity: .error)\n                result.checkUnordered(diagnostic: \"unknown dependency 'foos' in target 'Target2'; valid dependencies are: 'foo' (at '\\(fooPkg)'), 'bar' (at '\\(barPkg)')\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    products: [],\n                    dependencies: [\n                        .package(name: \"Foo\", path: \"/foo1\"),\n                        .package(name: \"Bar\", path: \"/bar1\"),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"Target1\",\n                            dependencies: [.product(name: \"product\", package: \"foo1\")]),\n                        .target(\n                            name: \"Target2\",\n                            dependencies: [\"foos\"]),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                let foo1Pkg: AbsolutePath = \"/foo1\"\n                let bar1Pkg: AbsolutePath = \"/bar1\"\n                result.checkUnordered(diagnostic: \"unknown package 'foo1' in dependencies of target 'Target1'; valid packages are: 'Foo' (at '\\(foo1Pkg)'), 'Bar' (at '\\(bar1Pkg)')\", severity: .error)\n                result.checkUnordered(diagnostic: \"unknown dependency 'foos' in target 'Target2'; valid dependencies are: 'Foo' (at '\\(foo1Pkg)'), 'Bar' (at '\\(bar1Pkg)')\", severity: .error)\n            }\n        }\n    }\n\n    func testTargetDependencyReference() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Trivial\",\n                products: [],\n                dependencies: [\n                    .package(name: \"Foobar\", url: \"/foobar\", from: \"1.0.0\"),\n                    .package(name: \"Barfoo\", url: \"/barfoo\", from: \"1.0.0\"),\n                ],\n                targets: [\n                    .target(\n                        name: \"foo\",\n                        dependencies: [.product(name: \"Something\", package: \"Foobar\"), \"Barfoo\"]),\n                    .target(\n                        name: \"bar\",\n                        dependencies: [\"foo\"]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let dependencies = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.nameForModuleDependencyResolutionOnly, $0) })\n        let dependencyFoobar = dependencies[\"Foobar\"]!\n        let dependencyBarfoo = dependencies[\"Barfoo\"]!\n        let targetFoo = manifest.targetMap[\"foo\"]!\n        let targetBar = manifest.targetMap[\"bar\"]!\n        XCTAssertEqual(manifest.packageDependency(referencedBy: targetFoo.dependencies[0]), dependencyFoobar)\n        XCTAssertEqual(manifest.packageDependency(referencedBy: targetFoo.dependencies[1]), dependencyBarfoo)\n        XCTAssertEqual(manifest.packageDependency(referencedBy: targetBar.dependencies[0]), nil)\n    }\n\n    func testResourcesUnavailable() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .target(\n                       name: \"Foo\",\n                       resources: [\n                           .copy(\"foo.txt\"),\n                           .process(\"bar.txt\"),\n                       ]\n                   ),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                XCTAssertMatch(error, .contains(\"is unavailable\"))\n                XCTAssertMatch(error, .contains(\"was introduced in PackageDescription 5.3\"))\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testBinaryTargetUnavailable() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [],\n                    targets: [\n                        .binaryTarget(\n                            name: \"Foo\",\n                            path: \"../Foo.xcframework\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                    XCTAssertMatch(error, .contains(\"is unavailable\"))\n                    XCTAssertMatch(error, .contains(\"was introduced in PackageDescription 5.3\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [],\n                    targets: [\n                        .binaryTarget(\n                            name: \"Foo\",\n                            url: \"https://foo.com/foo.zip\",\n                            checksum: \"21321441231232\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                    XCTAssertMatch(error, .contains(\"is unavailable\"))\n                    XCTAssertMatch(error, .contains(\"was introduced in PackageDescription 5.3\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n    }\n\n    func testConditionalTargetDependenciesUnavailable() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                dependencies: [\n                    .package(path: \"/Baz\"),\n                ],\n                targets: [\n                    .target(name: \"Foo\", dependencies: [\n                        .target(name: \"Biz\"),\n                        .target(name: \"Bar\", condition: .when(platforms: [.linux])),\n                    ]),\n                    .target(name: \"Bar\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                XCTAssertMatch(error, .contains(\"is unavailable\"))\n                XCTAssertMatch(error, .contains(\"was introduced in PackageDescription 5.3\"))\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testDefaultLocalizationUnavailable() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    defaultLocalization: \"fr\",\n                    products: [],\n                    targets: [\n                        .target(name: \"Foo\"),\n                    ],\n                    swiftLanguageVersions: [.v5]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                    XCTAssertMatch(error, .contains(\"is unavailable\"))\n                    XCTAssertMatch(error, .contains(\"was introduced in PackageDescription 5.3\"))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n    }\n\n    func testManifestLoadingIsSandboxed() async throws {\n        #if !os(macOS)\n        // Sandboxing is only done on macOS today.\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let content = \"\"\"\n            import Foundation\n\n            try! String(contentsOf: URL(string: \"http://127.0.0.1\")!)\n\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                targets: [\n                    .target(name: \"Foo\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                XCTAssertTrue(error.contains(\"Operation not permitted\"), \"unexpected error message: \\(error)\")\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_5_3_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport PackageLoading\nimport _InternalTestSupport\nimport XCTest\n\nimport enum TSCBasic.PathValidationError\n\nfinal class PackageDescription5_3LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v5_3\n    }\n\n    func testResources() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .target(\n                       name: \"Foo\",\n                       resources: [\n                           .copy(\"foo.txt\"),\n                           .process(\"bar.txt\"),\n                           .process(\"biz.txt\", localization: .default),\n                           .process(\"baz.txt\", localization: .base),\n                       ]\n                    ),\n                    .testTarget(\n                       name: \"FooTests\",\n                       resources: [\n                           .process(\"testfixture.txt\"),\n                       ]\n                    ),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let resources = manifest.targets[0].resources\n        XCTAssertEqual(resources[0], TargetDescription.Resource(rule: .copy, path: \"foo.txt\"))\n        XCTAssertEqual(resources[1], TargetDescription.Resource(rule: .process(localization: .none), path: \"bar.txt\"))\n        XCTAssertEqual(resources[2], TargetDescription.Resource(rule: .process(localization: .default), path: \"biz.txt\"))\n        XCTAssertEqual(resources[3], TargetDescription.Resource(rule: .process(localization: .base), path: \"baz.txt\"))\n\n        let testResources = manifest.targets[1].resources\n        XCTAssertEqual(testResources[0], TargetDescription.Resource(rule: .process(localization: .none), path: \"testfixture.txt\"))\n    }\n\n    func testBinaryTargetsTrivial() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .library(name: \"Foo1\", targets: [\"Foo1\"]),\n                    .library(name: \"Foo2\", targets: [\"Foo2\"])\n                ],\n                targets: [\n                    .binaryTarget(\n                        name: \"Foo1\",\n                        path: \"../Foo1.xcframework\"),\n                    .binaryTarget(\n                        name: \"Foo2\",\n                        url: \"https://foo.com/Foo2-1.0.0.zip\",\n                        checksum: \"839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A\"),\n                    .binaryTarget(\n                        name: \"Foo3\",\n                        path: \"./Foo3.zip\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let targets = Dictionary(uniqueKeysWithValues: manifest.targets.map({ ($0.name, $0) }))\n        let foo1 = targets[\"Foo1\"]!\n        let foo2 = targets[\"Foo2\"]!\n        let foo3 = targets[\"Foo3\"]\n        XCTAssertEqual(foo1, try? TargetDescription(\n            name: \"Foo1\",\n            dependencies: [],\n            path: \"../Foo1.xcframework\",\n            url: nil,\n            exclude: [],\n            sources: nil,\n            resources: [],\n            publicHeadersPath: nil,\n            type: .binary,\n            packageAccess: false,\n            pkgConfig: nil,\n            providers: nil,\n            settings: [],\n            checksum: nil))\n        XCTAssertEqual(foo2, try? TargetDescription(\n            name: \"Foo2\",\n            dependencies: [],\n            path: nil,\n            url: \"https://foo.com/Foo2-1.0.0.zip\",\n            exclude: [],\n            sources: nil,\n            resources: [],\n            publicHeadersPath: nil,\n            type: .binary,\n            packageAccess: false,\n            pkgConfig: nil,\n            providers: nil,\n            settings: [],\n            checksum: \"839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A\"))\n        XCTAssertEqual(foo3, try? TargetDescription(\n            name: \"Foo3\",\n            dependencies: [],\n            path: \"./Foo3.zip\",\n            url: nil,\n            exclude: [],\n            sources: nil,\n            resources: [],\n            publicHeadersPath: nil,\n            type: .binary,\n            packageAccess: false,\n            pkgConfig: nil,\n            providers: nil,\n            settings: [],\n            checksum: nil\n        ))\n    }\n\n    func testBinaryTargetsDisallowedProperties() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            var fwBinaryTarget = Target.binaryTarget(\n                name: \"Foo\",\n                url: \"https://example.com/foo.git\",\n                checksum: \"xyz\"\n            )\n            fwBinaryTarget.linkerSettings = [ .linkedFramework(\"AVFoundation\") ]\n            let package = Package(name: \"foo\", targets: [fwBinaryTarget])\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            XCTAssertEqual(error.localizedDescription,\n                \"target 'Foo' is assigned a property 'settings' which is not accepted for the binary target type. \" +\n                \"The current property value has the following representation: \" +\n                \"[PackageModel.TargetBuildSettingDescription.Setting(\" +\n                \"tool: PackageModel.TargetBuildSettingDescription.Tool.linker, \" +\n                \"kind: PackageModel.TargetBuildSettingDescription.Kind.linkedFramework(\\\"AVFoundation\\\"), \" +\n                \"condition: nil)].\")\n        }\n    }\n\n    func testBinaryTargetRequiresPathOrUrl() async throws {\n        let content = \"\"\"\n        import PackageDescription\n        var fwBinaryTarget = Target.binaryTarget(\n            name: \"nickel\",\n            url: \"https://example.com/foo.git\",\n            checksum: \"bee\"\n        )\n        fwBinaryTarget.url = nil\n        let package = Package(name: \"foo\", targets: [fwBinaryTarget])\n        \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(\n            try await loadAndValidateManifest(\n                content, observabilityScope: observability.topScope\n            ), \"expected error\"\n        ) { error in\n            XCTAssertEqual(\n                error.localizedDescription,\n                \"binary target 'nickel' must define either path or URL for its artifacts\"\n            )\n        }\n    }\n\n    func testBinaryTargetsValidation() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"FooLibrary\", type: .static, targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(name: \"Foo\", path: \"Foo.xcframework\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"invalid type for binary product 'FooLibrary'; products referencing only binary targets must be executable or automatic library products\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"FooLibrary\", type: .static, targets: [\"Foo\", \"Bar\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(name: \"Foo\", path: \"Foo.xcframework\"),\n                        .target(name: \"Bar\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(name: \"Foo\", path: \" \"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"invalid local path ' ' for binary target 'Foo', path expected to be relative to package root.\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(name: \"Foo\", url: \"http://foo.com/foo.zip\", checksum: \"checksum\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"invalid URL scheme for binary target 'Foo'; valid schemes are: 'https'\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(name: \"Foo\", path: \"../Foo\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"unsupported extension for binary target 'Foo'; valid extensions are: 'artifactbundle', 'xcframework', 'zip'\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(\n                            name: \"Foo\",\n                            url: \"https://foo.com/foo-1\",\n                            checksum: \"839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"unsupported extension for binary target 'Foo'; valid extensions are: 'artifactbundleindex', 'zip'\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(name: \"Foo\", path: \"../Foo.a\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"unsupported extension for binary target 'Foo'; valid extensions are: 'artifactbundle', 'xcframework', 'zip'\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(\n                            name: \"Foo\",\n                            url: \"https://foo.com/foo-1.0.0.xcframework\",\n                            checksum: \"839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"unsupported extension for binary target 'Foo'; valid extensions are: 'artifactbundleindex', 'zip'\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(\n                            name: \"Foo\",\n                            url: \"ssh://foo/bar\",\n                            checksum: \"839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"invalid URL scheme for binary target 'Foo'; valid schemes are: 'https'\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(\n                            name: \"Foo\",\n                            url: \" \",\n                            checksum: \"839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A\"),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"invalid URL ' ' for binary target 'Foo'\", severity: .error)\n            }\n        }\n\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    products: [\n                        .library(name: \"Foo\", targets: [\"Foo\"]),\n                    ],\n                    targets: [\n                        .binaryTarget(\n                            name: \"Foo\",\n                            path: \"/tmp/foo/bar\")\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.check(diagnostic: \"invalid local path '/tmp/foo/bar' for binary target 'Foo', path expected to be relative to package root.\", severity: .error)\n            }\n        }\n    }\n\n    func testConditionalTargetDependencies() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                dependencies: [\n                    .package(path: \"/Baz\"),\n                ],\n                targets: [\n                    .target(name: \"Foo\", dependencies: [\n                        .target(name: \"Biz\"),\n                        .target(name: \"Bar\", condition: .when(platforms: [.linux])),\n                        .product(name: \"Baz\", package: \"Baz\", condition: .when(platforms: [.macOS])),\n                        .byName(name: \"Bar\", condition: .when(platforms: [.watchOS, .iOS])),\n                    ]),\n                    .target(name: \"Bar\"),\n                    .target(name: \"Biz\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let dependencies = manifest.targets[0].dependencies\n        XCTAssertEqual(dependencies[0], .target(name: \"Biz\"))\n        XCTAssertEqual(dependencies[1], .target(name: \"Bar\", condition: .init(platformNames: [\"linux\"], config: nil)))\n        XCTAssertEqual(dependencies[2], .product(name: \"Baz\", package: \"Baz\", condition: .init(platformNames: [\"macos\"])))\n        XCTAssertEqual(dependencies[3], .byName(name: \"Bar\", condition: .init(platformNames: [\"watchos\", \"ios\"])))\n    }\n\n    func testDefaultLocalization() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                defaultLocalization: \"fr\",\n                targets: [\n                    .target(name: \"Foo\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n        XCTAssertEqual(manifest.defaultLocalization, \"fr\")\n    }\n\n    func testTargetPathsValidation() async throws {\n        let manifestItemToDiagnosticMap = [\n            \"sources: [\\\"/foo.swift\\\"]\": \"invalid relative path '/foo.swift\",\n            \"resources: [.copy(\\\"/foo.txt\\\")]\": \"invalid relative path '/foo.txt'\",\n            \"exclude: [\\\"/foo.md\\\"]\": \"invalid relative path '/foo.md\",\n        ]\n\n        for (manifestItem, expectedDiag) in manifestItemToDiagnosticMap {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    targets: [\n                        .target(\n                            name: \"Foo\",\n                            \\(manifestItem)\n                        ),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n                if let error = error as? PathValidationError {\n                    XCTAssertMatch(error.description, .contains(expectedDiag))\n                } else {\n                    XCTFail(\"unexpected error: \\(error)\")\n                }\n            }\n        }\n    }\n\n    func testNonZeroExitStatusDoesNotAssert() async throws {\n        let content = \"\"\"\n            print(\"crash\")\n            exit(1)\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            XCTAssertNotNil(error as? ManifestParseError)\n        }\n    }\n\n    func testManifestLoadingIsSandboxed() async throws {\n        #if !os(macOS)\n        // Sandboxing is only done on macOS today.\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let content = \"\"\"\n            import Foundation\n\n            try! \"should not be allowed\".write(to: URL(fileURLWithPath: \"/tmp/file.txt\"), atomically: true, encoding: String.Encoding.utf8)\n\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                targets: [\n                    .target(name: \"Foo\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                XCTAssertTrue(error.contains(\"Operation not permitted\"), \"unexpected error message: \\(error)\")\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_5_4_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nclass PackageDescription5_4LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v5_4\n    }\n\n    func testExecutableTargets() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .executableTarget(\n                       name: \"Foo\"\n                    ),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.targets[0].type, .executable)\n    }\n\n    func testPluginsAreUnavailable() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .plugin(\n                       name: \"Foo\",\n                       capability: .buildTool()\n                   ),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                XCTAssertMatch(message, .contains(\"is unavailable\"))\n                XCTAssertMatch(message, .contains(\"was introduced in PackageDescription 5.5\"))\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_5_5_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nclass PackageDescription5_5LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v5_5\n    }\n\n    func testPackageDependencies() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               dependencies: [\n                   .package(url: \"/foo5\", branch: \"main\"),\n                   .package(url: \"/foo7\", revision: \"58e9de4e7b79e67c72a46e164158e3542e570ab6\"),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n        XCTAssertEqual(deps[\"foo5\"], .localSourceControl(path: \"/foo5\", requirement: .branch(\"main\")))\n        XCTAssertEqual(deps[\"foo7\"], .localSourceControl(path: \"/foo7\", requirement: .revision(\"58e9de4e7b79e67c72a46e164158e3542e570ab6\")))\n    }\n\n    func testPlatforms() async throws {\n        let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               platforms: [\n                   .macOS(.v12), .iOS(.v15),\n                   .tvOS(.v15), .watchOS(.v8),\n                   .macCatalyst(.v15), .driverKit(.v21),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.platforms, [\n            PlatformDescription(name: \"macos\", version: \"12.0\"),\n            PlatformDescription(name: \"ios\", version: \"15.0\"),\n            PlatformDescription(name: \"tvos\", version: \"15.0\"),\n            PlatformDescription(name: \"watchos\", version: \"8.0\"),\n            PlatformDescription(name: \"maccatalyst\", version: \"15.0\"),\n            PlatformDescription(name: \"driverkit\", version: \"21.0\"),\n        ])\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_5_6_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageDescription5_6LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v5_6\n    }\n\n    func testSourceControlDependencies() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"MyPackage\",\n               dependencies: [\n                    // from\n                   .package(name: \"foo1\", url: \"http://localhost/foo1\", from: \"1.1.1\"),\n                   .package(url: \"http://localhost/foo2\", from: \"1.1.1\"),\n                    // upToNextMajor\n                   .package(name: \"bar1\", url: \"http://localhost/bar1\", .upToNextMajor(from: \"1.1.1\")),\n                   .package(url: \"http://localhost/bar2\", .upToNextMajor(from: \"1.1.1\")),\n                    // upToNextMinor\n                   .package(name: \"baz1\", url: \"http://localhost/baz1\", .upToNextMinor(from: \"1.1.1\")),\n                   .package(url: \"http://localhost/baz2\", .upToNextMinor(from: \"1.1.1\")),\n                    // exact\n                   .package(name: \"qux1\", url: \"http://localhost/qux1\", .exact(\"1.1.1\")),\n                   .package(url: \"http://localhost/qux2\", .exact(\"1.1.1\")),\n                   .package(url: \"http://localhost/qux3\", exact: \"1.1.1\"),\n                    // branch\n                   .package(name: \"quux1\", url: \"http://localhost/quux1\", .branch(\"main\")),\n                   .package(url: \"http://localhost/quux2\", .branch(\"main\")),\n                   .package(url: \"http://localhost/quux3\", branch: \"main\"),\n                    // revision\n                   .package(name: \"quuz1\", url: \"http://localhost/quuz1\", .revision(\"abcdefg\")),\n                   .package(url: \"http://localhost/quuz2\", .revision(\"abcdefg\")),\n                   .package(url: \"http://localhost/quuz3\", revision: \"abcdefg\"),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertFalse(observability.diagnostics.hasErrors)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n        XCTAssertEqual(deps[\"foo1\"], .remoteSourceControl(identity: .plain(\"foo1\"), deprecatedName: \"foo1\", url: \"http://localhost/foo1\", requirement: .range(\"1.1.1\" ..< \"2.0.0\")))\n        XCTAssertEqual(deps[\"foo2\"], .remoteSourceControl(identity: .plain(\"foo2\"), url: \"http://localhost/foo2\", requirement: .range(\"1.1.1\" ..< \"2.0.0\")))\n        XCTAssertEqual(deps[\"bar1\"], .remoteSourceControl(identity: .plain(\"bar1\"), deprecatedName: \"bar1\", url: \"http://localhost/bar1\", requirement: .range(\"1.1.1\" ..< \"2.0.0\")))\n        XCTAssertEqual(deps[\"bar2\"], .remoteSourceControl(identity: .plain(\"bar2\"), url: \"http://localhost/bar2\", requirement: .range(\"1.1.1\" ..< \"2.0.0\")))\n        XCTAssertEqual(deps[\"baz1\"], .remoteSourceControl(identity: .plain(\"baz1\"), deprecatedName: \"baz1\", url: \"http://localhost/baz1\", requirement: .range(\"1.1.1\" ..< \"1.2.0\")))\n        XCTAssertEqual(deps[\"baz2\"], .remoteSourceControl(identity: .plain(\"baz2\"), url: \"http://localhost/baz2\", requirement: .range(\"1.1.1\" ..< \"1.2.0\")))\n        XCTAssertEqual(deps[\"qux1\"], .remoteSourceControl(identity: .plain(\"qux1\"), deprecatedName: \"qux1\", url: \"http://localhost/qux1\", requirement: .exact(\"1.1.1\")))\n        XCTAssertEqual(deps[\"qux2\"], .remoteSourceControl(identity: .plain(\"qux2\"), url: \"http://localhost/qux2\", requirement: .exact(\"1.1.1\")))\n        XCTAssertEqual(deps[\"qux3\"], .remoteSourceControl(identity: .plain(\"qux3\"), url: \"http://localhost/qux3\", requirement: .exact(\"1.1.1\")))\n        XCTAssertEqual(deps[\"quux1\"], .remoteSourceControl(identity: .plain(\"quux1\"), deprecatedName: \"quux1\", url: \"http://localhost/quux1\", requirement: .branch(\"main\")))\n        XCTAssertEqual(deps[\"quux2\"], .remoteSourceControl(identity: .plain(\"quux2\"), url: \"http://localhost/quux2\", requirement: .branch(\"main\")))\n        XCTAssertEqual(deps[\"quux3\"], .remoteSourceControl(identity: .plain(\"quux3\"), url: \"http://localhost/quux3\", requirement: .branch(\"main\")))\n        XCTAssertEqual(deps[\"quuz1\"], .remoteSourceControl(identity: .plain(\"quuz1\"), deprecatedName: \"quuz1\", url: \"http://localhost/quuz1\", requirement: .revision(\"abcdefg\")))\n        XCTAssertEqual(deps[\"quuz2\"], .remoteSourceControl(identity: .plain(\"quuz2\"), url: \"http://localhost/quuz2\", requirement: .revision(\"abcdefg\")))\n        XCTAssertEqual(deps[\"quuz3\"], .remoteSourceControl(identity: .plain(\"quuz3\"), url: \"http://localhost/quuz3\", requirement: .revision(\"abcdefg\")))\n    }\n\n    func testBuildToolPluginTarget() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .plugin(\n                       name: \"Foo\",\n                       capability: .buildTool()\n                    )\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.targets[0].type, .plugin)\n        XCTAssertEqual(manifest.targets[0].pluginCapability, .buildTool)\n    }\n\n    func testPluginTargetRequiresPluginCapability() async throws {\n        let content = \"\"\"\n        import PackageDescription\n        var fwPluginTarget = Target.plugin(\n            name: \"quarter\",\n            capability: .buildTool\n        )\n        fwPluginTarget.pluginCapability = nil\n        let package = Package(name: \"foo\", targets: [fwPluginTarget])\n        \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(\n            try await loadAndValidateManifest(\n                content, observabilityScope: observability.topScope\n            ), \"expected error\"\n        ) { error in\n            XCTAssertEqual(\n                error.localizedDescription,\n                \"plugin target 'quarter' must define a plugin capability\"\n            )\n        }\n    }\n\n    func testPluginTargetCustomization() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .plugin(\n                       name: \"Foo\",\n                       capability: .buildTool(),\n                       path: \"Sources/Foo\",\n                       exclude: [\"IAmOut.swift\"],\n                       sources: [\"CountMeIn.swift\"]\n                    )\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.targets[0].type, .plugin)\n        XCTAssertEqual(manifest.targets[0].pluginCapability, .buildTool)\n        XCTAssertEqual(manifest.targets[0].path, \"Sources/Foo\")\n        XCTAssertEqual(manifest.targets[0].exclude, [\"IAmOut.swift\"])\n        XCTAssertEqual(manifest.targets[0].sources, [\"CountMeIn.swift\"])\n    }\n\n    func testCustomPlatforms() async throws {\n        // One custom platform.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [\n                       .custom(\"customos\", versionString: \"1.0\"),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            XCTAssertEqual(manifest.platforms, [\n                PlatformDescription(name: \"customos\", version: \"1.0\"),\n            ])\n        }\n\n        // Two custom platforms.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [\n                       .custom(\"customos\", versionString: \"1.0\"),\n                       .custom(\"anothercustomos\", versionString: \"2.3\"),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(validationDiagnostics)\n\n            XCTAssertEqual(manifest.platforms, [\n                PlatformDescription(name: \"customos\", version: \"1.0\"),\n                PlatformDescription(name: \"anothercustomos\", version: \"2.3\"),\n            ])\n        }\n\n        // Invalid custom platform version.\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                   name: \"Foo\",\n                   platforms: [\n                       .custom(\"customos\", versionString: \"xx\"),\n                   ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            do {\n                _  = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n                XCTFail(\"manifest loading unexpectedly did not throw an error\")\n            } catch ManifestParseError.runtimeManifestErrors(let errors) {\n                XCTAssertEqual(errors, [\"invalid custom platform version xx; xx should be a positive integer\"])\n            }\n        }\n    }\n\n    /// Tests use of Context.current.packageDirectory\n    func testPackageContextName() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(name: Context.packageDirectory)\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertNotNil(parsedManifest)\n        XCTAssertNotNil(parsedManifest.parentDirectory)\n        let name = try XCTUnwrap(parsedManifest.parentDirectory).pathString\n        XCTAssertEqual(manifest.displayName, name)\n    }\n\n    /// Tests access to the package's directory contents.\n    func testPackageContextDirectory() async throws {\n        try XCTSkipOnWindows(because: \"Skipping since this tests does not fully work without the VFS overlay which is currently disabled on Windows\")\n\n        let content = \"\"\"\n            import PackageDescription\n            import Foundation\n\n            let fileManager = FileManager.default\n            let contents = (try? fileManager.contentsOfDirectory(atPath: Context.packageDirectory)) ?? []\n\n            let package = Package(name: contents.joined(separator: \",\"))\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        // FIXME: temporary filter a diagnostic that shows up on macOS 14.0\n        XCTAssertNoDiagnostics(observability.diagnostics.filter { !$0.message.contains(\"coreservicesd\") })\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let files = manifest.displayName.split(separator: \",\").map(String.init)\n        // Since we're loading `/Package.swift` in these tests, the context's package directory is supposed to be /.\n        let expectedFiles = try FileManager.default.contentsOfDirectory(atPath: \"/\")\n        XCTAssertEqual(files, expectedFiles)\n    }\n\n    func testCommandPluginTarget() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               targets: [\n                   .plugin(\n                       name: \"Foo\",\n                       capability: .command(\n                           intent: .custom(verb: \"mycmd\", description: \"helpful description of mycmd\"),\n                           permissions: [ .writeToPackageDirectory(reason: \"YOLO\") ]\n                       )\n                   )\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.targets[0].type, .plugin)\n        XCTAssertEqual(manifest.targets[0].pluginCapability, .command(intent: .custom(verb: \"mycmd\", description: \"helpful description of mycmd\"), permissions: [.writeToPackageDirectory(reason: \"YOLO\")]))\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_5_7_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageDescription5_7LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v5_7\n    }\n\n    func testImplicitFoundationImportWorks() async throws {\n        let content = \"\"\"\n            import PackageDescription\n\n            _ = FileManager.default\n\n            let package = Package(name: \"MyPackage\")\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n        XCTAssertEqual(manifest.displayName, \"MyPackage\")\n    }\n\n    func testRegistryDependencies() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"MyPackage\",\n               dependencies: [\n                   .package(id: \"x.foo\", from: \"1.1.1\"),\n                   .package(id: \"x.bar\", exact: \"1.1.1\"),\n                   .package(id: \"x.baz\", .upToNextMajor(from: \"1.1.1\")),\n                   .package(id: \"x.qux\", .upToNextMinor(from: \"1.1.1\")),\n                   .package(id: \"x.quux\", \"1.1.1\" ..< \"3.0.0\"),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n        XCTAssertEqual(deps[\"x.foo\"], .registry(identity: \"x.foo\", requirement: .range(\"1.1.1\" ..< \"2.0.0\")))\n        XCTAssertEqual(deps[\"x.bar\"], .registry(identity: \"x.bar\", requirement: .exact(\"1.1.1\")))\n        XCTAssertEqual(deps[\"x.baz\"], .registry(identity: \"x.baz\", requirement: .range(\"1.1.1\" ..< \"2.0.0\")))\n        XCTAssertEqual(deps[\"x.qux\"], .registry(identity: \"x.qux\", requirement: .range(\"1.1.1\" ..< \"1.2.0\")))\n        XCTAssertEqual(deps[\"x.quux\"], .registry(identity: \"x.quux\", requirement: .range(\"1.1.1\" ..< \"3.0.0\")))\n    }\n\n    func testConditionalTargetDependencies() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                dependencies: [],\n                targets: [\n                    .target(name: \"Foo\", dependencies: [\n                        .target(name: \"Bar\", condition: .when(platforms: [])),\n                        .target(name: \"Baz\", condition: .when(platforms: [.linux])),\n                    ]),\n                    .target(name: \"Bar\"),\n                    .target(name: \"Baz\"),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        let dependencies = manifest.targets[0].dependencies\n        XCTAssertEqual(dependencies[0], .target(name: \"Bar\", condition: .none))\n        XCTAssertEqual(dependencies[1], .target(name: \"Baz\", condition: .init(platformNames: [\"linux\"], config: .none)))\n    }\n\n    func testConditionalTargetDependenciesDeprecation() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                dependencies: [],\n                targets: [\n                    .target(name: \"Foo\", dependencies: [\n                        .target(name: \"Bar\", condition: .when(platforms: nil))\n                    ]),\n                    .target(name: \"Bar\")\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") { error in\n            if case ManifestParseError.invalidManifestFormat(let error, _, _) = error {\n                XCTAssertMatch(error, .contains(\"when(platforms:)' was obsoleted\"))\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testTargetDeprecatedDependencyCase() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                dependencies: [\n                   .package(url: \"http://localhost/BarPkg\", from: \"1.1.1\"),\n                ],\n                targets: [\n                    .target(name: \"Foo\",\n                            dependencies: [\n                                .productItem(name: \"Bar\", package: \"BarPkg\", condition: nil),\n                            ]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope)) { error in\n            if case ManifestParseError.invalidManifestFormat(let message, _, _) = error {\n                XCTAssertMatch(message, .contains(\"error: 'productItem(name:package:condition:)' is unavailable: use .product(name:package:condition) instead.\"))\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testPlatforms() async throws {\n        let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               platforms: [\n                   .macOS(.v13), .iOS(.v16),\n                   .tvOS(.v16), .watchOS(.v9),\n                   .macCatalyst(.v16), .driverKit(.v22),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.platforms, [\n            PlatformDescription(name: \"macos\", version: \"13.0\"),\n            PlatformDescription(name: \"ios\", version: \"16.0\"),\n            PlatformDescription(name: \"tvos\", version: \"16.0\"),\n            PlatformDescription(name: \"watchos\", version: \"9.0\"),\n            PlatformDescription(name: \"maccatalyst\", version: \"16.0\"),\n            PlatformDescription(name: \"driverkit\", version: \"22.0\"),\n        ])\n    }\n\n    func testImportRestrictions() async throws {\n        let content =  \"\"\"\n            import PackageDescription\n            import BestModule\n            let package = Package(name: \"Foo\")\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let manifestLoader = ManifestLoader(toolchain: try UserToolchain.default, importRestrictions: (.v5_7, []))\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, customManifestLoader: manifestLoader, observabilityScope: observability.topScope)) { error in\n            if case ManifestParseError.importsRestrictedModules(let modules) = error {\n                XCTAssertEqual(modules.sorted(), [\"BestModule\", \"Foundation\"])\n            } else {\n                XCTFail(\"unexpected error: \\(error)\")\n            }\n        }\n    }\n\n    func testTargetDependencyProductInvalidPackage() async throws {\n        do {\n            let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Trivial\",\n                    products: [],\n                    dependencies: [\n                        .package(id: \"org.foo\", from: \"1.0.0\"),\n                        .package(id: \"org.bar\", from: \"1.0.0\"),\n                    ],\n                    targets: [\n                        .target(\n                            name: \"Target1\",\n                            dependencies: [.product(name: \"product\", package: \"org.baz\")]),\n                        .target(\n                            name: \"Target2\",\n                            dependencies: [\"foos\"]),\n                    ]\n                )\n                \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            testDiagnostics(validationDiagnostics) { result in\n                result.checkUnordered(diagnostic: \"unknown package 'org.baz' in dependencies of target 'Target1'; valid packages are: 'org.foo', 'org.bar'\", severity: .error)\n                result.checkUnordered(diagnostic: \"unknown dependency 'foos' in target 'Target2'; valid dependencies are: 'org.foo', 'org.bar'\", severity: .error)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_5_9_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageDescription5_9LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v5_9\n    }\n\n    func testPlatforms() async throws {\n        let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n               name: \"Foo\",\n               platforms: [\n                   .macOS(.v14), .iOS(.v17),\n                   .tvOS(.v17), .watchOS(.v10), .visionOS(.v1),\n                   .macCatalyst(.v17), .driverKit(.v23),\n               ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.platforms, [\n            PlatformDescription(name: \"macos\", version: \"14.0\"),\n            PlatformDescription(name: \"ios\", version: \"17.0\"),\n            PlatformDescription(name: \"tvos\", version: \"17.0\"),\n            PlatformDescription(name: \"watchos\", version: \"10.0\"),\n            PlatformDescription(name: \"visionos\", version: \"1.0\"),\n            PlatformDescription(name: \"maccatalyst\", version: \"17.0\"),\n            PlatformDescription(name: \"driverkit\", version: \"23.0\"),\n        ])\n    }\n\n    func testMacroTargets() async throws {\n        let content = \"\"\"\n            import CompilerPluginSupport\n            import PackageDescription\n\n            let package = Package(name: \"MyPackage\",\n                targets: [\n                    .macro(name: \"MyMacro\", swiftSettings: [.define(\"BEST\")], linkerSettings: [.linkedLibrary(\"best\")]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (_, diagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertEqual(diagnostics.count, 0, \"unexpected diagnostics: \\(diagnostics)\")\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_6_0_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageDescription6_0LoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v6_0\n    }\n\n    func testPackageContextGitStatus() async throws {\n        let content = \"\"\"\n                import PackageDescription\n                let package = Package(name: \"\\\\(Context.gitInformation?.hasUncommittedChanges == true)\")\n                \"\"\"\n\n        try await loadRootManifestWithBasicGitRepository(manifestContent: content) { manifest, observability in\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(manifest.displayName, \"true\")\n        }\n    }\n\n    func testPackageContextGitTag() async throws {\n        let content = \"\"\"\n                import PackageDescription\n                let package = Package(name: \"\\\\(Context.gitInformation?.currentTag ?? \"\")\")\n                \"\"\"\n\n        try await loadRootManifestWithBasicGitRepository(manifestContent: content) { manifest, observability in\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(manifest.displayName, \"lunch\")\n        }\n    }\n\n    func testPackageContextGitCommit() async throws {\n        let content = \"\"\"\n                import PackageDescription\n                let package = Package(name: \"\\\\(Context.gitInformation?.currentCommit ?? \"\")\")\n                \"\"\"\n\n        try await loadRootManifestWithBasicGitRepository(manifestContent: content) { manifest, observability in\n            XCTAssertNoDiagnostics(observability.diagnostics)\n\n            let repo = GitRepository(path: manifest.path.parentDirectory)\n            let currentRevision = try repo.getCurrentRevision()\n            XCTAssertEqual(manifest.displayName, currentRevision.identifier)\n        }\n    }\n\n    func testSwiftLanguageModesPerTarget() async throws {\n        let content = \"\"\"\n                import PackageDescription\n                let package = Package(\n                    name: \"Foo\",\n                    defaultLocalization: \"fr\",\n                    products: [],\n                    targets: [\n                        .target(\n                            name: \"Foo\",\n                            swiftSettings: [\n                                .swiftLanguageMode(.v5)\n                            ]\n                        ),\n                        .target(\n                            name: \"Bar\",\n                            swiftSettings: [\n                                .swiftLanguageVersion(.v6)\n                            ]\n                        )\n                    ]\n                )\n                \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n        testDiagnostics(observability.diagnostics) { result in\n            result.checkUnordered(diagnostic: .contains(\"'swiftLanguageVersion' is deprecated: renamed to 'swiftLanguageMode(_:_:)'\"), severity: .warning)\n        }\n    }\n\n    private func loadRootManifestWithBasicGitRepository(\n        manifestContent: String, \n        validator: (Manifest, TestingObservability) throws -> ()\n    ) async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await testWithTemporaryDirectory { tmpdir in\n            let manifestPath = tmpdir.appending(component: Manifest.filename)\n            try localFileSystem.writeFileContents(manifestPath, string: manifestContent)\n            try localFileSystem.writeFileContents(tmpdir.appending(\"best.txt\"), string: \"best\")\n\n            let repo = GitRepository(path: tmpdir)\n            try repo.create()\n            try repo.stage(file: manifestPath.pathString)\n            try repo.commit(message: \"best\")\n            try repo.tag(name: \"lunch\")\n\n            let manifest = try await manifestLoader.load(\n                manifestPath: manifestPath,\n                packageKind: .root(tmpdir),\n                toolsVersion: self.toolsVersion,\n                fileSystem: localFileSystem,\n                observabilityScope: observability.topScope\n            )\n\n            try validator(manifest, observability)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_6_2_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport Testing\n\nstruct PackageDescription6_2LoadingTests {\n    @Test(\n        .tags(\n            Tag.Feature.TargetSettings\n        )\n    )\n    func warningControlFlags() async throws {\n        let content = \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                products: [],\n                targets: [\n                    .target(\n                        name: \"Foo\",\n                        cSettings: [\n                            .enableWarning(\"implicit-fallthrough\"),\n                            .disableWarning(\"unused-parameter\"),\n                            .treatAllWarnings(as: .error),\n                            .treatWarning(\"deprecated-declarations\", as: .warning),\n                        ],\n                        cxxSettings: [\n                            .enableWarning(\"implicit-fallthrough\"),\n                            .disableWarning(\"unused-parameter\"),\n                            .treatAllWarnings(as: .warning),\n                            .treatWarning(\"deprecated-declarations\", as: .error),\n                        ],\n                        swiftSettings: [\n                            .treatAllWarnings(as: .error),\n                            .treatWarning(\"DeprecatedDeclaration\", as: .warning),\n                        ]\n                    ),\n                    .target(\n                        name: \"Bar\",\n                        cSettings: [\n                            .enableWarning(\"implicit-fallthrough\"),\n                            .disableWarning(\"unused-parameter\"),\n                            .treatAllWarnings(as: .warning),\n                            .treatWarning(\"deprecated-declarations\", as: .error),\n                        ],\n                        cxxSettings: [\n                            .enableWarning(\"implicit-fallthrough\"),\n                            .disableWarning(\"unused-parameter\"),\n                            .treatAllWarnings(as: .error),\n                            .treatWarning(\"deprecated-declarations\", as: .warning),\n                        ],\n                        swiftSettings: [\n                            .treatAllWarnings(as: .warning),\n                            .treatWarning(\"DeprecatedDeclaration\", as: .error),\n                        ]\n                    )\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        try await withKnownIssue(\"https://github.com/swiftlang/swift-package-manager/issues/8543: there are compilation errors on Windows\", isIntermittent: true) {\n            let (_, validationDiagnostics) = try await PackageDescriptionLoadingTests\n                .loadAndValidateManifest(\n                    content,\n                    toolsVersion: .v6_2,\n                    packageKind: .fileSystem(.root),\n                    manifestLoader: ManifestLoader(\n                        toolchain: try! UserToolchain.default\n                    ),\n                    observabilityScope: observability.topScope\n                )\n            try expectDiagnostics(validationDiagnostics) { results in\n                results.checkIsEmpty()\n            }\n            try expectDiagnostics(observability.diagnostics) { results in\n                results.checkIsEmpty()\n            }\n        } when: {\n            isWindows && !CiEnvironment.runningInSmokeTestPipeline\n        }\n    }\n}\n\nprivate var isWindows: Bool {\n#if os(Windows)\n    true\n#else\n    false\n#endif\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PD_Next_LoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nfinal class PackageDescriptionNextLoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .vNext\n    }\n\n    func testImplicitFoundationImportFails() async throws {\n        let content = \"\"\"\n            import PackageDescription\n\n            _ = FileManager.default\n\n            let package = Package(name: \"MyPackage\")\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        await XCTAssertAsyncThrowsError(try await loadAndValidateManifest(content, observabilityScope: observability.topScope), \"expected error\") {\n            if case ManifestParseError.invalidManifestFormat(let error, _, _) = $0 {\n                XCTAssertMatch(error, .contains(\"cannot find 'FileManager' in scope\"))\n            } else {\n                XCTFail(\"unexpected error: \\($0)\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PackageBuilderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\nimport Basics\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport Testing\n\n/// Tests for the handling of source layout conventions.\n@Suite(\n    .tags(\n        .TestSize.medium\n    )\n)\nstruct PackageBuilderTests {\n    @Test\n    func testDotFilesAreIgnored() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo/.Bar.swift\",\n            \"/Sources/foo/Foo.swift\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            path: .root,\n            targets: [\n                try TargetDescription(name: \"foo\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { module in\n                module.check(c99name: \"foo\", type: .library)\n                module.checkSources(root: \"/Sources/foo\", paths: \"Foo.swift\")\n            }\n        }\n    }\n\n    @Test\n    func testXCPrivacyIgnored() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo/PrivacyInfo.xcprivacy\",\n            \"/Sources/foo/Foo.swift\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            path: .root,\n            targets: [\n                try TargetDescription(name: \"foo\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { module in\n                module.check(c99name: \"foo\", type: .library)\n                module.checkSources(root: \"/Sources/foo\", paths: \"Foo.swift\")\n                module.checkResources(resources: [])\n            }\n        }\n    }\n\n    @Test\n    func testMixedSources() throws {\n        let foo: AbsolutePath = \"/Sources/foo\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            foo.appending(components: \"main.swift\").pathString,\n            foo.appending(components: \"main.c\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            path: .root,\n            targets: [\n                try TargetDescription(name: \"foo\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n            diagnostics.check(diagnostic: \"target at '\\(foo)' contains mixed language source files; feature not supported\", severity: .error)\n        }\n    }\n\n    @Test\n    func testBrokenSymlink() throws {\n        try testWithTemporaryDirectory { path in\n            let fs = localFileSystem\n\n            let sources = path.appending(components: \"Sources\", \"foo\")\n            try fs.createDirectory(sources, recursive: true)\n            try fs.writeFileContents(sources.appending(components: \"foo.swift\"), bytes: \"\")\n\n            // Create a stray symlink in sources.\n            let linkDestPath = path.appending(components: \"link.swift\")\n            let linkPath = sources.appending(components: \"link.swift\")\n            try fs.writeFileContents(linkDestPath, bytes: \"\")\n            try fs.createSymbolicLink(linkPath, pointingAt: linkDestPath, relative: false)\n            try fs.removeFileTree(linkDestPath)\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                path: path,\n                targets: [\n                    try TargetDescription(name: \"foo\"),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, path: path, in: fs) { package, diagnostics in\n                diagnostics.check(\n                    diagnostic: \"ignoring broken symlink \\(linkPath)\",\n                    severity: .warning\n                )\n                try package.checkModule(\"foo\")\n            }\n        }\n    }\n\n    @Test\n    func testSymlinkedSourcesDirectory() throws {\n        try testWithTemporaryDirectory { path in\n            let fs = localFileSystem\n\n            let sources = path.appending(components: \"Sources\")\n            let foo = sources.appending(components: \"foo\")\n            let bar = sources.appending(components: \"bar\")\n            try fs.createDirectory(foo, recursive: true)\n            try fs.writeFileContents(foo.appending(components: \"foo.swift\"), bytes: \"\")\n\n            // Create a symlink to foo.\n            try fs.createSymbolicLink(bar, pointingAt: foo, relative: false)\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"bar\"),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, path: path, in: fs) { package, _ in\n                try package.checkModule(\"bar\")\n            }\n        }\n    }\n\n    @Test\n    func testCInTests() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/MyPackage/main.swift\",\n            \"/Tests/MyPackageTests/abc.c\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"MyPackage\",\n            targets: [\n                try TargetDescription(name: \"MyPackage\"),\n                try TargetDescription(name: \"MyPackageTests\", dependencies: [\"MyPackage\"], type: .test),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"MyPackage\") { module in\n                module.check(type: .executable)\n                module.checkSources(root: \"/Sources/MyPackage\", paths: \"main.swift\")\n            }\n\n            try package.checkModule(\"MyPackageTests\") { module in\n                module.check(type: .test)\n                module.checkSources(root: \"/Tests/MyPackageTests\", paths: \"abc.c\")\n            }\n\n            package.checkProduct(\"MyPackage\") { _ in }\n\n            #if os(Linux)\n            diagnostics.check(\n                diagnostic: \"ignoring target 'MyPackageTests' in package '\\(package.packageIdentity)'; C language in tests is not yet supported\",\n                severity: .warning\n            )\n            #elseif os(macOS) || os(Android) || os(Windows)\n            package.checkProduct(\"MyPackagePackageTests\") { _ in }\n            #endif\n        }\n    }\n\n    @Test\n    func testValidSources() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/pkg/main.swift\",\n            \"/Sources/pkg/noExtension\",\n            \"/Sources/pkg/Package.swift\",\n            \"/.git/anchor\",\n            \"/.xcodeproj/anchor\",\n            \"/.playground/anchor\",\n            \"/Package.swift\",\n            \"/Packages/MyPackage/main.c\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(name: \"pkg\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"pkg\") { module in\n                module.check(type: .executable)\n                module.checkSources(root: \"/Sources/pkg\", paths: \"main.swift\", \"Package.swift\")\n            }\n            package.checkProduct(\"pkg\") { _ in }\n        }\n    }\n\n    @Test\n    func testVersionSpecificManifests() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Package.swift\",\n            \"/Package@swift-999.swift\",\n            \"/Sources/Foo/Package.swift\",\n            \"/Sources/Foo/Package@swift-1.swift\")\n\n        let name = \"Foo\"\n        let manifest = Manifest.createRootManifest(\n            displayName: name,\n            targets: [\n                try TargetDescription(name: name),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(name) { module in\n                module.check(c99name: name, type: .library)\n                module.checkSources(root: \"/Sources/Foo\", paths: \"Package.swift\", \"Package@swift-1.swift\")\n            }\n        }\n    }\n\n    @Test\n    func testModuleMapLayout() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/clib/include/module.modulemap\",\n            \"/Sources/clib/include/clib.h\",\n            \"/Sources/clib/clib.c\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"MyPackage\",\n            targets: [\n                try TargetDescription(name: \"clib\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"clib\") { module in\n                module.check(c99name: \"clib\", type: .library)\n                module.checkSources(root: \"/Sources/clib\", paths: \"clib.c\")\n                module.check(moduleMapType: .custom(\"/Sources/clib/include/module.modulemap\"))\n            }\n        }\n    }\n\n    @Test\n    func testPublicIncludeDirMixedWithSources() throws {\n        let Sources: AbsolutePath = \"/Sources\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            Sources.appending(components: \"clib\", \"nested\", \"nested.h\").pathString,\n            Sources.appending(components: \"clib\", \"nested\", \"nested.c\").pathString,\n            Sources.appending(components: \"clib\", \"clib.h\").pathString,\n            Sources.appending(components: \"clib\", \"clib.c\").pathString,\n            Sources.appending(components: \"clib\", \"clib2.h\").pathString,\n            Sources.appending(components: \"clib\", \"clib2.c\").pathString,\n            \"/done\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"MyPackage\",\n            targets: [\n                try TargetDescription(\n                    name: \"clib\",\n                    path: \"Sources\",\n                    sources: [\"clib\", \"clib\"],\n                    publicHeadersPath: \".\"\n                ),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diags in\n            diags.check(\n                diagnostic: \"found duplicate sources declaration in the package manifest: \\(Sources.appending(components: \"clib\"))\",\n                severity: .warning\n            )\n            try package.checkModule(\"clib\") { module in\n                module.check(c99name: \"clib\", type: .library)\n                module.checkSources(root: Sources.pathString, paths: RelativePath(\"clib\").appending(components: \"clib.c\").pathString, RelativePath(\"clib\").appending(components: \"clib2.c\").pathString, RelativePath(\"clib\").appending(components: \"nested\", \"nested.c\").pathString)\n                module.check(moduleMapType: .umbrellaHeader(Sources.appending(components: \"clib\", \"clib.h\")))\n            }\n        }\n    }\n\n    @Test\n    func testDeclaredSourcesWithDot() throws {\n        let swiftLib: RelativePath = RelativePath(\"swift.lib\")\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/swift.lib/foo.swift\",\n            \"/Sources/swiftlib1/swift.lib/foo.swift\",\n            \"/Sources/swiftlib2/swift.lib/foo.swift\",\n            \"/Sources/swiftlib3/swift.lib/foo.swift\",\n            \"/Sources/swiftlib3/swift.lib/foo.bar/bar.swift\",\n            \"/done\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"MyPackage\",\n            targets: [\n                try TargetDescription(\n                    name: \"swift.lib\"\n                ),\n                try TargetDescription(\n                    name: \"swiftlib1\",\n                    path: \"Sources/swiftlib1\",\n                    sources: [swiftLib.pathString]\n                ),\n                try TargetDescription(\n                    name: \"swiftlib2\",\n                    path: \"Sources/swiftlib2/swift.lib\"\n                ),\n                try TargetDescription(\n                    name: \"swiftlib3\",\n                    path: \"Sources/swiftlib3/swift.lib\"\n                ),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { result, _ in\n            try result.checkModule(\"swift.lib\") { module in\n                module.checkSources(sources: [\"foo.swift\"])\n            }\n            try result.checkModule(\"swiftlib1\") { module in\n                module.checkSources(sources: [swiftLib.appending(components: \"foo.swift\").pathString])\n            }\n            try result.checkModule(\"swiftlib2\") { module in\n                module.checkSources(sources: [\"foo.swift\"])\n            }\n            try result.checkModule(\"swiftlib3\") { module in\n                module.checkSources(sources: [RelativePath(\"foo.bar\").appending(components: \"bar.swift\").pathString, \"foo.swift\"])\n            }\n        }\n    }\n\n    @Test\n    func testOverlappingDeclaredSources() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/clib/subfolder/foo.h\",\n            \"/Sources/clib/subfolder/foo.c\",\n            \"/Sources/clib/bar.h\",\n            \"/Sources/clib/bar.c\",\n            \"/done\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"MyPackage\",\n            targets: [\n                try TargetDescription(\n                    name: \"clib\",\n                    path: \"Sources\",\n                    sources: [\"clib\", \"clib/subfolder\"]\n                ),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { result, _ in\n            try result.checkModule(\"clib\") { module in\n                module.checkSources(sources: [RelativePath(\"clib\").appending(components: \"bar.c\").pathString, RelativePath(\"clib\").appending(components: \"subfolder\", \"foo.c\").pathString])\n            }\n        }\n    }\n\n    @Test\n    func testDeclaredExecutableProducts() throws {\n        // Check that declaring executable product doesn't collide with the\n        // inferred products.\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/exec/main.swift\",\n            \"/Sources/foo/foo.swift\"\n        )\n\n        var manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            products: [\n                try ProductDescription(name: \"exec\", type: .executable, targets: [\"exec\", \"foo\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"foo\"),\n                try TargetDescription(name: \"exec\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { _ in }\n            try package.checkModule(\"exec\") { _ in }\n            package.checkProduct(\"exec\") { product in\n                product.check(type: .executable, targets: [\"exec\", \"foo\"])\n            }\n        }\n\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            products: [],\n            targets: [\n                try TargetDescription(name: \"foo\"),\n                try TargetDescription(name: \"exec\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { _ in }\n            try package.checkModule(\"exec\") { _ in }\n            package.checkProduct(\"exec\") { product in\n                product.check(type: .executable, targets: [\"exec\"])\n            }\n        }\n\n        // If we already have an explicit product, we shouldn't create an\n        // implicit one.\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            products: [\n                try ProductDescription(name: \"exec1\", type: .executable, targets: [\"exec\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"foo\"),\n                try TargetDescription(name: \"exec\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { _ in }\n            try package.checkModule(\"exec\") { _ in }\n            package.checkProduct(\"exec1\") { product in\n                product.check(type: .executable, targets: [\"exec\"])\n            }\n        }\n    }\n\n    @Test\n    func testExecutableTargets() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/exec1/exec.swift\",\n            \"/Sources/exec2/main.swift\",\n            \"/Sources/lib/lib.swift\"\n        )\n\n        // Check that an explicitly declared target without a main source file works.\n        var manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5_5,\n            products: [\n                try ProductDescription(name: \"exec1\", type: .executable, targets: [\"exec1\", \"lib\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"exec1\", type: .executable),\n                try TargetDescription(name: \"lib\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"lib\") { _ in }\n            try package.checkModule(\"exec1\") { _ in }\n            package.checkProduct(\"exec1\") { product in\n                product.check(type: .executable, targets: [\"exec1\", \"lib\"])\n            }\n        }\n\n        // Check that products are inferred for explicitly declared executable targets.\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5_5,\n            products: [],\n            targets: [\n                try TargetDescription(name: \"exec1\", type: .executable),\n                try TargetDescription(name: \"lib\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"lib\") { _ in }\n            try package.checkModule(\"exec1\") { _ in }\n            package.checkProduct(\"exec1\") { product in\n                product.check(type: .executable, targets: [\"exec1\"])\n            }\n        }\n\n        // Check that products are not inferred if there is an explicit executable product.\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5_5,\n            products: [\n                try ProductDescription(name: \"exec1\", type: .executable, targets: [\"exec1\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"lib\"),\n                try TargetDescription(name: \"exec1\", type: .executable),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"lib\") { _ in }\n            try package.checkModule(\"exec1\") { _ in }\n            package.checkProduct(\"exec1\") { product in\n                product.check(type: .executable, targets: [\"exec1\"])\n            }\n        }\n\n        // Check that an explicitly declared target with a main source file still works.\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5_5,\n            products: [\n                try ProductDescription(name: \"exec1\", type: .executable, targets: [\"exec1\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"lib\"),\n                try TargetDescription(name: \"exec1\", type: .executable),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"lib\") { _ in }\n            try package.checkModule(\"exec1\") { _ in }\n            package.checkProduct(\"exec1\") { product in\n                product.check(type: .executable, targets: [\"exec1\"])\n            }\n        }\n\n        // Check that a inferred target with a main source file still works but yields a warning.\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5_5,\n            products: [\n                try ProductDescription(name: \"exec2\", type: .executable, targets: [\"exec2\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"lib\"),\n                try TargetDescription(name: \"exec2\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            diagnostics.check(\n                diagnostic: \"'exec2' was identified as an executable target given the presence of a 'main' file. Starting with tools version 5.4.0 executable targets should be declared as 'executableTarget()'\",\n                severity: .warning\n            )\n            try package.checkModule(\"lib\") { _ in }\n            try package.checkModule(\"exec2\") { _ in }\n            package.checkProduct(\"exec2\") { product in\n                product.check(type: .executable, targets: [\"exec2\"])\n            }\n        }\n    }\n\n    @Test\n    func testTestEntryPointFound() throws {\n        try SwiftModule.testEntryPointNames.forEach { name in\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/swift/exe/foo.swift\",\n                \"/\\(name)\",\n                \"/swift/tests/footests.swift\"\n            )\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"exe\", path: \"swift/exe\"),\n                    try TargetDescription(name: \"tests\", path: \"swift/tests\", type: .test),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, _ in\n                try package.checkModule(\"exe\") { module in\n                    module.check(c99name: \"exe\", type: .library)\n                    module.checkSources(root: \"/swift/exe\", paths: \"foo.swift\")\n                }\n\n                try package.checkModule(\"tests\") { module in\n                    module.check(c99name: \"tests\", type: .test)\n                    module.checkSources(root: \"/swift/tests\", paths: \"footests.swift\")\n                }\n\n                package.checkProduct(\"pkgPackageTests\") { product in\n                    product.check(type: .test, targets: [\"tests\"])\n                    product.check(testEntryPointPath: \"/\\(name)\")\n                }\n            }\n        }\n    }\n\n    @Test(\n        .tags(\n            Tag.Feature.PackageType.Executable,\n            Tag.Feature.PackageType.Library,\n        ),\n    )\n    func testTestManifestSearch() throws {\n        try withKnownIssue(isIntermittent: true) {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/pkg/foo.swift\",\n                \"/pkg/footests.swift\"\n            )\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(\n                        name: \"exe\",\n                        path: \"./\",\n                        sources: [\"foo.swift\"]\n                    ),\n                    try TargetDescription(\n                        name: \"tests\",\n                        path: \"./\",\n                        sources: [\"footests.swift\"],\n                        type: .test\n                    ),\n                ]\n            )\n            try PackageBuilderTester(manifest, path: \"/pkg\", in: fs) { package, _ in\n                try package.checkModule(\"exe\") { _ in }\n                try package.checkModule(\"tests\") { _ in }\n\n                package.checkProduct(\"pkgPackageTests\") { product in\n                    product.check(type: .test, targets: [\"tests\"])\n                    product.check(testEntryPointPath: nil)\n                }\n            }\n        } when: {\n            ProcessInfo.hostOperatingSystem == .windows\n        }\n    }\n\n    @Test\n    func testEmptyProductNameError() throws {\n        let fs = InMemoryFileSystem(emptyFiles: \"/Sources/best/best.swift\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            products: [\n                try ProductDescription(name: \"\", type: .library(.automatic), targets: [\"best\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"best\"),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            diagnostics.check(diagnostic: \"product names can not be empty\", severity: .error)\n        }\n    }\n\n    @Test\n    func testMultipleTestEntryPointsError() throws {\n        let name = SwiftModule.defaultTestEntryPointName\n        let swift: AbsolutePath = \"/swift\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            AbsolutePath.root.appending(components: name).pathString,\n            swift.appending(components: name).pathString,\n            swift.appending(components: \"tests\", \"footests.swift\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(\n                    name: \"tests\",\n                    path: \"swift/tests\",\n                    type: .test\n                ),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            diagnostics.check(diagnostic: \"package '\\(package.packageIdentity)' has multiple test entry point files: \\(try! AbsolutePath(validating: \"/\\(name)\")), \\(swift.appending(components: name))\", severity: .error)\n        }\n    }\n\n    @Test\n    func testCustomTargetPaths() throws {\n        let Sources: AbsolutePath = \"/Sources\"\n        let swift: RelativePath = \"swift\"\n        let bar: AbsolutePath = \"/bar\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/mah/target/exe/swift/exe/main.swift\",\n            \"/mah/target/exe/swift/exe/foo.swift\",\n            \"/mah/target/exe/swift/bar.swift\",\n            \"/mah/target/exe/shouldBeIgnored.swift\",\n            \"/mah/target/exe/foo.c\",\n            Sources.appending(components: \"foo\", \"foo.swift\").pathString,\n            bar.appending(components: \"bar\", \"foo.swift\").pathString,\n            bar.appending(components: \"bar\", \"excluded.swift\").pathString,\n            bar.appending(components: \"bar\", \"fixture\", \"fix1.swift\").pathString,\n            bar.appending(components: \"bar\", \"fixture\", \"fix2.swift\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(\n                    name: \"exe\",\n                    path: \"mah/target/exe\",\n                    sources: [swift.pathString]),\n                try TargetDescription(\n                    name: \"clib\",\n                    path: \"mah/target/exe\",\n                    sources: [\"foo.c\"]),\n                try TargetDescription(\n                    name: \"foo\"),\n                try TargetDescription(\n                    name: \"bar\",\n                    path: \"bar\",\n                    exclude: [\"bar/excluded.swift\", \"bar/fixture\"],\n                    sources: [\"bar\"]),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            package.checkPredefinedPaths(target: Sources, testTarget: \"/Tests\")\n\n            try package.checkModule(\"exe\") { module in\n                module.check(c99name: \"exe\", type: .executable)\n                module.checkSources(root: \"/mah/target/exe\",\n                    paths: swift.appending(components: \"exe\", \"main.swift\").pathString, swift.appending(components: \"exe\", \"foo.swift\").pathString, swift.appending(components: \"bar.swift\").pathString)\n            }\n\n            try package.checkModule(\"clib\") { module in\n                module.check(c99name: \"clib\", type: .library)\n                module.checkSources(root: \"/mah/target/exe\", paths: \"foo.c\")\n            }\n\n            try package.checkModule(\"foo\") { module in\n                module.check(c99name: \"foo\", type: .library)\n                module.checkSources(root: \"/Sources/foo\", paths: \"foo.swift\")\n            }\n\n            try package.checkModule(\"bar\") { module in\n                module.check(c99name: \"bar\", type: .library)\n                module.checkSources(root: bar.pathString, paths: RelativePath(\"bar\").appending(components: \"foo.swift\").pathString)\n            }\n\n            package.checkProduct(\"exe\") { _ in }\n        }\n    }\n\n    @Test\n    func testCustomTargetPathsOverlap() throws {\n        let bar: AbsolutePath = \"/target/bar\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            bar.appending(components: \"bar.swift\").pathString,\n            bar.appending(components: \"Tests\", \"barTests.swift\").pathString\n        )\n\n        var manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(\n                    name: \"bar\",\n                    path: \"target/bar\"),\n                try TargetDescription(\n                    name: \"barTests\",\n                    path: \"target/bar/Tests\",\n                    type: .test),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            diagnostics.check(diagnostic: \"target 'barTests' has overlapping sources: \\(bar.appending(components: \"Tests\", \"barTests.swift\"))\", severity: .error)\n        }\n\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(\n                    name: \"bar\",\n                    path: \"target/bar\",\n                    exclude: [\"Tests\"]),\n                try TargetDescription(\n                    name: \"barTests\",\n                    path: \"target/bar/Tests\",\n                    type: .test),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            package.checkPredefinedPaths(target: \"/Sources\", testTarget: \"/Tests\")\n\n            try package.checkModule(\"bar\") { module in\n                module.check(c99name: \"bar\", type: .library)\n                module.checkSources(root: \"/target/bar\", paths: \"bar.swift\")\n            }\n\n            try package.checkModule(\"barTests\") { module in\n                module.check(c99name: \"barTests\", type: .test)\n                module.checkSources(root: bar.appending(components: \"Tests\").pathString, paths: \"barTests.swift\")\n            }\n\n            package.checkProduct(\"pkgPackageTests\")\n        }\n    }\n\n    @Test\n    func testPublicHeadersPath() throws {\n        let Sources: AbsolutePath = \"/Sources\"\n        let Tests: AbsolutePath = \"/Tests\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            Sources.appending(components: \"Foo\", \"inc\", \"module.modulemap\").pathString,\n            Sources.appending(components: \"Foo\", \"inc\", \"Foo.h\").pathString,\n            Sources.appending(components: \"Foo\", \"Foo_private.h\").pathString,\n            Sources.appending(components: \"Foo\", \"Foo.c\").pathString,\n            Sources.appending(components: \"Bar\", \"include\", \"module.modulemap\").pathString,\n            Sources.appending(components: \"Bar\", \"include\", \"Bar.h\").pathString,\n            Sources.appending(components: \"Bar\", \"Bar.c\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            targets: [\n                try TargetDescription(\n                    name: \"Foo\",\n                    publicHeadersPath: \"inc\"),\n                try TargetDescription(\n                    name: \"Bar\"),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            package.checkPredefinedPaths(target: Sources, testTarget: Tests)\n\n            try package.checkModule(\"Foo\") { module in\n                let clangTarget = try #require(module.target as? ClangModule)\n                #expect(clangTarget.headers.map{ $0.pathString } == [Sources.appending(components: \"Foo\", \"Foo_private.h\").pathString, Sources.appending(components: \"Foo\", \"inc\", \"Foo.h\").pathString])\n                module.check(c99name: \"Foo\", type: .library)\n                module.checkSources(root: Sources.appending(components: \"Foo\").pathString, paths: \"Foo.c\")\n                module.check(includeDir: Sources.appending(components: \"Foo\", \"inc\").pathString)\n                module.check(moduleMapType: .custom(Sources.appending(components: \"Foo\", \"inc\", \"module.modulemap\")))\n            }\n\n            try package.checkModule(\"Bar\") { module in\n                module.check(c99name: \"Bar\", type: .library)\n                module.checkSources(root: Sources.appending(components: \"Bar\").pathString, paths: \"Bar.c\")\n                module.check(includeDir: Sources.appending(components: \"Bar\", \"include\").pathString)\n                module.check(moduleMapType: .custom(Sources.appending(components: \"Bar\", \"include\", \"module.modulemap\")))\n            }\n        }\n    }\n\n    @Test\n    func testInvalidPublicHeadersPath() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/Foo/inc/module.modulemap\",\n            \"/Sources/Foo/inc/Foo.h\",\n            \"/Sources/Foo/Foo.c\",\n            \"/Sources/Bar/include/module.modulemap\",\n            \"/Sources/Bar/include/Bar.h\",\n            \"/Sources/Bar/Bar.c\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            targets: [\n                try TargetDescription(\n                    name: \"Foo\",\n                    publicHeadersPath: \"/inc\"),\n                try TargetDescription(\n                    name: \"Bar\"),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n            diagnostics.check(diagnostic: \"invalid relative path \\'/inc\\'; relative path should not begin with \\'\\(AbsolutePath.root)\\'\", severity: .error)\n        }\n    }\n\n    @Test\n    func testTestsLayoutsv4() throws {\n        let Sources: AbsolutePath = \"/Sources\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            Sources.appending(components: \"A\", \"main.swift\").pathString,\n            \"/Tests/B/Foo.swift\",\n            \"/Tests/ATests/Foo.swift\",\n            \"/Tests/TheTestOfA/Foo.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            targets: [\n                try TargetDescription(name: \"A\"),\n                try TargetDescription(name: \"TheTestOfA\", dependencies: [\"A\"], type: .test),\n                try TargetDescription(name: \"ATests\", type: .test),\n                try TargetDescription(name: \"B\", type: .test),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            package.checkPredefinedPaths(target: Sources, testTarget: \"/Tests\")\n\n            try package.checkModule(\"A\") { module in\n                module.check(c99name: \"A\", type: .executable)\n                module.checkSources(root: \"/Sources/A\", paths: \"main.swift\")\n            }\n\n            try package.checkModule(\"TheTestOfA\") { module in\n                module.check(c99name: \"TheTestOfA\", type: .test)\n                module.checkSources(root: \"/Tests/TheTestOfA\", paths: \"Foo.swift\")\n                module.check(targetDependencies: [\"A\"])\n            }\n\n            try package.checkModule(\"B\") { module in\n                module.check(c99name: \"B\", type: .test)\n                module.checkSources(root: \"/Tests/B\", paths: \"Foo.swift\")\n                module.check(targetDependencies: [])\n            }\n\n            try package.checkModule(\"ATests\") { module in\n                module.check(c99name: \"ATests\", type: .test)\n                module.checkSources(root: \"/Tests/ATests\", paths: \"Foo.swift\")\n                module.check(targetDependencies: [])\n            }\n\n            package.checkProduct(\"FooPackageTests\") { _ in }\n            package.checkProduct(\"A\") { _ in }\n        }\n    }\n\n    @Test\n    func testMultipleTestProducts() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo/foo.swift\",\n            \"/Tests/fooTests/foo.swift\",\n            \"/Tests/barTests/bar.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(name: \"foo\"),\n                try TargetDescription(name: \"fooTests\", type: .test),\n                try TargetDescription(name: \"barTests\", type: .test),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, shouldCreateMultipleTestProducts: true, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { _ in }\n            try package.checkModule(\"fooTests\") { _ in }\n            try package.checkModule(\"barTests\") { _ in }\n            package.checkProduct(\"fooTests\") { product in\n                product.check(type: .test, targets: [\"fooTests\"])\n            }\n            package.checkProduct(\"barTests\") { product in\n                product.check(type: .test, targets: [\"barTests\"])\n            }\n        }\n\n        try PackageBuilderTester(manifest, shouldCreateMultipleTestProducts: false, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { _ in }\n            try package.checkModule(\"fooTests\") { _ in }\n            try package.checkModule(\"barTests\") { _ in }\n            package.checkProduct(\"pkgPackageTests\") { product in\n                product.check(type: .test, targets: [\"barTests\", \"fooTests\"])\n            }\n        }\n    }\n\n    @Test\n    func testCustomTargetDependencies() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/Foo/Foo.swift\",\n            \"/Sources/Bar/Bar.swift\",\n            \"/Sources/Baz/Baz.swift\")\n\n        // Direct.\n        var manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                try TargetDescription(name: \"Bar\"),\n                try TargetDescription(name: \"Baz\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"Foo\") { module in\n                module.check(c99name: \"Foo\", type: .library)\n                module.checkSources(root: \"/Sources/Foo\", paths: \"Foo.swift\")\n                module.check(targetDependencies: [\"Bar\"])\n            }\n\n            for target in [\"Bar\", \"Baz\"] {\n                try package.checkModule(target) { module in\n                    module.check(c99name: target, type: .library)\n                    module.checkSources(root: \"/Sources/\\(target)\", paths: \"\\(target).swift\")\n                }\n            }\n        }\n\n        // Transitive.\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                try TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n                try TargetDescription(name: \"Baz\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"Foo\") { module in\n                module.check(c99name: \"Foo\", type: .library)\n                module.checkSources(root: \"/Sources/Foo\", paths: \"Foo.swift\")\n                module.check(targetDependencies: [\"Bar\"])\n            }\n\n            try package.checkModule(\"Bar\") { module in\n                module.check(c99name: \"Bar\", type: .library)\n                module.checkSources(root: \"/Sources/Bar\", paths: \"Bar.swift\")\n                module.check(targetDependencies: [\"Baz\"])\n            }\n\n            try package.checkModule(\"Baz\") { module in\n                module.check(c99name: \"Baz\", type: .library)\n                module.checkSources(root: \"/Sources/Baz\", paths: \"Baz.swift\")\n            }\n        }\n    }\n\n    @Test\n    func testTargetDependencies() throws {\n        let Sources: AbsolutePath = \"/Sources\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            Sources.appending(components: \"Foo\", \"Foo.swift\").pathString,\n            Sources.appending(components: \"Bar\", \"Bar.swift\").pathString,\n            Sources.appending(components: \"Baz\", \"Baz.swift\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(name: \"Bar\"),\n                try TargetDescription(name: \"Baz\"),\n                try TargetDescription(\n                    name: \"Foo\",\n                    dependencies: [\"Bar\", \"Baz\", \"Bam\"]),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n\n            package.checkPredefinedPaths(target: Sources, testTarget: \"/Tests\")\n\n            try package.checkModule(\"Foo\") { module in\n                module.check(c99name: \"Foo\", type: .library)\n                module.checkSources(root: Sources.appending(components: \"Foo\").pathString, paths: \"Foo.swift\")\n                module.check(targetDependencies: [\"Bar\", \"Baz\"])\n                module.check(productDependencies: [.init(name: \"Bam\", package: nil)])\n            }\n\n            for target in [\"Bar\", \"Baz\"] {\n                try package.checkModule(target) { module in\n                    module.check(c99name: target, type: .library)\n                    module.checkSources(root: \"/Sources/\\(target)\", paths: \"\\(target).swift\")\n                }\n            }\n        }\n    }\n\n    /// Starting with tools version 5.9, packages are permitted to place\n    /// sources anywhere in ./Sources when a package has a single target.\n    @Test\n    func testRelaxedSourceLocationSingleTargetRegular() throws {\n        let predefinedSourceDir = PackageBuilder.suggestedPredefinedSourceDirectory(type: .regular)\n        do {\n            // Single target: Sources are expected in ./Sources.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Foo.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\"),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\") { result in\n                    #expect(\"/\\(predefinedSourceDir)\" == result.target.path)\n                }\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Sources.\n            // In this case, there is a stray source file at the top-level, and no sources\n            // under ./Sources, so the target Random has no sources.\n            // This results in a *warning* that there are no sources for the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target Random should be located under '\\(predefinedSourceDir)/Random', '\\(predefinedSourceDir)', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .warning)\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Sources. In this case,\n            // there is a stray source file at the top-level which is ignored.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\",\n                \"/\\(predefinedSourceDir)/Random.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\")\n            }\n        }\n        do {\n            // Single target: Sources can be expected in ./Sources/<target>.\n            // If that directory exists, stray sources inside ./Sources will\n            // not be included in the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Stray.swift\",\n                \"/\\(predefinedSourceDir)/Random/Random.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\") { result in\n                    result.checkSources(paths: \"Random.swift\")\n                }\n            }\n        }\n        do {\n            // Multiple targets: Sources are expected in their respective subdirectories\n            // under Sources\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Foo.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"TargetA\"),\n                    try TargetDescription(name: \"TargetB\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target TargetA should be located under '\\(predefinedSourceDir)/TargetA', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .error)\n            }\n        }\n    }\n\n    @Test\n    func testRelaxedSourceLocationSingleTargetTest() throws {\n        let predefinedSourceDir = PackageBuilder.suggestedPredefinedSourceDirectory(type: .test)\n        do {\n            // Single target: Sources are expected in ./Sources.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Foo.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"MyTests\", type: .test),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"MyTests\") { result in\n                    #expect(\"/\\(predefinedSourceDir)\" == result.target.path)\n                }\n                package.checkProduct(\"pkgPackageTests\")\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Tests.\n            // In this case, there is a stray source file at the top-level, and no sources\n            // under ./Tests, so the target RandomTests has no sources.\n            // This results in a *warning* that there are no sources for the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"RandomTests\", type: .test),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target RandomTests should be located under '\\(predefinedSourceDir)/RandomTests', '\\(predefinedSourceDir)', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .warning)\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Tests. In this case,\n            // there is a stray source file at the top-level which is ignored.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\",\n                \"/\\(predefinedSourceDir)/RandomTests.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"RandomTests\", type: .test),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"RandomTests\")\n                package.checkProduct(\"pkgPackageTests\")\n            }\n        }\n        do {\n            // Single target: Sources can be expected in ./Tests/<target>.\n            // If that directory exists, stray sources inside ./Tests will\n            // not be included in the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Stray.swift\",\n                \"/\\(predefinedSourceDir)/RandomTests/Random.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"RandomTests\", type: .test),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"RandomTests\") { result in\n                    result.checkSources(paths: \"Random.swift\")\n                }\n                package.checkProduct(\"pkgPackageTests\")\n            }\n        }\n        do {\n            // Multiple targets: Sources are expected in their respective subdirectories\n            // under Sources\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Foo.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"TargetA\", type: .test),\n                    try TargetDescription(name: \"TargetB\", type: .test),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target TargetA should be located under '\\(predefinedSourceDir)/TargetA', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .error)\n            }\n        }\n    }\n\n    @Test\n    func testRelaxedSourceLocationSingleTargetPlugin() throws {\n        let predefinedSourceDir = PackageBuilder.suggestedPredefinedSourceDirectory(type: .plugin)\n        do {\n            // Single target: Sources are expected in ./Sources.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Foo.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"MyPlugin\") { result in\n                    result.checkSources(root: result.target.path.appending(component: predefinedSourceDir).pathString, paths: \"Foo.swift\")\n                }\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Plugins.\n            // In this case, there is a stray source file at the top-level, and no sources\n            // under ./Plugins, so the target Random has no sources.\n            // This results in a *warning* that there are no sources for the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .plugin, pluginCapability: .buildTool),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target Random should be located under '\\(predefinedSourceDir)/Random', '\\(predefinedSourceDir)', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .warning)\n            }\n        }\n\n        do {\n            // Single target: Sources are expected in ./Plugins. In this case,\n            // there is a stray source file at the top-level which is ignored.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\",\n                \"/\\(predefinedSourceDir)/Random.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .plugin, pluginCapability: .buildTool),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\")\n            }\n        }\n        do {\n            // Single target: Sources can be expected in ./Plugins/<target>.\n            // If that directory exists, stray sources inside ./Plugins will\n            // not be included in the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Stray.swift\",\n                \"/\\(predefinedSourceDir)/Random/Random.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .plugin, pluginCapability: .buildTool),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\") { result in\n                    result.checkSources(paths: \"Random.swift\")\n                }\n            }\n        }\n        do {\n            // Multiple targets: Sources are expected in their respective subdirectories\n            // under Sources\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Foo.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"TargetA\", type: .plugin, pluginCapability: .buildTool),\n                    try TargetDescription(name: \"TargetB\", type: .plugin, pluginCapability: .buildTool),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target TargetA should be located under '\\(predefinedSourceDir)/TargetA', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .error)\n            }\n        }\n    }\n\n    @Test\n    func testRelaxedSourceLocationSingleTargetExecutable() throws {\n        let predefinedSourceDir = PackageBuilder.suggestedPredefinedSourceDirectory(type: .executable)\n        do {\n            // Single target: Sources are expected in ./Sources.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Foo.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"MyExe\", type: .executable),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"MyExe\") { result in\n                    #expect(\"/\\(predefinedSourceDir)\" == result.target.path)\n                }\n                package.checkProduct(\"MyExe\")\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Sources.\n            // In this case, there is a stray source file at the top-level, and no sources\n            // under ./Sources, so the target Random has no sources.\n            // This results in a *warning* that there are no sources for the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .executable),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target Random should be located under '\\(predefinedSourceDir)/Random', '\\(predefinedSourceDir)', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .warning)\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Sources. In this case,\n            // there is a stray source file at the top-level which is ignored.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\",\n                \"/\\(predefinedSourceDir)/Random.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .executable)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\")\n                package.checkProduct(\"Random\")\n            }\n        }\n        do {\n            // Single target: Sources can be expected in ./Sources/<target>.\n            // If that directory exists, stray sources inside ./Sources will\n            // not be included in the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Stray.swift\",\n                \"/\\(predefinedSourceDir)/Random/Random.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .executable)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\") { result in\n                    result.checkSources(paths: \"Random.swift\")\n                }\n                package.checkProduct(\"Random\")\n            }\n        }\n        do {\n            // Multiple targets: Sources are expected in their respective subdirectories\n            // under Sources\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Foo.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"TargetA\", type: .executable),\n                    try TargetDescription(name: \"TargetB\", type: .executable)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target TargetA should be located under '\\(predefinedSourceDir)/TargetA', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .error)\n            }\n        }\n    }\n\n    @Test\n    func testRelaxedSourceLocationSingleTargetSystem() throws {\n        let predefinedSourceDir = PackageBuilder.suggestedPredefinedSourceDirectory(type: .system)\n        do {\n            // Single target: Sources are expected in ./Sources.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/module.modulemap\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Foo\", type: .system),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Foo\") { result in\n                    #expect(\"/\\(predefinedSourceDir)\" == result.target.path)\n                }\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Sources.\n            // In this case, there is a stray source file at the top-level, and no sources\n            // under ./Sources, so the target Random has no sources.\n            // This results in a *warning* that there are no sources for the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .system),\n                ]\n            )\n            let map = \"/\\(predefinedSourceDir)/module.modulemap\"\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n#if _runtime(_ObjC)\n                diagnostics.check(diagnostic: \"package has unsupported layout; missing system target module map at '\\(map)'\", severity: .error)\n#else\n                // FIXME: there is a memory leak here\n                diagnostics.check(diagnostic: \"package has unsupported layout; missing system target module map at '\\(String(cString: map.fileSystemRepresentation))'\", severity: .error)\n#endif\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Sources. In this case,\n            // there is a stray source file at the top-level which is ignored.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\",\n                \"/\\(predefinedSourceDir)/module.modulemap\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .system)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\")\n            }\n        }\n        do {\n            // Single target: Sources can be expected in ./Sources/<target>.\n            // If that directory exists, stray sources inside ./Sources will\n            // not be included in the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Stray.swift\",\n                \"/\\(predefinedSourceDir)/module.modulemap\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .system)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\") { result in\n                    result.checkSources()\n                }\n            }\n        }\n        do {\n            // Multiple targets: Sources are expected in their respective subdirectories\n            // under Sources\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Foo.swift\")\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"TargetA\", type: .system),\n                    try TargetDescription(name: \"TargetB\", type: .system)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target TargetA should be located under '\\(predefinedSourceDir)/TargetA', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .error)\n            }\n        }\n    }\n\n    @Test\n    func testRelaxedSourceLocationSingleTargetMacro() throws {\n        let predefinedSourceDir = PackageBuilder.suggestedPredefinedSourceDirectory(type: .macro)\n        do {\n            // Single target: Sources are expected in ./Sources.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Foo.swift\"\n            )\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Foo\", type: .macro),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Foo\") { result in\n                    #expect(\"/\\(predefinedSourceDir)\" == result.target.path)\n                }\n                package.checkProduct(\"Foo\")\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Sources.\n            // In this case, there is a stray source file at the top-level, and no sources\n            // under ./Sources, so the target Random has no sources.\n            // This results in a *warning* that there are no sources for the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\")\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .macro),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target Random should be located under '\\(predefinedSourceDir)/Random', '\\(predefinedSourceDir)', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .warning)\n            }\n        }\n        do {\n            // Single target: Sources are expected in ./Sources. In this case,\n            // there is a stray source file at the top-level which is ignored.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Stray.swift\",\n                \"/\\(predefinedSourceDir)/Random.swift\")\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .macro)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\") { result in\n                    result.checkSources(root: \"/\\(predefinedSourceDir)\", paths: \"Random.swift\")\n                }\n                package.checkProduct(\"Random\")\n            }\n        }\n        do {\n            // Single target: Sources can be expected in ./Sources/<target>.\n            // If that directory exists, stray sources inside ./Sources will\n            // not be included in the target.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/\\(predefinedSourceDir)/Stray.swift\",\n                \"/\\(predefinedSourceDir)/Random/Random.swift\"\n            )\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"Random\", type: .macro)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                try package.checkModule(\"Random\") { result in\n                    result.checkSources(root: \"/\\(predefinedSourceDir)/Random\", paths: \"Random.swift\")\n                }\n                package.checkProduct(\"Random\")\n            }\n        }\n        do {\n            // Multiple targets: Sources are expected in their respective subdirectories\n            // under Sources\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Foo.swift\")\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                toolsVersion: .v5_9,\n                targets: [\n                    try TargetDescription(name: \"TargetA\", type: .macro),\n                    try TargetDescription(name: \"TargetB\", type: .macro)\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"Source files for target TargetA should be located under '\\(predefinedSourceDir)/TargetA', or a custom sources path can be set with the 'path' property in Package.swift\", severity: .error)\n            }\n        }\n    }\n\n    @Test\n    func testStrictSourceLocationPre5_9() throws {\n        do {\n            for fs in [\n                InMemoryFileSystem(emptyFiles:\n                                    \"/Sources/Foo.swift\"),\n                InMemoryFileSystem(emptyFiles:\n                                    \"/Stray.swift\"),\n                InMemoryFileSystem(emptyFiles:\n                                    \"/Stray.swift\",\n                                   \"/Sources/Random.swift\"),\n            ] {\n                let manifest = Manifest.createRootManifest(\n                    displayName: \"pkg\",\n                    targets: [\n                        try TargetDescription(name: \"Random\"),\n                    ]\n                )\n                try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                    diagnostics.check(diagnostic: .contains(\"Source files for target Random should be located under 'Sources/Random'\"), severity: .error)\n                }\n            }\n        }\n    }\n\n    @Test\n    func testManifestTargetDeclErrors() throws {\n        do {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/src/pkg/Foo.swift\")\n            // Reference an invalid dependency.\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"pkg\", dependencies: [.target(name: \"Foo\")]),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: .contains(\"Source files for target Foo should be located under 'Sources/Foo'\"), severity: .error)\n            }\n        }\n\n        do {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Sources/pkg/Foo.swift\")\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"pkg\", dependencies: []),\n                    try TargetDescription(name: \"pkgTests\", dependencies: [], type: .test),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: .contains(\"Source files for target pkgTests should be located under 'Tests/pkgTests'\"), severity: .error)\n            }\n        }\n\n        do {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Source/pkg/Foo.swift\")\n            // Reference self in dependencies.\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"pkg\", dependencies: [.target(name: \"pkg\")]),\n                ],\n                traits: []\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"cyclic dependency declaration found: pkg -> pkg\", severity: .error)\n            }\n        }\n\n        do {\n            let fs = InMemoryFileSystem()\n            // Binary target.\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"foo\", url: \"https://foo.com/foo.zip\", type: .binary, checksum: \"checksum\"),\n                    try TargetDescription(name: \"foo2\", path: \"./foo2.zip\", type: .binary)\n                ]\n            )\n\n            try fs.writeFileContents(\"/foo2.zip\", bytes: \"\")\n\n            let binaryArtifacts = [\n                \"foo\": BinaryArtifact(kind: .xcframework, originURL: \"https://foo.com/foo.zip\", path: \"/foo.xcframework\"),\n                \"foo2\": BinaryArtifact(kind: .xcframework, originURL: nil, path: \"/foo2.xcframework\")\n            ]\n            try PackageBuilderTester(manifest, binaryArtifacts: binaryArtifacts, in: fs) { package, _ in\n                try package.checkModule(\"foo\")\n                try package.checkModule(\"foo2\")\n            }\n        }\n\n        do {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Sources/pkg1/Foo.swift\",\n                \"/Sources/pkg2/Foo.swift\",\n                \"/Sources/pkg3/Foo.swift\"\n            )\n            // Cyclic dependency.\n            var manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"pkg1\", dependencies: [\"pkg2\"]),\n                    try TargetDescription(name: \"pkg2\", dependencies: [\"pkg3\"]),\n                    try TargetDescription(name: \"pkg3\", dependencies: [\"pkg1\"]),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"cyclic dependency declaration found: pkg1 -> pkg2 -> pkg3 -> pkg1\", severity: .error)\n            }\n\n            manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"pkg1\", dependencies: [\"pkg2\"]),\n                    try TargetDescription(name: \"pkg2\", dependencies: [\"pkg3\"]),\n                    try TargetDescription(name: \"pkg3\", dependencies: [\"pkg2\"]),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"cyclic dependency declaration found: pkg1 -> pkg2 -> pkg3 -> pkg2\", severity: .error)\n            }\n        }\n\n        do {\n            let pkg2: AbsolutePath = \"/Sources/pkg2\"\n\n            // Reference a target which doesn't have sources.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Sources/pkg1/Foo.swift\",\n                pkg2.appending(components: \"readme.txt\").pathString\n            )\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"pkg1\", dependencies: [\"pkg2\"]),\n                    try TargetDescription(name: \"pkg2\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n                diagnostics.check(\n                    diagnostic: .contains(\"Source files for target pkg2 should be located under 'Sources/pkg2'\"),\n                    severity: .warning\n                )\n                try package.checkModule(\"pkg1\") { module in\n                    module.check(c99name: \"pkg1\", type: .library)\n                    module.checkSources(root: \"/Sources/pkg1\", paths: \"Foo.swift\")\n                }\n            }\n        }\n\n        do {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Sources/Foo/Foo.c\",\n                \"/Sources/Bar/Bar.c\")\n\n            var manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                targets: [\n                    try TargetDescription(name: \"Foo\", publicHeadersPath: \"../inc\"),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"public headers (\\\"include\\\") directory path for 'Foo' is invalid or not contained in the target\", severity: .error)\n            }\n\n            manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                targets: [\n                    try TargetDescription(name: \"Bar\", publicHeadersPath: \"inc/../../../foo\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"public headers (\\\"include\\\") directory path for 'Bar' is invalid or not contained in the target\", severity: .error)\n            }\n        }\n\n        do {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/pkg/Sources/Foo/Foo.c\",\n                \"/foo/Bar.c\")\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                targets: [\n                    try TargetDescription(name: \"Foo\", path: \"../foo\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, path: \"/pkg\", in: fs) { package, diagnostics in\n                diagnostics.check(diagnostic: \"target 'Foo' in package '\\(package.packageIdentity)' is outside the package root\", severity: .error)\n            }\n        }\n        do {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/pkg/Sources/Foo/Foo.c\",\n                \"/foo/Bar.c\")\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                targets: [\n                    try TargetDescription(name: \"Foo\", path: \"/foo\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, path: \"/pkg\", in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"target path \\'/foo\\' is not supported; it should be relative to package root\", severity: .error)\n            }\n        }\n\n        /*\n        do {\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/pkg/Sources/Foo/Foo.c\",\n                \"/foo/Bar.c\")\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                targets: [\n                    try TargetDescription(name: \"Foo\", path: \"~/foo\"),\n                ]\n            )\n            try PackageBuilderTester(manifest, path: \"/pkg\", in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: \"target path \\'~/foo\\' is not supported; it should be relative to package root\", severity: .error)\n            }\n        }*/\n    }\n\n    @Test\n    func testExecutableAsADep() throws {\n        // Executable as dependency.\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/exec/main.swift\",\n            \"/Sources/lib/lib.swift\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(name: \"lib\", dependencies: [\"exec\"]),\n                try TargetDescription(name: \"exec\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"exec\") { module in\n                module.check(c99name: \"exec\", type: .executable)\n                module.checkSources(root: \"/Sources/exec\", paths: \"main.swift\")\n            }\n\n            try package.checkModule(\"lib\") { module in\n                module.check(c99name: \"lib\", type: .library)\n                module.checkSources(root: \"/Sources/lib\", paths: \"lib.swift\")\n            }\n\n            package.checkProduct(\"exec\")\n        }\n    }\n\n    @Test\n    func testInvalidManifestConfigForNonSystemModules() throws {\n        var fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/main.swift\"\n        )\n\n        var manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            pkgConfig: \"foo\"\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            diagnostics.check(\n                diagnostic: \"configuration of package '\\(package.packageIdentity)' is invalid; the 'pkgConfig' property can only be used with a System Module Package\",\n                severity: .error)\n        }\n\n        fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/Foo/main.c\"\n        )\n        manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            providers: [.brew([\"foo\"])]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            diagnostics.check(\n                diagnostic: \"configuration of package '\\(package.packageIdentity)' is invalid; the 'providers' property can only be used with a System Module Package\",\n                severity: .error)\n        }\n    }\n\n    @Test\n    func testResolvesSystemModulePackage() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/module.modulemap\")\n\n        let manifest = Manifest.createRootManifest(displayName: \"SystemModulePackage\")\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"SystemModulePackage\") { module in\n                module.check(c99name: \"SystemModulePackage\", type: .systemModule)\n                module.checkSources(root: \"/\")\n            }\n        }\n    }\n\n    @Test\n    func testCompatibleSwiftVersions() throws {\n        // Single swift executable target.\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/foo/main.swift\"\n        )\n\n        func createManifest(swiftVersions: [SwiftLanguageVersion]?) throws -> Manifest {\n            return Manifest.createRootManifest(\n                displayName: \"pkg\",\n                swiftLanguageVersions: swiftVersions,\n                targets: [\n                    try TargetDescription(name: \"foo\", path: \"foo\"),\n                ]\n            )\n        }\n\n        var manifest = try createManifest(swiftVersions: [.v3, .v4])\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { module in\n                module.check(swiftVersion: \"4\")\n            }\n            package.checkProduct(\"foo\") { _ in }\n        }\n\n        manifest = try createManifest(swiftVersions: [.v3])\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { module in\n                module.check(swiftVersion: \"3\")\n            }\n            package.checkProduct(\"foo\") { _ in }\n        }\n\n        manifest = try createManifest(swiftVersions: [.v4])\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { module in\n                module.check(swiftVersion: \"4\")\n            }\n            package.checkProduct(\"foo\") { _ in }\n        }\n\n        manifest = try createManifest(swiftVersions: nil)\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { module in\n                module.check(swiftVersion: \"4\")\n            }\n            package.checkProduct(\"foo\") { _ in }\n        }\n\n        manifest = try createManifest(swiftVersions: [SwiftLanguageVersion(string: \"5\")!])\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"foo\") { module in\n                module.check(swiftVersion: \"5\")\n            }\n            package.checkProduct(\"foo\") { _ in }\n        }\n\n        manifest = try createManifest(swiftVersions: [SwiftLanguageVersion(string: \"6\")!])\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"foo\") { module in\n                module.check(swiftVersion: \"6\")\n            }\n            package.checkProduct(\"foo\") { _ in }\n        }\n\n        manifest = try createManifest(swiftVersions: [])\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            diagnostics.check(\n                diagnostic: \"package '\\(package.packageIdentity)' supported Swift language versions is empty\",\n                severity: .error\n            )\n        }\n\n        manifest = try createManifest(swiftVersions: [SwiftLanguageVersion(string: \"7\")!])\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            diagnostics.check(\n                diagnostic: \"package '\\(package.packageIdentity)' requires minimum Swift language version 7 which is not supported by the current tools version (\\(ToolsVersion.current))\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func testPredefinedTargetSearchError() throws {\n\n        do {\n            // We should look only in one of the predefined search paths.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Source/Foo/Foo.swift\",\n                \"/src/Bar/Bar.swift\")\n\n            let manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n                    try TargetDescription(name: \"Bar\"),\n                ]\n            )\n\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: .contains(\"Source files for target Bar should be located under 'Sources/Bar'\"), severity: .error)\n            }\n        }\n\n        do {\n            // We should look only in one of the predefined search paths.\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Source/Foo/Foo.swift\",\n                \"/Tests/FooTests/Foo.swift\",\n                \"/Source/BarTests/Foo.swift\")\n\n            var manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"BarTests\", type: .test),\n                    try TargetDescription(name: \"FooTests\", type: .test),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n                diagnostics.check(diagnostic: .contains(\"Source files for target BarTests should be located under 'Tests/BarTests'\"), severity: .error)\n            }\n\n            // We should be able to fix this by using custom paths.\n            manifest = Manifest.createRootManifest(\n                displayName: \"pkg\",\n                targets: [\n                    try TargetDescription(name: \"BarTests\", path: \"Source/BarTests\", type: .test),\n                    try TargetDescription(name: \"FooTests\", type: .test),\n                ]\n            )\n            try PackageBuilderTester(manifest, in: fs) { package, _ in\n                try package.checkModule(\"BarTests\") { module in\n                    module.check(c99name: \"BarTests\", type: .test)\n                }\n                try package.checkModule(\"FooTests\") { module in\n                    module.check(c99name: \"FooTests\", type: .test)\n                }\n                package.checkProduct(\"pkgPackageTests\") { _ in }\n            }\n        }\n    }\n\n    @Test\n    func testSpecifiedCustomPathDoesNotExist() throws {\n        let fs = InMemoryFileSystem(emptyFiles: \"/Foo.swift\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            targets: [\n                try TargetDescription(name: \"Foo\", path: \"./NotExist\")\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n            diagnostics.check(diagnostic: \"invalid custom path './NotExist' for target 'Foo'\", severity: .error)\n        }\n    }\n\n    @Test\n    func testSpecialTargetDir() throws {\n        let src: AbsolutePath = \"/src\"\n        // Special directory should be src because both target and test target are under it.\n        let fs = InMemoryFileSystem(emptyFiles:\n            src.appending(components: \"A\", \"Foo.swift\").pathString,\n            src.appending(components: \"ATests\", \"Foo.swift\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            targets: [\n                try TargetDescription(name: \"A\"),\n                try TargetDescription(name: \"ATests\", type: .test),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            package.checkPredefinedPaths(target: src, testTarget: src)\n\n            try package.checkModule(\"A\") { module in\n                module.check(c99name: \"A\", type: .library)\n            }\n            try package.checkModule(\"ATests\") { module in\n                module.check(c99name: \"ATests\", type: .test)\n            }\n\n            package.checkProduct(\"FooPackageTests\") { _ in }\n        }\n    }\n\n    @Test\n    func testExcludes() throws {\n        // The exclude should win if a file is in exclude as well as sources.\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/bar/barExcluded.swift\",\n            \"/Sources/bar/bar.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            targets: [\n                try TargetDescription(\n                    name: \"bar\",\n                    exclude: [\"barExcluded.swift\",],\n                    sources: [\"bar.swift\", \"barExcluded.swift\"]\n                ),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"bar\") { module in\n                module.check(c99name: \"bar\", type: .library)\n                module.checkSources(root: \"/Sources/bar\", paths: \"bar.swift\")\n            }\n        }\n    }\n\n    @Test\n    func testDuplicateProducts() throws {\n        // Check that declaring executable product doesn't collide with the\n        // inferred products.\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo/foo.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            products: [\n                try ProductDescription(name: \"foo\", type: .library(.automatic), targets: [\"foo\"]),\n                try ProductDescription(name: \"foo\", type: .library(.static), targets: [\"foo\"]),\n                try ProductDescription(name: \"foo\", type: .library(.dynamic), targets: [\"foo\"]),\n                try ProductDescription(name: \"foo-dy\", type: .library(.dynamic), targets: [\"foo\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"foo\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"foo\") { _ in }\n            package.checkProduct(\"foo\") { product in\n                product.check(type: .library(.automatic), targets: [\"foo\"])\n            }\n            package.checkProduct(\"foo-dy\") { product in\n                product.check(type: .library(.dynamic), targets: [\"foo\"])\n            }\n            diagnostics.check(\n                diagnostic: \"ignoring duplicate product 'foo' (static library)\",\n                severity: .warning\n            )\n            diagnostics.check(\n                diagnostic: \"ignoring duplicate product 'foo' (dynamic library)\",\n                severity: .warning\n            )\n        }\n    }\n\n    @Test\n    func testSystemPackageDeclaresTargetsDiagnostic() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/module.modulemap\",\n            \"/Sources/foo/main.swift\",\n            \"/Sources/bar/main.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"SystemModulePackage\",\n            targets: [\n                try TargetDescription(name: \"foo\"),\n                try TargetDescription(name: \"bar\"),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"SystemModulePackage\") { module in\n                module.check(c99name: \"SystemModulePackage\", type: .systemModule)\n                module.checkSources(root: \"/\")\n            }\n            diagnostics.check(\n                diagnostic: \"ignoring declared target(s) 'foo, bar' in the system package\",\n                severity: .warning\n            )\n        }\n    }\n\n    @Test\n    func testSystemLibraryTarget() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo/module.modulemap\",\n            \"/Sources/bar/bar.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            products: [\n                try ProductDescription(name: \"foo\", type: .library(.automatic), targets: [\"foo\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"foo\", type: .system),\n                try TargetDescription(name: \"bar\", dependencies: [\"foo\"]),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { module in\n                module.check(c99name: \"foo\", type: .systemModule)\n                module.checkSources(root: \"/Sources/foo\")\n            }\n            try package.checkModule(\"bar\") { module in\n                module.check(c99name: \"bar\", type: .library)\n                module.checkSources(root: \"/Sources/bar\", paths: \"bar.swift\")\n                module.check(targetDependencies: [\"foo\"])\n            }\n            package.checkProduct(\"foo\") { product in\n                product.check(type: .library(.automatic), targets: [\"foo\"])\n            }\n        }\n    }\n\n    @Test\n    func testSystemLibraryTargetDiagnostics() throws {\n        let Sources: AbsolutePath = \"/Sources\"\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            Sources.appending(components: \"foo\", \"module.modulemap\").pathString,\n            Sources.appending(components: \"bar\", \"bar.swift\").pathString\n        )\n\n        var manifest = Manifest.createRootManifest(\n            displayName: \"SystemModulePackage\",\n            products: [\n                try ProductDescription(name: \"foo\", type: .library(.automatic), targets: [\"foo\", \"bar\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"foo\", type: .system),\n                try TargetDescription(name: \"bar\", dependencies: [\"foo\"]),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"foo\") { _ in }\n            try package.checkModule(\"bar\") { _ in }\n            diagnostics.check(\n                diagnostic: \"system library product foo shouldn't have a type and contain only one target\",\n                severity: .error\n            )\n        }\n\n        manifest = Manifest.createRootManifest(\n            displayName: \"SystemModulePackage\",\n            products: [\n                try ProductDescription(name: \"foo\", type: .library(.static), targets: [\"foo\"]),\n            ],\n            targets: [\n                try TargetDescription(name: \"foo\", type: .system),\n                try TargetDescription(name: \"bar\", dependencies: [\"foo\"]),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"foo\") { _ in }\n            try package.checkModule(\"bar\") { _ in }\n            diagnostics.check(\n                diagnostic: \"system library product foo shouldn't have a type and contain only one target\",\n                severity: .error\n            )\n        }\n\n        manifest = Manifest.createRootManifest(\n            displayName: \"bar\",\n            products: [\n                try ProductDescription(name: \"bar\", type: .library(.automatic), targets: [\"bar\"])\n            ],\n            targets: [\n                try TargetDescription(name: \"bar\", type: .system)\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { _, diagnostics in\n            diagnostics.check(\n                diagnostic: \"package has unsupported layout; missing system target module map at '\\(Sources.appending(components: \"bar\", \"module.modulemap\"))'\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func testBadExecutableProductDecl() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo1/main.swift\",\n            \"/Sources/foo2/main.swift\",\n            \"/Sources/FooLib1/lib.swift\",\n            \"/Sources/FooLib2/lib.swift\",\n            \"/Plugins/Plugin1/plugin.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"MyPackage\",\n            products: [\n                try ProductDescription(name: \"foo1\", type: .executable, targets: [\"FooLib1\"]),\n                try ProductDescription(name: \"foo2\", type: .executable, targets: [\"FooLib1\", \"FooLib2\"]),\n                try ProductDescription(name: \"foo3\", type: .executable, targets: [\"foo1\", \"foo2\"]),\n                try ProductDescription(name: \"foo3\", type: .executable, targets: [\"foo1\", \"Plugin1\"])\n            ],\n            targets: [\n                try TargetDescription(name: \"foo1\"),\n                try TargetDescription(name: \"foo2\"),\n                try TargetDescription(name: \"FooLib1\"),\n                try TargetDescription(name: \"FooLib2\"),\n                try TargetDescription(name: \"Plugin1\", type: .plugin, pluginCapability: .buildTool),\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"foo1\") { _ in }\n            try package.checkModule(\"foo2\") { _ in }\n            try package.checkModule(\"FooLib1\") { _ in }\n            try package.checkModule(\"FooLib2\") { _ in }\n            try package.checkModule(\"Plugin1\") { _ in }\n            diagnostics.check(\n                diagnostic: \"\"\"\n                    executable product 'foo1' expects target 'FooLib1' to be executable; an executable target requires \\\n                    a 'main.swift' file\n                    \"\"\",\n                severity: .error\n            )\n            diagnostics.check(\n                diagnostic: \"\"\"\n                    executable product 'foo2' should have one executable target; an executable target requires a \\\n                    'main.swift' file\n                    \"\"\",\n                severity: .error\n            )\n            diagnostics.check(\n                diagnostic: \"executable product 'foo3' should not have more than one executable target\",\n                severity: .error\n            )\n            diagnostics.check(\n                diagnostic: \"executable product 'foo3' should not contain plugin targets (it has 'Plugin1')\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func testLibraryProductDiagnostics() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/MyLibrary/library.swift\",\n            \"/Plugins/MyPlugin/plugin.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"MyPackage\",\n            products: [\n                try ProductDescription(name: \"MyLibrary\", type: .library(.automatic), targets: [\"MyLibrary\", \"MyPlugin\"])\n            ],\n            targets: [\n                try TargetDescription(name: \"MyLibrary\", type: .regular),\n                try TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool)\n            ]\n        )\n        try PackageBuilderTester(manifest, in: fs) { package, diagnostics in\n            try package.checkModule(\"MyLibrary\") { _ in }\n            try package.checkModule(\"MyPlugin\") { _ in }\n            diagnostics.check(\n                diagnostic: \"\"\"\n                    library product 'MyLibrary' should not contain plugin targets (it has 'MyPlugin')\n                    \"\"\",\n                severity: .error\n            )\n        }\n    }\n\n\n    @Test\n    func testBadREPLPackage() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/exe/main.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Pkg\",\n            targets: [\n                try TargetDescription(name: \"exe\"),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, createREPLProduct: true, in: fs) { package, diagnostics in\n            try package.checkModule(\"exe\") { _ in }\n            package.checkProduct(\"exe\") { _ in }\n            diagnostics.check(\n                diagnostic: \"unable to synthesize a REPL product as there are no library targets in the package\",\n                severity: .error\n            )\n        }\n    }\n\n    @Test\n    func testAsmIsIgnoredInV4_2Manifest() throws {\n        // .s is not considered a valid source in 4.2 manifest.\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/lib/lib.s\",\n            \"/Sources/lib/lib2.S\",\n            \"/Sources/lib/lib.c\",\n            \"/Sources/lib/include/lib.h\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v4_2,\n            targets: [\n                try TargetDescription(name: \"lib\", dependencies: []),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"lib\") { module in\n                module.checkSources(root: \"/Sources/lib\", paths: \"lib.c\")\n            }\n        }\n    }\n\n    @Test\n    func testAsmInV5Manifest() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/lib/lib.s\",\n            \"/Sources/lib/lib2.S\",\n            \"/Sources/lib/lib.c\",\n            \"/Sources/lib/include/lib.h\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Pkg\",\n            toolsVersion: .v5,\n            targets: [\n                try TargetDescription(name: \"lib\", dependencies: []),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"lib\") { module in\n                module.checkSources(root: \"/Sources/lib\", paths: \"lib.c\", \"lib.s\", \"lib2.S\")\n            }\n        }\n    }\n\n    @Test\n    func testUnknownSourceFilesUnderDeclaredSourcesIgnoredInV5_2Manifest() throws {\n        let lib: AbsolutePath = \"/Sources/lib\"\n\n        // Files with unknown suffixes under declared sources are not considered valid sources in 5.2 manifest.\n        let fs = InMemoryFileSystem(emptyFiles:\n            lib.appending(components: \"movie.mkv\").pathString,\n            lib.appending(components: \"lib.c\").pathString,\n            lib.appending(components: \"include\", \"lib.h\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5_2,\n            targets: [\n                try TargetDescription(name: \"lib\", dependencies: [], path: \"./Sources/lib\", sources: [\".\"]),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"lib\") { module in\n                module.checkSources(root: lib.pathString, paths: \"lib.c\")\n                module.check(includeDir: lib.appending(components: \"include\").pathString)\n                module.check(moduleMapType: .umbrellaHeader(lib.appending(components: \"include\", \"lib.h\")))\n            }\n        }\n    }\n\n    @Test\n    func testUnknownSourceFilesUnderDeclaredSourcesCompiledInV5_3Manifest() throws {\n        let lib: AbsolutePath = \"/Sources/lib\"\n\n        // Files with unknown suffixes under declared sources are treated as compilable in 5.3 manifest.\n        let fs = InMemoryFileSystem(emptyFiles:\n            lib.appending(components: \"movie.mkv\").pathString,\n            lib.appending(components: \"lib.c\").pathString,\n            lib.appending(components: \"include\", \"lib.h\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5_3,\n            targets: [\n                try TargetDescription(name: \"lib\", dependencies: [], path: \"./Sources/lib\", sources: [\".\"]),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"lib\") { module in\n                module.checkSources(root: lib.pathString, paths: \"movie.mkv\", \"lib.c\")\n                module.check(includeDir: lib.appending(components: \"include\").pathString)\n                module.check(moduleMapType: .umbrellaHeader(lib.appending(components: \"include\", \"lib.h\")))\n            }\n        }\n    }\n\n    @Test\n    func testBuildSettings() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/exe/main.swift\",\n            \"/Sources/bar/bar.swift\",\n            \"/Sources/cbar/barcpp.cpp\",\n            \"/Sources/cbar/bar.c\",\n            \"/Sources/cbar/include/bar.h\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5,\n            targets: [\n                try TargetDescription(\n                    name: \"cbar\",\n                    settings: [\n                        .init(tool: .c, kind: .headerSearchPath(\"Sources/headers\")),\n                        .init(tool: .cxx, kind: .headerSearchPath(\"Sources/cppheaders\")),\n\n                        .init(tool: .c, kind: .define(\"CCC=2\")),\n                        .init(tool: .cxx, kind: .define(\"CXX\")),\n                        .init(tool: .cxx, kind: .define(\"RCXX\"), condition: .init(config: \"release\")),\n\n                        .init(tool: .c, kind: .unsafeFlags([\"-Icfoo\", \"-L\", \"cbar\"])),\n                        .init(tool: .cxx, kind: .unsafeFlags([\"-Icxxfoo\", \"-L\", \"cxxbar\"])),\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"bar\", dependencies: [\"foo\"],\n                    settings: [\n                        .init(tool: .swift, kind: .define(\"SOMETHING\")),\n                        .init(tool: .swift, kind: .define(\"LINUX\"), condition: .init(platformNames: [\"linux\"])),\n                        .init(tool: .swift, kind: .define(\"RLINUX\"), condition: .init(platformNames: [\"linux\"], config: \"release\")),\n                        .init(tool: .swift, kind: .define(\"DMACOS\"), condition: .init(platformNames: [\"macos\"], config: \"debug\")),\n                        .init(tool: .swift, kind: .unsafeFlags([\"-Isfoo\", \"-L\", \"sbar\"])),\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"exe\", dependencies: [\"bar\"],\n                    settings: [\n                        .init(tool: .linker, kind: .linkedLibrary(\"sqlite3\")),\n                        .init(tool: .linker, kind: .linkedFramework(\"CoreData\"), condition: .init(platformNames: [\"ios\"])),\n                        .init(tool: .linker, kind: .unsafeFlags([\"-Ilfoo\", \"-L\", \"lbar\"])),\n                    ]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"cbar\") { package in\n                let scope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS) == [\"CCC=2\", \"CXX\"])\n                #expect(scope.evaluate(.HEADER_SEARCH_PATHS) == [\"Sources/headers\", \"Sources/cppheaders\"])\n                #expect(scope.evaluate(.OTHER_CFLAGS) == [\"-Icfoo\", \"-L\", \"cbar\"])\n                #expect(scope.evaluate(.OTHER_CPLUSPLUSFLAGS) == [\"-Icxxfoo\", \"-L\", \"cxxbar\"])\n\n                let releaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(releaseScope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS) == [\"CCC=2\", \"CXX\", \"RCXX\"])\n            }\n\n            try package.checkModule(\"bar\") { package in\n                let scope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .linux, configuration: .debug)\n                )\n                #expect(scope.evaluate(.SWIFT_ACTIVE_COMPILATION_CONDITIONS) == [\"SOMETHING\", \"LINUX\"])\n                #expect(scope.evaluate(.OTHER_SWIFT_FLAGS) == [\"-Isfoo\", \"-L\", \"sbar\"])\n\n                let rscope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .linux, configuration: .release)\n                )\n                #expect(rscope.evaluate(.SWIFT_ACTIVE_COMPILATION_CONDITIONS) == [\"SOMETHING\", \"LINUX\", \"RLINUX\"])\n\n                let mscope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(mscope.evaluate(.SWIFT_ACTIVE_COMPILATION_CONDITIONS) == [\"SOMETHING\", \"DMACOS\"])\n            }\n\n            try package.checkModule(\"exe\") { package in\n                let scope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .linux, configuration: .debug)\n                )\n                #expect(scope.evaluate(.LINK_LIBRARIES) == [\"sqlite3\"])\n                #expect(scope.evaluate(.OTHER_LDFLAGS) == [\"-Ilfoo\", \"-L\", \"lbar\"])\n                #expect(scope.evaluate(.LINK_FRAMEWORKS) == [])\n                #expect(scope.evaluate(.OTHER_SWIFT_FLAGS) == [])\n                #expect(scope.evaluate(.OTHER_CFLAGS) == [])\n                #expect(scope.evaluate(.OTHER_CPLUSPLUSFLAGS) == [])\n\n                let mscope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .iOS, configuration: .debug)\n                )\n                #expect(mscope.evaluate(.LINK_LIBRARIES) == [\"sqlite3\"])\n                #expect(mscope.evaluate(.LINK_FRAMEWORKS) == [\"CoreData\"])\n\n            }\n\n            package.checkProduct(\"exe\")\n        }\n    }\n\n    @Test\n    func testEmptyUnsafeFlagsAreAllowed() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo/foo.swift\",\n            \"/Sources/bar/bar.cpp\",\n            \"/Sources/bar/bar.c\",\n            \"/Sources/bar/include/bar.h\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5,\n            targets: [\n                try TargetDescription(\n                    name: \"foo\",\n                    settings: [\n                        .init(tool: .c, kind: .unsafeFlags([])),\n                        .init(tool: .cxx, kind: .unsafeFlags([])),\n                        .init(tool: .cxx, kind: .unsafeFlags([]), condition: .init(config: \"release\")),\n                        .init(tool: .linker, kind: .unsafeFlags([])),\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"bar\",\n                    settings: [\n                        .init(tool: .swift, kind: .unsafeFlags([]), condition: .init(platformNames: [\"macos\"], config: \"debug\")),\n                        .init(tool: .linker, kind: .unsafeFlags([])),\n                        .init(tool: .linker, kind: .unsafeFlags([]), condition: .init(platformNames: [\"linux\"])),\n                    ]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { package in\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(macosDebugScope.evaluate(.OTHER_CFLAGS) == [])\n                #expect(macosDebugScope.evaluate(.OTHER_CPLUSPLUSFLAGS) == [])\n                #expect(macosDebugScope.evaluate(.OTHER_LDFLAGS) == [])\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(macosReleaseScope.evaluate(.OTHER_CFLAGS) == [])\n                #expect(macosReleaseScope.evaluate(.OTHER_CPLUSPLUSFLAGS) == [])\n                #expect(macosReleaseScope.evaluate(.OTHER_LDFLAGS) == [])\n            }\n\n            try package.checkModule(\"bar\") { package in\n                let linuxDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .linux, configuration: .debug)\n                )\n                #expect(linuxDebugScope.evaluate(.OTHER_SWIFT_FLAGS) == [])\n                #expect(linuxDebugScope.evaluate(.OTHER_LDFLAGS) == [])\n\n                let linuxReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .linux, configuration: .release)\n                )\n                #expect(linuxReleaseScope.evaluate(.OTHER_SWIFT_FLAGS) == [])\n                #expect(linuxReleaseScope.evaluate(.OTHER_LDFLAGS) == [])\n\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(macosDebugScope.evaluate(.OTHER_SWIFT_FLAGS) == [])\n                #expect(macosDebugScope.evaluate(.OTHER_LDFLAGS) == [])\n            }\n        }\n    }\n\n    @Test\n    func testInvalidHeaderSearchPath() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/pkg/Sources/exe/main.swift\"\n        )\n\n        let manifest1 = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5,\n            targets: [\n                try TargetDescription(\n                    name: \"exe\",\n                    settings: [\n                        .init(tool: .c, kind: .headerSearchPath(\"/Sources/headers\")),\n                    ]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest1, path: \"/pkg\", in: fs) { package, diagnostics in\n            diagnostics.check(diagnostic: \"invalid relative path '/Sources/headers'; relative path should not begin with '\\(AbsolutePath.root)'\", severity: .error)\n        }\n\n        let manifest2 = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5,\n            targets: [\n                try TargetDescription(\n                    name: \"exe\",\n                    settings: [\n                        .init(tool: .c, kind: .headerSearchPath(\"../../..\")),\n                    ]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest2, path: \"/pkg\", in: fs) { _, diagnostics in\n            diagnostics.check(diagnostic: \"invalid header search path '../../..'; header search path should not be outside the package root\", severity: .error)\n        }\n    }\n\n    @Test\n    func testDuplicateTargetDependencies() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Foo/Sources/Foo/foo.swift\",\n            \"/Foo/Sources/Foo2/foo.swift\",\n            \"/Foo/Sources/Foo3/foo.swift\",\n            \"/Foo/Sources/Qux/foo.swift\",\n            \"/Bar/Sources/Bar/bar.swift\",\n            \"/Bar/Sources/Bar2/bar.swift\",\n            \"/Bar/Sources/Qux/bar.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            toolsVersion: .v5,\n            dependencies: [\n                .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            ],\n            targets: [\n                try TargetDescription(\n                    name: \"Foo\",\n                    dependencies: [\n                        // invalid - same target in package \"Bar\"\n                        \"Bar\",\n                        \"Bar\",\n\n                        // invalid - same target in package \"Bar\"\n                        \"Bar2\",\n                        .product(name: \"Bar2\", package: \"Bar\"),\n\n                        // invalid - same target in this package\n                        \"Foo2\",\n                        \"Foo2\",\n\n                        // invalid - same target in this package\n                        \"Foo3\",\n                        .target(name: \"Foo3\"),\n\n                        // valid - different packages\n                        \"Qux\",\n                        .product(name: \"Qux\", package: \"Bar\")\n                    ]),\n                try TargetDescription(name: \"Foo2\"),\n                try TargetDescription(name: \"Foo3\"),\n                try TargetDescription(name: \"Qux\")\n            ],\n            traits: []\n        )\n\n        try PackageBuilderTester(manifest, path: \"/Foo\", in: fs) { package, diagnostics in\n            try package.checkModule(\"Foo\")\n            try package.checkModule(\"Foo2\")\n            try package.checkModule(\"Foo3\")\n            try package.checkModule(\"Qux\")\n            diagnostics.checkUnordered(\n                diagnostic: \"invalid duplicate target dependency declaration 'Bar' in target 'Foo' from package '\\(package.packageIdentity)'\",\n                severity: .warning\n            )\n            diagnostics.checkUnordered(\n                diagnostic: \"invalid duplicate target dependency declaration 'Foo2' in target 'Foo' from package '\\(package.packageIdentity)'\",\n                severity: .warning\n            )\n            diagnostics.checkUnordered(\n                diagnostic: \"invalid duplicate target dependency declaration 'Bar2' in target 'Foo' from package '\\(package.packageIdentity)'\",\n                severity: .warning\n            )\n            diagnostics.checkUnordered(\n                diagnostic: \"invalid duplicate target dependency declaration 'Foo3' in target 'Foo' from package '\\(package.packageIdentity)'\",\n                severity: .warning\n            )\n        }\n    }\n\n    @Test\n    func testConditionalDependencies() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/Foo/main.swift\",\n            \"/Sources/Bar/bar.swift\",\n            \"/Sources/Baz/baz.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            toolsVersion: .v5,\n            dependencies: [\n                .fileSystem(path: \"/Biz\"),\n            ],\n            targets: [\n                try TargetDescription(\n                    name: \"Foo\",\n                    dependencies: [\n                        .target(name: \"Bar\", condition: PackageConditionDescription(\n                            platformNames: [\"macos\"],\n                            config: nil\n                        )),\n                        .byName(name: \"Baz\", condition: PackageConditionDescription(\n                            platformNames: [],\n                            config: \"debug\"\n                        )),\n                        .product(name: \"Biz\", package: \"Biz\", condition: PackageConditionDescription(\n                            platformNames: [\"watchos\", \"ios\"],\n                            config: \"release\"\n                        )),\n                    ]\n                ),\n                try TargetDescription(name: \"Bar\"),\n                try TargetDescription(name: \"Baz\"),\n            ],\n            traits: []\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            package.checkProduct(\"Foo\")\n            try package.checkModule(\"Bar\")\n            try package.checkModule(\"Baz\")\n            try package.checkModule(\"Foo\") { target in\n                target.check(dependencies: [\"Bar\", \"Baz\", \"Biz\"])\n\n                target.checkDependency(\"Bar\") { result in\n                    result.checkConditions(satisfy: .init(platform: .macOS, configuration: .debug))\n                    result.checkConditions(satisfy: .init(platform: .macOS, configuration: .release))\n                    result.checkConditions(dontSatisfy: .init(platform: .watchOS, configuration: .release))\n                }\n\n                target.checkDependency(\"Baz\") { result in\n                    result.checkConditions(satisfy: .init(platform: .macOS, configuration: .debug))\n                    result.checkConditions(satisfy: .init(platform: .linux, configuration: .debug))\n                    result.checkConditions(dontSatisfy: .init(platform: .linux, configuration: .release))\n                }\n\n                target.checkDependency(\"Biz\") { result in\n                    result.checkConditions(satisfy: .init(platform: .watchOS, configuration: .release))\n                    result.checkConditions(satisfy: .init(platform: .iOS, configuration: .release))\n                    result.checkConditions(dontSatisfy: .init(platform: .linux, configuration: .release))\n                    result.checkConditions(dontSatisfy: .init(platform: .iOS, configuration: .debug))\n                }\n            }\n        }\n    }\n\n    @Test\n    func testMissingDefaultLocalization() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Foo/Sources/Foo/foo.swift\",\n            \"/Foo/Sources/Foo/Resources/en.lproj/Localizable.strings\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            toolsVersion: .v5_3,\n            targets: [\n                try TargetDescription(name: \"Foo\", resources: [\n                    .init(rule: .process(localization: .none), path: \"Resources\")\n                ]),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, path: \"/Foo\", in: fs) { _, diagnostics in\n            diagnostics.check(diagnostic: \"manifest property 'defaultLocalization' not set; it is required in the presence of localized resources\", severity: .error)\n        }\n    }\n\n    @Test\n    func testXcodeResources5_4AndEarlier() throws {\n        // In SwiftTools 5.4 and earlier, supported xcbuild file types are supported by default.\n        // Of course, modern file types such as xcstrings won't be supported here because those require a newer Swift tools version in general.\n\n        let root: AbsolutePath = \"/Foo\"\n        let foo = root.appending(components: \"Sources\", \"Foo\")\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            foo.appending(components: \"foo.swift\").pathString,\n            foo.appending(components: \"Foo.xcassets\").pathString,\n            foo.appending(components: \"Foo.xib\").pathString,\n            foo.appending(components: \"Foo.xcdatamodel\").pathString,\n            foo.appending(components: \"Foo.metal\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            toolsVersion: .v5_3,\n            targets: [\n                try TargetDescription(name: \"Foo\"),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, path: root, in: fs) { result, diagnostics in\n            try result.checkModule(\"Foo\") { result in\n                result.checkSources(sources: [\"foo.swift\"])\n                result.checkResources(resources: [\n                    foo.appending(components: \"Foo.xib\").pathString,\n                    foo.appending(components: \"Foo.xcdatamodel\").pathString,\n                    foo.appending(components: \"Foo.xcassets\").pathString,\n                    foo.appending(components: \"Foo.metal\").pathString\n                ])\n            }\n        }\n    }\n\n    @Test\n    func testXcodeResources5_5AndLater() throws {\n        // In SwiftTools 5.5 and later, xcbuild file types are only supported when explicitly passed via additionalFileRules.\n\n        let root: AbsolutePath = \"/Foo\"\n        let foo = root.appending(components: \"Sources\", \"Foo\")\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            foo.appending(components: \"foo.swift\").pathString,\n            foo.appending(components: \"Foo.xcassets\").pathString,\n            foo.appending(components: \"Foo.xcstrings\").pathString,\n            foo.appending(components: \"Foo.xib\").pathString,\n            foo.appending(components: \"Foo.xcdatamodel\").pathString,\n            foo.appending(components: \"Foo.metal\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            toolsVersion: .v5_9,\n            targets: [\n                try TargetDescription(name: \"Foo\"),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, path: root, supportXCBuildTypes: true, in: fs) { result, diagnostics in\n            try result.checkModule(\"Foo\") { result in\n                result.checkSources(sources: [\"foo.swift\"])\n                result.checkResources(resources: [\n                    foo.appending(components: \"Foo.xib\").pathString,\n                    foo.appending(components: \"Foo.xcdatamodel\").pathString,\n                    foo.appending(components: \"Foo.xcassets\").pathString,\n                    foo.appending(components: \"Foo.xcstrings\").pathString,\n                    foo.appending(components: \"Foo.metal\").pathString\n                ])\n            }\n        }\n    }\n\n    @Test\n    func testXcodeResources6_0AndLater() throws {\n        // In SwiftTools 6.0 and later, xcprivacy file types are only supported when explicitly passed via additionalFileRules.\n\n        let root: AbsolutePath = \"/Foo\"\n        let foo = root.appending(components: \"Sources\", \"Foo\")\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            foo.appending(components: \"foo.swift\").pathString,\n            foo.appending(components: \"Foo.xcassets\").pathString,\n            foo.appending(components: \"Foo.xcstrings\").pathString,\n            foo.appending(components: \"Foo.xib\").pathString,\n            foo.appending(components: \"Foo.xcdatamodel\").pathString,\n            foo.appending(components: \"Foo.metal\").pathString,\n            foo.appending(components: \"PrivacyInfo.xcprivacy\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            toolsVersion: .v6_0,\n            targets: [\n                try TargetDescription(name: \"Foo\"),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, path: root, supportXCBuildTypes: true, in: fs) { result, diagnostics in\n            try result.checkModule(\"Foo\") { result in\n                result.checkSources(sources: [\"foo.swift\"])\n                result.checkResources(resources: [\n                    foo.appending(components: \"Foo.xib\").pathString,\n                    foo.appending(components: \"Foo.xcdatamodel\").pathString,\n                    foo.appending(components: \"Foo.xcassets\").pathString,\n                    foo.appending(components: \"Foo.xcstrings\").pathString,\n                    foo.appending(components: \"Foo.metal\").pathString,\n                    foo.appending(components: \"PrivacyInfo.xcprivacy\").pathString,\n                ])\n            }\n        }\n    }\n\n    @Test\n    func testXCPrivacyNoDiagnostics() throws {\n        // In SwiftTools 6.0 and later, xcprivacy file types should not produce diagnostics messages when included\n        // as resources and built with `swift build`.\n\n        let root: AbsolutePath = \"/Foo\"\n        let foo = root.appending(components: \"Sources\", \"Foo\")\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            foo.appending(components: \"foo.swift\").pathString,\n            foo.appending(components: \"PrivacyInfo.xcprivacy\").pathString\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            toolsVersion: .v6_0,\n            targets: [\n                try TargetDescription(\n                    name: \"Foo\",\n                    resources: [.init(rule: .copy, path: \"PrivacyInfo.xcprivacy\")]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, path: root, supportXCBuildTypes: false, in: fs) { result, diagnostics in\n            try result.checkModule(\"Foo\") { result in\n                result.checkSources(sources: [\"foo.swift\"])\n                result.checkResources(resources: [\n                    foo.appending(components: \"PrivacyInfo.xcprivacy\").pathString,\n                ])\n            }\n\n            diagnostics.checkIsEmpty()\n        }\n    }\n\n    @Test(\n        .tags(\n            .Feature.Snippets,\n        ),\n    )\n    func testSnippetsLinkProductLibraries() throws {\n        let root = AbsolutePath(\"/Foo\")\n        let internalSourcesDir = root.appending(components: \"Sources\", \"Internal\")\n        let productSourcesDir = root.appending(components: \"Sources\", \"Product\")\n        let snippetsDir = root.appending(components: \"Snippets\")\n        let fs = InMemoryFileSystem(emptyFiles:\n                                        internalSourcesDir.appending(\"Internal.swift\").pathString,\n            productSourcesDir.appending(\"Product.swift\").pathString,\n            snippetsDir.appending(\"ASnippet.swift\").pathString)\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\", toolsVersion: .v5_7,\n            products: [\n                try ProductDescription(name: \"Product\", type: .library(.automatic), targets: [\"Product\"])\n            ],\n            targets: [\n                try TargetDescription(name: \"Internal\"),\n                try TargetDescription(name: \"Product\"),\n            ])\n\n        try PackageBuilderTester(manifest, path: root, in: fs) { result, diagnostics in\n            result.checkProduct(\"Product\") { product in\n                product.check(type: .library(.automatic), targets: [\"Product\"])\n            }\n            result.checkProduct(\"ASnippet\") { aSnippet in\n                aSnippet.check(type: .snippet, targets: [\"ASnippet\"])\n            }\n            try result.checkModule(\"Internal\") { foo in\n                foo.checkSources(sources: [\"Internal.swift\"])\n            }\n            try result.checkModule(\"Product\") { foo in\n                foo.checkSources(sources: [\"Product.swift\"])\n            }\n            try result.checkModule(\"ASnippet\") { aSnippet in\n                aSnippet.checkSources(sources: [\"ASnippet.swift\"])\n                aSnippet.check(targetDependencies: [\"Product\"])\n            }\n        }\n    }\n\n    @Test\n    func testCustomPlatformInConditionals() throws {\n        let fs = InMemoryFileSystem(emptyFiles: \"/Sources/Foo/Best.swift\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"Foo\",\n            path: .root,\n            targets: [\n                try TargetDescription(\n                    name: \"Foo\",\n                    settings: [\n                        .init(tool: .swift, kind: .define(\"YOLO\"), condition: .init(platformNames: [\"bestOS\"])),\n                    ]\n                )\n            ]\n        )\n\n        var assignment = BuildSettings.Assignment()\n        assignment.values = [\"YOLO\"]\n        assignment.conditions = [PackageCondition(platforms: [.custom(name: \"bestOS\", oldestSupportedVersion: .unknown)])]\n\n        var versionAssignment = BuildSettings.Assignment(default: true)\n        versionAssignment.values = [\"4\"]\n\n        var settings = BuildSettings.AssignmentTable()\n        settings.add(assignment, for: .SWIFT_ACTIVE_COMPILATION_CONDITIONS)\n        settings.add(versionAssignment, for: .SWIFT_VERSION)\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"Foo\") { module in\n                module.check(c99name: \"Foo\", type: .library)\n                module.check(buildSettings: settings)\n            }\n        }\n    }\n\n    @Test\n    func testSwiftLanguageVersionPerTarget() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo/foo.swift\",\n            \"/Sources/bar/bar.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v5,\n            targets: [\n                try TargetDescription(\n                    name: \"foo\",\n                    settings: [\n                        .init(tool: .swift, kind: .swiftLanguageMode(.v5))\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"bar\",\n                    settings: [\n                        .init(tool: .swift, kind: .swiftLanguageMode(.v3), condition: .init(platformNames: [\"linux\"])),\n                        .init(tool: .swift, kind: .swiftLanguageMode(.v4), condition: .init(platformNames: [\"macos\"], config: \"debug\"))\n                    ]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { package in\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(macosDebugScope.evaluate(.SWIFT_VERSION) == [\"5\"])\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(macosReleaseScope.evaluate(.SWIFT_VERSION) == [\"5\"])\n            }\n\n            try package.checkModule(\"bar\") { package in\n                let linuxDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .linux, configuration: .debug)\n                )\n                #expect(linuxDebugScope.evaluate(.SWIFT_VERSION) == [\"3\"])\n\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(macosDebugScope.evaluate(.SWIFT_VERSION) == [\"4\"])\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(macosReleaseScope.evaluate(.SWIFT_VERSION) == [\"5\"])\n            }\n        }\n    }\n\n    @Test\n    func testSwiftWarningControlFlags() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/foo/foo.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v6_2,\n            targets: [\n                try TargetDescription(\n                    name: \"foo\",\n                    settings: [\n                        .init(tool: .swift, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                        .init(tool: .swift, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                        .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .error), condition: .init(config: \"release\")),\n                        .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .warning), condition: .init(config: \"debug\")),\n                    ]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"foo\") { package in\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(\n                    macosDebugScope.evaluate(.OTHER_SWIFT_FLAGS) ==\n                    [\"-no-warnings-as-errors\", \"-Wwarning\", \"DeprecatedDeclaration\"]\n                )\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(\n                    macosReleaseScope.evaluate(.OTHER_SWIFT_FLAGS) ==\n                    [\"-warnings-as-errors\", \"-Werror\", \"DeprecatedDeclaration\"]\n                )\n            }\n        }\n    }\n\n    @Test\n    func testCWarningControlFlags() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/cfoo/foo.c\",\n            \"/Sources/cfoo/include/cfoo.h\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v6_2,\n            targets: [\n                try TargetDescription(\n                    name: \"cfoo\",\n                    settings: [\n                        .init(tool: .c, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                        .init(tool: .c, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                        .init(tool: .c, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                        .init(tool: .c, kind: .treatWarning(\"deprecated-declarations\", .warning), condition: .init(config: \"debug\")),\n                    ]\n                )\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"cfoo\") { package in\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(\n                    macosDebugScope.evaluate(.OTHER_CFLAGS) ==\n                    [\"-Wno-error\", \"-Wno-error=deprecated-declarations\"]\n                )\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(\n                    macosReleaseScope.evaluate(.OTHER_CFLAGS) ==\n                    [\"-Werror\", \"-Werror=deprecated-declarations\"]\n                )\n            }\n        }\n    }\n\n    @Test\n    func testCXXWarningControlFlags() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/cxxfoo/foo.cpp\",\n            \"/Sources/cxxfoo/include/cxxfoo.h\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v6_2,\n            targets: [\n                try TargetDescription(\n                    name: \"cxxfoo\",\n                    settings: [\n                        .init(tool: .cxx, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                        .init(tool: .cxx, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                        .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                        .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .warning), condition: .init(config: \"debug\")),\n                    ]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"cxxfoo\") { package in\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(\n                    macosDebugScope.evaluate(.OTHER_CPLUSPLUSFLAGS) ==\n                    [\"-Wno-error\", \"-Wno-error=deprecated-declarations\"]\n                )\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(\n                    macosReleaseScope.evaluate(.OTHER_CPLUSPLUSFLAGS) ==\n                    [\"-Werror\", \"-Werror=deprecated-declarations\"]\n                )\n            }\n        }\n    }\n\n    @Test\n    func testCWarningEnableDisable() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/cfoo/foo.c\",\n            \"/Sources/cfoo/include/cfoo.h\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v6_2,\n            targets: [\n                try TargetDescription(\n                    name: \"cfoo\",\n                    settings: [\n                        .init(tool: .c, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                        .init(tool: .c, kind: .disableWarning(\"unused-parameter\"), condition: .init(config: \"release\")),\n                    ]\n                )\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"cfoo\") { package in\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(\n                    macosDebugScope.evaluate(.OTHER_CFLAGS) ==\n                    [\"-Wimplicit-fallthrough\"]\n                )\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(\n                    macosReleaseScope.evaluate(.OTHER_CFLAGS) ==\n                    [\"-Wno-unused-parameter\"]\n                )\n            }\n        }\n    }\n\n    @Test\n    func testCXXWarningEnableDisable() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/cxxfoo/foo.cpp\",\n            \"/Sources/cxxfoo/include/cxxfoo.h\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v6_2,\n            targets: [\n                try TargetDescription(\n                    name: \"cxxfoo\",\n                    settings: [\n                        .init(tool: .cxx, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                        .init(tool: .cxx, kind: .disableWarning(\"unused-parameter\"), condition: .init(config: \"release\")),\n                    ]\n                )\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"cxxfoo\") { package in\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(\n                    macosDebugScope.evaluate(.OTHER_CPLUSPLUSFLAGS) ==\n                    [\"-Wimplicit-fallthrough\"]\n                )\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(\n                    macosReleaseScope.evaluate(.OTHER_CPLUSPLUSFLAGS) ==\n                    [\"-Wno-unused-parameter\"]\n                )\n            }\n        }\n    }\n\n    @Test\n    func testDefaultIsolationPerTarget() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Sources/A/a.swift\",\n            \"/Sources/B/b.swift\"\n        )\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            toolsVersion: .v6_2,\n            targets: [\n                try TargetDescription(\n                    name: \"A\",\n                    settings: [\n                        .init(tool: .swift, kind: .defaultIsolation(.MainActor))\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"B\",\n                    settings: [\n                        .init(tool: .swift, kind: .defaultIsolation(.nonisolated), condition: .init(platformNames: [\"linux\"])),\n                        .init(tool: .swift, kind: .defaultIsolation(.MainActor), condition: .init(platformNames: [\"macos\"], config: \"debug\"))\n                    ]\n                ),\n            ]\n        )\n\n        try PackageBuilderTester(manifest, in: fs) { package, _ in\n            try package.checkModule(\"A\") { package in\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(macosDebugScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"-default-isolation\"))\n                #expect(macosDebugScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"MainActor\"))\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(macosReleaseScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"-default-isolation\"))\n                #expect(macosReleaseScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"MainActor\"))\n\n            }\n\n            try package.checkModule(\"B\") { package in\n                let linuxDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .linux, configuration: .debug)\n                )\n                #expect(linuxDebugScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"-default-isolation\"))\n                #expect(linuxDebugScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"nonisolated\"))\n\n                let macosDebugScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .debug)\n                )\n                #expect(macosDebugScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"-default-isolation\"))\n                #expect(macosDebugScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"MainActor\"))\n\n                let macosReleaseScope = BuildSettings.Scope(\n                    package.target.buildSettings,\n                    environment: BuildEnvironment(platform: .macOS, configuration: .release)\n                )\n                #expect(!macosReleaseScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"-default-isolation\") ||\n                        !macosReleaseScope.evaluate(.OTHER_SWIFT_FLAGS).contains(\"MainActor\"))\n\n            }\n        }\n    }\n}\n\nfinal class PackageBuilderTester {\n    private enum Result {\n        case package(PackageModel.Package)\n        case error(String)\n    }\n\n    // the package identity\n    public let packageIdentity: PackageIdentity\n\n    /// Contains the result produced by PackageBuilder.\n    private let result: Result\n\n    /// Contains the targets which have not been checked yet.\n    private var uncheckedModules: Set<PackageModel.Module> = []\n\n    /// Contains the products which have not been checked yet.\n    private var uncheckedProducts: Set<PackageModel.Product> = []\n\n    @discardableResult\n    init(\n        _ manifest: Manifest,\n        path: AbsolutePath = .root,\n        binaryArtifacts: [String: BinaryArtifact] = [:],\n        shouldCreateMultipleTestProducts: Bool = false,\n        createREPLProduct: Bool = false,\n        supportXCBuildTypes: Bool = false,\n        in fs: FileSystem,\n        sourceLocation: SourceLocation = #_sourceLocation,\n        _ body: (PackageBuilderTester, DiagnosticsTestResult) throws -> Void\n    ) throws {\n        self.packageIdentity = PackageIdentity(urlString: manifest.packageLocation)\n        let observability = ObservabilitySystem.makeForTesting()\n        do {\n            // FIXME: We should allow customizing root package boolean.\n            let builder = PackageBuilder(\n                identity: self.packageIdentity,\n                manifest: manifest,\n                productFilter: .everything,\n                path: path,\n                additionalFileRules: supportXCBuildTypes ? FileRuleDescription.xcbuildFileTypes : FileRuleDescription.swiftpmFileTypes,\n                binaryArtifacts: binaryArtifacts,\n                shouldCreateMultipleTestProducts: shouldCreateMultipleTestProducts,\n                warnAboutImplicitExecutableTargets: true,\n                createREPLProduct: createREPLProduct,\n                fileSystem: fs,\n                observabilityScope: observability.topScope,\n                enabledTraits: []\n            )\n            let loadedPackage = try builder.construct()\n            self.result = .package(loadedPackage)\n            uncheckedModules = Set(loadedPackage.modules)\n            uncheckedProducts = Set(loadedPackage.products)\n        } catch {\n            let errorString = String(describing: error)\n            self.result = .error(errorString)\n            observability.topScope.emit(error)\n        }\n\n        try expectDiagnostics(observability.diagnostics, sourceLocation: sourceLocation) { diagnostics in\n            try body(self, diagnostics)\n        }\n\n        validateCheckedModules(sourceLocation: sourceLocation)\n    }\n\n    private func validateCheckedModules(sourceLocation: SourceLocation = #_sourceLocation) {\n        if !uncheckedModules.isEmpty {\n            Issue.record(\"Unchecked targets: \\(uncheckedModules)\", sourceLocation: sourceLocation)\n        }\n\n        if !uncheckedProducts.isEmpty {\n            Issue.record(\"Unchecked products: \\(uncheckedProducts)\", sourceLocation: sourceLocation)\n        }\n    }\n\n    func checkPredefinedPaths(target: AbsolutePath, testTarget: AbsolutePath, sourceLocation: SourceLocation = #_sourceLocation) {\n        guard case .package(let package) = result else {\n            Issue.record(\"Expected package did not load \\(self)\", sourceLocation: sourceLocation)\n            return\n        }\n        #expect(target == package.targetSearchPath, sourceLocation: sourceLocation)\n        #expect(testTarget == package.testTargetSearchPath, sourceLocation: sourceLocation)\n    }\n\n    func checkModule(_ name: String, sourceLocation: SourceLocation = #_sourceLocation, _ body: ((ModuleResult) throws -> Void)? = nil) throws {\n        guard case .package(let package) = result else {\n            Issue.record(\"Expected package did not load \\(self)\", sourceLocation: sourceLocation)\n            return\n        }\n        guard let target = package.modules.first(where: {$0.name == name}) else {\n            Issue.record(\"Module: \\(name) not found\", sourceLocation: sourceLocation)\n            return\n        }\n        uncheckedModules.remove(target)\n        try body?(ModuleResult(target))\n    }\n\n    func checkProduct(_ name: String, sourceLocation: SourceLocation = #_sourceLocation, _ body: ((ProductResult) -> Void)? = nil) {\n        guard case .package(let package) = result else {\n            Issue.record(\"Expected package did not load \\(self)\", sourceLocation: sourceLocation)\n            return\n        }\n        let foundProducts = package.products.filter{$0.name == name}\n        guard foundProducts.count == 1 else {\n            Issue.record(\"Couldn't get the product: \\(name). Found products \\(foundProducts)\", sourceLocation: sourceLocation)\n            return\n        }\n        uncheckedProducts.remove(foundProducts[0])\n        body?(ProductResult(foundProducts[0]))\n    }\n\n    final class ProductResult {\n        private let product: PackageModel.Product\n\n        init(_ product: PackageModel.Product) {\n            self.product = product\n        }\n\n        func check(type: PackageModel.ProductType, targets: [String], sourceLocation: SourceLocation = #_sourceLocation) {\n            #expect(product.type == type, sourceLocation: sourceLocation)\n            #expect(product.modules.map{$0.name}.sorted() == targets.sorted(), sourceLocation: sourceLocation)\n        }\n\n        func check(testEntryPointPath: String?, sourceLocation: SourceLocation = #_sourceLocation) {\n            let expectedPath = testEntryPointPath.map({ try! AbsolutePath(validating: $0) })\n            #expect(product.testEntryPointPath == expectedPath, sourceLocation: sourceLocation)\n        }\n    }\n\n    final class ModuleResult {\n        let target: PackageModel.Module\n\n        fileprivate init(_ target: PackageModel.Module) {\n            self.target = target\n        }\n\n        func check(includeDir: String, sourceLocation: SourceLocation = #_sourceLocation) {\n            guard case let target as ClangModule = target else {\n                Issue.record(\"Include directory is being checked on a non clang target\", sourceLocation: sourceLocation)\n                return\n            }\n            #expect(target.includeDir.pathString == includeDir, sourceLocation: sourceLocation)\n        }\n\n        func check(moduleMapType: ModuleMapType, sourceLocation: SourceLocation = #_sourceLocation) {\n            guard case let target as ClangModule = target else {\n                Issue.record(\"Module map type is being checked on a non-Clang target\", sourceLocation: sourceLocation)\n                return\n            }\n            #expect(target.moduleMapType == moduleMapType, sourceLocation: sourceLocation)\n        }\n\n        func check(c99name: String? = nil, type: PackageModel.Module.Kind? = nil, sourceLocation: SourceLocation = #_sourceLocation) {\n            if let c99name {\n                #expect(target.c99name == c99name, sourceLocation: sourceLocation)\n            }\n            if let type {\n                #expect(target.type == type, sourceLocation: sourceLocation)\n            }\n        }\n\n        func checkSources(root: String? = nil, sources paths: [String], sourceLocation: SourceLocation = #_sourceLocation) {\n            if let root {\n                let expectedRoot = try! AbsolutePath(validating: root)\n                #expect(target.sources.root == expectedRoot, sourceLocation: sourceLocation)\n            }\n            let sources = Set(self.target.sources.relativePaths.map({ $0.pathString }))\n            #expect(sources == Set(paths), \"unexpected source files in \\(target.name)\", sourceLocation: sourceLocation)\n        }\n\n        func checkSources(root: String? = nil, paths: String..., sourceLocation: SourceLocation = #_sourceLocation) {\n            checkSources(root: root, sources: paths, sourceLocation: sourceLocation)\n        }\n\n        func checkResources(resources: [String], sourceLocation: SourceLocation = #_sourceLocation) {\n            #expect(Set(resources) == Set(self.target.resources.map{ $0.path.pathString }), \"unexpected resource files in \\(target.name)\", sourceLocation: sourceLocation)\n        }\n\n        func check(targetDependencies depsToCheck: [String], sourceLocation: SourceLocation = #_sourceLocation) {\n            #expect(Set(depsToCheck) == Set(target.dependencies.compactMap { $0.module?.name }), \"unexpected dependencies in \\(target.name)\", sourceLocation: sourceLocation)\n        }\n\n        func check(\n            productDependencies depsToCheck: [Module.ProductReference],\n            sourceLocation: SourceLocation = #_sourceLocation\n        ) {\n            let productDependencies = target.dependencies.compactMap { $0.product }\n            guard depsToCheck.count == productDependencies.count else {\n                Issue.record(\"Incorrect product dependencies\", sourceLocation: sourceLocation)\n                return\n            }\n            for (idx, element) in depsToCheck.enumerated() {\n                let rhs = productDependencies[idx]\n                guard element.name == rhs.name && element.package == rhs.package else {\n                    Issue.record(\"Incorrect product dependencies\", sourceLocation: sourceLocation)\n                    return\n                }\n            }\n        }\n\n        func check(dependencies: [String], sourceLocation: SourceLocation = #_sourceLocation) {\n            #expect(\n                Set(dependencies) == Set(target.dependencies.map({ $0.name })),\n                \"unexpected dependencies in \\(target.name)\",\n                sourceLocation: sourceLocation\n            )\n        }\n\n        func checkDependency(\n            _ name: String,\n            sourceLocation: SourceLocation = #_sourceLocation,\n            _ body: (ModuleDependencyResult) -> Void\n        ) {\n            guard let dependency = target.dependencies.first(where: { $0.name == name }) else {\n                Issue.record(\"Module: \\(name) not found\", sourceLocation: sourceLocation)\n                return\n            }\n            body(ModuleDependencyResult(dependency))\n        }\n\n        func check(swiftVersion: String, sourceLocation: SourceLocation = #_sourceLocation) {\n            guard case let swiftTarget as SwiftModule = target else {\n                Issue.record(\"\\(target) is not a swift target\", sourceLocation: sourceLocation)\n                return\n            }\n            guard let versionAssignments = swiftTarget.buildSettings.assignments[.SWIFT_VERSION]?\n                .filter { $0.conditions.isEmpty }.flatMap(\\.values) else {\n                    Issue.record(\"\\(target) has no version assignments\", sourceLocation: sourceLocation)\n                    return\n                }\n            #expect(versionAssignments.contains(swiftVersion) != nil, sourceLocation: sourceLocation)\n        }\n\n        func check(pluginCapability: PluginCapability, sourceLocation: SourceLocation = #_sourceLocation) {\n            guard case let target as PluginModule = target else {\n                Issue.record(\"Plugin capability is being checked on a target\", sourceLocation: sourceLocation)\n                return\n            }\n            #expect(target.capability == pluginCapability, sourceLocation: sourceLocation)\n        }\n\n        func check(buildSettings: PackageModel.BuildSettings.AssignmentTable, sourceLocation: SourceLocation = #_sourceLocation) {\n            #expect(target.buildSettings.assignments == buildSettings.assignments, sourceLocation: sourceLocation)\n        }\n    }\n\n    final class ModuleDependencyResult {\n        let dependency: PackageModel.Module.Dependency\n\n        fileprivate init(_ dependency: PackageModel.Module.Dependency) {\n            self.dependency = dependency\n        }\n\n        func checkConditions(satisfy environment: BuildEnvironment, sourceLocation: SourceLocation = #_sourceLocation) {\n            #expect(dependency.conditions.allSatisfy { $0.satisfies(environment) }, sourceLocation: sourceLocation)\n        }\n\n        func checkConditions(\n            dontSatisfy environment: BuildEnvironment,\n            sourceLocation: SourceLocation = #_sourceLocation\n        ) {\n            #expect(!dependency.conditions.allSatisfy { $0.satisfies(environment) }, sourceLocation: sourceLocation)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PkgConfigAllowlistTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport XCTest\n\nfinal class PkgConfigAllowlistTests: XCTestCase {\n    func testSimpleFlags() throws {\n        let cFlags = [\"-I/usr/local/Cellar/gtk+3/3.18.9/include/gtk-3.0\"]\n        let libs = [\"-L/usr/local/Cellar/gtk+3/3.18.9/lib\", \"-lgtk-3\", \"-w\"]\n        XCTAssertTrue(try allowlist(pcFile: \"dummy\", flags: (cFlags, libs)).disallowed.isEmpty)\n    }\n\n    func testFlagsWithInvalidFlags() throws {\n        let cFlags = [\"-I/usr/local/Cellar/gtk+3/3.18.9/include/gtk-3.0\", \"-L/hello\"]\n        let libs = [\"-L/usr/local/Cellar/gtk+3/3.18.9/lib\", \"-lgtk-3\", \"-module-name\", \"name\", \"-werror\"]\n        let disallowed = try allowlist(pcFile: \"dummy\", flags: (cFlags, libs)).disallowed\n        XCTAssertEqual(disallowed, [\"-L/hello\", \"-module-name\", \"name\", \"-werror\"])\n    }\n\n    func testFlagsWithValueInNextFlag() throws {\n        let cFlags = [\"-I/usr/local\", \"-I\", \"/usr/local/Cellar/gtk+3/3.18.9/include/gtk-3.0\", \"-L/hello\"]\n        let libs = [\"-L\", \"/usr/lib\", \"-L/usr/local/Cellar/gtk+3/3.18.9/lib\", \"-lgtk-3\", \"-module-name\", \"-lcool\", \"ok\", \"name\"]\n        let disallowed = try allowlist(pcFile: \"dummy\", flags: (cFlags, libs)).disallowed\n        XCTAssertEqual(disallowed, [\"-L/hello\", \"-module-name\", \"ok\", \"name\"])\n    }\n\n    func testRemoveDefaultFlags() throws {\n        let cFlags = [\"-I/usr/include\", \"-I\", \"/usr/include\" , \"-I\", \"/usr/include/Cellar/gtk+3/3.18.9/include/gtk-3.0\", \"-L/hello\", \"-I\", \"/usr/include\"]\n        let libs = [\"-L\", \"/usr/lib\", \"-L/usr/lib/Cellar/gtk+3/3.18.9/lib\", \"-L/usr/lib\", \"-L/usr/lib\", \"-lgtk-3\", \"-module-name\", \"-lcool\", \"ok\", \"name\", \"-L\", \"/usr/lib\"]\n        let result = try removeDefaultFlags(cFlags: cFlags, libs: libs)\n\n        XCTAssertEqual(result.0, [\"-I\", \"/usr/include/Cellar/gtk+3/3.18.9/include/gtk-3.0\", \"-L/hello\"])\n        XCTAssertEqual(result.1, [\"-L/usr/lib/Cellar/gtk+3/3.18.9/lib\", \"-lgtk-3\", \"-module-name\", \"-lcool\", \"ok\", \"name\"])\n    }\n\n    func testPathSDKPaths() throws {\n        let flags = [\"-I/opt/homebrew/Cellar/cairo/1.16.0_5/include/cairo\", \"-I/Library/Developer/CommandLineTools/SDKs/MacOSX13.sdk/usr/include/ffi\"]\n        let sdk = AbsolutePath(\"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.3.sdk\")\n        let result = try patchSDKPaths(in: flags, to: sdk)\n\n        XCTAssertEqual(result, [\"-I/opt/homebrew/Cellar/cairo/1.16.0_5/include/cairo\", \"-I\\(sdk)/usr/include/ffi\"])\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PkgConfigParserTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import PackageLoading\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCBasic.ByteString\n\nfinal class PkgConfigParserTests: XCTestCase {\n    func testCircularPCFile() throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        _ = try PkgConfig(\n            name: \"harfbuzz\",\n            additionalSearchPaths: [AbsolutePath(#file).parentDirectory.appending(components: \"pkgconfigInputs\")],\n            fileSystem: localFileSystem,\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .equal(\"circular dependency detected while parsing harfbuzz: harfbuzz -> freetype2 -> harfbuzz\"), severity: .warning)\n        }\n    }\n\n    func testGTK3PCFile() throws {\n        try! loadPCFile(\"gtk+-3.0.pc\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"libdir\": \"/usr/local/Cellar/gtk+3/3.18.9/lib\",\n                \"gtk_host\": \"x86_64-apple-darwin15.3.0\",\n                \"includedir\": \"/usr/local/Cellar/gtk+3/3.18.9/include\",\n                \"prefix\": \"/usr/local/Cellar/gtk+3/3.18.9\",\n                \"gtk_binary_version\": \"3.0.0\",\n                \"exec_prefix\": \"/usr/local/Cellar/gtk+3/3.18.9\",\n                \"targets\": \"quartz\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": AbsolutePath.root.pathString\n            ])\n            XCTAssertEqual(parser.dependencies, [\"gdk-3.0\", \"atk\", \"cairo\", \"cairo-gobject\", \"gdk-pixbuf-2.0\", \"gio-2.0\"])\n            XCTAssertEqual(parser.privateDependencies, [\"atk\", \"epoxy\", \"gio-unix-2.0\"])\n            XCTAssertEqual(parser.cFlags, [\"-I/usr/local/Cellar/gtk+3/3.18.9/include/gtk-3.0\"])\n            XCTAssertEqual(parser.libs, [\"-L/usr/local/Cellar/gtk+3/3.18.9/lib\", \"-lgtk-3\"])\n        }\n    }\n\n    func testEmptyCFlags() throws {\n        try! loadPCFile(\"empty_cflags.pc\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"prefix\": \"/usr/local/bin\",\n                \"exec_prefix\": \"/usr/local/bin\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": AbsolutePath.root.pathString\n            ])\n            XCTAssertEqual(parser.dependencies, [\"gdk-3.0\", \"atk\"])\n            XCTAssertEqual(parser.cFlags, [])\n            XCTAssertEqual(parser.libs, [\"-L/usr/local/bin\", \"-lgtk-3\"])\n        }\n    }\n\n    func testCFlagsCaseInsensitveKeys() throws {\n        try! loadPCFile(\"case_insensitive.pc\") { parser in\n            XCTAssertEqual(parser.cFlags, [\"-I/usr/local/include\"])\n        }\n    }\n\n    func testVariableinDependency() throws {\n        try! loadPCFile(\"deps_variable.pc\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"prefix\": \"/usr/local/bin\",\n                \"exec_prefix\": \"/usr/local/bin\",\n                \"my_dep\": \"atk\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": AbsolutePath.root.pathString\n            ])\n            XCTAssertEqual(parser.dependencies, [\"gdk-3.0\", \"atk\"])\n            XCTAssertEqual(parser.cFlags, [\"-I\"])\n            XCTAssertEqual(parser.libs, [\"-L/usr/local/bin\", \"-lgtk-3\"])\n        }\n    }\n\n    func testUnresolvablePCFile() throws {\n        do {\n            try loadPCFile(\"failure_case.pc\")\n            XCTFail(\"Unexpected success\")\n        } catch PkgConfigError.parsingError(let desc) {\n            XCTAssert(desc.hasPrefix(\"Expected a value for variable\"))\n        }\n    }\n\n    func testEscapedSpaces() throws {\n        try! loadPCFile(\"escaped_spaces.pc\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"prefix\": \"/usr/local/bin\",\n                \"exec_prefix\": \"/usr/local/bin\",\n                \"my_dep\": \"atk\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": AbsolutePath.root.pathString\n            ])\n            XCTAssertEqual(parser.dependencies, [\"gdk-3.0\", \"atk\"])\n            XCTAssertEqual(parser.cFlags, [\"-I/usr/local/Wine Cellar/gtk+3/3.18.9/include/gtk-3.0\", \"-I/after/extra/spaces\"])\n            XCTAssertEqual(parser.libs, [\"-L/usr/local/bin\", \"-lgtk 3\", \"-wantareal\\\\here\", \"-one\\\\\", \"-two\"])\n        }\n    }\n\n    func testDummyDependency() throws {\n        try loadPCFile(\"dummy_dependency.pc\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"prefix\": \"/usr/local/bin\",\n                \"exec_prefix\": \"/usr/local/bin\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": AbsolutePath.root.pathString\n            ])\n            XCTAssertEqual(parser.dependencies, [\"pango\", \"fontconfig\"])\n            XCTAssertEqual(parser.cFlags, [])\n            XCTAssertEqual(parser.libs, [\"-L/usr/local/bin\", \"-lpangoft2-1.0\"])\n        }\n    }\n\n    /// Test custom search path get higher priority for locating pc files.\n    func testCustomPcFileSearchPath() throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        /// Temporary workaround for PCFileFinder's use of static variables.\n        PCFileFinder.resetCachedPkgConfigPaths()\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/usr/lib/pkgconfig/foo.pc\",\n            \"/usr/local/opt/foo/lib/pkgconfig/foo.pc\",\n            \"/custom/foo.pc\")\n        XCTAssertEqual(\n            \"/custom/foo.pc\",\n            try PCFileFinder().locatePCFile(name: \"foo\", customSearchPaths: [\"/custom\"], fileSystem: fs, observabilityScope: observability.topScope)\n        )\n        XCTAssertEqual(\n            \"/custom/foo.pc\",\n            try PkgConfig(name: \"foo\", additionalSearchPaths: [\"/custom\"], fileSystem: fs, observabilityScope: observability.topScope).pcFile\n        )\n        XCTAssertEqual(\n            \"/usr/lib/pkgconfig/foo.pc\",\n            try PCFileFinder().locatePCFile(name: \"foo\", customSearchPaths: [], fileSystem: fs, observabilityScope: observability.topScope)\n        )\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": \"/usr/local/opt/foo/lib/pkgconfig\"]) {\n            XCTAssertEqual(\"/usr/local/opt/foo/lib/pkgconfig/foo.pc\", try PkgConfig(name: \"foo\", fileSystem: fs, observabilityScope: observability.topScope).pcFile)\n        }\n#if os(Windows)\n        let separator = \";\"\n#else\n        let separator = \":\"\n#endif\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": \"/usr/local/opt/foo/lib/pkgconfig\\(separator)/usr/lib/pkgconfig\"]) {\n            XCTAssertEqual(\"/usr/local/opt/foo/lib/pkgconfig/foo.pc\", try PkgConfig(name: \"foo\", fileSystem: fs, observabilityScope: observability.topScope).pcFile)\n        }\n    }\n\n    func testBrewPrefix() throws {\n        /// Temporary workaround for PCFileFinder's use of static variables.\n        PCFileFinder.resetCachedPkgConfigPaths()\n\n        try testWithTemporaryDirectory { tmpdir in\n#if os(Windows)\n            let fakePkgConfig = tmpdir.appending(components: \"bin\", \"pkg-config.cmd\")\n#else\n            let fakePkgConfig = tmpdir.appending(components: \"bin\", \"pkg-config\")\n#endif\n            try localFileSystem.createDirectory(fakePkgConfig.parentDirectory)\n\n#if os(Windows)\n            let script = \"\"\"\n            @echo off\n            echo /Volumes/BestDrive/pkgconfig\n            \"\"\"\n#else\n            let script = \"\"\"\n            #!/bin/sh\n            echo \"/Volumes/BestDrive/pkgconfig\"\n            \"\"\"\n#endif\n            try localFileSystem.writeFileContents(fakePkgConfig, string: script)\n            try localFileSystem.chmod(.executable, path: fakePkgConfig, options: [])\n\n#if os(Windows)\n            _ = PCFileFinder(pkgConfig: fakePkgConfig)\n#else\n            _ = PCFileFinder(brewPrefix: fakePkgConfig.parentDirectory.parentDirectory)\n#endif\n        }\n\n        XCTAssertEqual(PCFileFinder.pkgConfigPaths, [\"/Volumes/BestDrive/pkgconfig\"])\n    }\n\n    func testAbsolutePathDependency() throws {\n        let libffiPath = \"/usr/local/opt/libffi/lib/pkgconfig/libffi.pc\"\n\n        try loadPCFile(\"gobject-2.0.pc\") { parser in\n            XCTAssert(parser.dependencies.isEmpty)\n            XCTAssertEqual(parser.privateDependencies, [libffiPath])\n        }\n\n        try loadPCFile(\"libffi.pc\") { parser in\n            XCTAssert(parser.dependencies.isEmpty)\n            XCTAssert(parser.privateDependencies.isEmpty)\n        }\n\n        let fileSystem = try InMemoryFileSystem(\n            files: [\n                \"/usr/local/opt/glib/lib/pkgconfig/gobject-2.0.pc\": pcFileByteString(\"gobject-2.0.pc\"),\n                libffiPath: pcFileByteString(\"libffi.pc\")\n            ]\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        XCTAssertNoThrow(\n            try PkgConfig(\n                name: \"gobject-2.0\",\n                additionalSearchPaths: [\"/usr/local/opt/glib/lib/pkgconfig\"],\n                brewPrefix: \"/usr/local\",\n                fileSystem: fileSystem,\n                observabilityScope: observability.topScope\n            )\n        )\n    }\n\n    func testUnevenQuotes() throws {\n        do {\n            try loadPCFile(\"quotes_failure.pc\")\n            XCTFail(\"Unexpected success\")\n        } catch PkgConfigError.parsingError(let desc) {\n            XCTAssert(desc.hasPrefix(\"Text ended before matching quote\"))\n        }\n    }\n\n    func testSysrootDir() throws {\n        // sysroot should be prepended to all path variables, and should therefore appear in cflags and libs.\n        try loadPCFile(\"gtk+-3.0.pc\", sysrootDir: \"/opt/sysroot/somewhere\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"libdir\": \"/opt/sysroot/somewhere/usr/local/Cellar/gtk+3/3.18.9/lib\",\n                \"gtk_host\": \"x86_64-apple-darwin15.3.0\",\n                \"includedir\": \"/opt/sysroot/somewhere/usr/local/Cellar/gtk+3/3.18.9/include\",\n                \"prefix\": \"/opt/sysroot/somewhere/usr/local/Cellar/gtk+3/3.18.9\",\n                \"gtk_binary_version\": \"3.0.0\",\n                \"exec_prefix\": \"/opt/sysroot/somewhere/usr/local/Cellar/gtk+3/3.18.9\",\n                \"targets\": \"quartz\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": \"/opt/sysroot/somewhere\"\n            ])\n            XCTAssertEqual(parser.dependencies, [\"gdk-3.0\", \"atk\", \"cairo\", \"cairo-gobject\", \"gdk-pixbuf-2.0\", \"gio-2.0\"])\n            XCTAssertEqual(parser.privateDependencies, [\"atk\", \"epoxy\", \"gio-unix-2.0\"])\n            XCTAssertEqual(parser.cFlags, [\"-I/opt/sysroot/somewhere/usr/local/Cellar/gtk+3/3.18.9/include/gtk-3.0\"])\n            XCTAssertEqual(parser.libs, [\"-L/opt/sysroot/somewhere/usr/local/Cellar/gtk+3/3.18.9/lib\", \"-lgtk-3\"])\n        }\n\n        // sysroot should be not be prepended if it is already a prefix\n        // - pkgconf makes this check, but pkg-config does not\n        // - If the .pc file lies outside sysrootDir, pkgconf sets pc_sysrootdir to the empty string\n        //      https://github.com/pkgconf/pkgconf/issues/213\n        //   SwiftPM does not currently implement this special case.\n        try loadPCFile(\"gtk+-3.0.pc\", sysrootDir: \"/usr/local/Cellar\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"libdir\": \"/usr/local/Cellar/gtk+3/3.18.9/lib\",\n                \"gtk_host\": \"x86_64-apple-darwin15.3.0\",\n                \"includedir\": \"/usr/local/Cellar/gtk+3/3.18.9/include\",\n                \"prefix\": \"/usr/local/Cellar/gtk+3/3.18.9\",\n                \"gtk_binary_version\": \"3.0.0\",\n                \"exec_prefix\": \"/usr/local/Cellar/gtk+3/3.18.9\",\n                \"targets\": \"quartz\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": \"/usr/local/Cellar\"\n            ])\n            XCTAssertEqual(parser.dependencies, [\"gdk-3.0\", \"atk\", \"cairo\", \"cairo-gobject\", \"gdk-pixbuf-2.0\", \"gio-2.0\"])\n            XCTAssertEqual(parser.privateDependencies, [\"atk\", \"epoxy\", \"gio-unix-2.0\"])\n            XCTAssertEqual(parser.cFlags, [\"-I/usr/local/Cellar/gtk+3/3.18.9/include/gtk-3.0\"])\n            XCTAssertEqual(parser.libs, [\"-L/usr/local/Cellar/gtk+3/3.18.9/lib\", \"-lgtk-3\"])\n        }\n\n        // sysroot should be not be double-prepended if it is used explicitly by the .pc file\n        // - pkgconf makes this check, but pkg-config does not\n        try loadPCFile(\"double_sysroot.pc\", sysrootDir: \"/sysroot\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"prefix\": \"/sysroot/usr\",\n                \"datarootdir\": \"/sysroot/usr/share\",\n                \"pkgdatadir\": \"/sysroot/usr/share/pkgdata\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": \"/sysroot\"\n            ])\n        }\n\n        // pkgconfig strips a leading sysroot prefix if sysroot appears anywhere else in the\n        // expanded variable.   SwiftPM's implementation is faithful to pkgconfig, even\n        // thought it might seem more logical not to strip the prefix in this case.\n        try loadPCFile(\"not_double_sysroot.pc\", sysrootDir: \"/sysroot\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"prefix\": \"/sysroot/usr\",\n                \"datarootdir\": \"/sysroot/usr/share\",\n                \"pkgdatadir\": \"/filler/sysroot/usr/share/pkgdata\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": \"/sysroot\"\n            ])\n        }\n\n        // pkgconfig does not strip sysroot if it is a relative path\n        try loadPCFile(\"double_sysroot.pc\", sysrootDir: \"sysroot\") { parser in\n            XCTAssertEqual(parser.variables, [\n                \"prefix\": \"sysroot/usr\",\n                \"datarootdir\": \"sysroot/usr/share\",\n                \"pkgdatadir\": \"sysroot/sysroot/usr/share/pkgdata\",\n                \"pcfiledir\": parser.pcFile.parentDirectory.pathString,\n                \"pc_sysrootdir\": \"sysroot\"\n            ])\n        }\n    }\n\n    private func pcFilePath(_ inputName: String) -> AbsolutePath {\n        return AbsolutePath(#file).parentDirectory.appending(components: \"pkgconfigInputs\", inputName)\n    }\n\n    private func loadPCFile(_ inputName: String, sysrootDir: String? = nil, body: ((PkgConfigParser) -> Void)? = nil) throws {\n        var parser = try PkgConfigParser(pcFile: pcFilePath(inputName), fileSystem: localFileSystem, sysrootDir: sysrootDir)\n        try parser.parse()\n        body?(parser)\n    }\n\n    private func pcFileByteString(_ inputName: String) throws -> ByteString {\n        return try localFileSystem.readFileContents(pcFilePath(inputName))\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/PkgConfigTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nextension SystemLibraryModule {\n    convenience init(pkgConfig: String, providers: [SystemPackageProviderDescription] = []) {\n        self.init(\n            name: \"Foo\",\n            path: \"/fake\",\n            pkgConfig: pkgConfig.isEmpty ? nil : pkgConfig,\n            providers: providers.isEmpty ? nil : providers)\n    }\n}\n\nclass PkgConfigTests: XCTestCase {\n    let inputsDir = AbsolutePath(#file).parentDirectory.appending(components: \"Inputs\")\n    let observability = ObservabilitySystem.makeForTesting()\n    let fs = localFileSystem\n\n    func testBasics() throws {\n        // No pkgConfig name.\n        do {\n            let result = try pkgConfigArgs(\n                for: SystemLibraryModule(pkgConfig: \"\"),\n                pkgConfigDirectories: [],\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            XCTAssertTrue(result.isEmpty)\n        }\n\n        // No pc file.\n        do {\n            let target = SystemLibraryModule(\n                pkgConfig: \"Foo\",\n                providers: [\n                    .brew([\"libFoo\"]),\n                    .apt([\"libFoo-dev\"]),\n                    .yum([\"libFoo-devel\"]),\n                    .nuget([\"Foo\"]),\n                ]\n            )\n            for result in try pkgConfigArgs(\n                for: target,\n                pkgConfigDirectories: [],\n                fileSystem: fs,\n                observabilityScope: observability.topScope) {\n                XCTAssertEqual(result.pkgConfigName, \"Foo\")\n                XCTAssertEqual(result.cFlags, [])\n                XCTAssertEqual(result.libs, [])\n                switch result.provider {\n                case .brew(let names)?:\n                    XCTAssertEqual(names, [\"libFoo\"])\n                case .apt(let names)?:\n                    XCTAssertEqual(names, [\"libFoo-dev\"])\n                case .yum(let names)?:\n                    XCTAssertEqual(names, [\"libFoo-devel\"])\n                case .nuget(let names)?:\n                    XCTAssertEqual(names, [\"Foo\"])\n                case .pkg(let names)?:\n                    XCTAssertEqual(names, [\"Foo\"])\n                case nil:\n                    XCTFail(\"Expected a provider here\")\n                }\n                XCTAssertTrue(result.couldNotFindConfigFile)\n                switch result.error {\n                case PkgConfigError.couldNotFindConfigFile?: break\n                default:\n                    XCTFail(\"Unexpected error \\(String(describing: result.error))\")\n                }\n            }\n        }\n    }\n\n    func testEnvVar() throws {\n        // Pc file.\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": inputsDir.pathString]) {\n            for result in try pkgConfigArgs(\n                for: SystemLibraryModule(pkgConfig: \"Foo\"),\n                pkgConfigDirectories: [],\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ) {\n                XCTAssertEqual(result.pkgConfigName, \"Foo\")\n                XCTAssertEqual(result.cFlags, [\"-I/path/to/inc\", \"-I\\(inputsDir.pathString)\"])\n                XCTAssertEqual(result.libs, [\"-L/usr/da/lib\", \"-lSystemModule\", \"-lok\"])\n                XCTAssertNil(result.provider)\n                XCTAssertNil(result.error)\n                XCTAssertFalse(result.couldNotFindConfigFile)\n            }\n        }\n\n        // Pc file with prohibited flags.\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": inputsDir.pathString]) {\n            for result in try pkgConfigArgs(\n                for: SystemLibraryModule(pkgConfig: \"Bar\"),\n                pkgConfigDirectories: [],\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ) {\n                XCTAssertEqual(result.pkgConfigName, \"Bar\")\n                XCTAssertEqual(result.cFlags, [\"-I/path/to/inc\"])\n                XCTAssertEqual(result.libs, [\"-L/usr/da/lib\", \"-lSystemModule\", \"-lok\"])\n                XCTAssertNil(result.provider)\n                XCTAssertFalse(result.couldNotFindConfigFile)\n                switch result.error {\n                case PkgConfigError.prohibitedFlags(let desc)?:\n                    XCTAssertEqual(desc, \"-DDenyListed\")\n                default:\n                    XCTFail(\"unexpected error \\(result.error.debugDescription)\")\n                }\n            }\n        }\n\n        // Pc file with -framework Framework flag.\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": inputsDir.pathString]) {\n            for result in try pkgConfigArgs(\n                for: SystemLibraryModule(pkgConfig: \"Framework\"),\n                pkgConfigDirectories: [],\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            ) {\n                XCTAssertEqual(result.pkgConfigName, \"Framework\")\n                XCTAssertEqual(result.cFlags, [\"-F/usr/lib\"])\n                XCTAssertEqual(result.libs, [\"-F/usr/lib\", \"-framework\", \"SystemFramework\"])\n                XCTAssertNil(result.provider)\n                XCTAssertFalse(result.couldNotFindConfigFile)\n                switch result.error {\n                case PkgConfigError.prohibitedFlags(let desc)?:\n                    XCTAssertEqual(desc, \"-DDenyListed\")\n                default:\n                    XCTFail(\"unexpected error \\(result.error.debugDescription)\")\n                }\n            }\n        }\n    }\n\n    func testExplicitPkgConfigDirectories() throws {\n        // Pc file.\n        for result in try pkgConfigArgs(\n            for: SystemLibraryModule(pkgConfig: \"Foo\"),\n            pkgConfigDirectories: [inputsDir],\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ) {\n            XCTAssertEqual(result.pkgConfigName, \"Foo\")\n            XCTAssertEqual(result.cFlags, [\"-I/path/to/inc\", \"-I\\(inputsDir.pathString)\"])\n            XCTAssertEqual(result.libs, [\"-L/usr/da/lib\", \"-lSystemModule\", \"-lok\"])\n            XCTAssertNil(result.provider)\n            XCTAssertNil(result.error)\n            XCTAssertFalse(result.couldNotFindConfigFile)\n        }\n\n        // Pc file with prohibited flags.\n        for result in try pkgConfigArgs(\n            for: SystemLibraryModule(pkgConfig: \"Bar\"),\n            pkgConfigDirectories: [inputsDir],\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ) {\n            XCTAssertEqual(result.pkgConfigName, \"Bar\")\n            XCTAssertEqual(result.cFlags, [\"-I/path/to/inc\"])\n            XCTAssertEqual(result.libs, [\"-L/usr/da/lib\", \"-lSystemModule\", \"-lok\"])\n            XCTAssertNil(result.provider)\n            XCTAssertFalse(result.couldNotFindConfigFile)\n            switch result.error {\n            case PkgConfigError.prohibitedFlags(let desc)?:\n                XCTAssertEqual(desc, \"-DDenyListed\")\n            default:\n                XCTFail(\"unexpected error \\(result.error.debugDescription)\")\n            }\n        }\n\n        // Pc file with -framework Framework flag.\n        let observability = ObservabilitySystem.makeForTesting()\n        for result in try pkgConfigArgs(\n            for: SystemLibraryModule(pkgConfig: \"Framework\"),\n            pkgConfigDirectories: [inputsDir],\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        ) {\n            XCTAssertEqual(result.pkgConfigName, \"Framework\")\n            XCTAssertEqual(result.cFlags, [\"-F/usr/lib\"])\n            XCTAssertEqual(result.libs, [\"-F/usr/lib\", \"-framework\", \"SystemFramework\"])\n            XCTAssertNil(result.provider)\n            XCTAssertFalse(result.couldNotFindConfigFile)\n            switch result.error {\n            case PkgConfigError.prohibitedFlags(let desc)?:\n                XCTAssertEqual(desc, \"-DDenyListed\")\n            default:\n                XCTFail(\"unexpected error \\(result.error.debugDescription)\")\n            }\n        }\n    }\n\n    func testDependencies() throws {\n        // Use additionalSearchPaths instead of pkgConfigArgs to test handling\n        // of search paths when loading dependencies.\n        let result = try PkgConfig(\n            name: \"Dependent\",\n            additionalSearchPaths: [inputsDir],\n            fileSystem: localFileSystem,\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertEqual(result.name, \"Dependent\")\n        XCTAssertEqual(result.cFlags, [\"-I/path/to/dependent/include\", \"-I/path/to/dependency/include\"])\n        XCTAssertEqual(result.libs, [\"-L/path/to/dependent/lib\", \"-L/path/to/dependency/lib\"])\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/TargetSourcesBuilderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\nimport PackageLoading\nimport _InternalTestSupport\nimport XCTest\n\nfinal class TargetSourcesBuilderTests: XCTestCase {\n    func testBasicFileContentsComputation() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [\"some2\"],\n            sources: nil,\n            resources: [\n                .init(rule: .copy, path: \"some/path/toBeCopied\")\n            ],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/Foo.swift\",\n            \"/Bar.swift\",\n            \"/some/path.swift\",\n            \"/some2/path2.swift\",\n            \"/.some2/hello.swift\",\n            \"/Hello.something/hello.txt\",\n            \"/file\",\n            \"/path/to/file.xcodeproj/pbxproj\",\n            \"/path/to/somefile.txt\",\n            \"/some/path/toBeCopied/cool/hello.swift\",\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root(.root),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            toolsVersion: .v5,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let contents = builder.computeContents().sorted()\n\n        XCTAssertEqual(contents, [\n            \"/Bar.swift\",\n            \"/Foo.swift\",\n            \"/Hello.something/hello.txt\",\n            \"/file\",\n            \"/path/to/somefile.txt\",\n            \"/some/path.swift\",\n            \"/some/path/toBeCopied\",\n        ])\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testDirectoryWithExt_5_3() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: nil,\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/some/hello.swift\",\n            \"/some.thing/hello.txt\",\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root(.root),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            toolsVersion: .v5_3,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let contents = builder.computeContents().sorted()\n\n        XCTAssertEqual(contents, [\n            \"/some.thing\",\n            \"/some/hello.swift\",\n        ])\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testDirectoryWithExt_5_6() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: nil,\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/some/hello.swift\",\n            \"/some.thing/hello.txt\",\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root(.root),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            toolsVersion: .v5_6,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let contents = builder.computeContents().sorted()\n\n        XCTAssertEqual(contents, [\n            \"/some.thing/hello.txt\",\n            \"/some/hello.swift\",\n        ])\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testSpecialDirectoryWithExt_5_6() throws {\n        let root = AbsolutePath.root\n\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: nil,\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            root.appending(components: \"some.xcassets\", \"hello.txt\").pathString,\n            root.appending(components: \"some\", \"hello.swift\").pathString\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root(.root),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            toolsVersion: .v5_6,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let contents = builder.computeContents().sorted()\n\n        XCTAssertEqual(contents, [\n            root.appending(components: \"some.xcassets\"),\n            root.appending(components: \"some\", \"hello.swift\"),\n        ])\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testBasicRuleApplication() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [\"some2\"],\n            sources: nil,\n            resources: [\n                .init(rule: .process(localization: .none), path: \"path\"),\n                .init(rule: .copy, path: \"some/path/toBeCopied\"),\n            ],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/Foo.swift\",\n            \"/Bar.swift\",\n            \"/some/path.swift\",\n            \"/some2/path2.swift\",\n            \"/.some2/hello.swift\",\n            \"/Hello.something/hello.txt\",\n            \"/file\",\n            \"/path/to/file.xcodeproj/pbxproj\",\n            \"/path/to/somefile.txt\",\n            \"/path/to/somefile2.txt\",\n            \"/some/path/toBeCopied/cool/hello.swift\",\n        ])\n\n        let somethingRule = FileRuleDescription(\n            rule: .processResource(localization: .none),\n            toolsVersion: .minimumRequired,\n            fileTypes: [\"something\"])\n\n        build(target: target, additionalFileRules: [somethingRule], toolsVersion: .v5, fs: fs) { _, _, _, _, _, _, _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testDoesNotErrorWithAdditionalFileRules() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: nil,\n            resources: [],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let files: [AbsolutePath] = [\n            \"/Foo.swift\",\n            \"/Bar.swift\",\n            \"/Baz.something\",\n        ]\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: files.map(\\.pathString))\n\n        let somethingRule = FileRuleDescription(\n            rule: .compile,\n            toolsVersion: .v5_5,\n            fileTypes: [\"something\"]\n        )\n\n        build(target: target, additionalFileRules: [somethingRule], toolsVersion: .v5_5, fs: fs) { sources, _, _, _, _, _, _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(\n                sources.paths.sorted(),\n                files.sorted()\n            )\n        }\n    }\n\n    func testResourceConflicts() throws {\n        // Conflict between processed resources.\n\n        do {\n            let target = try TargetDescription(name: \"Foo\", resources: [\n                .init(rule: .process(localization: .none), path: \"Resources\")\n            ])\n\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Resources/foo.txt\",\n                \"/Resources/Sub/foo.txt\"\n            )\n\n            build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                testDiagnostics(diagnostics, problemsOnly: false) { result in\n                    var diagnosticsFound = [Basics.Diagnostic?]()\n                    diagnosticsFound.append(result.check(diagnostic: \"multiple resources named 'foo.txt' in target 'Foo'\", severity: .error))\n                    diagnosticsFound.append(result.checkUnordered(diagnostic: \"found '\\(RelativePath(\"Resources\").appending(components: \"foo.txt\"))'\", severity: .info))\n                    diagnosticsFound.append(result.checkUnordered(diagnostic: \"found '\\(RelativePath(\"Resources\").appending(components: \"Sub\", \"foo.txt\"))'\", severity: .info))\n\n                    for diagnostic in diagnosticsFound {\n                        XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                        XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                        XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                    }\n                }\n            }\n        }\n\n        // Conflict between processed and copied resources.\n\n        do {\n            let target = try TargetDescription(name: \"Foo\", resources: [\n                .init(rule: .process(localization: .none), path: \"Processed\"),\n                .init(rule: .copy, path: \"Copied/foo.txt\"),\n            ])\n\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Processed/foo.txt\",\n                \"/Copied/foo.txt\"\n            )\n\n            build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                testDiagnostics(diagnostics, problemsOnly: false) { result in\n                    var diagnosticsFound = [Basics.Diagnostic?]()\n                    diagnosticsFound.append(result.check(diagnostic: \"multiple resources named 'foo.txt' in target 'Foo'\", severity: .error))\n                    diagnosticsFound.append(result.checkUnordered(diagnostic: \"found '\\(RelativePath(\"Processed\").appending(components: \"foo.txt\"))'\", severity: .info))\n                    diagnosticsFound.append(result.checkUnordered(diagnostic: \"found '\\(RelativePath(\"Copied\").appending(components: \"foo.txt\"))'\", severity: .info))\n\n                    for diagnostic in diagnosticsFound {\n                        XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                        XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                        XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                    }\n                }\n            }\n        }\n\n        // No conflict between processed and copied in sub-path resources.\n\n        do {\n            let target = try TargetDescription(name: \"Foo\", resources: [\n                .init(rule: .process(localization: .none), path: \"Processed\"),\n                .init(rule: .copy, path: \"Copied\"),\n            ])\n\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Processed/foo.txt\",\n                \"/Copied/foo.txt\"\n            )\n\n            build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, _, _, _, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n            }\n        }\n\n        // Conflict between copied directory resources.\n\n        do {\n            let target = try TargetDescription(name: \"Foo\", resources: [\n                .init(rule: .copy, path: \"A/Copy\"),\n                .init(rule: .copy, path: \"B/Copy\"),\n            ])\n\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/A/Copy/foo.txt\",\n                \"/B/Copy/foo.txt\"\n            )\n\n            build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                testDiagnostics(diagnostics, problemsOnly: false) { result in\n                    var diagnosticsFound = [Basics.Diagnostic?]()\n                    diagnosticsFound.append(result.check(diagnostic: \"multiple resources named 'Copy' in target 'Foo'\", severity: .error))\n                    diagnosticsFound.append(result.checkUnordered(diagnostic: \"found '\\(RelativePath(\"A\").appending(components: \"Copy\"))'\", severity: .info))\n                    diagnosticsFound.append(result.checkUnordered(diagnostic: \"found '\\(RelativePath(\"B\").appending(components: \"Copy\"))'\", severity: .info))\n\n                    for diagnostic in diagnosticsFound {\n                        XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                        XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                        XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                    }\n                }\n            }\n        }\n\n        // Conflict between processed localizations.\n\n        do {\n            let target = try TargetDescription(name: \"Foo\", resources: [\n                .init(rule: .process(localization: .none), path: \"A\"),\n                .init(rule: .process(localization: .none), path: \"B\"),\n            ])\n\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/A/en.lproj/foo.txt\",\n                \"/B/EN.lproj/foo.txt\"\n            )\n\n            build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                testDiagnostics(diagnostics, problemsOnly: false) { result in\n                    var diagnosticsFound = [Basics.Diagnostic?]()\n                    diagnosticsFound.append(result.check(diagnostic: \"multiple resources named '\\(RelativePath(\"en.lproj\").appending(components: \"foo.txt\"))' in target 'Foo'\", severity: .error))\n                    diagnosticsFound.append(result.checkUnordered(diagnostic: \"found '\\(RelativePath(\"A\").appending(components: \"en.lproj\", \"foo.txt\"))'\", severity: .info))\n                    diagnosticsFound.append(result.checkUnordered(diagnostic: \"found '\\(RelativePath(\"B\").appending(components: \"EN.lproj\", \"foo.txt\"))'\", severity: .info))\n\n                    for diagnostic in diagnosticsFound {\n                        XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                        XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                        XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                    }\n                }\n            }\n        }\n\n        // Conflict between processed localizations and copied resources.\n\n        do {\n            let target = try TargetDescription(name: \"Foo\", resources: [\n                .init(rule: .process(localization: .none), path: \"A\"),\n                .init(rule: .copy, path: \"B/en.lproj\"),\n            ])\n\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/A/EN.lproj/foo.txt\",\n                \"/B/en.lproj/foo.txt\"\n            )\n\n            build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    let diagnostic = result.check(\n                        diagnostic: \"resource '\\(RelativePath(\"B\").appending(components: \"en.lproj\"))' in target 'Foo' conflicts with other localization directories\",\n                        severity: .error\n                    )\n                    XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                    XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                    XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                }\n            }\n        }\n    }\n\n    func testLocalizationDirectoryIgnoredOn5_2() throws {\n        let target = try TargetDescription(name: \"Foo\")\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/en.lproj/Localizable.strings\"\n        )\n\n        build(target: target, toolsVersion: .v5_2, fs: fs) { _, resources, _, _, _, _, _, diagnostics in\n            XCTAssert(resources.isEmpty)\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testLocalizationDirectorySubDirectory() throws {\n        let target = try TargetDescription(name: \"Foo\", resources: [\n            .init(rule: .process(localization: .none), path: \"Processed\"),\n            .init(rule: .copy, path: \"Copied\")\n        ])\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Processed/en.lproj/sub/Localizable.strings\",\n            \"/Copied/en.lproj/sub/Localizable.strings\"\n        )\n\n        build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let diagnostic = result.check(\n                    diagnostic: \"localization directory '\\(RelativePath(\"Processed\").appending(components: \"en.lproj\"))' in target 'Foo' contains sub-directories, which is forbidden\",\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n            }\n        }\n    }\n\n    func testExplicitLocalizationInLocalizationDirectory() throws {\n        let target = try TargetDescription(name: \"Foo\", resources: [\n            .init(rule: .process(localization: .base), path: \"Resources\"),\n        ])\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Resources/en.lproj/Localizable.strings\"\n        )\n\n        build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let diagnostic = result.check(\n                    diagnostic: .contains(\"\"\"\n                        resource '\\(RelativePath(\"Resources\").appending(components: \"en.lproj\", \"Localizable.strings\"))' in target 'Foo' is in a localization directory \\\n                        and has an explicit localization declaration\n                        \"\"\"),\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n            }\n        }\n    }\n\n    // rdar://86297221\n    // There is no need to validate localization exists for default localization\n    func testMissingDefaultLocalization() throws {\n        let target = try TargetDescription(name: \"Foo\", resources: [\n            .init(rule: .process(localization: .none), path: \"Resources\"),\n            .init(rule: .process(localization: .default), path: \"Image.png\"),\n            .init(rule: .process(localization: .base), path: \"Icon.png\"),\n        ])\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Resources/en.lproj/Localizable.strings\",\n            \"/Resources/en.lproj/Icon.png\",\n            \"/Resources/fr.lproj/Localizable.strings\",\n            \"/Resources/fr.lproj/Sign.png\",\n            \"/Resources/Base.lproj/Storyboard.storyboard\",\n            \"/Image.png\",\n            \"/Icon.png\"\n        )\n\n        do {\n            build(target: target, defaultLocalization: \"fr\", toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n            }\n        }\n\n        do {\n            build(target: target, defaultLocalization: \"en\", toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n            }\n        }\n    }\n\n    func testLocalizedAndUnlocalizedResources() throws {\n        let target = try TargetDescription(name: \"Foo\", resources: [\n            .init(rule: .process(localization: .none), path: \"Resources\"),\n            .init(rule: .process(localization: .default), path: \"Image.png\"),\n            .init(rule: .process(localization: .base), path: \"Icon.png\"),\n        ])\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Resources/en.lproj/Localizable.strings\",\n            \"/Resources/Localizable.strings\",\n            \"/Resources/Base.lproj/Storyboard.storyboard\",\n            \"/Resources/Storyboard.storyboard\",\n            \"/Resources/Image.png\",\n            \"/Resources/Icon.png\",\n            \"/Image.png\",\n            \"/Icon.png\"\n        )\n\n        build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                var diagnosticsFound = [Basics.Diagnostic?]()\n                diagnosticsFound.append(result.checkUnordered(\n                    diagnostic: .contains(\"resource 'Localizable.strings' in target 'Foo' has both localized and un-localized variants\"),\n                    severity: .warning\n                ))\n                diagnosticsFound.append(result.checkUnordered(\n                    diagnostic: .contains(\"resource 'Storyboard.storyboard' in target 'Foo' has both localized and un-localized variants\"),\n                    severity: .warning\n                ))\n                diagnosticsFound.append(result.checkUnordered(\n                    diagnostic: .contains(\"resource 'Image.png' in target 'Foo' has both localized and un-localized variants\"),\n                    severity: .warning\n                ))\n                diagnosticsFound.append(result.checkUnordered(\n                    diagnostic: .contains(\"resource 'Icon.png' in target 'Foo' has both localized and un-localized variants\"),\n                    severity: .warning\n                ))\n\n                for diagnostic in diagnosticsFound {\n                    XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                    XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                    XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                }\n            }\n        }\n    }\n\n    func testLocalizedResources() throws {\n        let target = try TargetDescription(name: \"Foo\", resources: [\n            .init(rule: .process(localization: .none), path: \"Processed\"),\n            .init(rule: .copy, path: \"Copied\"),\n            .init(rule: .process(localization: .base), path: \"Other/Launch.storyboard\"),\n            .init(rule: .process(localization: .default), path: \"Other/Image.png\"),\n        ])\n\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Processed/foo.txt\",\n            \"/Processed/En-uS.lproj/Localizable.stringsdict\",\n            \"/Processed/en-US.lproj/Localizable.strings\",\n            \"/Processed/fr.lproj/Localizable.strings\",\n            \"/Processed/fr.lproj/Localizable.stringsdict\",\n            \"/Processed/Base.lproj/Storyboard.storyboard\",\n            \"/Copied/en.lproj/Localizable.strings\",\n            \"/Other/Launch.storyboard\",\n            \"/Other/Image.png\"\n        )\n\n        build(target: target, defaultLocalization: \"fr\", toolsVersion: .v5_3, fs: fs) { _, resources, _,  _, _, _, _, diagnostics in\n            XCTAssertEqual(resources.sorted(by: { $0.path < $1.path }), [\n                Resource(rule: .process(localization: .none), path: \"/Processed/foo.txt\"),\n                Resource(rule: .process(localization: \"en-us\"), path: \"/Processed/En-uS.lproj/Localizable.stringsdict\"),\n                Resource(rule: .process(localization: \"en-us\"), path: \"/Processed/en-US.lproj/Localizable.strings\"),\n                Resource(rule: .process(localization: \"fr\"), path: \"/Processed/fr.lproj/Localizable.strings\"),\n                Resource(rule: .process(localization: \"fr\"), path: \"/Processed/fr.lproj/Localizable.stringsdict\"),\n                Resource(rule: .process(localization: \"Base\"), path: \"/Processed/Base.lproj/Storyboard.storyboard\"),\n                Resource(rule: .copy, path: \"/Copied\"),\n                Resource(rule: .process(localization: \"Base\"), path: \"/Other/Launch.storyboard\"),\n                Resource(rule: .process(localization: \"fr\"), path: \"/Other/Image.png\"),\n            ].sorted(by: { $0.path < $1.path }))\n        }\n    }\n\n    func testLocalizedImage() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Foo/fr.lproj/Image.png\",\n            \"/Foo/es.lproj/Image.png\"\n        )\n\n        build(target: try TargetDescription(name: \"Foo\"), defaultLocalization: \"fr\", toolsVersion: .v5_3, fs: fs) { _, resources, _, _, _, _, _, diagnostics in\n            XCTAssertEqual(resources.sorted(by: { $0.path < $1.path }), [\n                Resource(rule: .process(localization: \"fr\"), path: \"/Foo/fr.lproj/Image.png\"),\n                Resource(rule: .process(localization: \"es\"), path: \"/Foo/es.lproj/Image.png\"),\n            ].sorted(by: { $0.path < $1.path }))\n        }\n    }\n\n    func testInfoPlistResource() throws {\n        do {\n            let target = try TargetDescription(name: \"Foo\", resources: [\n                .init(rule: .process(localization: .none), path: \"Resources\"),\n            ])\n\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Resources/Processed/Info.plist\"\n            )\n\n            build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    let diagnostic = result.check(\n                        diagnostic: .contains(\"resource '\\(RelativePath(\"Resources\").appending(components: \"Processed\", \"Info.plist\"))' in target 'Foo' is forbidden\"),\n                        severity: .error\n                    )\n                    XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                    XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                    XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                }\n            }\n        }\n\n        do {\n            let target = try TargetDescription(name: \"Foo\", resources: [\n                .init(rule: .copy, path: \"Resources/Copied/Info.plist\"),\n            ])\n\n            let fs = InMemoryFileSystem(emptyFiles:\n                \"/Resources/Copied/Info.plist\"\n            )\n\n            build(target: target, toolsVersion: .v5_3, fs: fs) { _, _, _, _, identity, kind, path, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    let diagnostic = result.check(\n                        diagnostic: .contains(\"resource '\\(RelativePath(\"Resources\").appending(components: \"Copied\", \"Info.plist\"))' in target 'Foo' is forbidden\"),\n                        severity: .error\n                    )\n                    XCTAssertEqual(diagnostic?.metadata?.packageIdentity, identity)\n                    XCTAssertEqual(diagnostic?.metadata?.packageKind, kind)\n                    XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                }\n            }\n        }\n    }\n\n    func testMissingExclude() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [\"fakeDir\", \"../../fileOutsideRoot.py\"],\n            sources: nil,\n            resources: [],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/Foo.swift\",\n            \"/Bar.swift\"\n        ])\n\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let builder = TargetSourcesBuilder(\n                packageIdentity: .plain(\"test\"),\n                packageKind: .root(\"/test\"),\n                packagePath: \"/test\",\n                target: target,\n                path: .root,\n                toolsVersion: .v5,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            _ = try builder.run()\n\n            testDiagnostics(observability.diagnostics) { result in\n                var diagnosticsFound = [Basics.Diagnostic?]()\n                diagnosticsFound.append(result.checkUnordered(diagnostic: \"Invalid Exclude '\\(AbsolutePath(\"/fileOutsideRoot.py\"))': File not found.\", severity: .warning))\n                diagnosticsFound.append(result.checkUnordered(diagnostic: \"Invalid Exclude '\\(AbsolutePath(\"/fakeDir\"))': File not found.\", severity: .warning))\n\n                for diagnostic in diagnosticsFound {\n                    XCTAssertEqual(diagnostic?.metadata?.packageIdentity, builder.packageIdentity)\n                    XCTAssertEqual(diagnostic?.metadata?.packageKind, builder.packageKind)\n                    XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                }\n            }\n        }\n\n        // should not emit for \"remote\" packages\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let builder = TargetSourcesBuilder(\n                packageIdentity: .plain(\"test\"),\n                packageKind: .remoteSourceControl(SourceControlURL(\"https://some.where/foo/bar\")),\n                packagePath: \"/test\",\n                target: target,\n                path: .root,\n                toolsVersion: .v5,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            _ = try builder.run()\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n    }\n    \n    func testMissingResource() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: nil,\n            resources: [.init(rule: .copy, path: \"../../../Fake.txt\"),\n                        .init(rule: .process(localization: .none), path: \"NotReal\")],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/Foo.swift\",\n            \"/Bar.swift\"\n        ])\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let builder = TargetSourcesBuilder(\n                packageIdentity: .plain(\"test\"),\n                packageKind: .root(.root),\n                packagePath: .root,\n                target: target,\n                path: .root,\n                toolsVersion: .v5,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            _ = try builder.run()\n\n            testDiagnostics(observability.diagnostics) { result in\n                var diagnosticsFound = [Basics.Diagnostic?]()\n                diagnosticsFound.append(result.checkUnordered(diagnostic: \"Invalid Resource '../../../Fake.txt': File not found.\", severity: .warning))\n                diagnosticsFound.append(result.checkUnordered(diagnostic: \"Invalid Resource 'NotReal': File not found.\", severity: .warning))\n\n                for diagnostic in diagnosticsFound {\n                    XCTAssertEqual(diagnostic?.metadata?.packageIdentity, builder.packageIdentity)\n                    XCTAssertEqual(diagnostic?.metadata?.packageKind, builder.packageKind)\n                    XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n                }\n            }\n        }\n\n        // should not emit for \"remote\" packages\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let builder = TargetSourcesBuilder(\n                packageIdentity: .plain(\"test\"),\n                packageKind: .remoteSourceControl(SourceControlURL(\"https://some.where/foo/bar\")),\n                packagePath: .root,\n                target: target,\n                path: .root,\n                toolsVersion: .v5,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            _ = try builder.run()\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    \n    func testMissingSource() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: [\"InvalidPackage.swift\",\n                      \"DoesNotExist.swift\",\n                      \"../../Tests/InvalidPackageTests/InvalidPackageTests.swift\"],\n            resources: [],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/Foo.swift\",\n            \"/Bar.swift\"\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root(\"/test\"),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            toolsVersion: .v5,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics) { result in\n            var diagnosticsFound = [Basics.Diagnostic?]()\n            diagnosticsFound.append(result.checkUnordered(diagnostic: \"Invalid Source '\\(AbsolutePath(\"/InvalidPackage.swift\"))': File not found.\", severity: .warning))\n            diagnosticsFound.append(result.checkUnordered(diagnostic: \"Invalid Source '\\(AbsolutePath(\"/DoesNotExist.swift\"))': File not found.\", severity: .warning))\n            diagnosticsFound.append(result.checkUnordered(diagnostic: \"Invalid Source '\\(AbsolutePath(\"/Tests/InvalidPackageTests/InvalidPackageTests.swift\"))': File not found.\", severity: .warning))\n\n            for diagnostic in diagnosticsFound {\n                XCTAssertEqual(diagnostic?.metadata?.packageIdentity, builder.packageIdentity)\n                XCTAssertEqual(diagnostic?.metadata?.packageKind, builder.packageKind)\n                XCTAssertEqual(diagnostic?.metadata?.moduleName, target.name)\n            }\n        }\n    }\n\n    func testXcodeSpecificResourcesAreNotIncludedByDefault() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: [\"File.swift\"],\n            resources: [],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/File.swift\",\n            \"/Foo.xcdatamodel\"\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root( \"/test\"),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            toolsVersion: .v5_5,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let outputs = try builder.run()\n        XCTAssertEqual(outputs.sources.paths, [\"/File.swift\"])\n        XCTAssertEqual(outputs.resources, [])\n        XCTAssertEqual(outputs.ignored, [])\n        XCTAssertEqual(outputs.others, [\"/Foo.xcdatamodel\"])\n\n        XCTAssertFalse(observability.hasWarningDiagnostics)\n        XCTAssertFalse(observability.hasErrorDiagnostics)\n    }\n\n    func testUnhandledResources() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: [\"File.swift\"],\n            resources: [],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/File.swift\",\n            \"/foo.bar\"\n        ])\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let builder = TargetSourcesBuilder(\n                packageIdentity: .plain(\"test\"),\n                packageKind: .root(\"/test\"),\n                packagePath: .root,\n                target: target,\n                path: .root,\n                toolsVersion: .v5_5,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            let outputs = try builder.run()\n            XCTAssertEqual(outputs.sources.paths, [\"/File.swift\"])\n            XCTAssertEqual(outputs.resources, [])\n            XCTAssertEqual(outputs.ignored, [])\n            XCTAssertEqual(outputs.others, [\"/foo.bar\"])\n\n            XCTAssertFalse(observability.hasWarningDiagnostics)\n            XCTAssertFalse(observability.hasErrorDiagnostics)\n        }\n\n        // should not emit for \"remote\" packages\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let builder = TargetSourcesBuilder(\n                packageIdentity: .plain(\"test\"),\n                packageKind: .remoteSourceControl(SourceControlURL(\"https://some.where/foo/bar\")),\n                packagePath: .root,\n                target: target,\n                path: .root,\n                toolsVersion: .v5_5,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            _ = try builder.run()\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n        }\n    }\n\n    func testDocCFilesDoNotCauseWarningOutsideXCBuild() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: [\"File.swift\"],\n            resources: [],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/File.swift\",\n            \"/Foo.docc\"\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root(.root),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            defaultLocalization: nil,\n            additionalFileRules: FileRuleDescription.swiftpmFileTypes,\n            toolsVersion: .v5_5,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let outputs = try builder.run()\n        XCTAssertEqual(outputs.sources.paths, [\"/File.swift\"])\n        XCTAssertEqual(outputs.resources, [])\n        XCTAssertEqual(outputs.ignored, [\"/Foo.docc\"])\n        XCTAssertEqual(outputs.others, [])\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testResourcesAreSorted() throws {\n        let target = try TargetDescription(\n            name: \"Foo\",\n            path: nil,\n            exclude: [],\n            sources: [\"File.swift\"],\n            resources: [\n                .init(rule: .copy, path: \"a.txt\"),\n                .init(rule: .copy, path: \"c.txt\"),\n                .init(rule: .copy, path: \"b.txt\"),\n            ],\n            publicHeadersPath: nil,\n            type: .regular\n        )\n\n        let fs = InMemoryFileSystem()\n        fs.createEmptyFiles(at: AbsolutePath.root, files: [\n            \"/File.swift\",\n            \"/a.txt\",\n            \"/b.txt\",\n            \"/c.txt\",\n        ])\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root(.root),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            defaultLocalization: nil,\n            additionalFileRules: FileRuleDescription.swiftpmFileTypes,\n            toolsVersion: .v5_5,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let outputs = try builder.run()\n        XCTAssertEqual(outputs.sources.paths, [\"/File.swift\"])\n        XCTAssertEqual(outputs.resources, [\n            .init(rule: .copy, path: try .init(validating: \"/a.txt\")),\n            .init(rule: .copy, path: try .init(validating: \"/b.txt\")),\n            .init(rule: .copy, path: try .init(validating: \"/c.txt\")),\n        ])\n        XCTAssertEqual(outputs.ignored, [])\n        XCTAssertEqual(outputs.others, [])\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    // MARK: -  Utilities\n\n    private func build(\n        target: TargetDescription,\n        defaultLocalization: String? = nil,\n        additionalFileRules: [FileRuleDescription] = [],\n        toolsVersion: ToolsVersion,\n        fs: FileSystem,\n        file: StaticString = #file,\n        line: UInt = #line,\n        checker: (Sources, [Resource], [AbsolutePath], [AbsolutePath], PackageIdentity, PackageReference.Kind, AbsolutePath, [Basics.Diagnostic]) throws -> Void\n    ) {\n        let observability = ObservabilitySystem.makeForTesting()\n        let builder = TargetSourcesBuilder(\n            packageIdentity: .plain(\"test\"),\n            packageKind: .root(.root),\n            packagePath: .root,\n            target: target,\n            path: .root,\n            defaultLocalization: defaultLocalization,\n            additionalFileRules: additionalFileRules,\n            toolsVersion: toolsVersion,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        do {\n            let (sources, resources, headers, _, others) = try builder.run()\n            try checker(sources, resources, headers, others, builder.packageIdentity, builder.packageKind, builder.packagePath, observability.diagnostics)\n        } catch {\n            XCTFail(error.localizedDescription, file: file, line: line)\n        }\n    }\n}\n\nextension TargetSourcesBuilder {\n    public init(\n        packageIdentity: PackageIdentity,\n        packageKind: PackageReference.Kind,\n        packagePath: AbsolutePath,\n        target: TargetDescription,\n        path: AbsolutePath,\n        toolsVersion: ToolsVersion,\n        fileSystem: FileSystem,\n        observabilityScope: ObservabilityScope\n    ) {\n        self.init(\n            packageIdentity: packageIdentity,\n            packageKind: packageKind,\n            packagePath: packagePath,\n            target: target,\n            path: path,\n            defaultLocalization: .none,\n            additionalFileRules: [],\n            toolsVersion: toolsVersion,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/ToolsVersionParserTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport PackageLoading\nimport _InternalTestSupport\nimport XCTest\n\nfinal class ToolsVersionParserTests: XCTestCase {\n    func parse(_ content: String, _ body: ((ToolsVersion) -> Void)? = nil) throws {\n        let toolsVersion = try ToolsVersionParser.parse(utf8String: content)\n        body?(toolsVersion)\n    }\n\n    /// Verifies correct parsing for valid version specifications, and that the parser isn't confused by contents following the version specification.\n    func testValidVersions() throws {\n        let manifestsSnippetWithValidVersionSpecification = [\n            // No spacing surrounding the label for Swift ≥ 5.4:\n            \"//swift-tools-version:5.4.0\"              : (5, 4, 0, \"5.4.0\"),\n            \"//swift-tools-version:5.4-dev\"            : (5, 4, 0, \"5.4.0\"),\n            \"//swift-tools-version:5.8.0\"              : (5, 8, 0, \"5.8.0\"),\n            \"//swift-tools-version:5.8.0-dev.al+sha.x\" : (5, 8, 0, \"5.8.0\"),\n            \"//swift-tools-version:6.1.2\"              : (6, 1, 2, \"6.1.2\"),\n            \"//swift-tools-version:6.1.2;\"             : (6, 1, 2, \"6.1.2\"),\n            \"//swift-tools-vErsion:6.1.2;;;;;\"         : (6, 1, 2, \"6.1.2\"),\n            \"//swift-tools-version:6.1.2;x;x;x;x;x;\"   : (6, 1, 2, \"6.1.2\"),\n            \"//swift-toolS-version:5.5.2;hello\"        : (5, 5, 2, \"5.5.2\"),\n            \"//sWiFt-tOoLs-vErSiOn:5.5.2\\nkkk\\n\"       : (5, 5, 2, \"5.5.2\"),\n            // No spacing before, and 1 space (U+0020) after the label for Swift ≥ 5.4:\n            \"//swift-tools-version: 5.4.0\"              : (5, 4, 0, \"5.4.0\"),\n            \"//swift-tools-version: 5.4-dev\"            : (5, 4, 0, \"5.4.0\"),\n            \"//swift-tools-version: 5.8.0\"              : (5, 8, 0, \"5.8.0\"),\n            \"//swift-tools-version: 5.8.0-dev.al+sha.x\" : (5, 8, 0, \"5.8.0\"),\n            \"//swift-tools-version: 6.1.2\"              : (6, 1, 2, \"6.1.2\"),\n            \"//swift-tools-version: 6.1.2;\"             : (6, 1, 2, \"6.1.2\"),\n            \"//swift-tools-vErsion: 6.1.2;;;;;\"         : (6, 1, 2, \"6.1.2\"),\n            \"//swift-tools-version: 6.1.2;x;x;x;x;x;\"   : (6, 1, 2, \"6.1.2\"),\n            \"//swift-toolS-version: 5.5.2;hello\"        : (5, 5, 2, \"5.5.2\"),\n            \"//sWiFt-tOoLs-vErSiOn: 5.5.2\\nkkk\\n\"       : (5, 5, 2, \"5.5.2\"),\n            // 1 space (U+0020) before, and no spacing after the label:\n            \"// swift-tools-version:3.1\"                : (3, 1, 0, \"3.1.0\"),\n            \"// swift-tools-version:3.1-dev\"            : (3, 1, 0, \"3.1.0\"),\n            \"// swift-tools-version:5.8.0\"              : (5, 8, 0, \"5.8.0\"),\n            \"// swift-tools-version:5.8.0-dev.al+sha.x\" : (5, 8, 0, \"5.8.0\"),\n            \"// swift-tools-version:3.1.2\"              : (3, 1, 2, \"3.1.2\"),\n            \"// swift-tools-version:3.1.2;\"             : (3, 1, 2, \"3.1.2\"),\n            \"// swift-tools-vErsion:3.1.2;;;;;\"         : (3, 1, 2, \"3.1.2\"),\n            \"// swift-tools-version:3.1.2;x;x;x;x;x;\"   : (3, 1, 2, \"3.1.2\"),\n            \"// swift-toolS-version:3.5.2;hello\"        : (3, 5, 2, \"3.5.2\"),\n            \"// sWiFt-tOoLs-vErSiOn:3.5.2\\nkkk\\n\"       : (3, 5, 2, \"3.5.2\"),\n            // leading line feeds (U+000A) before the specification, and 1 space (U+0020) before and no space after the label for Swift ≥ 5.4:\n            \"\\n// swift-tools-version:6.1\"                            : (6, 1, 0, \"6.1.0\"),\n            \"\\n\\n// swift-tools-version:6.2-dev\"                      : (6, 2, 0, \"6.2.0\"),\n            \"\\n\\n\\n// swift-tools-version:5.8.0\"                      : (5, 8, 0, \"5.8.0\"),\n            \"\\n\\n\\n\\n// swift-tools-version:6.8.0-dev.al+sha.x\"       : (6, 8, 0, \"6.8.0\"),\n            \"\\n\\n\\n\\n\\n// swift-tools-version:7.1.2\"                  : (7, 1, 2, \"7.1.2\"),\n            \"\\n\\n\\n\\n\\n\\n// swift-tools-version:8.1.2;\"               : (8, 1, 2, \"8.1.2\"),\n            \"\\n\\n\\n\\n\\n\\n\\n// swift-tools-vErsion:9.1.2;;;;;\"         : (9, 1, 2, \"9.1.2\"),\n            \"\\n\\n\\n\\n\\n\\n\\n\\n// swift-tools-version:6.1.2;x;x;x;x;x;\" : (6, 1, 2, \"6.1.2\"),\n            \"\\n\\n\\n\\n\\n\\n\\n\\n\\n// swift-toolS-version:5.5.2;hello\"    : (5, 5, 2, \"5.5.2\"),\n            \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n// sWiFt-tOoLs-vErSiOn:6.5.2\\nkkk\\n\" : (6, 5, 2, \"6.5.2\"),\n            // An assortment of horizontal whitespace characters surrounding the label for Swift ≥ 5.4:\n            \"//swift-tools-version:\\u{2002}\\u{202F}\\u{3000}\\u{A0}\\u{1680}\\t\\u{2000}\\u{2001}5.4.0\"              : (5, 4, 0, \"5.4.0\"),\n            \"//\\u{2001}swift-tools-version:\\u{2002}\\u{202F}\\u{3000}\\u{A0}\\u{1680}\\t\\u{2000}5.4-dev\"            : (5, 4, 0, \"5.4.0\"),\n            \"//\\t\\u{2000}\\u{2001}swift-tools-version:\\u{2002}\\u{202F}\\u{3000}\\u{A0}\\u{1680}5.8.0\"              : (5, 8, 0, \"5.8.0\"),\n            \"//\\u{1680}\\t\\u{2000}\\u{2001}swift-tools-version:\\u{2002}\\u{202F}\\u{3000}\\u{A0}5.8.0-dev.al+sha.x\" : (5, 8, 0, \"5.8.0\"),\n            \"//\\u{A0}\\u{1680}\\t\\u{2000}\\u{2001}swift-tools-version:\\u{2002}\\u{202F}\\u{3000}6.1.2\"              : (6, 1, 2, \"6.1.2\"),\n            \"//\\u{3000}\\u{A0}\\u{1680}\\t\\u{2000}\\u{2001}swift-tools-version:\\u{2002}\\u{202F}6.1.2;\"             : (6, 1, 2, \"6.1.2\"),\n            \"//\\u{202F}\\u{3000}\\u{A0}\\u{1680}\\t\\u{2000}\\u{2001}swift-tools-vErsion:\\u{2002}6.1.2;;;;;\"         : (6, 1, 2, \"6.1.2\"),\n            \"//\\u{2002}\\u{202F}\\u{3000}\\u{A0}\\u{1680}\\t\\u{2000}\\u{2001}swift-tools-version:6.1.2;x;x;x;x;x;\"   : (6, 1, 2, \"6.1.2\"),\n            \"//\\u{2000}\\u{2002}\\u{202F}\\u{3000}\\t\\u{2001}swift-toolS-version:\\u{A0}\\u{1680}5.5.2;hello\"        : (5, 5, 2, \"5.5.2\"),\n            \"//\\u{2000}\\u{2001}\\u{2002}\\u{202F}\\u{3000}\\tsWiFt-tOoLs-vErSiOn:\\u{A0}\\u{1680}5.5.2\\nkkk\\n\"       : (5, 5, 2, \"5.5.2\"),\n            // Some leading whitespace characters, and no spacing surrounding the label for Swift ≥ 5.4:\n            \"\\u{A} //swift-tools-version:5.4.0\"                             : (5, 4, 0, \"5.4.0\"),\n            \"\\u{B}\\t\\u{A}//swift-tools-version:5.4-dev\"                     : (5, 4, 0, \"5.4.0\"),\n            \"\\u{3000}\\u{A0}\\u{C}//swift-tools-version:5.8.0\"                : (5, 8, 0, \"5.8.0\"),\n            \"\\u{2002}\\u{D}\\u{2001}//swift-tools-version:5.8.0-dev.al+sha.x\" : (5, 8, 0, \"5.8.0\"),\n            \"\\u{D}\\u{A}\\u{A0}\\u{1680}//swift-tools-version:6.1.2\"           : (6, 1, 2, \"6.1.2\"),\n            \"   \\u{85}//swift-tools-version:6.1.2;\"                         : (6, 1, 2, \"6.1.2\"),\n            \"\\u{2028}//swift-tools-vErsion:6.1.2;;;;;\"                      : (6, 1, 2, \"6.1.2\"),\n            \"\\u{202F}\\u{2029}//swift-tools-version:6.1.2;x;x;x;x;x;\"        : (6, 1, 2, \"6.1.2\"),\n            \"\\u{A}\\u{B}\\u{C}\\u{D}\\u{A}\\u{D}\\u{85}\\u{202F}\\u{2029}\\u{2001}\\u{2002}\\u{205F}\\u{85}\\u{2028}//swift-toolS-version:5.5.2;hello\" : (5, 5, 2, \"5.5.2\"),\n            \"\\u{B}  \\u{200A}\\u{D}\\u{A}\\t\\u{85}\\u{85}\\u{A}\\u{2028}\\u{2009}\\u{2001}\\u{C}//sWiFt-tOoLs-vErSiOn:5.5.2\\nkkk\\n\"                 : (5, 5, 2, \"5.5.2\"),\n            // Some leading whitespace characters, and an assortment of horizontal whitespace characters surrounding the label for Swift ≥ 5.4:\n            \"\\u{2002}\\u{202F}\\u{A}//\\u{A0}\\u{1680}\\t\\u{2004}\\u{2001} \\u{2002}swift-tools-version:\\u{3000}5.4.0\"       : (5, 4, 0, \"5.4.0\"),\n            \"\\u{B}//\\u{A0}\\u{1680}\\t\\u{2000}\\u{2001} \\u{2002}swift-tools-version:\\u{202F}\\u{3000}5.4-dev\"             : (5, 4, 0, \"5.4.0\"),\n            \"\\u{C}//\\u{A0}\\u{1680}\\t\\u{2000}\\u{2001} swift-tools-version:\\u{2002}\\u{202F}\\u{3000}5.8.0\"               : (5, 8, 0, \"5.8.0\"),\n            \"\\u{D}//\\u{A0}\\u{1680}\\t\\u{2005} \\u{202F}\\u{3000}swift-tools-version:\\u{2001}5.8.0-dev.al+sha.x\"          : (5, 8, 0, \"5.8.0\"),\n            \"\\u{D}\\u{A}//\\u{A0}\\u{2001} \\u{2002}\\u{202F}\\u{3000}swift-tools-version:\\u{1680}\\t\\u{2000}6.1.2\"          : (6, 1, 2, \"6.1.2\"),\n            \"\\u{85}//\\u{2000}\\u{2001} \\u{2006}\\u{202F}\\u{3000}swift-tools-version:\\u{A0}\\u{1680}\\t6.1.2;\"             : (6, 1, 2, \"6.1.2\"),\n            \"\\u{2028}//\\u{2001} \\u{2002}\\u{2007}\\u{3000}swift-tools-vErsion:\\u{A0}\\u{1680}\\t\\u{2000}6.1.2;;;;;\"       : (6, 1, 2, \"6.1.2\"),\n            \"\\u{2029}//\\u{202F}\\u{3000}swift-tools-version:\\u{A0}\\u{1680}\\t\\u{2000}\\u{2001} \\u{2002}6.1.2;x;x;x;x;x;\" : (6, 1, 2, \"6.1.2\"),\n            \"\\u{A}\\u{D}\\u{85}\\u{202F}\\u{2029}\\u{A}\\u{2028}//\\u{2000}\\u{2001}\\u{9}swift-toolS-version:\\u{A0}\\u{1680}\\t\\u{2000}\\u{2009} \\u{2002}\\u{202F}5.5.2;hello\" : (5, 5, 2, \"5.5.2\"),\n            \"\\u{D}\\u{A}\\t\\u{85}\\u{85}\\u{A}\\u{2028}\\u{2029}//\\u{2001}\\u{2002}\\u{202F}sWiFt-tOoLs-vErSiOn:\\u{1680}\\t\\u{2000}\\u{200A} \\u{2002}\\u{202F}5.5.2\\nkkk\\n\"   : (5, 5, 2, \"5.5.2\"),\n        ]\n\n        for (snippet, result) in manifestsSnippetWithValidVersionSpecification {\n            try self.parse(snippet) { toolsVersion in\n                XCTAssertEqual(toolsVersion.major, result.0)\n                XCTAssertEqual(toolsVersion.minor, result.1)\n                XCTAssertEqual(toolsVersion.patch, result.2)\n                XCTAssertEqual(toolsVersion.description, result.3)\n            }\n        }\n\n\n        do {\n            try self.parse(\n                \"\"\"\n                // swift-tools-version:3.1.0\n\n\n\n                let package = ..\n                \"\"\"\n            ) { toolsVersion in\n                XCTAssertEqual(toolsVersion.description, \"3.1.0\")\n            }\n        }\n\n        do {\n            try self.parse(\n                \"\"\"\n                // swift-tools-version:3.1.0\n\n                // swift-tools-version:4.1.0\n\n\n\n\n                let package = ..\n                \"\"\"\n            ) { toolsVersion in\n                XCTAssertEqual(toolsVersion.description, \"3.1.0\")\n            }\n        }\n    }\n\n    func testToolsVersionAllowsComments() throws {\n        try self.parse(\n        \"\"\"\n        // comment 1\n        // comment 2\n        // swift-tools-version: 6.0\n        // comment\n        let package = ..\n        \"\"\"\n        ) { toolsVersion in\n            XCTAssertEqual(toolsVersion.description, \"6.0.0\")\n        }\n\n        do {\n            try self.parse(\n            \"\"\"\n            // comment 1\n            // comment 2\n            // swift-tools-version:5.0\n            // comment\n            let package = ..\n            \"\"\"\n            ) { _ in\n                XCTFail(\"expected an error to be thrown\")\n            }\n        } catch ToolsVersionParser.Error.backwardIncompatiblePre6_0(let incompatibility, _) {\n            XCTAssertEqual(incompatibility, .toolsVersionNeedsToBeFirstLine)\n        } catch {\n            XCTFail(\"unexpected error: \\(error)\")\n        }\n\n        do {\n            try self.parse(\n            \"\"\"\n            // comment 1\n            // comment 2\n            let package = ..\n            \"\"\"\n            ) { _ in\n                XCTFail(\"expected an error to be thrown\")\n            }\n        } catch ToolsVersionParser.Error.malformedToolsVersionSpecification(.label(.isMisspelt(let label))) {\n            XCTAssertEqual(label, \"comment\")\n        } catch {\n            XCTFail(\"unexpected error: \\(error)\")\n        }\n\n        try self.parse(\n        \"\"\"\n        /*\n        this is a multiline comment\n        */\n        // swift-tools-version: 6.0\n        // comment\n        let package = ..\n        \"\"\"\n        ) { toolsVersion in\n            XCTAssertEqual(toolsVersion.description, \"6.0.0\")\n        }\n    }\n\n    /// Verifies that if a manifest appears empty to SwiftPM, a distinct error is thrown.\n    func testEmptyManifest() throws {\n        let fs = InMemoryFileSystem()\n\n\t\tlet packageRoot = AbsolutePath(\"/lorem/ipsum/dolor\")\n\t\ttry fs.createDirectory(packageRoot, recursive: true)\n\n\t\tlet manifestPath = packageRoot.appending(\"Package.swift\")\n        try fs.writeFileContents(manifestPath, bytes: \"\")\n\n        XCTAssertThrowsError(\n            try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fs),\n            \"empty manifest '\\(manifestPath.pathString)'\") { error in\n                guard let error = error as? ManifestParseError, case .emptyManifest(let errorPath) = error else {\n                    XCTFail(\"'ManifestParseError.emptyManifest' should've been thrown, but a different error is thrown\")\n                    return\n                }\n\n                guard errorPath == manifestPath else {\n                    XCTFail(\"error is in '\\(manifestPath)', but '\\(errorPath)' is given for the error message\")\n                    return\n                }\n\n                XCTAssertEqual(error.description, \"'\\(manifestPath._nativePathString(escaped: false))' is empty\")\n            }\n    }\n\n    /// Verifies that the correct error is thrown for each non-empty manifest missing its Swift tools version specification.\n    func testMissingSpecifications() throws {\n        /// Leading snippets of manifest files that don't have Swift tools version specifications.\n        let manifestSnippetsWithoutSpecification = [\n            \"\\n\",\n            \"\\n\\r\\r\\n\",\n            \"ni\",\n            \"\\rimport PackageDescription\",\n            \"let package = Package(\\n\",\n        ]\n\n        for manifestSnippet in manifestSnippetsWithoutSpecification {\n            XCTAssertThrowsError(\n                try self.parse(manifestSnippet),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the Swift tools version specification is missing from the manifest snippet\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.commentMarker(.isMissing)) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.commentMarker(.isMissing))' should've been thrown, but a different error is thrown\")\n                    return\n                }\n\n                XCTAssertEqual(\n                    error.description,\n                    \"the manifest is missing a Swift tools version specification; consider prepending to the manifest '// swift-tools-version:\\(ToolsVersion.current < .v5_4 ? \"\" : \" \")\\(ToolsVersion.current.major).\\(ToolsVersion.current.minor)\\(ToolsVersion.current.patch == 0 ? \"\" : \".\\(ToolsVersion.current.patch)\")' to specify the current Swift toolchain version as the lowest Swift version supported by the project; if such a specification already exists, consider moving it to the top of the manifest, or prepending it with '//' to help Swift Package Manager find it\"\n                )\n            }\n        }\n    }\n\n    /// Verifies that the correct error is thrown for each Swift tools version specification missing its comment marker.\n    func testMissingSpecificationCommentMarkers() throws {\n        let manifestSnippetsWithoutSpecificationCommentMarker = [\n            \" swift-tools-version:4.0\",\n            // Missing comment markers are diagnosed before missing Labels.\n            \" 4.2\",\n            // Missing comment markers are diagnosed before missing version specifiers.\n            \" swift-tools-version:\",\n            \" \",\n            // Missing comment markers are diagnosed before misspelt labels.\n            \" Swift toolchain version 5.1\",\n            \" shiny-tools-version\",\n            // Missing comment markers are diagnosed before misspelt version specifiers.\n            \" swift-tools-version:0\",\n            \" The Answer to the Ultimate Question of Life, the Universe, and Everything is 42\",\n            \" 9999999\",\n            // Missing comment markers are diagnosed before backward-compatibility checks.\n            \"\\n\\n\\nswift-tools-version:3.1\\r\",\n            \"\\r\\n\\r\\ncontrafibularity\",\n            \"\\n\\r\\t3.14\",\n        ]\n\n        for manifestSnippet in manifestSnippetsWithoutSpecificationCommentMarker {\n            XCTAssertThrowsError(\n                try self.parse(manifestSnippet),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the comment marker is missing from the Swift tools version specification\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.commentMarker(.isMissing)) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.commentMarker(.isMissing))' should've been thrown, but a different error is thrown\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"the manifest is missing a Swift tools version specification; consider prepending to the manifest '// swift-tools-version:\\(ToolsVersion.current < .v5_4 ? \"\" : \" \")\\(ToolsVersion.current.major).\\(ToolsVersion.current.minor)\\(ToolsVersion.current.patch == 0 ? \"\" : \".\\(ToolsVersion.current.patch)\")' to specify the current Swift toolchain version as the lowest Swift version supported by the project; if such a specification already exists, consider moving it to the top of the manifest, or prepending it with '//' to help Swift Package Manager find it\"\n                )\n            }\n        }\n    }\n\n    /// Verifies that the correct error is thrown for each Swift tools version specification missing its label.\n    func testMissingSpecificationLabels() throws {\n        let manifestSnippetsWithoutSpecificationLabel = [\n            \"// 5.3\",\n            // Missing labels are diagnosed before missing version specifiers.\n            \"// \",\n            // Missing labels are diagnosed before misspelt comment markers.\n            \"/// \",\n            \"/* \",\n            // Missing labels are diagnosed before misspelt version specifiers.\n            \"// 6 × 9 = 42\",\n            \"/// 99 little bugs in the code\",\n            // Missing labels are diagnosed before backward-compatibility checks.\n            \"\\r\\n// \",\n            \"//\",\n            \"\\n\\r///\\t2.1\\r\",\n        ]\n\n        for manifestSnippet in manifestSnippetsWithoutSpecificationLabel {\n            XCTAssertThrowsError(\n                try self.parse(manifestSnippet),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the label is missing from the Swift tools version specification\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.label(.isMissing)) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.label(.isMissing))' should've been thrown, but a different error is thrown\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"the Swift tools version specification is missing a label; consider inserting 'swift-tools-version:' between the comment marker and the version specifier\"\n                )\n            }\n        }\n    }\n\n    /// Verifies that the correct error is thrown for each Swift tools version specification missing its version specifier.\n    func testMissingVersionSpecifiers() throws {\n        let manifestSnippetsWithoutVersionSpecifier = [\n            \"// swift-tools-version:\",\n            // Missing version specifiers are diagnosed before misspelt comment markers.\n            \"/// swift-tools-version:\",\n            \"/* swift-tools-version:\",\n            // Missing version specifiers are diagnosed before misspelt labels.\n            \"// swallow tools version:\",\n            \"/// We are the knights who say 'Ni!'\",\n            // Missing version specifiers are diagnosed before backward-compatibility checks.\n            \"\\r\\n//\\tswift-tools-version:\",\n            \"\\n\\r///The swifts hovered in the sky in much the same way that bricks don't.\\u{85}\",\n        ]\n\n        for manifestSnippet in manifestSnippetsWithoutVersionSpecifier {\n            XCTAssertThrowsError(\n                try self.parse(manifestSnippet),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the version specifier is missing from the Swift tools version specification\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.versionSpecifier(.isMissing)) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.versionSpecifier(.isMissing))' should've been thrown, but a different error is thrown\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"the Swift tools version specification is possibly missing a version specifier; consider using '// swift-tools-version:\\(ToolsVersion.current < .v5_4 ? \"\" : \" \")\\(ToolsVersion.current.major).\\(ToolsVersion.current.minor)\\(ToolsVersion.current.patch == 0 ? \"\" : \".\\(ToolsVersion.current.patch)\")' to specify the current Swift toolchain version as the lowest Swift version supported by the project\"\n                )\n            }\n        }\n    }\n\n    /// Verifies that the correct error is thrown for each misspelt comment marker in Swift tools version specification.\n    func testMisspeltSpecificationCommentMarkers() throws {\n        let manifestSnippetsWithMisspeltSpecificationCommentMarker = [\n            \"/// swift-tools-version:4.0\",\n            \"/** swift-tools-version:4.1\",\n            // Misspelt comment markers are diagnosed before misspelt labels.\n            \"//// Shiny toolchain version 4.2\",\n            // Misspelt comment markers are diagnosed before misspelt version specifiers.\n            \"/* swift-tools-version:43\",\n            \"/** Swift version 4.4 **/\",\n            // Misspelt comment markers are diagnosed before backward-compatibility checks.\n            \"\\r\\r\\r*/swift-tools-version:4.5\",\n            \"\\n\\n\\n/*/*\\t\\tSwift5\\r\",\n        ]\n\n        for manifestSnippet in manifestSnippetsWithMisspeltSpecificationCommentMarker {\n            XCTAssertThrowsError(\n                try self.parse(manifestSnippet),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the comment marker is misspelt in the Swift tools version specification\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.commentMarker(.isMisspelt(let misspeltCommentMarker))) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.commentMarker(.isMisspelt))' should've been thrown, but a different error is thrown\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"the comment marker '\\(misspeltCommentMarker)' is misspelt for the Swift tools version specification; consider replacing it with '//'\"\n                )\n            }\n        }\n    }\n\n    /// Verifies that the correct error is thrown for each misspelt label in Swift tools version specification.\n    func testMisspeltSpecificationLabels() throws {\n        let manifestSnippetsWithMisspeltSpecificationLabel = [\n            \"// fast-tools-version:3.0\",\n            // Misspelt labels are diagnosed before misspelt version specifiers.\n            \"// rapid-tools-version:3\",\n            \"// swift-too1s-version:3.0\",\n            // Misspelt labels are diagnosed before backward-compatibility checks.\n            \"\\n\\r//\\t\\u{A0}prompt-t00ls-version:3.0.0.0\\r\\n\",\n        ]\n\n        for manifestSnippet in manifestSnippetsWithMisspeltSpecificationLabel {\n            XCTAssertThrowsError(\n                try self.parse(manifestSnippet),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the label is misspelt in the Swift tools version specification\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.label(.isMisspelt(let misspeltLabel))) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.label(.isMisspelt))' should've been thrown, but a different error is thrown\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"the Swift tools version specification's label '\\(misspeltLabel)' is misspelt; consider replacing it with 'swift-tools-version:'\"\n                )\n            }\n        }\n    }\n\n    /// Verifies that the correct error is thrown for each misspelt version specifier in Swift tools version specification.\n    func testMisspeltVersionSpecifiers() throws {\n        let manifestSnippetsWithMisspeltVersionSpecifier = [\n            \"// swift-tools-version:5²\",\n            \"// swift-tools-version:5⃣️.2⃣️\",\n            \"// swift-tools-version:5 ÷ 2 = 2.5\",\n            // If the label starts with exactly \"swift-tools-version:\" (case-insensitive), then all its misspellings are treated as the version specifier's.\n            \"// swift-tools-version::5.2\",\n            \"// Swift-tOOls-versIon:-2.5\",\n            // Misspelt version specifiers are diagnosed before backward-compatibility checks.\n            \"\\u{A}\\u{B}\\u{C}\\u{D}//\\u{3000}swift-tools-version:五.二\\u{2028}\",\n        ]\n\n        for manifestSnippet in manifestSnippetsWithMisspeltVersionSpecifier {\n            XCTAssertThrowsError(\n                try self.parse(manifestSnippet),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the version specifier is misspelt in the Swift tools version specification\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .malformedToolsVersionSpecification(.versionSpecifier(.isMisspelt(let misspeltVersionSpecifier))) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.malformedToolsVersionSpecification(.versionSpecifier(.isMisspelt))' should've been thrown, but a different error is thrown\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"the Swift tools version '\\(misspeltVersionSpecifier)' is misspelt or otherwise invalid; consider replacing it with '\\(ToolsVersion.current.specification())' to specify the current Swift toolchain version as the lowest Swift version supported by the project\"\n                )\n            }\n        }\n    }\n\n    /// Verifies that a correct error is thrown, if the manifest is valid for Swift tools version ≥ 5.4, but invalid for version < 5.4.\n    func testBackwardIncompatibilityPre5_4() throws {\n\n        // The order of tests in this function:\n        // 1. Test backward-incompatible leading whitespace for Swift < 5.4.\n        // 2. Test that backward-incompatible leading whitespace is diagnosed before backward-incompatible spacings.\n        // 3. Test spacings before the label.\n        // 4. Test that backward-incompatible spacings before the label are diagnosed before those after the label.\n        // 5. Test spacings after the label.\n\n        // MARK: 1 leading u+000D\n\n        let manifestSnippetWith1LeadingCarriageReturn = [\n            \"\\u{D}//swift-tools-version:3.1\"                : \"3.1.0\",\n            \"\\u{D}//swift-tools-version:3.1-dev\"            : \"3.1.0\",\n            \"\\u{D}//swift-tools-version:5.3\"                : \"5.3.0\",\n            \"\\u{D}//swift-tools-version:5.3.0\"              : \"5.3.0\",\n            \"\\u{D}//swift-tools-version:5.3-dev\"            : \"5.3.0\",\n            \"\\u{D}//swift-tools-version:4.8.0\"              : \"4.8.0\",\n            \"\\u{D}//swift-tools-version:4.8.0-dev.al+sha.x\" : \"4.8.0\",\n            \"\\u{D}//swift-tools-version:3.1.2\"              : \"3.1.2\",\n            \"\\u{D}//swift-tools-version:3.1.2;\"             : \"3.1.2\",\n            \"\\u{D}//swift-tools-vErsion:3.1.2;;;;;\"         : \"3.1.2\",\n            \"\\u{D}//swift-tools-version:3.1.2;x;x;x;x;x;\"   : \"3.1.2\",\n            \"\\u{D}//swift-toolS-version:3.5.2;hello\"        : \"3.5.2\",\n            \"\\u{D}//sWiFt-tOoLs-vErSiOn:3.5.2\\nkkk\\n\"       : \"3.5.2\",\n        ]\n\n        for (specification, toolsVersionString) in manifestSnippetWith1LeadingCarriageReturn {\n            XCTAssertThrowsError(\n                try self.parse(specification),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the manifest starts with a U+000D, and the specified version \\(toolsVersionString) (< 5.4) supports only leading line feeds (U+000A).\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.leadingWhitespace, _) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.leadingWhitespace, _)' should've been thrown, but a different error is thrown.\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"leading whitespace sequence [U+000D] in manifest is supported by only Swift ≥ 5.4; the specified version \\(toolsVersionString) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest\"\n                )\n            }\n        }\n\n        // MARK: 1 U+0020\n\n        let manifestSnippetWith1LeadingSpace = [\n            \"\\u{20}//swift-tools-version:3.1\"                : \"3.1.0\",\n            \"\\u{20}//swift-tools-version:3.1-dev\"            : \"3.1.0\",\n            \"\\u{20}//swift-tools-version:5.3\"                : \"5.3.0\",\n            \"\\u{20}//swift-tools-version:5.3.0\"              : \"5.3.0\",\n            \"\\u{20}//swift-tools-version:5.3-dev\"            : \"5.3.0\",\n            \"\\u{20}//swift-tools-version:4.8.0\"              : \"4.8.0\",\n            \"\\u{20}//swift-tools-version:4.8.0-dev.al+sha.x\" : \"4.8.0\",\n            \"\\u{20}//swift-tools-version:3.1.2\"              : \"3.1.2\",\n            \"\\u{20}//swift-tools-version:3.1.2;\"             : \"3.1.2\",\n            \"\\u{20}//swift-tools-vErsion:3.1.2;;;;;\"         : \"3.1.2\",\n            \"\\u{20}//swift-tools-version:3.1.2;x;x;x;x;x;\"   : \"3.1.2\",\n            \"\\u{20}//swift-toolS-version:3.5.2;hello\"        : \"3.5.2\",\n            \"\\u{20}//sWiFt-tOoLs-vErSiOn:3.5.2\\nkkk\\n\"       : \"3.5.2\",\n        ]\n\n        for (specification, toolsVersionString) in manifestSnippetWith1LeadingSpace {\n            XCTAssertThrowsError(\n                try self.parse(specification),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the manifest starts with a U+0020, and the specified version \\(toolsVersionString) (< 5.4) supports only leading line feeds (U+000A).\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.leadingWhitespace, _) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.leadingWhitespace, _)' should've been thrown, but a different error is thrown.\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"leading whitespace sequence [U+0020] in manifest is supported by only Swift ≥ 5.4; the specified version \\(toolsVersionString) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest\"\n                )\n            }\n        }\n\n        // MARK: An assortment of leading whitespace characters\n\n        let manifestSnippetWithAnAssortmentOfLeadingWhitespaceCharacters = [\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:3.1\"                : \"3.1.0\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:3.1-dev\"            : \"3.1.0\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:5.3\"                : \"5.3.0\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:5.3.0\"              : \"5.3.0\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:5.3-dev\"            : \"5.3.0\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:4.8.0\"              : \"4.8.0\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:4.8.0-dev.al+sha.x\" : \"4.8.0\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:3.1.2\"              : \"3.1.2\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:3.1.2;\"             : \"3.1.2\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-vErsion:3.1.2;;;;;\"         : \"3.1.2\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-tools-version:3.1.2;x;x;x;x;x;\"   : \"3.1.2\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//swift-toolS-version:3.5.2;hello\"        : \"3.5.2\",\n            \"\\u{A}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}\\u{D}\\u{D}\\u{A}\\u{85}\\u{2001}\\u{2028}\\u{2002}\\u{202F}\\u{2029}\\u{3000}//sWiFt-tOoLs-vErSiOn:3.5.2\\nkkk\\n\"       : \"3.5.2\",\n        ]\n\n        for (specification, toolsVersionString) in manifestSnippetWithAnAssortmentOfLeadingWhitespaceCharacters {\n            XCTAssertThrowsError(\n                try self.parse(specification),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the manifest starts with an assortment of whitespace characters, and the specified version \\(toolsVersionString) (< 5.4) supports only leading line feeds (U+000A).\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.leadingWhitespace, _) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.leadingWhitespace, _)' should've been thrown, but a different error is thrown.\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"leading whitespace sequence [U+000A, U+00A0, U+000B, U+1680, U+000C, U+0009, U+2000, U+000D, U+000D, U+000A, U+0085, U+2001, U+2028, U+2002, U+202F, U+2029, U+3000] in manifest is supported by only Swift ≥ 5.4; the specified version \\(toolsVersionString) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest\"\n                )\n            }\n        }\n\n        // MARK: An assortment of leading whitespace characters and an assortment of horizontal whitespace characters surrounding the label\n\n        let manifestSnippetWithAnAssortmentOfLeadingWhitespaceCharactersAndAnAssortmentOfWhitespacesSurroundingLabel = [\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}3.1\"                : \"3.1.0\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}3.1-dev\"            : \"3.1.0\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}5.3\"                : \"5.3.0\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}5.3.0\"              : \"5.3.0\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}5.3-dev\"            : \"5.3.0\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}4.8.0\"              : \"4.8.0\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}4.8.0-dev.al+sha.x\" : \"4.8.0\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}3.1.2\"              : \"3.1.2\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}3.1.2;\"             : \"3.1.2\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-vErsion:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}3.1.2;;;;;\"         : \"3.1.2\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}3.1.2;x;x;x;x;x;\"   : \"3.1.2\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-toolS-version:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}3.5.2;hello\"        : \"3.5.2\",\n            \"\\u{D}\\u{202F}\\u{2029}\\u{85}\\u{2001}\\u{2028}\\u{3000}\\u{A}\\u{D}\\u{A}\\u{2002}\\u{A0}\\u{B}\\u{1680}\\u{C}\\t\\u{2000}//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}sWiFt-tOoLs-vErSiOn:\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}3.5.2\\nkkk\\n\"       : \"3.5.2\",\n        ]\n\n        // Backward-incompatible leading whitespace is diagnosed before backward-incompatible spacings surrounding the label.\n        // So the errors thrown here should be about invalid leading whitespace, although both the leading whitespace and the spacings here are backward-incompatible.\n        for (specification, toolsVersionString) in manifestSnippetWithAnAssortmentOfLeadingWhitespaceCharactersAndAnAssortmentOfWhitespacesSurroundingLabel {\n            XCTAssertThrowsError(\n                try self.parse(specification),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the manifest starts with an assortment of whitespace characters, and the specified version \\(toolsVersionString) (< 5.4) supports only leading line feeds (U+000A).\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.leadingWhitespace, _) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.leadingWhitespace, _)' should've been thrown, but a different error is thrown.\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"leading whitespace sequence [U+000D, U+202F, U+2029, U+0085, U+2001, U+2028, U+3000, U+000A, U+000D, U+000A, U+2002, U+00A0, U+000B, U+1680, U+000C, U+0009, U+2000] in manifest is supported by only Swift ≥ 5.4; the specified version \\(toolsVersionString) supports only line feeds (U+000A) preceding the Swift tools version specification; consider moving the Swift tools version specification to the first line of the manifest\"\n                )\n            }\n        }\n\n        // MARK: No spacing surrounding the label\n\n        let specificationsWithZeroSpacing = [\n            \"//swift-tools-version:3.1\"                : \"3.1.0\",\n            \"//swift-tools-version:3.1-dev\"            : \"3.1.0\",\n            \"//swift-tools-version:5.3\"                : \"5.3.0\",\n            \"//swift-tools-version:5.3.0\"              : \"5.3.0\",\n            \"//swift-tools-version:5.3-dev\"            : \"5.3.0\",\n            \"//swift-tools-version:4.8.0\"              : \"4.8.0\",\n            \"//swift-tools-version:4.8.0-dev.al+sha.x\" : \"4.8.0\",\n            \"//swift-tools-version:3.1.2\"              : \"3.1.2\",\n            \"//swift-tools-version:3.1.2;\"             : \"3.1.2\",\n            \"//swift-tools-vErsion:3.1.2;;;;;\"         : \"3.1.2\",\n            \"//swift-tools-version:3.1.2;x;x;x;x;x;\"   : \"3.1.2\",\n            \"//swift-toolS-version:3.5.2;hello\"        : \"3.5.2\",\n            \"//sWiFt-tOoLs-vErSiOn:3.5.2\\nkkk\\n\"       : \"3.5.2\",\n        ]\n\n        for (specification, toolsVersionString) in specificationsWithZeroSpacing {\n            XCTAssertThrowsError(\n                try self.parse(specification),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because there is no spacing between '//' and 'swift-tools-version', and the specified version \\(toolsVersionString) (< 5.4) supports exactly 1 space (U+0020) there\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _)' should've been thrown, but a different error is thrown.\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"zero spacing between '//' and 'swift-tools-version' is supported by only Swift ≥ 5.4; consider replacing the sequence with a single space (U+0020) for Swift \\(toolsVersionString)\"\n                )\n            }\n        }\n\n        // MARK: An assortment of horizontal whitespace characters before the label\n\n        let specificationsWithAnAssortmentOfWhitespacesBeforeLabel = [\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:3.1\"                : \"3.1.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:3.1-dev\"            : \"3.1.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:5.3\"                : \"5.3.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:5.3.0\"              : \"5.3.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:5.3-dev\"            : \"5.3.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:4.8.0\"              : \"4.8.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:4.8.0-dev.al+sha.x\" : \"4.8.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:3.1.2\"              : \"3.1.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:3.1.2;\"             : \"3.1.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-vErsion:3.1.2;;;;;\"         : \"3.1.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-tools-version:3.1.2;x;x;x;x;x;\"   : \"3.1.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}swift-toolS-version:3.5.2;hello\"        : \"3.5.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}sWiFt-tOoLs-vErSiOn:3.5.2\\nkkk\\n\"       : \"3.5.2\",\n        ]\n\n        for (specification, toolsVersionString) in specificationsWithAnAssortmentOfWhitespacesBeforeLabel {\n            XCTAssertThrowsError(\n                try self.parse(specification),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the spacing between '//' and 'swift-tools-version' is an assortment of horizontal whitespace characters, and the specified version \\(toolsVersionString) (< 5.4) supports exactly 1 space (U+0020) there.\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _)' should've been thrown, but a different error is thrown.\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"horizontal whitespace sequence [U+0009, U+0020, U+00A0, U+1680, U+2000, U+2001, U+2002, U+2003, U+2004, U+2005, U+2006, U+2007, U+2008, U+2009, U+200A, U+202F, U+205F, U+3000] between '//' and 'swift-tools-version' is supported by only Swift ≥ 5.4; consider replacing the sequence with a single space (U+0020) for Swift \\(toolsVersionString)\"\n                )\n            }\n        }\n\n        // MARK: An assortment of horizontal whitespace characters surrounding the label\n\n        let specificationsWithAnAssortmentOfWhitespacesBeforeAndAfterLabel = [\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1\"                : \"3.1.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1-dev\"            : \"3.1.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}5.3\"                : \"5.3.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}5.3.0\"              : \"5.3.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}5.3-dev\"            : \"5.3.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}4.8.0\"              : \"4.8.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}4.8.0-dev.al+sha.x\" : \"4.8.0\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1.2\"              : \"3.1.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1.2;\"             : \"3.1.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-vErsion:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1.2;;;;;\"         : \"3.1.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-tools-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1.2;x;x;x;x;x;\"   : \"3.1.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}swift-toolS-version:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.5.2;hello\"        : \"3.5.2\",\n            \"//\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}sWiFt-tOoLs-vErSiOn:\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.5.2\\nkkk\\n\"       : \"3.5.2\",\n        ]\n\n        // Backward-incompatible spacings after the comment marker is diagnosed before backward-incompatible spacings after the label.\n        // So the errors thrown here should be about invalid spacing after comment marker, although both the spacings here are backward-incompatible.\n        for (specification, toolsVersionString) in specificationsWithAnAssortmentOfWhitespacesBeforeAndAfterLabel {\n            XCTAssertThrowsError(\n                try self.parse(specification),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the spacing between '//' and 'swift-tools-version' is an assortment of horizontal whitespace characters, and the specified version \\(toolsVersionString) (< 5.4) supports exactly 1 space (U+0020) there.\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.spacingAfterCommentMarker, _)' should've been thrown, but a different error is thrown.\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"horizontal whitespace sequence [U+0009, U+0020, U+00A0, U+1680, U+2000, U+2001, U+2002, U+2003, U+2004] between '//' and 'swift-tools-version' is supported by only Swift ≥ 5.4; consider replacing the sequence with a single space (U+0020) for Swift \\(toolsVersionString)\"\n                )\n            }\n        }\n\n        // MARK: 1 U+0020 before the label and an assortment of horizontal whitespace characters after the label\n\n        let specificationsWithAnAssortmentOfWhitespacesAfterLabel = [\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1\"                : \"3.1.0\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1-dev\"            : \"3.1.0\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}5.3\"                : \"5.3.0\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}5.3.0\"              : \"5.3.0\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}5.3-dev\"            : \"5.3.0\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}4.8.0\"              : \"4.8.0\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}4.8.0-dev.al+sha.x\" : \"4.8.0\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1.2\"              : \"3.1.2\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1.2;\"             : \"3.1.2\",\n            \"// swift-tools-vErsion:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1.2;;;;;\"         : \"3.1.2\",\n            \"// swift-tools-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.1.2;x;x;x;x;x;\"   : \"3.1.2\",\n            \"// swift-toolS-version:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.5.2;hello\"        : \"3.5.2\",\n            \"// sWiFt-tOoLs-vErSiOn:\\u{9}\\u{20}\\u{A0}\\u{1680}\\u{2000}\\u{2001}\\u{2002}\\u{2003}\\u{2004}\\u{2005}\\u{2006}\\u{2007}\\u{2008}\\u{2009}\\u{200A}\\u{202F}\\u{205F}\\u{3000}3.5.2\\nkkk\\n\"       : \"3.5.2\",\n        ]\n\n        for (specification, toolsVersionString) in specificationsWithAnAssortmentOfWhitespacesAfterLabel {\n            XCTAssertThrowsError(\n                try self.parse(specification),\n                \"a 'ToolsVersionLoader.Error' should've been thrown, because the spacing between 'swift-tools-version' and the version specifier is an assortment of horizontal whitespace characters, and the specified version \\(toolsVersionString) (< 5.4) supports no spacing there.\"\n            ) { error in\n                guard let error = error as? ToolsVersionParser.Error, case .backwardIncompatiblePre5_4(.spacingAfterLabel, _) = error else {\n                    XCTFail(\"'ToolsVersionLoader.Error.backwardIncompatiblePre5_4(.spacingAfterLabel, _)' should've been thrown, but a different error is thrown.\")\n                    return\n                }\n                XCTAssertEqual(\n                    error.description,\n                    \"horizontal whitespace sequence [U+0009, U+0020, U+00A0, U+1680, U+2000, U+2001, U+2002, U+2003, U+2004, U+2005, U+2006, U+2007, U+2008, U+2009, U+200A, U+202F, U+205F, U+3000] immediately preceding the version specifier is supported by only Swift ≥ 5.4; consider removing the sequence for Swift \\(toolsVersionString)\"\n                )\n            }\n        }\n\n    }\n\n    func testVersionSpecificManifest() throws {\n        let fs = InMemoryFileSystem()\n        let root = AbsolutePath(\"/pkg\")\n\n        /// Loads the tools version of root pkg.\n        func parse(_ body: (ToolsVersion) -> Void) throws {\n            let manifestPath = try ManifestLoader.findManifest(packagePath: root, fileSystem: fs, currentToolsVersion: .current)\n            body(try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fs))\n        }\n\n        // Test default manifest.\n        try fs.writeFileContents(root.appending(\"Package.swift\"), string: \"// swift-tools-version:3.1.1\\n\")\n        try parse { version in\n            XCTAssertEqual(version.description, \"3.1.1\")\n        }\n\n        // Test version specific manifests.\n        let keys = ToolsVersion.current.versionSpecificKeys\n\n        // In case the count ever changes, we will need to modify this test.\n        XCTAssertEqual(keys.count, 3)\n\n        // Test the last key.\n        try fs.writeFileContents(root.appending(\"Package\\(keys[2]).swift\"), string: \"// swift-tools-version:3.4.1\\n\")\n        try parse { version in\n            XCTAssertEqual(version.description, \"3.4.1\")\n        }\n\n        // Test the second last key.\n        try fs.writeFileContents(root.appending(\"Package\\(keys[1]).swift\"), string: \"// swift-tools-version:3.4.0\\n\")\n        try parse { version in\n            XCTAssertEqual(version.description, \"3.4.0\")\n        }\n\n        // Test the first key.\n        try fs.writeFileContents(root.appending(\"Package\\(keys[0]).swift\"), string: \"// swift-tools-version:3.4.5\\n\")\n        try parse { version in\n            XCTAssertEqual(version.description, \"3.4.5\")\n        }\n    }\n\n    func testVersionSpecificManifestFallbacks() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/pkg/foo\"\n        )\n        let root = AbsolutePath(\"/pkg\")\n\n        func parse(currentToolsVersion: ToolsVersion, _ body: (ToolsVersion) -> Void) throws {\n            let manifestPath = try ManifestLoader.findManifest(packagePath: root, fileSystem: fs, currentToolsVersion: currentToolsVersion)\n            body(try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fs))\n        }\n\n        try fs.writeFileContents(root.appending(\"Package.swift\"), string: \"// swift-tools-version:1.0.0\\n\")\n        try fs.writeFileContents(root.appending(\"Package@swift-4.2.swift\"), string: \"// swift-tools-version:3.4.5\\n\")\n        try fs.writeFileContents(root.appending(\"Package@swift-15.1.swift\"), string: \"// swift-tools-version:3.4.6\\n\")\n        try fs.writeFileContents(root.appending(\"Package@swift-15.2.swift\"), string: \"// swift-tools-version:3.4.7\\n\")\n        try fs.writeFileContents(root.appending(\"Package@swift-15.3.swift\"), string: \"// swift-tools-version:3.4.8\\n\")\n\n        try parse(currentToolsVersion: ToolsVersion(version: \"15.1.1\")) { version in\n            XCTAssertEqual(version.description, \"3.4.6\")\n        }\n\n        try parse(currentToolsVersion: ToolsVersion(version: \"15.2.5\")) { version in\n            XCTAssertEqual(version.description, \"3.4.7\")\n        }\n\n        try parse(currentToolsVersion: ToolsVersion(version: \"3.0.0\")) { version in\n            XCTAssertEqual(version.description, \"1.0.0\")\n        }\n\n        try parse(currentToolsVersion: ToolsVersion(version: \"15.3.0\")) { version in\n            XCTAssertEqual(version.description, \"3.4.8\")\n        }\n    }\n\n    func testVersionSpecificManifestMostCompatibleIfLower() throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/pkg/foo\"\n        )\n        let root = AbsolutePath(\"/pkg\")\n\n        try fs.writeFileContents(root.appending(\"Package.swift\"), string: \"// swift-tools-version:6.0.0\\n\")\n        try fs.writeFileContents(root.appending(\"Package@swift-5.0.swift\"), string: \"// swift-tools-version:5.0.0\\n\")\n\n        let currentToolsVersion = ToolsVersion(version: \"5.5.0\")\n        let manifestPath = try ManifestLoader.findManifest(packagePath: root, fileSystem: fs, currentToolsVersion: currentToolsVersion)\n        let version = try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: fs)\n        try version.validateToolsVersion(currentToolsVersion, packageIdentity: .plain(\"lunch\"))\n        XCTAssertEqual(version.description, \"5.0.0\")\n    }\n\n    func testExperimentalFlag() throws {\n        let version = try ToolsVersionParser.parse(utf8String: \"// swift-tools-version: 6.3;(experimentalCGen)\")\n        XCTAssertEqual(version, ToolsVersion(version: .init(6, 3, 0)))\n        XCTAssertTrue(version.experimentalFeatures.contains(.experimentalCGen))\n\n        let version2 = try ToolsVersionParser.parse(utf8String: \"// swift-tools-version: 6.3;(experimentalIgnored)\")\n        XCTAssertEqual(version2, ToolsVersion(version: .init(6, 3, 0)))\n        XCTAssertTrue(version2.experimentalFeatures.isEmpty)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/TraitLoadingTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\nimport XCTest\n\nfinal class TraitLoadingTests: PackageDescriptionLoadingTests {\n    override var toolsVersion: ToolsVersion {\n        .v6_1\n    }\n\n    func testTraits() async throws {\n        let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                traits: [\n                    \"Trait1\",\n                    Trait(name: \"Trait2\", description: \"Trait 2 description\"),\n                    .trait(name: \"Trait3\", description: \"Trait 3 description\", enabledTraits: [\"Trait1\"]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.traits, [\n            TraitDescription(name: \"Trait1\"),\n            TraitDescription(name: \"Trait2\", description: \"Trait 2 description\"),\n            TraitDescription(name: \"Trait3\", description: \"Trait 3 description\", enabledTraits: [\"Trait1\"]),\n        ])\n    }\n\n    func testTraits_whenTooMany() async throws {\n        let traits = Array(0...300).map { \"\\\"Trait\\($0)\\\"\" }.joined(separator: \",\")\n        let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                traits: [\\(traits)]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let firstDiagnostic = try XCTUnwrap(validationDiagnostics.first)\n        XCTAssertEqual(firstDiagnostic.severity, .error)\n        XCTAssertEqual(firstDiagnostic.message, \"A package can define a maximum of 300 traits\")\n    }\n\n    func testTraits_whenUnknownEnabledTrait() async throws {\n        let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                traits: [\n                    Trait(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let firstDiagnostic = try XCTUnwrap(validationDiagnostics.first)\n        XCTAssertEqual(firstDiagnostic.severity, .error)\n        XCTAssertEqual(firstDiagnostic.message, \"Trait Trait1 enables Trait2 which is not defined in the package\")\n    }\n\n    func testTraits_whenInvalidFirstCharacter() async throws {\n        let invalidTraitNames = [\n            \";\",\n            \"{\",\n            \"}\",\n            \"<\",\n            \">\",\n            \"$\",\n            \".\",\n            \"?\",\n            \",\",\n        ]\n\n        for traitName in invalidTraitNames {\n            let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                traits: [\n                    \"\\(traitName)\"\n                ]\n            )\n            \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            let firstDiagnostic = try XCTUnwrap(validationDiagnostics.first)\n            XCTAssertEqual(firstDiagnostic.severity, .error)\n            XCTAssertEqual(firstDiagnostic.message, \"Invalid trait name \\(traitName). Trait names must be valid Swift identifiers\")\n        }\n    }\n\n    func testTraits_whenInvalidSecondCharacter() async throws {\n        let invalidTraitNames = [\n            \"_;\",\n            \"_{\",\n            \"_}\",\n            \"_<\",\n            \"_>\",\n            \"_$\",\n            \"foo,\",\n            \"foo:bar\",\n            \"foo?\",\n        ]\n\n        for traitName in invalidTraitNames {\n            let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                traits: [\n                    \"\\(traitName)\"\n                ]\n            )\n            \"\"\"\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let (_, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            let firstDiagnostic = try XCTUnwrap(validationDiagnostics.first)\n            XCTAssertEqual(firstDiagnostic.severity, .error)\n        }\n    }\n\n    func testDefaultTraits() async throws {\n        let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                traits: [\n                    .default(enabledTraits: [\"Trait1\", \"Trait3\"]),\n                    Trait(name: \"Trait1\"),\n                    Trait(name: \"Trait2\"),\n                    .trait(name: \"Trait3\", enabledTraits: [\"Trait1\"]),\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.traits, [\n            TraitDescription(name: \"default\", description: \"The default traits of this package.\", enabledTraits: [\"Trait1\", \"Trait3\"]),\n            TraitDescription(name: \"Trait1\"),\n            TraitDescription(name: \"Trait2\"),\n            TraitDescription(name: \"Trait3\", enabledTraits: [\"Trait1\"]),\n        ])\n    }\n\n    func testDependencies() async throws {\n        let content =  \"\"\"\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                traits: [\n                    .default(enabledTraits: [\"Trait1\", \"Trait2\"]),\n                    .trait(name: \"Trait1\"),\n                    .trait(name: \"Trait2\"),\n                ],\n                dependencies: [\n                    .package(\n                        id: \"x.foo\",\n                        from: \"1.1.1\",\n                        traits: [\n                            \"FooTrait1\",\n                            .trait(name: \"FooTrait2\", condition: .when(traits: [\"Trait1\"])),\n                            Package.Dependency.Trait(name: \"FooTrait3\", condition: .when(traits: [\"Trait2\"])),\n                            .defaults\n                        ]\n                    ),\n                    .package(\n                        path: \"../Bar\",\n                        traits: [\n                            \"BarTrait1\",\n                            .trait(name: \"BarTrait2\", condition: .when(traits: [\"Trait1\"])),\n                            Package.Dependency.Trait(name: \"BarTrait3\", condition: .when(traits: [\"Trait2\"])),\n                            .defaults\n                        ]\n                    ),\n                    .package(\n                        url: \"https://github.com/Foo/FooBar\",\n                        from: \"1.0.0\",\n                        traits: [\n                            \"FooBarTrait1\",\n                            .trait(name: \"FooBarTrait2\", condition: .when(traits: [\"Trait1\"])),\n                            Package.Dependency.Trait(name: \"FooBarTrait3\", condition: .when(traits: [\"Trait2\"])),\n                            .defaults\n                        ]\n                    ),\n                ],\n                targets: [\n                    .target(\n                        name: \"Target\",\n                        dependencies: [\n                            .product(\n                                name: \"Product1\",\n                                package: \"foobar\",\n                                condition: .when(traits: [\"Trait1\"])\n                            ),\n                            .product(\n                                name: \"Product2\",\n                                package: \"bar\",\n                                condition: .when(traits: [\"Trait2\"])\n                            ),\n                        ],\n                        swiftSettings: [\n                            .define(\"DEFINE1\", .when(traits: [\"Trait1\"])),\n                            .define(\"DEFINE2\", .when(traits: [\"Trait2\"])),\n                            .define(\"DEFINE3\", .when(traits: [\"Trait1\", \"Trait2\"])),\n                        ]\n                    )\n                ]\n            )\n            \"\"\"\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let (manifest, validationDiagnostics) = try await loadAndValidateManifest(content, observabilityScope: observability.topScope)\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        XCTAssertNoDiagnostics(validationDiagnostics)\n\n        XCTAssertEqual(manifest.traits, [\n            TraitDescription(name: \"default\", description: \"The default traits of this package.\", enabledTraits: [\"Trait1\", \"Trait2\"]),\n            TraitDescription(name: \"Trait1\"),\n            TraitDescription(name: \"Trait2\"),\n        ])\n        let deps = Dictionary(uniqueKeysWithValues: manifest.dependencies.map{ ($0.identity.description, $0) })\n        XCTAssertEqual(\n            deps[\"x.foo\"]?.traits,\n            [\n                .init(name: \"FooTrait1\"),\n                .init(name: \"FooTrait2\", condition: .init(traits: [\"Trait1\"])),\n                .init(name: \"FooTrait3\", condition: .init(traits: [\"Trait2\"])),\n                .init(name: \"default\"),\n            ]\n        )\n        XCTAssertEqual(\n            deps[\"bar\"]?.traits,\n            [\n                .init(name: \"BarTrait1\"),\n                .init(name: \"BarTrait2\", condition: .init(traits: [\"Trait1\"])),\n                .init(name: \"BarTrait3\", condition: .init(traits: [\"Trait2\"])),\n                .init(name: \"default\"),\n            ]\n        )\n        XCTAssertEqual(\n            deps[\"foobar\"]?.traits,\n            [\n                .init(name: \"FooBarTrait1\"),\n                .init(name: \"FooBarTrait2\", condition: .init(traits: [\"Trait1\"])),\n                .init(name: \"FooBarTrait3\", condition: .init(traits: [\"Trait2\"])),\n                .init(name: \"default\"),\n            ]\n        )\n        XCTAssertEqual(\n            manifest.targets.first,\n            try .init(\n                name: \"Target\",\n                dependencies: [\n                    .product(\n                        name: \"Product1\",\n                        package: \"foobar\",\n                        condition: .init(traits: [\"Trait1\"])\n                    ),\n                    .product(\n                        name: \"Product2\",\n                        package: \"bar\",\n                        condition: .init(traits: [\"Trait2\"])\n                    ),\n                ],\n                settings: [\n                    .init(\n                        tool: .swift,\n                        kind: .define(\"DEFINE1\"),\n                        condition: .init(traits: [\"Trait1\"])\n                    ),\n                    .init(\n                        tool: .swift,\n                        kind: .define(\"DEFINE2\"),\n                        condition: .init(traits: [\"Trait2\"])\n                    ),\n                    .init(\n                        tool: .swift,\n                        kind: .define(\"DEFINE3\"),\n                        condition: .init(traits: [\"Trait1\", \"Trait2\"])\n                    ),\n                ]\n            )\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/case_insensitive.pc",
    "content": "prefix=/usr/local/bin\nexec_prefix=${prefix}\n\n#some comment\nName: case_insensitive\nVersion: 1\nDescription: Demonstrate that pkgconfig keys are case-insensitive\n\n# upstream pkg-config parser allows Cflags & CFlags as key\nCFlags: -I/usr/local/include\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/deps_variable.pc",
    "content": "prefix=/usr/local/bin\nexec_prefix=${prefix}\nmy_dep=atk\n#some comment\nName: deps_variable\nVersion: 1\nDescription: Demonstrate use of a locally-defined variable\n\nRequires: gdk-3.0 >= 1.0.0 ${my_dep}\nLibs: -L${prefix} -lgtk-3 \nCflags: -I\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/double_sysroot.pc",
    "content": "prefix=/usr\ndatarootdir=${prefix}/share\npkgdatadir=${pc_sysrootdir}/${datarootdir}/pkgdata\n\nName: double_sysroot\nDescription: Demonstrate double-prefixing of pc_sysrootdir (https://github.com/pkgconf/pkgconf/issues/123)\nVersion: 1\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/dummy_dependency.pc",
    "content": "prefix=/usr/local/bin\nexec_prefix=${prefix}\n\n#some comment\nName: dummy_dependency\nVersion: 1\nDescription: Demonstrate a blank dependency entry\n\nRequires: pango, , fontconfig >=  2.13.0\nLibs:-L${prefix} -lpangoft2-1.0\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/empty_cflags.pc",
    "content": "prefix=/usr/local/bin\nexec_prefix=${prefix}\n\n#some comment\nName: empty_cflags\nVersion: 1\nDescription: Demonstrate an empty cflags list\n\nRequires: gdk-3.0 atk\nLibs:-L${prefix} -lgtk-3 \nCflags:\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/escaped_spaces.pc",
    "content": "prefix=/usr/local/bin\nexec_prefix=${prefix}\nmy_dep=atk\n#some comment\nName: escaped_spaces\nVersion: 1\nDescription: Demonstrate use of escape characters in flag values\n\nRequires: gdk-3.0 >= 1.0.0 ${my_dep}\nLibs: -L\"${prefix}\" -l\"gtk 3\" -wantareal\\\\here -one\\\\ -two\nCflags: -I/usr/local/Wine\\ Cellar/gtk+3/3.18.9/include/gtk-3.0    -I/after/extra/spaces\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/failure_case.pc",
    "content": "prefix=/usr/local/bin\nexec_prefix=${prefix}\n\n#some comment\nName: failure_case\nVersion: 1\nDescription: Demonstrate failure caused by use of an undefined variable\n\nRequires: gdk-3.0 >= 1.0.0\nLibs: -L${prefix} -lgtk-3 ${my_dep}\nCflags: -I\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/freetype2.pc",
    "content": "prefix=/usr\nexec_prefix=/usr\nlibdir=/usr/lib\nincludedir=/usr/include\n\nName: FreeType 2\nURL: https://freetype.org\nDescription: A free, high-quality, and portable font engine.\nVersion: 23.4.17\nRequires:\nRequires.private: harfbuzz\nLibs: -L${libdir} -lfreetype\nLibs.private: -lbz2\nCflags: -I${includedir}/freetype2\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/gobject-2.0.pc",
    "content": "prefix=/usr/local/Cellar/glib/2.64.3\nlibdir=${prefix}/lib\nincludedir=${prefix}/include\n\nName: GObject\nDescription: GLib Type, Object, Parameter and Signal Library\nVersion: 2.64.3\n# Requires: glib-2.0\nRequires.private: /usr/local/opt/libffi/lib/pkgconfig/libffi.pc >=  3.0.0\nLibs: -L${libdir} -lgobject-2.0\nLibs.private: -lintl\nCflags:-I${includedir}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/gtk+-3.0.pc",
    "content": "prefix = /usr/local/Cellar/gtk+3/3.18.9\nexec_prefix=${prefix}\nlibdir=${exec_prefix}/lib\nincludedir=${prefix}/include\ntargets=quartz\n#some comment\ngtk_binary_version=3.0.0\ngtk_host=x86_64-apple-darwin15.3.0\n\nName: GTK+\nDescription: GTK+ Graphical UI Library\nVersion: 3.18.9\nRequires: gdk-3.0,atk    >=   2.15.1    cairo >= 1.14.0 cairo-gobject >= 1.14.0 gdk-pixbuf-2.0 >= 2.30.0 gio-2.0 >= 2.45.8        #some random comment \nRequires.private: atk   epoxy >= 1.0 gio-unix-2.0 >= 2.45.8\nLibs: -L${libdir} -lgtk-3 \nCflags: -I${includedir}/gtk-3.0 \n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/harfbuzz.pc",
    "content": "prefix=/usr\nlibdir=${prefix}/lib\nincludedir=${prefix}/include\n\nName: harfbuzz\nDescription: HarfBuzz text shaping library\nVersion: 2.7.4\nRequires.private: freetype2 \nLibs: -L${libdir} -lharfbuzz\nLibs.private: -pthread -lm\nCflags: -I${includedir}/harfbuzz\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/libffi.pc",
    "content": "prefix=/usr/local/Cellar/libffi/3.3\nexec_prefix=${prefix}\nlibdir=${exec_prefix}/lib\ntoolexeclibdir=${libdir}\nincludedir=${prefix}/include\n\nName: libffi\nDescription: Library supporting Foreign Function Interfaces\nVersion: 3.3\nLibs: -L${toolexeclibdir} -lffi\nCflags: -I${includedir}\n"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/not_double_sysroot.pc",
    "content": "prefix=/usr\ndatarootdir=${prefix}/share\npkgdatadir=${pc_sysrootdir}/filler/${datarootdir}/pkgdata\n\nName: double_sysroot\nDescription: Demonstrate pc_sysrootdir appearing elsewhere in a path - this is not a double prefix and should not be removed"
  },
  {
    "path": "Tests/PackageLoadingTests/pkgconfigInputs/quotes_failure.pc",
    "content": "prefix=/usr/local/bin\nexec_prefix=${prefix}\nmy_dep=atk\n#some comment\nName: quotes_failure\nVersion: 1\nDescription: Demonstrate failure due to unbalanced quotes\n\nRequires: gdk-3.0 >= 1.0.0 ${my_dep}\nLibs: -L\"${prefix}\" -l\"gt\"k3\" -wantareal\\\\here -one\\\\ -two\nCflags: -I/usr/local/Wine\\ Cellar/gtk+3/3.18.9/include/gtk-3.0    -I/after/extra/spaces\n"
  },
  {
    "path": "Tests/PackageModelTests/CanonicalPackageLocationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\n@testable import PackageModel\n\nfinal class CanonicalPackageLocationTests: XCTestCase {\n    func testCaseInsensitivity() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"MONA/LINKEDLIST\").description,\n            \"mona/linkedlist\"\n        )\n\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"mona/linkedlist\").description,\n            \"mona/linkedlist\"\n        )\n    }\n\n    func testNormalizationInsensitivity() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"mona/e\\u{0301}clair\").description, // ◌́ COMBINING ACUTE ACCENT (U+0301)\n            \"mona/éclair\"\n        )\n\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"mona/\\u{00C9}clair\").description, // LATIN CAPITAL LETTER E WITH ACUTE (U+00C9)\n            \"mona/éclair\"\n        )\n    }\n\n    func testCaseAndNormalizationInsensitivity() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"mona/E\\u{0301}clair\").description, // ◌́ COMBINING ACUTE ACCENT (U+0301)\n            \"mona/éclair\"\n        )\n    }\n\n    // MARK: - Filesystem\n\n    func testFileScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"file:///Users/mona/LinkedList\").description,\n            \"/users/mona/linkedlist\"\n        )\n    }\n\n    func testImplicitFileSchemeWithAbsolutePath() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"/Users/mona/LinkedList\").description,\n            \"/users/mona/linkedlist\"\n        )\n    }\n\n    // MARK: - FTP / FTPS\n\n    func testFTPScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"ftp://example.com/mona/LinkedList\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testFTPSScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"ftps://example.com/mona/LinkedList\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    // MARK: - HTTP / HTTPS\n\n    func testHTTPScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"http://example.com/mona/LinkedList\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithUser() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://user@example.com/mona/LinkedList\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithUserAndPassword() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://user:sw0rdf1sh!@example.com/mona/LinkedList\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithPort() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com:443/mona/LinkedList\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithTrailingSlash() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList/\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithGitSuffix() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithGitSuffixAndTrailingSlash() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList.git/\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithGitSuffixAndSwiftExtension() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList.swift.git\").description,\n            \"example.com/mona/linkedlist.swift\"\n        )\n    }\n\n    func testHTTPSSchemeWithQuery() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList?utm_source=forums.swift.org\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithQueryAndTrailingSlash() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList/?utm_source=forums.swift.org\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithQueryAndGitSuffix() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList.git?utm_source=forums.swift.org\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithFragment() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList#installation\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithFragmentAndTrailingSlash() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList/#installation\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithFragmentAndGitSuffix() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList.git#installation\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithFragmentAndQuery() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/LinkedList.git#installation?utm_source=forums.swift.org\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testHTTPSSchemeWithPercentEncoding() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/%F0%9F%94%97List\").description,\n            \"example.com/mona/🔗list\"\n        )\n    }\n\n    func testHTTPSSchemeWithInvalidPercentEncoding() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://example.com/mona/100%\").description,\n            \"example.com/mona/100%\"\n        )\n    }\n\n    func testHTTPSSchemeWithInternationalizedDomainName() throws {\n        // TODO: Implement Punycode conversion\n        try XCTSkipIf(true, \"internationalized domain names aren't yet supported\")\n\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"https://xn--schlssel-95a.tld/mona/LinkedList\").description,\n            \"schlüssel.tld/mona/LinkedList\"\n        )\n    }\n\n    // MARK: - Git\n\n    func testGitScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"git://example.com/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testGitSchemeWithPort() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"git://example.com:9418/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testGitPlusHTTPSScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"git+https://example.com/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    // MARK: - SSH\n\n    func testSSHScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"ssh://git@example.com/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testSSHSchemeWithColonAndRelativePath() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"ssh://git@example.com:mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testSSHSchemeWithColonAndAbsolutePath() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"ssh://git@example.com:/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testSSHSchemeWithPort() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"ssh://git@example.com:22/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testSSHSchemeWithTildeExpansion() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"ssh://mona@example.com/~/LinkedList.git\").description,\n            \"example.com/~mona/linkedlist\"\n        )\n    }\n\n    func testSSHSchemeWithoutTildeExpansion() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"ssh://git@example.com/~mona/LinkedList.git\").description,\n            \"example.com/~mona/linkedlist\"\n        )\n    }\n\n    func testImplicitSSHScheme() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"git@example.com/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testImplicitSSHSchemeWithColonAndRelativePath() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"git@example.com:mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testImplicitSSHSchemeWithColonAndAbsolutePath() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"git@example.com:/mona/LinkedList.git\").description,\n            \"example.com/mona/linkedlist\"\n        )\n    }\n\n    func testImplicitSSHSchemeWithTildeExpansion() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"mona@example.com/~/LinkedList.git\").description,\n            \"example.com/~mona/linkedlist\"\n        )\n    }\n\n    func testImplicitSSHSchemeWithoutTildeExpansion() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"git@example.com/~mona/LinkedList.git\").description,\n            \"example.com/~mona/linkedlist\"\n        )\n    }\n\n    func testImplicitSSHSchemeWithColonInPathComponent() {\n        XCTAssertEqual(\n            CanonicalPackageLocation(\"user:sw0rdf1sh!@example.com:/mona/Linked:List.git\").description,\n            \"example.com/mona/linked:list\"\n        )\n    }\n\n    func testScheme() {\n        XCTAssertEqual(CanonicalPackageURL(\"https://example.com/mona/LinkedList\").scheme, \"https\")\n        XCTAssertEqual(CanonicalPackageURL(\"git@example.com/mona/LinkedList\").scheme, \"ssh\")\n        XCTAssertEqual(CanonicalPackageURL(\"git@example.com:mona/LinkedList.git \").scheme, \"ssh\")\n        XCTAssertEqual(CanonicalPackageURL(\"ssh://mona@example.com/~/LinkedList.git\").scheme, \"ssh\")\n        XCTAssertEqual(CanonicalPackageURL(\"file:///Users/mona/LinkedList\").scheme, \"file\")\n        XCTAssertEqual(CanonicalPackageURL(\"example.com:443/mona/LinkedList\").scheme, nil)\n        XCTAssertEqual(CanonicalPackageURL(\"example.com/mona/%F0%9F%94%97List\").scheme, nil)\n        XCTAssertEqual(CanonicalPackageURL(\"example.com/mona/LinkedList.git\").scheme, nil)\n        XCTAssertEqual(CanonicalPackageURL(\"example.com/mona/LinkedList/\").scheme, nil)\n        XCTAssertEqual(CanonicalPackageURL(\"example.com/mona/LinkedList#installation\").scheme, nil)\n        XCTAssertEqual(CanonicalPackageURL(\"example.com/mona/LinkedList?utm_source=forums.swift.org\").scheme, nil)\n        XCTAssertEqual(CanonicalPackageURL(\"user:sw0rdf1sh!@example.com:/mona/Linked:List.git\").scheme, nil)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/EnabledTraitTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\nimport struct PackageModel.EnabledTrait\nimport struct PackageModel.EnabledTraits\nimport struct PackageModel.EnabledTraitsMap\n\n@Suite(\n    .tags(\n        .TestSize.small\n    )\n)\nstruct EnabledTraitTests {\n\n    // MARK: - EnabledTrait Tests\n\n    /// Verifies that `EnabledTrait` equality is based solely on the trait name, not the setter.\n    /// Two traits with the same name but different setters are equal, while traits with different names are not equal.\n    @Test\n    func enabledTrait_checkEquality() {\n        let appleTraitSetByApplePie = EnabledTrait.init(name: \"Apple\", setBy: .package(.init(identity: \"ApplePie\")))\n        let appleTraitSetByAppleJuice = EnabledTrait.init(name: \"Apple\", setBy: .trait(\"AppleJuice\"))\n        let appleCoreTrait = EnabledTrait.init(name: \"AppleCore\", setBy: .default)\n\n        #expect(appleTraitSetByApplePie == appleTraitSetByAppleJuice)\n        #expect(appleCoreTrait != appleTraitSetByApplePie)\n        #expect(appleCoreTrait != appleTraitSetByAppleJuice)\n    }\n\n    /// Tests that unifying two `EnabledTrait` instances with the same name merges their setters\n    /// into a single set containing both original setters.\n    @Test\n    func enabledTrait_unifyEqualTraits() throws {\n        let bananaTraitSetByFruit = EnabledTrait(name: \"Banana\", setBy: .package(.init(identity: \"Fruit\")))\n        let bananaTraitSetByBread = EnabledTrait(name: \"Banana\", setBy: .trait(\"Bread\"))\n\n        let unifiedBananaTrait = try #require(bananaTraitSetByBread.unify(bananaTraitSetByFruit))\n        let setters: Set<EnabledTrait.Setter> = [\n            EnabledTrait.Setter.package(.init(identity: \"Fruit\")),\n            EnabledTrait.Setter.trait(.init(\"Bread\"))\n        ]\n\n        #expect(unifiedBananaTrait.setters == setters)\n    }\n\n    /// Verifies that attempting to unify two traits with different names returns `nil`,\n    /// as they cannot be unified.\n    @Test\n    func enabledTrait_unifyDifferentTraits() {\n        let bananaTrait = EnabledTrait(name: \"Banana\", setBy: .package(.init(identity: \"Fruit\")))\n        let appleTrait = EnabledTrait(name: \"Apple\", setBy: .package(.init(identity: \"Fruit\")))\n\n        let unifiedTrait = bananaTrait.unify(appleTrait)\n\n        #expect(unifiedTrait == nil)\n        #expect(bananaTrait.setters == appleTrait.setters)\n    }\n\n    /// Tests that `EnabledTrait` can be compared to a string literal for equality in both\n    /// directions (trait == string and string == trait).\n    @Test\n    func enabledTrait_compareToStringLiteral() {\n        let appleTrait = EnabledTrait(name: \"Apple\", setBy: .default)\n\n        #expect(\"Apple\" == appleTrait) // test when EnabledTrait rhs\n        #expect(appleTrait == \"Apple\") // test when EnabledTrait lhs\n    }\n\n    /// Tests that `EnabledTrait` can be compared to a `String` for equality in both\n    /// directions (trait == string and string == trait).\n    @Test\n    func enabledTrait_compareToStringAsEnabledTraitConvertible() {\n        let appleTrait = EnabledTrait(name: \"Apple\", setBy: .default)\n        let stringTrait = \"Apple\"\n\n        #expect(stringTrait.asEnabledTrait == appleTrait) // test when EnabledTrait rhs\n        #expect(appleTrait == stringTrait.asEnabledTrait) // test when EnabledTrait lhs\n    }\n\n    /// Verifies that an `EnabledTrait` can be initialized using a string literal and is\n    /// equivalent to initialization with `setBy: .default`.\n    @Test\n    func enabledTrait_initializedByStringLiteral() {\n        let appleTraitByString: EnabledTrait = \"Apple\"\n        let appleTraitByInit = EnabledTrait(name: \"Apple\", setBy: .default)\n\n        #expect(appleTraitByString == appleTraitByInit)\n    }\n\n    /// Confirms that the `id` property of an `EnabledTrait` equals its `name` property.\n    @Test\n    func enabledTrait_assertIdIsName() {\n        let appleTrait = EnabledTrait(name: \"Apple\", setBy: .default)\n\n        #expect(appleTrait.id == appleTrait.name)\n    }\n\n    /// Tests the `isDefault` property to verify that a trait named \"default\" is correctly\n    /// identified as a default trait.\n    @Test\n    func enabledTrait_CheckIfDefault() {\n        let defaultTrait: EnabledTrait = \"default\"\n\n        #expect(defaultTrait.isDefault)\n    }\n\n    /// Verifies that `EnabledTrait` instances can be sorted alphabetically by name and\n    /// compared using comparison operators (`<`, `>`).\n    @Test\n    func enabledTrait_SortAndCompare() {\n        let appleTrait: EnabledTrait = \"Apple\"\n        let bananaTrait: EnabledTrait = \"Banana\"\n        let orangeTrait: EnabledTrait = \"Orange\"\n\n        let traits = [orangeTrait, appleTrait, bananaTrait]\n        let sortedTraits = traits.sorted()\n\n        #expect(sortedTraits == [appleTrait, bananaTrait, orangeTrait])\n        #expect(sortedTraits != traits)\n        #expect(appleTrait < bananaTrait)\n        #expect(orangeTrait > bananaTrait)\n    }\n\n    /// Tests the `parentPackages` property to ensure it correctly filters and returns only\n    /// package-based setters, excluding trait and trait configuration setters.\n    @Test\n    func enabledTrait_getParentPackageSetters() throws {\n        let traitSetByPackages = EnabledTrait(\n            name: \"Coffee\",\n            setBy: [\n                .package(.init(identity: \"Cafe\")),\n                .package(.init(identity:\"Home\")),\n                .package(.init(identity: \"Breakfast\")),\n                .trait(\"NotAPackage\"),\n                .traitConfiguration\n            ])\n\n        let parentPackagesFromTrait = traitSetByPackages.parentPackages\n\n        #expect(Set(parentPackagesFromTrait) == [\"Cafe\", \"Home\", \"Breakfast\"])\n    }\n\n    // MARK: - EnabledTraits Tests\n\n    /// Verifies that `EnabledTraits` can be initialized from an array literal of strings,\n    /// comparing it against another set of traits initialized by a list of `EnabledTrait`\n    /// containing traits of the same names.\n    @Test\n    func enabledTraits_initWithStrings() {\n        let enabledTraits: EnabledTraits = [\"One\", \"Two\", \"Three\"]\n        let toTestAgainst = EnabledTraits([\n            EnabledTrait(name: \"One\", setBy: .default),\n            EnabledTrait(name: \"Two\", setBy: .default),\n            EnabledTrait(name: \"Three\", setBy: .default)\n        ])\n\n        #expect(enabledTraits == toTestAgainst)\n    }\n\n    /// Tests the `.defaults` static property returns an `EnabledTraits` set containing\n    /// only the \"default\" trait.\n    @Test\n    func enabledTraits_defaultSet() {\n        let defaults: EnabledTraits = .defaults\n\n        #expect(defaults == [\"default\"])\n        #expect(defaults == [EnabledTrait(name: \"default\", setBy: .default)])\n    }\n\n    /// Verifies the `contains` method works with both string literals and `EnabledTrait` instances,\n    /// and correctly identifies traits that are and aren't in the set.\n    @Test\n    func enabledTraits_containsTrait() {\n        let enabledTraits: EnabledTraits = [\"Apple\", \"Banana\"]\n\n        // Test against a string literal\n        #expect(enabledTraits.contains(\"Apple\"))\n\n        // Test against an explicitly initialized EnabledTrait\n        #expect(enabledTraits.contains(EnabledTrait(name: \"Apple\", setBy: .default)))\n\n        // Test against string literal that is not in the set\n        #expect(!enabledTraits.contains(\"Orange\"))\n\n        // Test against initialized EnabledTrait that is not in the set\n        #expect(!enabledTraits.contains(EnabledTrait(name: \"Pineapple\", setBy: .trait(\"Apple\"))))\n    }\n\n    /// Tests inserting a trait that already exists (unifying setters), removing it, and verifying\n    /// the removed trait has the merged setters. Also tests inserting a new trait via string literal.\n    @Test\n    func enabledTraits_insertAndRemoveExistingTrait() throws {\n        var enabledTraits: EnabledTraits = [\"Apple\", \"Banana\", \"Orange\"]\n\n        let newTrait = EnabledTrait(name: \"Apple\", setBy: [.package(.init(identity: \"Fruit\")), .trait(\"FavouriteFruit\")])\n\n        // Assert amount of elements before adding trait\n        #expect(enabledTraits.count == 3)\n\n        // Insert trait; this should update the existing \"Apple\" trait by unifying its setters\n        enabledTraits.insert(newTrait)\n        #expect(enabledTraits.count == 3)\n        #expect(enabledTraits == [\"Apple\", \"Banana\", \"Orange\"])\n\n\n        // Assure that Apple trait is removed and returned\n        let appleTrait = enabledTraits.remove(\"Apple\")\n        let unwrappedAppleTrait = try #require(appleTrait)\n        #expect(enabledTraits.count == 2)\n        #expect(!enabledTraits.contains(\"Apple\"))\n\n        // Assure that Apple trait now has updated setters\n        #expect(unwrappedAppleTrait.setters == [.package(.init(identity: \"Fruit\")), .trait(\"FavouriteFruit\")])\n\n        // Insert trait via string literal\n        enabledTraits.insert(\"MyStringTrait\")\n        #expect(enabledTraits.count == 3)\n        #expect(enabledTraits.contains(\"MyStringTrait\"))\n    }\n\n    /// Verifies that removing a non-existent trait returns `nil`, and inserting a new trait\n    /// adds it to the set.\n    @Test\n    func enabledTraits_insertAndRemoveNonExistingTrait() throws {\n        var enabledTraits: EnabledTraits = [\"Banana\"]\n\n        let newTrait = EnabledTrait(name: \"Apple\", setBy: [.package(.init(identity: \"Fruit\")), .trait(\"FavouriteFruit\")])\n\n\n        // Try to remove Apple trait before inserting:\n        #expect(enabledTraits.remove(\"Apple\") == nil)\n        #expect(enabledTraits.count == 1)\n\n        // Insert trait\n        enabledTraits.insert(newTrait)\n        #expect(enabledTraits.count == 2)\n        #expect(enabledTraits.contains(\"Apple\"))\n    }\n\n    /// Tests the `map` method to transform each trait in the set by adding a new setter to each.\n    @Test\n    func enabledTraits_flatMapAgainstSetOfTraits() {\n        let enabledTraits: EnabledTraits = [\"Apple\", \"Coffee\", \"Cookie\"]\n        let transformedTraits = enabledTraits.map({ oldTrait in\n            var newTrait = oldTrait\n            newTrait.setters.insert(.package(.init(identity: \"Breakfast\")))\n            return newTrait\n        })\n\n        #expect(\n            transformedTraits == EnabledTraits([\n                EnabledTrait(name: \"Apple\", setBy: .package(.init(identity: \"Breakfast\"))),\n                EnabledTrait(name: \"Coffee\", setBy: .package(.init(identity: \"Breakfast\"))),\n                EnabledTrait(name: \"Cookie\", setBy: .package(.init(identity: \"Breakfast\")))\n            ])\n        )\n    }\n\n    /// Verifies that unioning two sets with no overlapping traits combines them into a single larger set\n    /// containing the traits of both sets.\n    @Test\n    func enabledTraits_unionWithNewTraits() {\n        let enabledTraits: EnabledTraits = [\"Banana\"]\n        let newTraits: EnabledTraits = [\"Cookie\", \"Pancakes\", \"Milkshake\"]\n\n        let unifiedSetOfTraits = enabledTraits.union(newTraits)\n\n        #expect(unifiedSetOfTraits.count == 4)\n        #expect(unifiedSetOfTraits == [\"Banana\", \"Cookie\", \"Pancakes\", \"Milkshake\"])\n    }\n\n    /// Tests unioning sets with overlapping traits, verifying that duplicate traits have their\n    /// setters merged correctly.\n    @Test\n    func enabledTraits_unionWithExistingTraits() throws {\n        let enabledTraits: EnabledTraits = [\n            EnabledTrait(name: \"Banana\", setBy: .default),\n            EnabledTrait(name: \"Apple\", setBy: .package(.init(identity: \"MyFruits\")))\n        ]\n        let newTraits: EnabledTraits = [\n            EnabledTrait(name: \"Banana\", setBy: [.package(.init(identity: \"OtherFruits\")), .trait(\"Bread\")]),\n            EnabledTrait(name: \"Apple\", setBy: .default),\n            \"Milkshake\"\n        ]\n\n        var unifiedSetOfTraits = enabledTraits.union(newTraits)\n\n        #expect(unifiedSetOfTraits.count == 3)\n        #expect(unifiedSetOfTraits == [\"Banana\", \"Apple\", \"Milkshake\"])\n\n        // Check each of the setters for each enabled trait, and assure\n        // that they can be succesfully removed from the set.\n        let bananaTrait = try unifiedSetOfTraits.unwrapRemove(\"Banana\")\n\n        #expect(unifiedSetOfTraits.count == 2)\n        #expect(\n            bananaTrait.setters == Set([\n                .package(.init(identity: \"OtherFruits\")),\n                .trait(\"Bread\"),\n                .default\n            ])\n        )\n\n        let appleTrait = try unifiedSetOfTraits.unwrapRemove(EnabledTrait(name: \"Apple\", setBy: .default))\n        #expect(unifiedSetOfTraits.count == 1)\n        #expect(\n            appleTrait.setters == Set([\n                .package(.init(identity: \"MyFruits\")),\n                .default\n            ])\n        )\n\n        let milkshakeTrait = try unifiedSetOfTraits.unwrapRemove(\"Milkshake\")\n        #expect(unifiedSetOfTraits.isEmpty)\n        #expect(milkshakeTrait.setters.isEmpty)\n    }\n\n    /// Verifies that initializing `EnabledTraits` with duplicate trait names in the array\n    /// results in a single trait (set behavior).\n    @Test\n    func enabledTraits_testInitWithArrayOfSameString() throws {\n        var traits: EnabledTraits = [\n            \"Banana\",\n            EnabledTrait(name: \"Banana\", setBy: .default),\n            \"Chocolate\"\n        ]\n\n        #expect(traits.count == 2)\n        #expect(traits.contains(\"Banana\"))\n        #expect(traits.contains(\"Chocolate\"))\n\n        let bananaTrait = try traits.unwrapRemove(\"Banana\")\n        #expect(traits.count == 1)\n        #expect(traits.contains(\"Chocolate\"))\n        #expect(!traits.contains(bananaTrait))\n    }\n\n    /// Tests that intersecting with an empty set returns an empty set.\n    @Test\n    func enabledTraits_testIntersectionWithEmptySet() {\n        let enabledTraits: EnabledTraits = [\"Apple\", \"Banana\", \"Cheese\"]\n        let emptyTraits = EnabledTraits()\n\n        let intersection = enabledTraits.intersection(emptyTraits)\n        #expect(intersection.isEmpty)\n    }\n\n    /// Verifies that intersecting with an identical set returns the same set.\n    @Test\n    func enabledTraits_testIntersectionWithIdenticalSet() {\n        let enabledTraits: EnabledTraits = [\"Apple\", \"Banana\", \"Cheese\"]\n        let otherEnabledTraits: EnabledTraits = [\"Apple\", \"Banana\", \"Cheese\"]\n        #expect(enabledTraits == otherEnabledTraits)\n\n        let intersection = enabledTraits.intersection(otherEnabledTraits)\n        #expect(intersection == enabledTraits)\n        #expect(intersection == otherEnabledTraits)\n    }\n\n    /// Tests intersection of two sets with partial overlap, verifying only common traits are returned.\n    @Test\n    func enabledTraits_testIntersectionWithDifferentSets() throws {\n        let enabledTraits: EnabledTraits = [\"Apple\", \"Banana\", \"Orange\"]\n        var otherEnabledTraits: EnabledTraits = [\"Banana\", \"Chocolate\"]\n        #expect(enabledTraits != otherEnabledTraits)\n\n        let intersection = enabledTraits.intersection(otherEnabledTraits)\n        #expect(intersection.count == 1)\n        #expect(intersection.contains(\"Banana\"))\n\n        let bananaTrait = try otherEnabledTraits.unwrapRemove(\"Banana\")\n        #expect(!otherEnabledTraits.contains(bananaTrait))\n\n        let newIntersection = enabledTraits.intersection(otherEnabledTraits)\n        #expect(newIntersection.isEmpty)\n    }\n\n    /// Verifies intersection behavior with single-element sets containing the same trait.\n    @Test\n    func enabledTraits_testIntersectionWithOneElementSets() throws {\n        let enabledTraits: EnabledTraits = [\"Apple\"]\n        let otherEnabledTraits: EnabledTraits = [EnabledTrait(name: \"Apple\", setBy: .package(.init(identity: \"MyFruits\")))]\n        #expect(enabledTraits == otherEnabledTraits)\n\n        let intersection = enabledTraits.intersection(otherEnabledTraits)\n        #expect(intersection.count == 1)\n        #expect(intersection == enabledTraits)\n        #expect(intersection == otherEnabledTraits)\n    }\n\n    /// Verifies that isExplicitlySetDefault returns true when \"default\" is set with an explicit setter\n    @Test\n    func enabledTraits_isExplicitlySetDefaultWithSetter() {\n        let defaultWithSetter = EnabledTraits(\n            [\"default\"],\n            setBy: .package(\"Package\")\n        )\n\n        #expect(defaultWithSetter.isExplicitlySetDefault == true)\n    }\n\n    /// Verifies that isExplicitlySetDefault returns false for the sentinel .defaults value\n    @Test\n    func enabledTraits_isExplicitlySetDefaultForSentinel() {\n        let sentinelDefault = EnabledTraits.defaults\n\n        #expect(sentinelDefault.isExplicitlySetDefault == false)\n    }\n\n    /// Verifies that isExplicitlySetDefault returns false for non-default traits\n    @Test\n    func enabledTraits_isExplicitlySetDefaultForNonDefault() {\n        let feature = EnabledTraits(\n            [\"Feature1\"],\n            setBy: .package(\"Package\")\n        )\n\n        #expect(feature.isExplicitlySetDefault == false)\n    }\n\n    /// Verifies that isExplicitlySetDefault returns false for multiple traits including default\n    @Test\n    func enabledTraits_isExplicitlySetDefaultWithMultipleTraits() {\n        let mixed = EnabledTraits(\n            [\"default\", \"Feature1\"],\n            setBy: .package(\"Package\")\n        )\n\n        #expect(mixed.isExplicitlySetDefault == false)\n    }\n\n    // MARK: - EnabledTraitsMap Tests\n\n    /// Tests basic initialization of an empty `EnabledTraitsMap` and verifies default trait behavior.\n    @Test\n    func enabledTraitsMap_initEmpty() {\n        let map = EnabledTraitsMap()\n\n        // Accessing a non-existent package should return [\"default\"]\n        #expect(map[\"PackageNotFound\"] == [\"default\"])\n    }\n\n    /// Verifies that `EnabledTraitsMap` can be initialized using dictionary literal syntax.\n    @Test\n    func enabledTraitsMap_initWithDictionaryLiteral() {\n        let map: EnabledTraitsMap = [\n            \"PackageA\": [\"Apple\", \"Banana\"],\n            \"PackageB\": [\"Coffee\"]\n        ]\n\n        #expect(map[\"PackageA\"] == [\"Apple\", \"Banana\"])\n        #expect(map[\"PackageB\"] == [\"Coffee\"])\n    }\n\n    /// Tests that `EnabledTraitsMap` can be initialized from a dictionary.\n    @Test\n    func enabledTraitsMap_initWithDictionary() {\n        let dictionary: [String: EnabledTraits] = [\n            \"PackageA\": [\"Apple\", \"Banana\"],\n            \"PackageB\": [\"Coffee\"]\n        ]\n\n        let map = EnabledTraitsMap(dictionary)\n\n        #expect(map[\"PackageA\"] == [\"Apple\", \"Banana\"])\n        #expect(map[\"PackageB\"] == [\"Coffee\"])\n    }\n\n    /// Verifies that setting traits via subscript adds them to the map.\n    @Test\n    func enabledTraitsMap_setTraitsViaSubscript() {\n        var map = EnabledTraitsMap()\n\n        map[\"MyPackage\"] = [\"Apple\", \"Banana\"]\n\n        #expect(map[\"MyPackage\"] == [\"Apple\", \"Banana\"])\n    }\n\n    /// Tests that setting \"default\" traits explicitly does not store them in the map,\n    /// since the map returns \"default\" by default for packages without explicitly\n    /// set traits.\n    @Test\n    func enabledTraitsMap_setDefaultTraitsDoesNotStore() {\n        var map = EnabledTraitsMap()\n\n        // Setting [\"default\"] should be omitted from storage\n        map[\"MyPackage\"] = [\"default\"]\n\n        // The package should still return [\"default\"] when accessed\n        #expect(map[\"MyPackage\"] == [\"default\"])\n\n        // But there should be no explicit entry in storage\n        #expect(map[explicitlyEnabledTraitsFor: \"MyPackage\"] == nil)\n    }\n\n    /// Verifies that setting traits multiple times on the same package unifies them\n    /// (forms union) rather than replacing them.\n    @Test\n    func enabledTraitsMap_multipleSetsCombineTraits() {\n        var map = EnabledTraitsMap()\n\n        map[\"MyPackage\"] = [\"Apple\", \"Banana\"]\n        map[\"MyPackage\"] = [\"Coffee\", \"Chocolate\"]\n\n        // Should contain all four traits\n        #expect(map[\"MyPackage\"].contains(\"Apple\"))\n        #expect(map[\"MyPackage\"].contains(\"Banana\"))\n        #expect(map[\"MyPackage\"].contains(\"Coffee\"))\n        #expect(map[\"MyPackage\"].contains(\"Chocolate\"))\n        #expect(map[\"MyPackage\"].count == 4)\n    }\n\n    /// Tests that setting overlapping traits unifies the setters correctly.\n    @Test\n    func enabledTraitsMap_overlappingTraitsUnifySetters() throws {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n        let parentPackage1 = \"Parent1\"\n        let parentPackage2 = \"Parent2\"\n\n        map[packageId] = EnabledTraits([\n            EnabledTrait(name: \"Apple\", setBy: .package(.init(identity: parentPackage1)))\n        ])\n\n        map[packageId] = EnabledTraits([\n            EnabledTrait(name: \"Apple\", setBy: .package(.init(identity: parentPackage2)))\n        ])\n\n        var traits = map[packageId]\n        let appleTrait = try traits.unwrapRemove(\"Apple\")\n\n        // The Apple trait should have both setters\n        #expect(appleTrait.setters.count == 2)\n        #expect(appleTrait.setters.contains(.package(.init(identity: parentPackage1))))\n        #expect(appleTrait.setters.contains(.package(.init(identity: parentPackage2))))\n    }\n\n    /// Verifies the `explicitlyEnabledTraitsFor` subscript returns `nil` for packages\n    /// without explicitly set traits.\n    @Test\n    func enabledTraitsMap_explicitlyEnabledTraitsReturnsNilForDefault() {\n        let map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n\n        // No traits have been set, so explicit traits should be nil\n        #expect(map[explicitlyEnabledTraitsFor: packageId] == nil)\n\n        // But regular subscript should return [\"default\"]\n        #expect(map[packageId] == [\"default\"])\n    }\n\n    /// Tests that `explicitlyEnabledTraitsFor` returns the actual traits when they are set.\n    @Test\n    func enabledTraitsMap_explicitlyEnabledTraitsReturnsSetTraits() {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n\n        map[packageId] = [\"Apple\", \"Banana\"]\n\n        let explicitTraits = map[explicitlyEnabledTraitsFor: packageId]\n\n        #expect(explicitTraits != nil)\n        #expect(explicitTraits == [\"Apple\", \"Banana\"])\n    }\n\n    /// Verifies that `dictionaryLiteral` property returns the underlying storage as a dictionary.\n    @Test\n    func enabledTraitsMap_dictionaryLiteralReturnsStorage() {\n        var map = EnabledTraitsMap()\n\n        map[\"PackageA\"] = [\"Apple\", \"Banana\"]\n        map[\"PackageB\"] = [\"Coffee\"]\n\n        let dictionary = map.dictionaryLiteral\n\n        #expect(dictionary.count == 2)\n        #expect(dictionary[\"PackageA\"] == [\"Apple\", \"Banana\"])\n        #expect(dictionary[\"PackageB\"] == [\"Coffee\"])\n    }\n\n    /// Tests that after setting default traits explicitly, they are omitted from `dictionaryLiteral`.\n    @Test\n    func enabledTraitsMap_dictionaryLiteralOmitsDefaultTraits() {\n        var map = EnabledTraitsMap()\n\n        map[\"PackageA\"] = [\"Apple\", \"Banana\"]\n        map[\"PackageB\"] = [\"default\"]  // Should not be stored\n\n        let dictionary = map.dictionaryLiteral\n\n        // Only PackageA should be in the dictionary\n        #expect(dictionary.count == 1)\n        #expect(dictionary[\"PackageA\"] == [\"Apple\", \"Banana\"])\n        #expect(dictionary[\"PackageB\"] == nil)\n    }\n\n    /// Verifies behavior when mixing default and non-default traits in a single set operation.\n    @Test\n    func enabledTraitsMap_setMixedDefaultAndNonDefaultTraits() {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n\n        // Set traits including \"default\"\n        map[packageId] = [\"Apple\", \"default\", \"Banana\"]\n\n        // The traits should be stored since there are non-default traits\n        #expect(map[packageId].contains(\"Apple\"))\n        #expect(map[packageId].contains(\"Banana\"))\n        #expect(map[packageId].contains(\"default\"))\n\n        // Should have explicit entry\n        #expect(map[explicitlyEnabledTraitsFor: packageId] != nil)\n    }\n\n    /// Tests that multiple packages can be stored independently in the map.\n    @Test\n    func enabledTraitsMap_multiplePackagesIndependent() {\n        var map = EnabledTraitsMap()\n        let packageA = \"PackageA\"\n        let packageB = \"PackageB\"\n        let packageC = \"PackageC\"\n\n        map[packageA] = [\"Apple\"]\n        map[packageB] = [\"Banana\"]\n        // PackageC not set, should default\n\n        #expect(map[packageA] == [\"Apple\"])\n        #expect(map[packageB] == [\"Banana\"])\n        #expect(map[packageC] == [\"default\"])\n\n        #expect(map[explicitlyEnabledTraitsFor: packageA] != nil)\n        #expect(map[explicitlyEnabledTraitsFor: packageB] != nil)\n        #expect(map[explicitlyEnabledTraitsFor: packageC] == nil)\n    }\n\n    // MARK: - Disablers Tests\n\n    /// Verifies that setting an empty trait set with a setter records the disabler.\n    /// Disablers track explicit [] assignments, which disable default traits.\n    @Test\n    func enabledTraitsMap_emptyTraitsRecordsDisabler() throws {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n        let parentPackage = \"ParentPackage\"\n\n        // Parent package explicitly sets [] to disable default traits\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage)))\n\n        // Should record the disabler\n        let disablers = try #require(map[disablersFor: packageId])\n        #expect(disablers.count == 1)\n        #expect(disablers.first == .package(.init(identity: parentPackage)))\n    }\n\n    /// Tests that the `disabledBy` property correctly identifies the setter that explicitly set [].\n    /// This tracks who disabled default traits.\n    @Test\n    func enabledTraits_disabledByIdentifiesSetter() {\n        let parentPackage = \"ParentPackage\"\n        let traits = EnabledTraits([], setBy: .package(.init(identity: parentPackage)))\n\n        #expect(traits.isEmpty)\n        #expect(traits.disabledBy == .package(.init(identity: parentPackage)))\n    }\n\n    /// Verifies that a non-empty trait set has no disabler.\n    /// Disablers only track explicit [] assignments.\n    @Test\n    func enabledTraits_nonEmptyTraitsHaveNoDisabler() {\n        let traits = EnabledTraits([\"Apple\", \"Banana\"], setBy: .traitConfiguration)\n\n        #expect(!traits.isEmpty)\n        #expect(traits.disabledBy == nil)\n    }\n\n    /// Tests that multiple disablers can be recorded for the same package.\n    /// Multiple parties can each explicitly disable default traits with [].\n    @Test\n    func enabledTraitsMap_multipleDisablersRecorded() throws {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n        let parentPackage1 = \"Parent1\"\n        let parentPackage2 = \"Parent2\"\n\n        // First parent explicitly disables defaults with []\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage1)))\n\n        // Second parent also explicitly disables defaults with []\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage2)))\n\n        let disablers = try #require(map[disablersFor: packageId])\n        #expect(disablers.count == 2)\n        #expect(disablers.contains(.package(.init(identity: parentPackage1))) == true)\n        #expect(disablers.contains(.package(.init(identity: parentPackage2))) == true)\n    }\n\n    /// Verifies that disablers from trait configuration are recorded.\n    /// User can explicitly disable default traits via command line with [].\n    @Test\n    func enabledTraitsMap_traitConfigurationDisabler() throws {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n\n        // User explicitly disables defaults via command line with []\n        map[packageId] = EnabledTraits([], setBy: .traitConfiguration)\n\n        let disablers = try #require(map[disablersFor: packageId])\n        #expect(disablers.count == 1)\n        #expect(disablers.contains(.traitConfiguration) == true)\n    }\n\n    /// Tests that a package with no disablers returns nil for the disablers subscript.\n    /// Non-empty trait sets don't create disablers.\n    @Test\n    func enabledTraitsMap_noDisablersReturnsNil() {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n\n        // Set some traits (not empty, so no disabler)\n        map[packageId] = EnabledTraits([\"Apple\"], setBy: .traitConfiguration)\n\n        let disablers = map[disablersFor: packageId]\n        #expect(disablers == nil)\n    }\n\n    /// Verifies that disablers track explicit disablement while traits can still be enabled by other setters.\n    /// This demonstrates the unified nature: a package can have both disablers AND enabled traits.\n    @Test\n    func enabledTraitsMap_disablersCoexistWithEnabledTraits() {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n        let parentPackage = \"ParentPackage\"\n\n        // Parent package explicitly disables default traits with []\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage)))\n\n        // Then trait configuration explicitly enables some traits\n        map[packageId] = EnabledTraits([\"Apple\"], setBy: .traitConfiguration)\n\n        // Disablers should be recorded (parent disabled defaults)\n        let disablers = map[disablersFor: packageId]\n        #expect(disablers != nil)\n        #expect(disablers?.contains(.package(.init(identity: parentPackage))) == true)\n\n        // And traits should be present (configuration enabled traits)\n        #expect(map[packageId].contains(\"Apple\"))\n        #expect(map[packageId].count == 1)\n        #expect(!map[packageId].contains(\"default\"))\n    }\n\n    /// Tests the distinction between an unset package and a package with explicitly disabled default traits.\n    /// Disabling (setting []) means \"don't use default traits\", but the package still returns defaults\n    /// if no other traits are explicitly enabled.\n    @Test\n    func enabledTraitsMap_distinguishUnsetVsDisabled() {\n        var map = EnabledTraitsMap()\n        let unsetPackage = \"UnsetPackage\"\n        let disabledPackage = \"DisabledPackage\"\n        let parentPackage = \"ParentPackage\"\n\n        // Parent explicitly disables default traits with []\n        map[disabledPackage] = EnabledTraits([], setBy: .package(.init(identity: parentPackage)))\n\n        // Unset package: never touched, no disablers\n        #expect(map[unsetPackage] == [\"default\"])\n        #expect(map[explicitlyEnabledTraitsFor: unsetPackage] == nil)\n        #expect(map[disablersFor: unsetPackage] == nil)\n\n        // Disabled package: explicitly set to [], has disablers, and returns empty set\n        #expect(map[disabledPackage] == [])\n        #expect(map[explicitlyEnabledTraitsFor: disabledPackage] == [])\n        #expect(map[disablersFor: disabledPackage] != nil)\n    }\n\n    /// Verifies that initializing EnabledTraits with an empty string collection creates a disabler.\n    /// Empty [] means \"explicitly disable default traits\".\n    @Test\n    func enabledTraits_initWithEmptyCollectionCreatesDisabler() {\n        let emptyTraits: [String] = []\n        let traits = EnabledTraits(emptyTraits, setBy: .traitConfiguration)\n\n        #expect(traits.isEmpty)\n        #expect(traits.disabledBy == .traitConfiguration)\n    }\n\n    /// Verifies that the same disabler set multiple times only appears once in the set.\n    /// Set semantics ensure unique disablers.\n    @Test\n    func enabledTraitsMap_duplicateDisablerOnlyStoredOnce() {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n        let parentPackage = \"ParentPackage\"\n\n        // Set the same disabler multiple times\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage)))\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage)))\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage)))\n\n        let disablers = map[disablersFor: packageId]\n        #expect(disablers != nil)\n        #expect(disablers?.count == 1)\n        #expect(disablers?.contains(.package(.init(identity: parentPackage))) == true)\n    }\n\n    /// Tests that when one package disables defaults with [] but another package enables traits\n    /// (including default), the unified map contains the enabled traits plus records the disabler.\n    @Test\n    func enabledTraitsMap_disablerAndEnabledTraitsCoexist() {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n        let parentPackage1 = \"Parent1\"\n        let parentPackage2 = \"Parent2\"\n\n        // Parent1 explicitly disables default traits with []\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage1)))\n\n        // Parent2 enables default trait for the same package\n        map[packageId] = EnabledTraits([\"default\"], setBy: .package(.init(identity: parentPackage2)))\n\n        // The disabler should be recorded\n        let disablers = map[disablersFor: packageId]\n        #expect(disablers != nil)\n        #expect(disablers?.contains(.package(.init(identity: parentPackage1))) == true)\n\n        // And the default trait should be returned from the map,\n        // but not included in the explicitly enabled traits set itself.\n        #expect(map[packageId].contains(\"default\"))\n        #expect(map[explicitlyEnabledTraitsFor: packageId] == nil)\n    }\n\n    /// Tests that when one package disables defaults and another enables non-default traits,\n    /// both the disabler and the enabled traits are tracked.\n    @Test\n    func enabledTraitsMap_disablerWithNonDefaultTraitsEnabled() {\n        var map = EnabledTraitsMap()\n        let packageId = \"MyPackage\"\n        let parentPackage1 = \"Parent1\"\n        let parentPackage2 = \"Parent2\"\n\n        // Parent1 disables defaults with []\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parentPackage1)))\n\n        // Parent2 enables specific traits\n        map[packageId] = EnabledTraits([\"Apple\", \"Banana\"], setBy: .package(.init(identity: parentPackage2)))\n\n        // Disabler should be recorded\n        let disablers = map[disablersFor: packageId]\n        #expect(disablers != nil)\n        #expect(disablers?.contains(.package(.init(identity: parentPackage1))) == true)\n\n        // Traits should be present\n        #expect(map[packageId].contains(\"Apple\"))\n        #expect(map[packageId].contains(\"Banana\"))\n        #expect(!map[packageId].contains(\"default\"))\n        #expect(map[packageId].count == 2)\n        #expect(map[explicitlyEnabledTraitsFor: packageId] == [\"Apple\", \"Banana\"])\n    }\n\n    // MARK: - Default Setters Tests\n\n    /// Verifies that explicitly-set defaults are tracked in _defaultSetters and not stored\n    @Test\n    func enabledTraitsMap_defaultSettersTrackedNotStored() {\n        var map = EnabledTraitsMap()\n        let packageId = \"ChildPackage\"\n        let parentId = \"ParentPackage\"\n\n        // Parent explicitly sets default\n        map[packageId] = EnabledTraits([\"default\"], setBy: .package(.init(identity: parentId)))\n\n        // Default setter should be tracked\n        let defaultSetters = map[defaultSettersFor: packageId]\n        #expect(defaultSetters != nil)\n        #expect(defaultSetters?.contains(.package(.init(identity: parentId))) == true)\n\n        // But \"default\" should NOT be in storage\n        #expect(map[explicitlyEnabledTraitsFor: packageId] == nil)\n\n        // The getter should still return [\"default\"] (sentinel value)\n        #expect(map[packageId] == [\"default\"])\n    }\n\n    /// Verifies that multiple parents can set defaults and all are tracked\n    @Test\n    func enabledTraitsMap_multipleDefaultSetters() {\n        var map = EnabledTraitsMap()\n        let packageId = \"ChildPackage\"\n        let parent1 = \"Parent1\"\n        let parent2 = \"Parent2\"\n\n        // Both parents set defaults\n        map[packageId] = EnabledTraits([\"default\"], setBy: .package(.init(identity: parent1)))\n        map[packageId] = EnabledTraits([\"default\"], setBy: .package(.init(identity: parent2)))\n\n        // Both should be tracked\n        let defaultSetters = map[defaultSettersFor: packageId]\n        #expect(defaultSetters?.count == 2)\n        #expect(defaultSetters?.contains(.package(.init(identity: parent1))) == true)\n        #expect(defaultSetters?.contains(.package(.init(identity: parent2))) == true)\n    }\n\n    /// Verifies that default setters coexist with disablers\n    @Test\n    func enabledTraitsMap_defaultSettersCoexistWithDisablers() {\n        var map = EnabledTraitsMap()\n        let packageId = \"ChildPackage\"\n        let parent1 = \"Parent1\"\n        let parent2 = \"Parent2\"\n\n        // Parent1 disables traits\n        map[packageId] = EnabledTraits([], setBy: .package(.init(identity: parent1)))\n\n        // Parent2 wants defaults\n        map[packageId] = EnabledTraits([\"default\"], setBy: .package(.init(identity: parent2)))\n\n        // Both should be tracked independently\n        let disablers = map[disablersFor: packageId]\n        let defaultSetters = map[defaultSettersFor: packageId]\n\n        #expect(disablers?.contains(.package(.init(identity: parent1))) == true)\n        #expect(defaultSetters?.contains(.package(.init(identity: parent2))) == true)\n    }\n\n    /// Verifies that default setters coexist with explicit traits\n    @Test\n    func enabledTraitsMap_defaultSettersCoexistWithExplicitTraits() {\n        var map = EnabledTraitsMap()\n        let packageId = \"ChildPackage\"\n        let parent1 = \"Parent1\"\n        let parent2 = \"Parent2\"\n\n        // Parent1 explicitly enables Feature1\n        map[packageId] = EnabledTraits([\"Feature1\"], setBy: .package(.init(identity: parent1)))\n\n        // Parent2 wants defaults\n        map[packageId] = EnabledTraits([\"default\"], setBy: .package(.init(identity: parent2)))\n\n        // Default setters should be tracked\n        let defaultSetters = map[defaultSettersFor: packageId]\n        #expect(defaultSetters?.contains(.package(.init(identity: parent2))) == true)\n\n        // And explicit traits should be stored\n        #expect(map[packageId].contains(\"Feature1\"))\n    }\n\n    /// Verifies that setting sentinel .defaults doesn't create a default setter\n    @Test\n    func enabledTraitsMap_sentinelDefaultsDoesNotCreateSetter() {\n        var map = EnabledTraitsMap()\n        let packageId = \"Package\"\n\n        // Set sentinel .defaults\n        map[packageId] = .defaults\n\n        // No default setters should be recorded\n        #expect(map[defaultSettersFor: packageId] == nil)\n        #expect(map[explicitlyEnabledTraitsFor: packageId] == nil)\n    }\n\n    /// Verifies that traitConfiguration can also set defaults and be tracked\n    @Test\n    func enabledTraitsMap_traitConfigurationAsDefaultSetter() throws {\n        var map = EnabledTraitsMap()\n        let packageId = \"Package\"\n\n        // Trait configuration sets default\n        map[packageId] = EnabledTraits([\"default\"], setBy: .traitConfiguration)\n\n        // Should be tracked\n        let defaultSetters = try #require(map[defaultSettersFor: packageId])\n        #expect(defaultSetters.contains(.traitConfiguration) == true)\n    }\n\n    /// Verifies that no default setters exist for unset packages\n    @Test\n    func enabledTraitsMap_noDefaultSettersForUnsetPackage() {\n        let map = EnabledTraitsMap()\n        let packageId = \"UnsetPackage\"\n\n        // Never touched\n        #expect(map[defaultSettersFor: packageId] == nil)\n    }\n}\n\n\n// MARK: - Test Helpers\nextension EnabledTraits {\n    /// Helper method that removes a trait from the set and unwraps the returned optional.\n    /// This method asserts that the trait exists in the set before removal, making tests\n    /// more concise by combining removal and nil-checking in a single operation.\n    package mutating func unwrapRemove(_ trait: Element) throws -> Element {\n        let optionalTrait = self.remove(trait)\n        let trait = try #require(optionalTrait)\n        return trait\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/InstalledSwiftPMConfigurationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\n@testable import PackageModel\n\nfinal class InstalledSwiftPMConfigurationTests: XCTestCase {\n    func testVersionDescription() {\n        do {\n            let version = InstalledSwiftPMConfiguration.Version(major: 509, minor: 0, patch: 0)\n            XCTAssertEqual(version.description, \"509.0.0\")\n        }\n        do {\n            let version = InstalledSwiftPMConfiguration.Version(major: 509, minor: 0, patch: 0, prereleaseIdentifier: \"alpha1\")\n            XCTAssertEqual(version.description, \"509.0.0-alpha1\")\n        }\n        do {\n            let version = InstalledSwiftPMConfiguration.Version(major: 509, minor: 0, patch: 0, prereleaseIdentifier: \"beta.1\")\n            XCTAssertEqual(version.description, \"509.0.0-beta.1\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/ManifestTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport PackageModel\nimport XCTest\n\nclass ManifestTests: XCTestCase {\n    func testRequiredTargets() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n            TargetDescription(name: \"Baz\", dependencies: [\"MyPlugin\"]),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n            TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(manifest.targetsRequired(for: .everything).map(\\.name).sorted(), [\n                \"Bar\",\n                \"Baz\",\n                \"Foo\",\n                \"FooBar\",\n                \"MyPlugin\",\n            ])\n        }\n\n        do {\n            let manifest = Manifest.createLocalSourceControlManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(manifest.targetsRequired(for: .specific([\"Foo\", \"Bar\"])).map(\\.name).sorted(), [\n                \"Bar\",\n                \"Baz\",\n                \"Foo\",\n                \"MyPlugin\",\n            ])\n        }\n    }\n\n    func testRequiredDependencies() throws {\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Bar2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Bar3\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo1\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo1\", dependencies: [\"Foo2\", \"Bar1\"]),\n            TargetDescription(name: \"Foo2\", dependencies: [.product(name: \"B2\", package: \"Bar2\")]),\n            TargetDescription(name: \"Foo3\", dependencies: [\"Bar3\"]),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5,\n                dependencies: dependencies,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(\n                try manifest.dependenciesRequired(for: .everything).map(\\.identity.description).sorted(),\n                [\n                    \"bar1\",\n                    \"bar2\",\n                    \"bar3\",\n                ]\n            )\n        }\n\n        do {\n            let manifest = Manifest.createLocalSourceControlManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5,\n                dependencies: dependencies,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(\n                try manifest.dependenciesRequired(for: .specific([\"Foo\"])).map(\\.identity.description).sorted(),\n                [\n                    \"bar1\", // Foo → Foo1 → Bar1\n                    \"bar2\", // Foo → Foo1 → Foo2 → Bar2\n                    \"bar3\", // Foo → Foo1 → Bar1 → could be from any package due to pre‐5.2 tools version.\n                ]\n            )\n        }\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(\n                try manifest.dependenciesRequired(for: .everything).map(\\.identity.description).sorted(),\n                [\n                    \"bar1\",\n                    \"bar2\",\n                    \"bar3\",\n                ]\n            )\n        }\n\n        do {\n            let manifest = Manifest.createLocalSourceControlManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets\n            )\n\n            #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n            XCTAssertEqual(\n                manifest.dependenciesRequired(for: .specific([\"Foo\"]), nil).map(\\.identity.description).sorted(),\n                [\n                    \"bar1\", // Foo → Foo1 → Bar1\n                    \"bar2\", // Foo → Foo1 → Foo2 → Bar2\n                    // (Bar3 is unreachable.)\n                ]\n            )\n            #endif\n        }\n    }\n\n    func testIsTraitEnabled_WhenNoTraitsInManifest() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n            TargetDescription(name: \"Baz\", dependencies: [\"MyPlugin\"]),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n            TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n        ]\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/MyPlugin\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: [],\n                pruneDependencies: true // Since all dependencies are used, this shouldn't affect the outcome.\n            )\n\n            let enabledTraits = EnabledTraits(traits.map(\\.name), setBy: .traitConfiguration)\n            for trait in traits.sorted(by: { $0.name < $1.name }) {\n                XCTAssertThrowsError(try manifest.isTraitEnabled(trait, enabledTraits)) { error in\n                    XCTAssertEqual(\"\\(error)\", \"\"\"\n                    Trait '\\(\n                        trait\n                            .name\n                    )' is not declared by package 'foo' (Foo). There are no available traits declared by this package.\n                    \"\"\")\n                }\n            }\n        }\n    }\n\n    func testIsTraitEnabled_WhenInvalidTraitQueried() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n            TargetDescription(name: \"Baz\", dependencies: [\"MyPlugin\"]),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n            TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n        ]\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/MyPlugin\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: traits,\n                pruneDependencies: true // Since all dependencies are used, this shouldn't affect the outcome.\n            )\n\n            // Test `isTraitEnabled` when the trait we're querying for does not exist.\n            XCTAssertThrowsError(try manifest.isTraitEnabled(.init(stringLiteral: \"IDontExist\"), [\"default\"])) { error in\n                XCTAssertEqual(\"\\(error)\", \"\"\"\n                Trait 'IDontExist' is not declared by package 'foo' (Foo). The available traits declared by this package are: Trait1, Trait2.\n                \"\"\")\n            }\n\n            // Test `isTraitEnabled` when the set of enabled traits contains a trait that isn't defined in the package.\n            XCTAssertThrowsError(try manifest.isTraitEnabled(.init(stringLiteral: \"Trait1\"), [\"IDontExist\"])) { error in\n                XCTAssertEqual(\"\\(error)\", \"\"\"\n                Trait 'IDontExist' is not declared by package 'foo' (Foo). The available traits declared by this package are: Trait1, Trait2.\n                \"\"\")\n            }\n\n            // Test `isTraitEnabled` when the set of enabled traits contains a trait that isn't defined in the package, and the queried trait is the same non-existant trait.\n            XCTAssertThrowsError(try manifest.isTraitEnabled(.init(stringLiteral: \"IDontExist\"), [\"IDontExist\"])) { error in\n                XCTAssertEqual(\"\\(error)\", \"\"\"\n                Trait 'IDontExist' is not declared by package 'foo' (Foo). The available traits declared by this package are: Trait1, Trait2.\n                \"\"\")\n            }\n\n            // Test `isTraitEnabled` when the set of enabled traits contains a trait that isn't defined in the package, and the queried trait is another non-existant trait.\n            XCTAssertThrowsError(try manifest.isTraitEnabled(.init(stringLiteral: \"IDontExistPart2\"), [\"IDontExist\"])) { error in\n                XCTAssertEqual(\"\\(error)\", \"\"\"\n                Trait 'IDontExistPart2' is not declared by package 'foo' (Foo). The available traits declared by this package are: Trait1, Trait2.\n                \"\"\")\n            }\n\n        }\n    }\n\n    func testEnabledTraits_WhenTraitsNotSupported() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n            TargetDescription(name: \"Baz\", dependencies: [\"MyPlugin\"]),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n            TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n        ]\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/MyPlugin\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: [],\n                pruneDependencies: true // Since all dependencies are used, this shouldn't affect the outcome.\n            )\n\n            // Enabled Traits when passed a TraitConfiguration:\n\n            // When passed .disableAllTraits configuration\n            XCTAssertThrowsError(try manifest.enabledTraits(using: .disableAllTraits)) { error in\n                XCTAssertEqual(\"\\(error)\", \"\"\"\n                    Disabled default traits by command-line trait configuration on package 'foo' (Foo) that declares no traits. This is prohibited to allow packages to adopt traits initially without causing an API break.\n                    \"\"\")\n            }\n\n            // When passed .enableAllTraits configuration\n            XCTAssertThrowsError(try manifest.enabledTraits(using: .enabledTraits([\"Trait1\"]))) { error in\n                XCTAssertEqual(\"\\(error)\", \"\"\"\n                    Traits [Trait1] have been enabled on package 'foo' (Foo) that declares no traits.\n                    \"\"\")\n            }\n\n            XCTAssertNoThrow(try manifest.enabledTraits(using: .enableAllTraits))\n            XCTAssertNoThrow(try manifest.enabledTraits(using: .default))\n\n            // Enabled Traits when passed explicitly enabled traits list:\n\n            // If given a parent package, and the enabled traits being passed don't exist:\n            XCTAssertThrowsError(try manifest.enabledTraits(using: [EnabledTrait(name: \"Trait1\", setBy: .package(.init(identity: \"qux\")))])) { error in\n                XCTAssertEqual(\"\\(error)\", \"\"\"\n                    Package 'qux' enables traits [Trait1] on package 'foo' (Foo) that declares no traits.\n                    \"\"\")\n            }\n\n            // If given a parent package, and the default traits are disabled:\n            XCTAssertThrowsError(try manifest.enabledTraits(using: .init([], setBy: .package(\"qux\")))) { error in\n                XCTAssertEqual(\"\\(error)\", \"\"\"\n                    Disabled default traits by package 'qux' on package 'foo' (Foo) that declares no traits. This is prohibited to allow packages to adopt traits initially without causing an API break.\n                    \"\"\")\n            }\n        }\n    }\n\n    func testIsTraitEnabled_WhenNoDefaultTraitsAndNoConfig() throws {\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Buzz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\", \"Boo\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(\n                name: \"Bar\",\n                dependencies: [.product(name: \"Baz\", package: \"Baz\", condition: .init(traits: [\"Trait2\"]))]\n            ),\n            TargetDescription(name: \"Boo\", dependencies: [.product(name: \"Buzz\", package: \"Buzz\")]),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: traits\n            )\n\n            // Assure that the trait-guarded dependencies pruned.\n            XCTAssertEqual(\n                try manifest.dependenciesRequired(for: .everything).map(\\.identity.description).sorted(),\n                [\n                    \"buzz\",\n                ]\n            )\n\n            // Assure that each trait is not enabled.\n            for trait in traits {\n                XCTAssertEqual(try manifest.isTraitEnabled(trait, [\"default\"]), false)\n            }\n\n            // Now, create a version of the same manifest but with the `pruneDependencies` flag set to true.\n            let manifestPrunedDeps = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: traits,\n                pruneDependencies: true\n            )\n\n            // Since we've enabled pruned dependencies for this manifest, we should only see \"buzz\"\n            XCTAssertEqual(\n                try manifestPrunedDeps.dependenciesRequired(for: .everything).map(\\.identity.description).sorted(),\n                [\n                    \"buzz\",\n                ]\n            )\n\n            // Assure that each trait is not enabled.\n            for trait in traits {\n                XCTAssertEqual(try manifestPrunedDeps.isTraitEnabled(trait, [\"default\"]), false)\n            }\n        }\n    }\n\n    func testIsTraitEnabled_WhenDefaultTraitsAndNoTraitConfig() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n            TargetDescription(name: \"Baz\", dependencies: [\"MyPlugin\"]),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n            TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"default\", enabledTraits: [\"Trait1\"]),\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets,\n                traits: traits\n            )\n\n            // Like the above configuration, Trait1 is on by default. When calling `isTraitEnabled`,\n            // it should calculate transitively enabled traits from here which would eventualy uncover\n            // that each trait is enabled.\n            let enabledTraits = EnabledTraits([\"Trait1\"], setBy: .trait(\"default\"))\n\n            for trait in traits.sorted(by: { $0.name < $1.name }) {\n                XCTAssertTrue(try manifest.isTraitEnabled(trait, enabledTraits))\n            }\n        }\n    }\n\n    func testEnabledTraits_WithAllTraitsDisabled() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n            TargetDescription(name: \"Baz\", dependencies: [\"MyPlugin\"]),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n            TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n        ]\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/MyPlugin\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n            TraitDescription(name: \"Trait3\")\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: traits,\n                pruneDependencies: true // Since all dependencies are used, this shouldn't affect the outcome.\n            )\n\n            XCTAssertNoThrow(try {\n                let enabledTraits = try XCTUnwrap(manifest.enabledTraits(using: .disableAllTraits))\n                XCTAssertEqual(enabledTraits, [])\n            }())\n        }\n    }\n\n    func testEnabledTraits_WithOnlyDefaultTraitsEnabled() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\"),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"default\", enabledTraits: [\"Trait1\"]),\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n            TraitDescription(name: \"Trait3\"),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets,\n                traits: traits\n            )\n\n            // Calculate the enabled traits without an explicitly declared set of enabled traits.\n            // This should default to fetching the default traits, if they exist (which in this test case\n            // they do), and then will calculate the transitive set of traits that are enabled.\n            let allEnabledTraits = try XCTUnwrap(manifest.enabledTraits(using: .default)).sorted()\n            XCTAssertEqual(allEnabledTraits, [\"Trait1\", \"Trait2\"])\n        }\n    }\n\n    func testEnabledTraits_WithExplicitTraitsEnabled() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\"),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"default\", enabledTraits: [\"Trait1\"]),\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n            TraitDescription(name: \"Trait3\"),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets,\n                traits: traits\n            )\n\n            // Calculate the enabled traits with an explicitly declared set of enabled traits.\n            // This should override the default traits (since it isn't explicitly passed in here).\n            let allEnabledTraitsWithoutDefaults = try manifest.enabledTraits(using: .enabledTraits([\"Trait3\"])).sorted()\n            XCTAssertEqual(allEnabledTraitsWithoutDefaults, [\"Trait3\"])\n\n            // Calculate the enabled traits with an explicitly declared set of enabled traits,\n            // including the default traits. Since default traits are explicitly enabled in the\n            // passed set of traits, this will be factored into the calculation.\n            let allEnabledTraitsWithDefaults = try manifest.enabledTraits(using: .enabledTraits([\"default\", \"Trait3\"])).sorted()\n            XCTAssertEqual(allEnabledTraitsWithDefaults, [\"Trait1\", \"Trait2\", \"Trait3\"])\n        }\n    }\n\n    func testEnabledTraits_WithAllTraitsEnabled() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(name: \"Foo\", dependencies: [\"Bar\"]),\n            TargetDescription(name: \"Bar\"),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"default\", enabledTraits: [\"Trait1\"]),\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n            TraitDescription(name: \"Trait3\"),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets,\n                traits: traits\n            )\n\n            // Calculate the enabled traits with all traits enabled flag.\n            let allEnabledTraits = try manifest.enabledTraits(using: .enableAllTraits).sorted()\n            XCTAssertEqual(allEnabledTraits, [\"Trait1\", \"Trait2\", \"Trait3\"])\n        }\n    }\n\n    func testTraitGuardedDependencies() throws {\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(\n                name: \"Foo\",\n                dependencies: [\n                    .product(\n                        name: \"Bar\",\n                        package: \"Bar\",\n                        condition: .init(traits: [\"Trait2\"])\n                    ),\n                    .product(\n                        name: \"Baz\",\n                        package: \"Baz\"\n                    ),\n                    .product(\n                        name: \"Bar2\",\n                        package: \"Bar\"\n                    )\n                ]\n            ),\n        ]\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"default\", enabledTraits: [\"Trait1\"]),\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n            TraitDescription(name: \"Trait3\"),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: traits\n            )\n\n            let traitGuardedDependencies = manifest.traitGuardedTargetDependencies()\n\n            XCTAssertEqual(\n                traitGuardedDependencies,\n                [\n                    \"Bar\": [\n                        .product(name: \"Bar\", package: \"Bar\", condition: .init(traits: [\"Trait2\"]))\n                    ]\n                ]\n            )\n        }\n    }\n\n    func testIsTargetDependencyEnabled() throws {\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Cosmic\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let unguardedTargetDependency: TargetDescription.Dependency = .product(\n            name: \"Bar\",\n            package: \"Blah\"\n        )\n\n        let trait3GuardedTargetDependency: TargetDescription.Dependency = .product(\n            name: \"Baz\",\n            package: \"Buzz\",\n            condition: .init(traits: [\"Trait3\"])\n        )\n\n        let defaultTraitGuardedTargetDependency: TargetDescription.Dependency = .product(\n            name: \"Bam\",\n            package: \"Boom\",\n            condition: .init(traits: [\"Trait2\"])\n        )\n\n        let enabledTargetDependencyWithSamePackage: TargetDescription.Dependency = .product(\n            name: \"Kaboom\",\n            package: \"Boom\"\n        )\n\n        let manyTraitsEnableTargetDependency: TargetDescription.Dependency = .product(\n            name: \"Supernova\",\n            package: \"Cosmic\",\n            condition: .init(traits: [\"Space\", \"Music\"])\n        )\n\n        let target = try TargetDescription(\n            name: \"Foo\",\n            dependencies: [\n                unguardedTargetDependency,\n                trait3GuardedTargetDependency,\n                defaultTraitGuardedTargetDependency,\n                enabledTargetDependencyWithSamePackage,\n                manyTraitsEnableTargetDependency\n            ]\n        )\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"default\", enabledTraits: [\"Trait1\"]),\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n            TraitDescription(name: \"Trait3\"),\n            TraitDescription(name: \"Space\"),\n            TraitDescription(name: \"Music\"),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: [target],\n                traits: traits\n            )\n\n            // Test if an unguarded target dependency is enabled; should be true.\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                unguardedTargetDependency,\n                enabledTraits: [\"default\"]\n            ))\n\n            // Test if a trait-guarded dependency is enabled when passed a set of enabled traits that\n            // unblock this target dependency; should be true.\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                trait3GuardedTargetDependency,\n                enabledTraits: [\"Trait3\"]\n            ))\n\n            // Test if a trait-guarded dependency is enabled when passed all traits enabled;\n            // should be true.\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                trait3GuardedTargetDependency,\n                enabledTraits: [\"Trait1\", \"Trait2\", \"Trait3\"]\n            ))\n\n            // Test if a trait-guarded dependency is enabled when there are no enabled traits passsed.\n            XCTAssertFalse(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                trait3GuardedTargetDependency,\n                enabledTraits: [\"default\"]\n            ))\n\n            // Test if a target dependency guarded by default traits is enabled when passed no explicitly\n            // enabled traits; should be true.\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                defaultTraitGuardedTargetDependency,\n                enabledTraits: [\"default\"]\n            ))\n\n            // Test if a target dependency guarded by default traits is enabled when passed an empty set\n            // of enabled traits, overriding the default traits; should be false.\n            XCTAssertFalse(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                defaultTraitGuardedTargetDependency,\n                enabledTraits: []\n            ))\n\n            // Test if a target dependency that isn't guarded by traits wherein it uses a product\n            // from the same package as another target dependency that is guarded by traits; should be true.\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                enabledTargetDependencyWithSamePackage,\n                enabledTraits: []\n            ))\n\n            // Test variations of traits that enable a target dependency that is unguarded by many traits.\n            XCTAssertFalse(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                manyTraitsEnableTargetDependency,\n                enabledTraits: []\n            ))\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                manyTraitsEnableTargetDependency,\n                enabledTraits: [\"Space\"]\n            ))\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                manyTraitsEnableTargetDependency,\n                enabledTraits: [\"Music\"]\n            ))\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                manyTraitsEnableTargetDependency,\n                enabledTraits: [\"Music\", \"Space\"]\n            ))\n            XCTAssertTrue(try manifest.isTargetDependencyEnabled(\n                target: \"Foo\",\n                manyTraitsEnableTargetDependency,\n                enabledTraits: [\"Trait3\", \"Music\", \"Space\", \"Trait1\", \"Trait2\"]\n            ))\n        }\n    }\n\n    func testIsPackageDependencyUsed() throws {\n        let bar: PackageDependency = .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\"))\n        let baz: PackageDependency = .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\"))\n        let bam: PackageDependency = .localSourceControl(path: \"/Bam\", requirement: .upToNextMajor(from: \"1.0.0\"))\n        let drinks: PackageDependency = .localSourceControl(path: \"/Drinks\", requirement: .upToNextMajor(from: \"1.0.0\"))\n\n        let dependencies: [PackageDependency] = [\n            bar,\n            baz,\n            bam,\n            drinks,\n        ]\n\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let unguardedTargetDependency: TargetDescription.Dependency = .product(\n            name: \"Bar\",\n            package: \"Bar\"\n        )\n\n        let trait3GuardedTargetDependency: TargetDescription.Dependency = .product(\n            name: \"Baz\",\n            package: \"Baz\",\n            condition: .init(traits: [\"Trait3\"])\n        )\n\n        let defaultTraitGuardedTargetDependency: TargetDescription.Dependency = .product(\n            name: \"Bam\",\n            package: \"Bam\",\n            condition: .init(traits: [\"Trait2\"])\n        )\n\n        let unguardedTargetDependencyWithBamPackage: TargetDescription.Dependency = .product(\n            name: \"Qux\",\n            package: \"Bam\"\n        )\n\n        let manyTraitsGuardingTargetDependency: TargetDescription.Dependency = .product(\n            name: \"Coffee\",\n            package: \"Drinks\",\n            condition: .init(traits: [\"Sugar\", \"Cream\"])\n        )\n\n        let target = try TargetDescription(\n            name: \"Foo\",\n            dependencies: [\n                unguardedTargetDependency,\n                trait3GuardedTargetDependency,\n                defaultTraitGuardedTargetDependency,\n                manyTraitsGuardingTargetDependency\n            ]\n        )\n\n        let targetWithUnguardedBamPackageDep = try TargetDescription(\n            name: \"Foo\",\n            dependencies: [\n                unguardedTargetDependency,\n                trait3GuardedTargetDependency,\n                defaultTraitGuardedTargetDependency,\n                unguardedTargetDependencyWithBamPackage,\n            ]\n        )\n\n        let traits: Set<TraitDescription> = [\n            TraitDescription(name: \"default\", enabledTraits: [\"Trait1\"]),\n            TraitDescription(name: \"Trait1\", enabledTraits: [\"Trait2\"]),\n            TraitDescription(name: \"Trait2\"),\n            TraitDescription(name: \"Trait3\"),\n            TraitDescription(name: \"Sugar\"),\n            TraitDescription(name: \"Cream\"),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: [target],\n                traits: traits\n            )\n\n            let manifestWithBamDependencyAlwaysUsed = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: [targetWithUnguardedBamPackageDep],\n                traits: traits\n            )\n\n            XCTAssertTrue(try manifest.isPackageDependencyUsed(bar, enabledTraits: []))\n            XCTAssertTrue(try manifest.isPackageDependencyUsed(baz, enabledTraits: [\"Trait3\"]))\n            XCTAssertFalse(try manifest.isPackageDependencyUsed(bam, enabledTraits: []))\n            XCTAssertFalse(try manifest.isPackageDependencyUsed(bam, enabledTraits: [\"Trait3\"]))\n            XCTAssertFalse(try manifest.isPackageDependencyUsed(drinks, enabledTraits: []))\n            XCTAssertTrue(try manifest.isPackageDependencyUsed(drinks, enabledTraits: [\"Sugar\"]))\n            XCTAssertTrue(try manifest.isPackageDependencyUsed(drinks, enabledTraits: [\"Cream\"]))\n            XCTAssertTrue(try manifest.isPackageDependencyUsed(drinks, enabledTraits: [\"Sugar\", \"Cream\"]))\n\n            // Configuration of the manifest that includes a case where there exists a target\n            // dependency that depends on the same package as another target dependency, but\n            // is unguarded by traits; therefore, this package dependency should be considered used\n            // in every scenario, regardless of the passed trait configuration.\n            XCTAssertTrue(try manifestWithBamDependencyAlwaysUsed.isPackageDependencyUsed(bam, enabledTraits: []))\n            XCTAssertTrue(try manifestWithBamDependencyAlwaysUsed.isPackageDependencyUsed(bam, enabledTraits: [\"Trait3\"]))\n        }\n    }\n\n    func testPrunedDependencies_WhenAllDependenciesUsed() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(\n                name: \"Foo\",\n                dependencies: [\n                    .product(\n                        name: \"Bar\",\n                        package: \"Bar\",\n                        condition: .init(traits: [\"Trait1\"])\n                    ),\n                ]\n            ),\n            TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n            TargetDescription(name: \"Baz\", dependencies: [\"MyPlugin\"]),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n            TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n        ]\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/MyPlugin\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: [.init(name: \"default\", enabledTraits: [\"Trait1\"]), \"Trait1\", \"Trait2\"],\n                // Since all dependencies are used, this shouldn't affect the outcome.\n                pruneDependencies: true\n            )\n\n            // The list of required dependencies should remain the same, since all depenencies are being\n            // used in the current manifest.\n            let calculatedDependencies = try manifest.dependenciesRequired(for: .everything)\n            XCTAssertEqual(calculatedDependencies.map(\\.identity).sorted(), dependencies.map(\\.identity).sorted())\n        }\n    }\n\n    func testPrunedDependencies_WhenSomeDependenciesUsed() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(\n                name: \"Foo\",\n                dependencies: [\n                    .product(\n                        // This dependency on Bar is guarded by Trait1\n                        name: \"Bar\",\n                        package: \"Bar\",\n                        condition: .init(traits: [\"Trait1\"])\n                    ),\n                ]\n            ),\n            TargetDescription(\n                name: \"Bar\",\n                dependencies: [\n                    .product(\n                        name: \"Baz\",\n                        package: \"Baz\",\n                        condition: .init(traits: [\"Trait2\"])\n                    ),\n                ]\n            ),\n            TargetDescription(\n                name: \"Baz\",\n                dependencies: [\n                    \"MyPlugin\",\n                    \"Bar\", // Bar as a dependency is not trait-guarded here\n                ]\n            ),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n        ]\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/MyPlugin\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: [.init(name: \"default\", enabledTraits: [\"Trait1\"]), \"Trait1\", \"Trait2\"],\n                pruneDependencies: true\n            )\n\n            let calculatedDependenciesWithDefaultTraits = try manifest.dependenciesRequired(for: .everything)\n            XCTAssertEqual(\n                calculatedDependenciesWithDefaultTraits.map(\\.identity).sorted(),\n                [\n                    PackageIdentity(stringLiteral: \"Bar\"),\n                    PackageIdentity(stringLiteral: \"MyPlugin\"),\n                ]\n            )\n\n            let calculatedDependenciesWithTrait2EnabledOnly = try manifest.dependenciesRequired(\n                for: .everything,\n                [\"Trait2\"]\n            )\n            XCTAssertEqual(\n                calculatedDependenciesWithTrait2EnabledOnly.map(\\.identity).sorted(),\n                [\n                    PackageIdentity(stringLiteral: \"Bar\"),\n                    PackageIdentity(stringLiteral: \"Baz\"),\n                    PackageIdentity(stringLiteral: \"MyPlugin\"),\n                ]\n            )\n\n            let calculatedDependenciesWithAllTraitsEnabled = try manifest.dependenciesRequired(\n                for: .everything,\n                [\"Trait1\", \"Trait2\"]\n            )\n            XCTAssertEqual(\n                calculatedDependenciesWithAllTraitsEnabled.map(\\.identity).sorted(),\n                [\n                    PackageIdentity(stringLiteral: \"Bar\"),\n                    PackageIdentity(stringLiteral: \"Baz\"),\n                    PackageIdentity(stringLiteral: \"MyPlugin\"),\n                ]\n            )\n        }\n    }\n\n    func testDependenciesGuardedByTraits_WithTraitConfigurations() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n            ProductDescription(name: \"Bar\", type: .library(.automatic), targets: [\"Bar\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(\n                name: \"Foo\",\n                dependencies: [\n                    .product(\n                        name: \"Bar\",\n                        package: \"Bar\",\n                        condition: .init(traits: [\"Trait1\"])\n                    ),\n                ]\n            ),\n            TargetDescription(name: \"Bar\", dependencies: [\"Baz\"]),\n            TargetDescription(name: \"Baz\", dependencies: [\"MyPlugin\"]),\n            TargetDescription(name: \"FooBar\", dependencies: []),\n            TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .buildTool),\n        ]\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/MyPlugin\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets,\n                traits: [.init(name: \"default\", enabledTraits: [\"Trait1\"]), \"Trait1\", \"Trait2\"]\n            )\n\n            // With an empty list of enabled traits, the `Bar` dependency should be trait-guarded here.\n            let traitGuardedDependencies = manifest.dependenciesTraitGuarded(withEnabledTraits: [])\n            XCTAssertEqual(traitGuardedDependencies.map(\\.identity), [PackageIdentity(path: \"/Bar\")])\n\n            // When using default traits (since we omit a list of enabled traits here),\n            // `Bar` should not be trait-guarded since `Trait1` is enabled by default.\n            let noTraitGuardedDependencies = manifest.dependenciesTraitGuarded(withEnabledTraits: [\"default\"])\n            XCTAssertEqual(noTraitGuardedDependencies, [])\n        }\n    }\n\n    func testTargetDescriptionDependencyName_ForProduct() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(\n                name: \"Foo\",\n                dependencies: [\n                    .product(\n                        name: \"Bar\",\n                        package: \"Blah\"\n                    ),\n                ]\n            ),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertTrue(manifest.targets.count == 1)\n            let target = try XCTUnwrap(manifest.targets.first)\n            XCTAssertEqual(target.name, \"Foo\")\n\n            for dependency in target.dependencies {\n                XCTAssertEqual(dependency.name, \"Bar\")\n            }\n        }\n    }\n\n    func testTargetDescriptionDependencyName_ForTarget() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(\n                name: \"Foo\",\n                dependencies: [\n                    .target(\n                        name: \"Baz\"\n                    ),\n                ]\n            ),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertTrue(manifest.targets.count == 1)\n            let target = try XCTUnwrap(manifest.targets.first)\n            XCTAssertEqual(target.name, \"Foo\")\n\n            for dependency in target.dependencies {\n                XCTAssertEqual(dependency.name, \"Baz\")\n            }\n        }\n    }\n\n    func testTargetDescriptionDependencyName_ForByName() throws {\n        let products = try [\n            ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n        ]\n\n        let targets = try [\n            TargetDescription(\n                name: \"Foo\",\n                dependencies: [\n                    \"Boo\",\n                ]\n            ),\n        ]\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertTrue(manifest.targets.count == 1)\n            let target = try XCTUnwrap(manifest.targets.first)\n            XCTAssertEqual(target.name, \"Foo\")\n\n            for dependency in target.dependencies {\n                XCTAssertEqual(dependency.name, \"Boo\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/MinimumDeploymentTargetTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import PackageModel\nimport XCTest\n\nimport struct Basics.AsyncProcessResult\n\nfinal class MinimumDeploymentTargetTests: XCTestCase {\n    func testDoesNotAssertWithNoOutput() throws {\n        #if !os(macOS)\n        // these tests eventually call `xcrun`.\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let result = AsyncProcessResult(\n            arguments: [],\n            environment: [:],\n            exitStatus: .terminated(code: 0),\n            output: \"\".asResult,\n            stderrOutput: \"xcodebuild: error: SDK \\\"macosx\\\" cannot be located.\".asResult\n        )\n\n        XCTAssertNil(try MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(with: result, platform: .macOS))\n    }\n\n    func testThrowsWithNonPathOutput() throws {\n        #if !os(macOS)\n        // these tests eventually call `xcrun`.\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let result = AsyncProcessResult(\n            arguments: [],\n            environment: [:],\n            exitStatus: .terminated(code: 0),\n            output: \"some string\".asResult,\n            stderrOutput: \"\".asResult\n        )\n\n        XCTAssertThrowsError(try MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(\n            with: result,\n            platform: .macOS\n        ))\n    }\n\n    func testThrowsWithErrorForOutput() throws {\n        #if !os(macOS)\n        // these tests eventually call `xcrun`.\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let result = AsyncProcessResult(\n            arguments: [],\n            environment: [:],\n            exitStatus: .terminated(code: 0),\n            output: .failure(DummyError()),\n            stderrOutput: \"\".asResult\n        )\n\n        XCTAssertThrowsError(try MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(\n            with: result,\n            platform: .macOS\n        ))\n    }\n}\n\nprivate struct DummyError: Error {}\n\nextension String {\n    fileprivate var asResult: Result<[UInt8], Error> {\n        .success(Array(utf8))\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/PackageIdentityNameTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\nimport Basics\nimport PackageModel\n\nclass PackageIdentityNameTests: XCTestCase {\n    func testValidNames() throws {\n        XCTAssertNoThrow(try PackageIdentity.Name(validating: \"LinkedList\"))\n        XCTAssertNoThrow(try PackageIdentity.Name(validating: \"Linked-List\"))\n        XCTAssertNoThrow(try PackageIdentity.Name(validating: \"Linked_List\"))\n        XCTAssertNoThrow(try PackageIdentity.Name(validating: \"A\"))\n        XCTAssertNoThrow(try PackageIdentity.Name(validating: \"1\"))\n        XCTAssertNoThrow(try PackageIdentity.Name(validating: String(repeating: \"A\", count: 100)))\n    }\n\n    func testInvalidNames() throws {\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"The minimum length of a package name is 1 character.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: String(repeating: \"a\", count: 101))) { error in\n            XCTAssertEqual(error.localizedDescription, \"The maximum length of a package name is 100 characters.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"!\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"A package name consists of alphanumeric characters, underscores, and hyphens.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"あ\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"A package name consists of alphanumeric characters, underscores, and hyphens.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"🧍\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"A package name consists of alphanumeric characters, underscores, and hyphens.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"-a\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens and underscores may not occur at the beginning of a name.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"_a\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens and underscores may not occur at the beginning of a name.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"a-\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens and underscores may not occur at the end of a name.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"a_\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens and underscores may not occur at the end of a name.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"a_-a\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens and underscores may not occur consecutively within a name.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"a-_a\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens and underscores may not occur consecutively within a name.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"a--a\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens and underscores may not occur consecutively within a name.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Name(validating: \"a__a\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens and underscores may not occur consecutively within a name.\")\n        }\n    }\n\n    func testNamesAreCaseInsensitive() throws {\n        let lowercase: PackageIdentity.Name = \"linkedlist\"\n        let uppercase: PackageIdentity.Name = \"LINKEDLIST\"\n\n        XCTAssertEqual(lowercase, uppercase)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/PackageIdentityParser.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\n@testable import PackageModel\n\nfinal class PackageIdentityParserTests: XCTestCase {\n    func testPackageIdentityDescriptions() {\n        XCTAssertEqual(PackageIdentityParser(\"foo\").description, \"foo\")\n        XCTAssertEqual(PackageIdentityParser(\"/foo\").description, \"foo\")\n        XCTAssertEqual(PackageIdentityParser(\"/foo/bar\").description, \"bar\")\n        XCTAssertEqual(PackageIdentityParser(\"foo/bar\").description, \"bar\")\n        XCTAssertEqual(PackageIdentityParser(\"https://foo/bar/baz\").description, \"baz\")\n        XCTAssertEqual(PackageIdentityParser(\"git@github.com/foo/bar/baz\").description, \"baz\")\n        XCTAssertEqual(PackageIdentityParser(\"/path/to/foo/bar/baz/\").description, \"baz\")\n        XCTAssertEqual(PackageIdentityParser(\"https://foo/bar/baz.git\").description, \"baz\")\n        XCTAssertEqual(PackageIdentityParser(\"git@github.com/foo/bar/baz.git\").description, \"baz\")\n        XCTAssertEqual(PackageIdentityParser(\"/path/to/foo/bar/baz.git\").description, \"baz\")\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/PackageIdentityScopeTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\nimport Basics\nimport PackageModel\n\nclass PackageIdentityScopeTests: XCTestCase {\n    func testValidScopes() throws {\n        XCTAssertNoThrow(try PackageIdentity.Scope(validating: \"mona\"))\n        XCTAssertNoThrow(try PackageIdentity.Scope(validating: \"m-o-n-a\"))\n        XCTAssertNoThrow(try PackageIdentity.Scope(validating: \"a\"))\n        XCTAssertNoThrow(try PackageIdentity.Scope(validating: \"1\"))\n        XCTAssertNoThrow(try PackageIdentity.Scope(validating: String(repeating: \"a\", count: 39)))\n    }\n\n    func testInvalidScopes() throws {\n        XCTAssertThrowsError(try PackageIdentity.Scope(validating: \"\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"The minimum length of a package scope is 1 character.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Scope(validating: String(repeating: \"a\", count: 100))) { error in\n            XCTAssertEqual(error.localizedDescription, \"The maximum length of a package scope is 39 characters.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Scope(validating: \"!\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"A package scope consists of alphanumeric characters and hyphens.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Scope(validating: \"あ\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"A package scope consists of alphanumeric characters and hyphens.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Scope(validating: \"🧍\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"A package scope consists of alphanumeric characters and hyphens.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Scope(validating: \"-a\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens may not occur at the beginning of a scope.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Scope(validating: \"a-\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens may not occur at the end of a scope.\")\n        }\n\n        XCTAssertThrowsError(try PackageIdentity.Scope(validating: \"a--a\")) { error in\n            XCTAssertEqual(error.localizedDescription, \"Hyphens may not occur consecutively within a scope.\")\n        }\n    }\n\n    func testScopesAreCaseInsensitive() throws {\n        let lowercase: PackageIdentity.Scope = \"mona\"\n        let uppercase: PackageIdentity.Scope = \"MONA\"\n\n        XCTAssertEqual(lowercase, uppercase)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/PackageModelTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n\n@_spi(SwiftPMInternal)\n@testable import PackageModel\n\nimport _InternalTestSupport\nimport func TSCBasic.withTemporaryFile\nimport XCTest\n\nimport struct TSCBasic.ByteString\n\nfinal class PackageModelTests: XCTestCase {\n    func testProductTypeCodable() throws {\n        struct Foo: Codable, Equatable {\n            var type: ProductType\n        }\n\n        func checkCodable(_ type: ProductType) {\n            do {\n                let foo = Foo(type: type)\n                let data = try JSONEncoder.makeWithDefaults().encode(foo)\n                let decodedFoo = try JSONDecoder.makeWithDefaults().decode(Foo.self, from: data)\n                XCTAssertEqual(foo, decodedFoo)\n            } catch {\n                XCTFail(\"\\(error)\")\n            }\n        }\n\n        checkCodable(.library(.automatic))\n        checkCodable(.library(.static))\n        checkCodable(.library(.dynamic))\n        checkCodable(.executable)\n        checkCodable(.test)\n    }\n\n    func testProductFilterCodable() throws {\n        // Test ProductFilter.everything\n        try {\n            let data = try JSONEncoder().encode(ProductFilter.everything)\n            let decoded = try JSONDecoder().decode(ProductFilter.self, from: data)\n            XCTAssertEqual(decoded, ProductFilter.everything)\n        }()\n        // Test ProductFilter.specific(), including that the order is normalized\n        try {\n            let data = try JSONEncoder().encode(ProductFilter.specific([\"Bar\", \"Foo\"]))\n            let decoded = try JSONDecoder().decode(ProductFilter.self, from: data)\n            XCTAssertEqual(decoded, ProductFilter.specific([\"Foo\", \"Bar\"]))\n        }()\n    }\n\n    func testAndroidCompilerFlags() throws {\n        let triple = try Triple(\"x86_64-unknown-linux-android\")\n        let fileSystem = InMemoryFileSystem()\n        let sdkDir = AbsolutePath(\"/some/path/to/an/SDK.sdk\")\n        try fileSystem.createDirectory(sdkDir, recursive: true)\n        let toolchainPath = AbsolutePath(\"/some/path/to/a/toolchain.xctoolchain\")\n        try fileSystem.createDirectory(toolchainPath, recursive: true)\n\n        let swiftSDK = SwiftSDK(\n            targetTriple: triple,\n            toolset: .init(toolchainBinDir: toolchainPath.appending(components: \"usr\", \"bin\"), buildFlags: .init()),\n            pathsConfiguration: .init(sdkRootPath: sdkDir)\n        )\n\n        XCTAssertEqual(\n            try UserToolchain.deriveSwiftCFlags(\n                triple: triple,\n                swiftSDK: swiftSDK,\n                environment: .current,\n                fileSystem: fileSystem\n            ).map { $0.value },\n            [\n                // Needed when cross‐compiling for Android. 2020‐03‐01\n                \"-sdk\",\n                sdkDir.pathString,\n            ]\n        )\n    }\n\n    // tiny PE binary from: https://archive.is/w01DO\n    static let tinyPEBytes: [UInt8] = [\n        0x4D, 0x5A, 0x00, 0x00, 0x50, 0x45, 0x00, 0x00, 0x4C, 0x01, 0x01, 0x00,\n        0x6A, 0x2A, 0x58, 0xC3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x04, 0x00, 0x03, 0x01, 0x0B, 0x01, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00,\n        0x04, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00,\n        0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,\n        0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x68, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n        0x02,\n    ]\n\n    func testWindowsLibrarianSelection() throws {\n\n        #if os(Windows)\n        let suffix = \".exe\"\n        #else\n        let suffix = \"\"\n        #endif\n\n        let triple = try Triple(\"x86_64-unknown-windows-msvc\")\n        let fs = localFileSystem\n\n        try withTemporaryFile { _ in\n            try withTemporaryDirectory(removeTreeOnDeinit: true) { tmp in\n                let contents = Self.tinyPEBytes\n                let bin = tmp.appending(\"bin\")\n                try fs.createDirectory(bin)\n\n                let lld = bin.appending(\"lld-link\\(suffix)\")\n                try fs.writeFileContents(lld, bytes: ByteString(contents))\n\n                let not = bin.appending(\"not-link\\(suffix)\")\n                try fs.writeFileContents(not, bytes: ByteString(contents))\n\n                #if !os(Windows)\n                try fs.chmod(.executable, path: lld, options: [])\n                try fs.chmod(.executable, path: not, options: [])\n                #endif\n\n                try XCTAssertEqual(\n                    UserToolchain.determineLibrarian(\n                        triple: triple, binDirectories: [bin], useXcrun: false, environment: [:], searchPaths: [],\n                        extraSwiftFlags: [\"-Xswiftc\", \"-use-ld=lld\"],\n                        fileSystem: fs\n                    ),\n                    lld\n                )\n\n                try XCTAssertEqual(\n                    UserToolchain.determineLibrarian(\n                        triple: triple, binDirectories: [bin], useXcrun: false, environment: [:], searchPaths: [],\n                        extraSwiftFlags: [\"-Xswiftc\", \"-use-ld=not-link\"],\n                        fileSystem: fs\n                    ),\n                    not\n                )\n\n                try XCTAssertThrowsError(\n                    UserToolchain.determineLibrarian(\n                        triple: triple, binDirectories: [bin], useXcrun: false, environment: [:], searchPaths: [],\n                        extraSwiftFlags: [],\n                        fileSystem: fs\n                    )\n                )\n            }\n        }\n    }\n\n    func testDetermineSwiftCompilers() throws {\n        let fs = localFileSystem\n            try withTemporaryDirectory(removeTreeOnDeinit: true) { tmp in\n                // When swiftc is not in the toolchain bin directory, UserToolchain\n                // should find it in the system PATH search paths in the order they\n                // are specified.\n                let toolchainPath = tmp.appending(\"swift.xctoolchain\")\n                let toolchainBinDir = toolchainPath.appending(components: \"usr\", \"bin\")\n                // Create the toolchain bin directory, but don't put swiftc in it.\n                try fs.createDirectory(toolchainBinDir, recursive: true)\n\n                // Create a directory with two swiftc binaries in it.\n                let binDirs = [\"bin1\", \"bin2\"].map { tmp.appending($0) }\n                #if os(Windows)\n                let exeSuffix = \".exe\"\n                #else\n                let exeSuffix = \"\"\n                #endif\n                let expectedExecuable = \"swiftc\\(exeSuffix)\" // Files that end with .exe are considered executable on Windows.\n                for binDir in binDirs {\n                    try fs.createDirectory(binDir)\n                    let binFile = binDir.appending(expectedExecuable)\n                    try fs.writeFileContents(binFile, bytes: ByteString(Self.tinyPEBytes))\n                    XCTAssertTrue(fs.exists(binFile), \"File '\\(binFile)' does not exist when it should\")\n                    #if !os(Windows)\n                    try fs.chmod(.executable, path: binFile, options: [])\n                    #endif\n                }\n\n                let compilers = try UserToolchain.determineSwiftCompilers(\n                    binDirectories: [toolchainBinDir],\n                    useXcrun: false,\n                    environment: [:],\n                    searchPaths: binDirs,\n                    fileSystem: fs\n                )\n\n                // The first swiftc in the search paths should be chosen.\n                XCTAssertEqual(compilers.compile, binDirs.first?.appending(expectedExecuable))\n            }\n    }\n\n    func testDetermineSwiftCompilersWarnsOnInvalidSWIFT_EXEC() throws {\n        let fs = localFileSystem\n        try withTemporaryDirectory(removeTreeOnDeinit: true) { tmp in\n            let toolchainPath = tmp.appending(\"swift.xctoolchain\")\n            let toolchainBinDir = toolchainPath.appending(components: \"usr\", \"bin\")\n            try fs.createDirectory(toolchainBinDir, recursive: true)\n\n            #if os(Windows)\n            let exeSuffix = \".exe\"\n            #else\n            let exeSuffix = \"\"\n            #endif\n\n            // Create a valid swiftc in the toolchain\n            let validSwiftc = toolchainBinDir.appending(\"swiftc\\(exeSuffix)\")\n            try fs.writeFileContents(validSwiftc, bytes: ByteString(Self.tinyPEBytes))\n            #if !os(Windows)\n            try fs.chmod(.executable, path: validSwiftc, options: [])\n            #endif\n\n            // Test 1: SWIFT_EXEC points to non-existent file\n            do {\n                let observability = ObservabilitySystem.makeForTesting()\n                let nonExistentPath = tmp.appending(components: \"nonexistent\", \"path\", \"to\", \"swiftc\")\n                let environment: Environment = [\"SWIFT_EXEC\": nonExistentPath.pathString]\n\n                _ = try UserToolchain.determineSwiftCompilers(\n                    binDirectories: [toolchainBinDir],\n                    useXcrun: false,\n                    environment: environment,\n                    searchPaths: [],\n                    fileSystem: fs,\n                    observabilityScope: observability.topScope\n                )\n\n                testDiagnostics(observability.diagnostics) { result in\n                    result.check(diagnostic: .contains(\"SWIFT_EXEC is set to '\\(nonExistentPath.pathString)' but the file does not exist; ignoring\"), severity: .warning)\n                }\n            }\n\n            // Test 2: SWIFT_EXEC points to file that exists but is not executable\n            do {\n                let observability = ObservabilitySystem.makeForTesting()\n                let notExecutablePath = tmp.appending(\"not-executable\")\n                try fs.writeFileContents(notExecutablePath, bytes: \"\")\n                #if !os(Windows)\n                try fs.chmod(.userUnWritable, path: notExecutablePath, options: [])\n                #endif\n\n                let environment: Environment = [\"SWIFT_EXEC\": notExecutablePath.pathString]\n\n                _ = try UserToolchain.determineSwiftCompilers(\n                    binDirectories: [toolchainBinDir],\n                    useXcrun: false,\n                    environment: environment,\n                    searchPaths: [],\n                    fileSystem: fs,\n                    observabilityScope: observability.topScope\n                )\n\n                testDiagnostics(observability.diagnostics) { result in\n                    result.check(diagnostic: .contains(\"SWIFT_EXEC is set to '\\(notExecutablePath.pathString)' which exists but is not executable; ignoring\"), severity: .warning)\n                }\n            }\n\n            // Test 3: SWIFT_EXEC is not an absolute path and not found in search paths\n            do {\n                let observability = ObservabilitySystem.makeForTesting()\n                let environment: Environment = [\"SWIFT_EXEC\": \"nonexistent-compiler\"]\n\n                _ = try UserToolchain.determineSwiftCompilers(\n                    binDirectories: [toolchainBinDir],\n                    useXcrun: false,\n                    environment: environment,\n                    searchPaths: [],\n                    fileSystem: fs,\n                    observabilityScope: observability.topScope\n                )\n\n                testDiagnostics(observability.diagnostics) { result in\n                    result.check(diagnostic: .contains(\"SWIFT_EXEC is set to 'nonexistent-compiler' but no executable was found in search paths; ignoring\"), severity: .warning)\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/SnippetTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@testable import PackageModel\nimport Testing\n\n@Suite(\n    .tags(\n        .TestSize.small,\n        .Feature.Snippets,\n    ),\n)\nstruct SnippetTests {\n    let fakeSourceFilePath = AbsolutePath(\"/fake/path/to/test.swift\")\n\n    /// Test the contents of the ``Snippet`` model when parsing an empty file.\n    /// Currently, no errors are emitted and most things are either nil or empty.\n    @Test\n    func testEmptySourceFile() async throws {\n        let source = \"\"\n        let snippet = Snippet(parsing: source, path: fakeSourceFilePath)\n        #expect(snippet.path == fakeSourceFilePath)\n        #expect(snippet.explanation.isEmpty)\n        #expect(snippet.presentationCode.isEmpty)\n        #expect(snippet.groupName == nil)\n        #expect(\"test\" == snippet.name)\n    }\n\n    /// Test the contents of the ``Snippet`` model when parsing a typical\n    /// source file.\n    @Test\n    func testBasic() async throws {\n        let explanation = \"This snippet does a foo. Try it when XYZ.\"\n        let presentationCode = \"\"\"\n        import Module\n\n        func foo(x: X) {}\n        \"\"\"\n\n        let source = \"\"\"\n\n        //! \\(explanation)\n\n        \\(presentationCode)\n\n        // MARK: HIDE\n\n        print(foo(x: x()))\n        \"\"\"\n\n        let snippet = Snippet(parsing: source, path: fakeSourceFilePath)\n\n        #expect(snippet.path == fakeSourceFilePath)\n        #expect(explanation == snippet.explanation)\n        #expect(presentationCode == snippet.presentationCode)\n        #expect(snippet.groupName == nil)\n        #expect(\"test\" == snippet.name)\n    }\n\n    /// Test that multiple consecutive newlines in a snippet's\n    /// presentation code is coalesced into no more than two newlines,\n    /// and test that newlines at the beginning and end of are stripped.\n    @Test\n    func testMultiNewlineCoalescing() async throws {\n        let explanation = \"This snippet does a foo. Try it when XYZ.\"\n        let presentationCode = \"\"\"\n\n\n        import Module\n\n\n\n\n        func foo(x: X) {}\n\n\n        \"\"\"\n\n        let source = \"\"\"\n\n        //!\n        //! \\(explanation)\n        //!\n\n        \\(presentationCode)\n\n        // MARK: HIDE\n\n        print(foo(x: x()))\n        \"\"\"\n\n        let expectedPresentationCode = \"\"\"\n        import Module\n\n        func foo(x: X) {}\n        \"\"\"\n\n        let snippet = Snippet(parsing: source, path: fakeSourceFilePath)\n        #expect(explanation == snippet.explanation)\n        #expect(expectedPresentationCode == snippet.presentationCode)\n    }\n\n    /// Test that toggling back and forth with `mark: hide` and `mark: show`\n    /// works as intended.\n    func testMarkHideShowToggle() async throws {\n        let source = \"\"\"\n        shown1\n\n        // mark: hide\n        hidden1\n\n        // mark: show\n        shown2\n\n        // mark: hide\n        hidden2\n\n        // mark: show\n        shown3\n        \"\"\"\n\n        let expectedPresentationCode = \"\"\"\n        shown1\n\n        shown2\n        \n        shown3\n        \"\"\"\n\n        let snippet = Snippet(parsing: source, path: fakeSourceFilePath)\n        #expect(!snippet.presentationCode.contains(\"hidden\"))\n        #expect(!snippet.explanation.contains(\"hidden\"))\n        #expect(expectedPresentationCode == snippet.presentationCode)\n    }\n\n    /// Tests that extra indentation is removed when extracting some inner\n    /// part of nested code.\n    @Test\n    func testRemoveExtraIndentation() async throws {\n        let source = \"\"\"\n        // mark: hide\n        struct Outer {\n          struct Inner {\n            // mark: show\n            struct InnerInner {\n            }\n            // mark: hide\n          }\n        }\n        \"\"\"\n\n        let expectedPresentationCode = \"\"\"\n        struct InnerInner {\n        }\n        \"\"\"\n        let snippet = Snippet(parsing: source, path: fakeSourceFilePath)\n        #expect(expectedPresentationCode == snippet.presentationCode)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/SwiftLanguageVersionTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\n\nimport PackageModel\n\nclass SwiftLanguageVersionTests: XCTestCase {\n\n    func testBasics() throws {\n\n        let validVersions = [\n            \"4\"     : \"4\",\n            \"4.0\"   : \"4.0\",\n            \"4.2\"   : \"4.2\",\n            \"1.0.0\" : \"1.0.0\",\n            \"3.1.0\" : \"3.1.0\",\n        ]\n\n        for (version, expected) in validVersions {\n            guard let swiftVersion = SwiftLanguageVersion(string: version) else {\n                return XCTFail(\"Couldn't form a version with string: \\(version)\")\n            }\n            XCTAssertEqual(swiftVersion.rawValue, expected)\n            XCTAssertEqual(swiftVersion.description, expected)\n        }\n\n        let invalidVersions = [\n            \"1.2.3.4\",\n            \"1.2-al..beta.0+bu.uni.ra\",\n            \"1.2.33-al..beta.0+bu.uni.ra\",\n            \".1.0.0-x.7.z.92\",\n            \"1.0.0-alpha.beta+\",\n            \"1.0.0beta\",\n            \"1.0.0-\",\n            \"1.-2.3\",\n            \"1.2.3d\",\n        ]\n\n        for version in invalidVersions {\n            if let swiftVersion = SwiftLanguageVersion(string: version) {\n                XCTFail(\"Formed an invalid version \\(swiftVersion) with string: \\(version)\")\n            }\n        }\n    }\n\n    func testComparison() {\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4.0.1\")! > SwiftLanguageVersion(string: \"4\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4.0\")! == SwiftLanguageVersion(string: \"4\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4.1\")! > SwiftLanguageVersion(string: \"4\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"5\")! >= SwiftLanguageVersion(string: \"4\")!)\n\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4.0.1\")! < ToolsVersion(string: \"4.1\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4\")! == ToolsVersion(string: \"4.0\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4.2\")! == ToolsVersion(string: \"4.2\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4.2\")! < ToolsVersion(string: \"4.3\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4.2\")! <= ToolsVersion(string: \"4.3\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4.2\")! <= ToolsVersion(string: \"5.0\")!)\n        XCTAssertTrue(SwiftLanguageVersion(string: \"4\")! < ToolsVersion(string: \"5.0\")!)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/SwiftSDKBundleTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\n@_spi(SwiftPMInternal)\n@testable import PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCBasic.ByteString\nimport protocol TSCBasic.FileSystem\nimport class Workspace.Workspace\n\nprivate let testArtifactID = \"test-artifact\"\n\nprivate let targetTriple = try! Triple(\"aarch64-unknown-linux\")\n\nprivate let jsonEncoder = JSONEncoder()\n\nprivate func generateBundleFiles(bundle: MockBundle) throws -> [(String, ByteString)] {\n    return try [\n        (\n            \"\\(bundle.path)/info.json\",\n            ByteString(json: \"\"\"\n            {\n                \"artifacts\" : {\n                    \\(bundle.artifacts.map {\n                            let path = if let metadataPath = $0.metadataPath {\n                                metadataPath.pathString\n                            } else {\n                                \"\\($0.id)/\\(targetTriple.triple)\"\n                            }\n\n                            return \"\"\"\n                            \"\\($0.id)\" : {\n                                \"type\" : \"swiftSDK\",\n                                \"version\" : \"0.0.1\",\n                                \"variants\" : [\n                                    {\n                                        \"path\" : \"\\(path)\",\n                                        \"supportedTriples\" : \\($0.supportedTriples.map(\\.tripleString))\n                                    }\n                                ]\n                            }\n                            \"\"\"\n                        }.joined(separator: \",\\n\")\n                    )\n                },\n                \"schemaVersion\" : \"1.0\"\n            }\n            \"\"\")\n        ),\n\n    ] + bundle.artifacts.map {\n        let path = if let metadataPath = $0.metadataPath {\n            \"\\(bundle.path)/\\(metadataPath.pathString)\"\n        } else {\n            \"\\(bundle.path)/\\($0.id)/\\(targetTriple.triple)/swift-sdk.json\"\n        }\n\n        return (\n            path,\n            ByteString(json: try generateSwiftSDKMetadata(jsonEncoder, createToolset: $0.toolsetRootPath != nil))\n        )\n    } + bundle.artifacts.compactMap { artifact in\n        let toolsetPath = if artifact.metadataPath != nil {\n            \"\\(bundle.path)/toolset.json\"\n        } else {\n            \"\\(bundle.path)/\\(artifact.id)/\\(targetTriple.triple)/toolset.json\"\n        }\n        return artifact.toolsetRootPath.map { path in\n            (\n                \"\\(toolsetPath)\",\n                ByteString(json: \"\"\"\n                {\n                    \"schemaVersion\": \"1.0\",\n                    \"rootPath\": \"\\(path)\"\n                }\n                \"\"\")\n            )\n        }\n    }\n}\n\nprivate func generateSwiftSDKMetadata(_ encoder: JSONEncoder, createToolset: Bool) throws -> SerializedJSON {\n    try \"\"\"\n    {\n        \"schemaVersion\": \"4.0\",\n        \"targetTriples\": \\(\n            String(\n                bytes: encoder.encode([\n                    targetTriple.tripleString: SwiftSDKMetadataV4.TripleProperties(sdkRootPath: \"sdk\", toolsetPaths: createToolset ? [\n                        \"toolset.json\"\n                    ] : nil)\n                ]),\n                encoding: .utf8\n            )!\n        )\n    }\n    \"\"\"\n}\n\nprivate struct MockBundle {\n    let name: String\n    let path: String\n    let artifacts: [MockArtifact]\n}\n\nprivate struct MockArtifact {\n    let id: String\n    let supportedTriples: [Triple]\n    var metadataPath: RelativePath?\n    var toolsetRootPath: AbsolutePath?\n}\n\nprivate func generateTestFileSystem(\n    bundleArtifacts: [MockArtifact]\n) throws -> (some FileSystem, [MockBundle], AbsolutePath) {\n    let bundles = bundleArtifacts.enumerated().map { (i, artifacts) in\n        let bundleName = \"test\\(i).\\(artifactBundleExtension)\"\n        return MockBundle(name: \"test\\(i).\\(artifactBundleExtension)\", path: \"/\\(bundleName)\", artifacts: [artifacts])\n    }\n\n    let fileSystem = try InMemoryFileSystem(\n        files: Dictionary(\n            uniqueKeysWithValues: bundles.flatMap {\n                try generateBundleFiles(bundle: $0)\n            }\n        )\n    )\n\n    let swiftSDKsDirectory = try AbsolutePath(validating: \"/sdks\")\n    try fileSystem.createDirectory(fileSystem.tempDirectory)\n    try fileSystem.createDirectory(swiftSDKsDirectory)\n\n    return (fileSystem, bundles, swiftSDKsDirectory)\n}\n\nprivate let arm64Triple = try! Triple(\"arm64-apple-macosx13.0\")\nprivate let i686Triple = try! Triple(\"i686-apple-macosx13.0\")\n\nprivate let fixtureSDKsPath = try! AbsolutePath(validating: #file)\n    .parentDirectory\n    .parentDirectory\n    .parentDirectory\n    .appending(components: [\"Fixtures\", \"SwiftSDKs\"])\n\nfinal class SwiftSDKBundleTests: XCTestCase {\n    func testInstallRemote() async throws {\n        #if canImport(Darwin) && !os(macOS)\n        try XCTSkipIf(true, \"skipping test because process launching is not available\")\n        #endif\n\n        let system = ObservabilitySystem.makeForTesting()\n        let observabilityScope = system.topScope\n        let cancellator = Cancellator(observabilityScope: observabilityScope)\n        let archiver = UniversalArchiver(localFileSystem, cancellator)\n\n        let fixtureAndURLs: [(url: String, fixture: String, checksum: String)] = [\n            (\"https://localhost/archive?test=foo\", \"test-sdk.artifactbundle.tar.gz\", \"724b5abf125287517dbc5be9add055d4755dfca679e163b249ea1045f5800c6e\"),\n            (\"https://localhost/archive.tar.gz\", \"test-sdk.artifactbundle.tar.gz\", \"724b5abf125287517dbc5be9add055d4755dfca679e163b249ea1045f5800c6e\"),\n            (\"https://localhost/archive.zip\", \"test-sdk.artifactbundle.zip\", \"74f6df5aa91c582c12e3a6670ff95973e463dd3266aabbc52ad13c3cd27e2793\"),\n        ]\n\n        for (bundleURLString, fixture, checksum) in fixtureAndURLs {\n            let httpClient = HTTPClient { request, _ in\n                guard case let .download(_, downloadPath) = request.kind else {\n                    XCTFail(\"Unexpected HTTPClient.Request.Kind\")\n                    return .init(statusCode: 400)\n                }\n                let fixturePath = fixtureSDKsPath.appending(component: fixture)\n                try localFileSystem.copy(from: fixturePath, to: downloadPath)\n                return .init(statusCode: 200)\n            }\n\n            try await withTemporaryDirectory(fileSystem: localFileSystem, removeTreeOnDeinit: true) { tmpDir in\n                var output = [SwiftSDKBundleStore.Output]()\n                let store = SwiftSDKBundleStore(\n                    swiftSDKsDirectory: tmpDir,\n                    hostToolchainBinDir: tmpDir,\n                    fileSystem: localFileSystem,\n                    observabilityScope: observabilityScope,\n                    outputHandler: {\n                        output.append($0)\n                    }\n                )\n                try await store.install(bundlePathOrURL: bundleURLString, checksum: checksum, archiver, httpClient) {\n                    try Workspace.BinaryArtifactsManager.checksum(forBinaryArtifactAt: $0, fileSystem: localFileSystem)\n                }\n\n                let bundleURL = URL(string: bundleURLString)!\n                XCTAssertEqual(output, [\n                    .downloadStarted(bundleURL),\n                    .downloadFinishedSuccessfully(bundleURL),\n                    .verifyingChecksum,\n                    .checksumValid,\n                    .unpackingArchive(bundlePathOrURL: bundleURLString),\n                    .installationSuccessful(\n                        bundlePathOrURL: bundleURLString,\n                        bundleName: \"test-sdk.artifactbundle\"\n                    ),\n                ])\n            }.value\n        }\n    }\n\n    func testInstall() async throws {\n        let system = ObservabilitySystem.makeForTesting()\n\n        let (fileSystem, bundles, swiftSDKsDirectory) = try generateTestFileSystem(\n            bundleArtifacts: [\n                .init(id: testArtifactID, supportedTriples: [arm64Triple]),\n                .init(id: testArtifactID, supportedTriples: [arm64Triple])\n            ]\n        )\n\n        let archiver = MockArchiver()\n\n        var output = [SwiftSDKBundleStore.Output]()\n        let store = SwiftSDKBundleStore(\n            swiftSDKsDirectory: swiftSDKsDirectory,\n            hostToolchainBinDir: \"/tmp\",\n            fileSystem: fileSystem,\n            observabilityScope: system.topScope,\n            outputHandler: {\n                output.append($0)\n            }\n        )\n\n        // Expected to be successful:\n        try await store.install(bundlePathOrURL: bundles[0].path, archiver)\n\n        // Expected to fail:\n        let invalidPath = \"foobar\"\n        do {\n            try await store.install(bundlePathOrURL: invalidPath, archiver)\n\n            XCTFail(\"Function expected to throw\")\n        } catch {\n            guard let error = error as? SwiftSDKError else {\n                XCTFail(\"Unexpected error type\")\n                return\n            }\n\n            switch error {\n            case let .invalidBundleArchive(archivePath):\n                XCTAssertEqual(archivePath, AbsolutePath.root.appending(invalidPath))\n            default:\n                XCTFail(\"Unexpected error value\")\n            }\n        }\n\n        do {\n            try await store.install(bundlePathOrURL: bundles[0].path, archiver)\n\n            XCTFail(\"Function expected to throw\")\n        } catch {\n            guard let error = error as? SwiftSDKError else {\n                XCTFail(\"Unexpected error type\")\n                return\n            }\n\n            switch error {\n            case let .swiftSDKArtifactAlreadyInstalled(installedBundleName, newBundleName, artifactID):\n                XCTAssertEqual(bundles[0].name, installedBundleName)\n                XCTAssertEqual(newBundleName, \"test0.\\(artifactBundleExtension)\")\n                XCTAssertEqual(artifactID, testArtifactID)\n            default:\n                XCTFail(\"Unexpected error value\")\n            }\n        }\n\n        do {\n            try await store.install(bundlePathOrURL: bundles[1].path, archiver)\n\n             XCTFail(\"Function expected to throw\")\n         } catch {\n            guard let error = error as? SwiftSDKError else {\n                XCTFail(\"Unexpected error type\")\n                return\n            }\n\n            switch error {\n            case .swiftSDKArtifactAlreadyInstalled(let installedBundleName, let newBundleName, let artifactID):\n                XCTAssertEqual(bundles[0].name, installedBundleName)\n                XCTAssertEqual(bundles[1].name, newBundleName)\n                XCTAssertEqual(artifactID, testArtifactID)\n            default:\n                XCTFail(\"Unexpected error value\")\n            }\n        }\n\n        XCTAssertEqual(output, [\n            .installationSuccessful(\n                bundlePathOrURL: bundles[0].path,\n                bundleName: AbsolutePath(bundles[0].path).components.last!\n            ),\n            .unpackingArchive(bundlePathOrURL: invalidPath),\n        ])\n    }\n\n    func testList() async throws {\n        let (fileSystem, bundles, swiftSDKsDirectory) = try generateTestFileSystem(\n            bundleArtifacts: [\n                .init(id: \"\\(testArtifactID)2\", supportedTriples: [i686Triple]),\n                .init(id: \"\\(testArtifactID)1\", supportedTriples: [arm64Triple]),\n            ]\n        )\n        let system = ObservabilitySystem.makeForTesting()\n        let archiver = MockArchiver()\n\n        var output = [SwiftSDKBundleStore.Output]()\n        let store = SwiftSDKBundleStore(\n            swiftSDKsDirectory: swiftSDKsDirectory,\n            hostToolchainBinDir: \"/tmp\",\n            fileSystem: fileSystem,\n            observabilityScope: system.topScope,\n            outputHandler: {\n                output.append($0)\n            }\n        )\n\n        for bundle in bundles {\n            try await store.install(bundlePathOrURL: bundle.path, archiver)\n        }\n\n        let validBundles = try store.allValidBundles\n\n        XCTAssertEqual(validBundles.count, bundles.count)\n\n        XCTAssertEqual(validBundles.sortedArtifactIDs, [\"\\(testArtifactID)1\", \"\\(testArtifactID)2\"])\n        XCTAssertEqual(output, [\n            .installationSuccessful(\n                bundlePathOrURL: bundles[0].path,\n                bundleName: AbsolutePath(bundles[0].path).components.last!\n            ),\n            .installationSuccessful(\n                bundlePathOrURL: bundles[1].path,\n                bundleName: AbsolutePath(bundles[1].path).components.last!\n            ),\n        ])\n    }\n\n    func testBundleSelection() async throws {\n        let (fileSystem, bundles, swiftSDKsDirectory) = try generateTestFileSystem(\n            bundleArtifacts: [\n                .init(id: \"\\(testArtifactID)1\", supportedTriples: [arm64Triple]),\n                .init(id: \"\\(testArtifactID)2\", supportedTriples: [i686Triple])\n            ]\n        )\n        let system = ObservabilitySystem.makeForTesting()\n\n        var output = [SwiftSDKBundleStore.Output]()\n        let store = SwiftSDKBundleStore(\n            swiftSDKsDirectory: swiftSDKsDirectory,\n            hostToolchainBinDir: \"/tmp\",\n            fileSystem: fileSystem,\n            observabilityScope: system.topScope,\n            outputHandler: {\n                output.append($0)\n            }\n        )\n\n        let archiver = MockArchiver()\n        for bundle in bundles {\n            try await store.install(bundlePathOrURL: bundle.path, archiver)\n        }\n\n        let sdk = try store.selectBundle(\n            matching: \"\\(testArtifactID)1\",\n            hostTriple: Triple(\"arm64-apple-macosx14.0\")\n        )\n\n        XCTAssertEqual(sdk.targetTriple, targetTriple)\n        XCTAssertEqual(output, [\n            .installationSuccessful(\n                bundlePathOrURL: bundles[0].path,\n                bundleName: AbsolutePath(bundles[0].path).components.last!\n            ),\n            .installationSuccessful(\n                bundlePathOrURL: bundles[1].path,\n                bundleName: AbsolutePath(bundles[1].path).components.last!\n            ),\n        ])\n    }\n\n    func testTargetSDKDerivation() async throws {\n        let toolsetRootPath = AbsolutePath(\"/path/to/toolpath\")\n        let (fileSystem, bundles, swiftSDKsDirectory) = try generateTestFileSystem(\n            bundleArtifacts: [\n                .init(id: \"\\(testArtifactID)1\", supportedTriples: [arm64Triple]),\n                .init(id: \"\\(testArtifactID)2\", supportedTriples: [arm64Triple], toolsetRootPath: toolsetRootPath),\n            ]\n        )\n        let system = ObservabilitySystem.makeForTesting()\n        let hostSwiftSDK = try SwiftSDK.hostSwiftSDK(environment: [:])\n        let hostTriple = try! Triple(\"arm64-apple-macosx14.0\")\n        let hostToolchainBinDir = AbsolutePath(\"/tmp\")\n        let archiver = MockArchiver()\n        let store = SwiftSDKBundleStore(\n            swiftSDKsDirectory: swiftSDKsDirectory,\n            hostToolchainBinDir: hostToolchainBinDir,\n            fileSystem: fileSystem,\n            observabilityScope: system.topScope,\n            outputHandler: { _ in }\n        )\n        \n        for bundle in bundles {\n            try await store.install(bundlePathOrURL: bundle.path, archiver)\n        }\n\n        do {\n            let targetSwiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostTriple,\n                store: store,\n                observabilityScope: system.topScope,\n                fileSystem: fileSystem\n            )\n            // By default, the target SDK is the same as the host SDK.\n            XCTAssertEqual(targetSwiftSDK, hostSwiftSDK)\n        }\n\n        do {\n            let targetSwiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostTriple,\n                customCompileTriple: .arm64Linux,\n                store: store,\n                observabilityScope: system.topScope,\n                fileSystem: fileSystem\n            )\n\n            // With a custom target triple, toolset extra CLI options should be empty\n            XCTAssertEqual(targetSwiftSDK.toolset.rootPaths, hostSwiftSDK.toolset.rootPaths)\n            for tool in targetSwiftSDK.toolset.knownTools.values {\n                XCTAssertEqual(tool.extraCLIOptions, [])\n            }\n        }\n\n        do {\n            let targetSwiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostTriple,\n                swiftSDKSelector: \"\\(testArtifactID)1\",\n                store: store,\n                observabilityScope: system.topScope,\n                fileSystem: fileSystem\n            )\n            // With a target SDK selector, SDK should be chosen from the store.\n            XCTAssertEqual(targetSwiftSDK.targetTriple, targetTriple)\n            // No toolset in the SDK, so it should be the same as the host SDK.\n            XCTAssertEqual(targetSwiftSDK.toolset.rootPaths, hostSwiftSDK.toolset.rootPaths)\n        }\n\n        do {\n            let targetSwiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostTriple,\n                swiftSDKSelector: \"\\(testArtifactID)2\",\n                store: store,\n                observabilityScope: system.topScope,\n                fileSystem: fileSystem\n            )\n            // With toolset in the target SDK, it should contain the host toolset roots at the end.\n            XCTAssertEqual(targetSwiftSDK.toolset.rootPaths, [toolsetRootPath] + hostSwiftSDK.toolset.rootPaths)\n        }\n\n        do {\n            // Check explicit overriding options.\n            let customCompileSDK = AbsolutePath(\"/path/to/sdk\")\n            let archs = [\"x86_64-apple-macosx10.15\"]\n            let customCompileToolchain = AbsolutePath(\"/path/to/toolchain\")\n            try fileSystem.createDirectory(customCompileToolchain, recursive: true)\n\n            let targetSwiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostTriple,\n                customCompileToolchain: customCompileToolchain,\n                customCompileSDK: customCompileSDK,\n                architectures: archs,\n                store: store,\n                observabilityScope: system.topScope,\n                fileSystem: fileSystem\n            )\n            XCTAssertEqual(targetSwiftSDK.architectures, archs)\n            XCTAssertEqual(targetSwiftSDK.pathsConfiguration.sdkRootPath, customCompileSDK)\n            XCTAssertEqual(\n                targetSwiftSDK.toolset.rootPaths,\n                [customCompileToolchain.appending(components: [\"usr\", \"bin\"])] + hostSwiftSDK.toolset.rootPaths\n            )\n        }\n    }\n\n    func testMetadataJSONPaths() async throws {\n        let toolsetRootPath = AbsolutePath(\"/path/to/toolpath\")\n        let (fileSystem, bundles, swiftSDKsDirectory) = try generateTestFileSystem(\n            bundleArtifacts: [\n                .init(\n                    id: \"\\(testArtifactID)1\",\n                    supportedTriples: [arm64Triple],\n                    metadataPath: \"metadata1.json\"\n                ),\n                .init(\n                    id: \"\\(testArtifactID)2\",\n                    supportedTriples: [i686Triple],\n                    metadataPath: \"metadata2.json\",\n                    toolsetRootPath: toolsetRootPath\n                ),\n            ]\n        )\n        let system = ObservabilitySystem.makeForTesting()\n        let archiver = MockArchiver()\n        \n        var output = [SwiftSDKBundleStore.Output]()\n        let store = SwiftSDKBundleStore(\n            swiftSDKsDirectory: swiftSDKsDirectory,\n            hostToolchainBinDir: \"/tmp\",\n            fileSystem: fileSystem,\n            observabilityScope: system.topScope,\n            outputHandler: { output.append($0) }\n        )\n\n        for bundle in bundles {\n            try await store.install(bundlePathOrURL: bundle.path, archiver)\n        }\n\n        let validBundles = try store.allValidBundles\n\n        XCTAssertEqual(validBundles.count, bundles.count)\n\n        XCTAssertEqual(validBundles.sortedArtifactIDs, [\"\\(testArtifactID)1\", \"\\(testArtifactID)2\"])\n        XCTAssertEqual(output.count, 2)\n        XCTAssertEqual(output, [\n            .installationSuccessful(\n                bundlePathOrURL: bundles[0].path,\n                bundleName: AbsolutePath(bundles[0].path).components.last!\n            ),\n            .installationSuccessful(\n                bundlePathOrURL: bundles[1].path,\n                bundleName: AbsolutePath(bundles[1].path).components.last!\n            ),\n        ])\n    }\n\n    func testConfigureSDKRootPath() async throws {\n        func createConfigurationStore() async throws -> (SwiftSDKConfigurationStore, FileSystem) {\n            let (fileSystem, bundles, swiftSDKsDirectory) = try generateTestFileSystem(\n                bundleArtifacts: [\n                    .init(id: testArtifactID, supportedTriples: [arm64Triple, i686Triple]),\n                ]\n            )\n            let system = ObservabilitySystem.makeForTesting()\n\n            var output = [SwiftSDKBundleStore.Output]()\n            let store = SwiftSDKBundleStore(\n                swiftSDKsDirectory: swiftSDKsDirectory,\n                hostToolchainBinDir: \"/tmp\",\n                fileSystem: fileSystem,\n                observabilityScope: system.topScope,\n                outputHandler: {\n                    output.append($0)\n                }\n            )\n\n            let archiver = MockArchiver()\n            for bundle in bundles {\n                try await store.install(bundlePathOrURL: bundle.path, archiver)\n            }\n\n            let hostTriple = try Triple(\"arm64-apple-macosx14.0\")\n            let sdk = try store.selectBundle(\n                matching: testArtifactID,\n                hostTriple: hostTriple\n            )\n\n            XCTAssertEqual(sdk.targetTriple, targetTriple)\n            XCTAssertEqual(output, [\n                .installationSuccessful(\n                    bundlePathOrURL: bundles[0].path,\n                    bundleName: AbsolutePath(bundles[0].path).components.last!\n                )\n            ])\n\n            let config = try SwiftSDKConfigurationStore(\n                hostTimeTriple: hostTriple,\n                swiftSDKBundleStore: store\n            )\n\n            return (config, fileSystem)\n        }\n\n        do {\n            let (config, _) = try await createConfigurationStore()\n            let args = SwiftSDK.PathsConfiguration<String>()\n            let configSuccess = try config.configure(\n                sdkID: testArtifactID,\n                targetTriple: nil,\n                showConfiguration: false,\n                resetConfiguration: false,\n                config: args\n            )\n            XCTAssertEqual(configSuccess, false, \"Expected failure for SwiftSDKConfigurationStore.configure with no updated properties\")\n        }\n\n        let targetTripleConfigPath = AbsolutePath(\"/sdks/configuration/\\(testArtifactID)_\\(targetTriple.tripleString).json\")\n\n        #if os(Windows)\n        let sdkRootPath = \"C:\\\\some\\\\sdk\\\\root\\\\path\"\n        #else\n        let sdkRootPath = \"/some/sdk/root/path\"\n        #endif\n\n        do {\n            let (config, fileSystem) = try await createConfigurationStore()\n            var args = SwiftSDK.PathsConfiguration<String>()\n            args.sdkRootPath = sdkRootPath\n            let configSuccess = try config.configure(\n                sdkID: testArtifactID,\n                targetTriple: targetTriple.tripleString,\n                showConfiguration: false,\n                resetConfiguration: false,\n                config: args\n            )\n            XCTAssertTrue(configSuccess)\n            XCTAssertTrue(fileSystem.isFile(targetTripleConfigPath))\n\n            let updatedConfig = try config.readConfiguration(\n                sdkID: testArtifactID,\n                targetTriple: targetTriple\n            )\n            XCTAssertEqual(args.sdkRootPath, updatedConfig?.pathsConfiguration.sdkRootPath?.pathString)\n        }\n\n        do {\n            let (config, fileSystem) = try await createConfigurationStore()\n            var args = SwiftSDK.PathsConfiguration<String>()\n            args.sdkRootPath = sdkRootPath\n            // an empty targetTriple will configure all triples\n            let configSuccess = try config.configure(\n                sdkID: testArtifactID,\n                targetTriple: nil,\n                showConfiguration: false,\n                resetConfiguration: false,\n                config: args\n            )\n            XCTAssertTrue(configSuccess)\n            XCTAssertTrue(fileSystem.isFile(targetTripleConfigPath))\n\n            let resetSuccess = try config.configure(\n                sdkID: testArtifactID,\n                targetTriple: nil,\n                showConfiguration: false,\n                resetConfiguration: true,\n                config: args\n            )\n            XCTAssertTrue(resetSuccess, \"Reset configuration should succeed\")\n            XCTAssertFalse(fileSystem.isFile(targetTripleConfigPath), \"Reset configuration should clear configuration folder\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/SwiftSDKTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\n\n@_spi(SwiftPMInternal)\n@testable import PackageModel\n\n@testable import SPMBuildCore\nimport XCTest\n\nprivate let bundleRootPath = try! AbsolutePath(validating: \"/tmp/cross-toolchain\")\nprivate let toolchainBinDir = RelativePath(\"swift.xctoolchain/usr/bin\")\nprivate let sdkRootDir = RelativePath(\"ubuntu-jammy.sdk\")\nprivate let hostTriple = try! Triple(\"arm64-apple-darwin22.1.0\")\nprivate let olderHostTriple = try! Triple(\"arm64-apple-darwin20.1.0\")\nprivate let linuxGNUTargetTriple = try! Triple(\"x86_64-unknown-linux-gnu\")\nprivate let linuxMuslTargetTriple = try! Triple(\"x86_64-unknown-linux-musl\")\nprivate let androidTargetTriple = try! Triple(\"aarch64-unknown-linux-android28\")\nprivate let wasiTargetTriple = try! Triple(\"wasm32-unknown-wasi\")\nprivate let extraFlags = BuildFlags(\n    cCompilerFlags: [\"-fintegrated-as\"].constructBuildFlags(source: .swiftSDK),\n    cxxCompilerFlags: [\"-fno-exceptions\"].constructBuildFlags(source: .swiftSDK),\n    swiftCompilerFlags: [\"-enable-experimental-cxx-interop\", \"-use-ld=lld\"].constructBuildFlags(source: .swiftSDK),\n    linkerFlags: [\"-R/usr/lib/swift/linux/\"].constructBuildFlags(source: .swiftSDK)\n)\n\nprivate let destinationV1 = (\n    path: bundleRootPath.appending(component: \"destinationV1.json\"),\n    json: #\"\"\"\n    {\n        \"version\": 1,\n        \"sdk\": \"\\#(bundleRootPath.appending(sdkRootDir))\",\n        \"toolchain-bin-dir\": \"\\#(bundleRootPath.appending(toolchainBinDir))\",\n        \"target\": \"\\#(linuxGNUTargetTriple.tripleString)\",\n        \"extra-cc-flags\": \\#(extraFlags.cCompilerFlags.rawFlags),\n        \"extra-swiftc-flags\": \\#(extraFlags.swiftCompilerFlags.rawFlags),\n        \"extra-cpp-flags\": \\#(extraFlags.cxxCompilerFlags.rawFlags)\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let destinationV2 = (\n    path: bundleRootPath.appending(component: \"destinationV2.json\"),\n    json: #\"\"\"\n    {\n        \"version\": 2,\n        \"sdkRootDir\": \"\\#(sdkRootDir)\",\n        \"toolchainBinDir\": \"\\#(toolchainBinDir)\",\n        \"hostTriples\": [\"\\#(hostTriple.tripleString)\"],\n        \"targetTriples\": [\"\\#(linuxGNUTargetTriple.tripleString)\"],\n        \"extraCCFlags\": \\#(extraFlags.cCompilerFlags.rawFlags),\n        \"extraSwiftCFlags\": \\#(extraFlags.swiftCompilerFlags.rawFlags),\n        \"extraCXXFlags\": \\#(extraFlags.cxxCompilerFlags.rawFlags),\n        \"extraLinkerFlags\": \\#(extraFlags.linkerFlags.rawFlags)\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let toolsetNoRootDestinationV3 = (\n    path: bundleRootPath.appending(component: \"toolsetNoRootDestinationV3.json\"),\n    json: #\"\"\"\n    {\n        \"runTimeTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/otherToolsNoRoot.json\"]\n            }\n        },\n        \"schemaVersion\": \"3.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let toolsetRootDestinationV3 = (\n    path: bundleRootPath.appending(component: \"toolsetRootDestinationV3.json\"),\n    json: #\"\"\"\n    {\n        \"runTimeTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/someToolsWithRoot.json\", \"/tools/otherToolsNoRoot.json\"]\n            }\n        },\n        \"schemaVersion\": \"3.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let missingToolsetDestinationV3 = (\n    path: bundleRootPath.appending(component: \"missingToolsetDestinationV3.json\"),\n    json: #\"\"\"\n    {\n        \"runTimeTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/asdf.json\"]\n            }\n        },\n        \"schemaVersion\": \"3.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let invalidVersionDestinationV3 = (\n    path: bundleRootPath.appending(component: \"invalidVersionDestinationV3.json\"),\n    json: #\"\"\"\n    {\n        \"runTimeTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/someToolsWithRoot.json\"]\n            }\n        },\n        \"schemaVersion\": \"2.9\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let invalidToolsetDestinationV3 = (\n    path: bundleRootPath.appending(component: \"invalidToolsetDestinationV3.json\"),\n    json: #\"\"\"\n    {\n        \"runTimeTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/invalidToolset.json\"]\n            }\n        },\n        \"schemaVersion\": \"3.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\n\nprivate let wasiWithoutToolsetsSwiftSDKv4 = (\n    path: bundleRootPath.appending(component: \"wasiSwiftSDKv4.json\"),\n    json: #\"\"\"\n    {\n        \"targetTriples\": {\n            \"\\#(wasiTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": []\n            }\n        },\n        \"schemaVersion\": \"4.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let toolsetNoRootSwiftSDKv4 = (\n    path: bundleRootPath.appending(component: \"toolsetNoRootSwiftSDKv4.json\"),\n    json: #\"\"\"\n    {\n        \"targetTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/otherToolsNoRoot.json\"]\n            }\n        },\n        \"schemaVersion\": \"4.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let toolsetRootSwiftSDKv4 = (\n    path: bundleRootPath.appending(component: \"toolsetRootSwiftSDKv4.json\"),\n    json: #\"\"\"\n    {\n        \"targetTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/someToolsWithRoot.json\", \"/tools/otherToolsNoRoot.json\"]\n            }\n        },\n        \"schemaVersion\": \"4.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let androidWithoutSDKRootPathSwiftSDKv4 = (\n    path: bundleRootPath.appending(component: \"androidWithoutSDKRootPathSwiftSDKv4.json\"),\n    json: #\"\"\"\n    {\n        \"targetTriples\": {\n            \"\\#(androidTargetTriple.tripleString)\": {\n                \"toolsetPaths\": [\"/tools/otherToolsNoRoot.json\"]\n            }\n        },\n        \"schemaVersion\": \"4.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let missingToolsetSwiftSDKv4 = (\n    path: bundleRootPath.appending(component: \"missingToolsetSwiftSDKv4.json\"),\n    json: #\"\"\"\n    {\n        \"targetTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/asdf.json\"]\n            }\n        },\n        \"schemaVersion\": \"4.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let invalidVersionSwiftSDKv4 = (\n    path: bundleRootPath.appending(component: \"invalidVersionSwiftSDKv4.json\"),\n    json: #\"\"\"\n    {\n        \"targetTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/someToolsWithRoot.json\"]\n            }\n        },\n        \"schemaVersion\": \"42.9\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let invalidToolsetSwiftSDKv4 = (\n    path: bundleRootPath.appending(component: \"invalidToolsetSwiftSDKv4.json\"),\n    json: #\"\"\"\n    {\n        \"targetTriples\": {\n            \"\\#(linuxGNUTargetTriple.tripleString)\": {\n                \"sdkRootPath\": \"\\#(sdkRootDir)\",\n                \"toolsetPaths\": [\"/tools/invalidToolset.json\"]\n            }\n        },\n        \"schemaVersion\": \"4.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let usrBinTools = Dictionary(uniqueKeysWithValues: Toolset.KnownTool.allCases.map {\n    ($0, \"/usr/bin/\\($0.rawValue)\")\n})\n\nprivate let otherToolsNoRoot = (\n    path: try! AbsolutePath(validating: \"/tools/otherToolsNoRoot.json\"),\n    json: #\"\"\"\n    {\n        \"schemaVersion\": \"1.0\",\n        \"librarian\": { \"path\": \"\\#(usrBinTools[.librarian]!)\" },\n        \"linker\": { \"path\": \"\\#(usrBinTools[.linker]!)\" },\n        \"debugger\": { \"path\": \"\\#(usrBinTools[.debugger]!)\" }\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let cCompilerOptions = [\"-fopenmp\"]\n\nprivate let someToolsWithRoot = (\n    path: try! AbsolutePath(validating: \"/tools/someToolsWithRoot.json\"),\n    json: #\"\"\"\n    {\n        \"schemaVersion\": \"1.0\",\n        \"rootPath\": \"/custom\",\n        \"cCompiler\": { \"extraCLIOptions\": \\#(cCompilerOptions) },\n        \"linker\": { \"path\": \"ld\" },\n        \"librarian\": { \"path\": \"llvm-ar\" },\n        \"debugger\": { \"path\": \"\\#(usrBinTools[.debugger]!)\" }\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let invalidToolset = (\n    path: try! AbsolutePath(validating: \"/tools/invalidToolset.json\"),\n    json: #\"\"\"\n    {\n      \"rootPath\" : \"swift.xctoolchain\\/usr\\/bin\",\n      \"tools\" : [\n        \"linker\",\n        {\n          \"path\" : \"ld.lld\"\n        },\n        \"swiftCompiler\",\n        {\n          \"extraCLIOptions\" : [\n            \"-use-ld=lld\",\n            \"-Xlinker\",\n            \"-R\\/usr\\/lib\\/swift\\/linux\\/\"\n          ]\n        },\n        \"cxxCompiler\",\n        {\n          \"extraCLIOptions\" : [\n            \"-lstdc++\"\n          ]\n        }\n      ],\n      \"schemaVersion\" : \"1.0\"\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let sdkRootAbsolutePath = bundleRootPath.appending(sdkRootDir)\nprivate let toolchainBinAbsolutePath = bundleRootPath.appending(toolchainBinDir)\n\nprivate let parsedDestinationV2GNU = SwiftSDK(\n    hostTriple: hostTriple,\n    targetTriple: linuxGNUTargetTriple,\n    toolset: .init(toolchainBinDir: toolchainBinAbsolutePath, buildFlags: extraFlags),\n    pathsConfiguration: .init(sdkRootPath: sdkRootAbsolutePath)\n)\n\nprivate let parsedDestinationV2Musl = SwiftSDK(\n    hostTriple: hostTriple,\n    targetTriple: linuxMuslTargetTriple,\n    toolset: .init(toolchainBinDir: toolchainBinAbsolutePath, buildFlags: extraFlags),\n    pathsConfiguration: .init(sdkRootPath: sdkRootAbsolutePath)\n)\n\nprivate let parsedDestinationForOlderHost = SwiftSDK(\n    targetTriple: linuxMuslTargetTriple,\n    toolset: .init(toolchainBinDir: toolchainBinAbsolutePath, buildFlags: extraFlags),\n    pathsConfiguration: .init(sdkRootPath: sdkRootAbsolutePath)\n)\n\nprivate let parsedToolsetNoRootDestination = SwiftSDK(\n    targetTriple: linuxGNUTargetTriple,\n    toolset: .init(\n        knownTools: [\n            .librarian: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.librarian]!)\")),\n            .linker: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.linker]!)\")),\n            .debugger: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.debugger]!)\")),\n        ],\n        rootPaths: []\n    ),\n    swiftSDKManifest: toolsetNoRootSwiftSDKv4.path,\n    pathsConfiguration: .init(\n        sdkRootPath: bundleRootPath.appending(sdkRootDir),\n        toolsetPaths: [\"/tools/otherToolsNoRoot.json\"]\n            .map { try! AbsolutePath(validating: $0) }\n    )\n)\n\nprivate let parsedToolsetRootDestination = SwiftSDK(\n    targetTriple: linuxGNUTargetTriple,\n    toolset: .init(\n        knownTools: [\n            .cCompiler: .init(extraCLIOptions: cCompilerOptions),\n            .librarian: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.librarian]!)\")),\n            .linker: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.linker]!)\")),\n            .debugger: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.debugger]!)\")),\n        ],\n        rootPaths: [try! AbsolutePath(validating: \"/custom\")]\n    ),\n    swiftSDKManifest: toolsetRootSwiftSDKv4.path,\n    pathsConfiguration: .init(\n        sdkRootPath: bundleRootPath.appending(sdkRootDir),\n        toolsetPaths: [\"/tools/someToolsWithRoot.json\", \"/tools/otherToolsNoRoot.json\"]\n            .map { try! AbsolutePath(validating: $0) }\n    )\n)\n\nprivate let parsedToolsetNoSDKRootPathDestination = SwiftSDK(\n    targetTriple: androidTargetTriple,\n    toolset: .init(\n        knownTools: [\n            .librarian: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.librarian]!)\")),\n            .linker: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.linker]!)\")),\n            .debugger: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.debugger]!)\")),\n        ],\n        rootPaths: []\n    ),\n    swiftSDKManifest: androidWithoutSDKRootPathSwiftSDKv4.path,\n    pathsConfiguration: .init(\n        sdkRootPath: nil,\n        toolsetPaths: [\"/tools/otherToolsNoRoot.json\"]\n            .map { try! AbsolutePath(validating: $0) }\n    )\n)\n\nprivate let testFiles: [(path: AbsolutePath, json: SerializedJSON)] = [\n    destinationV1,\n    destinationV2,\n    toolsetNoRootDestinationV3,\n    toolsetRootDestinationV3,\n    missingToolsetDestinationV3,\n    invalidVersionDestinationV3,\n    invalidToolsetDestinationV3,\n    toolsetNoRootSwiftSDKv4,\n    toolsetRootSwiftSDKv4,\n    missingToolsetSwiftSDKv4,\n    invalidVersionSwiftSDKv4,\n    invalidToolsetSwiftSDKv4,\n    wasiWithoutToolsetsSwiftSDKv4,\n    androidWithoutSDKRootPathSwiftSDKv4,\n    otherToolsNoRoot,\n    someToolsWithRoot,\n    invalidToolset,\n]\n\nfinal class SwiftSDKTests: XCTestCase {\n    func testDestinationCodable() throws {\n        let fs = InMemoryFileSystem()\n        try fs.createDirectory(AbsolutePath(validating: \"/tools\"))\n        try fs.createDirectory(AbsolutePath(validating: \"/tmp\"))\n        try fs.createDirectory(AbsolutePath(validating: \"\\(bundleRootPath)\"))\n        for testFile in testFiles {\n            try fs.writeFileContents(testFile.path, string: testFile.json.underlying)\n        }\n\n        let system = ObservabilitySystem.makeForTesting()\n        let observability = system.topScope\n\n        let destinationV1Decoded = try SwiftSDK.decode(\n            fromFile: destinationV1.path,\n            hostToolchainBinDir: bundleRootPath.appending(toolchainBinDir),\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        var flagsWithoutLinkerFlags = extraFlags\n        flagsWithoutLinkerFlags.linkerFlags = []\n\n        XCTAssertEqual(\n            destinationV1Decoded,\n            [\n                SwiftSDK(\n                    targetTriple: linuxGNUTargetTriple,\n                    toolset: .init(toolchainBinDir: toolchainBinAbsolutePath, buildFlags: flagsWithoutLinkerFlags),\n                    pathsConfiguration: .init(\n                        sdkRootPath: sdkRootAbsolutePath\n                    )\n                ),\n            ]\n        )\n\n        let destinationV2Decoded = try SwiftSDK.decode(\n            fromFile: destinationV2.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        XCTAssertEqual(destinationV2Decoded, [parsedDestinationV2GNU])\n\n        let toolsetNoRootDestinationV3Decoded = try SwiftSDK.decode(\n            fromFile: toolsetNoRootDestinationV3.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        let parsedToolsetNoRootDestinationV3 = SwiftSDK(\n            targetTriple: linuxGNUTargetTriple,\n            toolset: .init(\n                knownTools: [\n                    .librarian: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.librarian]!)\")),\n                    .linker: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.linker]!)\")),\n                    .debugger: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.debugger]!)\")),\n                ],\n                rootPaths: []\n            ),\n            swiftSDKManifest: toolsetNoRootDestinationV3.path,\n            pathsConfiguration: .init(\n                sdkRootPath: bundleRootPath.appending(sdkRootDir),\n                toolsetPaths: [\"/tools/otherToolsNoRoot.json\"]\n                    .map { try! AbsolutePath(validating: $0) }\n            )\n        )\n        XCTAssertEqual(toolsetNoRootDestinationV3Decoded, [parsedToolsetNoRootDestinationV3])\n\n        let toolsetRootDestinationV3Decoded = try SwiftSDK.decode(\n            fromFile: toolsetRootDestinationV3.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        let parsedToolsetRootDestinationV3Decoded = SwiftSDK(\n            targetTriple: linuxGNUTargetTriple,\n            toolset: .init(\n                knownTools: [\n                    .cCompiler: .init(extraCLIOptions: cCompilerOptions),\n                    .librarian: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.librarian]!)\")),\n                    .linker: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.linker]!)\")),\n                    .debugger: .init(path: try! AbsolutePath(validating: \"\\(usrBinTools[.debugger]!)\")),\n                ],\n                rootPaths: [try! AbsolutePath(validating: \"/custom\")]\n            ),\n            swiftSDKManifest: toolsetRootDestinationV3.path,\n            pathsConfiguration: .init(\n                sdkRootPath: bundleRootPath.appending(sdkRootDir),\n                toolsetPaths: [\"/tools/someToolsWithRoot.json\", \"/tools/otherToolsNoRoot.json\"]\n                    .map { try! AbsolutePath(validating: $0) }\n            )\n        )\n\n        XCTAssertEqual(toolsetRootDestinationV3Decoded, [parsedToolsetRootDestinationV3Decoded])\n\n        XCTAssertThrowsError(try SwiftSDK.decode(\n            fromFile: missingToolsetDestinationV3.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )) {\n            let toolsetDefinition: AbsolutePath = \"/tools/asdf.json\"\n            XCTAssertEqual(\n                $0 as? StringError,\n                StringError(\n                    \"\"\"\n                    Couldn't parse toolset configuration at `\\(toolsetDefinition)`: \\\n                    \\(toolsetDefinition) doesn't exist in file system\n                    \"\"\"\n                )\n            )\n        }\n        XCTAssertThrowsError(try SwiftSDK.decode(\n            fromFile: invalidVersionDestinationV3.path,\n            hostToolchainBinDir: bundleRootPath.appending(toolchainBinDir),\n            fileSystem: fs,\n            observabilityScope: observability\n        ))\n\n        XCTAssertThrowsError(try SwiftSDK.decode(\n            fromFile: invalidToolsetDestinationV3.path,\n            hostToolchainBinDir: bundleRootPath.appending(toolchainBinDir),\n            fileSystem: fs,\n            observabilityScope: observability\n        )) {\n            let toolsetDefinition: AbsolutePath = \"/tools/invalidToolset.json\"\n            XCTAssertTrue(\n                ($0 as? StringError)?.description\n                    .hasPrefix(\"Couldn't parse toolset configuration at `\\(toolsetDefinition)`: \") ?? false\n            )\n        }\n\n        let toolsetNoRootSwiftSDKv4Decoded = try SwiftSDK.decode(\n            fromFile: toolsetNoRootSwiftSDKv4.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        XCTAssertEqual(toolsetNoRootSwiftSDKv4Decoded, [parsedToolsetNoRootDestination])\n\n        let toolsetRootSwiftSDKv4Decoded = try SwiftSDK.decode(\n            fromFile: toolsetRootSwiftSDKv4.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        XCTAssertEqual(toolsetRootSwiftSDKv4Decoded, [parsedToolsetRootDestination])\n\n        let androidWithoutSDKRootPathSwiftSDKv4Decoded = try SwiftSDK.decode(\n            fromFile: androidWithoutSDKRootPathSwiftSDKv4.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        XCTAssertEqual(androidWithoutSDKRootPathSwiftSDKv4Decoded, [parsedToolsetNoSDKRootPathDestination])\n\n        XCTAssertThrowsError(try SwiftSDK.decode(\n            fromFile: missingToolsetSwiftSDKv4.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )) {\n            let toolsetDefinition: AbsolutePath = \"/tools/asdf.json\"\n            XCTAssertEqual(\n                $0 as? StringError,\n                StringError(\n                    \"\"\"\n                    Couldn't parse toolset configuration at `\\(toolsetDefinition)`: \\\n                    \\(toolsetDefinition) doesn't exist in file system\n                    \"\"\"\n                )\n            )\n        }\n        XCTAssertThrowsError(try SwiftSDK.decode(\n            fromFile: invalidVersionSwiftSDKv4.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        ))\n\n        XCTAssertThrowsError(try SwiftSDK.decode(\n            fromFile: invalidToolsetSwiftSDKv4.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )) {\n            let toolsetDefinition: AbsolutePath = \"/tools/invalidToolset.json\"\n            XCTAssertTrue(\n                ($0 as? StringError)?.description\n                    .hasPrefix(\"Couldn't parse toolset configuration at `\\(toolsetDefinition)`: \") ?? false\n            )\n        }\n\n        let wasiWithoutToolsetsDecoded = try SwiftSDK.decode(\n            fromFile: wasiWithoutToolsetsSwiftSDKv4.path,\n            hostToolchainBinDir: toolchainBinAbsolutePath,\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        XCTAssertEqual(wasiWithoutToolsetsDecoded.count, 1)\n\n        let wasmKitProperties = Toolset.ToolProperties(\n            path: toolchainBinAbsolutePath.appending(\"wasmkit\"),\n            extraCLIOptions: [\"run\", \"--dir\", \".\"]\n        )\n        XCTAssertEqual(wasiWithoutToolsetsDecoded[0].toolset.knownTools[.debugger], wasmKitProperties)\n\n        XCTAssertEqual(wasiWithoutToolsetsDecoded[0].toolset.knownTools[.testRunner], wasmKitProperties)\n    }\n\n    func testSelectDestination() throws {\n        let bundles = [\n            SwiftSDKBundle(\n                path: try AbsolutePath(validating: \"/destination.artifactsbundle\"),\n                artifacts: [\n                    \"id1\": [\n                        .init(\n                            metadata: .init(\n                                path: \"id1\",\n                                supportedTriples: [hostTriple]\n                            ),\n                            swiftSDKs: [parsedDestinationV2GNU]\n                        ),\n                    ],\n                    \"id2\": [\n                        .init(\n                            metadata: .init(\n                                path: \"id2\",\n                                supportedTriples: []\n                            ),\n                            swiftSDKs: [parsedDestinationV2GNU]\n                        ),\n                    ],\n                    \"id3\": [\n                        .init(\n                            metadata: .init(\n                                path: \"id3\",\n                                supportedTriples: [hostTriple]\n                            ),\n                            swiftSDKs: [parsedDestinationV2Musl]\n                        ),\n                    ],\n                    \"id4\": [\n                        .init(\n                            metadata: .init(\n                                path: \"id4\",\n                                supportedTriples: [olderHostTriple]\n                            ),\n                            swiftSDKs: [parsedDestinationForOlderHost]\n                        ),\n                    ],\n                    \"id5\": [\n                        .init(\n                            metadata: .init(\n                                path: \"id5\",\n                                supportedTriples: nil\n                            ),\n                            swiftSDKs: [parsedDestinationV2GNU]\n                        ),\n                    ],\n                ]\n            ),\n        ]\n\n        let system = ObservabilitySystem.makeForTesting()\n\n        XCTAssertEqual(\n            bundles.selectSwiftSDK(\n                matching: \"id1\",\n                hostTriple: hostTriple,\n                observabilityScope: system.topScope\n            ),\n            parsedDestinationV2GNU\n        )\n\n        // Expecting `nil` because no host triple is specified for this destination\n        // in the fake destination bundle.\n        XCTAssertNil(\n            bundles.selectSwiftSDK(\n                matching: \"id2\",\n                hostTriple: hostTriple,\n                observabilityScope: system.topScope\n            )\n        )\n\n        XCTAssertEqual(\n            bundles.selectSwiftSDK(\n                matching: \"id3\",\n                hostTriple: hostTriple,\n                observabilityScope: system.topScope\n            ),\n            parsedDestinationV2Musl\n        )\n\n        // Newer hostTriple should match with older supportedTriples\n        XCTAssertEqual(\n            bundles.selectSwiftSDK(\n                id: \"id4\",\n                hostTriple: hostTriple,\n                targetTriple: linuxMuslTargetTriple\n            ),\n            parsedDestinationForOlderHost\n        )\n        XCTAssertEqual(\n            bundles.selectSwiftSDK(\n                matching: \"id4\",\n                hostTriple: hostTriple,\n                observabilityScope: system.topScope\n            ),\n            parsedDestinationForOlderHost\n        )\n\n        // nil supportedTriples should match with any hostTriple\n        XCTAssertEqual(\n            bundles.selectSwiftSDK(\n                id: \"id5\",\n                hostTriple: hostTriple,\n                targetTriple: linuxGNUTargetTriple\n            ),\n            parsedDestinationV2GNU\n        )\n        XCTAssertEqual(\n            bundles.selectSwiftSDK(\n                matching: \"id5\",\n                hostTriple: hostTriple,\n                observabilityScope: system.topScope\n            ),\n            parsedDestinationV2GNU\n        )\n    }\n\n    func testDefaultSDKs() throws {\n        let hostSDK = try SwiftSDK.hostSwiftSDK(\"/prefix/bin\")\n\n        #if os(macOS)\n        let iOSPlatform = try AbsolutePath(validating: \"/usr/share/iPhoneOS.platform\")\n        let iOSRoot = try AbsolutePath(validating: \"/usr/share/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk\")\n        let iOSTriple = try Triple(\"arm64-apple-ios\")\n        let iOS = try XCTUnwrap(SwiftSDK.defaultSwiftSDK(\n            for: iOSTriple,\n            hostSDK: hostSDK,\n            environment: [\n                \"SWIFTPM_PLATFORM_PATH_iphoneos\": iOSPlatform.pathString,\n                \"SWIFTPM_SDKROOT_iphoneos\": iOSRoot.pathString,\n            ]\n        ))\n        XCTAssertEqual(iOS.toolset.rootPaths, hostSDK.toolset.rootPaths)\n\n        XCTAssertEqual(iOS.pathsConfiguration.sdkRootPath, iOSRoot)\n\n        let cFlags = iOS.toolset.knownTools[.cCompiler]?.extraCLIOptions ?? []\n        XCTAssert(cFlags.contains([\"-F\", \"\\(iOSPlatform.pathString)/Developer/Library/Frameworks\"]))\n        XCTAssertFalse(cFlags.contains { $0.lowercased().contains(\"macos\") }, \"Found macOS path in \\(cFlags)\")\n        #endif\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/ToolsVersionTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\nimport PackageModel\nimport Testing\n\n@Suite(\n    .tags(\n        .TestSize.small,\n    ),\n)\nstruct ToolsVersionTests {\n\n    @Test(\n        arguments: [\n            (version: \"3.1.0\", expected: \"3.1.0\",),\n            (version: \"4.0\", expected: \"4.0.0\",),\n            (version: \"0000104.0000000.4444\", expected: \"104.0.4444\",),\n            (version: \"1.2.3-alpha.beta+1011\", expected: \"1.2.3\",),\n            (version: \"1.2-alpha.beta+1011\", expected: \"1.2.0\",),\n            (version: \"1.0.0-alpha+001\", expected: \"1.0.0\",),\n            (version: \"1.0.0+20130313144700\", expected: \"1.0.0\",),\n            (version: \"1.0.0-beta+exp.sha.5114f85\", expected: \"1.0.0\",),\n            (version: \"1.0.0-alpha\", expected: \"1.0.0\",),\n            (version: \"1.0.0-alpha.1\", expected: \"1.0.0\",),\n            (version: \"1.0.0-0.3.7\", expected: \"1.0.0\",),\n            (version: \"1.0.0-x.7.z.92\", expected: \"1.0.0\",),\n            (version: \"1.0.0-alpha.beta\", expected: \"1.0.0\",),\n            (version: \"1.0.0-beta\", expected: \"1.0.0\",),\n            (version: \"1.0.0-beta.2\", expected: \"1.0.0\",),\n            (version: \"1.0.0-beta.11\", expected: \"1.0.0\",),\n            (version: \"1.0.0-rc.1\", expected: \"1.0.0\",),\n            (version: \"1.0.0\", expected: \"1.0.0\",),\n            (version: \"1.2.3-4\", expected: \"1.2.3\",),\n            (version: \"2.7.2+asdf\", expected: \"2.7.2\",),\n            (version: \"1.2.3-a.b.c.10.d.5\", expected: \"1.2.3\",),\n            (version: \"2.7.2-foo+bar\", expected: \"2.7.2\",),\n            (version: \"1.2.3-alpha.10.beta.0\", expected: \"1.2.3\",),\n            (version: \"1.2.3-al.10.beta.0+bu.uni.ra\", expected: \"1.2.3\",),\n            (version: \"1.2-al.10.beta.0+bu.uni.ra\", expected: \"1.2.0\",),\n        ],\n    )\n    func basicsValidVersions(\n        version: String,\n        expected: String\n    ) async  throws {\n        let toolsVersion = try #require(\n            ToolsVersion(string: version),\n            \"Couldn't form a version with string: \\(version)\"\n        )\n        #expect(toolsVersion.description == expected)\n    }\n\n    @Test(\n        arguments: [\n            \"1.2.3.4\",\n            \"1.2-al..beta.0+bu.uni.ra\",\n            \"1.2.33-al..beta.0+bu.uni.ra\",\n            \".1.0.0-x.7.z.92\",\n            \"1.0.0-alpha.beta+\",\n            \"1.0.0beta\",\n            \"1.0.0-\",\n            \"1.-2.3\",\n            \"1.2.3d\",\n        ],\n    )\n    func basicInvalidVersionreturnsNil(\n        version: String,\n    ) async throws {\n        #expect(ToolsVersion(string: version) == nil, \"Valid version generate from version: \\(version)\")\n    }\n\n    @Test(\n        arguments: [\n            (version: \"4.0.0\", expectedRuntimeSubpath: \"4\"),\n            (version: \"4.1.0\", expectedRuntimeSubpath: \"4\"),\n            (version: \"4.1.9\", expectedRuntimeSubpath: \"4\"),\n            (version: \"4.2.0\", expectedRuntimeSubpath: \"4_2\"),\n            (version: \"4.3.0\", expectedRuntimeSubpath: \"4_2\"),\n            (version: \"5.0.0\", expectedRuntimeSubpath: \"4_2\"),\n            (version: \"5.1.9\", expectedRuntimeSubpath: \"4_2\"),\n            (version: \"6.0.0\", expectedRuntimeSubpath: \"4_2\"),\n            (version: \"7.0.0\", expectedRuntimeSubpath: \"4_2\"),\n        ],\n    )\n    func runtimeSubpath(\n        version: String,\n        expectedRuntimeSubpath: String,\n    ) async  throws {\n        let version = try #require(ToolsVersion(string: version))\n\n        #expect(version.runtimeSubpath.pathString == expectedRuntimeSubpath)\n    }\n\n    @Test(\n        arguments: [\n            (version: \"4.0.0\", expectedSwiftLanguageVersion: \"4\"),\n            (version: \"4.1.0\", expectedSwiftLanguageVersion: \"4\"),\n            (version: \"4.1.9\", expectedSwiftLanguageVersion: \"4\"),\n            (version: \"4.2.0\", expectedSwiftLanguageVersion: \"4.2\"),\n            (version: \"4.3.0\", expectedSwiftLanguageVersion: \"4.2\"),\n            (version: \"5.0.0\", expectedSwiftLanguageVersion: \"5\"),\n            (version: \"5.1.9\", expectedSwiftLanguageVersion: \"5\"),\n            (version: \"6.0.0\", expectedSwiftLanguageVersion: \"6\"),\n            (version: \"7.0.0\", expectedSwiftLanguageVersion: \"6\"),\n        ],\n    )\n    func swiftLangVersion(\n        version: String,\n        expectedSwiftLanguageVersion: String,\n    ) async  throws {\n        let version = try #require(ToolsVersion(string: version))\n        #expect(version.swiftLanguageVersion.description == expectedSwiftLanguageVersion)\n    }\n}\n"
  },
  {
    "path": "Tests/PackageModelTests/ToolsetTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\n@testable import PackageModel\nimport _InternalTestSupport\nimport XCTest\n\nprivate let usrBinTools = Dictionary(uniqueKeysWithValues: Toolset.KnownTool.allCases.map {\n    ($0, try! AbsolutePath(validating: \"/usr/bin/\\($0.rawValue)\"))\n})\n\nprivate let cCompilerOptions = [\"-fopenmp\"]\nprivate let newCCompilerOptions = [\"-pedantic\"]\nprivate let cxxCompilerOptions = [\"-nostdinc++\"]\n\nprivate let compilersNoRoot = (\n    path: try! AbsolutePath(validating: \"/tools/compilersNoRoot.json\"),\n    json: #\"\"\"\n    {\n        \"schemaVersion\": \"1.0\",\n        \"swiftCompiler\": { \"path\": \"\\#(usrBinTools[.swiftCompiler]!)\" },\n        \"cCompiler\": { \"path\": \"\\#(usrBinTools[.cCompiler]!)\", \"extraCLIOptions\": \\#(cCompilerOptions) },\n        \"cxxCompiler\": { \"path\": \"\\#(usrBinTools[.cxxCompiler]!)\", \"extraCLIOptions\": \\#(cxxCompilerOptions) },\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let noValidToolsNoRoot = (\n    path: try! AbsolutePath(validating: \"/tools/noValidToolsNoRoot.json\"),\n    json: #\"\"\"\n    {\n        \"schemaVersion\": \"1.0\",\n        \"cCompiler\": {}\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let unknownToolsNoRoot = (\n    path: try! AbsolutePath(validating: \"/tools/unknownToolsNoRoot.json\"),\n    json: #\"\"\"\n    {\n        \"schemaVersion\": \"1.0\",\n        \"foo\": {},\n        \"bar\": {}\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let otherToolsNoRoot = (\n    path: try! AbsolutePath(validating: \"/tools/otherToolsNoRoot.json\"),\n    json: #\"\"\"\n    {\n        \"schemaVersion\": \"1.0\",\n        \"librarian\": { \"path\": \"\\#(usrBinTools[.librarian]!)\" },\n        \"linker\": { \"path\": \"\\#(usrBinTools[.linker]!)\" },\n        \"debugger\": { \"path\": \"\\#(usrBinTools[.debugger]!)\" }\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let someToolsWithRoot = (\n    path: try! AbsolutePath(validating: \"/tools/someToolsWithRoot.json\"),\n    json: #\"\"\"\n    {\n        \"schemaVersion\": \"1.0\",\n        \"rootPath\": \"/custom\",\n        \"cCompiler\": { \"extraCLIOptions\": \\#(newCCompilerOptions) },\n        \"linker\": { \"path\": \"ld\" },\n        \"librarian\": { \"path\": \"llvm-ar\" },\n        \"debugger\": { \"path\": \"\\#(usrBinTools[.debugger]!)\" }\n    }\n    \"\"\"# as SerializedJSON\n)\n\nprivate let someToolsWithRelativeRoot = (\n    path: try! AbsolutePath(validating: \"/tools/someToolsWithRelativeRoot.json\"),\n    json: #\"\"\"\n    {\n        \"schemaVersion\": \"1.0\",\n        \"rootPath\": \"relative/custom\",\n        \"cCompiler\": { \"extraCLIOptions\": \\#(newCCompilerOptions) }\n    }\n    \"\"\"# as SerializedJSON\n)\n\nfinal class ToolsetTests: XCTestCase {\n    func testToolset() throws {\n        let fileSystem = InMemoryFileSystem()\n        try fileSystem.createDirectory(AbsolutePath(validating: \"/tools\"))\n        for testFile in [compilersNoRoot, noValidToolsNoRoot, unknownToolsNoRoot, otherToolsNoRoot, someToolsWithRoot, someToolsWithRelativeRoot] {\n            try fileSystem.writeFileContents(testFile.path, string: testFile.json.underlying)\n        }\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let compilersToolset = try Toolset(from: compilersNoRoot.path, at: fileSystem, observability.topScope)\n\n        XCTAssertEqual(\n            compilersToolset.knownTools[.swiftCompiler],\n            Toolset.ToolProperties(path: usrBinTools[.swiftCompiler]!)\n        )\n        XCTAssertEqual(\n            compilersToolset.knownTools[.cCompiler],\n            Toolset.ToolProperties(path: usrBinTools[.cCompiler]!, extraCLIOptions: cCompilerOptions)\n        )\n        XCTAssertEqual(\n            compilersToolset.knownTools[.cxxCompiler],\n            Toolset.ToolProperties(path: usrBinTools[.cxxCompiler]!, extraCLIOptions: cxxCompilerOptions)\n        )\n\n        XCTAssertThrowsError(try Toolset(from: noValidToolsNoRoot.path, at: fileSystem, observability.topScope))\n\n        XCTAssertEqual(observability.errors.count, 1)\n        XCTAssertEqual(observability.warnings.count, 0)\n\n        let unknownToolsToolset = try Toolset(from: unknownToolsNoRoot.path, at: fileSystem, observability.topScope)\n\n        XCTAssertTrue(unknownToolsToolset.knownTools.isEmpty)\n        // +2 warnings for each unknown tool, no new errors\n        XCTAssertEqual(observability.errors.count, 1)\n        XCTAssertEqual(observability.warnings.count, 2)\n\n        var otherToolsToolset = try Toolset(from: otherToolsNoRoot.path, at: fileSystem, observability.topScope)\n\n        XCTAssertEqual(otherToolsToolset.knownTools.count, 3)\n        // no new warnings and errors were emitted\n        XCTAssertEqual(observability.errors.count, 1)\n        XCTAssertEqual(observability.warnings.count, 2)\n\n        otherToolsToolset.merge(with: compilersToolset)\n\n        XCTAssertEqual(\n            compilersToolset.knownTools[.swiftCompiler],\n            Toolset.ToolProperties(path: usrBinTools[.swiftCompiler]!)\n        )\n        XCTAssertEqual(\n            compilersToolset.knownTools[.cCompiler],\n            Toolset.ToolProperties(path: usrBinTools[.cCompiler]!, extraCLIOptions: cCompilerOptions)\n        )\n        XCTAssertEqual(\n            compilersToolset.knownTools[.cxxCompiler],\n            Toolset.ToolProperties(path: usrBinTools[.cxxCompiler]!, extraCLIOptions: cxxCompilerOptions)\n        )\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.librarian],\n            Toolset.ToolProperties(path: usrBinTools[.librarian]!)\n        )\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.linker],\n            Toolset.ToolProperties(path: usrBinTools[.linker]!)\n        )\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.debugger],\n            Toolset.ToolProperties(path: usrBinTools[.debugger]!)\n        )\n\n        let someToolsWithRoot = try Toolset(from: someToolsWithRoot.path, at: fileSystem, observability.topScope)\n\n        XCTAssertEqual(someToolsWithRoot.knownTools.count, 4)\n        // no new warnings and errors emitted\n        XCTAssertEqual(observability.errors.count, 1)\n        XCTAssertEqual(observability.warnings.count, 2)\n\n        otherToolsToolset.merge(with: someToolsWithRoot)\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.swiftCompiler],\n            Toolset.ToolProperties(path: usrBinTools[.swiftCompiler]!)\n        )\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.cCompiler],\n            Toolset.ToolProperties(\n                path: usrBinTools[.cCompiler]!,\n                extraCLIOptions: cCompilerOptions + newCCompilerOptions\n            )\n        )\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.cxxCompiler],\n            Toolset.ToolProperties(path: usrBinTools[.cxxCompiler]!, extraCLIOptions: cxxCompilerOptions)\n        )\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.librarian],\n            Toolset.ToolProperties(path: try! AbsolutePath(validating: \"/custom/llvm-ar\"))\n        )\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.linker],\n            Toolset.ToolProperties(path: try! AbsolutePath(validating: \"/custom/ld\"))\n        )\n        XCTAssertEqual(\n            otherToolsToolset.knownTools[.debugger],\n            Toolset.ToolProperties(path: usrBinTools[.debugger]!)\n        )\n\n        let someToolsWithRelativeRoot = try Toolset(from: someToolsWithRelativeRoot.path, at: fileSystem, observability.topScope)\n        XCTAssertEqual(\n            someToolsWithRelativeRoot,\n            Toolset(\n                knownTools: [.cCompiler: .init(extraCLIOptions: newCCompilerOptions)],\n                rootPaths: [try AbsolutePath(validating: \"/tools/relative/custom\")]\n            )\n        )\n    }\n\n    func testToolsetTargetToolchain() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        for testFile in [compilersNoRoot, noValidToolsNoRoot, unknownToolsNoRoot, otherToolsNoRoot, someToolsWithRoot, someToolsWithRelativeRoot] {\n            try fileSystem.writeFileContents(testFile.path, string: testFile.json.underlying)\n        }\n\n        let hostSwiftSDK = try SwiftSDK.hostSwiftSDK(environment: [:])\n        let hostTriple = try! Triple(\"arm64-apple-macosx14.0\")\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let store = SwiftSDKBundleStore(\n            swiftSDKsDirectory: \"/\",\n            hostToolchainBinDir: usrBinTools[.swiftCompiler]!.parentDirectory,\n            fileSystem: fileSystem,\n            observabilityScope: observability.topScope,\n            outputHandler: { _ in }\n        )\n\n        do {\n            let targetSwiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostTriple,\n                customToolsets: [compilersNoRoot.path],\n                store: store,\n                observabilityScope: observability.topScope,\n                fileSystem: fileSystem\n            )\n\n            let targetToolset = try Toolset(from: compilersNoRoot.path, at: fileSystem, observability.topScope)\n\n            // By default, the target SDK paths configuration is the same as the host SDK.\n            XCTAssertEqual(targetSwiftSDK.pathsConfiguration, hostSwiftSDK.pathsConfiguration)\n\n            var expectedToolset = hostSwiftSDK.toolset\n            expectedToolset.merge(with: targetToolset)\n\n            XCTAssertEqual(targetSwiftSDK.toolset, expectedToolset)\n        }\n\n        do {\n            let targetSwiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostTriple,\n                customToolsets: [someToolsWithRoot.path],\n                store: store,\n                observabilityScope: observability.topScope,\n                fileSystem: fileSystem\n            )\n\n            let targetToolset = try Toolset(from: someToolsWithRoot.path, at: fileSystem, observability.topScope)\n\n            // By default, the target SDK paths configuration is the same as the host SDK.\n            XCTAssertEqual(targetSwiftSDK.pathsConfiguration, hostSwiftSDK.pathsConfiguration)\n\n            var expectedToolset = hostSwiftSDK.toolset\n            expectedToolset.merge(with: targetToolset)\n\n            XCTAssertEqual(targetSwiftSDK.toolset, expectedToolset)\n        }\n\n        do {\n            let targetSwiftSDK = try SwiftSDK.deriveTargetSwiftSDK(\n                hostSwiftSDK: hostSwiftSDK,\n                hostTriple: hostTriple,\n                customToolsets: [compilersNoRoot.path, someToolsWithRoot.path],\n                store: store,\n                observabilityScope: observability.topScope,\n                fileSystem: fileSystem\n            )\n\n            let toolset1 = try Toolset(from: compilersNoRoot.path, at: fileSystem, observability.topScope)\n            let toolset2 = try Toolset(from: someToolsWithRoot.path, at: fileSystem, observability.topScope)\n\n            // By default, the target SDK paths configuration is the same as the host SDK.\n            XCTAssertEqual(targetSwiftSDK.pathsConfiguration, hostSwiftSDK.pathsConfiguration)\n\n            var expectedToolset = hostSwiftSDK.toolset\n            expectedToolset.merge(with: toolset1)\n            expectedToolset.merge(with: toolset2)\n\n            XCTAssertEqual(targetSwiftSDK.toolset, expectedToolset)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackagePluginAPITests/ArgumentExtractorTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackagePlugin\nimport XCTest\n\nclass ArgumentExtractorAPITests: XCTestCase {\n\n    func testBasics() throws {\n        var extractor = ArgumentExtractor([\"--verbose\", \"--target\", \"Target1\", \"Positional1\", \"--flag\", \"--verbose\", \"--target\", \"Target2\", \"Positional2\"])\n        XCTAssertEqual(extractor.extractOption(named: \"target\"), [\"Target1\", \"Target2\"])\n        XCTAssertEqual(extractor.extractFlag(named: \"flag\"), 1)\n        XCTAssertEqual(extractor.extractFlag(named: \"verbose\"), 2)\n        XCTAssertEqual(extractor.extractFlag(named: \"nothing\"), 0)\n        XCTAssertEqual(extractor.unextractedOptionsOrFlags, [])\n        XCTAssertEqual(extractor.remainingArguments, [\"Positional1\", \"Positional2\"])\n    }\n\n    func testExtractOption() throws {\n        var extractor = ArgumentExtractor([\"--output\", \"Dir1\", \"--target=Target1\", \"Positional1\", \"--flag\", \"--target\", \"Target2\", \"Positional2\", \"--output=Dir2\"])\n        XCTAssertEqual(extractor.extractOption(named: \"target\"), [\"Target1\", \"Target2\"])\n        XCTAssertEqual(extractor.extractOption(named: \"output\"), [\"Dir1\", \"Dir2\"])\n        XCTAssertEqual(extractor.extractFlag(named: \"flag\"), 1)\n        XCTAssertEqual(extractor.unextractedOptionsOrFlags, [])\n        XCTAssertEqual(extractor.remainingArguments, [\"Positional1\", \"Positional2\"])\n    }\n\n    func testDashDashTerminal() throws {\n        var extractor = ArgumentExtractor([\"--verbose\", \"--\", \"--target\", \"Target1\", \"Positional\", \"--verbose\"])\n        XCTAssertEqual(extractor.extractOption(named: \"target\"), [])\n        XCTAssertEqual(extractor.extractFlag(named: \"verbose\"), 1)\n        XCTAssertEqual(extractor.unextractedOptionsOrFlags, [])\n        XCTAssertEqual(extractor.remainingArguments, [\"--target\", \"Target1\", \"Positional\", \"--verbose\"])\n    }\n\n    func testEdgeCases() throws {\n        var extractor1 = ArgumentExtractor([])\n        XCTAssertEqual(extractor1.extractOption(named: \"target\"), [])\n        XCTAssertEqual(extractor1.extractFlag(named: \"verbose\"), 0)\n        XCTAssertEqual(extractor1.unextractedOptionsOrFlags, [])\n        XCTAssertEqual(extractor1.remainingArguments, [])\n\n        var extractor2 = ArgumentExtractor([\"--\"])\n        XCTAssertEqual(extractor2.extractOption(named: \"target\"), [])\n        XCTAssertEqual(extractor2.extractFlag(named: \"verbose\"), 0)\n        XCTAssertEqual(extractor2.unextractedOptionsOrFlags, [])\n        XCTAssertEqual(extractor2.remainingArguments, [])\n    }\n}\n"
  },
  {
    "path": "Tests/PackagePluginAPITests/PathTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport PackagePlugin\nimport XCTest\n\nclass PathAPITests: XCTestCase {\n\n    func testBasics() throws {\n        let path = Path(\"/tmp/file.foo\")\n        XCTAssertEqual(path.lastComponent, \"file.foo\")\n        XCTAssertEqual(path.stem, \"file\")\n        XCTAssertEqual(path.extension, \"foo\")\n        XCTAssertEqual(path.removingLastComponent(), Path(\"/tmp\"))\n    }\n\n    func testEdgeCases() throws {\n        let path = Path(\"/tmp/file.foo\")\n        XCTAssertEqual(path.removingLastComponent().removingLastComponent().removingLastComponent(), Path(\"/\"))\n    }\n}\n"
  },
  {
    "path": "Tests/PackageRegistryTests/PackageSigningEntityTOFUTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport Basics\nimport PackageModel\n@testable import PackageRegistry\n@testable import PackageSigning\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCUtility.Version\n\nfinal class PackageSigningEntityTOFUTests: XCTestCase {\n    func testSigningEntitySeenForTheFirstTime() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage()\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Package doesn't have any recorded signer.\n        // It should be ok to assign one.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity\n        )\n\n        // `signingEntity` meets requirement to be used for TOFU\n        // (i.e., it's .recognized), so it should be saved to storage.\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[signingEntity]?.versions, [version])\n    }\n\n    func testNilSigningEntityShouldNotBeSaved() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n\n        let signingEntityStorage = MockPackageSigningEntityStorage()\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Package doesn't have any recorded signer.\n        // It should be ok to continue not to have one.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: .none\n        )\n\n        // `signingEntity` is nil, so it should not be saved to storage.\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertTrue(packageSigners.isEmpty)\n    }\n\n    func testUnrecognizedSigningEntityShouldNotBeSaved() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let signingEntity = SigningEntity.unrecognized(\n            name: \"J. Appleseed\",\n            organizationalUnit: nil,\n            organization: nil\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage()\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Package doesn't have any recorded signer.\n        // It should be ok to continue not to have one.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity\n        )\n\n        // `signingEntity` is not .recognized, so it should not be saved to storage.\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertTrue(packageSigners.isEmpty)\n    }\n\n    func testSigningEntityMatchesStorageForSameVersion() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [signingEntity: PackageSigner(\n                    signingEntity: signingEntity,\n                    origins: [.registry(registry.url)],\n                    versions: [version]\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Storage has \"J. Appleseed\" as signer for package version.\n        // Signer remaining the same should be ok.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity\n        )\n    }\n\n    func testSigningEntityDoesNotMatchStorageForSameVersion_strictMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: [version]\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Storage has \"J. Smith\" as signer for package version.\n        // The given signer \"J. Appleseed\" is different so it should fail.\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                signingEntity: signingEntity\n            )\n        ) { error in\n            guard case RegistryError.signingEntityForReleaseChanged(_, _, _, let latest, let previous) = error else {\n                return XCTFail(\"Expected RegistryError.signingEntityForReleaseChanged, got '\\(error)'\")\n            }\n            XCTAssertEqual(latest, signingEntity)\n            XCTAssertEqual(previous, existingSigningEntity)\n        }\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, [version])\n    }\n\n    func testSigningEntityDoesNotMatchStorageForSameVersion_warnMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: [version]\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.warn // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Storage has \"J. Smith\" as signer for package version.\n        // The given signer \"J. Appleseed\" is different, but because\n        // of .warn mode, no error is thrown.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"different from the previously recorded value\"), severity: .warning)\n        }\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, [version])\n    }\n\n    func testPackageVersionLosingSigningEntity_strictMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: [version]\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Storage has \"J. Smith\" as signer for package version.\n        // The given signer is nil which is different so it should fail.\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                signingEntity: .none\n            )\n        ) { error in\n            guard case RegistryError.signingEntityForReleaseChanged(_, _, _, let latest, let previous) = error else {\n                return XCTFail(\"Expected RegistryError.signingEntityForReleaseChanged, got '\\(error)'\")\n            }\n            XCTAssertNil(latest)\n            XCTAssertEqual(previous, existingSigningEntity)\n        }\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, [version])\n    }\n\n    func testSigningEntityMatchesStorageForDifferentVersion() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let existingVersion = Version(\"2.0.0\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [signingEntity: PackageSigner(\n                    signingEntity: signingEntity,\n                    origins: [.registry(registry.url)],\n                    versions: [existingVersion]\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Storage has \"J. Appleseed\" as signer for package v2.0.0.\n        // Signer remaining the same should be ok.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity\n        )\n\n        // Storage should be updated with version 1.1.1 added\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[signingEntity]?.versions, [existingVersion, version])\n    }\n\n    func testSigningEntityDoesNotMatchStorageForDifferentVersion_strictMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let existingVersion = Version(\"2.0.0\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: [existingVersion]\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Storage has \"J. Smith\" as signer for package v2.0.0.\n        // The given signer \"J. Appleseed\" is different so it should fail.\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                signingEntity: signingEntity\n            )\n        ) { error in\n            guard case RegistryError.signingEntityForPackageChanged(\n                _,\n                _,\n                _,\n                let latest,\n                let previous,\n                let previousVersion\n            ) = error else {\n                return XCTFail(\"Expected RegistryError.signingEntityForPackageChanged, got '\\(error)'\")\n            }\n            XCTAssertEqual(latest, signingEntity)\n            XCTAssertEqual(previous, existingSigningEntity)\n            XCTAssertEqual(previousVersion, existingVersion)\n        }\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, [existingVersion])\n    }\n\n    func testSigningEntityDoesNotMatchStorageForDifferentVersion_warnMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let existingVersion = Version(\"2.0.0\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: [existingVersion]\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.warn // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Storage has \"J. Smith\" as signer for package v2.0.0.\n        // The given signer \"J. Appleseed\" is different, but because\n        // of .warn mode, no error is thrown.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"different from the previously recorded value\"), severity: .warning)\n        }\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, [existingVersion])\n    }\n\n    func testNilSigningEntityWhenStorageHasNewerSignedVersions() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let existingVersions = Set([Version(\"1.5.0\"), Version(\"2.0.0\")])\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: existingVersions\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Storage has versions 1.5.0 and 2.0.0 signed. The given version 1.1.1 is\n        // \"older\" than both, and we allow nil signer in this case, assuming\n        // this is before package started being signed.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: .none\n        )\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, existingVersions)\n    }\n\n    func testNilSigningEntityWhenStorageHasOlderSignedVersions_strictMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.6.1\")\n        let existingVersions = Set([Version(\"1.5.0\"), Version(\"2.0.0\")])\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: existingVersions\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Storage has versions 1.5.0 and 2.0.0 signed. The given version 1.6.1 is\n        // \"newer\" than 1.5.0, which we don't allow, because we assume from 1.5.0\n        // onwards all versions are signed.\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                signingEntity: .none\n            )\n        ) { error in\n            guard case RegistryError.signingEntityForPackageChanged(\n                _,\n                _,\n                _,\n                let latest,\n                let previous,\n                let previousVersion\n            ) = error else {\n                return XCTFail(\"Expected RegistryError.signingEntityForPackageChanged, got '\\(error)'\")\n            }\n            XCTAssertNil(latest)\n            XCTAssertEqual(previous, existingSigningEntity)\n            XCTAssertEqual(previousVersion, Version(\"1.5.0\"))\n        }\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, existingVersions)\n    }\n\n    func testNilSigningEntityWhenStorageHasOlderSignedVersions_warnMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.6.1\")\n        let existingVersions = Set([Version(\"1.5.0\"), Version(\"2.0.0\")])\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: existingVersions\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.warn // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Storage has versions 1.5.0 and 2.0.0 signed. The given version 1.6.1 is\n        // \"newer\" than 1.5.0, which we don't allow, because we assume from 1.5.0\n        // onwards all versions are signed. However, because of .warn mode,\n        // no error is thrown.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: .none,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"different from the previously recorded value\"), severity: .warning)\n        }\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, existingVersions)\n    }\n\n    func testNilSigningEntityWhenStorageHasOlderSignedVersionsInDifferentMajorVersion() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"2.0.0\")\n        let existingVersions = Set([Version(\"1.5.0\"), Version(\"3.0.0\")])\n        let existingSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: .none,\n                signers: [existingSigningEntity: PackageSigner(\n                    signingEntity: existingSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: existingVersions\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Storage has versions 1.5.0 and 3.0.0 signed. The given version 2.0.0 is\n        // \"newer\" than 1.5.0, but in a different major version (i.e., 1.x vs. 2.x).\n        // We allow this with the assumption that package signing might not have\n        // begun until a later 2.x version, so until we encounter a signed 2.x version,\n        // we assume none of them is signed.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: .none\n        )\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[existingSigningEntity]?.versions, existingVersions)\n    }\n\n    func testSigningEntityOfNewerVersionMatchesExpectedSigner() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"2.0.0\")\n        let expectedSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n        let expectedFromVersion = Version(\"1.5.0\")\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: (signingEntity: expectedSigningEntity, fromVersion: expectedFromVersion),\n                signers: [expectedSigningEntity: PackageSigner(\n                    signingEntity: expectedSigningEntity,\n                    origins: [.registry(registry.url)],\n                    versions: [expectedFromVersion]\n                )]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Package has expected signer starting from v1.5.0.\n        // The given v2.0.0 is newer than v1.5.0, and signer\n        // matches the expected signer.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: expectedSigningEntity\n        )\n\n        // Storage should be updated with v2.0.0 added\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 1)\n        XCTAssertEqual(packageSigners.signers[expectedSigningEntity]?.versions, [expectedFromVersion, version])\n    }\n\n    func testSigningEntityOfNewerVersionDoesNotMatchExpectedSignerButOlderThanExisting() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"2.0.0\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let existingVersion = Version(\"2.2.0\")\n        let expectedSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n        let expectedFromVersion = Version(\"1.5.0\")\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: (signingEntity: expectedSigningEntity, fromVersion: expectedFromVersion),\n                signers: [\n                    expectedSigningEntity: PackageSigner(\n                        signingEntity: expectedSigningEntity,\n                        origins: [.registry(registry.url)],\n                        versions: [expectedFromVersion]\n                    ),\n                    signingEntity: PackageSigner(\n                        signingEntity: signingEntity,\n                        origins: [.registry(registry.url)],\n                        versions: [existingVersion]\n                    ),\n                ]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Package has expected signer starting from v1.5.0, but\n        // the given signer was recorded previously for v2.2.0.\n        // The given v2.0.0 is before v2.2.0, and we allow the same\n        // signer for older versions.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity\n        )\n\n        // Storage should be updated with v2.0.0 added\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 2)\n        XCTAssertEqual(packageSigners.signers[expectedSigningEntity]?.versions, [expectedFromVersion])\n        XCTAssertEqual(packageSigners.signers[signingEntity]?.versions, [existingVersion, version])\n    }\n\n    func testSigningEntityOfNewerVersionDoesNotMatchExpectedSignerAndNewerThanExisting() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"2.3.0\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let existingVersion = Version(\"2.2.0\")\n        let expectedSigningEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Smith\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n        let expectedFromVersion = Version(\"1.5.0\")\n\n        let signingEntityStorage = MockPackageSigningEntityStorage(\n            [package.underlying: PackageSigners(\n                expectedSigner: (signingEntity: expectedSigningEntity, fromVersion: expectedFromVersion),\n                signers: [\n                    expectedSigningEntity: PackageSigner(\n                        signingEntity: expectedSigningEntity,\n                        origins: [.registry(registry.url)],\n                        versions: [expectedFromVersion]\n                    ),\n                    signingEntity: PackageSigner(\n                        signingEntity: signingEntity,\n                        origins: [.registry(registry.url)],\n                        versions: [existingVersion]\n                    ),\n                ]\n            )]\n        )\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // Package has expected signer starting from v1.5.0, and\n        // the given signer was recorded previously for v2.2.0, but\n        // the given v2.3.0 is after v2.2.0, which we don't allow\n        // because we assume the signer has \"stopped\" signing at v2.2.0.\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                signingEntity: signingEntity\n            )\n        ) { error in\n            guard case RegistryError.signingEntityForPackageChanged(\n                _,\n                _,\n                _,\n                let latest,\n                let previous,\n                let previousVersion\n            ) = error else {\n                return XCTFail(\"Expected RegistryError.signingEntityForPackageChanged, got '\\(error)'\")\n            }\n            XCTAssertEqual(latest, signingEntity)\n            XCTAssertEqual(previous, expectedSigningEntity)\n            XCTAssertEqual(previousVersion, expectedFromVersion)\n        }\n\n        // Storage should not be updated\n        let packageSigners = try signingEntityStorage.get(\n            package: package.underlying,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(packageSigners.signers.count, 2)\n        XCTAssertEqual(packageSigners.signers[expectedSigningEntity]?.versions, [expectedFromVersion])\n        XCTAssertEqual(packageSigners.signers[signingEntity]?.versions, [existingVersion])\n    }\n\n    func testWriteConflictsWithStorage_strictMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = WriteConflictSigningEntityStorage()\n        let signingEntityCheckingMode = SigningEntityCheckingMode.strict // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // This triggers a storage write conflict\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                signingEntity: signingEntity\n            )\n        ) { error in\n            guard case RegistryError.signingEntityForReleaseChanged = error else {\n                return XCTFail(\"Expected RegistryError.signingEntityForReleaseChanged, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testWriteConflictsWithStorage_warnMode() async throws {\n        let registry = Registry(url: URL(\"https://packages.example.com\"), supportsAvailability: false)\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let version = Version(\"1.1.1\")\n        let signingEntity = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n\n        let signingEntityStorage = WriteConflictSigningEntityStorage()\n        let signingEntityCheckingMode = SigningEntityCheckingMode.warn // intended for this test; don't change\n\n        let tofu = PackageSigningEntityTOFU(\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // This triggers a storage write conflict, but\n        // because of .warn mode, no error is thrown.\n        _ = try await tofu.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"different from the previously recorded value\"), severity: .warning)\n        }\n    }\n}\n\nextension PackageSigningEntityTOFU {\n    fileprivate func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        signingEntity: SigningEntity?,\n        observabilityScope: ObservabilityScope? = nil\n    ) async throws {\n        try await self.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            observabilityScope: observabilityScope ?? ObservabilitySystem.NOOP\n        )\n    }\n}\n\nprivate class WriteConflictSigningEntityStorage: PackageSigningEntityStorage {\n    func get(package: PackageModel.PackageIdentity, observabilityScope: Basics.ObservabilityScope) throws -> PackageSigning.PackageSigners {\n        return PackageSigners()\n    }\n\n    public func put(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        let existing = SigningEntity.recognized(\n            type: .adp,\n            name: \"xxx-\\(signingEntity.name ?? \"\")\",\n            organizationalUnit: \"xxx-\\(signingEntity.organizationalUnit ?? \"\")\",\n            organization: \"xxx-\\(signingEntity.organization ?? \"\")\"\n        )\n        throw PackageSigningEntityStorageError.conflict(\n            package: package,\n            version: version,\n            given: signingEntity,\n            existing: existing\n        )\n    }\n\n    public func add(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        throw StringError(\"unexpected call\")\n    }\n\n    public func changeSigningEntityFromVersion(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        throw StringError(\"unexpected call\")\n    }\n\n    public func changeSigningEntityForAllVersions(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        throw StringError(\"unexpected call\")\n    }\n}\n\nextension SigningEntity {\n    var name: String? {\n        switch self {\n        case .recognized(_, let name, _, _):\n            return name\n        case .unrecognized(let name, _, _):\n            return name\n        }\n    }\n\n    var organizationalUnit: String? {\n        switch self {\n        case .recognized(_, _, let organizationalUnit, _):\n            return organizationalUnit\n        case .unrecognized(_, let organizationalUnit, _):\n            return organizationalUnit\n        }\n    }\n\n    var organization: String? {\n        switch self {\n        case .recognized(_, _, _, let organization):\n            return organization\n        case .unrecognized(_, _, let organization):\n            return organization\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageRegistryTests/PackageVersionChecksumTOFUTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Foundation\nimport PackageFingerprint\nimport PackageModel\n@testable import PackageRegistry\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCUtility.Version\n\nfinal class PackageVersionChecksumTOFUTests: XCTestCase {\n    func testSourceArchiveChecksumSeenForTheFirstTime() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let metadataURL = URL(\"\\(registryURL)/\\(package.scope)/\\(package.name)/\\(version)\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        // Get package version metadata endpoint will be called to fetch expected checksum\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                XCTAssertEqual(request.headers.get(\"Accept\").first, \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                    \"id\": \"mona.LinkedList\",\n                    \"version\": \"1.1.1\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"description\": \"One thing links to another.\"\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = MockPackageFingerprintStorage()\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        // Checksum for package version not found in storage,\n        // so we fetch metadata to get the expected checksum,\n        // then save it to storage for future reference.\n        try await tofu.validateSourceArchive(\n            registry: registry,\n            package: package,\n            version: version,\n            checksum: checksum\n        )\n\n        // Checksum should have been saved to storage\n        let fingerprint = try fingerprintStorage.get(\n            package: identity,\n            version: version,\n            kind: .registry,\n            contentType: .sourceCode,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        XCTAssertEqual(SourceControlURL(registryURL), fingerprint.origin.url)\n        XCTAssertEqual(checksum, fingerprint.value)\n    }\n\n    func testSourceArchiveMetadataChecksumConflictsWithStorage_strictMode() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let metadataURL = URL(\"\\(registryURL)/\\(package.scope)/\\(package.name)/\\(version)\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                XCTAssertEqual(request.headers.get(\"Accept\").first, \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                    \"id\": \"mona.LinkedList\",\n                    \"version\": \"1.1.1\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"description\": \"One thing links to another.\"\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = WriteConflictFingerprintStorage()\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict // intended for this test, don't change\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        // We get expected checksum from metadata but it's different\n        // from value in storage, and because of .strict mode,\n        // an error is thrown.\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validateSourceArchive(\n                registry: registry,\n                package: package,\n                version: version,\n                checksum: checksum\n            )\n        ) { error in\n            guard case RegistryError.checksumChanged = error else {\n                return XCTFail(\"Expected RegistryError.checksumChanged, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testSourceArchiveMetadataChecksumConflictsWithStorage_warnMode() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let metadataURL = URL(\"\\(registryURL)/\\(package.scope)/\\(package.name)/\\(version)\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                XCTAssertEqual(request.headers.get(\"Accept\").first, \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                    \"id\": \"mona.LinkedList\",\n                    \"version\": \"1.1.1\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"description\": \"One thing links to another.\"\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = WriteConflictFingerprintStorage()\n        let fingerprintCheckingMode = FingerprintCheckingMode.warn // intended for this test, don't change\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // We get expected checksum from metadata and it's different\n        // from value in storage, but because of .warn mode,\n        // no error is thrown.\n        try await tofu.validateSourceArchive(\n            registry: registry,\n            package: package,\n            version: version,\n            checksum: checksum,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"does not match previously recorded value\"), severity: .warning)\n        }\n    }\n\n    func testFetchSourceArchiveMetadataChecksum_404() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let metadataURL = URL(\"\\(registryURL)/\\(package.scope)/\\(package.name)/\\(version)\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: metadataURL,\n            errorCode: 404,\n            errorDescription: \"not found\"\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = MockPackageFingerprintStorage()\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validateSourceArchive(\n                registry: registry,\n                package: package,\n                version: version,\n                checksum: checksum\n            )\n        ) { error in\n            guard case RegistryError.failedRetrievingReleaseChecksum = error else {\n                return XCTFail(\"Expected RegistryError.failedRetrievingReleaseChecksum, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testFetchSourceArchiveMetadataChecksum_ServerError() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let metadataURL = URL(\"\\(registryURL)/\\(package.scope)/\\(package.name)/\\(version)\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: metadataURL,\n            errorCode: 500,\n            errorDescription: UUID().uuidString\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = MockPackageFingerprintStorage()\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validateSourceArchive(\n                registry: registry,\n                package: package,\n                version: version,\n                checksum: checksum\n            )\n        ) { error in\n            guard case RegistryError.failedRetrievingReleaseChecksum = error else {\n                return XCTFail(\"Expected RegistryError.failedRetrievingReleaseChecksum, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testFetchSourceArchiveMetadataChecksum_RegistryNotAvailable() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        let serverErrorHandler = UnavailableServerErrorHandler(registryURL: registryURL)\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = MockPackageFingerprintStorage()\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validateSourceArchive(\n                registry: registry,\n                package: package,\n                version: version,\n                checksum: checksum\n            )\n        ) { error in\n            guard case RegistryError.failedRetrievingReleaseChecksum = error else {\n                return XCTFail(\"Expected RegistryError.failedRetrievingReleaseChecksum, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testSourceArchiveChecksumMatchingStorage() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        // Checksum already exists in storage so API will not be called\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"Unexpected request\")\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        .sourceCode: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: checksum,\n                            contentType: .sourceCode\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        // Checksum for package version found in storage,\n        // so we just compare that with the given checksum.\n        try await tofu.validateSourceArchive(\n            registry: registry,\n            package: package,\n            version: version,\n            checksum: checksum\n        )\n    }\n\n    func testSourceArchiveChecksumDoesNotMatchExpectedFromStorage_strictMode() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        // Checksum already exists in storage so API will not be called\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"Unexpected request\")\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        .sourceCode: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: .sourceCode\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict // intended for this test; don't change\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        // Checksum for package version found in storage,\n        // so we just compare that with the given checksum.\n        // Since the checksums don't match, and because of\n        // .strict mode, an error is thrown.\n        await XCTAssertAsyncThrowsError(\n            try await tofu.validateSourceArchive(\n                registry: registry,\n                package: package,\n                version: version,\n                checksum: checksum\n            )\n        ) { error in\n            guard case RegistryError.invalidChecksum = error else {\n                return XCTFail(\"Expected RegistryError.invalidChecksum, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testSourceArchiveChecksumDoesNotMatchExpectedFromStorage_warnMode() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        // Checksum already exists in storage so API will not be called\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"Unexpected request\")\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        .sourceCode: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: .sourceCode\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let fingerprintCheckingMode = FingerprintCheckingMode.warn // intended for this test; don't change\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Checksum for package version found in storage,\n        // so we just compare that with the given checksum.\n        // The checksums don't match, but because of\n        // .warn mode, no error is thrown.\n        try await tofu.validateSourceArchive(\n            registry: registry,\n            package: package,\n            version: version,\n            checksum: checksum,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"does not match previously recorded value\"), severity: .warning)\n        }\n    }\n\n    func testManifestChecksumSeenForTheFirstTime() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n\n        // Registry API doesn't include manifest checksum so we don't call it\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"Unexpected request\")\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let fingerprintStorage = MockPackageFingerprintStorage()\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        // Checksum for package version not found in storage,\n        // so we save it to storage for future reference.\n        try tofu.validateManifest(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: .v5_6, // Version specific manifest\n            checksum: \"Package@swift-5.6.swift checksum\"\n        )\n\n        try tofu.validateManifest(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: .none, // default manifest\n            checksum: \"Package.swift checksum\"\n        )\n\n        // Checksums should have been saved to storage\n        do {\n            let fingerprint = try fingerprintStorage.get(\n                package: identity,\n                version: version,\n                kind: .registry,\n                contentType: .manifest(.none),\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            XCTAssertEqual(SourceControlURL(registryURL), fingerprint.origin.url)\n            XCTAssertEqual(\"Package.swift checksum\", fingerprint.value)\n        }\n        do {\n            let fingerprint = try fingerprintStorage.get(\n                package: identity,\n                version: version,\n                kind: .registry,\n                contentType: .manifest(.v5_6),\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            XCTAssertEqual(SourceControlURL(registryURL), fingerprint.origin.url)\n            XCTAssertEqual(\"Package@swift-5.6.swift checksum\", fingerprint.value)\n        }\n    }\n\n    func testManifestChecksumMatchingStorage() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        // Registry API doesn't include manifest checksum so we don't call it\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"Unexpected request\")\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let contentType = Fingerprint.ContentType.manifest(.none)\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        contentType: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: checksum,\n                            contentType: contentType\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        // Checksum for package version found in storage,\n        // so we just compare that with the given checksum.\n        try tofu.validateManifest(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: .none,\n            checksum: checksum\n        )\n    }\n\n    func testManifestChecksumDoesNotMatchExpectedFromStorage_strictMode() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        // Registry API doesn't include manifest checksum so we don't call it\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"Unexpected request\")\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let contentType = Fingerprint.ContentType.manifest(.none)\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        contentType: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: contentType\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let fingerprintCheckingMode = FingerprintCheckingMode.strict // intended for this test; don't change\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        // Checksum for package version found in storage,\n        // so we just compare that with the given checksum.\n        // Since the checksums don't match, and because of\n        // .strict mode, an error is thrown.\n        await XCTAssertAsyncThrowsError(\n            try tofu.validateManifest(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: .none,\n                checksum: checksum\n            )\n        ) { error in\n            guard case RegistryError.invalidChecksum = error else {\n                return XCTFail(\"Expected RegistryError.invalidChecksum, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testManifestChecksumDoesNotMatchExpectedFromStorage_warnMode() async throws {\n        let registryURL = URL(\"https://packages.example.com\")\n        let identity = PackageIdentity.plain(\"mona.LinkedList\")\n        let package = identity.registry!\n        let version = Version(\"1.1.1\")\n        let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n\n        // Registry API doesn't include manifest checksum so we don't call it\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"Unexpected request\")\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let contentType = Fingerprint.ContentType.manifest(.none)\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        contentType: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: contentType\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let fingerprintCheckingMode = FingerprintCheckingMode.warn // intended for this test; don't change\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode\n        )\n\n        let tofu = PackageVersionChecksumTOFU(\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Checksum for package version found in storage,\n        // so we just compare that with the given checksum.\n        // The checksums don't match, but because of\n        // .warn mode, no error is thrown.\n        try tofu.validateManifest(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: .none,\n            checksum: checksum,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"does not match previously recorded value\"), severity: .warning)\n        }\n    }\n}\n\nextension PackageVersionChecksumTOFU {\n    fileprivate func validateSourceArchive(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        checksum: String,\n        observabilityScope: ObservabilityScope? = nil\n    ) async throws {\n        try await self.validateSourceArchive(\n            registry: registry,\n            package: package,\n            version: version,\n            checksum: checksum,\n            timeout: nil,\n            observabilityScope: observabilityScope ?? ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func validateManifest(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        toolsVersion: ToolsVersion?,\n        checksum: String,\n        observabilityScope: ObservabilityScope? = nil\n    ) throws {\n        try self.validateManifest(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: toolsVersion,\n            checksum: checksum,\n            timeout: nil,\n            observabilityScope: observabilityScope ?? ObservabilitySystem.NOOP\n        )\n    }\n}\n\nprivate class WriteConflictFingerprintStorage: PackageFingerprintStorage {\n    func get(\n        package: PackageIdentity,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]] {\n        throw PackageFingerprintStorageError.notFound\n    }\n\n    func put(\n        package: PackageIdentity,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        let existing = Fingerprint(\n            origin: fingerprint.origin,\n            value: \"xxx-\\(fingerprint.value)\",\n            contentType: fingerprint.contentType\n        )\n        throw PackageFingerprintStorageError.conflict(given: fingerprint, existing: existing)\n    }\n\n    func get(\n        package: PackageReference,\n        version: Version,\n        observabilityScope: ObservabilityScope\n    ) throws -> [Fingerprint.Kind: [Fingerprint.ContentType: Fingerprint]]{\n        try self.get(\n            package: package.identity,\n            version: version,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    func put(\n        package: PackageReference,\n        version: Version,\n        fingerprint: Fingerprint,\n        observabilityScope: ObservabilityScope\n    ) throws {\n        try self.put(\n            package: package.identity,\n            version: version,\n            fingerprint: fingerprint,\n            observabilityScope: observabilityScope\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/PackageRegistryTests/RegistryClientTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport _Concurrency\nimport Foundation\nimport PackageFingerprint\nimport PackageLoading\nimport PackageModel\n@testable import PackageRegistry\nimport PackageSigning\nimport _InternalTestSupport\nimport Testing\n\nimport protocol TSCBasic.HashAlgorithm\nimport struct TSCUtility.Version\n\nfileprivate let registryURL = URL(\"https://packages.example.com\")\nfileprivate let identity = PackageIdentity.plain(\"mona.LinkedList\")\nfileprivate let version = Version(\"1.1.1\")\nfileprivate let packageURL = SourceControlURL(\"https://example.com/mona/LinkedList\")\nfileprivate var releasesURL = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)\")\nfileprivate var releaseURL = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)\")\nfileprivate var metadataURL = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)\")\nfileprivate var manifestURL = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)/Package.swift\")\nfileprivate var downloadURL = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version).zip\")\nfileprivate var identifiersURL = URL(\"\\(registryURL)/identifiers?url=\\(packageURL.absoluteString)\")\nfileprivate var publishURL = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)\")\nfileprivate var availabilityURL = URL(\"\\(registryURL)/availability\")\n\n@Suite(\"Package Metadata\") struct PackageMetadata {\n    @Test func getPackageMetadata() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, releasesURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = #\"\"\"\n                {\n                    \"releases\": {\n                        \"1.1.1\": {\n                            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.1\"\n                        },\n                        \"1.1.0\": {\n                            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.0\",\n                            \"problem\": {\n                                \"status\": 410,\n                                \"title\": \"Gone\",\n                                \"detail\": \"this release was removed from the registry\"\n                            }\n                        },\n                        \"1.0.0\": {\n                            \"url\": \"https://packages.example.com/mona/LinkedList/1.0.0\"\n                        }\n                    }\n                }\n                \"\"\"#.data(using: .utf8)!\n\n                let links = \"\"\"\n                <https://github.com/mona/LinkedList>; rel=\"canonical\",\n                <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n                <git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n                <https://gitlab.com/mona/LinkedList>; rel=\"alternate\"\n                \"\"\"\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Link\", value: links),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let assert: (RegistryClient.PackageMetadata) -> Void = { metadata in\n            #expect(metadata.versions == [\"1.1.1\", \"1.0.0\"])\n            #expect(metadata.alternateLocations == [\n                SourceControlURL(\"https://github.com/mona/LinkedList\"),\n                SourceControlURL(\"ssh://git@github.com:mona/LinkedList.git\"),\n                SourceControlURL(\"git@github.com:mona/LinkedList.git\"),\n                SourceControlURL(\"https://gitlab.com/mona/LinkedList\"),\n            ])\n        }\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        let metadata = try await registryClient.getPackageMetadata(package: identity)\n        assert(metadata)\n\n        let metadataSync = try await withCheckedThrowingContinuation { continuation in\n            return registryClient.getPackageMetadata(\n                package: identity,\n                timeout: nil,\n                observabilityScope: ObservabilitySystem.NOOP,\n                callbackQueue: .sharedConcurrent,\n                completion: { continuation.resume(with: $0) }\n            )\n        }\n        assert(metadataSync)\n    }\n\n    @Test func getPackageMetadataPaginated() async throws {\n        let releasesURLPage2 = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)?page=2\")\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            guard case .get = request.method else {\n                throw StringError(\"method should be `get`\")\n            }\n\n            #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n            let links: String\n            let data: Data\n            switch request.url {\n            case releasesURL:\n                data = #\"\"\"\n                {\n                    \"releases\": {\n                        \"1.1.1\": {\n                            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.1\"\n                        },\n                        \"1.1.0\": {\n                            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.0\",\n                            \"problem\": {\n                                \"status\": 410,\n                                \"title\": \"Gone\",\n                                \"detail\": \"this release was removed from the registry\"\n                            }\n                        }\n                    }\n                }\n                \"\"\"#.data(using: .utf8)!\n\n                links = \"\"\"\n                <https://github.com/mona/LinkedList>; rel=\"canonical\",\n                <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n                <git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n                <https://gitlab.com/mona/LinkedList>; rel=\"alternate\",\n                <\\(releasesURLPage2)>; rel=\"next\"\n                \"\"\"\n            case releasesURLPage2:\n                data = #\"\"\"\n                {\n                    \"releases\": {\n                        \"1.0.0\": {\n                            \"url\": \"https://packages.example.com/mona/LinkedList/1.0.0\"\n                        }\n                    }\n                }\n                \"\"\"#.data(using: .utf8)!\n\n                links = \"\"\"\n                <https://github.com/mona/LinkedList>; rel=\"canonical\",\n                <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n                <git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n                <https://gitlab.com/mona/LinkedList>; rel=\"alternate\"\n                \"\"\"\n            default:\n                throw StringError(\"method and url should match\")\n            }\n\n            return .init(\n                statusCode: 200,\n                headers: .init([\n                    .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                    .init(name: \"Content-Type\", value: \"application/json\"),\n                    .init(name: \"Content-Version\", value: \"1\"),\n                    .init(name: \"Link\", value: links),\n                ]),\n                body: data\n            )\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        let metadata = try await registryClient.getPackageMetadata(package: identity)\n        #expect(metadata.versions == [\"1.1.1\", \"1.0.0\"])\n        #expect(metadata.alternateLocations == [\n            SourceControlURL(\"https://github.com/mona/LinkedList\"),\n            SourceControlURL(\"ssh://git@github.com:mona/LinkedList.git\"),\n            SourceControlURL(\"git@github.com:mona/LinkedList.git\"),\n            SourceControlURL(\"https://gitlab.com/mona/LinkedList\"),\n        ])\n    }\n\n    @Test func getPackageMetadataPaginatedCancellation() async throws {\n        let releasesURLPage2 = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)?page=2\")\n\n        var task: Task<Void, Error>? = nil\n        let handler: HTTPClient.Implementation = { request, _ in\n            guard case .get = request.method else {\n                throw StringError(\"method should be `get`\")\n            }\n\n            #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n            let links: String\n            let data: Data\n            switch request.url {\n            case releasesURLPage2:\n                // Cancel during the second iteration\n                task?.cancel()\n                fallthrough\n            case releasesURL:\n                data = #\"\"\"\n                {\n                    \"releases\": {\n                        \"1.1.1\": {\n                            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.1\"\n                        },\n                        \"1.1.0\": {\n                            \"url\": \"https://packages.example.com/mona/LinkedList/1.1.0\",\n                            \"problem\": {\n                                \"status\": 410,\n                                \"title\": \"Gone\",\n                                \"detail\": \"this release was removed from the registry\"\n                            }\n                        }\n                    }\n                }\n                \"\"\"#.data(using: .utf8)!\n\n                links = \"\"\"\n                <https://github.com/mona/LinkedList>; rel=\"canonical\",\n                <ssh://git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n                <git@github.com:mona/LinkedList.git>; rel=\"alternate\",\n                <https://gitlab.com/mona/LinkedList>; rel=\"alternate\",\n                <\\(releasesURLPage2)>; rel=\"next\"\n                \"\"\"\n            default:\n                throw StringError(\"method and url should match\")\n            }\n\n            return .init(\n                statusCode: 200,\n                headers: .init([\n                    .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                    .init(name: \"Content-Type\", value: \"application/json\"),\n                    .init(name: \"Content-Version\", value: \"1\"),\n                    .init(name: \"Link\", value: links),\n                ]),\n                body: data\n            )\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n\n        task = Task {\n            await #expect(throws: _Concurrency.CancellationError.self) {\n                try await registryClient.getPackageMetadata(package: identity)\n            }\n        }\n\n        try await task?.value\n    }\n\n    @Test func handlesNotFound() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: releasesURL,\n            errorCode: 404,\n            errorDescription: UUID().uuidString\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getPackageMetadata(package: identity)\n        } throws: { error in\n            if case RegistryError.failedRetrievingReleases(\n                registry: configuration.defaultRegistry!,\n                package: identity,\n                error: RegistryError.packageNotFound\n            ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesServerError() async throws {\n        let releasesURL = URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)\")\n\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: releasesURL,\n            errorCode: Int.random(in: 405 ..< 500),\n            errorDescription: UUID().uuidString\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getPackageMetadata(package: identity)\n        } throws: { error in\n            if case RegistryError\n                .failedRetrievingReleases(\n                    registry: configuration.defaultRegistry!,\n                    package: identity,\n                    error: RegistryError.serverError(\n                        code: serverErrorHandler.errorCode,\n                        details: serverErrorHandler.errorDescription\n                    )\n                ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesRegistryNotAvailable() async throws {\n        let serverErrorHandler = UnavailableServerErrorHandler(registryURL: registryURL)\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getPackageMetadata(package: identity)\n        } throws: { error in\n            if case RegistryError.registryNotAvailable(registry) = error {\n                return true\n            }\n            return false\n        }\n    }\n}\n\n@Suite(\"Package Version Metadata\") struct PackageVersionMetadata {\n    @Test func getPackageVersionMetadata() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, releaseURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = #\"\"\"\n                {\n                    \"id\": \"mona.LinkedList\",\n                    \"version\": \"1.1.1\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\"#.data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let assert: (RegistryClient.PackageVersionMetadata) -> Void = { metadata in\n            #expect(metadata.resources.count == 1)\n            #expect(metadata.resources[0].name == \"source-archive\")\n            #expect(metadata.resources[0].type == \"application/zip\")\n            #expect(metadata.resources[0].checksum == \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\")\n            #expect(metadata.author?.name == \"J. Appleseed\")\n            #expect(metadata.licenseURL == URL(\"https://github.com/mona/LinkedList/license\"))\n            #expect(metadata.readmeURL == URL(\"https://github.com/mona/LinkedList/readme\"))\n            #expect(metadata.repositoryURLs! == [\n                SourceControlURL(\"https://github.com/mona/LinkedList\"),\n                SourceControlURL(\"ssh://git@github.com:mona/LinkedList.git\"),\n                SourceControlURL(\"git@github.com:mona/LinkedList.git\"),\n            ])\n        }\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        let metadata = try await registryClient.getPackageVersionMetadata(package: identity, version: version)\n        assert(metadata)\n\n        let metadataSync = try await withCheckedThrowingContinuation { continuation in\n            return registryClient.getPackageVersionMetadata(\n                package: identity,\n                version: version,\n                fileSystem: InMemoryFileSystem(),\n                observabilityScope: ObservabilitySystem.NOOP,\n                callbackQueue: .sharedConcurrent,\n                completion: { continuation.resume(with: $0) }\n            )\n        }\n        assert(metadataSync)\n    }\n\n    @Test func getPackageVersionMetadataInCache() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let expectedChecksums: [Version: String] = [\n            Version(\"1.1.1\"): \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\",\n            Version(\"1.1.0\"): checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n        ]\n\n        let counter = SendableBox(0)\n        let handler: HTTPClient.Implementation = { request, _ in\n            await counter.increment()\n            switch (request.method, request.url) {\n            case (.get, releasesURL.appending(component: \"1.1.1\")):\n                let expectedChecksum = expectedChecksums[Version(\"1.1.1\")]!\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                    \"id\": \"mona.LinkedList\",\n                    \"version\": \"1.1.1\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(expectedChecksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, releasesURL.appending(component: \"1.1.0\")):\n                let expectedChecksum = expectedChecksums[Version(\"1.1.0\")]!\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                    \"id\": \"mona.LinkedList\",\n                    \"version\": \"1.1.0\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(expectedChecksum)\",\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n\n        var expectedRequestCount = 0\n        try await check(version: Version(\"1.1.1\"), expectCached: false)\n        try await check(version: Version(\"1.1.0\"), expectCached: false)\n        try await check(version: Version(\"1.1.1\"), expectCached: true)\n        try await check(version: Version(\"1.1.0\"), expectCached: true)\n\n        func check(version: Version, expectCached: Bool) async throws {\n            let metadata = try await registryClient.getPackageVersionMetadata(package: identity, version: version)\n\n            if !expectCached {\n                expectedRequestCount += 1\n            }\n\n            let count = await counter.value\n            #expect(count == expectedRequestCount)\n            #expect(metadata.author?.name == \"J. Appleseed\")\n            #expect(metadata.resources[0].checksum == expectedChecksums[version]!)\n        }\n    }\n\n    func getPackageVersionMetadata_404() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: releaseURL,\n            errorCode: 404,\n            errorDescription: UUID().uuidString\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getPackageVersionMetadata(package: identity, version: version)\n        } throws: { error in\n            if case RegistryError\n                .failedRetrievingReleaseInfo(\n                    registry: configuration.defaultRegistry!,\n                    package: identity,\n                    version: version,\n                    error: RegistryError.packageVersionNotFound\n                ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesServerError() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: releaseURL,\n            errorCode: Int.random(in: 405 ..< 500),\n            errorDescription: UUID().uuidString\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getPackageVersionMetadata(package: identity, version: version)\n        } throws: { error in\n            if case RegistryError\n                .failedRetrievingReleaseInfo(\n                    registry: configuration.defaultRegistry!,\n                    package: identity,\n                    version: version,\n                    error: RegistryError.serverError(\n                        code: serverErrorHandler.errorCode,\n                        details: serverErrorHandler.errorDescription\n                    )\n                ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesRegistryNotAvailable() async throws {\n        let serverErrorHandler = UnavailableServerErrorHandler(registryURL: registryURL)\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getPackageVersionMetadata(package: identity, version: version)\n        } throws: { error in\n            if case RegistryError.registryNotAvailable(registry) = error {\n                return true\n            }\n            return false\n        }\n    }\n}\n\n@Suite(\"Available Manifests\") struct AvailabileManifests {\n    var metadataURL: URL { URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)\") }\n    var manifestURL: URL {\n        URL(\"\\(registryURL)/\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)/Package.swift\")\n    }\n    @Test func availableManifests() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let defaultManifest = \"\"\"\n        // swift-tools-version:5.5\n        import PackageDescription\n\n        let package = Package(\n            name: \"LinkedList\",\n            products: [\n                .library(name: \"LinkedList\", targets: [\"LinkedList\"])\n            ],\n            targets: [\n                .target(name: \"LinkedList\"),\n                .testTarget(name: \"LinkedListTests\", dependencies: [\"LinkedList\"]),\n            ],\n            swiftLanguageVersions: [.v4, .v5]\n        )\n        \"\"\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let defaultManifestData = Data(defaultManifest.utf8)\n\n                let links = \"\"\"\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4>; rel=\"alternate\"; filename=\"Package@swift-4.swift\"; swift-tools-version=\"4.0\",\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4.2>; rel=\"alternate\"; filename=\"Package@swift-4.2.swift\"; swift-tools-version=\"4.2\",\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=5.3>; rel=\"alternate\"; filename=\"Package@swift-5.3.swift\"; swift-tools-version=\"5.3\"\n                \"\"\"\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(defaultManifestData.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Link\", value: links),\n                    ]),\n                    body: defaultManifestData\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let assert: ([String: (toolsVersion: ToolsVersion, content: String?)]) -> Void = { availableManifests in\n            #expect(availableManifests[\"Package.swift\"]?.toolsVersion == .v5_5)\n            #expect(availableManifests[\"Package.swift\"]?.content == defaultManifest)\n            #expect(availableManifests[\"Package@swift-4.swift\"]?.toolsVersion == .v4)\n            #expect(availableManifests[\"Package@swift-4.swift\"]?.content == .none)\n            #expect(availableManifests[\"Package@swift-4.2.swift\"]?.toolsVersion == .v4_2)\n            #expect(availableManifests[\"Package@swift-4.2.swift\"]?.content == .none)\n            #expect(availableManifests[\"Package@swift-5.3.swift\"]?.toolsVersion == .v5_3)\n            #expect(availableManifests[\"Package@swift-5.3.swift\"]?.content == .none)\n        }\n\n        let availableManifests = try await registryClient.getAvailableManifests(\n            package: identity,\n            version: version,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n        assert(availableManifests)\n\n        let availableManifestsSync = try await withCheckedThrowingContinuation { continuation in\n            return registryClient.getAvailableManifests(\n                package: identity,\n                version: version,\n                observabilityScope: ObservabilitySystem.NOOP,\n                callbackQueue: .sharedConcurrent,\n                completion: { continuation.resume(with: $0) }\n            )\n        }\n        assert(availableManifestsSync)\n    }\n\n    @Test func availableManifestsMatchingChecksumInStorage() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let defaultManifest = \"\"\"\n        // swift-tools-version:5.5\n        import PackageDescription\n\n        let package = Package(\n            name: \"LinkedList\",\n            products: [\n                .library(name: \"LinkedList\", targets: [\"LinkedList\"])\n            ],\n            targets: [\n                .target(name: \"LinkedList\"),\n                .testTarget(name: \"LinkedListTests\", dependencies: [\"LinkedList\"]),\n            ],\n            swiftLanguageVersions: [.v4, .v5]\n        )\n        \"\"\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let defaultManifestData = Data(defaultManifest.utf8)\n\n                let links = \"\"\"\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4>; rel=\"alternate\"; filename=\"Package@swift-4.swift\"; swift-tools-version=\"4.0\",\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4.2>; rel=\"alternate\"; filename=\"Package@swift-4.2.swift\"; swift-tools-version=\"4.2\",\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=5.3>; rel=\"alternate\"; filename=\"Package@swift-5.3.swift\"; swift-tools-version=\"5.3\"\n                \"\"\"\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(defaultManifestData.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Link\", value: links),\n                    ]),\n                    body: defaultManifestData\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let contentType = Fingerprint.ContentType.manifest(.none)\n        let manifestChecksum = checksumAlgorithm.hash(.init(Data(defaultManifest.utf8)))\n            .hexadecimalRepresentation\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        contentType: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: manifestChecksum,\n                            contentType: contentType\n                        ),\n                    ],\n                ],\n            ],\n        ])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict,\n            checksumAlgorithm: checksumAlgorithm\n        )\n        let availableManifests = try await registryClient.getAvailableManifests(\n            package: identity,\n            version: version,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        #expect(availableManifests[\"Package.swift\"]?.toolsVersion == .v5_5)\n        #expect(availableManifests[\"Package.swift\"]?.content == defaultManifest)\n        #expect(availableManifests[\"Package@swift-4.swift\"]?.toolsVersion == .v4)\n        #expect(availableManifests[\"Package@swift-4.swift\"]?.content == .none)\n        #expect(availableManifests[\"Package@swift-4.2.swift\"]?.toolsVersion == .v4_2)\n        #expect(availableManifests[\"Package@swift-4.2.swift\"]?.content == .none)\n        #expect(availableManifests[\"Package@swift-5.3.swift\"]?.toolsVersion == .v5_3)\n        #expect(availableManifests[\"Package@swift-5.3.swift\"]?.content == .none)\n    }\n\n    @Test func availableManifestsNonMatchingChecksumInStorage_strict() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let defaultManifest = \"\"\"\n        // swift-tools-version:5.5\n        import PackageDescription\n\n        let package = Package(\n            name: \"LinkedList\",\n            products: [\n                .library(name: \"LinkedList\", targets: [\"LinkedList\"])\n            ],\n            targets: [\n                .target(name: \"LinkedList\"),\n                .testTarget(name: \"LinkedListTests\", dependencies: [\"LinkedList\"]),\n            ],\n            swiftLanguageVersions: [.v4, .v5]\n        )\n        \"\"\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let defaultManifestData = Data(defaultManifest.utf8)\n\n                let links = \"\"\"\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4>; rel=\"alternate\"; filename=\"Package@swift-4.swift\"; swift-tools-version=\"4.0\",\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4.2>; rel=\"alternate\"; filename=\"Package@swift-4.2.swift\"; swift-tools-version=\"4.2\",\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=5.3>; rel=\"alternate\"; filename=\"Package@swift-5.3.swift\"; swift-tools-version=\"5.3\"\n                \"\"\"\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(defaultManifestData.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Link\", value: links),\n                    ]),\n                    body: defaultManifestData\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let contentType = Fingerprint.ContentType.manifest(.none)\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        contentType: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: contentType\n                        ),\n                    ],\n                ],\n            ],\n        ])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict, // intended for this test; don't change\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        await #expect {\n            try await registryClient.getAvailableManifests(\n                package: identity,\n                version: version,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n        } throws: { error in\n            if case RegistryError.invalidChecksum = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func availableManifestsNonMatchingChecksumInStorage_warn() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let defaultManifest = \"\"\"\n        // swift-tools-version:5.5\n        import PackageDescription\n\n        let package = Package(\n            name: \"LinkedList\",\n            products: [\n                .library(name: \"LinkedList\", targets: [\"LinkedList\"])\n            ],\n            targets: [\n                .target(name: \"LinkedList\"),\n                .testTarget(name: \"LinkedListTests\", dependencies: [\"LinkedList\"]),\n            ],\n            swiftLanguageVersions: [.v4, .v5]\n        )\n        \"\"\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let defaultManifestData = Data(defaultManifest.utf8)\n\n                let links = \"\"\"\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4>; rel=\"alternate\"; filename=\"Package@swift-4.swift\"; swift-tools-version=\"4.0\",\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=4.2>; rel=\"alternate\"; filename=\"Package@swift-4.2.swift\"; swift-tools-version=\"4.2\",\n                <http://packages.example.com/mona/LinkedList/1.1.1/Package.swift?swift-version=5.3>; rel=\"alternate\"; filename=\"Package@swift-5.3.swift\"; swift-tools-version=\"5.3\"\n                \"\"\"\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(defaultManifestData.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Link\", value: links),\n                    ]),\n                    body: defaultManifestData\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let contentType = Fingerprint.ContentType.manifest(.none)\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        contentType: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: contentType\n                        ),\n                    ],\n                ],\n            ],\n        ])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .warn, // intended for this test; don't change\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        // The checksum differs from that in storage, but error is not thrown\n        // because fingerprintCheckingMode=.warn\n        let availableManifests = try await registryClient.getAvailableManifests(\n            package: identity,\n            version: version,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"does not match previously recorded value\"), severity: .warning)\n        }\n\n        #expect(availableManifests[\"Package.swift\"]?.toolsVersion == .v5_5)\n        #expect(availableManifests[\"Package.swift\"]?.content == defaultManifest)\n        #expect(availableManifests[\"Package@swift-4.swift\"]?.toolsVersion == .v4)\n        #expect(availableManifests[\"Package@swift-4.swift\"]?.content == .none)\n        #expect(availableManifests[\"Package@swift-4.2.swift\"]?.toolsVersion == .v4_2)\n        #expect(availableManifests[\"Package@swift-4.2.swift\"]?.content == .none)\n        #expect(availableManifests[\"Package@swift-5.3.swift\"]?.toolsVersion == .v5_3)\n        #expect(availableManifests[\"Package@swift-5.3.swift\"]?.content == .none)\n    }\n\n    @Test func handles404() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: manifestURL,\n            errorCode: 404,\n            errorDescription: \"not found\"\n        )\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [],\n                    \"metadata\": {}\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                return try await serverErrorHandler.handle(request: request, progress: nil)\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getAvailableManifests(\n                package: identity,\n                version: version,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n        } throws: { error in\n            if case RegistryError.failedRetrievingManifest(\n                registry: configuration.defaultRegistry!,\n                package: identity,\n                version: version,\n                error: RegistryError.packageVersionNotFound\n            ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesServerError() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: manifestURL,\n            errorCode: Int.random(in: 405 ..< 500),\n            errorDescription: UUID().uuidString\n        )\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [],\n                    \"metadata\": {}\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                return try await serverErrorHandler.handle(request: request, progress: nil)\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getAvailableManifests(\n                package: identity,\n                version: version,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n        } throws: { error in\n            if case RegistryError.failedRetrievingManifest(\n                registry: configuration.defaultRegistry!,\n                package: identity,\n                version: version,\n                error: RegistryError.serverError(\n                    code: serverErrorHandler.errorCode,\n                    details: serverErrorHandler.errorDescription\n                )\n            ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesRegistryNotAvailable() async throws {\n        let serverErrorHandler = UnavailableServerErrorHandler(registryURL: registryURL)\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getAvailableManifests(\n                package: identity,\n                version: version,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n        } throws: { error in\n            if case RegistryError.registryNotAvailable(registry) = error {\n                return true\n            }\n            return false\n        }\n    }\n}\n\n@Suite(\"Manifest Content\") struct ManifestContent {\n    @Test(arguments: [\n        (toolsVersion: ToolsVersion.v5_3, expectedToolsVersion: ToolsVersion.v5_3),\n        (toolsVersion: ToolsVersion.v4, expectedToolsVersion: ToolsVersion.v4),\n        (toolsVersion: nil, expectedToolsVersion: ToolsVersion.current)\n    ])\n    func getManifestContent(toolsVersion: ToolsVersion?, expectedToolsVersion: ToolsVersion) async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            var components = URLComponents(url: request.url, resolvingAgainstBaseURL: false)!\n            let toolsVersion = components.queryItems?.first { $0.name == \"swift-version\" }\n                .flatMap { ToolsVersion(string: $0.value!) } ?? ToolsVersion.current\n            // remove query\n            components.query = nil\n            let urlWithoutQuery = components.url\n            switch (request.method, urlWithoutQuery) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let data = \"\"\"\n                // swift-tools-version:\\(toolsVersion)\n\n                import PackageDescription\n\n                let package = Package()\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        do {\n            let manifest = try await registryClient.getManifestContent(\n                package: identity,\n                version: version,\n                customToolsVersion: toolsVersion\n            )\n            let parsedToolsVersion = try ToolsVersionParser.parse(utf8String: manifest)\n            #expect(parsedToolsVersion == expectedToolsVersion)\n        }\n\n        do {\n            let manifestSync = try await withCheckedThrowingContinuation { continuation in\n                return registryClient.getManifestContent(\n                    package: identity,\n                    version: version,\n                    customToolsVersion: toolsVersion,\n                    observabilityScope: ObservabilitySystem.NOOP,\n                    callbackQueue: .sharedConcurrent\n                ) { continuation.resume(with: $0) }\n            }\n            let parsedToolsVersion = try ToolsVersionParser.parse(utf8String: manifestSync)\n            #expect(parsedToolsVersion == expectedToolsVersion)\n        }\n    }\n\n    @Test(arguments: [\n        (toolsVersion: ToolsVersion.v5_3, expectedToolsVersion: ToolsVersion.v5_3),\n        (toolsVersion: nil, expectedToolsVersion: ToolsVersion.current)\n    ])\n    func getManifestContentWithOptionalContentVersion(toolsVersion: ToolsVersion?, expectedToolsVersion: ToolsVersion) async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            var components = URLComponents(url: request.url, resolvingAgainstBaseURL: false)!\n            let toolsVersion = components.queryItems?.first { $0.name == \"swift-version\" }\n                .flatMap { ToolsVersion(string: $0.value!) } ?? ToolsVersion.current\n            // remove query\n            components.query = nil\n            let urlWithoutQuery = components.url\n            switch (request.method, urlWithoutQuery) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let data = \"\"\"\n                // swift-tools-version:\\(toolsVersion)\n\n                import PackageDescription\n\n                let package = Package()\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        // Omit `Content-Version` header\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        do {\n            let manifest = try await registryClient.getManifestContent(\n                package: identity,\n                version: version,\n                customToolsVersion: toolsVersion\n            )\n            let parsedToolsVersion = try ToolsVersionParser.parse(utf8String: manifest)\n            #expect(parsedToolsVersion == expectedToolsVersion)\n        }\n    }\n\n    @Test(arguments: [\n        (toolsVersion: ToolsVersion.v5_3, expectedToolsVersion: ToolsVersion.v5_3),\n        (toolsVersion: nil, expectedToolsVersion: ToolsVersion.current)\n    ])\n    func getManifestContentMatchingChecksumInStorage(toolsVersion: ToolsVersion?, expectedToolsVersion: ToolsVersion) async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            var components = URLComponents(url: request.url, resolvingAgainstBaseURL: false)!\n            let toolsVersion = components.queryItems?.first { $0.name == \"swift-version\" }\n                .flatMap { ToolsVersion(string: $0.value!) } ?? ToolsVersion.current\n            // remove query\n            components.query = nil\n            let urlWithoutQuery = components.url\n            switch (request.method, urlWithoutQuery) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let data = Data(manifestContent(toolsVersion: toolsVersion).utf8)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let defaultManifestChecksum = checksumAlgorithm\n            .hash(.init(Data(manifestContent(toolsVersion: .none).utf8))).hexadecimalRepresentation\n        let versionManifestChecksum = checksumAlgorithm\n            .hash(.init(Data(manifestContent(toolsVersion: .v5_3).utf8))).hexadecimalRepresentation\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        Fingerprint.ContentType.manifest(.none): Fingerprint(\n                            origin: .registry(registryURL),\n                            value: defaultManifestChecksum,\n                            contentType: Fingerprint.ContentType.manifest(.none)\n                        ),\n                        Fingerprint.ContentType.manifest(.v5_3): Fingerprint(\n                            origin: .registry(registryURL),\n                            value: versionManifestChecksum,\n                            contentType: Fingerprint.ContentType.manifest(.v5_3)\n                        ),\n                    ],\n                ],\n            ],\n        ])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        do {\n            let manifest = try await registryClient.getManifestContent(\n                package: identity,\n                version: version,\n                customToolsVersion: toolsVersion\n            )\n            let parsedToolsVersion = try ToolsVersionParser.parse(utf8String: manifest)\n            #expect(parsedToolsVersion == expectedToolsVersion)\n        }\n    }\n\n    @Test(arguments: [ToolsVersion.v5_3, nil])\n    func getManifestContentWithNonMatchingChecksumInStorage_strict(toolsVersion: ToolsVersion?) async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            var components = URLComponents(url: request.url, resolvingAgainstBaseURL: false)!\n            let toolsVersion = components.queryItems?.first { $0.name == \"swift-version\" }\n                .flatMap { ToolsVersion(string: $0.value!) } ?? ToolsVersion.current\n            // remove query\n            components.query = nil\n            let urlWithoutQuery = components.url\n            switch (request.method, urlWithoutQuery) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let data = Data(manifestContent(toolsVersion: toolsVersion).utf8)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        Fingerprint.ContentType.manifest(.none): Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: Fingerprint.ContentType.manifest(.none)\n                        ),\n                        Fingerprint.ContentType.manifest(.v5_3): Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: Fingerprint.ContentType.manifest(.v5_3)\n                        ),\n                    ],\n                ],\n            ],\n        ])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict, // intended for this test; don't change\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        await #expect {\n            try await registryClient.getManifestContent(\n                package: identity,\n                version: version,\n                customToolsVersion: toolsVersion\n            )\n        } throws: { error in\n            if case RegistryError.invalidChecksum = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test(arguments: [\n        (toolsVersion: ToolsVersion.v5_3, expectedToolsVersion: ToolsVersion.v5_3),\n        (toolsVersion: nil, expectedToolsVersion: ToolsVersion.current)\n    ])\n    func getManifestContentWithNonMatchingChecksumInStorage_warn(toolsVersion: ToolsVersion?, expectedToolsVersion: ToolsVersion) async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            var components = URLComponents(url: request.url, resolvingAgainstBaseURL: false)!\n            let toolsVersion = components.queryItems?.first { $0.name == \"swift-version\" }\n                .flatMap { ToolsVersion(string: $0.value!) } ?? ToolsVersion.current\n            // remove query\n            components.query = nil\n            let urlWithoutQuery = components.url\n            switch (request.method, urlWithoutQuery) {\n            case (.get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.get, manifestURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+swift\")\n\n                let data = Data(manifestContent(toolsVersion: toolsVersion).utf8)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"text/x-swift\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        Fingerprint.ContentType.manifest(.none): Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: Fingerprint.ContentType.manifest(.none)\n                        ),\n                        Fingerprint.ContentType.manifest(.v5_3): Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: Fingerprint.ContentType.manifest(.v5_3)\n                        ),\n                    ],\n                ],\n            ],\n        ])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .warn, // intended for this test; don't change\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        do {\n            let observability = ObservabilitySystem.makeForTesting()\n            // The checksum differs from that in storage, but error is not thrown\n            // because fingerprintCheckingMode=.warn\n            let manifest = try await registryClient.getManifestContent(\n                package: identity,\n                version: version,\n                customToolsVersion: toolsVersion,\n                observabilityScope: observability.topScope\n            )\n\n            // But there should be a warning\n            try expectDiagnostics(observability.diagnostics) { result in\n                result.check(diagnostic: .contains(\"does not match previously recorded value\"), severity: .warning)\n            }\n\n            let parsedToolsVersion = try ToolsVersionParser.parse(utf8String: manifest)\n            #expect(parsedToolsVersion == expectedToolsVersion)\n        }\n    }\n\n    @Test func handles404() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: manifestURL,\n            errorCode: 404,\n            errorDescription: \"not found\"\n        )\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [],\n                    \"metadata\": {}\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                return try await serverErrorHandler.handle(request: request, progress: nil)\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getManifestContent(\n                package: identity,\n                version: version,\n                customToolsVersion: nil\n            )\n        } throws: { error in\n            if case RegistryError.failedRetrievingManifest(\n                registry: configuration.defaultRegistry!,\n                package: identity,\n                version: version,\n                error: RegistryError.packageVersionNotFound\n            ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesServerError() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: manifestURL,\n            errorCode: Int.random(in: 405 ..< 500),\n            errorDescription: UUID().uuidString\n        )\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [],\n                    \"metadata\": {}\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                return try await serverErrorHandler.handle(request: request, progress: nil)\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getManifestContent(\n                package: identity,\n                version: version,\n                customToolsVersion: nil\n            )\n        } throws: { error in\n            if case RegistryError.failedRetrievingManifest(\n                registry: configuration.defaultRegistry!,\n                package: identity,\n                version: version,\n                error: RegistryError.serverError(\n                    code: serverErrorHandler.errorCode,\n                    details: serverErrorHandler.errorDescription\n                )\n            ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesRegistryNotAvailable() async throws {\n        let serverErrorHandler = UnavailableServerErrorHandler(registryURL: registryURL)\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.getManifestContent(\n                package: identity,\n                version: version,\n                customToolsVersion: nil\n            )\n        } throws: { error in\n            if case RegistryError.registryNotAvailable(registry) = error {\n                return true\n            }\n            return false\n        }\n    }\n}\n\n@Suite(\"Download Source Archive\") struct DownloadSourceArchive {\n    @Test func downloadSourceArchive() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let author = UUID().uuidString\n        let licenseURL = URL(\"https://github.com/\\(identity.registry!.scope)/\\(identity.registry!.name)/license\")\n        let readmeURL = URL(\"https://github.com/\\(identity.registry!.scope)/\\(identity.registry!.name)/readme\")\n        let repositoryURLs = [\n            SourceControlURL(\"https://github.com/\\(identity.registry!.scope)/\\(identity.registry!.name)\"),\n            SourceControlURL(\"ssh://git@github.com:\\(identity.registry!.scope)/\\(identity.registry!.name).git\"),\n            SourceControlURL(\"git@github.com:\\(identity.registry!.scope)/\\(identity.registry!.name).git\"),\n        ]\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"\\(author)\"\n                        },\n                        \"licenseURL\": \"\\(licenseURL)\",\n                        \"readmeURL\": \"\\(readmeURL)\",\n                        \"repositoryURLs\": [\\\"\\(repositoryURLs.map(\\.absoluteString).joined(separator: \"\\\", \\\"\"))\\\"]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.download(let fileSystem, let path), .get, downloadURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+zip\")\n\n                let data = Data(emptyZipFile.contents)\n                try! fileSystem.writeFileContents(path, data: data)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/zip\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(\n                            name: \"Content-Disposition\",\n                            value: \"attachment; filename=\\\"\\(identity)-\\(version).zip\\\"\"\n                        ),\n                        .init(\n                            name: \"Digest\",\n                            value: \"sha-256=bc6c9a5d2f2226cfa1ef4fad8344b10e1cc2e82960f468f70d9ed696d26b3283\"\n                        ),\n                    ]),\n                    body: nil\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: .none,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            customArchiverProvider: { fileSystem in\n                MockArchiver(handler: { _, from, to, callback in\n                    let data = try fileSystem.readFileContents(from)\n                    #expect(data == emptyZipFile)\n\n                    let packagePath = to.appending(component: \"package\")\n                    try fileSystem.createDirectory(packagePath, recursive: true)\n                    try fileSystem.writeFileContents(packagePath.appending(component: \"Package.swift\"), string: \"\")\n                    callback(.success(()))\n                })\n            },\n            delegate: .none,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = try! AbsolutePath(validating: \"/\\(identity)-\\(version)\")\n\n        try await registryClient.downloadSourceArchive(\n            package: identity,\n            version: version,\n            fileSystem: fileSystem,\n            destinationPath: path\n        )\n\n        let assert: (AbsolutePath) throws -> Void = { path in\n            let contents = try fileSystem.getDirectoryContents(path)\n            #expect(contents.sorted() == [RegistryReleaseMetadataStorage.fileName, \"Package.swift\"].sorted())\n\n            let storedMetadata = try RegistryReleaseMetadataStorage.load(\n                from: path.appending(component: RegistryReleaseMetadataStorage.fileName),\n                fileSystem: fileSystem\n            )\n            #expect(storedMetadata.source == .registry(registryURL))\n            #expect(storedMetadata.metadata.author?.name == author)\n            #expect(storedMetadata.metadata.licenseURL == licenseURL)\n            #expect(storedMetadata.metadata.readmeURL == readmeURL)\n            #expect(storedMetadata.metadata.scmRepositoryURLs == repositoryURLs)\n        }\n        try assert(path)\n\n        let syncPath = try! AbsolutePath(validating: \"/\\(identity)-\\(version)-sync\")\n        try await withCheckedThrowingContinuation { continuation in\n            registryClient.downloadSourceArchive(\n                package: identity,\n                version: version,\n                destinationPath: syncPath,\n                progressHandler: nil,\n                fileSystem: fileSystem,\n                observabilityScope: ObservabilitySystem.NOOP,\n                callbackQueue: .sharedConcurrent,\n                completion: { continuation.resume(with: $0) }\n            )\n        }\n\n        try assert(syncPath)\n    }\n\n    @Test func sourceArchiveMatchingChecksumInStorage() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.download(let fileSystem, let path), .get, downloadURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+zip\")\n\n                let data = Data(emptyZipFile.contents)\n                try! fileSystem.writeFileContents(path, data: data)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/zip\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Content-Disposition\", value: #\"attachment; filename=\"LinkedList-1.1.1.zip\"\"#),\n                        .init(\n                            name: \"Digest\",\n                            value: \"sha-256=bc6c9a5d2f2226cfa1ef4fad8344b10e1cc2e82960f468f70d9ed696d26b3283\"\n                        ),\n                    ]),\n                    body: nil\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        .sourceCode: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: checksum,\n                            contentType: .sourceCode\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            customArchiverProvider: { fileSystem in\n                MockArchiver(handler: { _, from, to, callback in\n                    let data = try fileSystem.readFileContents(from)\n                    #expect(data == emptyZipFile)\n\n                    let packagePath = to.appending(\"package\")\n                    try fileSystem.createDirectory(packagePath, recursive: true)\n                    try fileSystem.writeFileContents(packagePath.appending(\"Package.swift\"), string: \"\")\n                    callback(.success(()))\n                })\n            },\n            delegate: .none,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = AbsolutePath(\"/LinkedList-1.1.1\")\n\n        try await registryClient.downloadSourceArchive(\n            package: identity,\n            version: version,\n            fileSystem: fileSystem,\n            destinationPath: path\n        )\n\n        let contents = try fileSystem.getDirectoryContents(path)\n        #expect(contents.sorted() == [RegistryReleaseMetadataStorage.fileName, \"Package.swift\"].sorted())\n    }\n\n    @Test func sourceArchiveNonMatchingChecksumInStorage() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.download(let fileSystem, let path), .get, downloadURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+zip\")\n\n                let data = Data(emptyZipFile.contents)\n                try! fileSystem.writeFileContents(path, data: data)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/zip\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Content-Disposition\", value: #\"attachment; filename=\"LinkedList-1.1.1.zip\"\"#),\n                        .init(\n                            name: \"Digest\",\n                            value: \"sha-256=bc6c9a5d2f2226cfa1ef4fad8344b10e1cc2e82960f468f70d9ed696d26b3283\"\n                        ),\n                    ]),\n                    body: nil\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        .sourceCode: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: .sourceCode\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict, // intended for this test; don't change\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            customArchiverProvider: { fileSystem in\n                MockArchiver(handler: { _, from, to, callback in\n                    let data = try fileSystem.readFileContents(from)\n                    #expect(data == emptyZipFile)\n\n                    let packagePath = to.appending(\"package\")\n                    try fileSystem.createDirectory(packagePath, recursive: true)\n                    try fileSystem.writeFileContents(packagePath.appending(\"Package.swift\"), string: \"\")\n                    callback(.success(()))\n                })\n            },\n            delegate: .none,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = AbsolutePath(\"/LinkedList-1.1.1\")\n\n        await #expect {\n            try await registryClient.downloadSourceArchive(\n                package: identity,\n                version: version,\n                fileSystem: fileSystem,\n                destinationPath: path\n            )\n        } throws: { error in\n            if case RegistryError.invalidChecksum = error {\n                return true\n            }\n            return false\n        }\n\n        // download did not succeed so directory does not exist\n        #expect(!fileSystem.exists(path))\n    }\n\n    @Test func sourceArchiveNonMatchingChecksumInStorage_fingerprintChecking_warn() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"J. Appleseed\"\n                        },\n                        \"licenseURL\": \"https://github.com/mona/LinkedList/license\",\n                        \"readmeURL\": \"https://github.com/mona/LinkedList/readme\",\n                        \"repositoryURLs\": [\n                            \"https://github.com/mona/LinkedList\",\n                            \"ssh://git@github.com:mona/LinkedList.git\",\n                            \"git@github.com:mona/LinkedList.git\"\n                        ]\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.download(let fileSystem, let path), .get, downloadURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+zip\")\n\n                let data = Data(emptyZipFile.contents)\n                try! fileSystem.writeFileContents(path, data: data)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/zip\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Content-Disposition\", value: #\"attachment; filename=\"LinkedList-1.1.1.zip\"\"#),\n                        .init(\n                            name: \"Digest\",\n                            value: \"sha-256=bc6c9a5d2f2226cfa1ef4fad8344b10e1cc2e82960f468f70d9ed696d26b3283\"\n                        ),\n                    ]),\n                    body: nil\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let fingerprintStorage = MockPackageFingerprintStorage([\n            identity: [\n                version: [\n                    .registry: [\n                        .sourceCode: Fingerprint(\n                            origin: .registry(registryURL),\n                            value: \"non-matching checksum\",\n                            contentType: .sourceCode\n                        ),\n                    ],\n                ],\n            ],\n        ])\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .warn, // intended for this test; don't change\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            customArchiverProvider: { fileSystem in\n                MockArchiver(handler: { _, from, to, callback in\n                    let data = try fileSystem.readFileContents(from)\n                    #expect(data == emptyZipFile)\n\n                    let packagePath = to.appending(\"package\")\n                    try fileSystem.createDirectory(packagePath, recursive: true)\n                    try fileSystem.writeFileContents(packagePath.appending(\"Package.swift\"), string: \"\")\n                    callback(.success(()))\n                })\n            },\n            delegate: .none,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = AbsolutePath(\"/LinkedList-1.1.1\")\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // The checksum differs from that in storage, but error is not thrown\n        // because fingerprintCheckingMode=.warn\n        try await registryClient.downloadSourceArchive(\n            package: identity,\n            version: version,\n            fileSystem: fileSystem,\n            destinationPath: path,\n            observabilityScope: observability.topScope\n        )\n\n        // But there should be a warning\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: .contains(\"does not match previously recorded value\"), severity: .warning)\n        }\n\n        let contents = try fileSystem.getDirectoryContents(path)\n        #expect(contents.sorted() == [RegistryReleaseMetadataStorage.fileName, \"Package.swift\"].sorted())\n    }\n\n    @Test func sourceArchiveChecksumNotInStorage() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.download(let fileSystem, let path), .get, downloadURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+zip\")\n\n                let data = Data(emptyZipFile.contents)\n                try! fileSystem.writeFileContents(path, data: data)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/zip\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(name: \"Content-Disposition\", value: #\"attachment; filename=\"LinkedList-1.1.1.zip\"\"#),\n                        .init(\n                            name: \"Digest\",\n                            value: \"sha-256=bc6c9a5d2f2226cfa1ef4fad8344b10e1cc2e82960f468f70d9ed696d26b3283\"\n                        ),\n                    ]),\n                    body: nil\n                )\n                // `downloadSourceArchive` calls this API to fetch checksum\n            case (.generic, .get, metadataURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                \"id\": \"mona.LinkedList\",\n                \"version\": \"1.1.1\",\n                \"resources\": [\n                    {\n                    \"name\": \"source-archive\",\n                    \"type\": \"application/zip\",\n                    \"checksum\": \"\\(checksum)\"\n                    }\n                ],\n                \"metadata\": {\n                    \"description\": \"One thing links to another.\"\n                }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let fingerprintStorage = MockPackageFingerprintStorage()\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            customArchiverProvider: { fileSystem in\n                MockArchiver(handler: { _, from, to, callback in\n                    let data = try fileSystem.readFileContents(from)\n                    #expect(data == emptyZipFile)\n\n                    let packagePath = to.appending(\"package\")\n                    try fileSystem.createDirectory(packagePath, recursive: true)\n                    try fileSystem.writeFileContents(packagePath.appending(\"Package.swift\"), string: \"\")\n                    callback(.success(()))\n                })\n            },\n            delegate: .none,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = AbsolutePath(\"/LinkedList-1.1.1\")\n\n        try await registryClient.downloadSourceArchive(\n            package: identity,\n            version: version,\n            fileSystem: fileSystem,\n            destinationPath: path\n        )\n\n        let contents = try fileSystem.getDirectoryContents(path)\n        #expect(contents.sorted() == [RegistryReleaseMetadataStorage.fileName, \"Package.swift\"].sorted())\n\n        // Expected checksum is not found in storage so the metadata API will be called\n        let fingerprint = try fingerprintStorage.get(\n            package: identity,\n            version: version,\n            kind: .registry,\n            contentType: .sourceCode,\n            observabilityScope: ObservabilitySystem\n                .NOOP\n        )\n        #expect(SourceControlURL(registryURL) == fingerprint.origin.url)\n        #expect(checksum == fingerprint.value)\n    }\n\n    @Test func downloadSourceArchiveOptionalContentVersion() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.download(let fileSystem, let path), .get, downloadURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+zip\")\n\n                let data = Data(emptyZipFile.contents)\n                try! fileSystem.writeFileContents(path, data: data)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/zip\"),\n                        // Omit `Content-Version` header\n                        .init(name: \"Content-Disposition\", value: #\"attachment; filename=\"LinkedList-1.1.1.zip\"\"#),\n                        .init(\n                            name: \"Digest\",\n                            value: \"sha-256=bc6c9a5d2f2226cfa1ef4fad8344b10e1cc2e82960f468f70d9ed696d26b3283\"\n                        ),\n                    ]),\n                    body: nil\n                )\n                // `downloadSourceArchive` calls this API to fetch checksum\n            case (.generic, .get, metadataURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                \"id\": \"mona.LinkedList\",\n                \"version\": \"1.1.1\",\n                \"resources\": [\n                    {\n                    \"name\": \"source-archive\",\n                    \"type\": \"application/zip\",\n                    \"checksum\": \"\\(checksum)\"\n                    }\n                ],\n                \"metadata\": {\n                    \"description\": \"One thing links to another.\"\n                }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let fingerprintStorage = MockPackageFingerprintStorage()\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            customArchiverProvider: { fileSystem in\n                MockArchiver(handler: { _, from, to, callback in\n                    let data = try fileSystem.readFileContents(from)\n                    #expect(data == emptyZipFile)\n\n                    let packagePath = to.appending(\"package\")\n                    try fileSystem.createDirectory(packagePath, recursive: true)\n                    try fileSystem.writeFileContents(packagePath.appending(\"Package.swift\"), string: \"\")\n                    callback(.success(()))\n                })\n            },\n            delegate: .none,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = AbsolutePath(\"/LinkedList-1.1.1\")\n\n        try await registryClient.downloadSourceArchive(\n            package: identity,\n            version: version,\n            fileSystem: fileSystem,\n            destinationPath: path\n        )\n\n        let contents = try fileSystem.getDirectoryContents(path)\n        // TODO: check metadata\n        #expect(contents.sorted() == [RegistryReleaseMetadataStorage.fileName, \"Package.swift\"].sorted())\n    }\n\n    @Test func handles404() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: downloadURL,\n            errorCode: 404,\n            errorDescription: \"not found\"\n        )\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [],\n                    \"metadata\": {}\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                return try await serverErrorHandler.handle(request: request, progress: nil)\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: .none,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            delegate: .none,\n            checksumAlgorithm: MockHashAlgorithm()\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = AbsolutePath(\"/LinkedList-1.1.1\")\n\n        await #expect {\n            try await registryClient.downloadSourceArchive(\n                package: identity,\n                version: version,\n                fileSystem: fileSystem,\n                destinationPath: path\n            )\n        } throws: { error in\n            if case RegistryError\n                .failedDownloadingSourceArchive(\n                    registry: configuration.defaultRegistry!,\n                    package: identity,\n                    version: version,\n                    error: RegistryError.packageVersionNotFound\n                ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesServerError() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: downloadURL,\n            errorCode: Int.random(in: 405 ..< 500),\n            errorDescription: UUID().uuidString\n        )\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [],\n                    \"metadata\": {}\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                return try await serverErrorHandler.handle(request: request, progress: nil)\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: .none,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            delegate: .none,\n            checksumAlgorithm: MockHashAlgorithm()\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = AbsolutePath(\"/LinkedList-1.1.1\")\n\n        await #expect {\n            try await registryClient.downloadSourceArchive(\n                package: identity,\n                version: version,\n                fileSystem: fileSystem,\n                destinationPath: path\n            )\n        } throws: { error in\n            if case RegistryError\n                .failedDownloadingSourceArchive(\n                    registry: configuration.defaultRegistry!,\n                    package: identity,\n                    version: version,\n                    error: RegistryError.serverError(code: serverErrorHandler.errorCode, details: serverErrorHandler.errorDescription)\n                ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesRegistryNotAvailable() async throws {\n        let serverErrorHandler = UnavailableServerErrorHandler(registryURL: registryURL)\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: .none,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            delegate: .none,\n            checksumAlgorithm: MockHashAlgorithm()\n        )\n\n        let fileSystem = InMemoryFileSystem()\n        let path = AbsolutePath(\"/LinkedList-1.1.1\")\n\n        await #expect {\n            try await registryClient.downloadSourceArchive(\n                package: identity,\n                version: version,\n                fileSystem: fileSystem,\n                destinationPath: path\n            )\n        } throws: { error in\n            if case RegistryError.registryNotAvailable(registry) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func downloadSourceArchiveWithSymlinks() async throws {\n        let checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n        let checksum = checksumAlgorithm.hash(emptyZipFile).hexadecimalRepresentation\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.kind, request.method, request.url) {\n            case (.generic, .get, metadataURL):\n                let data = \"\"\"\n                {\n                    \"id\": \"\\(identity)\",\n                    \"version\": \"\\(version)\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"author\": {\n                            \"name\": \"Test Author\"\n                        },\n                        \"description\": \"Test package with symlinks\"\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            case (.download(let fileSystem, let path), .get, downloadURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+zip\")\n\n                let data = Data(emptyZipFile.contents)\n                try! fileSystem.writeFileContents(path, data: data)\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/zip\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                        .init(\n                            name: \"Content-Disposition\",\n                            value: \"attachment; filename=\\\"\\(identity)-\\(version).zip\\\"\"\n                        ),\n                        .init(\n                            name: \"Digest\",\n                            value: \"sha-256=bc6c9a5d2f2226cfa1ef4fad8344b10e1cc2e82960f468f70d9ed696d26b3283\"\n                        ),\n                    ]),\n                    body: nil\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.security = .testDefault\n\n        let fileSystem = localFileSystem\n        let tmpDir = try fileSystem.tempDirectory.appending(component: UUID().uuidString)\n        try fileSystem.createDirectory(tmpDir, recursive: true)\n        defer {\n            try? fileSystem.removeFileTree(tmpDir)\n        }\n\n        let registryClient = RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: .none,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            customHTTPClient: httpClient,\n            customArchiverProvider: { fileSystem in\n                MockArchiver(handler: { _, from, to, callback in\n                    let data = try fileSystem.readFileContents(from)\n                    #expect(data == emptyZipFile)\n\n                    let packagePath = to.appending(component: \"package\")\n                    try fileSystem.createDirectory(packagePath, recursive: true)\n\n                    let targetFile = packagePath.appending(component: \"AFile.swift\")\n                    try fileSystem.writeFileContents(targetFile, string: \"// Target file content\\n\")\n\n                    let symlink = packagePath.appending(component: \"ZLinkToFile.swift\")\n                    try fileSystem.createSymbolicLink(symlink, pointingAt: targetFile, relative: true)\n\n                    // Also create Package.swift\n                    try fileSystem.writeFileContents(packagePath.appending(component: \"Package.swift\"), string: \"// Package manifest\\n\")\n\n                    callback(.success(()))\n                })\n            },\n            delegate: .none,\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        let path = tmpDir.appending(component: \"\\(identity)-\\(version)\")\n\n        try await registryClient.downloadSourceArchive(\n            package: identity,\n            version: version,\n            fileSystem: fileSystem,\n            destinationPath: path\n        )\n\n        let contents = try fileSystem.getDirectoryContents(path).sorted()\n        #expect(contents.contains(\"AFile.swift\"), \"Regular file AFile.swift should exist\")\n        #expect(contents.contains(\"ZLinkToFile.swift\"), \"Symlink ZLinkToFile.swift should exist\")\n        #expect(contents.contains(\"Package.swift\"), \"Package.swift should exist\")\n        #expect(contents.contains(RegistryReleaseMetadataStorage.fileName), \"Metadata file should exist\")\n\n        let symlinkPath = path.appending(component: \"ZLinkToFile.swift\")\n        let regularFilePath = path.appending(component: \"AFile.swift\")\n\n        let regularFileContent: String = try fileSystem.readFileContents(regularFilePath)\n        let symlinkContent: String = try fileSystem.readFileContents(symlinkPath)\n        #expect(symlinkContent == regularFileContent, \"Symlink should have same content as target file\")\n    }\n}\n\n@Suite(\"Lookup Identities\") struct LookupIdentities {\n    @Test func lookupIdentities() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, identifiersURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = #\"\"\"\n                {\n                    \"identifiers\": [\n                    \"mona.LinkedList\"\n                    ]\n                }\n                \"\"\"#.data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        let identities = try await registryClient.lookupIdentities(scmURL: packageURL)\n        #expect([PackageIdentity.plain(\"mona.LinkedList\")] == identities)\n\n        let syncIdentities = try await withCheckedThrowingContinuation { continuation in\n            registryClient.lookupIdentities(\n                scmURL: packageURL,\n                observabilityScope: ObservabilitySystem.NOOP,\n                callbackQueue: .sharedConcurrent,\n                completion: { continuation.resume(with: $0) }\n            )\n        }\n        #expect([PackageIdentity.plain(\"mona.LinkedList\")] == syncIdentities)\n    }\n\n    @Test func notFound() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, identifiersURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n                return .notFound()\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        let identities = try await registryClient.lookupIdentities(scmURL: packageURL)\n        #expect([] == identities)\n    }\n\n    @Test func handleServerError() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: identifiersURL,\n            errorCode: Int.random(in: 405 ..< 500), // avoid 404 since it is not considered an error\n            errorDescription: UUID().uuidString\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n        await #expect {\n            try await registryClient.lookupIdentities(scmURL: packageURL)\n        } throws: { error in\n            if case RegistryError.failedIdentityLookup(\n                registry: configuration.defaultRegistry!,\n                scmURL: packageURL,\n                error: RegistryError.serverError(code: serverErrorHandler.errorCode, details: serverErrorHandler.errorDescription)\n            ) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func requestAuthorization_token() async throws {\n        let token = \"top-sekret\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, identifiersURL):\n                #expect(request.headers.get(\"Authorization\").first == \"Bearer \\(token)\")\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = #\"\"\"\n                {\n                    \"identifiers\": [\n                    \"mona.LinkedList\"\n                    ]\n                }\n                \"\"\"#.data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.registryAuthentication[registryURL.host!] = .init(type: .token)\n\n        let authorizationProvider = TestProvider(map: [registryURL.host!: (\"token\", token)])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            authorizationProvider: authorizationProvider\n        )\n        let identities = try await registryClient.lookupIdentities(scmURL: packageURL)\n        #expect([PackageIdentity.plain(\"mona.LinkedList\")] == identities)\n    }\n\n    @Test func requestAuthorization_basic() async throws {\n        let user = \"jappleseed\"\n        let password = \"top-sekret\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, identifiersURL):\n                #expect(request.headers.get(\"Authorization\").first == \"Basic \\(Data(\"\\(user):\\(password)\".utf8).base64EncodedString())\")\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n\n                let data = #\"\"\"\n                {\n                    \"identifiers\": [\n                    \"mona.LinkedList\"\n                    ]\n                }\n                \"\"\"#.data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.registryAuthentication[registryURL.host!] = .init(type: .basic)\n\n        let authorizationProvider = TestProvider(map: [registryURL.host!: (user, password)])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            authorizationProvider: authorizationProvider\n        )\n        let identities = try await registryClient.lookupIdentities(scmURL: packageURL)\n        #expect([PackageIdentity.plain(\"mona.LinkedList\")] == identities)\n    }\n}\n\n@Suite(\"Login\") struct Login {\n    @Test func login() async throws {\n        let loginURL = URL(\"\\(registryURL)/login\")\n\n        let token = \"top-sekret\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.post, loginURL):\n                #expect(request.headers.get(\"Authorization\").first == \"Bearer \\(token)\")\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ])\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.registryAuthentication[registryURL.host!] = .init(type: .token)\n\n        let authorizationProvider = TestProvider(map: [registryURL.host!: (\"token\", token)])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            authorizationProvider: authorizationProvider\n        )\n        try await registryClient.login(loginURL: loginURL)\n\n        try await withCheckedThrowingContinuation { continuation in\n            registryClient.login(\n                loginURL: loginURL,\n                observabilityScope: ObservabilitySystem.NOOP,\n                callbackQueue: .sharedConcurrent,\n                completion: { continuation.resume(with: $0) }\n            )\n        }\n    }\n\n    @Test func handlesMissingCredentials() async throws {\n        let loginURL = URL(\"\\(registryURL)/login\")\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.post, loginURL):\n                #expect(request.headers.get(\"Authorization\").first == nil)\n\n                return .init(\n                    statusCode: 401,\n                    headers: .init([\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ])\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient\n        )\n\n        await #expect {\n            try await registryClient.login(loginURL: loginURL)\n        } throws: { error in\n            if case RegistryError.loginFailed(_, _) = error {\n                return true\n            }\n            return false\n        }\n    }\n\n    @Test func handlesAuthenticationMethodNotSupported() async throws {\n        let loginURL = URL(\"\\(registryURL)/login\")\n\n        let token = \"top-sekret\"\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.post, loginURL):\n                #expect(request.headers.get(\"Authorization\").first != nil)\n\n                return .init(\n                    statusCode: 501,\n                    headers: .init([\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ])\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        configuration.registryAuthentication[registryURL.host!] = .init(type: .token)\n\n        let authorizationProvider = TestProvider(map: [registryURL.host!: (\"token\", token)])\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            authorizationProvider: authorizationProvider\n        )\n\n        await #expect {\n            try await registryClient.login(loginURL: loginURL)\n        } throws: { error in\n            if case RegistryError.loginFailed = error {\n                return true\n            }\n            return false\n        }\n    }\n}\n\n@Suite(\"Registry Publishing\") struct RegistryPublishing {\n    @Test func publishSync() async throws {\n        let expectedLocation =\n        URL(\"https://\\(registryURL)/packages\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)\")\n\n        let archiveContent = UUID().uuidString\n        let metadataContent = UUID().uuidString\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.put, publishURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n                #expect(request.headers.get(\"X-Swift-Package-Signature-Format\").first == nil)\n\n                // TODO: implement multipart form parsing\n                let body = String(decoding: request.body!, as: UTF8.self)\n                XCTAssertMatch(body, .contains(archiveContent))\n                XCTAssertMatch(body, .contains(metadataContent))\n\n                return .init(\n                    statusCode: 201,\n                    headers: .init([\n                        .init(name: \"Location\", value: expectedLocation.absoluteString),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: .none\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        try await withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(\"\\(identity)-\\(version).zip\")\n            try localFileSystem.writeFileContents(archivePath, string: archiveContent)\n\n            let metadataPath = temporaryDirectory.appending(\"\\(identity)-\\(version)-metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, string: metadataContent)\n\n            let httpClient = HTTPClient(implementation: handler)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n\n            let result = try await withCheckedThrowingContinuation { continuation in\n                return registryClient.publish(\n                    registryURL: registryURL,\n                    packageIdentity: identity,\n                    packageVersion: version,\n                    packageArchive: archivePath,\n                    packageMetadata: metadataPath,\n                    signature: .none,\n                    metadataSignature: .none,\n                    signatureFormat: .none,\n                    fileSystem: localFileSystem,\n                    observabilityScope: ObservabilitySystem.NOOP,\n                    callbackQueue: .sharedConcurrent\n                ) { result in continuation.resume(with: result) }\n            }\n\n            #expect(result == .published(expectedLocation))\n        }\n    }\n\n    @Test func publishAsync() async throws {\n        let expectedLocation =\n        URL(\"https://\\(registryURL)/status\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)\")\n        let expectedRetry = Int.random(in: 10 ..< 100)\n\n        let archiveContent = UUID().uuidString\n        let metadataContent = UUID().uuidString\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.put, publishURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n                #expect(request.headers.get(\"X-Swift-Package-Signature-Format\").first == nil)\n\n                // TODO: implement multipart form parsing\n                let body = String(decoding: request.body!, as: UTF8.self)\n                XCTAssertMatch(body, .contains(archiveContent))\n                XCTAssertMatch(body, .contains(metadataContent))\n\n                return .init(\n                    statusCode: 202,\n                    headers: .init([\n                        .init(name: \"Location\", value: expectedLocation.absoluteString),\n                        .init(name: \"Retry-After\", value: expectedRetry.description),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: .none\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        try await withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(\"\\(identity)-\\(version).zip\")\n            try localFileSystem.writeFileContents(archivePath, string: archiveContent)\n\n            let metadataPath = temporaryDirectory.appending(\"\\(identity)-\\(version)-metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, string: metadataContent)\n\n            let httpClient = HTTPClient(implementation: handler)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n            let result = try await registryClient.publish(\n                registryURL: registryURL,\n                packageIdentity: identity,\n                packageVersion: version,\n                packageArchive: archivePath,\n                packageMetadata: metadataPath,\n                signature: .none,\n                metadataSignature: .none,\n                signatureFormat: .none,\n                fileSystem: localFileSystem\n            )\n\n            #expect(result == .processing(statusURL: expectedLocation, retryAfter: expectedRetry))\n        }\n    }\n\n    @Test func publishWithSignature() async throws {\n        let expectedLocation =\n        URL(\"https://\\(registryURL)/packages\\(identity.registry!.scope)/\\(identity.registry!.name)/\\(version)\")\n\n        let archiveContent = UUID().uuidString\n        let metadataContent = UUID().uuidString\n        let signature = UUID().uuidString\n        let metadataSignature = UUID().uuidString\n        let signatureFormat = SignatureFormat.cms_1_0_0\n\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.put, publishURL):\n                #expect(request.headers.get(\"Accept\").first == \"application/vnd.swift.registry.v1+json\")\n                #expect(request.headers.get(\"X-Swift-Package-Signature-Format\").first == signatureFormat.rawValue)\n\n                // TODO: implement multipart form parsing\n                let body = String(decoding: request.body!, as: UTF8.self)\n                XCTAssertMatch(body, .contains(archiveContent))\n                XCTAssertMatch(body, .contains(metadataContent))\n                XCTAssertMatch(body, .contains(signature))\n                XCTAssertMatch(body, .contains(metadataSignature))\n\n                return .init(\n                    statusCode: 201,\n                    headers: .init([\n                        .init(name: \"Location\", value: expectedLocation.absoluteString),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: .none\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        try await withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(component: \"\\(identity)-\\(version).zip\")\n            try localFileSystem.writeFileContents(archivePath, string: archiveContent)\n\n            let metadataPath = temporaryDirectory.appending(component: \"\\(identity)-\\(version)-metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, string: metadataContent)\n\n            let httpClient = HTTPClient(implementation: handler)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n            let result = try await registryClient.publish(\n                registryURL: registryURL,\n                packageIdentity: identity,\n                packageVersion: version,\n                packageArchive: archivePath,\n                packageMetadata: metadataPath,\n                signature: Array(signature.utf8),\n                metadataSignature: Array(metadataSignature.utf8),\n                signatureFormat: signatureFormat,\n                fileSystem: localFileSystem\n            )\n\n            #expect(result == .published(expectedLocation))\n        }\n    }\n\n    @Test func validateSignatureFormatIsRequiredIfSigned() throws {\n        let archiveContent = UUID().uuidString\n        let metadataContent = UUID().uuidString\n        let signature = UUID().uuidString\n        let metadataSignature = UUID().uuidString\n\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"should not be called\")\n        }\n\n        try withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(component: \"\\(identity)-\\(version).zip\")\n            try localFileSystem.writeFileContents(archivePath, string: archiveContent)\n\n            let metadataPath = temporaryDirectory.appending(component: \"\\(identity)-\\(version)-metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, string: metadataContent)\n\n            let httpClient = HTTPClient(implementation: handler)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n            await #expect {\n                try await registryClient.publish(\n                    registryURL: registryURL,\n                    packageIdentity: identity,\n                    packageVersion: version,\n                    packageArchive: archivePath,\n                    packageMetadata: metadataPath,\n                    signature: Array(signature.utf8),\n                    metadataSignature: Array(metadataSignature.utf8),\n                    signatureFormat: .none,\n                    fileSystem: localFileSystem\n                )\n            } throws: { error in\n                if case RegistryError.missingSignatureFormat = error {\n                    return true\n                }\n                return false\n            }\n        }\n    }\n\n    @Test func validateMetadataSignatureIsRequiredIfArchiveSigned() throws {\n        let archiveContent = UUID().uuidString\n        let metadataContent = UUID().uuidString\n        let signature = UUID().uuidString\n        let signatureFormat = SignatureFormat.cms_1_0_0\n\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"should not be called\")\n        }\n\n        try withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(component: \"\\(identity)-\\(version).zip\")\n            try localFileSystem.writeFileContents(archivePath, string: archiveContent)\n\n            let metadataPath = temporaryDirectory.appending(component: \"\\(identity)-\\(version)-metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, string: metadataContent)\n\n            let httpClient = HTTPClient(implementation: handler)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n            await #expect {\n                try await registryClient.publish(\n                    registryURL: registryURL,\n                    packageIdentity: identity,\n                    packageVersion: version,\n                    packageArchive: archivePath,\n                    packageMetadata: metadataPath,\n                    signature: Array(signature.utf8),\n                    metadataSignature: .none,\n                    signatureFormat: signatureFormat,\n                    fileSystem: localFileSystem\n                )\n            } throws: { error in\n                if case RegistryError.invalidSignature = error {\n                    return true\n                }\n                return false\n            }\n        }\n    }\n\n    @Test func validateArchiveSignatureIsRequiredIfMetadataSigned() throws {\n        let archiveContent = UUID().uuidString\n        let metadataContent = UUID().uuidString\n        let metadataSignature = UUID().uuidString\n        let signatureFormat = SignatureFormat.cms_1_0_0\n\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"should not be called\")\n        }\n\n        try withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(component: \"\\(identity)-\\(version).zip\")\n            try localFileSystem.writeFileContents(archivePath, string: archiveContent)\n\n            let metadataPath = temporaryDirectory.appending(component: \"\\(identity)-\\(version)-metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, string: metadataContent)\n\n            let httpClient = HTTPClient(implementation: handler)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n            await #expect {\n                try await registryClient.publish(\n                    registryURL: registryURL,\n                    packageIdentity: identity,\n                    packageVersion: version,\n                    packageArchive: archivePath,\n                    packageMetadata: metadataPath,\n                    signature: .none,\n                    metadataSignature: Array(metadataSignature.utf8),\n                    signatureFormat: signatureFormat,\n                    fileSystem: localFileSystem\n                )\n            } throws: { error in\n                if case RegistryError.invalidSignature = error {\n                    return true\n                }\n                return false\n            }\n        }\n    }\n\n    @Test func handlesServerError() throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .put,\n            url: publishURL,\n            errorCode: Int.random(in: 405 ..< 500),\n            errorDescription: UUID().uuidString\n        )\n\n        try withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(\"\\(identity)-\\(version).zip\")\n            try localFileSystem.writeFileContents(archivePath, bytes: [])\n\n            let metadataPath = temporaryDirectory.appending(\"\\(identity)-\\(version)-metadata.json\")\n            try localFileSystem.writeFileContents(metadataPath, bytes: [])\n\n            let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n            await #expect {\n                try await registryClient.publish(\n                    registryURL: registryURL,\n                    packageIdentity: identity,\n                    packageVersion: version,\n                    packageArchive: archivePath,\n                    packageMetadata: metadataPath,\n                    signature: .none,\n                    metadataSignature: .none,\n                    signatureFormat: .none,\n                    fileSystem: localFileSystem\n                )\n            } throws: { error in\n                if case RegistryError\n                    .failedPublishing(\n                        RegistryError\n                            .serverError(\n                                code: serverErrorHandler.errorCode,\n                                details: serverErrorHandler.errorDescription\n                            )\n                    ) = error {\n                    return true\n                }\n                return false\n            }\n        }\n    }\n\n    @Test func handlesInvalidArchive() throws {\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"should not be called\")\n        }\n\n        try withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(\"\\(identity)-\\(version).zip\")\n            // try localFileSystem.writeFileContents(archivePath, bytes: [])\n\n            let metadataPath = temporaryDirectory.appending(\"\\(identity)-\\(version)-metadata.json\")\n\n            let httpClient = HTTPClient(implementation: handler)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            await #expect {\n                try await makeRegistryClient(configuration: configuration, httpClient: httpClient).publish(\n                    registryURL: registryURL,\n                    packageIdentity: identity,\n                    packageVersion: version,\n                    packageArchive: archivePath,\n                    packageMetadata: metadataPath,\n                    signature: .none,\n                    metadataSignature: .none,\n                    signatureFormat: .none,\n                    fileSystem: localFileSystem\n                )\n            } throws: { error in\n                if case RegistryError.failedLoadingPackageArchive(archivePath) = error {\n                    return true\n                }\n                return false\n            }\n        }\n    }\n\n    @Test func handlesInvalidMetadata() throws {\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"should not be called\")\n        }\n\n        try withTemporaryDirectory { temporaryDirectory in\n            let archivePath = temporaryDirectory.appending(\"\\(identity)-\\(version).zip\")\n            try localFileSystem.writeFileContents(archivePath, bytes: [])\n\n            let metadataPath = temporaryDirectory.appending(\"\\(identity)-\\(version)-metadata.json\")\n\n            let httpClient = HTTPClient(implementation: handler)\n            var configuration = RegistryConfiguration()\n            configuration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n\n            let registryClient = makeRegistryClient(configuration: configuration, httpClient: httpClient)\n            await #expect {\n                try await registryClient.publish(\n                    registryURL: registryURL,\n                    packageIdentity: identity,\n                    packageVersion: version,\n                    packageArchive: archivePath,\n                    packageMetadata: metadataPath,\n                    signature: .none,\n                    metadataSignature: .none,\n                    signatureFormat: .none,\n                    fileSystem: localFileSystem\n                )\n            } throws: { error in\n                if case RegistryError.failedLoadingPackageMetadata(metadataPath) = error {\n                    return true\n                }\n                return false\n            }\n        }\n    }\n}\n\n@Suite(\"Registry Availablility\") struct RegistryAvailability {\n    @Test func checkAvailability() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, availabilityURL):\n                return .okay()\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n\n        let registryClient = makeRegistryClient(\n            configuration: .init(),\n            httpClient: httpClient\n        )\n\n        let status = try await registryClient.checkAvailability(registry: registry)\n        #expect(status == .available)\n\n        let syncStatus = try await withCheckedThrowingContinuation { continuation in\n            registryClient.checkAvailability(\n                registry: registry,\n                observabilityScope: ObservabilitySystem.NOOP,\n                callbackQueue: .sharedConcurrent,\n                completion: { continuation.resume(with: $0) }\n            )\n        }\n        #expect(syncStatus == .available)\n    }\n\n    @Test func handleNotAvailable() async throws {\n        for unavailableStatus in RegistryClient.AvailabilityStatus.unavailableStatusCodes {\n            let handler: HTTPClient.Implementation = { request, _ in\n                switch (request.method, request.url) {\n                case (.get, availabilityURL):\n                    return .init(statusCode: unavailableStatus)\n                default:\n                    throw StringError(\"method and url should match\")\n                }\n            }\n\n            let httpClient = HTTPClient(implementation: handler)\n            let registry = Registry(url: registryURL, supportsAvailability: true)\n\n            let registryClient = makeRegistryClient(\n                configuration: .init(),\n                httpClient: httpClient\n            )\n\n            let status = try await registryClient.checkAvailability(registry: registry)\n            #expect(status == .unavailable)\n        }\n    }\n\n    @Test func handleServerError() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, availabilityURL):\n                return .serverError(reason: \"boom\")\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n\n        let registryClient = makeRegistryClient(\n            configuration: .init(),\n            httpClient: httpClient\n        )\n\n        let status = try await registryClient.checkAvailability(registry: registry)\n        #expect(status == .error(\"unknown server error (500)\"))\n    }\n\n    @Test func handleMethodNotSupported() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, availabilityURL):\n                return .serverError(reason: \"boom\")\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: false)\n\n        let registryClient = makeRegistryClient(\n            configuration: .init(),\n            httpClient: httpClient\n        )\n\n        await #expect(throws: StringError(\"registry \\(registry.url) does not support availability checks.\")) {\n            try await registryClient.checkAvailability(registry: registry)\n        }\n    }\n\n    @Test func withAvailabilityCheck() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, availabilityURL):\n                return .okay()\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n\n        let registryClient = makeRegistryClient(\n            configuration: .init(),\n            httpClient: httpClient\n        )\n\n        try await registryClient.withAvailabilityCheck(\n            registry: registry,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    @Test func withAvailabilityCheckServerError() async throws {\n        let handler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.get, availabilityURL):\n                return .serverError(reason: \"boom\")\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n\n        let registryClient = makeRegistryClient(\n            configuration: .init(),\n            httpClient: httpClient\n        )\n\n        await #expect(throws: StringError(\"unknown server error (500)\")) {\n            try await registryClient.withAvailabilityCheck(\n                registry: registry,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n        }\n    }\n\n    @Test func withAvailabilityCheckInCache() async throws {\n        let counter = SendableBox(0)\n        let handler: HTTPClient.Implementation = { request, _ in\n            await counter.increment()\n            switch (request.method, request.url) {\n            case (.get, availabilityURL):\n                return .okay()\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        let registry = Registry(url: registryURL, supportsAvailability: true)\n\n        let registryClient = makeRegistryClient(\n            configuration: .init(),\n            httpClient: httpClient\n        )\n\n        // Request count should not increase after first check\n        for _ in 0..<5 {\n            try await registryClient.withAvailabilityCheck(\n                registry: registry,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            let count = await counter.value\n            #expect(count == 1)\n        }\n    }\n}\n\n// MARK: - Sugar\n\nextension RegistryClient {\n    fileprivate func getPackageMetadata(package: PackageIdentity) async throws -> RegistryClient.PackageMetadata {\n        try await self.getPackageMetadata(\n            package: package,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    func getPackageVersionMetadata(\n        package: PackageIdentity,\n        version: Version\n    ) async throws -> PackageVersionMetadata {\n        try await self.getPackageVersionMetadata(\n            package: package,\n            version: version,\n            fileSystem: InMemoryFileSystem(),\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    func getPackageVersionMetadata(\n        package: PackageIdentity.RegistryIdentity,\n        version: Version\n    ) async throws -> PackageVersionMetadata {\n        return try await self.getPackageVersionMetadata(\n            package: package.underlying,\n            version: version,\n            fileSystem: InMemoryFileSystem(),\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func downloadSourceArchive(\n        package: PackageIdentity,\n        version: Version,\n        fileSystem: FileSystem,\n        destinationPath: AbsolutePath,\n        observabilityScope: ObservabilityScope = ObservabilitySystem.NOOP\n    ) async throws {\n        try await self.downloadSourceArchive(\n            package: package,\n            version: version,\n            destinationPath: destinationPath,\n            progressHandler: .none,\n            fileSystem: fileSystem,\n            observabilityScope: observabilityScope\n        )\n    }\n\n    fileprivate func lookupIdentities(scmURL: SourceControlURL) async throws -> Set<PackageIdentity> {\n        try await self.lookupIdentities(\n            scmURL: scmURL,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func getManifestContent(\n        package: PackageIdentity,\n        version: Version,\n        customToolsVersion: ToolsVersion?\n    ) async throws -> String {\n        try await self.getManifestContent(\n            package: package,\n            version: version,\n            customToolsVersion: customToolsVersion,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func login(loginURL: URL) async throws {\n        try await self.login(\n            loginURL: loginURL,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    func publish(\n        registryURL: URL,\n        packageIdentity: PackageIdentity,\n        packageVersion: Version,\n        packageArchive: AbsolutePath,\n        packageMetadata: AbsolutePath?,\n        signature: [UInt8]?,\n        metadataSignature: [UInt8]?,\n        signatureFormat: SignatureFormat?,\n        fileSystem: FileSystem\n    ) async throws -> RegistryClient.PublishResult {\n        try await self.publish(\n            registryURL: registryURL,\n            packageIdentity: packageIdentity,\n            packageVersion: packageVersion,\n            packageArchive: packageArchive,\n            packageMetadata: packageMetadata,\n            signature: signature,\n            metadataSignature: metadataSignature,\n            signatureFormat: signatureFormat,\n            fileSystem: fileSystem,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    func checkAvailability(registry: Registry) async throws -> AvailabilityStatus {\n        try await self.checkAvailability(\n            registry: registry,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n}\n\nfunc makeRegistryClient(\n    configuration: RegistryConfiguration,\n    httpClient: HTTPClient,\n    authorizationProvider: AuthorizationProvider? = .none,\n    fingerprintStorage: PackageFingerprintStorage = MockPackageFingerprintStorage(),\n    fingerprintCheckingMode: FingerprintCheckingMode = .strict,\n    skipSignatureValidation: Bool = false,\n    signingEntityStorage: PackageSigningEntityStorage = MockPackageSigningEntityStorage(),\n    signingEntityCheckingMode: SigningEntityCheckingMode = .strict,\n    checksumAlgorithm: HashAlgorithm = MockHashAlgorithm()\n) -> RegistryClient {\n    RegistryClient(\n        configuration: configuration,\n        fingerprintStorage: fingerprintStorage,\n        fingerprintCheckingMode: fingerprintCheckingMode,\n        skipSignatureValidation: skipSignatureValidation,\n        signingEntityStorage: signingEntityStorage,\n        signingEntityCheckingMode: signingEntityCheckingMode,\n        authorizationProvider: authorizationProvider,\n        customHTTPClient: httpClient,\n        customArchiverProvider: { _ in MockArchiver() },\n        delegate: .none,\n        checksumAlgorithm: checksumAlgorithm\n    )\n}\n\nprivate struct TestProvider: AuthorizationProvider {\n    let map: [String: (user: String, password: String)]\n\n    func authentication(for url: URL) -> (user: String, password: String)? {\n        self.map[url.host!]\n    }\n}\n\nstruct ServerErrorHandler {\n    let method: HTTPMethod\n    let url: URL\n    let errorCode: Int\n    let errorDescription: String\n\n    init(\n        method: HTTPMethod,\n        url: URL,\n        errorCode: Int,\n        errorDescription: String\n    ) {\n        self.method = method\n        self.url = url\n        self.errorCode = errorCode\n        self.errorDescription = errorDescription\n    }\n\n    @Sendable func handle(\n        request: HTTPClient.Request,\n        progress: HTTPClient.ProgressHandler?\n    ) async throws -> HTTPClient.Response {\n        let data = \"\"\"\n        {\n            \"detail\": \"\\(self.errorDescription)\"\n        }\n        \"\"\".data(using: .utf8)!\n\n        if request.method == self.method &&\n            request.url == self.url\n        {\n            return .init(\n                statusCode: self.errorCode,\n                headers: .init([\n                    .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                    .init(name: \"Content-Type\", value: \"application/problem+json\"),\n                    .init(name: \"Content-Version\", value: \"1\"),\n                ]),\n                body: data\n            )\n        } else {\n            throw StringError(\"unexpected request\")\n        }\n    }\n}\n\nstruct UnavailableServerErrorHandler {\n    let registryURL: URL\n    init(registryURL: URL) {\n        self.registryURL = registryURL\n    }\n\n    @Sendable func handle(\n        request: HTTPClient.Request,\n        progress: HTTPClient.ProgressHandler?\n    ) async throws -> HTTPClient.Response {\n        if request.method == .get && request.url == URL(\"\\(self.registryURL)/availability\") {\n            return .init(\n                statusCode: RegistryClient.AvailabilityStatus.unavailableStatusCodes.first!\n            )\n        } else {\n            throw StringError(\"unexpected request\")\n        }\n    }\n}\n\nprivate func manifestContent(toolsVersion: ToolsVersion?) -> String {\n    \"\"\"\n    // swift-tools-version:\\(toolsVersion ?? ToolsVersion.current)\n\n    import PackageDescription\n\n    let package = Package()\n    \"\"\"\n}\n"
  },
  {
    "path": "Tests/PackageRegistryTests/RegistryConfigurationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport PackageModel\nimport PackageRegistry\nimport _InternalTestSupport\nimport XCTest\n\nprivate let defaultRegistryBaseURL = URL(\"https://packages.example.com/\")\nprivate let customRegistryBaseURL = URL(\"https://custom.packages.example.com/\")\n\nfinal class RegistryConfigurationTests: XCTestCase {\n    let encoder = JSONEncoder()\n    let decoder = JSONDecoder()\n\n    func testEmptyConfiguration() throws {\n        let configuration = RegistryConfiguration()\n        XCTAssertNil(configuration.defaultRegistry)\n        XCTAssertEqual(configuration.scopedRegistries, [:])\n        XCTAssertEqual(configuration.registryAuthentication, [:])\n        XCTAssertNil(configuration.security)\n    }\n\n    func testRoundTripCodingForEmptyConfiguration() throws {\n        let configuration = RegistryConfiguration()\n\n        let encoded = try encoder.encode(configuration)\n        let decoded = try decoder.decode(RegistryConfiguration.self, from: encoded)\n\n        XCTAssertEqual(configuration, decoded)\n    }\n\n    func testRoundTripCodingForExampleConfiguration() throws {\n        var configuration = RegistryConfiguration()\n\n        configuration.defaultRegistry = .init(url: defaultRegistryBaseURL, supportsAvailability: false)\n        configuration.scopedRegistries[\"foo\"] = .init(url: customRegistryBaseURL, supportsAvailability: false)\n        configuration.scopedRegistries[\"bar\"] = .init(url: customRegistryBaseURL, supportsAvailability: false)\n\n        configuration.registryAuthentication[defaultRegistryBaseURL.host!] = .init(type: .token)\n\n        var security = RegistryConfiguration.Security()\n        // default\n        var global = RegistryConfiguration.Security.Global()\n        global.signing = RegistryConfiguration.Security.Signing()\n        global.signing?.onUnsigned = .error\n        global.signing?.onUntrustedCertificate = .error\n        global.signing?.trustedRootCertificatesPath = \"/shared/roots\"\n        global.signing?.includeDefaultTrustedRootCertificates = false\n        global.signing?.validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n        global.signing?.validationChecks?.certificateExpiration = .enabled\n        global.signing?.validationChecks?.certificateRevocation = .strict\n        security.default = global\n        // registryOverrides\n        var registryOverride = RegistryConfiguration.Security.RegistryOverride()\n        registryOverride.signing = RegistryConfiguration.Security.Signing()\n        registryOverride.signing?.onUnsigned = .silentAllow\n        registryOverride.signing?.onUntrustedCertificate = .silentAllow\n        registryOverride.signing?.trustedRootCertificatesPath = \"/foo/roots\"\n        registryOverride.signing?.includeDefaultTrustedRootCertificates = false\n        registryOverride.signing?.validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n        registryOverride.signing?.validationChecks?.certificateExpiration = .enabled\n        registryOverride.signing?.validationChecks?.certificateRevocation = .allowSoftFail\n        security.registryOverrides[\"foo.com\"] = registryOverride\n        // scopeOverrides\n        let scope = try PackageIdentity.Scope(validating: \"mona\")\n        var scopeOverride = RegistryConfiguration.Security.ScopePackageOverride()\n        scopeOverride.signing = RegistryConfiguration.Security.ScopePackageOverride.Signing()\n        scopeOverride.signing?.trustedRootCertificatesPath = \"/mona/roots\"\n        scopeOverride.signing?.includeDefaultTrustedRootCertificates = false\n        security.scopeOverrides[scope] = scopeOverride\n        // packageOverrides\n        let packageIdentity = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        var packageOverride = RegistryConfiguration.Security.ScopePackageOverride()\n        packageOverride.signing = RegistryConfiguration.Security.ScopePackageOverride.Signing()\n        packageOverride.signing?.trustedRootCertificatesPath = \"/mona/LinkedList/roots\"\n        packageOverride.signing?.includeDefaultTrustedRootCertificates = false\n        security.packageOverrides[packageIdentity] = packageOverride\n        configuration.security = security\n\n        let encoded = try encoder.encode(configuration)\n        let decoded = try decoder.decode(RegistryConfiguration.self, from: encoded)\n\n        XCTAssertEqual(configuration, decoded)\n    }\n\n    func testDecodeEmptyConfiguration() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"authentication\": {},\n            \"security\": {},\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n        XCTAssertNil(configuration.defaultRegistry)\n        XCTAssertEqual(configuration.scopedRegistries, [:])\n        XCTAssertEqual(configuration.registryAuthentication, [:])\n        XCTAssertEqual(configuration.security, RegistryConfiguration.Security())\n    }\n\n    func testDecodeEmptyConfigurationWithMissingKeys() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n        XCTAssertNil(configuration.defaultRegistry)\n        XCTAssertEqual(configuration.scopedRegistries, [:])\n        XCTAssertEqual(configuration.registryAuthentication, [:])\n        XCTAssertNil(configuration.security)\n    }\n\n    func testDecodeExampleConfiguration() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {\n                \"[default]\": {\n                    \"url\": \"\\#(defaultRegistryBaseURL)\"\n                },\n                \"foo\": {\n                    \"url\": \"\\#(customRegistryBaseURL)\"\n                },\n                \"bar\": {\n                    \"url\": \"\\#(customRegistryBaseURL)\"\n                }\n            },\n            \"authentication\": {\n                \"packages.example.com\": {\n                    \"type\": \"basic\",\n                    \"loginAPIPath\": \"/v1/login\"\n                }\n            },\n            \"security\": {\n                \"default\": {\n                    \"signing\": {\n                        \"onUnsigned\": \"error\",\n                        \"onUntrustedCertificate\": \"error\",\n                        \"trustedRootCertificatesPath\": \"~/.swiftpm/security/trusted-root-certs/\",\n                        \"includeDefaultTrustedRootCertificates\": true,\n                        \"validationChecks\": {\n                            \"certificateExpiration\": \"disabled\",\n                            \"certificateRevocation\": \"disabled\"\n                        }\n                    }\n                },\n                \"registryOverrides\": {\n                    \"packages.example.com\": {\n                        \"signing\": {\n                            \"onUnsigned\": \"warn\",\n                            \"onUntrustedCertificate\": \"warn\",\n                            \"trustedRootCertificatesPath\": \"/foo/roots\",\n                            \"includeDefaultTrustedRootCertificates\": false,\n                            \"validationChecks\": {\n                                \"certificateExpiration\": \"enabled\",\n                                \"certificateRevocation\": \"allowSoftFail\"\n                            }\n                        }\n                    }\n                },\n                \"scopeOverrides\": {\n                    \"mona\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/mona/roots\",\n                            \"includeDefaultTrustedRootCertificates\": false\n                        }\n                    }\n                },\n                \"packageOverrides\": {\n                    \"mona.LinkedList\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/mona/LinkedList/roots\",\n                            \"includeDefaultTrustedRootCertificates\": false\n                        }\n                    }\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n        XCTAssertEqual(configuration.defaultRegistry?.url, defaultRegistryBaseURL)\n        XCTAssertEqual(configuration.scopedRegistries[\"foo\"]?.url, customRegistryBaseURL)\n        XCTAssertEqual(configuration.scopedRegistries[\"bar\"]?.url, customRegistryBaseURL)\n        XCTAssertEqual(configuration.registryAuthentication[\"packages.example.com\"]?.type, .basic)\n        XCTAssertEqual(configuration.registryAuthentication[\"packages.example.com\"]?.loginAPIPath, \"/v1/login\")\n        XCTAssertEqual(configuration.security?.default.signing?.onUnsigned, .error)\n        XCTAssertEqual(configuration.security?.default.signing?.onUntrustedCertificate, .error)\n        XCTAssertEqual(\n            configuration.security?.default.signing?.trustedRootCertificatesPath,\n            \"~/.swiftpm/security/trusted-root-certs/\"\n        )\n        XCTAssertEqual(configuration.security?.default.signing?.includeDefaultTrustedRootCertificates, true)\n        XCTAssertEqual(configuration.security?.default.signing?.validationChecks?.certificateExpiration, .disabled)\n        XCTAssertEqual(configuration.security?.default.signing?.validationChecks?.certificateRevocation, .disabled)\n        XCTAssertEqual(configuration.security?.registryOverrides[\"packages.example.com\"]?.signing?.onUnsigned, .warn)\n        XCTAssertEqual(\n            configuration.security?.registryOverrides[\"packages.example.com\"]?.signing?.onUntrustedCertificate,\n            .warn\n        )\n        XCTAssertEqual(\n            configuration.security?.registryOverrides[\"packages.example.com\"]?.signing?.trustedRootCertificatesPath,\n            \"/foo/roots\"\n        )\n        XCTAssertEqual(\n            configuration.security?.registryOverrides[\"packages.example.com\"]?.signing?\n                .includeDefaultTrustedRootCertificates,\n            false\n        )\n        XCTAssertEqual(\n            configuration.security?.registryOverrides[\"packages.example.com\"]?.signing?.validationChecks?\n                .certificateExpiration,\n            .enabled\n        )\n        XCTAssertEqual(\n            configuration.security?.registryOverrides[\"packages.example.com\"]?.signing?.validationChecks?\n                .certificateRevocation,\n            .allowSoftFail\n        )\n        XCTAssertEqual(\n            configuration.security?.scopeOverrides[PackageIdentity.Scope(stringLiteral: \"mona\")]?.signing?\n                .trustedRootCertificatesPath,\n            \"/mona/roots\"\n        )\n        XCTAssertEqual(\n            configuration.security?.scopeOverrides[PackageIdentity.Scope(stringLiteral: \"mona\")]?.signing?\n                .includeDefaultTrustedRootCertificates,\n            false\n        )\n        XCTAssertEqual(\n            configuration.security?.packageOverrides[PackageIdentity.plain(\"mona.LinkedList\").registry!]?.signing?\n                .trustedRootCertificatesPath,\n            \"/mona/LinkedList/roots\"\n        )\n        XCTAssertEqual(\n            configuration.security?.packageOverrides[PackageIdentity.plain(\"mona.LinkedList\").registry!]?.signing?\n                .includeDefaultTrustedRootCertificates,\n            false\n        )\n    }\n\n    func testDecodeConfigurationWithInvalidRegistryKey() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {\n                0: \"\\#(customRegistryBaseURL)\"\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        XCTAssertThrowsError(try self.decoder.decode(RegistryConfiguration.self, from: json))\n    }\n\n    func testDecodeConfigurationWithInvalidRegistryValue() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {\n                \"[default]\": \"\\#(customRegistryBaseURL)\"\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        XCTAssertThrowsError(try self.decoder.decode(RegistryConfiguration.self, from: json))\n    }\n\n    func testDecodeConfigurationWithInvalidAuthenticationType() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"authentication\": {\n                \"packages.example.com\": {\n                    \"type\": \"foobar\"\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        XCTAssertThrowsError(try self.decoder.decode(RegistryConfiguration.self, from: json))\n    }\n\n    func testDecodeConfigurationWithMissingVersion() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {}\n        }\n        \"\"\"#\n\n        XCTAssertThrowsError(try self.decoder.decode(RegistryConfiguration.self, from: json))\n    }\n\n    func testDecodeSecurityConfigurationWithInvalidScopeKey() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"authentication\": {\n                \"packages.example.com\": {\n                    \"type\": \"foobar\"\n                }\n            },\n            \"security\": {\n                \"scopeOverrides\": {\n                  \"mona.\": {\n                    \"signing\": {\n                      \"trustedRootCertificatesPath\": \"/mona/roots\",\n                      \"includeDefaultTrustedRootCertificates\": false\n                    }\n                  }\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        XCTAssertThrowsError(try self.decoder.decode(RegistryConfiguration.self, from: json))\n    }\n\n    func testDecodeSecurityConfigurationWithInvalidPackageKey() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"authentication\": {\n                \"packages.example.com\": {\n                    \"type\": \"foobar\"\n                }\n            },\n            \"security\": {\n                \"packageOverrides\": {\n                  \"LinkedList\": {\n                    \"signing\": {\n                      \"trustedRootCertificatesPath\": \"/mona/LinkedList/roots\",\n                      \"includeDefaultTrustedRootCertificates\": false\n                    }\n                  }\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        XCTAssertThrowsError(try self.decoder.decode(RegistryConfiguration.self, from: json))\n    }\n\n    func testDecodeConfigurationWithInvalidVersion() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"version\": 999\n        }\n        \"\"\"#\n\n        XCTAssertThrowsError(try self.decoder.decode(RegistryConfiguration.self, from: json))\n    }\n\n    func testGetAuthenticationConfigurationByRegistryURL() throws {\n        var configuration = RegistryConfiguration()\n        try configuration.add(authentication: .init(type: .token), for: defaultRegistryBaseURL)\n\n        XCTAssertEqual(try configuration.authentication(for: defaultRegistryBaseURL)?.type, .token)\n        XCTAssertNil(try configuration.authentication(for: customRegistryBaseURL))\n    }\n\n    func testGetSigning_noOverrides() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let registry = Registry(url: \"https://packages.example.com\", supportsAvailability: false)\n        let signing = configuration.signing(for: package, registry: registry)\n\n        XCTAssertEqual(signing.onUnsigned, .warn)\n        XCTAssertEqual(signing.onUntrustedCertificate, .warn)\n        XCTAssertNil(signing.trustedRootCertificatesPath)\n        XCTAssertEqual(signing.includeDefaultTrustedRootCertificates, true)\n        XCTAssertEqual(signing.validationChecks?.certificateExpiration, .disabled)\n        XCTAssertEqual(signing.validationChecks?.certificateRevocation, .disabled)\n    }\n\n    func testGetSigning_globalOverride() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"security\": {\n                \"default\": {\n                    \"signing\": {\n                        \"onUnsigned\": \"error\",\n                        \"trustedRootCertificatesPath\": \"/custom/roots\",\n                        \"validationChecks\": {\n                            \"certificateExpiration\": \"enabled\"\n                        }\n                    }\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let registry = Registry(url: \"https://packages.example.com\", supportsAvailability: false)\n        let signing = configuration.signing(for: package, registry: registry)\n\n        XCTAssertEqual(signing.onUnsigned, .error)\n        XCTAssertEqual(signing.onUntrustedCertificate, .warn)\n        XCTAssertEqual(signing.trustedRootCertificatesPath, \"/custom/roots\")\n        XCTAssertEqual(signing.includeDefaultTrustedRootCertificates, true)\n        XCTAssertEqual(signing.validationChecks?.certificateExpiration, .enabled)\n        XCTAssertEqual(signing.validationChecks?.certificateRevocation, .disabled)\n    }\n\n    func testGetSigning_registryOverride() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"security\": {\n                \"registryOverrides\": {\n                    \"packages.example.com\": {\n                        \"signing\": {\n                            \"onUntrustedCertificate\": \"warn\",\n                            \"trustedRootCertificatesPath\": \"/foo/roots\",\n                            \"validationChecks\": {\n                                \"certificateRevocation\": \"allowSoftFail\"\n                            }\n                        }\n                    },\n                    \"other.example.com\": {\n                        \"signing\": {\n                            \"onUntrustedCertificate\": \"error\"\n                        }\n                    }\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let registry = Registry(url: \"https://packages.example.com\", supportsAvailability: false)\n        let signing = configuration.signing(for: package, registry: registry)\n\n        XCTAssertEqual(signing.onUnsigned, .warn)\n        XCTAssertEqual(signing.onUntrustedCertificate, .warn)\n        XCTAssertEqual(signing.trustedRootCertificatesPath, \"/foo/roots\")\n        XCTAssertEqual(signing.includeDefaultTrustedRootCertificates, true)\n        XCTAssertEqual(signing.validationChecks?.certificateExpiration, .disabled)\n        XCTAssertEqual(signing.validationChecks?.certificateRevocation, .allowSoftFail)\n    }\n\n    func testGetSigning_scopeOverride() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"security\": {\n                \"scopeOverrides\": {\n                    \"mona\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/mona/roots\"\n                        }\n                    },\n                    \"foo\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/foo/roots\"\n                        }\n                    }\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let registry = Registry(url: \"https://packages.example.com\", supportsAvailability: false)\n        let signing = configuration.signing(for: package, registry: registry)\n\n        XCTAssertEqual(signing.onUnsigned, .warn)\n        XCTAssertEqual(signing.onUntrustedCertificate, .warn)\n        XCTAssertEqual(signing.trustedRootCertificatesPath, \"/mona/roots\")\n        XCTAssertEqual(signing.includeDefaultTrustedRootCertificates, true)\n        XCTAssertEqual(signing.validationChecks?.certificateExpiration, .disabled)\n        XCTAssertEqual(signing.validationChecks?.certificateRevocation, .disabled)\n    }\n\n    func testGetSigning_packageOverride() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"security\": {\n                \"packageOverrides\": {\n                    \"mona.LinkedList\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/mona/linkedlist/roots\"\n                        }\n                    },\n                    \"foo.bar\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/foo/bar/roots\"\n                        }\n                    }\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        let registry = Registry(url: \"https://packages.example.com\", supportsAvailability: false)\n        let signing = configuration.signing(for: package, registry: registry)\n\n        XCTAssertEqual(signing.onUnsigned, .warn)\n        XCTAssertEqual(signing.onUntrustedCertificate, .warn)\n        XCTAssertEqual(signing.trustedRootCertificatesPath, \"/mona/linkedlist/roots\")\n        XCTAssertEqual(signing.includeDefaultTrustedRootCertificates, true)\n        XCTAssertEqual(signing.validationChecks?.certificateExpiration, .disabled)\n        XCTAssertEqual(signing.validationChecks?.certificateRevocation, .disabled)\n    }\n\n    func testGetSigning_multipleOverrides() throws {\n        let json = #\"\"\"\n        {\n            \"registries\": {},\n            \"security\": {\n                \"default\": {\n                    \"signing\": {\n                        \"trustedRootCertificatesPath\": \"/custom/roots\"\n                    }\n                },\n                \"registryOverrides\": {\n                    \"packages.example.com\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/foo/roots\"\n                        }\n                    }\n                },\n                \"scopeOverrides\": {\n                    \"mona\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/mona/roots\"\n                        }\n                    }\n                },\n                \"packageOverrides\": {\n                    \"mona.LinkedList\": {\n                        \"signing\": {\n                            \"trustedRootCertificatesPath\": \"/mona/linkedlist/roots\"\n                        }\n                    }\n                }\n            },\n            \"version\": 1\n        }\n        \"\"\"#\n\n        let configuration = try decoder.decode(RegistryConfiguration.self, from: json)\n\n        // Package override wins\n        var package = PackageIdentity.plain(\"mona.LinkedList\").registry!\n        var registry = Registry(url: \"https://packages.example.com\", supportsAvailability: false)\n        var signing = configuration.signing(for: package, registry: registry)\n        XCTAssertEqual(signing.trustedRootCertificatesPath, \"/mona/linkedlist/roots\")\n\n        // No package override, closest match is scope override\n        package = PackageIdentity.plain(\"mona.Trie\").registry!\n        registry = Registry(url: \"https://packages.example.com\", supportsAvailability: false)\n        signing = configuration.signing(for: package, registry: registry)\n        XCTAssertEqual(signing.trustedRootCertificatesPath, \"/mona/roots\")\n\n        // No package override, closest match is registry override\n        package = PackageIdentity.plain(\"foo.bar\").registry!\n        registry = Registry(url: \"https://packages.example.com\", supportsAvailability: false)\n        signing = configuration.signing(for: package, registry: registry)\n        XCTAssertEqual(signing.trustedRootCertificatesPath, \"/foo/roots\")\n\n        // Global override\n        package = PackageIdentity.plain(\"foo.bar\").registry!\n        registry = Registry(url: \"https://other.example.com\", supportsAvailability: false)\n        signing = configuration.signing(for: package, registry: registry)\n        XCTAssertEqual(signing.trustedRootCertificatesPath, \"/custom/roots\")\n    }\n}\n"
  },
  {
    "path": "Tests/PackageRegistryTests/RegistryDownloadsManagerTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport PackageModel\nimport PackageLoading\n@testable import PackageRegistry\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCUtility.Version\n\nfinal class RegistryDownloadsManagerTests: XCTestCase {\n    func testNoCache() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let fs = InMemoryFileSystem()\n\n        let registry = MockRegistry(\n            filesystem: fs,\n            identityResolver: DefaultIdentityResolver(),\n            checksumAlgorithm: MockHashAlgorithm(),\n            fingerprintStorage: MockPackageFingerprintStorage(),\n            signingEntityStorage: MockPackageSigningEntityStorage()\n        )\n\n        let package: PackageIdentity = .plain(\"test.\\(UUID().uuidString)\")\n        let packageVersion: Version = \"1.0.0\"\n        let packageSource = InMemoryRegistryPackageSource(fileSystem: fs, path: .root.appending(components: \"registry\", \"server\", package.description))\n        try packageSource.writePackageContent()\n\n        registry.addPackage(\n            identity: package,\n            versions: [packageVersion],\n            source: packageSource\n        )\n\n        let delegate = MockRegistryDownloadsManagerDelegate()\n        let downloadsPath = AbsolutePath.root.appending(components: \"registry\", \"downloads\")\n        let manager = RegistryDownloadsManager(\n            fileSystem: fs,\n            path: downloadsPath,\n            cachePath: .none, // cache disabled\n            registryClient: registry.registryClient,\n            delegate: delegate\n        )\n\n        // try to get a package\n\n        do {\n            delegate.prepare(fetchExpected: true)\n            let path = try await manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))\n            XCTAssertTrue(fs.isDirectory(path))\n\n            try delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, 1)\n            XCTAssertEqual(delegate.willFetch.first?.packageVersion, .init(package: package, version: packageVersion))\n            XCTAssertEqual(delegate.willFetch.first?.fetchDetails, .init(fromCache: false, updatedCache: false))\n\n            XCTAssertEqual(delegate.didFetch.count, 1)\n            XCTAssertEqual(delegate.didFetch.first?.packageVersion, .init(package: package, version: packageVersion))\n            XCTAssertEqual(try! delegate.didFetch.first?.result.get(), .init(fromCache: false, updatedCache: false))\n        }\n\n        // try to get a package that does not exist\n\n        let unknownPackage: PackageIdentity = .plain(\"unknown.\\(UUID().uuidString)\")\n        let unknownPackageVersion: Version = \"1.0.0\"\n\n        do {\n            delegate.prepare(fetchExpected: true)\n            await XCTAssertAsyncThrowsError(try await manager.lookup(package: unknownPackage, version: unknownPackageVersion, observabilityScope: observability.topScope)) { error in\n                XCTAssertNotNil(error as? RegistryError)\n            }\n\n            try delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.map { ($0.packageVersion) },\n                           [\n                            (PackageVersion(package: package, version: packageVersion)),\n                            (PackageVersion(package: unknownPackage, version: unknownPackageVersion))\n                           ]\n            )\n            XCTAssertEqual(delegate.didFetch.map { ($0.packageVersion) },\n                           [\n                            (PackageVersion(package: package, version: packageVersion)),\n                            (PackageVersion(package: unknownPackage, version: unknownPackageVersion))\n                           ]\n            )\n        }\n\n        // try to get the existing package again, no fetching expected this time\n\n        do {\n            delegate.prepare(fetchExpected: false)\n            let path = try await manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))\n            XCTAssertTrue(fs.isDirectory(path))\n\n            try delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.map { ($0.packageVersion) },\n                           [\n                            (PackageVersion(package: package, version: packageVersion)),\n                            (PackageVersion(package: unknownPackage, version: unknownPackageVersion))\n                           ]\n            )\n            XCTAssertEqual(delegate.didFetch.map { ($0.packageVersion) },\n                           [\n                            (PackageVersion(package: package, version: packageVersion)),\n                            (PackageVersion(package: unknownPackage, version: unknownPackageVersion))\n                           ]\n            )\n        }\n\n        // remove the package\n\n        do {\n            try manager.remove(package: package)\n\n            delegate.prepare(fetchExpected: true)\n            let path = try await manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))\n            XCTAssertTrue(fs.isDirectory(path))\n\n            try delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.map { ($0.packageVersion) },\n                           [\n                            (PackageVersion(package: package, version: packageVersion)),\n                            (PackageVersion(package: unknownPackage, version: unknownPackageVersion)),\n                            (PackageVersion(package: package, version: packageVersion))\n                           ]\n            )\n            XCTAssertEqual(delegate.didFetch.map { ($0.packageVersion) },\n                           [\n                            (PackageVersion(package: package, version: packageVersion)),\n                            (PackageVersion(package: unknownPackage, version: unknownPackageVersion)),\n                            (PackageVersion(package: package, version: packageVersion))\n                           ]\n            )\n        }\n    }\n\n    func testCache() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let fs = InMemoryFileSystem()\n\n        let registry = MockRegistry(\n            filesystem: fs,\n            identityResolver: DefaultIdentityResolver(),\n            checksumAlgorithm: MockHashAlgorithm(),\n            fingerprintStorage: MockPackageFingerprintStorage(),\n            signingEntityStorage: MockPackageSigningEntityStorage()\n        )\n\n        let package: PackageIdentity = .plain(\"test.\\(UUID().uuidString)\")\n        let packageVersion: Version = \"1.0.0\"\n        let packageSource = InMemoryRegistryPackageSource(fileSystem: fs, path: .root.appending(components: \"registry\", \"server\", package.description))\n        try packageSource.writePackageContent()\n\n        registry.addPackage(\n            identity: package,\n            versions: [packageVersion],\n            source: packageSource\n        )\n\n        let delegate = MockRegistryDownloadsManagerDelegate()\n        let downloadsPath = AbsolutePath.root.appending(components: \"registry\", \"downloads\")\n        let cachePath = AbsolutePath.root.appending(components: \"registry\", \"cache\")\n        let manager = RegistryDownloadsManager(\n            fileSystem: fs,\n            path: downloadsPath,\n            cachePath: cachePath, // cache enabled\n            registryClient: registry.registryClient,\n            delegate: delegate\n        )\n\n        // try to get a package\n\n        do {\n            delegate.prepare(fetchExpected: true)\n            let path = try await manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))\n            XCTAssertTrue(fs.isDirectory(path))\n            XCTAssertTrue(fs.isDirectory(cachePath.appending(components: package.registry!.scope.description, package.registry!.name.description, packageVersion.description)))\n\n            try delegate.wait(timeout: .now() + 2)\n\n            XCTAssertEqual(delegate.willFetch.count, 1)\n            XCTAssertEqual(delegate.willFetch.first?.packageVersion, .init(package: package, version: packageVersion))\n            XCTAssertEqual(delegate.willFetch.first?.fetchDetails, .init(fromCache: false, updatedCache: false))\n\n            XCTAssertEqual(delegate.didFetch.count, 1)\n            XCTAssertEqual(delegate.didFetch.first?.packageVersion, .init(package: package, version: packageVersion))\n            XCTAssertEqual(try! delegate.didFetch.first?.result.get(), .init(fromCache: true, updatedCache: true))\n        }\n\n        // remove the \"local\" package, should come from cache\n\n        do {\n            try manager.remove(package: package)\n\n            delegate.prepare(fetchExpected: true)\n            let path = try await manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))\n            XCTAssertTrue(fs.isDirectory(path))\n\n            try delegate.wait(timeout: .now() + 2)\n\n            XCTAssertEqual(delegate.willFetch.count, 2)\n            XCTAssertEqual(delegate.willFetch.last?.packageVersion, .init(package: package, version: packageVersion))\n            XCTAssertEqual(delegate.willFetch.last?.fetchDetails, .init(fromCache: true, updatedCache: false))\n\n            XCTAssertEqual(delegate.didFetch.count, 2)\n            XCTAssertEqual(delegate.didFetch.last?.packageVersion, .init(package: package, version: packageVersion))\n            XCTAssertEqual(try! delegate.didFetch.last?.result.get(), .init(fromCache: true, updatedCache: false))\n        }\n\n        // remove the \"local\" package, and purge cache\n\n        do {\n            try manager.remove(package: package)\n            manager.purgeCache(observabilityScope: observability.topScope)\n\n            delegate.prepare(fetchExpected: true)\n            let path = try await manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertEqual(path, try downloadsPath.appending(package.downloadPath(version: packageVersion)))\n            XCTAssertTrue(fs.isDirectory(path))\n\n            try delegate.wait(timeout: .now() + 2)\n\n            XCTAssertEqual(delegate.willFetch.count, 3)\n            XCTAssertEqual(delegate.willFetch.last?.packageVersion, .init(package: package, version: packageVersion))\n            XCTAssertEqual(delegate.willFetch.last?.fetchDetails, .init(fromCache: false, updatedCache: false))\n\n            XCTAssertEqual(delegate.didFetch.count, 3)\n            XCTAssertEqual(delegate.didFetch.last?.packageVersion, .init(package: package, version: packageVersion))\n            XCTAssertEqual(try! delegate.didFetch.last?.result.get(), .init(fromCache: true, updatedCache: true))\n        }\n    }\n\n    func testConcurrency() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let fs = InMemoryFileSystem()\n\n        let registry = MockRegistry(\n            filesystem: fs,\n            identityResolver: DefaultIdentityResolver(),\n            checksumAlgorithm: MockHashAlgorithm(),\n            fingerprintStorage: MockPackageFingerprintStorage(),\n            signingEntityStorage: MockPackageSigningEntityStorage()\n        )\n\n        let downloadsPath = AbsolutePath.root.appending(components: \"registry\", \"downloads\")\n        let delegate = MockRegistryDownloadsManagerDelegate()\n        let manager = RegistryDownloadsManager(\n            fileSystem: fs,\n            path: downloadsPath,\n            cachePath: .none, // cache disabled\n            registryClient: registry.registryClient,\n            delegate: delegate\n        )\n\n        // many different versions\n\n        do {\n            let concurrency = 100\n            let package: PackageIdentity = .plain(\"test.\\(UUID().uuidString)\")\n            let packageVersions = (0 ..< concurrency).map { Version($0, 0 , 0) }\n            let packageSource = InMemoryRegistryPackageSource(fileSystem: fs, path: .root.appending(components: \"registry\", \"server\", package.description))\n            try packageSource.writePackageContent()\n\n            registry.addPackage(\n                identity: package,\n                versions: packageVersions,\n                source: packageSource\n            )\n\n            let results = ThreadSafeKeyValueStore<Version, AbsolutePath>()\n            try await withThrowingTaskGroup(of: Void.self) { group in\n                for packageVersion in packageVersions {\n                    group.addTask {\n                        delegate.prepare(fetchExpected: true)\n                        results[packageVersion] = try await manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)\n                    }\n                }\n                try await group.waitForAll()\n            }\n\n            try delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, concurrency)\n            XCTAssertEqual(delegate.didFetch.count, concurrency)\n\n            XCTAssertEqual(results.count, concurrency)\n            for packageVersion in packageVersions {\n                let expectedPath = try downloadsPath.appending(package.downloadPath(version: packageVersion))\n                XCTAssertEqual(results[packageVersion], expectedPath)\n            }\n        }\n\n        // same versions\n\n        do {\n            let concurrency = 1000\n            let repeatRatio = 10\n            let package: PackageIdentity = .plain(\"test.\\(UUID().uuidString)\")\n            let packageVersions = (0 ..< concurrency / 10).map { Version($0, 0 , 0) }\n            let packageSource = InMemoryRegistryPackageSource(fileSystem: fs, path: .root.appending(components: \"registry\", \"server\", package.description))\n            try packageSource.writePackageContent()\n\n            registry.addPackage(\n                identity: package,\n                versions: packageVersions,\n                source: packageSource\n            )\n\n            delegate.reset()\n            let results = ThreadSafeKeyValueStore<Version, AbsolutePath>()\n            try await withThrowingTaskGroup(of: Void.self) { group in\n                for index in 0 ..< concurrency {\n                    group.addTask {\n                        delegate.prepare(fetchExpected: index < concurrency / repeatRatio)\n                        let packageVersion = Version(index % (concurrency / repeatRatio), 0 , 0)\n                        results[packageVersion] = try await manager.lookup(package: package, version: packageVersion, observabilityScope: observability.topScope)\n                    }\n                }\n                try await group.waitForAll()\n            }\n\n            try delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, concurrency / repeatRatio)\n            XCTAssertEqual(delegate.didFetch.count, concurrency / repeatRatio)\n\n            XCTAssertEqual(results.count, concurrency / repeatRatio)\n            for packageVersion in packageVersions {\n                let expectedPath = try downloadsPath.appending(package.downloadPath(version: packageVersion))\n                XCTAssertEqual(results[packageVersion], expectedPath)\n            }\n        }\n    }\n}\n\nprivate final class MockRegistryDownloadsManagerDelegate: RegistryDownloadsManagerDelegate, @unchecked Sendable {\n    private var _willFetch = [(packageVersion: PackageVersion, fetchDetails: RegistryDownloadsManager.FetchDetails)]()\n    private var _didFetch = [(packageVersion: PackageVersion, result: Result<RegistryDownloadsManager.FetchDetails, Error>)]()\n\n    private let lock = NSLock()\n    private var group = DispatchGroup()\n\n    public func prepare(fetchExpected: Bool) {\n        if fetchExpected {\n            group.enter() // will fetch\n            group.enter() // did fetch\n        }\n    }\n\n    public func reset() {\n        self.group = DispatchGroup()\n        self._willFetch = []\n        self._didFetch = []\n    }\n\n    public func wait(timeout: DispatchTime) throws {\n        switch group.wait(timeout: timeout) {\n        case .success:\n            return\n        case .timedOut:\n            throw StringError(\"timeout\")\n        }\n    }\n\n    var willFetch: [(packageVersion: PackageVersion, fetchDetails: RegistryDownloadsManager.FetchDetails)] {\n        return self.lock.withLock { _willFetch }\n    }\n\n    var didFetch: [(packageVersion: PackageVersion, result: Result<RegistryDownloadsManager.FetchDetails, Error>)] {\n        return self.lock.withLock { _didFetch }\n    }\n\n    func willFetch(package: PackageIdentity, version: Version, fetchDetails: RegistryDownloadsManager.FetchDetails) {\n        self.lock.withLock {\n            _willFetch += [(PackageVersion(package: package, version: version), fetchDetails: fetchDetails)]\n        }\n        self.group.leave()\n    }\n\n    func didFetch(package: PackageIdentity, version: Version, result: Result<RegistryDownloadsManager.FetchDetails, Error>, duration: DispatchTimeInterval) {\n        self.lock.withLock {\n            _didFetch += [(PackageVersion(package: package, version: version), result: result)]\n        }\n        self.group.leave()\n    }\n\n    func fetching(package: PackageIdentity, version: Version, bytesDownloaded downloaded: Int64, totalBytesToDownload total: Int64?) {\n    }\n}\n\nfileprivate struct PackageVersion: Hashable, Equatable, Sendable {\n    let package: PackageIdentity\n    let version: Version\n}\n"
  },
  {
    "path": "Tests/PackageRegistryTests/SignatureValidationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageModel\n@testable import PackageRegistry\nimport PackageSigning\nimport _InternalTestSupport\nimport X509 // FIXME: need this import or else SwiftSigningIdentity init crashes\nimport XCTest\n\nimport struct TSCUtility.Version\n\nfinal class SignatureValidationTests: XCTestCase {\n    private static let unsignedManifest = \"\"\"\n    // swift-tools-version: 5.7\n\n    import PackageDescription\n    let package = Package(\n        name: \"library\",\n        products: [ .library(name: \"library\", targets: [\"library\"]) ],\n        targets: [ .target(name: \"library\") ]\n    )\n    \"\"\"\n\n    let registryURL = URL(\"https://packages.example.com\")\n    let identity: PackageIdentity = .plain(\"mona.LinkedList\")\n    var package: PackageIdentity.RegistryIdentity!\n    var metadataURL: URL!\n    let version = Version(\"1.1.1\")\n    let checksum = \"a2ac54cf25fbc1ad0028f03f0aa4b96833b83bb05a14e510892bb27dea4dc812\"\n    let signingEntityStorage = MockPackageSigningEntityStorage()\n    let signingEntityCheckingMode = SigningEntityCheckingMode.strict\n    var registry: Registry!\n\n    override func setUp() {\n        super.setUp()\n        package = identity.registry!\n        metadataURL = URL(\"\\(registryURL)/\\(package.scope)/\\(package.name)/\\(version)\")\n        registry = Registry(url: registryURL, supportsAvailability: false)\n    }\n\n    func testUnsignedPackage_shouldError() async throws {\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .error // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Package is not signed. With onUnsigned = .error,\n        // an error gets thrown.\n        await XCTAssertAsyncThrowsError(\n            try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                content: Data(emptyZipFile.contents),\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        ) { error in\n            guard case RegistryError.sourceArchiveNotSigned = error else {\n                return XCTFail(\"Expected RegistryError.sourceArchiveNotSigned, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testUnsignedPackage_shouldWarn() async throws {\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .warn // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Package is not signed. With onUnsigned = .warn,\n        // no error gets thrown but there should be a warning\n        _ = try await signatureValidation.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            content: Data(emptyZipFile.contents),\n            configuration: configuration.signing(for: package, registry: registry),\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics) { result in\n            let diagnostics = result.check(diagnostic: .contains(\"is not signed\"), severity: .warning)\n            XCTAssertEqual(diagnostics?.metadata?.packageIdentity, package.underlying)\n        }\n    }\n\n    func testUnsignedPackage_shouldPrompt() async throws {\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .prompt // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // prompt returning false\n        do {\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: RejectingSignatureValidationDelegate()\n            )\n\n            // Package is not signed. With onUnsigned = .error,\n            // an error gets thrown.\n            await XCTAssertAsyncThrowsError(\n                try await signatureValidation.validate(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    content: Data(emptyZipFile.contents),\n                    configuration: configuration.signing(for: package, registry: registry)\n                )\n            ) { error in\n                guard case RegistryError.sourceArchiveNotSigned = error else {\n                    return XCTFail(\"Expected RegistryError.sourceArchiveNotSigned, got '\\(error)'\")\n                }\n            }\n        }\n\n        // prompt returning continue\n        do {\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: AcceptingSignatureValidationDelegate()\n            )\n\n            // Package is not signed, signingEntity should be nil\n            let signingEntity = try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                content: Data(emptyZipFile.contents),\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n            XCTAssertNil(signingEntity)\n        }\n    }\n\n    func testFailedToFetchSignature_shouldError() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: metadataURL,\n            errorCode: 404,\n            errorDescription: \"not found\"\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .error // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Failed to fetch package metadata / signature\n        await XCTAssertAsyncThrowsError(\n            try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                content: Data(emptyZipFile.contents),\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        ) { error in\n            guard case RegistryError.failedRetrievingSourceArchiveSignature = error else {\n                return XCTFail(\"Expected RegistryError.failedRetrievingSourceArchiveSignature, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testUnsignedArchiveAndManifest_shouldPrompt() async throws {\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .prompt // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // prompt returning false\n        do {\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: RejectingSignatureValidationDelegate()\n            )\n\n            // Package is not signed. With onUnsigned = .prompt, prompt to continue.\n            await XCTAssertAsyncThrowsError(\n                try await signatureValidation.validate(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    toolsVersion: .none,\n                    manifestContent: Self.unsignedManifest,\n                    configuration: configuration.signing(for: package, registry: registry)\n                )\n            ) { error in\n                guard case RegistryError.sourceArchiveNotSigned = error else {\n                    return XCTFail(\"Expected RegistryError.sourceArchiveNotSigned, got '\\(error)'\")\n                }\n            }\n        }\n\n        // prompt returning continue\n        do {\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: AcceptingSignatureValidationDelegate()\n            )\n\n            // Package is not signed, signingEntity should be nil\n            let signingEntity = try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: .none,\n                manifestContent: Self.unsignedManifest,\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n            XCTAssertNil(signingEntity)\n        }\n    }\n\n    func testUnsignedArchiveAndManifest_nonPrompt() async throws {\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .error // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Package is not signed.\n        // With the exception of .prompt, we log then continue.\n        _ = try await signatureValidation.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: .none,\n            manifestContent: Self.unsignedManifest,\n            configuration: configuration.signing(for: package, registry: registry),\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics, problemsOnly: false) { result in\n            let diagnostics = result.check(diagnostic: .contains(\"is not signed\"), severity: .debug)\n            XCTAssertEqual(diagnostics?.metadata?.packageIdentity, package.underlying)\n        }\n    }\n\n    func testFailedToFetchArchiveSignatureToValidateManifest_diagnostics() async throws {\n        let serverErrorHandler = ServerErrorHandler(\n            method: .get,\n            url: metadataURL,\n            errorCode: 404,\n            errorDescription: \"not found\"\n        )\n\n        let httpClient = HTTPClient(implementation: serverErrorHandler.handle)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Failed to fetch package metadata / signature.\n        // This error is not thrown for manifest but there should be diagnostics.\n        _ = try await signatureValidation.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: .none,\n            manifestContent: Self.unsignedManifest,\n            configuration: configuration.signing(for: package, registry: registry),\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics, problemsOnly: false) { result in\n            result.check(\n                diagnostic: .contains(\n                    \"retrieval of source archive signature for \\(package!) \\(version) from \\(registry!) failed\"\n                ),\n                severity: .debug\n            )\n        }\n    }\n\n    func testSignedArchiveUnsignedManifest() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .error // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Archive is signed, but manifest is not signed\n        await XCTAssertAsyncThrowsError(\n            try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: ToolsVersion.v5_7,\n                manifestContent: Self.unsignedManifest,\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        ) { error in\n            guard case RegistryError.manifestNotSigned(_, _, _, let toolsVersion) = error else {\n                return XCTFail(\"Expected RegistryError.manifestNotSigned, got '\\(error)'\")\n            }\n            XCTAssertEqual(toolsVersion, ToolsVersion.v5_7)\n        }\n    }\n\n    func testSignedArchiveUnknownManifestSignatureFormat() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        let manifestSignatureBytes = try self.sign(\n            content: Array(Self.unsignedManifest.utf8),\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n        let manifestContent = \"\"\"\n        \\(Self.unsignedManifest)\n        // signature: abc-1.0.0;\\(Data(manifestSignatureBytes).base64EncodedString())\n        \"\"\"\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .error // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Archive is signed, but manifest signature format is bad\n        await XCTAssertAsyncThrowsError(\n            try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: .none,\n                manifestContent: manifestContent,\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        ) { error in\n            guard case RegistryError.unknownSignatureFormat = error else {\n                return XCTFail(\"Expected RegistryError.unknownSignatureFormat, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testSignedArchiveMalformedManifestSignature() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        let manifestContent = \"\"\"\n        \\(Self.unsignedManifest)\n        // signature: cms-1.0.0;manifest-signature\n        \"\"\"\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .error // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Archive is signed, but manifest signature is malformed\n        await XCTAssertAsyncThrowsError(\n            try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: .none,\n                manifestContent: manifestContent,\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        ) { error in\n            guard case RegistryError.invalidSignature(let reason) = error else {\n                return XCTFail(\"Expected RegistryError.invalidSignature, got '\\(error)'\")\n            }\n            XCTAssertTrue(reason.contains(\"malformed\"))\n        }\n    }\n\n    #if swift(>=5.5.2)\n    func testSignedPackage_validSignature() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        try await withTemporaryDirectory { temporaryDirectory in\n            // Write test root to trust roots directory\n            let trustRootsDirectoryPath = temporaryDirectory.appending(component: \"trust-roots\")\n            try localFileSystem.createDirectory(trustRootsDirectoryPath)\n            try localFileSystem.writeFileContents(\n                trustRootsDirectoryPath.appending(component: \"test-root.cer\"),\n                bytes: .init(keyAndCertChain.rootCertificate)\n            )\n\n            var signingConfiguration = RegistryConfiguration.Security.Signing()\n            signingConfiguration.trustedRootCertificatesPath = trustRootsDirectoryPath.pathString\n            signingConfiguration.includeDefaultTrustedRootCertificates = false\n            var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n            validationChecks.certificateExpiration = .disabled\n            validationChecks.certificateRevocation = .disabled\n            signingConfiguration.validationChecks = validationChecks\n\n            configuration.security = RegistryConfiguration.Security(\n                default: RegistryConfiguration.Security.Global(\n                    signing: signingConfiguration\n                )\n            )\n\n\n\n            let registryClient = makeRegistryClient(\n                configuration: configuration,\n                httpClient: httpClient,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode\n            )\n\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: RejectingSignatureValidationDelegate()\n            )\n\n            // Package signature is valid\n            _ = try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                content: Data(emptyZipFile.contents),\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        }\n    }\n\n    func testSignedPackage_badSignature() async throws {\n        let signatureBytes = Array(\"bad signature\".utf8)\n        let signatureFormat = SignatureFormat.cms_1_0_0\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: .init()\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Package signature can't be parsed so it is invalid\n        await XCTAssertAsyncThrowsError(\n            try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                content: Data(emptyZipFile.contents),\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        ) { error in\n            guard case RegistryError.invalidSignature = error else {\n                return XCTFail(\"Expected RegistryError.invalidSignature, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testSignedPackage_badSignature_skipSignatureValidation() async throws {\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler: HTTPClient.Implementation = { _, _ in\n            throw StringError(\"unexpected request\")\n        }\n\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: .init()\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: true, // intended for this test, don't change\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Signature is bad, but we are skipping signature\n        // validation, so no error is thrown.\n        _ = try await signatureValidation.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            content: Data(emptyZipFile.contents),\n            configuration: configuration.signing(for: package, registry: registry)\n        )\n    }\n\n    func testSignedPackage_invalidSignature() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: Array(\"other zip archive\".utf8), // signature is not for emptyZipFile but for something else\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        try await withTemporaryDirectory { temporaryDirectory in\n            // Write test root to trust roots directory\n            let trustRootsDirectoryPath = temporaryDirectory.appending(component: \"trust-roots\")\n            try localFileSystem.createDirectory(trustRootsDirectoryPath)\n            try localFileSystem.writeFileContents(\n                trustRootsDirectoryPath.appending(component: \"test-root.cer\"),\n                bytes: .init(keyAndCertChain.rootCertificate)\n            )\n\n            var signingConfiguration = RegistryConfiguration.Security.Signing()\n            signingConfiguration.trustedRootCertificatesPath = trustRootsDirectoryPath.pathString\n            signingConfiguration.includeDefaultTrustedRootCertificates = false\n            var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n            validationChecks.certificateExpiration = .disabled\n            validationChecks.certificateRevocation = .disabled\n            signingConfiguration.validationChecks = validationChecks\n\n            configuration.security = RegistryConfiguration.Security(\n                default: RegistryConfiguration.Security.Global(\n                    signing: signingConfiguration\n                )\n            )\n\n\n\n            let registryClient = makeRegistryClient(\n                configuration: configuration,\n                httpClient: httpClient,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode\n            )\n\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: RejectingSignatureValidationDelegate()\n            )\n\n            // Package signature doesn't match content so it's invalid\n            await XCTAssertAsyncThrowsError(\n                try await signatureValidation.validate(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    content: Data(emptyZipFile.contents),\n                    configuration: configuration.signing(for: package, registry: registry)\n                )\n            ) { error in\n                guard case RegistryError.invalidSignature = error else {\n                    return XCTFail(\"Expected RegistryError.invalidSignature, got '\\(error)'\")\n                }\n            }\n        }\n    }\n\n    func testSignedPackage_certificateNotTrusted_shouldError() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUntrustedCertificate = .error // intended for this test; don't change\n        // Test root not written to trust roots directory\n        signingConfiguration.includeDefaultTrustedRootCertificates = false\n        var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n        validationChecks.certificateExpiration = .disabled\n        validationChecks.certificateRevocation = .disabled\n        signingConfiguration.validationChecks = validationChecks\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Test root not trusted; onUntrustedCertificate is set to .error\n        await XCTAssertAsyncThrowsError(\n            try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                content: Data(emptyZipFile.contents),\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        ) { error in\n            guard case RegistryError.signerNotTrusted = error else {\n                return XCTFail(\"Expected RegistryError.signerNotTrusted, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testSignedPackage_certificateNotTrusted_shouldPrompt() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUntrustedCertificate = .prompt // intended for this test; don't change\n        // Test root not written to trust roots directory\n        signingConfiguration.includeDefaultTrustedRootCertificates = false\n        var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n        validationChecks.certificateExpiration = .disabled\n        validationChecks.certificateRevocation = .disabled\n        signingConfiguration.validationChecks = validationChecks\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // prompt returning false\n        do {\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: RejectingSignatureValidationDelegate()\n            )\n\n            // Test root not trusted; onUntrustedCertificate is set to .prompt\n            await XCTAssertAsyncThrowsError(\n                try await signatureValidation.validate(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    content: Data(emptyZipFile.contents),\n                    configuration: configuration.signing(for: package, registry: registry)\n                )\n            ) { error in\n                guard case RegistryError.signerNotTrusted = error else {\n                    return XCTFail(\"Expected RegistryError.signerNotTrusted, got '\\(error)'\")\n                }\n            }\n        }\n\n        // prompt returning continue\n        do {\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: AcceptingSignatureValidationDelegate()\n            )\n\n            // Package signer is untrusted, signingEntity should be nil\n            let signingEntity = try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                content: Data(emptyZipFile.contents),\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n            XCTAssertNil(signingEntity)\n        }\n    }\n\n    func testSignedPackage_certificateNotTrusted_shouldWarn() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUntrustedCertificate = .warn // intended for this test; don't change\n        // Test root not written to trust roots directory\n        signingConfiguration.includeDefaultTrustedRootCertificates = false\n        var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n        validationChecks.certificateExpiration = .disabled\n        validationChecks.certificateRevocation = .disabled\n        signingConfiguration.validationChecks = validationChecks\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Test root not trusted but onUntrustedCertificate is set to .warn\n        _ = try await signatureValidation.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            content: Data(emptyZipFile.contents),\n            configuration: configuration.signing(for: package, registry: registry),\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics) { result in\n            let diagnostics = result.check(diagnostic: .contains(\"not trusted\"), severity: .warning)\n            XCTAssertEqual(diagnostics?.metadata?.packageIdentity, package.underlying)\n        }\n    }\n\n    func testSignedManifest_validSignature() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        let manifestSignatureBytes = try self.sign(\n            content: Array(Self.unsignedManifest.utf8),\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n        let manifestContent = \"\"\"\n        \\(Self.unsignedManifest)\n        // signature: cms-1.0.0;\\(Data(manifestSignatureBytes).base64EncodedString())\n        \"\"\"\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        try await withTemporaryDirectory { temporaryDirectory in\n            // Write test root to trust roots directory\n            let trustRootsDirectoryPath = temporaryDirectory.appending(component: \"trust-roots\")\n            try localFileSystem.createDirectory(trustRootsDirectoryPath)\n            try localFileSystem.writeFileContents(\n                trustRootsDirectoryPath.appending(component: \"test-root.cer\"),\n                bytes: .init(keyAndCertChain.rootCertificate)\n            )\n\n            var signingConfiguration = RegistryConfiguration.Security.Signing()\n            signingConfiguration.trustedRootCertificatesPath = trustRootsDirectoryPath.pathString\n            signingConfiguration.includeDefaultTrustedRootCertificates = false\n            var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n            validationChecks.certificateExpiration = .disabled\n            validationChecks.certificateRevocation = .disabled\n            signingConfiguration.validationChecks = validationChecks\n\n            configuration.security = RegistryConfiguration.Security(\n                default: RegistryConfiguration.Security.Global(\n                    signing: signingConfiguration\n                )\n            )\n\n\n\n            let registryClient = makeRegistryClient(\n                configuration: configuration,\n                httpClient: httpClient,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode\n            )\n\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: RejectingSignatureValidationDelegate()\n            )\n\n            // Manifest signature is valid\n            _ = try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: .none,\n                manifestContent: manifestContent,\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        }\n    }\n\n    func testSignedManifest_badSignature() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        let manifestContent = \"\"\"\n        \\(Self.unsignedManifest)\n        // signature: cms-1.0.0;\\(Data(Array(\"bad signature\".utf8)).base64EncodedString())\n        \"\"\"\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: .init()\n            )\n        )\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Manifest signature can't be parsed so it is invalid\n        await XCTAssertAsyncThrowsError(\n            try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: .none,\n                manifestContent: manifestContent,\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n        ) { error in\n            guard case RegistryError.invalidSignature = error else {\n                return XCTFail(\"Expected RegistryError.invalidSignature, got '\\(error)'\")\n            }\n        }\n    }\n\n    func testSignedManifest_badSignature_skipSignatureValidation() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        let manifestContent = \"\"\"\n        \\(Self.unsignedManifest)\n        // signature: cms-1.0.0;\\(Data(Array(\"bad signature\".utf8)).base64EncodedString())\n        \"\"\"\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: .init()\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: true, // intended for this test, don't change\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        // Manifest signature is bad, but we are skipping signature\n        // validation, so no error is thrown.\n        _ = try await signatureValidation.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: .none,\n            manifestContent: manifestContent,\n            configuration: configuration.signing(for: package, registry: registry)\n        )\n    }\n\n    func testSignedManifest_invalidSignature() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        let manifestSignatureBytes = try self.sign(\n            content: Array(\"not manifest\".utf8), // signature is not for manifest but for something else\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n        let manifestContent = \"\"\"\n        \\(Self.unsignedManifest)\n        // signature: cms-1.0.0;\\(Data(manifestSignatureBytes).base64EncodedString())\n        \"\"\"\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        try await withTemporaryDirectory { temporaryDirectory in\n            // Write test root to trust roots directory\n            let trustRootsDirectoryPath = temporaryDirectory.appending(component: \"trust-roots\")\n            try localFileSystem.createDirectory(trustRootsDirectoryPath)\n            try localFileSystem.writeFileContents(\n                trustRootsDirectoryPath.appending(component: \"test-root.cer\"),\n                bytes: .init(keyAndCertChain.rootCertificate)\n            )\n\n            var signingConfiguration = RegistryConfiguration.Security.Signing()\n            signingConfiguration.trustedRootCertificatesPath = trustRootsDirectoryPath.pathString\n            signingConfiguration.includeDefaultTrustedRootCertificates = false\n            var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n            validationChecks.certificateExpiration = .disabled\n            validationChecks.certificateRevocation = .disabled\n            signingConfiguration.validationChecks = validationChecks\n\n            configuration.security = RegistryConfiguration.Security(\n                default: RegistryConfiguration.Security.Global(\n                    signing: signingConfiguration\n                )\n            )\n\n\n\n            let registryClient = makeRegistryClient(\n                configuration: configuration,\n                httpClient: httpClient,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode\n            )\n\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: RejectingSignatureValidationDelegate()\n            )\n\n            // Manifest signature doesn't match content so it's invalid\n            await XCTAssertAsyncThrowsError(\n                try await signatureValidation.validate(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    toolsVersion: .none,\n                    manifestContent: manifestContent,\n                    configuration: configuration.signing(for: package, registry: registry)\n                )\n            ) { error in\n                guard case RegistryError.invalidSignature = error else {\n                    return XCTFail(\"Expected RegistryError.invalidSignature, got '\\(error)'\")\n                }\n            }\n        }\n    }\n\n    func testSignedManifest_certificateNotTrusted_shouldPrompt() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        let manifestSignatureBytes = try self.sign(\n            content: Array(Self.unsignedManifest.utf8),\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n        let manifestContent = \"\"\"\n        \\(Self.unsignedManifest)\n        // signature: cms-1.0.0;\\(Data(manifestSignatureBytes).base64EncodedString())\n        \"\"\"\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUntrustedCertificate = .prompt // intended for this test; don't change\n        // Test root not written to trust roots directory\n        signingConfiguration.includeDefaultTrustedRootCertificates = false\n        var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n        validationChecks.certificateExpiration = .disabled\n        validationChecks.certificateRevocation = .disabled\n        signingConfiguration.validationChecks = validationChecks\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        // prompt returning false\n        do {\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: RejectingSignatureValidationDelegate()\n            )\n\n            // Test root not trusted; onUntrustedCertificate is set to .prompt\n            await XCTAssertAsyncThrowsError(\n                try await signatureValidation.validate(\n                    registry: registry,\n                    package: package,\n                    version: version,\n                    toolsVersion: .none,\n                    manifestContent: manifestContent,\n                    configuration: configuration.signing(for: package, registry: registry)\n                )\n            ) { error in\n                guard case RegistryError.signerNotTrusted = error else {\n                    return XCTFail(\"Expected RegistryError.signerNotTrusted, got '\\(error)'\")\n                }\n            }\n        }\n\n        // prompt returning continue\n        do {\n            let signatureValidation = SignatureValidation(\n                skipSignatureValidation: false,\n                signingEntityStorage: signingEntityStorage,\n                signingEntityCheckingMode: signingEntityCheckingMode,\n                versionMetadataProvider: registryClient.getPackageVersionMetadata,\n                delegate: AcceptingSignatureValidationDelegate()\n            )\n\n            // Package signer is not trusted, signingEntity should be nil\n            let signingEntity = try await signatureValidation.validate(\n                registry: registry,\n                package: package,\n                version: version,\n                toolsVersion: .none,\n                manifestContent: manifestContent,\n                configuration: configuration.signing(for: package, registry: registry)\n            )\n            XCTAssertNil(signingEntity)\n        }\n    }\n\n    func testSignedManifest_certificateNotTrusted_nonPrompt() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        let manifestSignatureBytes = try self.sign(\n            content: Array(Self.unsignedManifest.utf8),\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n        let manifestContent = \"\"\"\n        \\(Self.unsignedManifest)\n        // signature: cms-1.0.0;\\(Data(manifestSignatureBytes).base64EncodedString())\n        \"\"\"\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUntrustedCertificate = .error // intended for this test; don't change\n        // Test root not written to trust roots directory\n        signingConfiguration.includeDefaultTrustedRootCertificates = false\n        var validationChecks = RegistryConfiguration.Security.Signing.ValidationChecks()\n        validationChecks.certificateExpiration = .disabled\n        validationChecks.certificateRevocation = .disabled\n        signingConfiguration.validationChecks = validationChecks\n\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Test root not trusted.\n        // With the exception of .prompt, we log then continue.\n        _ = try await signatureValidation.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: .none,\n            manifestContent: manifestContent,\n            configuration: configuration.signing(for: package, registry: registry),\n            observabilityScope: observability.topScope\n        )\n\n        testDiagnostics(observability.diagnostics, problemsOnly: false) { result in\n            let diagnostics = result.check(diagnostic: .contains(\"not trusted\"), severity: .debug)\n            XCTAssertEqual(diagnostics?.metadata?.packageIdentity, package.underlying)\n        }\n    }\n\n    func testSignedManifest_emptyResources() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = try SwiftSigningIdentity(\n            derEncodedCertificate: keyAndCertChain.leafCertificate,\n            derEncodedPrivateKey: keyAndCertChain.privateKey,\n            privateKeyType: .p256\n        )\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signatureBytes = try self.sign(\n            content: emptyZipFile.contents,\n            signingIdentity: signingIdentity,\n            format: signatureFormat\n        )\n\n        // Get metadata endpoint will be called to see if package version is signed\n        let handler = HTTPClient.packageReleaseMetadataAPIHandler(\n            metadataURL: metadataURL,\n            checksum: checksum,\n            signatureBytes: signatureBytes,\n            signatureFormat: signatureFormat,\n            includeResouces: false\n        )\n        let httpClient = HTTPClient(implementation: handler)\n        var configuration = RegistryConfiguration()\n        configuration.defaultRegistry = registry\n\n        var signingConfiguration = RegistryConfiguration.Security.Signing()\n        signingConfiguration.onUnsigned = .error // intended for this test; don't change\n        configuration.security = RegistryConfiguration.Security(\n            default: RegistryConfiguration.Security.Global(\n                signing: signingConfiguration\n            )\n        )\n\n\n        let registryClient = makeRegistryClient(\n            configuration: configuration,\n            httpClient: httpClient,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode\n        )\n\n        let signatureValidation = SignatureValidation(\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            versionMetadataProvider: registryClient.getPackageVersionMetadata,\n            delegate: RejectingSignatureValidationDelegate()\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // Archive is signed, but manifest is not signed\n        let entity = try await signatureValidation.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: ToolsVersion.v5_7,\n            manifestContent: Self.unsignedManifest,\n            configuration: configuration.signing(for: package, registry: registry),\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNil(entity, \"Expected no signing entity\")\n\n        let manifestName = \"Package@swift-\\(ToolsVersion.v5_7).swift\"\n        testDiagnostics(observability.diagnostics, problemsOnly: false) { result in\n            result.check(\n                diagnostic: .contains(\n                    \"cannot determine if \\(manifestName) should be signed because source archive for \\(package!) \\(version) is not found in \\(registry!)\"\n                ),\n                severity: .debug\n            )\n        }\n    }\n    #endif\n\n    private func sign(\n        content: [UInt8],\n        signingIdentity: SigningIdentity,\n        intermediateCertificates: [[UInt8]] = [],\n        format: SignatureFormat = .cms_1_0_0,\n        observabilityScope: ObservabilityScope? = nil\n    ) throws -> [UInt8] {\n        try SignatureProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: intermediateCertificates,\n            format: format,\n            observabilityScope: observabilityScope ?? ObservabilitySystem.NOOP\n        )\n    }\n\n    private func ecSelfSignedTestKeyAndCertChain() throws -> KeyAndCertChain {\n        try fixtureXCTest(name: \"Signing\") { fixturePath in\n            let privateKey = try localFileSystem.readFileContents(\n                fixturePath.appending(components: \"Certificates\", \"Test_ec_self_signed_key.p8\")\n            ).contents\n            let certificate = try localFileSystem.readFileContents(\n                fixturePath.appending(components: \"Certificates\", \"Test_ec_self_signed.cer\")\n            ).contents\n\n            return KeyAndCertChain(\n                privateKey: privateKey,\n                certificateChain: [certificate]\n            )\n        }\n    }\n\n    private struct KeyAndCertChain {\n        let privateKey: [UInt8]\n        let certificateChain: [[UInt8]]\n\n        var leafCertificate: [UInt8] {\n            self.certificateChain.first!\n        }\n\n        var intermediateCertificates: [[UInt8]] {\n            guard self.certificateChain.count > 1 else {\n                return []\n            }\n            return Array(self.certificateChain.dropLast(1)[1...])\n        }\n\n        var rootCertificate: [UInt8] {\n            self.certificateChain.last!\n        }\n    }\n}\n\nextension SignatureValidation {\n    fileprivate func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        content: Data,\n        configuration: RegistryConfiguration.Security.Signing,\n        observabilityScope: ObservabilityScope? = nil\n    ) async throws -> SigningEntity? {\n        try await self.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            content: content,\n            configuration: configuration,\n            timeout: nil,\n            fileSystem: localFileSystem,\n            observabilityScope: observabilityScope ?? ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func validate(\n        registry: Registry,\n        package: PackageIdentity.RegistryIdentity,\n        version: Version,\n        toolsVersion: ToolsVersion?,\n        manifestContent: String,\n        configuration: RegistryConfiguration.Security.Signing,\n        observabilityScope: ObservabilityScope? = nil\n    ) async throws -> SigningEntity? {\n        try await self.validate(\n            registry: registry,\n            package: package,\n            version: version,\n            toolsVersion: toolsVersion,\n            manifestContent: manifestContent,\n            configuration: configuration,\n            timeout: nil,\n            fileSystem: localFileSystem,\n            observabilityScope: observabilityScope ?? ObservabilitySystem.NOOP\n        )\n    }\n}\n\nprivate struct RejectingSignatureValidationDelegate: SignatureValidation.Delegate {\n    func onUnsigned(\n        registry: Registry,\n        package: PackageIdentity,\n        version: Version,\n        completion: (Bool) -> Void\n    ) {\n        completion(false)\n    }\n\n    func onUntrusted(\n        registry: Registry,\n        package: PackageIdentity,\n        version: Version,\n        completion: (Bool) -> Void\n    ) {\n        completion(false)\n    }\n}\n\nprivate struct AcceptingSignatureValidationDelegate: SignatureValidation.Delegate {\n    func onUnsigned(\n        registry: Registry,\n        package: PackageIdentity,\n        version: Version,\n        completion: (Bool) -> Void\n    ) {\n        completion(true)\n    }\n\n    func onUntrusted(\n        registry: Registry,\n        package: PackageIdentity,\n        version: Version,\n        completion: (Bool) -> Void\n    ) {\n        completion(true)\n    }\n}\n\nextension PackageSigningEntityStorage {\n    fileprivate func get(package: PackageIdentity) throws -> PackageSigners {\n        try self.get(\n            package: package,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n}\n\nextension HTTPClient {\n    static func packageReleaseMetadataAPIHandler(\n        metadataURL: URL,\n        checksum: String\n    ) -> HTTPClient.Implementation {\n        { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                XCTAssertEqual(request.headers.get(\"Accept\").first, \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                    \"id\": \"mona.LinkedList\",\n                    \"version\": \"1.1.1\",\n                    \"resources\": [\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\"\n                        }\n                    ],\n                    \"metadata\": {\n                        \"description\": \"One thing links to another.\"\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n    }\n\n    static func packageReleaseMetadataAPIHandler(\n        metadataURL: URL,\n        checksum: String,\n        signatureBytes: [UInt8],\n        signatureFormat: SignatureFormat,\n        includeResouces: Bool = true\n    ) -> HTTPClient.Implementation {\n        { request, _ in\n            switch (request.method, request.url) {\n            case (.get, metadataURL):\n                XCTAssertEqual(request.headers.get(\"Accept\").first, \"application/vnd.swift.registry.v1+json\")\n\n                let data = \"\"\"\n                {\n                    \"id\": \"mona.LinkedList\",\n                    \"version\": \"1.1.1\",\n                    \"resources\": [\n                        \\(includeResouces ? \"\"\"\n                        {\n                            \"name\": \"source-archive\",\n                            \"type\": \"application/zip\",\n                            \"checksum\": \"\\(checksum)\",\n                            \"signing\": {\n                                \"signatureBase64Encoded\": \"\\(Data(signatureBytes).base64EncodedString())\",\n                                \"signatureFormat\": \"\\(signatureFormat.rawValue)\"\n                            }\n                        }\n                        \"\"\" : \"\")\n                    ],\n                    \"metadata\": {\n                        \"description\": \"One thing links to another.\"\n                    }\n                }\n                \"\"\".data(using: .utf8)!\n\n                return .init(\n                    statusCode: 200,\n                    headers: .init([\n                        .init(name: \"Content-Length\", value: \"\\(data.count)\"),\n                        .init(name: \"Content-Type\", value: \"application/json\"),\n                        .init(name: \"Content-Version\", value: \"1\"),\n                    ]),\n                    body: data\n                )\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/PackageSigningTests/FilePackageSigningEntityStorageTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport Basics\nimport PackageModel\n@testable import PackageSigning\nimport _InternalTestSupport\nimport Testing\n\nimport struct TSCUtility.Version\n\nstruct FilePackageSigningEntityStorageTests {\n    @Test\n    func happyCase() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        // Record signing entities for mona.LinkedList\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let davinci = SigningEntity.recognized(\n            type: .adp,\n            name: \"L. da Vinci\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.1.0\"),\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://bar.com\"))\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"2.0.0\"),\n            signingEntity: appleseed,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n        // Record signing entity for another package\n        let otherPackage = PackageIdentity.plain(\"other.LinkedList\")\n        try storage.put(\n            package: otherPackage,\n            version: Version(\"1.0.0\"),\n            signingEntity: appleseed,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n\n        // A data file should have been created for each package\n        #expect(mockFileSystem.exists(storage.directoryPath.appending(component: package.signedVersionsFilename)))\n        #expect(mockFileSystem\n            .exists(storage.directoryPath.appending(component: otherPackage.signedVersionsFilename)))\n\n        // Signed versions should be saved\n        do {\n            let packageSigners = try storage.get(package: package)\n            #expect(packageSigners.expectedSigner == nil)\n            #expect(packageSigners.signers.count == 2)\n            #expect(packageSigners.signers[davinci]?.versions == [Version(\"1.0.0\"), Version(\"1.1.0\")])\n            #expect(packageSigners.signers[davinci]?.origins == [.registry(URL(\"http://foo.com\")), .registry(URL(\"http://bar.com\"))])\n            #expect(packageSigners.signers[appleseed]?.versions == [Version(\"2.0.0\")])\n            #expect(packageSigners.signers[appleseed]?.origins == [.registry(URL(\"http://foo.com\"))])\n        }\n\n        do {\n            let packageSigners = try storage.get(package: otherPackage)\n            #expect(packageSigners.expectedSigner == nil)\n            #expect(packageSigners.signers.count == 1)\n            #expect(packageSigners.signers[appleseed]?.versions == [Version(\"1.0.0\")])\n            #expect(packageSigners.signers[appleseed]?.origins == [.registry(URL(\"http://foo.com\"))])\n        }\n    }\n\n    @Test\n    func putDifferentSigningEntityShouldConflict() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let davinci = SigningEntity.recognized(\n            type: .adp,\n            name: \"L. da Vinci\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n        let version = Version(\"1.0.0\")\n        try storage.put(\n            package: package,\n            version: version,\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n\n        // Writing different signing entities for the same version should fail\n        #expect {\n            try storage.put(\n                package: package,\n                version: version,\n                signingEntity: appleseed,\n                origin: .registry(URL(\"http://foo.com\"))\n            )\n        } throws: { error in\n            guard case PackageSigningEntityStorageError.conflict = error else {\n                Issue.record(\"Expected PackageSigningEntityStorageError.conflict, got \\(error)\")\n                return false\n            }\n            return true\n        }\n    }\n\n    @Test\n    func putSameSigningEntityShouldNotConflict() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n        let version = Version(\"1.0.0\")\n        try storage.put(\n            package: package,\n            version: version,\n            signingEntity: appleseed,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n\n        // Writing same signing entity for version should be ok\n        try storage.put(\n            package: package,\n            version: version,\n            signingEntity: appleseed,\n            origin: .registry(URL(\"http://bar.com\")) // origin is different and should be added\n        )\n\n        let packageSigners = try storage.get(package: package)\n        #expect(packageSigners.expectedSigner == nil)\n        #expect(packageSigners.signers.count == 1)\n        #expect(packageSigners.signers[appleseed]?.versions == [Version(\"1.0.0\")])\n        #expect(packageSigners.signers[appleseed]?.origins == [.registry(URL(\"http://foo.com\")), .registry(URL(\"http://bar.com\"))])\n    }\n\n    @Test\n    func putUnrecognizedSigningEntityShouldError() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.unrecognized(name: \"J. Appleseed\", organizationalUnit: nil, organization: nil)\n        let version = Version(\"1.0.0\")\n\n        #expect {\n            try storage.put(\n                package: package,\n                version: version,\n                signingEntity: appleseed,\n                origin: .registry(URL(\"http://bar.com\")) // origin is different and should be added\n            )\n        } throws: { error in\n            guard case PackageSigningEntityStorageError.unrecognizedSigningEntity = error else {\n                Issue.record(\"Expected PackageSigningEntityStorageError.unrecognizedSigningEntity but got \\(error)\")\n                return false\n            }\n            return true\n        }\n    }\n\n    @Test\n    func addDifferentSigningEntityShouldNotConflict() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let davinci = SigningEntity.recognized(\n            type: .adp,\n            name: \"L. da Vinci\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n        let version = Version(\"1.0.0\")\n        try storage.put(\n            package: package,\n            version: version,\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n\n        // Adding different signing entity for the same version should not fail\n        try storage.add(\n            package: package,\n            version: version,\n            signingEntity: appleseed,\n            origin: .registry(URL(\"http://bar.com\"))\n        )\n\n        let packageSigners = try storage.get(package: package)\n        #expect(packageSigners.expectedSigner == nil)\n        #expect(packageSigners.signers.count == 2)\n        #expect(packageSigners.signers[appleseed]?.versions == [Version(\"1.0.0\")])\n        #expect(packageSigners.signers[appleseed]?.origins == [.registry(URL(\"http://bar.com\"))])\n        #expect(packageSigners.signers[davinci]?.versions == [Version(\"1.0.0\")])\n        #expect(packageSigners.signers[davinci]?.origins == [.registry(URL(\"http://foo.com\"))])\n        #expect(packageSigners.signingEntities(of: Version(\"1.0.0\")) == [appleseed, davinci])\n    }\n\n    @Test\n    func addUnrecognizedSigningEntityShouldError() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.unrecognized(name: \"J. Appleseed\", organizationalUnit: nil, organization: nil)\n        let davinci = SigningEntity.recognized(\n            type: .adp,\n            name: \"L. da Vinci\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n        let version = Version(\"1.0.0\")\n        try storage.put(\n            package: package,\n            version: version,\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n\n        #expect {\n            try storage.add(\n                package: package,\n                version: version,\n                signingEntity: appleseed,\n                origin: .registry(URL(\"http://bar.com\"))\n            )\n        } throws: { error in\n            guard case PackageSigningEntityStorageError.unrecognizedSigningEntity = error else {\n                Issue.record(\"Expected PackageSigningEntityStorageError.unrecognizedSigningEntity but got \\(error)\")\n                return false\n            }\n            return true\n        }\n    }\n\n    @Test\n    func changeSigningEntityFromVersion() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let davinci = SigningEntity.recognized(\n            type: .adp,\n            name: \"L. da Vinci\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n\n        // Sets package's expectedSigner and add package version signer\n        try storage.changeSigningEntityFromVersion(\n            package: package,\n            version: Version(\"1.5.0\"),\n            signingEntity: appleseed,\n            origin: .registry(URL(\"http://bar.com\"))\n        )\n\n        let packageSigners = try storage.get(package: package)\n        #expect(packageSigners.expectedSigner?.signingEntity == appleseed)\n        #expect(packageSigners.expectedSigner?.fromVersion == Version(\"1.5.0\"))\n        #expect(packageSigners.signers.count == 2)\n        #expect(packageSigners.signers[appleseed]?.versions == [Version(\"1.5.0\")])\n        #expect(packageSigners.signers[appleseed]?.origins == [.registry(URL(\"http://bar.com\"))])\n        #expect(packageSigners.signers[davinci]?.versions == [Version(\"1.0.0\")])\n        #expect(packageSigners.signers[davinci]?.origins == [.registry(URL(\"http://foo.com\"))])\n    }\n\n    @Test\n    func changeSigningEntityFromVersion_unrecognizedSigningEntityShouldError() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.unrecognized(name: \"J. Appleseed\", organizationalUnit: nil, organization: nil)\n        let davinci = SigningEntity.recognized(\n            type: .adp,\n            name: \"L. da Vinci\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n\n        #expect {\n            try storage.changeSigningEntityFromVersion(\n                package: package,\n                version: Version(\"1.5.0\"),\n                signingEntity: appleseed,\n                origin: .registry(URL(\"http://bar.com\"))\n            )\n        } throws: { error in\n            guard case PackageSigningEntityStorageError.unrecognizedSigningEntity = error else {\n                Issue.record(\"Expected PackageSigningEntityStorageError.unrecognizedSigningEntity but got \\(error)\")\n                return false\n            }\n            return true\n        }\n    }\n\n    @Test\n    func changeSigningEntityForAllVersions() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.recognized(\n            type: .adp,\n            name: \"J. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit 1\",\n            organization: \"SwiftPM Test\"\n        )\n        let davinci = SigningEntity.recognized(\n            type: .adp,\n            name: \"L. da Vinci\",\n            organizationalUnit: \"SwiftPM Test Unit 2\",\n            organization: \"SwiftPM Test\"\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"2.0.0\"),\n            signingEntity: appleseed,\n            origin: .registry(URL(\"http://bar.com\"))\n        )\n\n        // Sets package's expectedSigner and remove all other signers\n        try storage.changeSigningEntityForAllVersions(\n            package: package,\n            version: Version(\"1.5.0\"),\n            signingEntity: appleseed,\n            origin: .registry(URL(\"http://bar.com\"))\n        )\n\n        let packageSigners = try storage.get(package: package)\n        #expect(packageSigners.expectedSigner?.signingEntity == appleseed)\n        #expect(packageSigners.expectedSigner?.fromVersion == Version(\"1.5.0\"))\n        #expect(packageSigners.signers.count == 1)\n        #expect(packageSigners.signers[appleseed]?.versions == [Version(\"1.5.0\"), Version(\"2.0.0\")])\n        #expect(packageSigners.signers[appleseed]?.origins == [.registry(URL(\"http://bar.com\"))])\n    }\n\n    @Test\n    func changeSigningEntityForAllVersions_unrecognizedSigningEntityShouldError() async throws {\n        let mockFileSystem = InMemoryFileSystem()\n        let directoryPath = AbsolutePath(\"/signing\")\n        let storage = FilePackageSigningEntityStorage(fileSystem: mockFileSystem, directoryPath: directoryPath)\n\n        let package = PackageIdentity.plain(\"mona.LinkedList\")\n        let appleseed = SigningEntity.unrecognized(name: \"J. Appleseed\", organizationalUnit: nil, organization: nil)\n        let davinci = SigningEntity.recognized(\n            type: .adp,\n            name: \"L. da Vinci\",\n            organizationalUnit: \"SwiftPM Test Unit\",\n            organization: \"SwiftPM Test\"\n        )\n        try storage.put(\n            package: package,\n            version: Version(\"1.0.0\"),\n            signingEntity: davinci,\n            origin: .registry(URL(\"http://foo.com\"))\n        )\n\n        #expect {\n            try storage.changeSigningEntityForAllVersions(\n                package: package,\n                version: Version(\"1.5.0\"),\n                signingEntity: appleseed,\n                origin: .registry(URL(\"http://bar.com\"))\n            )\n        } throws: { error in\n            guard case PackageSigningEntityStorageError.unrecognizedSigningEntity = error else {\n                Issue.record(\"Expected PackageSigningEntityStorageError.unrecognizedSigningEntity but got \\(error)\")\n                return false\n            }\n            return true\n        }\n    }\n}\n\nextension PackageSigningEntityStorage {\n    fileprivate func get(package: PackageIdentity) throws -> PackageSigners {\n        try self.get(\n            package: package,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func put(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin\n    ) throws {\n        try self.put(\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            origin: origin,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func add(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin\n    ) throws {\n        try self.add(\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            origin: origin,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func changeSigningEntityFromVersion(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin\n    ) throws {\n        try self.changeSigningEntityFromVersion(\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            origin: origin,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n\n    fileprivate func changeSigningEntityForAllVersions(\n        package: PackageIdentity,\n        version: Version,\n        signingEntity: SigningEntity,\n        origin: SigningEntity.Origin\n    ) throws {\n        try self.changeSigningEntityForAllVersions(\n            package: package,\n            version: version,\n            signingEntity: signingEntity,\n            origin: origin,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/PackageSigningTests/SigningEntityTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\nimport Testing\nimport XCTest\n\nimport Basics\n@testable import PackageSigning\nimport _InternalTestSupport\nimport X509\n\nstruct SigningEntityTests {\n    @Test\n    func twoADPSigningEntitiesAreEqualIfTeamIDEqual() {\n        let adp1 = SigningEntity.recognized(\n            type: .adp,\n            name: \"A. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit X\",\n            organization: \"A\"\n        )\n        let adp2 = SigningEntity.recognized(\n            type: .adp,\n            name: \"B. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit X\",\n            organization: \"B\"\n        )\n        let adp3 = SigningEntity.recognized(\n            type: .adp,\n            name: \"C. Appleseed\",\n            organizationalUnit: \"SwiftPM Test Unit Y\",\n            organization: \"C\"\n        )\n        #expect(adp1 == adp2) // Only team ID (org unit) needs to match\n        #expect(adp1 != adp3)\n    }\n\n    @Test(\n        \"From certificate key\",\n        arguments: [\n            (certificateFilename: \"Test_ec.cer\", id: \"EC Key\"),\n            (certificateFilename: \"Test_rsa.cer\", id: \"RSA Key\")\n        ]\n    )\n    func fromCertificate(certificateFilename: String, id: String) throws {\n        try fixture(name: \"Signing\") { fixturePath in\n            let certificateBytes = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\",\n                certificateFilename\n            )\n            let certificate = try Certificate(certificateBytes)\n\n            let signingEntity = SigningEntity.from(certificate: certificate)\n            guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n                Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n                return\n            }\n            #expect(name == certificate.subject.commonName)\n            #expect(organizationalUnit == certificate.subject.organizationalUnitName)\n            #expect(organization == certificate.subject.organizationName)\n        }\n    }\n}\n\nfinal class SigningEntityXCTests: XCTestCase {\n    #if os(macOS)\n    func testFromKeychainCertificate() async throws {\n        #if ENABLE_REAL_SIGNING_IDENTITY_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        guard let label = Environment.current[\"REAL_SIGNING_IDENTITY_LABEL\"] else {\n            throw XCTSkip(\"Skipping because 'REAL_SIGNING_IDENTITY_LABEL' env var is not set\")\n        }\n        let identityStore = SigningIdentityStore(observabilityScope: ObservabilitySystem.NOOP)\n        let matches = identityStore.find(by: label)\n        XCTAssertTrue(!matches.isEmpty)\n\n        let certificate = try Certificate(secIdentity: matches[0] as! SecIdentity)\n        let signingEntity = SigningEntity.from(certificate: certificate)\n        switch signingEntity {\n        case .recognized(_, let name, let organizationalUnit, let organization):\n            XCTAssertEqual(name, certificate.subject.commonName)\n            XCTAssertEqual(organizationalUnit, certificate.subject.organizationalUnitName)\n            XCTAssertEqual(organization, certificate.subject.organizationName)\n        case .unrecognized(let name, let organizationalUnit, let organization):\n            XCTAssertEqual(name, certificate.subject.commonName)\n            XCTAssertEqual(organizationalUnit, certificate.subject.organizationalUnitName)\n            XCTAssertEqual(organization, certificate.subject.organizationName)\n        }\n    }\n    #endif\n}\n"
  },
  {
    "path": "Tests/PackageSigningTests/SigningIdentityTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Testing\nimport XCTest\n\nimport _CryptoExtras // For RSA\nimport Basics\nimport Crypto\n@testable import PackageSigning\nimport _InternalTestSupport\nimport X509\n\nstruct SigningIdentityTests {\n    @Test\n    func swiftSigningIdentityWithECKey() throws {\n        try fixture(name: \"Signing\") { fixturePath in\n            let certificateBytes = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\",\n                \"Test_ec.cer\"\n            )\n            let certificate = try Certificate(certificateBytes)\n\n            let subject = certificate.subject\n            #expect(\"Test (EC) leaf\" == subject.commonName)\n            #expect(\"Test (EC) org unit\" == subject.organizationalUnitName)\n            #expect(\"Test (EC) org\" == subject.organizationName)\n\n            let privateKeyBytes = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\",\n                \"Test_ec_key.p8\"\n            )\n            let privateKey = try P256.Signing.PrivateKey(derRepresentation: privateKeyBytes)\n            _ = SwiftSigningIdentity(certificate: certificate, privateKey: Certificate.PrivateKey(privateKey))\n\n            // Test public API\n            #expect(throws: Never.self) {\n\n                try SwiftSigningIdentity(\n                    derEncodedCertificate: certificateBytes,\n                    derEncodedPrivateKey: privateKeyBytes,\n                    privateKeyType: .p256\n                )\n            }\n        }\n    }\n\n    @Test\n    func swiftSigningIdentityWithRSAKey() throws {\n        try fixture(name: \"Signing\") { fixturePath in\n            let certificateBytes = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\",\n                \"Test_rsa.cer\"\n            )\n            let certificate = try Certificate(certificateBytes)\n\n            let subject = certificate.subject\n            #expect(\"Test (RSA) leaf\" == subject.commonName)\n            #expect(\"Test (RSA) org unit\" == subject.organizationalUnitName)\n            #expect(\"Test (RSA) org\" == subject.organizationName)\n\n            let privateKeyBytes = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\",\n                \"Test_rsa_key.p8\"\n            )\n            let privateKey = try _RSA.Signing.PrivateKey(derRepresentation: privateKeyBytes)\n            _ = SwiftSigningIdentity(certificate: certificate, privateKey: Certificate.PrivateKey(privateKey))\n        }\n    }\n}\nfinal class SigningIdentityXCTests: XCTestCase {\n\n    #if os(macOS)\n    func testSigningIdentityFromKeychain() async throws {\n        #if ENABLE_REAL_SIGNING_IDENTITY_TEST\n        #else\n        try XCTSkipIf(true)\n        #endif\n\n        guard let label = Environment.current[\"REAL_SIGNING_IDENTITY_LABEL\"] else {\n            throw XCTSkip(\"Skipping because 'REAL_SIGNING_IDENTITY_LABEL' env var is not set\")\n        }\n        let identityStore = SigningIdentityStore(observabilityScope: ObservabilitySystem.NOOP)\n        let matches = identityStore.find(by: label)\n        XCTAssertTrue(!matches.isEmpty)\n\n        let subject = try Certificate(secIdentity: matches[0] as! SecIdentity).subject\n        XCTAssertNotNil(subject.commonName)\n        XCTAssertNotNil(subject.organizationalUnitName)\n        XCTAssertNotNil(subject.organizationName)\n    }\n    #endif\n}\n"
  },
  {
    "path": "Tests/PackageSigningTests/SigningTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _CryptoExtras // for RSA\nimport Basics\nimport Crypto\nimport Foundation\n@testable import PackageSigning\nimport _InternalTestSupport\nimport SwiftASN1\n@testable import X509 // need internal APIs for OCSP testing\nimport Testing\n\nstruct SigningTests {\n    @Test\n    func CMS1_0_0EndToEnd() async throws {\n        let keyAndCertChain = try self.ecTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signature = try SignatureProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            format: signatureFormat,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let status = try await SignatureProvider.status(\n            signature: signature,\n            content: content,\n            format: signatureFormat,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n            Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n            return\n        }\n        #expect(\"Test (EC) leaf\" == name)\n        #expect(\"Test (EC) org unit\" == organizationalUnit)\n        #expect(\"Test (EC) org\" == organization)\n    }\n\n    @Test\n    func CMSEndToEndWithECSigningIdentity() async throws {\n        let keyAndCertChain = try self.ecTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n            Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n            return\n        }\n        #expect(\"Test (EC) leaf\" == name)\n        #expect(\"Test (EC) org unit\" == organizationalUnit)\n        #expect(\"Test (EC) org\" == organization)\n    }\n\n    @Test\n    func CMSEndToEndWithRSASigningIdentity() async throws {\n        let keyAndCertChain = try self.rsaTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(_RSA.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .rsa)\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n            Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n            return\n        }\n        #expect(\"Test (RSA) leaf\" == name)\n        #expect(\"Test (RSA) org unit\" == organizationalUnit)\n        #expect(\"Test (RSA) org\" == organization)\n    }\n\n    @Test\n    func CMSWrongKeyTypeForSignatureAlgorithm() async throws {\n        let keyAndCertChain = try self.ecTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        // Key is EC but signature algorithm is RSA\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .rsa)\n\n        do {\n            _ = try cmsProvider.sign(\n                content: content,\n                identity: signingIdentity,\n                intermediateCertificates: keyAndCertChain.intermediateCertificates,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            Issue.record(\"Expected error\")\n        } catch {\n            guard case SigningError.keyDoesNotSupportSignatureAlgorithm = error else {\n                Issue.record(\n                    \"Expected SigningError.keyDoesNotSupportSignatureAlgorithm but got \\(error)\")\n                return\n            }\n        }\n    }\n\n    @Test\n    func CMS1_0_0EndToEndWithSelfSignedCertificate() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signature = try SignatureProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            format: signatureFormat,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let status = try await SignatureProvider.status(\n            signature: signature,\n            content: content,\n            format: signatureFormat,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n            Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n            return\n        }\n        #expect(\"Test (EC)\" == name)\n        #expect(\"Test (EC) org unit\" == organizationalUnit)\n        #expect(\"Test (EC) org\" == organization)\n    }\n\n    @Test\n    func CMSEndToEndWithSelfSignedECSigningIdentity() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n            Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n            return\n        }\n        #expect(\"Test (EC)\" == name)\n        #expect(\"Test (EC) org unit\" == organizationalUnit)\n        #expect(\"Test (EC) org\" == organization)\n    }\n\n    @Test\n    func CMSEndToEndWithSelfSignedRSASigningIdentity() async throws {\n        let keyAndCertChain = try self.rsaSelfSignedTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(_RSA.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .rsa)\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n            Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n            return\n        }\n        #expect(\"Test (RSA)\" == name)\n        #expect(\"Test (RSA) org unit\" == organizationalUnit)\n        #expect(\"Test (RSA) org\" == organization)\n    }\n\n    @Test\n    func CMSBadSignature() async throws {\n        let content = Array(\"per aspera ad astra\".utf8)\n        let signature = Array(\"bad signature\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: .init(),\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .invalid = status else {\n            Issue.record(\"Expected signature status to be .invalid but got \\(status)\")\n            return\n        }\n    }\n\n    @Test\n    func CMSInvalidSignature() async throws {\n        let keyAndCertChain = try self.ecTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let signatureContent = Array(\"per aspera ad astra\".utf8)\n        let otherContent = Array(\"ad infinitum\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n        let signature = try cmsProvider.sign(\n            content: signatureContent,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: otherContent,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .invalid = status else {\n            Issue.record(\"Expected signature status to be .invalid but got \\(status)\")\n            return\n        }\n    }\n\n    @Test\n    func CMSUntrustedCertificate() async throws {\n        let keyAndCertChain = try self.ecTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [], // trust store is empty\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .certificateNotTrusted = status else {\n            Issue.record(\n                \"Expected signature status to be .certificateNotTrusted but got \\(status)\")\n            return\n        }\n    }\n\n    @Test\n    func CMSCheckCertificateValidityPeriod() async throws {\n        let keyAndCertChain = try self.ecTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        do {\n            let verifierConfiguration = VerifierConfiguration(\n                trustedRoots: [keyAndCertChain.rootCertificate],\n                includeDefaultTrustStore: false,\n                certificateExpiration: .enabled(\n                    validationTime: signingIdentity.certificate.notValidBefore - .days(3)\n                ),\n                certificateRevocation: .disabled\n            )\n\n            let status = try await cmsProvider.status(\n                signature: signature,\n                content: content,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            guard case .certificateInvalid(let reason) = status else {\n                Issue.record(\n                    \"Expected signature status to be .certificateInvalid but got \\(status)\")\n                return\n            }\n            #expect(reason.contains(\"not yet valid\"))\n        }\n\n        do {\n            let verifierConfiguration = VerifierConfiguration(\n                trustedRoots: [keyAndCertChain.rootCertificate],\n                includeDefaultTrustStore: false,\n                certificateExpiration: .enabled(\n                    validationTime: signingIdentity.certificate.notValidAfter + .days(3)\n                ),\n                certificateRevocation: .disabled\n            )\n\n            let status = try await cmsProvider.status(\n                signature: signature,\n                content: content,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n\n            guard case .certificateInvalid(let reason) = status else {\n                Issue.record(\n                    \"Expected signature status to be .certificateInvalid but got \\(status)\")\n                return\n            }\n            #expect(reason.contains(\"has expired\"))\n        }\n    }\n\n    @Test\n    func CMSCheckCertificateRevocationStatus() async throws {\n        let leafName = try OCSPTestHelper.distinguishedName(commonName: \"localhost\")\n        let intermediateName = try OCSPTestHelper.distinguishedName(commonName: \"SwiftPM Test Intermediate CA\")\n        let caName = try OCSPTestHelper.distinguishedName(commonName: \"SwiftPM Test CA\")\n\n        let leafPrivateKey = P256.Signing.PrivateKey()\n        let intermediatePrivateKey = P256.Signing.PrivateKey()\n        let caPrivateKey = P256.Signing.PrivateKey()\n\n        let ocspResponderURI = \"http://ocsp.local\"\n        let chainWithSingleCertWithOCSP = [\n            try OCSPTestHelper.certificate(\n                subject: leafName,\n                publicKey: leafPrivateKey.publicKey,\n                issuer: intermediateName,\n                issuerPrivateKey: intermediatePrivateKey,\n                isIntermediate: false,\n                isCodeSigning: true,\n                ocspServer: ocspResponderURI\n            ),\n            try OCSPTestHelper.certificate(\n                subject: intermediateName,\n                publicKey: intermediatePrivateKey.publicKey,\n                issuer: caName,\n                issuerPrivateKey: caPrivateKey,\n                isIntermediate: true,\n                isCodeSigning: false\n            ),\n        ]\n\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: chainWithSingleCertWithOCSP[0],\n            privateKey: Certificate.PrivateKey(leafPrivateKey)\n        )\n\n        let validationTime = signingIdentity.certificate.notValidAfter - .days(3)\n\n        let ocspHandler: HTTPClient.Implementation = { request, _ in\n            switch (request.method, request.url) {\n            case (.post, URL(ocspResponderURI)):\n                guard let requestBody = request.body else {\n                    throw StringError(\"Empty request body\")\n                }\n\n                let ocspRequest = try OCSPRequest(derEncoded: Array(requestBody))\n\n                guard let nonce = try? ocspRequest.tbsRequest.requestExtensions?.ocspNonce else {\n                    throw StringError(\"Missing nonce\")\n                }\n                guard let singleRequest = ocspRequest.tbsRequest.requestList.first else {\n                    throw StringError(\"Missing OCSP request\")\n                }\n\n                let ocspResponse = try OCSPResponse.successful(\n                    .signed(\n                        responderID: ResponderID.byName(intermediateName),\n                        producedAt: GeneralizedTime(validationTime),\n                        responses: [\n                            OCSPSingleResponse(\n                                certID: singleRequest.certID,\n                                certStatus: .unknown,\n                                thisUpdate: GeneralizedTime(validationTime - .days(1)),\n                                nextUpdate: GeneralizedTime(validationTime + .days(1))\n                            )\n                        ],\n                        privateKey: intermediatePrivateKey,\n                        responseExtensions: { nonce }\n                    ))\n                return HTTPClientResponse(\n                    statusCode: 200, body: try Data(ocspResponse.derEncodedBytes()))\n            default:\n                throw StringError(\"method and url should match\")\n            }\n        }\n\n        let content = Array(\"per aspera ad astra\".utf8)\n        let cmsProvider = CMSSignatureProvider(\n            signatureAlgorithm: .ecdsaP256,\n            customHTTPClient: HTTPClient(implementation: ocspHandler)\n        )\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: [],\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        // certificateRevocation = .strict doesn't allow status 'unknown'\n        do {\n            let verifierConfiguration = VerifierConfiguration(\n                trustedRoots: [try chainWithSingleCertWithOCSP[1].derEncodedBytes()],\n                includeDefaultTrustStore: false,\n                certificateExpiration: .disabled,\n                certificateRevocation: .strict(validationTime: validationTime)\n            )\n\n            let status = try await cmsProvider.status(\n                signature: signature,\n                content: content,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            guard case .certificateInvalid(let reason) = status else {\n                Issue.record(\n                    \"Expected signature status to be .certificateInvalid but got \\(status)\")\n                return\n            }\n            #expect(reason.contains(\"status unknown\"))\n        }\n\n        // certificateRevocation = .allowSoftFail allows status 'unknown'\n        do {\n            let verifierConfiguration = VerifierConfiguration(\n                trustedRoots: [try chainWithSingleCertWithOCSP[1].derEncodedBytes()],\n                includeDefaultTrustStore: false,\n                certificateExpiration: .disabled,\n                certificateRevocation: .allowSoftFail(validationTime: validationTime)\n            )\n\n            let status = try await cmsProvider.status(\n                signature: signature,\n                content: content,\n                verifierConfiguration: verifierConfiguration,\n                observabilityScope: ObservabilitySystem.NOOP\n            )\n            guard case .valid = status else {\n                Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n                return\n            }\n        }\n    }\n\n    @Test(\n        .enabled(if: isRealSigningIdentitTestDefined)\n    )\n    func CMSEndToEndWithRSAKeyADPCertificate() async throws {\n        let keyAndCertChain = try rsaADPKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(_RSA.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .rsa)\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: true,\n            certificateExpiration: .enabled(validationTime: nil),\n            certificateRevocation: .strict(validationTime: nil)\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n\n        func rsaADPKeyAndCertChain() throws -> KeyAndCertChain {\n            try fixture(name: \"Signing\") { fixturePath in\n                let privateKey = try readFileContents(\n                    in: fixturePath,\n                    pathComponents: \"Certificates\", \"development_key.p8\"\n                )\n                let certificate = try readFileContents(\n                    in: fixturePath,\n                    pathComponents: \"Certificates\", \"development.cer\"\n                )\n\n                return KeyAndCertChain(\n                    privateKey: privateKey,\n                    certificateChain: [certificate]\n                )\n            }\n        }\n    }\n\n    @Test(\n        .enabled(if: isRealSigningIdentitTestDefined)\n    )\n    func CMSEndToEndWithECKeyADPCertificate() async throws {\n        let keyAndCertChain = try ecADPKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: true,\n            certificateExpiration: .enabled(validationTime: nil),\n            certificateRevocation: .strict(validationTime: nil)\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n\n        func ecADPKeyAndCertChain() throws -> KeyAndCertChain {\n            try fixture(name: \"Signing\") { fixturePath in\n                let privateKey = try readFileContents(\n                    in: fixturePath,\n                    pathComponents: \"Certificates\", \"swift_package_key.p8\"\n                )\n                let certificate = try readFileContents(\n                    in: fixturePath,\n                    pathComponents: \"Certificates\", \"swift_package.cer\"\n                )\n\n                return KeyAndCertChain(\n                    privateKey: privateKey,\n                    certificateChain: [certificate]\n                )\n            }\n        }\n    }\n\n    // #if os(macOS)\n    @Test(\n        .enabled(if: ProcessInfo.hostOperatingSystem == .windows),\n        .enabled(if: isRealSigningIdentitTestDefined),\n        .enabled(if: isRealSigningIdentyEcLabelEnvVarSet),\n    )\n    func CMS1_0_0EndToEndWithADPSigningIdentityFromKeychain() async throws {\n        let label = try #require(Environment.current[\"REAL_SIGNING_IDENTITY_EC_LABEL\"])\n\n        let identityStore = SigningIdentityStore(observabilityScope: ObservabilitySystem.NOOP)\n        let matches = identityStore.find(by: label)\n        #expect(!matches.isEmpty)\n\n        let signingIdentity = matches[0]\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        // This call will trigger OS prompt(s) for key access\n        let signature = try SignatureProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: [], // No need to pass intermediates for WWDR certs\n            format: signatureFormat,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [],\n            includeDefaultTrustStore: true, // WWDR roots are in the default trust store\n            certificateExpiration: .enabled(validationTime: nil),\n            certificateRevocation: .strict(validationTime: nil)\n        )\n\n        let status = try await SignatureProvider.status(\n            signature: signature,\n            content: content,\n            format: signatureFormat,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        switch signingEntity {\n        case .recognized:\n            break\n        case .unrecognized(let name, let organizationalUnit, let organization):\n            #expect(name != nil)\n            #expect(organizationalUnit != nil)\n            #expect(organization != nil)\n        }\n    }\n    // #endif\n\n    // #if os(macOS)\n    @Test(\n        .enabled(if: ProcessInfo.hostOperatingSystem == .windows),\n        .enabled(if: isRealSigningIdentitTestDefined),\n        .enabled(if: isRealSigningIdentyEcLabelEnvVarSet),\n    )\n    func CMSEndToEndWithECKeyADPSigningIdentityFromKeychain() async throws {\n        let label = try #require(Environment.current[\"REAL_SIGNING_IDENTITY_EC_LABEL\"])\n        let identityStore = SigningIdentityStore(observabilityScope: ObservabilitySystem.NOOP)\n        let matches = identityStore.find(by: label)\n        #expect(!matches.isEmpty)\n\n        let signingIdentity = matches[0]\n        let content = Array(\"per aspera ad astra\".utf8)\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .ecdsaP256)\n\n        // This call will trigger OS prompt(s) for key access\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: [], // No need to pass intermediates for WWDR certs\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [],\n            includeDefaultTrustStore: true, // WWDR roots are in the default trust store\n            certificateExpiration: .enabled(validationTime: nil),\n            certificateRevocation: .strict(validationTime: nil)\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        switch signingEntity {\n        case .recognized:\n            break\n        case .unrecognized(let name, let organizationalUnit, let organization):\n            #expect(name != nil)\n            #expect(organizationalUnit != nil)\n            #expect(organization != nil)\n        }\n    }\n    // #endif\n\n    // #if os(macOS)\n    @Test(\n        .enabled(if: ProcessInfo.hostOperatingSystem == .windows),\n        .enabled(if: isRealSigningIdentitTestDefined),\n        .enabled(if: isRealSigningIdentyEcLabelEnvVarSet),\n    )\n    func testCMSEndToEndWithRSAKeyADPSigningIdentityFromKeychain() async throws {\n        let label = try #require(Environment.current[\"REAL_SIGNING_IDENTITY_EC_LABEL\"])\n        let identityStore = SigningIdentityStore(observabilityScope: ObservabilitySystem.NOOP)\n        let matches = identityStore.find(by: label)\n        #expect(!matches.isEmpty)\n\n        let signingIdentity = matches[0]\n        let content = Array(\"per aspera ad astra\".utf8)\n        let cmsProvider = CMSSignatureProvider(signatureAlgorithm: .rsa)\n\n        // This call will trigger OS prompt(s) for key access\n        let signature = try cmsProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: [], // No need to pass intermediates for WWDR certs\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [],\n            includeDefaultTrustStore: true, // WWDR roots are in the default trust store\n            certificateExpiration: .enabled(validationTime: nil),\n            certificateRevocation: .strict(validationTime: nil)\n        )\n\n        let status = try await cmsProvider.status(\n            signature: signature,\n            content: content,\n            verifierConfiguration: verifierConfiguration,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        guard case .valid(let signingEntity) = status else {\n            Issue.record(\"Expected signature status to be .valid but got \\(status)\")\n            return\n        }\n        switch signingEntity {\n        case .recognized:\n            break\n        case .unrecognized(let name, let organizationalUnit, let organization):\n            #expect(name != nil)\n            #expect(organizationalUnit != nil)\n            #expect(organization != nil)\n        }\n    }\n    // #endif\n\n    @Test\n    func CMS1_0_0ExtractSigningEntity() async throws {\n        let keyAndCertChain = try self.ecTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signature = try SignatureProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            format: signatureFormat,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let signingEntity = try await SignatureProvider.extractSigningEntity(\n            signature: signature,\n            format: signatureFormat,\n            verifierConfiguration: verifierConfiguration\n        )\n\n        guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n            Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n            return\n        }\n        #expect(\"Test (EC) leaf\" == name)\n        #expect(\"Test (EC) org unit\" == organizationalUnit)\n        #expect(\"Test (EC) org\" == organization)\n    }\n\n    @Test\n    func CMS1_0_0ExtractSigningEntityWithSelfSignedCertificate() async throws {\n        let keyAndCertChain = try self.ecSelfSignedTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signature = try SignatureProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            format: signatureFormat,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [keyAndCertChain.rootCertificate],\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        let signingEntity = try await SignatureProvider.extractSigningEntity(\n            signature: signature,\n            format: signatureFormat,\n            verifierConfiguration: verifierConfiguration\n        )\n\n        guard case .unrecognized(let name, let organizationalUnit, let organization) = signingEntity else {\n            Issue.record(\"Expected SigningEntity.unrecognized but got \\(signingEntity)\")\n            return\n        }\n        #expect(\"Test (EC)\" == name)\n        #expect(\"Test (EC) org unit\" == organizationalUnit)\n        #expect(\"Test (EC) org\" == organization)\n    }\n\n    @Test\n    func CMS1_0_0ExtractSigningEntityWithUntrustedCertificate() async throws {\n        let keyAndCertChain = try self.ecTestKeyAndCertChain()\n        let signingIdentity = SwiftSigningIdentity(\n            certificate: try Certificate(keyAndCertChain.leafCertificate),\n            privateKey: try Certificate\n                .PrivateKey(P256.Signing.PrivateKey(derRepresentation: keyAndCertChain.privateKey))\n        )\n        let content = Array(\"per aspera ad astra\".utf8)\n\n        let signatureFormat = SignatureFormat.cms_1_0_0\n        let signature = try SignatureProvider.sign(\n            content: content,\n            identity: signingIdentity,\n            intermediateCertificates: keyAndCertChain.intermediateCertificates,\n            format: signatureFormat,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n\n        let verifierConfiguration = VerifierConfiguration(\n            trustedRoots: [], // trust store is empty\n            includeDefaultTrustStore: false,\n            certificateExpiration: .disabled,\n            certificateRevocation: .disabled\n        )\n\n        do {\n            _ = try await SignatureProvider.extractSigningEntity(\n                signature: signature,\n                format: signatureFormat,\n                verifierConfiguration: verifierConfiguration\n            )\n            Issue.record(\"expected error\")\n        } catch {\n            guard case SigningError.certificateNotTrusted = error else {\n                Issue.record(\n                    \"Expected error to be SigningError.certificateNotTrusted but got \\(error)\")\n                return\n            }\n        }\n    }\n\n    private func ecTestKeyAndCertChain() throws -> KeyAndCertChain {\n        try fixture(name: \"Signing\") { fixturePath in\n            let privateKey = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"Test_ec_key.p8\"\n            )\n            let certificate = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"Test_ec.cer\"\n            )\n            let intermediateCA = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"TestIntermediateCA.cer\"\n            )\n            let rootCA = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"TestRootCA.cer\"\n            )\n\n            return KeyAndCertChain(\n                privateKey: privateKey,\n                certificateChain: [certificate, intermediateCA, rootCA]\n            )\n        }\n    }\n\n    private func ecSelfSignedTestKeyAndCertChain() throws -> KeyAndCertChain {\n        try fixture(name: \"Signing\") { fixturePath in\n            let privateKey = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"Test_ec_self_signed_key.p8\"\n            )\n            let certificate = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"Test_ec_self_signed.cer\"\n            )\n\n            return KeyAndCertChain(\n                privateKey: privateKey,\n                certificateChain: [certificate]\n            )\n        }\n    }\n\n    private func rsaTestKeyAndCertChain() throws -> KeyAndCertChain {\n        try fixture(name: \"Signing\") { fixturePath in\n            let privateKey = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"Test_rsa_key.p8\"\n            )\n            let certificate = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"Test_rsa.cer\"\n            )\n            let intermediateCA = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"TestIntermediateCA.cer\"\n            )\n            let rootCA = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"TestRootCA.cer\"\n            )\n\n            return KeyAndCertChain(\n                privateKey: privateKey,\n                certificateChain: [certificate, intermediateCA, rootCA]\n            )\n        }\n    }\n\n    private func rsaSelfSignedTestKeyAndCertChain() throws -> KeyAndCertChain {\n        try fixture(name: \"Signing\") { fixturePath in\n            let privateKey = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"Test_rsa_self_signed_key.p8\"\n            )\n            let certificate = try readFileContents(\n                in: fixturePath,\n                pathComponents: \"Certificates\", \"Test_rsa_self_signed.cer\"\n            )\n\n            return KeyAndCertChain(\n                privateKey: privateKey,\n                certificateChain: [certificate]\n            )\n        }\n    }\n\n    private struct KeyAndCertChain {\n        let privateKey: [UInt8]\n        let certificateChain: [[UInt8]]\n\n        var leafCertificate: [UInt8] {\n            self.certificateChain.first!\n        }\n\n        var intermediateCertificates: [[UInt8]] {\n            guard self.certificateChain.count > 1 else {\n                return []\n            }\n            return Array(self.certificateChain.dropLast(1)[1...])\n        }\n\n        var rootCertificate: [UInt8] {\n            self.certificateChain.last!\n        }\n    }\n}\n\n// MARK: - Helpers for OCSP related testing\n\nenum OCSPTestHelper {\n    static func certificate(\n        subject: DistinguishedName,\n        publicKey: P256.Signing.PublicKey,\n        issuer: DistinguishedName,\n        issuerPrivateKey: P256.Signing.PrivateKey,\n        isIntermediate: Bool,\n        isCodeSigning: Bool,\n        ocspServer: String? = nil\n    ) throws -> Certificate {\n        try Certificate(\n            version: .v3,\n            serialNumber: .init(),\n            publicKey: .init(publicKey),\n            notValidBefore: Date() - .days(365),\n            notValidAfter: Date() + .days(365),\n            issuer: issuer,\n            subject: subject,\n            signatureAlgorithm: .ecdsaWithSHA256,\n            extensions: .init {\n                if isIntermediate {\n                    Critical(\n                        BasicConstraints.isCertificateAuthority(maxPathLength: 0)\n                    )\n                }\n                if isCodeSigning {\n                    Critical(\n                        try ExtendedKeyUsage([ExtendedKeyUsage.Usage.codeSigning])\n                    )\n                }\n                if let ocspServer {\n                    AuthorityInformationAccess([\n                        AuthorityInformationAccess.AccessDescription(\n                            method: .ocspServer,\n                            location: GeneralName.uniformResourceIdentifier(ocspServer)\n                        ),\n                    ])\n                }\n            },\n            issuerPrivateKey: .init(issuerPrivateKey)\n        )\n    }\n\n    static func distinguishedName(\n        countryName: String = \"US\",\n        organizationName: String = \"SwiftPM Test\",\n        commonName: String\n    ) throws -> DistinguishedName {\n        try DistinguishedName {\n            CountryName(countryName)\n            OrganizationName(organizationName)\n            CommonName(commonName)\n        }\n    }\n}\n\nextension Certificate {\n    fileprivate func derEncodedBytes() throws -> [UInt8] {\n        var serializer = DER.Serializer()\n        try serializer.serialize(self)\n        return serializer.serializedBytes\n    }\n}\n\nextension TimeInterval {\n    private static let oneDay: TimeInterval = 60 * 60 * 24\n\n    static func days(_ days: Int) -> TimeInterval {\n        Double(days) * self.oneDay\n    }\n}\n\nprivate let gregorianCalendar = Calendar(identifier: .gregorian)\nprivate let utcTimeZone = TimeZone(identifier: \"UTC\")!\n\nextension BasicOCSPResponse {\n    static func signed(\n        responseData: OCSPResponseData,\n        privateKey: P256.Signing.PrivateKey,\n        certs: [Certificate]?\n    ) throws -> Self {\n        var serializer = DER.Serializer()\n        try serializer.serialize(responseData)\n        let tbsCertificateBytes = serializer.serializedBytes[...]\n\n        let digest = SHA256.hash(data: tbsCertificateBytes)\n        let signature = try privateKey.signature(for: digest)\n\n        return try .init(\n            responseData: responseData,\n            signatureAlgorithm: .ecdsaWithSHA256,\n            signature: .init(bytes: Array(signature.derRepresentation)[...]),\n            certs: certs\n        )\n    }\n\n    static func signed(\n        version: OCSPVersion = .v1,\n        responderID: ResponderID,\n        producedAt: GeneralizedTime,\n        responses: [OCSPSingleResponse],\n        privateKey: P256.Signing.PrivateKey,\n        certs: [Certificate]? = [],\n        @ExtensionsBuilder responseExtensions: () throws -> Result<Certificate.Extensions, any Error> = {\n            // workaround for rdar://108897294\n            Result.success(Certificate.Extensions())\n        }\n    ) throws -> Self {\n        try .signed(\n            responseData: .init(\n                version: version,\n                responderID: responderID,\n                producedAt: producedAt,\n                responses: responses,\n                responseExtensions: try .init(builder: responseExtensions)\n            ),\n            privateKey: privateKey,\n            certs: certs\n        )\n    }\n\n    init(\n        responseData: OCSPResponseData,\n        signatureAlgorithm: AlgorithmIdentifier,\n        signature: ASN1BitString,\n        certs: [Certificate]?\n    ) throws {\n        self.init(\n            responseData: responseData,\n            responseDataBytes: try DER.Serializer.serialized(element: responseData)[...],\n            signatureAlgorithm: signatureAlgorithm,\n            signature: signature,\n            certs: certs\n        )\n    }\n}\n\nextension OCSPResponse {\n    fileprivate func derEncodedBytes() throws -> [UInt8] {\n        var serializer = DER.Serializer()\n        try serializer.serialize(self)\n        return serializer.serializedBytes\n    }\n}\n"
  },
  {
    "path": "Tests/PackageSigningTests/Utilities.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport XCTest\n\nfunc readFileContents(\n    in basePath: AbsolutePath,\n    pathComponents: String...,\n    fileSystem: FileSystem = localFileSystem\n) throws -> [UInt8] {\n    let path = basePath.appending(components: pathComponents)\n    return try fileSystem.readFileContents(path).contents\n}\n"
  },
  {
    "path": "Tests/QueryEngineTests/QueryEngineTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport _AsyncFileSystem\nimport Basics\nimport Crypto\nimport struct Foundation.Data\n@testable import QueryEngine\nimport struct SystemPackage.FilePath\nimport _InternalTestSupport\nimport Testing\n\nprivate let encoder = JSONEncoder()\nprivate let decoder = JSONDecoder()\n\nprivate extension AsyncFileSystem {\n    func read<V: Decodable>(_ path: FilePath, bufferLimit: Int = 10 * 1024 * 1024, as: V.Type) async throws -> V {\n        let data = try await self.withOpenReadableFile(path) {\n            var data = Data()\n            for try await chunk in try await $0.read() {\n                data.append(contentsOf: chunk)\n\n                assert(data.count < bufferLimit)\n            }\n            return data\n        }\n\n        return try decoder.decode(V.self, from: data)\n    }\n\n    func write(_ path: FilePath, _ value: some Encodable) async throws {\n        let data = try encoder.encode(value)\n        try await self.withOpenWritableFile(path) { fileHandle in\n            try await fileHandle.write(data)\n        }\n    }\n}\n\nprivate struct Const: CachingQuery {\n    let x: Int\n\n    func run(engine: QueryEngine) async throws -> FilePath {\n        let resultPath = FilePath(\"/Const-\\(x)\")\n        try await engine.fileSystem.write(resultPath, self.x)\n        return resultPath\n    }\n}\n\nprivate struct MultiplyByTwo: CachingQuery {\n    let x: Int\n\n    func run(engine: QueryEngine) async throws -> FilePath {\n        let constPath = try await engine[Const(x: self.x)].path\n        let constResult = try await engine.fileSystem.read(constPath, as: Int.self)\n\n        let resultPath = FilePath(\"/MultiplyByTwo-\\(constResult)\")\n        try await engine.fileSystem.write(resultPath, constResult * 2)\n        return resultPath\n    }\n}\n\nprivate struct AddThirty: CachingQuery {\n    let x: Int\n\n    func run(engine: QueryEngine) async throws -> FilePath {\n        let constPath = try await engine[Const(x: self.x)].path\n        let constResult = try await engine.fileSystem.read(constPath, as: Int.self)\n\n        let resultPath = FilePath(\"/AddThirty-\\(constResult)\")\n        try await engine.fileSystem.write(resultPath, constResult + 30)\n        return resultPath\n    }\n}\n\nprivate struct Expression: CachingQuery {\n    let x: Int\n    let y: Int\n\n    func run(engine: QueryEngine) async throws -> FilePath {\n        let multiplyPath = try await engine[MultiplyByTwo(x: self.x)].path\n        let addThirtyPath = try await engine[AddThirty(x: self.y)].path\n\n        let multiplyResult = try await engine.fileSystem.read(multiplyPath, as: Int.self)\n        let addThirtyResult = try await engine.fileSystem.read(addThirtyPath, as: Int.self)\n\n        let resultPath = FilePath(\"/Expression-\\(multiplyResult)-\\(addThirtyResult)\")\n        try await engine.fileSystem.write(resultPath, multiplyResult + addThirtyResult)\n        return resultPath\n    }\n}\n\nstruct QueryEngineTests {\n    @Test\n    func filePathHashing() throws {\n#if os(Windows)\n        let path = \"C:\\\\root\"\n#else\n        let path = \"/root\"\n#endif\n\n        let hashEncoder1 = HashEncoder<SHA256>()\n        try hashEncoder1.encode(FilePath(path))\n        let digest1 = hashEncoder1.finalize()\n\n        let hashEncoder2 = HashEncoder<SHA256>()\n        try hashEncoder2.encode(String(reflecting: FilePath.self))\n        try hashEncoder2.encode(path)\n        let digest2 = hashEncoder2.finalize()\n\n        #expect(digest1 == digest2)\n    }\n\n    @Test\n    func simpleCaching() async throws {\n        let observabilitySystem = ObservabilitySystem.makeForTesting()\n        let engine = QueryEngine(\n            MockFileSystem(),\n            observabilitySystem.topScope,\n            cacheLocation: .memory\n        )\n\n        var resultPath = try await engine[Expression(x: 1, y: 2)].path\n        var result = try await engine.fileSystem.read(resultPath, as: Int.self)\n\n        #expect(result == 34)\n\n        var cacheMisses = await engine.cacheMisses\n        #expect(cacheMisses == 5)\n\n        var cacheHits = await engine.cacheHits\n        #expect(cacheHits == 0)\n\n        resultPath = try await engine[Expression(x: 1, y: 2)].path\n        result = try await engine.fileSystem.read(resultPath, as: Int.self)\n        #expect(result == 34)\n\n        cacheMisses = await engine.cacheMisses\n        #expect(cacheMisses == 5)\n\n        cacheHits = await engine.cacheHits\n        #expect(cacheHits == 1)\n\n        resultPath = try await engine[Expression(x: 2, y: 1)].path\n        result = try await engine.fileSystem.read(resultPath, as: Int.self)\n        #expect(result == 35)\n\n        cacheMisses = await engine.cacheMisses\n        #expect(cacheMisses == 8)\n\n        cacheHits = await engine.cacheHits\n        #expect(cacheHits == 3)\n\n        resultPath = try await engine[Expression(x: 2, y: 1)].path\n        result = try await engine.fileSystem.read(resultPath, as: Int.self)\n        #expect(result == 35)\n\n        cacheMisses = await engine.cacheMisses\n        #expect(cacheMisses == 8)\n\n        cacheHits = await engine.cacheHits\n        #expect(cacheHits == 4)\n\n        try await engine.shutDown()\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/CycloneDXConverterTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct CycloneDXConverterTests {\n    @Test(\"convertToPedigree with nil commits\")\n    func convertToPedigreeWithNilCommits() async throws {\n        let originator = SBOMOriginator(commits: nil)\n        let result = try await CycloneDXConverter.convertToPedigree(from: originator)\n        #expect(result.commits == nil)\n    }\n\n    @Test(\"convertToPedigree with empty commits\")\n    func convertToPedigreeWithEmptyCommits() async throws {\n        let originator = SBOMOriginator(commits: [])\n        let result = try await CycloneDXConverter.convertToPedigree(from: originator)\n        let commits = try #require(result.commits)\n        #expect(commits.isEmpty)\n    }\n\n    @Test(\"convertToPedigree with single commit without authors\")\n    func convertToPedigreeWithSingleCommitNoAuthors() async throws {\n        let originator = SBOMOriginator(commits: [SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: nil,\n        )])\n        let result = try await CycloneDXConverter.convertToPedigree(from: originator)\n\n        let cdxCommits = try #require(result.commits)\n        #expect(cdxCommits.count == 1)\n\n        let cdxCommit = cdxCommits[0]\n        #expect(cdxCommit.uid == \"abc123\")\n        #expect(cdxCommit.url == \"https://github.com/swiftlang/swift-package-manager\")\n        #expect(cdxCommit.author == nil)\n    }\n\n    @Test(\"convertToPedigree with single commit with authors\")\n    func convertToPedigreeWithSingleCommitWithAuthors() async throws {\n        let originator = SBOMOriginator(commits: [\n            SBOMCommit(\n                sha: \"def456\",\n                repository: \"https://github.com/swiftlang/swift-package-manager\",\n                authors: [SBOMPerson(\n                    id: SBOMIdentifier(value: \"author1\"),\n                    name: \"John Doe\",\n                    email: \"john@example.com\"\n                )],\n            ),\n        ])\n\n        let result = try await CycloneDXConverter.convertToPedigree(from: originator)\n\n        let cdxCommits = try #require(result.commits)\n        #expect(cdxCommits.count == 1)\n\n        let cdxCommit = cdxCommits[0]\n        #expect(cdxCommit.uid == \"def456\")\n        #expect(cdxCommit.url == \"https://github.com/swiftlang/swift-package-manager\")\n\n        let cdxAuthor = try #require(cdxCommit.author)\n        #expect(cdxAuthor.name == \"John Doe\")\n        #expect(cdxAuthor.email == \"john@example.com\")\n    }\n\n    @Test(\"convertToPedigree with multiple commits\")\n    func convertToPedigreeWithMultipleCommits() async throws {\n        let author1 = SBOMPerson(\n            id: SBOMIdentifier(value: \"author1\"),\n            name: \"John Doe\",\n            email: \"john@example.com\"\n        )\n        let author2 = SBOMPerson(\n            id: SBOMIdentifier(value: \"author2\"),\n            name: \"Jane Smith\",\n            email: \"jane@example.com\"\n        )\n\n        let commit1 = SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: [author1],\n        )\n        let commit2 = SBOMCommit(\n            sha: \"def456\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: [author2],\n        )\n\n        let originator = SBOMOriginator(commits: [commit1, commit2])\n\n        let result = try await CycloneDXConverter.convertToPedigree(from: originator)\n\n        let cdxCommits = try #require(result.commits)\n        #expect(cdxCommits.count == 2)\n\n        let cdxCommit1 = cdxCommits[0]\n        #expect(cdxCommit1.uid == \"abc123\")\n        #expect(cdxCommit1.url == \"https://github.com/swiftlang/swift-package-manager\")\n        let cdxAuthor1 = try #require(cdxCommit1.author)\n        #expect(cdxAuthor1.name == \"John Doe\")\n\n        let cdxCommit2 = cdxCommits[1]\n        #expect(cdxCommit2.uid == \"def456\")\n        #expect(cdxCommit2.url == \"https://github.com/swiftlang/swift-package-manager\")\n        let cdxAuthor2 = try #require(cdxCommit2.author)\n        #expect(cdxAuthor2.name == \"Jane Smith\")\n    }\n\n    @Test(\"convertToPedigree uses first author only\")\n    func convertToPedigreeUsesFirstAuthorOnly() async throws {\n        let author1 = SBOMPerson(\n            id: SBOMIdentifier(value: \"author1\"),\n            name: \"John Doe\",\n            email: \"john@example.com\"\n        )\n        let author2 = SBOMPerson(\n            id: SBOMIdentifier(value: \"author2\"),\n            name: \"Jane Smith\",\n            email: \"jane@example.com\"\n        )\n\n        let commit = SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: [author1, author2],\n        )\n        let originator = SBOMOriginator(commits: [commit])\n        let result = try await CycloneDXConverter.convertToPedigree(from: originator)\n\n        let cdxCommits = try #require(result.commits)\n        #expect(cdxCommits.count == 1)\n        let cdxCommit = cdxCommits[0]\n        let cdxAuthor = try #require(cdxCommit.author)\n        #expect(cdxAuthor.name == \"John Doe\")\n        #expect(cdxAuthor.email == \"john@example.com\")\n    }\n\n    @Test(\n        \"convertToComponent with category\",\n        arguments: [\n            (SBOMComponent.Category.application, CycloneDXComponent.Category.application),\n            (.framework, .framework),\n            (.library, .library),\n            (.file, .file),\n        ]\n    )\n    func convertToComponentWithCategory(\n        sbomCategory: SBOMComponent.Category,\n        expectedCDXCategory: CycloneDXComponent.Category\n    ) async throws {\n        let component = SBOMComponent(\n            category: sbomCategory,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = try await CycloneDXConverter.convertToComponent(from: component)\n\n        #expect(result.type == expectedCDXCategory)\n        #expect(result.bomRef == \"test-id\")\n        #expect(result.name == \"TestComponent\")\n        #expect(result.version == \"1.0.0\")\n        #expect(result.scope == .required)\n        #expect(result.purl == \"pkg:swift/test@1.0.0\")\n    }\n\n    @Test(\n        \"convertToComponent with entity\",\n        arguments: [\n            (SBOMComponent.Entity.package, SBOMComponent.Entity.package.rawValue),\n            (.product, SBOMComponent.Entity.product.rawValue),\n        ]\n    )\n    func convertToComponentWithEntity(\n        sbomEntity: SBOMComponent.Entity,\n        sbomEntityString: String\n    ) async throws {\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .test,\n            entity: sbomEntity\n        )\n\n        let result = try await CycloneDXConverter.convertToComponent(from: component)\n\n        #expect(result.type == .library)\n        #expect(result.scope == .excluded)\n        #expect(result.bomRef == \"test-id\")\n        #expect(result.name == \"TestComponent\")\n        #expect(result.version == \"1.0.0\")\n        #expect(result.purl == \"pkg:swift/test@1.0.0\")\n        let properties = try #require(result.properties)\n        #expect(properties.count == 1)\n        #expect(properties[0].name == \"swift-entity\")\n        #expect(properties[0].value == sbomEntityString)\n    }\n\n    @Test(\n        \"convertToComponent with scope\",\n        arguments: [\n            (Optional(SBOMComponent.Scope.runtime), CycloneDXComponent.Scope.required),\n            (Optional(.optional), .optional),\n            (Optional(.test), .excluded),\n            (Optional<SBOMComponent.Scope>.none, .required),\n        ]\n    )\n    func convertToComponentWithScope(\n        sbomScope: SBOMComponent.Scope?,\n        expectedCDXScope: CycloneDXComponent.Scope\n    ) async throws {\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: sbomScope,\n            entity: .product\n        )\n\n        let result = try await CycloneDXConverter.convertToComponent(from: component)\n\n        #expect(result.type == .library)\n        #expect(result.scope == expectedCDXScope)\n        #expect(result.bomRef == \"test-id\")\n        #expect(result.name == \"TestComponent\")\n        #expect(result.version == \"1.0.0\")\n        #expect(result.purl == \"pkg:swift/test@1.0.0\")\n    }\n\n    @Test(\"convertToComponent with pedigree\")\n    func convertToComponentWithPedigree() async throws {\n        let originator = SBOMOriginator(commits: [\n            SBOMCommit(\n                sha: \"abc123\",\n                repository: \"https://github.com/swiftlang/swift-package-manager\",\n                authors: [\n                    SBOMPerson(\n                        id: SBOMIdentifier(value: \"author1\"),\n                        name: \"John Doe\",\n                        email: \"john@example.com\"\n                    ),\n                ],\n            ),\n        ])\n\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: originator,\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = try await CycloneDXConverter.convertToComponent(from: component)\n\n        #expect(result.type == .library)\n        #expect(result.bomRef == \"test-id\")\n        #expect(result.name == \"TestComponent\")\n        #expect(result.version == \"1.0.0\")\n        #expect(result.scope == .required)\n        #expect(result.purl == \"pkg:swift/test@1.0.0\")\n\n        let pedigree = try #require(result.pedigree)\n        let commits = try #require(pedigree.commits)\n        #expect(commits.count == 1)\n\n        let cdxCommit = commits[0]\n        #expect(cdxCommit.uid == \"abc123\")\n        #expect(cdxCommit.url == \"https://github.com/swiftlang/swift-package-manager\")\n\n        let cdxAuthor = try #require(cdxCommit.author)\n        #expect(cdxAuthor.name == \"John Doe\")\n        #expect(cdxAuthor.email == \"john@example.com\")\n    }\n\n    @Test(\"convertToDependency basic conversion\")\n    func convertToDependencyBasicConversion() async throws {\n        let result = try await CycloneDXConverter.convertToDependency(from:\n            SBOMRelationship(\n                id: SBOMIdentifier(value: \"dep-1\"),\n                parentID: SBOMIdentifier(value: \"parent-component\"),\n                childrenID: [\"child1\", \"child2\", \"child3\"].map { SBOMIdentifier(value: $0) }\n            )\n        )\n\n        #expect(result.ref == \"parent-component\")\n        #expect(result.dependsOn == [\"child1\", \"child2\", \"child3\"])\n    }\n\n    @Test(\"convertToDependency with empty children\")\n    func convertToDependencyWithEmptyChildren() async throws {\n        let result = try await CycloneDXConverter.convertToDependency(from:\n            SBOMRelationship(\n                id: SBOMIdentifier(value: \"dep-1\"),\n                parentID: SBOMIdentifier(value: \"parent-component\"),\n                childrenID: []\n            )\n        )\n        #expect(result.ref == \"parent-component\")\n        #expect(result.dependsOn.isEmpty)\n    }\n\n    @Test(\"convertToMetadata basic conversion\")\n    func convertToMetadataBasicConversion() async throws {\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: nil\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [primaryComponent], relationships: nil)\n        )\n\n        let result = try await CycloneDXConverter.convertToMetadata(from: document)\n\n        #expect(result.timestamp == \"2025-01-01T00:00:00Z\")\n        #expect(result.component.bomRef == \"primary-id\")\n        #expect(result.component.name == \"PrimaryApp\")\n        #expect(result.component.type == .application)\n        #expect(result.component.purl == \"pkg:swift/primary@1.0.0\")\n        #expect(result.component.version == \"1.0.0\")\n        #expect(result.tools == nil)\n    }\n\n    @Test(\"convertToMetadata with nil timestamp\")\n    func convertToMetadataWithNilTimestamp() async throws {\n        let metadata = SBOMMetadata(\n            timestamp: nil,\n            creators: nil\n        )\n        let primaryComponent = SBOMComponent(\n            category: .framework,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"2.0.0\"),\n            name: \"PrimaryFramework\",\n            version: SBOMComponent.Version(revision: \"2.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [primaryComponent], relationships: nil)\n        )\n\n        let result = try await CycloneDXConverter.convertToMetadata(from: document)\n\n        #expect(result.timestamp == nil)\n        #expect(result.component.bomRef == \"primary-id\")\n        #expect(result.component.name == \"PrimaryFramework\")\n        #expect(result.component.type == .framework)\n        #expect(result.component.purl == \"pkg:swift/primary@2.0.0\")\n        #expect(result.component.version == \"2.0.0\")\n        #expect(result.tools == nil)\n    }\n\n    @Test(\"convertToDocument with no components or dependencies\")\n    func convertToDocumentWithMinimalData() async throws {\n        let spec = SBOMSpec(spec: .cyclonedx)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: nil\n        )\n\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"urn:uuid:12345678-1234-1234-1234-123456789abc\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: nil)\n        )\n\n        let result = try await CycloneDXConverter.convertToDocument(from: document, spec: spec)\n\n        #expect(result.bomFormat == \"CycloneDX\")\n        #expect(result.specVersion == \"1.7\")\n        #expect(result.serialNumber == \"urn:uuid:12345678-1234-1234-1234-123456789abc\")\n        #expect(result.version == 1)\n        #expect(result.metadata.component.bomRef == \"primary-id\")\n        #expect(result.components?.isEmpty ?? false)\n        #expect(result.dependencies?.isEmpty ?? false)\n    }\n\n    @Test(\"convertToDocument with components and dependencies\")\n    func convertToDocumentWithComponentsAndDependencies() async throws {\n        let spec = SBOMSpec(spec: .cyclonedx)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: nil\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let component1 = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"lib1-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"lib1\", version: \"1.0.0\"),\n            name: \"Library1\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let component2 = SBOMComponent(\n            category: .framework,\n            id: SBOMIdentifier(value: \"framework1-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"framework1\", version: \"2.0.0\"),\n            name: \"Framework1\",\n            version: SBOMComponent.Version(revision: \"2.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .optional,\n            entity: .product\n        )\n        let dependency1 = SBOMRelationship(\n            id: SBOMIdentifier(value: \"dep-1\"),\n            parentID: SBOMIdentifier(value: \"primary-id\"),\n            childrenID: [\"lib1-id\", \"framework1-id\"].map { SBOMIdentifier(value: $0) }\n        )\n        let dependency2 = SBOMRelationship(\n            id: SBOMIdentifier(value: \"dep-2\"),\n            parentID: SBOMIdentifier(value: \"lib1-id\"),\n            childrenID: [\"framework1-id\"].map { SBOMIdentifier(value: $0) }\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"urn:uuid:12345678-1234-1234-1234-123456789abc\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(\n                components: [component1, component2],\n                relationships: [dependency1, dependency2]\n            )\n        )\n\n        let result = try await CycloneDXConverter.convertToDocument(from: document, spec: spec)\n\n        #expect(result.bomFormat == \"CycloneDX\")\n        #expect(result.specVersion == \"1.7\")\n        #expect(result.serialNumber == \"urn:uuid:12345678-1234-1234-1234-123456789abc\")\n        #expect(result.version == 1)\n\n        #expect(result.metadata.timestamp == \"2025-01-01T00:00:00Z\")\n        #expect(result.metadata.component.bomRef == \"primary-id\")\n        #expect(result.metadata.component.name == \"PrimaryApp\")\n\n        let components = try #require(result.components)\n        #expect(components.count == 2)\n\n        // Components are sorted by ID, so framework1-id comes before lib1-id\n        let cdxComponent1 = components[0]\n        #expect(cdxComponent1.bomRef == \"framework1-id\")\n        #expect(cdxComponent1.name == \"Framework1\")\n        #expect(cdxComponent1.type == .framework)\n        #expect(cdxComponent1.scope == .optional)\n\n        let cdxComponent2 = components[1]\n        #expect(cdxComponent2.bomRef == \"lib1-id\")\n        #expect(cdxComponent2.name == \"Library1\")\n        #expect(cdxComponent2.type == .library)\n        #expect(cdxComponent2.scope == .required)\n\n        let dependencies = try #require(result.dependencies)\n        #expect(dependencies.count == 2)\n\n        // Dependencies are sorted by relationship ID (dep-1 before dep-2)\n        // Children IDs are also sorted alphabetically for repeatability\n        let cdxDependency1 = dependencies[0]\n        #expect(cdxDependency1.ref == \"primary-id\")\n        #expect(cdxDependency1.dependsOn.sorted() == [\"framework1-id\", \"lib1-id\"])\n\n        let cdxDependency2 = dependencies[1]\n        #expect(cdxDependency2.ref == \"lib1-id\")\n        #expect(cdxDependency2.dependsOn == [\"framework1-id\"])\n    }\n\n    @Test(\"convertToDocument with empty components and dependencies\")\n    func convertToDocumentWithEmptyComponentsAndDependencies() async throws {\n        let spec = SBOMSpec(spec: .cyclonedx)\n\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: nil\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"urn:uuid:12345678-1234-1234-1234-123456789abc\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: [])\n        )\n        let result = try await CycloneDXConverter.convertToDocument(from: document, spec: spec)\n\n        #expect(result.bomFormat == \"CycloneDX\")\n        #expect(result.specVersion == \"1.7\")\n        #expect(result.serialNumber == \"urn:uuid:12345678-1234-1234-1234-123456789abc\")\n        #expect(result.version == 1)\n\n        let components = try #require(result.components)\n        #expect(components.isEmpty)\n\n        let dependencies = try #require(result.dependencies)\n        #expect(dependencies.isEmpty)\n    }\n\n    @Test(\"convertToMetadata with creators/tools\")\n    func convertToMetadataWithCreators() async throws {\n        let license1 = SBOMLicense(name: \"Apache-2.0\", url: \"https://www.apache.org/licenses/LICENSE-2.0\")\n        let license2 = SBOMLicense(name: \"MIT\", url: nil)\n        let tool1 = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-1\"),\n            name: \"SwiftPM\",\n            version: \"6.0.0\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"6.0.0\"),\n            licenses: [license1]\n        )\n        let tool2 = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-2\"),\n            name: \"Swift\",\n            version: \"5.9.0\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"Swift\", version: \"5.9.0\"),\n            licenses: [license2]\n        )\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: [tool1, tool2]\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: [])\n        )\n\n        let result = try await CycloneDXConverter.convertToMetadata(from: document)\n\n        #expect(result.timestamp == \"2025-01-01T00:00:00Z\")\n        #expect(result.component.bomRef == \"primary-id\")\n        #expect(result.component.name == \"PrimaryApp\")\n\n        let tools = try #require(result.tools)\n        #expect(tools.components.count == 2)\n\n        let cdxTool1 = tools.components[0]\n        #expect(cdxTool1.bomRef == \"tool-1\")\n        #expect(cdxTool1.name == \"SwiftPM\")\n        #expect(cdxTool1.version == \"6.0.0\")\n        #expect(cdxTool1.type == .application)\n        #expect(cdxTool1.scope == .excluded)\n        #expect(cdxTool1.purl == \"pkg:swift/github.com/swiftlang/SwiftPM@6.0.0\")\n        \n        let cdxTool1Licenses = try #require(cdxTool1.licenses)\n        #expect(cdxTool1Licenses.count == 1)\n        #expect(cdxTool1Licenses[0].license.id == \"Apache-2.0\")\n        #expect(cdxTool1Licenses[0].license.url == \"https://www.apache.org/licenses/LICENSE-2.0\")\n\n        let cdxTool2 = tools.components[1]\n        #expect(cdxTool2.bomRef == \"tool-2\")\n        #expect(cdxTool2.name == \"Swift\")\n        #expect(cdxTool2.version == \"5.9.0\")\n        #expect(cdxTool2.type == .application)\n        #expect(cdxTool2.scope == .excluded)\n        #expect(cdxTool2.purl == \"pkg:swift/github.com/swiftlang/Swift@5.9.0\")\n        \n        let cdxTool2Licenses = try #require(cdxTool2.licenses)\n        #expect(cdxTool2Licenses.count == 1)\n        #expect(cdxTool2Licenses[0].license.id == \"MIT\")\n        #expect(cdxTool2Licenses[0].license.url == nil)\n    }\n\n    @Test(\"convertToMetadata with empty creators\")\n    func convertToMetadataWithEmptyCreators() async throws {\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: []\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: [])\n        )\n\n        let result = try await CycloneDXConverter.convertToMetadata(from: document)\n\n        #expect(result.timestamp == \"2025-01-01T00:00:00Z\")\n        #expect(result.component.bomRef == \"primary-id\")\n        #expect(result.tools == nil)\n    }\n\n    @Test(\"convertToExternalReferences with nil entries\")\n    func convertToExternalReferencesWithNilEntries() async throws {\n        let originator = SBOMOriginator(commits: nil, entries: nil)\n        let result = try await CycloneDXConverter.convertToExternalReferences(from: originator)\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToExternalReferences with empty entries\")\n    func convertToExternalReferencesWithEmptyEntries() async throws {\n        let originator = SBOMOriginator(commits: nil, entries: [])\n        let result = try await CycloneDXConverter.convertToExternalReferences(from: originator)\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToExternalReferences with single entry with URL\")\n    func convertToExternalReferencesWithSingleEntryWithURL() async throws {\n        let url = try #require(URL(string: \"https://registry.example.com/packages/mypackage/1.0.0\"))\n        let entry = SBOMRegistryEntry(\n            url: url,\n            scope: \"example.scope\",\n            name: \"mypackage\",\n            version: \"1.0.0\"\n        )\n        let originator = SBOMOriginator(commits: nil, entries: [entry])\n        \n        let result = try await CycloneDXConverter.convertToExternalReferences(from: originator)\n        \n        #expect(result.count == 1)\n        let externalRef = result[0]\n        #expect(externalRef.url == url)\n        #expect(externalRef.refType == .distribution)\n    }\n\n    @Test(\"convertToExternalReferences with single entry without URL\")\n    func convertToExternalReferencesWithSingleEntryWithoutURL() async throws {\n        let entry = SBOMRegistryEntry(\n            url: nil,\n            scope: \"example.scope\",\n            name: \"mypackage\",\n            version: \"1.0.0\"\n        )\n        let originator = SBOMOriginator(commits: nil, entries: [entry])\n        \n        let result = try await CycloneDXConverter.convertToExternalReferences(from: originator)\n        \n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToExternalReferences with multiple entries all with URLs\")\n    func convertToExternalReferencesWithMultipleEntriesAllWithURLs() async throws {\n        let url1 = try #require(URL(string: \"https://registry.example.com/packages/package1/1.0.0\"))\n        let url2 = try #require(URL(string: \"https://registry.example.com/packages/package2/2.0.0\"))\n        let url3 = try #require(URL(string: \"https://registry.example.com/packages/package3/3.0.0\"))\n        \n        let entry1 = SBOMRegistryEntry(url: url1, scope: \"scope1\", name: \"package1\", version: \"1.0.0\")\n        let entry2 = SBOMRegistryEntry(url: url2, scope: \"scope2\", name: \"package2\", version: \"2.0.0\")\n        let entry3 = SBOMRegistryEntry(url: url3, scope: \"scope3\", name: \"package3\", version: \"3.0.0\")\n        \n        let originator = SBOMOriginator(commits: nil, entries: [entry1, entry2, entry3])\n        \n        let result = try await CycloneDXConverter.convertToExternalReferences(from: originator)\n        \n        #expect(result.count == 3)\n        #expect(result[0].url == url1)\n        #expect(result[0].refType == .distribution)\n        #expect(result[1].url == url2)\n        #expect(result[1].refType == .distribution)\n        #expect(result[2].url == url3)\n        #expect(result[2].refType == .distribution)\n    }\n\n    @Test(\"convertToExternalReferences with mixed entries (some with URLs, some without)\")\n    func convertToExternalReferencesWithMixedEntries() async throws {\n        let url1 = try #require(URL(string: \"https://registry.example.com/packages/package1/1.0.0\"))\n        let url3 = try #require(URL(string: \"https://registry.example.com/packages/package3/3.0.0\"))\n        \n        let entry1 = SBOMRegistryEntry(url: url1, scope: \"scope1\", name: \"package1\", version: \"1.0.0\")\n        let entry2 = SBOMRegistryEntry(url: nil, scope: \"scope2\", name: \"package2\", version: \"2.0.0\")\n        let entry3 = SBOMRegistryEntry(url: url3, scope: \"scope3\", name: \"package3\", version: \"3.0.0\")\n        let entry4 = SBOMRegistryEntry(url: nil, scope: \"scope4\", name: \"package4\", version: \"4.0.0\")\n        \n        let originator = SBOMOriginator(commits: nil, entries: [entry1, entry2, entry3, entry4])\n        \n        let result = try await CycloneDXConverter.convertToExternalReferences(from: originator)\n        \n        #expect(result.count == 2)\n        #expect(result[0].url == url1)\n        #expect(result[0].refType == .distribution)\n        #expect(result[1].url == url3)\n        #expect(result[1].refType == .distribution)\n    }\n\n    @Test(\"convertToExternalReferences with multiple entries all without URLs\")\n    func convertToExternalReferencesWithMultipleEntriesAllWithoutURLs() async throws {\n        let entry1 = SBOMRegistryEntry(url: nil, scope: \"scope1\", name: \"package1\", version: \"1.0.0\")\n        let entry2 = SBOMRegistryEntry(url: nil, scope: \"scope2\", name: \"package2\", version: \"2.0.0\")\n        let entry3 = SBOMRegistryEntry(url: nil, scope: \"scope3\", name: \"package3\", version: \"3.0.0\")\n        \n        let originator = SBOMOriginator(commits: nil, entries: [entry1, entry2, entry3])\n        \n        let result = try await CycloneDXConverter.convertToExternalReferences(from: originator)\n        \n        #expect(result.isEmpty)\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/PURLTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct PURLTests {\n    struct PURLStringTestCase {\n        let purl: PURL\n        let expectedString: String\n        let description: String\n    }\n\n    static let stringRepresentationTestCases: [PURLStringTestCase] = [\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: nil,\n                name: \"MyPackage\",\n                version: nil,\n                qualifiers: nil,\n                subpath: nil\n            ),\n            expectedString: \"pkg:swift/MyPackage\",\n            description: \"Basic PURL with scheme, type, and name only\"\n        ),\n\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: \"apple\",\n                name: \"swift-package-manager\",\n                version: nil,\n                qualifiers: nil,\n                subpath: nil\n            ),\n            expectedString: \"pkg:swift/apple/swift-package-manager\",\n            description: \"PURL with namespace\"\n        ),\n\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: nil,\n                name: \"MyPackage\",\n                version: \"1.0.0\",\n                qualifiers: nil,\n                subpath: nil\n            ),\n            expectedString: \"pkg:swift/MyPackage@1.0.0\",\n            description: \"PURL with version\"\n        ),\n\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: nil,\n                name: \"MyPackage\",\n                version: nil,\n                qualifiers: [\"arch\": \"arm64\"],\n                subpath: nil\n            ),\n            expectedString: \"pkg:swift/MyPackage?arch=arm64\",\n            description: \"PURL with single qualifier\"\n        ),\n\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: nil,\n                name: \"MyPackage\",\n                version: nil,\n                qualifiers: [\"os\": \"macos\", \"arch\": \"arm64\"],\n                subpath: nil\n            ),\n            expectedString: \"pkg:swift/MyPackage?arch=arm64&os=macos\",\n            description: \"PURL with multiple qualifiers\"\n        ),\n\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: nil,\n                name: \"MyPackage\",\n                version: nil,\n                qualifiers: nil,\n                subpath: \"Sources/MyModule\"\n            ),\n            expectedString: \"pkg:swift/MyPackage#Sources/MyModule\",\n            description: \"PURL with subpath\"\n        ),\n\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: \"apple\",\n                name: \"swift-package-manager\",\n                version: \"5.9.0\",\n                qualifiers: [\"arch\": \"arm64\", \"os\": \"macos\"],\n                subpath: \"Sources/PackageModel\"\n            ),\n            expectedString: \"pkg:swift/apple/swift-package-manager@5.9.0?arch=arm64&os=macos#Sources/PackageModel\",\n            description: \"Complete PURL with all components\"\n        ),\n\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: \"kitty\",\n                name: \"meowmeow\",\n                version: \"18.0.0\",\n                qualifiers: [:],\n                subpath: nil\n            ),\n            expectedString: \"pkg:swift/kitty/meowmeow@18.0.0\",\n            description: \"PURL with empty qualifiers dictionary\"\n        ),\n\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: nil,\n                name: \"MyPackage\",\n                version: nil,\n                qualifiers: nil,\n                subpath: \"Meow/MeowMeow/MeowMeowMeow/Meow/Meow.swift\"\n            ),\n            expectedString: \"pkg:swift/MyPackage#Meow/MeowMeow/MeowMeowMeow/Meow/Meow.swift\",\n            description: \"PURL with complex subpath\"\n        ),\n        // Test \"unknown\" version handling - should be omitted from string\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: nil,\n                name: \"MyPackage\",\n                version: \"unknown\",\n                qualifiers: nil,\n                subpath: nil\n            ),\n            expectedString: \"pkg:swift/MyPackage\",\n            description: \"PURL with 'unknown' version (should be omitted)\"\n        ),\n\n        // Test qualifier ordering - qualifiers should be sorted alphabetically\n        PURLStringTestCase(\n            purl: PURL(\n                scheme: \"pkg\",\n                type: \"swift\",\n                namespace: nil,\n                name: \"MyPackage\",\n                version: nil,\n                qualifiers: [\"zebra\": \"last\", \"alpha\": \"first\", \"middle\": \"mid\"],\n                subpath: nil\n            ),\n            expectedString: \"pkg:swift/MyPackage?alpha=first&middle=mid&zebra=last\",\n            description: \"PURL with qualifiers in alphabetical order\"\n        ),\n    ]\n\n    @Test(\"PURL string representation\", arguments: stringRepresentationTestCases)\n    func purlStringRepresentation(testCase: PURLStringTestCase) throws {\n        let actualString = testCase.purl.description\n        #expect(\n            actualString == testCase.expectedString,\n            \"Expected '\\(testCase.expectedString)' but got '\\(actualString)' for case \\(testCase.description)\"\n        )\n    }\n\n    // MARK: - CustomStringConvertible Protocol Conformance Tests\n\n    @Test(\"PURL conforms to CustomStringConvertible\")\n    func purlConformsToCustomStringConvertible() {\n        let purl = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            name: \"TestPackage\"\n        )\n\n        // Verify that PURL can be used as CustomStringConvertible\n        let _: CustomStringConvertible = purl\n\n        // Verify description property is accessible\n        let description = purl.description\n        #expect(!description.isEmpty)\n    }\n\n    @Test(\"PURL description is consistent\")\n    func purlDescriptionIsConsistent() {\n        let purl = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            namespace: \"github.com/apple\",\n            name: \"swift-package-manager\",\n            version: \"1.0.0\",\n            qualifiers: [\"os\": \"macos\"],\n            subpath: \"Sources\"\n        )\n\n        // Multiple calls to description should return the same value\n        let description1 = purl.description\n        let description2 = purl.description\n        #expect(description1 == description2)\n    }\n\n    @Test(\"PURL description can be used in string interpolation\")\n    func purlDescriptionInStringInterpolation() {\n        let purl = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            name: \"MyPackage\",\n            version: \"1.0.0\"\n        )\n\n        let interpolated = \"Package URL: \\(purl)\"\n        #expect(interpolated == \"Package URL: pkg:swift/MyPackage@1.0.0\")\n    }\n\n    @Test(\"PURL description handles special characters in components\")\n    func purlDescriptionWithSpecialCharacters() {\n        // Test with hyphens, underscores, and colons (common in package names)\n        let purl = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            namespace: \"github.com/my-org\",\n            name: \"my_package:product-name\",\n            version: \"1.0.0-beta.1\"\n        )\n\n        let description = purl.description\n        #expect(description.contains(\"my-org\"))\n        #expect(description.contains(\"my_package:product-name\"))\n        #expect(description.contains(\"1.0.0-beta.1\"))\n    }\n\n    @Test(\"PURL description with all nil optional components\")\n    func purlDescriptionWithAllNilOptionals() {\n        let purl = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            namespace: nil,\n            name: \"MinimalPackage\",\n            version: nil,\n            qualifiers: nil,\n            subpath: nil\n        )\n\n        #expect(purl.description == \"pkg:swift/MinimalPackage\")\n    }\n\n    @Test(\"PURL description format follows PURL specification\")\n    func purlDescriptionFollowsPURLSpec() {\n        let purl = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            namespace: \"github.com/apple\",\n            name: \"swift-package-manager\",\n            version: \"5.9.0\",\n            qualifiers: [\"arch\": \"arm64\"],\n            subpath: \"Sources/PackageModel\"\n        )\n\n        let description = purl.description\n\n        // Verify PURL format: scheme:type/namespace/name@version?qualifiers#subpath\n        #expect(description.hasPrefix(\"pkg:\"))\n        #expect(description.contains(\"swift/\"))\n        #expect(description.contains(\"github.com/apple/\"))\n        #expect(description.contains(\"swift-package-manager\"))\n        #expect(description.contains(\"@5.9.0\"))\n        #expect(description.contains(\"?arch=arm64\"))\n        #expect(description.contains(\"#Sources/PackageModel\"))\n    }\n\n    @Test(\"PURL description with multiple qualifiers maintains alphabetical order\")\n    func purlDescriptionQualifierOrdering() {\n        let purl = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            name: \"Package\",\n            qualifiers: [\n                \"zoo\": \"value1\",\n                \"apple\": \"value2\",\n                \"middle\": \"value3\",\n                \"beta\": \"value4\",\n            ]\n        )\n\n        let description = purl.description\n\n        // Verify qualifiers appear in alphabetical order\n        let qualifierPart = description.split(separator: \"?\").last?.split(separator: \"#\").first\n        #expect(qualifierPart == \"apple=value2&beta=value4&middle=value3&zoo=value1\")\n    }\n\n    @Test(\"PURL description equality matches struct equality\")\n    func purlDescriptionEqualityMatchesStructEquality() {\n        let purl1 = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            name: \"Package\",\n            version: \"1.0.0\"\n        )\n\n        let purl2 = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            name: \"Package\",\n            version: \"1.0.0\"\n        )\n\n        let purl3 = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            name: \"Package\",\n            version: \"2.0.0\"\n        )\n\n        // Equal PURLs should have equal descriptions\n        #expect(purl1 == purl2)\n        #expect(purl1.description == purl2.description)\n\n        // Different PURLs should have different descriptions\n        #expect(purl1 != purl3)\n        #expect(purl1.description != purl3.description)\n    }\n\n    @Test(\"PURL description with empty qualifiers dictionary is same as nil qualifiers\")\n    func purlDescriptionEmptyQualifiersEqualsNil() {\n        let purlWithNil = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            name: \"Package\",\n            qualifiers: nil\n        )\n\n        let purlWithEmpty = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            name: \"Package\",\n            qualifiers: [:]\n        )\n\n        // Both should produce the same description (no qualifiers section)\n        #expect(purlWithNil.description == purlWithEmpty.description)\n        #expect(purlWithNil == purlWithEmpty)\n        #expect(!purlWithNil.description.contains(\"?\"))\n        #expect(!purlWithEmpty.description.contains(\"?\"))\n    }\n\n    struct PURLNamespaceTestCase {\n        let location: String\n        let expectedNamespace: String?\n    }\n\n    static let packageNamespaceTestCases: [PURLNamespaceTestCase] = [\n        // HTTPS URLs with .git extension\n        PURLNamespaceTestCase(\n            location: \"https://github.com/apple/swift-system.git\",\n            expectedNamespace: \"github.com/apple\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"https://github.com/swiftlang/swift-llbuild.git\",\n            expectedNamespace: \"github.com/swiftlang\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"https://github.com/swiftlang/swift-package-manager.git\",\n            expectedNamespace: \"github.com/swiftlang\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"https://gitlab.com/myorg/mypackage.git\",\n            expectedNamespace: \"gitlab.com/myorg\"\n        ),\n        // HTTPS URLs without .git extension\n        PURLNamespaceTestCase(\n            location: \"https://github.com/apple/swift-system\",\n            expectedNamespace: \"github.com/apple\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"https://github.com/swiftlang/swift-llbuild\",\n            expectedNamespace: \"github.com/swiftlang\"\n        ),\n        // SSH URLs with .git extension\n        PURLNamespaceTestCase(\n            location: \"git@github.com:apple/swift-system.git\",\n            expectedNamespace: \"github.com/apple\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"git@gitlab.com:myorg/mypackage.git\",\n            expectedNamespace: \"gitlab.com/myorg\"\n        ),\n        // SSH URLs without .git extension\n        PURLNamespaceTestCase(\n            location: \"git@github.com:apple/swift-system\",\n            expectedNamespace: \"github.com/apple\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"git@github.com:swiftlang/swiftly\",\n            expectedNamespace: \"github.com/swiftlang\"\n        ),\n        // Registry identities\n        PURLNamespaceTestCase(\n            location: \"org.foo\",\n            expectedNamespace: \"org\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"com.example.package\",\n            expectedNamespace: \"com.example\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"scope.package-name\",\n            expectedNamespace: \"scope\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"mona.LinkedList\",\n            expectedNamespace: \"mona\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"org.swift.swift-package-manager\",\n            expectedNamespace: \"org.swift\"\n        ),\n        PURLNamespaceTestCase(\n            location: \"io.github.myorg.mypackage\",\n            expectedNamespace: \"io.github.myorg\"\n        ),\n        // Local file paths - should have no namespace (path goes in qualifier instead)\n        PURLNamespaceTestCase(\n            location: \"/Users/username/MyPackage\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"/swift-system\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"/path/to/package\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"/special.character/in/path.to/package\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"/path/to/MyLocalPackage\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"/path/to/git/repo\",\n            expectedNamespace: nil\n        ),\n        // Edge cases\n        PURLNamespaceTestCase(\n            location: \"\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"invalid\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"https://github.com/\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"git@github.com:\",\n            expectedNamespace: nil\n        ),\n        PURLNamespaceTestCase(\n            location: \"user@email.com\",\n            expectedNamespace: nil\n        ),\n    ]\n\n    @Test(\"Extract namespace\", arguments: packageNamespaceTestCases)\n    func extractNamespaceFromLocation(testCase: PURLNamespaceTestCase) async throws {\n        let version = SBOMComponent.Version(\n            revision: \"1.0.0\",\n            commit: SBOMCommit(sha: \"sha\", repository: testCase.location)\n        )\n        let actual = await PURL.extractNamespace(from: version)\n        #expect(actual == testCase.expectedNamespace)\n    }\n\n    @Test(\"Create PURL from ResolvedPackage\")\n    func createPURLFromResolvedPackage() async throws {\n        let packageIdentity = PackageIdentity.plain(\"swift-package-manager\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"TestModule\")\n        let package = SBOMTestModulesGraph.createPackage(\n            identity: packageIdentity,\n            displayName: \"swift-package-manager\",\n            path: \"/swift-package-manager\",\n            modules: [module],\n            products: []\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedPackage = SBOMTestModulesGraph.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedModule]),\n            products: []\n        )\n        \n        let purl = await PURL.from(package: resolvedPackage, version: SBOMComponent.Version(revision: \"1.0.0\", commit: nil))\n\n        #expect(purl.scheme == \"pkg\")\n        #expect(purl.type == \"swift\")\n        #expect(purl.namespace == nil)\n        #expect(purl.name == \"swift-package-manager\")\n        #expect(purl.version == \"1.0.0\")\n        #expect(purl.description == \"pkg:swift/swift-package-manager@1.0.0\")\n    }\n\n    @Test(\"Create PURL from ResolvedProduct with package location\")\n    func createPURLFromResolvedProduct() async throws {\n        let packageIdentity = PackageIdentity.plain(\"swift-package-manager\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"SwiftPMDataModel\")\n        let productType = ProductType.library(.automatic)\n        let product = try Product(\n            package: packageIdentity,\n            name: \"SwiftPMDataModel\",\n            type: productType,\n            modules: [module]\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedProduct = SBOMTestModulesGraph.createResolvedProduct(\n            packageIdentity: packageIdentity,\n            product: product,\n            modules: IdentifiableSet([resolvedModule])\n        )\n        \n        let purl = await PURL.from(\n            product: resolvedProduct,\n            version: SBOMComponent.Version(\n                revision: \"1.0.0\",\n                commit: SBOMCommit(sha: \"sha\", repository: \"https://github.com/swiftlang/swift-package-manager.git\")\n            )\n        )\n\n        #expect(purl.scheme == \"pkg\")\n        #expect(purl.type == \"swift\")\n        #expect(purl.namespace == \"github.com/swiftlang\")\n        #expect(purl.name == \"swift-package-manager:SwiftPMDataModel\")\n        #expect(purl.version == \"1.0.0\")\n        #expect(purl.description == \"pkg:swift/github.com/swiftlang/swift-package-manager:SwiftPMDataModel@1.0.0\")\n    }\n\n    @Test(\"Create PURL from ResolvedProduct with local package\")\n    func createPURLFromResolvedProductLocalPackage() async throws {\n        let packageIdentity = PackageIdentity.plain(\"swift-package-manager\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"SwiftPMDataModel\")\n        let productType = ProductType.library(.automatic)\n        let product = try Product(\n            package: packageIdentity,\n            name: \"SwiftPMDataModel\",\n            type: productType,\n            modules: [module]\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedProduct = SBOMTestModulesGraph.createResolvedProduct(\n            packageIdentity: packageIdentity,\n            product: product,\n            modules: IdentifiableSet([resolvedModule])\n        )\n        \n        let localPath = \"/Users/someuser/myCode/SwiftPM/\"\n        let purl = await PURL.from(\n            product: resolvedProduct,\n            version: SBOMComponent.Version(revision: \"1.0.0\", commit: SBOMCommit(sha: \"sha\", repository: localPath))\n        )\n\n        #expect(purl.scheme == \"pkg\")\n        #expect(purl.type == \"swift\")\n        #expect(purl.name == \"swift-package-manager:SwiftPMDataModel\")\n        #expect(purl.namespace == nil) // No namespace for local paths\n        #expect(purl.version == \"1.0.0\")\n        #expect(purl.qualifiers == [\"path\": localPath])\n        let actualDescription = purl.description\n        #expect(actualDescription == \"pkg:swift/swift-package-manager:SwiftPMDataModel@1.0.0?path=/Users/someuser/myCode/SwiftPM/\")\n    }\n\n    @Test(\"Create PURL from ResolvedProduct with SSH URL\")\n    func createPURLFromResolvedProductSSH() async throws {\n        let packageIdentity = PackageIdentity.plain(\"swiftly\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"swiftly\")\n        let productType = ProductType.library(.automatic)\n        let product = try Product(\n            package: packageIdentity,\n            name: \"swiftly\",\n            type: productType,\n            modules: [module]\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedProduct = SBOMTestModulesGraph.createResolvedProduct(\n            packageIdentity: packageIdentity,\n            product: product,\n            modules: IdentifiableSet([resolvedModule])\n        )\n        \n        let purl = await PURL.from(\n            product: resolvedProduct,\n            version: SBOMComponent.Version(\n                revision: \"1.0.0\",\n                commit: SBOMCommit(sha: \"sha\", repository: \"git@github.com:swiftlang/swiftly.git\")\n            )\n        )\n\n        #expect(purl.scheme == \"pkg\")\n        #expect(purl.type == \"swift\")\n        #expect(purl.namespace == \"github.com/swiftlang\")\n        #expect(purl.name == \"swiftly:swiftly\")\n        #expect(purl.version == \"1.0.0\")\n        #expect(purl.description == \"pkg:swift/github.com/swiftlang/swiftly:swiftly@1.0.0\")\n    }\n\n    @Test(\"Create PURL from registry package\")\n    func createPURLFromRegistryPackage() async throws {\n        let packageIdentity = PackageIdentity.plain(\"org.example.mypackage\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"MyPackage\")\n        let package = SBOMTestModulesGraph.createPackage(\n            identity: packageIdentity,\n            displayName: \"mypackage\",\n            path: \"/path/to/registry/packages/org.example.mypackage\",\n            modules: [module],\n            products: []\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedPackage = SBOMTestModulesGraph.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedModule]),\n            products: []\n        )\n        \n        let registryEntry = SBOMRegistryEntry(\n            url: URL(string: \"https://swift.org\"),\n            scope: \"org.example\",\n            name: \"mypackage\",\n            version: \"1.2.3\"\n        )\n        \n        let purl = await PURL.from(\n            package: resolvedPackage,\n            version: SBOMComponent.Version(\n                revision: \"1.2.3\",\n                commit: nil,\n                entry: registryEntry\n            )\n        )\n\n        #expect(purl.scheme == \"pkg\")\n        #expect(purl.type == \"swift\")\n        #expect(purl.namespace == \"org.example\")\n        #expect(purl.name == \"mypackage\")\n        #expect(purl.version == \"1.2.3\")\n        #expect(purl.qualifiers == nil)\n        #expect(purl.description == \"pkg:swift/org.example/mypackage@1.2.3\")\n    }\n\n    @Test(\"Create PURL from registry product\")\n    func createPURLFromRegistryProduct() async throws {\n        let packageIdentity = PackageIdentity.plain(\"com.company.networking\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"HTTPClient\")\n        let productType = ProductType.library(.automatic)\n        let product = try Product(\n            package: packageIdentity,\n            name: \"HTTPClient\",\n            type: productType,\n            modules: [module]\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedProduct = SBOMTestModulesGraph.createResolvedProduct(\n            packageIdentity: packageIdentity,\n            product: product,\n            modules: IdentifiableSet([resolvedModule])\n        )\n        \n        let registryEntry = SBOMRegistryEntry(\n            url: URL(string: \"https://swift.org\"),\n            scope: \"com.company\",\n            name: \"networking\",\n            version: \"2.0.0\"\n        )\n        \n        let purl = await PURL.from(\n            product: resolvedProduct,\n            version: SBOMComponent.Version(\n                revision: \"2.0.0\",\n                commit: nil,\n                entry: registryEntry\n            )\n        )\n\n        #expect(purl.scheme == \"pkg\")\n        #expect(purl.type == \"swift\")\n        #expect(purl.namespace == \"com.company\")\n        #expect(purl.name == \"networking:HTTPClient\")\n        #expect(purl.version == \"2.0.0\")\n        #expect(purl.qualifiers == nil)\n        #expect(purl.description == \"pkg:swift/com.company/networking:HTTPClient@2.0.0\")\n    }\n\n    @Test(\"Create PURL from single-scope registry package\")\n    func createPURLFromSingleScopeRegistryPackage() async throws {\n        let packageIdentity = PackageIdentity.plain(\"mona.LinkedList\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"LinkedList\")\n        let package = SBOMTestModulesGraph.createPackage(\n            identity: packageIdentity,\n            displayName: \"LinkedList\",\n            path: \"/path/to/registry/packages/mona.LinkedList\",\n            modules: [module],\n            products: []\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedPackage = SBOMTestModulesGraph.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedModule]),\n            products: []\n        )\n        \n        let registryEntry = SBOMRegistryEntry(\n            url: URL(string: \"https://swift.org\"),\n            scope: \"mona\",\n            name: \"LinkedList\",\n            version: \"3.1.4\"\n        )\n        \n        let purl = await PURL.from(\n            package: resolvedPackage,\n            version: SBOMComponent.Version(\n                revision: \"3.1.4\",\n                commit: nil,\n                entry: registryEntry\n            )\n        )\n\n        #expect(purl.scheme == \"pkg\")\n        #expect(purl.type == \"swift\")\n        #expect(purl.namespace == \"mona\")\n        #expect(purl.name == \"LinkedList\")\n        #expect(purl.version == \"3.1.4\")\n        #expect(purl.qualifiers == nil)\n        #expect(purl.description == \"pkg:swift/mona/LinkedList@3.1.4\")\n    }\n\n    @Test(\"Create PURL from registry package with hyphenated name\")\n    func createPURLFromRegistryPackageWithHyphenatedName() async throws {\n        let packageIdentity = PackageIdentity.plain(\"org.swift.swift-package-manager\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"SwiftPM\")\n        let package = SBOMTestModulesGraph.createPackage(\n            identity: packageIdentity,\n            displayName: \"swift-package-manager\",\n            path: \"/path/to/registry/packages/org.swift.swift-package-manager\",\n            modules: [module],\n            products: []\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedPackage = SBOMTestModulesGraph.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedModule]),\n            products: []\n        )\n        \n        let registryEntry = SBOMRegistryEntry(\n            url: URL(string: \"https://swift.org\"),\n            scope: \"org.swift\",\n            name: \"swift-package-manager\",\n            version: \"5.9.0\"\n        )\n        \n        let purl = await PURL.from(\n            package: resolvedPackage,\n            version: SBOMComponent.Version(\n                revision: \"5.9.0\",\n                commit: nil,\n                entry: registryEntry\n            )\n        )\n\n        #expect(purl.scheme == \"pkg\")\n        #expect(purl.type == \"swift\")\n        #expect(purl.namespace == \"org.swift\")\n        #expect(purl.name == \"swift-package-manager\")\n        #expect(purl.version == \"5.9.0\")\n        #expect(purl.qualifiers == nil)\n        #expect(purl.description == \"pkg:swift/org.swift/swift-package-manager@5.9.0\")\n    }\n\n    struct PURLQualifiersTestCase {\n        let location: String\n        let expectedQualifiers: [String: String]?\n    }\n\n    static let qualifiersTestCases: [PURLQualifiersTestCase] = [\n        // Local absolute paths should have path qualifier\n        PURLQualifiersTestCase(\n            location: \"/Users/jdoe/workspace/project/lib/foo.a\",\n            expectedQualifiers: [\"path\": \"/Users/jdoe/workspace/project/lib/foo.a\"]\n        ),\n        PURLQualifiersTestCase(\n            location: \"/Users/username/MyPackage\",\n            expectedQualifiers: [\"path\": \"/Users/username/MyPackage\"]\n        ),\n        PURLQualifiersTestCase(\n            location: \"/path/to/package\",\n            expectedQualifiers: [\"path\": \"/path/to/package\"]\n        ),\n        PURLQualifiersTestCase(\n            location: \"/swift-system\",\n            expectedQualifiers: [\"path\": \"/swift-system\"]\n        ),\n        // Remote URLs should have no qualifiers\n        PURLQualifiersTestCase(\n            location: \"https://github.com/apple/swift-system.git\",\n            expectedQualifiers: nil\n        ),\n        PURLQualifiersTestCase(\n            location: \"https://github.com/swiftlang/swift-package-manager\",\n            expectedQualifiers: nil\n        ),\n        PURLQualifiersTestCase(\n            location: \"git@github.com:apple/swift-system.git\",\n            expectedQualifiers: nil\n        ),\n        PURLQualifiersTestCase(\n            location: \"git@github.com:swiftlang/swiftly\",\n            expectedQualifiers: nil\n        ),\n        // Registry identities should have no qualifiers\n        PURLQualifiersTestCase(\n            location: \"org.foo\",\n            expectedQualifiers: nil\n        ),\n        PURLQualifiersTestCase(\n            location: \"com.example.package\",\n            expectedQualifiers: nil\n        ),\n        PURLQualifiersTestCase(\n            location: \"mona.LinkedList\",\n            expectedQualifiers: nil\n        ),\n        PURLQualifiersTestCase(\n            location: \"org.swift.swift-package-manager\",\n            expectedQualifiers: nil\n        ),\n        PURLQualifiersTestCase(\n            location: \"io.github.myorg.mypackage\",\n            expectedQualifiers: nil\n        ),\n        PURLQualifiersTestCase(\n            location: \"\",\n            expectedQualifiers: nil\n        ),\n    ]\n\n    @Test(\"Extract qualifiers\", arguments: qualifiersTestCases)\n    func extractQualifiersFromLocation(testCase: PURLQualifiersTestCase) async throws {\n        let commit = testCase.location.isEmpty ? nil : SBOMCommit(sha: \"sha\", repository: testCase.location)\n        let version = SBOMComponent.Version(revision: \"1.0.0\", commit: commit)\n        let actualQualifiers = await PURL.extractQualifiers(from: version)\n        #expect(\n            actualQualifiers == testCase.expectedQualifiers,\n            \"Expected \\(String(describing: testCase.expectedQualifiers)) but got \\(String(describing: actualQualifiers))\"\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMEncoderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.medium\n    )\n)\nstruct SBOMEncoderTests {\n    private func verifyJsonContentIsValid(at path: AbsolutePath, fileSystem: any FileSystem = localFileSystem, sourceLocation: SourceLocation = #_sourceLocation) throws {\n        try #require(fileSystem.exists(path), \"File should exist at \\(path)\", sourceLocation: sourceLocation)\n\n        let data = try fileSystem.readFileContents(path)\n        let jsonObject = try JSONSerialization.jsonObject(with: Data(data.contents))\n        #expect(jsonObject is [String: Any], \"File should contain valid JSON object\", sourceLocation: sourceLocation)\n    }\n\n    @Test(\"writeSBOMs creates output directory if it doesn't exist\")\n    func writeSBOMsCreatesOutputDirectory() async throws {\n        try await withTemporaryDirectory { tmpDir in\n            let outputDir = tmpDir.appending(\"output\")\n            \n            // Directory should not exist initially\n            #expect(!localFileSystem.exists(outputDir), \"Directory should not exist before test\")\n\n            let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n            let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n            let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n            let sbom = try await extractor.extractSBOM()\n            let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n            let outputs = try await encoder.writeSBOMs(specs: [.cyclonedx], outputDir: outputDir)\n\n            #expect(localFileSystem.exists(outputDir), \"Output directory should be created\")\n            #expect(!outputs.isEmpty, \"Output paths should not be empty\")\n        }\n    }\n\n    @Test(\"writeSBOMs generates files for multiple specs\")\n    func writeSBOMsGeneratesFilesForMultipleSpecs() async throws {\n        try await withTemporaryDirectory { tmpDir in\n            let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n            let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n            let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n            let sbom = try await extractor.extractSBOM()\n            let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n            let outputs = try await encoder.writeSBOMs(specs: [.cyclonedx, .spdx], outputDir: tmpDir)\n            \n            try #require(!outputs.isEmpty, \"Output paths should not be empty\")\n            let files = try localFileSystem.getDirectoryContents(tmpDir)\n            #expect(files.count == 2, \"Should generate two files for two specs\")\n\n            // Since test packages don't have real Git repos, the revision will be \"unknown\"\n            // Filenames include timestamps, so we need to check for patterns\n            let cycloneDXPattern = \"cyclonedx1-1.7-MyApp-unknown-all-\"\n            let spdxPattern = \"spdx3-3.0.1-MyApp-unknown-all-\"\n\n            let cycloneDXFile = try #require(\n                files.first { $0.hasPrefix(cycloneDXPattern) && $0.hasSuffix(\".json\") },\n                \"Should generate CycloneDX file\",\n            )\n            let spdxFile = try #require(\n                files.first { $0.hasPrefix(spdxPattern) && $0.hasSuffix(\".json\") },\n                \"Should generate SPDX file\",\n            )\n\n            try self.verifyJsonContentIsValid(at: tmpDir.appending(component: cycloneDXFile))\n            try self.verifyJsonContentIsValid(at: tmpDir.appending(component: spdxFile))\n        }\n    }\n\n    @Test(\"writeSBOMs with duplicate specs generates single file\")\n    func writeSBOMsWithDuplicateSpecsGeneratesSingleFile() async throws {\n        try await withTemporaryDirectory { tmpDir in\n            let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n            let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n            let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n            let sbom = try await extractor.extractSBOM()\n            let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n            let outputs = try await encoder.writeSBOMs(specs: [.cyclonedx, .cyclonedx1], outputDir: tmpDir)\n\n            let files = try localFileSystem.getDirectoryContents(tmpDir)\n            #expect(files.count == 1, \"Duplicate specs should result in single file\")\n            #expect(!outputs.isEmpty, \"Output paths should not be empty\")\n        }\n    }\n\n    @Test(\"writeSBOMs generates correct filename format\")\n    func writeSBOMsGeneratesCorrectFilenameFormat() async throws {\n        try await withTemporaryDirectory { tmpDir in\n            let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n            let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n            let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n            let sbom = try await extractor.extractSBOM()\n            let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n            let outputs = try await encoder.writeSBOMs(specs: [.cyclonedx], outputDir: tmpDir)\n\n            let files = try localFileSystem.getDirectoryContents(tmpDir)\n            #expect(files.count == 1)\n\n            let filename = files[0]\n            // Format: {spec}-{version}-{name}-{revision}-{filter}-{timestamp}.json\n            // Example: cyclonedx1-1.7-swiftly-unknown-all-2025-01-15T12_30_45Z.json\n            let pattern = #\"^cyclonedx1-1\\.7-swiftly-[^-]+-all-\\d{4}-\\d{2}-\\d{2}T\\d{2}_\\d{2}_\\d{2}Z\\.json$\"#\n            let regex = try Regex(pattern)\n            #expect(filename.contains(regex), \"Filename should match expected format with timestamp: \\(filename)\")\n            #expect(!outputs.isEmpty, \"Output paths should not be empty\")\n        }\n    }\n\n    @Test(\"encodeSBOM with outputDir writes file\")\n    func encodeSBOMWithOutputDirWritesFile() async throws {\n        try await withTemporaryDirectory { tmpDir in\n            let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n            let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n            let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n            let sbom = try await extractor.extractSBOM()\n            let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n            let spec = SBOMSpec(spec: .cyclonedx1)\n\n            let _ = try await encoder.encodeSBOM(spec: spec, outputDir: tmpDir)\n\n            let files = try localFileSystem.getDirectoryContents(tmpDir)\n            #expect(files.count == 1, \"Should write exactly one file\")\n        }\n    }\n\n    @Test(\n        \"writeSBOMs integration test\",\n        arguments: [\"SPM\", \"Swiftly\"]\n    )\n    func writeSBOMsIntegrationTest(graphName: String) async throws {\n        try await withTemporaryDirectory { tmpDir in\n            let graph: ModulesGraph\n            let store: ResolvedPackagesStore\n            \n            switch graphName {\n            case \"SPM\":\n                graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n                store = try SBOMTestStore.createSPMResolvedPackagesStore()\n            case \"Swiftly\":\n                graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n                store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n            default:\n                fatalError(\"Unknown graph name: \\(graphName)\")\n            }\n            \n            let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n            let sbom = try await extractor.extractSBOM()\n            let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n            let _ = try await encoder.writeSBOMs(specs: [.cyclonedx, .spdx], outputDir: tmpDir)\n\n            let files = try localFileSystem.getDirectoryContents(tmpDir)\n            #expect(files.count == 2, \"Should generate both CycloneDX and SPDX files\")\n\n            // Verify both files are valid\n            for filename in files {\n                let filePath = tmpDir.appending(component: filename)\n                try self.verifyJsonContentIsValid(at: filePath)\n            }\n        }\n    }\n}\n\n// MARK: - InMemoryFileSystem Tests\nextension SBOMEncoderTests {\n    @Test(\"writeSBOMs with InMemoryFileSystem creates directory\")\n    func writeSBOMsWithInMemoryFileSystemCreatesDirectory() async throws {\n        let fs = InMemoryFileSystem()\n        let outputDir = try AbsolutePath(validating: \"/output\")\n        \n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let sbom = try await extractor.extractSBOM()\n        let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n        let outputs = try await encoder.writeSBOMs(specs: [.cyclonedx], outputDir: outputDir, fileSystem: fs)\n\n        #expect(fs.exists(outputDir), \"Output directory should be created in InMemoryFileSystem\")\n        #expect(!outputs.isEmpty, \"Output paths should not be empty\")\n        \n        // Verify file was written to in-memory filesystem\n        let files = try fs.getDirectoryContents(outputDir)\n        #expect(files.count == 1, \"Should write exactly one file\")\n    }\n\n    @Test(\"writeSBOMs with InMemoryFileSystem writes valid JSON\")\n    func writeSBOMsWithInMemoryFileSystemWritesValidJSON() async throws {\n        let fs = InMemoryFileSystem()\n        let outputDir = try AbsolutePath(validating: \"/output\")\n        \n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let sbom = try await extractor.extractSBOM()\n        let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n        let outputs = try await encoder.writeSBOMs(specs: [.cyclonedx], outputDir: outputDir, fileSystem: fs)\n\n        #expect(!outputs.isEmpty, \"Output paths should not be empty\")\n        \n        // Verify the file content is valid JSON\n        let outputPath = outputs[0].path\n        try self.verifyJsonContentIsValid(at: outputPath, fileSystem: fs)\n    }\n\n    @Test(\"writeSBOMs with InMemoryFileSystem handles multiple specs\")\n    func writeSBOMsWithInMemoryFileSystemHandlesMultipleSpecs() async throws {\n        let fs = InMemoryFileSystem()\n        let outputDir = try AbsolutePath(validating: \"/output\")\n        \n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let sbom = try await extractor.extractSBOM()\n        let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n        let outputs = try await encoder.writeSBOMs(specs: [.cyclonedx, .spdx], outputDir: outputDir, fileSystem: fs)\n\n        #expect(outputs.count == 2, \"Should generate two output paths\")\n        \n        let files = try fs.getDirectoryContents(outputDir)\n        #expect(files.count == 2, \"Should write two files to InMemoryFileSystem\")\n        \n        // Verify both files are valid JSON\n        for output in outputs {\n            try self.verifyJsonContentIsValid(at: output.path, fileSystem: fs)\n        }\n    }\n\n    @Test(\"encodeSBOM with InMemoryFileSystem writes file\")\n    func encodeSBOMWithInMemoryFileSystemWritesFile() async throws {\n        let fs = InMemoryFileSystem()\n        let outputDir = try AbsolutePath(validating: \"/output\")\n        \n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let sbom = try await extractor.extractSBOM()\n        let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n        let spec = SBOMSpec(spec: .cyclonedx1)\n\n        let outputPath = try await encoder.encodeSBOM(spec: spec, outputDir: outputDir, fileSystem: fs)\n\n        #expect(fs.exists(outputPath), \"File should exist in InMemoryFileSystem\")\n        try self.verifyJsonContentIsValid(at: outputPath, fileSystem: fs)\n    }\n\n    @Test(\"writeSBOMs with InMemoryFileSystem isolates test from filesystem\")\n    func writeSBOMsWithInMemoryFileSystemIsolatesTestFromFilesystem() async throws {\n        let fs = InMemoryFileSystem()\n        let outputDir = try AbsolutePath(validating: \"/isolated-test-output\")\n        \n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let sbom = try await extractor.extractSBOM()\n        let encoder = SBOMEncoder(sbom: sbom, observabilityScope: ObservabilitySystem.makeForTesting().topScope)\n\n        let outputs = try await encoder.writeSBOMs(specs: [.cyclonedx, .spdx], outputDir: outputDir, fileSystem: fs)\n\n        // Verify files exist in InMemoryFileSystem\n        #expect(fs.exists(outputDir), \"Directory should exist in InMemoryFileSystem\")\n        #expect(outputs.count == 2, \"Should generate two files\")\n        \n        // Verify files do NOT exist on actual filesystem\n        #expect(!localFileSystem.exists(outputDir), \"Directory should NOT exist on actual filesystem\")\n        \n        // Verify we can read from InMemoryFileSystem\n        let files = try fs.getDirectoryContents(outputDir)\n        #expect(files.count == 2, \"Should have two files in InMemoryFileSystem\")\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMExtractCategoryTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct SBOMExtractCategoryTests {\n    // MARK: - Product Category Tests\n\n    struct ProductCategoryTestCase {\n        let productType: ProductType\n        let moduleType: Module.Kind\n        let expectedCategory: SBOMComponent.Category\n        let description: String\n    }\n\n    static let productCategoryTestCases: [ProductCategoryTestCase] = [\n        ProductCategoryTestCase(\n            productType: .executable,\n            moduleType: .executable,\n            expectedCategory: .application,\n            description: \"executable\"\n        ),\n        ProductCategoryTestCase(\n            productType: .library(.automatic),\n            moduleType: .library,\n            expectedCategory: .library,\n            description: \"library\"\n        ),\n        ProductCategoryTestCase(\n            productType: .test,\n            moduleType: .test,\n            expectedCategory: .library,\n            description: \"test\"\n        ),\n        ProductCategoryTestCase(\n            productType: .snippet,\n            moduleType: .library,\n            expectedCategory: .library,\n            description: \"snippet\"\n        ),\n        ProductCategoryTestCase(\n            productType: .plugin,\n            moduleType: .library,\n            expectedCategory: .library,\n            description: \"plugin\"\n        ),\n        ProductCategoryTestCase(\n            productType: .macro,\n            moduleType: .library,\n            expectedCategory: .library,\n            description: \"macro\"\n        ),\n    ]\n\n    @Test(\"extractCategoryFromProduct\", arguments: productCategoryTestCases)\n    func extractCategoryFromProduct(testCase: ProductCategoryTestCase) throws {\n        let resolvedProduct = try SBOMTestModulesGraph.createProduct(\n            name: \"MyProduct\",\n            type: testCase.productType,\n            moduleType: testCase.moduleType\n        )\n        let category = try SBOMExtractor.extractCategory(from: resolvedProduct)\n        #expect(category == testCase.expectedCategory)\n    }\n\n    // MARK: - Package Category Tests\n\n    struct PackageCategoryTestCase {\n        let productTypes: [(ProductType, Module.Kind?)]\n        let expectedCategory: SBOMComponent.Category\n        let description: String\n    }\n\n    static let packageCategoryTestCases: [PackageCategoryTestCase] = [\n        PackageCategoryTestCase(\n            productTypes: [(.executable, .executable)],\n            expectedCategory: .application,\n            description: \"executable product\"\n        ),\n        PackageCategoryTestCase(\n            productTypes: [(.library(.automatic), nil), (.library(.dynamic), nil)],\n            expectedCategory: .library,\n            description: \"only library products\"\n        ),\n        PackageCategoryTestCase(\n            productTypes: [(.library(.automatic), nil), (.executable, .executable)],\n            expectedCategory: .application,\n            description: \"mixed products with executable\"\n        ),\n        PackageCategoryTestCase(\n            productTypes: [(.test, .test)],\n            expectedCategory: .library,\n            description: \"test product\"\n        ),\n        PackageCategoryTestCase(\n            productTypes: [(.snippet, nil)],\n            expectedCategory: .library,\n            description: \"snippet product\"\n        ),\n        PackageCategoryTestCase(\n            productTypes: [(.plugin, nil)],\n            expectedCategory: .library,\n            description: \"plugin product\"\n        ),\n        PackageCategoryTestCase(\n            productTypes: [(.macro, nil)],\n            expectedCategory: .library,\n            description: \"macro product\"\n        ),\n        PackageCategoryTestCase(\n            productTypes: [(.executable, .executable), (.executable, .executable)],\n            expectedCategory: .application,\n            description: \"multiple executables\"\n        ),\n        PackageCategoryTestCase(\n            productTypes: [(.library(.automatic), nil), (.executable, .executable), (.test, .test), (.plugin, nil)],\n            expectedCategory: .application,\n            description: \"all product types with executable\"\n        ),\n    ]\n\n    @Test(\"extractCategoryFromPackage\", arguments: packageCategoryTestCases)\n    func extractCategoryFromPackage(testCase: PackageCategoryTestCase) throws {\n        var products: [ResolvedProduct] = []\n        for (index, (productType, moduleType)) in testCase.productTypes.enumerated() {\n            let product = try SBOMTestModulesGraph.createProduct(\n                name: \"Product\\(index)\",\n                type: productType,\n                moduleType: moduleType ?? .library\n            )\n            products.append(product)\n        }\n        \n        let resolvedPackage = try SBOMTestModulesGraph.createPackage(\n            name: \"TestPackage\",\n            products: products\n        )\n        let category = try SBOMExtractor.extractCategory(from: resolvedPackage)\n        #expect(category == testCase.expectedCategory)\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMExtractComponentsTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\nimport PackageRegistry\n@testable import SBOMModel\nimport Testing\nimport class TSCBasic.Process\n\nimport enum TSCUtility.Git\nimport struct TSCUtility.Version\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.medium\n    )\n)\nstruct SBOMExtractComponentsTests {\n\n    private func verifyComponents(\n        components: [SBOMComponent],\n        graph: ModulesGraph,\n        expectations: SBOMTestCase.TestExpectations,\n        filter: Filter = .all,\n        product: String? = nil\n    ) {\n        let isFullExtraction = filter == .all && product == nil\n        verifyComponentCounts(components, expectations: expectations, isFullExtraction: isFullExtraction)\n        verifyPackageIds(components, expectations: expectations, isFullExtraction: isFullExtraction)\n        verifyRootProducts(components, expectations: expectations, filter: filter, product: product)\n        verifyComponentProperties(components, filter: filter)\n    }\n    \n    private func verifyComponentCounts(\n        _ components: [SBOMComponent],\n        expectations: SBOMTestCase.TestExpectations,\n        isFullExtraction: Bool,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) {\n        if isFullExtraction {\n            #expect(components.count == expectations.totalComponentCount, sourceLocation: sourceLocation)\n        } else {\n            #expect(components.count <= expectations.totalComponentCount, sourceLocation: sourceLocation)\n        }\n    }\n    \n    private func verifyPackageIds(\n        _ components: [SBOMComponent],\n        expectations: SBOMTestCase.TestExpectations,\n        isFullExtraction: Bool,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) {\n        let componentPackageIds = Set(components.compactMap { component in\n            component.id.value.components(separatedBy: \":\").first\n        })\n        if isFullExtraction {\n            #expect(componentPackageIds == expectations.expectedPackageIds, \"Package IDs did not match\", sourceLocation: sourceLocation)\n        } else {\n            #expect(componentPackageIds.isSubset(of: expectations.expectedPackageIds), \"Package IDs should be a subset\", sourceLocation: sourceLocation)\n        }\n    }\n\n    private func verifyRootPackage(\n        _ components: [SBOMComponent],\n        expectations: SBOMTestCase.TestExpectations,\n        filter: Filter,\n        product: String?,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) {\n        let rootPackageComponent = components.first { $0.id.value == expectations.rootPackage && $0.entity == .package }\n        // If filter is product AND the primary component is a product, the root package should NOT be included\n        if let productName = product {\n            if filter == .product {\n                #expect(rootPackageComponent == nil, \"Root package should not be included when filter is .product and primary component '\\(productName)' is a product\", sourceLocation: sourceLocation)\n                return\n            }\n        } // else it's always included\n         #expect(rootPackageComponent != nil, \"Root package should be included\", sourceLocation: sourceLocation)\n    }\n    \n    private func verifyRootProducts(\n        _ components: [SBOMComponent],\n        expectations: SBOMTestCase.TestExpectations,\n        filter: Filter,\n        product: String?,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) {\n        let rootProducts = components.filter { $0.id.value.hasPrefix(expectations.rootPackagePrefix) }\n        let rootProductComponents = rootProducts.filter { $0.entity == .product }\n\n        if let productName = product {\n            // if product is primary component, it should always show up in components, regardless of filter\n            let targetProduct = rootProductComponents.first { $0.name == productName }\n            #expect(targetProduct != nil, \"Target product '\\(productName)' should be included\", sourceLocation: sourceLocation)\n        } else {\n            if filter == .all || filter == .product {\n                // expect all root products if filter is .all or .product, and primary component is root package\n                #expect(rootProducts.count == expectations.expectedRootProductCount, \"Filter.\\(filter) should include all root products\", sourceLocation: sourceLocation)\n                let rootProductNames = Set(rootProductComponents.map(\\.name))\n                #expect(rootProductNames == expectations.expectedRootProductNames, \"Root product names should match expectations\", sourceLocation: sourceLocation)\n            } else if filter == .package {\n                // no root products if filter is .package, and primary component is root package\n                #expect(rootProducts.count == 0, \"Filter.\\(filter) should include no root products\", sourceLocation: sourceLocation)\n            }\n        }\n    }\n    \n    private func verifyComponentProperties(_ components: [SBOMComponent], filter: Filter, sourceLocation: SourceLocation = #_sourceLocation) {\n        for component in components {\n            #expect(!component.id.value.isEmpty, \"Component ID should not be empty\", sourceLocation: sourceLocation)\n            #expect(!component.name.isEmpty, \"Component name should not be empty\", sourceLocation: sourceLocation)\n            #expect(!component.purl.description.isEmpty, \"Component PURL should not be empty\", sourceLocation: sourceLocation)\n            #expect(!component.version.revision.isEmpty, \"Component version should not be empty\", sourceLocation: sourceLocation)\n            #expect(\n                component.category == .application || component.category == .library,\n                \"Component category should be application or library\",\n                sourceLocation: sourceLocation\n            )\n            #expect(\n                component.scope == .runtime || component.scope == .test,\n                \"Component scope should be runtime or test\",\n                sourceLocation: sourceLocation\n            )\n        }\n    }\n\n    @Test(\"extractComponents with sample SPM ModulesGraph\")\n    func extractComponentsFromSPMModulesGraph() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        let components = try await extractor.extractDependencies().components\n        self.verifyComponents(components: components, graph: testCase.graph, expectations: testCase.expectations)\n    }\n\n    @Test(\"extractComponents with sample Swiftly ModulesGraph\")\n    func extractComponentsFromSwiftlyModulesGraph() async throws {\n        let testCase = try SBOMTestCase.createSwiftlyTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        let components = try await extractor.extractDependencies().components\n        self.verifyComponents(components: components, graph: testCase.graph, expectations: testCase.expectations)\n    }\n\n    @Test(\"extractComponents fails with empty root packages\")\n    func extractComponentsFailsWithEmptyRootPackages() async throws {\n        let emptyGraph = try ModulesGraph(\n            rootPackages: [],\n            rootDependencies: [],\n            packages: IdentifiableSet([]),\n            dependencies: [],\n            binaryArtifacts: [:]\n        )\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        await #expect(throws: SBOMExtractorError.self) {\n            let extractor = SBOMExtractor(modulesGraph: emptyGraph, dependencyGraph: nil, store: store)\n            _ = try await extractor.extractDependencies().components\n        }\n    }\n\n    @Test(\"extractComponents verifies commit extraction for non-main branch dependency\")\n    func extractComponentsForNonMainBranch() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        let components = try await extractor.extractDependencies().components\n\n        let swiftLLBuildComponent = components.first { component in\n            component.id.value == \"swift-llbuild\" || component.name == \"swift-llbuild\"\n        }\n\n        let component = try #require(swiftLLBuildComponent, \"swift-llbuild component should be found\")\n\n        let commits = try #require(\n            component.originator.commits,\n            \"swift-llbuild component should have commit information\"\n        )\n        #expect(!commits.isEmpty, \"swift-llbuild should have at least one commit\")\n\n        let commit = commits[0]\n        #expect(!commit.sha.isEmpty, \"Commit SHA should not be empty\")\n        \n        let expectedRepository = try testCase.store.getRepositoryURL(for: \"swift-llbuild\")\n        #expect(commit.repository == expectedRepository, \"Repository URL should match\")\n\n        let expectedMockRevision = SBOMTestStore.generateMockRevision(for: \"swift-llbuild\")\n        #expect(commit.sha == expectedMockRevision, \"Commit SHA should match the mock revision for swift-llbuild\")\n\n        #expect(\n            component.version.revision == commit.sha,\n            \"Component version should match commit SHA for branch-based dependency\"\n        )\n    }\n\n    @Test(\"extractComponents uses version tag when available for version, but keeps pedigree as commit sha\")\n    func extractComponentsUsesVersionTagWhenAvailable() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        let components = try await extractor.extractDependencies().components\n\n        // Find a version-based dependency (swift-argument-parser uses version \"1.5.1\")\n        let swiftSystemComponent = components.first { component in component.id.value == \"swift-system\" }\n\n        let versionComponent = try #require(swiftSystemComponent, \"component should be found\")\n\n        let commits = try #require(\n            versionComponent.originator.commits,\n            \"component should have commit information\"\n        )\n        #expect(!commits.isEmpty, \"component should have at least one commit\")\n\n        let commit = commits[0]\n        #expect(!commit.sha.isEmpty, \"Commit SHA should not be empty\")\n        \n        let expectedRepository = try testCase.store.getRepositoryURL(for: \"swift-system\")\n        #expect(\n            commit.repository == expectedRepository,\n            \"Repository URL should match\"\n        )\n\n        #expect(\n            versionComponent.version.revision == \"1.3.2\",\n            \"Component version should be the version tag for version-based dependency\"\n        )\n        #expect(\n            versionComponent.version.revision != commit.sha,\n            \"Component version should not be the commit SHA for version-based dependency\"\n        )\n    }\n\n    @Test(\"extractComponents with product filter\")\n    func extractComponentsWithProductFilter() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        let productName = \"SwiftPMDataModel\"\n        let components = try await extractor.extractDependencies(product: productName).components\n        let allComponents = try await extractor.extractDependencies().components\n\n        // Verify using the helper function\n        self.verifyComponents(\n            components: components,\n            graph: testCase.graph,\n            expectations: testCase.expectations,\n            filter: .all,\n            product: productName\n        )\n\n        #expect(components.count < allComponents.count)\n\n        let componentIDs = Set(components.map(\\.id.value))\n        #expect(components.count > 0)\n        #expect(components.count < allComponents.count)\n\n        let expectedComponentIDs: Set<String> = [\n            \"swift-toolchain-sqlite\", \"swift-certificates:X509\", \"swift-crypto\",\n            \"swift-tools-support-core\", \"swift-collections:Collections\",\n            \"swift-system\", \"swift-certificates\", \"swift-package-manager\",\n            \"swift-collections\", \"swift-system:SystemPackage\",\n            \"swift-collections:BitCollections\", \"swift-crypto:Crypto\",\n            \"swift-tools-support-core:SwiftToolsSupport-auto\", \"swift-asn1\",\n            \"swift-package-manager:SwiftPMDataModel\", \"swift-asn1:SwiftASN1\",\n            \"swift-toolchain-sqlite:SwiftToolchainCSQLite\", \"swift-crypto:_CryptoExtras\",\n        ]\n        #expect(componentIDs == expectedComponentIDs)\n\n        let componentIDsList = components.map(\\.id)\n        let uniqueIDs = Set(componentIDsList)\n        #expect(componentIDsList.count == uniqueIDs.count)\n    }\n\n    // MARK: - Revision Tests\n\n    @Test(\"Root package components should not have 'unknown' versions\")\n    func rootPackageComponentsShouldNotHaveUnknownVersions() async throws {\n        let (spmRepo, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let components = try await extractor.extractDependencies().components\n\n        let rootPackage = try #require(graph.rootPackages.first)\n        let rootPackageID = rootPackage.identity.description\n\n        let actualRevision = try spmRepo.getCurrentRevision().identifier\n\n        let rootComponents = components.filter { component in\n            component.id.value == rootPackageID || component.id.value.hasPrefix(\"\\(rootPackageID):\")\n        }\n\n        #expect(!rootComponents.isEmpty, \"Should have root package components\")\n\n        for component in rootComponents {\n            #expect(component.version.revision == actualRevision)\n            #expect(\n                component.originator.commits != nil,\n                \"Root package component '\\(component.id.value)' should have commit information\"\n            )\n            if let commits = component.originator.commits {\n                #expect(!commits.isEmpty)\n                #expect(commits[0].sha == actualRevision)\n            }\n        }\n    }\n\n    @Test(\"Root package components should include only origin remote in originator\")\n    func rootPackageComponentsShouldIncludeAllRemotesInOriginator() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        // Add a second remote to test multiple remotes\n        try await Process.checkNonZeroExit(\n            args: Git.tool,\n            \"-C\",\n            spmPath.pathString,\n            \"remote\",\n            \"add\",\n            \"upstream\",\n            \"https://github.com/fork/swift-package-manager.git\"\n        )\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let components = try await extractor.extractDependencies().components\n\n        let rootPackage = try #require(graph.rootPackages.first)\n        let rootPackageID = rootPackage.identity.description\n\n        let rootComponents = components.filter { component in\n            component.id.value == rootPackageID || component.id.value.hasPrefix(\"\\(rootPackageID):\")\n        }\n\n        #expect(!rootComponents.isEmpty, \"Should have root package components\")\n\n        for component in rootComponents {\n            let commits = try #require(\n                component.originator.commits,\n                \"Root package component '\\(component.id.value)' should have commit information\"\n            )\n            #expect(commits.count == 1)\n        }\n    }\n\n    // MARK: - Filter Tests\n    @Test(\"Filter.all includes all components\")\n    func filterAllIncludesAllComponents() async throws {\n        let testCase = try SBOMTestCase.createSimpleTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        let dependencies = try await extractor.extractDependencies(filter: .all)\n        \n        self.verifyComponents(\n            components: dependencies.components,\n            graph: testCase.graph,\n            expectations: testCase.expectations,\n            filter: .all\n        )\n    }\n    \n    @Test(\"Filter.product includes only product components and primary component\")\n    func filterProductIncludesOnlyProductsAndPrimaryComponent() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        \n        let dependencies = try await extractor.extractDependencies(filter: .product)\n        \n        self.verifyComponents(\n            components: dependencies.components,\n            graph: testCase.graph,\n            expectations: testCase.expectations,\n            filter: .product\n        )\n    }\n    \n    @Test(\"Filter.package includes only package components\")\n    func filterPackageIncludesOnlyPackages() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        let dependencies = try await extractor.extractDependencies(filter: .package)\n        self.verifyComponents(\n            components: dependencies.components,\n            graph: testCase.graph,\n            expectations: testCase.expectations,\n            filter: .package\n        )\n    }\n\n    @Test(\"Filter.all with SPM graph includes all entity types\")\n    func filterAllWithSPMGraph() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        let dependencies = try await extractor.extractDependencies(filter: .all)\n        self.verifyComponents(\n            components: dependencies.components,\n            graph: testCase.graph,\n            expectations: testCase.expectations,\n            filter: .all\n        )\n    }\n    \n\n    @Test(\"Filter.product with specific product contains only product components\")\n    func filterProductWithSpecificProduct() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        \n        let productName = \"SwiftPMPackageCollections\"\n        let dependencies = try await extractor.extractDependencies(product: productName, filter: .product)\n        self.verifyComponents(\n            components: dependencies.components,\n            graph: testCase.graph,\n            expectations: testCase.expectations,\n            filter: .product,\n            product: productName\n        )\n    }\n    \n    @Test(\"Filter.package with specific product contains only package components and product primary component\")\n    func filterPackageWithSpecificProduct() async throws {\n        let testCase = try SBOMTestCase.createSPMTestCase()\n        let extractor = SBOMExtractor(modulesGraph: testCase.graph, dependencyGraph: nil, store: testCase.store)\n        \n        let productName = \"SwiftPMPackageCollections\"\n        let dependencies = try await extractor.extractDependencies(product: productName, filter: .package)\n        self.verifyComponents(\n            components: dependencies.components,\n            graph: testCase.graph,\n            expectations: testCase.expectations,\n            filter: .package,\n            product: productName\n        )\n    }\n\n    // MARK: - Mock Registry Tests\n    \n    @Test(\"extractComponents from mock registry package\")\n    func extractComponentsFromMockRegistryPackage() async throws {\n        let fs = InMemoryFileSystem()\n        \n        // Create mock registry\n        let registry = MockRegistry(\n            filesystem: fs,\n            identityResolver: DefaultIdentityResolver(),\n            checksumAlgorithm: MockHashAlgorithm(),\n            fingerprintStorage: MockPackageFingerprintStorage(),\n            signingEntityStorage: MockPackageSigningEntityStorage()\n        )\n        \n        // Setup registry package\n        let registryPackageIdentity: PackageIdentity = .plain(\"example.TestLibrary\")\n        let registryPackageVersion: Version = \"1.0.0\"\n        let registryPackageSource = InMemoryRegistryPackageSource(\n            fileSystem: fs,\n            path: .root.appending(components: \"registry\", \"server\", registryPackageIdentity.description)\n        )\n        try registryPackageSource.writePackageContent(\n            targets: [\"TestLibrary\"],\n            toolsVersion: .v5_9\n        )\n        \n        // Add package to registry\n        registry.addPackage(\n            identity: registryPackageIdentity,\n            versions: [registryPackageVersion],\n            sourceControlURLs: [URL(\"https://github.com/example/TestLibrary\")],\n            source: registryPackageSource\n        )\n        \n        // Create registry dependency package first\n        let registryModule = SBOMTestModulesGraph.createSwiftModule(\n            name: \"TestLibrary\",\n            type: .library\n        )\n        let registryProduct = try Product(\n            package: registryPackageIdentity,\n            name: \"TestLibrary\",\n            type: .library(.automatic),\n            modules: [registryModule]\n        )\n        let registryPackage = SBOMTestModulesGraph.createPackage(\n            identity: registryPackageIdentity,\n            displayName: \"TestLibrary\",\n            path: \"/registry/TestLibrary\",\n            modules: [registryModule],\n            products: [registryProduct]\n        )\n        \n        // Create resolved modules and products for registry package\n        let registryResolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: registryPackageIdentity,\n            module: registryModule\n        )\n        let registryResolvedProduct = SBOMTestModulesGraph.createResolvedProduct(\n            packageIdentity: registryPackageIdentity,\n            product: registryProduct,\n            modules: IdentifiableSet([registryResolvedModule])\n        )\n        \n        // Create a root package that depends on the registry package\n        let rootPackageIdentity = PackageIdentity.plain(\"MyApp\")\n        let rootModule = SBOMTestModulesGraph.createSwiftModule(\n            name: \"MyApp\",\n            type: .executable\n        )\n        let rootProduct = try Product(\n            package: rootPackageIdentity,\n            name: \"App\",\n            type: .executable,\n            modules: [rootModule]\n        )\n        let rootPackage = SBOMTestModulesGraph.createPackage(\n            identity: rootPackageIdentity,\n            displayName: \"MyApp\",\n            path: \"/MyApp\",\n            modules: [rootModule],\n            products: [rootProduct]\n        )\n        \n        // Create resolved modules with dependency on registry product\n        let rootResolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: rootPackageIdentity,\n            module: rootModule,\n            dependencies: [\n                .product(registryResolvedProduct, conditions: [])\n            ]\n        )\n        let rootResolvedProduct = SBOMTestModulesGraph.createResolvedProduct(\n            packageIdentity: rootPackageIdentity,\n            product: rootProduct,\n            modules: IdentifiableSet([rootResolvedModule])\n        )\n        \n        // Create resolved packages with registry metadata\n        let registryURL = URL(\"http://localhost/registry/mock\")\n        let registryMetadata = RegistryReleaseMetadata(\n            source: .registry(registryURL),\n            metadata: .init(\n                author: nil,\n                description: \"Test library from registry\",\n                licenseURL: nil,\n                readmeURL: nil,\n                scmRepositoryURLs: [SourceControlURL(\"https://github.com/example/TestLibrary\")]\n            ),\n            signature: nil\n        )\n        \n        let rootResolvedPackage = SBOMTestModulesGraph.createResolvedPackage(\n            package: rootPackage,\n            modules: IdentifiableSet([rootResolvedModule]),\n            products: [rootResolvedProduct],\n            dependencies: [registryPackageIdentity]\n        )\n        \n        let registryResolvedPackage = ResolvedPackage(\n            underlying: registryPackage,\n            defaultLocalization: nil,\n            supportedPlatforms: [],\n            dependencies: [],\n            enabledTraits: nil,\n            modules: IdentifiableSet([registryResolvedModule]),\n            products: [registryResolvedProduct],\n            registryMetadata: registryMetadata,\n            platformVersionProvider: PlatformVersionProvider(implementation: .minimumDeploymentTargetDefault)\n        )\n        \n        // Create package references\n        let registryPackageRef = PackageReference.registry(identity: registryPackageIdentity)\n        \n        // Create modules graph\n        let graph = try ModulesGraph(\n            rootPackages: [rootResolvedPackage],\n            rootDependencies: [registryResolvedPackage],\n            packages: IdentifiableSet([rootResolvedPackage, registryResolvedPackage]),\n            dependencies: [registryPackageRef],\n            binaryArtifacts: [:]\n        )\n        \n        // Create store with registry package\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        store.track(\n            packageRef: registryPackageRef,\n            state: .version(registryPackageVersion, revision: \"abc123\")\n        )\n        \n        // Extract components\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let components = try await extractor.extractDependencies().components\n        \n        // Verify components - should have root package, root product, registry package, and registry product\n        #expect(components.count >= 3, \"Should have at least root package, root product, and registry product\")\n        \n        // Find registry product component (not package - products are what get extracted as dependencies)\n        let registryProductComponent = components.first {\n            $0.id.value.contains(\"TestLibrary\") && $0.entity == .product\n        }\n        let foundRegistryProduct = try #require(registryProductComponent, \"Registry product component should be found. Available: \\(components.map { \"\\($0.id.value) (\\($0.entity))\" }.joined(separator: \", \"))\")\n        \n        // Verify registry product properties\n        #expect(foundRegistryProduct.name == \"TestLibrary\")\n        #expect(foundRegistryProduct.version.revision == \"1.0.0\")\n        #expect(foundRegistryProduct.entity == .product)\n        \n        // Find registry package component\n        let registryPackageComponent = components.first {\n            $0.id.value == registryPackageIdentity.description && $0.entity == .package\n        }\n        let foundRegistryPackage = try #require(registryPackageComponent, \"Registry package component should be found\")\n        \n        // Verify registry package properties\n        #expect(foundRegistryPackage.name == \"example.TestLibrary\")\n        #expect(foundRegistryPackage.version.revision == \"1.0.0\")\n        #expect(foundRegistryPackage.entity == .package)\n        \n        // Verify registry entry in version\n        let registryEntry = try #require(\n            foundRegistryPackage.version.entry,\n            \"Registry package should have registry entry\"\n        )\n        #expect(registryEntry.url == registryURL)\n        #expect(registryEntry.scope == \"example\")\n        #expect(registryEntry.name == \"TestLibrary\")\n        #expect(registryEntry.version == \"1.0.0\")\n        \n        // Verify registry entry in originator\n        let originatorEntries = try #require(\n            foundRegistryPackage.originator.entries,\n            \"Registry package should have originator entries\"\n        )\n        #expect(originatorEntries[0].url == registryURL)\n        \n        // Verify PURL is correct for registry package\n        let expectedPURL = PURL(\n            scheme: \"pkg\",\n            type: \"swift\",\n            namespace: \"example\",\n            name: \"TestLibrary\",\n            version: \"1.0.0\"\n        )\n        #expect(foundRegistryPackage.purl == expectedPURL)\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMExtractDependenciesTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Foundation\nimport PackageGraph\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.medium\n    )\n)\nstruct SBOMExtractDependenciesTests {\n\n    // MARK: - Helper Methods for Validation\n\n\n    private func detectCycles(in dependencies: [SBOMRelationship]) -> [String] {\n        var graph: [String: [String]] = [:]\n        for dependency in dependencies {\n            graph[dependency.parentID.value] = dependency.childrenID.map(\\.value)\n        }\n\n        var visited: Set<String> = []\n        var recursionStack: Set<String> = []\n        var cycles: [String] = []\n\n        func dfs(node: String, path: [String]) {\n            if recursionStack.contains(node) {\n                // Found a cycle - build the cycle path\n                if let cycleStart = path.firstIndex(of: node) {\n                    let cyclePath = (path[cycleStart...] + [node]).joined(separator: \" -> \")\n                    cycles.append(cyclePath)\n                }\n                return\n            }\n            if visited.contains(node) {\n                return\n            }\n            visited.insert(node)\n            recursionStack.insert(node)\n            if let children = graph[node] {\n                for child in children {\n                    dfs(node: child, path: path + [node])\n                }\n            }\n            recursionStack.remove(node)\n        }\n        for node in graph.keys {\n            if !visited.contains(node) {\n                dfs(node: node, path: [])\n            }\n        }\n        return cycles\n    }\n    \n    private func isProductID(_ id: String) -> Bool {\n        id.contains(\":\")\n    }\n    \n    private func isOwnProduct(childID: String, parentID: String) -> Bool {\n        childID.hasPrefix(parentID)\n    }\n    \n    private func validateOwnProductDependency(childID: String, parentID: String, sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(\n            isOwnProduct(childID: childID, parentID: parentID),\n            \"Package '\\(parentID)' product dependency '\\(childID)' should depend on '\\(parentID)'\",\n            sourceLocation: sourceLocation\n        )\n    }\n    \n    private func validatePackageDependency(childID: String, parentID: String, packageIDs: [String], sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(\n            packageIDs.contains(childID),\n            \"Package '\\(parentID)' package dependency '\\(childID)' should be a valid package\",\n            sourceLocation: sourceLocation\n        )\n    }\n    \n    private func validateProductDependency(childID: String, parentID: String, sourceLocation: SourceLocation = #_sourceLocation) {\n        #expect(\n            isProductID(childID),\n            \"Product '\\(parentID)' should only depend on other products, but found package dependency '\\(childID)'\",\n            sourceLocation: sourceLocation\n        )\n    }\n    \n    private func validatePackageChildren(\n        dependency: SBOMRelationship,\n        rootPackageID: String,\n        packageIDs: [String],\n        filter: Filter = .all,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) {\n        for child in dependency.childrenID {\n            if isProductID(child.value) { // package-to-product\n                // root-package to root product is allowed when filter == .package or .product\n                if filter == .package && rootPackageID != dependency.parentID.value {\n                    #expect(!isProductID(child.value), \"Package \\(dependency.parentID) should only depend on packages when filter is .package'\", sourceLocation: sourceLocation)\n                    return\n                } else if filter == .product && rootPackageID != dependency.parentID.value {\n                    #expect(!isProductID(child.value), \"Package \\(dependency.parentID) should only depend on root products and not other products when filter is .product'\", sourceLocation: sourceLocation)\n                    return\n                }\n                validateOwnProductDependency(childID: child.value, parentID: dependency.parentID.value, sourceLocation: sourceLocation)\n            } else { // package-to-package\n                validatePackageDependency(childID: child.value, parentID: dependency.parentID.value, packageIDs: packageIDs, sourceLocation: sourceLocation)\n            }\n        }\n    }\n    \n    private func validateProductChildren(dependency: SBOMRelationship, sourceLocation: SourceLocation = #_sourceLocation) {\n        for child in dependency.childrenID { // product-to-product\n            validateProductDependency(childID: child.value, parentID: dependency.parentID.value, sourceLocation: sourceLocation)\n        }\n    }\n    \n    private func validateRootPackageChildren(\n        dependency: SBOMRelationship,\n        rootPackageID: String,\n        packageIDs: [String],\n        filter: Filter = .all,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) {\n        #expect(!dependency.childrenID.map(\\.value).contains(rootPackageID), sourceLocation: sourceLocation)\n        validatePackageChildren(dependency: dependency, rootPackageID: rootPackageID, packageIDs: packageIDs, filter: filter, sourceLocation: sourceLocation)\n    }\n    \n    private func verifyProductDependencies(\n        graph: ModulesGraph,\n        store: ResolvedPackagesStore,\n        dependencyGraph: [String: [String]]? = nil,\n        filter: Filter = .all,\n        product: String? = nil,\n        sourceLocation: SourceLocation = #_sourceLocation\n    ) async throws {\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: dependencyGraph, store: store)\n        let dependencies = try await #require(extractor.extractDependencies(product: product, filter: filter).relationships, sourceLocation: sourceLocation)\n        let rootPackage = try #require(graph.rootPackages.first, sourceLocation: sourceLocation)\n        let rootPackageID = SBOMExtractor.extractComponentID(from: rootPackage).value\n        let packageIDs = graph.packages.map(\\.identity.description)\n\n        #expect(!dependencies.isEmpty, sourceLocation: sourceLocation)\n\n        let parentIDs = dependencies.map(\\.parentID)\n        #expect(parentIDs.count == Set(parentIDs).count, \"Parent IDs should be unique\", sourceLocation: sourceLocation)\n\n        let cycles = self.detectCycles(in: dependencies)\n        #expect(cycles.isEmpty, \"Dependency graph should not contain cycles. Found: \\(cycles.joined(separator: \"; \"))\", sourceLocation: sourceLocation)\n\n        for dependency in dependencies {\n            #expect(!dependency.id.value.isEmpty, \"Dependency ID should not be empty\", sourceLocation: sourceLocation)\n            #expect(!dependency.parentID.value.isEmpty, \"Parent ID should not be empty\", sourceLocation: sourceLocation)\n            #expect(!dependency.childrenID.isEmpty, \"Children ID should not be empty\", sourceLocation: sourceLocation)\n\n            #expect(\n                !dependency.childrenID.map(\\.value).contains(dependency.parentID.value),\n                \"parent '\\(dependency.parentID.value)' should not depend on itself\",\n                sourceLocation: sourceLocation\n            )\n\n            if packageIDs.contains(dependency.parentID.value) { // package-to-product or package-to-package\n                validatePackageChildren(dependency: dependency, rootPackageID: rootPackageID, packageIDs: packageIDs, filter: filter, sourceLocation: sourceLocation)\n            } else {\n                // product-to-product\n                validateProductChildren(dependency: dependency, sourceLocation: sourceLocation)\n            }\n\n            if product == nil {\n                #expect(!dependency.childrenID.map(\\.value).contains(rootPackageID), sourceLocation: sourceLocation)\n            }\n        }\n    }\n\n    @Test(\"extractDependencies with sample SPM ModulesGraph\")\n    func extractDependenciesFromSPMModulesGraph() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        try await self.verifyProductDependencies(graph: graph, store: store)\n    }\n\n    @Test(\"extractDependencies with sample Swiftly ModulesGraph\")\n    func extractDependenciesFromSwiftlyModulesGraph() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n        try await self.verifyProductDependencies(graph: graph, store: store)\n    }\n\n    @Test(\"extractDependencies with product filter SwiftPMPackageCollections\")\n    func extractDependenciesWithProductFilter() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n\n        let productName = \"SwiftPMPackageCollections\"\n        try await self.verifyProductDependencies(graph: graph, store: store, product: productName)\n    }\n\n    @Test(\"extractDependencies with product filter SwiftPMDataModel\")\n    func extractDependenciesWithProductFilterSwiftPMDataModel() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n\n        let productName = \"SwiftPMDataModel\"\n        try await self.verifyProductDependencies(graph: graph, store: store, product: productName)\n    }\n\n    @Test(\"extractDependencies with simple test graph\")\n    func extractDependenciesFromSimpleGraph() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        try await self.verifyProductDependencies(graph: graph, store: store)\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let dependencies = try await #require(extractor.extractDependencies().relationships)\n\n        #expect(dependencies.count == 3, \"Simple graph should have exactly 3 dependency relationships\")\n\n        let myAppPackageDep = try #require(dependencies.first { $0.parentID.value == \"MyApp\" })\n        let utilsPackageDep = try #require(dependencies.first { $0.parentID.value == \"Utils\" })\n        let appProductDep = try #require(dependencies.first { $0.parentID.value == \"MyApp:App\" })\n\n        #expect(myAppPackageDep.childrenID.count == 2, \"MyApp package should have 2 dependencies\")\n        #expect(myAppPackageDep.childrenID.map(\\.value).contains(\"Utils\"), \"MyApp should depend on Utils package\")\n        #expect(\n            myAppPackageDep.childrenID.map(\\.value).contains(\"MyApp:App\"),\n            \"MyApp should depend on its own App product\"\n        )\n\n        #expect(utilsPackageDep.childrenID.count == 1, \"Utils package should have 1 dependency\")\n        #expect(\n            utilsPackageDep.childrenID.map(\\.value).contains(\"Utils:Utils\"),\n            \"Utils should depend on its own Utils product\"\n        )\n\n        #expect(appProductDep.childrenID.count == 1, \"App product should have 1 dependency\")\n        #expect(\n            appProductDep.childrenID.map(\\.value).contains(\"Utils:Utils\"),\n            \"App product should depend on Utils product\"\n        )\n    }\n\n    // MARK: - Build Graph Tests\n\n    @Test(\"extractDependencies with build graph for simple test graph\")\n    func extractDependenciesFromSimpleGraphWithBuildGraph() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let buildGraph = SBOMTestDependencyGraph.createSimpleDependencyGraph()\n\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: buildGraph, store: store)\n        let dependencies = try await #require(extractor.extractDependencies().relationships)\n\n        #expect(!dependencies.isEmpty, \"Should have dependencies when using build graph\")\n\n        try await self.verifyProductDependencies(graph: graph, store: store, dependencyGraph: buildGraph)\n\n        let myAppPackageDep = try #require(dependencies.first { $0.parentID.value == \"MyApp\" })\n        let utilsPackageDep = try #require(dependencies.first { $0.parentID.value == \"Utils\" })\n        let appProductDep = try #require(dependencies.first { $0.parentID.value == \"MyApp:App\" })\n\n        #expect(myAppPackageDep.childrenID.count == 2, \"MyApp package should have 2 dependencies\")\n        #expect(myAppPackageDep.childrenID.map(\\.value).contains(\"Utils\"), \"MyApp should depend on Utils package\")\n        #expect(\n            myAppPackageDep.childrenID.map(\\.value).contains(\"MyApp:App\"),\n            \"MyApp should depend on its own App product\"\n        )\n\n        #expect(utilsPackageDep.childrenID.count == 1, \"Utils package should have 1 dependency\")\n        #expect(\n            utilsPackageDep.childrenID.map(\\.value).contains(\"Utils:Utils\"),\n            \"Utils should depend on its own Utils product\"\n        )\n\n        #expect(appProductDep.childrenID.count == 1, \"App product should have 1 dependency\")\n        #expect(\n            appProductDep.childrenID.map(\\.value).contains(\"Utils:Utils\"),\n            \"App product should depend on Utils product\"\n        )\n    }\n\n    @Test(\"extractDependencies with build graph for SPM ModulesGraph\")\n    func extractDependenciesFromSPMModulesGraphWithBuildGraph() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let buildGraph = SBOMTestDependencyGraph.createSPMDependencyGraph()\n        try await self.verifyProductDependencies(graph: graph, store: store, dependencyGraph: buildGraph)\n    }\n\n    @Test(\"extractDependencies with build graph for Swiftly ModulesGraph\")\n    func extractDependenciesFromSwiftlyModulesGraphWithBuildGraph() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n        let buildGraph = SBOMTestDependencyGraph.createSwiftlyDependencyGraph()\n        try await self.verifyProductDependencies(graph: graph, store: store, dependencyGraph: buildGraph)\n    }\n\n    @Test(\"extractDependencies with build graph and product filter for SPM\")\n    func extractDependenciesWithBuildGraphAndProductFilterSPM() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let buildGraph = SBOMTestDependencyGraph.createSPMDependencyGraph()\n        let productName = \"SwiftPMPackageCollections\"\n        try await self.verifyProductDependencies(graph: graph, store: store, dependencyGraph: buildGraph, product: productName)\n    }\n\n    @Test(\"extractDependencies with build graph and product filter for Swiftly\")\n    func extractDependenciesWithBuildGraphAndProductFilterSwiftly() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n        let buildGraph = SBOMTestDependencyGraph.createSwiftlyDependencyGraph()\n        let productName = \"swiftly\"\n        try await self.verifyProductDependencies(graph: graph, store: store, dependencyGraph: buildGraph, product: productName)\n    }\n\n    @Test(\"extractDependencies with empty build graph falls back to ModulesGraph\")\n    func extractDependenciesWithEmptyBuildGraph() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        // Empty build graph - should fall back to ModulesGraph\n        let buildGraph: [String: [String]] = [:]\n        try await self.verifyProductDependencies(graph: graph, store: store, dependencyGraph: buildGraph)\n    }\n\n    @Test(\"extractDependencies with simple different build graph doesn't have some dependencies\")\n    func extractDependenciesWithSimpleDifferenntBuildGraph() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let buildGraph = SBOMTestDependencyGraph.createSimpleDifferentDependencyGraph()\n        try await self.verifyProductDependencies(graph: graph, store: store, dependencyGraph: buildGraph)\n    \n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: buildGraph, store: store)\n        let dependencies = try await #require(extractor.extractDependencies().relationships)\n\n        #expect(!dependencies.isEmpty, \"Should have dependencies when using build graph\")\n\n        let myAppPackageDep = try #require(dependencies.first { $0.parentID.value == \"MyApp\" })\n        #expect(myAppPackageDep.childrenID.count == 1, \"MyApp package should have 1 dependency\")\n        #expect(myAppPackageDep.childrenID.map(\\.value).contains(\"MyApp:App\"), \"MyApp should depend on App product\")\n\n        let appProductDep = dependencies.first { $0.parentID.value == \"MyApp:App\" }\n        #expect(appProductDep == nil, \"App product should not appear in dependencies as parent\")\n        let utilsPackageDep = dependencies.first { $0.parentID.value == \"Utils\" }\n        #expect(utilsPackageDep == nil, \"Utils package should not appear in dependencies as parent\")\n        let utilsProductDep = dependencies.first { $0.parentID.value == \"Utils:Util\" }\n        #expect(utilsProductDep == nil, \"Util product should not appear in dependencies as parent\")\n    }\n    \n    // MARK: - Filter Tests\n    \n    @Test(\"Filter.all tracks all relationships\")\n    func filterAllTracksAllRelationships() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        try await self.verifyProductDependencies(graph: graph, store: store)\n    }\n    \n    @Test(\"Filter.product tracks only product-to-product and cross-boundary relationships when primary component is package\")\n    func filterProductTracksOnlyProductRelationships() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()        \n        try await self.verifyProductDependencies(graph: graph, store: store, filter: .product, product: nil)\n    }\n    \n    @Test(\"Filter.package tracks only package-to-package relationships when primary component is package\")\n    func filterPackageTracksOnlyPackageRelationships() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()        \n        try await self.verifyProductDependencies(graph: graph, store: store, filter: .package, product: nil)\n    }\n\n    @Test(\"Filter.product tracks only product-to-product when primary component is product\")\n    func filterProductTracksOnlyProductRelationshipsForProduct() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        try await self.verifyProductDependencies(graph: graph, store: store, filter: .product, product: \"SwiftPMDataModel\")\n    }\n    \n    @Test(\"Filter.package tracks only package-to-package relationships and cross-boundary relationships when primary component is product\")\n    func filterPackageTracksOnlyPackageRelationshipsForProduct() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        try await self.verifyProductDependencies(graph: graph, store: store, filter: .package, product: \"SwiftPMDataModel\")\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMExtractMetadataTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct SBOMExtractMetadataTests {\n    @Test(\"extractMetadata good weather\")\n    func extractMetadataParameterized() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let metadata = try await extractor.extractMetadata()\n\n        let timestamp = try #require(metadata.timestamp)\n        #expect(!timestamp.isEmpty)\n\n        let formatter = ISO8601DateFormatter()\n        _ = try #require(formatter.date(from: timestamp))\n\n        let creators = try #require(metadata.creators)\n        #expect(creators.count == 1)\n        let creator = creators[0]\n        #expect(!creator.id.value.isEmpty)\n        #expect(creator.name == \"swift-package-manager\")\n        #expect(!creator.version.isEmpty)\n\n        let licenses = try #require(creator.licenses)\n        #expect(licenses.count == 1)\n        let license = licenses[0]\n        #expect(license.name == \"Apache-2.0\")\n        #expect(license.url == \"http://swift.org/LICENSE.txt\")\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMExtractPrimaryComponentTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageModel\n@testable import SBOMModel\nimport SourceControl\nimport Testing\nimport class TSCBasic.Process\nimport enum TSCUtility.Git\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct SBOMExtractPrimaryComponentTests {\n    @Test(\"extractPrimaryComponent from sample SwiftPM ModulesGraph\")\n    func extractPrimaryComponentFromSPMModulesGraph() async throws {\n        let (spmRepo, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractPrimaryComponent() }()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let expectedRevision = try spmRepo.getCurrentRevision().identifier\n\n        #expect(component.category == .application)\n        #expect(component.name == rootPackage.identity.description)\n        #expect(component.id.value == rootPackage.identity.description)\n        #expect(component.purl.description == \"pkg:swift/github.com/swiftlang/swift-package-manager@\\(expectedRevision)\")\n        #expect(component.version.revision == expectedRevision)\n        #expect(component.version.commit?.sha == expectedRevision)\n        #expect(component.version.commit?.repository == SBOMTestStore.swiftPMURL)\n        #expect(component.scope == .runtime)\n        #expect(component.description == rootPackage.description)\n\n        let commits = try #require(component.originator.commits)\n        #expect(commits.count == 1)\n        let firstCommit = try #require(commits.first)\n        #expect(firstCommit.sha == expectedRevision)\n        #expect(firstCommit.repository == SBOMTestStore.swiftPMURL)\n    }\n\n    @Test(\"extractPrimaryComponent from sample Swiftly ModulesGraph\")\n    func extractPrimaryComponentFromSwiftlyModulesGraph() async throws {\n        let (swiftlyRepo, swiftlyPath) = try SBOMTestRepo.setupSwiftlyTestRepo()\n        defer { try? SBOMTestRepo.cleanup(swiftlyPath) }\n\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph(rootPath: swiftlyPath.pathString)\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractPrimaryComponent() }()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let expectedRevision = try swiftlyRepo.getCurrentRevision().identifier\n\n        #expect(component.category == SBOMComponent.Category.application)\n        #expect(component.name == rootPackage.identity.description)\n        #expect(component.id.value == rootPackage.identity.description)\n        #expect(component.purl.description == \"pkg:swift/github.com/swiftlang/swiftly@v1.0.0\")\n        #expect(component.version.revision == \"v1.0.0\")\n        #expect(component.version.commit?.sha == expectedRevision)\n        #expect(component.version.commit?.repository == SBOMTestStore.swiftlyURL)\n        #expect(component.scope == .runtime)\n        #expect(component.description == rootPackage.description)\n        let commits = try #require(component.originator.commits)\n        #expect(commits.count == 1)\n        let firstCommit = try #require(commits.first)\n        #expect(firstCommit.sha == expectedRevision)\n        #expect(firstCommit.repository == SBOMTestStore.swiftlyURL)\n    }\n\n    @Test(\"extractComponent from product from primary component from sample SwiftPM ModulesGraph\")\n    func extractComponentFromProductFromSPMModulesGraph() async throws {\n        let (gitRepo, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let resolvedProduct = try #require(rootPackage.products.first { $0.name == \"SwiftPMDataModel\" })\n        let actualRevision = try gitRepo.getCurrentRevision().identifier\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(product: resolvedProduct) }()\n\n        #expect(component.category == SBOMComponent.Category.library)\n        #expect(component.name == \"SwiftPMDataModel\")\n        #expect(component.id.value == \"swift-package-manager:SwiftPMDataModel\")\n        #expect(component.version.revision == actualRevision)\n        #expect(component.scope == .runtime)\n        #expect(component.purl.description\n            .contains(\"pkg:swift/github.com/swiftlang/swift-package-manager:SwiftPMDataModel@\\(actualRevision)\"))\n        #expect(component.description == nil)\n        let commits = try #require(component.originator.commits)\n        #expect(commits.count == 1)\n        let firstCommit = try #require(commits.first)\n        #expect(firstCommit.sha == actualRevision)\n        #expect(firstCommit.repository == SBOMTestStore.swiftPMURL)\n    }\n\n    @Test(\"extractComponent from product from primary component from sample Swiftly ModulesGraph\")\n    func extractComponentFromProductFromSwiftlyModulesGraph() async throws {\n        let (swiftlyRepo, swiftlyPath) = try SBOMTestRepo.setupSwiftlyTestRepo()\n        defer { try? SBOMTestRepo.cleanup(swiftlyPath) }\n\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph(rootPath: swiftlyPath.pathString)\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let resolvedProduct = try #require(rootPackage.products.first)\n        let actualRevision = try swiftlyRepo.getCurrentRevision().identifier\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(product: resolvedProduct) }()\n\n        #expect(component.category == SBOMComponent.Category.application)\n        #expect(component.name == \"swiftly\")\n        #expect(component.id.value == \"swiftly:swiftly\")\n        #expect(component.version.revision == \"v1.0.0\")\n        #expect(component.scope == .runtime)\n        #expect(component.purl.description.contains(\"pkg:swift/github.com/swiftlang/swiftly:swiftly@v1.0.0\"))\n        #expect(component.description == nil)\n\n        let commits = try #require(component.originator.commits)\n        #expect(commits.count == 1)\n        let firstCommit = try #require(commits.first)\n        #expect(firstCommit.sha == actualRevision)\n        #expect(firstCommit.repository == SBOMTestStore.swiftlyURL)\n    }\n\n    @Test(\"extractPrimaryComponent with product filter\")\n    func extractPrimaryComponentWithProductFilter() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n\n        let productName = \"SwiftPMDataModel\"\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractPrimaryComponent(product: productName) }()\n\n        #expect(component.name == productName)\n        #expect(component.id.value == \"swift-package-manager:\\(productName)\")\n        #expect(component.category == .library)\n\n        let packageComponent = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractPrimaryComponent() }()\n        #expect(packageComponent.name == \"swift-package-manager\")\n        #expect(packageComponent.id.value == \"swift-package-manager\")\n        #expect(component.category == .library)\n\n        #expect(component.id != packageComponent.id)\n    }\n\n    @Test(\"SBOMVersionCache caches version information across multiple extractions\")\n    func versionCacheStoresAndReusesVersions() async throws {\n        let (spmRepo, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let expectedRevision = try spmRepo.getCurrentRevision().identifier\n        let caches = SBOMCaches()\n\n        let component1 = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store,\n            caches: caches\n        ); return try await extractor.extractPrimaryComponent() }()\n        #expect(component1.version.revision == expectedRevision)\n\n        let cachedVersion = await caches.version.get(rootPackage.identity)\n        #expect(cachedVersion != nil, \"Cache should contain version for root package\")\n        #expect(cachedVersion?.version.revision == expectedRevision, \"Cached version should match expected revision\")\n\n        let gitPath = spmPath.appending(\".git\")\n        try localFileSystem.removeFileTree(gitPath)\n        #expect(!localFileSystem.exists(gitPath), \"Git directory should be removed\")\n\n        let component2 = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store,\n            caches: caches\n        ); return try await extractor.extractPrimaryComponent() }()\n        #expect(component2.version.revision == expectedRevision, \"Should return cached version even without Git\")\n        #expect(\n            component2.version.revision == component1.version.revision,\n            \"Both extractions should return same version\"\n        )\n\n        let resolvedProduct = try #require(rootPackage.products.first { $0.name == \"SwiftPMDataModel\" })\n        let productComponent = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store,\n            caches: caches\n        ); return try await extractor.extractComponent(product: resolvedProduct) }()\n        #expect(\n            productComponent.version.revision == expectedRevision,\n            \"Product should use cached version from root package\"\n        )\n\n        let cachedVersionAfter = await caches.version.get(rootPackage.identity)\n        #expect(cachedVersionAfter?.version.revision == expectedRevision, \"Cache should still contain same version\")\n    }\n\n    @Test(\"extractComponent from package includes all products as nested components\")\n    func extractComponentFromPackageIncludesAllProducts() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        #expect(component.components != nil, \"Package component should have nested product components\")\n        let nestedComponents = try #require(component.components)\n        #expect(nestedComponents.count == rootPackage.products.count, \"Should have one component per product\")\n\n        for product in rootPackage.products {\n            let productComponent = nestedComponents.first { $0.name == product.name }\n            #expect(productComponent != nil, \"Should have component for product \\(product.name)\")\n            #expect(productComponent?.id.value == \"swift-package-manager:\\(product.name)\")\n        }\n    }\n\n    @Test(\"extractComponent from package with executable product has application category\")\n    func extractComponentFromPackageWithExecutableHasApplicationCategory() async throws {\n        let (_, swiftlyPath) = try SBOMTestRepo.setupSwiftlyTestRepo()\n        defer { try? SBOMTestRepo.cleanup(swiftlyPath) }\n\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph(rootPath: swiftlyPath.pathString)\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        #expect(component.category == .application, \"Package with executable should be application category\")\n        #expect(component.name == \"swiftly\")\n        #expect(component.id.value == \"swiftly\")\n    }\n\n    @Test(\"extractComponent from dependency package uses store version\")\n    func extractComponentFromDependencyPackageUsesStoreVersion() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n\n        let dependencyPackage = try #require(graph.packages.first { $0.identity.description == \"swift-system\" })\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: dependencyPackage) }()\n\n        #expect(component.name == \"swift-system\")\n        #expect(component.id.value == \"swift-system\")\n        #expect(component.category == .library)\n        #expect(component.version.revision == \"1.3.2\")\n        let expectedSHA = SBOMTestStore.generateMockRevision(for: \"swift-system\")\n        #expect(component.version.commit?.sha == expectedSHA)\n        #expect(component.version.commit?.repository == \"https://github.com/apple/swift-system.git\")\n    }\n\n    @Test(\"extractComponent from product without graph uses store version\")\n    func extractComponentFromProductWithoutGraphUsesStoreVersion() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n\n        let dependencyPackage = try #require(graph.packages.first { $0.identity.description == \"swift-collections\" })\n        let product = try #require(dependencyPackage.products.first { $0.name == \"OrderedCollections\" })\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(product: product) }()\n\n        #expect(component.name == \"OrderedCollections\")\n        #expect(component.id.value == \"swift-collections:OrderedCollections\")\n        #expect(component.category == .library)\n        #expect(component.version.revision == \"1.1.4\")\n        #expect(component.description == nil, \"Products should not have description\")\n    }\n\n    @Test(\"extractComponent from package sets correct PURL\")\n    func extractComponentFromPackageSetsCorrectPURL() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        #expect(component.purl.description.hasPrefix(\"pkg:swift/github.com/swiftlang/swift-package-manager@\"))\n        #expect(component.purl.description.contains(\"github.com/swiftlang/swift-package-manager\"))\n    }\n\n    @Test(\"extractComponent from product sets correct PURL with subpath\")\n    func extractComponentFromProductSetsCorrectPURLWithSubpath() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let product = try #require(rootPackage.products.first { $0.name == \"SwiftPMPackageCollections\" })\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(product: product) }()\n\n        #expect(component.purl.description\n            .contains(\"pkg:swift/github.com/swiftlang/swift-package-manager:SwiftPMPackageCollections@\"))\n        #expect(component.purl.description.contains(\":SwiftPMPackageCollections@\"))\n    }\n\n    @Test(\"extractComponent from package includes originator with commit info\")\n    func extractComponentFromPackageIncludesOriginatorWithCommitInfo() async throws {\n        let (spmRepo, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let expectedRevision = try spmRepo.getCurrentRevision().identifier\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        #expect(component.originator.commits != nil)\n        let commits = try #require(component.originator.commits)\n        #expect(commits.count == 1)\n        #expect(commits.first?.sha == expectedRevision)\n        #expect(commits.first?.repository == SBOMTestStore.swiftPMURL)\n    }\n\n    @Test(\"extractComponent from product includes originator with commit info\")\n    func extractComponentFromProductIncludesOriginatorWithCommitInfo() async throws {\n        let (spmRepo, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let product = try #require(rootPackage.products.first)\n        let expectedRevision = try spmRepo.getCurrentRevision().identifier\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(product: product) }()\n\n        let commits = try #require(component.originator.commits)\n        #expect(commits.count == 1)\n        let firstCommit = try #require(commits.first)\n        #expect(firstCommit.sha == expectedRevision)\n        #expect(firstCommit.repository == SBOMTestStore.swiftPMURL)\n    }\n\n    @Test(\"extractComponent from package preserves package description\")\n    func extractComponentFromPackagePreservesDescription() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        #expect(component.description == rootPackage.description)\n    }\n\n    @Test(\"extractComponent from product has nil description\")\n    func extractComponentFromProductHasNilDescription() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let product = try #require(rootPackage.products.first)\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(product: product) }()\n\n        #expect(component.description == nil, \"Products should not have description\")\n    }\n\n    @Test(\"extractComponent from package extracts all products with correct properties\")\n    func extractComponentFromPackageExtractsAllProductsWithCorrectProperties() async throws {\n        let (spmRepo, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let expectedRevision = try spmRepo.getCurrentRevision().identifier\n\n        let packageComponent = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        let productComponents = try #require(packageComponent.components)\n        #expect(productComponents.count == rootPackage.products.count)\n\n        for (_, product) in rootPackage.products.enumerated() {\n            let productComponent = try #require(productComponents.first { $0.name == product.name })\n            #expect(productComponent.id.value == \"swift-package-manager:\\(product.name)\")\n            let expectedCategory: SBOMComponent.Category = product.type == .executable ? .application : .library\n            #expect(productComponent.category == expectedCategory)\n            #expect(productComponent.version.revision == expectedRevision)\n            let versionCommit = try #require(productComponent.version.commit)\n            #expect(versionCommit.sha == expectedRevision)\n            #expect(productComponent.scope == .runtime || productComponent.scope == .test)\n            #expect(productComponent.description == nil)\n            #expect(productComponent.purl.description.contains(\":\\(product.name)@\"))\n        }\n    }\n\n    @Test(\"extractComponent from package with multiple product types extracts all correctly\")\n    func extractComponentFromPackageWithMultipleProductTypesExtractsAllCorrectly() async throws {\n        let (_, swiftlyPath) = try SBOMTestRepo.setupSwiftlyTestRepo()\n        defer { try? SBOMTestRepo.cleanup(swiftlyPath) }\n\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph(rootPath: swiftlyPath.pathString)\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n\n        let packageComponent = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        let productComponents = try #require(packageComponent.components)\n        #expect(productComponents.count == rootPackage.products.count)\n\n        let executableProduct = try #require(rootPackage.products.first { $0.type == .executable })\n        let executableComponent = try #require(productComponents.first { $0.name == executableProduct.name })\n        #expect(executableComponent.category == .application)\n        #expect(executableComponent.id.value == \"swiftly:swiftly\")\n    }\n\n    @Test(\"extractComponent from dependency package extracts products with store versions\")\n    func extractComponentFromDependencyPackageExtractsProductsWithStoreVersions() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n\n        let dependencyPackage = try #require(graph.packages.first { $0.identity.description == \"swift-collections\" })\n\n        let packageComponent = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: dependencyPackage) }()\n\n        let productComponents = try #require(packageComponent.components)\n        #expect(productComponents.count == dependencyPackage.products.count)\n\n        let expectedVersion = \"1.1.4\"\n        let expectedSHA = SBOMTestStore.generateMockRevision(for: \"swift-collections\")\n        for productComponent in productComponents {\n            #expect(productComponent.version.revision == expectedVersion)\n            #expect(productComponent.version.commit?.sha == expectedSHA)\n        }\n\n        let orderedCollections = try #require(productComponents.first { $0.name == \"OrderedCollections\" })\n        #expect(orderedCollections.id.value == \"swift-collections:OrderedCollections\")\n        #expect(orderedCollections.category == .library)\n    }\n\n    @Test(\"extractComponent from package with no products has empty components array\")\n    func extractComponentFromPackageWithNoProductsHasEmptyComponentsArray() async throws {\n        // Create a simple package with no products for testing\n        let packageIdentity = PackageIdentity.plain(\"TestPackage\")\n        let module = SBOMTestModulesGraph.createSwiftModule(name: \"TestModule\")\n        let package = SBOMTestModulesGraph.createPackage(\n            identity: packageIdentity,\n            displayName: \"TestPackage\",\n            path: \"/TestPackage\",\n            modules: [module],\n            products: []\n        )\n        let resolvedModule = SBOMTestModulesGraph.createResolvedModule(\n            packageIdentity: packageIdentity,\n            module: module\n        )\n        let resolvedPackage = SBOMTestModulesGraph.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedModule]),\n            products: []\n        )\n\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: resolvedPackage) }()\n\n        #expect(component.components != nil)\n        #expect(component.components?.isEmpty == true, \"Package with no products should have empty components array\")\n    }\n\n    @Test(\"extractComponent from package preserves product order\")\n    func extractComponentFromPackagePreservesProductOrder() async throws {\n        let (_, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n\n        let packageComponent = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        let productComponents = try #require(packageComponent.components)\n        let productNames = productComponents.map(\\.name)\n        let expectedProductNames = rootPackage.products.map(\\.name)\n\n        #expect(\n            productNames == expectedProductNames,\n            \"Product components should maintain the same order as package products\"\n        )\n    }\n\n    @Test(\"extractComponent uses origin remote for version commit\")\n    func extractComponentUsesOriginRemoteForVersionCommit() async throws {\n        let (spmRepo, spmPath) = try SBOMTestRepo.setupSPMTestRepo()\n        defer { try? SBOMTestRepo.cleanup(spmPath) }\n\n        // Add a second remote to verify origin is preferred\n        try await Process.checkNonZeroExit(\n            args: Git.tool,\n            \"-C\",\n            spmPath.pathString,\n            \"remote\",\n            \"add\",\n            \"upstream\",\n            \"https://github.com/apple/swift-package-manager.git\"\n        )\n\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: spmPath.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let expectedRevision = try spmRepo.getCurrentRevision().identifier\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n\n        // Verify the version commit uses the origin remote, not upstream\n        let versionCommit = try #require(component.version.commit)\n        #expect(versionCommit.repository == SBOMTestStore.swiftPMURL)\n        #expect(versionCommit.sha == expectedRevision)\n\n        // Verify originator still contains all remotes\n        let commits = try #require(component.originator.commits)\n        #expect(commits.count == 1, \"Should prioritize origin remote\")\n\n        let originCommit = commits.first { $0.repository == SBOMTestStore.swiftPMURL }\n        #expect(originCommit != nil, \"Should have commit for origin remote\")\n    }\n\n    @Test(\"extractComponent handles repository with no remotes\")\n    func extractComponentHandlesRepositoryWithNoRemotes() async throws {\n        let uniqueID = UUID().uuidString\n        let path = AbsolutePath(\"/tmp/SwiftPM-no-remotes-\\(uniqueID)\")\n        defer { try? SBOMTestRepo.cleanup(path) }\n\n        try localFileSystem.createDirectory(path, recursive: true)\n        initGitRepo(path, addFile: true)\n\n        // Don't add any remotes\n        let gitRepo = GitRepository(path: path)\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: path.pathString)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let expectedRevision = try gitRepo.getCurrentRevision().identifier\n\n        let component = try await { let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        ); return try await extractor.extractComponent(package: rootPackage) }()\n        #expect(component.version.commit == nil)\n        #expect(component.version.revision == expectedRevision)\n        #expect(component.originator.commits == nil)\n    }\n\n    @Test(\"extractComponentID from package returns package identity\")\n    func extractComponentIDFromPackageReturnsPackageIdentity() throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let rootPackage = try #require(graph.rootPackages.first)\n\n        let componentID = SBOMExtractor.extractComponentID(from: rootPackage)\n\n        #expect(componentID.value == \"MyApp\")\n        #expect(componentID.value == rootPackage.identity.description)\n    }\n\n    @Test(\"extractComponentID from product returns package:product format\")\n    func extractComponentIDFromProductReturnsPackageProductFormat() throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let rootPackage = try #require(graph.rootPackages.first)\n        let product = try #require(rootPackage.products.first)\n\n        let componentID = SBOMExtractor.extractComponentID(from: product)\n\n        #expect(componentID.value == \"MyApp:App\")\n        #expect(componentID.value.hasPrefix(\"\\(product.packageIdentity):\"))\n        #expect(componentID.value.hasSuffix(\":\\(product.name)\"))\n    }\n\n    @Test(\"extractComponentID from multiple products maintains correct format\")\n    func extractComponentIDFromMultipleProductsMaintainsCorrectFormat() throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let rootPackage = try #require(graph.rootPackages.first)\n        for product in rootPackage.products {\n            let componentID = SBOMExtractor.extractComponentID(from: product)\n            let expectedID = \"\\(product.packageIdentity):\\(product.name)\"\n\n            #expect(componentID.value == expectedID)\n            #expect(componentID.value.contains(\":\"), \"Product ID should contain colon separator\")\n\n            let parts = componentID.value.split(separator: \":\")\n            #expect(parts.count == 2, \"Product ID should have exactly two parts\")\n            #expect(String(parts[0]) == product.packageIdentity.description)\n            #expect(String(parts[1]) == product.name)\n        }\n    }\n\n    @Test(\"extractComponentID from dependency packages returns correct identity\")\n    func extractComponentIDFromDependencyPackagesReturnsCorrectIdentity() throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        for package in graph.packages where package.identity.description != \"swift-package-manager\" {\n            let componentID = SBOMExtractor.extractComponentID(from: package)\n\n            #expect(componentID.value == package.identity.description)\n            #expect(!componentID.value.contains(\":\"), \"Package ID should not contain colon\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMExtractScopeTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct SBOMExtractScopeTests {\n    struct ProductScopeTestCase {\n        let productType: ProductType\n        let moduleType: Module.Kind\n        let expectedScope: SBOMComponent.Scope\n        let description: String\n    }\n\n    static let productScopeTestCases: [ProductScopeTestCase] = [\n        ProductScopeTestCase(\n            productType: .executable,\n            moduleType: .executable,\n            expectedScope: .runtime,\n            description: \"executable\"\n        ),\n        ProductScopeTestCase(\n            productType: .library(.automatic),\n            moduleType: .library,\n            expectedScope: .runtime,\n            description: \"library\"\n        ),\n        ProductScopeTestCase(\n            productType: .test,\n            moduleType: .test,\n            expectedScope: .test,\n            description: \"test\"\n        ),\n        ProductScopeTestCase(\n            productType: .library(.automatic),\n            moduleType: .test,\n            expectedScope: .test,\n            description: \"library with test module\"\n        ),\n    ]\n\n    @Test(\"extractScopeFromProduct\", arguments: productScopeTestCases)\n    func extractScopeFromProduct(testCase: ProductScopeTestCase) throws {\n        let resolvedProduct = try SBOMTestModulesGraph.createProduct(\n            name: \"MyProduct\",\n            type: testCase.productType,\n            moduleType: testCase.moduleType\n        )\n        let scope = try SBOMExtractor.extractScope(from: resolvedProduct)\n        #expect(scope == testCase.expectedScope)\n    }\n\n    struct PackageScopeTestCase {\n        let productTypes: [(ProductType, Module.Kind?)]\n        let additionalModules: [Module.Kind]\n        let expectedScope: SBOMComponent.Scope\n        let description: String\n    }\n\n    static let packageScopeTestCases: [PackageScopeTestCase] = [\n        PackageScopeTestCase(\n            productTypes: [(.executable, .executable)],\n            additionalModules: [],\n            expectedScope: .runtime,\n            description: \"executable product\"\n        ),\n        PackageScopeTestCase(\n            productTypes: [(.library(.automatic), nil)],\n            additionalModules: [],\n            expectedScope: .runtime,\n            description: \"library product\"\n        ),\n        PackageScopeTestCase(\n            productTypes: [(.test, .test)],\n            additionalModules: [],\n            expectedScope: .test,\n            description: \"test product\"\n        ),\n        PackageScopeTestCase(\n            productTypes: [(.executable, .executable), (.test, .test)],\n            additionalModules: [],\n            expectedScope: .runtime,\n            description: \"mixed products with test\"\n        ),\n        PackageScopeTestCase(\n            productTypes: [(.library(.automatic), nil)],\n            additionalModules: [.test],\n            expectedScope: .runtime,\n            description: \"test module but no test product\"\n        ),\n        PackageScopeTestCase(\n            productTypes: [(.executable, .executable), (.library(.automatic), nil)],\n            additionalModules: [],\n            expectedScope: .runtime,\n            description: \"only runtime products and modules\"\n        ),\n    ]\n\n    @Test(\"extractScopeFromPackage\", arguments: packageScopeTestCases)\n    func extractScopeFromPackage(testCase: PackageScopeTestCase) throws {\n        var products: [ResolvedProduct] = []\n        for (index, (productType, moduleType)) in testCase.productTypes.enumerated() {\n            let product = try SBOMTestModulesGraph.createProduct(\n                name: \"Product\\(index)\",\n                type: productType,\n                moduleType: moduleType ?? .library\n            )\n            products.append(product)\n        }\n        \n        var modules: [Module] = []\n        for (index, moduleType) in testCase.additionalModules.enumerated() {\n            let module = SBOMTestModulesGraph.createSwiftModule(\n                name: \"AdditionalModule\\(index)\",\n                type: moduleType\n            )\n            modules.append(module)\n        }\n        \n        let resolvedPackage = try SBOMTestModulesGraph.createPackage(\n            name: \"TestPackage\",\n            products: products,\n            modules: modules\n        )\n        let scope = try SBOMExtractor.extractScope(from: resolvedPackage)\n        #expect(scope == testCase.expectedScope)\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMExtractTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Foundation\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct SBOMExtractTests {\n    @Test(\"extractSBOM with product filter for SwiftPM\")\n    func extractSBOMWithProductFilterForSwiftPM() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n\n        let productName = \"SwiftPMPackageCollections\"\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let sbom = try await extractor.extractSBOM(product: productName)\n\n        #expect(sbom.primaryComponent.name == productName)\n        #expect(sbom.primaryComponent.id.value == \"swift-package-manager:\\(productName)\")\n        #expect(sbom.primaryComponent.category == .library)\n\n        let fullSbom = try await extractor.extractSBOM()\n        #expect(fullSbom.primaryComponent.name == \"swift-package-manager\")\n        #expect(fullSbom.primaryComponent.id.value == \"swift-package-manager\")\n        #expect(fullSbom.primaryComponent.category == .application)\n\n        #expect(sbom.dependencies.components.count < fullSbom.dependencies.components.count)\n\n        #expect((sbom.dependencies.relationships?.count ?? 0) < (fullSbom.dependencies.relationships?.count ?? 0))\n\n        let componentIDs = Set(sbom.dependencies.components.map(\\.id.value))\n\n        #expect(\n            componentIDs.contains(\"swift-package-manager:SwiftPMPackageCollections\"),\n            \"should contain target product\"\n        )\n        #expect(componentIDs.contains(\"swift-package-manager\"), \"should contain root package\")\n\n        let swiftPMDependency = try #require(sbom.dependencies.relationships?\n            .first(where: { $0.parentID.value == \"swift-package-manager\" }))\n        #expect(Set(swiftPMDependency.childrenID.map(\\.value)) == Set([\n            \"swift-certificates\", \"swift-tools-support-core\", \"swift-collections\", \"swift-crypto\",\n            \"swift-toolchain-sqlite\",\n            \"swift-system\", \"swift-package-manager:SwiftPMPackageCollections\",\n        ]))\n    }\n\n    @Test(\"extractSBOM with product filter for Swiftly\")\n    func extractSBOMWithProductFilterForSwiftly() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n\n        let productName = \"swiftly\"\n        let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n        let sbom = try await extractor.extractSBOM(product: productName)\n\n        #expect(sbom.primaryComponent.name == productName)\n        #expect(sbom.primaryComponent.id.value == \"swiftly:swiftly\")\n        #expect(sbom.primaryComponent.category == .application)\n\n        let fullSbom = try await extractor.extractSBOM()\n        #expect(fullSbom.primaryComponent.name == \"swiftly\")\n        #expect(fullSbom.primaryComponent.id.value == \"swiftly\")\n        #expect(fullSbom.primaryComponent.category == .application)\n\n        #expect(sbom.dependencies.components.count < fullSbom.dependencies.components.count)\n\n        #expect((sbom.dependencies.relationships?.count ?? 0) < (fullSbom.dependencies.relationships?.count ?? 0))\n\n        let componentIDs = Set(sbom.dependencies.components.map(\\.id.value))\n        #expect(componentIDs.contains(\"swiftly:swiftly\"), \"should contain target product\")\n        #expect(componentIDs.contains(\"swiftly\"), \"should contain root package\")\n        #expect(\n            componentIDs.contains(\"swift-tools-support-core:SwiftToolsSupport-auto\"),\n            \"should contain a dependency product\"\n        )\n\n        let swiftlyDependency = try #require(sbom.dependencies.relationships?\n            .first(where: { $0.parentID.value == \"swiftly\" }))\n        #expect(Set(swiftlyDependency.childrenID.map(\\.value)) == Set([\n            \"swiftly:swiftly\",\n            \"swift-tools-support-core\",\n            \"swift-argument-parser\",\n            \"swift-system\",\n            \"async-http-client\",\n            \"swift-openapi-async-http-client\",\n            \"swift-nio\",\n            \"swift-openapi-runtime\",\n            \"swift-algorithms\",\n            \"swift-nio-transport-services\",\n            \"swift-nio-ssl\",\n            \"swift-openapi-generator\",\n            \"swift-nio-http2\",\n            \"swift-distributed-tracing\",\n            \"swift-nio-extras\",\n            \"swift-subprocess\",\n        ]))\n        let swiftlyProductDependency = try #require(sbom.dependencies.relationships?\n            .first(where: { $0.parentID.value == \"swiftly:swiftly\" }))\n        #expect(Set(swiftlyProductDependency.childrenID.map(\\.value)) == Set([\n            \"async-http-client:AsyncHTTPClient\",\n            \"swift-openapi-async-http-client:OpenAPIAsyncHTTPClient\",\n            \"swift-openapi-runtime:OpenAPIRuntime\",\n            \"swift-tools-support-core:SwiftToolsSupport-auto\",\n            \"swift-argument-parser:ArgumentParser\",\n            \"swift-nio:NIOFoundationCompat\",\n            \"swift-system:SystemPackage\",\n            \"swift-subprocess:Subprocess\",\n            \"swift-openapi-generator:OpenAPIGenerator\",\n        ]))\n        let swiftSystemDependency = try #require(sbom.dependencies.relationships?\n            .first(where: { $0.parentID.value == \"swift-system\" }))\n        #expect(Set(swiftSystemDependency.childrenID.map(\\.value)) == Set([\"swift-system:SystemPackage\"]))\n        let swiftArgumentParserDependency = try #require(sbom.dependencies.relationships?\n            .first(where: { $0.parentID.value == \"swift-argument-parser\" }))\n        #expect(Set(swiftArgumentParserDependency.childrenID.map(\\.value)) ==\n            Set([\"swift-argument-parser:ArgumentParser\"]))\n        let swiftToolsSupportDependency = try #require(sbom.dependencies.relationships?\n            .first(where: { $0.parentID.value == \"swift-tools-support-core\" }))\n        #expect(Set(swiftToolsSupportDependency.childrenID.map(\\.value)) ==\n            Set([\"swift-tools-support-core:SwiftToolsSupport-auto\"]))\n    }\n\n    @Test(\"extractSBOM with invalid product name throws error\")\n    func extractSBOMWithInvalidProductNameThrowsError() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n\n        await #expect(throws: SBOMExtractorError.self) {\n            let extractor = SBOMExtractor(modulesGraph: graph, dependencyGraph: nil, store: store)\n            _ = try await extractor.extractSBOM(product: \"NonExistentProduct\")\n        }\n    }\n\n    @Test(\"generateSBOMID generates valid URN UUID format\")\n    func generateSBOMIDGeneratesValidURNUUIDFormat() async throws {\n        let id1 = SBOMIdentifier.generate()\n        let id2 = SBOMIdentifier.generate()\n\n        #expect(id1.value.hasPrefix(\"urn:uuid:\"))\n        #expect(id2.value.hasPrefix(\"urn:uuid:\"))\n\n        let uuid1String = String(id1.value.dropFirst(\"urn:uuid:\".count))\n        let uuid2String = String(id2.value.dropFirst(\"urn:uuid:\".count))\n\n        #expect(UUID(uuidString: uuid1String) != nil, \"Should be a valid UUID\")\n        #expect(UUID(uuidString: uuid2String) != nil, \"Should be a valid UUID\")\n\n        #expect(uuid1String == uuid1String.lowercased(), \"UUID should be lowercase\")\n        #expect(uuid2String == uuid2String.lowercased(), \"UUID should be lowercase\")\n\n        #expect(id1 != id2, \"Each call should generate a unique ID\")\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMFilterStrategyTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct SBOMFilterStrategyTests {\n    \n    // MARK: - Helper Methods\n    \n    private func createTestComponent(\n        id: String,\n        name: String,\n        entity: SBOMComponent.Entity,\n        scope: SBOMComponent.Scope = .runtime\n    ) -> SBOMComponent {\n        return SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: id),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: name),\n            name: name,\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(),\n            scope: scope,\n            entity: entity\n        )\n    }\n    \n    // MARK: - AllFilterStrategy Tests\n    \n    @Test(\"AllFilterStrategy includes all components\")\n    func allFilterIncludesAllComponents() {\n        let strategy = AllFilterStrategy()\n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        \n        let packageComponent = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let productComponent = createTestComponent(id: \"root:prod1\", name: \"Product1\", entity: .product)\n        \n        #expect(strategy.shouldIncludeComponent(packageComponent, primaryComponent: primaryPackage))\n        #expect(strategy.shouldIncludeComponent(productComponent, primaryComponent: primaryPackage))\n        #expect(strategy.shouldIncludeComponent(primaryPackage, primaryComponent: primaryPackage))\n    }\n    \n    @Test(\"AllFilterStrategy tracks all relationships except self-referential\")\n    func allFilterTracksAllRelationships() {\n        let strategy = AllFilterStrategy()\n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        \n        let parent = createTestComponent(id: \"parent\", name: \"Parent\", entity: .package)\n        let child = createTestComponent(id: \"child\", name: \"Child\", entity: .package)\n        let product = createTestComponent(id: \"root:prod\", name: \"Product\", entity: .product)\n        let product2 = createTestComponent(id: \"root:prod2\", name: \"Product2\", entity: .product)\n        \n        // Should track package-to-package, package-to-product, and product-to-product\n        #expect(strategy.shouldTrackRelationship(parent: parent, child: child, primaryComponent: primaryPackage))\n        #expect(strategy.shouldTrackRelationship(parent: parent, child: product, primaryComponent: primaryPackage))\n        #expect(strategy.shouldTrackRelationship(parent: parent, child: product2, primaryComponent: primaryPackage))\n\n        // Should NOT track self-referential\n        #expect(!strategy.shouldTrackRelationship(parent: product, child: product, primaryComponent: primaryPackage))\n        #expect(!strategy.shouldTrackRelationship(parent: parent, child: parent, primaryComponent: primaryPackage))\n    }\n    \n    // MARK: - ProductFilterStrategy Tests\n    \n    @Test(\"ProductFilterStrategy includes only products and root package when primary component is package\")\n    func productFilterIncludesOnlyProductsWhenPrimaryIsPackage() {\n        let strategy = ProductFilterStrategy()\n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        \n        let packageComponent = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let productComponent = createTestComponent(id: \"root:prod1\", name: \"Product1\", entity: .product)\n        let otherProduct = createTestComponent(id: \"pkg1:prod2\", name: \"Product2\", entity: .product)\n        \n        // Should include the primary package\n        #expect(strategy.shouldIncludeComponent(primaryPackage, primaryComponent: primaryPackage))\n        \n        // Should include products\n        #expect(strategy.shouldIncludeComponent(productComponent, primaryComponent: primaryPackage))\n        #expect(strategy.shouldIncludeComponent(otherProduct, primaryComponent: primaryPackage))\n        \n        // Should NOT include other packages\n        #expect(!strategy.shouldIncludeComponent(packageComponent, primaryComponent: primaryPackage))\n    }\n    \n    @Test(\"ProductFilterStrategy includes only products when primary is product\")\n    func productFilterIncludesOnlyProductsWhenPrimaryIsProduct() {\n        let strategy = ProductFilterStrategy()\n        let primaryProduct = createTestComponent(id: \"root:main\", name: \"Main\", entity: .product)\n        \n        let packageComponent = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let productComponent = createTestComponent(id: \"root:prod1\", name: \"Product1\", entity: .product)\n        let otherProduct = createTestComponent(id: \"pkg1:prod2\", name: \"Product2\", entity: .product)\n        \n        // Should include products\n        #expect(strategy.shouldIncludeComponent(primaryProduct, primaryComponent: primaryProduct))\n        #expect(strategy.shouldIncludeComponent(productComponent, primaryComponent: primaryProduct))\n        #expect(strategy.shouldIncludeComponent(otherProduct, primaryComponent: primaryProduct))\n        \n        // Should NOT include packages\n        #expect(!strategy.shouldIncludeComponent(packageComponent, primaryComponent: primaryProduct))\n    }\n    \n    @Test(\"ProductFilterStrategy tracks product-to-product relationships\")\n    func productFilterTracksProductToProductRelationships() {\n        let strategy = ProductFilterStrategy()\n        let primaryProduct = createTestComponent(id: \"root:main\", name: \"Main\", entity: .product)\n        \n        let product1 = createTestComponent(id: \"root:prod1\", name: \"Product1\", entity: .product)\n        let product2 = createTestComponent(id: \"pkg1:prod2\", name: \"Product2\", entity: .product)\n        \n        // Should track product-to-product\n        #expect(strategy.shouldTrackRelationship(parent: product1, child: product2, primaryComponent: primaryProduct))\n        #expect(strategy.shouldTrackRelationship(parent: primaryProduct, child: product1, primaryComponent: primaryProduct))\n    }\n    \n    @Test(\"ProductFilterStrategy tracks root-package-to-product when primary is package\")\n    func productFilterTracksRootPackageToProductWhenPrimaryIsPackage() {\n        let strategy = ProductFilterStrategy()\n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        \n        let product = createTestComponent(id: \"root:prod\", name: \"Product\", entity: .product)\n        let otherPackage = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        \n        // Should track root-package-to-product\n        #expect(strategy.shouldTrackRelationship(parent: primaryPackage, child: product, primaryComponent: primaryPackage))\n        \n        // Should NOT track other package-to-product\n        #expect(!strategy.shouldTrackRelationship(parent: otherPackage, child: product, primaryComponent: primaryPackage))\n    }\n    \n    @Test(\"ProductFilterStrategy does not track package-to-package relationships\")\n    func productFilterDoesNotTrackPackageToPackageRelationships() {\n        let strategy = ProductFilterStrategy()\n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        \n        let package1 = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let package2 = createTestComponent(id: \"pkg2\", name: \"Package2\", entity: .package)\n        \n        // Should NOT track package-to-package\n        #expect(!strategy.shouldTrackRelationship(parent: package1, child: package2, primaryComponent: primaryPackage))\n        #expect(!strategy.shouldTrackRelationship(parent: primaryPackage, child: package1, primaryComponent: primaryPackage))\n    }\n    \n    @Test(\"ProductFilterStrategy prevents self-referential relationships\")\n    func productFilterPreventsSelfReferentialRelationships() {\n        let strategy = ProductFilterStrategy()\n        let primaryProduct = createTestComponent(id: \"root:main\", name: \"Main\", entity: .product)\n        \n        let product = createTestComponent(id: \"root:prod\", name: \"Product\", entity: .product)\n        \n        // Should NOT track self-referential\n        #expect(!strategy.shouldTrackRelationship(parent: product, child: product, primaryComponent: primaryProduct))\n        #expect(!strategy.shouldTrackRelationship(parent: primaryProduct, child: primaryProduct, primaryComponent: primaryProduct))\n    }\n    \n    // MARK: - PackageFilterStrategy Tests\n    \n    @Test(\"PackageFilterStrategy includes only packages when primary is package\")\n    func packageFilterIncludesOnlyPackagesWhenPrimaryIsPackage() {\n        let strategy = PackageFilterStrategy()\n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        \n        let packageComponent = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let productComponent = createTestComponent(id: \"root:prod1\", name: \"Product1\", entity: .product)\n        \n        // Should include packages\n        #expect(strategy.shouldIncludeComponent(primaryPackage, primaryComponent: primaryPackage))\n        #expect(strategy.shouldIncludeComponent(packageComponent, primaryComponent: primaryPackage))\n        \n        // Should NOT include products\n        #expect(!strategy.shouldIncludeComponent(productComponent, primaryComponent: primaryPackage))\n    }\n    \n    @Test(\"PackageFilterStrategy includes packages and primary product when primary is product\")\n    func packageFilterIncludesPackagesAndPrimaryProductWhenPrimaryIsProduct() {\n        let strategy = PackageFilterStrategy()\n        let primaryProduct = createTestComponent(id: \"root:main\", name: \"Main\", entity: .product)\n        \n        let packageComponent = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let otherProduct = createTestComponent(id: \"root:prod1\", name: \"Product1\", entity: .product)\n        \n        // Should include the primary product\n        #expect(strategy.shouldIncludeComponent(primaryProduct, primaryComponent: primaryProduct))\n        \n        // Should include packages\n        #expect(strategy.shouldIncludeComponent(packageComponent, primaryComponent: primaryProduct))\n        \n        // Should NOT include other products\n        #expect(!strategy.shouldIncludeComponent(otherProduct, primaryComponent: primaryProduct))\n    }\n    \n    @Test(\"PackageFilterStrategy tracks package-to-package relationships\")\n    func packageFilterTracksPackageToPackageRelationships() {\n        let strategy = PackageFilterStrategy()\n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        \n        let package1 = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let package2 = createTestComponent(id: \"pkg2\", name: \"Package2\", entity: .package)\n        \n        // Should track package-to-package\n        #expect(strategy.shouldTrackRelationship(parent: package1, child: package2, primaryComponent: primaryPackage))\n        #expect(strategy.shouldTrackRelationship(parent: primaryPackage, child: package1, primaryComponent: primaryPackage))\n    }\n    \n    @Test(\"PackageFilterStrategy tracks package-to-primary-product when primary is product\")\n    func packageFilterTracksPackageToPrimaryProductWhenPrimaryIsProduct() {\n        let strategy = PackageFilterStrategy()\n        let primaryProduct = createTestComponent(id: \"root:main\", name: \"Main\", entity: .product)\n        \n        let package = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let otherProduct = createTestComponent(id: \"root:other\", name: \"Other\", entity: .product)\n        \n        // Should track package-to-primary-product\n        #expect(strategy.shouldTrackRelationship(parent: package, child: primaryProduct, primaryComponent: primaryProduct))\n        \n        // Should NOT track package-to-other-product\n        #expect(!strategy.shouldTrackRelationship(parent: package, child: otherProduct, primaryComponent: primaryProduct))\n    }\n    \n    @Test(\"PackageFilterStrategy does not track product-to-product relationships\")\n    func packageFilterDoesNotTrackProductToProductRelationships() {\n        let strategy = PackageFilterStrategy()\n        let primaryProduct = createTestComponent(id: \"root:main\", name: \"Main\", entity: .product)\n        \n        let product1 = createTestComponent(id: \"root:prod1\", name: \"Product1\", entity: .product)\n        let product2 = createTestComponent(id: \"pkg1:prod2\", name: \"Product2\", entity: .product)\n        \n        // Should NOT track product-to-product\n        #expect(!strategy.shouldTrackRelationship(parent: product1, child: product2, primaryComponent: primaryProduct))\n        #expect(!strategy.shouldTrackRelationship(parent: primaryProduct, child: product1, primaryComponent: primaryProduct))\n    }\n    \n    @Test(\"PackageFilterStrategy prevents self-referential relationships\")\n    func packageFilterPreventsSelfReferentialRelationships() {\n        let strategy = PackageFilterStrategy()\n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        \n        let package = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        \n        // Should NOT track self-referential\n        #expect(!strategy.shouldTrackRelationship(parent: package, child: package, primaryComponent: primaryPackage))\n        #expect(!strategy.shouldTrackRelationship(parent: primaryPackage, child: primaryPackage, primaryComponent: primaryPackage))\n    }\n    \n    // MARK: - Filter Extension Tests\n    \n    @Test(\"Filter.all creates AllFilterStrategy\")\n    func filterAllCreatesAllFilterStrategy() {\n        let strategy = Filter.all.createStrategy()\n        #expect(strategy is AllFilterStrategy)\n    }\n    \n    @Test(\"Filter.product creates ProductFilterStrategy\")\n    func filterProductCreatesProductFilterStrategy() {\n        let strategy = Filter.product.createStrategy()\n        #expect(strategy is ProductFilterStrategy)\n    }\n    \n    @Test(\"Filter.package creates PackageFilterStrategy\")\n    func filterPackageCreatesPackageFilterStrategy() {\n        let strategy = Filter.package.createStrategy()\n        #expect(strategy is PackageFilterStrategy)\n    }\n    \n    // MARK: - Cross-Strategy Comparison Tests\n    \n    @Test(\"Different strategies have different component inclusion behavior\")\n    func differentStrategiesHaveDifferentComponentInclusion() {\n        let allStrategy = AllFilterStrategy()\n        let productStrategy = ProductFilterStrategy()\n        let packageStrategy = PackageFilterStrategy()\n        \n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        let packageComponent = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let productComponent = createTestComponent(id: \"root:prod\", name: \"Product\", entity: .product)\n        \n        // All strategy includes everything\n        #expect(allStrategy.shouldIncludeComponent(packageComponent, primaryComponent: primaryPackage))\n        #expect(allStrategy.shouldIncludeComponent(productComponent, primaryComponent: primaryPackage))\n        \n        // Product strategy excludes non-primary packages\n        #expect(!productStrategy.shouldIncludeComponent(packageComponent, primaryComponent: primaryPackage))\n        #expect(productStrategy.shouldIncludeComponent(productComponent, primaryComponent: primaryPackage))\n        \n        // Package strategy excludes products\n        #expect(packageStrategy.shouldIncludeComponent(packageComponent, primaryComponent: primaryPackage))\n        #expect(!packageStrategy.shouldIncludeComponent(productComponent, primaryComponent: primaryPackage))\n    }\n    \n    @Test(\"Different strategies have different relationship tracking behavior\")\n    func differentStrategiesHaveDifferentRelationshipTracking() {\n        let allStrategy = AllFilterStrategy()\n        let productStrategy = ProductFilterStrategy()\n        let packageStrategy = PackageFilterStrategy()\n        \n        let primaryPackage = createTestComponent(id: \"root\", name: \"Root\", entity: .package)\n        let package1 = createTestComponent(id: \"pkg1\", name: \"Package1\", entity: .package)\n        let package2 = createTestComponent(id: \"pkg2\", name: \"Package2\", entity: .package)\n        let product1 = createTestComponent(id: \"root:prod1\", name: \"Product1\", entity: .product)\n        let product2 = createTestComponent(id: \"pkg1:prod2\", name: \"Product2\", entity: .product)\n        \n        // Package-to-package relationships\n        #expect(allStrategy.shouldTrackRelationship(parent: package1, child: package2, primaryComponent: primaryPackage))\n        #expect(!productStrategy.shouldTrackRelationship(parent: package1, child: package2, primaryComponent: primaryPackage))\n        #expect(packageStrategy.shouldTrackRelationship(parent: package1, child: package2, primaryComponent: primaryPackage))\n        \n        // Product-to-product relationships\n        #expect(allStrategy.shouldTrackRelationship(parent: product1, child: product2, primaryComponent: primaryPackage))\n        #expect(productStrategy.shouldTrackRelationship(parent: product1, child: product2, primaryComponent: primaryPackage))\n        #expect(!packageStrategy.shouldTrackRelationship(parent: product1, child: product2, primaryComponent: primaryPackage))\n    }\n}"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMGetSpecTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct SBOMGetSpecTests {\n    struct GetSpecTestCase {\n        let input: Spec\n        let expectedConcreteSpec: SBOMSpec.ConcreteSpec\n        let expectedVersion: String\n    }\n\n    static let specTestCases: [GetSpecTestCase] = [\n        GetSpecTestCase(\n            input: .cyclonedx,\n            expectedConcreteSpec: .cyclonedx1,\n            expectedVersion: CycloneDXConstants.cyclonedx1SpecVersion\n        ),\n        GetSpecTestCase(\n            input: .cyclonedx1,\n            expectedConcreteSpec: .cyclonedx1,\n            expectedVersion: CycloneDXConstants.cyclonedx1SpecVersion\n        ),\n        GetSpecTestCase(\n            input: .spdx,\n            expectedConcreteSpec: .spdx3,\n            expectedVersion: SPDXConstants.spdx3SpecVersion\n        ),\n        GetSpecTestCase(\n            input: .spdx3,\n            expectedConcreteSpec: .spdx3,\n            expectedVersion: SPDXConstants.spdx3SpecVersion\n        ),\n    ]\n\n    @Test(\"internalSpec good weather\", arguments: specTestCases)\n    func getSpecParameterized(testCase: GetSpecTestCase) throws {\n        let spec = testCase.input.internalSpec()\n\n        #expect(spec.concreteSpec == testCase.expectedConcreteSpec)\n        #expect(spec.versionString == testCase.expectedVersion)\n    }\n\n    // MARK: - Multiple Specs Tests\n\n    @Test(\"internalSpec returns unique specs\")\n    func getSpecsReturnsUniqueSpecs() throws {\n        let inputSpecs: [Spec] = [.cyclonedx, .cyclonedx1, .spdx, .spdx3]\n        let specs = Array(Set(inputSpecs.map { $0.internalSpec() })).sorted()\n\n        #expect(specs.count == 2, \"Should return only unique specs\")\n\n        let types = Set(specs.map(\\.concreteSpec))\n        #expect(types.contains(.cyclonedx1))\n        #expect(types.contains(.spdx3))\n    }\n\n    @Test(\"internalSpec handles empty array\")\n    func getSpecsHandlesEmptyArray() throws {\n        let inputSpecs: [Spec] = []\n        let specs = Array(Set(inputSpecs.map { $0.internalSpec() })).sorted()\n\n        #expect(specs.isEmpty, \"Should return empty array for empty input\")\n    }\n\n    @Test(\"internalSpec handles single spec\")\n    func getSpecsHandlesSingleSpec() throws {\n        let inputSpecs: [Spec] = [.cyclonedx]\n        let specs = Array(Set(inputSpecs.map { $0.internalSpec() })).sorted()\n\n        #expect(specs.count == 1)\n        #expect(specs[0].concreteSpec == .cyclonedx1)\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMGraphsConverterTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Foundation\nimport PackageGraph\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.medium\n    )\n)\nstruct SBOMGraphsConverterTests {\n    \n    // MARK: - toProduct and toModule Tests\n    // Note: Basic name mapping tests (getTargetName, getProductName, getModuleName) have been\n    // moved to Tests/SwiftBuildSupportTests/PackagePIFBuilderHelpersTests.swift to test the\n    // underlying PackagePIFBuilder functions directly.\n\n    @Test(\"toProduct(fromTarget:) returns correct product for valid product targets\")\n    func toProductWithValidTargets() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n\n        let swiftlyProduct = SBOMGraphsConverter.toProduct(fromTarget: \"swiftly-product\", modulesGraph: graph)\n        #expect(swiftlyProduct?.name == \"swiftly\", \"Product name should be 'swiftly'\")\n\n        let testSwiftlyProduct = SBOMGraphsConverter.toProduct(fromTarget: \"test-swiftly-product\", modulesGraph: graph)\n        #expect(testSwiftlyProduct?.name == \"test-swiftly\", \"Product name should be 'test-swiftly'\")\n    }\n\n    @Test(\"toProduct(fromTarget:) returns nil for non-product targets\")\n    func toProductWithNonProductTargets() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n\n        #expect(SBOMGraphsConverter.toProduct(fromTarget: \"Swiftly\", modulesGraph: graph) == nil, \"Module name should not be recognized as product\")\n        #expect(\n            SBOMGraphsConverter.toProduct(fromTarget: \"SwiftlyCore\", modulesGraph: graph) == nil,\n            \"Module name should not be recognized as product\"\n        )\n        #expect(\n            SBOMGraphsConverter.toProduct(fromTarget: \"_AsyncFileSystem\", modulesGraph: graph) == nil,\n            \"Module with underscore should not be recognized as product\"\n        )\n        #expect(SBOMGraphsConverter.toProduct(fromTarget: \"SPMSQLite3\", modulesGraph: graph) == nil, \"Module name should not be recognized as product\")\n\n        #expect(\n            SBOMGraphsConverter.toProduct(fromTarget: \"swift-nio_NIOPosix\", modulesGraph: graph) == nil,\n            \"Package_module format should not be recognized as product\"\n        )\n        #expect(\n            SBOMGraphsConverter.toProduct(fromTarget: \"swift-nio__NIOBase64\", modulesGraph: graph) == nil,\n            \"Package_module with underscore should not be recognized as product\"\n        )\n    }\n\n    @Test(\"toProduct(fromTarget:) handles edge cases for product targets\")\n    func toProductEdgeCases() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n\n        let swiftBuildProduct = SBOMGraphsConverter.toProduct(fromTarget: \"SwiftBuild-product\", modulesGraph: graph)\n        #expect(swiftBuildProduct != nil, \"SwiftBuild-product should exist in modules graph\")\n\n        let swbBuildServiceProduct = SBOMGraphsConverter.toProduct(fromTarget: \"SWBBuildService-product\", modulesGraph: graph)\n        #expect(swbBuildServiceProduct != nil, \"SWBBuildService-product should exist in modules graph\")\n    }\n\n    @Test(\"toModule(fromTarget:) returns correct module for simple module names\")\n    func toModuleWithSimpleNames() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n\n        let swiftlyModule = SBOMGraphsConverter.toModule(fromTarget: \"Swiftly\", modulesGraph: graph)\n        #expect(swiftlyModule?.name == \"Swiftly\", \"Module name should be 'Swiftly'\")\n\n        let swiftlyCoreModule = SBOMGraphsConverter.toModule(fromTarget: \"SwiftlyCore\", modulesGraph: graph)\n        #expect(swiftlyCoreModule?.name == \"SwiftlyCore\", \"Module name should be 'SwiftlyCore'\")\n    }\n\n    @Test(\"toModule(fromTarget:) returns correct module for system module\")\n    func toModuleWithSystemModules() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n\n        let spmSQLite3Module = SBOMGraphsConverter.toModule(fromTarget: \"SPMSQLite3\", modulesGraph: graph)\n        #expect(spmSQLite3Module?.name == \"SPMSQLite3\", \"Module name should be 'SPMSQLite3'\")\n    }\n\n    @Test(\"toModule(fromTarget:) returns correct module for modules with leading underscores\")\n    func toModuleWithLeadingUnderscores() async throws {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph()\n\n        let asyncFileSystemModule = SBOMGraphsConverter.toModule(fromTarget: \"_AsyncFileSystem\", modulesGraph: graph)\n        #expect(asyncFileSystemModule?.name == \"_AsyncFileSystem\", \"Module name should be '_AsyncFileSystem'\")\n\n        let certificateInternalsModule = SBOMGraphsConverter.toModule(fromTarget: \"_CertificateInternals\", modulesGraph: graph)\n        #expect(\n            certificateInternalsModule?.name == \"_CertificateInternals\",\n            \"Module name should be '_CertificateInternals'\"\n        )\n\n        let cryptoExtrasModule = SBOMGraphsConverter.toModule(fromTarget: \"_CryptoExtras\", modulesGraph: graph)\n        #expect(cryptoExtrasModule?.name == \"_CryptoExtras\", \"Module name should be '_CryptoExtras'\")\n\n        let swiftSyntaxCShimsModule = SBOMGraphsConverter.toModule(fromTarget: \"_SwiftSyntaxCShims\", modulesGraph: graph)\n        #expect(swiftSyntaxCShimsModule?.name == \"_SwiftSyntaxCShims\", \"Module name should be '_SwiftSyntaxCShims'\")\n\n        let swiftlyGraph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n\n        let subprocessCShimsModule = SBOMGraphsConverter.toModule(fromTarget: \"_SubprocessCShims\", modulesGraph: swiftlyGraph)\n        #expect(subprocessCShimsModule?.name == \"_SubprocessCShims\", \"Module name should be '_SubprocessCShims'\")\n    }\n\n    @Test(\"toModule(fromTarget:) returns nil for package_module format (because they're resource bundles)\")\n    func toModuleWithPackageModuleFormat() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n\n        let nioPosixModule = SBOMGraphsConverter.toModule(fromTarget: \"swift-nio_NIOPosix\", modulesGraph: graph)\n        #expect(nioPosixModule == nil)\n\n        let nioSSLModule = SBOMGraphsConverter.toModule(fromTarget: \"swift-nio-ssl_NIOSSL\", modulesGraph: graph)\n        #expect(nioSSLModule == nil)\n\n        // Test modules with leading underscores in package_module format\n        let nioBase64Module = SBOMGraphsConverter.toModule(fromTarget: \"swift-nio__NIOBase64\", modulesGraph: graph)\n        #expect(nioBase64Module == nil)\n\n        let nioDataStructuresModule = SBOMGraphsConverter.toModule(fromTarget: \"swift-nio__NIODataStructures\", modulesGraph: graph)\n        #expect(nioDataStructuresModule == nil)\n\n        let cryptoExtrasModule = SBOMGraphsConverter.toModule(fromTarget: \"swift-crypto__CryptoExtras\", modulesGraph: graph)\n        #expect(cryptoExtrasModule == nil)\n    }\n\n    @Test(\"toModule(fromTarget:) returns nil for product targets\")\n    func toModuleWithProductTargets() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n\n        #expect(\n            SBOMGraphsConverter.toModule(fromTarget: \"swiftly-product\", modulesGraph: graph) == nil,\n            \"Product target should not be recognized as module\"\n        )\n        #expect(\n            SBOMGraphsConverter.toModule(fromTarget: \"test-swiftly-product\", modulesGraph: graph) == nil,\n            \"Product target should not be recognized as module\"\n        )\n        #expect(\n            SBOMGraphsConverter.toModule(fromTarget: \"SwiftBuild-product\", modulesGraph: graph) == nil,\n            \"Product target should not be recognized as module\"\n        )\n        #expect(\n            SBOMGraphsConverter.toModule(fromTarget: \"SWBBuildService-product\", modulesGraph: graph) == nil,\n            \"Product target should not be recognized as module\"\n        )\n    }\n\n    @Test(\"toModule(fromTarget:) handles non-existent modules gracefully\")\n    func toModuleWithNonExistentModules() async throws {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n\n        #expect(SBOMGraphsConverter.toModule(fromTarget: \"NonExistentModule\", modulesGraph: graph) == nil, \"Non-existent module should return nil\")\n        #expect(\n            SBOMGraphsConverter.toModule(fromTarget: \"_NonExistentModule\", modulesGraph: graph) == nil,\n            \"Non-existent module with underscore should return nil\"\n        )\n        #expect(\n            SBOMGraphsConverter.toModule(fromTarget: \"package_NonExistentModule\", modulesGraph: graph) == nil,\n            \"Non-existent package_module should return nil\"\n        )\n    }\n\n    @Test(\"toProduct and toModule are mutually exclusive\")\n    func toProductAndToModuleMutualExclusivity() async throws {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph()\n\n        // Product targets should only work with toProduct\n        let productTarget = \"swiftly-product\"\n        #expect(SBOMGraphsConverter.toProduct(fromTarget: productTarget, modulesGraph: graph) != nil, \"Product target should work with toProduct\")\n        #expect(SBOMGraphsConverter.toModule(fromTarget: productTarget, modulesGraph: graph) == nil, \"Product target should not work with toModule\")\n\n        // Module targets should only work with toModule\n        let moduleTarget = \"Swiftly\"\n        #expect(SBOMGraphsConverter.toModule(fromTarget: moduleTarget, modulesGraph: graph) != nil, \"Module target should work with toModule\")\n        #expect(SBOMGraphsConverter.toProduct(fromTarget: moduleTarget, modulesGraph: graph) == nil, \"Module target should not work with toProduct\")\n\n        // Package_module format should only work with toModule\n        let packageModuleTarget = \"swift-nio_NIOPosix\"\n        if SBOMGraphsConverter.toModule(fromTarget: packageModuleTarget, modulesGraph: graph) != nil {\n            #expect(\n                SBOMGraphsConverter.toProduct(fromTarget: packageModuleTarget, modulesGraph: graph) == nil,\n                \"Package_module format should not work with toProduct\"\n            )\n        }\n    }\n}"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestDependencyGraphHelpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\n\nstruct SBOMTestDependencyGraph {}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestDependencyGraphSPM.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\n\nextension SBOMTestDependencyGraph {\n    static func createSPMDependencyGraph() -> [String: [String]] {\n        [\n            \"SwiftRefactor-product\": [\n                \"SwiftRefactor\",\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n                \"SwiftBasicFormat\",\n                \"SwiftParser\",\n                \"SwiftDiagnostics\",\n                \"SwiftParserDiagnostics\",\n                \"SwiftSyntaxBuilder\",\n            ],\n            \"SwiftPMPackageCollections-product\": [\n                \"PackageCollections\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageModel\",\n                \"_AsyncFileSystem\",\n                \"Basics\",\n                \"SourceControl\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"SWBCSupport\": [],\n            \"swift-crypto_Crypto\": [],\n            \"SwiftPMDataModel-product\": [\n                \"PackageCollections\",\n                \"PackageCollectionsModel\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageMetadata\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"Workspace\",\n                \"_AsyncFileSystem\",\n                \"Basics\",\n                \"PackageCollectionsSigning\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"swift-run-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"Commands\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SWBLibc\": [\"SWBCLibc\"],\n            \"swift-package-collection\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"PackageCollectionsCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"llvmDemangle\": [],\n            \"DriverSupport\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"SwiftDriver-product\",\n            ],\n            \"SwiftBuild_SWBApplePlatform\": [],\n            \"CryptoBoringWrapper\": [\"swift-crypto_CryptoBoringWrapper\", \"CCryptoBoringSSL\", \"CCryptoBoringSSLShims\"],\n            \"swift-crypto_CCryptoBoringSSL\": [],\n            \"swift-test-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftBuild_SWBWindowsPlatform\": [],\n            \"SWBCAS\": [\"SWBCSupport\", \"SWBCLibc\", \"SWBLibc\", \"SWBUtil\", \"ArgumentParser-product\"],\n            \"SWBMacro\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n            ],\n            \"SWBCore\": [\n                \"SwiftBuild_SWBCore\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"SwiftSyntax509\": [],\n            \"SWBProjectModel\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBProtocol\",\n                \"ArgumentParser-product\",\n            ],\n            \"ArgumentParser-product\": [\"ArgumentParser\", \"ArgumentParserToolInfo\"],\n            \"XCBuildSupport-product\": [\n                \"XCBuildSupport\",\n                \"_AsyncFileSystem\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"PackageFingerprint\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"CSystem\": [],\n            \"SwiftBuild\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"SWBProjectModel\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"SwiftSyntax603\": [],\n            \"_CertificateInternals\": [],\n            \"Basics\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"SwiftBuild_SWBQNXPlatform\": [],\n            \"swift-build-prebuilts-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"PackageFingerprint\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"Workspace\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"ArgumentParser-product\",\n            ],\n            \"SwiftBasicFormat\": [\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n            ],\n            \"swift-package-manager\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SwiftSDKCommand\",\n                \"PackageCollectionsCommand\",\n                \"PackageRegistryCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftRefactor\": [\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n                \"SwiftBasicFormat\",\n                \"SwiftParser\",\n                \"SwiftDiagnostics\",\n                \"SwiftParserDiagnostics\",\n                \"SwiftSyntaxBuilder\",\n            ],\n            \"llbuildBuildSystem\": [\"llvmDemangle\", \"llvmSupport\", \"llbuildBasic\", \"llbuildCore\"],\n            \"SwiftSyntax600\": [],\n            \"CompilerPluginSupport\": [\"PackageDescription\"],\n            \"libllbuild\": [\n                \"llvmDemangle\",\n                \"llvmSupport\",\n                \"llbuildBasic\",\n                \"llbuildCore\",\n                \"llbuildBuildSystem\",\n                \"llbuildNinja\",\n            ],\n            \"swift-bootstrap\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n            ],\n            \"SwiftASN1-product\": [\"SwiftASN1\"],\n            \"SwiftDiagnostics\": [\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n            ],\n            \"PackagePlugin-product\": [\"PackagePlugin\"],\n            \"SWBBuildService-product\": [\n                \"SWBBuildService\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"SWBTaskConstruction\",\n                \"SWBTaskExecution\",\n                \"SWBBuildSystem\",\n                \"SWBAndroidPlatform\",\n                \"SWBApplePlatform\",\n                \"SWBGenericUnixPlatform\",\n                \"SWBQNXPlatform\",\n                \"SWBUniversalPlatform\",\n                \"SWBWebAssemblyPlatform\",\n                \"SWBWindowsPlatform\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"swift-package-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"ArgumentParser\": [\"ArgumentParserToolInfo\"],\n            \"swiftpm-testing-helper\": [],\n            \"_InternalTestSupport\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"DriverSupport\",\n                \"PackageFingerprint\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"Workspace\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"TSCTestSupport-product\",\n            ],\n            \"_CryptoExtras\": [\n                \"swift-crypto__CryptoExtras\",\n                \"CCryptoBoringSSL\",\n                \"CCryptoBoringSSLShims\",\n                \"CryptoBoringWrapper\",\n                \"Crypto\",\n                \"SwiftASN1-product\",\n            ],\n            \"SPMLLBuild\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"SwiftBuild_SWBWebAssemblyPlatform\": [],\n            \"package-info\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"PackageFingerprint\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"Workspace\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"SWBGenericUnixPlatform\": [\n                \"SwiftBuild_SWBGenericUnixPlatform\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"SwiftSyntaxBuilder\": [\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n                \"SwiftBasicFormat\",\n                \"SwiftParser\",\n                \"SwiftDiagnostics\",\n                \"SwiftParserDiagnostics\",\n            ],\n            \"_CryptoExtras-product\": [\n                \"_CryptoExtras\",\n                \"swift-crypto__CryptoExtras\",\n                \"CCryptoBoringSSL\",\n                \"CCryptoBoringSSLShims\",\n                \"CryptoBoringWrapper\",\n                \"Crypto\",\n                \"SwiftASN1-product\",\n            ],\n            \"TSCBasic-product\": [\"TSCBasic\", \"TSCLibc\", \"TSCclibc\"],\n            \"SWBBuildService\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"SWBTaskConstruction\",\n                \"SWBTaskExecution\",\n                \"SWBBuildSystem\",\n                \"SWBAndroidPlatform\",\n                \"SWBApplePlatform\",\n                \"SWBGenericUnixPlatform\",\n                \"SWBQNXPlatform\",\n                \"SWBUniversalPlatform\",\n                \"SWBWebAssemblyPlatform\",\n                \"SWBWindowsPlatform\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"SWBWindowsPlatform\": [\n                \"SwiftBuild_SWBWindowsPlatform\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"llbuildCore\": [\"llvmDemangle\", \"llvmSupport\", \"llbuildBasic\"],\n            \"SwiftOptions\": [\"SwiftToolsSupport-auto-product\"],\n            \"BinarySymbols\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n            ],\n            \"SwiftDriver\": [\"SwiftOptions\", \"CSwiftScan\", \"SwiftToolsSupport-auto-product\"],\n            \"LLBuildManifest\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"llbuildSwift\": [\n                \"llvmDemangle\",\n                \"llvmSupport\",\n                \"llbuildBasic\",\n                \"llbuildCore\",\n                \"llbuildBuildSystem\",\n                \"llbuildNinja\",\n                \"libllbuild\",\n            ],\n            \"PackageCollectionsSigning\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageCollectionsModel\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"SourceControl\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"PackageLoading\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"SystemPackage\": [\"CSystem\"],\n            \"OrderedCollections\": [\"InternalCollectionsUtilities\"],\n            \"SwiftFixIt\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n            ],\n            \"swift-crypto_CCryptoBoringSSLShims\": [],\n            \"SWBBuildSystem\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"SWBTaskConstruction\",\n                \"SWBTaskExecution\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"CCryptoBoringSSLShims\": [\"swift-crypto_CCryptoBoringSSLShims\", \"CCryptoBoringSSL\"],\n            \"PackageManagerDocs\": [],\n            \"PackageModel\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"swift-build-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"DequeModule-product\": [\"DequeModule\", \"InternalCollectionsUtilities\"],\n            \"SWBUtil\": [\"SWBCSupport\", \"SWBCLibc\", \"SWBLibc\", \"ArgumentParser-product\"],\n            \"SWBServiceCore\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBProtocol\",\n                \"ArgumentParser-product\",\n            ],\n            \"swift-package-collection-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"PackageCollectionsCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftSyntax510\": [],\n            \"PackageMetadata\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageCollections\",\n                \"PackageFingerprint\",\n                \"PackageLoading\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"SPMBuildCore\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"DequeModule\": [\"InternalCollectionsUtilities\"],\n            \"PackagePlugin\": [],\n            \"_AsyncFileSystem\": [\"SystemPackage-product\"],\n            \"SPMSQLite3\": [],\n            \"llbuildBasic\": [\"llvmDemangle\", \"llvmSupport\"],\n            \"SwiftBuild-product\": [\n                \"SwiftBuild\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"SWBProjectModel\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"TSCBasic\": [\"TSCLibc\", \"TSCclibc\"],\n            \"CCryptoBoringSSL\": [\"swift-crypto_CCryptoBoringSSL\"],\n            \"swift-sdk-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SwiftSDKCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftPM_SBOMModel\": [],\n            \"dummy-swiftc\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"TSCTestSupport\": [\"TSCLibc\", \"TSCclibc\", \"TSCBasic\", \"TSCUtility\"],\n            \"swift-package\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftBuildSupport\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n            ],\n            \"swift-sdk\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SwiftSDKCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"XCBuildSupport\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"SWBApplePlatform\": [\n                \"SwiftBuild_SWBApplePlatform\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"SWBTaskConstruction\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"PackageDescription-product\": [\"PackageDescription\", \"CompilerPluginSupport\"],\n            \"package-info-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"PackageFingerprint\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"Workspace\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"SwiftBuild_SWBAndroidPlatform\": [],\n            \"SWBQNXPlatform\": [\n                \"SwiftBuild_SWBQNXPlatform\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"SwiftSyntax602\": [],\n            \"AppleProductTypes-product\": [\"AppleProductTypes\", \"PackageDescription\"],\n            \"SWBProtocol\": [\"SWBCSupport\", \"SWBCLibc\", \"SWBLibc\", \"SWBUtil\", \"ArgumentParser-product\"],\n            \"SwiftSyntax601\": [],\n            \"PackageCollectionsModel\": [],\n            \"SwiftParser\": [\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n            ],\n            \"swift-package-registry\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"PackageRegistryCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftIDEUtils-product\": [\n                \"SwiftIDEUtils\",\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n                \"SwiftDiagnostics\",\n                \"SwiftParser\",\n            ],\n            \"SwiftIDEUtils\": [\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n                \"SwiftDiagnostics\",\n                \"SwiftParser\",\n            ],\n            \"X509\": [\"_CertificateInternals\", \"SwiftASN1-product\", \"Crypto-product\", \"_CryptoExtras-product\"],\n            \"tsan_utils\": [],\n            \"SwiftPM-auto-product\": [\n                \"PackageCollections\",\n                \"PackageCollectionsModel\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageMetadata\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"Workspace\",\n                \"Build\",\n                \"LLBuildManifest\",\n                \"SourceKitLSPAPI\",\n                \"SPMLLBuild\",\n                \"_AsyncFileSystem\",\n                \"Basics\",\n                \"PackageCollectionsSigning\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"DriverSupport\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n            ],\n            \"swift-build-prebuilts\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"PackageFingerprint\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"Workspace\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"ArgumentParser-product\",\n            ],\n            \"PackageRegistryCommand\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"CSwiftScan\": [],\n            \"_SwiftSyntaxCShims\": [],\n            \"AllExcludingTests\": [\n                \"SwiftPM_SBOMModelTests\",\n                \"SwiftPM-product\",\n                \"SwiftPMDataModel-product\",\n                \"PackageDescription-product\",\n                \"AppleProductTypes-product\",\n                \"PackagePlugin-product\",\n                \"swiftpm-testing-helper-product\",\n                \"swift-test-product\",\n                \"swift-sdk-product\",\n                \"swift-run-product\",\n                \"swift-package-registry-product\",\n                \"swift-package-manager-product\",\n                \"swift-package-collection-product\",\n                \"swift-package-product\",\n                \"swift-experimental-sdk-product\",\n                \"swift-build-prebuilts-product\",\n                \"swift-build-product\",\n                \"swift-bootstrap-product\",\n                \"package-info-product\",\n                \"dummy-swiftc-product\",\n                \"PackageCollections\",\n                \"PackageCollectionsModel\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageMetadata\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"Workspace\",\n                \"Build\",\n                \"LLBuildManifest\",\n                \"SourceKitLSPAPI\",\n                \"SPMLLBuild\",\n                \"XCBuildSupport\",\n                \"PackageDescription\",\n                \"CompilerPluginSupport\",\n                \"AppleProductTypes\",\n                \"PackagePlugin\",\n                \"PackageCollectionsSigning\",\n                \"swiftpm-testing-helper\",\n                \"swift-test\",\n                \"swift-sdk\",\n                \"swift-run\",\n                \"swift-package-registry\",\n                \"swift-package-manager\",\n                \"swift-package-collection\",\n                \"swift-package\",\n                \"swift-experimental-sdk\",\n                \"swift-build-prebuilts\",\n                \"swift-build\",\n                \"swift-bootstrap\",\n                \"package-info\",\n                \"dummy-swiftc\",\n                \"tsan_utils\",\n                \"_InternalTestSupport\",\n                \"_InternalBuildTestSupport\",\n                \"_IntegrationTestSupport\",\n                \"_AsyncFileSystem\",\n                \"SwiftSDKCommand\",\n                \"SwiftFixIt\",\n                \"SwiftBuildSupport\",\n                \"SPMBuildCore\",\n                \"SBOMModel\",\n                \"SwiftPM_SBOMModel\",\n                \"QueryEngine\",\n                \"PackageSigning\",\n                \"PackageRegistryCommand\",\n                \"PackageRegistry\",\n                \"PackageManagerDocs\",\n                \"PackageFingerprint\",\n                \"PackageCollectionsCommand\",\n                \"DriverSupport\",\n                \"CoreCommands\",\n                \"Commands\",\n                \"BinarySymbols\",\n                \"Basics\",\n                \"SwiftPM-auto-product\",\n                \"SwiftPMDataModel-auto-product\",\n                \"XCBuildSupport-product\",\n                \"PackageCollectionsModel-product\",\n                \"SwiftPMPackageCollections-product\",\n            ],\n            \"TSCLibc\": [],\n            \"TSCTestSupport-product\": [\"TSCTestSupport\", \"TSCLibc\", \"TSCclibc\", \"TSCBasic\", \"TSCUtility\"],\n            \"SystemPackage-product\": [\"SystemPackage\", \"CSystem\"],\n            \"PackageDescription\": [],\n            \"SwiftPM-product\": [\n                \"PackageCollections\",\n                \"PackageCollectionsModel\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageMetadata\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"Workspace\",\n                \"Build\",\n                \"LLBuildManifest\",\n                \"SourceKitLSPAPI\",\n                \"SPMLLBuild\",\n                \"_AsyncFileSystem\",\n                \"Basics\",\n                \"PackageCollectionsSigning\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"DriverSupport\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n            ],\n            \"SwiftToolsSupport-auto-product\": [\"TSCBasic\", \"TSCUtility\", \"TSCLibc\", \"TSCclibc\"],\n            \"swiftpm-testing-helper-product\": [],\n            \"swift-bootstrap-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n            ],\n            \"swift-package-registry-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"PackageRegistryCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftBuild_SWBCore\": [],\n            \"PackageCollectionsCommand\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftSDKCommand\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n            ],\n            \"PackageRegistry\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"PackageFingerprint\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageSigning\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"SwiftPM_SBOMModelTests\": [],\n            \"SWBTaskExecution\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"SWBTaskConstruction\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"Crypto-product\": [\"Crypto\", \"swift-crypto_Crypto\"],\n            \"SwiftASN1\": [],\n            \"Build\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n            ],\n            \"QueryEngine\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n            ],\n            \"SwiftParser-product\": [\n                \"SwiftParser\",\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n            ],\n            \"swift-experimental-sdk\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SwiftSDKCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SwiftBuild_SWBUniversalPlatform\": [],\n            \"TSCUtility\": [\"TSCLibc\", \"TSCclibc\", \"TSCBasic\"],\n            \"SWBWebAssemblyPlatform\": [\n                \"SwiftBuild_SWBWebAssemblyPlatform\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"SBOMModel\": [\n                \"SwiftPM_SBOMModel\",\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageCollections\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"SwiftPMDataModel-auto-product\": [\n                \"PackageCollections\",\n                \"PackageCollectionsModel\",\n                \"PackageGraph\",\n                \"PackageLoading\",\n                \"PackageMetadata\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"Workspace\",\n                \"_AsyncFileSystem\",\n                \"Basics\",\n                \"PackageCollectionsSigning\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"swift-experimental-sdk-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SwiftSDKCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"SWBCLibc\": [],\n            \"SwiftSyntax-product\": [\n                \"SwiftSyntax\",\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n            ],\n            \"llbuildSwift-product\": [\n                \"llbuildSwift\",\n                \"llvmDemangle\",\n                \"llvmSupport\",\n                \"llbuildBasic\",\n                \"llbuildCore\",\n                \"llbuildBuildSystem\",\n                \"llbuildNinja\",\n                \"libllbuild\",\n            ],\n            \"SwiftSyntax\": [\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n            ],\n            \"swift-run\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"PackageSigning\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"PackageCollectionsModel-product\": [\"PackageCollectionsModel\"],\n            \"swift-crypto__CryptoExtras\": [],\n            \"SwiftParserDiagnostics\": [\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n                \"SwiftBasicFormat\",\n                \"SwiftDiagnostics\",\n                \"SwiftParser\",\n            ],\n            \"Workspace\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"PackageFingerprint\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"SWBLLBuild\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"ArgumentParser-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"swift-package-manager-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SwiftSDKCommand\",\n                \"PackageCollectionsCommand\",\n                \"PackageRegistryCommand\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"_InternalBuildTestSupport\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"_InternalTestSupport\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"TSCTestSupport-product\",\n            ],\n            \"Crypto\": [\"swift-crypto_Crypto\"],\n            \"PackageCollections\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n            ],\n            \"swift-crypto_CryptoBoringWrapper\": [],\n            \"AppleProductTypes\": [\"PackageDescription\"],\n            \"_IntegrationTestSupport\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"DriverSupport\",\n                \"PackageFingerprint\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"SPMBuildCore\",\n                \"Workspace\",\n                \"_InternalTestSupport\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"TSCTestSupport-product\",\n            ],\n            \"SwiftDiagnostics-product\": [\n                \"SwiftDiagnostics\",\n                \"_SwiftSyntaxCShims\",\n                \"SwiftSyntax509\",\n                \"SwiftSyntax510\",\n                \"SwiftSyntax600\",\n                \"SwiftSyntax601\",\n                \"SwiftSyntax602\",\n                \"SwiftSyntax603\",\n                \"SwiftSyntax\",\n            ],\n            \"llbuildNinja\": [\"llvmDemangle\", \"llvmSupport\", \"llbuildBasic\"],\n            \"llvmSupport\": [\"llvmDemangle\"],\n            \"swift-build\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"swift-test\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"BinarySymbols\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"CoreCommands\",\n                \"PackageCollectionsModel\",\n                \"PackageCollectionsSigning\",\n                \"PackageCollections\",\n                \"SBOMModel\",\n                \"SwiftFixIt\",\n                \"Commands\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"TSCBasic-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n                \"SwiftDiagnostics-product\",\n                \"SwiftIDEUtils-product\",\n                \"SwiftParser-product\",\n                \"SwiftSyntax-product\",\n                \"SwiftRefactor-product\",\n            ],\n            \"InternalCollectionsUtilities\": [],\n            \"ArgumentParserToolInfo\": [],\n            \"CoreCommands\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"PackageFingerprint\",\n                \"PackageSigning\",\n                \"PackageRegistry\",\n                \"Workspace\",\n                \"XCBuildSupport\",\n                \"SwiftBuildSupport\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n                \"Crypto-product\",\n                \"X509-product\",\n                \"SwiftBuild-product\",\n                \"SWBBuildService-product\",\n                \"ArgumentParser-product\",\n            ],\n            \"SwiftBuild_SWBGenericUnixPlatform\": [],\n            \"SwiftDriver-product\": [\"SwiftDriver\", \"SwiftOptions\", \"CSwiftScan\", \"SwiftToolsSupport-auto-product\"],\n            \"SWBTaskConstruction\": [\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"X509-product\": [\n                \"X509\",\n                \"_CertificateInternals\",\n                \"SwiftASN1-product\",\n                \"Crypto-product\",\n                \"_CryptoExtras-product\",\n            ],\n            \"SourceKitLSPAPI\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"LLBuildManifest\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"PackageGraph\",\n                \"SPMBuildCore\",\n                \"SPMLLBuild\",\n                \"DriverSupport\",\n                \"Build\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n                \"llbuildSwift-product\",\n                \"SwiftDriver-product\",\n            ],\n            \"TSCclibc\": [],\n            \"SWBAndroidPlatform\": [\n                \"SwiftBuild_SWBAndroidPlatform\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"libllbuild-product\": [\n                \"libllbuild\",\n                \"llvmDemangle\",\n                \"llvmSupport\",\n                \"llbuildBasic\",\n                \"llbuildCore\",\n                \"llbuildBuildSystem\",\n                \"llbuildNinja\",\n            ],\n            \"dummy-swiftc-product\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"OrderedCollections-product\": [\"OrderedCollections\", \"InternalCollectionsUtilities\"],\n            \"SWBUniversalPlatform\": [\n                \"SwiftBuild_SWBUniversalPlatform\",\n                \"SWBCSupport\",\n                \"SWBCLibc\",\n                \"SWBLibc\",\n                \"SWBUtil\",\n                \"SWBMacro\",\n                \"SWBProtocol\",\n                \"SWBServiceCore\",\n                \"SWBCAS\",\n                \"SWBLLBuild\",\n                \"SWBCore\",\n                \"SWBTaskConstruction\",\n                \"SWBTaskExecution\",\n                \"ArgumentParser-product\",\n                \"SwiftDriver-product\",\n                \"libllbuild-product\",\n                \"llbuildSwift-product\",\n            ],\n            \"PackageGraph\": [\n                \"_AsyncFileSystem\",\n                \"SPMSQLite3\",\n                \"Basics\",\n                \"PackageModel\",\n                \"SourceControl\",\n                \"PackageLoading\",\n                \"SystemPackage-product\",\n                \"DequeModule-product\",\n                \"OrderedCollections-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n        ]\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestDependencyGraphSimple.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\n\nextension SBOMTestDependencyGraph {\n    static func createSimpleDependencyGraph() -> [String: [String]] {\n        [\n            \"App-product\": [\"Utils-product\"],\n            \"Utils-product\": [],\n        ]\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestDependencyGraphSimpleDifferent.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\n\nextension SBOMTestDependencyGraph {\n    static func createSimpleDifferentDependencyGraph() -> [String: [String]] {\n        [\n            \"App-product\": [],\n            \"Utils-product\": [],\n        ]\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestDependencyGraphSwiftly.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\n\nextension SBOMTestDependencyGraph {\n    static func createSwiftlyDependencyGraph() -> [String: [String]] {\n        [\n            \"NIOSSL\": [\n                \"swift-nio-ssl_NIOSSL\",\n                \"CNIOBoringSSL\",\n                \"CNIOBoringSSLShims\",\n                \"NIO-product\",\n                \"NIOCore-product\",\n                \"NIOConcurrencyHelpers-product\",\n                \"NIOTLS-product\",\n            ],\n            \"CLibArchive\": [],\n            \"build-swiftly-release-product\": [\n                \"OpenAPIGenerator-product\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyWebsiteAPI\",\n                \"generate-command-models-product\",\n                \"GenerateCommandModels\",\n                \"SwiftlyCore\",\n                \"CLibArchive\",\n                \"MacOSPlatform\",\n                \"OpenAPIRuntime-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n                \"OpenAPIAsyncHTTPClient-product\",\n                \"Subprocess-product\",\n                \"_NIOFileSystem-product\",\n            ],\n            \"OpenAPIGenerator\": [\n                \"_OpenAPIGeneratorCore\",\n                \"swift-openapi-generator-product\",\n                \"OpenAPIKit-product\",\n                \"OpenAPIKit30-product\",\n                \"OpenAPIKitCompat-product\",\n                \"Algorithms-product\",\n                \"OrderedCollections-product\",\n                \"Yams-product\",\n                \"ArgumentParser-product\",\n            ],\n            \"_NumericsShims\": [],\n            \"NIOEmbedded\": [\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"HTTPTypes-product\": [\"HTTPTypes\"],\n            \"generate-command-models\": [\"ArgumentParser-product\", \"SystemPackage-product\"],\n            \"NIO\": [\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"NIOEmbedded\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"ArgumentParser\": [\"ArgumentParserToolInfo\"],\n            \"swift-nio_NIOPosix\": [],\n            \"AsyncHTTPClient-product\": [\n                \"AsyncHTTPClient\",\n                \"CAsyncHTTPClient\",\n                \"NIO-product\",\n                \"NIOTLS-product\",\n                \"NIOCore-product\",\n                \"NIOPosix-product\",\n                \"NIOHTTP1-product\",\n                \"NIOConcurrencyHelpers-product\",\n                \"NIOHTTP2-product\",\n                \"NIOSSL-product\",\n                \"NIOHTTPCompression-product\",\n                \"NIOSOCKS-product\",\n                \"NIOTransportServices-product\",\n                \"Atomics-product\",\n                \"Algorithms-product\",\n                \"Logging-product\",\n                \"Tracing-product\",\n            ],\n            \"RealModule\": [\"_NumericsShims\"],\n            \"OpenAPIKit30-product\": [\"OpenAPIKit30\", \"OpenAPIKitCore\"],\n            \"swiftly-product\": [\n                \"OpenAPIGenerator-product\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyWebsiteAPI\",\n                \"generate-command-models-product\",\n                \"GenerateCommandModels\",\n                \"SwiftlyCore\",\n                \"CLibArchive\",\n                \"MacOSPlatform\",\n                \"OpenAPIRuntime-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n                \"OpenAPIAsyncHTTPClient-product\",\n                \"Subprocess-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"TSCclibc\": [],\n            \"Subprocess-product\": [\"Subprocess\", \"_SubprocessCShims\", \"SystemPackage-product\"],\n            \"OpenAPIRuntime-product\": [\"OpenAPIRuntime\", \"HTTPTypes-product\"],\n            \"swift-nio__NIOFileSystem\": [],\n            \"NIOConcurrencyHelpers\": [\"CNIOAtomics\"],\n            \"SwiftlyCore\": [\n                \"OpenAPIGenerator-product\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyWebsiteAPI\",\n                \"generate-command-models-product\",\n                \"GenerateCommandModels\",\n                \"OpenAPIRuntime-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n                \"OpenAPIAsyncHTTPClient-product\",\n                \"Subprocess-product\",\n            ],\n            \"SwiftlyDownloadAPI\": [\"OpenAPIGenerator-product\", \"OpenAPIRuntime-product\"],\n            \"CNIOBoringSSL\": [],\n            \"swift-openapi-generator-product\": [\n                \"_OpenAPIGeneratorCore\",\n                \"OpenAPIKit-product\",\n                \"OpenAPIKit30-product\",\n                \"OpenAPIKitCompat-product\",\n                \"Algorithms-product\",\n                \"OrderedCollections-product\",\n                \"Yams-product\",\n                \"ArgumentParser-product\",\n            ],\n            \"Yams-product\": [\"Yams\", \"CYaml\"],\n            \"NIOTransportServices-product\": [\n                \"NIOTransportServices\",\n                \"NIO-product\",\n                \"NIOCore-product\",\n                \"NIOFoundationCompat-product\",\n                \"NIOTLS-product\",\n                \"Atomics-product\",\n            ],\n            \"test-swiftly-product\": [\n                \"OpenAPIGenerator-product\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyWebsiteAPI\",\n                \"generate-command-models-product\",\n                \"GenerateCommandModels\",\n                \"SwiftlyCore\",\n                \"CLibArchive\",\n                \"MacOSPlatform\",\n                \"OpenAPIRuntime-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n                \"OpenAPIAsyncHTTPClient-product\",\n                \"Subprocess-product\",\n            ],\n            \"_NIOFileSystem\": [\n                \"swift-nio__NIOFileSystem\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n                \"SystemPackage-product\",\n            ],\n            \"CAsyncHTTPClient\": [],\n            \"GenerateDocsReference\": [\"generate-docs-reference-product\", \"ArgumentParser-product\"],\n            \"SwiftToolsSupport-auto-product\": [\"TSCBasic\", \"TSCUtility\", \"TSCLibc\", \"TSCclibc\"],\n            \"TestSwiftly\": [\n                \"OpenAPIGenerator-product\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyWebsiteAPI\",\n                \"generate-command-models-product\",\n                \"GenerateCommandModels\",\n                \"SwiftlyCore\",\n                \"CLibArchive\",\n                \"MacOSPlatform\",\n                \"OpenAPIRuntime-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n                \"OpenAPIAsyncHTTPClient-product\",\n                \"Subprocess-product\",\n            ],\n            \"SwiftlyWebsiteAPI\": [\"OpenAPIGenerator-product\", \"OpenAPIRuntime-product\"],\n            \"OpenAPIKitCompat\": [\"OpenAPIKitCore\", \"OpenAPIKit30\", \"OpenAPIKit\"],\n            \"NIOConcurrencyHelpers-product\": [\"NIOConcurrencyHelpers\", \"CNIOAtomics\"],\n            \"SystemPackage-product\": [\"SystemPackage\", \"CSystem\"],\n            \"DequeModule\": [\"InternalCollectionsUtilities\"],\n            \"NIOCore\": [\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"NIOHTTP1-product\": [\n                \"NIOHTTP1\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"NIOEmbedded\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"NIO\",\n                \"CNIOLLHTTP\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"CNIOLLHTTP\": [],\n            \"generate-docs-reference\": [\"ArgumentParser-product\"],\n            \"CNIOBoringSSLShims\": [\"CNIOBoringSSL\"],\n            \"CNIOAtomics\": [],\n            \"NIOHTTPCompression-product\": [\n                \"NIOHTTPCompression\",\n                \"CNIOExtrasZlib\",\n                \"NIO-product\",\n                \"NIOCore-product\",\n                \"NIOHTTP1-product\",\n            ],\n            \"_NIODataStructures\": [],\n            \"Logging-product\": [\"Logging\"],\n            \"Algorithms\": [\"RealModule-product\"],\n            \"NIOSOCKS\": [\"NIO-product\", \"NIOCore-product\"],\n            \"SwiftlyDocs\": [],\n            \"OpenAPIKit\": [\"OpenAPIKitCore\"],\n            \"_NIOBase64\": [],\n            \"OpenAPIRuntime\": [\"HTTPTypes-product\"],\n            \"GenerateCommandModels\": [\n                \"generate-command-models-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n            ],\n            \"generate-docs-reference-product\": [\"ArgumentParser-product\"],\n            \"NIOSOCKS-product\": [\"NIOSOCKS\", \"NIO-product\", \"NIOCore-product\"],\n            \"ServiceContextModule-product\": [\"ServiceContextModule\"],\n            \"MacOSPlatform\": [\n                \"OpenAPIGenerator-product\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyWebsiteAPI\",\n                \"generate-command-models-product\",\n                \"GenerateCommandModels\",\n                \"SwiftlyCore\",\n                \"OpenAPIRuntime-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n                \"OpenAPIAsyncHTTPClient-product\",\n                \"Subprocess-product\",\n            ],\n            \"AsyncHTTPClient\": [\n                \"CAsyncHTTPClient\",\n                \"NIO-product\",\n                \"NIOTLS-product\",\n                \"NIOCore-product\",\n                \"NIOPosix-product\",\n                \"NIOHTTP1-product\",\n                \"NIOConcurrencyHelpers-product\",\n                \"NIOHTTP2-product\",\n                \"NIOSSL-product\",\n                \"NIOHTTPCompression-product\",\n                \"NIOSOCKS-product\",\n                \"NIOTransportServices-product\",\n                \"Atomics-product\",\n                \"Algorithms-product\",\n                \"Logging-product\",\n                \"Tracing-product\",\n            ],\n            \"TSCLibc\": [],\n            \"OpenAPIKitCompat-product\": [\"OpenAPIKitCompat\", \"OpenAPIKitCore\", \"OpenAPIKit30\", \"OpenAPIKit\"],\n            \"Subprocess\": [\"_SubprocessCShims\", \"SystemPackage-product\"],\n            \"NIOSSL-product\": [\n                \"NIOSSL\",\n                \"swift-nio-ssl_NIOSSL\",\n                \"CNIOBoringSSL\",\n                \"CNIOBoringSSLShims\",\n                \"NIO-product\",\n                \"NIOCore-product\",\n                \"NIOConcurrencyHelpers-product\",\n                \"NIOTLS-product\",\n            ],\n            \"TSCUtility\": [\"TSCLibc\", \"TSCclibc\", \"TSCBasic\"],\n            \"NIOPosix\": [\n                \"swift-nio_NIOPosix\",\n                \"CNIOLinux\",\n                \"CNIODarwin\",\n                \"CNIOWindows\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"CNIOPosix\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"swiftly_SwiftlyTests\": [],\n            \"Swiftly\": [\n                \"OpenAPIGenerator-product\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyWebsiteAPI\",\n                \"generate-command-models-product\",\n                \"GenerateCommandModels\",\n                \"SwiftlyCore\",\n                \"CLibArchive\",\n                \"MacOSPlatform\",\n                \"OpenAPIRuntime-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n                \"OpenAPIAsyncHTTPClient-product\",\n                \"Subprocess-product\",\n                \"SwiftToolsSupport-auto-product\",\n            ],\n            \"NIOPosix-product\": [\n                \"NIOPosix\",\n                \"swift-nio_NIOPosix\",\n                \"CNIOLinux\",\n                \"CNIODarwin\",\n                \"CNIOWindows\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"CNIOPosix\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"OrderedCollections-product\": [\"OrderedCollections\", \"InternalCollectionsUtilities\"],\n            \"CNIOExtrasZlib\": [],\n            \"_AtomicsShims\": [],\n            \"OpenAPIKit-product\": [\"OpenAPIKit\", \"OpenAPIKitCore\"],\n            \"Atomics-product\": [\"Atomics\", \"_AtomicsShims\"],\n            \"CSystem\": [],\n            \"HTTPTypes\": [],\n            \"TSCBasic\": [\"TSCLibc\", \"TSCclibc\"],\n            \"OpenAPIKit30\": [\"OpenAPIKitCore\"],\n            \"NIOHTTP2-product\": [\n                \"NIOHTTP2\",\n                \"NIOHPACK\",\n                \"NIO-product\",\n                \"NIOCore-product\",\n                \"NIOConcurrencyHelpers-product\",\n                \"NIOHTTP1-product\",\n                \"NIOTLS-product\",\n                \"Atomics-product\",\n            ],\n            \"CNIOLinux\": [],\n            \"NIOFoundationCompat-product\": [\n                \"NIOFoundationCompat\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"NIOEmbedded\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"NIO\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"Algorithms-product\": [\"Algorithms\", \"RealModule-product\"],\n            \"CYaml\": [],\n            \"AllExcludingTests\": [\n                \"swiftly_SwiftlyTests\",\n                \"swiftly-product\",\n                \"test-swiftly-product\",\n                \"generate-docs-reference-product\",\n                \"generate-command-models-product\",\n                \"build-swiftly-release-product\",\n                \"Swiftly\",\n                \"TestSwiftly\",\n                \"generate-docs-reference\",\n                \"generate-command-models\",\n                \"build-swiftly-release\",\n                \"SwiftlyWebsiteAPI\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyDocs\",\n                \"SwiftlyCore\",\n                \"MacOSPlatform\",\n                \"GenerateDocsReference\",\n                \"GenerateCommandModels\",\n            ],\n            \"NIOCore-product\": [\n                \"NIOCore\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"NIOTLS\": [\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"NIOEmbedded\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"NIO\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"OpenAPIGenerator-product\": [\"OpenAPIGenerator\"],\n            \"Instrumentation\": [\"ServiceContextModule-product\"],\n            \"NIOTransportServices\": [\n                \"NIO-product\",\n                \"NIOCore-product\",\n                \"NIOFoundationCompat-product\",\n                \"NIOTLS-product\",\n                \"Atomics-product\",\n            ],\n            \"OpenAPIAsyncHTTPClient\": [\n                \"OpenAPIRuntime-product\",\n                \"HTTPTypes-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n            ],\n            \"ServiceContextModule\": [],\n            \"NIOHTTPCompression\": [\"CNIOExtrasZlib\", \"NIO-product\", \"NIOCore-product\", \"NIOHTTP1-product\"],\n            \"NIOFoundationCompat\": [\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"NIOEmbedded\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"NIO\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"CNIOWindows\": [],\n            \"ArgumentParserToolInfo\": [],\n            \"CNIOPosix\": [],\n            \"NIOTLS-product\": [\n                \"NIOTLS\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"NIOEmbedded\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"NIO\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"Tracing\": [\"Instrumentation\", \"ServiceContextModule-product\"],\n            \"_SubprocessCShims\": [],\n            \"OrderedCollections\": [\"InternalCollectionsUtilities\"],\n            \"NIOHTTP2\": [\n                \"NIOHPACK\",\n                \"NIO-product\",\n                \"NIOCore-product\",\n                \"NIOConcurrencyHelpers-product\",\n                \"NIOHTTP1-product\",\n                \"NIOTLS-product\",\n                \"Atomics-product\",\n            ],\n            \"CNIODarwin\": [],\n            \"InternalCollectionsUtilities\": [],\n            \"Tracing-product\": [\"Tracing\", \"Instrumentation\", \"ServiceContextModule-product\"],\n            \"CNIOWASI\": [],\n            \"RealModule-product\": [\"RealModule\", \"_NumericsShims\"],\n            \"_OpenAPIGeneratorCore\": [\n                \"OpenAPIKit-product\",\n                \"OpenAPIKit30-product\",\n                \"OpenAPIKitCompat-product\",\n                \"Algorithms-product\",\n                \"OrderedCollections-product\",\n                \"Yams-product\",\n            ],\n            \"SystemPackage\": [\"CSystem\"],\n            \"_NIOFileSystem-product\": [\n                \"_NIOFileSystem\",\n                \"NIOFileSystem\",\n                \"swift-nio__NIOFileSystem\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n                \"SystemPackage-product\",\n            ],\n            \"NIO-product\": [\n                \"NIO\",\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"NIOEmbedded\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"ArgumentParser-product\": [\"ArgumentParser\", \"ArgumentParserToolInfo\"],\n            \"OpenAPIKitCore\": [],\n            \"build-swiftly-release\": [\n                \"OpenAPIGenerator-product\",\n                \"SwiftlyDownloadAPI\",\n                \"SwiftlyWebsiteAPI\",\n                \"generate-command-models-product\",\n                \"GenerateCommandModels\",\n                \"SwiftlyCore\",\n                \"CLibArchive\",\n                \"MacOSPlatform\",\n                \"OpenAPIRuntime-product\",\n                \"ArgumentParser-product\",\n                \"SystemPackage-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n                \"OpenAPIAsyncHTTPClient-product\",\n                \"Subprocess-product\",\n                \"_NIOFileSystem-product\",\n            ],\n            \"swift-nio-ssl_NIOSSL\": [],\n            \"NIOHPACK\": [\"NIO-product\", \"NIOCore-product\", \"NIOConcurrencyHelpers-product\", \"NIOHTTP1-product\"],\n            \"NIOFileSystem\": [\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"_NIOFileSystem\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n                \"SystemPackage-product\",\n            ],\n            \"OpenAPIAsyncHTTPClient-product\": [\n                \"OpenAPIAsyncHTTPClient\",\n                \"OpenAPIRuntime-product\",\n                \"HTTPTypes-product\",\n                \"AsyncHTTPClient-product\",\n                \"NIOFoundationCompat-product\",\n            ],\n            \"DequeModule-product\": [\"DequeModule\", \"InternalCollectionsUtilities\"],\n            \"generate-command-models-product\": [\"ArgumentParser-product\", \"SystemPackage-product\"],\n            \"NIOHTTP1\": [\n                \"CNIOAtomics\",\n                \"NIOConcurrencyHelpers\",\n                \"_NIOBase64\",\n                \"CNIODarwin\",\n                \"CNIOLinux\",\n                \"CNIOWindows\",\n                \"CNIOWASI\",\n                \"_NIODataStructures\",\n                \"NIOCore\",\n                \"NIOEmbedded\",\n                \"CNIOPosix\",\n                \"NIOPosix\",\n                \"NIO\",\n                \"CNIOLLHTTP\",\n                \"DequeModule-product\",\n                \"Atomics-product\",\n            ],\n            \"Atomics\": [\"_AtomicsShims\"],\n            \"Logging\": [],\n            \"Yams\": [\"CYaml\"],\n        ]\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestError.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\nenum SBOMTestError: Error {\n    case failedToCaptureModulesGraph\n    case failedToGetCurrentBranch\n}"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestModulesGraphConditional.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    private static let conditionalDeps: [MockDependency] = [\n        .sourceControl(path: \"./Package1\", requirement: .upToNextMajor(from: \"1.0.0\"), products: .specific([\"Package1Library1\"])),\n        .sourceControl(path: \"./Package2\", requirement: .upToNextMajor(from: \"1.0.0\"), products: .specific([\"Package2Library1\"]))\n    ]\n\n    static func createConditionalModulesGraph(traitConfiguration: TraitConfiguration) async throws -> ModulesGraph {\n       let sandbox = AbsolutePath(\"/tmp/ws-traits-\\(UUID().uuidString)\")\n        let fs = InMemoryFileSystem()\n        \n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"PackageConditionalDeps\",\n                    targets: [\n                        try MockTarget(\n                            name: \"PackageConditionalDeps\",\n                            dependencies: [\n                                .product(\n                                    name: \"Package1Library1\",\n                                    package: \"Package1\",\n                                    condition: .init(traits: [\"EnablePackage1Dep\"])\n                                ),\n                                .product(\n                                    name: \"Package2Library1\",\n                                    package: \"Package2\",\n                                    condition: .init(traits: [\"EnablePackage2Dep\"])\n                                )\n                            ]\n                        )\n                    ],\n                    products: [\n                        MockProduct(name: \"PackageConditionalDeps\", modules: [\"PackageConditionalDeps\"])\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Package1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Package2\", requirement: .upToNextMajor(from: \"1.0.0\"))\n                    ],\n                    traits: [\n                        .init(name: \"default\", enabledTraits: [\"EnablePackage1Dep\"]),\n                        \"EnablePackage1Dep\",\n                        \"EnablePackage2Dep\"\n                    ]\n                )\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Package1\",\n                    targets: [try MockTarget(name: \"Package1Library1\")],\n                    products: [MockProduct(name: \"Package1Library1\", modules: [\"Package1Library1\"])],\n                    traits: [\"Package1Trait1\"],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Package2\",\n                    targets: [try MockTarget(name: \"Package2Library1\")],\n                    products: [MockProduct(name: \"Package2Library1\", modules: [\"Package2Library1\"])],\n                    versions: [\"1.0.0\"]\n                )\n            ],\n            traitConfiguration: traitConfiguration\n        )\n        \n        var capturedGraph: ModulesGraph?\n        try await workspace.checkPackageGraph(\n            roots: [\"PackageConditionalDeps\"],\n            deps: conditionalDeps\n        ) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            capturedGraph = graph\n        }\n        \n        guard let graph = capturedGraph else {\n            throw SBOMTestError.failedToCaptureModulesGraph\n        }\n        return graph\n    }\n}\n\n\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestModulesGraphHelpers.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\n/// A test case that bundles a ModulesGraph with its expected test outcomes\nstruct SBOMTestCase {\n    let name: String\n    let graph: ModulesGraph\n    let store: ResolvedPackagesStore\n    let expectations: TestExpectations\n    \n    struct TestExpectations {\n        let totalComponentCount: Int\n        let expectedPackageIds: Set<String>\n        let rootPackage: String\n        let rootPackagePrefix: String\n        let expectedRootProductCount: Int\n        let expectedRootProductNames: Set<String>\n    }\n    \n    /// Creates a test case for the simple test graph\n    static func createSimpleTestCase() throws -> SBOMTestCase {\n        let graph = try SBOMTestModulesGraph.createSimpleModulesGraph()\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let expectations = TestExpectations(\n            totalComponentCount: 4,\n            expectedPackageIds: Set([\"MyApp\", \"Utils\"]),\n            rootPackage: \"MyApp\",\n            rootPackagePrefix: \"MyApp:\",\n            expectedRootProductCount: 1,\n            expectedRootProductNames: Set([\"App\"])\n        )\n        return SBOMTestCase(\n            name: \"Simple\",\n            graph: graph,\n            store: store,\n            expectations: expectations\n        )\n    }\n    \n    /// Creates a test case for the SPM test graph\n    static func createSPMTestCase(rootPath: String = \"/swift-package-manager\") throws -> SBOMTestCase {\n        let graph = try SBOMTestModulesGraph.createSPMModulesGraph(rootPath: rootPath)\n        let store = try SBOMTestStore.createSPMResolvedPackagesStore()\n        let expectations = TestExpectations(\n            totalComponentCount: 57,\n            expectedPackageIds: Set([\n                \"swift-build\", \"swift-llbuild\", \"swift-driver\", \"swift-certificates\", \"swift-syntax\",\n                \"swift-tools-support-core\",\n                \"swift-crypto\", \"swift-argument-parser\", \"swift-asn1\", \"swift-collections\", \"swift-system\",\n                \"swift-package-manager\",\n                \"swift-toolchain-sqlite\",\n            ]),\n            rootPackage: \"swift-package-manager\",\n            rootPackagePrefix: \"swift-package-manager:\",\n            expectedRootProductCount: 24,\n            expectedRootProductNames: Set([\n                \"swift-package-registry\", \"PackageDescription\", \"PackageCollectionsModel\", \"swift-test\",\n                \"swift-package-collection\",\n                \"swift-sdk\", \"SwiftPMPackageCollections\", \"swift-experimental-sdk\", \"swift-package\", \"swift-run\",\n                \"PackagePlugin\",\n                \"swift-build-prebuilts\", \"SwiftPMDataModel\", \"swift-build\", \"package-info\", \"dummy-swiftc\",\n                \"SwiftPMDataModel-auto\",\n                \"XCBuildSupport\", \"swift-package-manager\", \"SwiftPM-auto\", \"AppleProductTypes\", \"swift-bootstrap\",\n                \"swiftpm-testing-helper\",\n                \"SwiftPM\",\n            ])\n        )\n        return SBOMTestCase(\n            name: \"SPM\",\n            graph: graph,\n            store: store,\n            expectations: expectations\n        )\n    }\n    \n    /// Creates a test case for the Swiftly test graph\n    static func createSwiftlyTestCase(rootPath: String = \"/tmp/swiftly-mock\") throws -> SBOMTestCase {\n        let graph = try SBOMTestModulesGraph.createSwiftlyModulesGraph(rootPath: rootPath)\n        let store = try SBOMTestStore.createSwiftlyResolvedPackagesStore()\n        let expectations = TestExpectations(\n            totalComponentCount: 64,\n            expectedPackageIds: Set([\"swift-nio-http2\", \"swift-tools-support-core\",\n                                     \"swift-nio-transport-services\", \"swiftly\",\n                                     \"swift-distributed-tracing\", \"swift-service-context\", \"swift-nio-ssl\",\n                                     \"swift-nio\", \"swift-collections\", \"swift-system\", \"swift-algorithms\",\n                                     \"swift-openapi-generator\", \"swift-openapi-async-http-client\",\n                                     \"swift-argument-parser\", \"openapikit\", \"yams\", \"swift-subprocess\",\n                                     \"async-http-client\", \"swift-log\", \"swift-atomics\", \"swift-numerics\",\n                                     \"swift-openapi-runtime\", \"swift-http-types\", \"swift-nio-extras\"]),\n            rootPackage: \"swiftly\",\n            rootPackagePrefix: \"swiftly:\",\n            expectedRootProductCount: 6,\n            expectedRootProductNames: Set([\n                \"test-swiftly\",\n                \"swiftly\",\n                \"generate-command-models\",\n                \"SwiftlyTests\",\n                \"build-swiftly-release\",\n                \"generate-docs-reference\",\n            ])\n        )\n        return SBOMTestCase(\n            name: \"Swiftly\",\n            graph: graph,\n            store: store,\n            expectations: expectations\n        )\n    }\n}\n\nenum SBOMTestModulesGraph {\n    // MARK: - Helper functions\n\n    static func createSwiftModule(\n        name: String,\n        dependencies: [Module.Dependency] = [],\n        packageAccess: Bool = false,\n        type: Module.Kind = .library\n    ) -> SwiftModule {\n        let path = AbsolutePath(\"/\\(name)\")\n        let sources = Sources(paths: [], root: path)\n        return SwiftModule(\n            name: name,\n            type: type,\n            path: path,\n            sources: sources,\n            dependencies: dependencies,\n            packageAccess: packageAccess,\n            usesUnsafeFlags: false,\n            implicit: false\n        )\n    }\n\n    static func createPackage(\n        identity: PackageIdentity,\n        displayName: String,\n        path: String,\n        modules: [Module],\n        products: [Product]\n    ) -> Package {\n        let manifest = Manifest.createFileSystemManifest(\n            displayName: displayName,\n            path: AbsolutePath(path),\n            toolsVersion: .vNext\n        )\n\n        return Package(\n            identity: identity,\n            manifest: manifest,\n            path: AbsolutePath(path),\n            targets: modules,\n            products: products,\n            targetSearchPath: AbsolutePath(path).appending(\"Sources\"),\n            testTargetSearchPath: AbsolutePath(path).appending(\"Tests\")\n        )\n    }\n\n    static func createResolvedModule(\n        packageIdentity: PackageIdentity,\n        module: Module,\n        dependencies: [ResolvedModule.Dependency] = [],\n        supportedPlatforms: [SupportedPlatform] = []\n    ) -> ResolvedModule {\n        ResolvedModule(\n            packageIdentity: packageIdentity,\n            underlying: module,\n            dependencies: dependencies,\n            defaultLocalization: nil,\n            supportedPlatforms: supportedPlatforms,\n            platformConstraint: .all,\n            platformVersionProvider: PlatformVersionProvider(implementation: .minimumDeploymentTargetDefault)\n        )\n    }\n\n    static func createResolvedProduct(\n        packageIdentity: PackageIdentity,\n        product: Product,\n        modules: IdentifiableSet<ResolvedModule>\n    ) -> ResolvedProduct {\n        ResolvedProduct(\n            packageIdentity: packageIdentity,\n            product: product,\n            modules: modules\n        )\n    }\n\n    static func createResolvedPackage(\n        package: Package,\n        modules: IdentifiableSet<ResolvedModule>,\n        products: [ResolvedProduct],\n        dependencies: [PackageIdentity] = [],\n        enabledTraits: Set<String>? = nil\n    ) -> ResolvedPackage {\n        ResolvedPackage(\n            underlying: package,\n            defaultLocalization: nil,\n            supportedPlatforms: [],\n            dependencies: dependencies,\n            enabledTraits: enabledTraits,\n            modules: modules,\n            products: products,\n            registryMetadata: nil,\n            platformVersionProvider: PlatformVersionProvider(implementation: .minimumDeploymentTargetDefault)\n        )\n    }\n\n    static func createProduct(\n        name: String,\n        type: ProductType,\n        moduleType: Module.Kind = .library\n    ) throws -> ResolvedProduct {\n        let packageName = PackageIdentity.plain(\"Package\\(name)\")\n        let module = self.createSwiftModule(\n            name: \"\\(name)Module\",\n            type: moduleType\n        )\n        let product = try Product(\n            package: packageName,\n            name: name,\n            type: type,\n            modules: [module]\n        )\n        let resolvedModule = self.createResolvedModule(\n            packageIdentity: packageName,\n            module: module\n        )\n        return self.createResolvedProduct(\n            packageIdentity: packageName,\n            product: product,\n            modules: IdentifiableSet([resolvedModule])\n        )\n    }\n\n    static func createPackage(\n        name: String,\n        products: [ResolvedProduct],\n        modules: [Module] = []\n    ) throws -> ResolvedPackage {\n        let packageName = PackageIdentity.plain(\"Package\\(name)\")\n        let package = self.createPackage(\n            identity: packageName,\n            displayName: name,\n            path: \"/\\(name)\",\n            modules: modules,\n            products: products.map(\\.underlying)\n        )\n        let resolvedModules = modules.map { module in\n            self.createResolvedModule(\n                packageIdentity: packageName,\n                module: module\n            )\n        }\n        return self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet(resolvedModules),\n            products: products\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestModulesGraphSPM.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    /// Creates a complete SPM ModulesGraph with all dependencies including the root SwiftPM package\n    /// This assembles all the individual package fixtures into a complete dependency graph\n    /// The root package includes the SwiftPMDataModel product that was previously missing\n    static func createSPMModulesGraph(rootPath: String = \"/swift-package-manager\") throws -> ModulesGraph {\n        // MARK: - Create all foundation packages\n\n        let systemPackage = try createSPMSwiftSystemPackage()\n        let collectionsPackage = try createSPMSwiftCollectionsPackage()\n        let argumentParserPackage = try createSPMSwiftArgumentParserPackage()\n        let sqlitePackage = try createSPMSwiftToolchainSQLitePackage()\n\n        // MARK: - Create build tooling packages\n\n        let llbuildPackage = try createSPMSwiftLLBuildPackage(\n            swiftToolchainCSQLiteProduct: sqlitePackage.resolvedProducts[0]\n        )\n\n        let toolsSupportPackage = try createSPMSwiftToolsSupportCorePackage()\n\n        let driverPackage = try createSPMSwiftDriverPackage(\n            swiftToolsSupportAutoProduct: toolsSupportPackage.resolvedProducts[2],\n            llbuildSwiftProduct: llbuildPackage.resolvedProducts[3],\n            argumentParserProduct: argumentParserPackage.resolvedProducts[0]\n        )\n\n        // MARK: - Create security packages\n\n        let asn1Package = try createSPMSwiftASN1Package()\n\n        let cryptoPackage = try createSPMSwiftCryptoPackage(\n            swiftASN1Product: asn1Package.resolvedProducts[0]\n        )\n\n        let certificatesPackage = try createSPMSwiftCertificatesPackage(\n            swiftASN1Product: asn1Package.resolvedProducts[0],\n            cryptoProduct: cryptoPackage.resolvedProducts[0],\n            cryptoExtrasProduct: cryptoPackage.resolvedProducts[1]\n        )\n\n        // MARK: - Create documentation packages\n\n        let symbolKitPackage = try createSPMSwiftDoccSymbolKitPackage()\n\n        let doccPluginPackage = try createSPMSwiftDoccPluginPackage(\n            symbolKitProduct: symbolKitPackage.resolvedProducts[0]\n        )\n\n        // MARK: - Create swift-syntax package\n\n        let syntaxPackage = try createSPMSwiftSyntaxPackage()\n\n        // MARK: - Create swift-build package\n\n        let buildPackage = try createSPMSwiftBuildPackage(\n            swiftSyntaxProduct: syntaxPackage.resolvedProducts[0],\n            swiftParserProduct: syntaxPackage.resolvedProducts[2],\n            swiftDriverProduct: driverPackage.resolvedProducts[0],\n            swiftDriverExecutionProduct: driverPackage.resolvedProducts[2],\n            llbuildSwiftProduct: llbuildPackage.resolvedProducts[3],\n            swiftToolsSupportAutoProduct: toolsSupportPackage.resolvedProducts[2],\n            argumentParserProduct: argumentParserPackage.resolvedProducts[0],\n            systemPackageProduct: systemPackage.resolvedProducts[0],\n            cryptoProduct: cryptoPackage.resolvedProducts[0],\n            x509Product: certificatesPackage.resolvedProducts[0]\n        )\n\n        // MARK: - Create ROOT SwiftPM package (with SwiftPMDataModel product)\n\n        let rootPackage = try createSPMRootPackageComplete(\n            rootPath: rootPath,\n            systemPackageProduct: systemPackage.resolvedProducts[0],\n            dequeModuleProduct: collectionsPackage.resolvedProducts[0],\n            orderedCollectionsProduct: collectionsPackage.resolvedProducts[6],\n            argumentParserProduct: argumentParserPackage.resolvedProducts[0],\n            llbuildSwiftProduct: llbuildPackage.resolvedProducts[3],\n            swiftDriverProduct: driverPackage.resolvedProducts[0],\n            swiftToolsSupportAutoProduct: toolsSupportPackage.resolvedProducts[2],\n            tscBasicProduct: toolsSupportPackage.resolvedProducts[0],\n            tscTestSupportProduct: toolsSupportPackage.resolvedProducts[3],\n            cryptoProduct: cryptoPackage.resolvedProducts[0],\n            x509Product: certificatesPackage.resolvedProducts[0],\n            swiftToolchainCSQLiteProduct: sqlitePackage.resolvedProducts[0],\n            swiftIDEUtilsProduct: syntaxPackage.resolvedProducts[7],\n            swiftRefactorProduct: syntaxPackage.resolvedProducts[8],\n            swiftDiagnosticsProduct: syntaxPackage.resolvedProducts[3],\n            swiftParserProduct: syntaxPackage.resolvedProducts[2],\n            swiftSyntaxProduct: syntaxPackage.resolvedProducts[0],\n            swiftBuildProduct: buildPackage.resolvedProducts[5],\n            swbBuildServiceProduct: buildPackage.resolvedProducts[0]\n        )\n\n        // MARK: - Assemble all packages\n\n        let allResolvedPackages: IdentifiableSet<ResolvedPackage> = IdentifiableSet([\n            rootPackage.resolvedPackage,\n            buildPackage.resolvedPackage,\n            syntaxPackage.resolvedPackage,\n            driverPackage.resolvedPackage,\n            llbuildPackage.resolvedPackage,\n            toolsSupportPackage.resolvedPackage,\n            argumentParserPackage.resolvedPackage,\n            systemPackage.resolvedPackage,\n            collectionsPackage.resolvedPackage,\n            sqlitePackage.resolvedPackage,\n            asn1Package.resolvedPackage,\n            cryptoPackage.resolvedPackage,\n            certificatesPackage.resolvedPackage,\n            symbolKitPackage.resolvedPackage,\n            doccPluginPackage.resolvedPackage,\n        ])\n\n        let rootDependencies = [\n            buildPackage.resolvedPackage,\n            syntaxPackage.resolvedPackage,\n            driverPackage.resolvedPackage,\n            llbuildPackage.resolvedPackage,\n            toolsSupportPackage.resolvedPackage,\n            argumentParserPackage.resolvedPackage,\n            systemPackage.resolvedPackage,\n            collectionsPackage.resolvedPackage,\n            sqlitePackage.resolvedPackage,\n            asn1Package.resolvedPackage,\n            cryptoPackage.resolvedPackage,\n            certificatesPackage.resolvedPackage,\n            symbolKitPackage.resolvedPackage,\n            doccPluginPackage.resolvedPackage,\n        ]\n\n        let packageReferences = [\n            rootPackage.packageRef,\n            buildPackage.packageRef,\n            syntaxPackage.packageRef,\n            driverPackage.packageRef,\n            llbuildPackage.packageRef,\n            toolsSupportPackage.packageRef,\n            argumentParserPackage.packageRef,\n            systemPackage.packageRef,\n            collectionsPackage.packageRef,\n            sqlitePackage.packageRef,\n            asn1Package.packageRef,\n            cryptoPackage.packageRef,\n            certificatesPackage.packageRef,\n            symbolKitPackage.packageRef,\n            doccPluginPackage.packageRef,\n        ]\n\n        // MARK: - Create and return ModulesGraph\n\n        return try ModulesGraph(\n            rootPackages: [rootPackage.resolvedPackage],\n            rootDependencies: rootDependencies,\n            packages: allResolvedPackages,\n            dependencies: packageReferences,\n            binaryArtifacts: [:]\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestModulesGraphSimple.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    static func createSimpleModulesGraph(rootPath: String = \"/tmp/simple-mock\") throws -> ModulesGraph {\n        // - MyApp package depends on Utils package and App product\n        // - Utils package depends on Utils product\n        // - App product depends on Utils product\n\n        // Package identities\n        let appIdentity = PackageIdentity.plain(\"MyApp\")\n        let utilsIdentity = PackageIdentity.plain(\"Utils\")\n\n        // Create modules for Utils package (dependency)\n        let utilsModule = self.createSwiftModule(name: \"Utils\")\n\n        // Create modules for MyApp package (root)\n        let appModule = self.createSwiftModule(name: \"App\", type: .executable)\n\n        // Create products\n        let utilsProduct = try Product(\n            package: utilsIdentity,\n            name: \"Utils\",\n            type: .library(.automatic),\n            modules: [utilsModule]\n        )\n\n        let appProduct = try Product(\n            package: appIdentity,\n            name: \"App\",\n            type: .executable,\n            modules: [appModule]\n        )\n\n        // Create packages\n        let utilsPackage = self.createPackage(\n            identity: utilsIdentity,\n            displayName: \"Utils\",\n            path: \"/Utils\",\n            modules: [utilsModule],\n            products: [utilsProduct]\n        )\n\n        let appPackage = self.createPackage(\n            identity: appIdentity,\n            displayName: \"MyApp\",\n            path: rootPath,\n            modules: [appModule],\n            products: [appProduct]\n        )\n\n        // Create resolved modules\n        let resolvedUtilsModule = self.createResolvedModule(\n            packageIdentity: utilsIdentity,\n            module: utilsModule\n        )\n\n        let resolvedAppModule = self.createResolvedModule(\n            packageIdentity: appIdentity,\n            module: appModule,\n            dependencies: [\n                .product(self.createResolvedProduct(\n                    packageIdentity: utilsIdentity,\n                    product: utilsProduct,\n                    modules: IdentifiableSet([resolvedUtilsModule])\n                ), conditions: []),\n            ]\n        )\n\n        // Create resolved products\n        let resolvedUtilsProduct = self.createResolvedProduct(\n            packageIdentity: utilsIdentity,\n            product: utilsProduct,\n            modules: IdentifiableSet([resolvedUtilsModule])\n        )\n\n        let resolvedAppProduct = self.createResolvedProduct(\n            packageIdentity: appIdentity,\n            product: appProduct,\n            modules: IdentifiableSet([resolvedAppModule])\n        )\n\n        // Create resolved packages\n        let resolvedUtilsPackage = self.createResolvedPackage(\n            package: utilsPackage,\n            modules: IdentifiableSet([resolvedUtilsModule]),\n            products: [resolvedUtilsProduct]\n        )\n\n        let resolvedAppPackage = self.createResolvedPackage(\n            package: appPackage,\n            modules: IdentifiableSet([resolvedAppModule]),\n            products: [resolvedAppProduct],\n            dependencies: [utilsIdentity]\n        )\n\n        // Create package references\n        let utilsRef = PackageReference(\n            identity: utilsIdentity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/example/utils.git\"))\n        )\n\n        // Create the ModulesGraph\n        return try ModulesGraph(\n            rootPackages: [resolvedAppPackage],\n            rootDependencies: [resolvedUtilsPackage],\n            packages: IdentifiableSet([resolvedAppPackage, resolvedUtilsPackage]),\n            dependencies: [utilsRef],\n            binaryArtifacts: [:]\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestModulesGraphSwiftly.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    /// Creates a complete ModulesGraph for the Swiftly project with all dependencies\n    static func createSwiftlyModulesGraph(rootPath: String = \"/tmp/swiftly-mock\") throws -> ModulesGraph {\n        // MARK: - Create Foundation Packages (no dependencies)\n\n        let systemPackage = try createSwiftSystemPackage()\n        let argumentParserPackage = try createSwiftArgumentParserPackage()\n        let toolsSupportPackage = try createSwiftToolsSupportCorePackage()\n        let httpTypesPackage = try createSwiftHTTPTypesPackage()\n\n        // MARK: - Create Security Packages\n\n        let asn1Package = try createSwiftlySwiftASN1Package()\n\n        let cryptoPackage = try createSwiftlySwiftCryptoPackage(\n            swiftASN1Product: asn1Package.resolvedProducts[0]\n        )\n\n        let certificatesPackage = try createSwiftlySwiftCertificatesPackage(\n            swiftASN1Product: asn1Package.resolvedProducts[0],\n            cryptoProduct: cryptoPackage.resolvedProducts[0],\n            cryptoExtrasProduct: cryptoPackage.resolvedProducts[1]\n        )\n\n        // MARK: - Create Packages with Foundation Dependencies\n\n        let subprocessPackage = try createSwiftSubprocessPackage(\n            systemPackageProduct: systemPackage.resolvedProducts[0]\n        )\n\n        // MARK: - Create Collections and Utility Packages\n\n        let collectionsPackage = try createSwiftCollectionsPackage()\n        let numericsPackage = try createSwiftNumericsPackage()\n        let algorithmsPackage = try createSwiftAlgorithmsPackage(\n            realModuleProduct: numericsPackage.resolvedProducts[0]\n        )\n        let atomicsPackage = try createSwiftAtomicsPackage()\n\n        let logPackage = try createSwiftLogPackage()\n        let serviceContextPackage = try createSwiftServiceContextPackage()\n        let distributedTracingPackage = try createSwiftDistributedTracingPackage(\n            serviceContextProduct: serviceContextPackage.resolvedProducts[0]\n        )\n        let yamsPackage = try createYamsPackage()\n        let openAPIKitPackage = try createOpenAPIKitPackage()\n\n        // MARK: - Create NIO Packages\n\n        let nioPackage = try createSwiftNIOPackage(\n            atomicsProduct: atomicsPackage.resolvedProducts[0],\n            dequeProduct: collectionsPackage.resolvedProducts[0], // DequeModule\n            systemPackageProduct: systemPackage.resolvedProducts[0]\n        )\n\n        let nioSSLPackage = try createSwiftNIOSSLPackage(\n            nioProduct: nioPackage.resolvedProducts[2], // NIO\n            nioCoreProduct: nioPackage.resolvedProducts[1], // NIOCore\n            nioConcurrencyHelpersProduct: nioPackage.resolvedProducts[0], // NIOConcurrencyHelpers\n            nioTLSProduct: nioPackage.resolvedProducts[4] // NIOTLS\n        )\n\n        let nioHTTP2Package = try createSwiftNIOHTTP2Package(\n            nioProduct: nioPackage.resolvedProducts[2], // NIO\n            nioCoreProduct: nioPackage.resolvedProducts[1], // NIOCore\n            nioConcurrencyHelpersProduct: nioPackage.resolvedProducts[0], // NIOConcurrencyHelpers\n            nioHTTP1Product: nioPackage.resolvedProducts[5], // NIOHTTP1\n            nioTLSProduct: nioPackage.resolvedProducts[4], // NIOTLS\n            atomicsProduct: atomicsPackage.resolvedProducts[0]\n        )\n\n        let nioExtrasPackage = try createSwiftNIOExtrasPackage(\n            nioProduct: nioPackage.resolvedProducts[2], // NIO\n            nioCoreProduct: nioPackage.resolvedProducts[1], // NIOCore\n            nioHTTP1Product: nioPackage.resolvedProducts[5] // NIOHTTP1\n        )\n\n        let nioTransportServicesPackage = try createSwiftNIOTransportServicesPackage(\n            nioProduct: nioPackage.resolvedProducts[2], // NIO\n            nioCoreProduct: nioPackage.resolvedProducts[1], // NIOCore\n            nioFoundationCompatProduct: nioPackage.resolvedProducts[6], // NIOFoundationCompat\n            nioTLSProduct: nioPackage.resolvedProducts[4], // NIOTLS\n            atomicsProduct: atomicsPackage.resolvedProducts[0]\n        )\n\n        // MARK: - Create OpenAPI Packages\n\n        let openAPIRuntimePackage = try createSwiftOpenAPIRuntimePackage(\n            httpTypesProduct: httpTypesPackage.resolvedProducts[0]\n        )\n\n        let openAPIGeneratorPackage = try createSwiftOpenAPIGeneratorPackage(\n            openAPIKitProduct: openAPIKitPackage.resolvedProducts[0], // OpenAPIKit\n            openAPIKit30Product: openAPIKitPackage.resolvedProducts[1], // OpenAPIKit30\n            openAPIKitCompatProduct: openAPIKitPackage.resolvedProducts[2], // OpenAPIKitCompat\n            algorithmsProduct: algorithmsPackage.resolvedProducts[0],\n            orderedCollectionsProduct: collectionsPackage.resolvedProducts[1], // OrderedCollections\n            yamsProduct: yamsPackage.resolvedProducts[0],\n            argumentParserProduct: argumentParserPackage.resolvedProducts[0]\n        )\n\n        let asyncHTTPClientPackage = try createAsyncHTTPClientPackage(\n            nioProduct: nioPackage.resolvedProducts[2], // NIO\n            nioTLSProduct: nioPackage.resolvedProducts[4], // NIOTLS\n            nioCoreProduct: nioPackage.resolvedProducts[1], // NIOCore\n            nioPosixProduct: nioPackage.resolvedProducts[3], // NIOPosix\n            nioHTTP1Product: nioPackage.resolvedProducts[5], // NIOHTTP1\n            nioConcurrencyHelpersProduct: nioPackage.resolvedProducts[0], // NIOConcurrencyHelpers\n            nioHTTP2Product: nioHTTP2Package.resolvedProducts[0], // NIOHTTP2\n            nioSSLProduct: nioSSLPackage.resolvedProducts[0], // NIOSSL\n            nioHTTPCompressionProduct: nioExtrasPackage.resolvedProducts[0], // NIOHTTPCompression\n            nioSOCKSProduct: nioExtrasPackage.resolvedProducts[1], // NIOSOCKS\n            nioTransportServicesProduct: nioTransportServicesPackage.resolvedProducts[0],\n            atomicsProduct: atomicsPackage.resolvedProducts[0],\n            algorithmsProduct: algorithmsPackage.resolvedProducts[0],\n            loggingProduct: logPackage.resolvedProducts[0],\n            tracingProduct: distributedTracingPackage.resolvedProducts[0]\n        )\n\n        let openAPIAsyncHTTPClientPackage = try createSwiftOpenAPIAsyncHTTPClientPackage(\n            openAPIRuntimeProduct: openAPIRuntimePackage.resolvedProducts[0],\n            httpTypesProduct: httpTypesPackage.resolvedProducts[0],\n            asyncHTTPClientProduct: asyncHTTPClientPackage.resolvedProducts[0],\n            nioFoundationCompatProduct: nioPackage.resolvedProducts[6] // NIOFoundationCompat\n        )\n\n        // MARK: - Create Swiftly Root Package\n\n        let swiftlyPackage = try createSwiftlyRootPackage(\n            rootPath: rootPath,\n            openAPIGeneratorProduct: openAPIGeneratorPackage.resolvedProducts[0], // OpenAPIGenerator\n            openAPIRuntimeProduct: openAPIRuntimePackage.resolvedProducts[0],\n            argumentParserProduct: argumentParserPackage.resolvedProducts[0],\n            systemPackageProduct: systemPackage.resolvedProducts[0],\n            asyncHTTPClientProduct: asyncHTTPClientPackage.resolvedProducts[0],\n            nioFoundationCompatProduct: nioPackage.resolvedProducts[6], // NIOFoundationCompat\n            openAPIAsyncHTTPClientProduct: openAPIAsyncHTTPClientPackage.resolvedProducts[0],\n            subprocessProduct: subprocessPackage.resolvedProducts[0],\n            swiftToolsSupportProduct: toolsSupportPackage.resolvedProducts[0],\n            nioFileSystemProduct: nioPackage.resolvedProducts[7] // _NIOFileSystem\n        )\n\n        // MARK: - Assemble All Packages\n\n        let allResolvedPackages: IdentifiableSet<ResolvedPackage> = IdentifiableSet([\n            swiftlyPackage.resolvedPackage,\n            systemPackage.resolvedPackage,\n            subprocessPackage.resolvedPackage,\n            argumentParserPackage.resolvedPackage,\n            toolsSupportPackage.resolvedPackage,\n            httpTypesPackage.resolvedPackage,\n            asn1Package.resolvedPackage,\n            cryptoPackage.resolvedPackage,\n            certificatesPackage.resolvedPackage,\n            collectionsPackage.resolvedPackage,\n            numericsPackage.resolvedPackage,\n            algorithmsPackage.resolvedPackage,\n            atomicsPackage.resolvedPackage,\n            logPackage.resolvedPackage,\n            serviceContextPackage.resolvedPackage,\n            distributedTracingPackage.resolvedPackage,\n            yamsPackage.resolvedPackage,\n            openAPIKitPackage.resolvedPackage,\n            nioPackage.resolvedPackage,\n            nioSSLPackage.resolvedPackage,\n            nioHTTP2Package.resolvedPackage,\n            nioExtrasPackage.resolvedPackage,\n            nioTransportServicesPackage.resolvedPackage,\n            openAPIRuntimePackage.resolvedPackage,\n            openAPIGeneratorPackage.resolvedPackage,\n            asyncHTTPClientPackage.resolvedPackage,\n            openAPIAsyncHTTPClientPackage.resolvedPackage,\n        ])\n\n        let rootDependencies = [\n            systemPackage.resolvedPackage,\n            subprocessPackage.resolvedPackage,\n            argumentParserPackage.resolvedPackage,\n            toolsSupportPackage.resolvedPackage,\n            httpTypesPackage.resolvedPackage,\n            asn1Package.resolvedPackage,\n            cryptoPackage.resolvedPackage,\n            certificatesPackage.resolvedPackage,\n            collectionsPackage.resolvedPackage,\n            numericsPackage.resolvedPackage,\n            algorithmsPackage.resolvedPackage,\n            atomicsPackage.resolvedPackage,\n            logPackage.resolvedPackage,\n            serviceContextPackage.resolvedPackage,\n            distributedTracingPackage.resolvedPackage,\n            yamsPackage.resolvedPackage,\n            openAPIKitPackage.resolvedPackage,\n            nioPackage.resolvedPackage,\n            nioSSLPackage.resolvedPackage,\n            nioHTTP2Package.resolvedPackage,\n            nioExtrasPackage.resolvedPackage,\n            nioTransportServicesPackage.resolvedPackage,\n            openAPIRuntimePackage.resolvedPackage,\n            openAPIGeneratorPackage.resolvedPackage,\n            asyncHTTPClientPackage.resolvedPackage,\n            openAPIAsyncHTTPClientPackage.resolvedPackage,\n        ]\n\n        let packageReferences = [\n            swiftlyPackage.packageRef,\n            systemPackage.packageRef,\n            subprocessPackage.packageRef,\n            argumentParserPackage.packageRef,\n            toolsSupportPackage.packageRef,\n            httpTypesPackage.packageRef,\n            asn1Package.packageRef,\n            cryptoPackage.packageRef,\n            certificatesPackage.packageRef,\n            collectionsPackage.packageRef,\n            numericsPackage.packageRef,\n            algorithmsPackage.packageRef,\n            atomicsPackage.packageRef,\n            logPackage.packageRef,\n            serviceContextPackage.packageRef,\n            distributedTracingPackage.packageRef,\n            yamsPackage.packageRef,\n            openAPIKitPackage.packageRef,\n            nioPackage.packageRef,\n            nioSSLPackage.packageRef,\n            nioHTTP2Package.packageRef,\n            nioExtrasPackage.packageRef,\n            nioTransportServicesPackage.packageRef,\n            openAPIRuntimePackage.packageRef,\n            openAPIGeneratorPackage.packageRef,\n            asyncHTTPClientPackage.packageRef,\n            openAPIAsyncHTTPClientPackage.packageRef,\n        ]\n\n        // MARK: - Create ModulesGraph\n\n        return try ModulesGraph(\n            rootPackages: [swiftlyPackage.resolvedPackage],\n            rootDependencies: rootDependencies,\n            packages: allResolvedPackages,\n            dependencies: packageReferences,\n            binaryArtifacts: [:]\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestRepo.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport SourceControl\nimport class TSCBasic.Process\nimport enum TSCUtility.Git\n\nenum SBOMTestRepo {\n    static func setupSPMTestRepo() throws -> (GitRepository, AbsolutePath) {\n        let uniqueID = UUID().uuidString\n        let path = AbsolutePath(\"/tmp/SwiftPM-mock-\\(uniqueID)\")\n\n        try localFileSystem.createDirectory(path, recursive: true)\n        \n        let repo = GitRepository(path: path)\n        try repo.create()\n        \n        try Process.checkNonZeroExit(\n            args: Git.tool,\n            \"-C\",\n            path.pathString,\n            \"remote\",\n            \"add\",\n            \"test_origin\",\n            SBOMTestStore.swiftPMURL\n        )\n        \n        let file = path.appending(\"Package.swift\")\n        try localFileSystem.writeFileContents(file, string: \"// swift-tools-version: 5.9\\nimport PackageDescription\\n\")\n        try repo.stageEverything()\n        try repo.commit(message: \"Initial commit\")\n        guard let branch = try repo.getCurrentBranch() else {\n            throw SBOMTestError.failedToGetCurrentBranch\n        }\n        \n        try Process.checkNonZeroExit(\n            args: Git.tool,\n            \"-C\",\n            path.pathString,\n            \"config\",\n            \"branch.\\(branch).remote\",\n            \"test_origin\"\n        )\n\n        return (repo, path)\n    }\n\n    static func setupSwiftlyTestRepo() throws -> (GitRepository, AbsolutePath) {\n        let uniqueID = UUID().uuidString\n        let path = AbsolutePath(\"/tmp/swiftly-mock-\\(uniqueID)\")\n\n        try localFileSystem.createDirectory(path, recursive: true)\n        \n        let repo = GitRepository(path: path)\n        try repo.create()\n        \n        try Process.checkNonZeroExit(\n            args: Git.tool,\n            \"-C\",\n            path.pathString,\n            \"remote\",\n            \"add\",\n            \"test_origin\",\n            SBOMTestStore.swiftlyURL\n        )\n        \n        let file = path.appending(\"Package.swift\")\n        try localFileSystem.writeFileContents(file, string: \"// swift-tools-version: 5.9\\nimport PackageDescription\\n\")\n        try repo.stageEverything()\n        try repo.commit(message: \"Initial commit\")\n        guard let branch = try repo.getCurrentBranch() else {\n            throw SBOMTestError.failedToGetCurrentBranch\n        }\n        \n        try repo.tag(name: \"v1.0.0\")\n        \n        try Process.checkNonZeroExit(\n            args: Git.tool,\n            \"-C\",\n            path.pathString,\n            \"config\",\n            \"branch.\\(branch).remote\",\n            \"test_origin\"\n        )\n\n        return (repo, path)\n    }\n\n    /// Clean up a test repository directory\n    static func cleanup(_ path: AbsolutePath) throws {\n        if localFileSystem.exists(path) {\n            try localFileSystem.removeFileTree(path)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestStore.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nimport struct TSCUtility.Version\n\nenum SBOMTestStore {\n    static let swiftPMRevision = \"e535ac05e3ec765611044bdafa9703db3f67ac07\"\n    static let swiftPMURL = \"https://github.com/swiftlang/swift-package-manager.git\"\n\n    static let swiftlyRevision = \"985e34f447d55854f2212f5112ef2d344a7e2072\"\n    static let swiftlyURL = \"https://github.com/swiftlang/swiftly.git\"\n\n    private static let spmDependencies = [\n        (\"swift-system\", \"https://github.com/apple/swift-system.git\", \"1.3.2\"),\n        (\"swift-collections\", \"https://github.com/apple/swift-collections.git\", \"1.1.4\"),\n        (\"swift-argument-parser\", \"https://github.com/apple/swift-argument-parser.git\", \"1.5.1\"),\n        (\"swift-toolchain-sqlite\", \"https://github.com/swiftlang/swift-toolchain-sqlite.git\", \"1.0.0\"),\n        (\"swift-llbuild\", \"https://github.com/swiftlang/swift-llbuild.git\", \"swift-6.0-branch\"),\n        (\"swift-tools-support-core\", \"https://github.com/swiftlang/swift-tools-support-core.git\", \"main\"),\n        (\"swift-driver\", \"https://github.com/swiftlang/swift-driver.git\", \"main\"),\n        (\"swift-asn1\", \"https://github.com/apple/swift-asn1.git\", \"1.2.0\"),\n        (\"swift-crypto\", \"https://github.com/apple/swift-crypto.git\", \"3.0.0\"),\n        (\"swift-certificates\", \"https://github.com/apple/swift-certificates.git\", \"1.5.0\"),\n    ]\n\n    private static let swiftlyDependencies = [\n        (\"swift-system\", \"https://github.com/apple/swift-system.git\", \"1.4.2\"),\n        (\"swift-subprocess\", \"https://github.com/swiftlang/swift-subprocess.git\", \"1.0.0\"),\n        (\"swift-argument-parser\", \"https://github.com/apple/swift-argument-parser.git\", \"1.3.0\"),\n        (\"swift-tools-support-core\", \"https://github.com/swiftlang/swift-tools-support-core.git\", \"0.7.2\"),\n        (\"swift-collections\", \"https://github.com/apple/swift-collections.git\", \"1.1.4\"),\n        (\"swift-numerics\", \"https://github.com/apple/swift-numerics.git\", \"1.0.2\"),\n        (\"swift-algorithms\", \"https://github.com/apple/swift-algorithms.git\", \"1.2.0\"),\n        (\"swift-atomics\", \"https://github.com/apple/swift-atomics.git\", \"1.2.0\"),\n        (\"async-http-client\", \"https://github.com/swift-server/async-http-client.git\", \"1.24.0\"),\n        (\n            \"swift-openapi-async-http-client\",\n            \"https://github.com/swift-server/swift-openapi-async-http-client.git\",\n            \"1.1.0\"\n        ),\n        (\"swift-nio\", \"https://github.com/apple/swift-nio.git\", \"2.80.0\"),\n        (\"swift-openapi-runtime\", \"https://github.com/apple/swift-openapi-runtime.git\", \"1.8.2\"),\n    ]\n\n    private static func createResolvedPackagesStore(\n        name: String,\n        url: String,\n        revision: String,\n        dependencies: [(String, String, String)]\n    ) throws -> ResolvedPackagesStore {\n        let store = try createBaseStore(filename: \"\\(name)-Package.resolved\")\n        try addRemoteRepository(\n            to: store,\n            name: name,\n            url: url,\n            revision: revision\n        )\n        try addDependencies(dependencies, to: store)\n        return store\n    }\n\n    package static func createSPMResolvedPackagesStore() throws -> ResolvedPackagesStore {\n        try self.createResolvedPackagesStore(\n            name: \"swift-package-manager\",\n            url: self.swiftPMURL,\n            revision: self.swiftPMRevision,\n            dependencies: self.spmDependencies\n        )\n    }\n\n    package static func createSwiftlyResolvedPackagesStore() throws -> ResolvedPackagesStore {\n        try self.createResolvedPackagesStore(\n            name: \"swiftly\",\n            url: self.swiftlyURL,\n            revision: self.swiftlyRevision,\n            dependencies: self.swiftlyDependencies\n        )\n    }\n\n    package static func createSimpleResolvedPackagesStore() throws -> ResolvedPackagesStore {\n        try self.createResolvedPackagesStore(\n            name: \"MyApp\",\n            url: \"https://github.com/example/myapp.git\",\n            revision: \"abc123def456abc123def456abc123def456abc1\",\n            dependencies: [\n                (\"Utils\", \"https://github.com/example/utils.git\", \"1.0.0\"),\n            ]\n        )\n    }\n\n    private static func createBaseStore(filename: String) throws -> ResolvedPackagesStore {\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/tmp/\\(filename)\")\n\n        return try ResolvedPackagesStore(\n            packageResolvedFile: packageResolvedFile,\n            workingDirectory: .root,\n            fileSystem: fs,\n            mirrors: .init()\n        )\n    }\n\n    private static func addRemoteRepository(\n        to store: ResolvedPackagesStore,\n        name: String,\n        url: String,\n        revision: String\n    ) throws {\n        let identity = PackageIdentity.plain(name)\n        let packageRef = PackageReference.remoteSourceControl(\n            identity: identity,\n            url: SourceControlURL(url)\n        )\n\n        store.track(\n            packageRef: packageRef,\n            state: .revision(revision)\n        )\n    }\n\n    private static func addDependencies(\n        _ dependencies: [(String, String, String)],\n        to store: ResolvedPackagesStore\n    ) throws {\n        for (name, url, version) in dependencies {\n            let identity = PackageIdentity.plain(name)\n            let packageRef = PackageReference.remoteSourceControl(\n                identity: identity,\n                url: SourceControlURL(url)\n            )\n\n            let mockRevision = self.generateMockRevision(for: name)\n            let state = try createResolutionState(version: version, revision: mockRevision)\n\n            store.track(packageRef: packageRef, state: state)\n        }\n    }\n\n    private static func createResolutionState(\n        version: String,\n        revision: String\n    ) throws -> ResolvedPackagesStore.ResolutionState {\n        // Try to parse as a version first\n        if let parsedVersion = try? Version(versionString: version) {\n            .version(parsedVersion, revision: revision)\n        } else {\n            // If it can't be parsed as a version, treat it as a branch\n            .branch(name: version, revision: revision)\n        }\n    }\n\n    package static func generateMockRevision(for packageName: String) -> String {\n        let hash = packageName.hash\n        return String(format: \"%040x\", abs(hash)).prefix(40).padding(toLength: 40, withPad: \"0\", startingAt: 0)\n    }\n}\n\nextension ResolvedPackagesStore {\n    /// Get the repository URL for a given package name from the store\n    package func getRepositoryURL(for packageName: String) throws -> String {\n        let identity = PackageIdentity.plain(packageName)\n        \n        guard let resolvedPackage = self.resolvedPackages[identity] else {\n            throw SBOMTestStoreError.packageNotFound(packageName)\n        }\n        \n        switch resolvedPackage.packageRef.kind {\n        case .remoteSourceControl(let url):\n            return url.absoluteString\n        case .localSourceControl(let path):\n            return path.pathString\n        case .registry:\n            throw SBOMTestStoreError.registryPackageHasNoURL(packageName)\n        case .fileSystem:\n            throw SBOMTestStoreError.fileSystemPackageHasNoURL(packageName)\n        case .root(let path):\n            return path.pathString\n        }\n    }\n}\n\nenum SBOMTestStoreError: Error {\n    case packageNotFound(String)\n    case registryPackageHasNoURL(String)\n    case fileSystemPackageHasNoURL(String)\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMTestTraits.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\nimport Testing\n\nstruct SBOMTestTraits {\n    \n    private func extractSBOM(from graph: ModulesGraph) async throws -> SBOMDependencies {\n        // doesn't matter which store is used, so just the simple one\n        let store = try SBOMTestStore.createSimpleResolvedPackagesStore()\n        let extractor = SBOMExtractor(\n            modulesGraph: graph,\n            dependencyGraph: nil,\n            store: store\n        )\n        return try await extractor.extractDependencies()\n    }\n    \n    // MARK: - Tests\n    \n    @Test(\"SBOM extraction with PackageConditionalDeps fixture - default traits\")\n    func extractSBOMwithConditionalDepsFixtureDefaultTraits() async throws {\n        let graph = try await SBOMTestModulesGraph.createConditionalModulesGraph(\n            traitConfiguration: .default\n        )\n        let dependencies = try await extractSBOM(from: graph)\n        \n        // Verify: Package1 should be included (default trait enables it)\n        #expect(dependencies.components.contains(where: { $0.name == \"package1\" }))\n        \n        // Verify: Package2 should NOT be included (trait not enabled by default)\n        #expect(!dependencies.components.contains(where: { $0.name == \"package2\" }))\n        \n        // Verify: Root package is included\n        #expect(dependencies.components.contains(where: { $0.name == \"packageconditionaldeps\" }))\n    }\n    \n    @Test(\"SBOM extraction with PackageConditionalDeps fixture - all traits enabled\")\n    func extractSBOMwithConditionalDepsFixtureAllTraits() async throws {\n        let graph = try await SBOMTestModulesGraph.createConditionalModulesGraph(\n            traitConfiguration: .enabledTraits([\"EnablePackage1Dep\", \"EnablePackage2Dep\"])\n        )\n        let dependencies = try await extractSBOM(from: graph)\n        \n        // Verify: Both packages should be included (both traits enabled)\n        #expect(dependencies.components.contains(where: { $0.name == \"package1\" }))\n        #expect(dependencies.components.contains(where: { $0.name == \"package2\" }))\n        #expect(dependencies.components.contains(where: { $0.name == \"packageconditionaldeps\" }))\n    }\n    \n    @Test(\"SBOM extraction with PackageConditionalDeps fixture - no traits enabled\")\n    func extractSBOMwithConditionalDepsFixtureNoTraits() async throws {\n        let graph = try await SBOMTestModulesGraph.createConditionalModulesGraph(\n            traitConfiguration: .disableAllTraits\n        )\n        let dependencies = try await extractSBOM(from: graph)\n        \n        // Verify: Neither dependency package should be included (no traits enabled)\n        #expect(!dependencies.components.contains(where: { $0.name == \"package1\" }))\n        #expect(!dependencies.components.contains(where: { $0.name == \"package2\" }))\n        \n        // Verify: Root package is still included\n        #expect(dependencies.components.contains(where: { $0.name == \"packageconditionaldeps\" }))\n    }\n}"
  },
  {
    "path": "Tests/SBOMModelTests/SBOMValidationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\n@testable import SBOMModel\nimport Testing\n\n// MARK: - Test Helper for Loading Validators\n\n/// Helper function to create a validator for tests by finding the SBOMModel module bundle\n/// This bypasses the bundle search logic in production code which doesn't work in test contexts\nfileprivate func createTestValidator(for spec: SBOMSpec) throws -> any SBOMValidatorProtocol {\n    let schemaFilename = spec.schemaFilename\n    \n    // Find the SBOMModel bundle - schema files are resources of SBOMModel, not SBOMModelTests\n    // Search for the bundle in the same directory as the test bundle\n    let testBundleURL = Bundle.module.bundleURL\n    let buildDir = testBundleURL.deletingLastPathComponent()\n    \n    // Try both .bundle and .resources extensions (macOS vs other platforms)\n    let bundleExtensions = [\"bundle\", \"resources\"]\n    var sbomModelBundle: Bundle?\n    \n    for ext in bundleExtensions {\n        let bundleURL = buildDir.appendingPathComponent(\"SwiftPM_SBOMModel.\\(ext)\")\n        if let bundle = Bundle(url: bundleURL) {\n            sbomModelBundle = bundle\n            break\n        }\n    }\n    \n    guard let bundle = sbomModelBundle,\n          let schemaURL = bundle.url(forResource: schemaFilename, withExtension: \"json\") else {\n        throw SBOMSchemaError.schemaFileNotFound(filename: schemaFilename, bundlePath: buildDir.path)\n    }\n    \n    let schemaData = try Data(contentsOf: schemaURL)\n    guard let jsonObject = try JSONSerialization.jsonObject(with: schemaData) as? [String: Any] else {\n        throw SBOMSchemaError.invalidSchemaFormat(message: \"Could not parse schema as JSON dictionary\")\n    }\n    \n    // Create the appropriate validator based on spec type\n    switch spec.concreteSpec {\n    case .cyclonedx1:\n        return CycloneDXValidator(schema: jsonObject)\n    case .spdx3:\n        return SPDXValidator(schema: jsonObject)\n    }\n}\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.medium\n    )\n)\nstruct SBOMValidationTests {\n    struct ValidateGraphSBOMTestCase: CustomStringConvertible {\n        let graphName: String\n        let inputSpec: SBOMSpec\n        let inputGraph: ModulesGraph\n        let inputStore: ResolvedPackagesStore\n        let wantError: Bool\n\n        var description: String { // don't print the graph because it's large\n            \"ValidateGraphSBOMTestCase(graph: \\(self.graphName), spec: \\(self.inputSpec), wantError: \\(self.wantError))\"\n        }\n    }\n\n    static func getValidateGraphSBOMTestCases() throws -> [ValidateGraphSBOMTestCase] {\n        try [\n            ValidateGraphSBOMTestCase(\n                graphName: \"SwiftPM\",\n                inputSpec: SBOMSpec(spec: .cyclonedx),\n                inputGraph: SBOMTestModulesGraph.createSPMModulesGraph(),\n                inputStore: SBOMTestStore.createSPMResolvedPackagesStore(),\n                wantError: false\n            ),\n            ValidateGraphSBOMTestCase(\n                graphName: \"SwiftPM\",\n                inputSpec: SBOMSpec(spec: .spdx),\n                inputGraph: SBOMTestModulesGraph.createSPMModulesGraph(),\n                inputStore: SBOMTestStore.createSPMResolvedPackagesStore(),\n                wantError: false\n            ),\n            ValidateGraphSBOMTestCase(\n                graphName: \"Swiftly\",\n                inputSpec: SBOMSpec(spec: .cyclonedx),\n                inputGraph: SBOMTestModulesGraph.createSwiftlyModulesGraph(),\n                inputStore: SBOMTestStore.createSwiftlyResolvedPackagesStore(),\n                wantError: false\n            ),\n            ValidateGraphSBOMTestCase(\n                graphName: \"Swiftly\",\n                inputSpec: SBOMSpec(spec: .spdx),\n                inputGraph: SBOMTestModulesGraph.createSwiftlyModulesGraph(),\n                inputStore: SBOMTestStore.createSwiftlyResolvedPackagesStore(),\n                wantError: false\n            ),\n        ]\n    }\n\n    @Test(\"validate SBOM from graphs\", arguments: try getValidateGraphSBOMTestCases())\n    func validateSBOMFromGraph(testCase: ValidateGraphSBOMTestCase) async throws {\n        let extractor = SBOMExtractor(\n            modulesGraph: testCase.inputGraph,\n            dependencyGraph: nil,\n            store: testCase.inputStore\n        )\n        let document = try await extractor.extractSBOM()\n        let observability = ObservabilitySystem.makeForTesting()\n        let encoder = SBOMEncoder(sbom: document, observabilityScope: observability.topScope)\n        let encodedData = try await encoder.encodeSBOMData(spec: testCase.inputSpec)\n        \n        guard let sbomJSONObject = try JSONSerialization.jsonObject(with: encodedData) as? [String: Any] else {\n            throw SBOMEncoderError.jsonConversionFailed(message: \"Could not convert generated SBOM file into JSON object for validation\")\n        }\n        \n        let validator = try createTestValidator(for: testCase.inputSpec)\n        try await validator.validate(sbomJSONObject)\n    }\n\n    struct ValidateFileSBOMTestCase {\n        let inputFilePath: String\n        let inputSBOMSpec: SBOMSpec\n        let expectedEncoderErrorType: Error.Type?\n    }\n\n    static func getValidateFileSBOMTestCases() throws -> [ValidateFileSBOMTestCase] {\n        [\n            // valid CycloneDX SBOMs\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/valid-cyclonedx-1.7-empty-comps\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: nil,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/valid-cyclonedx-1.7-minimal\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: nil,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/valid-cyclonedx-1.7-unicode\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: nil,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/valid-cyclonedx-1.7-spm\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: nil,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/valid-cyclonedx-1.7-versions\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: nil,\n            ),\n\n            // valid SPDX SBOMs\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/valid-spdx-3.0.1-spm\",\n                inputSBOMSpec: SBOMSpec(spec: .spdx3),\n                expectedEncoderErrorType: nil,\n            ),\n\n            // invalid CycloneDX SBOMs\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/invalid-cyclonedx-1-missing-fields\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: SBOMValidatorError.self,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/invalid-cyclonedx-1-small\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: SBOMValidatorError.self,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/invalid-cyclonedx-1.7-uppercase-uuid\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: SBOMValidatorError.self,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/invalid-cyclonedx-1.7-wrong-bomformat\",\n                inputSBOMSpec: SBOMSpec(spec: .cyclonedx1),\n                expectedEncoderErrorType: SBOMValidatorError.self,\n            ),\n\n            // invalid SPDX SBOMs\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/invalid-spdx-3-small\",\n                inputSBOMSpec: SBOMSpec(spec: .spdx3),\n                expectedEncoderErrorType: NSError.self,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/invalid-spdx-3.0.1-no-iri\",\n                inputSBOMSpec: SBOMSpec(spec: .spdx3),\n                expectedEncoderErrorType: SBOMValidatorError.self,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/invalid-spdx-3.0.1-spm\",\n                inputSBOMSpec: SBOMSpec(spec: .spdx3),\n                expectedEncoderErrorType: SBOMValidatorError.self,\n            ),\n            ValidateFileSBOMTestCase(\n                inputFilePath: \"testfiles/invalid-spdx-3.0.1-wrong-relationshiptype\",\n                inputSBOMSpec: SBOMSpec(spec: .spdx3),\n                expectedEncoderErrorType: SBOMValidatorError.self,\n            ),\n        ]\n    }\n\n    @Test(\"validate SBOM from files\", arguments: try getValidateFileSBOMTestCases())\n    func validateSBOMFromFile(testCase: ValidateFileSBOMTestCase) async throws {\n        let testBundle = Bundle.module\n        let fileURL = try #require(\n            testBundle.url(forResource: testCase.inputFilePath, withExtension: \"json\"),\n            \"Could not find \\(testCase.inputFilePath).json test file\"\n        )\n        let encodedData = try Data(contentsOf: fileURL)\n        if let errorType = testCase.expectedEncoderErrorType {\n            await #expect {\n                let sbomJSONObject = try JSONSerialization.jsonObject(with: encodedData) as? [String: Any]\n                let validator = try createTestValidator(for: testCase.inputSBOMSpec)\n                try await validator.validate(sbomJSONObject)\n            } throws: { error in\n                type(of: error) == errorType\n            }\n        } else {\n            let sbomJSONObject = try JSONSerialization.jsonObject(with: encodedData) as? [String: Any]\n            let validator = try createTestValidator(for: testCase.inputSBOMSpec)\n            try await validator.validate(sbomJSONObject)\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPDXConverterTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n@testable import SBOMModel\nimport Testing\n\n@Suite(\n    .tags(\n        .Feature.SBOM,\n        .TestSize.small\n    )\n)\nstruct SPDXConverterTests {\n    @Test(\"convertToAgent with nil metadata\")\n    func convertToAgentWithNilMetadata() async throws {\n        let result = await SPDXConverter.convertToAgent(from: nil)\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToAgent with nil creators\")\n    func convertToAgentWithNilCreators() async throws {\n        let metadata = SBOMMetadata(\n            timestamp: \"1970-01-01T00:00:00Z\",\n            creators: nil\n        )\n        let result = await SPDXConverter.convertToAgent(from: metadata)\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToAgent with empty creators\")\n    func convertToAgentWithEmptyCreators() async throws {\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: []\n        )\n        let result = await SPDXConverter.convertToAgent(from: metadata)\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToAgent with single creator\")\n    func convertToAgentWithSingleCreator() async throws {\n        let license = SBOMLicense(name: \"Apache-2.0\", url: \"https://www.apache.org/licenses/LICENSE-2.0\")\n        let creator = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-1\"),\n            name: \"SwiftPM\",\n            version: \"3.0.1\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"3.0.1\"),\n            licenses: [license]\n        )\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: [creator]\n        )\n\n        let result = await SPDXConverter.convertToAgent(from: metadata)\n        #expect(result.count == 4) // CreationInfo + Agent + LicenseExpression + Relationship\n\n        let relationship = result[0] as? SPDXRelationship\n        let relationshipUnwrapped = try #require(relationship)\n        #expect(relationshipUnwrapped.type == .Relationship)\n        #expect(relationshipUnwrapped.category == .hasDeclaredLicense)\n        #expect(relationshipUnwrapped.parentID == \"urn:spdx:tool-1\")\n        #expect(relationshipUnwrapped.childrenID.count == 1)\n        #expect(relationshipUnwrapped.childrenID[0] == \"urn:spdx:Apache-2.0\")\n\n        let licenseExpression = result[1] as? SPDXLicenseExpression\n        let licenseExpressionUnwrapped = try #require(licenseExpression)\n        #expect(licenseExpressionUnwrapped.id == \"urn:spdx:Apache-2.0\")\n        #expect(licenseExpressionUnwrapped.type == .LicenseExpression)\n        #expect(licenseExpressionUnwrapped.expression == \"Apache-2.0\")\n        #expect(licenseExpressionUnwrapped.creationInfoID == \"urn:spdx:tool-1:creationInfo\")\n\n        let creationInfo = result[2] as? SPDXCreationInfo\n        let creationInfoUnwrapped = try #require(creationInfo)\n        #expect(creationInfoUnwrapped.id == \"urn:spdx:tool-1:creationInfo\")\n        #expect(creationInfoUnwrapped.type == .CreationInfo)\n        #expect(creationInfoUnwrapped.specVersion == \"3.0.1\")\n        #expect(creationInfoUnwrapped.createdBy == [\"urn:spdx:tool-1\"])\n        #expect(creationInfoUnwrapped.created == \"1970-01-01T00:00:00Z\")\n\n        let agent = result[3] as? SPDXAgent\n        let agentUnwrapped = try #require(agent)\n        #expect(agentUnwrapped.id == \"urn:spdx:tool-1\")\n        #expect(agentUnwrapped.type == .Agent)\n        #expect(agentUnwrapped.name == \"SwiftPM\")\n        #expect(agentUnwrapped.creationInfoID == \"urn:spdx:tool-1:creationInfo\")\n    }\n\n    @Test(\"convertToAgent with multiple creators\")\n    func convertToAgentWithMultipleCreators() async throws {\n        let license1 = SBOMLicense(name: \"Apache-2.0\", url: \"https://www.apache.org/licenses/LICENSE-2.0\")\n        let license2 = SBOMLicense(name: \"MIT\", url: nil)\n        let creator1 = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-1\"),\n            name: \"SwiftPM\",\n            version: \"3.0.1\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"3.0.1\"),\n            licenses: [license1]\n        )\n        let creator2 = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-2\"),\n            name: \"CustomTool\",\n            version: \"1.0.0\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"CustomTool\", version: \"1.0.0\"),\n            licenses: [license2]\n        )\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: [creator1, creator2]\n        )\n\n        let result = await SPDXConverter.convertToAgent(from: metadata)\n        #expect(result.count == 8) // 2 * (Relationship + LicenseExpression + CreationInfo + Agent)\n\n        // First creator's license relationship\n        let relationship1 = result[0] as? SPDXRelationship\n        let relationship1Unwrapped = try #require(relationship1)\n        #expect(relationship1Unwrapped.category == .hasDeclaredLicense)\n        #expect(relationship1Unwrapped.parentID == \"urn:spdx:tool-1\")\n        #expect(relationship1Unwrapped.childrenID == [\"urn:spdx:Apache-2.0\"])\n\n        // First creator's license expression\n        let licenseExpression1 = result[1] as? SPDXLicenseExpression\n        let licenseExpression1Unwrapped = try #require(licenseExpression1)\n        #expect(licenseExpression1Unwrapped.id == \"urn:spdx:Apache-2.0\")\n        #expect(licenseExpression1Unwrapped.expression == \"Apache-2.0\")\n\n        let creationInfo1 = result[2] as? SPDXCreationInfo\n        let creationInfo1Unwrapped = try #require(creationInfo1)\n        #expect(creationInfo1Unwrapped.id == \"urn:spdx:tool-1:creationInfo\")\n        #expect(creationInfo1Unwrapped.createdBy == [\"urn:spdx:tool-1\"])\n\n        let agent1 = result[3] as? SPDXAgent\n        let agent1Unwrapped = try #require(agent1)\n        #expect(agent1Unwrapped.id == \"urn:spdx:tool-1\")\n        #expect(agent1Unwrapped.name == \"SwiftPM\")\n\n        // Second creator's license relationship\n        let relationship2 = result[4] as? SPDXRelationship\n        let relationship2Unwrapped = try #require(relationship2)\n        #expect(relationship2Unwrapped.category == .hasDeclaredLicense)\n        #expect(relationship2Unwrapped.parentID == \"urn:spdx:tool-2\")\n        #expect(relationship2Unwrapped.childrenID == [\"urn:spdx:MIT\"])\n\n        // Second creator's license expression\n        let licenseExpression2 = result[5] as? SPDXLicenseExpression\n        let licenseExpression2Unwrapped = try #require(licenseExpression2)\n        #expect(licenseExpression2Unwrapped.id == \"urn:spdx:MIT\")\n        #expect(licenseExpression2Unwrapped.expression == \"MIT\")\n\n        let creationInfo2 = result[6] as? SPDXCreationInfo\n        let creationInfo2Unwrapped = try #require(creationInfo2)\n        #expect(creationInfo2Unwrapped.id == \"urn:spdx:tool-2:creationInfo\")\n        #expect(creationInfo2Unwrapped.createdBy == [\"urn:spdx:tool-2\"])\n\n        let agent2 = result[7] as? SPDXAgent\n        let agent2Unwrapped = try #require(agent2)\n        #expect(agent2Unwrapped.id == \"urn:spdx:tool-2\")\n        #expect(agent2Unwrapped.name == \"CustomTool\")\n    }\n\n    @Test(\"convertToDocument with missing timestamp throws error\")\n    func convertToDocumentWithMissingTimestamp() async throws {\n        let spec = SBOMSpec(spec: .spdx)\n        let metadata = SBOMMetadata(\n            timestamp: nil,\n            creators: [SBOMTool(id: SBOMIdentifier(value: \"tool-1\"), name: \"SwiftPM\", version: \"3.0.1\", purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"3.0.1\"))]\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .package\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: nil)\n        )\n\n        await #expect(throws: Error.self) {\n            try await SPDXConverter.convertToDocument(from: document, spec: spec)\n        }\n    }\n\n    @Test(\"convertToDocument with missing creators throws error\")\n    func convertToDocumentWithMissingCreators() async throws {\n        let spec = SBOMSpec(spec: .spdx)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: nil\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: nil)\n        )\n\n        await #expect(throws: Error.self) {\n            try await SPDXConverter.convertToDocument(from: document, spec: spec)\n        }\n    }\n\n    @Test(\"convertToDocument with empty creators throws error\")\n    func convertToDocumentWithEmptyCreators() async throws {\n        let spec = SBOMSpec(spec: .spdx)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: []\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: nil)\n        )\n\n        await #expect(throws: Error.self) {\n            try await SPDXConverter.convertToDocument(from: document, spec: spec)\n        }\n    }\n\n    @Test(\"convertToDocument with valid data\")\n    func convertToDocumentWithValidData() async throws {\n        let creator = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-1\"),\n            name: \"SwiftPM\",\n            version: \"3.0.1\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"3.0.1\")\n        )\n        let spec = SBOMSpec(spec: .spdx)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: [creator]\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: nil)\n        )\n\n        let result = try await SPDXConverter.convertToDocument(from: document, spec: spec)\n        #expect(result.count == 4)\n\n        let creationInfo = result[0] as? SPDXCreationInfo\n        let creationInfoUnwrapped = try #require(creationInfo)\n        #expect(creationInfoUnwrapped.id == \"_:creationInfo\")\n        #expect(creationInfoUnwrapped.type == .CreationInfo)\n        #expect(creationInfoUnwrapped.specVersion == \"3.0.1\")\n        #expect(creationInfoUnwrapped.createdBy == [\"urn:spdx:tool-1\"])\n        #expect(creationInfoUnwrapped.created == \"2025-01-01T00:00:00Z\")\n\n        let sbom = result[1] as? SPDXSBOM\n        let sbomUnwrapped = try #require(sbom)\n        #expect(sbomUnwrapped.type == .SoftwareSBOM)\n        #expect(sbomUnwrapped.creationInfoID == \"_:creationInfo\")\n        #expect(sbomUnwrapped.profileConformance == [\"core\", \"software\"])\n        #expect(sbomUnwrapped.rootElementIDs == [\"urn:spdx:primary-id\"])\n\n        let relationship = result[2] as? SPDXRelationship\n        let relationshipUnwrapped = try #require(relationship)\n        #expect(relationshipUnwrapped.type == .Relationship)\n        #expect(relationshipUnwrapped.category == .describes)\n        #expect(relationshipUnwrapped.creationInfoID == \"_:creationInfo\")\n        #expect(relationshipUnwrapped.parentID == sbomUnwrapped.id)\n        #expect(relationshipUnwrapped.childrenID == [\"urn:spdx:primary-id\"])\n\n        let spdxDocument = result[3] as? SPDXDocument\n        let documentUnwrapped = try #require(spdxDocument)\n        #expect(documentUnwrapped.id == \"urn:spdx:doc-1\")\n        #expect(documentUnwrapped.type == .SpdxDocument)\n        #expect(documentUnwrapped.creationInfoID == \"_:creationInfo\")\n        #expect(documentUnwrapped.profileConformance == [\"core\", \"software\"])\n        #expect(documentUnwrapped.rootElementIDs == [sbomUnwrapped.id])\n    }\n\n    @Test(\n        \"convertToPackage with category\",\n        arguments: [\n            (SBOMComponent.Category.application, SPDXPackage.Purpose.application),\n            (.framework, .framework),\n            (.library, .library),\n            (.file, .file),\n        ]\n    )\n    func convertToPackageWithCategory(\n        sbomCategory: SBOMComponent.Category,\n        expectedSPDXPurpose: SPDXPackage.Purpose\n    ) async throws {\n        let component = SBOMComponent(\n            category: sbomCategory,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            description: \"Test description\",\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = try await SPDXConverter.convertToPackage(from: component)\n\n        #expect(result.id == \"urn:spdx:test-id\")\n        #expect(result.type == .SoftwarePackage)\n        #expect(result.purpose == expectedSPDXPurpose)\n        #expect(result.purl == \"pkg:swift/test@1.0.0\")\n        #expect(result.name == \"TestComponent\")\n        #expect(result.version == \"1.0.0\")\n        #expect(result.creationInfoID == \"_:creationInfo\")\n        #expect(result.description == \"Test description\")\n    }\n\n    @Test(\n        \"convertToPackage with entity\",\n        arguments: [\n            (SBOMComponent.Entity.package, SBOMComponent.Entity.package.rawValue),\n            (.product, SBOMComponent.Entity.product.rawValue),\n        ]\n    )\n    func convertToPackageWithEntity(\n        sbomEntity: SBOMComponent.Entity,\n        sbomEntityString: String\n    ) async throws {\n        let component = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            description: \"Test description\",\n            scope: .runtime,\n            entity: sbomEntity\n        )\n\n        let result = try await SPDXConverter.convertToPackage(from: component)\n\n        #expect(result.id == \"urn:spdx:test-id\")\n        #expect(result.type == .SoftwarePackage)\n        #expect(result.purpose == .application)\n        #expect(result.purl == \"pkg:swift/test@1.0.0\")\n        #expect(result.name == \"TestComponent\")\n        #expect(result.version == \"1.0.0\")\n        #expect(result.creationInfoID == \"_:creationInfo\")\n        #expect(result.description == \"Test description\")\n        #expect(result.summary == sbomEntityString)\n    }\n\n    @Test(\"convertToPackage with nil description\")\n    func convertToPackageWithNilDescription() async throws {\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"urn:spdx:test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            description: nil,\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = try await SPDXConverter.convertToPackage(from: component)\n\n        #expect(result.id == \"urn:spdx:test-id\")\n        #expect(result.type == .SoftwarePackage)\n        #expect(result.purpose == .library)\n        #expect(result.description == nil)\n    }\n\n    @Test(\"convertToExternalIdentifiers with nil components\")\n    func convertToExternalIdentifiersWithNilComponents() async throws {\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: nil)\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToExternalIdentifiers with empty components\")\n    func convertToExternalIdentifiersWithEmptyComponents() async throws {\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [])\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToExternalIdentifiers with components without commits\")\n    func convertToExternalIdentifiersWithComponentsWithoutCommits() async throws {\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component])\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToExternalIdentifiers with components with empty commits\")\n    func convertToExternalIdentifiersWithComponentsWithEmptyCommits() async throws {\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: []),\n            scope: .runtime,\n            entity: .product\n        )\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component])\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToExternalIdentifiers with single commit\")\n    func convertToExternalIdentifiersWithSingleCommit() async throws {\n        let commit = SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: nil,\n        )\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: [commit]),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component])\n        #expect(result.count == 2)\n\n        let externalIdentifiers = result.compactMap { $0 as? SPDXExternalIdentifier }\n        let relationships = result.compactMap { $0 as? SPDXRelationship }\n        \n        #expect(externalIdentifiers.count == 1)\n        #expect(relationships.count == 1)\n        \n        let externalIdentifier = externalIdentifiers[0]\n        #expect(externalIdentifier.identifier == \"urn:spdx:abc123\")\n        #expect(externalIdentifier.identifierLocator == [\"https://github.com/swiftlang/swift-package-manager\"])\n        #expect(externalIdentifier.type == .ExternalIdentifier)\n        #expect(externalIdentifier.category == .gitoid)\n\n        let relationship = relationships[0]\n        #expect(relationship.id == \"urn:spdx:abc123-generates\")\n        #expect(relationship.type == .Relationship)\n        #expect(relationship.category == .generates)\n        #expect(relationship.creationInfoID == \"_:creationInfo\")\n        #expect(relationship.parentID == \"urn:spdx:abc123\")\n        #expect(relationship.childrenID == [\"urn:spdx:test-id\"])\n    }\n\n    @Test(\"convertToExternalIdentifiers with multiple commits\")\n    func convertToExternalIdentifiersWithMultipleCommits() async throws {\n        let commit1 = SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: nil,\n        )\n        let commit2 = SBOMCommit(\n            sha: \"def456\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: nil,\n        )\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: [commit1, commit2]),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component])\n        #expect(result.count == 4) // 2 ExternalIdentifiers and 2 Relationships\n\n        let externalIdentifiers = result.compactMap { $0 as? SPDXExternalIdentifier }\n        let relationships = result.compactMap { $0 as? SPDXRelationship }\n\n        #expect(externalIdentifiers.count == 2)\n        #expect(relationships.count == 2)\n\n        let identifiers = externalIdentifiers.map(\\.identifier)\n        #expect(identifiers.contains(\"urn:spdx:abc123\"))\n        #expect(identifiers.contains(\"urn:spdx:def456\"))\n\n        for relationship in relationships {\n            #expect(relationship.type == .Relationship)\n            #expect(relationship.category == .generates)\n            #expect(relationship.creationInfoID == \"_:creationInfo\")\n            #expect(relationship.childrenID == [\"urn:spdx:test-id\"])\n            #expect([\"urn:spdx:abc123\", \"urn:spdx:def456\"].contains(relationship.parentID))\n        }\n    }\n\n    @Test(\"convertToExternalIdentifiers with multiple components sharing same commit\")\n    func convertToExternalIdentifiersWithMultipleComponentsSharingSameCommit() async throws {\n        let commit = SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: nil,\n        )\n        let component1 = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id-1\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test1\", version: \"1.0.0\"),\n            name: \"TestComponent1\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: [commit]),\n            scope: .runtime,\n            entity: .product\n        )\n        let component2 = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id-2\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test2\", version: \"1.0.0\"),\n            name: \"TestComponent2\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: [commit]),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component1, component2])\n        #expect(result.count == 2) // 1 ExternalIdentifier and 1 Relationship\n\n        let externalIdentifiers = result.compactMap { $0 as? SPDXExternalIdentifier }\n        let relationships = result.compactMap { $0 as? SPDXRelationship }\n        \n        #expect(externalIdentifiers.count == 1)\n        #expect(relationships.count == 1)\n        \n        let externalIdentifier = externalIdentifiers[0]\n        #expect(externalIdentifier.identifier == \"urn:spdx:abc123\")\n        #expect(externalIdentifier.identifierLocator == [\"https://github.com/swiftlang/swift-package-manager\"])\n        #expect(externalIdentifier.type == .ExternalIdentifier)\n        #expect(externalIdentifier.category == .gitoid)\n\n        let relationship = relationships[0]\n        #expect(relationship.type == .Relationship)\n        #expect(relationship.category == .generates)\n        #expect(relationship.creationInfoID == \"_:creationInfo\")\n        #expect(relationship.parentID == \"urn:spdx:abc123\")\n\n        #expect(relationship.childrenID.count == 2)\n        #expect(relationship.childrenID.contains(\"urn:spdx:test-id-1\"))\n        #expect(relationship.childrenID.contains(\"urn:spdx:test-id-2\"))\n    }\n    @Test(\"convertToExternalIdentifiers with single registry entry\")\n    func convertToExternalIdentifiersWithSingleRegistryEntry() async throws {\n        let registryEntry = SBOMRegistryEntry(\n            url: URL(string: \"https://registry.example.com/package/1.0.0\"),\n            scope: \"example\",\n            name: \"package\",\n            version: \"1.0.0\"\n        )\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil, entries: [registryEntry]),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component])\n        #expect(result.count == 2) // 1 ExternalIdentifier + 1 Relationship\n\n        let externalIdentifiers = result.compactMap { $0 as? SPDXExternalIdentifier }\n        let relationships = result.compactMap { $0 as? SPDXRelationship }\n        \n        #expect(externalIdentifiers.count == 1)\n        #expect(relationships.count == 1)\n        \n        let externalIdentifier = externalIdentifiers[0]\n        #expect(externalIdentifier.identifier == \"urn:spdx:https://registry.example.com/package/1.0.0\")\n        #expect(externalIdentifier.identifierLocator == [\"https://registry.example.com/package/1.0.0\"])\n        #expect(externalIdentifier.type == .ExternalIdentifier)\n        #expect(externalIdentifier.category == .urlScheme)\n\n        let relationship = relationships[0]\n        #expect(relationship.id == \"urn:spdx:example-package-1.0.0-availableFrom-urn:spdx:test-id\")\n        #expect(relationship.type == .Relationship)\n        #expect(relationship.category == .availableFrom)\n        #expect(relationship.creationInfoID == \"_:creationInfo\")\n        #expect(relationship.parentID == \"urn:spdx:test-id\")\n        #expect(relationship.childrenID == [\"urn:spdx:https://registry.example.com/package/1.0.0\"])\n    }\n\n    @Test(\"convertToExternalIdentifiers with multiple registry entries\")\n    func convertToExternalIdentifiersWithMultipleRegistryEntries() async throws {\n        let registryEntry1 = SBOMRegistryEntry(\n            url: URL(string: \"https://registry1.example.com/package/1.0.0\"),\n            scope: \"example\",\n            name: \"package\",\n            version: \"1.0.0\"\n        )\n        let registryEntry2 = SBOMRegistryEntry(\n            url: URL(string: \"https://registry2.example.com/package/1.0.0\"),\n            scope: \"example\",\n            name: \"package\",\n            version: \"1.0.0\"\n        )\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil, entries: [registryEntry1, registryEntry2]),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component])\n        #expect(result.count == 4) // 2 ExternalIdentifiers + 2 Relationships\n\n        let externalIdentifiers = result.compactMap { $0 as? SPDXExternalIdentifier }\n        let relationships = result.compactMap { $0 as? SPDXRelationship }\n\n        #expect(externalIdentifiers.count == 2)\n        #expect(relationships.count == 2)\n\n        let identifiers = externalIdentifiers.map(\\.identifier)\n        #expect(identifiers.contains(\"urn:spdx:https://registry1.example.com/package/1.0.0\"))\n        #expect(identifiers.contains(\"urn:spdx:https://registry2.example.com/package/1.0.0\"))\n\n        for relationship in relationships {\n            #expect(relationship.type == .Relationship)\n            #expect(relationship.category == .availableFrom)\n            #expect(relationship.creationInfoID == \"_:creationInfo\")\n            #expect(relationship.parentID == \"urn:spdx:test-id\")\n        }\n    }\n\n    @Test(\"convertToExternalIdentifiers with registry entry without URL\")\n    func convertToExternalIdentifiersWithRegistryEntryWithoutURL() async throws {\n        let registryEntry = SBOMRegistryEntry(\n            url: nil,\n            scope: \"example\",\n            name: \"package\",\n            version: \"1.0.0\"\n        )\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil, entries: [registryEntry]),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component])\n        #expect(result.isEmpty) // Registry entry without URL should be skipped\n    }\n\n    @Test(\"convertToExternalIdentifiers with both commits and registry entries\")\n    func convertToExternalIdentifiersWithBothCommitsAndRegistryEntries() async throws {\n        let commit = SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: nil\n        )\n        let registryEntry = SBOMRegistryEntry(\n            url: URL(string: \"https://registry.example.com/package/1.0.0\"),\n            scope: \"example\",\n            name: \"package\",\n            version: \"1.0.0\"\n        )\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: [commit], entries: [registryEntry]),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component])\n        #expect(result.count == 4) // 1 commit ExternalIdentifier + 1 commit Relationship + 1 registry ExternalIdentifier + 1 registry Relationship\n\n        let externalIdentifiers = result.compactMap { $0 as? SPDXExternalIdentifier }\n        let relationships = result.compactMap { $0 as? SPDXRelationship }\n\n        #expect(externalIdentifiers.count == 2)\n        #expect(relationships.count == 2)\n\n        // Check commit external identifier\n        let commitIdentifier = externalIdentifiers.first { $0.category == .gitoid }\n        let commitIdentifierUnwrapped = try #require(commitIdentifier)\n        #expect(commitIdentifierUnwrapped.identifier == \"urn:spdx:abc123\")\n        #expect(commitIdentifierUnwrapped.identifierLocator == [\"https://github.com/swiftlang/swift-package-manager\"])\n\n        // Check registry external identifier\n        let registryIdentifier = externalIdentifiers.first { $0.category == .urlScheme }\n        let registryIdentifierUnwrapped = try #require(registryIdentifier)\n        #expect(registryIdentifierUnwrapped.identifier == \"urn:spdx:https://registry.example.com/package/1.0.0\")\n        #expect(registryIdentifierUnwrapped.identifierLocator == [\"https://registry.example.com/package/1.0.0\"])\n\n        // Check commit relationship\n        let generatesRelationship = relationships.first { $0.category == .generates }\n        let generatesRelationshipUnwrapped = try #require(generatesRelationship)\n        #expect(generatesRelationshipUnwrapped.parentID == \"urn:spdx:abc123\")\n        #expect(generatesRelationshipUnwrapped.childrenID == [\"urn:spdx:test-id\"])\n\n        // Check registry relationship\n        let availableFromRelationship = relationships.first { $0.category == .availableFrom }\n        let availableFromRelationshipUnwrapped = try #require(availableFromRelationship)\n        #expect(availableFromRelationshipUnwrapped.parentID == \"urn:spdx:test-id\")\n        #expect(availableFromRelationshipUnwrapped.childrenID == [\"urn:spdx:https://registry.example.com/package/1.0.0\"])\n    }\n\n    @Test(\"convertToExternalIdentifiers with multiple components with registry entries\")\n    func convertToExternalIdentifiersWithMultipleComponentsWithRegistryEntries() async throws {\n        let registryEntry1 = SBOMRegistryEntry(\n            url: URL(string: \"https://registry.example.com/package1/1.0.0\"),\n            scope: \"example\",\n            name: \"package1\",\n            version: \"1.0.0\"\n        )\n        let registryEntry2 = SBOMRegistryEntry(\n            url: URL(string: \"https://registry.example.com/package2/2.0.0\"),\n            scope: \"example\",\n            name: \"package2\",\n            version: \"2.0.0\"\n        )\n        let component1 = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id-1\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test1\", version: \"1.0.0\"),\n            name: \"TestComponent1\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil, entries: [registryEntry1]),\n            scope: .runtime,\n            entity: .product\n        )\n        let component2 = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id-2\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test2\", version: \"2.0.0\"),\n            name: \"TestComponent2\",\n            version: SBOMComponent.Version(revision: \"2.0.0\"),\n            originator: SBOMOriginator(commits: nil, entries: [registryEntry2]),\n            scope: .runtime,\n            entity: .product\n        )\n\n        let result = await SPDXConverter.convertToExternalIdentifiers(from: [component1, component2])\n        #expect(result.count == 4) // 2 ExternalIdentifiers + 2 Relationships\n\n        let externalIdentifiers = result.compactMap { $0 as? SPDXExternalIdentifier }\n        let relationships = result.compactMap { $0 as? SPDXRelationship }\n\n        #expect(externalIdentifiers.count == 2)\n        #expect(relationships.count == 2)\n\n        // All should be urlScheme category\n        for identifier in externalIdentifiers {\n            #expect(identifier.category == .urlScheme)\n        }\n\n        // All relationships should be availableFrom\n        for relationship in relationships {\n            #expect(relationship.category == .availableFrom)\n        }\n    }\n\n\n    @Test(\"convertToRelationships with nil dependencies\")\n    func convertToRelationshipsWithNilDependencies() async throws {\n        let result = await SPDXConverter.convertToRelationships(from: nil)\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToRelationships with empty dependencies\")\n    func convertToRelationshipsWithEmptyDependencies() async throws {\n        let result = await SPDXConverter.convertToRelationships(from: SBOMDependencies(\n            components: [],\n            relationships: []\n        ))\n        #expect(result.isEmpty)\n    }\n\n    @Test(\"convertToRelationships with single dependency\")\n    func convertToRelationshipsWithSingleDependency() async throws {\n        let dependency = SBOMRelationship(\n            id: SBOMIdentifier(value: \"dep-1\"),\n            parentID: SBOMIdentifier(value: \"parent-component\"),\n            childrenID: [SBOMIdentifier(value: \"child1\"), SBOMIdentifier(value: \"child2\")]\n        )\n\n        let result = await SPDXConverter.convertToRelationships(from: SBOMDependencies(\n            components: [],\n            relationships: [dependency]\n        ))\n        #expect(result.count == 1)\n\n        let relationship = result[0] as? SPDXRelationship\n        let relationshipUnwrapped = try #require(relationship)\n        #expect(relationshipUnwrapped.id == \"urn:spdx:parent-component-dependsOn\")\n        #expect(relationshipUnwrapped.type == SPDXType.Relationship)\n        #expect(relationshipUnwrapped.category == SPDXRelationship.Category.dependsOn)\n        #expect(relationshipUnwrapped.creationInfoID == \"_:creationInfo\")\n        #expect(relationshipUnwrapped.parentID == \"urn:spdx:parent-component\")\n        #expect(relationshipUnwrapped.childrenID == [\"urn:spdx:child1\", \"urn:spdx:child2\"])\n    }\n\n    @Test(\"convertToRelationships with multiple dependencies\")\n    func convertToRelationshipsWithMultipleDependencies() async throws {\n        let dependency1 = SBOMRelationship(\n            id: SBOMIdentifier(value: \"dep-1\"),\n            parentID: SBOMIdentifier(value: \"parent1\"),\n            childrenID: [SBOMIdentifier(value: \"child1\")]\n        )\n        let dependency2 = SBOMRelationship(\n            id: SBOMIdentifier(value: \"dep-2\"),\n            parentID: SBOMIdentifier(value: \"parent2\"),\n            childrenID: [SBOMIdentifier(value: \"child2\"), SBOMIdentifier(value: \"child3\")]\n        )\n\n        let result = await SPDXConverter.convertToRelationships(from: SBOMDependencies(\n            components: [],\n            relationships: [dependency1, dependency2]\n        ))\n        #expect(result.count == 2)\n\n        let relationship1 = result[0] as? SPDXRelationship\n        let relationship1Unwrapped = try #require(relationship1)\n        #expect(relationship1Unwrapped.id == \"urn:spdx:parent1-dependsOn\")\n        #expect(relationship1Unwrapped.parentID == \"urn:spdx:parent1\")\n        #expect(relationship1Unwrapped.childrenID == [\"urn:spdx:child1\"])\n        #expect(relationship1Unwrapped.category == SPDXRelationship.Category.dependsOn)\n\n        let relationship2 = result[1] as? SPDXRelationship\n        let relationship2Unwrapped = try #require(relationship2)\n        #expect(relationship2Unwrapped.id == \"urn:spdx:parent2-dependsOn\")\n        #expect(relationship2Unwrapped.parentID == \"urn:spdx:parent2\")\n        #expect(relationship2Unwrapped.childrenID == [\"urn:spdx:child2\", \"urn:spdx:child3\"])\n        #expect(relationship2Unwrapped.category == SPDXRelationship.Category.dependsOn)\n    }\n\n    @Test(\"convertToRelationships with test and optional relationships\")\n    func convertToRelationshipsWithTestAndOptionalRelationships() async throws {\n        let commit1 = SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: nil,\n        )\n        let parent = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"parent-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test3\", version: \"1.0.0\"),\n            name: \"TestComponent3\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: [commit1]),\n            scope: .runtime,\n            entity: .product\n        )\n        let component = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test\", version: \"1.0.0\"),\n            name: \"TestComponent\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: [commit1]),\n            scope: .test,\n            entity: .product,\n        )\n        let component2 = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"test-id2\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"test2\", version: \"2.0.0\"),\n            name: \"TestComponent2\",\n            version: SBOMComponent.Version(revision: \"2.0.0\"),\n            originator: SBOMOriginator(commits: [commit1]),\n            scope: .optional,\n            entity: .product,\n        )\n        let dependency1 = SBOMRelationship(\n            id: SBOMIdentifier(value: \"dep1\"),\n            parentID: SBOMIdentifier(value: \"parent-id\"),\n            childrenID: [SBOMIdentifier(value: \"test-id\"), SBOMIdentifier(value: \"test-id2\")]\n        )\n\n        let result = await SPDXConverter.convertToRelationships(from: SBOMDependencies(\n            components: [parent, component, component2],\n            relationships: [dependency1]\n        ))\n        #expect(result.count == 3) // 1 dependsOn, 1 hasOptionalDependency, 1 hasTest\n\n        let relationship2 = result[1] as? SPDXRelationship\n        let relationship2Unwrapped = try #require(relationship2)\n        #expect(relationship2Unwrapped.id == \"urn:spdx:parent-id-hasOptionalDependency\")\n        #expect(relationship2Unwrapped.parentID == \"urn:spdx:parent-id\")\n        #expect(relationship2Unwrapped.childrenID == [\"urn:spdx:test-id2\"])\n        #expect(relationship2Unwrapped.category == SPDXRelationship.Category.hasOptionalDependency)\n\n        let relationship1 = result[2] as? SPDXRelationship\n        let relationship1Unwrapped = try #require(relationship1)\n        #expect(relationship1Unwrapped.id == \"urn:spdx:parent-id-hasTest\")\n        #expect(relationship1Unwrapped.parentID == \"urn:spdx:parent-id\")\n        #expect(relationship1Unwrapped.childrenID == [\"urn:spdx:test-id\"])\n        #expect(relationship1Unwrapped.category == SPDXRelationship.Category.hasTest)\n    }\n\n    @Test(\"convertToGraph with non-SPDX spec throws error\")\n    func convertToGraphWithNonSPDXSpec() async throws {\n        let spec = SBOMSpec(spec: .cyclonedx)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: [SBOMTool(id: SBOMIdentifier(value: \"tool-1\"), name: \"SwiftPM\", version: \"3.0.1\", purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"3.0.1\"))]\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: [])\n        )\n\n        await #expect(throws: Error.self) {\n            try await SPDXConverter.convertToGraph(from: document, spec: spec)\n        }\n    }\n\n    @Test(\"convertToGraph with minimal SPDX document\")\n    func convertToGraphWithMinimalSPDXDocument() async throws {\n        let creator = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-1\"),\n            name: \"SwiftPM\",\n            version: \"3.0.1\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"3.0.1\")\n        )\n        let spec = SBOMSpec(spec: .spdx)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: [creator]\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [], relationships: [])\n        )\n\n        let result = try await SPDXConverter.convertToGraph(from: document, spec: spec)\n\n        #expect(result.context == SPDXConstants.spdx3Context)\n        #expect(result.graph\n            .count ==\n            6) // 1 agent CreationInfo + 1 agent + 4 document elements + 0 packages + 0 relationships + 0 commits\n    }\n\n    @Test(\"convertToGraph with components and dependencies\")\n    func convertToGraphWithComponentsAndDependencies() async throws {\n        let creator = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-1\"),\n            name: \"SwiftPM\",\n            version: \"3.0.1\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"3.0.1\")\n        )\n        let spec = SBOMSpec(spec: .spdx3)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: [creator]\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let component1 = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"lib1-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"lib1\", version: \"1.0.0\"),\n            name: \"Library1\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let dependency = SBOMRelationship(\n            id: SBOMIdentifier(value: \"dep-1\"),\n            parentID: SBOMIdentifier(value: \"primary-id\"),\n            childrenID: [SBOMIdentifier(value: \"lib1-id\")]\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [component1], relationships: [dependency])\n        )\n\n        let result = try await SPDXConverter.convertToGraph(from: document, spec: spec)\n\n        #expect(result.context == SPDXConstants.spdx3Context)\n        #expect(result.graph\n            .count ==\n            8) // 1 agent CreationInfo + 1 agent + 4 document elements + 1 package + 1 relationship + 0 commits\n\n        let agents = result.graph.compactMap { $0.getValue() as SPDXAgent? }\n        #expect(agents.count == 1)\n\n        let creationInfos = result.graph.compactMap { $0.getValue() as SPDXCreationInfo? }\n        #expect(creationInfos.count == 2) // 1 from agent + 1 from document\n\n        let packages = result.graph.compactMap { $0.getValue() as SPDXPackage? }\n        #expect(packages.count == 1)\n        #expect(packages[0].id == \"urn:spdx:lib1-id\")\n\n        let relationships = result.graph.compactMap { $0.getValue() as SPDXRelationship? }\n        #expect(relationships.count == 2) // 1 describes + 1 dependsOn relationship\n\n        let sboms = result.graph.compactMap { $0.getValue() as SPDXSBOM? }\n        #expect(sboms.count == 1)\n\n        let documents = result.graph.compactMap { $0.getValue() as SPDXDocument? }\n        #expect(documents.count == 1)\n    }\n\n    @Test(\"convertToGraph with components containing commits\")\n    func convertToGraphWithComponentsContainingCommits() async throws {\n        let creator = SBOMTool(\n            id: SBOMIdentifier(value: \"tool-1\"),\n            name: \"SwiftPM\",\n            version: \"3.0.1\",\n            purl: PURL(scheme: \"pkg\", type: \"swift\", namespace: \"github.com/swiftlang\", name: \"SwiftPM\", version: \"3.0.1\")\n        )\n        let spec = SBOMSpec(spec: .spdx)\n        let metadata = SBOMMetadata(\n            timestamp: \"2025-01-01T00:00:00Z\",\n            creators: [creator]\n        )\n        let primaryComponent = SBOMComponent(\n            category: .application,\n            id: SBOMIdentifier(value: \"primary-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"primary\", version: \"1.0.0\"),\n            name: \"PrimaryApp\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: nil),\n            scope: .runtime,\n            entity: .product\n        )\n        let commit = SBOMCommit(\n            sha: \"abc123\",\n            repository: \"https://github.com/swiftlang/swift-package-manager\",\n            authors: nil,\n        )\n        let component1 = SBOMComponent(\n            category: .library,\n            id: SBOMIdentifier(value: \"lib1-id\"),\n            purl: PURL(scheme: \"pkg\", type: \"swift\", name: \"lib1\", version: \"1.0.0\"),\n            name: \"Library1\",\n            version: SBOMComponent.Version(revision: \"1.0.0\"),\n            originator: SBOMOriginator(commits: [commit]),\n            scope: .runtime,\n            entity: .product\n        )\n        let document = SBOMDocument(\n            id: SBOMIdentifier(value: \"doc-1\"),\n            metadata: metadata,\n            primaryComponent: primaryComponent,\n            dependencies: SBOMDependencies(components: [component1], relationships: nil)\n        )\n\n        let result = try await SPDXConverter.convertToGraph(from: document, spec: spec)\n\n        #expect(result.context == SPDXConstants.spdx3Context)\n\n        let externalIdentifiers = result.graph.compactMap { $0.getValue() as SPDXExternalIdentifier? }\n        #expect(externalIdentifiers.count == 1)\n        #expect(externalIdentifiers[0].identifier == \"urn:spdx:abc123\")\n\n        let relationships = result.graph.compactMap { $0.getValue() as SPDXRelationship? }\n        let generatesRelationships = relationships.filter { $0.category == .generates }\n        #expect(generatesRelationships.count == 1)\n        #expect(generatesRelationships[0].parentID == \"urn:spdx:abc123\")\n        #expect(generatesRelationships[0].childrenID == [\"urn:spdx:lib1-id\"])\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMBuildToolingPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-llbuild Package\n\n    static func createSPMSwiftLLBuildPackage(\n        swiftToolchainCSQLiteProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-llbuild\")\n\n        // Modules\n        let llvmDemangleModule = self.createSwiftModule(name: \"llvmDemangle\")\n        let llvmSupportModule = self.createSwiftModule(name: \"llvmSupport\")\n        let llbuildBasicModule = self.createSwiftModule(name: \"llbuildBasic\")\n        let llbuildCoreModule = self.createSwiftModule(name: \"llbuildCore\")\n        let llbuildNinjaModule = self.createSwiftModule(name: \"llbuildNinja\")\n        let llbuildBuildSystemModule = self.createSwiftModule(name: \"llbuildBuildSystem\")\n        let llbuildCommandsModule = self.createSwiftModule(name: \"llbuildCommands\")\n        let libllbuildModule = self.createSwiftModule(name: \"libllbuild\")\n        let llbuildSwiftModule = self.createSwiftModule(name: \"llbuildSwift\")\n        let llbuildAnalysisModule = self.createSwiftModule(name: \"llbuildAnalysis\")\n        let llbuildExecModule = self.createSwiftModule(name: \"llbuild\", type: .executable)\n\n        // Products\n        let libllbuildProduct = try Product(\n            package: identity,\n            name: \"libllbuild\",\n            type: .library(.automatic),\n            modules: [libllbuildModule]\n        )\n\n        let llbuildProduct = try Product(\n            package: identity,\n            name: \"llbuild\",\n            type: .executable,\n            modules: [llbuildExecModule]\n        )\n\n        let llbuildAnalysisProduct = try Product(\n            package: identity,\n            name: \"llbuildAnalysis\",\n            type: .library(.automatic),\n            modules: [llbuildAnalysisModule]\n        )\n\n        let llbuildSwiftProduct = try Product(\n            package: identity,\n            name: \"llbuildSwift\",\n            type: .library(.automatic),\n            modules: [llbuildSwiftModule]\n        )\n\n        let llbuildSwiftDynamicProduct = try Product(\n            package: identity,\n            name: \"llbuildSwiftDynamic\",\n            type: .library(.dynamic),\n            modules: [llbuildSwiftModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"llbuild\",\n            path: \"/swift-llbuild\",\n            modules: [\n                llvmDemangleModule, llvmSupportModule, llbuildBasicModule, llbuildCoreModule,\n                llbuildNinjaModule, llbuildBuildSystemModule, llbuildCommandsModule,\n                libllbuildModule, llbuildSwiftModule, llbuildAnalysisModule, llbuildExecModule,\n            ],\n            products: [\n                libllbuildProduct, llbuildProduct, llbuildAnalysisProduct,\n                llbuildSwiftProduct, llbuildSwiftDynamicProduct,\n            ]\n        )\n\n        // Resolved modules\n        let resolvedLLVMDemangleModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llvmDemangleModule\n        )\n\n        let resolvedLLVMSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llvmSupportModule,\n            dependencies: [\n                .module(resolvedLLVMDemangleModule, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildBasicModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildBasicModule,\n            dependencies: [\n                .module(resolvedLLVMSupportModule, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildCoreModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildCoreModule,\n            dependencies: [\n                .module(resolvedLLBuildBasicModule, conditions: []),\n                .product(swiftToolchainCSQLiteProduct, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildNinjaModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildNinjaModule,\n            dependencies: [\n                .module(resolvedLLBuildBasicModule, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildBuildSystemModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildBuildSystemModule,\n            dependencies: [\n                .module(resolvedLLBuildCoreModule, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildCommandsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildCommandsModule,\n            dependencies: [\n                .module(resolvedLLBuildCoreModule, conditions: []),\n                .module(resolvedLLBuildBuildSystemModule, conditions: []),\n                .module(resolvedLLBuildNinjaModule, conditions: []),\n            ]\n        )\n\n        let resolvedLibllbuildModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: libllbuildModule,\n            dependencies: [\n                .module(resolvedLLBuildCoreModule, conditions: []),\n                .module(resolvedLLBuildBuildSystemModule, conditions: []),\n                .module(resolvedLLBuildNinjaModule, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildSwiftModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildSwiftModule,\n            dependencies: [\n                .module(resolvedLibllbuildModule, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildAnalysisModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildAnalysisModule,\n            dependencies: [\n                .module(resolvedLLBuildSwiftModule, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildExecModule,\n            dependencies: [\n                .module(resolvedLLBuildCommandsModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedLibllbuildProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: libllbuildProduct,\n            modules: IdentifiableSet([resolvedLibllbuildModule])\n        )\n\n        let resolvedLLBuildProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: llbuildProduct,\n            modules: IdentifiableSet([resolvedLLBuildExecModule])\n        )\n\n        let resolvedLLBuildAnalysisProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: llbuildAnalysisProduct,\n            modules: IdentifiableSet([resolvedLLBuildAnalysisModule])\n        )\n\n        let resolvedLLBuildSwiftProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: llbuildSwiftProduct,\n            modules: IdentifiableSet([resolvedLLBuildSwiftModule])\n        )\n\n        let resolvedLLBuildSwiftDynamicProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: llbuildSwiftDynamicProduct,\n            modules: IdentifiableSet([resolvedLLBuildSwiftModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedLLVMDemangleModule, resolvedLLVMSupportModule, resolvedLLBuildBasicModule,\n                resolvedLLBuildCoreModule, resolvedLLBuildNinjaModule, resolvedLLBuildBuildSystemModule,\n                resolvedLLBuildCommandsModule, resolvedLibllbuildModule, resolvedLLBuildSwiftModule,\n                resolvedLLBuildAnalysisModule, resolvedLLBuildExecModule,\n            ]),\n            products: [\n                resolvedLibllbuildProduct, resolvedLLBuildProduct, resolvedLLBuildAnalysisProduct,\n                resolvedLLBuildSwiftProduct, resolvedLLBuildSwiftDynamicProduct,\n            ],\n            dependencies: [PackageIdentity.plain(\"swift-toolchain-sqlite\")],\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-llbuild.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                llvmDemangleModule, llvmSupportModule, llbuildBasicModule, llbuildCoreModule,\n                llbuildNinjaModule, llbuildBuildSystemModule, llbuildCommandsModule,\n                libllbuildModule, llbuildSwiftModule, llbuildAnalysisModule, llbuildExecModule,\n            ],\n            products: [\n                libllbuildProduct, llbuildProduct, llbuildAnalysisProduct,\n                llbuildSwiftProduct, llbuildSwiftDynamicProduct,\n            ],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedLLVMDemangleModule, resolvedLLVMSupportModule, resolvedLLBuildBasicModule,\n                resolvedLLBuildCoreModule, resolvedLLBuildNinjaModule, resolvedLLBuildBuildSystemModule,\n                resolvedLLBuildCommandsModule, resolvedLibllbuildModule, resolvedLLBuildSwiftModule,\n                resolvedLLBuildAnalysisModule, resolvedLLBuildExecModule,\n            ],\n            resolvedProducts: [\n                resolvedLibllbuildProduct, resolvedLLBuildProduct, resolvedLLBuildAnalysisProduct,\n                resolvedLLBuildSwiftProduct, resolvedLLBuildSwiftDynamicProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-tools-support-core Package\n\n    static func createSPMSwiftToolsSupportCorePackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-tools-support-core\")\n\n        // Modules\n        let tscLibcModule = self.createSwiftModule(name: \"TSCLibc\")\n        let tscClibcModule = self.createSwiftModule(name: \"TSCclibc\")\n        let tscBasicModule = self.createSwiftModule(name: \"TSCBasic\")\n        let tscUtilityModule = self.createSwiftModule(name: \"TSCUtility\")\n        let tscTestSupportModule = self.createSwiftModule(name: \"TSCTestSupport\")\n\n        // Products\n        let tscBasicProduct = try Product(\n            package: identity,\n            name: \"TSCBasic\",\n            type: .library(.automatic),\n            modules: [tscBasicModule]\n        )\n\n        let swiftToolsSupportProduct = try Product(\n            package: identity,\n            name: \"SwiftToolsSupport\",\n            type: .library(.dynamic),\n            modules: [tscBasicModule, tscUtilityModule]\n        )\n\n        let swiftToolsSupportAutoProduct = try Product(\n            package: identity,\n            name: \"SwiftToolsSupport-auto\",\n            type: .library(.automatic),\n            modules: [tscBasicModule, tscUtilityModule]\n        )\n\n        let tscTestSupportProduct = try Product(\n            package: identity,\n            name: \"TSCTestSupport\",\n            type: .library(.automatic),\n            modules: [tscTestSupportModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-tools-support-core\",\n            path: \"/swift-tools-support-core\",\n            modules: [tscLibcModule, tscClibcModule, tscBasicModule, tscUtilityModule, tscTestSupportModule],\n            products: [tscBasicProduct, swiftToolsSupportProduct, swiftToolsSupportAutoProduct, tscTestSupportProduct]\n        )\n\n        // Resolved modules\n        let resolvedTSCLibcModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscLibcModule\n        )\n\n        let resolvedTSCClibcModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscClibcModule\n        )\n\n        let resolvedTSCBasicModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscBasicModule,\n            dependencies: [\n                .module(resolvedTSCLibcModule, conditions: []),\n                .module(resolvedTSCClibcModule, conditions: []),\n            ]\n        )\n\n        let resolvedTSCUtilityModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscUtilityModule,\n            dependencies: [\n                .module(resolvedTSCBasicModule, conditions: []),\n                .module(resolvedTSCClibcModule, conditions: []),\n            ]\n        )\n\n        let resolvedTSCTestSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscTestSupportModule,\n            dependencies: [\n                .module(resolvedTSCBasicModule, conditions: []),\n                .module(resolvedTSCUtilityModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedTSCBasicProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: tscBasicProduct,\n            modules: IdentifiableSet([resolvedTSCBasicModule])\n        )\n\n        let resolvedSwiftToolsSupportProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftToolsSupportProduct,\n            modules: IdentifiableSet([resolvedTSCBasicModule, resolvedTSCUtilityModule])\n        )\n\n        let resolvedSwiftToolsSupportAutoProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftToolsSupportAutoProduct,\n            modules: IdentifiableSet([resolvedTSCBasicModule, resolvedTSCUtilityModule])\n        )\n\n        let resolvedTSCTestSupportProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: tscTestSupportProduct,\n            modules: IdentifiableSet([resolvedTSCTestSupportModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedTSCLibcModule, resolvedTSCClibcModule, resolvedTSCBasicModule,\n                resolvedTSCUtilityModule, resolvedTSCTestSupportModule,\n            ]),\n            products: [\n                resolvedTSCBasicProduct, resolvedSwiftToolsSupportProduct,\n                resolvedSwiftToolsSupportAutoProduct, resolvedTSCTestSupportProduct,\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-tools-support-core.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [tscLibcModule, tscClibcModule, tscBasicModule, tscUtilityModule, tscTestSupportModule],\n            products: [tscBasicProduct, swiftToolsSupportProduct, swiftToolsSupportAutoProduct, tscTestSupportProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedTSCLibcModule, resolvedTSCClibcModule, resolvedTSCBasicModule,\n                resolvedTSCUtilityModule, resolvedTSCTestSupportModule,\n            ],\n            resolvedProducts: [\n                resolvedTSCBasicProduct, resolvedSwiftToolsSupportProduct,\n                resolvedSwiftToolsSupportAutoProduct, resolvedTSCTestSupportProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-driver Package\n\n    static func createSPMSwiftDriverPackage(\n        swiftToolsSupportAutoProduct: ResolvedProduct,\n        llbuildSwiftProduct: ResolvedProduct,\n        argumentParserProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-driver\")\n\n        // Modules\n        let cSwiftScanModule = self.createSwiftModule(name: \"CSwiftScan\")\n        let swiftOptionsModule = self.createSwiftModule(name: \"SwiftOptions\")\n        let swiftDriverModule = self.createSwiftModule(name: \"SwiftDriver\")\n        let swiftDriverExecutionModule = self.createSwiftModule(name: \"SwiftDriverExecution\")\n        let swiftDriverExecModule = self.createSwiftModule(name: \"swift-driver\", type: .executable)\n        let swiftHelpModule = self.createSwiftModule(name: \"swift-help\", type: .executable)\n        let swiftBuildSDKInterfacesModule = self.createSwiftModule(\n            name: \"swift-build-sdk-interfaces\",\n            type: .executable\n        )\n\n        // Products\n        let swiftDriverProduct = try Product(\n            package: identity,\n            name: \"SwiftDriver\",\n            type: .library(.automatic),\n            modules: [swiftDriverModule]\n        )\n\n        let swiftDriverDynamicProduct = try Product(\n            package: identity,\n            name: \"SwiftDriverDynamic\",\n            type: .library(.dynamic),\n            modules: [swiftDriverModule]\n        )\n\n        let swiftDriverExecutionProduct = try Product(\n            package: identity,\n            name: \"SwiftDriverExecution\",\n            type: .library(.automatic),\n            modules: [swiftDriverExecutionModule]\n        )\n\n        let swiftOptionsProduct = try Product(\n            package: identity,\n            name: \"SwiftOptions\",\n            type: .library(.automatic),\n            modules: [swiftOptionsModule]\n        )\n\n        let swiftDriverExecProduct = try Product(\n            package: identity,\n            name: \"swift-driver\",\n            type: .executable,\n            modules: [swiftDriverExecModule]\n        )\n\n        let swiftHelpProduct = try Product(\n            package: identity,\n            name: \"swift-help\",\n            type: .executable,\n            modules: [swiftHelpModule]\n        )\n\n        let swiftBuildSDKInterfacesProduct = try Product(\n            package: identity,\n            name: \"swift-build-sdk-interfaces\",\n            type: .executable,\n            modules: [swiftBuildSDKInterfacesModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-driver\",\n            path: \"/swift-driver\",\n            modules: [\n                cSwiftScanModule, swiftOptionsModule, swiftDriverModule, swiftDriverExecutionModule,\n                swiftDriverExecModule, swiftHelpModule, swiftBuildSDKInterfacesModule,\n            ],\n            products: [\n                swiftDriverProduct, swiftDriverDynamicProduct, swiftDriverExecutionProduct,\n                swiftOptionsProduct, swiftDriverExecProduct, swiftHelpProduct, swiftBuildSDKInterfacesProduct,\n            ]\n        )\n\n        // Resolved modules\n        let resolvedCSwiftScanModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cSwiftScanModule\n        )\n\n        let resolvedSwiftOptionsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftOptionsModule,\n            dependencies: [\n                .product(swiftToolsSupportAutoProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftDriverModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftDriverModule,\n            dependencies: [\n                .module(resolvedSwiftOptionsModule, conditions: []),\n                .module(resolvedCSwiftScanModule, conditions: []),\n                .product(swiftToolsSupportAutoProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftDriverExecutionModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftDriverExecutionModule,\n            dependencies: [\n                .module(resolvedSwiftDriverModule, conditions: []),\n                .product(swiftToolsSupportAutoProduct, conditions: []),\n                .product(llbuildSwiftProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftDriverExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftDriverExecModule,\n            dependencies: [\n                .module(resolvedSwiftDriverExecutionModule, conditions: []),\n                .module(resolvedSwiftDriverModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftHelpModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftHelpModule,\n            dependencies: [\n                .module(resolvedSwiftOptionsModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(swiftToolsSupportAutoProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftBuildSDKInterfacesModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftBuildSDKInterfacesModule,\n            dependencies: [\n                .module(resolvedSwiftDriverModule, conditions: []),\n                .module(resolvedSwiftDriverExecutionModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedSwiftDriverProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftDriverProduct,\n            modules: IdentifiableSet([resolvedSwiftDriverModule])\n        )\n\n        let resolvedSwiftDriverDynamicProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftDriverDynamicProduct,\n            modules: IdentifiableSet([resolvedSwiftDriverModule])\n        )\n\n        let resolvedSwiftDriverExecutionProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftDriverExecutionProduct,\n            modules: IdentifiableSet([resolvedSwiftDriverExecutionModule])\n        )\n\n        let resolvedSwiftOptionsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftOptionsProduct,\n            modules: IdentifiableSet([resolvedSwiftOptionsModule])\n        )\n\n        let resolvedSwiftDriverExecProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftDriverExecProduct,\n            modules: IdentifiableSet([resolvedSwiftDriverExecModule])\n        )\n\n        let resolvedSwiftHelpProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftHelpProduct,\n            modules: IdentifiableSet([resolvedSwiftHelpModule])\n        )\n\n        let resolvedSwiftBuildSDKInterfacesProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftBuildSDKInterfacesProduct,\n            modules: IdentifiableSet([resolvedSwiftBuildSDKInterfacesModule])\n        )\n\n        // Resolved package\n        // swift-driver\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedCSwiftScanModule, resolvedSwiftOptionsModule, resolvedSwiftDriverModule,\n                resolvedSwiftDriverExecutionModule, resolvedSwiftDriverExecModule, resolvedSwiftHelpModule,\n                resolvedSwiftBuildSDKInterfacesModule,\n            ]),\n            products: [\n                resolvedSwiftDriverProduct, resolvedSwiftDriverDynamicProduct, resolvedSwiftDriverExecutionProduct,\n                resolvedSwiftOptionsProduct, resolvedSwiftDriverExecProduct, resolvedSwiftHelpProduct,\n                resolvedSwiftBuildSDKInterfacesProduct,\n            ],\n            dependencies: [\n                PackageIdentity.plain(\"swift-argument-parser\"),\n                PackageIdentity.plain(\"swift-llbuild\"),\n                PackageIdentity.plain(\"swift-tools-support-core\"),\n            ],\n            // enabledTraits: [\"SPMTrait1\", \"SPMTrait2\"]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-driver.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                cSwiftScanModule, swiftOptionsModule, swiftDriverModule, swiftDriverExecutionModule,\n                swiftDriverExecModule, swiftHelpModule, swiftBuildSDKInterfacesModule,\n            ],\n            products: [\n                swiftDriverProduct, swiftDriverDynamicProduct, swiftDriverExecutionProduct,\n                swiftOptionsProduct, swiftDriverExecProduct, swiftHelpProduct, swiftBuildSDKInterfacesProduct,\n            ],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedCSwiftScanModule, resolvedSwiftOptionsModule, resolvedSwiftDriverModule,\n                resolvedSwiftDriverExecutionModule, resolvedSwiftDriverExecModule, resolvedSwiftHelpModule,\n                resolvedSwiftBuildSDKInterfacesModule,\n            ],\n            resolvedProducts: [\n                resolvedSwiftDriverProduct, resolvedSwiftDriverDynamicProduct, resolvedSwiftDriverExecutionProduct,\n                resolvedSwiftOptionsProduct, resolvedSwiftDriverExecProduct, resolvedSwiftHelpProduct,\n                resolvedSwiftBuildSDKInterfacesProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMDocumentationPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-docc-symbolkit Package\n\n    static func createSPMSwiftDoccSymbolKitPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-docc-symbolkit\")\n\n        // Modules\n        let symbolKitModule = self.createSwiftModule(name: \"SymbolKit\")\n\n        // Products\n        let symbolKitProduct = try Product(\n            package: identity,\n            name: \"SymbolKit\",\n            type: .library(.automatic),\n            modules: [symbolKitModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"SymbolKit\",\n            path: \"/swift-docc-symbolkit\",\n            modules: [symbolKitModule],\n            products: [symbolKitProduct]\n        )\n\n        // Resolved modules\n        let resolvedSymbolKitModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: symbolKitModule\n        )\n\n        // Resolved products\n        let resolvedSymbolKitProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: symbolKitProduct,\n            modules: IdentifiableSet([resolvedSymbolKitModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedSymbolKitModule]),\n            products: [resolvedSymbolKitProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-docc-symbolkit\"))\n        )\n\n        return (\n            package: package,\n            modules: [symbolKitModule],\n            products: [symbolKitProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedSymbolKitModule],\n            resolvedProducts: [resolvedSymbolKitProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-docc-plugin Package\n\n    static func createSPMSwiftDoccPluginPackage(\n        symbolKitProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-docc-plugin\")\n\n        // Modules\n        let snippetsModule = self.createSwiftModule(name: \"Snippets\")\n        let snippetExtractModule = self.createSwiftModule(name: \"snippet-extract\", type: .executable)\n        let swiftDoccModule = self.createSwiftModule(name: \"Swift-DocC\", type: .plugin)\n        let swiftDoccPreviewModule = self.createSwiftModule(name: \"Swift-DocC Preview\", type: .plugin)\n\n        // Products\n        let snippetExtractProduct = try Product(\n            package: identity,\n            name: \"snippet-extract\",\n            type: .executable,\n            modules: [snippetExtractModule]\n        )\n\n        let swiftDoccProduct = try Product(\n            package: identity,\n            name: \"Swift-DocC\",\n            type: .plugin,\n            modules: [swiftDoccModule]\n        )\n\n        let swiftDoccPreviewProduct = try Product(\n            package: identity,\n            name: \"Swift-DocC Preview\",\n            type: .plugin,\n            modules: [swiftDoccPreviewModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"SwiftDocCPlugin\",\n            path: \"/swift-docc-plugin\",\n            modules: [snippetsModule, snippetExtractModule, swiftDoccModule, swiftDoccPreviewModule],\n            products: [snippetExtractProduct, swiftDoccProduct, swiftDoccPreviewProduct]\n        )\n\n        // Resolved modules\n        let resolvedSnippetsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: snippetsModule\n        )\n\n        let resolvedSnippetExtractModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: snippetExtractModule,\n            dependencies: [\n                .module(resolvedSnippetsModule, conditions: []),\n                .product(symbolKitProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftDoccModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftDoccModule,\n            dependencies: [\n                .module(resolvedSnippetExtractModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftDoccPreviewModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftDoccPreviewModule,\n            dependencies: [\n                .module(resolvedSnippetExtractModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedSnippetExtractProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: snippetExtractProduct,\n            modules: IdentifiableSet([resolvedSnippetExtractModule])\n        )\n\n        let resolvedSwiftDoccProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftDoccProduct,\n            modules: IdentifiableSet([resolvedSwiftDoccModule])\n        )\n\n        let resolvedSwiftDoccPreviewProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftDoccPreviewProduct,\n            modules: IdentifiableSet([resolvedSwiftDoccPreviewModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedSnippetsModule, resolvedSnippetExtractModule,\n                resolvedSwiftDoccModule, resolvedSwiftDoccPreviewModule,\n            ]),\n            products: [\n                resolvedSnippetExtractProduct, resolvedSwiftDoccProduct, resolvedSwiftDoccPreviewProduct,\n            ],\n            dependencies: [PackageIdentity.plain(\"swift-docc-symbolkit\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-docc-plugin\"))\n        )\n\n        return (\n            package: package,\n            modules: [snippetsModule, snippetExtractModule, swiftDoccModule, swiftDoccPreviewModule],\n            products: [snippetExtractProduct, swiftDoccProduct, swiftDoccPreviewProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedSnippetsModule, resolvedSnippetExtractModule,\n                resolvedSwiftDoccModule, resolvedSwiftDoccPreviewModule,\n            ],\n            resolvedProducts: [\n                resolvedSnippetExtractProduct, resolvedSwiftDoccProduct, resolvedSwiftDoccPreviewProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMFoundationPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-system Package\n\n    static func createSPMSwiftSystemPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-system\")\n\n        // Modules\n        let cSystemModule = self.createSwiftModule(name: \"CSystem\")\n        let systemPackageModule = self.createSwiftModule(name: \"SystemPackage\")\n\n        // Products\n        let systemPackageProduct = try Product(\n            package: identity,\n            name: \"SystemPackage\",\n            type: .library(.automatic),\n            modules: [systemPackageModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-system\",\n            path: \"/swift-system\",\n            modules: [cSystemModule, systemPackageModule],\n            products: [systemPackageProduct]\n        )\n\n        // Resolved modules\n        let resolvedCSystemModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cSystemModule\n        )\n\n        let resolvedSystemPackageModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: systemPackageModule,\n            dependencies: [\n                .module(resolvedCSystemModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedSystemPackageProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: systemPackageProduct,\n            modules: IdentifiableSet([resolvedSystemPackageModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedCSystemModule, resolvedSystemPackageModule]),\n            products: [resolvedSystemPackageProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-system.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [cSystemModule, systemPackageModule],\n            products: [systemPackageProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedCSystemModule, resolvedSystemPackageModule],\n            resolvedProducts: [resolvedSystemPackageProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-collections Package\n\n    static func createSPMSwiftCollectionsPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-collections\")\n\n        // Modules\n        let internalCollectionsUtilitiesModule = self.createSwiftModule(name: \"InternalCollectionsUtilities\")\n        let bitCollectionsModule = self.createSwiftModule(name: \"BitCollections\")\n        let dequeModuleModule = self.createSwiftModule(name: \"DequeModule\")\n        let hashTreeCollectionsModule = self.createSwiftModule(name: \"HashTreeCollections\")\n        let heapModuleModule = self.createSwiftModule(name: \"HeapModule\")\n        let orderedCollectionsModule = self.createSwiftModule(name: \"OrderedCollections\")\n        let ropeModuleModule = self.createSwiftModule(name: \"_RopeModule\")\n        let collectionsModule = self.createSwiftModule(name: \"Collections\")\n\n        // Products\n        let bitCollectionsProduct = try Product(\n            package: identity,\n            name: \"BitCollections\",\n            type: .library(.automatic),\n            modules: [bitCollectionsModule]\n        )\n\n        let dequeModuleProduct = try Product(\n            package: identity,\n            name: \"DequeModule\",\n            type: .library(.automatic),\n            modules: [dequeModuleModule]\n        )\n\n        let hashTreeCollectionsProduct = try Product(\n            package: identity,\n            name: \"HashTreeCollections\",\n            type: .library(.automatic),\n            modules: [hashTreeCollectionsModule]\n        )\n\n        let heapModuleProduct = try Product(\n            package: identity,\n            name: \"HeapModule\",\n            type: .library(.automatic),\n            modules: [heapModuleModule]\n        )\n\n        let orderedCollectionsProduct = try Product(\n            package: identity,\n            name: \"OrderedCollections\",\n            type: .library(.automatic),\n            modules: [orderedCollectionsModule]\n        )\n\n        let ropeModuleProduct = try Product(\n            package: identity,\n            name: \"_RopeModule\",\n            type: .library(.automatic),\n            modules: [ropeModuleModule]\n        )\n\n        let collectionsProduct = try Product(\n            package: identity,\n            name: \"Collections\",\n            type: .library(.automatic),\n            modules: [collectionsModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-collections\",\n            path: \"/swift-collections\",\n            modules: [\n                internalCollectionsUtilitiesModule, bitCollectionsModule, dequeModuleModule,\n                hashTreeCollectionsModule, heapModuleModule, orderedCollectionsModule,\n                ropeModuleModule, collectionsModule,\n            ],\n            products: [\n                bitCollectionsProduct, dequeModuleProduct, hashTreeCollectionsProduct,\n                heapModuleProduct, orderedCollectionsProduct, ropeModuleProduct, collectionsProduct,\n            ]\n        )\n\n        // Resolved modules\n        let resolvedInternalCollectionsUtilitiesModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: internalCollectionsUtilitiesModule\n        )\n\n        let resolvedBitCollectionsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: bitCollectionsModule,\n            dependencies: [\n                .module(resolvedInternalCollectionsUtilitiesModule, conditions: []),\n            ]\n        )\n\n        let resolvedDequeModuleModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: dequeModuleModule,\n            dependencies: [\n                .module(resolvedInternalCollectionsUtilitiesModule, conditions: []),\n            ]\n        )\n\n        let resolvedHashTreeCollectionsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: hashTreeCollectionsModule,\n            dependencies: [\n                .module(resolvedInternalCollectionsUtilitiesModule, conditions: []),\n            ]\n        )\n\n        let resolvedHeapModuleModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: heapModuleModule,\n            dependencies: [\n                .module(resolvedInternalCollectionsUtilitiesModule, conditions: []),\n            ]\n        )\n\n        let resolvedOrderedCollectionsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: orderedCollectionsModule,\n            dependencies: [\n                .module(resolvedInternalCollectionsUtilitiesModule, conditions: []),\n            ]\n        )\n\n        let resolvedRopeModuleModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: ropeModuleModule,\n            dependencies: [\n                .module(resolvedInternalCollectionsUtilitiesModule, conditions: []),\n            ]\n        )\n\n        let resolvedCollectionsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: collectionsModule,\n            dependencies: [\n                .module(resolvedBitCollectionsModule, conditions: []),\n                .module(resolvedDequeModuleModule, conditions: []),\n                .module(resolvedHashTreeCollectionsModule, conditions: []),\n                .module(resolvedHeapModuleModule, conditions: []),\n                .module(resolvedOrderedCollectionsModule, conditions: []),\n                .module(resolvedRopeModuleModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedBitCollectionsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: bitCollectionsProduct,\n            modules: IdentifiableSet([resolvedBitCollectionsModule])\n        )\n\n        let resolvedDequeModuleProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: dequeModuleProduct,\n            modules: IdentifiableSet([resolvedDequeModuleModule])\n        )\n\n        let resolvedHashTreeCollectionsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: hashTreeCollectionsProduct,\n            modules: IdentifiableSet([resolvedHashTreeCollectionsModule])\n        )\n\n        let resolvedHeapModuleProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: heapModuleProduct,\n            modules: IdentifiableSet([resolvedHeapModuleModule])\n        )\n\n        let resolvedOrderedCollectionsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: orderedCollectionsProduct,\n            modules: IdentifiableSet([resolvedOrderedCollectionsModule])\n        )\n\n        let resolvedRopeModuleProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: ropeModuleProduct,\n            modules: IdentifiableSet([resolvedRopeModuleModule])\n        )\n\n        let resolvedCollectionsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: collectionsProduct,\n            modules: IdentifiableSet([resolvedCollectionsModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedInternalCollectionsUtilitiesModule, resolvedBitCollectionsModule,\n                resolvedDequeModuleModule, resolvedHashTreeCollectionsModule, resolvedHeapModuleModule,\n                resolvedOrderedCollectionsModule, resolvedRopeModuleModule, resolvedCollectionsModule,\n            ]),\n            products: [\n                resolvedBitCollectionsProduct, resolvedDequeModuleProduct, resolvedHashTreeCollectionsProduct,\n                resolvedHeapModuleProduct, resolvedOrderedCollectionsProduct, resolvedRopeModuleProduct,\n                resolvedCollectionsProduct,\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-collections.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                internalCollectionsUtilitiesModule, bitCollectionsModule, dequeModuleModule,\n                hashTreeCollectionsModule, heapModuleModule, orderedCollectionsModule,\n                ropeModuleModule, collectionsModule,\n            ],\n            products: [\n                bitCollectionsProduct, dequeModuleProduct, hashTreeCollectionsProduct,\n                heapModuleProduct, orderedCollectionsProduct, ropeModuleProduct, collectionsProduct,\n            ],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedInternalCollectionsUtilitiesModule, resolvedBitCollectionsModule,\n                resolvedDequeModuleModule, resolvedHashTreeCollectionsModule, resolvedHeapModuleModule,\n                resolvedOrderedCollectionsModule, resolvedRopeModuleModule, resolvedCollectionsModule,\n            ],\n            resolvedProducts: [\n                resolvedBitCollectionsProduct, resolvedDequeModuleProduct, resolvedHashTreeCollectionsProduct,\n                resolvedHeapModuleProduct, resolvedOrderedCollectionsProduct, resolvedRopeModuleProduct,\n                resolvedCollectionsProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-argument-parser Package\n\n    static func createSPMSwiftArgumentParserPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-argument-parser\")\n\n        // Modules\n        let argumentParserToolInfoModule = self.createSwiftModule(name: \"ArgumentParserToolInfo\")\n        let argumentParserModule = self.createSwiftModule(name: \"ArgumentParser\")\n        let generateDoccReferenceModule = self.createSwiftModule(name: \"GenerateDoccReference\", type: .plugin)\n        let generateManualModule = self.createSwiftModule(name: \"GenerateManual\", type: .plugin)\n        let generateDoccReferenceExecModule = self.createSwiftModule(name: \"generate-docc-reference\", type: .executable)\n        let generateManualExecModule = self.createSwiftModule(name: \"generate-manual\", type: .executable)\n\n        // Products\n        let argumentParserProduct = try Product(\n            package: identity,\n            name: \"ArgumentParser\",\n            type: .library(.automatic),\n            modules: [argumentParserModule]\n        )\n\n        let generateDoccReferenceProduct = try Product(\n            package: identity,\n            name: \"GenerateDoccReference\",\n            type: .plugin,\n            modules: [generateDoccReferenceModule]\n        )\n\n        let generateManualProduct = try Product(\n            package: identity,\n            name: \"GenerateManual\",\n            type: .plugin,\n            modules: [generateManualModule]\n        )\n\n        let generateDoccReferenceExecProduct = try Product(\n            package: identity,\n            name: \"generate-docc-reference\",\n            type: .executable,\n            modules: [generateDoccReferenceExecModule]\n        )\n\n        let generateManualExecProduct = try Product(\n            package: identity,\n            name: \"generate-manual\",\n            type: .executable,\n            modules: [generateManualExecModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-argument-parser\",\n            path: \"/swift-argument-parser\",\n            modules: [\n                argumentParserToolInfoModule, argumentParserModule, generateDoccReferenceModule,\n                generateManualModule, generateDoccReferenceExecModule, generateManualExecModule,\n            ],\n            products: [\n                argumentParserProduct, generateDoccReferenceProduct, generateManualProduct,\n                generateDoccReferenceExecProduct, generateManualExecProduct,\n            ]\n        )\n\n        // Resolved modules\n        let resolvedArgumentParserToolInfoModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: argumentParserToolInfoModule\n        )\n\n        let resolvedArgumentParserModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: argumentParserModule,\n            dependencies: [\n                .module(resolvedArgumentParserToolInfoModule, conditions: []),\n            ]\n        )\n\n        let resolvedGenerateDoccReferenceExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: generateDoccReferenceExecModule,\n            dependencies: [\n                .module(resolvedArgumentParserModule, conditions: []),\n                .module(resolvedArgumentParserToolInfoModule, conditions: []),\n            ]\n        )\n\n        let resolvedGenerateManualExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: generateManualExecModule,\n            dependencies: [\n                .module(resolvedArgumentParserModule, conditions: []),\n                .module(resolvedArgumentParserToolInfoModule, conditions: []),\n            ]\n        )\n\n        let resolvedGenerateDoccReferenceModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: generateDoccReferenceModule,\n            dependencies: [\n                .module(resolvedGenerateDoccReferenceExecModule, conditions: []),\n            ]\n        )\n\n        let resolvedGenerateManualModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: generateManualModule,\n            dependencies: [\n                .module(resolvedGenerateManualExecModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedArgumentParserProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: argumentParserProduct,\n            modules: IdentifiableSet([resolvedArgumentParserModule])\n        )\n\n        let resolvedGenerateDoccReferenceProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: generateDoccReferenceProduct,\n            modules: IdentifiableSet([resolvedGenerateDoccReferenceModule])\n        )\n\n        let resolvedGenerateManualProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: generateManualProduct,\n            modules: IdentifiableSet([resolvedGenerateManualModule])\n        )\n\n        let resolvedGenerateDoccReferenceExecProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: generateDoccReferenceExecProduct,\n            modules: IdentifiableSet([resolvedGenerateDoccReferenceExecModule])\n        )\n\n        let resolvedGenerateManualExecProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: generateManualExecProduct,\n            modules: IdentifiableSet([resolvedGenerateManualExecModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedArgumentParserToolInfoModule, resolvedArgumentParserModule,\n                resolvedGenerateDoccReferenceModule, resolvedGenerateManualModule,\n                resolvedGenerateDoccReferenceExecModule, resolvedGenerateManualExecModule,\n            ]),\n            products: [\n                resolvedArgumentParserProduct, resolvedGenerateDoccReferenceProduct,\n                resolvedGenerateManualProduct, resolvedGenerateDoccReferenceExecProduct,\n                resolvedGenerateManualExecProduct,\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-argument-parser.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                argumentParserToolInfoModule, argumentParserModule, generateDoccReferenceModule,\n                generateManualModule, generateDoccReferenceExecModule, generateManualExecModule,\n            ],\n            products: [\n                argumentParserProduct, generateDoccReferenceProduct, generateManualProduct,\n                generateDoccReferenceExecProduct, generateManualExecProduct,\n            ],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedArgumentParserToolInfoModule, resolvedArgumentParserModule,\n                resolvedGenerateDoccReferenceModule, resolvedGenerateManualModule,\n                resolvedGenerateDoccReferenceExecModule, resolvedGenerateManualExecModule,\n            ],\n            resolvedProducts: [\n                resolvedArgumentParserProduct, resolvedGenerateDoccReferenceProduct,\n                resolvedGenerateManualProduct, resolvedGenerateDoccReferenceExecProduct,\n                resolvedGenerateManualExecProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-toolchain-sqlite Package\n\n    static func createSPMSwiftToolchainSQLitePackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-toolchain-sqlite\")\n\n        // Modules\n        let swiftToolchainCSQLiteModule = self.createSwiftModule(name: \"SwiftToolchainCSQLite\")\n        let sqliteModule = self.createSwiftModule(name: \"sqlite\", type: .executable)\n\n        // Products\n        let swiftToolchainCSQLiteProduct = try Product(\n            package: identity,\n            name: \"SwiftToolchainCSQLite\",\n            type: .library(.automatic),\n            modules: [swiftToolchainCSQLiteModule]\n        )\n\n        let sqliteProduct = try Product(\n            package: identity,\n            name: \"sqlite\",\n            type: .executable,\n            modules: [sqliteModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-toolchain-sqlite\",\n            path: \"/swift-toolchain-sqlite\",\n            modules: [swiftToolchainCSQLiteModule, sqliteModule],\n            products: [swiftToolchainCSQLiteProduct, sqliteProduct]\n        )\n\n        // Resolved modules\n        let resolvedSwiftToolchainCSQLiteModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftToolchainCSQLiteModule\n        )\n\n        let resolvedSQLiteModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: sqliteModule,\n            dependencies: [\n                .module(resolvedSwiftToolchainCSQLiteModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedSwiftToolchainCSQLiteProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftToolchainCSQLiteProduct,\n            modules: IdentifiableSet([resolvedSwiftToolchainCSQLiteModule])\n        )\n\n        let resolvedSQLiteProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: sqliteProduct,\n            modules: IdentifiableSet([resolvedSQLiteModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedSwiftToolchainCSQLiteModule, resolvedSQLiteModule]),\n            products: [resolvedSwiftToolchainCSQLiteProduct, resolvedSQLiteProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-toolchain-sqlite.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [swiftToolchainCSQLiteModule, sqliteModule],\n            products: [swiftToolchainCSQLiteProduct, sqliteProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedSwiftToolchainCSQLiteModule, resolvedSQLiteModule],\n            resolvedProducts: [resolvedSwiftToolchainCSQLiteProduct, resolvedSQLiteProduct],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMRootPackageAssembly.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - Root SPM Package - Part 4: Products & Assembly\n\n    static func createSPMRootPackageComplete(\n        rootPath: String = \"/swift-package-manager\",\n        systemPackageProduct: ResolvedProduct,\n        dequeModuleProduct: ResolvedProduct,\n        orderedCollectionsProduct: ResolvedProduct,\n        argumentParserProduct: ResolvedProduct,\n        llbuildSwiftProduct: ResolvedProduct,\n        swiftDriverProduct: ResolvedProduct,\n        swiftToolsSupportAutoProduct: ResolvedProduct,\n        tscBasicProduct: ResolvedProduct,\n        tscTestSupportProduct: ResolvedProduct,\n        cryptoProduct: ResolvedProduct,\n        x509Product: ResolvedProduct,\n        swiftToolchainCSQLiteProduct: ResolvedProduct,\n        swiftIDEUtilsProduct: ResolvedProduct,\n        swiftRefactorProduct: ResolvedProduct,\n        swiftDiagnosticsProduct: ResolvedProduct,\n        swiftParserProduct: ResolvedProduct,\n        swiftSyntaxProduct: ResolvedProduct,\n        swiftBuildProduct: ResolvedProduct,\n        swbBuildServiceProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-package-manager\")\n\n        // MARK: - Create all module groups\n\n        let coreResult = createSPMRootCoreModules(\n            systemPackageProduct: systemPackageProduct,\n            dequeModuleProduct: dequeModuleProduct,\n            orderedCollectionsProduct: orderedCollectionsProduct,\n            swiftToolchainCSQLiteProduct: swiftToolchainCSQLiteProduct,\n            swiftToolsSupportAutoProduct: swiftToolsSupportAutoProduct,\n            llbuildSwiftProduct: llbuildSwiftProduct,\n            swiftDriverProduct: swiftDriverProduct,\n            tscBasicProduct: tscBasicProduct,\n            cryptoProduct: cryptoProduct,\n            x509Product: x509Product\n        )\n\n        let commandResult = createSPMRootCommandModules(\n            coreResolvedModules: coreResult.resolvedModules,\n            argumentParserProduct: argumentParserProduct,\n            orderedCollectionsProduct: orderedCollectionsProduct,\n            tscBasicProduct: tscBasicProduct,\n            swiftIDEUtilsProduct: swiftIDEUtilsProduct,\n            swiftRefactorProduct: swiftRefactorProduct,\n            swiftDiagnosticsProduct: swiftDiagnosticsProduct,\n            swiftParserProduct: swiftParserProduct,\n            swiftSyntaxProduct: swiftSyntaxProduct,\n            swiftBuildProduct: swiftBuildProduct,\n            swbBuildServiceProduct: swbBuildServiceProduct\n        )\n\n        let executableResult = createSPMRootExecutableModules(\n            coreResolvedModules: coreResult.resolvedModules,\n            commandResolvedModules: commandResult.resolvedModules,\n            argumentParserProduct: argumentParserProduct,\n            orderedCollectionsProduct: orderedCollectionsProduct\n        )\n\n        // Combine all modules\n        let allModules = coreResult.modules + commandResult.modules + executableResult.modules\n        let allResolvedModules = coreResult.resolvedModules + commandResult.resolvedModules + executableResult\n            .resolvedModules\n\n        // Extract specific resolved modules for products\n        let resolvedBuildModule = coreResult.resolvedModules.first { $0.name == \"Build\" }!\n        let resolvedLLBuildManifestModule = coreResult.resolvedModules.first { $0.name == \"LLBuildManifest\" }!\n        let resolvedPackageCollectionsModule = coreResult.resolvedModules.first { $0.name == \"PackageCollections\" }!\n        let resolvedPackageCollectionsModelModule = coreResult.resolvedModules\n            .first { $0.name == \"PackageCollectionsModel\" }!\n        let resolvedPackageCollectionsSigningModule = coreResult.resolvedModules\n            .first { $0.name == \"PackageCollectionsSigning\" }!\n        let resolvedPackageGraphModule = coreResult.resolvedModules.first { $0.name == \"PackageGraph\" }!\n        let resolvedPackageLoadingModule = coreResult.resolvedModules.first { $0.name == \"PackageLoading\" }!\n        let resolvedPackageMetadataModule = coreResult.resolvedModules.first { $0.name == \"PackageMetadata\" }!\n        let resolvedPackageModelModule = coreResult.resolvedModules.first { $0.name == \"PackageModel\" }!\n        let resolvedSPMLLBuildModule = coreResult.resolvedModules.first { $0.name == \"SPMLLBuild\" }!\n        let resolvedSourceControlModule = coreResult.resolvedModules.first { $0.name == \"SourceControl\" }!\n        let resolvedSourceKitLSPAPIModule = coreResult.resolvedModules.first { $0.name == \"SourceKitLSPAPI\" }!\n        let resolvedWorkspaceModule = coreResult.resolvedModules.first { $0.name == \"Workspace\" }!\n\n        let resolvedCompilerPluginSupportModule = commandResult.resolvedModules\n            .first { $0.name == \"CompilerPluginSupport\" }!\n        let resolvedPackageDescriptionModule = commandResult.resolvedModules.first { $0.name == \"PackageDescription\" }!\n        let resolvedPackagePluginModule = commandResult.resolvedModules.first { $0.name == \"PackagePlugin\" }!\n        let resolvedAppleProductTypesModule = commandResult.resolvedModules.first { $0.name == \"AppleProductTypes\" }!\n        let resolvedXCBuildSupportModule = commandResult.resolvedModules.first { $0.name == \"XCBuildSupport\" }!\n\n        // MARK: - Create Products\n\n        // Dynamic library products\n        let appleProductTypesProduct = try Product(\n            package: identity,\n            name: \"AppleProductTypes\",\n            type: .library(.dynamic),\n            modules: [allModules.first { $0.name == \"AppleProductTypes\" }!]\n        )\n\n        let packageDescriptionProduct = try Product(\n            package: identity,\n            name: \"PackageDescription\",\n            type: .library(.dynamic),\n            modules: [\n                allModules.first { $0.name == \"CompilerPluginSupport\" }!,\n                allModules.first { $0.name == \"PackageDescription\" }!,\n            ]\n        )\n\n        let packagePluginProduct = try Product(\n            package: identity,\n            name: \"PackagePlugin\",\n            type: .library(.dynamic),\n            modules: [allModules.first { $0.name == \"PackagePlugin\" }!]\n        )\n\n        let swiftPMProduct = try Product(\n            package: identity,\n            name: \"SwiftPM\",\n            type: .library(.dynamic),\n            modules: [\n                allModules.first { $0.name == \"Build\" }!,\n                allModules.first { $0.name == \"LLBuildManifest\" }!,\n                allModules.first { $0.name == \"PackageCollections\" }!,\n                allModules.first { $0.name == \"PackageCollectionsModel\" }!,\n                allModules.first { $0.name == \"PackageGraph\" }!,\n                allModules.first { $0.name == \"PackageLoading\" }!,\n                allModules.first { $0.name == \"PackageMetadata\" }!,\n                allModules.first { $0.name == \"PackageModel\" }!,\n                allModules.first { $0.name == \"SPMLLBuild\" }!,\n                allModules.first { $0.name == \"SourceControl\" }!,\n                allModules.first { $0.name == \"SourceKitLSPAPI\" }!,\n                allModules.first { $0.name == \"Workspace\" }!,\n            ]\n        )\n\n        // THE KEY PRODUCT: SwiftPMDataModel\n        let swiftPMDataModelProduct = try Product(\n            package: identity,\n            name: \"SwiftPMDataModel\",\n            type: .library(.dynamic),\n            modules: [\n                allModules.first { $0.name == \"PackageCollections\" }!,\n                allModules.first { $0.name == \"PackageCollectionsModel\" }!,\n                allModules.first { $0.name == \"PackageGraph\" }!,\n                allModules.first { $0.name == \"PackageLoading\" }!,\n                allModules.first { $0.name == \"PackageMetadata\" }!,\n                allModules.first { $0.name == \"PackageModel\" }!,\n                allModules.first { $0.name == \"SourceControl\" }!,\n                allModules.first { $0.name == \"Workspace\" }!,\n            ]\n        )\n\n        // Automatic library products\n        let swiftPMAutoProduct = try Product(\n            package: identity,\n            name: \"SwiftPM-auto\",\n            type: .library(.automatic),\n            modules: [\n                allModules.first { $0.name == \"Build\" }!,\n                allModules.first { $0.name == \"LLBuildManifest\" }!,\n                allModules.first { $0.name == \"PackageCollections\" }!,\n                allModules.first { $0.name == \"PackageCollectionsModel\" }!,\n                allModules.first { $0.name == \"PackageGraph\" }!,\n                allModules.first { $0.name == \"PackageLoading\" }!,\n                allModules.first { $0.name == \"PackageMetadata\" }!,\n                allModules.first { $0.name == \"PackageModel\" }!,\n                allModules.first { $0.name == \"SPMLLBuild\" }!,\n                allModules.first { $0.name == \"SourceControl\" }!,\n                allModules.first { $0.name == \"SourceKitLSPAPI\" }!,\n                allModules.first { $0.name == \"Workspace\" }!,\n            ]\n        )\n\n        let swiftPMDataModelAutoProduct = try Product(\n            package: identity,\n            name: \"SwiftPMDataModel-auto\",\n            type: .library(.automatic),\n            modules: [\n                allModules.first { $0.name == \"PackageCollections\" }!,\n                allModules.first { $0.name == \"PackageCollectionsModel\" }!,\n                allModules.first { $0.name == \"PackageGraph\" }!,\n                allModules.first { $0.name == \"PackageLoading\" }!,\n                allModules.first { $0.name == \"PackageMetadata\" }!,\n                allModules.first { $0.name == \"PackageModel\" }!,\n                allModules.first { $0.name == \"SourceControl\" }!,\n                allModules.first { $0.name == \"Workspace\" }!,\n            ]\n        )\n\n        let packageCollectionsModelProduct = try Product(\n            package: identity,\n            name: \"PackageCollectionsModel\",\n            type: .library(.automatic),\n            modules: [allModules.first { $0.name == \"PackageCollectionsModel\" }!]\n        )\n\n        let swiftPMPackageCollectionsProduct = try Product(\n            package: identity,\n            name: \"SwiftPMPackageCollections\",\n            type: .library(.automatic),\n            modules: [\n                allModules.first { $0.name == \"PackageCollections\" }!,\n                allModules.first { $0.name == \"PackageCollectionsModel\" }!,\n                allModules.first { $0.name == \"PackageCollectionsSigning\" }!,\n                allModules.first { $0.name == \"PackageModel\" }!,\n            ]\n        )\n\n        let xcBuildSupportProduct = try Product(\n            package: identity,\n            name: \"XCBuildSupport\",\n            type: .library(.automatic),\n            modules: [allModules.first { $0.name == \"XCBuildSupport\" }!]\n        )\n\n        // Executable products (simplified - just create them without listing all)\n        let executableProducts = try [\n            Product(\n                package: identity,\n                name: \"dummy-swiftc\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"dummy-swiftc\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"package-info\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"package-info\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-bootstrap\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-bootstrap\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-build\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-build\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-build-prebuilts\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-build-prebuilts\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-experimental-sdk\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-experimental-sdk\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-package\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-package\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-package-collection\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-package-collection\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-package-manager\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-package-manager\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-package-registry\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-package-registry\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-run\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-run\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-sdk\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-sdk\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swift-test\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swift-test\" }!]\n            ),\n            Product(\n                package: identity,\n                name: \"swiftpm-testing-helper\",\n                type: .executable,\n                modules: [allModules.first { $0.name == \"swiftpm-testing-helper\" }!]\n            ),\n        ]\n\n        let allProducts = [\n            appleProductTypesProduct, packageDescriptionProduct, packagePluginProduct,\n            swiftPMProduct, swiftPMDataModelProduct, swiftPMAutoProduct, swiftPMDataModelAutoProduct,\n            packageCollectionsModelProduct, swiftPMPackageCollectionsProduct, xcBuildSupportProduct,\n        ] + executableProducts\n\n        // MARK: - Create Package\n\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"SwiftPM\",\n            path: rootPath,\n            modules: allModules,\n            products: allProducts\n        )\n\n        // MARK: - Create Resolved Products\n\n        let resolvedAppleProductTypesProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: appleProductTypesProduct,\n            modules: IdentifiableSet([resolvedAppleProductTypesModule])\n        )\n\n        let resolvedPackageDescriptionProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: packageDescriptionProduct,\n            modules: IdentifiableSet([resolvedCompilerPluginSupportModule, resolvedPackageDescriptionModule])\n        )\n\n        let resolvedPackagePluginProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: packagePluginProduct,\n            modules: IdentifiableSet([resolvedPackagePluginModule])\n        )\n\n        let resolvedSwiftPMProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftPMProduct,\n            modules: IdentifiableSet([\n                resolvedBuildModule, resolvedLLBuildManifestModule, resolvedPackageCollectionsModule,\n                resolvedPackageCollectionsModelModule, resolvedPackageGraphModule, resolvedPackageLoadingModule,\n                resolvedPackageMetadataModule, resolvedPackageModelModule, resolvedSPMLLBuildModule,\n                resolvedSourceControlModule, resolvedSourceKitLSPAPIModule, resolvedWorkspaceModule,\n            ])\n        )\n\n        let resolvedSwiftPMDataModelProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftPMDataModelProduct,\n            modules: IdentifiableSet([\n                resolvedPackageCollectionsModule, resolvedPackageCollectionsModelModule, resolvedPackageGraphModule,\n                resolvedPackageLoadingModule, resolvedPackageMetadataModule, resolvedPackageModelModule,\n                resolvedSourceControlModule, resolvedWorkspaceModule,\n            ])\n        )\n\n        let resolvedSwiftPMAutoProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftPMAutoProduct,\n            modules: IdentifiableSet([\n                resolvedBuildModule, resolvedLLBuildManifestModule, resolvedPackageCollectionsModule,\n                resolvedPackageCollectionsModelModule, resolvedPackageGraphModule, resolvedPackageLoadingModule,\n                resolvedPackageMetadataModule, resolvedPackageModelModule, resolvedSPMLLBuildModule,\n                resolvedSourceControlModule, resolvedSourceKitLSPAPIModule, resolvedWorkspaceModule,\n            ])\n        )\n\n        let resolvedSwiftPMDataModelAutoProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftPMDataModelAutoProduct,\n            modules: IdentifiableSet([\n                resolvedPackageCollectionsModule, resolvedPackageCollectionsModelModule, resolvedPackageGraphModule,\n                resolvedPackageLoadingModule, resolvedPackageMetadataModule, resolvedPackageModelModule,\n                resolvedSourceControlModule, resolvedWorkspaceModule,\n            ])\n        )\n\n        let resolvedPackageCollectionsModelProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: packageCollectionsModelProduct,\n            modules: IdentifiableSet([resolvedPackageCollectionsModelModule])\n        )\n\n        let resolvedSwiftPMPackageCollectionsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftPMPackageCollectionsProduct,\n            modules: IdentifiableSet([\n                resolvedPackageCollectionsModule, resolvedPackageCollectionsModelModule,\n                resolvedPackageCollectionsSigningModule, resolvedPackageModelModule,\n            ])\n        )\n\n        let resolvedXCBuildSupportProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: xcBuildSupportProduct,\n            modules: IdentifiableSet([resolvedXCBuildSupportModule])\n        )\n\n        // Create resolved executable products\n        let resolvedExecutableProducts = executableProducts.map { product in\n            self.createResolvedProduct(\n                packageIdentity: identity,\n                product: product,\n                modules: IdentifiableSet([allResolvedModules.first { $0.name == product.name }!])\n            )\n        }\n\n        let allResolvedProducts = [\n            resolvedAppleProductTypesProduct, resolvedPackageDescriptionProduct, resolvedPackagePluginProduct,\n            resolvedSwiftPMProduct, resolvedSwiftPMDataModelProduct, resolvedSwiftPMAutoProduct,\n            resolvedSwiftPMDataModelAutoProduct, resolvedPackageCollectionsModelProduct,\n            resolvedSwiftPMPackageCollectionsProduct, resolvedXCBuildSupportProduct,\n        ] + resolvedExecutableProducts\n\n        // MARK: - Create Resolved Package\n\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet(allResolvedModules),\n            products: allResolvedProducts,\n            dependencies: [\n                PackageIdentity.plain(\"swift-system\"),\n                PackageIdentity.plain(\"swift-collections\"),\n                PackageIdentity.plain(\"swift-argument-parser\"),\n                PackageIdentity.plain(\"swift-llbuild\"),\n                PackageIdentity.plain(\"swift-tools-support-core\"),\n                PackageIdentity.plain(\"swift-driver\"),\n                PackageIdentity.plain(\"swift-crypto\"),\n                PackageIdentity.plain(\"swift-certificates\"),\n                PackageIdentity.plain(\"swift-toolchain-sqlite\"),\n                PackageIdentity.plain(\"swift-syntax\"),\n                PackageIdentity.plain(\"swift-build\"),\n                PackageIdentity.plain(\"swift-docc-plugin\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .root(AbsolutePath(rootPath))\n        )\n\n        return (\n            package: package,\n            modules: allModules,\n            products: allProducts,\n            resolvedPackage: resolvedPackage,\n            resolvedModules: allResolvedModules,\n            resolvedProducts: allResolvedProducts,\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMRootPackageCommand.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - Root SPM Package - Part 2: Command & Support Modules\n\n    /// Creates command, support, and plugin modules for the root SwiftPM package\n    /// These include Commands, XCBuildSupport, SwiftBuildSupport, PackagePlugin, etc.\n    static func createSPMRootCommandModules(\n        coreResolvedModules: [ResolvedModule],\n        argumentParserProduct: ResolvedProduct,\n        orderedCollectionsProduct: ResolvedProduct,\n        tscBasicProduct: ResolvedProduct,\n        swiftIDEUtilsProduct: ResolvedProduct,\n        swiftRefactorProduct: ResolvedProduct,\n        swiftDiagnosticsProduct: ResolvedProduct,\n        swiftParserProduct: ResolvedProduct,\n        swiftSyntaxProduct: ResolvedProduct,\n        swiftBuildProduct: ResolvedProduct,\n        swbBuildServiceProduct: ResolvedProduct\n    ) -> (\n        modules: [Module],\n        resolvedModules: [ResolvedModule]\n    ) {\n        let identity = PackageIdentity.plain(\"swift-package-manager\")\n\n        // Extract core resolved modules we need\n        let resolvedBasicsModule = coreResolvedModules.first { $0.name == \"Basics\" }!\n        let resolvedBinarySymbolsModule = coreResolvedModules.first { $0.name == \"BinarySymbols\" }!\n        let resolvedBuildModule = coreResolvedModules.first { $0.name == \"Build\" }!\n        let resolvedPackageModelModule = coreResolvedModules.first { $0.name == \"PackageModel\" }!\n        let resolvedPackageLoadingModule = coreResolvedModules.first { $0.name == \"PackageLoading\" }!\n        let resolvedPackageGraphModule = coreResolvedModules.first { $0.name == \"PackageGraph\" }!\n        let resolvedPackageCollectionsModule = coreResolvedModules.first { $0.name == \"PackageCollections\" }!\n        _ = coreResolvedModules.first { $0.name == \"PackageCollectionsModel\" }!\n        let resolvedPackageRegistryModule = coreResolvedModules.first { $0.name == \"PackageRegistry\" }!\n        let resolvedPackageSigningModule = coreResolvedModules.first { $0.name == \"PackageSigning\" }!\n        let resolvedSourceControlModule = coreResolvedModules.first { $0.name == \"SourceControl\" }!\n        let resolvedWorkspaceModule = coreResolvedModules.first { $0.name == \"Workspace\" }!\n        let resolvedSBOMModelModule = coreResolvedModules.first { $0.name == \"SBOMModel\" }!\n        let resolvedSPMBuildCoreModule = coreResolvedModules.first { $0.name == \"SPMBuildCore\" }!\n\n        // MARK: - Create Command & Support Modules\n\n        let xcBuildSupportModule = self.createSwiftModule(name: \"XCBuildSupport\")\n        let swiftBuildSupportModule = self.createSwiftModule(name: \"SwiftBuildSupport\")\n        let swiftFixItModule = self.createSwiftModule(name: \"SwiftFixIt\")\n        let coreCommandsModule = self.createSwiftModule(name: \"CoreCommands\")\n        let commandsModule = self.createSwiftModule(name: \"Commands\")\n        let packageCollectionsCommandModule = self.createSwiftModule(name: \"PackageCollectionsCommand\")\n        let swiftSDKCommandModule = self.createSwiftModule(name: \"SwiftSDKCommand\")\n        let packageRegistryCommandModule = self.createSwiftModule(name: \"PackageRegistryCommand\")\n        let packageDescriptionModule = self.createSwiftModule(name: \"PackageDescription\")\n        let compilerPluginSupportModule = self.createSwiftModule(name: \"CompilerPluginSupport\")\n        let packagePluginModule = self.createSwiftModule(name: \"PackagePlugin\")\n        let appleProductTypesModule = self.createSwiftModule(name: \"AppleProductTypes\")\n        let packageManagerDocsModule = self.createSwiftModule(name: \"PackageManagerDocs\")\n\n        // Test support modules\n        let internalTestSupportModule = self.createSwiftModule(name: \"_InternalTestSupport\")\n        let integrationTestSupportModule = self.createSwiftModule(name: \"_IntegrationTestSupport\")\n        let internalBuildTestSupportModule = self.createSwiftModule(name: \"_InternalBuildTestSupport\")\n        let tsanUtilsModule = self.createSwiftModule(name: \"tsan_utils\")\n\n        // MARK: - Create Resolved Modules with Dependencies\n\n        let resolvedXCBuildSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: xcBuildSupportModule,\n            dependencies: [\n                .module(resolvedSPMBuildCoreModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftBuildSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftBuildSupportModule,\n            dependencies: [\n                .module(resolvedSPMBuildCoreModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .product(swiftBuildProduct, conditions: []),\n                .product(swbBuildServiceProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftFixItModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftFixItModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .product(tscBasicProduct, conditions: []),\n                .product(swiftDiagnosticsProduct, conditions: []),\n                .product(swiftIDEUtilsProduct, conditions: []),\n                .product(swiftParserProduct, conditions: []),\n                .product(swiftSyntaxProduct, conditions: []),\n            ]\n        )\n\n        let resolvedCoreCommandsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: coreCommandsModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedBuildModule, conditions: []),\n                .module(resolvedPackageLoadingModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedWorkspaceModule, conditions: []),\n                .module(resolvedXCBuildSupportModule, conditions: []),\n                .module(resolvedSwiftBuildSupportModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n            ]\n        )\n\n        let resolvedCommandsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: commandsModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedBinarySymbolsModule, conditions: []),\n                .module(resolvedBuildModule, conditions: []),\n                .module(resolvedCoreCommandsModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedSBOMModelModule, conditions: []),\n                .module(resolvedSourceControlModule, conditions: []),\n                .module(resolvedWorkspaceModule, conditions: []),\n                .module(resolvedXCBuildSupportModule, conditions: []),\n                .module(resolvedSwiftBuildSupportModule, conditions: []),\n                .module(resolvedSwiftFixItModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n                .product(swiftIDEUtilsProduct, conditions: []),\n                .product(swiftRefactorProduct, conditions: []),\n            ]\n        )\n\n        let resolvedPackageCollectionsCommandModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageCollectionsCommandModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedCommandsModule, conditions: []),\n                .module(resolvedCoreCommandsModule, conditions: []),\n                .module(resolvedPackageCollectionsModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftSDKCommandModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSDKCommandModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedCoreCommandsModule, conditions: []),\n                .module(resolvedSPMBuildCoreModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n            ]\n        )\n\n        let resolvedPackageRegistryCommandModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageRegistryCommandModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedCommandsModule, conditions: []),\n                .module(resolvedCoreCommandsModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedPackageLoadingModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedPackageRegistryModule, conditions: []),\n                .module(resolvedPackageSigningModule, conditions: []),\n                .module(resolvedSourceControlModule, conditions: []),\n                .module(resolvedSPMBuildCoreModule, conditions: []),\n                .module(resolvedWorkspaceModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n            ]\n        )\n\n        let resolvedPackageDescriptionModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageDescriptionModule\n        )\n\n        let resolvedCompilerPluginSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: compilerPluginSupportModule,\n            dependencies: [.module(resolvedPackageDescriptionModule, conditions: [])]\n        )\n\n        let resolvedPackagePluginModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packagePluginModule\n        )\n\n        let resolvedAppleProductTypesModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: appleProductTypesModule,\n            dependencies: [.module(resolvedPackageDescriptionModule, conditions: [])]\n        )\n\n        let resolvedPackageManagerDocsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageManagerDocsModule\n        )\n\n        // Test support modules\n        let resolvedInternalTestSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: internalTestSupportModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedPackageLoadingModule, conditions: []),\n                .module(resolvedPackageRegistryModule, conditions: []),\n                .module(resolvedPackageSigningModule, conditions: []),\n                .module(resolvedSourceControlModule, conditions: []),\n                .module(resolvedWorkspaceModule, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedIntegrationTestSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: integrationTestSupportModule,\n            dependencies: [.module(resolvedInternalTestSupportModule, conditions: [])]\n        )\n\n        let resolvedInternalBuildTestSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: internalBuildTestSupportModule,\n            dependencies: [\n                .module(resolvedBuildModule, conditions: []),\n                .module(resolvedXCBuildSupportModule, conditions: []),\n                .module(resolvedSwiftBuildSupportModule, conditions: []),\n                .module(resolvedInternalTestSupportModule, conditions: []),\n            ]\n        )\n\n        let resolvedTsanUtilsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tsanUtilsModule\n        )\n\n        return (\n            modules: [\n                xcBuildSupportModule, swiftBuildSupportModule, swiftFixItModule, coreCommandsModule,\n                commandsModule, packageCollectionsCommandModule, swiftSDKCommandModule,\n                packageRegistryCommandModule, packageDescriptionModule, compilerPluginSupportModule,\n                packagePluginModule, appleProductTypesModule, packageManagerDocsModule,\n                internalTestSupportModule, integrationTestSupportModule, internalBuildTestSupportModule,\n                tsanUtilsModule,\n            ],\n            resolvedModules: [\n                resolvedXCBuildSupportModule, resolvedSwiftBuildSupportModule, resolvedSwiftFixItModule,\n                resolvedCoreCommandsModule, resolvedCommandsModule, resolvedPackageCollectionsCommandModule,\n                resolvedSwiftSDKCommandModule, resolvedPackageRegistryCommandModule, resolvedPackageDescriptionModule,\n                resolvedCompilerPluginSupportModule, resolvedPackagePluginModule, resolvedAppleProductTypesModule,\n                resolvedPackageManagerDocsModule, resolvedInternalTestSupportModule,\n                resolvedIntegrationTestSupportModule,\n                resolvedInternalBuildTestSupportModule, resolvedTsanUtilsModule,\n            ]\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMRootPackageCore.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - Root SPM Package - Part 1: Core Library Modules\n\n    /// Creates the core library modules for the root SwiftPM package\n    /// These are the fundamental building blocks: Basics, PackageModel, PackageGraph, etc.\n    static func createSPMRootCoreModules(\n        systemPackageProduct: ResolvedProduct,\n        dequeModuleProduct: ResolvedProduct,\n        orderedCollectionsProduct: ResolvedProduct,\n        swiftToolchainCSQLiteProduct: ResolvedProduct,\n        swiftToolsSupportAutoProduct: ResolvedProduct,\n        llbuildSwiftProduct: ResolvedProduct,\n        swiftDriverProduct: ResolvedProduct,\n        tscBasicProduct: ResolvedProduct,\n        cryptoProduct: ResolvedProduct,\n        x509Product: ResolvedProduct\n    ) -> (\n        modules: [Module],\n        resolvedModules: [ResolvedModule]\n    ) {\n        let identity = PackageIdentity.plain(\"swift-package-manager\")\n\n        // MARK: - Create Core Modules\n\n        let asyncFileSystemModule = self.createSwiftModule(name: \"_AsyncFileSystem\")\n        let basicsModule = self.createSwiftModule(name: \"Basics\")\n        let binarySymbolsModule = self.createSwiftModule(name: \"BinarySymbols\")\n        let packageModelModule = self.createSwiftModule(name: \"PackageModel\")\n        let sourceControlModule = self.createSwiftModule(name: \"SourceControl\")\n        let packageLoadingModule = self.createSwiftModule(name: \"PackageLoading\")\n        let packageGraphModule = self.createSwiftModule(name: \"PackageGraph\")\n        let packageCollectionsModelModule = self.createSwiftModule(name: \"PackageCollectionsModel\")\n        let packageCollectionsSigningModule = self.createSwiftModule(name: \"PackageCollectionsSigning\")\n        let packageCollectionsModule = self.createSwiftModule(name: \"PackageCollections\")\n        let packageMetadataModule = self.createSwiftModule(name: \"PackageMetadata\")\n        let packageFingerprintModule = self.createSwiftModule(name: \"PackageFingerprint\")\n        let packageSigningModule = self.createSwiftModule(name: \"PackageSigning\")\n        let packageRegistryModule = self.createSwiftModule(name: \"PackageRegistry\")\n        let spmBuildCoreModule = self.createSwiftModule(name: \"SPMBuildCore\")\n        let workspaceModule = self.createSwiftModule(name: \"Workspace\")\n        let llbuildManifestModule = self.createSwiftModule(name: \"LLBuildManifest\")\n        let spmLLBuildModule = self.createSwiftModule(name: \"SPMLLBuild\")\n        let driverSupportModule = self.createSwiftModule(name: \"DriverSupport\")\n        let buildModule = self.createSwiftModule(name: \"Build\")\n        let sourceKitLSPAPIModule = self.createSwiftModule(name: \"SourceKitLSPAPI\")\n        let queryEngineModule = self.createSwiftModule(name: \"QueryEngine\")\n        let sbomModelModule = self.createSwiftModule(name: \"SBOMModel\")\n        let spmSQLite3Module = self.createSwiftModule(name: \"SPMSQLite3\", type: .systemModule)\n\n        // MARK: - Create Resolved Modules with Dependencies\n\n        let resolvedAsyncFileSystemModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: asyncFileSystemModule,\n            dependencies: [.product(systemPackageProduct, conditions: [])]\n        )\n\n        let resolvedBasicsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: basicsModule,\n            dependencies: [\n                .module(resolvedAsyncFileSystemModule, conditions: []),\n                .product(swiftToolchainCSQLiteProduct, conditions: []),\n                .product(dequeModuleProduct, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n                .product(swiftToolsSupportAutoProduct, conditions: []),\n            ]\n        )\n\n        let resolvedBinarySymbolsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: binarySymbolsModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .product(tscBasicProduct, conditions: []),\n            ]\n        )\n\n        let resolvedPackageModelModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageModelModule,\n            dependencies: [.module(resolvedBasicsModule, conditions: [])]\n        )\n\n        let resolvedSourceControlModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: sourceControlModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n            ]\n        )\n\n        let resolvedPackageLoadingModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageLoadingModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedSourceControlModule, conditions: []),\n            ]\n        )\n\n        let resolvedPackageGraphModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageGraphModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedPackageLoadingModule, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedPackageCollectionsModelModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageCollectionsModelModule,\n            dependencies: [.module(resolvedBasicsModule, conditions: [])]\n        )\n\n        let resolvedPackageCollectionsSigningModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageCollectionsSigningModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageCollectionsModelModule, conditions: []),\n                .product(cryptoProduct, conditions: []),\n                .product(x509Product, conditions: []),\n            ]\n        )\n\n        let resolvedPackageCollectionsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageCollectionsModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageCollectionsModelModule, conditions: []),\n                .module(resolvedPackageCollectionsSigningModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedSourceControlModule, conditions: []),\n            ]\n        )\n\n        let resolvedPackageMetadataModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageMetadataModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageCollectionsModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n            ]\n        )\n\n        let resolvedPackageFingerprintModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageFingerprintModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n            ]\n        )\n\n        let resolvedPackageSigningModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageSigningModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .product(cryptoProduct, conditions: []),\n                .product(x509Product, conditions: []),\n            ]\n        )\n\n        let resolvedPackageRegistryModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageRegistryModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageFingerprintModule, conditions: []),\n                .module(resolvedPackageLoadingModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedPackageSigningModule, conditions: []),\n            ]\n        )\n\n        let resolvedSPMBuildCoreModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: spmBuildCoreModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedWorkspaceModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: workspaceModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageFingerprintModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedPackageRegistryModule, conditions: []),\n                .module(resolvedPackageSigningModule, conditions: []),\n                .module(resolvedSourceControlModule, conditions: []),\n                .module(resolvedSPMBuildCoreModule, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedLLBuildManifestModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: llbuildManifestModule,\n            dependencies: [.module(resolvedBasicsModule, conditions: [])]\n        )\n\n        let resolvedSPMLLBuildModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: spmLLBuildModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .product(llbuildSwiftProduct, conditions: []),\n            ]\n        )\n\n        let resolvedDriverSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: driverSupportModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .product(swiftDriverProduct, conditions: []),\n            ]\n        )\n\n        let resolvedBuildModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: buildModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedLLBuildManifestModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedSPMBuildCoreModule, conditions: []),\n                .module(resolvedSPMLLBuildModule, conditions: []),\n                .module(resolvedDriverSupportModule, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n                .product(swiftDriverProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSourceKitLSPAPIModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: sourceKitLSPAPIModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedBuildModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedPackageLoadingModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedSPMBuildCoreModule, conditions: []),\n            ]\n        )\n\n        let resolvedQueryEngineModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: queryEngineModule,\n            dependencies: [\n                .module(resolvedAsyncFileSystemModule, conditions: []),\n                .module(resolvedBasicsModule, conditions: []),\n                .product(cryptoProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSBOMModelModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: sbomModelModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedPackageCollectionsModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedSourceControlModule, conditions: []),\n            ]\n        )\n\n        let resolvedSPMSQLite3Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: spmSQLite3Module\n        )\n\n        return (\n            modules: [\n                asyncFileSystemModule, basicsModule, binarySymbolsModule, packageModelModule,\n                sourceControlModule, packageLoadingModule, packageGraphModule, packageCollectionsModelModule,\n                packageCollectionsSigningModule, packageCollectionsModule, packageMetadataModule,\n                packageFingerprintModule, packageSigningModule, packageRegistryModule, spmBuildCoreModule,\n                workspaceModule, llbuildManifestModule, spmLLBuildModule, driverSupportModule,\n                buildModule, sourceKitLSPAPIModule, queryEngineModule, sbomModelModule, spmSQLite3Module,\n            ],\n            resolvedModules: [\n                resolvedAsyncFileSystemModule, resolvedBasicsModule, resolvedBinarySymbolsModule,\n                resolvedPackageModelModule, resolvedSourceControlModule, resolvedPackageLoadingModule,\n                resolvedPackageGraphModule, resolvedPackageCollectionsModelModule,\n                resolvedPackageCollectionsSigningModule,\n                resolvedPackageCollectionsModule, resolvedPackageMetadataModule, resolvedPackageFingerprintModule,\n                resolvedPackageSigningModule, resolvedPackageRegistryModule, resolvedSPMBuildCoreModule,\n                resolvedWorkspaceModule, resolvedLLBuildManifestModule, resolvedSPMLLBuildModule,\n                resolvedDriverSupportModule, resolvedBuildModule, resolvedSourceKitLSPAPIModule,\n                resolvedQueryEngineModule, resolvedSBOMModelModule, resolvedSPMSQLite3Module,\n            ]\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMRootPackageExecutable.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - Root SPM Package - Part 3: Executable Modules\n\n    /// Creates all executable modules for the root SwiftPM package\n    /// These are the CLI tools: swift-build, swift-package, swift-run, etc.\n    static func createSPMRootExecutableModules(\n        coreResolvedModules: [ResolvedModule],\n        commandResolvedModules: [ResolvedModule],\n        argumentParserProduct: ResolvedProduct,\n        orderedCollectionsProduct: ResolvedProduct\n    ) -> (\n        modules: [Module],\n        resolvedModules: [ResolvedModule]\n    ) {\n        let identity = PackageIdentity.plain(\"swift-package-manager\")\n\n        // Extract resolved modules we need\n        let resolvedBasicsModule = coreResolvedModules.first { $0.name == \"Basics\" }!\n        let resolvedBuildModule = coreResolvedModules.first { $0.name == \"Build\" }!\n        let resolvedPackageModelModule = coreResolvedModules.first { $0.name == \"PackageModel\" }!\n        let resolvedPackageLoadingModule = coreResolvedModules.first { $0.name == \"PackageLoading\" }!\n        let resolvedPackageGraphModule = coreResolvedModules.first { $0.name == \"PackageGraph\" }!\n        let resolvedWorkspaceModule = coreResolvedModules.first { $0.name == \"Workspace\" }!\n\n        let resolvedCommandsModule = commandResolvedModules.first { $0.name == \"Commands\" }!\n        let resolvedXCBuildSupportModule = commandResolvedModules.first { $0.name == \"XCBuildSupport\" }!\n        let resolvedSwiftBuildSupportModule = commandResolvedModules.first { $0.name == \"SwiftBuildSupport\" }!\n        let resolvedSwiftSDKCommandModule = commandResolvedModules.first { $0.name == \"SwiftSDKCommand\" }!\n        let resolvedPackageCollectionsCommandModule = commandResolvedModules\n            .first { $0.name == \"PackageCollectionsCommand\" }!\n        let resolvedPackageRegistryCommandModule = commandResolvedModules.first { $0.name == \"PackageRegistryCommand\" }!\n\n        // MARK: - Create Executable Modules\n\n        let dummySwiftcModule = self.createSwiftModule(name: \"dummy-swiftc\", type: .executable)\n        let packageInfoModule = self.createSwiftModule(name: \"package-info\", type: .executable)\n        let swiftBootstrapModule = self.createSwiftModule(name: \"swift-bootstrap\", type: .executable)\n        let swiftBuildExecModule = self.createSwiftModule(name: \"swift-build\", type: .executable)\n        let swiftBuildPrebuiltsModule = self.createSwiftModule(name: \"swift-build-prebuilts\", type: .executable)\n        let swiftExperimentalSDKModule = self.createSwiftModule(name: \"swift-experimental-sdk\", type: .executable)\n        let swiftPackageExecModule = self.createSwiftModule(name: \"swift-package\", type: .executable)\n        let swiftPackageCollectionExecModule = self.createSwiftModule(\n            name: \"swift-package-collection\",\n            type: .executable\n        )\n        let swiftPackageManagerExecModule = self.createSwiftModule(name: \"swift-package-manager\", type: .executable)\n        let swiftPackageRegistryExecModule = self.createSwiftModule(name: \"swift-package-registry\", type: .executable)\n        let swiftRunModule = self.createSwiftModule(name: \"swift-run\", type: .executable)\n        let swiftSDKModule = self.createSwiftModule(name: \"swift-sdk\", type: .executable)\n        let swiftTestModule = self.createSwiftModule(name: \"swift-test\", type: .executable)\n        let swiftpmTestingHelperModule = self.createSwiftModule(name: \"swiftpm-testing-helper\", type: .executable)\n\n        // MARK: - Create Resolved Modules with Dependencies\n\n        let resolvedDummySwiftcModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: dummySwiftcModule,\n            dependencies: [.module(resolvedBasicsModule, conditions: [])]\n        )\n\n        let resolvedPackageInfoModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: packageInfoModule,\n            dependencies: [.module(resolvedWorkspaceModule, conditions: [])]\n        )\n\n        let resolvedSwiftBootstrapModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftBootstrapModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedBuildModule, conditions: []),\n                .module(resolvedPackageGraphModule, conditions: []),\n                .module(resolvedPackageLoadingModule, conditions: []),\n                .module(resolvedPackageModelModule, conditions: []),\n                .module(resolvedXCBuildSupportModule, conditions: []),\n                .module(resolvedSwiftBuildSupportModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftBuildExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftBuildExecModule,\n            dependencies: [.module(resolvedCommandsModule, conditions: [])]\n        )\n\n        let resolvedSwiftBuildPrebuiltsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftBuildPrebuiltsModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedWorkspaceModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftExperimentalSDKModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftExperimentalSDKModule,\n            dependencies: [\n                .module(resolvedCommandsModule, conditions: []),\n                .module(resolvedSwiftSDKCommandModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftPackageExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftPackageExecModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedCommandsModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftPackageCollectionExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftPackageCollectionExecModule,\n            dependencies: [\n                .module(resolvedCommandsModule, conditions: []),\n                .module(resolvedPackageCollectionsCommandModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftPackageManagerExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftPackageManagerExecModule,\n            dependencies: [\n                .module(resolvedBasicsModule, conditions: []),\n                .module(resolvedCommandsModule, conditions: []),\n                .module(resolvedSwiftSDKCommandModule, conditions: []),\n                .module(resolvedPackageCollectionsCommandModule, conditions: []),\n                .module(resolvedPackageRegistryCommandModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftPackageRegistryExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftPackageRegistryExecModule,\n            dependencies: [\n                .module(resolvedCommandsModule, conditions: []),\n                .module(resolvedPackageRegistryCommandModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftRunModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftRunModule,\n            dependencies: [.module(resolvedCommandsModule, conditions: [])]\n        )\n\n        let resolvedSwiftSDKModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSDKModule,\n            dependencies: [\n                .module(resolvedCommandsModule, conditions: []),\n                .module(resolvedSwiftSDKCommandModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftTestModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftTestModule,\n            dependencies: [.module(resolvedCommandsModule, conditions: [])]\n        )\n\n        let resolvedSwiftpmTestingHelperModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftpmTestingHelperModule\n        )\n\n        return (\n            modules: [\n                dummySwiftcModule, packageInfoModule, swiftBootstrapModule, swiftBuildExecModule,\n                swiftBuildPrebuiltsModule, swiftExperimentalSDKModule, swiftPackageExecModule,\n                swiftPackageCollectionExecModule, swiftPackageManagerExecModule, swiftPackageRegistryExecModule,\n                swiftRunModule, swiftSDKModule, swiftTestModule, swiftpmTestingHelperModule,\n            ],\n            resolvedModules: [\n                resolvedDummySwiftcModule, resolvedPackageInfoModule, resolvedSwiftBootstrapModule,\n                resolvedSwiftBuildExecModule, resolvedSwiftBuildPrebuiltsModule, resolvedSwiftExperimentalSDKModule,\n                resolvedSwiftPackageExecModule, resolvedSwiftPackageCollectionExecModule,\n                resolvedSwiftPackageManagerExecModule, resolvedSwiftPackageRegistryExecModule,\n                resolvedSwiftRunModule, resolvedSwiftSDKModule, resolvedSwiftTestModule,\n                resolvedSwiftpmTestingHelperModule,\n            ]\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMSecurityPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-asn1 Package\n\n    static func createSPMSwiftASN1Package() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-asn1\")\n\n        // Modules\n        let swiftASN1Module = self.createSwiftModule(name: \"SwiftASN1\")\n\n        // Products\n        let swiftASN1Product = try Product(\n            package: identity,\n            name: \"SwiftASN1\",\n            type: .library(.automatic),\n            modules: [swiftASN1Module]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-asn1\",\n            path: \"/swift-asn1\",\n            modules: [swiftASN1Module],\n            products: [swiftASN1Product]\n        )\n\n        // Resolved modules\n        let resolvedSwiftASN1Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftASN1Module\n        )\n\n        // Resolved products\n        let resolvedSwiftASN1Product = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftASN1Product,\n            modules: IdentifiableSet([resolvedSwiftASN1Module])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedSwiftASN1Module]),\n            products: [resolvedSwiftASN1Product]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-asn1.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [swiftASN1Module],\n            products: [swiftASN1Product],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedSwiftASN1Module],\n            resolvedProducts: [resolvedSwiftASN1Product],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-crypto Package\n\n    static func createSPMSwiftCryptoPackage(\n        swiftASN1Product: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-crypto\")\n\n        // Modules\n        let cCryptoBoringSSLModule = self.createSwiftModule(name: \"CCryptoBoringSSL\")\n        let cCryptoBoringSSLShimsModule = self.createSwiftModule(name: \"CCryptoBoringSSLShims\")\n        let cryptoBoringWrapperModule = self.createSwiftModule(name: \"CryptoBoringWrapper\")\n        let cryptoModule = self.createSwiftModule(name: \"Crypto\")\n        let cryptoExtrasModule = self.createSwiftModule(name: \"_CryptoExtras\")\n\n        // Products\n        let cryptoProduct = try Product(\n            package: identity,\n            name: \"Crypto\",\n            type: .library(.automatic),\n            modules: [cryptoModule]\n        )\n\n        let cryptoExtrasProduct = try Product(\n            package: identity,\n            name: \"_CryptoExtras\",\n            type: .library(.automatic),\n            modules: [cryptoExtrasModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-crypto\",\n            path: \"/swift-crypto\",\n            modules: [\n                cCryptoBoringSSLModule, cCryptoBoringSSLShimsModule, cryptoBoringWrapperModule,\n                cryptoModule, cryptoExtrasModule,\n            ],\n            products: [cryptoProduct, cryptoExtrasProduct]\n        )\n\n        // Resolved modules\n        let resolvedCCryptoBoringSSLModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cCryptoBoringSSLModule\n        )\n\n        let resolvedCCryptoBoringSSLShimsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cCryptoBoringSSLShimsModule,\n            dependencies: [\n                .module(resolvedCCryptoBoringSSLModule, conditions: []),\n            ]\n        )\n\n        let resolvedCryptoBoringWrapperModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cryptoBoringWrapperModule,\n            dependencies: [\n                .module(resolvedCCryptoBoringSSLModule, conditions: []),\n                .module(resolvedCCryptoBoringSSLShimsModule, conditions: []),\n            ]\n        )\n\n        let resolvedCryptoModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cryptoModule,\n            dependencies: [\n                .module(resolvedCCryptoBoringSSLModule, conditions: []),\n                .module(resolvedCCryptoBoringSSLShimsModule, conditions: []),\n                .module(resolvedCryptoBoringWrapperModule, conditions: []),\n            ]\n        )\n\n        let resolvedCryptoExtrasModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cryptoExtrasModule,\n            dependencies: [\n                .module(resolvedCCryptoBoringSSLModule, conditions: []),\n                .module(resolvedCCryptoBoringSSLShimsModule, conditions: []),\n                .module(resolvedCryptoBoringWrapperModule, conditions: []),\n                .module(resolvedCryptoModule, conditions: []),\n                .product(swiftASN1Product, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedCryptoProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: cryptoProduct,\n            modules: IdentifiableSet([resolvedCryptoModule])\n        )\n\n        let resolvedCryptoExtrasProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: cryptoExtrasProduct,\n            modules: IdentifiableSet([resolvedCryptoExtrasModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedCCryptoBoringSSLModule, resolvedCCryptoBoringSSLShimsModule,\n                resolvedCryptoBoringWrapperModule, resolvedCryptoModule, resolvedCryptoExtrasModule,\n            ]),\n            products: [resolvedCryptoProduct, resolvedCryptoExtrasProduct],\n            dependencies: [PackageIdentity.plain(\"swift-asn1\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-crypto.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                cCryptoBoringSSLModule, cCryptoBoringSSLShimsModule, cryptoBoringWrapperModule,\n                cryptoModule, cryptoExtrasModule,\n            ],\n            products: [cryptoProduct, cryptoExtrasProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedCCryptoBoringSSLModule, resolvedCCryptoBoringSSLShimsModule,\n                resolvedCryptoBoringWrapperModule, resolvedCryptoModule, resolvedCryptoExtrasModule,\n            ],\n            resolvedProducts: [resolvedCryptoProduct, resolvedCryptoExtrasProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-certificates Package\n\n    static func createSPMSwiftCertificatesPackage(\n        swiftASN1Product: ResolvedProduct,\n        cryptoProduct: ResolvedProduct,\n        cryptoExtrasProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-certificates\")\n\n        // Modules\n        let certificateInternalsModule = self.createSwiftModule(name: \"_CertificateInternals\")\n        let x509Module = self.createSwiftModule(name: \"X509\")\n\n        // Products\n        let x509Product = try Product(\n            package: identity,\n            name: \"X509\",\n            type: .library(.automatic),\n            modules: [x509Module]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-certificates\",\n            path: \"/swift-certificates\",\n            modules: [certificateInternalsModule, x509Module],\n            products: [x509Product]\n        )\n\n        // Resolved modules\n        let resolvedCertificateInternalsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: certificateInternalsModule\n        )\n\n        let resolvedX509Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: x509Module,\n            dependencies: [\n                .module(resolvedCertificateInternalsModule, conditions: []),\n                .product(swiftASN1Product, conditions: []),\n                .product(cryptoProduct, conditions: []),\n                .product(cryptoExtrasProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedX509Product = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: x509Product,\n            modules: IdentifiableSet([resolvedX509Module])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedCertificateInternalsModule, resolvedX509Module]),\n            products: [resolvedX509Product],\n            dependencies: [\n                PackageIdentity.plain(\"swift-asn1\"),\n                PackageIdentity.plain(\"swift-crypto\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-certificates.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [certificateInternalsModule, x509Module],\n            products: [x509Product],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedCertificateInternalsModule, resolvedX509Module],\n            resolvedProducts: [resolvedX509Product],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMSwiftBuildPackage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-build Package (24 modules, 7 products)\n\n    static func createSPMSwiftBuildPackage(\n        swiftSyntaxProduct: ResolvedProduct,\n        swiftParserProduct: ResolvedProduct,\n        swiftDriverProduct: ResolvedProduct,\n        swiftDriverExecutionProduct: ResolvedProduct,\n        llbuildSwiftProduct: ResolvedProduct,\n        swiftToolsSupportAutoProduct: ResolvedProduct,\n        argumentParserProduct: ResolvedProduct,\n        systemPackageProduct: ResolvedProduct,\n        cryptoProduct: ResolvedProduct,\n        x509Product: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-build\")\n\n        // MARK: - Create all 24 modules from spm-debug-output.txt\n\n        // Platform modules\n        let swbAndroidPlatformModule = self.createSwiftModule(name: \"SWBAndroidPlatform\")\n        let swbApplePlatformModule = self.createSwiftModule(name: \"SWBApplePlatform\")\n        let swbGenericUnixPlatformModule = self.createSwiftModule(name: \"SWBGenericUnixPlatform\")\n        let swbQNXPlatformModule = self.createSwiftModule(name: \"SWBQNXPlatform\")\n        let swbUniversalPlatformModule = self.createSwiftModule(name: \"SWBUniversalPlatform\")\n        let swbWebAssemblyPlatformModule = self.createSwiftModule(name: \"SWBWebAssemblyPlatform\")\n        let swbWindowsPlatformModule = self.createSwiftModule(name: \"SWBWindowsPlatform\")\n\n        // Core modules\n        let swbBuildServiceModule = self.createSwiftModule(name: \"SWBBuildService\")\n        let swbBuildSystemModule = self.createSwiftModule(name: \"SWBBuildSystem\")\n        let swbCASModule = self.createSwiftModule(name: \"SWBCAS\")\n        let swbCLibcModule = self.createSwiftModule(name: \"SWBCLibc\")\n        let swbCSupportModule = self.createSwiftModule(name: \"SWBCSupport\")\n        let swbCoreModule = self.createSwiftModule(name: \"SWBCore\")\n        let swbLLBuildModule = self.createSwiftModule(name: \"SWBLLBuild\")\n        let swbLibcModule = self.createSwiftModule(name: \"SWBLibc\")\n        let swbMacroModule = self.createSwiftModule(name: \"SWBMacro\")\n        let swbProjectModelModule = self.createSwiftModule(name: \"SWBProjectModel\")\n        let swbProtocolModule = self.createSwiftModule(name: \"SWBProtocol\")\n        let swbServiceCoreModule = self.createSwiftModule(name: \"SWBServiceCore\")\n        let swbTaskConstructionModule = self.createSwiftModule(name: \"SWBTaskConstruction\")\n        let swbTaskExecutionModule = self.createSwiftModule(name: \"SWBTaskExecution\")\n        let swbUtilModule = self.createSwiftModule(name: \"SWBUtil\")\n\n        // SwiftBuild library module\n        let swiftBuildLibraryModule = self.createSwiftModule(name: \"SwiftBuild\")\n\n        // Executable modules\n        let swbBuildServiceBundleModule = self.createSwiftModule(name: \"SWBBuildServiceBundle\", type: .executable)\n        let swbuildModule = self.createSwiftModule(name: \"swbuild\", type: .executable)\n\n        // MARK: - Create products (7 products from spm-debug-output.txt)\n\n        let swbBuildServiceProduct = try Product(\n            package: identity,\n            name: \"SWBBuildService\",\n            type: .library(.automatic),\n            modules: [swbBuildServiceModule]\n        )\n        let swbBuildServiceBundleProduct = try Product(\n            package: identity,\n            name: \"SWBBuildServiceBundle\",\n            type: .executable,\n            modules: [swbBuildServiceBundleModule]\n        )\n        let swbProjectModelProduct = try Product(\n            package: identity,\n            name: \"SWBProjectModel\",\n            type: .library(.automatic),\n            modules: [swbProjectModelModule]\n        )\n        let swbProtocolProduct = try Product(\n            package: identity,\n            name: \"SWBProtocol\",\n            type: .library(.automatic),\n            modules: [swbProtocolModule]\n        )\n        let swbUtilProduct = try Product(\n            package: identity,\n            name: \"SWBUtil\",\n            type: .library(.automatic),\n            modules: [swbUtilModule]\n        )\n        let swiftBuildLibraryProduct = try Product(\n            package: identity,\n            name: \"SwiftBuild\",\n            type: .library(.automatic),\n            modules: [swiftBuildLibraryModule]\n        )\n        let swbuildProduct = try Product(\n            package: identity,\n            name: \"swbuild\",\n            type: .executable,\n            modules: [swbuildModule]\n        )\n\n        // MARK: - Create package\n\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"SwiftBuild\",\n            path: \"/swift-build\",\n            modules: [\n                swbAndroidPlatformModule, swbApplePlatformModule, swbBuildServiceModule,\n                swbBuildServiceBundleModule, swbBuildSystemModule, swbCASModule, swbCLibcModule,\n                swbCSupportModule, swbCoreModule, swbGenericUnixPlatformModule, swbLLBuildModule,\n                swbLibcModule, swbMacroModule, swbProjectModelModule, swbProtocolModule,\n                swbQNXPlatformModule, swbServiceCoreModule, swbTaskConstructionModule,\n                swbTaskExecutionModule, swbUniversalPlatformModule, swbUtilModule,\n                swbWebAssemblyPlatformModule, swbWindowsPlatformModule, swiftBuildLibraryModule,\n                swbuildModule,\n            ],\n            products: [\n                swbBuildServiceProduct, swbBuildServiceBundleProduct, swbProjectModelProduct,\n                swbProtocolProduct, swbUtilProduct, swiftBuildLibraryProduct, swbuildProduct,\n            ]\n        )\n\n        // MARK: - Create resolved modules with dependencies (based on spm-debug-output.txt lines 462-586)\n\n        let resolvedSWBCLibcModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbCLibcModule,\n            dependencies: []\n        )\n\n        let resolvedSWBCSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbCSupportModule,\n            dependencies: []\n        )\n\n        let resolvedSWBLibcModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbLibcModule,\n            dependencies: [\n                .module(resolvedSWBCLibcModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBUtilModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbUtilModule,\n            dependencies: [\n                .module(resolvedSWBCSupportModule, conditions: []),\n                .module(resolvedSWBLibcModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSWBCASModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbCASModule,\n            dependencies: [\n                .module(resolvedSWBUtilModule, conditions: []),\n                .module(resolvedSWBCSupportModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBLLBuildModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbLLBuildModule,\n            dependencies: [\n                .module(resolvedSWBUtilModule, conditions: []),\n                .product(llbuildSwiftProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSWBProtocolModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbProtocolModule,\n            dependencies: [\n                .module(resolvedSWBUtilModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBServiceCoreModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbServiceCoreModule,\n            dependencies: [\n                .module(resolvedSWBProtocolModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBMacroModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbMacroModule,\n            dependencies: [\n                .module(resolvedSWBUtilModule, conditions: []),\n                .product(swiftDriverProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSWBCoreModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbCoreModule,\n            dependencies: [\n                .module(resolvedSWBMacroModule, conditions: []),\n                .module(resolvedSWBProtocolModule, conditions: []),\n                .module(resolvedSWBServiceCoreModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n                .module(resolvedSWBCASModule, conditions: []),\n                .module(resolvedSWBLLBuildModule, conditions: []),\n                .product(swiftDriverProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSWBTaskConstructionModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbTaskConstructionModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBTaskExecutionModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbTaskExecutionModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n                .module(resolvedSWBCASModule, conditions: []),\n                .module(resolvedSWBLLBuildModule, conditions: []),\n                .module(resolvedSWBTaskConstructionModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBBuildSystemModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbBuildSystemModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBTaskConstructionModule, conditions: []),\n                .module(resolvedSWBTaskExecutionModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBAndroidPlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbAndroidPlatformModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBMacroModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBApplePlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbApplePlatformModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBMacroModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n                .module(resolvedSWBTaskConstructionModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBGenericUnixPlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbGenericUnixPlatformModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBQNXPlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbQNXPlatformModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBMacroModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBUniversalPlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbUniversalPlatformModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBMacroModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n                .module(resolvedSWBTaskConstructionModule, conditions: []),\n                .module(resolvedSWBTaskExecutionModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSWBWebAssemblyPlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbWebAssemblyPlatformModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBMacroModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBWindowsPlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbWindowsPlatformModule,\n            dependencies: [\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBMacroModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBBuildServiceModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbBuildServiceModule,\n            dependencies: [\n                .module(resolvedSWBBuildSystemModule, conditions: []),\n                .module(resolvedSWBServiceCoreModule, conditions: []),\n                .module(resolvedSWBTaskExecutionModule, conditions: []),\n                .module(resolvedSWBAndroidPlatformModule, conditions: []),\n                .module(resolvedSWBApplePlatformModule, conditions: []),\n                .module(resolvedSWBGenericUnixPlatformModule, conditions: []),\n                .module(resolvedSWBQNXPlatformModule, conditions: []),\n                .module(resolvedSWBUniversalPlatformModule, conditions: []),\n                .module(resolvedSWBWebAssemblyPlatformModule, conditions: []),\n                .module(resolvedSWBWindowsPlatformModule, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSWBProjectModelModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbProjectModelModule,\n            dependencies: [\n                .module(resolvedSWBProtocolModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftBuildLibraryModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftBuildLibraryModule,\n            dependencies: [\n                .module(resolvedSWBCSupportModule, conditions: []),\n                .module(resolvedSWBCoreModule, conditions: []),\n                .module(resolvedSWBProtocolModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n                .module(resolvedSWBProjectModelModule, conditions: []),\n            ]\n        )\n\n        let resolvedSWBBuildServiceBundleModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbBuildServiceBundleModule,\n            dependencies: [\n                .module(resolvedSWBBuildServiceModule, conditions: []),\n                .module(resolvedSWBBuildSystemModule, conditions: []),\n                .module(resolvedSWBServiceCoreModule, conditions: []),\n                .module(resolvedSWBUtilModule, conditions: []),\n                .module(resolvedSWBCoreModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwbuildModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swbuildModule,\n            dependencies: [\n                .module(resolvedSwiftBuildLibraryModule, conditions: []),\n                .module(resolvedSWBBuildServiceBundleModule, conditions: []),\n            ]\n        )\n\n        // MARK: - Create resolved products\n\n        let resolvedSWBBuildServiceProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swbBuildServiceProduct,\n            modules: IdentifiableSet([resolvedSWBBuildServiceModule])\n        )\n\n        let resolvedSWBBuildServiceBundleProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swbBuildServiceBundleProduct,\n            modules: IdentifiableSet([resolvedSWBBuildServiceBundleModule])\n        )\n\n        let resolvedSWBProjectModelProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swbProjectModelProduct,\n            modules: IdentifiableSet([resolvedSWBProjectModelModule])\n        )\n\n        let resolvedSWBProtocolProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swbProtocolProduct,\n            modules: IdentifiableSet([resolvedSWBProtocolModule])\n        )\n\n        let resolvedSWBUtilProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swbUtilProduct,\n            modules: IdentifiableSet([resolvedSWBUtilModule])\n        )\n\n        let resolvedSwiftBuildLibraryProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftBuildLibraryProduct,\n            modules: IdentifiableSet([resolvedSwiftBuildLibraryModule])\n        )\n\n        let resolvedSwbuildProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swbuildProduct,\n            modules: IdentifiableSet([resolvedSwbuildModule])\n        )\n\n        // MARK: - Create resolved package\n\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedSWBAndroidPlatformModule, resolvedSWBApplePlatformModule, resolvedSWBBuildServiceModule,\n                resolvedSWBBuildServiceBundleModule, resolvedSWBBuildSystemModule, resolvedSWBCASModule,\n                resolvedSWBCLibcModule, resolvedSWBCSupportModule, resolvedSWBCoreModule,\n                resolvedSWBGenericUnixPlatformModule, resolvedSWBLLBuildModule, resolvedSWBLibcModule,\n                resolvedSWBMacroModule, resolvedSWBProjectModelModule, resolvedSWBProtocolModule,\n                resolvedSWBQNXPlatformModule, resolvedSWBServiceCoreModule, resolvedSWBTaskConstructionModule,\n                resolvedSWBTaskExecutionModule, resolvedSWBUniversalPlatformModule, resolvedSWBUtilModule,\n                resolvedSWBWebAssemblyPlatformModule, resolvedSWBWindowsPlatformModule,\n                resolvedSwiftBuildLibraryModule, resolvedSwbuildModule,\n            ]),\n            products: [\n                resolvedSWBBuildServiceProduct, resolvedSWBBuildServiceBundleProduct,\n                resolvedSWBProjectModelProduct, resolvedSWBProtocolProduct, resolvedSWBUtilProduct,\n                resolvedSwiftBuildLibraryProduct, resolvedSwbuildProduct,\n            ],\n            dependencies: [\n                PackageIdentity.plain(\"swift-argument-parser\"),\n                PackageIdentity.plain(\"swift-driver\"),\n                PackageIdentity.plain(\"swift-llbuild\"),\n                PackageIdentity.plain(\"swift-system\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-build.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                swbAndroidPlatformModule, swbApplePlatformModule, swbBuildServiceModule,\n                swbBuildServiceBundleModule, swbBuildSystemModule, swbCASModule, swbCLibcModule,\n                swbCSupportModule, swbCoreModule, swbGenericUnixPlatformModule, swbLLBuildModule,\n                swbLibcModule, swbMacroModule, swbProjectModelModule, swbProtocolModule,\n                swbQNXPlatformModule, swbServiceCoreModule, swbTaskConstructionModule,\n                swbTaskExecutionModule, swbUniversalPlatformModule, swbUtilModule,\n                swbWebAssemblyPlatformModule, swbWindowsPlatformModule, swiftBuildLibraryModule,\n                swbuildModule,\n            ],\n            products: [\n                swbBuildServiceProduct, swbBuildServiceBundleProduct, swbProjectModelProduct,\n                swbProtocolProduct, swbUtilProduct, swiftBuildLibraryProduct, swbuildProduct,\n            ],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedSWBAndroidPlatformModule, resolvedSWBApplePlatformModule, resolvedSWBBuildServiceModule,\n                resolvedSWBBuildServiceBundleModule, resolvedSWBBuildSystemModule, resolvedSWBCASModule,\n                resolvedSWBCLibcModule, resolvedSWBCSupportModule, resolvedSWBCoreModule,\n                resolvedSWBGenericUnixPlatformModule, resolvedSWBLLBuildModule, resolvedSWBLibcModule,\n                resolvedSWBMacroModule, resolvedSWBProjectModelModule, resolvedSWBProtocolModule,\n                resolvedSWBQNXPlatformModule, resolvedSWBServiceCoreModule, resolvedSWBTaskConstructionModule,\n                resolvedSWBTaskExecutionModule, resolvedSWBUniversalPlatformModule, resolvedSWBUtilModule,\n                resolvedSWBWebAssemblyPlatformModule, resolvedSWBWindowsPlatformModule,\n                resolvedSwiftBuildLibraryModule, resolvedSwbuildModule,\n            ],\n            resolvedProducts: [\n                resolvedSWBBuildServiceProduct, resolvedSWBBuildServiceBundleProduct,\n                resolvedSWBProjectModelProduct, resolvedSWBProtocolProduct, resolvedSWBUtilProduct,\n                resolvedSwiftBuildLibraryProduct, resolvedSwbuildProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SPMFixtures/SBOMSPMSwiftSyntaxPackage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-syntax Package (26 modules)\n\n    static func createSPMSwiftSyntaxPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-syntax\")\n\n        // MARK: - Create all 26 modules\n\n        // Base/Support modules\n        let swiftSyntaxCShimsModule = self.createSwiftModule(name: \"_SwiftSyntaxCShims\")\n        let swiftSyntax509Module = self.createSwiftModule(name: \"SwiftSyntax509\")\n        let swiftSyntax510Module = self.createSwiftModule(name: \"SwiftSyntax510\")\n        let swiftSyntax600Module = self.createSwiftModule(name: \"SwiftSyntax600\")\n        let swiftSyntax601Module = self.createSwiftModule(name: \"SwiftSyntax601\")\n        let swiftSyntax602Module = self.createSwiftModule(name: \"SwiftSyntax602\")\n        let swiftSyntax603Module = self.createSwiftModule(name: \"SwiftSyntax603\")\n        let swiftSyntaxGenericTestSupportModule = self.createSwiftModule(name: \"_SwiftSyntaxGenericTestSupport\")\n        let swiftLibraryPluginProviderCShimsModule = self.createSwiftModule(name: \"_SwiftLibraryPluginProviderCShims\")\n\n        // Core modules\n        let swiftSyntaxModule = self.createSwiftModule(name: \"SwiftSyntax\")\n        let swiftDiagnosticsModule = self.createSwiftModule(name: \"SwiftDiagnostics\")\n        let swiftParserModule = self.createSwiftModule(name: \"SwiftParser\")\n        let swiftBasicFormatModule = self.createSwiftModule(name: \"SwiftBasicFormat\")\n        let swiftOperatorsModule = self.createSwiftModule(name: \"SwiftOperators\")\n        let swiftParserDiagnosticsModule = self.createSwiftModule(name: \"SwiftParserDiagnostics\")\n        let swiftSyntaxBuilderModule = self.createSwiftModule(name: \"SwiftSyntaxBuilder\")\n\n        // Advanced modules\n        let swiftIDEUtilsModule = self.createSwiftModule(name: \"SwiftIDEUtils\")\n        let swiftIfConfigModule = self.createSwiftModule(name: \"SwiftIfConfig\")\n        let swiftLexicalLookupModule = self.createSwiftModule(name: \"SwiftLexicalLookup\")\n        let swiftRefactorModule = self.createSwiftModule(name: \"SwiftRefactor\")\n        let swiftSyntaxMacrosModule = self.createSwiftModule(name: \"SwiftSyntaxMacros\")\n        let swiftSyntaxMacroExpansionModule = self.createSwiftModule(name: \"SwiftSyntaxMacroExpansion\")\n\n        // Compiler/Plugin modules\n        let swiftCompilerPluginMessageHandlingModule = self\n            .createSwiftModule(name: \"SwiftCompilerPluginMessageHandling\")\n        let swiftCompilerPluginModule = self.createSwiftModule(name: \"SwiftCompilerPlugin\")\n        let swiftLibraryPluginProviderModule = self.createSwiftModule(name: \"SwiftLibraryPluginProvider\")\n\n        // Test support modules\n        let swiftSyntaxMacrosGenericTestSupportModule = self\n            .createSwiftModule(name: \"SwiftSyntaxMacrosGenericTestSupport\")\n        let swiftSyntaxMacrosTestSupportModule = self.createSwiftModule(name: \"SwiftSyntaxMacrosTestSupport\")\n\n        // MARK: - Create products (18 products)\n\n        let swiftSyntaxProduct = try Product(\n            package: identity,\n            name: \"SwiftSyntax\",\n            type: .library(.automatic),\n            modules: [swiftSyntaxModule]\n        )\n        let swiftDiagnosticsProduct = try Product(\n            package: identity,\n            name: \"SwiftDiagnostics\",\n            type: .library(.automatic),\n            modules: [swiftDiagnosticsModule]\n        )\n        let swiftParserProduct = try Product(\n            package: identity,\n            name: \"SwiftParser\",\n            type: .library(.automatic),\n            modules: [swiftParserModule]\n        )\n        let swiftBasicFormatProduct = try Product(\n            package: identity,\n            name: \"SwiftBasicFormat\",\n            type: .library(.automatic),\n            modules: [swiftBasicFormatModule]\n        )\n        let swiftOperatorsProduct = try Product(\n            package: identity,\n            name: \"SwiftOperators\",\n            type: .library(.automatic),\n            modules: [swiftOperatorsModule]\n        )\n        let swiftParserDiagnosticsProduct = try Product(\n            package: identity,\n            name: \"SwiftParserDiagnostics\",\n            type: .library(.automatic),\n            modules: [swiftParserDiagnosticsModule]\n        )\n        let swiftSyntaxBuilderProduct = try Product(\n            package: identity,\n            name: \"SwiftSyntaxBuilder\",\n            type: .library(.automatic),\n            modules: [swiftSyntaxBuilderModule]\n        )\n        let swiftIDEUtilsProduct = try Product(\n            package: identity,\n            name: \"SwiftIDEUtils\",\n            type: .library(.automatic),\n            modules: [swiftIDEUtilsModule]\n        )\n        let swiftIfConfigProduct = try Product(\n            package: identity,\n            name: \"SwiftIfConfig\",\n            type: .library(.automatic),\n            modules: [swiftIfConfigModule]\n        )\n        let swiftLexicalLookupProduct = try Product(\n            package: identity,\n            name: \"SwiftLexicalLookup\",\n            type: .library(.automatic),\n            modules: [swiftLexicalLookupModule]\n        )\n        let swiftRefactorProduct = try Product(\n            package: identity,\n            name: \"SwiftRefactor\",\n            type: .library(.automatic),\n            modules: [swiftRefactorModule]\n        )\n        let swiftSyntaxMacrosProduct = try Product(\n            package: identity,\n            name: \"SwiftSyntaxMacros\",\n            type: .library(.automatic),\n            modules: [swiftSyntaxMacrosModule]\n        )\n        let swiftSyntaxMacroExpansionProduct = try Product(\n            package: identity,\n            name: \"SwiftSyntaxMacroExpansion\",\n            type: .library(.automatic),\n            modules: [swiftSyntaxMacroExpansionModule]\n        )\n        let swiftCompilerPluginProduct = try Product(\n            package: identity,\n            name: \"SwiftCompilerPlugin\",\n            type: .library(.automatic),\n            modules: [swiftCompilerPluginModule]\n        )\n        let swiftCompilerPluginMessageHandlingProduct = try Product(\n            package: identity,\n            name: \"_SwiftCompilerPluginMessageHandling\",\n            type: .library(.automatic),\n            modules: [swiftCompilerPluginMessageHandlingModule]\n        )\n        let swiftLibraryPluginProviderProduct = try Product(\n            package: identity,\n            name: \"_SwiftLibraryPluginProvider\",\n            type: .library(.automatic),\n            modules: [swiftLibraryPluginProviderModule]\n        )\n        let swiftSyntaxMacrosGenericTestSupportProduct = try Product(\n            package: identity,\n            name: \"SwiftSyntaxMacrosGenericTestSupport\",\n            type: .library(.automatic),\n            modules: [swiftSyntaxMacrosGenericTestSupportModule]\n        )\n        let swiftSyntaxMacrosTestSupportProduct = try Product(\n            package: identity,\n            name: \"SwiftSyntaxMacrosTestSupport\",\n            type: .library(.automatic),\n            modules: [swiftSyntaxMacrosTestSupportModule]\n        )\n\n        // MARK: - Create package\n\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-syntax\",\n            path: \"/swift-syntax\",\n            modules: [\n                swiftSyntaxCShimsModule, swiftSyntax509Module, swiftSyntax510Module, swiftSyntax600Module,\n                swiftSyntax601Module, swiftSyntax602Module, swiftSyntax603Module, swiftSyntaxGenericTestSupportModule,\n                swiftLibraryPluginProviderCShimsModule, swiftSyntaxModule, swiftDiagnosticsModule, swiftParserModule,\n                swiftBasicFormatModule, swiftOperatorsModule, swiftParserDiagnosticsModule, swiftSyntaxBuilderModule,\n                swiftIDEUtilsModule, swiftIfConfigModule, swiftLexicalLookupModule, swiftRefactorModule,\n                swiftSyntaxMacrosModule, swiftSyntaxMacroExpansionModule, swiftCompilerPluginMessageHandlingModule,\n                swiftCompilerPluginModule, swiftLibraryPluginProviderModule, swiftSyntaxMacrosGenericTestSupportModule,\n                swiftSyntaxMacrosTestSupportModule,\n            ],\n            products: [\n                swiftSyntaxProduct, swiftDiagnosticsProduct, swiftParserProduct, swiftBasicFormatProduct,\n                swiftOperatorsProduct, swiftParserDiagnosticsProduct, swiftSyntaxBuilderProduct, swiftIDEUtilsProduct,\n                swiftIfConfigProduct, swiftLexicalLookupProduct, swiftRefactorProduct, swiftSyntaxMacrosProduct,\n                swiftSyntaxMacroExpansionProduct, swiftCompilerPluginProduct, swiftCompilerPluginMessageHandlingProduct,\n                swiftLibraryPluginProviderProduct, swiftSyntaxMacrosGenericTestSupportProduct,\n                swiftSyntaxMacrosTestSupportProduct,\n            ]\n        )\n\n        // MARK: - Create resolved modules with dependencies\n\n        let resolvedSwiftSyntaxCShimsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntaxCShimsModule\n        )\n        let resolvedSwiftSyntax509Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntax509Module\n        )\n        let resolvedSwiftSyntax510Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntax510Module\n        )\n        let resolvedSwiftSyntax600Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntax600Module\n        )\n        let resolvedSwiftSyntax601Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntax601Module\n        )\n        let resolvedSwiftSyntax602Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntax602Module\n        )\n        let resolvedSwiftSyntax603Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntax603Module\n        )\n        let resolvedSwiftSyntaxGenericTestSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntaxGenericTestSupportModule\n        )\n        let resolvedSwiftLibraryPluginProviderCShimsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftLibraryPluginProviderCShimsModule\n        )\n\n        let resolvedSwiftSyntaxModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntaxModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxCShimsModule, conditions: []),\n                .module(resolvedSwiftSyntax509Module, conditions: []),\n                .module(resolvedSwiftSyntax510Module, conditions: []),\n                .module(resolvedSwiftSyntax600Module, conditions: []),\n                .module(resolvedSwiftSyntax601Module, conditions: []),\n                .module(resolvedSwiftSyntax602Module, conditions: []),\n                .module(resolvedSwiftSyntax603Module, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftDiagnosticsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftDiagnosticsModule,\n            dependencies: [.module(resolvedSwiftSyntaxModule, conditions: [])]\n        )\n\n        let resolvedSwiftParserModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftParserModule,\n            dependencies: [.module(resolvedSwiftSyntaxModule, conditions: [])]\n        )\n\n        let resolvedSwiftBasicFormatModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftBasicFormatModule,\n            dependencies: [.module(resolvedSwiftSyntaxModule, conditions: [])]\n        )\n\n        let resolvedSwiftOperatorsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftOperatorsModule,\n            dependencies: [\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftParserDiagnosticsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftParserDiagnosticsModule,\n            dependencies: [\n                .module(resolvedSwiftBasicFormatModule, conditions: []),\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftSyntaxBuilderModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntaxBuilderModule,\n            dependencies: [\n                .module(resolvedSwiftBasicFormatModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftParserDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftIDEUtilsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftIDEUtilsModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftIfConfigModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftIfConfigModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n                .module(resolvedSwiftSyntaxBuilderModule, conditions: []),\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftOperatorsModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftLexicalLookupModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftLexicalLookupModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n                .module(resolvedSwiftIfConfigModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftRefactorModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftRefactorModule,\n            dependencies: [\n                .module(resolvedSwiftBasicFormatModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n                .module(resolvedSwiftSyntaxBuilderModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftSyntaxMacrosModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntaxMacrosModule,\n            dependencies: [\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftIfConfigModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n                .module(resolvedSwiftSyntaxBuilderModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftSyntaxMacroExpansionModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntaxMacroExpansionModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n                .module(resolvedSwiftSyntaxBuilderModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacrosModule, conditions: []),\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftOperatorsModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftCompilerPluginMessageHandlingModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftCompilerPluginMessageHandlingModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxCShimsModule, conditions: []),\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftOperatorsModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacrosModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacroExpansionModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftCompilerPluginModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftCompilerPluginModule,\n            dependencies: [\n                .module(resolvedSwiftCompilerPluginMessageHandlingModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacrosModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftLibraryPluginProviderModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftLibraryPluginProviderModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxMacrosModule, conditions: []),\n                .module(resolvedSwiftCompilerPluginMessageHandlingModule, conditions: []),\n                .module(resolvedSwiftLibraryPluginProviderCShimsModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftSyntaxMacrosGenericTestSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntaxMacrosGenericTestSupportModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxGenericTestSupportModule, conditions: []),\n                .module(resolvedSwiftDiagnosticsModule, conditions: []),\n                .module(resolvedSwiftIDEUtilsModule, conditions: []),\n                .module(resolvedSwiftIfConfigModule, conditions: []),\n                .module(resolvedSwiftParserModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacrosModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacroExpansionModule, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftSyntaxMacrosTestSupportModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftSyntaxMacrosTestSupportModule,\n            dependencies: [\n                .module(resolvedSwiftSyntaxModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacroExpansionModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacrosModule, conditions: []),\n                .module(resolvedSwiftSyntaxMacrosGenericTestSupportModule, conditions: []),\n            ]\n        )\n\n        // MARK: - Create resolved products\n\n        let resolvedSwiftSyntaxProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftSyntaxProduct,\n            modules: IdentifiableSet([resolvedSwiftSyntaxModule])\n        )\n        let resolvedSwiftDiagnosticsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftDiagnosticsProduct,\n            modules: IdentifiableSet([resolvedSwiftDiagnosticsModule])\n        )\n        let resolvedSwiftParserProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftParserProduct,\n            modules: IdentifiableSet([resolvedSwiftParserModule])\n        )\n        let resolvedSwiftBasicFormatProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftBasicFormatProduct,\n            modules: IdentifiableSet([resolvedSwiftBasicFormatModule])\n        )\n        let resolvedSwiftOperatorsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftOperatorsProduct,\n            modules: IdentifiableSet([resolvedSwiftOperatorsModule])\n        )\n        let resolvedSwiftParserDiagnosticsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftParserDiagnosticsProduct,\n            modules: IdentifiableSet([resolvedSwiftParserDiagnosticsModule])\n        )\n        let resolvedSwiftSyntaxBuilderProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftSyntaxBuilderProduct,\n            modules: IdentifiableSet([resolvedSwiftSyntaxBuilderModule])\n        )\n        let resolvedSwiftIDEUtilsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftIDEUtilsProduct,\n            modules: IdentifiableSet([resolvedSwiftIDEUtilsModule])\n        )\n        let resolvedSwiftIfConfigProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftIfConfigProduct,\n            modules: IdentifiableSet([resolvedSwiftIfConfigModule])\n        )\n        let resolvedSwiftLexicalLookupProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftLexicalLookupProduct,\n            modules: IdentifiableSet([resolvedSwiftLexicalLookupModule])\n        )\n        let resolvedSwiftRefactorProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftRefactorProduct,\n            modules: IdentifiableSet([resolvedSwiftRefactorModule])\n        )\n        let resolvedSwiftSyntaxMacrosProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftSyntaxMacrosProduct,\n            modules: IdentifiableSet([resolvedSwiftSyntaxMacrosModule])\n        )\n        let resolvedSwiftSyntaxMacroExpansionProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftSyntaxMacroExpansionProduct,\n            modules: IdentifiableSet([resolvedSwiftSyntaxMacroExpansionModule])\n        )\n        let resolvedSwiftCompilerPluginProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftCompilerPluginProduct,\n            modules: IdentifiableSet([resolvedSwiftCompilerPluginModule])\n        )\n        let resolvedSwiftCompilerPluginMessageHandlingProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftCompilerPluginMessageHandlingProduct,\n            modules: IdentifiableSet([resolvedSwiftCompilerPluginMessageHandlingModule])\n        )\n        let resolvedSwiftLibraryPluginProviderProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftLibraryPluginProviderProduct,\n            modules: IdentifiableSet([resolvedSwiftLibraryPluginProviderModule])\n        )\n        let resolvedSwiftSyntaxMacrosGenericTestSupportProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftSyntaxMacrosGenericTestSupportProduct,\n            modules: IdentifiableSet([resolvedSwiftSyntaxMacrosGenericTestSupportModule])\n        )\n        let resolvedSwiftSyntaxMacrosTestSupportProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftSyntaxMacrosTestSupportProduct,\n            modules: IdentifiableSet([resolvedSwiftSyntaxMacrosTestSupportModule])\n        )\n\n        // MARK: - Create resolved package\n\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedSwiftSyntaxCShimsModule, resolvedSwiftSyntax509Module, resolvedSwiftSyntax510Module,\n                resolvedSwiftSyntax600Module, resolvedSwiftSyntax601Module, resolvedSwiftSyntax602Module,\n                resolvedSwiftSyntax603Module, resolvedSwiftSyntaxGenericTestSupportModule,\n                resolvedSwiftLibraryPluginProviderCShimsModule,\n                resolvedSwiftSyntaxModule, resolvedSwiftDiagnosticsModule, resolvedSwiftParserModule,\n                resolvedSwiftBasicFormatModule, resolvedSwiftOperatorsModule, resolvedSwiftParserDiagnosticsModule,\n                resolvedSwiftSyntaxBuilderModule, resolvedSwiftIDEUtilsModule, resolvedSwiftIfConfigModule,\n                resolvedSwiftLexicalLookupModule, resolvedSwiftRefactorModule, resolvedSwiftSyntaxMacrosModule,\n                resolvedSwiftSyntaxMacroExpansionModule, resolvedSwiftCompilerPluginMessageHandlingModule,\n                resolvedSwiftCompilerPluginModule, resolvedSwiftLibraryPluginProviderModule,\n                resolvedSwiftSyntaxMacrosGenericTestSupportModule, resolvedSwiftSyntaxMacrosTestSupportModule,\n            ]),\n            products: [\n                resolvedSwiftSyntaxProduct, resolvedSwiftDiagnosticsProduct, resolvedSwiftParserProduct,\n                resolvedSwiftBasicFormatProduct, resolvedSwiftOperatorsProduct, resolvedSwiftParserDiagnosticsProduct,\n                resolvedSwiftSyntaxBuilderProduct, resolvedSwiftIDEUtilsProduct, resolvedSwiftIfConfigProduct,\n                resolvedSwiftLexicalLookupProduct, resolvedSwiftRefactorProduct, resolvedSwiftSyntaxMacrosProduct,\n                resolvedSwiftSyntaxMacroExpansionProduct, resolvedSwiftCompilerPluginProduct,\n                resolvedSwiftCompilerPluginMessageHandlingProduct, resolvedSwiftLibraryPluginProviderProduct,\n                resolvedSwiftSyntaxMacrosGenericTestSupportProduct, resolvedSwiftSyntaxMacrosTestSupportProduct,\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-syntax.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                swiftSyntaxCShimsModule, swiftSyntax509Module, swiftSyntax510Module, swiftSyntax600Module,\n                swiftSyntax601Module, swiftSyntax602Module, swiftSyntax603Module, swiftSyntaxGenericTestSupportModule,\n                swiftLibraryPluginProviderCShimsModule, swiftSyntaxModule, swiftDiagnosticsModule, swiftParserModule,\n                swiftBasicFormatModule, swiftOperatorsModule, swiftParserDiagnosticsModule, swiftSyntaxBuilderModule,\n                swiftIDEUtilsModule, swiftIfConfigModule, swiftLexicalLookupModule, swiftRefactorModule,\n                swiftSyntaxMacrosModule, swiftSyntaxMacroExpansionModule, swiftCompilerPluginMessageHandlingModule,\n                swiftCompilerPluginModule, swiftLibraryPluginProviderModule, swiftSyntaxMacrosGenericTestSupportModule,\n                swiftSyntaxMacrosTestSupportModule,\n            ],\n            products: [\n                swiftSyntaxProduct, swiftDiagnosticsProduct, swiftParserProduct, swiftBasicFormatProduct,\n                swiftOperatorsProduct, swiftParserDiagnosticsProduct, swiftSyntaxBuilderProduct, swiftIDEUtilsProduct,\n                swiftIfConfigProduct, swiftLexicalLookupProduct, swiftRefactorProduct, swiftSyntaxMacrosProduct,\n                swiftSyntaxMacroExpansionProduct, swiftCompilerPluginProduct, swiftCompilerPluginMessageHandlingProduct,\n                swiftLibraryPluginProviderProduct, swiftSyntaxMacrosGenericTestSupportProduct,\n                swiftSyntaxMacrosTestSupportProduct,\n            ],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedSwiftSyntaxCShimsModule, resolvedSwiftSyntax509Module, resolvedSwiftSyntax510Module,\n                resolvedSwiftSyntax600Module, resolvedSwiftSyntax601Module, resolvedSwiftSyntax602Module,\n                resolvedSwiftSyntax603Module, resolvedSwiftSyntaxGenericTestSupportModule,\n                resolvedSwiftLibraryPluginProviderCShimsModule,\n                resolvedSwiftSyntaxModule, resolvedSwiftDiagnosticsModule, resolvedSwiftParserModule,\n                resolvedSwiftBasicFormatModule, resolvedSwiftOperatorsModule, resolvedSwiftParserDiagnosticsModule,\n                resolvedSwiftSyntaxBuilderModule, resolvedSwiftIDEUtilsModule, resolvedSwiftIfConfigModule,\n                resolvedSwiftLexicalLookupModule, resolvedSwiftRefactorModule, resolvedSwiftSyntaxMacrosModule,\n                resolvedSwiftSyntaxMacroExpansionModule, resolvedSwiftCompilerPluginMessageHandlingModule,\n                resolvedSwiftCompilerPluginModule, resolvedSwiftLibraryPluginProviderModule,\n                resolvedSwiftSyntaxMacrosGenericTestSupportModule, resolvedSwiftSyntaxMacrosTestSupportModule,\n            ],\n            resolvedProducts: [\n                resolvedSwiftSyntaxProduct, resolvedSwiftDiagnosticsProduct, resolvedSwiftParserProduct,\n                resolvedSwiftBasicFormatProduct, resolvedSwiftOperatorsProduct, resolvedSwiftParserDiagnosticsProduct,\n                resolvedSwiftSyntaxBuilderProduct, resolvedSwiftIDEUtilsProduct, resolvedSwiftIfConfigProduct,\n                resolvedSwiftLexicalLookupProduct, resolvedSwiftRefactorProduct, resolvedSwiftSyntaxMacrosProduct,\n                resolvedSwiftSyntaxMacroExpansionProduct, resolvedSwiftCompilerPluginProduct,\n                resolvedSwiftCompilerPluginMessageHandlingProduct, resolvedSwiftLibraryPluginProviderProduct,\n                resolvedSwiftSyntaxMacrosGenericTestSupportProduct, resolvedSwiftSyntaxMacrosTestSupportProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SwiftlyFixtures/SBOMSwiftlyCollectionsPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-collections Package\n\n    static func createSwiftCollectionsPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-collections\")\n\n        // Modules\n        let internalCollectionsUtilitiesModule = self.createSwiftModule(name: \"InternalCollectionsUtilities\")\n        let dequeModule = self.createSwiftModule(name: \"DequeModule\")\n        let orderedCollectionsModule = self.createSwiftModule(name: \"OrderedCollections\")\n\n        // Products\n        let dequeProduct = try Product(\n            package: identity,\n            name: \"DequeModule\",\n            type: .library(.automatic),\n            modules: [dequeModule]\n        )\n\n        let orderedCollectionsProduct = try Product(\n            package: identity,\n            name: \"OrderedCollections\",\n            type: .library(.automatic),\n            modules: [orderedCollectionsModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-collections\",\n            path: \"/swift-collections\",\n            modules: [internalCollectionsUtilitiesModule, dequeModule, orderedCollectionsModule],\n            products: [dequeProduct, orderedCollectionsProduct]\n        )\n\n        // Resolved modules\n        let resolvedInternalCollectionsUtilitiesModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: internalCollectionsUtilitiesModule\n        )\n\n        let resolvedDequeModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: dequeModule,\n            dependencies: [\n                .module(resolvedInternalCollectionsUtilitiesModule, conditions: []),\n            ]\n        )\n\n        let resolvedOrderedCollectionsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: orderedCollectionsModule,\n            dependencies: [\n                .module(resolvedInternalCollectionsUtilitiesModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedDequeProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: dequeProduct,\n            modules: IdentifiableSet([resolvedDequeModule])\n        )\n\n        let resolvedOrderedCollectionsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: orderedCollectionsProduct,\n            modules: IdentifiableSet([resolvedOrderedCollectionsModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedInternalCollectionsUtilitiesModule,\n                resolvedDequeModule,\n                resolvedOrderedCollectionsModule,\n            ]),\n            products: [resolvedDequeProduct, resolvedOrderedCollectionsProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-collections.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [internalCollectionsUtilitiesModule, dequeModule, orderedCollectionsModule],\n            products: [dequeProduct, orderedCollectionsProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedInternalCollectionsUtilitiesModule,\n                resolvedDequeModule,\n                resolvedOrderedCollectionsModule,\n            ],\n            resolvedProducts: [resolvedDequeProduct, resolvedOrderedCollectionsProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-numerics Package\n\n    static func createSwiftNumericsPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-numerics\")\n\n        // Modules\n        let numericsShimsModule = self.createSwiftModule(name: \"_NumericsShims\")\n        let realModule = self.createSwiftModule(name: \"RealModule\")\n\n        // Products\n        let realModuleProduct = try Product(\n            package: identity,\n            name: \"RealModule\",\n            type: .library(.automatic),\n            modules: [realModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-numerics\",\n            path: \"/swift-numerics\",\n            modules: [numericsShimsModule, realModule],\n            products: [realModuleProduct]\n        )\n\n        // Resolved modules\n        let resolvedNumericsShimsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: numericsShimsModule\n        )\n\n        let resolvedRealModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: realModule,\n            dependencies: [\n                .module(resolvedNumericsShimsModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedRealModuleProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: realModuleProduct,\n            modules: IdentifiableSet([resolvedRealModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedNumericsShimsModule, resolvedRealModule]),\n            products: [resolvedRealModuleProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-numerics.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [numericsShimsModule, realModule],\n            products: [realModuleProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedNumericsShimsModule, resolvedRealModule],\n            resolvedProducts: [resolvedRealModuleProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-algorithms Package\n\n    static func createSwiftAlgorithmsPackage(\n        realModuleProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-algorithms\")\n\n        // Modules\n        let algorithmsModule = self.createSwiftModule(name: \"Algorithms\")\n\n        // Products\n        let algorithmsProduct = try Product(\n            package: identity,\n            name: \"Algorithms\",\n            type: .library(.automatic),\n            modules: [algorithmsModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-algorithms\",\n            path: \"/swift-algorithms\",\n            modules: [algorithmsModule],\n            products: [algorithmsProduct]\n        )\n\n        // Resolved modules\n        let resolvedAlgorithmsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: algorithmsModule,\n            dependencies: [\n                .product(realModuleProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedAlgorithmsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: algorithmsProduct,\n            modules: IdentifiableSet([resolvedAlgorithmsModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedAlgorithmsModule]),\n            products: [resolvedAlgorithmsProduct],\n            dependencies: [PackageIdentity.plain(\"swift-numerics\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-algorithms.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [algorithmsModule],\n            products: [algorithmsProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedAlgorithmsModule],\n            resolvedProducts: [resolvedAlgorithmsProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-atomics Package\n\n    static func createSwiftAtomicsPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-atomics\")\n\n        // Modules\n        let atomicsShimsModule = self.createSwiftModule(name: \"_AtomicsShims\")\n        let atomicsModule = self.createSwiftModule(name: \"Atomics\")\n\n        // Products\n        let atomicsProduct = try Product(\n            package: identity,\n            name: \"Atomics\",\n            type: .library(.automatic),\n            modules: [atomicsModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-atomics\",\n            path: \"/swift-atomics\",\n            modules: [atomicsShimsModule, atomicsModule],\n            products: [atomicsProduct]\n        )\n\n        // Resolved modules\n        let resolvedAtomicsShimsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: atomicsShimsModule\n        )\n\n        let resolvedAtomicsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: atomicsModule,\n            dependencies: [\n                .module(resolvedAtomicsShimsModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedAtomicsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: atomicsProduct,\n            modules: IdentifiableSet([resolvedAtomicsModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedAtomicsShimsModule, resolvedAtomicsModule]),\n            products: [resolvedAtomicsProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-atomics.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [atomicsShimsModule, atomicsModule],\n            products: [atomicsProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedAtomicsShimsModule, resolvedAtomicsModule],\n            resolvedProducts: [resolvedAtomicsProduct],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SwiftlyFixtures/SBOMSwiftlyFoundationPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-system Package\n\n    static func createSwiftSystemPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-system\")\n\n        // Modules\n        let cSystemModule = self.createSwiftModule(name: \"CSystem\")\n        let systemPackageModule = self.createSwiftModule(name: \"SystemPackage\")\n\n        // Products\n        let systemPackageProduct = try Product(\n            package: identity,\n            name: \"SystemPackage\",\n            type: .library(.automatic),\n            modules: [systemPackageModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-system\",\n            path: \"/swift-system\",\n            modules: [cSystemModule, systemPackageModule],\n            products: [systemPackageProduct]\n        )\n\n        // Resolved modules\n        let resolvedCSystemModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cSystemModule\n        )\n\n        let resolvedSystemPackageModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: systemPackageModule,\n            dependencies: [\n                .module(resolvedCSystemModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedSystemPackageProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: systemPackageProduct,\n            modules: IdentifiableSet([resolvedSystemPackageModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedCSystemModule, resolvedSystemPackageModule]),\n            products: [resolvedSystemPackageProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-system\"))\n        )\n\n        return (\n            package: package,\n            modules: [cSystemModule, systemPackageModule],\n            products: [systemPackageProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedCSystemModule, resolvedSystemPackageModule],\n            resolvedProducts: [resolvedSystemPackageProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-subprocess Package\n\n    static func createSwiftSubprocessPackage(\n        systemPackageProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-subprocess\")\n\n        // Modules\n        let subprocessCShimsModule = self.createSwiftModule(name: \"_SubprocessCShims\")\n        let subprocessModule = self.createSwiftModule(name: \"Subprocess\")\n\n        // Products\n        let subprocessProduct = try Product(\n            package: identity,\n            name: \"Subprocess\",\n            type: .library(.automatic),\n            modules: [subprocessModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"Subprocess\",\n            path: \"/swift-subprocess\",\n            modules: [subprocessCShimsModule, subprocessModule],\n            products: [subprocessProduct]\n        )\n\n        // Resolved modules\n        let resolvedSubprocessCShimsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: subprocessCShimsModule\n        )\n\n        let resolvedSubprocessModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: subprocessModule,\n            dependencies: [\n                .module(resolvedSubprocessCShimsModule, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedSubprocessProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: subprocessProduct,\n            modules: IdentifiableSet([resolvedSubprocessModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedSubprocessCShimsModule, resolvedSubprocessModule]),\n            products: [resolvedSubprocessProduct],\n            dependencies: [PackageIdentity.plain(\"swift-system\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swiftlang/swift-subprocess\"))\n        )\n\n        return (\n            package: package,\n            modules: [subprocessCShimsModule, subprocessModule],\n            products: [subprocessProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedSubprocessCShimsModule, resolvedSubprocessModule],\n            resolvedProducts: [resolvedSubprocessProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-argument-parser Package\n\n    static func createSwiftArgumentParserPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-argument-parser\")\n\n        // Modules\n        let argumentParserToolInfoModule = self.createSwiftModule(name: \"ArgumentParserToolInfo\")\n        let argumentParserModule = self.createSwiftModule(name: \"ArgumentParser\")\n\n        // Products\n        let argumentParserProduct = try Product(\n            package: identity,\n            name: \"ArgumentParser\",\n            type: .library(.automatic),\n            modules: [argumentParserModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-argument-parser\",\n            path: \"/swift-argument-parser\",\n            modules: [argumentParserToolInfoModule, argumentParserModule],\n            products: [argumentParserProduct]\n        )\n\n        // Resolved modules\n        let resolvedArgumentParserToolInfoModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: argumentParserToolInfoModule\n        )\n\n        let resolvedArgumentParserModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: argumentParserModule,\n            dependencies: [\n                .module(resolvedArgumentParserToolInfoModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedArgumentParserProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: argumentParserProduct,\n            modules: IdentifiableSet([resolvedArgumentParserModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedArgumentParserToolInfoModule, resolvedArgumentParserModule]),\n            products: [resolvedArgumentParserProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-argument-parser\"))\n        )\n\n        return (\n            package: package,\n            modules: [argumentParserToolInfoModule, argumentParserModule],\n            products: [argumentParserProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedArgumentParserToolInfoModule, resolvedArgumentParserModule],\n            resolvedProducts: [resolvedArgumentParserProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-tools-support-core Package\n\n    static func createSwiftToolsSupportCorePackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-tools-support-core\")\n\n        // Modules\n        let tscClibcModule = self.createSwiftModule(name: \"TSCclibc\")\n        let tscLibcModule = self.createSwiftModule(name: \"TSCLibc\")\n        let tscBasicModule = self.createSwiftModule(name: \"TSCBasic\")\n        let tscUtilityModule = self.createSwiftModule(name: \"TSCUtility\")\n\n        // Products\n        let swiftToolsSupportAutoProduct = try Product(\n            package: identity,\n            name: \"SwiftToolsSupport-auto\",\n            type: .library(.automatic),\n            modules: [tscBasicModule, tscUtilityModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-tools-support-core\",\n            path: \"/swift-tools-support-core\",\n            modules: [tscClibcModule, tscLibcModule, tscBasicModule, tscUtilityModule],\n            products: [swiftToolsSupportAutoProduct]\n        )\n\n        // Resolved modules\n        let resolvedTSCClibcModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscClibcModule\n        )\n\n        let resolvedTSCLibcModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscLibcModule\n        )\n\n        let resolvedTSCBasicModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscBasicModule,\n            dependencies: [\n                .module(resolvedTSCLibcModule, conditions: []),\n                .module(resolvedTSCClibcModule, conditions: []),\n            ]\n        )\n\n        let resolvedTSCUtilityModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tscUtilityModule,\n            dependencies: [\n                .module(resolvedTSCBasicModule, conditions: []),\n                .module(resolvedTSCClibcModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedSwiftToolsSupportAutoProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftToolsSupportAutoProduct,\n            modules: IdentifiableSet([resolvedTSCBasicModule, resolvedTSCUtilityModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedTSCClibcModule,\n                resolvedTSCLibcModule,\n                resolvedTSCBasicModule,\n                resolvedTSCUtilityModule,\n            ]),\n            products: [resolvedSwiftToolsSupportAutoProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-tools-support-core.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [tscClibcModule, tscLibcModule, tscBasicModule, tscUtilityModule],\n            products: [swiftToolsSupportAutoProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedTSCClibcModule,\n                resolvedTSCLibcModule,\n                resolvedTSCBasicModule,\n                resolvedTSCUtilityModule,\n            ],\n            resolvedProducts: [resolvedSwiftToolsSupportAutoProduct],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SwiftlyFixtures/SBOMSwiftlyNIOPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-nio Package (Core)\n\n    static func createSwiftNIOPackage(\n        atomicsProduct: ResolvedProduct,\n        dequeProduct: ResolvedProduct,\n        systemPackageProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-nio\")\n\n        // C modules\n        let cnioAtomicsModule = self.createSwiftModule(name: \"CNIOAtomics\")\n        let cnioDarwinModule = self.createSwiftModule(name: \"CNIODarwin\")\n        let cnioLinuxModule = self.createSwiftModule(name: \"CNIOLinux\")\n        let cnioWindowsModule = self.createSwiftModule(name: \"CNIOWindows\")\n        let cnioWASIModule = self.createSwiftModule(name: \"CNIOWASI\")\n        let cnioPosixModule = self.createSwiftModule(name: \"CNIOPosix\")\n        let cnioLLHTTPModule = self.createSwiftModule(name: \"CNIOLLHTTP\")\n\n        // Internal modules\n        let nioBase64Module = self.createSwiftModule(name: \"_NIOBase64\")\n        let nioDataStructuresModule = self.createSwiftModule(name: \"_NIODataStructures\")\n        let nioFileSystemModule = self.createSwiftModule(name: \"_NIOFileSystem\")\n\n        // Core modules\n        let nioConcurrencyHelpersModule = self.createSwiftModule(name: \"NIOConcurrencyHelpers\")\n        let nioCoreModule = self.createSwiftModule(name: \"NIOCore\")\n        let nioEmbeddedModule = self.createSwiftModule(name: \"NIOEmbedded\")\n        let nioPosixModule = self.createSwiftModule(name: \"NIOPosix\")\n        let nioModule = self.createSwiftModule(name: \"NIO\")\n        let nioTLSModule = self.createSwiftModule(name: \"NIOTLS\")\n        let nioHTTP1Module = self.createSwiftModule(name: \"NIOHTTP1\")\n        let nioFoundationCompatModule = self.createSwiftModule(name: \"NIOFoundationCompat\")\n        let nioFileSystemPublicModule = self.createSwiftModule(name: \"NIOFileSystem\")\n\n        // Products\n        let nioConcurrencyHelpersProduct = try Product(\n            package: identity,\n            name: \"NIOConcurrencyHelpers\",\n            type: .library(.automatic),\n            modules: [nioConcurrencyHelpersModule]\n        )\n\n        let nioCoreProduct = try Product(\n            package: identity,\n            name: \"NIOCore\",\n            type: .library(.automatic),\n            modules: [nioCoreModule]\n        )\n\n        let nioProduct = try Product(\n            package: identity,\n            name: \"NIO\",\n            type: .library(.automatic),\n            modules: [nioModule]\n        )\n\n        let nioPosixProduct = try Product(\n            package: identity,\n            name: \"NIOPosix\",\n            type: .library(.automatic),\n            modules: [nioPosixModule]\n        )\n\n        let nioTLSProduct = try Product(\n            package: identity,\n            name: \"NIOTLS\",\n            type: .library(.automatic),\n            modules: [nioTLSModule]\n        )\n\n        let nioHTTP1Product = try Product(\n            package: identity,\n            name: \"NIOHTTP1\",\n            type: .library(.automatic),\n            modules: [nioHTTP1Module]\n        )\n\n        let nioFoundationCompatProduct = try Product(\n            package: identity,\n            name: \"NIOFoundationCompat\",\n            type: .library(.automatic),\n            modules: [nioFoundationCompatModule]\n        )\n\n        let nioFileSystemProduct = try Product(\n            package: identity,\n            name: \"_NIOFileSystem\",\n            type: .library(.automatic),\n            modules: [nioFileSystemPublicModule, nioFileSystemModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-nio\",\n            path: \"/swift-nio\",\n            modules: [\n                cnioAtomicsModule, cnioDarwinModule, cnioLinuxModule, cnioWindowsModule,\n                cnioWASIModule, cnioPosixModule, cnioLLHTTPModule,\n                nioBase64Module, nioDataStructuresModule, nioFileSystemModule,\n                nioConcurrencyHelpersModule, nioCoreModule, nioEmbeddedModule,\n                nioPosixModule, nioModule, nioTLSModule, nioHTTP1Module,\n                nioFoundationCompatModule, nioFileSystemPublicModule,\n            ],\n            products: [\n                nioConcurrencyHelpersProduct, nioCoreProduct, nioProduct,\n                nioPosixProduct, nioTLSProduct, nioHTTP1Product,\n                nioFoundationCompatProduct, nioFileSystemProduct,\n            ]\n        )\n\n        // Resolved C modules\n        let resolvedCNIOAtomicsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioAtomicsModule\n        )\n\n        let resolvedCNIODarwinModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioDarwinModule\n        )\n\n        let resolvedCNIOLinuxModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioLinuxModule\n        )\n\n        let resolvedCNIOWindowsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioWindowsModule\n        )\n\n        let resolvedCNIOWASIModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioWASIModule\n        )\n\n        let resolvedCNIOPosixModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioPosixModule\n        )\n\n        let resolvedCNIOLLHTTPModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioLLHTTPModule\n        )\n\n        // Resolved internal modules\n        let resolvedNIOBase64Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioBase64Module\n        )\n\n        let resolvedNIODataStructuresModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioDataStructuresModule\n        )\n\n        // Resolved core modules\n        let resolvedNIOConcurrencyHelpersModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioConcurrencyHelpersModule,\n            dependencies: [\n                .module(resolvedCNIOAtomicsModule, conditions: []),\n            ]\n        )\n\n        let resolvedNIOCoreModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioCoreModule,\n            dependencies: [\n                .module(resolvedCNIOAtomicsModule, conditions: []),\n                .module(resolvedNIOConcurrencyHelpersModule, conditions: []),\n                .module(resolvedNIOBase64Module, conditions: []),\n                .module(resolvedCNIODarwinModule, conditions: []),\n                .module(resolvedCNIOLinuxModule, conditions: []),\n                .module(resolvedCNIOWindowsModule, conditions: []),\n                .module(resolvedCNIOWASIModule, conditions: []),\n                .module(resolvedNIODataStructuresModule, conditions: []),\n                .product(dequeProduct, conditions: []),\n                .product(atomicsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedNIOEmbeddedModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioEmbeddedModule,\n            dependencies: [\n                .module(resolvedNIOCoreModule, conditions: []),\n                .module(resolvedNIOConcurrencyHelpersModule, conditions: []),\n                .module(resolvedNIODataStructuresModule, conditions: []),\n                .product(atomicsProduct, conditions: []),\n                .product(dequeProduct, conditions: []),\n            ]\n        )\n\n        let resolvedNIOPosixModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioPosixModule,\n            dependencies: [\n                .module(resolvedCNIOLinuxModule, conditions: []),\n                .module(resolvedCNIODarwinModule, conditions: []),\n                .module(resolvedCNIOWindowsModule, conditions: []),\n                .module(resolvedNIOConcurrencyHelpersModule, conditions: []),\n                .module(resolvedNIOCoreModule, conditions: []),\n                .module(resolvedNIODataStructuresModule, conditions: []),\n                .module(resolvedCNIOPosixModule, conditions: []),\n                .product(atomicsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedNIOModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioModule,\n            dependencies: [\n                .module(resolvedNIOCoreModule, conditions: []),\n                .module(resolvedNIOEmbeddedModule, conditions: []),\n                .module(resolvedNIOPosixModule, conditions: []),\n            ]\n        )\n\n        let resolvedNIOTLSModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioTLSModule,\n            dependencies: [\n                .module(resolvedNIOModule, conditions: []),\n                .module(resolvedNIOCoreModule, conditions: []),\n                .product(dequeProduct, conditions: []),\n            ]\n        )\n\n        let resolvedNIOHTTP1Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioHTTP1Module,\n            dependencies: [\n                .module(resolvedNIOModule, conditions: []),\n                .module(resolvedNIOCoreModule, conditions: []),\n                .module(resolvedNIOConcurrencyHelpersModule, conditions: []),\n                .module(resolvedCNIOLLHTTPModule, conditions: []),\n                .product(dequeProduct, conditions: []),\n            ]\n        )\n\n        let resolvedNIOFoundationCompatModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioFoundationCompatModule,\n            dependencies: [\n                .module(resolvedNIOModule, conditions: []),\n                .module(resolvedNIOCoreModule, conditions: []),\n            ]\n        )\n\n        let resolvedNIOFileSystemModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioFileSystemModule,\n            dependencies: [\n                .module(resolvedNIOCoreModule, conditions: []),\n                .module(resolvedNIOPosixModule, conditions: []),\n                .module(resolvedCNIOLinuxModule, conditions: []),\n                .module(resolvedCNIODarwinModule, conditions: []),\n                .product(atomicsProduct, conditions: []),\n                .product(dequeProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n            ]\n        )\n\n        let resolvedNIOFileSystemPublicModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioFileSystemPublicModule,\n            dependencies: [\n                .module(resolvedNIOFileSystemModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedNIOConcurrencyHelpersProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioConcurrencyHelpersProduct,\n            modules: IdentifiableSet([resolvedNIOConcurrencyHelpersModule])\n        )\n\n        let resolvedNIOCoreProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioCoreProduct,\n            modules: IdentifiableSet([resolvedNIOCoreModule])\n        )\n\n        let resolvedNIOProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioProduct,\n            modules: IdentifiableSet([resolvedNIOModule])\n        )\n\n        let resolvedNIOPosixProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioPosixProduct,\n            modules: IdentifiableSet([resolvedNIOPosixModule])\n        )\n\n        let resolvedNIOTLSProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioTLSProduct,\n            modules: IdentifiableSet([resolvedNIOTLSModule])\n        )\n\n        let resolvedNIOHTTP1Product = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioHTTP1Product,\n            modules: IdentifiableSet([resolvedNIOHTTP1Module])\n        )\n\n        let resolvedNIOFoundationCompatProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioFoundationCompatProduct,\n            modules: IdentifiableSet([resolvedNIOFoundationCompatModule])\n        )\n\n        let resolvedNIOFileSystemProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioFileSystemProduct,\n            modules: IdentifiableSet([resolvedNIOFileSystemPublicModule, resolvedNIOFileSystemModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedCNIOAtomicsModule, resolvedCNIODarwinModule, resolvedCNIOLinuxModule,\n                resolvedCNIOWindowsModule, resolvedCNIOWASIModule, resolvedCNIOPosixModule,\n                resolvedCNIOLLHTTPModule, resolvedNIOBase64Module, resolvedNIODataStructuresModule,\n                resolvedNIOConcurrencyHelpersModule, resolvedNIOCoreModule, resolvedNIOEmbeddedModule,\n                resolvedNIOPosixModule, resolvedNIOModule, resolvedNIOTLSModule, resolvedNIOHTTP1Module,\n                resolvedNIOFoundationCompatModule, resolvedNIOFileSystemModule, resolvedNIOFileSystemPublicModule,\n            ]),\n            products: [\n                resolvedNIOConcurrencyHelpersProduct, resolvedNIOCoreProduct, resolvedNIOProduct,\n                resolvedNIOPosixProduct, resolvedNIOTLSProduct, resolvedNIOHTTP1Product,\n                resolvedNIOFoundationCompatProduct, resolvedNIOFileSystemProduct,\n            ],\n            dependencies: [\n                PackageIdentity.plain(\"swift-atomics\"),\n                PackageIdentity.plain(\"swift-collections\"),\n                PackageIdentity.plain(\"swift-system\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-nio.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                cnioAtomicsModule, cnioDarwinModule, cnioLinuxModule, cnioWindowsModule,\n                cnioWASIModule, cnioPosixModule, cnioLLHTTPModule,\n                nioBase64Module, nioDataStructuresModule, nioFileSystemModule,\n                nioConcurrencyHelpersModule, nioCoreModule, nioEmbeddedModule,\n                nioPosixModule, nioModule, nioTLSModule, nioHTTP1Module,\n                nioFoundationCompatModule, nioFileSystemPublicModule,\n            ],\n            products: [\n                nioConcurrencyHelpersProduct, nioCoreProduct, nioProduct,\n                nioPosixProduct, nioTLSProduct, nioHTTP1Product,\n                nioFoundationCompatProduct, nioFileSystemProduct,\n            ],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedCNIOAtomicsModule, resolvedCNIODarwinModule, resolvedCNIOLinuxModule,\n                resolvedCNIOWindowsModule, resolvedCNIOWASIModule, resolvedCNIOPosixModule,\n                resolvedCNIOLLHTTPModule, resolvedNIOBase64Module, resolvedNIODataStructuresModule,\n                resolvedNIOConcurrencyHelpersModule, resolvedNIOCoreModule, resolvedNIOEmbeddedModule,\n                resolvedNIOPosixModule, resolvedNIOModule, resolvedNIOTLSModule, resolvedNIOHTTP1Module,\n                resolvedNIOFoundationCompatModule, resolvedNIOFileSystemModule, resolvedNIOFileSystemPublicModule,\n            ],\n            resolvedProducts: [\n                resolvedNIOConcurrencyHelpersProduct, resolvedNIOCoreProduct, resolvedNIOProduct,\n                resolvedNIOPosixProduct, resolvedNIOTLSProduct, resolvedNIOHTTP1Product,\n                resolvedNIOFoundationCompatProduct, resolvedNIOFileSystemProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-nio-ssl Package\n\n    static func createSwiftNIOSSLPackage(\n        nioProduct: ResolvedProduct,\n        nioCoreProduct: ResolvedProduct,\n        nioConcurrencyHelpersProduct: ResolvedProduct,\n        nioTLSProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-nio-ssl\")\n\n        // Modules\n        let cnioBoringSSLModule = self.createSwiftModule(name: \"CNIOBoringSSL\")\n        let cnioBoringSSLShimsModule = self.createSwiftModule(name: \"CNIOBoringSSLShims\")\n        let nioSSLModule = self.createSwiftModule(name: \"NIOSSL\")\n\n        // Products\n        let nioSSLProduct = try Product(\n            package: identity,\n            name: \"NIOSSL\",\n            type: .library(.automatic),\n            modules: [nioSSLModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-nio-ssl\",\n            path: \"/swift-nio-ssl\",\n            modules: [cnioBoringSSLModule, cnioBoringSSLShimsModule, nioSSLModule],\n            products: [nioSSLProduct]\n        )\n\n        // Resolved modules\n        let resolvedCNIOBoringSSLModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioBoringSSLModule\n        )\n\n        let resolvedCNIOBoringSSLShimsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioBoringSSLShimsModule,\n            dependencies: [\n                .module(resolvedCNIOBoringSSLModule, conditions: []),\n            ]\n        )\n\n        let resolvedNIOSSLModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioSSLModule,\n            dependencies: [\n                .module(resolvedCNIOBoringSSLModule, conditions: []),\n                .module(resolvedCNIOBoringSSLShimsModule, conditions: []),\n                .product(nioProduct, conditions: []),\n                .product(nioCoreProduct, conditions: []),\n                .product(nioConcurrencyHelpersProduct, conditions: []),\n                .product(nioTLSProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedNIOSSLProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioSSLProduct,\n            modules: IdentifiableSet([resolvedNIOSSLModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedCNIOBoringSSLModule,\n                resolvedCNIOBoringSSLShimsModule,\n                resolvedNIOSSLModule,\n            ]),\n            products: [resolvedNIOSSLProduct],\n            dependencies: [PackageIdentity.plain(\"swift-nio\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-nio-ssl.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [cnioBoringSSLModule, cnioBoringSSLShimsModule, nioSSLModule],\n            products: [nioSSLProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedCNIOBoringSSLModule,\n                resolvedCNIOBoringSSLShimsModule,\n                resolvedNIOSSLModule,\n            ],\n            resolvedProducts: [resolvedNIOSSLProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-nio-http2 Package\n\n    static func createSwiftNIOHTTP2Package(\n        nioProduct: ResolvedProduct,\n        nioCoreProduct: ResolvedProduct,\n        nioConcurrencyHelpersProduct: ResolvedProduct,\n        nioHTTP1Product: ResolvedProduct,\n        nioTLSProduct: ResolvedProduct,\n        atomicsProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-nio-http2\")\n\n        // Modules\n        let niohpackModule = self.createSwiftModule(name: \"NIOHPACK\")\n        let niohttp2Module = self.createSwiftModule(name: \"NIOHTTP2\")\n\n        // Products\n        let niohttp2Product = try Product(\n            package: identity,\n            name: \"NIOHTTP2\",\n            type: .library(.automatic),\n            modules: [niohttp2Module]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-nio-http2\",\n            path: \"/swift-nio-http2\",\n            modules: [niohpackModule, niohttp2Module],\n            products: [niohttp2Product]\n        )\n\n        // Resolved modules\n        let resolvedNIOHPACKModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: niohpackModule,\n            dependencies: [\n                .product(nioProduct, conditions: []),\n                .product(nioCoreProduct, conditions: []),\n                .product(nioConcurrencyHelpersProduct, conditions: []),\n                .product(nioHTTP1Product, conditions: []),\n            ]\n        )\n\n        let resolvedNIOHTTP2Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: niohttp2Module,\n            dependencies: [\n                .module(resolvedNIOHPACKModule, conditions: []),\n                .product(nioProduct, conditions: []),\n                .product(nioCoreProduct, conditions: []),\n                .product(nioHTTP1Product, conditions: []),\n                .product(nioTLSProduct, conditions: []),\n                .product(nioConcurrencyHelpersProduct, conditions: []),\n                .product(atomicsProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedNIOHTTP2Product = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: niohttp2Product,\n            modules: IdentifiableSet([resolvedNIOHTTP2Module])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedNIOHPACKModule, resolvedNIOHTTP2Module]),\n            products: [resolvedNIOHTTP2Product],\n            dependencies: [\n                PackageIdentity.plain(\"swift-atomics\"),\n                PackageIdentity.plain(\"swift-nio\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-nio-http2.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [niohpackModule, niohttp2Module],\n            products: [niohttp2Product],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedNIOHPACKModule, resolvedNIOHTTP2Module],\n            resolvedProducts: [resolvedNIOHTTP2Product],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-nio-extras Package\n\n    static func createSwiftNIOExtrasPackage(\n        nioProduct: ResolvedProduct,\n        nioCoreProduct: ResolvedProduct,\n        nioHTTP1Product: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-nio-extras\")\n\n        // Modules\n        let cnioExtrasZlibModule = self.createSwiftModule(name: \"CNIOExtrasZlib\")\n        let nioHTTPCompressionModule = self.createSwiftModule(name: \"NIOHTTPCompression\")\n        let nioSOCKSModule = self.createSwiftModule(name: \"NIOSOCKS\")\n\n        // Products\n        let nioHTTPCompressionProduct = try Product(\n            package: identity,\n            name: \"NIOHTTPCompression\",\n            type: .library(.automatic),\n            modules: [nioHTTPCompressionModule]\n        )\n\n        let nioSOCKSProduct = try Product(\n            package: identity,\n            name: \"NIOSOCKS\",\n            type: .library(.automatic),\n            modules: [nioSOCKSModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-nio-extras\",\n            path: \"/swift-nio-extras\",\n            modules: [cnioExtrasZlibModule, nioHTTPCompressionModule, nioSOCKSModule],\n            products: [nioHTTPCompressionProduct, nioSOCKSProduct]\n        )\n\n        // Resolved modules\n        let resolvedCNIOExtrasZlibModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cnioExtrasZlibModule\n        )\n\n        let resolvedNIOHTTPCompressionModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioHTTPCompressionModule,\n            dependencies: [\n                .module(resolvedCNIOExtrasZlibModule, conditions: []),\n                .product(nioProduct, conditions: []),\n                .product(nioCoreProduct, conditions: []),\n                .product(nioHTTP1Product, conditions: []),\n            ]\n        )\n\n        let resolvedNIOSOCKSModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioSOCKSModule,\n            dependencies: [\n                .product(nioProduct, conditions: []),\n                .product(nioCoreProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedNIOHTTPCompressionProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioHTTPCompressionProduct,\n            modules: IdentifiableSet([resolvedNIOHTTPCompressionModule])\n        )\n\n        let resolvedNIOSOCKSProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioSOCKSProduct,\n            modules: IdentifiableSet([resolvedNIOSOCKSModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedCNIOExtrasZlibModule,\n                resolvedNIOHTTPCompressionModule,\n                resolvedNIOSOCKSModule,\n            ]),\n            products: [resolvedNIOHTTPCompressionProduct, resolvedNIOSOCKSProduct],\n            dependencies: [PackageIdentity.plain(\"swift-nio\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-nio-extras.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [cnioExtrasZlibModule, nioHTTPCompressionModule, nioSOCKSModule],\n            products: [nioHTTPCompressionProduct, nioSOCKSProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedCNIOExtrasZlibModule,\n                resolvedNIOHTTPCompressionModule,\n                resolvedNIOSOCKSModule,\n            ],\n            resolvedProducts: [resolvedNIOHTTPCompressionProduct, resolvedNIOSOCKSProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-nio-transport-services Package\n\n    static func createSwiftNIOTransportServicesPackage(\n        nioProduct: ResolvedProduct,\n        nioCoreProduct: ResolvedProduct,\n        nioFoundationCompatProduct: ResolvedProduct,\n        nioTLSProduct: ResolvedProduct,\n        atomicsProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-nio-transport-services\")\n\n        // Modules\n        let nioTransportServicesModule = self.createSwiftModule(name: \"NIOTransportServices\")\n\n        // Products\n        let nioTransportServicesProduct = try Product(\n            package: identity,\n            name: \"NIOTransportServices\",\n            type: .library(.automatic),\n            modules: [nioTransportServicesModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-nio-transport-services\",\n            path: \"/swift-nio-transport-services\",\n            modules: [nioTransportServicesModule],\n            products: [nioTransportServicesProduct]\n        )\n\n        // Resolved modules\n        let resolvedNIOTransportServicesModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: nioTransportServicesModule,\n            dependencies: [\n                .product(nioProduct, conditions: []),\n                .product(nioCoreProduct, conditions: []),\n                .product(nioFoundationCompatProduct, conditions: []),\n                .product(nioTLSProduct, conditions: []),\n                .product(atomicsProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedNIOTransportServicesProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: nioTransportServicesProduct,\n            modules: IdentifiableSet([resolvedNIOTransportServicesModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedNIOTransportServicesModule]),\n            products: [resolvedNIOTransportServicesProduct],\n            dependencies: [\n                PackageIdentity.plain(\"swift-atomics\"),\n                PackageIdentity.plain(\"swift-nio\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-nio-transport-services.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [nioTransportServicesModule],\n            products: [nioTransportServicesProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedNIOTransportServicesModule],\n            resolvedProducts: [resolvedNIOTransportServicesProduct],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SwiftlyFixtures/SBOMSwiftlyOpenAPIPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-openapi-runtime Package\n\n    static func createSwiftOpenAPIRuntimePackage(\n        httpTypesProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-openapi-runtime\")\n\n        // Modules\n        let openAPIRuntimeModule = self.createSwiftModule(name: \"OpenAPIRuntime\")\n\n        // Products\n        let openAPIRuntimeProduct = try Product(\n            package: identity,\n            name: \"OpenAPIRuntime\",\n            type: .library(.automatic),\n            modules: [openAPIRuntimeModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-openapi-runtime\",\n            path: \"/swift-openapi-runtime\",\n            modules: [openAPIRuntimeModule],\n            products: [openAPIRuntimeProduct]\n        )\n\n        // Resolved modules\n        let resolvedOpenAPIRuntimeModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: openAPIRuntimeModule,\n            dependencies: [\n                .product(httpTypesProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedOpenAPIRuntimeProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: openAPIRuntimeProduct,\n            modules: IdentifiableSet([resolvedOpenAPIRuntimeModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedOpenAPIRuntimeModule]),\n            products: [resolvedOpenAPIRuntimeProduct],\n            dependencies: [PackageIdentity.plain(\"swift-http-types\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-openapi-runtime\"))\n        )\n\n        return (\n            package: package,\n            modules: [openAPIRuntimeModule],\n            products: [openAPIRuntimeProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedOpenAPIRuntimeModule],\n            resolvedProducts: [resolvedOpenAPIRuntimeProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-openapi-generator Package\n\n    static func createSwiftOpenAPIGeneratorPackage(\n        openAPIKitProduct: ResolvedProduct,\n        openAPIKit30Product: ResolvedProduct,\n        openAPIKitCompatProduct: ResolvedProduct,\n        algorithmsProduct: ResolvedProduct,\n        orderedCollectionsProduct: ResolvedProduct,\n        yamsProduct: ResolvedProduct,\n        argumentParserProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-openapi-generator\")\n\n        // Modules\n        let openAPIGeneratorCoreModule = self.createSwiftModule(name: \"_OpenAPIGeneratorCore\")\n        let openAPIGeneratorModule = self.createSwiftModule(name: \"OpenAPIGenerator\", type: .plugin)\n        let swiftOpenAPIGeneratorModule = self.createSwiftModule(name: \"swift-openapi-generator\", type: .executable)\n\n        // Products\n        let openAPIGeneratorProduct = try Product(\n            package: identity,\n            name: \"OpenAPIGenerator\",\n            type: .plugin,\n            modules: [openAPIGeneratorModule]\n        )\n\n        let swiftOpenAPIGeneratorProduct = try Product(\n            package: identity,\n            name: \"swift-openapi-generator\",\n            type: .executable,\n            modules: [swiftOpenAPIGeneratorModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-openapi-generator\",\n            path: \"/swift-openapi-generator\",\n            modules: [openAPIGeneratorCoreModule, openAPIGeneratorModule, swiftOpenAPIGeneratorModule],\n            products: [openAPIGeneratorProduct, swiftOpenAPIGeneratorProduct]\n        )\n\n        // Resolved modules\n        let resolvedOpenAPIGeneratorCoreModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: openAPIGeneratorCoreModule,\n            dependencies: [\n                .product(openAPIKitProduct, conditions: []),\n                .product(openAPIKit30Product, conditions: []),\n                .product(openAPIKitCompatProduct, conditions: []),\n                .product(algorithmsProduct, conditions: []),\n                .product(orderedCollectionsProduct, conditions: []),\n                .product(yamsProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftOpenAPIGeneratorModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftOpenAPIGeneratorModule,\n            dependencies: [\n                .module(resolvedOpenAPIGeneratorCoreModule, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n            ]\n        )\n\n        let resolvedOpenAPIGeneratorModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: openAPIGeneratorModule,\n            dependencies: [\n                .module(resolvedSwiftOpenAPIGeneratorModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedOpenAPIGeneratorProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: openAPIGeneratorProduct,\n            modules: IdentifiableSet([resolvedOpenAPIGeneratorModule])\n        )\n\n        let resolvedSwiftOpenAPIGeneratorProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftOpenAPIGeneratorProduct,\n            modules: IdentifiableSet([resolvedSwiftOpenAPIGeneratorModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedOpenAPIGeneratorCoreModule,\n                resolvedOpenAPIGeneratorModule,\n                resolvedSwiftOpenAPIGeneratorModule,\n            ]),\n            products: [resolvedOpenAPIGeneratorProduct, resolvedSwiftOpenAPIGeneratorProduct],\n            dependencies: [\n                PackageIdentity.plain(\"openapikit\"),\n                PackageIdentity.plain(\"swift-algorithms\"),\n                PackageIdentity.plain(\"swift-argument-parser\"),\n                PackageIdentity.plain(\"swift-collections\"),\n                PackageIdentity.plain(\"yams\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-openapi-generator\"))\n        )\n\n        return (\n            package: package,\n            modules: [openAPIGeneratorCoreModule, openAPIGeneratorModule, swiftOpenAPIGeneratorModule],\n            products: [openAPIGeneratorProduct, swiftOpenAPIGeneratorProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedOpenAPIGeneratorCoreModule,\n                resolvedOpenAPIGeneratorModule,\n                resolvedSwiftOpenAPIGeneratorModule,\n            ],\n            resolvedProducts: [resolvedOpenAPIGeneratorProduct, resolvedSwiftOpenAPIGeneratorProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - async-http-client Package\n\n    static func createAsyncHTTPClientPackage(\n        nioProduct: ResolvedProduct,\n        nioTLSProduct: ResolvedProduct,\n        nioCoreProduct: ResolvedProduct,\n        nioPosixProduct: ResolvedProduct,\n        nioHTTP1Product: ResolvedProduct,\n        nioConcurrencyHelpersProduct: ResolvedProduct,\n        nioHTTP2Product: ResolvedProduct,\n        nioSSLProduct: ResolvedProduct,\n        nioHTTPCompressionProduct: ResolvedProduct,\n        nioSOCKSProduct: ResolvedProduct,\n        nioTransportServicesProduct: ResolvedProduct,\n        atomicsProduct: ResolvedProduct,\n        algorithmsProduct: ResolvedProduct,\n        loggingProduct: ResolvedProduct,\n        tracingProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"async-http-client\")\n\n        // Modules\n        let cAsyncHTTPClientModule = self.createSwiftModule(name: \"CAsyncHTTPClient\")\n        let asyncHTTPClientModule = self.createSwiftModule(name: \"AsyncHTTPClient\")\n\n        // Products\n        let asyncHTTPClientProduct = try Product(\n            package: identity,\n            name: \"AsyncHTTPClient\",\n            type: .library(.automatic),\n            modules: [asyncHTTPClientModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"async-http-client\",\n            path: \"/async-http-client\",\n            modules: [cAsyncHTTPClientModule, asyncHTTPClientModule],\n            products: [asyncHTTPClientProduct]\n        )\n\n        // Resolved modules\n        let resolvedCAsyncHTTPClientModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cAsyncHTTPClientModule\n        )\n\n        let resolvedAsyncHTTPClientModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: asyncHTTPClientModule,\n            dependencies: [\n                .module(resolvedCAsyncHTTPClientModule, conditions: []),\n                .product(nioProduct, conditions: []),\n                .product(nioTLSProduct, conditions: []),\n                .product(nioCoreProduct, conditions: []),\n                .product(nioPosixProduct, conditions: []),\n                .product(nioHTTP1Product, conditions: []),\n                .product(nioConcurrencyHelpersProduct, conditions: []),\n                .product(nioHTTP2Product, conditions: []),\n                .product(nioSSLProduct, conditions: []),\n                .product(nioHTTPCompressionProduct, conditions: []),\n                .product(nioSOCKSProduct, conditions: []),\n                .product(nioTransportServicesProduct, conditions: []),\n                .product(atomicsProduct, conditions: []),\n                .product(algorithmsProduct, conditions: []),\n                .product(loggingProduct, conditions: []),\n                .product(tracingProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedAsyncHTTPClientProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: asyncHTTPClientProduct,\n            modules: IdentifiableSet([resolvedAsyncHTTPClientModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedCAsyncHTTPClientModule, resolvedAsyncHTTPClientModule]),\n            products: [resolvedAsyncHTTPClientProduct],\n            dependencies: [\n                PackageIdentity.plain(\"swift-algorithms\"),\n                PackageIdentity.plain(\"swift-atomics\"),\n                PackageIdentity.plain(\"swift-distributed-tracing\"),\n                PackageIdentity.plain(\"swift-log\"),\n                PackageIdentity.plain(\"swift-nio\"),\n                PackageIdentity.plain(\"swift-nio-extras\"),\n                PackageIdentity.plain(\"swift-nio-http2\"),\n                PackageIdentity.plain(\"swift-nio-ssl\"),\n                PackageIdentity.plain(\"swift-nio-transport-services\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/swift-server/async-http-client\"))\n        )\n\n        return (\n            package: package,\n            modules: [cAsyncHTTPClientModule, asyncHTTPClientModule],\n            products: [asyncHTTPClientProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedCAsyncHTTPClientModule, resolvedAsyncHTTPClientModule],\n            resolvedProducts: [resolvedAsyncHTTPClientProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-openapi-async-http-client Package\n\n    static func createSwiftOpenAPIAsyncHTTPClientPackage(\n        openAPIRuntimeProduct: ResolvedProduct,\n        httpTypesProduct: ResolvedProduct,\n        asyncHTTPClientProduct: ResolvedProduct,\n        nioFoundationCompatProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-openapi-async-http-client\")\n\n        // Modules\n        let openAPIAsyncHTTPClientModule = self.createSwiftModule(name: \"OpenAPIAsyncHTTPClient\")\n\n        // Products\n        let openAPIAsyncHTTPClientProduct = try Product(\n            package: identity,\n            name: \"OpenAPIAsyncHTTPClient\",\n            type: .library(.automatic),\n            modules: [openAPIAsyncHTTPClientModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-openapi-async-http-client\",\n            path: \"/swift-openapi-async-http-client\",\n            modules: [openAPIAsyncHTTPClientModule],\n            products: [openAPIAsyncHTTPClientProduct]\n        )\n\n        // Resolved modules\n        let resolvedOpenAPIAsyncHTTPClientModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: openAPIAsyncHTTPClientModule,\n            dependencies: [\n                .product(openAPIRuntimeProduct, conditions: []),\n                .product(httpTypesProduct, conditions: []),\n                .product(asyncHTTPClientProduct, conditions: []),\n                .product(nioFoundationCompatProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedOpenAPIAsyncHTTPClientProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: openAPIAsyncHTTPClientProduct,\n            modules: IdentifiableSet([resolvedOpenAPIAsyncHTTPClientModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedOpenAPIAsyncHTTPClientModule]),\n            products: [resolvedOpenAPIAsyncHTTPClientProduct],\n            dependencies: [\n                PackageIdentity.plain(\"async-http-client\"),\n                PackageIdentity.plain(\"swift-http-types\"),\n                PackageIdentity.plain(\"swift-nio\"),\n                PackageIdentity.plain(\"swift-openapi-runtime\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(\n                SourceControlURL(\"https://github.com/swift-server/swift-openapi-async-http-client\")\n            )\n        )\n\n        return (\n            package: package,\n            modules: [openAPIAsyncHTTPClientModule],\n            products: [openAPIAsyncHTTPClientProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedOpenAPIAsyncHTTPClientModule],\n            resolvedProducts: [resolvedOpenAPIAsyncHTTPClientProduct],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SwiftlyFixtures/SBOMSwiftlyRootPackage.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swiftly Package (Root)\n\n    static func createSwiftlyRootPackage(\n        rootPath: String = \"/tmp/swiftly-mock\",\n        openAPIGeneratorProduct: ResolvedProduct,\n        openAPIRuntimeProduct: ResolvedProduct,\n        argumentParserProduct: ResolvedProduct,\n        systemPackageProduct: ResolvedProduct,\n        asyncHTTPClientProduct: ResolvedProduct,\n        nioFoundationCompatProduct: ResolvedProduct,\n        openAPIAsyncHTTPClientProduct: ResolvedProduct,\n        subprocessProduct: ResolvedProduct,\n        swiftToolsSupportProduct: ResolvedProduct,\n        nioFileSystemProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swiftly\")\n\n        // System module\n        let cLibArchiveModule = self.createSwiftModule(name: \"CLibArchive\", type: .systemModule)\n\n        // Plugin modules\n        let generateCommandModelsModule = self.createSwiftModule(name: \"GenerateCommandModels\", type: .plugin)\n        let generateDocsReferenceModule = self.createSwiftModule(name: \"GenerateDocsReference\", type: .plugin)\n\n        // Executable modules\n        let generateCommandModelsExecModule = self.createSwiftModule(name: \"generate-command-models\", type: .executable)\n        let generateDocsReferenceExecModule = self.createSwiftModule(name: \"generate-docs-reference\", type: .executable)\n        let swiftlyModule = self.createSwiftModule(name: \"Swiftly\", type: .executable)\n        let testSwiftlyModule = self.createSwiftModule(name: \"TestSwiftly\", type: .executable)\n        let buildSwiftlyReleaseModule = self.createSwiftModule(name: \"build-swiftly-release\", type: .executable)\n\n        // Library modules\n        let swiftlyWebsiteAPIModule = self.createSwiftModule(name: \"SwiftlyWebsiteAPI\")\n        let swiftlyDownloadAPIModule = self.createSwiftModule(name: \"SwiftlyDownloadAPI\")\n        let swiftlyDocsModule = self.createSwiftModule(name: \"SwiftlyDocs\")\n        let swiftlyCoreModule = self.createSwiftModule(name: \"SwiftlyCore\")\n        let macOSPlatformModule = self.createSwiftModule(name: \"MacOSPlatform\")\n        let linuxPlatformModule = self.createSwiftModule(name: \"LinuxPlatform\")\n\n        // Test module\n        let swiftlyTestsModule = self.createSwiftModule(name: \"SwiftlyTests\", type: .test)\n\n        // Products\n        let swiftlyProduct = try Product(\n            package: identity,\n            name: \"swiftly\",\n            type: .executable,\n            modules: [swiftlyModule]\n        )\n\n        let testSwiftlyProduct = try Product(\n            package: identity,\n            name: \"test-swiftly\",\n            type: .executable,\n            modules: [testSwiftlyModule]\n        )\n\n        let generateDocsReferenceProduct = try Product(\n            package: identity,\n            name: \"generate-docs-reference\",\n            type: .executable,\n            modules: [generateDocsReferenceExecModule]\n        )\n\n        let generateCommandModelsProduct = try Product(\n            package: identity,\n            name: \"generate-command-models\",\n            type: .executable,\n            modules: [generateCommandModelsExecModule]\n        )\n\n        let buildSwiftlyReleaseProduct = try Product(\n            package: identity,\n            name: \"build-swiftly-release\",\n            type: .executable,\n            modules: [buildSwiftlyReleaseModule]\n        )\n\n        let swiftlyTestsProduct = try Product(\n            package: identity,\n            name: \"SwiftlyTests\",\n            type: .test,\n            modules: [swiftlyTestsModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swiftly\",\n            path: rootPath,\n            modules: [\n                cLibArchiveModule, generateCommandModelsModule, generateDocsReferenceModule,\n                generateCommandModelsExecModule, generateDocsReferenceExecModule,\n                swiftlyModule, testSwiftlyModule, buildSwiftlyReleaseModule,\n                swiftlyWebsiteAPIModule, swiftlyDownloadAPIModule, swiftlyDocsModule,\n                swiftlyCoreModule, macOSPlatformModule, linuxPlatformModule,\n                swiftlyTestsModule,\n            ],\n            products: [\n                swiftlyProduct, testSwiftlyProduct, generateDocsReferenceProduct,\n                generateCommandModelsProduct, buildSwiftlyReleaseProduct, swiftlyTestsProduct,\n            ]\n        )\n\n        // Resolved modules - System and plugins\n        let resolvedCLibArchiveModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cLibArchiveModule\n        )\n\n        let resolvedGenerateCommandModelsExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: generateCommandModelsExecModule,\n            dependencies: [\n                .product(argumentParserProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n            ]\n        )\n\n        let resolvedGenerateCommandModelsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: generateCommandModelsModule,\n            dependencies: [\n                .module(resolvedGenerateCommandModelsExecModule, conditions: []),\n            ]\n        )\n\n        let resolvedGenerateDocsReferenceExecModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: generateDocsReferenceExecModule,\n            dependencies: [\n                .product(argumentParserProduct, conditions: []),\n            ]\n        )\n\n        let resolvedGenerateDocsReferenceModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: generateDocsReferenceModule,\n            dependencies: [\n                .module(resolvedGenerateDocsReferenceExecModule, conditions: []),\n            ]\n        )\n\n        // Resolved library modules\n        let resolvedSwiftlyWebsiteAPIModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftlyWebsiteAPIModule,\n            dependencies: [\n                .product(openAPIGeneratorProduct, conditions: []),\n                .product(openAPIRuntimeProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftlyDownloadAPIModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftlyDownloadAPIModule,\n            dependencies: [\n                .product(openAPIGeneratorProduct, conditions: []),\n                .product(openAPIRuntimeProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftlyDocsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftlyDocsModule\n        )\n\n        let resolvedSwiftlyCoreModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftlyCoreModule,\n            dependencies: [\n                .product(openAPIGeneratorProduct, conditions: []),\n                .module(resolvedSwiftlyDownloadAPIModule, conditions: []),\n                .module(resolvedSwiftlyWebsiteAPIModule, conditions: []),\n                .module(resolvedGenerateCommandModelsModule, conditions: []),\n                .product(openAPIRuntimeProduct, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n                .product(asyncHTTPClientProduct, conditions: []),\n                .product(nioFoundationCompatProduct, conditions: []),\n                .product(openAPIAsyncHTTPClientProduct, conditions: []),\n                .product(subprocessProduct, conditions: []),\n            ]\n        )\n\n        let resolvedMacOSPlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: macOSPlatformModule,\n            dependencies: [\n                .product(openAPIGeneratorProduct, conditions: []),\n                .module(resolvedSwiftlyDownloadAPIModule, conditions: []),\n                .module(resolvedSwiftlyWebsiteAPIModule, conditions: []),\n                .module(resolvedGenerateCommandModelsModule, conditions: []),\n                .module(resolvedSwiftlyCoreModule, conditions: []),\n                .product(openAPIRuntimeProduct, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n                .product(asyncHTTPClientProduct, conditions: []),\n                .product(nioFoundationCompatProduct, conditions: []),\n                .product(openAPIAsyncHTTPClientProduct, conditions: []),\n                .product(subprocessProduct, conditions: []),\n            ]\n        )\n\n        let resolvedLinuxPlatformModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: linuxPlatformModule,\n            dependencies: [\n                .product(openAPIGeneratorProduct, conditions: []),\n                .module(resolvedSwiftlyDownloadAPIModule, conditions: []),\n                .module(resolvedSwiftlyWebsiteAPIModule, conditions: []),\n                .module(resolvedGenerateCommandModelsModule, conditions: []),\n                .module(resolvedSwiftlyCoreModule, conditions: []),\n                .module(resolvedCLibArchiveModule, conditions: []),\n                .product(openAPIRuntimeProduct, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n                .product(asyncHTTPClientProduct, conditions: []),\n                .product(nioFoundationCompatProduct, conditions: []),\n                .product(openAPIAsyncHTTPClientProduct, conditions: []),\n                .product(subprocessProduct, conditions: []),\n            ]\n        )\n\n        // Resolved executable modules\n        let resolvedSwiftlyModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftlyModule,\n            dependencies: [\n                .product(openAPIGeneratorProduct, conditions: []),\n                .module(resolvedSwiftlyDownloadAPIModule, conditions: []),\n                .module(resolvedSwiftlyWebsiteAPIModule, conditions: []),\n                .module(resolvedGenerateCommandModelsModule, conditions: []),\n                .module(resolvedSwiftlyCoreModule, conditions: []),\n                .module(resolvedCLibArchiveModule, conditions: []),\n                .module(resolvedMacOSPlatformModule, conditions: []),\n                .product(openAPIRuntimeProduct, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n                .product(asyncHTTPClientProduct, conditions: []),\n                .product(nioFoundationCompatProduct, conditions: []),\n                .product(openAPIAsyncHTTPClientProduct, conditions: []),\n                .product(subprocessProduct, conditions: []),\n                .product(swiftToolsSupportProduct, conditions: []),\n            ]\n        )\n\n        let resolvedTestSwiftlyModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: testSwiftlyModule,\n            dependencies: [\n                .product(openAPIGeneratorProduct, conditions: []),\n                .module(resolvedSwiftlyDownloadAPIModule, conditions: []),\n                .module(resolvedSwiftlyWebsiteAPIModule, conditions: []),\n                .module(resolvedGenerateCommandModelsModule, conditions: []),\n                .module(resolvedSwiftlyCoreModule, conditions: []),\n                .module(resolvedCLibArchiveModule, conditions: []),\n                .module(resolvedMacOSPlatformModule, conditions: []),\n                .product(openAPIRuntimeProduct, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n                .product(asyncHTTPClientProduct, conditions: []),\n                .product(nioFoundationCompatProduct, conditions: []),\n                .product(openAPIAsyncHTTPClientProduct, conditions: []),\n                .product(subprocessProduct, conditions: []),\n            ]\n        )\n\n        let resolvedBuildSwiftlyReleaseModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: buildSwiftlyReleaseModule,\n            dependencies: [\n                .product(openAPIGeneratorProduct, conditions: []),\n                .module(resolvedSwiftlyDownloadAPIModule, conditions: []),\n                .module(resolvedSwiftlyWebsiteAPIModule, conditions: []),\n                .module(resolvedGenerateCommandModelsModule, conditions: []),\n                .module(resolvedSwiftlyCoreModule, conditions: []),\n                .module(resolvedCLibArchiveModule, conditions: []),\n                .module(resolvedMacOSPlatformModule, conditions: []),\n                .product(openAPIRuntimeProduct, conditions: []),\n                .product(argumentParserProduct, conditions: []),\n                .product(systemPackageProduct, conditions: []),\n                .product(asyncHTTPClientProduct, conditions: []),\n                .product(nioFoundationCompatProduct, conditions: []),\n                .product(openAPIAsyncHTTPClientProduct, conditions: []),\n                .product(subprocessProduct, conditions: []),\n                .product(nioFileSystemProduct, conditions: []),\n            ]\n        )\n\n        let resolvedSwiftlyTestsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftlyTestsModule,\n            dependencies: [\n                .product(systemPackageProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedSwiftlyProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftlyProduct,\n            modules: IdentifiableSet([resolvedSwiftlyModule])\n        )\n\n        let resolvedTestSwiftlyProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: testSwiftlyProduct,\n            modules: IdentifiableSet([resolvedTestSwiftlyModule])\n        )\n\n        let resolvedGenerateDocsReferenceProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: generateDocsReferenceProduct,\n            modules: IdentifiableSet([resolvedGenerateDocsReferenceExecModule])\n        )\n\n        let resolvedGenerateCommandModelsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: generateCommandModelsProduct,\n            modules: IdentifiableSet([resolvedGenerateCommandModelsExecModule])\n        )\n\n        let resolvedBuildSwiftlyReleaseProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: buildSwiftlyReleaseProduct,\n            modules: IdentifiableSet([resolvedBuildSwiftlyReleaseModule])\n        )\n\n        let resolvedSwiftlyTestsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftlyTestsProduct,\n            modules: IdentifiableSet([resolvedSwiftlyTestsModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedCLibArchiveModule, resolvedGenerateCommandModelsModule, resolvedGenerateDocsReferenceModule,\n                resolvedGenerateCommandModelsExecModule, resolvedGenerateDocsReferenceExecModule,\n                resolvedSwiftlyModule, resolvedTestSwiftlyModule, resolvedBuildSwiftlyReleaseModule,\n                resolvedSwiftlyWebsiteAPIModule, resolvedSwiftlyDownloadAPIModule, resolvedSwiftlyDocsModule,\n                resolvedSwiftlyCoreModule, resolvedMacOSPlatformModule, resolvedLinuxPlatformModule,\n                resolvedSwiftlyTestsModule,\n            ]),\n            products: [\n                resolvedSwiftlyProduct, resolvedTestSwiftlyProduct, resolvedGenerateDocsReferenceProduct,\n                resolvedGenerateCommandModelsProduct, resolvedBuildSwiftlyReleaseProduct, resolvedSwiftlyTestsProduct,\n            ],\n            dependencies: [\n                PackageIdentity.plain(\"async-http-client\"),\n                PackageIdentity.plain(\"swift-argument-parser\"),\n                PackageIdentity.plain(\"swift-docc-plugin\"),\n                PackageIdentity.plain(\"swift-nio\"),\n                PackageIdentity.plain(\"swift-openapi-async-http-client\"),\n                PackageIdentity.plain(\"swift-openapi-generator\"),\n                PackageIdentity.plain(\"swift-openapi-runtime\"),\n                PackageIdentity.plain(\"swift-subprocess\"),\n                PackageIdentity.plain(\"swift-system\"),\n                PackageIdentity.plain(\"swift-tools-support-core\"),\n                PackageIdentity.plain(\"swiftformat\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .root(AbsolutePath(rootPath))\n        )\n\n        return (\n            package: package,\n            modules: [\n                cLibArchiveModule, generateCommandModelsModule, generateDocsReferenceModule,\n                generateCommandModelsExecModule, generateDocsReferenceExecModule,\n                swiftlyModule, testSwiftlyModule, buildSwiftlyReleaseModule,\n                swiftlyWebsiteAPIModule, swiftlyDownloadAPIModule, swiftlyDocsModule,\n                swiftlyCoreModule, macOSPlatformModule, linuxPlatformModule,\n                swiftlyTestsModule,\n            ],\n            products: [\n                swiftlyProduct, testSwiftlyProduct, generateDocsReferenceProduct,\n                generateCommandModelsProduct, buildSwiftlyReleaseProduct, swiftlyTestsProduct,\n            ],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedCLibArchiveModule, resolvedGenerateCommandModelsModule, resolvedGenerateDocsReferenceModule,\n                resolvedGenerateCommandModelsExecModule, resolvedGenerateDocsReferenceExecModule,\n                resolvedSwiftlyModule, resolvedTestSwiftlyModule, resolvedBuildSwiftlyReleaseModule,\n                resolvedSwiftlyWebsiteAPIModule, resolvedSwiftlyDownloadAPIModule, resolvedSwiftlyDocsModule,\n                resolvedSwiftlyCoreModule, resolvedMacOSPlatformModule, resolvedLinuxPlatformModule,\n                resolvedSwiftlyTestsModule,\n            ],\n            resolvedProducts: [\n                resolvedSwiftlyProduct, resolvedTestSwiftlyProduct, resolvedGenerateDocsReferenceProduct,\n                resolvedGenerateCommandModelsProduct, resolvedBuildSwiftlyReleaseProduct, resolvedSwiftlyTestsProduct,\n            ],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SwiftlyFixtures/SBOMSwiftlySecurityPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-asn1 Package\n\n    static func createSwiftlySwiftASN1Package() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-asn1\")\n\n        // Modules\n        let swiftASN1Module = self.createSwiftModule(name: \"SwiftASN1\")\n\n        // Products\n        let swiftASN1Product = try Product(\n            package: identity,\n            name: \"SwiftASN1\",\n            type: .library(.automatic),\n            modules: [swiftASN1Module]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-asn1\",\n            path: \"/swift-asn1\",\n            modules: [swiftASN1Module],\n            products: [swiftASN1Product]\n        )\n\n        // Resolved modules\n        let resolvedSwiftASN1Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: swiftASN1Module\n        )\n\n        // Resolved products\n        let resolvedSwiftASN1Product = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: swiftASN1Product,\n            modules: IdentifiableSet([resolvedSwiftASN1Module])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedSwiftASN1Module]),\n            products: [resolvedSwiftASN1Product]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-asn1.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [swiftASN1Module],\n            products: [swiftASN1Product],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedSwiftASN1Module],\n            resolvedProducts: [resolvedSwiftASN1Product],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-crypto Package\n\n    static func createSwiftlySwiftCryptoPackage(\n        swiftASN1Product: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-crypto\")\n\n        // Modules\n        let cCryptoBoringSSLModule = self.createSwiftModule(name: \"CCryptoBoringSSL\")\n        let cCryptoBoringSSLShimsModule = self.createSwiftModule(name: \"CCryptoBoringSSLShims\")\n        let cryptoBoringWrapperModule = self.createSwiftModule(name: \"CryptoBoringWrapper\")\n        let cryptoModule = self.createSwiftModule(name: \"Crypto\")\n        let cryptoExtrasModule = self.createSwiftModule(name: \"_CryptoExtras\")\n\n        // Products\n        let cryptoProduct = try Product(\n            package: identity,\n            name: \"Crypto\",\n            type: .library(.automatic),\n            modules: [cryptoModule]\n        )\n\n        let cryptoExtrasProduct = try Product(\n            package: identity,\n            name: \"_CryptoExtras\",\n            type: .library(.automatic),\n            modules: [cryptoExtrasModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-crypto\",\n            path: \"/swift-crypto\",\n            modules: [\n                cCryptoBoringSSLModule, cCryptoBoringSSLShimsModule, cryptoBoringWrapperModule,\n                cryptoModule, cryptoExtrasModule,\n            ],\n            products: [cryptoProduct, cryptoExtrasProduct]\n        )\n\n        // Resolved modules\n        let resolvedCCryptoBoringSSLModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cCryptoBoringSSLModule\n        )\n\n        let resolvedCCryptoBoringSSLShimsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cCryptoBoringSSLShimsModule,\n            dependencies: [\n                .module(resolvedCCryptoBoringSSLModule, conditions: []),\n            ]\n        )\n\n        let resolvedCryptoBoringWrapperModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cryptoBoringWrapperModule,\n            dependencies: [\n                .module(resolvedCCryptoBoringSSLModule, conditions: []),\n                .module(resolvedCCryptoBoringSSLShimsModule, conditions: []),\n            ]\n        )\n\n        let resolvedCryptoModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cryptoModule,\n            dependencies: [\n                .module(resolvedCCryptoBoringSSLModule, conditions: []),\n                .module(resolvedCCryptoBoringSSLShimsModule, conditions: []),\n                .module(resolvedCryptoBoringWrapperModule, conditions: []),\n            ]\n        )\n\n        let resolvedCryptoExtrasModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cryptoExtrasModule,\n            dependencies: [\n                .module(resolvedCCryptoBoringSSLModule, conditions: []),\n                .module(resolvedCCryptoBoringSSLShimsModule, conditions: []),\n                .module(resolvedCryptoBoringWrapperModule, conditions: []),\n                .module(resolvedCryptoModule, conditions: []),\n                .product(swiftASN1Product, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedCryptoProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: cryptoProduct,\n            modules: IdentifiableSet([resolvedCryptoModule])\n        )\n\n        let resolvedCryptoExtrasProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: cryptoExtrasProduct,\n            modules: IdentifiableSet([resolvedCryptoExtrasModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedCCryptoBoringSSLModule, resolvedCCryptoBoringSSLShimsModule,\n                resolvedCryptoBoringWrapperModule, resolvedCryptoModule, resolvedCryptoExtrasModule,\n            ]),\n            products: [resolvedCryptoProduct, resolvedCryptoExtrasProduct],\n            dependencies: [PackageIdentity.plain(\"swift-asn1\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-crypto.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [\n                cCryptoBoringSSLModule, cCryptoBoringSSLShimsModule, cryptoBoringWrapperModule,\n                cryptoModule, cryptoExtrasModule,\n            ],\n            products: [cryptoProduct, cryptoExtrasProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedCCryptoBoringSSLModule, resolvedCCryptoBoringSSLShimsModule,\n                resolvedCryptoBoringWrapperModule, resolvedCryptoModule, resolvedCryptoExtrasModule,\n            ],\n            resolvedProducts: [resolvedCryptoProduct, resolvedCryptoExtrasProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-certificates Package\n\n    static func createSwiftlySwiftCertificatesPackage(\n        swiftASN1Product: ResolvedProduct,\n        cryptoProduct: ResolvedProduct,\n        cryptoExtrasProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-certificates\")\n\n        // Modules\n        let certificateInternalsModule = self.createSwiftModule(name: \"_CertificateInternals\")\n        let x509Module = self.createSwiftModule(name: \"X509\")\n\n        // Products\n        let x509Product = try Product(\n            package: identity,\n            name: \"X509\",\n            type: .library(.automatic),\n            modules: [x509Module]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-certificates\",\n            path: \"/swift-certificates\",\n            modules: [certificateInternalsModule, x509Module],\n            products: [x509Product]\n        )\n\n        // Resolved modules\n        let resolvedCertificateInternalsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: certificateInternalsModule\n        )\n\n        let resolvedX509Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: x509Module,\n            dependencies: [\n                .module(resolvedCertificateInternalsModule, conditions: []),\n                .product(swiftASN1Product, conditions: []),\n                .product(cryptoProduct, conditions: []),\n                .product(cryptoExtrasProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedX509Product = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: x509Product,\n            modules: IdentifiableSet([resolvedX509Module])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedCertificateInternalsModule, resolvedX509Module]),\n            products: [resolvedX509Product],\n            dependencies: [\n                PackageIdentity.plain(\"swift-asn1\"),\n                PackageIdentity.plain(\"swift-crypto\"),\n            ]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-certificates.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [certificateInternalsModule, x509Module],\n            products: [x509Product],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedCertificateInternalsModule, resolvedX509Module],\n            resolvedProducts: [resolvedX509Product],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/SwiftlyFixtures/SBOMSwiftlyUtilityPackages.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport Foundation\nimport PackageGraph\nimport PackageModel\n@testable import SBOMModel\n\nextension SBOMTestModulesGraph {\n    // MARK: - swift-log Package\n\n    static func createSwiftLogPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-log\")\n\n        // Modules\n        let loggingModule = self.createSwiftModule(name: \"Logging\")\n\n        // Products\n        let loggingProduct = try Product(\n            package: identity,\n            name: \"Logging\",\n            type: .library(.automatic),\n            modules: [loggingModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-log\",\n            path: \"/swift-log\",\n            modules: [loggingModule],\n            products: [loggingProduct]\n        )\n\n        // Resolved modules\n        let resolvedLoggingModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: loggingModule\n        )\n\n        // Resolved products\n        let resolvedLoggingProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: loggingProduct,\n            modules: IdentifiableSet([resolvedLoggingModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedLoggingModule]),\n            products: [resolvedLoggingProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-log.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [loggingModule],\n            products: [loggingProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedLoggingModule],\n            resolvedProducts: [resolvedLoggingProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-service-context Package\n\n    static func createSwiftServiceContextPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-service-context\")\n\n        // Modules\n        let serviceContextModule = self.createSwiftModule(name: \"ServiceContextModule\")\n\n        // Products\n        let serviceContextProduct = try Product(\n            package: identity,\n            name: \"ServiceContextModule\",\n            type: .library(.automatic),\n            modules: [serviceContextModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-service-context\",\n            path: \"/swift-service-context\",\n            modules: [serviceContextModule],\n            products: [serviceContextProduct]\n        )\n\n        // Resolved modules\n        let resolvedServiceContextModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: serviceContextModule\n        )\n\n        // Resolved products\n        let resolvedServiceContextProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: serviceContextProduct,\n            modules: IdentifiableSet([resolvedServiceContextModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedServiceContextModule]),\n            products: [resolvedServiceContextProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-service-context.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [serviceContextModule],\n            products: [serviceContextProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedServiceContextModule],\n            resolvedProducts: [resolvedServiceContextProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-distributed-tracing Package\n\n    static func createSwiftDistributedTracingPackage(\n        serviceContextProduct: ResolvedProduct\n    ) throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-distributed-tracing\")\n\n        // Modules\n        let instrumentationModule = self.createSwiftModule(name: \"Instrumentation\")\n        let tracingModule = self.createSwiftModule(name: \"Tracing\")\n\n        // Products\n        let tracingProduct = try Product(\n            package: identity,\n            name: \"Tracing\",\n            type: .library(.automatic),\n            modules: [tracingModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-distributed-tracing\",\n            path: \"/swift-distributed-tracing\",\n            modules: [instrumentationModule, tracingModule],\n            products: [tracingProduct]\n        )\n\n        // Resolved modules\n        let resolvedInstrumentationModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: instrumentationModule,\n            dependencies: [\n                .product(serviceContextProduct, conditions: []),\n            ]\n        )\n\n        let resolvedTracingModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: tracingModule,\n            dependencies: [\n                .module(resolvedInstrumentationModule, conditions: []),\n                .product(serviceContextProduct, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedTracingProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: tracingProduct,\n            modules: IdentifiableSet([resolvedTracingModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedInstrumentationModule, resolvedTracingModule]),\n            products: [resolvedTracingProduct],\n            dependencies: [PackageIdentity.plain(\"swift-service-context\")]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-distributed-tracing.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [instrumentationModule, tracingModule],\n            products: [tracingProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedInstrumentationModule, resolvedTracingModule],\n            resolvedProducts: [resolvedTracingProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - yams Package\n\n    static func createYamsPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"yams\")\n\n        // Modules\n        let cYamlModule = self.createSwiftModule(name: \"CYaml\")\n        let yamsModule = self.createSwiftModule(name: \"Yams\")\n\n        // Products\n        let yamsProduct = try Product(\n            package: identity,\n            name: \"Yams\",\n            type: .library(.automatic),\n            modules: [yamsModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"Yams\",\n            path: \"/yams\",\n            modules: [cYamlModule, yamsModule],\n            products: [yamsProduct]\n        )\n\n        // Resolved modules\n        let resolvedCYamlModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: cYamlModule\n        )\n\n        let resolvedYamsModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: yamsModule,\n            dependencies: [\n                .module(resolvedCYamlModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedYamsProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: yamsProduct,\n            modules: IdentifiableSet([resolvedYamsModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedCYamlModule, resolvedYamsModule]),\n            products: [resolvedYamsProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/jpsim/Yams.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [cYamlModule, yamsModule],\n            products: [yamsProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedCYamlModule, resolvedYamsModule],\n            resolvedProducts: [resolvedYamsProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - openapikit Package\n\n    static func createOpenAPIKitPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"openapikit\")\n\n        // Modules\n        let openAPIKitCoreModule = self.createSwiftModule(name: \"OpenAPIKitCore\")\n        let openAPIKitModule = self.createSwiftModule(name: \"OpenAPIKit\")\n        let openAPIKit30Module = self.createSwiftModule(name: \"OpenAPIKit30\")\n        let openAPIKitCompatModule = self.createSwiftModule(name: \"OpenAPIKitCompat\")\n\n        // Products\n        let openAPIKitProduct = try Product(\n            package: identity,\n            name: \"OpenAPIKit\",\n            type: .library(.automatic),\n            modules: [openAPIKitModule]\n        )\n\n        let openAPIKit30Product = try Product(\n            package: identity,\n            name: \"OpenAPIKit30\",\n            type: .library(.automatic),\n            modules: [openAPIKit30Module]\n        )\n\n        let openAPIKitCompatProduct = try Product(\n            package: identity,\n            name: \"OpenAPIKitCompat\",\n            type: .library(.automatic),\n            modules: [openAPIKitCompatModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"OpenAPIKit\",\n            path: \"/openapikit\",\n            modules: [openAPIKitCoreModule, openAPIKitModule, openAPIKit30Module, openAPIKitCompatModule],\n            products: [openAPIKitProduct, openAPIKit30Product, openAPIKitCompatProduct]\n        )\n\n        // Resolved modules\n        let resolvedOpenAPIKitCoreModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: openAPIKitCoreModule\n        )\n\n        let resolvedOpenAPIKitModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: openAPIKitModule,\n            dependencies: [\n                .module(resolvedOpenAPIKitCoreModule, conditions: []),\n            ]\n        )\n\n        let resolvedOpenAPIKit30Module = self.createResolvedModule(\n            packageIdentity: identity,\n            module: openAPIKit30Module,\n            dependencies: [\n                .module(resolvedOpenAPIKitCoreModule, conditions: []),\n            ]\n        )\n\n        let resolvedOpenAPIKitCompatModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: openAPIKitCompatModule,\n            dependencies: [\n                .module(resolvedOpenAPIKit30Module, conditions: []),\n                .module(resolvedOpenAPIKitModule, conditions: []),\n            ]\n        )\n\n        // Resolved products\n        let resolvedOpenAPIKitProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: openAPIKitProduct,\n            modules: IdentifiableSet([resolvedOpenAPIKitModule])\n        )\n\n        let resolvedOpenAPIKit30Product = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: openAPIKit30Product,\n            modules: IdentifiableSet([resolvedOpenAPIKit30Module])\n        )\n\n        let resolvedOpenAPIKitCompatProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: openAPIKitCompatProduct,\n            modules: IdentifiableSet([resolvedOpenAPIKitCompatModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([\n                resolvedOpenAPIKitCoreModule,\n                resolvedOpenAPIKitModule,\n                resolvedOpenAPIKit30Module,\n                resolvedOpenAPIKitCompatModule,\n            ]),\n            products: [resolvedOpenAPIKitProduct, resolvedOpenAPIKit30Product, resolvedOpenAPIKitCompatProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/mattpolzin/OpenAPIKit\"))\n        )\n\n        return (\n            package: package,\n            modules: [openAPIKitCoreModule, openAPIKitModule, openAPIKit30Module, openAPIKitCompatModule],\n            products: [openAPIKitProduct, openAPIKit30Product, openAPIKitCompatProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [\n                resolvedOpenAPIKitCoreModule,\n                resolvedOpenAPIKitModule,\n                resolvedOpenAPIKit30Module,\n                resolvedOpenAPIKitCompatModule,\n            ],\n            resolvedProducts: [resolvedOpenAPIKitProduct, resolvedOpenAPIKit30Product, resolvedOpenAPIKitCompatProduct],\n            packageRef: packageRef\n        )\n    }\n\n    // MARK: - swift-http-types Package\n\n    static func createSwiftHTTPTypesPackage() throws -> (\n        package: Package,\n        modules: [Module],\n        products: [Product],\n        resolvedPackage: ResolvedPackage,\n        resolvedModules: [ResolvedModule],\n        resolvedProducts: [ResolvedProduct],\n        packageRef: PackageReference\n    ) {\n        let identity = PackageIdentity.plain(\"swift-http-types\")\n\n        // Modules\n        let httpTypesModule = self.createSwiftModule(name: \"HTTPTypes\")\n\n        // Products\n        let httpTypesProduct = try Product(\n            package: identity,\n            name: \"HTTPTypes\",\n            type: .library(.automatic),\n            modules: [httpTypesModule]\n        )\n\n        // Package\n        let package = self.createPackage(\n            identity: identity,\n            displayName: \"swift-http-types\",\n            path: \"/swift-http-types\",\n            modules: [httpTypesModule],\n            products: [httpTypesProduct]\n        )\n\n        // Resolved modules\n        let resolvedHTTPTypesModule = self.createResolvedModule(\n            packageIdentity: identity,\n            module: httpTypesModule\n        )\n\n        // Resolved products\n        let resolvedHTTPTypesProduct = self.createResolvedProduct(\n            packageIdentity: identity,\n            product: httpTypesProduct,\n            modules: IdentifiableSet([resolvedHTTPTypesModule])\n        )\n\n        // Resolved package\n        let resolvedPackage = self.createResolvedPackage(\n            package: package,\n            modules: IdentifiableSet([resolvedHTTPTypesModule]),\n            products: [resolvedHTTPTypesProduct]\n        )\n\n        // Package reference\n        let packageRef = PackageReference(\n            identity: identity,\n            kind: .remoteSourceControl(SourceControlURL(\"https://github.com/apple/swift-http-types.git\"))\n        )\n\n        return (\n            package: package,\n            modules: [httpTypesModule],\n            products: [httpTypesProduct],\n            resolvedPackage: resolvedPackage,\n            resolvedModules: [resolvedHTTPTypesModule],\n            resolvedProducts: [resolvedHTTPTypesProduct],\n            packageRef: packageRef\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/invalid-cyclonedx-1-missing-fields.json",
    "content": "{\n    \"bomFormat\": \"CycloneDX\"\n}"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/invalid-cyclonedx-1-small.json",
    "content": "[1, 2, 3]"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/invalid-cyclonedx-1.7-uppercase-uuid.json",
    "content": "{\n  \"$schema\" : \"http://cyclonedx.org/schema/bom-1.7.schema.json\",\n  \"bomFormat\" : \"CycloneDX\",\n  \"components\" : [\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPMPackageTests\",\n      \"name\" : \"SwiftPMPackageTests\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPMPackageTests\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPM\",\n      \"name\" : \"SwiftPM\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPM\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPM-auto\",\n      \"name\" : \"SwiftPM-auto\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPM-auto\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPMDataModel\",\n      \"name\" : \"SwiftPMDataModel\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPMDataModel\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPMDataModel-auto\",\n      \"name\" : \"SwiftPMDataModel-auto\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPMDataModel-auto\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:XCBuildSupport\",\n      \"name\" : \"XCBuildSupport\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/XCBuildSupport\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:PackageDescription\",\n      \"name\" : \"PackageDescription\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/PackageDescription\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:AppleProductTypes\",\n      \"name\" : \"AppleProductTypes\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/AppleProductTypes\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:PackagePlugin\",\n      \"name\" : \"PackagePlugin\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/PackagePlugin\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:PackageCollectionsModel\",\n      \"name\" : \"PackageCollectionsModel\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/PackageCollectionsModel\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPMPackageCollections\",\n      \"name\" : \"SwiftPMPackageCollections\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPMPackageCollections\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swiftpm-testing-helper\",\n      \"name\" : \"swiftpm-testing-helper\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swiftpm-testing-helper\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-test\",\n      \"name\" : \"swift-test\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-test\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-sdk\",\n      \"name\" : \"swift-sdk\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-sdk\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-run\",\n      \"name\" : \"swift-run\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-run\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-package-registry\",\n      \"name\" : \"swift-package-registry\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-package-registry\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-package-manager\",\n      \"name\" : \"swift-package-manager\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-package-manager\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-package-collection\",\n      \"name\" : \"swift-package-collection\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-package-collection\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-package\",\n      \"name\" : \"swift-package\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-package\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-experimental-sdk\",\n      \"name\" : \"swift-experimental-sdk\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-experimental-sdk\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-build-prebuilts\",\n      \"name\" : \"swift-build-prebuilts\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-build-prebuilts\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-build\",\n      \"name\" : \"swift-build\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-build\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-bootstrap\",\n      \"name\" : \"swift-bootstrap\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-bootstrap\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:package-info\",\n      \"name\" : \"package-info\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/package-info\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:dummy-swiftc\",\n      \"name\" : \"dummy-swiftc\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/dummy-swiftc\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager\",\n      \"name\" : \"swift-package-manager\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/echeng3805/swift-package-manager\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:swbuild\",\n      \"name\" : \"swbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/swbuild@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBBuildServiceBundle\",\n      \"name\" : \"SWBBuildServiceBundle\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBBuildServiceBundle@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SwiftBuild\",\n      \"name\" : \"SwiftBuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SwiftBuild@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBProtocol\",\n      \"name\" : \"SWBProtocol\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBProtocol@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBUtil\",\n      \"name\" : \"SWBUtil\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBUtil@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBProjectModel\",\n      \"name\" : \"SWBProjectModel\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBProjectModel@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBBuildService\",\n      \"name\" : \"SWBBuildService\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBBuildService@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build\",\n      \"name\" : \"swift-build\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-driver\",\n      \"name\" : \"swift-driver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-help\",\n      \"name\" : \"swift-help\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/swift-help@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"name\" : \"swift-build-sdk-interfaces\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/swift-build-sdk-interfaces@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriver\",\n      \"name\" : \"SwiftDriver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/SwiftDriver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriverDynamic\",\n      \"name\" : \"SwiftDriverDynamic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/SwiftDriverDynamic@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftOptions\",\n      \"name\" : \"SwiftOptions\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/SwiftOptions@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriverExecution\",\n      \"name\" : \"SwiftDriverExecution\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/SwiftDriverExecution@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver\",\n      \"name\" : \"swift-driver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:TSCBasic\",\n      \"name\" : \"TSCBasic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-tools-support-core/TSCBasic@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"name\" : \"SwiftToolsSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-tools-support-core/SwiftToolsSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"name\" : \"SwiftToolsSupport-auto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-tools-support-core/SwiftToolsSupport-auto@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"name\" : \"TSCTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-tools-support-core/TSCTestSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core\",\n      \"name\" : \"swift-tools-support-core\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:Swift-DocC\",\n      \"name\" : \"Swift-DocC\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-docc-plugin/Swift-DocC@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"name\" : \"Swift-DocC Preview\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-docc-plugin/Swift-DocC Preview@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:snippet-extract\",\n      \"name\" : \"snippet-extract\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-docc-plugin/snippet-extract@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin\",\n      \"name\" : \"swift-docc-plugin\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin@1.4.5\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"1.4.5\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"name\" : \"SymbolKit\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-docc-symbolkit/SymbolKit@b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-symbolkit\",\n      \"name\" : \"swift-docc-symbolkit\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit@1.0.0\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.0.0\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite:sqlite\",\n      \"name\" : \"sqlite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-toolchain-sqlite/sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"name\" : \"SwiftToolchainCSQLite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-toolchain-sqlite/SwiftToolchainCSQLite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite\",\n      \"name\" : \"swift-toolchain-sqlite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-certificates:X509\",\n      \"name\" : \"X509\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-certificates/X509@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n    },\n    {\n      \"bom-ref\" : \"swift-certificates\",\n      \"name\" : \"swift-certificates\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-certificates@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n    },\n    {\n      \"bom-ref\" : \"swift-asn1:SwiftASN1\",\n      \"name\" : \"SwiftASN1\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-asn1/SwiftASN1@40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n    },\n    {\n      \"bom-ref\" : \"swift-asn1\",\n      \"name\" : \"swift-asn1\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-asn1@1.5.0\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.5.0\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:BitCollections\",\n      \"name\" : \"BitCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/BitCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:DequeModule\",\n      \"name\" : \"DequeModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/DequeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:HashTreeCollections\",\n      \"name\" : \"HashTreeCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/HashTreeCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:HeapModule\",\n      \"name\" : \"HeapModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/HeapModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:OrderedCollections\",\n      \"name\" : \"OrderedCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/OrderedCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:_RopeModule\",\n      \"name\" : \"_RopeModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/_RopeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:Collections\",\n      \"name\" : \"Collections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/Collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections\",\n      \"name\" : \"swift-collections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-system:SystemPackage\",\n      \"name\" : \"SystemPackage\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-system/SystemPackage@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n    },\n    {\n      \"bom-ref\" : \"swift-system\",\n      \"name\" : \"swift-system\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-system@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto:Crypto\",\n      \"name\" : \"Crypto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-crypto/Crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto:_CryptoExtras\",\n      \"name\" : \"_CryptoExtras\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-crypto/_CryptoExtras@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto\",\n      \"name\" : \"swift-crypto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:ArgumentParser\",\n      \"name\" : \"ArgumentParser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-argument-parser/ArgumentParser@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:GenerateManual\",\n      \"name\" : \"GenerateManual\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-argument-parser/GenerateManual@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:generate-manual\",\n      \"name\" : \"generate-manual\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-argument-parser/generate-manual@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser\",\n      \"name\" : \"swift-argument-parser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-argument-parser@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftBasicFormat\",\n      \"name\" : \"SwiftBasicFormat\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftBasicFormat@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"name\" : \"SwiftCompilerPlugin\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftCompilerPlugin@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftDiagnostics\",\n      \"name\" : \"SwiftDiagnostics\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftDiagnostics@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftIDEUtils\",\n      \"name\" : \"SwiftIDEUtils\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftIDEUtils@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftIfConfig\",\n      \"name\" : \"SwiftIfConfig\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftIfConfig@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"name\" : \"SwiftLexicalLookup\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftLexicalLookup@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftOperators\",\n      \"name\" : \"SwiftOperators\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftOperators@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftParser\",\n      \"name\" : \"SwiftParser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftParser@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"name\" : \"SwiftParserDiagnostics\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftParserDiagnostics@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftRefactor\",\n      \"name\" : \"SwiftRefactor\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftRefactor@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntax\",\n      \"name\" : \"SwiftSyntax\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntax@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"name\" : \"SwiftSyntaxBuilder\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxBuilder@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"name\" : \"SwiftSyntaxMacros\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacros@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"name\" : \"SwiftSyntaxMacroExpansion\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacroExpansion@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"name\" : \"SwiftSyntaxMacrosTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacrosTestSupport@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"name\" : \"SwiftSyntaxMacrosGenericTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacrosGenericTestSupport@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"name\" : \"_SwiftCompilerPluginMessageHandling\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/_SwiftCompilerPluginMessageHandling@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"name\" : \"_SwiftLibraryPluginProvider\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/_SwiftLibraryPluginProvider@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax\",\n      \"name\" : \"swift-syntax\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuild\",\n      \"name\" : \"llbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:libllbuild\",\n      \"name\" : \"libllbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/libllbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildSwift\",\n      \"name\" : \"llbuildSwift\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/llbuildSwift@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildAnalysis\",\n      \"name\" : \"llbuildAnalysis\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/llbuildAnalysis@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"name\" : \"llbuildSwiftDynamic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/llbuildSwiftDynamic@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild\",\n      \"name\" : \"swift-llbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    }\n  ],\n  \"dependencies\" : [\n    {\n      \"dependsOn\" : [\n        \"swift-build\",\n        \"swift-driver\",\n        \"swift-tools-support-core\",\n        \"swift-docc-plugin\",\n        \"swift-docc-symbolkit\",\n        \"swift-toolchain-sqlite\",\n        \"swift-certificates\",\n        \"swift-asn1\",\n        \"swift-collections\",\n        \"swift-system\",\n        \"swift-crypto\",\n        \"swift-argument-parser\",\n        \"swift-syntax\",\n        \"swift-llbuild\",\n        \"swift-package-manager:SwiftPMPackageTests\",\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPM-auto\",\n        \"swift-package-manager:SwiftPMDataModel\",\n        \"swift-package-manager:SwiftPMDataModel-auto\",\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-package-manager:PackageDescription\",\n        \"swift-package-manager:AppleProductTypes\",\n        \"swift-package-manager:PackagePlugin\",\n        \"swift-package-manager:PackageCollectionsModel\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-package-manager:swiftpm-testing-helper\",\n        \"swift-package-manager:swift-test\",\n        \"swift-package-manager:swift-sdk\",\n        \"swift-package-manager:swift-run\",\n        \"swift-package-manager:swift-package-registry\",\n        \"swift-package-manager:swift-package-manager\",\n        \"swift-package-manager:swift-package-collection\",\n        \"swift-package-manager:swift-package\",\n        \"swift-package-manager:swift-experimental-sdk\",\n        \"swift-package-manager:swift-build-prebuilts\",\n        \"swift-package-manager:swift-build\",\n        \"swift-package-manager:swift-bootstrap\",\n        \"swift-package-manager:package-info\",\n        \"swift-package-manager:dummy-swiftc\"\n      ],\n      \"ref\" : \"swift-package-manager\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\"\n      ],\n      \"ref\" : \"swift-build\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"ref\" : \"swift-driver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\"\n      ],\n      \"ref\" : \"swift-tools-support-core\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"ref\" : \"swift-docc-symbolkit\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"ref\" : \"swift-toolchain-sqlite\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-certificates:X509\"\n      ],\n      \"ref\" : \"swift-certificates\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"ref\" : \"swift-asn1\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\"\n      ],\n      \"ref\" : \"swift-collections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-system\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"ref\" : \"swift-crypto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"ref\" : \"swift-argument-parser\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\"\n      ],\n      \"ref\" : \"swift-syntax\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\"\n      ],\n      \"ref\" : \"swift-llbuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:PackagePlugin\",\n        \"swift-package-manager:PackageDescription\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-package-manager:swift-package-manager\",\n        \"swift-package-manager:dummy-swiftc\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPMPackageTests\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPM\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPM-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPMDataModel\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPMDataModel-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager:XCBuildSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:PackageDescription\"\n      ],\n      \"ref\" : \"swift-package-manager:PackageDescription\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:PackageDescription\"\n      ],\n      \"ref\" : \"swift-package-manager:AppleProductTypes\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-crypto:Crypto\",\n        \"swift-certificates:X509\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPMPackageCollections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"ref\" : \"swift-package-manager:swift-build-prebuilts\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager:swift-bootstrap\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\"\n      ],\n      \"ref\" : \"swift-package-manager:package-info\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBBuildServiceBundle\"\n      ],\n      \"ref\" : \"swift-build:swbuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBBuildService\",\n        \"swift-build:SWBUtil\"\n      ],\n      \"ref\" : \"swift-build:SWBBuildServiceBundle\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\"\n      ],\n      \"ref\" : \"swift-build:SwiftBuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBUtil\"\n      ],\n      \"ref\" : \"swift-build:SWBProtocol\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-build:SWBUtil\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBProtocol\"\n      ],\n      \"ref\" : \"swift-build:SWBProjectModel\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-build:SWBBuildService\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriverExecution\",\n        \"swift-driver:SwiftDriver\"\n      ],\n      \"ref\" : \"swift-driver:swift-driver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:swift-help\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"ref\" : \"swift-driver:swift-build-sdk-interfaces\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriverDynamic\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftOptions\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriverExecution\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"ref\" : \"swift-tools-support-core:SwiftToolsSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"ref\" : \"swift-tools-support-core:SwiftToolsSupport-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\"\n      ],\n      \"ref\" : \"swift-tools-support-core:TSCTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin:Swift-DocC\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin:Swift-DocC Preview\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"ref\" : \"swift-docc-plugin:snippet-extract\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"ref\" : \"swift-toolchain-sqlite:sqlite\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"ref\" : \"swift-certificates:X509\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\"\n      ],\n      \"ref\" : \"swift-collections:Collections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"ref\" : \"swift-crypto:_CryptoExtras\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"ref\" : \"swift-argument-parser:GenerateManual\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"ref\" : \"swift-argument-parser:generate-manual\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftBasicFormat\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:SwiftSyntaxMacros\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftCompilerPlugin\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftDiagnostics\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftIDEUtils\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftIfConfig\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftIfConfig\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftLexicalLookup\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftOperators\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftParser\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftParserDiagnostics\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftRefactor\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxBuilder\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacros\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacroExpansion\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"ref\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n      ],\n      \"ref\" : \"swift-syntax:_SwiftLibraryPluginProvider\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildSwift\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildAnalysis\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildSwiftDynamic\"\n    }\n  ],\n  \"metadata\" : {\n    \"component\" : {\n      \"bom-ref\" : \"swift-package-manager\",\n      \"name\" : \"swift-package-manager\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/echeng3805/swift-package-manager\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    \"timestamp\" : \"2025-10-23T17:33:11Z\"\n  },\n  \"serialNumber\" : \"urn:uuid:DC760B5E-9DB5-4B71-8FBC-8BBADDDC027B\",\n  \"specVersion\" : \"1.7\",\n  \"version\" : 1\n}"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/invalid-cyclonedx-1.7-wrong-bomformat.json",
    "content": "{\n    \"bomFormat\": \"WrongFormat\",\n    \"specVersion\": \"1.7\",\n    \"serialNumber\": \"urn:uuid:12345678-1234-1234-1234-123456789abc\",\n    \"version\": 1,\n    \"metadata\": {\n        \"timestamp\": \"2025-01-01T00:00:00Z\",\n        \"component\": {\n            \"type\": \"application\",\n            \"bom-ref\": \"test-app\",\n            \"name\": \"TestApp\",\n            \"version\": \"1.0.0\"\n        }\n    }\n}"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/invalid-spdx-3-small.json",
    "content": "{ invalid json }"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/invalid-spdx-3.0.1-no-iri.json",
    "content": "{\n  \"@context\" : \"https://spdx.org/rdf/3.0.1/spdx-context.jsonld\",\n  \"@graph\" : [\n    {\n      \"@id\" : \"urn:uuid:2a24c08d-e1ae-4e53-a92d-3187ad997dfc:creationInfo\",\n      \"created\" : \"1970-01-01T00:00:00Z\",\n      \"createdBy\" : [\n        \"urn:uuid:2a24c08d-e1ae-4e53-a92d-3187ad997dfc\"\n      ],\n      \"specVersion\" : \"6.3.0-dev\",\n      \"type\" : \"CreationInfo\"\n    },\n    {\n      \"creationInfo\" : \"urn:uuid:2a24c08d-e1ae-4e53-a92d-3187ad997dfc:creationInfo\",\n      \"name\" : \"swift-package-manager\",\n      \"spdxId\" : \"urn:uuid:2a24c08d-e1ae-4e53-a92d-3187ad997dfc\",\n      \"type\" : \"Agent\"\n    },\n    {\n      \"@id\" : \"_:creationInfo\",\n      \"created\" : \"2025-10-30T21:29:42Z\",\n      \"createdBy\" : [\n        \"urn:uuid:2a24c08d-e1ae-4e53-a92d-3187ad997dfc\"\n      ],\n      \"specVersion\" : \"3.0.1\",\n      \"type\" : \"CreationInfo\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"profileConformance\" : [\n        \"core\",\n        \"software\"\n      ],\n      \"rootElement\" : [\n        \"swift-package-manager-fork\"\n      ],\n      \"spdxId\" : \"urn:uuid:urn:uuid:438b9a71-7a36-49b6-a550-c049ae628b07\",\n      \"type\" : \"software_Sbom\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:uuid:urn:uuid:438b9a71-7a36-49b6-a550-c049ae628b07\",\n      \"relationshipType\" : \"describes\",\n      \"spdxId\" : \"urn:uuid:urn:uuid:438b9a71-7a36-49b6-a550-c049ae628b07-describes-swift-package-manager-fork\",\n      \"to\" : [\n        \"swift-package-manager-fork\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"profileConformance\" : [\n        \"core\",\n        \"software\"\n      ],\n      \"rootElement\" : [\n        \"urn:uuid:urn:uuid:438b9a71-7a36-49b6-a550-c049ae628b07\"\n      ],\n      \"spdxId\" : \"urn:uuid:f2e4c92c-bd82-4bd0-b909-b626887c5db3\",\n      \"type\" : \"SpdxDocument\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMPackageTests\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMPackageTests@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageTests\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPM\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPM@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPM-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPM-auto@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMDataModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMDataModel@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMDataModel-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMDataModel-auto@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"XCBuildSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:XCBuildSupport@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:XCBuildSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackageDescription\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackageDescription@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackageDescription\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"AppleProductTypes\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:AppleProductTypes@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:AppleProductTypes\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackagePlugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackagePlugin@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackagePlugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackageCollectionsModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackageCollectionsModel@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackageCollectionsModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMPackageCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMPackageCollections@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swiftpm-testing-helper\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swiftpm-testing-helper@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swiftpm-testing-helper\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-test\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-test@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-test\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-sdk\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-sdk@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-sdk\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-run\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-run@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-run\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-registry\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-registry@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-registry\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-manager\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-manager@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-manager\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-collection\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-collection@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-collection\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-experimental-sdk\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-experimental-sdk@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-experimental-sdk\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build-prebuilts\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-build-prebuilts@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build-prebuilts\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-build@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-bootstrap\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-bootstrap@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-bootstrap\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"package-info\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:package-info@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:package-info\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"dummy-swiftc\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:dummy-swiftc@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:dummy-swiftc\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-package-manager-fork>\",\n      \"name\" : \"swift-package-manager-fork\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:swbuild@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build:swbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBBuildServiceBundle\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBBuildServiceBundle@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftBuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SwiftBuild@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SwiftBuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBProtocol\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBProtocol@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBProtocol\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBUtil\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBUtil@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBUtil\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBProjectModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBProjectModel@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBProjectModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBBuildService\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBBuildService@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBBuildService\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-build>\",\n      \"name\" : \"swift-build\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-driver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-driver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-help\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-help@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-help\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build-sdk-interfaces\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-build-sdk-interfaces@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriverDynamic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriverDynamic@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftOptions\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftOptions@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftOptions\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriverExecution\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriverExecution@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-driver>\",\n      \"name\" : \"swift-driver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"TSCBasic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:TSCBasic@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:TSCBasic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolsSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:SwiftToolsSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolsSupport-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:SwiftToolsSupport-auto@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"TSCTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:TSCTestSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-tools-support-core>\",\n      \"name\" : \"swift-tools-support-core\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Swift-DocC\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:Swift-DocC@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Swift-DocC Preview\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:Swift-DocC Preview@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"snippet-extract\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:snippet-extract@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-docc-plugin>\",\n      \"name\" : \"swift-docc-plugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-docc-plugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SymbolKit\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit:SymbolKit@1.0.0\",\n      \"software_packageVersion\" : \"1.0.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-docc-symbolkit>\",\n      \"name\" : \"swift-docc-symbolkit\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit@1.0.0\",\n      \"software_packageVersion\" : \"1.0.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-symbolkit\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"sqlite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite:sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolchainCSQLite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite:SwiftToolchainCSQLite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-toolchain-sqlite>\",\n      \"name\" : \"swift-toolchain-sqlite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-toolchain-sqlite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"X509\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-certificates:X509@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_packageVersion\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-certificates:X509\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-certificates>\",\n      \"name\" : \"swift-certificates\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-certificates@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_packageVersion\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-certificates\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftASN1\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-asn1:SwiftASN1@1.5.0\",\n      \"software_packageVersion\" : \"1.5.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-asn1:SwiftASN1\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-asn1>\",\n      \"name\" : \"swift-asn1\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-asn1@1.5.0\",\n      \"software_packageVersion\" : \"1.5.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-asn1\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"BitCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:BitCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:BitCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"DequeModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:DequeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:DequeModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"HashTreeCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:HashTreeCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:HashTreeCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"HeapModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:HeapModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:HeapModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"OrderedCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:OrderedCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:OrderedCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_RopeModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:_RopeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:_RopeModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Collections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:Collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:Collections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-collections>\",\n      \"name\" : \"swift-collections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SystemPackage\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-system:SystemPackage@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_packageVersion\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-system:SystemPackage\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-system>\",\n      \"name\" : \"swift-system\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-system@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_packageVersion\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-system\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Crypto\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto:Crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto:Crypto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_CryptoExtras\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto:_CryptoExtras@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-crypto>\",\n      \"name\" : \"swift-crypto\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"ArgumentParser\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:ArgumentParser@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:ArgumentParser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"GenerateDoccReference\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:GenerateDoccReference@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:GenerateDoccReference\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"GenerateManual\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:GenerateManual@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"generate-manual\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:generate-manual@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"generate-docc-reference\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:generate-docc-reference@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser:generate-docc-reference\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-argument-parser>\",\n      \"name\" : \"swift-argument-parser\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftBasicFormat\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftBasicFormat@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftCompilerPlugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftCompilerPlugin@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDiagnostics\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftDiagnostics@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftIDEUtils\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftIDEUtils@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftIfConfig\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftIfConfig@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftLexicalLookup\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftLexicalLookup@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftOperators\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftOperators@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftParser\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftParser@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftParser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftParserDiagnostics\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftParserDiagnostics@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftRefactor\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftRefactor@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntax\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntax@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntax\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxBuilder\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxBuilder@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacros\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacros@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacroExpansion\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacroExpansion@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacrosTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacrosTestSupport@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacrosGenericTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacrosGenericTestSupport@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_SwiftCompilerPluginMessageHandling\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:_SwiftCompilerPluginMessageHandling@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_SwiftLibraryPluginProvider\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:_SwiftLibraryPluginProvider@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-syntax>\",\n      \"name\" : \"swift-syntax\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-llbuild:llbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"libllbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:libllbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:libllbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildSwift\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildSwift@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildAnalysis\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildAnalysis@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildSwiftDynamic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildSwiftDynamic@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-llbuild>\",\n      \"name\" : \"swift-llbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-llbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork-dependsOn\",\n      \"to\" : [\n        \"swift-build\",\n        \"swift-driver\",\n        \"swift-tools-support-core\",\n        \"swift-docc-plugin\",\n        \"swift-docc-symbolkit\",\n        \"swift-toolchain-sqlite\",\n        \"swift-certificates\",\n        \"swift-asn1\",\n        \"swift-collections\",\n        \"swift-system\",\n        \"swift-crypto\",\n        \"swift-argument-parser\",\n        \"swift-syntax\",\n        \"swift-llbuild\",\n        \"swift-package-manager-fork:SwiftPMPackageTests\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPM-auto\",\n        \"swift-package-manager-fork:SwiftPMDataModel\",\n        \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:AppleProductTypes\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageCollectionsModel\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-package-manager-fork:swiftpm-testing-helper\",\n        \"swift-package-manager-fork:swift-test\",\n        \"swift-package-manager-fork:swift-sdk\",\n        \"swift-package-manager-fork:swift-run\",\n        \"swift-package-manager-fork:swift-package-registry\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:swift-package-collection\",\n        \"swift-package-manager-fork:swift-package\",\n        \"swift-package-manager-fork:swift-experimental-sdk\",\n        \"swift-package-manager-fork:swift-build-prebuilts\",\n        \"swift-package-manager-fork:swift-build\",\n        \"swift-package-manager-fork:swift-bootstrap\",\n        \"swift-package-manager-fork:package-info\",\n        \"swift-package-manager-fork:dummy-swiftc\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork\",\n      \"relationshipType\" : \"hasTest\",\n      \"spdxId\" : \"swift-package-manager-fork-hasTest\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPMPackageTests\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build-dependsOn\",\n      \"to\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-symbolkit\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-symbolkit-dependsOn\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-toolchain-sqlite-dependsOn\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-certificates-dependsOn\",\n      \"to\" : [\n        \"swift-certificates:X509\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-asn1\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-asn1-dependsOn\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-collections-dependsOn\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-system\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-system-dependsOn\",\n      \"to\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-crypto-dependsOn\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateDoccReference\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\",\n        \"swift-argument-parser:generate-docc-reference\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMPackageTests\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageTests-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:dummy-swiftc\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPM\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPM-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-auto-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMDataModel\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-auto-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:XCBuildSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:XCBuildSupport-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:AppleProductTypes\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:AppleProductTypes-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:PackageDescription\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMPackageCollections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageCollections-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-crypto:Crypto\",\n        \"swift-certificates:X509\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-build-prebuilts\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build-prebuilts-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-bootstrap\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-bootstrap-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:package-info\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:package-info-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:swbuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:swbuild-dependsOn\",\n      \"to\" : [\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBBuildServiceBundle\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildServiceBundle\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBBuildService\",\n        \"swift-build:SWBUtil\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SwiftBuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SwiftBuild-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProtocol\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBProtocol-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBUtil\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBUtil\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBUtil-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProjectModel\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBProjectModel-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBProtocol\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildService\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBBuildService-dependsOn\",\n      \"to\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-driver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-driver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriverExecution\",\n        \"swift-driver:SwiftDriver\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-help\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-help-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverDynamic\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftOptions\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftOptions-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverExecution\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:snippet-extract\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract-dependsOn\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite:sqlite\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite-dependsOn\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates:X509\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-certificates:X509-dependsOn\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:Collections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-collections:Collections-dependsOn\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto:_CryptoExtras\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras-dependsOn\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateDoccReference\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:GenerateDoccReference-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:generate-docc-reference\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateManual\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-manual\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-docc-reference\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:generate-docc-reference-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftBasicFormat\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:SwiftSyntaxMacros\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftDiagnostics\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIDEUtils\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIfConfig\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftIfConfig\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftOperators\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParser\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftParser-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftRefactor\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwift\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildAnalysis\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-argument-parser.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3-generates\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateDoccReference\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\",\n        \"swift-argument-parser:generate-docc-reference\",\n        \"swift-argument-parser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-plugin\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06-generates\",\n      \"to\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\",\n        \"swift-docc-plugin\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"ef033f4611f44b911592b609e2df015f01086d69-generates\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\",\n        \"swift-syntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507-generates\",\n      \"to\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\",\n        \"swift-build\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-system.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6-generates\",\n      \"to\" : [\n        \"swift-system:SystemPackage\",\n        \"swift-system\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-toolchain-sqlite.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff-generates\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n        \"swift-toolchain-sqlite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-generates\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPMPackageTests\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPM-auto\",\n        \"swift-package-manager-fork:SwiftPMDataModel\",\n        \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:AppleProductTypes\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageCollectionsModel\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-package-manager-fork:swiftpm-testing-helper\",\n        \"swift-package-manager-fork:swift-test\",\n        \"swift-package-manager-fork:swift-sdk\",\n        \"swift-package-manager-fork:swift-run\",\n        \"swift-package-manager-fork:swift-package-registry\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:swift-package-collection\",\n        \"swift-package-manager-fork:swift-package\",\n        \"swift-package-manager-fork:swift-experimental-sdk\",\n        \"swift-package-manager-fork:swift-build-prebuilts\",\n        \"swift-package-manager-fork:swift-build\",\n        \"swift-package-manager-fork:swift-bootstrap\",\n        \"swift-package-manager-fork:package-info\",\n        \"swift-package-manager-fork:dummy-swiftc\",\n        \"swift-package-manager-fork\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-crypto.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70-generates\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\",\n        \"swift-crypto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-certificates.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"386001a92200c70fd06217b3ccad58d7226edb84-generates\",\n      \"to\" : [\n        \"swift-certificates:X509\",\n        \"swift-certificates\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d-generates\",\n      \"to\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\",\n        \"swift-driver\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-symbolkit\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"b45d1f2ed151d057b54504d653e0da5552844e34-generates\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\",\n        \"swift-docc-symbolkit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"c11818f3cae0780656baa430b49e7f163f08dffd-generates\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\",\n        \"swift-collections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-llbuild.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f-generates\",\n      \"to\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\",\n        \"swift-llbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-asn1.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d-generates\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"swift-asn1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-tools-support-core.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1-generates\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"swift-tools-support-core\"\n      ],\n      \"type\" : \"Relationship\"\n    }\n  ]\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/invalid-spdx-3.0.1-spm.json",
    "content": "{\n  \"@context\" : \"https://spdx.org/rdf/3.0.1/spdx-context.jsonld\",\n  \"@graph\" : [\n    {\n      \"@id\" : \"6a9fc944-6ec0-491c-ba29-068e186e7cbd:creationInfo\",\n      \"created\" : \"1970-01-01T00:00:00Z\",\n      \"createdBy\" : [\n        \"6a9fc944-6ec0-491c-ba29-068e186e7cbd\"\n      ],\n      \"specVersion\" : \"6.3.0-dev\",\n      \"type\" : \"CreationInfo\"\n    },\n    {\n      \"creationInfo\" : \"6a9fc944-6ec0-491c-ba29-068e186e7cbd:creationInfo\",\n      \"name\" : \"Swift Package Manager\",\n      \"spdxId\" : \"6a9fc944-6ec0-491c-ba29-068e186e7cbd\",\n      \"type\" : \"Agent\"\n    },\n    {\n      \"@id\" : \"_:creationInfo\",\n      \"created\" : \"2025-10-23T20:21:19Z\",\n      \"createdBy\" : [\n        \"6a9fc944-6ec0-491c-ba29-068e186e7cbd\"\n      ],\n      \"specVersion\" : \"3.0.1\",\n      \"type\" : \"CreationInfo\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"profileConformance\" : [\n        \"core\",\n        \"software\"\n      ],\n      \"rootElement\" : [\n        \"swift-package-manager\"\n      ],\n      \"spdxId\" : \"urn:uuid:b2c3a0f9-1489-4bbc-9760-936838e10768\",\n      \"type\" : \"software_Sbom\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:uuid:b2c3a0f9-1489-4bbc-9760-936838e10768\",\n      \"relationshipType\" : \"describes\",\n      \"spdxId\" : \"urn:uuid:b2c3a0f9-1489-4bbc-9760-936838e10768-describes-swift-package-manager\",\n      \"to\" : [\n        \"swift-package-manager\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"profileConformance\" : [\n        \"core\",\n        \"software\"\n      ],\n      \"rootElement\" : [\n        \"urn:uuid:b2c3a0f9-1489-4bbc-9760-936838e10768\"\n      ],\n      \"spdxId\" : \"urn:uuid:b9814532-71e2-4061-aed3-da6160964576\",\n      \"type\" : \"SpdxDocument\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMPackageTests\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/SwiftPMPackageTests\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:SwiftPMPackageTests\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPM\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/SwiftPM\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:SwiftPM\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPM-auto\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/SwiftPM-auto\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:SwiftPM-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMDataModel\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/SwiftPMDataModel\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:SwiftPMDataModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMDataModel-auto\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/SwiftPMDataModel-auto\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:SwiftPMDataModel-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"XCBuildSupport\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/XCBuildSupport\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:XCBuildSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackageDescription\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/PackageDescription\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:PackageDescription\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"AppleProductTypes\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/AppleProductTypes\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:AppleProductTypes\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackagePlugin\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/PackagePlugin\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:PackagePlugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackageCollectionsModel\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/PackageCollectionsModel\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:PackageCollectionsModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMPackageCollections\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/SwiftPMPackageCollections\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager:SwiftPMPackageCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swiftpm-testing-helper\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swiftpm-testing-helper\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swiftpm-testing-helper\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-test\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-test\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-test\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-sdk\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-sdk\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-sdk\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-run\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-run\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-run\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-registry\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-package-registry\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-package-registry\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-manager\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-package-manager\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-package-manager\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-collection\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-package-collection\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-package-collection\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-package\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-package\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-experimental-sdk\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-experimental-sdk\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-experimental-sdk\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build-prebuilts\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-build-prebuilts\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-build-prebuilts\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-build\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-build\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-bootstrap\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/swift-bootstrap\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:swift-bootstrap\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"package-info\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/package-info\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:package-info\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"dummy-swiftc\",\n      \"packageUrl\" : \"pkg:swift/swift-package-manager/dummy-swiftc\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager:dummy-swiftc\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-package-manager>\",\n      \"name\" : \"swift-package-manager\",\n      \"packageUrl\" : \"pkg:swift/echeng3805/swift-package-manager\",\n      \"software_packageVersion\" : \"unknown\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swbuild\",\n      \"packageUrl\" : \"pkg:swift/swift-build/swbuild@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_packageVersion\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build:swbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBBuildServiceBundle\",\n      \"packageUrl\" : \"pkg:swift/swift-build/SWBBuildServiceBundle@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_packageVersion\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftBuild\",\n      \"packageUrl\" : \"pkg:swift/swift-build/SwiftBuild@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_packageVersion\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SwiftBuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBProtocol\",\n      \"packageUrl\" : \"pkg:swift/swift-build/SWBProtocol@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_packageVersion\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBProtocol\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBUtil\",\n      \"packageUrl\" : \"pkg:swift/swift-build/SWBUtil@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_packageVersion\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBUtil\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBProjectModel\",\n      \"packageUrl\" : \"pkg:swift/swift-build/SWBProjectModel@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_packageVersion\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBProjectModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBBuildService\",\n      \"packageUrl\" : \"pkg:swift/swift-build/SWBBuildService@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_packageVersion\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBBuildService\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-build>\",\n      \"name\" : \"swift-build\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_packageVersion\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-driver\",\n      \"packageUrl\" : \"pkg:swift/swift-driver/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-driver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-help\",\n      \"packageUrl\" : \"pkg:swift/swift-driver/swift-help@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-help\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build-sdk-interfaces\",\n      \"packageUrl\" : \"pkg:swift/swift-driver/swift-build-sdk-interfaces@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriver\",\n      \"packageUrl\" : \"pkg:swift/swift-driver/SwiftDriver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriverDynamic\",\n      \"packageUrl\" : \"pkg:swift/swift-driver/SwiftDriverDynamic@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftOptions\",\n      \"packageUrl\" : \"pkg:swift/swift-driver/SwiftOptions@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftOptions\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriverExecution\",\n      \"packageUrl\" : \"pkg:swift/swift-driver/SwiftDriverExecution@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-driver>\",\n      \"name\" : \"swift-driver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"TSCBasic\",\n      \"packageUrl\" : \"pkg:swift/swift-tools-support-core/TSCBasic@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:TSCBasic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolsSupport\",\n      \"packageUrl\" : \"pkg:swift/swift-tools-support-core/SwiftToolsSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolsSupport-auto\",\n      \"packageUrl\" : \"pkg:swift/swift-tools-support-core/SwiftToolsSupport-auto@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"TSCTestSupport\",\n      \"packageUrl\" : \"pkg:swift/swift-tools-support-core/TSCTestSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-tools-support-core>\",\n      \"name\" : \"swift-tools-support-core\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Swift-DocC\",\n      \"packageUrl\" : \"pkg:swift/swift-docc-plugin/Swift-DocC@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"software_packageVersion\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Swift-DocC Preview\",\n      \"packageUrl\" : \"pkg:swift/swift-docc-plugin/Swift-DocC Preview@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"software_packageVersion\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"snippet-extract\",\n      \"packageUrl\" : \"pkg:swift/swift-docc-plugin/snippet-extract@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"software_packageVersion\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-docc-plugin>\",\n      \"name\" : \"swift-docc-plugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-docc-plugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SymbolKit\",\n      \"packageUrl\" : \"pkg:swift/swift-docc-symbolkit/SymbolKit@b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"software_packageVersion\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-docc-symbolkit>\",\n      \"name\" : \"swift-docc-symbolkit\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit@1.0.0\",\n      \"software_packageVersion\" : \"1.0.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-symbolkit\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"sqlite\",\n      \"packageUrl\" : \"pkg:swift/swift-toolchain-sqlite/sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolchainCSQLite\",\n      \"packageUrl\" : \"pkg:swift/swift-toolchain-sqlite/SwiftToolchainCSQLite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-toolchain-sqlite>\",\n      \"name\" : \"swift-toolchain-sqlite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-toolchain-sqlite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"X509\",\n      \"packageUrl\" : \"pkg:swift/swift-certificates/X509@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_packageVersion\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-certificates:X509\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-certificates>\",\n      \"name\" : \"swift-certificates\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-certificates@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_packageVersion\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-certificates\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftASN1\",\n      \"packageUrl\" : \"pkg:swift/swift-asn1/SwiftASN1@40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"software_packageVersion\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-asn1:SwiftASN1\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-asn1>\",\n      \"name\" : \"swift-asn1\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-asn1@1.5.0\",\n      \"software_packageVersion\" : \"1.5.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-asn1\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"BitCollections\",\n      \"packageUrl\" : \"pkg:swift/swift-collections/BitCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:BitCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"DequeModule\",\n      \"packageUrl\" : \"pkg:swift/swift-collections/DequeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:DequeModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"HashTreeCollections\",\n      \"packageUrl\" : \"pkg:swift/swift-collections/HashTreeCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:HashTreeCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"HeapModule\",\n      \"packageUrl\" : \"pkg:swift/swift-collections/HeapModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:HeapModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"OrderedCollections\",\n      \"packageUrl\" : \"pkg:swift/swift-collections/OrderedCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:OrderedCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_RopeModule\",\n      \"packageUrl\" : \"pkg:swift/swift-collections/_RopeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:_RopeModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Collections\",\n      \"packageUrl\" : \"pkg:swift/swift-collections/Collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:Collections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-collections>\",\n      \"name\" : \"swift-collections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SystemPackage\",\n      \"packageUrl\" : \"pkg:swift/swift-system/SystemPackage@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_packageVersion\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-system:SystemPackage\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-system>\",\n      \"name\" : \"swift-system\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-system@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_packageVersion\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-system\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Crypto\",\n      \"packageUrl\" : \"pkg:swift/swift-crypto/Crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto:Crypto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_CryptoExtras\",\n      \"packageUrl\" : \"pkg:swift/swift-crypto/_CryptoExtras@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-crypto>\",\n      \"name\" : \"swift-crypto\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"ArgumentParser\",\n      \"packageUrl\" : \"pkg:swift/swift-argument-parser/ArgumentParser@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"software_packageVersion\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:ArgumentParser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"GenerateManual\",\n      \"packageUrl\" : \"pkg:swift/swift-argument-parser/GenerateManual@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"software_packageVersion\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"generate-manual\",\n      \"packageUrl\" : \"pkg:swift/swift-argument-parser/generate-manual@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"software_packageVersion\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-argument-parser>\",\n      \"name\" : \"swift-argument-parser\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"software_packageVersion\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftBasicFormat\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftBasicFormat@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftCompilerPlugin\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftCompilerPlugin@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDiagnostics\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftDiagnostics@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftIDEUtils\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftIDEUtils@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftIfConfig\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftIfConfig@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftLexicalLookup\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftLexicalLookup@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftOperators\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftOperators@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftParser\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftParser@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftParser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftParserDiagnostics\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftParserDiagnostics@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftRefactor\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftRefactor@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntax\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftSyntax@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntax\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxBuilder\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftSyntaxBuilder@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacros\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacros@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacroExpansion\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacroExpansion@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacrosTestSupport\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacrosTestSupport@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacrosGenericTestSupport\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacrosGenericTestSupport@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_SwiftCompilerPluginMessageHandling\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/_SwiftCompilerPluginMessageHandling@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_SwiftLibraryPluginProvider\",\n      \"packageUrl\" : \"pkg:swift/swift-syntax/_SwiftLibraryPluginProvider@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-syntax>\",\n      \"name\" : \"swift-syntax\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_packageVersion\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuild\",\n      \"packageUrl\" : \"pkg:swift/swift-llbuild/llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-llbuild:llbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"libllbuild\",\n      \"packageUrl\" : \"pkg:swift/swift-llbuild/libllbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:libllbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildSwift\",\n      \"packageUrl\" : \"pkg:swift/swift-llbuild/llbuildSwift@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildAnalysis\",\n      \"packageUrl\" : \"pkg:swift/swift-llbuild/llbuildAnalysis@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildSwiftDynamic\",\n      \"packageUrl\" : \"pkg:swift/swift-llbuild/llbuildSwiftDynamic@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-llbuild>\",\n      \"name\" : \"swift-llbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-llbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-dependsOn\",\n      \"to\" : [\n        \"swift-build\",\n        \"swift-driver\",\n        \"swift-tools-support-core\",\n        \"swift-docc-plugin\",\n        \"swift-docc-symbolkit\",\n        \"swift-toolchain-sqlite\",\n        \"swift-certificates\",\n        \"swift-asn1\",\n        \"swift-collections\",\n        \"swift-system\",\n        \"swift-crypto\",\n        \"swift-argument-parser\",\n        \"swift-syntax\",\n        \"swift-llbuild\",\n        \"swift-package-manager:SwiftPMPackageTests\",\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPM-auto\",\n        \"swift-package-manager:SwiftPMDataModel\",\n        \"swift-package-manager:SwiftPMDataModel-auto\",\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-package-manager:PackageDescription\",\n        \"swift-package-manager:AppleProductTypes\",\n        \"swift-package-manager:PackagePlugin\",\n        \"swift-package-manager:PackageCollectionsModel\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-package-manager:swiftpm-testing-helper\",\n        \"swift-package-manager:swift-test\",\n        \"swift-package-manager:swift-sdk\",\n        \"swift-package-manager:swift-run\",\n        \"swift-package-manager:swift-package-registry\",\n        \"swift-package-manager:swift-package-manager\",\n        \"swift-package-manager:swift-package-collection\",\n        \"swift-package-manager:swift-package\",\n        \"swift-package-manager:swift-experimental-sdk\",\n        \"swift-package-manager:swift-build-prebuilts\",\n        \"swift-package-manager:swift-build\",\n        \"swift-package-manager:swift-bootstrap\",\n        \"swift-package-manager:package-info\",\n        \"swift-package-manager:dummy-swiftc\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build-dependsOn\",\n      \"to\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-symbolkit\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-symbolkit-dependsOn\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-toolchain-sqlite-dependsOn\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-certificates-dependsOn\",\n      \"to\" : [\n        \"swift-certificates:X509\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-asn1\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-asn1-dependsOn\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-collections-dependsOn\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-system\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-system-dependsOn\",\n      \"to\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-crypto-dependsOn\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:SwiftPMPackageTests\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:SwiftPMPackageTests-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:PackagePlugin\",\n        \"swift-package-manager:PackageDescription\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-package-manager:swift-package-manager\",\n        \"swift-package-manager:dummy-swiftc\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:SwiftPM\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:SwiftPM-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:SwiftPM-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:SwiftPM-auto-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:SwiftPMDataModel\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:SwiftPMDataModel-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:SwiftPMDataModel-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:SwiftPMDataModel-auto-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:XCBuildSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:XCBuildSupport-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:PackageDescription\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:PackageDescription-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:PackageDescription\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:AppleProductTypes\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:AppleProductTypes-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:PackageDescription\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:SwiftPMPackageCollections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:SwiftPMPackageCollections-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-crypto:Crypto\",\n        \"swift-certificates:X509\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:swift-build-prebuilts\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:swift-build-prebuilts-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:swift-bootstrap\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:swift-bootstrap-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager:package-info\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager:package-info-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager:SwiftPM\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:swbuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:swbuild-dependsOn\",\n      \"to\" : [\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBBuildServiceBundle\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildServiceBundle\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBBuildService\",\n        \"swift-build:SWBUtil\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SwiftBuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SwiftBuild-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProtocol\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBProtocol-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBUtil\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBUtil\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBUtil-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProjectModel\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBProjectModel-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBProtocol\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildService\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBBuildService-dependsOn\",\n      \"to\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-driver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-driver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriverExecution\",\n        \"swift-driver:SwiftDriver\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-help\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-help-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverDynamic\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftOptions\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftOptions-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverExecution\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:snippet-extract\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract-dependsOn\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite:sqlite\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite-dependsOn\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates:X509\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-certificates:X509-dependsOn\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:Collections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-collections:Collections-dependsOn\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto:_CryptoExtras\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras-dependsOn\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateManual\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-manual\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftBasicFormat\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:SwiftSyntaxMacros\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftDiagnostics\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIDEUtils\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIfConfig\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftIfConfig\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftOperators\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParser\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftParser-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftRefactor\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwift\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildAnalysis\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-build.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:swbuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:swbuild-wasGeneratedFrom-e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"to\" : [\n        \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-build.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildServiceBundle\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle-wasGeneratedFrom-e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"to\" : [\n        \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-build.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SwiftBuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SwiftBuild-wasGeneratedFrom-e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"to\" : [\n        \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-build.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProtocol\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBProtocol-wasGeneratedFrom-e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"to\" : [\n        \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-build.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBUtil\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBUtil-wasGeneratedFrom-e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"to\" : [\n        \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-build.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProjectModel\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBProjectModel-wasGeneratedFrom-e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"to\" : [\n        \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-build.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildService\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBBuildService-wasGeneratedFrom-e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"to\" : [\n        \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-build.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build-wasGeneratedFrom-e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"to\" : [\n        \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-driver.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-driver\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:swift-driver-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-driver.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-help\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:swift-help-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-driver.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-driver.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriver\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:SwiftDriver-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-driver.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverDynamic\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-driver.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftOptions\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:SwiftOptions-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-driver.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverExecution\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-driver.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-tools-support-core.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:TSCBasic\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core:TSCBasic-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-tools-support-core.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-tools-support-core.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-tools-support-core.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-tools-support-core.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-docc-plugin\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC-wasGeneratedFrom-3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"to\" : [\n        \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-docc-plugin\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview-wasGeneratedFrom-3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"to\" : [\n        \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-docc-plugin\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:snippet-extract\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract-wasGeneratedFrom-3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"to\" : [\n        \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-docc-plugin\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-plugin-wasGeneratedFrom-3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"to\" : [\n        \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-docc-symbolkit\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-symbolkit:SymbolKit-wasGeneratedFrom-b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"to\" : [\n        \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-docc-symbolkit\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-symbolkit\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-symbolkit-wasGeneratedFrom-b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"to\" : [\n        \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-toolchain-sqlite.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite:sqlite\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite-wasGeneratedFrom-b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"to\" : [\n        \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-toolchain-sqlite.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite-wasGeneratedFrom-b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"to\" : [\n        \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-toolchain-sqlite.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-toolchain-sqlite-wasGeneratedFrom-b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"to\" : [\n        \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-certificates.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates:X509\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-certificates:X509-wasGeneratedFrom-386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"to\" : [\n        \"386001a92200c70fd06217b3ccad58d7226edb84\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-certificates.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-certificates-wasGeneratedFrom-386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"to\" : [\n        \"386001a92200c70fd06217b3ccad58d7226edb84\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-asn1.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-asn1:SwiftASN1\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-asn1:SwiftASN1-wasGeneratedFrom-40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"to\" : [\n        \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-asn1.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-asn1\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-asn1-wasGeneratedFrom-40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"to\" : [\n        \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-collections.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:BitCollections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:BitCollections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-collections.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:DequeModule\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:DequeModule-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-collections.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:HashTreeCollections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:HashTreeCollections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-collections.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:HeapModule\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:HeapModule-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-collections.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:OrderedCollections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:OrderedCollections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-collections.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:_RopeModule\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:_RopeModule-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-collections.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:Collections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:Collections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-collections.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-system.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-system:SystemPackage\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-system:SystemPackage-wasGeneratedFrom-61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"to\" : [\n        \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-system.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-system\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-system-wasGeneratedFrom-61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"to\" : [\n        \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-crypto.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto:Crypto\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-crypto:Crypto-wasGeneratedFrom-d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"to\" : [\n        \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-crypto.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto:_CryptoExtras\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras-wasGeneratedFrom-d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"to\" : [\n        \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-crypto.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-crypto-wasGeneratedFrom-d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"to\" : [\n        \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-argument-parser.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:ArgumentParser\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser:ArgumentParser-wasGeneratedFrom-011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"to\" : [\n        \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-argument-parser.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateManual\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual-wasGeneratedFrom-011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"to\" : [\n        \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-argument-parser.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-manual\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual-wasGeneratedFrom-011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"to\" : [\n        \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"identifierLocator\" : \"https://github.com/apple/swift-argument-parser.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser-wasGeneratedFrom-011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"to\" : [\n        \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftBasicFormat\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftDiagnostics\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIDEUtils\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIfConfig\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftOperators\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParser\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftParser-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftRefactor\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntax\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntax-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-syntax.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax-wasGeneratedFrom-ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"to\" : [\n        \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-llbuild.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:llbuild-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-llbuild.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:libllbuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:libllbuild-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-llbuild.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwift\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-llbuild.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildAnalysis\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-llbuild.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : \"https://github.com/swiftlang/swift-llbuild.git\",\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    }\n  ]\n}"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/invalid-spdx-3.0.1-wrong-relationshiptype.json",
    "content": "{\n  \"@context\" : \"https://spdx.org/rdf/3.0.1/spdx-context.jsonld\",\n  \"@graph\" : [\n    {\n      \"@id\" : \"urn:uuid:8893d465-d998-442e-a799-30451b436850:creationInfo\",\n      \"created\" : \"1970-01-01T00:00:00Z\",\n      \"createdBy\" : [\n        \"urn:uuid:8893d465-d998-442e-a799-30451b436850\"\n      ],\n      \"specVersion\" : \"6.3.0-dev\",\n      \"type\" : \"CreationInfo\"\n    },\n    {\n      \"creationInfo\" : \"urn:uuid:8893d465-d998-442e-a799-30451b436850:creationInfo\",\n      \"name\" : \"swift-package-manager\",\n      \"spdxId\" : \"urn:uuid:8893d465-d998-442e-a799-30451b436850\",\n      \"type\" : \"Agent\"\n    },\n    {\n      \"@id\" : \"_:creationInfo\",\n      \"created\" : \"2025-10-30T21:17:58Z\",\n      \"createdBy\" : [\n        \"urn:uuid:8893d465-d998-442e-a799-30451b436850\"\n      ],\n      \"specVersion\" : \"3.0.1\",\n      \"type\" : \"CreationInfo\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"profileConformance\" : [\n        \"core\",\n        \"software\"\n      ],\n      \"rootElement\" : [\n        \"swift-package-manager-fork\"\n      ],\n      \"spdxId\" : \"urn:uuid:urn:uuid:e50f33db-cc8b-4460-9d39-3082daa65bc4\",\n      \"type\" : \"software_Sbom\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:uuid:urn:uuid:e50f33db-cc8b-4460-9d39-3082daa65bc4\",\n      \"relationshipType\" : \"describes\",\n      \"spdxId\" : \"urn:uuid:urn:uuid:e50f33db-cc8b-4460-9d39-3082daa65bc4-describes-swift-package-manager-fork\",\n      \"to\" : [\n        \"swift-package-manager-fork\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"profileConformance\" : [\n        \"core\",\n        \"software\"\n      ],\n      \"rootElement\" : [\n        \"urn:uuid:urn:uuid:e50f33db-cc8b-4460-9d39-3082daa65bc4\"\n      ],\n      \"spdxId\" : \"urn:uuid:5bb7a716-a72b-42ab-8a3d-1d76f7e89b58\",\n      \"type\" : \"SpdxDocument\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMPackageTests\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMPackageTests@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageTests\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPM\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPM@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPM-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPM-auto@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMDataModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMDataModel@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMDataModel-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMDataModel-auto@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"XCBuildSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:XCBuildSupport@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:XCBuildSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackageDescription\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackageDescription@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackageDescription\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"AppleProductTypes\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:AppleProductTypes@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:AppleProductTypes\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackagePlugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackagePlugin@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackagePlugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackageCollectionsModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackageCollectionsModel@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackageCollectionsModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMPackageCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMPackageCollections@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swiftpm-testing-helper\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swiftpm-testing-helper@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swiftpm-testing-helper\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-test\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-test@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-test\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-sdk\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-sdk@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-sdk\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-run\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-run@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-run\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-registry\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-registry@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-registry\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-manager\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-manager@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-manager\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-collection\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-collection@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-collection\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-experimental-sdk\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-experimental-sdk@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-experimental-sdk\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build-prebuilts\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-build-prebuilts@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build-prebuilts\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-build@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-bootstrap\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-bootstrap@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-bootstrap\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"package-info\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:package-info@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:package-info\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"dummy-swiftc\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:dummy-swiftc@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:dummy-swiftc\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-package-manager-fork>\",\n      \"name\" : \"swift-package-manager-fork\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork@3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_packageVersion\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:swbuild@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build:swbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBBuildServiceBundle\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBBuildServiceBundle@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftBuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SwiftBuild@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SwiftBuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBProtocol\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBProtocol@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBProtocol\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBUtil\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBUtil@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBUtil\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBProjectModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBProjectModel@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBProjectModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBBuildService\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBBuildService@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBBuildService\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-build>\",\n      \"name\" : \"swift-build\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-driver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-driver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-help\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-help@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-help\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build-sdk-interfaces\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-build-sdk-interfaces@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriverDynamic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriverDynamic@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftOptions\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftOptions@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftOptions\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriverExecution\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriverExecution@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-driver>\",\n      \"name\" : \"swift-driver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"TSCBasic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:TSCBasic@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:TSCBasic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolsSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:SwiftToolsSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolsSupport-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:SwiftToolsSupport-auto@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"TSCTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:TSCTestSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-tools-support-core>\",\n      \"name\" : \"swift-tools-support-core\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Swift-DocC\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:Swift-DocC@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Swift-DocC Preview\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:Swift-DocC Preview@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"snippet-extract\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:snippet-extract@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-docc-plugin>\",\n      \"name\" : \"swift-docc-plugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-docc-plugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SymbolKit\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit:SymbolKit@1.0.0\",\n      \"software_packageVersion\" : \"1.0.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-docc-symbolkit>\",\n      \"name\" : \"swift-docc-symbolkit\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit@1.0.0\",\n      \"software_packageVersion\" : \"1.0.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-symbolkit\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"sqlite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite:sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolchainCSQLite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite:SwiftToolchainCSQLite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-toolchain-sqlite>\",\n      \"name\" : \"swift-toolchain-sqlite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-toolchain-sqlite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"X509\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-certificates:X509@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_packageVersion\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-certificates:X509\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-certificates>\",\n      \"name\" : \"swift-certificates\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-certificates@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_packageVersion\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-certificates\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftASN1\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-asn1:SwiftASN1@1.5.0\",\n      \"software_packageVersion\" : \"1.5.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-asn1:SwiftASN1\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-asn1>\",\n      \"name\" : \"swift-asn1\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-asn1@1.5.0\",\n      \"software_packageVersion\" : \"1.5.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-asn1\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"BitCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:BitCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:BitCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"DequeModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:DequeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:DequeModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"HashTreeCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:HashTreeCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:HashTreeCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"HeapModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:HeapModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:HeapModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"OrderedCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:OrderedCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:OrderedCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_RopeModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:_RopeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:_RopeModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Collections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:Collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:Collections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-collections>\",\n      \"name\" : \"swift-collections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SystemPackage\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-system:SystemPackage@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_packageVersion\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-system:SystemPackage\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-system>\",\n      \"name\" : \"swift-system\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-system@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_packageVersion\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-system\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Crypto\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto:Crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto:Crypto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_CryptoExtras\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto:_CryptoExtras@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-crypto>\",\n      \"name\" : \"swift-crypto\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"ArgumentParser\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:ArgumentParser@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:ArgumentParser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"GenerateDoccReference\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:GenerateDoccReference@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:GenerateDoccReference\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"GenerateManual\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:GenerateManual@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"generate-manual\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:generate-manual@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"generate-docc-reference\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:generate-docc-reference@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser:generate-docc-reference\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-argument-parser>\",\n      \"name\" : \"swift-argument-parser\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftBasicFormat\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftBasicFormat@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftCompilerPlugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftCompilerPlugin@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDiagnostics\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftDiagnostics@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftIDEUtils\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftIDEUtils@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftIfConfig\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftIfConfig@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftLexicalLookup\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftLexicalLookup@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftOperators\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftOperators@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftParser\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftParser@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftParser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftParserDiagnostics\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftParserDiagnostics@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftRefactor\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftRefactor@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntax\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntax@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntax\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxBuilder\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxBuilder@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacros\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacros@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacroExpansion\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacroExpansion@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacrosTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacrosTestSupport@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacrosGenericTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacrosGenericTestSupport@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_SwiftCompilerPluginMessageHandling\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:_SwiftCompilerPluginMessageHandling@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_SwiftLibraryPluginProvider\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:_SwiftLibraryPluginProvider@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-syntax>\",\n      \"name\" : \"swift-syntax\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-llbuild:llbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"libllbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:libllbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:libllbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildSwift\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildSwift@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildAnalysis\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildAnalysis@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildSwiftDynamic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildSwiftDynamic@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-llbuild>\",\n      \"name\" : \"swift-llbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-llbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork-dependsOn\",\n      \"to\" : [\n        \"swift-build\",\n        \"swift-driver\",\n        \"swift-tools-support-core\",\n        \"swift-docc-plugin\",\n        \"swift-docc-symbolkit\",\n        \"swift-toolchain-sqlite\",\n        \"swift-certificates\",\n        \"swift-asn1\",\n        \"swift-collections\",\n        \"swift-system\",\n        \"swift-crypto\",\n        \"swift-argument-parser\",\n        \"swift-syntax\",\n        \"swift-llbuild\",\n        \"swift-package-manager-fork:SwiftPMPackageTests\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPM-auto\",\n        \"swift-package-manager-fork:SwiftPMDataModel\",\n        \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:AppleProductTypes\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageCollectionsModel\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-package-manager-fork:swiftpm-testing-helper\",\n        \"swift-package-manager-fork:swift-test\",\n        \"swift-package-manager-fork:swift-sdk\",\n        \"swift-package-manager-fork:swift-run\",\n        \"swift-package-manager-fork:swift-package-registry\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:swift-package-collection\",\n        \"swift-package-manager-fork:swift-package\",\n        \"swift-package-manager-fork:swift-experimental-sdk\",\n        \"swift-package-manager-fork:swift-build-prebuilts\",\n        \"swift-package-manager-fork:swift-build\",\n        \"swift-package-manager-fork:swift-bootstrap\",\n        \"swift-package-manager-fork:package-info\",\n        \"swift-package-manager-fork:dummy-swiftc\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork\",\n      \"relationshipType\" : \"hasTest\",\n      \"spdxId\" : \"swift-package-manager-fork-hasTest\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPMPackageTests\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build-dependsOn\",\n      \"to\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-symbolkit\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-symbolkit-dependsOn\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-toolchain-sqlite-dependsOn\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-certificates-dependsOn\",\n      \"to\" : [\n        \"swift-certificates:X509\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-asn1\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-asn1-dependsOn\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-collections-dependsOn\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-system\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-system-dependsOn\",\n      \"to\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-crypto-dependsOn\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateDoccReference\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\",\n        \"swift-argument-parser:generate-docc-reference\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMPackageTests\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageTests-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:dummy-swiftc\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPM\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPM-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-auto-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMDataModel\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-auto-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:XCBuildSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:XCBuildSupport-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:AppleProductTypes\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:AppleProductTypes-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:PackageDescription\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMPackageCollections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageCollections-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-crypto:Crypto\",\n        \"swift-certificates:X509\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-build-prebuilts\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build-prebuilts-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-bootstrap\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-bootstrap-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:package-info\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:package-info-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:swbuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:swbuild-dependsOn\",\n      \"to\" : [\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBBuildServiceBundle\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildServiceBundle\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBBuildService\",\n        \"swift-build:SWBUtil\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SwiftBuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SwiftBuild-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProtocol\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBProtocol-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBUtil\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBUtil\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBUtil-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProjectModel\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBProjectModel-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBProtocol\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildService\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBBuildService-dependsOn\",\n      \"to\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-driver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-driver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriverExecution\",\n        \"swift-driver:SwiftDriver\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-help\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-help-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverDynamic\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftOptions\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftOptions-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverExecution\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:snippet-extract\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract-dependsOn\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite:sqlite\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite-dependsOn\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates:X509\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-certificates:X509-dependsOn\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:Collections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-collections:Collections-dependsOn\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto:_CryptoExtras\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras-dependsOn\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateDoccReference\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:GenerateDoccReference-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:generate-docc-reference\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateManual\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-manual\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-docc-reference\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:generate-docc-reference-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftBasicFormat\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:SwiftSyntaxMacros\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftDiagnostics\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIDEUtils\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIfConfig\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftIfConfig\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftOperators\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParser\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftParser-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftRefactor\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwift\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildAnalysis\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMPackageTests\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageTests-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPM\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPM-auto\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-auto-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMDataModel\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-auto-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:XCBuildSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:XCBuildSupport-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:PackageDescription\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:PackageDescription-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:AppleProductTypes\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:AppleProductTypes-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:PackagePlugin\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:PackagePlugin-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:PackageCollectionsModel\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:PackageCollectionsModel-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMPackageCollections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageCollections-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swiftpm-testing-helper\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swiftpm-testing-helper-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-test\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-test-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-sdk\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-sdk-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-run\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-run-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-package-registry\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-registry-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-package-manager\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-manager-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-package-collection\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-collection-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-package\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-experimental-sdk\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-experimental-sdk-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-build-prebuilts\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build-prebuilts-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-build\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-bootstrap\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-bootstrap-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:package-info\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:package-info-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:dummy-swiftc\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork:dummy-swiftc-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-package-manager-fork-wasGeneratedFrom-3047c0857293a958ab0ffa5c8b57a148f0c36a70\",\n      \"to\" : [\n        \"3047c0857293a958ab0ffa5c8b57a148f0c36a70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:swbuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:swbuild-wasGeneratedFrom-6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"to\" : [\n        \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildServiceBundle\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle-wasGeneratedFrom-6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"to\" : [\n        \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SwiftBuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SwiftBuild-wasGeneratedFrom-6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"to\" : [\n        \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProtocol\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBProtocol-wasGeneratedFrom-6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"to\" : [\n        \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBUtil\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBUtil-wasGeneratedFrom-6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"to\" : [\n        \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProjectModel\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBProjectModel-wasGeneratedFrom-6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"to\" : [\n        \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildService\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build:SWBBuildService-wasGeneratedFrom-6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"to\" : [\n        \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-build-wasGeneratedFrom-6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"to\" : [\n        \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-driver\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:swift-driver-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-help\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:swift-help-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriver\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:SwiftDriver-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverDynamic\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftOptions\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:SwiftOptions-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverExecution\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-driver-wasGeneratedFrom-c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"to\" : [\n        \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-tools-support-core.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:TSCBasic\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core:TSCBasic-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-tools-support-core.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-tools-support-core.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-tools-support-core.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-tools-support-core.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-tools-support-core-wasGeneratedFrom-c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"to\" : [\n        \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-plugin\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC-wasGeneratedFrom-3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"to\" : [\n        \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-plugin\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview-wasGeneratedFrom-3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"to\" : [\n        \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-plugin\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:snippet-extract\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract-wasGeneratedFrom-3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"to\" : [\n        \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-plugin\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-plugin-wasGeneratedFrom-3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"to\" : [\n        \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-symbolkit\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-symbolkit:SymbolKit-wasGeneratedFrom-b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"to\" : [\n        \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-symbolkit\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-symbolkit\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-docc-symbolkit-wasGeneratedFrom-b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"to\" : [\n        \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-toolchain-sqlite.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite:sqlite\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite-wasGeneratedFrom-b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"to\" : [\n        \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-toolchain-sqlite.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite-wasGeneratedFrom-b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"to\" : [\n        \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-toolchain-sqlite.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-toolchain-sqlite-wasGeneratedFrom-b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"to\" : [\n        \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-certificates.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates:X509\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-certificates:X509-wasGeneratedFrom-386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"to\" : [\n        \"386001a92200c70fd06217b3ccad58d7226edb84\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-certificates.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-certificates-wasGeneratedFrom-386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"to\" : [\n        \"386001a92200c70fd06217b3ccad58d7226edb84\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-asn1.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-asn1:SwiftASN1\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-asn1:SwiftASN1-wasGeneratedFrom-40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"to\" : [\n        \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-asn1.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-asn1\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-asn1-wasGeneratedFrom-40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"to\" : [\n        \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:BitCollections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:BitCollections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:DequeModule\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:DequeModule-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:HashTreeCollections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:HashTreeCollections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:HeapModule\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:HeapModule-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:OrderedCollections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:OrderedCollections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:_RopeModule\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:_RopeModule-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:Collections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections:Collections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-collections-wasGeneratedFrom-c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"to\" : [\n        \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-system.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-system:SystemPackage\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-system:SystemPackage-wasGeneratedFrom-61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"to\" : [\n        \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-system.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-system\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-system-wasGeneratedFrom-61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"to\" : [\n        \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-crypto.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto:Crypto\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-crypto:Crypto-wasGeneratedFrom-d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"to\" : [\n        \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-crypto.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto:_CryptoExtras\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras-wasGeneratedFrom-d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"to\" : [\n        \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-crypto.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-crypto-wasGeneratedFrom-d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"to\" : [\n        \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-argument-parser.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:ArgumentParser\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser:ArgumentParser-wasGeneratedFrom-309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"to\" : [\n        \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-argument-parser.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateDoccReference\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser:GenerateDoccReference-wasGeneratedFrom-309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"to\" : [\n        \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-argument-parser.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateManual\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual-wasGeneratedFrom-309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"to\" : [\n        \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-argument-parser.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-manual\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual-wasGeneratedFrom-309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"to\" : [\n        \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-argument-parser.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-docc-reference\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser:generate-docc-reference-wasGeneratedFrom-309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"to\" : [\n        \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-argument-parser.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-argument-parser-wasGeneratedFrom-309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"to\" : [\n        \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftBasicFormat\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftDiagnostics\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIDEUtils\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIfConfig\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftOperators\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParser\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftParser-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftRefactor\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntax\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntax-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-syntax-wasGeneratedFrom-ef033f4611f44b911592b609e2df015f01086d69\",\n      \"to\" : [\n        \"ef033f4611f44b911592b609e2df015f01086d69\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-llbuild.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:llbuild-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-llbuild.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:libllbuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:libllbuild-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-llbuild.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwift\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-llbuild.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildAnalysis\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-llbuild.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-llbuild.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild\",\n      \"relationshipType\" : \"wasGeneratedFrom\",\n      \"spdxId\" : \"swift-llbuild-wasGeneratedFrom-9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"to\" : [\n        \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n      ],\n      \"type\" : \"Relationship\"\n    }\n  ]\n}"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/valid-cyclonedx-1.7-empty-comps.json",
    "content": "{\n    \"bomFormat\": \"CycloneDX\",\n    \"specVersion\": \"1.7\",\n    \"serialNumber\": \"urn:uuid:12345678-1234-1234-1234-123456789abc\",\n    \"version\": 1,\n    \"metadata\": {\n        \"timestamp\": \"2025-01-01T00:00:00Z\",\n        \"component\": {\n            \"type\": \"application\",\n            \"bom-ref\": \"test-app\",\n            \"name\": \"TestApp\",\n            \"version\": \"1.0.0\"\n        }\n    },\n    \"components\": [],\n    \"dependencies\": []\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/valid-cyclonedx-1.7-minimal.json",
    "content": "{\n    \"bomFormat\": \"CycloneDX\",\n    \"specVersion\": \"1.7\",\n    \"serialNumber\": \"urn:uuid:12345678-1234-1234-1234-123456789abc\",\n    \"version\": 1,\n    \"metadata\": {\n        \"component\": {\n            \"type\": \"application\",\n            \"bom-ref\": \"test-app\",\n            \"name\": \"TestApp\",\n            \"version\": \"1.0.0\"\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/valid-cyclonedx-1.7-spm.json",
    "content": "{\n  \"$schema\" : \"http://cyclonedx.org/schema/bom-1.7.schema.json\",\n  \"bomFormat\" : \"CycloneDX\",\n  \"components\" : [\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPMPackageTests\",\n      \"name\" : \"SwiftPMPackageTests\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPMPackageTests\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPM\",\n      \"name\" : \"SwiftPM\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPM\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPM-auto\",\n      \"name\" : \"SwiftPM-auto\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPM-auto\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPMDataModel\",\n      \"name\" : \"SwiftPMDataModel\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPMDataModel\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPMDataModel-auto\",\n      \"name\" : \"SwiftPMDataModel-auto\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPMDataModel-auto\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:XCBuildSupport\",\n      \"name\" : \"XCBuildSupport\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/XCBuildSupport\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:PackageDescription\",\n      \"name\" : \"PackageDescription\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/PackageDescription\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:AppleProductTypes\",\n      \"name\" : \"AppleProductTypes\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/AppleProductTypes\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:PackagePlugin\",\n      \"name\" : \"PackagePlugin\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/PackagePlugin\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:PackageCollectionsModel\",\n      \"name\" : \"PackageCollectionsModel\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/PackageCollectionsModel\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:SwiftPMPackageCollections\",\n      \"name\" : \"SwiftPMPackageCollections\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/SwiftPMPackageCollections\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swiftpm-testing-helper\",\n      \"name\" : \"swiftpm-testing-helper\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swiftpm-testing-helper\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-test\",\n      \"name\" : \"swift-test\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-test\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-sdk\",\n      \"name\" : \"swift-sdk\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-sdk\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-run\",\n      \"name\" : \"swift-run\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-run\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-package-registry\",\n      \"name\" : \"swift-package-registry\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-package-registry\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-package-manager\",\n      \"name\" : \"swift-package-manager\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-package-manager\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-package-collection\",\n      \"name\" : \"swift-package-collection\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-package-collection\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-package\",\n      \"name\" : \"swift-package\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-package\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-experimental-sdk\",\n      \"name\" : \"swift-experimental-sdk\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-experimental-sdk\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-build-prebuilts\",\n      \"name\" : \"swift-build-prebuilts\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-build-prebuilts\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-build\",\n      \"name\" : \"swift-build\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-build\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:swift-bootstrap\",\n      \"name\" : \"swift-bootstrap\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/swift-bootstrap\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:package-info\",\n      \"name\" : \"package-info\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/package-info\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager:dummy-swiftc\",\n      \"name\" : \"dummy-swiftc\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/swift-package-manager/dummy-swiftc\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager\",\n      \"name\" : \"swift-package-manager\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/echeng3805/swift-package-manager\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:swbuild\",\n      \"name\" : \"swbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/swbuild@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBBuildServiceBundle\",\n      \"name\" : \"SWBBuildServiceBundle\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBBuildServiceBundle@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SwiftBuild\",\n      \"name\" : \"SwiftBuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SwiftBuild@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBProtocol\",\n      \"name\" : \"SWBProtocol\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBProtocol@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBUtil\",\n      \"name\" : \"SWBUtil\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBUtil@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBProjectModel\",\n      \"name\" : \"SWBProjectModel\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBProjectModel@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBBuildService\",\n      \"name\" : \"SWBBuildService\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-build/SWBBuildService@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-build\",\n      \"name\" : \"swift-build\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build@e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"e6c5bd564e702ec74948bde4c7a66fd2a1ee8a8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-driver\",\n      \"name\" : \"swift-driver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-help\",\n      \"name\" : \"swift-help\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/swift-help@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"name\" : \"swift-build-sdk-interfaces\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/swift-build-sdk-interfaces@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriver\",\n      \"name\" : \"SwiftDriver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/SwiftDriver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriverDynamic\",\n      \"name\" : \"SwiftDriverDynamic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/SwiftDriverDynamic@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftOptions\",\n      \"name\" : \"SwiftOptions\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/SwiftOptions@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriverExecution\",\n      \"name\" : \"SwiftDriverExecution\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-driver/SwiftDriverExecution@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver\",\n      \"name\" : \"swift-driver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:TSCBasic\",\n      \"name\" : \"TSCBasic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-tools-support-core/TSCBasic@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"name\" : \"SwiftToolsSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-tools-support-core/SwiftToolsSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"name\" : \"SwiftToolsSupport-auto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-tools-support-core/SwiftToolsSupport-auto@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"name\" : \"TSCTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-tools-support-core/TSCTestSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core\",\n      \"name\" : \"swift-tools-support-core\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:Swift-DocC\",\n      \"name\" : \"Swift-DocC\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-docc-plugin/Swift-DocC@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"name\" : \"Swift-DocC Preview\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-docc-plugin/Swift-DocC Preview@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:snippet-extract\",\n      \"name\" : \"snippet-extract\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-docc-plugin/snippet-extract@3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin\",\n      \"name\" : \"swift-docc-plugin\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin@1.4.5\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"1.4.5\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"name\" : \"SymbolKit\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-docc-symbolkit/SymbolKit@b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-symbolkit\",\n      \"name\" : \"swift-docc-symbolkit\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit@1.0.0\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.0.0\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite:sqlite\",\n      \"name\" : \"sqlite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-toolchain-sqlite/sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"name\" : \"SwiftToolchainCSQLite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-toolchain-sqlite/SwiftToolchainCSQLite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite\",\n      \"name\" : \"swift-toolchain-sqlite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-certificates:X509\",\n      \"name\" : \"X509\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-certificates/X509@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n    },\n    {\n      \"bom-ref\" : \"swift-certificates\",\n      \"name\" : \"swift-certificates\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-certificates@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n    },\n    {\n      \"bom-ref\" : \"swift-asn1:SwiftASN1\",\n      \"name\" : \"SwiftASN1\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-asn1/SwiftASN1@40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n    },\n    {\n      \"bom-ref\" : \"swift-asn1\",\n      \"name\" : \"swift-asn1\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-asn1@1.5.0\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.5.0\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:BitCollections\",\n      \"name\" : \"BitCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/BitCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:DequeModule\",\n      \"name\" : \"DequeModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/DequeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:HashTreeCollections\",\n      \"name\" : \"HashTreeCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/HashTreeCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:HeapModule\",\n      \"name\" : \"HeapModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/HeapModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:OrderedCollections\",\n      \"name\" : \"OrderedCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/OrderedCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:_RopeModule\",\n      \"name\" : \"_RopeModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/_RopeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:Collections\",\n      \"name\" : \"Collections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-collections/Collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections\",\n      \"name\" : \"swift-collections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-system:SystemPackage\",\n      \"name\" : \"SystemPackage\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-system/SystemPackage@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n    },\n    {\n      \"bom-ref\" : \"swift-system\",\n      \"name\" : \"swift-system\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-system@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto:Crypto\",\n      \"name\" : \"Crypto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-crypto/Crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto:_CryptoExtras\",\n      \"name\" : \"_CryptoExtras\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-crypto/_CryptoExtras@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto\",\n      \"name\" : \"swift-crypto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:ArgumentParser\",\n      \"name\" : \"ArgumentParser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-argument-parser/ArgumentParser@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:GenerateManual\",\n      \"name\" : \"GenerateManual\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-argument-parser/GenerateManual@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:generate-manual\",\n      \"name\" : \"generate-manual\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-argument-parser/generate-manual@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser\",\n      \"name\" : \"swift-argument-parser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-argument-parser@011f0c765fb46d9cac61bca19be0527e99c98c8b\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"011f0c765fb46d9cac61bca19be0527e99c98c8b\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftBasicFormat\",\n      \"name\" : \"SwiftBasicFormat\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftBasicFormat@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"name\" : \"SwiftCompilerPlugin\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftCompilerPlugin@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftDiagnostics\",\n      \"name\" : \"SwiftDiagnostics\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftDiagnostics@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftIDEUtils\",\n      \"name\" : \"SwiftIDEUtils\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftIDEUtils@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftIfConfig\",\n      \"name\" : \"SwiftIfConfig\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftIfConfig@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"name\" : \"SwiftLexicalLookup\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftLexicalLookup@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftOperators\",\n      \"name\" : \"SwiftOperators\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftOperators@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftParser\",\n      \"name\" : \"SwiftParser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftParser@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"name\" : \"SwiftParserDiagnostics\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftParserDiagnostics@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftRefactor\",\n      \"name\" : \"SwiftRefactor\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftRefactor@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntax\",\n      \"name\" : \"SwiftSyntax\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntax@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"name\" : \"SwiftSyntaxBuilder\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxBuilder@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"name\" : \"SwiftSyntaxMacros\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacros@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"name\" : \"SwiftSyntaxMacroExpansion\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacroExpansion@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"name\" : \"SwiftSyntaxMacrosTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacrosTestSupport@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"name\" : \"SwiftSyntaxMacrosGenericTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/SwiftSyntaxMacrosGenericTestSupport@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"name\" : \"_SwiftCompilerPluginMessageHandling\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/_SwiftCompilerPluginMessageHandling@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"name\" : \"_SwiftLibraryPluginProvider\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-syntax/_SwiftLibraryPluginProvider@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax\",\n      \"name\" : \"swift-syntax\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax@ccfe3fcc9db129dce2dca5ab81851e241de5c90f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ccfe3fcc9db129dce2dca5ab81851e241de5c90f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuild\",\n      \"name\" : \"llbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:libllbuild\",\n      \"name\" : \"libllbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/libllbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildSwift\",\n      \"name\" : \"llbuildSwift\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/llbuildSwift@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildAnalysis\",\n      \"name\" : \"llbuildAnalysis\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/llbuildAnalysis@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"name\" : \"llbuildSwiftDynamic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/swift-llbuild/llbuildSwiftDynamic@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild\",\n      \"name\" : \"swift-llbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    }\n  ],\n  \"dependencies\" : [\n    {\n      \"dependsOn\" : [\n        \"swift-build\",\n        \"swift-driver\",\n        \"swift-tools-support-core\",\n        \"swift-docc-plugin\",\n        \"swift-docc-symbolkit\",\n        \"swift-toolchain-sqlite\",\n        \"swift-certificates\",\n        \"swift-asn1\",\n        \"swift-collections\",\n        \"swift-system\",\n        \"swift-crypto\",\n        \"swift-argument-parser\",\n        \"swift-syntax\",\n        \"swift-llbuild\",\n        \"swift-package-manager:SwiftPMPackageTests\",\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPM-auto\",\n        \"swift-package-manager:SwiftPMDataModel\",\n        \"swift-package-manager:SwiftPMDataModel-auto\",\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-package-manager:PackageDescription\",\n        \"swift-package-manager:AppleProductTypes\",\n        \"swift-package-manager:PackagePlugin\",\n        \"swift-package-manager:PackageCollectionsModel\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-package-manager:swiftpm-testing-helper\",\n        \"swift-package-manager:swift-test\",\n        \"swift-package-manager:swift-sdk\",\n        \"swift-package-manager:swift-run\",\n        \"swift-package-manager:swift-package-registry\",\n        \"swift-package-manager:swift-package-manager\",\n        \"swift-package-manager:swift-package-collection\",\n        \"swift-package-manager:swift-package\",\n        \"swift-package-manager:swift-experimental-sdk\",\n        \"swift-package-manager:swift-build-prebuilts\",\n        \"swift-package-manager:swift-build\",\n        \"swift-package-manager:swift-bootstrap\",\n        \"swift-package-manager:package-info\",\n        \"swift-package-manager:dummy-swiftc\"\n      ],\n      \"ref\" : \"swift-package-manager\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\"\n      ],\n      \"ref\" : \"swift-build\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"ref\" : \"swift-driver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\"\n      ],\n      \"ref\" : \"swift-tools-support-core\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"ref\" : \"swift-docc-symbolkit\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"ref\" : \"swift-toolchain-sqlite\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-certificates:X509\"\n      ],\n      \"ref\" : \"swift-certificates\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"ref\" : \"swift-asn1\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\"\n      ],\n      \"ref\" : \"swift-collections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-system\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"ref\" : \"swift-crypto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"ref\" : \"swift-argument-parser\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\"\n      ],\n      \"ref\" : \"swift-syntax\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\"\n      ],\n      \"ref\" : \"swift-llbuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:PackagePlugin\",\n        \"swift-package-manager:PackageDescription\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-package-manager:swift-package-manager\",\n        \"swift-package-manager:dummy-swiftc\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPMPackageTests\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPM\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPM-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPMDataModel\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPMDataModel-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager:XCBuildSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:PackageDescription\"\n      ],\n      \"ref\" : \"swift-package-manager:PackageDescription\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:PackageDescription\"\n      ],\n      \"ref\" : \"swift-package-manager:AppleProductTypes\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:SwiftPMPackageCollections\",\n        \"swift-crypto:Crypto\",\n        \"swift-certificates:X509\"\n      ],\n      \"ref\" : \"swift-package-manager:SwiftPMPackageCollections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"ref\" : \"swift-package-manager:swift-build-prebuilts\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\",\n        \"swift-package-manager:XCBuildSupport\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager:swift-bootstrap\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager:SwiftPM\"\n      ],\n      \"ref\" : \"swift-package-manager:package-info\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBBuildServiceBundle\"\n      ],\n      \"ref\" : \"swift-build:swbuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBBuildService\",\n        \"swift-build:SWBUtil\"\n      ],\n      \"ref\" : \"swift-build:SWBBuildServiceBundle\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\"\n      ],\n      \"ref\" : \"swift-build:SwiftBuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBUtil\"\n      ],\n      \"ref\" : \"swift-build:SWBProtocol\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-build:SWBUtil\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBProtocol\"\n      ],\n      \"ref\" : \"swift-build:SWBProjectModel\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-build:SWBBuildService\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriverExecution\",\n        \"swift-driver:SwiftDriver\"\n      ],\n      \"ref\" : \"swift-driver:swift-driver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:swift-help\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"ref\" : \"swift-driver:swift-build-sdk-interfaces\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriverDynamic\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftOptions\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriverExecution\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"ref\" : \"swift-tools-support-core:SwiftToolsSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"ref\" : \"swift-tools-support-core:SwiftToolsSupport-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\"\n      ],\n      \"ref\" : \"swift-tools-support-core:TSCTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin:Swift-DocC\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin:Swift-DocC Preview\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"ref\" : \"swift-docc-plugin:snippet-extract\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"ref\" : \"swift-toolchain-sqlite:sqlite\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"ref\" : \"swift-certificates:X509\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\"\n      ],\n      \"ref\" : \"swift-collections:Collections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"ref\" : \"swift-crypto:_CryptoExtras\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"ref\" : \"swift-argument-parser:GenerateManual\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"ref\" : \"swift-argument-parser:generate-manual\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftBasicFormat\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:SwiftSyntaxMacros\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftCompilerPlugin\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftDiagnostics\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftIDEUtils\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftIfConfig\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftIfConfig\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftLexicalLookup\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftOperators\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftParser\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftParserDiagnostics\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftRefactor\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxBuilder\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacros\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacroExpansion\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"ref\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n      ],\n      \"ref\" : \"swift-syntax:_SwiftLibraryPluginProvider\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildSwift\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildAnalysis\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildSwiftDynamic\"\n    }\n  ],\n  \"metadata\" : {\n    \"component\" : {\n      \"bom-ref\" : \"swift-package-manager\",\n      \"name\" : \"swift-package-manager\",\n      \"pedigree\" : {\n\n      },\n      \"purl\" : \"pkg:swift/echeng3805/swift-package-manager\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"application\",\n      \"version\" : \"unknown\"\n    },\n    \"timestamp\" : \"2025-10-23T19:03:58Z\"\n  },\n  \"serialNumber\" : \"urn:uuid:d6b121d1-943b-4f09-9fef-b1ec7ae4365f\",\n  \"specVersion\" : \"1.7\",\n  \"version\" : 1\n}"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/valid-cyclonedx-1.7-unicode.json",
    "content": "{\n    \"bomFormat\": \"CycloneDX\",\n    \"specVersion\": \"1.7\",\n    \"serialNumber\": \"urn:uuid:12345678-1234-1234-1234-123456789abc\",\n    \"version\": 1,\n    \"metadata\": {\n        \"component\": {\n            \"type\": \"application\",\n            \"bom-ref\": \"test-app-🚀\",\n            \"name\": \"TestApp\",\n            \"version\": \"1.0.0\",\n            \"description\": \"A test application with émojis and ünïcödé\"\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/valid-cyclonedx-1.7-versions.json",
    "content": "{\n  \"$schema\" : \"http://cyclonedx.org/schema/bom-1.7.schema.json\",\n  \"bomFormat\" : \"CycloneDX\",\n  \"components\" : [\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:SwiftPMPackageTests\",\n      \"name\" : \"SwiftPMPackageTests\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMPackageTests@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:SwiftPM\",\n      \"name\" : \"SwiftPM\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPM@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:SwiftPM-auto\",\n      \"name\" : \"SwiftPM-auto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPM-auto@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:SwiftPMDataModel\",\n      \"name\" : \"SwiftPMDataModel\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMDataModel@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n      \"name\" : \"SwiftPMDataModel-auto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMDataModel-auto@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:XCBuildSupport\",\n      \"name\" : \"XCBuildSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:XCBuildSupport@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:PackageDescription\",\n      \"name\" : \"PackageDescription\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackageDescription@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:AppleProductTypes\",\n      \"name\" : \"AppleProductTypes\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:AppleProductTypes@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:PackagePlugin\",\n      \"name\" : \"PackagePlugin\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackagePlugin@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:PackageCollectionsModel\",\n      \"name\" : \"PackageCollectionsModel\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackageCollectionsModel@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:SwiftPMPackageCollections\",\n      \"name\" : \"SwiftPMPackageCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMPackageCollections@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swiftpm-testing-helper\",\n      \"name\" : \"swiftpm-testing-helper\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swiftpm-testing-helper@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-test\",\n      \"name\" : \"swift-test\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-test@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-sdk\",\n      \"name\" : \"swift-sdk\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-sdk@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-run\",\n      \"name\" : \"swift-run\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-run@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-package-registry\",\n      \"name\" : \"swift-package-registry\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-registry@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-package-manager\",\n      \"name\" : \"swift-package-manager\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-manager@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-package-collection\",\n      \"name\" : \"swift-package-collection\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-collection@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-package\",\n      \"name\" : \"swift-package\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-experimental-sdk\",\n      \"name\" : \"swift-experimental-sdk\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-experimental-sdk@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-build-prebuilts\",\n      \"name\" : \"swift-build-prebuilts\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-build-prebuilts@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-build\",\n      \"name\" : \"swift-build\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-build@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:swift-bootstrap\",\n      \"name\" : \"swift-bootstrap\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-bootstrap@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:package-info\",\n      \"name\" : \"package-info\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:package-info@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork:dummy-swiftc\",\n      \"name\" : \"dummy-swiftc\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:dummy-swiftc@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-package-manager-fork\",\n      \"name\" : \"swift-package-manager-fork\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:swbuild\",\n      \"name\" : \"swbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n            \"url\" : \"https://github.com/swiftlang/swift-build.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build:swbuild@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBBuildServiceBundle\",\n      \"name\" : \"SWBBuildServiceBundle\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n            \"url\" : \"https://github.com/swiftlang/swift-build.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBBuildServiceBundle@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SwiftBuild\",\n      \"name\" : \"SwiftBuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n            \"url\" : \"https://github.com/swiftlang/swift-build.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build:SwiftBuild@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBProtocol\",\n      \"name\" : \"SWBProtocol\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n            \"url\" : \"https://github.com/swiftlang/swift-build.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBProtocol@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBUtil\",\n      \"name\" : \"SWBUtil\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n            \"url\" : \"https://github.com/swiftlang/swift-build.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBUtil@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBProjectModel\",\n      \"name\" : \"SWBProjectModel\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n            \"url\" : \"https://github.com/swiftlang/swift-build.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBProjectModel@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n    },\n    {\n      \"bom-ref\" : \"swift-build:SWBBuildService\",\n      \"name\" : \"SWBBuildService\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n            \"url\" : \"https://github.com/swiftlang/swift-build.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBBuildService@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n    },\n    {\n      \"bom-ref\" : \"swift-build\",\n      \"name\" : \"swift-build\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n            \"url\" : \"https://github.com/swiftlang/swift-build.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-build@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-driver\",\n      \"name\" : \"swift-driver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n            \"url\" : \"https://github.com/swiftlang/swift-driver.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-help\",\n      \"name\" : \"swift-help\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n            \"url\" : \"https://github.com/swiftlang/swift-driver.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-help@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"name\" : \"swift-build-sdk-interfaces\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n            \"url\" : \"https://github.com/swiftlang/swift-driver.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-build-sdk-interfaces@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriver\",\n      \"name\" : \"SwiftDriver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n            \"url\" : \"https://github.com/swiftlang/swift-driver.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriverDynamic\",\n      \"name\" : \"SwiftDriverDynamic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n            \"url\" : \"https://github.com/swiftlang/swift-driver.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriverDynamic@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftOptions\",\n      \"name\" : \"SwiftOptions\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n            \"url\" : \"https://github.com/swiftlang/swift-driver.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftOptions@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver:SwiftDriverExecution\",\n      \"name\" : \"SwiftDriverExecution\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n            \"url\" : \"https://github.com/swiftlang/swift-driver.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriverExecution@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-driver\",\n      \"name\" : \"swift-driver\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n            \"url\" : \"https://github.com/swiftlang/swift-driver.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:TSCBasic\",\n      \"name\" : \"TSCBasic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n            \"url\" : \"https://github.com/swiftlang/swift-tools-support-core.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:TSCBasic@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"name\" : \"SwiftToolsSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n            \"url\" : \"https://github.com/swiftlang/swift-tools-support-core.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:SwiftToolsSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"name\" : \"SwiftToolsSupport-auto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n            \"url\" : \"https://github.com/swiftlang/swift-tools-support-core.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:SwiftToolsSupport-auto@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"name\" : \"TSCTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n            \"url\" : \"https://github.com/swiftlang/swift-tools-support-core.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:TSCTestSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-tools-support-core\",\n      \"name\" : \"swift-tools-support-core\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n            \"url\" : \"https://github.com/swiftlang/swift-tools-support-core.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:Swift-DocC\",\n      \"name\" : \"Swift-DocC\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n            \"url\" : \"https://github.com/swiftlang/swift-docc-plugin\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:Swift-DocC@1.4.5\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.4.5\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"name\" : \"Swift-DocC Preview\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n            \"url\" : \"https://github.com/swiftlang/swift-docc-plugin\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:Swift-DocC Preview@1.4.5\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.4.5\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin:snippet-extract\",\n      \"name\" : \"snippet-extract\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n            \"url\" : \"https://github.com/swiftlang/swift-docc-plugin\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:snippet-extract@1.4.5\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"1.4.5\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-plugin\",\n      \"name\" : \"swift-docc-plugin\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"3e4f133a77e644a5812911a0513aeb7288b07d06\",\n            \"url\" : \"https://github.com/swiftlang/swift-docc-plugin\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin@1.4.5\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"1.4.5\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"name\" : \"SymbolKit\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n            \"url\" : \"https://github.com/swiftlang/swift-docc-symbolkit\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit:SymbolKit@1.0.0\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.0.0\"\n    },\n    {\n      \"bom-ref\" : \"swift-docc-symbolkit\",\n      \"name\" : \"swift-docc-symbolkit\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45d1f2ed151d057b54504d653e0da5552844e34\",\n            \"url\" : \"https://github.com/swiftlang/swift-docc-symbolkit\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit@1.0.0\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.0.0\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite:sqlite\",\n      \"name\" : \"sqlite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n            \"url\" : \"https://github.com/swiftlang/swift-toolchain-sqlite.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite:sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"name\" : \"SwiftToolchainCSQLite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n            \"url\" : \"https://github.com/swiftlang/swift-toolchain-sqlite.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite:SwiftToolchainCSQLite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-toolchain-sqlite\",\n      \"name\" : \"swift-toolchain-sqlite\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n            \"url\" : \"https://github.com/swiftlang/swift-toolchain-sqlite.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\"\n    },\n    {\n      \"bom-ref\" : \"swift-certificates:X509\",\n      \"name\" : \"X509\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n            \"url\" : \"https://github.com/apple/swift-certificates.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-certificates:X509@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n    },\n    {\n      \"bom-ref\" : \"swift-certificates\",\n      \"name\" : \"swift-certificates\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n            \"url\" : \"https://github.com/apple/swift-certificates.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-certificates@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"386001a92200c70fd06217b3ccad58d7226edb84\"\n    },\n    {\n      \"bom-ref\" : \"swift-asn1:SwiftASN1\",\n      \"name\" : \"SwiftASN1\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n            \"url\" : \"https://github.com/apple/swift-asn1.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-asn1:SwiftASN1@1.5.0\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.5.0\"\n    },\n    {\n      \"bom-ref\" : \"swift-asn1\",\n      \"name\" : \"swift-asn1\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n            \"url\" : \"https://github.com/apple/swift-asn1.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-asn1@1.5.0\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"1.5.0\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:BitCollections\",\n      \"name\" : \"BitCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n            \"url\" : \"https://github.com/apple/swift-collections.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections:BitCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:DequeModule\",\n      \"name\" : \"DequeModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n            \"url\" : \"https://github.com/apple/swift-collections.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections:DequeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:HashTreeCollections\",\n      \"name\" : \"HashTreeCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n            \"url\" : \"https://github.com/apple/swift-collections.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections:HashTreeCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:HeapModule\",\n      \"name\" : \"HeapModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n            \"url\" : \"https://github.com/apple/swift-collections.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections:HeapModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:OrderedCollections\",\n      \"name\" : \"OrderedCollections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n            \"url\" : \"https://github.com/apple/swift-collections.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections:OrderedCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:_RopeModule\",\n      \"name\" : \"_RopeModule\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n            \"url\" : \"https://github.com/apple/swift-collections.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections:_RopeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections:Collections\",\n      \"name\" : \"Collections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n            \"url\" : \"https://github.com/apple/swift-collections.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections:Collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-collections\",\n      \"name\" : \"swift-collections\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n            \"url\" : \"https://github.com/apple/swift-collections.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\"\n    },\n    {\n      \"bom-ref\" : \"swift-system:SystemPackage\",\n      \"name\" : \"SystemPackage\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n            \"url\" : \"https://github.com/apple/swift-system.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-system:SystemPackage@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n    },\n    {\n      \"bom-ref\" : \"swift-system\",\n      \"name\" : \"swift-system\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n            \"url\" : \"https://github.com/apple/swift-system.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-system@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto:Crypto\",\n      \"name\" : \"Crypto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n            \"url\" : \"https://github.com/apple/swift-crypto.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-crypto:Crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto:_CryptoExtras\",\n      \"name\" : \"_CryptoExtras\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n            \"url\" : \"https://github.com/apple/swift-crypto.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-crypto:_CryptoExtras@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-crypto\",\n      \"name\" : \"swift-crypto\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n            \"url\" : \"https://github.com/apple/swift-crypto.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:ArgumentParser\",\n      \"name\" : \"ArgumentParser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n            \"url\" : \"https://github.com/apple/swift-argument-parser.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-argument-parser:ArgumentParser@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:GenerateDoccReference\",\n      \"name\" : \"GenerateDoccReference\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n            \"url\" : \"https://github.com/apple/swift-argument-parser.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-argument-parser:GenerateDoccReference@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:GenerateManual\",\n      \"name\" : \"GenerateManual\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n            \"url\" : \"https://github.com/apple/swift-argument-parser.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-argument-parser:GenerateManual@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:generate-manual\",\n      \"name\" : \"generate-manual\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n            \"url\" : \"https://github.com/apple/swift-argument-parser.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-argument-parser:generate-manual@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser:generate-docc-reference\",\n      \"name\" : \"generate-docc-reference\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n            \"url\" : \"https://github.com/apple/swift-argument-parser.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-argument-parser:generate-docc-reference@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n    },\n    {\n      \"bom-ref\" : \"swift-argument-parser\",\n      \"name\" : \"swift-argument-parser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n            \"url\" : \"https://github.com/apple/swift-argument-parser.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/apple/swift-argument-parser@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftBasicFormat\",\n      \"name\" : \"SwiftBasicFormat\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftBasicFormat@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"name\" : \"SwiftCompilerPlugin\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftCompilerPlugin@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftDiagnostics\",\n      \"name\" : \"SwiftDiagnostics\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftDiagnostics@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftIDEUtils\",\n      \"name\" : \"SwiftIDEUtils\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftIDEUtils@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftIfConfig\",\n      \"name\" : \"SwiftIfConfig\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftIfConfig@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"name\" : \"SwiftLexicalLookup\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftLexicalLookup@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftOperators\",\n      \"name\" : \"SwiftOperators\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftOperators@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftParser\",\n      \"name\" : \"SwiftParser\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftParser@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"name\" : \"SwiftParserDiagnostics\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftParserDiagnostics@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftRefactor\",\n      \"name\" : \"SwiftRefactor\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftRefactor@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntax\",\n      \"name\" : \"SwiftSyntax\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntax@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"name\" : \"SwiftSyntaxBuilder\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxBuilder@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"name\" : \"SwiftSyntaxMacros\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacros@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"name\" : \"SwiftSyntaxMacroExpansion\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacroExpansion@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"name\" : \"SwiftSyntaxMacrosTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacrosTestSupport@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"name\" : \"SwiftSyntaxMacrosGenericTestSupport\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacrosGenericTestSupport@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"name\" : \"_SwiftCompilerPluginMessageHandling\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:_SwiftCompilerPluginMessageHandling@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"name\" : \"_SwiftLibraryPluginProvider\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:_SwiftLibraryPluginProvider@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-syntax\",\n      \"name\" : \"swift-syntax\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n            \"url\" : \"https://github.com/swiftlang/swift-syntax.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-syntax@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"ef033f4611f44b911592b609e2df015f01086d69\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuild\",\n      \"name\" : \"llbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n            \"url\" : \"https://github.com/swiftlang/swift-llbuild.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:libllbuild\",\n      \"name\" : \"libllbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n            \"url\" : \"https://github.com/swiftlang/swift-llbuild.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:libllbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildSwift\",\n      \"name\" : \"llbuildSwift\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n            \"url\" : \"https://github.com/swiftlang/swift-llbuild.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildSwift@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildAnalysis\",\n      \"name\" : \"llbuildAnalysis\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n            \"url\" : \"https://github.com/swiftlang/swift-llbuild.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildAnalysis@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"name\" : \"llbuildSwiftDynamic\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n            \"url\" : \"https://github.com/swiftlang/swift-llbuild.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildSwiftDynamic@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"library\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    },\n    {\n      \"bom-ref\" : \"swift-llbuild\",\n      \"name\" : \"swift-llbuild\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n            \"url\" : \"https://github.com/swiftlang/swift-llbuild.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"scope\" : \"required\",\n      \"type\" : \"application\",\n      \"version\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\"\n    }\n  ],\n  \"dependencies\" : [\n    {\n      \"dependsOn\" : [\n        \"swift-build\",\n        \"swift-driver\",\n        \"swift-tools-support-core\",\n        \"swift-docc-plugin\",\n        \"swift-docc-symbolkit\",\n        \"swift-toolchain-sqlite\",\n        \"swift-certificates\",\n        \"swift-asn1\",\n        \"swift-collections\",\n        \"swift-system\",\n        \"swift-crypto\",\n        \"swift-argument-parser\",\n        \"swift-syntax\",\n        \"swift-llbuild\",\n        \"swift-package-manager-fork:SwiftPMPackageTests\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPM-auto\",\n        \"swift-package-manager-fork:SwiftPMDataModel\",\n        \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:AppleProductTypes\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageCollectionsModel\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-package-manager-fork:swiftpm-testing-helper\",\n        \"swift-package-manager-fork:swift-test\",\n        \"swift-package-manager-fork:swift-sdk\",\n        \"swift-package-manager-fork:swift-run\",\n        \"swift-package-manager-fork:swift-package-registry\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:swift-package-collection\",\n        \"swift-package-manager-fork:swift-package\",\n        \"swift-package-manager-fork:swift-experimental-sdk\",\n        \"swift-package-manager-fork:swift-build-prebuilts\",\n        \"swift-package-manager-fork:swift-build\",\n        \"swift-package-manager-fork:swift-bootstrap\",\n        \"swift-package-manager-fork:package-info\",\n        \"swift-package-manager-fork:dummy-swiftc\"\n      ],\n      \"ref\" : \"swift-package-manager-fork\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\"\n      ],\n      \"ref\" : \"swift-build\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"ref\" : \"swift-driver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\"\n      ],\n      \"ref\" : \"swift-tools-support-core\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"ref\" : \"swift-docc-symbolkit\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"ref\" : \"swift-toolchain-sqlite\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-certificates:X509\"\n      ],\n      \"ref\" : \"swift-certificates\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"ref\" : \"swift-asn1\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\"\n      ],\n      \"ref\" : \"swift-collections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-system\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"ref\" : \"swift-crypto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateDoccReference\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\",\n        \"swift-argument-parser:generate-docc-reference\"\n      ],\n      \"ref\" : \"swift-argument-parser\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\"\n      ],\n      \"ref\" : \"swift-syntax\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\"\n      ],\n      \"ref\" : \"swift-llbuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:dummy-swiftc\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:SwiftPMPackageTests\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:SwiftPM\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:SwiftPM-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:SwiftPMDataModel\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:XCBuildSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:PackageDescription\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:AppleProductTypes\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-crypto:Crypto\",\n        \"swift-certificates:X509\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:SwiftPMPackageCollections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:swift-build-prebuilts\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:swift-bootstrap\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-package-manager-fork:SwiftPM\"\n      ],\n      \"ref\" : \"swift-package-manager-fork:package-info\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBBuildServiceBundle\"\n      ],\n      \"ref\" : \"swift-build:swbuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBBuildService\",\n        \"swift-build:SWBUtil\"\n      ],\n      \"ref\" : \"swift-build:SWBBuildServiceBundle\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\"\n      ],\n      \"ref\" : \"swift-build:SwiftBuild\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBUtil\"\n      ],\n      \"ref\" : \"swift-build:SWBProtocol\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-build:SWBUtil\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-build:SWBProtocol\"\n      ],\n      \"ref\" : \"swift-build:SWBProjectModel\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"ref\" : \"swift-build:SWBBuildService\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriverExecution\",\n        \"swift-driver:SwiftDriver\"\n      ],\n      \"ref\" : \"swift-driver:swift-driver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:swift-help\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"ref\" : \"swift-driver:swift-build-sdk-interfaces\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriver\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriverDynamic\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"ref\" : \"swift-driver:SwiftOptions\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-driver:SwiftDriverExecution\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"ref\" : \"swift-tools-support-core:SwiftToolsSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"ref\" : \"swift-tools-support-core:SwiftToolsSupport-auto\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\"\n      ],\n      \"ref\" : \"swift-tools-support-core:TSCTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin:Swift-DocC\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"ref\" : \"swift-docc-plugin:Swift-DocC Preview\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"ref\" : \"swift-docc-plugin:snippet-extract\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"ref\" : \"swift-toolchain-sqlite:sqlite\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"ref\" : \"swift-certificates:X509\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\"\n      ],\n      \"ref\" : \"swift-collections:Collections\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"ref\" : \"swift-crypto:_CryptoExtras\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:generate-docc-reference\"\n      ],\n      \"ref\" : \"swift-argument-parser:GenerateDoccReference\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"ref\" : \"swift-argument-parser:GenerateManual\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"ref\" : \"swift-argument-parser:generate-manual\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"ref\" : \"swift-argument-parser:generate-docc-reference\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftBasicFormat\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:SwiftSyntaxMacros\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftCompilerPlugin\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftDiagnostics\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftIDEUtils\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftIfConfig\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftIfConfig\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftLexicalLookup\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftOperators\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftParser\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftParserDiagnostics\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftRefactor\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxBuilder\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacros\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacroExpansion\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"ref\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"ref\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n      ],\n      \"ref\" : \"swift-syntax:_SwiftLibraryPluginProvider\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildSwift\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildAnalysis\"\n    },\n    {\n      \"dependsOn\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"ref\" : \"swift-llbuild:llbuildSwiftDynamic\"\n    }\n  ],\n  \"metadata\" : {\n    \"component\" : {\n      \"bom-ref\" : \"swift-package-manager-fork\",\n      \"name\" : \"swift-package-manager-fork\",\n      \"pedigree\" : {\n        \"commits\" : [\n          {\n            \"uid\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c\",\n            \"url\" : \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n          }\n        ]\n      },\n      \"purl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork@ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\",\n      \"scope\" : \"excluded\",\n      \"type\" : \"application\",\n      \"version\" : \"ba0bb4e58628a3b13d0b72b40a44db3fce2a2c7c-modified\"\n    },\n    \"timestamp\" : \"2025-10-29T20:48:50Z\",\n    \"tools\" : {\n      \"components\" : [\n        {\n          \"bom-ref\" : \"83b5f97c-a4bd-435a-beff-ba30b28a9913\",\n          \"name\" : \"swift-package-manager\",\n          \"purl\" : \"pkg:swift/github.com/swiftlang/swift-package-manager@6.3.0-dev\",\n          \"scope\" : \"excluded\",\n          \"type\" : \"application\",\n          \"version\" : \"6.3.0-dev\"\n        }\n      ]\n    }\n  },\n  \"serialNumber\" : \"urn:uuid:82659c4c-7488-43de-9ca6-5d9e977ea6c8\",\n  \"specVersion\" : \"1.7\",\n  \"version\" : 1\n}"
  },
  {
    "path": "Tests/SBOMModelTests/testfiles/valid-spdx-3.0.1-spm.json",
    "content": "{\n  \"@context\" : \"https://spdx.org/rdf/3.0.1/spdx-context.jsonld\",\n  \"@graph\" : [\n    {\n      \"@id\" : \"urn:uuid:e2dae645-68bd-4b95-b63d-cfabb200327a:creationInfo\",\n      \"created\" : \"1970-01-01T00:00:00Z\",\n      \"createdBy\" : [\n        \"urn:uuid:e2dae645-68bd-4b95-b63d-cfabb200327a\"\n      ],\n      \"specVersion\" : \"6.3.0-dev\",\n      \"type\" : \"CreationInfo\"\n    },\n    {\n      \"creationInfo\" : \"urn:uuid:e2dae645-68bd-4b95-b63d-cfabb200327a:creationInfo\",\n      \"name\" : \"swift-package-manager\",\n      \"spdxId\" : \"urn:uuid:e2dae645-68bd-4b95-b63d-cfabb200327a\",\n      \"type\" : \"Agent\"\n    },\n    {\n      \"@id\" : \"_:creationInfo\",\n      \"created\" : \"2025-11-03T20:18:13Z\",\n      \"createdBy\" : [\n        \"urn:uuid:e2dae645-68bd-4b95-b63d-cfabb200327a\"\n      ],\n      \"specVersion\" : \"3.0.1\",\n      \"type\" : \"CreationInfo\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"profileConformance\" : [\n        \"core\",\n        \"software\"\n      ],\n      \"rootElement\" : [\n        \"urn:spdx:swift-package-manager-fork\"\n      ],\n      \"spdxId\" : \"urn:uuid:7054b4b7-19dc-4dd2-b32f-10d6d737cbef\",\n      \"type\" : \"software_Sbom\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:uuid:7054b4b7-19dc-4dd2-b32f-10d6d737cbef\",\n      \"relationshipType\" : \"describes\",\n      \"spdxId\" : \"urn:uuid:7054b4b7-19dc-4dd2-b32f-10d6d737cbef-describes-urn:spdx:swift-package-manager-fork\",\n      \"to\" : [\n        \"urn:spdx:swift-package-manager-fork\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"profileConformance\" : [\n        \"core\",\n        \"software\"\n      ],\n      \"rootElement\" : [\n        \"urn:uuid:7054b4b7-19dc-4dd2-b32f-10d6d737cbef\"\n      ],\n      \"spdxId\" : \"urn:uuid:467648c8-5557-4e51-8313-58339825599b\",\n      \"type\" : \"SpdxDocument\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMPackageTests\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMPackageTests@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageTests\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPM\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPM@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPM-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPM-auto@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMDataModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMDataModel@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMDataModel-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMDataModel-auto@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"XCBuildSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:XCBuildSupport@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:XCBuildSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackageDescription\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackageDescription@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackageDescription\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"AppleProductTypes\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:AppleProductTypes@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:AppleProductTypes\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackagePlugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackagePlugin@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackagePlugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"PackageCollectionsModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:PackageCollectionsModel@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:PackageCollectionsModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftPMPackageCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:SwiftPMPackageCollections@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swiftpm-testing-helper\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swiftpm-testing-helper@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swiftpm-testing-helper\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-test\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-test@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-test\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-sdk\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-sdk@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-sdk\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-run\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-run@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-run\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-registry\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-registry@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-registry\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-manager\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-manager@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-manager\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package-collection\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package-collection@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package-collection\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-package\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-package@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-package\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-experimental-sdk\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-experimental-sdk@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-experimental-sdk\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build-prebuilts\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-build-prebuilts@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build-prebuilts\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-build@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-bootstrap\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:swift-bootstrap@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-bootstrap\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"package-info\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:package-info@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:package-info\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"dummy-swiftc\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork:dummy-swiftc@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-package-manager-fork:dummy-swiftc\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-package-manager-fork>\",\n      \"name\" : \"swift-package-manager-fork\",\n      \"packageUrl\" : \"pkg:swift/github.com/echeng3805/swift-package-manager-fork@0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_packageVersion\" : \"0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-modified\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"urn:spdx:swift-package-manager-fork\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:swbuild@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build:swbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBBuildServiceBundle\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBBuildServiceBundle@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftBuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SwiftBuild@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SwiftBuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBProtocol\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBProtocol@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBProtocol\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBUtil\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBUtil@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBUtil\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBProjectModel\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBProjectModel@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBProjectModel\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SWBBuildService\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build:SWBBuildService@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-build:SWBBuildService\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-build>\",\n      \"name\" : \"swift-build\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-build@6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_packageVersion\" : \"6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"urn:spdx:swift-build\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-driver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-driver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-help\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-help@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-help\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"swift-build-sdk-interfaces\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:swift-build-sdk-interfaces@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriverDynamic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriverDynamic@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftOptions\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftOptions@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftOptions\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDriverExecution\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver:SwiftDriverExecution@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-driver>\",\n      \"name\" : \"swift-driver\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-driver@c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_packageVersion\" : \"c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"urn:spdx:swift-driver\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"TSCBasic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:TSCBasic@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:TSCBasic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolsSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:SwiftToolsSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolsSupport-auto\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:SwiftToolsSupport-auto@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"TSCTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core:TSCTestSupport@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-tools-support-core>\",\n      \"name\" : \"swift-tools-support-core\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-tools-support-core@c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_packageVersion\" : \"c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"urn:spdx:swift-tools-support-core\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Swift-DocC\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:Swift-DocC@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Swift-DocC Preview\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:Swift-DocC Preview@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"snippet-extract\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin:snippet-extract@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-docc-plugin>\",\n      \"name\" : \"swift-docc-plugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-plugin@1.4.5\",\n      \"software_packageVersion\" : \"1.4.5\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"urn:spdx:swift-docc-plugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SymbolKit\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit:SymbolKit@1.0.0\",\n      \"software_packageVersion\" : \"1.0.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-docc-symbolkit:SymbolKit\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-docc-symbolkit>\",\n      \"name\" : \"swift-docc-symbolkit\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-docc-symbolkit@1.0.0\",\n      \"software_packageVersion\" : \"1.0.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"urn:spdx:swift-docc-symbolkit\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"sqlite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite:sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftToolchainCSQLite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite:SwiftToolchainCSQLite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-toolchain-sqlite>\",\n      \"name\" : \"swift-toolchain-sqlite\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-toolchain-sqlite@b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_packageVersion\" : \"b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"urn:spdx:swift-toolchain-sqlite\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"X509\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-certificates:X509@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_packageVersion\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-certificates:X509\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-certificates>\",\n      \"name\" : \"swift-certificates\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-certificates@386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_packageVersion\" : \"386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"urn:spdx:swift-certificates\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftASN1\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-asn1:SwiftASN1@1.5.0\",\n      \"software_packageVersion\" : \"1.5.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-asn1:SwiftASN1\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-asn1>\",\n      \"name\" : \"swift-asn1\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-asn1@1.5.0\",\n      \"software_packageVersion\" : \"1.5.0\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"urn:spdx:swift-asn1\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"BitCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:BitCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:BitCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"DequeModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:DequeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:DequeModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"HashTreeCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:HashTreeCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:HashTreeCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"HeapModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:HeapModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:HeapModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"OrderedCollections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:OrderedCollections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:OrderedCollections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_RopeModule\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:_RopeModule@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:_RopeModule\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Collections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections:Collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-collections:Collections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-collections>\",\n      \"name\" : \"swift-collections\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-collections@c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_packageVersion\" : \"c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"urn:spdx:swift-collections\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SystemPackage\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-system:SystemPackage@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_packageVersion\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-system:SystemPackage\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-system>\",\n      \"name\" : \"swift-system\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-system@61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_packageVersion\" : \"61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"urn:spdx:swift-system\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"Crypto\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto:Crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto:Crypto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_CryptoExtras\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto:_CryptoExtras@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-crypto>\",\n      \"name\" : \"swift-crypto\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-crypto@d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_packageVersion\" : \"d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"urn:spdx:swift-crypto\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"ArgumentParser\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:ArgumentParser@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:ArgumentParser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"GenerateDoccReference\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:GenerateDoccReference@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:GenerateDoccReference\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"GenerateManual\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:GenerateManual@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"generate-manual\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:generate-manual@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"generate-docc-reference\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser:generate-docc-reference@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-argument-parser:generate-docc-reference\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-argument-parser>\",\n      \"name\" : \"swift-argument-parser\",\n      \"packageUrl\" : \"pkg:swift/github.com/apple/swift-argument-parser@309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_packageVersion\" : \"309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"urn:spdx:swift-argument-parser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftBasicFormat\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftBasicFormat@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftCompilerPlugin\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftCompilerPlugin@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftDiagnostics\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftDiagnostics@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftIDEUtils\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftIDEUtils@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftIfConfig\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftIfConfig@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftLexicalLookup\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftLexicalLookup@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftOperators\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftOperators@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftParser\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftParser@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftParser\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftParserDiagnostics\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftParserDiagnostics@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftRefactor\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftRefactor@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntax\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntax@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntax\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxBuilder\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxBuilder@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacros\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacros@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacroExpansion\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacroExpansion@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacrosTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacrosTestSupport@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"SwiftSyntaxMacrosGenericTestSupport\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:SwiftSyntaxMacrosGenericTestSupport@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_SwiftCompilerPluginMessageHandling\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:_SwiftCompilerPluginMessageHandling@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"_SwiftLibraryPluginProvider\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax:_SwiftLibraryPluginProvider@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-syntax>\",\n      \"name\" : \"swift-syntax\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-syntax@ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_packageVersion\" : \"ef033f4611f44b911592b609e2df015f01086d69\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"urn:spdx:swift-syntax\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"swift-llbuild:llbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"libllbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:libllbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:libllbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildSwift\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildSwift@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildAnalysis\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildAnalysis@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"name\" : \"llbuildSwiftDynamic\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild:llbuildSwiftDynamic@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"library\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"description\" : \"<ResolvedPackage: swift-llbuild>\",\n      \"name\" : \"swift-llbuild\",\n      \"packageUrl\" : \"pkg:swift/github.com/swiftlang/swift-llbuild@9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_packageVersion\" : \"9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"software_primaryPurpose\" : \"application\",\n      \"spdxId\" : \"urn:spdx:swift-llbuild\",\n      \"type\" : \"software_Package\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-package-manager-fork\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-package-manager-fork-dependsOn\",\n      \"to\" : [\n        \"urn:spdx:swift-build\",\n        \"urn:spdx:swift-driver\",\n        \"urn:spdx:swift-tools-support-core\",\n        \"urn:spdx:swift-docc-plugin\",\n        \"urn:spdx:swift-docc-symbolkit\",\n        \"urn:spdx:swift-toolchain-sqlite\",\n        \"urn:spdx:swift-certificates\",\n        \"urn:spdx:swift-asn1\",\n        \"urn:spdx:swift-collections\",\n        \"urn:spdx:swift-system\",\n        \"urn:spdx:swift-crypto\",\n        \"urn:spdx:swift-argument-parser\",\n        \"urn:spdx:swift-syntax\",\n        \"urn:spdx:swift-llbuild\",\n        \"swift-package-manager-fork:SwiftPMPackageTests\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPM-auto\",\n        \"swift-package-manager-fork:SwiftPMDataModel\",\n        \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:AppleProductTypes\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageCollectionsModel\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-package-manager-fork:swiftpm-testing-helper\",\n        \"swift-package-manager-fork:swift-test\",\n        \"swift-package-manager-fork:swift-sdk\",\n        \"swift-package-manager-fork:swift-run\",\n        \"swift-package-manager-fork:swift-package-registry\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:swift-package-collection\",\n        \"swift-package-manager-fork:swift-package\",\n        \"swift-package-manager-fork:swift-experimental-sdk\",\n        \"swift-package-manager-fork:swift-build-prebuilts\",\n        \"swift-package-manager-fork:swift-build\",\n        \"swift-package-manager-fork:swift-bootstrap\",\n        \"swift-package-manager-fork:package-info\",\n        \"swift-package-manager-fork:dummy-swiftc\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-package-manager-fork\",\n      \"relationshipType\" : \"hasTest\",\n      \"spdxId\" : \"urn:spdx:swift-package-manager-fork-hasTest\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPMPackageTests\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-build\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-build-dependsOn\",\n      \"to\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-driver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-driver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-tools-support-core\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-tools-support-core-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-docc-plugin\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-docc-plugin-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-docc-symbolkit\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-docc-symbolkit-dependsOn\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-toolchain-sqlite\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-toolchain-sqlite-dependsOn\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-certificates\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-certificates-dependsOn\",\n      \"to\" : [\n        \"swift-certificates:X509\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-asn1\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-asn1-dependsOn\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-collections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-collections-dependsOn\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-system\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-system-dependsOn\",\n      \"to\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-crypto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-crypto-dependsOn\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-argument-parser\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-argument-parser-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateDoccReference\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\",\n        \"swift-argument-parser:generate-docc-reference\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-syntax\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-syntax-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:swift-llbuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"urn:spdx:swift-llbuild-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMPackageTests\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageTests-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:dummy-swiftc\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPM\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPM-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPM-auto-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMDataModel\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMDataModel-auto-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:XCBuildSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:XCBuildSupport-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:AppleProductTypes\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:AppleProductTypes-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:PackageDescription\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:SwiftPMPackageCollections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:SwiftPMPackageCollections-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-crypto:Crypto\",\n        \"swift-certificates:X509\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-build-prebuilts\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-build-prebuilts-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:swift-bootstrap\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:swift-bootstrap-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-collections:OrderedCollections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-package-manager-fork:package-info\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-package-manager-fork:package-info-dependsOn\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPM\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:swbuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:swbuild-dependsOn\",\n      \"to\" : [\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBBuildServiceBundle\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildServiceBundle\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBBuildServiceBundle-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBBuildService\",\n        \"swift-build:SWBUtil\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SwiftBuild\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SwiftBuild-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProtocol\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBProtocol-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBUtil\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBUtil\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBUtil-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBProjectModel\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBProjectModel-dependsOn\",\n      \"to\" : [\n        \"swift-build:SWBProtocol\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-build:SWBBuildService\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-build:SWBBuildService-dependsOn\",\n      \"to\" : [\n        \"swift-system:SystemPackage\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-driver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-driver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriverExecution\",\n        \"swift-driver:SwiftDriver\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-help\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-help-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:swift-build-sdk-interfaces\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:swift-build-sdk-interfaces-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverExecution\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriver\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriver-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverDynamic\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriverDynamic-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftOptions\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftOptions\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftOptions-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:SwiftToolsSupport-auto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-driver:SwiftDriverExecution\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-driver:SwiftDriverExecution-dependsOn\",\n      \"to\" : [\n        \"swift-driver:SwiftDriver\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:SwiftToolsSupport-auto\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:SwiftToolsSupport-auto-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-tools-support-core:TSCTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-tools-support-core:TSCTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:Swift-DocC Preview\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:Swift-DocC Preview-dependsOn\",\n      \"to\" : [\n        \"swift-docc-plugin:snippet-extract\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-docc-plugin:snippet-extract\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-docc-plugin:snippet-extract-dependsOn\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-toolchain-sqlite:sqlite\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-toolchain-sqlite:sqlite-dependsOn\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-certificates:X509\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-certificates:X509-dependsOn\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-collections:Collections\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-collections:Collections-dependsOn\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-crypto:_CryptoExtras\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-crypto:_CryptoExtras-dependsOn\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-asn1:SwiftASN1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateDoccReference\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:GenerateDoccReference-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:generate-docc-reference\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:GenerateManual\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:GenerateManual-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:generate-manual\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-manual\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:generate-manual-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-argument-parser:generate-docc-reference\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-argument-parser:generate-docc-reference-dependsOn\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftBasicFormat\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftBasicFormat-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftCompilerPlugin\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftCompilerPlugin-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:SwiftSyntaxMacros\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftDiagnostics\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftDiagnostics-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIDEUtils\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftIDEUtils-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftIfConfig\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftIfConfig-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftLexicalLookup\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftLexicalLookup-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftIfConfig\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftOperators\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftOperators-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParser\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftParser-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftParserDiagnostics\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftParserDiagnostics-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftRefactor\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftRefactor-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxBuilder\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxBuilder-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftSyntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacros\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacros-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacroExpansion\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacroExpansion-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:_SwiftCompilerPluginMessageHandling-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-syntax:_SwiftLibraryPluginProvider\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-syntax:_SwiftLibraryPluginProvider-dependsOn\",\n      \"to\" : [\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwift\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwift-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildAnalysis\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildAnalysis-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:llbuildSwift\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"swift-llbuild:llbuildSwiftDynamic\",\n      \"relationshipType\" : \"dependsOn\",\n      \"spdxId\" : \"swift-llbuild:llbuildSwiftDynamic-dependsOn\",\n      \"to\" : [\n        \"swift-llbuild:libllbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-driver.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:c54107dac2e89bd31a1224a3cb7f7186ab73173d\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:c54107dac2e89bd31a1224a3cb7f7186ab73173d-generates\",\n      \"to\" : [\n        \"swift-driver:swift-driver\",\n        \"swift-driver:swift-help\",\n        \"swift-driver:swift-build-sdk-interfaces\",\n        \"swift-driver:SwiftDriver\",\n        \"swift-driver:SwiftDriverDynamic\",\n        \"swift-driver:SwiftOptions\",\n        \"swift-driver:SwiftDriverExecution\",\n        \"urn:spdx:swift-driver\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:0bc0e733f8e0e512c6486b92ac943cc0b0a812c5\",\n      \"identifierLocator\" : [\n        \"git@github.com:echeng3805/swift-package-manager-fork.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:0bc0e733f8e0e512c6486b92ac943cc0b0a812c5\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:0bc0e733f8e0e512c6486b92ac943cc0b0a812c5-generates\",\n      \"to\" : [\n        \"swift-package-manager-fork:SwiftPMPackageTests\",\n        \"swift-package-manager-fork:SwiftPM\",\n        \"swift-package-manager-fork:SwiftPM-auto\",\n        \"swift-package-manager-fork:SwiftPMDataModel\",\n        \"swift-package-manager-fork:SwiftPMDataModel-auto\",\n        \"swift-package-manager-fork:XCBuildSupport\",\n        \"swift-package-manager-fork:PackageDescription\",\n        \"swift-package-manager-fork:AppleProductTypes\",\n        \"swift-package-manager-fork:PackagePlugin\",\n        \"swift-package-manager-fork:PackageCollectionsModel\",\n        \"swift-package-manager-fork:SwiftPMPackageCollections\",\n        \"swift-package-manager-fork:swiftpm-testing-helper\",\n        \"swift-package-manager-fork:swift-test\",\n        \"swift-package-manager-fork:swift-sdk\",\n        \"swift-package-manager-fork:swift-run\",\n        \"swift-package-manager-fork:swift-package-registry\",\n        \"swift-package-manager-fork:swift-package-manager\",\n        \"swift-package-manager-fork:swift-package-collection\",\n        \"swift-package-manager-fork:swift-package\",\n        \"swift-package-manager-fork:swift-experimental-sdk\",\n        \"swift-package-manager-fork:swift-build-prebuilts\",\n        \"swift-package-manager-fork:swift-build\",\n        \"swift-package-manager-fork:swift-bootstrap\",\n        \"swift-package-manager-fork:package-info\",\n        \"swift-package-manager-fork:dummy-swiftc\",\n        \"urn:spdx:swift-package-manager-fork\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-llbuild.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:9cd06072bc98869d6058ecf0cbb62533ca10c02f\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:9cd06072bc98869d6058ecf0cbb62533ca10c02f-generates\",\n      \"to\" : [\n        \"swift-llbuild:llbuild\",\n        \"swift-llbuild:libllbuild\",\n        \"swift-llbuild:llbuildSwift\",\n        \"swift-llbuild:llbuildAnalysis\",\n        \"swift-llbuild:llbuildSwiftDynamic\",\n        \"urn:spdx:swift-llbuild\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-argument-parser.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:309a47b2b1d9b5e991f36961c983ecec72275be3\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:309a47b2b1d9b5e991f36961c983ecec72275be3-generates\",\n      \"to\" : [\n        \"swift-argument-parser:ArgumentParser\",\n        \"swift-argument-parser:GenerateDoccReference\",\n        \"swift-argument-parser:GenerateManual\",\n        \"swift-argument-parser:generate-manual\",\n        \"swift-argument-parser:generate-docc-reference\",\n        \"urn:spdx:swift-argument-parser\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-plugin\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:3e4f133a77e644a5812911a0513aeb7288b07d06\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:3e4f133a77e644a5812911a0513aeb7288b07d06-generates\",\n      \"to\" : [\n        \"swift-docc-plugin:Swift-DocC\",\n        \"swift-docc-plugin:Swift-DocC Preview\",\n        \"swift-docc-plugin:snippet-extract\",\n        \"urn:spdx:swift-docc-plugin\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-collections.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:c11818f3cae0780656baa430b49e7f163f08dffd\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:c11818f3cae0780656baa430b49e7f163f08dffd-generates\",\n      \"to\" : [\n        \"swift-collections:BitCollections\",\n        \"swift-collections:DequeModule\",\n        \"swift-collections:HashTreeCollections\",\n        \"swift-collections:HeapModule\",\n        \"swift-collections:OrderedCollections\",\n        \"swift-collections:_RopeModule\",\n        \"swift-collections:Collections\",\n        \"urn:spdx:swift-collections\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-build.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:6bffad0230473416f5c6faccf5fdebcc5478b507\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:6bffad0230473416f5c6faccf5fdebcc5478b507-generates\",\n      \"to\" : [\n        \"swift-build:swbuild\",\n        \"swift-build:SWBBuildServiceBundle\",\n        \"swift-build:SwiftBuild\",\n        \"swift-build:SWBProtocol\",\n        \"swift-build:SWBUtil\",\n        \"swift-build:SWBProjectModel\",\n        \"swift-build:SWBBuildService\",\n        \"urn:spdx:swift-build\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-certificates.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:386001a92200c70fd06217b3ccad58d7226edb84\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:386001a92200c70fd06217b3ccad58d7226edb84-generates\",\n      \"to\" : [\n        \"swift-certificates:X509\",\n        \"urn:spdx:swift-certificates\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-crypto.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:d79c573e1b400d670ed12c0cb29d33f2c0f5ab70\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:d79c573e1b400d670ed12c0cb29d33f2c0f5ab70-generates\",\n      \"to\" : [\n        \"swift-crypto:Crypto\",\n        \"swift-crypto:_CryptoExtras\",\n        \"urn:spdx:swift-crypto\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-asn1.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:40d25bbb2fc5b557a9aa8512210bded327c0f60d\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:40d25bbb2fc5b557a9aa8512210bded327c0f60d-generates\",\n      \"to\" : [\n        \"swift-asn1:SwiftASN1\",\n        \"urn:spdx:swift-asn1\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-tools-support-core.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:c26cd00ec0ee74769993169cfb196122ca4f62e1\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:c26cd00ec0ee74769993169cfb196122ca4f62e1-generates\",\n      \"to\" : [\n        \"swift-tools-support-core:TSCBasic\",\n        \"swift-tools-support-core:SwiftToolsSupport\",\n        \"swift-tools-support-core:SwiftToolsSupport-auto\",\n        \"swift-tools-support-core:TSCTestSupport\",\n        \"urn:spdx:swift-tools-support-core\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:ef033f4611f44b911592b609e2df015f01086d69\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-syntax.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:ef033f4611f44b911592b609e2df015f01086d69\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:ef033f4611f44b911592b609e2df015f01086d69-generates\",\n      \"to\" : [\n        \"swift-syntax:SwiftBasicFormat\",\n        \"swift-syntax:SwiftCompilerPlugin\",\n        \"swift-syntax:SwiftDiagnostics\",\n        \"swift-syntax:SwiftIDEUtils\",\n        \"swift-syntax:SwiftIfConfig\",\n        \"swift-syntax:SwiftLexicalLookup\",\n        \"swift-syntax:SwiftOperators\",\n        \"swift-syntax:SwiftParser\",\n        \"swift-syntax:SwiftParserDiagnostics\",\n        \"swift-syntax:SwiftRefactor\",\n        \"swift-syntax:SwiftSyntax\",\n        \"swift-syntax:SwiftSyntaxBuilder\",\n        \"swift-syntax:SwiftSyntaxMacros\",\n        \"swift-syntax:SwiftSyntaxMacroExpansion\",\n        \"swift-syntax:SwiftSyntaxMacrosTestSupport\",\n        \"swift-syntax:SwiftSyntaxMacrosGenericTestSupport\",\n        \"swift-syntax:_SwiftCompilerPluginMessageHandling\",\n        \"swift-syntax:_SwiftLibraryPluginProvider\",\n        \"urn:spdx:swift-syntax\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-toolchain-sqlite.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:b45b80b943e88db3cb8ddea798fa3fa9912375ff\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:b45b80b943e88db3cb8ddea798fa3fa9912375ff-generates\",\n      \"to\" : [\n        \"swift-toolchain-sqlite:sqlite\",\n        \"swift-toolchain-sqlite:SwiftToolchainCSQLite\",\n        \"urn:spdx:swift-toolchain-sqlite\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"identifierLocator\" : [\n        \"https://github.com/apple/swift-system.git\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:61e4ca4b81b9e09e2ec863b00c340eb13497dac6\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:61e4ca4b81b9e09e2ec863b00c340eb13497dac6-generates\",\n      \"to\" : [\n        \"swift-system:SystemPackage\",\n        \"urn:spdx:swift-system\"\n      ],\n      \"type\" : \"Relationship\"\n    },\n    {\n      \"externalIdentifierType\" : \"gitoid\",\n      \"identifier\" : \"urn:spdx:b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"identifierLocator\" : [\n        \"https://github.com/swiftlang/swift-docc-symbolkit\"\n      ],\n      \"type\" : \"ExternalIdentifier\"\n    },\n    {\n      \"creationInfo\" : \"_:creationInfo\",\n      \"from\" : \"urn:spdx:b45d1f2ed151d057b54504d653e0da5552844e34\",\n      \"relationshipType\" : \"generates\",\n      \"spdxId\" : \"urn:spdx:b45d1f2ed151d057b54504d653e0da5552844e34-generates\",\n      \"to\" : [\n        \"swift-docc-symbolkit:SymbolKit\",\n        \"urn:spdx:swift-docc-symbolkit\"\n      ],\n      \"type\" : \"Relationship\"\n    }\n  ]\n}"
  },
  {
    "path": "Tests/SPMBuildCoreTests/ArtifactsArchiveMetadataTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport Testing\n\nstruct ArtifactsArchiveMetadataTests {\n    @Test\n    func parseMetadata() throws {\n        let fileSystem = InMemoryFileSystem()\n        try fileSystem.writeFileContents(\n            \"/info.json\",\n            string: \"\"\"\n            {\n                \"schemaVersion\": \"1.0\",\n                \"artifacts\": {\n                    \"protocol-buffer-compiler\": {\n                        \"type\": \"executable\",\n                        \"version\": \"3.5.1\",\n                        \"variants\": [\n                            {\n                                \"path\": \"x86_64-apple-macosx/protoc\",\n                                \"supportedTriples\": [\"x86_64-apple-macosx\"]\n                            },\n                            {\n                                \"path\": \"x86_64-unknown-linux-gnu/protoc\",\n                                \"supportedTriples\": [\"x86_64-unknown-linux-gnu\"]\n                            }\n                        ]\n                    }\n                }\n            }\n            \"\"\"\n        )\n\n        let metadata = try ArtifactsArchiveMetadata.parse(fileSystem: fileSystem, rootPath: .root)\n        let expected = try ArtifactsArchiveMetadata(\n            schemaVersion: \"1.0\",\n            artifacts: [\n                \"protocol-buffer-compiler\": ArtifactsArchiveMetadata.Artifact(\n                    type: .executable,\n                    version: \"3.5.1\",\n                    variants: [\n                        ArtifactsArchiveMetadata.Variant(\n                            path: \"x86_64-apple-macosx/protoc\",\n                            supportedTriples: [Triple(\"x86_64-apple-macosx\")]\n                        ),\n                        ArtifactsArchiveMetadata.Variant(\n                            path: \"x86_64-unknown-linux-gnu/protoc\",\n                            supportedTriples: [Triple(\"x86_64-unknown-linux-gnu\")]\n                        ),\n                    ]\n                ),\n            ]\n        )\n        #expect(metadata == expected, \"Actual is not as expected\")\n    }\n\n    @Test\n    func parseMetadataWithoutSupportedTriple() throws {\n        let fileSystem = InMemoryFileSystem()\n        try fileSystem.writeFileContents(\n            \"/info.json\",\n            string: \"\"\"\n            {\n                \"schemaVersion\": \"1.0\",\n                \"artifacts\": {\n                    \"protocol-buffer-compiler\": {\n                        \"type\": \"executable\",\n                        \"version\": \"3.5.1\",\n                        \"variants\": [\n                            {\n                                \"path\": \"x86_64-apple-macosx/protoc\"\n                            },\n                            {\n                                \"path\": \"x86_64-unknown-linux-gnu/protoc\",\n                                \"supportedTriples\": null\n                            }\n                        ]\n                    }\n                }\n            }\n            \"\"\"\n        )\n\n        let metadata = try ArtifactsArchiveMetadata.parse(fileSystem: fileSystem, rootPath: .root)\n        let expected = ArtifactsArchiveMetadata(\n            schemaVersion: \"1.0\",\n            artifacts: [\n                \"protocol-buffer-compiler\": ArtifactsArchiveMetadata.Artifact(\n                    type: .executable,\n                    version: \"3.5.1\",\n                    variants: [\n                        ArtifactsArchiveMetadata.Variant(\n                            path: \"x86_64-apple-macosx/protoc\",\n                            supportedTriples: nil\n                        ),\n                        ArtifactsArchiveMetadata.Variant(\n                            path: \"x86_64-unknown-linux-gnu/protoc\",\n                            supportedTriples: nil\n                        ),\n                    ]\n                ),\n            ]\n        )\n        #expect(metadata == expected, \"Actual is not as expected\")\n\n        let binaryTarget = BinaryModule(\n            name: \"protoc\", kind: .artifactsArchive(types: [.executable]), path: .root, origin: .local\n        )\n        // No supportedTriples with binaryTarget should be rejected\n        #expect(throws: (any Error).self) {\n            try binaryTarget.parseExecutableArtifactArchives(\n                for: Triple(\"x86_64-apple-macosx\"), fileSystem: fileSystem\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SPMBuildCoreTests/BuildParametersTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import SPMBuildCore\nimport Basics\nimport struct PackageModel.BuildEnvironment\nimport _InternalTestSupport\nimport Testing\n\nstruct BuildParametersTests {\n    @Test\n    func configurationDependentProperties() throws {\n        var parameters = mockBuildParameters(\n            destination: .host,\n            environment: BuildEnvironment(platform: .linux, configuration: .debug)\n        )\n        #expect(parameters.enableTestability)\n        parameters.configuration = .release\n        #expect(!parameters.enableTestability)\n    }\n}\n"
  },
  {
    "path": "Tests/SPMBuildCoreTests/MainAttrDetectionTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Basics\nimport SPMBuildCore\nimport Testing\n\nstruct ContainsAtMainReturnsExpectedValueTestData: CustomStringConvertible {\n    var description: String {\n        self.id\n    }\n\n    let fileContent: String\n    let expected: Bool\n    let id: String\n}\n\n@Suite(\n    .tags(\n        .TestSize.small,\n    )\n)\nstruct MainAttrDetectionTests {\n    @Test(\n        .tags(\n            .TestSize.small,\n        ),\n        arguments: [\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                \"\"\",\n                expected: false,\n                id: \"Empty file\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                @main\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"Simple @main case\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                    @main\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"@main with leading whitespace\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                // @main\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: false,\n                id: \"@main in single-line comment (should be ignored)\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                struct MyApp {\n                    // This is @main but not at start\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: false,\n                id: \"@main not at beginning of line (should not match)\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                import Foundation\n                import SwiftUI\n\n                @main\n                struct MyApp: App {\n                    var body: some Scene {\n                        WindowGroup {\n                            ContentView()\n                        }\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"@main with imports and other code\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                @main\n                struct FirstApp {\n                    static func main() {\n                        print(\"First\")\n                    }\n                }\n\n                // @main (commented out)\n                struct SecondApp {\n                    static func main() {\n                        print(\"Second\")\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"Multiple @main occurrences (first one should be detected)\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                @main\n                struct MyApp {\n                    static func main() {\n                        let text = \"@main is cool\"\n                        print(text)\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"@main in string literal (should still match as it's at line start)\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: false,\n                id: \"No @main, just regular code\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                \\t  @main\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"@main with tabs and spaces\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                /*\n                @main\n                */\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: false,\n                id: \"@main in multi-line comment (should be ignored)\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                /* @main */\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: false,\n                id: \"@main in multi-line comment on same line (should be ignored)\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                /*\n                Some comment\n                */\n                @main\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"@main after multi-line comment ends\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                // This is a comment\n                /* Multi-line\n                   comment */\n                @main\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"@main with mixed comments\",\n            ),\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                /*\n                This is a multi-line comment\n                that spans multiple lines\n                @main should be ignored here\n                */\n\n                @main\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"Complex multi-line comment scenario\",\n            ),\n        ],\n    )\n    func containsAtMainReturnsExpectedValue(\n        data: ContainsAtMainReturnsExpectedValueTestData,\n    ) async throws {\n        try await self._testImplementation_containsAtMainReturnsExpectedValue(data: data)\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9685\", relationship: .defect),\n        arguments: [\n            ContainsAtMainReturnsExpectedValueTestData(\n                fileContent: \"\"\"\n                /*\n                This is a multi-line comment\n                /* @main\n                struct MyApp {\n                    static func main() {\n                        print(\"Hello, World!\")\n                    }\n                }\n                \"\"\",\n                expected: true,\n                id: \"Multi-line comment end on a line containing @main\",\n            )\n\n        ],\n    )\n    func containsAtMainReturnsExpectedValueCurrentlyFails(\n        data: ContainsAtMainReturnsExpectedValueTestData,\n    ) async throws {\n        await withKnownIssue {\n            try await self._testImplementation_containsAtMainReturnsExpectedValue(data: data)\n        }\n    }\n\n    fileprivate func _testImplementation_containsAtMainReturnsExpectedValue(\n        data: ContainsAtMainReturnsExpectedValueTestData,\n        sourceLocation: SourceLocation = #_sourceLocation,\n    ) async throws {\n        let fileContent = data.fileContent\n        let expected = data.expected\n\n        let fileUnderTest = AbsolutePath.root.appending(\"myfile.swift\")\n        let fs = InMemoryFileSystem()\n        try fs.createDirectory(fileUnderTest.parentDirectory, recursive: true)\n        try fs.writeFileContents(fileUnderTest, string: fileContent)\n\n        let actual = try containsAtMain(fileSystem: fs, path: fileUnderTest)\n\n        #expect(actual == expected, sourceLocation: sourceLocation)\n    }\n}\n"
  },
  {
    "path": "Tests/SPMBuildCoreTests/XCFrameworkMetadataTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport class Basics.InMemoryFileSystem\nimport SPMBuildCore\nimport Testing\n\nstruct XCFrameworkMetadataTests {\n    @Test\n    func parseFramework() throws {\n        let fileSystem = InMemoryFileSystem(files: [\n            \"/Info.plist\":  \"\"\"\n            <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n            <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n            <plist version=\"1.0\">\n            <dict>\n                <key>AvailableLibraries</key>\n                <array>\n                    <dict>\n                        <key>LibraryIdentifier</key>\n                        <string>macos-x86_64</string>\n                        <key>LibraryPath</key>\n                        <string>MyFramework.framework</string>\n                        <key>SupportedArchitectures</key>\n                        <array>\n                            <string>x86_64</string>\n                        </array>\n                        <key>SupportedPlatform</key>\n                        <string>macos</string>\n                    </dict>\n                    <dict>\n                        <key>LibraryIdentifier</key>\n                        <string>ios-arm64_x86_64-simulator</string>\n                        <key>LibraryPath</key>\n                        <string>MyFramework.framework</string>\n                        <key>SupportedArchitectures</key>\n                        <array>\n                            <string>arm64</string>\n                            <string>x86_64</string>\n                        </array>\n                        <key>SupportedPlatform</key>\n                        <string>ios</string>\n                        <key>SupportedPlatformVariant</key>\n                        <string>simulator</string>\n                    </dict>\n                </array>\n                <key>CFBundlePackageType</key>\n                <string>XFWK</string>\n                <key>XCFrameworkFormatVersion</key>\n                <string>1.0</string>\n            </dict>\n            </plist>\n            \"\"\",\n        ])\n\n        let metadata = try XCFrameworkMetadata.parse(fileSystem: fileSystem, rootPath: .root)\n        let expected = XCFrameworkMetadata(\n            libraries: [\n                XCFrameworkMetadata.Library(\n                    libraryIdentifier: \"macos-x86_64\",\n                    libraryPath: \"MyFramework.framework\",\n                    headersPath: nil,\n                    platform: \"macos\",\n                    architectures: [\"x86_64\"],\n                    variant: nil\n                ),\n                XCFrameworkMetadata.Library(\n                    libraryIdentifier: \"ios-arm64_x86_64-simulator\",\n                    libraryPath: \"MyFramework.framework\",\n                    headersPath: nil,\n                    platform: \"ios\",\n                    architectures: [\"arm64\", \"x86_64\"],\n                    variant: \"simulator\"\n                ),\n            ],\n        )\n        #expect(metadata == expected)\n    }\n\n    @Test\n    func parseLibrary() throws {\n        let fileSystem = InMemoryFileSystem(files: [\n            \"/Info.plist\": \"\"\"\n            <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n            <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n            <plist version=\"1.0\">\n            <dict>\n                <key>AvailableLibraries</key>\n                <array>\n                    <dict>\n                        <key>LibraryIdentifier</key>\n                        <string>macos-x86_64</string>\n                        <key>HeadersPath</key>\n                        <string>Headers</string>\n                        <key>LibraryPath</key>\n                        <string>MyLibrary.a</string>\n                        <key>SupportedArchitectures</key>\n                        <array>\n                            <string>x86_64</string>\n                        </array>\n                        <key>SupportedPlatform</key>\n                        <string>macos</string>\n                    </dict>\n                </array>\n                <key>CFBundlePackageType</key>\n                <string>XFWK</string>\n                <key>XCFrameworkFormatVersion</key>\n                <string>1.0</string>\n            </dict>\n            </plist>\n            \"\"\",\n        ])\n\n        let metadata = try XCFrameworkMetadata.parse(fileSystem: fileSystem, rootPath: .root)\n        let expected = XCFrameworkMetadata(\n            libraries: [\n                XCFrameworkMetadata.Library(\n                    libraryIdentifier: \"macos-x86_64\",\n                    libraryPath: \"MyLibrary.a\",\n                    headersPath: \"Headers\",\n                    platform: \"macos\",\n                    architectures: [\"x86_64\"],\n                    variant: nil\n                ),\n            ],\n        )\n        #expect(metadata == expected)\n    }\n}\n"
  },
  {
    "path": "Tests/SourceControlTests/GitRepositoryProviderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2022-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport _InternalTestSupport\n@testable import SourceControl\nimport Testing\n\nstruct GitRepositoryProviderTests {\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8564\"),\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n    )\n    func isValidDirectory() throws {\n        try testWithTemporaryDirectory { sandbox in\n            let provider = GitRepositoryProvider()\n\n            // standard repository\n            let repositoryPath = sandbox.appending(\"test\")\n            try localFileSystem.createDirectory(repositoryPath)\n            initGitRepo(repositoryPath)\n            #expect(try provider.isValidDirectory(repositoryPath))\n\n            // no-checkout bare repository\n            let noCheckoutRepositoryPath = sandbox.appending(\"test-no-checkout\")\n            try localFileSystem.copy(from: repositoryPath.appending(\".git\"), to: noCheckoutRepositoryPath)\n            #expect(try provider.isValidDirectory(noCheckoutRepositoryPath))\n\n            // non-git directory\n            let notGitPath = sandbox.appending(\"test-not-git\")\n            #expect(throws: (any Error).self) {\n                try provider.isValidDirectory(notGitPath)\n            }\n\n            // non-git child directory of a git directory\n            let notGitChildPath = repositoryPath.appending(\"test-not-git\")\n            #expect(throws: (any Error).self) {\n                try provider.isValidDirectory(notGitChildPath)\n            }\n        }\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8564\"),\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n    )\n    func isValidDirectoryThrowsPrintableError() throws {\n        try testWithTemporaryDirectory { temp in\n            let provider = GitRepositoryProvider()\n            let expectedErrorMessage = \"not a git repository\"\n            #expect {\n                try provider.isValidDirectory(temp)\n            } throws: { error in\n                let errorString = String(describing: error)\n                let matched = errorString.contains(expectedErrorMessage)\n                return matched\n            }\n        }\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8564\"),\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n    )\n    func gitShellErrorIsPrintable() throws {\n        let stdOut = \"An error from Git - stdout\"\n        let stdErr = \"An error from Git - stderr\"\n        let arguments = [\"git\", \"error\"]\n        let command = \"git error\"\n        let result = AsyncProcessResult(\n            arguments: arguments,\n            environment: [:],\n            exitStatus: .terminated(code: 1),\n            output: .success(Array(stdOut.utf8)),\n            stderrOutput: .success(Array(stdErr.utf8))\n        )\n        let error = GitShellError(result: result)\n        let errorString = \"\\(error)\"\n        #expect(\n            errorString.contains(stdOut),\n            \"Error string '\\(errorString)' should contain '\\(stdOut)'\")\n        #expect(\n            errorString.contains(stdErr),\n            \"Error string '\\(errorString)' should contain '\\(stdErr)'\")\n        #expect(\n            errorString.contains(command),\n            \"Error string '\\(errorString)' should contain '\\(command)'\")\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8564\"),\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n    )\n    func gitShellErrorEmptyStdOut() throws {\n        let stdErr = \"An error from Git - stderr\"\n        let result = AsyncProcessResult(\n            arguments: [\"git\", \"error\"],\n            environment: [:],\n            exitStatus: .terminated(code: 1),\n            output: .success([]),\n            stderrOutput: .success(Array(stdErr.utf8))\n        )\n        let error = GitShellError(result: result)\n        let errorString = \"\\(error)\"\n        #expect(\n            errorString.contains(stdErr),\n            \"Error string '\\(errorString)' should contain '\\(stdErr)'\")\n    }\n\n    @Test(\n        .bug(\"https://github.com/swiftlang/swift-package-manager/issues/8564\"),\n        .disabled(if: CiEnvironment.runningInSelfHostedPipeline && ProcessInfo.hostOperatingSystem == .windows),\n    )\n    func gitShellErrorEmptyStdErr() throws {\n        let stdOut = \"An error from Git - stdout\"\n        let result = AsyncProcessResult(\n            arguments: [\"git\", \"error\"],\n            environment: [:],\n            exitStatus: .terminated(code: 1),\n            output: .success(Array(stdOut.utf8)),\n            stderrOutput: .success([])\n        )\n        let error = GitShellError(result: result)\n        let errorString = \"\\(error)\"\n        #expect(\n            errorString.contains(stdOut),\n            \"Error string '\\(errorString)' should contain '\\(stdOut)'\"\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SourceControlTests/GitRepositoryTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@_spi(ProcessEnvironmentBlockShim)\nimport Basics\n@testable import SourceControl\nimport _InternalTestSupport\nimport XCTest\n\nimport struct TSCBasic.FileSystemError\nimport func TSCBasic.makeDirectories\nimport class Basics.AsyncProcess\n\nimport enum TSCUtility.Git\n\nclass GitRepositoryTests: XCTestCase {\n\n    override func setUp() {\n        // needed for submodule tests\n        Git.environmentBlock = [\"GIT_ALLOW_PROTOCOL\": \"file\"]\n    }\n\n    override func tearDown() {\n        Git.environmentBlock = .init(Environment.current)\n    }\n\n    /// Test the basic provider functions.\n    func testRepositorySpecifier() {\n        do {\n            let s1 = RepositorySpecifier(url: \"a\")\n            let s2 = RepositorySpecifier(url: \"a\")\n            let s3 = RepositorySpecifier(url: \"b\")\n\n            XCTAssertEqual(s1, s1)\n            XCTAssertEqual(s1, s2)\n            XCTAssertEqual(Set([s1]), Set([s2]))\n            XCTAssertNotEqual(s1, s3)\n            XCTAssertNotEqual(s2, s3)\n        }\n\n        do {\n            let s1 = RepositorySpecifier(path: \"/A\")\n            let s2 = RepositorySpecifier(path: \"/A\")\n            let s3 = RepositorySpecifier(path: \"/B\")\n\n            XCTAssertEqual(s1, s1)\n            XCTAssertEqual(s1, s2)\n            XCTAssertEqual(Set([s1]), Set([s2]))\n            XCTAssertNotEqual(s1, s3)\n            XCTAssertNotEqual(s2, s3)\n        }\n    }\n\n    /// Test the basic provider functions.\n    func testProvider() async throws {\n        // Skipping all tests that call git on Windows.\n        // We have a test stall in CI when running in parallel.\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            let testRepoPath = path.appending(\"test-repo\")\n            try! makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath, tag: \"1.2.3\")\n\n            // Test the provider.\n            let testCheckoutPath = path.appending(\"checkout\")\n            let provider = GitRepositoryProvider()\n            XCTAssertTrue(try provider.workingCopyExists(at: testRepoPath))\n            let repoSpec = RepositorySpecifier(path: testRepoPath)\n            try await provider.fetch(repository: repoSpec, to: testCheckoutPath)\n\n            // Verify the checkout was made.\n            XCTAssertDirectoryExists(testCheckoutPath)\n\n            // Test the repository interface.\n            let repository = provider.open(repository: repoSpec, at: testCheckoutPath)\n            let tags = try repository.getTags()\n            XCTAssertEqual(try repository.getTags(), [\"1.2.3\"])\n\n            let revision = try repository.resolveRevision(tag: tags.first ?? \"<invalid>\")\n            // FIXME: It would be nice if we had a deterministic hash here...\n            let testRepoRevParsed = try await AsyncProcess.popen(args: Git.tool, \"-C\", testRepoPath.pathString, \"rev-parse\", \"--verify\", \"1.2.3\")\n                .utf8Output()\n                .spm_chomp()\n            XCTAssertEqual(revision.identifier, testRepoRevParsed)\n\n            if let revision = try? repository.resolveRevision(tag: \"<invalid>\") {\n                XCTFail(\"unexpected resolution of invalid tag to \\(revision)\")\n            }\n\n            let main = try repository.resolveRevision(identifier: \"main\")\n            let mainRevParsed = try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", testRepoPath.pathString, \"rev-parse\", \"--verify\", \"main\")\n                .spm_chomp()\n            XCTAssertEqual(main.identifier, mainRevParsed)\n\n            // Check that git hashes resolve to themselves.\n            let mainIdentifier = try repository.resolveRevision(identifier: main.identifier)\n            XCTAssertEqual(main.identifier, mainIdentifier.identifier)\n\n            // Check that invalid identifier doesn't resolve.\n            if let revision = try? repository.resolveRevision(identifier: \"invalid\") {\n                XCTFail(\"unexpected resolution of invalid identifier to \\(revision)\")\n            }\n        }\n    }\n\n    /// Check hash validation.\n    func testGitRepositoryHash() throws {\n        let validHash = \"0123456789012345678901234567890123456789\"\n        XCTAssertNotEqual(GitRepository.Hash(validHash), nil)\n\n        let invalidHexHash = validHash + \"1\"\n        XCTAssertEqual(GitRepository.Hash(invalidHexHash), nil)\n\n        let invalidNonHexHash = \"012345678901234567890123456789012345678!\"\n        XCTAssertEqual(GitRepository.Hash(invalidNonHexHash), nil)\n    }\n\n    /// Check raw repository facilities.\n    ///\n    /// In order to be stable, this test uses a static test git repository in\n    /// `Inputs`, which has known commit hashes. See the `construct.sh` script\n    /// contained within it for more information.\n    func testRawRepository() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8385: test repository has non-portable file names\")\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n\n        try await testWithTemporaryDirectory { path in\n            // Unarchive the static test repository.\n            let inputArchivePath = AbsolutePath(#file).parentDirectory.appending(components: \"Inputs\", \"TestRepo.tgz\")\n#if os(Windows)\n            try await AsyncProcess.checkNonZeroExit(args: \"tar.exe\", \"-x\", \"-v\", \"-C\", path.pathString, \"-f\", inputArchivePath.pathString)\n#else\n            try await AsyncProcess.checkNonZeroExit(args: \"tar\", \"--no-same-owner\", \"-x\", \"-v\", \"-C\", path.pathString, \"-f\", inputArchivePath.pathString)\n#endif\n            let testRepoPath = path.appending(\"TestRepo\")\n\n            // Check hash resolution.\n            let repo = GitRepository(path: testRepoPath)\n            XCTAssertEqual(\n                try repo.resolveHash(treeish: \"1.0\", type: \"commit\"),\n                try repo.resolveHash(treeish: \"main\"),\n            )\n\n            // Get the initial commit.\n            let initialCommitHash = try repo.resolveHash(treeish: \"a8b9fcb\")\n            XCTAssertEqual(initialCommitHash, GitRepository.Hash(\"a8b9fcbf893b3b02c0196609059ebae37aeb7f0b\"))\n\n            // Check commit loading.\n            let initialCommit = try repo.readCommit(hash: initialCommitHash)\n            XCTAssertEqual(initialCommit.hash, initialCommitHash)\n            XCTAssertEqual(initialCommit.tree, GitRepository.Hash(\"9d463c3b538619448c5d2ecac379e92f075a8976\"))\n\n            // Check tree loading.\n            let initialTree = try repo.readTree(hash: initialCommit.tree)\n            guard case .hash(let initialTreeHash) = initialTree.location else {\n                return XCTFail(\"wrong pointer\")\n            }\n            XCTAssertEqual(initialTreeHash, initialCommit.tree)\n            XCTAssertEqual(initialTree.contents.count, 1)\n            guard let readmeEntry = initialTree.contents.first else { return XCTFail() }\n            guard case .hash(let readmeEntryHash) = readmeEntry.location else {\n                return XCTFail(\"wrong pointer\")\n            }\n            XCTAssertEqual(readmeEntryHash, GitRepository.Hash(\"92513075b3491a54c45a880be25150d92388e7bc\"))\n            XCTAssertEqual(readmeEntry.type, .blob)\n            XCTAssertEqual(readmeEntry.name, \"README.txt\")\n\n            // Check loading of odd names.\n            //\n            // This is a commit which has a subdirectory 'funny-names' with\n            // paths with special characters.\n            let funnyNamesCommit = try repo.readCommit(hash: repo.resolveHash(treeish: \"a7b19a7\"))\n            let funnyNamesRoot = try repo.readTree(hash: funnyNamesCommit.tree)\n            XCTAssertEqual(funnyNamesRoot.contents.map{ $0.name }, [\"README.txt\", \"funny-names\", \"subdir\"])\n            guard funnyNamesRoot.contents.count == 3 else { return XCTFail() }\n\n            // FIXME: This isn't yet supported.\n            let funnyNamesSubdirEntry = funnyNamesRoot.contents[1]\n            XCTAssertEqual(funnyNamesSubdirEntry.type, .tree)\n            if let _ = try? repo.readTree(location: funnyNamesSubdirEntry.location) {\n                XCTFail(\"unexpected success reading tree with funny names\")\n            }\n       }\n    }\n\n    func testSubmoduleRead() throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try testWithTemporaryDirectory { path in\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n\n            let repoPath = path.appending(\"repo\")\n            try makeDirectories(repoPath)\n            initGitRepo(repoPath)\n\n            try AsyncProcess.checkNonZeroExit(\n                args: Git.tool, \"-C\", repoPath.pathString, \"submodule\", \"add\", testRepoPath.pathString,\n                environment: .init(Git.environmentBlock)\n            )\n            let repo = GitRepository(path: repoPath)\n            try repo.stageEverything()\n            try repo.commit()\n            // We should be able to read a repo which as a submdoule.\n            _ = try repo.readTree(hash: try repo.resolveHash(treeish: \"main\"))\n        }\n    }\n\n    /// Test the Git file system view.\n    func testGitFileView() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n\n            // Add a few files and a directory.\n            let test1FileContents = \"Hello, world!\"\n            let test2FileContents = \"Hello, happy world!\"\n            let test3FileContents = \"\"\"\n                #!/bin/sh\n                set -e\n                exit 0\n                \"\"\"\n            try localFileSystem.writeFileContents(testRepoPath.appending(\"test-file-1.txt\"), string: test1FileContents)\n            try localFileSystem.createDirectory(testRepoPath.appending(\"subdir\"))\n            try localFileSystem.writeFileContents(testRepoPath.appending(components: \"subdir\", \"test-file-2.txt\"), string: test2FileContents)\n            try localFileSystem.writeFileContents(testRepoPath.appending(\"test-file-3.sh\"), string: test3FileContents)\n            try localFileSystem.chmod(.executable, path: testRepoPath.appending(\"test-file-3.sh\"), options: [])\n            let testRepo = GitRepository(path: testRepoPath)\n            try testRepo.stage(files: \"test-file-1.txt\", \"subdir/test-file-2.txt\", \"test-file-3.sh\")\n            try testRepo.commit()\n            try testRepo.tag(name: \"test-tag\")\n\n            // Get the the repository via the provider. the provider.\n            let testClonePath = path.appending(\"clone\")\n            let provider = GitRepositoryProvider()\n            let repoSpec = RepositorySpecifier(path: testRepoPath)\n            try await provider.fetch(repository: repoSpec, to: testClonePath)\n            let repository = provider.open(repository: repoSpec, at: testClonePath)\n\n            // Get and test the file system view.\n            let view = try repository.openFileView(revision: repository.resolveRevision(tag: \"test-tag\"))\n\n            // Check basic predicates.\n            XCTAssert(view.isDirectory(\"/\"))\n            XCTAssert(view.isDirectory(\"/subdir\"))\n            XCTAssert(!view.isDirectory(\"/does-not-exist\"))\n            XCTAssert(view.exists(\"/test-file-1.txt\"))\n            XCTAssert(!view.exists(\"/does-not-exist\"))\n            XCTAssert(view.isFile(\"/test-file-1.txt\"))\n            XCTAssert(!view.isSymlink(\"/test-file-1.txt\"))\n            XCTAssert(!view.isExecutableFile(\"/does-not-exist\"))\n#if !os(Windows)\n            XCTAssert(view.isExecutableFile(\"/test-file-3.sh\"))\n#endif\n\n            // Check read of a directory.\n            let subdirPath = AbsolutePath(\"/subdir\")\n            XCTAssertEqual(try view.getDirectoryContents(AbsolutePath(\"/\")).sorted(), [\"file.swift\", \"subdir\", \"test-file-1.txt\", \"test-file-3.sh\"])\n            XCTAssertEqual(try view.getDirectoryContents(subdirPath).sorted(), [\"test-file-2.txt\"])\n            XCTAssertThrows(FileSystemError(.isDirectory, subdirPath)) {\n                _ = try view.readFileContents(subdirPath)\n            }\n\n            // Check read versus root.\n            XCTAssertThrows(FileSystemError(.isDirectory, AbsolutePath.root)) {\n                _ = try view.readFileContents(.root)\n            }\n\n            // Check read through a non-directory.\n            let notDirectoryPath1 = AbsolutePath(\"/test-file-1.txt\")\n            XCTAssertThrows(FileSystemError(.notDirectory, notDirectoryPath1)) {\n                _ = try view.getDirectoryContents(notDirectoryPath1)\n            }\n            let notDirectoryPath2 = AbsolutePath(\"/test-file-1.txt/thing\")\n            XCTAssertThrows(FileSystemError(.notDirectory, notDirectoryPath2)) {\n                _ = try view.readFileContents(notDirectoryPath2)\n            }\n\n            // Check read/write into a missing directory.\n            let noEntryPath1 = AbsolutePath(\"/does-not-exist\")\n            XCTAssertThrows(FileSystemError(.noEntry, noEntryPath1)) {\n                _ = try view.getDirectoryContents(noEntryPath1)\n            }\n            let noEntryPath2 = AbsolutePath(\"/does/not/exist\")\n            XCTAssertThrows(FileSystemError(.noEntry, noEntryPath2)) {\n                _ = try view.readFileContents(noEntryPath2)\n            }\n\n            // Check read of a file.\n            XCTAssertEqual(try view.readFileContents(\"/test-file-1.txt\"), test1FileContents)\n            XCTAssertEqual(try view.readFileContents(\"/subdir/test-file-2.txt\"), test2FileContents)\n            XCTAssertEqual(try view.readFileContents(\"/test-file-3.sh\"), test3FileContents)\n        }\n    }\n\n    /// Test the handling of local checkouts.\n    func testCheckouts() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            // Create a test repository.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath, tag: \"initial\")\n            let initialRevision = try GitRepository(path: testRepoPath).getCurrentRevision()\n\n            // Add a couple files and a directory.\n            try localFileSystem.writeFileContents(testRepoPath.appending(\"test.txt\"), bytes: \"Hi\")\n            let testRepo = GitRepository(path: testRepoPath)\n            try testRepo.stage(file: \"test.txt\")\n            try testRepo.commit()\n            try testRepo.tag(name: \"test-tag\")\n            let currentRevision = try GitRepository(path: testRepoPath).getCurrentRevision()\n\n            // Fetch the repository using the provider.\n            let testClonePath = path.appending(\"clone\")\n            let provider = GitRepositoryProvider()\n            let repoSpec = RepositorySpecifier(path: testRepoPath)\n            try await provider.fetch(repository: repoSpec, to: testClonePath)\n\n            // Clone off a checkout.\n            let checkoutPath = path.appending(\"checkout\")\n            _ = try await provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: false)\n            // The remote of this checkout should point to the clone.\n            XCTAssertEqual(try GitRepository(path: checkoutPath).remotes()[0].url, testClonePath.pathString)\n\n            let editsPath = path.appending(\"edit\")\n            _ = try await provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: editsPath, editable: true)\n            // The remote of this checkout should point to the original repo.\n            XCTAssertEqual(try GitRepository(path: editsPath).remotes()[0].url, testRepoPath.pathString)\n\n            // Check the working copies.\n            for path in [checkoutPath, editsPath] {\n                let workingCopy = try provider.openWorkingCopy(at: path)\n                try workingCopy.checkout(tag: \"test-tag\")\n                XCTAssertEqual(try workingCopy.getCurrentRevision(), currentRevision)\n                XCTAssertFileExists(path.appending(\"test.txt\"))\n                try workingCopy.checkout(tag: \"initial\")\n                XCTAssertEqual(try workingCopy.getCurrentRevision(), initialRevision)\n                XCTAssertNoSuchPath(path.appending(\"test.txt\"))\n            }\n        }\n    }\n\n    func testFetch() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath, tag: \"1.2.3\")\n            let repo = GitRepository(path: testRepoPath)\n            XCTAssertEqual(try repo.getTags(), [\"1.2.3\"])\n\n            // Clone it somewhere.\n            let testClonePath = path.appending(\"clone\")\n            let provider = GitRepositoryProvider()\n            let repoSpec = RepositorySpecifier(path: testRepoPath)\n            try await provider.fetch(repository: repoSpec, to: testClonePath)\n            let clonedRepo = provider.open(repository: repoSpec, at: testClonePath)\n            XCTAssertEqual(try clonedRepo.getTags(), [\"1.2.3\"])\n\n            // Clone off a checkout.\n            let checkoutPath = path.appending(\"checkout\")\n            let checkoutRepo = try await provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: false)\n            XCTAssertEqual(try checkoutRepo.getTags(), [\"1.2.3\"])\n\n            // Add a new file to original repo.\n            try localFileSystem.writeFileContents(testRepoPath.appending(\"test.txt\"), bytes: \"Hi\")\n            let testRepo = GitRepository(path: testRepoPath)\n            try testRepo.stage(file: \"test.txt\")\n            try testRepo.commit()\n            try testRepo.tag(name: \"2.0.0\")\n\n            // Update the cloned repo.\n            try clonedRepo.fetch()\n            XCTAssertEqual(try clonedRepo.getTags().sorted(), [\"1.2.3\", \"2.0.0\"])\n\n            // Update the checkout.\n            try checkoutRepo.fetch()\n            XCTAssertEqual(try checkoutRepo.getTags().sorted(), [\"1.2.3\", \"2.0.0\"])\n        }\n    }\n\n    func testHasUnpushedCommits() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n\n            // Create a bare clone it somewhere because we want to later push into the repo.\n            let testBareRepoPath = path.appending(\"test-repo-bare\")\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"clone\", \"--bare\", testRepoPath.pathString, testBareRepoPath.pathString)\n\n            // Clone it somewhere.\n            let testClonePath = path.appending(\"clone\")\n            let provider = GitRepositoryProvider()\n            let repoSpec = RepositorySpecifier(path: testBareRepoPath)\n            try await provider.fetch(repository: repoSpec, to: testClonePath)\n\n            // Clone off a checkout.\n            let checkoutPath = path.appending(\"checkout\")\n            let checkoutRepo = try await provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: true)\n\n            XCTAssertFalse(try checkoutRepo.hasUnpushedCommits())\n            // Add a new file to checkout.\n            try localFileSystem.writeFileContents(checkoutPath.appending(\"test.txt\"), bytes: \"Hi\")\n            let checkoutTestRepo = GitRepository(path: checkoutPath)\n            try checkoutTestRepo.stage(file: \"test.txt\")\n            try checkoutTestRepo.commit()\n\n            // We should have commits which are not pushed.\n            XCTAssert(try checkoutRepo.hasUnpushedCommits())\n            // Push the changes and check again.\n            try checkoutTestRepo.push(remote: \"origin\", branch: \"main\")\n            XCTAssertFalse(try checkoutRepo.hasUnpushedCommits())\n        }\n    }\n\n    func testSetRemote() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n            let repo = GitRepository(path: testRepoPath)\n\n            // There should be no remotes currently.\n            XCTAssert(try repo.remotes().isEmpty)\n\n            // Add a remote via git cli.\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", testRepoPath.pathString, \"remote\", \"add\", \"origin\", \"../foo\")\n            // Test if it was added.\n            XCTAssertEqual(Dictionary(uniqueKeysWithValues: try repo.remotes().map { ($0.0, $0.1) }), [\"origin\": \"../foo\"])\n            // Change remote.\n            try repo.setURL(remote: \"origin\", url: \"../bar\")\n            XCTAssertEqual(Dictionary(uniqueKeysWithValues: try repo.remotes().map { ($0.0, $0.1) }), [\"origin\": \"../bar\"])\n            // Try changing remote of non-existent remote.\n            do {\n                try repo.setURL(remote: \"fake\", url: \"../bar\")\n                XCTFail(\"unexpected success (shouldn’t have been able to set URL of missing remote)\")\n            }\n            catch let error as GitRepositoryError {\n                XCTAssertEqual(error.path, testRepoPath)\n                XCTAssertNotNil(error.diagnosticLocation)\n            }\n        }\n    }\n\n    func testUncommittedChanges() throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n\n            // Create a file (which we will modify later).\n            try localFileSystem.writeFileContents(testRepoPath.appending(\"test.txt\"), bytes: \"Hi\")\n            let repo = GitRepository(path: testRepoPath)\n\n            XCTAssert(repo.hasUncommittedChanges())\n\n            try repo.stage(file: \"test.txt\")\n\n            XCTAssert(repo.hasUncommittedChanges())\n\n            try repo.commit()\n\n            XCTAssertFalse(repo.hasUncommittedChanges())\n\n            // Modify the file in the repo.\n            try localFileSystem.writeFileContents(repo.path.appending(\"test.txt\"), bytes: \"Hello\")\n            XCTAssert(repo.hasUncommittedChanges())\n        }\n    }\n\n    func testBranchOperations() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n\n            let repo = GitRepository(path: testRepoPath)\n            var currentRevision = try repo.getCurrentRevision()\n            // This is the default branch of a new repo.\n            XCTAssertTrue(repo.exists(revision: Revision(identifier: \"main\")))\n            // Check a non existent revision.\n            XCTAssertFalse(repo.exists(revision: Revision(identifier: \"nonExistent\")))\n            // Checkout a new branch using command line.\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", testRepoPath.pathString, \"checkout\", \"-b\", \"TestBranch1\")\n            XCTAssertTrue(repo.exists(revision: Revision(identifier: \"TestBranch1\")))\n            XCTAssertEqual(try repo.getCurrentRevision(), currentRevision)\n\n            // Make sure we're on the new branch right now.\n            XCTAssertEqual(try repo.currentBranch(), \"TestBranch1\")\n\n            // Checkout new branch using our API.\n            currentRevision = try repo.getCurrentRevision()\n            try repo.checkout(newBranch: \"TestBranch2\")\n            XCTAssert(repo.exists(revision: Revision(identifier: \"TestBranch2\")))\n            XCTAssertEqual(try repo.getCurrentRevision(), currentRevision)\n            XCTAssertEqual(try repo.currentBranch(), \"TestBranch2\")\n        }\n    }\n\n    func testRevisionOperations() throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try testWithTemporaryDirectory { path in\n            // Create a repo.\n            let repositoryPath = path.appending(\"test-repo\")\n            try makeDirectories(repositoryPath)\n            initGitRepo(repositoryPath)\n\n            let repo = GitRepository(path: repositoryPath)\n\n            do {\n                let revision = try repo.getCurrentRevision()\n                XCTAssertTrue(repo.exists(revision: revision))\n            }\n\n            do {\n                XCTAssertFalse(repo.exists(revision: Revision(identifier: UUID().uuidString)))\n\n                let tag = UUID().uuidString\n                try repo.tag(name: tag)\n                let revision = try repo.resolveRevision(tag: tag)\n                XCTAssertTrue(repo.exists(revision: revision))\n            }\n        }\n    }\n\n    func testCheckoutRevision() throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n            let repo = GitRepository(path: testRepoPath)\n\n            func createAndStageTestFile() throws {\n                try localFileSystem.writeFileContents(testRepoPath.appending(\"test.txt\"), bytes: \"Hi\")\n                try repo.stage(file: \"test.txt\")\n            }\n\n            try repo.checkout(revision: Revision(identifier: \"main\"))\n            // Current branch must be main.\n            XCTAssertEqual(try repo.currentBranch(), \"main\")\n            // Create a new branch.\n            try repo.checkout(newBranch: \"TestBranch\")\n            XCTAssertEqual(try repo.currentBranch(), \"TestBranch\")\n            // Create some random file.\n            try createAndStageTestFile()\n            XCTAssert(repo.hasUncommittedChanges())\n            // Checkout current revision again, the test file should go away.\n            let currentRevision = try repo.getCurrentRevision()\n            try repo.checkout(revision: currentRevision)\n            XCTAssertFalse(repo.hasUncommittedChanges())\n            // We should be on detached head.\n            XCTAssertEqual(try repo.currentBranch(), \"HEAD\")\n\n            // Try again and checkout to a previous branch.\n            try createAndStageTestFile()\n            XCTAssert(repo.hasUncommittedChanges())\n            try repo.checkout(revision: Revision(identifier: \"TestBranch\"))\n            XCTAssertFalse(repo.hasUncommittedChanges())\n            XCTAssertEqual(try repo.currentBranch(), \"TestBranch\")\n\n            do {\n                try repo.checkout(revision: Revision(identifier: \"nonExistent\"))\n                XCTFail(\"Unexpected checkout success on non existent branch\")\n            } catch {}\n        }\n    }\n\n    func testSubmodules() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            let provider = GitRepositoryProvider()\n\n            // Create repos: foo and bar, foo will have bar as submodule and then later\n            // the submodule ref will be updated in foo.\n            let fooPath = path.appending(\"foo-original\")\n            let fooSpecifier = RepositorySpecifier(path: fooPath)\n            let fooRepoPath = path.appending(\"foo-repo\")\n            let fooWorkingPath = path.appending(\"foo-working\")\n            let barPath = path.appending(\"bar-original\")\n            let bazPath = path.appending(\"baz-original\")\n            // Create the repos and add a file.\n            for path in [fooPath, barPath, bazPath] {\n                try makeDirectories(path)\n                initGitRepo(path)\n                try localFileSystem.writeFileContents(path.appending(\"hello.txt\"), bytes: \"hello\")\n                let repo = GitRepository(path: path)\n                try repo.stageEverything()\n                try repo.commit()\n            }\n            let foo = GitRepository(path: fooPath)\n            let bar = GitRepository(path: barPath)\n            // The tag 1.0.0 does not contain the submodule.\n            try foo.tag(name: \"1.0.0\")\n\n            // Fetch and clone repo foo.\n            try await provider.fetch(repository: fooSpecifier, to: fooRepoPath)\n            _ = try await provider.createWorkingCopy(repository: fooSpecifier, sourcePath: fooRepoPath, at: fooWorkingPath, editable: false)\n\n            let fooRepo = GitRepository(path: fooRepoPath, isWorkingRepo: false)\n            let fooWorkingRepo = GitRepository(path: fooWorkingPath)\n\n            // Checkout the first tag which doesn't has submodule.\n            try fooWorkingRepo.checkout(tag: \"1.0.0\")\n            XCTAssertNoSuchPath(fooWorkingPath.appending(\"bar\"))\n\n            // Add submodule to foo and tag it as 1.0.1\n            try foo.checkout(newBranch: \"submodule\")\n            try await AsyncProcess.checkNonZeroExit(\n                args: Git.tool, \"-C\", fooPath.pathString, \"submodule\", \"add\", barPath.pathString, \"bar\",\n                environment: .init(Git.environmentBlock)\n            )\n\n            try foo.stageEverything()\n            try foo.commit()\n            try foo.tag(name: \"1.0.1\")\n\n            // Update our bare and working repos.\n            try fooRepo.fetch()\n            try fooWorkingRepo.fetch()\n            // Checkout the tag with submodule and expect submodules files to be present.\n            try fooWorkingRepo.checkout(tag: \"1.0.1\")\n            XCTAssertFileExists(fooWorkingPath.appending(components: \"bar\", \"hello.txt\"))\n            // Checkout the tag without submodule and ensure that the submodule files are gone.\n            try fooWorkingRepo.checkout(tag: \"1.0.0\")\n            XCTAssertNoSuchPath(fooWorkingPath.appending(components: \"bar\"))\n\n            // Add something to bar.\n            try localFileSystem.writeFileContents(barPath.appending(\"bar.txt\"), bytes: \"hello\")\n            // Add a submodule too to check for recursive submodules.\n            try await AsyncProcess.checkNonZeroExit(\n                args: Git.tool, \"-C\", barPath.pathString, \"submodule\", \"add\", bazPath.pathString, \"baz\",\n                environment: .init(Git.environmentBlock)\n            )\n\n            try bar.stageEverything()\n            try bar.commit()\n\n            // Update the ref of bar in foo and tag as 1.0.2\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", fooPath.appending(\"bar\").pathString, \"pull\")\n            try foo.stageEverything()\n            try foo.commit()\n            try foo.tag(name: \"1.0.2\")\n\n            try fooRepo.fetch()\n            try fooWorkingRepo.fetch()\n            // We should see the new file we added in the submodule.\n            try fooWorkingRepo.checkout(tag: \"1.0.2\")\n            XCTAssertFileExists(fooWorkingPath.appending(components: \"bar\", \"hello.txt\"))\n            XCTAssertFileExists(fooWorkingPath.appending(components: \"bar\", \"bar.txt\"))\n            XCTAssertFileExists(fooWorkingPath.appending(components: \"bar\", \"baz\", \"hello.txt\"))\n\n            // Double check.\n            try fooWorkingRepo.checkout(tag: \"1.0.0\")\n            XCTAssertNoSuchPath(fooWorkingPath.appending(components: \"bar\"))\n        }\n    }\n\n    func testAlternativeObjectStoreValidation() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath, tag: \"1.2.3\")\n            let repo = GitRepository(path: testRepoPath)\n            XCTAssertEqual(try repo.getTags(), [\"1.2.3\"])\n\n            // Clone it somewhere.\n            let testClonePath = path.appending(\"clone\")\n            let provider = GitRepositoryProvider()\n            let repoSpec = RepositorySpecifier(path: testRepoPath)\n            try await provider.fetch(repository: repoSpec, to: testClonePath)\n            let clonedRepo = provider.open(repository: repoSpec, at: testClonePath)\n            XCTAssertEqual(try clonedRepo.getTags(), [\"1.2.3\"])\n\n            // Clone off a checkout.\n            let checkoutPath = path.appending(\"checkout\")\n            let checkoutRepo = try await provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: false)\n\n            // The object store should be valid.\n            XCTAssertTrue(checkoutRepo.isAlternateObjectStoreValid(expected: testClonePath))\n\n            // Wrong path\n            XCTAssertFalse(checkoutRepo.isAlternateObjectStoreValid(expected: testClonePath.appending(UUID().uuidString)))\n\n            // Delete the clone (alternative object store).\n            try localFileSystem.removeFileTree(testClonePath)\n            XCTAssertFalse(checkoutRepo.isAlternateObjectStoreValid(expected: testClonePath))\n        }\n    }\n\n    func testAreIgnored() throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test_repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n            let repo = GitRepository(path: testRepoPath)\n\n            // Add a .gitignore\n            try localFileSystem.writeFileContents(testRepoPath.appending(\".gitignore\"), bytes: \"ignored_file1\\nignored file2\")\n\n            let ignored = try repo.areIgnored([testRepoPath.appending(\"ignored_file1\"), testRepoPath.appending(\"ignored file2\"), testRepoPath.appending(\"not ignored\")])\n            XCTAssertTrue(ignored[0])\n            XCTAssertTrue(ignored[1])\n            XCTAssertFalse(ignored[2])\n\n            let notIgnored = try repo.areIgnored([testRepoPath.appending(\"not_ignored\")])\n            XCTAssertFalse(notIgnored[0])\n        }\n    }\n\n    func testAreIgnoredWithSpaceInRepoPath() throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try testWithTemporaryDirectory { path in\n            // Create a repo.\n            let testRepoPath = path.appending(\"test repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n            let repo = GitRepository(path: testRepoPath)\n\n            // Add a .gitignore\n            try localFileSystem.writeFileContents(testRepoPath.appending(\".gitignore\"), bytes: \"ignored_file1\")\n\n            let ignored = try repo.areIgnored([testRepoPath.appending(\"ignored_file1\")])\n            XCTAssertTrue(ignored[0])\n        }\n    }\n\n    func testMissingDefaultBranch() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { path in\n            // Create a repository.\n            let testRepoPath = path.appending(\"test-repo\")\n            try makeDirectories(testRepoPath)\n            initGitRepo(testRepoPath)\n            let repo = GitRepository(path: testRepoPath)\n\n            // Create a `newMain` branch and remove `main`.\n            try repo.checkout(newBranch: \"newMain\")\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", testRepoPath.pathString, \"branch\", \"-D\", \"main\")\n\n            // Change the branch name to something non-existent.\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", testRepoPath.pathString, \"symbolic-ref\", \"HEAD\", \"refs/heads/_non_existent_branch_\")\n\n            // Clone it somewhere.\n            let testClonePath = path.appending(\"clone\")\n            let provider = GitRepositoryProvider()\n            let repoSpec = RepositorySpecifier(path: testRepoPath)\n            try await provider.fetch(repository: repoSpec, to: testClonePath)\n            let clonedRepo = provider.open(repository: repoSpec, at: testClonePath)\n            XCTAssertEqual(try clonedRepo.getTags(), [])\n\n            // Clone off a checkout.\n            let checkoutPath = path.appending(\"checkout\")\n            let checkoutRepo = try await provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: false)\n            XCTAssertNoSuchPath(checkoutPath.appending(\"file.swift\"))\n\n            // Try to check out the `main` branch.\n            try checkoutRepo.checkout(revision: Revision(identifier: \"newMain\"))\n            XCTAssertFileExists(checkoutPath.appending(\"file.swift\"))\n\n            // The following will throw if HEAD was set incorrectly and we didn't do a no-checkout clone.\n            XCTAssertNoThrow(try checkoutRepo.getCurrentRevision())\n        }\n    }\n\n    func testValidDirectoryLocalRelativeOrigin() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { tmpDir in\n            // Create a repository.\n            let packageDir = tmpDir.appending(\"SomePackage\")\n            try localFileSystem.createDirectory(packageDir)\n\n            // Create a repository manager for it.\n            let repoProvider = GitRepositoryProvider()\n            let repositoryManager = RepositoryManager(\n                fileSystem: localFileSystem,\n                path: packageDir,\n                provider: repoProvider,\n                delegate: .none\n            )\n\n            let customRemote = \"../OriginOfSomePackage.git\"\n\n            // Before initializing the directory with a git repo, it is never valid.\n            XCTAssertThrowsError(try repositoryManager.isValidDirectory(packageDir))\n            XCTAssertThrowsError(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(packageDir.pathString))))\n            XCTAssertThrowsError(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(customRemote))))\n\n            initGitRepo(packageDir)\n            // Set the remote.\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", packageDir.pathString, \"remote\", \"add\", \"origin\", customRemote)\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir))\n\n            let customRemoteWithoutPathExtension = (customRemote as NSString).deletingPathExtension\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(customRemote))))\n            // We consider the directory valid even if the remote does not have the same path extension - in this case we expected '.git'.\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(customRemoteWithoutPathExtension))))\n            // We consider the directory valid even if the remote does not have the same path extension - in this case we expected '.git'.\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for:  RepositorySpecifier(url: SourceControlURL((customRemote as NSString).deletingPathExtension + \"/\"))))\n\n            // The following ensure that are actually checking the remote's origin.\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: AbsolutePath(validating: \"/\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(\"/\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: packageDir)))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(packageDir.pathString))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: packageDir.appending(extension: \"git\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(packageDir.pathString.appending(\".git\")))))\n\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(\"https://mycustomdomain/some-package.git\"))))\n        }\n    }\n\n    func testValidDirectoryLocalAbsoluteOrigin() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { tmpDir in\n            // Create a repository.\n            let packageDir = tmpDir.appending(\"SomePackage\")\n            try localFileSystem.createDirectory(packageDir)\n\n            // Create a repository manager for it.\n            let repoProvider = GitRepositoryProvider()\n            let repositoryManager = RepositoryManager(\n                fileSystem: localFileSystem,\n                path: packageDir,\n                provider: repoProvider,\n                delegate: .none\n            )\n\n            let customRemote = tmpDir.appending(\"OriginOfSomePackage.git\")\n\n            // Before initializing the directory with a git repo, it is never valid.\n            XCTAssertThrowsError(try repositoryManager.isValidDirectory(packageDir))\n            XCTAssertThrowsError(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(packageDir.pathString))))\n            XCTAssertThrowsError(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(customRemote.pathString))))\n\n            initGitRepo(packageDir)\n            // Set the remote.\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", packageDir.pathString, \"remote\", \"add\", \"origin\", customRemote.pathString)\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir))\n\n            let customRemotePath = customRemote.pathString\n            let customRemotePathWithoutPathExtension = (customRemotePath as NSString).deletingPathExtension\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: customRemote)))\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(customRemotePath))))\n            // We consider the directory valid even if the remote does not have the same path extension - in this case we expected '.git'.\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: try AbsolutePath(validating: customRemotePathWithoutPathExtension))))\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(customRemotePathWithoutPathExtension))))\n            // We consider the directory valid even if the remote does not have the same path extension - in this case we expected '.git'.\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for:  RepositorySpecifier(path: try AbsolutePath(validating: customRemotePathWithoutPathExtension + \"/\"))))\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for:  RepositorySpecifier(url: SourceControlURL((customRemotePath as NSString).deletingPathExtension + \"/\"))))\n\n            // The following ensure that are actually checking the remote's origin.\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: AbsolutePath(validating: \"/\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(\"/\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: packageDir)))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(packageDir.pathString))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: packageDir.appending(extension: \"git\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(packageDir.pathString.appending(\".git\")))))\n\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(\"https://mycustomdomain/some-package.git\"))))\n        }\n    }\n\n    func testValidDirectoryRemoteOrigin() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8564\", skipSelfHostedCI: true)\n        try await testWithTemporaryDirectory { tmpDir in\n            // Create a repository.\n            let packageDir = tmpDir.appending(\"SomePackage\")\n            try localFileSystem.createDirectory(packageDir)\n\n            // Create a repository manager for it.\n            let repoProvider = GitRepositoryProvider()\n            let repositoryManager = RepositoryManager(\n                fileSystem: localFileSystem,\n                path: packageDir,\n                provider: repoProvider,\n                delegate: .none\n            )\n\n            let customRemote = try XCTUnwrap(URL(string: \"https://mycustomdomain/some-package.git\"))\n\n            // Before initializing the directory with a git repo, it is never valid.\n            XCTAssertThrowsError(try repositoryManager.isValidDirectory(packageDir))\n            XCTAssertThrowsError(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(customRemote))))\n\n            initGitRepo(packageDir)\n            // Set the remote.\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", packageDir.pathString, \"remote\", \"add\", \"origin\", customRemote.absoluteString)\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir))\n\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(customRemote))))\n            // We consider the directory valid even if the remote does not have the same path extension - in this case we expected '.git'.\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(\"https://mycustomdomain/some-package\"))))\n            // We consider the directory valid even if the remote does not have the same path extension - in this case we expected '.git'.\n            XCTAssertTrue(try repositoryManager.isValidDirectory(packageDir, for:  RepositorySpecifier(url: SourceControlURL(\"https://mycustomdomain/some-package/\"))))\n\n            // The following ensure that are actually checking the remote's origin.\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: AbsolutePath(validating: \"/\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(\"/\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: packageDir)))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(packageDir.pathString))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(path: packageDir.appending(extension: \"git\"))))\n            XCTAssertFalse(try repositoryManager.isValidDirectory(packageDir, for: RepositorySpecifier(url: SourceControlURL(packageDir.pathString.appending(\".git\")))))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SourceControlTests/InMemoryGitRepositoryTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\nimport Basics\nimport SourceControl\nimport _InternalTestSupport\nimport Testing\n\nstruct InMemoryGitRepositoryTests {\n    @Test\n    func basics() throws {\n        let fs = InMemoryFileSystem()\n        let repo = InMemoryGitRepository(path: .root, fs: fs)\n\n        try repo.createDirectory(\"/new-dir/subdir\", recursive: true)\n        #expect(!repo.hasUncommittedChanges())\n        let filePath = AbsolutePath(\"/new-dir/subdir\").appending(\"new-file.txt\")\n\n        try repo.writeFileContents(filePath, bytes: \"one\")\n        #expect(try repo.readFileContents(filePath) == \"one\")\n        #expect(repo.hasUncommittedChanges())\n\n        let firstCommit = try repo.commit()\n        #expect(!repo.hasUncommittedChanges())\n\n        #expect(try repo.readFileContents(filePath) == \"one\")\n        #expect(try fs.readFileContents(filePath) == \"one\")\n\n        try repo.writeFileContents(filePath, bytes: \"two\")\n        #expect(try repo.readFileContents(filePath) == \"two\")\n        #expect(repo.hasUncommittedChanges())\n\n        let secondCommit = try repo.commit()\n        #expect(!repo.hasUncommittedChanges())\n        #expect(try repo.readFileContents(filePath) == \"two\")\n\n        try repo.writeFileContents(filePath, bytes: \"three\")\n        #expect(repo.hasUncommittedChanges())\n        #expect(try repo.readFileContents(filePath) == \"three\")\n\n        try repo.checkout(revision: firstCommit)\n        #expect(!repo.hasUncommittedChanges())\n        #expect(try repo.readFileContents(filePath) == \"one\")\n        #expect(try fs.readFileContents(filePath) == \"one\")\n\n        try repo.checkout(revision: secondCommit)\n        #expect(!repo.hasUncommittedChanges())\n        #expect(try repo.readFileContents(filePath) == \"two\")\n\n        #expect(try repo.getTags().isEmpty)\n        try repo.tag(name: \"2.0.0\")\n        #expect(try repo.getTags() == [\"2.0.0\"])\n        #expect(!repo.hasUncommittedChanges())\n        #expect(try repo.readFileContents(filePath) == \"two\")\n        #expect(try fs.readFileContents(filePath) == \"two\")\n\n        try repo.checkout(revision: firstCommit)\n        #expect(!repo.hasUncommittedChanges())\n        #expect(try repo.readFileContents(filePath) == \"one\")\n\n        try repo.checkout(tag: \"2.0.0\")\n        #expect(!repo.hasUncommittedChanges())\n        #expect(try repo.readFileContents(filePath) == \"two\")\n    }\n\n    @Test\n    func provider() async throws {\n        let v1 = \"1.0.0\"\n        let v2 = \"2.0.0\"\n        let repo = InMemoryGitRepository(path: .root, fs: InMemoryFileSystem())\n\n        let specifier = RepositorySpecifier(path: \"/Foo\")\n        try repo.createDirectory(\"/new-dir/subdir\", recursive: true)\n        let filePath = AbsolutePath(\"/new-dir/subdir\").appending(\"new-file.txt\")\n        try repo.writeFileContents(filePath, bytes: \"one\")\n        try repo.commit()\n        try repo.tag(name: v1)\n        try repo.writeFileContents(filePath, bytes: \"two\")\n        try repo.commit()\n        try repo.tag(name: v2)\n\n        let provider = InMemoryGitRepositoryProvider()\n        provider.add(specifier: specifier, repository: repo)\n\n        let fooRepoPath = AbsolutePath(\"/fooRepo\")\n        try await provider.fetch(repository: specifier, to: fooRepoPath)\n        let fooRepo = try provider.open(repository: specifier, at: fooRepoPath)\n\n        // Adding a new tag in original repo shouldn't show up in fetched repo.\n        try repo.tag(name: \"random\")\n        #expect(try fooRepo.getTags().sorted() == [v1, v2])\n        #expect(fooRepo.exists(revision: try fooRepo.resolveRevision(tag: v1)))\n\n        let fooCheckoutPath = AbsolutePath(\"/fooCheckout\")\n        #expect(!(try provider.workingCopyExists(at: fooCheckoutPath)))\n        _ = try await provider.createWorkingCopy(repository: specifier, sourcePath: fooRepoPath, at: fooCheckoutPath, editable: false)\n        #expect(try provider.workingCopyExists(at: fooCheckoutPath))\n        let fooCheckout = try await provider.openWorkingCopy(at: fooCheckoutPath)\n\n        #expect(try fooCheckout.getTags().sorted() == [v1, v2])\n        #expect(fooCheckout.exists(revision: try fooCheckout.getCurrentRevision()))\n        let checkoutRepo = try provider.openRepo(at: fooCheckoutPath)\n\n        try fooCheckout.checkout(tag: v1)\n        #expect(try checkoutRepo.readFileContents(filePath) == \"one\")\n\n        try fooCheckout.checkout(tag: v2)\n        #expect(try checkoutRepo.readFileContents(filePath) == \"two\")\n    }\n}\n"
  },
  {
    "path": "Tests/SourceControlTests/RepositoryManagerTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n@testable import Basics\nimport _Concurrency\nimport PackageModel\nimport _InternalTestSupport\n@testable import SourceControl\nimport XCTest\n\nfinal class RepositoryManagerTests: XCTestCase {\n    func testBasics() async throws {\n        let fs = localFileSystem\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await testWithTemporaryDirectory { path in\n            let provider = DummyRepositoryProvider(fileSystem: fs)\n            let delegate = DummyRepositoryManagerDelegate()\n\n            let manager = RepositoryManager(\n                fileSystem: fs,\n                path: path,\n                provider: provider,\n                delegate: delegate\n            )\n\n            let dummyRepo = RepositorySpecifier(path: \"/dummy\")\n            let badDummyRepo = RepositorySpecifier(path: \"/badDummy\")\n            var prevHandle: RepositoryManager.RepositoryHandle?\n\n            // Check that we can \"fetch\" a repository.\n\n            do {\n                delegate.prepare(fetchExpected: true, updateExpected: false)\n                let handle = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n                XCTAssertNoDiagnostics(observability.diagnostics)\n\n                prevHandle = handle\n                XCTAssertEqual(provider.numFetches, 0)\n\n                // Open the repository.\n                let repository = try! await handle.open()\n                XCTAssertEqual(try! repository.getTags(), [\"1.0.0\"])\n\n                // Create a checkout of the repository.\n                let checkoutPath = path.appending(\"checkout\")\n                _ = try! await handle.createWorkingCopy(at: checkoutPath, editable: false)\n\n                XCTAssertDirectoryExists(checkoutPath)\n                XCTAssertFileExists(checkoutPath.appending(\"README.txt\"))\n\n                try await delegate.wait(timeout: .now() + 2)\n                XCTAssertEqual(delegate.willFetch.map { $0.repository }, [dummyRepo])\n                XCTAssertEqual(delegate.didFetch.map { $0.repository }, [dummyRepo])\n            }\n\n            // Get a bad repository.\n            do {\n                delegate.prepare(fetchExpected: true, updateExpected: false)\n                await XCTAssertAsyncThrowsError(try await manager.lookup(repository: badDummyRepo, observabilityScope: observability.topScope)) { error in\n                    XCTAssertEqual(error as? DummyError, DummyError.invalidRepository)\n                }\n\n                XCTAssertNotNil(prevHandle)\n\n                try await delegate.wait(timeout: .now() + 2)\n                XCTAssertEqual(delegate.willFetch.map { $0.repository }, [dummyRepo, badDummyRepo])\n                XCTAssertEqual(delegate.didFetch.map { $0.repository }, [dummyRepo, badDummyRepo])\n                // We shouldn't have made any update call yet.\n                XCTAssert(delegate.willUpdate.isEmpty)\n                XCTAssert(delegate.didUpdate.isEmpty)\n            }\n\n            do {\n                delegate.prepare(fetchExpected: false, updateExpected: true)\n                let handle = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                XCTAssertEqual(handle.repository, dummyRepo)\n                XCTAssertEqual(handle.repository, prevHandle?.repository)\n\n                // We should always get back the same handle once fetched.\n                // Since we looked up this repo again, we should have made a fetch call.\n                try await delegate.wait(timeout: .now() + 2)\n                XCTAssertEqual(provider.numFetches, 1)\n                XCTAssertEqual(delegate.willUpdate, [dummyRepo])\n                XCTAssertEqual(delegate.didUpdate, [dummyRepo])\n            }\n\n            // Remove the repo.\n            do {\n                try manager.remove(repository: dummyRepo)\n\n                // Check removing the repo updates the persistent file.\n                /*do {\n                    let checkoutsStateFile = path.appending(\"checkouts-state.json\")\n                    let jsonData = try JSON(bytes: localFileSystem.readFileContents(checkoutsStateFile))\n                    XCTAssertEqual(jsonData.dictionary?[\"object\"]?.dictionary?[\"repositories\"]?.dictionary?[dummyRepo.location.description], nil)\n                }*/\n\n                // We should get a new handle now because we deleted the existing repository.\n                delegate.prepare(fetchExpected: true, updateExpected: false)\n                let handle = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                XCTAssertEqual(handle.repository, dummyRepo)\n\n                // We should have tried fetching these two.\n                try await delegate.wait(timeout: .now() + 2)\n                XCTAssertEqual(delegate.willFetch.map { $0.repository }, [dummyRepo, badDummyRepo, dummyRepo])\n                XCTAssertEqual(delegate.didFetch.map { $0.repository }, [dummyRepo, badDummyRepo, dummyRepo])\n                XCTAssertEqual(delegate.willUpdate, [dummyRepo])\n                XCTAssertEqual(delegate.didUpdate, [dummyRepo])\n            }\n        }\n    }\n\n    func testCache() async throws {\n        let fs = localFileSystem\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await fixtureXCTest(name: \"DependencyResolution/External/Simple\", createGitRepo: true) { (fixturePath: AbsolutePath) in\n            let cachePath = fixturePath.appending(\"cache\")\n            let repositoriesPath = fixturePath.appending(\"repositories\")\n            let repo = RepositorySpecifier(path: fixturePath.appending(\"Foo\"))\n\n            let provider = GitRepositoryProvider()\n            let delegate = DummyRepositoryManagerDelegate()\n\n            let manager = RepositoryManager(\n                fileSystem: fs,\n                path: repositoriesPath,\n                provider: provider,\n                cachePath: cachePath,\n                cacheLocalPackages: true,\n                delegate: delegate\n            )\n\n            // fetch packages and populate cache\n            delegate.prepare(fetchExpected: true, updateExpected: false)\n            _ = try await manager.lookup(repository: repo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try XCTAssertDirectoryExists(cachePath.appending(repo.storagePath()))\n            try XCTAssertDirectoryExists(repositoriesPath.appending(repo.storagePath()))\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch[0].details,\n                           RepositoryManager.FetchDetails(fromCache: false, updatedCache: false))\n            XCTAssertEqual(try delegate.didFetch[0].result.get(),\n                           RepositoryManager.FetchDetails(fromCache: false, updatedCache: true))\n\n            // removing the repositories path to force re-fetch\n            try fs.removeFileTree(repositoriesPath)\n\n            // fetch packages from the cache\n            delegate.prepare(fetchExpected: true, updateExpected: false)\n            _ = try await manager.lookup(repository: repo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try XCTAssertDirectoryExists(repositoriesPath.appending(repo.storagePath()))\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch[1].details,\n                           RepositoryManager.FetchDetails(fromCache: true, updatedCache: false))\n            XCTAssertEqual(try delegate.didFetch[1].result.get(),\n                           RepositoryManager.FetchDetails(fromCache: true, updatedCache: true))\n\n            //  reset the state on disk\n            try fs.removeFileTree(cachePath)\n            try fs.removeFileTree(repositoriesPath)\n\n            // fetch packages and populate cache\n            delegate.prepare(fetchExpected: true, updateExpected: false)\n            _ = try await manager.lookup(repository: repo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try XCTAssertDirectoryExists(cachePath.appending(repo.storagePath()))\n            try XCTAssertDirectoryExists(repositoriesPath.appending(repo.storagePath()))\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch[2].details,\n                           RepositoryManager.FetchDetails(fromCache: false, updatedCache: false))\n            XCTAssertEqual(try delegate.didFetch[2].result.get(),\n                           RepositoryManager.FetchDetails(fromCache: false, updatedCache: true))\n\n            // update packages from the cache\n            delegate.prepare(fetchExpected: false, updateExpected: true)\n            _ = try await manager.lookup(repository: repo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try await delegate.wait(timeout: .now() + 2)\n            try XCTAssertEqual(delegate.willUpdate[0].storagePath(), repo.storagePath())\n            try XCTAssertEqual(delegate.didUpdate[0].storagePath(), repo.storagePath())\n        }\n    }\n\n    func testReset() async throws {\n        let fs = localFileSystem\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await testWithTemporaryDirectory { path in\n            let repos = path.appending(\"repo\")\n            let provider = DummyRepositoryProvider(fileSystem: fs)\n            let delegate = DummyRepositoryManagerDelegate()\n\n            try fs.createDirectory(repos, recursive: true)\n\n            let manager = RepositoryManager(\n                fileSystem: fs,\n                path: repos,\n                provider: provider,\n                delegate: delegate\n            )\n            let dummyRepo = RepositorySpecifier(path: \"/dummy\")\n\n            delegate.prepare(fetchExpected: true, updateExpected: false)\n            _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            delegate.prepare(fetchExpected: false, updateExpected: true)\n            _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, 1)\n            XCTAssertEqual(delegate.didFetch.count, 1)\n\n            manager.reset(observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n\n            XCTAssertTrue(!fs.isDirectory(repos))\n            try fs.createDirectory(repos, recursive: true)\n\n            delegate.prepare(fetchExpected: true, updateExpected: false)\n            _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, 2)\n            XCTAssertEqual(delegate.didFetch.count, 2)\n        }\n    }\n\n    /// Check that the manager is persistent.\n    func testPersistence() async throws {\n        let fs = localFileSystem\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await testWithTemporaryDirectory { path in\n            let provider = DummyRepositoryProvider(fileSystem: fs)\n            let dummyRepo = RepositorySpecifier(path: \"/dummy\")\n\n            // Do the initial fetch.\n            do {\n                let delegate = DummyRepositoryManagerDelegate()\n                let manager = RepositoryManager(\n                    fileSystem: fs,\n                    path: path,\n                    provider: provider,\n                    delegate: delegate\n                )\n\n                delegate.prepare(fetchExpected: true, updateExpected: false)\n                _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                try await delegate.wait(timeout: .now() + 2)\n                XCTAssertEqual(delegate.willFetch.map { $0.repository }, [dummyRepo])\n                XCTAssertEqual(delegate.didFetch.map { $0.repository }, [dummyRepo])\n            }\n            // We should have performed one fetch.\n            XCTAssertEqual(provider.numClones, 1)\n            XCTAssertEqual(provider.numFetches, 0)\n\n            // Create a new manager, and fetch.\n            do {\n                let delegate = DummyRepositoryManagerDelegate()\n                let manager = RepositoryManager(\n                    fileSystem: fs,\n                    path: path,\n                    provider: provider,\n                    delegate: delegate\n                )\n\n                delegate.prepare(fetchExpected: true, updateExpected: false)\n                _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                // This time fetch shouldn't be called.\n                try await delegate.wait(timeout: .now() + 2)\n                XCTAssertEqual(delegate.willFetch.map { $0.repository }, [])\n            }\n            // We shouldn't have done a new fetch.\n            XCTAssertEqual(provider.numClones, 1)\n            XCTAssertEqual(provider.numFetches, 1)\n\n            // Manually destroy the manager state, and check it still works.\n            do {\n                let delegate = DummyRepositoryManagerDelegate()\n                var manager = RepositoryManager(\n                    fileSystem: fs,\n                    path: path,\n                    provider: provider,\n                    delegate: delegate\n                )\n                try! fs.removeFileTree(path.appending(dummyRepo.storagePath()))\n                manager = RepositoryManager(\n                    fileSystem: fs,\n                    path: path,\n                    provider: provider,\n                    delegate: delegate\n                )\n                let dummyRepo = RepositorySpecifier(path: \"/dummy\")\n\n                delegate.prepare(fetchExpected: true, updateExpected: false)\n                _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n                XCTAssertNoDiagnostics(observability.diagnostics)\n                try await delegate.wait(timeout: .now() + 2)\n                XCTAssertEqual(delegate.willFetch.map { $0.repository }, [dummyRepo])\n                XCTAssertEqual(delegate.didFetch.map { $0.repository }, [dummyRepo])\n            }\n            // We should have re-fetched.\n            XCTAssertEqual(provider.numClones, 2)\n            XCTAssertEqual(provider.numFetches, 1)\n        }\n    }\n\n    func testCanonicalLocation() throws {\n        let variants: [RepositorySpecifier] = [\n            .init(url: \"https://scm.com/org/foo\"),\n            .init(url: \"https://scm.com/org/foo.git\"),\n        ]\n\n        for variant in variants {\n            XCTAssertEqual(try variant.storagePath(), try variants[0].storagePath())\n        }\n    }\n\n    func testConcurrency() async throws {\n        let fs = localFileSystem\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await testWithTemporaryDirectory { path in\n            let provider = DummyRepositoryProvider(fileSystem: fs)\n            let delegate = DummyRepositoryManagerDelegate()\n            let manager = RepositoryManager(\n                fileSystem: fs,\n                path: path,\n                provider: provider,\n                delegate: delegate\n            )\n            let dummyRepoPath = try AbsolutePath(validating: \"/dummy\")\n            let dummyRepo = RepositorySpecifier(path: dummyRepoPath)\n\n            let results = ThreadSafeKeyValueStore<Int, RepositoryManager.RepositoryHandle>()\n            let concurrency = 10000\n            try await withThrowingTaskGroup(of: Void.self) { group in\n                for index in 0 ..< concurrency {\n                    group.addTask {\n                        delegate.prepare(fetchExpected: index == 0, updateExpected: index > 0)\n                        results[index] = try await manager.lookup(\n                            package: PackageIdentity(path: dummyRepoPath),\n                            repository: dummyRepo,\n                            updateStrategy: .always,\n                            observabilityScope: observability.topScope\n                        )\n                    }\n                }\n                try await group.waitForAll()\n            }\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, 1)\n            XCTAssertEqual(delegate.didFetch.count, 1)\n            XCTAssertEqual(delegate.willUpdate.count, concurrency - 1)\n            XCTAssertEqual(delegate.didUpdate.count, concurrency - 1)\n\n            XCTAssertEqual(results.count, concurrency)\n            for index in 0 ..< concurrency {\n                XCTAssertEqual(results[index]?.repository, dummyRepo)\n            }\n        }\n    }\n\n    func testSkipUpdate() async throws {\n        let fs = localFileSystem\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await testWithTemporaryDirectory { path in\n            let repos = path.appending(\"repo\")\n            let provider = DummyRepositoryProvider(fileSystem: fs)\n            let delegate = DummyRepositoryManagerDelegate()\n\n            try fs.createDirectory(repos, recursive: true)\n\n            let manager = RepositoryManager(\n                fileSystem: fs,\n                path: repos,\n                provider: provider,\n                delegate: delegate\n            )\n            let dummyRepo = RepositorySpecifier(path: \"/dummy\")\n\n            delegate.prepare(fetchExpected: true, updateExpected: false)\n            _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, 1)\n            XCTAssertEqual(delegate.didFetch.count, 1)\n            XCTAssertEqual(delegate.willUpdate.count, 0)\n            XCTAssertEqual(delegate.didUpdate.count, 0)\n\n            delegate.prepare(fetchExpected: false, updateExpected: true)\n            _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            delegate.prepare(fetchExpected: false, updateExpected: true)\n            _ = try await manager.lookup(repository: dummyRepo, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, 1)\n            XCTAssertEqual(delegate.didFetch.count, 1)\n            XCTAssertEqual(delegate.willUpdate.count, 2)\n            XCTAssertEqual(delegate.didUpdate.count, 2)\n\n            delegate.prepare(fetchExpected: false, updateExpected: false)\n            _ = try await manager.lookup(repository: dummyRepo, updateStrategy: .never, observabilityScope: observability.topScope)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            try await delegate.wait(timeout: .now() + 2)\n            XCTAssertEqual(delegate.willFetch.count, 1)\n            XCTAssertEqual(delegate.didFetch.count, 1)\n            XCTAssertEqual(delegate.willUpdate.count, 2)\n            XCTAssertEqual(delegate.didUpdate.count, 2)\n        }\n    }\n\n    func testCancel() throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let cancellator = Cancellator(observabilityScope: observability.topScope)\n\n        let total = 10\n        let provider = MockRepositoryProvider(total: total)\n        let manager = RepositoryManager(\n            fileSystem: InMemoryFileSystem(),\n            path: .root,\n            provider: provider,\n            maxConcurrentOperations: total\n        )\n\n        cancellator.register(name: \"repository manager\", handler: manager)\n\n        let finishGroup = DispatchGroup()\n        let results = ThreadSafeKeyValueStore<RepositorySpecifier, Result<RepositoryManager.RepositoryHandle, Error>>()\n        for index in 0 ..< total {\n            let path = try AbsolutePath(validating: \"/repo/\\(index)\")\n            let repository = RepositorySpecifier(path: path)\n            provider.startGroup.enter()\n            finishGroup.enter()\n            manager.lookup(\n                package: PackageIdentity(path: path),\n                repository: repository,\n                updateStrategy: .never,\n                observabilityScope: observability.topScope,\n                callbackQueue: .sharedConcurrent\n            ) { result in\n                defer { finishGroup.leave() }\n                results[repository] = result\n            }\n        }\n\n        XCTAssertEqual(.success, provider.startGroup.wait(timeout: .now() + 5), \"timeout starting tasks\")\n\n        let cancelled = cancellator._cancel(deadline: .now() + .seconds(1))\n        XCTAssertEqual(cancelled, 1, \"expected to be terminated\")\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        // this releases the fetch threads that are waiting to test if the call was cancelled\n        provider.terminatedGroup.leave()\n\n        XCTAssertEqual(.success, finishGroup.wait(timeout: .now() + 5), \"timeout finishing tasks\")\n\n        XCTAssertEqual(results.count, total, \"expected \\(total) results\")\n        for (repository, result) in results.get() {\n            switch (Int(repository.basename)! < total / 2, result) {\n            case (true, .success):\n                break // as expected!\n            case (true, .failure(let error)):\n                XCTFail(\"expected success, but failed with \\(type(of: error)) '\\(error)'\")\n            case (false, .success):\n                XCTFail(\"expected operation to be cancelled\")\n            case (false, .failure(let error)):\n                XCTAssert(error is CancellationError, \"expected error to be CancellationError, but was \\(type(of: error)) '\\(error)'\")\n            }\n        }\n\n        // wait for outstanding threads that would be cancelled and completion handlers thrown away\n        XCTAssertEqual(.success, provider.outstandingGroup.wait(timeout: .now() + .seconds(5)), \"timeout waiting for outstanding tasks\")\n\n        // the provider called in a thread managed by the RepositoryManager\n        // the use of blocking semaphore is intentional\n        class MockRepositoryProvider: RepositoryProvider, @unchecked Sendable {\n            let total: Int\n            // this DispatchGroup is used to wait for the requests to start before calling cancel\n            let startGroup = DispatchGroup()\n            // this DispatchGroup is used to park the delayed threads that would be cancelled\n            let terminatedGroup = DispatchGroup()\n            // this DispatchGroup is used to monitor the outstanding threads that would be cancelled and completion handlers thrown away\n            let outstandingGroup = DispatchGroup()\n\n            init(total: Int) {\n                self.total = total\n                self.terminatedGroup.enter()\n            }\n\n            func fetch(repository: RepositorySpecifier, to path: AbsolutePath, progressHandler: ((FetchProgress) -> Void)?) async throws {\n                print(\"fetching \\(repository)\")\n                // startGroup may not be 100% accurate given the blocking nature of the provider so giving it a bit of a buffer\n                DispatchQueue.sharedConcurrent.asyncAfter(deadline: .now() + .milliseconds(100)) {\n                    self.startGroup.leave()\n                }\n                if Int(repository.basename)! >= total / 2 {\n                    self.outstandingGroup.enter()\n                    defer { self.outstandingGroup.leave() }\n                    print(\"\\(repository) waiting to be cancelled\")\n                    await withCheckedContinuation { continuation in\n                        self.terminatedGroup.notify(queue: DispatchQueue.sharedConcurrent) {\n                            continuation.resume()\n                        }\n                    }\n                }\n                print(\"\\(repository) okay\")\n            }\n\n            func open(repository: RepositorySpecifier, at path: AbsolutePath) throws -> Repository {\n                fatalError(\"should not be called\")\n            }\n\n            func createWorkingCopy(repository: RepositorySpecifier, sourcePath: AbsolutePath, at destinationPath: AbsolutePath, editable: Bool) async throws -> WorkingCheckout {\n                fatalError(\"should not be called\")\n            }\n\n            func workingCopyExists(at path: AbsolutePath) throws -> Bool {\n                fatalError(\"should not be called\")\n            }\n\n            func openWorkingCopy(at path: AbsolutePath) async throws -> WorkingCheckout {\n                fatalError(\"should not be called\")\n            }\n\n            func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {\n                fatalError(\"should not be called\")\n            }\n\n            func isValidDirectory(_ directory: AbsolutePath) throws -> Bool {\n                return false\n            }\n\n            public func isValidDirectory(_ directory: AbsolutePath, for repository: RepositorySpecifier) throws -> Bool {\n                fatalError(\"should not be called\")\n            }\n\n            func cancel(deadline: DispatchTime) throws {\n                print(\"cancel\")\n            }\n        }\n    }\n\n    func testInvalidRepositoryOnDisk() async throws {\n        let fileSystem = localFileSystem\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await testWithTemporaryDirectory { path in\n            let repositoriesDirectory = path.appending(\"repositories\")\n            try fileSystem.createDirectory(repositoriesDirectory, recursive: true)\n\n            let testRepository = RepositorySpecifier(url: .init(\"test-\\(UUID().uuidString)\"))\n            let provider = MockRepositoryProvider(repository: testRepository)\n\n            let manager = RepositoryManager(\n                fileSystem: fileSystem,\n                path: repositoriesDirectory,\n                provider: provider,\n                delegate: nil\n            )\n\n            _ = try await manager.lookup(repository: testRepository, observabilityScope: observability.topScope)\n            testDiagnostics(observability.diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\"is not valid git repository for '\\(testRepository)', will fetch again\"),\n                    severity: .warning\n                )\n            }\n        }\n\n        class MockRepositoryProvider: RepositoryProvider, @unchecked Sendable {\n            let repository: RepositorySpecifier\n            var fetch: Int = 0\n\n            init(repository: RepositorySpecifier) {\n                self.repository = repository\n            }\n\n            func fetch(repository: RepositorySpecifier, to path: AbsolutePath, progressHandler: ((FetchProgress) -> Void)?) async throws {\n                assert(repository == self.repository)\n                self.fetch += 1\n            }\n\n            func open(repository: RepositorySpecifier, at path: AbsolutePath) throws -> Repository {\n                return MockRepository()\n            }\n\n            func createWorkingCopy(repository: RepositorySpecifier, sourcePath: AbsolutePath, at destinationPath: AbsolutePath, editable: Bool) async throws -> WorkingCheckout {\n                fatalError(\"should not be called\")\n            }\n\n            func workingCopyExists(at path: AbsolutePath) throws -> Bool {\n                fatalError(\"should not be called\")\n            }\n\n            func openWorkingCopy(at path: AbsolutePath) async throws -> WorkingCheckout {\n                fatalError(\"should not be called\")\n            }\n\n            func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {\n                fatalError(\"should not be called\")\n            }\n\n            func isValidDirectory(_ directory: AbsolutePath) throws -> Bool {\n                // the directory exists\n                return true\n            }\n\n            public func isValidDirectory(_ directory: AbsolutePath, for repository: RepositorySpecifier) throws -> Bool {\n                assert(repository == self.repository)\n                // the directory is not valid\n                return false\n            }\n\n            func cancel(deadline: DispatchTime) throws {\n                fatalError(\"should not be called\")\n            }\n        }\n\n        class MockRepository: Repository {\n            func getTags() throws -> [String] {\n                fatalError(\"unexpected API call\")\n            }\n\n            func resolveRevision(tag: String) throws -> Revision {\n                fatalError(\"unexpected API call\")\n            }\n\n            func resolveRevision(identifier: String) throws -> Revision {\n                fatalError(\"unexpected API call\")\n            }\n\n            func exists(revision: Revision) -> Bool {\n                fatalError(\"unexpected API call\")\n            }\n\n            func fetch() throws {\n                // noop\n            }\n\n            func openFileView(revision: Revision) throws -> FileSystem {\n                fatalError(\"unexpected API call\")\n            }\n\n            public func openFileView(tag: String) throws -> FileSystem {\n                fatalError(\"unexpected API call\")\n            }\n        }\n    }\n}\n\nextension RepositoryManager {\n    public convenience init(\n        fileSystem: FileSystem,\n        path: AbsolutePath,\n        provider: RepositoryProvider,\n        cachePath: AbsolutePath? =  .none,\n        cacheLocalPackages: Bool = false,\n        maxConcurrentOperations: Int? = .none,\n        delegate: RepositoryManagerDelegate? = .none\n    ) {\n        self.init(\n            fileSystem: fileSystem,\n            path: path,\n            provider: provider,\n            cachePath: cachePath,\n            cacheLocalPackages: cacheLocalPackages,\n            maxConcurrentOperations: maxConcurrentOperations,\n            initializationWarningHandler: { _ in },\n            delegate: delegate\n        )\n    }\n\n    fileprivate func lookup(\n        repository: RepositorySpecifier,\n        updateStrategy: RepositoryUpdateStrategy = .always,\n        observabilityScope: ObservabilityScope\n    ) async throws -> RepositoryHandle {\n        try await self.lookup(\n            package: .init(url: SourceControlURL(repository.url)),\n            repository: repository,\n            updateStrategy: updateStrategy,\n            observabilityScope: observabilityScope\n        )\n    }\n}\n\nprivate enum DummyError: Swift.Error {\n    case invalidRepository\n}\n\nprivate class DummyRepositoryProvider: RepositoryProvider, @unchecked Sendable {\n    private let fileSystem: FileSystem\n\n    private let lock = NSLock()\n    private var _numClones = 0\n    private var _numFetches = 0\n\n    init(fileSystem: FileSystem) {\n        self.fileSystem = fileSystem\n    }\n\n    func fetch(repository: RepositorySpecifier, to path: AbsolutePath, progressHandler: FetchProgress.Handler? = nil) async throws {\n        assert(!self.fileSystem.exists(path), \"\\(path) should not exist\")\n        try self.fileSystem.createDirectory(path, recursive: true)\n        try self.fileSystem.writeFileContents(path.appending(\"readme.md\"), string: repository.location.description)\n\n        self.lock.withLock {\n            self._numClones += 1\n        }\n\n        // We only support one dummy URL.\n        let basename = repository.basename\n        if basename != \"dummy\" {\n            throw DummyError.invalidRepository\n        }\n    }\n\n    func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {\n        try self.fileSystem.copy(from: sourcePath, to: destinationPath)\n\n        self.lock.withLock {\n            self._numClones += 1\n        }\n\n        // We only support one dummy URL.\n        let basename = sourcePath.basename\n        if basename != \"dummy\" {\n            throw DummyError.invalidRepository\n        }\n    }\n\n    func open(repository: RepositorySpecifier, at path: AbsolutePath) -> Repository {\n        return DummyRepository(provider: self)\n    }\n\n    func createWorkingCopy(repository: RepositorySpecifier, sourcePath: AbsolutePath, at destinationPath: AbsolutePath, editable: Bool) async throws -> WorkingCheckout  {\n        try self.fileSystem.createDirectory(destinationPath)\n        try self.fileSystem.writeFileContents(destinationPath.appending(\"README.txt\"), bytes: \"Hi\")\n        return try await self.openWorkingCopy(at: destinationPath)\n    }\n\n    func workingCopyExists(at path: AbsolutePath) throws -> Bool {\n        return false\n    }\n\n    func openWorkingCopy(at path: AbsolutePath) async throws -> WorkingCheckout {\n        return DummyWorkingCheckout(at: path)\n    }\n\n    func isValidDirectory(_ directory: AbsolutePath) throws -> Bool {\n        return self.fileSystem.isDirectory(directory)\n    }\n\n    func isValidDirectory(_ directory: AbsolutePath, for repository: RepositorySpecifier) throws -> Bool {\n        return true\n    }\n\n    func cancel(deadline: DispatchTime) throws {\n        // noop\n    }\n\n    func increaseFetchCount() {\n        self.lock.withLock {\n            self._numFetches += 1\n        }\n    }\n\n    var numClones: Int {\n        self.lock.withLock {\n            self._numClones\n        }\n    }\n\n    var numFetches: Int {\n        self.lock.withLock {\n            self._numFetches\n        }\n    }\n\n    struct DummyWorkingCheckout: WorkingCheckout {\n        let path : AbsolutePath\n\n        init(at path: AbsolutePath) {\n            self.path = path\n        }\n\n        func getTags() throws -> [String] {\n            fatalError(\"not implemented\")\n        }\n\n        func getCurrentRevision() throws -> Revision {\n            fatalError(\"not implemented\")\n        }\n\n        func fetch() throws {\n            fatalError(\"not implemented\")\n        }\n\n        func hasUnpushedCommits() throws -> Bool {\n            fatalError(\"not implemented\")\n        }\n\n        func hasUncommittedChanges() -> Bool {\n            fatalError(\"not implemented\")\n        }\n\n        func checkout(tag: String) throws {\n            fatalError(\"not implemented\")\n        }\n\n        func checkout(revision: Revision) throws {\n            fatalError(\"not implemented\")\n        }\n\n        func exists(revision: Revision) -> Bool {\n            fatalError(\"not implemented\")\n        }\n\n        func checkout(newBranch: String) throws {\n            fatalError(\"not implemented\")\n        }\n\n        func isAlternateObjectStoreValid(expected: AbsolutePath) -> Bool {\n            fatalError(\"not implemented\")\n        }\n\n        func areIgnored(_ paths: [AbsolutePath]) throws -> [Bool] {\n            fatalError(\"not implemented\")\n        }\n    }\n}\n\nfileprivate class DummyRepositoryManagerDelegate: RepositoryManager.Delegate, @unchecked Sendable {\n    private var _willFetch = ThreadSafeArrayStore<(repository: RepositorySpecifier, details: RepositoryManager.FetchDetails)>()\n    private var _didFetch = ThreadSafeArrayStore<(repository: RepositorySpecifier, result: Result<RepositoryManager.FetchDetails, Error>)>()\n    private var _willUpdate = ThreadSafeArrayStore<RepositorySpecifier>()\n    private var _didUpdate = ThreadSafeArrayStore<RepositorySpecifier>()\n\n    private var group = DispatchGroup()\n\n    public func prepare(fetchExpected: Bool, updateExpected: Bool) {\n        if fetchExpected {\n            self.group.enter() // will fetch\n            self.group.enter() // did fetch\n        }\n        if updateExpected {\n            self.group.enter() // will update\n            self.group.enter() // did v\n        }\n    }\n\n    public func reset() {\n        self.group = DispatchGroup()\n        self._willFetch = .init()\n        self._didFetch = .init()\n        self._willUpdate = .init()\n        self._didUpdate = .init()\n    }\n\n    public func wait(timeout: DispatchTime) async throws {\n        try await withCheckedThrowingContinuation { continuation in\n            self.group.notify(queue: DispatchQueue.sharedConcurrent) {\n                continuation.resume()\n            }\n        }\n    }\n\n    var willFetch: [(repository: RepositorySpecifier, details: RepositoryManager.FetchDetails)] {\n        return self._willFetch.get()\n    }\n\n    var didFetch: [(repository: RepositorySpecifier, result: Result<RepositoryManager.FetchDetails, Error>)] {\n        return self._didFetch.get()\n    }\n\n    var willUpdate: [RepositorySpecifier] {\n        return self._willUpdate.get()\n    }\n\n    var didUpdate: [RepositorySpecifier] {\n        return self._didUpdate.get()\n    }\n\n    func willFetch(package: PackageIdentity, repository: RepositorySpecifier, details: RepositoryManager.FetchDetails) {\n        self._willFetch.append((repository: repository, details: details))\n        self.group.leave()\n    }\n\n    func fetching(package: PackageIdentity, repository: RepositorySpecifier, objectsFetched: Int, totalObjectsToFetch: Int) {\n    }\n\n    func didFetch(package: PackageIdentity, repository: RepositorySpecifier, result: Result<RepositoryManager.FetchDetails, Error>, duration: DispatchTimeInterval) {\n        self._didFetch.append((repository: repository, result: result))\n        self.group.leave()\n    }\n\n    func willUpdate(package: PackageIdentity, repository: RepositorySpecifier) {\n        self._willUpdate.append(repository)\n        self.group.leave()\n    }\n\n    func didUpdate(package: PackageIdentity, repository: RepositorySpecifier, duration: DispatchTimeInterval) {\n        self._didUpdate.append(repository)\n        self.group.leave()\n    }\n}\n\nfileprivate class DummyRepository: Repository {\n    unowned let provider: DummyRepositoryProvider\n\n    init(provider: DummyRepositoryProvider) {\n        self.provider = provider\n    }\n\n    func getTags() throws -> [String] {\n        [\"1.0.0\"]\n    }\n\n    func resolveRevision(tag: String) throws -> Revision {\n        fatalError(\"unexpected API call\")\n    }\n\n    func resolveRevision(identifier: String) throws -> Revision {\n        fatalError(\"unexpected API call\")\n    }\n\n    func exists(revision: Revision) -> Bool {\n        fatalError(\"unexpected API call\")\n    }\n\n    func fetch() throws {\n        self.provider.increaseFetchCount()\n    }\n\n    func openFileView(revision: Revision) throws -> FileSystem {\n        fatalError(\"unexpected API call\")\n    }\n\n    public func openFileView(tag: String) throws -> FileSystem {\n        fatalError(\"unexpected API call\")\n    }\n}\n"
  },
  {
    "path": "Tests/SourceKitLSPAPITests/SourceKitLSPAPITests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Build\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport PackageGraph\n\nimport PackageModel\n@testable import SourceKitLSPAPI\nimport SPMBuildCore\nimport _InternalTestSupport\nimport XCTest\n\nfinal class SourceKitLSPAPITests: XCTestCase {\n    func testBasicSwiftPackage() async throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/exe/README.md\",\n            \"/Pkg/Sources/exe/exe.docc/GettingStarted.md\",\n            \"/Pkg/Sources/exe/Resources/some_file.txt\",\n            \"/Pkg/Sources/lib/lib.swift\",\n            \"/Pkg/Sources/lib/README.md\",\n            \"/Pkg/Sources/lib/lib.docc/GettingStarted.md\",\n            \"/Pkg/Sources/lib/Resources/some_file.txt\",\n            \"/Pkg/Plugins/plugin/plugin.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    toolsVersion: .v5_10,\n                    targets: [\n                        TargetDescription(\n                            name: \"exe\",\n                            dependencies: [\"lib\"],\n                            resources: [.init(rule: .copy, path: \"Resources/some_file.txt\")],\n                            type: .executable\n                        ),\n                        TargetDescription(\n                            name: \"lib\",\n                            dependencies: [],\n                            resources: [.init(rule: .copy, path: \"Resources/some_file.txt\")]\n                        ),\n                        TargetDescription(name: \"plugin\", type: .plugin, pluginCapability: .buildTool)\n                    ]),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let description = BuildDescription(buildPlan: plan)\n\n        try description.checkArguments(\n            for: \"exe\",\n            graph: graph,\n            partialArguments: [\n                \"-module-name\", \"exe\",\n                \"-package-name\", \"pkg\",\n                \"-emit-dependencies\",\n                \"-emit-module\",\n                \"-emit-module-path\", AbsolutePath(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/debug/Modules/exe.swiftmodule\").pathString\n            ],\n            resources: [.init(filePath: \"/Pkg/Sources/exe/Resources/some_file.txt\")],\n            ignoredFiles: [.init(filePath: \"/Pkg/Sources/exe/exe.docc\")],\n            otherFiles: [.init(filePath: \"/Pkg/Sources/exe/README.md\")],\n            isPartOfRootPackage: true\n        )\n        try description.checkArguments(\n            for: \"lib\",\n            graph: graph,\n            partialArguments: [\n                \"-module-name\", \"lib\",\n                \"-package-name\", \"pkg\",\n                \"-emit-dependencies\",\n                \"-emit-module\",\n                \"-emit-module-path\", AbsolutePath(\"/path/to/build/\\(plan.destinationBuildParameters.triple)/debug/Modules/lib.swiftmodule\").pathString\n            ],\n            resources: [.init(filePath: \"/Pkg/Sources/lib/Resources/some_file.txt\")],\n            ignoredFiles: [.init(filePath: \"/Pkg/Sources/lib/lib.docc\")],\n            otherFiles: [.init(filePath: \"/Pkg/Sources/lib/README.md\")],\n            isPartOfRootPackage: true\n        )\n        try description.checkArguments(\n            for: \"plugin\",\n            graph: graph,\n            partialArguments: [\n                \"-I\", AbsolutePath(\"/fake/manifestLib/path\").pathString\n            ],\n            isPartOfRootPackage: true,\n            destination: .host\n        )\n    }\n\n    func testModuleTraversal() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.swift\",\n            \"/Pkg/Plugins/plugin/plugin.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: []),\n                        TargetDescription(\n                            name: \"plugin\",\n                            dependencies: [\"exe\"],\n                            type: .plugin,\n                            pluginCapability: .buildTool\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let description = BuildDescription(buildPlan: plan)\n\n        struct Result: Equatable {\n            let moduleName: String\n            let moduleDestination: BuildDestination\n            let parentName: String?\n            let parentDestination: BuildDestination?\n        }\n\n        var results: [Result] = []\n        description.traverseModules { current, parent in\n            results.append(\n                Result(\n                    moduleName: current.name,\n                    moduleDestination: current.destination,\n                    parentName: parent?.name,\n                    parentDestination: parent?.destination\n                )\n            )\n        }\n\n        XCTAssertEqual(\n            results,\n            [\n                Result(moduleName: \"lib\", moduleDestination: .target, parentName: nil, parentDestination: nil),\n                Result(moduleName: \"plugin\", moduleDestination: .host, parentName: nil, parentDestination: nil),\n                Result(moduleName: \"exe\", moduleDestination: .host, parentName: \"plugin\", parentDestination: .host),\n                Result(moduleName: \"lib\", moduleDestination: .host, parentName: \"exe\", parentDestination: .host),\n                Result(moduleName: \"exe\", moduleDestination: .target, parentName: nil, parentDestination: nil),\n                Result(moduleName: \"lib\", moduleDestination: .target, parentName: \"exe\", parentDestination: .target),\n            ]\n        )\n    }\n\n    func testModuleTraversalRecordsDependencyOfVisitedNode() async throws {\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Pkg/Sources/exe/main.swift\",\n            \"/Pkg/Sources/lib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    targets: [\n                        TargetDescription(name: \"exe\", dependencies: [\"lib\"]),\n                        TargetDescription(name: \"lib\", dependencies: [])\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let description = BuildDescription(buildPlan: plan)\n\n        struct Result: Equatable {\n            let moduleName: String\n            let parentName: String?\n        }\n\n        var results: [Result] = []\n        description.traverseModules { current, parent in\n            results.append(Result(moduleName: current.name, parentName: parent?.name))\n        }\n\n        XCTAssertEqual(\n            results,\n            [\n                Result(moduleName: \"lib\", parentName: nil),\n                Result(moduleName: \"exe\", parentName: nil),\n                Result(moduleName: \"lib\", parentName: \"exe\"),\n            ]\n        )\n    }\n\n    func testLoadPackage() async throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Pkg/Sources/lib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    toolsVersion: .v5_10,\n                    targets: [\n                        TargetDescription(\n                            name: \"lib\",\n                            dependencies: []\n                        )\n                    ]),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let destinationBuildParameters = mockBuildParameters(destination: .target)\n        try await withTemporaryDirectory { tmpDir in\n            let pluginConfiguration = PluginConfiguration(\n                scriptRunner: DefaultPluginScriptRunner(\n                    fileSystem: fs,\n                    cacheDir: tmpDir.appending(\"cache\"),\n                    toolchain: try UserToolchain.default\n                ),\n                workDirectory: tmpDir.appending(\"work\"),\n                disableSandbox: false\n            )\n            let scratchDirectory = tmpDir.appending(\".build\")\n\n            let loaded = try await BuildDescription.load(\n                destinationBuildParameters: destinationBuildParameters,\n                toolsBuildParameters: mockBuildParameters(destination: .host),\n                packageGraph: graph,\n                pluginConfiguration: pluginConfiguration,\n                traitConfiguration: TraitConfiguration(),\n                disableSandbox: false,\n                scratchDirectory: scratchDirectory.asURL,\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n\n            try loaded.description.checkArguments(\n                for: \"lib\",\n                graph: graph,\n                partialArguments: [\n                    \"-module-name\", \"lib\",\n                    \"-package-name\", \"pkg\",\n                    \"-emit-dependencies\",\n                    \"-emit-module\",\n                    \"-emit-module-path\", AbsolutePath(\"/path/to/build/\\(destinationBuildParameters.triple)/debug/Modules/lib.swiftmodule\").pathString\n                ],\n                isPartOfRootPackage: true\n            )\n        }\n    }\n\n    func testClangOutputPaths() async throws {\n        let fs = InMemoryFileSystem(emptyFiles:\n            \"/Pkg/Sources/lib/include/lib.h\",\n            \"/Pkg/Sources/lib/lib.cpp\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Pkg\",\n                    path: \"/Pkg\",\n                    toolsVersion: .v5_10,\n                    targets: [\n                        TargetDescription(\n                            name: \"lib\",\n                            dependencies: []\n                        )\n                    ]),\n            ],\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n        let plan = try await BuildPlan(\n            destinationBuildParameters: mockBuildParameters(\n                destination: .target,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            toolsBuildParameters: mockBuildParameters(\n                destination: .host,\n                shouldLinkStaticSwiftStdlib: true\n            ),\n            graph: graph,\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let description = BuildDescription(buildPlan: plan)\n\n        let target = try XCTUnwrap(description.getBuildTarget(for: XCTUnwrap(graph.module(for: \"lib\")), destination: .target))\n        XCTAssertEqual(target.compiler, .clang)\n        XCTAssertEqual(target.sources.count, 1)\n        XCTAssertEqual(target.sources.last?.outputFile?.lastPathComponent, \"lib.cpp.o\")\n    }\n}\n\nextension SourceKitLSPAPI.BuildDescription {\n    @discardableResult func checkArguments(\n        for targetName: String,\n        graph: ModulesGraph,\n        partialArguments: [String],\n        resources: [URL] = [],\n        ignoredFiles: [URL] = [],\n        otherFiles: [URL] = [],\n        isPartOfRootPackage: Bool,\n        destination: BuildParameters.Destination = .target\n    ) throws -> Bool {\n        let target = try XCTUnwrap(graph.module(for: targetName))\n        let buildTarget = try XCTUnwrap(self.getBuildTarget(for: target, destination: destination))\n\n        XCTAssertEqual(buildTarget.resources, resources, \"build target \\(targetName) contains unexpected resource files\")\n        XCTAssertEqual(buildTarget.ignored, ignoredFiles, \"build target \\(targetName) contains unexpected ignored files\")\n        XCTAssertEqual(buildTarget.others, otherFiles, \"build target \\(targetName) contains unexpected other files\")\n\n        guard let source = buildTarget.sources.first?.sourceFile else {\n            XCTFail(\"build target \\(targetName) contains no source files\")\n            return false\n        }\n\n        let arguments = try buildTarget.compileArguments(for: source)\n        let result = arguments.contains(partialArguments)\n\n        XCTAssertTrue(result, \"could not match \\(partialArguments) to actual arguments \\(arguments)\")\n        XCTAssertEqual(buildTarget.isPartOfRootPackage, isPartOfRootPackage)\n        return result\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftBuildSupportTests/CGenPIFTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2026 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\nimport Basics\nimport PackageLoading\nimport SwiftBuildSupport\nimport Testing\nimport _InternalTestSupport\nimport SwiftBuild\n\n@testable import SPMBuildCore\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly) @testable import PackageGraph\n@_spi(SwiftPMInternal) @testable import PackageModel\n\n@Suite struct CGenPIFTests {\n    enum Kind {\n        case cModule\n        case swiftModule\n    }\n\n    let pluginOutputDir: Basics.AbsolutePath = \"/plugin-working-dir/outputs/mypkg/MyModule/tools/MyPlugin\"\n    var pluginIncludeDir: Basics.AbsolutePath { pluginOutputDir.appending(\"include\") }\n    var pluginModuleMapFile: Basics.AbsolutePath { pluginIncludeDir.appending(\"module.modulemap\") }\n    var pluginModuleMapArg: String { \"-fmodule-map-file=\\(pluginModuleMapFile.pathString)\" }\n    var pluginAPINotesFile: Basics.AbsolutePath { pluginIncludeDir.appending(\"Gened.apinotes\")}\n    var pluginHeaderFile: Basics.AbsolutePath { pluginIncludeDir.appending(\"Gened.h\")}\n    var pluginSourceFile: Basics.AbsolutePath { pluginOutputDir.appending(\"Gened.c\") }\n\n    func setup(\n        kind: Kind = .cModule,\n        gened: [RelativePath],\n        toolsVersion: ToolsVersion? = nil,\n        observability: ObservabilityScope\n    ) async throws -> SwiftBuildSupport.PIF.TopLevelObject {\n        let toolsVersion = try toolsVersion ?? #require(ToolsVersion(string: \"6.3\", experimentalFeatures: [.experimentalCGen]))\n        let sources = switch kind {\n        case .cModule:\n            [\n                \"/MyPkg/Sources/MyModule/MyModule.c\",\n                \"/MyPkg/Sources/MyModule/include/MyModule.h\",\n            ]\n        case .swiftModule:\n            [\n                \"/MyPkg/Sources/MyModule/MyModule.swift\",\n            ]\n        }\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPkg/Plugins/MyPlugin/MyPlugin.swift\",\n                \"/MyPkg/Sources/MyGenerator/MyGenerator.swift\",\n                \"/MyPkg/Sources/MyModule/data.in\",\n                \"/MyPkg/Sources/MyCModule/include/MyCModule.h\",\n                \"/MyPkg/Sources/MyCModule/MyCModule.c\",\n                \"/MyPkg/Sources/MyExe/MyExe.swift\"\n            ] + sources\n        )\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                .createRootManifest(\n                    displayName: \"MyPkg\",\n                    path: \"/MyPkg\",\n                    toolsVersion: toolsVersion,\n                    products: [\n                        .init(name: \"MyExe\", type: .executable, targets: [\"MyExe\"]),\n                    ],\n                    targets: [\n                        .init(name: \"MyGenerator\", type: .executable),\n                        .init(\n                            name: \"MyPlugin\",\n                            dependencies: [\"MyGenerator\"],\n                            type: .plugin,\n                            pluginCapability: .buildTool\n                        ),\n                        .init(name: \"MyModule\", dependencies: [\"MyPlugin\"]),\n                        .init(name: \"MyCModule\", dependencies: [\"MyModule\"]),\n                        .init(name: \"MyExe\", dependencies: [\"MyCModule\"], type: .executable)\n                    ]\n                )\n            ],\n            observabilityScope: observability\n        )\n\n        // TODO: this should be made a utility\n        struct MockPluginScriptRunner: PluginScriptRunner {\n            let genMessages: (\n                _ sourceFiles: [Basics.AbsolutePath],\n                _ workingDirectory: Basics.AbsolutePath,\n            ) -> [PluginToHostMessage]\n\n            func compilePluginScript(\n                sourceFiles: [Basics.AbsolutePath],\n                pluginName: String,\n                toolsVersion: PackageModel.ToolsVersion,\n                workers: UInt32,\n                observabilityScope: Basics.ObservabilityScope,\n                callbackQueue: DispatchQueue,\n                delegate: any SPMBuildCore.PluginScriptCompilerDelegate,\n                completion: @escaping (Result<SPMBuildCore.PluginCompilationResult, any Error>) -> Void)\n            {\n                callbackQueue.sync {\n                    completion(.failure(StringError(\"unimplemented\")))\n                }\n            }\n\n            func runPluginScript(\n                sourceFiles: [Basics.AbsolutePath],\n                pluginName: String,\n                initialMessage: Data,\n                toolsVersion: PackageModel.ToolsVersion,\n                workingDirectory: Basics.AbsolutePath,\n                writableDirectories: [Basics.AbsolutePath],\n                readOnlyDirectories: [Basics.AbsolutePath],\n                allowNetworkConnections: [Basics.SandboxNetworkPermission],\n                workers: UInt32,\n                fileSystem: any Basics.FileSystem,\n                observabilityScope: Basics.ObservabilityScope,\n                callbackQueue: DispatchQueue,\n                delegate: any SPMBuildCore.PluginScriptCompilerDelegate & SPMBuildCore.PluginScriptRunnerDelegate,\n                completion: @escaping (Result<Int32, any Error>) -> Void)\n            {\n                callbackQueue.sync {\n                    do {\n                        let decoder = JSONDecoder.makeWithDefaults()\n                        let encoder = JSONEncoder(outputFormatting: .prettyPrinted)\n\n                        let initial = try decoder.decode(HostToPluginMessage.self, from: initialMessage)\n                        guard case let .createBuildToolCommands(context: context, rootPackageId: _, targetId: _, pluginGeneratedSources: _, pluginGeneratedResources: _) = initial else {\n                            completion(.failure(StringError(\"Invalid initial message\")))\n                            return\n                        }\n                        let workDir = try context.url(for: context.pluginWorkDirId)\n\n                        for message in genMessages(sourceFiles, workDir) {\n                            let data = try encoder.encode(message)\n                            try delegate.handleMessage(data: data, responder: { _ in })\n                        }\n                        completion(.success(0))\n                    } catch {\n                        completion(.failure(error))\n                    }\n                }\n            }\n\n            var hostTriple: Triple {\n                get throws {\n                    return try UserToolchain.default.targetTriple\n                }\n            }\n        }\n\n        let pluginScriptRunner = MockPluginScriptRunner { sourceFiles, outputDirectory in\n            let inFiles = sourceFiles.filter({ $0.extension == \"in\" }).map(\\.asURL)\n            let outFiles = gened.map({ outputDirectory.appending($0).asURL })\n\n            return [\n                .defineBuildCommand(\n                    configuration: .init(\n                        executable: URL(filePath: \"/foo\"),\n                        arguments: [],\n                        environment: [:]\n                    ),\n                    inputFiles: inFiles,\n                    outputFiles: outFiles\n                )\n            ]\n        }\n\n        let pifBuilder: PIFBuilder = PIFBuilder(\n            graph: graph,\n            parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(\n                temporaryDirectory: AbsolutePath.root,\n                addLocalRpaths: true,\n                pluginScriptRunner: pluginScriptRunner\n            ),\n            fileSystem: fs,\n            observabilityScope: observability\n        )\n\n        return try await pifBuilder.constructPIF(\n            buildParameters: mockBuildParameters(destination: .host)\n        )\n    }\n\n    /// This is more to test out that the setup routines provide a good test environment\n    @Test func testSwift() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try await setup(\n            kind: .swiftModule,\n            gened: [\"Gened.swift\"],\n            observability: observability.topScope\n        )\n        #expect(!observability.hasErrorDiagnostics && !observability.hasWarningDiagnostics)\n    }\n\n    @Test func testSuccessPath() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        let pif = try await setup(\n            gened: [\n                \"include/Gened.h\",\n                \"include/module.modulemap\",\n                \"include/Gened.apinotes\",\n                \"Gened.c\",\n            ], observability: observability.topScope\n        )\n        #expect(!observability.hasErrorDiagnostics && !observability.hasWarningDiagnostics)\n\n        let project = try #require(pif.workspace.projects.filter({ $0.underlying.name == \"MyPkg\" }).only)\n        let modules = project.underlying.targets.filter({ $0.common.name == \"MyModule\" })\n        for module in modules {\n            for config in module.common.buildConfigs {\n                let headerSearchPaths = try #require(config.settings[.HEADER_SEARCH_PATHS])\n                #expect(headerSearchPaths.contains(pluginIncludeDir.pathString))\n                let impartedHeaderPaths = try #require(config.impartedBuildProperties.settings[.HEADER_SEARCH_PATHS])\n                #expect(impartedHeaderPaths.contains(pluginIncludeDir.pathString))\n\n                let impartedCFlags = try #require(config.impartedBuildProperties.settings[.OTHER_CFLAGS])\n                #expect(impartedCFlags.contains(pluginModuleMapArg))\n                let impartedSwiftFlags = try #require(config.impartedBuildProperties.settings[.OTHER_SWIFT_FLAGS])\n                #expect(impartedSwiftFlags.contains(pluginModuleMapArg))\n            }\n\n            // Make sure our generated source is included\n            let sourcesPhase: ProjectModel.SourcesBuildPhase = try #require(module.common.buildPhases.compactMap({\n                guard case let .sources(sourcesBuildPhase) = $0 else {\n                    return nil\n                }\n                return sourcesBuildPhase\n            }).only)\n            let x = sourcesPhase.files.contains(where: {\n                guard case .reference(id: let refId) = $0.ref,\n                      let file = try? project.underlying.mainGroup.findSource(ref: refId)\n                else {\n                    return false\n                }\n                return file == pluginSourceFile\n            })\n            #expect(x)\n        }\n    }\n\n    /// Test that generating C into Swift modules throws warnings\n    @Test func testCinSwift() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try await setup(\n            kind: .swiftModule,\n            gened: [\n                \"include/Gened.h\",\n                \"include/module.modulemap\",\n                \"include/Gened.apinotes\",\n                \"Gened.c\",\n            ], observability: observability.topScope\n        )\n\n        let warnings = observability.warnings.map(\\.message)\n        let messages: [String] = [\n            \"Only C modules support plugin generated C header files: \\(pluginHeaderFile.pathString)\",\n            \"Only C modules support plugin generated module map files: \\(pluginModuleMapFile.pathString)\",\n            \"Only C modules support plugin generated API notes files: \\(pluginAPINotesFile.pathString)\",\n            \"Only C modules support plugin generated C source files: \\(pluginSourceFile.pathString)\",\n        ]\n\n        for message in messages {\n            #expect(warnings.contains(message))\n        }\n    }\n\n    /// Test that the feature is disabled on previous tools versions\n    @Test func testOldToolsVersion() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n        _ = try await setup(\n            gened: [\n                \"include/Gened.h\",\n                \"include/module.modulemap\",\n                \"include/Gened.apinotes\",\n                \"Gened.c\",\n            ],\n            toolsVersion: .v6_2,\n            observability: observability.topScope\n        )\n        let warnings = observability.warnings.map(\\.message)\n        let messages: [String] = [\n            \"C header file generation not enabled: \\(pluginHeaderFile.pathString)\",\n            \"Module map generation not enabled: \\(pluginModuleMapFile.pathString)\",\n            \"API notes generation not enabled: \\(pluginAPINotesFile.pathString)\",\n            \"C source file generation not enabled: \\(pluginSourceFile.pathString)\",\n        ]\n\n        for message in messages {\n            #expect(warnings.contains(message))\n        }\n    }\n}\n\nextension HostToPluginMessage.InputContext {\n    func url(for id: WireInput.URL.Id) throws -> Basics.AbsolutePath {\n        // Compose a path based on an optional base path and a subpath.\n        let wirePath = paths[id]\n        let basePath = try paths[id].baseURLId.map{ try self.url(for: $0) }\n        let path: Basics.AbsolutePath\n        if let basePath {\n            path = basePath.appending(wirePath.subpath)\n        } else {\n            path = AbsolutePath.root.appending(wirePath.subpath)\n        }\n        return path\n    }\n}\n\nextension ProjectModel.Group {\n    func findSource(ref: GUID) throws -> Basics.AbsolutePath? {\n        for child in subitems {\n            switch child {\n            case .file(let file):\n                if file.id == ref {\n                    if let file = try? Basics.AbsolutePath(validating: file.path) {\n                        return file\n                    }\n                    guard self.pathBase == .absolute else {\n                        return nil\n                    }\n                    let groupPath = try Basics.AbsolutePath(validating: self.path)\n                    return groupPath.appending(file.path)\n                }\n            case .group(let group):\n                if let file = try group.findSource(ref: ref) {\n                    return file\n                }\n            }\n        }\n        return nil\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftBuildSupportTests/PIFBuilderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Testing\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SPMBuildCore\nimport SwiftBuild\nimport SwiftBuildSupport\nimport _InternalTestSupport\nimport Workspace\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly) import PackageGraph\n\n// MARK: - Helpers\n\nextension PIFBuilderParameters {\n    static func constructDefaultParametersForTesting(\n        temporaryDirectory: Basics.AbsolutePath,\n        addLocalRpaths: Bool,\n        shouldCreateDylibForDynamicProducts: Bool = false,\n        pluginScriptRunner: PluginScriptRunner? = nil\n    ) throws -> Self {\n        try self.init(\n            isPackageAccessModifierSupported: true,\n            enableTestability: false,\n            shouldCreateDylibForDynamicProducts: shouldCreateDylibForDynamicProducts,\n            materializeStaticArchiveProductsForRootPackages: true,\n            createDynamicVariantsForLibraryProducts: false,\n            toolchainLibDir: temporaryDirectory.appending(component: \"toolchain-lib-dir\"),\n            pkgConfigDirectories: [],\n            supportedSwiftVersions: [.v4, .v4_2, .v5, .v6],\n            pluginScriptRunner: pluginScriptRunner ?? DefaultPluginScriptRunner(\n                fileSystem: localFileSystem,\n                cacheDir: temporaryDirectory.appending(component: \"plugin-cache-dir\"),\n                toolchain: try UserToolchain.default\n            ),\n            disableSandbox: false,\n            pluginWorkingDirectory: temporaryDirectory.appending(component: \"plugin-working-dir\"),\n            additionalFileRules: [],\n            addLocalRPaths: addLocalRpaths\n        )\n    }\n}\n\nfileprivate func withGeneratedPIF(\n    fromFixture fixtureName: String,\n    addLocalRpaths: Bool = true,\n    shouldCreateDylibForDynamicProducts: Bool = true,\n    buildParameters: BuildParameters? = nil,\n    do doIt: (SwiftBuildSupport.PIF.TopLevelObject, TestingObservability) async throws -> ()\n) async throws {\n    let buildParameters = if let buildParameters {\n        buildParameters\n    } else {\n        mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild)\n    }\n    try await fixture(name: fixtureName) { fixturePath in\n        let observabilitySystem: TestingObservability = ObservabilitySystem.makeForTesting(verbose: false)\n        let toolchain = try UserToolchain.default\n        var config = WorkspaceConfiguration.default\n        config.shouldCreateMultipleTestProducts = true\n        let workspace = try Workspace(\n            fileSystem: localFileSystem,\n            forRootPackage: fixturePath,\n            configuration: config,\n            customManifestLoader: ManifestLoader(toolchain: toolchain),\n            delegate: MockWorkspaceDelegate()\n        )\n        let rootInput = PackageGraphRootInput(packages: [fixturePath], dependencies: [])\n        let graph = try await workspace.loadPackageGraph(\n            rootInput: rootInput,\n            observabilityScope: observabilitySystem.topScope\n        )\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(\n                temporaryDirectory: fixturePath,\n                addLocalRpaths: addLocalRpaths,\n                shouldCreateDylibForDynamicProducts: shouldCreateDylibForDynamicProducts\n            ),\n            fileSystem: localFileSystem,\n            observabilityScope: observabilitySystem.topScope\n        )\n        let pif = try await builder.constructPIF(\n            buildParameters: buildParameters,\n        )\n        try await doIt(pif, observabilitySystem)\n    }\n}\n\nextension SwiftBuildSupport.PIF.Workspace {\n    fileprivate func project(named name: String) throws -> SwiftBuildSupport.PIF.Project {\n        let matchingProjects = projects.filter {\n            $0.underlying.name == name\n        }\n        if matchingProjects.isEmpty {\n            throw StringError(\"No project named \\(name) in PIF workspace\")\n        } else if matchingProjects.count > 1 {\n            throw StringError(\"Multiple projects named \\(name) in PIF workspace\")\n        } else {\n            return matchingProjects[0]\n        }\n    }\n}\n\nextension SwiftBuildSupport.PIF.Project {\n    fileprivate func target(id: String) throws -> ProjectModel.BaseTarget {\n        let matchingTargets: [ProjectModel.BaseTarget] = underlying.targets.filter {\n            return $0.common.id.value == String(id)\n        }\n        if matchingTargets.isEmpty {\n            throw StringError(\"No target named \\(id) in PIF project\")\n        } else if matchingTargets.count > 1 {\n            throw StringError(\"Multiple target named \\(id) in PIF project\")\n        } else {\n            return matchingTargets[0]\n        }\n    }\n\n    fileprivate func target(named name: String) throws -> ProjectModel.BaseTarget {\n        let matchingTargets = underlying.targets.filter {\n            $0.common.name == name\n        }\n        switch matchingTargets.count {\n        case 0:\n            throw StringError(\"No target named \\(name) in PIF project\")\n        case 1:\n            return matchingTargets[0]\n        case 2:\n            if let nonDynamicVariant = matchingTargets.filter({ !$0.id.value.hasSuffix(\"-dynamic\") }).only {\n                return nonDynamicVariant\n            } else {\n                fallthrough\n            }\n        default:\n            throw StringError(\"Multiple targets named \\(name) in PIF project\")\n        }\n    }\n\n    fileprivate func buildConfig(named name: BuildConfiguration) throws -> SwiftBuild.ProjectModel.BuildConfig {\n        let matchingConfigs = underlying.buildConfigs.filter {\n            $0.name == name.pifConfiguration\n        }\n        if matchingConfigs.isEmpty {\n            throw StringError(\"No config named \\(name) in PIF project\")\n        } else if matchingConfigs.count > 1 {\n            throw StringError(\"Multiple configs named \\(name) in PIF project\")\n        } else {\n            return matchingConfigs[0]\n        }\n    }\n}\n\nextension SwiftBuild.ProjectModel.BaseTarget {\n    fileprivate func buildConfig(named name: BuildConfiguration) throws -> SwiftBuild.ProjectModel.BuildConfig {\n        let matchingConfigs = common.buildConfigs.filter {\n            $0.name == name.pifConfiguration\n        }\n        if matchingConfigs.isEmpty {\n            throw StringError(\"No config named \\(name) in PIF target\")\n        } else if matchingConfigs.count > 1 {\n            throw StringError(\"Multiple configs named \\(name) in PIF target\")\n        } else {\n            return matchingConfigs[0]\n        }\n    }\n}\n\nextension BuildConfiguration {\n    var pifConfiguration: String {\n        switch self {\n            case .debug, .release: self.rawValue.capitalized\n        }\n    }\n}\n\n// MARK: - Tests\n\n@Suite(\n    .tags(\n        .TestSize.medium,\n        .FunctionalArea.PIF\n    )\n)\nstruct PIFBuilderTests {\n\n    struct RootPackagesTestData {\n        let id: String\n        let rootPackages: [(name: String, path: Basics.AbsolutePath)]\n        let expectedData: (pifPath: Basics.AbsolutePath, pifName: String, pifId: String)\n    }\n    @Test(\n        arguments:[\n            RootPackagesTestData(\n                id: \"Single root package, package path at root\",\n                rootPackages: [\n                    (name: \"fooPackage\", path: AbsolutePath(\"/fooPackage\")),\n                ],\n                expectedData: (\n                    pifPath: \"/fooPackage\",\n                    pifName: \"fooPackage\",\n                    pifId: \"/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Single root package, package path nested \",\n                rootPackages: [\n                    (name: \"fooPackage\", path: AbsolutePath(\"/a/b/c/d/fooPackage\")),\n                ],\n                expectedData: (\n                    pifPath: \"/a/b/c/d/fooPackage\",\n                    pifName: \"fooPackage\",\n                    pifId: \"/a/b/c/d/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Two root packages, unordered, no common parent directory\",\n                rootPackages: [\n                    (name: \"fooPackage\", path: AbsolutePath(\"/fooPackage\")),\n                    (name: \"barPackage\", path: AbsolutePath(\"/barPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath.root,\n                    pifName: \"barPackage,fooPackage\",\n                    pifId: \"/barPackage,/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Two root packages, ordered, no common parent directory\",\n                rootPackages: [\n                    (name: \"barPackage\", path: AbsolutePath(\"/barPackage\")),\n                    (name: \"fooPackage\", path: AbsolutePath(\"/fooPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath.root,\n                    pifName: \"barPackage,fooPackage\",\n                    pifId: \"/barPackage,/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Two root packages, unordered, no common parent directory\",\n                rootPackages: [\n                    (name: \"fooPackage\", path: AbsolutePath(\"/fooPackage\")),\n                    (name: \"barPackage\", path: AbsolutePath(\"/barPackage\")),\n                    (name: \"bazPackage\", path: AbsolutePath(\"/bazPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath.root,\n                    pifName: \"barPackage,bazPackage,fooPackage\",\n                    pifId: \"/barPackage,/bazPackage,/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Multiple root packages, ordered, no common parent directory\",\n                rootPackages: [\n                    (name: \"barPackage\", path: AbsolutePath(\"/barPackage\")),\n                    (name: \"bazPackage\", path: AbsolutePath(\"/bazPackage\")),\n                    (name: \"fooPackage\", path: AbsolutePath(\"/fooPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath.root,\n                    pifName: \"barPackage,bazPackage,fooPackage\",\n                    pifId: \"/barPackage,/bazPackage,/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Two root packages, unordered, contains common directory, packages are sibling\",\n                rootPackages: [\n                    (name: \"fooPackage\", path: AbsolutePath(\"/a/b/c/fooPackage\")),\n                    (name: \"barPackage\", path: AbsolutePath(\"/a/b/c/barPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath(\"/a/b/c\"),\n                    pifName: \"barPackage,fooPackage\",\n                    pifId: \"/a/b/c/barPackage,/a/b/c/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Two root packages, ordered, contains common directory, packages are sibling\",\n                rootPackages: [\n                    (name: \"barPackage\", path: AbsolutePath(\"/a/b/c/barPackage\")),\n                    (name: \"fooPackage\", path: AbsolutePath(\"/a/b/c/fooPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath(\"/a/b/c\"),\n                    pifName: \"barPackage,fooPackage\",\n                    pifId: \"/a/b/c/barPackage,/a/b/c/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Two root packages, ybordered, contains common directory, packages are not siblings\",\n                rootPackages: [\n                    (name: \"fooPackage\", path: AbsolutePath(\"/a/b/c/pink/fuzz/fooPackage\")),\n                    (name: \"barPackage\", path: AbsolutePath(\"/a/b/c/absolute/zero/barPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath(\"/a/b/c\"),\n                    pifName: \"barPackage,fooPackage\",\n                    pifId: \"/a/b/c/absolute/zero/barPackage,/a/b/c/pink/fuzz/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Two root packages, ordered, contains common directory, packages are not siblings\",\n                rootPackages: [\n                    (name: \"barPackage\", path: AbsolutePath(\"/a/b/c/absolute/zero/barPackage\")),\n                    (name: \"fooPackage\", path: AbsolutePath(\"/a/b/c/pink/fuzz/fooPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath(\"/a/b/c\"),\n                    pifName: \"barPackage,fooPackage\",\n                    pifId: \"/a/b/c/absolute/zero/barPackage,/a/b/c/pink/fuzz/fooPackage\",\n                ),\n            ),\n\n            RootPackagesTestData(\n                id: \"Many root packages, unordered, contains common directory, packages are not siblings\",\n                rootPackages: [\n                    (name: \"fooPackage\", path: AbsolutePath(\"/a/b/c/pink/fuzz/fooPackage\")),\n                    (name: \"barPackage\", path: AbsolutePath(\"/a/b/c/absolute/zero/barPackage\")),\n                    (name: \"bazPackage\", path: AbsolutePath(\"/a/b/c/absolute/legend/bazPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath(\"/a/b/c\"),\n                    pifName: \"barPackage,bazPackage,fooPackage\",\n                    pifId: \"/a/b/c/absolute/zero/barPackage,/a/b/c/absolute/legend/bazPackage,/a/b/c/pink/fuzz/fooPackage\",\n                ),\n            ),\n            RootPackagesTestData(\n                id: \"Many root packages, ordered, contains common directory, packages are not siblings\",\n                rootPackages: [\n                    (name: \"barPackage\", path: AbsolutePath(\"/a/b/c/absolute/zero/barPackage\")),\n                    (name: \"bazPackage\", path: AbsolutePath(\"/a/b/c/absolute/legend/bazPackage\")),\n                    (name: \"fooPackage\", path: AbsolutePath(\"/a/b/c/pink/fuzz/fooPackage\")),\n                ],\n                expectedData: (\n                    pifPath: Basics.AbsolutePath(\"/a/b/c\"),\n                    pifName: \"barPackage,bazPackage,fooPackage\",\n                    pifId: \"/a/b/c/absolute/zero/barPackage,/a/b/c/absolute/legend/bazPackage,/a/b/c/pink/fuzz/fooPackage\",\n                ),\n            ),\n        ],\n    )\n    func multipleRootPackages(\n        testData: RootPackagesTestData,\n    ) async throws {\n        // Arrange\n        try #require(testData.rootPackages.count >= 1, \"Test configuration data error.  No root packages are specified.\")\n\n        let fs = InMemoryFileSystem()\n        let observabilityScope = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: testData.rootPackages.map { rootPackage in\n                Manifest.createRootManifest(\n                    displayName: rootPackage.name,\n                    path: rootPackage.path,\n                    products: [],\n                    targets: [],\n                )\n            },\n            observabilityScope: observabilityScope.topScope\n        )\n\n        let pifBuilder = PIFBuilder(\n            graph: graph,\n            parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(\n                temporaryDirectory: AbsolutePath.root.appending(\"tmp\"),\n                addLocalRpaths: true,\n            ),\n            fileSystem: fs,\n            observabilityScope: observabilityScope.topScope,\n        )\n\n        // Act\n        let pif = try await pifBuilder.constructPIF(\n            buildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild),\n        )\n\n        // Assert\n        #expect(\n            pif.workspace.path == testData.expectedData.pifPath,\n            \"Actual path is not as expected\",\n        )\n        #expect(\n            pif.workspace.name == testData.expectedData.pifName,\n            \"Actual pif name is not as expected\",\n        )\n\n    }\n\n    @Test func platformExecutableModuleLibrarySearchPath() async throws {\n        try await withGeneratedPIF(fromFixture: \"PIFBuilder/BasicExecutable\") { pif, observabilitySystem in\n            let releaseConfig = try pif.workspace\n                .project(named: \"BasicExecutable\")\n                .target(named: \"Executable\")\n                .buildConfig(named: .release)\n\n            for platform in ProjectModel.BuildSettings.Platform.allCases {\n                let search_paths = releaseConfig.impartedBuildProperties.settings[.LIBRARY_SEARCH_PATHS, platform]\n                switch platform {\n                    case .macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .xrOS, .driverKit, .freebsd, .android, .linux, .wasi, .openbsd, ._iOSDevice:\n                         #expect(search_paths == nil, \"for platform \\(platform)\")\n                    case .windows:\n                        #expect(search_paths == [\"$(inherited)\", \"$(TARGET_BUILD_DIR)/ExecutableModules\"], \"for platform \\(platform)\")\n                }\n            }\n        }\n    }\n\n    @Test func platformConditionBasics() async throws {\n        try await withGeneratedPIF(fromFixture: \"PIFBuilder/UnknownPlatforms\") { pif, observabilitySystem in\n            // We should emit a warning to the PIF log about the unknown platform\n            #expect(observabilitySystem.diagnostics.filter {\n                $0.severity == .warning && $0.message.contains(\"Ignoring settings assignments for unknown platform 'DoesNotExist'\")\n            }.count > 0)\n\n            let releaseConfig = try pif.workspace\n                .project(named: \"UnknownPlatforms\")\n                .target(named: \"UnknownPlatforms\")\n                .buildConfig(named: .release)\n\n            // The platforms with conditional settings should have those propagated to the PIF.\n            #expect(releaseConfig.settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, .linux] == [\"$(inherited)\", \"BAR\"])\n            #expect(releaseConfig.settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, .macOS] == [\"$(inherited)\", \"BAZ\"])\n            #expect(releaseConfig.settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS, .windows] == nil)\n        }\n    }\n\n    @Test func platformCCLibrary() async throws {\n        try await withGeneratedPIF(fromFixture: \"PIFBuilder/CCPackage\") { pif, observabilitySystem in\n            let releaseConfig = try pif.workspace\n                .project(named: \"CCPackage\")\n                .target(id: \"PACKAGE-TARGET:CCTarget\")\n                .buildConfig(named: .release)\n\n            for platform in ProjectModel.BuildSettings.Platform.allCases {\n                let ld_flags = releaseConfig.impartedBuildProperties.settings[.OTHER_LDFLAGS, platform]\n                switch platform {\n                    case .macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .xrOS, .driverKit, .freebsd:\n                         #expect(ld_flags == [\"-lc++\", \"$(inherited)\"], \"for platform \\(platform)\")\n                    case .android, .linux, .wasi, .openbsd:\n                        #expect(ld_flags == [\"-lstdc++\", \"$(inherited)\"], \"for platform \\(platform)\")\n                    case .windows, ._iOSDevice:\n                        #expect(ld_flags == nil, \"for platform \\(platform)\")\n                }\n            }\n        }\n    }\n\n    @Test func packageWithInternal() async throws {\n        try await withGeneratedPIF(fromFixture: \"PIFBuilder/PackageWithSDKSpecialization\") { pif, observabilitySystem in\n            let errors: [Diagnostic] = observabilitySystem.diagnostics.filter { $0.severity == .error }\n            #expect(errors.isEmpty, \"Expected no errors during PIF generation, but got: \\(errors)\")\n\n            let releaseConfig = try pif.workspace\n                .project(named: \"PackageWithSDKSpecialization\")\n                .buildConfig(named: .release)\n\n            #expect(releaseConfig.settings[.SPECIALIZATION_SDK_OPTIONS, .macOS] == [\"foo\"])\n        }\n    }\n\n    @Test func pluginWithBinaryTargetDependency() async throws {\n        try await withGeneratedPIF(fromFixture: \"Miscellaneous/Plugins/BinaryTargetExePlugin\") { pif, observabilitySystem in\n            // Verify that PIF generation succeeds for a package with a plugin that depends on a binary target\n            #expect(pif.workspace.projects.count > 0)\n\n            let project = try pif.workspace.project(named: \"MyBinaryTargetExePlugin\")\n\n            // Verify the plugin target exists\n            let pluginTarget = try project.target(named: \"MyPlugin\")\n            #expect(pluginTarget.common.name == \"MyPlugin\")\n\n            // Verify the executable target that uses the plugin exists\n            let executableTarget = try project.target(named: \"MyPluginExe\")\n            #expect(executableTarget.common.name == \"MyPluginExe\")\n\n            // Verify no errors were emitted during PIF generation\n            let errors = observabilitySystem.diagnostics.filter { $0.severity == .error }\n            #expect(errors.isEmpty, \"Expected no errors during PIF generation, but got: \\(errors)\")\n\n            // Verify that the plugin target has a dependency (binary targets are handled differently in PIF)\n            // The key test is that PIF generation succeeds without errors when a plugin depends on a binary target\n            let binaryArtifactMessages = observabilitySystem.diagnostics.filter {\n                $0.message.contains(\"found binary artifact\")\n            }\n            #expect(binaryArtifactMessages.count > 0, \"Expected to find binary artifact processing messages\")\n        }\n    }\n\n    @Test(\n        arguments: BuildConfiguration.allCases,\n    )\n    func dynamicLibraryProductExecutablePrefix(\n        configuration: BuildConfiguration,\n    ) async throws {\n        try await withGeneratedPIF(\n            fromFixture: \"PIFBuilder/Library\",\n            shouldCreateDylibForDynamicProducts: true\n        ) { pif, observabilitySystem in\n            let errors: [Diagnostic] = observabilitySystem.diagnostics.filter { $0.severity == .error }\n            #expect(errors.isEmpty, \"Expected no errors during PIF generation, but got: \\(errors)\")\n\n            let target = try pif.workspace\n                .project(named: \"Library\")\n                .target(named: \"LibraryDynamic-product\")\n\n            guard case .target(let concreteTarget) = target else {\n                Issue.record(\"Expected a regular target, got \\(target)\")\n                return\n            }\n            #expect(concreteTarget.productType == .dynamicLibrary)\n            let config = try target.buildConfig(named: configuration)\n            #expect(config.settings[.EXECUTABLE_PREFIX] == \"lib\")\n            #expect(config.settings[.EXECUTABLE_PREFIX, .windows] == \"\")\n        }\n\n        try await withGeneratedPIF(\n            fromFixture: \"PIFBuilder/Library\",\n            shouldCreateDylibForDynamicProducts: false\n        ) { pif, observabilitySystem in\n            let errors: [Diagnostic] = observabilitySystem.diagnostics.filter { $0.severity == .error }\n            #expect(errors.isEmpty, \"Expected no errors during PIF generation, but got: \\(errors)\")\n\n            let target = try pif.workspace\n                .project(named: \"Library\")\n                .target(named: \"LibraryDynamic-product\")\n\n            let config = try target.buildConfig(named: configuration)\n            #expect(config.settings[.EXECUTABLE_PREFIX] == nil)\n        }\n    }\n\n    @Test(\n        arguments: BuildConfiguration.allCases,\n    )\n    func executablePrefixIsSetCorrectly(\n        configuration: BuildConfiguration,\n    ) async throws {\n        try await withGeneratedPIF(fromFixture: \"PIFBuilder/Library\") { pif, observabilitySystem in\n            let errors: [Diagnostic] = observabilitySystem.diagnostics.filter { $0.severity == .error }\n            #expect(errors.isEmpty, \"Expected no errors during PIF generation, but got: \\(errors)\")\n\n            struct ExpectedValue {\n                let targetName: String\n                let expectedValue: String?\n                let expectedValueForWindows: String?\n            }\n            let targetsUnderTest = [\n                ExpectedValue(\n                    targetName: \"LibraryDynamic-product\",\n                    expectedValue: \"lib\",\n                    expectedValueForWindows: \"\",\n                ),\n                ExpectedValue(\n                    targetName: \"LibraryStatic-product\",\n                    expectedValue: \"lib\",\n                    expectedValueForWindows: \"\",\n                ),\n                ExpectedValue(\n                    targetName: \"LibraryAuto-product\",\n                    expectedValue: \"lib\",\n                    expectedValueForWindows: \"\",\n                ),\n            ]\n            for targetUnderTest in targetsUnderTest {\n                let projectConfig = try pif.workspace\n                    .project(named: \"Library\")\n                    .target(named: targetUnderTest.targetName)\n                    .buildConfig(named: configuration)\n\n                let actualValue = projectConfig.settings[.EXECUTABLE_PREFIX]\n                let actualValueForWindows = projectConfig.settings[.EXECUTABLE_PREFIX, .windows]\n                #expect(actualValue == targetUnderTest.expectedValue)\n                #expect(actualValueForWindows == targetUnderTest.expectedValueForWindows)\n\n            }\n        }\n    }\n\n\n    @Test(arguments: BuildConfiguration.allCases)\n    func conditionalLinkerSettings(configuration: BuildConfiguration) async throws {\n        try await withGeneratedPIF(fromFixture: \"PIFBuilder/ConditionalBuildSettings\") { pif, observabilitySystem in\n            let errors = observabilitySystem.diagnostics.filter { $0.severity == .error }\n            #expect(errors.isEmpty, \"Expected no errors during PIF generation, but got: \\(errors)\")\n\n            let targetConfig = try pif.workspace\n                .project(named: \"ConditionalBuildSettings\")\n                .target(id: \"PACKAGE-TARGET:ConditionalBuildSettings\")\n                .buildConfig(named: configuration)\n\n            let ldflags = targetConfig.settings[.OTHER_LDFLAGS]\n            switch configuration {\n            case .debug:\n               let debugFlags = try #require(ldflags, \"Debug config requires OTHER_LDFLAGS\")\n                #expect(\n                    debugFlags.contains(\"-Xlinker\") && debugFlags.contains(\"-interposable\"),\n                    \"Debug config missing required flags: \\(debugFlags)\"\n                )\n            case .release:\n                #expect(ldflags == nil, \"Release config should not have debug flags, but got \\(ldflags)\")\n            }\n        }\n    }\n\n    @Test func impartedModuleMaps() async throws {\n        try await withGeneratedPIF(fromFixture: \"CFamilyTargets/ModuleMapGenerationCases\") { pif, observabilitySystem in\n            #expect(observabilitySystem.diagnostics.filter {\n                $0.severity == .error\n            }.isEmpty)\n\n            do {\n                let releaseConfig = try pif.workspace\n                    .project(named: \"ModuleMapGenerationCases\")\n                    .target(named: \"UmbrellaHeader\")\n                    .buildConfig(named: .release)\n\n                #expect(releaseConfig.impartedBuildProperties.settings[.OTHER_CFLAGS] == [\"-fmodule-map-file=\\(RelativePath(\"$(GENERATED_MODULEMAP_DIR)\").appending(component: \"UmbrellaHeader.modulemap\").pathString)\", \"$(inherited)\"])\n            }\n\n            do {\n                let releaseConfig = try pif.workspace\n                    .project(named: \"ModuleMapGenerationCases\")\n                    .target(named: \"UmbrellaDirectoryInclude\")\n                    .buildConfig(named: .release)\n\n                #expect(releaseConfig.impartedBuildProperties.settings[.OTHER_CFLAGS] == [\"-fmodule-map-file=\\(RelativePath(\"$(GENERATED_MODULEMAP_DIR)\").appending(component: \"UmbrellaDirectoryInclude.modulemap\").pathString)\", \"$(inherited)\"])\n            }\n\n            do {\n                let releaseConfig = try pif.workspace\n                    .project(named: \"ModuleMapGenerationCases\")\n                    .target(named: \"CustomModuleMap\")\n                    .buildConfig(named: .release)\n                let arg = try #require(releaseConfig.impartedBuildProperties.settings[.OTHER_CFLAGS]?.first)\n                #expect(arg.hasPrefix(\"-fmodule-map-file\") && arg.hasSuffix(RelativePath(\"CustomModuleMap\").appending(components: [\"include\", \"module.modulemap\"]).pathString))\n            }\n        }\n    }\n\n    @Test func disablingLocalRpaths() async throws {\n        try await withGeneratedPIF(fromFixture: \"Miscellaneous/Simple\") { pif, observabilitySystem in\n            #expect(observabilitySystem.diagnostics.filter {\n                $0.severity == .error\n            }.isEmpty)\n\n            do {\n                let releaseConfig = try pif.workspace\n                    .project(named: \"Foo\")\n                    .target(named: \"Foo\")\n                    .buildConfig(named: .release)\n\n                #expect(releaseConfig.impartedBuildProperties.settings[.LD_RUNPATH_SEARCH_PATHS] == [\"$(RPATH_ORIGIN)\", \"$(inherited)\"])\n            }\n        }\n\n        try await withGeneratedPIF(fromFixture: \"Miscellaneous/Simple\", addLocalRpaths: false) { pif, observabilitySystem in\n            #expect(observabilitySystem.diagnostics.filter {\n                $0.severity == .error\n            }.isEmpty)\n\n            do {\n                let releaseConfig = try pif.workspace\n                    .project(named: \"Foo\")\n                    .target(named: \"Foo\")\n                    .buildConfig(named: .release)\n\n                #expect(releaseConfig.impartedBuildProperties.settings[.LD_RUNPATH_SEARCH_PATHS] == nil)\n            }\n        }\n    }\n\n    @Test func warningSettingsInRemotePackage() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let fs = InMemoryFileSystem(emptyFiles: [\n            \"/Root/Sources/RootLib/RootLib.swift\",\n            \"/RemotePkg/Sources/swiftLib/swiftLib.swift\",\n            \"/RemotePkg/Sources/cLib/cLib.c\",\n            \"/RemotePkg/Sources/cLib/include/cLib.h\",\n            \"/RemotePkg/Sources/cxxLib/cxxLib.cpp\",\n            \"/RemotePkg/Sources/cxxLib/include/cxxLib.h\",\n            \"/LocalPkg/Sources/localLib/localLib.swift\",\n        ])\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Root\",\n                    path: \"/Root\",\n                    toolsVersion: .v6_2,\n                    dependencies: [\n                        .remoteSourceControl(\n                            url: \"https://example.com/remote-pkg\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .fileSystem(path: \"/LocalPkg\"),\n                    ],\n                    products: [],\n                    targets: [\n                        TargetDescription(\n                            name: \"RootLib\",\n                            dependencies: [\n                                .product(name: \"RemoteLib\", package: \"remote-pkg\"),\n                                .product(name: \"RemoteCLib\", package: \"remote-pkg\"),\n                                .product(name: \"RemoteCXXLib\", package: \"remote-pkg\"),\n                                .product(name: \"LocalLib\", package: \"LocalPkg\"),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createRemoteSourceControlManifest(\n                    displayName: \"remote-pkg\",\n                    url: \"https://example.com/remote-pkg\",\n                    path: \"/RemotePkg\",\n                    toolsVersion: .v6_2,\n                    products: [\n                        ProductDescription(name: \"RemoteLib\", type: .library(.automatic), targets: [\"swiftLib\"]),\n                        ProductDescription(name: \"RemoteCLib\", type: .library(.automatic), targets: [\"cLib\"]),\n                        ProductDescription(name: \"RemoteCXXLib\", type: .library(.automatic), targets: [\"cxxLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"swiftLib\",\n                            settings: [\n                                .init(tool: .swift, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                                .init(tool: .swift, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .error), condition: .init(config: \"release\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"cLib\",\n                            settings: [\n                                .init(tool: .c, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                                .init(tool: .c, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .c, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"cxxLib\",\n                            settings: [\n                                .init(tool: .cxx, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                                .init(tool: .cxx, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                                .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                            ]\n                        ),\n                    ]\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"LocalPkg\",\n                    path: \"/LocalPkg\",\n                    toolsVersion: .v6_2,\n                    products: [\n                        ProductDescription(name: \"LocalLib\", type: .library(.automatic), targets: [\"localLib\"]),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"localLib\",\n                            settings: [\n                                .init(tool: .swift, kind: .treatAllWarnings(.error)),\n                            ]\n                        ),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        let pifBuilder = PIFBuilder(\n            graph: graph,\n            parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(\n                temporaryDirectory: AbsolutePath.root,\n                addLocalRpaths: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try await pifBuilder.constructPIF(\n            buildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild)\n        )\n\n        let remoteProject = try pif.workspace.project(named: \"remote-pkg\")\n        for config in [BuildConfiguration.debug, .release] {\n            #expect(try remoteProject.buildConfig(named: config).settings[.SUPPRESS_WARNINGS] == \"YES\")\n        }\n\n        let swiftLibTarget = try remoteProject.target(named: \"swiftLib\")\n        let strippedSwiftFlags = [\"-warnings-as-errors\", \"-no-warnings-as-errors\", \"-Wwarning\", \"-Werror\", \"DeprecatedDeclaration\"]\n        for config in [BuildConfiguration.debug, .release] {\n            let swiftLibConfig = try swiftLibTarget.buildConfig(named: config)\n            if let swiftFlags = swiftLibConfig.settings[.OTHER_SWIFT_FLAGS] {\n                for flag in strippedSwiftFlags {\n                    #expect(!swiftFlags.contains(flag))\n                }\n            }\n        }\n\n        for clangLibTargetName in [\"cLib\", \"cxxLib\"] {\n            let cLibTarget = try remoteProject.target(named: clangLibTargetName)\n            for config in [BuildConfiguration.debug, .release] {\n                let cLibConfig = try cLibTarget.buildConfig(named: config)\n                if let cFlags = cLibConfig.settings[.OTHER_CFLAGS] {\n                    #expect(cFlags.filter { $0.count > 2 && $0.hasPrefix(\"-W\") }.isEmpty)\n                }\n                if let cPlusPlusFlags = cLibConfig.settings[.OTHER_CPLUSPLUSFLAGS] {\n                    #expect(cPlusPlusFlags.filter { $0.count > 2 && $0.hasPrefix(\"-W\") }.isEmpty)\n                }\n            }\n        }\n\n        let localProject = try pif.workspace.project(named: \"LocalPkg\")\n\n        for config in [BuildConfiguration.debug, .release] {\n            #expect(try localProject.buildConfig(named: config).settings[.SUPPRESS_WARNINGS] == nil)\n        }\n\n        let localLibTarget = try localProject.target(named: \"localLib\")\n        for config in [BuildConfiguration.debug, .release] {\n            #expect(try localLibTarget.buildConfig(named: config).settings[.OTHER_SWIFT_FLAGS]?.contains(\"-warnings-as-errors\") == true)\n        }\n    }\n\n    @Suite(\n        .tags(\n            .FunctionalArea.IndexMode\n        )\n    )\n    struct IndexModeSettingTests {\n\n        @Test(\n            arguments: [BuildParameters.IndexStoreMode.auto], [BuildConfiguration.debug],\n            // arguments: BuildParameters.IndexStoreMode.allCases, BuildConfiguration.allCases,\n        )\n         func indexModeSettingSetTo(\n            indexStoreSettingUT: BuildParameters.IndexStoreMode,\n            configuration: BuildConfiguration,\n         ) async throws {\n            try await withGeneratedPIF(\n                fromFixture: \"PIFBuilder/Simple\",\n                buildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild, indexStoreMode: indexStoreSettingUT),\n            ) { pif, observabilitySystem in\n                // #expect(false, \"fail purposefully...\")\n                #expect(observabilitySystem.diagnostics.filter {\n                    $0.severity == .error\n                }.isEmpty)\n\n                let targetConfig = try pif.workspace\n                    .project(named: \"Simple\")\n                    // .target(named: \"Simple\")\n                    .buildConfig(named: configuration)\n                switch indexStoreSettingUT {\n                    case .on, .off:\n                        #expect(targetConfig.settings[.SWIFT_INDEX_STORE_ENABLE] == nil)\n                    case .auto:\n                        let expectedSwiftIndexStoreEnableValue: String? = switch configuration {\n                            case .debug: \"YES\"\n                            case .release: nil\n                        }\n                        #expect(targetConfig.settings[.SWIFT_INDEX_STORE_ENABLE] == expectedSwiftIndexStoreEnableValue)\n                }\n\n                let testTargetConfig = try pif.workspace\n                    .project(named: \"Simple\")\n                    .target(named: \"SimpleTests-product\")\n                    .buildConfig(named: configuration)\n                switch indexStoreSettingUT {\n                    case .on, .off:\n                        #expect(testTargetConfig.settings[.SWIFT_INDEX_STORE_ENABLE] == nil)\n                    case .auto:\n                        #expect(testTargetConfig.settings[.SWIFT_INDEX_STORE_ENABLE] == \"YES\")\n                }\n            }\n        }\n    }\n\n    @Test func swiftCompileForStaticLinkingInDynamicLibraries() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let fs = InMemoryFileSystem(emptyFiles: [\n            \"/Root/Sources/ModuleA/ModuleA.swift\",\n            \"/Root/Sources/ModuleB/ModuleB.swift\",\n            \"/Root/Sources/ModuleC/ModuleC.swift\",\n        ])\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Root\",\n                    path: \"/Root\",\n                    toolsVersion: .v6_0,\n                    products: [\n                        ProductDescription(name: \"DynamicLib\", type: .library(.dynamic), targets: [\"ModuleA\", \"ModuleB\"]),\n                        ProductDescription(name: \"StaticLib\", type: .library(.static), targets: [\"ModuleC\"]),\n                    ],\n                    targets: [\n                        TargetDescription(name: \"ModuleA\"),\n                        TargetDescription(name: \"ModuleB\"),\n                        TargetDescription(name: \"ModuleC\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        let pifBuilder = PIFBuilder(\n            graph: graph,\n            parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(\n                temporaryDirectory: AbsolutePath.root.appending(\"tmp\"),\n                addLocalRpaths: true\n            ),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n\n        let pif = try await pifBuilder.constructPIF(\n            buildParameters: mockBuildParameters(destination: .host, buildSystemKind: .swiftbuild)\n        )\n\n        let project = try pif.workspace.project(named: \"Root\")\n\n        // Modules that are direct dependencies of dynamic library products should have\n        // SWIFT_COMPILE_FOR_STATIC_LINKING = \"NO\" on Windows\n        for moduleName in [\"ModuleA\", \"ModuleB\"] {\n            let moduleTarget = try project.target(named: moduleName)\n            let config = try moduleTarget.buildConfig(named: .release)\n\n            // Check that the setting is \"NO\" on Windows\n            #expect(\n                config.settings[.SWIFT_COMPILE_FOR_STATIC_LINKING, .windows] == \"NO\",\n                \"Module \\(moduleName) in dynamic library should have SWIFT_COMPILE_FOR_STATIC_LINKING=NO on Windows\"\n            )\n\n            // Check that the setting is not set on other platforms\n            for platform in SwiftBuild.ProjectModel.BuildSettings.Platform.allCases where platform != .windows {\n                #expect(\n                    config.settings[.SWIFT_COMPILE_FOR_STATIC_LINKING, platform] == nil,\n                    \"Module \\(moduleName) should not have SWIFT_COMPILE_FOR_STATIC_LINKING on platform \\(platform)\"\n                )\n            }\n        }\n\n        // Modules that are NOT in dynamic library products should not have this setting\n        let moduleC = try project.target(named: \"ModuleC\")\n        let moduleCConfig = try moduleC.buildConfig(named: .release)\n\n        for platform in ProjectModel.BuildSettings.Platform.allCases {\n            let setting = moduleCConfig.settings[.SWIFT_COMPILE_FOR_STATIC_LINKING, platform]\n            #expect(\n                setting == nil,\n                \"Module ModuleC (not in dynamic library) should not have SWIFT_COMPILE_FOR_STATIC_LINKING on platform \\(platform)\"\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftBuildSupportTests/PackagePIFBuilderHelpersTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\nimport SwiftBuildSupport\n\n@Suite(\n    .tags(\n        .TestSize.small,\n        .FunctionalArea.PIF\n    )\n)\nstruct PackagePIFBuilderHelpersTests {\n    \n    // MARK: - targetName(forProductName:) Tests\n\n    @Test(\"targetName(forProductName:) converts product names correctly\")\n    func targetNameForProduct() {\n        // Test with various product names\n        #expect(PackagePIFBuilder.targetName(forProductName: \"swiftly\") == \"swiftly-product\")\n        #expect(PackagePIFBuilder.targetName(forProductName: \"test-swiftly\") == \"test-swiftly-product\")\n        #expect(PackagePIFBuilder.targetName(forProductName: \"ArgumentParser\") == \"ArgumentParser-product\")\n        #expect(PackagePIFBuilder.targetName(forProductName: \"AsyncHTTPClient\") == \"AsyncHTTPClient-product\")\n        #expect(PackagePIFBuilder.targetName(forProductName: \"OpenAPIRuntime\") == \"OpenAPIRuntime-product\")\n        #expect(PackagePIFBuilder.targetName(forProductName: \"SystemPackage\") == \"SystemPackage-product\")\n\n        #expect(PackagePIFBuilder.targetName(forProductName: \"\") == \"-product\")\n        #expect(PackagePIFBuilder.targetName(forProductName: \"A\") == \"A-product\")\n        #expect(PackagePIFBuilder.targetName(forProductName: \"product\") == \"product-product\")\n    }\n\n    // MARK: - targetName(forModuleName:) Tests\n\n    @Test(\"targetName(forModuleName:) converts module names correctly\")\n    func targetNameForModule() {\n        // Test with various module names\n        #expect(PackagePIFBuilder.targetName(forModuleName: \"Swiftly\") == \"Swiftly\")\n        #expect(PackagePIFBuilder.targetName(forModuleName: \"TestSwiftly\") == \"TestSwiftly\")\n        #expect(PackagePIFBuilder.targetName(forModuleName: \"ArgumentParser\") == \"ArgumentParser\")\n        #expect(PackagePIFBuilder.targetName(forModuleName: \"SwiftlyCore\") == \"SwiftlyCore\")\n        #expect(PackagePIFBuilder.targetName(forModuleName: \"MacOSPlatform\") == \"MacOSPlatform\")\n        \n        // Modules with leading underscores\n        #expect(PackagePIFBuilder.targetName(forModuleName: \"_CryptoExtras\") == \"_CryptoExtras\")\n        #expect(PackagePIFBuilder.targetName(forModuleName: \"__AsyncFileSystem\") == \"__AsyncFileSystem\")\n        \n        #expect(PackagePIFBuilder.targetName(forModuleName: \"\") == \"\")\n        #expect(PackagePIFBuilder.targetName(forModuleName: \"A\") == \"A\")\n    }\n\n    // MARK: - productName(forTargetName:) Tests\n\n    @Test(\"productName(forTargetName:) converts target names correctly\")\n    func productNameFromTarget() {\n        #expect(PackagePIFBuilder.productName(forTargetName: \"swiftly-product\") == \"swiftly\")\n        #expect(PackagePIFBuilder.productName(forTargetName: \"test-swiftly-product\") == \"test-swiftly\")\n        #expect(PackagePIFBuilder.productName(forTargetName: \"ArgumentParser-product\") == \"ArgumentParser\")\n        #expect(PackagePIFBuilder.productName(forTargetName: \"AsyncHTTPClient-product\") == \"AsyncHTTPClient\")\n        #expect(PackagePIFBuilder.productName(forTargetName: \"OpenAPIRuntime-product\") == \"OpenAPIRuntime\")\n        #expect(PackagePIFBuilder.productName(forTargetName: \"SystemPackage-product\") == \"SystemPackage\")\n        #expect(PackagePIFBuilder.productName(forTargetName: \"SwiftBuild-product\") == \"SwiftBuild\")\n\n        #expect(PackagePIFBuilder.productName(forTargetName: \"Swiftly\") == nil)\n        #expect(PackagePIFBuilder.productName(forTargetName: \"TestSwiftly\") == nil)\n        #expect(PackagePIFBuilder.productName(forTargetName: \"ArgumentParser\") == nil)\n        #expect(PackagePIFBuilder.productName(forTargetName: \"SwiftlyCore\") == nil)\n        #expect(PackagePIFBuilder.productName(forTargetName: \"MacOSPlatform\") == nil)\n\n        #expect(PackagePIFBuilder.productName(forTargetName: \"-product\") == \"\")\n        #expect(PackagePIFBuilder.productName(forTargetName: \"\") == nil)\n        #expect(PackagePIFBuilder.productName(forTargetName: \"product\") == nil)\n        #expect(PackagePIFBuilder.productName(forTargetName: \"my-product-product\") == \"my-product\")\n    }\n\n    @Test(\"productName(forTargetName:) removes TargetSuffix patterns correctly\")\n    func productNameRemovesSuffixes() {\n        // Test -dynamic suffix removal from PACKAGE-PRODUCT GUIDs\n        // PACKAGE-PRODUCT:swift-build_SwiftBuild.SwiftBuild-6FA70E1059D35307-dynamic\n        #expect(PackagePIFBuilder.productName(forTargetName: \"SwiftBuild-dynamic-product\") == \"SwiftBuild\")\n        \n        // PACKAGE-PRODUCT:swift-build_SWBProtocol.SWBProtocol-479FEB9464127B49-dynamic\n        #expect(PackagePIFBuilder.productName(forTargetName: \"SWBProtocol-dynamic-product\") == \"SWBProtocol\")\n        \n        // Test -testable suffix removal\n        // snippet-extract-4D525650E9464C3A-testable\n        #expect(PackagePIFBuilder.productName(forTargetName: \"snippet-extract-testable-product\") == \"snippet-extract\")\n        \n        // swift-run--4E81F76B4FDE3E48-testable\n        #expect(PackagePIFBuilder.productName(forTargetName: \"swift-run-testable-product\") == \"swift-run\")\n        \n        // swift-experimental-sdk--453A89A57E5CD913-testable\n        #expect(PackagePIFBuilder.productName(forTargetName: \"swift-experimental-sdk-testable-product\") == \"swift-experimental-sdk\")\n        \n        // swift-bootstrap-19E6669016298B47-testable\n        #expect(PackagePIFBuilder.productName(forTargetName: \"swift-bootstrap-testable-product\") == \"swift-bootstrap\")\n        \n        // Test products without suffixes\n        #expect(PackagePIFBuilder.productName(forTargetName: \"SwiftBuild-product\") == \"SwiftBuild\")\n        #expect(PackagePIFBuilder.productName(forTargetName: \"ArgumentParser-product\") == \"ArgumentParser\")\n    }\n\n    // MARK: - moduleName(forTargetName:) Tests\n\n    @Test(\"moduleName(forTargetName:) converts target names correctly\")\n    func moduleNameFromTarget() {\n        // Test simple module names (no package prefix)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"Swiftly\") == \"Swiftly\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"TestSwiftly\") == \"TestSwiftly\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"ArgumentParser\") == \"ArgumentParser\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"SwiftlyCore\") == \"SwiftlyCore\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"MacOSPlatform\") == \"MacOSPlatform\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"LinuxPlatform\") == \"LinuxPlatform\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"SwiftlyWebsiteAPI\") == \"SwiftlyWebsiteAPI\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"SwiftlyDownloadAPI\") == \"SwiftlyDownloadAPI\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"AsyncHTTPClient\") == \"AsyncHTTPClient\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"OpenAPIRuntime\") == \"OpenAPIRuntime\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"SPMSQLite3\") == \"SPMSQLite3\")\n\n        // Modules that start with underscores\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"_CryptoExtras\") == \"_CryptoExtras\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"_AsyncFileSystem\") == \"_AsyncFileSystem\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"_CertificateInternals\") == \"_CertificateInternals\")\n\n        // Test product names (should return nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swiftly-product\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"test-swiftly-product\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"ArgumentParser-product\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"AsyncHTTPClient-product\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"OpenAPIRuntime-product\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"SystemPackage-product\") == nil)\n\n        // Test edge cases\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"\") == \"\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"A\") == \"A\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"-product\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"my-product-product\") == nil)\n\n        // Test resource bundle package_module target format (with underscores)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-nio_NIOPosix\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-nio-ssl_NIOSSL\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-crypto_Crypto\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-crypto__CryptoExtras\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-nio__NIOBase64\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-nio__NIODataStructures\") == nil)\n\n        // Test modules with multiple leading underscores\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"___ModuleName\") == \"___ModuleName\")\n    }\n\n    @Test(\"moduleName(forTargetName:) removes TargetSuffix patterns correctly\")\n    func moduleNameRemovesSuffixes() {\n        // Test -dynamic suffix removal from PACKAGE-TARGET GUIDs\n        // PACKAGE-TARGET:SWBTaskConstruction--13A05A6A6704C663-dynamic\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"SWBTaskConstruction-dynamic\") == \"SWBTaskConstruction\")\n        \n        // PACKAGE-TARGET:_IntegrationTestSupport-1FB010E086040497-dynamic\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"_IntegrationTestSupport-dynamic\") == \"_IntegrationTestSupport\")\n        \n        // PACKAGE-TARGET:_AsyncFileSystem--4E4E671E738B868E-dynamic\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"_AsyncFileSystem-dynamic\") == \"_AsyncFileSystem\")\n        \n        // PACKAGE-TARGET:PackageSigning--7F242844F5C56277-dynamic\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"PackageSigning-dynamic\") == \"PackageSigning\")\n        \n        // Test -testable suffix removal\n        // snippet-extract-4D525650E9464C3A-testable\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"snippet-extract-testable\") == \"snippet-extract\")\n        \n        // swift-run--4E81F76B4FDE3E48-testable\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-run-testable\") == \"swift-run\")\n        \n        // swift-experimental-sdk--453A89A57E5CD913-testable\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-experimental-sdk-testable\") == \"swift-experimental-sdk\")\n        \n        // swift-bootstrap-19E6669016298B47-testable\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-bootstrap-testable\") == \"swift-bootstrap\")\n        \n        // Test modules without suffixes\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"SwiftBuild\") == \"SwiftBuild\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"_AsyncFileSystem\") == \"_AsyncFileSystem\")\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"ArgumentParser\") == \"ArgumentParser\")\n        \n        // Test that product targets still return nil even with suffixes\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"SwiftBuild-dynamic-product\") == nil)\n        #expect(PackagePIFBuilder.moduleName(forTargetName: \"swift-run-testable-product\") == nil)\n    }\n\n    // MARK: - Round-trip and Mutual Exclusivity Tests\n\n    @Test(\"name mapping functions are inverses for products\")\n    func productNameMappingRoundTrip() {\n        let productNames = [\"swiftly\", \"test-swiftly\", \"ArgumentParser\", \"AsyncHTTPClient\", \"OpenAPIRuntime\"]\n\n        for productName in productNames {\n            let targetName = PackagePIFBuilder.targetName(forProductName: productName)\n            let recoveredName = PackagePIFBuilder.productName(forTargetName: targetName)\n            #expect(recoveredName == productName, \"Round trip failed for product '\\(productName)'\")\n        }\n    }\n\n    @Test(\"product and module mapping functions are mutually exclusive\")\n    func productAndModuleMappingExclusivity() {\n        // Product target names should not be recognized as modules\n        let productTargetNames = [\"swiftly-product\", \"ArgumentParser-product\", \"AsyncHTTPClient-product\"]\n        for targetName in productTargetNames {\n            #expect(\n                PackagePIFBuilder.moduleName(forTargetName: targetName) == nil,\n                \"Product target '\\(targetName)' should not be recognized as a module\"\n            )\n            #expect(\n                PackagePIFBuilder.productName(forTargetName: targetName) != nil,\n                \"Product target '\\(targetName)' should be recognized as a product\"\n            )\n        }\n\n        // Module target names should not be recognized as products\n        let moduleTargetNames = [\"Swiftly\", \"ArgumentParser\", \"SwiftlyCore\"]\n        for targetName in moduleTargetNames {\n            #expect(\n                PackagePIFBuilder.productName(forTargetName: targetName) == nil,\n                \"Module target '\\(targetName)' should not be recognized as a product\"\n            )\n            #expect(\n                PackagePIFBuilder.moduleName(forTargetName: targetName) != nil,\n                \"Module target '\\(targetName)' should be recognized as a module\"\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftBuildSupportTests/PrebuiltsPIFTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageLoading\nimport SwiftBuildSupport\nimport Testing\nimport _InternalTestSupport\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly) @testable import PackageGraph\n@_spi(SwiftPMInternal) @testable import PackageModel\n\n/// PIF version of the PrebuiltsBuildPlanTests\n@Suite\nstruct PrebuiltsPIFTests {\n    // The prebuilts used for these tests\n    let prebuiltLibrary = PrebuiltLibrary(\n        identity: .plain(\"swift-syntax\"),\n        libraryName: \"MacroSupport\",\n        path: \"/MyPackage/.build/prebuilts/swift-syntax/600.0.1/6.1-MacroSupport-macos_aarch64\",\n        checkoutPath: \"/MyPackage/.build/checkouts/swift-syntax\",\n        products: [\n            \"SwiftBasicFormat\",\n            \"SwiftCompilerPlugin\",\n            \"SwiftDiagnostics\",\n            \"SwiftIDEUtils\",\n            \"SwiftOperators\",\n            \"SwiftParser\",\n            \"SwiftParserDiagnostics\",\n            \"SwiftRefactor\",\n            \"SwiftSyntax\",\n            \"SwiftSyntaxBuilder\",\n            \"SwiftSyntaxMacros\",\n            \"SwiftSyntaxMacroExpansion\",\n            \"SwiftSyntaxMacrosTestSupport\",\n            \"SwiftSyntaxMacrosGenericTestSupport\",\n            \"_SwiftCompilerPluginMessageHandling\",\n            \"_SwiftLibraryPluginProvider\",\n        ],\n        includePath: [\n            \"Sources/_SwiftSyntaxCShims/include\"\n        ]\n    )\n\n    @Test func testSuccessPath() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPackage/Sources/Base/Base.swift\",\n                \"/MyPackage/Sources/Intermediate/Intermediate.swift\",\n                \"/MyPackage/Sources/Macros/Macros.swift\",\n                \"/MyPackage/Sources/MacroLib/MacroLib.swift\",\n                \"/MyPackage/Sources/Generator/Generator.swift\",\n                \"/MyPackage/Plugins/Plugin/Plugin.swift\",\n                \"/MyRoot/Sources/MyApp/MyApp.swift\",\n                \"/swift-syntax/Sources/SwiftSyntaxMacros/SwiftSyntaxMacros.swift\",\n            ]\n        )\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"MyRoot\",\n                    path: \"/MyRoot\",\n                    dependencies: [\n                        .remoteSourceControl(\n                            url: \"https://github.com/swiftlang/swift-syntax\",\n                            requirement: .exact(\"600.0.1\")),\n                        .fileSystem(path: \"/MyPackage\"),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MyApp\",\n                            type: .executable,\n                            targets: [\"MyApp\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"MyApp\",\n                            dependencies: [\n                                .product(name: \"MacroLib\", package: \"MyPackage\")\n                            ],\n                            type: .executable\n                        )\n                    ],\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"MyPackage\",\n                    path: \"/MyPackage\",\n                    dependencies: [\n                        .remoteSourceControl(\n                            url: \"https://github.com/swiftlang/swift-syntax\",\n                            requirement: .exact(\"600.0.1\"))\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MacroLib\",\n                            type: .library(.automatic),\n                            targets: [\n                                \"MacroLib\"\n                            ]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Base\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\")\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Intermediate\",\n                            dependencies: [\n                                \"Base\"\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Macros\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                \"Intermediate\",\n                            ],\n                            type: .macro\n                        ),\n                        TargetDescription(\n                            name: \"MacroLib\",\n                            dependencies: [\n                                \"Macros\"\n                            ]\n                        ),\n                    ],\n                ),\n                Manifest.createRemoteSourceControlManifest(\n                    displayName: \"swift-syntax\",\n                    url: \"https://github.com/swiftlang/swift-syntax\",\n                    path: \"/swift-syntax\",\n                    products: [\n                        ProductDescription(\n                            name: \"SwiftSyntaxMacros\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftSyntaxMacros\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(name: \"SwiftSyntaxMacros\")\n                    ]\n                ),\n            ],\n            prebuilts: [\n                prebuiltLibrary.identity: prebuiltLibrary.products.reduce(into: [:]) {\n                    $0[$1] = prebuiltLibrary\n                }\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        let pifBuilder: PIFBuilder = PIFBuilder(\n            graph: graph,\n            parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(\n                temporaryDirectory: AbsolutePath.root, addLocalRpaths: true),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try await pifBuilder.constructPIF(\n            buildParameters: mockBuildParameters(destination: .host)\n        )\n\n        let hostTargets = Set([\n            \"Macros\",\n            \"Intermediate\",\n            \"Base\",\n            \"SwiftSyntaxMacros\",\n        ])\n\n        let allPlatTargets = Set([\n            \"MacroLib-product\",\n            \"MacroLibdynamic-product\",\n            \"MacroLib\",\n            \"MyApp-product\",\n            \"AllIncludingTests\",\n            \"AllExcludingTests\",\n            \"SwiftSyntaxMacros-product\",\n            \"SwiftSyntaxMacrosdynamic-product\",\n            \"swift-syntaxPackageTests-product\",\n            \"MyRootPackageTests-product\",\n            \"MyPackagePackageTests-product\",\n        ])\n\n        let targets = pif.workspace.projects.flatMap({ $0.underlying.targets })\n        for target in targets {\n            let isHost: Bool = target.common.buildConfigs.contains {\n                guard let platforms = $0.settings[.SUPPORTED_PLATFORMS] else {\n                    return false\n                }\n                return platforms == [\"$(HOST_PLATFORM)\"]\n            }\n\n            if isHost {\n                #expect(hostTargets.contains(target.common.name))\n            } else {\n                #expect(allPlatTargets.contains(target.common.name))\n            }\n        }\n    }\n\n    // Make sure HOST_PLATFORM isn't set if a library leaks out the prebuilts to potential cross builds\n    @Test func testLeakyLibrary() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        let fs = InMemoryFileSystem(\n            emptyFiles: [\n                \"/MyPackage/Sources/Base/Base.swift\",\n                \"/MyPackage/Sources/Intermediate/Intermediate.swift\",\n                \"/MyPackage/Sources/Macros/Macros.swift\",\n                \"/MyPackage/Sources/MacroLib/MacroLib.swift\",\n                \"/MyPackage/Sources/Generator/Generator.swift\",\n                \"/MyPackage/Plugins/Plugin/Plugin.swift\",\n                \"/MyRoot/Sources/MyApp/MyApp.swift\",\n                \"/MyRoot/Sources/LeakyLib/LeakyLib.swift\",\n                \"/swift-syntax/Sources/SwiftSyntaxMacros/SwiftSyntaxMacros.swift\",\n            ]\n        )\n\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"MyRoot\",\n                    path: \"/MyRoot\",\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://github.com/swiftlang/swift-syntax\", requirement: .exact(\"600.0.1\")),\n                        .fileSystem(path: \"/MyPackage\"),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MyApp\",\n                            type: .executable,\n                            targets: [\"MyApp\"]\n                        ),\n                        ProductDescription(\n                            name: \"LeakyLib\",\n                            type: .library(.automatic),\n                            targets: [\"LeakyLib\"]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"MyApp\",\n                            dependencies: [\n                                .product(name: \"MacroLib\", package: \"MyPackage\"),\n                            ],\n                            type: .executable,\n                            pluginUsages: [\n                                .plugin(name: \"Plugin\", package: \"MyPackage\")\n                            ],\n                        ),\n                        TargetDescription(\n                            name: \"LeakyLib\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                            ]\n                        )\n                    ],\n                ),\n                Manifest.createFileSystemManifest(\n                    displayName: \"MyPackage\",\n                    path: \"/MyPackage\",\n                    dependencies: [\n                        .remoteSourceControl(url: \"https://github.com/swiftlang/swift-syntax\", requirement: .exact(\"600.0.1\")),\n                    ],\n                    products: [\n                        ProductDescription(\n                            name: \"MacroLib\",\n                            type: .library(.automatic),\n                            targets: [\n                                \"MacroLib\"\n                            ]\n                        ),\n                        ProductDescription(\n                            name: \"Plugin\",\n                            type: .plugin,\n                            targets: [\n                                \"Plugin\"\n                            ]\n                        ),\n                    ],\n                    targets: [\n                        TargetDescription(\n                            name: \"Base\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Intermediate\",\n                            dependencies: [\n                                \"Base\"\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Macros\",\n                            dependencies: [\n                                .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                \"Intermediate\",\n                            ],\n                            type: .macro\n                        ),\n                        TargetDescription(\n                            name: \"MacroLib\",\n                            dependencies: [\n                                \"Macros\"\n                            ]\n                        ),\n                        TargetDescription(\n                            name: \"Generator\",\n                            dependencies: [\n                                \"Base\"\n                            ],\n                            type: .executable\n                        ),\n                        TargetDescription(\n                            name: \"Plugin\",\n                            dependencies: [\n                                \"Generator\"\n                            ],\n                            type: .plugin,\n                            pluginCapability: .buildTool\n                        ),\n                    ],\n                ),\n                Manifest.createRemoteSourceControlManifest(\n                    displayName: \"swift-syntax\",\n                    url: \"https://github.com/swiftlang/swift-syntax\",\n                    path: \"/swift-syntax\",\n                    products: [\n                        ProductDescription(\n                            name: \"SwiftSyntaxMacros\",\n                            type: .library(.automatic),\n                            targets: [\"SwiftSyntaxMacros\"]\n                        )\n                    ],\n                    targets: [\n                        TargetDescription(name: \"SwiftSyntaxMacros\")\n                    ]\n                )\n            ],\n            prebuilts: [prebuiltLibrary.identity: prebuiltLibrary.products.reduce(into: [:]) {\n                $0[$1] = prebuiltLibrary\n            }],\n            observabilityScope: observability.topScope\n        )\n\n        let pifBuilder: PIFBuilder = PIFBuilder(\n            graph: graph,\n            parameters: try PIFBuilderParameters.constructDefaultParametersForTesting(\n                temporaryDirectory: AbsolutePath.root, addLocalRpaths: true),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try await pifBuilder.constructPIF(\n            buildParameters: mockBuildParameters(destination: .host)\n        )\n\n        let targets = pif.workspace.projects.flatMap({ $0.underlying.targets })\n        for target in targets {\n            guard target.common.name != \"Plugin\" else {\n                // The Plugin target does have HOST_PLATFORM test\n                continue\n            }\n            let isHost: Bool = target.common.buildConfigs.contains {\n                guard let platforms = $0.settings[.SUPPORTED_PLATFORMS] else {\n                    return false\n                }\n                return platforms == [\"$(HOST_PLATFORM)\"]\n            }\n            #expect(isHost == false, \"\\(target.common.name)\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftBuildSupportTests/ProductTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\nimport Foundation\nimport _InternalTestSupport\n\n// Tests which rely on implementation details of the build system's directory layout to verify outputs are correct.\n// These are fairly susceptible to breaking when implementation details change, so should be extended sparingly.\n@Suite\nstruct ProductTests {\n    @Test\n    func materializedStaticProducts() async throws {\n        try await fixture(name: \"Miscellaneous/Simple\") { fixturePath in\n            try await executeSwiftBuild(fixturePath, buildSystem: .swiftbuild)\n            let productsSubDirectory: String\n            let expectedProductName: String\n            switch try ProcessInfo.processInfo.hostOperatingSystem() {\n            case .macOS:\n                productsSubDirectory = \"Debug\"\n                expectedProductName = \"libFoo.a\"\n            case .iOS:\n                productsSubDirectory = \"Debug-iphoneos\"\n                expectedProductName = \"libFoo.a\"\n            case .tvOS:\n                productsSubDirectory = \"Debug-appletvos\"\n                expectedProductName = \"libFoo.a\"\n            case .watchOS:\n                productsSubDirectory = \"Debug-watchos\"\n                expectedProductName = \"libFoo.a\"\n            case .visionOS:\n                productsSubDirectory = \"Debug-xros\"\n                expectedProductName = \"libFoo.a\"\n            case .windows:\n                productsSubDirectory = \"Debug-windows\"\n                expectedProductName = \"Foo.objlib\"\n            case .linux:\n                productsSubDirectory = \"Debug-linux\"\n                expectedProductName = \"libFoo.a\"\n            case .freebsd:\n                productsSubDirectory = \"Debug-freebsd\"\n                expectedProductName = \"libFoo.a\"\n            case .openbsd:\n                productsSubDirectory = \"Debug-openbsd\"\n                expectedProductName = \"libFoo.a\"\n            case .android:\n                productsSubDirectory = \"Debug-android\"\n                expectedProductName = \"libFoo.a\"\n            case .unknown:\n                productsSubDirectory = \"Debug\"\n                expectedProductName = \"libFoo.a\"\n            }\n            let products = try FileManager.default.contentsOfDirectory(atPath: fixturePath.appending(components: [\".build\", \"out\", \"Products\", productsSubDirectory]).pathString)\n            #expect(products.contains(expectedProductName))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftBuildSupportTests/SwiftBuildSystemMessageHandlerTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\nimport struct SWBUtil.AbsolutePath\nimport Testing\n@_spi(Testing)\nimport SwiftBuild\nimport SwiftBuildSupport\n\nimport TSCBasic\nimport _InternalTestSupport\n\n@Suite\nstruct SwiftBuildSystemMessageHandlerTests {\n    struct MockMessageHandlerProvider {\n        private let warningMessageHandler: SwiftBuildSystemMessageHandler\n        private let errorMessageHandler: SwiftBuildSystemMessageHandler\n        private let debugMessageHandler: SwiftBuildSystemMessageHandler\n\n        public init(\n            outputStream: BufferedOutputByteStream,\n            observabilityScope: ObservabilityScope,\n        ) {\n            self.warningMessageHandler = .init(\n                observabilityScope: observabilityScope,\n                outputStream: outputStream,\n                logLevel: .warning\n            )\n            self.errorMessageHandler = .init(\n                observabilityScope: observabilityScope,\n                outputStream: outputStream,\n                logLevel: .error\n            )\n            self.debugMessageHandler = .init(\n                observabilityScope: observabilityScope,\n                outputStream: outputStream,\n                logLevel: .debug\n            )\n        }\n\n        public var warning: SwiftBuildSystemMessageHandler {\n            return warningMessageHandler\n        }\n\n        public var error: SwiftBuildSystemMessageHandler {\n            return errorMessageHandler\n        }\n\n        public var debug: SwiftBuildSystemMessageHandler {\n            return debugMessageHandler\n        }\n    }\n\n    let outputStream: BufferedOutputByteStream\n    let observability: TestingObservability\n    let messageHandler: MockMessageHandlerProvider\n\n    init() {\n        self.outputStream = BufferedOutputByteStream()\n        self.observability = ObservabilitySystem.makeForTesting(\n            outputStream: outputStream\n        )\n        self.messageHandler = .init(\n            outputStream: self.outputStream,\n            observabilityScope: self.observability.topScope\n        )\n    }\n\n    @Test\n    func testExceptionThrownWhenTaskCompleteEventReceivedWithoutTaskStart() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .taskCompleteInfo(result: .success)\n        ]\n\n        #expect(throws: (any Error).self) {\n            for event in events {\n                _ = try messageHandler.emitEvent(event)\n            }\n        }\n    }\n\n    @Test\n    func testNoDiagnosticsReported() throws {\n        let messageHandler = self.messageHandler.warning\n        let events: [SwiftBuildMessage] = [\n            .taskStartedInfo(),\n            .taskCompleteInfo(),\n            .buildCompletedInfo()\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        // Check output stream\n        let output = self.outputStream.bytes.description\n        #expect(!output.contains(\"error\"))\n\n        // Check observability diagnostics\n        expectNoDiagnostics(self.observability.diagnostics)\n    }\n\n    @Test\n    func testSimpleDiagnosticReported() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .taskStartedInfo(taskSignature: \"simple-diagnostic\"),\n            .diagnostic(locationContext2: .init(taskSignature: \"simple-diagnostic\"), message: \"Simple diagnostic\", appendToOutputStream: true),\n            .taskCompleteInfo(taskSignature: \"simple-diagnostic\", result: .failed) // Handler only emits when a task is completed.\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        #expect(self.observability.hasErrorDiagnostics)\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: \"Simple diagnostic\", severity: .error)\n        }\n    }\n\n    @Test\n    func testTwoDifferentDiagnosticsReported() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .taskStartedInfo(taskSignature: \"diagnostics\"),\n            .diagnostic(\n                locationContext2: .init(\n                    taskSignature: \"diagnostics\"\n                ),\n                message: \"First diagnostic\",\n                appendToOutputStream: true\n            ),\n            .diagnostic(\n                locationContext2: .init(\n                    taskSignature: \"diagnostics\"\n                ),\n                message: \"Second diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskCompleteInfo(taskSignature: \"diagnostics\", result: .failed) // Handler only emits when a task is completed.\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        #expect(self.observability.hasErrorDiagnostics)\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: \"First diagnostic\", severity: .error)\n            result.check(diagnostic: \"Second diagnostic\", severity: .error)\n        }\n    }\n\n    @Test\n    func testManyDiagnosticsReported() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .taskStartedInfo(taskID: 1, taskSignature: \"simple-diagnostic\"),\n            .diagnostic(\n                locationContext2: .init(taskSignature: \"simple-diagnostic\"),\n                message: \"Simple diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskStartedInfo(taskID: 2, taskSignature: \"another-diagnostic\"),\n            .taskStartedInfo(taskID: 3, taskSignature: \"warning-diagnostic\"),\n            .diagnostic(\n                kind: .warning,\n                locationContext2: .init(taskSignature: \"warning-diagnostic\"),\n                message: \"Warning diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskCompleteInfo(taskID: 1, taskSignature: \"simple-diagnostic\", result: .failed),\n            .diagnostic(\n                kind: .warning,\n                locationContext2: .init(taskSignature: \"warning-diagnostic\"),\n                message: \"Another warning diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskCompleteInfo(taskID: 3, taskSignature: \"warning-diagnostic\", result: .success),\n            .diagnostic(\n                kind: .note,\n                locationContext2: .init(taskSignature: \"another-diagnostic\"),\n                message: \"Another diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskCompleteInfo(taskID: 2, taskSignature: \"another-diagnostic\", result: .failed)\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        #expect(self.observability.hasErrorDiagnostics)\n\n        try expectDiagnostics(observability.diagnostics) { result in\n            result.check(diagnostic: \"Simple diagnostic\", severity: .error)\n            result.check(diagnostic: \"Another diagnostic\", severity: .info)\n            result.check(diagnostic: \"Another warning diagnostic\", severity: .warning)\n            result.check(diagnostic: \"Warning diagnostic\", severity: .warning)\n        }\n    }\n\n    @Test\n    func testCompilerOutputDiagnosticsWithoutDuplicatedLogging() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let simpleDiagnosticString: String = \"[error]: Simple diagnostic\\n\"\n        let simpleOutputInfo: SwiftBuildMessage = .outputInfo(\n            data: data(simpleDiagnosticString),\n            locationContext: .task(taskID: 1, targetID: 1),\n            locationContext2: .init(targetID: 1, taskSignature: \"simple-diagnostic\")\n        )\n\n        let warningDiagnosticString: String = \"[warning]: Warning diagnostic\\n\"\n        let warningOutputInfo: SwiftBuildMessage = .outputInfo(\n            data: data(warningDiagnosticString),\n            locationContext: .task(taskID: 3, targetID: 1),\n            locationContext2: .init(targetID: 1, taskSignature: \"warning-diagnostic\")\n        )\n\n        let anotherDiagnosticString = \"[note]: Another diagnostic\\n\"\n        let anotherOutputInfo: SwiftBuildMessage = .outputInfo(\n            data: data(anotherDiagnosticString),\n            locationContext: .task(taskID: 2, targetID: 1),\n            locationContext2: .init(targetID: 1, taskSignature: \"another-diagnostic\")\n        )\n\n        let anotherWarningDiagnosticString: String = \"[warning]: Another warning diagnostic\\n\"\n        let anotherWarningOutputInfo: SwiftBuildMessage = .outputInfo(\n            data: data(anotherWarningDiagnosticString),\n            locationContext: .task(taskID: 3, targetID: 1),\n            locationContext2: .init(targetID: 1, taskSignature: \"warning-diagnostic\")\n        )\n\n        let events: [SwiftBuildMessage] = [\n            .taskStartedInfo(taskID: 1, taskSignature: \"simple-diagnostic\"),\n            .diagnostic(\n                locationContext2: .init(taskSignature: \"simple-diagnostic\"),\n                message: \"Simple diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskStartedInfo(taskID: 2, taskSignature: \"another-diagnostic\"),\n            .taskStartedInfo(taskID: 3, taskSignature: \"warning-diagnostic\"),\n            .diagnostic(\n                kind: .warning,\n                locationContext2: .init(taskSignature: \"warning-diagnostic\"),\n                message: \"Warning diagnostic\",\n                appendToOutputStream: true\n            ),\n            anotherWarningOutputInfo,\n            simpleOutputInfo,\n            .taskCompleteInfo(taskID: 1, taskSignature: \"simple-diagnostic\"),\n            .diagnostic(\n                kind: .warning,\n                locationContext2: .init(taskSignature: \"warning-diagnostic\"),\n                message: \"Another warning diagnostic\",\n                appendToOutputStream: true\n            ),\n            warningOutputInfo,\n            .taskCompleteInfo(taskID: 3, taskSignature: \"warning-diagnostic\"),\n            .diagnostic(\n                kind: .note,\n                locationContext2: .init(taskSignature: \"another-diagnostic\"),\n                message: \"Another diagnostic\",\n                appendToOutputStream: true\n            ),\n            anotherOutputInfo,\n            .taskCompleteInfo(taskID: 2, taskSignature: \"another-diagnostic\")\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        let outputText = self.outputStream.bytes.description\n        #expect(outputText.contains(\"error\"))\n    }\n\n    @Test\n    func testDiagnosticOutputWhenOnlyWarnings() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .taskStartedInfo(taskID: 1, taskSignature: \"simple-warning-diagnostic\"),\n            .diagnostic(\n                kind: .warning,\n                locationContext2: .init(taskSignature: \"simple-warning-diagnostic\"),\n                message: \"Simple warning diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskCompleteInfo(taskID: 1, taskSignature: \"simple-warning-diagnostic\", result: .success)\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        #expect(self.observability.hasWarningDiagnostics)\n    }\n\n    @Test\n    func testDiagnosticOutputWhenOnlyNotes() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .taskStartedInfo(taskID: 1, taskSignature: \"simple-note-diagnostic\"),\n            .diagnostic(\n                kind: .note,\n                locationContext2: .init(taskSignature: \"simple-note-diagnostic\"),\n                message: \"Simple note diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskCompleteInfo(taskID: 1, taskSignature: \"simple-note-diagnostic\", result: .success)\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n        \n        #expect(!self.observability.hasWarningDiagnostics)\n        #expect(!self.observability.hasErrorDiagnostics)\n        #expect(self.observability.diagnostics.count == 1)\n        try expectDiagnostics(self.observability.diagnostics) { result in\n            result.check(diagnostic: \"Simple note diagnostic\", severity: .info)\n        }\n    }\n\n    @Test\n    func testDiagnosticOutputWhenOnlyDebugs() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .taskStartedInfo(taskID: 1, taskSignature: \"simple-debug-diagnostic\"),\n            .diagnostic(\n                kind: .remark,\n                locationContext2: .init(taskSignature: \"simple-debug-diagnostic\"),\n                message: \"Simple debug diagnostic\",\n                appendToOutputStream: true\n            ),\n            .taskCompleteInfo(taskID: 1, taskSignature: \"simple-debug-diagnostic\", result: .success)\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        #expect(!self.observability.hasWarningDiagnostics)\n        #expect(!self.observability.hasErrorDiagnostics)\n        #expect(self.observability.diagnostics.count == 1)\n        try expectDiagnostics(self.observability.diagnostics) { result in\n            result.check(diagnostic: \"Simple debug diagnostic\", severity: .debug)\n        }\n    }\n\n    @Test\n    func testPlanningOperationStartAndCompleteMessagesVerboseOnly() throws {\n        let verboseMessageHandler = self.messageHandler.debug\n\n        let events: [SwiftBuildMessage] = [\n            .planningOperationStartedInfo(),\n            .planningOperationCompletedInfo()\n        ]\n\n        for event in events {\n            _ = try verboseMessageHandler.emitEvent(event)\n        }\n\n        let verboseOutput = self.outputStream.bytes.description\n\n        #expect(!self.observability.hasWarningDiagnostics)\n        #expect(!self.observability.hasErrorDiagnostics)\n        #expect(self.observability.diagnostics.count == 0)\n\n        #expect(verboseOutput.contains(\"Planning build\"))\n        #expect(verboseOutput.contains(\"Planning complete\"))\n    }\n\n    @Test\n    func testPlanningOperationStartAndCompleteNoMessageWarningLogLevel() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .planningOperationStartedInfo(),\n            .planningOperationCompletedInfo()\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        let output = self.outputStream.bytes.description\n\n        #expect(!self.observability.hasWarningDiagnostics)\n        #expect(!self.observability.hasErrorDiagnostics)\n        #expect(self.observability.diagnostics.count == 0)\n\n        #expect(!output.contains(\"Planning build\"))\n        #expect(!output.contains(\"Planning complete\"))\n    }\n\n    @Test\n    func testPlanningOperationStartAndCompleteNoMessageErrorLogLevel() throws {\n        let messageHandler = self.messageHandler.error\n\n        let events: [SwiftBuildMessage] = [\n            .planningOperationStartedInfo(),\n            .planningOperationCompletedInfo()\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        let output = self.outputStream.bytes.description\n\n        #expect(!self.observability.hasWarningDiagnostics)\n        #expect(!self.observability.hasErrorDiagnostics)\n        #expect(self.observability.diagnostics.count == 0)\n\n        #expect(!output.contains(\"Planning build\"))\n        #expect(!output.contains(\"Planning complete\"))\n    }\n\n    @Test\n    func testTargetUpToDateMessage() throws {\n        let messageHandler = self.messageHandler.debug\n\n        let events: [SwiftBuildMessage] = [\n            .targetUpToDateInfo()\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        #expect(!self.observability.hasWarningDiagnostics)\n        #expect(!self.observability.hasErrorDiagnostics)\n        #expect(self.observability.diagnostics.count == 0)\n\n        let output = self.outputStream.bytes.description\n        #expect(output.contains(\"Target mock-target-guid up to date.\"))\n    }\n\n    @Test\n    func testBuildProgressMessages() throws {\n        let messageHandler = self.messageHandler.warning\n\n        let events: [SwiftBuildMessage] = [\n            .progress(message: \"Weird percent\", percentComplete: -1),\n            .progress(message: \"12 / 32\", percentComplete: 0),\n            .progress(message: \"Something useful\", percentComplete: 12),\n            .progress(message: \"Complete\", percentComplete: 100)\n        ]\n\n        for event in events {\n            _ = try messageHandler.emitEvent(event)\n        }\n\n        #expect(!self.observability.hasWarningDiagnostics)\n        #expect(!self.observability.hasErrorDiagnostics)\n        #expect(self.observability.diagnostics.count == 0)\n\n        let output = self.outputStream.bytes.description\n        #expect(output.contains(\"Weird percent\"))\n        #expect(!output.contains(\"12 / 32\"))\n        #expect(output.contains(\"Something useful\"))\n        #expect(output.contains(\"Complete\"))\n    }\n}\n\nprivate func data(_ message: String) -> Data {\n    Data(message.utf8)\n}\n\n/// Convenience inits for testing\nextension SwiftBuildMessage {\n    /// SwiftBuildMessage.TaskStartedInfo\n    package static func taskStartedInfo(\n        taskID: Int = 1,\n        targetID: Int? = nil,\n        taskSignature: String = \"mock-task-signature\",\n        parentTaskID: Int? = nil,\n        ruleInfo: String = \"mock-rule\",\n        interestingPath: SwiftBuild.AbsolutePath? = nil,\n        commandLineDisplayString: String? = nil,\n        executionDescription: String = \"execution description\",\n        serializedDiagnosticsPath: [SwiftBuild.AbsolutePath] = []\n    ) -> SwiftBuildMessage {\n        .taskStarted(\n            .init(\n                taskID: taskID,\n                targetID: targetID,\n                taskSignature: taskSignature,\n                parentTaskID: parentTaskID,\n                ruleInfo: ruleInfo,\n                interestingPath: interestingPath,\n                commandLineDisplayString: commandLineDisplayString,\n                executionDescription: executionDescription,\n                serializedDiagnosticsPaths: serializedDiagnosticsPath\n            )\n        )\n    }\n\n    /// SwiftBuildMessage.TaskCompletedInfo\n    package static func taskCompleteInfo(\n        taskID: Int = 1,\n        taskSignature: String = \"mock-task-signature\",\n        result: TaskCompleteInfo.Result = .success,\n        signalled: Bool = false,\n        metrics: TaskCompleteInfo.Metrics? = nil\n    ) -> SwiftBuildMessage {\n        .taskComplete(\n            .init(\n                taskID: taskID,\n                taskSignature: taskSignature,\n                result: result,\n                signalled: signalled,\n                metrics: metrics\n            )\n        )\n    }\n\n    /// SwiftBuildMessage.DiagnosticInfo\n    package static func diagnostic(\n        kind: DiagnosticInfo.Kind = .error,\n        location: DiagnosticInfo.Location = .unknown,\n        locationContext: LocationContext = .task(taskID: 1, targetID: 1),\n        locationContext2: LocationContext2 = .init(),\n        component: DiagnosticInfo.Component = .default,\n        message: String = \"Mock diagnostic message.\",\n        optionName: String? = nil,\n        appendToOutputStream: Bool = false,\n        childDiagnostics: [DiagnosticInfo] = [],\n        sourceRanges: [DiagnosticInfo.SourceRange] = [],\n        fixIts: [SwiftBuildMessage.DiagnosticInfo.FixIt] = []\n    ) -> SwiftBuildMessage {\n        .diagnostic(\n            .init(\n                kind: kind,\n                location: location,\n                locationContext: locationContext,\n                locationContext2: locationContext2,\n                component: component,\n                message: message,\n                optionName: optionName,\n                appendToOutputStream: appendToOutputStream,\n                childDiagnostics: childDiagnostics,\n                sourceRanges: sourceRanges,\n                fixIts: fixIts\n            )\n        )\n    }\n\n    /// SwiftBuildMessage.BuildStartedInfo\n    package static func buildStartedInfo(\n        baseDirectory: SwiftBuild.AbsolutePath,\n        derivedDataPath: SwiftBuild.AbsolutePath? = nil\n    ) -> SwiftBuildMessage.BuildStartedInfo {\n        .init(\n            baseDirectory: baseDirectory,\n            derivedDataPath: derivedDataPath\n        )\n    }\n\n    /// SwiftBuildMessage.BuildCompleteInfo\n    package static func buildCompletedInfo(\n        result: BuildCompletedInfo.Result = .ok,\n        metrics: BuildOperationMetrics? = nil\n    ) -> SwiftBuildMessage {\n        .buildCompleted(\n            .init(\n                result: result,\n                metrics: metrics\n            )\n        )\n    }\n\n    /// SwiftBuildMessage.OutputInfo\n    package static func outputInfo(\n        data: Data,\n        locationContext: LocationContext = .task(taskID: 1, targetID: 1),\n        locationContext2: LocationContext2 = .init(targetID: 1, taskSignature: \"mock-task-signature\")\n    ) -> SwiftBuildMessage {\n        .output(\n            .init(\n                data: data,\n                locationContext: locationContext,\n                locationContext2: locationContext2\n            )\n        )\n    }\n\n    /// SwiftBuildMessage.PlanningOperationStartedInfo\n    package static func planningOperationStartedInfo(\n        planningOperationID: String = \"mock-planning-operation-id\"\n    ) -> SwiftBuildMessage {\n        .planningOperationStarted(\n            .init(planningOperationID: planningOperationID)\n        )\n    }\n\n    /// SwiftBuildMessage.PlanningOperationCompletedInfo\n    package static func planningOperationCompletedInfo(\n        planningOperationID: String = \"mock-planning-operation-id\"\n    ) -> SwiftBuildMessage {\n        .planningOperationCompleted(\n            .init(planningOperationID: planningOperationID)\n        )\n    }\n\n    /// SwiftBuildMessage.TargetUpToDateInfo\n    package static func targetUpToDateInfo(\n        guid: String = \"mock-target-guid\"\n    ) -> SwiftBuildMessage {\n        .targetUpToDate(\n            .init(guid: guid)\n        )\n    }\n\n    /// SwiftBuildMessage.DidUpdateProgressInfo\n    package static func progress(\n        message: String,\n        percentComplete: Double,\n        showInLog: Bool = false,\n        targetName: String? = nil\n    ) -> SwiftBuildMessage {\n        .didUpdateProgress(\n            .init(\n                message: message,\n                percentComplete: percentComplete,\n                showInLog: showInLog,\n                targetName: targetName\n            )\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftBuildSupportTests/SwiftBuildSystemTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\n@testable import SwiftBuildSupport\nimport SPMBuildCore\n\nimport var TSCBasic.stderrStream\nimport Basics\nimport Workspace\nimport PackageModel\nimport PackageGraph\nimport PackageLoading\n\n@testable import SwiftBuild\nimport SWBBuildService\n\nimport _InternalTestSupport\n\nfunc withInstantiatedSwiftBuildSystem(\n    fromFixture fixtureName: String,\n    buildParameters: BuildParameters? = nil,\n    logLevel: Basics.Diagnostic.Severity = .warning,\n    do doIt: @escaping (SwiftBuildSupport.SwiftBuildSystem, SWBBuildServiceSession, TestingObservability, BuildParameters,) async throws -> (),\n) async throws {\n    let fileSystem = Basics.localFileSystem\n\n    try await fixture(name: fixtureName) { fixturePath  in\n        try await withTemporaryDirectory  { tmpDir in\n            let buildParameters = if let buildParameters {\n                buildParameters\n            } else {\n                mockBuildParameters(destination: .host)\n            }\n            let observabilitySystem: TestingObservability = ObservabilitySystem.makeForTesting()\n            let toolchain = try UserToolchain.default\n            let workspace = try Workspace(\n                fileSystem: fileSystem,\n                forRootPackage: fixturePath,\n                customManifestLoader: ManifestLoader(toolchain: toolchain),\n            )\n            let rootInput = PackageGraphRootInput(packages: [fixturePath], dependencies: [])\n            let graphLoader = {\n                try await workspace.loadPackageGraph(\n                    rootInput: rootInput,\n                    observabilityScope: observabilitySystem.topScope\n                )\n            }\n\n            let pluginScriptRunner = try DefaultPluginScriptRunner(\n                fileSystem: fileSystem,\n                cacheDir: tmpDir.appending(\"plugin-script-cache\"),\n                toolchain: UserToolchain.default,\n            )\n\n            let swBuild = try SwiftBuildSystem(\n                buildParameters: buildParameters,\n                packageGraphLoader: graphLoader,\n                packageManagerResourcesDirectory: nil,\n                additionalFileRules: [],\n                outputStream: TSCBasic.stderrStream,\n                logLevel: logLevel,\n                fileSystem: fileSystem,\n                observabilityScope: observabilitySystem.topScope,\n                pluginConfiguration: PluginConfiguration(\n                    scriptRunner: pluginScriptRunner,\n                    workDirectory: AbsolutePath(\"/tmp/plugin-script-working-dir\"),\n                    disableSandbox: true,\n                ),\n                delegate: nil,\n            )\n\n            try await SwiftBuildSupport.withService(\n                connectionMode: .inProcessStatic(swiftbuildServiceEntryPoint),\n            ) { service in\n\n                let result = await service.createSession(\n                    name: \"session\",\n                    cachePath: nil,\n                    inferiorProductsPath: nil,\n                    environment: nil,\n                )\n\n                let buildSession: SWBBuildServiceSession\n                switch result {\n                case (.success(let session), _):\n                    buildSession = session\n                case (.failure(let error), _):\n                    throw StringError(\"\\(error)\")\n                    // throw SessionFailedError(error: error, diagnostics: diagnostics)\n                }\n\n                do {\n                    try await doIt(swBuild, buildSession, observabilitySystem, buildParameters)\n                    try await buildSession.close()\n                } catch {\n                    try await buildSession.close()\n                    throw error\n                }\n            }\n        }\n    }\n}\n\nextension PackageModel.Sanitizer {\n    var hasSwiftBuildSupport: Bool {\n        switch self {\n            case .address, .thread, .undefined: true\n            case .fuzzer, .scudo: false\n        }\n    }\n\n    var swiftBuildSettingName: String? {\n        switch self {\n            case .address: \"ENABLE_ADDRESS_SANITIZER\"\n            case .thread: \"ENABLE_THREAD_SANITIZER\"\n            case .undefined: \"ENABLE_UNDEFINED_BEHAVIOR_SANITIZER\"\n            case .fuzzer, .scudo: nil\n        }\n\n    }\n}\n\n@Suite(\n    .tags(\n        .TestSize.medium,\n    ),\n    .requireCompiledWith6_3OrLater(\"https://github.com/swiftlang/swift-corelibs-foundation/pull/5269\")\n)\nstruct SwiftBuildSystemTests {\n\n    @Suite(\n        .tags(\n            .FunctionalArea.Sanitizer,\n        )\n    )\n    struct SanitizerTests {\n\n        @Test(\n            arguments: PackageModel.Sanitizer.allCases.filter { $0.hasSwiftBuildSupport },\n        )\n        func sanitizersSettingSetCorrectBuildRequest(\n            sanitizer: Sanitizer,\n        ) async throws {\n            try await withInstantiatedSwiftBuildSystem(\n                fromFixture: \"PIFBuilder/Simple\",\n                buildParameters: mockBuildParameters(\n                    destination: .host,\n                    sanitizers: [sanitizer],\n                ),\n            ) { swiftBuild, session, observabilityScope, buildParameters in\n                let buildSettings: SWBBuildParameters = try await swiftBuild.makeBuildParameters(\n                    session: session,\n                    symbolGraphOptions: nil,\n                    setToolchainSetting: false, // Set this to false as SwiftBuild checks the toolchain path\n                )\n\n                let synthesizedArgs = try #require(buildSettings.overrides.synthesized)\n\n                let swbSettingName = try #require(sanitizer.swiftBuildSettingName)\n                #expect(synthesizedArgs.table[swbSettingName] == \"YES\")\n            }\n\n        }\n\n        @Test(\n            arguments: PackageModel.Sanitizer.allCases.filter { !$0.hasSwiftBuildSupport },\n        )\n        func unsupportedSanitizersRaisesError(\n            sanitizer: Sanitizer,\n        ) async throws {\n            try await withInstantiatedSwiftBuildSystem(\n                fromFixture: \"PIFBuilder/Simple\",\n                buildParameters: mockBuildParameters(\n                    destination: .host,\n                    sanitizers: [sanitizer],\n                ),\n            ) { swiftBuild, session, observabilityScope, buildParameters in\n                await #expect(throws: (any Error).self) {\n                    try await swiftBuild.makeBuildParameters(\n                        session: session,\n                        symbolGraphOptions: nil,\n                        setToolchainSetting: false, // Set this to false as SwiftBuild checks the toolchain path\n                    )\n                }\n            }\n        }\n    }\n\n    @Suite(\n        .tags(\n            .FunctionalArea.LinkSwiftStaticStdlib,\n        ),\n    )\n    struct SwiftStaticStdlibSettingTests {\n        @Test\n        func makingBuildParametersRaisesAWarningWhenRunOnDarwin() async throws {\n            // GIVEN we have a Darwin triple\n            let triple = try Triple(\"x86_64-apple-macosx\")\n            // AND we want to statically link Swift sdtlib\n            let shouldLinkStaticSwiftStdlib = true\n            try await withInstantiatedSwiftBuildSystem(\n                fromFixture: \"PIFBuilder/Simple\",\n                buildParameters: mockBuildParameters(\n                    destination: .host,\n                    shouldLinkStaticSwiftStdlib: shouldLinkStaticSwiftStdlib,\n                    triple: triple,\n                ),\n            ) { swiftBuild, session, observabilityScope, buildParameters in\n                // WHEN we make the build parameter\n                let _: SWBBuildParameters = try await swiftBuild.makeBuildParameters(\n                    session: session,\n                    symbolGraphOptions: nil,\n                    setToolchainSetting: false, // Set this to false as SwiftBuild checks the toolchain path\n                )\n\n                // THEN we expect a warning to be emitted\n                let warnings = observabilityScope.diagnostics.filter {\n                    $0.severity == .warning\n                }\n                #expect(warnings.count == 1)\n\n                let diagnostic = try #require(warnings.first)\n                // AND we expect the diagnostic message, severity and description to be as expected\n                #expect(diagnostic.message == Basics.Diagnostic.swiftBackDeployWarning.message)\n                #expect(diagnostic.severity == Basics.Diagnostic.swiftBackDeployWarning.severity)\n                #expect(diagnostic.description == Basics.Diagnostic.swiftBackDeployWarning.description)\n            }\n        }\n\n        @Test(\n            arguments: [\n                (shouldLinkStaticSwiftStdlib: true, expectedValue: \"YES\"),\n                (shouldLinkStaticSwiftStdlib: false, expectedValue: \"NO\"),\n            ]\n        )\n        func swiftStaticStdLibSettingIsSetCorrectly(\n            shouldLinkStaticSwiftStdlib: Bool,\n            expectedValue: String\n        ) async throws {\n            // GIVEN we have a non-darwin triple AND we want statically link Swift sdtlib or not\n            let nonDarwinTriple = try Triple(\"i686-pc-windows-cygnus\")\n            try await withInstantiatedSwiftBuildSystem(\n                fromFixture: \"PIFBuilder/Simple\",\n                buildParameters: mockBuildParameters(\n                    destination: .host,\n                    shouldLinkStaticSwiftStdlib: shouldLinkStaticSwiftStdlib,\n                    triple: nonDarwinTriple,\n                ),\n            ) { swiftBuild, session, observabilityScope, buildParameters in\n                // WHEN we make the build parameter\n                let buildSettings = try await swiftBuild.makeBuildParameters(\n                    session: session,\n                    symbolGraphOptions: nil,\n                    setToolchainSetting: false, // Set this to false as SwiftBuild checks the toolchain path\n                )\n\n                // THEN we don't expect any warnings to be emitted\n                let warnings = observabilityScope.diagnostics.filter {\n                    $0.severity == .warning\n                }\n                #expect(warnings.isEmpty)\n\n                // AND we expect the build setting to be set correctly\n                let synthesizedArgs = try #require(buildSettings.overrides.synthesized)\n                #expect(synthesizedArgs.table[\"SWIFT_FORCE_STATIC_LINK_STDLIB\"] == expectedValue)\n            }\n        }\n    }\n\n    @Test(\n        arguments: BuildParameters.IndexStoreMode.allCases,\n        // arguments: [BuildParameters.IndexStoreMode.on],\n    )\n    func indexModeSettingSetCorrectBuildRequest(\n        indexStoreSettingUT: BuildParameters.IndexStoreMode\n    ) async throws {\n        try await withInstantiatedSwiftBuildSystem(\n            fromFixture: \"PIFBuilder/Simple\",\n            buildParameters: mockBuildParameters(\n                destination: .host,\n                indexStoreMode: indexStoreSettingUT,\n            ),\n        ) { swiftBuild, session, observabilityScope, buildParameters in\n            let buildSettings = try await swiftBuild.makeBuildParameters(\n                session: session,\n                symbolGraphOptions: nil,\n                setToolchainSetting: false, // Set this to false as SwiftBuild checks the toolchain path\n            )\n\n            let synthesizedArgs = try #require(buildSettings.overrides.synthesized)\n            let expectedSettingValue: String? = switch indexStoreSettingUT {\n                case .on: \"YES\"\n                case .off: \"NO\"\n                case .auto: nil\n            }\n            let expectedPathValue: String? = switch indexStoreSettingUT {\n                case .on: buildParameters.indexStore.pathString\n                case .off: nil\n                case .auto: nil\n            }\n\n            #expect(synthesizedArgs.table[\"SWIFT_INDEX_STORE_ENABLE\"] == expectedSettingValue)\n            #expect(synthesizedArgs.table[\"CLANG_INDEX_STORE_ENABLE\"] == expectedSettingValue)\n            #expect(synthesizedArgs.table[\"SWIFT_INDEX_STORE_PATH\"] == expectedPathValue)\n            #expect(synthesizedArgs.table[\"CLANG_INDEX_STORE_PATH\"] == expectedPathValue)\n        }\n    }\n\n    @Test(\n        .serialized,\n        arguments: [\n            (linkerDeadStripUT: true, expectedValue: \"YES\"),\n            (linkerDeadStripUT: false, expectedValue: nil),\n        ]\n    )\n    func validateDeadStripSetting(\n        linkerDeadStripUT: Bool,\n        expectedValue: String?\n    ) async throws {\n        try await withInstantiatedSwiftBuildSystem(\n            fromFixture: \"PIFBuilder/Simple\",\n            buildParameters: mockBuildParameters(\n                destination: .host,\n                linkerDeadStrip: linkerDeadStripUT,\n            ),\n        ) { swiftBuild, session, observabilityScope, buildParameters in\n\n            let buildSettings = try await swiftBuild.makeBuildParameters(\n                session: session,\n                symbolGraphOptions: nil,\n                setToolchainSetting: false, // Set this to false as SwiftBuild checks the toolchain path\n            )\n\n            let synthesizedArgs = try #require(buildSettings.overrides.synthesized)\n            let actual = synthesizedArgs.table[\"DEAD_CODE_STRIPPING\"]\n            #expect(\n                actual == expectedValue,\n                \"dead strip: \\(linkerDeadStripUT) >>> Actual: '\\(actual)' expected: '\\(String(describing: expectedValue))'\",\n            )\n       }\n    }\n\n    @Test(\n        .issue(\"https://github.com/swiftlang/swift-package-manager/issues/9321\", relationship: .verifies),\n        arguments: [\n            0,\n            1,\n            2,\n            10,\n        ],\n    )\n    func numberOfWorkersBuildParameterSetsTheExpectedSwiftBuildRequest(\n        expectedNumberOfWorkers: UInt32,\n    ) async throws {\n        try await withTemporaryDirectory { tempDir in\n            try await withInstantiatedSwiftBuildSystem(\n                fromFixture: \"PIFBuilder/Simple\",\n                buildParameters: mockBuildParameters(\n                    destination: .host,\n                    numberOfWorkers: expectedNumberOfWorkers,\n                ),\n            ) { swiftBuild, session, observabilityScope, buildParameters in\n                let buildRequest = try await swiftBuild.makeBuildRequest(\n                    session: session,\n                    configuredTargets: [],\n                    derivedDataPath: tempDir,\n                    symbolGraphOptions: nil,\n                    setToolchainSetting: false\n                )\n\n                #expect(buildRequest.schedulerLaneWidthOverride == expectedNumberOfWorkers)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftFixItTests/BasicTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\nstruct BasicTests {\n    @Test\n    func testNoDiagnostics() throws {\n        // Edge case.\n        try testAPI1File { _ in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"var x = 1\"),\n                summary: .init(numberOfFixItsApplied: 0, numberOfFilesChanged: 0),\n                diagnostics: []\n            )\n        }\n    }\n\n    @Test\n    func testPrimaryDiag() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"let x = 1\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testNote() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"let x = 1\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error\",\n                        location: .init(path: path, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"note\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 1),\n                                        end: .init(path: path, line: 1, column: 4),\n                                        text: \"let\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testMultiplePrimaryDiagsWithNotes() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"let x = 22\"),\n                summary: .init(numberOfFixItsApplied: 2, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"error1_note1\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 1),\n                                        end: .init(path: path, line: 1, column: 4),\n                                        text: \"let\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"error2_note1\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Make sure we apply this fix-it.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 9),\n                                        end: .init(path: path, line: 1, column: 10),\n                                        text: \"22\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testNonOverlappingCompoundFixIt() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(\n                    input: \"\"\"\n                    var x = 1\n                    var y = 2\n                    var z = 3\n                    var w = foo(1, 2)\n                    \"\"\",\n                    result: \"\"\"\n                    let x = 1\n                    var y = 244\n                    z = 3\n                    w = fooo(1, 233)\n                    \"\"\"\n                ),\n                summary: .init(numberOfFixItsApplied: 2, numberOfFilesChanged: 1),\n                diagnostics: [\n                    // Different lines.\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Replacement.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                            // Addition.\n                            .init(\n                                start: .init(path: path, line: 2, column: 10),\n                                end: .init(path: path, line: 2, column: 10),\n                                text: \"44\"\n                            ),\n                            // Deletion.\n                            .init(\n                                start: .init(path: path, line: 3, column: 1),\n                                end: .init(path: path, line: 3, column: 5),\n                                text: \"\"\n                            ),\n                        ]\n                    ),\n                    // Same line.\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 4, column: 1),\n                        fixIts: [\n                            // Replacement.\n                            .init(\n                                start: .init(path: path, line: 4, column: 9),\n                                end: .init(path: path, line: 4, column: 12),\n                                text: \"fooo\"\n                            ),\n                            // Addition.\n                            .init(\n                                start: .init(path: path, line: 4, column: 17),\n                                end: .init(path: path, line: 4, column: 17),\n                                text: \"33\"\n                            ),\n                            // Deletion.\n                            .init(\n                                start: .init(path: path, line: 4, column: 1),\n                                end: .init(path: path, line: 4, column: 5),\n                                text: \"\"\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testOverlappingCompoundFixIt() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"_ = 1\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 6),\n                                text: \"_\"\n                            ),\n                            // Skipped, overlaps with previous fix-it.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testOverlappingFixIts() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"_ = 1\"),\n                summary: .init(\n                    // 2 because skipped by SwiftIDEUtils.FixItApplier, not SwiftFixIt.\n                    numberOfFixItsApplied: 2 /**/,\n                    numberOfFilesChanged: 1\n                ),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 6),\n                                text: \"_\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Skipped, overlaps with previous fix-it.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testFixItsMultipleFiles() throws {\n        try testAPI2Files { path1, path2 in\n            .init(\n                edits: (\n                    .init(input: \"var x = 1\", result: \"let _ = 1\"),\n                    .init(input: \"var x = 1\", result: \"let _ = 1\")\n                ),\n                summary: .init(numberOfFixItsApplied: 4, numberOfFilesChanged: 2),\n                diagnostics: [\n                    // path1\n                    PrimaryDiagnostic(\n                        level: .warning,\n                        text: \"warning1\",\n                        location: .init(path: path1, line: 1, column: 1),\n                        fixIts: [\n                            .init(\n                                start: .init(path: path1, line: 1, column: 1),\n                                end: .init(path: path1, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path1, line: 1, column: 5),\n                        fixIts: [\n                            .init(\n                                start: .init(path: path1, line: 1, column: 5),\n                                end: .init(path: path1, line: 1, column: 6),\n                                text: \"_\"\n                            ),\n                        ]\n                    ),\n                    // path2\n                    PrimaryDiagnostic(\n                        level: .warning,\n                        text: \"warning2\",\n                        location: .init(path: path2, line: 1, column: 5),\n                        fixIts: [\n                            .init(\n                                start: .init(path: path2, line: 1, column: 5),\n                                end: .init(path: path2, line: 1, column: 6),\n                                text: \"_\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path2, line: 1, column: 1),\n                        fixIts: [\n                            .init(\n                                start: .init(path: path2, line: 1, column: 1),\n                                end: .init(path: path2, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testNoteInDifferentFile() throws {\n        try testAPI2Files { path1, path2 in\n            .init(\n                edits: (\n                    .init(input: \"var x = 1\", result: \"let x = 1\"),\n                    .init(input: \"var x = 1\", result: \"var x = 1\")\n                ),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error\",\n                        location: .init(path: path2, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"note\",\n                                location: .init(path: path1, line: 1, column: 1),\n                                fixIts: [\n                                    .init(\n                                        start: .init(path: path1, line: 1, column: 1),\n                                        end: .init(path: path1, line: 1, column: 4),\n                                        text: \"let\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testDiagNotInTheSameFileAsFixIt() {\n        #expect(throws: Error.self) {\n            try testAPI2Files { path1, path2 in\n                .init(\n                    edits: (\n                        .init(input: \"var x = 1\", result: \"let x = 1\"),\n                        .init(input: \"\", result: \"\")\n                    ),\n                    summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                    diagnostics: [\n                        PrimaryDiagnostic(\n                            level: .error,\n                            text: \"error\",\n                            location: .init(path: path2, line: 1, column: 1),\n                            fixIts: [\n                                .init(\n                                    start: .init(path: path1, line: 1, column: 1),\n                                    end: .init(path: path1, line: 1, column: 4),\n                                    text: \"let\"\n                                ),\n                            ]\n                        ),\n                    ]\n                )\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftFixItTests/CategoryTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\nstruct CategoryTests {\n    @Test\n    func testCorrectCategory() throws {\n        try testAPI1File(categories: [\"Other\", \"Test\"]) { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"let _ = 1\"),\n                summary: .init(numberOfFixItsApplied: 2, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        category: \"Test\",\n                        fixIts: [\n                            // Applied, correct category.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 4),\n                        category: \"Other\",\n                        fixIts: [\n                            // Applied, correct category.\n                            .init(\n                                start: .init(path: path, line: 1, column: 5),\n                                end: .init(path: path, line: 1, column: 6),\n                                text: \"_\"\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testCorrectCategoryWithNotes() throws {\n        try testAPI1File(categories: [\"Other\", \"Test\"]) { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"let _ = 22\"),\n                summary: .init(numberOfFixItsApplied: 3, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        category: \"Test\",\n                        notes: [\n                            Note(\n                                text: \"error1_note1\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Applied, primary diagnostic has correct category.\n                                    // Category of note does not matter.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 1),\n                                        end: .init(path: path, line: 1, column: 4),\n                                        text: \"let\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 4),\n                        category: \"Other\",\n                        notes: [\n                            // This separator note should not make a difference.\n                            Note(\n                                text: \"error2_note1\",\n                                location: .init(path: path, line: 1, column: 3),\n                            ),\n                            Note(\n                                text: \"error2_note2\",\n                                location: .init(path: path, line: 1, column: 4),\n                                fixIts: [\n                                    // Applied, primary diagnostic has correct category.\n                                    // Category of note does not matter.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 5),\n                                        end: .init(path: path, line: 1, column: 6),\n                                        text: \"_\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error3\",\n                        location: .init(path: path, line: 1, column: 1),\n                        category: \"Test\",\n                        notes: [\n                            Note(\n                                text: \"error3_note1\",\n                                location: .init(path: path, line: 1, column: 1),\n                                category: \"Wrong\",\n                                fixIts: [\n                                    // Applied, primary diagnostic has correct category.\n                                    // Category of note does not matter.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 9),\n                                        end: .init(path: path, line: 1, column: 10),\n                                        text: \"22\",\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testNoCategory() throws {\n        try testAPI1File(categories: [\"Test\"]) { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"var x = 22\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Skipped, no category.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 1),\n                        category: \"Test\",\n                        fixIts: [\n                            // Applied, correct category.\n                            .init(\n                                start: .init(path: path, line: 1, column: 9),\n                                end: .init(path: path, line: 1, column: 10),\n                                text: \"22\",\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testNoCategoryWithNotes() throws {\n        try testAPI1File(categories: [\"Test\"]) { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"var x = 22\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 5),\n                        category: nil,\n                        notes: [\n                            // This separator note should not make a difference.\n                            Note(\n                                text: \"error1_note1\",\n                                location: .init(path: path, line: 1, column: 3),\n                            ),\n                            Note(\n                                text: \"error1_note2\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Skipped, primary diagnostic has no category.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 1),\n                                        end: .init(path: path, line: 1, column: 4),\n                                        text: \"let\",\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 1),\n                        category: \"Test\",\n                        fixIts: [\n                            // Applied, correct category.\n                            .init(\n                                start: .init(path: path, line: 1, column: 9),\n                                end: .init(path: path, line: 1, column: 10),\n                                text: \"22\",\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error3\",\n                        location: .init(path: path, line: 1, column: 4),\n                        category: nil,\n                        notes: [\n                            Note(\n                                text: \"error3_note1\",\n                                location: .init(path: path, line: 1, column: 4),\n                                category: \"Test\",\n                                fixIts: [\n                                    // Skipped, primary diagnostic has no category.\n                                    // Category of note does not matter.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 5),\n                                        end: .init(path: path, line: 1, column: 6),\n                                        text: \"_\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testWrongCategory() throws {\n        try testAPI1File(categories: [\"Test\"]) { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"var x = 22\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        category: \"Other\",\n                        fixIts: [\n                            // Skipped, wrong category.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 1),\n                        category: \"Test\",\n                        fixIts: [\n                            // Applied, correct category.\n                            .init(\n                                start: .init(path: path, line: 1, column: 9),\n                                end: .init(path: path, line: 1, column: 10),\n                                text: \"22\",\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testWrongCategoryWithNotes() throws {\n        try testAPI1File(categories: [\"Test\"]) { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"var x = 22\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 5),\n                        category: \"Other\",\n                        notes: [\n                            // This separator note should not make a difference.\n                            Note(\n                                text: \"error1_note1\",\n                                location: .init(path: path, line: 1, column: 3),\n                            ),\n                            Note(\n                                text: \"error1_note2\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Skipped, primary diagnostic has wrong category.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 1),\n                                        end: .init(path: path, line: 1, column: 4),\n                                        text: \"let\",\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 1),\n                        category: \"Test\",\n                        fixIts: [\n                            // Applied, correct category.\n                            .init(\n                                start: .init(path: path, line: 1, column: 9),\n                                end: .init(path: path, line: 1, column: 10),\n                                text: \"22\",\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error3\",\n                        location: .init(path: path, line: 1, column: 4),\n                        category: \"Other\",\n                        notes: [\n                            Note(\n                                text: \"error3_note1\",\n                                location: .init(path: path, line: 1, column: 4),\n                                category: \"Test\",\n                                fixIts: [\n                                    // Skipped, primary diagnostic has wrong category.\n                                    // Category of note does not matter.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 5),\n                                        end: .init(path: path, line: 1, column: 6),\n                                        text: \"_\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftFixItTests/FilteringTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Testing\n\nstruct FilteringTests {\n    @Test\n    func testIgnoredDiag() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"var x = 22\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .ignored,\n                        text: \"ignored1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Skipped, diagnostic is 'ignored'.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 9),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 9),\n                                end: .init(path: path, line: 1, column: 10),\n                                text: \"22\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .ignored,\n                        text: \"ignored2\",\n                        location: .init(path: path, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"ignored2_note1\",\n                                location: .init(path: path, line: 1, column: 1)\n                            ),\n                            Note(\n                                text: \"ignored2_note2\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Skipped, primary diagnostic is 'ignored'.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 5),\n                                        end: .init(path: path, line: 1, column: 6),\n                                        text: \"_\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testDiagWithNoLocation() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"var x = 22\"),\n                summary: .init(numberOfFixItsApplied: 1, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: nil,\n                        fixIts: [\n                            // Skipped, no location.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 9),\n                                end: .init(path: path, line: 1, column: 10),\n                                text: \"22\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error3\",\n                        location: .init(path: path, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"error3_note1\",\n                                location: .init(path: path, line: 1, column: 3),\n                            ),\n                            Note(\n                                text: \"error3_note2\",\n                                location: nil,\n                                fixIts: [\n                                    // Skipped, no location.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 5),\n                                        end: .init(path: path, line: 1, column: 6),\n                                        text: \"_\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error4\",\n                        location: nil,\n                        notes: [\n                            Note(\n                                text: \"error4_note1\",\n                                location: .init(path: path, line: 1, column: 1)\n                            ),\n                            Note(\n                                text: \"error4_note2\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Skipped, primary diagnostic has no location.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 7),\n                                        end: .init(path: path, line: 1, column: 8),\n                                        text: \":\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testMultipleNotesWithFixIts() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"var x = 1\"),\n                summary: .init(numberOfFixItsApplied: 0, numberOfFilesChanged: 0),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"error1_note1\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Skipped, primary diagnostic has more than 1 note with fix-it.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 1),\n                                        end: .init(path: path, line: 1, column: 4),\n                                        text: \"let\"\n                                    ),\n                                ]\n                            ),\n                            Note(\n                                text: \"error1_note2\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Skipped, primary diagnostic has more than 1 note with fix-it.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 9),\n                                        end: .init(path: path, line: 1, column: 10),\n                                        text: \"22\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .warning,\n                        text: \"warning1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"warning1_note1\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Skipped, primary diagnostic has more than 1 note with fix-it.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 5),\n                                        end: .init(path: path, line: 1, column: 6),\n                                        text: \"y\"\n                                    ),\n                                ]\n                            ),\n                            // This separator note should not make a difference.\n                            Note(\n                                text: \"warning1_note2\",\n                                location: .init(path: path, line: 1, column: 1)\n                            ),\n                            Note(\n                                text: \"warning1_note3\",\n                                location: .init(path: path, line: 1, column: 1),\n                                fixIts: [\n                                    // Skipped, primary diagnostic has more than 1 note with fix-it.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 7),\n                                        end: .init(path: path, line: 1, column: 8),\n                                        text: \":\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testDuplicatePrimaryDiag() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = (1, 1)\", result: \"let x = (22, 13)\"),\n                summary: .init(numberOfFixItsApplied: 3, numberOfFilesChanged: 1),\n                diagnostics: [\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .warning,\n                        text: \"warning1\",\n                        location: .init(path: path, line: 1, column: 10),\n                        notes: [\n                            Note(\n                                text: \"warning1_note1\",\n                                location: .init(path: path, line: 1, column: 10),\n                                fixIts: [\n                                    // Applied.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 10),\n                                        end: .init(path: path, line: 1, column: 11),\n                                        text: \"22\"\n                                    ),\n                                ]\n                            ),\n                            Note(\n                                text: \"warning1_note2\",\n                                location: .init(path: path, line: 1, column: 5),\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        notes: [\n                            Note(\n                                text: \"error1_note1\",\n                                location: .init(path: path, line: 1, column: 5),\n                                fixIts: [\n                                    // Skipped, duplicate primary diagnostic.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 5),\n                                        end: .init(path: path, line: 1, column: 6),\n                                        text: \"y\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .warning,\n                        text: \"warning1\",\n                        location: .init(path: path, line: 1, column: 10),\n                        fixIts: [\n                            // Skipped, duplicate primary diagnostic.\n                            .init(\n                                start: .init(path: path, line: 1, column: 7),\n                                end: .init(path: path, line: 1, column: 8),\n                                text: \":\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 14),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 14),\n                                end: .init(path: path, line: 1, column: 14),\n                                text: \"3\"\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testDuplicateReplacementFixIts() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"let x = 22\"),\n                summary: .init(\n                    // 4 because skipped by SwiftIDEUtils.FixItApplier, not SwiftFixIt.\n                    numberOfFixItsApplied: 4,\n                    numberOfFilesChanged: 1\n                ),\n                diagnostics: [\n                    // On primary diagnostics.\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2\",\n                        location: .init(path: path, line: 1, column: 4),\n                        fixIts: [\n                            // Skipped.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 4),\n                                text: \"let\"\n                            ),\n                        ]\n                    ),\n                    // On notes.\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error3\",\n                        location: .init(path: path, line: 1, column: 9),\n                        notes: [\n                            Note(\n                                text: \"error3_note1\",\n                                location: .init(path: path, line: 1, column: 9),\n                                fixIts: [\n                                    // Applied.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 9),\n                                        end: .init(path: path, line: 1, column: 10),\n                                        text: \"22\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error4\",\n                        location: .init(path: path, line: 1, column: 9),\n                        notes: [\n                            Note(\n                                text: \"error4_note1\",\n                                location: .init(path: path, line: 1, column: 9),\n                                fixIts: [\n                                    // Skipped.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 9),\n                                        end: .init(path: path, line: 1, column: 10),\n                                        text: \"22\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testDuplicateInsertionFixIts() throws {\n        try testAPI1File { path in\n            .init(\n                edits: .init(input: \"var x = 1\", result: \"@W var yx = 21\"),\n                summary: .init(\n                    // 6 because skipped by SwiftIDEUtils.FixItApplier, not SwiftFixIt.\n                    numberOfFixItsApplied: 6,\n                    numberOfFilesChanged: 1\n                ),\n                diagnostics: [\n                    // Duplicate fix-it pairs:\n                    // - on primary + on primary.\n                    // - on note + on note.\n                    // - on primary + on note.\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1_fixit1\",\n                        location: .init(path: path, line: 1, column: 1),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 1),\n                                text: \"@W \"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2_fixit2\",\n                        location: .init(path: path, line: 1, column: 2),\n                        notes: [\n                            Note(\n                                text: \"error2_note1\",\n                                location: .init(path: path, line: 1, column: 9),\n                                fixIts: [\n                                    // Applied.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 9),\n                                        end: .init(path: path, line: 1, column: 9),\n                                        text: \"2\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error3_fixit1\",\n                        location: .init(path: path, line: 1, column: 3),\n                        fixIts: [\n                            // Skipped, duplicate insertion.\n                            .init(\n                                start: .init(path: path, line: 1, column: 1),\n                                end: .init(path: path, line: 1, column: 1),\n                                text: \"@W \"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error4_fixit3\",\n                        location: .init(path: path, line: 1, column: 4),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path, line: 1, column: 5),\n                                end: .init(path: path, line: 1, column: 5),\n                                text: \"y\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error5_fixit2\",\n                        location: .init(path: path, line: 1, column: 5),\n                        notes: [\n                            Note(\n                                text: \"error5_note1\",\n                                location: .init(path: path, line: 1, column: 9),\n                                fixIts: [\n                                    // Skipped, duplicate insertion.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 9),\n                                        end: .init(path: path, line: 1, column: 9),\n                                        text: \"2\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error6_fixit3\",\n                        location: .init(path: path, line: 1, column: 6),\n                        notes: [\n                            Note(\n                                text: \"error6_note1\",\n                                location: .init(path: path, line: 1, column: 5),\n                                fixIts: [\n                                    // Skipped, duplicate insertion.\n                                    .init(\n                                        start: .init(path: path, line: 1, column: 5),\n                                        end: .init(path: path, line: 1, column: 5),\n                                        text: \"y\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n\n    @Test\n    func testExcludedSourceDirectories() throws {\n        // Each generated file has a distinct parent directory.\n        try testAPI2Files { path1, path2 in\n            .init(\n                edits: (\n                    .init(input: \"var x = 1\", result: \"var x = 1\"),\n                    .init(input: \"var x = 1\", result: \"var y = 2\")\n                ),\n                summary: .init(\n                    // 6 because skipped by SwiftIDEUtils.FixItApplier, not SwiftFixIt.\n                    numberOfFixItsApplied: 2,\n                    numberOfFilesChanged: 1\n                ),\n                excludedSourceDirectories: [path1.parentDirectory],\n                diagnostics: [\n                    // path1.\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1_fixit1\",\n                        location: .init(path: path1, line: 1, column: 5),\n                        fixIts: [\n                            // Skipped, excluded directory.\n                            .init(\n                                start: .init(path: path1, line: 1, column: 5),\n                                end: .init(path: path1, line: 1, column: 6),\n                                text: \"y\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2_fixit2\",\n                        location: .init(path: path1, line: 1, column: 9),\n                        notes: [\n                            Note(\n                                text: \"error2_note1\",\n                                location: .init(path: path1, line: 1, column: 9),\n                                fixIts: [\n                                    // Skipped, excluded directory.\n                                    .init(\n                                        start: .init(path: path1, line: 1, column: 9),\n                                        end: .init(path: path1, line: 1, column: 10),\n                                        text: \"2\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                    // path2.\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error1_fixit1\",\n                        location: .init(path: path2, line: 1, column: 5),\n                        fixIts: [\n                            // Applied.\n                            .init(\n                                start: .init(path: path2, line: 1, column: 5),\n                                end: .init(path: path2, line: 1, column: 6),\n                                text: \"y\"\n                            ),\n                        ]\n                    ),\n                    PrimaryDiagnostic(\n                        level: .error,\n                        text: \"error2_fixit2\",\n                        location: .init(path: path2, line: 1, column: 9),\n                        notes: [\n                            Note(\n                                text: \"error2_note1\",\n                                location: .init(path: path2, line: 1, column: 9),\n                                fixIts: [\n                                    // Applied.\n                                    .init(\n                                        start: .init(path: path2, line: 1, column: 9),\n                                        end: .init(path: path2, line: 1, column: 10),\n                                        text: \"2\"\n                                    ),\n                                ]\n                            ),\n                        ]\n                    ),\n                ]\n            )\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftFixItTests/Utilities.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport struct Basics.AbsolutePath\nimport var Basics.localFileSystem\nimport struct Foundation.UUID\n@testable\nimport SwiftFixIt\nimport class SwiftSyntax.SourceLocationConverter\nimport Testing\nimport struct TSCUtility.SerializedDiagnostics\n\nstruct SourceLocation: AnySourceLocation {\n    var path: AbsolutePath\n    var line: UInt64\n    var column: UInt64\n    var offset: UInt64\n\n    var filename: String {\n        self.path.pathString\n    }\n\n    init(path: AbsolutePath, line: UInt64, column: UInt64) {\n        self.path = path\n        self.line = line\n        self.column = column\n        self.offset = 0\n    }\n\n    fileprivate mutating func computeOffset(\n        using converters: [AbsolutePath: SourceLocationConverter]\n    ) {\n        guard let converter = converters[self.path] else {\n            return\n        }\n        self.offset = UInt64(converter.position(ofLine: Int(self.line), column: Int(self.column)).utf8Offset)\n    }\n}\n\nstruct FixIt: AnyFixIt {\n    var start: SourceLocation\n    var end: SourceLocation\n    var text: String\n}\n\nprivate struct Diagnostic: AnyDiagnostic {\n    var level: SerializedDiagnostics.Diagnostic.Level\n    var text: String\n    var location: SourceLocation?\n    var category: String?\n    var categoryURL: String?\n    var flag: String?\n    var ranges: [(SourceLocation, SourceLocation)]\n    var fixIts: [FixIt]\n\n    fileprivate func withSourceLocationOffsets(\n        using converters: [AbsolutePath: SourceLocationConverter]\n    ) -> Self {\n        var copy = self\n\n        copy.location?.computeOffset(using: converters)\n        for i in self.ranges.indices {\n            copy.ranges[i].0.computeOffset(using: converters)\n            copy.ranges[i].1.computeOffset(using: converters)\n        }\n        for i in self.fixIts.indices {\n            copy.fixIts[i].start.computeOffset(using: converters)\n            copy.fixIts[i].end.computeOffset(using: converters)\n        }\n\n        return copy\n    }\n}\n\nstruct Note {\n    fileprivate var diagnostic: Diagnostic\n\n    init(\n        text: String,\n        location: SourceLocation?,\n        category: String? = nil,\n        categoryURL: String? = nil,\n        flag: String? = nil,\n        ranges: [(SourceLocation, SourceLocation)] = [],\n        fixIts: [FixIt] = [],\n    ) {\n        self.diagnostic = .init(\n            level: .note,\n            text: text,\n            location: location,\n            category: category,\n            categoryURL: categoryURL,\n            flag: flag,\n            ranges: ranges,\n            fixIts: fixIts,\n        )\n    }\n}\n\nstruct PrimaryDiagnostic {\n    enum Level {\n        case ignored, warning, error, fatal, remark\n    }\n\n    fileprivate var diagnostic: Diagnostic\n    let notes: [Note]\n\n    init(\n        level: Level,\n        text: String,\n        location: SourceLocation?,\n        category: String? = nil,\n        categoryURL: String? = nil,\n        flag: String? = nil,\n        ranges: [(SourceLocation, SourceLocation)] = [],\n        fixIts: [FixIt] = [],\n        notes: [Note] = [],\n    ) {\n        let level: SerializedDiagnostics.Diagnostic.Level = switch level {\n        case .ignored: .ignored\n        case .warning: .warning\n        case .error: .error\n        case .fatal: .fatal\n        case .remark: .remark\n        }\n        self.diagnostic = .init(\n            level: level,\n            text: text,\n            location: location,\n            category: category,\n            categoryURL: categoryURL,\n            flag: flag,\n            ranges: ranges,\n            fixIts: fixIts,\n        )\n        self.notes = notes\n    }\n}\n\nstruct SourceFileEdit {\n    let input: String\n    let result: String\n    fileprivate let locationInTest: Testing.SourceLocation\n\n    init(\n        input: String,\n        result: String,\n        locationInTest: Testing.SourceLocation = #_sourceLocation\n    ) {\n        self.input = input\n        self.result = result\n        self.locationInTest = locationInTest\n    }\n}\n\nstruct Summary {\n    let summary: SwiftFixIt.Summary\n    fileprivate let locationInTest: Testing.SourceLocation\n\n    init(\n        numberOfFixItsApplied: Int,\n        numberOfFilesChanged: Int,\n        locationInTest: Testing.SourceLocation = #_sourceLocation\n    ) {\n        self.summary = .init(numberOfFixItsApplied: numberOfFixItsApplied, numberOfFilesChanged: numberOfFilesChanged)\n        self.locationInTest = locationInTest\n    }\n}\n\nstruct TestCase<T> {\n    var edits: T\n    var summary: Summary\n    var excludedSourceDirectories: Set<AbsolutePath> = []\n    var diagnostics: [PrimaryDiagnostic]\n}\n\nextension Testing.Issue {\n    fileprivate static func record<T>(\n        title: String,\n        comparisonComponents components: T...,\n        sourceLocation: Testing.SourceLocation\n    ) {\n        let messageDelimiter = \"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\"\n        let componentSeparator = \"────────────────────────────────────────────\"\n\n        var message = \"\\n\\(messageDelimiter)\\n\\(title)\\n\\(messageDelimiter)\\n\"\n        for component in components {\n            message += \"\\(component)\\n\"\n            break\n        }\n        for component in components.dropFirst() {\n            message += \"\\(componentSeparator)\\n\\(component)\\n\"\n        }\n        message += messageDelimiter\n\n        Issue.record(.init(rawValue: message), sourceLocation: sourceLocation)\n    }\n}\n\nprivate func _testAPI(\n    _ sourceFilePathsAndEdits: [(AbsolutePath, SourceFileEdit)],\n    _ expectedSummary: Summary,\n    _ diagnostics: [PrimaryDiagnostic],\n    _ categories: Set<String>,\n    _ excludedSourceDirectories: Set<AbsolutePath>,\n) throws {\n    for (path, edit) in sourceFilePathsAndEdits {\n        try localFileSystem.writeFileContents(path, string: edit.input)\n    }\n\n    let flatDiagnostics: [Diagnostic]\n    do {\n        let converters = Dictionary(uniqueKeysWithValues: sourceFilePathsAndEdits.map { path, edit in\n            (path, SourceLocationConverter(file: path.pathString, source: edit.input))\n        })\n\n        flatDiagnostics = diagnostics.reduce(into: Array()) { partialResult, primaryDiagnostic in\n            partialResult.append(primaryDiagnostic.diagnostic.withSourceLocationOffsets(using: converters))\n            for note in primaryDiagnostic.notes {\n                partialResult.append(note.diagnostic.withSourceLocationOffsets(using: converters))\n            }\n        }\n    }\n\n    let swiftFixIt = try SwiftFixIt(\n        diagnostics: flatDiagnostics,\n        categories: categories,\n        excludedSourceDirectories: excludedSourceDirectories,\n        fileSystem: localFileSystem\n    )\n    let actualSummary = try swiftFixIt.applyFixIts()\n\n    for (i, (path, edit)) in sourceFilePathsAndEdits.enumerated() {\n        let actualContents = try localFileSystem.readFileContents(path) as String\n        let expectedContents = edit.result\n        let originalContents = edit.input\n\n        if expectedContents != actualContents {\n            Issue.record(\n                title: \"File #\\(i + 1) (original/expected/actual contents)\",\n                comparisonComponents: originalContents, expectedContents, actualContents,\n                sourceLocation: edit.locationInTest\n            )\n        }\n    }\n\n    if expectedSummary.summary != actualSummary {\n        Issue.record(\n            title: \"Expected/actual change summaries\",\n            comparisonComponents: expectedSummary.summary, actualSummary,\n            sourceLocation: expectedSummary.locationInTest\n        )\n    }\n}\n\n// Cannot use variadic generics: crashes.\nfunc testAPI1File(\n    function: StaticString = #function,\n    categories: Set<String> = [],\n    _ getTestCase: (AbsolutePath) -> TestCase<SourceFileEdit>\n) throws {\n    try testWithTemporaryDirectory(function: function) { fixturePath in\n        let sourceFilePath = fixturePath.appending(\"file.swift\")\n\n        let testCase = getTestCase(sourceFilePath)\n\n        try _testAPI(\n            [(sourceFilePath, testCase.edits)],\n            testCase.summary,\n            testCase.diagnostics,\n            categories,\n            testCase.excludedSourceDirectories,\n        )\n    }\n}\n\nfunc testAPI2Files(\n    function: StaticString = #function,\n    categories: Set<String> = [],\n    _ getTestCase: (AbsolutePath, AbsolutePath) -> TestCase<(SourceFileEdit, SourceFileEdit)>,\n) throws {\n    try testWithTemporaryDirectory(function: function) { fixturePath in\n        // Create each file in a separate subdirectory so that we can test\n        // directory exclusion.\n        let sourceFilePath1 = fixturePath.appending(components: [UUID().uuidString, \"file.swift\"])\n        let sourceFilePath2 = fixturePath.appending(components: [UUID().uuidString, \"file.swift\"])\n\n        let testCase = getTestCase(sourceFilePath1, sourceFilePath2)\n\n        try _testAPI(\n            [(sourceFilePath1, testCase.edits.0), (sourceFilePath2, testCase.edits.1)],\n            testCase.summary,\n            testCase.diagnostics,\n            categories,\n            testCase.excludedSourceDirectories,\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/SwiftPMBuildServerTests/BuildServerTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n#if canImport(LanguageServerProtocolTransport)\nimport Basics\nimport Foundation\nimport PackageModel\nimport BuildServerProtocol\nimport LanguageServerProtocol\nimport LanguageServerProtocolTransport\nimport SwiftPMBuildServer\nimport _InternalTestSupport\nimport Testing\n\nfinal fileprivate class NotificationCollectingMessageHandler: MessageHandler {\n    func handle(_ notification: some NotificationType) {}\n    func handle<Request>(_ request: Request, id: RequestID, reply: @escaping @Sendable (LSPResult<Request.Response>) -> Void) where Request : RequestType {}\n}\n\nfileprivate func withSwiftPMBSP(fixtureName: String, extraBSPArgs: [String] = [], body: (Connection, NotificationCollectingMessageHandler, AbsolutePath) async throws -> Void) async throws {\n    await withKnownIssue(\"Tests occasionally fail to load build description in CI\", isIntermittent: true) {\n        try await fixture(name: fixtureName) { fixture in\n            let inPipe = Pipe()\n            let outPipe = Pipe()\n            let connection = JSONRPCConnection(\n                name: \"bsp-connection\",\n                protocol: MessageRegistry.bspProtocol,\n                receiveFD: inPipe.fileHandleForReading,\n                sendFD: outPipe.fileHandleForWriting\n            )\n            defer {\n                connection.close()\n            }\n            let bspProcess = Process()\n            bspProcess.standardOutputPipe = inPipe\n            bspProcess.standardInput = outPipe\n            let execPath = SwiftPM.xctestBinaryPath(for: \"swift-package\").pathString\n            bspProcess.executableURL = URL(filePath: execPath)\n            bspProcess.arguments = [\"--package-path\", fixture.pathString] + [\"experimental-build-server\", \"--build-system\", \"swiftbuild\"] + extraBSPArgs\n            async let terminationPromise: Void = try await bspProcess.run()\n            let notificationCollector = NotificationCollectingMessageHandler()\n            connection.start(receiveHandler: notificationCollector)\n            _ = try await connection.send(\n                InitializeBuildRequest(\n                    displayName: \"test-bsp-client\",\n                    version: \"1.0.0\",\n                    bspVersion: \"2.2.0\",\n                    rootUri: URI(URL(filePath: fixture.pathString)),\n                    capabilities: .init(languageIds: [.swift, .c, .objective_c, .cpp, .objective_cpp])\n                )\n            )\n            connection.send(OnBuildInitializedNotification())\n            _ = try await connection.send(WorkspaceWaitForBuildSystemUpdatesRequest())\n            try await body(connection, notificationCollector, fixture)\n            _ = try await connection.send(BuildShutdownRequest())\n            connection.send(OnBuildExitNotification())\n            try await terminationPromise\n        }\n    }\n}\n\n@Suite(\n    .disabled(if: ProcessInfo.hostOperatingSystem == .windows, \"This hangs intermittently on Windows in CI using the native build system\")\n)\nstruct SwiftPMBuildServerTests {\n    @Test\n    func lifecycleBasics() async throws {\n        try await withSwiftPMBSP(fixtureName: \"Miscellaneous/Simple\") { _, _, _ in\n            // Do nothing, but ensure the surrounding initialization and shutdown complete successfully.\n        }\n    }\n\n    @Test\n    func buildTargetsListBasics() async throws {\n        try await withSwiftPMBSP(fixtureName: \"Miscellaneous/Simple\") { connection, _, _ in\n            let response = try await connection.send(WorkspaceBuildTargetsRequest())\n            #expect(response.targets.count == 3)\n            #expect(response.targets.map(\\.displayName).sorted() == [\"Foo\", \"Foo-product\", \"Package Manifest\"])\n        }\n    }\n\n    @Test\n    func sourcesItemsBasics() async throws {\n        try await withSwiftPMBSP(fixtureName: \"Miscellaneous/Simple\") { connection, _, _ in\n            let targetResponse = try await connection.send(WorkspaceBuildTargetsRequest())\n            #expect(targetResponse.targets.count == 3)\n            #expect(targetResponse.targets.map(\\.displayName).sorted() == [\"Foo\", \"Foo-product\", \"Package Manifest\"])\n\n            let fooID = try #require(targetResponse.targets.first(where: { $0.displayName == \"Foo\" })).id\n            let sourcesResponse = try await connection.send(BuildTargetSourcesRequest(targets: [fooID]))\n            let item = try #require(sourcesResponse.items.only?.sources.only)\n            #expect(item.kind == .file)\n            #expect(item.uri.fileURL?.lastPathComponent == \"Foo.swift\")\n        }\n    }\n\n    @Test\n    func compilerArgsBasics() async throws {\n        try await withSwiftPMBSP(fixtureName: \"Miscellaneous/Simple\") { connection, _, _ in\n            let targetResponse = try await connection.send(WorkspaceBuildTargetsRequest())\n            #expect(targetResponse.targets.count == 3)\n            #expect(targetResponse.targets.map(\\.displayName).sorted() == [\"Foo\", \"Foo-product\", \"Package Manifest\"])\n\n            let fooID = try #require(targetResponse.targets.first(where: { $0.displayName == \"Foo\" })).id\n            let sourcesResponse = try await connection.send(BuildTargetSourcesRequest(targets: [fooID]))\n            let item = try #require(sourcesResponse.items.only?.sources.only)\n            #expect(item.kind == .file)\n            #expect(item.uri.fileURL?.lastPathComponent == \"Foo.swift\")\n\n            _ = try await connection.send(BuildTargetPrepareRequest(targets: [fooID]))\n\n            let settingsResponse = try #require(try await connection.send(TextDocumentSourceKitOptionsRequest(textDocument: TextDocumentIdentifier(item.uri), target: fooID, language: .swift)))\n            #expect(settingsResponse.compilerArguments.contains([\"-module-name\", \"Foo\"]))\n            try await AsyncProcess.checkNonZeroExit(arguments: [UserToolchain.default.swiftCompilerPath.pathString, \"-typecheck\"] + settingsResponse.compilerArguments)\n        }\n    }\n\n    @Test\n    func packageReloadBasics() async throws {\n        try await withSwiftPMBSP(fixtureName: \"Miscellaneous/Simple\") { connection, _, fixturePath in\n            let targetResponse = try await connection.send(WorkspaceBuildTargetsRequest())\n            #expect(targetResponse.targets.count == 3)\n            #expect(targetResponse.targets.map(\\.displayName).sorted() == [\"Foo\", \"Foo-product\", \"Package Manifest\"])\n\n            let fooID = try #require(targetResponse.targets.first(where: { $0.displayName == \"Foo\" })).id\n            let sourcesResponse = try await connection.send(BuildTargetSourcesRequest(targets: [fooID]))\n            let sourcesItem = try #require(sourcesResponse.items.only)\n            #expect(sourcesItem.sources.count == 1)\n            #expect(sourcesItem.sources.map(\\.uri.fileURL?.lastPathComponent).sorted() == [\"Foo.swift\"])\n\n            try localFileSystem.writeFileContents(fixturePath.appending(component: \"Bar.swift\"), body: {\n                $0.write(\"public let baz = \\\"hello\\\"\")\n            })\n\n            connection.send(OnWatchedFilesDidChangeNotification(changes: [\n                .init(uri: .init(.init(filePath: fixturePath.appending(component: \"Bar.swift\").pathString)), type: .created)\n            ]))\n            _ = try await connection.send(WorkspaceWaitForBuildSystemUpdatesRequest())\n\n            let updatedSourcesResponse = try await connection.send(BuildTargetSourcesRequest(targets: [fooID]))\n            let updatedSourcesItem = try #require(updatedSourcesResponse.items.only)\n            #expect(updatedSourcesItem.sources.count == 2)\n            #expect(updatedSourcesItem.sources.map(\\.uri.fileURL?.lastPathComponent).sorted() == [\"Bar.swift\", \"Foo.swift\"])\n        }\n    }\n\n    @Test\n    func compilerArgsFromUserInitiatedBuild() async throws {\n        try await withSwiftPMBSP(\n            fixtureName: \"Miscellaneous/Simple\",\n            extraBSPArgs: [\"--experimental-skip-acquiring-lock\"]\n        ) { connection, _, fixturePath in\n            // Populate the build folder as we would in a user-initiated build\n            try await SwiftPM.Build.execute([\"--build-system\", \"swiftbuild\"], packagePath: fixturePath)\n\n            let targetResponse = try await connection.send(WorkspaceBuildTargetsRequest())\n            #expect(targetResponse.targets.count == 3)\n            #expect(targetResponse.targets.map(\\.displayName).sorted() == [\"Foo\", \"Foo-product\", \"Package Manifest\"])\n\n            let fooID = try #require(targetResponse.targets.first(where: { $0.displayName == \"Foo\" })).id\n            let sourcesResponse = try await connection.send(BuildTargetSourcesRequest(targets: [fooID]))\n            let item = try #require(sourcesResponse.items.only?.sources.only)\n            #expect(item.kind == .file)\n            #expect(item.uri.fileURL?.lastPathComponent == \"Foo.swift\")\n\n            let settingsResponse = try #require(try await connection.send(TextDocumentSourceKitOptionsRequest(textDocument: TextDocumentIdentifier(item.uri), target: fooID, language: .swift)))\n            #expect(settingsResponse.compilerArguments.contains([\"-module-name\", \"Foo\"]))\n            try await AsyncProcess.checkNonZeroExit(arguments: [UserToolchain.default.swiftCompilerPath.pathString, \"-typecheck\"] + settingsResponse.compilerArguments)\n        }\n    }\n\n    @Test\n    func manifestArgs() async throws {\n        try await withSwiftPMBSP(fixtureName: \"Miscellaneous/VersionSpecificManifest\") { connection, _, _ in\n            let targetResponse = try await connection.send(WorkspaceBuildTargetsRequest())\n            #expect(targetResponse.targets.count == 3)\n            #expect(targetResponse.targets.map(\\.displayName).sorted() == [\"Foo\", \"Foo-product\", \"Package Manifest\"])\n\n            let manifestTarget = try #require(targetResponse.targets.first(where: { $0.displayName == \"Package Manifest\" }))\n            #expect(manifestTarget.tags.contains(.notBuildable))\n            let manifestID = manifestTarget.id\n            let sourcesResponse = try await connection.send(BuildTargetSourcesRequest(targets: [manifestID]))\n            let manifestItems = try #require(sourcesResponse.items.only?.sources)\n            #expect(manifestItems.map(\\.uri.fileURL?.lastPathComponent).sorted() == [\"Package.swift\", \"Package@swift-5.0.swift\"])\n            for item in manifestItems {\n                let settingsResponse = try #require(try await connection.send(TextDocumentSourceKitOptionsRequest(textDocument: TextDocumentIdentifier(item.uri), target: manifestID, language: .swift)))\n                try await AsyncProcess.checkNonZeroExit(arguments: [UserToolchain.default.swiftCompilerPath.pathString, \"-typecheck\"] + settingsResponse.compilerArguments)\n            }\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "Tests/WorkspaceTests/AuthorizationProviderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\n@testable import Basics\nimport _InternalTestSupport\nimport Workspace\nimport Testing\n\nfileprivate struct AuthorizationProviderTests {\n    @Test\n    func netrcAuthorizationProviders() throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // custom .netrc file\n        do {\n            let fileSystem: FileSystem = InMemoryFileSystem()\n\n            let customPath = try fileSystem.homeDirectory.appending(components: UUID().uuidString, \"custom-netrc-file\")\n            try fileSystem.createDirectory(customPath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(\n                customPath,\n                string: \"machine mymachine.labkey.org login custom@labkey.org password custom\"\n            )\n\n            let configuration = Workspace.Configuration.Authorization(netrc: .custom(customPath), keychain: .disabled)\n            let authorizationProvider = try configuration.makeAuthorizationProvider(fileSystem: fileSystem, observabilityScope: observability.topScope) as? CompositeAuthorizationProvider\n            let netrcProviders = try #require(authorizationProvider?.providers.compactMap { $0 as? NetrcAuthorizationProvider })\n\n            let expectedNetrcProvider = try resolveSymlinks(customPath)\n            #expect(netrcProviders.count == 1)\n            #expect(try netrcProviders.first.map { try resolveSymlinks($0.path) } == expectedNetrcProvider)\n\n            let auth = try #require(authorizationProvider?.authentication(for: \"https://mymachine.labkey.org\"))\n            #expect(auth.user == \"custom@labkey.org\")\n            #expect(auth.password == \"custom\")\n\n            // delete it\n            try fileSystem.removeFileTree(customPath)\n            #expect(throws: StringError(\"Did not find netrc file at \\(customPath).\")) {\n                try configuration.makeAuthorizationProvider(fileSystem: fileSystem, observabilityScope: observability.topScope)\n            }\n        }\n\n        // user .netrc file\n        do {\n            let fileSystem = InMemoryFileSystem()\n\n            let userPath = try fileSystem.homeDirectory.appending(\".netrc\")\n            try fileSystem.createDirectory(userPath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(\n                userPath,\n                string: \"machine mymachine.labkey.org login user@labkey.org password user\"\n            )\n\n            let configuration = Workspace.Configuration.Authorization(netrc: .user, keychain: .disabled)\n            let authorizationProvider = try configuration.makeAuthorizationProvider(fileSystem: fileSystem, observabilityScope: observability.topScope) as? CompositeAuthorizationProvider\n            let netrcProviders = try #require(authorizationProvider?.providers.compactMap { $0 as? NetrcAuthorizationProvider })\n\n            let expectedNetrcProvider = try resolveSymlinks(userPath)\n            #expect(netrcProviders.count == 1)\n            #expect(try netrcProviders.first.map { try resolveSymlinks($0.path) } == expectedNetrcProvider)\n\n            let auth = try #require(authorizationProvider?.authentication(for: \"https://mymachine.labkey.org\"))\n            #expect(auth.user == \"user@labkey.org\")\n            #expect(auth.password == \"user\")\n\n            // delete it\n            do {\n                try fileSystem.removeFileTree(userPath)\n                let authorizationProvider = try configuration.makeAuthorizationProvider(fileSystem: fileSystem, observabilityScope: observability.topScope) as? CompositeAuthorizationProvider\n                #expect(authorizationProvider == nil)\n            }\n        }\n    }\n\n    @Test\n    func registryNetrcAuthorizationProviders() throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // custom .netrc file\n\n        do {\n            let fileSystem: FileSystem = InMemoryFileSystem()\n\n            let customPath = try fileSystem.homeDirectory.appending(components: UUID().uuidString, \"custom-netrc-file\")\n            try fileSystem.createDirectory(customPath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(\n                customPath,\n                string: \"machine mymachine.labkey.org login custom@labkey.org password custom\"\n            )\n\n            let configuration = Workspace.Configuration.Authorization(netrc: .custom(customPath), keychain: .disabled)\n            let netrcProvider = try configuration.makeRegistryAuthorizationProvider(fileSystem: fileSystem, observabilityScope: observability.topScope) as? NetrcAuthorizationProvider\n\n            let expectedNetrcProvider = try resolveSymlinks(customPath)\n            #expect(netrcProvider != nil)\n            #expect(try netrcProvider.map { try resolveSymlinks($0.path) } == expectedNetrcProvider)\n\n            let auth = try #require(netrcProvider?.authentication(for: \"https://mymachine.labkey.org\"))\n            #expect(auth.user == \"custom@labkey.org\")\n            #expect(auth.password == \"custom\")\n\n            // delete it\n            try fileSystem.removeFileTree(customPath)\n            #expect(throws: StringError(\"did not find netrc file at \\(customPath)\")) {\n                try configuration.makeRegistryAuthorizationProvider(fileSystem: fileSystem, observabilityScope: observability.topScope)\n            }\n        }\n\n        // user .netrc file\n\n        do {\n            let fileSystem = InMemoryFileSystem()\n\n            let userPath = try fileSystem.homeDirectory.appending(\".netrc\")\n            try fileSystem.createDirectory(userPath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(\n                userPath,\n                string: \"machine mymachine.labkey.org login user@labkey.org password user\"\n            )\n\n            let configuration = Workspace.Configuration.Authorization(netrc: .user, keychain: .disabled)\n            let netrcProvider = try configuration.makeRegistryAuthorizationProvider(fileSystem: fileSystem, observabilityScope: observability.topScope) as? NetrcAuthorizationProvider\n\n            let expectedNetrcProvider = try resolveSymlinks(userPath)\n            #expect(netrcProvider != nil)\n            #expect(try netrcProvider.map { try resolveSymlinks($0.path) } == expectedNetrcProvider)\n\n            let auth = try #require(netrcProvider?.authentication(for: \"https://mymachine.labkey.org\"))\n            #expect(auth.user == \"user@labkey.org\")\n            #expect(auth.password == \"user\")\n\n            // delete it\n            do {\n                try fileSystem.removeFileTree(userPath)\n                let authorizationProviderOpt =\n                    try configuration.makeRegistryAuthorizationProvider(\n                        fileSystem: fileSystem,\n                        observabilityScope: observability.topScope,\n                    ) as? NetrcAuthorizationProvider\n                // Even if user .netrc file doesn't exist, the provider will be non-nil but contain no data.\n                let expectedAuthorizationProvider = try resolveSymlinks(userPath)\n                let authorizationProvider: NetrcAuthorizationProvider = try #require(\n                    authorizationProviderOpt)\n                #expect(authorizationProvider.path == expectedAuthorizationProvider)\n                #expect(authorizationProvider.machines.isEmpty)\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/InitTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _InternalTestSupport\nimport PackageModel\nimport Workspace\nimport Testing\n\nimport struct SPMBuildCore.BuildSystemProvider\n\n@Suite(\n    .tags(\n        .FunctionalArea.Workspace,\n    ),\n)\nstruct InitTests {\n\n    // MARK: TSCBasic package creation for each package type.\n\n    @Test(\n        .tags(\n            .TestSize.medium,\n        ),\n    )\n    func initPackageEmpty() throws {\n        try withTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"Foo\")\n            let name = path.basename\n            try fs.createDirectory(path)\n\n            // Create the package\n            let initPackage = try InitPackage(\n                name: name,\n                packageType: .empty,\n                destinationPath: path,\n                fileSystem: localFileSystem\n            )\n            var progressMessages = [String]()\n            initPackage.progressReporter = { message in\n                progressMessages.append(message)\n            }\n            try initPackage.writePackageStructure()\n\n            // Not picky about the specific progress messages, just checking that we got some.\n            #expect(progressMessages.count > 0)\n\n            // Verify basic file system content that we expect in the package\n            let manifest = path.appending(\"Package.swift\")\n            try requireFileExists(at: manifest)\n\n            let manifestContents: String = try localFileSystem.readFileContents(manifest)\n            let version = InitPackage.newPackageToolsVersion\n            let versionSpecifier = \"\\(version.major).\\(version.minor)\"\n            #expect(manifestContents.hasPrefix(\"// swift-tools-version:\\(version < .v5_4 ? \"\" : \" \")\\(versionSpecifier)\\n\"))\n            #expect(manifestContents.contains(packageWithNameOnly(named: name)))\n        }\n    }\n\n    @Suite(\n        .serialized, // Crash occurred when executed in parallel.  Needs investigation\n        .tags(\n            .TestSize.large,\n        ),\n    )\n    struct InitTestsThatPerformABuild {\n        @Test(\n            .tags(\n                .Feature.Command.Build,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initPackageExecutable(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws  {\n            let configuration = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                let name = path.basename\n                try fs.createDirectory(path)\n\n                // Create the package\n                let initPackage = try InitPackage(\n                    name: name,\n                    packageType: .executable,\n                    destinationPath: path,\n                    fileSystem: localFileSystem\n                )\n                var progressMessages = [String]()\n                initPackage.progressReporter = { message in\n                    progressMessages.append(message)\n                }\n                try initPackage.writePackageStructure()\n\n                // Not picky about the specific progress messages, just checking that we got some.\n                #expect(progressMessages.count > 0)\n\n                // Verify basic file system content that we expect in the package\n                let manifest = path.appending(\"Package.swift\")\n                try requireFileExists(at: manifest)\n\n                let manifestContents: String = try localFileSystem.readFileContents(manifest)\n                let version = InitPackage.newPackageToolsVersion\n                let versionSpecifier = \"\\(version.major).\\(version.minor)\"\n                #expect(manifestContents.hasPrefix(\"// swift-tools-version:\\(version < .v5_4 ? \"\" : \" \")\\(versionSpecifier)\\n\"))\n\n                #expect(try fs.getDirectoryContents(path.appending(\"Sources\").appending(\"Foo\")) == [\"Foo.swift\"])\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let binPath = try path.appending(components: buildSystem.binPath(for: configuration))\n                expectFileExists(at: binPath.appending(executableName(\"Foo\")))\n                let expectedOutput: [String]\n                switch buildSystem {\n                    case .native:\n                    expectedOutput = [\"Modules\", \"Foo.swiftmodule\"]\n                    case .swiftbuild:\n                    expectedOutput = [\"Foo.swiftmodule\"]\n                    case .xcode:\n                    expectedOutput = [\"Foo.swiftmodule\"]\n                    Issue.record(\"Test expectation is not implemented\")\n                }\n                let expectedFile = binPath.appending(components: expectedOutput)\n\n                expectFileExists(at: expectedFile)\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Build,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initPackageExecutableCalledMain(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let configuration = BuildConfiguration.debug\n            try await testWithTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"main\")\n                let name = path.basename\n                try fs.createDirectory(path)\n\n                // Create the package\n                let initPackage = try InitPackage(\n                    name: name,\n                    packageType: .executable,\n                    destinationPath: path,\n                    fileSystem: localFileSystem\n                )\n                try initPackage.writePackageStructure()\n\n                let contents = try fs.getDirectoryContents(path.appending(\"Sources\").appending(\"main\"))\n                try #require(contents == [\"MainEntrypoint.swift\"])\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Build,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initPackageLibraryWithXCTestOnly(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let configuration = BuildConfiguration.debug\n            try await withTemporaryDirectory(removeTreeOnDeinit: true) { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                let name = path.basename\n                try fs.createDirectory(path)\n\n                // Create the package\n                let initPackage = try InitPackage(\n                    name: name,\n                    packageType: .library,\n                    supportedTestingLibraries: [.xctest],\n                    destinationPath: path,\n                    fileSystem: localFileSystem\n                )\n                var progressMessages = [String]()\n                initPackage.progressReporter = { message in\n                    progressMessages.append(message)\n                }\n                try initPackage.writePackageStructure()\n\n                // Not picky about the specific progress messages, just checking that we got some.\n                #expect(progressMessages.count > 0)\n\n                // Verify basic file system content that we expect in the package\n                let manifest = path.appending(\"Package.swift\")\n                try requireFileExists(at:  manifest)\n                let manifestContents: String = try localFileSystem.readFileContents(manifest)\n                let version = InitPackage.newPackageToolsVersion\n                let versionSpecifier = \"\\(version.major).\\(version.minor)\"\n                #expect(manifestContents.hasPrefix(\"// swift-tools-version:\\(version < .v5_4 ? \"\" : \" \")\\(versionSpecifier)\\n\"))\n\n                #expect(try fs.getDirectoryContents(path.appending(\"Sources\").appending(\"Foo\")) == [\"Foo.swift\"])\n\n                let tests = path.appending(\"Tests\")\n                #expect(try fs.getDirectoryContents(tests).sorted() == [\"FooTests\"])\n\n                let testFile = tests.appending(\"FooTests\").appending(\"FooTests.swift\")\n                let testFileContents: String = try localFileSystem.readFileContents(testFile)\n                #expect(testFileContents.hasPrefix(\"import XCTest\"), \"\"\"\n                            Validates formatting of XCTest source file, in particular that it does not contain leading whitespace:\n                            \\(testFileContents)\n                            \"\"\")\n                #expect(testFileContents.contains(\"func testExample() throws\"))\n\n                // Try building it\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let expectedOutput: [String]\n                switch buildSystem {\n                    case .native:\n                    expectedOutput = [\"Modules\", \"Foo.swiftmodule\"]\n                    case .swiftbuild:\n                    expectedOutput = [\"Foo.swiftmodule\"]\n                    case .xcode:\n                    expectedOutput = [\"Foo.swiftmodule\"]\n                    Issue.record(\"Test expectation is not implemented\")\n                }\n                let expectedFile = try path.appending(components: buildSystem.binPath(for: configuration) + expectedOutput)\n                expectFileExists(at: expectedFile)\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Build,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initPackageLibraryWithSwiftTestingOnly(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws  {\n            let configuration = BuildConfiguration.debug\n            try withTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                let name = path.basename\n                try fs.createDirectory(path)\n\n                // Create the package\n                let initPackage = try InitPackage(\n                    name: name,\n                    packageType: .library,\n                    supportedTestingLibraries: [.swiftTesting],\n                    destinationPath: path,\n                    fileSystem: localFileSystem\n                )\n                try initPackage.writePackageStructure()\n\n                // Verify basic file system content that we expect in the package\n                let manifest = path.appending(\"Package.swift\")\n                try requireFileExists(at: manifest)\n\n                let testFile = path.appending(\"Tests\").appending(\"FooTests\").appending(\"FooTests.swift\")\n                let testFileContents: String = try localFileSystem.readFileContents(testFile)\n                #expect(testFileContents.contains(#\"import Testing\"#))\n                #expect(!testFileContents.contains(#\"import XCTest\"#))\n                #expect(testFileContents.contains(#\"@Test func example() async throws\"#))\n                #expect(!testFileContents.contains(\"func testExample() throws\"))\n\n    #if canImport(TestingDisabled)\n                // Try building it\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let triple = try UserToolchain.default.targetTriple\n                expectFileExists(at: path.appending(components: buildSystem.binPath(for: configuration) + [\"Modules\", \"Foo.swiftmodule\"]))\n    #endif\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Build,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initPackageLibraryWithBothSwiftTestingAndXCTest(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws  {\n            let configuration = BuildConfiguration.debug\n            try withTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                let name = path.basename\n                try fs.createDirectory(path)\n\n                // Create the package\n                let initPackage = try InitPackage(\n                    name: name,\n                    packageType: .library,\n                    supportedTestingLibraries: [.swiftTesting, .xctest],\n                    destinationPath: path,\n                    fileSystem: localFileSystem\n                )\n                try initPackage.writePackageStructure()\n\n                // Verify basic file system content that we expect in the package\n                let manifest = path.appending(\"Package.swift\")\n                try requireFileExists(at: manifest)\n\n                let testFile = path.appending(\"Tests\").appending(\"FooTests\").appending(\"FooTests.swift\")\n                let testFileContents: String = try localFileSystem.readFileContents(testFile)\n                #expect(testFileContents.contains(#\"import Testing\"#))\n                #expect(testFileContents.contains(#\"import XCTest\"#))\n                #expect(testFileContents.contains(#\"@Test func example() async throws\"#))\n                #expect(testFileContents.contains(\"func testExample() throws\"))\n\n    #if canImport(TestingDisabled)\n                // Try building it\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let triple = try UserToolchain.default.targetTriple\n                expectFileExists(at: path.appending(components: buildSystem.binPath(for: configuration) + [\"Modules\", \"Foo.swiftmodule\"]))\n    #endif\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Build,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initPackageLibraryWithNoTests(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let configuration = BuildConfiguration.debug\n            try withTemporaryDirectory { tmpPath in\n                let fs = localFileSystem\n                let path = tmpPath.appending(\"Foo\")\n                let name = path.basename\n                try fs.createDirectory(path)\n\n                // Create the package\n                let initPackage = try InitPackage(\n                    name: name,\n                    packageType: .library,\n                    supportedTestingLibraries: [],\n                    destinationPath: path,\n                    fileSystem: localFileSystem\n                )\n                try initPackage.writePackageStructure()\n\n                // Verify basic file system content that we expect in the package\n                let manifest = path.appending(\"Package.swift\")\n                try requireFileExists(at: manifest)\n\n                let manifestContents: String = try localFileSystem.readFileContents(manifest)\n                #expect(!manifestContents.contains(#\".testTarget\"#))\n\n                expectFileDoesNotExists(at: path.appending(\"Tests\"))\n\n    #if canImport(TestingDisabled)\n                // Try building it\n                try await executeSwiftBuild(\n                    path,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n                let triple = try UserToolchain.default.targetTriple\n                expectFileExists(at: path.appending(components: \".build\", triple.platformBuildPathComponent, configuration.dirname, \"Modules\", \"Foo.swiftmodule\"))\n    #endif\n            }\n        }\n\n        // MARK: Special case testing\n\n        @Test(\n            .tags(\n                .Feature.Command.Build,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func initPackageNonc99Directory(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let configuration = BuildConfiguration.debug\n            try await withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in\n                expectDirectoryExists(at: tempDirPath)\n\n                // Create a directory with non c99name.\n                let packageRoot = tempDirPath.appending(\"some-package\")\n                let packageName = packageRoot.basename\n                try localFileSystem.createDirectory(packageRoot)\n                expectDirectoryExists(at: packageRoot)\n\n                // Create the package\n                let initPackage = try InitPackage(\n                    name: packageName,\n                    packageType: .library,\n                    destinationPath: packageRoot,\n                    fileSystem: localFileSystem\n                )\n                initPackage.progressReporter = { message in }\n                try initPackage.writePackageStructure()\n\n                // Try building it.\n                try await executeSwiftBuild(\n                    packageRoot,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n\n                let expectedFile: AbsolutePath\n                switch buildSystem {\n                    case .native:\n                    expectedFile = try packageRoot.appending(components: buildSystem.binPath(for: configuration) + [\"Modules\", \"some_package.swiftmodule\"])\n                    case .swiftbuild:\n                    expectedFile = try packageRoot.appending(components: buildSystem.binPath(for: configuration) + [ \"some_package.swiftmodule\"])\n                    case .xcode:\n                    expectedFile = try packageRoot.appending(components: buildSystem.binPath(for: configuration) + [ \"some_package.swiftmodule\"])\n                    Issue.record(\"Test expectation is not implemented\")\n                }\n\n                expectFileExists(at: expectedFile)\n            }\n        }\n\n        @Test(\n            .tags(\n                .Feature.Command.Build,\n            ),\n            arguments: SupportedBuildSystemOnAllPlatforms,\n        )\n        func nonC99NameExecutablePackage(\n            buildSystem: BuildSystemProvider.Kind,\n        ) async throws {\n            let configuration = BuildConfiguration.debug\n            try await withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in\n                expectDirectoryExists(at: tempDirPath)\n\n                let packageRoot = tempDirPath.appending(\"Foo\")\n                try localFileSystem.createDirectory(packageRoot)\n                expectDirectoryExists(at: packageRoot)\n\n                // Create package with non c99name.\n                let initPackage = try InitPackage(\n                    name: \"package-name\",\n                    packageType: .executable,\n                    destinationPath: packageRoot,\n                    fileSystem: localFileSystem\n                )\n                try initPackage.writePackageStructure()\n\n                try await executeSwiftBuild(\n                    packageRoot,\n                    configuration: configuration,\n                    buildSystem: buildSystem,\n                )\n            }\n        }\n\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium,\n        ),\n    )\n    func initPackageExecutableWithSwiftTesting() async throws {\n        try withTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"Foo\")\n            let name = path.basename\n            try fs.createDirectory(path)\n            // Create the package\n            let initPackage = try InitPackage(\n                name: name,\n                packageType: .executable,\n                supportedTestingLibraries: [.swiftTesting],\n                destinationPath: path,\n                fileSystem: localFileSystem\n            )\n\n            try initPackage.writePackageStructure()\n            // Verify basic file system content that we expect in the package\n            let manifest = path.appending(\"Package.swift\")\n            try requireFileExists(at: manifest)\n\n            let manifestContents: String = try localFileSystem.readFileContents(manifest)\n            #expect(manifestContents.contains(\".testTarget(\"))\n            let testFile = path.appending(\"Tests\").appending(\"FooTests\").appending(\"FooTests.swift\")\n            let testFileContents: String = try localFileSystem.readFileContents(testFile)\n            #expect(testFileContents.contains(#\"import Testing\"#))\n            #expect(!testFileContents.contains(#\"import XCTest\"#))\n            #expect(testFileContents.contains(#\"@Test func example() async throws\"#))\n            #expect(!testFileContents.contains(\"func testExample() throws\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium,\n        ),\n    )\n    func initPackageToolWithSwiftTesting() async throws {\n        try withTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"Foo\")\n            let name = path.basename\n            try fs.createDirectory(path)\n            // Create the package\n            let initPackage = try InitPackage(\n                name: name,\n                packageType: .tool,\n                supportedTestingLibraries: [.swiftTesting],\n                destinationPath: path,\n                fileSystem: localFileSystem\n            )\n\n            try initPackage.writePackageStructure()\n            // Verify basic file system content that we expect in the package\n            let manifest = path.appending(\"Package.swift\")\n            try requireFileExists(at: manifest)\n\n            let manifestContents: String = try localFileSystem.readFileContents(manifest)\n            #expect(manifestContents.contains(\".testTarget(\"))\n            let testFile = path.appending(\"Tests\").appending(\"FooTests\").appending(\"FooTests.swift\")\n            let testFileContents: String = try localFileSystem.readFileContents(testFile)\n            #expect(testFileContents.contains(#\"import Testing\"#))\n            #expect(!testFileContents.contains(#\"import XCTest\"#))\n            #expect(testFileContents.contains(#\"@Test func example() async throws\"#))\n            #expect(!testFileContents.contains(\"func testExample() throws\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium,\n        ),\n    )\n    func initPackageCommandPlugin() throws {\n        try withTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"MyCommandPlugin\")\n            let name = path.basename\n            try fs.createDirectory(path)\n\n            // Create the package\n            try InitPackage(\n                name: name,\n                packageType: .commandPlugin,\n                destinationPath: path,\n                fileSystem: localFileSystem\n            ).writePackageStructure()\n\n            // Verify basic file system content that we expect in the package\n            let manifest = path.appending(\"Package.swift\")\n            try requireFileExists(at: manifest)\n\n            let manifestContents: String = try localFileSystem.readFileContents(manifest)\n            #expect(manifestContents.contains(\".plugin(\") && manifestContents.contains(\"targets: [\\\"MyCommandPlugin\\\"]\"))\n            #expect(manifestContents.contains(\".plugin(\") &&\n                   manifestContents.contains(\"capability: .command(intent: .custom(\") &&\n                   manifestContents.contains(\"verb: \\\"MyCommandPlugin\\\"\"))\n\n            // Check basic content that we expect in the plugin source file\n            let source = path.appending(\"Plugins\", \"MyCommandPlugin.swift\")\n            expectFileExists(at: source)\n            let sourceContents: String = try localFileSystem.readFileContents(source)\n            #expect(sourceContents.contains(\"struct MyCommandPlugin: CommandPlugin\"))\n            #expect(sourceContents.contains(\"performCommand(context: PluginContext\"))\n            #expect(sourceContents.contains(\"import XcodeProjectPlugin\"))\n            #expect(sourceContents.contains(\"extension MyCommandPlugin: XcodeCommandPlugin\"))\n            #expect(sourceContents.contains(\"performCommand(context: XcodePluginContext\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium,\n        ),\n    )\n    func initPackageBuildToolPlugin() throws {\n        try withTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"MyBuildToolPlugin\")\n            let name = path.basename\n            try fs.createDirectory(path)\n\n            // Create the package\n            try InitPackage(\n                name: name,\n                packageType: .buildToolPlugin,\n                destinationPath: path,\n                fileSystem: localFileSystem\n            ).writePackageStructure()\n\n            // Verify basic file system content that we expect in the package\n            let manifest = path.appending(\"Package.swift\")\n            try requireFileExists(at: manifest)\n\n            let manifestContents: String = try localFileSystem.readFileContents(manifest)\n            #expect(manifestContents.contains(\".plugin(\") && manifestContents.contains(\"targets: [\\\"MyBuildToolPlugin\\\"]\"))\n            #expect(manifestContents.contains(\".plugin(\") && manifestContents.contains(\"capability: .buildTool()\"))\n\n            // Check basic content that we expect in the plugin source file\n            let source = path.appending(\"Plugins\", \"MyBuildToolPlugin.swift\")\n            expectFileExists(at: source)\n            let sourceContents: String = try localFileSystem.readFileContents(source)\n            #expect(sourceContents.contains(\"struct MyBuildToolPlugin: BuildToolPlugin\"))\n            #expect(sourceContents.contains(\"createBuildCommands(context: PluginContext\"))\n            #expect(sourceContents.contains(\"import XcodeProjectPlugin\"))\n            #expect(sourceContents.contains(\"extension MyBuildToolPlugin: XcodeBuildToolPlugin\"))\n            #expect(sourceContents.contains(\"createBuildCommands(context: XcodePluginContext\"))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium,\n        ),\n    )\n    func platforms() throws {\n        try withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in\n            var options = InitPackage.InitPackageOptions(packageType: .library, supportedTestingLibraries: [])\n            options.platforms = [\n                .init(platform: .macOS, version: PlatformVersion(\"10.15\")),\n                .init(platform: .iOS, version: PlatformVersion(\"12\")),\n                .init(platform: .watchOS, version: PlatformVersion(\"2.1\")),\n                .init(platform: .tvOS, version: PlatformVersion(\"999\")),\n            ]\n\n            let packageRoot = tempDirPath.appending(\"Foo\")\n            try localFileSystem.removeFileTree(packageRoot)\n            try localFileSystem.createDirectory(packageRoot)\n\n            let initPackage = try InitPackage(\n                name: \"Foo\",\n                options: options,\n                destinationPath: packageRoot,\n                installedSwiftPMConfiguration: .default,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n\n            let contents: String = try localFileSystem.readFileContents(packageRoot.appending(\"Package.swift\"))\n            #expect(contents.contains(#\"platforms: [.macOS(.v10_15), .iOS(.v12), .watchOS(\"2.1\"), .tvOS(\"999.0\")],\"#))\n        }\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium,\n        ),\n    )\n    func initPackageIncludesSwiftLanguageMode() throws {\n        try withTemporaryDirectory { tmpPath in\n            let fs = localFileSystem\n            let path = tmpPath.appending(\"testInitPackageIncludesSwiftLanguageMode\")\n            let name = path.basename\n            try fs.createDirectory(path)\n\n            // Create a library package\n            let initPackage = try InitPackage(\n                name: name,\n                packageType: .library,\n                supportedTestingLibraries: [],\n                destinationPath: path,\n                installedSwiftPMConfiguration: .default,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n\n            // Verify the manifest includes Swift language mode\n            let manifest = path.appending(\"Package.swift\")\n            let manifestContents: String = try localFileSystem.readFileContents(manifest)\n            #expect(manifestContents.contains(\"swiftLanguageModes: [.v6]\"))\n        }\n    }\n\n    private func packageWithNameOnly(named name: String) -> String {\n        return \"\"\"\n        let package = Package(\n            name: \"\\(name)\"\n        )\n        \"\"\"\n    }\n\n    private func packageWithNameAndDependencies(with name: String) -> String {\n        return \"\"\"\nlet package = Package(\n    name: \"\\(name)\",\n    dependencies: [\n        // Dependencies declare other packages that this package depends on.\n        // .package(url: /* package url */, from: \"1.0.0\"),\n    ]\n)\n\"\"\"\n    }\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/ManifestSourceGenerationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport _InternalTestSupport\nimport Workspace\nimport XCTest\n\nextension String {\n    fileprivate func nativePathString(escaped: Bool) -> String {\n#if _runtime(_ObjC)\n        return self\n#else\n        let fsr = self.fileSystemRepresentation\n        defer { fsr.deallocate() }\n        if escaped {\n            return String(cString: fsr).replacingOccurrences(of: \"\\\\\", with: \"\\\\\\\\\")\n        }\n        return String(cString: fsr)\n#endif\n    }\n}\n\nfinal class ManifestSourceGenerationTests: XCTestCase {\n    /// Private function that writes the contents of a package manifest to a temporary package directory and then loads it, then serializes the loaded manifest back out again and loads it once again, after which it compares that no information was lost. Return the source of the newly generated manifest.\n    @discardableResult\n    private func testManifestWritingRoundTrip(\n        manifestContents: String,\n        toolsVersion: ToolsVersion,\n        toolsVersionHeaderComment: String? = .none,\n        additionalImportModuleNames: [String] = [],\n        fs: FileSystem = localFileSystem,\n        file: StaticString = #file,\n        line: UInt = #line,\n    ) async throws -> String {\n        try await withTemporaryDirectory { packageDir in\n            let observability = ObservabilitySystem.makeForTesting()\n\n            // Write the original manifest file contents, and load it.\n            let manifestPath = packageDir.appending(component: Manifest.filename)\n            try fs.writeFileContents(manifestPath, string: manifestContents)\n            let manifestLoader = ManifestLoader(toolchain: try UserToolchain.default)\n            let identityResolver = DefaultIdentityResolver()\n            let dependencyMapper = DefaultDependencyMapper(identityResolver: identityResolver)\n            let manifest = try await manifestLoader.load(\n                manifestPath: manifestPath,\n                manifestToolsVersion: toolsVersion,\n                packageIdentity: .plain(\"Root\"),\n                packageKind: .root(packageDir),\n                packageLocation: packageDir.pathString,\n                packageVersion: nil,\n                identityResolver: identityResolver,\n                dependencyMapper: dependencyMapper,\n                fileSystem: fs,\n                observabilityScope: observability.topScope,\n                delegateQueue: .sharedConcurrent\n            )\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n\n            // Generate source code for the loaded manifest,\n            let newContents = try manifest.generateManifestFileContents(\n                packageDirectory: packageDir,\n                toolsVersionHeaderComment: toolsVersionHeaderComment,\n                additionalImportModuleNames: additionalImportModuleNames)\n\n            // Check that the tools version was serialized properly.\n            let versionSpacing = (toolsVersion >= .v5_4) ? \" \" : \"\"\n            XCTAssertMatch(newContents, .prefix(\"// swift-tools-version:\\(versionSpacing)\\(toolsVersion.major).\\(toolsVersion.minor)\"))\n\n            // Write out the generated manifest to replace the old manifest file contents, and load it again.\n            try fs.writeFileContents(manifestPath, string: newContents)\n            let newManifest = try await manifestLoader.load(\n                manifestPath: manifestPath,\n                manifestToolsVersion: toolsVersion,\n                packageIdentity: .plain(\"Root\"),\n                packageKind: .root(packageDir),\n                packageLocation: packageDir.pathString,\n                packageVersion: nil,\n                identityResolver: identityResolver,\n                dependencyMapper: dependencyMapper,\n                fileSystem: fs,\n                observabilityScope: observability.topScope,\n                delegateQueue: .sharedConcurrent\n            )\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n\n            // Check that all the relevant properties survived.\n            let failureDetails = \"\\n--- ORIGINAL MANIFEST CONTENTS ---\\n\" + manifestContents + \"\\n--- REWRITTEN MANIFEST CONTENTS ---\\n\" + newContents\n            XCTAssertEqual(newManifest.toolsVersion, manifest.toolsVersion, \"toolsVersion not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.displayName, manifest.displayName, \"displayName not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.defaultLocalization, manifest.defaultLocalization, \"defaultLocalization not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.platforms, manifest.platforms, \"platforms not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.pkgConfig, manifest.pkgConfig, \"pkgConfig not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.providers, manifest.providers, \"providers not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.products, manifest.products, \"products not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.traits, manifest.traits, \"traits not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.dependencies, manifest.dependencies, \"dependencies not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.targets, manifest.targets, \"targets not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.swiftLanguageVersions, manifest.swiftLanguageVersions, \"swiftLanguageVersions not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.cLanguageStandard, manifest.cLanguageStandard, \"cLanguageStandard not as expected\" + failureDetails, file: file, line: line)\n            XCTAssertEqual(newManifest.cxxLanguageStandard, manifest.cxxLanguageStandard, \"cxxLanguageStandard not as expected\" + failureDetails, file: file, line: line)\n\n            // Return the generated manifest so that the caller can do further testing on it.\n            return newContents\n        }\n    }\n\n    func testBasics() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.3\n            // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n            import PackageDescription\n\n            let package = Package(\n                name: \"MyPackage\",\n                platforms: [\n                    .macOS(.v10_14),\n                    .iOS(.v13)\n                ],\n                products: [\n                    // Products define the executables and libraries a package produces, and make them visible to other packages.\n                    .library(\n                        name: \"MyPackage\",\n                        targets: [\"MyPackage\"]),\n                ],\n                dependencies: [\n                    // Dependencies declare other packages that this package depends on.\n                    // .package(url: /* package url */, from: \"1.0.0\"),\n                ],\n                targets: [\n                    // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n                    // Targets can depend on other targets in this package, and on products in packages this package depends on.\n                    .target(\n                        name: \"MyPackage\",\n                        dependencies: []),\n                    .testTarget(\n                        name: \"MyPackageTests\",\n                        dependencies: [\"MyPackage\"]),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)\n    }\n\n    func testDynamicLibraryType() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.3\n            // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n            import PackageDescription\n\n            let package = Package(\n                name: \"MyPackage\",\n                platforms: [\n                    .macOS(.v10_14),\n                    .iOS(.v13)\n                ],\n                products: [\n                    // Products define the executables and libraries a package produces, and make them visible to other packages.\n                    .library(\n                        name: \"MyPackage\",\n                        type: .dynamic,\n                        targets: [\"MyPackage\"]),\n                ],\n                dependencies: [\n                    // Dependencies declare other packages that this package depends on.\n                    // .package(url: /* package url */, from: \"1.0.0\"),\n                ],\n                targets: [\n                    // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n                    // Targets can depend on other targets in this package, and on products in packages this package depends on.\n                    .target(\n                        name: \"MyPackage\",\n                        dependencies: []),\n                    .testTarget(\n                        name: \"MyPackageTests\",\n                        dependencies: [\"MyPackage\"]),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)\n    }\n\n    func testCustomPlatform() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.6\n            // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n            import PackageDescription\n\n            let package = Package(\n                name: \"MyPackage\",\n                platforms: [\n                    .custom(\"customOS\", versionString: \"1.0\")\n                ],\n                products: [\n                    // Products define the executables and libraries a package produces, and make them visible to other packages.\n                    .library(\n                        name: \"MyPackage\",\n                        targets: [\"MyPackage\"]),\n                ],\n                dependencies: [\n                    // Dependencies declare other packages that this package depends on.\n                    // .package(url: /* package url */, from: \"1.0.0\"),\n                ],\n                targets: [\n                    // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n                    // Targets can depend on other targets in this package, and on products in packages this package depends on.\n                    .target(\n                        name: \"MyPackage\",\n                        dependencies: []),\n                    .testTarget(\n                        name: \"MyPackageTests\",\n                        dependencies: [\"MyPackage\"]),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_6)\n    }\n\n    func testAdvancedFeatures() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.3\n            // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n            import PackageDescription\n\n            #if os(Windows)\n            let absolutePath = \"c:/a/b/c\"\n            #else\n            let absolutePath = \"/a/b/c\"\n            #endif\n\n            let package = Package(\n                name: \"MyPackage\",\n                products: [\n                    // Products define the executables and libraries a package produces, and make them visible to other packages.\n                    .library(\n                        name: \"MyPackage\",\n                        targets: [\"MyPackage\"]),\n                ],\n                dependencies: [\n                    // Dependencies declare other packages that this package depends on.\n                    .package(path: absolutePath),\n                    .package(name: \"abc\", path: absolutePath),\n                ],\n                targets: [\n                    // Targets are the basic building blocks of a package. A target can define a module or a test suite.\n                    // Targets can depend on other targets in this package, and on products in packages this package depends on.\n                    .systemLibrary(\n                        name: \"SystemLibraryTarget\",\n                        pkgConfig: \"libSystemModule\",\n                        providers: [\n                            .brew([\"SystemModule\"]),\n                        ]),\n                    .target(\n                        name: \"MyPackage\",\n                        dependencies: [\n                            .target(name: \"SystemLibraryTarget\", condition: .when(platforms: [.macOS]))\n                        ],\n                        linkerSettings: [\n                            .unsafeFlags([\"-Xlinker\", \"-rpath\", \"-Xlinker\", \"@executable_path/../../../lib/swift/macosx\"], .when(platforms: [.iOS])),\n                        ]),\n                    .testTarget(\n                        name: \"MyPackageTests\",\n                        dependencies: [\"MyPackage\"]),\n                ],\n                swiftLanguageVersions: [.v5],\n                cLanguageStandard: .c11,\n                cxxLanguageStandard: .cxx11\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)\n    }\n\n    func testPackageDependencyVariations() async throws {\n        try XCTSkipOnWindows(\n            because:\"Intermittently fails\",\n            skipPlatformCi: true,\n        )\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.4\n            import PackageDescription\n\n            #if os(Windows)\n            let absolutePath = \"file:///C:/Users/user/SourceCache/path/to/MyPkg16\"\n            #else\n            let absolutePath = \"file:///path/to/MyPkg16\"\n            #endif\n\n            let package = Package(\n                name: \"MyPackage\",\n                dependencies: [\n                   .package(url: \"https://example.com/MyPkg1\", from: \"1.0.0\"),\n                   .package(url: \"https://example.com/MyPkg2\", .revision(\"58e9de4e7b79e67c72a46e164158e3542e570ab6\")),\n                   .package(url: \"https://example.com/MyPkg5\", .exact(\"1.2.3\")),\n                   .package(url: \"https://example.com/MyPkg6\", \"1.2.3\"..<\"2.0.0\"),\n                   .package(url: \"https://example.com/MyPkg7\", .branch(\"main\")),\n                   .package(url: \"https://example.com/MyPkg8\", .upToNextMinor(from: \"1.3.4\")),\n                   .package(url: \"ssh://git@example.com/MyPkg9\", .branch(\"my branch with spaces\")),\n                   .package(url: \"../MyPkg10\", from: \"0.1.0\"),\n                   .package(path: \"../MyPkg11\"),\n                   .package(path: \"packages/path/to/MyPkg12\"),\n                   .package(path: \"~/path/to/MyPkg13\"),\n                   .package(path: \"~MyPkg14\"),\n                   .package(path: \"~/path/to/~/MyPkg15\"),\n                   .package(path: \"~\"),\n                   .package(path: absolutePath),\n                ]\n            )\n            \"\"\"\n        let newContents = try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)\n\n        // Check some things about the contents of the manifest.\n        XCTAssertTrue(newContents.contains(\"url: \\\"\\(\"../MyPkg10\".nativePathString(escaped: true))\\\"\"), newContents)\n        XCTAssertTrue(newContents.contains(\"path: \\\"\\(\"../MyPkg11\".nativePathString(escaped: true))\\\"\"), newContents)\n        XCTAssertTrue(newContents.contains(\"path: \\\"\\(\"packages/path/to/MyPkg12\".nativePathString(escaped: true))\"), newContents)\n    }\n\n    func testResources() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.3\n            import PackageDescription\n\n            let package = Package(\n                name: \"Resources\",\n                defaultLocalization: \"is\",\n                targets: [\n                    .target(\n                        name: \"SwiftyResource\",\n                        resources: [\n                            .copy(\"foo.txt\"),\n                            .process(\"a/b/c/\"),\n                        ]\n                    ),\n                    .target(\n                        name: \"SeaResource\",\n                        resources: [\n                            .process(\"foo.txt\", localization: .base),\n                        ]\n                    ),\n                    .target(\n                        name: \"SieResource\",\n                        resources: [\n                            .copy(\"bar.boo\"),\n                        ]\n                    ),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)\n    }\n\n    func testBuildSettings() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.3\n            import PackageDescription\n\n            let package = Package(\n                name: \"Localized\",\n                targets: [\n                    .target(name: \"exe\",\n                        cxxSettings: [\n                            .headerSearchPath(\"ProjectName\"),\n                            .headerSearchPath(\"../../..\"),\n                            .define(\"ABC=DEF\"),\n                            .define(\"GHI\", to: \"JKL\")\n                        ]\n                    ),\n                    .target(\n                        name: \"MyTool\",\n                        dependencies: [\"Utility\"],\n                        cSettings: [\n                            .headerSearchPath(\"path/relative/to/my/target\"),\n                            .define(\"DISABLE_SOMETHING\", .when(platforms: [.iOS], configuration: .release)),\n                        ],\n                        swiftSettings: [\n                            .define(\"ENABLE_SOMETHING\", .when(configuration: .release)),\n                        ],\n                        linkerSettings: [\n                            .linkedLibrary(\"openssl\", .when(platforms: [.linux])),\n                        ]\n                    ),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_3)\n    }\n\n    func testPluginTargets() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.5\n            import PackageDescription\n\n            let package = Package(\n                name: \"Plugins\",\n                targets: [\n                    .plugin(\n                        name: \"MyPlugin\",\n                        capability: .buildTool(),\n                        dependencies: [\"MyTool\"]\n                    ),\n                    .executableTarget(\n                        name: \"MyTool\"\n                    ),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5)\n    }\n\n    func testCustomToolsVersionHeaderComment() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.5\n            import PackageDescription\n\n            let package = Package(\n                name: \"Plugins\",\n                targets: [\n                    .plugin(\n                        name: \"MyPlugin\",\n                        capability: .buildTool(),\n                        dependencies: [\"MyTool\"]\n                    ),\n                    .executableTarget(\n                        name: \"MyTool\"\n                    ),\n                ]\n            )\n            \"\"\"\n        let newContents = try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5, toolsVersionHeaderComment: \"a comment\")\n\n        XCTAssertTrue(newContents.hasPrefix(\"// swift-tools-version: 5.5; a comment\\n\"), \"contents: \\(newContents)\")\n    }\n\n    func testAdditionalModuleImports() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.5\n            import PackageDescription\n            import Foundation\n\n            let package = Package(\n                name: \"MyPkg\",\n                targets: [\n                    .executableTarget(\n                        name: \"MyExec\"\n                    ),\n                ]\n            )\n            \"\"\"\n        let newContents = try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5, additionalImportModuleNames: [\"Foundation\"])\n\n        XCTAssertTrue(newContents.contains(\"import Foundation\\n\"), \"contents: \\(newContents)\")\n    }\n\n    func testLatestPlatformVersions() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version: 5.9\n            // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n            import PackageDescription\n\n            let package = Package(\n                name: \"MyPackage\",\n                platforms: [\n                    .macOS(.v14),\n                    .iOS(.v17),\n                    .tvOS(.v17),\n                    .watchOS(.v10),\n                    .visionOS(.v1),\n                    .macCatalyst(.v17),\n                    .driverKit(.v23)\n                ],\n                targets: [\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_9)\n    }\n\n    func testTargetPlatformConditions() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version: 5.9\n            // The swift-tools-version declares the minimum version of Swift required to build this package.\n\n            import PackageDescription\n\n            let package = Package(\n                name: \"MyPackage\",\n                targets: [\n                    .target(\n                        name: \"MyExe\",\n                        dependencies: [\n                            .target(name: \"MyLib\", condition: .when(platforms: [\n                                .macOS, .macCatalyst, .iOS, .tvOS, .watchOS, .visionOS,\n                                .driverKit, .linux, .windows, .android, .wasi, .openbsd,\n                                .custom(\"freebsd\"), .custom(\"toasterOS\")\n                            ]))\n                        ]\n                    ),\n                    .target(\n                        name: \"MyLib\"\n                    ),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_9)\n    }\n    \n    func testCustomProductSourceGeneration() throws {\n        // Create a manifest containing a product for which we'd like to do custom source fragment generation.\n        let packageDir = AbsolutePath(\"/tmp/MyLibrary\")\n        let manifest = Manifest.createManifest(\n            displayName: \"MyLibrary\",\n            path: packageDir.appending(\"Package.swift\"),\n            packageKind: .root(\"/tmp/MyLibrary\"),\n            packageIdentity: .plain(\"MyLibrary\"),\n            packageLocation: packageDir.pathString,\n            platforms: [],\n            toolsVersion: .v5_5,\n            products: [\n                try .init(name: \"Foo\", type: .library(.static), targets: [\"Bar\"])\n            ]\n        )\n\n        // Generate the manifest contents, using a custom source generator for the product type.\n        let contents = manifest.generateManifestFileContents(packageDirectory: packageDir, customProductTypeSourceGenerator: { product in\n            // This example handles library types in a custom way, for testing purposes.\n            var params: [SourceCodeFragment] = []\n            params.append(SourceCodeFragment(key: \"name\", string: product.name))\n            if !product.targets.isEmpty {\n                params.append(SourceCodeFragment(key: \"targets\", strings: product.targets))\n            }\n            // Handle .library specially (by not emitting as multiline), otherwise asking for default behavior.\n            if case .library(let type) = product.type {\n                if type != .automatic {\n                    params.append(SourceCodeFragment(key: \"type\", enum: type.rawValue))\n                }\n                return SourceCodeFragment(enum: \"library\", subnodes: params, multiline: false)\n            }\n            else {\n                return nil\n            }\n        })\n\n        // Check that we generated what we expected.\n        XCTAssertTrue(contents.contains(\".library(name: \\\"Foo\\\", targets: [\\\"Bar\\\"], type: .static)\"), \"contents: \\(contents)\")\n    }\n\n    /// Tests a fully customized iOSApplication (one that exercises every parameter in at least some way).\n    func testAppleProductSettings() throws {\n      #if ENABLE_APPLE_PRODUCT_TYPES\n        let manifestContents = \"\"\"\n            // swift-tools-version: 999.0\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .iOSApplication(\n                        name: \"Foo\",\n                        targets: [\"Foo\"],\n                        bundleIdentifier: \"com.my.app\",\n                        teamIdentifier: \"ZXYTEAM123\",\n                        displayVersion: \"1.4.2 Extra Cool\",\n                        bundleVersion: \"1.4.2\",\n                        appIcon: .placeholder(icon: .cloud),\n                        accentColor: .presetColor(.red),\n                        supportedDeviceFamilies: [.phone, .pad, .mac],\n                        supportedInterfaceOrientations: [\n                            .portrait,\n                            .landscapeRight(),\n                            .landscapeLeft(.when(deviceFamilies: [.mac]))\n                        ],\n                        capabilities: [\n                            .camera(purposeString: \"All the better to see you with…\", .when(deviceFamilies: [.pad, .phone])),\n                            .fileAccess(.userSelectedFiles, mode: .readOnly, .when(deviceFamilies: [.mac])),\n                            .fileAccess(.pictureFolder, mode: .readWrite, .when(deviceFamilies: [.mac])),\n                            .fileAccess(.musicFolder, mode: .readOnly),\n                            .fileAccess(.downloadsFolder, mode: .readWrite, .when(deviceFamilies: [.mac])),\n                            .fileAccess(.moviesFolder, mode: .readWrite, .when(deviceFamilies: [.mac])),\n                            .incomingNetworkConnections(.when(deviceFamilies: [.mac])),\n                            .outgoingNetworkConnections(),\n                            .microphone(purposeString: \"All the better to hear you with…\"),\n                            .motion(purposeString: \"Move along, move along, …\"),\n                            .localNetwork(\n                                purposeString: \"Communication is key…\",\n                                bonjourServiceTypes: [\"_ipp._tcp\", \"_ipps._tcp\"],\n                                .when(deviceFamilies: [.mac])\n                            ),\n                            .appTransportSecurity(\n                                configuration: .init(\n                                    allowsArbitraryLoadsInWebContent: true,\n                                    allowsArbitraryLoadsForMedia: false,\n                                    allowsLocalNetworking: false,\n                                    exceptionDomains: [\n                                        .init(\n                                            domainName: \"not-shady-at-all-domain.biz\",\n                                            includesSubdomains: true,\n                                            exceptionAllowsInsecureHTTPLoads: true,\n                                            exceptionMinimumTLSVersion: \"2\",\n                                            exceptionRequiresForwardSecrecy: false,\n                                            requiresCertificateTransparency: false\n                                        )\n                                    ],\n                                    pinnedDomains: [\n                                        .init(\n                                            domainName: \"honest-harrys-pinned-domain.biz\",\n                                            includesSubdomains : false,\n                                            pinnedCAIdentities : [[\"a\": \"b\", \"x\": \"y\"], [:]],\n                                            pinnedLeafIdentities : [[\"v\": \"w\"]]\n                                        )\n                                    ]\n                                ),\n                                .when(deviceFamilies: [.phone, .pad])\n                            )\n                        ],\n                        appCategory: .weather,\n                        additionalInfoPlistContentFilePath: \"some/path/to/a/file.plist\"\n                    ),\n                ],\n                targets: [\n                    .executableTarget(\n                        name: \"Foo\"\n                    ),\n                ]\n            )\n            \"\"\"\n        try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5)\n      #else\n        throw XCTSkip(\"ENABLE_APPLE_PRODUCT_TYPES is not set\")\n      #endif\n    }\n\n    /// Tests loading an iOSApplication product configured with the `.asset(_)` variant of the\n    /// appIcon and accentColor parameters.\n    func testAssetBasedAccentColorAndAppIconAppleProductSettings() throws {\n      #if ENABLE_APPLE_PRODUCT_TYPES\n        let manifestContents = \"\"\"\n            // swift-tools-version: 999.0\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .iOSApplication(\n                        name: \"Foo\",\n                        targets: [\"Foo\"],\n                        appIcon: .asset(\"AppIcon\"),\n                        accentColor: .asset(\"AccentColor\")\n                    ),\n                ],\n                targets: [\n                    .executableTarget(\n                        name: \"Foo\"\n                    ),\n                ]\n            )\n            \"\"\"\n        try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5)\n      #else\n        throw XCTSkip(\"ENABLE_APPLE_PRODUCT_TYPES is not set\")\n      #endif\n    }\n\n    /// Tests loading an iOSApplication product configured with legacy 'iconAssetName' and 'accentColorAssetName' parameters.\n    func testLegacyAccentColorAndAppIconAppleProductSettings() throws {\n      #if ENABLE_APPLE_PRODUCT_TYPES\n        let manifestContents = \"\"\"\n            // swift-tools-version: 999.0\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .iOSApplication(\n                        name: \"Foo\",\n                        targets: [\"Foo\"],\n                        iconAssetName: \"icon\",\n                        accentColorAssetName: \"accentColor\"\n                    ),\n                ],\n                targets: [\n                    .executableTarget(\n                        name: \"Foo\"\n                    ),\n                ]\n            )\n            \"\"\"\n        try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5)\n      #else\n        throw XCTSkip(\"ENABLE_APPLE_PRODUCT_TYPES is not set\")\n      #endif\n    }\n\n    /// Tests the smallest allowed iOSApplication (one that has default values for everything not required). Make sure no defaults get added to it.\n    func testMinimalAppleProductSettings() throws {\n      #if ENABLE_APPLE_PRODUCT_TYPES\n        let manifestContents = \"\"\"\n            // swift-tools-version: 999.0\n            import PackageDescription\n            let package = Package(\n                name: \"Foo\",\n                products: [\n                    .iOSApplication(\n                        name: \"Foo\",\n                        targets: [\"Foo\"],\n                        accentColor: .asset(\"AccentColor\"),\n                        supportedDeviceFamilies: [\n                            .mac\n                        ],\n                        supportedInterfaceOrientations: [\n                            .portrait\n                        ]\n                    ),\n                ],\n                targets: [\n                    .executableTarget(\n                        name: \"Foo\"\n                    ),\n                ]\n            )\n            \"\"\"\n        try testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_5)\n      #else\n        throw XCTSkip(\"ENABLE_APPLE_PRODUCT_TYPES is not set\")\n      #endif\n    }\n\n    func testModuleAliasGeneration() async throws {\n        let manifest = Manifest.createRootManifest(\n            displayName: \"thisPkg\",\n            path: \"/thisPkg\",\n            toolsVersion: .v5_7,\n            dependencies: [\n                .localSourceControl(path: \"/fooPkg\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                .localSourceControl(path: \"/barPkg\", requirement: .upToNextMajor(from: \"2.0.0\")),\n            ],\n            targets: [\n                try TargetDescription(name: \"exe\",\n                                  dependencies: [\"Logging\",\n                                                 .product(name: \"Foo\",\n                                                          package: \"fooPkg\",\n                                                          moduleAliases: [\"Logging\": \"FooLogging\"]\n                                                         ),\n                                                 .product(name: \"Bar\",\n                                                          package: \"barPkg\",\n                                                          moduleAliases: [\"Logging\": \"BarLogging\"]\n                                                         )\n                                                ]),\n                try TargetDescription(name: \"Logging\", dependencies: []),\n            ])\n        let contents = try manifest.generateManifestFileContents(packageDirectory: manifest.path.parentDirectory)\n        let parts =\n        \"\"\"\n            dependencies: [\n                \"Logging\",\n                .product(name: \"Foo\", package: \"fooPkg\", moduleAliases: [\n                    \"Logging\": \"FooLogging\"\n                ]),\n                .product(name: \"Bar\", package: \"barPkg\", moduleAliases: [\n                    \"Logging\": \"BarLogging\"\n                ])\n            ]\n        \"\"\"\n        let trimmedContents = contents.components(separatedBy: CharacterSet.whitespacesAndNewlines)\n        let trimmedParts = parts.components(separatedBy: CharacterSet.whitespacesAndNewlines)\n        let isContained = trimmedParts.allSatisfy(trimmedContents.contains(_:))\n        XCTAssertTrue(isContained)\n\n        try await testManifestWritingRoundTrip(manifestContents: contents, toolsVersion: .v5_8)\n    }\n\n    func testUpcomingAndExperimentalFeatures() async throws {\n        let manifestContents = \"\"\"\n            // swift-tools-version:5.8\n            import PackageDescription\n\n            let package = Package(\n                name: \"UpcomingAndExperimentalFeatures\",\n                targets: [\n                    .target(\n                        name: \"MyTool\",\n                        swiftSettings: [\n                            .enableUpcomingFeature(\"UpcomingFeatureOne\"),\n                            .enableUpcomingFeature(\"UpcomingFeatureTwo\"),\n                            .enableExperimentalFeature(\"ExperimentalFeature\")\n                        ]\n                    ),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v5_8)\n    }\n\n    func testStrictMemorySafety() async throws {\n        try XCTSkipIfCompilerLessThan6_2()\n\n        let manifestContents = \"\"\"\n            // swift-tools-version:6.2\n            import PackageDescription\n\n            let package = Package(\n                name: \"UpcomingAndExperimentalFeatures\",\n                targets: [\n                    .target(\n                        name: \"MyTool\",\n                        swiftSettings: [\n                            .strictMemorySafety(),\n                        ]\n                    ),\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v6_2)\n    }\n\n    func testPluginNetworkingPermissionGeneration() async throws {\n        let manifest = Manifest.createRootManifest(\n            displayName: \"thisPkg\",\n            path: \"/thisPkg\",\n            toolsVersion: .v5_9,\n            dependencies: [],\n            targets: [\n                try TargetDescription(name: \"MyPlugin\", type: .plugin, pluginCapability: .command(intent: .custom(verb: \"foo\", description: \"bar\"), permissions: [.allowNetworkConnections(scope: .all(ports: [23, 42, 443, 8080]), reason: \"internet good\")]))\n            ])\n        let contents = try manifest.generateManifestFileContents(packageDirectory: manifest.path.parentDirectory)\n        try await testManifestWritingRoundTrip(manifestContents: contents, toolsVersion: .v5_9)\n    }\n\n    func testManifestGenerationWithSwiftLanguageMode() async throws {\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            path: \"/pkg\",\n            toolsVersion: .v6_0,\n            dependencies: [],\n            targets: [\n                try TargetDescription(\n                    name: \"v5\",\n                    type: .executable,\n                    settings: [\n                        .init(tool: .swift, kind: .swiftLanguageMode(.v6))\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"custom\",\n                    type: .executable,\n                    settings: [\n                        .init(tool: .swift, kind: .swiftLanguageMode(.init(string: \"5.10\")!))\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"conditional\",\n                    type: .executable,\n                    settings: [\n                        .init(tool: .swift, kind: .swiftLanguageMode(.v5), condition: .init(platformNames: [\"linux\"])),\n                        .init(tool: .swift, kind: .swiftLanguageMode(.v4), condition: .init(platformNames: [\"macos\"], config: \"debug\"))\n                    ]\n                )\n            ])\n        let contents = try manifest.generateManifestFileContents(packageDirectory: manifest.path.parentDirectory)\n        try await testManifestWritingRoundTrip(manifestContents: contents, toolsVersion: .v6_0)\n    }\n\n    func testManifestGenerationWithWarningControlFlags() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8543: there are compilation errors\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            path: \"/pkg\",\n            toolsVersion: .v6_2,\n            dependencies: [],\n            targets: [\n                try TargetDescription(\n                    name: \"swiftTarget\",\n                    settings: [\n                        .init(tool: .swift, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                        .init(tool: .swift, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                        .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .warning), condition: .init(config: \"release\")),\n                        .init(tool: .swift, kind: .treatWarning(\"DeprecatedDeclaration\", .error), condition: .init(config: \"debug\")),\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"cTarget\",\n                    settings: [\n                        .init(tool: .c, kind: .disableWarning(\"unused-parameter\"), condition: .init(config: \"release\")),\n                        .init(tool: .c, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                        .init(tool: .c, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                        .init(tool: .c, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                        .init(tool: .c, kind: .treatWarning(\"implicit-function-declaration\", .error), condition: .init(config: \"release\")),\n                        .init(tool: .c, kind: .treatWarning(\"implicit-function-declaration\", .warning), condition: .init(config: \"debug\")),\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"cxxTarget\",\n                    settings: [\n                        .init(tool: .cxx, kind: .disableWarning(\"unused-parameter\"), condition: .init(config: \"release\")),\n                        .init(tool: .cxx, kind: .enableWarning(\"implicit-fallthrough\"), condition: .init(config: \"debug\")),\n                        .init(tool: .cxx, kind: .treatAllWarnings(.error), condition: .init(config: \"release\")),\n                        .init(tool: .cxx, kind: .treatAllWarnings(.warning), condition: .init(config: \"debug\")),\n                        .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .error), condition: .init(config: \"release\")),\n                        .init(tool: .cxx, kind: .treatWarning(\"deprecated-declarations\", .warning), condition: .init(config: \"debug\")),\n                    ]\n                ),\n            ])\n        let contents = try manifest.generateManifestFileContents(packageDirectory: manifest.path.parentDirectory)\n        try await testManifestWritingRoundTrip(manifestContents: contents, toolsVersion: .v6_2)\n    }\n\n    func testDefaultIsolation() async throws {\n        try XCTSkipOnWindows(because: \"https://github.com/swiftlang/swift-package-manager/issues/8543: there are compilation errors\")\n\n        let manifest = Manifest.createRootManifest(\n            displayName: \"pkg\",\n            path: \"/pkg\",\n            toolsVersion: .v6_2,\n            dependencies: [],\n            targets: [\n                try TargetDescription(\n                    name: \"A\",\n                    type: .executable,\n                    settings: [\n                        .init(tool: .swift, kind: .defaultIsolation(.nonisolated))\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"B\",\n                    type: .executable,\n                    settings: [\n                        .init(tool: .swift, kind: .defaultIsolation(.MainActor))\n                    ]\n                ),\n                try TargetDescription(\n                    name: \"conditional\",\n                    type: .executable,\n                    settings: [\n                        .init(tool: .swift, kind: .defaultIsolation(.nonisolated), condition: .init(platformNames: [\"linux\"])),\n                        .init(tool: .swift, kind: .defaultIsolation(.MainActor), condition: .init(platformNames: [\"macos\"], config: \"debug\"))\n                    ]\n                )\n            ])\n        let contents = try manifest.generateManifestFileContents(packageDirectory: manifest.path.parentDirectory)\n        try await testManifestWritingRoundTrip(manifestContents: contents, toolsVersion: .v6_2)\n    }\n\n    func testTraits() async throws {\n        try XCTSkipIfCompilerLessThan6_1()\n\n        let manifestContents = \"\"\"\n            // swift-tools-version: 6.1\n            import PackageDescription\n\n            let package = Package(\n                name: \"TraitExample\",\n                traits: [\n                    \"Foo\",\n                    .trait(\n                        name: \"Bar\",\n                        enabledTraits: [\n                            \"Foo\",\n                        ]\n                    ),\n                    .trait(\n                        name: \"FooBar\",\n                        enabledTraits: [\n                            \"Foo\",\n                            \"Bar\",\n                        ]\n                    ),\n                    .default(enabledTraits: [\"Foo\"]),\n                ],\n                dependencies: [\n                    .package(\n                        url: \"https://github.com/Org/SomePackage.git\",\n                        from: \"1.0.0\",\n                        traits: [\n                            .defaults,\n                            \"SomeTrait\",\n                            .trait(name: \"SomeOtherTrait\", condition: .when(traits: [\"Foo\"])),\n                        ]\n                    ),\n                ],\n                targets: [\n                    .target(\n                        name: \"SomeTarget\",\n                        dependencies: [\n                            .product(\n                                name: \"SomeProduct\",\n                                package: \"SomePackage\",\n                                condition: .when(traits: [\"Foo\"])\n                            ),\n                        ]\n                    )\n                ]\n            )\n            \"\"\"\n        try await testManifestWritingRoundTrip(manifestContents: manifestContents, toolsVersion: .v6_1)\n    }\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/MirrorsConfigurationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2020-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _InternalTestSupport\nimport Workspace\nimport Testing\n\nfileprivate struct MirrorsConfigurationTests {\n    @Test\n    func loadingSchema1() throws {\n        let fs = InMemoryFileSystem()\n        let configFile = AbsolutePath(\"/config/mirrors.json\")\n\n        let originalURL = \"https://github.com/apple/swift-argument-parser.git\"\n        let mirrorURL = \"https://github.com/mona/swift-argument-parser.git\"\n\n        try fs.createDirectory(configFile.parentDirectory)\n        try fs.writeFileContents(\n            configFile,\n            string: \"\"\"\n            {\n              \"object\": [\n                {\n                  \"mirror\": \"\\(mirrorURL)\",\n                  \"original\": \"\\(originalURL)\"\n                }\n              ],\n              \"version\": 1\n            }\n            \"\"\"\n        )\n\n        let config = Workspace.Configuration.MirrorsStorage(path: configFile, fileSystem: fs, deleteWhenEmpty: true)\n        let mirrors = try config.get()\n\n        #expect(mirrors.mirror(for: originalURL) == mirrorURL)\n        #expect(mirrors.original(for: mirrorURL) == originalURL)\n    }\n\n    @Test\n    func throwsWhenNotFound() throws {\n        let gitUrl = \"https://github.com/apple/swift-argument-parser.git\"\n        let fs = InMemoryFileSystem()\n        let configFile = AbsolutePath(\"/config/mirrors.json\")\n\n        let config = Workspace.Configuration.MirrorsStorage(path: configFile, fileSystem: fs, deleteWhenEmpty: true)\n        let mirrors = try config.get()\n\n        #expect(throws: StringError(\"Mirror not found for '\\(gitUrl)'\")) {\n            try mirrors.unset(originalOrMirror: gitUrl)\n        }\n    }\n\n    @Test\n    func deleteWhenEmpty() throws {\n        let fs = InMemoryFileSystem()\n        let configFile = AbsolutePath(\"/config/mirrors.json\")\n\n        let config = Workspace.Configuration.MirrorsStorage(path: configFile, fileSystem: fs, deleteWhenEmpty: true)\n\n        try config.apply{ _ in }\n        #expect(!fs.exists(configFile))\n\n        let originalURL = \"https://github.com/apple/swift-argument-parser.git\"\n        let mirrorURL = \"https://github.com/mona/swift-argument-parser.git\"\n\n        try config.apply{ mirrors in\n            try mirrors.set(mirror: mirrorURL, for: originalURL)\n        }\n        #expect(fs.exists(configFile))\n\n        try config.apply{ mirrors in\n            try mirrors.unset(originalOrMirror: originalURL)\n        }\n        #expect(!fs.exists(configFile))\n    }\n\n    @Test\n    func dontDeleteWhenEmpty() throws {\n        let fs = InMemoryFileSystem()\n        let configFile = AbsolutePath(\"/config/mirrors.json\")\n\n        let config = Workspace.Configuration.MirrorsStorage(path: configFile, fileSystem: fs, deleteWhenEmpty: false)\n\n        try config.apply{ _ in }\n        #expect(!fs.exists(configFile))\n\n        let originalURL = \"https://github.com/apple/swift-argument-parser.git\"\n        let mirrorURL = \"https://github.com/mona/swift-argument-parser.git\"\n\n        try config.apply{ mirrors in\n            try mirrors.set(mirror: mirrorURL, for: originalURL)\n        }\n        #expect(fs.exists(configFile))\n\n        try config.apply{ mirrors in\n            try mirrors.unset(originalOrMirror: originalURL)\n        }\n        #expect(fs.exists(configFile))\n        #expect(try config.get().isEmpty)\n    }\n\n    @Test\n    func localAndShared() throws {\n        let fs = InMemoryFileSystem()\n        let localConfigFile = AbsolutePath(\"/config/local-mirrors.json\")\n        let sharedConfigFile = AbsolutePath(\"/config/shared-mirrors.json\")\n\n        let config = try Workspace.Configuration.Mirrors(\n            fileSystem: fs,\n            localMirrorsFile: localConfigFile,\n            sharedMirrorsFile: sharedConfigFile\n        )\n\n        // first write to shared location\n\n        let original1URL = \"https://github.com/apple/swift-argument-parser.git\"\n        let mirror1URL = \"https://github.com/mona/swift-argument-parser.git\"\n\n        try config.applyShared { mirrors in\n            try mirrors.set(mirror: mirror1URL, for: original1URL)\n        }\n\n        #expect(config.mirrors.count == 1)\n        #expect(config.mirrors.mirror(for: original1URL) == mirror1URL)\n        #expect(config.mirrors.original(for: mirror1URL) == original1URL)\n\n        // now write to local location\n\n        let original2URL = \"https://github.com/apple/swift-nio.git\"\n        let mirror2URL = \"https://github.com/mona/swift-nio.git\"\n\n        try config.applyLocal { mirrors in\n            try mirrors.set(mirror: mirror2URL, for: original2URL)\n        }\n\n        #expect(config.mirrors.count == 1)\n        #expect(config.mirrors.mirror(for: original2URL) == mirror2URL)\n        #expect(config.mirrors.original(for: mirror2URL) == original2URL)\n\n        // should not see the shared any longer\n        #expect(config.mirrors.mirror(for: original1URL) == nil)\n        #expect(config.mirrors.original(for: mirror1URL) == nil)\n    }\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/PrebuiltsTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n///\n/// Tests for the macro prebuilts features that will use a prebuilt library for swift-syntax dependencies for macros.\n///\n\nimport Basics\nimport struct TSCBasic.SHA256\nimport struct TSCBasic.ByteString\nimport let TSCBasic.stdoutStream\nimport struct TSCUtility.Version\nimport PackageGraph\nimport PackageModel\nimport Workspace\nimport XCTest\nimport _InternalTestSupport\n\nfinal class PrebuiltsTests: XCTestCase {\n    let swiftVersion = \"swift-\\(SwiftVersion.current.major).\\(SwiftVersion.current.minor)\"\n\n    func with(\n        fileSystem: FileSystem,\n        artifact: Data,\n        swiftSyntaxVersion: String,\n        swiftSyntaxURL: String? = nil,\n        run: (Workspace.SignedPrebuiltsManifest, AbsolutePath, MockPackage, MockPackage) async throws -> ()\n    ) async throws {\n        try await fixtureXCTest(name: \"Signing\") { fixturePath in\n            let swiftSyntaxURL = swiftSyntaxURL ?? \"https://github.com/swiftlang/swift-syntax\"\n\n            let manifest = Workspace.PrebuiltsManifest(libraries: [\n                .init(\n                    name: \"MacroSupport\",\n                    checksum: SHA256().hash(ByteString(artifact)).hexadecimalRepresentation,\n                    products: [\n                        \"SwiftSyntaxMacrosTestSupport\",\n                        \"SwiftCompilerPlugin\",\n                        \"SwiftSyntaxMacros\"\n                    ],\n                    includePath: [\n                        .init(\"Sources/_SwiftSyntaxCShims/include\")\n                    ]\n                )\n            ])\n\n            let certsPath = fixturePath.appending(\"Certificates\")\n\n            let certPaths = [\n                certsPath.appending(\"Test_rsa.cer\"),\n                certsPath.appending(\"TestIntermediateCA.cer\"),\n                certsPath.appending(\"TestRootCA.cer\"),\n            ]\n            let privateKeyPath = certsPath.appending(\"Test_rsa_key.pem\")\n\n            // Copy into in memory file system\n            for path in certPaths + [privateKeyPath] {\n                try fileSystem.writeFileContents(path, data: Data(contentsOf: path.asURL))\n            }\n\n            let rootCertPath = certPaths.last!\n            let trustDir = certsPath.appending(\"Trust\")\n            try fileSystem.createDirectory(trustDir, recursive: true)\n            try fileSystem.copy(from: rootCertPath, to: trustDir.appending(rootCertPath.basename))\n\n            let signer = ManifestSigning(\n                trustedRootCertsDir: trustDir,\n                observabilityScope: ObservabilitySystem({ _, diagnostic in print(diagnostic) }, outputStream: stdoutStream, logLevel: .debug).topScope\n            )\n\n            let signature = try await signer.sign(\n                manifest: manifest,\n                certChainPaths: certPaths,\n                certPrivateKeyPath: privateKeyPath,\n                fileSystem: fileSystem\n            )\n\n            // Make sure the signing is valid\n            try await signer.validate(manifest: manifest, signature: signature, fileSystem: fileSystem)\n\n            let signedManifest = Workspace.SignedPrebuiltsManifest(manifest: manifest, signature: signature)\n\n            let rootPackage = try MockPackage(\n                name: \"Foo\",\n                targets: [\n                    MockTarget(\n                        name: \"FooMacros\",\n                        dependencies: [\n                            .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                            .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\"),\n                        ],\n                        type: .macro\n                    ),\n                    MockTarget(\n                        name: \"Foo\",\n                        dependencies: [\"FooMacros\"]\n                    ),\n                    MockTarget(\n                        name: \"FooClient\",\n                        dependencies: [\"Foo\"],\n                        type: .executable\n                    ),\n                    MockTarget(\n                        name: \"FooTests\",\n                        dependencies: [\n                            \"FooMacros\",\n                            .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n                        ],\n                        type: .test\n                    ),\n                ],\n                dependencies: [\n                    .sourceControl(\n                        url: swiftSyntaxURL,\n                        requirement: .exact(try XCTUnwrap(Version(swiftSyntaxVersion)))\n                    )\n                ]\n            )\n\n            let swiftSyntax = try MockPackage(\n                name: \"swift-syntax\",\n                url: swiftSyntaxURL,\n                targets: [\n                    MockTarget(name: \"SwiftSyntaxMacrosTestSupport\"),\n                    MockTarget(name: \"SwiftCompilerPlugin\"),\n                    MockTarget(name: \"SwiftSyntaxMacros\"),\n                ],\n                products: [\n                    MockProduct(name: \"SwiftSyntaxMacrosTestSupport\", modules: [\"SwiftSyntaxMacrosTestSupport\"]),\n                    MockProduct(name: \"SwiftCompilerPlugin\", modules: [\"SwiftCompilerPlugin\"]),\n                    MockProduct(name: \"SwiftSyntaxMacros\", modules: [\"SwiftSyntaxMacros\"]),\n                ],\n                versions: [\"600.0.1\", \"600.0.2\", \"601.0.0\"]\n            )\n\n            try await run(signedManifest, rootCertPath, rootPackage, swiftSyntax)\n        }\n    }\n\n    func checkSettings(_ rootPackage: ResolvedPackage, _ targetName: String, usePrebuilt: Bool) throws {\n        let target = try XCTUnwrap(rootPackage.underlying.modules.first(where: { $0.name == targetName }))\n        if usePrebuilt {\n            let includes = try XCTUnwrap(target.buildSettings.assignments[.PREBUILT_INCLUDE_PATHS]).flatMap(\\.values)\n            XCTAssertEqual(includes.count, 2)\n            XCTAssertTrue(includes.contains(\"/tmp/ws/.build/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport/Modules\".fixwin))\n            XCTAssertTrue(includes.contains(\"/tmp/ws/.build/checkouts/swift-syntax/Sources/_SwiftSyntaxCShims/include\".fixwin))\n            let libPaths = try XCTUnwrap(target.buildSettings.assignments[.PREBUILT_LIBRARY_PATHS]).flatMap(\\.values)\n            XCTAssertEqual(libPaths, [\"/tmp/ws/.build/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport/lib\".fixwin])\n            let lib = try XCTUnwrap(target.buildSettings.assignments[.PREBUILT_LIBRARIES]).flatMap(\\.values)\n            XCTAssertEqual(lib, [\"MacroSupport\"])\n        } else {\n            XCTAssertNil(target.buildSettings.assignments[.OTHER_SWIFT_FLAGS])\n            XCTAssertNil(target.buildSettings.assignments[.OTHER_LDFLAGS])\n        }\n    }\n\n    func testSuccessPath() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { manifest, rootCertPath, rootPackage, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                ),\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error || $0.severity == .warning }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testVersionChange() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { manifest, rootCertPath, rootPackage, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    // make sure it's the updated one\n                    XCTAssertEqual(\n                        request.url,\n                        \"https://download.swift.org/prebuilts/swift-syntax/601.0.0/\\(self.swiftVersion).json\"\n                    )\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [rootPackage.name]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error || $0.severity == .warning }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n\n            // Change the version of swift syntax to one that doesn't have prebuilts\n            try await workspace.closeWorkspace(resetState: false, resetResolvedFile: false)\n            let key = MockManifestLoader.Key(url: sandbox.appending(components: \"roots\", rootPackage.name).pathString)\n            let oldManifest = try XCTUnwrap(workspace.manifestLoader.manifests[key])\n            let oldSCM: PackageDependency.SourceControl\n            if case let .sourceControl(scm) = oldManifest.dependencies[0] {\n                oldSCM = scm\n            } else {\n                XCTFail(\"not source control\")\n                return\n            }\n            let newDep = PackageDependency.sourceControl(\n                identity: oldSCM.identity,\n                nameForTargetDependencyResolutionOnly: oldSCM.nameForTargetDependencyResolutionOnly,\n                location: oldSCM.location,\n                requirement: .exact(try XCTUnwrap(Version(\"601.0.0\"))),\n                productFilter: oldSCM.productFilter\n            )\n            let newManifest = oldManifest.with(dependencies: [newDep])\n            workspace.manifestLoader.manifests[key] = newManifest\n\n            try await workspace.checkPackageGraph(roots: [rootPackage.name]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error || $0.severity == .warning }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n\n            // Change it back\n            try await workspace.closeWorkspace(resetState: false, resetResolvedFile: false)\n            workspace.manifestLoader.manifests[key] = oldManifest\n\n            try await workspace.checkPackageGraph(roots: [rootPackage.name]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error || $0.severity == .warning }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testSSHURL() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\", swiftSyntaxURL: \"git@github.com:swiftlang/swift-syntax.git\") {\n            manifest, rootCertPath, rootPackage, swiftSyntax in\n\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testRedirectURL() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\", swiftSyntaxURL: \"https://github.com/apple/swift-syntax.git\") {\n            manifest, rootCertPath, rootPackage, swiftSyntax in\n\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n    func testCachedArtifact() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n        let cacheFile = try AbsolutePath(validating: \"/home/user/caches/org.swift.swiftpm/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\")\n        try fs.writeFileContents(cacheFile, data: artifact)\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { manifest, rootCertPath, rootPackage, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    XCTFail(\"Unexpect download of archive\")\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testUnsupportedSwiftSyntaxVersion() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.2\") { _, rootCertPath, rootPackage, swiftSyntax in\n            let secondFetch = SendableBox(false)\n            \n            let httpClient = HTTPClient { request, progressHandler in\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.2/\\(self.swiftVersion).json\" {\n                    let secondFetch = await secondFetch.value\n                    XCTAssertFalse(secondFetch, \"unexpected second fetch\")\n                    return .notFound()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n            \n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTFail(\"Unexpected call to archiver\")\n                completion(.success(()))\n            })\n            \n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    rootCertPath: rootCertPath\n                )\n            )\n            \n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n            \n            await secondFetch.set(true)\n            \n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testUnsupportedArch() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { manifest, rootCertPath, rootPackage, swiftSyntax in\n            let httpClient = HTTPClient { request, progressHandler in\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    // Pretend it's not there.\n                    return .notFound()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTFail(\"Unexpected call to archiver\")\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .ubuntu_noble_x86_64,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testUnsupportedSwiftVersion() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { _, rootCertPath, rootPackage, swiftSyntax in\n            let httpClient = HTTPClient { request, progressHandler in\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    // Pretend it's a different swift version\n                    return .notFound()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTFail(\"Unexpected call to archiver\")\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testBadSignature() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { goodManifest, rootCertPath, rootPackage, swiftSyntax in\n            // Make a change in the manifest\n            var manifest = goodManifest.manifest\n            manifest.libraries[0].checksum = \"BAD\"\n            let badManifest = Workspace.SignedPrebuiltsManifest(\n                manifest: manifest,\n                signature: goodManifest.signature\n            )\n            let manifestData = try JSONEncoder().encode(badManifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTFail(\"Unexpected call to archiver\")\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                XCTAssertTrue(diagnostics.contains(where: { $0.message == \"Failed to decode prebuilt manifest: invalidSignature\" }))\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testBadChecksumHttp() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { manifest, rootCertPath, rootPackage, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let fakeArtifact = Data([56])\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: fakeArtifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTFail(\"Unexpected call to archiver\")\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testBadChecksumCache() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { manifest, rootCertPath, rootPackage, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let fakeArtifact = Data([56])\n            let cacheFile = try AbsolutePath(validating: \"/home/user/caches/org.swift.swiftpm/prebuilts/swift-syntax/\\(self.swiftVersion)-MacroSupport.zip\")\n            try fs.writeFileContents(cacheFile, data: fakeArtifact)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testBadManifest() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { manifest, _, rootPackage, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    let badManifestData = manifestData + Data(\"bad\".utf8)\n                    try fileSystem.writeFileContents(destination, data: badManifestData)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTFail(\"Unexpected call to archiver\")\n                completion(.success(()))\n            })\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver\n                )\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    func testDisabled() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: \"600.0.1\") { _, _, rootPackage, swiftSyntax in\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    rootPackage\n                ],\n                packages: [\n                    swiftSyntax\n                ]\n            )\n            \n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    // Test a macro that uses a library that doesn't use prebuilts which then uses a library that does works.\n    // Also test plugins work\n    func testIndirectLibrary() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n        let swiftSyntaxVersion = \"600.0.1\"\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: swiftSyntaxVersion) { manifest, rootCertPath, _, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let libraryURL = \"https://github.com/swiftlang/Library\"\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    .init(\n                        name: \"Foo\",\n                        targets: [\n                            MockTarget(\n                                name: \"FooMacros\",\n                                dependencies: [\n                                    .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                    .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\"),\n                                    .product(name: \"Intermediate\", package: \"Library\"),\n                                ],\n                                type: .macro\n                            ),\n                            MockTarget(\n                                name: \"Foo\",\n                                dependencies: [\"FooMacros\"]\n                            ),\n                            MockTarget(\n                                name: \"FooClient\",\n                                dependencies: [\n                                    \"Foo\",\n                                ],\n                                type: .executable\n                            ),\n                            MockTarget(\n                                name: \"FooTests\",\n                                dependencies: [\n                                    \"FooMacros\",\n                                    .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n                                ],\n                                type: .test\n                            ),\n                        ],\n                        products: [\n                            MockProduct(\n                                name: \"Library\",\n                                modules: [\n                                    \"Foo\",\n                                ]\n                            ),\n                        ],\n                        dependencies: [\n                            .sourceControl(\n                                url: \"https://github.com/swiftlang/swift-syntax\",\n                                requirement: .exact(try XCTUnwrap(Version(\"600.0.1\")))\n                            ),\n                            .sourceControl(\n                                url: libraryURL,\n                                requirement: .exact(try XCTUnwrap(Version(\"1.0.0\")))\n                            ),\n                        ]\n                    )\n                ],\n                packages: [\n                    MockPackage(\n                        name: \"Library\",\n                        url: libraryURL,\n                        targets: [\n                            MockTarget(\n                                name: \"Base\",\n                                dependencies: [\n                                    .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                ]\n                            ),\n                            MockTarget(\n                                name: \"Intermediate\",\n                                dependencies: [\n                                    \"Base\",\n                                ]\n                            ),\n                        ],\n                        products: [\n                            MockProduct(\n                                name: \"Intermediate\",\n                                modules: [\n                                    \"Intermediate\"\n                                ]\n                            ),\n                        ],\n                        dependencies: [\n                            .sourceControl(\n                                url: \"https://github.com/swiftlang/swift-syntax\",\n                                requirement: .exact(try XCTUnwrap(Version(\"600.0.1\")))\n                            )\n                        ],\n                        versions: [\"1.0.0\"]\n                    ),\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                ),\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error || $0.severity == .warning }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: true)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    // Test that if a library using prebuilts is exposed outside the root package that prebuilts are turned off\n    func testLeakyLibrary() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n        let swiftSyntaxVersion = \"600.0.1\"\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: swiftSyntaxVersion) { manifest, rootCertPath, _, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let libraryURL = \"https://github.com/swiftlang/Library\"\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    .init(\n                        name: \"Foo\",\n                        targets: [\n                            MockTarget(\n                                name: \"FooMacros\",\n                                dependencies: [\n                                    .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                    .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\"),\n                                    .product(name: \"Intermediate\", package: \"Library\"),\n                                ],\n                                type: .macro\n                            ),\n                            MockTarget(\n                                name: \"Foo\",\n                                dependencies: [\"FooMacros\"]\n                            ),\n                            MockTarget(\n                                name: \"FooClient\",\n                                dependencies: [\n                                    \"Foo\",\n                                    .product(name: \"Plugin\", package: \"Library\"),\n                                ],\n                                type: .executable\n                            ),\n                            MockTarget(\n                                name: \"FooTests\",\n                                dependencies: [\n                                    \"FooMacros\",\n                                    .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n                                ],\n                                type: .test\n                            ),\n                            MockTarget(\n                                name: \"Leaking\",\n                                dependencies: [\n                                    .product(name: \"Intermediate\", package: \"Library\"),\n                                ]\n                            )\n                        ],\n                        products: [\n                            MockProduct(\n                                name: \"Library\",\n                                modules: [\n                                    \"Foo\",\n                                    \"Leaking\"\n                                ]\n                            ),\n                        ],\n                        dependencies: [\n                            .sourceControl(\n                                url: \"https://github.com/swiftlang/swift-syntax\",\n                                requirement: .exact(try XCTUnwrap(Version(\"600.0.1\")))\n                            ),\n                            .sourceControl(\n                                url: libraryURL,\n                                requirement: .exact(try XCTUnwrap(Version(\"1.0.0\")))\n                            ),\n                        ]\n                    )\n                ],\n                packages: [\n                    MockPackage(\n                        name: \"Library\",\n                        url: libraryURL,\n                        targets: [\n                            MockTarget(\n                                name: \"Base\",\n                                dependencies: [\n                                    .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                ]\n                            ),\n                            MockTarget(\n                                name: \"Intermediate\",\n                                dependencies: [\n                                    \"Base\",\n                                ]\n                            ),\n                            MockTarget(\n                                name: \"Generator\",\n                                dependencies: [\n                                    \"Intermediate\"\n                                ],\n                                type: .executable\n                            ),\n                            MockTarget(\n                                name: \"Plugin\",\n                                dependencies: [\n                                    \"Generator\"\n                                ],\n                                type: .plugin,\n                                pluginCapability: .buildTool\n                            )\n                        ],\n                        products: [\n                            MockProduct(\n                                name: \"Intermediate\",\n                                modules: [\n                                    \"Intermediate\"\n                                ]\n                            ),\n                            MockProduct(\n                                name: \"Plugin\",\n                                modules: [\n                                    \"Plugin\",\n                                ],\n                                type: .plugin\n                            ),\n                        ],\n                        dependencies: [\n                            .sourceControl(\n                                url: \"https://github.com/swiftlang/swift-syntax\",\n                                requirement: .exact(try XCTUnwrap(Version(\"600.0.1\")))\n                            )\n                        ],\n                        versions: [\"1.0.0\"]\n                    ),\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                ),\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Foo\"]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error || $0.severity == .warning }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.rootPackages.first)\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooTests\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"FooClient\", usePrebuilt: false)\n            }\n        }\n    }\n\n    // Test that if a library using prebuilts is exposed outside root dependencies that prebuilts are turned off\n    func testRootDependency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n        let artifact = Data()\n        let swiftSyntaxVersion = \"600.0.1\"\n\n        try await with(fileSystem: fs, artifact: artifact, swiftSyntaxVersion: swiftSyntaxVersion) { manifest, rootCertPath, _, swiftSyntax in\n            let manifestData = try JSONEncoder().encode(manifest)\n\n            let httpClient = HTTPClient { request, progressHandler in\n                guard case .download(let fileSystem, let destination) = request.kind else {\n                    throw StringError(\"invalid request \\(request.kind)\")\n                }\n\n                if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion).json\" {\n                    try fileSystem.writeFileContents(destination, data: manifestData)\n                    return .okay()\n                } else if request.url == \"https://download.swift.org/prebuilts/swift-syntax/600.0.1/\\(self.swiftVersion)-MacroSupport.zip\" {\n                    try fileSystem.writeFileContents(destination, data: artifact)\n                    return .okay()\n                } else {\n                    XCTFail(\"Unexpected URL \\(request.url)\")\n                    return .notFound()\n                }\n            }\n\n            let archiver = MockArchiver(handler: { _, archivePath, destination, completion in\n                XCTAssertEqual(archivePath, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport.zip\"))\n                XCTAssertEqual(destination, sandbox.appending(components: \".build\", \"prebuilts\", \"swift-syntax\", \"600.0.1\", \"\\(self.swiftVersion)-MacroSupport\"))\n                completion(.success(()))\n            })\n\n            let libraryURL = \"https://github.com/swiftlang/Library\"\n\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [],\n                packages: [\n                    .init(\n                        name: \"Foo\",\n                        targets: [\n                            MockTarget(\n                                name: \"FooMacros\",\n                                dependencies: [\n                                    .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                    .product(name: \"SwiftCompilerPlugin\", package: \"swift-syntax\"),\n                                    .product(name: \"Intermediate\", package: \"Library\"),\n                                ],\n                                type: .macro\n                            ),\n                            MockTarget(\n                                name: \"Foo\",\n                                dependencies: [\"FooMacros\"]\n                            ),\n                            MockTarget(\n                                name: \"FooClient\",\n                                dependencies: [\n                                    \"Foo\",\n                                    .product(name: \"Plugin\", package: \"Library\"),\n                                ],\n                                type: .executable\n                            ),\n                            MockTarget(\n                                name: \"FooTests\",\n                                dependencies: [\n                                    \"FooMacros\",\n                                    .product(name: \"SwiftSyntaxMacrosTestSupport\", package: \"swift-syntax\"),\n                                ],\n                                type: .test\n                            ),\n                            MockTarget(\n                                name: \"Leaking\",\n                                dependencies: [\n                                    .product(name: \"Intermediate\", package: \"Library\"),\n                                ]\n                            )\n                        ],\n                        products: [\n                            MockProduct(\n                                name: \"Library\",\n                                modules: [\n                                    \"Foo\",\n                                    \"Leaking\"\n                                ]\n                            ),\n                        ],\n                        dependencies: [\n                            .sourceControl(\n                                url: \"https://github.com/swiftlang/swift-syntax\",\n                                requirement: .exact(try XCTUnwrap(Version(\"600.0.1\")))\n                            ),\n                            .sourceControl(\n                                url: libraryURL,\n                                requirement: .exact(try XCTUnwrap(Version(\"1.0.0\")))\n                            ),\n                        ],\n                        versions: [nil]\n                    ),\n                    MockPackage(\n                        name: \"Library\",\n                        url: libraryURL,\n                        targets: [\n                            MockTarget(\n                                name: \"Base\",\n                                dependencies: [\n                                    .product(name: \"SwiftSyntaxMacros\", package: \"swift-syntax\"),\n                                ]\n                            ),\n                            MockTarget(\n                                name: \"Intermediate\",\n                                dependencies: [\n                                    \"Base\",\n                                ]\n                            ),\n                            MockTarget(\n                                name: \"Generator\",\n                                dependencies: [\n                                    \"Intermediate\"\n                                ],\n                                type: .executable\n                            ),\n                            MockTarget(\n                                name: \"Plugin\",\n                                dependencies: [\n                                    \"Generator\"\n                                ],\n                                type: .plugin,\n                                pluginCapability: .buildTool\n                            )\n                        ],\n                        products: [\n                            MockProduct(\n                                name: \"Intermediate\",\n                                modules: [\n                                    \"Intermediate\"\n                                ]\n                            ),\n                            MockProduct(\n                                name: \"Plugin\",\n                                modules: [\n                                    \"Plugin\",\n                                ],\n                                type: .plugin\n                            ),\n                        ],\n                        dependencies: [\n                            .sourceControl(\n                                url: \"https://github.com/swiftlang/swift-syntax\",\n                                requirement: .exact(try XCTUnwrap(Version(\"600.0.1\")))\n                            )\n                        ],\n                        versions: [\"1.0.0\"]\n                    ),\n                    swiftSyntax\n                ],\n                prebuiltsManager: .init(\n                    swiftVersion: swiftVersion,\n                    httpClient: httpClient,\n                    archiver: archiver,\n                    hostPlatform: .macos_universal,\n                    rootCertPath: rootCertPath\n                ),\n            )\n\n            let rootDep = PackageDependency.fileSystem(identity: .plain(\"Foo\"), path: workspace.packagesDir.appending(\"Foo\"))\n            try await workspace.checkPackageGraph(roots: [], dependencies: [rootDep]) { modulesGraph, diagnostics in\n                XCTAssertTrue(diagnostics.filter({ $0.severity == .error || $0.severity == .warning }).isEmpty)\n                let rootPackage = try XCTUnwrap(modulesGraph.package(for: rootDep.identity))\n                try checkSettings(rootPackage, \"FooMacros\", usePrebuilt: false)\n                try checkSettings(rootPackage, \"Foo\", usePrebuilt: false)\n            }\n        }\n    }\n}\n\nextension String {\n    var fixwin: String {\n        #if os(Windows)\n        return self.replacingOccurrences(of: \"/\", with: \"\\\\\")\n        #else\n        return self\n        #endif\n    }\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/RegistryPackageContainerTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport PackageRegistry\nimport _InternalTestSupport\n@testable import Workspace\nimport XCTest\n\nimport struct TSCUtility.Version\n\nfinal class RegistryPackageContainerTests: XCTestCase {\n\n    override func setUpWithError() throws {\n        try XCTSkipOnWindows()\n    }\n\n    func testToolsVersionCompatibleVersions() async throws {\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n\n        let packageIdentity = PackageIdentity.plain(\"org.foo\")\n        let packageVersion = Version(\"1.0.0\")\n        let packagePath = AbsolutePath.root\n\n        func createProvider(_ toolsVersion: ToolsVersion) throws -> PackageContainerProvider {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: packageIdentity,\n                packageVersion: packageVersion,\n                packagePath: packagePath,\n                fileSystem: fs,\n                releasesRequestHandler: { request, _ in\n                    let metadata = RegistryClient.Serialization.PackageMetadata(\n                        releases: [\n                            \"1.0.0\":  .init(url: .none, problem: .none),\n                            \"1.0.1\":  .init(url: .none, problem: .none),\n                            \"1.0.2\":  .init(url: .none, problem: .none),\n                            \"1.0.3\":  .init(url: .none, problem: .none)\n                        ]\n                    )\n                    return HTTPClientResponse(\n                        statusCode: 200,\n                        headers: [\n                            \"Content-Version\": \"1\",\n                            \"Content-Type\": \"application/json\"\n                        ],\n                        body: try! JSONEncoder.makeWithDefaults().encode(metadata)\n                    )\n                },\n                manifestRequestHandler: { request, _ in\n                    let toolsVersion: ToolsVersion\n                    switch request.url.deletingLastPathComponent().lastPathComponent {\n                    case \"1.0.0\":\n                        toolsVersion = .v3\n                    case \"1.0.1\":\n                        toolsVersion = .v4\n                    case \"1.0.2\":\n                        toolsVersion = .v4_2\n                    case \"1.0.3\":\n                        toolsVersion = .v5_4\n                    default:\n                        toolsVersion = .current\n                    }\n                    return HTTPClientResponse(\n                        statusCode: 200,\n                        headers: [\n                            \"Content-Version\": \"1\",\n                            \"Content-Type\": \"text/x-swift\"\n                        ],\n                        body: Data(\"// swift-tools-version:\\(toolsVersion)\".utf8)\n                    )\n                }\n            )\n\n            return try Workspace._init(\n                fileSystem: fs,\n                environment: .mockEnvironment,\n                location: .init(forRootPackage: packagePath, fileSystem: fs),\n                customToolsVersion: toolsVersion,\n                customHostToolchain: .mockHostToolchain(fs),\n                customManifestLoader: MockManifestLoader(manifests: [:]),\n                customRegistryClient: registryClient\n            )\n        }\n\n        do {\n            let provider = try createProvider(.v4)\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref)\n            let versions = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(versions, [\"1.0.1\"])\n        }\n\n        do {\n            let provider = try createProvider(.v4_2)\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref)\n            let versions = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(versions, [\"1.0.2\", \"1.0.1\"])\n        }\n\n        do {\n            let provider = try createProvider(.v5_4)\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref)\n            let versions = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(versions, [\"1.0.3\", \"1.0.2\", \"1.0.1\"])\n        }\n    }\n\n    func testAlternateManifests() async throws {\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n\n        let packageIdentity = PackageIdentity.plain(\"org.foo\")\n        let packageVersion = Version(\"1.0.0\")\n        let packagePath = AbsolutePath.root\n\n        func createProvider(_ toolsVersion: ToolsVersion) throws -> PackageContainerProvider {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: packageIdentity,\n                packageVersion: packageVersion,\n                packagePath: packagePath,\n                fileSystem: fs,\n                manifestRequestHandler: { request, _ in\n                    return HTTPClientResponse(\n                        statusCode: 200,\n                        headers: [\n                            \"Content-Version\": \"1\",\n                            \"Content-Type\": \"text/x-swift\",\n                            \"Link\": \"\"\"\n                            \\(self.manifestLink(packageIdentity, .v5_4)),\n                            \\(self.manifestLink(packageIdentity, .v5_5)),\n                            \"\"\"\n                        ],\n                        body: Data(\"// swift-tools-version:\\(ToolsVersion.v5_3)\".utf8)\n                    )\n                }\n            )\n\n            return try Workspace._init(\n                fileSystem: fs,\n                environment: .mockEnvironment,\n                location: .init(forRootPackage: packagePath, fileSystem: fs),\n                customToolsVersion: toolsVersion,\n                customHostToolchain: .mockHostToolchain(fs),\n                customManifestLoader: MockManifestLoader(manifests: [:]),\n                customRegistryClient: registryClient\n            )\n        }\n\n        do {\n            let provider = try createProvider(.v5_2) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref)\n            let version = try await container.toolsVersion(for: packageVersion)\n            XCTAssertEqual(version, .v5_3)\n            let versions = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(versions, [])\n        }\n\n        do {\n            let provider = try createProvider(.v5_3) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref)\n            let version = try await container.toolsVersion(for: packageVersion)\n            XCTAssertEqual(version, .v5_3)\n            let versions = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(versions, [packageVersion])\n        }\n\n        do {\n            let provider = try createProvider(.v5_4) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref)\n            let version = try await container.toolsVersion(for: packageVersion)\n            XCTAssertEqual(version, .v5_4)\n            let versions = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(versions, [packageVersion])\n        }\n\n        do {\n            let provider = try createProvider(.v5_5) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref)\n            let version = try await container.toolsVersion(for: packageVersion)\n            XCTAssertEqual(version, .v5_5)\n            let versions = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(versions, [packageVersion])\n        }\n\n        do {\n            let provider = try createProvider(.v5_6) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref)\n            let version = try await container.toolsVersion(for: packageVersion)\n            XCTAssertEqual(version, .v5_5)\n            let versions = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(versions, [packageVersion])\n        }\n    }\n\n    func testLoadManifest() async throws {\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n\n        let packageIdentity = PackageIdentity.plain(\"org.foo\")\n        let packageVersion = Version(\"1.0.0\")\n        let packagePath = AbsolutePath.root\n\n        let v5_3_3 = ToolsVersion(string: \"5.3.3\")!\n\n        func createProvider(_ toolsVersion: ToolsVersion) throws -> PackageContainerProvider {\n            let supportedVersions = Set<ToolsVersion>([ToolsVersion.v5, .v5_3, v5_3_3, .v5_4, .v5_5])\n            let registryClient = try makeRegistryClient(\n                packageIdentity: packageIdentity,\n                packageVersion: packageVersion,\n                packagePath: packagePath,\n                fileSystem: fs,\n                manifestRequestHandler: { request, _ in\n                    let requestedVersionString = request.url.query?.spm_dropPrefix(\"swift-version=\")\n                    let requestedVersion = (requestedVersionString.flatMap{ ToolsVersion(string: $0) }) ?? .v5_3\n                    guard supportedVersions.contains(requestedVersion) else {\n                        throw StringError(\"invalid version \\(requestedVersion)\")\n                    }\n                    return HTTPClientResponse(\n                        statusCode: 200,\n                        headers: [\n                            \"Content-Version\": \"1\",\n                            \"Content-Type\": \"text/x-swift\",\n                            \"Link\": (supportedVersions.subtracting([requestedVersion])).map {\n                                self.manifestLink(packageIdentity, $0)\n                            }.joined(separator: \",\\n\")\n                        ],\n                        body: Data(\"// swift-tools-version:\\(requestedVersion)\".utf8)\n                    )\n                }\n            )\n\n            return try Workspace._init(\n                fileSystem: fs,\n                environment: .mockEnvironment,\n                location: .init(forRootPackage: packagePath, fileSystem: fs),\n                customToolsVersion: toolsVersion,\n                customHostToolchain: .mockHostToolchain(fs),\n                customManifestLoader: MockManifestLoader(),\n                customRegistryClient: registryClient\n            )\n\n            struct MockManifestLoader: ManifestLoaderProtocol {\n                func load(\n                    manifestPath: AbsolutePath,\n                    manifestToolsVersion: ToolsVersion,\n                    packageIdentity: PackageIdentity,\n                    packageKind: PackageReference.Kind,\n                    packageLocation: String,\n                    packageVersion: (version: Version?, revision: String?)?,\n                    identityResolver: IdentityResolver,\n                    dependencyMapper: DependencyMapper,\n                    fileSystem: FileSystem,\n                    observabilityScope: ObservabilityScope,\n                    delegateQueue: DispatchQueue\n                ) async throws -> Manifest {\n                    Manifest.createManifest(\n                        displayName: packageIdentity.description,\n                        path: manifestPath,\n                        packageKind: packageKind,\n                        packageIdentity: packageIdentity,\n                        packageLocation: packageLocation,\n                        platforms: [],\n                        toolsVersion: manifestToolsVersion\n                    )\n                }\n\n                func resetCache(observabilityScope: ObservabilityScope) {}\n                func purgeCache(observabilityScope: ObservabilityScope) {}\n            }\n        }\n\n        do {\n            let provider = try createProvider(.v5_3) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref) as! RegistryPackageContainer\n            let manifest = try await container.loadManifest(version: packageVersion)\n            XCTAssertEqual(manifest.toolsVersion, .v5_3)\n        }\n\n        do {\n            let provider = try createProvider(v5_3_3) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref) as! RegistryPackageContainer\n            let manifest = try await container.loadManifest(version: packageVersion)\n            XCTAssertEqual(manifest.toolsVersion, v5_3_3)\n        }\n\n        do {\n            let provider = try createProvider(.v5_4) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref) as! RegistryPackageContainer\n            let manifest = try await container.loadManifest(version: packageVersion)\n            XCTAssertEqual(manifest.toolsVersion, .v5_4)\n        }\n\n        do {\n            let provider = try createProvider(.v5_5) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref) as! RegistryPackageContainer\n            let manifest = try await container.loadManifest(version: packageVersion)\n            XCTAssertEqual(manifest.toolsVersion, .v5_5)\n        }\n\n        do {\n            let provider = try createProvider(.v5_6) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref) as! RegistryPackageContainer\n            let manifest = try await container.loadManifest(version: packageVersion)\n            XCTAssertEqual(manifest.toolsVersion, .v5_5)\n        }\n\n        do {\n            let provider = try createProvider(.v5) // the version of the alternate\n            let ref = PackageReference.registry(identity: packageIdentity)\n            let container = try await provider.getContainer(for: ref) as! RegistryPackageContainer\n            let manifest = try await container.loadManifest(version: packageVersion)\n            XCTAssertEqual(manifest.toolsVersion, .v5)\n        }\n    }\n\n    func makeRegistryClient(\n        packageIdentity: PackageIdentity,\n        packageVersion: Version,\n        packagePath: AbsolutePath,\n        fileSystem: FileSystem,\n        configuration: PackageRegistry.RegistryConfiguration? = .none,\n        releasesRequestHandler: HTTPClient.Implementation? = .none,\n        versionMetadataRequestHandler: HTTPClient.Implementation? = .none,\n        manifestRequestHandler: HTTPClient.Implementation? = .none,\n        downloadArchiveRequestHandler: HTTPClient.Implementation? = .none,\n        archiver: Archiver? = .none\n    ) throws -> RegistryClient {\n        let jsonEncoder = JSONEncoder.makeWithDefaults()\n        let fingerprintStorage = MockPackageFingerprintStorage()\n\n        guard let registryIdentity = packageIdentity.registry else {\n            throw StringError(\"Invalid package identifier: '\\(packageIdentity)'\")\n        }\n\n        var configuration = configuration\n        if configuration == nil {\n            configuration = PackageRegistry.RegistryConfiguration()\n            configuration!.defaultRegistry = .init(url: \"http://localhost\", supportsAvailability: false)\n        }\n\n        let releasesRequestHandler = releasesRequestHandler ?? { request, _ in\n            let metadata = RegistryClient.Serialization.PackageMetadata(\n                releases: [packageVersion.description:  .init(url: .none, problem: .none)]\n            )\n            return HTTPClientResponse(\n                statusCode: 200,\n                headers: [\n                    \"Content-Version\": \"1\",\n                    \"Content-Type\": \"application/json\"\n                ],\n                body: try! jsonEncoder.encode(metadata)\n            )\n        }\n\n        let versionMetadataRequestHandler = versionMetadataRequestHandler ?? { request, _ in\n            let metadata = RegistryClient.Serialization.VersionMetadata(\n                id: packageIdentity.description,\n                version: packageVersion.description,\n                resources: [\n                    .init(\n                        name: \"source-archive\",\n                        type: \"application/zip\",\n                        checksum: \"\",\n                        signing: nil\n                    )\n                ],\n                metadata: .init(description: \"\"),\n                publishedAt: nil\n            )\n            return HTTPClientResponse(\n                statusCode: 200,\n                headers: [\n                    \"Content-Version\": \"1\",\n                    \"Content-Type\": \"application/json\"\n                ],\n                body: try! jsonEncoder.encode(metadata)\n            )\n        }\n\n        let manifestRequestHandler = manifestRequestHandler ?? { request, _ in\n            return HTTPClientResponse(\n                statusCode: 200,\n                headers: [\n                    \"Content-Version\": \"1\",\n                    \"Content-Type\": \"text/x-swift\"\n                ],\n                body: Data(\"// swift-tools-version:\\(ToolsVersion.current)\".utf8)\n            )\n        }\n\n        let downloadArchiveRequestHandler = downloadArchiveRequestHandler ?? { request, _ in\n            // meh\n            let path = packagePath\n                .appending(components: \".build\", \"registry\", \"downloads\", registryIdentity.scope.description, registryIdentity.name.description)\n                .appending(\"\\(packageVersion).zip\")\n            try! fileSystem.createDirectory(path.parentDirectory, recursive: true)\n            try! fileSystem.writeFileContents(path, string: \"\")\n\n            return HTTPClientResponse(\n                statusCode: 200,\n                headers: [\n                    \"Content-Version\": \"1\",\n                    \"Content-Type\": \"application/zip\"\n                ],\n                body: Data(\"\".utf8)\n            )\n        }\n\n        let archiver = archiver ?? MockArchiver(handler: { archiver, from, to, completion in\n            do {\n                try fileSystem.createDirectory(to.appending(\"top\"), recursive: true)\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        return RegistryClient(\n            configuration: configuration!,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: .strict,\n            skipSignatureValidation: false,\n            signingEntityStorage: .none,\n            signingEntityCheckingMode: .strict,\n            authorizationProvider: .none,\n            customHTTPClient: HTTPClient(configuration: .init(), implementation: { request, progress in\n                var pathComponents = request.url.pathComponents\n                if pathComponents.first == \"/\" {\n                    pathComponents = Array(pathComponents.dropFirst())\n                }\n                guard pathComponents.count >= 2 else {\n                    throw StringError(\"invalid url \\(request.url)\")\n                }\n                guard pathComponents[0] == registryIdentity.scope.description else {\n                    throw StringError(\"invalid url \\(request.url)\")\n                }\n                guard pathComponents[1] == registryIdentity.name.description else {\n                    throw StringError(\"invalid url \\(request.url)\")\n                }\n\n                switch pathComponents.count {\n                case 2:\n                    return try await releasesRequestHandler(request, progress)\n                case 3 where pathComponents[2].hasSuffix(\".zip\"):\n                    return try await downloadArchiveRequestHandler(request, progress)\n                case 3:\n                    return try await versionMetadataRequestHandler(request, progress)\n                case 4 where pathComponents[3].hasSuffix(\".swift\"):\n                    return try await manifestRequestHandler(request, progress)\n                default:\n                    throw StringError(\"unexpected url \\(request.url)\")\n                }\n            }),\n            customArchiverProvider: { _ in archiver },\n            delegate: .none,\n            checksumAlgorithm: MockHashAlgorithm()\n        )\n    }\n\n    private func manifestLink(_ identity: PackageIdentity, _ version: ToolsVersion) -> String {\n        guard let registryIdentity = identity.registry else {\n            preconditionFailure(\"invalid registry identity: '\\(identity)'\")\n        }\n        let versionString = if version.patch == 0 && version.minor == 0 {\n            \"\\(version.major)\"\n        } else if version.patch == 0 {\n            \"\\(version.major).\\(version.minor)\"\n        } else {\n            version.description\n        }\n        return \"<http://localhost/\\(registryIdentity.scope)/\\(registryIdentity.name)/\\(version)/\\(Manifest.filename)?swift-version=\\(version)>; rel=\\\"alternate\\\"; filename=\\\"\\(Manifest.basename)@swift-\\(versionString).swift\\\"; swift-tools-version=\\\"\\(version)\\\"\"\n    }\n}\n\nextension PackageContainerProvider {\n    fileprivate func getContainer(for package: PackageReference, updateStrategy: ContainerUpdateStrategy = .always) async throws -> PackageContainer {\n        try await self.getContainer(\n            for: package,\n            updateStrategy: updateStrategy,\n            observabilityScope: ObservabilitySystem.NOOP\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/ResolvedPackagesStoreTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport PackageModel\nimport PackageGraph\nimport _InternalTestSupport\nimport SourceControl\nimport Workspace\nimport XCTest\n\nimport struct TSCUtility.Version\n\nfinal class ResolvedPackagesStoreTests: XCTestCase {\n\n    let v1: Version = \"1.0.0\"\n\n    func testBasics() throws {\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n\n        do {\n            let fooPath = AbsolutePath(\"/foo\")\n            let foo = PackageIdentity(path: fooPath)\n            let fooRef = PackageReference.localSourceControl(identity: foo, path: fooPath)\n\n            let barPath = AbsolutePath(\"/bar\")\n            let bar = PackageIdentity(path: barPath)\n            let barRef = PackageReference.localSourceControl(identity: bar, path: barPath)\n\n            var store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n            \n            // `Package.resolved` file should not be created right now.\n            XCTAssert(!fs.exists(packageResolvedFile))\n            XCTAssert(store.resolvedPackages.isEmpty)\n\n            let revision = UUID().uuidString\n            let state = ResolvedPackagesStore.ResolutionState.version(v1, revision: revision)\n            store.track(packageRef: fooRef, state: state)\n            try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n\n            XCTAssert(fs.exists(packageResolvedFile))\n\n            // Load the store again from disk.\n            let store2 = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n            // Test basics on the store.\n            for s in [store, store2] {\n                XCTAssert(s.resolvedPackages.count == 1)\n                XCTAssertEqual(s.resolvedPackages[bar], nil)\n                let fooResolution = s.resolvedPackages[foo]!\n                XCTAssertEqual(fooResolution.packageRef, fooRef)\n                XCTAssertEqual(fooResolution.state, .version(v1, revision: revision))\n                XCTAssertEqual(fooResolution.state.description, v1.description)\n            }\n\n            // We should be able to resolve again.\n            store.track(packageRef: fooRef, state: state)\n            store.track(\n                packageRef: fooRef,\n                state: .version(\"1.0.2\", revision: revision)\n            )\n            store.track(packageRef: barRef, state: state)\n            try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n\n            store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n            XCTAssert(store.resolvedPackages.count == 2)\n\n        }\n\n        // Test source control version resolution.\n\n        do {\n            let path = AbsolutePath(\"/foo\")\n            let identity = PackageIdentity(path: path)\n            let revision = UUID().uuidString\n\n            var store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n            store.track(\n                packageRef: .localSourceControl(identity: identity, path: path),\n                state: .version(\"1.2.3\", revision: revision)\n            )\n            try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n            store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n\n            let resolution = store.resolvedPackages[identity]!\n            XCTAssertEqual(resolution.state, .version(\"1.2.3\", revision: revision))\n            XCTAssertEqual(resolution.state.description, \"1.2.3\")\n        }\n\n        // Test source control branch resolution.\n\n        do {\n            let path = AbsolutePath(\"/foo\")\n            let identity = PackageIdentity(path: path)\n            let revision = UUID().uuidString\n\n            var store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n            store.track(\n                packageRef: .localSourceControl(identity: identity, path: path),\n                state: .branch(name: \"develop\", revision: revision)\n            )\n            try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n            store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n\n            let resolution = store.resolvedPackages[identity]!\n            XCTAssertEqual(resolution.state, .branch(name: \"develop\", revision: revision))\n            XCTAssertEqual(resolution.state.description, \"develop\")\n        }\n\n        // Test source control revision resolution.\n\n        do {\n            let path = AbsolutePath(\"/foo\")\n            let identity = PackageIdentity(path: path)\n            let revision = UUID().uuidString\n\n            var store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n            store.track(\n                packageRef: .localSourceControl(identity: identity, path: path),\n                state: .revision(revision)\n            )\n            try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n            store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n\n            let resolution = store.resolvedPackages[identity]!\n            XCTAssertEqual(resolution.state, .revision(revision))\n            XCTAssertEqual(resolution.state.description, revision)\n        }\n\n        // Test registry resolution.\n\n        do {\n            let identity = PackageIdentity.plain(\"baz.baz\") // FIXME: use scope identifier\n\n            var store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n            store.track(\n                packageRef: .registry(identity: identity),\n                state: .version(\"1.2.3\", revision: .none)\n            )\n            try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n            store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n\n            let resolution = store.resolvedPackages[identity]!\n            XCTAssertEqual(resolution.state, .version(\"1.2.3\", revision: .none))\n            XCTAssertEqual(resolution.state.description, \"1.2.3\")\n        }\n    }\n\n    func testLoadingSchema1() throws {\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n\n        try fs.writeFileContents(packageResolvedFile, string:\n            \"\"\"\n            {\n              \"version\": 1,\n              \"object\": {\n                \"pins\": [\n                  {\n                    \"package\": \"Clang_C\",\n                    \"repositoryURL\": \"https://github.com/something/Clang_C.git\",\n                    \"state\": {\n                      \"branch\": null,\n                      \"revision\": \"90a9574276f0fd17f02f58979423c3fd4d73b59e\",\n                      \"version\": \"1.0.2\",\n                    }\n                  },\n                  {\n                    \"package\": \"Commandant\",\n                    \"repositoryURL\": \"https://github.com/something/Commandant.git\",\n                    \"state\": {\n                      \"branch\": null,\n                      \"revision\": \"c281992c31c3f41c48b5036c5a38185eaec32626\",\n                      \"version\": \"0.12.0\"\n                    }\n                  }\n                ]\n              }\n            }\n            \"\"\"\n        )\n\n        let store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n        XCTAssertEqual(store.resolvedPackages.keys.map { $0.description }.sorted(), [\"clang_c\", \"commandant\"])\n    }\n\n    func testLoadingSchema2() throws {\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n\n        try fs.writeFileContents(packageResolvedFile, string:\n            \"\"\"\n            {\n                \"version\": 2,\n                \"pins\": [\n                  {\n                    \"identity\": \"clang_c\",\n                    \"kind\": \"remoteSourceControl\",\n                    \"location\": \"https://github.com/something/Clang_C.git\",\n                    \"state\": {\n                      \"revision\": \"90a9574276f0fd17f02f58979423c3fd4d73b59e\",\n                      \"version\": \"1.0.2\",\n                    }\n                  },\n                  {\n                    \"identity\": \"commandant\",\n                    \"kind\": \"remoteSourceControl\",\n                    \"location\": \"https://github.com/something/Commandant.git\",\n                    \"state\": {\n                      \"revision\": \"c281992c31c3f41c48b5036c5a38185eaec32626\",\n                      \"version\": \"0.12.0\"\n                    }\n                  },\n                  {\n                    \"identity\": \"scope.package\",\n                    \"kind\": \"registry\",\n                    \"location\": \"\",\n                    \"state\": {\n                      \"version\": \"0.12.0\"\n                    }\n                  }\n                ]\n            }\n            \"\"\"\n        )\n\n        let store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n        XCTAssertEqual(store.resolvedPackages.keys.map { $0.description }.sorted(), [\"clang_c\", \"commandant\", \"scope.package\"])\n    }\n\n    func testLoadingSchema3() throws {\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n\n        let originHash = UUID().uuidString\n\n        try fs.writeFileContents(packageResolvedFile, string:\n            \"\"\"\n            {\n                \"version\": 3,\n                \"originHash\": \"\\(originHash)\",\n                \"pins\": [\n                  {\n                    \"identity\": \"clang_c\",\n                    \"kind\": \"remoteSourceControl\",\n                    \"location\": \"https://github.com/something/Clang_C.git\",\n                    \"state\": {\n                      \"revision\": \"90a9574276f0fd17f02f58979423c3fd4d73b59e\",\n                      \"version\": \"1.0.2\",\n                    }\n                  },\n                  {\n                    \"identity\": \"commandant\",\n                    \"kind\": \"remoteSourceControl\",\n                    \"location\": \"https://github.com/something/Commandant.git\",\n                    \"state\": {\n                      \"revision\": \"c281992c31c3f41c48b5036c5a38185eaec32626\",\n                      \"version\": \"0.12.0\"\n                    }\n                  },\n                  {\n                    \"identity\": \"scope.package\",\n                    \"kind\": \"registry\",\n                    \"location\": \"\",\n                    \"state\": {\n                      \"version\": \"0.12.0\"\n                    }\n                  }\n                ]\n            }\n            \"\"\"\n        )\n\n        let store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n        XCTAssertEqual(store.resolvedPackages.keys.map { $0.description }.sorted(), [\"clang_c\", \"commandant\", \"scope.package\"])\n        XCTAssertEqual(store.originHash, originHash)\n    }\n\n    func testLoadingUnknownSchemaVersion() throws {\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n\n        let version = -1\n        try fs.writeFileContents(packageResolvedFile, string: \"{ \\\"version\\\": \\(version) }\");\n\n        XCTAssertThrowsError(try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()), \"error expected\", { error in\n            XCTAssertEqual(\"\\(error)\", \"\\(packageResolvedFile) file is corrupted or malformed; fix or delete the file to continue: unknown 'Package.resolved' version '\\(version)' at '\\(packageResolvedFile)'.\")\n        })\n\n    }\n\n    func testLoadingBadFormat() throws {\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n\n        try fs.writeFileContents(packageResolvedFile, string: \"boom\")\n\n        XCTAssertThrowsError(try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init()), \"error expected\", { error in\n            XCTAssertMatch(\"\\(error)\", .contains(\"\\(packageResolvedFile) file is corrupted or malformed; fix or delete the file to continue\"))\n        })\n    }\n\n    func testEmptyPackageResolved() throws {\n        let fs = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n        let store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fs, mirrors: .init())\n\n        try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n        XCTAssertFalse(fs.exists(packageResolvedFile))\n\n        let fooPath = AbsolutePath(\"/foo\")\n        let foo = PackageIdentity(path: fooPath)\n        let fooRef = PackageReference.localSourceControl(identity: foo, path: fooPath)\n        let revision = \"81513c8fd220cf1ed1452b98060cd80d3725c5b7\"\n        store.track(packageRef: fooRef, state: .version(v1, revision: revision))\n\n        XCTAssert(!fs.exists(packageResolvedFile))\n\n        try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n        XCTAssert(fs.exists(packageResolvedFile))\n\n        store.reset()\n        try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n        XCTAssertFalse(fs.exists(packageResolvedFile))\n    }\n\n    func testResolutionWithMirrors() throws {\n        let fooURL = SourceControlURL(\"https://github.com/corporate/foo.git\")\n        let fooIdentity = PackageIdentity(url: fooURL)\n        let fooMirroredURL = SourceControlURL(\"https://github.corporate.com/team/foo.git\")\n\n        let barURL = SourceControlURL(\"https://github.com/corporate/baraka.git\")\n        let barIdentity = PackageIdentity(url: barURL)\n        let barMirroredURL = SourceControlURL(\"https://github.corporate.com/team/bar.git\")\n        let barMirroredIdentity = PackageIdentity(url: barMirroredURL)\n\n        let bazURL = SourceControlURL(\"https://github.com/cool/baz.git\")\n        let bazIdentity = PackageIdentity(url: bazURL)\n\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: fooMirroredURL.absoluteString, for: fooURL.absoluteString)\n        try mirrors.set(mirror: barMirroredURL.absoluteString, for: barURL.absoluteString)\n\n        let fileSystem = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n\n        let store = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: mirrors)\n\n        store.track(packageRef: .remoteSourceControl(identity: fooIdentity, url: fooMirroredURL),\n                  state: .version(v1, revision: \"foo-revision\"))\n        store.track(packageRef: .remoteSourceControl(identity: barIdentity, url: barMirroredURL),\n                  state: .version(v1, revision: \"bar-revision\"))\n        store.track(packageRef: .remoteSourceControl(identity: bazIdentity, url: bazURL),\n                  state: .version(v1, revision: \"baz-revision\"))\n\n        XCTAssert(store.resolvedPackages.count == 3)\n        XCTAssertEqual(store.resolvedPackages[fooIdentity]!.packageRef.kind, .remoteSourceControl(fooMirroredURL))\n        XCTAssertEqual(store.resolvedPackages[barIdentity]!.packageRef.kind, .remoteSourceControl(barMirroredURL))\n        XCTAssertNil(store.resolvedPackages[barMirroredIdentity])\n        XCTAssertEqual(store.resolvedPackages[bazIdentity]!.packageRef.kind, .remoteSourceControl(bazURL))\n\n        try store.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n        XCTAssert(fileSystem.exists(packageResolvedFile))\n\n        let content: String = try fileSystem.readFileContents(packageResolvedFile)\n        XCTAssertMatch(content, .contains(fooURL.absoluteString))\n        XCTAssertNoMatch(content, .contains(fooMirroredURL.absoluteString))\n\n        // Load the store again from disk, with no mirrors\n        let store2 = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: .init())\n        XCTAssert(store2.resolvedPackages.count == 3)\n        XCTAssertEqual(store2.resolvedPackages[fooIdentity]!.packageRef.kind, .remoteSourceControl(fooURL))\n        XCTAssertEqual(store2.resolvedPackages[barIdentity]!.packageRef.kind, .remoteSourceControl(barURL))\n        XCTAssertEqual(store2.resolvedPackages[bazIdentity]!.packageRef.kind, .remoteSourceControl(bazURL))\n\n        // Load the store again from disk, with mirrors\n        let store3 = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: mirrors)\n        XCTAssert(store3.resolvedPackages.count == 3)\n        XCTAssertEqual(store3.resolvedPackages, store.resolvedPackages)\n    }\n\n    func testResolutionWithMirrorsDeterminism() throws {\n        let fooIdentity = PackageIdentity.plain(\"foo\")\n        let fooURL1 = SourceControlURL(\"https://github.com/corporate/foo\")\n        let fooURL2 = SourceControlURL(\"https://github.com/corporate/foo.git\")\n        let fooURL3 = SourceControlURL(\"https://github.com/old-corporate/foo\")\n        let fooURL4 = SourceControlURL(\"https://github.com/old-corporate/foo.git\")\n        let fooMirroredURL = SourceControlURL(\"https://github.corporate.com/team/foo\")\n\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: fooMirroredURL.absoluteString, for: fooURL1.absoluteString)\n        try mirrors.set(mirror: fooMirroredURL.absoluteString, for: fooURL2.absoluteString)\n        try mirrors.set(mirror: fooMirroredURL.absoluteString, for: fooURL3.absoluteString)\n        try mirrors.set(mirror: fooMirroredURL.absoluteString, for: fooURL4.absoluteString)\n\n        let fileSystem = InMemoryFileSystem()\n        let packageResolvedFile = AbsolutePath(\"/Package.resolved\")\n\n        let store1 = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: mirrors)\n        store1.track(\n            packageRef: .remoteSourceControl(identity: fooIdentity, url: fooMirroredURL),\n            state: .version(v1, revision: \"revision\")\n        )\n\n        XCTAssert(store1.resolvedPackages.count == 1)\n        XCTAssertEqual(store1.resolvedPackages[fooIdentity]!.packageRef.kind, .remoteSourceControl(fooMirroredURL))\n\n        try store1.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n        XCTAssert(fileSystem.exists(packageResolvedFile))\n\n        let content: String = try fileSystem.readFileContents(packageResolvedFile)\n        XCTAssertMatch(content, .contains(fooURL1.absoluteString))\n        XCTAssertNoMatch(content, .contains(fooURL2.absoluteString))\n        XCTAssertNoMatch(content, .contains(fooURL3.absoluteString))\n        XCTAssertNoMatch(content, .contains(fooURL4.absoluteString))\n        XCTAssertNoMatch(content, .contains(fooMirroredURL.absoluteString))\n\n        // Load the store again from disk, with no mirrors\n        let store2 = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: .init())\n        XCTAssert(store2.resolvedPackages.count == 1)\n        XCTAssertEqual(store2.resolvedPackages[fooIdentity]!.packageRef.kind, .remoteSourceControl(fooURL1))\n\n        // Load the store again from disk, with mirrors\n        let store3 = try ResolvedPackagesStore(packageResolvedFile: packageResolvedFile, workingDirectory: .root, fileSystem: fileSystem, mirrors: mirrors)\n        XCTAssert(store3.resolvedPackages.count == 1)\n        XCTAssertEqual(store3.resolvedPackages, store1.resolvedPackages)\n    }\n\n    func testMirrorsDeterminism() throws {\n        let URL1 = URL(\"https://github.com/corporate/foo\")\n        let URL2 = URL(\"https://github.com/corporate/foo.git\")\n        let URL3 = URL(\"https://github.com/old-corporate/foo\")\n        let URL4 = URL(\"https://github.com/old-corporate/foo.git\")\n        let mirroredURL = URL(\"https://github.corporate.com/team/foo\")\n\n        do {\n            let mirrors = try DependencyMirrors([\n                URL1.absoluteString: mirroredURL.absoluteString,\n                URL2.absoluteString: mirroredURL.absoluteString,\n                URL3.absoluteString: mirroredURL.absoluteString,\n                URL4.absoluteString: mirroredURL.absoluteString\n            ])\n\n            XCTAssertEqual(mirrors.mirror(for: URL2.absoluteString), mirroredURL.absoluteString)\n            // reverse index is sorted by \"visited\", then alphabetically\n            XCTAssertEqual(mirrors.original(for: mirroredURL.absoluteString), URL2.absoluteString)\n        }\n\n        do {\n            let mirrors = try DependencyMirrors([\n                URL1.absoluteString: mirroredURL.absoluteString,\n                URL2.absoluteString: mirroredURL.absoluteString,\n                URL3.absoluteString: mirroredURL.absoluteString,\n                URL4.absoluteString: mirroredURL.absoluteString\n            ])\n\n            XCTAssertEqual(mirrors.mirror(for: URL3.absoluteString), mirroredURL.absoluteString)\n            // reverse index is sorted by \"visited\", then alphabetically\n            XCTAssertEqual(mirrors.original(for: mirroredURL.absoluteString), URL3.absoluteString)\n        }\n\n        do {\n            let mirrors = try DependencyMirrors([\n                URL1.absoluteString: mirroredURL.absoluteString,\n                URL2.absoluteString: mirroredURL.absoluteString,\n                URL3.absoluteString: mirroredURL.absoluteString,\n                URL4.absoluteString: mirroredURL.absoluteString\n            ])\n\n            XCTAssertEqual(mirrors.mirror(for: URL2.absoluteString), mirroredURL.absoluteString)\n            XCTAssertEqual(mirrors.mirror(for: URL3.absoluteString), mirroredURL.absoluteString)\n            // reverse index is sorted by \"visited\", then alphabetically\n            XCTAssertEqual(mirrors.original(for: mirroredURL.absoluteString), URL2.absoluteString)\n        }\n\n        do {\n            let mirrors = try DependencyMirrors([\n                URL1.absoluteString: mirroredURL.absoluteString,\n                URL2.absoluteString: mirroredURL.absoluteString,\n                URL3.absoluteString: mirroredURL.absoluteString,\n                URL4.absoluteString: mirroredURL.absoluteString\n            ])\n\n            XCTAssertEqual(mirrors.mirror(for: URL3.absoluteString), mirroredURL.absoluteString)\n            XCTAssertEqual(mirrors.mirror(for: URL2.absoluteString), mirroredURL.absoluteString)\n            // reverse index is sorted by \"visited\", then alphabetically\n            XCTAssertEqual(mirrors.original(for: mirroredURL.absoluteString), URL3.absoluteString)\n        }\n\n        do {\n            let mirrors = try DependencyMirrors([\n                URL1.absoluteString: mirroredURL.absoluteString,\n                URL2.absoluteString: mirroredURL.absoluteString,\n                URL3.absoluteString: mirroredURL.absoluteString,\n                URL4.absoluteString: mirroredURL.absoluteString\n            ])\n\n            // reverse index is sorted by \"visited\", then alphabetically\n            XCTAssertEqual(mirrors.original(for: mirroredURL.absoluteString), URL1.absoluteString)\n        }\n    }\n\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/SourceControlPackageContainerTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _Concurrency\nimport Foundation\nimport PackageGraph\nimport PackageLoading\nimport PackageModel\nimport SourceControl\nimport _InternalTestSupport\n@testable import Workspace\nimport XCTest\n\nimport enum TSCUtility.Git\nimport struct TSCUtility.Version\n\nprivate class MockRepository: Repository {\n    /// The fake location of the repository.\n    let location: RepositorySpecifier.Location\n\n    /// The known repository versions, as a map of tags to manifests.\n    let versions: [Version: Manifest]\n\n    let fs: FileSystem\n\n    let packageRef: PackageReference\n\n    init(fs: FileSystem, path: AbsolutePath, versions: [Version: Manifest]) {\n        self.fs = fs\n        self.location = .path(path)\n        self.packageRef = .localSourceControl(identity: PackageIdentity(path: path), path: path)\n        self.versions = versions\n    }\n\n    init(fs: FileSystem, url: SourceControlURL, versions: [Version: Manifest]) {\n        self.fs = fs\n        self.location = .url(url)\n        self.packageRef = .remoteSourceControl(identity: PackageIdentity(url: url), url: url)\n        self.versions = versions\n    }\n\n    var specifier: RepositorySpecifier {\n        return RepositorySpecifier(location: self.location)\n    }\n\n    func getTags() throws -> [String] {\n        return self.versions.keys.map { String(describing: $0) }\n    }\n\n    func resolveRevision(tag: String) throws -> Revision {\n        assert(self.versions.index(forKey: Version(tag)!) != nil)\n        return Revision(identifier: tag)\n    }\n\n    func resolveRevision(identifier: String) throws -> Revision {\n        fatalError(\"Unexpected API call\")\n    }\n\n    func fetch() throws {\n        fatalError(\"Unexpected API call\")\n    }\n\n    func exists(revision: Revision) -> Bool {\n        fatalError(\"Unexpected API call\")\n    }\n\n    func remove() throws {\n        fatalError(\"Unexpected API call\")\n    }\n\n    func openFileView(revision: Revision) throws -> FileSystem {\n        assert(self.versions.index(forKey: Version(revision.identifier)!) != nil)\n        // This is used for reading the tools version.\n        return self.fs\n    }\n\n    public func openFileView(tag: String) throws -> FileSystem {\n        let revision = try self.resolveRevision(tag: tag)\n        return try self.openFileView(revision: revision)\n    }\n}\n\nprivate class MockRepositoryManagerDelegate: RepositoryManager.Delegate {\n    var fetched = ThreadSafeArrayStore<RepositorySpecifier>()\n    var updated = ThreadSafeArrayStore<RepositorySpecifier>()\n\n    func willFetch(package: PackageIdentity, repository: RepositorySpecifier, details: RepositoryManager.FetchDetails) {\n        self.fetched.append(repository)\n    }\n\n    func fetching(package: PackageIdentity, repository: RepositorySpecifier, objectsFetched: Int, totalObjectsToFetch: Int) {}\n\n    func didFetch(package: PackageIdentity, repository: RepositorySpecifier, result: Result<RepositoryManager.FetchDetails, Error>, duration: DispatchTimeInterval) {}\n\n    func willUpdate(package: PackageIdentity, repository: RepositorySpecifier) {\n        self.updated.append(repository)\n    }\n\n    func didUpdate(package: PackageIdentity, repository: RepositorySpecifier, duration: DispatchTimeInterval) {}\n\n    func reset() {\n        self.fetched.clear()\n        self.updated.clear()\n    }\n}\n\n// Some handy versions & ranges.\n//\n// The convention is that the name matches how specific the version is, so \"v1\"\n// means \"any 1.?.?\", and \"v1_1\" means \"any 1.1.?\".\n\nprivate let v1: Version = \"1.0.0\"\nprivate let v2: Version = \"2.0.0\"\nprivate let v1Range: VersionSetSpecifier = .range(\"1.0.0\" ..< \"2.0.0\")\n\nfinal class SourceControlPackageContainerTests: XCTestCase {\n    func testVprefixVersions() async throws {\n        try XCTSkipOnWindows(because: \"\"\"\n        https://github.com/swiftlang/swift-package-manager/issues/8578\n        \"\"\")\n\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n\n        let repoPath = AbsolutePath.root\n        let filePath = repoPath.appending(\"Package.swift\")\n\n        let specifier = RepositorySpecifier(path: repoPath)\n        let repo = InMemoryGitRepository(path: repoPath, fs: fs)\n        try repo.createDirectory(repoPath, recursive: true)\n        try repo.writeFileContents(filePath, string: \"// swift-tools-version:\\(ToolsVersion.current)\\n\")\n        try repo.commit()\n        try repo.tag(name: \"v1.0.0\")\n        try repo.tag(name: \"v1.0.1\")\n        try repo.tag(name: \"v1.0.2\")\n        try repo.tag(name: \"v1.0.3\")\n        try repo.tag(name: \"v2.0.3\")\n\n        let inMemRepoProvider = InMemoryGitRepositoryProvider()\n        inMemRepoProvider.add(specifier: specifier, repository: repo)\n\n        let p = AbsolutePath.root.appending(\"repoManager\")\n        try fs.createDirectory(p, recursive: true)\n        let repositoryManager = RepositoryManager(\n            fileSystem: fs,\n            path: p,\n            provider: inMemRepoProvider,\n            delegate: MockRepositoryManagerDelegate()\n        )\n\n        let provider = try Workspace._init(\n            fileSystem: fs,\n            environment: .mockEnvironment,\n            location: .init(forRootPackage: repoPath, fileSystem: fs),\n            customHostToolchain: .mockHostToolchain(fs),\n            customManifestLoader: MockManifestLoader(manifests: [:]),\n            customRepositoryManager: repositoryManager\n        )\n\n        let ref = PackageReference.localSourceControl(identity: PackageIdentity(path: repoPath), path: repoPath)\n        let container = try await provider.getContainer(for: ref)\n        let v = try await container.toolsVersionsAppropriateVersionsDescending()\n        XCTAssertEqual(v, [\"2.0.3\", \"1.0.3\", \"1.0.2\", \"1.0.1\", \"1.0.0\"])\n    }\n\n    func testVersions() async throws {\n        try XCTSkipOnWindows(because: \"\"\"\n        https://github.com/swiftlang/swift-package-manager/issues/8578\n        \"\"\")\n\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n\n        let repoPath = AbsolutePath.root\n        let filePath = repoPath.appending(\"Package.swift\")\n\n        let specifier = RepositorySpecifier(path: repoPath)\n        let repo = InMemoryGitRepository(path: repoPath, fs: fs)\n\n        try repo.createDirectory(repoPath, recursive: true)\n\n        try repo.writeFileContents(filePath, bytes: \"// swift-tools-version:3.1\")\n        try repo.commit()\n        try repo.tag(name: \"1.0.0\")\n\n        try repo.writeFileContents(filePath, bytes: \"// swift-tools-version:4.0\")\n        try repo.commit()\n        try repo.tag(name: \"1.0.1\")\n\n        try repo.writeFileContents(filePath, bytes: \"// swift-tools-version:4.2.0;hello\\n\")\n        try repo.commit()\n        try repo.tag(name: \"1.0.2\")\n\n        try repo.writeFileContents(filePath, bytes: \"// swift-tools-version:4.2.0\\n\")\n        try repo.commit()\n        try repo.tag(name: \"1.0.3\")\n\n        let inMemRepoProvider = InMemoryGitRepositoryProvider()\n        inMemRepoProvider.add(specifier: specifier, repository: repo)\n\n        let p = AbsolutePath.root.appending(\"repoManager\")\n        try fs.createDirectory(p, recursive: true)\n        let repositoryManager = RepositoryManager(\n            fileSystem: fs,\n            path: p,\n            provider: inMemRepoProvider,\n            delegate: MockRepositoryManagerDelegate()\n        )\n\n        func createProvider(_ currentToolsVersion: ToolsVersion) throws -> PackageContainerProvider {\n            return try Workspace._init(\n                fileSystem: fs,\n                environment: .mockEnvironment,\n                location: .init(forRootPackage: repoPath, fileSystem: fs),\n                customToolsVersion: currentToolsVersion,\n                customHostToolchain: .mockHostToolchain(fs),\n                customManifestLoader: MockManifestLoader(manifests: [:]),\n                customRepositoryManager: repositoryManager\n            )\n        }\n\n        do {\n            let provider = try createProvider(ToolsVersion(version: \"4.0.0\"))\n            let ref = PackageReference.localSourceControl(identity: PackageIdentity(path: repoPath), path: repoPath)\n            let container = try await provider.getContainer(for: ref)\n            let v = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(v, [\"1.0.1\"])\n        }\n\n        do {\n            let provider = try createProvider(ToolsVersion(version: \"4.2.0\"))\n            let ref = PackageReference.localSourceControl(identity: PackageIdentity(path: repoPath), path: repoPath)\n            let container = try await provider.getContainer(for: ref) as! SourceControlPackageContainer\n            XCTAssertTrue(container.validToolsVersionsCache.isEmpty)\n            let v = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(container.validToolsVersionsCache[\"1.0.0\"], false)\n            XCTAssertEqual(container.validToolsVersionsCache[\"1.0.1\"], true)\n            XCTAssertEqual(container.validToolsVersionsCache[\"1.0.2\"], true)\n            XCTAssertEqual(container.validToolsVersionsCache[\"1.0.3\"], true)\n            XCTAssertEqual(v, [\"1.0.3\", \"1.0.2\", \"1.0.1\"])\n        }\n\n        do {\n            let provider = try createProvider(ToolsVersion(version: \"3.0.0\"))\n            let ref = PackageReference.localSourceControl(identity: PackageIdentity(path: repoPath), path: repoPath)\n            let container = try await provider.getContainer(for: ref)\n            let v = try await container.toolsVersionsAppropriateVersionsDescending()\n            XCTAssertEqual(v, [])\n        }\n\n        // Test that getting dependencies on a revision that has unsupported tools version is diagnosed properly.\n        do {\n            let provider = try createProvider(ToolsVersion(version: \"4.0.0\"))\n            let ref = PackageReference.localSourceControl(identity: PackageIdentity(path: repoPath), path: repoPath)\n            let container = try await provider.getContainer(for: ref) as! SourceControlPackageContainer\n            let revision = try container.getRevision(forTag: \"1.0.0\")\n            do {\n                _ = try await container.getDependencies(at: revision.identifier, productFilter: .nothing)\n            } catch let error as SourceControlPackageContainer.GetDependenciesError {\n                let error = error.underlyingError as! UnsupportedToolsVersion\n                XCTAssertMatch(error.description, .and(.prefix(\"package '\\(PackageIdentity(path: repoPath))' @\"), .suffix(\"is using Swift tools version 3.1.0 which is no longer supported; consider using '// swift-tools-version:4.0' to specify the current tools version\")))\n            }\n        }\n    }\n\n    func testPreReleaseVersions() async throws {\n        try XCTSkipOnWindows(because: \"\"\"\n        https://github.com/swiftlang/swift-package-manager/issues/8578\n        \"\"\")\n\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n\n        let repoPath = AbsolutePath.root\n        let filePath = repoPath.appending(\"Package.swift\")\n\n        let specifier = RepositorySpecifier(path: repoPath)\n        let repo = InMemoryGitRepository(path: repoPath, fs: fs)\n        try repo.createDirectory(repoPath, recursive: true)\n        try repo.writeFileContents(filePath, string: \"// swift-tools-version:\\(ToolsVersion.current)\\n\")\n        try repo.commit()\n        try repo.tag(name: \"1.0.0-alpha.1\")\n        try repo.tag(name: \"1.0.0-beta.1\")\n        try repo.tag(name: \"1.0.0\")\n        try repo.tag(name: \"1.0.1\")\n        try repo.tag(name: \"1.0.2-dev\")\n        try repo.tag(name: \"1.0.2-dev.2\")\n        try repo.tag(name: \"1.0.4-alpha\")\n\n        let inMemRepoProvider = InMemoryGitRepositoryProvider()\n        inMemRepoProvider.add(specifier: specifier, repository: repo)\n\n        let p = AbsolutePath.root.appending(\"repoManager\")\n        try fs.createDirectory(p, recursive: true)\n        let repositoryManager = RepositoryManager(\n            fileSystem: fs,\n            path: p,\n            provider: inMemRepoProvider,\n            delegate: MockRepositoryManagerDelegate()\n        )\n\n        let provider = try Workspace._init(\n            fileSystem: fs,\n            environment: .mockEnvironment,\n            location: .init(forRootPackage: repoPath, fileSystem: fs),\n            customHostToolchain: .mockHostToolchain(fs),\n            customManifestLoader: MockManifestLoader(manifests: [:]),\n            customRepositoryManager: repositoryManager\n        )\n\n        let ref = PackageReference.localSourceControl(identity: PackageIdentity(path: repoPath), path: repoPath)\n        let container = try await provider.getContainer(for: ref)\n        let v = try await container.toolsVersionsAppropriateVersionsDescending()\n        XCTAssertEqual(v, [\"1.0.4-alpha\", \"1.0.2-dev.2\", \"1.0.2-dev\", \"1.0.1\", \"1.0.0\", \"1.0.0-beta.1\", \"1.0.0-alpha.1\"])\n    }\n\n    func testSimultaneousVersions() async throws {\n        try XCTSkipOnWindows(because: \"\"\"\n        https://github.com/swiftlang/swift-package-manager/issues/8578\n        \"\"\")\n\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n\n        let repoPath = AbsolutePath.root\n        let filePath = repoPath.appending(\"Package.swift\")\n\n        let specifier = RepositorySpecifier(path: repoPath)\n        let repo = InMemoryGitRepository(path: repoPath, fs: fs)\n        try repo.createDirectory(repoPath, recursive: true)\n        try repo.writeFileContents(filePath, string: \"// swift-tools-version:\\(ToolsVersion.current)\\n\")\n        try repo.commit()\n        try repo.tag(name: \"v1.0.0\")\n        try repo.tag(name: \"1.0.0\")\n        try repo.tag(name: \"v1.1.0\")\n        try repo.tag(name: \"1.1.0\")\n        try repo.tag(name: \"1.1\")\n        try repo.tag(name: \"1.2\")\n        try repo.tag(name: \"1.3\")\n        try repo.tag(name: \"1.3.0\")\n        try repo.tag(name: \"1.0.1\")\n        try repo.tag(name: \"v1.0.2\")\n        try repo.tag(name: \"1.0.4\")\n        try repo.tag(name: \"v2.0.1\")\n\n        let inMemRepoProvider = InMemoryGitRepositoryProvider()\n        inMemRepoProvider.add(specifier: specifier, repository: repo)\n\n        let p = AbsolutePath.root.appending(\"repoManager\")\n        try fs.createDirectory(p, recursive: true)\n        let repositoryManager = RepositoryManager(\n            fileSystem: fs,\n            path: p,\n            provider: inMemRepoProvider,\n            delegate: MockRepositoryManagerDelegate()\n        )\n\n        let provider = try Workspace._init(\n            fileSystem: fs,\n            environment: .mockEnvironment,\n            location: .init(forRootPackage: repoPath, fileSystem: fs),\n            customHostToolchain: .mockHostToolchain(fs),\n            customManifestLoader: MockManifestLoader(manifests: [:]),\n            customRepositoryManager: repositoryManager\n        )\n        let ref = PackageReference.localSourceControl(identity: PackageIdentity(path: repoPath), path: repoPath)\n        let container = try await provider.getContainer(for: ref)\n        let v = try await container.toolsVersionsAppropriateVersionsDescending()\n        XCTAssertEqual(v, [\"2.0.1\", \"1.3.0\", \"1.2.0\", \"1.1.0\", \"1.0.4\", \"1.0.2\", \"1.0.1\", \"1.0.0\"])\n    }\n\n    func testDependencyConstraints() throws {\n#if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n#else\n        try XCTSkipIf(true, \"Target based dependency resolution is disabled\")\n#endif\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(path: \"/Bar1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Bar2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .localSourceControl(path: \"/Bar3\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        let products = [\n            try ProductDescription(name: \"Foo\", type: .library(.automatic), targets: [\"Foo1\"]),\n        ]\n\n        let targets = [\n            try TargetDescription(name: \"Foo1\", dependencies: [\"Foo2\", \"Bar1\"]),\n            try TargetDescription(name: \"Foo2\", dependencies: [.product(name: \"B2\", package: \"Bar2\")]),\n            try TargetDescription(name: \"Foo3\", dependencies: [\"Bar3\"]),\n        ]\n\n        let v5ProductMapping: [String: ProductFilter] = [\n            \"bar1\": .specific([\"Bar1\", \"Bar3\"]),\n            \"bar2\": .specific([\"B2\", \"Bar1\", \"Bar3\"]),\n            \"bar3\": .specific([\"Bar1\", \"Bar3\"]),\n        ]\n        let v5Constraints = try dependencies.map {\n            PackageContainerConstraint(\n                package: $0.packageRef,\n                requirement: try $0.toConstraintRequirement(),\n                products: v5ProductMapping[$0.identity.description]!\n            )\n        }\n        let v5_2ProductMapping: [String: ProductFilter] = [\n            \"bar1\": .specific([\"Bar1\"]),\n            \"bar2\": .specific([\"B2\"]),\n            \"bar3\": .specific([\"Bar3\"]),\n        ]\n        let v5_2Constraints = try dependencies.map {\n            PackageContainerConstraint(\n                package: $0.packageRef,\n                requirement: try $0.toConstraintRequirement(),\n                products: v5_2ProductMapping[$0.identity.description]!\n            )\n        }\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5,\n                dependencies: dependencies,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(\n                try manifest\n                    .dependencyConstraints(productFilter: .everything)\n                    .sorted(by: { $0.package.identity < $1.package.identity }),\n                [\n                    v5Constraints[0],\n                    v5Constraints[1],\n                    v5Constraints[2],\n                ]\n            )\n        }\n\n        do {\n            let manifest = Manifest.createFileSystemManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5,\n                dependencies: dependencies,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(\n                try manifest\n                    .dependencyConstraints(productFilter: .everything)\n                    .sorted(by: { $0.package.identity < $1.package.identity }),\n                [\n                    v5Constraints[0],\n                    v5Constraints[1],\n                    v5Constraints[2],\n                ]\n            )\n        }\n\n        do {\n            let manifest = Manifest.createRootManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(\n                try manifest\n                    .dependencyConstraints(productFilter: .everything)\n                    .sorted(by: { $0.package.identity < $1.package.identity }),\n                [\n                    v5_2Constraints[0],\n                    v5_2Constraints[1],\n                    v5_2Constraints[2],\n                ]\n            )\n        }\n\n        do {\n            let manifest = Manifest.createFileSystemManifest(\n                displayName: \"Foo\",\n                path: \"/Foo\",\n                toolsVersion: .v5_2,\n                dependencies: dependencies,\n                products: products,\n                targets: targets\n            )\n\n            XCTAssertEqual(\n                try manifest\n                    .dependencyConstraints(productFilter: .specific(Set(products.map { $0.name })))\n                    .sorted(by: { $0.package.identity < $1.package.identity }),\n                [\n                    v5_2Constraints[0],\n                    v5_2Constraints[1],\n                ]\n            )\n        }\n    }\n\n    func testMissingBranchDiagnostics() async throws {\n        try await testWithTemporaryDirectory { tmpDir in\n            // Create a repository.\n            let packageDir = tmpDir.appending(\"SomePackage\")\n            try localFileSystem.createDirectory(packageDir)\n            initGitRepo(packageDir)\n            let packageRepo = GitRepository(path: packageDir)\n\n            // Create a package manifest in it (it only needs the `swift-tools-version` part, because we'll supply the manifest later).\n            let manifestFile = packageDir.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(manifestFile, string: \"// swift-tools-version:4.2\")\n\n            // Commit it and tag it.\n            try packageRepo.stage(file: \"Package.swift\")\n            try packageRepo.commit(message: \"Initial\")\n            try packageRepo.tag(name: \"1.0.0\")\n\n            // Rename the default branch to `main`.\n            try await AsyncProcess.checkNonZeroExit(args: Git.tool, \"-C\", packageDir.pathString, \"branch\", \"-m\", \"main\")\n\n            // Create a repository manager for it.\n            let repoProvider = GitRepositoryProvider()\n            let repositoryManager = RepositoryManager(\n                fileSystem: localFileSystem,\n                path: packageDir,\n                provider: repoProvider,\n                delegate: .none\n            )\n\n            // Create a container provider, configured with a mock manifest loader that will return the package manifest.\n            let manifest = Manifest.createRootManifest(\n                displayName: packageDir.basename,\n                path: packageDir,\n                targets: [\n                    try TargetDescription(name: packageDir.basename, path: packageDir.pathString),\n                ]\n            )\n            let containerProvider = try Workspace._init(\n                fileSystem: localFileSystem,\n                environment: .current,\n                location: .init(forRootPackage: packageDir, fileSystem: localFileSystem),\n                customManifestLoader: MockManifestLoader(manifests: [.init(url: packageDir.pathString, version: nil): manifest]),\n                customRepositoryManager: repositoryManager\n            )\n\n            // Get a hold of the container for the test package.\n            let packageRef = PackageReference.localSourceControl(identity: PackageIdentity(path: packageDir), path: packageDir)\n            let container = try await containerProvider.getContainer(for: packageRef) as! SourceControlPackageContainer\n\n            // Simulate accessing a fictitious dependency on the `master` branch, and check that we get back the expected error.                //ignore-unacceptable-language\n            do { _ = try await container.getDependencies(at: \"master\", productFilter: .everything) }                                            //ignore-unacceptable-language\n            catch let error as SourceControlPackageContainer.GetDependenciesError {\n                // We expect to get an error message that mentions main.\n                XCTAssertMatch(error.description, .and(.prefix(\"could not find a branch named ‘master’\"), .suffix(\"(did you mean ‘main’?)\")))   //ignore-unacceptable-language\n                XCTAssertMatch(error.repository.description, .suffix(\"SomePackage\"))\n                XCTAssertMatch(error.reference, \"master\")                                                                                       //ignore-unacceptable-language\n            }\n\n            // Simulate accessing a fictitious dependency on some random commit that doesn't exist, and check that we get back the expected error.\n            do { _ = try await container.getDependencies(at: \"535f4cb5b4a0872fa691473e82d7b27b9894df00\", productFilter: .everything) }\n            catch let error as SourceControlPackageContainer.GetDependenciesError {\n                // We expect to get an error message about the specific commit.\n                XCTAssertMatch(error.description, .prefix(\"could not find the commit 535f4cb5b4a0872fa691473e82d7b27b9894df00\"))\n                XCTAssertMatch(error.repository.description, .suffix(\"SomePackage\"))\n                XCTAssertMatch(error.reference, \"535f4cb5b4a0872fa691473e82d7b27b9894df00\")\n            }\n        }\n    }\n\n    func testRepositoryContainerUpdateStrategy() async throws {\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"MyPackage\")\n            let package = PackageReference.localSourceControl(identity: PackageIdentity(path: packageDirectory), path: packageDirectory)\n\n            try localFileSystem.createDirectory(packageDirectory)\n            initGitRepo(packageDirectory)\n\n            try localFileSystem.writeFileContents(packageDirectory.appending(Manifest.filename), string: \"\")\n            try ToolsVersionSpecificationWriter.rewriteSpecification(manifestDirectory: packageDirectory, toolsVersion: .current, fileSystem: localFileSystem)\n\n\n            let repositoryProvider = GitRepositoryProvider()\n            let repositoryManagerDelegate = MockRepositoryManagerDelegate()\n            let repositoryManager = RepositoryManager(\n                fileSystem: localFileSystem,\n                path: packageDirectory,\n                provider: repositoryProvider,\n                delegate: repositoryManagerDelegate\n            )\n\n            let containerProvider = try Workspace._init(\n                fileSystem: localFileSystem,\n                environment: .current,\n                location: .init(forRootPackage: packageDirectory, fileSystem: localFileSystem),\n                customManifestLoader: MockManifestLoader(\n                    manifests: [\n                        .init(url: packageDirectory.pathString, version: nil): Manifest.createRootManifest(\n                            displayName: packageDirectory.basename,\n                            path: packageDirectory,\n                            targets: [\n                                try TargetDescription(name: packageDirectory.basename, path: packageDirectory.pathString),\n                            ]\n                        )\n                    ]\n                ),\n                customRepositoryManager: repositoryManager\n            )\n\n            do {\n                repositoryManagerDelegate.reset()\n                XCTAssertEqual(repositoryManagerDelegate.updated.count, 0)\n                _ = try await containerProvider.getContainer(\n                    for: package,\n                    updateStrategy: .never\n                )\n                XCTAssertEqual(repositoryManagerDelegate.updated.count, 0)\n            }\n\n            do {\n                repositoryManagerDelegate.reset()\n                XCTAssertEqual(repositoryManagerDelegate.updated.count, 0)\n                _ = try await containerProvider.getContainer(\n                    for: package,\n                    updateStrategy: .always\n                )\n                XCTAssertEqual(repositoryManagerDelegate.updated.count, 1)\n            }\n\n            do {\n                let repository = GitRepository(path: packageDirectory)\n                try repository.tag(name: \"1.0.0\")\n                let revision = try repository.resolveRevision(tag: \"1.0.0\")\n\n                repositoryManagerDelegate.reset()\n                XCTAssertEqual(repositoryManagerDelegate.updated.count, 0)\n                _ = try await containerProvider.getContainer(\n                    for: package,\n                    updateStrategy: .ifNeeded(revision: revision.identifier)\n                )\n                XCTAssertEqual(repositoryManagerDelegate.updated.count, 0)\n            }\n\n            do {\n                repositoryManagerDelegate.reset()\n                XCTAssertEqual(repositoryManagerDelegate.updated.count, 0)\n                _ = try await containerProvider.getContainer(\n                    for: package,\n                    updateStrategy: .ifNeeded(revision: UUID().uuidString)\n                )\n                XCTAssertEqual(repositoryManagerDelegate.updated.count, 1)\n            }\n        }\n    }\n\n    // From rdar://problem/65284674\n    // RepositoryPackageContainer used to erroneously cache dependencies based only on version,\n    // storing the result of the first product filter and then continually returning it for other filters too.\n    // This lead to corrupt graph states.\n    func testRepositoryPackageContainerCache() async throws {\n        try await testWithTemporaryDirectory { temporaryDirectory in\n            let packageDirectory = temporaryDirectory.appending(\"Package\")\n            try localFileSystem.createDirectory(packageDirectory)\n            initGitRepo(packageDirectory)\n            let packageRepository = GitRepository(path: packageDirectory)\n\n            let manifestFile = packageDirectory.appending(\"Package.swift\")\n            try localFileSystem.writeFileContents(manifestFile, string: \"// swift-tools-version:5.2\")\n\n            try packageRepository.stage(file: \"Package.swift\")\n            try packageRepository.commit(message: \"Initialized.\")\n            try packageRepository.tag(name: \"1.0.0\")\n\n            let repositoryProvider = GitRepositoryProvider()\n            let repositoryManager = RepositoryManager(\n                fileSystem: localFileSystem,\n                path: packageDirectory,\n                provider: repositoryProvider,\n                delegate: .none\n            )\n\n            let version = Version(1, 0, 0)\n            let manifest = Manifest.createRootManifest(\n                displayName: packageDirectory.basename,\n                path: packageDirectory,\n                toolsVersion: .v5_2,\n                dependencies: [\n                    .localSourceControl(\n                        path: \"/Somewhere/Dependency\",\n                        requirement: .exact(version),\n                        productFilter: .specific([])\n                    )\n                ],\n                products: [\n                    try ProductDescription(name: \"Product\", type: .library(.automatic), targets: [\"Target\"])\n                ],\n                targets: [\n                    try TargetDescription(\n                        name: \"Target\",\n                        dependencies: [.product(name: \"DependencyProduct\", package: \"Dependency\")]\n                    ),\n                ]\n            )\n            let containerProvider = try Workspace._init(\n                fileSystem: localFileSystem,\n                environment: .current,\n                location: .init(forRootPackage: packageDirectory, fileSystem: localFileSystem),\n                customManifestLoader: MockManifestLoader(\n                    manifests: [.init(url: packageDirectory.pathString, version: Version(1, 0, 0)): manifest]\n                ),\n                customRepositoryManager: repositoryManager\n            )\n\n            let packageReference = PackageReference.localSourceControl(identity: PackageIdentity(path: packageDirectory), path: packageDirectory)\n            let container = try await containerProvider.getContainer(for: packageReference)\n\n            let forNothing = try await container.getDependencies(at: version, productFilter: .specific([]), [\"default\"])\n            let forProduct = try await container.getDependencies(at: version, productFilter: .specific([\"Product\"]), [\"default\"])\n            #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n            // If the cache overlaps (incorrectly), these will be the same.\n            XCTAssertNotEqual(forNothing, forProduct)\n            #endif\n        }\n    }\n}\n\nextension PackageContainerProvider {\n    fileprivate func getContainer(\n        for package: PackageReference,\n        updateStrategy: ContainerUpdateStrategy = .always\n    ) async throws -> PackageContainer {\n        try await withCheckedThrowingContinuation { continuation in\n            self.getContainer(\n                for: package,\n                updateStrategy: updateStrategy,\n                observabilityScope: ObservabilitySystem.NOOP,\n                on: .global(),\n                completion: {\n                  continuation.resume(with: $0)\n                }\n            )\n        }\n    }\n}\n\nextension RepositoryManager {\n    fileprivate convenience init(\n        fileSystem: FileSystem,\n        path: AbsolutePath,\n        provider: RepositoryProvider,\n        cachePath: AbsolutePath? =  .none,\n        cacheLocalPackages: Bool = false,\n        delegate: RepositoryManagerDelegate? = .none\n    ) {\n        self.init(\n            fileSystem: fileSystem,\n            path: path,\n            provider: provider,\n            cachePath: cachePath,\n            cacheLocalPackages: cacheLocalPackages,\n            initializationWarningHandler: { _ in },\n            delegate: delegate\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/ToolsVersionSpecificationGenerationTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Foundation\n\n///\n/// This file tests the generation of a Swift tools version specification from a known version.\n///\n\nimport Testing\nimport PackageModel\n\nimport struct TSCUtility.Version\n\n/// Test cases for the generation of Swift tools version specifications.\nfileprivate struct ToolsVersionSpecificationGenerationTests {\n    /// Tests the generation of Swift tools version specifications.\n    @Test\n    func toolsVersionSpecificationGeneration() throws {\n        let versionWithNonZeroPatch = ToolsVersion(version: Version(4, 3, 2))\n        #expect(versionWithNonZeroPatch.specification() == \"// swift-tools-version:4.3.2\")\n        #expect(versionWithNonZeroPatch.specification(roundedTo: .automatic) == \"// swift-tools-version:4.3.2\")\n        #expect(versionWithNonZeroPatch.specification(roundedTo: .minor) == \"// swift-tools-version:4.3\")\n        #expect(versionWithNonZeroPatch.specification(roundedTo: .patch) == \"// swift-tools-version:4.3.2\")\n\n        let versionWithZeroPatch = ToolsVersion.v5_3 // 5.3.0\n        #expect(versionWithZeroPatch.specification() == \"// swift-tools-version:5.3\")\n        #expect(versionWithZeroPatch.specification(roundedTo: .automatic) == \"// swift-tools-version:5.3\")\n        #expect(versionWithZeroPatch.specification(roundedTo: .minor) == \"// swift-tools-version:5.3\")\n        #expect(versionWithZeroPatch.specification(roundedTo: .patch) == \"// swift-tools-version:5.3.0\")\n\n        let newMajorVersion = ToolsVersion.v5 // 5.0.0\n        #expect(newMajorVersion.specification() == \"// swift-tools-version:5.0\")\n        #expect(newMajorVersion.specification(roundedTo: .automatic) == \"// swift-tools-version:5.0\")\n        #expect(newMajorVersion.specification(roundedTo: .minor) == \"// swift-tools-version:5.0\")\n        #expect(newMajorVersion.specification(roundedTo: .patch) == \"// swift-tools-version:5.0.0\")\n\n        let allZeroVersion = ToolsVersion(version: Version(0, 0, 0))\n        #expect(allZeroVersion.specification() == \"// swift-tools-version:0.0\")\n        #expect(allZeroVersion.specification(roundedTo: .automatic) == \"// swift-tools-version:0.0\")\n        #expect(allZeroVersion.specification(roundedTo: .minor) == \"// swift-tools-version:0.0\")\n        #expect(allZeroVersion.specification(roundedTo: .patch) == \"// swift-tools-version:0.0.0\")\n    }\n\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/ToolsVersionSpecificationRewriterTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n///\n/// This file tests `Workspace.rewriteToolsVersionSpecification(toDefaultManifestIn:specifying:fileSystem:)`.\n///\n\nimport Basics\nimport PackageModel\n@testable import Workspace\nimport Testing\n\n/// Test cases for `rewriteToolsVersionSpecification(toDefaultManifestIn:specifying:fileSystem:)`\nfileprivate struct ToolsVersionSpecificationRewriterTests {\n\n    struct NonVersionSpecificManifestTestData: Identifiable {\n        let id: String\n        let content: String\n        let version: ToolsVersion\n        let expected: String\n    }\n    @Test(\n        arguments:[\n            NonVersionSpecificManifestTestData(\n                id: \"Empty file.\",\n                content: \"\",\n                version: ToolsVersion(version: \"4.1.2\"),\n                expected: \"// swift-tools-version:4.1.2\\n\"\n            ),\n            NonVersionSpecificManifestTestData(\n                id: \"File with just a new line.\",\n                content: \"\\n\",\n                version: ToolsVersion(version: \"4.1.2\"),\n                expected: \"// swift-tools-version:4.1.2\\n\\n\"\n            ),\n            NonVersionSpecificManifestTestData(\n                id: \"File with some contents.\",\n                content: \"let package = ... \\n\",\n                version: ToolsVersion(version: \"4.1.2\"),\n                expected: \"// swift-tools-version:4.1.2\\nlet package = ... \\n\"\n            ),\n            NonVersionSpecificManifestTestData(\n                id: \"File already having a valid version specifier.\",\n                content: \"\"\"\n                // swift-tools-version:3.1.2\n                ...\n                \"\"\",\n                version: ToolsVersion(version: \"4.1.2\"),\n                expected: \"// swift-tools-version:4.1.2\\n...\"\n            ),\n            NonVersionSpecificManifestTestData(\n                id: \"File already having a valid version specifier.\",\n                content: \"\"\"\n                // swift-tools-version:3.1.2\n                ...\n                \"\"\",\n                version: ToolsVersion(version: \"2.1.0\"),\n                expected: \"// swift-tools-version:2.1\\n...\"\n            ),\n            NonVersionSpecificManifestTestData(\n                id: \"Contents with invalid tools version specification (ignoring the validity of the version specifier).\",\n                content: \"\"\"\n                // swift-tool-version:3.1.2\n                ...\n                \"\"\",\n                version: ToolsVersion(version: \"4.1.2\"),\n                expected:  \"// swift-tools-version:4.1.2\\n// swift-tool-version:3.1.2\\n...\"\n            ),\n            NonVersionSpecificManifestTestData(\n                id: \"Contents with invalid version specifier.\",\n                content: \"\"\"\n                // swift-tools-version:3.1.2\n                ...\n                \"\"\",\n                version: ToolsVersion(version: \"4.1.2\"),\n                expected: \"// swift-tools-version:4.1.2\\n...\"\n            ),\n            NonVersionSpecificManifestTestData(\n                id: \"Contents with invalid version specifier and some meta data.\",\n                content: \"\"\"\n                // swift-tools-version:3.1.2\n                ...\n                \"\"\",\n                version: ToolsVersion(version: \"4.1.2\"),\n                expected: \"// swift-tools-version:4.1.2\\n...\"\n            ),\n            NonVersionSpecificManifestTestData(\n                id: \"Try to write a version with prerelease and build meta data.\",\n                content: \"let package = ... \\n\",\n                version: ToolsVersion(version: \"4.1.2-alpha.beta+sha.1234\"),\n                expected: \"// swift-tools-version:4.1.2\\nlet package = ... \\n\"\n            )\n        ]\n    )\n    func nonVersionSpecificManifests(_ data: NonVersionSpecificManifestTestData) throws {\n        let content = data.content\n        let version = data.version\n        let expected =  data.expected\n\n        let inMemoryFileSystem = InMemoryFileSystem()\n\n        let manifestFilePath = AbsolutePath(\"/pkg/Package.swift\")\n\n        try inMemoryFileSystem.createDirectory(manifestFilePath.parentDirectory, recursive: true)\n        try inMemoryFileSystem.writeFileContents(manifestFilePath, string: content)\n\n        try ToolsVersionSpecificationWriter.rewriteSpecification(\n            manifestDirectory: manifestFilePath.parentDirectory,\n            toolsVersion: version,\n            fileSystem: inMemoryFileSystem\n        )\n\n        // resultHandler(try inMemoryFileSystem.readFileContents(manifestFilePath))\n        let actual = try inMemoryFileSystem.readFileContents(manifestFilePath)\n        #expect(actual.validDescription == expected, \"Actual is not expected\")\n    }\n\n    @Test\n    func manifestAccessFailures() throws {\n        let toolsVersion = ToolsVersion.v5_3\n\n        let inMemoryFileSystem = InMemoryFileSystem()\n        let manifestFilePath = AbsolutePath(\"/pkg/Package.swift/Package.swift\")\n        try inMemoryFileSystem.createDirectory(manifestFilePath.parentDirectory, recursive: true) // /pkg/Package.swift/\n\n        // Test `ManifestAccessError.Kind.isADirectory`\n\n        #expect{\n            try ToolsVersionSpecificationWriter.rewriteSpecification(\n                manifestDirectory: manifestFilePath.parentDirectory.parentDirectory, // /pkg/\n                toolsVersion: toolsVersion,\n                fileSystem: inMemoryFileSystem\n            )\n        } throws: { error in\n            let error = try #require(\n                error as? ToolsVersionSpecificationWriter.ManifestAccessError,\n                \"a ManifestAccessError should've been thrown\"\n            )\n            let isExpectedKind = (error.kind == .isADirectory)\n            let isExpectedDescription = (error.description == \"no accessible Swift Package Manager manifest file found at '\\(manifestFilePath.parentDirectory)'; the path is a directory; a file is expected\")\n\n            return isExpectedKind && isExpectedDescription\n        }\n\n        // Test `ManifestAccessError.Kind.noSuchFileOrDirectory`\n        #expect {\n            try ToolsVersionSpecificationWriter.rewriteSpecification(\n                manifestDirectory: manifestFilePath.parentDirectory, // /pkg/Package.swift/\n                toolsVersion: toolsVersion,\n                fileSystem: inMemoryFileSystem\n            )\n        } throws: { error in\n            let error = try #require(\n                error as? ToolsVersionSpecificationWriter.ManifestAccessError,\n                \"a ManifestAccessError should've been thrown\"\n            )\n            let isExpectedKind = (error.kind == .noSuchFileOrDirectory)\n            let isExpectedDescription = (error.description == \"no accessible Swift Package Manager manifest file found at '\\(manifestFilePath)'; a component of the path does not exist, or the path is an empty string\")\n\n            return isExpectedKind && isExpectedDescription\n        }\n    }\n\n    // Private functions are not run in tests.\n    @Test\n    func versionSpecificManifests() throws {\n\n    }\n\n    @Test\n    func zeroedPatchVersion() {\n        #expect(ToolsVersion(version: \"4.2.1\").zeroedPatch.description == \"4.2.0\")\n        #expect(ToolsVersion(version: \"4.2.0\").zeroedPatch.description == \"4.2.0\")\n        #expect(ToolsVersion(version: \"6.0.129\").zeroedPatch.description == \"6.0.0\")\n    }\n\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/WorkspaceStateTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2021-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport Basics\n@testable import Workspace\nimport Testing\n\nfileprivate struct WorkspaceStateTests {\n    @Test(\n        .tags(\n            .TestSize.small,\n        ),\n    )\n    func v4Format() async throws {\n        let fs = InMemoryFileSystem()\n\n        let buildDir = AbsolutePath(\"/.build\")\n        let statePath = buildDir.appending(\"workspace-state.json\")\n        try fs.writeFileContents(\n            statePath,\n            string: \"\"\"\n            {\n                \"version\": 4,\n                \"object\": {\n                    \"artifacts\": [],\n                    \"dependencies\": [\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"yams\",\n                              \"kind\": \"remote\",\n                              \"location\": \"https://github.com/jpsim/Yams.git\",\n                              \"name\": \"Yams\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"revision\": \"9ff1cc9327586db4e0c8f46f064b6a82ec1566fa\",\n                                \"version\": \"4.0.6\"\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"Yams\"\n                        },\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"swift-tools-support-core\",\n                              \"kind\": \"remote\",\n                              \"location\": \"https://github.com/apple/swift-tools-support-core.git\",\n                              \"name\": \"swift-tools-support-core\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"branch\": \"main\",\n                                \"revision\": \"f9bbd6b80d67408021576adf6247e17c2e957d92\",\n                                \"version\": null\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"swift-tools-support-core\"\n                        },\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"swift-argument-parser\",\n                              \"kind\": \"local\",\n                              \"location\": \"/Users/tomerd/code/swift/swift-argument-parser\",\n                              \"name\": \"swift-argument-parser\"\n                            },\n                            \"state\": {\n                              \"name\": \"local\"\n                            },\n                            \"subpath\": \"swift-argument-parser\"\n                        }\n                    ]\n                }\n            }\n            \"\"\"\n        )\n\n        let dependencies = await WorkspaceState(fileSystem: fs, storageDirectory: buildDir).dependencies\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"yams\") }))\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"swift-tools-support-core\") }))\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"swift-argument-parser\") }))\n    }\n\n    @Test(\n        .tags(\n            .TestSize.small,\n        ),\n    )\n    func v4FormatWithPath() async throws {\n        let fs = InMemoryFileSystem()\n\n        let buildDir = AbsolutePath(\"/.build\")\n        let statePath = buildDir.appending(\"workspace-state.json\")\n        try fs.writeFileContents(\n            statePath,\n            string: \"\"\"\n            {\n                \"version\": 4,\n                \"object\": {\n                    \"artifacts\": [],\n                    \"dependencies\": [\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"yams\",\n                              \"kind\": \"remote\",\n                              \"path\": \"https://github.com/jpsim/Yams.git\",\n                              \"name\": \"Yams\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"revision\": \"9ff1cc9327586db4e0c8f46f064b6a82ec1566fa\",\n                                \"version\": \"4.0.6\"\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"Yams\"\n                        },\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"swift-tools-support-core\",\n                              \"kind\": \"remote\",\n                              \"path\": \"https://github.com/apple/swift-tools-support-core.git\",\n                              \"name\": \"swift-tools-support-core\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"branch\": \"main\",\n                                \"revision\": \"f9bbd6b80d67408021576adf6247e17c2e957d92\",\n                                \"version\": null\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"swift-tools-support-core\"\n                        },\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"swift-argument-parser\",\n                              \"kind\": \"local\",\n                              \"path\": \"/Users/tomerd/code/swift/swift-argument-parser\",\n                              \"name\": \"swift-argument-parser\"\n                            },\n                            \"state\": {\n                              \"name\": \"local\"\n                            },\n                            \"subpath\": \"swift-argument-parser\"\n                        }\n                    ]\n                }\n            }\n            \"\"\"\n        )\n\n        let dependencies = await WorkspaceState(fileSystem: fs, storageDirectory: buildDir).dependencies\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"yams\") }))\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"swift-tools-support-core\") }))\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"swift-argument-parser\") }))\n    }\n\n    @Test(\n        .tags(\n            .TestSize.small,\n        ),\n    )\n    func v5Format() async throws {\n        let fs = InMemoryFileSystem()\n\n        let buildDir = AbsolutePath(\"/.build\")\n        let statePath = buildDir.appending(\"workspace-state.json\")\n        try fs.writeFileContents(\n            statePath,\n            string: \"\"\"\n            {\n                \"version\": 5,\n                \"object\": {\n                    \"artifacts\": [],\n                    \"dependencies\": [\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"yams\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/jpsim/Yams.git\",\n                              \"name\": \"Yams\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"revision\": \"9ff1cc9327586db4e0c8f46f064b6a82ec1566fa\",\n                                \"version\": \"4.0.6\"\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"Yams\"\n                        },\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"swift-tools-support-core\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/apple/swift-tools-support-core.git\",\n                              \"name\": \"swift-tools-support-core\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"branch\": \"main\",\n                                \"revision\": \"f9bbd6b80d67408021576adf6247e17c2e957d92\"\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"swift-tools-support-core\"\n                        },\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"swift-argument-parser\",\n                              \"kind\": \"fileSystem\",\n                              \"location\": \"/Users/tomerd/code/swift/swift-argument-parser\",\n                              \"name\": \"swift-argument-parser\"\n                            },\n                            \"state\": {\n                              \"name\": \"local\",\n                              \"path\": \"/Users/tomerd/code/swift/swift-argument-parser\"\n                            },\n                            \"subpath\": \"swift-argument-parser\"\n                        }\n                    ]\n                }\n            }\n            \"\"\"\n        )\n\n        let dependencies = await WorkspaceState(fileSystem: fs, storageDirectory: buildDir).dependencies\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"yams\") }))\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"swift-tools-support-core\") }))\n        #expect(dependencies.contains(where: { $0.packageRef.identity == .plain(\"swift-argument-parser\") }))\n    }\n\n    @Test(\n        .tags(\n            .TestSize.medium,\n        ),\n    )\n    func savedDependenciesAreSorted() async throws {\n        let fs = InMemoryFileSystem()\n\n        let buildDir = AbsolutePath(\"/.build\")\n        let statePath = buildDir.appending(\"workspace-state.json\")\n        try fs.writeFileContents(\n            statePath,\n            string: \"\"\"\n            {\n                \"version\": 5,\n                \"object\": {\n                    \"artifacts\": [],\n                    \"dependencies\": [\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"yams\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/jpsim/Yams.git\",\n                              \"name\": \"Yams\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"revision\": \"9ff1cc9327586db4e0c8f46f064b6a82ec1566fa\",\n                                \"version\": \"4.0.6\"\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"Yams\"\n                        },\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"swift-argument-parser\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/apple/swift-argument-parser.git\",\n                              \"name\": \"swift-argument-parser\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"revision\": \"83b23d940471b313427da226196661856f6ba3e0\",\n                                \"version\": \"0.4.4\"\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"swift-argument-parser\"\n                        }\n                    ]\n                }\n            }\n            \"\"\"\n        )\n\n        let state = WorkspaceState(fileSystem: fs, storageDirectory: buildDir)\n        try await state.save()\n\n        let serialized: String = try fs.readFileContents(statePath)\n\n        let argpRange = try #require(serialized.range(of: \"swift-argument-parser\"))\n        let yamsRange = try #require(serialized.range(of: \"yams\"))\n\n        #expect(argpRange.lowerBound < yamsRange.lowerBound)\n    }\n\n    @Test(\n        .tags(\n            .TestSize.small,\n        ),\n    )\n    func artifacts() async throws {\n        let fs = InMemoryFileSystem()\n\n        let buildDir = AbsolutePath(\"/.build\")\n        let statePath = buildDir.appending(\"workspace-state.json\")\n        try fs.writeFileContents(\n            statePath,\n            string: \"\"\"\n            {\n                \"version\": 5,\n                \"object\": {\n                    \"artifacts\": [\n                        {\n                            \"packageRef\": {\n                              \"identity\": \"foo\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/org/foo.git\",\n                              \"name\": \"foo\"\n                            },\n                            \"targetName\": \"foo\",\n                            \"source\": {\n                                \"type\": \"remote\",\n                                \"url\": \"https://github.com/org/binary1.zip\",\n                                \"checksum\": \"77AFD0BA-D1CF-4628-A43B-B6E66F44448A\"\n                            },\n                            \"path\": \"/path/to/binary1\"\n                        },\n                        {\n                            \"packageRef\": {\n                              \"identity\": \"foo\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/org/foo.git\",\n                              \"name\": \"foo\"\n                            },\n                            \"targetName\": \"bar\",\n                            \"source\": {\n                                \"type\": \"remote\",\n                                \"url\": \"https://github.com/org/binary2.zip\",\n                                \"checksum\": \"77AFD0BA-D1CF-4628-A43B-B6E66F44448A\"\n                            },\n                            \"path\": \"/path/to/binary2\"\n                        },\n                        {\n                            \"packageRef\": {\n                              \"identity\": \"bar\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/org/bar.git\",\n                              \"name\": \"bar\"\n                            },\n                            \"targetName\": \"bar\",\n                            \"source\": {\n                                \"type\": \"remote\",\n                                \"url\": \"https://github.com/org/binary3.zip\",\n                                \"checksum\": \"77AFD0BA-D1CF-4628-A43B-B6E66F44448A\"\n                            },\n                            \"path\": \"/path/to/binary3\"\n                        }\n                    ],\n                    \"dependencies\": []\n                }\n            }\n            \"\"\"\n        )\n\n        let artifacts = await WorkspaceState(fileSystem: fs, storageDirectory: buildDir).artifacts\n        #expect(artifacts.contains(where: { $0.packageRef.identity == .plain(\"foo\") && $0.targetName == \"foo\" }))\n        #expect(artifacts.contains(where: { $0.packageRef.identity == .plain(\"foo\") && $0.targetName == \"bar\" }))\n        #expect(artifacts.contains(where: { $0.packageRef.identity == .plain(\"bar\") && $0.targetName == \"bar\" }))\n    }\n\n    @Test(\n        .issue(\"rdar://86857825\", relationship: .defect),\n        .tags(\n            .TestSize.small,\n        ),\n    )\n    func duplicateDependenciesDoNotCrash() async throws {\n        let fs = InMemoryFileSystem()\n\n        let buildDir = AbsolutePath(\"/.build\")\n        let statePath = buildDir.appending(\"workspace-state.json\")\n        try fs.writeFileContents(\n            statePath,\n            string: \"\"\"\n            {\n                \"version\": 5,\n                \"object\": {\n                    \"artifacts\": [],\n                    \"dependencies\": [\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"yams\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/jpsim/Yams.git\",\n                              \"name\": \"Yams\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"revision\": \"9ff1cc9327586db4e0c8f46f064b6a82ec1566fa\",\n                                \"version\": \"4.0.6\"\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"Yams\"\n                        },\n                        {\n                            \"basedOn\": null,\n                            \"packageRef\": {\n                              \"identity\": \"yams\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/jpsim/Yams.git\",\n                              \"name\": \"Yams\"\n                            },\n                            \"state\": {\n                              \"checkoutState\": {\n                                \"revision\": \"9ff1cc9327586db4e0c8f46f064b6a82ec1566fa\",\n                                \"version\": \"4.0.6\"\n                              },\n                              \"name\": \"checkout\"\n                            },\n                            \"subpath\": \"Yams\"\n                        },\n                    ]\n                }\n            }\n            \"\"\"\n        )\n\n        let dependencies = await WorkspaceState(fileSystem: fs, storageDirectory: buildDir).dependencies\n        // empty since we have dups so we warn and fail the loading\n        // TODO: test for diagnostics when we can get them from the WorkspaceState initializer\n        #expect(dependencies.isEmpty)\n    }\n\n    @Test(\n        .issue(\"rdar://86857825\", relationship: .defect),\n        .tags(\n            .TestSize.small,\n        ),\n    )\n    func duplicateArtifactsDoNotCrash() async throws {\n        let fs = InMemoryFileSystem()\n\n        let buildDir = AbsolutePath(\"/.build\")\n        let statePath = buildDir.appending(\"workspace-state.json\")\n        try fs.writeFileContents(\n            statePath,\n            string: \"\"\"\n            {\n                \"version\": 5,\n                \"object\": {\n                    \"artifacts\": [\n                        {\n                            \"packageRef\": {\n                              \"identity\": \"foo\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/org/foo.git\",\n                              \"name\": \"foo\"\n                            },\n                            \"targetName\": \"foo\",\n                            \"source\": {\n                                \"type\": \"remote\",\n                                \"url\": \"https://github.com/org/binary1.zip\",\n                                \"checksum\": \"77AFD0BA-D1CF-4628-A43B-B6E66F44448A\"\n                            },\n                            \"path\": \"/path/to/binary1\"\n                        },\n                        {\n                            \"packageRef\": {\n                              \"identity\": \"foo\",\n                              \"kind\": \"remoteSourceControl\",\n                              \"location\": \"https://github.com/org/foo.git\",\n                              \"name\": \"foo\"\n                            },\n                            \"targetName\": \"foo\",\n                            \"source\": {\n                                \"type\": \"remote\",\n                                \"url\": \"https://github.com/org/binary2.zip\",\n                                \"checksum\": \"77AFD0BA-D1CF-4628-A43B-B6E66F44448A\"\n                            },\n                            \"path\": \"/path/to/binary2\"\n                        }\n                    ],\n                    \"dependencies\": []\n                }\n            }\n            \"\"\"\n        )\n\n        let artifacts = await WorkspaceState(fileSystem: fs, storageDirectory: buildDir).artifacts\n        // empty since we have dups so we warn and fail the loading\n        // TODO: test for diagnostics when we can get them from the WorkspaceState initializer\n        #expect(artifacts.isEmpty)\n    }\n}\n\nextension WorkspaceState {\n    fileprivate init(fileSystem: FileSystem, storageDirectory: AbsolutePath) {\n        self.init(fileSystem: fileSystem, storageDirectory: storageDirectory, initializationWarningHandler: { _ in })\n    }\n}\n"
  },
  {
    "path": "Tests/WorkspaceTests/WorkspaceTests+Traits.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport PackageModel\nimport XCTest\n\nextension WorkspaceTests {\n    func testTraitConfigurationExists_NoDefaultTraits() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            dependencies: [\n                                .product(\n                                    name: \"Baz\",\n                                    package: \"Baz\",\n                                    // Trait1 enabled; should be present in list of dependencies\n                                    condition: .init(traits: [\"Trait1\"])\n                                ),\n                                .product(\n                                    name: \"Boo\",\n                                    package: \"Boo\",\n                                    // Trait2 disabled; should remove this dependency from graph\n                                    condition: .init(traits: [\"Trait2\"])\n                                ),\n                            ]\n                        ),\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\", \"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Boo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    traits: [\"Trait1\", \"Trait2\"]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Boo\",\n                    targets: [\n                        MockTarget(name: \"Boo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Boo\", modules: [\"Boo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ],\n            // Only Trait1 is configured to be enabled; since `pruneDependencies` is false\n            // by default, there will be unused dependencies present\n            traitConfiguration: .init(enabledTraits: [\"Trait1\"], enableAllTraits: false)\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Baz\", requirement: .exact(\"1.0.0\"), products: .specific([\"Baz\"])),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Baz\", \"Foo\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testTraitConfigurationExists_WithDefaultTraits() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            dependencies: [\n                                .product(\n                                    name: \"Baz\",\n                                    package: \"Baz\",\n                                    condition: .init(traits: [\"Trait1\"])\n                                ),\n                                .product(\n                                    name: \"Boo\",\n                                    package: \"Boo\",\n                                    condition: .init(traits: [\"Trait2\"])\n                                ),\n                            ]\n                        ),\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\", \"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Boo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    traits: [.init(name: \"default\", enabledTraits: [\"Trait2\"]), \"Trait1\", \"Trait2\"]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Boo\",\n                    targets: [\n                        MockTarget(name: \"Boo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Boo\", modules: [\"Boo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ],\n            // Trait configuration overrides default traits; all traits set to enabled.\n            traitConfiguration: .init(enabledTraits: [], enableAllTraits: true),\n            // With this configuration, no dependencies are unused so nothing should be pruned\n            // despite the `pruneDependencies` flag being set to true.\n            pruneDependencies: true\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Baz\", requirement: .exact(\"1.0.0\"), products: .specific([\"Baz\"])),\n            .sourceControl(path: \"./Boo\", requirement: .exact(\"1.0.0\"), products: .specific([\"Boo\"])),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Baz\", \"Foo\", \"Boo\")\n                result.check(modules: \"Bar\", \"Baz\", \"Boo\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\", \"Boo\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"boo\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testTraitConfiguration_WithPrunedDependencies() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            dependencies: [\n                                .product(\n                                    name: \"Baz\",\n                                    package: \"Baz\",\n                                    condition: .init(traits: [\"Trait1\"])\n                                ),\n                                .product(\n                                    name: \"Boo\",\n                                    package: \"Boo\",\n                                    condition: .init(traits: [\"Trait2\"])\n                                ),\n                            ]\n                        ),\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\", \"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        // unused dependency due to trait guarding; should be omitted\n                        .sourceControl(path: \"./Boo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        // unused dependency; should be omitted\n                        .sourceControl(path: \"./Bam\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    traits: [.init(name: \"default\", enabledTraits: [\"Trait2\"]), \"Trait1\", \"Trait2\"]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ],\n            // Trait configuration overrides default traits; no traits enabled\n            traitConfiguration: .init(enabledTraits: [], enableAllTraits: false),\n            pruneDependencies: true\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Baz\", requirement: .exact(\"1.0.0\"), products: .specific([\"Baz\"])),\n            .sourceControl(path: \"./Boo\", requirement: .exact(\"1.0.0\"), products: .specific([\"Boo\"])),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Baz\", \"Foo\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: []) }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testNoTraitConfiguration_WithDefaultTraits() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            dependencies: [\n                                .product(\n                                    name: \"Baz\",\n                                    package: \"Baz\",\n                                    condition: .init(traits: [\"Trait1\"]) // Baz dependency guarded by traits.\n                                ),\n                                .product(\n                                    name: \"Boo\",\n                                    package: \"Boo\",\n                                    condition: .init(traits: [\"Trait2\"])\n                                ),\n                            ]\n                        ),\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]), // Baz dependency not guarded by traits.\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\", \"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Boo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    traits: [.init(name: \"default\", enabledTraits: [\"Trait2\"]), \"Trait1\", \"Trait2\"]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Boo\",\n                    targets: [\n                        MockTarget(name: \"Boo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Boo\", modules: [\"Boo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Baz\", requirement: .exact(\"1.0.0\"), products: .specific([\"Baz\"])),\n            .sourceControl(path: \"./Boo\", requirement: .exact(\"1.0.0\"), products: .specific([\"Boo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Baz\", \"Boo\", \"Foo\")\n                result.check(modules: \"Bar\", \"Baz\", \"Boo\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Boo\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testInvalidTrait_WhenParentPackageEnablesTraits() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            dependencies: [\n                                .product(\n                                    name: \"Baz\",\n                                    package: \"Baz\",\n                                    condition: .init(traits: [\"Trait1\"])\n                                ),\n                            ]\n                        ),\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\", \"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\"), traits: [\"TraitNotFound\"]),\n                    ],\n                    traits: [.init(name: \"default\", enabledTraits: [\"Trait2\"]), \"Trait1\", \"Trait2\"]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    traits: [\"TraitFound\"],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Baz\", requirement: .exact(\"1.0.0\"), products: .specific([\"Baz\"]), traits: [\"TraitFound\"]),\n        ]\n\n        try await workspace.checkPackageGraphFailure(roots: [\"Foo\"], deps: deps) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .equal(\"Trait 'TraitNotFound' enabled by package 'foo' (Foo) is not declared by package 'baz' (Baz). The available traits declared by this package are: TraitFound.\"), severity: .error)\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testInvalidTraitConfiguration_ForRootPackage() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            dependencies: [\n                                .product(\n                                    name: \"Baz\",\n                                    package: \"Baz\",\n                                    condition: .init(traits: [\"Trait1\"])\n                                ),\n                            ]\n                        ),\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\", \"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\"), traits: [\"TraitFound\"]),\n                    ],\n                    traits: [.init(name: \"default\", enabledTraits: [\"Trait2\"]), \"Trait1\", \"Trait2\"]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    traits: [\"TraitFound\"],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ],\n            // Trait configuration containing trait that isn't defined in the root package.\n            traitConfiguration: .enabledTraits([\"TraitNotFound\"]),\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Baz\", requirement: .exact(\"1.0.0\"), products: .specific([\"Baz\"]), traits: [\"TraitFound\"]),\n        ]\n\n        try await workspace.checkPackageGraphFailure(roots: [\"Foo\"], deps: deps) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .equal(\"Trait 'TraitNotFound' enabled by command-line trait configuration is not declared by package 'foo' (Foo). The available traits declared by this package are: Trait1, Trait2, default.\"), severity: .error)\n            }\n        }\n    }\n\n    func testManyTraitsEnableTargetDependency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        func createMockWorkspace(_ traitConfiguration: TraitConfiguration) async throws -> MockWorkspace {\n            try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    MockPackage(\n                        name: \"Cereal\",\n                        targets: [\n                            MockTarget(\n                                name: \"Wheat\",\n                                dependencies: [\n                                    .product(\n                                        name: \"Icing\",\n                                        package: \"Sugar\",\n                                        condition: .init(traits: [\"BreakfastOfChampions\", \"DontTellMom\"])\n                                    ),\n                                ]\n                            ),\n                        ],\n                        products: [\n                            MockProduct(name: \"YummyBreakfast\", modules: [\"Wheat\"])\n                        ],\n                        dependencies: [\n                            .sourceControl(path: \"./Sugar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        ],\n                        traits: [\"BreakfastOfChampions\", \"DontTellMom\"]\n                    ),\n                ],\n                packages: [\n                    MockPackage(\n                        name: \"Sugar\",\n                        targets: [\n                            MockTarget(name: \"Icing\"),\n                        ],\n                        products: [\n                            MockProduct(name: \"Icing\", modules: [\"Icing\"]),\n                        ],\n                        versions: [\"1.0.0\", \"1.5.0\"]\n                    ),\n                ],\n                traitConfiguration: traitConfiguration\n            )\n        }\n\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Sugar\", requirement: .exact(\"1.0.0\"), products: .specific([\"Icing\"])),\n        ]\n\n        let workspaceOfChampions = try await createMockWorkspace(.enabledTraits([\"BreakfastOfChampions\"]))\n        try await workspaceOfChampions.checkPackageGraph(roots: [\"Cereal\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Cereal\")\n                result.check(packages: \"cereal\", \"sugar\")\n                result.check(modules: \"Wheat\", \"Icing\")\n                result.check(products: \"YummyBreakfast\", \"Icing\")\n                result.checkTarget(\"Wheat\") { result in\n                    result.check(dependencies: \"Icing\")\n                }\n            }\n        }\n\n        let dontTellMomAboutThisWorkspace = try await createMockWorkspace(.enabledTraits([\"DontTellMom\"]))\n        try await dontTellMomAboutThisWorkspace.checkPackageGraph(roots: [\"Cereal\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Cereal\")\n                result.check(packages: \"cereal\", \"sugar\")\n                result.check(modules: \"Wheat\", \"Icing\")\n                result.check(products: \"YummyBreakfast\", \"Icing\")\n                result.checkTarget(\"Wheat\") { result in\n                    result.check(dependencies: \"Icing\")\n                }\n            }\n        }\n\n        let allEnabledTraitsWorkspace = try await createMockWorkspace(.enableAllTraits)\n        try await allEnabledTraitsWorkspace.checkPackageGraph(roots: [\"Cereal\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Cereal\")\n                result.check(packages: \"cereal\", \"sugar\")\n                result.check(modules: \"Wheat\", \"Icing\")\n                result.check(products: \"YummyBreakfast\", \"Icing\")\n                result.checkTarget(\"Wheat\") { result in\n                    result.check(dependencies: \"Icing\")\n                }\n            }\n        }\n\n        let noSugarForBreakfastWorkspace = try await createMockWorkspace(.disableAllTraits)\n        try await noSugarForBreakfastWorkspace.checkPackageGraph(roots: [\"Cereal\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Cereal\")\n                result.check(packages: \"cereal\")\n                result.check(modules: \"Wheat\")\n                result.check(products: \"YummyBreakfast\")\n            }\n        }\n    }\n\n    /// Tests that different trait configurations correctly control which conditional dependencies are included.\n    /// Verifies that enabling different traits (BreakfastOfChampions vs Healthy) includes different\n    /// dependencies, and that both are included with `enableAllTraits` while neither is included with `disableAllTraits`.\n    func testTraitsConditionalDependencies() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        func createMockWorkspace(_ traitConfiguration: TraitConfiguration) async throws -> MockWorkspace {\n            try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    MockPackage(\n                        name: \"Cereal\",\n                        targets: [\n                            MockTarget(\n                                name: \"Wheat\",\n                                dependencies: [\n                                    .product(\n                                        name: \"Icing\",\n                                        package: \"Sugar\",\n                                        condition: .init(traits: [\"BreakfastOfChampions\"])\n                                    ),\n                                    .product(\n                                        name: \"Raisin\",\n                                        package: \"Fruit\",\n                                        condition: .init(traits: [\"Healthy\"])\n                                    )\n                                ]\n                            ),\n                        ],\n                        products: [\n                            MockProduct(name: \"YummyBreakfast\", modules: [\"Wheat\"])\n                        ],\n                        dependencies: [\n                            .sourceControl(path: \"./Sugar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                            .sourceControl(path: \"./Fruit\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        ],\n                        traits: [\"Healthy\", \"BreakfastOfChampions\"]\n                    ),\n                ],\n                packages: [\n                    MockPackage(\n                        name: \"Sugar\",\n                        targets: [\n                            MockTarget(name: \"Icing\"),\n                        ],\n                        products: [\n                            MockProduct(name: \"Icing\", modules: [\"Icing\"]),\n                        ],\n                        versions: [\"1.0.0\", \"1.5.0\"]\n                    ),\n                    MockPackage(\n                        name: \"Fruit\",\n                        targets: [\n                            MockTarget(name: \"Raisin\"),\n                        ],\n                        products: [\n                            MockProduct(name: \"Raisin\", modules: [\"Raisin\"]),\n                        ],\n                        versions: [\"1.0.0\", \"1.2.0\"]\n                    ),\n                ],\n                traitConfiguration: traitConfiguration\n            )\n        }\n\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Sugar\", requirement: .exact(\"1.0.0\"), products: .specific([\"Icing\"])),\n            .sourceControl(path: \"./Fruit\", requirement: .exact(\"1.0.0\"), products: .specific([\"Raisin\"])),\n        ]\n\n        let workspaceOfChampions = try await createMockWorkspace(.enabledTraits([\"BreakfastOfChampions\"]))\n        try await workspaceOfChampions.checkPackageGraph(roots: [\"Cereal\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Cereal\")\n                result.check(packages: \"cereal\", \"sugar\")\n                result.check(modules: \"Wheat\", \"Icing\")\n                result.checkTarget(\"Wheat\") { result in\n                    result.check(dependencies: \"Icing\")\n                }\n            }\n        }\n\n        let healthyWorkspace = try await createMockWorkspace(.enabledTraits([\"Healthy\"]))\n        try await healthyWorkspace.checkPackageGraph(roots: [\"Cereal\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Cereal\")\n                result.check(packages: \"cereal\", \"fruit\")\n                result.check(modules: \"Wheat\", \"Raisin\")\n                result.check(products: \"YummyBreakfast\", \"Raisin\")\n                result.checkTarget(\"Wheat\") { result in\n                    result.check(dependencies: \"Raisin\")\n                }\n            }\n        }\n\n        let allEnabledTraitsWorkspace = try await createMockWorkspace(.enableAllTraits)\n        try await allEnabledTraitsWorkspace.checkPackageGraph(roots: [\"Cereal\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Cereal\")\n                result.check(packages: \"cereal\", \"sugar\", \"fruit\")\n                result.check(modules: \"Wheat\", \"Icing\", \"Raisin\")\n                result.check(products: \"YummyBreakfast\", \"Icing\", \"Raisin\")\n                result.checkTarget(\"Wheat\") { result in\n                    result.check(dependencies: \"Icing\", \"Raisin\")\n                }\n            }\n        }\n\n        let boringBreakfastWorkspace = try await createMockWorkspace(.disableAllTraits)\n        try await boringBreakfastWorkspace.checkPackageGraph(roots: [\"Cereal\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Cereal\")\n                result.check(packages: \"cereal\")\n                result.check(modules: \"Wheat\")\n                result.check(products: \"YummyBreakfast\")\n            }\n        }\n    }\n\n    /// Tests that default traits of a dependency package are automatically enabled when\n    ////  the parent doesn't specify traits.\n    /// Verifies that the default trait enables its configured traits (Enabled1 and\n    /// Enabled2), which in turn enables trait-guarded dependencies in the dependency's package graph.\n    func testDefaultTraitsEnabledInPackageDependency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"RootPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(\n                                    name: \"MyProduct\",\n                                    package: \"PackageWithDefaultTraits\",\n                                ),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"RootProduct\", modules: [\"MyTarget\"])\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./PackageWithDefaultTraits\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"PackageWithDefaultTraits\",\n                    targets: [\n                        MockTarget(\n                            name: \"PackageTarget\",\n                            dependencies: [\n                                .product(\n                                    name: \"GuardedProduct\",\n                                    package: \"GuardedDependency\",\n                                    condition: .init(traits: [\"Enabled1\"])\n                                )\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"MyProduct\", modules: [\"PackageTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./GuardedDependency\", requirement: .upToNextMajor(from: \"1.0.0\"))\n                    ],\n                    traits: [\n                        \"Enabled1\",\n                        \"Enabled2\",\n                        TraitDescription(name: \"default\", enabledTraits: [\"Enabled1\", \"Enabled2\"]),\n                        \"NotEnabled\"\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"GuardedDependency\",\n                    targets: [\n                        MockTarget(\n                            name: \"GuardedTarget\"\n                        )\n                    ],\n                    products: [\n                        MockProduct(name: \"GuardedProduct\", modules: [\"GuardedTarget\"])\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                )\n            ],\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./PackageWithDefaultTraits\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"RootPackage\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"RootPackage\")\n                result.checkPackage(\"PackageWithDefaultTraits\") { package in\n                    guard let enabledTraits = package.enabledTraits else {\n                        XCTFail(\"No enabled traits on resolved package \\(package.identity.description) that is expected to have enabled traits.\")\n                        return\n                    }\n\n                    let deps = package.dependencies\n                    XCTAssertEqual(deps, [PackageIdentity(urlString: \"./GuardedDependency\")])\n                    XCTAssertEqual(enabledTraits, [\"Enabled1\", \"Enabled2\"])\n                }\n            }\n        }\n    }\n\n    /// Tests the unified trait system where one parent disables default traits with []\n    /// while another parent doesn't specify traits (defaults to default traits).\n    /// The resulting EnabledTraitsMap should have both disablers AND enabled default traits.\n    func testDefaultTraitDisablersCoexistWithDefaultTraits() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"RootPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"RootTarget\",\n                            dependencies: [\n                                .product(name: \"Parent1Product\", package: \"Parent1\"),\n                                .product(name: \"Parent2Product\", package: \"Parent2\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"RootProduct\", modules: [\"RootTarget\"])\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Parent1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Parent2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Parent1\",\n                    targets: [\n                        MockTarget(\n                            name: \"Parent1Target\",\n                            dependencies: [\n                                .product(name: \"ChildProduct\", package: \"ChildPackage\")\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Parent1Product\", modules: [\"Parent1Target\"])\n                    ],\n                    dependencies: [\n                        // Parent1 explicitly disables ChildPackage's traits with []\n                        .sourceControl(path: \"./ChildPackage\", requirement: .upToNextMajor(from: \"1.0.0\"), traits: [])\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Parent2\",\n                    targets: [\n                        MockTarget(\n                            name: \"Parent2Target\",\n                            dependencies: [\n                                .product(name: \"ChildProduct\", package: \"ChildPackage\")\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Parent2Product\", modules: [\"Parent2Target\"])\n                    ],\n                    dependencies: [\n                        // Parent2 doesn't specify traits, so ChildPackage defaults to default traits\n                        .sourceControl(path: \"./ChildPackage\", requirement: .upToNextMajor(from: \"1.0.0\"))\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"ChildPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"ChildTarget\",\n                            dependencies: [\n                                .product(\n                                    name: \"GuardedProduct\",\n                                    package: \"GuardedDependency\",\n                                    condition: .init(traits: [\"Feature1\"])\n                                )\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"ChildProduct\", modules: [\"ChildTarget\"])\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./GuardedDependency\", requirement: .upToNextMajor(from: \"1.0.0\"))\n                    ],\n                    traits: [\n                        \"Feature1\",\n                        \"Feature2\",\n                        TraitDescription(name: \"default\", enabledTraits: [\"Feature1\"])\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"GuardedDependency\",\n                    targets: [\n                        MockTarget(name: \"GuardedTarget\")\n                    ],\n                    products: [\n                        MockProduct(name: \"GuardedProduct\", modules: [\"GuardedTarget\"])\n                    ],\n                    versions: [\"1.0.0\"]\n                )\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Parent1\", requirement: .exact(\"1.0.0\")),\n            .sourceControl(path: \"./Parent2\", requirement: .exact(\"1.0.0\")),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"RootPackage\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"RootPackage\")\n                result.check(packages: \"RootPackage\", \"Parent1\", \"Parent2\", \"ChildPackage\", \"GuardedDependency\")\n\n                // Verify ChildPackage has default traits enabled (from Parent2)\n                result.checkPackage(\"ChildPackage\") { package in\n                    guard let enabledTraits = package.enabledTraits else {\n                        XCTFail(\"No enabled traits on ChildPackage\")\n                        return\n                    }\n\n                    // Should contain Feature1 from default trait (enabled by Parent2)\n                    XCTAssertEqual(enabledTraits, [\"Feature1\"])\n\n                    // Verify the dependency on GuardedDependency is included\n                    let deps = package.dependencies\n                    XCTAssertEqual(deps, [PackageIdentity(urlString: \"./GuardedDependency\")])\n                }\n\n                // The graph should include GuardedDependency since Feature1 is enabled\n                result.check(modules: \"RootTarget\", \"Parent1Target\", \"Parent2Target\", \"ChildTarget\", \"GuardedTarget\")\n            }\n        }\n    }\n\n    /// Verifies that when a parent requests defaults (doesn't specify traits),\n    /// the defaults are properly expanded when the dependency's manifest loads.\n    /// The \"default\" trait itself should never appear in the final enabled traits list.\n    func testDefaultTraitSettersFlattenedOnManifestLoad() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"RootPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"RootTarget\",\n                            dependencies: [.product(name: \"ChildProduct\", package: \"ChildPackage\")]\n                        ),\n                    ],\n                    products: [MockProduct(name: \"RootProduct\", modules: [\"RootTarget\"])],\n                    dependencies: [\n                        // Root doesn't specify traits - wants defaults\n                        .sourceControl(path: \"./ChildPackage\", requirement: .upToNextMajor(from: \"1.0.0\"))\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"ChildPackage\",\n                    targets: [\n                        MockTarget(name: \"ChildTarget\"),\n                    ],\n                    products: [MockProduct(name: \"ChildProduct\", modules: [\"ChildTarget\"])],\n                    traits: [\n                        // Default trait enables Feature1\n                        .init(name: \"default\", enabledTraits: [\"Feature1\"]),\n                        .init(name: \"Feature1\"),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./ChildPackage\", requirement: .upToNextMajor(from: \"1.0.0\"))\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"RootPackage\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"RootPackage\")\n                result.check(packages: \"RootPackage\", \"ChildPackage\")\n\n                // Verify ChildPackage has Feature1 enabled (from expanded default)\n                // The \"default\" trait should NOT appear - it should be flattened to Feature1\n                result.checkPackage(\"ChildPackage\") { package in\n                    guard let enabledTraits = package.enabledTraits else {\n                        XCTFail(\"No enabled traits on ChildPackage\")\n                        return\n                    }\n\n                    // Should contain Feature1 (expanded from default)\n                    XCTAssertTrue(enabledTraits.contains(\"Feature1\"))\n                    // Should NOT contain \"default\" - it should be flattened\n                    XCTAssertFalse(enabledTraits.contains(\"default\"))\n                    // Should only have Feature1\n                    XCTAssertEqual(enabledTraits.count, 1)\n                }\n            }\n        }\n    }\n\n    /// Verifies that when multiple parents don't specify traits (want defaults),\n    /// all their default requests are tracked and the result is the same regardless of load order.\n    /// The \"default\" trait should be flattened to the actual traits it enables.\n    func testMultipleDefaultTraitSettersOrderIndependent() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"RootPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"RootTarget\",\n                            dependencies: [\n                                .product(name: \"Parent1Product\", package: \"Parent1\"),\n                                .product(name: \"Parent2Product\", package: \"Parent2\"),\n                            ]\n                        ),\n                    ],\n                    products: [MockProduct(name: \"RootProduct\", modules: [\"RootTarget\"])],\n                    dependencies: [\n                        .sourceControl(path: \"./Parent1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Parent2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Parent1\",\n                    targets: [\n                        MockTarget(\n                            name: \"Parent1Target\",\n                            dependencies: [.product(name: \"ChildProduct\", package: \"ChildPackage\")]\n                        ),\n                    ],\n                    products: [MockProduct(name: \"Parent1Product\", modules: [\"Parent1Target\"])],\n                    dependencies: [\n                        // Parent1 doesn't specify traits - wants defaults\n                        .sourceControl(path: \"./ChildPackage\", requirement: .upToNextMajor(from: \"1.0.0\"))\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Parent2\",\n                    targets: [\n                        MockTarget(\n                            name: \"Parent2Target\",\n                            dependencies: [.product(name: \"ChildProduct\", package: \"ChildPackage\")]\n                        ),\n                    ],\n                    products: [MockProduct(name: \"Parent2Product\", modules: [\"Parent2Target\"])],\n                    dependencies: [\n                        // Parent2 also doesn't specify traits - wants defaults\n                        .sourceControl(path: \"./ChildPackage\", requirement: .upToNextMajor(from: \"1.0.0\"))\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"ChildPackage\",\n                    targets: [MockTarget(name: \"ChildTarget\")],\n                    products: [MockProduct(name: \"ChildProduct\", modules: [\"ChildTarget\"])],\n                    traits: [\n                        .init(name: \"default\", enabledTraits: [\"Feature1\"]),\n                        .init(name: \"Feature1\"),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Parent1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .sourceControl(path: \"./Parent2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"RootPackage\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.checkPackage(\"ChildPackage\") { package in\n                    guard let enabledTraits = package.enabledTraits else {\n                        XCTFail(\"No enabled traits on ChildPackage\")\n                        return\n                    }\n\n                    // Should have Feature1 enabled from both parents wanting defaults\n                    XCTAssertTrue(enabledTraits.contains(\"Feature1\"))\n                    // Should NOT contain \"default\" - it should be flattened\n                    XCTAssertFalse(enabledTraits.contains(\"default\"))\n                }\n            }\n        }\n    }\n\n    /// Verifies that when all parents disable traits, no defaults are enabled.\n    /// The final enabled traits should be empty.\n    func testAllParentsDisableDefaultTraits() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"RootPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"RootTarget\",\n                            dependencies: [\n                                .product(name: \"Parent1Product\", package: \"Parent1\"),\n                                .product(name: \"Parent2Product\", package: \"Parent2\"),\n                            ]\n                        ),\n                    ],\n                    products: [MockProduct(name: \"RootProduct\", modules: [\"RootTarget\"])],\n                    dependencies: [\n                        .sourceControl(path: \"./Parent1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Parent2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Parent1\",\n                    targets: [\n                        MockTarget(\n                            name: \"Parent1Target\",\n                            dependencies: [.product(name: \"ChildProduct\", package: \"ChildPackage\")]\n                        ),\n                    ],\n                    products: [MockProduct(name: \"Parent1Product\", modules: [\"Parent1Target\"])],\n                    dependencies: [\n                        // Parent1 disables all traits\n                        .sourceControl(path: \"./ChildPackage\", requirement: .upToNextMajor(from: \"1.0.0\"), traits: [])\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Parent2\",\n                    targets: [\n                        MockTarget(\n                            name: \"Parent2Target\",\n                            dependencies: [.product(name: \"ChildProduct\", package: \"ChildPackage\")]\n                        ),\n                    ],\n                    products: [MockProduct(name: \"Parent2Product\", modules: [\"Parent2Target\"])],\n                    dependencies: [\n                        // Parent2 also disables all traits\n                        .sourceControl(path: \"./ChildPackage\", requirement: .upToNextMajor(from: \"1.0.0\"), traits: [])\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"ChildPackage\",\n                    targets: [MockTarget(name: \"ChildTarget\")],\n                    products: [MockProduct(name: \"ChildProduct\", modules: [\"ChildTarget\"])],\n                    traits: [\n                        .init(name: \"default\", enabledTraits: [\"Feature1\"]),\n                        .init(name: \"Feature1\"),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Parent1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n            .sourceControl(path: \"./Parent2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"RootPackage\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.checkPackage(\"ChildPackage\") { package in\n                    guard let enabledTraits = package.enabledTraits else {\n                        XCTFail(\"No enabled traits on ChildPackage\")\n                        return\n                    }\n\n                    // Should have NO traits enabled (both parents disabled)\n                    XCTAssertTrue(enabledTraits.isEmpty)\n                }\n            }\n        }\n    }\n\n}\n\n"
  },
  {
    "path": "Tests/WorkspaceTests/WorkspaceTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport _InternalTestSupport\nimport Basics\nimport PackageFingerprint\n@testable import PackageGraph\nimport PackageLoading\nimport PackageModel\nimport PackageRegistry\nimport PackageSigning\nimport SourceControl\nimport SPMBuildCore\n@testable import Workspace\nimport XCTest\n\nimport struct TSCBasic.ByteString\n\nimport struct TSCUtility.Version\n\nfinal class WorkspaceTests: XCTestCase {\n    func testBasics() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]),\n                        MockTarget(name: \"BarTests\", dependencies: [\"Bar\"], type: .test),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\", \"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Quix\",\n                    targets: [\n                        MockTarget(name: \"Quix\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Quix\", modules: [\"Quix\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.2.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Quix\", requirement: .upToNextMajor(from: \"1.0.0\"), products: .specific([\"Quix\"])),\n            .sourceControl(path: \"./Baz\", requirement: .exact(\"1.0.0\"), products: .specific([\"Baz\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Baz\", \"Foo\", \"Quix\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\", \"Quix\")\n                result.check(testModules: \"BarTests\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Bar\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n                result.checkTarget(\"BarTests\") { result in result.check(dependencies: \"Bar\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"quix\", at: .checkout(.version(\"1.2.0\")))\n        }\n\n        // Check the load-package callbacks.\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for root package: \\(sandbox.appending(components: \"roots\", \"Foo\")) (identity: foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for root package: \\(sandbox.appending(components: \"roots\", \"Foo\")) (identity: foo)\"]\n        )\n\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"will load manifest for localSourceControl package: \\(sandbox.appending(components: \"pkgs\", \"Quix\")) (identity: quix)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"did load manifest for localSourceControl package: \\(sandbox.appending(components: \"pkgs\", \"Quix\")) (identity: quix)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"will load manifest for localSourceControl package: \\(sandbox.appending(components: \"pkgs\", \"Baz\")) (identity: baz)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"did load manifest for localSourceControl package: \\(sandbox.appending(components: \"pkgs\", \"Baz\")) (identity: baz)\",\n            ]\n        )\n\n        // Close and reopen workspace.\n        try await workspace.closeWorkspace(resetState: false)\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"quix\", at: .checkout(.version(\"1.2.0\")))\n        }\n\n        let stateFile = try await workspace.getOrCreateWorkspace().state.storagePath\n\n        // Remove state file and check we can get the state back automatically.\n        try fs.removeFileTree(stateFile)\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { _, _ in }\n        XCTAssertTrue(fs.exists(stateFile), \"workspace state file should exist\")\n\n        // Remove state file and check we get back to a clean state.\n        try await fs.removeFileTree(workspace.getOrCreateWorkspace().state.storagePath)\n        try await workspace.closeWorkspace()\n        await workspace.checkManagedDependencies { result in\n            result.checkEmpty()\n        }\n    }\n\n    func testInterpreterFlags() async throws {\n        let fs = localFileSystem\n\n        try testWithTemporaryDirectory { path in\n            let foo = path.appending(\"foo\")\n            let packageManifest = foo.appending(\"Package.swift\")\n\n            func createWorkspace(_ content: String) throws -> Workspace {\n                try fs.writeFileContents(packageManifest, string: content)\n\n                let manifestLoader = try ManifestLoader(toolchain: UserToolchain.default)\n\n                let sandbox = path.appending(\"ws\")\n                return try Workspace(\n                    fileSystem: fs,\n                    forRootPackage: sandbox,\n                    customManifestLoader: manifestLoader,\n                    delegate: MockWorkspaceDelegate()\n                )\n            }\n\n            do {\n                let ws = try createWorkspace(\n                    \"\"\"\n                    // swift-tools-version:4.0\n                    import PackageDescription\n                    let package = Package(\n                        name: \"foo\"\n                    )\n                    \"\"\"\n                )\n\n                XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-swift-version\"), .equal(\"4\")])\n            }\n\n            do {\n                let ws = try createWorkspace(\n                    \"\"\"\n                    // swift-tools-version:3.1\n                    import PackageDescription\n                    let package = Package(\n                        name: \"foo\"\n                    )\n                    \"\"\"\n                )\n\n                XCTAssertThrowsError(try ws.interpreterFlags(for: packageManifest))\n            }\n\n            do {\n                let ws = try createWorkspace(\n                    \"\"\"\n                    // swift-tools-version:999.0\n                    import PackageDescription\n                    let package = Package(\n                        name: \"foo\"\n                    )\n                    \"\"\"\n                )\n                if SwiftVersion.current.isDevelopment {\n                    XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-swift-version\"), .equal(\"6\")])\n                } else {\n                    XCTAssertThrowsError(\n                        try ws.interpreterFlags(for: packageManifest)\n                    )\n                }\n            }\n\n            do {\n                let ws = try createWorkspace(\n                \"\"\"\n                // swift-tools-version:6.0\n                import PackageDescription\n                let package = Package(\n                    name: \"foo\"\n                )\n                \"\"\"\n                )\n\n                XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-swift-version\"), .equal(\"6\")])\n            }\n\n            do {\n                let ws = try createWorkspace(\n                \"\"\"\n                // swift-tools-version:6.1\n                import PackageDescription\n                let package = Package(\n                    name: \"foo\"\n                )\n                \"\"\"\n                )\n\n                XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-swift-version\"), .equal(\"6\")])\n                XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-package-description-version\"), .equal(\"6.1.0\")])\n            }\n\n            do {\n                let ws = try createWorkspace(\n                \"\"\"\n                // swift-tools-version:6.2\n                import PackageDescription\n                let package = Package(\n                    name: \"foo\"\n                )\n                \"\"\"\n                )\n\n                XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-swift-version\"), .equal(\"6\")])\n                XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-package-description-version\"), .equal(\"6.2.0\")])\n            }\n\n            do {\n                let ws = try createWorkspace(\n                    \"\"\"\n                    // swift-tools-version:5.9.2\n                    import PackageDescription\n                    let package = Package(\n                        name: \"foo\"\n                    )\n                    \"\"\"\n                )\n\n                XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-swift-version\"), .equal(\"5\")])\n            }\n\n            do {\n                // Invalid package manifest should still produce build settings.\n                let ws = try createWorkspace(\n                    \"\"\"\n                    // swift-tools-version:5.9.2\n                    import PackageDescription\n                    \"\"\"\n                )\n\n                XCTAssertMatch(try ws.interpreterFlags(for: packageManifest), [.equal(\"-package-description-version\")])\n            }\n\n            do {\n                let ws = try createWorkspace(\n                    \"\"\"\n                    // swift-tools-version:3.0\n                    import PackageDescription\n                    \"\"\"\n                )\n                XCTAssertThrowsError(\n                    try ws.interpreterFlags(for: packageManifest),\n                    \"error expected\"\n                ) { error in\n                    XCTAssertEqual(\n                        error as? StringError,\n                        StringError(\"invalid tools version\")\n                    )\n                }\n            }\n\n            do {\n                // Invalid package manifest should still produce build settings.\n                let ws = try createWorkspace(\n                    \"\"\"\n                    // swift-tools-version:5.1\n                    import PackageDescription\n                    \"\"\"\n                )\n\n                XCTAssertMatch(\n                    try ws.interpreterFlags(for: packageManifest),\n                    [.equal(\"-package-description-version\"), .equal(\"5.1.0\")]\n                )\n            }\n        }\n    }\n\n    func testManifestParseError() async throws {\n        let observability = ObservabilitySystem.makeForTesting()\n\n        try await testWithTemporaryDirectory { path in\n            let pkgDir = path.appending(\"MyPkg\")\n            try localFileSystem.createDirectory(pkgDir)\n            try localFileSystem.writeFileContents(\n                pkgDir.appending(\"Package.swift\"),\n                string: \"\"\"\n                // swift-tools-version:4.0\n                import PackageDescription\n                #error(\"An error in MyPkg\")\n                let package = Package(\n                    name: \"MyPkg\"\n                )\n                \"\"\"\n            )\n            let workspace = try Workspace(\n                fileSystem: localFileSystem,\n                forRootPackage: pkgDir,\n                customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),\n                delegate: MockWorkspaceDelegate()\n            )\n            let rootInput = PackageGraphRootInput(packages: [pkgDir], dependencies: [])\n            let rootManifests = try await workspace.loadRootManifests(\n                packages: rootInput.packages,\n                observabilityScope: observability.topScope\n            )\n\n            XCTAssert(rootManifests.count == 0, \"\\(rootManifests)\")\n\n            testDiagnostics(observability.diagnostics) { result in\n                let diagnostic = result.check(\n                    diagnostic: .contains(\n                        \"\\(pkgDir.appending(\"Package.swift\")):3:8: error: An error in MyPkg\"\n                    ),\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic?.metadata?.packageIdentity, .init(path: pkgDir))\n                XCTAssertEqual(diagnostic?.metadata?.packageKind, .root(pkgDir))\n            }\n        }\n    }\n\n    func testMultipleRootPackages() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .exact(\"1.0.1\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.0.1\", \"1.0.3\", \"1.0.5\", \"1.0.8\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\", \"Bar\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Bar\", \"Foo\")\n                result.check(packages: \"Bar\", \"Baz\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.1\")))\n        }\n    }\n\n    func testRootPackagesOverride() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"bazzz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: []\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    path: \"Overridden/bazzz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    path: \"bazzz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.0.1\", \"1.0.3\", \"1.0.5\", \"1.0.8\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\", \"Bar\", \"Overridden/bazzz\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"bar\", \"Foo\", \"bazzz\")\n                result.check(packages: \"bar\", \"bazzz\", \"foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testDuplicateRootPackages() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    path: \"Nested/Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: []\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Foo\", \"Nested/Foo\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .equal(\"found multiple top-level packages named 'Foo'\"), severity: .error)\n            }\n        }\n    }\n\n    /// Test that the explicit name given to a package is not used as its identity.\n    func testExplicitPackageNameIsNotUsedAsPackageIdentity() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    path: \"foo-package\",\n                    targets: [\n                        MockTarget(\n                            name: \"FooTarget\",\n                            dependencies: [.product(name: \"BarProduct\", package: \"BarPackage\")]\n                        ),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"BarPackage\",\n                            path: \"bar-package\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v5\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar-package\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.0.1\"]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar-package\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.0.1\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(\n            roots: [\"foo-package\", \"bar-package\"],\n            dependencies: [\n                .localSourceControl(\n                    path: \"\\(sandbox)/pkgs/bar-package\",\n                    requirement: .upToNextMajor(from: \"1.0.0\")\n                ),\n            ]\n        ) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"foo-package\", \"bar-package\")\n                result.check(packages: \"foo-package\", \"bar-package\")\n                result.checkTarget(\"FooTarget\") { result in result.check(dependencies: \"BarProduct\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    /// Test that the remote repository is not resolved when a root package with same name is already present.\n    func testRootAsDependency1() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"BazAB\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"BazA\"),\n                        MockTarget(name: \"BazB\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazAB\", modules: [\"BazA\", \"BazB\"]),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\", \"Baz\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Baz\", \"Foo\")\n                result.check(packages: \"Baz\", \"Foo\")\n                result.check(modules: \"BazA\", \"BazB\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"BazAB\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(notPresent: \"baz\")\n        }\n        XCTAssertNoMatch(workspace.delegate.events, [.equal(\"fetching package: \\(sandbox)/pkgs/Baz\")])\n        XCTAssertNoMatch(workspace.delegate.events, [.equal(\"will resolve dependencies\")])\n    }\n\n    /// Test that a root package can be used as a dependency when the remote version was resolved previously.\n    func testRootAsDependency2() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"BazA\"),\n                        MockTarget(name: \"BazB\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"BazA\", \"BazB\"]),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        // Load only Foo right now so Baz is loaded from remote.\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Baz\", \"Foo\")\n                result.check(modules: \"Baz\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n        }\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [.equal(\"fetching package: \\(sandbox.appending(components: \"pkgs\", \"Baz\"))\")]\n        )\n        XCTAssertMatch(workspace.delegate.events, [.equal(\"will resolve dependencies\")])\n\n        // Now load with Baz as a root package.\n        workspace.delegate.clear()\n        try await workspace.checkPackageGraph(roots: [\"Foo\", \"Baz\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Baz\", \"Foo\")\n                result.check(packages: \"Baz\", \"Foo\")\n                result.check(modules: \"BazA\", \"BazB\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(notPresent: \"baz\")\n        }\n        XCTAssertNoMatch(\n            workspace.delegate.events,\n            [.equal(\"fetching package: \\(sandbox.appending(components: \"pkgs\", \"Baz\"))\")]\n        )\n        XCTAssertNoMatch(workspace.delegate.events, [.equal(\"will resolve dependencies\")])\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [.equal(\"removing repo: \\(sandbox.appending(components: \"pkgs\", \"Baz\"))\")]\n        )\n    }\n\n    func testGraphRootDependencies() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        let dependencies: [PackageDependency] = [\n            .localSourceControl(\n                path: workspace.packagesDir.appending(\"Bar\"),\n                requirement: .upToNextMajor(from: \"1.0.0\"),\n                productFilter: .specific([\"Bar\"])\n            ),\n            .localSourceControl(\n                path: workspace.packagesDir.appending(\"Foo\"),\n                requirement: .upToNextMajor(from: \"1.0.0\"),\n                productFilter: .specific([\"Foo\"])\n            ),\n        ]\n\n        try await workspace.checkPackageGraph(dependencies: dependencies) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"Bar\", \"Foo\")\n                result.check(modules: \"Bar\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Bar\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testCanResolveWithIncompatiblePackages() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(name: \"A\", dependencies: [\"AA\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"A\", modules: [\"A\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./AA\", requirement: .exact(\"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(name: \"A\", dependencies: [\"AA\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"A\", modules: [\"A\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./AA\", requirement: .exact(\"2.0.0\")),\n                    ],\n                    versions: [\"1.0.1\"]\n                ),\n                MockPackage(\n                    name: \"AA\",\n                    targets: [\n                        MockTarget(name: \"AA\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"AA\", modules: [\"AA\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        // Resolve when A = 1.0.0.\n        do {\n            let deps: [MockDependency] = [\n                .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\"), products: .specific([\"A\"])),\n            ]\n            try await workspace.checkPackageGraph(deps: deps) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(packages: \"A\", \"AA\")\n                    result.check(modules: \"A\", \"AA\")\n                    result.checkTarget(\"A\") { result in result.check(dependencies: \"AA\") }\n                }\n                XCTAssertNoDiagnostics(diagnostics)\n            }\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"a\", at: .checkout(.version(\"1.0.0\")))\n                result.check(dependency: \"aa\", at: .checkout(.version(\"1.0.0\")))\n            }\n            workspace.checkResolved { result in\n                result.check(dependency: \"a\", at: .checkout(.version(\"1.0.0\")))\n                result.check(dependency: \"aa\", at: .checkout(.version(\"1.0.0\")))\n            }\n        }\n\n        // Resolve when A = 1.0.1.\n        do {\n            let deps: [MockDependency] = [\n                .sourceControl(path: \"./A\", requirement: .exact(\"1.0.1\"), products: .specific([\"A\"])),\n            ]\n            try await workspace.checkPackageGraph(deps: deps) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.checkTarget(\"A\") { result in result.check(dependencies: \"AA\") }\n                }\n                XCTAssertNoDiagnostics(diagnostics)\n            }\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"a\", at: .checkout(.version(\"1.0.1\")))\n                result.check(dependency: \"aa\", at: .checkout(.version(\"2.0.0\")))\n            }\n            workspace.checkResolved { result in\n                result.check(dependency: \"a\", at: .checkout(.version(\"1.0.1\")))\n                result.check(dependency: \"aa\", at: .checkout(.version(\"2.0.0\")))\n            }\n            XCTAssertMatch(\n                workspace.delegate.events,\n                [.equal(\"updating repo: \\(sandbox.appending(components: \"pkgs\", \"A\"))\")]\n            )\n            XCTAssertMatch(\n                workspace.delegate.events,\n                [.equal(\"updating repo: \\(sandbox.appending(components: \"pkgs\", \"AA\"))\")]\n            )\n            XCTAssertEqual(workspace.delegate.events.filter { $0.hasPrefix(\"updating repo\") }.count, 2)\n        }\n    }\n\n    func testResolverCanHaveError() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(name: \"A\", dependencies: [\"AA\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"A\", modules: [\"A\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./AA\", requirement: .exact(\"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"B\",\n                    targets: [\n                        MockTarget(name: \"B\", dependencies: [\"AA\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"B\", modules: [\"B\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./AA\", requirement: .exact(\"2.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"AA\",\n                    targets: [\n                        MockTarget(name: \"AA\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"AA\", modules: [\"AA\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\"), products: .specific([\"A\"])),\n            .sourceControl(path: \"./B\", requirement: .exact(\"1.0.0\"), products: .specific([\"B\"])),\n        ]\n        try await workspace.checkPackageGraph(deps: deps) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .contains(\"Dependencies could not be resolved\"), severity: .error)\n            }\n        }\n        // There should be no extra fetches.\n        XCTAssertNoMatch(workspace.delegate.events, [.contains(\"updating repo\")])\n    }\n\n    func testPrecomputeResolution_empty() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let bPath = RelativePath(\"B\")\n        let v1_5 = CheckoutState.version(\"1.0.5\", revision: Revision(identifier: \"hello\"))\n        let v2 = CheckoutState.version(\"2.0.0\", revision: Revision(identifier: \"hello\"))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: []\n                ),\n            ],\n            packages: []\n        )\n\n        let bPackagePath = try workspace.pathToPackage(withName: \"B\")\n        let bRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: bPackagePath),\n            path: bPackagePath\n        )\n\n        let cPackagePath = try workspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await workspace.set(\n            resolvedPackages: [bRef: v1_5, cRef: v2],\n            managedDependencies: [\n                bPackagePath: .sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath)\n                    .edited(subpath: bPath, unmanagedPath: .none),\n            ]\n        )\n\n        let result = try await workspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(result.result.isRequired, false)\n    }\n\n    func testPrecomputeResolution_newPackages() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let bPath = RelativePath(\"B\")\n        let v1Requirement: SourceControlRequirement = .range(\"1.0.0\" ..< \"2.0.0\")\n        let v1 = CheckoutState.version(\"1.0.0\", revision: Revision(identifier: \"hello\"))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./B\", requirement: v1Requirement),\n                        .sourceControl(path: \"./C\", requirement: v1Requirement),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"B\",\n                    targets: [MockTarget(name: \"B\")],\n                    products: [MockProduct(name: \"B\", modules: [\"B\"])],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"C\",\n                    targets: [MockTarget(name: \"C\")],\n                    products: [MockProduct(name: \"C\", modules: [\"C\"])],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        let bPackagePath = try workspace.pathToPackage(withName: \"B\")\n        let bRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: bPackagePath),\n            path: bPackagePath\n        )\n\n        let cPackagePath = try workspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await workspace.set(\n            resolvedPackages: [bRef: v1],\n            managedDependencies: [\n                bPackagePath: .sourceControlCheckout(packageRef: bRef, state: v1, subpath: bPath),\n            ]\n        )\n\n        let result = try await workspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(result.result, .required(reason: .newPackages(packages: [cRef])))\n    }\n\n    func testPrecomputeResolution_requirementChange_versionToBranch() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let bPath = RelativePath(\"B\")\n        let cPath = RelativePath(\"C\")\n        let v1Requirement: SourceControlRequirement = .range(\"1.0.0\" ..< \"2.0.0\")\n        let branchRequirement: SourceControlRequirement = .branch(\"main\")\n        let v1_5 = CheckoutState.version(\"1.0.5\", revision: Revision(identifier: \"hello\"))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./B\", requirement: v1Requirement),\n                        .sourceControl(path: \"./C\", requirement: branchRequirement),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"B\",\n                    targets: [MockTarget(name: \"B\")],\n                    products: [MockProduct(name: \"B\", modules: [\"B\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"C\",\n                    targets: [MockTarget(name: \"C\")],\n                    products: [MockProduct(name: \"C\", modules: [\"C\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        let bPackagePath = try workspace.pathToPackage(withName: \"B\")\n        let bRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: bPackagePath),\n            path: bPackagePath\n        )\n\n        let cPackagePath = try workspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await workspace.set(\n            resolvedPackages: [bRef: v1_5, cRef: v1_5],\n            managedDependencies: [\n                bPackagePath: .sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),\n                cPackagePath: .sourceControlCheckout(packageRef: cRef, state: v1_5, subpath: cPath),\n            ]\n        )\n\n        let result = try await workspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(\n            package: cRef,\n            state: .sourceControlCheckout(v1_5),\n            requirement: .revision(\"main\")\n        )))\n    }\n\n    func testPrecomputeResolution_requirementChange_versionToRevision() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let cPath = RelativePath(\"C\")\n        let v1_5 = CheckoutState.version(\"1.0.5\", revision: Revision(identifier: \"hello\"))\n\n        let testWorkspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./C\", requirement: .revision(\"hello\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"C\",\n                    targets: [MockTarget(name: \"C\")],\n                    products: [MockProduct(name: \"C\", modules: [\"C\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        let cPackagePath = try testWorkspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await testWorkspace.set(\n            resolvedPackages: [cRef: v1_5],\n            managedDependencies: [\n                cPackagePath: .sourceControlCheckout(packageRef: cRef, state: v1_5, subpath: cPath),\n            ]\n        )\n\n        let result = try await testWorkspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(\n            package: cRef,\n            state: .sourceControlCheckout(v1_5),\n            requirement: .revision(\"hello\")\n        )))\n    }\n\n    func testPrecomputeResolution_requirementChange_localToBranch() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let bPath = RelativePath(\"B\")\n        let v1Requirement: SourceControlRequirement = .range(\"1.0.0\" ..< \"2.0.0\")\n        let masterRequirement: SourceControlRequirement = .branch(\"main\")\n        let v1_5 = CheckoutState.version(\"1.0.5\", revision: Revision(identifier: \"hello\"))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./B\", requirement: v1Requirement),\n                        .sourceControl(path: \"./C\", requirement: masterRequirement),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"B\",\n                    targets: [MockTarget(name: \"B\")],\n                    products: [MockProduct(name: \"B\", modules: [\"B\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"C\",\n                    targets: [MockTarget(name: \"C\")],\n                    products: [MockProduct(name: \"C\", modules: [\"C\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        let bPackagePath = try workspace.pathToPackage(withName: \"B\")\n        let bRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: bPackagePath),\n            path: bPackagePath\n        )\n\n        let cPackagePath = try workspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await workspace.set(\n            resolvedPackages: [bRef: v1_5],\n            managedDependencies: [\n                bPackagePath: .sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),\n                cPackagePath: .fileSystem(packageRef: cRef),\n            ]\n        )\n\n        let result = try await workspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(\n            package: cRef,\n            state: .fileSystem(cPackagePath),\n            requirement: .revision(\"main\")\n        )))\n    }\n\n    func testPrecomputeResolution_requirementChange_versionToLocal() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let bPath = RelativePath(\"B\")\n        let cPath = RelativePath(\"C\")\n        let v1Requirement: SourceControlRequirement = .range(\"1.0.0\" ..< \"2.0.0\")\n        let v1_5 = CheckoutState.version(\"1.0.5\", revision: Revision(identifier: \"hello\"))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./B\", requirement: v1Requirement),\n                        .fileSystem(path: \"./C\"),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"B\",\n                    targets: [MockTarget(name: \"B\")],\n                    products: [MockProduct(name: \"B\", modules: [\"B\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"C\",\n                    targets: [MockTarget(name: \"C\")],\n                    products: [MockProduct(name: \"C\", modules: [\"C\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        let bPackagePath = try workspace.pathToPackage(withName: \"B\")\n        let bRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: bPackagePath),\n            path: bPackagePath\n        )\n\n        let cPackagePath = try workspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await workspace.set(\n            resolvedPackages: [bRef: v1_5, cRef: v1_5],\n            managedDependencies: [\n                bPackagePath: .sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),\n                cPackagePath: .sourceControlCheckout(packageRef: cRef, state: v1_5, subpath: cPath),\n            ]\n        )\n\n        let result = try await workspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(\n            package: cRef,\n            state: .sourceControlCheckout(v1_5),\n            requirement: .unversioned\n        )))\n    }\n\n    func testPrecomputeResolution_requirementChange_branchToLocal() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let bPath = RelativePath(\"B\")\n        let cPath = RelativePath(\"C\")\n        let v1Requirement: SourceControlRequirement = .range(\"1.0.0\" ..< \"2.0.0\")\n        let v1_5 = CheckoutState.version(\"1.0.5\", revision: Revision(identifier: \"hello\"))\n        let main = CheckoutState.branch(name: \"main\", revision: Revision(identifier: \"main\"))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./B\", requirement: v1Requirement),\n                        .fileSystem(path: \"./C\"),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"B\",\n                    targets: [MockTarget(name: \"B\")],\n                    products: [MockProduct(name: \"B\", modules: [\"B\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"C\",\n                    targets: [MockTarget(name: \"C\")],\n                    products: [MockProduct(name: \"C\", modules: [\"C\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        let bPackagePath = try workspace.pathToPackage(withName: \"B\")\n        let bRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: bPackagePath),\n            path: bPackagePath\n        )\n\n        let cPackagePath = try workspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await workspace.set(\n            resolvedPackages: [bRef: v1_5, cRef: main],\n            managedDependencies: [\n                bPackagePath: .sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),\n                cPackagePath: .sourceControlCheckout(packageRef: cRef, state: main, subpath: cPath),\n            ]\n        )\n\n        let result = try await workspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(result.result, .required(reason: .packageRequirementChange(\n            package: cRef,\n            state: .sourceControlCheckout(main),\n            requirement: .unversioned\n        )))\n    }\n\n    func testPrecomputeResolution_other() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let bPath = RelativePath(\"B\")\n        let cPath = RelativePath(\"C\")\n        let v1Requirement: SourceControlRequirement = .range(\"1.0.0\" ..< \"2.0.0\")\n        let v2Requirement: SourceControlRequirement = .range(\"2.0.0\" ..< \"3.0.0\")\n        let v1_5 = CheckoutState.version(\"1.0.5\", revision: Revision(identifier: \"hello\"))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./B\", requirement: v1Requirement),\n                        .sourceControl(path: \"./C\", requirement: v2Requirement),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"B\",\n                    targets: [MockTarget(name: \"B\")],\n                    products: [MockProduct(name: \"B\", modules: [\"B\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"C\",\n                    targets: [MockTarget(name: \"C\")],\n                    products: [MockProduct(name: \"C\", modules: [\"C\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        let bPackagePath = try workspace.pathToPackage(withName: \"B\")\n        let bRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: bPackagePath),\n            path: bPackagePath\n        )\n\n        let cPackagePath = try workspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await workspace.set(\n            resolvedPackages: [bRef: v1_5, cRef: v1_5],\n            managedDependencies: [\n                bPackagePath: .sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),\n                cPackagePath: .sourceControlCheckout(packageRef: cRef, state: v1_5, subpath: cPath),\n            ]\n        )\n\n        let result = try await workspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(\n            result.result,\n            .required(reason: .other(\n                \"Dependencies could not be resolved because no versions of \\'c\\' match the requirement 2.0.0..<3.0.0 and root depends on \\'c\\' 2.0.0..<3.0.0.\"\n            ))\n        )\n    }\n\n    func testPrecomputeResolution_notRequired() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let bPath = RelativePath(\"B\")\n        let cPath = RelativePath(\"C\")\n        let v1Requirement: SourceControlRequirement = .range(\"1.0.0\" ..< \"2.0.0\")\n        let v2Requirement: SourceControlRequirement = .range(\"2.0.0\" ..< \"3.0.0\")\n        let v1_5 = CheckoutState.version(\"1.0.5\", revision: Revision(identifier: \"hello\"))\n        let v2 = CheckoutState.version(\"2.0.0\", revision: Revision(identifier: \"hello\"))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [MockTarget(name: \"A\")],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./B\", requirement: v1Requirement),\n                        .sourceControl(path: \"./C\", requirement: v2Requirement),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"B\",\n                    targets: [MockTarget(name: \"B\")],\n                    products: [MockProduct(name: \"B\", modules: [\"B\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"C\",\n                    targets: [MockTarget(name: \"C\")],\n                    products: [MockProduct(name: \"C\", modules: [\"C\"])],\n                    versions: [nil, \"1.0.0\", \"1.0.5\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        let bPackagePath = try workspace.pathToPackage(withName: \"B\")\n        let bRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: bPackagePath),\n            path: bPackagePath\n        )\n\n        let cPackagePath = try workspace.pathToPackage(withName: \"C\")\n        let cRef = PackageReference.localSourceControl(\n            identity: PackageIdentity(path: cPackagePath),\n            path: cPackagePath\n        )\n\n        try await workspace.set(\n            resolvedPackages: [bRef: v1_5, cRef: v2],\n            managedDependencies: [\n                bPackagePath: .sourceControlCheckout(packageRef: bRef, state: v1_5, subpath: bPath),\n                cPackagePath: .sourceControlCheckout(packageRef: cRef, state: v2, subpath: cPath),\n            ]\n        )\n\n        let result = try await workspace.checkPrecomputeResolution()\n        XCTAssertNoDiagnostics(result.diagnostics)\n        XCTAssertEqual(result.result.isRequired, false)\n    }\n\n    func testLoadingRootManifests() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                .genericPackage(named: \"A\"),\n                .genericPackage(named: \"B\"),\n                .genericPackage(named: \"C\"),\n            ],\n            packages: []\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"A\", \"B\", \"C\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"A\", \"B\", \"C\")\n                result.check(modules: \"A\", \"B\", \"C\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testUpdate() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Root\", modules: [\"Root\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        // Do an initial run, capping at Foo at 1.0.0.\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Foo\", requirement: .exact(\"1.0.0\"), products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Bar\", \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Run update.\n        try await workspace.checkUpdate(roots: [\"Root\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.5.0\")))\n        }\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [.equal(\"removing repo: \\(sandbox.appending(components: \"pkgs\", \"Bar\"))\")]\n        )\n\n        // Run update again.\n        // Ensure that up-to-date delegate is called when there is nothing to update.\n        try await workspace.checkUpdate(roots: [\"Root\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        XCTAssertMatch(workspace.delegate.events, [.equal(\"Everything is already up-to-date\")])\n    }\n\n    func testUpdateDryRun() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Root\", modules: [\"Root\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.5.0\"]\n                ),\n            ]\n        )\n\n        // Do an initial run, capping at Foo at 1.0.0.\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Foo\", requirement: .exact(\"1.0.0\"), products: .specific([\"Foo\"])),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Run update.\n        try await workspace.checkUpdateDryRun(roots: [\"Root\"]) { changes, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n            let stateChange = Workspace.PackageStateChange\n                .updated(.init(requirement: .version(Version(\"1.5.0\")), products: .specific([\"Foo\"])))\n            #else\n            let stateChange = Workspace.PackageStateChange\n                .updated(.init(requirement: .version(Version(\"1.5.0\")), products: .everything))\n            #endif\n\n            let path = sandbox.appending(components: [\"pkgs\",\"Foo\"])\n            let expectedChange = (\n                PackageReference.localSourceControl(identity: PackageIdentity(path: path), path: path),\n                stateChange\n            )\n            guard let change = changes?.first, changes?.count == 1 else {\n                XCTFail()\n                return\n            }\n            XCTAssertEqual(expectedChange, change)\n        }\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testPartialUpdate() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Root\", modules: [\"Root\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMinor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.2.0\"]\n                ),\n            ]\n        )\n\n        // Do an initial run, capping at Foo at 1.0.0.\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Foo\", requirement: .exact(\"1.0.0\"), products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Run partial updates.\n        //\n        // Try to update just Bar. This shouldn't do anything because Bar can't be updated due\n        // to Foo's requirements.\n        try await workspace.checkUpdate(roots: [\"Root\"], packages: [\"Bar\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Try to update just Foo. This should update Foo but not Bar.\n        try await workspace.checkUpdate(roots: [\"Root\"], packages: [\"Foo\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.5.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Run full update.\n        try await workspace.checkUpdate(roots: [\"Root\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.5.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.2.0\")))\n        }\n    }\n\n    func testCleanAndReset() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Root\", modules: [\"Root\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        // Load package graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Drop a build artifact in data directory.\n        let ws = try workspace.getOrCreateWorkspace()\n        let buildArtifact = ws.location.scratchDirectory.appending(\"test.o\")\n        try fs.writeFileContents(buildArtifact, bytes: \"Hi\")\n\n        // Double checks.\n        XCTAssert(fs.exists(buildArtifact))\n        XCTAssert(fs.exists(ws.location.repositoriesCheckoutsDirectory))\n\n        // Check clean.\n        workspace.checkClean { diagnostics in\n            // Only the build artifact should be removed.\n            XCTAssertFalse(fs.exists(buildArtifact))\n            XCTAssert(fs.exists(ws.location.repositoriesCheckoutsDirectory))\n            XCTAssert(fs.exists(ws.location.scratchDirectory))\n\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Add the build artifact again.\n        try fs.writeFileContents(buildArtifact, bytes: \"Hi\")\n\n        // Check reset.\n        await workspace.checkReset { diagnostics in\n            // Only the build artifact should be removed.\n            XCTAssertFalse(fs.exists(buildArtifact))\n            XCTAssertFalse(fs.exists(ws.location.repositoriesCheckoutsDirectory))\n            XCTAssertFalse(fs.exists(ws.location.scratchDirectory))\n\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.checkEmpty()\n        }\n    }\n\n    func testDependencyManifestLoading() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs: InMemoryFileSystem = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root1\",\n                    targets: [\n                        MockTarget(name: \"Root1\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Root2\",\n                    targets: [\n                        MockTarget(name: \"Root2\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                .genericPackage(named: \"Foo\"),\n                .genericPackage(named: \"Bar\"),\n            ]\n        )\n\n        // Check that we can compute missing dependencies.\n        try await workspace.loadDependencyManifests(roots: [\"Root1\", \"Root2\"]) { manifests, diagnostics in\n            XCTAssertEqual(\n                try! manifests.missingPackages.map(\\.locationString).sorted(),\n                [\n                    sandbox.appending(components: \"pkgs\", \"Bar\").pathString,\n                    sandbox.appending(components: \"pkgs\", \"Foo\").pathString,\n                ]\n            )\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Load the graph with one root.\n        try await workspace.checkPackageGraph(roots: [\"Root1\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"Foo\", \"Root1\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Check that we compute the correct missing dependencies.\n        try await workspace.loadDependencyManifests(roots: [\"Root1\", \"Root2\"]) { manifests, diagnostics in\n            XCTAssertEqual(\n                try! manifests.missingPackages.map(\\.locationString).sorted(),\n                [sandbox.appending(components: \"pkgs\", \"Bar\").pathString]\n            )\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Load the graph with both roots.\n        try await workspace.checkPackageGraph(roots: [\"Root1\", \"Root2\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"Bar\", \"Foo\", \"Root1\", \"Root2\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Check that we compute the correct missing dependencies.\n        try await workspace.loadDependencyManifests(roots: [\"Root1\", \"Root2\"]) { manifests, diagnostics in\n            XCTAssertEqual(try! manifests.missingPackages.map(\\.locationString).sorted(), [])\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testDependencyManifestsOrder() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root1\",\n                    targets: [\n                        MockTarget(name: \"Root1\", dependencies: [\"Foo\", \"Bar\", \"Baz\", \"Bam\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Bam\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\", \"Baz\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                .genericPackage(named: \"Bar\"),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\", dependencies: [\"Bam\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bam\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                .genericPackage(named: \"Bam\"),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root1\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        try await workspace.loadDependencyManifests(roots: [\"Root1\"]) { manifests, diagnostics in\n            // Ensure that the order of the manifests is stable.\n            XCTAssertEqual(\n                manifests.allDependencyManifests.map(\\.value.manifest.displayName),\n                [\"Bam\", \"Baz\", \"Bar\", \"Foo\"]\n            )\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testBranchAndRevision() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .branch(\"develop\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"develop\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"boo\"]\n                ),\n            ]\n        )\n\n        // Get some revision identifier of Bar.\n        let bar = RepositorySpecifier(path: \"\\(sandbox)/pkgs/Bar\")\n        let barRevision = workspace.repositoryProvider.specifierMap[bar]!.revisions[0]\n\n        // We request Bar via revision.\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Bar\", requirement: .revision(barRevision), products: .specific([\"Bar\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Bar\", \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.branch(\"develop\")))\n            result.check(dependency: \"bar\", at: .checkout(.revision(barRevision)))\n        }\n    }\n\n    func testResolve() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.2.3\"]\n                ),\n            ]\n        )\n\n        // Load initial version.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.2.3\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.2.3\")))\n        }\n\n        // Resolve to an older version.\n        await workspace.checkResolve(pkg: \"Foo\", roots: [\"Root\"], version: \"1.0.0\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Check failure.\n        await workspace.checkResolve(pkg: \"Foo\", roots: [\"Root\"], version: \"1.3.0\") { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .contains(\"'foo' 1.3.0\"), severity: .error)\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testDeletedCheckoutDirectory() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                .genericPackage(named: \"Foo\"),\n            ]\n        )\n\n        // Load the graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        try fs.removeFileTree(workspace.getOrCreateWorkspace().location.repositoriesCheckoutsDirectory)\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .contains(\"dependency 'foo' is missing; cloning again\"), severity: .warning)\n            }\n        }\n    }\n\n    func testMinimumRequiredToolsVersionInDependencyResolution() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    toolsVersion: .v3\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .contains(\"'foo' 1.0.0..<2.0.0\"), severity: .error)\n            }\n        }\n    }\n\n    func testToolsVersionRootPackages() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: []\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: []\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: []\n                ),\n            ],\n            packages: [],\n            toolsVersion: .v4\n        )\n\n        let roots = try workspace.rootPaths(for: [\"Foo\", \"Bar\", \"Baz\"]).map { $0.appending(\"Package.swift\") }\n\n        try fs.writeFileContents(roots[0], bytes: \"// swift-tools-version:4.0\")\n        try fs.writeFileContents(roots[1], bytes: \"// swift-tools-version:4.1.0\")\n        try fs.writeFileContents(roots[2], bytes: \"// swift-tools-version:3.1\")\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkPackageGraphFailure(roots: [\"Bar\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let diagnostic = result.check(\n                    diagnostic: .equal(\n                        \"package 'bar' is using Swift tools version 4.1.0 but the installed version is 4.0.0\"\n                    ),\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic?.metadata?.packageIdentity, .plain(\"bar\"))\n            }\n        }\n        await workspace.checkPackageGraphFailure(roots: [\"Foo\", \"Bar\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let diagnostic = result.check(\n                    diagnostic: .equal(\n                        \"package 'bar' is using Swift tools version 4.1.0 but the installed version is 4.0.0\"\n                    ),\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic?.metadata?.packageIdentity, .plain(\"bar\"))\n            }\n        }\n        await workspace.checkPackageGraphFailure(roots: [\"Baz\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let diagnostic = result.check(\n                    diagnostic: .equal(\n                        \"package 'baz' is using Swift tools version 3.1.0 which is no longer supported; consider using '// swift-tools-version:4.0' to specify the current tools version\"\n                    ),\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic?.metadata?.packageIdentity, .plain(\"baz\"))\n            }\n        }\n    }\n\n\n    func testEditDependency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\", \"Bar\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        // Load the graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: .plain(\"Root\"))\n                result.check(packages: .plain(\"bar\"), .plain(\"foo\"), .plain(\"Root\"))\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Edit foo.\n        let fooPath = try workspace.getOrCreateWorkspace().location.editsDirectory.appending(\"foo\")\n        await workspace.checkEdit(packageIdentity: \"foo\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .edited(nil))\n        }\n        XCTAssertTrue(fs.exists(fooPath))\n\n        try await workspace.loadDependencyManifests(roots: [\"Root\"]) { manifests, diagnostics in\n            let editedPackages = manifests.editedPackagesConstraints\n            XCTAssertEqual(editedPackages.map(\\.package.locationString), [fooPath.pathString])\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Try re-editing foo.\n        await workspace.checkEdit(packageIdentity: \"foo\") { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .equal(\"dependency 'foo' already in edit mode\"), severity: .error)\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .edited(nil))\n        }\n\n        // Try editing bar at bad revision.\n        await workspace.checkEdit(packageIdentity: \"bar\", revision: Revision(identifier: \"dev\")) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .equal(\"revision 'dev' does not exist\"), severity: .error)\n            }\n        }\n\n        // Edit bar at a custom path and branch (ToT).\n        let barPath = sandbox.appending(components: [\"custom\", \"bar\"])\n        await workspace.checkEdit(packageIdentity: \"bar\", path: barPath, checkoutBranch: \"dev\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"bar\", at: .edited(barPath))\n        }\n        let barRepo = try await workspace.repositoryProvider.openWorkingCopy(at: barPath) as! InMemoryGitRepository\n        XCTAssert(barRepo.revisions.contains(\"dev\"))\n\n        // Test unediting.\n        await workspace.checkUnedit(packageIdentity: \"foo\", roots: [\"Root\"]) { diagnostics in\n            XCTAssertFalse(fs.exists(fooPath))\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkUnedit(packageIdentity: \"bar\", roots: [\"Root\"]) { diagnostics in\n            XCTAssert(fs.exists(barPath))\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testUnsafeFlagsInEditedPackage() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"Root\",\n                            dependencies: [\"Foo\"],\n                            settings: [\n                                .init(tool: .swift, kind: .unsafeFlags([\"-F\", \"/tmp\"])),\n                            ]\n                        ),\n                    ],\n                    products: [],\n                    dependencies: [\n                        // Must be a branch or revision for unsafe flags\n                        .sourceControl(path: \"./Foo\", requirement: .revision(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            settings: [\n                                .init(tool: .swift, kind: .unsafeFlags([\"-F\", \"/tmp\"])),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: .plain(\"Root\"))\n                result.check(packages: .plain(\"root\"), .plain(\"Foo\"))\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        let editedFooPath = sandbox.appending(\"Foo\")\n        await workspace.checkEdit(packageIdentity: \"Foo\", path: editedFooPath) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testMissingEditCanRestoreOriginalCheckout() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        // Load the graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, _ in }\n\n        // Edit foo.\n        let fooPath = try workspace.getOrCreateWorkspace().location.editsDirectory.appending(\"Foo\")\n        await workspace.checkEdit(packageIdentity: \"Foo\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .edited(nil))\n        }\n        XCTAssertTrue(fs.exists(fooPath))\n\n        // Remove the edited package.\n        try fs.removeFileTree(fooPath)\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .equal(\n                        \"dependency 'foo' was being edited but is missing; falling back to original checkout\"\n                    ),\n                    severity: .warning\n                )\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testCanUneditRemovedDependencies() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\"), products: .specific([\"Foo\"])),\n        ]\n        let ws = try workspace.getOrCreateWorkspace()\n\n        // Load the graph and edit foo.\n        try await workspace.checkPackageGraph(deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"Foo\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkEdit(packageIdentity: \"Foo\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .edited(nil))\n        }\n\n        // Remove foo.\n        try await workspace.checkUpdate { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [.equal(\"removing repo: \\(sandbox.appending(components: \"pkgs\", \"Foo\"))\")]\n        )\n        try await workspace.checkPackageGraph(deps: []) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // There should still be an entry for `foo`, which we can unedit.\n        let editedDependency = await ws.state.dependencies[.plain(\"foo\")]\n        if case .edited(let basedOn, _) = editedDependency?.state {\n            XCTAssertNil(basedOn)\n        } else {\n            XCTFail(\"expected edited dependency\")\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .edited(nil))\n        }\n\n        // Unedit foo.\n        await workspace.checkUnedit(packageIdentity: \"Foo\", roots: []) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.checkEmpty()\n        }\n    }\n\n    func testDependencyResolutionWithEdit() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\", \"Bar\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.2.0\", \"1.3.2\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Foo\", requirement: .exact(\"1.0.0\"), products: .specific([\"Foo\"])),\n        ]\n        // Load the graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Bar\", \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Edit bar.\n        await workspace.checkEdit(packageIdentity: \"Bar\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .edited(nil))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Add entry for the edited package.\n        do {\n            let barKey = MockManifestLoader.Key(url: sandbox.appending(components: \"pkgs\", \"Bar\").pathString)\n            let editedBarKey = MockManifestLoader.Key(url: sandbox.appending(components: \"edits\", \"Bar\").pathString)\n            let manifest = workspace.manifestLoader.manifests[barKey]!\n            workspace.manifestLoader.manifests[editedBarKey] = manifest\n        }\n\n        // Now, resolve foo at a different version.\n        await workspace.checkResolve(pkg: \"Foo\", roots: [\"Root\"], version: \"1.2.0\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.2.0\")))\n            result.check(dependency: \"bar\", at: .edited(nil))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.2.0\")))\n            result.check(notPresent: \"bar\")\n        }\n\n        // Try package update.\n        try await workspace.checkUpdate(roots: [\"Root\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.3.2\")))\n            result.check(dependency: \"bar\", at: .edited(nil))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.3.2\")))\n            result.check(notPresent: \"bar\")\n        }\n\n        // Unedit should get the Package.resolved entry back.\n        await workspace.checkUnedit(packageIdentity: \"bar\", roots: [\"Root\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.3.2\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.3.2\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testPrefetchingWithOverridenPackage() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [nil]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        // Load the graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        let deps: [MockDependency] = [\n            .fileSystem(path: \"./Foo\", products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Bar\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .local)\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    // Test that changing a particular dependency re-resolves the graph.\n    func testChangeOneDependency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ]\n        )\n\n        // Initial resolution.\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Bar\", \"Foo\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Check that changing the requirement to 1.5.0 triggers re-resolution.\n        let fooKey = MockManifestLoader.Key(url: sandbox.appending(components: \"roots\", \"Foo\").pathString)\n        let manifest = workspace.manifestLoader.manifests[fooKey]!\n\n        let dependency = manifest.dependencies[0]\n        switch dependency {\n        case .sourceControl(let settings):\n            let updatedDependency: PackageDependency = .sourceControl(\n                identity: settings.identity,\n                nameForTargetDependencyResolutionOnly: settings.nameForTargetDependencyResolutionOnly,\n                location: settings.location,\n                requirement: .exact(\"1.5.0\"),\n                productFilter: settings.productFilter\n            )\n\n            workspace.manifestLoader.manifests[fooKey] = Manifest.createManifest(\n                displayName: manifest.displayName,\n                path: manifest.path,\n                packageKind: manifest.packageKind,\n                packageIdentity: manifest.packageIdentity,\n                packageLocation: manifest.packageLocation,\n                platforms: [],\n                version: manifest.version,\n                toolsVersion: manifest.toolsVersion,\n                dependencies: [updatedDependency],\n                targets: manifest.targets\n            )\n        default:\n            XCTFail(\"unexpected dependency type\")\n        }\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.5.0\")))\n        }\n    }\n\n    func testResolutionFailureWithEditedDependency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        // Load the graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkEdit(packageIdentity: \"Foo\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .edited(nil))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Add entry for the edited package.\n        do {\n            let fooKey = MockManifestLoader.Key(url: sandbox.appending(components: \"pkgs\", \"Foo\").pathString)\n            let editedFooKey = MockManifestLoader.Key(url: sandbox.appending(components: \"edits\", \"Foo\").pathString)\n            let manifest = workspace.manifestLoader.manifests[fooKey]!\n            workspace.manifestLoader.manifests[editedFooKey] = manifest\n        }\n\n    }\n    func testResolutionFailureWithEditedDependencyWithABadGraph() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // Try resolving a bad graph.\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Bar\", requirement: .exact(\"1.1.0\"), products: .specific([\"Bar\"])),\n        ]\n\n        // Replicate earlier workspace, include Bar dependency in target so that dependency resolution can include it.\n        let badWorkspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\", \"Bar\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n        try await badWorkspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .contains(\"'bar' 1.1.0\"), severity: .error)\n            }\n        }\n    }\n\n    func testStateModified() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\n                            .product(name: \"Foo\", package: \"foo\"),\n                            .product(name: \"Bar\", package: \"bar\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"https://scm.com/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://scm.com/org/foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [nil, \"1.0.0\", \"1.1.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"https://scm.com/org/bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: []) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"Bar\", \"Foo\", \"Root\")\n            }\n        }\n\n        let underlying = try workspace.getOrCreateWorkspace()\n        let fooEditPath = sandbox.appending(components: [\"edited\", \"foo\"])\n\n        // mimic external process putting a dependency into edit mode\n        do {\n            try fs.writeFileContents(fooEditPath.appending(\"Package.swift\"), string: \"// swift-tools-version: 5.6\")\n\n            let fooState = await underlying.state.dependencies[.plain(\"foo\")]!\n            let externalState = await WorkspaceState(\n                fileSystem: fs,\n                storageDirectory: underlying.state.storagePath.parentDirectory,\n                initializationWarningHandler: { _ in }\n            )\n            await externalState.remove(identity: fooState.packageRef.identity)\n            try await externalState.add(dependency: fooState.edited(subpath: \"foo\", unmanagedPath: fooEditPath))\n            try await externalState.save()\n        }\n\n        // reload graph after \"external\" change\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: []) { graph, _ in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"Bar\", \"Foo\", \"Root\")\n            }\n        }\n\n        do {\n            let fooState = await underlying.state.dependencies[.plain(\"foo\")]!\n            guard case .edited(basedOn: _, unmanagedPath: fooEditPath) = fooState.state else {\n                XCTFail(\n                    \"'\\(fooState.packageRef.identity)' dependency expected to be in edit mode, but was: \\(fooState)\"\n                )\n                return\n            }\n        }\n    }\n\n    func testSkipUpdate() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Root\", modules: [\"Root\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.5.0\"]\n                ),\n            ],\n            skipDependenciesUpdates: true\n        )\n\n        // Run update and remove all events.\n        try await workspace.checkUpdate(roots: [\"Root\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        workspace.delegate.clear()\n\n        // Check we don't have updating Foo event.\n        try await workspace.checkUpdate(roots: [\"Root\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertMatch(workspace.delegate.events, [\"Everything is already up-to-date\"])\n        }\n    }\n\n    func testLocalDependencyBasics() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\", \"Baz\"]),\n                        MockTarget(name: \"FooTests\", dependencies: [\"Foo\"], type: .test),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .fileSystem(path: \"./Bar\"),\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\", nil]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Bar\", \"Baz\", \"Foo\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\")\n                result.check(testModules: \"FooTests\")\n                result.checkTarget(\"Baz\") { result in result.check(dependencies: \"Bar\") }\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\", \"Bar\") }\n                result.checkTarget(\"FooTests\") { result in result.check(dependencies: \"Foo\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.5.0\")))\n            result.check(dependency: \"bar\", at: .local)\n        }\n\n        // Test that its not possible to edit or resolve this package.\n        await workspace.checkEdit(packageIdentity: \"Bar\") { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .contains(\"local dependency 'bar' can't be edited\"), severity: .error)\n            }\n        }\n        await workspace.checkResolve(pkg: \"Bar\", roots: [\"Foo\"], version: \"1.0.0\") { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .contains(\"local dependency 'bar' can't be resolved\"), severity: .error)\n            }\n        }\n    }\n\n\n    func testLocalDependencyTransitive() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                        MockTarget(name: \"FooTests\", dependencies: [\"Foo\"], type: .test),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\", dependencies: [\"Baz\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    dependencies: [\n                        .fileSystem(path: \"./Baz\"),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\", nil]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\", nil]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Foo\")\n                result.check(modules: \"Foo\")\n            }\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\"'bar' {1.0.0..<1.5.0, 1.5.1..<2.0.0} cannot be used\"),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testLocalDependencyWithPackageUpdate() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\", nil]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Bar\", \"Foo\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.5.0\")))\n        }\n\n        // Override with local package and run update.\n        let deps: [MockDependency] = [\n            .fileSystem(path: \"./Bar\", products: .specific([\"Bar\"])),\n        ]\n        try await workspace.checkUpdate(roots: [\"Foo\"], deps: deps) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"bar\", at: .local)\n        }\n\n        // Go back to the versioned state.\n        try await workspace.checkUpdate(roots: [\"Foo\"]) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.5.0\")))\n        }\n    }\n\n    func testMissingLocalDependencyDiagnostic() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .fileSystem(path: \"Bar\"),\n                    ]\n                ),\n            ],\n            packages: [\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Foo\")\n                result.check(modules: \"Foo\")\n            }\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\n                        \"the package at '\\(sandbox.appending(components: \"pkgs\", \"Bar\"))' cannot be accessed (\\(sandbox.appending(components: \"pkgs\", \"Bar\")) doesn't exist in file system\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testRevisionVersionSwitch() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"develop\", \"1.0.0\"]\n                ),\n            ]\n        )\n\n        // Test that switching between revision and version requirement works\n        // without running swift package update.\n\n        var deps: [MockDependency] = [\n            .sourceControl(path: \"./Foo\", requirement: .branch(\"develop\"), products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.branch(\"develop\")))\n        }\n\n        deps = [\n            .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\"), products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        deps = [\n            .sourceControl(path: \"./Foo\", requirement: .branch(\"develop\"), products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.branch(\"develop\")))\n        }\n    }\n\n    func testLocalVersionSwitch() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"develop\", \"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        // Test that switching between local and version requirement works\n        // without running swift package update.\n\n        var deps: [MockDependency] = [\n            .fileSystem(path: \"./Foo\", products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .local)\n        }\n\n        deps = [\n            .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\"), products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        deps = [\n            .fileSystem(path: \"./Foo\", products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .local)\n        }\n    }\n\n    func testLocalLocalSwitch() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [nil]\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    path: \"Foo2\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [nil]\n                ),\n            ]\n        )\n\n        // Test that switching between two same local packages placed at\n        // different locations works correctly.\n\n        var deps: [MockDependency] = [\n            .fileSystem(path: \"./Foo\", products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .local)\n        }\n\n        deps = [\n            .fileSystem(path: \"./Foo2\", products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo2\", at: .local)\n        }\n    }\n\n    // Test that switching between two same local packages placed at\n    // different locations works correctly.\n    func testDependencySwitchLocalWithSameIdentity() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [nil]\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    path: \"Nested/Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [nil]\n                ),\n            ]\n        )\n\n        var deps: [MockDependency] = [\n            .fileSystem(path: \"./Foo\", products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .local)\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"foo\")]?.packageRef.locationString,\n                sandbox.appending(components: \"pkgs\", \"Foo\").pathString\n            )\n        }\n\n        deps = [\n            .fileSystem(path: \"./Nested/Foo\", products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .local)\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"foo\")]?.packageRef.locationString,\n                sandbox.appending(components: \"pkgs\", \"Nested\", \"Foo\").pathString\n            )\n        }\n    }\n\n    // Test that switching between two remote packages at\n    // different locations works correctly.\n    func testDependencySwitchRemoteWithSameIdentity() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://scm.com/org/foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://scm.com/other/foo\",\n                    targets: [\n                        MockTarget(name: \"OtherFoo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"OtherFoo\", modules: [\"OtherFoo\"]),\n                    ],\n                    versions: [\"1.1.0\"]\n                ),\n            ]\n        )\n\n        var deps: [MockDependency] = [\n            .sourceControl(url: \"https://scm.com/org/foo\", requirement: .exact(\"1.0.0\")),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Foo\", \"Root\")\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n        do {\n            let ws = try workspace.getOrCreateWorkspace()\n            let locationString = await ws.state.dependencies[.plain(\"foo\")]?.packageRef.locationString\n            XCTAssertEqual(locationString, \"https://scm.com/org/foo\")\n        }\n\n        deps = [\n            .sourceControl(url: \"https://scm.com/other/foo\", requirement: .exact(\"1.1.0\")),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.1.0\")))\n        }\n        do {\n            let ws = try workspace.getOrCreateWorkspace()\n            let locationString = await ws.state.dependencies[.plain(\"foo\")]?.packageRef.locationString\n            XCTAssertEqual(locationString, \"https://scm.com/other/foo\")\n        }\n    }\n\n    func testResolvedFileUpdate() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\"), products: .specific([\"Foo\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: []) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n        }\n        workspace.checkResolved { result in\n            result.check(notPresent: \"foo\")\n        }\n    }\n\n    func testResolvedFileSchemeToolsVersion() async throws {\n        for pair in [\n            (ToolsVersion.v5_2, ToolsVersion.v5_2),\n            (ToolsVersion.v5_6, ToolsVersion.v5_6),\n            (ToolsVersion.v5_2, ToolsVersion.v5_6),\n        ] {\n            let fs = InMemoryFileSystem()\n            let sandbox = AbsolutePath(\"/tmp/ws/\")\n            let workspace = try await MockWorkspace(\n                sandbox: sandbox,\n                fileSystem: fs,\n                roots: [\n                    MockPackage(\n                        name: \"Root1\",\n                        targets: [\n                            MockTarget(name: \"Root1\", dependencies: [\"Foo\"]),\n                        ],\n                        products: [],\n                        dependencies: [\n                            .sourceControl(\n                                path: \"./Foo\",\n                                requirement: .upToNextMajor(from: \"1.0.0\"),\n                                products: .specific([\"Foo\"])\n                            ),\n                        ],\n                        toolsVersion: pair.0\n                    ),\n                    MockPackage(\n                        name: \"Root2\",\n                        targets: [\n                            MockTarget(name: \"Root2\", dependencies: []),\n                        ],\n                        products: [],\n                        dependencies: [],\n                        toolsVersion: pair.1\n                    ),\n                ],\n                packages: [\n                    MockPackage(\n                        name: \"Foo\",\n                        targets: [\n                            MockTarget(name: \"Foo\"),\n                        ],\n                        products: [\n                            MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                        ],\n                        versions: [\"1.0.0\"]\n                    ),\n                ]\n            )\n\n            try await workspace.checkPackageGraph(roots: [\"Root1\", \"Root2\"]) { _, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n            }\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            }\n            workspace.checkResolved { result in\n                result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            }\n\n            let minToolsVersion = [pair.0, pair.1].min()!\n            let expectedSchemeVersion = minToolsVersion >= .v5_6 ? 2 : 1\n            let actualSchemeVersion = try workspace.getOrCreateWorkspace().resolvedPackagesStore.load().schemeVersion()\n            XCTAssertEqual(\n                actualSchemeVersion,\n                expectedSchemeVersion,\n                \"Actual scheme version (\\(actualSchemeVersion)) is not as expected (\\(expectedSchemeVersion)). Pair 0 (\\(pair.0)) pair 1 (\\(pair.1))\"\n            )\n        }\n    }\n\n    func testResolvedFileStableCanonicalLocation() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: []),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://localhost/org/foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"],\n                    revisionProvider: { version in version } // stable revisions\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"https://localhost/org/bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"],\n                    revisionProvider: { version in version } // stable revisions\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://localhost/ORG/FOO\", // diff: case\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"],\n                    revisionProvider: { version in version } // stable revisions\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://localhost/org/foo.git\", // diff: .git extension\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"],\n                    revisionProvider: { version in version } // stable revisions\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"https://localhost/org/bar.git\", // diff: .git extension\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"],\n                    revisionProvider: { version in version } // stable revisions\n                ),\n            ]\n        )\n\n        // case 1: initial loading\n\n        var deps: [MockDependency] = [\n            .sourceControl(url: \"https://localhost/org/foo\", requirement: .exact(\"1.0.0\")),\n            .sourceControl(url: \"https://localhost/org/bar\", requirement: .exact(\"1.0.0\")),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://localhost/org/foo\"\n            )\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar\"\n            )\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://localhost/org/foo\"\n            )\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar\"\n            )\n        }\n\n        // case 2: set state with slightly different URLs that are canonically the same\n\n        deps = [\n            .sourceControl(url: \"https://localhost/ORG/FOO\", requirement: .exact(\"1.0.0\")),\n            .sourceControl(url: \"https://localhost/org/bar.git\", requirement: .exact(\"1.0.0\")),\n        ]\n\n        // reset state, excluding the resolved file\n        try await workspace.closeWorkspace(resetResolvedFile: false)\n        XCTAssertTrue(fs.exists(sandbox.appending(\"Package.resolved\")))\n        // run update\n        try await workspace.checkUpdate(roots: [\"Root\"], deps: deps) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            // URLs should reflect the actual dependencies\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://localhost/ORG/FOO\"\n            )\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar.git\"\n            )\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            // URLs should be stable since URLs are canonically the same and we kept the resolved file between the two\n            // iterations\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://localhost/org/foo\"\n            )\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar\"\n            )\n        }\n\n        // case 2: set state with slightly different URLs that are canonically the same but request different versions\n\n        deps = [\n            .sourceControl(url: \"https://localhost/ORG/FOO\", requirement: .exact(\"1.1.0\")),\n            .sourceControl(url: \"https://localhost/org/bar.git\", requirement: .exact(\"1.1.0\")),\n        ]\n        // reset state, excluding the resolved file\n        try await workspace.closeWorkspace(resetResolvedFile: false)\n        XCTAssertTrue(fs.exists(sandbox.appending(\"Package.resolved\")))\n        // run update\n        try await workspace.checkUpdate(roots: [\"Root\"], deps: deps) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.1.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.1.0\")))\n            // URLs should reflect the actual dependencies\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://localhost/ORG/FOO\"\n            )\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar.git\"\n            )\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.1.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.1.0\")))\n            // URLs should reflect the actual dependencies since the new version forces rewrite of the resolved file\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://localhost/ORG/FOO\"\n            )\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar.git\"\n            )\n        }\n\n        // case 3: set state with slightly different URLs that are canonically the same but remove resolved file\n\n        deps = [\n            .sourceControl(url: \"https://localhost/org/foo.git\", requirement: .exact(\"1.0.0\")),\n            .sourceControl(url: \"https://localhost/org/bar.git\", requirement: .exact(\"1.0.0\")),\n        ]\n        // reset state, including the resolved file\n        await workspace.checkReset { XCTAssertNoDiagnostics($0) }\n        try fs.removeFileTree(sandbox.appending(\"Package.resolved\"))\n        XCTAssertFalse(fs.exists(sandbox.appending(\"Package.resolved\")))\n        // run update\n        try await workspace.checkUpdate(roots: [\"Root\"], deps: deps) { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            // URLs should reflect the actual dependencies\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://localhost/org/foo.git\"\n            )\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar.git\"\n            )\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            // URLs should reflect the actual dependencies since we deleted the resolved file\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://localhost/org/foo.git\"\n            )\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar.git\"\n            )\n        }\n    }\n\n    func testPreferResolvedFileWhenExists() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"Root\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"foo\"),\n                                .product(name: \"Bar\", package: \"bar\"),\n                            ]\n                        ),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://localhost/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"https://localhost/org/bar\", requirement: .upToNextMinor(from: \"1.1.0\")),\n                    ],\n                    toolsVersion: .v5_10\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://localhost/org/foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.0.1\", \"1.1.0\", \"1.1.1\", \"1.2.0\", \"1.2.1\", \"1.3.0\", \"1.3.1\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"https://localhost/org/bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.0.1\", \"1.1.0\", \"1.1.1\", \"1.2.0\", \"1.2.1\", \"1.3.0\", \"1.3.1\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    url: \"https://localhost/org/baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.0.1\", \"1.1.0\", \"1.1.1\", \"1.2.0\", \"1.2.1\", \"1.3.0\", \"1.3.1\"]\n                ),\n            ]\n        )\n\n        // initial resolution without resolved file\n\n        do {\n            try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"Bar\", \"Foo\", \"Root\")\n                }\n                // no errors\n                XCTAssertNoDiagnostics(diagnostics)\n                // check resolution mode\n                testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                    result.checkUnordered(\n                        diagnostic: \"resolving and updating '\\(Workspace.DefaultLocations.resolvedFileName)'\",\n                        severity: .debug\n                    )\n                }\n            }\n\n            workspace.checkResolved { result in\n                result.check(dependency: \"foo\", at: .checkout(.version(\"1.3.1\")))\n                result.check(dependency: \"bar\", at: .checkout(.version(\"1.1.1\")))\n            }\n\n            let resolvedPackagesStore = try workspace.getOrCreateWorkspace().resolvedPackagesStore.load()\n            checkPinnedVersion(pin: resolvedPackagesStore.resolvedPackages[\"foo\"]!, version: \"1.3.1\")\n            checkPinnedVersion(pin: resolvedPackagesStore.resolvedPackages[\"bar\"]!, version: \"1.1.1\")\n        }\n\n        do {\n            // reset but keep resolved file\n            try await workspace.closeWorkspace(resetResolvedFile: false)\n            // run resolution again, now it should rely on the resolved file\n            try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"Bar\", \"Foo\", \"Root\")\n                }\n                // no error\n                XCTAssertNoDiagnostics(diagnostics)\n                // check resolution mode\n                testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                    result.checkUnordered(\n                        diagnostic: \"'\\(Workspace.DefaultLocations.resolvedFileName)' origin hash matches manifest dependencies, attempting resolution based on this file\",\n                        severity: .debug\n                    )\n                }\n            }\n        }\n\n        do {\n            // reset but keep resolved file\n            try await workspace.closeWorkspace(resetResolvedFile: false)\n            // change the manifest\n            let rootManifestPath = try workspace.pathToRoot(withName: \"Root\").appending(Manifest.filename)\n            let manifestContent: String = try fs.readFileContents(rootManifestPath)\n            try fs.writeFileContents(rootManifestPath, string: manifestContent.appending(\"\\n\"))\n\n            // run resolution again, but change requirements\n            try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"Bar\", \"Foo\", \"Root\")\n                }\n                // no error\n                XCTAssertNoDiagnostics(diagnostics)\n                // check resolution mode\n                testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                    result.checkUnordered(\n                        diagnostic: \"'\\(Workspace.DefaultLocations.resolvedFileName)' origin hash does do not match manifest dependencies. resolving and updating accordingly\",\n                        severity: .debug\n                    )\n                    result.checkUnordered(\n                        diagnostic: \"resolving and updating '\\(Workspace.DefaultLocations.resolvedFileName)'\",\n                        severity: .debug\n                    )\n                }\n            }\n\n            // reset but keep resolved file\n            try await workspace.closeWorkspace(resetResolvedFile: false)\n            // restore original manifest\n            try fs.writeFileContents(rootManifestPath, string: manifestContent)\n            // run resolution again, now it should rely on the resolved file\n            try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"Bar\", \"Foo\", \"Root\")\n                }\n                // no error\n                XCTAssertNoDiagnostics(diagnostics)\n                // check resolution mode\n                testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                    result.checkUnordered(\n                        diagnostic: \"'\\(Workspace.DefaultLocations.resolvedFileName)' origin hash matches manifest dependencies, attempting resolution based on this file\",\n                        severity: .debug\n                    )\n                }\n            }\n        }\n\n        do {\n            // reset but keep resolved file\n            try await workspace.closeWorkspace(resetResolvedFile: false)\n            // change the dependency requirements\n            let changedDeps: [PackageDependency] = [\n                .remoteSourceControl(url: \"https://localhost/org/baz\", requirement: .upToNextMinor(from: \"1.0.0\")),\n            ]\n            // run resolution again, but change requirements\n            try await workspace.checkPackageGraph(roots: [\"Root\"], dependencies: changedDeps) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"Bar\", \"Baz\", \"Foo\", \"Root\")\n                }\n                // no error\n                XCTAssertNoDiagnostics(diagnostics)\n                // check resolution mode\n                testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                    result.checkUnordered(\n                        diagnostic: \"'\\(Workspace.DefaultLocations.resolvedFileName)' origin hash does do not match manifest dependencies. resolving and updating accordingly\",\n                        severity: .debug\n                    )\n                    result.checkUnordered(\n                        diagnostic: \"resolving and updating '\\(Workspace.DefaultLocations.resolvedFileName)'\",\n                        severity: .debug\n                    )\n                }\n            }\n\n            // reset but keep resolved file\n            try await workspace.closeWorkspace(resetResolvedFile: false)\n            // run resolution again, but change requirements back to original\n            try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"Bar\", \"Foo\", \"Root\")\n                }\n                // no error\n                XCTAssertNoDiagnostics(diagnostics)\n                // check resolution mode\n                testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                    result.checkUnordered(\n                        diagnostic: \"'\\(Workspace.DefaultLocations.resolvedFileName)' origin hash does do not match manifest dependencies. resolving and updating accordingly\",\n                        severity: .debug\n                    )\n                    result.checkUnordered(\n                        diagnostic: \"resolving and updating '\\(Workspace.DefaultLocations.resolvedFileName)'\",\n                        severity: .debug\n                    )\n                }\n            }\n\n            // reset but keep resolved file\n            try await workspace.closeWorkspace(resetResolvedFile: false)\n            // run resolution again, now it should rely on the resolved file\n            try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"Bar\", \"Foo\", \"Root\")\n                }\n                // no error\n                XCTAssertNoDiagnostics(diagnostics)\n                // check resolution mode\n                testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                    result.checkUnordered(\n                        diagnostic: \"'\\(Workspace.DefaultLocations.resolvedFileName)' origin hash matches manifest dependencies, attempting resolution based on this file\",\n                        severity: .debug\n                    )\n                }\n            }\n        }\n\n        do {\n            // reset including removing resolved file\n            try await workspace.closeWorkspace(resetResolvedFile: true)\n            // run resolution again\n            try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"Bar\", \"Foo\", \"Root\")\n                }\n                // no error\n                XCTAssertNoDiagnostics(diagnostics)\n                // check resolution mode\n                testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                    result.checkUnordered(\n                        diagnostic: \"resolving and updating '\\(Workspace.DefaultLocations.resolvedFileName)'\",\n                        severity: .debug\n                    )\n                }\n            }\n        }\n    }\n\n    // util\n    func checkPinnedVersion(pin: ResolvedPackagesStore.ResolvedPackage, version: Version) {\n        switch pin.state {\n        case .version(let pinnedVersion, _):\n            XCTAssertEqual(pinnedVersion, version)\n        default:\n            XCTFail(\"non-version pin \\(pin.state)\")\n        }\n    }\n\n    func testPackageSimpleMirrorPath() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(\n            mirror: sandbox.appending(components: \"pkgs\", \"BarMirror\").pathString,\n            for: sandbox.appending(components: \"pkgs\", \"Bar\").pathString\n        )\n        try mirrors.set(\n            mirror: sandbox.appending(components: \"pkgs\", \"BazMirror\").pathString,\n            for: sandbox.appending(components: \"pkgs\", \"Baz\").pathString\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"Dep\", package: \"dep\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Dep\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Dep\",\n                    targets: [\n                        MockTarget(name: \"Dep\", dependencies: [\n                            .product(name: \"Bar\", package: \"bar\"),\n                            .product(name: \"Baz\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Dep\", modules: [\"Dep\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.4.0\"]\n                ),\n                MockPackage(\n                    name: \"BarMirror\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"BazMirror\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.6.0\"]\n                ),\n            ],\n            mirrors: mirrors\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"BarMirror\", \"BazMirror\", \"Foo\", \"Dep\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\", \"Dep\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"dep\", at: .checkout(.version(\"1.4.0\")))\n            result.check(dependency: \"barmirror\", at: .checkout(.version(\"1.5.0\")))\n            result.check(dependency: \"bazmirror\", at: .checkout(.version(\"1.6.0\")))\n            result.check(notPresent: \"bar\")\n            result.check(notPresent: \"baz\")\n        }\n    }\n\n    func testPackageMirrorPath() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(\n            mirror: sandbox.appending(components: \"pkgs\", \"BarMirror\").pathString,\n            for: sandbox.appending(components: \"pkgs\", \"Bar\").pathString\n        )\n        try mirrors.set(\n            mirror: sandbox.appending(components: \"pkgs\", \"BarMirror\").pathString,\n            for: sandbox.appending(components: \"pkgs\", \"Baz\").pathString\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"Dep\", package: \"dep\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Dep\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Dep\",\n                    targets: [\n                        MockTarget(name: \"Dep\", dependencies: [\n                            .product(name: \"Bar\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Dep\", modules: [\"Dep\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.4.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.6.0\"]\n                ),\n                MockPackage(\n                    name: \"BarMirror\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ],\n            mirrors: mirrors\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\"), products: .specific([\"Baz\"])),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"BarMirror\", \"Foo\", \"Dep\")\n                result.check(modules: \"Bar\", \"Foo\", \"Dep\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"dep\", at: .checkout(.version(\"1.4.0\")))\n            result.check(dependency: \"barmirror\", at: .checkout(.version(\"1.5.0\")))\n            result.check(notPresent: \"baz\")\n            result.check(notPresent: \"bar\")\n        }\n    }\n\n    func testPackageSimpleMirrorURL() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"https://scm.com/org/bar-mirror\", for: \"https://scm.com/org/bar\")\n        try mirrors.set(mirror: \"https://scm.com/org/baz-mirror\", for: \"https://scm.com/org/baz\")\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"Dep\", package: \"dep\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/org/dep\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Dep\",\n                    url: \"https://scm.com/org/dep\",\n                    targets: [\n                        MockTarget(name: \"Dep\", dependencies: [\n                            .product(name: \"Bar\", package: \"bar\"),\n                            .product(name: \"Baz\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Dep\", modules: [\"Dep\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"https://scm.com/org/baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.4.0\"]\n                ),\n                MockPackage(\n                    name: \"BarMirror\",\n                    url: \"https://scm.com/org/bar-mirror\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"BazMirror\",\n                    url: \"https://scm.com/org/baz-mirror\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.6.0\"]\n                ),\n            ],\n            mirrors: mirrors\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"bar-mirror\", \"baz-mirror\", \"foo\", \"dep\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\", \"Dep\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"dep\", at: .checkout(.version(\"1.4.0\")))\n            result.check(dependency: \"bar-mirror\", at: .checkout(.version(\"1.5.0\")))\n            result.check(dependency: \"baz-mirror\", at: .checkout(.version(\"1.6.0\")))\n            result.check(notPresent: \"bar\")\n            result.check(notPresent: \"baz\")\n        }\n    }\n\n    func testPackageMirrorURL() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"https://scm.com/org/bar-mirror\", for: \"https://scm.com/org/bar\")\n        try mirrors.set(mirror: \"https://scm.com/org/bar-mirror\", for: \"https://scm.com/org/baz\")\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"Dep\", package: \"dep\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/org/dep\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Dep\",\n                    url: \"https://scm.com/org/dep\",\n                    targets: [\n                        MockTarget(name: \"Dep\", dependencies: [\n                            .product(name: \"Bar\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Dep\", modules: [\"Dep\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.4.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"https://scm.com/org/bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    url: \"https://scm.com/org/baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.6.0\"]\n                ),\n                MockPackage(\n                    name: \"BarMirror\",\n                    url: \"https://scm.com/org/bar-mirror\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n            ],\n            mirrors: mirrors\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(\n                url: \"https://scm.com/org/baz\",\n                requirement: .upToNextMajor(from: \"1.0.0\"),\n                products: .specific([\"Baz\"])\n            ),\n        ]\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"bar-mirror\", \"foo\", \"dep\")\n                result.check(modules: \"Bar\", \"Foo\", \"Dep\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"dep\", at: .checkout(.version(\"1.4.0\")))\n            result.check(dependency: \"bar-mirror\", at: .checkout(.version(\"1.5.0\")))\n            result.check(notPresent: \"bar\")\n            result.check(notPresent: \"baz\")\n        }\n    }\n\n    func testPackageMirrorURLToRegistry() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"org.bar-mirror\", for: \"https://scm.com/org/bar\")\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"Bar\", package: \"bar\"),\n                            .product(name: \"Baz\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"https://scm.com/org/baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"BarMirror\",\n                    identity: \"org.bar-mirror\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    url: \"https://scm.com/org/baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.6.0\"]\n                ),\n            ],\n            mirrors: mirrors\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"org.bar-mirror\", \"baz\", \"foo\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"org.bar-mirror\", at: .registryDownload(\"1.5.0\"))\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.6.0\")))\n            result.check(notPresent: \"bar\")\n        }\n    }\n\n    func testPackageMirrorRegistryToURL() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"https://scm.com/org/bar-mirror\", for: \"org.bar\")\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"Bar\", package: \"org.bar\"),\n                            .product(name: \"Baz\", package: \"org.baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"BarMirror\",\n                    url: \"https://scm.com/org/bar-mirror\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    identity: \"org.baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.6.0\"]\n                ),\n            ],\n            mirrors: mirrors\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"bar-mirror\", \"org.baz\", \"foo\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\")\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"bar-mirror\", at: .checkout(.version(\"1.5.0\")))\n            result.check(dependency: \"org.baz\", at: .registryDownload(\"1.6.0\"))\n            result.check(notPresent: \"org.bar\")\n        }\n    }\n\n    // In this test, we get into a state where an entry in the resolved\n    // file for a transitive dependency whose URL is later changed to\n    // something else, while keeping the same package identity.\n    func testTransitiveDependencySwitchWithSameIdentity() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // Use the same revision (hash) for \"foo\" to indicate they are the same\n        // package despite having different URLs.\n        let fooRevision = String((UUID().uuidString + UUID().uuidString).prefix(40))\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"Root\",\n                            dependencies: [\n                                .product(name: \"Bar\", package: \"bar\"),\n                            ]\n                        ),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"https://scm.com/org/bar\",\n                    targets: [\n                        MockTarget(\n                            name: \"Bar\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"foo\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"https://scm.com/org/bar\",\n                    targets: [\n                        MockTarget(\n                            name: \"Bar\",\n                            dependencies: [\n                                .product(name: \"OtherFoo\", package: \"foo\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://scm.com/other/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.1.0\"],\n                    toolsVersion: .v5\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://scm.com/org/foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    revisionProvider: { _ in fooRevision }\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"https://scm.com/other/foo\",\n                    targets: [\n                        MockTarget(name: \"OtherFoo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"OtherFoo\", modules: [\"OtherFoo\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    revisionProvider: { _ in fooRevision }\n                ),\n            ]\n        )\n\n        var deps: [MockDependency] = [\n            .sourceControl(url: \"https://scm.com/org/bar\", requirement: .exact(\"1.0.0\")),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Bar\", \"Foo\", \"Root\")\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://scm.com/org/foo\"\n            )\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://scm.com/org/foo\"\n            )\n        }\n\n        // reset state\n        await workspace.checkReset { XCTAssertNoDiagnostics($0) }\n\n        deps = [\n            .sourceControl(url: \"https://scm.com/org/bar\", requirement: .exact(\"1.1.0\")),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"Bar\", \"Foo\", \"Root\")\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.1.0\")))\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://scm.com/other/foo\"\n            )\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.1.0\")))\n            XCTAssertEqual(\n                result.store.resolvedPackages[.plain(\"foo\")]?.packageRef.locationString,\n                \"https://scm.com/other/foo\"\n            )\n        }\n    }\n\n    func testForceResolveToResolvedVersions() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\", \"Bar\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.2.0\", \"1.3.2\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"develop\"]\n                ),\n            ]\n        )\n\n        // Load the initial graph.\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./Bar\", requirement: .revision(\"develop\"), products: .specific([\"Bar\"])),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Root\"], deps: deps) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.3.2\")))\n            result.check(dependency: \"bar\", at: .checkout(.branch(\"develop\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.3.2\")))\n            result.check(dependency: \"bar\", at: .checkout(.branch(\"develop\")))\n        }\n\n        // Change pin of foo to something else.\n        do {\n            let ws = try workspace.getOrCreateWorkspace()\n            let resolvedPackagesStore = try ws.resolvedPackagesStore.load()\n            let fooPin = try XCTUnwrap(\n                resolvedPackagesStore.resolvedPackages.values\n                    .first(where: { $0.packageRef.identity.description == \"foo\" })\n            )\n\n            let fooRepo = try workspace.repositoryProvider\n                .specifierMap[RepositorySpecifier(path: AbsolutePath(\n                    validating: fooPin.packageRef\n                        .locationString\n                ))]!\n            let revision = try fooRepo.resolveRevision(tag: \"1.0.0\")\n            let newState = ResolvedPackagesStore.ResolutionState.version(\"1.0.0\", revision: revision.identifier)\n\n            resolvedPackagesStore.track(packageRef: fooPin.packageRef, state: newState)\n            try resolvedPackagesStore.saveState(toolsVersion: ToolsVersion.current, originHash: .none)\n        }\n\n        // Check force resolve. This should produce an error because the resolved file is out-of-date.\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"], forceResolvedVersions: true) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: \"an out-of-date resolved file was detected at \\(sandbox.appending(components: \"Package.resolved\")), which is not allowed when automatic dependency resolution is disabled; please make sure to update the file to reflect the changes in dependencies. Running resolver because requirements have changed.\",\n                    severity: .error\n                )\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.branch(\"develop\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.branch(\"develop\")))\n        }\n\n        // A normal resolution.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // This force resolution should succeed.\n        try await workspace.checkPackageGraph(roots: [\"Root\"], forceResolvedVersions: true) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n        workspace.checkResolved { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testForceResolveToResolvedVersionsDuplicateLocalDependency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\", \"Bar\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .fileSystem(path: \"./Bar\"),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.2.0\", \"1.3.2\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\", \"Bar\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        try await workspace.checkPackageGraph(roots: [\"Root\", \"Bar\"], forceResolvedVersions: true) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testForceResolveWithNoResolvedFile() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\", \"Bar\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.2.0\", \"1.3.2\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", \"develop\"]\n                ),\n            ]\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"], forceResolvedVersions: true) { diagnostics in\n            // rdar://82544922 (`WorkspaceResolveReason` is non-deterministic)\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .prefix(\n                        \"a resolved file is required when automatic dependency resolution is disabled and should be placed at \\(Workspace.DefaultLocations.resolvedVersionsFile(forRootPackage: sandbox)). Running resolver because the following dependencies were added:\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testForceResolveToResolvedVersionsLocalPackage() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .fileSystem(path: \"./Foo\"),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [nil]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"], forceResolvedVersions: true) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .local)\n        }\n    }\n\n    func testForceResolveToResolvedVersionsLocalPackageInAdditionalDependencies() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\"),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [nil]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(\n            roots: [\"Root\"],\n            dependencies: [.fileSystem(path: workspace.packagesDir.appending(component: \"Foo\"))],\n            forceResolvedVersions: true\n        ) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .local)\n        }\n    }\n\n    // This verifies that the simplest possible loading APIs are available for package clients.\n    func testSimpleAPI() async throws {\n        try await testWithTemporaryDirectory { path in\n            // Create a temporary package as a test case.\n            let packagePath = path.appending(\"MyPkg\")\n            let initPackage = try InitPackage(\n                name: packagePath.basename,\n                packageType: .executable,\n                destinationPath: packagePath,\n                fileSystem: localFileSystem\n            )\n            try initPackage.writePackageStructure()\n\n            // Load the workspace.\n            let observability = ObservabilitySystem.makeForTesting()\n            let workspace = try Workspace(\n                forRootPackage: packagePath,\n                customHostToolchain: UserToolchain.default\n            )\n\n            // From here the API should be simple and straightforward:\n            let manifest = try await workspace.loadRootManifest(\n                at: packagePath,\n                observabilityScope: observability.topScope\n            )\n            XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description)\n            XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description)\n\n            let package = try await workspace.loadRootPackage(\n                at: packagePath,\n                observabilityScope: observability.topScope\n            )\n            XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description)\n            XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description)\n\n            let graph = try await workspace.loadPackageGraph(\n                rootPath: packagePath,\n                observabilityScope: observability.topScope\n            )\n            XCTAssertFalse(observability.hasWarningDiagnostics, observability.diagnostics.description)\n            XCTAssertFalse(observability.hasErrorDiagnostics, observability.diagnostics.description)\n\n            XCTAssertEqual(manifest.displayName, \"MyPkg\")\n            XCTAssertEqual(package.identity, .plain(manifest.displayName))\n            XCTAssert(graph.reachableProducts.contains(where: { $0.name == \"MyPkg\" }))\n\n            let reloadedPackage = try await workspace.loadPackage(\n                with: package.identity,\n                packageGraph: graph,\n                observabilityScope: observability.topScope\n            )\n\n            XCTAssertEqual(package.identity, reloadedPackage.identity)\n            XCTAssertEqual(package.manifest.displayName, reloadedPackage.manifest.displayName)\n            XCTAssertEqual(package.products.map(\\.name), reloadedPackage.products.map(\\.name))\n        }\n    }\n\n    func testRevisionDepOnLocal() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .branch(\"develop\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Local\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .fileSystem(path: \"./Local\"),\n                    ],\n                    versions: [\"develop\"]\n                ),\n                MockPackage(\n                    name: \"Local\",\n                    targets: [\n                        MockTarget(name: \"Local\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Local\", modules: [\"Local\"]),\n                    ],\n                    versions: [nil]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .equal(\n                        \"package 'foo' is required using a revision-based requirement and it depends on local package 'local', which is not supported\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testRootPackagesOverrideBasenameMismatch() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Baz\",\n                    path: \"Overridden/bazzz-default\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    path: \"bazzz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(path: \"./bazzz\", requirement: .exact(\"1.0.0\"), products: .specific([\"Baz\"])),\n        ]\n\n        try await workspace.checkPackageGraphFailure(roots: [\"Overridden/bazzz-default\"], deps: deps) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .equal(\n                        \"unable to override package 'Baz' because its identity 'bazzz' doesn't match override's identity (directory name) 'bazzz-default'\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testManagedDependenciesNotCaseSensitive() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"Bar\", package: \"bar\"),\n                            .product(name: \"Baz\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://localhost/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"https://localhost/org/baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"https://localhost/org/bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\", dependencies: [\n                            .product(name: \"Baz\", package: \"Baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://localhost/org/Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    url: \"https://localhost/org/baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    url: \"https://localhost/org/Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Foo\"]) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Bar\", \"Baz\", \"Foo\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Bar\", \"Baz\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n            }\n            testDiagnostics(diagnostics, minSeverity: .info) { result in\n                result.checkUnordered(\n                    diagnostic: \"dependency on 'baz' is represented by similar locations ('https://localhost/org/baz' and 'https://localhost/org/Baz') which are treated as the same canonical location 'localhost/org/baz'.\",\n                    severity: .info\n                )\n            }\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"bar\")]?.packageRef.locationString,\n                \"https://localhost/org/bar\"\n            )\n            // root casing should win, so testing for lower case\n            XCTAssertEqual(\n                result.managedDependencies[.plain(\"baz\")]?.packageRef.locationString,\n                \"https://localhost/org/baz\"\n            )\n        }\n    }\n\n    func testUnsafeFlags() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\", settings: [.init(tool: .swift, kind: .unsafeFlags([\"-F\", \"/tmp\"]))]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", nil],\n                ),\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\", \"Baz\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .fileSystem(path: \"./Bar\"),\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\", settings: [.init(tool: .swift, kind: .unsafeFlags([\"-F\", \"/tmp\"]))]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"1.0.0\", nil],\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(\n                            name: \"Baz\",\n                            dependencies: [\"Bar\"],\n                            settings: [.init(tool: .swift, kind: .unsafeFlags([\"-F\", \"/tmp\"]))]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.5.0\"],\n                    toolsVersion: .minimumRequired\n                ),\n            ]\n        )\n\n        // We should only see errors about use of unsafe flag in the version-based dependency.\n        try await workspace.checkPackageGraph(roots: [\"Foo\", \"Bar\"]) { _, diagnostics in\n            // We have disabled the check so there shouldn't be any errors.\n            testDiagnostics(diagnostics) { result in\n                let diagnostic1 = result.checkUnordered(\n                    diagnostic: .equal(\"the target 'Baz' in product 'Baz' contains unsafe build flags\"),\n                    severity: .error\n                )\n                XCTAssertEqual(diagnostic1?.metadata?.packageIdentity, .plain(\"foo\"))\n                XCTAssertEqual(diagnostic1?.metadata?.moduleName, \"Foo\")\n\n                // since Bar is using the current tools version and we've disabled the check since 6.2,\n                // the result should now be empty.\n                result.checkIsEmpty()\n            }\n        }\n    }\n\n    func testUnsafeFlagsInFoundation() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Test\",\n                    targets: [\n                        MockTarget(\n                            name: \"Test\",\n                            dependencies: [\n                                .product(\n                                    name: \"Foundation\",\n                                    package: \"swift-corelibs-foundation\"\n                                ),\n                            ]\n                        ),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"swift-corelibs-foundation\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"swift-corelibs-foundation\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foundation\",\n                            settings: [.init(tool: .swift, kind: .unsafeFlags([\"-F\", \"/tmp\"]))]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foundation\", modules: [\"Foundation\"]),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Test\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testEditDependencyHadOverridableConstraints() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\", \"Baz\"]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .branch(\"main\")),\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .branch(\"main\")),\n                    ],\n                    versions: [\"main\", nil]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"main\", \"1.0.0\", nil]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\", dependencies: [\"Bar\"]),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", nil]\n                ),\n            ]\n        )\n\n        // Load the graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.branch(\"main\")))\n            result.check(dependency: \"bar\", at: .checkout(.branch(\"main\")))\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n        }\n\n        // Edit foo.\n        let fooPath = try workspace.getOrCreateWorkspace().location.editsDirectory.appending(\"Foo\")\n        await workspace.checkEdit(packageIdentity: \"Foo\") { diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .edited(nil))\n        }\n        XCTAssertTrue(fs.exists(fooPath))\n\n        // Add entry for the edited package.\n        do {\n            let fooKey = MockManifestLoader.Key(url: sandbox.appending(components: \"pkgs\", \"Foo\").pathString)\n            let editedFooKey = MockManifestLoader.Key(url: sandbox.appending(components: \"edits\", \"Foo\").pathString)\n            let manifest = workspace.manifestLoader.manifests[fooKey]!\n            workspace.manifestLoader.manifests[editedFooKey] = manifest\n        }\n        XCTAssertMatch(workspace.delegate.events, [.equal(\"will resolve dependencies\")])\n        workspace.delegate.clear()\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .edited(nil))\n            result.check(dependency: \"bar\", at: .checkout(.branch(\"main\")))\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n        }\n        XCTAssertNoMatch(workspace.delegate.events, [.equal(\"will resolve dependencies\")])\n    }\n\n    func testTargetBasedDependency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let barProducts: [MockProduct]\n        #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n        barProducts = [\n            MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n            MockProduct(name: \"BarUnused\", modules: [\"BarUnused\"]),\n        ]\n        #else\n        // Whether a product is being used does not affect dependency resolution in this case, so we omit the unused\n        // product.\n        barProducts = [MockProduct(name: \"Bar\", modules: [\"Bar\"])]\n        #endif\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Root\", dependencies: [\"Foo\", \"Bar\"]),\n                        MockTarget(name: \"RootTests\", dependencies: [\"TestHelper1\"], type: .test),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./Foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./TestHelper1\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_2\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo1\", dependencies: [\"Foo2\"]),\n                        MockTarget(name: \"Foo2\", dependencies: [\"Baz\"]),\n                        MockTarget(name: \"FooTests\", dependencies: [\"TestHelper2\"], type: .test),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo1\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./TestHelper2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"],\n                    toolsVersion: .v5_2\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                        MockTarget(name: \"BarUnused\", dependencies: [\"Biz\"]),\n                        MockTarget(name: \"BarTests\", dependencies: [\"TestHelper2\"], type: .test),\n                    ],\n                    products: barProducts,\n                    dependencies: [\n                        .sourceControl(path: \"./TestHelper2\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"./Biz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"],\n                    toolsVersion: .v5_2\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    toolsVersion: .v5_2\n                ),\n                MockPackage(\n                    name: \"TestHelper1\",\n                    targets: [\n                        MockTarget(name: \"TestHelper1\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"TestHelper1\", modules: [\"TestHelper1\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    toolsVersion: .v5_2\n                ),\n            ],\n            toolsVersion: .v5_2\n        )\n\n        // Load the graph.\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"baz\", at: .checkout(.version(\"1.0.0\")))\n            result.check(dependency: \"testhelper1\", at: .checkout(.version(\"1.0.0\")))\n            result.check(notPresent: \"biz\")\n            result.check(notPresent: \"testhelper2\")\n        }\n    }\n\n    func testLocalArchivedArtifactExtractionHappyPath() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // create dummy xcframework and artifactbundle directories from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"A1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                case \"A2.zip\":\n                    try createDummyArtifactBundle(fileSystem: fs, path: destinationPath, name: \"A2\")\n                case \"B.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"B\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"A1\", package: \"A\"),\n                            .product(name: \"A2\", package: \"A\"),\n                            .product(name: \"B\", package: \"B\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                        .sourceControl(path: \"./B\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            path: \"XCFrameworks/A1.zip\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            path: \"ArtifactBundles/A2.zip\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A1\", modules: [\"A1\"]),\n                        MockProduct(name: \"A2\", modules: [\"A2\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"B\",\n                    targets: [\n                        MockTarget(\n                            name: \"B\",\n                            type: .binary,\n                            path: \"XCFrameworks/B.zip\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"B\", modules: [\"B\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            binaryArtifactsManager: .init(archiver: archiver)\n        )\n\n        // Create dummy xcframework/artifactbundle zip files\n        let aPath = workspace.packagesDir.appending(components: \"A\")\n\n        let aFrameworksPath = aPath.appending(\"XCFrameworks\")\n        let a1FrameworkArchivePath = aFrameworksPath.appending(\"A1.zip\")\n        try fs.createDirectory(aFrameworksPath, recursive: true)\n        try fs.writeFileContents(a1FrameworkArchivePath, bytes: ByteString([0xA1]))\n\n        let aArtifactBundlesPath = aPath.appending(\"ArtifactBundles\")\n        let a2ArtifactBundleArchivePath = aArtifactBundlesPath.appending(\"A2.zip\")\n        try fs.createDirectory(aArtifactBundlesPath, recursive: true)\n        try fs.writeFileContents(a2ArtifactBundleArchivePath, bytes: ByteString([0xA2]))\n\n        let bPath = workspace.packagesDir.appending(components: \"B\")\n\n        let bFrameworksPath = bPath.appending(\"XCFrameworks\")\n        let bFrameworkArchivePath = bFrameworksPath.appending(\"B.zip\")\n        try fs.createDirectory(bFrameworksPath, recursive: true)\n        try fs.writeFileContents(bFrameworkArchivePath, bytes: ByteString([0xB0]))\n\n        // Ensure that the artifacts do not exist yet\n        XCTAssertFalse(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"A\", \"A1.xcframework\"])))\n        XCTAssertFalse(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"A\", \"A2\", \"artifactbundle\"])))\n        XCTAssertFalse(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"B\", \"B\", \"xcframework\"])))\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n\n            // Ensure that the artifacts have been properly extracted\n            XCTAssertTrue(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"a\", \"A1\", \"A1.xcframework\"])))\n            XCTAssertTrue(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"a\", \"A2\", \"A2.artifactbundle\"])))\n            XCTAssertTrue(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"b\", \"B\", \"B.xcframework\"])))\n\n            // Ensure that the original archives have been untouched\n            XCTAssertTrue(fs.exists(a1FrameworkArchivePath))\n            XCTAssertTrue(fs.exists(a2ArtifactBundleArchivePath))\n            XCTAssertTrue(fs.exists(bFrameworkArchivePath))\n\n            // Ensure that the temporary folders have been properly created\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A1\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A2\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"b\", \"B\"]),\n            ])\n\n            // Ensure that the temporary directories have been removed\n            XCTAssertTrue(try! fs.getDirectoryContents(sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A1\"])).isEmpty)\n            XCTAssertTrue(try! fs.getDirectoryContents(sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A2\"])).isEmpty)\n            XCTAssertTrue(try! fs.getDirectoryContents(sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"b\", \"B\"])).isEmpty)\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A1\",\n                source: .local(checksum: \"a1\"),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A1\", \"A1.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A2\",\n                source: .local(checksum: \"a2\"),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A2\", \"A2.artifactbundle\")\n            )\n            result.check(\n                packageIdentity: .plain(\"b\"),\n                targetName: \"B\",\n                source: .local(checksum: \"b0\"),\n                path: workspace.artifactsDir.appending(components: \"b\", \"B\", \"B.xcframework\")\n            )\n        }\n    }\n\n    // There are 6 possible transition permutations of the artifact source set\n    // {local, local-archived, and remote}, namely:\n    //\n    // (remote         -> local)\n    // (local          -> remote)\n    // (local          -> local-archived)\n    // (local-archived -> local)\n    // (remote         -> local-archived)\n    // (local-archived -> remote)\n    //\n    // This test covers the last 4 permutations where the `local-archived` source is involved.\n    // It ensures that all the appropriate clean-up operations are executed, and the workspace\n    // contains the correct set of managed artifacts after the transition.\n    func testLocalArchivedArtifactSourceTransitionPermutations() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let a1FrameworkName = \"A1.xcframework\"\n        let a2FrameworkName = \"A2.xcframework\"\n        let a3FrameworkName = \"A3.xcframework\"\n        let a4FrameworkName = \"A4.xcframework\"\n        let a5FrameworkName = \"A5.xcframework\"\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a4.zip\":\n                contents = [0xA4]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            return .okay()\n        }\n\n        // create a dummy xcframework directory (with a marker subdirectory) from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                // var subdirectoryName: String?\n                switch archivePath.basename {\n                case \"A1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                case \"A2.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A2\")\n                case \"A3.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A3\")\n                    try fs.createDirectory(\n                        destinationPath.appending(components: [a3FrameworkName, \"local-archived\"]),\n                        recursive: false\n                    )\n                case \"a4.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A4\")\n                    try fs.createDirectory(\n                        destinationPath.appending(components: [a4FrameworkName, \"remote\"]),\n                        recursive: false\n                    )\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"A1\", package: \"A\"),\n                            .product(name: \"A2\", package: \"A\"),\n                            .product(name: \"A3\", package: \"A\"),\n                            .product(name: \"A4\", package: \"A\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            path: \"XCFrameworks/A1.zip\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            path: \"XCFrameworks/\\(a2FrameworkName)\"\n                        ),\n                        MockTarget(\n                            name: \"A3\",\n                            type: .binary,\n                            path: \"XCFrameworks/A3.zip\"\n                        ),\n                        MockTarget(\n                            name: \"A4\",\n                            type: .binary,\n                            url: \"https://a.com/a4.zip\",\n                            checksum: \"a4\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A1\", modules: [\"A1\"]),\n                        MockProduct(name: \"A2\", modules: [\"A2\"]),\n                        MockProduct(name: \"A3\", modules: [\"A3\"]),\n                        MockProduct(name: \"A4\", modules: [\"A4\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        // Create dummy xcframework directories and zip files\n        let aFrameworksPath = workspace.packagesDir.appending(components: \"A\", \"XCFrameworks\")\n        try fs.createDirectory(aFrameworksPath, recursive: true)\n\n        let a1FrameworkPath = aFrameworksPath.appending(component: a1FrameworkName)\n        let a1FrameworkArchivePath = aFrameworksPath.appending(\"A1.zip\")\n        try fs.createDirectory(a1FrameworkPath, recursive: true)\n        try fs.writeFileContents(a1FrameworkArchivePath, bytes: ByteString([0xA1]))\n\n        let a2FrameworkPath = aFrameworksPath.appending(component: a2FrameworkName)\n        let a2FrameworkArchivePath = aFrameworksPath.appending(\"A2.zip\")\n        try createDummyXCFramework(fileSystem: fs, path: a2FrameworkPath.parentDirectory, name: \"A2\")\n        try fs.writeFileContents(a2FrameworkArchivePath, bytes: ByteString([0xA2]))\n\n        let a3FrameworkArchivePath = aFrameworksPath.appending(\"A3.zip\")\n        try fs.writeFileContents(a3FrameworkArchivePath, bytes: ByteString([0xA3]))\n\n        let a4FrameworkArchivePath = aFrameworksPath.appending(\"A4.zip\")\n        try fs.writeFileContents(a4FrameworkArchivePath, bytes: ByteString([0xA4]))\n\n        // Pin A to 1.0.0, Checkout B to 1.0.0\n        let aPath = try workspace.pathToPackage(withName: \"A\")\n        let aRef = PackageReference.localSourceControl(identity: PackageIdentity(path: aPath), path: aPath)\n        let aRepo = workspace.repositoryProvider.specifierMap[RepositorySpecifier(path: aPath)]!\n        let aRevision = try aRepo.resolveRevision(tag: \"1.0.0\")\n        let aState = CheckoutState.version(\"1.0.0\", revision: aRevision)\n\n        // Set an initial workspace state\n        try await workspace.set(\n            resolvedPackages: [aRef: aState],\n            managedArtifacts: [\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A1\",\n                    source: .local(),\n                    path: a1FrameworkPath,\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A2\",\n                    source: .local(checksum: \"a2\"),\n                    path: workspace.artifactsDir.appending(components: \"A\", a2FrameworkName),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A3\",\n                    source: .remote(url: \"https://a.com/a3.zip\", checksum: \"a3\"),\n                    path: workspace.artifactsDir.appending(components: \"A\", a3FrameworkName),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A4\",\n                    source: .local(checksum: \"a4\"),\n                    path: workspace.artifactsDir.appending(components: \"A\", a4FrameworkName),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A5\",\n                    source: .local(checksum: \"a5\"),\n                    path: workspace.artifactsDir.appending(components: \"A\", a5FrameworkName),\n                    kind: .xcframework\n                ),\n            ]\n        )\n\n        // Create marker folders to later check that the frameworks' content is properly overwritten\n        try fs.createDirectory(\n            workspace.artifactsDir.appending(components: \"A\", \"A3\", a3FrameworkName, \"remote\"),\n            recursive: true\n        )\n        try fs.createDirectory(\n            workspace.artifactsDir.appending(components: \"A\", \"A4\", a4FrameworkName, \"local-archived\"),\n            recursive: true\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n\n            // Ensure that the original archives have been untouched\n            XCTAssertTrue(fs.exists(a1FrameworkArchivePath))\n            XCTAssertTrue(fs.exists(a2FrameworkArchivePath))\n            XCTAssertTrue(fs.exists(a3FrameworkArchivePath))\n            XCTAssertTrue(fs.exists(a4FrameworkArchivePath))\n\n            // Ensure that the new artifacts have been properly extracted\n            XCTAssertTrue(try fs.exists(AbsolutePath(validating: \"\\(sandbox)/.build/artifacts/a/A1/\\(a1FrameworkName)\")))\n            XCTAssertTrue(\n                try fs\n                    .exists(\n                        AbsolutePath(validating: \"\\(sandbox)/.build/artifacts/a/A3/\\(a3FrameworkName)/local-archived\")\n                    )\n            )\n            XCTAssertTrue(\n                try fs\n                    .exists(AbsolutePath(validating: \"\\(sandbox)/.build/artifacts/a/A4/\\(a4FrameworkName)/remote\"))\n            )\n\n            // Ensure that the old artifacts have been removed\n            XCTAssertFalse(try fs.exists(AbsolutePath(validating: \"\\(sandbox)/.build/artifacts/a/A2/\\(a2FrameworkName)\")))\n            XCTAssertFalse(\n                try fs\n                    .exists(AbsolutePath(validating: \"\\(sandbox)/.build/artifacts/a/A3/\\(a3FrameworkName)/remote\"))\n            )\n            XCTAssertFalse(\n                try fs\n                    .exists(\n                        AbsolutePath(validating: \"\\(sandbox)/.build/artifacts/a/A4/\\(a4FrameworkName)/local-archived\")\n                    )\n            )\n            XCTAssertFalse(try fs.exists(AbsolutePath(validating: \"\\(sandbox)/.build/artifacts/a/A5/\\(a5FrameworkName)\")))\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A1\",\n                source: .local(checksum: \"a1\"),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A1\", a1FrameworkName)\n            )\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A2\",\n                source: .local(),\n                path: a2FrameworkPath\n            )\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A3\",\n                source: .local(checksum: \"a3\"),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A3\", a3FrameworkName)\n            )\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A4\",\n                source: .remote(url: \"https://a.com/a4.zip\", checksum: \"a4\"),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A4\", a4FrameworkName)\n            )\n        }\n    }\n\n    func testLocalArchivedArtifactNameDoesNotMatchTargetName() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs: InMemoryFileSystem = InMemoryFileSystem()\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"archived-does-not-match-target-name.zip\":\n                    try createDummyXCFramework(\n                        fileSystem: fs,\n                        path: destinationPath,\n                        name: \"artifact-does-not-match-target-name\"\n                    )\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            path: \"XCFrameworks/archived-does-not-match-target-name.zip\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                archiver: archiver\n            )\n        )\n\n        // Create dummy zip files\n        let rootPath = try workspace.pathToRoot(withName: \"Root\")\n        let frameworksPath = rootPath.appending(\"XCFrameworks\")\n        try fs.createDirectory(frameworksPath, recursive: true)\n        try fs.writeFileContents(\n            frameworksPath.appending(\"archived-does-not-match-target-name.zip\"),\n            bytes: ByteString([0xA1])\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testLocalArchivedArtifactExtractionError() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let archiver = MockArchiver(handler: { _, _, _, completion in\n            completion(.failure(DummyError()))\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            path: \"XCFrameworks/A1.zip\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            path: \"ArtifactBundles/A2.zip\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                archiver: archiver\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"failed extracting '\\(sandbox.appending(components: \"roots\", \"Root\", \"XCFrameworks\", \"A1.zip\"))' which is required by binary target 'A1': dummy error\"\n                    ),\n                    severity: .error\n                )\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"failed extracting '\\(sandbox.appending(components: \"roots\", \"Root\", \"ArtifactBundles\", \"A2.zip\"))' which is required by binary target 'A2': dummy error\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testLocalArchiveDoesNotMatchTargetName() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // create dummy xcframework and artifactbundle directories from the request archive\n        let archiver = MockArchiver(handler: { _, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"A1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"foo\")\n                case \"A2.zip\":\n                    try createDummyArtifactBundle(fileSystem: fs, path: destinationPath, name: \"bar\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            path: \"XCFrameworks/A1.zip\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            path: \"ArtifactBundles/A2.zip\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                archiver: archiver\n            )\n        )\n\n        // Create dummy zip files\n        let rootPath = try workspace.pathToRoot(withName: \"Root\")\n        let frameworksPath = rootPath.appending(\"XCFrameworks\")\n        try fs.createDirectory(frameworksPath, recursive: true)\n        try fs.writeFileContents(frameworksPath.appending(\"A1.zip\"), bytes: ByteString([0xA1]))\n\n        let aArtifactBundlesPath = rootPath.appending(\"ArtifactBundles\")\n        try fs.createDirectory(aArtifactBundlesPath, recursive: true)\n        try fs.writeFileContents(aArtifactBundlesPath.appending(\"A2.zip\"), bytes: ByteString([0xA2]))\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A1\",\n                source: .local(checksum: \"a1\"),\n                path: workspace.artifactsDir.appending(components: \"root\", \"A1\", \"foo.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A2\",\n                source: .local(checksum: \"a2\"),\n                path: workspace.artifactsDir.appending(components: \"root\", \"A2\", \"bar.artifactbundle\")\n            )\n        }\n    }\n\n////// STAET ATDIN\n    func testLocalArchivedArtifactChecksumChange() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // create dummy xcframework directories from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"A1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                case \"A2.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A2\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            path: \"XCFrameworks/A1.zip\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            path: \"XCFrameworks/A2.zip\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                archiver: archiver\n            )\n        )\n\n        let rootPath = try workspace.pathToRoot(withName: \"Root\")\n        let rootRef = PackageReference.root(identity: PackageIdentity(path: rootPath), path: rootPath)\n\n        // Set an initial workspace state\n        try await workspace.set(\n            managedArtifacts: [\n                .init(\n                    packageRef: rootRef,\n                    targetName: \"A1\",\n                    source: .local(checksum: \"old-checksum\"),\n                    path: workspace.artifactsDir.appending(components: \"root\", \"A1\", \"A1.xcframework\"),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: rootRef,\n                    targetName: \"A2\",\n                    source: .local(checksum: \"a2\"),\n                    path: workspace.artifactsDir.appending(components: \"root\", \"A2\", \"A2.xcframework\"),\n                    kind: .xcframework\n                ),\n            ]\n        )\n\n        // Create dummy zip files\n        let frameworksPath = rootPath.appending(components: \"XCFrameworks\")\n        try fs.createDirectory(frameworksPath, recursive: true)\n\n        let a1FrameworkArchivePath = frameworksPath.appending(\"A1.zip\")\n        try fs.writeFileContents(a1FrameworkArchivePath, bytes: ByteString([0xA1]))\n\n        let a2FrameworkArchivePath = frameworksPath.appending(\"A2.zip\")\n        try fs.writeFileContents(a2FrameworkArchivePath, bytes: ByteString([0xA2]))\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, _ in\n            // Ensure that only the artifact archive with the changed checksum has been extracted\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"A1\"]),\n            ])\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A1\",\n                source: .local(checksum: \"a1\"),\n                path: workspace.artifactsDir.appending(components: \"root\", \"A1\", \"A1.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A2\",\n                source: .local(checksum: \"a2\"),\n                path: workspace.artifactsDir.appending(components: \"root\", \"A2\", \"A2.xcframework\")\n            )\n        }\n    }\n\n    func testLocalArchivedArtifactStripFirstComponent() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"flat.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"flat\")\n                case \"nested.zip\":\n                    let nestedPath = destinationPath.appending(\"root\")\n                    try fs.createDirectory(nestedPath, recursive: true)\n                    try createDummyXCFramework(fileSystem: fs, path: nestedPath, name: \"nested\")\n                case \"nested2.zip\":\n                    let nestedPath = destinationPath.appending(\"root\")\n                    try fs.createDirectory(nestedPath, recursive: true)\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"nested2\")\n                    try fs\n                        .writeFileContents(\n                            nestedPath.appending(\".DS_Store\"),\n                            bytes: []\n                        ) // add a file next to the directory\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"flat\",\n                            type: .binary,\n                            path: \"frameworks/flat.zip\"\n                        ),\n                        MockTarget(\n                            name: \"nested\",\n                            type: .binary,\n                            path: \"frameworks/nested.zip\"\n                        ),\n\n                        MockTarget(\n                            name: \"nested2\",\n                            type: .binary,\n                            path: \"frameworks/nested2.zip\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                archiver: archiver\n            )\n        )\n\n        // create the mock archives\n        let rootPath = try workspace.pathToRoot(withName: \"Root\")\n        let archivesPath = rootPath.appending(components: \"frameworks\")\n        try fs.createDirectory(archivesPath, recursive: true)\n        try fs.writeFileContents(archivesPath.appending(\"flat.zip\"), bytes: ByteString([0x1]))\n        try fs.writeFileContents(archivesPath.appending(\"nested.zip\"), bytes: ByteString([0x2]))\n        try fs.writeFileContents(archivesPath.appending(\"nested2.zip\"), bytes: ByteString([0x3]))\n\n        // ensure that the artifacts do not exist yet\n        XCTAssertFalse(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"root\", \"flat\", \"flat.xcframework\"])))\n        XCTAssertFalse(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"root\", \"nested\", \"nested.artifactbundle\"])))\n        XCTAssertFalse(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"root\", \"nested2\", \"nested2.xcframework\"])))\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"root\"])))\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"flat\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"nested\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"nested2\"]),\n            ])\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"flat\",\n                source: .local(checksum: \"01\"),\n                path: workspace.artifactsDir.appending(components: \"root\", \"flat\", \"flat.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"nested\",\n                source: .local(checksum: \"02\"),\n                path: workspace.artifactsDir.appending(components: \"root\", \"nested\", \"nested.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"nested2\",\n                source: .local(checksum: \"03\"),\n                path: workspace.artifactsDir.appending(components: \"root\", \"nested2\", \"nested2.xcframework\")\n            )\n        }\n    }\n\n    func testLocalArtifactHappyPath() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            path: \"XCFrameworks/A1.xcframework\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            path: \"ArtifactBundles/A2.artifactbundle\"\n                        ),\n                    ]\n                ),\n            ]\n        )\n\n        let rootPath = try workspace.pathToRoot(withName: \"Root\")\n\n        // make sure the directory exist in their destined location\n        try createDummyXCFramework(fileSystem: fs, path: rootPath.appending(\"XCFrameworks\"), name: \"A1\")\n        try createDummyArtifactBundle(fileSystem: fs, path: rootPath.appending(\"ArtifactBundles\"), name: \"A2\")\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A1\",\n                source: .local(checksum: .none),\n                path: rootPath.appending(components: \"XCFrameworks\", \"A1.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A2\",\n                source: .local(checksum: .none),\n                path: rootPath.appending(components: \"ArtifactBundles\", \"A2.artifactbundle\")\n            )\n        }\n    }\n\n    func testLocalArtifactDoesNotExist() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            path: \"XCFrameworks/incorrect.xcframework\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            path: \"ArtifactBundles/incorrect.artifactbundle\"\n                        ),\n                    ]\n                ),\n            ]\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"local binary target 'A1' at '\\(sandbox.appending(components: [\"roots\", \"Root\", \"XCFrameworks\", \"incorrect.xcframework\"]))' does not contain a binary artifact.\"\n                    ),\n                    severity: .error\n                )\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"local binary target 'A2' at '\\(sandbox.appending(components: [\"roots\", \"Root\", \"ArtifactBundles\", \"incorrect.artifactbundle\"]))' does not contain a binary artifact.\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testArtifactDownloadHappyPath() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a1.zip\":\n                contents = [0xA1]\n            case \"a2.zip\":\n                contents = [0xA2]\n            case \"b.zip\":\n                contents = [0xB0]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads[request.url] = destination\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"a1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                case \"a2.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A2\")\n                case \"b.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"B\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"A1\", package: \"A\"),\n                            .product(name: \"A2\", package: \"A\"),\n                            \"B\",\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                        .sourceControl(path: \"./B\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            url: \"https://a.com/a2.zip\",\n                            checksum: \"a2\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A1\", modules: [\"A1\"]),\n                        MockProduct(name: \"A2\", modules: [\"A2\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"B\",\n                    targets: [\n                        MockTarget(\n                            name: \"B\",\n                            type: .binary,\n                            url: \"https://b.com/b.zip\",\n                            checksum: \"b0\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"B\", modules: [\"B\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false // disable cache\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"a\"])))\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"b\"])))\n            XCTAssertEqual(downloads.map(\\.key.absoluteString).sorted(), [\n                \"https://a.com/a1.zip\",\n                \"https://a.com/a2.zip\",\n                \"https://b.com/b.zip\",\n            ])\n            XCTAssertEqual(workspace.checksumAlgorithm.hashes.map(\\.hexadecimalRepresentation).sorted(), [\n                ByteString([0xA1]).hexadecimalRepresentation,\n                ByteString([0xA2]).hexadecimalRepresentation,\n                ByteString([0xB0]).hexadecimalRepresentation,\n            ])\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A1\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A2\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"b\", \"B\"]),\n            ])\n            XCTAssertEqual(\n                downloads.map(\\.value).sorted(),\n                archiver.extractions.map(\\.archivePath).sorted()\n            )\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A1\",\n                source: .remote(\n                    url: \"https://a.com/a1.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A1\", \"A1.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A2\",\n                source: .remote(\n                    url: \"https://a.com/a2.zip\",\n                    checksum: \"a2\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A2\", \"A2.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"b\"),\n                targetName: \"B\",\n                source: .remote(\n                    url: \"https://b.com/b.zip\",\n                    checksum: \"b0\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"b\", \"B\", \"B.xcframework\")\n            )\n        }\n\n        XCTAssertMatch(workspace.delegate.events, [\"downloading binary artifact package: https://a.com/a1.zip\"])\n        XCTAssertMatch(workspace.delegate.events, [\"downloading binary artifact package: https://a.com/a2.zip\"])\n        XCTAssertMatch(workspace.delegate.events, [\"downloading binary artifact package: https://b.com/b.zip\"])\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"finished downloading binary artifact package: https://a.com/a1.zip\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"finished downloading binary artifact package: https://a.com/a2.zip\"]\n        )\n        XCTAssertMatch(workspace.delegate.events, [\"finished downloading binary artifact package: https://b.com/b.zip\"])\n    }\n\n    func testArtifactDownloadWithPreviousState() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a1.zip\":\n                contents = [0xA1]\n            case \"a2.zip\":\n                contents = [0xA2]\n            case \"a3.zip\":\n                contents = [0xA3]\n            case \"a7.zip\":\n                contents = [0xA7]\n            case \"b.zip\":\n                contents = [0xB0]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads[request.url] = destination\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"a1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                case \"a2.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A2\")\n                case \"a3.zip\":\n                    fs.createEmptyFiles(at: destinationPath, files: \".DS_Store\") // invalid binary artifact\n                case \"a7.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A7\")\n                case \"b.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"B\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            \"B\",\n                            .product(name: \"A1\", package: \"A\"),\n                            .product(name: \"A2\", package: \"A\"),\n                            .product(name: \"A3\", package: \"A\"),\n                            .product(name: \"A4\", package: \"A\"),\n                            .product(name: \"A7\", package: \"A\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                        .sourceControl(path: \"./B\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            url: \"https://a.com/a2.zip\",\n                            checksum: \"a2\"\n                        ),\n                        MockTarget(\n                            name: \"A3\",\n                            type: .binary,\n                            url: \"https://a.com/a3.zip\",\n                            checksum: \"a3\"\n                        ),\n                        MockTarget(\n                            name: \"A4\",\n                            type: .binary,\n                            path: \"XCFrameworks/A4.xcframework\"\n                        ),\n                        MockTarget(\n                            name: \"A7\",\n                            type: .binary,\n                            url: \"https://a.com/a7.zip\",\n                            checksum: \"a7\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A1\", modules: [\"A1\"]),\n                        MockProduct(name: \"A2\", modules: [\"A2\"]),\n                        MockProduct(name: \"A3\", modules: [\"A3\"]),\n                        MockProduct(name: \"A4\", modules: [\"A4\"]),\n                        MockProduct(name: \"A7\", modules: [\"A7\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"B\",\n                    targets: [\n                        MockTarget(\n                            name: \"B\",\n                            type: .binary,\n                            url: \"https://b.com/b.zip\",\n                            checksum: \"b0\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"B\", modules: [\"B\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        let a4FrameworkPath = workspace.packagesDir.appending(components: \"A\", \"XCFrameworks\", \"A4.xcframework\")\n        try createDummyXCFramework(fileSystem: fs, path: a4FrameworkPath.parentDirectory, name: \"A4\")\n\n        // Pin A to 1.0.0, Checkout B to 1.0.0\n        let aPath = try workspace.pathToPackage(withName: \"A\")\n        let aRef = PackageReference.localSourceControl(identity: PackageIdentity(path: aPath), path: aPath)\n        let aRepo = workspace.repositoryProvider.specifierMap[RepositorySpecifier(path: aPath)]!\n        let aRevision = try aRepo.resolveRevision(tag: \"1.0.0\")\n        let aState = CheckoutState.version(\"1.0.0\", revision: aRevision)\n\n        try await workspace.set(\n            resolvedPackages: [aRef: aState],\n            managedArtifacts: [\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A1\",\n                    source: .remote(\n                        url: \"https://a.com/a1.zip\",\n                        checksum: \"a1\"\n                    ),\n                    path: workspace.artifactsDir.appending(components: \"a\", \"A1\", \"A1.xcframework\"),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A3\",\n                    source: .remote(\n                        url: \"https://a.com/old/a3.zip\",\n                        checksum: \"a3-old-checksum\"\n                    ),\n                    path: workspace.artifactsDir.appending(components: \"a\", \"A3\", \"A3.xcframework\"),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A4\",\n                    source: .remote(\n                        url: \"https://a.com/a4.zip\",\n                        checksum: \"a4\"\n                    ),\n                    path: workspace.artifactsDir.appending(components: \"a\", \"A4\", \"A4.xcframework\"),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A5\",\n                    source: .remote(\n                        url: \"https://a.com/a5.zip\",\n                        checksum: \"a5\"\n                    ),\n                    path: workspace.artifactsDir.appending(components: \"a\", \"A5\", \"A5.xcframework\"),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A6\",\n                    source: .local(),\n                    path: workspace.artifactsDir.appending(components: \"a\", \"A6\", \"A6.xcframework\"),\n                    kind: .xcframework\n                ),\n                .init(\n                    packageRef: aRef,\n                    targetName: \"A7\",\n                    source: .local(),\n                    path: workspace.packagesDir.appending(components: \"a\", \"XCFrameworks\", \"A7.xcframework\"),\n                    kind: .xcframework\n                ),\n            ]\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: \"downloaded archive of binary target 'A3' from 'https://a.com/a3.zip' does not contain a binary artifact.\",\n                    severity: .error\n                )\n            }\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"b\"])))\n            XCTAssert(fs.exists(sandbox.appending(components: [\".build\", \"artifacts\", \"a\", \"A1\", \"A1.xcframework\"])))\n            XCTAssert(fs.exists(sandbox.appending(components: [\".build\", \"artifacts\", \"a\", \"A2\", \"A2.xcframework\"])))\n            XCTAssert(!fs.exists(sandbox.appending(components: [\".build\", \"artifacts\", \"a\", \"A3\", \"A3.xcframework\"])))\n            XCTAssert(!fs.exists(sandbox.appending(components: [\".build\", \"artifacts\", \"a\", \"A4\", \"A4.xcframework\"])))\n            XCTAssert(!fs.exists(sandbox.appending(components: [\".build\", \"artifacts\", \"a\", \"A5\", \"A5.xcframework\"])))\n            XCTAssert(fs.exists(sandbox.appending(components: [\"pkgs\", \"a\", \"XCFrameworks\", \"A7.xcframework\"])))\n            XCTAssert(!fs.exists(sandbox.appending(components: [\".build\", \"artifacts\", \"Foo\"])))\n            XCTAssertEqual(downloads.map(\\.key.absoluteString).sorted(), [\n                \"https://a.com/a2.zip\",\n                \"https://a.com/a3.zip\",\n                \"https://a.com/a7.zip\",\n                \"https://b.com/b.zip\",\n            ])\n            XCTAssertEqual(workspace.checksumAlgorithm.hashes.map(\\.hexadecimalRepresentation).sorted(), [\n                ByteString([0xA2]).hexadecimalRepresentation,\n                ByteString([0xA3]).hexadecimalRepresentation,\n                ByteString([0xA7]).hexadecimalRepresentation,\n                ByteString([0xB0]).hexadecimalRepresentation,\n            ])\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\",\"a\", \"A2\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\",\"a\", \"A3\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\",\"a\", \"A7\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\",\"b\", \"B\"]),\n            ])\n            XCTAssertEqual(\n                downloads.map(\\.value).sorted(),\n                archiver.extractions.map(\\.archivePath).sorted()\n            )\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A1\",\n                source: .remote(\n                    url: \"https://a.com/a1.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A1\", \"A1.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A2\",\n                source: .remote(\n                    url: \"https://a.com/a2.zip\",\n                    checksum: \"a2\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A2\", \"A2.xcframework\")\n            )\n            result.checkNotPresent(packageName: \"A\", targetName: \"A3\")\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A4\",\n                source: .local(),\n                path: a4FrameworkPath\n            )\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A7\",\n                source: .remote(\n                    url: \"https://a.com/a7.zip\",\n                    checksum: \"a7\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A7\", \"A7.xcframework\")\n            )\n            result.checkNotPresent(packageName: \"A\", targetName: \"A5\")\n            result.check(\n                packageIdentity: .plain(\"b\"),\n                targetName: \"B\",\n                source: .remote(\n                    url: \"https://b.com/b.zip\",\n                    checksum: \"b0\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"b\", \"B\", \"B.xcframework\")\n            )\n        }\n    }\n\n    func testArtifactDownloadTwice() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeArrayStore<(URL, AbsolutePath)>()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a1.zip\":\n                contents = [0xA1]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads.append((request.url, destination))\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                let name: String\n                switch archivePath.basename {\n                case \"a1.zip\":\n                    name = \"A1.xcframework\"\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                let path = destinationPath.appending(component: name)\n                if fs.exists(path) {\n                    throw StringError(\"\\(path) already exists\")\n                }\n                try createDummyXCFramework(fileSystem: fs, path: path.parentDirectory, name: \"A1\")\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"root\"])))\n            XCTAssertEqual(workspace.checksumAlgorithm.hashes.map(\\.hexadecimalRepresentation).sorted(), [\n                ByteString([0xA1]).hexadecimalRepresentation,\n            ])\n        }\n\n        XCTAssertEqual(downloads.map(\\.0.absoluteString).sorted(), [\n            \"https://a.com/a1.zip\",\n        ])\n        XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n            sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"A1\"]),\n        ])\n        XCTAssertEqual(\n            downloads.map(\\.1).sorted(),\n            archiver.extractions.map(\\.archivePath).sorted()\n        )\n\n        // reset\n\n        try await workspace.resetState()\n\n        // do it again\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"root\"])))\n\n            XCTAssertEqual(workspace.checksumAlgorithm.hashes.map(\\.hexadecimalRepresentation).sorted(), [\n                ByteString([0xA1]).hexadecimalRepresentation, ByteString([0xA1]).hexadecimalRepresentation,\n            ])\n        }\n\n        XCTAssertEqual(downloads.map(\\.0.absoluteString).sorted(), [\n            \"https://a.com/a1.zip\", \"https://a.com/a1.zip\",\n        ])\n        XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n            sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"A1\"]),\n            sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"A1\"]),\n        ])\n        XCTAssertEqual(\n            downloads.map(\\.1).sorted(),\n            archiver.extractions.map(\\.archivePath).sorted()\n        )\n    }\n\n    func testArtifactDownloadServerError() async throws {\n        let fs = InMemoryFileSystem()\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        try fs.createDirectory(sandbox, recursive: true)\n        let artifactUrl = \"https://a.com/a.zip\"\n\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            // mimics URLSession behavior which write the file even if sends an error message\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: \"not found\",\n                atomically: true\n            )\n\n            return .notFound()\n        }\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: artifactUrl,\n                            checksum: \"a1\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\n                        \"failed downloading 'https://a.com/a.zip' which is required by binary target 'A1': badResponseStatusCode(404)\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n\n        // make sure artifact downloaded is deleted\n        XCTAssertTrue(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"root\"])))\n        XCTAssertFalse(fs.exists(sandbox.appending(components: [\".build\", \"artifacts\", \"root\", \"a.zip\"])))\n\n        // make sure the cached artifact is also deleted\n        let artifactCacheKey = artifactUrl.spm_mangledToC99ExtendedIdentifier()\n        guard let cachePath = workspace.workspaceLocation?\n            .sharedBinaryArtifactsCacheDirectory?\n            .appending(artifactCacheKey)\n        else {\n            XCTFail(\"Required workspace location wasn't found\")\n            return\n        }\n\n        XCTAssertFalse(fs.exists(cachePath))\n    }\n\n    func testArtifactDownloaderOrArchiverError() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            switch request.url {\n            case \"https://a.com/a1.zip\":\n                return .serverError()\n            case \"https://a.com/a2.zip\":\n                try fileSystem.writeFileContents(destination, bytes: ByteString([0xA2]))\n                return .okay()\n            case \"https://a.com/a3.zip\":\n                try fileSystem.writeFileContents(destination, bytes: \"different contents = different checksum\")\n                return .okay()\n            default:\n                throw StringError(\"unexpected url\")\n            }\n        }\n\n        let archiver = MockArchiver(handler: { _, _, destinationPath, completion in\n            XCTAssertEqual(destinationPath.parentDirectory, sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"A2\"]))\n            completion(.failure(DummyError()))\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            url: \"https://a.com/a2.zip\",\n                            checksum: \"a2\"\n                        ),\n                        MockTarget(\n                            name: \"A3\",\n                            type: .binary,\n                            url: \"https://a.com/a3.zip\",\n                            checksum: \"a3\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"failed downloading 'https://a.com/a1.zip' which is required by binary target 'A1': badResponseStatusCode(500)\"\n                    ),\n                    severity: .error\n                )\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"failed extracting 'https://a.com/a2.zip' which is required by binary target 'A2': dummy error\"\n                    ),\n                    severity: .error\n                )\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"checksum of downloaded artifact of binary target 'A3' (6d75736b6365686320746e65726566666964203d2073746e65746e6f6320746e65726566666964) does not match checksum specified by the manifest (a3)\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadedArtifactNotAnArchiveError() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            switch request.url {\n            case \"https://a.com/a1.zip\":\n                try fileSystem.writeFileContents(destination, bytes: ByteString([0xA1]))\n                return .okay()\n            case \"https://a.com/a2.zip\":\n                try fileSystem.writeFileContents(destination, bytes: ByteString([0xA2]))\n                return .okay()\n            case \"https://a.com/a3.zip\":\n                try fileSystem.writeFileContents(destination, bytes: ByteString([0xA3]))\n                return .okay()\n            default:\n                throw StringError(\"unexpected url\")\n            }\n        }\n\n        let archiver = MockArchiver(\n            extractionHandler: { archiver, archivePath, destinationPath, completion in\n                do {\n                    if archivePath.basenameWithoutExt == \"a1\" {\n                        try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                        archiver.extractions\n                            .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                        completion(.success(()))\n                    } else {\n                        throw StringError(\"unexpected path\")\n                    }\n                } catch {\n                    completion(.failure(error))\n                }\n            },\n            validationHandler: { _, path, completion in\n                if path.basenameWithoutExt == \"a1\" {\n                    completion(.success(true))\n                } else if path.basenameWithoutExt == \"a2\" {\n                    completion(.success(false))\n                } else if path.basenameWithoutExt == \"a3\" {\n                    completion(.failure(DummyError()))\n                } else {\n                    XCTFail(\"unexpected path\")\n                    completion(.success(false))\n                }\n            }\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            url: \"https://a.com/a2.zip\",\n                            checksum: \"a2\"\n                        ),\n                        MockTarget(\n                            name: \"A3\",\n                            type: .binary,\n                            url: \"https://a.com/a3.zip\",\n                            checksum: \"a3\"\n                        ),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"invalid archive returned from 'https://a.com/a2.zip' which is required by binary target 'A2'\"\n                    ),\n                    severity: .error\n                )\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"failed validating archive from 'https://a.com/a3.zip' which is required by binary target 'A3': dummy error\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadedArtifactInvalid() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            switch request.url {\n            case \"https://a.com/a1.zip\":\n                try fileSystem.writeFileContents(destination, bytes: ByteString([0xA1]))\n                return .okay()\n            default:\n                throw StringError(\"unexpected url\")\n            }\n        }\n\n        let archiver = MockArchiver(\n            extractionHandler: { _, archivePath, destinationPath, completion in\n                do {\n                    if archivePath.basenameWithoutExt == \"a1\" {\n                        // create file instead of directory\n                        fs.createEmptyFiles(at: destinationPath, files: \"A1.Framework\")\n                        completion(.success(()))\n                    } else {\n                        throw StringError(\"unexpected path\")\n                    }\n                } catch {\n                    completion(.failure(error))\n                }\n            }\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.checkUnordered(\n                    diagnostic: .contains(\n                        \"downloaded archive of binary target 'A1' from 'https://a.com/a1.zip' does not contain a binary artifact.\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadedArtifactDoesNotMatchTargetName() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            switch request.url {\n            case \"https://a.com/foo.zip\":\n                try fileSystem.writeFileContents(destination, bytes: ByteString([0xA1]))\n                return .okay()\n            default:\n                throw StringError(\"unexpected url\")\n            }\n        }\n\n        let archiver = MockArchiver(\n            extractionHandler: { _, archivePath, destinationPath, completion in\n                do {\n                    if archivePath.basename == \"foo.zip\" {\n                        try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"bar\")\n                        completion(.success(()))\n                    } else {\n                        throw StringError(\"unexpected path\")\n                    }\n                } catch {\n                    completion(.failure(error))\n                }\n            }\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/foo.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ],\n                    products: [],\n                    dependencies: []\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A1\",\n                source: .remote(\n                    url: \"https://a.com/foo.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"root\", \"A1\", \"bar.xcframework\")\n            )\n        }\n    }\n\n    func testArtifactChecksum() async throws {\n        try XCTSkipOnWindows(because: #\"\"\"\n        threw error \"\\tmp\\ws doesn't exist in file system\" because there is an issue with InMemoryFileSystem readFileContents(...) on Windows\n        \"\"\"#)\n\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n\n        try fs.createDirectory(sandbox, recursive: true)\n\n        let checksumAlgorithm = MockHashAlgorithm()\n        let binaryArtifactsManager = try Workspace.BinaryArtifactsManager(\n            fileSystem: fs,\n            authorizationProvider: .none,\n            hostToolchain: UserToolchain.mockHostToolchain(fs),\n            checksumAlgorithm: checksumAlgorithm,\n            cachePath: .none,\n            customHTTPClient: .none,\n            customArchiver: .none,\n            delegate: .none\n        )\n\n        // Checks the valid case.\n        do {\n            let binaryPath = sandbox.appending(\"binary.zip\")\n            try fs.writeFileContents(binaryPath, bytes: ByteString([0xAA, 0xBB, 0xCC]))\n\n            let checksum = try binaryArtifactsManager.checksum(forBinaryArtifactAt: binaryPath)\n            XCTAssertEqual(checksumAlgorithm.hashes.map(\\.contents), [[0xAA, 0xBB, 0xCC]])\n            XCTAssertEqual(checksum, \"ccbbaa\")\n        }\n\n        // Checks an unsupported extension.\n        do {\n            let unknownPath = sandbox.appending(\"unknown\")\n            XCTAssertThrowsError(\n                try binaryArtifactsManager.checksum(forBinaryArtifactAt: unknownPath),\n                \"error expected\"\n            ) { error in\n                XCTAssertEqual(\n                    error as? StringError,\n                    StringError(\"unexpected file type; supported extensions are: zip\")\n                )\n            }\n        }\n\n        // Checks a supported extension that is not a file (does not exist).\n        do {\n            let unknownPath = sandbox.appending(\"missingFile.zip\")\n            XCTAssertThrowsError(\n                try binaryArtifactsManager.checksum(forBinaryArtifactAt: unknownPath),\n                \"error expected\"\n            ) { error in\n                XCTAssertEqual(\n                    error as? StringError,\n                    StringError(\"file not found at path: \\(sandbox.appending(\"missingFile.zip\"))\")\n                )\n            }\n        }\n\n        // Checks a supported extension that is a directory instead of a file.\n        do {\n            let unknownPath = sandbox.appending(\"aDirectory.zip\")\n            try fs.createDirectory(unknownPath)\n            XCTAssertThrowsError(\n                try binaryArtifactsManager.checksum(forBinaryArtifactAt: unknownPath),\n                \"error expected\"\n            ) { error in\n                XCTAssertEqual(\n                    error as? StringError,\n                    StringError(\"file not found at path: \\(sandbox.appending(\"aDirectory.zip\"))\")\n                )\n            }\n        }\n    }\n\n    func testDownloadedArtifactChecksumChange() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let httpClient = HTTPClient { _, _ in\n            throw StringError(\"should not be called\")\n        }\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"A\", type: .binary, url: \"https://a.com/a.zip\", checksum: \"new-checksum\"),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient\n            )\n        )\n\n        let rootPath = try workspace.pathToRoot(withName: \"Root\")\n        let rootRef = PackageReference.root(identity: PackageIdentity(path: rootPath), path: rootPath)\n\n        try await workspace.set(\n            managedArtifacts: [\n                .init(\n                    packageRef: rootRef,\n                    targetName: \"A\",\n                    source: .remote(\n                        url: \"https://a.com/a.zip\",\n                        checksum: \"old-checksum\"\n                    ),\n                    path: workspace.artifactsDir.appending(components: \"Root\", \"A.xcframework\"),\n                    kind: .xcframework\n                ),\n            ]\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\"artifact of binary target 'A' has changed checksum\"),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadedArtifactChecksumChangeURLChange() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a.zip\":\n                contents = [0xA1]\n            case \"b.zip\":\n                contents = [0xB1]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            return .okay()\n        }\n\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"a.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A\")\n                case \"b.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"B\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/b.zip\",\n                            checksum: \"b1\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        let rootPath = try workspace.pathToRoot(withName: \"Root\")\n        let rootRef = PackageReference.root(identity: PackageIdentity(path: rootPath), path: rootPath)\n\n        try await workspace.set(\n            managedArtifacts: [\n                .init(\n                    packageRef: rootRef,\n                    targetName: \"A\",\n                    source: .remote(\n                        url: \"https://a.com/a.zip\",\n                        checksum: \"a1\"\n                    ),\n                    path: workspace.artifactsDir.appending(components: \"Root\", \"A.xcframework\"),\n                    kind: .xcframework\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testArtifactDownloadAddsAcceptHeader() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let acceptHeaders = ThreadSafeBox([String]())\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n            acceptHeaders.mutate { $0.append(request.headers.get(\"accept\").first!) }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a1.zip\":\n                contents = [0xA1]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"a1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(acceptHeaders.get(), [\n                \"application/octet-stream\",\n            ])\n        }\n    }\n\n    func testDownloadedArtifactNoCache() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeBox(0)\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a1.zip\":\n                contents = [0xA1]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads.increment()\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"a1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        // should not come from cache\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.get(), 1)\n        }\n\n        // state is there, should not come from local cache\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.get(), 1)\n        }\n\n        // resetting state, should not come from global cache\n        try await workspace.resetState()\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.get(), 2)\n        }\n    }\n\n    func testDownloadedArtifactCache() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeBox(0)\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a1.zip\":\n                contents = [0xA1]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads.increment()\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"a1.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A1\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: true\n            )\n        )\n\n        // should not come from cache\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.get(), 1)\n        }\n\n        // state is there, should not come from local cache\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.get(), 1)\n        }\n\n        // resetting state, should come from global cache\n        try await workspace.resetState()\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.get(), 1)\n        }\n\n        // delete global cache, should download again\n        try await workspace.resetState()\n        try fs.removeFileTree(fs.swiftPMCacheDirectory)\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.get(), 2)\n        }\n\n        // resetting state, should come from global cache again\n        try await workspace.resetState()\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.get(), 2)\n        }\n    }\n\n    func testDownloadedArtifactTransitive() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a.zip\":\n                contents = [0xA]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            if downloads[request.url] != nil {\n                throw StringError(\"\\(request.url) already requested\")\n            }\n            downloads[request.url] = destination\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"a.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A\")\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n\n                if archiver.extractions.get().contains(where: { $0.archivePath == archivePath }) {\n                    throw StringError(\"\\(archivePath) already extracted\")\n                }\n\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"A\", package: \"A\"),\n                            .product(name: \"B\", package: \"B\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                        .sourceControl(path: \"./B\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(name: \"A\", type: .binary, url: \"https://a.com/a.zip\", checksum: \"0a\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"A\", modules: [\"A\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"B\",\n                    targets: [\n                        MockTarget(name: \"B\", dependencies: [\n                            .product(name: \"C\", package: \"C\"),\n                            .product(name: \"D\", package: \"D\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"B\", modules: [\"B\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./C\", requirement: .exact(\"1.0.0\")),\n                        .sourceControl(path: \"./D\", requirement: .exact(\"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"C\",\n                    targets: [\n                        MockTarget(name: \"C\", dependencies: [\n                            .product(name: \"A\", package: \"A\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"C\", modules: [\"C\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"D\",\n                    targets: [\n                        MockTarget(name: \"D\", dependencies: [\n                            .product(name: \"A\", package: \"A\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"D\", modules: [\"D\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"a\"])))\n            XCTAssertEqual(downloads.map(\\.key.absoluteString).sorted(), [\n                \"https://a.com/a.zip\",\n            ])\n            XCTAssertEqual(workspace.checksumAlgorithm.hashes.map(\\.hexadecimalRepresentation).sorted(), [\n                ByteString([0xA]).hexadecimalRepresentation,\n            ])\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A\"]),\n            ])\n            XCTAssertEqual(\n                downloads.map(\\.value).sorted(),\n                archiver.extractions.map(\\.archivePath).sorted()\n            )\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A\",\n                source: .remote(\n                    url: \"https://a.com/a.zip\",\n                    checksum: \"0a\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A\", \"A.xcframework\")\n            )\n        }\n    }\n\n    func testDownloadedArtifactArchiveExists() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        // this relies on internal knowledge of the destination path construction\n        let expectedDownloadDestination = sandbox.appending(\n            components: \".build\",\n            \"artifacts\",\n            \"root\",\n            \"binary\",\n            \"binary.zip\"\n        )\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            // this is to test the test's integrity, as it relied on internal knowledge of the destination path\n            // construction\n            guard expectedDownloadDestination == destination else {\n                throw StringError(\"expected destination of \\(expectedDownloadDestination)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"binary.zip\":\n                contents = [0x01]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            // in-memory fs does not check for this!\n            if fileSystem.exists(destination) {\n                throw StringError(\"\\(destination) already exists\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"binary.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"binary\")\n                    archiver.extractions\n                        .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"binary\",\n                            type: .binary,\n                            url: \"https://a.com/binary.zip\",\n                            checksum: \"01\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        // write the file to test it gets deleted\n\n        try fs.createDirectory(expectedDownloadDestination.parentDirectory, recursive: true)\n        try fs.writeFileContents(\n            expectedDownloadDestination,\n            bytes: [],\n            atomically: true\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"binary\",\n                source: .remote(\n                    url: \"https://a.com/binary.zip\",\n                    checksum: \"01\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"root\", \"binary\", \"binary.xcframework\")\n            )\n        }\n    }\n\n    func testDownloadedArtifactConcurrency() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let maxConcurrentRequests = 2\n        let concurrentRequests = ThreadSafeBox(0)\n\n        var configuration = HTTPClient.Configuration()\n        configuration.maxConcurrentRequests = maxConcurrentRequests\n        let httpClient = HTTPClient(configuration: configuration) { request, _ in\n            defer {\n                concurrentRequests.decrement()\n            }\n\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            concurrentRequests.increment()\n            if concurrentRequests.get() > maxConcurrentRequests {\n                XCTFail(\"too many concurrent requests \\(concurrentRequests), expected \\(maxConcurrentRequests)\")\n            }\n\n            // returns a dummy zipfile for the requested artifact\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: [0x01],\n                atomically: true\n            )\n\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { _, archivePath, destinationPath, completion in\n            do {\n                try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: archivePath.basenameWithoutExt)\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let packages = try (0 ... maxConcurrentRequests * 10).map { index in\n            try MockPackage(\n                name: \"library\\(index)\",\n                targets: [\n                    MockTarget(\n                        name: \"binary\\(index)\",\n                        type: .binary,\n                        url: \"https://somewhere.com/binary\\(index).zip\",\n                        checksum: \"01\"\n                    ),\n                ],\n                products: [\n                    MockProduct(name: \"binary\\(index)\", modules: [\"binary\\(index)\"]),\n                ],\n                versions: [\"1.0.0\"]\n            )\n        }\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"App\",\n                    targets: [\n                        MockTarget(\n                            name: \"App\",\n                            dependencies: packages.map { package in\n                                .product(name: package.targets.first!.name, package: package.name)\n                            }\n                        ),\n                    ],\n                    products: [],\n                    dependencies: packages.map { package in\n                        .sourceControl(path: \"./\\(package.name)\", requirement: .exact(\"1.0.0\"))\n                    }\n                ),\n            ],\n            packages: packages,\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"App\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            for package in packages {\n                let targetName = package.targets.first!.name\n                result.check(\n                    packageIdentity: .plain(package.name),\n                    targetName: targetName,\n                    source: .remote(\n                        url: \"https://somewhere.com/\\(targetName).zip\",\n                        checksum: \"01\"\n                    ),\n                    path: workspace.artifactsDir.appending(\n                        components: package.name,\n                        targetName,\n                        \"\\(targetName).xcframework\"\n                    )\n                )\n            }\n        }\n    }\n\n    func testDownloadedArtifactStripFirstComponent() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"flat.zip\":\n                contents = [0x01]\n            case \"nested.zip\":\n                contents = [0x02]\n            case \"nested2.zip\":\n                contents = [0x03]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads[request.url] = destination\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                switch archivePath.basename {\n                case \"flat.zip\":\n                    try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"flat\")\n                    archiver.extractions\n                        .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                case \"nested.zip\":\n                    let nestedPath = destinationPath.appending(\"root\")\n                    try fs.createDirectory(nestedPath)\n                    try createDummyXCFramework(fileSystem: fs, path: nestedPath, name: \"nested\")\n                    archiver.extractions\n                        .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                case \"nested2.zip\":\n                    let nestedPath = destinationPath.appending(\"root\")\n                    try fs.createDirectory(nestedPath)\n                    try createDummyXCFramework(fileSystem: fs, path: nestedPath, name: \"nested2\")\n                    try fs\n                        .writeFileContents(\n                            nestedPath.appending(\".DS_Store\"),\n                            bytes: []\n                        ) // add a file next to the directory\n\n                    archiver.extractions\n                        .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"flat\",\n                            type: .binary,\n                            url: \"https://a.com/flat.zip\",\n                            checksum: \"01\"\n                        ),\n                        MockTarget(\n                            name: \"nested\",\n                            type: .binary,\n                            url: \"https://a.com/nested.zip\",\n                            checksum: \"02\"\n                        ),\n\n                        MockTarget(\n                            name: \"nested2\",\n                            type: .binary,\n                            url: \"https://a.com/nested2.zip\",\n                            checksum: \"03\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"root\"])))\n            XCTAssertEqual(downloads.map(\\.key.absoluteString).sorted(), [\n                \"https://a.com/flat.zip\",\n                \"https://a.com/nested.zip\",\n                \"https://a.com/nested2.zip\",\n            ])\n            XCTAssertEqual(workspace.checksumAlgorithm.hashes.map(\\.hexadecimalRepresentation).sorted(), [\n                ByteString([0x01]).hexadecimalRepresentation,\n                ByteString([0x02]).hexadecimalRepresentation,\n                ByteString([0x03]).hexadecimalRepresentation,\n            ])\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"flat\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"nested\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"nested2\"]),\n            ])\n            XCTAssertEqual(\n                downloads.map(\\.value).sorted(),\n                archiver.extractions.map(\\.archivePath).sorted()\n            )\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"flat\",\n                source: .remote(\n                    url: \"https://a.com/flat.zip\",\n                    checksum: \"01\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"root\", \"flat\", \"flat.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"nested\",\n                source: .remote(\n                    url: \"https://a.com/nested.zip\",\n                    checksum: \"02\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"root\", \"nested\", \"nested.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"nested2\",\n                source: .remote(\n                    url: \"https://a.com/nested2.zip\",\n                    checksum: \"03\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"root\", \"nested2\", \"nested2.xcframework\")\n            )\n        }\n    }\n\n    // MARK: - Binary Artifact Mirroring Tests\n\n    func testRemoteBinaryArtifactMirroring() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n\n        // Setup mirrors\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"https://mirror.example.com/artifacts/a.zip\", for: \"https://a.com/a.zip\")\n        try mirrors.set(mirror: \"https://mirror.example.com/artifacts/b.zip\", for: \"https://b.com/b.zip\")\n\n        // HTTP client that tracks which URLs were actually requested\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.absoluteString {\n            case \"https://mirror.example.com/artifacts/a.zip\":\n                contents = [0xA1]\n            case \"https://mirror.example.com/artifacts/b.zip\":\n                contents = [0xB0]\n            default:\n                throw StringError(\"unexpected url \\(request.url.absoluteString)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads[request.url] = destination\n            return .okay()\n        }\n\n        // Create dummy xcframework directories\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                let name: String\n                switch archivePath.basename {\n                case \"a.zip\":\n                    name = \"A\"\n                case \"b.zip\":\n                    name = \"B\"\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: name)\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"A\", package: \"A\"),\n                            \"B\",\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                        .sourceControl(path: \"./B\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A\", modules: [\"A\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"B\",\n                    targets: [\n                        MockTarget(\n                            name: \"B\",\n                            type: .binary,\n                            url: \"https://b.com/b.zip\",\n                            checksum: \"b0\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"B\", modules: [\"B\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            mirrors: mirrors,\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false // disable cache\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Verify that mirrored URLs were used for downloads\n        let downloadedURLs = downloads.map(\\.key.absoluteString).sorted()\n        XCTAssertEqual(downloadedURLs, [\n            \"https://mirror.example.com/artifacts/a.zip\",\n            \"https://mirror.example.com/artifacts/b.zip\",\n        ])\n\n        // Verify managed artifacts store the mirrored URLs\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A\",\n                source: .remote(\n                    url: \"https://mirror.example.com/artifacts/a.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A\", \"A.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"b\"),\n                targetName: \"B\",\n                source: .remote(\n                    url: \"https://mirror.example.com/artifacts/b.zip\",\n                    checksum: \"b0\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"b\", \"B\", \"B.xcframework\")\n            )\n        }\n\n        // Verify delegate events use mirrored URLs\n        XCTAssertMatch(workspace.delegate.events, [\"downloading binary artifact package: https://mirror.example.com/artifacts/a.zip\"])\n        XCTAssertMatch(workspace.delegate.events, [\"downloading binary artifact package: https://mirror.example.com/artifacts/b.zip\"])\n    }\n\n    func testRemoteBinaryArtifactNoMirroring() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n\n        // No mirrors configured\n        let mirrors = try DependencyMirrors()\n\n        // HTTP client that tracks which URLs were actually requested\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.absoluteString {\n            case \"https://a.com/a.zip\":\n                contents = [0xA1]\n            default:\n                throw StringError(\"unexpected url \\(request.url.absoluteString)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads[request.url] = destination\n            return .okay()\n        }\n\n        // Create dummy xcframework directory\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A\")\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"A\", package: \"A\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A\", modules: [\"A\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            mirrors: mirrors,\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Verify that original URLs were used when no mirror is configured\n        let downloadedURLs = downloads.map(\\.key.absoluteString)\n        XCTAssertEqual(downloadedURLs, [\"https://a.com/a.zip\"])\n\n        // Verify managed artifacts store the original URLs\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A\",\n                source: .remote(\n                    url: \"https://a.com/a.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A\", \"A.xcframework\")\n            )\n        }\n    }\n\n    func testRemoteBinaryArtifactMirroringWithArtifactBundleIndex() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n        let hostToolchain = try UserToolchain.mockHostToolchain(fs)\n\n        // Setup mirrors\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"https://mirror.example.com/artifacts/index.artifactbundleindex\", for: \"https://a.com/index.artifactbundleindex\")\n\n        // Prepare artifact bundle index JSON\n        let indexJSON = \"\"\"\n        {\n          \"schemaVersion\": \"1.0\",\n          \"archives\": [\n            {\n              \"fileName\": \"a.zip\",\n              \"checksum\": \"a1\",\n              \"supportedTriples\": [\"\\(hostToolchain.targetTriple.tripleString)\"]\n            }\n          ]\n        }\n        \"\"\"\n\n        // Calculate checksum for the index file\n        let checksumAlgorithm = MockHashAlgorithm()\n        let indexFileChecksum = checksumAlgorithm.hash(ByteString(Array(indexJSON.utf8))).hexadecimalRepresentation\n\n        // HTTP client that handles both index file and archive downloads\n        let httpClient = HTTPClient { request, _ in\n            switch request.kind {\n            case .generic:\n                switch request.url.absoluteString {\n                case \"https://mirror.example.com/artifacts/index.artifactbundleindex\":\n                    return .okay(body: indexJSON)\n                default:\n                    throw StringError(\"unexpected url \\(request.url.absoluteString)\")\n                }\n\n            case .download(let fileSystem, let destination):\n                switch request.url.absoluteString {\n                case \"https://mirror.example.com/artifacts/a.zip\":\n                    // Return the actual archive\n                    try fileSystem.writeFileContents(\n                        destination,\n                        bytes: ByteString([0xA1]),\n                        atomically: true\n                    )\n                default:\n                    throw StringError(\"unexpected url \\(request.url.absoluteString)\")\n                }\n                downloads[request.url] = destination\n                return .okay()\n            }\n        }\n\n        // Create dummy xcframework directory\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: \"A\")\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"A\", package: \"A\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/index.artifactbundleindex\",\n                            checksum: indexFileChecksum\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A\", modules: [\"A\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            mirrors: mirrors,\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            ), checksumAlgorithm: checksumAlgorithm\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Verify that mirrored URLs were used for both index and archive downloads\n        // Note: The index file is downloaded via .generic request, not .download, so it won't appear in downloads\n        let downloadedURLs = downloads.map(\\.key.absoluteString).sorted()\n        XCTAssertEqual(downloadedURLs, [\n            \"https://mirror.example.com/artifacts/a.zip\",\n        ])\n\n        // Verify managed artifacts store the mirrored archive URL\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A\",\n                source: .remote(\n                    url: \"https://mirror.example.com/artifacts/a.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A\", \"A.xcframework\")\n            )\n        }\n    }\n\n    func testRemoteBinaryArtifactPartialMirroring() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n\n        // Setup mirrors for only one artifact\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"https://mirror.example.com/artifacts/a.zip\", for: \"https://a.com/a.zip\")\n        // No mirror for b.com/b.zip\n\n        // HTTP client that handles both mirrored and non-mirrored URLs\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.absoluteString {\n            case \"https://mirror.example.com/artifacts/a.zip\":\n                contents = [0xA1]\n            case \"https://b.com/b.zip\":\n                contents = [0xB0]\n            default:\n                throw StringError(\"unexpected url \\(request.url.absoluteString)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads[request.url] = destination\n            return .okay()\n        }\n\n        // Create dummy xcframework directories\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                let name: String\n                switch archivePath.basename {\n                case \"a.zip\":\n                    name = \"A\"\n                case \"b.zip\":\n                    name = \"B\"\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: name)\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"A\", package: \"A\"),\n                            \"B\",\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                        .sourceControl(path: \"./B\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.zip\",\n                            checksum: \"a1\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A\", modules: [\"A\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"B\",\n                    targets: [\n                        MockTarget(\n                            name: \"B\",\n                            type: .binary,\n                            url: \"https://b.com/b.zip\",\n                            checksum: \"b0\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"B\", modules: [\"B\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            mirrors: mirrors,\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n\n        // Verify that mirrored URL was used for A, original URL for B\n        let downloadedURLs = downloads.map(\\.key.absoluteString).sorted()\n        XCTAssertEqual(downloadedURLs, [\n            \"https://b.com/b.zip\",\n            \"https://mirror.example.com/artifacts/a.zip\",\n        ])\n\n        // Verify managed artifacts store the correct URLs\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A\",\n                source: .remote(\n                    url: \"https://mirror.example.com/artifacts/a.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A\", \"A.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"b\"),\n                targetName: \"B\",\n                source: .remote(\n                    url: \"https://b.com/b.zip\",\n                    checksum: \"b0\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"b\", \"B\", \"B.xcframework\")\n            )\n        }\n    }\n\n    func testArtifactMultipleExtensions() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs: InMemoryFileSystem = InMemoryFileSystem()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n\n        // returns a dummy zipfile for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            guard case .download(let fileSystem, let destination) = request.kind else {\n                throw StringError(\"invalid request \\(request.kind)\")\n            }\n\n            let contents: [UInt8]\n            switch request.url.lastPathComponent {\n            case \"a1.xcframework.zip\":\n                contents = [0xA1]\n            case \"a2.zip.zip\":\n                contents = [0xA2]\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n\n            try fileSystem.writeFileContents(\n                destination,\n                bytes: ByteString(contents),\n                atomically: true\n            )\n\n            downloads[request.url] = destination\n            return .okay()\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                let name: String\n                switch archivePath.basename {\n                case \"a1.xcframework.zip\":\n                    name = \"A1\"\n                case \"a2.zip.zip\":\n                    name = \"A2\"\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                try createDummyXCFramework(fileSystem: fs, path: destinationPath, name: name)\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.xcframework.zip\",\n                            checksum: \"a1\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            url: \"https://a.com/a2.zip.zip\",\n                            checksum: \"a2\"\n                        ),\n                    ],\n                    products: []\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssertEqual(downloads.map(\\.key.absoluteString).sorted(), [\n                \"https://a.com/a1.xcframework.zip\",\n                \"https://a.com/a2.zip.zip\",\n            ])\n            XCTAssertEqual(workspace.checksumAlgorithm.hashes.map(\\.hexadecimalRepresentation).sorted(), [\n                ByteString([0xA1]).hexadecimalRepresentation,\n                ByteString([0xA2]).hexadecimalRepresentation,\n            ])\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"A1\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"root\", \"A2\"]),\n            ])\n            XCTAssertEqual(\n                downloads.map(\\.value).sorted(),\n                archiver.extractions.map(\\.archivePath).sorted()\n            )\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A1\",\n                source: .remote(\n                    url: \"https://a.com/a1.xcframework.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"root\", \"A1\", \"A1.xcframework\")\n            )\n            result.check(\n                packageIdentity: .plain(\"root\"),\n                targetName: \"A2\",\n                source: .remote(\n                    url: \"https://a.com/a2.zip.zip\",\n                    checksum: \"a2\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"root\", \"A2\", \"A2.xcframework\")\n            )\n        }\n    }\n\n    func testLoadRootPackageWithBinaryDependencies() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.zip\",\n                            checksum: \"a1\"\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            url: \"https://a.com/a2.xcframework.zip\",\n                            checksum: \"a2\"\n                        ),\n                        MockTarget(\n                            name: \"A3\",\n                            type: .binary,\n                            url: \"https://a.com/a2.zip.zip\",\n                            checksum: \"a3\"\n                        ),\n                        MockTarget(\n                            name: \"A4\",\n                            type: .binary,\n                            path: \"a4.zip\"\n                        ),\n                    ],\n                    products: []\n                ),\n            ]\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let wks = try workspace.getOrCreateWorkspace()\n        _ = try await wks.loadRootPackage(\n            at: workspace.rootsDir.appending(\"Root\"),\n            observabilityScope: observability.topScope\n        )\n        XCTAssertNoDiagnostics(observability.diagnostics)\n    }\n\n    func testDownloadArchiveIndexFilesHappyPath() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n        let downloads = ThreadSafeKeyValueStore<URL, AbsolutePath>()\n        let hostToolchain = try UserToolchain.mockHostToolchain(fs)\n\n        let ariFiles = [\n            \"\"\"\n            {\n                \"schemaVersion\": \"1.0\",\n                \"archives\": [\n                    {\n                        \"fileName\": \"a1.zip\",\n                        \"checksum\": \"a1\",\n                        \"supportedTriples\": [\"\\(hostToolchain.targetTriple.tripleString)\"]\n                    }\n                ]\n            }\n            \"\"\",\n            \"\"\"\n            {\n                \"schemaVersion\": \"1.0\",\n                \"archives\": [\n                    {\n                        \"fileName\": \"a2/a2.zip\",\n                        \"checksum\": \"a2\",\n                        \"supportedTriples\": [\"\\(hostToolchain.targetTriple.tripleString)\"]\n                    }\n                ]\n            }\n            \"\"\",\n        ]\n\n        let checksumAlgorithm = MockHashAlgorithm() // used in tests\n        let ariFilesChecksums = ariFiles.map { checksumAlgorithm.hash($0).hexadecimalRepresentation }\n\n        // returns a dummy file for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            switch request.kind {\n            case .generic:\n                let contents: String\n                switch request.url.lastPathComponent {\n                case \"a1.artifactbundleindex\":\n                    contents = ariFiles[0]\n                case \"a2.artifactbundleindex\":\n                    contents = ariFiles[1]\n                default:\n                    throw StringError(\"unexpected url \\(request.url)\")\n                }\n                return .okay(body: contents)\n\n            case .download(let fileSystem, let destination):\n                let contents: [UInt8]\n                switch request.url.lastPathComponent {\n                case \"a1.zip\":\n                    contents = [0xA1]\n                case \"a2.zip\":\n                    contents = [0xA2]\n                case \"b.zip\":\n                    contents = [0xB0]\n                default:\n                    throw StringError(\"unexpected url \\(request.url)\")\n                }\n\n                try fileSystem.writeFileContents(\n                    destination,\n                    bytes: ByteString(contents),\n                    atomically: true\n                )\n\n                downloads[request.url] = destination\n                return .okay()\n            }\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                let name: String\n                switch archivePath.basename {\n                case \"a1.zip\":\n                    name = \"A1\"\n                case \"a2.zip\":\n                    name = \"A2\"\n                case \"b.zip\":\n                    name = \"B\"\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                try createDummyArtifactBundle(fileSystem: fs, path: destinationPath, name: name)\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\n                            .product(name: \"A1\", package: \"A\"),\n                            .product(name: \"A2\", package: \"A\"),\n                            \"B\",\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"./A\", requirement: .exact(\"1.0.0\")),\n                        .sourceControl(path: \"./B\", requirement: .exact(\"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"A\",\n                    targets: [\n                        MockTarget(\n                            name: \"A1\",\n                            type: .binary,\n                            url: \"https://a.com/a1.artifactbundleindex\",\n                            checksum: ariFilesChecksums[0]\n                        ),\n                        MockTarget(\n                            name: \"A2\",\n                            type: .binary,\n                            url: \"https://a.com/a2.artifactbundleindex\",\n                            checksum: ariFilesChecksums[1]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"A1\", modules: [\"A1\"]),\n                        MockProduct(name: \"A2\", modules: [\"A2\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"B\",\n                    targets: [\n                        MockTarget(\n                            name: \"B\",\n                            type: .binary,\n                            url: \"https://b.com/b.zip\",\n                            checksum: \"b0\"\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"B\", modules: [\"B\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver,\n                useCache: false\n            ),\n            checksumAlgorithm: checksumAlgorithm\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"a\"])))\n            XCTAssert(fs.isDirectory(sandbox.appending(components: [\".build\", \"artifacts\", \"b\"])))\n            XCTAssertEqual(downloads.map(\\.key.absoluteString).sorted(), [\n                \"https://a.com/a1.zip\",\n                \"https://a.com/a2/a2.zip\",\n                \"https://b.com/b.zip\",\n            ])\n            XCTAssertEqual(\n                checksumAlgorithm.hashes.map(\\.hexadecimalRepresentation).sorted(),\n                (\n                    ariFiles.map(ByteString.init(encodingAsUTF8:)) +\n                        ariFiles.map(ByteString.init(encodingAsUTF8:)) +\n                        [\n                            ByteString([0xA1]),\n                            ByteString([0xA2]),\n                            ByteString([0xB0]),\n                        ]\n                ).map(\\.hexadecimalRepresentation).sorted()\n            )\n            XCTAssertEqual(archiver.extractions.map(\\.destinationPath.parentDirectory).sorted(), [\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A1\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"a\", \"A2\"]),\n                sandbox.appending(components: [\".build\", \"artifacts\", \"extract\", \"b\", \"B\"]),\n            ])\n            XCTAssertEqual(\n                downloads.map(\\.value).sorted(),\n                archiver.extractions.map(\\.archivePath).sorted()\n            )\n        }\n\n        await workspace.checkManagedArtifacts { result in\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A1\",\n                source: .remote(\n                    url: \"https://a.com/a1.zip\",\n                    checksum: \"a1\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A1\", \"A1.artifactbundle\")\n            )\n            result.check(\n                packageIdentity: .plain(\"a\"),\n                targetName: \"A2\",\n                source: .remote(\n                    url: \"https://a.com/a2/a2.zip\",\n                    checksum: \"a2\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"a\", \"A2\", \"A2.artifactbundle\")\n            )\n            result.check(\n                packageIdentity: .plain(\"b\"),\n                targetName: \"B\",\n                source: .remote(\n                    url: \"https://b.com/b.zip\",\n                    checksum: \"b0\"\n                ),\n                path: workspace.artifactsDir.appending(components: \"b\", \"B\", \"B.artifactbundle\")\n            )\n        }\n\n        XCTAssertMatch(workspace.delegate.events, [\"downloading binary artifact package: https://a.com/a1.zip\"])\n        XCTAssertMatch(workspace.delegate.events, [\"downloading binary artifact package: https://a.com/a2/a2.zip\"])\n        XCTAssertMatch(workspace.delegate.events, [\"downloading binary artifact package: https://b.com/b.zip\"])\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"finished downloading binary artifact package: https://a.com/a1.zip\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"finished downloading binary artifact package: https://a.com/a2/a2.zip\"]\n        )\n        XCTAssertMatch(workspace.delegate.events, [\"finished downloading binary artifact package: https://b.com/b.zip\"])\n    }\n\n    func testDownloadArchiveIndexServerError() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        // returns a dummy files for the requested artifact\n        let httpClient = HTTPClient { _, _ in\n            .serverError()\n        }\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.artifactbundleindex\",\n                            checksum: \"does-not-matter\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\n                        \"failed retrieving 'https://a.com/a.artifactbundleindex': badResponseStatusCode(500)\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadArchiveIndexFileBadChecksum() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n        let hostToolchain = try UserToolchain.mockHostToolchain(fs)\n\n        let ari = \"\"\"\n        {\n            \"schemaVersion\": \"1.0\",\n            \"archives\": [\n                {\n                    \"fileName\": \"a1.zip\",\n                    \"checksum\": \"a1\",\n                    \"supportedTriples\": [\"\\(hostToolchain.targetTriple.tripleString)\"]\n                }\n            ]\n        }\n        \"\"\"\n        let checksumAlgorithm = MockHashAlgorithm() // used in tests\n        let ariChecksums = checksumAlgorithm.hash(ari).hexadecimalRepresentation\n\n        // returns a dummy files for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            let contents: String\n            switch request.url.lastPathComponent {\n            case \"a.artifactbundleindex\":\n                contents = ari\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n            return .okay(body: contents)\n        }\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.artifactbundleindex\",\n                            checksum: \"incorrect\"\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\n                        \"failed retrieving 'https://a.com/a.artifactbundleindex': checksum of downloaded artifact of binary target 'A' (\\(ariChecksums)) does not match checksum specified by the manifest (incorrect)\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadArchiveIndexFileChecksumChanges() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.artifactbundleindex\",\n                            checksum: \"new-checksum\"\n                        ),\n                    ]\n                ),\n            ]\n        )\n\n        let rootPath = try workspace.pathToRoot(withName: \"Root\")\n        let rootRef = PackageReference.root(identity: PackageIdentity(path: rootPath), path: rootPath)\n\n        try await workspace.set(\n            managedArtifacts: [\n                .init(\n                    packageRef: rootRef,\n                    targetName: \"A\",\n                    source: .remote(\n                        url: \"https://a.com/a.artifactbundleindex\",\n                        checksum: \"old-checksum\"\n                    ),\n                    path: workspace.artifactsDir.appending(components: \"root\", \"A.xcframework\"),\n                    kind: .xcframework\n                ),\n            ]\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\"artifact of binary target 'A' has changed checksum\"),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadArchiveIndexFileBadArchivesChecksum() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n        let hostToolchain = try UserToolchain.mockHostToolchain(fs)\n\n        let ari = \"\"\"\n        {\n            \"schemaVersion\": \"1.0\",\n            \"archives\": [\n                {\n                    \"fileName\": \"a.zip\",\n                    \"checksum\": \"a\",\n                    \"supportedTriples\": [\"\\(hostToolchain.targetTriple.tripleString)\"]\n                }\n            ]\n        }\n        \"\"\"\n        let checksumAlgorithm = MockHashAlgorithm() // used in tests\n        let ariChecksums = checksumAlgorithm.hash(ari).hexadecimalRepresentation\n\n        // returns a dummy files for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            switch request.kind {\n            case .generic:\n                let contents: String\n                switch request.url.lastPathComponent {\n                case \"a.artifactbundleindex\":\n                    contents = ari\n                default:\n                    throw StringError(\"unexpected url \\(request.url)\")\n                }\n\n                return .okay(body: contents)\n\n            case .download(let fileSystem, let destination):\n                let contents: [UInt8]\n                switch request.url.lastPathComponent {\n                case \"a.zip\":\n                    contents = [0x42]\n                default:\n                    throw StringError(\"unexpected url \\(request.url)\")\n                }\n\n                try fileSystem.writeFileContents(\n                    destination,\n                    bytes: ByteString(contents),\n                    atomically: true\n                )\n\n                return .okay()\n            }\n        }\n\n        // create a dummy xcframework directory from the request archive\n        let archiver = MockArchiver(handler: { archiver, archivePath, destinationPath, completion in\n            do {\n                let name: String\n                switch archivePath.basename {\n                case \"a.zip\":\n                    name = \"A.artifactbundle\"\n                default:\n                    throw StringError(\"unexpected archivePath \\(archivePath)\")\n                }\n                try fs.createDirectory(destinationPath.appending(component: name), recursive: false)\n                archiver.extractions\n                    .append(MockArchiver.Extraction(archivePath: archivePath, destinationPath: destinationPath))\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.artifactbundleindex\",\n                            checksum: ariChecksums\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient,\n                archiver: archiver\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\n                        \"checksum of downloaded artifact of binary target 'A' (42) does not match checksum specified by the manifest (a)\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadArchiveIndexFileArchiveNotFound() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n        let hostToolchain = try UserToolchain.mockHostToolchain(fs)\n\n        let ari = \"\"\"\n        {\n            \"schemaVersion\": \"1.0\",\n            \"archives\": [\n                {\n                    \"fileName\": \"not-found.zip\",\n                    \"checksum\": \"a\",\n                    \"supportedTriples\": [\"\\(hostToolchain.targetTriple.tripleString)\"]\n                }\n            ]\n        }\n        \"\"\"\n        let checksumAlgorithm = MockHashAlgorithm() // used in tests\n        let ariChecksums = checksumAlgorithm.hash(ari).hexadecimalRepresentation\n\n        // returns a dummy files for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            switch request.kind {\n            case .generic:\n                let contents: String\n                switch request.url.lastPathComponent {\n                case \"a.artifactbundleindex\":\n                    contents = ari\n                default:\n                    throw StringError(\"unexpected url \\(request.url)\")\n                }\n                return .okay(body: contents)\n\n            case .download:\n                return .notFound()\n            }\n        }\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.artifactbundleindex\",\n                            checksum: ariChecksums\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\n                        \"failed downloading 'https://a.com/not-found.zip' which is required by binary target 'A': badResponseStatusCode(404)\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDownloadArchiveIndexTripleNotFound() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        try fs.createMockToolchain()\n\n        let hostToolchain = try UserToolchain.mockHostToolchain(fs)\n        let androidTriple = try Triple(\"x86_64-unknown-linux-android\")\n        let macTriple = try Triple(\"arm64-apple-macosx\")\n        let notHostTriple = hostToolchain.targetTriple == androidTriple ? macTriple : androidTriple\n\n        let ari = \"\"\"\n        {\n            \"schemaVersion\": \"1.0\",\n            \"archives\": [\n                {\n                    \"fileName\": \"a1.zip\",\n                    \"checksum\": \"a1\",\n                    \"supportedTriples\": [\"\\(notHostTriple.tripleString)\"]\n                }\n            ]\n        }\n        \"\"\"\n        let checksumAlgorithm = MockHashAlgorithm() // used in tests\n        let ariChecksum = checksumAlgorithm.hash(ari).hexadecimalRepresentation\n\n        // returns a dummy files for the requested artifact\n        let httpClient = HTTPClient { request, _ in\n            let contents: String\n            switch request.url.lastPathComponent {\n            case \"a.artifactbundleindex\":\n                contents = ari\n            default:\n                throw StringError(\"unexpected url \\(request.url)\")\n            }\n            return .okay(body: contents)\n        }\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(\n                            name: \"A\",\n                            type: .binary,\n                            url: \"https://a.com/a.artifactbundleindex\",\n                            checksum: ariChecksum\n                        ),\n                    ]\n                ),\n            ],\n            binaryArtifactsManager: .init(\n                httpClient: httpClient\n            )\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"Root\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .contains(\n                        \"failed retrieving 'https://a.com/a.artifactbundleindex': No supported archive was found for '\\(hostToolchain.targetTriple.tripleString)'\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDuplicateDependencyIdentityWithNameAtRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"FooUtilityPackage\"),\n                            .product(name: \"BarProduct\", package: \"BarUtilityPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"FooUtilityPackage\",\n                            path: \"foo/utility\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControlWithDeprecatedName(\n                            name: \"BarUtilityPackage\",\n                            path: \"bar/utility\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooUtilityPackage\",\n                    path: \"foo/utility\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                // this package never gets loaded since the dependency declaration identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"BarUtilityPackage\",\n                    path: \"bar/utility\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: \"Conflicting identity for utility: dependency '\\(CanonicalPackageLocation(sandbox.pathString))/pkgs/bar/utility' and dependency '\\(CanonicalPackageLocation(sandbox.pathString))/pkgs/foo/utility' both point to the same package identity 'utility'.\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDuplicateDependencyIdentityWithoutNameAtRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"FooUtilityPackage\"),\n                            .product(name: \"BarProduct\", package: \"BarUtilityPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo/utility\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"bar/utility\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooUtilityPackage\",\n                    path: \"foo/utility\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                // this package never gets loaded since the dependency declaration identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"BarUtilityPackage\",\n                    path: \"bar/utility\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                result.check(\n                    diagnostic: \"Conflicting identity for utility: dependency '\\(tmpDirCanonicalPackageLocation)/pkgs/bar/utility' and dependency '\\(tmpDirCanonicalPackageLocation)/pkgs/foo/utility' both point to the same package identity 'utility'.\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDuplicateExplicitDependencyName_AtRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"FooPackage\"),\n                            .product(name: \"BarProduct\", package: \"BarPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"FooPackage\",\n                            path: \"foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControlWithDeprecatedName(\n                            name: \"FooPackage\",\n                            path: \"bar\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                // this package never gets loaded since the dependency declaration name is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: \"'root' dependency on '\\(sandbox.appending(components: \"pkgs\", \"bar\"))' conflicts with dependency on '\\(sandbox.appending(components: \"pkgs\", \"foo\"))' which has the same explicit name 'FooPackage'\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDuplicateManifestNameAtRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            \"FooProduct\",\n                            \"BarProduct\",\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"MyPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testDuplicateManifestName_ExplicitProductPackage_AtRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"MyPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testManifestNameAndIdentityConflict_AtRoot_Pre52() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            \"FooProduct\",\n                            \"BarProduct\",\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"foo\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"foo\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testManifestNameAndIdentityConflict_AtRoot_Post52_Incorrect() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            \"FooProduct\",\n                            \"BarProduct\",\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_3\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"foo\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"foo\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: \"dependency 'FooProduct' in target 'RootTarget' requires explicit declaration; reference the package in the target dependency with '.product(name: \\\"FooProduct\\\", package: \\\"foo\\\")'\",\n                    severity: .error\n                )\n                result.check(\n                    diagnostic: \"dependency 'BarProduct' in target 'RootTarget' requires explicit declaration; reference the package in the target dependency with '.product(name: \\\"BarProduct\\\", package: \\\"bar\\\")'\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testManifestNameAndIdentityConflict_AtRoot_Post52_Correct() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_3\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"foo\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"foo\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testManifestNameAndIdentityConflict_ExplicitDependencyNames_AtRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            \"FooProduct\",\n                            \"BarProduct\",\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControlWithDeprecatedName(\n                            name: \"foo\",\n                            path: \"bar\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"foo\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"foo\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: \"'root' dependency on '\\(sandbox.appending(components: \"pkgs\", \"bar\"))' conflicts with dependency on '\\(sandbox.appending(components: \"pkgs\", \"foo\"))' which has the same explicit name 'foo'\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testManifestNameAndIdentityConflict_ExplicitDependencyNames_ExplicitProductPackage_AtRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControlWithDeprecatedName(\n                            name: \"foo\",\n                            path: \"bar\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v5_3\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"foo\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"foo\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: \"'root' dependency on '\\(sandbox.appending(components: \"pkgs\", \"bar\"))' conflicts with dependency on '\\(sandbox.appending(components: \"pkgs\", \"foo\"))' which has the same explicit name 'foo'\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDuplicateTransitiveIdentityWithNames() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooUtilityProduct\", package: \"FooUtilityPackage\"),\n                            .product(name: \"BarProduct\", package: \"BarPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"FooUtilityPackage\",\n                            path: \"foo/utility\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControlWithDeprecatedName(\n                            name: \"BarPackage\",\n                            path: \"bar\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooUtilityPackage\",\n                    path: \"foo/utility\",\n                    targets: [\n                        MockTarget(name: \"FooUtilityTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooUtilityProduct\", modules: [\"FooUtilityTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"OtherUtilityProduct\", package: \"OtherUtilityPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"OtherUtilityPackage\",\n                            path: \"other/utility\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"OtherUtilityPackage\",\n                    path: \"other/utility\",\n                    targets: [\n                        MockTarget(name: \"OtherUtilityTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"OtherUtilityProduct\", modules: [\"OtherUtilityTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                result.check(\n                    diagnostic: \"Conflicting identity for utility: dependency '\\(tmpDirCanonicalPackageLocation)/pkgs/other/utility' and dependency '\\(tmpDirCanonicalPackageLocation)/pkgs/foo/utility' both point to the same package identity 'utility'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->\\(tmpDirCanonicalPackageLocation)/pkgs/bar->\\(tmpDirCanonicalPackageLocation)/pkgs/other/utility (B) \\(tmpDirCanonicalPackageLocation)/roots/root->\\(tmpDirCanonicalPackageLocation)/pkgs/foo/utility. If there are multiple chains that lead to the same dependency, only the first chain is shown here. To see all chains use debug output option. To resolve the conflict, coordinate with the maintainer of the package that introduces the conflicting dependency.\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDuplicateTransitiveIdentityMultiplePossibleChains() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"HouseProduct\", package: \"HousePackage\"),\n                            .product(name: \"ShackProduct\", package: \"ShackPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"HousePackage\",\n                            path: \"house\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControlWithDeprecatedName(\n                            name: \"ShackPackage\",\n                            path: \"shack\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"HousePackage\",\n                    path: \"house\",\n                    targets: [\n                        MockTarget(name: \"HouseTarget\", dependencies: [\n                            .product(name: \"BudgetWindowProduct\", package: \"BudgetWindowPackage\"),\n                            .product(name: \"PremiumWindowProduct\", package: \"PremiumWindowPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"HouseProduct\", modules: [\"HouseTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"BudgetWindowPackage\",\n                            path: \"budget_window\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControlWithDeprecatedName(\n                            name: \"PremiumWindowPackage\",\n                            path: \"premium_window\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"ShackPackage\",\n                    path: \"shack\",\n                    targets: [\n                        MockTarget(name: \"ShackTarget\", dependencies: [\n                            .product(name: \"StandardGlassProduct\", package: \"StandardGlassPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"ShackProduct\", modules: [\"ShackTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"StandardGlassPackage\",\n                            path: \"standard/glass\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BudgetWindowPackage\",\n                    path: \"budget_window\",\n                    targets: [\n                        MockTarget(name: \"BudgetWindowTarget\", dependencies: [\n                            .product(name: \"StandardGlassProduct\", package: \"StandardGlassPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BudgetWindowProduct\", modules: [\"BudgetWindowTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"StandardGlassPackage\",\n                            path: \"standard/glass\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"PremiumWindowPackage\",\n                    path: \"premium_window\",\n                    targets: [\n                        MockTarget(name: \"PremiumWindowTarget\", dependencies: [\n                            .product(name: \"TemperedGlassProduct\", package: \"TemperedGlassPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"PremiumWindowProduct\", modules: [\"PremiumWindowTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"TemperedGlassPackage\",\n                            path: \"tempered/glass\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"StandardGlassPackage\",\n                    path: \"standard/glass\",\n                    targets: [\n                        MockTarget(name: \"StandardGlassTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"StandardGlassProduct\", modules: [\"StandardGlassTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n\n                // This package triggers the conflict.\n                MockPackage(\n                    name: \"TemperedGlassPackage\",\n                    path: \"tempered/glass\",\n                    targets: [\n                        MockTarget(name: \"TemperedTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"TemperedGlassProduct\", modules: [\"TemperedGlassTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        let sandboxCanonicalPackageLocation: CanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: \"Conflicting identity for glass: dependency '\\(sandboxCanonicalPackageLocation)/pkgs/tempered/glass' and dependency '\\(sandboxCanonicalPackageLocation)/pkgs/standard/glass' both point to the same package identity 'glass'. The dependencies are introduced through the following chains: (A) \\(sandboxCanonicalPackageLocation)/roots/root->\\(sandboxCanonicalPackageLocation)/pkgs/house->\\(sandboxCanonicalPackageLocation)/pkgs/premium_window->\\(sandboxCanonicalPackageLocation)/pkgs/tempered/glass (B) \\(sandboxCanonicalPackageLocation)/roots/root->\\(sandboxCanonicalPackageLocation)/pkgs/shack->\\(sandboxCanonicalPackageLocation)/pkgs/standard/glass. If there are multiple chains that lead to the same dependency, only the first chain is shown here. To see all chains use debug output option. To resolve the conflict, coordinate with the maintainer of the package that introduces the conflicting dependency.\",\n                    severity: .error\n                )\n            }\n        }\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                let prefix1 = sandbox.appending(components: [\"pkgs\", \"tempered\", \"glass\"])\n                result.checkUnordered(\n                    diagnostic: .contains(\"Conflicting identity for glass: chains of dependencies for \\(prefix1): [[\\(sandboxCanonicalPackageLocation)/roots/root, \\(sandboxCanonicalPackageLocation)/pkgs/house, \\(sandboxCanonicalPackageLocation)/pkgs/premium_window, \\(sandboxCanonicalPackageLocation)/pkgs/tempered/glass]]\"),\n                    severity: .debug\n                )\n\n                let prefix2 = sandbox.appending(components: [\"pkgs\", \"standard\", \"glass\"])\n                result.checkUnordered(\n                    diagnostic: .contains(\"Conflicting identity for glass: chains of dependencies for \\(prefix2): [[\\(sandboxCanonicalPackageLocation)/roots/root, \\(sandboxCanonicalPackageLocation)/pkgs/shack, \\(sandboxCanonicalPackageLocation)/pkgs/standard/glass], [\\(sandboxCanonicalPackageLocation)/roots/root, \\(sandboxCanonicalPackageLocation)/pkgs/house, \\(sandboxCanonicalPackageLocation)/pkgs/budget_window, \\(sandboxCanonicalPackageLocation)/pkgs/standard/glass]]\"),\n                    severity: .debug\n                )\n            }\n        }\n    }\n\n    func testDuplicateIdentityDependenciesMultipleRoots() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"River\",\n                    targets: [\n                        MockTarget(name: \"RiverTarget\", dependencies: [\n                            .product(name: \"FlowingWaterProduct\", package: \"FlowingWaterPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"FlowingWaterPackage\",\n                            path: \"flowing/water\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Lake\",\n                    targets: [\n                        MockTarget(name: \"LakeTarget\", dependencies: [\n                            .product(name: \"StandingWaterProduct\", package: \"StandingWaterPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"StandingWaterPackage\",\n                            path: \"standing/water\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FlowingWaterPackage\",\n                    path: \"flowing/water\",\n                    targets: [\n                        MockTarget(name: \"FlowingWaterTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FlowingWaterProduct\", modules: [\"FlowingWaterTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n\n                // This package triggers the conflict.\n                MockPackage(\n                    name: \"StandingWaterPackage\",\n                    path: \"standing/water\",\n                    targets: [\n                        MockTarget(name: \"StandingWaterTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"StandingWaterProduct\", modules: [\"StandingWaterTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"River\", \"Lake\"]) { _, diagnostics in\n            testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                // Order of roots processing is not deterministic. To make the test less brittle, we check debug\n                // output of individual conflicts instead of a summarized error message.\n                let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                let prefix = sandbox.appending(components: [\"pkgs\", \"standing\", \"water\"])\n                result.checkUnordered(\n                    diagnostic: .contains(\"Conflicting identity for water: chains of dependencies for \\(prefix): [[\\(tmpDirCanonicalPackageLocation)/roots/lake, \\(tmpDirCanonicalPackageLocation)/pkgs/standing/water]]\"),\n                    severity: .debug\n                )\n\n                let prefix2 = sandbox.appending(components: [\"pkgs\", \"flowing\", \"water\"])\n                result.checkUnordered(\n                    diagnostic: .contains(\"Conflicting identity for water: chains of dependencies for \\(prefix2): [[\\(tmpDirCanonicalPackageLocation)/roots/river, \\(tmpDirCanonicalPackageLocation)/pkgs/flowing/water]]\"),\n                    severity: .debug\n                )\n            }\n        }\n    }\n\n    func testDuplicateTransitiveIdentityWithoutNames() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooUtilityProduct\", package: \"utility\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo/utility\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooUtilityPackage\",\n                    path: \"foo/utility\",\n                    targets: [\n                        MockTarget(name: \"FooUtilityTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooUtilityProduct\", modules: [\"FooUtilityTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"OtherUtilityProduct\", package: \"utility\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"other-foo/utility\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"OtherUtilityPackage\",\n                    path: \"other-foo/utility\",\n                    targets: [\n                        MockTarget(name: \"OtherUtilityTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"OtherUtilityProduct\", modules: [\"OtherUtilityTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        // 9/2021 this is currently emitting a warning only to support backwards compatibility\n        // we will escalate this to an error in a few versions to tighten up the validation\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                result.check(\n                    diagnostic: \"Conflicting identity for utility: dependency '\\(tmpDirCanonicalPackageLocation)/pkgs/other-foo/utility' and dependency '\\(tmpDirCanonicalPackageLocation)/pkgs/foo/utility' both point to the same package identity 'utility'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->\\(tmpDirCanonicalPackageLocation)/pkgs/bar->\\(tmpDirCanonicalPackageLocation)/pkgs/other-foo/utility (B) \\(tmpDirCanonicalPackageLocation)/roots/root->\\(tmpDirCanonicalPackageLocation)/pkgs/foo/utility. If there are multiple chains that lead to the same dependency, only the first chain is shown here. To see all chains use debug output option. To resolve the conflict, coordinate with the maintainer of the package that introduces the conflicting dependency. This will be escalated to an error in future versions of SwiftPM.\",\n                    severity: .warning\n                )\n                // FIXME: rdar://72940946\n                // we need to improve this situation or diagnostics when working on identity\n                result.check(\n                    diagnostic: \"product 'OtherUtilityProduct' required by package 'bar' target 'BarTarget' not found in package 'utility'.\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDuplicateTransitiveIdentitySimilarURLs1() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://github.com/foo/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/foo/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/foo/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/foo/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testDuplicateTransitiveIdentitySimilarURLs2() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/foo/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/foo/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"http://github.com/foo/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"http://github.com/foo/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testDuplicateTransitiveIdentityGitHubURLs1() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/foo/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/foo/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"git@github.com:foo/foo.git\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"git@github.com:foo/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testDuplicateTransitiveIdentityGitHubURLs2() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.enterprise.com/foo/foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.enterprise.com/foo/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"git@github.enterprise.com:foo/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"git@github.enterprise.com:foo/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testDuplicateTransitiveIdentityUnfamiliarURLs() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/foo/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/foo/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/foo-moved/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/foo-moved/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        // 9/2021 this is currently emitting a warning only to support backwards compatibility\n        // we will escalate this to an error in a few versions to tighten up the validation\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                result.check(\n                    diagnostic: \"Conflicting identity for foo: dependency 'github.com/foo-moved/foo' and dependency 'github.com/foo/foo' both point to the same package identity 'foo'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->\\(tmpDirCanonicalPackageLocation)/pkgs/bar->github.com/foo-moved/foo (B) \\(tmpDirCanonicalPackageLocation)/roots/root->github.com/foo/foo. If there are multiple chains that lead to the same dependency, only the first chain is shown here. To see all chains use debug output option. To resolve the conflict, coordinate with the maintainer of the package that introduces the conflicting dependency. This will be escalated to an error in future versions of SwiftPM.\",\n                    severity: .warning\n                )\n            }\n        }\n    }\n\n    func testDuplicateTransitiveIdentityWithSimilarURLs() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                            .product(name: \"BazProduct\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/bar.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/baz.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"https://github.com/org/bar.git\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"Foo\"),\n                            .product(name: \"BazProduct\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/ORG/Foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(url: \"https://github.com/org/baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    url: \"https://github.com/org/baz.git\",\n                    targets: [\n                        MockTarget(name: \"BazTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // URL with different casing\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/ORG/Foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // URL with no .git extension\n                MockPackage(\n                    name: \"BazPackage\",\n                    url: \"https://github.com/org/baz\",\n                    targets: [\n                        MockTarget(name: \"BazTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        // 9/2021 this is currently emitting a warning only to support backwards compatibility\n        // we will escalate this to an error in a few versions to tighten up the validation\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics, minSeverity: .info) { result in\n                result.checkUnordered(\n                    diagnostic: \"dependency on 'foo' is represented by similar locations ('https://github.com/org/foo.git' and 'https://github.com/ORG/Foo.git') which are treated as the same canonical location 'github.com/org/foo'.\",\n                    severity: .info\n                )\n                result.checkUnordered(\n                    diagnostic: \"dependency on 'baz' is represented by similar locations ('https://github.com/org/baz.git' and 'https://github.com/org/baz') which are treated as the same canonical location 'github.com/org/baz'.\",\n                    severity: .info\n                )\n            }\n        }\n    }\n\n    func testDuplicateNestedTransitiveIdentityWithNames() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooUtilityProduct\", package: \"FooUtilityPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"FooUtilityPackage\",\n                            path: \"foo/utility\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v6_0\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooUtilityPackage\",\n                    path: \"foo/utility\",\n                    targets: [\n                        MockTarget(name: \"FooUtilityTarget\", dependencies: [\n                            .product(name: \"BarProduct\", package: \"BarPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooUtilityProduct\", modules: [\"FooUtilityTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"BarPackage\",\n                            path: \"bar\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"OtherUtilityProduct\", package: \"OtherUtilityPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"OtherUtilityPackage\",\n                            path: \"other/utility\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"OtherUtilityPackage\",\n                    path: \"other/utility\",\n                    targets: [\n                        MockTarget(name: \"OtherUtilityTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"OtherUtilityProduct\", modules: [\"OtherUtilityTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                result.check(\n                    diagnostic: \"Conflicting identity for utility: dependency '\\(tmpDirCanonicalPackageLocation)/pkgs/other/utility' and dependency '\\(tmpDirCanonicalPackageLocation)/pkgs/foo/utility' both point to the same package identity 'utility'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->\\(tmpDirCanonicalPackageLocation)/pkgs/foo/utility->\\(tmpDirCanonicalPackageLocation)/pkgs/bar->\\(tmpDirCanonicalPackageLocation)/pkgs/other/utility (B) \\(tmpDirCanonicalPackageLocation)/roots/root->\\(tmpDirCanonicalPackageLocation)/pkgs/foo/utility. If there are multiple chains that lead to the same dependency, only the first chain is shown here. To see all chains use debug output option. To resolve the conflict, coordinate with the maintainer of the package that introduces the conflicting dependency.\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDuplicateNestedTransitiveIdentityWithoutNames() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooUtilityProduct\", package: \"FooUtilityPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(path: \"foo/utility\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooUtilityPackage\",\n                    path: \"foo/utility\",\n                    targets: [\n                        MockTarget(name: \"FooUtilityTarget\", dependencies: [\n                            .product(name: \"BarProduct\", package: \"BarPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooUtilityProduct\", modules: [\"FooUtilityTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"],\n                    toolsVersion: .v5\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"OtherUtilityProduct\", package: \"OtherUtilityPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(path: \"other/utility\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"],\n                    toolsVersion: .v5\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"OtherUtilityPackage\",\n                    path: \"other/utility\",\n                    targets: [\n                        MockTarget(name: \"OtherUtilityTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"OtherUtilityProduct\", modules: [\"OtherUtilityTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                // FIXME: rdar://72940946\n                // we need to improve this situation or diagnostics when working on identity\n                result.check(\n                    diagnostic: \"cyclic dependency between packages Root -> FooUtilityPackage -> BarPackage -> FooUtilityPackage requires tools-version 6.0 or later\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testRootPathConflictsWithTransitiveIdentity() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"BarProduct\", package: \"BarPackage\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"BarPackage\",\n                            path: \"bar\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    toolsVersion: .v6_0\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"BarPackage\",\n                    path: \"bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"FooPackage\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControlWithDeprecatedName(\n                            name: \"FooPackage\",\n                            path: \"foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                // this package never gets loaded since its identity is the same as \"FooPackage\"\n                MockPackage(\n                    name: \"FooPackage\",\n                    path: \"foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"foo\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                // FIXME: rdar://72940946\n                // we need to improve this situation or diagnostics when working on identity\n                result.check(\n                    diagnostic: \"product 'FooProduct' required by package 'bar' target 'BarTarget' not found in package 'FooPackage'.\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testDeterministicURLPreference() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                            .product(name: \"BazProduct\", package: \"baz\"),\n                            .product(name: \"QuxProduct\", package: \"qux\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/bar.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/baz.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/qux.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"https://github.com/org/bar.git\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"http://github.com/org/foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"http://github.com/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    url: \"https://github.com/org/baz.git\",\n                    targets: [\n                        MockTarget(name: \"BazTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"git@github.com:org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"git@github.com:org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"QuxPackage\",\n                    url: \"https://github.com/org/qux.git\",\n                    targets: [\n                        MockTarget(name: \"QuxTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"QuxProduct\", modules: [\"QuxTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"bar\", \"baz\", \"foo\", \"Root\", \"qux\")\n                let package = result.find(package: \"foo\")\n                XCTAssertEqual(package?.manifest.packageLocation, \"https://github.com/org/foo.git\")\n            }\n            testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                result.checkUnordered(\n                    diagnostic: \"similar variants of package 'foo' found at 'git@github.com:org/foo.git' and 'https://github.com/org/foo.git'. using preferred variant 'https://github.com/org/foo.git'\",\n                    severity: .debug\n                )\n                result.checkUnordered(\n                    diagnostic: \"similar variants of package 'foo' found at 'http://github.com/org/foo' and 'https://github.com/org/foo.git'. using preferred variant 'https://github.com/org/foo.git'\",\n                    severity: .debug\n                )\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            XCTAssertEqual(\n                result.managedDependencies[\"foo\"]?.packageRef.locationString,\n                \"https://github.com/org/foo.git\"\n            )\n        }\n\n        workspace.checkResolved { result in\n            XCTAssertEqual(\n                result.store.resolvedPackages[\"foo\"]?.packageRef.locationString,\n                \"https://github.com/org/foo.git\"\n            )\n        }\n    }\n\n    func testDeterministicURLPreferenceWithRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                            .product(name: \"BazProduct\", package: \"baz\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"git@github.com:org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/bar.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/baz.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"git@github.com:org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"https://github.com/org/bar.git\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"http://github.com/org/foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"http://github.com/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    url: \"https://github.com/org/baz.git\",\n                    targets: [\n                        MockTarget(name: \"BazTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"bar\", \"baz\", \"foo\", \"Root\")\n                let package = result.find(package: \"foo\")\n                XCTAssertEqual(package?.manifest.packageLocation, \"git@github.com:org/foo.git\")\n            }\n            testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                result.checkUnordered(\n                    diagnostic: \"similar variants of package 'foo' found at 'https://github.com/org/foo.git' and 'git@github.com:org/foo.git'. using preferred root variant 'git@github.com:org/foo.git'\",\n                    severity: .debug\n                )\n                result.checkUnordered(\n                    diagnostic: \"similar variants of package 'foo' found at 'http://github.com/org/foo' and 'git@github.com:org/foo.git'. using preferred root variant 'git@github.com:org/foo.git'\",\n                    severity: .debug\n                )\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            XCTAssertEqual(result.managedDependencies[\"foo\"]?.packageRef.locationString, \"git@github.com:org/foo.git\")\n        }\n\n        workspace.checkResolved { result in\n            XCTAssertEqual(\n                result.store.resolvedPackages[\"foo\"]?.packageRef.locationString,\n                \"git@github.com:org/foo.git\"\n            )\n        }\n    }\n\n    func testCanonicalURLWithPreviousManagedState() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/bar.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Root2\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                            .product(name: \"BazProduct\", package: \"baz\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/bar.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/baz.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"],\n                    revisionProvider: { _ in \"foo\" } // we need this to be consistent for fingerprints check to work\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"git@github.com:org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"],\n                    revisionProvider: { _ in \"foo\" } // we need this to be consistent for fingerprints check to work\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"https://github.com/org/bar.git\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"git@github.com:org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"],\n                    revisionProvider: { _ in \"bar\" } // we need this to be consistent for fingerprints check to work\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    url: \"https://github.com/org/baz.git\",\n                    targets: [\n                        MockTarget(name: \"BazTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"],\n                    revisionProvider: { _ in \"baz\" } // we need this to be consistent for fingerprints check to work\n                ),\n            ]\n        )\n\n        // resolve to set previous state\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"bar\", \"foo\", \"Root\")\n                let package = result.find(package: \"foo\")\n                XCTAssertEqual(package?.manifest.packageLocation, \"git@github.com:org/foo.git\")\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            XCTAssertEqual(result.managedDependencies[\"foo\"]?.packageRef.locationString, \"git@github.com:org/foo.git\")\n        }\n\n        workspace.checkResolved { result in\n            XCTAssertEqual(\n                result.store.resolvedPackages[\"foo\"]?.packageRef.locationString,\n                \"git@github.com:org/foo.git\"\n            )\n        }\n\n        // update to a different url via transitive dependencies\n\n        try await workspace.checkPackageGraph(roots: [\"Root2\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"bar\", \"baz\", \"foo\", \"Root2\")\n                let package = result.find(package: \"foo\")\n                XCTAssertEqual(package?.manifest.packageLocation, \"git@github.com:org/foo.git\")\n            }\n            testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                result.checkUnordered(\n                    diagnostic: \"required dependency 'foo' from 'https://github.com/org/foo' was not found in managed dependencies, using alternative location 'git@github.com:org/foo.git' instead\",\n                    severity: .info\n                )\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            // we expect the managed dependency to carry the old state\n            XCTAssertEqual(result.managedDependencies[\"foo\"]?.packageRef.locationString, \"git@github.com:org/foo.git\")\n        }\n\n        workspace.checkResolved { result in\n            XCTAssertEqual(\n                result.store.resolvedPackages[\"foo\"]?.packageRef.locationString,\n                \"https://github.com/org/foo\"\n            )\n        }\n    }\n\n    func testCanonicalURLChanges() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Root2\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"git@github.com:org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    revisionProvider: { _ in \"foo\" } // we need this to be consistent for fingerprints check to work\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"git@github.com:org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    revisionProvider: { _ in \"foo\" } // we need this to be consistent for fingerprints check to work\n                ),\n            ]\n        )\n\n        // check usage of canonical URL\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"foo\", \"Root\")\n                let package = result.find(package: \"foo\")\n                XCTAssertEqual(package?.manifest.packageLocation, \"https://github.com/org/foo.git\")\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            XCTAssertEqual(\n                result.managedDependencies[\"foo\"]?.packageRef.locationString,\n                \"https://github.com/org/foo.git\"\n            )\n        }\n\n        workspace.checkResolved { result in\n            XCTAssertEqual(\n                result.store.resolvedPackages[\"foo\"]?.packageRef.locationString,\n                \"https://github.com/org/foo.git\"\n            )\n        }\n\n        // update URL to one with different scheme\n\n        try await workspace.checkPackageGraph(roots: [\"Root2\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"foo\", \"Root2\")\n                let package = result.find(package: \"foo\")\n                XCTAssertEqual(package?.manifest.packageLocation, \"git@github.com:org/foo.git\")\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            XCTAssertEqual(result.managedDependencies[\"foo\"]?.packageRef.locationString, \"git@github.com:org/foo.git\")\n        }\n\n        workspace.checkResolved { result in\n            XCTAssertEqual(\n                result.store.resolvedPackages[\"foo\"]?.packageRef.locationString,\n                \"git@github.com:org/foo.git\"\n            )\n        }\n    }\n\n    func testCanonicalURLChangesWithTransitiveDependencies() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"https://github.com/org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/bar.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Root2\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"git@github.com:org/foo.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .sourceControl(\n                            url: \"https://github.com/org/bar.git\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://github.com/org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    revisionProvider: { _ in \"foo\" } // we need this to be consistent for fingerprints check to work\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"https://github.com/org/bar.git\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"http://github.com/org/foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"http://github.com/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    revisionProvider: { _ in \"foo\" } // we need this to be consistent for fingerprints check to work\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"git@github.com:org/foo.git\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"],\n                    revisionProvider: { _ in \"foo\" } // we need this to be consistent for fingerprints check to work\n                ),\n            ]\n        )\n\n        // check usage of canonical URL\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"bar\", \"foo\", \"Root\")\n                let package = result.find(package: \"foo\")\n                XCTAssertEqual(package?.manifest.packageLocation, \"https://github.com/org/foo.git\")\n            }\n            testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                result.checkUnordered(\n                    diagnostic: \"similar variants of package 'foo' found at 'http://github.com/org/foo' and 'https://github.com/org/foo.git'. using preferred root variant 'https://github.com/org/foo.git'\",\n                    severity: .debug\n                )\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            XCTAssertEqual(\n                result.managedDependencies[\"foo\"]?.packageRef.locationString,\n                \"https://github.com/org/foo.git\"\n            )\n        }\n\n        workspace.checkResolved { result in\n            XCTAssertEqual(\n                result.store.resolvedPackages[\"foo\"]?.packageRef.locationString,\n                \"https://github.com/org/foo.git\"\n            )\n        }\n\n        // update URL to one with different scheme\n\n        try await workspace.checkPackageGraph(roots: [\"Root2\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(packages: \"bar\", \"foo\", \"Root2\")\n                let package = result.find(package: \"foo\")\n                XCTAssertEqual(package?.manifest.packageLocation, \"git@github.com:org/foo.git\")\n            }\n            testPartialDiagnostics(diagnostics, minSeverity: .debug) { result in\n                result.checkUnordered(\n                    diagnostic: \"similar variants of package 'foo' found at 'http://github.com/org/foo' and 'git@github.com:org/foo.git'. using preferred root variant 'git@github.com:org/foo.git'\",\n                    severity: .debug\n                )\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            XCTAssertEqual(result.managedDependencies[\"foo\"]?.packageRef.locationString, \"git@github.com:org/foo.git\")\n        }\n\n        workspace.checkResolved { result in\n            XCTAssertEqual(\n                result.store.resolvedPackages[\"foo\"]?.packageRef.locationString,\n                \"git@github.com:org/foo.git\"\n            )\n        }\n    }\n\n    func testCycleRoot() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root1\",\n                    targets: [\n                        .init(name: \"Root1Target\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"Root2Product\", package: \"Root2\"),\n                        ]),\n                    ],\n                    products: [\n                        .init(name: \"Root1Product\", modules: [\"Root1Target\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"http://scm.com/org/foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                        .fileSystem(path: \"Root2\"),\n                    ]\n                ),\n                MockPackage(\n                    name: \"Root2\",\n                    targets: [\n                        .init(name: \"Root2Target\", dependencies: [\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [\n                        .init(name: \"Root2Product\", modules: [\"Root2Target\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"http://scm.com/org/bar\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"http://scm.com/org/foo\",\n                    targets: [\n                        .init(name: \"FooTarget\", dependencies: [\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [\n                        .init(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"http://scm.com/org/bar\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"http://scm.com/org/bar\",\n                    targets: [\n                        .init(name: \"BarTarget\", dependencies: [\n                            .product(name: \"BazProduct\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [\n                        .init(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"http://scm.com/org/baz\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    url: \"http://scm.com/org/baz\",\n                    targets: [\n                        .init(name: \"BazTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        .init(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(\n                            url: \"http://scm.com/org/foo\",\n                            requirement: .upToNextMajor(from: \"1.0.0\")\n                        ),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root1\", \"Root2\"]) { _, diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .regex(\"cyclic dependency declaration found: Root[1|2]Target -> *\"),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testResolutionBranchAndVersion() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"http://localhost/org/foo\", requirement: .branch(\"experiment\")),\n                        .sourceControl(url: \"http://localhost/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"http://localhost/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"experiment\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"http://localhost/org/bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"http://localhost/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"Root\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"bar\", \"foo\", \"Root\")\n                result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                result.checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.branch(\"experiment\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"1.0.0\")))\n        }\n    }\n\n    func testBinaryArtifactsInvalidPath() async throws {\n        try await testWithTemporaryDirectory { path in\n            let fs = localFileSystem\n            let observability = ObservabilitySystem.makeForTesting()\n\n            let foo = path.appending(\"foo\")\n            try fs.writeFileContents(\n                foo.appending(\"Package.swift\"),\n                string: \"\"\"\n                // swift-tools-version:5.3\n                import PackageDescription\n                let package = Package(\n                    name: \"Best\",\n                    targets: [\n                        .binaryTarget(name: \"best\", path: \"/best.xcframework\")\n                    ]\n                )\n                \"\"\"\n            )\n\n            let manifestLoader = try ManifestLoader(toolchain: UserToolchain.default)\n            let sandbox = path.appending(\"ws\")\n            let workspace = try Workspace(\n                fileSystem: fs,\n                forRootPackage: sandbox,\n                customManifestLoader: manifestLoader,\n                delegate: MockWorkspaceDelegate()\n            )\n\n            try await workspace.resolve(root: .init(packages: [foo]), observabilityScope: observability.topScope)\n            testDiagnostics(observability.diagnostics) { result in\n                result.check(\n                    diagnostic: \"invalid local path '/best.xcframework' for binary target 'best', path expected to be relative to package root.\",\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testManifestLoaderDiagnostics() async throws {\n        struct TestLoader: ManifestLoaderProtocol {\n            let error: Error?\n\n            init(error: Error?) {\n                self.error = error\n            }\n\n            func load(\n                manifestPath: AbsolutePath,\n                manifestToolsVersion: ToolsVersion,\n                packageIdentity: PackageIdentity,\n                packageKind: PackageReference.Kind,\n                packageLocation: String,\n                packageVersion: (version: Version?, revision: String?)?,\n                identityResolver: IdentityResolver,\n                dependencyMapper: DependencyMapper,\n                fileSystem: FileSystem,\n                observabilityScope: ObservabilityScope,\n                delegateQueue: DispatchQueue\n            ) async throws -> Manifest {\n                if let error {\n                    throw error\n                } else {\n                    return Manifest.createManifest(\n                        displayName: packageIdentity.description,\n                        path: manifestPath,\n                        packageKind: packageKind,\n                        packageIdentity: packageIdentity,\n                        packageLocation: packageLocation,\n                        platforms: [],\n                        toolsVersion: manifestToolsVersion\n                    )\n                }\n            }\n\n            func resetCache(observabilityScope: ObservabilityScope) {}\n            func purgeCache(observabilityScope: ObservabilityScope) {}\n        }\n\n        let fs = InMemoryFileSystem()\n        try fs.createMockToolchain()\n        let observability = ObservabilitySystem.makeForTesting()\n\n        // write a manifest\n        try fs.writeFileContents(.root.appending(component: Manifest.filename), bytes: \"\")\n        try ToolsVersionSpecificationWriter.rewriteSpecification(\n            manifestDirectory: .root,\n            toolsVersion: .current,\n            fileSystem: fs\n        )\n\n        let customHostToolchain = try UserToolchain.mockHostToolchain(fs)\n\n        do {\n            // no error\n            let delegate = MockWorkspaceDelegate()\n            let workspace = try Workspace(\n                fileSystem: fs,\n                environment: .mockEnvironment,\n                forRootPackage: .root,\n                customHostToolchain: customHostToolchain,\n                customManifestLoader: TestLoader(error: .none),\n                delegate: delegate\n            )\n            try await workspace.loadPackageGraph(rootPath: .root, observabilityScope: observability.topScope)\n\n            XCTAssertNotNil(delegate.manifest)\n            XCTAssertNoDiagnostics(observability.diagnostics)\n            XCTAssertNoDiagnostics(delegate.manifestLoadingDiagnostics ?? [])\n        }\n\n        do {\n            // actual error\n            let delegate = MockWorkspaceDelegate()\n            let workspace = try Workspace(\n                fileSystem: fs,\n                environment: .mockEnvironment,\n                forRootPackage: .root,\n                customHostToolchain: customHostToolchain,\n                customManifestLoader: TestLoader(error: StringError(\"boom\")),\n                delegate: delegate\n            )\n            try await workspace.loadPackageGraph(rootPath: .root, observabilityScope: observability.topScope)\n\n            XCTAssertNil(delegate.manifest)\n            testDiagnostics(delegate.manifestLoadingDiagnostics ?? []) { result in\n                result.check(diagnostic: .equal(\"boom\"), severity: .error)\n            }\n            testDiagnostics(delegate.manifestLoadingDiagnostics ?? []) { result in\n                result.check(diagnostic: .equal(\"boom\"), severity: .error)\n            }\n        }\n    }\n\n    func testBasicResolutionFromSourceControl() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget1\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"foo\"),\n                            ]\n                        ),\n                        MockTarget(\n                            name: \"MyTarget2\",\n                            dependencies: [\n                                .product(name: \"Bar\", package: \"bar\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"MyProduct\", modules: [\"MyTarget1\", \"MyTarget2\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"http://localhost/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"http://localhost/org/bar\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"http://localhost/org/foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\", \"1.3.0\", \"1.4.0\", \"1.5.0\", \"1.5.1\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"http://localhost/org/bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"2.0.0\", \"2.1.0\", \"2.2.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"MyPackage\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"MyPackage\")\n                result.check(packages: \"Bar\", \"Foo\", \"MyPackage\")\n                result.check(modules: \"Foo\", \"Bar\", \"MyTarget1\", \"MyTarget2\")\n                result.checkTarget(\"MyTarget1\") { result in result.check(dependencies: \"Foo\") }\n                result.checkTarget(\"MyTarget2\") { result in result.check(dependencies: \"Bar\") }\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.5.1\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"2.2.0\")))\n        }\n\n        // Check the load-package callbacks.\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"will load manifest for root package: \\(sandbox.appending(components: \"roots\", \"MyPackage\")) (identity: mypackage)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"did load manifest for root package: \\(sandbox.appending(components: \"roots\", \"MyPackage\")) (identity: mypackage)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for remoteSourceControl package: http://localhost/org/foo (identity: foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for remoteSourceControl package: http://localhost/org/foo (identity: foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for remoteSourceControl package: http://localhost/org/bar (identity: bar)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for remoteSourceControl package: http://localhost/org/bar (identity: bar)\"]\n        )\n    }\n\n    func testBasicTransitiveResolutionFromSourceControl() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget1\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"foo\"),\n                            ]\n                        ),\n                        MockTarget(\n                            name: \"MyTarget2\",\n                            dependencies: [\n                                .product(name: \"Bar\", package: \"bar\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"MyProduct\", modules: [\"MyTarget1\", \"MyTarget2\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"http://localhost/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"http://localhost/org/bar\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    url: \"http://localhost/org/foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            dependencies: [\n                                .product(name: \"Baz\", package: \"baz\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"http://localhost/org/baz\", requirement: .range(\"2.0.0\" ..< \"4.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    url: \"http://localhost/org/bar\",\n                    targets: [\n                        MockTarget(\n                            name: \"Bar\",\n                            dependencies: [\n                                .product(name: \"Baz\", package: \"baz\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"http://localhost/org/baz\", requirement: .upToNextMajor(from: \"3.0.0\")),\n                    ],\n                    versions: [\"2.0.0\", \"2.1.0\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    url: \"http://localhost/org/baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"2.0.0\", \"2.1.0\", \"3.0.0\", \"3.1.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"MyPackage\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"MyPackage\")\n                result.check(packages: \"Bar\", \"Baz\", \"Foo\", \"MyPackage\")\n                result.check(modules: \"Foo\", \"Bar\", \"Baz\", \"MyTarget1\", \"MyTarget2\")\n                result.checkTarget(\"MyTarget1\") { result in result.check(dependencies: \"Foo\") }\n                result.checkTarget(\"MyTarget2\") { result in result.check(dependencies: \"Bar\") }\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"foo\", at: .checkout(.version(\"1.1.0\")))\n            result.check(dependency: \"bar\", at: .checkout(.version(\"2.1.0\")))\n            result.check(dependency: \"baz\", at: .checkout(.version(\"3.1.0\")))\n        }\n\n        // Check the load-package callbacks.\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"will load manifest for root package: \\(sandbox.appending(components: \"roots\", \"MyPackage\")) (identity: mypackage)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"did load manifest for root package: \\(sandbox.appending(components: \"roots\", \"MyPackage\")) (identity: mypackage)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for remoteSourceControl package: http://localhost/org/foo (identity: foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for remoteSourceControl package: http://localhost/org/foo (identity: foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for remoteSourceControl package: http://localhost/org/bar (identity: bar)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for remoteSourceControl package: http://localhost/org/bar (identity: bar)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for remoteSourceControl package: http://localhost/org/baz (identity: baz)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for remoteSourceControl package: http://localhost/org/baz (identity: baz)\"]\n        )\n    }\n\n    func testBasicResolutionFromRegistry() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget1\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                        MockTarget(\n                            name: \"MyTarget2\",\n                            dependencies: [\n                                .product(name: \"Bar\", package: \"org.bar\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"MyProduct\", modules: [\"MyTarget1\", \"MyTarget2\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\", \"1.3.0\", \"1.4.0\", \"1.5.0\", \"1.5.1\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"2.0.0\", \"2.1.0\", \"2.2.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"MyPackage\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"MyPackage\")\n                result.check(packages: \"org.bar\", \"org.foo\", \"mypackage\")\n                result.check(modules: \"Foo\", \"Bar\", \"MyTarget1\", \"MyTarget2\")\n                result.checkTarget(\"MyTarget1\") { result in result.check(dependencies: \"Foo\") }\n                result.checkTarget(\"MyTarget2\") { result in result.check(dependencies: \"Bar\") }\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"org.foo\", at: .registryDownload(\"1.5.1\"))\n            result.check(dependency: \"org.bar\", at: .registryDownload(\"2.2.0\"))\n        }\n\n        // Check the load-package callbacks.\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"will load manifest for root package: \\(sandbox.appending(components: \"roots\", \"MyPackage\")) (identity: mypackage)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"did load manifest for root package: \\(sandbox.appending(components: \"roots\", \"MyPackage\")) (identity: mypackage)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for registry package: org.foo (identity: org.foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for registry package: org.foo (identity: org.foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for registry package: org.bar (identity: org.bar)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for registry package: org.bar (identity: org.bar)\"]\n        )\n    }\n\n    func testBasicTransitiveResolutionFromRegistry() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget1\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                        MockTarget(\n                            name: \"MyTarget2\",\n                            dependencies: [\n                                .product(name: \"Bar\", package: \"org.bar\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"MyProduct\", modules: [\"MyTarget1\", \"MyTarget2\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(\n                            name: \"Foo\",\n                            dependencies: [\n                                .product(name: \"Baz\", package: \"org.baz\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.baz\", requirement: .range(\"2.0.0\" ..< \"4.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(\n                            name: \"Bar\",\n                            dependencies: [\n                                .product(name: \"Baz\", package: \"org.baz\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.baz\", requirement: .upToNextMajor(from: \"3.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"2.0.0\", \"2.1.0\"]\n                ),\n                MockPackage(\n                    name: \"Baz\",\n                    identity: \"org.baz\",\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"2.0.0\", \"2.1.0\", \"3.0.0\", \"3.1.0\"]\n                ),\n            ]\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"MyPackage\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"MyPackage\")\n                result.check(packages: \"org.bar\", \"org.baz\", \"org.foo\", \"mypackage\")\n                result.check(modules: \"Foo\", \"Bar\", \"Baz\", \"MyTarget1\", \"MyTarget2\")\n                result.checkTarget(\"MyTarget1\") { result in result.check(dependencies: \"Foo\") }\n                result.checkTarget(\"MyTarget2\") { result in result.check(dependencies: \"Bar\") }\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Baz\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"org.foo\", at: .registryDownload(\"1.1.0\"))\n            result.check(dependency: \"org.bar\", at: .registryDownload(\"2.1.0\"))\n            result.check(dependency: \"org.baz\", at: .registryDownload(\"3.1.0\"))\n        }\n\n        // Check the load-package callbacks.\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"will load manifest for root package: \\(sandbox.appending(components: \"roots\", \"MyPackage\")) (identity: mypackage)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\n                \"did load manifest for root package: \\(sandbox.appending(components: \"roots\", \"MyPackage\")) (identity: mypackage)\",\n            ]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for registry package: org.foo (identity: org.foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for registry package: org.foo (identity: org.foo)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for registry package: org.bar (identity: org.bar)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for registry package: org.bar (identity: org.bar)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"will load manifest for registry package: org.baz (identity: org.baz)\"]\n        )\n        XCTAssertMatch(\n            workspace.delegate.events,\n            [\"did load manifest for registry package: org.baz (identity: org.baz)\"]\n        )\n    }\n\n    func testTransitiveResolutionFromRegistryWithByNameDependencies() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Bar\",\n                    identity: \"org.bar\",\n                    alternativeURLs: [\"https://git/org/Bar\"],\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\", dependencies: [\n                            \"Bar\",\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/Bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n            ]\n        )\n\n        workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n        try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                result.checkTarget(\"RootTarget\") { result in\n                    result.check(dependencies: \"FooProduct\")\n                }\n                result.checkTarget(\"FooTarget\") { result in\n                    result.check(dependencies: \"Bar\")\n                }\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"org.foo\", at: .registryDownload(\"1.2.0\"))\n            result.check(dependency: \"org.bar\", at: .registryDownload(\"1.1.0\"))\n        }\n    }\n\n    // no dups\n    func testResolutionMixedRegistryAndSourceControl1() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"org.bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://git/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"foo\", at: .checkout(.version(\"1.2.0\")))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .checkout(.version(\"1.2.0\")))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .registryDownload(\"1.2.0\"))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n    }\n\n    func testTransitiveResolutionFromRegistryWithDifferentPackageNameCasing() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"Foo\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n            ]\n        )\n\n        workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n        try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Root\")\n                result.check(packages: \"org.foo\", \"Root\")\n                result.check(modules: \"FooTarget\", \"RootTarget\")\n                result.checkTarget(\"RootTarget\") { result in\n                    result.check(dependencies: \"FooProduct\")\n                }\n                result.checkTarget(\"FooTarget\") { result in\n                    result.check(dependencies: [])\n                }\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"org.foo\", at: .registryDownload(\"1.2.0\"))\n        }\n    }\n\n    // duplicate package at root level\n    func testResolutionMixedRegistryAndSourceControl2() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://git/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n\n            await XCTAssertAsyncThrowsError(try await workspace.checkPackageGraph(roots: [\"root\"]) { _, _ in\n            }) { error in\n                XCTAssertEqual(\n                    (error as? PackageGraphError)?.description,\n                    \"multiple packages (\\'foo\\' (from \\'https://git/org/foo\\'), \\'org.foo\\') declare products with a conflicting name: \\'FooProduct’; product names need to be unique across the package graph\"\n                )\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: \"Conflicting identity for org.foo: dependency 'org.foo' and dependency 'git/org/foo' both point to the same package identity 'org.foo'.\",\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            // TODO: this error message should be improved\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: \"Conflicting identity for org.foo: dependency 'org.foo' and dependency 'org.foo' both point to the same package identity 'org.foo'.\",\n                        severity: .error\n                    )\n                }\n            }\n        }\n    }\n\n    // mixed graph root --> dep1 scm\n    //                  --> dep2 scm --> dep1 registry\n    func testResolutionMixedRegistryAndSourceControl3() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"https://git/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://git/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"2.0.0\", \"2.1.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"https://git/org/bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"org.foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"2.0.0\", \"2.1.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"2.0.0\", \"2.1.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        multiple similar targets 'FooTarget' appear in registry package 'org.foo' and source control package 'foo'\n                        \"\"\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        dependency 'org.foo' and dependency 'git/org/foo' both point to the same package identity 'org.foo'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->git/org/bar->org.foo (B) \\(tmpDirCanonicalPackageLocation)/roots/root->git/org/foo.\n                        \"\"\"),\n                        severity: .warning\n                    )\n                }\n\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .checkout(.version(\"1.1.0\")))\n                result.check(dependency: \"bar\", at: .checkout(.version(\"1.1.0\")))\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .registryDownload(\"1.1.0\"))\n                result.check(dependency: \"bar\", at: .checkout(.version(\"1.1.0\")))\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .registryDownload(\"1.1.0\"))\n                result.check(dependency: \"bar\", at: .checkout(.version(\"1.1.0\")))\n            }\n        }\n    }\n\n    // mixed graph root --> dep1 scm\n    //                  --> dep2 registry --> dep1 registry\n    func testResolutionMixedRegistryAndSourceControl4() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"org.bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"1.1.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://git/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"org.foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.2.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        multiple similar targets 'FooTarget' appear in registry package 'org.foo' and source control package 'foo'\n                        \"\"\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        dependency 'org.foo' and dependency 'git/org/foo' both point to the same package identity 'org.foo'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->org.bar->org.foo (B) \\(tmpDirCanonicalPackageLocation)/roots/root->git/org/foo.\n                        \"\"\"),\n                        severity: .warning\n                    )\n                }\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .checkout(.version(\"1.2.0\")))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .registryDownload(\"1.2.0\"))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n    }\n\n    // mixed graph root --> dep1 scm\n    //                  --> dep2 scm --> dep1 registry incompatible version\n    func testResolutionMixedRegistryAndSourceControl5() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .sourceControl(url: \"https://git/org/bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://git/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    url: \"https://git/org/bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"org.foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        multiple similar targets 'FooTarget' appear in registry package 'org.foo' and source control package 'foo'\n                        \"\"\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic:\n                        \"\"\"\n                        Dependencies could not be resolved because root depends on 'org.foo' 1.0.0..<2.0.0 and root depends on 'bar' 1.0.0..<2.0.0.\n                        'bar' >= 1.0.0 practically depends on 'org.foo' 2.0.0..<3.0.0 because no versions of 'bar' match the requirement 1.0.1..<2.0.0 and 'bar' 1.0.0 depends on 'org.foo' 2.0.0..<3.0.0.\n                        \"\"\",\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic:\n                        \"\"\"\n                        Dependencies could not be resolved because root depends on 'org.foo' 1.0.0..<2.0.0 and root depends on 'bar' 1.0.0..<2.0.0.\n                        'bar' >= 1.0.0 practically depends on 'org.foo' 2.0.0..<3.0.0 because no versions of 'bar' match the requirement 1.0.1..<2.0.0 and 'bar' 1.0.0 depends on 'org.foo' 2.0.0..<3.0.0.\n                        \"\"\",\n                        severity: .error\n                    )\n                }\n            }\n        }\n    }\n\n    // mixed graph root --> dep1 registry\n    //                  --> dep2 registry --> dep1 scm\n    func testResolutionMixedRegistryAndSourceControl6() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"org.foo\"),\n                            .product(name: \"BarProduct\", package: \"org.bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.1.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"1.2.0\")),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://git/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        multiple similar targets 'FooTarget' appear in registry package 'org.foo' and source control package 'foo'\n                        \"\"\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        dependency 'git/org/foo' and dependency 'org.foo' both point to the same package identity 'org.foo'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->org.bar->git/org/foo (B) \\(tmpDirCanonicalPackageLocation)/roots/root->org.foo.\n                        \"\"\"),\n                        severity: .warning\n                    )\n                    if ToolsVersion.current >= .v5_8 {\n                        result.check(\n                            diagnostic: .contains(\"\"\"\n                            product 'FooProduct' required by package 'org.bar' target 'BarTarget' not found in package 'foo'.\n                            \"\"\"),\n                            severity: .error\n                        )\n                    }\n                }\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .registryDownload(\"1.2.0\"))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .registryDownload(\"1.2.0\"))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n    }\n\n    // mixed graph root --> dep1 registry\n    //                  --> dep2 registry --> dep1 scm incompatible version\n    func testResolutionMixedRegistryAndSourceControl7() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"org.foo\"),\n                            .product(name: \"BarProduct\", package: \"org.bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://git/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        multiple similar targets 'FooTarget' appear in registry package 'org.foo' and source control package 'foo'\n                        \"\"\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic:\n                        \"\"\"\n                        Dependencies could not be resolved because root depends on 'org.foo' 1.0.0..<2.0.0 and root depends on 'org.bar' 1.0.0..<2.0.0.\n                        'org.bar' >= 1.0.0 practically depends on 'org.foo' 2.0.0..<3.0.0 because no versions of 'org.bar' match the requirement 1.0.1..<2.0.0 and 'org.bar' 1.0.0 depends on 'org.foo' 2.0.0..<3.0.0.\n                        \"\"\",\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic:\n                        \"\"\"\n                        Dependencies could not be resolved because root depends on 'org.foo' 1.0.0..<2.0.0 and root depends on 'org.bar' 1.0.0..<2.0.0.\n                        'org.bar' >= 1.0.0 practically depends on 'org.foo' 2.0.0..<3.0.0 because no versions of 'org.bar' match the requirement 1.0.1..<2.0.0 and 'org.bar' 1.0.0 depends on 'org.foo' 2.0.0..<3.0.0.\n                        \"\"\",\n                        severity: .error\n                    )\n                }\n            }\n        }\n    }\n\n    // mixed graph root --> dep1 registry --> dep3 scm\n    //                  --> dep2 registry --> dep3 registry\n    func testResolutionMixedRegistryAndSourceControl8() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"org.foo\"),\n                            .product(name: \"BarProduct\", package: \"org.bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\", dependencies: [\n                            .product(name: \"BazProduct\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/baz\", requirement: .upToNextMajor(from: \"1.1.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"BazProduct\", package: \"org.baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    url: \"https://git/org/baz\",\n                    targets: [\n                        MockTarget(name: \"BazTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"]\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    identity: \"org.baz\",\n                    alternativeURLs: [\"https://git/org/baz\"],\n                    targets: [\n                        MockTarget(name: \"BazTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        multiple similar targets 'BazTarget' appear in registry package 'org.baz' and source control package 'baz'\n                        \"\"\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        dependency 'git/org/baz' and dependency 'org.baz' both point to the same package identity 'org.baz'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->org.foo->git/org/baz (B) \\(tmpDirCanonicalPackageLocation)/roots/root->org.bar->org.baz.\n                        \"\"\"),\n                        severity: .warning\n                    )\n                    if ToolsVersion.current >= .v5_8 {\n                        result.check(\n                            diagnostic: .contains(\"\"\"\n                            product 'BazProduct' required by package 'org.foo' target 'FooTarget' not found in package 'baz'.\n                            \"\"\"),\n                            severity: .error\n                        )\n                    }\n                }\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.baz\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"BazTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                    if ToolsVersion.current < .v5_8 {\n                        result.checkTarget(\"FooTarget\") { result in result.check(dependencies: \"BazProduct\") }\n                    }\n                    result.checkTarget(\"BarTarget\") { result in result.check(dependencies: \"BazProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .registryDownload(\"1.0.0\"))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.0.0\"))\n                result.check(dependency: \"org.baz\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                XCTAssertNoDiagnostics(diagnostics)\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.baz\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"BazTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                    result.checkTarget(\"FooTarget\") { result in result.check(dependencies: \"BazProduct\") }\n                    result.checkTarget(\"BarTarget\") { result in result.check(dependencies: \"BazProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .registryDownload(\"1.0.0\"))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.0.0\"))\n                result.check(dependency: \"org.baz\", at: .registryDownload(\"1.1.0\"))\n            }\n        }\n    }\n\n    // mixed graph root --> dep1 registry --> dep3 scm\n    //                  --> dep2 registry --> dep3 registry incompatible version\n    func testResolutionMixedRegistryAndSourceControl9() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"org.foo\"),\n                            .product(name: \"BarProduct\", package: \"org.bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\", dependencies: [\n                            .product(name: \"BazProduct\", package: \"baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/baz\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"BazProduct\", package: \"org.baz\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.baz\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    url: \"https://git/org/baz\",\n                    targets: [\n                        MockTarget(name: \"BazTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"BazPackage\",\n                    identity: \"org.baz\",\n                    alternativeURLs: [\"https://git/org/baz\"],\n                    targets: [\n                        MockTarget(name: \"BazTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"BazProduct\", modules: [\"BazTarget\"]),\n                    ],\n                    versions: [\"1.0.0\", \"2.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        multiple similar targets 'BazTarget' appear in registry package 'org.baz' and source control package 'baz'\n                        \"\"\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: \"\"\"\n                        Dependencies could not be resolved because root depends on 'org.foo' 1.0.0..<2.0.0 and root depends on 'org.bar' 1.0.0..<2.0.0.\n                        'org.bar' is incompatible with 'org.foo' because 'org.foo' 1.0.0 depends on 'org.baz' 1.0.0..<2.0.0 and no versions of 'org.foo' match the requirement 1.0.1..<2.0.0.\n                        'org.bar' >= 1.0.0 practically depends on 'org.baz' 2.0.0..<3.0.0 because no versions of 'org.bar' match the requirement 1.0.1..<2.0.0 and 'org.bar' 1.0.0 depends on 'org.baz' 2.0.0..<3.0.0.\n                        \"\"\",\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: \"\"\"\n                        Dependencies could not be resolved because root depends on 'org.foo' 1.0.0..<2.0.0 and root depends on 'org.bar' 1.0.0..<2.0.0.\n                        'org.bar' is incompatible with 'org.foo' because 'org.foo' 1.0.0 depends on 'org.baz' 1.0.0..<2.0.0 and no versions of 'org.foo' match the requirement 1.0.1..<2.0.0.\n                        'org.bar' >= 1.0.0 practically depends on 'org.baz' 2.0.0..<3.0.0 because no versions of 'org.bar' match the requirement 1.0.1..<2.0.0 and 'org.bar' 1.0.0 depends on 'org.baz' 2.0.0..<3.0.0.\n                        \"\"\",\n                        severity: .error\n                    )\n                }\n            }\n        }\n    }\n\n    // mixed graph root --> dep1 scm branch\n    //                  --> dep2 registry --> dep1 registry\n    func testResolutionMixedRegistryAndSourceControl10() async throws {\n        let sandbox: AbsolutePath = AbsolutePath(\"/tmp/ws/\")\n        let tmpDirCanonicalPackageLocation = CanonicalPackageLocation(sandbox.pathString)\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Root\",\n                    path: \"root\",\n                    targets: [\n                        MockTarget(name: \"RootTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"foo\"),\n                            .product(name: \"BarProduct\", package: \"org.bar\"),\n                        ]),\n                    ],\n                    products: [],\n                    dependencies: [\n                        .sourceControl(url: \"https://git/org/foo\", requirement: .branch(\"experiment\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    toolsVersion: .v5_6\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"FooPackage\",\n                    url: \"https://git/org/foo\",\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"experiment\"]\n                ),\n                MockPackage(\n                    name: \"BarPackage\",\n                    identity: \"org.bar\",\n                    targets: [\n                        MockTarget(name: \"BarTarget\", dependencies: [\n                            .product(name: \"FooProduct\", package: \"org.foo\"),\n                        ]),\n                    ],\n                    products: [\n                        MockProduct(name: \"BarProduct\", modules: [\"BarTarget\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n                MockPackage(\n                    name: \"FooPackage\",\n                    identity: \"org.foo\",\n                    alternativeURLs: [\"https://git/org/foo\"],\n                    targets: [\n                        MockTarget(name: \"FooTarget\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"FooProduct\", modules: [\"FooTarget\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .disabled\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { _, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        multiple similar targets 'FooTarget' appear in registry package 'org.foo' and source control package 'foo'\n                        \"\"\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .identity\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        dependency 'org.foo' and dependency 'git/org/foo' both point to the same package identity 'org.foo'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->org.bar->org.foo (B) \\(tmpDirCanonicalPackageLocation)/roots/root->git/org/foo.\n                        \"\"\"),\n                        severity: .warning\n                    )\n                }\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result.check(dependency: \"org.foo\", at: .checkout(.branch(\"experiment\")))\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.0.0\"))\n            }\n        }\n\n        // reset\n        try await workspace.closeWorkspace()\n\n        do {\n            workspace.sourceControlToRegistryDependencyTransformation = .swizzle\n\n            try await workspace.checkPackageGraph(roots: [\"root\"]) { graph, diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .contains(\"\"\"\n                        dependency 'org.foo' and dependency 'git/org/foo' both point to the same package identity 'org.foo'. The dependencies are introduced through the following chains: (A) \\(tmpDirCanonicalPackageLocation)/roots/root->org.bar->org.foo (B) \\(tmpDirCanonicalPackageLocation)/roots/root->git/org/foo.\n                        \"\"\"),\n                        severity: .warning\n                    )\n                }\n                PackageGraphTesterXCTest(graph) { result in\n                    result.check(roots: \"Root\")\n                    result.check(packages: \"org.bar\", \"org.foo\", \"Root\")\n                    result.check(modules: \"FooTarget\", \"BarTarget\", \"RootTarget\")\n                    result\n                        .checkTarget(\"RootTarget\") { result in result.check(dependencies: \"BarProduct\", \"FooProduct\") }\n                }\n            }\n\n            await workspace.checkManagedDependencies { result in\n                result\n                    .check(\n                        dependency: \"org.foo\",\n                        at: .checkout(.branch(\"experiment\"))\n                    ) // we cannot swizzle branch based deps\n                result.check(dependency: \"org.bar\", at: .registryDownload(\"1.0.0\"))\n            }\n        }\n    }\n\n    func testCustomPackageContainerProvider() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let customFS = InMemoryFileSystem()\n        // write a manifest\n        try customFS.writeFileContents(.root.appending(component: Manifest.filename), bytes: \"\")\n        try ToolsVersionSpecificationWriter.rewriteSpecification(\n            manifestDirectory: .root,\n            toolsVersion: .current,\n            fileSystem: customFS\n        )\n        // write the sources\n        let sourcesDir = AbsolutePath(\"/Sources\")\n        let targetDir = sourcesDir.appending(\"Baz\")\n        try customFS.createDirectory(targetDir, recursive: true)\n        try customFS.writeFileContents(targetDir.appending(\"file.swift\"), bytes: \"\")\n\n        let bazURL = SourceControlURL(\"https://example.com/baz\")\n        let bazPackageReference = PackageReference(\n            identity: PackageIdentity(url: bazURL),\n            kind: .remoteSourceControl(bazURL)\n        )\n        let bazContainer = MockPackageContainer(\n            package: bazPackageReference,\n            dependencies: [\"1.0.0\": []],\n            fileSystem: customFS,\n            customRetrievalPath: .root\n        )\n\n        let fooPath = sandbox.appending(\"Foo\")\n        let fooPackageReference = PackageReference(identity: PackageIdentity(path: fooPath), kind: .root(fooPath))\n        let fooContainer = MockPackageContainer(package: fooPackageReference)\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"Foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\", dependencies: [\"Bar\"]),\n                        MockTarget(name: \"Bar\", dependencies: [.product(name: \"Baz\", package: \"baz\")]),\n                        MockTarget(name: \"BarTests\", dependencies: [\"Bar\"], type: .test),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\", \"Bar\"]),\n                    ],\n                    dependencies: [\n                        .sourceControl(url: bazURL, requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Baz\",\n                    url: bazURL.absoluteString,\n                    targets: [\n                        MockTarget(name: \"Baz\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Baz\", modules: [\"Baz\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            customPackageContainerProvider: MockPackageContainerProvider(containers: [fooContainer, bazContainer])\n        )\n\n        let deps: [MockDependency] = [\n            .sourceControl(url: bazURL, requirement: .exact(\"1.0.0\")),\n        ]\n        try await workspace.checkPackageGraph(roots: [\"Foo\"], deps: deps) { graph, diagnostics in\n            PackageGraphTesterXCTest(graph) { result in\n                result.check(roots: \"Foo\")\n                result.check(packages: \"Baz\", \"Foo\")\n                result.check(modules: \"Bar\", \"Baz\", \"Foo\")\n                result.check(testModules: \"BarTests\")\n                result.checkTarget(\"Foo\") { result in result.check(dependencies: \"Bar\") }\n                result.checkTarget(\"Bar\") { result in result.check(dependencies: \"Baz\") }\n                result.checkTarget(\"BarTests\") { result in result.check(dependencies: \"Bar\") }\n            }\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"baz\", at: .custom(Version(1, 0, 0), .root))\n        }\n    }\n\n    func testRegistryMissingConfigurationErrors() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let registryClient = try makeRegistryClient(\n            packageIdentity: .plain(\"org.foo\"),\n            packageVersion: \"1.0.0\",\n            configuration: .init(),\n            fileSystem: fs\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            registryClient: registryClient\n        )\n\n        await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(diagnostic: .equal(\"no registry configured for 'org' scope\"), severity: .error)\n            }\n    }\n    }\n\n    func testRegistryReleasesServerErrors() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: .plain(\"org.foo\"),\n                packageVersion: \"1.0.0\",\n                releasesRequestHandler: { _, _ in\n                    throw StringError(\"boom\")\n                },\n                fileSystem: fs\n            )\n\n            try await workspace.closeWorkspace()\n            workspace.registryClient = registryClient\n            await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .equal(\"failed fetching org.foo releases list from http://localhost: boom\"),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        do {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: .plain(\"org.foo\"),\n                packageVersion: \"1.0.0\",\n                releasesRequestHandler: { _, _ in\n                    .serverError()\n                },\n                fileSystem: fs\n            )\n\n            try await workspace.closeWorkspace()\n            workspace.registryClient = registryClient\n            await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .equal(\n                            \"failed fetching org.foo releases list from http://localhost: server error 500: Internal Server Error\"\n                        ),\n                        severity: .error\n                    )\n                }\n            }\n        }\n    }\n\n    func testRegistryReleaseChecksumServerErrors() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: .plain(\"org.foo\"),\n                packageVersion: \"1.0.0\",\n                versionMetadataRequestHandler: { _, _ in\n                    throw StringError(\"boom\")\n                },\n                fileSystem: fs\n            )\n\n            try await workspace.closeWorkspace()\n            workspace.registryClient = registryClient\n            await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .equal(\n                            \"failed fetching org.foo version 1.0.0 release information from http://localhost: boom\"\n                        ),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        do {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: .plain(\"org.foo\"),\n                packageVersion: \"1.0.0\",\n                versionMetadataRequestHandler: { _, _ in\n                    .serverError()\n                },\n                fileSystem: fs\n            )\n\n            try await workspace.closeWorkspace()\n            workspace.registryClient = registryClient\n            await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .equal(\n                            \"failed fetching org.foo version 1.0.0 release information from http://localhost: server error 500: Internal Server Error\"\n                        ),\n                        severity: .error\n                    )\n                }\n            }\n        }\n    }\n\n    func testRegistryManifestServerErrors() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: .plain(\"org.foo\"),\n                packageVersion: \"1.0.0\",\n                manifestRequestHandler: { _, _ in\n                    throw StringError(\"boom\")\n                },\n                fileSystem: fs\n            )\n\n            try await workspace.closeWorkspace()\n            workspace.registryClient = registryClient\n            await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .equal(\n                            \"failed retrieving org.foo version 1.0.0 manifest from http://localhost: boom\"\n                        ),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        do {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: .plain(\"org.foo\"),\n                packageVersion: \"1.0.0\",\n                manifestRequestHandler: { _, _ in\n                    .serverError()\n                },\n                fileSystem: fs\n            )\n\n            try await workspace.closeWorkspace()\n            workspace.registryClient = registryClient\n            await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .equal(\n                            \"failed retrieving org.foo version 1.0.0 manifest from http://localhost: server error 500: Internal Server Error\"\n                        ),\n                        severity: .error\n                    )\n                }\n            }\n        }\n    }\n\n    func testRegistryDownloadServerErrors() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ]\n        )\n\n        do {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: .plain(\"org.foo\"),\n                packageVersion: \"1.0.0\",\n                downloadArchiveRequestHandler: { _, _ in\n                    throw StringError(\"boom\")\n                },\n                fileSystem: fs\n            )\n\n            try await workspace.closeWorkspace()\n            workspace.registryClient = registryClient\n            await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .equal(\n                            \"failed downloading org.foo version 1.0.0 source archive from http://localhost: boom\"\n                        ),\n                        severity: .error\n                    )\n                }\n            }\n        }\n\n        do {\n            let registryClient = try makeRegistryClient(\n                packageIdentity: .plain(\"org.foo\"),\n                packageVersion: \"1.0.0\",\n                downloadArchiveRequestHandler: { _, _ in\n                    .serverError()\n                },\n                fileSystem: fs\n            )\n\n            try await workspace.closeWorkspace()\n            workspace.registryClient = registryClient\n            await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n                testDiagnostics(diagnostics) { result in\n                    result.check(\n                        diagnostic: .equal(\n                            \"failed downloading org.foo version 1.0.0 source archive from http://localhost: server error 500: Internal Server Error\"\n                        ),\n                        severity: .error\n                    )\n                }\n            }\n        }\n    }\n\n    func testRegistryArchiveErrors() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let registryClient = try makeRegistryClient(\n            packageIdentity: .plain(\"org.foo\"),\n            packageVersion: \"1.0.0\",\n            archiver: MockArchiver(handler: { _, _, _, completion in\n                completion(.failure(StringError(\"boom\")))\n            }),\n            fileSystem: fs\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            registryClient: registryClient\n        )\n\n        try await workspace.closeWorkspace()\n        workspace.registryClient = registryClient\n        await workspace.checkPackageGraphFailure(roots: [\"MyPackage\"]) { diagnostics in\n            testDiagnostics(diagnostics) { result in\n                result.check(\n                    diagnostic: .regex(\n                        \"failed extracting '.*[\\\\\\\\/]registry[\\\\\\\\/]downloads[\\\\\\\\/]org[\\\\\\\\/]foo[\\\\\\\\/]1.0.0.zip' to '.*[\\\\\\\\/]registry[\\\\\\\\/]downloads[\\\\\\\\/]org[\\\\\\\\/]foo[\\\\\\\\/]1.0.0': boom\"\n                    ),\n                    severity: .error\n                )\n            }\n        }\n    }\n\n    func testRegistryMetadata() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        let registryURL = URL(\"https://packages.example.com\")\n        var registryConfiguration = RegistryConfiguration()\n        registryConfiguration.defaultRegistry = Registry(url: registryURL, supportsAvailability: false)\n        registryConfiguration.security = RegistryConfiguration.Security()\n        registryConfiguration.security!.default.signing = RegistryConfiguration.Security.Signing()\n        registryConfiguration.security!.default.signing!.onUnsigned = .silentAllow\n\n        let registryClient = try makeRegistryClient(\n            packageIdentity: .plain(\"org.foo\"),\n            packageVersion: \"1.5.1\",\n            targets: [\"Foo\"],\n            configuration: registryConfiguration,\n            fileSystem: fs\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"MyProduct\", modules: [\"MyTarget\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            registryClient: registryClient\n        )\n\n        // for mock manifest loader to work with an actual registry download\n        // we populate the mock manifest with a pointer to the correct download location\n        let defaultLocations = try Workspace.Location(forRootPackage: sandbox, fileSystem: fs)\n        let packagePath = defaultLocations.registryDownloadDirectory.appending(components: [\"org\", \"foo\", \"1.5.1\"])\n        workspace.manifestLoader.manifests[.init(url: \"org.foo\", version: \"1.5.1\")] =\n            try Manifest.createManifest(\n                displayName: \"Foo\",\n                path: packagePath.appending(component: Manifest.filename),\n                packageKind: .registry(\"org.foo\"),\n                packageIdentity: .plain(\"Foo\"),\n                packageLocation: \"org.foo\",\n                toolsVersion: .current,\n                products: [\n                    .init(name: \"Foo\", type: .library(.automatic), targets: [\"Foo\"]),\n                ],\n                targets: [\n                    .init(name: \"Foo\"),\n                ]\n            )\n\n        try await workspace.checkPackageGraph(roots: [\"MyPackage\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                guard let foo = result.find(package: \"org.foo\") else {\n                    return XCTFail(\"missing package\")\n                }\n                XCTAssertNotNil(foo.registryMetadata, \"expecting registry metadata\")\n                XCTAssertEqual(foo.registryMetadata?.source, .registry(registryURL))\n                XCTAssertMatch(foo.registryMetadata?.metadata.description, .contains(\"org.foo\"))\n                XCTAssertMatch(foo.registryMetadata?.metadata.readmeURL?.absoluteString, .contains(\"org.foo\"))\n                XCTAssertMatch(foo.registryMetadata?.metadata.licenseURL?.absoluteString, .contains(\"org.foo\"))\n            }\n        }\n\n        await workspace.checkManagedDependencies { result in\n            result.check(dependency: \"org.foo\", at: .registryDownload(\"1.5.1\"))\n        }\n    }\n\n    func testRegistryDefaultRegistryConfiguration() async throws {\n        let sandbox = AbsolutePath(\"/tmp/ws/\")\n        let fs = InMemoryFileSystem()\n\n        var configuration = RegistryConfiguration()\n        configuration.security = .testDefault\n\n        let registryClient = try makeRegistryClient(\n            packageIdentity: .plain(\"org.foo\"),\n            packageVersion: \"1.0.0\",\n            configuration: configuration,\n            fileSystem: fs\n        )\n\n        let workspace = try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\"]\n                ),\n            ],\n            registryClient: registryClient,\n            defaultRegistry: .init(\n                url: \"http://some-registry.com\",\n                supportsAvailability: false\n            )\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"MyPackage\"]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                XCTAssertNotNil(result.find(package: \"org.foo\"), \"missing package\")\n            }\n        }\n    }\n\n    // MARK: - Expected signing entity verification\n\n    func createBasicRegistryWorkspace(\n        metadata: [String: RegistryReleaseMetadata],\n        mirrors: DependencyMirrors? = nil\n    ) async throws -> MockWorkspace {\n        // let sandbox = AbsolutePath.root.appending(\"swiftpm-tests-can-be-deleted/tmp/ws\")\n        let sandbox = AbsolutePath.root.appending(components: [\"swiftpm-tests-can-be-deleted\", \"tmp\", \"ws\"])\n        let fs = InMemoryFileSystem()\n\n        return try await MockWorkspace(\n            sandbox: sandbox,\n            fileSystem: fs,\n            roots: [\n                MockPackage(\n                    name: \"MyPackage\",\n                    targets: [\n                        MockTarget(\n                            name: \"MyTarget1\",\n                            dependencies: [\n                                .product(name: \"Foo\", package: \"org.foo\"),\n                            ]\n                        ),\n                        MockTarget(\n                            name: \"MyTarget2\",\n                            dependencies: [\n                                .product(name: \"Bar\", package: \"org.bar\"),\n                            ]\n                        ),\n                    ],\n                    products: [\n                        MockProduct(name: \"MyProduct\", modules: [\"MyTarget1\", \"MyTarget2\"]),\n                    ],\n                    dependencies: [\n                        .registry(identity: \"org.foo\", requirement: .upToNextMajor(from: \"1.0.0\")),\n                        .registry(identity: \"org.bar\", requirement: .upToNextMajor(from: \"2.0.0\")),\n                    ]\n                ),\n            ],\n            packages: [\n                MockPackage(\n                    name: \"Foo\",\n                    identity: \"org.foo\",\n                    metadata: metadata[\"org.foo\"],\n                    targets: [\n                        MockTarget(name: \"Foo\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Foo\", modules: [\"Foo\"]),\n                    ],\n                    versions: [\"1.0.0\", \"1.1.0\", \"1.2.0\", \"1.3.0\", \"1.4.0\", \"1.5.0\", \"1.5.1\"]\n                ),\n                MockPackage(\n                    name: \"Bar\",\n                    identity: \"org.bar\",\n                    metadata: metadata[\"org.bar\"],\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"2.0.0\", \"2.1.0\", \"2.2.0\"]\n                ),\n                MockPackage(\n                    name: \"BarMirror\",\n                    url: \"https://scm.com/org/bar-mirror\",\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"2.0.0\", \"2.1.0\", \"2.2.0\"]\n                ),\n                MockPackage(\n                    name: \"BarMirrorRegistry\",\n                    identity: \"ecorp.bar\",\n                    metadata: metadata[\"ecorp.bar\"],\n                    targets: [\n                        MockTarget(name: \"Bar\"),\n                    ],\n                    products: [\n                        MockProduct(name: \"Bar\", modules: [\"Bar\"]),\n                    ],\n                    versions: [\"2.0.0\", \"2.1.0\", \"2.2.0\"]\n                ),\n            ],\n            mirrors: mirrors\n        )\n    }\n\n    func testSigningEntityVerification_SignedCorrectly() async throws {\n        let actualMetadata = RegistryReleaseMetadata.createWithSigningEntity(\n            .recognized(\n                type: \"adp\",\n                commonName: \"John Doe\",\n                organization: \"Example Corp\",\n                identity: \"XYZ\"\n            )\n        )\n\n        let workspace = try await createBasicRegistryWorkspace(metadata: [\"org.bar\": actualMetadata])\n\n        try await workspace.checkPackageGraph(roots: [\"MyPackage\"], expectedSigningEntities: [\n            PackageIdentity.plain(\"org.bar\"): XCTUnwrap(actualMetadata.signature?.signedBy),\n        ]) { _, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n        }\n    }\n\n    func testSigningEntityVerification_SignedIncorrectly() async throws {\n        let actualMetadata = RegistryReleaseMetadata.createWithSigningEntity(\n            .recognized(\n                type: \"adp\",\n                commonName: \"John Doe\",\n                organization: \"Example Corp\",\n                identity: \"XYZ\"\n            )\n        )\n        let expectedSigningEntity: RegistryReleaseMetadata.SigningEntity = .recognized(\n            type: \"adp\",\n            commonName: \"John Doe\",\n            organization: \"Evil Corp\",\n            identity: \"ABC\"\n        )\n\n        let workspace = try await createBasicRegistryWorkspace(metadata: [\"org.bar\": actualMetadata])\n\n        do {\n            try await workspace.checkPackageGraph(roots: [\"MyPackage\"], expectedSigningEntities: [\n                PackageIdentity.plain(\"org.bar\"): expectedSigningEntity,\n            ]) { _, _ in }\n            XCTFail(\"should not succeed\")\n        } catch Workspace.SigningError.mismatchedSigningEntity(_, let expected, let actual) {\n            XCTAssertEqual(actual, actualMetadata.signature?.signedBy)\n            XCTAssertEqual(expected, expectedSigningEntity)\n        } catch {\n            XCTFail(\"unexpected error: \\(error)\")\n        }\n    }\n\n    func testSigningEntityVerification_Unsigned() async throws {\n        let expectedSigningEntity: RegistryReleaseMetadata.SigningEntity = .recognized(\n            type: \"adp\",\n            commonName: \"Jane Doe\",\n            organization: \"Example Corp\",\n            identity: \"XYZ\"\n        )\n\n        let workspace = try await createBasicRegistryWorkspace(metadata: [:])\n\n        do {\n            try await workspace.checkPackageGraph(roots: [\"MyPackage\"], expectedSigningEntities: [\n                PackageIdentity.plain(\"org.bar\"): expectedSigningEntity,\n            ]) { _, _ in }\n            XCTFail(\"should not succeed\")\n        } catch Workspace.SigningError.unsigned(_, let expected) {\n            XCTAssertEqual(expected, expectedSigningEntity)\n        } catch {\n            XCTFail(\"unexpected error: \\(error)\")\n        }\n    }\n\n    func testSigningEntityVerification_NotFound() async throws {\n        let expectedSigningEntity: RegistryReleaseMetadata.SigningEntity = .recognized(\n            type: \"adp\",\n            commonName: \"Jane Doe\",\n            organization: \"Example Corp\",\n            identity: \"XYZ\"\n        )\n\n        let workspace = try await createBasicRegistryWorkspace(metadata: [:])\n\n        do {\n            try await workspace.checkPackageGraph(roots: [\"MyPackage\"], expectedSigningEntities: [\n                PackageIdentity.plain(\"foo.bar\"): expectedSigningEntity,\n            ]) { _, _ in }\n            XCTFail(\"should not succeed\")\n        } catch Workspace.SigningError.expectedIdentityNotFound(let package) {\n            XCTAssertEqual(package.description, \"foo.bar\")\n        } catch {\n            XCTFail(\"unexpected error: \\(error)\")\n        }\n    }\n\n    func testSigningEntityVerification_MirroredSignedCorrectly() async throws {\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"ecorp.bar\", for: \"org.bar\")\n\n        let actualMetadata = RegistryReleaseMetadata.createWithSigningEntity(\n            .recognized(\n                type: \"adp\",\n                commonName: \"John Doe\",\n                organization: \"Example Corp\",\n                identity: \"XYZ\"\n            )\n        )\n\n        let workspace = try await createBasicRegistryWorkspace(\n            metadata: [\"ecorp.bar\": actualMetadata],\n            mirrors: mirrors\n        )\n\n        try await workspace.checkPackageGraph(roots: [\"MyPackage\"], expectedSigningEntities: [\n            PackageIdentity.plain(\"org.bar\"): XCTUnwrap(actualMetadata.signature?.signedBy),\n        ]) { graph, diagnostics in\n            XCTAssertNoDiagnostics(diagnostics)\n            PackageGraphTesterXCTest(graph) { result in\n                XCTAssertNotNil(result.find(package: \"ecorp.bar\"), \"missing package\")\n                XCTAssertNil(result.find(package: \"org.bar\"), \"unexpectedly present package\")\n            }\n        }\n    }\n\n    func testSigningEntityVerification_MirrorSignedIncorrectly() async throws {\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"ecorp.bar\", for: \"org.bar\")\n\n        let actualMetadata = RegistryReleaseMetadata.createWithSigningEntity(\n            .recognized(\n                type: \"adp\",\n                commonName: \"John Doe\",\n                organization: \"Example Corp\",\n                identity: \"XYZ\"\n            )\n        )\n        let expectedSigningEntity: RegistryReleaseMetadata.SigningEntity = .recognized(\n            type: \"adp\",\n            commonName: \"John Doe\",\n            organization: \"Evil Corp\",\n            identity: \"ABC\"\n        )\n\n        let workspace = try await createBasicRegistryWorkspace(\n            metadata: [\"ecorp.bar\": actualMetadata],\n            mirrors: mirrors\n        )\n\n        do {\n            try await workspace.checkPackageGraph(roots: [\"MyPackage\"], expectedSigningEntities: [\n                PackageIdentity.plain(\"org.bar\"): expectedSigningEntity,\n            ]) { _, _ in }\n            XCTFail(\"should not succeed\")\n        } catch Workspace.SigningError.mismatchedSigningEntity(_, let expected, let actual) {\n            XCTAssertEqual(actual, actualMetadata.signature?.signedBy)\n            XCTAssertEqual(expected, expectedSigningEntity)\n        } catch {\n            XCTFail(\"unexpected error: \\(error)\")\n        }\n    }\n\n    func testSigningEntityVerification_MirroredUnsigned() async throws {\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"ecorp.bar\", for: \"org.bar\")\n\n        let expectedSigningEntity: RegistryReleaseMetadata.SigningEntity = .recognized(\n            type: \"adp\",\n            commonName: \"Jane Doe\",\n            organization: \"Example Corp\",\n            identity: \"XYZ\"\n        )\n\n        let workspace = try await createBasicRegistryWorkspace(metadata: [:], mirrors: mirrors)\n\n        do {\n            try await workspace.checkPackageGraph(roots: [\"MyPackage\"], expectedSigningEntities: [\n                PackageIdentity.plain(\"org.bar\"): expectedSigningEntity,\n            ]) { _, _ in }\n            XCTFail(\"should not succeed\")\n        } catch Workspace.SigningError.unsigned(_, let expected) {\n            XCTAssertEqual(expected, expectedSigningEntity)\n        } catch {\n            XCTFail(\"unexpected error: \\(error)\")\n        }\n    }\n\n    func testSigningEntityVerification_MirroredToSCM() async throws {\n        let mirrors = try DependencyMirrors()\n        try mirrors.set(mirror: \"https://scm.com/org/bar-mirror\", for: \"org.bar\")\n\n        let expectedSigningEntity: RegistryReleaseMetadata.SigningEntity = .recognized(\n            type: \"adp\",\n            commonName: \"Jane Doe\",\n            organization: \"Example Corp\",\n            identity: \"XYZ\"\n        )\n\n        let workspace = try await createBasicRegistryWorkspace(metadata: [:], mirrors: mirrors)\n\n        do {\n            try await workspace.checkPackageGraph(roots: [\"MyPackage\"], expectedSigningEntities: [\n                PackageIdentity.plain(\"org.bar\"): expectedSigningEntity,\n            ]) { _, _ in }\n            XCTFail(\"should not succeed\")\n        } catch Workspace.SigningError.expectedSignedMirroredToSourceControl(_, let expected) {\n            XCTAssertEqual(expected, expectedSigningEntity)\n        } catch {\n            XCTFail(\"unexpected error: \\(error)\")\n        }\n    }\n\n    func makeRegistryClient(\n        packageIdentity: PackageIdentity,\n        packageVersion: Version,\n        targets: [String] = [],\n        configuration: PackageRegistry.RegistryConfiguration? = .none,\n        identityResolver: IdentityResolver? = .none,\n        fingerprintStorage: PackageFingerprintStorage? = .none,\n        fingerprintCheckingMode: FingerprintCheckingMode = .strict,\n        signingEntityStorage: PackageSigningEntityStorage? = .none,\n        signingEntityCheckingMode: SigningEntityCheckingMode = .strict,\n        authorizationProvider: AuthorizationProvider? = .none,\n        releasesRequestHandler: HTTPClient.Implementation? = .none,\n        versionMetadataRequestHandler: HTTPClient.Implementation? = .none,\n        manifestRequestHandler: HTTPClient.Implementation? = .none,\n        downloadArchiveRequestHandler: HTTPClient.Implementation? = .none,\n        archiver: Archiver? = .none,\n        fileSystem: FileSystem\n    ) throws -> RegistryClient {\n        let jsonEncoder = JSONEncoder.makeWithDefaults()\n\n        guard let identity = packageIdentity.registry else {\n            throw StringError(\"Invalid package identifier: '\\(packageIdentity)'\")\n        }\n\n        let configuration = configuration ?? {\n            var configuration = PackageRegistry.RegistryConfiguration()\n            configuration.defaultRegistry = .init(url: \"http://localhost\", supportsAvailability: false)\n            configuration.security = .testDefault\n            return configuration\n        }()\n\n        let releasesRequestHandler = releasesRequestHandler ?? { _, _ in\n            let metadata = RegistryClient.Serialization.PackageMetadata(\n                releases: [packageVersion.description: .init(url: .none, problem: .none)]\n            )\n            return HTTPClientResponse(\n                statusCode: 200,\n                headers: [\n                    \"Content-Version\": \"1\",\n                    \"Content-Type\": \"application/json\",\n                ],\n                body: try! jsonEncoder.encode(metadata)\n            )\n        }\n\n        let versionMetadataRequestHandler = versionMetadataRequestHandler ?? { _, _ in\n            let metadata = RegistryClient.Serialization.VersionMetadata(\n                id: packageIdentity.description,\n                version: packageVersion.description,\n                resources: [\n                    .init(\n                        name: \"source-archive\",\n                        type: \"application/zip\",\n                        checksum: \"\",\n                        signing: nil\n                    ),\n                ],\n                metadata: .init(\n                    description: \"package \\(identity) description\",\n                    licenseURL: \"/\\(identity)/license\",\n                    readmeURL: \"/\\(identity)/readme\"\n                ),\n                publishedAt: nil\n            )\n            return HTTPClientResponse(\n                statusCode: 200,\n                headers: [\n                    \"Content-Version\": \"1\",\n                    \"Content-Type\": \"application/json\",\n                ],\n                body: try! jsonEncoder.encode(metadata)\n            )\n        }\n\n        let manifestRequestHandler = manifestRequestHandler ?? { _, _ in\n            HTTPClientResponse(\n                statusCode: 200,\n                headers: [\n                    \"Content-Version\": \"1\",\n                    \"Content-Type\": \"text/x-swift\",\n                ],\n                body: Data(\"// swift-tools-version:\\(ToolsVersion.current)\".utf8)\n            )\n        }\n\n        let downloadArchiveRequestHandler = downloadArchiveRequestHandler ?? { request, _ in\n            switch request.kind {\n            case .download(let fileSystem, let destination):\n                // creates a dummy zipfile which is required by the archiver step\n                try! fileSystem.createDirectory(destination.parentDirectory, recursive: true)\n                try! fileSystem.writeFileContents(destination, string: \"\")\n            default:\n                preconditionFailure(\"invalid request\")\n            }\n\n            return HTTPClientResponse(\n                statusCode: 200,\n                headers: [\n                    \"Content-Version\": \"1\",\n                    \"Content-Type\": \"application/zip\",\n                ],\n                body: Data(\"\".utf8)\n            )\n        }\n\n        let archiver = archiver ?? MockArchiver(handler: { _, _, to, completion in\n            do {\n                let packagePath = to.appending(\"top\")\n                try fileSystem.createDirectory(packagePath, recursive: true)\n                try fileSystem.writeFileContents(packagePath.appending(component: Manifest.filename), bytes: [])\n                try ToolsVersionSpecificationWriter.rewriteSpecification(\n                    manifestDirectory: packagePath,\n                    toolsVersion: .current,\n                    fileSystem: fileSystem\n                )\n                for target in targets {\n                    try fileSystem.createDirectory(\n                        packagePath.appending(components: \"Sources\", target),\n                        recursive: true\n                    )\n                    try fileSystem.writeFileContents(\n                        packagePath.appending(components: [\"Sources\", target, \"file.swift\"]),\n                        bytes: []\n                    )\n                }\n                completion(.success(()))\n            } catch {\n                completion(.failure(error))\n            }\n        })\n        let fingerprintStorage = fingerprintStorage ?? MockPackageFingerprintStorage()\n        let signingEntityStorage = signingEntityStorage ?? MockPackageSigningEntityStorage()\n\n        return RegistryClient(\n            configuration: configuration,\n            fingerprintStorage: fingerprintStorage,\n            fingerprintCheckingMode: fingerprintCheckingMode,\n            skipSignatureValidation: false,\n            signingEntityStorage: signingEntityStorage,\n            signingEntityCheckingMode: signingEntityCheckingMode,\n            authorizationProvider: authorizationProvider,\n            customHTTPClient: HTTPClient(configuration: .init(), implementation: { request, progress in\n                switch request.url.path {\n                // request to get package releases\n                case \"/\\(identity.scope)/\\(identity.name)\":\n                    return try await releasesRequestHandler(request, progress)\n                // request to get package version metadata\n                case \"/\\(identity.scope)/\\(identity.name)/\\(packageVersion)\":\n                    return try await versionMetadataRequestHandler(request, progress)\n                // request to get package manifest\n                case \"/\\(identity.scope)/\\(identity.name)/\\(packageVersion)/Package.swift\":\n                    return try await manifestRequestHandler(request, progress)\n                // request to get download the version source archive\n                case \"/\\(identity.scope)/\\(identity.name)/\\(packageVersion).zip\":\n                    return try await downloadArchiveRequestHandler(request, progress)\n                default:\n                    throw StringError(\"unexpected url \\(request.url)\")\n                }\n            }),\n            customArchiverProvider: { _ in archiver },\n            delegate: .none,\n            checksumAlgorithm: MockHashAlgorithm()\n        )\n    }\n}\n\nfunc createDummyXCFramework(fileSystem: FileSystem, path: AbsolutePath, name: String) throws {\n    let path = path.appending(\"\\(name).xcframework\")\n    try fileSystem.createDirectory(path, recursive: true)\n    try fileSystem.writeFileContents(\n        path.appending(\"info.plist\"),\n        string: \"\"\"\n        <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n        <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n        <plist version=\"1.0\">\n        <dict>\n            <key>AvailableLibraries</key>\n            <array></array>\n            <key>CFBundlePackageType</key>\n            <string>XFWK</string>\n            <key>XCFrameworkFormatVersion</key>\n            <string>1.0</string>\n        </dict>\n        </plist>\n        \"\"\"\n    )\n}\n\nfunc createDummyArtifactBundle(fileSystem: FileSystem, path: AbsolutePath, name: String) throws {\n    let path = path.appending(\"\\(name).artifactbundle\")\n    try fileSystem.createDirectory(path, recursive: true)\n    try fileSystem.writeFileContents(\n        path.appending(\"info.json\"),\n        string: \"\"\"\n        {\n            \"schemaVersion\": \"1.0\",\n            \"artifacts\": {}\n        }\n        \"\"\"\n    )\n}\n\nstruct DummyError: LocalizedError, Equatable {\n    public var errorDescription: String? { \"dummy error\" }\n}\n\nextension RegistryReleaseMetadata {\n    fileprivate static func createWithSigningEntity(\n        _ entity: RegistryReleaseMetadata\n            .SigningEntity\n    ) -> RegistryReleaseMetadata {\n        self.init(\n            source: .registry(URL(string: \"https://example.com\")!),\n            metadata: .init(scmRepositoryURLs: nil),\n            signature: .init(signedBy: entity, format: \"xyz\", value: [])\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/XCBuildSupportTests/Inputs/Foo.pc",
    "content": "prefix=/usr\nexec_prefix=${prefix}\nlibdir=${exec_prefix}/lib\nincludedir=${prefix}/include\n\nName: Foo\nURL: http://127.0.0.1/\nDescription: The one and only SystemModule\nVersion: 1.10.0\nCflags: -I${includedir} -I/path/to/inc -I${pcfiledir}\nLibs: -L${libdir} -L/usr/da/lib -lSystemModule -lok\n"
  },
  {
    "path": "Tests/XCBuildSupportTests/PIFBuilderTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport Foundation\n\n@_spi(DontAdoptOutsideOfSwiftPMExposedForBenchmarksAndTestsOnly)\nimport PackageGraph\n\nimport PackageLoading\n@testable import PackageModel\nimport SPMBuildCore\nimport _InternalTestSupport\nimport _InternalBuildTestSupport\n@testable import XCBuildSupport\nimport XCTest\nimport Testing\n\nfinal class PIFBuilderTests: XCTestCase {\n    let inputsDir = AbsolutePath(#file).parentDirectory.appending(components: \"Inputs\")\n\n    func testOrdering() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        // Repeat multiple times to detect non-deterministic shuffling due to sets.\n        for _ in 0 ..< 10 {\n            let fs = InMemoryFileSystem(\n                emptyFiles:\n                \"/A/Sources/A1/main.swift\",\n                \"/A/Sources/A2/lib.swift\",\n                \"/A/Sources/A3/lib.swift\",\n                \"/B/Sources/B1/main.swift\",\n                \"/B/Sources/B2/lib.swift\"\n            )\n\n            let observability = ObservabilitySystem.makeForTesting()\n            let graph = try loadModulesGraph(\n                fileSystem: fs,\n                manifests: [\n                    Manifest.createLocalSourceControlManifest(\n                        displayName: \"B\",\n                        path: \"/B\",\n                        toolsVersion: .v5_2,\n                        products: [\n                            .init(name: \"bexe\", type: .executable, targets: [\"B1\"]),\n                            .init(name: \"blib\", type: .library(.static), targets: [\"B2\"]),\n                        ],\n                        targets: [\n                            .init(name: \"B2\", dependencies: []),\n                            .init(name: \"B1\", dependencies: [\"B2\"]),\n                        ]\n                    ),\n                    Manifest.createRootManifest(\n                        displayName: \"A\",\n                        path: \"/A\",\n                        toolsVersion: .v5_2,\n                        dependencies: [\n                            .localSourceControl(path: \"/B\", requirement: .branch(\"main\")),\n                        ],\n                        products: [\n                            .init(name: \"alib\", type: .library(.static), targets: [\"A2\"]),\n                            .init(name: \"aexe\", type: .executable, targets: [\"A1\"]),\n                        ],\n                        targets: [\n                            .init(name: \"A1\", dependencies: [\"A3\", \"A2\", .product(name: \"blib\", package: \"B\")]),\n                            .init(name: \"A2\", dependencies: []),\n                            .init(name: \"A3\", dependencies: []),\n                        ]\n                    ),\n                ],\n                observabilityScope: observability.topScope\n            )\n\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(),\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            let pif = try builder.construct()\n\n            XCTAssertNoDiagnostics(observability.diagnostics)\n\n            let projectNames = pif.workspace.projects.map(\\.name)\n            XCTAssertEqual(projectNames, [\"A\", \"B\", \"Aggregate\"])\n            let projectATargetNames = pif.workspace.projects[0].targets.map(\\.name)\n            XCTAssertEqual(\n                projectATargetNames,\n                [\"aexe_79CC9E117_PackageProduct\", \"alib_79D40CF5C_PackageProduct\", \"A2\", \"A3\"]\n            )\n            let targetAExeDependencies = pif.workspace.projects[0].targets[0].dependencies\n            XCTAssertEqual(\n                targetAExeDependencies.map(\\.targetGUID),\n                [\"PACKAGE-PRODUCT:blib\", \"PACKAGE-TARGET:A2\", \"PACKAGE-TARGET:A3\"]\n            )\n            let projectBTargetNames = pif.workspace.projects[1].targets.map(\\.name)\n            #if ENABLE_TARGET_BASED_DEPENDENCY_RESOLUTION\n            XCTAssertEqual(projectBTargetNames, [\"blib_7AE74026D_PackageProduct\", \"B2\"])\n            #else\n            XCTAssertEqual(\n                projectBTargetNames,\n                [\"bexe_7ADFD1428_PackageProduct\", \"blib_7AE74026D_PackageProduct\", \"B2\"]\n            )\n            #endif\n        }\n    }\n\n    func testProject() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Tests/FooTests/tests.swift\",\n            \"/Bar/Sources/BarLib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    packageKind: .root(\"/Foo\"),\n                    packageIdentity: .plain(\"Foo\"),\n                    defaultLocalization: \"fr\",\n                    toolsVersion: .v5_2,\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .branch(\"main\")),\n                    ],\n                    targets: [\n                        .init(name: \"foo\", dependencies: [.product(name: \"BarLib\", package: \"Bar\")]),\n                        .init(name: \"FooTests\", type: .test),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"10.14\"),\n                        PlatformDescription(name: \"ios\", version: \"12\"),\n                        PlatformDescription(name: \"tvos\", version: \"11\"),\n                        PlatformDescription(name: \"watchos\", version: \"6\"),\n                    ],\n                    toolsVersion: .v5_2,\n                    products: [\n                        .init(name: \"BarLib\", type: .library(.automatic), targets: [\"BarLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"BarLib\"),\n                        .init(name: \"BarTests\", type: .test),\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                XCTAssertEqual(project.path.pathString, \"/Foo\")\n                XCTAssertEqual(project.projectDirectory.pathString, \"/Foo\")\n                XCTAssertEqual(project.name, \"Foo\")\n                XCTAssertEqual(project.developmentRegion, \"fr\")\n\n                project.checkTarget(\"PACKAGE-PRODUCT:foo\")\n                project.checkTarget(\"PACKAGE-PRODUCT:FooTests\")\n\n                project.checkBuildConfiguration(\"Debug\") { configuration in\n                    XCTAssertEqual(configuration.guid, \"PACKAGE:/Foo::BUILDCONFIG_Debug\")\n                    XCTAssertEqual(configuration.name, \"Debug\")\n\n                    configuration.checkAllBuildSettings { settings in\n                        XCTAssertEqual(settings[.CLANG_ENABLE_OBJC_ARC], \"YES\")\n                        XCTAssertEqual(settings[.CODE_SIGN_IDENTITY], \"\")\n                        XCTAssertEqual(settings[.CODE_SIGNING_REQUIRED], \"NO\")\n                        XCTAssertEqual(settings[.COPY_PHASE_STRIP], \"NO\")\n                        XCTAssertEqual(settings[.DEBUG_INFORMATION_FORMAT], \"dwarf\")\n                        XCTAssertEqual(settings[.DRIVERKIT_DEPLOYMENT_TARGET], \"19.0\")\n                        XCTAssertEqual(settings[.DYLIB_INSTALL_NAME_BASE], \"@rpath\")\n                        XCTAssertEqual(settings[.ENABLE_NS_ASSERTIONS], \"YES\")\n                        XCTAssertEqual(settings[.ENABLE_TESTABILITY], \"YES\")\n                        XCTAssertEqual(settings[.ENABLE_TESTING_SEARCH_PATHS], \"YES\")\n                        XCTAssertEqual(settings[.ENTITLEMENTS_REQUIRED], \"NO\")\n                        XCTAssertEqual(settings[.GCC_OPTIMIZATION_LEVEL], \"0\")\n                        XCTAssertEqual(\n                            settings[.GCC_PREPROCESSOR_DEFINITIONS],\n                            [\"$(inherited)\", \"SWIFT_PACKAGE\", \"DEBUG=1\"]\n                        )\n                        XCTAssertEqual(settings[.IPHONEOS_DEPLOYMENT_TARGET], \"12.0\")\n                        XCTAssertEqual(settings[.IPHONEOS_DEPLOYMENT_TARGET, for: .macCatalyst], \"13.0\")\n                        XCTAssertEqual(settings[.KEEP_PRIVATE_EXTERNS], \"NO\")\n                        XCTAssertEqual(settings[.MACOSX_DEPLOYMENT_TARGET], \"10.13\")\n                        XCTAssertEqual(settings[.ONLY_ACTIVE_ARCH], \"YES\")\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                        XCTAssertEqual(settings[.SDK_VARIANT], \"auto\")\n                        XCTAssertEqual(settings[.SDKROOT], \"auto\")\n                        XCTAssertEqual(settings[.SKIP_INSTALL], \"YES\")\n                        XCTAssertEqual(settings[.SUPPORTED_PLATFORMS], [\"$(AVAILABLE_PLATFORMS)\"])\n                        XCTAssertEqual(\n                            settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                            [\"$(inherited)\", \"SWIFT_PACKAGE\", \"DEBUG\"]\n                        )\n                        XCTAssertEqual(settings[.SWIFT_INSTALL_OBJC_HEADER], \"NO\")\n                        XCTAssertEqual(settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME], \"\")\n                        XCTAssertEqual(settings[.SWIFT_OPTIMIZATION_LEVEL], \"-Onone\")\n                        XCTAssertEqual(settings[.TVOS_DEPLOYMENT_TARGET], \"12.0\")\n                        XCTAssertEqual(settings[.USE_HEADERMAP], \"NO\")\n                        XCTAssertEqual(settings[.WATCHOS_DEPLOYMENT_TARGET], \"4.0\")\n                        XCTAssertEqual(settings[.XROS_DEPLOYMENT_TARGET], \"1.0\")\n\n                        let frameworksSearchPaths = [\"$(inherited)\", \"$(PLATFORM_DIR)/Developer/Library/Frameworks\"]\n                        for platform in [PIF.BuildSettings.Platform.macOS, .iOS, .tvOS] {\n                            XCTAssertEqual(settings[.FRAMEWORK_SEARCH_PATHS, for: platform], frameworksSearchPaths)\n                        }\n\n                        for platform in PIF.BuildSettings.Platform.allCases {\n                            XCTAssertEqual(settings[.SPECIALIZATION_SDK_OPTIONS, for: platform], nil)\n                        }\n                    }\n                }\n\n                project.checkBuildConfiguration(\"Release\") { configuration in\n                    XCTAssertEqual(configuration.guid, \"PACKAGE:/Foo::BUILDCONFIG_Release\")\n                    XCTAssertEqual(configuration.name, \"Release\")\n\n                    configuration.checkAllBuildSettings { settings in\n                        XCTAssertEqual(settings[.CLANG_ENABLE_OBJC_ARC], \"YES\")\n                        XCTAssertEqual(settings[.CODE_SIGN_IDENTITY], \"\")\n                        XCTAssertEqual(settings[.CODE_SIGNING_REQUIRED], \"NO\")\n                        XCTAssertEqual(settings[.COPY_PHASE_STRIP], \"YES\")\n                        XCTAssertEqual(settings[.DEBUG_INFORMATION_FORMAT], \"dwarf-with-dsym\")\n                        XCTAssertEqual(settings[.DRIVERKIT_DEPLOYMENT_TARGET], \"19.0\")\n                        XCTAssertEqual(settings[.DYLIB_INSTALL_NAME_BASE], \"@rpath\")\n                        XCTAssertEqual(settings[.ENABLE_TESTING_SEARCH_PATHS], \"YES\")\n                        XCTAssertEqual(settings[.ENTITLEMENTS_REQUIRED], \"NO\")\n                        XCTAssertEqual(settings[.GCC_OPTIMIZATION_LEVEL], \"s\")\n                        XCTAssertEqual(settings[.GCC_PREPROCESSOR_DEFINITIONS], [\"$(inherited)\", \"SWIFT_PACKAGE\"])\n                        XCTAssertEqual(settings[.IPHONEOS_DEPLOYMENT_TARGET], \"12.0\")\n                        XCTAssertEqual(settings[.IPHONEOS_DEPLOYMENT_TARGET, for: .macCatalyst], \"13.0\")\n                        XCTAssertEqual(settings[.KEEP_PRIVATE_EXTERNS], \"NO\")\n                        XCTAssertEqual(settings[.MACOSX_DEPLOYMENT_TARGET], \"10.13\")\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                        XCTAssertEqual(settings[.SDK_VARIANT], \"auto\")\n                        XCTAssertEqual(settings[.SDKROOT], \"auto\")\n                        XCTAssertEqual(settings[.SKIP_INSTALL], \"YES\")\n                        XCTAssertEqual(settings[.SUPPORTED_PLATFORMS], [\"$(AVAILABLE_PLATFORMS)\"])\n                        XCTAssertEqual(\n                            settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                            [\"$(inherited)\", \"SWIFT_PACKAGE\"]\n                        )\n                        XCTAssertEqual(settings[.SWIFT_INSTALL_OBJC_HEADER], \"NO\")\n                        XCTAssertEqual(settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME], \"\")\n                        XCTAssertEqual(settings[.SWIFT_OPTIMIZATION_LEVEL], \"-Owholemodule\")\n                        XCTAssertEqual(settings[.TVOS_DEPLOYMENT_TARGET], \"12.0\")\n                        XCTAssertEqual(settings[.USE_HEADERMAP], \"NO\")\n                        XCTAssertEqual(settings[.WATCHOS_DEPLOYMENT_TARGET], \"4.0\")\n                        XCTAssertEqual(settings[.XROS_DEPLOYMENT_TARGET], \"1.0\")\n\n                        let frameworksSearchPaths = [\"$(inherited)\", \"$(PLATFORM_DIR)/Developer/Library/Frameworks\"]\n                        for platform in [PIF.BuildSettings.Platform.macOS, .iOS, .tvOS] {\n                            XCTAssertEqual(settings[.FRAMEWORK_SEARCH_PATHS, for: platform], frameworksSearchPaths)\n                        }\n\n                        for platform in PIF.BuildSettings.Platform.allCases {\n                            XCTAssertEqual(settings[.SPECIALIZATION_SDK_OPTIONS, for: platform], nil)\n                        }\n                    }\n                }\n            }\n\n            try workspace.checkProject(\"PACKAGE:/Bar\") { project in\n                XCTAssertEqual(project.path.pathString, \"/Bar\")\n                XCTAssertEqual(project.projectDirectory.pathString, \"/Bar\")\n                XCTAssertEqual(project.name, \"Bar\")\n                XCTAssertEqual(project.developmentRegion, \"en\")\n\n                project.checkTarget(\"PACKAGE-PRODUCT:BarLib\")\n\n                project.checkBuildConfiguration(\"Debug\") { configuration in\n                    XCTAssertEqual(configuration.guid, \"PACKAGE:/Bar::BUILDCONFIG_Debug\")\n                    XCTAssertEqual(configuration.name, \"Debug\")\n\n                    configuration.checkAllBuildSettings { settings in\n                        XCTAssertEqual(settings[.CLANG_ENABLE_OBJC_ARC], \"YES\")\n                        XCTAssertEqual(settings[.CODE_SIGN_IDENTITY], \"\")\n                        XCTAssertEqual(settings[.CODE_SIGNING_REQUIRED], \"NO\")\n                        XCTAssertEqual(settings[.COPY_PHASE_STRIP], \"NO\")\n                        XCTAssertEqual(settings[.DEBUG_INFORMATION_FORMAT], \"dwarf\")\n                        XCTAssertEqual(settings[.DRIVERKIT_DEPLOYMENT_TARGET], \"19.0\")\n                        XCTAssertEqual(settings[.DYLIB_INSTALL_NAME_BASE], \"@rpath\")\n                        XCTAssertEqual(settings[.ENABLE_NS_ASSERTIONS], \"YES\")\n                        XCTAssertEqual(settings[.ENABLE_TESTABILITY], \"YES\")\n                        XCTAssertEqual(settings[.ENABLE_TESTING_SEARCH_PATHS], \"YES\")\n                        XCTAssertEqual(settings[.ENTITLEMENTS_REQUIRED], \"NO\")\n                        XCTAssertEqual(settings[.GCC_OPTIMIZATION_LEVEL], \"0\")\n                        XCTAssertEqual(\n                            settings[.GCC_PREPROCESSOR_DEFINITIONS],\n                            [\"$(inherited)\", \"SWIFT_PACKAGE\", \"DEBUG=1\"]\n                        )\n                        XCTAssertEqual(settings[.IPHONEOS_DEPLOYMENT_TARGET], \"12.0\")\n                        XCTAssertEqual(settings[.IPHONEOS_DEPLOYMENT_TARGET, for: .macCatalyst], \"13.0\")\n                        XCTAssertEqual(settings[.KEEP_PRIVATE_EXTERNS], \"NO\")\n                        XCTAssertEqual(settings[.MACOSX_DEPLOYMENT_TARGET], \"10.14\")\n                        XCTAssertEqual(settings[.ONLY_ACTIVE_ARCH], \"YES\")\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                        XCTAssertEqual(settings[.SDK_VARIANT], \"auto\")\n                        XCTAssertEqual(settings[.SDKROOT], \"auto\")\n                        XCTAssertEqual(settings[.SKIP_INSTALL], \"YES\")\n                        XCTAssertEqual(settings[.SUPPORTED_PLATFORMS], [\"$(AVAILABLE_PLATFORMS)\"])\n                        XCTAssertEqual(\n                            settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                            [\"$(inherited)\", \"SWIFT_PACKAGE\", \"DEBUG\"]\n                        )\n                        XCTAssertEqual(settings[.SWIFT_INSTALL_OBJC_HEADER], \"NO\")\n                        XCTAssertEqual(settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME], \"\")\n                        XCTAssertEqual(settings[.SWIFT_OPTIMIZATION_LEVEL], \"-Onone\")\n                        XCTAssertEqual(settings[.TVOS_DEPLOYMENT_TARGET], \"12.0\")\n                        XCTAssertEqual(settings[.USE_HEADERMAP], \"NO\")\n                        XCTAssertEqual(settings[.WATCHOS_DEPLOYMENT_TARGET], \"6.0\")\n                        XCTAssertEqual(settings[.XROS_DEPLOYMENT_TARGET], \"1.0\")\n\n                        let frameworksSearchPaths = [\"$(inherited)\", \"$(PLATFORM_DIR)/Developer/Library/Frameworks\"]\n                        for platform in [PIF.BuildSettings.Platform.macOS, .iOS, .tvOS] {\n                            XCTAssertEqual(settings[.FRAMEWORK_SEARCH_PATHS, for: platform], frameworksSearchPaths)\n                        }\n\n                        for platform in PIF.BuildSettings.Platform.allCases {\n                            XCTAssertEqual(settings[.SPECIALIZATION_SDK_OPTIONS, for: platform], nil)\n                        }\n                    }\n                }\n\n                project.checkBuildConfiguration(\"Release\") { configuration in\n                    XCTAssertEqual(configuration.guid, \"PACKAGE:/Bar::BUILDCONFIG_Release\")\n                    XCTAssertEqual(configuration.name, \"Release\")\n\n                    configuration.checkAllBuildSettings { settings in\n                        XCTAssertEqual(settings[.CLANG_ENABLE_OBJC_ARC], \"YES\")\n                        XCTAssertEqual(settings[.CODE_SIGN_IDENTITY], \"\")\n                        XCTAssertEqual(settings[.CODE_SIGNING_REQUIRED], \"NO\")\n                        XCTAssertEqual(settings[.COPY_PHASE_STRIP], \"YES\")\n                        XCTAssertEqual(settings[.DEBUG_INFORMATION_FORMAT], \"dwarf-with-dsym\")\n                        XCTAssertEqual(settings[.DRIVERKIT_DEPLOYMENT_TARGET], \"19.0\")\n                        XCTAssertEqual(settings[.DYLIB_INSTALL_NAME_BASE], \"@rpath\")\n                        XCTAssertEqual(settings[.ENABLE_TESTING_SEARCH_PATHS], \"YES\")\n                        XCTAssertEqual(settings[.ENTITLEMENTS_REQUIRED], \"NO\")\n                        XCTAssertEqual(settings[.GCC_OPTIMIZATION_LEVEL], \"s\")\n                        XCTAssertEqual(settings[.GCC_PREPROCESSOR_DEFINITIONS], [\"$(inherited)\", \"SWIFT_PACKAGE\"])\n                        XCTAssertEqual(settings[.IPHONEOS_DEPLOYMENT_TARGET], \"12.0\")\n                        XCTAssertEqual(settings[.IPHONEOS_DEPLOYMENT_TARGET, for: .macCatalyst], \"13.0\")\n                        XCTAssertEqual(settings[.KEEP_PRIVATE_EXTERNS], \"NO\")\n                        XCTAssertEqual(settings[.MACOSX_DEPLOYMENT_TARGET], \"10.14\")\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                        XCTAssertEqual(settings[.SDK_VARIANT], \"auto\")\n                        XCTAssertEqual(settings[.SDKROOT], \"auto\")\n                        XCTAssertEqual(settings[.SKIP_INSTALL], \"YES\")\n                        XCTAssertEqual(settings[.SUPPORTED_PLATFORMS], [\"$(AVAILABLE_PLATFORMS)\"])\n                        XCTAssertEqual(\n                            settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                            [\"$(inherited)\", \"SWIFT_PACKAGE\"]\n                        )\n                        XCTAssertEqual(settings[.SWIFT_INSTALL_OBJC_HEADER], \"NO\")\n                        XCTAssertEqual(settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME], \"\")\n                        XCTAssertEqual(settings[.SWIFT_OPTIMIZATION_LEVEL], \"-Owholemodule\")\n                        XCTAssertEqual(settings[.TVOS_DEPLOYMENT_TARGET], \"12.0\")\n                        XCTAssertEqual(settings[.USE_HEADERMAP], \"NO\")\n                        XCTAssertEqual(settings[.WATCHOS_DEPLOYMENT_TARGET], \"6.0\")\n                        XCTAssertEqual(settings[.XROS_DEPLOYMENT_TARGET], \"1.0\")\n\n                        let frameworksSearchPaths = [\"$(inherited)\", \"$(PLATFORM_DIR)/Developer/Library/Frameworks\"]\n                        for platform in [PIF.BuildSettings.Platform.macOS, .iOS, .tvOS] {\n                            XCTAssertEqual(settings[.FRAMEWORK_SEARCH_PATHS, for: platform], frameworksSearchPaths)\n                        }\n\n                        for platform in PIF.BuildSettings.Platform.allCases {\n                            XCTAssertEqual(settings[.SPECIALIZATION_SDK_OPTIONS, for: platform], nil)\n                        }\n                    }\n                }\n            }\n\n            try workspace.checkProject(\"AGGREGATE\") { project in\n                project.checkAggregateTarget(\"ALL-EXCLUDING-TESTS\") { target in\n                    XCTAssertEqual(target.name, PIFBuilder.allExcludingTestsTargetName)\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-PRODUCT:foo\"])\n                }\n\n                project.checkAggregateTarget(\"ALL-INCLUDING-TESTS\") { target in\n                    XCTAssertEqual(target.name, PIFBuilder.allIncludingTestsTargetName)\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-PRODUCT:foo\", \"PACKAGE-PRODUCT:FooTests\"])\n                }\n            }\n        }\n    }\n\n    func testExecutableProducts() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Sources/cfoo/main.c\",\n            \"/Foo/Sources/FooLib/lib.swift\",\n            \"/Foo/Sources/SystemLib/module.modulemap\",\n            \"/Bar/Sources/bar/main.swift\",\n            \"/Bar/Sources/cbar/main.c\",\n            \"/Bar/Sources/BarLib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    swiftLanguageVersions: [.v4_2, .v5],\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .branch(\"main\")),\n                    ],\n                    targets: [\n                        .init(name: \"foo\", dependencies: [\n                            \"FooLib\",\n                            \"SystemLib\",\n                            \"cfoo\",\n                            .product(name: \"bar\", package: \"Bar\"),\n                            .product(name: \"cbar\", package: \"Bar\"),\n                        ]),\n                        .init(name: \"cfoo\"),\n                        .init(name: \"SystemLib\", type: .system, pkgConfig: \"Foo\"),\n                        .init(name: \"FooLib\", dependencies: [\n                            .product(name: \"BarLib\", package: \"Bar\"),\n                        ]),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v4_2,\n                    cLanguageStandard: \"c11\",\n                    cxxLanguageStandard: \"c++14\",\n                    swiftLanguageVersions: [.v4_2],\n                    products: [\n                        .init(name: \"bar\", type: .executable, targets: [\"bar\"]),\n                        .init(name: \"cbar\", type: .executable, targets: [\"cbar\"]),\n                        .init(name: \"BarLib\", type: .library(.static), targets: [\"BarLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"bar\", dependencies: [\"BarLib\"]),\n                        .init(name: \"cbar\"),\n                        .init(name: \"BarLib\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        var pif: PIF.TopLevelObject!\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": self.inputsDir.pathString]) {\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(),\n                fileSystem: localFileSystem,\n                observabilityScope: observability.topScope\n            )\n            pif = try builder.construct()\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n\n                // Root Swift executable target\n\n                project.checkTarget(\"PACKAGE-PRODUCT:foo\") { target in\n                    XCTAssertEqual(target.name, \"foo_1EF26F7F_PackageProduct\")\n                    XCTAssertEqual(target.productType, .executable)\n                    XCTAssertEqual(target.productName, \"foo\")\n                    XCTAssertEqual(target.dependencies, [\n                        \"PACKAGE-PRODUCT:cfoo\",\n                        \"PACKAGE-PRODUCT:bar\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                        \"PACKAGE-PRODUCT:cbar\",\n                        \"PACKAGE-TARGET:FooLib\",\n                        \"PACKAGE-TARGET:SystemLib\",\n                    ])\n                    XCTAssertEqual(target.sources, [\"/Foo/Sources/foo/main.swift\"])\n                    XCTAssertEqual(target.frameworks, [\n                        \"PACKAGE-TARGET:FooLib\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                        \"PACKAGE-PRODUCT:cbar\",\n                        \"PACKAGE-PRODUCT:bar\",\n                    ])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:foo::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.INSTALL_PATH], \"/usr/local/bin\")\n                            XCTAssertEqual(\n                                settings[.LD_RUNPATH_SEARCH_PATHS],\n                                [\"$(inherited)\", \"@executable_path/../lib\"]\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"foo\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"foo\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SKIP_INSTALL], \"NO\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"5\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"foo\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:foo::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.INSTALL_PATH], \"/usr/local/bin\")\n                            XCTAssertEqual(\n                                settings[.LD_RUNPATH_SEARCH_PATHS],\n                                [\"$(inherited)\", \"@executable_path/../lib\"]\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"foo\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"foo\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SKIP_INSTALL], \"NO\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"5\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"foo\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkNoImpartedBuildSettings()\n                }\n\n                // Root Clang executable target\n\n                project.checkTarget(\"PACKAGE-PRODUCT:cfoo\") { target in\n                    XCTAssertEqual(target.name, \"cfoo_7BF40D05B_PackageProduct\")\n                    XCTAssertEqual(target.productType, .executable)\n                    XCTAssertEqual(target.productName, \"cfoo\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.sources, [\"/Foo/Sources/cfoo/main.c\"])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:cfoo::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(\n                                settings[.HEADER_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/Foo/Sources/cfoo/include\"]\n                            )\n                            XCTAssertEqual(settings[.INSTALL_PATH], \"/usr/local/bin\")\n                            XCTAssertEqual(\n                                settings[.LD_RUNPATH_SEARCH_PATHS],\n                                [\"$(inherited)\", \"@executable_path/../lib\"]\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"cfoo\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"cfoo\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SKIP_INSTALL], \"NO\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"cfoo\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:cfoo::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(\n                                settings[.HEADER_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/Foo/Sources/cfoo/include\"]\n                            )\n                            XCTAssertEqual(settings[.INSTALL_PATH], \"/usr/local/bin\")\n                            XCTAssertEqual(\n                                settings[.LD_RUNPATH_SEARCH_PATHS],\n                                [\"$(inherited)\", \"@executable_path/../lib\"]\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"cfoo\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"cfoo\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SKIP_INSTALL], \"NO\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"cfoo\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                        }\n                    }\n\n                    target.checkNoImpartedBuildSettings()\n                }\n            }\n\n            try workspace.checkProject(\"PACKAGE:/Bar\") { project in\n\n                // Non-root Swift executable target\n\n                project.checkTarget(\"PACKAGE-PRODUCT:bar\") { target in\n                    XCTAssertEqual(target.name, \"bar_1ECDA8F8_PackageProduct\")\n                    XCTAssertEqual(target.productType, .executable)\n                    XCTAssertEqual(target.productName, \"bar\")\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-TARGET:BarLib\"])\n                    XCTAssertEqual(target.sources, [\"/Bar/Sources/bar/main.swift\"])\n                    XCTAssertEqual(target.frameworks, [\"PACKAGE-TARGET:BarLib\"])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:bar::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"bar\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"bar\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"4.2\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"bar\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:bar::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"bar\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"bar\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"4.2\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"bar\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkNoImpartedBuildSettings()\n                }\n\n                // Non-root Clang executable target\n\n                project.checkTarget(\"PACKAGE-PRODUCT:cbar\") { target in\n                    XCTAssertEqual(target.name, \"cbar_7BEFB595C_PackageProduct\")\n                    XCTAssertEqual(target.productType, .executable)\n                    XCTAssertEqual(target.productName, \"cbar\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.sources, [\"/Bar/Sources/cbar/main.c\"])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:cbar::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_CXX_LANGUAGE_STANDARD], \"c++14\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GCC_C_LANGUAGE_STANDARD], \"c11\")\n                            XCTAssertEqual(\n                                settings[.HEADER_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/Bar/Sources/cbar/include\"]\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"cbar\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"cbar\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"cbar\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:cbar::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_CXX_LANGUAGE_STANDARD], \"c++14\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GCC_C_LANGUAGE_STANDARD], \"c11\")\n                            XCTAssertEqual(\n                                settings[.HEADER_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/Bar/Sources/cbar/include\"]\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"cbar\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"cbar\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"cbar\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                        }\n                    }\n\n                    target.checkNoImpartedBuildSettings()\n                }\n            }\n        }\n    }\n\n    func testTestProducts() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/FooTests/FooTests.swift\",\n            \"/Foo/Sources/CFooTests/CFooTests.m\",\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Sources/FooLib/lib.swift\",\n            \"/Foo/Sources/SystemLib/module.modulemap\",\n            \"/Bar/Sources/bar/main.swift\",\n            \"/Bar/Sources/BarTests/BarTests.swift\",\n            \"/Bar/Sources/CBarTests/CBarTests.m\",\n            \"/Bar/Sources/BarLib/lib.swift\",\n            inputsDir.appending(\"Foo.pc\").pathString\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    swiftLanguageVersions: [.v4_2, .v5],\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .branch(\"main\")),\n                    ],\n                    targets: [\n                        .init(name: \"FooTests\", dependencies: [\n                            \"foo\",\n                            \"FooLib\",\n                            .product(name: \"bar\", package: \"Bar\"),\n                            \"SystemLib\",\n                        ], type: .test),\n                        .init(name: \"CFooTests\", type: .test),\n                        .init(name: \"foo\"),\n                        .init(name: \"SystemLib\", type: .system, pkgConfig: \"Foo\"),\n                        .init(name: \"FooLib\", dependencies: [\n                            .product(name: \"BarLib\", package: \"Bar\"),\n                        ]),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v4_2,\n                    cLanguageStandard: \"c11\",\n                    cxxLanguageStandard: \"c++14\",\n                    swiftLanguageVersions: [.v4_2],\n                    products: [\n                        .init(name: \"bar\", type: .executable, targets: [\"bar\"]),\n                        .init(name: \"BarLib\", type: .library(.static), targets: [\"BarLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"bar\", dependencies: [\"BarLib\"]),\n                        .init(name: \"BarTests\", dependencies: [\"BarLib\"], type: .test),\n                        .init(name: \"CBarTests\", type: .test),\n                        .init(name: \"BarLib\"),\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        var pif: PIF.TopLevelObject!\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": self.inputsDir.pathString]) {\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(),\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            pif = try builder.construct()\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:FooTests\") { target in\n                    XCTAssertEqual(target.name, \"FooTests_-5E24708DC81AF5C1_PackageProduct\")\n                    XCTAssertEqual(target.productType, .unitTest)\n                    XCTAssertEqual(target.productName, \"FooTests\")\n                    XCTAssertEqual(target.dependencies, [\n                        \"PACKAGE-PRODUCT:foo\",\n                        \"PACKAGE-PRODUCT:bar\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                        \"PACKAGE-TARGET:FooLib\",\n                        \"PACKAGE-TARGET:SystemLib\",\n                    ])\n                    XCTAssertEqual(target.sources, [\"/Foo/Sources/FooTests/FooTests.swift\"])\n                    XCTAssertEqual(target.frameworks, [\n                        \"PACKAGE-PRODUCT:bar\",\n                        \"PACKAGE-TARGET:FooLib\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:FooTests::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.LD_RUNPATH_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"@loader_path/Frameworks\",\n                                \"@loader_path/../Frameworks\",\n                            ])\n                            XCTAssertEqual(settings[.LIBRARY_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"/toolchain/lib/swift/macosx\",\n                            ])\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"FooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"FooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"5\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"FooTests\")\n                            XCTAssertEqual(\n                                settings[.WATCHOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .watchOS)\n                                    .versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.IPHONEOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .iOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.TVOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .tvOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.MACOSX_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .macOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.XROS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .visionOS)\n                                    .versionString\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:FooTests::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.LD_RUNPATH_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"@loader_path/Frameworks\",\n                                \"@loader_path/../Frameworks\",\n                            ])\n                            XCTAssertEqual(settings[.LIBRARY_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"/toolchain/lib/swift/macosx\",\n                            ])\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"FooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"FooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"5\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"FooTests\")\n                            XCTAssertEqual(\n                                settings[.WATCHOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .watchOS)\n                                    .versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.IPHONEOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .iOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.TVOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .tvOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.MACOSX_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .macOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.XROS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .visionOS)\n                                    .versionString\n                            )\n                        }\n                    }\n\n                    target.checkNoImpartedBuildSettings()\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:CFooTests\") { target in\n                    XCTAssertEqual(target.name, \"CFooTests_A328606A9BCFA83_PackageProduct\")\n                    XCTAssertEqual(target.productType, .unitTest)\n                    XCTAssertEqual(target.productName, \"CFooTests\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.sources, [\"/Foo/Sources/CFooTests/CFooTests.m\"])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:CFooTests::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"/Foo/Sources/CFooTests/include\",\n                            ])\n                            XCTAssertEqual(settings[.LD_RUNPATH_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"@loader_path/Frameworks\",\n                                \"@loader_path/../Frameworks\",\n                            ])\n                            XCTAssertEqual(settings[.LIBRARY_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"/toolchain/lib/swift/macosx\",\n                            ])\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"CFooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"CFooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"CFooTests\")\n                            XCTAssertEqual(\n                                settings[.WATCHOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .watchOS)\n                                    .versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.IPHONEOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .iOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.TVOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .tvOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.MACOSX_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .macOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.XROS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .visionOS)\n                                    .versionString\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:CFooTests::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"/Foo/Sources/CFooTests/include\",\n                            ])\n                            XCTAssertEqual(settings[.LD_RUNPATH_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"@loader_path/Frameworks\",\n                                \"@loader_path/../Frameworks\",\n                            ])\n                            XCTAssertEqual(settings[.LIBRARY_SEARCH_PATHS], [\n                                \"$(inherited)\",\n                                \"/toolchain/lib/swift/macosx\",\n                            ])\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"CFooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"CFooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"CFooTests\")\n                            XCTAssertEqual(\n                                settings[.WATCHOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .watchOS)\n                                    .versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.IPHONEOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .iOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.TVOS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .tvOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.MACOSX_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .macOS).versionString\n                            )\n                            XCTAssertEqual(\n                                settings[.XROS_DEPLOYMENT_TARGET],\n                                MinimumDeploymentTarget.computeXCTestMinimumDeploymentTarget(for: .visionOS)\n                                    .versionString\n                            )\n                        }\n                    }\n\n                    target.checkNoImpartedBuildSettings()\n                }\n            }\n\n            try workspace.checkProject(\"PACKAGE:/Bar\") { project in\n                project.checkNoTarget(\"PACKAGE-PRODUCT:BarTests\")\n                project.checkNoTarget(\"PACKAGE-PRODUCT:CBarTests\")\n            }\n        }\n    }\n\n    func testLibraryProducts() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/FooLib1/lib.swift\",\n            \"/Foo/Sources/FooLib2/lib.swift\",\n            \"/Foo/Sources/SystemLib/module.modulemap\",\n            \"/Bar/Sources/BarLib/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    swiftLanguageVersions: [.v4_2, .v5],\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .branch(\"main\")),\n                    ],\n                    products: [\n                        .init(name: \"FooLib1\", type: .library(.static), targets: [\"FooLib1\"]),\n                        .init(name: \"FooLib2\", type: .library(.automatic), targets: [\"FooLib2\"]),\n                    ],\n                    targets: [\n                        .init(name: \"FooLib1\", dependencies: [\"SystemLib\", \"FooLib2\"]),\n                        .init(name: \"FooLib2\", dependencies: [\n                            .product(name: \"BarLib\", package: \"Bar\"),\n                        ]),\n                        .init(name: \"SystemLib\", type: .system, pkgConfig: \"Foo\"),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v4_2,\n                    cLanguageStandard: \"c11\",\n                    cxxLanguageStandard: \"c++14\",\n                    swiftLanguageVersions: [.v4_2],\n                    products: [\n                        .init(name: \"BarLib\", type: .library(.dynamic), targets: [\"BarLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"BarLib\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        var pif: PIF.TopLevelObject!\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": self.inputsDir.pathString]) {\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(),\n                fileSystem: localFileSystem,\n                observabilityScope: observability.topScope\n            )\n            pif = try builder.construct()\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:FooLib1\") { target in\n                    XCTAssertEqual(target.name, \"FooLib1_32B0F01AD0DD0FF3_PackageProduct\")\n                    XCTAssertEqual(target.productType, .packageProduct)\n                    XCTAssertEqual(target.productName, \"libFooLib1.a\")\n                    XCTAssertEqual(target.dependencies, [\n                        \"PACKAGE-TARGET:FooLib1\",\n                        \"PACKAGE-TARGET:FooLib2\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n                    XCTAssertEqual(target.sources, [])\n                    XCTAssertEqual(target.frameworks, [\n                        \"PACKAGE-TARGET:FooLib1\",\n                        \"PACKAGE-TARGET:FooLib2\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:FooLib1::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.USES_SWIFTPM_UNSAFE_FLAGS], \"NO\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:FooLib1::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.USES_SWIFTPM_UNSAFE_FLAGS], \"NO\")\n                        }\n                    }\n\n                    target.checkAllImpartedBuildSettings { _ in\n                        // No imparted build settings.\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:FooLib2\") { target in\n                    XCTAssertEqual(target.name, \"FooLib2_32B0F01AD0DD1074_PackageProduct\")\n                    XCTAssertEqual(target.productType, .packageProduct)\n                    XCTAssertEqual(target.productName, \"libFooLib2.a\")\n                    XCTAssertEqual(target.dependencies, [\n                        \"PACKAGE-TARGET:FooLib2\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n                    XCTAssertEqual(target.sources, [])\n                    XCTAssertEqual(target.frameworks, [\n                        \"PACKAGE-TARGET:FooLib2\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:FooLib2::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.USES_SWIFTPM_UNSAFE_FLAGS], \"NO\")\n                            XCTAssertEqual(settings[.APPLICATION_EXTENSION_API_ONLY], \"YES\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:FooLib2::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.USES_SWIFTPM_UNSAFE_FLAGS], \"NO\")\n                            XCTAssertEqual(settings[.APPLICATION_EXTENSION_API_ONLY], \"YES\")\n                        }\n                    }\n\n                    target.checkNoImpartedBuildSettings()\n                }\n            }\n\n            try workspace.checkProject(\"PACKAGE:/Bar\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:BarLib\") { target in\n                    XCTAssertEqual(target.name, \"BarLib_175D063FAE17B2_PackageProduct\")\n                    XCTAssertEqual(target.productType, .framework)\n                    XCTAssertEqual(target.productName, \"BarLib.framework\")\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-TARGET:BarLib\"])\n                    XCTAssertEqual(target.sources, [])\n                    XCTAssertEqual(target.frameworks, [\"PACKAGE-TARGET:BarLib\"])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:BarLib::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.USES_SWIFTPM_UNSAFE_FLAGS], \"NO\")\n                            XCTAssertEqual(settings[.APPLICATION_EXTENSION_API_ONLY], \"YES\")\n                            XCTAssertEqual(settings[.BUILT_PRODUCTS_DIR], \"$(BUILT_PRODUCTS_DIR)/PackageFrameworks\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.CURRENT_PROJECT_VERSION], \"1\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.EXECUTABLE_PREFIX], \"lib\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.INSTALL_PATH], \"/usr/local/lib\")\n                            XCTAssertEqual(settings[.MARKETING_VERSION], \"1.0\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SKIP_INSTALL], \"NO\")\n                            XCTAssertEqual(settings[.TARGET_BUILD_DIR], \"$(TARGET_BUILD_DIR)/PackageFrameworks\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"BarLib\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:BarLib::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.APPLICATION_EXTENSION_API_ONLY], \"YES\")\n                            XCTAssertEqual(settings[.BUILT_PRODUCTS_DIR], \"$(BUILT_PRODUCTS_DIR)/PackageFrameworks\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.CURRENT_PROJECT_VERSION], \"1\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.EXECUTABLE_PREFIX], \"lib\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.INSTALL_PATH], \"/usr/local/lib\")\n                            XCTAssertEqual(settings[.MARKETING_VERSION], \"1.0\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.SKIP_INSTALL], \"NO\")\n                            XCTAssertEqual(settings[.TARGET_BUILD_DIR], \"$(TARGET_BUILD_DIR)/PackageFrameworks\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"BarLib\")\n                            XCTAssertEqual(settings[.USES_SWIFTPM_UNSAFE_FLAGS], \"NO\")\n                            XCTAssertEqual(\n                                settings[.LIBRARY_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/toolchain/lib/swift/macosx\"]\n                            )\n                        }\n                    }\n\n                    target.checkNoImpartedBuildSettings()\n                }\n            }\n        }\n    }\n\n    func testLibraryTargets() async throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/FooLib1/lib.swift\",\n            \"/Foo/Sources/FooLib2/lib.cpp\",\n            \"/Foo/Sources/SystemLib/module.modulemap\",\n            \"/Bar/Sources/BarLib/lib.c\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    cxxLanguageStandard: \"c++14\",\n                    swiftLanguageVersions: [.v4_2, .v5],\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .branch(\"main\")),\n                    ],\n                    targets: [\n                        .init(name: \"FooLib1\", dependencies: [\"SystemLib\", \"FooLib2\"]),\n                        .init(name: \"FooLib2\", dependencies: [\n                            .product(name: \"BarLib\", package: \"Bar\"),\n                        ]),\n                        .init(name: \"SystemLib\", type: .system, pkgConfig: \"Foo\"),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v4_2,\n                    cLanguageStandard: \"c11\",\n                    swiftLanguageVersions: [.v4_2],\n                    products: [\n                        .init(name: \"BarLib\", type: .library(.dynamic), targets: [\"BarLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"BarLib\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        var pif: PIF.TopLevelObject!\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": self.inputsDir.pathString]) {\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(),\n                fileSystem: localFileSystem,\n                observabilityScope: observability.topScope\n            )\n            pif = try builder.construct()\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-TARGET:FooLib1\") { target in\n                    XCTAssertEqual(target.name, \"FooLib1\")\n                    XCTAssertEqual(target.productType, .objectFile)\n                    XCTAssertEqual(target.productName, \"FooLib1_Module.o\")\n                    XCTAssertEqual(target.dependencies, [\n                        \"PACKAGE-TARGET:FooLib2\",\n                        \"PACKAGE-TARGET:SystemLib\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n                    XCTAssertEqual(target.sources, [\"/Foo/Sources/FooLib1/lib.swift\"])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:FooLib1::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_COVERAGE_MAPPING_LINKER_ARGS], \"NO\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GENERATE_MASTER_OBJECT_FILE], \"NO\")\n                            XCTAssertEqual(settings[.MACH_O_TYPE], \"mh_object\")\n                            XCTAssertEqual(settings[.MODULEMAP_FILE_CONTENTS], \"\"\"\n                            module FooLib1 {\n                                header \"FooLib1-Swift.h\"\n                                export *\n                            }\n                            \"\"\")\n                            XCTAssertEqual(\n                                settings[.MODULEMAP_PATH],\n                                \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/FooLib1.modulemap\"\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"FooLib1\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"FooLib1\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_OBJC_INTERFACE_HEADER_DIR],\n                                \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)\"\n                            )\n                            XCTAssertEqual(settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME], \"FooLib1-Swift.h\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"5\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"FooLib1_Module\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:FooLib1::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_COVERAGE_MAPPING_LINKER_ARGS], \"NO\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GENERATE_MASTER_OBJECT_FILE], \"NO\")\n                            XCTAssertEqual(settings[.MACH_O_TYPE], \"mh_object\")\n                            XCTAssertEqual(settings[.MODULEMAP_FILE_CONTENTS], \"\"\"\n                            module FooLib1 {\n                                header \"FooLib1-Swift.h\"\n                                export *\n                            }\n                            \"\"\")\n                            XCTAssertEqual(\n                                settings[.MODULEMAP_PATH],\n                                \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/FooLib1.modulemap\"\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"FooLib1\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"FooLib1\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_OBJC_INTERFACE_HEADER_DIR],\n                                \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)\"\n                            )\n                            XCTAssertEqual(settings[.SWIFT_OBJC_INTERFACE_HEADER_NAME], \"FooLib1-Swift.h\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"5\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"FooLib1_Module\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkAllImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.OTHER_CFLAGS], [\n                            \"$(inherited)\",\n                            \"-fmodule-map-file=$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/FooLib1.modulemap\",\n                        ])\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(settings[.OTHER_LDFLAGS], [\"$(inherited)\", \"-Wl,-no_warn_duplicate_libraries\"])\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-TARGET:FooLib2\") { target in\n                    XCTAssertEqual(target.name, \"FooLib2\")\n                    XCTAssertEqual(target.productType, .objectFile)\n                    XCTAssertEqual(target.productName, \"FooLib2_Module.o\")\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-PRODUCT:BarLib\"])\n                    XCTAssertEqual(target.sources, [\"/Foo/Sources/FooLib2/lib.cpp\"])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:FooLib2::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_COVERAGE_MAPPING_LINKER_ARGS], \"NO\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.CLANG_CXX_LANGUAGE_STANDARD], \"c++14\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GENERATE_MASTER_OBJECT_FILE], \"NO\")\n                            XCTAssertEqual(\n                                settings[.HEADER_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/Foo/Sources/FooLib2/include\"]\n                            )\n                            XCTAssertEqual(settings[.MACH_O_TYPE], \"mh_object\")\n                            XCTAssertEqual(settings[.MODULEMAP_FILE_CONTENTS], \"\"\"\n                            module FooLib2 {\n                                umbrella \"/Foo/Sources/FooLib2/include\"\n                                export *\n                            }\n                            \"\"\")\n                            XCTAssertEqual(\n                                settings[.MODULEMAP_PATH],\n                                \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/FooLib2.modulemap\"\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"FooLib2\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"FooLib2\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"FooLib2_Module\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:FooLib2::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_COVERAGE_MAPPING_LINKER_ARGS], \"NO\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.CLANG_CXX_LANGUAGE_STANDARD], \"c++14\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GENERATE_MASTER_OBJECT_FILE], \"NO\")\n                            XCTAssertEqual(\n                                settings[.HEADER_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/Foo/Sources/FooLib2/include\"]\n                            )\n                            XCTAssertEqual(settings[.MACH_O_TYPE], \"mh_object\")\n                            XCTAssertEqual(settings[.MODULEMAP_FILE_CONTENTS], \"\"\"\n                            module FooLib2 {\n                                umbrella \"/Foo/Sources/FooLib2/include\"\n                                export *\n                            }\n                            \"\"\")\n                            XCTAssertEqual(\n                                settings[.MODULEMAP_PATH],\n                                \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/FooLib2.modulemap\"\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"FooLib2\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"FooLib2\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"FooLib2_Module\")\n                        }\n                    }\n\n                    target.checkAllImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], [\"$(inherited)\", \"/Foo/Sources/FooLib2/include\"])\n                        XCTAssertEqual(settings[.OTHER_CFLAGS], [\n                            \"$(inherited)\",\n                            \"-fmodule-map-file=$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/FooLib2.modulemap\",\n                        ])\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(\n                            settings[.OTHER_LDFLAGS],\n                            [\"$(inherited)\", \"-lc++\", \"-Wl,-no_warn_duplicate_libraries\"]\n                        )\n                        XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], [\n                            \"$(inherited)\",\n                            \"-Xcc\",\n                            \"-fmodule-map-file=$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/FooLib2.modulemap\",\n                        ])\n                    }\n                }\n            }\n\n            try workspace.checkProject(\"PACKAGE:/Bar\") { project in\n                project.checkTarget(\"PACKAGE-TARGET:BarLib\") { target in\n                    XCTAssertEqual(target.name, \"BarLib\")\n                    XCTAssertEqual(target.productType, .objectFile)\n                    XCTAssertEqual(target.productName, \"BarLib_Module.o\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.sources, [\"/Bar/Sources/BarLib/lib.c\"])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:BarLib::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_COVERAGE_MAPPING_LINKER_ARGS], \"NO\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GCC_C_LANGUAGE_STANDARD], \"c11\")\n                            XCTAssertEqual(settings[.GENERATE_MASTER_OBJECT_FILE], \"NO\")\n                            XCTAssertEqual(\n                                settings[.HEADER_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/Bar/Sources/BarLib/include\"]\n                            )\n                            XCTAssertEqual(settings[.MACH_O_TYPE], \"mh_object\")\n                            XCTAssertEqual(settings[.MODULEMAP_FILE_CONTENTS], \"\"\"\n                            module BarLib {\n                                umbrella \"/Bar/Sources/BarLib/include\"\n                                export *\n                            }\n                            \"\"\")\n                            XCTAssertEqual(\n                                settings[.MODULEMAP_PATH],\n                                \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/BarLib.modulemap\"\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"BarLib_Module\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:BarLib::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.CLANG_COVERAGE_MAPPING_LINKER_ARGS], \"NO\")\n                            XCTAssertEqual(settings[.CLANG_ENABLE_MODULES], \"YES\")\n                            XCTAssertEqual(settings[.DEFINES_MODULE], \"YES\")\n                            XCTAssertEqual(settings[.GCC_C_LANGUAGE_STANDARD], \"c11\")\n                            XCTAssertEqual(settings[.GENERATE_MASTER_OBJECT_FILE], \"NO\")\n                            XCTAssertEqual(\n                                settings[.HEADER_SEARCH_PATHS],\n                                [\"$(inherited)\", \"/Bar/Sources/BarLib/include\"]\n                            )\n                            XCTAssertEqual(settings[.MACH_O_TYPE], \"mh_object\")\n                            XCTAssertEqual(settings[.MODULEMAP_FILE_CONTENTS], \"\"\"\n                            module BarLib {\n                                umbrella \"/Bar/Sources/BarLib/include\"\n                                export *\n                            }\n                            \"\"\")\n                            XCTAssertEqual(\n                                settings[.MODULEMAP_PATH],\n                                \"$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/BarLib.modulemap\"\n                            )\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"regular\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"BarLib_Module\")\n                        }\n                    }\n\n                    target.checkAllImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], [\"$(inherited)\", \"/Bar/Sources/BarLib/include\"])\n                        XCTAssertEqual(settings[.OTHER_CFLAGS], [\n                            \"$(inherited)\",\n                            \"-fmodule-map-file=$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/BarLib.modulemap\",\n                        ])\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(settings[.OTHER_LDFLAGS], [\"$(inherited)\", \"-Wl,-no_warn_duplicate_libraries\"])\n                        XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], [\n                            \"$(inherited)\",\n                            \"-Xcc\",\n                            \"-fmodule-map-file=$(OBJROOT)/GeneratedModuleMaps/$(PLATFORM_NAME)/BarLib.modulemap\",\n                        ])\n                    }\n                }\n            }\n        }\n    }\n\n    func testPIFGenWithModuleAliases() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/App/Sources/App/main.swift\",\n            \"/App/Sources/Logging/lib.swift\",\n            \"/App/Sources/Utils/lib.swift\",\n            \"/Bar/Sources/Lib/lib.swift\",\n            \"/Bar/Sources/Logging/lib.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"App\",\n                    path: \"/App\",\n                    dependencies: [\n                        .localSourceControl(path: \"/Bar\", requirement: .branch(\"main\")),\n                    ],\n                    targets: [\n                        .init(name: \"App\", dependencies: [\"Logging\", \"Utils\"], type: .executable),\n                        .init(name: \"Logging\", dependencies: []),\n                        .init(name: \"Utils\", dependencies: [\n                            .product(name: \"BarLib\", package: \"Bar\", moduleAliases: [\"Logging\": \"BarLogging\"]),\n                        ]),\n                    ]\n                ),\n                Manifest.createLocalSourceControlManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    products: [\n                        .init(name: \"BarLib\", type: .library(.dynamic), targets: [\"Lib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"Lib\", dependencies: [\"Logging\"]),\n                        .init(name: \"Logging\", dependencies: []),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        var pif: PIF.TopLevelObject!\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": self.inputsDir.pathString]) {\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(),\n                fileSystem: localFileSystem,\n                observabilityScope: observability.topScope\n            )\n            pif = try builder.construct()\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/App\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:App\") { target in\n                    XCTAssertEqual(target.name, \"App_1DA2DD44_PackageProduct\")\n                    XCTAssertEqual(target.productType, .executable)\n                    XCTAssertEqual(target.productName, \"App\")\n                    XCTAssertEqual(target.dependencies, [\n                        \"PACKAGE-TARGET:Utils\",\n                        \"PACKAGE-TARGET:Logging\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n                    XCTAssertEqual(target.frameworks, [\n                        \"PACKAGE-TARGET:Utils\",\n                        \"PACKAGE-TARGET:Logging\",\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:App::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.SWIFT_MODULE_ALIASES])\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:App::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.SWIFT_MODULE_ALIASES])\n                        }\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-TARGET:Utils\") { target in\n                    XCTAssertEqual(target.name, \"Utils\")\n                    XCTAssertEqual(target.productType, .objectFile)\n                    XCTAssertEqual(target.productName, \"Utils_Module.o\")\n                    XCTAssertEqual(target.dependencies, [\n                        \"PACKAGE-PRODUCT:BarLib\",\n                    ])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:Utils::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.SWIFT_MODULE_ALIASES])\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:Utils::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.SWIFT_MODULE_ALIASES])\n                        }\n                    }\n                }\n                project.checkTarget(\"PACKAGE-TARGET:Logging\") { target in\n                    XCTAssertEqual(target.name, \"Logging\")\n                    XCTAssertEqual(target.productType, .objectFile)\n                    XCTAssertEqual(target.productName, \"Logging_Module.o\")\n                    XCTAssertEqual(target.dependencies, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:Logging::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.SWIFT_MODULE_ALIASES])\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:Logging::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.SWIFT_MODULE_ALIASES])\n                        }\n                    }\n                }\n            }\n\n            try workspace.checkProject(\"PACKAGE:/Bar\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:BarLib\") { target in\n                    XCTAssertEqual(target.name, \"BarLib_175D063FAE17B2_PackageProduct\")\n                    XCTAssertEqual(target.productType, .framework)\n                    XCTAssertEqual(target.productName, \"BarLib.framework\")\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-TARGET:BarLogging\", \"PACKAGE-TARGET:Lib\"])\n                    XCTAssertEqual(target.frameworks, [\"PACKAGE-TARGET:BarLogging\", \"PACKAGE-TARGET:Lib\"])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:BarLib::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.SWIFT_MODULE_ALIASES])\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"BarLib\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-PRODUCT:BarLib::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.SWIFT_MODULE_ALIASES])\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"BarLib\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"BarLib\")\n                        }\n                    }\n                }\n                project.checkTarget(\"PACKAGE-TARGET:BarLogging\") { target in\n                    XCTAssertEqual(target.name, \"BarLogging\")\n                    XCTAssertEqual(target.productType, .objectFile)\n                    XCTAssertEqual(target.productName, \"BarLogging_Module.o\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:BarLogging::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.SWIFT_MODULE_ALIASES], [\"Logging=BarLogging\"])\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"BarLogging_Module\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:BarLogging::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.SWIFT_MODULE_ALIASES], [\"Logging=BarLogging\"])\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"BarLogging_Module\")\n                        }\n                    }\n                }\n                project.checkTarget(\"PACKAGE-TARGET:Lib\") { target in\n                    XCTAssertEqual(target.name, \"Lib\")\n                    XCTAssertEqual(target.productType, .objectFile)\n                    XCTAssertEqual(target.productName, \"Lib_Module.o\")\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-TARGET:BarLogging\"])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:Lib::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.SWIFT_MODULE_ALIASES], [\"Logging=BarLogging\"])\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"Lib_Module\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:Lib::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.SWIFT_MODULE_ALIASES], [\"Logging=BarLogging\"])\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.TARGET_NAME], \"Lib_Module\")\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    func testLibraryTargetsAsDylib() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Bar/Sources/BarLib/lib.c\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    toolsVersion: .v4_2,\n                    cLanguageStandard: \"c11\",\n                    swiftLanguageVersions: [.v4_2],\n                    products: [\n                        .init(name: \"BarLib\", type: .library(.dynamic), targets: [\"BarLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"BarLib\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        var pif: PIF.TopLevelObject!\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": self.inputsDir.pathString]) {\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(shouldCreateDylibForDynamicProducts: true),\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            pif = try builder.construct()\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Bar\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:BarLib\") { target in\n                    XCTAssertEqual(target.name, \"BarLib_175D063FAE17B2_PackageProduct\")\n                    XCTAssertEqual(target.productType, .dynamicLibrary)\n                    XCTAssertEqual(target.productName, \"libBarLib.dylib\")\n                }\n            }\n        }\n    }\n\n    func testLibraryTargetWithModuleMap() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Bar/Sources/BarLib/lib.c\",\n            \"/Bar/Sources/BarLib/module.modulemap\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createManifest(\n                    displayName: \"Bar\",\n                    path: \"/Bar\",\n                    packageKind: .root(\"/Bar\"),\n                    packageIdentity: .plain(\"Bar\"),\n                    toolsVersion: .v4_2,\n                    cLanguageStandard: \"c11\",\n                    swiftLanguageVersions: [.v4_2],\n                    products: [\n                        .init(name: \"BarLib\", type: .library(.dynamic), targets: [\"BarLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"BarLib\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        var pif: PIF.TopLevelObject!\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": self.inputsDir.pathString]) {\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(shouldCreateDylibForDynamicProducts: true),\n                fileSystem: fs,\n                observabilityScope: observability.topScope\n            )\n            pif = try builder.construct()\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Bar\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:BarLib\") { target in\n                    XCTAssertEqual(target.name, \"BarLib_175D063FAE17B2_PackageProduct\")\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertNil(settings[.MODULEMAP_FILE_CONTENTS])\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    func testSystemLibraryTargets() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/SystemLib1/module.modulemap\",\n            \"/Foo/Sources/SystemLib2/module.modulemap\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_2,\n                    cxxLanguageStandard: \"c++14\",\n                    swiftLanguageVersions: [.v4_2, .v5],\n                    targets: [\n                        .init(name: \"SystemLib1\", type: .system),\n                        .init(name: \"SystemLib2\", type: .system, pkgConfig: \"Foo\"),\n                    ]\n                ),\n            ],\n            observabilityScope: observability.topScope\n        )\n\n        var pif: PIF.TopLevelObject!\n        try Environment.makeCustom([\"PKG_CONFIG_PATH\": self.inputsDir.pathString]) {\n            let builder = PIFBuilder(\n                graph: graph,\n                parameters: .mock(),\n                fileSystem: localFileSystem,\n                observabilityScope: observability.topScope\n            )\n            pif = try builder.construct()\n        }\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkAggregateTarget(\"PACKAGE-TARGET:SystemLib1\") { target in\n                    XCTAssertEqual(target.name, \"SystemLib1\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.sources, [])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:SystemLib1::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkNoBuildSettings()\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:SystemLib1::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkNoBuildSettings()\n                    }\n\n                    target.checkAllImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.OTHER_CFLAGS], [\n                            \"$(inherited)\",\n                            \"-fmodule-map-file=/Foo/Sources/SystemLib1/module.modulemap\",\n                        ])\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], [\n                            \"$(inherited)\",\n                            \"-Xcc\", \"-fmodule-map-file=/Foo/Sources/SystemLib1/module.modulemap\",\n                        ])\n                    }\n                }\n\n                project.checkAggregateTarget(\"PACKAGE-TARGET:SystemLib2\") { target in\n                    XCTAssertEqual(target.name, \"SystemLib2\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.sources, [])\n                    XCTAssertEqual(target.frameworks, [])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:SystemLib2::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkNoBuildSettings()\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-TARGET:SystemLib2::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkNoBuildSettings()\n                    }\n\n                    target.checkAllImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.OTHER_CFLAGS], [\n                            \"$(inherited)\",\n                            \"-fmodule-map-file=/Foo/Sources/SystemLib2/module.modulemap\",\n                            \"-I/path/to/inc\",\n                            \"-I\\(self.inputsDir)\",\n                        ])\n                        XCTAssertEqual(settings[.OTHER_LDFLAGS], [\n                            \"$(inherited)\",\n                            \"-L/usr/da/lib\",\n                            \"-lSystemModule\",\n                            \"-lok\",\n                        ])\n                        XCTAssertEqual(settings[.OTHER_LDRFLAGS], [])\n                        XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], [\n                            \"$(inherited)\",\n                            \"-Xcc\", \"-fmodule-map-file=/Foo/Sources/SystemLib2/module.modulemap\",\n                            \"-I/path/to/inc\",\n                            \"-I\\(self.inputsDir)\",\n                        ])\n                    }\n                }\n            }\n        }\n    }\n\n    func testBinaryTargets() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Sources/FooLib/lib.swift\",\n            \"/Foo/Sources/FooTests/FooTests.swift\",\n            \"/Foo/BinaryLibrary.xcframework/Info.plist\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_3,\n                    products: [\n                        .init(name: \"FooLib\", type: .library(.automatic), targets: [\"FooLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"foo\", dependencies: [\"BinaryLibrary\"]),\n                        .init(name: \"FooLib\", dependencies: [\"BinaryLibrary\"]),\n                        .init(name: \"FooTests\", dependencies: [\"BinaryLibrary\"], type: .test),\n                        .init(name: \"BinaryLibrary\", path: \"BinaryLibrary.xcframework\", type: .binary),\n                    ]\n                ),\n            ],\n            binaryArtifacts: [\n                .plain(\"foo\"): [\n                    \"BinaryLibrary\": .init(kind: .xcframework, originURL: nil, path: \"/Foo/BinaryLibrary.xcframework\"),\n                ],\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:foo\") { target in\n                    XCTAssert(target.frameworks.contains(\"/Foo/BinaryLibrary.xcframework\"))\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:FooLib\") { target in\n                    XCTAssert(target.frameworks.contains(\"/Foo/BinaryLibrary.xcframework\"))\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:FooTests\") { target in\n                    XCTAssert(target.frameworks.contains(\"/Foo/BinaryLibrary.xcframework\"))\n                }\n\n                project.checkTarget(\"PACKAGE-TARGET:FooLib\") { target in\n                    XCTAssert(target.frameworks.contains(\"/Foo/BinaryLibrary.xcframework\"))\n                }\n            }\n        }\n    }\n\n    func testResources() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Sources/foo/Resources/Data.plist\",\n            \"/Foo/Sources/foo/Resources/Database.xcdatamodel\",\n            \"/Foo/Sources/foo/Resources/Assets.xcassets\",\n            \"/Foo/Sources/foo/Resources/Localizable.xcstrings\",\n            \"/Foo/Sources/FooLib/lib.swift\",\n            \"/Foo/Sources/FooLib/Resources/Data.plist\",\n            \"/Foo/Sources/FooLib/Resources/Database.xcdatamodel\",\n            \"/Foo/Sources/FooLib/Resources/Assets.xcassets\",\n            \"/Foo/Sources/FooLib/Resources/Localizable.xcstrings\",\n            \"/Foo/Sources/FooTests/FooTests.swift\",\n            \"/Foo/Sources/FooTests/Resources/Data.plist\",\n            \"/Foo/Sources/FooTests/Resources/Database.xcdatamodel\",\n            \"/Foo/Sources/FooTests/Resources/Assets.xcassets\",\n            \"/Foo/Sources/FooTests/Resources/Localizable.xcstrings\",\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_9,\n                    products: [\n                        .init(name: \"FooLib\", type: .library(.automatic), targets: [\"FooLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"foo\", resources: [\n                            // This is intentionally specific to test that we pick up `.xcdatamodel` implicitly.\n                            .init(rule: .process(localization: .none), path: \"Resources/Data.plist\"),\n                        ], type: .executable),\n                        .init(name: \"FooLib\", resources: [\n                            .init(rule: .process(localization: .none), path: \"Resources\"),\n                        ]),\n                        .init(name: \"FooTests\", resources: [\n                            .init(rule: .process(localization: .none), path: \"Resources\"),\n                        ], type: .test),\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            useXCBuildFileRules: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(shouldCreateDylibForDynamicProducts: true),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:foo\") { target in\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-RESOURCE:foo\"])\n                    // All of these file types can generate code.\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/foo/Resources/Database.xcdatamodel\"))\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/foo/Resources/Assets.xcassets\"))\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/foo/Resources/Localizable.xcstrings\"))\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_BUNDLE_NAME], \"Foo_foo\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_BUNDLE_NAME], \"Foo_foo\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES], nil)\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-RESOURCE:foo\") { target in\n                    XCTAssertEqual(target.name, \"Foo_foo\")\n                    XCTAssertEqual(target.productType, .bundle)\n                    XCTAssertEqual(target.productName, \"Foo_foo\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.sources, [])\n                    XCTAssertEqual(target.frameworks, [])\n                    XCTAssertEqual(target.resources, [\n                        \"/Foo/Sources/foo/Resources/Data.plist\",\n                        \"/Foo/Sources/foo/Resources/Database.xcdatamodel\",\n                        \"/Foo/Sources/foo/Resources/Assets.xcassets\",\n                        \"/Foo/Sources/foo/Resources/Localizable.xcstrings\",\n                    ])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-RESOURCE:foo::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.TARGET_NAME], \"Foo_foo\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"Foo_foo\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"Foo.foo.resources\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"resource\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-RESOURCE:foo::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.TARGET_NAME], \"Foo_foo\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"Foo_foo\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"Foo.foo.resources\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"resource\")\n                        }\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:FooLib\") { target in\n                    XCTAssert(!target.dependencies.contains(\"PACKAGE-RESOURCE:FooLib\"))\n                    XCTAssert(!target.sources.contains(\"/Foo/Sources/FooLib/Resources/Database.xcdatamodel\"))\n                    XCTAssert(!target.sources.contains(\"/Foo/Sources/FooLib/Resources/Assets.xcassets\"))\n                    XCTAssert(!target.sources.contains(\"/Foo/Sources/FooLib/Resources/Localizable.xcstrings\"))\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_BUNDLE_NAME], nil)\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_BUNDLE_NAME], nil)\n                        }\n                    }\n\n                    target.checkImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES], nil)\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-TARGET:FooLib\") { target in\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-RESOURCE:FooLib\"])\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/FooLib/Resources/Database.xcdatamodel\"))\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/FooLib/Resources/Assets.xcassets\"))\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/FooLib/Resources/Localizable.xcstrings\"))\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_BUNDLE_NAME], \"Foo_FooLib\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_BUNDLE_NAME], \"Foo_FooLib\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES], [\"$(inherited)\", \"Foo_FooLib\"])\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:FooTests\") { target in\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-RESOURCE:FooTests\"])\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/FooTests/Resources/Database.xcdatamodel\"))\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/FooTests/Resources/Assets.xcassets\"))\n                    XCTAssert(target.sources.contains(\"/Foo/Sources/FooTests/Resources/Localizable.xcstrings\"))\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_BUNDLE_NAME], \"Foo_FooTests\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_BUNDLE_NAME], \"Foo_FooTests\")\n                            XCTAssertEqual(\n                                settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS],\n                                [\"$(inherited)\", \"SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE\"]\n                            )\n                        }\n                    }\n\n                    target.checkImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.EMBED_PACKAGE_RESOURCE_BUNDLE_NAMES], nil)\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-RESOURCE:FooTests\") { target in\n                    XCTAssertEqual(target.name, \"Foo_FooTests\")\n                    XCTAssertEqual(target.productType, .bundle)\n                    XCTAssertEqual(target.productName, \"Foo_FooTests\")\n                    XCTAssertEqual(target.dependencies, [])\n                    XCTAssertEqual(target.sources, [])\n                    XCTAssertEqual(target.frameworks, [])\n                    XCTAssertEqual(target.resources, [\n                        \"/Foo/Sources/FooTests/Resources/Data.plist\",\n                        \"/Foo/Sources/FooTests/Resources/Database.xcdatamodel\",\n                        \"/Foo/Sources/FooTests/Resources/Assets.xcassets\",\n                        \"/Foo/Sources/FooTests/Resources/Localizable.xcstrings\",\n                    ])\n\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-RESOURCE:FooTests::BUILDCONFIG_Debug\")\n                        XCTAssertEqual(configuration.name, \"Debug\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.TARGET_NAME], \"Foo_FooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"Foo_FooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"Foo.FooTests.resources\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"resource\")\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        XCTAssertEqual(configuration.guid, \"PACKAGE-RESOURCE:FooTests::BUILDCONFIG_Release\")\n                        XCTAssertEqual(configuration.name, \"Release\")\n                        configuration.checkAllBuildSettings { settings in\n                            XCTAssertEqual(settings[.TARGET_NAME], \"Foo_FooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_NAME], \"$(TARGET_NAME)\")\n                            XCTAssertEqual(settings[.PRODUCT_MODULE_NAME], \"Foo_FooTests\")\n                            XCTAssertEqual(settings[.PRODUCT_BUNDLE_IDENTIFIER], \"Foo.FooTests.resources\")\n                            XCTAssertEqual(settings[.GENERATE_INFOPLIST_FILE], \"YES\")\n                            XCTAssertEqual(settings[.PACKAGE_RESOURCE_TARGET_KIND], \"resource\")\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    func buildSettingsTestCase(isPackageAccessModifierSupported: Bool) throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Sources/FooLib/lib.swift\",\n            \"/Foo/Sources/FooTests/FooTests.swift\"\n        )\n\n        let toolsVersion: ToolsVersion = if isPackageAccessModifierSupported { .v5_9 } else { .v5 }\n        let mainTargetType: TargetDescription.TargetKind = if toolsVersion >= .v5_9 { .executable } else { .regular }\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: toolsVersion,\n                    products: [\n                        .init(name: \"FooLib\", type: .library(.automatic), targets: [\"FooLib\"]),\n                    ],\n                    targets: [\n                        .init(\n                            name: \"foo\",\n                            type: mainTargetType,\n                            settings: [\n                                .init(\n                                    tool: .c,\n                                    kind: .define(\"ENABLE_BEST_MODE\")\n                                ),\n                                .init(\n                                    tool: .cxx,\n                                    kind: .headerSearchPath(\"some/path\"),\n                                    condition: .init(platformNames: [\"macos\"])\n                                ),\n                                .init(\n                                    tool: .linker,\n                                    kind: .linkedLibrary(\"z\"),\n                                    condition: .init(config: \"debug\")\n                                ),\n                                .init(\n                                    tool: .swift,\n                                    kind: .unsafeFlags([\"-secret\", \"value\"]),\n                                    condition: .init(platformNames: [\"macos\", \"linux\"], config: \"release\")\n                                ),\n                            ]\n                        ),\n                        .init(name: \"FooLib\", settings: [\n                            .init(\n                                tool: .c,\n                                kind: .define(\"ENABLE_BEST_MODE\")\n                            ),\n                            .init(\n                                tool: .cxx,\n                                kind: .headerSearchPath(\"some/path\"),\n                                condition: .init(platformNames: [\"macos\"])\n                            ),\n                            .init(\n                                tool: .linker,\n                                kind: .linkedLibrary(\"z\"),\n                                condition: .init(config: \"debug\")\n                            ),\n                            .init(\n                                tool: .swift,\n                                kind: .unsafeFlags([\"-secret\", \"value\"]),\n                                condition: .init(platformNames: [\"macos\", \"linux\"], config: \"release\")\n                            ),\n                        ]),\n                        .init(name: \"FooTests\", type: .test, settings: [\n                            .init(\n                                tool: .c,\n                                kind: .define(\"ENABLE_BEST_MODE\")\n                            ),\n                            .init(\n                                tool: .cxx,\n                                kind: .headerSearchPath(\"some/path\"),\n                                condition: .init(platformNames: [\"macos\"])\n                            ),\n                            .init(\n                                tool: .linker,\n                                kind: .linkedLibrary(\"z\"),\n                                condition: .init(config: \"debug\")\n                            ),\n                            .init(\n                                tool: .swift,\n                                kind: .unsafeFlags([\"-secret\", \"value\"]),\n                                condition: .init(platformNames: [\"macos\", \"linux\"], config: \"release\")\n                            ),\n                        ]),\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(isPackageAccessModifierSupported: isPackageAccessModifierSupported),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let packageNameOptions = if isPackageAccessModifierSupported {\n            [\"-package-name\", \"foo\"]\n        } else {\n            [String]?.none\n        }\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:foo\") { target in\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(\n                                settings[.GCC_PREPROCESSOR_DEFINITIONS],\n                                [\"$(inherited)\", \"ENABLE_BEST_MODE\"]\n                            )\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS, for: .macOS], [\n                                \"$(inherited)\",\n                                \"/Foo/Sources/foo/some/path\",\n                            ])\n                            XCTAssertEqual(settings[.OTHER_LDFLAGS], [\"$(inherited)\", \"-lz\"])\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], packageNameOptions)\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(\n                                settings[.GCC_PREPROCESSOR_DEFINITIONS],\n                                [\"$(inherited)\", \"ENABLE_BEST_MODE\"]\n                            )\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS, for: .macOS], [\n                                \"$(inherited)\",\n                                \"/Foo/Sources/foo/some/path\",\n                            ])\n                            XCTAssertEqual(settings[.OTHER_LDFLAGS], nil)\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], packageNameOptions)\n                            XCTAssertEqual(\n                                settings[.OTHER_SWIFT_FLAGS, for: .macOS],\n                                [\"$(inherited)\", \"-secret\", \"value\"]\n                            )\n                            XCTAssertEqual(\n                                settings[.OTHER_SWIFT_FLAGS, for: .linux],\n                                [\"$(inherited)\", \"-secret\", \"value\"]\n                            )\n                        }\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:FooLib\") { target in\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.GCC_PREPROCESSOR_DEFINITIONS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS, for: .macOS], nil)\n                            XCTAssertEqual(settings[.OTHER_LDFLAGS], nil)\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], nil)\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.GCC_PREPROCESSOR_DEFINITIONS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS, for: .macOS], nil)\n                            XCTAssertEqual(settings[.OTHER_LDFLAGS], nil)\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], nil)\n                        }\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-TARGET:FooLib\") { target in\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(\n                                settings[.GCC_PREPROCESSOR_DEFINITIONS],\n                                [\"$(inherited)\", \"ENABLE_BEST_MODE\"]\n                            )\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS, for: .macOS], [\n                                \"$(inherited)\",\n                                \"/Foo/Sources/FooLib/some/path\",\n                            ])\n                            XCTAssertEqual(settings[.OTHER_LDFLAGS], [\"$(inherited)\", \"-lz\"])\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], packageNameOptions)\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(\n                                settings[.GCC_PREPROCESSOR_DEFINITIONS],\n                                [\"$(inherited)\", \"ENABLE_BEST_MODE\"]\n                            )\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS, for: .macOS], [\n                                \"$(inherited)\",\n                                \"/Foo/Sources/FooLib/some/path\",\n                            ])\n                            XCTAssertEqual(settings[.OTHER_LDFLAGS], nil)\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], packageNameOptions)\n                            XCTAssertEqual(\n                                settings[.OTHER_SWIFT_FLAGS, for: .macOS],\n                                [\"$(inherited)\", \"-secret\", \"value\"]\n                            )\n                            XCTAssertEqual(\n                                settings[.OTHER_SWIFT_FLAGS, for: .linux],\n                                [\"$(inherited)\", \"-secret\", \"value\"]\n                            )\n                        }\n                    }\n\n                    target.checkImpartedBuildSettings { settings in\n                        XCTAssertEqual(settings[.GCC_PREPROCESSOR_DEFINITIONS], nil)\n                        XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                        XCTAssertEqual(\n                            settings[.OTHER_LDFLAGS],\n                            [\"$(inherited)\", \"-Wl,-no_warn_duplicate_libraries\", \"-lz\"]\n                        )\n                        XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], nil)\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:FooTests\") { target in\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(\n                                settings[.GCC_PREPROCESSOR_DEFINITIONS],\n                                [\"$(inherited)\", \"ENABLE_BEST_MODE\"]\n                            )\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS, for: .macOS], [\n                                \"$(inherited)\",\n                                \"/Foo/Sources/FooTests/some/path\",\n                            ])\n                            XCTAssertEqual(settings[.OTHER_LDFLAGS], [\"$(inherited)\", \"-lz\"])\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], packageNameOptions)\n                        }\n                    }\n\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(\n                                settings[.GCC_PREPROCESSOR_DEFINITIONS],\n                                [\"$(inherited)\", \"ENABLE_BEST_MODE\"]\n                            )\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS], nil)\n                            XCTAssertEqual(settings[.HEADER_SEARCH_PATHS, for: .macOS], [\n                                \"$(inherited)\",\n                                \"/Foo/Sources/FooTests/some/path\",\n                            ])\n                            XCTAssertEqual(settings[.OTHER_LDFLAGS], nil)\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], packageNameOptions)\n                            XCTAssertEqual(\n                                settings[.OTHER_SWIFT_FLAGS, for: .macOS],\n                                [\"$(inherited)\", \"-secret\", \"value\"]\n                            )\n                            XCTAssertEqual(\n                                settings[.OTHER_SWIFT_FLAGS, for: .linux],\n                                [\"$(inherited)\", \"-secret\", \"value\"]\n                            )\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    func testBuildSettings() throws {\n        try self.buildSettingsTestCase(isPackageAccessModifierSupported: false)\n    }\n\n    func testBuildSettingsPackageAccess() throws {\n        try self.buildSettingsTestCase(isPackageAccessModifierSupported: true)\n    }\n\n    func testConditionalDependencies() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Sources/FooLib1/lib.swift\",\n            \"/Foo/Sources/FooLib2/lib.swift\",\n            \"/Foo/Sources/FooTests/FooTests.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    packageKind: .root(\"/Foo\"),\n                    packageIdentity: .plain(\"Foo\"),\n                    toolsVersion: .v5_3,\n                    targets: [\n                        .init(name: \"foo\", dependencies: [\n                            .target(name: \"FooLib1\", condition: .init(platformNames: [\"macos\"])),\n                            .target(name: \"FooLib2\", condition: .init(platformNames: [\"ios\"])),\n                        ]),\n                        .init(name: \"FooLib1\"),\n                        .init(name: \"FooLib2\"),\n                    ],\n                    traits: []\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        let expectedFilters: [PIF.GUID: [PIF.PlatformFilter]] = [\n            \"PACKAGE-TARGET:FooLib1\": PIF.PlatformFilter.macOSFilters,\n            \"PACKAGE-TARGET:FooLib2\": PIF.PlatformFilter.iOSFilters,\n        ]\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:foo\") { target in\n                    XCTAssertEqual(target.dependencies, [\"PACKAGE-TARGET:FooLib1\", \"PACKAGE-TARGET:FooLib2\"])\n                    XCTAssertEqual(target.frameworks, [\"PACKAGE-TARGET:FooLib1\", \"PACKAGE-TARGET:FooLib2\"])\n\n                    let dependencyMap = Dictionary(uniqueKeysWithValues: target.baseTarget.dependencies.map { (\n                        $0.targetGUID,\n                        $0.platformFilters\n                    ) })\n                    XCTAssertEqual(dependencyMap, expectedFilters)\n\n                    let frameworksBuildFiles = target.baseTarget.buildPhases.first { $0 is PIF.FrameworksBuildPhase }?\n                        .buildFiles ?? []\n                    let frameworksBuildFilesMap = Dictionary(\n                        uniqueKeysWithValues: frameworksBuildFiles\n                            .compactMap { file -> (\n                                PIF.GUID,\n                                [PIF.PlatformFilter]\n                            )? in\n                                switch file.reference {\n                                case .target(let guid):\n                                    return (guid, file.platformFilters)\n                                case .file:\n                                    return nil\n                                }\n                            }\n                    )\n                    XCTAssertEqual(dependencyMap, frameworksBuildFilesMap)\n                }\n            }\n        }\n    }\n\n    func testSDKOptions() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    platforms: [\n                        PlatformDescription(name: \"macos\", version: \"10.14\", options: [\"best\"]),\n                    ],\n                    toolsVersion: .v5_3,\n                    targets: [\n                        .init(name: \"foo\", dependencies: []),\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkBuildConfiguration(\"Debug\") { configuration in\n                    configuration.checkBuildSettings { settings in\n                        XCTAssertEqual(settings[.SPECIALIZATION_SDK_OPTIONS, for: .macOS], [\"best\"])\n                    }\n                }\n            }\n        }\n    }\n\n    /// Tests that the inference of XCBuild build settings based on the package manifest's declared unsafe settings\n    /// works as expected.\n    func testUnsafeFlagsBuildSettingInference() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/MyLib/Sources/MyLib/Foo.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"MyLib\",\n                    path: \"/MyLib\",\n                    toolsVersion: .v5,\n                    products: [\n                        .init(name: \"MyLib\", type: .library(.automatic), targets: [\"MyLib\"]),\n                    ],\n                    targets: [\n                        .init(name: \"MyLib\", settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .unsafeFlags([\"-enable-library-evolution\"]),\n                                condition: .init(config: \"release\")\n                            ),\n                        ]),\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/MyLib\") { project in\n                project.checkTarget(\"PACKAGE-TARGET:MyLib\") { target in\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            // Check that the `-enable-library-evolution` setting for Release didn't affect Debug.\n                            XCTAssertEqual(settings[.SWIFT_EMIT_MODULE_INTERFACE], nil)\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], nil)\n                        }\n                    }\n                    target.checkBuildConfiguration(\"Release\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            // Check that the `-enable-library-evolution` setting for Release also set\n                            // SWIFT_EMIT_MODULE_INTERFACE.\n                            XCTAssertEqual(settings[.SWIFT_EMIT_MODULE_INTERFACE], \"YES\")\n                            XCTAssertEqual(settings[.OTHER_SWIFT_FLAGS], [\"$(inherited)\", \"-enable-library-evolution\"])\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    func testSupportedSwiftVersions() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Sources/bar/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_3,\n                    swiftLanguageVersions: [.v4_2, .v5],\n                    targets: [\n                        .init(name: \"foo\", dependencies: []),\n                        .init(name: \"bar\", dependencies: [], settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .swiftLanguageMode(.v4_2),\n                                condition: .init(platformNames: [\"linux\"])\n                            ),\n                        ]),\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(supportedSwiftVersions: [.v4_2, .v5]),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-PRODUCT:foo\") { target in\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"5\")\n                        }\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-PRODUCT:bar\") { target in\n                    target.checkBuildConfiguration(\"Debug\") { configuration in\n                        configuration.checkBuildSettings { settings in\n                            XCTAssertEqual(settings[.SWIFT_VERSION], \"5\")\n                            XCTAssertEqual(settings[.SWIFT_VERSION, for: .linux], \"4.2\")\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    func testPerTargetSwiftVersions() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/main.swift\",\n            \"/Foo/Sources/bar/main.swift\",\n            \"/Foo/Sources/baz/main.swift\",\n            \"/Foo/Sources/qux/main.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting(verbose: false) // Don't print expected [error]s.\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v5_3,\n                    swiftLanguageVersions: [.v4_2],\n                    targets: [\n                        .init(name: \"foo\", dependencies: [], settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .swiftLanguageMode(.v4_2)\n                            ),\n                        ]),\n                        .init(name: \"bar\", dependencies: [], settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .swiftLanguageMode(.v6)\n                            ),\n                        ]),\n                        .init(name: \"baz\", dependencies: [], settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .swiftLanguageMode(.v3),\n                                condition: .init(platformNames: [\"linux\"])\n                            ),\n                            .init(\n                                tool: .swift,\n                                kind: .swiftLanguageMode(.v4_2),\n                                condition: .init(platformNames: [\"macOS\"])\n                            ),\n                        ]),\n                        .init(name: \"qux\", dependencies: [], settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .swiftLanguageMode(.v5)\n                            )\n                        ]),\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(supportedSwiftVersions: [.v4_2, .v5]),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let _ = try builder.construct()\n\n        testDiagnostics(observability.diagnostics) { result in\n            result.check(\n                diagnostic: \"Some of the Swift language versions used in target 'bar' settings are unsupported. (given: [6], supported: [4.2, 5])\",\n                severity: .error\n            )\n            result.check(\n                diagnostic: \"Some of the Swift language versions used in target 'baz' settings are unsupported. (given: [3], supported: [4.2, 5])\",\n                severity: .error\n            )\n            result.checkIsEmpty()\n        }\n    }\n\n    func testPerTargetDefaultIsolation() throws {\n        #if !os(macOS)\n        try XCTSkipIf(true, \"test is only supported on macOS\")\n        #endif\n        let fs = InMemoryFileSystem(\n            emptyFiles:\n            \"/Foo/Sources/foo/foo.swift\",\n            \"/Foo/Sources/bar/bar.swift\",\n            \"/Foo/Sources/baz/baz.swift\"\n        )\n\n        let observability = ObservabilitySystem.makeForTesting()\n        let graph = try loadModulesGraph(\n            fileSystem: fs,\n            manifests: [\n                Manifest.createRootManifest(\n                    displayName: \"Foo\",\n                    path: \"/Foo\",\n                    toolsVersion: .v6_2,\n                    targets: [\n                        .init(name: \"foo\", dependencies: [], settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .defaultIsolation(.MainActor)\n                            ),\n                        ]),\n                        .init(name: \"bar\", dependencies: [], settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .defaultIsolation(.nonisolated)\n                            ),\n                        ]),\n                        .init(name: \"baz\", dependencies: [], settings: [\n                            .init(\n                                tool: .swift,\n                                kind: .defaultIsolation(.MainActor),\n                                condition: .init(platformNames: [\"linux\"])\n                            )\n                        ])\n                    ]\n                ),\n            ],\n            shouldCreateMultipleTestProducts: true,\n            observabilityScope: observability.topScope\n        )\n\n        let builder = PIFBuilder(\n            graph: graph,\n            parameters: .mock(supportedSwiftVersions: [.v6]),\n            fileSystem: fs,\n            observabilityScope: observability.topScope\n        )\n        let pif = try builder.construct()\n\n        XCTAssertNoDiagnostics(observability.diagnostics)\n\n        try PIFTester(pif) { workspace in\n            try workspace.checkProject(\"PACKAGE:/Foo\") { project in\n                project.checkTarget(\"PACKAGE-TARGET:foo\") { target in\n                    for config in [\"Debug\", \"Release\"] {\n                        target.checkBuildConfiguration(config) { configuration in\n                            configuration.checkBuildSettings { settings in\n                                XCTAssertMatch(\n                                    settings[.OTHER_SWIFT_FLAGS] ?? [],\n                                     [.anySequence, \"-default-isolation\", \"MainActor\", .anySequence]\n                                )\n                            }\n                        }\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-TARGET:bar\") { target in\n                    for config in [\"Debug\", \"Release\"] {\n                        target.checkBuildConfiguration(config) { configuration in\n                            configuration.checkBuildSettings { settings in\n                                XCTAssertMatch(\n                                    settings[.OTHER_SWIFT_FLAGS] ?? [],\n                                    [.anySequence, \"-default-isolation\", \"nonisolated\", .anySequence]\n                                )\n                            }\n                        }\n                    }\n                }\n\n                project.checkTarget(\"PACKAGE-TARGET:baz\") { target in\n                    for config in [\"Debug\", \"Release\"] {\n                        target.checkBuildConfiguration(config) { configuration in\n                            configuration.checkBuildSettings { settings in\n                                XCTAssertMatch(\n                                    settings[.OTHER_SWIFT_FLAGS, for: .linux] ?? [],\n                                    [.anySequence, \"-default-isolation\", \"MainActor\", .anySequence]\n                                )\n                                XCTAssertNoMatch(\n                                    settings[.OTHER_SWIFT_FLAGS, for: .macOS] ?? [],\n                                    [.anySequence, \"-default-isolation\", \"MainActor\", .anySequence]\n                                )\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nextension PIFBuilderParameters {\n    static func mock(\n        isPackageAccessModifierSupported: Bool = false,\n        shouldCreateDylibForDynamicProducts: Bool = false,\n        supportedSwiftVersions: [SwiftLanguageVersion] = []\n    ) -> Self {\n        PIFBuilderParameters(\n            triple: .macOS,\n            isPackageAccessModifierSupported: isPackageAccessModifierSupported,\n            enableTestability: false,\n            shouldCreateDylibForDynamicProducts: shouldCreateDylibForDynamicProducts,\n            toolchainLibDir: \"/toolchain/lib\",\n            pkgConfigDirectories: [\"/pkg-config\"],\n            sdkRootPath: \"/some.sdk\",\n            supportedSwiftVersions: supportedSwiftVersions\n        )\n    }\n}\n"
  },
  {
    "path": "Tests/XCBuildSupportTests/PIFTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport XCTest\nimport Basics\nimport PackageModel\nimport SPMBuildCore\nimport XCBuildSupport\nimport _InternalTestSupport\n\nimport enum TSCBasic.JSON\n\nclass PIFTests: XCTestCase {\n    let topLevelObject = PIF.TopLevelObject(workspace:\n        PIF.Workspace(\n            guid: \"workspace\",\n            name: \"MyWorkspace\",\n            path: \"/path/to/workspace\",\n            projects: [\n                PIF.Project(\n                    guid: \"project\",\n                    name: \"MyProject\",\n                    path: \"/path/to/workspace/project\",\n                    projectDirectory: \"/path/to/workspace/project\",\n                    developmentRegion: \"fr\",\n                    buildConfigurations: [\n                        PIF.BuildConfiguration(\n                            guid: \"project-config-debug-guid\",\n                            name: \"Debug\",\n                            buildSettings: {\n                                var settings = PIF.BuildSettings()\n                                settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n                                settings[.SUPPORTED_PLATFORMS] = [\"$(AVAILABLE_PLATFORMS)\"]\n                                return settings\n                            }()\n                        ),\n                        PIF.BuildConfiguration(\n                            guid: \"project-config-release-guid\",\n                            name: \"Release\",\n                            buildSettings: {\n                                var settings = PIF.BuildSettings()\n                                settings[.PRODUCT_NAME] = \"$(TARGET_NAME)\"\n                                settings[.SUPPORTED_PLATFORMS] = [\"$(AVAILABLE_PLATFORMS)\"]\n                                settings[.GCC_OPTIMIZATION_LEVEL] = \"s\"\n                                return settings\n                            }()\n                        ),\n                    ],\n                    targets: [\n                        PIF.Target(\n                            guid: \"target-exe-guid\",\n                            name: \"MyExecutable\",\n                            productType: .executable,\n                            productName: \"MyExecutable\",\n                            buildConfigurations: [\n                                PIF.BuildConfiguration(\n                                    guid: \"target-exe-config-debug-guid\",\n                                    name: \"Debug\",\n                                    buildSettings: {\n                                        var settings = PIF.BuildSettings()\n                                        settings[.TARGET_NAME] = \"MyExecutable\"\n                                        return settings\n                                    }()\n                                ),\n                                PIF.BuildConfiguration(\n                                    guid: \"target-exe-config-release-guid\",\n                                    name: \"Release\",\n                                    buildSettings: {\n                                        var settings = PIF.BuildSettings()\n                                        settings[.TARGET_NAME] = \"MyExecutable\"\n                                        settings[.SKIP_INSTALL] = \"NO\"\n                                        return settings\n                                    }()\n                                ),\n                            ],\n                            buildPhases: [\n                                PIF.SourcesBuildPhase(\n                                    guid: \"target-exe-sources-build-phase-guid\",\n                                    buildFiles: [\n                                        PIF.BuildFile(\n                                            guid: \"target-exe-sources-build-file-guid\",\n                                            fileGUID: \"exe-file-guid\",\n                                            platformFilters: []\n                                        )\n                                    ]\n                                ),\n                                PIF.FrameworksBuildPhase(\n                                    guid: \"target-exe-frameworks-build-phase-guid\",\n                                    buildFiles: [\n                                        PIF.BuildFile(\n                                            guid: \"target-exe-frameworks-build-file-guid\",\n                                            targetGUID: \"target-lib-guid\",\n                                            platformFilters: []\n                                        )\n                                    ]\n                                ),\n                                PIF.HeadersBuildPhase(\n                                    guid: \"target-exe-headers-build-phase-guid\",\n                                    buildFiles: [\n                                        PIF.BuildFile(\n                                            guid: \"target-exe-headers-build-file-guid\",\n                                            targetGUID: \"target-lib-guid\",\n                                            platformFilters: [],\n                                            headerVisibility: .public\n                                        )\n                                    ]\n                                )\n                            ],\n                            dependencies: [\n                                .init(targetGUID: \"target-lib-guid\")\n                            ],\n                            impartedBuildSettings: PIF.BuildSettings()\n                        ),\n                        PIF.Target(\n                            guid: \"target-lib-guid\",\n                            name: \"MyLibrary\",\n                            productType: .objectFile,\n                            productName: \"MyLibrary\",\n                            buildConfigurations: [\n                                PIF.BuildConfiguration(\n                                    guid: \"target-lib-config-debug-guid\",\n                                    name: \"Debug\",\n                                    buildSettings: {\n                                        var settings = PIF.BuildSettings()\n                                        settings[.TARGET_NAME] = \"MyLibrary-Debug\"\n                                        return settings\n                                    }(),\n                                    impartedBuildProperties: {\n                                        var settings = PIF.BuildSettings()\n                                        settings[.OTHER_CFLAGS] = [\"-fmodule-map-file=modulemap\", \"$(inherited)\"]\n                                        return PIF.ImpartedBuildProperties(settings: settings)\n                                    }()\n                                ),\n                                PIF.BuildConfiguration(\n                                    guid: \"target-lib-config-release-guid\",\n                                    name: \"Release\",\n                                    buildSettings: {\n                                        var settings = PIF.BuildSettings()\n                                        settings[.TARGET_NAME] = \"MyLibrary\"\n                                        return settings\n                                    }(),\n                                    impartedBuildProperties: {\n                                        var settings = PIF.BuildSettings()\n                                        settings[.OTHER_CFLAGS] = [\"-fmodule-map-file=modulemap\", \"$(inherited)\"]\n                                        return PIF.ImpartedBuildProperties(settings: settings)\n                                    }()\n                                ),\n                            ],\n                            buildPhases: [\n                                PIF.SourcesBuildPhase(\n                                    guid: \"target-lib-sources-build-phase-guid\",\n                                    buildFiles: [\n                                        PIF.BuildFile(\n                                            guid: \"target-lib-sources-build-file-guid\",\n                                            fileGUID: \"lib-file-guid\",\n                                            platformFilters: []\n                                        )\n                                    ]\n                                )\n                            ],\n                            dependencies: [],\n                            impartedBuildSettings: PIF.BuildSettings()\n                        ),\n                        PIF.AggregateTarget(\n                            guid: \"aggregate-target-guid\",\n                            name: \"AggregateLibrary\",\n                            buildConfigurations: [\n                                PIF.BuildConfiguration(\n                                    guid: \"aggregate-target-config-debug-guid\",\n                                    name: \"Debug\",\n                                    buildSettings: PIF.BuildSettings(),\n                                    impartedBuildProperties: {\n                                        var settings = PIF.BuildSettings()\n                                        settings[.OTHER_CFLAGS] = [\"-fmodule-map-file=modulemap\", \"$(inherited)\"]\n                                        return PIF.ImpartedBuildProperties(settings: settings)\n                                    }()\n                                ),\n                                PIF.BuildConfiguration(\n                                    guid: \"aggregate-target-config-release-guid\",\n                                    name: \"Release\",\n                                    buildSettings: PIF.BuildSettings(),\n                                    impartedBuildProperties: {\n                                        var settings = PIF.BuildSettings()\n                                        settings[.OTHER_CFLAGS] = [\"-fmodule-map-file=modulemap\", \"$(inherited)\"]\n                                        return PIF.ImpartedBuildProperties(settings: settings)\n                                    }()\n                                ),\n                            ],\n                            buildPhases: [],\n                            dependencies: [\n                                .init(targetGUID: \"target-lib-guid\"),\n                                .init(targetGUID: \"target-exe-guid\"),\n                            ],\n                            impartedBuildSettings: PIF.BuildSettings()\n                        )\n                    ],\n                    groupTree: PIF.Group(guid: \"main-group-guid\", path: \"\", children: [\n                        PIF.FileReference(guid: \"exe-file-guid\", path: \"main.swift\"),\n                        PIF.FileReference(guid: \"lib-file-guid\", path: \"lib.swift\"),\n                    ])\n                )\n            ]\n        )\n    )\n\n    func testRoundTrip() throws {\n        let encoder = JSONEncoder.makeWithDefaults()\n        if #available(macOS 10.13, *) {\n            encoder.outputFormatting = [.sortedKeys, .prettyPrinted]\n        }\n\n        let workspace = topLevelObject.workspace\n        let encodedData = try encoder.encode(workspace)\n        let decodedWorkspace = try JSONDecoder.makeWithDefaults().decode(PIF.Workspace.self, from: encodedData)\n\n        let originalPIF = try encoder.encode(workspace)\n        let decodedPIF = try encoder.encode(decodedWorkspace)\n\n        let originalString = String(decoding: originalPIF, as: UTF8.self)\n        let decodedString = String(decoding: decodedPIF, as: UTF8.self)\n\n        XCTAssertEqual(originalString, decodedString)\n    }\n\n    func testEncodable() throws {\n        let encoder = JSONEncoder.makeWithDefaults()\n        encoder.userInfo[.encodeForXCBuild] = true\n        try PIF.sign(topLevelObject.workspace)\n        let data = try encoder.encode(topLevelObject)\n        let json = try JSON(data: data)\n\n        guard case .array(let objects) = json else {\n            XCTFail(\"invalid json type\")\n            return\n        }\n\n        guard objects.count == 5 else {\n            XCTFail(\"invalid number of objects\")\n            return\n        }\n\n        let workspace = objects[0]\n        guard let workspaceContents = workspace[\"contents\"] else {\n            XCTFail(\"missing workspace contents\")\n            return\n        }\n\n        let project = objects[1]\n        guard let projectContents = project[\"contents\"] else {\n            XCTFail(\"missing project contents\")\n            return\n        }\n\n        let exeTarget = objects[2]\n        guard let exeTargetContents = exeTarget[\"contents\"] else {\n            XCTFail(\"missing exe target contents\")\n            return\n        }\n\n        let libTarget = objects[3]\n        guard let libTargetContents = libTarget[\"contents\"] else {\n            XCTFail(\"missing lib target contents\")\n            return\n        }\n\n        let aggregateTarget = objects[4]\n        guard let aggregateTargetContents = aggregateTarget[\"contents\"] else {\n            XCTFail(\"missing aggregate target contents\")\n            return\n        }\n\n        XCTAssertEqual(workspace[\"type\"]?.string, \"workspace\")\n        XCTAssertEqual(workspaceContents[\"guid\"]?.string, \"workspace@11\")\n        XCTAssertEqual(workspaceContents[\"path\"]?.string, AbsolutePath(\"/path/to/workspace\").pathString)\n        XCTAssertEqual(workspaceContents[\"name\"]?.string, \"MyWorkspace\")\n        XCTAssertEqual(workspaceContents[\"projects\"]?.array, [project[\"signature\"]!])\n\n        XCTAssertEqual(project[\"type\"]?.string, \"project\")\n        XCTAssertEqual(projectContents[\"guid\"]?.string, \"project@11\")\n        XCTAssertEqual(projectContents[\"path\"]?.string, AbsolutePath(\"/path/to/workspace/project\").pathString)\n        XCTAssertEqual(projectContents[\"projectDirectory\"]?.string, AbsolutePath(\"/path/to/workspace/project\").pathString)\n        XCTAssertEqual(projectContents[\"projectName\"]?.string, \"MyProject\")\n        XCTAssertEqual(projectContents[\"projectIsPackage\"]?.string, \"true\")\n        XCTAssertEqual(projectContents[\"developmentRegion\"]?.string, \"fr\")\n        XCTAssertEqual(projectContents[\"defaultConfigurationName\"]?.string, \"Release\")\n        XCTAssertEqual(projectContents[\"targets\"]?.array, [\n            exeTarget[\"signature\"]!,\n            libTarget[\"signature\"]!,\n            aggregateTarget[\"signature\"]!,\n        ])\n\n        if let configurations = projectContents[\"buildConfigurations\"]?.array, configurations.count == 2 {\n            let debugConfiguration = configurations[0]\n            XCTAssertEqual(debugConfiguration[\"guid\"]?.string, \"project-config-debug-guid\")\n            XCTAssertEqual(debugConfiguration[\"name\"]?.string, \"Debug\")\n            let debugSettings = debugConfiguration[\"buildSettings\"]\n            XCTAssertEqual(debugSettings?[\"PRODUCT_NAME\"]?.string, \"$(TARGET_NAME)\")\n            XCTAssertEqual(debugSettings?[\"SUPPORTED_PLATFORMS\"]?.array, [.string(\"$(AVAILABLE_PLATFORMS)\")])\n\n            let releaseConfiguration = configurations[1]\n            XCTAssertEqual(releaseConfiguration[\"guid\"]?.string, \"project-config-release-guid\")\n            XCTAssertEqual(releaseConfiguration[\"name\"]?.string, \"Release\")\n            let releaseSettings = releaseConfiguration[\"buildSettings\"]\n            XCTAssertEqual(releaseSettings?[\"PRODUCT_NAME\"]?.string, \"$(TARGET_NAME)\")\n            XCTAssertEqual(releaseSettings?[\"SUPPORTED_PLATFORMS\"]?.array, [.string(\"$(AVAILABLE_PLATFORMS)\")])\n        } else {\n            XCTFail(\"invalid number of build configurations\")\n        }\n\n        if let groupTree = projectContents[\"groupTree\"] {\n            XCTAssertEqual(groupTree[\"guid\"]?.string, \"main-group-guid\")\n            XCTAssertEqual(groupTree[\"sourceTree\"]?.string, \"<group>\")\n            XCTAssertEqual(groupTree[\"path\"]?.string, \"\")\n            XCTAssertEqual(groupTree[\"name\"]?.string, \"\")\n\n            if let children = groupTree[\"children\"]?.array, children.count == 2 {\n                let file1 = children[0]\n                XCTAssertEqual(file1[\"guid\"]?.string, \"exe-file-guid\")\n                XCTAssertEqual(file1[\"sourceTree\"]?.string, \"<group>\")\n                XCTAssertEqual(file1[\"path\"]?.string, \"main.swift\")\n                XCTAssertEqual(file1[\"name\"]?.string, \"main.swift\")\n\n                let file2 = children[1]\n                XCTAssertEqual(file2[\"guid\"]?.string, \"lib-file-guid\")\n                XCTAssertEqual(file2[\"sourceTree\"]?.string, \"<group>\")\n                XCTAssertEqual(file2[\"path\"]?.string, \"lib.swift\")\n                XCTAssertEqual(file2[\"name\"]?.string, \"lib.swift\")\n            } else {\n                XCTFail(\"invalid number of groupTree children\")\n            }\n        } else {\n            XCTFail(\"missing project groupTree\")\n        }\n\n        XCTAssertEqual(exeTarget[\"type\"]?.string, \"target\")\n        XCTAssertEqual(exeTargetContents[\"guid\"]?.string, \"target-exe-guid@11\")\n        XCTAssertEqual(exeTargetContents[\"name\"]?.string, \"MyExecutable\")\n        XCTAssertEqual(exeTargetContents[\"dependencies\"]?.array, [JSON([\"guid\": \"target-lib-guid@11\"])])\n        XCTAssertEqual(exeTargetContents[\"type\"]?.string, \"standard\")\n        XCTAssertEqual(exeTargetContents[\"productTypeIdentifier\"]?.string, \"com.apple.product-type.tool\")\n        XCTAssertEqual(exeTargetContents[\"buildRules\"]?.array, [])\n\n        XCTAssertEqual(exeTargetContents[\"productReference\"], JSON([\n            \"type\": \"file\",\n            \"guid\": \"PRODUCTREF-target-exe-guid\",\n            \"name\": \"MyExecutable\"\n        ]))\n\n        if let configurations = exeTargetContents[\"buildConfigurations\"]?.array, configurations.count == 2 {\n            let debugConfiguration = configurations[0]\n            XCTAssertEqual(debugConfiguration[\"guid\"]?.string, \"target-exe-config-debug-guid\")\n            XCTAssertEqual(debugConfiguration[\"name\"]?.string, \"Debug\")\n            let debugSettings = debugConfiguration[\"buildSettings\"]\n            XCTAssertEqual(debugSettings?[\"TARGET_NAME\"]?.string, \"MyExecutable\")\n            XCTAssertEqual(debugConfiguration[\"impartedBuildProperties\"]?.dictionary, [\"buildSettings\": JSON([:])])\n\n            let releaseConfiguration = configurations[1]\n            XCTAssertEqual(releaseConfiguration[\"guid\"]?.string, \"target-exe-config-release-guid\")\n            XCTAssertEqual(releaseConfiguration[\"name\"]?.string, \"Release\")\n            let releaseSettings = releaseConfiguration[\"buildSettings\"]\n            XCTAssertEqual(releaseSettings?[\"TARGET_NAME\"]?.string, \"MyExecutable\")\n            XCTAssertEqual(releaseSettings?[\"SKIP_INSTALL\"]?.string, \"NO\")\n            XCTAssertEqual(releaseConfiguration[\"impartedBuildProperties\"]?.dictionary, [\"buildSettings\": JSON([:])])\n        } else {\n            XCTFail(\"invalid number of build configurations\")\n        }\n\n        if let buildPhases = exeTargetContents[\"buildPhases\"]?.array, buildPhases.count == 3 {\n            let buildPhase1 = buildPhases[0]\n            XCTAssertEqual(buildPhase1[\"guid\"]?.string, \"target-exe-sources-build-phase-guid\")\n            XCTAssertEqual(buildPhase1[\"type\"]?.string, \"com.apple.buildphase.sources\")\n            if let sources = buildPhase1[\"buildFiles\"]?.array, sources.count == 1 {\n                XCTAssertEqual(sources[0][\"guid\"]?.string, \"target-exe-sources-build-file-guid\")\n                XCTAssertEqual(sources[0][\"fileReference\"]?.string, \"exe-file-guid\")\n            } else {\n                XCTFail(\"invalid number of build files\")\n            }\n\n            let buildPhase2 = buildPhases[1]\n            XCTAssertEqual(buildPhase2[\"guid\"]?.string, \"target-exe-frameworks-build-phase-guid\")\n            XCTAssertEqual(buildPhase2[\"type\"]?.string, \"com.apple.buildphase.frameworks\")\n            if let frameworks = buildPhase2[\"buildFiles\"]?.array, frameworks.count == 1 {\n                XCTAssertEqual(frameworks[0][\"guid\"]?.string, \"target-exe-frameworks-build-file-guid\")\n                XCTAssertEqual(frameworks[0][\"targetReference\"]?.string, \"target-lib-guid@11\")\n            } else {\n                XCTFail(\"invalid number of build files\")\n            }\n\n            let buildPhase3 = buildPhases[2]\n            XCTAssertEqual(buildPhase3[\"guid\"]?.string, \"target-exe-headers-build-phase-guid\")\n            XCTAssertEqual(buildPhase3[\"type\"]?.string, \"com.apple.buildphase.headers\")\n            if let frameworks = buildPhase3[\"buildFiles\"]?.array, frameworks.count == 1 {\n                XCTAssertEqual(frameworks[0][\"guid\"]?.string, \"target-exe-headers-build-file-guid\")\n                XCTAssertEqual(frameworks[0][\"targetReference\"]?.string, \"target-lib-guid@11\")\n                XCTAssertEqual(frameworks[0][\"headerVisibility\"]?.string, \"public\")\n            } else {\n                XCTFail(\"invalid number of build files\")\n            }\n        } else {\n            XCTFail(\"invalid number of build configurations\")\n        }\n\n        XCTAssertEqual(libTarget[\"type\"]?.string, \"target\")\n        XCTAssertEqual(libTargetContents[\"guid\"]?.string, \"target-lib-guid@11\")\n        XCTAssertEqual(libTargetContents[\"name\"]?.string, \"MyLibrary\")\n        XCTAssertEqual(libTargetContents[\"dependencies\"]?.array, [])\n        XCTAssertEqual(libTargetContents[\"type\"]?.string, \"standard\")\n        XCTAssertEqual(libTargetContents[\"productTypeIdentifier\"]?.string, \"com.apple.product-type.objfile\")\n        XCTAssertEqual(libTargetContents[\"buildRules\"]?.array, [])\n\n        XCTAssertEqual(libTargetContents[\"productReference\"], JSON([\n            \"type\": \"file\",\n            \"guid\": \"PRODUCTREF-target-lib-guid\",\n            \"name\": \"MyLibrary\"\n        ]))\n\n        if let configurations = libTargetContents[\"buildConfigurations\"]?.array, configurations.count == 2 {\n            let debugConfiguration = configurations[0]\n            XCTAssertEqual(debugConfiguration[\"guid\"]?.string, \"target-lib-config-debug-guid\")\n            XCTAssertEqual(debugConfiguration[\"name\"]?.string, \"Debug\")\n            let debugSettings = debugConfiguration[\"buildSettings\"]\n            XCTAssertEqual(debugSettings?[\"TARGET_NAME\"]?.string, \"MyLibrary-Debug\")\n            XCTAssertEqual(\n                debugConfiguration[\"impartedBuildProperties\"]?[\"buildSettings\"]?[\"OTHER_CFLAGS\"]?.array,\n                [.string(\"-fmodule-map-file=modulemap\"), .string(\"$(inherited)\")]\n            )\n\n            let releaseConfiguration = configurations[1]\n            XCTAssertEqual(releaseConfiguration[\"guid\"]?.string, \"target-lib-config-release-guid\")\n            XCTAssertEqual(releaseConfiguration[\"name\"]?.string, \"Release\")\n            let releaseSettings = releaseConfiguration[\"buildSettings\"]\n            XCTAssertEqual(releaseSettings?[\"TARGET_NAME\"]?.string, \"MyLibrary\")\n            XCTAssertEqual(\n                releaseConfiguration[\"impartedBuildProperties\"]?[\"buildSettings\"]?[\"OTHER_CFLAGS\"]?.array,\n                [.string(\"-fmodule-map-file=modulemap\"), .string(\"$(inherited)\")]\n            )\n        } else {\n            XCTFail(\"invalid number of build configurations\")\n        }\n\n        if let buildPhases = libTargetContents[\"buildPhases\"]?.array, buildPhases.count == 1 {\n            let buildPhase1 = buildPhases[0]\n            XCTAssertEqual(buildPhase1[\"guid\"]?.string, \"target-lib-sources-build-phase-guid\")\n            XCTAssertEqual(buildPhase1[\"type\"]?.string, \"com.apple.buildphase.sources\")\n            if let sources = buildPhase1[\"buildFiles\"]?.array, sources.count == 1 {\n                XCTAssertEqual(sources[0][\"guid\"]?.string, \"target-lib-sources-build-file-guid\")\n                XCTAssertEqual(sources[0][\"fileReference\"]?.string, \"lib-file-guid\")\n            } else {\n                XCTFail(\"invalid number of build files\")\n            }\n        } else {\n            XCTFail(\"invalid number of build configurations\")\n        }\n\n        XCTAssertEqual(aggregateTarget[\"type\"]?.string, \"target\")\n        XCTAssertEqual(aggregateTargetContents[\"guid\"]?.string, \"aggregate-target-guid@11\")\n        XCTAssertEqual(aggregateTargetContents[\"type\"]?.string, \"aggregate\")\n        XCTAssertEqual(aggregateTargetContents[\"name\"]?.string, \"AggregateLibrary\")\n        XCTAssertEqual(aggregateTargetContents[\"dependencies\"]?.array, [\n            JSON([\"guid\": \"target-lib-guid@11\"]),\n            JSON([\"guid\": \"target-exe-guid@11\"]),\n        ])\n        XCTAssertEqual(aggregateTargetContents[\"buildRules\"], nil)\n\n        if let configurations = aggregateTargetContents[\"buildConfigurations\"]?.array, configurations.count == 2 {\n            let debugConfiguration = configurations[0]\n            XCTAssertEqual(debugConfiguration[\"guid\"]?.string, \"aggregate-target-config-debug-guid\")\n            XCTAssertEqual(debugConfiguration[\"name\"]?.string, \"Debug\")\n            let debugSettings = debugConfiguration[\"buildSettings\"]\n            XCTAssertNotNil(debugSettings)\n            XCTAssertEqual(\n                debugConfiguration[\"impartedBuildProperties\"]?[\"buildSettings\"]?[\"OTHER_CFLAGS\"]?.array,\n                [.string(\"-fmodule-map-file=modulemap\"), .string(\"$(inherited)\")]\n            )\n\n            let releaseConfiguration = configurations[1]\n            XCTAssertEqual(releaseConfiguration[\"guid\"]?.string, \"aggregate-target-config-release-guid\")\n            XCTAssertEqual(releaseConfiguration[\"name\"]?.string, \"Release\")\n            let releaseSettings = releaseConfiguration[\"buildSettings\"]\n            XCTAssertNotNil(releaseSettings)\n            XCTAssertEqual(\n                releaseConfiguration[\"impartedBuildProperties\"]?[\"buildSettings\"]?[\"OTHER_CFLAGS\"]?.array,\n                [.string(\"-fmodule-map-file=modulemap\"), .string(\"$(inherited)\")]\n            )\n        } else {\n            XCTFail(\"invalid number of build configurations\")\n        }\n\n        if let buildPhases = aggregateTargetContents[\"buildPhases\"]?.array, buildPhases.count == 0 {\n        } else {\n            XCTFail(\"invalid number of build configurations\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/_AsyncFileSystemTests/AsyncFileSystemTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\nimport _AsyncFileSystem\nimport _InternalTestSupport\nimport Testing\nimport struct SystemPackage.FilePath\n\nstruct AsyncFileSystemTests {\n    @Test\n    func mockFileSystem() async throws {\n        let fs = MockFileSystem()\n\n        let mockPath: FilePath = \"/foo/bar\"\n\n        #expect(await !fs.exists(mockPath))\n\n        let mockContent = \"baz\".utf8\n\n        try await fs.write(mockPath, bytes: mockContent)\n\n        #expect(await fs.exists(mockPath))\n\n        // Test overwriting\n        try await fs.write(mockPath, bytes: mockContent)\n\n        #expect(await fs.exists(mockPath))\n\n        let bytes = try await fs.withOpenReadableFile(mockPath) { fileHandle in\n            try await fileHandle.read().reduce(into: []) { $0.append(contentsOf: $1) }\n        }\n\n        #expect(bytes == Array(mockContent))\n    }\n    @Test\n    func oSFileSystem() async throws {\n        try await testWithTemporaryDirectory { tmpDir in\n            let fs = OSFileSystem()\n\n            let mockPath = FilePath(tmpDir.appending(\"foo\").pathString)\n\n            #expect(await !fs.exists(mockPath))\n\n            let mockContent = \"baz\".utf8\n\n            try await fs.write(mockPath, bytes: mockContent)\n\n            #expect(await fs.exists(mockPath))\n\n            // Test overwriting\n            try await fs.write(mockPath, bytes: mockContent)\n\n            #expect(await fs.exists(mockPath))\n\n            let bytes = try await fs.withOpenReadableFile(mockPath) { fileHandle in\n                try await fileHandle.read().reduce(into: []) { $0.append(contentsOf: $1) }\n            }\n\n            #expect(bytes == Array(mockContent))\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/_InternalTestSupportTests/FileSystemHelpersTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport _InternalTestSupport\nimport Testing\n\n@Suite(\n    .serialized, // these change CWD\n    .tags(\n        .TestSize.small,\n    ),\n)\nstruct FileSystemHelpersTests {\n    @Test\n    func testGetFilesAbsolutePathRecursive() throws {\n        // Create an in-memory file system for testing\n        let fileSystem = InMemoryFileSystem()\n\n        // Create a test directory structure\n        let testDir = try AbsolutePath(validating: \"/test\")\n        try fileSystem.createDirectory(testDir, recursive: true)\n\n        // Create some test files\n        let swiftFile1 = testDir.appending(\"file1.swift\")\n        let swiftFile2 = testDir.appending(\"subdir\").appending(\"file2.swift\")\n        let txtFile = testDir.appending(\"readme.txt\")\n        let swiftFile3 = testDir.appending(\"subdir\").appending(\"nested\").appending(\"file3.swift\")\n\n        try fileSystem.createDirectory(swiftFile2.parentDirectory, recursive: true)\n        try fileSystem.createDirectory(swiftFile3.parentDirectory, recursive: true)\n\n        try fileSystem.writeFileContents(swiftFile1, string: \"// Swift file 1\")\n        try fileSystem.writeFileContents(swiftFile2, string: \"// Swift file 2\")\n        try fileSystem.writeFileContents(txtFile, string: \"This is a text file\")\n        try fileSystem.writeFileContents(swiftFile3, string: \"// Swift file 3\")\n\n        // Test recursive search (default)\n        let swiftFiles = try getFiles(\n            in: testDir,\n            matchingExtension: \"swift\",\n            fileSystem: fileSystem\n        )\n\n        // Verify results\n        #expect(swiftFiles.count == 3)\n        #expect(swiftFiles.contains(swiftFile1))\n        #expect(swiftFiles.contains(swiftFile2))\n        #expect(swiftFiles.contains(swiftFile3))\n        #expect(!swiftFiles.contains(txtFile))\n\n        // Test with different extension\n        let txtFiles = try getFiles(\n            in: testDir,\n            matchingExtension: \"txt\",\n            fileSystem: fileSystem\n        )\n\n        #expect(txtFiles.count == 1)\n        #expect(txtFiles.contains(txtFile))\n    }\n\n    @Test\n    func testGetFilesAbsolutePathNonRecursive() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        let testDir = try AbsolutePath(validating: \"/test\")\n        try fileSystem.createDirectory(testDir, recursive: true)\n\n        // Create files at different levels\n        let swiftFile1 = testDir.appending(\"file1.swift\")\n        let swiftFile2 = testDir.appending(\"subdir\").appending(\"file2.swift\")\n\n        try fileSystem.createDirectory(swiftFile2.parentDirectory, recursive: true)\n        try fileSystem.writeFileContents(swiftFile1, string: \"// Swift file 1\")\n        try fileSystem.writeFileContents(swiftFile2, string: \"// Swift file 2\")\n\n        // Test non-recursive search\n        let swiftFiles = try getFiles(\n            in: testDir,\n            matchingExtension: \"swift\",\n            recursive: false,\n            fileSystem: fileSystem\n        )\n\n        // Should only find the top-level file\n        #expect(swiftFiles.count == 1)\n        #expect(swiftFiles.contains(swiftFile1))\n        #expect(!swiftFiles.contains(swiftFile2))\n    }\n\n    @Test\n    func testGetFilesWithCaseInsensitiveExtensionReturnsexpectedValue() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        let testDir = try AbsolutePath(validating: \"/test\")\n        try fileSystem.createDirectory(testDir, recursive: true)\n\n        // Create files with different case extensions\n        let swiftFile = testDir.appending(\"file1.swift\")\n        let SwiftFile = testDir.appending(\"file2.Swift\")\n        let SWIFTFile = testDir.appending(\"file3.SWIFT\")\n\n        try fileSystem.writeFileContents(swiftFile, string: \"// file1\")\n        try fileSystem.writeFileContents(SwiftFile, string: \"// file2\")\n        try fileSystem.writeFileContents(SWIFTFile, string: \"// file3\")\n\n        // Test with lowercase extension\n        let results = try getFiles(\n            in: testDir,\n            matchingExtension: \"swift\",\n            fileSystem: fileSystem\n        )\n\n        #expect(results.count == 3)\n        #expect(results.contains(swiftFile))\n        #expect(results.contains(SwiftFile))\n        #expect(results.contains(SWIFTFile))\n    }\n\n    @Test\n    func testGetFilesNonExistentDirectoryRasiesAnError() throws {\n        let fileSystem = InMemoryFileSystem()\n        let nonExistentDir = try AbsolutePath(validating: \"/nonexistent\")\n\n        #expect(throws: StringError.self) {\n            try getFiles(\n                in: nonExistentDir,\n                matchingExtension: \"swift\",\n                fileSystem: fileSystem\n            )\n        }\n    }\n\n    @Test\n    func testGetFilesWithFileAsInputRaisesAnError() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        let testFile = try AbsolutePath(validating: \"/test.swift\")\n        try fileSystem.writeFileContents(testFile, string: \"// test file\")\n\n        #expect(throws: StringError.self) {\n            try getFiles(\n                in: testFile,\n                matchingExtension: \"swift\",\n                fileSystem: fileSystem\n            )\n        }\n    }\n\n    @Test\n    func testGetFilesEmptyDirectoryReturnsEmptyList() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        let testDir = try AbsolutePath(validating: \"/empty\")\n        try fileSystem.createDirectory(testDir, recursive: true)\n\n        let results = try getFiles(\n            in: testDir,\n            matchingExtension: \"swift\",\n            fileSystem: fileSystem\n        )\n\n        #expect(results.isEmpty)\n    }\n\n    @Test\n    func testGetFilesRelativePathNonRecursive() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        // Set up current working directory\n        let cwd = try AbsolutePath(validating: \"/current\")\n        try fileSystem.createDirectory(cwd, recursive: true)\n        try fileSystem.changeCurrentWorkingDirectory(to: cwd)\n\n        // Create test directory structure\n        let testDir = try RelativePath(validating: \"test\")\n        let absoluteTestDir = cwd.appending(testDir)\n        try fileSystem.createDirectory(absoluteTestDir, recursive: true)\n\n        // Create files at different levels\n        let swiftFile1 = absoluteTestDir.appending(\"file1.swift\")\n        let swiftFile2 = absoluteTestDir.appending(\"subdir\").appending(\"file2.swift\")\n\n        try fileSystem.createDirectory(swiftFile2.parentDirectory, recursive: true)\n        try fileSystem.writeFileContents(swiftFile1, string: \"// Swift file 1\")\n        try fileSystem.writeFileContents(swiftFile2, string: \"// Swift file 2\")\n\n        // Test non-recursive search\n        let swiftFiles = try getFiles(\n            in: testDir,\n            matchingExtension: \"swift\",\n            recursive: false,\n            fileSystem: fileSystem\n        )\n\n        // Should only find the top-level file\n        #expect(swiftFiles.count == 1)\n\n        let expectedFile1 = swiftFile1.relative(to: cwd)\n        #expect(swiftFiles.contains(expectedFile1))\n\n        // Should not find the nested file\n        let expectedFile2 = swiftFile2.relative(to: cwd)\n        #expect(!swiftFiles.contains(expectedFile2))\n    }\n\n    @Test\n    func testGetFilesRelativePathInvalid() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        // Set up current working directory\n        let cwd = try AbsolutePath(validating: \"/current\")\n        try fileSystem.createDirectory(cwd, recursive: true)\n        try fileSystem.changeCurrentWorkingDirectory(to: cwd)\n\n        // Try to access non-existent relative directory\n        let nonExistentDir = try RelativePath(validating: \"nonexistent\")\n\n        #expect(throws: StringError.self) {\n            try getFiles(\n                in: nonExistentDir,\n                matchingExtension: \"swift\",\n                fileSystem: fileSystem\n            )\n        }\n    }\n\n    @Test\n    func testGetFilesRelativePathWithFileAsInputRaisesAnError() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        // Set up current working directory\n        let cwd = try AbsolutePath(validating: \"/current\")\n        try fileSystem.createDirectory(cwd, recursive: true)\n        try fileSystem.changeCurrentWorkingDirectory(to: cwd)\n\n        // Create a file instead of directory\n        let testFile = cwd.appending(\"test.swift\")\n        try fileSystem.writeFileContents(testFile, string: \"// test file\")\n\n        let relativeFile = try RelativePath(validating: \"test.swift\")\n\n        #expect(throws: StringError.self) {\n            try getFiles(\n                in: relativeFile,\n                matchingExtension: \"swift\",\n                fileSystem: fileSystem\n            )\n        }\n    }\n\n    @Test\n    func testGetFilesRelativePathNoCwdRaisesAnError() throws {\n        let fileSystem = InMemoryFileSystem()\n        // Don't set a current working directory\n\n        let testDir = try RelativePath(validating: \"test\")\n\n        #expect(throws: StringError.self) {\n            try getFiles(\n                in: testDir,\n                matchingExtension: \"swift\",\n                fileSystem: fileSystem\n            )\n        }\n    }\n\n    @Test\n    func testGetFilesRelativePathComplexStructureReturnsExpectedList() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        // Set up current working directory\n        let cwd = try AbsolutePath(validating: \"/project\")\n        try fileSystem.createDirectory(cwd, recursive: true)\n        try fileSystem.changeCurrentWorkingDirectory(to: cwd)\n\n        // Create complex directory structure\n        let sourcesDir = try RelativePath(validating: \"Sources\")\n        let absoluteSourcesDir = cwd.appending(sourcesDir)\n        try fileSystem.createDirectory(absoluteSourcesDir, recursive: true)\n\n        // Create files in various subdirectories\n        let files = [\n            \"Sources/App/main.swift\",\n            \"Sources/App/Models/User.swift\",\n            \"Sources/App/Controllers/UserController.swift\",\n            \"Sources/Shared/Utils.swift\",\n            \"Sources/Shared/Extensions/String+Extensions.swift\",\n            \"Sources/Tests/AppTests.swift\",\n            \"Sources/README.md\",  // Non-Swift file\n        ]\n\n        for filePath in files {\n            let absolutePath = try AbsolutePath(validating: filePath, relativeTo: cwd)\n            try fileSystem.createDirectory(absolutePath.parentDirectory, recursive: true)\n            try fileSystem.writeFileContents(absolutePath, string: \"// \\(absolutePath.basename)\")\n        }\n\n        // Test recursive search\n        let allSwiftFiles = try getFiles(\n            in: sourcesDir,\n            matchingExtension: \"swift\",\n            fileSystem: fileSystem\n        )\n\n        #expect(allSwiftFiles.count == 6)  // All .swift files, excluding README.md\n\n        // Verify all expected files are found\n        let expectedSwiftFiles = files.filter { $0.hasSuffix(\".swift\") }\n        for expectedFile in expectedSwiftFiles {\n            let relativePath = try RelativePath(validating: expectedFile)\n            #expect(allSwiftFiles.contains(relativePath))\n        }\n\n        // Test non-recursive search (should find no files at Sources root level)\n        let topLevelSwiftFiles = try getFiles(\n            in: sourcesDir,\n            matchingExtension: \"swift\",\n            recursive: false,\n            fileSystem: fileSystem\n        )\n\n        #expect(topLevelSwiftFiles.isEmpty)\n    }\n\n    @Test\n    func testGetFilesRelativePathCaseSensitivity() throws {\n        let fileSystem = InMemoryFileSystem()\n\n        // Set up current working directory\n        let cwd = try AbsolutePath(validating: \"/test\")\n        try fileSystem.createDirectory(cwd, recursive: true)\n        try fileSystem.changeCurrentWorkingDirectory(to: cwd)\n\n        // Create test directory\n        let testDir = try RelativePath(validating: \"files\")\n        let absoluteTestDir = cwd.appending(testDir)\n        try fileSystem.createDirectory(absoluteTestDir, recursive: true)\n\n        // Create files with different case extensions\n        let files = [\n            \"file1.swift\",\n            \"file2.Swift\",\n            \"file3.SWIFT\",\n            \"file4.swiFT\",\n            \"file5.txt\",  // Different extension\n        ]\n\n        for fileName in files {\n            let filePath = absoluteTestDir.appending(fileName)\n            try fileSystem.writeFileContents(filePath, string: \"// \\(fileName)\")\n        }\n\n        // Test case-insensitive matching\n        let swiftFiles = try getFiles(\n            in: testDir,\n            matchingExtension: \"swift\",\n            fileSystem: fileSystem\n        )\n\n        #expect(swiftFiles.count == 4)  // All .swift variants, excluding .txt\n\n        // Test with uppercase extension\n        let swiftFilesUpper = try getFiles(\n            in: testDir,\n            matchingExtension: \"SWIFT\",\n            fileSystem: fileSystem\n        )\n\n        #expect(swiftFilesUpper.count == 4)  // Should match the same files\n        #expect(Set(swiftFiles) == Set(swiftFilesUpper))\n    }\n\n    // MARK: - Parameterized Tests\n\n    @Test(\n        arguments: [\n            (\n                extension: \"swift\",\n                expectedFiles: [\"file1.swift\", \"file2.Swift\", \"file3.SWIFT\", \"file4.swiFT\"],\n                allFiles: [\"file1.swift\", \"file2.Swift\", \"file3.SWIFT\", \"file4.swiFT\", \"file5.txt\"],\n            ),\n            (\n                extension: \"SWIFT\",\n                expectedFiles: [\"file1.swift\", \"file2.Swift\", \"file3.SWIFT\", \"file4.swiFT\"],\n                allFiles: [\"file1.swift\", \"file2.Swift\", \"file3.SWIFT\", \"file4.swiFT\", \"file5.txt\"],\n\n            ),\n            (\n                extension: \"Swift\",\n                expectedFiles: [\"file1.swift\", \"file2.Swift\", \"file3.SWIFT\", \"file4.swiFT\"],\n                allFiles: [\"file1.swift\", \"file2.Swift\", \"file3.SWIFT\", \"file4.swiFT\", \"file5.txt\"],\n            ),\n            (\n                extension: \"txt\",\n                expectedFiles: [\"file5.txt\"],\n                allFiles: [\"file1.swift\", \"file2.Swift\", \"file3.SWIFT\", \"file4.swiFT\", \"file5.txt\"],\n            ),\n        ],\n    )\n    func testCaseInsensitiveExtensionsParameterized(\n        extension: String,\n        expectedFiles: [String],\n        allFiles: [String],\n    ) throws {\n        let fileSystem = InMemoryFileSystem()\n        let testDir = try AbsolutePath(validating: \"/test\")\n        try fileSystem.createDirectory(testDir, recursive: true)\n\n        // Create files with different case extensions\n        for fileName in allFiles {\n            let filePath = testDir.appending(fileName)\n            try fileSystem.writeFileContents(filePath, string: \"// \\(fileName)\")\n        }\n\n        let results = try getFiles(\n            in: testDir,\n            matchingExtension: `extension`,\n            fileSystem: fileSystem\n        )\n\n        #expect(results.count == expectedFiles.count, \"Expected \\(expectedFiles.count) files for extension '\\(`extension`)'\")\n\n        for expectedFile in expectedFiles {\n            let expectedPath = testDir.appending(expectedFile)\n            #expect(results.contains(expectedPath), \"Should contain \\(expectedFile)\")\n        }\n    }\n\n    @Test(\n        arguments: [\n            (\"non-existent directory\", \"/nonexistent\", false),\n            (\"file instead of directory\", \"/test.swift\", true),\n        ]\n    )\n    func testErrorHandling(\n        description: String,\n        path: String,\n        createFile: Bool,\n    ) throws {\n        let fileSystem = InMemoryFileSystem()\n\n        if createFile {\n            // Create a file for the \"file instead of directory\" test\n            let testFile = try AbsolutePath(validating: path)\n            try fileSystem.writeFileContents(testFile, string: \"// test file\")\n        }\n\n        let testPath = try AbsolutePath(validating: path)\n\n        #expect(throws: StringError.self) {\n            try getFiles(\n                in: testPath,\n                matchingExtension: \"swift\",\n                fileSystem: fileSystem\n            )\n        }\n    }\n\n    @Test(\n        arguments: [\n            (\"invalid path\", true, false),\n            (\"file instead of directory\", true, true),\n            (\"no current working directory\", false, false),\n        ]\n    )\n    func testRelativePathErrorConditions(\n        description: String,\n        setCwd: Bool,\n        createFile: Bool,\n    ) throws {\n        let fileSystem = InMemoryFileSystem()\n\n        if setCwd {\n            let cwd = try AbsolutePath(validating: \"/current\")\n            try fileSystem.createDirectory(cwd, recursive: true)\n            try fileSystem.changeCurrentWorkingDirectory(to: cwd)\n\n            if createFile {\n                // Create a file for the \"file instead of directory\" test\n                let testFile = cwd.appending(\"test.swift\")\n                try fileSystem.writeFileContents(testFile, string: \"// test file\")\n            }\n        }\n\n        let testPath = try RelativePath(validating: createFile ? \"test.swift\" : \"nonexistent\")\n\n        #expect(throws: StringError.self) {\n            try getFiles(\n                in: testPath,\n                matchingExtension: \"swift\",\n                fileSystem: fileSystem\n            )\n        }\n    }\n\n    @Test(\n        arguments: [\n            (\n                recursive: true,\n                expectedCount: 3,\n                description: \"recursive search should find all files\"\n            ),\n            (\n                recursive: false,\n                expectedCount: 1,\n                description: \"non-recursive search should find only top-level files\"\n            ),\n        ]\n    )\n    func testgetFilesWithVariousRecursionModes(\n        recursive: Bool,\n        expectedCount: Int,\n        description: String,\n    ) throws {\n        let fileSystem = InMemoryFileSystem()\n        let testDir = try AbsolutePath(validating: \"/test\")\n        try fileSystem.createDirectory(testDir, recursive: true)\n\n        // Create files at different levels\n        let swiftFile1 = testDir.appending(\"file1.swift\")\n        let swiftFile2 = testDir.appending(\"subdir\").appending(\"file2.swift\")\n        let swiftFile3 = testDir.appending(\"subdir\").appending(\"nested\").appending(\"file3.swift\")\n\n        try fileSystem.createDirectory(swiftFile2.parentDirectory, recursive: true)\n        try fileSystem.createDirectory(swiftFile3.parentDirectory, recursive: true)\n\n        try fileSystem.writeFileContents(swiftFile1, string: \"// Swift file 1\")\n        try fileSystem.writeFileContents(swiftFile2, string: \"// Swift file 2\")\n        try fileSystem.writeFileContents(swiftFile3, string: \"// Swift file 3\")\n\n        let results = try getFiles(\n            in: testDir,\n            matchingExtension: \"swift\",\n            recursive: recursive,\n            fileSystem: fileSystem\n        )\n\n        #expect(results.count == expectedCount, \"\\(description): expected \\(expectedCount), got \\(results.count)\")\n\n        // Always should contain the top-level file\n        #expect(results.contains(swiftFile1), \"Should always contain top-level file\")\n\n        if recursive {\n            // Should contain nested files\n            #expect(results.contains(swiftFile2), \"Recursive search should contain nested files\")\n            #expect(results.contains(swiftFile3), \"Recursive search should contain deeply nested files\")\n        } else {\n            // Should not contain nested files\n            #expect(!results.contains(swiftFile2), \"Non-recursive search should not contain nested files\")\n            #expect(!results.contains(swiftFile3), \"Non-recursive search should not contain deeply nested files\")\n        }\n    }\n\n    @Test(\n        arguments: [\n            (\n                recursive: true,\n                expectedCount: 2,\n                description: \"recursive RelativePath search\",\n            ),\n            (\n                recursive: false,\n                expectedCount: 1,\n                description: \"non-recursive RelativePath search\",\n            ),\n        ]\n    )\n    func testRelativePathRecursion(\n        recursive: Bool,\n        expectedCount: Int,\n        description: String,\n    ) throws {\n        let fileSystem = InMemoryFileSystem()\n\n        // Set up current working directory\n        let cwd = try AbsolutePath(validating: \"/current\")\n        try fileSystem.createDirectory(cwd, recursive: true)\n        try fileSystem.changeCurrentWorkingDirectory(to: cwd)\n\n        // Create test directory structure\n        let testDir = try RelativePath(validating: \"test\")\n        let absoluteTestDir = cwd.appending(testDir)\n        try fileSystem.createDirectory(absoluteTestDir, recursive: true)\n\n        // Create files at different levels\n        let swiftFile1 = absoluteTestDir.appending(\"file1.swift\")\n        let swiftFile2 = absoluteTestDir.appending(\"subdir\").appending(\"file2.swift\")\n\n        try fileSystem.createDirectory(swiftFile2.parentDirectory, recursive: true)\n        try fileSystem.writeFileContents(swiftFile1, string: \"// Swift file 1\")\n        try fileSystem.writeFileContents(swiftFile2, string: \"// Swift file 2\")\n\n        let results = try getFiles(\n            in: testDir,\n            matchingExtension: \"swift\",\n            recursive: recursive,\n            fileSystem: fileSystem\n        )\n\n        #expect(results.count == expectedCount, \"\\(description): expected \\(expectedCount), got \\(results.count)\")\n\n        let expectedFile1 = swiftFile1.relative(to: cwd)\n        #expect(results.contains(expectedFile1), \"Should contain top-level file\")\n\n        let expectedFile2 = swiftFile2.relative(to: cwd)\n        if recursive {\n            #expect(results.contains(expectedFile2), \"Recursive search should contain nested file\")\n        } else {\n            #expect(!results.contains(expectedFile2), \"Non-recursive search should not contain nested file\")\n        }\n    }\n}\n"
  },
  {
    "path": "Tests/_InternalTestSupportTests/MiscTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2024-2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport SPMBuildCore\nimport _InternalTestSupport\nimport Testing\n\nstruct TestGetNumberOfMatches {\n    @Test(\n        arguments: [\n            (\n                matchOn: \"\",\n                value: \"\",\n                expectedNumMatches: 0,\n                id: \"Empty string matches on empty string zero times\",\n            ),\n            (\n                matchOn: \"\",\n                value: \"This is a non-empty string\",\n                expectedNumMatches: 0,\n                id: \"Empty string matches on non-empty string zero times\",\n            ),\n            (\n                matchOn: \"\",\n                value: \"This is a non-empty string\\nThis is the second line\",\n                expectedNumMatches: 0,\n                id: \"Empty string matches on non-empty multiline string with new line character zero times\",\n            ),\n            (\n                matchOn: \"\",\n                value: \"\"\"\n                    This is a non-empty string\n                    This is the second line\n                    This is the third line\n                    \"\"\",\n                expectedNumMatches: 0,\n                id: \"Empty string matches on non-empty multiline string using triple double quotes zero times\",\n            ),\n            (\n                matchOn: \"\"\"\n                    This is a non-empty string\n                    This is the second line\n                    This is the third line\n                    \"\"\",\n                value: \"\",\n                expectedNumMatches: 0,\n                id: \"non-empty string matches on empty string zero times\",\n            ),\n            (\n                matchOn: \"error: fatalError\",\n                value: \"\"\"\n                    > swift test                                                                                          25/10/24 10:44:14\n                    Building for debugging...\n                    /Users/arandomuser/Documents/personal/repro-swiftpm-6605/Tests/repro-swiftpm-6605Tests/repro_swiftpm_6605Tests.swift:7:19: error: division by zero\n                            let y = 1 / x\n                                    ^\n                    error: fatalError\n\n                    error: fatalError\n                    \"\"\",\n                expectedNumMatches: 2,\n                id: \"fatal error matches on multiline with two occurrences returns two\",\n            ),\n            (\n                matchOn: \"\\nerror: fatalError\",\n                value: \"\"\"\n                    > swift test                                                                                          25/10/24 10:44:14\n                    Building for debugging...\n                    /Users/arandomuser/Documents/personal/repro-swiftpm-6605/Tests/repro-swiftpm-6605Tests/repro_swiftpm_6605Tests.swift:7:19: error: division by zero\n                            let y = 1 / x\n                                    ^\n                    error: fatalError\n\n                    error: fatalError\n                    \"\"\",\n                expectedNumMatches: 2,\n                id: \"fatal error with leading new line matches on multi line with two occurences returns two\",\n            ),\n            (\n                matchOn: \"\\nerror: fatalError\\n\",\n                value: \"\"\"\n                    > swift test                                                                                          25/10/24 10:44:14\n                    Building for debugging...\n                    /Users/arandomuser/Documents/personal/repro-swiftpm-6605/Tests/repro-swiftpm-6605Tests/repro_swiftpm_6605Tests.swift:7:19: error: division by zero\n                            let y = 1 / x\n                                    ^\n                    error: fatalError\n\n                    error: fatalError\n                    \"\"\",\n                expectedNumMatches: 1,\n                id: \"fatal error with leading and trailing new line matches on multi line with two occurences returns two\",\n            ),\n        ]\n    )\n    func getNumberOfMatchesReturnsExpectedValue(\n        matchOn: String,\n        value: String,\n        expectedNumMatches: Int,\n        id: String,\n    ) async throws {\n        let actual = getNumberOfMatches(of: matchOn, in: value)\n\n        #expect(actual == expectedNumMatches)\n    }\n}\n\nstruct TestGetBuildSystemArgs {\n    @Test\n    func nilArgumentReturnsEmptyArray() {\n        let expected: [String] = []\n        let inputUnderTest: BuildSystemProvider.Kind?  = nil\n\n        let actual = getBuildSystemArgs(for: inputUnderTest)\n\n        #expect(actual == expected)\n    }\n\n    @Test(\n        arguments: SupportedBuildSystemOnPlatform\n    )\n    func validArgumentsReturnsCorrectCommandLineArguments(_ inputValue: BuildSystemProvider.Kind) {\n        let expected = [\n            \"--build-system\",\n            \"\\(inputValue)\"\n        ]\n\n        let actual = getBuildSystemArgs(for: inputValue)\n\n        #expect(actual == expected)\n    }\n}\n"
  },
  {
    "path": "Tests/_InternalTestSupportTests/XCTAssertHelpersTests.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2025 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Basics\nimport XCTest\nimport func _InternalTestSupport.XCTAssertThrows\nimport func _InternalTestSupport._requiresTools\n\nfinal class TestRequiresTool: XCTestCase {\n    func testErrorIsThrownIfExecutableIsNotFoundOnThePath() throws {\n        XCTAssertThrows(\n            try _requiresTools(\"doesNotExists\")\n        ) { (error: AsyncProcessResult.Error) in\n            return true\n        }\n    }\n\n    func testErrorIsNotThrownIfExecutableIsOnThePath() throws {\n        // Essentially call either \"which which\" or \"where.exe where.exe\"\n        #if os(Windows)\n        let executable = \"where.exe\"\n        #else\n        let executable = \"which\"\n        #endif\n        XCTAssertNoThrow(\n            try _requiresTools(executable)\n        )\n    }\n}"
  },
  {
    "path": "Utilities/Certificates/Package.swift",
    "content": "// swift-tools-version: 999.0\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"Certificates\",\n    targets: [\n        .target(name: \"Certificates\",\n                path: \".\",\n                exclude: [\"README.md\", \"generate.sh\"],\n                resources: [\n                    .embedInCode(\"Intermediates\"),\n                    .embedInCode(\"Roots\"),\n                ]),\n    ]\n)\n"
  },
  {
    "path": "Utilities/Certificates/README.md",
    "content": "# Temporary manual solution for embedding certificates into SwiftPM\n\nRunning `./generate.sh` will use SwiftPM's 5.9 feature for embedding resources to generate code and then the script copies it into the `PackageSigning` and `PackageCollectionsSigning` target directories. Whenever there are new certificates to embed, copy them into this directory and update the package manifest. The updated generated source file needs to be checked in.\n"
  },
  {
    "path": "Utilities/Certificates/empty.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) YEARS Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n"
  },
  {
    "path": "Utilities/Certificates/generate.sh",
    "content": "#!/bin/bash\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) YEARS Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nswift build\ncp .build/arm64-apple-macosx/debug/Certificates.build/DerivedSources/embedded_resources.swift ../../Sources/PackageSigning/\ncp .build/arm64-apple-macosx/debug/Certificates.build/DerivedSources/embedded_resources.swift ../../Sources/PackageCollectionsSigning/\n"
  },
  {
    "path": "Utilities/Docker/Dockerfile",
    "content": "##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2014-2024 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nARG swift_version=5.9\nARG ubuntu_version=jammy\nARG base_image=swift:$swift_version-$ubuntu_version\nFROM $base_image\n# needed to do again after FROM due to docker limitation\nARG swift_version\nARG ubuntu_version\n\n# set as UTF-8\nRUN apt-get update && apt-get install -y locales locales-all\nENV LC_ALL en_US.UTF-8\nENV LANG en_US.UTF-8\nENV LANGUAGE en_US.UTF-8\n\n# SwiftPM dependencies\n#---------------------\n\nRUN apt-get update && apt-get install -y \\\n  git \\\n  libsqlite3-dev \\\n  libncurses5-dev \\\n  sqlite3 \\\n  zip\n\n# Bootstrap script dependencies\n#------------------------------\n\nRUN apt-get install -y wget software-properties-common\n\n# use kitware for recent versions of cmake and ninja (required by bootstrap script)\nRUN wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | apt-key add -\nRUN apt-add-repository \"deb https://apt.kitware.com/ubuntu/ $ubuntu_version main\"\n\nRUN apt-get install -y \\\n  python3 \\\n  cmake \\\n  ninja-build\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.1604.53.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:16.04-5.3\n    build:\n      args:\n        ubuntu_version: \"xenial\"\n        swift_version: \"5.3\"\n\n  build:\n    image: swift-package-manager:16.04-5.3\n\n  test:\n    image: swift-package-manager:16.04-5.3\n\n  bootstrap-clean:\n    image: swift-package-manager:16.04-5.3\n\n  bootstrap-build:\n    image: swift-package-manager:16.04-5.3\n\n  bootstrap-test:\n    image: swift-package-manager:16.04-5.3\n\n  shell:\n    image: swift-package-manager:16.04-5.3\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.1804.53.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:18.04-5.3\n    build:\n      args:\n        ubuntu_version: \"bionic\"\n        swift_version: \"5.3\"\n\n  build:\n    image: swift-package-manager:18.04-5.3\n\n  test:\n    image: swift-package-manager:18.04-5.3\n\n  bootstrap-clean:\n    image: swift-package-manager:18.04-5.3\n\n  bootstrap-build:\n    image: swift-package-manager:18.04-5.3\n\n  bootstrap-test:\n    image: swift-package-manager:18.04-5.3\n\n  shell:\n    image: swift-package-manager:18.04-5.3\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.2004.54.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:20.04-5.4\n    build:\n      args:\n        ubuntu_version: \"focal\"\n        swift_version: \"5.4\"\n\n  build:\n    image: swift-package-manager:20.04-5.4\n\n  test:\n    image: swift-package-manager:20.04-5.4\n\n  bootstrap-clean:\n    image: swift-package-manager:20.04-5.4\n\n  bootstrap-build:\n    image: swift-package-manager:20.04-5.4\n\n  bootstrap-test:\n    image: swift-package-manager:20.04-5.4\n\n  shell:\n    image: swift-package-manager:20.04-5.4\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.2004.55.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:20.04-5.5\n    build:\n      args:\n        ubuntu_version: \"focal\"\n        swift_version: \"5.5\"\n\n  build:\n    image: swift-package-manager:20.04-5.5\n\n  test:\n    image: swift-package-manager:20.04-5.5\n\n  bootstrap-clean:\n    image: swift-package-manager:20.04-5.5\n\n  bootstrap-build:\n    image: swift-package-manager:20.04-5.5\n\n  bootstrap-test:\n    image: swift-package-manager:20.04-5.5\n\n  shell:\n    image: swift-package-manager:20.04-5.5\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.2004.56.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:20.04-5.6\n    build:\n      args:\n        ubuntu_version: \"focal\"\n        swift_version: \"5.6\"\n\n  build:\n    image: swift-package-manager:20.04-5.6\n\n  test:\n    image: swift-package-manager:20.04-5.6\n\n  bootstrap-clean:\n    image: swift-package-manager:20.04-5.6\n\n  bootstrap-build:\n    image: swift-package-manager:20.04-5.6\n\n  bootstrap-test:\n    image: swift-package-manager:20.04-5.6\n\n  shell:\n    image: swift-package-manager:20.04-5.6\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.2004.57.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2022 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:20.04-5.7\n    build:\n      args:\n        ubuntu_version: \"focal\"\n        swift_version: \"5.7\"\n\n  build:\n    image: swift-package-manager:20.04-5.7\n\n  test:\n    image: swift-package-manager:20.04-5.7\n\n  bootstrap-clean:\n    image: swift-package-manager:20.04-5.7\n\n  bootstrap-build:\n    image: swift-package-manager:20.04-5.7\n\n  bootstrap-test:\n    image: swift-package-manager:20.04-5.7\n\n  shell:\n    image: swift-package-manager:20.04-5.7\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.2004.main.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:20.04-main\n    build:\n      args:\n        ubuntu_version: \"focal\"\n        swift_version: \"main\"\n        base_image: \"swiftlang/swift:nightly-main-focal\"\n\n  build:\n    image: swift-package-manager:20.04-main\n\n  test:\n    image: swift-package-manager:20.04-main\n\n  bootstrap-clean:\n    image: swift-package-manager:20.04-main\n\n  bootstrap-build:\n    image: swift-package-manager:20.04-main\n\n  bootstrap-test:\n    image: swift-package-manager:20.04-main\n\n  shell:\n    image: swift-package-manager:20.04-main\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.2204.58.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:22.04-5.8\n    build:\n      args:\n        ubuntu_version: \"jammy\"\n        swift_version: \"5.8\"\n        base_image: \"swiftlang/swift:nightly-5.8-jammy\"\n\n  build:\n    image: swift-package-manager:22.04-5.8\n\n  test:\n    image: swift-package-manager:22.04-5.8\n\n  bootstrap-clean:\n    image: swift-package-manager:22.04-5.8\n\n  bootstrap-build:\n    image: swift-package-manager:22.04-5.8\n\n  bootstrap-test:\n    image: swift-package-manager:22.04-5.8\n\n  shell:\n    image: swift-package-manager:22.04-5.8\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.2204.59.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:22.04-5.9\n    build:\n      args:\n        ubuntu_version: \"jammy\"\n        swift_version: \"5.9\"\n        base_image: \"swiftlang/swift:nightly-5.9-jammy\"\n\n  build:\n    image: swift-package-manager:22.04-5.9\n\n  test:\n    image: swift-package-manager:22.04-5.9\n\n  bootstrap-clean:\n    image: swift-package-manager:22.04-5.9\n\n  bootstrap-build:\n    image: swift-package-manager:22.04-5.9\n\n  bootstrap-test:\n    image: swift-package-manager:22.04-5.9\n\n  shell:\n    image: swift-package-manager:22.04-5.9\n"
  },
  {
    "path": "Utilities/Docker/docker-compose.yaml",
    "content": "# This source file is part of the Swift open source project\n#\n# Copyright (c) 2021-2023 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\n# this file is not designed to be run directly\n# instead, use the docker-compose.<os>.<swift> files\n# eg docker-compose -f Utilities/docker/docker-compose.yaml -f Utilities/docker/docker-compose.2004.57.yaml run test\nversion: \"3\"\n\nservices:\n\n  runtime-setup:\n    image: swift-package-manager:default\n    build:\n      context: .\n      dockerfile: Dockerfile\n\n  common: &common\n    image: swift-package-manager:default\n    depends_on: [runtime-setup]\n    volumes:\n      # ssh, caches\n      - ~/.ssh:/root/.ssh\n      - ~/.cache:/root/.cache\n      - ~/.swiftpm/cache:/root/.swiftpm/cache\n      - ~/.swiftpm/configuration:/root/.swiftpm/config  # old location, remove after 5.6\n      - ~/.swiftpm/configuration:/root/.swiftpm/configuration\n      - ~/.swiftpm/security:/root/.swiftpm/security\n      # swift-package-manager code\n      - ../..:/code/swift-package-manager:z\n      # bootstrap script requires dependencies to be pre-fetched and in a specific place\n      - ../../../swift-tools-support-core:/code/swift-tools-support-core:z\n      - ../../../yams:/code/yams:z\n      - ../../../swift-argument-parser:/code/swift-argument-parser:z\n      - ../../../swift-crypto:/code/swift-crypto:z\n      - ../../../swift-driver:/code/swift-driver:z\n      - ../../../swift-llbuild:/code/llbuild:z\n      - ../../../swift-system:/code/swift-system:z\n      - ../../../swift-collections:/code/swift-collections:z\n      - ../../../swift-asn1:/code/swift-asn1:z\n      - ../../../swift-certificates:/code/swift-certificates:z\n    working_dir: /code/swift-package-manager\n    cap_drop:\n      - CAP_NET_RAW\n      - CAP_NET_BIND_SERVICE\n\n  build:\n    <<: *common\n    command: /bin/bash -cl \"swift build\"\n\n  test:\n    <<: *common\n    command: /bin/bash -cl \"swift test --parallel\"\n\n  bootstrap-clean:\n    <<: *common\n    command: /bin/bash -cl \"./Utilities/bootstrap clean\"\n\n  bootstrap-build:\n    <<: *common\n    command: /bin/bash -cl \"./Utilities/bootstrap build\"\n\n  bootstrap-test:\n    <<: *common\n    command: /bin/bash -cl \"./Utilities/bootstrap test\"\n\n  # util\n\n  shell:\n    <<: *common\n    entrypoint: /bin/bash\n"
  },
  {
    "path": "Utilities/InstalledSwiftPMConfiguration/Package.swift",
    "content": "// swift-tools-version: 5.9\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"InstalledSwiftPMConfiguration\",\n    targets: [\n        .executableTarget(\n            name: \"InstalledSwiftPMConfiguration\"\n        ),\n    ]\n)\n"
  },
  {
    "path": "Utilities/InstalledSwiftPMConfiguration/Sources/exec.swift",
    "content": "//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport Foundation\n\n@main\nstruct Exec {\n  static func main() throws {\n      let config = InstalledSwiftPMConfiguration(version: 1, swiftSyntaxVersionForMacroTemplate: .init(major: 509, minor: 0, patch: 0))\n      let data = try JSONEncoder().encode(config)\n      try data.write(to: URL(fileURLWithPath: \"config.json\"))\n  }\n}\n"
  },
  {
    "path": "Utilities/README.md",
    "content": "# Windows Self-Hosted Test\n\nHere are some steps the worked running on Windows.\n\n1. Install Docker on a Windows host\n2. Launch a `Powershell.exe` session\n3. Run the following in power shell to start a container running the nightly toolchain\n    ```\n    docker run --pull always --rm --interactive --tty swiftlang/swift:nightly-6.2-windowsservercore-1809 powershell.exe\n    ```\n4. When the container start, clone the \"merged\" PR to `C:\\source`\n    ```\n    mkdir C:\\source\n    cd C:\\source\n    git clone https://github.com/swiftlang/swift-package-manager .\n    # Assign the PR ID to a variable\n    $PR_ID = \"8288\"\n    git fetch origin pull/$PR_ID/merge\n    git checkout FETCH_HEAD\n    ```\n5. Run the CI pipeline script\n    ```\n    python C:\\source\\Utilities\\build-using-self  --enable-swift-testing --enable-xctest\n    ```\n"
  },
  {
    "path": "Utilities/SwiftPM+SwiftBuild.xcworkspace/contents.xcworkspacedata",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n   version = \"1.0\">\n   <FileRef\n      location = \"container:../../swift-build\">\n   </FileRef>\n   <FileRef\n      location = \"container:../../swiftpm\">\n   </FileRef>\n</Workspace>\n"
  },
  {
    "path": "Utilities/bootstrap",
    "content": "#!/usr/bin/env python3\n# encoding: utf-8\n\n\"\"\"\n This source file is part of the Swift open source project\n//\n// Copyright (c) 2014-2023 Apple Inc. and the Swift project authors\n Licensed under Apache License v2.0 with Runtime Library Exception\n\n See http://swift.org/LICENSE.txt for license information\n See http://swift.org/CONTRIBUTORS.txt for Swift project authors\n\n -------------------------------------------------------------------------\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport json\nimport logging\nimport os\nimport pathlib\nimport platform\nimport re\nimport shutil\nimport subprocess\nimport sys\nfrom helpers import symlink_force, mkdir_p, call, call_output\n\n\nlogging.basicConfig(\n    stream=sys.stdout,\n    format=\" | \".join([\n            f\"--- {pathlib.Path(sys.argv[0]).name}\",  # Prefix script name to the log in an attempt to avoid confusion when parsing logs\n            \"%(asctime)s\",\n            \"%(levelname)-7s\",\n            \"%(threadName)s\",\n            \"%(module)s\",\n            \"%(funcName)s\",\n            \"Line:%(lineno)d\",\n            \"%(message)s\",\n    ]),\n    level=logging.INFO,\n)\ng_macos_deployment_target = '14.0'\n\ng_shared_lib_prefix = \"lib\"\nif platform.system() == 'Darwin':\n    g_shared_lib_suffix = \".dylib\"\nelse:\n    g_shared_lib_suffix = \".so\"\n\nclass BinaryNotFound(BaseException):\n\n    def __init__(self, *, tool: str, path: pathlib.Path):\n        super().__init__(f\"Unable to find {tool} source directory at {path}\")\n\ndef log_entry_exit(func):\n    def wrapper(*args, **kwargs):\n        logging.debug(\"Starting call to %s ...\", func.__name__)\n        try:\n            return func(*args, **kwargs)\n        finally:\n            logging.debug(\"Done call to %s ...\", func.__name__)\n\n    return wrapper\n\n@log_entry_exit\ndef main():\n    parser = argparse.ArgumentParser(description=\"\"\"\n        This script will build a bootstrapped copy of the Swift Package Manager, and optionally perform extra\n        actions like installing the result (with 'install') to a location ('--prefix').\n        \"\"\")\n    subparsers = parser.add_subparsers(dest='command')\n    subparsers.required = True\n\n    # clean\n    parser_clean = subparsers.add_parser(\"clean\", help=\"cleans build artifacts\")\n    parser_clean.set_defaults(func=clean)\n    add_global_args(parser_clean)\n\n    # build\n    parser_build = subparsers.add_parser(\"build\", help=\"builds SwiftPM and runtime libraries\")\n    parser_build.set_defaults(func=build)\n    add_build_args(parser_build)\n\n    # test\n    parser_test = subparsers.add_parser(\"test\", help=\"builds and tests SwiftPM\")\n    parser_test.set_defaults(func=test)\n    add_test_args(parser_test)\n\n    # install\n    parser_install = subparsers.add_parser(\"install\", help=\"builds and installs SwiftPM and runtime libraries\")\n    parser_install.set_defaults(func=install)\n    add_build_args(parser_install)\n\n    logging.info(\"sys.argv: %r\", sys.argv)\n    args = parser.parse_args()\n    # update the root logger level based on the verbose flag\n    logging.getLogger().setLevel(logging.DEBUG if args.verbose else logging.INFO)\n    args.func = args.func or build\n    args.func(args)\n\n# -----------------------------------------------------------\n# Argument parsing\n# -----------------------------------------------------------\n\n@log_entry_exit\ndef add_global_args(parser):\n    \"\"\"Configures the parser with the arguments necessary for all actions.\"\"\"\n    parser.add_argument(\n        \"--build-dir\",\n        help=\"path where products will be built [%(default)s]\",\n        default=\".build\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"-v\", \"--verbose\",\n        action=\"store_true\",\n        help=\"whether to print verbose output\")\n    parser.add_argument(\n        \"--reconfigure\",\n        action=\"store_true\",\n        help=\"whether to always reconfigure cmake\")\n    parser.add_argument(\n        \"--install-only\",\n        action=\"store_true\",\n        default=False)\n\n@log_entry_exit\ndef add_build_args(parser):\n    \"\"\"Configures the parser with the arguments necessary for build-related actions.\"\"\"\n    add_global_args(parser)\n    parser.add_argument(\n        \"--swift-build-path\",\n        help=\"path to the prebuilt SwiftPM `swift-build` binary\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"--swiftc-path\",\n        help=\"path to the swift compiler\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"--clang-path\",\n        help=\"path to the clang compiler\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        '--cmake-path',\n        metavar='PATH',\n        help='path to the cmake binary to use for building')\n    parser.add_argument(\n        '--ninja-path',\n        metavar='PATH',\n        help='path to the ninja binary to use for building with CMake')\n    parser.add_argument(\n        '--ar-path',\n        metavar='PATH',\n        help='path to the ar binary to use for building with CMake')\n    parser.add_argument(\n        '--ranlib-path',\n        metavar='PATH',\n        help='path to the ranlib binary to use for building with CMake')\n    parser.add_argument(\n        \"--dispatch-build-dir\",\n        help=\"path to Dispatch build directory\")\n    parser.add_argument(\n        \"--foundation-build-dir\",\n        help=\"path to Foundation build directory\")\n    parser.add_argument(\n        \"--llbuild-build-dir\",\n        help=\"path to llbuild build directory\")\n    parser.add_argument(\n        \"--llbuild-link-framework\",\n        action=\"store_true\",\n        help=\"whether to link to the llbuild framework\")\n    parser.add_argument(\n        \"--release\",\n        action=\"store_true\",\n        help=\"enables building SwiftPM in release mode\")\n    parser.add_argument(\n        \"--skip-cmake-bootstrap\",\n        action=\"store_true\",\n        help=\"build with prebuilt package manager in toolchain if it exists\")\n    parser.add_argument(\n        \"--libswiftpm-install-dir\",\n        metavar='PATH',\n        help=\"where to install libSwiftPM\")\n    parser.add_argument(\n        \"--libswiftpmdatamodel-install-dir\",\n        metavar='PATH',\n        help=\"where to install libSwiftPMDataModel\")\n    parser.add_argument(\n        \"--prefix\",\n        dest=\"install_prefixes\",\n        nargs='*',\n        help=\"paths (relative to the project root) where to install build products [%(default)s]\",\n        default=[\"/tmp/swiftpm\"],\n        metavar=\"PATHS\")\n    parser.add_argument(\n        \"--cross-compile-hosts\",\n        dest=\"cross_compile_hosts\",\n        help=\"List of cross compile hosts targets.\",\n        default=[])\n    parser.add_argument(\n        \"--cross-compile-config\",\n        help=\"Swift flags to cross-compile SwiftPM with itself\")\n\n@log_entry_exit\ndef add_test_args(parser):\n    \"\"\"Configures the parser with the arguments necessary for the test action.\"\"\"\n    add_build_args(parser)\n    parser.add_argument(\n        \"--parallel\",\n        action=\"store_true\",\n        help=\"whether to run tests in parallel\",\n        default=True)\n    parser.add_argument(\n        \"--filter\",\n        action=\"append\",\n        help=\"filter to apply on which tests to run\",\n        default=[])\n    parser.add_argument(\n        \"--skip-integrated-driver-tests\",\n        action=\"store_true\",\n        help=\"whether to skip tests with the integrated driver\",\n        default=True)\n\n@log_entry_exit\ndef parse_global_args(args):\n    \"\"\"Parses and cleans arguments necessary for all actions.\"\"\"\n    # Test if 'build_dirs' and 'source_dirs' exist, and initialise them only if not.\n    # Otherwise, both are reset to empty dictionaries every time 'parse_global_args' is called, which crashes 'test', because 'test' calls it (via 'parse_test_args' → 'parse_build_args') after 'build' has called it (via 'parse_build_args').\n    try:\n        args.build_dirs\n    except AttributeError:\n        args.build_dirs = {}\n    try:\n        args.source_dirs\n    except AttributeError:\n        args.source_dirs = {}\n    args.build_dir                            = os.path.abspath(args.build_dir)\n    args.project_root                         = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n    args.source_dirs[\"tsc\"]                   = os.path.join(args.project_root, \"..\", \"swift-tools-support-core\")\n    args.source_dirs[\"swift-argument-parser\"] = os.path.join(args.project_root, \"..\", \"swift-argument-parser\")\n    args.source_dirs[\"swift-crypto\"]          = os.path.join(args.project_root, \"..\", \"swift-crypto\")\n    args.source_dirs[\"swift-driver\"]          = os.path.join(args.project_root, \"..\", \"swift-driver\")\n    args.source_dirs[\"swift-system\"]          = os.path.join(args.project_root, \"..\", \"swift-system\")\n    args.source_dirs[\"swift-collections\"]     = os.path.join(args.project_root, \"..\", \"swift-collections\")\n    args.source_dirs[\"swift-tools-protocols\"] = os.path.join(args.project_root, \"..\", \"swift-tools-protocols\")\n    args.source_dirs[\"swift-certificates\"]    = os.path.join(args.project_root, \"..\", \"swift-certificates\")\n    args.source_dirs[\"swift-asn1\"]            = os.path.join(args.project_root, \"..\", \"swift-asn1\")\n    args.source_dirs[\"swift-syntax\"]          = os.path.join(args.project_root, \"..\", \"swift-syntax\")\n    args.source_dirs[\"swift-build\"]           = os.path.join(args.project_root, \"..\", \"swift-build\")\n    args.source_root                          = os.path.join(args.project_root, \"Sources\")\n\n    if platform.system() == 'Darwin':\n        args.sysroot = call_output([\"xcrun\", \"--sdk\", \"macosx\", \"--show-sdk-path\"], verbose=args.verbose)\n    else:\n        args.sysroot = None\n\n@log_entry_exit\ndef parse_build_args(args):\n    \"\"\"Parses and cleans arguments necessary for build-related actions.\"\"\"\n    parse_global_args(args)\n\n    if args.dispatch_build_dir:\n        args.dispatch_build_dir = os.path.abspath(args.dispatch_build_dir)\n\n    if args.foundation_build_dir:\n        args.foundation_build_dir = os.path.abspath(args.foundation_build_dir)\n\n    if args.llbuild_build_dir:\n        args.build_dirs[\"llbuild\"] = os.path.abspath(args.llbuild_build_dir)\n\n    args.swiftc_path = get_swiftc_path(args)\n    logging.debug(\"Returned value of get_swiftc_path(args): %r\", get_swiftc_path(args))\n    logging.debug(\"Settings args.swiftc_path to %r\", args.swiftc_path)\n    args.clang_path = get_tool_path(args, \"clang\")\n    args.clangxx_path = get_tool_path(args, \"clang++\")\n    if not args.skip_cmake_bootstrap:\n        args.cmake_path = get_tool_path(args, \"cmake\")\n        args.ninja_path = get_tool_path(args, \"ninja\")\n    args.ar_path = get_tool_path(args, \"ar\")\n    args.ranlib_path = get_tool_path(args, \"ranlib\")\n    if args.cross_compile_hosts:\n        if re.match(\"macosx-\", args.cross_compile_hosts):\n            # Use XCBuild target directory when building for multiple arches.\n            args.target_dir = os.path.join(args.build_dir, \"apple/Products\")\n        elif re.match('android-', args.cross_compile_hosts):\n            args.target_dir = os.path.join(\n                                  args.build_dir,\n                                  get_build_target(args,cross_compile=True))\n    else:\n        if platform.system() == 'FreeBSD':\n            args.target_dir = os.path.join(args.build_dir, get_unversioned_build_target(args))\n        else:\n            args.target_dir = os.path.join(args.build_dir, get_build_target(args))\n    args.bootstrap_dir = os.path.join(args.target_dir, \"bootstrap\")\n    args.conf = 'release' if args.release else 'debug'\n    args.bin_dir = os.path.join(args.target_dir, args.conf)\n    args.bootstrap = not args.skip_cmake_bootstrap or \\\n                     not os.path.exists(os.path.join(os.path.split(args.swiftc_path)[0], \"swift-build\"))\n\n@log_entry_exit\ndef parse_test_args(args):\n    \"\"\"Parses and cleans arguments necessary for the test action.\"\"\"\n    parse_build_args(args)\n\n@log_entry_exit\ndef get_swiftc_path(args):\n    \"\"\"Returns the path to the Swift compiler.\"\"\"\n    logging.debug(\"Getting path to swiftc...\")\n    if args.swiftc_path:\n        swiftc_path = os.path.abspath(args.swiftc_path)\n        logging.debug(\"path provided via command line argument. swiftc_path is %r\", swiftc_path)\n    elif os.getenv(\"SWIFT_EXEC\"):\n        swiftc_path = os.getenv(\"SWIFT_EXEC\")\n        logging.debug(\"SWIFT_EXEC env set. swiftc_path set to %r\", swiftc_path)\n    elif platform.system() == 'Darwin':\n        logging.debug(\"we are on darwin, so calling `xcrun --find swiftc`\")\n        swiftc_path = call_output(\n            [\"xcrun\", \"--find\", \"swiftc\"],\n            stderr=subprocess.PIPE,\n            verbose=args.verbose,\n        )\n        logging.debug(\"swiftc_path is set to %r\", swiftc_path)\n    else:\n        swiftc_path = call_output([\"which\", \"swiftc\"], verbose=args.verbose)\n        logging.debug(\"calling 'which swiftc'.  path is  %r\", swiftc_path)\n\n    if os.path.basename(swiftc_path) == 'swift':\n        swiftc_path = swiftc_path + 'c'\n        logging.debug(\"appending to path, it is now %r\", swiftc_path)\n\n    logging.debug(\"swiftc_path set to %r\", swiftc_path)\n    if os.path.exists(swiftc_path):\n        logging.debug(\"swiftc_path exists.. returning %r...\", swiftc_path)\n        return swiftc_path\n    logging.error(\"unable to find swiftc at %s\", swiftc_path)\n    raise BinaryNotFound(tool=\"swiftc\", path=swiftc_path)\n\n@log_entry_exit\ndef get_tool_path(args, tool):\n    \"\"\"Returns the path to the specified tool.\"\"\"\n    logging.debug(\"Searching for %s tool\", tool)\n    path = getattr(args, tool + \"_path\", None)\n    if path is not None:\n        return os.path.abspath(path)\n    elif platform.system() == 'Darwin':\n        return call_output(\n            [\"xcrun\", \"--find\", tool],\n            stderr=subprocess.PIPE,\n            verbose=args.verbose,\n        )\n    else:\n        return call_output([\"which\", tool], verbose=args.verbose)\n\n@log_entry_exit\ndef get_build_target(args, cross_compile=False):\n    \"\"\"Returns the target-triple of the current machine or for cross-compilation.\"\"\"\n    try:\n        command = [args.swiftc_path, '-print-target-info']\n        if cross_compile:\n            cross_compile_json = json.load(open(args.cross_compile_config))\n            command += ['-target', cross_compile_json[\"target\"]]\n        logging.debug(\"Running command >>> %r\", command)\n        target_info_json = subprocess.check_output(command,\n                               stderr=subprocess.PIPE, universal_newlines=True, env=os.environ).strip()\n        logging.debug(\"Command returned: %r\", target_info_json)\n        args.target_info = json.loads(target_info_json)\n        return args.target_info[\"target\"][\"unversionedTriple\" if platform.system() == 'Darwin' else \"triple\"]\n    except subprocess.CalledProcessError as cpe:\n        logging.debug(\"Command failed...\")\n        # Temporary fallback for Darwin.\n        if platform.system() == 'Darwin':\n            macOS_default = 'x86_64-apple-macosx'\n            logging.debug(\"we are on Darwin. defaulting to %r\", macOS_default)\n            return macOS_default\n        else:\n            logging.error(\"get build targets: %s\", str(cpe))\n            raise cpe\n\ndef get_unversioned_build_target(args, cross_compile=False):\n    \"\"\"Returns the target-triple of the current machine or for cross-compilation.\"\"\"\n    try:\n        command = [args.swiftc_path, '-print-target-info']\n        if cross_compile:\n            cross_compile_json = json.load(open(args.cross_compile_config))\n            command += ['-target', cross_compile_json[\"target\"]]\n        logging.debug(\"Running command >>> %r\", command)\n        target_info_json = subprocess.check_output(command,\n                               stderr=subprocess.PIPE, universal_newlines=True, env=os.environ).strip()\n        logging.debug(\"Command returned: %r\", target_info_json)\n        args.target_info = json.loads(target_info_json)\n        return args.target_info[\"target\"][\"unversionedTriple\"]\n    except subprocess.CalledProcessError as cpe:\n        logging.debug(\"Command failed...\")\n        # Temporary fallback for Darwin.\n        if platform.system() == 'Darwin':\n            macOS_default = 'x86_64-apple-macosx'\n            logging.debug(\"we are on Darwin. defaulting to %r\", macOS_default)\n            return macOS_default\n        else:\n            logging.error(\"get build targets: %s\", str(cpe))\n            raise cpe\n\n# -----------------------------------------------------------\n# Actions\n# -----------------------------------------------------------\n\n@log_entry_exit\ndef clean(args):\n    \"\"\"Cleans the build artifacts.\"\"\"\n    logging.info(\"Cleaning\")\n    parse_global_args(args)\n\n    call([\"rm\", \"-rf\", args.build_dir], verbose=args.verbose)\n\n@log_entry_exit\ndef build(args):\n    \"\"\"Builds SwiftPM using a two-step process: first using CMake, then with itself.\"\"\"\n    parse_build_args(args)\n\n    if args.bootstrap:\n        logging.info(\"Building bootstrap\")\n        # Build llbuild if its build path is not passed in.\n        if not \"llbuild\" in args.build_dirs:\n            build_llbuild(args)\n\n        # tsc depends on swift-system so they must be built first.\n        build_dependency(args, \"swift-system\")\n        # swift-driver depends on tsc and swift-argument-parser so they must be built first.\n        tsc_cmake_flags = [\n            \"-DSwiftSystem_DIR=\"    + os.path.join(args.build_dirs[\"swift-system\"], \"cmake/modules\"),\n        ]\n        build_dependency(args, \"tsc\", tsc_cmake_flags)\n        build_dependency(args, \"swift-argument-parser\", [\"-DBUILD_TESTING=NO\", \"-DBUILD_EXAMPLES=NO\"])\n\n        swift_driver_cmake_flags = [\n            get_llbuild_cmake_arg(args),\n            \"-DSwiftSystem_DIR=\"    + os.path.join(args.build_dirs[\"swift-system\"], \"cmake/modules\"),\n            \"-DTSC_DIR=\" + os.path.join(args.build_dirs[\"tsc\"], \"cmake/modules\"),\n            \"-DArgumentParser_DIR=\" + os.path.join(args.build_dirs[\"swift-argument-parser\"], \"cmake/modules\"),\n        ]\n        build_dependency(args, \"swift-driver\", swift_driver_cmake_flags)\n        build_dependency(args, \"swift-collections\")\n        build_dependency(args, \"swift-tools-protocols\")\n        build_dependency(args, \"swift-asn1\")\n        build_dependency(args, \"swift-crypto\",\n            [\"-DSwiftASN1_DIR=\" + os.path.join(args.build_dirs[\"swift-asn1\"], \"cmake/modules\")])\n        build_dependency(args, \"swift-certificates\",\n            [\"-DSwiftASN1_DIR=\" + os.path.join(args.build_dirs[\"swift-asn1\"], \"cmake/modules\"),\n             \"-DSwiftCrypto_DIR=\" + os.path.join(args.build_dirs[\"swift-crypto\"], \"cmake/modules\")])\n        swift_build_cmake_flags = [\n            get_llbuild_cmake_arg(args),\n            \"-DSwiftSystem_DIR=\"    + os.path.join(args.build_dirs[\"swift-system\"], \"cmake/modules\"),\n            \"-DSwiftASN1_DIR=\" + os.path.join(args.build_dirs[\"swift-asn1\"], \"cmake/modules\"),\n            \"-DSwiftCrypto_DIR=\" + os.path.join(args.build_dirs[\"swift-crypto\"], \"cmake/modules\"),\n            \"-DTSC_DIR=\" + os.path.join(args.build_dirs[\"tsc\"], \"cmake/modules\"),\n            \"-DArgumentParser_DIR=\" + os.path.join(args.build_dirs[\"swift-argument-parser\"], \"cmake/modules\"),\n            \"-DSwiftDriver_DIR=\" + os.path.join(args.build_dirs[\"swift-driver\"], \"cmake/modules\"),\n            \"-DSwiftToolsProtocols_DIR=\" + os.path.join(args.build_dirs[\"swift-tools-protocols\"], \"cmake/modules\"),\n        ]\n        build_dependency(args, \"swift-build\", swift_build_cmake_flags)\n        build_swiftpm_with_cmake(args)\n\n    build_swiftpm_with_swiftpm(args,integrated_swift_driver=False)\n\n@log_entry_exit\ndef test(args):\n    \"\"\"Builds SwiftPM, then tests itself.\"\"\"\n    build(args)\n\n    logging.info(\"Testing\")\n    parse_test_args(args)\n    cmd = [\n        os.path.join(args.bin_dir, \"swift-test\")\n    ]\n    if args.parallel:\n        cmd.append(\"--parallel\")\n    for arg in args.filter:\n        cmd.extend([\"--filter\", arg])\n\n    # Test SwiftPM.\n    call_swiftpm(args, cmd)\n\n    if args.skip_integrated_driver_tests:\n        return\n\n    # Build SwiftPM with the integrated driver.\n    logging.info(\"Bootstrap with the integrated Swift driver\")\n    build_swiftpm_with_swiftpm(args,integrated_swift_driver=True)\n\n    # Test SwiftPM with the integrated driver. Only the build and\n    # functional tests are interesting.\n    integratedDriverCmd = cmd\n    integratedDriverCmd.append(\"--use-integrated-swift-driver\")\n    if args.filter:\n        integratedDriverCmd.append(\"--filter\")\n        integratedDriverCmd.append(\"BuildTests;FunctionalTests\")\n    call_swiftpm(args, integratedDriverCmd)\n\n@log_entry_exit\ndef install(args):\n    \"\"\"Builds SwiftPM, then installs its build products.\"\"\"\n    if args.install_only:\n        parse_build_args(args)\n    else:\n        build(args)\n\n    # Install swiftpm content in all of the passed prefixes.\n    for prefix in args.install_prefixes:\n        install_swiftpm(prefix, args)\n        config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"config.json\")\n        install_file(args, config_path, os.path.join(os.path.join(prefix, \"share\"), \"pm\"))\n\n        libs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"provided-libraries.json\")\n        install_file(args, config_path, os.path.join(os.path.join(prefix, \"share\"), \"pm\"))\n\n    # Install libSwiftPM if an install directory was provided.\n    if args.libswiftpm_install_dir:\n        libswiftpm_modules = [\n            \"TSCLibc\", \"TSCBasic\",\n            \"TSCUtility\", \"SourceControl\",\n            \"SPMLLBuild\", \"LLBuildManifest\",\n            \"PackageModel\", \"PackageLoading\",\n            \"PackageGraph\", \"SPMBuildCore\", \"Build\",\n            \"Workspace\"\n        ]\n        install_dylib(args, \"SwiftPM\", args.libswiftpm_install_dir, libswiftpm_modules)\n\n    # Install libSwiftPMDataModel if an install directory was provided.\n    if args.libswiftpmdatamodel_install_dir:\n        libswiftpmdatamodel_modules = [\n            \"TSCLibc\", \"TSCBasic\",\n            \"TSCUtility\", \"SourceControl\",\n            \"PackageModel\", \"PackageLoading\",\n            \"PackageGraph\", \"SPMBuildCore\",\n            \"Workspace\"\n        ]\n        install_dylib(args, \"SwiftPMDataModel\", args.libswiftpmdatamodel_install_dir, libswiftpmdatamodel_modules)\n\n# Installs the SwiftPM tools and runtime support libraries.\n@log_entry_exit\ndef install_swiftpm(prefix, args):\n    # Install the swift-package-manager tool and create symlinks to it.\n    cli_tool_dest = os.path.join(prefix, \"bin\")\n    aux_tool_dest = os.path.join(prefix, \"libexec\", \"swift\", \"pm\")\n\n    install_binary(args, \"swift-package-manager\", os.path.join(cli_tool_dest, \"swift-package\"), destination_is_directory=False)\n\n    # `swiftpm-testing-helper` only exists on Darwin platforms\n    if os.path.exists(os.path.join(args.bin_dir, \"swiftpm-testing-helper\")):\n        install_binary(args, \"swiftpm-testing-helper\", aux_tool_dest)\n\n    for tool in [\"swift-build\", \"swift-test\", \"swift-run\", \"swift-package-collection\", \"swift-package-registry\", \"swift-sdk\", \"swift-experimental-sdk\"]:\n        src = \"swift-package\"\n        dest = os.path.join(cli_tool_dest, tool)\n        logging.info(\"Creating tool symlink from %s to %s\", src, dest)\n        symlink_force(src, dest)\n\n    # Install the PackageDescription/CompilerPluginSupport libraries and associated modules.\n    dest = os.path.join(prefix, \"lib\", \"swift\", \"pm\", \"ManifestAPI\")\n    install_dylib(args, \"PackageDescription\", dest, [\"PackageDescription\", \"CompilerPluginSupport\"])\n\n    # Install the PackagePlugin library and associated modules.\n    dest = os.path.join(prefix, \"lib\", \"swift\", \"pm\", \"PluginAPI\")\n    install_dylib(args, \"PackagePlugin\", dest, [\"PackagePlugin\"])\n\n    # Install resource bundles produced during the build.\n    for file in os.listdir(args.bin_dir):\n        if file.endswith('.bundle') or file.endswith('.resources'):\n            install_binary(args, file, os.path.join(os.path.join(prefix, \"share\"), \"pm\"))\n\n\n# Helper function that installs a dynamic library and a set of modules to a particular directory.\n@log_entry_exit\ndef install_dylib(args, library_name, install_dir, module_names):\n    # Install the dynamic library itself.\n    install_binary(args, g_shared_lib_prefix + library_name + g_shared_lib_suffix, install_dir)\n\n    # Install the swiftmodule/swiftinterface and swiftdoc files for all the modules.\n    for module in module_names:\n        # If we're cross-compiling, we expect the .swiftmodule to be a directory that contains everything.\n        if args.cross_compile_hosts and re.match(\"macosx-\", args.cross_compile_hosts):\n            install_binary(args, module + \".swiftmodule\", install_dir, ['Project', '*.swiftmodule'])\n        elif args.cross_compile_hosts:\n            install_binary(args, module + \".swiftmodule\", install_dir, ['Project', '*.swiftmodule'], subpath=\"Modules\")\n        else:\n            # Otherwise we have either a .swiftinterface or a .swiftmodule, plus a .swiftdoc.\n            if os.path.exists(os.path.join(args.bin_dir, module + \".swiftinterface\")):\n                install_binary(args, module + \".swiftinterface\", install_dir, subpath=\"Modules\")\n            else:\n                install_binary(args, module + \".swiftmodule\", install_dir, subpath=\"Modules\")\n            install_binary(args, module + \".swiftdoc\", install_dir, subpath=\"Modules\")\n\n\n# Helper function that installs a single built artifact to a particular directory. The source may be either a file or a directory.\n@log_entry_exit\ndef install_binary(args, binary, destination, destination_is_directory=True, ignored_patterns=[], subpath=None):\n    if subpath:\n        basepath = os.path.join(args.bin_dir, subpath)\n    else:\n        basepath = args.bin_dir\n    src = os.path.join(basepath, binary)\n    install_file(args, src, destination, destination_is_directory=destination_is_directory, ignored_patterns=ignored_patterns)\n\n@log_entry_exit\ndef install_file(args, src, destination, destination_is_directory=True, ignored_patterns=[]):\n    if destination_is_directory:\n        dest = os.path.join(destination, os.path.basename(src))\n        mkdir_p(os.path.dirname(dest))\n    else:\n        dest = destination\n\n    logging.info(\"Installing %s to %s\", src, dest)\n    if os.path.isdir(src):\n        additional_kwargs = { \"dirs_exist_ok\": True } if sys.version_info.major >=3 and sys.version_info.minor >= 8 else {}\n        shutil.copytree(src, dest, ignore=shutil.ignore_patterns(*ignored_patterns), **additional_kwargs)\n    else:\n        shutil.copy2(src, dest)\n\n# -----------------------------------------------------------\n# Build functions\n# -----------------------------------------------------------\n\n@log_entry_exit\ndef build_with_cmake(args, cmake_args, ninja_args, source_path, build_dir, cmake_env = []):\n    \"\"\"Runs CMake if needed, then builds with Ninja.\"\"\"\n    cache_path = os.path.join(build_dir, \"CMakeCache.txt\")\n    if args.reconfigure or not os.path.isfile(cache_path) or not args.swiftc_path in open(cache_path).read():\n        swift_flags = \"\"\n        if args.sysroot:\n            swift_flags = \"-sdk %s\" % args.sysroot\n\n        # Ensure we are not sharing the module cache with concurrent builds in CI\n        swift_flags += ' -module-cache-path \"{}\"'.format(os.path.join(build_dir, 'module-cache'))\n\n        cmd = [\n            \"env\"] + cmake_env + [\"MACOSX_DEPLOYMENT_TARGET=%s\" % (g_macos_deployment_target),\n            args.cmake_path, \"-G\", \"Ninja\",\n            \"-DCMAKE_MAKE_PROGRAM=%s\" % args.ninja_path,\n            \"-DCMAKE_BUILD_TYPE:=Debug\",\n            \"-DCMAKE_Swift_FLAGS='%s'\" % swift_flags,\n            \"-DCMAKE_Swift_COMPILER:=%s\" % (args.swiftc_path),\n            \"-DCMAKE_Swift_COMPILER_TARGET={}\".format((get_build_target(args) + g_macos_deployment_target) if platform.system() == 'Darwin' else get_build_target(args)),\n            \"-DCMAKE_C_COMPILER:=%s\" % (args.clang_path),\n            \"-DCMAKE_AR:PATH=%s\" % (args.ar_path),\n            \"-DCMAKE_RANLIB:PATH=%s\" % (args.ranlib_path),\n        ] + cmake_args + [source_path]\n\n        logging.debug(' '.join(cmd))\n\n        mkdir_p(build_dir)\n        call(cmd, cwd=build_dir, verbose=True)\n\n    # Build.\n    ninja_cmd = [args.ninja_path]\n\n    if args.verbose:\n        ninja_cmd.append(\"-v\")\n\n    if platform.system() == 'Darwin':\n        call([\"sed\", \"-i\", \"\", \"s/macosx10.10/macosx%s/\" % (g_macos_deployment_target), \"build.ninja\"], cwd=build_dir)\n\n    call(ninja_cmd + ninja_args, cwd=build_dir, verbose=args.verbose)\n\n@log_entry_exit\ndef build_llbuild(args):\n    \"\"\"Builds LLBuild using CMake.\"\"\"\n    logging.info(\"Building llbuild\")\n\n    # Set where we are going to build llbuild for future steps to find it\n    args.build_dirs[\"llbuild\"] = os.path.join(args.target_dir, \"llbuild\")\n\n    api_dir = os.path.join(args.build_dirs[\"llbuild\"], \".cmake/api/v1/query\")\n    mkdir_p(api_dir)\n    call([\"touch\", \"codemodel-v2\"], cwd=api_dir, verbose=args.verbose)\n\n    flags = [\n        \"-DCMAKE_C_COMPILER:=%s\" % (args.clang_path),\n        \"-DCMAKE_CXX_COMPILER:=%s\" % (args.clangxx_path),\n        \"-DCMAKE_AR:PATH=%s\" % (args.ar_path),\n        \"-DCMAKE_RANLIB:PATH=%s\" % (args.ranlib_path),\n        \"-DLLBUILD_SUPPORT_BINDINGS:=Swift\",\n    ]\n    cmake_env = []\n\n    if platform.system() == 'Darwin':\n        # On Darwin, make sure we're building for the host architecture.\n        flags.append(\"-DCMAKE_OSX_ARCHITECTURES:=%s\" % (get_build_target(args).split('-')[0]))\n        # Inject linkage of C++ standard library\n        cmake_env.append(\"LDFLAGS=-lc++\")\n\n    if args.sysroot:\n        flags.append(\"-DSQLite3_INCLUDE_DIR=%s/usr/include\" % args.sysroot)\n\n    args.source_dirs[\"llbuild\"] = get_llbuild_source_path(args)\n    build_with_cmake(args, flags, [], args.source_dirs[\"llbuild\"], args.build_dirs[\"llbuild\"], cmake_env=cmake_env)\n\n@log_entry_exit\ndef build_dependency(args, target_name, common_cmake_flags = [], non_darwin_cmake_flags = []):\n    logging.info(\"Building dependency %s\", target_name)\n    args.build_dirs[target_name] = os.path.join(args.target_dir, target_name)\n\n    cmake_flags = common_cmake_flags\n    if platform.system() == 'Darwin':\n        cmake_flags.append(\"-DCMAKE_C_FLAGS=-target %s%s\" % (get_build_target(args), g_macos_deployment_target))\n        cmake_flags.append(\"-DCMAKE_OSX_DEPLOYMENT_TARGET=%s\" % g_macos_deployment_target)\n    else:\n        cmake_flags += non_darwin_cmake_flags\n\n    build_with_cmake(args, cmake_flags, [], args.source_dirs[target_name], args.build_dirs[target_name])\n\n@log_entry_exit\ndef add_rpath_for_cmake_build(args, rpath):\n    \"Adds the given rpath to the CMake-built swift-bootstrap\"\n    swift_build = os.path.join(args.bootstrap_dir, \"bin/swift-bootstrap\")\n    add_rpath_cmd = [\"install_name_tool\", \"-add_rpath\", rpath, swift_build]\n    logging.info(' '.join(add_rpath_cmd))\n    subprocess.call(add_rpath_cmd, stderr=subprocess.PIPE, env=os.environ)\n\n@log_entry_exit\ndef get_swift_backdeploy_library_paths(args):\n    if platform.system() == 'Darwin':\n        return ['/usr/lib/swift']\n    else:\n        return []\n\n@log_entry_exit\ndef build_swiftpm_with_cmake(args):\n    \"\"\"Builds SwiftPM using CMake.\"\"\"\n    logging.info(\"Building SwiftPM (with CMake)\")\n\n    get_build_target(args)\n    module_triple = args.target_info[\"target\"][\"moduleTriple\"]\n\n    cmake_flags = [\n        get_llbuild_cmake_arg(args),\n        \"-DTSC_DIR=\"                 + os.path.join(args.build_dirs[\"tsc\"],                   \"cmake/modules\"),\n        \"-DArgumentParser_DIR=\"      + os.path.join(args.build_dirs[\"swift-argument-parser\"], \"cmake/modules\"),\n        \"-DSwiftToolsProtocols_DIR=\" + os.path.join(args.build_dirs[\"swift-tools-protocols\"], \"cmake/modules\"),\n        \"-DSwiftDriver_DIR=\"         + os.path.join(args.build_dirs[\"swift-driver\"],          \"cmake/modules\"),\n        \"-DSwiftSystem_DIR=\"         + os.path.join(args.build_dirs[\"swift-system\"],          \"cmake/modules\"),\n        \"-DSwiftCollections_DIR=\"    + os.path.join(args.build_dirs[\"swift-collections\"],     \"cmake/modules\"),\n        \"-DSwiftCrypto_DIR=\"         + os.path.join(args.build_dirs[\"swift-crypto\"],          \"cmake/modules\"),\n        \"-DSwiftASN1_DIR=\"           + os.path.join(args.build_dirs[\"swift-asn1\"],            \"cmake/modules\"),\n        \"-DSwiftCertificates_DIR=\"   + os.path.join(args.build_dirs[\"swift-certificates\"],    \"cmake/modules\"),\n        \"-DSwiftBuild_DIR=\"          + os.path.join(args.build_dirs[\"swift-build\"],           \"cmake/modules\"),\n        \"-DSWIFTPM_PATH_TO_SWIFT_SYNTAX_SOURCE=\" + args.source_dirs[\"swift-syntax\"],\n        \"-DSwiftPMRuntime_MODULE_TRIPLE={}\".format(module_triple),\n    ]\n\n    if platform.system() == 'Darwin':\n        cmake_flags.append(\"-DCMAKE_C_FLAGS=-target %s%s\" % (get_build_target(args), g_macos_deployment_target))\n        cmake_flags.append(\"-DCMAKE_OSX_DEPLOYMENT_TARGET=%s\" % g_macos_deployment_target)\n\n    build_with_cmake(args, cmake_flags, [\"swift-bootstrap\", \"PackageDescription\", \"PackagePlugin\", \"CompilerPluginSupport\"], args.project_root, args.bootstrap_dir)\n\n    mkdir_p(os.path.join(args.bootstrap_dir, \"pm\", \"ManifestAPI\"))\n    shutil.copy2(os.path.join(args.bootstrap_dir, \"Sources\", \"Runtimes\", \"PackageDescription\", \"PackageDescription.swiftmodule\", \"%s.swiftmodule\" % module_triple),\n                 os.path.join(args.bootstrap_dir, \"pm\", \"ManifestAPI\", \"PackageDescription.swiftmodule\"))\n    shutil.copy2(os.path.join(args.bootstrap_dir, \"Sources\", \"Runtimes\", \"CompilerPluginSupport\", \"CompilerPluginSupport.swiftmodule\", \"%s.swiftmodule\" % module_triple),\n                 os.path.join(args.bootstrap_dir, \"pm\", \"ManifestAPI\", \"CompilerPluginSupport.swiftmodule\"))\n\n    mkdir_p(os.path.join(args.bootstrap_dir, \"pm\", \"PluginAPI\"))\n    shutil.copy2(os.path.join(args.bootstrap_dir, \"Sources\", \"Runtimes\", \"PackagePlugin\", \"PackagePlugin.swiftmodule\", \"%s.swiftmodule\" % module_triple),\n                 os.path.join(args.bootstrap_dir, \"pm\", \"PluginAPI\", \"PackagePlugin.swiftmodule\"))\n\n    if args.llbuild_link_framework:\n        add_rpath_for_cmake_build(args, args.build_dirs[\"llbuild\"])\n\n    if platform.system() == \"Darwin\":\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-argument-parser\"], \"lib\"))\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-crypto\"],          \"lib\"))\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-driver\"],          \"lib\"))\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-system\"],          \"lib\"))\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-collections\"],     \"lib\"))\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-tools-protocols\"], \"lib\"))\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-asn1\"],            \"lib\"))\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-certificates\"],    \"lib\"))\n        add_rpath_for_cmake_build(args, os.path.join(args.build_dirs[\"swift-build\"],          \"lib\"))\n\n        # rpaths for compatibility libraries\n        for lib_path in get_swift_backdeploy_library_paths(args):\n            add_rpath_for_cmake_build(args, lib_path)\n\n@log_entry_exit\ndef build_swiftpm_with_swiftpm(args, integrated_swift_driver):\n    \"\"\"Builds SwiftPM using the version of SwiftPM built with CMake.\"\"\"\n\n    swiftpm_args = []\n\n    if args.bootstrap:\n        logging.info(\"Building SwiftPM (with a freshly built swift-bootstrap)\")\n        swiftpm_args.append(\"SWIFTPM_CUSTOM_LIBS_DIR=\" + os.path.join(args.bootstrap_dir, \"pm\"))\n        swiftpm_args.append(os.path.join(args.bootstrap_dir, \"bin/swift-bootstrap\"))\n    else:\n        logging.info(\"Building SwiftPM (with a prebuilt swift-build)\")\n        swiftpm_args.append(args.swift_build_path or os.path.join(os.path.split(args.swiftc_path)[0], \"swift-build\"))\n        swiftpm_args.append(\"--disable-sandbox\")\n\n        # Enforce resolved versions to avoid stray dependencies that aren't local.\n        swiftpm_args.append(\"--force-resolved-versions\")\n\n        # Any leftover resolved file from a run without `SWIFTCI_USE_LOCAL_DEPS` needs to be deleted.\n        if os.path.exists(\"Package.resolved\"):\n            logging.debug(\"removing Package.resolve\")\n            os.remove(\"Package.resolved\")\n\n    if integrated_swift_driver:\n        swiftpm_args.append(\"--use-integrated-swift-driver\")\n\n    # Build SwiftPM, including libSwiftPM, all the command line tools, and the current variant of PackageDescription.\n    call_swiftpm(args, swiftpm_args)\n\n    # Setup symlinks that'll allow using swiftpm from the build directory.\n    symlink_force(args.swiftc_path, os.path.join(args.target_dir, args.conf, \"swiftc\"))\n    symlink_force(args.swiftc_path, os.path.join(args.target_dir, args.conf, \"swift\"))\n    symlink_force(args.swiftc_path, os.path.join(args.target_dir, args.conf, \"swift-autolink-extract\"))\n\n    lib_dir = os.path.join(args.target_dir, \"lib\", \"swift\")\n\n    # Remove old cruft.\n    if os.path.isdir(lib_dir):\n        shutil.rmtree(lib_dir)\n\n    mkdir_p(lib_dir)\n\n    symlink_force(os.path.join(args.bootstrap_dir, \"pm\"), os.path.join(lib_dir, \"pm\"))\n\n@log_entry_exit\ndef call_swiftpm(args, cmd, cwd=None):\n    \"\"\"Calls a SwiftPM binary with the necessary environment variables and flags.\"\"\"\n    logging.info(\"function args: %r, cmd: %r, cwd: %r\", args, cmd, cwd)\n    args.build_target = get_build_target(args, cross_compile=(True if args.cross_compile_config else False))\n\n    logging.debug(\"build target: %r\", args.build_target)\n    args.platform_path = None\n    for path in args.target_info[\"paths\"][\"runtimeLibraryPaths\"]:\n        args.platform_path = re.search(r\"(lib/swift/([^/]+))$\", path)\n        if args.platform_path:\n            break\n    else:\n        # this gets called if the for loop does not break\n        logging.error(\n            \"the command `%s -print-target-info` didn't return a valid runtime library path\",\n            args.swiftc_path\n        )\n        raise SystemExit(1)\n\n    full_cmd = get_swiftpm_env_cmd(args) + cmd + get_swiftpm_flags(args)\n    if cwd is None:\n        cwd = args.project_root\n    call(full_cmd, cwd=cwd)\n\n# -----------------------------------------------------------\n# Build-related helper functions\n# -----------------------------------------------------------\n\n@log_entry_exit\ndef get_dispatch_cmake_arg(args):\n    \"\"\"Returns the CMake argument to the Dispatch configuration to use for building SwiftPM.\"\"\"\n    dispatch_dir = os.path.join(args.dispatch_build_dir, \"cmake/modules\")\n    return \"-Ddispatch_DIR=\" + dispatch_dir\n\n@log_entry_exit\ndef get_foundation_cmake_arg(args):\n    \"\"\"Returns the CMake argument to the Foundation configuration to use for building SwiftPM.\"\"\"\n    foundation_dir = os.path.join(args.foundation_build_dir, \"cmake/modules\")\n    return \"-DFoundation_DIR=\" + foundation_dir\n\n@log_entry_exit\ndef get_llbuild_cmake_arg(args):\n    \"\"\"Returns the CMake argument to the LLBuild framework/binary to use for building SwiftPM.\"\"\"\n    if args.llbuild_link_framework:\n        return \"-DCMAKE_FIND_FRAMEWORK_EXTRA_LOCATIONS=%s\" % args.build_dirs[\"llbuild\"]\n    else:\n        llbuild_dir = os.path.join(args.build_dirs[\"llbuild\"], \"cmake/modules\")\n        return \"-DLLBuild_DIR=\" + llbuild_dir\n\n@log_entry_exit\ndef get_llbuild_source_path(args):\n    \"\"\"Returns the path to the LLBuild source folder.\"\"\"\n    llbuild_path = os.path.join(args.project_root, \"..\", \"llbuild\")\n    if os.path.exists(llbuild_path):\n        return llbuild_path\n    logging.info(\"clone llbuild next to swiftpm directory; see development docs: https://github.com/swiftlang/swift-package-manager/blob/main/Documentation/Contributing.md\")\n    logging.error(\"unable to find llbuild source directory at %s\", llbuild_path)\n    raise BinaryNotFound(tool=\"llbuild\", path=llbuild_path)\n\n@log_entry_exit\ndef get_swiftpm_env_cmd(args):\n    \"\"\"Returns the environment variable command to run SwiftPM binaries.\"\"\"\n    env_cmd = [\"env\"]\n\n    if args.sysroot:\n        env_cmd.append(\"SDKROOT=%s\" % args.sysroot)\n\n    if args.llbuild_link_framework:\n        env_cmd.append(\"SWIFTPM_LLBUILD_FWK=1\")\n    env_cmd.append(\"SWIFTCI_USE_LOCAL_DEPS=1\")\n    env_cmd.append(\"SWIFTPM_MACOS_DEPLOYMENT_TARGET=%s\" % g_macos_deployment_target)\n\n    if not '-macosx' in args.build_target and args.command == 'install':\n        env_cmd.append(\"SWIFTCI_INSTALL_RPATH_OS=%s\" % args.platform_path.group(2))\n\n    if args.bootstrap:\n        libs = [\n            os.path.join(args.bootstrap_dir,                       \"lib\"),\n            os.path.join(args.build_dirs[\"tsc\"],                   \"lib\"),\n            os.path.join(args.build_dirs[\"llbuild\"],               \"lib\"),\n            os.path.join(args.build_dirs[\"swift-argument-parser\"], \"lib\"),\n            os.path.join(args.build_dirs[\"swift-crypto\"],          \"lib\"),\n            os.path.join(args.build_dirs[\"swift-driver\"],          \"lib\"),\n            os.path.join(args.build_dirs[\"swift-system\"],          \"lib\"),\n            os.path.join(args.build_dirs[\"swift-collections\"],     \"lib\"),\n            os.path.join(args.build_dirs[\"swift-tools-protocols\"], \"lib\"),\n            os.path.join(args.build_dirs[\"swift-asn1\"],            \"lib\"),\n            os.path.join(args.build_dirs[\"swift-certificates\"],    \"lib\"),\n            os.path.join(args.build_dirs[\"swift-build\"],           \"lib\"),\n        ]\n\n        if platform.system() == 'Darwin':\n            env_cmd.append(\"DYLD_LIBRARY_PATH=%s\" % \":\".join(libs))\n        else:\n            libs_joined = \":\".join(libs + args.target_info[\"paths\"][\"runtimeLibraryPaths\"])\n            env_cmd.append(\"LD_LIBRARY_PATH=%s\" % libs_joined)\n\n    if '-macosx' in args.build_target:\n        env_cmd.append(\"SWIFTCI_DISABLE_SDK_DEPENDENT_TESTS=YES\")\n\n    env_cmd += [\n        \"SWIFT_EXEC=\" + args.swiftc_path,\n        \"SWIFT_DRIVER_SWIFT_EXEC=\" + args.swiftc_path,\n        \"CC=\" + args.clang_path,\n    ]\n    return env_cmd\n\n@log_entry_exit\ndef get_swiftpm_flags(args):\n    \"\"\"Returns the flags to run SwiftPM binaries.\"\"\"\n    build_flags = [\n        \"--build-path\", args.build_dir,\n    ]\n\n    if args.release:\n        build_flags.extend([\n            \"--configuration\", \"release\",\n        ])\n\n    if not '-macosx' in args.build_target and args.command == 'install':\n        build_flags.append(\"--disable-local-rpath\")\n\n    if args.verbose:\n        build_flags.append(\"--very-verbose\")\n\n    if args.llbuild_link_framework:\n        build_flags.extend([\n            \"-Xswiftc\", \"-F\" + args.build_dirs[\"llbuild\"],\n            \"-Xlinker\", \"-F\" + args.build_dirs[\"llbuild\"],\n\n            # For LLBuild in Xcode.\n            \"-Xlinker\", \"-rpath\",\n            \"-Xlinker\", \"@executable_path/../../../../../SharedFrameworks\",\n\n            # For LLBuild in CLT.\n            \"-Xlinker\", \"-rpath\",\n            \"-Xlinker\", \"@executable_path/../lib/swift/pm/llbuild\",\n        ])\n\n    if '-openbsd' in args.build_target:\n        # Because of swiftlang/swift#80059, swiftpm only works\n        # with BTCFI disabled.\n        if 'aarch64' in args.build_target:\n            build_flags.extend([\"-Xlinker\", \"-z\", \"-Xlinker\", \"nobtcfi\"])\n        build_flags.extend([\"-Xlinker\", \"-z\", \"-Xlinker\", \"origin\"])\n        build_flags.extend([\"-Xcc\", \"-I/usr/local/include\"])\n        build_flags.extend([\"-Xlinker\", \"-L/usr/local/lib\"])\n\n    if '-freebsd' in args.build_target:\n        build_flags.extend([\"-Xlinker\", \"-z\", \"-Xlinker\", \"origin\"])\n        build_flags.extend([\"-Xcc\", \"-I/usr/local/include\"])\n        build_flags.extend([\"-Xlinker\", \"-L/usr/local/lib\"])\n\n    cross_compile_hosts = args.cross_compile_hosts\n    if cross_compile_hosts:\n        if '-apple-macosx' in args.build_target and cross_compile_hosts.startswith('macosx-'):\n            build_flags += [\"--arch\", \"x86_64\", \"--arch\", \"arm64\"]\n        elif cross_compile_hosts.startswith('android-'):\n            build_flags.extend([\"--destination\", args.cross_compile_config])\n        else:\n            logging.error(\"cannot cross-compile for %s\", cross_compile_hosts)\n            raise SystemExit(1)\n\n    # Ensure we are not sharing the module cache with concurrent builds in CI\n    local_module_cache_path=os.path.join(args.build_dir, \"module-cache\")\n    for modifier in [\"-Xswiftc\", \"-Xbuild-tools-swiftc\"]:\n        build_flags.extend([modifier, \"-module-cache-path\", modifier, local_module_cache_path])\n\n    # Disabled, enable this again when it works\n    # Enforce explicit target dependencies\n    # build_flags.extend([\"--explicit-target-dependency-import-check\", \"error\"])\n\n    return build_flags\n\nif __name__ == '__main__':\n    logging.info(\"start\")\n    main()\n    logging.info(\"end\")\n"
  },
  {
    "path": "Utilities/build-using-self",
    "content": "#!/usr/bin/env python3\n# ===----------------------------------------------------------------------===##\n#\n# This source file is part of the Swift open source project\n#\n# Copyright (c) 2025 Apple Inc. and the Swift project authors\n# Licensed under Apache License v2.0 with Runtime Library Exception\n#\n# See http://swift.org/LICENSE.txt for license information\n# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n#\n# ===----------------------------------------------------------------------===##\n\nimport argparse\nimport dataclasses\nimport itertools\nimport logging\nimport os\nimport pathlib\nimport platform\nimport shlex\nimport sys\nfrom datetime import datetime\n\nimport typing as t\n\nfrom helpers import (\n    change_directory,\n    call,\n    call_output,\n)\n\nlogging.basicConfig(\n    format=\" | \".join(\n        [\n            # Prefix script name to the log in an attempt to avoid confusion when parsing logs\n            f\"{pathlib.Path(sys.argv[0]).name}\",\n            \"%(asctime)s\",\n            \"%(levelname)-8s\",\n            \"%(module)s\",\n            \"%(funcName)s\",\n            \"Line:%(lineno)d\",\n            \"%(message)s\",\n        ]\n    ),\n    level=logging.INFO,\n)\n\n\nREPO_ROOT_PATH = pathlib.Path(__file__).parent.parent.resolve()\n\n\nclass UnsupportedArchitecture(Exception):\n\n    pass\n\n\ndef get_arguments() -> argparse.Namespace:\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.ArgumentDefaultsHelpFormatter\n    )\n\n    parser.add_argument(\n        \"-v\",\n        \"--verbose\",\n        dest=\"is_verbose\",\n        action=\"store_true\",\n        help=\"When set, prints verbose information.\",\n    )\n    parser.add_argument(\n        \"-c\",\n        \"--configuration\",\n        type=str,\n        dest=\"config\",\n        help=\"The configuration to use.\",\n    )\n    parser.add_argument(\n        \"-t\",\n        \"--triple\",\n        type=str,\n        dest=\"triple\",\n    )\n    parser.add_argument(\n        \"-b\",\n        \"--build-system\",\n        type=str,\n        dest=\"build_system\",\n    )\n    parser.add_argument(\n        \"--skip-clean\",\n        action=\"store_false\",\n        dest=\"should_clean\",\n        help=\"When set, do not clean the build output\"\n    )\n    parser.add_argument(\n        \"--skip-update\",\n        action=\"store_false\",\n        dest=\"should_update\",\n        help=\"When set, do not run a swift package update\"\n    )\n    parser.add_argument(\n        \"--additional-build-args\",\n        type=str,\n        dest=\"additional_build_args\",\n        default=\"\"\n    )\n    parser.add_argument(\n        \"--additional-run-args\",\n        type=str,\n        dest=\"additional_run_args\",\n        default=\"\"\n    )\n    parser.add_argument(\n        \"--additional-test-args\",\n        type=str,\n        dest=\"additional_test_args\",\n        default=\"\"\n    )\n    parser.add_argument(\n        \"--skip-bootstrap\",\n        dest=\"skip_bootstrap\",\n        action=\"store_true\"\n    )\n    parser.set_defaults(skip_bootstrap=False)\n    args = parser.parse_args()\n    return args\n\n\ndef log_environment() -> None:\n    logging.info(\"Environment Variables\")\n    for key, value in sorted(os.environ.items()):\n        logging.info(\"  --> %s=%r\", key, value)\n\n\nBUILD_OVERRIDES: t.List[str] = [\n    \"--build-system\",\n    \"native\",\n]\n\n\ndef get_swiftpm_bin_dir(\n        *,\n        global_args: t.List[str],\n) -> pathlib.Path:\n    logging.info(\"Retrieving Swift PM binary directory.\")\n    swiftpm_bin_dir = pathlib.Path(\n        call_output([\n            \"swift\",\n            \"build\",\n            *global_args,\n            *BUILD_OVERRIDES,\n            \"--show-bin-path\",\n        ])\n    )\n    logging.info(\"SwiftPM BIN DIR: %s\", swiftpm_bin_dir)\n    return swiftpm_bin_dir\n\n\ndef is_on_darwin() -> bool:\n    return platform.system() == \"Darwin\"\n\n\ndef set_environment() -> None:\n    os.environ[\"SWIFTCI_IS_SELF_HOSTED\"] = \"1\"\n\n    # Ensure SDKROOT is configure\n    if is_on_darwin():\n        sdk_root = call_output(shlex.split(\"xcrun --show-sdk-path --sdk macosx\"))\n        logging.debug(\"macos sdk root = %r\", sdk_root)\n        os.environ[\"SDKROOT\"] = sdk_root\n    log_environment()\n\n\ndef run_bootstrap(swiftpm_bin_dir: pathlib.Path) -> None:\n    logging.info(\"Current working directory is %s\", pathlib.Path.cwd())\n    logging.info(\"Bootstrapping with the XCBuild codepath...\")\n    cross_compile_arch: str\n    arch = platform.machine()\n    if arch == \"arm64\":\n        cross_compile_arch = \"x86_64\"\n    elif arch == \"x86_64\":\n        cross_compile_arch = \"arm64\"\n    else:\n        raise UnsupportedArchitecture(f\"Architecture {arch} is not supported.\")\n\n    call(\n        [\n            REPO_ROOT_PATH / \"Utilities\" / \"bootstrap\",\n            \"build\",\n            \"--release\",\n            \"--verbose\",\n            \"--cross-compile-hosts\",\n            f\"macosx-{cross_compile_arch}\",\n            \"--skip-cmake-bootstrap\",\n            \"--swift-build-path\",\n            (swiftpm_bin_dir / \"swift-build\").resolve(),\n        ],\n    )\n\n\nGlobalArgsValueType = str\n\n\n@dataclasses.dataclass\nclass GlobalArgs:\n    global_argument: str\n    value: t.Optional[GlobalArgsValueType]\n\n\ndef filterIsTruthy(items: t.Iterable) -> t.Iterable:\n    return list(filter(lambda x: x, items))\n\ndef log_directory_contents(directory: pathlib.Path) -> None:\n    logging.info(\"Build path directory      : %s\", directory)\n    logging.info(\"Listing files in directory: %s\", directory)\n    try:\n        for item in sorted(os.listdir(path=directory)):\n            logging.info(\" -> %s\", item)\n    except FileNotFoundError:\n        logging.warning(\"Directory %s does not exist.\", directory)\n\n\ndef main() -> None:\n    args = get_arguments()\n    logging.getLogger().setLevel(logging.DEBUG if args.is_verbose else logging.INFO)\n    logging.debug(\"Args: %r\", args)\n    ignore_args = [\"-Xlinker\", \"/ignore:4217\"] if os.name == \"nt\" else []\n    globalArgsData = [\n        GlobalArgs(global_argument=\"--triple\", value=args.triple),\n        GlobalArgs(global_argument=\"--build-system\", value=args.build_system),\n        GlobalArgs(global_argument=\"--configuration\", value=args.config),\n    ]\n    global_args: t.Iterator[GlobalArgsValueType] = list(\n        itertools.chain.from_iterable(\n            [[arg.global_argument, arg.value] for arg in globalArgsData if arg.value]\n        )\n    )\n    logging.debug(\"Global Args: %r\", global_args)\n    start_time = datetime.now()\n    with change_directory(REPO_ROOT_PATH) as dir:\n        swiftpm_bin_dir = get_swiftpm_bin_dir(global_args=global_args)\n        set_environment()\n\n        call(\n            filterIsTruthy(\n                [\n                    \"swift\",\n                    \"--version\",\n                ]\n            )\n        )\n\n        if args.should_clean:\n            call(\n                filterIsTruthy(\n                    [\n                        \"swift\",\n                        \"package\",\n                        *global_args,\n                        *BUILD_OVERRIDES,\n                        \"clean\",\n                    ]\n                )\n            )\n\n        if args.should_update:\n            call(\n                filterIsTruthy(\n                    [\n                        \"swift\",\n                        \"package\",\n                        *global_args,\n                        *BUILD_OVERRIDES,\n                        \"update\",\n                    ]\n                )\n            )\n\n        call(\n            filterIsTruthy(\n                [\n                    \"swift\",\n                    \"build\",\n                    *global_args,\n                    *BUILD_OVERRIDES,\n                    *ignore_args,\n                    *args.additional_build_args.split(\" \")\n                ]\n            )\n        )\n\n        call(\n            filterIsTruthy(\n                [\n                    \"swift\",\n                    \"run\",\n                    *global_args,\n                    *BUILD_OVERRIDES,\n                    *ignore_args,\n                    *args.additional_run_args.split(\" \"),\n                    \"swift-test\",\n                    *global_args,\n                    \"--force-resolved-versions\",\n                    \"--parallel\",\n                    \"--scratch-path\",\n                    \".test\",\n                    *ignore_args,\n                    *args.additional_test_args.split(\" \")\n                ]\n            )\n        )\n\n    if is_on_darwin() and not args.skip_bootstrap:\n        run_bootstrap(swiftpm_bin_dir=swiftpm_bin_dir)\n\n    end_time = datetime.now()\n    elapsed_time = end_time - start_time\n\n    logging.info(\"Done (%s)\", str(elapsed_time))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "Utilities/config.json",
    "content": "{\"version\":1,\n  \"swiftSyntaxVersionForMacroTemplate\":{\"major\":603,\"minor\":0,\"patch\":0, \"prereleaseIdentifier\":\"latest\"},\n  \"swiftTestingVersionForTestTemplate\":{\"major\":0,\"minor\":8,\"patch\":0}}\n"
  },
  {
    "path": "Utilities/generate_contributors_list.sh",
    "content": "#!/bin/bash\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2022 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nset -eu\nhere=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\ncontributor_list=$( cd \"$here\"/.. && git shortlog -es | cut -f2 )\nfiltered_hashes=$( cat \"$here/../.mailfilter\" | grep -E '^[a-z0-9]+$' | sort )\n\nNL=$'\\n'\n\ncontributors=''\nwhile IFS= read -r line; do\n\thashed=\"$(echo -n \"$line\" | shasum | head -c 40)\"\n\tfound_hash=$(comm -12 <(echo \"$hashed\") <(echo \"$filtered_hashes\"))\n\tif [ ! -z \"$found_hash\" ]; then\n\t\tcontinue\n\tfi\n\tcontributors=\"${contributors}- $line$NL\"\ndone <<< \"$contributor_list\"\n\ncat > \"$here/../CONTRIBUTORS.txt\" <<- EOF\n\tFor the purpose of tracking copyright, this is the list of individuals and\n\torganizations who have contributed to Swift Package Manager.\n\n\tFor employees of an organization/company where the copyright of work done\n\tby employees of that company is held by the company itself, only the company\n\tneeds to be listed here.\n\n\t## COPYRIGHT HOLDERS\n\n\t- Apple Inc. (all contributors with '@apple.com')\n\n\t### Contributors\n\n\t$contributors\n\t**Updating this list**\n\n\tPlease do not edit this file manually. It is generated using \\`./Utilities/generate_contributors_list.sh\\`. If a name is misspelled or appearing multiple times: add an entry in \\`./.mailmap\\`\nEOF\n"
  },
  {
    "path": "Utilities/helpers.py",
    "content": "#!/usr/bin/env python3\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2014-2025 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nimport contextlib\nimport enum\nimport errno\nimport logging\nimport os\nimport pathlib\nimport subprocess\nimport typing as t\n\n\n@contextlib.contextmanager\ndef change_directory(directory: pathlib.Path) -> t.Iterator[pathlib.Path]:\n    current_directory = pathlib.Path.cwd()\n    logging.info(\"Current directory is %s\", current_directory)\n    logging.info(\"Changing directory to: %s\", directory)\n    os.chdir(directory)\n\n    try:\n        yield directory\n    finally:\n        logging.debug(\"Chaning directory back to %s\", current_directory)\n        os.chdir(current_directory)\n\n\nclass Configuration(str, enum.Enum):\n    DEBUG = \"debug\"\n    RELEASE = \"release\"\n\n    def __str__(self) -> str:\n        return self.value\n\n\ndef symlink_force(source, destination):\n    try:\n        os.symlink(source, destination)\n    except OSError as e:\n        if e.errno == errno.EEXIST:\n            os.remove(destination)\n            os.symlink(source, destination)\n\n\ndef mkdir_p(path):\n    \"\"\"Create the given directory, if it does not exist.\"\"\"\n    try:\n        os.makedirs(path)\n    except OSError as e:\n        # Ignore EEXIST, which may occur during a race condition.\n        if e.errno != errno.EEXIST:\n            raise\n\n\ndef call(cmd, cwd=None, verbose=False):\n    \"\"\"Calls a subprocess.\"\"\"\n    cwd = cwd or pathlib.Path.cwd()\n    try:\n        logging.info(\"executing command >>> %r with cwd %s\", cmd, cwd)\n        subprocess.check_call(cmd, cwd=cwd)\n    except subprocess.CalledProcessError as cpe:\n        logging.debug(\"executing command >>> %r with cwd %s\", cmd, cwd)\n        logging.error(\n            \"\\n\".join([\n                \"Process failure with return code %d: %s\",\n                \"[---- START stdout ----]\",\n                \"%s\",\n                \"[---- END stdout ----]\",\n                \"[---- START stderr ----]\",\n                \"%s\",\n                \"[---- END stderr ----]\",\n                \"[---- START OUTPUT ----]\",\n                \"%s\",\n                \"[---- END OUTPUT ----]\",\n            ]),\n            cpe.returncode,\n            str(cpe),\n            cpe.stdout,\n            cpe.stderr,\n            cpe.output,\n        )\n        raise cpe\n\n\ndef call_output(cmd, cwd=None, stderr=False, verbose=False):\n    \"\"\"Calls a subprocess for its return data.\"\"\"\n    stderr = subprocess.STDOUT if stderr else False\n    cwd = cwd or pathlib.Path.cwd()\n    logging.info(\"executing command >>> %r with cwd %s\", cmd, cwd)\n    try:\n        return subprocess.check_output(\n            cmd,\n            cwd=cwd,\n            stderr=stderr,\n            universal_newlines=True,\n        ).strip()\n    except subprocess.CalledProcessError as cpe:\n        logging.debug(\"executing command >>> %r with cwd %s\", cmd, cwd)\n        logging.error(\n            \"\\n\".join([\n                \"Process failure with return code %d: %s\",\n                \"[---- START stdout ----]\",\n                \"%s\",\n                \"[---- END stdout ----]\",\n                \"[---- START stderr ----]\",\n                \"%s\",\n                \"[---- END stderr ----]\",\n                \"[---- START OUTPUT ----]\",\n                \"%s\",\n                \"[---- END OUTPUT ----]\",\n            ]),\n            cpe.returncode,\n            str(cpe),\n            cpe.stdout,\n            cpe.stderr,\n            cpe.output,\n        )\n        raise cpe\n"
  },
  {
    "path": "Utilities/new-bootstrap",
    "content": "#!/bin/bash\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2014-2022 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nset -eu\n\n__dir=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\n\nexec ${__dir}/bootstrap \"$@\"\n"
  },
  {
    "path": "Utilities/soundness.sh",
    "content": "#!/bin/bash\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2022 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nset -eu\nset -o pipefail\n\nhere=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nfunction replace_acceptable_years() {\n    # this needs to replace all acceptable forms with 'YEARS'\n    sed -e 's/20[12][0123456789]-20[12][0123456789]/YEARS/' -e 's/20[12][0123456789]/YEARS/'\n}\n\nprintf \"=> Checking for unacceptable language... \"\n# This greps for unacceptable terminology. The square bracket[s] are so that\n# \"git grep\" doesn't find the lines that greps :).\nunacceptable_terms=(\n    -e blacklis[t]\n    -e whitelis[t]\n    -e slav[e]\n    -e sanit[y]\n)\n\n# We have to exclude the code of conduct as it gives examples of unacceptable language.\nif git grep --color=never -i \"${unacceptable_terms[@]}\" -- . > /dev/null; then\n    printf \"\\033[0;31mUnacceptable language found.\\033[0m\\n\"\n    git grep -i \"${unacceptable_terms[@]}\" -- .\n    exit 1\nfi\nprintf \"\\033[0;32mokay.\\033[0m\\n\"\n\nprintf \"=> Checking format... \\n\"\ngit diff --name-only | grep -v \".swiftpm\" | grep \".swift\" | while read changed_file; do\n  printf \"  * checking ${changed_file}... \"\n  before=$(cat ${changed_file})\n  swiftformat $changed_file > /dev/null 2>&1\n  after=$(cat ${changed_file})\n\n  if [[ \"$before\" != \"$after\" ]]; then\n    printf \"\\033[0;31mformatting issues!\\033[0m\\n\"\n    git --no-pager diff ${changed_file}\n    exit 1\n  else\n    printf \"\\033[0;32mokay.\\033[0m\\n\"\n  fi\ndone\n\nprintf \"=> Checking license headers... \\n\"\ntmp=$(mktemp /tmp/.swift-package-manager-soundness_XXXXXX)\n\nfor language in swift-or-c bash python; do\n  printf \"   * $language... \"\n  declare -a matching_files\n  declare -a exceptions\n  exceptions=( )\n  matching_files=( -name '*' )\n  case \"$language\" in\n      swift-or-c)\n        exceptions=(\n          -name \"Package.swift\"\n          -o -path \"./Sources/PackageSigning/embedded_resources.swift\"\n          -o -path \"./Examples/*\"\n          -o -path \"./Fixtures/*\"\n          -o -path \"./IntegrationTests/*\"\n          -o -path \"./Tests/ExtraTests/*\"\n          -o -path \"./Tests/PackageLoadingTests/Inputs/*\"\n        )\n        matching_files=( -name '*.swift' -o -name '*.c' -o -name '*.h' )\n        cat > \"$tmp\" <<\"EOF\"\n//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift open source project\n//\n// Copyright (c) YEARS Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See http://swift.org/LICENSE.txt for license information\n// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nEOF\n        ;;\n      bash)\n        exceptions=( -path \"./Examples/*\" -o -path \"./Fixtures/*\" -o -path \"./IntegrationTests/*\" -o -path \"*/.build/*\" )\n        matching_files=( -name '*.sh' )\n        cat > \"$tmp\" <<\"EOF\"\n#!/bin/bash\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) YEARS Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\nEOF\n      ;;\n      python)\n        exceptions=( -path \"./Examples/*\" -o -path \"./Fixtures/*\" -o -path \"./IntegrationTests/*\"  -o -path \"*/.build/*\" )\n        matching_files=( -name '*.py' )\n        cat > \"$tmp\" <<\"EOF\"\n#!/usr/bin/env python3\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) YEARS Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\nEOF\n      ;;\n    *)\n      echo >&2 \"ERROR: unknown language '$language'\"\n      ;;\n  esac\n\n  expected_lines=$(cat \"$tmp\" | wc -l)\n  expected_sha=$(cat \"$tmp\" | shasum)\n\n  (\n    cd \"$here/..\"\n    {\n        find . \\\n            \\( \\! -path './.build/*' -a \\\n            \\( \"${matching_files[@]}\" \\) -a \\\n            \\( \\! \\( \"${exceptions[@]}\" \\) \\) \\)\n\n    } | while read line; do\n      if [[ \"$(cat \"$line\" | replace_acceptable_years | head -n $expected_lines | shasum)\" != \"$expected_sha\" ]]; then\n        printf \"\\033[0;31mmissing headers in file '$line'!\\033[0m\\n\"\n        diff -u <(cat \"$line\" | replace_acceptable_years | head -n $expected_lines) \"$tmp\"\n        exit 1\n      fi\n    done\n    printf \"\\033[0;32mokay.\\033[0m\\n\"\n  )\ndone\n\nrm \"$tmp\"\n"
  },
  {
    "path": "Utilities/test-toolchain",
    "content": "#!/usr/bin/env python3\n##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2014-2019 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nimport argparse\nimport os\nimport subprocess\nimport platform\nfrom helpers import note, error, symlink_force, mkdir_p, call, call_output\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"\"\"\n        This script runs the automated tests located in IntegrationTests against a toolchain to validate it behaves\n        correctly.\n        \"\"\")\n\n    parser.add_argument(\n        \"--toolchain-path\",\n        help=\"path to the toolchain to test\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"--swift-path\",\n        help=\"path to the Swift main executable to use for tests\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"--swiftc-path\",\n        help=\"path to the Swift compiler to use for tests\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"--lldb-path\",\n        help=\"path to the LLDB binary to use for tests\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"--swiftpm-bin-dir\",\n        help=\"path to the SwiftPM binary directory to get SwiftPM executables from\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"--filter\",\n        help=\"filter which tests to run\",\n        metavar=\"PATH\")\n    parser.add_argument(\n        \"-v\", \"--verbose\",\n        action=\"store_true\",\n        help=\"whether to print verbose output\")\n\n    args = parser.parse_args()\n    clean_args(args)\n    test(args)\n\ndef clean_args(args):\n    \"\"\"Parses and cleans arguments.\"\"\"\n    args.project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n    # On Darwin, always push SDKROOT in the environment.\n    if platform.system() == \"Darwin\":\n        args.sdk_root = call_output([\"xcrun\", \"--sdk\", \"macosx\", \"--show-sdk-path\"])\n\n    # Get the toolchain path.\n    if args.toolchain_path is None:\n        # If a package wasn't provided, use the current selected toolchain on Darwin.\n        if platform.system() == \"Darwin\":\n            swiftc_path = call_output([\"xcrun\", \"--find\", \"swift\"])\n            args.toolchain_path = os.path.join(swiftc_path, \"../../../\")\n    if args.toolchain_path is None:\n        error(\"'--package-path=PATH' is required\")\n    args.toolchain_path = os.path.abspath(args.toolchain_path)\n\n    # Find the tools we need.\n\n    if args.swift_path:\n        args.swift_path = os.path.abspath(args.swift_path)\n    else:\n        args.swift_path = os.path.join(args.toolchain_path, \"usr\", \"bin\", \"swift\")\n    note(\"testing using 'swift': %s\" % args.swift_path)\n\n    if args.swiftc_path:\n        args.swiftc_path = os.path.abspath(args.swiftc_path)\n    if args.lldb_path:\n        args.lldb_path = os.path.abspath(args.lldb_path)\n\n    # Add substitutions for swiftpm executables.\n\n    if args.swiftpm_bin_dir:\n        args.swiftpm_bin_dir = os.path.abspath(args.swiftpm_bin_dir)\n        note(\"testing using swiftpm binary directory: %s\" % args.swiftpm_bin_dir)\n        args.swift_test_path = os.path.join(args.swiftpm_bin_dir, \"swift-test\")\n    else:\n        args.swift_test_path = args.swift_path + '-test'\n\ndef test(args):\n    cmd = [\"env\"]\n    for key, value in get_env(args).items():\n        if \" \" in value:\n            error(\"Can't set environment variable %s as it contains a space: %s\" % (key, value))\n        else:\n            cmd += ['%s=%s' % (key,value)]\n\n    integration_test_dir = os.path.join(args.project_root, \"IntegrationTests\")\n    cmd += [\n        args.swift_test_path,\n        \"--package-path\", integration_test_dir,\n        \"--parallel\"\n    ]\n\n    if args.filter:\n        cmd += [\"--filter\", args.filter]\n\n    call(cmd, cwd=args.project_root, verbose=True)\n\ndef get_env(args):\n    env = {\n        \"SWIFT_PATH\": args.swift_path,\n    }\n\n    if args.sdk_root:\n        env['SDKROOT'] = args.sdk_root\n    if args.swiftc_path:\n        env['SWIFTC_PATH'] = args.swiftc_path\n    if args.lldb_path:\n        env['LLDB_PATH'] = args.lldb_path\n    if args.swiftpm_bin_dir:\n        env[\"SWIFTPM_CUSTOM_BIN_DIR\"] = args.swiftpm_bin_dir\n\n    return env\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "cmake/modules/CMakeLists.txt",
    "content": "get_property(SwiftPM_EXPORTS GLOBAL PROPERTY SwiftPM_EXPORTS)\nexport(TARGETS ${SwiftPM_EXPORTS} FILE SwiftPMConfig.cmake)\n"
  },
  {
    "path": "cmake/modules/FindLLBuild.cmake",
    "content": "##===----------------------------------------------------------------------===##\n##\n## This source file is part of the Swift open source project\n##\n## Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n## Licensed under Apache License v2.0 with Runtime Library Exception\n##\n## See http://swift.org/LICENSE.txt for license information\n## See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n##\n##===----------------------------------------------------------------------===##\n\nif(TARGET llbuildSwift)\n  return()\nendif()\n\ninclude(CMakeFindFrameworks)\ncmake_find_frameworks(llbuild)\nif(llbuild_FRAMEWORKS)\n  if(NOT TARGET llbuildSwift)\n    add_library(llbuildSwift UNKNOWN IMPORTED)\n    set_target_properties(llbuildSwift PROPERTIES\n      FRAMEWORK TRUE\n      INTERFACE_COMPILE_OPTIONS -F${llbuild_FRAMEWORKS}\n      IMPORTED_LOCATION ${llbuild_FRAMEWORKS}/llbuild.framework/llbuild)\n  endif()\n\n  include(FindPackageHandleStandardArgs)\n  find_package_handle_standard_args(LLBuild\n    REQUIRED_VARS llbuild_FRAMEWORKS)\nelse()\n  find_library(libllbuild_LIBRARIES libllbuild)\n  find_file(libllbuild_INCLUDE_DIRS llbuild/llbuild.h)\n\n  find_library(llbuildSwift_LIBRARIES llbuildSwift)\n  find_file(llbuildSwift_INCLUDE_DIRS llbuildSwift.swiftmodule)\n\n  include(FindPackageHandleStandardArgs)\n  find_package_handle_standard_args(LLBuild REQUIRED_VARS\n    libllbuild_LIBRARIES\n    libllbuild_INCLUDE_DIRS\n    llbuildSwift_LIBRARIES\n    llbuildSwift_INCLUDE_DIRS)\n\n  if(NOT TARGET libllbuild)\n    add_library(libllbuild UNKNOWN IMPORTED)\n    get_filename_component(libllbuild_INCLUDE_DIRS\n      ${libllbuild_INCLUDE_DIRS} DIRECTORY)\n    set_target_properties(libllbuild PROPERTIES\n      INTERFACE_INCLUDE_DIRECTORIES ${libllbuild_INCLUDE_DIRS}\n      IMPORTED_LOCATION ${libllbuild_LIBRARIES})\n  endif()\n  if(NOT TARGET llbuildSwift)\n    add_library(llbuildSwift UNKNOWN IMPORTED)\n    get_filename_component(llbuildSwift_INCLUDE_DIRS\n      ${llbuildSwift_INCLUDE_DIRS} DIRECTORY)\n    set_target_properties(llbuildSwift PROPERTIES\n      INTERFACE_LINK_LIBRARIES libllbuild\n      INTERFACE_INCLUDE_DIRECTORIES ${llbuildSwift_INCLUDE_DIRS}\n      IMPORTED_LOCATION ${llbuildSwift_LIBRARIES})\n  endif()\nendif()\n"
  },
  {
    "path": "swiftbuild_specific_issues.md",
    "content": "# SwiftBuild-Specific `withKnownIssue` Tests (Excluding Native Build System)\n\n## Analysis Methodology\nThis report identifies Swift Testing tests containing `withKnownIssue` blocks that specifically affect the SwiftBuild backend but **NOT** the native build system, organized by platform.\n\n## Windows Platform - SwiftBuild Specific Issues\n\n### 1. BuildCommandTests.swift\n- **`importOfMissedDepWarning`**\n  - **When clause**: `[.swiftbuild, .xcode].contains(buildSystem)`\n  - **Issue**: Warning message regarding missing imports expected to be more verbose at SwiftPM level\n  - **Excludes**: Native build system\n\n- **`importOfMissedDepWarningVerifyingErrorFlow`**\n  - **When clause**: `[.swiftbuild, .xcode].contains(buildSystem)`\n  - **Issue**: Error flow verification for missing import warnings\n  - **Excludes**: Native build system\n\n- **`buildExistingExecutableProductIsSuccessfull`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && data.buildSystem == .swiftbuild`\n  - **Issue**: Failures possibly due to long file paths\n  - **Windows + SwiftBuild only**\n\n- **`buildExistingLibraryProductIsSuccessfull`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild`\n  - **Issue**: Found multiple targets named 'lib1' error message handling\n  - **Windows + SwiftBuild only**\n\n- **`buildExistingTargetIsSuccessfull`**\n  - **When clause**: `[.swiftbuild, .xcode].contains(buildSystem)`\n  - **Issue**: Could not find target named 'exec2'\n  - **Excludes**: Native build system\n\n- **`parseableInterfaces`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild`\n  - **Issue**: Errors with SwiftBuild on Windows possibly due to long path\n  - **Windows + SwiftBuild only**\n\n- **`buildSystemDefaultSettings`**\n  - **When clause**: `buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows`\n  - **Issue**: Sometimes failed to build due to possible path issue\n  - **Windows + SwiftBuild only**\n\n- **`automaticParseableInterfacesWithLibraryEvolution`**\n  - **When clause**: `buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows`\n  - **Issue**: Missing 'A.swiftmodule/*.swiftinterface' files\n  - **Windows + SwiftBuild only**\n\n- **`buildCompleteMessage`**\n  - **When clause**: `buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows`\n  - **Issue**: Build complete message verification\n  - **Windows + SwiftBuild only**\n\n- **`swiftDriverRawOutputGetsNewlines`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild`\n  - **Issue**: Error produced for this fixture\n  - **Windows + SwiftBuild only**\n\n- **`swiftBuildQuietLogLevel`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild`\n  - **Issue**: Quiet log level behavior\n  - **Windows + SwiftBuild only**\n\n- **`parseAsLibraryCriteria`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild`\n  - **Issue**: Parse as library functionality\n  - **Windows + SwiftBuild only**\n\n- **`doesNotRebuildWithFlags`**\n  - **When clause**: `buildSystem == .swiftbuild`\n  - **Issue**: --very-verbose causes rebuild on SwiftBuild\n  - **SwiftBuild only (all platforms)**\n\n### 2. TestCommandTests.swift\n- **`basicXCTestSupport`**\n  - **When clause**: Indirectly SwiftBuild specific through Windows testing\n  - **Issue**: Driver threw unable to load output file map\n  - **Windows specific**\n\n### 3. PluginTests.swift\n- **`testUseOfBuildToolPluginTargetNoPreBuildCommands`**\n  - **When clause**: `buildSystem == .swiftbuild`\n  - **Issue**: File handling for unhandled files warning\n  - **SwiftBuild only**\n\n- **`testIncorrectDependencies`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild`\n  - **Issue**: Build tests functionality\n  - **Windows + SwiftBuild only**\n\n- **`testTransitivePluginOnlyDependency`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild`\n  - **Issue**: Plugin dependency resolution\n  - **Windows + SwiftBuild only**\n\n- **`testDependentPlugins`**\n  - **When clause**: `buildSystem == .swiftbuild && ProcessInfo.hostOperatingSystem == .windows`\n  - **Issue**: Plugin dependency functionality\n  - **Windows + SwiftBuild only**\n\n### 4. PluginTests.swift - Snippet Tests\n- **`testBasicBuildIndividualSnippets`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .windows && buildSystem == .swiftbuild`\n  - **Issue**: Individual snippet building\n  - **Windows + SwiftBuild only**\n\n- **`testBasicRunSnippets`**\n  - **When clause**: `[.windows].contains(ProcessInfo.hostOperatingSystem) && buildSystem == .swiftbuild`\n  - **Issue**: Snippet execution\n  - **Windows + SwiftBuild only**\n\n## All Platforms - SwiftBuild Specific Issues\n\n### 1. BuildCommandTests.swift\n- **`buildToolWithoutOutputs`** (partial)\n  - **When clause**: `buildSystem == .swiftbuild`\n  - **Issue**: Warning about build tool commands without output files\n  - **SwiftBuild only, all platforms**\n\n### 2. PluginTests.swift\n- **Multiple plugin tests** have nested `withKnownIssue` blocks specifically for SwiftBuild:\n  - Various plugin functionality gaps in SwiftBuild vs Native\n\n### 3. TraitTests.swift\n- **`testConditionTraits`** (multiple variants)\n  - **When clause**: Various combinations excluding native (e.g., `[.swiftbuild, .xcode].contains(buildSystem)`)\n  - **Issue**: Condition trait handling\n  - **Excludes**: Native build system\n\n## Linux Platform - SwiftBuild Specific Issues\n\n### 1. PluginTests.swift\n- **`testIncorrectDependencies`**\n  - **When clause**: `ProcessInfo.hostOperatingSystem == .linux && buildSystem == .swiftbuild && CiEnvironment.runningInSmokeTestPipeline`\n  - **Issue**: Plugin dependency issues in CI\n  - **Linux + SwiftBuild only**\n\n## macOS Platform - SwiftBuild Specific Issues\n\n### 1. BuildCommandTests.swift\n- **`getTaskAllowEntitlement`**\n  - **When clause**: `[.swiftbuild, .xcode].contains(buildSystem) && ProcessInfo.hostOperatingSystem != .linux`\n  - **Issue**: Entitlement handling differences\n  - **Excludes**: Native build system and Linux\n\n## Cross-Platform Issues (SwiftBuild vs Native Feature Gaps)\n\n### 1. Build System Behavioral Differences\n- **Output handling**: SwiftBuild often produces different output formats\n- **Error reporting**: Different error message formats between build systems\n- **Plugin integration**: SwiftBuild has known gaps in plugin functionality\n- **Path handling**: SwiftBuild more sensitive to long paths on Windows\n\n### 2. Missing SwiftBuild Features\n- **Symbol graph extraction**: Limited functionality compared to native\n- **Test discovery**: Different behavior patterns\n- **Resource bundling**: Some gaps in resource handling\n\n## Summary by Platform\n\n### Windows (Majority of Issues)\n- **17+ SwiftBuild-specific tests** failing on Windows\n- **Primary issues**: Path length limitations, file system operations, plugin integration\n- **Pattern**: Most Windows issues are SwiftBuild-only, suggesting platform-specific integration problems\n\n### All Platforms\n- **5+ SwiftBuild-specific tests** affecting all platforms\n- **Primary issues**: Feature parity gaps, output format differences, plugin functionality\n\n### Linux\n- **2+ SwiftBuild-specific tests** in CI environments\n- **Primary issues**: CI-specific plugin and dependency resolution\n\n### macOS\n- **2+ SwiftBuild-specific tests**\n- **Primary issues**: Entitlement handling, sandboxing differences\n\n## Key Insights\n\n1. **Windows Disproportionately Affected**: ~75% of SwiftBuild-specific issues are Windows-only\n2. **Plugin System Gaps**: SwiftBuild consistently has plugin-related issues not present in native\n3. **Path Handling**: SwiftBuild is more sensitive to Windows path length limitations\n4. **Feature Parity**: SwiftBuild lacks several features available in the native build system\n5. **Output Format Differences**: SwiftBuild often produces different output that requires separate test expectations\n\nThis analysis shows SwiftBuild has significant platform-specific issues, especially on Windows, and feature gaps compared to the native build system.\n"
  },
  {
    "path": "withKnownIssue_tests_report.md",
    "content": "# Swift Package Manager Tests with `withKnownIssue` Report\n\n## Summary\nFound 203 test methods across 37 test files containing `withKnownIssue` blocks. Below is a detailed breakdown by test suite, platform constraints, and build system impacts.\n\n## Major Test Suites with `withKnownIssue` Tests\n\n### 1. [`BuildCommandTestCases`](Tests/CommandsTests/BuildCommandTests.swift)\n**Platform Constraints**: Primarily Windows-specific issues\n**Build Systems**: All platforms support (Native, SwiftBuild, Xcode)\n\n**Key Tests:**\n- `importOfMissedDepWarning` - **Build Systems**: SwiftBuild, Xcode - **Platform**: All\n- `importOfMissedDepWarningVerifyingErrorFlow` - **Build Systems**: SwiftBuild, Xcode - **Platform**: All\n- `symlink` - **Build Systems**: All - **Platform**: Windows only\n- `buildExistingExecutableProductIsSuccessfull` - **Build Systems**: SwiftBuild only - **Platform**: Windows only\n- `buildExistingLibraryProductIsSuccessfull` - **Build Systems**: SwiftBuild only - **Platform**: Windows only\n- `parseableInterfaces` - **Build Systems**: SwiftBuild only - **Platform**: Windows only\n- `buildSystemDefaultSettings` - **Build Systems**: SwiftBuild only - **Platform**: Windows only\n- `swiftGetVersion` - **Build Systems**: Xcode, SwiftBuild, Native (release) - **Platform**: Windows or others\n- `getTaskAllowEntitlement` - **Build Systems**: SwiftBuild, Xcode - **Platform**: Non-Linux only\n\n### 2. [`PluginTests`](Tests/FunctionalTests/PluginTests.swift)\n**Platform Constraints**: Heavily Windows-focused issues\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `testUseOfBuildToolPluginTargetByExecutableInSamePackage` - **Build Systems**: All - **Platform**: Windows only\n- `testUseOfBuildToolPluginTargetNoPreBuildCommands` - **Build Systems**: Native (Windows CI), SwiftBuild (all) - **Platform**: Mixed\n- `testLocalAndRemoteToolDependencies` - **Build Systems**: All - **Platform**: Windows only\n- `testIncorrectDependencies` - **Build Systems**: SwiftBuild - **Platform**: Windows and Linux (CI)\n- `testTransitivePluginOnlyDependency` - **Build Systems**: SwiftBuild only - **Platform**: Windows only\n\n### 3. [`TestCommandTests`](Tests/CommandsTests/TestCommandTests.swift)\n**Platform Constraints**: Mixed Windows and general platform issues\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `basicXCTestSupport` - **Build Systems**: All - **Platform**: Windows only\n- `listTests` - **Build Systems**: All - **Platform**: Windows only\n- `testableExecutableTests` - **Build Systems**: All - **Platform**: General intermittent\n- `parallelTests` - **Build Systems**: All - **Platform**: General intermittent\n- `testDiscovery` - **Build Systems**: All - **Platform**: General intermittent\n\n### 4. [`PackageCommandTests`](Tests/CommandsTests/PackageCommandTests.swift)\n**Platform Constraints**: General intermittent issues and some Windows-specific\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `archiveSource` - **Build Systems**: All - **Platform**: General intermittent\n- `dumpSymbolGraph` - **Build Systems**: All - **Platform**: General intermittent\n- Multiple plugin-related tests - **Build Systems**: All - **Platform**: General intermittent\n\n### 5. [`CFamilyTargetTests`](Tests/FunctionalTests/CFamilyTargetTests.swift)\n**Platform Constraints**: General intermittent issues\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `testCLibraryTargets` - **Build Systems**: All - **Platform**: General intermittent\n- `testModuleMapGenerationCases` - **Build Systems**: All - **Platform**: General intermittent\n\n### 6. [`DependencyResolutionTests`](Tests/FunctionalTests/DependencyResolutionTests.swift)\n**Platform Constraints**: Windows and general intermittent\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `testInternalSimpleTargets` - **Build Systems**: All - **Platform**: General intermittent\n- `testExternalSimpleTargets` - **Build Systems**: All - **Platform**: General intermittent\n- `testExternalBranchTargets` - **Build Systems**: All - **Platform**: Windows specific for some\n\n### 7. [`ResourcesTests`](Tests/FunctionalTests/ResourcesTests.swift)\n**Platform Constraints**: General intermittent issues\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `testBasicResourceAccessibility` - **Build Systems**: All - **Platform**: General intermittent\n- `testResourcesInClangTargets` - **Build Systems**: All - **Platform**: General intermittent\n\n### 8. [`ModuleAliasingFixtureTests`](Tests/FunctionalTests/ModuleAliasingFixtureTests.swift)\n**Platform Constraints**: General intermittent issues\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `testDirectDeps1` - **Build Systems**: All - **Platform**: General intermittent\n- `testNestedDeps1` - **Build Systems**: All - **Platform**: General intermittent\n\n### 9. [`TraitTests`](Tests/FunctionalTests/TraitTests.swift)\n**Platform Constraints**: Mixed Windows and SwiftBuild issues\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `testBasicTraits` - **Build Systems**: All - **Platform**: General intermittent\n- `testConditionTraits` - **Build Systems**: SwiftBuild, Xcode - **Platform**: Windows and others\n\n### 10. [`TestDiscoveryTests`](Tests/FunctionalTests/TestDiscoveryTests.swift)\n**Platform Constraints**: Windows path issues\n**Build Systems**: All platforms support\n\n**Key Tests:**\n- `build` - **Build Systems**: All - **Platform**: Windows only\n- `discovery` - **Build Systems**: All - **Platform**: Windows only\n- `asyncMethods` - **Build Systems**: All - **Platform**: Windows only\n\n## Additional Test Suites\n\n### [`CoverageTests`](Tests/CommandsTests/CoverageTests.swift)\n- `codeCoverageBasic` - **Build Systems**: All - **Platform**: General intermittent\n- `codeCoverageFileReport` - **Build Systems**: All - **Platform**: General intermittent\n\n### [`RunCommandTests`](Tests/CommandsTests/RunCommandTests.swift)\n- `swiftRunWithVerbosity` - **Build Systems**: All - **Platform**: General intermittent\n- `swiftRunExecutable` - **Build Systems**: All - **Platform**: General intermittent\n\n### [`APIDiffTests`](Tests/CommandsTests/APIDiffTests.swift)\n- `testAPIDiffOfModuleWithCDependency` - **Build Systems**: All - **Platform**: General intermittent\n- `testAPIDiffOfVendoredCDependency` - **Build Systems**: All - **Platform**: General intermittent\n\n### [`SwiftSDKCommandTests`](Tests/CommandsTests/SwiftSDKCommandTests.swift)\n- `installationAndUsage` - **Build Systems**: All - **Platform**: General intermittent\n\n### [`PathTests`](Tests/BasicsTests/FileSystem/PathTests.swift)\n**Platform Constraints**: Windows path handling issues\n**Build Systems**: N/A (Basic functionality tests)\n\n**Key Tests:**\n- Multiple path manipulation tests - **Platform**: Windows only\n- Path component and validation tests - **Platform**: Windows only\n\n## Platform Distribution Summary\n\n**Windows-Specific Issues**: ~60% of `withKnownIssue` tests\n- File path length limitations\n- Platform-specific build failures\n- SwiftBuild integration issues on Windows\n- Path handling and directory operations\n\n**General Intermittent Issues**: ~35% of tests\n- Network-dependent operations\n- Timing-sensitive operations\n- CI environment variations\n- Build caching issues\n\n**Other Platform-Specific**: ~5% of tests\n- macOS-only sandboxing tests\n- Linux-specific issues\n- Amazon Linux specific issues\n\n## Build System Impact Analysis\n\n**SwiftBuild**: Most impacted build system\n- Windows platform issues\n- Feature gaps compared to native build system\n- Integration issues with various Swift Package Manager features\n- Plugin system compatibility issues\n\n**Native**: Generally more stable\n- Occasional issues with newer features\n- Some Windows-specific problems\n- Better plugin support\n\n**Xcode**: Moderate impact\n- Some feature gaps\n- Integration testing needed for certain scenarios\n- Limited plugin functionality\n\n## Key Patterns Observed\n\n1. **Platform-Conditional Issues**: Most `withKnownIssue` blocks use `when:` clauses to specify platform or build system constraints\n2. **Intermittent Failures**: Many tests marked with `isIntermittent: true` for CI stability\n3. **Feature Gaps**: SwiftBuild often has missing features compared to native build system\n4. **Path Issues**: Windows long path handling is a recurring theme\n5. **Integration Issues**: Plugin system, test discovery, and build tool integration show most issues\n6. **Build System Parity**: Tests often have different expectations per build system\n7. **CI Environment Issues**: Many failures are environment-specific\n\n## Recommendations\n\n1. **Windows Support**: Focus on improving Windows compatibility, especially for:\n   - Path length handling\n   - SwiftBuild integration\n   - File system operations\n\n2. **SwiftBuild Parity**: Address feature gaps between SwiftBuild and native build system\n\n3. **CI Stability**: Investigate and resolve intermittent failures to improve test reliability\n\n4. **Plugin System**: Strengthen plugin system integration across all build systems\n\n5. **Test Infrastructure**: Consider improving test isolation to reduce platform-specific issues\n\n---\n\n*Report generated from analysis of 203 `withKnownIssue` test methods across 37 test files in the Swift Package Manager test suite.*\n"
  },
  {
    "path": "xcode/SwiftPM-Package.xctestplan",
    "content": "{\n  \"configurations\" : [\n    {\n      \"id\" : \"2178F4FD-6533-44DD-8F74-D1D6E64575E8\",\n      \"name\" : \"Test Scheme Action\",\n      \"options\" : {\n\n      }\n    }\n  ],\n  \"defaultOptions\" : {\n    \"targetForVariableExpansion\" : {\n      \"containerPath\" : \"container:\",\n      \"identifier\" : \"package-info\",\n      \"name\" : \"package-info\"\n    }\n  },\n  \"testTargets\" : [\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"BasicsTests\",\n        \"name\" : \"BasicsTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"BuildTests\",\n        \"name\" : \"BuildTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"CommandsTests\",\n        \"name\" : \"CommandsTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"FunctionalPerformanceTests\",\n        \"name\" : \"FunctionalPerformanceTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"FunctionalTests\",\n        \"name\" : \"FunctionalTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageCollectionsModelTests\",\n        \"name\" : \"PackageCollectionsModelTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageCollectionsSigningTests\",\n        \"name\" : \"PackageCollectionsSigningTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageCollectionsTests\",\n        \"name\" : \"PackageCollectionsTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageDescriptionTests\",\n        \"name\" : \"PackageDescriptionTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageFingerprintTests\",\n        \"name\" : \"PackageFingerprintTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageGraphPerformanceTests\",\n        \"name\" : \"PackageGraphPerformanceTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageGraphTests\",\n        \"name\" : \"PackageGraphTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageLoadingTests\",\n        \"name\" : \"PackageLoadingTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageModelTests\",\n        \"name\" : \"PackageModelTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackagePluginAPITests\",\n        \"name\" : \"PackagePluginAPITests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageRegistryTests\",\n        \"name\" : \"PackageRegistryTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"PackageSigningTests\",\n        \"name\" : \"PackageSigningTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"SPMBuildCoreTests\",\n        \"name\" : \"SPMBuildCoreTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"SourceControlTests\",\n        \"name\" : \"SourceControlTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"WorkspaceTests\",\n        \"name\" : \"WorkspaceTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"XCBuildSupportTests\",\n        \"name\" : \"XCBuildSupportTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"LLBuildManifestTests\",\n        \"name\" : \"LLBuildManifestTests\"\n      }\n    },\n    {\n      \"parallelizable\" : true,\n      \"target\" : {\n        \"containerPath\" : \"container:\",\n        \"identifier\" : \"SourceKitLSPAPITests\",\n        \"name\" : \"SourceKitLSPAPITests\"\n      }\n    }\n  ],\n  \"version\" : 1\n}\n"
  }
]